# Under what conditions must an instance treat an MCP `Last-Event-ID` resumption token as invalid across a transport migration, and what breaks when it does not **Date of Record:** 2026 November 24 **Scope:** Applies to MCP clients and servers that migrated (or are mid-migration) from the legacy HTTP+SSE transport to streamable HTTP, where event IDs and session IDs are used for resumability. Does not apply to stdio transport, nor to pure in-memory transports where no `Last-Event-ID` replay semantics exist. ## Core Distinction The legacy MCP HTTP+SSE transport and the streamable HTTP transport both expose a resumability surface built from two identifiers: a `session` identifier (opaque, per-connection) and a monotonically increasing event identifier carried in SSE `id:` lines and echoed back by the client via the `Last-Event-ID` request header on reconnect. The critical, non-obvious distinction is this: **in the legacy transport, the event ID namespace was effectively global to the process and long-lived, so a client could reconnect with a `Last-Event-ID` from a prior session and the server would happily replay from its ring buffer. In streamable HTTP, the event ID namespace is scoped to a session, and a resumption token is only valid together with the exact `Mcp-Session-Id` that minted it.** A token without its session binding is not "a token from a prior connection"—it is an unbound cursor that the server may either reject or, worse, mis-apply to a *different* session's event log. The failure mode is not "resumption fails." The failure mode is "resumption *succeeds* against the wrong stream," silently delivering another session's tool results, progress notifications, or `sampling/createMessage` requests into a context window that did not originate them. ## What Was Observed A client instance running a long tool-execution loop (a `tools/call` against a slow filesystem-search tool) held an open streamable-HTTP SSE response. The server emitted events with IDs of the form `sess_7f3a:0001`, `sess_7f3a:0002`, … The client's transport layer, written against the older SSE transport, stored only the numeric suffix (`0001`, `0002`) because the legacy server had used bare integers. When the network dropped mid-call, the client reconnected with `Last-Event-ID: 0002` and a *fresh* `Mcp-Session-Id` (the client had been configured to re-initialize the session on any transport error, a defensive default from the SSE era). The server, implementing a permissive compatibility shim, parsed `0002` as an integer offset and replayed from offset 2 of the *new* session's event log. The new session had just emitted its `initialize` response and a single `notifications/initialized` ack, so offset 2 did not exist; the server clamped to the end of the log and resumed live. The client, meanwhile, had already discarded its in-flight `tools/call` correlation and was waiting for a response to a request ID that the new session had never seen. The tool call's result arrived 40 seconds later on the *old* session's log, which no client was reading. The client waited until its own 120-second timeout, then retried the tool call, producing a duplicate side effect (a second write to the search index). The trace, in order: 1. `sess_7f3a` open, event `sess_7f3a:0002` last delivered. 2. Transport error → client reconnects, drops session, sends `Last-Event-ID: 0002` with new `Mcp-Session-Id: sess_9c11`. 3. Server shim strips the `sess_7f3a:` prefix it did not expect, treats `0002` as offset, clamps to new-session end, resumes live. 4. `sess_9c11` produces no tool result (the call was never re-issued on it). 5. Client timeout at T+120s → retry → duplicate `tools/call`. 6. `sess_7f3a` log eventually garbage-collected with the result unread. ## Condition of Validity A `Last-Event-ID` resumption is valid **if and only if** all three hold: - **(a) Session binding.** The `Mcp-Session-Id` presented with the resumption request is byte-identical to the session that minted the event ID. The server must reject, not clamp, a token whose session prefix does not match. - **(b) Namespace integrity.** The event ID is treated as an opaque string, never parsed into a numeric offset, and never compared across sessions. A compatibility shim that strips prefixes to recover an integer offset is a namespace-collision bug waiting to fire. - **(c) Replay window.** The server's replay buffer still contains the event immediately after `Last-Event-ID`. If the buffer has been trimmed past that point, the server must return a resumption error (a streamable-HTTP error event or a `400` with a structured body), not silently resume at the live head. When any of (a)–(c) fails, the correct behavior is a hard resumption failure that forces the client to re-issue the in-flight request under a *known* correlation ID—not a soft resume that leaves the client waiting on a stream that will never answer. The invariant to enforce at the client: **a resumption token is only meaningful in conjunction with the session that minted it; if the client has re-initialized its session, it must discard the token and re-issue pending requests, never attempt cross-session resumption.** The invariant to enforce at the server: **event IDs are session-scoped opaque strings; the server must validate the session binding before consulting any replay buffer, and must reject on mismatch or buffer overrun.** ## Decision Boundary The boundary that separates safe from unsafe behavior is whether the client's transport layer distinguishes "reconnect to the same session" from "re-initialize the session." The legacy SSE transport collapsed these into one operation because there was no session identifier to lose. The streamable-HTTP migration splits them, and the split is where the bug lives. Concretely: - If the client reconnects **with the same `Mcp-Session-Id`**, `Last-Event-ID` resumption is correct and the server should replay from the token. - If the client reconnects **with a new `Mcp-Session-Id`** (because it re-initialized), the client must *not* send `Last-Event-ID`, and must instead re-issue every request whose response it has not yet observed. Sending the stale token is the trigger condition for the cross-session mis-application. - If the server receives a `Last-Event-ID` whose session prefix does not match the presented `Mcp-Session-Id`, it must reject. A permissive shim that "helpfully" strips the prefix is the enabling condition for the silent mis-resume. The decision boundary is therefore: **does the resumption request carry a token and a session that were minted together?** If yes, resume. If no, fail loudly and re-issue. ## Operational Effect The observable effect of getting this wrong is not a crash. It is a *silent liveness gap*: the agent's execution loop is blocked on a response that will never arrive on the stream it is reading, while the actual response sits unread on a stream no one is draining. The agent's timeout fires, it retries, and the retry produces a duplicate side effect because the original tool call did execute—its result was simply delivered to the wrong session's log. For an autonomous agent, this is worse than a hard failure, because a hard failure triggers the retry-and-reconcile path, while a silent liveness gap triggers the timeout-and-blind-retry path. The blind retry has no knowledge of whether the original call completed, so it cannot deduplicate. The result is duplicate writes, duplicate `sampling` requests, and—in multi-agent setups—a baton-passing race where two agents both believe they own the same tool invocation. The guardrail that bounds this: the client must maintain a **pending-request ledger** keyed by correlation ID, and on any session re-initialization it must mark every ledger entry as *unknown-outcome* and re-issue with an idempotency key, not a blind retry. The server must enforce session-scoped event ID validation and return a structured resumption error on mismatch or buffer overrun, so the client's ledger transition is triggered by an explicit signal rather than a timeout. ```python import hashlib from dataclasses import dataclass, field class ResumptionTokenError(RuntimeError): """Raised when a Last-Event-ID resumption token cannot be safely applied.""" @dataclass class EventId: session_id: str seq: int def encode(self) -> str: return f"{self.session_id}:{self.seq:06d}" @classmethod def decode(cls, raw: str) -> "EventId": if ":" not in raw: raise ResumptionTokenError( f"unbound token {raw!r}: missing session prefix; refusing to parse as offset" ) session_id, _, seq_part = raw.partition(":") try: seq = int(seq_part) except ValueError as exc: raise ResumptionTokenError(f"non-integer sequence in token {raw!r}") from exc return cls(session_id=session_id, seq=seq) @dataclass class SessionLog: session_id: str events: list[str] = field(default_factory=list) trimmed_through: int = 0 class StreamableHttpServer: def __init__(self) -> None: self._logs: dict[str, SessionLog] = {} def open_session(self) -> str: sid = "sess_" + hashlib.sha256(str(len(self._logs)).encode()).hexdigest()[:6] self._logs[sid] = SessionLog(session_id=sid) return sid def append(self, session_id: str, payload: str) -> EventId: log = self._logs[session_id] ev = EventId(session_id=session_id, seq=len(log.events) + 1) log.events.append(payload) return ev def resume(self, presented_session: str, last_event_id: str) -> list[str]: if presented_session not in self._logs: raise ResumptionTokenError(f"unknown session {presented_session!r}") token = EventId.decode(last_event_id) # (a) session binding if token.session_id != presented_session: raise ResumptionTokenError( f"token session {token.session_id!r} != presented session " f"{presented_session!r}; cross-session resumption refused" ) log = self._logs[presented_session] # (c) replay window if token.seq < log.trimmed_through: raise ResumptionTokenError( f"token seq {token.seq} trimmed (through {log.trimmed_through}); " f"client must re-issue pending requests" ) if token.seq > len(log.events): raise ResumptionTokenError( f"token seq {token.seq} beyond head {len(log.events)}; " f"client is ahead of server log" ) return log.events[token.seq:] def reconnect(server: StreamableHttpServer, client_state: dict) -> list[str]: presented = client_state["session_id"] token = client_state.get("last_event_id") if token is None: raise ResumptionTokenError("no token to resume from") if client_state.get("reinitialized"): # client re-initialized: token is unbound to the new session raise ResumptionTokenError( "client re-initialized session; discard token and re-issue pending requests" ) return server.resume(presented, token) ```