All Agent Engineering

Handle MCP Streamable HTTP Sessions and Reconnection

An acceptance flow for Streamable HTTP, from transport choice through session ID, recovery and termination.

AINavWritten / Updated
On this page

At a glance

MCP 2025-06-18 defines two standard transports, stdio and Streamable HTTP. In the HTTP case the server is an independent process that communicates through a single MCP endpoint using POST and GET, optionally streaming with SSE. For HTTP MCP connections, session IDs and disconnection events, this task gives an acceptance flow covering transport choice, session recovery and termination conditions.

Runtime and applicability

Article type
Engineering practice
Verified
Applies to
  • MCP Handle MCP Streamable HTTP Sessions and Reconnection

Execution locations and responsibilities

  • MCP client and server Use the workflow below to distinguish responsibilities of the caller, runtime, and external actions.
Engineering workflow order
Engineering workflow order1. Choose the transport and confirm safety preconditions → 2. Connect and fall back to the old transport if needed → 3. Record session information and protocol version → 4. Separate disconnection from cancellation and track unfinished requests → 5. Try to resume the stream and confirm request completion → 6. Handle an expired session → 7. Terminate the session deliberately. Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.1. Choose the transport and confirm safety preconditions2. Connect and fall back to the old transport if needed3. Record session information and protocol version4. Separate disconnection from cancellation and trackunfinished requests5. Try to resume the stream and confirm requestcompletion6. Handle an expired session7. Terminate the session deliberately

Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.

When to use

  • Clients should support stdio whenever possible; with stdio the client launches the server as a subprocess, while Streamable HTTP targets a server running independently. Over HTTP the server must validate the Origin header against DNS rebinding, should bind only to 127.0.0.1 when running locally, and should authenticate all connections.

When not to use

  • Event IDs and resumable streams are optional server capabilities, and the supplied text gives no replay window or retention time, so do not promise that messages are recoverable after a drop; a reopened stream does not mean the original request was answered.
  • A session ID is an identifier assigned by the server; the page requires visible ASCII characters but it is not authentication, and OAuth token and resource matching belong to other topics.
  • This task covers Streamable HTTP and the fallback to old HTTP+SSE only; it does not discuss stdio message framing or custom transports, and the supplied text sets no timeout length for waiting on unfinished requests.

Prerequisites and input

  • You have an HTTP MCP endpoint and know that the server may or may not assign session IDs.
  • The client can log each request's status code, headers used, unfinished requests, and the last SSE event ID received.
  • This client keeps at most one active SSE stream, explicitly linking pending requests and the last event ID to it. Independent cursors for concurrent streams are outside this implementation.

Engineering checks

Transport layer: choice and safety — Clients should support stdio whenever possible; with stdio the client launches the server as a subprocess, while Streamable HTTP targets a server running independently. Over HTTP the server must validate the Origin header against DNS rebinding, should bind only to 127.0.0.1 when running locally, and should authenticate all connections.

Message layer: POST, GET and SSE — Every JSON-RPC message from the client is a new POST, and the Accept header must list both application/json and text/event-stream. For a request the server returns either JSON or an SSE stream and the client must handle both; an accepted notification or response gets 202. A GET can open a separate SSE stream, and the server answers 405 if it offers none.

Session layer: ID, recovery and termination — The server may, but need not, assign a session ID in the Mcp-Session-Id header of the initialization response; once assigned, the client must send it on every later request. A disconnect is not a cancellation; to resume, use GET with Last-Event-ID, and the server may choose to replay messages from that stream. After a session ends the server answers 404 for that ID and the client must initialize again.

1. Choose the transport and confirm safety preconditions

Where: deployment and server configuration. Input: a subprocess, localhost server or remote service. Consider stdio for subprocesses and Streamable HTTP for independent services. Origin validation is specification MUST. Localhost binding for locally run servers and authentication are SHOULD safeguards; inspect remote listeners according to their actual design. This workflow chooses applicable localhost binding and authentication as stricter local gates without converting SHOULD into universal protocol requirements. Completion: record normative strength, environment applicability and local choices. Stop on unmet MUST; pause exposure for unmet locally chosen safeguards without requiring every environment to bind only 127.0.0.1.

2. Connect and fall back to the old transport if needed

Where: first probe of the user-supplied URL. Input: InitializeRequest and Accept. POST first; success selects Streamable HTTP. Only an initial HTTP 4xx follows the documented compatibility GET fallback, using its first endpoint event to identify legacy HTTP+SSE. For initial 5xx, network failure or timeout this workflow stops and records the error rather than falling back; later retries need a separate bounded policy. Completion: record selected transport or failure branch. Both POST and GET failing is the stopping rule only for the 4xx compatibility branch; other initial failures stop/report directly without requiring a nonexistent second attempt. Established-session errors use the later session workflow.If GET yields a legacy endpoint event, record its POST address, hand off to the dedicated legacy HTTP+SSE initialization/communication workflow and end this procedure. Do not enter the following Streamable HTTP steps. Steps 3–7 apply only to Streamable HTTP after a successful InitializeResult.

