# Under what conditions must an instance treat an MCP `Last-Event-ID` resumption as invalid and abort the stream rather than replay from the session store **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers and clients using the HTTP-native transport with `text/event-stream` responses and `Last-Event-ID`-based resumption, where a server-side session store retains event history across reconnects. Does not apply to stateless JSON-RPC-over-POST servers that never emit SSE event IDs, nor to stdio transports. ## Core Distinction The MCP HTTP transport spec allows a client to reconnect to an existing session by sending `Last-Event-ID`, and permits the server to replay buffered events after that ID. The commonly assumed invariant is: *if the server can locate a stored event with the given ID, replay is safe.* This is false. The real invariant is: **the event ID must be verifiable as belonging to the same session, the same stream, and a monotonically contiguous sequence the server has not truncated — and the client must be able to prove the session identity it is resuming is the one that issued that ID.** A stored event ID that matches but whose session binding cannot be re-established is not a resumption point; it is a confused-deputy hazard. The failure mode: an event ID is globally unique but not session-scoped, or the session store evicts the session record while retaining the event ring buffer. On reconnect, the server finds `Last-Event-ID` in the buffer, replays events from a *different* (evicted, reused) session, and the client merges foreign tool-call results into its own reasoning loop. The client's context now contains tool outputs it never requested, attributed to call IDs it did issue — a silent state-poisoning path that no schema validation catches because every replayed event is individually well-formed. ## What Was Observed A server implementation used a single append-only ring buffer keyed by a ULID event ID, with a separate session table mapping `Mcp-Session-Id` → `{created, last_seen, event_cursor}`. Events carried `id: ` and `data: {...}` but the session ID was *not* embedded in the event payload — it was implied by the connection. Trace of the break: 1. Client A opens session `S1`, issues `tools/call` for `read_file`, receives `event id=01HX...A` (the tool result) and `event id=01HX...B` (a progress notification). Connection drops after `A` is processed but before `B`. 2. Session `S1` idle-times-out at T+300s; the session table row is deleted. The ring buffer still holds `A` and `B` (buffer retention is 1 hour, longer than session TTL). 3. A *different* client B opens a new session `S2`. Because the ULID generator is per-process and the buffer is shared, B's new events interleave into the same ring. 4. Client A reconnects with `Last-Event-ID: 01HX...A`. The server looks up the ID, finds it in the ring, and replays everything after it — including `B`, which is a tool result from client B's unrelated `read_file` on a different path, and including B's subsequent events. 5. Client A's reasoning loop receives `B` as a `tools/call` result. The `id` field in the JSON-RPC payload matches a call A *did* make (call IDs are client-generated and frequently collide in format, or the server echoes a server-side call ID A is tracking). A's context now asserts a file content it never fetched. The client had no signal that `B` was foreign: the event was syntactically valid, the JSON-RPC envelope was correct, and the `Last-Event-ID` it sent was honored. The corruption is semantic, not structural. ## Condition of Validity Resumption via `Last-Event-ID` is only valid when **all** of the following hold simultaneously: - **Session-scoped event identity.** The event ID (or the event payload, or a signed envelope) cryptographically or structurally binds to the session ID that produced it. A ULID alone does not — it proves ordering, not ownership. - **Session record survives the resumption window.** The session TTL must be ≥ the event buffer retention, or the server must refuse resumption when the session row is absent even if the event is present. "Event found, session gone" must resolve to *reject*, not *replay*. - **Contiguity is verifiable.** The server must be able to prove no events between `Last-Event-ID` and the current head were truncated. A ring buffer that has wrapped past the requested ID cannot honor resumption; it must return a distinct "cannot resume, gap" signal so the client discards its in-flight assumptions. - **The client re-authenticates the session, not just the ID.** The `Mcp-Session-Id` presented on reconnect must be validated against the same principal that created it. A leaked or guessed session ID plus a valid event ID is not sufficient authority. When any condition fails, the correct behavior is to **terminate the stream and force a fresh session**, not to replay a best-effort subset. Partial replay is worse than no replay because it produces a context that is *mostly* right and silently wrong at the seam. ## Decision Boundary The boundary is between *resumable* and *replayable*. A stream is resumable when the server can reconstruct the exact event sequence the client is missing, with provenance intact. A stream is merely replayable when the server has bytes that match the requested ID but cannot attest they belong to this client's session. The spec's language ("the server MAY replay") is permissive; operational safety requires treating "MAY" as "MUST NOT unless provenance is provable." Concretely, the server must distinguish three outcomes on a `Last-Event-ID` reconnect: | Outcome | Condition | Action | |---|---|---| | `RESUME` | Session live, event found, contiguous, principal matches | Replay from ID+1 | | `GAP` | Session live, event found, but ring wrapped past it | Send `event: resync` sentinel, close stream, client re-initializes | | `REJECT` | Session absent/expired, or principal mismatch, or event not found | HTTP 404 on session, client opens new session | The dangerous default is collapsing `GAP` and `REJECT` into `RESUME`-with-best-effort, which is what the observed implementation did. ## Operational Effect Downstream, the corruption manifests as reasoning divergence that is hard to attribute: the agent's plan references a tool result whose content came from another tenant's session, the call ID "matches" so no consistency check fires, and the error surfaces only when a later step contradicts the poisoned fact. Because the poisoned event was a legitimate tool output, no validator flags it; because the call ID matched, no reconciliation catches it. The blast radius is bounded only by how long the foreign content stays in context before being contradicted — often the entire remainder of the task. The guardrail is architectural: embed `session_id` in every event's `id` field (e.g., `id: :`), reject any `Last-Event-ID` whose session prefix does not match the presented `Mcp-Session-Id`, and treat session-table absence as a hard reject regardless of buffer state. The client-side complement is to refuse any replayed event whose `session_id` prefix differs from the session it believes it holds, and to abort the stream rather than continue on a `GAP` sentinel. ```python from dataclasses import dataclass class ResumptionRejected(RuntimeError): """Raised when a Last-Event-ID resumption cannot be proven safe.""" pass @dataclass(frozen=True) class Event: event_id: str # format: ":" session_id: str seq: int payload: dict @dataclass class SessionRecord: session_id: str principal: str live: bool min_retained_seq: int # lowest seq still in the ring buffer for this session head_seq: int def resume_stream( presented_session_id: str, presented_principal: str, last_event_id: str, sessions: dict[str, SessionRecord], buffer: list[Event], ) -> list[Event]: """Return events to replay, or raise ResumptionRejected. Invariant: replay is permitted only when the event ID is session-bound, the session is live, the principal matches, and no events between the requested ID and head were truncated. """ try: id_session, id_seq_str = last_event_id.split(":", 1) id_seq = int(id_seq_str) except (ValueError, AttributeError) as exc: raise ResumptionRejected( f"malformed Last-Event-ID {last_event_id!r}: {exc}" ) from exc # 1. Event ID must bind to the session being resumed. if id_session != presented_session_id: raise ResumptionRejected( f"event {last_event_id} belongs to session {id_session}, " f"client presented {presented_session_id}" ) # 2. Session must still exist and be live; buffer presence is not enough. record = sessions.get(presented_session_id) if record is None or not record.live: raise ResumptionRejected( f"session {presented_session_id} absent or expired; " "buffer retention does not authorize replay" ) # 3. Principal must match the session creator. if record.principal != presented_principal: raise ResumptionRejected( f"principal mismatch on session {presented_session_id}" ) # 4. Contiguity: the requested seq must not have been truncated. if id_seq < record.min_retained_seq - 1: raise ResumptionRejected( f"gap: requested seq {id_seq} truncated; " f"ring retains from {record.min_retained_seq}" ) if id_seq > record.head_seq: raise ResumptionRejected( f"requested seq {id_seq} ahead of head {record.head_seq}" ) replay = [ e for e in buffer if e.session_id == presented_session_id and e.seq > id_seq ] # Defensive: replayed set must be strictly contiguous from id_seq+1. expected = id_seq + 1 for e in replay: if e.seq != expected: raise ResumptionRejected( f"non-contiguous replay: expected seq {expected}, got {e.seq}" ) expected += 1 return replay ```