mcp-integration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMCP Integration for Claude Code Plugins
Claude Code插件的MCP集成
Overview
概述
Model Context Protocol (MCP) enables Claude Code plugins to integrate with external services and APIs by providing structured tool access. Use MCP integration to expose external service capabilities as tools within Claude Code.
Key capabilities:
- Connect to external services (databases, APIs, file systems)
- Provide 10+ related tools from a single service
- Handle OAuth and complex authentication flows
- Bundle MCP servers with plugins for automatic setup
Model Context Protocol (MCP) 使Claude Code插件能够通过提供结构化的工具访问来集成外部服务和API。使用MCP集成可将外部服务功能作为工具暴露在Claude Code中。
核心功能:
- 连接到外部服务(数据库、API、文件系统)
- 从单个服务提供10+相关工具
- 处理OAuth和复杂认证流程
- 将MCP服务器与插件捆绑以实现自动设置
MCP Server Configuration Methods
MCP服务器配置方式
Plugins can bundle MCP servers in two ways:
插件可以通过两种方式捆绑MCP服务器:
Method 1: Dedicated .mcp.json (Recommended)
方式1:专用.mcp.json(推荐)
Create at plugin root:
.mcp.jsonjson
{
"database-tools": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
"env": {
"DB_URL": "${DB_URL}"
}
}
}Benefits:
- Clear separation of concerns
- Easier to maintain
- Better for multiple servers
在插件根目录创建:
.mcp.jsonjson
{
"database-tools": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
"env": {
"DB_URL": "${DB_URL}"
}
}
}优势:
- 关注点清晰分离
- 更易于维护
- 适合多服务器场景
Method 2: Inline in plugin.json
方式2:内联到plugin.json
Add field to plugin.json:
mcpServersjson
{
"name": "my-plugin",
"version": "1.0.0",
"mcpServers": {
"plugin-api": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server",
"args": ["--port", "8080"]
}
}
}Benefits:
- Single configuration file
- Good for simple single-server plugins
在plugin.json中添加字段:
mcpServersjson
{
"name": "my-plugin",
"version": "1.0.0",
"mcpServers": {
"plugin-api": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server",
"args": ["--port", "8080"]
}
}
}优势:
- 单一配置文件
- 适合简单的单服务器插件
MCP Server Types
MCP服务器类型
stdio (Local Process)
stdio(本地进程)
Execute local MCP servers as child processes. Best for local tools and custom servers.
Configuration:
json
{
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
"env": {
"LOG_LEVEL": "debug"
}
}
}Use cases:
- File system access
- Local database connections
- Custom MCP servers
- NPM-packaged MCP servers
Process management:
- Claude Code spawns and manages the process
- Communicates via stdin/stdout
- Terminates when Claude Code exits
将本地MCP服务器作为子进程执行。最适合本地工具和自定义服务器。
配置:
json
{
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
"env": {
"LOG_LEVEL": "debug"
}
}
}适用场景:
- 文件系统访问
- 本地数据库连接
- 自定义MCP服务器
- NPM打包的MCP服务器
进程管理:
- Claude Code生成并管理进程
- 通过stdin/stdout通信
- 当Claude Code退出时终止进程
SSE (Server-Sent Events)
SSE(Server-Sent Events)
Connect to hosted MCP servers with OAuth support. Best for cloud services.
Configuration:
json
{
"asana": {
"type": "sse",
"url": "https://mcp.asana.com/sse"
}
}Use cases:
- Official hosted MCP servers (Asana, GitHub, etc.)
- Cloud services with MCP endpoints
- OAuth-based authentication
- No local installation needed
Authentication:
- OAuth flows handled automatically
- User prompted on first use
- Tokens managed by Claude Code
连接到支持OAuth的托管MCP服务器。最适合云服务。
配置:
json
{
"asana": {
"type": "sse",
"url": "https://mcp.asana.com/sse"
}
}适用场景:
- 官方托管MCP服务器(Asana、GitHub等)
- 带有MCP端点的云服务
- 基于OAuth的认证
- 无需本地安装
认证:
- OAuth流程自动处理
- 首次使用时提示用户
- 令牌由Claude Code管理
HTTP (REST API)
HTTP(REST API)
Connect to RESTful MCP servers with token authentication.
Configuration:
json
{
"api-service": {
"type": "http",
"url": "https://api.example.com/mcp",
"headers": {
"Authorization": "Bearer ${API_TOKEN}",
"X-Custom-Header": "value"
}
}
}Use cases:
- REST API-based MCP servers
- Token-based authentication
- Custom API backends
- Stateless interactions
连接到使用令牌认证的RESTful MCP服务器。
配置:
json
{
"api-service": {
"type": "http",
"url": "https://api.example.com/mcp",
"headers": {
"Authorization": "Bearer ${API_TOKEN}",
"X-Custom-Header": "value"
}
}
}适用场景:
- 基于REST API的MCP服务器
- 基于令牌的认证
- 自定义API后端
- 无状态交互
WebSocket (Real-time)
WebSocket(实时)
Connect to WebSocket MCP servers for real-time bidirectional communication.
Configuration:
json
{
"realtime-service": {
"type": "ws",
"url": "wss://mcp.example.com/ws",
"headers": {
"Authorization": "Bearer ${TOKEN}"
}
}
}Use cases:
- Real-time data streaming
- Persistent connections
- Push notifications from server
- Low-latency requirements
连接到WebSocket MCP服务器以实现实时双向通信。
配置:
json
{
"realtime-service": {
"type": "ws",
"url": "wss://mcp.example.com/ws",
"headers": {
"Authorization": "Bearer ${TOKEN}"
}
}
}适用场景:
- 实时数据流
- 持久连接
- 来自服务器的推送通知
- 低延迟需求
Environment Variable Expansion
环境变量展开
All MCP configurations support environment variable substitution:
${CLAUDE_PLUGIN_ROOT} - Plugin directory (always use for portability):
json
{
"command": "${CLAUDE_PLUGIN_ROOT}/servers/my-server"
}User environment variables - From user's shell:
json
{
"env": {
"API_KEY": "${MY_API_KEY}",
"DATABASE_URL": "${DB_URL}"
}
}Best practice: Document all required environment variables in plugin README.
所有MCP配置都支持环境变量替换:
${CLAUDE_PLUGIN_ROOT} - 插件目录(为了可移植性请始终使用):
json
{
"command": "${CLAUDE_PLUGIN_ROOT}/servers/my-server"
}用户环境变量 - 来自用户的shell:
json
{
"env": {
"API_KEY": "${MY_API_KEY}",
"DATABASE_URL": "${DB_URL}"
}
}最佳实践: 在插件README中记录所有必需的环境变量。
MCP Tool Naming
MCP工具命名
When MCP servers provide tools, they're automatically prefixed:
Format:
mcp__plugin_<plugin-name>_<server-name>__<tool-name>Example:
- Plugin:
asana - Server:
asana - Tool:
create_task - Full name:
mcp__plugin_asana_asana__asana_create_task
当MCP服务器提供工具时,它们会自动添加前缀:
格式:
mcp__plugin_<plugin-name>_<server-name>__<tool-name>示例:
- 插件:
asana - 服务器:
asana - 工具:
create_task - 全名:
mcp__plugin_asana_asana__asana_create_task
Using MCP Tools in Commands
在命令中使用MCP工具
Pre-allow specific MCP tools in command frontmatter:
markdown
---
allowed-tools: [
"mcp__plugin_asana_asana__asana_create_task",
"mcp__plugin_asana_asana__asana_search_tasks"
]
---Wildcard (use sparingly):
markdown
---
allowed-tools: ["mcp__plugin_asana_asana__*"]
---Best practice: Pre-allow specific tools, not wildcards, for security.
在命令前置元数据中预先允许特定MCP工具:
markdown
---
allowed-tools: [
"mcp__plugin_asana_asana__asana_create_task",
"mcp__plugin_asana_asana__asana_search_tasks"
]
---通配符(谨慎使用):
markdown
---
allowed-tools: ["mcp__plugin_asana_asana__*"]
---最佳实践: 为了安全,预先允许特定工具,而非使用通配符。
Lifecycle Management
生命周期管理
Automatic startup:
- MCP servers start when plugin enables
- Connection established before first tool use
- Restart required for configuration changes
Lifecycle:
- Plugin loads
- MCP configuration parsed
- Server process started (stdio) or connection established (SSE/HTTP/WS)
- Tools discovered and registered
- Tools available as
mcp__plugin_...__...
Viewing servers:
Use command to see all servers including plugin-provided ones.
/mcp自动启动:
- MCP服务器在插件启用时启动
- 在首次使用工具前建立连接
- 配置更改后需要重启
生命周期:
- 插件加载
- 解析MCP配置
- 启动服务器进程(stdio)或建立连接(SSE/HTTP/WS)
- 发现并注册工具
- 工具以形式可用
mcp__plugin_...__...
查看服务器:
使用命令查看所有服务器,包括插件提供的服务器。
/mcpAuthentication Patterns
认证模式
OAuth (SSE/HTTP)
OAuth(SSE/HTTP)
OAuth handled automatically by Claude Code:
json
{
"type": "sse",
"url": "https://mcp.example.com/sse"
}User authenticates in browser on first use. No additional configuration needed.
OAuth由Claude Code自动处理:
json
{
"type": "sse",
"url": "https://mcp.example.com/sse"
}用户在首次使用时在浏览器中认证。无需额外配置。
Token-Based (Headers)
基于令牌(Headers)
Static or environment variable tokens:
json
{
"type": "http",
"url": "https://api.example.com",
"headers": {
"Authorization": "Bearer ${API_TOKEN}"
}
}Document required environment variables in README.
静态或环境变量令牌:
json
{
"type": "http",
"url": "https://api.example.com",
"headers": {
"Authorization": "Bearer ${API_TOKEN}"
}
}在README中记录必需的环境变量。
Environment Variables (stdio)
环境变量(stdio)
Pass configuration to MCP server:
json
{
"command": "python",
"args": ["-m", "my_mcp_server"],
"env": {
"DATABASE_URL": "${DB_URL}",
"API_KEY": "${API_KEY}",
"LOG_LEVEL": "info"
}
}将配置传递给MCP服务器:
json
{
"command": "python",
"args": ["-m", "my_mcp_server"],
"env": {
"DATABASE_URL": "${DB_URL}",
"API_KEY": "${API_KEY}",
"LOG_LEVEL": "info"
}
}Integration Patterns
集成模式
Pattern 1: Simple Tool Wrapper
模式1:简单工具包装器
Commands use MCP tools with user interaction:
markdown
undefined命令通过用户交互使用MCP工具:
markdown
undefinedCommand: create-item.md
Command: create-item.md
allowed-tools: ["mcp__plugin_name_server__create_item"]
Steps:
- Gather item details from user
- Use mcp__plugin_name_server__create_item
- Confirm creation
**Use for:** Adding validation or preprocessing before MCP calls.allowed-tools: ["mcp__plugin_name_server__create_item"]
步骤:
- 从用户处收集项目详情
- 使用mcp__plugin_name_server__create_item
- 确认创建
**用途:** 在调用MCP之前添加验证或预处理。Pattern 2: Autonomous Agent
模式2:自主Agent
Agents use MCP tools autonomously:
markdown
undefinedAgent自主使用MCP工具:
markdown
undefinedAgent: data-analyzer.md
Agent: data-analyzer.md
Analysis Process:
- Query data via mcp__plugin_db_server__query
- Process and analyze results
- Generate insights report
**Use for:** Multi-step MCP workflows without user interaction.分析流程:
- 通过mcp__plugin_db_server__query查询数据
- 处理并分析结果
- 生成洞察报告
**用途:** 无需用户交互的多步骤MCP工作流。Pattern 3: Multi-Server Plugin
模式3:多服务器插件
Integrate multiple MCP servers:
json
{
"github": {
"type": "sse",
"url": "https://mcp.github.com/sse"
},
"jira": {
"type": "sse",
"url": "https://mcp.jira.com/sse"
}
}Use for: Workflows spanning multiple services.
集成多个MCP服务器:
json
{
"github": {
"type": "sse",
"url": "https://mcp.github.com/sse"
},
"jira": {
"type": "sse",
"url": "https://mcp.jira.com/sse"
}
}用途: 跨多个服务的工作流。
Security Best Practices
安全最佳实践
Use HTTPS/WSS
使用HTTPS/WSS
Always use secure connections:
json
✅ "url": "https://mcp.example.com/sse"
❌ "url": "http://mcp.example.com/sse"始终使用安全连接:
json
✅ "url": "https://mcp.example.com/sse"
❌ "url": "http://mcp.example.com/sse"Token Management
令牌管理
DO:
- ✅ Use environment variables for tokens
- ✅ Document required env vars in README
- ✅ Let OAuth flow handle authentication
DON'T:
- ❌ Hardcode tokens in configuration
- ❌ Commit tokens to git
- ❌ Share tokens in documentation
建议:
- ✅ 使用环境变量存储令牌
- ✅ 在README中记录必需的环境变量
- ✅ 让OAuth流处理认证
禁止:
- ❌ 在配置中硬编码令牌
- ❌ 将令牌提交到git
- ❌ 在文档中共享令牌
Permission Scoping
权限范围
Pre-allow only necessary MCP tools:
markdown
✅ allowed-tools: [
"mcp__plugin_api_server__read_data",
"mcp__plugin_api_server__create_item"
]
❌ allowed-tools: ["mcp__plugin_api_server__*"]预先仅允许必要的MCP工具:
markdown
✅ allowed-tools: [
"mcp__plugin_api_server__read_data",
"mcp__plugin_api_server__create_item"
]
❌ allowed-tools: ["mcp__plugin_api_server__*"]Error Handling
错误处理
Connection Failures
连接失败
Handle MCP server unavailability:
- Provide fallback behavior in commands
- Inform user of connection issues
- Check server URL and configuration
处理MCP服务器不可用的情况:
- 在命令中提供回退行为
- 通知用户连接问题
- 检查服务器URL和配置
Tool Call Errors
工具调用错误
Handle failed MCP operations:
- Validate inputs before calling MCP tools
- Provide clear error messages
- Check rate limiting and quotas
处理失败的MCP操作:
- 在调用MCP工具前验证输入
- 提供清晰的错误消息
- 检查速率限制和配额
Configuration Errors
配置错误
Validate MCP configuration:
- Test server connectivity during development
- Validate JSON syntax
- Check required environment variables
验证MCP配置:
- 在开发期间测试服务器连接
- 验证JSON语法
- 检查必需的环境变量
Performance Considerations
性能考虑
Lazy Loading
延迟加载
MCP servers connect on-demand:
- Not all servers connect at startup
- First tool use triggers connection
- Connection pooling managed automatically
MCP服务器按需连接:
- 并非所有服务器在启动时都连接
- 首次使用工具时触发连接
- 连接池自动管理
Batching
批处理
Batch similar requests when possible:
undefined尽可能批量处理相似请求:
undefinedGood: Single query with filters
推荐:带过滤器的单次查询
tasks = search_tasks(project="X", assignee="me", limit=50)
tasks = search_tasks(project="X", assignee="me", limit=50)
Avoid: Many individual queries
避免:多次单独查询
for id in task_ids:
task = get_task(id)
undefinedfor id in task_ids:
task = get_task(id)
undefinedTesting MCP Integration
测试MCP集成
Local Testing
本地测试
- Configure MCP server in
.mcp.json - Install plugin locally ()
.claude-plugin/ - Run to verify server appears
/mcp - Test tool calls in commands
- Check logs for connection issues
claude --debug
- 在中配置MCP服务器
.mcp.json - 本地安装插件()
.claude-plugin/ - 运行验证服务器是否出现
/mcp - 在命令中测试工具调用
- 查看日志排查连接问题
claude --debug
Validation Checklist
验证清单
- MCP configuration is valid JSON
- Server URL is correct and accessible
- Required environment variables documented
- Tools appear in output
/mcp - Authentication works (OAuth or tokens)
- Tool calls succeed from commands
- Error cases handled gracefully
- MCP配置是有效的JSON
- 服务器URL正确且可访问
- 必需的环境变量已记录
- 工具出现在输出中
/mcp - 认证正常工作(OAuth或令牌)
- 从命令调用工具成功
- 错误情况已妥善处理
Debugging
调试
Enable Debug Logging
启用调试日志
bash
claude --debugLook for:
- MCP server connection attempts
- Tool discovery logs
- Authentication flows
- Tool call errors
bash
claude --debug查找以下内容:
- MCP服务器连接尝试
- 工具发现日志
- 认证流程
- 工具调用错误
Common Issues
常见问题
Server not connecting:
- Check URL is correct
- Verify server is running (stdio)
- Check network connectivity
- Review authentication configuration
Tools not available:
- Verify server connected successfully
- Check tool names match exactly
- Run to see available tools
/mcp - Restart Claude Code after config changes
Authentication failing:
- Clear cached auth tokens
- Re-authenticate
- Check token scopes and permissions
- Verify environment variables set
服务器无法连接:
- 检查URL是否正确
- 验证服务器是否在运行(stdio)
- 检查网络连接
- 查看认证配置
工具不可用:
- 验证服务器是否成功连接
- 检查工具名称是否完全匹配
- 运行查看可用工具
/mcp - 配置更改后重启Claude Code
认证失败:
- 清除缓存的认证令牌
- 重新认证
- 检查令牌范围和权限
- 验证环境变量是否设置
Quick Reference
快速参考
MCP Server Types
MCP服务器类型
| Type | Transport | Best For | Auth |
|---|---|---|---|
| stdio | Process | Local tools, custom servers | Env vars |
| SSE | HTTP | Hosted services, cloud APIs | OAuth |
| HTTP | REST | API backends, token auth | Tokens |
| ws | WebSocket | Real-time, streaming | Tokens |
| 类型 | 传输方式 | 最佳适用场景 | 认证方式 |
|---|---|---|---|
| stdio | 进程 | 本地工具、自定义服务器 | 环境变量 |
| SSE | HTTP | 托管服务、云API | OAuth |
| HTTP | REST | API后端、令牌认证 | 令牌 |
| ws | WebSocket | 实时、流处理 | 令牌 |
Configuration Checklist
配置清单
- Server type specified (stdio/SSE/HTTP/ws)
- Type-specific fields complete (command or url)
- Authentication configured
- Environment variables documented
- HTTPS/WSS used (not HTTP/WS)
- ${CLAUDE_PLUGIN_ROOT} used for paths
- 指定了服务器类型(stdio/SSE/HTTP/ws)
- 完成了类型特定字段(command或url)
- 配置了认证
- 记录了环境变量
- 使用了HTTPS/WSS(而非HTTP/WS)
- 路径使用了${CLAUDE_PLUGIN_ROOT}
Best Practices
最佳实践
DO:
- ✅ Use ${CLAUDE_PLUGIN_ROOT} for portable paths
- ✅ Document required environment variables
- ✅ Use secure connections (HTTPS/WSS)
- ✅ Pre-allow specific MCP tools in commands
- ✅ Test MCP integration before publishing
- ✅ Handle connection and tool errors gracefully
DON'T:
- ❌ Hardcode absolute paths
- ❌ Commit credentials to git
- ❌ Use HTTP instead of HTTPS
- ❌ Pre-allow all tools with wildcards
- ❌ Skip error handling
- ❌ Forget to document setup
建议:
- ✅ 使用${CLAUDE_PLUGIN_ROOT}实现可移植路径
- ✅ 在README中记录必需的环境变量
- ✅ 使用安全连接(HTTPS/WSS)
- ✅ 在命令中预先允许特定MCP工具
- ✅ 发布前测试MCP集成
- ✅ 妥善处理连接和工具错误
禁止:
- ❌ 硬编码绝对路径
- ❌ 将凭据提交到git
- ❌ 使用HTTP而非HTTPS
- ❌ 使用通配符预先允许所有工具
- ❌ 跳过错误处理
- ❌ 忘记在README中记录设置
Additional Resources
附加资源
Reference Files
参考文件
For detailed information, consult:
- - Deep dive on each server type
references/server-types.md - - Authentication patterns and OAuth
references/authentication.md - - Using MCP tools in commands and agents
references/tool-usage.md
如需详细信息,请查阅:
- - 每种服务器类型的深入介绍
references/server-types.md - - 认证模式和OAuth
references/authentication.md - - 在命令和Agent中使用MCP工具
references/tool-usage.md
Example Configurations
示例配置
Working examples in :
examples/- - Local stdio MCP server
stdio-server.json - - Hosted SSE server with OAuth
sse-server.json - - REST API with token auth
http-server.json
examples/- - 本地stdio MCP服务器
stdio-server.json - - 带OAuth的托管SSE服务器
sse-server.json - - 带令牌认证的REST API
http-server.json
External Resources
外部资源
- Official MCP Docs: https://modelcontextprotocol.io/
- Claude Code MCP Docs: https://docs.claude.com/en/docs/claude-code/mcp
- MCP SDK: @modelcontextprotocol/sdk
- Testing: Use and
claude --debugcommand/mcp
- 官方MCP文档:https://modelcontextprotocol.io/
- Claude Code MCP文档:https://docs.claude.com/en/docs/claude-code/mcp
- MCP SDK:@modelcontextprotocol/sdk
- 测试:使用和
claude --debug命令/mcp
Implementation Workflow
实施工作流
To add MCP integration to a plugin:
- Choose MCP server type (stdio, SSE, HTTP, ws)
- Create at plugin root with configuration
.mcp.json - Use ${CLAUDE_PLUGIN_ROOT} for all file references
- Document required environment variables in README
- Test locally with command
/mcp - Pre-allow MCP tools in relevant commands
- Handle authentication (OAuth or tokens)
- Test error cases (connection failures, auth errors)
- Document MCP integration in plugin README
Focus on stdio for custom/local servers, SSE for hosted services with OAuth.
要为插件添加MCP集成:
- 选择MCP服务器类型(stdio、SSE、HTTP、ws)
- 在插件根目录创建并配置
.mcp.json - 所有文件引用使用${CLAUDE_PLUGIN_ROOT}
- 在README中记录必需的环境变量
- 使用命令本地测试
/mcp - 在相关命令中预先允许MCP工具
- 处理认证(OAuth或令牌)
- 测试错误情况(连接失败、认证错误)
- 在插件README中记录MCP集成
对于自定义/本地服务器重点使用stdio,对于带OAuth的托管服务重点使用SSE。