遷移 2025 年代的伺服器

閱讀約需 83 分鐘 分鐘,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 版本下成立。你會找出伺服器的相依項目、移除其中的 session、讓它脫離 HTTP+SSE 傳輸、取代 sampling、roots、logging 與 Dynamic Client Registration、移植程式碼,並在舊版用戶端仍存在時,同時服務兩個時代的用戶端。

前面每一章都從一開始就為商店(本書唯一的案例)建構伺服器,並將其寫成針對指定修訂版本的 shop-support。多數團隊並非從這裡起步。他們手上的伺服器,是 2025 年代的團隊依 2025-03-26 至 2025-11-25 的各版修訂與 SDK 1.x 所撰寫,而且主機端仍使用這些修訂版本。本章是唯一講授 2025 年代協定的一章,而且只把它當作要遷移的來源。

從這些修訂版本到指定的修訂版本之間,Model Context Protocol(MCP)移除了 initialize 交握與協定 session,移除了伺服器在呼叫途中向用戶端推送的請求,並棄用了五項功能,以及某個 sampling 欄位的兩個值(變更紀錄)。商店的 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 版

盤點舊伺服器的依賴項目中的掃描首先列出了工作階段(session)。在 2025 年的各版規格下,連線以 initialize 開始,Streamable HTTP 伺服器可以在回應中指派工作階段 ID。用戶端接著必須在每個請求中送出 Mcp-Session-Id,在伺服器回應 404 時開啟新的工作階段,並以 DELETE 結束工作階段(2025-11-25 傳輸層)。伺服器可以為每個工作階段保存任何想保存的資料。

鎖定的版本移除了交握與工作階段。每個請求都在 _meta 中帶有其協定版本與用戶端的能力。用戶端以 server/discover 詢問伺服器支援什麼,每個伺服器都必須(MUST)實作它;需要跨呼叫保存狀態的伺服器,則會產生一個明確的控制代碼(handle),並讓用戶端把它當作一般的工具參數傳回來(變更記錄)。在每個請求中帶上版本與能力說明了 _meta 的各個鍵。

2025 年代的伺服器為每個工作階段保存一份狀態。quote_refund 把報價存在 ctx.session 之下,這是 SDK 為連線提供的物件,而 issue_refund 不接受任何參數,直接對該連線最近一次產生的報價退款。在 SDK 1.x 下,一個連線的所有請求共用同一個物件(1.x 中的 mcp/server/lowlevel/server.py),因此這樣可行。我們把這兩個工具原封不動地移到 2.x,圍繞第 3 章的報價與退款函式,並以鎖定的版本從單一用戶端各呼叫一次。接著以同樣方式呼叫第 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 端點旁提供舊端點,依用戶端記錄每一次連線,並訂出移除日期,告知每個主機的擁有者。請將這種傳輸方式視為已可移除,因為它的寬限期是三個月,而不是十二個月。

取代 sampling、roots 與 logging

最近一次變動於第 2026.11.11 版

盤點舊伺服器的相依項目找到的相依項目中,有三項疊加了兩種變更,最好分開看待。第一種是機制上的變更。2025 年的伺服器會在呼叫進行到一半時,自行向用戶端發出請求(elicitation/create、sampling/createMessage、roots/list),並等待回應。固定採用的修訂版指出,這種模式「不再受到支援」,而且這是一項破壞性變更。伺服器改以多輪往返請求(Multi Round-Trip Request)提出詢問,回傳一個輸入請求,其值可以是 ElicitRequest、CreateMessageRequest 或 ListRootsRequest(多輪往返請求)。第二種是功能本身的變更。Roots、sampling 與 logging 都已被棄用,登錄表中也列有遷移路徑:roots 改用工具參數、資源 URI 或伺服器設定;sampling 改為直接整合模型供應商的 API;logging 在 stdio 上改寫到 stderr,或使用 OpenTelemetry(已棄用的功能)。

因此,多輪往返請求取代的是伺服器主動推送的機制,而不是 sampling。若伺服器只是把 sampling/createMessage 搬進輸入請求,仍然相依於已棄用的功能。三者之中只有 elicitation 沒有被棄用,所以它是唯一值得搬進往返流程並保留的功能。

2025 年版的 issue_refund 以 ctx.elicit 推送確認,這在固定採用的修訂版上會失敗,如了解無狀態伺服器為何無法等待回應所示。移植版改以 resolver 來詢問。宣告為 Annotated[Release, Resolve(confirm)] 的參數,會在工具執行前先執行 confirm 來填入;當 confirm 回傳 Elicit(...) 時,SDK 會詢問主機端的使用者(以 elicitation 請求結構化輸入)。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。這個 resolver 對 2025 年版的用戶端同樣適用,因為 SDK 會依用戶端所用的修訂版,以對應的形式送出問題(mcp/server/mcpserver/resolve.py)。在過渡期同時服務新舊用戶端會同時執行兩者。

