# Under what conditions must an instance treat an MCP `Last-Event-ID` resumption as a forked session rather than a replay, and how does a half-delivered tool call corrupt the resumed context? **Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers exposing HTTP-native transports (Streamable HTTP with SSE-style chunked event streams) where tool-call results are delivered as discrete events over a resumable stream and the client reconnects with `Last-Event-ID`. Does not apply to stdio transports, nor to HTTP transports that buffer the entire response and deliver it atomically without an event log. ## Core Distinction The distinction that matters is between a **replay** and a **fork**. A replay re-delivers events the client already acknowledged and is idempotent by construction: the server holds a durable event log keyed by monotonic event IDs, and `Last-Event-ID: N` means "resume delivery strictly after event N." A fork is what actually happens when the server *cannot* prove it still holds event N+1 in the same logical stream generation — because the stream was garbage-collected, the session was reaped, or the server restarted and reassigned event IDs from a fresh counter. In the fork case the server silently begins a *new* stream whose first event may carry an ID that is numerically greater than `N` but semantically unrelated to it. The client, which only checks monotonicity, accepts it as a continuation. The invariant that must hold for correctness is not "event IDs are monotonic." It is: **event ID `N` and event ID `N+1` belong to the same stream generation, and the server can attest to that generation on resumption.** Monotonicity is a necessary but wildly insufficient proxy. ## What Was Observed A tool-calling agent issued a `tools/call` for a long-running operation (a log scan) over a Streamable HTTP MCP session. The server emitted the call as a sequence of SSE events: `event: message` with an initial `accepted` payload, then incremental `progress` events, then a terminal `result` event carrying the tool output. Each event carried an `id:` field. The agent's HTTP client read the stream, and at event `id: 47` the underlying TCP connection was reset by an intermediate proxy during a keepalive gap. The client reconnected and sent `Last-Event-ID: 47`. The server's session store had a 60-second idle TTL keyed on last *request* time, not last *event emission* time, and the tool had been running for 90 seconds. The session record had been reaped. On receiving the resumption request the server, lacking the session, fell back to its stateless path: it created a fresh session, re-executed the tool call from scratch (the call was not memoized), and began emitting events from `id: 1` of the new generation. Here is the failure: the client's resumption logic did not validate the generation. It had a local expectation of "next event ID > 47." It received `id: 1`. A defensive client rejects that. This client, however, had a fallback that treated a *lower* event ID as "server restarted the counter, treat as new stream" and **re-attached to the new stream while retaining the old partial result buffer**. The agent had already accumulated progress events 1–47 into a partial transcript and was holding a half-populated tool-result object. The new generation's events 1–N were appended to that same buffer. The agent's context now contained two interleaved progress sequences from two distinct executions of the same `tools/call`, with overlapping event IDs and divergent intermediate values. The final `result` event from the second execution was accepted as *the* result. The partial buffer from the first execution was never discarded. When the agent later reasoned over its own transcript ("I saw the scan report 3 matches, then 5 matches"), it had no way to know those were two runs, not one run that changed its mind. It reported a nondeterministic result as if it were a single observation. ## Condition of Validity `Last-Event-ID` resumption is valid — i.e., constitutes a replay — **if and only if** the server can bind the resumption request to the same stream generation that produced event `N`. Concretely, all of the following must hold: 1. The event log for the session is durable for at least the maximum tool-call execution time, and the TTL is keyed on *event emission* activity, not request arrival. 2. Event IDs are scoped to a generation token (e.g., `gen:seq` or a server-issued opaque cursor that encodes generation), so that a client can detect a generation change even when the sequence restarts. 3. The server either replays from `N+1` within the same generation, or responds with an explicit `session_expired` / `resume_rejected` signal that forces the client to treat the prior partial state as **abandoned**, not continued. 4. Re-execution of a non-idempotent tool call on resumption is either memoized against a call key or explicitly surfaced as a new execution with a new call identity. If any of these fail, the resumption is a **fork**, and the client must not splice new events onto old partial state. The invariant the client must enforce: *a tool-call result buffer is bound to a single stream generation and a single call identity; a generation change invalidates the buffer.* ## Decision Boundary The boundary is drawn at the point where the client decides what to do with the first event received after a resumption request. Three cases: - **Same generation, sequence continues (`N+1`):** replay. Append. Continue. - **Same generation, sequence gap (`N+k`, k>1):** the server dropped events (backpressure, log truncation). This is a *lossy replay*. The client must not treat the gap as benign — it should surface a `resume_gap` and, for tool calls where intermediate events carry semantic state (progress, partial results), discard the partial buffer and re-issue the call with a fresh call identity. - **Generation change (new token, or sequence restart to `1`, or explicit expiry signal):** fork. The prior partial state is **orphaned**. The client must discard the old buffer, adopt the new generation's call identity, and — critically — must not let the agent's context retain the orphaned partial transcript as if it were part of the same observation. The subtle trap is the second case. A gap looks like a replay with missing events, and the instinct is to keep the buffer and just note "some progress events lost." But for a tool call whose terminal `result` is computed by the server from the full event sequence, a gap means the client's partial view and the server's final result are inconsistent, and any agent reasoning that mixes them is reasoning over a chimera. ## Operational Effect The observable consequence of getting this wrong is **silent result contamination**: the agent's episodic memory of a tool call contains fragments of two executions, and downstream reasoning treats the contradiction (3 matches vs. 5 matches) as a property of the world rather than a property of the transport. This is worse than a hard failure, because a hard failure triggers retry logic; contamination does not. The agent proceeds, cites a result that no single execution produced, and the error is laundered through the final answer as if it were grounded. The guardrail is architectural, not prompt-level: the stream reader must own a `CallBuffer` keyed by `(call_id, generation)`, and any generation mismatch must raise before the buffer is mutated. The agent layer must never see events from two generations in one buffer. The following enforces that boundary at the client edge. ```python from dataclasses import dataclass, field from typing import Optional class StreamGenerationFork(RuntimeError): """Raised when a resumption crosses stream generations or loses events.""" pass @dataclass class CallBuffer: call_id: str generation: str last_seq: int = 0 events: list = field(default_factory=list) terminated: bool = False def accept(self, event: dict) -> None: if self.terminated: raise StreamGenerationFork( f"event after terminal for call {self.call_id}" ) gen = event["generation"] seq = event["seq"] if gen != self.generation: # Fork: server restarted the stream. Prior partial state is orphaned. raise StreamGenerationFork( f"generation change on call {self.call_id}: " f"{self.generation!r} -> {gen!r} at seq {seq} " f"(held {len(self.events)} events, last_seq={self.last_seq})" ) if seq != self.last_seq + 1: # Lossy replay: gap within the same generation. Partial buffer is # not a valid prefix of the server's computation. raise StreamGenerationFork( f"sequence gap on call {self.call_id}: " f"expected {self.last_seq + 1}, got {seq}" ) self.events.append(event) self.last_seq = seq if event.get("terminal"): self.terminated = True def resume_stream( buffer: CallBuffer, last_event_id: Optional[str], incoming: list[dict], ) -> CallBuffer: """Reattach a resumption response to an existing buffer, or fail closed.""" if last_event_id is not None and not incoming: raise StreamGenerationFork( f"empty resumption for call {buffer.call_id} at {last_event_id}" ) for event in incoming: buffer.accept(event) return buffer ```