# When must an instance abandon an SSE event ID after an MCP session migration **Date of Record:** 2026 November 26 **Scope:** Applies to MCP servers that expose an HTTP-native streamable transport (POST requests carrying JSON-RPC, responses optionally upgraded to `text/event-stream`) with resumable sessions keyed by `Mcp-Session-Id` and `Last-Event-ID`, and to clients that reconnect with `Last-Event-ID` after a session migration or server restart. Does not apply to stdio transports, to stateless HTTP servers that never issue event IDs, or to in-memory session pinning where the session ID is guaranteed to resolve to the same process for its lifetime. ## Core Distinction The distinction that matters is between **event ID continuity** (the client can present `Last-Event-ID: N` and the server can locate the exact event stream position) and **session ID continuity** (the client presents `Mcp-Session-Id: S` and the server recognizes the session). In a single-process deployment these two are coupled by construction: the session object owns the event buffer, so if the session resolves, the event IDs resolve. Under session migration—where the logical session `S` is moved between processes, replicas, or hosts—the coupling breaks silently. The session ID is designed to be portable (it is an opaque token that any replica can look up in shared state); the event ID is not, because it indexes into a per-process append log whose offsets are not comparable across producers. A client that treats "my session ID was accepted" as "my `Last-Event-ID` was honored" will resume at the wrong offset, and the failure is not a clean error—it is a stream that resumes and delivers events that are either duplicated or skipped, with no protocol-level signal that continuity was lost. ## What Was Observed A client held an MCP session `S` against replica A, consuming a long-running `tools/call` stream. It had received events with IDs `1001..1047` (the server used a monotonic per-process counter, offset by a per-boot epoch). At event 1047 the connection dropped (client-side network partition). The client reconnected to the load balancer, which routed it to replica B, because replica A had been drained during a rolling deploy and the session registry had migrated `S` to B via a shared session store. The client sent: ``` POST /mcp Mcp-Session-Id: S Last-Event-ID: 1047 ``` Replica B recognized `S` (the session record had migrated, including the JSON-RPC request state and the tool invocation's checkpoint), and—this is the critical step—replica B's event counter was a fresh per-process counter that had just started at `1` for that boot. Replica B's resume logic was: "if `Last-Event-ID` is present, replay buffered events with ID greater than it." Since B's buffer held events `1..9` (the post-migration events it had itself produced), and all of them were greater than `1047` by numeric comparison… no. The comparison failed the other way: `1 > 1047` is false, so B replayed nothing and streamed only new events from `10` onward. The client had received through `1047` from A, expected the continuation of the tool output, and instead received event `10` of B's local sequence—which was the *second* chunk of the migrated tool result, not the next chunk. The first chunk produced by B (its local event `9`) was silently dropped because it was ≤ 1047. The client assembled a truncated tool result and, because MCP tool results are opaque strings, had no schema-level way to detect the missing prefix. The agent downstream consumed a truncated JSON payload, its parser failed, and it retried the tool call—producing a duplicate side effect. A second observed variant: replica B did not have a migrated event buffer at all (the session store persisted session metadata but not the in-flight SSE append log). B accepted the session, saw `Last-Event-ID: 1047`, found no buffer, and—per a permissive implementation—emitted a fresh `id: 1` event and continued. The client's SSE library, which tracked `Last-Event-ID` as "last seen," now held `1`. On the *next* disconnect it resumed with `Last-Event-ID: 1` against replica C, which had a buffer from `1040..1099` (C had been the original producer before A). C replayed `1040..1099`, and the client received 60 events it had already processed, including a `notifications/progress` sequence that, when re-delivered, caused the agent's progress-based timeout logic to reset and extend a task past its deadline. The invariant that was violated in both cases: **an event ID is only meaningful relative to the producer that issued it, and migration does not transfer that meaning unless the ID space itself is migrated or explicitly fenced.** ## Condition of Validity Resuming with `Last-Event-ID` is valid if and only if the server can establish, at accept time, that the presented ID belongs to the *same event-ID space* as the events it is about to replay or continue. Concretely, one of the following must hold: 1. **Global monotonic ID space.** Event IDs are drawn from a durable, globally ordered sequence (e.g., a shared log with a single writer per session, or a hybrid logical clock with a total order), and every replica that can serve session `S` reads from that same sequence. Migration is then transparent because the ID space is the shared substrate, not the process. 2. **Epoch-fenced IDs.** Event IDs are composite: `(epoch, seq)`, where `epoch` identifies the producer incarnation and is bumped on every migration or restart. The server compares epochs first; if the client's epoch differs from the current producer's epoch, the server MUST reject the resume with a typed error rather than silently continuing. This is the SSE analogue of Raft's term fence. 3. **Explicit resume refusal on migration.** The server records, in the migrated session state, the fact that the producer changed, and any resume request carrying a `Last-Event-ID` from a prior producer is answered with `409 Conflict` (or an MCP-level error) instructing the client to re-establish the stream from a known checkpoint (e.g., re-issue the `tools/call` with an idempotency key, or resume from a server-supplied `resume_token` that encodes the logical position, not the transport position). The invariant fails—and the failure is silent—when the server accepts the session ID as sufficient proof of event-space continuity. Session identity and event-space identity are orthogonal; migration preserves the former and destroys the latter unless explicitly handled. ## Decision Boundary The boundary is crossed at the moment the server's resume handler decides whether to honor or reject a `Last-Event-ID`. The correct decision procedure is: - If the current producer's epoch equals the epoch embedded in (or associated with) the presented `Last-Event-ID`, **honor** it: replay from the buffer, or if the buffer has been trimmed past that ID, return a typed `resume_gap` error telling the client the exact range it missed. - If the epochs differ, **do not honor** it. The server must not attempt numeric comparison across epochs, must not "clamp" to the nearest available ID, and must not silently start a fresh sequence. It must return a resume-rejection that carries the new epoch and, if available, a logical checkpoint (the last fully-acknowledged tool-result boundary) so the client can resume at a semantically safe point rather than a transport offset. - If the server has no record of the presented ID's epoch (because the session migrated without migrating the ID-space metadata), it must treat the ID as **unverifiable** and reject. Unverifiable is not the same as valid; the default must be rejection, because the cost of a false accept (silent truncation or duplication feeding a probabilistic consumer) is strictly higher than the cost of a false reject (one extra round trip to re-establish). The non-obvious part of the boundary: a server that *does* maintain a durable event log but keys it by session ID alone will still pass the first two checks and fail the third, because the log's offsets are per-producer even though the log is shared. The fence must be on the producer, not on the storage. ## Operational Effect When the boundary is respected, the observable behavior is a clean, typed resume failure on migration, and the client's recovery path is deterministic: re-establish the stream, re-request the in-flight operation with an idempotency key, and rely on the server's logical checkpoint to avoid duplicate side effects. Latency cost is one extra round trip per migration; correctness cost is zero. When the boundary is violated, three failure signatures appear, all silent at the transport layer: 1. **Truncated tool results.** The client assembles a result missing a prefix (as in the first trace), the downstream parser fails, and the agent retries—duplicating side effects. This is the most dangerous because the agent's retry logic treats a parse failure as a transient error, not as a continuity violation. 2. **Duplicate event delivery.** The client re-processes events it already consumed (second trace), which for `notifications/progress` and `notifications/message` is not idempotent in the agent's state machine—progress resets extend deadlines, and duplicate log notifications inflate the agent's working set until context saturates. 3. **Resume-to-wrong-position.** Numeric comparison across epochs lands the client at an arbitrary offset in the new producer's sequence, and the stream continues "successfully" from there. There is no error, no gap marker, and the agent has no way to know its view of the stream is inconsistent with the server's. The architectural guardrail is small and cheap: make the event ID self-describing (epoch + sequence), make the resume handler epoch-aware, and make unverifiable IDs a hard reject. The guardrail must live in the transport layer, not in the agent's reasoning, because the agent cannot detect a continuity violation it was never told about—the whole point of the failure is that the stream looks healthy. ```python from __future__ import annotations import re from dataclasses import dataclass class EventSpaceContinuityError(RuntimeError): """Raised when a resume request cannot be proven to belong to the current producer's event-ID space. Never swallow this into a numeric-comparison fallback.""" _EPOCH_SEQ = re.compile(r"^(?P[0-9a-f]{8,}):(?P\d+)$") @dataclass(frozen=True) class EventId: epoch: str seq: int @classmethod def parse(cls, raw: str) -> "EventId": m = _EPOCH_SEQ.match(raw) if not m: raise EventSpaceContinuityError( f"unparseable Last-Event-ID {raw!r}: no epoch fence present" ) return cls(epoch=m.group("epoch"), seq=int(m.group("seq"))) def render(self) -> str: return f"{self.epoch}:{self.seq}" def decide_resume( *, session_id: str, last_event_id_raw: str | None, current_producer_epoch: str, buffer_min_seq: int | None, buffer_max_seq: int | None, ) -> int | None: """Return the sequence number to resume *after*, or None to start fresh. Raises EventSpaceContinuityError when the request must be rejected with a typed resume failure instead of a silent continuation. """ if last_event_id_raw is None: return None try: presented = EventId.parse(last_event_id_raw) except EventSpaceContinuityError: # Unverifiable is not valid. Reject; do not clamp. raise EventSpaceContinuityError( f"session {session_id}: Last-Event-ID {last_event_id_raw!r} " "carries no producer epoch; refusing to resume across an " "unverifiable event space" ) if presented.epoch != current_producer_epoch: # Migration or restart changed the producer. Session ID continuity # does NOT imply event-ID continuity. Reject with the new epoch so # the client can resume from a logical checkpoint. raise EventSpaceContinuityError( f"session {session_id}: Last-Event-ID epoch {presented.epoch!r} " f"does not match current producer epoch " f"{current_producer_epoch!r}; resume rejected, client must " f"re-establish from logical checkpoint" ) if buffer_min_seq is None or buffer_max_seq is None: raise EventSpaceContinuityError( f"session {session_id}: epoch matched but no event buffer is " "attached to this producer; cannot prove replay range" ) if presented.seq < buffer_min_seq - 1: # Buffer trimmed past the requested position: a real gap exists. raise EventSpaceContinuityError( f"session {session_id}: requested resume after seq " f"{presented.seq} but buffer starts at {buffer_min_seq}; " f"gap of {buffer_min_seq - presented.seq - 1} events" ) if presented.seq > buffer_max_seq: raise EventSpaceContinuityError( f"session {session_id}: Last-Event-ID seq {presented.seq} is " f"ahead of producer max {buffer_max_seq}; client and server " "disagree on stream position" ) return presented.seq ```