FastAPI-MCP 架构实践: 使用FastAPI一键转化MCP服务器 原创

发布于 2025-5-19 08:26
浏览
0收藏

你是否遇到过这样的情况:你希望聊天机器人使用一个工具回答问题?虽然这听起来有些复杂,但现在,MCP(模型上下文协议)提供外部工具中的方法,不仅让LLM能够轻松调用工具,还可以基于不同应用场景使用工具。本文将深入探讨使用 FastAPI 完成Web 应用转换过程,该应用程序由 MCP 服务器提供支持,使用 FastAPI-MCP。

FastAPI 与 MCP

FastAPI 是由Python提供的工具,帮助用户构建API 应用从而协助完成Web 应用程序的开发。由于其使用方便、上手快,深受业内人士的欢迎。如果将 FastAPI 视为智能服务员,来接受你的订单(HTTP 请求),前往厨房(数据库/服务器),然后响应订单(输出),最后展示给你。FastAPI是构建 Web 后端、移动应用程序服务等的强大工具。

MCP 是 Anthropic 提供的一种使模型与外部数据源和工具通信的开放标准协议。这里我们将 MCP 视为特定任务提供的工具包,并使用 MCP 来创建响应的服务器,从而提供任务所需要的工具服务。

这些工具服务可以赋予LLM更广泛的能力。这就是 FastAPI 与 MCP 集成的价值和意义。​FastAPI 负责处理不同来源的工具服务,而 MCP 负责处理 LLM 的上下文。通过使用 FastAPI 与 MCP 服务器,我们可以访问部署在 Web 上的工具,并将其用作 LLM 工具,使 LLM 更有效地完成任务。

FastAPI-MCP 架构实践: 使用FastAPI一键转化MCP服务器-AI.x社区

如上图所示, MCP 服务器连接到API 端点。这个 API 端点可以是FastAPI 端点,也可以是互联网上的第三方 API 服务。

FastAPI-MCP 是什么?

FastAPI-MCP 是一个工具,它可以将任何 FastAPI 应用程序转换为像 ​ChatGPT​ 或 Claude的 LLM 工具,让用户可以轻松理解和使用。通过使用 FastAPI-MCP,可以将你的 FastAPI 端点包装起来,成为LLM 的 AI 生态系统中即插即用的工具。​

什么 API 可以使用 FastAPI-MCP 转换为 MCP?

使用 FastAPI-MCP,任何 FastAPI 端点都可以转换为 LLMs 的 MCP 工具。这些端点应包括:

  • GET 端点:转换为 MCP 资源。​
  • POST、PUT、DELETE 端点:转换为 MCP 工具。​
  • 自定义实用功能:可作为额外的 MCP 工具添加。​

FastAPI-MCP会自动发现并将API端点转换为 MCP。同时会保留API 的模式以及文档。

使用 FastAPI-MCP 进行实际操作

让我们看一个简单的示例,演示如何将 FastAPI 端点转换为 MCP 服务器。首先,我们将创建一个 FastAPI 端点,然后开始将其转换为使用 fastapi-mcp 的 MCP 服务器。

配置 FastAPI

安装依赖项。

通过安装所需的依赖项使你的系统兼容。

pip install fastapi fastapi_mcp uvicorn mcp-proxy

导入所需的依赖项

创建一个名为 '​main.py​' 的新文件,然后在其中导入以下依赖项。

from fastapi import FastAPI, HTTPException, Query
import httpx
from fastapi_mcp import FastApiMCP

定义 FastAPI 应用程序

让我们定义一个名为“Weather Updates API”的 FastAPI 应用程序。

app = FastAPI(title="Weather Updates API")

定义路由和函数

接着,为应用程序定义路由,也就是将端点与函数进行一一对应。这里,使用 ​weather.gov​ API(免费)制作天气应用,不需要任何 API 密钥。只需要使用正确的纬度和经度值访问如下URL即可, https://api.weather.gov/points/{lat},{lon}​。​

于是,定义了get_weather 函数,它将以州名或代码作为参数,然后在 CITY_COORDINATES 字典中找到相应的坐标,然后使用这些坐标访问基本 URL。

# Predefined latitude and longitude for major cities (for simplicity)
# In a production app, you could use a geocoding service like Nominatim or Google Geocoding API
CITY_COORDINATES = {
   "Los Angeles": {"lat": 34.0522, "lon": -118.2437},
   "San Francisco": {"lat": 37.7749, "lon": -122.4194},
   "San Diego": {"lat": 32.7157, "lon": -117.1611},
   "New York": {"lat": 40.7128, "lon": -74.0060},
   "Chicago": {"lat": 41.8781, "lon": -87.6298},
   # Add more cities as needed
}


