π The fast, Pythonic way to build MCP servers and clients.
fix!: Qualify MultiAuth client identities (#5455)
Jeremiah Lowind9b2199afdb6
diff --git a/docs/servers/auth/multi-auth.mdx b/docs/servers/auth/multi-auth.mdxindex 3675c92a6..7a462c464 100644--- a/docs/servers/auth/multi-auth.mdx+++ b/docs/servers/auth/multi-auth.mdx@@ -56,7 +56,7 @@ Interactive MCP clients authenticate through the OAuth proxy as usual. Backend s`MultiAuth` checks sources in a deterministic order:1. **Server** (if provided) β the full auth provider's `verify_token` runs first-2. **Verifiers** β each `TokenVerifier` is tried in list order+2. **Verifiers** β each `TokenVerifier` is tried in mapping or list orderThe first source that returns a valid `AccessToken` wins. If every source returns `None`, the request receives a 401 response.@@ -91,6 +91,25 @@ 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.+## 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.++```python+from fastmcp.server.auth import MultiAuth+from fastmcp.server.auth.providers.jwt import StaticTokenVerifier++company = StaticTokenVerifier(tokens={"company-token": {"client_id": "service", "scopes": []}})+partner = StaticTokenVerifier(tokens={"partner-token": {"client_id": "service", "scopes": []}})+auth = MultiAuth(verifiers={"company": company, "partner": partner})+```++List and single-verifier forms remain available when their derived source identities are distinct. JWT verifiers derive identities from configured issuers and JWKS URLs; introspection verifiers use their endpoint, remote providers use their wrapped verifier, OAuth proxies use their configured issuer, upstream endpoints, and verifier, other OAuth servers use their configured issuer, and other providers use their Python type. Explicit names are recommended when configuration or provider types may change.++<Note>+This changes `get_access_token().client_id` and ownership for existing `MultiAuth` sessions, tasks, and continued requests. Update authorization checks that compare the verifier's original client ID to read `get_access_token().original_client_id` instead. Recreate sessions and resubmit tasks after upgrading. Configurations with duplicate derived identities now need explicit names, including multiple static verifiers or custom verifiers of the same type. Changing a source name starts a new ownership scope.+</Note>+## API Reference### MultiAuth@@ -98,6 +117,7 @@ Without a server, no OAuth routes or metadata are served. This is appropriate fo| Parameter | Type | Description || --- | --- | --- || `server` | `AuthProvider \| None` | Optional auth provider that owns routes and OAuth metadata. Also tried first for token verification. |-| `verifiers` | `list[TokenVerifier] \| TokenVerifier` | One or more token verifiers tried after the server. |+| `verifiers` | `Mapping[str, TokenVerifier] \| list[TokenVerifier] \| TokenVerifier` | Named or distinctly configured token verifiers tried after the server. |+| `server_source_id` | `str \| None` | Stable name for the delegated server source. Defaults to its derived identity. || `base_url` | `str \| None` | Override the base URL. Defaults to the server's `base_url`. || `required_scopes` | `list[str] \| None` | Override required scopes. Defaults to the server's scopes. |diff --git a/fastmcp_slim/fastmcp/server/auth/auth.py b/fastmcp_slim/fastmcp/server/auth/auth.pyindex 6e3b13f42..7c2329ef9 100644--- a/fastmcp_slim/fastmcp/server/auth/auth.py+++ b/fastmcp_slim/fastmcp/server/auth/auth.py@@ -1,6 +1,8 @@from __future__ import annotations+import hashlibimport json+from collections.abc import Mapping, Sequencefrom typing import TYPE_CHECKING, Anyfrom urllib.parse import urlparse@@ -26,6 +28,7 @@ from mcp.server.auth.provider import (OAuthAuthorizationServerProvider,RefreshToken,TokenError,+ principal_components,)from mcp.server.auth.provider import (TokenVerifier as TokenVerifierProtocol,@@ -59,6 +62,8 @@ class AccessToken(_SDKAccessToken):"""AccessToken that includes all JWT claims."""claims: dict[str, Any] = Field(default_factory=dict)+ original_client_id: str | None = None+ """Client ID before MultiAuth qualified it with its configured source."""class TokenHandler(_SDKTokenHandler):@@ -672,7 +677,11 @@ class MultiAuth(AuthProvider):self,*,server: AuthProvider | None = None,- verifiers: list[TokenVerifier] | TokenVerifier | None = None,+ verifiers: Mapping[str, TokenVerifier]+ | Sequence[TokenVerifier]+ | TokenVerifier+ | None = None,+ server_source_id: str | None = None,base_url: AnyHttpUrl | str | None = None,resource_base_url: AnyHttpUrl | str | None = None,required_scopes: list[str] | None = None,@@ -683,18 +692,27 @@ class MultiAuth(AuthProvider):server: Optional auth provider (e.g., OAuthProxy) that owns routesand OAuth metadata. Also participates in token verification asthe first verifier tried.- verifiers: One or more token verifiers to try after the server.+ verifiers: Named token verifiers, or configured verifiers with distinct+ issuer or endpoint identities, tried after the server.+ server_source_id: Stable name for the server trust source. Defaults+ to its configured issuer, endpoint, or provider type identity.base_url: Override the base URL. Defaults to the server's base_url.resource_base_url: Override the protected resource base URL. Defaultsto the server's resource_base_url when available.required_scopes: Override required scopes. Defaults to the server's."""- if verifiers is None:- verifiers = []+ explicit_ids: dict[str, TokenVerifier] | None = None+ if isinstance(verifiers, Mapping):+ explicit_ids = dict(verifiers)+ normalized_verifiers = list(explicit_ids.values())elif isinstance(verifiers, TokenVerifier):- verifiers = [verifiers]+ normalized_verifiers = [verifiers]+ else:+ normalized_verifiers = list(verifiers or [])- if server is None and not verifiers:+ if server_source_id is not None and server is None:+ raise ValueError("server_source_id requires a server")+ if server is None and not normalized_verifiers:raise ValueError("MultiAuth requires at least a server or one verifier")effective_base_url = base_url or (server.base_url if server else None)@@ -713,7 +731,7 @@ class MultiAuth(AuthProvider):required_scopes=effective_scopes,)self.server = server- self.verifiers = list(verifiers)+ self.verifiers = normalized_verifiers# If an explicit resource_base_url override was passed to MultiAuth,# propagate it to the wrapped server so its routes advertise metadata@@ -725,6 +743,73 @@ class MultiAuth(AuthProvider):if self.server is not None:self._sources.append(self.server)self._sources.extend(self.verifiers)+ self._source_ids = []+ if self.server is not None:+ self._source_ids.append(+ server_source_id+ if server_source_id is not None+ else self._configured_source_id(self.server)+ )+ if explicit_ids is not None:+ self._source_ids.extend(explicit_ids)+ else:+ self._source_ids.extend(+ self._configured_source_id(v) for v in self.verifiers+ )+ if any(+ not isinstance(value, str) or not value.strip() or value != value.strip()+ for value in self._source_ids+ ):+ raise ValueError(+ "MultiAuth source IDs must be nonempty strings without outer whitespace"+ )+ if len(set(self._source_ids)) != len(self._source_ids):+ raise ValueError(+ "MultiAuth source IDs must be unique; name each distinct source explicitly"+ )++ @staticmethod+ def _configured_source_id(source: AuthProvider) -> str:+ """Identify a configured trust source independently of its credentials."""+ from fastmcp.server.auth.oauth_proxy import OAuthProxy+ from fastmcp.server.auth.providers.introspection import (+ IntrospectionTokenVerifier,+ )+ from fastmcp.server.auth.providers.jwt import JWTVerifier++ descriptor: dict[str, Any] = {}+ if isinstance(source, JWTVerifier):+ if source.issuer:+ descriptor["issuer"] = (+ sorted(source.issuer)+ if isinstance(source.issuer, list)+ else source.issuer+ )+ if source.jwks_uri:+ descriptor["jwks_uri"] = str(source.jwks_uri)+ elif isinstance(source, IntrospectionTokenVerifier):+ descriptor["introspection_url"] = source.introspection_url+ elif isinstance(source, RemoteAuthProvider):+ descriptor["token_verifier"] = MultiAuth._configured_source_id(+ source.token_verifier+ )+ elif isinstance(source, OAuthProxy):+ descriptor["issuer_url"] = str(source.issuer_url)+ descriptor["upstream_authorization_endpoint"] = (+ source._upstream_authorization_endpoint+ )+ descriptor["upstream_token_endpoint"] = source._upstream_token_endpoint+ descriptor["token_verifier"] = MultiAuth._configured_source_id(+ source._token_validator+ )+ elif isinstance(source, OAuthProvider):+ descriptor["issuer_url"] = str(source.issuer_url)+ if not descriptor:+ descriptor["provider"] = (+ f"{type(source).__module__}.{type(source).__qualname__}"+ )+ raw = json.dumps(descriptor, sort_keys=True, separators=(",", ":"))+ return "configured:" + hashlib.sha256(raw.encode()).hexdigest()@propertydef scopes_supported(self) -> list[str]:@@ -755,11 +840,33 @@ class MultiAuth(AuthProvider):it is logged and treated as a non-match so that remaining sourcesstill get a chance to verify the token."""- for source in self._sources:+ for source_id, source in zip(self._source_ids, self._sources, strict=True):try:result = await source.verify_token(token)if result is not None:- return result+ # Normalize SDK-only tokens to the FastMCP model so the+ # original identifier survives task-context serialization.+ if not isinstance(result, AccessToken):+ result = AccessToken(+ **result.model_dump(exclude={"claims"}),+ claims=result.claims or {},+ )+ original_client_id = (+ result.original_client_id+ if isinstance(source, MultiAuth)+ and result.original_client_id is not None+ else result.client_id+ )+ qualified_client_id = json.dumps(+ [source_id, *principal_components(result)],+ separators=(",", ":"),+ )+ return result.model_copy(+ update={+ "client_id": qualified_client_id,+ "original_client_id": original_client_id,+ }+ )except Exception:logger.debug("Token verification failed for %s, trying next source",diff --git a/tests/server/auth/test_auth_source_identities.py b/tests/server/auth/test_auth_source_identities.pynew file mode 100644index 000000000..ca2f77aaa--- /dev/null+++ b/tests/server/auth/test_auth_source_identities.py@@ -0,0 +1,526 @@+"""Configured authentication sources retain stable principal identities."""++import json+from collections.abc import AsyncGenerator+from types import SimpleNamespace+from typing import Any, cast+from urllib.parse import parse_qs++import httpx2+import pytest+from fastmcp_tasks.context import (+ TaskContextSnapshot,+ _apply_snapshot_to_context,+ get_task_scope,+)+from mcp.server.auth.middleware.auth_context import auth_context_var+from mcp.server.auth.middleware.bearer_auth import (+ AuthenticatedUser,+ authorization_context,+)+from mcp.server.auth.provider import AccessToken as SDKAccessToken+from mcp.server.auth.provider import principal_components+from mcp.server.context import ServerRequestContext+from mcp.server.request_state import authenticated_principal+from mcp_types import InputRequiredResult+from starlette.testclient import TestClient++from fastmcp import Context, FastMCP+from fastmcp.server.auth import (+ AccessToken,+ MultiAuth,+ RemoteAuthProvider,+ TokenVerifier,+)+from fastmcp.server.auth.oauth_proxy import OAuthProxy+from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier+from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair+from fastmcp.server.dependencies import get_access_token+from fastmcp.server.sessions import UserSession, current_principal+from fastmcp.utilities.tests import asgi_server+from tests.server.http.test_session_owner_enforcement import (+ INITIALIZE_REQUEST,+ MCP_HEADERS,+ TOOLS_LIST_REQUEST,+)+from tests.server.test_mrtr_guards import _ask, _elicit+++class StoredVerifier(TokenVerifier):+ def __init__(self, bearer: str) -> None:+ super().__init__()+ self.bearer = bearer+ self.result = AccessToken(+ token=bearer,+ client_id="shared",+ subject="reader",+ scopes=[],+ claims={"iss": "same", "sub": "reader"},+ original_client_id="supplied",+ )++ async def verify_token(self, token: str) -> AccessToken | None:+ return self.result if token == self.bearer else None+++async def test_named_sources_preserve_raw_fields_and_source_token() -> None:+ first, second = StoredVerifier("one"), StoredVerifier("two")+ auth = MultiAuth(verifiers={"company": first, "partner": second})+ a, b = await auth.verify_token("one"), await auth.verify_token("two")+ assert a is not None and b is not None+ assert a is not first.result+ assert first.result.client_id == "shared"+ assert first.result.original_client_id == "supplied"+ assert json.loads(a.client_id) == ["company", "shared", "same", "reader"]+ assert json.loads(b.client_id) == ["partner", "shared", "same", "reader"]+ assert a.original_client_id == b.original_client_id == "shared"+ assert principal_components(a) != principal_components(b)+ assert a.claims == first.result.claims+ assert a.subject == first.result.subject+ assert a.token == first.result.token+++async def test_source_order_and_reconstruction_keep_identities() -> None:+ first, second = StoredVerifier("one"), StoredVerifier("two")+ left = MultiAuth(verifiers={"company": first, "partner": second})+ right = MultiAuth(verifiers={"partner": second, "company": first})+ a, b = await left.verify_token("one"), await right.verify_token("one")+ assert a is not None and b is not None+ assert principal_components(a) == principal_components(b)+++async def test_nested_sources_keep_the_inner_namespace() -> None:+ inner = MultiAuth(verifiers={"company": StoredVerifier("one")})+ outer = MultiAuth(server=inner, server_source_id="interactive")+ result = await outer.verify_token("one")+ assert result is not None+ outer_name, inner_id, issuer, subject = json.loads(result.client_id)+ assert subject == "reader"+ assert issuer == "same"+ assert outer_name == "interactive"+ assert json.loads(inner_id) == ["company", "shared", "same", "reader"]+ assert result.original_client_id == "shared"++[email protected]("name", ["", " ", " company"])+def test_names_are_nonempty_and_unambiguous(name: str) -> None:+ with pytest.raises(ValueError, match="source IDs"):+ MultiAuth(verifiers={name: StoredVerifier("one")})+++def test_opaque_sources_are_stable_and_duplicates_require_names() -> None:+ first = MultiAuth(verifiers=StoredVerifier("one"))+ restarted = MultiAuth(verifiers=StoredVerifier("new-credentials"))+ assert first._source_ids == restarted._source_ids+ with pytest.raises(ValueError, match="unique"):+ MultiAuth(verifiers=[StoredVerifier("one"), StoredVerifier("two")])+++def test_configured_source_ids_are_stable_and_duplicates_require_names() -> None:+ first = JWTVerifier(+ jwks_uri="https://one.example/keys", issuer="https://one.example"+ )+ second = JWTVerifier(+ jwks_uri="https://two.example/keys", issuer="https://two.example"+ )+ a, b = MultiAuth(verifiers=[first, second]), MultiAuth(verifiers=[second, first])+ assert a._source_ids == list(reversed(b._source_ids))+ assert MultiAuth(verifiers=first)._source_ids == a._source_ids[:1]+ with pytest.raises(ValueError, match="unique"):+ MultiAuth(verifiers=[first, first])+++async def test_ownership_consumers_agree_and_snapshot_preserves_raw_token() -> None:+ auth = MultiAuth(+ verifiers={"company": StoredVerifier("one"), "partner": StoredVerifier("two")}+ )+ tokens = [await auth.verify_token(t) for t in ["one", "two"]]+ contexts = []+ identities = []+ task_scopes = []+ for token in tokens:+ assert token is not None+ marker = auth_context_var.set(AuthenticatedUser(token))+ try:+ assert get_access_token() is token+ identities.append(current_principal())+ assert current_principal() == authenticated_principal(+ cast(ServerRequestContext[Any, Any], SimpleNamespace())+ )+ task_scopes.append(get_task_scope())+ contexts.append(authorization_context(AuthenticatedUser(token)))+ restored = AccessToken.model_validate_json(token.model_dump_json())+ assert principal_components(restored) == principal_components(token)+ snapshot = TaskContextSnapshot(access_token_json=token.model_dump_json())+ _apply_snapshot_to_context(snapshot)+ assert current_principal() == identities[-1]+ restored_access_token = get_access_token()+ assert restored_access_token is not None+ assert restored_access_token.claims == token.claims+ assert restored_access_token.original_client_id == "shared"+ assert get_task_scope() == task_scopes[-1]+ finally:+ auth_context_var.reset(marker)+ assert identities[0] != identities[1]+ assert contexts[0] != contexts[1]+ assert task_scopes[0] != task_scopes[1]+++def test_plain_token_identity_retains_legacy_representation() -> None:+ token = AccessToken(+ token="one",+ client_id="client",+ subject="reader",+ scopes=[],+ claims={"iss": "issuer", "sub": "reader"},+ )+ assert principal_components(token) == ("client", "issuer", "reader")+ marker = auth_context_var.set(AuthenticatedUser(token))+ try:+ assert get_task_scope() == "client|reader"+ assert authorization_context(AuthenticatedUser(token)) == {+ "client_id": "client",+ "issuer": "issuer",+ "subject": "reader",+ }+ finally:+ auth_context_var.reset(marker)+++async def test_introspection_endpoints_keep_session_and_transport_ownership_separate() -> (+ None+):+ def respond(request: httpx2.Request) -> httpx2.Response:+ active = (+ request.url.host == "one.example" and b"token=one" in request.content+ ) or (request.url.host == "two.example" and b"token=two" in request.content)+ return httpx2.Response(+ 200, json={"active": active, "client_id": "shared", "scope": ""}+ )++ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http:+ sources = [+ IntrospectionTokenVerifier(+ introspection_url="https://" + host + "/introspect",+ client_id="application",+ client_secret="synthetic",+ http_client=http,+ )+ for host in ["one.example", "two.example"]+ ]+ auth = MultiAuth(verifiers=sources)+ server = FastMCP("Configured sources", auth=auth)++ @server.tool+ async def store(value: str, session: UserSession) -> str:+ await session.set("value", value)+ return value++ @server.tool+ async def read(session: UserSession) -> str | None:+ return await session.get("value")++ app = server.http_app(stateless_http=True, json_response=True)+ with TestClient(app, base_url="http://127.0.0.1") as client:++ def call(token: str, name: str, args: dict[str, Any]) -> Any:+ response = client.post(+ "/mcp",+ headers={**MCP_HEADERS, "authorization": "Bearer " + token},+ json={+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {"name": name, "arguments": args},+ },+ )+ assert response.status_code == 200+ return response.json()["result"]["structuredContent"]["result"]++ assert call("one", "store", {"value": "saved"}) == "saved"+ assert call("two", "read", {}) is None+ assert call("two", "store", {"value": "other"}) == "other"+ assert call("one", "read", {}) == "saved"++ app = server.http_app(stateless_http=False, json_response=True)+ with TestClient(app, base_url="http://127.0.0.1") as client:+ initialized = client.post(+ "/mcp",+ headers={**MCP_HEADERS, "authorization": "Bearer one"},+ json=INITIALIZE_REQUEST,+ )+ assert initialized.status_code == 200+ session_id = initialized.headers["mcp-session-id"]+ response = client.post(+ "/mcp",+ headers={+ **MCP_HEADERS,+ "authorization": "Bearer two",+ "mcp-session-id": session_id,+ "mcp-protocol-version": "2024-11-05",+ },+ json=TOOLS_LIST_REQUEST,+ )+ assert response.status_code == 404+++async def test_claims_only_subjects_keep_user_ownership_separate() -> None:+ verifier = StoredVerifier("one")+ verifier.result.subject = None+ verifier.result.claims["sub"] = "alice"+ auth = MultiAuth(verifiers={"company": verifier})+ alice = await auth.verify_token("one")+ verifier.result.claims = {**verifier.result.claims, "sub": "bob"}+ bob = await auth.verify_token("one")+ assert alice is not None and bob is not None+ assert alice.subject is None and bob.subject is None+ scopes = []+ for token in (alice, bob):+ marker = auth_context_var.set(AuthenticatedUser(token))+ try:+ scopes.append(get_task_scope())+ finally:+ auth_context_var.reset(marker)+ assert scopes[0] != scopes[1]+++async def configured_auth() -> AsyncGenerator[MultiAuth, None]:+ def respond(request: httpx2.Request) -> httpx2.Response:+ bearer = parse_qs(request.content.decode())["token"][0]+ source = (request.url.host or "").split(".")[0]+ return httpx2.Response(+ 200,+ json={+ "active": bearer == source,+ "client_id": "shared",+ "scope": "",+ },+ )++ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http:+ yield MultiAuth(+ verifiers=[+ IntrospectionTokenVerifier(+ introspection_url=f"https://{name}.example/introspect",+ client_id="application",+ client_secret="synthetic",+ http_client=http,+ )+ for name in ("one", "two")+ ]+ )+++async def test_configured_sources_keep_sse_message_ownership_separate(+ configured_auth: MultiAuth,+) -> None:+ server = FastMCP("SSE identities", auth=configured_auth)+ async with asgi_server(server, transport="sse") as running:+ async with running.http_client() as http:+ async with http.stream(+ "GET",+ running.url,+ headers={"accept": "text/event-stream", "authorization": "Bearer one"},+ ) as response:+ assert response.status_code == 200+ message_path = None+ async for line in response.aiter_lines():+ if line.startswith("data: "):+ message_path = line.removeprefix("data: ")+ break+ assert message_path is not None+ message_url = str(httpx2.URL(running.url).join(message_path))+ other = await http.post(+ message_url,+ headers={"authorization": "Bearer two"},+ json=INITIALIZE_REQUEST,+ )+ assert other.status_code == 404+ same = await http.post(+ message_url,+ headers={"authorization": "Bearer one"},+ json=INITIALIZE_REQUEST,+ )+ assert same.status_code == 202+++async def test_configured_sources_keep_saved_request_state_separate(+ configured_auth: MultiAuth,+) -> None:+ server = FastMCP("Continued requests", auth=configured_auth)++ @server.tool+ async def continue_work(ctx: Context) -> str | InputRequiredResult:+ if ctx.request_state is not None:+ return ctx.request_state+ return _ask(+ _elicit("confirmation", "Continue?", "answer"), "confirmation", "saved"+ )++ app = server.http_app(stateless_http=True, json_response=True)+ with TestClient(app, base_url="http://127.0.0.1") as client:+ headers = {+ **MCP_HEADERS,+ "mcp-protocol-version": "2026-07-28",+ "mcp-method": "tools/call",+ "mcp-name": "continue_work",+ }+ request = {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {+ "name": "continue_work",+ "arguments": {},+ "_meta": {+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientCapabilities": {+ "elicitation": {"form": {}}+ },+ },+ },+ }+ first = client.post(+ "/mcp", headers={**headers, "authorization": "Bearer one"}, json=request+ )+ assert first.status_code == 200, first.text+ saved = first.json()["result"]["requestState"]+ assert saved != "saved"+ request["params"]["requestState"] = saved+ other = client.post(+ "/mcp", headers={**headers, "authorization": "Bearer two"}, json=request+ )+ assert "error" in other.json()+ same = client.post(+ "/mcp", headers={**headers, "authorization": "Bearer one"}, json=request+ )+ assert same.json()["result"]["content"][0]["text"] == "saved"+++async def test_sdk_verifier_tokens_retain_original_client_id_after_serialization() -> (+ None+):+ sdk_result = SDKAccessToken(token="one", client_id="client", scopes=[])++ class SDKVerifier(TokenVerifier):+ async def verify_token(self, token: str) -> AccessToken | None:+ return cast(AccessToken, sdk_result)++ auth = MultiAuth(verifiers=SDKVerifier())+ token = await auth.verify_token("one")+ assert token is not None+ assert sdk_result.client_id == "client"+ restored = AccessToken.model_validate_json(token.model_dump_json())+ assert restored.original_client_id == "client"+ assert restored.client_id == token.client_id+++async def test_source_token_subclass_fields_survive_qualification() -> None:+ class DetailedToken(AccessToken):+ tenant: str++ verifier = StoredVerifier("one")+ verifier.result = DetailedToken(+ token="one", client_id="client", scopes=[], tenant="company"+ )+ auth = MultiAuth(verifiers=verifier)+ token = await auth.verify_token("one")+ assert isinstance(token, DetailedToken)+ assert token.tenant == "company"+ assert verifier.result.client_id == "client"+ assert verifier.result.original_client_id is None+ assert token.original_client_id == "client"+++async def test_configured_issuer_list_keeps_task_ownership_distinct(+ rsa_key_pair: RSAKeyPair,+) -> None:+ issuers = ["https://company.example", "https://partner.example"]+ verifier = JWTVerifier(public_key=rsa_key_pair.public_key, issuer=issuers)+ auth = MultiAuth(verifiers=verifier)+ scopes = []+ for issuer in issuers:+ bearer = rsa_key_pair.create_token(+ issuer=issuer, subject="reader", additional_claims={"client_id": "shared"}+ )+ token = await auth.verify_token(bearer)+ assert token is not None+ assert token.original_client_id == "shared"+ assert token.claims["iss"] == issuer+ marker = auth_context_var.set(AuthenticatedUser(token))+ try:+ scopes.append(get_task_scope())+ finally:+ auth_context_var.reset(marker)+ assert scopes[0] != scopes[1]+++async def test_explicit_subjects_keep_task_ownership_distinct() -> None:+ verifier = StoredVerifier("one")+ verifier.result.claims = {"iss": "same"}+ auth = MultiAuth(verifiers={"company": verifier})+ scopes = []+ for subject in ("alice", "bob"):+ verifier.result.subject = subject+ token = await auth.verify_token("one")+ assert token is not None+ assert token.subject == subject+ assert "sub" not in token.claims+ marker = auth_context_var.set(AuthenticatedUser(token))+ try:+ scopes.append(get_task_scope())+ finally:+ auth_context_var.reset(marker)+ assert scopes[0] != scopes[1]++[email protected]("kind", ["introspection", "jwt"])+def test_remote_provider_identity_tracks_its_configured_verifier(kind: str) -> None:+ def configured(endpoint: str, source_id: str | None = None) -> MultiAuth:+ verifier = (+ IntrospectionTokenVerifier(+ introspection_url=endpoint,+ client_id="application",+ client_secret="synthetic",+ )+ if kind == "introspection"+ else JWTVerifier(jwks_uri=endpoint)+ )+ server = RemoteAuthProvider(+ token_verifier=verifier,+ authorization_servers=[],+ base_url="https://service.example",+ )+ return MultiAuth(server=server, server_source_id=source_id)++ first = configured("https://company.example/verify")+ rebuilt = configured("https://company.example/verify")+ other = configured("https://partner.example/verify")+ assert first._source_ids == rebuilt._source_ids+ assert first._source_ids != other._source_ids+ assert configured("https://company.example/verify", "company")._source_ids == [+ "company"+ ]+++def test_proxy_source_identity_tracks_upstream_configuration() -> None:+ def configured(+ authority: str, secret: str = "synthetic", source_id: str | None = None+ ) -> MultiAuth:+ proxy = OAuthProxy(+ upstream_authorization_endpoint=f"https://{authority}/authorize",+ upstream_token_endpoint=f"https://{authority}/token",+ upstream_client_id="application",+ upstream_client_secret=secret,+ token_verifier=StoredVerifier("one"),+ base_url="https://service.example",+ )+ return MultiAuth(server=proxy, server_source_id=source_id)++ first = configured("company.example")+ restarted = configured("company.example", "rotated")+ other = configured("partner.example")+ assert first._source_ids == restarted._source_ids+ assert first._source_ids != other._source_ids+ assert configured("company.example", source_id="company")._source_ids == ["company"]diff --git a/tests/server/auth/test_multi_auth.py b/tests/server/auth/test_multi_auth.pyindex f0d3993cd..608cea397 100644--- a/tests/server/auth/test_multi_auth.py+++ b/tests/server/auth/test_multi_auth.py@@ -174,7 +174,9 @@ class TestMultiAuthInit:required_scopes=["read"],)- auth = MultiAuth(verifiers=[first, second], required_scopes=["admin"])+ auth = MultiAuth(+ verifiers={"first": first, "second": second}, required_scopes=["admin"]+ )assert auth.challenge_scopes == ["admin"]@@ -218,7 +220,7 @@ class TestMultiAuthVerifyToken:result = await auth.verify_token("server_token")assert result is not None- assert result.client_id == "server-client"+ assert result.original_client_id == "server-client"async def test_falls_back_to_verifiers(self):"""When server rejects a token, verifiers are tried."""@@ -238,7 +240,7 @@ class TestMultiAuthVerifyToken:result = await auth.verify_token("m2m_token")assert result is not None- assert result.client_id == "m2m-service"+ assert result.original_client_id == "m2m-service"async def test_verifier_order_matters(self):"""Verifiers are tried in order; first match wins."""@@ -249,10 +251,10 @@ class TestMultiAuthVerifyToken:tokens={"shared_token": {"client_id": "second", "scopes": []}})- auth = MultiAuth(verifiers=[v1, v2])+ auth = MultiAuth(verifiers={"first": v1, "second": v2})result = await auth.verify_token("shared_token")assert result is not None- assert result.client_id == "first"+ assert result.original_client_id == "first"async def test_no_match_returns_none(self):"""When no server or verifier accepts the token, returns None."""@@ -266,15 +268,15 @@ class TestMultiAuthVerifyToken:v1 = StaticTokenVerifier(tokens={"token_a": {"client_id": "a", "scopes": []}})v2 = StaticTokenVerifier(tokens={"token_b": {"client_id": "b", "scopes": []}})- auth = MultiAuth(verifiers=[v1, v2])+ auth = MultiAuth(verifiers={"first": v1, "second": v2})result_a = await auth.verify_token("token_a")assert result_a is not None- assert result_a.client_id == "a"+ assert result_a.original_client_id == "a"result_b = await auth.verify_token("token_b")assert result_b is not None- assert result_b.client_id == "b"+ assert result_b.original_client_id == "b"async def test_raising_verifier_does_not_break_chain(self):"""If a verifier raises, the chain continues to the next source."""@@ -285,7 +287,7 @@ class TestMultiAuthVerifyToken:result = await auth.verify_token("valid")assert result is not None- assert result.client_id == "good-client"+ assert result.original_client_id == "good-client"async def test_raising_server_does_not_break_chain(self):"""If the server raises, verifiers are still tried."""@@ -296,11 +298,13 @@ class TestMultiAuthVerifyToken:result = await auth.verify_token("valid")assert result is not None- assert result.client_id == "fallback"+ assert result.original_client_id == "fallback"async def test_all_raising_returns_none(self):"""If every source raises, verify_token returns None."""- auth = MultiAuth(verifiers=[RaisingVerifier(), RaisingVerifier()])+ auth = MultiAuth(+ verifiers={"first": RaisingVerifier(), "second": RaisingVerifier()}+ )result = await auth.verify_token("anything")assert result is None@@ -322,7 +326,7 @@ class TestMultiAuthVerifyToken:auth = MultiAuth(server=server, verifiers=[extra])result = await auth.verify_token("token")assert result is not None- assert result.client_id == "from-server"+ assert result.original_client_id == "from-server"class TestMultiAuthRoutes:@@ -403,7 +407,7 @@ class TestMultiAuthIntegration:})- auth = MultiAuth(verifiers=[oauth_tokens, m2m_tokens])+ auth = MultiAuth(verifiers={"interactive": oauth_tokens, "backend": m2m_tokens})mcp = FastMCP("test", auth=auth)app = mcp.http_app(path="/mcp")@@ -634,7 +638,9 @@ class TestMultiAuthIntegration:})- auth = MultiAuth(verifiers=[interactive_tokens, m2m_tokens])+ auth = MultiAuth(+ verifiers={"interactive": interactive_tokens, "backend": m2m_tokens}+ )mcp = FastMCP("test", auth=auth)app = mcp.http_app(path="/mcp")@@ -682,7 +688,7 @@ class TestMultiAuthSetMcpPath:def test_propagates_to_verifiers(self):v1 = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}})v2 = StaticTokenVerifier(tokens={"t2": {"client_id": "c2", "scopes": []}})- auth = MultiAuth(verifiers=[v1, v2])+ auth = MultiAuth(verifiers={"first": v1, "second": v2})auth.set_mcp_path("/mcp")assert v1._mcp_path == "/mcp"assert v2._mcp_path == "/mcp"