移植版的記錄行使用 Python 的 logging,而不是 ctx.info。MCPServer 在建立時就會將 logging 設定為寫到 stderr(mcp/server/mcpserver/utilities/logging.py),所以這一行會進入伺服器自己的記錄,而不會送到用戶端。在 stdio 上,stdout 只承載協定的訊息,stderr 才是伺服器記錄該去的地方(stdio)。另一條路徑見以 OpenTelemetry 追蹤呼叫。

Sampling 則完全移除。2025 年版的 triage_ticket 透過 sampling 詢問主機端的模型某張工單需要哪個工具,移植版刪除了這個工具。主機端自己的模型本來就會讀取每張工單並挑選工具(處理工單佇列),所以伺服器是在請主機做主機本來就會做的事。若伺服器自己的工作需要模型,就以自己的憑證呼叫模型供應商,這也讓它能自行選擇並負擔模型的費用。

save_restock_report 會向用戶端索取 roots,並寫入第一個 root。它的移植版改以參數接收資料夾,並在解析路徑之後,對照伺服器設定中 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.」現在由主機或模型傳入資料夾,而可以寫入何處,則由伺服器而非用戶端決定。

實用原則: 把每一個推送式的 elicitation 都搬進 resolver,它同時適用於兩個時期。刪除 sampling,而不是搬移它:讓主機端的模型負責模型工作,或由伺服器以自己的憑證呼叫供應商。把 roots 改成參數,並對照伺服器設定中的允許清單檢查;記錄行與追蹤資料則送往 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),所以伺服器的使用說明變成了它的標題。用戶端看到的標題是「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 年代的用戶端在部署或橫向擴充之後,收到 404 與「Session not found」,如 讓舊用戶端與新用戶端在過渡期間都能連線中的副本 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,因此預設會被印出(新功能),仍使用 sampling、roots 或 logging 的伺服器會把它寫入記錄檔。若整個關閉,也會連下一次的棄用一併隱藏。只有在該功能已列入附有日期的清單之後,才依訊息內容逐一過濾各項警告。

**對 HTTP+SSE 與註冊保持沉默。**如清查所發現,2.3.0 版的 SDK 對這兩者都不發出警告。伺服器可能在沒有任何警告的情況下通過測試,卻在傳輸層被移除時失去最舊的主機。請在 CI 中保留清查舊伺服器所依賴的項目中的掃描,並把後續 SDK 版本加入這些警告視為重新確認日期的理由。

**把最早移除日期當成結束日期。**若團隊計畫在 2027-07-28 前停用 sampling 或 roots,就沒有任何餘裕,因為在該日期當天或之後發布的第一個修訂版本,就可能移除它們。若團隊把該日期理解為功能消失的當天,也可能捨棄 SDK 其實會支援更久的功能。請依所服務的用戶端來規劃:登錄表給出最早的日期,而你的記錄檔則給出實際的日期。

**實用原則:**在移植版本接收流量之前,先透過真實的代理伺服器路徑加以驗證,並進行四項測試:2025 用戶端完成一次確認、2026 用戶端完成同樣的確認、2025 工作階段在部署後仍然存續,以及版本標頭確實到達伺服器。之後再依時代監看 requests、依用戶端監看 404,並監看每一則棄用警告,直到 2025 的數量降為零。

本章做出的決定

  • 2025 年代的伺服器是一份程式碼清單,而不是可執行的範例。lib.legacy 以文字形式保存它,供 SDK 1.x 使用;範例只執行 2.x 上的移植版本,因為同一個環境無法同時容納兩條版本線。
  • 盤點會把相依項目分成已移除、已棄用與 SDK 變更三類,並附上登錄表中每項已棄用功能最早的移除時間,這個時間應視為最早日期,而不是終止日期。
  • 掃描在整個過渡期間於 CI 中執行,因為 SDK 會對 sampling、roots 與 logging 發出警告,卻不會對 HTTP+SSE 或註冊發出警告。
  • **各工作階段的狀態改為控制代碼(handle):**報價就是第 3 章的 quote_id,由用戶端回傳,並儲存在每個副本都能讀取的位置。
  • **HTTP+SSE 移除。**商店的伺服器只提供 Streamable HTTP,且只在日誌顯示仍有主機使用舊端點時,才保留這些端點。
  • **Elicitation 移入解析器(resolver),**兩個年代都由它處理。Sampling 則刪除:由主機的模型負責分流工單。Roots 改為 export_dir 參數,並對照 SHOP_EXPORT_DIRS 檢查。Logging 改送至 stderr 與追蹤資料。
  • 主機透過 client_metadata_url 使用 Client ID Metadata Document,授權伺服器只為無法發布該文件的主機保留註冊機制。
  • 移植到 2.x 是單一變更,在測試通過之前以 mcp<2 鎖定版本,並以關鍵字傳入 instructions=,傳輸設定則放在 run() 上。
  • **單一雙年代應用程式在過渡期間同時服務兩個年代:**2025 年代的流量依 Mcp-Session-Id 進行黏性路由(sticky routing),且不使用 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. 取代 sampling、roots 與 logging
  5. Replace dynamic client registration
  6. 將程式碼從 SDK 1.x 移植到 2.x
  7. Serve old and new clients through the window
  8. 正式環境中會出什麼問題
  9. 本章做出的決定

返回頂端所有章節