什么是 FastMCP?
FastMCP 是 Python 生态中类似于 FastAPI 的 MCP 开发框架。它大幅精简了底层 JSON-RPC 与生命周期通信协议,允许开发者通过标准的 Python 类型提示和装饰器编写 AI 工具。
1. 安装与环境准备
推荐使用 uv 快速管理 Python 依赖:
uv init fastmcp-demo && cd fastmcp-demo
uv add "mcp[cli]" httpx
2. 编写 FastMCP 脚本
创建 server.py:
from mcp.server.fastmcp import FastMCP
import httpx
# 初始化服务
mcp = FastMCP("Developer-Toolkit")
@mcp.tool()
async def query_github_repo(owner: str, repo: str) -> str:
"""查询 GitHub 仓库的 Star 数量与最近更新描述"""
url = f"https://api.github.com/repos/{owner}/{repo}"
async with httpx.AsyncClient() as client:
res = await client.get(url, headers={"User-Agent": "FastMCP-Agent"})
if res.status_code != 200:
return f"获取失败: HTTP {res.status_code}"
data = res.json()
return (
f"仓库: {data.get('full_name')}\n"
f"描述: {data.get('description')}\n"
f"Stars: {data.get('stargazers_count')}\n"
f"默认分支: {data.get('default_branch')}"
)
@mcp.resource("config://app-settings")
def get_settings() -> str:
"""提供应用运行时的配置信息供模型参考"""
return "env=production; timeout=30; retry=3"
if __name__ == "__main__":
mcp.run()
3. 本地调试与测试
FastMCP 内置了开发调试命令,可以在终端中直接通过交互界面测试:
mcp dev server.py
该命令会自动启动 MCP Inspector Web 界面,直观查看工具注册、入参 Schema 并手动触发工具测试。
4. 接入 Cursor 与 Claude
在 Cursor 的 MCP 配置文件中添加:
{
"mcpServers": {
"developer-toolkit": {
"command": "uv",
"args": ["run", "--directory", "/path/to/fastmcp-demo", "python", "server.py"]
}
}
}
FastMCP 自动推导类型并生成 JSON Schema,省去了大量样板代码,是 Python 开发者构建 MCP 的首选利器。