迁移 2025 年代的服务器

阅读约需 82分钟 分钟,9节中含6个示例。

版次 2026.11.14 示例于 2026年11月19日 通过 70个示例中有70个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.14。 阅读原文

读完本章,你将能够把一个按 2025 年各修订版和 Python SDK 1.x 系列编写的 Model Context Protocol 服务器,迁移到修订版 2026-07-28 规范和 mcp 2.3.0 上。关于目标的各项论断,在该修订版和该 SDK 版本下成立。你会找出它的依赖项,移除它的会话,让它脱离 HTTP+SSE 传输,替换采样、根目录、日志和动态客户端注册(Dynamic Client Registration),移植代码,并在旧客户端仍然存在期间同时为两个时代的客户端提供服务。

前面每一章构建的都是商店的服务器,也就是本书唯一的案例,并且从一开始就按固定的修订版把它写成 shop-support。大多数团队并不是从这里起步的。他们手里有一个由 2025 年代的团队依据 2025-03-26 至 2025-11-25 各修订版和 SDK 1.x 编写的服务器,还有仍然使用这些修订版的宿主。本章是唯一讲授 2025 年协议的一章,而且只把它当作迁移的起点来讲。

从那些修订版到固定的修订版之间,Model Context Protocol(MCP)移除了 initialize 握手和协议会话,移除了服务器在调用中途向客户端推送的请求,并弃用了五项功能以及某个采样字段的两个取值(变更日志)。商店的 2025 年代服务器用到了这些修订版所移除或弃用的大部分内容。下面的代码清单就是这台服务器,是团队为 mcp==1.30.0 编写的样子:

"""shop-support as a 2025-era team wrote it, for SDK 1.x and revisions up to 2025-11-25."""
import os

from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
from mcp.types import SamplingMessage, TextContent
from pydantic import BaseModel

import shop_calls                                   # the shop's API, as chapter 3 calls it; not shown

server = FastMCP("shop-support", "Answers the support team's questions about orders, refunds and stock.",
                 port=8000, stateless_http=False)
quotes: dict[ServerSession, dict] = {}              # each connection's open quote

class Release(BaseModel):
    release: bool

@server.tool()
async def quote_refund(order_id: str, ctx: Context) -> dict:
    quotes[ctx.session] = quote = shop_calls.quote(order_id)
    await ctx.info(f"quoted {quote['amount']} for {order_id}")
    return quote

@server.tool()
async def issue_refund(ctx: Context) -> dict:
    quote = quotes.pop(ctx.session)                 # the quote this connection made last
    if not quote["within_limit"]:
        answer = await ctx.elicit(f"Refund {quote['amount']}? It is above the policy limit.", Release)
        if answer.action != "accept" or not answer.data.release:
            return shop_calls.hold(quote)
    return shop_calls.refund(quote)

@server.tool()
async def triage_ticket(text: str, ctx: Context) -> str:
    reply = await ctx.session.create_message(
        [SamplingMessage(role="user", content=TextContent(type="text", text=text))],
        max_tokens=20, system_prompt="Name the one shop tool this ticket needs.")
    return reply.content.text

@server.tool()
async def save_restock_report(ctx: Context) -> str:
    folder = (await ctx.session.list_roots()).roots[0].uri.path
    return shop_calls.write_restock_report(folder)

server.run(transport="sse" if os.environ.get("SHOP_OLD_HOSTS") else "streamable-http")   # HTTP+SSE: the 2024 transport

该清单是 2025 年代的商店服务器。本章还有一个共享模块 lib.legacy,以文本形式保存这份清单,同时保存宿主的 OAuth 设置和查找各个依赖项的规则。它只用于展示和扫描,从不运行。SDK 1.x 和 SDK 2.x 都是 mcp 这个发行包,因此一个环境只能装其中一个,而各示例的环境固定为 2.x。每个示例要么在 2.x 上运行移植后的服务器,要么只读取该清单。shop_calls 代表第 3 章中的工具对商店 API 发出的调用,清单中没有显示它。

这部分尚未翻译,因此以英文显示。

Inventory what the old server depends on

最近一次修改见于版次 2026.11.14

A migration starts with a list, because the pinned revision treats each old feature in one of three ways, and each way sets its own deadline. The first group was removed at revision 2026-07-28, with no window: the initialize handshake, protocol sessions and the Mcp-Session-Id header, requests a server sends to the client in the middle of a call, whatever they ask for, the HTTP GET stream, resources/subscribe, ping, logging/setLevel and stream resumability (changelog). A client at the pinned revision never uses any of them, so code that depends on one fails for that client the first time it runs.

The second group is deprecated: roots, sampling, logging, the HTTP+SSE transport and Dynamic Client Registration. The changelog says that roots, sampling and logging stay "fully functional during the deprecation window" (same source), and the specification's registry gives each deprecated feature a migration path and an earliest removal (deprecated features). An earliest removal is the date when a feature becomes eligible to go, not when it goes. Removal is a decision the core maintainers make when they prepare a revision, so a feature may stay deprecated much longer (feature lifecycle). The window runs at least twelve months from the release of the revision that first marks the feature deprecated, and it can be cut to ninety days for an active security risk, so the windows differ from feature to feature. Dropping a feature from the specification doesn't oblige an SDK to drop it, because each SDK's own policy decides (same source).

The third kind isn't a protocol change at all. SDK 2.x renamed and moved parts of the 1.x API, so a 1.x server fails to start on 2.x even where the protocol didn't change (migration guide).

We parse the server listing in this chapter and the host's OAuth setup, shown in Replace dynamic client registration, with Python's ast module, and match each node against lib.legacy.RULES. Each rule names a dependency, its status at the pinned revision, its replacement and, for a deprecated feature, the registry's earliest removal. The scan then prints them grouped by status, with the function each one sits in.

