tutorial15 min read
如何用 Python 构建 MCP 服务器(分步教程)
使用 FastMCP 用 Python 构建 MCP 服务器。涵盖工具、资源、提示词、MCP Inspector 测试,以及 Claude Code/Desktop/Cursor 配置。
WI
William Wang · Apr 9, 2026
William Wang — TokRepo & GEOScore AI 创始人,专注 AI 开发者工具和搜索可见性。
学习如何使用官方 FastMCP SDK 用 Python 构建生产级 MCP 服务器,用 MCP Inspector 测试,并在 Claude Code、Claude Desktop 和 Cursor 中配置。
前置条件
- Python 3.10+
uv包管理器(推荐)或pip- 基本 Python 知识
什么是 MCP?
模型上下文协议(MCP) 是 Anthropic 创建的开放标准,让你构建服务器向 LLM 应用暴露数据和功能。MCP 服务器提供三种能力:
- 工具(Tools) — LLM 可调用的函数
- 资源(Resources) — LLM 可访问的只读数据
- 提示词(Prompts) — 可复用的 LLM 交互模板
浏览 TokRepo 上的 MCP 服务器配置 查看已有资源。
步骤 1 — 搭建环境
curl -LsSf https://astral.sh/uv/install.sh | sh
uv init my-mcp-server && cd my-mcp-server
uv venv && source .venv/bin/activate
uv add "mcp[cli]"
touch server.py
步骤 2 — 创建基础服务器
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("my-first-server")
@mcp.tool()
def add(a: int, b: int) -> int:
"""将两个数字相加。"""
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""将两个数字相乘。"""
return a * b
if __name__ == "__main__":
mcp.run(transport="stdio")
FastMCP 利用 Python 类型提示和 docstring 自动生成工具 schema。@mcp.tool() 装饰器注册 MCP 工具。
步骤 3 — 添加资源
@mcp.resource("config://app-settings")
def get_settings() -> str:
"""返回应用设置。"""
return '{"theme": "dark", "language": "en"}'
步骤 4 — 完整示例:GitHub Stars 服务器
from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("github-stars")
async def github_request(path: str) -> dict[str, Any] | None:
async with httpx.AsyncClient() as client:
try:
response = await client.get(
f"https://api.github.com{path}",
headers={"Accept": "application/vnd.github.v3+json"},
timeout=30.0
)
response.raise_for_status()
return response.json()
except Exception:
return None
@mcp.tool()
async def get_repo_info(owner: str, repo: str) -> str:
"""获取 GitHub 仓库信息。"""
data = await github_request(f"/repos/{owner}/{repo}")
if not data:
return "获取失败。"
return f"仓库: {data['full_name']}\nStars: {data.get('stargazers_count', 0):,}"
if __name__ == "__main__":
mcp.run(transport="stdio")
步骤 5 — 用 MCP Inspector 测试
npx @modelcontextprotocol/inspector uv run server.py
在 http://localhost:6274 打开可视化调试界面。
步骤 6 — 配置到 Claude Code
claude mcp add --transport stdio my-server \
-- uv --directory /absolute/path/to/my-mcp-server run server.py
或创建 .mcp.json:
{
"mcpServers": {
"my-server": {
"command": "uv",
"args": ["--directory", "/path/to/server", "run", "server.py"]
}
}
}
重要:stdio 传输模式下绝对不要用 print(),会破坏 JSON-RPC 消息。用 print("msg", file=sys.stderr) 或 logging.info()。
FAQ
Q: MCP 需要什么 Python 版本? A: Python 3.10+。SDK 当前版本 v1.27.0。
Q: 可以用 pip 代替 uv 吗?
A: 可以。pip install "mcp[cli]" 即可。