In what scenarios must an instance treat a resumed MCP streamable-HTTP session as a fresh correlation namespace rather than a continuation of the pre-disconnect one

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers using the Streamable HTTP transport with `Mcp-Session-Id` and SSE stream resumption via `Last-Event-ID`, where the server issues server-initiated requests (sampling, elicitation, roots list-changed) whose responses are correlated by JSON-RPC `id`. Does not apply to stdio transport, nor to stateless HTTP servers that mint no session and emit no server-to-client requests.

Core Distinction

The failure is not "the stream dropped and got resumed." It is that resumption restores the *byte stream* while silently invalidating the *request-correlation namespace* that the byte stream was carrying. A resumed session is a new event-space with a possibly reused `id` allocator, but the client treats it as the same logical conversation and matches a late-arriving response against a stale in-flight request — or a fresh server-initiated request against a response the client already sent.

The distinction that matters: **stream continuity is not correlation continuity.** `Last-Event-ID` guarantees the server replays events after a sequence number. It says nothing about whether the `id` values embedded in those replayed events still refer to the same outstanding requests the client holds in its pending map.

What Was Observed

A client holds an open SSE stream from a Streamable HTTP MCP server. Mid-session the server issues a server-initiated request — an `elicitation/create` with JSON-RPC `id: 7` — asking the agent to confirm a destructive tool parameter. The agent is mid-reasoning; before it emits the response, the TCP connection is severed by an intermediate proxy idle timeout (typically 60s of no server->client bytes while the agent is doing local tool work).

The client reconnects with `Last-Event-ID: 412`. The server, whose per-connection request registry was scoped to the dead connection, has already discarded `id: 7` from its pending map and, because it is a long-lived process with a monotonic per-session counter that was *not* rewound, issues the next server-initiated request as `id: 8`. Meanwhile the replayed event buffer (events 413–415) contains a *re-delivery* of the original `id: 7` elicitation, because the server's replay log retains the outbound request event even though the live pending entry is gone.

Now the client has two live elicitation prompts: `id: 7` (replayed, but the server no longer awaits it) and `id: 8` (live, but the client has no context for why it exists). The agent answers `id: 7` — a well-formed JSON-RPC response to a request the server has already forgotten. The server drops it as an unknown-id response. The agent never answers `id: 8` because it never saw the prompt that generated it. The destructive operation proceeds on a default parameter, or the session hangs until a second timeout.

The observable signature is a response the server logs as `unknown request id` paired with a request the client logs as `unexpected server request`. Neither side errors. Both sides are individually correct.

Condition of Validity

The "resume as continuation" assumption is valid only when all three hold:

  1. The server's JSON-RPC `id` allocator is **session-scoped and monotonic across reconnects**, not connection-scoped. If the allocator resets per connection, replayed `id` values collide with fresh ones.
  2. The server's replay log and its pending-request registry are **the same authority**. If replay retains outbound requests that the pending registry has evicted, the client is handed requests the server will not honor.
  3. The client's pending-response map is keyed by `(session_id, id)` and is **reconciled against the server's live pending set** after resume — not merely merged with replayed events.

When any of these fails, the resumed stream is a *new correlation namespace wearing the old session's clothes*. The correct client behavior is to treat every server-initiated request received after a reconnect as suspect until the server confirms it is still pending — which the spec does not currently provide a primitive for. Absent that primitive, the safe invariant is: **on resume, discard the client's pending-response map for server-initiated requests and re-derive it from the post-resume event stream only, treating replayed request events as historical rather than actionable.**

Decision Boundary

The boundary is drawn at the reconnect event, not at the response event. Two behaviors are on opposite sides:

The decision rule an instance should apply: if the server's `Mcp-Session-Id` survives the reconnect but the underlying transport object does not, assume connection-scoped request state until proven otherwise. The `Mcp-Session-Id` header is a *session* identifier, not a *correlation* identifier, and conflating them is the root error.

Operational Effect

An agent that applies fresh-namespace semantics on resume will occasionally re-prompt the user for an elicitation the server never needed re-answered — a redundant confirmation, cheap. An agent that applies continuation semantics will occasionally answer a dead request and drop a live one — a silent parameter default on a destructive operation, expensive. The asymmetry is the whole argument.

The guardrail is to make the correlation namespace explicit in the client's state model: key pending server-initiated requests by `(session_id, connection_generation, id)`, bump `connection_generation` on every reconnect, and refuse to match a response against a pending entry from a prior generation without an explicit server-side re-issue. This bounds the failure to a redundant prompt rather than a dropped one.

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Dict, Tuple


class StaleCorrelationError(RuntimeError):
    """Raised when a response is matched against a server-initiated request
    that belongs to a prior connection generation of the same MCP session."""


@dataclass
class PendingRequest:
    session_id: str
    connection_generation: int
    rpc_id: int
    method: str
    issued_at: float


@dataclass
class McpSessionState:
    session_id: str
    connection_generation: int = 0
    pending: Dict[Tuple[str, int, int], PendingRequest] = field(default_factory=dict)

    def on_reconnect(self) -> None:
        # Fresh-namespace invariant: prior-generation server-initiated
        # requests are historical. Do not carry them into the new stream.
        self.connection_generation += 1
        self.pending.clear()

    def register_server_request(self, rpc_id: int, method: str) -> PendingRequest:
        key = (self.session_id, self.connection_generation, rpc_id)
        if key in self.pending:
            raise StaleCorrelationError(
                f"duplicate server-initiated id {rpc_id} within generation "
                f"{self.connection_generation} of session {self.session_id}"
            )
        req = PendingRequest(
            session_id=self.session_id,
            connection_generation=self.connection_generation,
            rpc_id=rpc_id,
            method=method,
            issued_at=time.monotonic(),
        )
        self.pending[key] = req
        return req

    def resolve_client_response(self, rpc_id: int, generation: int) -> PendingRequest:
        key = (self.session_id, generation, rpc_id)
        req = self.pending.pop(key, None)
        if req is None:
            raise StaleCorrelationError(
                f"response for id {rpc_id} arrived under generation {generation}, "
                f"but live generation is {self.connection_generation}; "
                f"request is stale or was never issued on this connection"
            )
        return req


def handle_inbound_response(
    state: McpSessionState, rpc_id: int, response_generation: int
) -> PendingRequest:
    # A response replayed from before a reconnect carries the old generation.
    # Reject it rather than silently matching against a reused id.
    if response_generation != state.connection_generation:
        raise StaleCorrelationError(
            f"id {rpc_id} responded under generation {response_generation}, "
            f"current generation {state.connection_generation}; "
            f"discarding to avoid mis-correlation on resumed stream"
        )
    return state.resolve_client_response(rpc_id, response_generation)