scan-a-2025-server.py Python 3.12.15 通过
"""Sorts the 2025-era server's dependencies, and its host's OAuth setup, into removed, deprecated and SDK changes, eachwith its replacement. The prose's point, that removed dependencies fail for every client at the pinned revision, rests on the first group'scount and the functions it names."""import astfrom lib import legacyfound: dict[str, list[str]] = {rule.feature: [] for rule in legacy.RULES}def where(tree: ast.Module, node: ast.AST, listing: str) -> str:    """The function a node sits in, or the listing's setup when it sits in none."""    for function in ast.walk(tree):        if isinstance(function, ast.AsyncFunctionDef | ast.FunctionDef) and node in ast.walk(function):            return function.name    return f"{listing} setup"                # module-level code, outside every functionfor listing, source in legacy.LISTINGS.items():    tree = ast.parse(source)                   # parsed, never run: SDK 1.x can't install beside 2.x    for node in ast.walk(tree):        for rule in legacy.RULES:            # each function is listed once per feature, however many of its nodes match            if rule.matches(node) and where(tree, node, listing) not in found[rule.feature]:                found[rule.feature].append(where(tree, node, listing))print("written for:", legacy.WRITTEN_FOR)for kind in ("removed", "deprecated", "sdk"):    rules = [rule for rule in legacy.RULES if rule.kind == kind and found[rule.feature]]   # a rule with no match is left out    print(f"{kind} dependencies:", len(rules))    for rule in rules:        print(f"  {rule.feature}: {', '.join(found[rule.feature])} -> {rule.replacement}")        if rule.removal:                          # only deprecated features have a removal date            print(f"  {rule.feature} earliest removal: {rule.removal}")
输出python scan-a-2025-server.py
written for: mcp==1.30.0
removed dependencies: 2
  sessions: server setup, quote_refund, issue_refund -> a handle the server mints, passed back as a tool argument
  pushed requests: triage_ticket, issue_refund, save_restock_report -> an input request in a Multi Round-Trip Request
deprecated dependencies: 5
  sampling: triage_ticket -> a model call the host or the server makes itself
  sampling earliest removal: first revision released on or after 2027-07-28
  roots: save_restock_report -> a tool parameter, a resource URI or server configuration
  roots earliest removal: first revision released on or after 2027-07-28
  logging: quote_refund -> stderr on stdio, or OpenTelemetry
  logging earliest removal: first revision released on or after 2027-07-28
  HTTP+SSE transport: server setup -> Streamable HTTP
  HTTP+SSE transport earliest removal: three months after SEP-2596 reaches Final
  dynamic client registration: host setup -> a Client ID Metadata Document
  dynamic client registration earliest removal: first revision released on or after 2027-07-28
sdk dependencies: 3
  FastMCP: server setup -> mcp.server.mcpserver.MCPServer
  positional instructions: server setup -> instructions= by keyword
  transport settings on the constructor: server setup -> arguments to run() or streamable_http_app()

The removed ones come first, because they fail for every client at the pinned revision. The scan found 2 removed dependencies, 5 deprecated ones and 3 SDK changes. The removed dependencies are the sessions that quote_refund and issue_refund share, and the requests that three tools push in the middle of a call: ctx.elicit in issue_refund, create_message in triage_ticket and list_roots in save_restock_report.

So sampling and roots are on both lists. As features they are deprecated, and they keep working through their window: for a 2025-era client as written, and for a client at the pinned revision only when the server asks for them through a round trip, as Replace sampling, roots and logging shows. Pushed mid-call, they fail for that client as ctx.elicit does, with SDK 2.3.0 raising NoBackChannelError (mcp/server/_streamable_http_modern.py). Of sampling, roots and logging, only logging works as written for a client at the pinned revision, and only for a request whose _meta asks for a log level. For any other request the SDK drops the line (mcp/server/connection.py).

Four of the deprecated features share one earliest removal, the first revision released on or after 2027-07-28. The HTTP+SSE transport's date is different, and Move from HTTP+SSE to Streamable HTTP gives it.

The SDK at 2.3.0 doesn't warn about all of these either. Its sampling, roots and logging APIs emit MCPDeprecationWarning, a UserWarning that prints by default (what's new). Its HTTP+SSE app and client and its registration code carry no deprecation marker: we searched mcp/server/sse.py, mcp/client/sse.py, mcp/server/auth/handlers/register.py and mcp/client/auth/oauth2.py for "deprecat" and found nothing. A server can run on 2.x without a single warning and still depend on two deprecated features.

Working rule: Inventory before you change anything, and sort the list by status. Fix every removed dependency before you let a client at the pinned revision connect, because there is no window for it, and count every request the server pushes mid-call as removed, even when the feature it asks for is only deprecated. Give each deprecated one a date of your own, earlier than the registry's earliest removal, and don't wait for warnings: run a scan like this one in CI, because the SDK is silent about some deprecated features.

移除 initialize 与会话 ID

最近一次修改见于版次 2026.11.11

盘点旧服务器的依赖项中的扫描首先列出了会话。在 2025 年的各个修订版中,连接以 initialize 开始,Streamable HTTP 服务器可以在应答中分配一个会话 ID。随后,客户端必须在每个请求中发送 Mcp-Session-Id,在服务器返回 404 时开启新的会话,并用 DELETE 结束会话(2025-11-25 传输层)。服务器可以按会话保存任何它想保存的内容。

固定的修订版取消了握手和会话。每个请求都在 _meta 中携带其协议版本和客户端的能力。客户端通过 server/discover 询问服务器支持什么,每个服务器都必须实现这一方法;如果服务器需要跨调用保存状态,就生成一个显式的句柄,并让客户端把它作为普通的工具参数传回来(变更日志)。在每个请求中携带版本和能力展示了 _meta 中的各个键。

2025 年时代的服务器为每个会话保存一份状态。quote_refund 把报价存放在 ctx.session 之下,这是 SDK 为连接提供的对象,而 issue_refund 不接受参数,它会为该连接最后生成的报价退款。在 SDK 1.x 下,一个连接的所有请求共用同一个对象(见 1.x 中的 mcp/server/lowlevel/server.py),因此这种做法行得通。我们围绕第 3 章的报价和退款函数,把这两个工具原样迁移到 2.x,并在固定的修订版下用同一个客户端各调用一次。然后,我们以同样的方式调用第 3 章的服务器:它的 quote_refund 返回一个 quote_id,由 issue_refund 接收。

stateless-after-migration.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Ports the 2025 server's per-connection quote to SDK 2.x unchanged, then with the handle the pinned revision asks for.The prose's point rests on the session-keyed failure, the count of session objects, and the handle's refund line."""import asyncioimport osfrom mcp import Clientfrom mcp.server.mcpserver import Context, MCPServerfrom mcp.server.mcpserver.exceptions import ToolErrorfrom lib import confirmations, loopback, shop_api, shop_toolschapter3 = confirmations.chapter3_tools()          # quote_refund and issue_refund from lib.shop_toolsserver = MCPServer("shop-support", version="0.12.0")quotes = {}                                        # the 2025 code: each connection's open quote, by its sessionsessions_seen = set()@server.tool(description="Quote a refund for a whole order, for issue_refund to refund.")def quote_refund(order_id: str, ctx: Context) -> str:    sessions_seen.add(id(ctx.session))       # each request gets its own session object at the pinned revision    quotes[ctx.session] = chapter3["quote_refund"].fn(order_id, sku="KG-1050")   # chapter 3's quote needs a SKU; the port pins one    return f"Quoted {quotes[ctx.session].amount}."@server.tool(description="Refund the quote this connection made last.")def issue_refund(ctx: Context) -> shop_tools.Refund:    sessions_seen.add(id(ctx.session))    if ctx.session not in quotes:        raise ToolError("There is no open quote in this session. Call quote_refund first.")    return chapter3["issue_refund"].fn(quotes.pop(ctx.session).quote_id)   # pop: a quote is used onceasync def main() -> None:    with loopback.serve(shop_api.create_app()) as api_url:        os.environ.update(shop_api.server_env(api_url))      # both servers run in this process        with loopback.serve(server.streamable_http_app()) as old, \             loopback.serve(shop_tools.create_server().streamable_http_app()) as new:            async with Client(old + "/mcp") as client:                await client.call_tool("quote_refund", {"order_id": "O-2415"})                print("session-keyed issue_refund:", (await client.call_tool("issue_refund", {})).content[0].text)                print("session objects in two calls:", len(sessions_seen))            async with Client(new + "/mcp") as client:                quote = await client.call_tool("quote_refund", {"order_id": "O-2415", "sku": "KG-1050"})                refund = await client.call_tool("issue_refund", {"quote_id": quote.structured_content["quote_id"]})                print("handle issue_refund:", refund.structured_content["status"], refund.structured_content["amount"])asyncio.run(main())
输出python stateless-after-migration.py
session-keyed issue_refund: Error executing tool issue_refund: There is no open quote in this session. Call quote_refund first.
session objects in two calls: 2
handle issue_refund: requested 23.98

原样运行时,迁移后的代码在第二次调用时失败了:“Error executing tool issue_refund: There is no open quote in this session. Call quote_refund first.”这两次调用来自同一个客户端、同一个进程,却看到了 2 个不同的会话对象。在固定的修订版下,不存在可供会话归属的连接,因此 SDK 为每个请求单独提供一个会话对象。存储报价时没有任何报错,只有在读取时才会暴露这个缺陷。如果服务器以 Mcp-Session-Id 头作为状态的键,情况会更糟:在固定的修订版下,没有客户端会发送该头,于是所有客户端的状态都会落在同一个键 None 之下。

使用句柄之后,退款成功了:requested 23.98。这正是围绕任务而非端点设计工具为第 3 章选择的设计。规范对这类句柄的指导是:句柄应当不透明且会过期,启用认证的服务器应在每次调用时,针对该句柄检查调用方的授权(工具)。防止服务器成为混淆代理把商店的报价 ID 绑定到它们所颁发给的客户。存放在某个进程内存中的句柄仍会随进程消亡,因此一旦服务器以多个副本运行,句柄就应放入共享存储,正如不借助粘性会话运行多个副本用 SQLite 所做的那样。

工作准则: 在旧服务器中搜索所有用到会话、会话 ID 以及任何按连接存储内容的地方,把每一份状态都变成句柄:由一个工具返回,下一个工具将其作为参数接收。让句柄保持不透明,给它设定一个过期时间,并在创建它的工具的描述中写明;每次调用时检查调用方是否有权使用它,并把它存放在每个副本都能读取的地方。后续调用所需的任何内容,都不要保存在以会话为键的字典中,即使面对仍然带有会话的 2025 年时代的客户端也是如此。

从 HTTP+SSE 迁移到 Streamable HTTP

最近一次修改见于版次 2026.11.11

移除 initialize 与会话 ID一节中的会话属于 Streamable HTTP 的 2025 年形态。商店 2025 年代的服务器中还保留着另一种更早的传输方式:当设置了 SHOP_OLD_HOSTS 时,它的最后一行会提供 HTTP+SSE 服务,这正是 2025-03-26 版本所取代的传输方式。在这种传输方式中,客户端在一个端点上保持事件流打开,并把消息通过 POST 发送到另一个端点(Streamable HTTP)。SDK 1.x 在 /sse 和 /messages/ 上提供这一对端点(在 1.x 中位于 mcp/server/fastmcp/server.py)。2025-03-26 版本用 Streamable HTTP 取代了它(2025-03-26 变更日志),而本书固定的版本将它纳入生命周期政策,并给出更短的窗口期(变更日志)。

对服务器而言,这次迁移就是一次删除。移植后的商店服务器在一个端点上提供 streamable_http_app() 或 run(transport="streamable-http"),做法见将服务器从 stdio 迁移到 HTTP,其工具无需任何改动。在固定版本下,每个通过 HTTP 连接的客户端都使用 Streamable HTTP,所以传输方式本身并不构成阻碍。真正决定旧传输方式何时可以移除的,是仍通过 HTTP+SSE 连接的宿主,而按定义它们都是 2025 年代的客户端。

