MCP 环境配置
本章介绍如何搭建 MCP 开发环境,包括 SDK 安装、项目配置和客户端集成。
安装 MCP SDK
Python SDK
Python SDK 提供了两种使用方式:底层 Server 类和高级 FastMCP 类。
使用 pip 安装:
pip install mcp
使用 uv 安装(推荐,更快的包管理器):
# 安装 uv
curl -LsSf https://astral.sh/uv/install.sh | sh
# 创建项目
uv init my-mcp-server
cd my-mcp-server
uv venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# 安装 MCP SDK
uv add "mcp[cli]"
安装完成后验证:
import mcp
print(mcp.__version__)
系统要求:Python 3.10 或更高版本,MCP SDK 1.2.0 或更高版本。
TypeScript SDK
# 创建项目目录
mkdir my-mcp-server
cd my-mcp-server
# 初始化项目
npm init -y
# 安装 SDK
npm install @modelcontextprotocol/sdk zod
# 安装开发依赖
npm install -D @types/node typescript
配置 tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
},
"include": ["src/**/*"]
}
更新 package.json:
{
"type": "module",
"bin": {
"my-server": "./build/index.js"
},
"scripts": {
"build": "tsc"
}
}
创建 MCP 服务器
使用 FastMCP(Python 推荐)
FastMCP 是 Python SDK 提供的高级 API,可以快速创建 MCP 服务器:
# server.py
from mcp.server.fastmcp import FastMCP
# 创建服务器实例
mcp = FastMCP("my-server")
# 定义工具
@mcp.tool()
def calculate(expression: str) -> str:
"""计算数学表达式
Args:
expression: 数学表达式,如 '2 + 3 * 4'
"""
# 安全起见,使用简单的表达式解析
try:
result = eval(expression, {"__builtins__": {}}, {})
return f"结果: {result}"
except Exception as e:
return f"计算错误: {e}"
# 定义资源
@mcp.resource("config://settings")
def get_settings() -> str:
"""获取应用配置"""
import json
return json.dumps({"version": "1.0", "debug": False})
# 运行服务器
if __name__ == "__main__":
mcp.run()
FastMCP 会自动:
- 从函数签名生成 inputSchema
- 从文档字符串提取描述
- 处理服务器初始化和传输
使用底层 Server 类
需要更多控制时,可以使用底层 Server 类:
# server.py
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() -> list[Tool]:
return [
Tool(
name="echo",
description="返回输入的文本",
inputSchema={
"type": "object",
"properties": {
"text": {"type": "string", "description": "要返回的文本"}
},
"required": ["text"]
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict | None) -> list[TextContent]:
if name == "echo":
return [TextContent(type="text", text=arguments["text"])]
raise ValueError(f"Unknown tool: {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__":
asyncio.run(main())
TypeScript 服务器
// src/index.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "my-server",
version: "1.0.0"
});
// 定义工具
server.tool(
"echo",
{ text: z.string().describe("要返回的文本") },
async ({ text }) => ({
content: [{ type: "text", text }]
})
);
// 运行服务器
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Server running on stdio"); // 注意:使用 stderr
}
main().catch(console.error);
日志处理重要提醒
对于 STDIO 传输的服务器,日志输出有严格要求:
Python:
import sys
import logging
# ✅ 正确:输出到 stderr
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logging.info("Server started")
# ✅ 正确:print 到 stderr
print("Debug info", file=sys.stderr)
# ❌ 错误:stdout 用于 MCP 消息,写入会破坏协议
print("This will break MCP!")
TypeScript:
// ✅ 正确
console.error("Server started");
// ❌ 错误
console.log("This will break MCP!");
客户端配置
Claude Desktop 配置
找到 Claude Desktop 配置文件:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
添加服务器配置:
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["/absolute/path/to/server.py"]
},
"my-ts-server": {
"command": "node",
"args": ["/absolute/path/to/build/index.js"]
}
}
}
使用 uv 运行 Python 服务器:
{
"mcpServers": {
"my-server": {
"command": "uv",
"args": [
"--directory",
"/absolute/path/to/project",
"run",
"server.py"
]
}
}
}
VS Code 配置
在 .vscode/mcp.json 中配置:
{
"servers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
}
}
}
Cursor 配置
在 Cursor 设置中配置 MCP 服务器,路径类似 Claude Desktop。
官方参考服务器
MCP 提供了一系列官方参考服务器,可以直接使用:
| 服务器 | 功能 | 安装命令 |
|---|---|---|
| filesystem | 文件系统访问 | npx @modelcontextprotocol/server-filesystem /path |
| github | GitHub API 集成 | npx @modelcontextprotocol/server-github |
| postgres | PostgreSQL 数据库 | npx @modelcontextprotocol/server-postgres |
| sqlite | SQLite 数据库 | npx @modelcontextprotocol/server-sqlite |
| brave-search | Brave 搜索 | npx @modelcontextprotocol/server-brave-search |
使用示例:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"]
}
}
}
项目结构建议
my-mcp-server/
├── src/
│ ├── __init__.py
│ ├── server.py # 主服务器文件
│ ├── tools/ # 工具模块
│ │ ├── __init__.py
│ │ ├── file_ops.py
│ │ └── api_calls.py
│ └── resources/ # 资源模块
│ ├── __init__.py
│ └── config.py
├── tests/ # 测试文件
├── pyproject.toml # 项目配置
└── README.md
故障排除
服务器无法启动
- 检查 Python 版本:
python --version # 需要 3.10+
- 检查依赖安装:
pip list | grep mcp
- 手动运行服务器:
python server.py
# 观察是否有错误输出
连接失败
- 检查配置文件路径是否正确(使用绝对路径)
- 验证命令可执行:
which python
which uv
工具未显示
- 确认服务器已正确实现
list_tools - 使用 MCP Inspector 测试:
npx @modelcontextprotocol/inspector python server.py
协议错误
如果出现 JSON 解析错误,检查是否有代码写入 stdout。
下一步
完成环境配置后,继续学习: