什么是Low-Level Server?

無名 发表于: 2025-07-15   最后更新时间: 2025-07-15 18:42:29   22 游览

什么是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?

MCP
发表于 2025-07-15

“Low-Level Server”这个名字,源于软件开发中一个常见的术语:“low-level”(低层/底层)。它不是说“服务器很差”,而是强调它比高级封装更接近底层、原始的实现,意思是:

1. 什么是 “Low-Level Server”?

在 MCP 框架中,Low-Level Server 是一种更接近协议核心、需要你手动控制生命周期、注册处理函数的服务器写法,也就是说:

  • 你负责:

    • 启动关闭逻辑(生命周期)
    • 注册处理函数(比如 call_tool()list_prompts() 等)
    • 管理数据资源(比如数据库连接)
    • 使用低层 API(如 server.run()

它不像官方的 mcp runmcp dev 那样封装好一整套流程(这些是 high-level 工具,自动帮你处理各种事情)。

2. 为什么叫 “low-level”?

  • 因为这是“手动控制一切”的模式,没有帮你封装生命周期、标准输入输出处理、异常处理等。
  • 和 “high-level”(高级封装) 相对:

    • high-level 例子:uv run mcp run
    • low-level:你自己写 server.run(...),你控制 lifespan,你处理 stream

就像 Python 的 asyncio

  • high-level:asyncio.run(main())
  • low-level:你用 loop = asyncio.get_event_loop() 手动跑 loop

3. 什么时候要用 low-level server?

用它是为了“更细粒度的控制”,适合这几种场景:

场景 为什么用 low-level server
你想注册多个自定义 handler,比如 get_promptcall_tool 高级接口可能不够灵活
你想控制资源生命周期,比如连接数据库、清理缓存 需要用 lifespan
你要接入自定义协议或更复杂的启动流程 高级封装不支持
你不想使用 mcp runuv run 这些不支持 low-level server

4. 总结一句话:

“low-level server” 指的是一种更底层、自由度更高、但需要你自己处理细节的服务器写法。适合需要完全控制启动流程、资源管理、自定义能力的高级开发者。

你的答案

查看MCP相关的其他问题或提一个您自己的问题