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产品经理如何学习
求大家的点赞和收藏,我花2万买的大模型学习资料免费共享给你们,来看看有哪些东西。
1.学习路线图
第一阶段: 从大模型系统设计入手,讲解大模型的主要方法;
第二阶段: 在通过大模型提示词工程从Prompts角度入手更好发挥模型的作用;
第三阶段: 大模型平台应用开发借助阿里云PAI平台构建电商领域虚拟试衣系统;
第四阶段: 大模型知识库应用开发以LangChain框架为例,构建物流行业咨询智能问答系统;
第五阶段: 大模型微调开发借助以大健康、新零售、新媒体领域构建适合当前领域大模型;
第六阶段: 以SD多模态大模型为主,搭建了文生图小程序案例;
第七阶段: 以大模型平台应用与开发为主,通过星火大模型,文心大模型等成熟大模型构建大模型行业应用。
2.视频教程
网上虽然也有很多的学习资源,但基本上都残缺不全的,这是我自己整理的大模型视频教程,上面路线图的每一个知识点,我都有配套的视频讲解。
(都打包成一块的了,不能一一展开,总共300多集)
因篇幅有限,仅展示部分资料,需要点击下方图片前往获取
3.技术文档和电子书
这里主要整理了大模型相关PDF书籍、行业报告、文档,有几百本,都是目前行业最新的。
4.LLM面试题和面经合集
这里主要整理了行业目前最新的大模型面试题和各种大厂offer面经合集。
👉学会后的收获:👈
• 基于大模型全栈工程实现(前端、后端、产品经理、设计、数据分析等),通过这门课可获得不同能力;
• 能够利用大模型解决相关实际项目需求: 大数据时代,越来越多的企业和机构需要处理海量数据,利用大模型技术可以更好地处理这些数据,提高数据分析和决策的准确性。因此,掌握大模型应用开发技能,可以让程序员更好地应对实际项目需求;
• 基于大模型和企业数据AI应用开发,实现大模型理论、掌握GPU算力、硬件、LangChain开发框架和项目实战技能, 学会Fine-tuning垂直训练大模型(数据准备、数据蒸馏、大模型部署)一站式掌握;
• 能够完成时下热门大模型垂直领域模型训练能力,提高程序员的编码能力: 大模型应用开发需要掌握机器学习算法、深度学习框架等技术,这些技术的掌握可以提高程序员的编码能力和分析能力,让程序员更加熟练地编写高质量的代码。
1.AI大模型学习路线图
2.100套AI大模型商业化落地方案
3.100集大模型视频教程
4.200本大模型PDF书籍
5.LLM面试题合集
6.AI产品经理资源合集***
👉获取方式:
😝有需要的小伙伴,可以保存图片到wx扫描二v码免费领取【保证100%免费】🆓