Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Preserve provider challenge defaults through MultiAuth (#5454)

Taylor Wilsdone21ec0b78040
diff --git a/docs/servers/auth/oauth-proxy.mdx b/docs/servers/auth/oauth-proxy.mdx
index 1abc98a60..d2a2a2e5c 100644
--- a/docs/servers/auth/oauth-proxy.mdx
+++ b/docs/servers/auth/oauth-proxy.mdx
@@ -405,6 +405,39 @@ JWTVerifier(..., required_scopes = ["read:user", "write:data"])
Dynamic clients created by the proxy will automatically include these scopes in their authorization requests. See the [Token Verification](#token-verification) section below for detailed setup.
+`required_scopes` and `valid_scopes` play different roles. `required_scopes` is what every token must carry, and it is the set the `WWW-Authenticate` challenge tells clients to request. `valid_scopes` is the catalog of scopes clients may request, advertised as `scopes_supported` in protected resource metadata. MCP clients that follow the challenge request only the required scopes, so a scope that appears only in `valid_scopes` stays optional.
+
+When your tools depend on scopes that clients won't know to ask for, you have two options. Adding them to `required_scopes` makes them mandatory, so token validation rejects any token without them. Overriding `get_challenge_scopes` asks clients to request them up front while validation stays on the narrower set. FastMCP calls the method with no argument for the server-wide challenge:
+
+```python
+from fastmcp import FastMCP
+from fastmcp.server.auth.providers.google import GoogleProvider
+
+GMAIL_READONLY = "https://www.googleapis.com/auth/gmail.readonly"
+
+
+class GmailProvider(GoogleProvider):
+ def get_challenge_scopes(
+ self, required_scopes: list[str] | None = None
+ ) -> list[str]:
+ if required_scopes is None:
+ return self.scopes_supported
+ return required_scopes
+
+
+auth = GmailProvider(
+ client_id="123456789.apps.googleusercontent.com",
+ client_secret="GOCSPX-abc123...",
+ base_url="http://localhost:8000",
+ required_scopes=["openid"],
+ valid_scopes=["openid", GMAIL_READONLY],
+)
+
+mcp = FastMCP("Gmail Server", auth=auth)
+```
+
+The override also sets the default challenge when the provider is wrapped in `MultiAuth`. Passing `required_scopes` to `MultiAuth` replaces it with exactly the scopes you pass.
+
### Custom Parameters
Some OAuth providers require additional parameters beyond the standard OAuth2 flow. Use `extra_authorize_params` and `extra_token_params` to pass provider-specific requirements. For example, Auth0 requires an `audience` parameter to issue JWT tokens instead of opaque tokens:
diff --git a/fastmcp_slim/fastmcp/server/auth/auth.py b/fastmcp_slim/fastmcp/server/auth/auth.py
index 7c2329ef9..a4db1cb0d 100644
--- a/fastmcp_slim/fastmcp/server/auth/auth.py
+++ b/fastmcp_slim/fastmcp/server/auth/auth.py
@@ -368,10 +368,12 @@ class AuthProvider(TokenVerifierProtocol):
def get_challenge_scopes(
self, required_scopes: list[str] | None = None
) -> list[str]:
- """Translate validation scopes into scopes clients should request.
+ """Select the scopes a `WWW-Authenticate` challenge asks clients to request.
- Providers whose authorization server uses a different scope format can
- override this method to translate any effective set of validation scopes.
+ Called without arguments for the server-wide challenge, which defaults to
+ `required_scopes`. Override this method to translate scopes for an
+ authorization server that uses a different format, or to request
+ optional scopes up front.
"""
return self.required_scopes if required_scopes is None else required_scopes
@@ -731,6 +733,7 @@ class MultiAuth(AuthProvider):
required_scopes=effective_scopes,
)
self.server = server
+ self._required_scopes_override = required_scopes
self.verifiers = normalized_verifiers
# If an explicit resource_base_url override was passed to MultiAuth,
@@ -821,12 +824,18 @@ class MultiAuth(AuthProvider):
def get_challenge_scopes(
self, required_scopes: list[str] | None = None
) -> list[str]:
- """Translate effective scopes through an unambiguous auth source."""
+ """Select challenge scopes through an unambiguous auth source.
+
+ Without a `required_scopes` override, the server selects its own default
+ challenge, including any customization of this hook.
+ """
+ if required_scopes is None:
+ required_scopes = self._required_scopes_override
+ if self.server is not None:
+ return self.server.get_challenge_scopes(required_scopes)
effective_scopes = (
self.required_scopes if required_scopes is None else required_scopes
)
- if self.server is not None:
- return self.server.get_challenge_scopes(effective_scopes)
if len(self.verifiers) == 1:
translator = getattr(self.verifiers[0], "get_challenge_scopes", None)
if translator is not None:
diff --git a/tests/server/auth/test_multi_auth.py b/tests/server/auth/test_multi_auth.py
index 608cea397..ab6a7fa17 100644
--- a/tests/server/auth/test_multi_auth.py
+++ b/tests/server/auth/test_multi_auth.py
@@ -1,10 +1,12 @@
import httpx2
import pytest
+from key_value.aio.stores.memory import MemoryStore
from pydantic import AnyHttpUrl
from fastmcp import FastMCP
from fastmcp.server.auth import MultiAuth, RemoteAuthProvider, TokenVerifier
from fastmcp.server.auth.auth import AccessToken
+from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.providers.azure import AzureJWTVerifier
from fastmcp.server.auth.providers.jwt import StaticTokenVerifier
@@ -30,6 +32,31 @@ class UnderScopedAzureJWTVerifier(AzureJWTVerifier):
return AccessToken(token=token, client_id="c", scopes=[])
+class OptionalScopeChallengeProxy(OAuthProxy):
+ """A proxy whose default challenge requests every supported scope."""
+
+ def get_challenge_scopes(
+ self, required_scopes: list[str] | None = None
+ ) -> list[str]:
+ if required_scopes is None:
+ return self.scopes_supported
+ return required_scopes
+
+
+def optional_scope_challenge_proxy() -> OptionalScopeChallengeProxy:
+ return OptionalScopeChallengeProxy(
+ upstream_authorization_endpoint="https://auth.example.com/authorize",
+ upstream_token_endpoint="https://auth.example.com/token",
+ upstream_client_id="client-id",
+ upstream_client_secret="client-secret",
+ token_verifier=StaticTokenVerifier(tokens={}, required_scopes=["openid"]),
+ base_url="https://api.example.com",
+ valid_scopes=["openid", "email", "calendar"],
+ jwt_signing_key="test-secret",
+ client_storage=MemoryStore(),
+ )
+
+
class TestMultiAuthInit:
"""Test MultiAuth initialization and validation."""
@@ -198,6 +225,18 @@ class TestMultiAuthInit:
assert auth.scopes_supported == ["api://client-id/read"]
assert auth.challenge_scopes == ["admin"]
+ def test_challenge_scopes_use_server_default_selection(self):
+ auth = MultiAuth(server=optional_scope_challenge_proxy())
+
+ assert auth.challenge_scopes == ["openid", "email", "calendar"]
+
+ def test_challenge_scopes_keep_override_matching_server_default(self):
+ auth = MultiAuth(
+ server=optional_scope_challenge_proxy(), required_scopes=["openid"]
+ )
+
+ assert auth.challenge_scopes == ["openid"]
+
class TestMultiAuthVerifyToken:
"""Test MultiAuth token verification chain."""