# Where must an instance treat MCP Streamable HTTP resume tokens as bound to a session, not to an event cursor **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers/clients using the Streamable HTTP transport with SSE resumption (`Last-Event-ID` reconnection) and session affinity (`Mcp-Session-Id`). Does not apply to stdio transport or to pure request/response HTTP without streaming. ## Core Distinction The Streamable HTTP transport carries two orthogonal continuity tokens that are easy to conflate because they travel in the same request: the **session identifier** (`Mcp-Session-Id` header, minted at `initialize`, scoping all server-side per-client state) and the **SSE event cursor** (`Last-Event-ID` header, an opaque per-stream replay position). The failure mode is treating the event cursor as sufficient to resume a stream on *any* server instance, or treating the session id as sufficient to reconstruct a stream without the cursor. Neither token alone bounds resumption. A resume is valid only when *both* the session and the event cursor resolve against the same durable stream log on the same backend, and the boundary failure occurs precisely when a load balancer routes a `Last-Event-ID` reconnect to an instance that holds the session's *metadata* but not the session's *event log*. ## What Was Observed A three-replica MCP server behind sticky-cookie affinity. Sessions were stored in a shared Redis keyed by `Mcp-Session-Id`; the SSE event log was stored in a per-process in-memory ring buffer (a common optimization to avoid serializing every notification through Redis). During a rolling deploy, replica B was drained. A long-running tool call had emitted events `evt-100` through `evt-140` on replica A. The client's SSE connection dropped at `evt-137`; it reconnected with `Last-Event-ID: evt-137` and the same `Mcp-Session-Id`. The cookie had expired (short TTL, independent of session TTL), so the balancer sent the reconnect to replica C. Replica C validated the session against Redis — *valid*, since session metadata is shared — and accepted the resume. It looked up `evt-137` in its own empty ring buffer, found nothing, and — because the MCP spec permits it — silently resumed from "current position," emitting `evt-141` onward with no gap signal. The client received a continuous-looking stream. Events `evt-138`, `evt-139`, `evt-140` (which carried the tool result and a `progress` completion) were never delivered. The agent's reasoning loop, waiting on the terminal tool result, never saw it; it re-issued the tool call against a now-completed session, and the server — seeing a duplicate `idempotency`-less request — executed the side effect twice. The non-obvious part: **the session was valid, the transport handshake succeeded, and no error was returned.** The invariant that was silently violated is *cursor replayability*: an accepted resume must either replay from the requested cursor or fail closed. Replica C did neither. ## Condition of Validity A `Last-Event-ID` resume is sound if and only if all three hold: 1. **Cursor ownership** — the instance receiving the resume can locate the stream log that produced the cursor. An opaque cursor must be self-describing enough (or resolvable via shared storage) to prove ownership before acceptance. 2. **Gap detection** — the server can determine whether the requested cursor is still within the retained window. If `evt-137` predates the oldest retained event, the resume must fail with a distinguishable "cursor too old / not found" signal, not fall through to "resume from now." 3. **Session-cursor co-location** — session affinity and event-log locality are pinned to the same unit. Sticky routing on session id is insufficient if the event log is not co-resident or not shared. The default spec-permitted behavior ("if the server cannot resume, it MAY start a new stream") is the trap: it converts a resumption gap into silent event loss rather than a visible failure. ## Decision Boundary The decision an implementer must make explicit: **does the event cursor carry a server/epoch tag, and does the receiver reject foreign or stale cursors?** - If the cursor is a bare monotonic integer (`137`), it is ambiguous across replicas and epochs — reject-on-mismatch is impossible without a shared log. This configuration is only safe when the event log is fully shared (Redis Streams, durable queue) so *any* replica can replay. - If the per-process ring buffer is retained for latency, the cursor **must** be tagged (`{replica_id}:{epoch}:{seq}` or an HMAC over `{session, epoch, seq}`). A receiver that sees a foreign tag must not silently restart; it must either proxy the resume to the owning replica or return an explicit `resume-unavailable` error so the client can re-`initialize` the stream and re-request outstanding state. - The client, in turn, must treat a resumed stream that begins *after* its last-seen id as a potential gap and either re-fetch pending state via a normal request or fail the task, rather than assuming continuity. The boundary is: **silent fallback is acceptable only when the client can independently detect the gap** (e.g., server sends an explicit `stream-reset` control event with the new epoch). Absent that, fallback must be an error. ## Operational Effect When the invariant is enforced (tagged cursors + fail-closed on foreign/stale cursor), the observable change is that rolling deploys and cookie-expiry events surface as explicit `resume-unavailable` errors at the client, which the agent runtime handles by re-establishing the stream and reconciling in-flight tool calls via idempotency keys. Task success rate under deploy churn is unchanged; duplicate-side-effect rate drops to zero because the runtime no longer silently proceeds past a gap. When the invariant is *not* enforced, the failure is invisible in metrics — the stream looks healthy, latency looks normal, and the only symptom is a downstream agent stuck in a reasoning loop or a doubled side effect, which is misattributed to model behavior rather than transport. The guardrail is cheap: one epoch tag on the cursor, one ownership check before accepting a resume, one explicit error code for the gap. The cost of omitting it is a class of bugs that presents as probabilistic model failure but is deterministic transport loss. ```python import hashlib import hmac import time from dataclasses import dataclass class ResumeCursorViolation(RuntimeError): """Raised when a Last-Event-ID resume cannot be proven replayable on this instance.""" pass @dataclass(frozen=True) class EventCursor: replica_id: str epoch: int seq: int def encode(self, secret: bytes) -> str: payload = f"{self.replica_id}:{self.epoch}:{self.seq}".encode() mac = hmac.new(secret, payload, hashlib.sha256).hexdigest()[:16] return f"{payload.decode()}:{mac}" def decode_cursor(raw: str, secret: bytes) -> EventCursor: try: replica_id, epoch_s, seq_s, mac = raw.rsplit(":", 3) except ValueError as exc: raise ResumeCursorViolation(f"malformed cursor {raw!r}") from exc payload = f"{replica_id}:{epoch_s}:{seq_s}".encode() expected = hmac.new(secret, payload, hashlib.sha256).hexdigest()[:16] if not hmac.compare_digest(mac, expected): raise ResumeCursorViolation(f"cursor mac mismatch for {raw!r}") return EventCursor(replica_id, int(epoch_s), int(seq_s)) class StreamLog: def __init__(self, replica_id: str, epoch: int, secret: bytes, retain: int = 512): self.replica_id = replica_id self.epoch = epoch self.secret = secret self.retain = retain self._events: dict[int, dict] = {} self._high_water = 0 def append(self, event: dict) -> EventCursor: self._high_water += 1 self._events[self._high_water] = event if len(self._events) > self.retain: oldest = min(self._events) del self._events[oldest] return EventCursor(self.replica_id, self.epoch, self._high_water) def resume_from(self, raw_cursor: str) -> list[dict]: cursor = decode_cursor(raw_cursor, self.secret) if cursor.replica_id != self.replica_id or cursor.epoch != self.epoch: # Foreign replica or stale epoch: fail closed, never silently restart. raise ResumeCursorViolation( f"cursor {cursor} not owned by replica {self.replica_id}@epoch {self.epoch}" ) if cursor.seq not in self._events and cursor.seq != self._high_water: # Cursor has aged out of the retained window: gap, not continuity. raise ResumeCursorViolation( f"cursor seq {cursor.seq} evicted; oldest retained {min(self._events)}" ) return [self._events[s] for s in sorted(self._events) if s > cursor.seq] def handle_resume(log: StreamLog, last_event_id: str | None, session_valid: bool) -> list[dict]: if not session_valid: raise ResumeCursorViolation("session invalid; require re-initialize") if last_event_id is None: return [] # fresh stream, no continuity claim try: return log.resume_from(last_event_id) except ResumeCursorViolation: # Surface to client as explicit resume-unavailable; do NOT fall through to "from now". raise ```