3. Record session information and protocol version

Where: the initialization response and every later HTTP request. Input: the headers of the InitializeResult response. Action: check for Mcp-Session-Id; if present, store it and attach it to all later requests; if absent, treat the server as sessionless, which is a valid outcome. In both cases send the negotiated MCP-Protocol-Version header. Completion check: "session" or "no session" is recorded and the protocol version is stored. Stop condition: treat a 400 only as an HTTP error and inspect the response body and request context; possible causes include a missing session ID on a non-initialization request and an invalid or unsupported protocol version, but the list is not exhaustive.

4. Separate disconnection from cancellation and track unfinished requests

Where: the client's SSE read loop. Input: a connection drop event and the requests in flight at that moment. Action: do not treat the drop as cancellation; if cancelling is intended, send a CancelledNotification explicitly. Register the interrupted request as unfinished. Completion check: logs hold "disconnected" and "cancelled" as distinct records, and every unfinished request is registered. Stop condition: the specification sets no wait limit; the implementer must define and record a timeout or abandonment policy, and when it expires the request is marked unresolved and waiting stops. Associate pending requests with the single active stream. Before another stream starts, end this one or retain its unresolved record; the event ID is not a global cursor.

5. Try to resume the stream and confirm request completion

Where: the client's reconnect logic. Input: the last SSE event id received and the list of unfinished requests. Action: send a GET to the MCP endpoint with Last-Event-ID and an Accept header requesting text/event-stream. Completion check: reopening an event stream only restores the connection; a request is complete only when its matching JSON-RPC response arrives, otherwise it stays registered as unresolved. Stop condition: event IDs are optional for servers, and a server must not replay messages from another stream; on a 405, when no ID exists, or when replay fails, do not assume recovery, treat the request as unfinished and apply the abandonment policy from the previous step. The saved Last-Event-ID and pending requests must belong to the stream being resumed; verify only that stream’s matched responses.

6. Handle an expired session

Where: the client's status code handling. Input: the response to a request carrying Mcp-Session-Id. Action: on 404, discard the old session ID and send a new InitializeRequest without one. Completion check: initialization succeeds and the new result replaces the old session record. Stop condition: if initialization still fails, stop retrying and report; never reuse the old ID.

7. Terminate the session deliberately

Where: the client's exit path. Input: a session ID no longer needed (applicable only if the server assigned one). Action: send an HTTP DELETE to the MCP endpoint with Mcp-Session-Id. Completion check: the server's status code is logged. Stop condition: a 405 means the server does not let clients end sessions; just stop using the ID and do not retry the DELETE.

Task example

This is a hypothetical manual walkthrough, not a real run. Suppose the client first POSTs an initialization that succeeds, and the server returns a session ID that the client adds to every later request. An SSE stream for a long request drops midway; the expected behavior is that the client sends no cancellation, registers the request as unfinished, and tries a GET with the last event ID. If the server answers 405, the request stays unresolved until the implementer-defined abandonment policy applies. In another imagined case the server returns no session ID, and the client works normally without a session header. If the server later ends a session, a 404 is expected, and the client starts a fresh initialization with no session ID. All of this is an expected observation and has not been verified.

Completion checks

  • Transport check: is the reason for the choice written down, are Origin validation, localhost binding and authentication each backed by a configuration record, and did a 4xx on the initial probe lead to the old-transport check?
  • Session check: does every request after initialization carry MCP-Protocol-Version; if the server assigned an ID, does each also carry Mcp-Session-Id, does a 404 trigger re-initialization, and is a missing session ID accepted as valid?
  • Termination check: do disconnect, cancellation, failed resume (including a request with no matching response) and a rejected DELETE (405) each have a defined end state?
  • The recovery record links the stream, its last event ID and its pending requests, with no concurrent SSE stream opened during this procedure.
  • The legacy endpoint branch ends with a handoff. Later session headers, reconnection and DELETE apply only to successfully initialized Streamable HTTP.

Verification scope

Written only from the supplied Transports page of the MCP 2025-06-18 specification. The documentation was read; installation, login, API execution and output were not tested.

Sources

All links are official pages; verification dates are listed per source, and links point to the version checked.

  1. MCP · MCP documentation: mcp-transports

Found an error? Tell us →