这些宿主有两条出路。必须继续支持它们的服务器,可以在 Streamable HTTP 端点旁同时托管旧的 SSE 端点和 POST 端点,规范自 2025-03-26 版本起就允许这样做(Streamable HTTP)。SDK 2.3.0 仍然提供 MCPServer.sse_app(),其两个路径与 1.x 相同,并且支持 run(transport="sse")(mcp/server/mcpserver/server.py)。正如盘点旧服务器的依赖项一节所发现的,这两者都不会触发弃用警告。另一条出路是让宿主迁移到 Streamable HTTP,SDK 1.x 的客户端已经支持它(在 1.x 中位于 mcp/client/streamable_http.py)。

注册表中 HTTP+SSE 最早的移除日期是 three months after SEP-2596 reaches Final,这一日期可能已经过去。这并不意味着 SDK 会在那一天删除 sse_app(),因为每个 SDK 各自决定(功能生命周期)。当 SEP-2596 制定生命周期政策时,这种传输方式已被弃用一年多,因此它获得的是三个月的宽限期,而不是十二个月,该提案页面将其标记为 Final,但没有给出日期。这一日期意味着宿主不能指望该传输方式在下一个版本中继续存在,你也不能。

商店的支持团队确定了一个日期。只要服务器日志中仍显示有宿主连接到 /sse,旧端点就继续保留,团队会把端点下线的日期告知每个此类宿主的所有者。到那时仍无法迁移的宿主,可以继续使用 SDK 1.x,对接旧服务器的 1.x 部署,相关内容见将代码从 SDK 1.x 移植到 2.x。

工作准则: 除非日志显示仍有宿主在使用 HTTP+SSE 传输,否则应从服务器中删除它,而不是移植它。如果有,就在 Streamable HTTP 端点旁提供旧端点,按客户端记录每一次对它们的连接,并确定一个移除日期,告知每个宿主的所有者。应把该传输方式视为已经符合移除条件,因为它的窗口期是三个月,而不是十二个月。

替换采样、根目录和日志

最近一次修改见于版次 2026.11.11

盘点旧服务器的依赖找到的依赖中,有三项叠加了两处变化,最好把它们分开看。第一处是机制。2025 年的服务器会在调用进行到一半时向客户端发出自己的请求(elicitation/create、sampling/createMessage、roots/list),然后等待答复。固定修订版指出,这种模式“不再受支持”,并且这是一项破坏性变更。服务器改为通过多轮往返请求来提问,即返回一个输入请求,其值可以是 ElicitRequest、CreateMessageRequest 或 ListRootsRequest(多轮往返请求)。第二处是这些功能本身。根目录、采样和日志均已弃用,注册表中给出了迁移路径:根目录迁移到工具参数、资源 URI 或服务器配置;采样迁移到直接对接模型提供方的 API;日志在 stdio 上迁移到 stderr,或迁移到 OpenTelemetry(已弃用的功能)。

因此,多轮往返请求取代的是推送,而不是采样。把 sampling/createMessage 搬进输入请求的服务器,依赖的仍然是一项已弃用的功能。三者之中,只有征询(elicitation)没有被弃用,所以它是唯一值得迁入往返流程并保留的。

2025 年版本的 issue_refund 用 ctx.elicit 推送确认请求,这在固定修订版上会失败,正如了解无状态服务器为何不能等待答复所示。移植后的版本改用解析器来提问。声明为 Annotated[Release, Resolve(confirm)] 的参数,会在工具运行之前通过执行 confirm 来填充;当 confirm 返回 Elicit(...) 时,SDK 会询问宿主端的用户(用征询获取结构化输入)。confirm 只在商店的 API 将退款扣下等待确认时才提问。我们引用订单 O-2289,其退款超出了政策的上限,手动调用一次 issue_refund 查看第一轮,然后让 Client 与第 5 章中的脚本化负责人一起运行各轮,这位负责人会答复同意。

replace-pushed-requests.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Ports the 2025 server's pushed confirmation to a resolver that serves both eras, and its log line to stderr. The prose'spoint rests on the first round's result and the question it asks, and the refund's status after the lead's yes."""import asyncioimport loggingimport osfrom typing import Annotatedfrom mcp import Clientfrom mcp.server.mcpserver import Elicit, Resolvefrom pydantic import BaseModelfrom lib import confirmations, loopback, shop_api, shop_toolsserver, held = confirmations.shop_server(version="0.12.0")   # chapter 3's other tools; held is its issue_refundlog = logging.getLogger("shop-support")                       # to stderr, not to the clientclass Release(BaseModel):    release: booldef confirm(quote_id: confirmations.QuoteId) -> Elicit[Release] | Release:    refund = held.fn(quote_id)                                # the same quote always gives the same refund    if refund.status != "needs_confirmation":        return Release(release=False)                         # nothing held, so nothing to ask    # returning Elicit asks the person at the host; the SDK sends the question in the client's form    return Elicit(f"Refund {refund.amount} on order {refund.order_id}? It is above the policy limit.", Release)@server.tool(description=shop_tools.DESCRIPTIONS["issue_refund"], annotations=held.annotations)def issue_refund(quote_id: confirmations.QuoteId, answer: Annotated[Release, Resolve(confirm)]) -> shop_tools.Refund:    refund = held.fn(quote_id)    if refund.status == "needs_confirmation" and answer.release:        refund = confirmations.release(refund)    log.info("refund %s is %s", refund.refund_id, refund.status)    return refundasync def main() -> None:    with loopback.serve(shop_api.create_app()) as api_url:        os.environ.update(shop_api.server_env(api_url))      # the server runs in this process        with loopback.serve(server.streamable_http_app()) as url:            async with Client(url + "/mcp", elicitation_callback=confirmations.say_yes) as client:                quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content                first = await client.session.call_tool("issue_refund", {"quote_id": quote["quote_id"]},                                                        allow_input_required=True)   # returns the input request, not an answer                print("first round:", first.result_type)                print("first round asks:", ", ".join(r.method for r in first.input_requests.values()))                refund = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})   # Client answers with the lead's yes                print("refund after the lead's yes:", refund.structured_content["status"])asyncio.run(main())
输出python replace-pushed-requests.py
first round: input_required
first round asks: elicitation/create
refund after the lead's yes: requested

