使用 FastAPI 构建 MCP 服务器
Anthropic 推出的 MCP 协议旨在让 AI 代理和应用程序之间的对话变得更顺畅、更清晰。FastAPI 基于 Starlette 和 Uvicorn,采用异步编程模型,可轻松处理高并发请求,尤其适合 MCP 场景下大模型与外部系统的实时交互需求,其性能接近 Node.js 和 Go,在数据库查询、文件操作等 I/O 密集型任务中表现卓越。

FastAPI 基础知识
安装依赖
pip install uvicorn fastapi
FastAPI 服务代码示例
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"data": "Hello MCP!"}
uvicorn 启动 Server
uvicorn server:app --reload
接下来,我们将基于 FastAPI 来开发 MCP 服务器。

FastAPI 开发 MCP Server
FastAPI-MCP 是一个零配置工具,用于自动将 FastAPI 端点暴露为模型上下文协议(MCP)工具。其特点在于简洁性和高效性:
- 直接集成:不需要复杂的设置,直接集成到 FastAPI 应用中。
- 自动转换:无需手动编写代码,自动将 FastAPI 端点转换为 MCP 工具。
- 灵活性:支持自定义 MCP 工具,与自动生成的工具一同使用。
- 性能:基于 Python 3.10+ 和 FastAPI,保证了高性能的 API 服务。
- 文档友好:保持了原有的 API 文档,方便开发者使用和理解。
安装依赖
pip install fastapi-mcp
MCP 服务代码示例
from fastapi import FastAPI
from fastapi_mcp import add_mcp_server
from typing import Any
import httpx
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
app = FastAPI()
mcp_server = add_mcp_server(
app,
mount_path="/mcp",
name="Weather MCP Server",
describe_all_responses=True,
describe_full_response_schema=True
)
async def make_nws_request(url: str) -> dict[str, Any] | None:
"""向 NWS API 发起请求,并进行错误处理。"""
headers = {
"User-Agent": USER_AGENT,
"Accept": "application/geo+json"
}
async with httpx.AsyncClient() as client:
try:
response = await client.get(url, headers=headers, timeout=30.0)
response.raise_for_status()
return response.json()
except Exception:
return None
@mcp_server.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
"""获取地点的天气预报。
参数:
latitude: 地点的纬度
longitude: 地点的经度
"""
points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
points_data = await make_nws_request(points_url)
if not points_data:
return "Unable to fetch forecast data for this location."
forecast_url = points_data["properties"]["forecast"]
forecast_data = await make_nws_request(forecast_url)
if not forecast_data:
return "Unable to fetch detailed forecast."
periods = forecast_data["properties"]["periods"]
forecasts = []
for period in periods[:5]:
forecast = f"""
{period['name']}: Temperature: {period['temperature']}°{period['temperatureUnit']} Wind: {period['windSpeed']} {period['windDirection']} Forecast: {period['detailedForecast']}
"""
forecasts.append(forecast)
return "\n---\n".join(forecasts)
启动 MCP Server
uvicorn server:app --host 0.0.0.0 --port 8001 --reload

启动 MCP Inspector 调试
CLIENT_PORT=8081 SERVER_PORT=8082 npx -y @modelcontextprotocol/inspector

当集成了 MCP 的 FastAPI 应用运行起来后,可以用任何支持 SSE 的 MCP 客户端连接它。这里使用 mcp inspector 进行调试,通过 SSE 连接 Weather MCP 服务器。
SSE 是一种单向通信的模式,所以它需要配合 HTTP Post 来实现客户端与服务端的双向通信。严格的说,这是一种 HTTP Post(客户端->服务端) + HTTP SSE(服务端->客户端)的伪双工通信模式,区别于 WebSocket 双向通信。

如果 MCP 客户端不支持 SSE,可以使用 mcp-proxy 连接 MCP 服务器。本质上是本地通过 stdio 连接到 mcp-proxy,再由 mcp-proxy 通过 SSE 连接到 MCP Server 上。
mcp-proxy 支持两种模式:stdio to SSE 和 SSE to stdio。

安装 mcp-proxy
uv tool install mcp-proxy
配置 claude_desktop_config.json
{
"mcpServers": {
"weather-api-mcp-proxy": {
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8001/mcp"]
}
}
}
FastAPI-MCP 目前还有很多功能不完善,我们将持续关注进展。在后续进阶内容中,可以手搓一个自动挂载的功能,并基于现有 fastapi base_url 将 api 挂载至 mcp_server。
大模型基建工程总结
FastAPI 构建 MCP 服务器的核心价值在于:通过类型安全的异步接口,将企业现有能力快速转化为大模型可调用的标准化服务。这种架构既保留了 FastAPI 的高效开发体验,又通过 MCP 协议实现了与前沿 AI 技术的无缝对接,同时结合 Docker 和 Kubernetes 实现弹性伸缩部署,可以快速应对大模型调用量的突发增长,是构建下一代智能系统的理想选择。