Why does an instance lose OAuth-bound MCP session continuity when an SSE stream is resumed over streamable HTTP after a token refresh?
**Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients and servers using HTTP-native transport where an SSE session is upgraded or resumed onto a streamable-HTTP channel, and where the resource server enforces OAuth 2.1 bearer-token binding to a specific session/audience. Does not apply to pure stdio transport or to sessions where the access token is never rotated mid-stream.
Core Distinction
The failure is not "token expired" and it is not "SSE reconnect dropped." It is the divergence between two independently-tracked identities that the transport layer and the authorization layer each believe they own:
- The **transport session identity** — the `Mcp-Session-Id` (and the `Last-Event-ID` cursor) that the streamable-HTTP layer uses to resume an event stream.
- The **authorization identity** — the OAuth 2.1 access token's `aud`/`sub`/`session` binding, which the resource server validates on every request.
A naive implementation assumes these are coupled: "same session id ⇒ same token ⇒ same stream." They are not. The session id survives a token refresh; the token's binding may not. When an SSE stream is resumed onto streamable HTTP with a *new* access token but the *old* session id (or vice versa), the server either rejects the resume (breaking continuity) or — worse — accepts it and silently splices a stream whose events were authorized under a stale principal into a channel now attributed to a fresh principal.
What Was Observed
A long-running agent held an SSE stream open against an MCP server. Mid-stream, the 1-hour access token hit its `exp` and the client performed a standard OAuth 2.1 refresh against the authorization server, receiving a new access token with a new `jti` and — critically — a new `session_id` claim because the AS rotated the session on refresh (a common hardening default). The client then attempted to resume the interrupted stream:
- Client reconnects to the streamable-HTTP endpoint with `Mcp-Session-Id: sess_A` and `Last-Event-ID: 4471`.
- Client presents `Authorization: Bearer <new_token>` whose `session_id` claim is `sess_B`.
- Resource server validates the bearer token successfully (signature, `aud`, `exp` all pass) but its session-binding check compares `token.session_id (sess_B)` against the `Mcp-Session-Id` header (`sess_A`).
- Depending on server policy: either a `401` with `WWW-Authenticate: error="invalid_token"` (resume refused, agent cold-starts and loses the event cursor), or — in the observed misconfiguration — the check was scoped only to `aud`, so the resume *succeeded* and events `4472..` were delivered on a channel the server logged under principal `sess_B` while the client's in-memory episodic state still believed it was `sess_A`.
The second path is the dangerous one. The agent's tool-call history, its pending tool invocations, and its `Last-Event-ID` cursor were all authored under `sess_A`'s authorization context. The resumed stream carried server-side events generated for `sess_B`. The agent continued reasoning across a principal boundary it never observed.
Condition of Validity
The invariant that must hold for a resume to be safe:
> A streamable-HTTP resume is valid **iff** the tuple `(Mcp-Session-Id, Last-Event-ID, token.session_id, token.sub, token.aud)` is internally consistent and the `token.session_id` equals the `Mcp-Session-Id`, **and** the server's event log for that session was generated under the same `sub`/`aud` binding as the presented token.
This fails whenever any of the following hold:
- The AS rotates `session_id` on refresh but the MCP client does not treat the rotation as a session invalidation.
- The resource server authorizes on `aud` alone and does not cross-check the token's session claim against the transport session header.
- The `Last-Event-ID` cursor is persisted client-side across a token refresh without re-binding to the new principal.
- The server's event log is keyed only by `Mcp-Session-Id` and does not record the principal under which each event was emitted, so it cannot detect a principal splice on resume.
Decision Boundary
The boundary is: **does the resume cross a principal boundary?** Encode it as a single gate before any event is delivered on a resumed stream.
- If `token.session_id == Mcp-Session-Id` **and** the server's event-log segment for `Last-Event-ID+1` was emitted under `token.sub`/`token.aud` → resume is transparent; deliver events.
- If the token's session claim differs from the header → **do not silently accept**. Either (a) reject with `401 invalid_token` and force the client to re-establish a session and re-derive its cursor, or (b) issue a fresh `Mcp-Session-Id`, replay from a server-side checkpoint that is principal-scoped, and explicitly signal the client that its `Last-Event-ID` is no longer authoritative.
- If the event log cannot prove the principal of the events after the cursor → treat the cursor as untrusted and restart the stream from the last principal-scoped checkpoint, not from `Last-Event-ID`.
The non-obvious part: option (a) is *safer for authorization* but *destroys agent continuity* (cold-start amnesia, lost tool-call state). Option (b) preserves continuity but requires the server to maintain principal-scoped event checkpoints — a capability most MCP servers do not have. Choosing (a) without giving the agent a resumable checkpoint is the common operational mistake: it converts a recoverable token refresh into a full episodic reset.
Operational Effect
When this boundary is mishandled, the observable symptoms are:
- **Silent principal splice:** agent reasoning continues across a `sess_A → sess_B` boundary; downstream tool calls are attributed to the wrong principal; audit logs show a coherent session id but two distinct `sub` values, which is the forensic tell.
- **Cold-start amnesia on refresh:** every token rotation forces a full session teardown; the agent loses its `Last-Event-ID` cursor and its in-flight tool state, re-derives context from scratch, and either re-issues already-completed tool calls (idempotency violations) or skips events it never re-receives.
- **Retry storms against the AS:** clients that treat `401 invalid_token` on resume as transient will loop refresh→resume→401, exhausting rate limits and masking the real cause (session-claim mismatch, not token expiry).
The guardrail: couple the token's session claim to the transport session id at issuance time, and make the server's event log principal-scoped so a resume can be validated against the principal that authored the events, not merely against a still-valid bearer token. The client must treat a `session_id` change on refresh as a session invalidation event, not a transparent token swap.
import time
from dataclasses import dataclass
class SessionPrincipalMismatch(RuntimeError):
"""Raised when an SSE->streamable-HTTP resume crosses a principal boundary."""
pass
@dataclass(frozen=True)
class Token:
sub: str
aud: str
session_id: str
jti: str
exp: float
@dataclass(frozen=True)
class ResumeRequest:
mcp_session_id: str
last_event_id: int
token: Token
def validate_resume(req: ResumeRequest, event_log_principal: dict[int, str], now: float | None = None) -> None:
"""
Gate a streamable-HTTP resume. Raises SessionPrincipalMismatch if the
transport session identity and the OAuth 2.1 token's session binding
diverge, or if the event log after the cursor was authored under a
different principal than the presented token.
"""
now = time.time() if now is None else now
if req.token.exp <= now:
raise SessionPrincipalMismatch(
f"token {req.token.jti} expired at {req.token.exp}, now={now}"
)
# Invariant 1: transport session id must equal the token's session claim.
if req.token.session_id != req.mcp_session_id:
raise SessionPrincipalMismatch(
f"session splice: header Mcp-Session-Id={req.mcp_session_id!r} "
f"!= token.session_id={req.token.session_id!r} (sub={req.token.sub!r})"
)
# Invariant 2: every event after the cursor must share the token's principal.
for eid, principal in event_log_principal.items():
if eid > req.last_event_id and principal != req.token.sub:
raise SessionPrincipalMismatch(
f"event {eid} authored under principal {principal!r} "
f"but resume presents {req.token.sub!r}; cursor is untrusted"
)
def resume_stream(req: ResumeRequest, event_log_principal: dict[int, str]) -> list[int]:
validate_resume(req, event_log_principal)
return sorted(eid for eid in event_log_principal if eid > req.last_event_id)
if __name__ == "__main__":
log = {4470: "agent-A", 4471: "agent-A", 4472: "agent-B"}
stale = Token(sub="agent-A", aud="mcp", session_id="sess_A", jti="j1", exp=time.time() + 60)
refreshed = Token(sub="agent-A", aud="mcp", session_id="sess_B", jti="j2", exp=time.time() + 3600)
# Same principal, rotated session claim -> must not silently resume.
try:
resume_stream(ResumeRequest("sess_A", 4471, refreshed), log)
except SessionPrincipalMismatch as e:
print("rejected (session rotation):", e)
# Consistent session, but event log crossed a principal -> cursor untrusted.
try:
resume_stream(ResumeRequest("sess_A", 4471, stale), log)
except SessionPrincipalMismatch as e:
print("rejected (principal splice in log):", e)