π The fast, Pythonic way to build MCP servers and clients.
Fix OAuth proxy client storage and add retry logic (#1732)
Jeremiah Lowind11e98fe4ad0
diff --git a/src/fastmcp/client/auth/oauth.py b/src/fastmcp/client/auth/oauth.pyindex b589c2873..c703950d4 100644--- a/src/fastmcp/client/auth/oauth.py+++ b/src/fastmcp/client/auth/oauth.py@@ -4,6 +4,7 @@ import asyncioimport jsonimport webbrowserfrom asyncio import Future+from collections.abc import AsyncGeneratorfrom datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Any, Literal@@ -34,6 +35,12 @@ __all__ = ["OAuth"]logger = get_logger(__name__)+class ClientNotFoundError(Exception):+ """Raised when OAuth client credentials are not found on the server."""++ pass++class StoredToken(BaseModel):"""Token storage format with absolute expiry time."""@@ -173,7 +180,7 @@ class FileTokenStorage(TokenStorage):for file_type in file_types:path = self._get_file_path(file_type)path.unlink(missing_ok=True)- logger.info(f"Cleared OAuth cache for {self.get_base_url(self.server_url)}")+ logger.debug(f"Cleared OAuth cache for {self.get_base_url(self.server_url)}")@classmethoddef clear_all(cls, cache_dir: Path | None = None) -> None:@@ -300,7 +307,23 @@ class OAuth(OAuthClientProvider):self.context.update_token_expiry(self.context.current_tokens)async def redirect_handler(self, authorization_url: str) -> None:- """Open browser for authorization."""+ """Open browser for authorization, with pre-flight check for invalid client."""+ # Pre-flight check to detect invalid client_id before opening browser+ async with httpx.AsyncClient() as client:+ response = await client.get(authorization_url, follow_redirects=False)++ # Check for client not found error (400 typically means bad client_id)+ if response.status_code == 400:+ raise ClientNotFoundError(+ "OAuth client not found - cached credentials may be stale"+ )++ # For any non-redirect response, something is wrong+ if response.status_code not in (302, 303, 307, 308):+ raise RuntimeError(+ f"Unexpected authorization response: {response.status_code}"+ )+logger.info(f"OAuth authorization URL: {authorization_url}")webbrowser.open(authorization_url)@@ -336,3 +359,56 @@ class OAuth(OAuthClientProvider):tg.cancel_scope.cancel()raise RuntimeError("OAuth callback handler could not be started")++ async def async_auth_flow(+ self, request: httpx.Request+ ) -> AsyncGenerator[httpx.Request, httpx.Response]:+ """HTTPX auth flow with automatic retry on stale cached credentials.++ If the OAuth flow fails due to invalid/stale client credentials,+ clears the cache and retries once with fresh registration.+ """+ try:+ # First attempt with potentially cached credentials+ gen = super().async_auth_flow(request)+ response = None+ while True:+ try:+ yielded_request = await gen.asend(response)+ response = yield yielded_request+ except StopAsyncIteration:+ break++ except ClientNotFoundError:+ logger.debug(+ "OAuth client not found on server, clearing cache and retrying..."+ )++ # Clear cached state and retry once+ self._initialized = False++ # Try to clear storage if it supports it+ if hasattr(self.context.storage, "clear"):+ try:+ self.context.storage.clear()+ except Exception as e:+ logger.warning(f"Failed to clear OAuth storage cache: {e}")+ # Can't retry without clearing cache, re-raise original error+ raise ClientNotFoundError(+ "OAuth client not found and cache could not be cleared"+ ) from e+ else:+ logger.warning(+ "Storage does not support clear() - cannot retry with fresh credentials"+ )+ # Can't retry without clearing cache, re-raise original error+ raise++ gen = super().async_auth_flow(request)+ response = None+ while True:+ try:+ yielded_request = await gen.asend(response)+ response = yield yielded_request+ except StopAsyncIteration:+ breakdiff --git a/src/fastmcp/server/auth/oauth_proxy.py b/src/fastmcp/server/auth/oauth_proxy.pyindex f78f7389e..a75f8b690 100644--- a/src/fastmcp/server/auth/oauth_proxy.py+++ b/src/fastmcp/server/auth/oauth_proxy.py@@ -172,7 +172,6 @@ class OAuthProxy(OAuthProvider):1. Client Registration (DCR):- Accept any client registration request- Store ProxyDCRClient that accepts dynamic redirect URIs- - Return shared upstream credentials to all clients2. Authorization:- Store transaction mapping client details to proxy flow@@ -323,67 +322,28 @@ class OAuthProxy(OAuthProvider):# -------------------------------------------------------------------------async def get_client(self, client_id: str) -> OAuthClientInformationFull | None:- """Get client information by ID.+ """Get client information by ID. This is generally the random ID+ provided to the DCR client during registration, not the upstream client ID.- For unregistered clients, returns a ProxyDCRClient that accepts- any localhost redirect URI for DCR clients.-- Even registered clients use ProxyDCRClient to ensure they can- authenticate with different dynamic ports on reconnection. This- handles the case where a client with cached tokens reconnects- on a different port.+ For unregistered clients, returns None (which will raise an error in the SDK)."""client = self._clients.get(client_id)- if client is None:- # For unregistered DCR clients, create a permissive client- # that will accept any localhost redirect URI- # We need at least one URI for Pydantic validation, but our custom- # validate_redirect_uri will accept any localhost URI- client = ProxyDCRClient(- client_id=client_id,- client_secret=None,- redirect_uris=[- AnyUrl("http://localhost")- ], # Placeholder, validation uses allowed_patterns- grant_types=["authorization_code", "refresh_token"],- scope=self._default_scope_str,- token_endpoint_auth_method="none",- allowed_redirect_uri_patterns=self._allowed_client_redirect_uris,- )- logger.debug("Created ProxyDCRClient for unregistered client %s", client_id)-return clientasync def register_client(self, client_info: OAuthClientInformationFull) -> None:- """Register a client locally using fixed upstream credentials.-- This implementation always uses the upstream client_id and client_secret- regardless of what the client requests. It modifies the client_info object- in place since the MCP framework ignores return values.-- This ensures all clients use the same credentials that are registered- with the upstream server.-- Implementation Detail:- We store a ProxyDCRClient (not the original client_info) to ensure- the client can reconnect with different dynamic redirect URIs. This is- essential for cached token scenarios where the client port changes.+ """Register a client locally- The flow:- 1. Client provides its desired redirect URIs (dynamic localhost ports)- 2. We create a ProxyDCRClient that will accept ANY localhost URI- 3. We store this flexible client for future authentications- 4. When client reconnects with a different port, ProxyDCRClient accepts it+ When a client registers, we create a ProxyDCRClient that is more+ forgiving about validating redirect URIs, since the DCR client's+ redirect URI will likely be localhost or unknown to the proxied IDP. The+ proxied IDP only knows about this server's fixed redirect URI."""- # Always use the upstream credentials- upstream_id = self._upstream_client_id- upstream_secret = self._upstream_client_secret.get_secret_value()# Create a ProxyDCRClient with configured redirect URI validationproxy_client = ProxyDCRClient(- client_id=upstream_id,- client_secret=upstream_secret,+ client_id=client_info.client_id,+ client_secret=client_info.client_secret,redirect_uris=client_info.redirect_uris or [AnyUrl("http://localhost")],grant_types=client_info.grant_typesor ["authorization_code", "refresh_token"],@@ -392,8 +352,8 @@ class OAuthProxy(OAuthProvider):allowed_redirect_uri_patterns=self._allowed_client_redirect_uris,)- # Store the ProxyDCRClient using the upstream ID- self._clients[upstream_id] = proxy_client+ # Store the ProxyDCRClient+ self._clients[client_info.client_id] = proxy_client# Log redirect URIs to help users discover what patterns they might needif client_info.redirect_uris:@@ -406,7 +366,7 @@ class OAuthProxy(OAuthProvider):logger.debug("Registered client %s with %d redirect URIs",- upstream_id,+ client_info.client_id,len(proxy_client.redirect_uris),)diff --git a/tests/server/auth/test_oauth_proxy.py b/tests/server/auth/test_oauth_proxy.pyindex c56164440..6892ef8c2 100644--- a/tests/server/auth/test_oauth_proxy.py+++ b/tests/server/auth/test_oauth_proxy.py@@ -211,11 +211,11 @@ class TestOAuthProxyComprehensive:assert client_info.token_endpoint_auth_method == "client_secret_post"assert client_info.grant_types == ["authorization_code"]- # Verify ProxyDCRClient was stored with upstream credentials- stored_client = oauth_proxy._clients.get("test-client-id")+ # Verify ProxyDCRClient was stored with original client credentials+ stored_client = oauth_proxy._clients.get("original-client-id")assert stored_client is not None- assert stored_client.client_id == "test-client-id"- assert stored_client.client_secret == "test-client-secret"+ assert stored_client.client_id == "original-client-id"+ assert stored_client.client_secret == "original-secret"assert stored_client.scope == "read write"async def test_register_client_empty_grant_types(self, oauth_proxy):@@ -232,7 +232,7 @@ class TestOAuthProxyComprehensive:assert client_info.grant_types == []# Verify stored ProxyDCRClient has proper grant types- stored_client = oauth_proxy._clients.get("test-client-id")+ stored_client = oauth_proxy._clients.get("original-client-id")assert stored_client is not Noneassert stored_client.grant_types == ["authorization_code", "refresh_token"]@@ -247,31 +247,15 @@ class TestOAuthProxyComprehensive:await oauth_proxy.register_client(client_info)# Get the client- retrieved = await oauth_proxy.get_client("test-client-id")+ retrieved = await oauth_proxy.get_client("test-id")assert retrieved is not None- assert retrieved.client_id == "test-client-id"+ assert retrieved.client_id == "test-id"- async def test_get_client_temporary(self, oauth_proxy):- """Test getting a temporary client for unregistered client ID."""+ async def test_get_client_unregistered_returns_none(self, oauth_proxy):+ """Test that unregistered clients return None."""# Get a client that hasn't been registered- temp_client = await oauth_proxy.get_client("unknown-client-id")-- assert temp_client is not None- assert temp_client.client_id == "unknown-client-id"- assert temp_client.client_secret is None- assert temp_client.token_endpoint_auth_method == "none"- assert len(temp_client.redirect_uris) >= 1- # ProxyDCRClient uses a placeholder URL but accepts any localhost URI- assert str(temp_client.redirect_uris[0]) == "http://localhost/"- assert temp_client.scope == "read write"-- # Test that it accepts any localhost redirect URI- from pydantic import AnyUrl-- test_uri = temp_client.validate_redirect_uri(- AnyUrl("http://localhost:55454/callback")- )- assert str(test_uri) == "http://localhost:55454/callback"+ client = await oauth_proxy.get_client("unknown-client-id")+ assert client is Noneasync def test_authorize_creates_transaction(self, oauth_proxy):"""Test that authorize creates a transaction and returns upstream URL."""@@ -378,7 +362,10 @@ class TestOAuthProxyComprehensive:assert "scope" not in query_paramsasync def test_client_scope_empty_when_no_required_scopes(self):- """When required_scopes is None/empty, client scope should be empty string."""+ """When required_scopes is None/empty, registered client scope should be empty string."""+ from mcp.shared.auth import OAuthClientInformationFull+ from pydantic import AnyUrl+proxy = OAuthProxy(upstream_authorization_endpoint="https://auth.example.com/authorize",upstream_token_endpoint="https://auth.example.com/token",@@ -388,8 +375,18 @@ class TestOAuthProxyComprehensive:base_url="https://api.example.com",)- temp_client = await proxy.get_client("any-client")- assert temp_client.scope == ""+ # Register a client first+ client_info = OAuthClientInformationFull(+ client_id="test-client",+ client_secret="test-secret",+ redirect_uris=[AnyUrl("http://localhost:12345/callback")],+ )+ await proxy.register_client(client_info)++ # Get the registered client+ registered_client = await proxy.get_client("test-client")+ assert registered_client is not None+ assert registered_client.scope == ""async def test_load_authorization_code_valid(self, oauth_proxy):"""Test loading a valid authorization code."""diff --git a/tests/server/auth/test_oauth_proxy_redirect_validation.py b/tests/server/auth/test_oauth_proxy_redirect_validation.pyindex 10b44218e..8a2ab8564 100644--- a/tests/server/auth/test_oauth_proxy_redirect_validation.py+++ b/tests/server/auth/test_oauth_proxy_redirect_validation.py@@ -172,13 +172,15 @@ class TestOAuthProxyRedirectValidation:await proxy.register_client(client_info)# Get the registered client- registered = await proxy.get_client("test-client") # Uses upstream ID+ registered = await proxy.get_client(+ "new-client"+ ) # Use the client ID we registeredassert isinstance(registered, ProxyDCRClient)assert registered._allowed_redirect_uri_patterns == custom_patterns@pytest.mark.asyncio- async def test_proxy_unregistered_client_uses_patterns(self):- """Test that unregistered clients also use configured patterns."""+ async def test_proxy_unregistered_client_returns_none(self):+ """Test that unregistered clients return None."""custom_patterns = ["http://localhost:*", "http://127.0.0.1:*"]proxy = OAuthProxy(@@ -193,5 +195,4 @@ class TestOAuthProxyRedirectValidation:# Get an unregistered clientclient = await proxy.get_client("unknown-client")- assert isinstance(client, ProxyDCRClient)- assert client._allowed_redirect_uri_patterns == custom_patterns+ assert client is None