OAuth로 클라이언트 인가하기

읽는 데 약 87분분 걸린다, 9절에 7개 예제이(가) 있음.

2026.11.14판 예제 통과 2026년 11월 19 70개 예제 중 70개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.14판을 번역한 것이다. 원문 읽기

이 장을 마치면 상점의 Model Context Protocol 서버를 OAuth로 보호할 수 있다. 클라이언트를 인가 서버로 안내하는 메타데이터를 게시하고, Client ID Metadata Document로 지원팀의 호스트를 식별하며, PKCE로 토큰을 얻는다. 또 상점의 서버를 위해 발급된 토큰만 받아들이고, 각 응답의 발급자(issuer)로 혼동 공격(mix-up attack)을 잡아내며, 도구마다 스코프를 요구하고 환불에 더 높은 권한이 필요할 때는 단계 상승(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은 루프백에서 동작하는 상점의 인가 서버다. 메타데이터, PKCE를 사용하는 인가 코드 승인, 모든 응답의 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 뒤에 두며, 이 장이 끝날 때의 모습 그대로다.

모든 것은 평문 HTTP로 127.0.0.1에서 실행된다. 이는 로컬 개발에서만 허용된다. 프로덕션에서는 모든 인가 서버 엔드포인트를 반드시 HTTPS로 제공해야 한다(보안 고려 사항).

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Find the authorization server from the resource

마지막으로 변경된 판: 2026.11.11판

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.

discover-the-authorization-server.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 통과
"""Protect the shop's server with OAuth, then follow its 401 to the authorization server, as a client does. The pointrests on the challenge's error line and on the PKCE methods line; the asserts check the rest of the chain."""from urllib.parse import urlsplitimport httpx2from mcp.server.auth.settings import AuthSettingsfrom lib import auth_server, http_mcp, shop_toolsdef protected(issuer: str):    def build(base_url: str):                                   # the server must know its own URL: the resource        settings = AuthSettings(issuer_url=issuer, resource_server_url=base_url + "/mcp",                                required_scopes=["orders:read", "stock:read"], validate_token_resource=True)        verifier = auth_server.JwtVerifier(issuer)        return shop_tools.create_server(version="0.8.0", auth=settings, token_verifier=verifier).streamable_http_app()    return buildwith 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 URL    first = http_mcp.post(base_url + "/mcp", "tools/list")                     # no token    print("status:", first.status_code)    # [7:] drops the scheme, "Bearer ", which is 7 characters; the values that follow are quoted    challenge = dict(part.split("=", 1) for part in first.headers["www-authenticate"][7:].split(", "))    print("challenge parameters:", ", ".join(challenge))    print("challenge error:", challenge["error"].strip('"'))    metadata_url = challenge["resource_metadata"].strip('"')    print("resource metadata path:", urlsplit(metadata_url).path)    resource = httpx2.get(metadata_url).json()    assert resource["resource"] == base_url + "/mcp"                            # RFC 9728: the endpoint's own URL    print("authorization servers:", len(resource["authorization_servers"]))    print("scopes_supported:", " ".join(resource["scopes_supported"]))    found = resource["authorization_servers"][0]                                # the one server the metadata lists    metadata = httpx2.get(found + "/.well-known/oauth-authorization-server").json()    assert metadata["issuer"] == found                                          # RFC 8414: the URL it was fetched from    print("code_challenge_methods_supported:", metadata["code_challenge_methods_supported"])    assert metadata["client_id_metadata_document_supported"]                    # the server advertises metadata documents    assert metadata["authorization_response_iss_parameter_supported"]           # and iss on every authorization response
출력python discover-the-authorization-server.py
status: 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

마지막으로 변경된 판: 2026.11.14판

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.

publish-client-metadata.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 통과
"""The support host's Client ID Metadata Document, the checks an authorization server makes on it, and the SDK's clientsending its URL as the client ID, with and without the authorization server's support. The point rests on the`client_id sent` line and on the fallback's error line, which show what the SDK did in each case."""import asynciofrom mcp.client.auth import OAuthRegistrationErrorfrom lib import auth_server, oauth_client, protected_shopdocument = auth_server.client_document()                      # served at auth_server.CLIENT_IDprint("client_id:", document["client_id"])print("redirect_uris:", ", ".join(document["redirect_uris"]))print("token_endpoint_auth_method:", document["token_endpoint_auth_method"])for label, url, candidate in [        ("as published", auth_server.CLIENT_ID, document),        ("with a secret", auth_server.CLIENT_ID, auth_server.client_document(client_secret="not-a-secret")),        ("another client_id", auth_server.CLIENT_ID, auth_server.client_document(client_id="https://partner.example/")),        ("on http", "http://support.fernhill.example/oauth/client.json", document)]:    print(f"document {label}:", auth_server.document_problem(url, candidate) or "accepted")try:    oauth_client.provider("http://127.0.0.1/mcp", browser=oauth_client.ScriptedBrowser(),                          client_metadata_url="http://localhost:4280/client.json")   # the SDK checks the scheme when it's builtexcept ValueError:    print("SDK given an http client ID: ValueError")async def connect(**server_options) -> None:    with auth_server.serve(**server_options) as issuer, protected_shop.serve(issuer.url) as url:        browser = oauth_client.ScriptedBrowser()        try:            async with oauth_client.connect(url, browser=browser) as client:                await client.list_tools()            print("client_id sent:", browser.requests[0]["client_id"])        except* OAuthRegistrationError as group:                 # the SDK fell back to registration            print("without metadata document support:", group.exceptions[0])asyncio.run(connect())                                  # the shop's server advertises metadata document supportasyncio.run(connect(advertise_cimd=False))              # a server that doesn't, so the SDK registers instead
출력python publish-client-metadata.py
client_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.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Get a token with PKCE

마지막으로 변경된 판: 2026.11.11판

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.

token-with-pkce.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 통과
"""The SDK's client gets a token for the shop's server with the authorization code grant, PKCE S256 and the resourceparameter, then the authorization server refuses a code sent twice, a wrong verifier and the plain method. The pointrests on the status line, the refusals at the end, and the asserts that check the challenge, the resource and the token."""import asyncioimport osimport httpx2from lib import auth_server, loopback, oauth_client, protected_shop, shop_apiasync def main() -> None:    with auth_server.serve() as issuer, loopback.serve(shop_api.create_app()) as api_url:        os.environ.update(shop_api.server_env(api_url))                  # the server runs in this process        with protected_shop.serve(issuer.url) as url:            browser, storage = oauth_client.ScriptedBrowser(), oauth_client.MemoryStorage()            async with oauth_client.connect(url, browser=browser, storage=storage) as client:                result = await client.call_tool("get_order_status", {"order_id": "O-1873"})            print("O-1873 status:", result.structured_content["status"])            asked, exchanged = issuer.events                              # /authorize, then /token            print("authorization request:", ", ".join(key for key in asked if key != "endpoint"))            print("code_challenge_method:", asked["code_challenge_method"])            # the challenge is the hash of the verifier that the token request revealed            assert oauth_client.s256(exchanged["code_verifier"]) == asked["code_challenge"]            assert asked["resource"] == exchanged["resource"] == url                  # the server's URL, in both requests            claims = auth_server.claims(storage.tokens.access_token)            for claim, expected in [("aud", url), ("iss", issuer.url)]:            # the server; the issuer                assert claims[claim] == expected, claim            print("token sub:", claims["sub"])            print("token scope:", claims["scope"])            print("refresh token:", storage.tokens.refresh_token)            again = httpx2.post(issuer.url + "/token", data=exchanged)      # the same code a second time            print("code sent twice:", again.status_code, again.json()["error"])            # the challenge is the hash of a verifier this example knows, so the guessed one is the only thing wrong            code = oauth_client.authorize_by_hand(issuer.url, url, challenge=oauth_client.s256("the-real-verifier"))            stolen = {**exchanged, "code": code["code"], "code_verifier": "a-guessed-verifier"}            print("wrong verifier:", httpx2.post(issuer.url + "/token", data=stolen).json()["error"])            # method="plain" sends the verifier itself as the challenge, which OAuth 2.1 forbids            plain = oauth_client.authorize_by_hand(issuer.url, url, challenge="the-real-verifier", method="plain")            print("plain method:", plain["error"], "/", plain["error_description"])asyncio.run(main())
출력python token-with-pkce.py
O-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

마지막으로 변경된 판: 2026.11.11판

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.

wrong-audience-rejected.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 통과
"""A token issued for another server, presented to the shop's server: the SDK's default accepts it, and it's refused oncethe server checks the audience, either through AuthSettings or in the token verifier. The point rests on the partner'stoken's status line in each configuration, and on the warning line that the default alone raises."""import warningsfrom mcp.server.auth.settings import AuthSettingsfrom lib import auth_server, http_mcp, shop_toolsPARTNER = "https://partner.example/mcp"                  # another MCP server, with the same authorization serverSCOPES = ["orders:read", "stock:read"]def shop(issuer: str, validate_token_resource: bool | None, verifier_checks_aud: bool):    def build(base_url: str):        resource = base_url + "/mcp"        # the verifier checks aud only when it's given an audience; None checks nothing        verifier = auth_server.JwtVerifier(issuer, audience=resource if verifier_checks_aud else None)        # None leaves the SDK's default in place, which is off and warns; True refuses other servers' tokens        settings = AuthSettings(issuer_url=issuer, resource_server_url=resource, required_scopes=SCOPES,                                validate_token_resource=validate_token_resource)        return shop_tools.create_server(auth=settings, token_verifier=verifier).streamable_http_app()    return buildwith auth_server.serve() as issuer:    for label, validate, in_verifier in [("SDK default", None, False), ("validate_token_resource=True", True, False),                                         ("verifier checks aud", False, True)]:        # record every warning, and show them all, so each configuration reports only what it raised        with warnings.catch_warnings(record=True) as caught:            warnings.simplefilter("always")            with auth_server.serve_built(shop(issuer.url, validate, in_verifier)) as base_url:                url = base_url + "/mcp"                own = auth_server.mint(issuer.url, url, SCOPES)                foreign = auth_server.mint(issuer.url, PARTNER, SCOPES)     # signed by the same authorization server                for name, token in [("own token", own), ("partner's token", foreign)]:                    response = http_mcp.post(url, "tools/list", headers={"Authorization": f"Bearer {token}"})                    print(f"{label}, {name}:", response.status_code)        print(f"{label}, warnings:", ", ".join(sorted({w.category.__name__ for w in caught})) or "none")
출력python wrong-audience-rejected.py
SDK 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

마지막으로 변경된 판: 2026.11.11판

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.

mix-up-attack-blocked.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 통과
"""A mix-up attack on the support host, run against a shop server that sends `iss` and one that omits it. The point restson the codes-received lines: the `iss` mismatch leaves the attacker nothing, and without `iss` it gets a token."""import asynciofrom mcp.client.auth import OAuthFlowError, OAuthTokenErrorfrom lib import auth_server, oauth_client, protected_shopasync def attempt(label: str, **shop_options) -> None:    with auth_server.serve(**shop_options) as shop_issuer, protected_shop.serve(shop_issuer.url) as shop_url:        # the attacker's server forwards the browser to the shop's, and the partner's server names the attacker        with auth_server.serve_mix_up(shop_issuer.url, target=shop_url) as attacker, \                protected_shop.serve(attacker.url) as partner_url:            browser = oauth_client.ScriptedBrowser()            try:                async with oauth_client.connect(partner_url, browser=browser) as client:                    await client.list_tools()            except* (OAuthFlowError, OAuthTokenError) as group:                error = group.exceptions[0]                print(f"{label}, host stopped:", type(error).__name__, str(error).split(":")[0])  # the message's first phrase            assert "code" in browser.arrived                                  # the user consented at the shop's server            print(f"{label}, iss in the answer:", "shop's" if browser.arrived.get("iss") == shop_issuer.url else "none")            print(f"{label}, codes the attacker received:", len(attacker.stolen))            for loot in attacker.stolen:                claims = auth_server.claims(loot["access_token"])                assert claims["aud"] == shop_url                              # the token names the shop's server as its audience                print(f"{label}, attacker's token scope:", claims["scope"])asyncio.run(attempt("shop sends iss"))asyncio.run(attempt("shop omits iss", send_iss=False, advertise_iss=False))
출력python mix-up-attack-blocked.py
shop 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.

토큰이 허용하는 범위로 도구를 제한하기

마지막으로 변경된 판: 2026.11.11판

토큰을 하나의 서버에 묶기와 각 응답의 발급자 검증하기의 검사를 마치면, 상점 서버는 호출자가 누구인지 알게 된다. 그래도 각 호출자가 무엇을 할 수 있는지는 서버가 따로 정해야 한다. 토큰에는 부여된 스코프가 나열되며, 상점에는 스코프가 세 개 있다. 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를 받는다. 하나의 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는 토큰이 호출할 수 없는 도구를 숨길 수 있다(도구 목록을 작게 유지하기). 예제는 읽기 스코프 두 개를 가진 토큰으로 숨김을 끈 상태와 켠 상태에서 도구를 나열한 다음, 직접 작성한 호출을 보낸다.

refund-needs-a-scope.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 통과
"""The shop's server refuses a refund without `refunds:write` with a 403 challenge, decided on the parsed body rather thanon `Mcp-Name` or the first `Authorization` header, refuses methods no scope maps, and can hide the tools a token can'tcall. The point rests on the 403 lines, and on the refusals a header-only check would have let through: the spellings of`Mcp-Name`, the 2025-11-25 client, and the second header."""import jsonimport osfrom lib import auth_server, http_mcp, loopback, protected_shop, shop_apiREFUND = {"name": "issue_refund", "arguments": {"quote_id": "Q-00000000aa"}}IN_BASE64 = "=?base64?aXNzdWVfcmVmdW5k?="                                   # "issue_refund", as the spec encodes itdef bearer(token: str, **headers: str) -> dict[str, str]:    return {"Authorization": f"Bearer {token}", **headers}with auth_server.serve() as issuer, loopback.serve(shop_api.create_app()) as api_url:    os.environ.update(shop_api.server_env(api_url))                       # the server runs in this process    for hide in (False, True):                                       # hiding off, then on        with protected_shop.serve(issuer.url, hide_tools=hide) as url:  # hide_tools drops the tools this token can't call            token = auth_server.mint(issuer.url, url, ["orders:read", "stock:read"])            listed = http_mcp.post(url, "tools/list", headers=bearer(token)).json()["result"]            print(f"hide_tools={hide}, tools listed:", ", ".join(tool["name"] for tool in listed["tools"]))    print("tools/list cacheScope:", listed["cacheScope"])                 # the SDK's default, which suits a list that depends on the token    with protected_shop.serve(issuer.url) as url:        token = auth_server.mint(issuer.url, url, ["orders:read", "stock:read"])        status = http_mcp.post(url, "tools/call", {"name": "get_order_status", "arguments": {"order_id": "O-1873"}},                               headers=bearer(token))        print("get_order_status:", status.status_code)        refused = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token))        print("issue_refund:", refused.status_code)        print("challenge:", refused.headers["www-authenticate"].split(", resource_metadata")[0])   # the challenge without its URL        assert "resource_metadata=" in refused.headers["www-authenticate"]        # the header claims a tool the token may call, but the body asks for the refund, which the server must refuse        lying = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token, **{"Mcp-Name": "get_order_status"}))        print("issue_refund named get_order_status in Mcp-Name:", lying.status_code, lying.json()["error"]["code"])        encoded = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token, **{"Mcp-Name": IN_BASE64}))        print("issue_refund with Mcp-Name in base64:", encoded.status_code)        # revision 2025-11-25 sends no Mcp-Name header at all, so the server must check the body for it        print("issue_refund at 2025-11-25:", protected_shop.call_at_2025_11_25(url, token, REFUND).status_code)        # two Authorization headers: the read-only token first, then junk, which the server must refuse outright        twice = protected_shop.call_with_headers(url, REFUND, [("Authorization", f"Bearer {token}"),                                                               ("Authorization", "Bearer x")])        print("issue_refund with two Authorization headers:", twice.status_code, twice.json()["error"])        # prompts/get names a prompt, not a tool, so no scope in the map covers it and the server refuses it        unmapped = http_mcp.post(url, "prompts/get", {"name": "review_refund"}, headers=bearer(token))        print("prompts/get, which no scope maps:", unmapped.status_code)        lead = auth_server.mint(issuer.url, url, ["orders:read", "stock:read", "refunds:write"])        allowed = http_mcp.post(url, "tools/call", REFUND, headers=bearer(lead))        print("issue_refund with a lead token:", allowed.status_code, json.loads(allowed.text)["result"]["isError"])
출력python refund-needs-a-scope.py
hide_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를 받았다. 헤더만 검사하는 방식이라면 통과시켰을 요청 두 건이 스코프 때문에 거부되었다. Mcp-Name가 Base64인 환불은 403를 받았고, 2025-11-25 클라이언트의 환불은 403를 받았다.

읽기 전용 토큰에 의미 없는 두 번째 Authorization 헤더를 붙인 환불은 400 invalid_request를 받았다. 마지막 헤더를 읽는 검사였다면 SDK가 읽기 전용 토큰으로 환불을 처리했을 것이다. 매핑되지 않은 prompts/get는 403를 받았다. refunds:write가 있으면 호출이 도구에 도달했고, 도구는 200 True로 응답했다. 앞은 상태이고, 뒤는 결과의 isError이며, 예제의 견적 ID가 존재하지 않으므로 true이다.

작업 규칙: 모든 도구를 해당 스코프에 매핑하고, 헤더만으로 판단하지 말고 SDK가 인증하는 바로 그 자격 증명으로 파싱된 요청을 승인한다. Authorization 헤더가 둘이면 거부하고, 맵이 다루지 않는 메서드도 거부한다. Mcp-Name는 디코딩한 뒤 본문과 일치해야 하는 힌트로 취급하고, 서버가 파싱하는 방식과 똑같이 파싱할 수 없는 본문은 거부한다. 스코프가 없으면 도구가 요구하는 모든 스코프를 지정한 403 insufficient_scope 챌린지로 응답하고, required_scopes는 모든 요청에 필요한 범위로 한정한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Ask for more scope when a call needs it

마지막으로 변경된 판: 2026.11.14판

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.

step-up-for-refunds.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 통과
"""Step-up: the SDK's client meets the refund's 403, authorizes again for the union of its scopes and `refunds:write`, andretries. A user who may not grant `refunds:write` gets a token without it and a failed refund. The point rests on therefund status line for the lead and the refund failure line for the other user, with the scopes each authorization asked for."""import asyncioimport osfrom lib import auth_server, loopback, oauth_client, protected_shop, shop_apiasync def refund(label: str, user_scopes: tuple[str, ...]) -> None:    # user_scopes are the scopes this user may grant at consent; the scripted browser grants no more    with auth_server.serve(user_scopes=user_scopes) as issuer, protected_shop.serve(issuer.url) as url:        browser, storage = oauth_client.ScriptedBrowser(), oauth_client.MemoryStorage()        async with oauth_client.connect(url, browser=browser, storage=storage) as client:            quote = await client.call_tool("quote_refund", {"order_id": "O-1004", "reason": "arrived cracked"})            print(f"{label}, quote amount:", quote.structured_content["amount"])            print(f"{label}, quote within limit:", quote.structured_content["within_limit"])            try:                result = await client.call_tool("issue_refund", {"quote_id": quote.structured_content["quote_id"]})                print(f"{label}, refund status:", result.structured_content["status"])            except Exception as error:                print(f"{label}, refund failed:", type(error).__name__, error)        for number, asked in enumerate(browser.requests, start=1):          # one request per authorization, in order            print(f"{label}, authorization {number} asked for:", asked["scope"])        print(f"{label}, token scope:", auth_server.claims(storage.tokens.access_token)["scope"])async def main() -> None:    with loopback.serve(shop_api.create_app()) as api_url:        os.environ.update(shop_api.server_env(api_url))                    # the server runs in this process        await refund("lead", auth_server.SCOPES)        await refund("non-lead", ("orders:read", "stock:read"))asyncio.run(main())
출력python step-up-for-refunds.py
lead, 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

마지막으로 변경된 판: 2026.11.11판

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

마지막으로 변경된 판: 2026.11.11판
  • The shop's server is an OAuth resource server over Streamable HTTP, configured with the SDK's AuthSettings: its endpoint's URL as resource_server_url, orders:read and stock:read as required_scopes, and validate_token_resource=True.
  • The examples use a teaching authorization server, lib.auth_server, not the SDK's built-in one: S256 only, resource required, iss sent and advertised, single-use codes, JWT access tokens with aud and scope, 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, honours resource, sends and advertises iss, and supports Client ID Metadata Documents.
  • The support host is identified by a Client ID Metadata Document at an https:// URL on support.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 OAuthClientProvider with client_metadata_url, and add the PKCE support check the SDK leaves out.
  • Tokens are checked for audience by AuthSettings, and the token verifier reports aud as AccessToken.resource.
  • Scopes are per tool: orders:read for finding, reading and quoting orders, stock:read for stock, and refunds:write, which only support leads can grant, for refunds. An HTTP middleware decides on the parsed JSON-RPC body, with Mcp-Name only as a hint that must match it, and with the one token the SDK authenticates, refusing a second Authorization header. It answers a missing scope with a 403 challenge, and refuses tools and named methods that it doesn't map.
  • refunds:write arrives by step-up, never by default. It isn't in scopes_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 in lib.tool_scopes and unused.
  • Who the host acts for comes from the verified token's sub, through get_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판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 8장: OAuth로 클라이언트 인가하기

  1. Find the authorization server from the resource
  2. Identify the client with a metadata document
  3. Get a token with PKCE
  4. Bind each token to one server
  5. Validate the issuer of each response
  6. 토큰이 허용하는 범위로 도구를 제한하기
  7. Ask for more scope when a call needs it
  8. What goes wrong in production
  9. Decisions this chapter made

맨 위로 돌아가기전체 장