【大模子系列篇】大模子基建工程:基于 FastAPI 自动构建 SSE MCP 服务器 ...

一给  论坛元老 | 2025-4-18 06:00:28 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1892|帖子 1892|积分 5676

今天我们将使用FastAPI来构建 MCP 服务器,Anthropic 推出的这个MCP 协议,目的是让 AI 署理和你的应用程序之间的对话变得更顺畅、更清晰。FastAPI 基于 Starlette 和 Uvicorn,采用异步编程模子,可轻松处理高并发请求,尤其得当 MCP 场景下大模子与外部系统的实时交互需求,其性能接近 Node.js 和 Go,在数据库查询、文件操作等 I/O 密集型任务中体现卓越。

开始今天的正题前,我们往返顾下相关的知识内容:
《高性能Python Web服务部署架构解析》、《使用Python开发MCP Server及Inspector工具调试》、《构建智能体MCP客户端:完成大模子与MCP服务端能力集成与最小闭环验证》
 
FastAPI底子知识

安装依靠

  1. pip install uvicorn, fastapi
复制代码
FastAPI服务代码示例 

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get("/")
  4. async def root():
  5.     return {"data": "Hello MCP!"}
复制代码
uvicorn启动server 

  1. uvicorn server:app --reload
复制代码

接下来,我们将基于FastAPI来开发MCP服务器

 
FastAPI开发MCP Server

FastAPI-MCP 一个零设置工具,用于自动将FastAPI端点袒露为模子上下文协议(MCP)工具。其特点在于简洁性和高效性,以下是一些主要特点:


  • 直接集成:不必要复杂的设置,直接集成到FastAPI应用中。
  • 自动转换:无需手动编写代码,自动将FastAPI端点转换为MCP工具。
  • 机动性:支持自界说MCP工具,与自动天生的工具一同使用。
  • 性能:基于Python 3.10+和FastAPI,保证了高性能的API服务。
  • 文档友好:保持了原有的API文档,方便开发者使用和明白。
安装依靠

  1. pip install fastapi-mcp
复制代码
MCP服务代码示例

  1. from fastapi import FastAPI
  2. from fastapi_mcp import add_mcp_server
  3. from typing import Any
  4. import httpx
  5. # 常量
  6. NWS_API_BASE = "https://api.weather.gov"
  7. USER_AGENT = "weather-app/1.0"
  8. app = FastAPI()
  9. mcp_server = add_mcp_server(
  10.     app,                                    # FastAPI 应用
  11.     mount_path="/mcp",                      # MCP 服务器挂载的位置
  12.     name="Weather MCP Server",              # MCP 服务器的名字
  13.     describe_all_responses=True,            # 默认是 False。就像打开一个百宝箱,把所有可能的响应模式都包含在工具描述里,而不只是成功的响应。
  14.     describe_full_response_schema=True      # 默认是 False。把完整的 JSON 模式包含在工具描述里,而不只是一个对大语言模型友好的响应示例。
  15. )
  16. async def make_nws_request(url: str) -> dict[str, Any] | None:
  17.     """向 NWS API 发起请求,并进行错误处理。"""
  18.     headers = {
  19.         "User-Agent": USER_AGENT,
  20.         "Accept": "application/geo+json"
  21.     }
  22.     async with httpx.AsyncClient() as client:
  23.         try:
  24.             response = await client.get(url, headers=headers, timeout=30.0)
  25.             response.raise_for_status()
  26.             return response.json()
  27.         except Exception:
  28.             return None
  29. @mcp_server.tool()
  30. async def get_forecast(latitude: float, longitude: float) -> str:
  31.     """获取地点的天气预报。
  32.     参数:
  33.         latitude: 地点的纬度
  34.         longitude: 地点的经度
  35.     """
  36.     points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
  37.     points_data = await make_nws_request(points_url)
  38.     if not points_data:
  39.         return "Unable to fetch forecast data for this location."
  40.     forecast_url = points_data["properties"]["forecast"]
  41.     forecast_data = await make_nws_request(forecast_url)
  42.     if not forecast_data:
  43.         return "Unable to fetch detailed forecast."
  44.     periods = forecast_data["properties"]["periods"]
  45.     forecasts = []
  46.     for period in periods[:5]:
  47.         forecast = f"""
  48. {period['name']}:
  49. Temperature: {period['temperature']}°{period['temperatureUnit']}
  50. Wind: {period['windSpeed']} {period['windDirection']}
  51. Forecast: {period['detailedForecast']}
  52. """
  53.         forecasts.append(forecast)
  54.     return "\n---\n".join(forecasts)
复制代码
启动 mcp server

  1. uvicorn server:app --host 0.0.0.0 --port 8001 --reload
复制代码

 启动 mcp inspector 调试

  1. 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
  1. uv tool install mcp-proxy
复制代码
设置 claude_desktop_config.json 
  1. {
  2.   "mcpServers": {
  3.     "weather-api-mcp-proxy": {
  4.         "command": "mcp-proxy",
  5.         "args": ["http://127.0.0.1:8001/mcp"]
  6.     }
  7.   }
  8. }
复制代码
FastAPI-MCP 现在还有很多功能不完善,我们将持续关注进展。在《大模子基建工程:基于 FastAPI 自动构建 SSE MCP 服务器 —— 进阶篇》中我们手搓了一个自动挂载的功能,并基于现有fastapi base_url 将 api 挂载至 mcp_server。

大模子基建工程总结

FastAPI 构建 MCP 服务器的核心代价在于:通过范例安全的异步接口,将企业现有能力快速转化为大模子可调用的尺度化服务。这种架构既保留了 FastAPI 的高效开发体验,又通过 MCP 协议实现了与前沿 AI 技术的无缝对接,同时联合 Docker 和 Kubernetes 实现弹性伸缩部署,可以快速应对大模子调用量的突发增长,是构建下一代智能系统的理想选择。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

一给

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表