构建 MCP 服务器
一句话
构建MCP服务器以连接Claude/IDE与外部工具,提供工具、资源和提示功能。
什么时候翻这页
当你需要创建自己的MCP服务器,将外部服务或数据源集成到Claude或支持MCP的客户端时。
核心概念
- MCP服务器提供三种主要能力:
- Resources:可被客户端读取的类文件数据(如API响应或文件内容)
- Tools:可被LLM调用的函数(需用户批准)
- Prompts:帮助用户完成特定任务的预编写模板
- 本教程主要关注工具的实现
- 服务器可通过STDIO或HTTP协议与客户端通信
怎么做
-
环境准备:
- Python: 安装Python 3.10+和MCP SDK 1.2.0+
- TypeScript: 安装Node.js 16+和TypeScript
- Java: 使用Spring AI MCP自动配置和启动器
- Rust: 使用MCP SDK
- Go: 使用MCP Go SDK
-
实现工具:
- 导入必要的包和设置服务器实例
- 创建辅助函数处理API请求和数据格式化
- 实现工具执行逻辑
- 注册工具到服务器
-
运行服务器:
- Python: 使用
mcp.run(transport="stdio") - TypeScript: 使用
StdioServerTransport - Java: 使用
@SpringBootApplication和@McpServer - Rust: 使用
#[tool_router]和#[tool_handler]宏 - Go: 使用
mcp.NewServer和mcp.Run
- Python: 使用
-
连接到Claude for Desktop:
- 配置
claude_desktop_config.json文件 - 添加
mcpServers部分,指定服务器命令和参数 - 重启Claude for Desktop
- 配置
命令 / 配置速查
Python环境设置:
curl -LsSf https://astral.sh/uv/install.sh | sh # macOS/Linux
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # Windows
uv init weather
cd weather
uv venv
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows
uv add "mcp[cli]" httpx
TypeScript项目设置:
mkdir weather
cd weather
npm init -y
npm install @modelcontextprotocol/sdk zod@3
npm install -D @types/node typescript
Claude for Desktop配置:
{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
"run",
"weather.py"
]
}
}
}
与 Claude Code / Hello-Agents 的联系
- 与Claude Code手册中的MCP章节相关,但更专注于服务器端实现
- 与Hello-Agents第10章(Agent技能)相关,因为MCP服务器可以作为Agent技能的基础
初学者易错点
- STDIO服务器日志记录:不要使用
print()或console.log(),它们会写入stdout并破坏JSON-RPC消息- Python: 使用
print(..., file=sys.stderr)或logging模块 - TypeScript: 使用
console.error() - Go: 使用
log.Println()或fmt.Fprintln(os.Stderr, ...)
- Python: 使用
- 路径问题:在配置文件中使用绝对路径,而非相对路径
- 重启问题:必须完全退出并重新启动Claude for Desktop才能应用配置更改