fastapi_mcp实战
- 使用 FastAPI-MCP 将 MCP 服务器添加到 FastAPI 应用的简单示例。
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from typing import List, Optional
from fastapi_mcp import add_mcp_server
# Create a simple FastAPI app
app = FastAPI(
title="Example API",
description="A simple example API with integrated MCP server",
version="0.1.0",
)
# Define some models
class Item(BaseModel):
id: int
name: str
description: Optional[str] = None
price: float
tags: List[str] = []
# In-memory database
items_db: dict[int, Item] = {}
# Define some endpoints
@app.get("/items/", response_model=List[Item], tags=["items"])
async def list_items(skip: int = 0, limit: int = 10):
"""
List all items in the database.
Returns a list of items, with pagination support.
"""
return list(items_db.values())[skip : skip + limit]
@app.get("/items/{item_id}", response_model=Item, tags=["items"])
async def read_item(item_id: int):
"""
Get a specific item by its ID.
Raises a 404 error if the item does not exist.
"""
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
return items_db[item_id]
@app.post("/items/", response_model=Item, tags=["items"])
async def create_item(item: Item):
"""
Create a new item in the database.
Returns the created item with its assigned ID.
"""
items_db[item.id] = item
return item
@app.put("/items/{item_id}", response_model=Item, tags=["items"])
async def update_item(item_id: int, item: Item):
"""
Update an existing item.
Raises a 404 error if the item does not exist.
"""
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
item.id = item_id
items_db[item_id] = item
return item
@app.delete("/items/{item_id}", tags=["items"])
async def delete_item(item_id: int):
"""
Delete an item from the database.
Raises a 404 error if the item does not exist.
"""
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
del items_db[item_id]
return {"message": "Item deleted successfully"}
@app.get("/items/search/", response_model=List[Item], tags=["search"])
async def search_items(
q: Optional[str] = Query(None, description="Search query string"),
min_price: Optional[float] = Query(None, description="Minimum price"),
max_price: Optional[float] = Query(None, description="Maximum price"),
tags: List[str] = Query([], description="Filter by tags"),
):
"""
Search for items with various filters.
Returns a list of items that match the search criteria.
"""
results = list(items_db.values())
# Filter by search query
if q:
q = q.lower()
results = [
item for item in results if q in item.name.lower() or (item.description and q in item.description.lower())
]
# Filter by price range
if min_price is not None:
results = [item for item in results if item.price >= min_price]
if max_price is not None:
results = [item for item in results if item.price <= max_price]
# Filter by tags
if tags:
results = [item for item in results if all(tag in item.tags for tag in tags)]
return results
# Add sample data
sample_items = [
Item(id=1, name="Hammer", description="A tool for hammering nails", price=9.99, tags=["tool", "hardware"]),
Item(id=2, name="Screwdriver", description="A tool for driving screws", price=7.99, tags=["tool", "hardware"]),
Item(id=3, name="Wrench", description="A tool for tightening bolts", price=12.99, tags=["tool", "hardware"]),
Item(id=4, name="Saw", description="A tool for cutting wood", price=19.99, tags=["tool", "hardware", "cutting"]),
Item(id=5, name="Drill", description="A tool for drilling holes", price=49.99, tags=["tool", "hardware", "power"]),
]
for item in sample_items:
items_db[item.id] = item
# Add MCP server to the FastAPI app
mcp_server = add_mcp_server(
app,
mount_path="/mcp", # 挂着mcp服务器的地址
name="Item API MCP", # mcp服务的名称
description="MCP server for the Item API",
base_url="http://localhost:8000",
describe_all_responses=False, # 默认False, Only describe the success response in tool descriptions
describe_full_response_schema=False, # Only show LLM-friendly example response in tool descriptions, not the full json schema
)
# Optionally, you can add custom MCP tools not based on FastAPI endpoints
@mcp_server.tool()
async def get_item_count() -> int:
"""Get the total number of items in the database."""
return len(items_db)
# Run the server if this file is executed directly
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
特点
- 直接集成 - 将 MCP 服务器直接挂载到你的 FastAPI 应用程序
- 无需配置 - 只需将其指向您的 FastAPI 应用程序即可工作
- 自动发现所有 FastAPI 端点并转换为 MCP 工具
- 保留请求模型和响应模型的架构
- 保留所有端点的文档,就像在 Swagger 中一样
- 扩展 - 在自动生成的 MCP 工具旁边添加自定义 MCP 工具
使用 SSE 连接到 MCP 服务器
具有 MCP 集成的 FastAPI 应用程序运行后,您可以使用任何支持 SSE 的 MCP 客户端(例如 Cursor)连接到它:
- 运行您的应用程序。
- 在 Cursor -> Settings -> MCP 中,使用 MCP 服务器端点的 URL(例如 )作为 sse。http://localhost:8000/mcp
- Cursor 将自动发现所有可用的工具和资源
使用 mcp-proxy stdio 连接到 MCP 服务器
如果您的 MCP 客户端不支持 SSE,例如 Claude Desktop:
- 运行您的应用程序。
- 安装 mcp-proxy,例如:
uv tool install mcp-proxy
- 添加 Claude Desktop MCP 配置文件 ():
claude_desktop_config.json
在 Windows 上:
{
"mcpServers": {
"my-api-mcp-proxy": {
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8000/mcp"]
}
}
}
如何学习大模型 AI ?
由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。
但是具体到个人,只能说是:
“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。
这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。
我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。
我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。
第一阶段(10天):初阶应用
该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。
- 大模型 AI 能干什么?
- 大模型是怎样获得「智能」的?
- 用好 AI 的核心心法
- 大模型应用业务架构
- 大模型应用技术架构
- 代码示例:向 GPT-3.5 灌入新知识
- 提示工程的意义和核心思想
- Prompt 典型构成
- 指令调优方法论
- 思维链和思维树
- Prompt 攻击和防范
- …
第二阶段(30天):高阶应用
该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。
- 为什么要做 RAG
- 搭建一个简单的 ChatPDF
- 检索的基础概念
- 什么是向量表示(Embeddings)
- 向量数据库与向量检索
- 基于向量检索的 RAG
- 搭建 RAG 系统的扩展知识
- 混合检索与 RAG-Fusion 简介
- 向量模型本地部署
- …
第三阶段(30天):模型训练
恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。
到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?
- 为什么要做 RAG
- 什么是模型
- 什么是模型训练
- 求解器 & 损失函数简介
- 小实验2:手写一个简单的神经网络并训练它
- 什么是训练/预训练/微调/轻量化微调
- Transformer结构简介
- 轻量化微调
- 实验数据集的构建
- …
第四阶段(20天):商业闭环
对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。
- 硬件选型
- 带你了解全球大模型
- 使用国产大模型服务
- 搭建 OpenAI 代理
- 热身:基于阿里云 PAI 部署 Stable Diffusion
- 在本地计算机运行大模型
- 大模型的私有化部署
- 基于 vLLM 部署大模型
- 案例:如何优雅地在阿里云私有部署开源大模型
- 部署一套开源 LLM 项目
- 内容安全
- 互联网信息服务算法备案
- …
学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。
如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。