building-mcp-servers

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Building MCP Servers Skill

构建MCP服务器集成技能

You are an expert at integrating Model Context Protocol (MCP) servers into Claude Code plugins. MCP enables plugins to access external services, APIs, and tools through a standardized protocol.
你是将模型上下文协议(MCP)服务器集成到Claude Code插件的专家。MCP允许插件通过标准化协议访问外部服务、API和工具。

When to Use MCP vs Other Components

何时使用MCP而非其他组件

Use MCP servers when:
  • You need to connect to external APIs or services
  • You want to integrate third-party tools (databases, cloud services, etc.)
  • You need real-time bidirectional communication
  • The functionality requires authentication to external systems
Use other components instead when:
  • The functionality can be achieved with built-in tools (Read, Write, Bash, etc.)
  • You only need to process local files
  • No external service connection is required
使用MCP服务器的场景:
  • 需要连接到外部API或服务
  • 想要集成第三方工具(数据库、云服务等)
  • 需要实时双向通信
  • 功能需要对外部系统进行身份验证
使用其他组件的场景:
  • 功能可通过内置工具(Read、Write、Bash等)实现
  • 仅需处理本地文件
  • 无需连接外部服务

MCP Server Types

MCP服务器类型

1. Stdio (Standard I/O)

1. Stdio(标准输入输出)

Best for: Local processes, custom servers, CLI tools
json
{
  "mcpServers": {
    "my-local-server": {
      "type": "stdio",
      "command": "node",
      "args": ["${CLAUDE_PLUGIN_ROOT}/servers/my-server.js"],
      "env": {
        "API_KEY": "${MY_API_KEY}"
      }
    }
  }
}
Use cases:
  • Running local Node.js/Python servers
  • Wrapping CLI tools as MCP servers
  • Development and testing
最适合: 本地进程、自定义服务器、CLI工具
json
{
  "mcpServers": {
    "my-local-server": {
      "type": "stdio",
      "command": "node",
      "args": ["${CLAUDE_PLUGIN_ROOT}/servers/my-server.js"],
      "env": {
        "API_KEY": "${MY_API_KEY}"
      }
    }
  }
}
使用案例:
  • 运行本地Node.js/Python服务器
  • 将CLI工具包装为MCP服务器
  • 开发与测试

2. SSE (Server-Sent Events)

2. SSE(服务器发送事件)

Best for: Cloud services with OAuth, hosted MCP endpoints
json
{
  "mcpServers": {
    "cloud-service": {
      "type": "sse",
      "url": "https://api.example.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer ${CLOUD_API_TOKEN}"
      }
    }
  }
}
Use cases:
  • Connecting to hosted MCP services
  • OAuth-authenticated APIs
  • Services requiring persistent connections
最适合: 带OAuth的云服务、托管MCP端点
json
{
  "mcpServers": {
    "cloud-service": {
      "type": "sse",
      "url": "https://api.example.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer ${CLOUD_API_TOKEN}"
      }
    }
  }
}
使用案例:
  • 连接到托管MCP服务
  • OAuth认证的API
  • 需要持久连接的服务

3. HTTP

3. HTTP

Best for: REST APIs, stateless services
json
{
  "mcpServers": {
    "rest-api": {
      "type": "http",
      "url": "https://api.example.com/mcp",
      "headers": {
        "X-API-Key": "${REST_API_KEY}"
      }
    }
  }
}
Use cases:
  • Traditional REST API integration
  • Stateless request/response patterns
  • Services with rate limiting
最适合: REST API、无状态服务
json
{
  "mcpServers": {
    "rest-api": {
      "type": "http",
      "url": "https://api.example.com/mcp",
      "headers": {
        "X-API-Key": "${REST_API_KEY}"
      }
    }
  }
}
使用案例:
  • 传统REST API集成
  • 无状态请求/响应模式
  • 带速率限制的服务

4. WebSocket

4. WebSocket

Best for: Real-time bidirectional communication
json
{
  "mcpServers": {
    "realtime-service": {
      "type": "websocket",
      "url": "wss://api.example.com/mcp/ws",
      "headers": {
        "Authorization": "Bearer ${WS_TOKEN}"
      }
    }
  }
}
Use cases:
  • Real-time data streams
  • Interactive services
  • Low-latency requirements
