
一、简介
- FastAPI-MCP是一个基于python FastAPI框架开发的开源项目,可以自动识别并暴露FastAPI接口为MCP工具
- 拥有FastAPI框架的所有优点,如异步高并发、独立远程部署、OpenAPI文档
- 提供SSE、mcp-remote接入方式,支持设置授权访问,适配各种支持MCP协议客户端
- FastAPI-MCP开源地址:https://github.com/tadata-org/fastapi_mcp,工作原理参考下图:

二、安装并启动示例
1. 安装fastapi-mcp
2. 编写示例代码 fastapi-mcp.py,实现两个测试工具
- 一个获取当前时间的接口/工具(不需要授权)
- 一个模拟获取用户信息的/工具(需要授权)
from datetime import datetime
import uvicorn
from fastapi import FastAPI, Depends, HTTPException, Header
from fastapi_mcp import FastApiMCP
app = FastAPI()
# 授权验证,如果不需要,可以删除
async def verify_token(authorization: str | None = Header(None)):
# 这里替换为实际的验证逻辑,比如数据库查询,JWT验证等
valid_tokens = {"123456", "abcdef"} # 示例有效token集合
if authorization not in valid_tokens:
raise HTTPException(status_code=403, detail="Invalid Token")
return True
# 注意:要设置添加明确的 operation_id 参数,这会让大模型更容易理解工具的作用
# 编写一个获取当前时间的接口
@app.get("/getCurrentTime", operation_id="get_current_time")
async def get_current_time():
return {"current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
# 编写一个模拟获取用户信息的接口
@app.get("/users/{user_id}", operation_id="get_user_info")
async def get_user_info(user_id: int, is_auth: bool = Depends(verify_token)): # 验证请求头,需要授权访问
# 这里的data可以替换成实际的查询数据库,这里只作为示例返回
data = {
"user_id": user_id,
"name": "小狗狗",
"sex": "男",
"birthday": "2002-07-06",
}
return data
# 创建 MCP 服务器实例,绑定到 FastAPI app
mcp = FastApiMCP(app)
# 挂载 MCP 服务器,默认路径是 /mcp(可以修改)
mcp.mount()
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
3. 启动运行测试用例
python fastapi-mcp.py

4. 启动之后,可以直接访问原本FastAPI提供的在线文档、接口等
三、在Cherry Studio中使用FastAPI-MCP服务
四、总结
- FastAPI-MCP工具可以让你开发MCP工具像开发普通接口一样,灵活扩展、适应性强
- 使用FastAPI-MCP,可以快速搭建起自己的私有MCP工具集,独立部署、远程访问