π The fast, Pythonic way to build MCP servers and clients.
enh: Add public API for updating OAuthProxy scopes after initialization (#4091)
Taylor Wilsdon61e56c683ec9
diff --git a/src/fastmcp/server/auth/oauth_proxy/proxy.py b/src/fastmcp/server/auth/oauth_proxy/proxy.pyindex 98c2ffc16..c94d43b21 100644--- a/src/fastmcp/server/auth/oauth_proxy/proxy.py+++ b/src/fastmcp/server/auth/oauth_proxy/proxy.py@@ -351,10 +351,13 @@ class OAuthProxy(OAuthProvider, ConsentMixin):IDs, with metadata fetched from the URL. Supports private_key_jwt auth."""+ default_scopes = valid_scopes or token_verifier.required_scopes+# Always enable DCR since we implement it locally for MCP clientsclient_registration_options = ClientRegistrationOptions(enabled=True,- valid_scopes=valid_scopes or token_verifier.required_scopes,+ valid_scopes=list(default_scopes) if default_scopes is not None else None,+ default_scopes=list(default_scopes) if default_scopes is not None else None,)# Enable revocation only if upstream endpoint provided@@ -382,9 +385,7 @@ class OAuthProxy(OAuthProvider, ConsentMixin):else None)self._upstream_revocation_endpoint: str | None = upstream_revocation_endpoint- self._default_scope_str: str = " ".join(- valid_scopes or self.required_scopes or []- )+ self._default_scope_str: str = " ".join(default_scopes or [])# Store redirect configurationif not redirect_path:@@ -599,6 +600,32 @@ class OAuthProxy(OAuthProvider, ConsentMixin):self._upstream_authorization_endpoint,)+ # -------------------------------------------------------------------------+ # Scope Management+ # -------------------------------------------------------------------------++ def update_default_scopes(self, scopes: list[str]) -> None:+ """Update the default scopes advertised to clients and used for DCR/CIMD fallback.++ Use this method when the available scope set is determined after provider+ initialization (e.g., after tool registration widens the required scopes).++ This updates all internal state derived from scopes:+ - The default scope string used for DCR client registration fallback+ - The CIMD manager's default scope (if CIMD is enabled)+ - The client registration options default_scopes and valid_scopes (if registration options exist)++ Args:+ scopes: The new list of valid scopes to advertise and use as defaults.+ """+ scopes = list(scopes)+ self._default_scope_str = " ".join(scopes)+ if self._cimd_manager is not None:+ self._cimd_manager.default_scope = self._default_scope_str+ if self.client_registration_options is not None:+ self.client_registration_options.default_scopes = list(scopes)+ self.client_registration_options.valid_scopes = list(scopes)+# -------------------------------------------------------------------------# MCP Path Configuration# -------------------------------------------------------------------------diff --git a/src/fastmcp/server/auth/oidc_proxy.py b/src/fastmcp/server/auth/oidc_proxy.pyindex a84e12db8..a20282701 100644--- a/src/fastmcp/server/auth/oidc_proxy.py+++ b/src/fastmcp/server/auth/oidc_proxy.py@@ -427,11 +427,7 @@ class OIDCProxy(OAuthProxy):# from the (empty) verifier scopes.if verify_id_token and required_scopes:self.required_scopes = required_scopes- self._default_scope_str = " ".join(required_scopes)- if self.client_registration_options:- self.client_registration_options.valid_scopes = required_scopes- if self._cimd_manager is not None:- self._cimd_manager.default_scope = self._default_scope_str+ self.update_default_scopes(required_scopes)def _get_verification_token(self, upstream_token_set: UpstreamTokenSetdiff --git a/tests/server/auth/oauth_proxy/test_client_registration.py b/tests/server/auth/oauth_proxy/test_client_registration.pyindex eaa96aba2..946690b26 100644--- a/tests/server/auth/oauth_proxy/test_client_registration.py+++ b/tests/server/auth/oauth_proxy/test_client_registration.py@@ -1,8 +1,10 @@"""Tests for OAuth proxy client registration (DCR)."""+import httpximport pytestfrom mcp.shared.auth import OAuthClientInformationFullfrom pydantic import AnyUrl+from starlette.applications import Starlettefrom fastmcp.server.auth.oauth_proxy.models import InvalidRedirectUriError@@ -71,6 +73,33 @@ class TestOAuthProxyClientRegistration:"http://localhost:12345/updated_callback"]+ async def test_update_default_scopes_applies_to_dcr_registration(self, oauth_proxy):+ """DCR clients without scope should receive the updated default scopes."""+ oauth_proxy.update_default_scopes(["read", "write", "calendar"])++ app = Starlette(routes=oauth_proxy.get_routes())+ transport = httpx.ASGITransport(app=app)++ async with httpx.AsyncClient(+ transport=transport,+ base_url="https://myserver.com",+ ) as client:+ response = await client.post(+ "/register",+ json={+ "redirect_uris": ["https://client.example.com/callback"],+ "client_name": "Test Client",+ },+ )++ assert response.status_code == 201+ client_info = response.json()+ assert client_info["scope"] == "read write calendar"++ registered_client = await oauth_proxy.get_client(client_info["client_id"])+ assert registered_client is not None+ assert registered_client.scope == "read write calendar"+class TestUpstreamClientIdFallback:"""Tests for clients that skip DCR and use the upstream client_id directly."""diff --git a/tests/server/auth/oauth_proxy/test_oauth_proxy.py b/tests/server/auth/oauth_proxy/test_oauth_proxy.pyindex 549d78dad..846f82eaa 100644--- a/tests/server/auth/oauth_proxy/test_oauth_proxy.py+++ b/tests/server/auth/oauth_proxy/test_oauth_proxy.py@@ -62,6 +62,7 @@ class TestOAuthProxyInitialization:assert proxy._token_endpoint_auth_method == "client_secret_post"assert proxy.client_registration_options is not Noneassert proxy.client_registration_options.valid_scopes == ["custom", "scopes"]+ assert proxy.client_registration_options.default_scopes == ["custom", "scopes"]def test_default_scope_str_prefers_valid_scopes(self, jwt_verifier):"""When valid_scopes is provided, _default_scope_str should use it@@ -96,6 +97,96 @@ class TestOAuthProxyInitialization:)assert proxy._default_scope_str == "openid"+ def test_update_default_scopes_updates_scope_str(self, jwt_verifier):+ """update_default_scopes should update the internal default scope string."""+ proxy = OAuthProxy(+ upstream_authorization_endpoint="https://auth.example.com/authorize",+ upstream_token_endpoint="https://auth.example.com/token",+ upstream_client_id="client-123",+ upstream_client_secret="secret-456",+ token_verifier=jwt_verifier,+ base_url="https://api.example.com",+ valid_scopes=["openid"],+ jwt_signing_key="test-secret",+ client_storage=MemoryStore(),+ )+ assert proxy._default_scope_str == "openid"++ proxy.update_default_scopes(["openid", "email", "calendar"])+ assert proxy._default_scope_str == "openid email calendar"++ def test_update_default_scopes_updates_cimd_manager(self, jwt_verifier):+ """update_default_scopes should update CIMD manager's default_scope."""+ proxy = OAuthProxy(+ upstream_authorization_endpoint="https://auth.example.com/authorize",+ upstream_token_endpoint="https://auth.example.com/token",+ upstream_client_id="client-123",+ upstream_client_secret="secret-456",+ token_verifier=jwt_verifier,+ base_url="https://api.example.com",+ valid_scopes=["openid"],+ jwt_signing_key="test-secret",+ client_storage=MemoryStore(),+ enable_cimd=True,+ )+ assert proxy._cimd_manager is not None+ assert proxy._cimd_manager.default_scope == "openid"++ proxy.update_default_scopes(["openid", "email", "drive"])+ assert proxy._cimd_manager.default_scope == "openid email drive"++ def test_update_default_scopes_updates_registration_options(self, jwt_verifier):+ """update_default_scopes should update client registration scope options."""+ proxy = OAuthProxy(+ upstream_authorization_endpoint="https://auth.example.com/authorize",+ upstream_token_endpoint="https://auth.example.com/token",+ upstream_client_id="client-123",+ upstream_client_secret="secret-456",+ token_verifier=jwt_verifier,+ base_url="https://api.example.com",+ valid_scopes=["openid"],+ jwt_signing_key="test-secret",+ client_storage=MemoryStore(),+ )+ assert proxy.client_registration_options is not None+ assert proxy.client_registration_options.valid_scopes == ["openid"]+ assert proxy.client_registration_options.default_scopes == ["openid"]++ scopes = ["openid", "email", "calendar"]+ proxy.update_default_scopes(scopes)+ scopes.append("drive")++ assert proxy.client_registration_options.valid_scopes == [+ "openid",+ "email",+ "calendar",+ ]+ assert proxy.client_registration_options.default_scopes == [+ "openid",+ "email",+ "calendar",+ ]++ def test_update_default_scopes_no_cimd_manager(self, jwt_verifier):+ """update_default_scopes should work when CIMD is disabled (no manager)."""+ proxy = OAuthProxy(+ upstream_authorization_endpoint="https://auth.example.com/authorize",+ upstream_token_endpoint="https://auth.example.com/token",+ upstream_client_id="client-123",+ upstream_client_secret="secret-456",+ token_verifier=jwt_verifier,+ base_url="https://api.example.com",+ valid_scopes=["openid"],+ jwt_signing_key="test-secret",+ client_storage=MemoryStore(),+ enable_cimd=False,+ )+ assert proxy._cimd_manager is None++ # Should not raise+ proxy.update_default_scopes(["openid", "email"])+ assert proxy._default_scope_str == "openid email"+def test_redirect_path_normalization(self, jwt_verifier):"""Test that redirect_path is normalized with leading slash."""proxy = OAuthProxy(