{"id":"d3ac4e64-99ba-42ae-873f-52c572bdd703","entityType":"agent","slug":"clawhub-skills-1kalin-afrexai-mcp-engineering","name":"afrexai-mcp-engineering","canonicalUrl":"https://www.xpersona.co/agent/clawhub-skills-1kalin-afrexai-mcp-engineering","canonicalPath":"/agent/clawhub-skills-1kalin-afrexai-mcp-engineering","generatedAt":"2026-10-09T21:21:31.828Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"description":"MCP Engineering — Complete Model Context Protocol System MCP Engineering — Complete Model Context Protocol System Build, integrate, secure, and scale MCP servers and clients. From first server to production multi-tool architecture. When to Use - Building an MCP server (any language) - Integrating MCP tools into an AI agent - Debugging MCP connection/auth issues - Designing multi-server architectures - Securing MCP endpoints for production - Evaluating which MCP servers to","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. Last updated 4/15/2026.","installCommand":"clawhub skill install skills:1kalin:afrexai-mcp-engineering","sourceUrl":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-mcp-engineering","homepage":null,"primaryLinks":[{"label":"View on ClawHub","url":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-mcp-engineering","kind":"source"}],"safetyScore":84,"overallRank":62,"popularityScore":50,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"MCP Engineering — Complete Model Context Protocol System MCP Engineering — Complete Model Context Protocol System Build, integrate, secure, and scale MCP server"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"protocols":[{"protocol":"MCP","label":"MCP","status":"self-declared","notes":"Declared in the public agent profile."},{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[{"label":"access","status":"self-declared"},{"label":"ask","status":"self-declared"}],"verifiedCount":0,"selfDeclaredCount":4,"capabilityMatrix":{"rows":[{"key":"MCP","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"},{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"},{"key":"access","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"ask","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"}],"flattenedTokens":"protocol:MCP|unknown|profile protocol:OPENCLEW|unknown|profile capability:access|supported|profile capability:ask|supported|profile"}},"adoption":{"evidence":{"source":"no-adoption-signals","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No source adoption metrics were available."},"stars":null,"forks":null,"downloads":null,"packageName":null,"latestVersion":null,"tractionLabel":null},"release":{"evidence":{"source":"agent-index","verified":false,"confidence":"medium","updatedAt":"2026-02-25T06:17:42.915Z","emptyReason":null},"lastUpdatedAt":"2026-04-15T00:45:39.800Z","lastCrawledAt":"2026-02-25T06:17:42.915Z","lastIndexedAt":null,"nextCrawlAt":"2026-02-26T06:17:42.915Z","lastVerifiedAt":null,"highlights":[]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install skills:1kalin:afrexai-mcp-engineering","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["MCP","OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-09T21:21:31.827Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-mcp-engineering/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"readme":"# MCP Engineering — Complete Model Context Protocol System\n\nBuild, integrate, secure, and scale MCP servers and clients. From first server to production multi-tool architecture.\n\n## When to Use\n\n- Building an MCP server (any language)\n- Integrating MCP tools into an AI agent\n- Debugging MCP connection/auth issues\n- Designing multi-server architectures\n- Securing MCP endpoints for production\n- Evaluating which MCP servers to use\n\n---\n\n## Phase 1: MCP Fundamentals\n\n### What MCP Is\nModel Context Protocol = standardized way for AI agents to call external tools. Think of it as \"USB for AI\" — one protocol, any tool.\n\n### Architecture\n```\nAgent (Client) ←→ MCP Transport ←→ MCP Server ←→ External Service\n                   (stdio/HTTP)      (your code)    (API, DB, file system)\n```\n\n### Core Concepts\n| Concept | What It Does | Example |\n|---------|-------------|---------|\n| **Server** | Exposes tools, resources, prompts | A server wrapping the GitHub API |\n| **Client** | Discovers and calls server capabilities | OpenClaw, Claude Desktop, Cursor |\n| **Tool** | A callable function with typed params | `create_issue(title, body, labels)` |\n| **Resource** | Read-only data the agent can access | `file://workspace/config.json` |\n| **Prompt** | Reusable prompt templates | `summarize_pr(pr_url)` |\n| **Transport** | How client↔server communicate | stdio (local) or HTTP+SSE (remote) |\n\n### Transport Decision\n| Factor | stdio | HTTP/SSE | Streamable HTTP |\n|--------|-------|----------|-----------------|\n| Setup complexity | Low | Medium | Medium |\n| Multi-client | No | Yes | Yes |\n| Remote access | No | Yes | Yes |\n| Streaming | Via stdio | SSE | Native |\n| Auth needed | No (local) | Yes | Yes |\n| Best for | Local dev, single agent | Production, shared | Modern production |\n\n**Rule:** Start with stdio for development. Move to HTTP for production or multi-agent.\n\n---\n\n## Phase 2: Building Your First MCP Server\n\n### Server Brief YAML\n```yaml\nserver_name: \"[service]-mcp\"\ndescription: \"[What this server does in one sentence]\"\ntransport: stdio | http\ntools:\n  - name: \"[verb_noun]\"\n    description: \"[What it does — be specific for LLM tool selection]\"\n    params:\n      - name: \"[param]\"\n        type: \"string | number | boolean | object | array\"\n        required: true | false\n        description: \"[What this param controls]\"\n    returns: \"[What the tool returns]\"\n    error_cases:\n      - \"[When/how it fails]\"\nresources:\n  - uri: \"[protocol://path]\"\n    description: \"[What data this exposes]\"\nexternal_dependencies:\n  - \"[API/service this wraps]\"\nauth_required: true | false\nauth_method: \"api_key | oauth2 | none\"\n```\n\n### TypeScript Server Template (stdio)\n```typescript\n// server.ts — minimal MCP server\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\n\nconst server = new McpServer({\n  name: \"my-service\",\n  version: \"1.0.0\",\n});\n\n// Define a tool\nserver.tool(\n  \"get_item\",                          // tool name (verb_noun)\n  \"Fetch an item by ID\",               // description (LLM reads this)\n  { id: z.string().describe(\"Item ID\") }, // params with descriptions\n  async ({ id }) => {\n    try {\n      const result = await fetchItem(id);\n      return {\n        content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n      };\n    } catch (error) {\n      return {\n        content: [{ type: \"text\", text: `Error: ${error.message}` }],\n        isError: true,\n      };\n    }\n  }\n);\n\n// Define a resource\nserver.resource(\n  \"config\",\n  \"config://app\",\n  async (uri) => ({\n    contents: [{ uri: uri.href, mimeType: \"application/json\", text: JSON.stringify(config) }],\n  })\n);\n\n// Start\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n```\n\n### Python Server Template (stdio)\n```python\n# server.py — minimal MCP server\nfrom mcp.server import Server\nfrom mcp.server.stdio import stdio_server\nfrom mcp.types import Tool, TextContent\nimport json\n\nserver = Server(\"my-service\")\n\n@server.list_tools()\nasync def list_tools():\n    return [\n        Tool(\n            name=\"get_item\",\n            description=\"Fetch an item by ID\",\n            inputSchema={\n                \"type\": \"object\",\n                \"properties\": {\n                    \"id\": {\"type\": \"string\", \"description\": \"Item ID\"}\n                },\n                \"required\": [\"id\"]\n            }\n        )\n    ]\n\n@server.call_tool()\nasync def call_tool(name: str, arguments: dict):\n    if name == \"get_item\":\n        result = await fetch_item(arguments[\"id\"])\n        return [TextContent(type=\"text\", text=json.dumps(result, indent=2))]\n    raise ValueError(f\"Unknown tool: {name}\")\n\nasync def main():\n    async with stdio_server() as (read, write):\n        await server.run(read, write, server.create_initialization_options())\n\nif __name__ == \"__main__\":\n    import asyncio\n    asyncio.run(main())\n```\n\n### Tool Design Rules\n1. **Verb-noun naming**: `create_issue`, `search_docs`, `update_config` — never `issue` or `doStuff`\n2. **Descriptions are critical**: The LLM picks tools based on descriptions. Be specific. Include when NOT to use.\n3. **Granular over god-tools**: `search_issues` + `get_issue` + `create_issue` beats `manage_issues`\n4. **Return structured data**: JSON over prose. Let the LLM format for the user.\n5. **Error messages for LLMs**: Include what went wrong AND what to try next\n6. **Idempotent where possible**: `create_or_update` > `create` (prevents duplicates from retries)\n7. **Limit output size**: Paginate or truncate. A 10MB response kills the context window.\n8. **Include examples in descriptions**: \"Search issues. Example: search_issues(query='bug label:critical')\"\n\n### Tool Description Quality Checklist\n- [ ] Says what the tool DOES (not just the name restated)\n- [ ] Mentions when to use vs. when NOT to use\n- [ ] Each param has a description with format hints\n- [ ] Return format is documented\n- [ ] Edge cases mentioned (empty results, not found, etc.)\n\n---\n\n## Phase 3: HTTP Transport & Production Server\n\n### HTTP Server Template (TypeScript)\n```typescript\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport express from \"express\";\n\nconst app = express();\napp.use(express.json());\n\nconst server = new McpServer({ name: \"my-service\", version: \"1.0.0\" });\n// ... register tools ...\n\napp.post(\"/mcp\", async (req, res) => {\n  const transport = new StreamableHTTPServerTransport(\"/mcp\", res);\n  await server.connect(transport);\n  await transport.handleRequest(req, res);\n});\n\napp.listen(3001, () => console.log(\"MCP server on :3001\"));\n```\n\n### Auth Patterns\n\n#### API Key (simplest)\n```typescript\n// Middleware\nfunction authMiddleware(req, res, next) {\n  const key = req.headers[\"x-api-key\"] || req.headers.authorization?.replace(\"Bearer \", \"\");\n  if (!key || !validKeys.has(key)) {\n    return res.status(401).json({ error: \"Invalid API key\" });\n  }\n  req.userId = keyToUser.get(key);\n  next();\n}\n```\n\n#### OAuth 2.0 (for user-scoped access)\n```yaml\n# MCP OAuth flow\n1. Client requests tool → server returns 401 with auth URL\n2. User completes OAuth in browser → gets access token\n3. Client stores token, includes in subsequent requests\n4. Server validates token, calls external API on user's behalf\n```\n\n### Production Checklist\n- [ ] Rate limiting per client/key\n- [ ] Request validation (schema check before execution)\n- [ ] Structured logging (request ID, tool name, latency, status)\n- [ ] Health check endpoint (`/health`)\n- [ ] Graceful shutdown (finish in-flight requests)\n- [ ] Timeout on external calls (don't let tools hang forever)\n- [ ] Output size limits (truncate large responses)\n- [ ] Error categorization (4xx client vs 5xx server)\n- [ ] CORS if browser clients connect\n- [ ] TLS in production (always HTTPS)\n\n---\n\n## Phase 4: Client Integration\n\n### OpenClaw Configuration\n```yaml\n# In openclaw config — stdio server\nmcpServers:\n  my-service:\n    command: \"node\"\n    args: [\"path/to/server.js\"]\n    env:\n      API_KEY: \"{{env.MY_SERVICE_API_KEY}}\"\n```\n\n```yaml\n# HTTP server\nmcpServers:\n  my-service:\n    url: \"https://mcp.myservice.com/mcp\"\n    headers:\n      Authorization: \"Bearer {{env.MY_SERVICE_TOKEN}}\"\n```\n\n### Claude Desktop Configuration\n```json\n{\n  \"mcpServers\": {\n    \"my-service\": {\n      \"command\": \"node\",\n      \"args\": [\"/path/to/server.js\"],\n      \"env\": { \"API_KEY\": \"your-key\" }\n    }\n  }\n}\n```\n\n### Client-Side Tool Selection\nWhen multiple MCP servers are connected, the agent sees ALL tools. Help the agent pick correctly:\n\n1. **Unique tool names**: Prefix if needed (`github_search` vs `jira_search`)\n2. **Clear descriptions**: Disambiguate similar tools across servers\n3. **Don't overload**: 20-30 tools max across all servers. Beyond that, agents get confused.\n\n### Multi-Server Architecture\n```\nAgent\n├── github-mcp (code: create_pr, search_code, list_issues)\n├── slack-mcp (comms: send_message, search_messages)\n├── postgres-mcp (data: query, list_tables)\n└── internal-mcp (business: get_customer, update_pipeline)\n```\n\n**Principle:** One server per domain. Don't build a mega-server.\n\n---\n\n## Phase 5: Testing MCP Servers\n\n### Test Pyramid\n```\n        /  E2E  \\        Agent actually uses the tool\n       / Integration \\    Tool calls real API (sandbox)\n      /    Unit       \\   Business logic without MCP layer\n```\n\n### Unit Test Pattern\n```typescript\n// Test the tool handler directly, no MCP transport\ndescribe(\"get_item\", () => {\n  it(\"returns item when found\", async () => {\n    mockDb.findById.mockResolvedValue({ id: \"123\", name: \"Test\" });\n    const result = await getItemHandler({ id: \"123\" });\n    expect(result.content[0].text).toContain(\"Test\");\n  });\n\n  it(\"returns error for missing item\", async () => {\n    mockDb.findById.mockResolvedValue(null);\n    const result = await getItemHandler({ id: \"missing\" });\n    expect(result.isError).toBe(true);\n  });\n\n  it(\"handles API timeout gracefully\", async () => {\n    mockDb.findById.mockRejectedValue(new Error(\"timeout\"));\n    const result = await getItemHandler({ id: \"123\" });\n    expect(result.isError).toBe(true);\n    expect(result.content[0].text).toContain(\"try again\");\n  });\n});\n```\n\n### Integration Test with MCP Inspector\n```bash\n# Use the MCP Inspector to manually test\nnpx @modelcontextprotocol/inspector node server.js\n\n# Or use mcporter for CLI testing\nmcporter call my-service.get_item id=123\nmcporter list my-service --schema  # verify tool schemas\n```\n\n### Test Checklist Per Tool\n- [ ] Happy path returns expected format\n- [ ] Missing required params returns clear error\n- [ ] Invalid param types return clear error\n- [ ] Not-found cases handled (don't throw, return error content)\n- [ ] Rate limit / quota exceeded handled\n- [ ] Auth failure handled (expired token, invalid key)\n- [ ] Large response truncated appropriately\n- [ ] Timeout handled (external API slow)\n- [ ] Concurrent calls don't interfere\n\n---\n\n## Phase 6: Common MCP Server Patterns\n\n### 1. API Wrapper (most common)\nWrap an existing REST/GraphQL API as MCP tools.\n```\nExternal API → MCP Server → Agent\n```\n**Key decisions:**\n- Map 1 API endpoint → 1 MCP tool (usually)\n- Simplify params (agent doesn't need every API option)\n- Aggregate related calls (e.g., get user + get user's repos = 1 tool)\n- Cache where safe (reduce API calls)\n\n### 2. Database Query\n```\nDatabase → MCP Server → Agent\n```\n**Safety rules:**\n- Read-only by default. Write tools require explicit opt-in.\n- Parameterized queries only. NEVER interpolate agent input into SQL.\n- Row limit on all queries (agent can ask for more if needed).\n- Schema as a resource (let agent discover tables/columns).\n\n### 3. File System\n```\nFile System → MCP Server → Agent\n```\n**Safety rules:**\n- Sandbox to specific directories. Never allow `../` traversal.\n- Read-only by default. Write requires allowlist.\n- Size limits on reads. Don't send 1GB files through MCP.\n\n### 4. Multi-Step Workflow\nSome tools need to orchestrate multiple steps:\n```typescript\nserver.tool(\"deploy_service\", \"Build, test, and deploy a service\", {\n  service: z.string(),\n  environment: z.enum([\"staging\", \"production\"]),\n}, async ({ service, environment }) => {\n  // Step 1: Build\n  const buildResult = await build(service);\n  if (!buildResult.success) return error(`Build failed: ${buildResult.error}`);\n\n  // Step 2: Test\n  const testResult = await runTests(service);\n  if (!testResult.success) return error(`Tests failed: ${testResult.summary}`);\n\n  // Step 3: Deploy (only if build + tests pass)\n  if (environment === \"production\") {\n    // Extra safety: require confirmation resource\n    return {\n      content: [{\n        type: \"text\",\n        text: `Ready to deploy ${service} to production. Tests: ${testResult.passed}/${testResult.total} passed. Call confirm_deploy to proceed.`\n      }]\n    };\n  }\n  const deployResult = await deploy(service, environment);\n  return success(`Deployed ${service} to ${environment}: ${deployResult.url}`);\n});\n```\n\n### 5. Aggregator Server\nCombine multiple data sources into unified tools:\n```\nGitHub + Jira + PagerDuty → DevOps MCP Server → Agent\n```\nOne `get_service_status` tool that queries all three and returns a unified view.\n\n---\n\n## Phase 7: Security & Hardening\n\n### Threat Model\n| Threat | Risk | Mitigation |\n|--------|------|------------|\n| Prompt injection via tool output | Agent executes malicious instructions in API response | Sanitize output, strip HTML/scripts |\n| Excessive permissions | Tool has write access it shouldn't | Principle of least privilege per tool |\n| Data exfiltration | Agent sends sensitive data to wrong tool | Tool allowlists, audit logging |\n| Denial of service | Agent calls tool in infinite loop | Rate limiting, circuit breakers |\n| Credential leakage | API keys in tool responses | Strip sensitive fields from output |\n| SSRF | Agent provides URL that hits internal network | URL allowlisting, no private IPs |\n\n### Security Checklist\n- [ ] Every tool has minimum required permissions\n- [ ] Write operations require explicit confirmation or are behind feature flags\n- [ ] API keys/secrets NEVER appear in tool responses\n- [ ] Output sanitized (no HTML, no executable content)\n- [ ] Rate limits per tool AND per client\n- [ ] Audit log: who called what tool, when, with what params\n- [ ] Input validation before any external call\n- [ ] URL parameters validated against allowlist (prevent SSRF)\n- [ ] Timeout on every external call (max 30s default)\n- [ ] Circuit breaker: disable tool if error rate > 50% for 5 min\n\n### Dangerous Tool Patterns (Avoid)\n```\n❌ server.tool(\"execute_sql\", ..., async ({ query }) => db.raw(query))\n❌ server.tool(\"run_command\", ..., async ({ cmd }) => exec(cmd))\n❌ server.tool(\"fetch_url\", ..., async ({ url }) => fetch(url))  // SSRF\n❌ server.tool(\"write_file\", ..., async ({ path, content }) => fs.writeFile(path, content))\n```\n\n### Safe Alternatives\n```\n✅ Parameterized queries with allowlisted tables\n✅ Predefined commands with argument validation\n✅ URL allowlist + no private IP ranges\n✅ Write to specific directory + filename validation\n```\n\n---\n\n## Phase 8: Debugging & Troubleshooting\n\n### Common Issues\n\n| Symptom | Likely Cause | Fix |\n|---------|-------------|-----|\n| Tool not appearing in agent | Schema error / server not connected | Check `mcporter list` or client logs |\n| \"Connection refused\" | Server not running or wrong port | Verify process, check port |\n| Tool times out | External API slow or hanging | Add timeout, check API health |\n| \"Invalid params\" | Schema mismatch between client/server | Verify schema with `--schema` flag |\n| Agent picks wrong tool | Ambiguous descriptions | Rewrite descriptions, add \"Use this when...\" |\n| Agent calls tool in loop | Tool returning confusing error | Return clearer error with \"do NOT retry\" |\n| Large response crashes | No output truncation | Add pagination or character limit |\n| Auth errors intermittent | Token expiry | Implement token refresh |\n\n### Debug Workflow\n1. **Verify server starts**: `node server.js` — does it start without errors?\n2. **List tools**: `mcporter list my-server --schema` — are all tools registered?\n3. **Call directly**: `mcporter call my-server.tool_name param=value` — does it return expected output?\n4. **Check client config**: Is the server path/URL correct? Are env vars set?\n5. **Read client logs**: Most clients log MCP connection errors\n6. **Test with Inspector**: `npx @modelcontextprotocol/inspector` for interactive debugging\n\n### Logging Template\n```typescript\nserver.tool(\"my_tool\", description, schema, async (params) => {\n  const requestId = crypto.randomUUID().slice(0, 8);\n  console.error(`[${requestId}] my_tool called:`, JSON.stringify(params));\n  const start = Date.now();\n  try {\n    const result = await doWork(params);\n    console.error(`[${requestId}] my_tool success: ${Date.now() - start}ms`);\n    return success(result);\n  } catch (error) {\n    console.error(`[${requestId}] my_tool error: ${error.message} (${Date.now() - start}ms)`);\n    return errorResponse(error.message);\n  }\n});\n```\n\nNote: Use `console.error` for logs in stdio transport (stdout is reserved for MCP protocol).\n\n---\n\n## Phase 9: MCP Server Selection Guide\n\n### Evaluating Existing MCP Servers\n\nScore 0-5 per dimension:\n\n| Dimension | What to Check |\n|-----------|--------------|\n| **Maintained** | Last commit < 3 months? Issues addressed? Version > 1.0? |\n| **Secure** | No raw SQL/exec? Auth implemented? Input validated? |\n| **Well-typed** | Full JSON Schema for all tools? Descriptions useful? |\n| **Tested** | Has tests? CI passing? |\n| **Documented** | Setup instructions? Tool descriptions? Examples? |\n| **Lightweight** | Minimal dependencies? Fast startup? |\n\n**Score < 15/30**: Build your own. **Score 15-24**: Use with caution. **Score 25+**: Good to use.\n\n### Popular MCP Server Categories\n| Category | Use Case | Examples |\n|----------|----------|---------|\n| Code | GitHub, GitLab, code search | github-mcp, gitlab-mcp |\n| Data | PostgreSQL, SQLite, Snowflake | postgres-mcp, sqlite-mcp |\n| Comms | Slack, Discord, email | slack-mcp, gmail-mcp |\n| Docs | Notion, Confluence, Google Docs | notion-mcp, gdocs-mcp |\n| DevOps | AWS, GCP, Kubernetes, Terraform | aws-mcp, k8s-mcp |\n| Search | Brave, Google, vector stores | brave-search, rag-mcp |\n| Files | Local FS, S3, Google Drive | filesystem-mcp, s3-mcp |\n| CRM | HubSpot, Salesforce | hubspot-mcp, sfdc-mcp |\n\n---\n\n## Phase 10: Architecture Patterns\n\n### Single Agent + Multiple Servers\n```\nAgent ──┬── github-mcp\n        ├── slack-mcp\n        ├── postgres-mcp\n        └── custom-mcp\n```\nBest for: Most use cases. Simple, effective.\n\n### Gateway Pattern\n```\nAgent ── MCP Gateway ──┬── server-1\n                       ├── server-2\n                       └── server-3\n```\nGateway handles: auth, rate limiting, logging, routing.\nBest for: Enterprise, multi-tenant, compliance requirements.\n\n### Agent-per-Domain\n```\nOrchestrator Agent\n├── Code Agent (github-mcp, gitlab-mcp)\n├── Data Agent (postgres-mcp, analytics-mcp)\n└── Comms Agent (slack-mcp, email-mcp)\n```\nBest for: Complex workflows, specialized agents.\n\n### Tool Count Guidelines\n| Total Tools | Recommendation |\n|-------------|---------------|\n| 1-10 | Great. Agent handles well. |\n| 10-20 | Good. Ensure distinct descriptions. |\n| 20-30 | Caution. Group by server, review descriptions. |\n| 30-50 | Risk. Consider agent-per-domain pattern. |\n| 50+ | Dangerous. Agent WILL pick wrong tools. Split or use gateway. |\n\n---\n\n## Phase 11: Publishing MCP Servers\n\n### Package Structure\n```\nmy-mcp-server/\n├── src/\n│   ├── server.ts        # MCP server entry\n│   ├── tools/           # Tool handlers\n│   │   ├── search.ts\n│   │   └── create.ts\n│   ├── auth.ts          # Auth middleware\n│   └── config.ts        # Configuration\n├── tests/\n│   ├── tools.test.ts\n│   └── integration.test.ts\n├── package.json\n├── tsconfig.json\n├── README.md            # Setup + tool docs\n└── LICENSE\n```\n\n### README Template for MCP Servers\n```markdown\n# [Service] MCP Server\n\n[One sentence: what this enables]\n\n## Quick Start\n[3 steps max to get running]\n\n## Tools\n| Tool | Description | Params |\n|------|-------------|--------|\n[Table of all tools]\n\n## Configuration\n[Env vars, auth setup]\n\n## Examples\n[2-3 real usage examples with agent conversation]\n```\n\n### npm Publishing\n```bash\n# package.json\n{\n  \"name\": \"@myorg/service-mcp\",\n  \"version\": \"1.0.0\",\n  \"bin\": { \"service-mcp\": \"./dist/server.js\" },\n  \"files\": [\"dist\"],\n  \"keywords\": [\"mcp\", \"model-context-protocol\", \"ai-tools\"]\n}\n\nnpm publish\n```\n\n---\n\n## Quality Rubric (0-100)\n\n| Dimension | Weight | What to Score |\n|-----------|--------|--------------|\n| Tool design | 20% | Names, descriptions, granularity, params |\n| Security | 20% | Auth, input validation, output sanitization, least privilege |\n| Reliability | 15% | Error handling, timeouts, circuit breakers |\n| Testing | 15% | Unit + integration coverage, edge cases |\n| Documentation | 10% | Setup, tool docs, examples |\n| Performance | 10% | Response time, output size, caching |\n| Maintainability | 10% | Code structure, types, logging |\n\n**Score 0-40**: Not production ready. **40-70**: Usable with caveats. **70-90**: Solid. **90+**: Excellent.\n\n---\n\n## Common Mistakes\n\n| Mistake | Fix |\n|---------|-----|\n| God-tool that does everything | Split into focused tools |\n| Vague tool descriptions | Write descriptions as if explaining to a new hire |\n| No error handling | Every external call wrapped in try/catch |\n| Returning raw API responses | Shape output for agent consumption |\n| No rate limiting | Add per-tool and per-client limits |\n| Ignoring output size | Paginate or truncate responses |\n| Hardcoded credentials | Use env vars or secret manager |\n| No logging | Can't debug what you can't see |\n| Testing only happy path | Test errors, timeouts, edge cases |\n| Building before checking | Search for existing MCP server first |\n\n---\n\n## Natural Language Commands\n\n- \"Build an MCP server for [service]\" → Use Phase 2 templates\n- \"Add a tool to my MCP server\" → Follow tool design rules\n- \"Secure my MCP server\" → Phase 7 checklist\n- \"Debug MCP connection issue\" → Phase 8 workflow\n- \"Evaluate this MCP server\" → Phase 9 scoring\n- \"Design multi-server architecture\" → Phase 10 patterns\n- \"Publish my MCP server\" → Phase 11 structure\n- \"Convert REST API to MCP\" → Phase 6 Pattern 1\n- \"Add auth to my MCP server\" → Phase 3 auth patterns\n- \"Test my MCP server\" → Phase 5 checklist\n- \"How many tools is too many?\" → Phase 10 tool count table\n- \"Review my tool descriptions\" → Phase 2 quality checklist\n","readmeExcerpt":"MCP Engineering — Complete Model Context Protocol System Build, integrate, secure, and scale MCP servers and clients. From first server to production multi-tool architecture. When to Use - Building an MCP server (any language) - Integrating MCP tools into an AI agent - Debugging MCP connection/auth issues - Designing multi-server architectures - Securing MCP endpoints for production - Evaluating which MCP servers to ","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"Agent (Client) ←→ MCP Transport ←→ MCP Server ←→ External Service\n                   (stdio/HTTP)      (your code)    (API, DB, file system)"},{"language":"yaml","snippet":"server_name: \"[service]-mcp\"\ndescription: \"[What this server does in one sentence]\"\ntransport: stdio | http\ntools:\n  - name: \"[verb_noun]\"\n    description: \"[What it does — be specific for LLM tool selection]\"\n    params:\n      - name: \"[param]\"\n        type: \"string | number | boolean | object | array\"\n        required: true | false\n        description: \"[What this param controls]\"\n    returns: \"[What the tool returns]\"\n    error_cases:\n      - \"[When/how it fails]\"\nresources:\n  - uri: \"[protocol://path]\"\n    description: \"[What data this exposes]\"\nexternal_dependencies:\n  - \"[API/service this wraps]\"\nauth_required: true | false\nauth_method: \"api_key | oauth2 | none\""},{"language":"typescript","snippet":"// server.ts — minimal MCP server\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\n\nconst server = new McpServer({\n  name: \"my-service\",\n  version: \"1.0.0\",\n});\n\n// Define a tool\nserver.tool(\n  \"get_item\",                          // tool name (verb_noun)\n  \"Fetch an item by ID\",               // description (LLM reads this)\n  { id: z.string().describe(\"Item ID\") }, // params with descriptions\n  async ({ id }) => {\n    try {\n      const result = await fetchItem(id);\n      return {\n        content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n      };\n    } catch (error) {\n      return {\n        content: [{ type: \"text\", text: `Error: ${error.message}` }],\n        isError: true,\n      };\n    }\n  }\n);\n\n// Define a resource\nserver.resource(\n  \"config\",\n  \"config://app\",\n  async (uri) => ({\n    contents: [{ uri: uri.href, mimeType: \"application/json\", text: JSON.stringify(config) }],\n  })\n);\n\n// Start\nconst transport = new StdioServerTransport();\nawait server.connect(transport);"},{"language":"python","snippet":"# server.py — minimal MCP server\nfrom mcp.server import Server\nfrom mcp.server.stdio import stdio_server\nfrom mcp.types import Tool, TextContent\nimport json\n\nserver = Server(\"my-service\")\n\n@server.list_tools()\nasync def list_tools():\n    return [\n        Tool(\n            name=\"get_item\",\n            description=\"Fetch an item by ID\",\n            inputSchema={\n                \"type\": \"object\",\n                \"properties\": {\n                    \"id\": {\"type\": \"string\", \"description\": \"Item ID\"}\n                },\n                \"required\": [\"id\"]\n            }\n        )\n    ]\n\n@server.call_tool()\nasync def call_tool(name: str, arguments: dict):\n    if name == \"get_item\":\n        result = await fetch_item(arguments[\"id\"])\n        return [TextContent(type=\"text\", text=json.dumps(result, indent=2))]\n    raise ValueError(f\"Unknown tool: {name}\")\n\nasync def main():\n    async with stdio_server() as (read, write):\n        await server.run(read, write, server.create_initialization_options())\n\nif __name__ == \"__main__\":\n    import asyncio\n    asyncio.run(main())"},{"language":"typescript","snippet":"import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport express from \"express\";\n\nconst app = express();\napp.use(express.json());\n\nconst server = new McpServer({ name: \"my-service\", version: \"1.0.0\" });\n// ... register tools ...\n\napp.post(\"/mcp\", async (req, res) => {\n  const transport = new StreamableHTTPServerTransport(\"/mcp\", res);\n  await server.connect(transport);\n  await transport.handleRequest(req, res);\n});\n\napp.listen(3001, () => console.log(\"MCP server on :3001\"));"},{"language":"typescript","snippet":"// Middleware\nfunction authMiddleware(req, res, next) {\n  const key = req.headers[\"x-api-key\"] || req.headers.authorization?.replace(\"Bearer \", \"\");\n  if (!key || !validKeys.has(key)) {\n    return res.status(401).json({ error: \"Invalid API key\" });\n  }\n  req.userId = keyToUser.get(key);\n  next();\n}"}],"parameters":{},"dependencies":[],"permissions":[],"extractedFiles":[],"languages":["typescript"],"docsSourceLabel":"CLAWHUB","editorialOverview":"MCP Engineering — Complete Model Context Protocol System MCP Engineering — Complete Model Context Protocol System Build, integrate, secure, and scale MCP servers and clients. From first server to production multi-tool architecture. When to Use - Building an MCP server (any language) - Integrating MCP tools into an AI agent - Debugging MCP connection/auth issues - Designing multi-server architectures - Securing MCP endpoints for production - Evaluating which MCP servers to","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":381,"uniquenessScore":64,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T21:21:31.828Z","emptyReason":null},"items":[{"id":"91842505-d59e-48ad-ae35-d504a6e8eadb","entityType":"agent","canonicalPath":"/agent/ard-urn-air-com-brainiall-mcp-nlp","slug":"ard-urn-air-com-brainiall-mcp-nlp","name":"Brainiall NLP","description":"Sentiment, toxicity, entity extraction, PII, translation, summary, QA, fraud scoring, safety audit.","url":"https://api.brainiall.com/mcp/nlp/mcp","homepage":"https://api.brainiall.com/mcp/nlp/mcp","source":"ARD_REGISTRY","protocols":["MCP"],"capabilities":["mcp","mcp-registry"],"safetyScore":95,"overallRank":93.5,"updatedAt":"2026-10-09T19:59:36.369Z","createdAt":"2026-10-09T02:32:12.319Z","downloads":null},{"id":"c07bfd45-37e3-4ca4-bce7-0f2c138264a2","entityType":"agent","canonicalPath":"/agent/ard-urn-air-ai-revuo-mcp-revuo","slug":"ard-urn-air-ai-revuo-mcp-revuo","name":"Revuo","description":"Agent-callable B2B SaaS directory: capability-structured, continuously verified listings.","url":"https://www.revuo.ai/api/mcp","homepage":"https://www.revuo.ai/api/mcp","source":"ARD_REGISTRY","protocols":["MCP"],"capabilities":["mcp","mcp-registry"],"safetyScore":95,"overallRank":93.5,"updatedAt":"2026-10-09T19:04:52.902Z","createdAt":"2026-10-09T02:32:15.408Z","downloads":null},{"id":"b72e3032-816c-4f68-bcc9-1a847aef4d79","entityType":"agent","canonicalPath":"/agent/ard-urn-air-ai-bankee-mcp-inferventis-mcp","slug":"ard-urn-air-ai-bankee-mcp-inferventis-mcp","name":"Inferventis MCP Server","description":"Loan & mortgage calculator, compound interest, ROI, crypto prices, FX conversion for AI agents.","url":"https://mcp-server-295985738387.europe-west1.run.app/mcp","homepage":"https://mcp-server-295985738387.europe-west1.run.app/mcp","source":"ARD_REGISTRY","protocols":["MCP"],"capabilities":["mcp","mcp-registry"],"safetyScore":95,"overallRank":93.5,"updatedAt":"2026-10-09T18:09:37.547Z","createdAt":"2026-10-09T02:32:16.798Z","downloads":null},{"id":"a785e560-2661-4edd-a374-5e8de7c54e7a","entityType":"agent","canonicalPath":"/agent/ard-urn-air-io-github-cleandev-fix-mcp-shortlistlens","slug":"ard-urn-air-io-github-cleandev-fix-mcp-shortlistlens","name":"ShortlistLens","description":"Structured website and review evidence for AI-assisted local-business shortlisting.","url":"https://shortlistlens-mcp.streaming22box.workers.dev/mcp","homepage":"https://shortlistlens-mcp.streaming22box.workers.dev/mcp","source":"ARD_REGISTRY","protocols":["MCP"],"capabilities":["mcp","mcp-registry"],"safetyScore":95,"overallRank":93.5,"updatedAt":"2026-10-09T18:04:03.143Z","createdAt":"2026-10-09T02:32:13.915Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"MCP","href":"/agent/protocol/mcp"},{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}