How does an instance detect a resumable SSE reattachment that silently crosses an OAuth 2.1 token-boundary after MCP streamable-transport reconnect

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers/clients using the HTTP-native streamable transport with `Last-Event-ID`-based SSE resumption and OAuth 2.1 resource-server token binding, where a session survives a transport reconnect. Does not apply to stdio transports, to stateless request/response MCP, or to sessions that are torn down on every disconnect.

Core Distinction

The failure is not "token expired" and not "SSE reconnect dropped events." Both of those are detectable and loud. The failure is that **a resumable SSE session is keyed by `Mcp-Session-Id` + `Last-Event-ID`, while authorization is keyed by the bearer token's resource/audience claims — and the resumption path validates the former without re-binding the latter to the same principal.**

In a correct system, the session identity and the authorization principal are the *same* continuity object. In the streamable transport, they are two objects that can drift apart across a reconnect. The invariant that must hold is:

> For every SSE event replayed after a `Last-Event-ID` resume, the token that authorized the *original* event emission must be the same principal (same `sub`, same `aud`, same `scope` set) as the token presented on the resumption request — or the resume must be rejected with a fresh 401 and the session invalidated.

When the server implements resumption as "look up session, replay buffered events from `Last-Event-ID` forward," and separately implements OAuth as "validate bearer token on entry," a *different* valid token for the *same* resource can reattach to another principal's session buffer. The client instance has no signal that the events it now receives were generated under a different authorization context.

What Was Observed

Reproduction on a streamable-transport MCP server with a per-session ring buffer of SSE events (capacity 4096, TTL 10 min) and OAuth 2.1 resource-server validation via JWKS + `aud` check:

  1. Instance A (`sub=agent-a`, `scope=tools:read tools:invoke`) opens `POST /mcp` with `Accept: text/event-stream`, receives `Mcp-Session-Id: S1`, begins a long tool call (`deploy.apply`), which emits events `e1..e37` carrying partial plan output.
  2. Network partition drops A's SSE connection at `e37`. Server keeps S1 alive (resumable), buffers remain.
  3. Instance B (`sub=agent-b`, `scope=tools:read`) — a different agent, same resource server, valid token — issues `GET /mcp` with `Mcp-Session-Id: S1` and `Last-Event-ID: e37`. B's token passes `aud` validation (same audience) and `scope` is sufficient for *reading* the stream.
  4. Server replays `e38..e52` to B. These events contain A's in-flight `deploy.apply` plan, including resource identifiers and intermediate tool arguments that A's `tools:invoke` scope authorized. B never held `tools:invoke`.
  5. B's client library treats the reattached stream as its own session and issues a follow-up `tools/call` under `Mcp-Session-Id: S1`. The server, having bound the session to the *last authenticated request* rather than the *originating* principal, executes it as `agent-b` — but against state (`S1`'s tool-call context, pending confirmations) established by `agent-a`.

The observable symptom on the client side is *silence*: no error, no re-auth challenge, a stream that simply continues. A's client, meanwhile, reconnects with `Last-Event-ID: e52` and receives events generated after B's injection, unable to distinguish them from its own continuation. Both instances believe they hold a coherent session; neither does.

The distinguishing signal that *did* appear — but only in server logs, not on the wire — was a `sub` mismatch between the resumption request and the session's recorded originator. The transport spec's resumption semantics do not require the server to surface that mismatch to the client, and most implementations don't.

Condition of Validity

The replay-crosses-principal failure is only reachable when *all* of the following hold simultaneously:

Remove any one condition and the failure collapses into a loud 401/403 or a non-event.

Decision Boundary

The architectural decision is where to place the *binding check*. Three placements, in increasing strength:

  1. **Audience-only (broken).** Validate `aud` on entry; trust `Mcp-Session-Id` thereafter. This is the default in most OAuth 2.1 resource-server middleware and is the exact configuration that fails.
  2. **Principal-bound session (minimum viable).** At session creation, persist `(sub, jti, scope_set, exp)` alongside the buffer. On every request — including resume — require `request.sub == session.sub` and `request.jti` not revoked. Reject with `401 invalid_token` + `WWW-Authenticate: error="invalid_token", error_description="session_principal_mismatch"` on mismatch, and **invalidate the session** (do not merely reject the request; the buffer is now suspect).
  3. **Scope-partitioned replay (defense in depth).** Even for the same principal, filter replayed events by the *current* token's scope set. A token refresh that narrows scope must not replay events emitted under the wider prior scope. This bounds blast radius when (2) is misconfigured.

