你是否曾想过,让你精心构建的 FastAPI 应用接口,能够被 AI 模型(比如 Cursor、Claude 等)直接调用,成为它们强大的“外部工具”?
想象一下,不再需要手动为 AI 编写繁琐的工具描述和接口规范,只需几行代码,你的 API 就能无缝接入 AI 的工作流。
听起来很酷?现在,这一切都成为了可能!隆重介绍 FastAPI-MCP!
🤔 什么是 MCP?
你可能第一次听说 MCP。简单理解,MCP 是一种新兴的开放标准,旨在规范 AI 模型如何发现、理解和使用外部工具(比如 API、函数等)。有了这个标准,AI 就能更智能、更统一地与外部世界互动。
✨ FastAPI-MCP 的亮点?简直不要太方便!
厌倦了为 AI 手动适配 API?FastAPI-MCP 来拯救你了!
- 🤝 直接集成,无缝对接: 无需复杂的设置,直接将 MCP 服务挂载到你现有的 FastAPI 应用上。
- ⚙️ 零配置,开箱即用: 真的!你只需要告诉它你的 FastAPI 应用在哪里,剩下的交给它。
- 🤖 自动发现,智能转换: 它会自动扫描你所有的 FastAPI 路由(endpoints),并将其转换为 MCP 工具。
- 📑 保留模式,信息不丢失: 你精心设计的 Pydantic 请求/响应模型(schemas)会被完整保留,AI 清晰知道如何发送请求和解析响应。
- ✍️ 保留文档,AI 也爱看: 你在 Swagger/OpenAPI 中为端点编写的描述文档也会被一并转换,让 AI 准确理解每个工具的用途。
- 🧩 轻松扩展,自定义无忧: 除了自动生成的工具,你还可以轻松添加自定义的 MCP 工具,满足更复杂的需求。
🚀 如何快速上手?
上手 FastAPI-MCP 非常简单,就像给你的项目添加一个新依赖一样。
1. 安装:
我们推荐使用速度飞快的 uv
:
1uv add fastapi-mcp
当然,传统的 pip
也可以:
1pip install fastapi-mcp
2. 集成到你的 FastAPI 应用:
1from fastapi import FastAPI
2from fastapi_mcp import add_mcp_server
3
4app = FastAPI()
5
6mcp_server = add_mcp_server(
7 app, # Your FastAPI app
8 mount_path="/mcp", # Where to mount the MCP server
9 name="My API MCP", # Name for the MCP server
10 describe_all_responses=True, # False by default. Include all possible response schemas in tool descriptions, instead of just the successful response.
11 describe_full_response_schema=True # False by default. Include full JSON schema in tool descriptions, instead of just an LLM-friendly response example.
12)
13
14# Optionally add custom tools in addition to existing APIs.
15@mcp_server.tool()
16async def get_server_time() -> str:
17 """Get the current server time."""
18 from datetime import datetime
19 return datetime.now().isoformat()
20
21if __name__ == "__main__":
22 import uvicorn
23
24 uvicorn.run(app, host="127.0.0.1", port=8000)
25
搞定! 就是这么简单。现在,启动你的 FastAPI 应用,
1uv run ./server/py
你的 MCP 服务就已经在 http://localhost:8000/mcp
上运行了!
🔗 如何连接和使用?
一旦你的 FastAPI 应用跑起来了,支持 MCP 的 AI 客户端就能发现并使用这些工具了。
方法一:使用支持 SSE 的客户端 (如 Cursor)
- 运行你的 FastAPI 应用。
- 在 Cursor 的设置 (Settings -> MCP) 中,将你的 MCP 服务端点 URL (例如
http://localhost:8000/mcp
) 添加为 SSE 连接。
- Cursor 会自动发现你暴露的所有 API 工具!当出现绿色的小点证明Cursor成功发现我们的mcp服务了。
3. 接下来在Cursor中调用,切换左下角为agent,对话框输入“获取服务器时间”or “get server time”,Cursor会自动去调用MCP tools, 点击Run tools输出下面内容。
今天的分享就到这里啦!
觉得有用的话,别忘了点个“赞”和“在看”哦!你的支持是我继续分享的动力!