# Why does an instance lose tool-call continuity when an MCP Streamable HTTP SSE stream resumes under a rotated OAuth 2.1 access token? **Date of Record:** 2026 November 28 **Scope:** Applies to MCP servers implementing the Streamable HTTP transport with `Last-Event-ID` SSE resumption and OAuth 2.1 resource-server binding (RFC 8707 audience-bound tokens, RFC 6750 bearer presentation). Does not apply to stdio transport, nor to SSE streams resumed within a single token lifetime where no `401` re-challenge occurs mid-stream. ## Core Distinction The failure is not token expiry, and it is not SSE reconnect in isolation. It is the *interaction*: the MCP spec requires that a client resuming a stream present `Last-Event-ID`, and the OAuth 2.1 resource-server binding requires that every request carry a token whose `aud` claim equals the resource server identifier and whose `exp` has not passed. When a long-running tool invocation (e.g., a 90-second retrieval or code-execution call) outlives the access token, the transport layer re-challenges with `401`, the client refreshes, and the resumption request now arrives with a *new* token but the *old* `Last-Event-ID`. The server must decide whether the event-ID namespace is scoped to the token, the session, or the stream. If it is scoped to the token — the natural implementation when auth middleware keys the event store by bearer identity — the `Last-Event-ID` is unknown to the new token's store, and the server silently replays from the beginning of the *new* store (empty), emitting zero events and closing the stream. The client interprets an empty resumed stream as "invocation complete with no further output," and the tool result is lost. The agent proceeds with a `null` tool result and continues reasoning on a hole. The distinction that matters: **event-ID continuity is an authorization-scoped resource, not a transport-scoped one.** Most implementations treat `Last-Event-ID` as a transport cursor. Under OAuth 2.1 resource binding it is also an authorization artifact, and rotating the token silently rebinds it. ## What Was Observed A retrieval tool on an MCP server (`streamable-http`, `Mcp-Session-Id` issued at `initialize`) was invoked by an agent with a 60-second access token (short-lived by design for a sensitive corpus). The tool streamed 40 progress events over 74 seconds. At t≈61s the token expired. The transport emitted: ``` event: message data: {"jsonrpc":"2.0","method":"notifications/progress","params":{...}} id: evt-0031 HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer resource_metadata="https://mcp.example/.well-known/oauth-protected-resource" ``` The client's OAuth 2.1 flow performed a refresh, obtained a token with the same `aud` but new `jti` and `exp`, and reconnected: ``` GET /mcp HTTP/1.1 Authorization: Bearer Mcp-Session-Id: sess-7f2a Last-Event-ID: evt-0031 Accept: text/event-stream ``` The server's event store was keyed by `(session_id, token_jti)` — a defensible choice, since events may contain data the resource server wants to bind to the presenting principal. `evt-0031` did not exist under the new `jti`. The server, per its "unknown event ID ⇒ start fresh" branch, returned `200` with an empty stream and closed it after the keepalive interval. The client's SSE reader saw `onclose` with no `error` event and no terminal `result` message. Its state machine classified the stream as *completed*. The agent's tool-call record was finalized with `result: null`. Downstream, the agent's reasoning step received `{"content":[],"isError":false}` (the empty-content success shape) and continued, treating "the retrieval returned nothing" as evidence. Three subsequent tool calls were conditioned on that false premise. The failure was not visible in any single log line: the client logged `stream closed`, the server logged `401 → 200`, and the agent logged `tool call completed`. ## Condition of Validity The invariant holds — and the failure is reachable — only when all of the following are simultaneously true: 1. **The tool invocation lifetime exceeds the access token lifetime.** This is the trigger. If token TTL > max tool duration, no mid-stream re-challenge occurs and the event-ID namespace never rebinds. 2. **The server's event store is keyed by any authorization attribute** (`jti`, token hash, `sub`, scope set) rather than by `(session_id, stream_id)` alone. This is the implementation choice that converts a token refresh into an event-ID miss. 3. **The client treats `200` + empty stream + close as terminal success.** Per the MCP Streamable HTTP spec, a server *may* close a stream at any time and the client *should* reconnect with `Last-Event-ID`; but a client that does not distinguish "closed with pending request unanswered" from "closed after terminal response" will misclassify. 4. **The tool result is not independently retrievable.** If the tool also writes its result to a `resources/read`-addressable location, the agent can recover. If the only delivery channel is the SSE stream, the result is gone. Any one of these being false bounds the failure. The dangerous configuration is the one that looks most secure: short tokens (good) + per-token event stores (defensible) + streaming-only result delivery (common). ## Decision Boundary The architect must choose, explicitly, where the event-ID namespace lives. Three options, with distinct consequences: - **Namespace by session, authorize by current token.** Event store keyed by `Mcp-Session-Id`; every resumption request re-validates the *presenting* token's `aud` and scope against the session's recorded authorization context at `initialize`. Resumption across token rotation succeeds. Requires the session record to carry the original authorization decision and the server to enforce that the new token is not *weaker* (scope subset check). This is the correct default for tool invocations that outlive tokens. - **Namespace by token, forbid mid-stream rotation.** Event store keyed by token; on `401`, the server *must* terminate the stream with an explicit terminal error event (`isError: true`, `"token_expired_mid_stream"`) rather than a clean close, and the client *must* treat resumption under a different token as a new invocation requiring re-issue. Preserves strict per-principal isolation at the cost of losing in-flight work. - **Namespace by token, replay across rotation.** Event store keyed by token but resumption requests carry a signed `Mcp-Session-Id` binding that the server uses to look up the *prior* token's store, re-authorizing the read against the new token's scope. Correct only if the new token's scope is a superset of the events' required scope; otherwise it is a confused-deputy vulnerability. The boundary is: **if the tool can outlive the token, the event-ID namespace cannot be the token, unless the transport carries an explicit mid-stream expiration signal that both ends honor.** Silent close is never a valid boundary behavior. ## Operational Effect The observable effect is a *silent null tool result* that the agent's reasoning layer cannot distinguish from a legitimate empty result. Error compounding proceeds from there: the agent's next step conditions on absence-of-evidence as evidence-of-absence. In retrieval agents this manifests as "the corpus does not contain X" when in fact the stream was severed; in code-execution agents as "the command produced no output" when the command was still running server-side. The guardrail is a three-part invariant, enforced at the transport layer, not the agent layer: 1. **Terminal-response invariant.** Every MCP request that opens a stream must be answered by exactly one terminal JSON-RPC message (`result` or `error`) *or* an explicit transport error event. A stream close without a terminal message is a protocol violation, not a completion. Clients must map `close-without-terminal` to a retryable error, never to success. 2. **Resumption authorization invariant.** A resumption request with `Last-Event-ID` must be authorized against the *session's* authorization context, and the presenting token must satisfy `scope(new) ⊇ scope(events_pending)`. The event store must be keyed by `Mcp-Session-Id`, not by token identity. 3. **Mid-stream expiration invariant.** If the server cannot honor resumption (namespace mismatch, scope downgrade), it must emit a terminal `error` event with a machine-readable code before closing, so the client's state machine has a defined transition. The agent-layer consequence: an agent that receives `isError: false` with empty content must treat it as *indeterminate*, not *negative*, unless the tool's schema declares empty-content as a valid terminal success. That distinction belongs in the tool schema (`"emptyIsSuccess": false`), and the agent's loop must branch on it. ```python class StreamResumptionAuthMismatch(RuntimeError): """Raised when an SSE resumption request cannot be authorized against the session's original authorization context, or when a stream closes without a terminal JSON-RPC message.""" pass def resume_stream( session_id: str, last_event_id: str, presenting_token: dict, session_store: dict, event_store: dict, ) -> list: """ Resume an MCP Streamable HTTP SSE stream. presenting_token: decoded claims of the bearer token on the resumption request. session_store: session_id -> {"aud", "scope", "stream_id", "authorization_context"} event_store: (session_id, stream_id) -> list of events with monotonic ids. Invariant: event-ID namespace is the session, not the token. """ session = session_store.get(session_id) if session is None: raise StreamResumptionAuthMismatch( f"unknown session {session_id!r}; cannot resume across token rotation" ) # 1. Audience binding: the presenting token must target this resource server. if presenting_token.get("aud") != session["aud"]: raise StreamResumptionAuthMismatch( f"aud mismatch on resumption: token aud={presenting_token.get('aud')!r} " f"!= session aud={session['aud']!r}" ) # 2. Scope monotonicity: the new token must not be weaker than the session's # original authorization, or pending events become a confused deputy. new_scope = set(presenting_token.get("scope", "").split()) original_scope = set(session["scope"].split()) if not original_scope.issubset(new_scope): raise StreamResumptionAuthMismatch( f"scope downgrade on resumption: original={sorted(original_scope)} " f"new={sorted(new_scope)}; refusing to replay pending events" ) # 3. Event-ID lookup must be session-scoped, not token-scoped. stream = event_store.get((session_id, session["stream_id"])) if stream is None: raise StreamResumptionAuthMismatch( f"no event stream for session={session_id!r} stream={session['stream_id']!r}" ) pending = [e for e in stream if e["id"] > last_event_id] if not pending and not session.get("terminal_emitted"): raise StreamResumptionAuthMismatch( f"resumption at {last_event_id!r} yields no pending events and no terminal " f"message was emitted; stream close would be misread as success" ) return pending def close_stream(session: dict, terminal_emitted: bool) -> None: """Enforce the terminal-response invariant at stream close.""" if not terminal_emitted: raise StreamResumptionAuthMismatch( "stream closed without terminal JSON-RPC result/error; " "client must map this to a retryable transport error, not success" ) ```