什么是Low-Level Server?我搞不明白,也没有看到介绍,如下是python的一个实现:
Low-Level Server
For more control, you can use the low-level server implementation directly. This gives you full access to the protocol and allows you to customize every aspect of your server, including lifecycle management through the lifespan API:
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from fake_database import Database # Replace with your actual DB type
from mcp.server import Server
@asynccontextmanager
async def server_lifespan(server: Server) -> AsyncIterator[dict]:
"""Manage server startup and shutdown lifecycle."""
# Initialize resources on startup
db = await Database.connect()
try:
yield {"db": db}
finally:
# Clean up on shutdown
await db.disconnect()
# Pass lifespan to server
server = Server("example-server", lifespan=server_lifespan)
# Access lifespan context in handlers
@server.call_tool()
async def query_db(name: str, arguments: dict) -> list:
ctx = server.request_context
db = ctx.lifespan_context["db"]
return await db.query(arguments["query"])
谁能帮我解释一下什么是Low-Level Server?
“Low-Level Server”这个名字,源于软件开发中一个常见的术语:“low-level”(低层/底层)。它不是说“服务器很差”,而是强调它比高级封装更接近底层、原始的实现,意思是:
1. 什么是 “Low-Level Server”?
在 MCP 框架中,Low-Level Server 是一种更接近协议核心、需要你手动控制生命周期、注册处理函数的服务器写法,也就是说:
你负责:
call_tool()
、list_prompts()
等)server.run()
)它不像官方的
mcp run
或mcp dev
那样封装好一整套流程(这些是 high-level 工具,自动帮你处理各种事情)。2. 为什么叫 “low-level”?
和 “high-level”(高级封装) 相对:
uv run mcp run
server.run(...)
,你控制lifespan
,你处理 stream就像 Python 的
asyncio
:asyncio.run(main())
loop = asyncio.get_event_loop()
手动跑 loop3. 什么时候要用 low-level server?
用它是为了“更细粒度的控制”,适合这几种场景:
get_prompt
、call_tool
lifespan
mcp run
或uv run
4. 总结一句话:
你的答案