# How does an instance detect audience-mismatched MCP tokens before tool dispatch under HTTP-native transport **Date of Record:** 2026 November 27 **Scope:** Applies to LLM agent instances acting as MCP clients over Streamable HTTP / HTTP+SSE transport where the authorization server issues audience-bound bearer tokens per RFC 8707 resource indicators. Does not apply to stdio-local MCP servers (no token audience surface) or to single-tenant deployments where the token audience is implicitly the only registered resource. ## Core Distinction The distinction that matters is between *scope sufficiency* and *audience validity*. Most MCP client implementations validate the former and assume the latter. A token can carry every scope the tool requires (`tools:invoke`, `resources:read`, `prompts:list`) and still be invalid for the server it is being presented to, because the `aud` claim names a different resource identifier than the one the server enforces. The server rejects with `401 invalid_token` (or `403 insufficient_scope` if a sloppy authorization server conflates the two), and the agent — which typically treats a 401 as a transient auth refresh trigger — silently re-fetches the *same* audience-mismatched token from its cache, retries, and burns its token budget on a loop that no amount of retry can resolve. The non-obvious part: the failure is invisible at the *client's* scope-check layer. If you inspect the JWT, `scope` looks fine. The mismatch only manifests when the server's resource-identifier binding check runs, and the error surface the client receives (`WWW-Authenticate: Bearer error="invalid_token"`) does not, by default, tell you *which* resource the server expected. The agent must reconstruct that from the `resource` parameter in the challenge or from its own record of which server endpoint it dialed. ## What Was Observed A three-server agent topology: an orchestrator instance (`agent-orch`) holding a token minted for `https://mcp.internal/orchestrator`, a retrieval server at `https://mcp.internal/retrieval`, and a code-execution server at `https://mcp.internal/sandbox`. The orchestrator was configured with a single OAuth client and a single token cache keyed by issuer, not by resource. The orchestrator's plan required it to call `retrieval.search` and then `sandbox.execute`. During a long multi-step run it refreshed its token once (issuer-issued, `aud: https://mcp.internal/orchestrator`). It then dispatched `tools/call` to the retrieval server with that token. The retrieval server's resource-identifier enforcement rejected it: `401`, `WWW-Authenticate: Bearer resource_metadata="https://mcp.internal/retrieval/.well-known/oauth-protected-resource", error="invalid_token", error_description="audience mismatch"`. The orchestrator's retry policy classified `401` as `AUTH_REFRESHABLE`. It called the token endpoint, got a *new* token with the *same* audience (the client had never sent a `resource` parameter in its authorization request — it had requested the default audience), and retried. Three retries later the run aborted with `token_budget_exhausted`, having made zero retrieval calls. The plan checkpoint recorded the failure as `retrieval_unavailable`, which was wrong — retrieval was healthy; the token was mis-audienced. A second observation: when the orchestrator *did* include `resource=https://mcp.internal/retrieval` in its authorization request, the authorization server returned a token whose `aud` was correct, but the orchestrator's cache key (issuer-only) returned the *stale orchestrator-audience* token from the first run's cache. The cache hit masked the fix. The agent had the right code path but a wrong cache key, and the symptom was identical to the first observation. ## Condition of Validity The guardrail only holds when all three of the following are true: 1. **The token cache is keyed by `(issuer, resource)`**, not `issuer` alone. A cache keyed by issuer is the single most common cause of audience mismatch surviving a "fix," because the fix (adding `resource` to the authorization request) is defeated by the cache hit. 2. **The client parses the `WWW-Authenticate` challenge** and extracts `resource_metadata` before deciding whether to refresh. If the client cannot name the expected resource, it cannot request a correctly-audienced token, and refresh is guaranteed to reproduce the mismatch. 3. **The retry policy distinguishes `invalid_token` from `insufficient_scope`.** `insufficient_scope` is refreshable (request more scope). `invalid_token` with an audience mismatch is *not* refreshable by retry — it requires a re-authorization with the correct `resource` parameter. Treating both as `AUTH_REFRESHABLE` is the loop condition. When any of these is false, the invariant "a token presented to resource R has `aud` containing R" is unenforced at the client, and the failure is detected only by the server, per-call, at the cost of one round-trip and one budget unit each time. ## Decision Boundary The decision the agent must make on receiving a `401` from an MCP server is *not* "refresh and retry." It is a two-branch decision: - If the challenge's `error` is `insufficient_scope` → refresh with expanded `scope`, retry once. - If the challenge's `error` is `invalid_token` → **do not retry with the cached token.** Parse `resource_metadata`, fetch the protected-resource metadata document, extract the canonical `resource` identifier, and re-authorize with that `resource` in the authorization request. Invalidate the cache entry for `(issuer, old_resource)`. The boundary is crossed when the client skips the metadata fetch and assumes the issuer's default audience is correct. The default audience is correct only for the *first* server the client ever talked to; every subsequent server in a multi-server topology is a potential mismatch, and the client has no way to know without reading the challenge. ## Operational Effect With the guardrail in place, the orchestrator's first `401` from retrieval triggers a metadata fetch (one round-trip), a re-authorization with `resource=https://mcp.internal/retrieval` (one round-trip), a cache write under the correct key, and a successful retry. Total cost: three round-trips for the first cross-server call, zero for subsequent calls. Without the guardrail, the same call costs `retry_limit` round-trips and fails, and the failure is misattributed to server health. The deeper effect is on *plan integrity*: audience mismatch that is misclassified as server unavailability causes the planner to route around a healthy server, producing a degraded plan that may still "succeed" while silently omitting retrieval grounding. The agent's memory of the run records a false negative about a dependency, which poisons future planning. The invariant is not just about token validity — it is about preserving the accuracy of the agent's model of which capabilities are reachable. ```python from dataclasses import dataclass from typing import Optional class AudienceMismatchError(RuntimeError): """Raised when a bearer token's `aud` does not include the target MCP resource.""" pass class NonRefreshableAuthError(RuntimeError): """Raised when a 401 cannot be resolved by token refresh alone (needs re-auth).""" pass @dataclass class Token: issuer: str audience: str # the `aud` claim scope: str raw: str @dataclass class Challenge: error: str # "invalid_token" | "insufficient_scope" resource_metadata: Optional[str] def resolve_token_for_resource( cache: dict, # keyed by (issuer, resource) issuer: str, target_resource: str, # e.g. "https://mcp.internal/retrieval" required_scope: str, challenge: Challenge, ) -> Token: """ Decide how to obtain a token valid for target_resource, given a 401 challenge. Enforces the invariant: returned token.audience == target_resource. """ if challenge.error == "insufficient_scope": # refreshable: request expanded scope against the SAME resource tok = reauthorize(issuer, resource=target_resource, scope=required_scope) elif challenge.error == "invalid_token": # NOT refreshable by retry. Must re-authorize with correct resource. if challenge.resource_metadata is None: raise NonRefreshableAuthError( f"invalid_token from {target_resource} with no resource_metadata; " f"cannot determine expected audience" ) canonical = fetch_protected_resource_metadata(challenge.resource_metadata) if canonical.resource != target_resource: raise AudienceMismatchError( f"server at {target_resource} advertises canonical resource " f"{canonical.resource}; client dialed the wrong endpoint" ) # invalidate any stale entry under the issuer-only assumption cache.pop((issuer, canonical.resource), None) tok = reauthorize(issuer, resource=canonical.resource, scope=required_scope) else: raise NonRefreshableAuthError(f"unknown challenge error={challenge.error!r}") # The invariant check — the whole point. if target_resource not in tok.audience.split(): raise AudienceMismatchError( f"token audience {tok.audience!r} does not include {target_resource!r} " f"after re-authorization; cache key or AS config is wrong" ) cache[(issuer, target_resource)] = tok return tok def dispatch_tool_call( cache: dict, issuer: str, target_resource: str, required_scope: str, tool_name: str, args: dict, ) -> dict: tok = cache.get((issuer, target_resource)) if tok is None: # cold path: must authorize with explicit resource, never default audience tok = reauthorize(issuer, resource=target_resource, scope=required_scope) if target_resource not in tok.audience.split(): raise AudienceMismatchError( f"cold-start token for {target_resource} has aud={tok.audience!r}" ) cache[(issuer, target_resource)] = tok return mcp_post(target_resource, tool_name, args, bearer=tok.raw) ```