名称: mcp-patterns 描述: “用于构建与Claude Code集成的模型上下文协议(MCP)服务器模式。触发词:mcp服务器、模型上下文协议、工具处理器、mcp资源、mcp工具。” 兼容性: “MCP服务器开发需要Python 3.10+或Node.js 18+。” 允许的工具: “读取 写入 Bash” 依赖项: [] 相关技能: [claude-code-hooks, claude-code-debug]
MCP 模式
用于构建与Claude Code集成的模型上下文协议(MCP)服务器模式。
基础MCP服务器(Python)
from mcp.server import Server
from mcp.server.stdio import stdio_server
app = Server("my-server")
@app.list_tools()
async def list_tools():
return [
{
"name": "my_tool",
"description": "执行有用的功能",
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "搜索查询"}
},
"required": ["query"]
}
}
]
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "my_tool":
result = await do_something(arguments["query"])
return {"content": [{"type": "text", "text": result}]}
raise ValueError(f"未知工具: {name}")
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__":
import asyncio
asyncio.run(main())
项目结构
my-mcp-server/
├── src/
│ └── my_server/
│ ├── __init__.py
│ ├── server.py # 主服务器逻辑
│ ├── tools.py # 工具处理器
│ └── resources.py # 资源处理器
├── pyproject.toml
└── README.md
Claude桌面配置
基础配置
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["-m", "my_server"],
"env": {
"MY_API_KEY": "your-key-here"
}
}
}
}
使用uv(推荐)
{
"mcpServers": {
"my-server": {
"command": "uv",
"args": ["run", "--directory", "/path/to/my-server", "python", "-m", "my_server"],
"env": {
"MY_API_KEY": "your-key-here"
}
}
}
}
快速参考
| 模式 | 使用场景 | 参考文档 |
|---|---|---|
| 工具验证 | 使用Pydantic进行输入净化 | ./references/tool-patterns.md |
| 错误处理 | 优雅的失败响应 | ./references/tool-patterns.md |
| 多工具 | CRUD风格的工具注册 | ./references/tool-patterns.md |
| 静态资源 | 配置/设置暴露 | ./references/resource-patterns.md |
| 动态资源 | 数据库支持资源 | ./references/resource-patterns.md |
| 环境认证 | 从环境变量获取API密钥 | ./references/auth-patterns.md |
| OAuth令牌 | 带TTL的令牌刷新 | ./references/auth-patterns.md |
| SQLite缓存 | 持久化状态存储 | ./references/state-patterns.md |
| 内存缓存 | 基于TTL的缓存 | ./references/state-patterns.md |
| 手动测试 | 快速验证脚本 | ./references/testing-patterns.md |
| pytest异步 | 工具单元测试 | ./references/testing-patterns.md |
常见问题
| 问题 | 解决方案 |
|---|---|
| 服务器无法启动 | 检查command路径,确保依赖已安装 |
| 工具未显示 | 验证list_tools()返回有效模式 |
| 认证失败 | 检查配置中环境变量是否设置,而非shell中 |
| 超时错误 | 为httpx调用添加超时,正确使用异步 |
| JSON解析错误 | 确保call_tool返回正确的内容结构 |
官方文档
- https://modelcontextprotocol.io - MCP规范
- https://modelcontextprotocol.io/docs/concepts/tools - 工具参考
- https://modelcontextprotocol.io/docs/concepts/resources - 资源参考
- https://github.com/modelcontextprotocol/python-sdk - Python SDK
- https://github.com/modelcontextprotocol/servers - 官方MCP服务器
附加资源
如需详细模式,请加载:
./references/tool-patterns.md- 验证、错误处理、多工具注册./references/resource-patterns.md- 静态和动态资源暴露./references/auth-patterns.md- 环境变量、OAuth令牌刷新./references/state-patterns.md- SQLite持久化、内存缓存./references/testing-patterns.md- 手动测试脚本、pytest异步模式