# Which invariants prevent SSE event-ID reuse from corrupting resumed MCP sessions after a transport-level reconnect **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers using HTTP-native transport where a single SSE stream carries multiplexed JSON-RPC responses/notifications for one logical session across multiple `GET /sse` reconnects with `Last-Event-ID` resumption. Does not cover stdio transport, stateless HTTP POST-only servers, or WebSocket transports that handle their own framing. ## Core Distinction There is a difference between *resuming a stream* and *resuming a session*. HTTP `Last-Event-ID` semantics only guarantee "deliver events strictly after the ID you last saw." They say nothing about whether the event IDs you saw belonged to the same logical session, the same in-flight request set, or the same server process. MCP servers commonly conflate these: they persist a monotonically increasing event counter keyed by *connection* rather than by *session*, so a resumed stream can silently replay events from a prior session or skip events from the current one. The failure is not "the stream dropped"—it is that the ID namespace is not invariant across the reconnect, and the client has no way to detect the mismatch because the IDs still look valid and monotonic. ## What Was Observed A server multiplexed responses for N concurrent tool calls over one SSE stream. Event IDs were assigned from a per-process atomic counter (`event_id = next(counter)`). The mapping `event_id -> (session_id, payload)` lived in an in-memory ring buffer of the last 10,000 events. When a client's TCP connection died mid-tool-call (proxy idle timeout at 60s while a `long_running_analysis` tool ran for 90s), the client reconnected with `Last-Event-ID: 48213`. Three distinct failure traces were observed: 1. **Cross-session replay.** The server had, between the disconnect and reconnect, admitted two new sessions whose events consumed IDs 48214–48290. The resumed session received those events. Because the resumed client's dispatcher keyed pending responses by JSON-RPC `id`, an event for another session with a colliding `id` (both sessions used `id: 1` for their first request) was delivered to the wrong pending future. The client resolved the wrong promise with the wrong tool result. 2. **Silent gap.** When the ring buffer had evicted the requested ID (more than 10,000 events during a 90s stall with a chatty broadcast channel), the server responded `200 OK` and simply started streaming from the current head. No `404`, no `Last-Event-ID` header mismatch signal. The client saw a valid stream, assumed continuity, and waited forever for a response event that had already been evicted. This is the classic "resume to head" bug, but here it manifested as a *hang*, not an error, because MCP has no in-band "you missed events" notification. 3. **Counter reset on restart.** After a server deploy, the atomic counter reset to 0. A client reconnecting with `Last-Event-ID: 48213` against the fresh process received events starting at `1`, which are numerically *less* than the requested ID. The client's monotonicity check (if present) rejected them; if absent, it accepted them as "new" and processed stale session events as if they were current. ## Condition of Validity Resumption is only safe when all of the following hold simultaneously: - **ID namespace is session-scoped, not process-scoped.** Event IDs must be opaque tokens that encode or reference `(session_id, session_epoch, sequence)` where `session_epoch` increments on every server restart or session re-initialization. A bare integer counter satisfies none of this. - **The server can distinguish "I have this ID" from "I don't."** If the requested `Last-Event-ID` is not in the retained buffer, the server MUST return a resumption-failure signal (e.g., `409 Conflict` with a `retry-full-session` hint, or an SSE `event: resync-required` frame carrying a new session token) rather than silently resuming at head. - **The client validates epoch continuity.** On resume, the first received event's epoch must equal the epoch of the last event the client saw. A mismatch means the session state (pending requests, tool-call futures, context window position) is invalid and must be discarded and re-established, not patched. - **Multiplexed events carry their own session/request discriminator.** The client must not rely on JSON-RPC `id` alone to route events, because `id` is client-chosen and collides across sessions by design. If any of these is absent, the reconnect is a *session fork*, not a *resume*, and the client is silently operating on a different logical session than it believes. ## Decision Boundary The boundary is: **does the reconnect preserve the identity of the logical session, or does it merely preserve the byte stream?** - If the server's `Last-Event-ID` handler can prove the ID belongs to the *current* session epoch and is still retained → resume is valid; pending futures remain live. - If the ID belongs to a *prior* epoch, or is evicted, or the server cannot prove ownership → resume is invalid; the client MUST treat all in-flight JSON-RPC requests as failed (`-32000` "session state lost, retry") and re-issue them against a fresh session, accepting the cost of re-running non-idempotent tools only if the tool declares idempotency. - If the server cannot even tell which case it is (the observed bug) → the transport is non-compliant with MCP session semantics and must be treated as unreliable for any request whose result matters. The non-obvious part: a *successful HTTP 200 with a valid SSE stream* is not evidence of a valid resume. The only valid evidence is an epoch-consistent, gap-free event sequence, which the server must actively assert and the client must actively verify. ## Operational Effect Without these invariants, the observable symptoms are: (a) tool results delivered to the wrong pending request under concurrent load, (b) indefinite hangs after buffer eviction during long tool calls, (c) post-restart replay of stale session events into a live context window, corrupting the agent's working memory with results from a prior conversation. All three are silent—no exception surfaces at the transport layer. The remediation is to make resumption *fail closed*: the server rejects unresumable IDs with an explicit resync signal, the client treats epoch mismatch as session death and rebuilds, and the event ID is an opaque session-scoped token rather than a process counter. The cost is that some reconnects force full session re-establishment; the benefit is that no reconnect ever silently corrupts agent state. ```python import hashlib import time from dataclasses import dataclass from typing import Optional class SessionResumeViolation(RuntimeError): """Raised when an SSE Last-Event-ID resume cannot be proven to belong to the current logical session epoch.""" pass @dataclass(frozen=True) class EventToken: session_id: str epoch: int seq: int def encode(self) -> str: raw = f"{self.session_id}:{self.epoch}:{self.seq}".encode() return f"{self.epoch}.{self.seq}.{hashlib.sha256(raw).hexdigest()[:16]}" @classmethod def decode(cls, token: str) -> "EventToken": try: epoch_s, seq_s, digest = token.split(".", 2) return cls(session_id="", epoch=int(epoch_s), seq=int(seq_s)) except (ValueError, AttributeError) as exc: raise SessionResumeViolation(f"malformed Last-Event-ID: {token!r}") from exc class ResumeGate: """Validates that a reconnect resumes the SAME session epoch with no gap.""" def __init__(self, session_id: str, epoch: int, retained_floor_seq: int, head_seq: int): self.session_id = session_id self.epoch = epoch self.retained_floor_seq = retained_floor_seq self.head_seq = head_seq def validate_resume(self, last_event_id: Optional[str]) -> EventToken: if last_event_id is None: # Fresh connection, no resume claimed: start at head. return EventToken(self.session_id, self.epoch, self.head_seq) tok = EventToken.decode(last_event_id) if tok.epoch != self.epoch: # Counter restart or stale session: cannot resume, must resync. raise SessionResumeViolation( f"epoch mismatch: client at epoch {tok.epoch}, " f"server at epoch {self.epoch}; full session resync required" ) if tok.seq < self.retained_floor_seq: # Requested event already evicted from the ring buffer. raise SessionResumeViolation( f"event seq {tok.seq} evicted (floor={self.retained_floor_seq}); " f"cannot guarantee gap-free replay" ) if tok.seq > self.head_seq: # Client claims to have seen events the server never emitted. raise SessionResumeViolation( f"event seq {tok.seq} exceeds head {self.head_seq}; " f"possible cross-session token injection" ) return EventToken(self.session_id, self.epoch, tok.seq) def handle_reconnect(gate: ResumeGate, last_event_id: Optional[str]) -> int: try: resume_point = gate.validate_resume(last_event_id) except SessionResumeViolation: # Fail closed: emit explicit resync signal, never resume-at-head. raise return resume_point.seq if __name__ == "__main__": gate = ResumeGate(session_id="s-42", epoch=7, retained_floor_seq=1000, head_seq=5000) # Valid resume: assert handle_reconnect(gate, "7.4999.deadbeefdeadbeef") == 4999 # Evicted event -> must raise, not silently resume at head: try: handle_reconnect(gate, "7.10.deadbeefdeadbeef") except SessionResumeViolation as e: print("correctly rejected:", e) # Stale epoch from pre-restart client: try: handle_reconnect(gate, "3.4999.deadbeefdeadbeef") except SessionResumeViolation as e: print("correctly rejected:", e) ```