使用Fastmcp开发MCP服务
由于时效问题,该文某些代码、技术可能已经过期,请注意!!!本文最后更新于:5 小时前
mcp服务挂载现有的fastapi上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| from fastmcp import FastMCP from fastapi import FastAPI
mcp = FastMCP(stateless_http=True)
mcp_app = mcp.http_app(path='/mcp')
@mcp.tool def add(a: int, b: int) -> int: """两数相加""" return a + b
app = FastAPI(title="API", lifespan=mcp_app.lifespan)
app.mount("/", mcp_app)
|
合并生命周期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| from contextlib import asynccontextmanager from fastapi import FastAPI from fastmcp import FastMCP
@asynccontextmanager async def app_lifespan(app: FastAPI): print("正在启动应用程序...") yield print("正在关闭应用程序...")
mcp = FastMCP("工具") mcp_app = mcp.http_app(path='/mcp')
@asynccontextmanager async def combined_lifespan(app: FastAPI): async with app_lifespan(app): async with mcp_app.lifespan(app): yield
app = FastAPI(lifespan=combined_lifespan) app.mount("/mcp", mcp_app)
|
参考:https://fastmcp.wiki/zh/integrations/fastapi#mounting-an-mcp-server