用 FastAPI 搭一个 SSE MCP 服务
MCP 这套协议的意义不在于'又多了一层抽象',而是把 AI 代理和外部能力之间的边界说清楚了。对已经在用 FastAPI 的项目来说,接 MCP 服务器没必要重起炉灶,直接沿着现有路由和异步接口往下接,成本最低。

FastAPI 先跑起来
安装依赖:
pip install uvicorn fastapi
一个最小的 FastAPI 应用长这样:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"data": "Hello MCP!"}
启动服务:
uvicorn server:app --reload
这一步的目的很简单:先确认基础服务是通的,再往上叠 MCP。直接把 MCP 和业务代码一起改,排错会很烦。

用 fastapi-mcp 暴露工具
fastapi-mcp 的思路比较直接:把 FastAPI 端点自动挂成 MCP 工具,省掉手写一层适配器。它适合那种已经有一套 REST 接口、现在想尽快让大模型能调用的场景。
它的几个特点我会这样理解:
- 不需要额外做复杂编排,接入门槛低。
- 现有端点可以直接转成 MCP 工具。
- 还能手动补一些自定义工具,不会把路堵死。
- FastAPI 原来的文档和接口习惯基本还能保住。
安装依赖:
pip install fastapi-mcp
示例代码里用了一个天气查询工具,核心是通过 add_mcp_server() 把 MCP server 挂到 /mcp:
from fastapi import FastAPI
from fastapi_mcp import add_mcp_server
typing
httpx
NWS_API_BASE =
USER_AGENT =
app = FastAPI()
mcp_server = add_mcp_server(
app,
mount_path=,
name=,
describe_all_responses=,
describe_full_response_schema=
)
() -> [, ] | :
headers = {
: USER_AGENT,
:
}
httpx.AsyncClient() client:
:
response = client.get(url, headers=headers, timeout=)
response.raise_for_status()
response.json()
Exception:
() -> :
points_url =
points_data = make_nws_request(points_url)
points_data:
forecast_url = points_data[][]
forecast_data = make_nws_request(forecast_url)
forecast_data:
periods = forecast_data[][]
forecasts = []
period periods[:]:
forecast =
forecasts.append(forecast)
.join(forecasts)






