|
| 1 | +"""OAuth 2.0 Token Exchange (RFC 8693) client provider for MCP. |
| 2 | +
|
| 3 | +Provides `TokenExchangeOAuthProvider`, which exchanges a security token issued by an |
| 4 | +enterprise identity provider for an MCP access token at the MCP authorization server's |
| 5 | +token endpoint. This is the client side of SEP-990 (enterprise IdP policy controls): the |
| 6 | +client first obtains an Identity Assertion Authorization Grant (ID-JAG) from the IdP, then |
| 7 | +exchanges it here for a token usable against the MCP server. |
| 8 | +
|
| 9 | +Obtaining the ID-JAG (logging into the IdP and performing the first token exchange against |
| 10 | +it) is deployment-specific and out of scope for the SDK. The caller supplies it through the |
| 11 | +`subject_token_provider` callback, which receives the MCP authorization server's issuer |
| 12 | +identifier as its audience and returns the security token to exchange. |
| 13 | +""" |
| 14 | + |
| 15 | +from collections.abc import Awaitable, Callable |
| 16 | +from typing import Any, Literal |
| 17 | + |
| 18 | +import httpx |
| 19 | + |
| 20 | +from mcp.client.auth import OAuthClientProvider, OAuthFlowError, TokenStorage |
| 21 | +from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata |
| 22 | + |
| 23 | +TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" |
| 24 | +JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt" |
| 25 | +ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" |
| 26 | + |
| 27 | + |
| 28 | +class TokenExchangeOAuthProvider(OAuthClientProvider): |
| 29 | + """OAuth provider for the RFC 8693 token-exchange grant. |
| 30 | +
|
| 31 | + Exchanges a subject token (for SEP-990, the IdP-issued ID-JAG) for an MCP access token, |
| 32 | + bypassing the interactive authorization-code flow and dynamic client registration. The |
| 33 | + subject token is fetched lazily from `subject_token_provider` so a fresh token is used on |
| 34 | + each exchange. |
| 35 | +
|
| 36 | + Example: |
| 37 | + ```python |
| 38 | + async def fetch_id_jag(audience: str) -> str: |
| 39 | + # `audience` is the MCP authorization server's issuer identifier; the returned |
| 40 | + # ID-JAG must carry that as its `aud` claim. How the ID-JAG is obtained from the |
| 41 | + # enterprise IdP is deployment-specific and not handled by the SDK. |
| 42 | + return await my_idp.exchange_id_token_for_id_jag(audience=audience) |
| 43 | +
|
| 44 | +
|
| 45 | + provider = TokenExchangeOAuthProvider( |
| 46 | + server_url="https://mcp.example.com/mcp", |
| 47 | + storage=my_token_storage, |
| 48 | + client_id="my-client-id", |
| 49 | + subject_token_provider=fetch_id_jag, |
| 50 | + ) |
| 51 | + ``` |
| 52 | + """ |
| 53 | + |
| 54 | + def __init__( |
| 55 | + self, |
| 56 | + server_url: str, |
| 57 | + storage: TokenStorage, |
| 58 | + client_id: str, |
| 59 | + subject_token_provider: Callable[[str], Awaitable[str]], |
| 60 | + subject_token_type: str = JWT_TOKEN_TYPE, |
| 61 | + requested_token_type: str | None = ACCESS_TOKEN_TYPE, |
| 62 | + scopes: str | None = None, |
| 63 | + client_secret: str | None = None, |
| 64 | + token_endpoint_auth_method: Literal["client_secret_basic", "client_secret_post"] = "client_secret_post", |
| 65 | + ) -> None: |
| 66 | + """Initialize the token-exchange OAuth provider. |
| 67 | +
|
| 68 | + Args: |
| 69 | + server_url: The MCP server URL. |
| 70 | + storage: Token storage implementation. |
| 71 | + client_id: The OAuth client ID registered with the MCP authorization server. |
| 72 | + subject_token_provider: Async callback that takes the authorization server's |
| 73 | + issuer identifier (the audience) and returns the subject token to exchange |
| 74 | + (the ID-JAG for SEP-990). |
| 75 | + subject_token_type: RFC 8693 type identifier of the subject token. Defaults to |
| 76 | + `urn:ietf:params:oauth:token-type:jwt`, the type of an ID-JAG. |
| 77 | + requested_token_type: RFC 8693 desired type of the issued token. Defaults to |
| 78 | + `urn:ietf:params:oauth:token-type:access_token`, since SEP-990 yields an MCP |
| 79 | + access token; pass `None` to omit the parameter. |
| 80 | + scopes: Optional space-separated list of scopes to request. |
| 81 | + client_secret: Optional client secret. When set, the request authenticates as a |
| 82 | + confidential client using `token_endpoint_auth_method`; otherwise the public |
| 83 | + client form is used and the method is `none`. |
| 84 | + token_endpoint_auth_method: Authentication method when `client_secret` is set. |
| 85 | + Either `client_secret_post` (default) or `client_secret_basic`. |
| 86 | + """ |
| 87 | + auth_method = token_endpoint_auth_method if client_secret is not None else "none" |
| 88 | + client_metadata = OAuthClientMetadata( |
| 89 | + redirect_uris=None, |
| 90 | + grant_types=[TOKEN_EXCHANGE_GRANT_TYPE], |
| 91 | + token_endpoint_auth_method=auth_method, |
| 92 | + scope=scopes, |
| 93 | + ) |
| 94 | + super().__init__(server_url, client_metadata, storage, None, None, 300.0) |
| 95 | + self._subject_token_provider = subject_token_provider |
| 96 | + self._subject_token_type = subject_token_type |
| 97 | + self._requested_token_type = requested_token_type |
| 98 | + self._fixed_client_info = OAuthClientInformationFull( |
| 99 | + redirect_uris=None, |
| 100 | + client_id=client_id, |
| 101 | + client_secret=client_secret, |
| 102 | + grant_types=[TOKEN_EXCHANGE_GRANT_TYPE], |
| 103 | + token_endpoint_auth_method=auth_method, |
| 104 | + scope=scopes, |
| 105 | + ) |
| 106 | + |
| 107 | + async def _initialize(self) -> None: |
| 108 | + """Load stored tokens and set pre-configured client_info.""" |
| 109 | + self.context.current_tokens = await self.context.storage.get_tokens() |
| 110 | + self.context.client_info = self._fixed_client_info |
| 111 | + self._initialized = True |
| 112 | + |
| 113 | + async def _perform_authorization(self) -> httpx.Request: |
| 114 | + """Perform the token-exchange grant.""" |
| 115 | + return await self._exchange_token() |
| 116 | + |
| 117 | + async def _exchange_token(self) -> httpx.Request: |
| 118 | + """Build the RFC 8693 token-exchange request.""" |
| 119 | + if not self.context.oauth_metadata: |
| 120 | + raise OAuthFlowError("Missing OAuth metadata for token exchange") # pragma: no cover |
| 121 | + if not self.context.client_info: |
| 122 | + raise OAuthFlowError("Missing client info for token exchange") # pragma: no cover |
| 123 | + |
| 124 | + audience = str(self.context.oauth_metadata.issuer) |
| 125 | + subject_token = await self._subject_token_provider(audience) |
| 126 | + |
| 127 | + token_data: dict[str, Any] = { |
| 128 | + "grant_type": TOKEN_EXCHANGE_GRANT_TYPE, |
| 129 | + "subject_token": subject_token, |
| 130 | + "subject_token_type": self._subject_token_type, |
| 131 | + "client_id": self.context.client_info.client_id, |
| 132 | + } |
| 133 | + if self._requested_token_type is not None: |
| 134 | + token_data["requested_token_type"] = self._requested_token_type |
| 135 | + |
| 136 | + headers: dict[str, str] = {"Content-Type": "application/x-www-form-urlencoded"} |
| 137 | + token_data, headers = self.context.prepare_token_auth(token_data, headers) |
| 138 | + |
| 139 | + if self.context.should_include_resource_param(self.context.protocol_version): |
| 140 | + token_data["resource"] = self.context.get_resource_url() |
| 141 | + |
| 142 | + if self.context.client_metadata.scope: |
| 143 | + token_data["scope"] = self.context.client_metadata.scope |
| 144 | + |
| 145 | + token_url = self._get_token_endpoint() |
| 146 | + return httpx.Request("POST", token_url, data=token_data, headers=headers) |
0 commit comments