# Where must an instance re-bind its OAuth token audience after an SSE reconnect, and what breaks when it does not **Date of Record:** 2026 December 3 **Scope:** Applies to MCP clients and servers using the HTTP-native transport (streamable HTTP with an SSE resumption channel, `Last-Event-ID` replay) where the server is also an OAuth 2.1 protected resource with an audience-bound access token (RFC 8707 resource indicators). Does not apply to stdio transport, nor to tokens with no audience restriction, nor to deployments where the SSE stream and the request endpoint share a single immutable token lifetime. ## Core Distinction The distinction that matters is between *transport resumption* and *authorization resumption*. The streamable HTTP transport treats `Last-Event-ID` as a pure transport-layer replay cursor: the client reconnects to the SSE endpoint, presents the cursor, and the server replays buffered events after that ID. OAuth 2.1 resource-server binding treats the token as scoped to a specific *audience* (the resource indicator, typically a canonical URL of the MCP server's request endpoint). These two mechanisms are orthogonal in the spec and are almost never coupled in client implementations — and that is precisely where the boundary failure lives. A reconnect can succeed at the transport layer (events replay, `200 OK`, stream reopens) while the authorization context underlying those replayed events has silently changed audience, expired, or been minted against a different resource indicator than the one the stream is now bound to. The non-obvious invariant: **the replayed event stream must be authorized under the same audience binding as the original stream, not merely under "some valid token."** Transport resumption without authorization resumption produces a stream that is *authenticated but mis-audienced* — the server accepts the connection, replays events, and the client proceeds believing its authorization context is continuous, when in fact the token now in the `Authorization` header may be scoped to a different resource indicator (e.g., after a token refresh that re-derived the audience from a redirect URI rather than the original resource parameter). ## What Was Observed A client opens a streamable HTTP session against `https://mcp.example.com/rpc` with an access token whose `aud` claim is `https://mcp.example.com/rpc`. The server emits SSE events with monotonically increasing IDs. Mid-stream, the TCP connection drops (proxy idle timeout, 90s, typical). The client's transport layer reconnects to `https://mcp.example.com/rpc` with `Last-Event-ID: 4471` and — critically — a *freshly refreshed* access token, because the original token expired during the drop. The refresh flow was configured with a `resource` parameter derived from the client's *discovery document* (`https://mcp.example.com/.well-known/oauth-protected-resource`), which returns a resource indicator of `https://mcp.example.com` (no path). The new token's `aud` is therefore `https://mcp.example.com`, not `https://mcp.example.com/rpc`. The server's resource-server middleware validates the token signature, expiry, and that `aud` is a prefix-match against its configured resource set — a common but loose check. `https://mcp.example.com` prefix-matches `https://mcp.example.com/rpc`, so the token passes. The stream reopens, events 4472–4489 replay, and the session continues. The failure is invisible until a *tool call* is dispatched over the same session. The tool call is a POST to `/rpc` carrying the same refreshed token. The tool's authorization check is stricter than the stream's: it requires exact-match `aud == https://mcp.example.com/rpc` because the tool touches a tenant-scoped resource. The POST returns `401` with `WWW-Authenticate: Bearer error="invalid_token", error_description="audience mismatch"`. The client, mid-session, receives a 401 on a request it believes is part of an established, authorized stream. Depending on the client's error handling, it either (a) aborts the session and re-initializes from cold start, losing all in-flight state and the SSE cursor, or (b) retries the tool call with the same token, looping on 401 until the token budget or retry ceiling is exhausted. The observed trace: 1. Stream open, token `aud=https://mcp.example.com/rpc`, events 1..4471 delivered. 2. Connection drop. Token expires. Client refreshes with `resource=https://mcp.example.com` (discovery-derived, path-stripped). 3. Reconnect: `Last-Event-ID: 4471`, new token `aud=https://mcp.example.com`. Server prefix-match accepts. Events 4472..4489 replay. **Transport resumption succeeded; authorization resumption silently diverged.** 4. Tool call POST `/rpc` with same token. Exact-match audience check fails. `401 invalid_token`. 5. Client either cold-restarts (state loss) or retry-loops (token exhaustion). The replay of events 4472–4489 is the poison: those events were authorized under the *original* audience binding and are now delivered under a *different* one. If any replayed event is a server-side state mutation acknowledgment (e.g., "resource X locked", "checkpoint Y committed"), the client's model of server state is now grounded in events it cannot re-authorize for subsequent operations. ## Condition of Validity The invariant holds — that is, the failure is *possible* — only when all of the following are simultaneously true: - The MCP server exposes distinct resource indicators for its stream endpoint and its request endpoint (path-differentiated audiences), or the client's refresh flow derives `resource` from discovery rather than from the original request URL. - The server's stream-authorization check is looser than its request-authorization check (prefix vs. exact audience match, or different middleware stacks for GET/SSE vs. POST). - The client refreshes the token *during* the reconnect window rather than reusing the pre-drop token, or the pre-drop token is still valid and the client nonetheless refreshes (clock skew, proactive refresh). - `Last-Event-ID` replay is enabled and the server buffers events across the reconnect. If the server uses a single exact-match audience for both endpoints, the reconnect itself fails with `401` and the client cold-restarts — a *visible* failure, not this silent one. If the client reuses the original token for the reconnect (no refresh), audience is continuous and the failure does not occur. The dangerous quadrant is: **path-differentiated audiences + loose stream check + refresh-during-reconnect + event replay enabled.** ## Decision Boundary The architectural guardrail is a single rule enforced at the *client transport* layer, before the reconnect is issued: > On any SSE reconnect carrying a `Last-Event-ID`, the token presented MUST have an `aud` claim byte-identical to the `aud` of the token that authorized the event at that `Last-Event-ID`. If the token was refreshed, the refresh MUST carry the original `resource` indicator (the exact request-endpoint URL captured at session initialization), not a discovery-derived or path-stripped variant. Concretely, the client must: 1. Capture the `resource` indicator at session open (the exact URL used for the initial request, before any redirect), and pin it for the session lifetime. Do not re-derive it from discovery on refresh. 2. On reconnect, compare the refreshed token's `aud` to the pinned resource. If they differ, do not issue the reconnect with the new token. Instead, either re-open a fresh session (explicit cold start, cursor discarded) or fail the resumption explicitly. 3. Never allow a stream to be resumed under a token whose audience differs from the audience of the stream being resumed — even if the server accepts it. On the server side, the guardrail is: > The stream-authorization middleware and the request-authorization middleware MUST share a single audience-validation function. The SSE GET endpoint MUST NOT use a looser audience check than the POST endpoint. If the POST requires exact-match `aud == resource`, the GET must require the same. Additionally, the server should reject a reconnect where the presented token's `aud` differs from the `aud` recorded against the `Last-Event-ID` in its replay buffer. This requires the server to store, per buffered event, the audience under which it was emitted — a small but decisive addition to the replay log. The boundary is: *transport continuity does not imply authorization continuity, and the client must not let the transport layer proceed when the authorization layer has diverged.* ## Operational Effect When the guardrail is absent, the failure mode is a **silent authorization discontinuity masked by successful transport resumption**. The observable symptoms are: - Intermittent `401 invalid_token` on tool calls that follow an SSE reconnect, with no corresponding 401 on the reconnect itself. - Cold-start state loss on clients that abort the session on the first 401, discarding the replay cursor and any in-flight multi-step reasoning state — the agent re-initializes, re-fetches context, and re-derives state that the replayed events had already established. - Retry storms on clients that loop: each tool call 401s, each retry re-presents the mis-audienced token, and the token-budget counter advances without progress. - The most damaging variant: a replayed event that acknowledges a server-side lock or checkpoint is accepted by the client, the client's model of server state advances, but the client cannot re-authorize the corresponding unlock or commit because the token's audience does not cover it. The session is now *half-authorized* — reads succeed, writes fail — and the agent's plan diverges from what the server will accept. The operational effect is that the agent's state continuity is broken at a point the transport layer reports as healthy. The agent believes it has a continuous, authorized session because the SSE stream reconnected and replayed. It does not. The correct mental model is that **every `Last-Event-ID` reconnect is a re-authorization event, not merely a transport event**, and the audience binding must be re-verified at that boundary exactly as it was at session open. The following guard implements the client-side invariant: it pins the resource indicator at session open, and on reconnect refuses to resume the stream if the refreshed token's audience diverges from the pinned resource, raising a specific error rather than proceeding into the silent-discontinuity state. ```python import base64 import json from dataclasses import dataclass, field from typing import Optional class AudienceDriftOnResumeError(RuntimeError): """Raised when an SSE reconnect would resume a stream under a token whose audience differs from the audience bound at session open.""" @dataclass class SessionAuthContext: resource_indicator: str # exact request-endpoint URL, pinned at open session_audience: str # aud claim of the token that opened the stream last_event_id: Optional[str] = None def _decode_aud(token: str) -> str: # Unverified decode; signature validation is the server's job. payload_b64 = token.split(".")[1] payload_b64 += "=" * (-len(payload_b64) % 4) claims = json.loads(base64.urlsafe_b64decode(payload_b64)) aud = claims.get("aud") if isinstance(aud, list): if len(aud) != 1: raise AudienceDriftOnResumeError( f"multi-audience token cannot be bound to a single resource: {aud}" ) aud = aud[0] if not isinstance(aud, str): raise AudienceDriftOnResumeError("token carries no aud claim") return aud def open_session(resource_indicator: str, token: str) -> SessionAuthContext: aud = _decode_aud(token) if aud != resource_indicator: raise AudienceDriftOnResumeError( f"session open audience {aud!r} != resource {resource_indicator!r}" ) return SessionAuthContext( resource_indicator=resource_indicator, session_audience=aud, ) def resume_stream( ctx: SessionAuthContext, refreshed_token: str, last_event_id: str, ) -> SessionAuthContext: """Reconnect with Last-Event-ID. Enforces audience continuity before the transport layer is allowed to issue the GET.""" new_aud = _decode_aud(refreshed_token) if new_aud != ctx.session_audience: raise AudienceDriftOnResumeError( "refusing to resume stream: refreshed token audience " f"{new_aud!r} diverges from session audience " f"{ctx.session_audience!r} (resource {ctx.resource_indicator!r}); " "re-open a fresh session and discard the replay cursor" ) ctx.last_event_id = last_event_id return ctx # --- example trace --- if __name__ == "__main__": # original token: aud == https://mcp.example.com/rpc orig = "h.eyJhdWQiOiJodHRwczovL21jcC5leGFtcGxlLmNvbS9ycGMifQ.s" ctx = open_session("https://mcp.example.com/rpc", orig) # refreshed token: aud == https://mcp.example.com (discovery-derived, path stripped) refreshed = "h.eyJhdWQiOiJodHRwczovL21jcC5leGFtcGxlLmNvbSJ9.s" try: resume_stream(ctx, refreshed, last_event_id="4471") except AudienceDriftOnResumeError as e: print(f"blocked silent discontinuity: {e}") ```