FastAPI-MCP构建自定义MCP工具实操指南
一、简介
-
• FastAPI-MCP是一个基于python FastAPI框架开发的开源项目,可以自动识别并暴露FastAPI接口为MCP工具
-
• 拥有FastAPI框架的所有优点,如异步高并发、独立远程部署、OpenAPI文档
-
• 提供SSE、mcp-remote接入方式,支持设置授权访问,适配各种支持MCP协议客户端
-
• FastAPI-MCP开源地址:https://github.com/tadata-org/fastapi_mcp,工作原理参考下图:
二、安装并启动示例
1. 安装fastapi-mcp
-
• 提前准备好python 3.10+、uv/pip软件环境(此处不做赘述)
-
• 直接一键安装
//安装方式1: 使用uv命令
uv add fastapi-mcp
//安装方式2:使用pip命令
pip install fastapi-mcp
2. 编写示例代码 fastapi-mcp.py,实现两个测试工具
-
• 一个获取当前时间的接口/工具(不需要授权)
-
• 一个模拟获取用户信息的/工具(需要授权)
from datetime import datetimeimport uvicorn
from fastapi import FastAPI, Depends, HTTPException, Header
from fastapi_mcp import FastApiMCPapp = FastAPI()# 授权验证,如果不需要,可以删除
asyncdefverify_token(authorization: str | None = Header(None)):# 这里替换为实际的验证逻辑,比如数据库查询,JWT验证等valid_tokens = {"123456", "abcdef"} # 示例有效token集合if authorization notin valid_tokens:raise HTTPException(status_code=403, detail="Invalid Token")returnTrue# 注意:要设置添加明确的 operation_id 参数,这会让大模型更容易理解工具的作用
# 编写一个获取当前时间的接口
@app.get("/getCurrentTime", operation_id="get_current_time")
asyncdefget_current_time():return {"current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}# 编写一个模拟获取用户信息的接口
@app.get("/users/{user_id}", operation_id="get_user_info")
asyncdefget_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提供的在线文档、接口等
-
• 在线 Swagger 文档,访问:http://localhost:8000/docs
-
• 既是MCP工具,也是正常的API接口,如下使用 Postman 访问示例
三、在Cherry Studio中使用FastAPI-MCP服务
下载并安装 Cherry Studio 客户端软件,下载地址:https://www.cherry-ai.com/
配置使用 FastAPI-MCP 启动后提供的服务,默认MCP服务运行在:http://localhost:8000/mcp,配置如下:
- • Cherry Studio提供的非常方便的可视化配置界面
- • 实际上在其他支持SSE的MCP客户端,可以使用下面配置
{"mcpServers":{"fastapi-mcp":{"name":"fastapi-mcp","type":"sse","description":"","isActive":true,"baseUrl":"http://localhost:8000/mcp","headers":{"Content-Type":"application/json","Authorization":"123456"}}
}
- • 配置完成后,MCP客户端可以自动请求获取到相关的MCP工具了
在对话中,使用fastapi-mcp工具
- • 开启并选择fastapi-mcp工具
- • 获取当前时间示例
- • 获取用户ID为888888的用户信息
- • 可以自动链式调用多个工具,完成复杂任务:帮我看看用户ID为888888的用户多少岁了
四、总结
-
• FastAPI-MCP工具可以让你开发MCP工具像开发普通接口一样,灵活扩展、适应性强
-
• 使用FastAPI-MCP,可以快速搭建起自己的私有MCP工具集,独立部署、远程访问