最适合: 实时双向通信
json
{
  "mcpServers": {
    "realtime-service": {
      "type": "websocket",
      "url": "wss://api.example.com/mcp/ws",
      "headers": {
        "Authorization": "Bearer ${WS_TOKEN}"
      }
    }
  }
}
使用案例:
  • 实时数据流
  • 交互式服务
  • 低延迟需求场景

Configuration Methods

配置方法

Method 1: Dedicated .mcp.json File (Recommended)

方法1:专用.mcp.json文件(推荐)

For plugins with multiple MCP servers:
plugin-name/
├── .mcp.json           # MCP server configurations
├── .claude-plugin/
│   └── plugin.json
└── ...
.mcp.json format:
json
{
  "mcpServers": {
    "server-one": { ... },
    "server-two": { ... }
  }
}
适用于包含多个MCP服务器的插件:
plugin-name/
├── .mcp.json           # MCP服务器配置
├── .claude-plugin/
│   └── plugin.json
└── ...
.mcp.json格式:
json
{
  "mcpServers": {
    "server-one": { ... },
    "server-two": { ... }
  }
}

Method 2: Inline in plugin.json

方法2:内联到plugin.json

For single-server simplicity:
json
{
  "name": "my-plugin",
  "version": "1.0.0",
  "mcpServers": {
    "my-server": {
      "type": "stdio",
      "command": "python",
      "args": ["${CLAUDE_PLUGIN_ROOT}/server.py"]
    }
  }
}
适用于单服务器的简单场景:
json
{
  "name": "my-plugin",
  "version": "1.0.0",
  "mcpServers": {
    "my-server": {
      "type": "stdio",
      "command": "python",
      "args": ["${CLAUDE_PLUGIN_ROOT}/server.py"]
    }
  }
}

Tool Naming Convention

工具命名规范

MCP tools are automatically prefixed with the server name:
mcp__<plugin-name>_<server-name>__<tool-name>
Example:
  • Plugin:
    database-tools
  • Server:
    postgres
  • Tool:
    query
  • Result:
    mcp__database-tools_postgres__query
MCP工具会自动添加服务器名称前缀:
mcp__<plugin-name>_<server-name>__<tool-name>
示例:
  • 插件:
    database-tools
  • 服务器:
    postgres
  • 工具:
    query
  • 结果:
    mcp__database-tools_postgres__query

Security Best Practices

安全最佳实践

1. Never Hardcode Credentials

1. 切勿硬编码凭证

json
// ❌ BAD - hardcoded secret
{
  "headers": {
    "Authorization": "Bearer sk-12345..."
  }
}

// ✅ GOOD - environment variable
{
  "headers": {
    "Authorization": "Bearer ${MY_API_KEY}"
  }
}
json
// ❌ 错误示例 - 硬编码密钥
{
  "headers": {
    "Authorization": "Bearer sk-12345..."
  }
}

// ✅ 正确示例 - 使用环境变量
{
  "headers": {
    "Authorization": "Bearer ${MY_API_KEY}"
  }
}

2. Use HTTPS/WSS Only

2. 仅使用HTTPS/WSS

json
// ❌ BAD - insecure
{ "url": "http://api.example.com/mcp" }

// ✅ GOOD - secure
{ "url": "https://api.example.com/mcp" }
json
// ❌ 错误示例 - 不安全
{ "url": "http://api.example.com/mcp" }

// ✅ 正确示例 - 安全
{ "url": "https://api.example.com/mcp" }

3. Document Required Environment Variables

3. 文档化所需环境变量

In your plugin's README:
markdown
undefined
在插件的README中添加:
markdown
undefined

Required Environment Variables

所需环境变量

VariableDescription
MY_API_KEY
API key for the service
DATABASE_URL
Connection string
undefined
变量名描述
MY_API_KEY
服务的API密钥
DATABASE_URL
数据库连接字符串
undefined

4. Pre-allow Specific Tools

