mcp-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMCP Builder - Model Context Protocol Server Development
MCP构建指南 - Model Context Protocol服务器开发
What is MCP?
什么是MCP?
Model Context Protocol (MCP) is an open standard created by Anthropic that enables AI assistants like Claude to securely connect to external data sources and tools. Think of it as a universal adapter that allows Claude to interact with any system, API, or data source through a standardized interface.
Key Benefits:
- Standardization: One protocol for all integrations
- Security: Built-in authentication and permission controls
- Flexibility: Support for tools, resources, and prompts
- Scalability: Designed for production workloads
- Modularity: Create reusable MCP servers for different domains
Model Context Protocol(MCP)是由Anthropic推出的开放标准,可让Claude等AI助手安全连接到外部数据源和工具。可以将其视为一个通用适配器,允许Claude通过标准化接口与任何系统、API或数据源进行交互。
核心优势:
- 标准化:一套协议适配所有集成场景
- 安全性:内置身份验证和权限控制
- 灵活性:支持工具、资源和提示词
- 可扩展性:专为生产级负载设计
- 模块化:为不同领域创建可复用的MCP服务器
Architecture Overview
架构概述
MCP follows a client-server architecture:
┌─────────────┐ ┌─────────────┐ ┌──────────────┐
│ Claude │ ←──MCP──→ │ MCP Server │ ←──────→ │ External API │
│ (Client) │ │ (Your Code) │ │ Database │
└─────────────┘ └─────────────┘ └──────────────┘Components:
- Client: Claude Desktop, Claude Code, or custom applications
- Server: Your MCP implementation (Python, TypeScript, etc.)
- Transport: Communication channel (stdio, HTTP, SSE)
- Protocol: Standardized message format (JSON-RPC 2.0)
For detailed protocol specification, see Protocol Specification Reference.
MCP采用客户端-服务器架构:
┌─────────────┐ ┌─────────────┐ ┌──────────────┐
│ Claude │ ←──MCP──→ │ MCP Server │ ←──────→ │ External API │
│ (Client) │ │ (Your Code) │ │ Database │
└─────────────┘ └─────────────┘ └──────────────┘组件说明:
- 客户端:Claude Desktop、Claude Code或自定义应用程序
- 服务器:你的MCP实现(Python、TypeScript等)
- 传输层:通信通道(stdio、HTTP、SSE)
- 协议:标准化消息格式(JSON-RPC 2.0)
如需详细协议规范,请查看协议规范参考。
Core Components
核心组件
1. Tools: Exposing Functions Claude Can Call
1. 工具:开放Claude可调用的函数
Tools are the primary way to give Claude new capabilities. Each tool is a function that Claude can invoke with specific arguments.
Tool Definition Structure:
python
{
"name": "tool_name",
"description": "Clear description of what this tool does",
"inputSchema": {
"type": "object",
"properties": {
"param1": {
"type": "string",
"description": "Description of parameter"
}
},
"required": ["param1"]
}
}Key Principles:
- Clear naming: Use descriptive, action-oriented names (e.g., , not
search_database)db_query - Comprehensive descriptions: Explain what the tool does, when to use it, and what it returns
- Strong schemas: Use JSON Schema to validate inputs and guide Claude
- Error handling: Return clear error messages when things go wrong
For complete schema design patterns and best practices, see Tool Schema Reference.
工具是为Claude赋予新能力的主要方式。每个工具都是Claude可以调用的带参函数。
工具定义结构:
python
{
"name": "tool_name",
"description": "Clear description of what this tool does",
"inputSchema": {
"type": "object",
"properties": {
"param1": {
"type": "string",
"description": "Description of parameter"
}
},
"required": ["param1"]
}
}核心原则:
- 清晰命名:使用描述性、面向动作的名称(例如,而非
search_database)db_query - 全面描述:说明工具功能、适用场景和返回结果
- 强模式校验:使用JSON Schema验证输入并引导Claude
- 错误处理:出现问题时返回明确的错误信息
完整的模式设计模式和最佳实践,请查看工具模式参考。
2. Resources: Providing Data/Documentation Access
2. 资源:提供数据/文档访问能力
Resources allow Claude to access files, documentation, or structured data. Unlike tools (which perform actions), resources provide information.
Resource Types:
- Static: Fixed content (e.g., documentation files)
- Dynamic: Generated on-demand (e.g., database queries)
- Templates: Parameterized resources (e.g., user profiles)
Resource URI Patterns:
file:///path/to/file.txt # Local file
http://example.com/api/docs # HTTP resource
custom://database/users/123 # Custom scheme
template://report/{user_id} # Template resource资源允许Claude访问文件、文档或结构化数据。与工具(执行操作)不同,资源用于提供信息。
资源类型:
- 静态资源:固定内容(例如文档文件)
- 动态资源:按需生成(例如数据库查询结果)
- 模板资源:参数化资源(例如用户配置文件)
资源URI模式:
file:///path/to/file.txt # 本地文件
http://example.com/api/docs # HTTP资源
custom://database/users/123 # 自定义协议
template://report/{user_id} # 模板资源3. Prompts: Reusable Prompt Templates
3. 提示词:可复用的提示模板
Prompts are pre-defined message templates that users can invoke. They help standardize common workflows and best practices.
Prompt Definition:
python
{
"name": "code_review",
"description": "Comprehensive code review checklist",
"arguments": [
{
"name": "language",
"description": "Programming language",
"required": True
}
]
}提示词是用户可以调用的预定义消息模板,有助于标准化常见工作流和最佳实践。
提示词定义:
python
{
"name": "code_review",
"description": "Comprehensive code review checklist",
"arguments": [
{
"name": "language",
"description": "Programming language",
"required": True
}
]
}4. Authentication Methods
4. 身份验证方法
MCP supports multiple authentication methods:
- No Authentication (development only)
- API Key Authentication (simple, medium security)
- OAuth 2.0 (third-party, high security)
- Bearer Token (API-to-API, high security)
For complete security implementation guides, see Security Best Practices.
MCP支持多种身份验证方法:
- 无身份验证(仅适用于开发环境)
- API密钥验证(简单,中等安全性)
- OAuth 2.0(第三方集成,高安全性)
- Bearer Token(API间调用,高安全性)
完整的安全实现指南,请查看安全最佳实践。
Server Implementation Workflow
服务器实现流程
Phase 1: Project Setup
阶段1:项目搭建
Create your MCP server project:
bash
undefined创建你的MCP服务器项目:
bash
undefinedCreate project directory
Create project directory
mkdir my-mcp-server
cd my-mcp-server
mkdir my-mcp-server
cd my-mcp-server
Initialize Python project
Initialize Python project
uv init
uv add mcp
uv init
uv add mcp
Create server file
Create server file
touch server.py
undefinedtouch server.py
undefinedPhase 2: Basic Server Structure
阶段2:基础服务器结构
Minimal working server:
python
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import asyncio
app = Server("my-mcp-server")
@app.list_tools()
async def list_tools():
return [
Tool(
name="my_tool",
description="Description of what this tool does",
inputSchema={
"type": "object",
"properties": {
"param": {"type": "string"}
},
"required": ["param"]
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "my_tool":
param = arguments["param"]
result = f"Processed: {param}"
return [TextContent(type="text", text=result)]
async def main():
async with stdio_server() as (read_stream, write_stream):
await app.run(read_stream, write_stream, app.create_initialization_options())
if __name__ == "__main__":
asyncio.run(main())最简可用服务器:
python
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import asyncio
app = Server("my-mcp-server")
@app.list_tools()
async def list_tools():
return [
Tool(
name="my_tool",
description="Description of what this tool does",
inputSchema={
"type": "object",
"properties": {
"param": {"type": "string"}
},
"required": ["param"]
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "my_tool":
param = arguments["param"]
result = f"Processed: {param}"
return [TextContent(type="text", text=result)]
async def main():
async with stdio_server() as (read_stream, write_stream):
await app.run(read_stream, write_stream, app.create_initialization_options())
if __name__ == "__main__":
asyncio.run(main())Phase 3: Tool Registration and Handlers
阶段3:工具注册与处理程序
Registration Pattern:
python
@app.list_tools()
async def list_tools():
return [
Tool(
name="calculator_add",
description="Add two numbers",
inputSchema={
"type": "object",
"properties": {
"a": {"type": "number", "description": "First number"},
"b": {"type": "number", "description": "Second number"}
},
"required": ["a", "b"]
}
)
]Handler Pattern:
python
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "calculator_add":
return await handle_calculator_add(arguments)
else:
raise ValueError(f"Unknown tool: {name}")
async def handle_calculator_add(arguments: dict):
a = arguments["a"]
b = arguments["b"]
result = a + b
return [TextContent(type="text", text=f"{a} + {b} = {result}")]注册模式:
python
@app.list_tools()
async def list_tools():
return [
Tool(
name="calculator_add",
description="Add two numbers",
inputSchema={
"type": "object",
"properties": {
"a": {"type": "number", "description": "First number"},
"b": {"type": "number", "description": "Second number"}
},
"required": ["a", "b"]
}
)
]处理程序模式:
python
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "calculator_add":
return await handle_calculator_add(arguments)
else:
raise ValueError(f"Unknown tool: {name}")
async def handle_calculator_add(arguments: dict):
a = arguments["a"]
b = arguments["b"]
result = a + b
return [TextContent(type="text", text=f"{a} + {b} = {result}")]Phase 4: Resource Implementation
阶段4:资源实现
Static and dynamic resource examples:
python
from mcp.types import Resource, ResourceContents, TextResourceContents
@app.list_resources()
async def list_resources():
return [Resource(uri="file:///docs/readme.md", name="README",
description="Documentation", mimeType="text/markdown")]
@app.read_resource()
async def read_resource(uri: str):
if uri.startswith("file://"):
with open(uri[7:], 'r') as f:
return ResourceContents(contents=[TextResourceContents(
uri=uri, mimeType="text/markdown", text=f.read())])See Resource Server Example for complete implementation.
静态与动态资源示例:
python
from mcp.types import Resource, ResourceContents, TextResourceContents
@app.list_resources()
async def list_resources():
return [Resource(uri="file:///docs/readme.md", name="README",
description="Documentation", mimeType="text/markdown")]
@app.read_resource()
async def read_resource(uri: str):
if uri.startswith("file://"):
with open(uri[7:], 'r') as f:
return ResourceContents(contents=[TextResourceContents(
uri=uri, mimeType="text/markdown", text=f.read())])完整实现请查看资源服务器示例。
Phase 5: Error Handling and Testing
阶段5:错误处理与测试
Error Response Pattern:
python
async def call_tool(name: str, arguments: dict):
try:
return [TextContent(type="text", text=await execute_tool(name, arguments))]
except ValueError as e:
return [TextContent(type="text", text=f"Invalid input: {str(e)}", isError=True)]
except Exception as e:
logger.exception("Unexpected error")
return [TextContent(type="text", text=f"Error: {type(e).__name__}", isError=True)]Testing:
bash
undefined错误响应模式:
python
async def call_tool(name: str, arguments: dict):
try:
return [TextContent(type="text", text=await execute_tool(name, arguments))]
except ValueError as e:
return [TextContent(type="text", text=f"Invalid input: {str(e)}", isError=True)]
except Exception as e:
logger.exception("Unexpected error")
return [TextContent(type="text", text=f"Error: {type(e).__name__}", isError=True)]测试方法:
bash
undefinedTest with MCP inspector
Test with MCP inspector
npx @modelcontextprotocol/inspector python server.py
See [Testing and Debugging Guide](./references/testing-debugging.md) for comprehensive strategies.npx @modelcontextprotocol/inspector python server.py
全面的测试与调试策略,请查看[测试与调试指南](./references/testing-debugging.md)。Phase 6: Claude Desktop Integration
阶段6:Claude Desktop集成
Configuration: Edit :
claude_desktop_config.json- macOS:
~/Library/Application Support/Claude/ - Windows:
%APPDATA%\Claude/ - Linux:
~/.config/Claude/
json
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["/absolute/path/to/server.py"],
"env": {"API_KEY": "your-key"}
}
}
}配置步骤: 编辑:
claude_desktop_config.json- macOS:
~/Library/Application Support/Claude/ - Windows:
%APPDATA%\Claude/ - Linux:
~/.config/Claude/
json
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["/absolute/path/to/server.py"],
"env": {"API_KEY": "your-key"}
}
}
}Best Practices
最佳实践
Tool Schema Design
工具模式设计
Use descriptive names:
python
undefined使用描述性名称:
python
undefined✅ Good
✅ Good
"search_customer_by_email"
"calculate_shipping_cost"
"search_customer_by_email"
"calculate_shipping_cost"
❌ Bad
❌ Bad
"search"
"calc"
**Provide comprehensive descriptions:**
```python"search"
"calc"
**提供全面描述:**
```python✅ Good
✅ Good
description="""
Search for customers by email address. Returns customer profile including:
- Contact information
- Order history
- Account status """
description="""
Search for customers by email address. Returns customer profile including:
- Contact information
- Order history
- Account status """
❌ Bad
❌ Bad
description="Search customers"
**Use enums for fixed options:**
```pythondescription="Search customers"
**为固定选项使用枚举:**
```python✅ Good
✅ Good
"status": {
"type": "string",
"enum": ["pending", "approved", "rejected"],
"description": "Application status"
}
undefined"status": {
"type": "string",
"enum": ["pending", "approved", "rejected"],
"description": "Application status"
}
undefinedError Handling Strategies
错误处理策略
Categorize errors with custom exceptions and provide actionable messages:
python
class ValidationError(Exception): pass
class AuthenticationError(Exception): pass
async def call_tool(name: str, arguments: dict):
try:
return await execute_tool(name, arguments)
except ValidationError as e:
return [TextContent(type="text", text=f"Invalid input: {str(e)}", isError=True)]使用自定义异常对错误分类,并提供可操作的提示信息:
python
class ValidationError(Exception): pass
class AuthenticationError(Exception): pass
async def call_tool(name: str, arguments: dict):
try:
return await execute_tool(name, arguments)
except ValidationError as e:
return [TextContent(type="text", text=f"Invalid input: {str(e)}", isError=True)]Security Considerations
安全注意事项
Always validate inputs and use environment variables for secrets:
python
undefined始终验证输入,并使用环境变量存储敏感信息:
python
undefinedInput validation
Input validation
def validate_url(url: str) -> bool:
if urlparse(url).scheme not in ['http', 'https']:
raise ValidationError("Only HTTP/HTTPS URLs allowed")
def validate_url(url: str) -> bool:
if urlparse(url).scheme not in ['http', 'https']:
raise ValidationError("Only HTTP/HTTPS URLs allowed")
Secrets management
Secrets management
API_KEY = os.getenv("API_KEY") # ✅ Good
API_KEY = os.getenv("API_KEY") # ✅ Good
API_KEY = "sk-1234" # ❌ Bad - Never hardcode!
API_KEY = "sk-1234" # ❌ Bad - Never hardcode!
undefinedundefinedPerformance Optimization
性能优化
Use connection pooling and parallel async operations:
python
undefined使用连接池和并行异步操作:
python
undefined✅ Parallel execution
✅ Parallel execution
results = await asyncio.gather(*[fetch_user_data(uid) for uid in user_ids])
results = await asyncio.gather(*[fetch_user_data(uid) for uid in user_ids])
❌ Sequential execution (slow)
❌ Sequential execution (slow)
for user_id in user_ids:
result = await fetch_user_data(user_id)
undefinedfor user_id in user_ids:
result = await fetch_user_data(user_id)
undefinedCommon Pitfalls
常见陷阱
Schema Validation Errors
模式验证错误
Missing required validation:
python
undefined缺少必填项验证:
python
undefined❌ Bad: No validation
❌ Bad: No validation
async def handle_create_user(arguments: dict):
username = arguments["username"] # Will crash if missing!
async def handle_create_user(arguments: dict):
username = arguments["username"] # Will crash if missing!
✅ Good: Validate inputs
✅ Good: Validate inputs
async def handle_create_user(arguments: dict):
if "username" not in arguments:
return [TextContent(type="text", text="Error: username required", isError=True)]
username = arguments["username"]
undefinedasync def handle_create_user(arguments: dict):
if "username" not in arguments:
return [TextContent(type="text", text="Error: username required", isError=True)]
username = arguments["username"]
undefinedAuthentication Issues
身份验证问题
Insecure storage:
python
undefined不安全的存储方式:
python
undefined❌ Bad: Hardcoded API key
❌ Bad: Hardcoded API key
API_KEY = "sk-1234567890abcdef"
API_KEY = "sk-1234567890abcdef"
✅ Good: Environment variables
✅ Good: Environment variables
API_KEY = os.getenv("API_KEY")
if not API_KEY:
raise ValueError("API_KEY environment variable required")
undefinedAPI_KEY = os.getenv("API_KEY")
if not API_KEY:
raise ValueError("API_KEY environment variable required")
undefinedTransport Configuration
传输配置问题
Path issues:
python
undefined路径错误:
python
undefined❌ Bad: Relative path
❌ Bad: Relative path
{
"command": "python",
"args": ["server.py"] # Won't work!
}
{
"command": "python",
"args": ["server.py"] # Won't work!
}
✅ Good: Absolute path
✅ Good: Absolute path
{
"command": "python",
"args": ["/Users/username/projects/mcp-server/server.py"]
}
undefined{
"command": "python",
"args": ["/Users/username/projects/mcp-server/server.py"]
}
undefinedError Propagation
错误传播问题
Silent failures:
python
undefined静默失败:
python
undefined❌ Bad: Silent failure
❌ Bad: Silent failure
async def call_tool(name: str, arguments: dict):
try:
return await execute_tool(name, arguments)
except Exception:
return [TextContent(type="text", text="Something went wrong")]
async def call_tool(name: str, arguments: dict):
try:
return await execute_tool(name, arguments)
except Exception:
return [TextContent(type="text", text="Something went wrong")]
✅ Good: Descriptive errors
✅ Good: Descriptive errors
async def call_tool(name: str, arguments: dict):
try:
return await execute_tool(name, arguments)
except ValueError as e:
return [TextContent(type="text", text=f"Invalid input: {str(e)}", isError=True)]
except Exception as e:
logger.exception("Unexpected error")
return [TextContent(type="text", text=f"Error: {type(e).name}", isError=True)]
**Not marking errors:**
```pythonasync def call_tool(name: str, arguments: dict):
try:
return await execute_tool(name, arguments)
except ValueError as e:
return [TextContent(type="text", text=f"Invalid input: {str(e)}", isError=True)]
except Exception as e:
logger.exception("Unexpected error")
return [TextContent(type="text", text=f"Error: {type(e).name}", isError=True)]
**未标记错误:**
```python❌ Bad
❌ Bad
return [TextContent(type="text", text="Error: Failed")]
return [TextContent(type="text", text="Error: Failed")]
✅ Good
✅ Good
return [TextContent(type="text", text="Error: Failed", isError=True)]
undefinedreturn [TextContent(type="text", text="Error: Failed", isError=True)]
undefinedAdditional Resources
附加资源
Official Documentation
官方文档
- MCP Specification: https://modelcontextprotocol.io/
- Python SDK: https://github.com/modelcontextprotocol/python-sdk
- TypeScript SDK: https://github.com/modelcontextprotocol/typescript-sdk
- MCP规范:https://modelcontextprotocol.io/
- Python SDK:https://github.com/modelcontextprotocol/python-sdk
- TypeScript SDK:https://github.com/modelcontextprotocol/typescript-sdk
Detailed References
详细参考
- Protocol Specification - Complete protocol details, message formats, transport mechanisms
- Tool Schema Guide - Comprehensive schema patterns and validation
- Security Best Practices - Authentication, authorization, input validation, secrets management
- Testing and Debugging - Unit tests, integration tests, MCP inspector usage, debugging techniques
- Production Deployment - Production configuration, monitoring, scaling, Docker deployment
- 协议规范 - 完整的协议细节、消息格式、传输机制
- 工具模式指南 - 全面的模式设计和验证方法
- 安全最佳实践 - 身份验证、授权、输入验证、敏感信息管理
- 测试与调试 - 单元测试、集成测试、MCP Inspector使用、调试技巧
- 生产部署 - 生产环境配置、监控、扩容、Docker部署
Complete Examples
完整示例
- Simple Calculator Server - Basic arithmetic tools
- REST API Wrapper - GitHub API integration
- Database Server - Safe database query access
- Resource Server - Static and dynamic resources
- 简单计算器服务器 - 基础算术工具
- REST API封装 - GitHub API集成
- 数据库服务器 - 安全的数据库查询访问
- 资源服务器 - 静态与动态资源
Tools
工具
- MCP Inspector: https://github.com/modelcontextprotocol/inspector
- Claude Desktop: https://claude.ai/download
- MCP Inspector:https://github.com/modelcontextprotocol/inspector
- Claude Desktop:https://claude.ai/download
Quick Reference
快速参考
Server Template (Python)
服务器模板(Python)
python
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import asyncio
app = Server("my-server")
@app.list_tools()
async def list_tools():
return [Tool(name="my_tool", description="...", inputSchema={...})]
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "my_tool":
return [TextContent(type="text", text="Result")]
async def main():
async with stdio_server() as (read_stream, write_stream):
await app.run(read_stream, write_stream, app.create_initialization_options())
if __name__ == "__main__":
asyncio.run(main())python
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import asyncio
app = Server("my-server")
@app.list_tools()
async def list_tools():
return [Tool(name="my_tool", description="...", inputSchema={...})]
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "my_tool":
return [TextContent(type="text", text="Result")]
async def main():
async with stdio_server() as (read_stream, write_stream):
await app.run(read_stream, write_stream, app.create_initialization_options())
if __name__ == "__main__":
asyncio.run(main())Common Patterns
常见模式
Error handling:
python
return [TextContent(type="text", text="Error message", isError=True)]Async operations:
python
results = await asyncio.gather(*tasks)Input validation:
python
if "required_param" not in arguments:
return [TextContent(type="text", text="Missing parameter", isError=True)]End of MCP Builder Skill Guide
For complete working examples and detailed technical references, explore the and directories.
examples/references/错误处理:
python
return [TextContent(type="text", text="Error message", isError=True)]异步操作:
python
results = await asyncio.gather(*tasks)输入验证:
python
if "required_param" not in arguments:
return [TextContent(type="text", text="Missing parameter", isError=True)]MCP构建指南结束
如需完整的可运行示例和详细技术参考,请查看和目录。
examples/references/