以 OAuth 授權用戶端
閱讀約需 126 分鐘 分鐘,9 節 中共有 7 個範例。
讀完本章,你就能用 OAuth 保護商店的 Model Context Protocol 伺服器。你會發布中繼資料,引導用戶端找到授權伺服器;以 Client ID Metadata Document 識別客服團隊的主機;透過 PKCE 取得權杖;只接受為商店伺服器所簽發的權杖;藉由每個回應中的簽發者(issuer)攔截混淆攻擊(mix-up attack);並要求每個工具都具備對應的範圍(scope),在退款需要更多權限時進行升級授權(step-up)。本章的論述依據規格修訂版 2026-07-28,並以 Python SDK 的 mcp 2.3.0 所實作的內容為準。
以 Streamable HTTP 提供服務已將 shop-support 移到 HTTP 位址上,好讓客服人員的主機能共用它;這個伺服器供商店的客服人員讀取訂單並辦理退款。它的 Origin 檢查只能擋下網頁,其他都擋不住:任何能連上該連接埠的程式都可以讀取訂單並辦理退款(拒絕來自其他來源的請求)。因此,商店需要知道是哪個主機在呼叫、代表哪一個人,以及這個人可以做什麼。客服人員可以讀取訂單與庫存;只有客服主管可以退款。
Model Context Protocol(MCP)的答案是 OAuth 2.1。MCP 的授權是選用的,且屬於 HTTP 傳輸層:stdio 伺服器改從環境中取得憑證(授權)。受保護的 MCP 伺服器是 OAuth 資源伺服器,主機對它而言的用戶端是 OAuth 用戶端,並由授權伺服器簽發權杖,授權伺服器可以與 MCP 伺服器放在一起,也可以分開部署。你從其他 API 的用戶端角度已經熟悉這個流程。MCP 帶來的改變是,用戶端事先對伺服器一無所知,只從一個 URL 出發,因此探索、用戶端的身分,以及權杖的受眾(audience),都必須在雙方沒有任何事先設定的情況下運作。
examples/lib/ 中的四個共用模組承擔了本章的設定,所以每個範例只呈現其核心概念:
lib.auth_server是商店在本機迴路(loopback)上的授權伺服器:提供中繼資料、搭配 PKCE 的授權碼授權(authorization code grant)、在每個回應中附上iss,以及綁定單一伺服器的 JWT 存取權杖。使用者同意的步驟由腳本代行,取代在瀏覽器前操作的人。它只是供這些本機迴路範例使用的教學用伺服器,絕對不可部署。它不會讓任何人登入,而且其簽章金鑰由本書公開的種子推導而來,任何拿到本書的人都能鑄造它會接受的權杖。實際部署應使用符合本章各項檢查的成熟授權伺服器。Python SDK 自身也有授權伺服器,但其文件不建議新伺服器採用,而且它的中繼資料既未宣告iss,也未宣告 Client ID Metadata Document(SDK 授權文件)。lib.oauth_client是主機這一側:使用 SDK 的OAuthClientProvider搭配記憶體內的權杖儲存,以及一個腳本化的瀏覽器,它會跟隨授權伺服器的重新導向,並把回應交還給 SDK。lib.tool_scopes補上 SDK 所沒有的逐工具範圍檢查。lib.protected_shop把它們組合起來:第 3 章的五個工具置於 OAuth 之後,即本章留下它們的樣子。
所有內容都在 127.0.0.1 上以純 HTTP 執行。這僅適用於本機開發。在正式環境中,授權伺服器的每個端點都必須以 HTTPS 提供服務(安全性考量)。
此部分尚未翻譯,因此以英文呈現。
Find the authorization server from the resource
A client that has only a server's URL must learn from the server where to get a token, and the pinned revision does this in two steps. First, MCP servers MUST publish Protected Resource Metadata (RFC 9728), a JSON document that names the resource and lists at least one authorization server (authorization). A request without a token gets 401, and its WWW-Authenticate header points to that document in a resource_metadata parameter. A client that finds no such parameter tries the well-known URI, /.well-known/oauth-protected-resource with the server's path inserted, and then without the path (authorization server discovery). Second, the client fetches the authorization server's own metadata (RFC 8414), which lists its endpoints and what it supports.
Two values must match along the way. The resource in the server's metadata must be identical to the URL the client used, or the client must not use the metadata (RFC 9728, section 3.3). And the issuer in the authorization server's metadata must be identical to the issuer the client built the well-known URL from (RFC 8414, section 3.3). Both checks stop a client from trusting a document that describes some other server.
The shop's server states its own URL, and the authorization server states its issuer. The SDK does the server's half when you give MCPServer an AuthSettings and a token verifier: issuer_url names the authorization server, resource_server_url is the server's own endpoint URL, and required_scopes lists the scopes every request needs. The shop's server requires orders:read and stock:read, because every ticket needs one or both. refunds:write comes later, and only when a refund needs it. The token verifier is lib.auth_server.JwtVerifier, which checks a token's signature, issuer and expiry. On loopback the port, and so the resource URL, is known only once the socket is open. So the server is built in a function of its base URL, and serve_built from lib.auth_server opens the socket first. Then the example plays a client: it sends tools/list with no token and follows the answer.
1"""Protect the shop's server with OAuth, then follow its 401 to the authorization server, as a client does. The point2rests on the challenge's error line and on the PKCE methods line; the asserts check the rest of the chain."""3from urllib.parse import urlsplit45import httpx26from mcp.server.auth.settings import AuthSettings78from lib import auth_server, http_mcp, shop_tools91011def protected(issuer: str):12 def build(base_url: str): # the server must know its own URL: the resource13 settings = AuthSettings(issuer_url=issuer, resource_server_url=base_url + "/mcp",14 required_scopes=["orders:read", "stock:read"], validate_token_resource=True)15 verifier = auth_server.JwtVerifier(issuer)16 return shop_tools.create_server(version="0.8.0", auth=settings, token_verifier=verifier).streamable_http_app()17 return build181920with auth_server.serve() as issuer, auth_server.serve_built(protected(issuer.url)) as base_url: # the socket opens before the app is built, so the app knows its URL21 first = http_mcp.post(base_url + "/mcp", "tools/list") # no token22 print("status:", first.status_code)23 # [7:] drops the scheme, "Bearer ", which is 7 characters; the values that follow are quoted24 challenge = dict(part.split("=", 1) for part in first.headers["www-authenticate"][7:].split(", "))25 print("challenge parameters:", ", ".join(challenge))26 print("challenge error:", challenge["error"].strip('"'))27 metadata_url = challenge["resource_metadata"].strip('"')28 print("resource metadata path:", urlsplit(metadata_url).path)29 resource = httpx2.get(metadata_url).json()30 assert resource["resource"] == base_url + "/mcp" # RFC 9728: the endpoint's own URL31 print("authorization servers:", len(resource["authorization_servers"]))32 print("scopes_supported:", " ".join(resource["scopes_supported"]))33 found = resource["authorization_servers"][0] # the one server the metadata lists34 metadata = httpx2.get(found + "/.well-known/oauth-authorization-server").json()35 assert metadata["issuer"] == found # RFC 8414: the URL it was fetched from36 print("code_challenge_methods_supported:", metadata["code_challenge_methods_supported"])37 assert metadata["client_id_metadata_document_supported"] # the server advertises metadata documents38 assert metadata["authorization_response_iss_parameter_supported"] # and iss on every authorization response
python discover-the-authorization-server.pystatus: 401
challenge parameters: error, error_description, resource_metadata
challenge error: invalid_token
resource metadata path: /.well-known/oauth-protected-resource/mcp
authorization servers: 1
scopes_supported: orders:read stock:read
code_challenge_methods_supported: ['S256']
The first request got 401, with a challenge carrying error, error_description, resource_metadata and the error invalid_token. That error is the SDK's choice, and a departure from RFC 6750, which says a server SHOULD NOT include an error code when a request carries no credentials at all (RFC 6750, section 3.1).
The metadata URL's path is /.well-known/oauth-protected-resource/mcp, the well-known prefix with the server's path inserted, as RFC 9728 asks. The metadata names the endpoint's own URL as its resource, lists 1 authorization server, and gives scopes_supported as orders:read stock:read, which the SDK fills from required_scopes.
The challenge has no scope parameter, because the SDK's 401 never sends one (mcp/server/auth/middleware/bearer_auth.py). So a client falls back to scopes_supported. The specification's order is the challenge's scope first, then every scope in scopes_supported, then no scope at all (authorization). That is why scopes_supported should be the smallest set that works, not every scope the server knows: whatever it lists, every host asks every user for.
The authorization server's metadata names the URL the client fetched it from as its issuer, and it states three things the rest of the chapter relies on: PKCE methods ['S256'], support for Client ID Metadata Documents, and iss on authorization responses. The SDK's client makes both matching checks for you. It raises OAuthFlowError when the metadata's issuer differs from the expected one, compared as plain strings (SDK migration guide). Its resource check is laxer than RFC 9728: it accepts metadata whose resource is a same-origin path prefix of the server's URL (mcp/shared/auth_utils.py). A validate_resource_url callback on OAuthClientProvider replaces that check with your own.
Working rule: Give every protected server an AuthSettings with its endpoint's URL as resource_server_url, exactly as clients will type it, and the smallest required_scopes that every request needs. Check the chain with one request that carries no token: a 401, a resource_metadata URL, metadata whose resource is the endpoint, and authorization server metadata whose issuer is the URL you fetched it from. When a value differs by a trailing slash or a port, fix the configuration rather than relaxing the client.
此部分尚未翻譯,因此以英文呈現。
Identify the client with a metadata document
Find the authorization server from the resource tells the host where to get a token. The authorization server still has to know which client is asking, and a host meets MCP servers it has never seen, so it can't have registered with each one's authorization server in advance. The pinned revision ranks the ways to get a client ID. Pre-registered client information comes first, if there is any. A Client ID Metadata Document comes next, if the authorization server advertises client_id_metadata_document_supported. Dynamic Client Registration follows, and the user is asked only when none of these is available (client registration).
A Client ID Metadata Document makes the client ID a URL. The client publishes a JSON document at an https:// URL with a path, and that URL is its client_id. The document must contain at least client_id, equal to the URL exactly, client_name and redirect_uris (client registration). The authorization server fetches the document when the client first appears, checks the ID and the redirect URI against it, and may cache it by its HTTP headers. It must not follow redirects while fetching, and it must not cache an error (metadata document draft -02).
A document can't carry a shared secret, because client_secret is forbidden. A client identified this way is therefore public, and it relies on PKCE, or proves itself with a key pair through private_key_jwt (draft -02, section 4.1). The MCP specification links draft -00 of that document, and we cite draft -02, the later text. A client ID from a document works with any authorization server. A pre-registered or registered client ID, by contrast, is bound to the server that issued it, and the pinned revision forbids reusing it with another (client registration).
Dynamic Client Registration is deprecated at the pinned revision. It stays as a fallback for authorization servers without metadata document support, and its earliest removal is the first revision released on or after 2027-07-28 (deprecated features). Replace dynamic client registration moves a client off it.
The support team's host publishes its document at https://support.fernhill.example/oauth/client.json. Nothing here reaches a network, and fernhill.example never resolves, so the shop's authorization server can't fetch it. Rather than give the host an http:// client ID that a loopback server could fetch, lib.auth_server keeps the document in a mapping from client ID URL to document. That mapping stands in for the fetch, and the server applies to it the checks it would apply to a fetched copy. This is pre-registration of the URL, which the draft allows as associating a client ID URL with its metadata "through other means" (draft -02, section 5). It is a test-only stand-in, and a deployed authorization server fetches the document over HTTPS.
The code prints the document's key values, runs the server's checks on it and on three broken copies, gives the SDK an http:// client ID, and then connects twice, to an authorization server that supports metadata documents and to one that doesn't.
1"""The support host's Client ID Metadata Document, the checks an authorization server makes on it, and the SDK's client2sending its URL as the client ID, with and without the authorization server's support. The point rests on the3`client_id sent` line and on the fallback's error line, which show what the SDK did in each case."""4import asyncio56from mcp.client.auth import OAuthRegistrationError78from lib import auth_server, oauth_client, protected_shop910document = auth_server.client_document() # served at auth_server.CLIENT_ID11print("client_id:", document["client_id"])12print("redirect_uris:", ", ".join(document["redirect_uris"]))13print("token_endpoint_auth_method:", document["token_endpoint_auth_method"])14for label, url, candidate in [15 ("as published", auth_server.CLIENT_ID, document),16 ("with a secret", auth_server.CLIENT_ID, auth_server.client_document(client_secret="not-a-secret")),17 ("another client_id", auth_server.CLIENT_ID, auth_server.client_document(client_id="https://partner.example/")),18 ("on http", "http://support.fernhill.example/oauth/client.json", document)]:19 print(f"document {label}:", auth_server.document_problem(url, candidate) or "accepted")20try:21 oauth_client.provider("http://127.0.0.1/mcp", browser=oauth_client.ScriptedBrowser(),22 client_metadata_url="http://localhost:4280/client.json") # the SDK checks the scheme when it's built23except ValueError:24 print("SDK given an http client ID: ValueError")252627async def connect(**server_options) -> None:28 with auth_server.serve(**server_options) as issuer, protected_shop.serve(issuer.url) as url:29 browser = oauth_client.ScriptedBrowser()30 try:31 async with oauth_client.connect(url, browser=browser) as client:32 await client.list_tools()33 print("client_id sent:", browser.requests[0]["client_id"])34 except* OAuthRegistrationError as group: # the SDK fell back to registration35 print("without metadata document support:", group.exceptions[0])363738asyncio.run(connect()) # the shop's server advertises metadata document support39asyncio.run(connect(advertise_cimd=False)) # a server that doesn't, so the SDK registers instead
python publish-client-metadata.pyclient_id: https://support.fernhill.example/oauth/client.json
redirect_uris: http://localhost:4280/callback
token_endpoint_auth_method: none
document as published: accepted
document with a secret: document carries a shared secret
document another client_id: document client_id differs from its URL
document on http: client_id must be an https URL with a path
SDK given an http client ID: ValueError
client_id sent: https://support.fernhill.example/oauth/client.json
without metadata document support: Registration failed: 404 Not Found
The document names https://support.fernhill.example/oauth/client.json as its own ID, and its redirect URI is http://localhost:4280/callback. Its token endpoint authentication method is none, so the host holds no secret. The authorization server accepts the document as published.
A copy with a secret fails with "document carries a shared secret", and the other two broken copies fail for the reasons printed beside them: one whose client_id names another site, and one whose client ID is on http. The SDK makes the same https check on its side. Given an http:// client ID, OAuthClientProvider raises ValueError as soon as it is built (mcp/client/auth/utils.py).
The SDK's client uses the document's URL as its client ID, and it falls back quietly when the server doesn't support that. Against the shop's authorization server it sent https://support.fernhill.example/oauth/client.json as the client ID, and made no registration request. Against a server that doesn't advertise support, it fell back to Dynamic Client Registration without a word, and the flow ended with "Registration failed: 404 Not Found", because the shop's authorization server has no registration endpoint. The SDK's documentation calls this fallback silent (OAuth clients). For the host, an authorization server without metadata document support shows up as a registration error, not as a missing feature.
Working rule: Give every host one Client ID Metadata Document at a stable https:// URL, with only the redirect URIs it uses and no secret, and pass that URL to the SDK as client_metadata_url. Use pre-registered credentials where an authorization server has issued them, since they rank first, and keep Dynamic Client Registration only for authorization servers that support nothing else. In tests on loopback, keep the client ID an https:// URL and associate it with a local copy of the document in the test authorization server, rather than giving the client an http:// ID that no production server accepts.
以 PKCE 取得權杖
有了在以中繼資料文件識別用戶端中取得的用戶端 ID,主機就可以請求權杖。MCP 使用授權碼授與流程(authorization code grant)。主機把使用者的瀏覽器導向授權伺服器的授權端點,使用者登入並同意後,瀏覽器會帶著一組授權碼回到主機的重新導向 URI。接著主機在權杖端點以該授權碼換取權杖。這次交換中有三個參數承擔了大部分的安全性。
PKCE 把授權碼綁定到提出請求的用戶端。用戶端產生隨機的 code_verifier,將其 SHA-256 雜湊值以 code_challenge 連同 code_challenge_method=S256 送出,並且只在權杖請求中才揭露 verifier,因此攔截到授權碼的人手上並沒有它。MCP 用戶端必須使用 PKCE 並採用 S256,而且如果授權伺服器的中繼資料中沒有 code_challenge_methods_supported,就必須拒絕繼續進行(安全性考量)。OAuth 2.1 自 draft-16 起已明確禁止 plain 方法,也就是 challenge 即為 verifier 本身的做法(OAuth 2.1 draft-16,第 7.5.2 節)。MCP 規格引用的是 draft-13,該版本仍允許這種做法(OAuth 2.1 draft-13)。
resource 參數(RFC 8707)以伺服器的標準 URI 指明權杖所要使用的伺服器。無論授權伺服器是否支援,MCP 用戶端都必須在授權請求與權杖請求中送出它(授權)。而 state 由用戶端在瀏覽器返回時檢查,把回應與請求連結起來。
SDK 的用戶端會替主機執行整個流程,而這個範例則從授權伺服器的角度觀察它。lib.oauth_client.connect 給用戶端一個 OAuthClientProvider,內含主機中繼資料文件的 URL,並以腳本化的瀏覽器取代真人。瀏覽器開啟授權 URL,跟隨重新導向,並在第一個指向重新導向 URI 的請求處停下。使用者在授權伺服器上的同意也是腳本化的:已登入的使用者會授與其角色所允許的所有被請求範圍。範例呼叫 get_order_status,讀取授權伺服器所記錄的內容,然後向授權伺服器送出三個 SDK 絕不會送出的請求。
1"""The SDK's client gets a token for the shop's server with the authorization code grant, PKCE S256 and the resource2parameter, then the authorization server refuses a code sent twice, a wrong verifier and the plain method. The point3rests on the status line, the refusals at the end, and the asserts that check the challenge, the resource and the token."""4import asyncio5import os67import httpx289from lib import auth_server, loopback, oauth_client, protected_shop, shop_api101112async def main() -> None:13 with auth_server.serve() as issuer, loopback.serve(shop_api.create_app()) as api_url:14 os.environ.update(shop_api.server_env(api_url)) # the server runs in this process15 with protected_shop.serve(issuer.url) as url:16 browser, storage = oauth_client.ScriptedBrowser(), oauth_client.MemoryStorage()17 async with oauth_client.connect(url, browser=browser, storage=storage) as client:18 result = await client.call_tool("get_order_status", {"order_id": "O-1873"})19 print("O-1873 status:", result.structured_content["status"])20 asked, exchanged = issuer.events # /authorize, then /token21 print("authorization request:", ", ".join(key for key in asked if key != "endpoint"))22 print("code_challenge_method:", asked["code_challenge_method"])23 # the challenge is the hash of the verifier that the token request revealed24 assert oauth_client.s256(exchanged["code_verifier"]) == asked["code_challenge"]25 assert asked["resource"] == exchanged["resource"] == url # the server's URL, in both requests26 claims = auth_server.claims(storage.tokens.access_token)27 for claim, expected in [("aud", url), ("iss", issuer.url)]: # the server; the issuer28 assert claims[claim] == expected, claim29 print("token sub:", claims["sub"])30 print("token scope:", claims["scope"])31 print("refresh token:", storage.tokens.refresh_token)32 again = httpx2.post(issuer.url + "/token", data=exchanged) # the same code a second time33 print("code sent twice:", again.status_code, again.json()["error"])34 # the challenge is the hash of a verifier this example knows, so the guessed one is the only thing wrong35 code = oauth_client.authorize_by_hand(issuer.url, url, challenge=oauth_client.s256("the-real-verifier"))36 stolen = {**exchanged, "code": code["code"], "code_verifier": "a-guessed-verifier"}37 print("wrong verifier:", httpx2.post(issuer.url + "/token", data=stolen).json()["error"])38 # method="plain" sends the verifier itself as the challenge, which OAuth 2.1 forbids39 plain = oauth_client.authorize_by_hand(issuer.url, url, challenge="the-real-verifier", method="plain")40 print("plain method:", plain["error"], "/", plain["error_description"])414243asyncio.run(main())
python token-with-pkce.pyO-1873 status: delivered
authorization request: response_type, client_id, redirect_uri, state, code_challenge, code_challenge_method, resource, scope
code_challenge_method: S256
token sub: staff-0007
token scope: orders:read stock:read
refresh token: None
code sent twice: 400 invalid_grant
wrong verifier: invalid_grant
plain method: invalid_request / PKCE with S256 is required
呼叫成功了,訂單 O-1873 的狀態是 delivered。授權請求帶有 response_type, client_id, redirect_uri, state, code_challenge, code_challenge_method, resource, scope,方法為 S256,其 challenge 正是權杖請求所揭露之 verifier 的雜湊值。兩個請求指名的是同一個資源,也就是端點的 URL。存取權杖是一個 JWT,其 aud 是伺服器的 URL,iss 是授權伺服器。它的範圍是 orders:read stock:read,也就是伺服器的 scopes_supported,因為 401 回應沒有指名任何範圍。
權杖的 sub(staff-0007)指的是主機代為行動的客服人員,而不是顧客,伺服器可從 SDK 的 get_access_token().subject 讀取它。因此,客服人員的權杖本身無法取代 SHOP_CUSTOMER_ID;在為使用者補全引數中,訂單的完成流程是透過 stdio 從環境中讀取它。對客服主機而言,顧客來自客服人員正在處理之工單的紀錄,由伺服器查詢並檢查,絕不來自工具引數。只有在顧客自行登入主機的情況下,sub 才是顧客,這是避免伺服器淪為混淆代理人所討論的情形。這裡沒有 refresh token(None):商店的授權伺服器不核發,而規格也要求用戶端不要假設一定有(授權)。
SDK 絕不會送出的這三個請求,顯示了 PKCE 與單次使用的授權碼能擋下什麼。同一個授權碼送出第二次時得到 400 invalid_grant,因為授權碼只能使用一次。以全新的授權碼搭配猜測的 verifier 送出時得到 invalid_grant,所以光是偷到授權碼毫無價值。使用 plain 的請求得到「invalid_request / PKCE with S256 is required」,因為商店的授權伺服器只接受 S256。
有一項檢查落在主機身上。SDK 的用戶端一律送出 S256,卻從不讀取 code_challenge_methods_supported,所以即使授權伺服器的中繼資料省略了該欄位,它仍會繼續進行(mcp/client/auth/oauth2.py)。必須符合規格的主機,會在連線前自行擷取每個授權伺服器的中繼資料,並拒絕任何未列出 S256 的伺服器。
**實用原則:**讓 SDK 的 OAuthClientProvider 執行授權碼流程,並從授權伺服器的角度檢查一次它送出了什麼:S256、state,以及在兩個請求中都等於伺服器 URL 的 resource。補上 SDK 略過的檢查,並拒絕中繼資料中未列出 S256 的授權伺服器。在你自己執行的授權伺服器上,只接受 S256,讓授權碼只能使用一次且效期短,並把每個授權碼綁定到其用戶端、重新導向 URI 與資源。
此部分尚未翻譯,因此以英文呈現。
Bind each token to one server
The token from Get a token with PKCE names the shop's server in aud, because the host sent resource. That protects no one unless the server checks it. An access token is a bearer credential, so whoever holds it can present it. Suppose the support host also connects to a partner's MCP server that trusts the same authorization server. The partner's server receives the tokens the host gets for it. If the shop's server accepted them, the partner's operator could replay them at the shop. RFC 8707 says the authorization server SHOULD restrict each token's audience to the requested resource, so that a token "legitimately presented to a resource cannot then be taken by that resource and presented elsewhere" (RFC 8707). The other half belongs to the server: MCP servers MUST validate that a token was issued for them as its audience, and MUST NOT accept or pass on any other token (authorization).
In the Python SDK at mcp 2.3.0, the server's half is off by default. AuthSettings.validate_token_resource decides whether the server refuses a token whose AccessToken.resource isn't resource_server_url. Left unset, it warns with MCPDeprecationWarning and behaves as False, and version 3.0 makes True the default (mcp/server/auth/settings.py). The SDK compares the two as URLs. The case of the scheme and host, a default port or a trailing slash makes no difference (mcp/server/auth/middleware/bearer_auth.py), and the comparison uses whatever your token verifier puts in AccessToken.resource. The other way is a verifier that checks aud itself.
Two tokens show which check does the work. The example signs both with the shop's authorization server's key, one for the shop's server and one for the partner's, https://partner.example/mcp, and presents each to the shop's server in three configurations: the SDK's default, validate_token_resource=True, and a verifier that passes the shop's URL to the JWT library as the expected audience.
1"""A token issued for another server, presented to the shop's server: the SDK's default accepts it, and it's refused once2the server checks the audience, either through AuthSettings or in the token verifier. The point rests on the partner's3token's status line in each configuration, and on the warning line that the default alone raises."""4import warnings56from mcp.server.auth.settings import AuthSettings78from lib import auth_server, http_mcp, shop_tools910PARTNER = "https://partner.example/mcp" # another MCP server, with the same authorization server11SCOPES = ["orders:read", "stock:read"]121314def shop(issuer: str, validate_token_resource: bool | None, verifier_checks_aud: bool):15 def build(base_url: str):16 resource = base_url + "/mcp"17 # the verifier checks aud only when it's given an audience; None checks nothing18 verifier = auth_server.JwtVerifier(issuer, audience=resource if verifier_checks_aud else None)19 # None leaves the SDK's default in place, which is off and warns; True refuses other servers' tokens20 settings = AuthSettings(issuer_url=issuer, resource_server_url=resource, required_scopes=SCOPES,21 validate_token_resource=validate_token_resource)22 return shop_tools.create_server(auth=settings, token_verifier=verifier).streamable_http_app()23 return build242526with auth_server.serve() as issuer:27 for label, validate, in_verifier in [("SDK default", None, False), ("validate_token_resource=True", True, False),28 ("verifier checks aud", False, True)]:29 # record every warning, and show them all, so each configuration reports only what it raised30 with warnings.catch_warnings(record=True) as caught:31 warnings.simplefilter("always")32 with auth_server.serve_built(shop(issuer.url, validate, in_verifier)) as base_url:33 url = base_url + "/mcp"34 own = auth_server.mint(issuer.url, url, SCOPES)35 foreign = auth_server.mint(issuer.url, PARTNER, SCOPES) # signed by the same authorization server36 for name, token in [("own token", own), ("partner's token", foreign)]:37 response = http_mcp.post(url, "tools/list", headers={"Authorization": f"Bearer {token}"})38 print(f"{label}, {name}:", response.status_code)39 print(f"{label}, warnings:", ", ".join(sorted({w.category.__name__ for w in caught})) or "none")
python wrong-audience-rejected.pySDK default, own token: 200
SDK default, partner's token: 200
SDK default, warnings: MCPDeprecationWarning
validate_token_resource=True, own token: 200
validate_token_resource=True, partner's token: 401
validate_token_resource=True, warnings: none
verifier checks aud, own token: 200
verifier checks aud, partner's token: 401
verifier checks aud, warnings: none
With the SDK's default, the partner's token got 200, and the server listed its tools for a token issued to someone else. The only sign was a warning at startup, MCPDeprecationWarning. Either check refuses the partner's token. With validate_token_resource=True it got 401, and with the audience check in the verifier it got 401. Both refusals are 401 with invalid_token, the answer the specification gives for a token that isn't valid for the server. The shop's own token was accepted in all three configurations, and neither fix warned.
We recommend validate_token_resource=True, which lib.protected_shop sets. It states the decision beside the server's other authorization settings, and it survives a change of token verifier. Check aud in the verifier as well when the verifier decodes the token anyway, since the second check costs nothing.
Working rule: Set validate_token_resource=True on every protected server, and make the token verifier fill AccessToken.resource from the token's aud. Treat an MCPDeprecationWarning from AuthSettings as a failed deployment, not as noise. Test the check with a token for another resource from the same authorization server, which must get 401. A server that calls another service on a client's behalf gets its own token for that service and never passes the client's token on (Never pass a client's token through).
此部分尚未翻譯,因此以英文呈現。
Validate the issuer of each response
Binding the audience, as Bind each token to one server does, keeps a token from working at the wrong server. A mix-up attack strikes earlier, at the authorization code. A host that talks to several authorization servers sends each code to whichever server it believes answered. In a mix-up, an attacker's authorization server gets the host to start a flow with it, then sends the user's browser on to an honest authorization server. The honest server's code arrives at the host's redirect URI. The host, still believing it is talking to the attacker, sends the code to the attacker's token endpoint. PKCE alone doesn't stop this, "because the client transmits the code_verifier to the attacker's token endpoint" (security best practices). Nor does resource, which the attacker rewrites in the request it forwards.
The defence is the iss parameter of RFC 9207. The authorization server names itself in its redirect, and the client compares that name with the server it sent the user to. The pinned revision introduced this check (changelog). Before redirecting, the client records the issuer from the authorization server's validated metadata, and it compares iss with that record by exact string comparison, with no normalisation of case, ports or slashes (authorization).
The rules are conditional. Authorization servers SHOULD include iss, and one that does MUST advertise authorization_response_iss_parameter_supported. A client MUST compare an iss that is present, whatever the metadata says, and MUST reject a response without iss only when the server advertised support. Otherwise it proceeds. On a mismatch, the client must not act on or display any error in the response. The specification expects a later revision to make iss a MUST for authorization servers (authorization). Comparing a present iss that wasn't advertised uses the latitude RFC 9207 leaves to local policy, and its default is that clients SHOULD discard such a response (RFC 9207, section 2.4).
The attacker in the shop's case is the partner, and MixUp from lib.auth_server plays it. The partner's MCP server names the attacker's authorization server, which copies the metadata of the shop's authorization server without iss support. Its authorization endpoint forwards the browser to the shop's authorization server, carrying the host's own request rewritten to ask for the shop's server and every scope. The host's client ID is a metadata document URL, which works with any authorization server, so the shop's authorization server sees a request from the real support host.
1"""A mix-up attack on the support host, run against a shop server that sends `iss` and one that omits it. The point rests2on the codes-received lines: the `iss` mismatch leaves the attacker nothing, and without `iss` it gets a token."""3import asyncio45from mcp.client.auth import OAuthFlowError, OAuthTokenError67from lib import auth_server, oauth_client, protected_shop8910async def attempt(label: str, **shop_options) -> None:11 with auth_server.serve(**shop_options) as shop_issuer, protected_shop.serve(shop_issuer.url) as shop_url:12 # the attacker's server forwards the browser to the shop's, and the partner's server names the attacker13 with auth_server.serve_mix_up(shop_issuer.url, target=shop_url) as attacker, \14 protected_shop.serve(attacker.url) as partner_url:15 browser = oauth_client.ScriptedBrowser()16 try:17 async with oauth_client.connect(partner_url, browser=browser) as client:18 await client.list_tools()19 except* (OAuthFlowError, OAuthTokenError) as group:20 error = group.exceptions[0]21 print(f"{label}, host stopped:", type(error).__name__, str(error).split(":")[0]) # the message's first phrase22 assert "code" in browser.arrived # the user consented at the shop's server23 print(f"{label}, iss in the answer:", "shop's" if browser.arrived.get("iss") == shop_issuer.url else "none")24 print(f"{label}, codes the attacker received:", len(attacker.stolen))25 for loot in attacker.stolen:26 claims = auth_server.claims(loot["access_token"])27 assert claims["aud"] == shop_url # the token names the shop's server as its audience28 print(f"{label}, attacker's token scope:", claims["scope"])293031asyncio.run(attempt("shop sends iss"))32asyncio.run(attempt("shop omits iss", send_iss=False, advertise_iss=False))
python mix-up-attack-blocked.pyshop sends iss, host stopped: OAuthFlowError Authorization response iss mismatch
shop sends iss, iss in the answer: shop's
shop sends iss, codes the attacker received: 0
shop omits iss, host stopped: OAuthTokenError Token exchange failed (400)
shop omits iss, iss in the answer: none
shop omits iss, codes the attacker received: 1
shop omits iss, attacker's token scope: orders:read stock:read refunds:write
The attack runs twice, against a shop authorization server that sends iss and against one that doesn't, and each run prints what the host saw and what the attacker got. In both runs the user consented at the shop's authorization server, because the request in front of them came from the real support host. When the shop sends iss, the answer carried the shop's issuer, the SDK stopped with OAuthFlowError Authorization response iss mismatch, and the attacker received 0 codes.
When the shop omits iss, the answer carried none, and the SDK went on, as the specification says it should for a server that never advertised iss. The attacker received 1 code with its verifier, redeemed it at the shop's authorization server, and holds a token for the shop's server with the scope orders:read stock:read refunds:write, refunds included. The host saw only OAuthTokenError Token exchange failed (400).
So the check protects a host only when the honest server sends iss. The security best practices say the check gives no protection against an honest server that omits iss (security best practices). The SDK follows the specification's table exactly (validate_authorization_response_iss in mcp/client/auth/utils.py). Whether the shop's tokens can be stolen this way therefore depends on the shop's authorization server, not on the host. The other defence RFC 9700 describes, a distinct redirect URI for each authorization server, doesn't help this host. RFC 9700 says it "cannot be used in scenarios where clients only register once for the use of many different issuers", and it should be used only when nothing else is available (RFC 9700, section 4.4.2.2). A client identified by a metadata document is that case, with one client_id and one list of redirect URIs for every authorization server, so the honest server accepts whichever listed URI the attacker forwards. What a host can do without the server's help is limit which authorization servers it uses at all. An attacker's server that isn't on the host's allow-list never starts a flow.
Working rule: Send iss from every authorization server you run, and advertise it with authorization_response_iss_parameter_supported: true, so that clients reject an answer without it. In a host, keep the SDK's check, add no normalisation around it, and treat a mismatch as an attack: show the user none of that response's error text. When a host must use an authorization server that doesn't send iss, keep the host to an allow-list of authorization servers, and refuse or warn the user about any server not on it. Don't count on a separate redirect URI per server when the host is identified by a metadata document.
依權杖允許的範圍來限定工具
完成〈將每個權杖綁定到單一伺服器〉與〈驗證每個回應的簽發者〉中的檢查後,商店的伺服器就知道呼叫者是誰,但仍須決定每位呼叫者可以做什麼。權杖列出已授予的範圍(scope),而商店共有三種:orders:read 用於尋找、讀取與報價訂單,stock:read 用於查詢庫存,refunds:write 用於發出退款,而退款範圍只有客服主管可以授予。
SDK 是依端點而非依工具來檢查範圍。AuthSettings.required_scopes 套用於每一個請求,而 SDK 自身回傳的 403 並未指出任何 scope(mcp/server/auth/middleware/bearer_auth.py)。規格要求提供用戶端能據以採取行動的挑戰(challenge):回傳帶有 WWW-Authenticate: Bearer error="insufficient_scope" 的 403,其中包含該操作所需的 scope 與 resource_metadata,並要求「在單一挑戰中列出目前操作所需的所有範圍」(authorization)。HTTP 中介層(middleware)可以送出這種回應。在固定的修訂版本中,每個 tools/call 都會在 Mcp-Name 標頭中指出其工具名稱,但伺服器在將它與請求本文比對之前,必須先解碼其 =?base64?...?= 形式(Streamable HTTP)。若只檢查原始標頭,經過編碼的 issue_refund 就會通過。此外,採用 2025-11-25 修訂版本的用戶端(SDK 的伺服器仍在同一端點接受它)完全不會送出 Mcp-Name。
因此,lib.tool_scopes.require 依據伺服器將實際執行的內容,並使用 SDK 所用的憑證來做決定。它從已解析本文的 params.name 讀取工具,而 Mcp-Name 標頭在依 SDK 的方式解碼後,必須與該名稱相符,否則請求會得到 -32020,HeaderMismatch。若本文不是單一的 JSON 物件,或含有重複的鍵,則予以拒絕。SDK 以第一個 Authorization 標頭進行驗證(mcp/server/auth/middleware/bearer_auth.py),因此中介層會以 400 invalid_request 拒絕含有兩個該標頭的請求,並透過 SDK 的 BearerAuthBackend 讀取權杖;若工具呼叫的權杖驗證不通過,則回應 401。
中介層預設為拒絕:未列入對照表的工具一律被拒絕。不指名任何對象的方法,例如 tools/list,只需要端點本身的範圍;其他任何方法,例如 prompts/get、resources/read 或 tasks/get,則得到 403。lib.protected_shop 對照了全部五個工具,而 lib.tool_scopes.hide_unscoped 可以隱藏權杖無法呼叫的工具(〈讓工具清單保持精簡〉)。在只有兩種讀取範圍的情況下,此範例分別在關閉與開啟隱藏時列出工具,然後送出手寫的呼叫。
1"""The shop's server refuses a refund without `refunds:write` with a 403 challenge, decided on the parsed body rather than2on `Mcp-Name` or the first `Authorization` header, refuses methods no scope maps, and can hide the tools a token can't3call. The point rests on the 403 lines, and on the refusals a header-only check would have let through: the spellings of4`Mcp-Name`, the 2025-11-25 client, and the second header."""5import json6import os78from lib import auth_server, http_mcp, loopback, protected_shop, shop_api910REFUND = {"name": "issue_refund", "arguments": {"quote_id": "Q-00000000aa"}}11IN_BASE64 = "=?base64?aXNzdWVfcmVmdW5k?=" # "issue_refund", as the spec encodes it121314def bearer(token: str, **headers: str) -> dict[str, str]:15 return {"Authorization": f"Bearer {token}", **headers}161718with auth_server.serve() as issuer, loopback.serve(shop_api.create_app()) as api_url:19 os.environ.update(shop_api.server_env(api_url)) # the server runs in this process20 for hide in (False, True): # hiding off, then on21 with protected_shop.serve(issuer.url, hide_tools=hide) as url: # hide_tools drops the tools this token can't call22 token = auth_server.mint(issuer.url, url, ["orders:read", "stock:read"])23 listed = http_mcp.post(url, "tools/list", headers=bearer(token)).json()["result"]24 print(f"hide_tools={hide}, tools listed:", ", ".join(tool["name"] for tool in listed["tools"]))25 print("tools/list cacheScope:", listed["cacheScope"]) # the SDK's default, which suits a list that depends on the token26 with protected_shop.serve(issuer.url) as url:27 token = auth_server.mint(issuer.url, url, ["orders:read", "stock:read"])28 status = http_mcp.post(url, "tools/call", {"name": "get_order_status", "arguments": {"order_id": "O-1873"}},29 headers=bearer(token))30 print("get_order_status:", status.status_code)31 refused = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token))32 print("issue_refund:", refused.status_code)33 print("challenge:", refused.headers["www-authenticate"].split(", resource_metadata")[0]) # the challenge without its URL34 assert "resource_metadata=" in refused.headers["www-authenticate"]35 # the header claims a tool the token may call, but the body asks for the refund, which the server must refuse36 lying = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token, **{"Mcp-Name": "get_order_status"}))37 print("issue_refund named get_order_status in Mcp-Name:", lying.status_code, lying.json()["error"]["code"])38 encoded = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token, **{"Mcp-Name": IN_BASE64}))39 print("issue_refund with Mcp-Name in base64:", encoded.status_code)40 # revision 2025-11-25 sends no Mcp-Name header at all, so the server must check the body for it41 print("issue_refund at 2025-11-25:", protected_shop.call_at_2025_11_25(url, token, REFUND).status_code)42 # two Authorization headers: the read-only token first, then junk, which the server must refuse outright43 twice = protected_shop.call_with_headers(url, REFUND, [("Authorization", f"Bearer {token}"),44 ("Authorization", "Bearer x")])45 print("issue_refund with two Authorization headers:", twice.status_code, twice.json()["error"])46 # prompts/get names a prompt, not a tool, so no scope in the map covers it and the server refuses it47 unmapped = http_mcp.post(url, "prompts/get", {"name": "review_refund"}, headers=bearer(token))48 print("prompts/get, which no scope maps:", unmapped.status_code)49 lead = auth_server.mint(issuer.url, url, ["orders:read", "stock:read", "refunds:write"])50 allowed = http_mcp.post(url, "tools/call", REFUND, headers=bearer(lead))51 print("issue_refund with a lead token:", allowed.status_code, json.loads(allowed.text)["result"]["isError"])
python refund-needs-a-scope.pyhide_tools=False, tools listed: find_orders, get_order_status, quote_refund, issue_refund, check_stock
hide_tools=True, tools listed: find_orders, get_order_status, quote_refund, check_stock
tools/list cacheScope: private
get_order_status: 200
issue_refund: 403
challenge: Bearer error="insufficient_scope", scope="refunds:write"
issue_refund named get_order_status in Mcp-Name: 400 -32020
issue_refund with Mcp-Name in base64: 403
issue_refund at 2025-11-25: 403
issue_refund with two Authorization headers: 400 invalid_request
prompts/get, which no scope maps: 403
issue_refund with a lead token: 200 True
伺服器從本文中的工具取得範圍。get_order_status 得到 200,issue_refund 得到 403,並附帶挑戰 Bearer error="insufficient_scope", scope="refunds:write"。該挑戰指出 refunds:write,並帶有 resource_metadata 網址。
關閉隱藏時,權杖看到的是 find_orders, get_order_status, quote_refund, issue_refund, check_stock;開啟隱藏時則是 find_orders, get_order_status, quote_refund, check_stock。無論哪一種,清單的快取範圍都是 private。這是 SDK 的預設值,適合依權杖而異的清單(〈快取清單結果〉)。
一筆退款的 Mcp-Name 宣稱是 get_order_status,結果得到 400 -32020。兩個只檢查標頭就會通過的請求,因範圍不足而被拒絕。以 Base64 編碼 Mcp-Name 的退款得到 403,來自 2025-11-25 用戶端的退款則得到 403。
使用唯讀權杖並附上多餘的第二個 Authorization 標頭的退款,得到 400 invalid_request。若檢查的是最後一個標頭,SDK 就會在唯讀權杖下完成退款。未列入對照的 prompts/get 得到 403。具備 refunds:write 時,呼叫抵達了工具,工具回應 200 True:先是狀態,接著是結果的 isError,其值為 true,因為範例中的報價 ID 並不存在。
實用原則: 將每個工具對應到其範圍,並且只以 SDK 所驗證的那個憑證來授權已解析的請求,絕不單憑標頭。拒絕含有兩個 Authorization 標頭的請求,以及對照表未涵蓋的任何方法。將 Mcp-Name 視為提示,解碼後必須與本文相符,並拒絕任何無法以與伺服器完全相同方式解析的本文。對於缺少的範圍,以 403 insufficient_scope 挑戰回應,並列出該工具的所有範圍,同時讓 required_scopes 只包含每個請求都需要的範圍。
此部分尚未翻譯,因此以英文呈現。
Ask for more scope when a call needs it
Step-up is the 403 from Scope tools by what the token allows and the client's answer to it: on insufficient_scope, the client authorizes again with the union of the scopes it asked for before and the scopes in the challenge, retries, and limits how many times it tries (authorization). The union rule is in the pinned revision's text, not in revision 2025-11-25's (2025-11-25 authorization). Without it, a client asking for refunds:write alone would lose orders:read, and its next order lookup would restart the cycle. The SDK's client steps up on 403 and unions the scopes (mcp/client/auth/oauth2.py).
A support lead and a staff member without that role each refund order O-1004 through the SDK's client. The refund, €24.98, is within the policy limit, so no confirmation is involved. The scripted consent lets the lead grant all three scopes and the other user only the two read scopes.
1"""Step-up: the SDK's client meets the refund's 403, authorizes again for the union of its scopes and `refunds:write`, and2retries. A user who may not grant `refunds:write` gets a token without it and a failed refund. The point rests on the3refund status line for the lead and the refund failure line for the other user, with the scopes each authorization asked for."""4import asyncio5import os67from lib import auth_server, loopback, oauth_client, protected_shop, shop_api8910async def refund(label: str, user_scopes: tuple[str, ...]) -> None:11 # user_scopes are the scopes this user may grant at consent; the scripted browser grants no more12 with auth_server.serve(user_scopes=user_scopes) as issuer, protected_shop.serve(issuer.url) as url:13 browser, storage = oauth_client.ScriptedBrowser(), oauth_client.MemoryStorage()14 async with oauth_client.connect(url, browser=browser, storage=storage) as client:15 quote = await client.call_tool("quote_refund", {"order_id": "O-1004", "reason": "arrived cracked"})16 print(f"{label}, quote amount:", quote.structured_content["amount"])17 print(f"{label}, quote within limit:", quote.structured_content["within_limit"])18 try:19 result = await client.call_tool("issue_refund", {"quote_id": quote.structured_content["quote_id"]})20 print(f"{label}, refund status:", result.structured_content["status"])21 except Exception as error:22 print(f"{label}, refund failed:", type(error).__name__, error)23 for number, asked in enumerate(browser.requests, start=1): # one request per authorization, in order24 print(f"{label}, authorization {number} asked for:", asked["scope"])25 print(f"{label}, token scope:", auth_server.claims(storage.tokens.access_token)["scope"])262728async def main() -> None:29 with loopback.serve(shop_api.create_app()) as api_url:30 os.environ.update(shop_api.server_env(api_url)) # the server runs in this process31 await refund("lead", auth_server.SCOPES)32 await refund("non-lead", ("orders:read", "stock:read"))333435asyncio.run(main())
python step-up-for-refunds.pylead, quote amount: 24.98
lead, quote within limit: True
lead, refund status: requested
lead, authorization 1 asked for: orders:read stock:read
lead, authorization 2 asked for: orders:read stock:read refunds:write
lead, token scope: orders:read stock:read refunds:write
non-lead, quote amount: 24.98
non-lead, quote within limit: True
non-lead, refund failed: MCPError Server returned an error response
non-lead, authorization 1 asked for: orders:read stock:read
non-lead, authorization 2 asked for: orders:read stock:read refunds:write
non-lead, token scope: orders:read stock:read
The lead's first authorization asked for orders:read stock:read, the two read scopes. The refund's 403 started a second, which asked for orders:read stock:read refunds:write, the union, although the challenge named only refunds:write. The retry went through, and the refund's status is requested.
The other user's second authorization asked for the same union. The user could grant only orders:read stock:read, and the retried call failed with MCPError Server returned an error response. The SDK stepped up once and stopped, so there was no loop. But the host got a generic error, not "this needs a lead".
Working rule: Let the SDK step up, and keep its union of scopes. List every tool a caller could gain by step-up, since a hidden tool never gets the 403 that starts it. In the host, compare the scope the token response granted with the scope the challenge asked for. When they differ, treat it as a decision, not a fault: tell the user which scope the call needs, and pass the ticket to someone who holds it. Never let an authorization server grant by step-up what a user's role doesn't allow. The client only asks, and the authorization server decides.
此部分尚未翻譯,因此以英文呈現。
What goes wrong in production
The shop's server, its authorization server and its host all work on loopback. In production they meet other people's authorization servers, gateways and clients, and each of the failures that follow leaves a trace you can look for.
An authorization server that doesn't send iss. It is a SHOULD at the pinned revision, so some authorization servers leave it out, and the SDK then proceeds without any defence against mix-up (Validate the issuer of each response). The sign is metadata without authorization_response_iss_parameter_supported. Check the metadata of each authorization server your host meets, and keep the host to an allow-list of authorization servers while any of them leaves iss out.
The silent fallback to registration. When an authorization server doesn't advertise Client ID Metadata Document support, the SDK registers dynamically without saying so (OAuth clients). Look for registration errors, or a growing list of registered clients at the authorization server. Log which kind of client ID each connection used.
The audience check is off. A server without validate_token_resource accepts tokens issued for other servers, and the only sign is an MCPDeprecationWarning at startup (Bind each token to one server). Make warnings from AuthSettings fail the deployment.
An issuer with a trailing slash. The issuer comparison is by exact string, so https://auth.fernhill.example and https://auth.fernhill.example/ are different issuers, and the SDK raises "Authorization server metadata issuer mismatch". The SDK's metadata models keep a URL without a path as it was sent, but an AnyHttpUrl object built in Python still gains the slash. Pass URLs to the SDK as strings (SDK migration guide). You'll see OAuthFlowError on the first connection to a server, from every host.
No PKCE check in the host. The SDK's client never reads code_challenge_methods_supported (Get a token with PKCE). Nothing fails, so the only sign is an audit: fetch each authorization server's metadata and look for S256.
A localhost redirect taken over. A metadata document proves which domain a client belongs to, not which program listens on a localhost redirect URI, and any local program can bind the port first. The specification says that metadata documents "cannot prevent localhost URL impersonation by themselves", and it asks authorization servers to show the redirect's host name to the user and to warn about localhost-only redirect URIs (security considerations). The giveaway is a consent screen that names the real host for a request no one at that machine made.
An authorization server used to probe the network. A server that fetches any client ID URL can be pointed at internal addresses. The draft says authorization servers MUST NOT fetch from special-use addresses, with a loopback exception only for development servers that themselves run on loopback (metadata document draft -02, section 8.6). Watch for metadata fetches to private addresses in the authorization server's logs.
Consent every few minutes. The shop's authorization server issues no refresh token, so the host runs the whole flow again whenever a token expires, and the user consents again. If you issue refresh tokens to hosts, which are public clients, the authorization server MUST rotate them, and MCP servers SHOULD NOT list offline_access in their challenges or scopes_supported (authorization). It shows up as authorization requests from one host at the token lifetime's interval.
Step-up that can never succeed. A server whose 403 names a scope the authorization server doesn't know, or one the user's role can't grant, sends every such call through a second authorization that fails. Pairs of authorization requests for one tool call, followed by a generic error in the host, are the tell (Ask for more scope when a call needs it).
Working rule: Run three probes against the deployment before the shop's server takes traffic. A request without a token gets 401 with a resource_metadata URL. A token for another resource gets 401. A refund with a read-only token gets 403 with scope="refunds:write", and the same refund with a second Authorization header gets 400. Then check the metadata of every authorization server your hosts use for S256, iss support and metadata document support, and watch the 401s, 403s and authorization requests per host.
此部分尚未翻譯,因此以英文呈現。
Decisions this chapter made
- The shop's server is an OAuth resource server over Streamable HTTP, configured with the SDK's
AuthSettings: its endpoint's URL asresource_server_url,orders:readandstock:readasrequired_scopes, andvalidate_token_resource=True. - The examples use a teaching authorization server,
lib.auth_server, not the SDK's built-in one: S256 only,resourcerequired,isssent and advertised, single-use codes, JWT access tokens withaudandscope, and no refresh tokens. It signs no one in, and its key derives from the book's public seed, so it must never be deployed. A deployment uses an established authorization server that offers S256 only, honoursresource, sends and advertisesiss, and supports Client ID Metadata Documents. - The support host is identified by a Client ID Metadata Document at an
https://URL onsupport.fernhill.example. In the examples the authorization server holds a local copy of the document in place of fetching it, and Dynamic Client Registration isn't offered. - Hosts use the SDK's
OAuthClientProviderwithclient_metadata_url, and add the PKCE support check the SDK leaves out. - Tokens are checked for audience by
AuthSettings, and the token verifier reportsaudasAccessToken.resource. - Scopes are per tool:
orders:readfor finding, reading and quoting orders,stock:readfor stock, andrefunds:write, which only support leads can grant, for refunds. An HTTP middleware decides on the parsed JSON-RPC body, withMcp-Nameonly as a hint that must match it, and with the one token the SDK authenticates, refusing a secondAuthorizationheader. It answers a missing scope with a 403 challenge, and refuses tools and named methods that it doesn't map. refunds:writearrives by step-up, never by default. It isn't inscopes_supported, and the SDK's client asks for the union of scopes when a refund needs it.- Every tool stays in
tools/list, so that step-up can start. Hiding tools by scope is available inlib.tool_scopesand unused. - Who the host acts for comes from the verified token's
sub, throughget_access_token(), never from a tool argument: for the support host, a member of staff. The customer a ticket concerns comes from the ticket record, which the server looks up and checks, not from the token or an argument. Where customers sign in themselves, see Keep the server from acting as a confused deputy.
本章,於本版次中
版次 2026.11.14範例於 2026年11 月 19 通過測試本章 7 個範例 個範例中有 7 個通過
譯自英文書,版次 2026.11.14。