# Which invariants prevent MCP streamable-transport session reattachment from silently forking an agent's tool-call history **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers and clients using the HTTP-native streamable transport (POST for client→server messages, optional SSE upgrade for server→client streaming) with resumable-event fallback and `Mcp-Session-Id`-based reattachment. Does not cover stdio transport, pure WebSocket transports, or stateless single-request tool servers that never emit a session id. ## Core Distinction The failure mode is not "the connection dropped." It is that a resumable stream and a reattached session are two different recovery primitives with two different identity guarantees, and the transport spec allows a client to satisfy one while violating the other. A resumed SSE stream guarantees **byte-continuity of the server→client event log** from a `Last-Event-ID`. A reattached session guarantees **logical continuity of server-side state** keyed by `Mcp-Session-Id`. When a client reconnects, it typically presents both — but the server may accept the session id while having already discarded the event buffer, or accept the event buffer belonging to a *prior* session incarnation under the same id. The boundary condition is the window in which the session id survives but the event log's causal prefix does not, and the client has no protocol-level way to detect it. This is distinct from ordinary idempotency: MCP tool calls are frequently non-idempotent (file writes, shell exec, message sends), so replaying an unacknowledged event is not free. The invariant that matters is that **an agent must never observe an event stream whose first delivered event is causally after an event it already acted on, unless the server explicitly declares the gap.** ## What Was Observed An agent driver held an open POST-initiated SSE stream (transport upgraded to `text/event-stream`) while executing a multi-step tool sequence. Step 3 (`write_file`) had been dispatched; the client had emitted the request but not yet received the result event. The underlying TCP connection was severed by an intermediary load balancer after 60s idle (the agent was mid-`reasoning` token stream, so no application bytes flowed). The client reconnected per spec: new GET with `Mcp-Session-Id: sess_7f3a...` and `Last-Event-ID: 412`. The server accepted the session id. It had, however, garbage-collected its per-session event ring buffer at the 5-minute mark because the session was flagged `idle` at the transport layer — the idle timer keyed on *last byte written to the socket*, not *last event acknowledged by the client*. The reconnect therefore resumed at event id 418 (the next event the server happened to generate), not 413. The client's `Last-Event-ID: 412` was silently ignored because the buffer no longer contained 412; the server's implementation treated an unresolvable `Last-Event-ID` as "resume from head" rather than "reject with 409/410." The consequence: the client never received the result of the step-3 `write_file`. Its local tool-call ledger still recorded step 3 as `PENDING`. The agent, seeing the stream resume with the step-4 result event (id 418), reasoned that step 3 must have completed and that the missing result was a display artifact. It proceeded to step 5, which read the file it believed step 3 had written. The file did not exist. The agent's subsequent reasoning compounded the phantom write across four more steps before a downstream `read_file` ENOENT surfaced the inconsistency — at which point the agent had already emitted a user-facing summary asserting the write succeeded. The non-obvious part: **nothing in the transport layer threw.** Every HTTP response was 200. The SSE frames were well-formed. The session id was valid. The failure was a *silent causal gap* — a hole in the event log that the protocol permitted the server to paper over with a head-resume. ## Condition of Validity The reattachment invariant holds only under the conjunction: 1. **Event-id monotonicity is per-session, not global.** `Last-Event-ID` is meaningful only relative to the session's own event sequence. A server must not reuse a session id across an event-sequence reset (e.g., after a server restart that re-zeroes the counter). If it does, a client's `Last-Event-ID: 412` can match a *different* event 412 from a prior incarnation — a classic ABA problem at the transport layer. 2. **Unresolvable `Last-Event-ID` is a hard error, not a soft resume.** If the server cannot honor the requested resume point, the only spec-conformant responses are (a) replay the full retained buffer from the earliest retained id *and* signal the gap, or (b) reject the resume with a distinct status so the client can re-initialize the session. Silently resuming from head violates the causal-prefix invariant. 3. **The idle timer must key on client acknowledgment, not socket quiescence.** A long-running tool call (or a long model reasoning turn) produces no server→client bytes for tens of seconds. If the retention clock is driven by socket write activity, the buffer can be evicted while a legitimate in-flight request is outstanding. 4. **Session-id lifetime must exceed event-buffer lifetime, or the two must be co-terminated.** If sessions outlive buffers, reattachment can succeed against a session whose causal history is gone — the exact fork observed. If buffers outlive sessions, a stale session id can resurrect a buffer that should be dead. The safe configuration is co-termination with an explicit `410 Gone` on either. When any of these fails, reattachment degrades from "resume" to "fork": the client continues from a state the server has already abandoned, and the two diverge without a detectable protocol error. ## Decision Boundary The boundary is between **resumable** and **reattachable**, and it must be decided per reconnect attempt, not assumed: - If the client's `Last-Event-ID` is present and the server's retained buffer's minimum id is ≤ that id, the reconnect is a **resume**: the client may trust that all events after that id will be delivered in order, and may replay unacknowledged tool calls. - If the client's `Last-Event-ID` is present but the buffer's minimum id is > that id, the reconnect is a **gap**: the client MUST NOT treat the session as continuous. It must either re-initialize (new session id, full state reconciliation) or, if the server supports it, request an explicit gap manifest. - If the client presents no `Last-Event-ID` but a session id, the reconnect is a **reattach**: the client must assume the entire in-flight event history is unknown and re-derive state from server-side session inspection (e.g., a `tools/list` + resource re-read), not from its local ledger. The dangerous quadrant is the one the observed system occupied: `Last-Event-ID` present, buffer evicted, server resumes from head. The client *believed* it was in the resume case; the server silently placed it in the reattach case. The boundary must be enforced by the server returning a distinguishable status for "cannot honor resume point," so the client's decision logic has a branch to take. ## Operational Effect For an agent, the operational consequence is that **the local tool-call ledger is not authoritative across a reconnect.** Any ledger entry in `PENDING` at the moment of disconnect must be treated as `UNKNOWN` after reattachment unless the server's resumed stream delivers its terminal event. The agent must insert a reconciliation step — a `read_file`, a `list_directory`, or a server-side `session/inspect` call — before using the result of any `PENDING` call in downstream reasoning. Without this, the agent's reasoning chain silently builds on phantom effects, and the error does not surface until an unrelated operation contradicts it, by which point the agent has often already committed user-visible claims. The architectural guardrail is threefold: (1) servers must return a distinct `409 Conflict` (or `410 Gone`) when `Last-Event-ID` cannot be honored, never a head-resume; (2) clients must gate every `PENDING`→`DONE` transition on receipt of the terminal event, and demote `PENDING`→`UNKNOWN` on any reconnect that is not a verified resume; (3) the agent loop must treat `UNKNOWN` tool results as requiring an explicit reconciliation tool call before they enter the reasoning context. The invariant to encode: **no tool-call result may enter the agent's context unless it arrived on a stream whose causal prefix is provably contiguous with the stream on which the call was dispatched.** ## Code ```python import hashlib from dataclasses import dataclass, field class StreamContinuityError(RuntimeError): """Raised when a resumed/reattached MCP stream cannot prove causal continuity.""" pass @dataclass class EventBuffer: session_id: str incarnation: str # bumped on any server restart / counter reset min_retained_id: int max_emitted_id: int retained: dict = field(default_factory=dict) # id -> payload @dataclass class ClientLedger: session_id: str incarnation: str last_acked_id: int pending_calls: dict = field(default_factory=dict) # call_id -> "PENDING" def reattach(buf: EventBuffer, ledger: ClientLedger, last_event_id: int | None) -> list: """ Server-side reattachment decision. Returns the events the client may trust. Raises StreamContinuityError when the client would otherwise silently fork. """ if buf.session_id != ledger.session_id: raise StreamContinuityError( f"session mismatch: server={buf.session_id} client={ledger.session_id}" ) # ABA guard: same session id, different event-sequence incarnation. if buf.incarnation != ledger.incarnation: raise StreamContinuityError( "session id reused across event-sequence reset; " "cannot honor resume point (ABA hazard)" ) if last_event_id is None: # Pure reattach: client must re-derive state, not trust ledger. for call_id in ledger.pending_calls: ledger.pending_calls[call_id] = "UNKNOWN" raise StreamContinuityError( "reattach without Last-Event-ID: in-flight history unknown; " "client must reconcile before trusting PENDING calls" ) if last_event_id < buf.min_retained_id - 1: # Buffer evicted past the requested resume point. Head-resume here # is the silent-fork bug; refuse instead. for call_id in ledger.pending_calls: ledger.pending_calls[call_id] = "UNKNOWN" raise StreamContinuityError( f"Last-Event-ID {last_event_id} below retained floor " f"{buf.min_retained_id}; causal gap cannot be closed" ) if last_event_id > buf.max_emitted_id: raise StreamContinuityError( f"Last-Event-ID {last_event_id} exceeds emitted {buf.max_emitted_id}" ) # Verified resume: contiguous prefix provable. Deliver in order. return [buf.retained[i] for i in sorted(buf.retained) if i > last_event_id] def commit_tool_result(ledger: ClientLedger, call_id: str, event_id: int) -> None: """Only a terminal event on a verified-contiguous stream may promote a call.""" if ledger.pending_calls.get(call_id) == "UNKNOWN": raise StreamContinuityError( f"call {call_id} demoted to UNKNOWN; require reconciliation tool call " f"before result may enter agent context" ) if event_id <= ledger.last_acked_id: raise StreamContinuityError( f"event {event_id} not causally after acked {ledger.last_acked_id}" ) ledger.pending_calls[call_id] = "DONE" ledger.last_acked_id = event_id ```