Skip to content

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

fix(auth): preserve verifier-defined challenge scopes through wrappers (#5478)

mika9af97ee0aa64
diff --git a/docs/servers/auth/multi-auth.mdx b/docs/servers/auth/multi-auth.mdx
index 7a462c464..d997aedc5 100644
--- a/docs/servers/auth/multi-auth.mdx
+++ b/docs/servers/auth/multi-auth.mdx
@@ -91,6 +91,14 @@ mcp = FastMCP("Multi-Issuer Server", auth=auth)
Without a server, no OAuth routes or metadata are served. This is appropriate for internal systems where clients already know how to obtain tokens.
+## Challenge Scopes
+
+Clients use the `WWW-Authenticate` challenge to decide which scopes to request. When you omit `required_scopes` or pass `None`, `MultiAuth` delegates default challenge selection to its server, or to its sole verifier when no server is configured. This preserves custom `get_challenge_scopes(None)` hooks. With multiple verifiers and no server, it does not select or combine their defaults; no scope parameter is advertised unless you configure `required_scopes`.
+
+An explicit `required_scopes` list is passed to the delegated challenge hook and also sets the scopes required by `MultiAuth`'s HTTP middleware. An empty list removes that outer scope requirement. Each verifier still enforces its own token validation requirements, so `required_scopes=[]` does not make invalid or under-scoped tokens valid.
+
+When the server is a `RemoteAuthProvider`, its configured `challenge_scopes` applies when the effective scopes equal that provider's `required_scopes`, including an explicit list with the same values. A different explicit list is passed to the verifier's hook for translation. Without configured `challenge_scopes`, the verifier receives the supplied list, or `None` to select its default.
+
## Source Names
Each source has a stable identity for sessions, background tasks, and continued requests. Use an ordered mapping to give verifiers explicit names; pass `server_source_id` to name the delegated auth server. These names follow the source across restarts and changes to verification order. MultiAuth qualifies the returned token's `client_id` with this source identity and the verified issuer and subject, when present. Its `original_client_id` field contains the identifier returned by the verifier; bearer token bytes, claims, subject, and scopes stay the same.
diff --git a/fastmcp_slim/fastmcp/server/auth/auth.py b/fastmcp_slim/fastmcp/server/auth/auth.py
index a4db1cb0d..7dcea2bd3 100644
--- a/fastmcp_slim/fastmcp/server/auth/auth.py
+++ b/fastmcp_slim/fastmcp/server/auth/auth.py
@@ -600,7 +600,7 @@ class RemoteAuthProvider(AuthProvider):
translator = getattr(self.token_verifier, "get_challenge_scopes", None)
if translator is None:
return effective_scopes
- return translator(effective_scopes)
+ return translator(required_scopes)
async def verify_token(self, token: str) -> AccessToken | None:
"""Verify token using the configured token verifier."""
@@ -826,8 +826,8 @@ class MultiAuth(AuthProvider):
) -> list[str]:
"""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.
+ Without a `required_scopes` override, the server or sole verifier selects
+ its own default challenge, including any customization of this hook.
"""
if required_scopes is None:
required_scopes = self._required_scopes_override
@@ -839,7 +839,7 @@ class MultiAuth(AuthProvider):
if len(self.verifiers) == 1:
translator = getattr(self.verifiers[0], "get_challenge_scopes", None)
if translator is not None:
- return translator(effective_scopes)
+ return translator(required_scopes)
return effective_scopes
async def verify_token(self, token: str) -> AccessToken | None:
diff --git a/tests/server/auth/test_auth_provider.py b/tests/server/auth/test_auth_provider.py
index e9ce2f4b0..9cba203a5 100644
--- a/tests/server/auth/test_auth_provider.py
+++ b/tests/server/auth/test_auth_provider.py
@@ -3,9 +3,10 @@ import re
import httpx2
import pytest
from pydantic import AnyHttpUrl
+from starlette.testclient import TestClient
from fastmcp import FastMCP
-from fastmcp.server.auth import RemoteAuthProvider, TokenVerifier
+from fastmcp.server.auth import MultiAuth, RemoteAuthProvider, TokenVerifier
from fastmcp.server.auth.auth import AccessToken
from fastmcp.server.auth.providers.jwt import StaticTokenVerifier
@@ -24,6 +25,27 @@ class LegacyTokenVerifier(TokenVerifier):
return None
+class OptionalScopeVerifier(TokenVerifier):
+ """Request optional scopes without requiring them for token validation."""
+
+ def get_challenge_scopes(
+ self, required_scopes: list[str] | None = None
+ ) -> list[str]:
+ return ["openid", "email"] if required_scopes is None else required_scopes
+
+ async def verify_token(self, token: str) -> AccessToken | None:
+ return None
+
+
+def optional_scope_remote_provider() -> RemoteAuthProvider:
+ return RemoteAuthProvider(
+ token_verifier=OptionalScopeVerifier(required_scopes=["openid"]),
+ authorization_servers=[AnyHttpUrl("https://issuer.example.com")],
+ base_url="https://api.example.com",
+ )
+
+
class TestAuthProviderBase:
"""Test suite for base AuthProvider behaviors that apply to all auth providers."""
@@ -35,6 +57,196 @@ class TestAuthProviderBase:
assert verifier.required_scopes == ["read"]
assert verifier.resource_base_url is None
+ @pytest.mark.parametrize("wrapper", ["direct", "remote", "multi", "multi_remote"])
+ @pytest.mark.parametrize("custom_default", [False, True])
+ async def test_wrappers_preserve_default_challenge_scopes(
+ self, wrapper: str, custom_default: bool
+ ):
+ verifier = (
+ OptionalScopeVerifier(required_scopes=["openid"])
+ if custom_default
+ else StaticTokenVerifier(tokens={}, required_scopes=["openid"])
+ )
+ auth = verifier
+ if wrapper in {"remote", "multi_remote"}:
+ auth = RemoteAuthProvider(
+ token_verifier=verifier,
+ authorization_servers=[AnyHttpUrl("https://issuer.example.com")],
+ base_url="https://api.example.com",
+ )
+ if wrapper == "multi":
+ auth = MultiAuth(verifiers=verifier)
+ elif wrapper == "multi_remote":
+ auth = MultiAuth(server=auth)
+
+ app = FastMCP("test", auth=auth).http_app()
+ async with httpx2.AsyncClient(
+ transport=httpx2.ASGITransport(app=app), base_url="https://api.example.com"
+ ) as client:
+ response = await client.get("/mcp")
+
+ assert response.status_code == 401
+ match = re.search(r'\bscope="([^"]*)"', response.headers["www-authenticate"])
+ assert match is not None
+ assert set(match.group(1).split()) == (
+ {"openid", "email"} if custom_default else {"openid"}
+ )
+
+ @pytest.mark.parametrize("use_server", [False, True])
+ @pytest.mark.parametrize("required_scopes", [["openid"], ["admin"], []])
+ async def test_multi_auth_explicit_challenge_scope_override(
+ self,
+ optional_scope_remote_provider: RemoteAuthProvider,
+ use_server: bool,
+ required_scopes: list[str],
+ ):
+ auth = (
+ MultiAuth(
+ server=optional_scope_remote_provider, required_scopes=required_scopes
+ )
+ if use_server
+ else MultiAuth(
+ verifiers=optional_scope_remote_provider.token_verifier,
+ required_scopes=required_scopes,
+ )
+ )
+ app = FastMCP("test", auth=auth).http_app()
+ async with httpx2.AsyncClient(
+ transport=httpx2.ASGITransport(app=app), base_url="https://api.example.com"
+ ) as client:
+ response = await client.get("/mcp")
+
+ assert response.status_code == 401
+ match = re.search(r'\bscope="([^"]*)"', response.headers["www-authenticate"])
+ scopes = set(match.group(1).split()) if match else set()
+ assert scopes == set(required_scopes)
+
+ @pytest.mark.parametrize("challenge_scopes", [["profile"], []])
+ def test_remote_auth_explicit_challenge_scopes(
+ self,
+ optional_scope_remote_provider: RemoteAuthProvider,
+ challenge_scopes: list[str],
+ ):
+ auth = RemoteAuthProvider(
+ token_verifier=optional_scope_remote_provider.token_verifier,
+ authorization_servers=optional_scope_remote_provider.authorization_servers,
+ base_url=optional_scope_remote_provider.base_url,
+ challenge_scopes=challenge_scopes,
+ )
+
+ assert auth.challenge_scopes == challenge_scopes
+ assert auth.get_challenge_scopes(["openid"]) == challenge_scopes
+ assert auth.get_challenge_scopes(["admin"]) == ["admin"]
+ assert auth.get_challenge_scopes([]) == []
+
+ @pytest.mark.parametrize("use_server", [False, True])
+ @pytest.mark.parametrize("required_scopes", [None, [], ["admin"]])
+ def test_multi_auth_scope_override_with_verified_tokens(
+ self, use_server: bool, required_scopes: list[str] | None
+ ) -> None:
+ verifier = StaticTokenVerifier(
+ tokens={
+ "valid": {"client_id": "client", "scopes": ["openid"]},
+ "under_scoped": {"client_id": "client", "scopes": []},
+ },
+ required_scopes=["openid"],
+ )
+ auth = (
+ MultiAuth(
+ server=RemoteAuthProvider(
+ token_verifier=verifier,
+ authorization_servers=[AnyHttpUrl("https://issuer.example.com")],
+ base_url="https://api.example.com",
+ ),
+ required_scopes=required_scopes,
+ )
+ if use_server
+ else MultiAuth(verifiers=verifier, required_scopes=required_scopes)
+ )
+ assert verifier.required_scopes == ["openid"]
+ assert auth.required_scopes == (
+ required_scopes
+ if required_scopes is not None
+ else (["openid"] if use_server else [])
+ )
+ app = FastMCP("test", auth=auth).http_app(stateless_http=True)
+ with TestClient(app) as client:
+ for token, expected_status in [
+ ("valid", 403 if required_scopes == ["admin"] else 200),
+ ("under_scoped", 401),
+ ("unknown", 401),
+ ]:
+ response = client.post(
+ "/mcp",
+ headers={
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/json, text/event-stream",
+ },
+ json={
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2026-07-28",
+ "capabilities": {},
+ "clientInfo": {"name": "test", "version": "1"},
+ },
+ },
+ )
+ assert response.status_code == expected_status
+ if required_scopes == [] and expected_status == 401:
+ assert 'scope="' not in response.headers["www-authenticate"]
+
+ @pytest.mark.parametrize(
+ ("verifier_scopes", "required_scopes", "expected_scopes"),
+ [
+ (["openid"], None, ["profile"]),
+ (["openid"], ["openid"], ["profile"]),
+ (["openid"], ["admin"], ["admin"]),
+ (["openid"], [], []),
+ ([], [], ["profile"]),
+ ],
+ )
+ def test_multi_auth_remote_challenge_scope_precedence(
+ self,
+ verifier_scopes: list[str],
+ required_scopes: list[str] | None,
+ expected_scopes: list[str],
+ ) -> None:
+ remote = RemoteAuthProvider(
+ token_verifier=OptionalScopeVerifier(required_scopes=verifier_scopes),
+ authorization_servers=[AnyHttpUrl("https://issuer.example.com")],
+ base_url="https://api.example.com",
+ challenge_scopes=["profile"],
+ )
+ auth = MultiAuth(server=remote, required_scopes=required_scopes)
+
+ assert auth.challenge_scopes == expected_scopes
+ assert auth.get_challenge_scopes(None) == expected_scopes
+
+ @pytest.mark.parametrize("required_scopes", [None, [], ["admin"]])
+ async def test_multiple_verifiers_do_not_choose_a_default_challenge(
+ self, required_scopes: list[str] | None
+ ) -> None:
+ first = OptionalScopeVerifier(required_scopes=["openid"])
+ second = LegacyTokenVerifier(required_scopes=["profile"])
+ assert first.challenge_scopes == ["openid", "email"]
+ assert second.challenge_scopes == ["profile"]
+ auth = MultiAuth(
+ verifiers={"first": first, "second": second},
+ required_scopes=required_scopes,
+ )
+ assert auth.challenge_scopes == (required_scopes or [])
+ app = FastMCP("test", auth=auth).http_app()
+ async with httpx2.AsyncClient(
+ transport=httpx2.ASGITransport(app=app), base_url="https://api.example.com"
+ ) as client:
+ response = await client.get("/mcp")
+ assert response.status_code == 401
+ match = re.search(r'\bscope="([^"]*)"', response.headers["www-authenticate"])
+ scopes = set(match.group(1).split()) if match else set()
+ assert scopes == set(required_scopes or [])
+
@pytest.fixture
def basic_remote_provider(self):
"""Basic RemoteAuthProvider fixture for testing base AuthProvider behaviors."""