fastapi_mcp 是一个用于将 FastAPI 端点暴露为模型上下文协议(Model Context Protocol, MCP)工具的库,并且支持认证功能。
环境macbook,python3.13
pip install fastapi uvicorn fastapi-mcp
代码
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fastapi_mcp import FastApiMCP# 定义图书模型
class Book(BaseModel):id: inttitle: strauthor: str# 创建 FastAPI 应用
app = FastAPI()# 模拟数据库
books_db = {}# 创建图书
@app.post("/books/", response_model=Book)
async def create_book(book: Book):if book.id in books_db:raise HTTPException(status_code=400, detail="Book with this ID already exists")books_db[book.id] = bookreturn book# 获取所有图书
@app.get("/books/", response_model=list[Book])
async def get_all_books():return list(books_db.values())# 获取单个图书
@app.get("/books/{book_id}", response_model=Book)
async def get_book(book_id: int):book = books_db.get(book_id)if book is None:raise HTTPException(status_code=404, detail="Book not found")return book# 更新图书
@app.put("/books/{book_id}", response_model=Book)
async def update_book(book_id: int, book: Book):if book_id not in books_db:raise HTTPException(status_code=404, detail="Book not found")book.id = book_idbooks_db[book_id] = bookreturn book# 删除图书
@app.delete("/books/{book_id}", status_code=204)
async def delete_book(book_id: int):if book_id not in books_db:raise HTTPException(status_code=404, detail="Book not found")del books_db[book_id]return None# 创建 FastApiMCP 实例
mcp = FastApiMCP(app)# 挂载 MCP 服务器
mcp.mount()if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)
python3 -m uvicorn main:app --reload
插入一本书
curl -X POST "http://localhost:8000/books/" -H "Content-Type: application/json" -d '{"id": 1, "title": "Python Crash Course", "author": "Eric Matthes"}'
查询
curl -X GET "http://localhost:8000/books/" [{"id":1,"title":"Python Crash Course","author":"Eric Matthes"}]
cherry studio
如果启动python时报错ImportError
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/pydantic_core/_pydantic_core.cpython-313-darwin.so, 0x0002)
解决
python3 -m pip install pydantic --force-reinstall