大模型基建:基于 FastAPI 自动构建 SSE MCP 服务器
介绍如何使用 FastAPI 结合 fastapi-mcp 库构建支持 SSE 协议的 MCP 服务器。内容涵盖环境搭建、代码实现(如 Weather MCP Server)、服务启动与调试(mcp inspector),以及通过 mcp-proxy 连接 Claude Desktop 的配置方法。FastAPI 凭借异步能力和类型安全,能高效将企业能力转化为大模型可调用的标准化服务,适合高并发场景下的实时交互需求。

介绍如何使用 FastAPI 结合 fastapi-mcp 库构建支持 SSE 协议的 MCP 服务器。内容涵盖环境搭建、代码实现(如 Weather MCP Server)、服务启动与调试(mcp inspector),以及通过 mcp-proxy 连接 Claude Desktop 的配置方法。FastAPI 凭借异步能力和类型安全,能高效将企业能力转化为大模型可调用的标准化服务,适合高并发场景下的实时交互需求。

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

pip install uvicorn fastapi
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"data": "Hello MCP!"}
uvicorn server:app --reload
接下来,我们将基于 FastAPI 开发 MCP 服务器。

fastapi-mcp 是一个零配置工具,用于自动将 FastAPI 端点暴露为模型上下文协议(MCP)工具。其特点在于简洁性和高效性:
pip install fastapi-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)
uvicorn server:app --host 0.0.0.0 --port 8001 --reload

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。

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

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online