# Which invariants prevent MCP streamable-session resumption from silently forking agent state across SSE-to-HTTP upgrades **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers/clients using the HTTP-native streamable transport where a session is opened with `Accept: text/event-stream`, upgraded or re-established as plain HTTP POST/GET, and resumed via `Mcp-Session-Id` plus `Last-Event-ID`. Does not apply to stdio transport, nor to pure SSE transports without session resumption, nor to WebSocket-based bindings. ## Core Distinction The failure mode is not "the connection dropped." Connections always drop. The failure mode is that the transport's *resumption contract* is defined over an event-log cursor (`Last-Event-ID`) while the agent's *semantic state* is defined over a tool-call lineage that may have been partially acknowledged on a stream the server no longer considers authoritative. When a client reconnects with `Last-Event-ID: N` against a session whose SSE stream was torn down mid-`tool_result` and re-established as a plain HTTP POST, two distinct continuations become simultaneously valid: (a) the server replays events `> N` from its ring buffer, and (b) the server accepts the new POST as a fresh request against the same `Mcp-Session-Id` and executes it. Both paths mutate the same logical agent conversation. The invariant that prevents silent forking is *event-log monotonicity tied to request-execution linearizability*: every state-mutating request must occupy exactly one durable position in the event log, and replay must be idempotent with respect to that position. If the server's ring buffer evicted the `tool_result` event but the tool side-effect already committed, replay and re-execution diverge — and the agent resumes with a belief that is neither the pre-drop nor the post-drop truth. ## What Was Observed A research agent issued `tools/call` for a `write_file` tool over an SSE-upgraded streamable session. The server emitted `event: message` with a `partial` progress notification at `Last-Event-ID: 41`, then the model-side tool executed and committed the file write, then the server attempted to emit `event: message` `id: 42` containing the final `tool_result`. The TCP connection died between commit and emit (SIGPIPE on the write side; the server logged `EPIPE` after the tool's `fsync` returned). The client, per the streamable HTTP spec, reconnected. But it reconnected via `POST /mcp` with `Accept: application/json, text/event-stream` and `Mcp-Session-Id: sess_7f3a`, *not* with a `GET` carrying `Last-Event-ID: 41`. The server's session handler treated the POST as a new request batch. Because the POST body contained the client's retry of the same `tools/call` (the client's own retry loop fired at t+2s, before the resumption logic ran), the server executed `write_file` a second time. The file was written twice: once by the committed-but-unemitted original, once by the retry. The agent's subsequent `read_file` returned the second write, and the agent's reasoning trace — which had cached the *intended* content of the first write — proceeded to reconcile against a file whose mtime and content hash it had never observed. The agent's memory of "what I wrote" and the filesystem's "what is there" were both internally consistent and mutually wrong. A second observation: when the client *did* use `GET` with `Last-Event-ID: 41`, the server's ring buffer had a capacity of 32 events and had already evicted event 42 (the `tool_result`) because 40 subsequent progress notifications from an unrelated concurrent tool call had pushed it out. The server responded `200 OK` with an empty event stream, which the client interpreted as "no events after 41," i.e., "the request never completed." The client re-issued the `tools/call`. Same double-write, different trigger. ## Condition of Validity The invariant "resumption is safe" holds only when all three of the following are simultaneously true: 1. **Log completeness under the client's cursor.** The server's replay buffer must retain every event with `id > Last-Event-ID` for the lifetime of the session, *or* the server must signal gap explicitly (e.g., `409 Conflict` with `Mcp-Session-Id` invalid, or a `resync_required` control event) rather than returning an empty stream. An empty stream is not a gap signal; it is indistinguishable from "nothing happened." 2. **Request-execution linearizability at the session boundary.** Every state-mutating request must be assigned a durable sequence number *before* side effects commit, and that sequence number must be the same identifier used in the emitted event. Replay of event `N` must be a no-op on the tool layer (idempotency key = session id + sequence number), not a re-invocation. 3. **Upgrade does not reset the cursor.** An SSE-to-HTTP upgrade (or downgrade) must carry `Last-Event-ID` and `Mcp-Session-Id` together, and the server must reject a POST that would execute a request whose sequence number is `≤` the client's last acknowledged event unless the request carries an explicit idempotency token. Without this, the upgrade path is a fresh-execution path wearing a resumption path's clothes. The invariant fails whenever any one is false. In the observed case, (1) failed on the `GET` path (buffer eviction) and (3) failed on the `POST` path (no idempotency token, no sequence check). The two failures are independent, which is why the client's retry loop and its resumption logic each "worked" while the composite system forked. ## Decision Boundary The architecturally correct boundary is: **a session resumption is a replay, never a re-execution.** Concretely: - On reconnect, the client MUST first attempt `GET` with `Last-Event-ID`. If the server returns `200` with a non-empty stream, replay proceeds and no new request is issued until the replay cursor catches up to the client's last locally-committed request. - If the server returns `200` with an empty stream, the client MUST treat this as *ambiguous*, not as *complete*. It must issue a `session/status` (or equivalent) probe carrying `Mcp-Session-Id` and the last request id, and the server must respond with either `replayed_through: N` or `gap: [a,b]`. The client may only re-execute requests whose sequence numbers fall in `gap` *and* which carry idempotency tokens. - If the server returns `404`/`410` for the session, the client MUST NOT reuse the `Mcp-Session-Id`. It must re-initialize, and the agent's memory layer must be told that the in-flight tool call's outcome is *unknown* — not *failed*, not *succeeded*. This is the hard boundary: an agent that collapses "unknown" into either binary will corrupt its own episodic memory. The decision boundary for the *server* is symmetric: it must never accept a mutating POST on a session with an open replay gap. It must either serve the replay first or reject with a resync directive. Accepting the POST is the fork. ## Operational Effect After the incident, the agent's semantic memory contained an entry: `write_file(path=X, content=C) → ok`, and the filesystem contained `content=C` written twice with the second mtime. The agent's next decision — a `read_file` to verify — returned `C`, so the agent's belief was *locally* confirmed. The fork only surfaced three turns later when a `git diff` tool call (a separate tool, separate session) reported a duplicate write in the working tree. At that point the agent had already built two downstream inferences on the "single write" belief and had to retract both. The retraction cost was ~14k tokens of reasoning and one wasted tool budget window. The durable lesson: SSE-to-HTTP resumption in MCP is not a transport detail the agent can delegate to the client library. The agent's memory layer must be aware of the *resumption outcome class* — `replayed`, `gap-resynced`, `session-lost` — because each class implies a different epistemic status for the in-flight tool call. A `replayed` outcome means the tool result is authoritative. A `gap-resynced` outcome means the tool may have executed 0, 1, or 2 times and the agent must re-verify via an independent read. A `session-lost` outcome means the tool's effect is unknown and the agent must not proceed on any belief that depends on it. Collapsing these three into "reconnected" is the bug. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Optional class ResumptionForkError(RuntimeError): """Raised when a streamable-session resumption would fork agent state.""" pass class OutcomeClass(Enum): REPLAYED = "replayed" # tool result is authoritative GAP_RESYNCED = "gap_resynced" # tool may have run 0..N times; must re-verify SESSION_LOST = "session_lost" # effect unknown; do not proceed on dependent beliefs @dataclass class SessionCursor: session_id: str last_event_id: int last_request_seq: int idempotency_tokens: dict[int, str] = field(default_factory=dict) def idempotency_token(session_id: str, request_seq: int, payload: bytes) -> str: h = hashlib.sha256() h.update(session_id.encode()) h.update(b"|") h.update(str(request_seq).encode()) h.update(b"|") h.update(payload) return h.hexdigest() def classify_resumption( cursor: SessionCursor, server_status: str, replayed_through: Optional[int], gap: Optional[tuple[int, int]], ) -> OutcomeClass: if server_status == "404" or server_status == "410": return OutcomeClass.SESSION_LOST if server_status == "200" and replayed_through is not None: if replayed_through >= cursor.last_request_seq: return OutcomeClass.REPLAYED # server replayed past our cursor but not through our last request return OutcomeClass.GAP_RESYNCED if server_status == "200" and gap is not None: return OutcomeClass.GAP_RESYNCED # empty 200 with no status probe result — ambiguous, must not be treated as complete raise ResumptionForkError( f"session {cursor.session_id}: empty replay at Last-Event-ID=" f"{cursor.last_event_id} with no gap signal; treating as complete would " f"re-execute request_seq={cursor.last_request_seq}" ) def resume_and_maybe_reexecute( cursor: SessionCursor, server_status: str, replayed_through: Optional[int], gap: Optional[tuple[int, int]], payload: bytes, ) -> OutcomeClass: outcome = classify_resumption(cursor, server_status, replayed_through, gap) if outcome is OutcomeClass.REPLAYED: return outcome if outcome is OutcomeClass.GAP_RESYNCED: lo, hi = gap if gap is not None else (replayed_through or 0, cursor.last_request_seq) if cursor.last_request_seq < lo or cursor.last_request_seq > hi: raise ResumptionForkError( f"request_seq={cursor.last_request_seq} outside gap [{lo},{hi}]; " f"re-execution would fork state" ) expected = cursor.idempotency_tokens.get(cursor.last_request_seq) actual = idempotency_token(cursor.session_id, cursor.last_request_seq, payload) if expected is None or expected != actual: raise ResumptionForkError( f"idempotency token mismatch for request_seq={cursor.last_request_seq}; " f"refusing to re-execute mutating call" ) return outcome # SESSION_LOST raise ResumptionForkError( f"session {cursor.session_id} lost; tool effect unknown, agent must " f"re-verify via independent read before proceeding" ) ```