使用 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!"}
启动服务:
uvicorn server:app --reload
在此基础上,我们开发 MCP 服务器。
使用 FastAPI-MCP 构建 MCP Server
fastapi-mcp 是一个零配置工具,能自动将 FastAPI 端点暴露为模型上下文协议(MCP)工具。它无需复杂设置,直接集成到应用中即可自动转换,同时支持自定义工具,性能基于 Python 3.10+ 和 FastAPI,文档友好。
安装依赖
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() -> [, ] | :
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)


