Repository navigation
Support RFC 8693 token exchange for enterprise IdP flows (SEP-990) #2988
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
e8df714
Support RFC 8693 token exchange for enterprise IdP flows (SEP-990)
Kludex 92fae82
Preserve empty issuer/resource paths on AuthSettings
Kludex 2c7cb17
Merge branch 'auth-settings-preserve-empty-path' into worktree-synthe…
Kludex c7cacf0
Merge remote-tracking branch 'origin/main' into worktree-synthetic-st…
Kludex 55c2413
Add end-to-end interaction tests for token exchange (SEP-990)
Kludex b94851b
Strengthen token-exchange interaction tests per review
Kludex 7783020
Use the RFC 7523 jwt-bearer grant for the SEP-990 ID-JAG leg
Kludex 0f4052c
Harden the identity-assertion grant per review
Kludex 05f60ce
Pin identity-assertion discovery to the expected authorization server
Kludex 6689e0a
Don't broaden initial identity-assertion scope; normalize origin ports
Kludex 4393b4b
Always send the configured scope on identity-assertion exchanges
Kludex d011d3a
Merge remote-tracking branch 'origin/main' into worktree-synthetic-st…
Kludex 095f189
Make IdentityAssertionOAuthProvider a standalone httpx.Auth
maxisbey dfd458a
Merge remote-tracking branch 'origin/worktree-synthetic-stirring-tree…
maxisbey File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| """Client side of SEP-990 (enterprise IdP policy controls). | ||
|
|
||
| `TokenExchangeOAuthProvider` exchanges a subject token issued by the enterprise IdP - the | ||
| Identity Assertion Authorization Grant (ID-JAG) - for an MCP access token, using the RFC 8693 | ||
| token-exchange grant at the MCP authorization server's token endpoint. No browser redirect or | ||
| dynamic client registration is involved. | ||
|
|
||
| Obtaining the ID-JAG (logging into the IdP and performing the first exchange against it) is | ||
| deployment-specific and out of scope for the SDK; supply it through the `subject_token_provider` | ||
| callback. The callback receives the authorization server's issuer identifier as its audience. | ||
| """ | ||
|
|
||
| import asyncio | ||
|
|
||
| import httpx | ||
|
|
||
| from mcp import ClientSession | ||
| from mcp.client.auth.extensions.token_exchange import TokenExchangeOAuthProvider | ||
| from mcp.client.streamable_http import streamable_http_client | ||
| from mcp.shared.auth import OAuthClientInformationFull, OAuthToken | ||
|
|
||
|
|
||
| class InMemoryTokenStorage: | ||
| """Demo in-memory token storage.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self.tokens: OAuthToken | None = None | ||
| self.client_info: OAuthClientInformationFull | None = None | ||
|
|
||
| async def get_tokens(self) -> OAuthToken | None: | ||
| return self.tokens | ||
|
|
||
| async def set_tokens(self, tokens: OAuthToken) -> None: | ||
| self.tokens = tokens | ||
|
|
||
| async def get_client_info(self) -> OAuthClientInformationFull | None: | ||
| return self.client_info | ||
|
|
||
| async def set_client_info(self, client_info: OAuthClientInformationFull) -> None: | ||
| self.client_info = client_info | ||
|
|
||
|
|
||
| async def fetch_id_jag(audience: str) -> str: | ||
| """Return the ID-JAG to exchange. | ||
|
|
||
| `audience` is the MCP authorization server's issuer identifier; the returned ID-JAG must | ||
| carry it as the `aud` claim. In production this exchanges the user's IdP ID token for an | ||
| ID-JAG against the enterprise identity provider. | ||
| """ | ||
| raise NotImplementedError("Obtain the ID-JAG from your enterprise identity provider") | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| oauth_auth = TokenExchangeOAuthProvider( | ||
| server_url="http://localhost:8001/mcp", | ||
| storage=InMemoryTokenStorage(), | ||
| client_id="enterprise-mcp-client", | ||
| subject_token_provider=fetch_id_jag, | ||
| scopes="user", | ||
| ) | ||
|
|
||
| async with httpx.AsyncClient(auth=oauth_auth, follow_redirects=True) as http_client: | ||
| async with streamable_http_client("http://localhost:8001/mcp", http_client=http_client) as (read, write): | ||
| async with ClientSession(read, write) as session: | ||
| await session.initialize() | ||
| tools = await session.list_tools() | ||
| print(f"Available tools: {[tool.name for tool in tools.tools]}") | ||
|
|
||
|
|
||
| def run() -> None: | ||
| asyncio.run(main()) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| run() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """Authorization-server side of SEP-990 (enterprise IdP policy controls). | ||
|
|
||
| An authorization server enables the RFC 8693 token-exchange grant by setting | ||
| `token_exchange_enabled=True` and implementing `exchange_token` on its provider. The | ||
| provider validates the subject token (the ID-JAG issued by the enterprise IdP), decides which | ||
| scopes the exchange may grant, and mints an MCP access token. | ||
|
|
||
| Two responsibilities are the provider's and must not be skipped (both are stubbed here): | ||
| - Validate the ID-JAG: signature against the IdP's keys, issuer/audience/expiry, and the | ||
| organization's policy. Returning a subject for any non-empty token, as `_validate_id_jag` | ||
| does below, is NOT safe for production. | ||
| - Narrow the granted scopes. The scopes a client requests must never be granted verbatim; the | ||
| ID-JAG and policy determine what is permitted. `_grant_scopes` intersects the request with | ||
| what the subject is allowed. | ||
|
|
||
| Wire the returned routes into a Starlette app with `create_auth_routes(..., | ||
| token_exchange_enabled=True)`, or set `AuthSettings(token_exchange_enabled=True)` when using | ||
| `MCPServer`/`Server` with an `auth_server_provider`. | ||
| """ | ||
|
|
||
| import secrets | ||
| import time | ||
|
|
||
| from mcp.server.auth.provider import ( | ||
| AccessToken, | ||
| AuthorizationCode, | ||
| OAuthAuthorizationServerProvider, | ||
| RefreshToken, | ||
| TokenError, | ||
| TokenExchangeParams, | ||
| ) | ||
| from mcp.shared.auth import OAuthClientInformationFull, OAuthToken, TokenExchangeToken | ||
|
|
||
| # The scopes this server is willing to grant via token exchange. A real implementation derives | ||
| # the permitted set from the validated ID-JAG and the organization's policy, not from a constant. | ||
| ALLOWED_SCOPES = ("mcp",) | ||
|
|
||
|
|
||
| class TokenExchangeProvider(OAuthAuthorizationServerProvider[AuthorizationCode, RefreshToken, AccessToken]): | ||
| """Authorization-server provider that accepts an ID-JAG via RFC 8693 token exchange.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self.access_tokens: dict[str, AccessToken] = {} | ||
|
|
||
| async def exchange_token(self, client: OAuthClientInformationFull, params: TokenExchangeParams) -> OAuthToken: | ||
| subject = self._validate_id_jag(params.subject_token) | ||
| if subject is None: | ||
| raise TokenError(error="invalid_grant", error_description="Invalid or rejected subject token") | ||
|
|
||
| scopes = self._grant_scopes(params.scopes) | ||
|
|
||
| assert client.client_id is not None | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| access_token = f"access_{secrets.token_hex(16)}" | ||
| self.access_tokens[access_token] = AccessToken( | ||
| token=access_token, | ||
| client_id=client.client_id, | ||
| scopes=scopes, | ||
| expires_at=int(time.time()) + 3600, | ||
| resource=params.resource, | ||
| subject=subject, | ||
| ) | ||
| # TokenExchangeToken sets RFC 8693's issued_token_type; it defaults to the access-token type. | ||
| return TokenExchangeToken( | ||
| access_token=access_token, | ||
| token_type="Bearer", | ||
| expires_in=3600, | ||
| scope=" ".join(scopes), | ||
| ) | ||
|
|
||
| def _validate_id_jag(self, subject_token: str) -> str | None: | ||
| """Validate the ID-JAG and return the subject, or None to reject. | ||
|
|
||
| A real implementation verifies the JWT signature against the IdP's keys, checks the | ||
| issuer/audience/expiry, and applies the organization's policy. This stub accepts any | ||
| non-empty token and uses it as the subject identifier - replace it before production. | ||
| """ | ||
| return subject_token or None | ||
|
|
||
| def _grant_scopes(self, requested: list[str] | None) -> list[str]: | ||
| """Return the scopes to grant, never exceeding what this server permits. | ||
|
|
||
| Requested scopes are intersected with the allowed set so a valid ID-JAG can never be | ||
| exchanged for broader access than policy allows; when none are requested, the full | ||
| allowed set is granted. | ||
| """ | ||
| if requested is None: | ||
| return list(ALLOWED_SCOPES) | ||
| granted = [scope for scope in requested if scope in ALLOWED_SCOPES] | ||
| if not granted: | ||
| raise TokenError(error="invalid_scope", error_description="No requested scope is permitted") | ||
| return granted | ||
|
|
||
| async def load_access_token(self, token: str) -> AccessToken | None: | ||
| return self.access_tokens.get(token) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| """OAuth 2.0 Token Exchange (RFC 8693) client provider for MCP. | ||
|
|
||
| Provides `TokenExchangeOAuthProvider`, which exchanges a security token issued by an | ||
| enterprise identity provider for an MCP access token at the MCP authorization server's | ||
| token endpoint. This is the client side of SEP-990 (enterprise IdP policy controls): the | ||
| client first obtains an Identity Assertion Authorization Grant (ID-JAG) from the IdP, then | ||
| exchanges it here for a token usable against the MCP server. | ||
|
|
||
| Obtaining the ID-JAG (logging into the IdP and performing the first token exchange against | ||
| it) is deployment-specific and out of scope for the SDK. The caller supplies it through the | ||
| `subject_token_provider` callback, which receives the MCP authorization server's issuer | ||
| identifier as its audience and returns the security token to exchange. | ||
| """ | ||
|
|
||
| from collections.abc import Awaitable, Callable | ||
| from typing import Any, Literal | ||
|
|
||
| import httpx | ||
|
|
||
| from mcp.client.auth import OAuthClientProvider, OAuthFlowError, TokenStorage | ||
| from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata | ||
|
|
||
| TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" | ||
| JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt" | ||
| ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" | ||
|
|
||
|
|
||
| class TokenExchangeOAuthProvider(OAuthClientProvider): | ||
| """OAuth provider for the RFC 8693 token-exchange grant. | ||
|
|
||
| Exchanges a subject token (for SEP-990, the IdP-issued ID-JAG) for an MCP access token, | ||
| bypassing the interactive authorization-code flow and dynamic client registration. The | ||
| subject token is fetched lazily from `subject_token_provider` so a fresh token is used on | ||
| each exchange. | ||
|
|
||
| Example: | ||
| ```python | ||
| async def fetch_id_jag(audience: str) -> str: | ||
| # `audience` is the MCP authorization server's issuer identifier; the returned | ||
| # ID-JAG must carry that as its `aud` claim. How the ID-JAG is obtained from the | ||
| # enterprise IdP is deployment-specific and not handled by the SDK. | ||
| return await my_idp.exchange_id_token_for_id_jag(audience=audience) | ||
|
|
||
|
|
||
| provider = TokenExchangeOAuthProvider( | ||
| server_url="https://mcp.example.com/mcp", | ||
| storage=my_token_storage, | ||
| client_id="my-client-id", | ||
| subject_token_provider=fetch_id_jag, | ||
| ) | ||
| ``` | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| server_url: str, | ||
| storage: TokenStorage, | ||
| client_id: str, | ||
| subject_token_provider: Callable[[str], Awaitable[str]], | ||
| subject_token_type: str = JWT_TOKEN_TYPE, | ||
| requested_token_type: str | None = ACCESS_TOKEN_TYPE, | ||
| scopes: str | None = None, | ||
| client_secret: str | None = None, | ||
| token_endpoint_auth_method: Literal["client_secret_basic", "client_secret_post"] = "client_secret_post", | ||
| ) -> None: | ||
| """Initialize the token-exchange OAuth provider. | ||
|
|
||
| Args: | ||
| server_url: The MCP server URL. | ||
| storage: Token storage implementation. | ||
| client_id: The OAuth client ID registered with the MCP authorization server. | ||
| subject_token_provider: Async callback that takes the authorization server's | ||
| issuer identifier (the audience) and returns the subject token to exchange | ||
| (the ID-JAG for SEP-990). | ||
| subject_token_type: RFC 8693 type identifier of the subject token. Defaults to | ||
| `urn:ietf:params:oauth:token-type:jwt`, the type of an ID-JAG. | ||
| requested_token_type: RFC 8693 desired type of the issued token. Defaults to | ||
| `urn:ietf:params:oauth:token-type:access_token`, since SEP-990 yields an MCP | ||
| access token; pass `None` to omit the parameter. | ||
| scopes: Optional space-separated list of scopes to request. | ||
| client_secret: Optional client secret. When set, the request authenticates as a | ||
| confidential client using `token_endpoint_auth_method`; otherwise the public | ||
| client form is used and the method is `none`. | ||
| token_endpoint_auth_method: Authentication method when `client_secret` is set. | ||
| Either `client_secret_post` (default) or `client_secret_basic`. | ||
| """ | ||
| auth_method = token_endpoint_auth_method if client_secret is not None else "none" | ||
| client_metadata = OAuthClientMetadata( | ||
| redirect_uris=None, | ||
| grant_types=[TOKEN_EXCHANGE_GRANT_TYPE], | ||
| token_endpoint_auth_method=auth_method, | ||
| scope=scopes, | ||
| ) | ||
| super().__init__(server_url, client_metadata, storage, None, None, 300.0) | ||
| self._subject_token_provider = subject_token_provider | ||
| self._subject_token_type = subject_token_type | ||
| self._requested_token_type = requested_token_type | ||
| self._fixed_client_info = OAuthClientInformationFull( | ||
| redirect_uris=None, | ||
| client_id=client_id, | ||
| client_secret=client_secret, | ||
| grant_types=[TOKEN_EXCHANGE_GRANT_TYPE], | ||
| token_endpoint_auth_method=auth_method, | ||
| scope=scopes, | ||
| ) | ||
|
|
||
| async def _initialize(self) -> None: | ||
| """Load stored tokens and set pre-configured client_info.""" | ||
| self.context.current_tokens = await self.context.storage.get_tokens() | ||
| self.context.client_info = self._fixed_client_info | ||
| self._initialized = True | ||
|
|
||
| async def _perform_authorization(self) -> httpx.Request: | ||
| """Perform the token-exchange grant.""" | ||
| return await self._exchange_token() | ||
|
|
||
| async def _exchange_token(self) -> httpx.Request: | ||
| """Build the RFC 8693 token-exchange request.""" | ||
| if not self.context.oauth_metadata: | ||
| raise OAuthFlowError("Missing OAuth metadata for token exchange") # pragma: no cover | ||
| if not self.context.client_info: | ||
| raise OAuthFlowError("Missing client info for token exchange") # pragma: no cover | ||
|
|
||
| audience = str(self.context.oauth_metadata.issuer) | ||
| subject_token = await self._subject_token_provider(audience) | ||
|
|
||
| token_data: dict[str, Any] = { | ||
| "grant_type": TOKEN_EXCHANGE_GRANT_TYPE, | ||
| "subject_token": subject_token, | ||
| "subject_token_type": self._subject_token_type, | ||
| "client_id": self.context.client_info.client_id, | ||
| } | ||
| if self._requested_token_type is not None: | ||
| token_data["requested_token_type"] = self._requested_token_type | ||
|
|
||
| headers: dict[str, str] = {"Content-Type": "application/x-www-form-urlencoded"} | ||
| token_data, headers = self.context.prepare_token_auth(token_data, headers) | ||
|
|
||
| if self.context.should_include_resource_param(self.context.protocol_version): | ||
| token_data["resource"] = self.context.get_resource_url() | ||
|
|
||
| if self.context.client_metadata.scope: | ||
| token_data["scope"] = self.context.client_metadata.scope | ||
|
|
||
| token_url = self._get_token_endpoint() | ||
| return httpx.Request("POST", token_url, data=token_data, headers=headers) | ||
|
claude[bot] marked this conversation as resolved.
Resolved
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.