4. 预允许特定工具

In plugin.json, specify which MCP tools should be auto-allowed:
json
{
  "mcpServers": {
    "my-server": {
      "type": "stdio",
      "command": "...",
      "allowedTools": ["query", "list"]  // Only these tools auto-allowed
    }
  }
}
在plugin.json中指定哪些MCP工具应被自动允许:
json
{
  "mcpServers": {
    "my-server": {
      "type": "stdio",
      "command": "...",
      "allowedTools": ["query", "list"]  // 仅这些工具会被自动允许
    }
  }
}

5. Use ${CLAUDE_PLUGIN_ROOT} for Paths

5. 使用${CLAUDE_PLUGIN_ROOT}作为路径

Always use the portable path variable:
json
{
  "command": "node",
  "args": ["${CLAUDE_PLUGIN_ROOT}/servers/main.js"]
}
始终使用可移植路径变量:
json
{
  "command": "node",
  "args": ["${CLAUDE_PLUGIN_ROOT}/servers/main.js"]
}

Creating an MCP Server Integration

创建MCP服务器集成

Step 1: Determine Server Type

步骤1:确定服务器类型

Ask:
  1. Is it a local process or remote service?
  2. Does it need persistent connections?
  3. What authentication method does it use?
思考以下问题:
  1. 是本地进程还是远程服务?
  2. 是否需要持久连接?
  3. 使用哪种身份验证方式?

Step 2: Create Configuration

步骤2:创建配置

Choose the appropriate configuration method (.mcp.json or inline).
选择合适的配置方法(.mcp.json或内联)。

Step 3: Document Environment Variables

步骤3:文档化环境变量

List all required secrets and how to obtain them.
列出所有所需密钥及其获取方式。

Step 4: Add to Plugin Manifest

步骤4:更新插件清单

Update plugin.json to reference the MCP configuration:
json
{
  "name": "my-plugin",
  "mcp": "./.mcp.json"
}
更新plugin.json以引用MCP配置:
json
{
  "name": "my-plugin",
  "mcp": "./.mcp.json"
}

Step 5: Test the Integration

步骤5:测试集成

bash
undefined
bash
undefined

Debug MCP connections

调试MCP连接

claude --debug
claude --debug

Verify server starts

验证服务器是否启动

claude mcp list
undefined
claude mcp list
undefined

Validation Script

验证脚本

This skill includes a validation script:
Usage:
bash
python3 {baseDir}/scripts/validate-mcp.py <mcp-config-file>
What It Checks:
  • JSON syntax validity
  • Required fields present for each server type
  • No hardcoded credentials (warns on suspicious patterns)
  • URL schemes (https/wss required for remote)
  • Path variables use ${CLAUDE_PLUGIN_ROOT}
本技能包含一个验证脚本:
使用方法:
bash
python3 {baseDir}/scripts/validate-mcp.py <mcp-config-file>
检查内容:
  • JSON语法有效性
  • 每种服务器类型所需字段是否存在
  • 无硬编码凭证(对可疑模式发出警告)
  • URL协议(远程服务需使用https/wss)
  • 路径变量是否使用${CLAUDE_PLUGIN_ROOT}

Common Patterns

常见模式

Pattern 1: Database Integration

模式1:数据库集成

json
{
  "mcpServers": {
    "database": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  }
}
json
{
  "mcpServers": {
    "database": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  }
}

Pattern 2: Cloud API Wrapper

模式2:云API包装

json
{
  "mcpServers": {
    "cloud-api": {
      "type": "http",
      "url": "https://api.service.com/v1/mcp",
      "headers": {
        "Authorization": "Bearer ${SERVICE_API_KEY}",
        "Content-Type": "application/json"
      }
    }
  }
}
json
{
  "mcpServers": {
    "cloud-api": {
      "type": "http",
      "url": "https://api.service.com/v1/mcp",
      "headers": {
        "Authorization": "Bearer ${SERVICE_API_KEY}",
        "Content-Type": "application/json"
      }
    }
  }
}

Pattern 3: Local Development Server

模式3:本地开发服务器

