FastMCP 服务器生命周期管理机制

FastMCP 的 lifespan 机制让代码在服务器启动时运行一次、停止时清理一次,不受客户端连接数量影响。它支持通过 yield 字典共享上下文、用管道符组合多个 lifespan,并能与 FastAPI 的生命周期合并。

Lifespans 允许您在服务器启动时运行一次代码, 当它停止时清除。 与每个会话处理器不同的是, 无论客户端连接多少, 寿命都会运行一次 。 ## 基本用途 使用该 `@lifespan` 定义寿命的装饰符 : ```python from fastmcp import FastMCP from fastmcp.server.lifespan import lifespan @lifespan async def app_lifespan(server): # Setup: runs once when server starts print("Starting up...") try: yield {"started_at": "2024-01-01"} finally: # Teardown: runs when server stops print("Shutting down...") mcp = FastMCP("MyServer", lifespan=app_lifespan) ``` 命令你屈服成为 **寿命背景**,从工具中获取。 总是使用 `try/finally` 用于清除代码,以确保它运行,即使服务器被取消。 ## 访问 Lifespan 背景 访问工具中的寿命背景 `ctx.lifespan_context`: ```python from fastmcp import FastMCP, Context from fastmcp.server.lifespan import lifespan @lifespan async def app_lifespan(server): # Initialize shared state data = {"users": ["alice", "bob"]} yield {"data": data} mcp = FastMCP("MyServer", lifespan=app_lifespan) @mcp.tool def list_users(ctx: Context) -> list[str]: data = ctx.lifespan_context["data"] return data["users"] ``` ## 编织寿命 与该物质组成多个寿命 `|` 运算符 : ```python from fastmcp import FastMCP from fastmcp.server.lifespan import lifespan @lifespan async def config_lifespan(server): config = {"debug": True, "version": "1.0"} yield {"config": config} @lifespan async def data_lifespan(server): data = {"items": []} yield {"data": data} # Compose with | mcp = FastMCP("MyServer", lifespan=config_lifespan | data_lifespan) ``` 构成寿命 : - 按顺序输入( 左到右) - 按反向顺序退出( 右到左) - 合并其上下文命令( 后值覆盖早先关于冲突的值) ## 后向兼容性 现有 `@asynccontextmanager` 寿命在直接传递给FastMCP时仍然有效 : ```python from contextlib import asynccontextmanager from fastmcp import FastMCP @asynccontextmanager async def legacy_lifespan(server): yield {"key": "value"} mcp = FastMCP("MyServer", lifespan=legacy_lifespan) ``` 编剧: `@asynccontextmanager` 函数为 `@lifespan` 函数,用 `ContextManagerLifespan`: ```python from contextlib import asynccontextmanager from fastmcp.server.lifespan import lifespan, ContextManagerLifespan @asynccontextmanager async def legacy_lifespan(server): yield {"legacy": True} @lifespan async def new_lifespan(server): yield {"new": True} # Wrap the legacy lifespan explicitly for composition combined = ContextManagerLifespan(legacy_lifespan) | new_lifespan ``` ## 与 FastAPI 连接 当将 FastMCP 安装到 FastAPI 时,使用 `combine_lifespans` 运行您的应用程序的寿命和 MCP 服务器的寿命 : ```python from contextlib import asynccontextmanager from fastapi import FastAPI from fastmcp import FastMCP from fastmcp.utilities.lifespan import combine_lifespans @asynccontextmanager async def app_lifespan(app): print("FastAPI starting...") yield print("FastAPI shutting down...") mcp = FastMCP("Tools") mcp_app = mcp.http_app() app = FastAPI(lifespan=combine_lifespans(app_lifespan, mcp_app.lifespan)) app.mount("/mcp", mcp_app) ``` 见 [FastAPI 集成指南](<https://github.com/integrations/fastapi#combining-lifespans>) 详细情况。

查看原始来源