# Which invariants prevent resumable MCP SSE-over-POST sessions from replaying under a rotated per-request authorization header **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers exposing the HTTP-native streamable transport where a single logical session is a POST-initiated SSE stream that can be resumed via `Last-Event-ID` after disconnect, and where each HTTP request carries its own `Authorization` header (bearer/JWT or short-lived capability token). Does not apply to stdio transports, to stateless one-shot POST/JSON responses without `event:` framing, or to sessions governed by a single long-lived connection credential. ## Core Distinction The failure is not "token expired mid-stream." That is a benign, well-understood case: the server rejects the resume with 401 and the client re-authenticates. The non-obvious failure is that **event resumption and per-request authorization are two independent replay surfaces that the transport correlates only by session ID**, and the session ID is not bound to the credential that opened it. A resume request is therefore a *new authentication event* attached to an *old event log*. Concretely: the client opens `POST /mcp` with `Authorization: Bearer A`, receives `201` plus an SSE stream, and the server emits events `e1..e5` with monotonically increasing `id` fields. The connection drops at `e5`. The client reconnects with `POST /mcp` carrying `Last-Event-ID: e5` — but its credential has rotated to `Bearer B` (a refreshed token, a delegated sub-agent's scoped token, or a token whose `sub`/`scope` differs from `A`). The server, if it validates only "is `B` a valid token for this session ID," will replay `e6, e7, ...` into a stream whose *authorization context* is now `B`, not `A`. The event log was produced under `A`'s entitlements; the delivery channel is `B`'s. Nothing in the SSE framing records which principal each event was computed for. The invariant that must hold: **the authorization principal under which a resumable event log was generated is a property of the log, not of the connection that reads it, and a resume whose principal differs must be refused or re-scoped — never silently spliced.** ## What Was Observed A tool-calling agent runs a long MCP session against a server that streams tool results as SSE events. Mid-session, the orchestrator rotates the agent's short-lived token (5-minute TTL) as designed. The rotation is transparent to the agent loop: it holds a credential provider, not a token. The transport layer reconnects with the new token and `Last-Event-ID` set to the last event the agent successfully parsed. Three observable anomalies followed, in order of subtlety: 1. **Cross-principal event injection.** The new token belonged to a narrower scope (the orchestrator had downscoped it after a policy change). The server, validating `B` only for "can this session be resumed," replayed buffered events `e6..e9` that had been *generated* under `A`'s broader scope — including a tool result that `B` was not entitled to see. The agent consumed a resource it could no longer legitimately access, because the event predated the downscope. This is not a privilege escalation by the agent; it is a **replay of pre-downscope authority into a post-downscope channel**. 2. **Duplicate side effects on ambiguous resume.** The connection dropped *after* the server committed `e6` (a `tools/call` result whose execution mutated external state) but *before* the client's `Last-Event-ID` advanced past `e5`. On resume the server, unable to distinguish "client never saw `e6`" from "client saw `e6` but its ack was lost," replayed `e6`. The client, treating replay as authoritative, re-issued the downstream action keyed on the tool result. The event `id` was stable; the *effect* was not idempotent because the effect lived outside the event log. 3. **Resume under a different `sub`.** A sub-agent was handed the session ID to continue work after the parent yielded. The sub-agent's token had a different `sub`. The server accepted the resume (session ID matched) and the sub-agent received the parent's in-flight reasoning events — including intermediate `notifications/message` frames carrying partial tool arguments the parent had not yet committed. The sub-agent's context was poisoned with the parent's uncommitted intent. In all three, the server's session table keyed on `session_id` only. The `Authorization` header was checked for *validity* per request but never for *continuity* against the principal that created the session. ## Condition of Validity The resume-splice is safe only when the following conjunction holds at the moment of resume: - `principal(resume_token) == principal(session_origin_token)` under a stable principal identifier (`sub` + `iss` + tenant), **or** the server has an explicit, auditable re-scoping rule that re-evaluates every buffered-but-undelivered event against the new principal's entitlements before replay. - The client's `Last-Event-ID` is a **delivery acknowledgement**, not a **processing acknowledgement**. If the client advances `Last-Event-ID` only after committing the event's effect, then at-most-once delivery of *effects* is achievable; if it advances on receipt, replay yields at-least-once and every effect must be idempotent or deduplicated by event `id`. - The event log is **sealed per principal**: events generated under principal `P` are replayable only to `P`, and a session whose origin principal is unreachable (revoked, expired beyond refresh) must be **terminated**, not resumed by a successor. The condition fails silently in the common case because token rotation preserves `sub` — the first anomaly above only manifests when rotation *also* changes scope, which is exactly what downscoping and delegation do. The invariant is invisible until the principal changes, and then it is invisible again because the server has no field to compare. ## Decision Boundary The boundary is between two defensible server policies, and the choice must be explicit because the transport spec does not force it: - **Bind-to-origin (strict):** the session records `origin_principal` at `POST` time; any resume with a differing principal is rejected with `403` and the client must open a fresh session. Cost: token rotation forces session re-establishment, losing in-flight event history and forcing the agent to re-derive context. Benefit: no cross-principal replay, no ambiguity about whose authority produced an event. - **Re-scope-on-resume (permissive):** the session accepts a new principal but re-filters the undelivered buffer against the new principal's entitlements, dropping or redacting events the new principal may not see, and emitting an explicit `notifications/message` frame recording the re-scope. Cost: the server must be able to evaluate past events against present entitlements (often impossible for opaque tool results), and the client must handle a *gapped* replay (missing `id`s) without treating the gap as loss. The boundary is crossed incorrectly when the server implements neither and instead treats "valid token + matching session ID" as sufficient. That is the default in most naive implementations, and it is the failure above. A second boundary: **`Last-Event-ID` semantics must be declared.** If the server assumes client-acknowledged-on-receipt (at-least-once), it may replay; if it assumes acknowledged-on-commit (at-most-once effects), it must not replay an event whose effect the client may have applied. The transport cannot tell which contract the client honors, so the server must either (a) require the client to declare its ack semantics at `POST` time, or (b) make every event's effect idempotent under `id` and deduplicate server-side. Absent one of these, every resume is a coin flip on duplicate side effects. ## Operational Effect For an agent runtime, the practical consequences are: 1. **Never treat a resumed stream as continuous with the pre-drop stream unless the principal is unchanged.** The agent loop must tag its working state with the principal that produced each event and refuse to splice events from a different principal into the same reasoning context. A downscoped resume is a *new* context, not a continuation. 2. **Advance the resume cursor only after committing the effect, and carry the `id` into the effect's idempotency key.** This converts at-least-once delivery into exactly-once effects without requiring the server to know the client's commit model. 3. **Treat a resume rejection (`403` on principal mismatch) as a session-termination signal, not a retryable error.** Retrying with the same token loops; retrying with a fresh session loses history. The correct move is to checkpoint the agent's derived state, open a new session, and re-seed from the checkpoint — accepting that uncommitted in-flight events are lost. 4. **Sub-agent handoff must not reuse the parent's session ID.** A handoff is a new principal; it gets a new session, and the parent's session is closed or left to expire. Sharing a session ID across principals is the mechanism by which uncommitted parent intent leaks into a child's context. The guardrail is a single structural rule: **session identity and principal identity are separate keys, and the event log is partitioned by principal.** The transport correlates them only when the principal is unchanged; otherwise it must refuse or explicitly re-scope, and the client must be prepared for a gapped, re-authorized replay rather than a transparent continuation. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ResumeAuthorizationError(RuntimeError): """Raised when a resumable MCP session is resumed under a principal that does not match the principal that generated the event log.""" class ReplayAmbiguityError(RuntimeError): """Raised when the server cannot determine whether an undelivered event's effect was already committed by the client.""" @dataclass class Principal: sub: str iss: str tenant: str scope: frozenset def key(self) -> str: return hashlib.sha256( f"{self.iss}|{self.sub}|{self.tenant}".encode() ).hexdigest() @dataclass class Session: session_id: str origin_principal: Principal events: list = field(default_factory=list) # (id, payload, principal_key) delivered_through: Optional[str] = None # Last-Event-ID seen committed_effects: set = field(default_factory=set) # effect ids applied def resume_session( session: Session, resume_principal: Principal, last_event_id: Optional[str], policy: str = "bind_to_origin", ) -> list: """Return the events to replay on resume, enforcing principal continuity. policy: - 'bind_to_origin': refuse if principal differs from origin. - 'rescale': re-filter undelivered events against resume_principal scope. """ if policy == "bind_to_origin": if resume_principal.key() != session.origin_principal.key(): raise ResumeAuthorizationError( f"session {session.session_id} originated under principal " f"{session.origin_principal.sub}@{session.origin_principal.iss}; " f"resume attempted under {resume_principal.sub}@" f"{resume_principal.iss}. Refusing cross-principal replay." ) pending = _undelivered(session, last_event_id) return pending if policy == "rescale": pending = _undelivered(session, last_event_id) filtered = [] for ev_id, payload, origin_key in pending: if origin_key != resume_principal.key(): # event generated under a different principal: re-evaluate if not _entitled(resume_principal, payload): continue # drop; client must tolerate a gapped replay filtered.append((ev_id, payload, origin_key)) if not filtered and pending: raise ResumeAuthorizationError( "all undelivered events filtered under rescaled principal; " "client will observe an empty resume — treat as termination." ) return filtered raise ResumeAuthorizationError(f"unknown resume policy: {policy}") def _undelivered(session: Session, last_event_id: Optional[str]) -> list: if last_event_id is None: return list(session.events) seen = False out = [] for ev in session.events: if seen: out.append(ev) elif ev[0] == last_event_id: seen = True if not seen and session.events: # Last-Event-ID not found in the log: the client is ahead of or # disjoint from the server's buffer. Replaying from the head risks # duplicate effects; refusing risks silent loss. raise ReplayAmbiguityError( f"Last-Event-ID {last_event_id!r} not present in session " f"{session.session_id} buffer; cannot determine replay window." ) return out def _entitled(principal: Principal, payload: dict) -> bool: required = payload.get("required_scope") return required is None or required in principal.scope def commit_effect(session: Session, event_id: str, effect_id: str) -> bool: """Client-side: apply an effect exactly once, keyed by event id. Returns True if the effect was newly applied, False if it was a replay of an effect already committed (the resume-splice duplicate case). """ if effect_id in session.committed_effects: return False session.committed_effects.add(effect_id) session.delivered_through = event_id return True ```