第一轮返回的是 input_required,带有一个问题 elicitation/create:这与 2025 年的服务器推送的请求相同,只是装在结果里送回。负责人同意之后,退款的状态为 requested。该解析器同样适用于 2025 年的客户端,因为 SDK 会按客户端所用修订版的形式发送问题(mcp/server/mcpserver/resolve.py)。通过窗口期同时服务新旧客户端会同时运行两者。

移植后的日志行使用 Python 的 logging,而不是 ctx.info。MCPServer 在构建时(mcp/server/mcpserver/utilities/logging.py)把日志配置为输出到 stderr,因此这一行进入服务器自己的日志,绝不会发给客户端。在 stdio 上,stdout 只承载协议消息,服务器的日志应当写到 stderr(stdio)。另一条路径见用 OpenTelemetry 追踪调用。

采样整体移除。2025 年版本的 triage_ticket 通过采样询问宿主的模型某张工单需要哪个工具,移植时删除了这个工具。宿主自己的模型本来就会阅读每张工单并挑选工具(处理工单队列),所以服务器是在请宿主做宿主本来就在做的事。需要模型来完成自身工作的服务器,应使用自己的凭据调用模型提供方,这样它还能自行选择模型并承担费用。

save_restock_report 曾向客户端请求其根目录,并写入第一个根目录。移植后的版本把文件夹作为参数接收,并在解析路径之后,将其与服务器配置在 SHOP_EXPORT_DIRS 中允许的文件夹进行核对,这样 .. 就无法跳出允许的范围。

roots-to-a-parameter.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Replaces the 2025 server's roots with a folder parameter that the server checks against its own allow-list. The prose'spoint rests on the two export lines: the allowed folder saves, and the path that climbs out is refused."""import asyncioimport osfrom pathlib import Pathfrom mcp import Clientfrom mcp.server.mcpserver import MCPServerfrom mcp.server.mcpserver.exceptions import ToolErrorfrom lib import loopback, restock, shop_apiserver = MCPServer("shop-support", version="0.12.0")EXPORT_DIRS = [Path(d).resolve() for d in os.environ.get("SHOP_EXPORT_DIRS", "exports").split(",")]   # the allow-list; a relative entry resolves from the working directory@server.tool(description="Recount stock and save the restock report as CSV in export_dir, a folder the server allows.")async def save_restock_report(export_dir: str) -> str:    folder = Path(export_dir).resolve()                  # "exports/../private" resolves outside exports    if folder not in EXPORT_DIRS:            # an exact match, so a subfolder of an allowed folder is refused too        raise ToolError(f"{export_dir} isn't an export folder. Use one of: {', '.join(d.name for d in EXPORT_DIRS)}.")    report = await restock.run(below=30, seconds=0)   # reports SKUs under 30 units; seconds=0 skips the per-SKU wait    folder.mkdir(exist_ok=True)    (folder / "restock.csv").write_text("sku,units\n" + "".join(f"{r.sku},{r.units}\n" for r in report.reorder))    return f"Saved {len(report.reorder)} products to reorder in {export_dir}/restock.csv."async def main() -> None:    with loopback.serve(shop_api.create_app()) as api_url:        os.environ.update(shop_api.server_env(api_url))      # the server runs in this process        async with Client(server) as client:            for folder in ("exports", "exports/../private"):                saved = await client.call_tool("save_restock_report", {"export_dir": folder})                print(f"export to {folder}:", saved.content[0].text)asyncio.run(main())
输出python roots-to-a-parameter.py
export to exports: Saved 5 products to reorder in exports/restock.csv.
export to exports/../private: Error executing tool save_restock_report: exports/../private isn't an export folder. Use one of: exports.

允许的文件夹通过了检查:“Saved 5 products to reorder in exports/restock.csv.” 跳出范围的路径则被拒绝:“Error executing tool save_restock_report: exports/../private isn't an export folder. Use one of: exports.” 现在由宿主或模型传入文件夹,而写入位置由服务器而不是客户端决定。

工作准则: 把每一个推送式征询都迁入解析器,它同时适用于两个时代的客户端。删除采样而不是迁移它:让宿主的模型完成模型工作,或由服务器使用自己的凭据调用提供方。把根目录改成参数,并对照服务器配置中的允许列表进行检查;把日志行发送到 stderr 和你的追踪系统,绝不发给客户端。

这部分尚未翻译,因此以英文显示。

Replace dynamic client registration

最近一次修改见于版次 2026.11.11

The last deprecated dependency that the inventory found is in the host, not the server, but it decides whether the support team's host can get a token for the ported server at all. The 2025 host registered itself with each authorization server it met, through OAuth Dynamic Client Registration:

"""How the support team's 2025 host got tokens for shop-support: it registered itself with each authorization server."""
from mcp.client.auth import OAuthClientProvider
from mcp.shared.auth import OAuthClientMetadata

auth = OAuthClientProvider(
    server_url="https://mcp.fernhill.example/mcp",
    client_metadata=OAuthClientMetadata(client_name="Support desk", redirect_uris=["http://127.0.0.1:3030/callback"]),
    storage=token_store, redirect_handler=open_browser, callback_handler=wait_for_code,
)

SDK 1.x's OAuthClientProvider registers this way when it isn't given a client_metadata_url (mcp/client/auth/oauth2.py in 1.x). The pinned revision deprecates Dynamic Client Registration in favour of Client ID Metadata Documents, which revision 2025-11-25 had already recommended, and keeps it for backward compatibility (changelog; 2025-11-25 changelog). Its earliest removal is the first revision released on or after 2027-07-28.

A Client ID Metadata Document makes the client ID an https:// URL where the host publishes its own metadata, so no authorization server has to register it first. Identify the client with a metadata document builds one for the shop's host and shows the order the pinned revision ranks the options in: pre-registered credentials, then a metadata document, then registration.

The port is one argument. The host passes its document's URL as client_metadata_url, and SDK 2.x's OAuthClientProvider then uses the document when the authorization server advertises client_id_metadata_document_supported. When the server doesn't, the provider falls back to registration without saying so, as chapter 8's example showed, and the SDK's registration code at 2.3.0 raises no deprecation warning. So the authorization server is half of the port. It has to advertise metadata document support, and it should keep its registration endpoint only for the window and only for hosts that can't publish a document.

