今天我们将使用FastAPI来构建 MCP 服务器,Anthropic 推出的这个MCP 协议,目的是让 AI 署理和你的应用程序之间的对话变得更顺畅、更清晰。FastAPI 基于 Starlette 和 Uvicorn,采用异步编程模子,可轻松处理高并发请求,尤其得当 MCP 场景下大模子与外部系统的实时交互需求,其性能接近 Node.js 和 Go,在数据库查询、文件操作等 I/O 密集型任务中体现卓越。
开始今天的正题前,我们往返顾下相关的知识内容:
《高性能Python Web服务部署架构解析》、《使用Python开发MCP Server及Inspector工具调试》、《构建智能体MCP客户端:完成大模子与MCP服务端能力集成与最小闭环验证》
FastAPI底子知识
安装依靠
- pip install uvicorn, fastapi
复制代码 FastAPI服务代码示例
- from fastapi import FastAPI
-
- app = FastAPI()
-
- @app.get("/")
- async def root():
- return {"data": "Hello MCP!"}
复制代码 uvicorn启动server
- uvicorn server:app --reload
复制代码
接下来,我们将基于FastAPI来开发MCP服务器
FastAPI开发MCP Server
FastAPI-MCP 一个零设置工具,用于自动将FastAPI端点袒露为模子上下文协议(MCP)工具。其特点在于简洁性和高效性,以下是一些主要特点:
- 直接集成:不必要复杂的设置,直接集成到FastAPI应用中。
- 自动转换:无需手动编写代码,自动将FastAPI端点转换为MCP工具。
- 机动性:支持自界说MCP工具,与自动天生的工具一同使用。
- 性能:基于Python 3.10+和FastAPI,保证了高性能的API服务。
- 文档友好:保持了原有的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, # FastAPI 应用
- mount_path="/mcp", # MCP 服务器挂载的位置
- name="Weather MCP Server", # MCP 服务器的名字
- describe_all_responses=True, # 默认是 False。就像打开一个百宝箱,把所有可能的响应模式都包含在工具描述里,而不只是成功的响应。
- describe_full_response_schema=True # 默认是 False。把完整的 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)
复制代码 启动 mcp server
- uvicorn server:app --host 0.0.0.0 --port 8001 --reload
复制代码
启动 mcp inspector 调试
- 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。
安装 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 自动构建 SSE MCP 服务器 —— 进阶篇》中我们手搓了一个自动挂载的功能,并基于现有fastapi base_url 将 api 挂载至 mcp_server。
大模子基建工程总结
FastAPI 构建 MCP 服务器的核心代价在于:通过范例安全的异步接口,将企业现有能力快速转化为大模子可调用的尺度化服务。这种架构既保留了 FastAPI 的高效开发体验,又通过 MCP 协议实现了与前沿 AI 技术的无缝对接,同时联合 Docker 和 Kubernetes 实现弹性伸缩部署,可以快速应对大模子调用量的突发增长,是构建下一代智能系统的理想选择。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|