在构建大模型应用时,Anthropic 推出的 MCP 协议能让 AI 代理与应用程序之间的对话更顺畅。FastAPI 基于 Starlette 和 Uvicorn,采用异步编程模型,处理高并发请求的能力很强,尤其适合大模型与外部系统的实时交互场景,性能接近 Node.js 和 Go。

FastAPI 基础准备
先安装核心依赖:
pip install uvicorn fastapi
写一个简单的服务代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"data": "Hello MCP!"}
启动服务:
uvicorn server:app --reload
这里 server 指的是你的 Python 文件名(例如 server.py),app 是实例名。
开发 MCP Server
为了简化开发,可以使用 fastapi-mcp 库。它能把 FastAPI 端点直接暴露为 MCP 工具,无需手动编写转换逻辑。
特点:
- 零配置集成:直接挂载到 FastAPI 应用中。
- 自动转换:端点自动变为 MCP 工具。
- 灵活扩展:支持自定义工具与自动生成工具混用。
- 文档友好:保留原有的 API 文档结构。
安装依赖
pip install fastapi-mcp
编写服务代码
下面是一个调用天气 API 的示例,展示了如何将业务逻辑封装为 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 服务器
mcp_server = add_mcp_server(
app,
mount_path="/mcp",
name="Weather MCP Server",
describe_all_responses=True, # 包含所有可能的响应模式
describe_full_response_schema=True # 包含完整的 JSON 模式
)
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)
启动服务
uvicorn server:app --host 0.0.0.0 --port 8001 --reload

调试与连接
运行起来后,可以用支持 SSE 的 MCP 客户端连接。推荐使用 mcp inspector 进行调试:
CLIENT_PORT=8081 SERVER_PORT=8082 npx -y @modelcontextprotocol/inspector


注意:SSE 是一种单向通信模式,配合 HTTP Post 实现伪双工通信。如果客户端不支持 SSE,可以使用
mcp-proxy桥接。

mcp-proxy 支持两种模式:stdio to SSE 和 SSE to stdio。本质是本地通过 stdio 连接到 proxy,再由 proxy 通过 SSE 连接到 Server。
安装 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 实现弹性伸缩部署,可以快速应对大模型调用量的突发增长,是构建下一代智能系统的理想选择。