Two rules from the pinned revision matter while registration lingers. A client MUST key the credentials it stores by the authorization server's issuer and register again when the authorization server changes (changelog; client registration). A client that registers MUST send an appropriate application_type, which SHOULD be native for a host that runs on the user's machine with a loopback redirect, as this one does (changelog; client registration). A 2025 host that stored one client ID per MCP server's URL breaks the first rule the day the shop moves its authorization server.

Working rule: Publish a Client ID Metadata Document for every host and pass its URL as client_metadata_url. Make every authorization server you run advertise support for it, keep its registration endpoint only until the hosts that need it have moved, and log which kind of client ID each token was issued to, so that you can see when registration traffic has stopped.

将代码从 SDK 1.x 移植到 2.x

最近一次修改见于版次 2026.11.11

前面各节改变的是商店服务器的行为。盘点旧服务器的依赖项一节发现的 SDK 变更是另一项工作,它们会使旧文件无法在 2.x 上启动。有两个事实决定了这项工作的形态。第一,1.x 系列仍在维护。首个 2.x 版本与一个 1.x 版本都在 2026-07-28 发布,即固定修订版本的发布当天;2026-09-07 的 1.x 版本,mcp==1.30.0,是“1.x 系列的维护版本”(PyPI;发布说明)。迁移指南称,1.x 系列将继续获得关键缺陷修复和安全补丁,且尚无人公布终止日期(迁移指南)。第二,两个系列是同一个 mcp 发行包,因此一次部署只能运行其中之一,不能两者并存。

指南列出了这些不兼容变更。涉及类似商店服务器的有:mcp.server.fastmcp.FastMCP 变为 mcp.server.mcpserver.MCPServer;McpError 变为 MCPError(code, message, data);字段改为 snake_case(input_schema、is_error);HTTP 客户端是 httpx2,不再是 httpx;streamablehttp_client 已移除,由 streamable_http_client 取代;host、port、stateless_http 和 json_response 从构造函数移到了 run() 和 streamable_http_app();instructions 不再是第二个位置参数;不再读取 MCP_* 环境变量;WebSocket 传输已移除;ctx.log 接受 data,而不是 message(迁移指南)。

其中多数会明显报错,这正是我们希望的那一类。有一项不会。我们在 2.3.0 上运行 2025 年代服务器的设置代码,观察导入、它抛出的异常以及构造函数。然后我们构建两次服务器,一次按原样传参,一次按移植后的写法,并分别询问客户端看到了什么。

port-to-sdk-2.py Python 3.12.15 · mcp 2.3.0 通过
"""Tries the 2025 server's setup lines on SDK 2.x: two breaks fail with an error, and one fails silently. The prose's point,that the second positional argument now sets the title, rests on the two title and instructions lines a client sees."""import asynciofrom mcp import Clientfrom mcp.server.mcpserver import MCPServerINSTRUCTIONS = "Answers the support team's questions about orders, refunds and stock."try:    from mcp.server.fastmcp import FastMCP          # the 2025 server's first importexcept ModuleNotFoundError as error:    print("import FastMCP:", str(error).split(". ", 1)[1].split("; see")[0])   # the message after its first sentencetry:    from mcp.shared.exceptions import McpError      # what 1.x tools raised for protocol errorsexcept ImportError as error:    print("import McpError:", str(error).split(" (")[0])   # drops the parentheticaltry:    MCPServer("shop-support", instructions=INSTRUCTIONS, port=8000, stateless_http=False)   # port and stateless_http moved to run() and streamable_http_app() in 2.xexcept TypeError as error:    print("port on the constructor:", error)as_written = MCPServer("shop-support", INSTRUCTIONS)                     # 1.x's second argument was instructionsported = MCPServer("shop-support", instructions=INSTRUCTIONS, version="0.12.0")   # a keyword, so the string can't become the titleasync def main() -> None:    for label, server in (("as written", as_written), ("ported", ported)):        async with Client(server) as client:            print(f"{label} title:", client.server_info.title)            print(f"{label} instructions:", client.instructions)asyncio.run(main())
输出python port-to-sdk-2.py
import FastMCP: This is mcp 2.x, where FastMCP was renamed to MCPServer (from mcp.server.mcpserver import MCPServer) and other APIs changed
import McpError: cannot import name 'McpError' from 'mcp.shared.exceptions'
port on the constructor: MCPServer.__init__() got an unexpected keyword argument 'port'
as written title: Answers the support team's questions about orders, refunds and stock.
as written instructions: None
ported title: None
ported instructions: Answers the support team's questions about orders, refunds and stock.

导入失败了,错误信息指出了重命名以及应改用的导入:“This is mcp 2.x, where FastMCP was renamed to MCPServer (from mcp.server.mcpserver import MCPServer) and other APIs changed”(mcp/server/fastmcp.py,该文件的存在只是为了抛出这一错误)。McpError 失败时给出“cannot import name 'McpError' from 'mcp.shared.exceptions'”,构造函数失败时给出“MCPServer.init() got an unexpected keyword argument 'port'”。每条信息都指向需要修改的那一行。

按原样传参的构造函数没有失败。在 2.x 中,第二个位置参数是 title(mcp/server/mcpserver/server.py),因此服务器的 instructions 变成了它的标题。客户端看到的标题是“Answers the support team's questions about orders, refunds and stock.”,而没有 instructions(None),把服务器 instructions 放入模型上下文的宿主会悄无声息地丢失它们。以关键字方式传入 instructions= 后,移植后服务器的标题是 None,其 instructions 也会送达。端口号移到最后一行,即 server.run(transport="streamable-http", port=8000)。

这些静默的不兼容变更有一个共同形态:要么是仍能通过类型检查的参数,要么是无人读取的设置,如 MCP_* 环境变量。要发现它们,应对照代码阅读指南的列表,而不是等待报错,并用类似“构建两次服务器”的测试检查客户端看到的内容。