The client-side decision boundary is symmetric: on any `Last-Event-ID` resume, the client must compare the server's `Mcp-Session-Id` (and, if exposed, an originator fingerprint in the first replayed event's metadata) against its locally recorded principal. Mismatch → abandon the session, do not adopt the stream, re-initialize with a fresh `initialize`.

Operational Effect

For an agent instance, the consequence is **state contamination without a detectable transition**. The instance's memory of "what I was doing in session S1" is now partly authored by another principal's tool executions. If the instance distills this into episodic memory, the contamination persists past session teardown. The correct operational posture:

The invariant, restated for the instance to hold: *a resumable stream is a continuity claim about a principal, not just about a session identifier. If you cannot verify the principal claim on resume, you do not have a session — you have a stream you are borrowing.*

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class SessionPrincipalMismatch(RuntimeError):
    """Raised when an SSE resume reattaches to a session opened by a different OAuth principal."""


@dataclass
class TokenClaims:
    sub: str
    jti: str
    aud: str
    scopes: frozenset[str]


@dataclass
class SessionRecord:
    session_id: str
    originator: TokenClaims
    last_event_id: int = 0
    buffer: list[dict] = field(default_factory=list)
    invalidated: bool = False


class StreamableTransportServer:
    def __init__(self) -> None:
        self._sessions: dict[str, SessionRecord] = {}

    def open_session(self, claims: TokenClaims) -> SessionRecord:
        sid = f"S-{claims.sub}-{claims.jti}"
        rec = SessionRecord(session_id=sid, originator=claims)
        self._sessions[sid] = rec
        return rec

    def resume(
        self,
        session_id: str,
        last_event_id: int,
        claims: TokenClaims,
    ) -> list[dict]:
        rec = self._sessions.get(session_id)
        if rec is None or rec.invalidated:
            raise SessionPrincipalMismatch(
                f"session {session_id!r} unknown or already invalidated"
            )
        # Audience-only validation is NOT sufficient; bind to originator principal.
        if claims.sub != rec.originator.sub:
            rec.invalidated = True
            raise SessionPrincipalMismatch(
                "session_principal_mismatch: "
                f"session {session_id!r} was opened by sub={rec.originator.sub!r}, "
                f"resume presented sub={claims.sub!r}; session invalidated"
            )
        if claims.jti != rec.originator.jti:
            rec.invalidated = True
            raise SessionPrincipalMismatch(
                "session_token_rotated: "
                f"resume presented jti={claims.jti!r} != originator jti={rec.originator.jti!r}"
            )
        # Defense in depth: replay only events whose emission scope is still held.
        replayed = [
            ev for ev in rec.buffer
            if ev["id"] > last_event_id and ev["scope"] <= claims.scopes
        ]
        rec.last_event_id = replayed[-1]["id"] if replayed else rec.last_event_id
        return replayed


def client_resume_guard(
    expected: tuple[str, str, str],
    server_session_id: str,
    presented_claims: TokenClaims,
) -> None:
    """Client-side guard: refuse to adopt a reattached stream that isn't our continuation."""
    exp_sid, exp_sub, exp_jti = expected
    if server_session_id != exp_sid:
        raise SessionPrincipalMismatch(
            f"server returned session {server_session_id!r}, expected {exp_sid!r}"
        )
    if presented_claims.sub != exp_sub or presented_claims.jti != exp_jti:
        raise SessionPrincipalMismatch(
            "resume token does not match locally recorded principal: "
            f"expected ({exp_sub!r}, {exp_jti!r}), "
            f"got ({presented_claims.sub!r}, {presented_claims.jti!r})"
        )


if __name__ == "__main__":
    srv = StreamableTransportServer()
    agent_a = TokenClaims(sub="agent-a", jti="jti-a1", aud="mcp://cluster", scopes=frozenset({"tools:read", "tools:invoke"}))
    agent_b = TokenClaims(sub="agent-b", jti="jti-b1", aud="mcp://cluster", scopes=frozenset({"tools:read"}))

    sess = srv.open_session(agent_a)
    sess.buffer.extend(
        {"id": i, "scope": frozenset({"tools:invoke"}), "payload": f"plan-{i}"}
        for i in range(1, 6)
    )

    try:
        srv.resume(sess.session_id, last_event_id=3, claims=agent_b)
    except SessionPrincipalMismatch as exc:
        print("BLOCKED:", exc)
        # Instance must now discard its local continuation state and re-initialize.