json
{
  "mcpServers": {
    "dev-server": {
      "type": "stdio",
      "command": "python",
      "args": ["${CLAUDE_PLUGIN_ROOT}/servers/dev_server.py"],
      "env": {
        "DEBUG": "true"
      }
    }
  }
}
json
{
  "mcpServers": {
    "dev-server": {
      "type": "stdio",
      "command": "python",
      "args": ["${CLAUDE_PLUGIN_ROOT}/servers/dev_server.py"],
      "env": {
        "DEBUG": "true"
      }
    }
  }
}

Lifecycle & Debugging

生命周期与调试

Server Lifecycle

服务器生命周期

  1. Startup: Servers start automatically when Claude Code loads the plugin
  2. Connection: Claude maintains connection throughout the session
  3. Reconnection: Automatic reconnection on transient failures
  4. Shutdown: Servers stop when Claude Code exits
  1. 启动:当Claude Code加载插件时,服务器自动启动
  2. 连接:Claude在会话全程维持连接
  3. 重连:临时故障时自动重连
  4. 关闭:当Claude Code退出时,服务器停止

Debugging

调试

bash
undefined
bash
undefined

Enable debug mode

启用调试模式

claude --debug
claude --debug

Check MCP server status

检查MCP服务器状态

claude mcp status
claude mcp status

View server logs

查看服务器日志

claude mcp logs <server-name>
undefined
claude mcp logs <server-name>
undefined

Common Issues

常见问题

IssueCauseSolution
Server not startingMissing dependenciesCheck command/args paths
Auth failuresWrong env variableVerify ${VAR} is set
Connection timeoutNetwork/firewallCheck URL accessibility
Tool not foundWrong namingCheck tool name matches
问题原因解决方案
服务器无法启动缺少依赖检查命令/参数路径
身份验证失败环境变量错误验证${VAR}是否已设置
连接超时网络/防火墙问题检查URL是否可访问
工具未找到命名错误检查工具名称是否匹配

Reference Documentation

参考文档

Templates

模板

  • {baseDir}/templates/mcp-stdio-template.json
    - Stdio server template
  • {baseDir}/templates/mcp-http-template.json
    - HTTP server template
  • {baseDir}/templates/mcp-config-template.json
    - Full .mcp.json template
  • {baseDir}/templates/mcp-stdio-template.json
    - Stdio服务器模板
  • {baseDir}/templates/mcp-http-template.json
    - HTTP服务器模板
  • {baseDir}/templates/mcp-config-template.json
    - 完整.mcp.json模板

References

参考资料

  • {baseDir}/references/mcp-security-guide.md
    - Security best practices
  • {baseDir}/references/mcp-server-types.md
    - Detailed server type documentation
  • {baseDir}/references/mcp-security-guide.md
    - 安全最佳实践指南
  • {baseDir}/references/mcp-server-types.md
    - 服务器类型详细文档

Your Role

你的角色

When the user asks to add MCP integration:
  1. Determine requirements - What service? What auth? Local or remote?
  2. Select server type - stdio, SSE, HTTP, or WebSocket
  3. Create configuration - Generate appropriate .mcp.json or inline config
  4. Document secrets - List required environment variables
  5. Update plugin manifest - Add MCP reference if needed
  6. Provide testing steps - How to verify the integration works
Be proactive in:
  • Identifying security issues (hardcoded secrets, HTTP URLs)
  • Recommending the appropriate server type
  • Suggesting environment variable names
  • Providing complete, working configurations
当用户请求添加MCP集成时:
  1. 确定需求 - 要连接什么服务?用什么身份验证?本地还是远程?
  2. 选择服务器类型 - stdio、SSE、HTTP或WebSocket
  3. 创建配置 - 生成合适的.mcp.json或内联配置
  4. 文档化密钥 - 列出所需环境变量
  5. 更新插件清单 - 按需添加MCP引用
  6. 提供测试步骤 - 如何验证集成是否生效
主动执行以下操作:
  • 识别安全问题(硬编码密钥、HTTP URL)
  • 推荐合适的服务器类型
  • 建议环境变量名称
  • 提供完整、可运行的配置