工作准则: 将 2025 年代的服务器固定在 mcp<2,直到其移植版本通过测试,然后在一次变更中完成移植:先处理报错所指出的导入和重命名,再处理迁移指南中的每一项静默变更,并用针对客户端所见内容的测试加以检查。之后精确固定 2.x 版本,并把每个 2.x 版本都视为需要测试的变更,因为 SDK 的警告和默认值会在版本之间变化。

这部分尚未翻译,因此以英文显示。

Serve old and new clients through the window

最近一次修改见于版次 2026.11.14

The ported server from Replace sampling, roots and logging answers clients at the pinned revision. The support team's hosts don't all move on one day, and a 2025-era host can't move forward on its own: it sends initialize and expects an answer. The pinned revision allows a dual-era server, which serves both eras on the same endpoint. An initialize request selects the 2025 semantics for that process on stdio or that session on HTTP, and a request with the pinned revision's _meta is served statelessly. A server that serves only the pinned revision SHOULD name the versions it supports in its error to initialize, because a 2025 client can't discover them any other way (versioning). On the other side, a 2.x Client in its default mode tries server/discover first and falls back to initialize (mcp/client/_probe.py; Call the tool from a client).

At 2.3.0, MCPServer.streamable_http_app() is dual-era with nothing to configure. It reads each request's MCP-Protocol-Version header: a request with no header, or with a version from 2024-11-05 to 2025-11-25, goes to the 2025 handler with its sessions, and anything else goes to the stateless handler (mcp/server/streamable_http_manager.py). The 2025 path keeps its sessions in the memory of the process that made them, so 2025-era clients keep their stickiness requirements (what's new).

We serve the ported server's app as replica a, recorded with chapter 6's lib.wire.record_http, and a second copy of it as replica b. A client in the default mode and a client in mode="legacy", which speaks the 2025 handshake, each quote a refund above the policy's limit and issue it on replica a, with the scripted lead saying yes. Then we send the 2025 client's session ID to each replica.

