利用 FastAPI 构建 MCP 服务器,能让 AI 代理与应用间的对话更顺畅、清晰。FastAPI 底层依托 Starlette 和 Uvicorn,采用异步编程模型,处理高并发请求的能力很强,尤其在数据库查询、文件操作等 I/O 密集型任务中表现卓越,非常适合大模型与外部系统的实时交互场景。
FastAPI 基础准备
先安装核心依赖:
pip install uvicorn fastapi
一个简单的服务示例如下,定义一个根路径接口:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"data": "Hello MCP!"}
启动服务时加上 --reload 参数方便开发调试:
uvicorn server:app --reload
集成 MCP 协议
有了基础后,直接切入核心场景。这里推荐使用 fastapi-mcp 库,它能零配置将 FastAPI 端点自动暴露为模型上下文协议(MCP)工具。它的优势在于无需手动编写转换代码,直接集成到现有应用中,同时保持原有的 API 文档友好性。
安装依赖:
pip install fastapi-mcp
下面是一个完整的 Weather MCP Server 示例,展示了如何将外部 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_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[, ] | :
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)


