# Where must an instance reconcile SSE event-ID monotonicity against the MCP `Last-Event-ID` replay window when an HTTP-native stream resumes mid-tool-call? **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers exposing HTTP-native streaming transports (SSE-over-POST, resumable streams keyed by `Last-Event-ID`) where tool invocations emit multiple stream events and the client may disconnect and resume. Does not apply to stdio transports or to fully buffered request/response MCP endpoints with no event log. ## Core Distinction The failure is not "the stream dropped." The failure is that after resumption, the *server's* event log and the *client's* perceived event sequence disagree about which events were already consumed, because SSE event IDs are assigned per-connection on some MCP server implementations while `Last-Event-ID` replay is specified against a per-session log. The boundary case: a tool call whose side effect (filesystem write, external API mutation) is emitted as event `E_k`, where the client received `E_k` but the transport-level ACK (TCP FIN or connection reset) meant the server never marked `E_k` as delivered before the session was evicted and replayed from `E_{k-1}`. The client resumes, receives `E_{k-1}` again, and—if it treats event IDs as a strictly increasing cursor—either silently drops the duplicate (losing the side-effect confirmation) or re-executes the tool (double side effect). The invariant that must hold: *event ID monotonicity is per-session, not per-connection, and the client's resume cursor must be the highest event ID it has durably processed, not the highest it has received on the wire.* ## What Was Observed An MCP client (agent runtime) invoked `write_file` through an HTTP-native MCP server advertising `Last-Event-ID` resumability. The server assigned event IDs from a monotonic counter scoped to the *stream connection*, not the session. During the tool call the connection reset at TCP level after the server had flushed `E_7` (the tool result) but before the client's read loop persisted it. The client reconnected with `Last-Event-ID: 6`. The server, having torn down the prior connection's counter, resumed its new connection's counter at `E_1` and replayed the pending tool result as `E_1`. The client's cursor logic—`if event.id <= last_seen_id: drop`—saw `1 <= 6`, dropped the tool result, and marked the tool call as "no result received," then timed out and retried the invocation. The file was written twice; the second write clobbered a concurrent edit from a sibling agent. No error surfaced in either the client or the server logs; both reported success. The tell was a divergence between the server's session log (which had one `write_file` completion at session-relative position 7) and the client's transcript (which had two `write_file` invocations and zero replayed results). ## Condition of Validity The guardrail holds only when all three of the following are enforced: 1. **Session-scoped event IDs.** The server must assign event IDs from a counter that is durable across connection teardown and bound to the session ID, not the socket. IDs must be strictly increasing within a session and never reused. A reconnecting client's `Last-Event-ID: N` must replay exactly events `N+1..M` from the session log, or return `409 Conflict` if `N` is not in the retained window. 2. **Client-side durable cursor.** The client must persist `last_processed_event_id` to durable storage *after* the side effect of processing that event is committed (e.g., after the tool result is written to the agent's episodic store), not on receipt. Receipt-then-crash must not advance the cursor. 3. **Idempotency key on tool invocation.** Every tool call must carry a client-generated idempotency key that the server records in the session log alongside the event, so a replayed or retried invocation returns the cached result rather than re-executing. When any of these is absent, the resumption path is unsound. The most common real-world gap is (1): many MCP HTTP servers derive event IDs from a per-connection `EventSource`-style counter because that is what the SSE spec's example implementation does, and the spec does not mandate session scope. ## Decision Boundary The agent must treat a resumed stream as *untrusted until the cursor is reconciled*. Concretely: - On reconnect, if the first replayed event ID is **less than or equal to** the client's durable cursor, the client must **not** silently drop it. It must either (a) request a full session snapshot via a separate `GET /session/{id}/state` call and diff against its local state, or (b) abort the session and surface a `StreamCursorDesync` condition to the orchestrator. Silent drop is the failure mode; loud reconciliation is the guardrail. - If the first replayed event ID is **greater than** cursor + 1, the client has missed events and must not process forward; it must request replay from `cursor` explicitly and verify contiguity. - If the server returns `409` (cursor outside retained window), the client must fall back to snapshot reconciliation; it must never assume "no events means no changes." The boundary is sharp: `replayed_id == cursor` is a duplicate (safe to re-ack, must not re-execute); `replayed_id == cursor + 1` is contiguous (safe to process); anything else is a desync requiring reconciliation. ## Operational Effect Without the invariant, the observable failure is *silent double-execution of non-idempotent tools across stream resumption*, with both sides reporting success. The downstream effects compound: the agent's episodic memory records two successful writes, semantic distillation later treats the second as authoritative, and the sibling agent's edit is lost with no audit trail. The blast radius is bounded only by how many non-idempotent tools the agent invokes per session. With the invariant enforced, resumption becomes a bounded reconciliation step: at most one snapshot fetch, at most one idempotency-key replay, and a hard abort on cursor desync. The cost is one extra round-trip per reconnect; the benefit is that "the stream resumed" no longer implies "the agent's state is consistent." The architectural rule: **the durable cursor is the source of truth for resumption, not the wire's last-seen ID, and the server's event log must be session-scoped or the client must refuse to resume.** ```python import hashlib from dataclasses import dataclass from typing import Optional class StreamCursorDesync(RuntimeError): """Raised when a resumed MCP SSE stream cannot be reconciled to the durable cursor.""" pass @dataclass class ResumeState: session_id: str durable_cursor: int # last event ID whose side effect is committed idempotency_key: str # per-tool-call, survives reconnect def reconcile_resume( state: ResumeState, first_replayed_id: Optional[int], server_window_floor: int, server_window_ceiling: int, ) -> str: """ Decide how to handle the first event after a stream resume. Returns one of: 'process', 'reconcile_snapshot', 'replay_from_cursor'. Raises StreamCursorDesync when the server's window cannot satisfy the cursor. """ if first_replayed_id is None: # Server sent no replay event. Could mean "nothing pending" OR "log lost". if state.durable_cursor < server_window_ceiling: raise StreamCursorDesync( f"session {state.session_id}: server reports ceiling " f"{server_window_ceiling} but replayed nothing for cursor " f"{state.durable_cursor}; cannot distinguish empty tail from lost log" ) return "process" if first_replayed_id == state.durable_cursor: # Duplicate of an already-committed event. Safe to re-ack, must not re-execute. return "process" if first_replayed_id == state.durable_cursor + 1: return "process" if first_replayed_id > state.durable_cursor + 1: # Gap: events were lost between cursor and replay start. return "replay_from_cursor" # first_replayed_id < durable_cursor: server rewound below our committed point. # This is the per-connection-counter failure. Refuse to proceed silently. if state.durable_cursor > server_window_ceiling: raise StreamCursorDesync( f"session {state.session_id}: cursor {state.durable_cursor} exceeds " f"server ceiling {server_window_ceiling}; session log was reset or " f"evicted, resumption is unsound" ) return "reconcile_snapshot" def commit_event(state: ResumeState, event_id: int, payload: bytes) -> ResumeState: """Advance the durable cursor only after the side effect is persisted.""" if event_id != state.durable_cursor + 1 and event_id != state.durable_cursor: raise StreamCursorDesync( f"session {state.session_id}: cannot commit event {event_id} " f"out of order against cursor {state.durable_cursor}" ) new_key = hashlib.sha256(payload + str(event_id).encode()).hexdigest()[:16] return ResumeState( session_id=state.session_id, durable_cursor=max(state.durable_cursor, event_id), idempotency_key=new_key, ) ```