OAuthでクライアントを認可する
読了まで約94 分分、9 節 節の 7 例 例。
この章を終えると、ショップの Model Context Protocol サーバーを OAuth で保護できるようになる。クライアントを認可サーバーへ導くメタデータを公開し、Client ID Metadata Document でサポートチームのホストを識別し、PKCE でトークンを取得し、ショップのサーバー向けに発行されたトークンだけを受け付け、各レスポンスの発行者によってミックスアップ攻撃を検出し、ツールごとにスコープを要求する。返金にさらに強い権限が必要な場合は、ステップアップを行う。ここでの記述は、リビジョン 2026-07-28 の仕様のものであり、Python SDK である mcp 2.3.0 が実装する内容に沿っている。
Serve over Streamable HTTP では、サポートスタッフが注文を閲覧し返金を行うためのサーバーである shop-support を、the shop の HTTP アドレスへ移し、ホスト同士で共有できるようにした。Origin チェックが防ぐのは Web ページからのアクセスだけである。ポートに到達できるプログラムであれば、どれでも注文を読み、返金を行える(Reject requests from other origins)。そのためショップは、どのホストが、誰のために呼び出しているのか、そしてその人に何が許されているのかを知る必要がある。サポートスタッフは注文と在庫を閲覧できる。返金できるのはサポートリードだけである。
Model Context Protocol(MCP)は、この問題に OAuth 2.1 で答える。MCP では認可は任意であり、HTTP トランスポートに属する。stdio サーバーは、代わりに環境から認証情報を受け取る(authorization)。保護された MCP サーバーは OAuth のリソースサーバーであり、ホストがそれに対して使うクライアントは OAuth クライアントである。トークンを発行するのは認可サーバーで、MCP サーバーと同じ場所に置くことも、別に置くこともできる。このフローは、他の API のクライアント側として知っているだろう。MCP で変わるのは、クライアントがサーバーについて事前に何も知らないという点である。クライアントは URL から出発するため、ディスカバリー、クライアントの識別、トークンのオーディエンスのすべてが、双方の事前設定なしに機能しなければならない。
examples/lib/ にある 4 つの共有モジュールがこの章の準備を担うので、各例ではその要点だけを示す。
lib.auth_serverは、ループバック上で動くショップの認可サーバーである。メタデータ、PKCE 付きの認可コードグラント、すべての応答におけるiss、そして 1 つのサーバーに結び付けられた JWT アクセストークンを備える。同意は、ブラウザの前にいる人の代わりにスクリプトで行う。これはループバックの例のための教育用サーバーであり、決してデプロイしてはならない。誰もサインインさせず、署名鍵は本書の公開シードから導出されるため、本書を持つ人なら誰でも、このサーバーが受け付けるトークンを作れる。実際の運用では、この章のチェックを満たす既存の認可サーバーを使う。Python SDK にも独自の認可サーバーがあるが、そのドキュメントは新規サーバーでの使用を勧めておらず、そのメタデータはissも Client ID Metadata Document も告知しない(SDK authorization docs)。lib.oauth_clientはホスト側である。トークンをメモリ上に保存する SDK のOAuthClientProviderと、認可サーバーのリダイレクトをたどって結果を SDK に返す、スクリプト化されたブラウザから成る。lib.tool_scopesは、SDK にないツールごとのスコープチェックを加える。lib.protected_shopはこれらを組み合わせ、第 3 章の 5 つのツールを、この章が仕上げる形で OAuth の背後に置く。
すべては 127.0.0.1 上で、平文の HTTP により動く。これが許されるのはローカル開発に限る。本番環境では、認可サーバーのすべてのエンドポイントを HTTPS で提供しなければならない(MUST)(security considerations)。
この部分はまだ翻訳されていないため、英語で表示している。
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.
メタデータ文書でクライアントを識別する
リソースから認可サーバーを見つけるは、ホストがトークンをどこで取得するかを示す。それでも認可サーバーは、どのクライアントが要求しているのかを知る必要がある。ホストは見たことのない MCP サーバーに出会うため、各サーバーの認可サーバーへ事前に登録しておくことはできない。固定されたリビジョンは、クライアント ID を得る方法に優先順位を付けている。まず、事前登録されたクライアント情報があれば、それが最優先となる。次に、認可サーバーが client_id_metadata_document_supported を通知している場合は、Client ID Metadata Document を用いる。その次が Dynamic Client Registration であり、これらのいずれも使えない場合に限って、ユーザーに尋ねる(クライアント登録)。
Client ID Metadata Document は、クライアント ID を URL にする仕組みである。クライアントは、パスを持つ https:// URL に JSON 文書を公開し、その URL がそのまま client_id となる。文書には、少なくとも、URL と完全に一致する client_id、client_name、redirect_uris を含めなければならない(クライアント登録)。認可サーバーは、クライアントが初めて現れたときに文書を取得し、ID とリダイレクト URI を文書の内容と照合する。取得結果は HTTP ヘッダーに従ってキャッシュしてもよい。取得時にリダイレクトを辿ってはならず、エラーをキャッシュしてもならない(メタデータ文書ドラフト -02)。
client_secret は禁止されているため、文書は共有シークレットを持てない。したがって、この方法で識別されるクライアントはパブリッククライアントであり、PKCE に依拠するか、private_key_jwt を通じて鍵ペアで自らを証明する(ドラフト -02、4.1 節)。MCP 仕様はこの文書のドラフト -00 にリンクしているが、本書では、より新しいドラフト -02 を引用する。文書から得たクライアント ID は、どの認可サーバーでも通用する。これに対し、事前登録されたクライアント ID や登録で得たクライアント ID は、発行したサーバーに結び付いており、固定されたリビジョンは、別のサーバーでの再利用を禁じている(クライアント登録)。
Dynamic Client Registration は、固定されたリビジョンでは非推奨である。メタデータ文書に対応しない認可サーバー向けのフォールバックとして残されており、最も早い削除時期は、2027-07-28 以降に最初にリリースされるリビジョンである(非推奨の機能)。クライアントをこの方式から移行する手順は、Dynamic Client Registration を置き換えるで扱う。
サポートチームのホストは、文書を https://support.fernhill.example/oauth/client.json に公開する。この例ではネットワークには一切接続せず、fernhill.example も名前解決されないため、ショップの認可サーバーは文書を取得できない。そこで、ホストにループバックサーバーが取得できてしまう http:// のクライアント ID を与える代わりに、lib.auth_server は、クライアント ID の URL から文書への対応表に文書を保持する。この対応表が取得処理の代役となり、サーバーは、取得したコピーに適用するのと同じ検査をそこに適用する。これは URL の事前登録であり、ドラフトが、クライアント ID の URL とそのメタデータを「他の手段」で関連付けることを認めているものに当たる(ドラフト -02、5 節)。これはテスト専用の代用手段であり、実際に運用される認可サーバーは、HTTPS で文書を取得する。
コードは、文書の主要な値を出力し、その文書と 3 つの壊れたコピーにサーバーの検査を実行し、SDK に http:// のクライアント ID を与え、そのうえで 2 回接続する。接続先は、メタデータ文書に対応する認可サーバーと、対応しない認可サーバーである。
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
文書は自身の ID として https://support.fernhill.example/oauth/client.json を名乗り、そのリダイレクト URI は http://localhost:4280/callback である。トークンエンドポイントの認証方式は none であるため、ホストはシークレットを保持しない。認可サーバーは、公開されたとおりの文書を受理する。
シークレットを含むコピーは「document carries a shared secret」で失敗し、残りの 2 つの壊れたコピーも、横に出力された理由で失敗する。1 つは client_id が別のサイトを指すもの、もう 1 つはクライアント ID が http 上にあるものである。SDK も自身の側で、同じ https の検査を行う。http:// のクライアント ID を与えると、OAuthClientProvider は構築した時点で ValueError を送出する(mcp/client/auth/utils.py)。
SDK のクライアントは、文書の URL をクライアント ID として使い、サーバーが対応していない場合は黙ってフォールバックする。ショップの認可サーバーに対しては、クライアント ID として https://support.fernhill.example/oauth/client.json を送り、登録リクエストは行わなかった。対応を通知しないサーバーに対しては、何も表示せずに Dynamic Client Registration にフォールバックし、フローは「Registration failed: 404 Not Found」で終了した。ショップの認可サーバーには登録エンドポイントがないためである。SDK のドキュメントは、このフォールバックを無言のものと説明している(OAuth クライアント)。ホストにとって、メタデータ文書に対応しない認可サーバーは、機能の欠如としてではなく、登録エラーとして現れる。
実践ルール: すべてのホストに、安定した https:// URL で公開する Client ID Metadata Document を 1 つ用意する。文書には実際に使うリダイレクト URI だけを記載し、シークレットは含めない。その URL を client_metadata_url として SDK に渡す。認可サーバーが事前登録の認証情報を発行している場合は、それが最優先であるため、そちらを使う。Dynamic Client Registration は、ほかに何も対応していない認可サーバーに限って使う。ループバックでのテストでは、クライアント ID を https:// の URL のままにして、テスト用認可サーバーの中でそれを文書のローカルコピーと関連付ける。本番のどのサーバーも受け付けない http:// の ID をクライアントに与えてはならない。
この部分はまだ翻訳されていないため、英語で表示している。
Get a token with PKCE
With its client ID from Identify the client with a metadata document, the host can ask for a token. MCP uses the authorization code grant. The host sends the user's browser to the authorization server's authorization endpoint, the user signs in and consents, and the browser returns to the host's redirect URI with a code. The host then exchanges that code for a token at the token endpoint. Three parameters of that exchange carry most of its security.
PKCE binds the code to the client that asked for it. The client makes a random code_verifier, sends its SHA-256 hash as code_challenge with code_challenge_method=S256, and reveals the verifier only in the token request, so someone who intercepts the code doesn't have it. MCP clients MUST use PKCE with S256, and MUST refuse to go on if the authorization server's metadata has no code_challenge_methods_supported (security considerations). OAuth 2.1 has explicitly forbidden the plain method, where the challenge is the verifier itself, since draft-16 (OAuth 2.1 draft-16, section 7.5.2). The MCP specification cites draft-13, which still allowed it (OAuth 2.1 draft-13).
The resource parameter (RFC 8707) names the server the token is for, by the server's canonical URI. MCP clients MUST send it in both the authorization request and the token request, whether or not the authorization server supports it (authorization). And state, which the client checks when the browser returns, ties the answer to the request.
The SDK's client runs that whole flow for the host, and the example watches it from the authorization server's side. lib.oauth_client.connect gives the client an OAuthClientProvider with the host's metadata document URL and a scripted browser in place of a person. The browser opens the authorization URL, follows the redirects, and stops at the first one addressed to the redirect URI. The person's consent at the authorization server is scripted too: the signed-in user grants every requested scope that their role allows. The example calls get_order_status, reads what the authorization server logged, and then sends the authorization server three requests the SDK never would.
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
The call worked, and order O-1873 is delivered. The authorization request carried response_type, client_id, redirect_uri, state, code_challenge, code_challenge_method, resource, scope, with the method S256, and its challenge is the hash of the verifier that the token request revealed. Both requests named the same resource, the endpoint's URL. The access token is a JWT whose aud is the server's URL and whose iss is the authorization server. Its scope is orders:read stock:read, the server's scopes_supported, because the 401 named no scope.
The token's sub, staff-0007, names the member of the support staff the host acts for, not a customer, and a server reads it from the SDK's get_access_token().subject. So a staff token can't by itself replace SHOP_CUSTOMER_ID, which the order completion in Complete arguments for the user read from its environment over stdio. For a support host, the customer comes from the record of the ticket the staff member is working on, which the server looks up and checks, never from a tool argument. Only where customers sign in to a host themselves is sub the customer, the case Keep the server from acting as a confused deputy takes up. There is no refresh token (None): the shop's authorization server issues none, and the specification tells clients not to assume one (authorization).
The three requests the SDK never sends show what PKCE and single-use codes stop. The same code sent a second time got 400 invalid_grant, because a code works once. A fresh code sent with a guessed verifier got invalid_grant, so a stolen code alone is worth nothing. A request with plain got "invalid_request / PKCE with S256 is required", because the shop's authorization server accepts only S256.
One check falls to the host. The SDK's client always sends S256, but it never reads code_challenge_methods_supported, so it goes ahead with an authorization server whose metadata leaves the field out (mcp/client/auth/oauth2.py). A host that must meet the specification fetches each authorization server's metadata itself before it connects, and it refuses any server that doesn't list S256.
Working rule: Let the SDK's OAuthClientProvider run the authorization code flow, and check once, from the authorization server's side, what it sends: S256, state, and a resource equal to the server's URL in both requests. Add the check the SDK skips, and refuse an authorization server whose metadata doesn't list S256. On an authorization server you run, accept only S256, make codes single-use and short-lived, and bind each code to its client, its redirect URI and its resource.
この部分はまだ翻訳されていないため、英語で表示している。
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.
トークンが許可する範囲でツールのスコープを決める
トークンを1つのサーバーに結び付けると各レスポンスの発行者を検証するの検査が済むと、ショップのサーバーは誰が呼び出しているかを把握できる。だが、各呼び出し元に何を許すかは、なおサーバーが決めなければならない。トークンには付与されたスコープが列挙されている。ショップのスコープは3つある。orders:readは注文の検索、参照、見積もりのため、stock:readは在庫の確認のため、refunds:writeは返金の実行のためのものであり、返金のスコープを付与できるのはサポートリーダーだけである。
SDK はスコープをツールごとではなくエンドポイントごとに検査する。AuthSettings.required_scopesはすべてのリクエストに適用され、SDK 自身の 403 には scope が示されない(mcp/server/auth/middleware/bearer_auth.py)。仕様は、クライアントが対処できるチャレンジを求めている。すなわち、WWW-Authenticate: Bearer error="insufficient_scope"を伴う 403 であり、その操作に必要なscopeとresource_metadataを含み、「現在の操作に必要なすべてのスコープを単一のチャレンジに」含めるというものである(authorization)。これは HTTP ミドルウェアで送出できる。固定されたリビジョンでは、各tools/callはMcp-Nameヘッダーにツール名を載せるが、サーバーは本文と比較する前に、その=?base64?...?=形式を必ずデコードしなければならない(Streamable HTTP)。生のヘッダーだけを検査すると、エンコードされたissue_refundが通過してしまう。さらに、SDK のサーバーが同じエンドポイントで引き続き受け付けるリビジョン 2025-11-25 のクライアントは、Mcp-Nameをまったく送らない。
そこでlib.tool_scopes.requireは、SDK が使う資格情報を用い、サーバーが実行する内容に基づいて判定する。ツールは解析済みの本文のparams.nameから読み取る。Mcp-Nameヘッダーは SDK と同じ方法でデコードしたうえでその名前と一致しなければならず、一致しなければリクエストは -32020、HeaderMismatchとなる。1つの JSON オブジェクトでない本文や、キーが重複している本文は拒否する。SDK は最初のAuthorizationヘッダーで認証する(mcp/server/auth/middleware/bearer_auth.py)。したがってミドルウェアは、それが2つあるリクエストを 400 invalid_requestで拒否し、トークンは SDK のBearerAuthBackendを通して読み取る。トークンが検証できないツール呼び出しには 401 を返す。
ミドルウェアは既定で拒否する。対応表にないツールは拒否される。tools/listのように何も指名しないメソッドには、エンドポイントのスコープだけが必要である。prompts/get、resources/read、tasks/getなど、その他のメソッドは 403 になる。lib.protected_shopは5つのツールすべてを対応付けており、lib.tool_scopes.hide_unscopedは、トークンが呼び出せないツールを隠せる(ツール一覧を小さく保つ)。例では、2つの読み取りスコープを持つトークンで、隠す設定をオフとオンにしてツールを一覧し、続いて手書きの呼び出しを送る。
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 URL を伴う。
隠す設定がオフのとき、トークンには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となった。ヘッダーだけの検査なら通過する2つのリクエストが、スコープ不足で拒否された。Mcp-Nameを Base64 にした返金は403となり、2025-11-25 のクライアントからの返金は403となった。
読み取り専用のトークンと、不正な2つ目のAuthorizationヘッダーを伴う返金は、400 invalid_requestとなった。最後のヘッダーを読む検査では、SDK が読み取り専用トークンで返金してしまっただろう。対応表にないprompts/getは403となった。refunds:writeを持つ場合、呼び出しはツールに到達し、ツールは200 Trueを返した。これはステータスに続いて結果のisErrorが並んだものであり、例の見積もり ID が存在しないため true である。
実践ルール: すべてのツールをそのスコープに対応付け、リクエストの認可は、ヘッダーだけに頼らず、SDK が認証するものとまったく同じ資格情報で、解析済みのリクエストに対して行う。Authorizationヘッダーが2つあるリクエストと、対応表が扱わないメソッドは拒否する。Mcp-Nameは、デコードしたうえで本文と一致しなければならないヒントとして扱い、サーバーとまったく同じようには解析できない本文は拒否する。スコープが不足している場合は、そのツールのすべてのスコープを示す 403 insufficient_scopeチャレンジで応答し、required_scopesはすべてのリクエストが必要とするものだけにとどめる。
呼び出しがより広いスコープを必要とするときに追加を求める
ステップアップとは、トークンが許可する範囲でツールのスコープを絞るで扱った 403 と、それに対するクライアントの応答である。insufficient_scope を受け取ると、クライアントは、以前に要求したスコープとチャレンジに含まれるスコープの和集合を使って再度認可を行い、呼び出しを再試行し、試行回数に上限を設ける(authorization)。この和集合の規則は固定したリビジョンの本文にあり、リビジョン 2025-11-25 の本文にはない(2025-11-25 authorization)。この規則がなければ、refunds:write だけを要求するクライアントは orders:read を失い、次の注文照会でふたたび同じ循環が始まる。SDK のクライアントは 403 でステップアップを行い、スコープの和集合をとる(mcp/client/auth/oauth2.py)。
サポートリードと、その役割を持たないスタッフが、それぞれ SDK のクライアントを通じて注文 O-1004 を返金する。返金額は €24.98 で、ポリシー上の上限内にあるため、確認は関与しない。スクリプト化された同意処理では、リードは 3 つのスコープすべてを付与でき、もう一方のユーザーは 2 つの読み取りスコープだけを付与できる。
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
リードの最初の認可が要求したのは orders:read stock:read、すなわち 2 つの読み取りスコープであった。返金の 403 によって 2 回目の認可が始まり、そこで要求されたのは orders:read stock:read refunds:write、すなわち和集合であった。チャレンジが挙げていたのは refunds:write だけだったにもかかわらずである。再試行は成功し、返金の状態は requested となる。
もう一方のユーザーの 2 回目の認可も同じ和集合を要求した。このユーザーが付与できたのは orders:read stock:read だけで、再試行した呼び出しは MCPError Server returned an error response で失敗した。SDK はステップアップを一度行って止まったので、ループは起きていない。しかしホストが受け取ったのは汎用的なエラーであり、「これにはリードが必要である」という情報ではなかった。
実践ルール: ステップアップは SDK に任せ、スコープの和集合は保持する。呼び出し側がステップアップによって得られる可能性のあるツールは、すべて一覧に載せる。隠されたツールは、ステップアップを開始させる 403 を受け取らないからである。ホストでは、トークンのレスポンスが付与したスコープと、チャレンジが求めたスコープを比較する。両者が異なる場合は、障害ではなく判断の場面として扱う。その呼び出しにどのスコープが必要かをユーザーに伝え、そのスコープを持つ人にチケットを引き渡す。ユーザーの役割が許していないものを、認可サーバーがステップアップで付与することは決して許してはならない。クライアントは要求するだけであり、決定するのは認可サーバーである。
この部分はまだ翻訳されていないため、英語で表示している。
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)から翻訳した。