serve-two-revisions.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Serves the ported refund confirmation from one app to a 2026-07-28 client and a 2025-11-25 client, then sends the 2025client's session ID to a second replica. The prose's point rests on the two "question came as" lines (one resolver, twoforms), the two refund lines, and the two session lines: the replica that made the session answers, and the other returns a 404."""import asyncioimport osimport httpx2from mcp import Clientfrom lib import confirmations, http_mcp, loopback, shop_api, wireLEGACY = {"MCP-Protocol-Version": "2025-11-25", "Accept": "application/json, text/event-stream"}   # a 2025 version routes to the 2025 handlerdef asked_how(exchanges: list[dict]) -> str:    messages = [m for e in exchanges for m in e["messages"]]    if any(m.get("method") == "elicitation/create" for m in messages):        return "a request the server pushed mid-call"    return "an input request in a result" if any(m.get("result", {}).get("resultType") == "input_required"                                                 for m in messages) else "never"async def main() -> None:    server = http_mcp.load_server("replace-pushed-requests.py")     # the ported issue_refund, with its resolver    with loopback.serve(shop_api.create_app()) as api_url:        os.environ.update(shop_api.server_env(api_url))        with loopback.serve(wire.record_http(server.streamable_http_app(), "a.jsonl")) as a, \             loopback.serve(http_mcp.load_server("replace-pushed-requests.py").streamable_http_app()) as b:            for mode, order in (("auto", "O-2289"), ("legacy", "O-1085")):     # both above the policy limit                seen = len(wire.read_http_trace("a.jsonl"))   # this client's exchanges come after this count                async with Client(a + "/mcp", mode=mode, elicitation_callback=confirmations.say_yes) as client:                    quote = (await client.call_tool("quote_refund", {"order_id": order})).structured_content                    refund = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})                    # the first response from this client that set a session ID                    session = next((e["response_headers"]["mcp-session-id"] for e in wire.read_http_trace("a.jsonl")                                    [seen:] if "mcp-session-id" in e["response_headers"]), None)                    print(f"{mode} revision:", client.protocol_version)                    print(f"{mode} session header:", "set" if session else "none")                    for replica, url in (("a", a), ("b", b)) if session else ():   # no session, nothing to send                        sent = httpx2.post(url + "/mcp", headers={"Mcp-Session-Id": session, **LEGACY},                                           json={"jsonrpc": "2.0", "id": 9, "method": "tools/list"})                        listed = "tools listed" if "check_stock" in sent.text else sent.json()["error"]["message"]                        print(f"2025 session on replica {replica}: HTTP {sent.status_code},", listed)                print(f"{mode} question came as:", asked_how(wire.read_http_trace("a.jsonl")[seen:]))  # this client's exchanges, as replica a logged them                print(f"{mode} refund:", refund.structured_content["status"])asyncio.run(main())
输出python serve-two-revisions.py
auto revision: 2026-07-28
auto session header: none
auto question came as: an input request in a result
auto refund: requested
legacy revision: 2025-11-25
legacy session header: set
2025 session on replica a: HTTP 200, tools listed
2025 session on replica b: HTTP 404, Session not found
legacy question came as: a request the server pushed mid-call
legacy refund: requested

The default client settled on 2026-07-28, got no session header (none), and its question came as an input request in a result. Its refund ended requested.

The 2025 client settled on 2025-11-25, got a session header (set), and its question came as a request the server pushed mid-call. Its refund ended requested, and so did the default client's.

One resolver served both eras, and no code in issue_refund checks which one it is in. That is simpler than the ctx.protocol_version check around ctx.elicit() that See why a stateless server can't wait for an answer allows. A hand-built input request, like chapter 5's, doesn't serve both: a 2025 client receives it as an invalid result (What goes wrong in production in chapter 5).

The 2025 session worked on replica a, which answered HTTP 200, tools listed, and failed on replica b, which answered HTTP 404, Session not found. A 2026 client has no session to lose. What it needs from replicas is handles they all reach, as Run replicas without sticky sessions showed. Behind a load balancer, then, 2025-era traffic needs routing by Mcp-Session-Id to the replica that made the session, while the rest goes anywhere. The SDK's other choice, stateless_http=True, removes the sessions for 2025 clients but takes away their cancellation and their server-to-client requests (What goes wrong in production in chapter 6). For the shop that would break the pushed confirmation that the 2025 client had answered, so we recommend sticky routing for the 2025 path, kept as small as the remaining clients allow.

Working rule: Serve both eras from one streamable_http_app() through the window, write every question a tool asks as a resolver, and route requests that carry Mcp-Session-Id to the replica that minted it. Count requests by era. When the 2025 count has stayed at zero for as long as your slowest host takes to upgrade, serve the pinned revision only, and answer initialize with an error that names the versions you support, as the specification asks.

生产环境中会出什么问题

最近一次修改见于版次 2026.11.11

迁移的失败发生在两个时代之间的缝隙里:一个客户端看到的是旧服务器,代理看到的是新服务器,而警告却什么也没说。下面是需要留意的几类故障。

2025 版会话落到了另一个副本上。 其表现是:在一次部署或扩容之后,只有 2025 时代的客户端收到带有 "Session not found" 的 404,如 通过过渡期同时服务新旧客户端 中的副本 b。遵循其修订版本的 2025 客户端会在收到 404 时开启新会话(2025-11-25 传输),因此症状可能是状态丢失,而不是报错。请按 Mcp-Session-Id 路由,并按客户端统计 404 的数量。

代理丢弃了版本请求头。 SDK 的应用仅凭 MCP-Protocol-Version 判断时代,其源码把按请求体路由标记为后续步骤(mcp/server/streamable_http_manager.py)。如果代理剥离了它不认识的请求头,就会把 2026 时代的请求送入 2025 路径,而该路径要求先完成握手。其表现是:只有位于该代理之后、使用所固定修订版本的客户端出现失败。应让每个代理都放行 MCP 请求头,具体见 读懂一次 HTTP 交换 中的列举。

错误码变了。 在所固定的修订版本中,资源缺失的错误码是 -32602,而不是 -32002,不过客户端仍然应当(SHOULD)接受 -32002(资源)。该修订版本新增了 -32020(请求头与请求体不一致)、-32021(缺少客户端能力)和 -32022(不支持的协议版本)(变更日志)。依据旧错误码分支处理的宿主,会把所固定修订版本新增的错误码当作未知错误码。在服务器迁移之前,应在客户端代码中逐一搜索每个数值错误码。

让人习惯于忽略警告的警告。 MCPDeprecationWarning 是一个 UserWarning,因此默认会被打印出来(新特性),仍在使用采样、根目录或日志功能的服务器会把它写入日志。若整体关闭,它也会把下一次弃用一并隐藏。只有当该功能已列入带有日期的清单之后,才应按消息逐条过滤警告。

对 HTTP+SSE 和注册保持沉默。 如清单盘点所示,2.3.0 版本的 SDK 对这两者都不发出警告。服务器可能在没有任何警告的情况下通过全部测试,却在传输方式被移除时失去最老的那批宿主。应在 CI 中保留 盘点旧服务器的依赖 中的扫描,并把后续 SDK 版本新增这些警告视为重新核对日期的理由。

把最早移除日期当作终止日期。 如果团队计划在 2027-07-28 迁离采样或根目录,就没有任何余量,因为在该日期当天或之后发布的第一个修订版本就可能移除它们。如果团队把该日期理解为功能消失的那一天,也可能放弃了 SDK 实际上仍会支持更久的功能。应按所服务的客户端来规划:注册表给出的是最早日期,而你的日志给出的才是真实日期。

工作准则: 在接入流量之前,先通过真实的代理路径验证移植结果,共四项测试:2025 客户端完成一次确认,2026 客户端完成同样的确认,2025 会话在一次部署后依然存活,版本请求头能够到达服务器。之后按时代观察请求、按客户端观察 404,并观察每一条弃用警告,直到 2025 的计数降为零。

本章做出的决定

  • 2025 年代的服务器是一份清单,而不是可运行的示例。lib.legacy 以文本形式保存它,供 SDK 1.x 使用,而示例只运行 2.x 上的移植版本,因为一个环境无法同时容纳两个版本线。
  • **清单把依赖项分为已移除、已弃用和 SDK 变更三类,**并为每个已弃用的功能记录注册表给出的最早移除日期,该日期按最早日期理解,而不是终止日期。
  • **扫描在整个过渡期内于 CI 中运行,**因为 SDK 会对采样、根目录和日志发出警告,但不会对 HTTP+SSE 或注册发出警告。
  • **会话级状态改为句柄:**报价就是第 3 章的 quote_id,由客户端传回,并存放在每个副本都能读取的位置。
  • **HTTP+SSE 被淘汰。**商店的服务器只提供 Streamable HTTP,仅当日志显示仍有主机在使用旧端点时,才保留这些端点。
  • **征询(elicitation)移入解析器,**它同时服务于两个年代。采样被删除:由主机的模型对工单进行分诊。根目录变为 export_dir 参数,并对照 SHOP_EXPORT_DIRS 进行检查。日志输出到 stderr 和追踪中。
  • **主机通过 client_metadata_url 使用客户端 ID 元数据文档(Client ID Metadata Document),**授权服务器仅为无法发布该文档的主机保留注册。
  • **向 2.x 的移植是一次变更,**在测试通过之前,版本约束保持为 mcp<2,按关键字传入 instructions=,并把传输设置放在 run() 上。
  • **一个双年代应用在过渡期内同时服务两个年代:**2025 年代的流量按 Mcp-Session-Id 做粘性路由,并且不使用 stateless_http。

本章,在本版次中

版次 2026.11.14示例于 2026年11月19日 通过本章 6个示例 个示例中有 6 个通过

译自英文版图书,版次 2026.11.14。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 12 章,共 12 章: 迁移 2025 年代的服务器

  1. Inventory what the old server depends on
  2. 移除 initialize 与会话 ID
  3. 从 HTTP+SSE 迁移到 Streamable HTTP
  4. 替换采样、根目录和日志
  5. Replace dynamic client registration
  6. 将代码从 SDK 1.x 移植到 2.x
  7. Serve old and new clients through the window
  8. 生产环境中会出什么问题
  9. 本章做出的决定

返回顶部全部章节