@app.get("/weather")
async def get_weather(
   stateCode: str = Query(..., description="State code (e.g., 'CA' for California)"),
   city: str = Query(..., description="City name (e.g., 'Los Angeles')")
):
   """
   Retrieve today's weather from the National Weather Service API based on city and state
   """
   # Get coordinates (latitude, longitude) for the given city
   if city not in CITY_COORDINATES:
       raise HTTPException(
           status_code=404,
           detail=f"City '{city}' not found in predefined list. Please use another city."
       )
  
   coordinates = CITY_COORDINATES[city]
   lat, lon = coordinates["lat"], coordinates["lon"]
  
   # URL for the NWS API Gridpoints endpoint
   base_url = f"https://api.weather.gov/points/{lat},{lon}"
  
   try:
       async with httpx.AsyncClient() as client:
           # First, get the gridpoint information for the given location
           gridpoint_response = await client.get(base_url)
           gridpoint_response.raise_for_status()
           gridpoint_data = gridpoint_response.json()
          
           # Retrieve the forecast data using the gridpoint information
           forecast_url = gridpoint_data["properties"]["forecast"]
           forecast_response = await client.get(forecast_url)
           forecast_response.raise_for_status()
           forecast_data = forecast_response.json()


           # Returning today's forecast
           today_weather = forecast_data["properties"]["periods"][0]
           return {
               "city": city,
               "state": stateCode,
               "date": today_weather["startTime"],
               "temperature": today_weather["temperature"],
               "temperatureUnit": today_weather["temperatureUnit"],
               "forecast": today_weather["detailedForecast"],
           }
  
   except httpx.HTTPStatusError as e:
       raise HTTPException(
           status_code=e.response.status_code,
           detail=f"NWS API error: {e.response.text}"
       )
   except Exception as e:
       raise HTTPException(
           status_code=500,
           detail=f"Internal server error: {str(e)}"
       )

设置 MCP 服务器

然后,让我们使用 fastapi-mcp 库将这个 FastAPI 应用程序转换为 MCP。这个过程非常简单,我们只需要添加几行代码,fastapi-mcp 就会自动将端点转换为 MCP 工具,并轻松检测其模式和文档。

mcp = FastApiMCP(
   app,
   name="Weather Updates API",
   description="API for retrieving today's weather from weather.gov",
)
mcp.mount() 

启动应用程序

在 ​Python 文件的末尾添加以下内容。

if __name__ == "__main__":
   import uvicorn
   uvicorn.run(app, host="0.0.0.0", port=8000)

然后,转到终端并运行 ​main.py 文件。

python main.py 

现在,FastAPI 应用程序在本地主机上成功启动。

配置Cursor

让我们配置 Cursor IDE 测试MCP 服务器。

1. 从这里下载,链接:https://www.cursor.com/downloads

2. 安装Cursor,注册并进入主屏幕

FastAPI-MCP 架构实践: 使用FastAPI一键转化MCP服务器-AI.x社区

3. 现在转到标题工具栏中的文件,然后点击首选项 ,再点击光标设置 。

FastAPI-MCP 架构实践: 使用FastAPI一键转化MCP服务器-AI.x社区

4. 从光标设置中,单击 MCP。

FastAPI-MCP 架构实践: 使用FastAPI一键转化MCP服务器-AI.x社区

5. 在 MCP 选项卡上,单击添加新全局 MCP 服务器 。它将打开一个 mcp.json 文件。将以下代码粘贴到其中并保存文件。

{
   "mcpServers": {
     "National Park Service": {
         "command": "mcp-proxy",
         "args": ["http://127.0.0.1:8000/mcp"]
     }
   }
}

6. 在光标设置处,你应该看到以下内容:

FastAPI-MCP 架构实践: 使用FastAPI一键转化MCP服务器-AI.x社区

如果你在屏幕上看到这个,这意味着你的服务器已成功运行并连接到 ​Cursor IDE​。如果显示一些错误,请尝试使用右上角的 重新启动 按钮。​

我们已成功在 Cursor IDE 中设置了 MCP 服务器。现在,让我们测试服务器。

测试 MCP 服务器

经过上面的操作,MCP 服务器可以检索天气更新了。只需向 Cursor IDE 询问任何位置的天气更新,它将使用 MCP 服务器为我们获取该信息。

输入查询:“ 请告诉我今天圣地亚哥的天气如何 ”

FastAPI-MCP 架构实践: 使用FastAPI一键转化MCP服务器-AI.x社区

Query: "New York weather?"

FastAPI-MCP 架构实践: 使用FastAPI一键转化MCP服务器-AI.x社区

从输出中看到MCP 服务器运行良好。只需要询问天气详情,它将自行决定是否使用 MCP 服务器。在第二个输出中,我们模糊地询问“纽约天气?”它能够根据我们之前的提示意识到查询的上下文,并使用适当的 MCP 工具来回答。

结论

MCP 允许 LLMs​ 通过访问外部工具来增强其回答能力,而 FastAPI 则提供了一种简单的方法。本文中,我们使用 fastapi-mcp 库结合了这两种技术。利用这个库,我们可以将任何 API 转换为 MCP 服务器,这将帮助 LLMs 和 AI 代理从 API 中获取最新信息。不需要为每个新任务定义自定义工具。MCP 与 FastAPI 将自动处理一切。MCP 的引入带来了 LLMs 领域的革命,现在,FastAPI 与 MCP 搭配正在改变 LLMs 访问这些工具的方式。​

译者介绍

崔皓,51CTO社区编辑,资深架构师,拥有18年的软件开发和架构经验,10年分布式架构经验。

原文标题:​How to Convert Any FastAPI App into MCP Server using FastAPI-MCP?​,作者:Harsh Mishra

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2025-5-19 08:27:02修改
收藏
回复
举报
回复
相关推荐