MCP: Model Context ProtocolBeginnerModule 04 — MCP protocol lifecycle
What happens when an MCP connection is interrupted?
Question 36 of 43 · Updated
On this page
- Direct answer
- 1. Separate transport interruption, session loss and business state
- 2. Failure detection and local admission
- 3. Recovery decision flow
- 4. Stdio interruption
- 5. Historical Streamable HTTP session continuity and expiry
- 6. Optional SSE resumption
- Acknowledgment and application processing
- 7. Outstanding requests during recovery
- 8. Why an interrupted request may have succeeded
- 9. Reinitialize, rediscover and reject stale routing
- 10. Tested Python example: model session recovery decisions
- What the tests establish
- Deliberate limitations
- 11. Production recovery policies and operational checks
- Interview-ready answer
Direct answer#
When an MCP connection is unexpectedly interrupted, the implementation must distinguish the loss of a transport path from the loss of the logical protocol relationship. A network connection or server-sent event stream may fail while the server still retains a valid session. A local stdio subprocess may instead exit, destroying the relationship. The appropriate recovery depends on the selected MCP revision, transport, session state, available resumption mechanisms and application policy.
Do not assume that all unanswered requests failed to execute. A server may have received a request and committed a business operation before the response path broke. A client should temporarily stop or restrict affected dispatch, determine whether the existing relationship can safely resume, and either recover its permitted communication state or abandon unresolved exchanges and establish a genuinely new relationship.
In historical MCP 2025-06-18 Streamable HTTP, a server may provide SSE event IDs for optional resumption. A client may reconnect with Last-Event-ID to request replay of the relevant stream. If a request carrying an assigned MCP-Session-Id receives HTTP 404 because the session has terminated, the historical client must start a new session with a fresh initialize request without that old session ID. This is distinct from replaying the original business request.
Learning continuity: Q34 explained pending-request correlation, Q38 failed initialization, Q41 method admission and Q42 intentional shutdown. Q43 focuses on unexpected transport loss, continuity evidence and recovery decisions. Q81–82 and Q85–92 cover transport details; Q170–171 and Q227 cover deadlines and retry policies; Q230–231 develop durable idempotency and business reconciliation. Q44 compares lifecycle designs only where revision-specific evidence is available.
Verification scope: Authorized offline research and changelog exceptions applied. Historical MCP 2025-06-18 is the reference baseline; it is not a claim about the latest specification. Official links and later revisions were not checked live. Python 3.13.5 syntax compilation and 12 named unittest tests with warnings treated as errors genuinely passed. The example models recovery transitions, not live SSE, HTTP, stdio or MCP SDK behavior. The MCP SDK and Mermaid CLI were unavailable locally; interoperability and Mermaid/frontend rendering remain unverified.
1. Separate transport interruption, session loss and business state#
Consider a support host using a remote inventory integration. During a stock request, the HTTP connection drops. The host has several independent questions to answer.
| Layer | Question | Example consequence |
|---|---|---|
| Physical connection | Can bytes still travel on this socket or pipe? | Open a replacement transport path if supported |
| Logical session | Does the server still recognize the negotiated relationship? | Preserve state only when continuity is established |
| Response delivery | Can the original response still be obtained? | Resume the appropriate stream if supported |
| Business execution | Was the requested operation actually applied? | Obtain authoritative evidence; do not infer from transport status |
A transport connection is not automatically a logical session. In Streamable HTTP, successive requests may use different underlying HTTP connections while belonging to the same assigned MCP session. One terminated SSE stream does not necessarily invalidate other streams or the entire relationship.
Conversely, a new transport connection is not proof of continuity. If a local subprocess exits and the host launches another process, treat the replacement as a new relationship and perform the applicable lifecycle. Do not assume its in-memory state, subscriptions or pending requests survived.
The application also needs to distinguish a connection that is usable for other operations from one whose particular response stream is interrupted. A host may choose to quarantine the affected relationship during recovery. This is a defensive local policy, not a requirement that every isolated stream failure disables all unrelated requests.
2. Failure detection and local admission#
Interruption can become visible in different ways:
| Observation | What it establishes |
|---|---|
| EOF on the stdio output | That output path has ended |
| Subprocess exit status | The owned process exited |
| HTTP read timeout | The awaited communication did not finish within the local budget |
| SSE connection closure before the expected result | That stream ended without a confirmed outcome |
| HTTP 404 on a request carrying a previously assigned session ID at the correct MCP endpoint | Under the historical session contract, the session must be replaced |
| Successful ping | A responsiveness exchange succeeded, not that every prior request completed |
An idle SSE stream may be healthy. Absence of a notification for an arbitrary period is not by itself proof of a failure. Likewise, an ordinary HTTP exchange may close normally after delivering its complete response. Detect interruption using the transport's actual completion semantics and applicable local deadlines, not merely the fact that a socket closed.
The client should prevent affected stale routes from dispatching while it is determining continuity. It should preserve trusted evidence needed for recovery: the accepted revision, assigned session identifier where applicable, outstanding requests, event cursor and source stream association if supported. Keep that state scoped to the approved endpoint and identity. A token or session identifier from another relationship cannot repair this one.
Bound pending work and recovery time. A pending operation should not wait forever because resumption might someday become possible.
3. Recovery decision flow#
This diagram is an application recovery model. It does not prescribe a standardized MCP recovery state machine, a universal continuity probe or an automatic retry loop. The bounded checks terminate when their configured budget expires; if continuity cannot be established, abandon the affected local relationship and use the supported replacement procedure if appropriate.
Session continuity, stream recovery and replaying an application request are different decisions. Resuming a stream can recover a response without executing the original operation again. A new session restores communication but does not recover a prior business operation by itself.
4. Stdio interruption#
In the historical stdio transport, the client typically owns a local server subprocess and exchanges UTF-8 newline-delimited JSON messages over its standard input and output.
If the subprocess exits or its pipes fail:
- Disable the affected route.
- Stop accepting ordinary operations through that transport.
- Resolve outstanding local waiters using an appropriate connection failure or unconfirmed-outcome classification.
- Release owned pipes, reader tasks and process resources.
- If recovery is permitted, launch an approved replacement process.
- Initialize the new relationship and discover its current authorized features.
A process restart is not a request resumption mechanism. The historical stdio transport does not define SSE event replay for these pipes. A replacement server may use the same executable, configuration and durable database, but its previous protocol state may be gone.
For a process that terminated unexpectedly, collect the exit status and protected diagnostics. Keep ordinary logs separate from the JSON-RPC output channel. A process crash, an invalid protocol frame and a downstream API failure are different problems; choose a recovery path based on actual evidence. Q82 covers crash diagnosis and local process recovery in detail.
A business operation may still have committed to a durable downstream database before the process crashed. Relaunching the server does not reverse that commit.
5. Historical Streamable HTTP session continuity and expiry#
In the 2025-06-18 historical transport, a server may assign an MCP-Session-Id in the HTTP response carrying the initialization result. When assigned, the client must include it in subsequent applicable HTTP requests. After initialization the negotiated revision also belongs in the MCP-Protocol-Version header under this historical contract.
The session identifier is distinct from a JSON-RPC request ID and from a credential. Treat it as sensitive relationship metadata and keep it attached to the approved server and authenticated context. Do not use it as the sole authorization mechanism.
The server can terminate the session at any time. The historical transport requires HTTP 404 for requests containing a session identifier that has been terminated; the client receiving HTTP 404 in response to a request containing a session ID must start a new session by sending a new initialize request without a session ID.
This rule applies to the established MCP endpoint and relevant historical transport context. It does not mean that every 404 from a downstream REST API, a mistyped endpoint or unrelated resource implies MCP session expiry. A client needs to know which HTTP interaction generated the response. Authentication and endpoint configuration must remain independently valid.
For example, the client previously used the following illustrative headers:
HTTPMCP-Session-Id: old-session MCP-Protocol-Version: 2025-06-18
After the applicable 404, it must not endlessly resend the same ordinary request with old-session. It should establish a new relationship with a fresh initialize request that does not include that old session identifier. The complete new initialize message and its HTTP framing depend on the applicable contract. Q36 covers the historical handshake.
If the server assigns a new session ID, retain that new value only after the required validation. Re-establish readiness, rediscover applicable capabilities and prevent old session state from authorizing work on the replacement.
Some historical deployments do not assign a session identifier at all. Do not invent one or apply the assigned-session 404 branch blindly to them. Use the selected server and transport contract.
6. Optional SSE resumption#
Historical Streamable HTTP can carry JSON-RPC messages over server-sent event streams. The 2025-06-18 transport allows servers to attach event IDs. If present, the IDs must be globally unique across streams within the session, or across streams for the client when session management is not used, and should encode enough information for the server to identify the originating stream.
If a stream disconnects, the historical client may issue an HTTP GET to the MCP endpoint with Last-Event-ID containing its last received event ID to resume that stream. The server may replay messages that would have been sent after that cursor and resume the stream. It must not use replay to deliver messages that belong to a different stream.
An illustrative request fragment:
HTTPGET /mcp HTTP/1.1 Accept: text/event-stream MCP-Session-Id: current-session MCP-Protocol-Version: 2025-06-18 Last-Event-ID: event-cursor-42
The endpoint, session identifier and event cursor are fictional. The fragment omits required authentication, host and other transport details. In an actual implementation use the last received event ID, not a guessed or incremented value. An event ID is an opaque transport cursor; it is not the JSON-RPC request identifier, a business operation ID or proof of completed application processing.
The diagram is an illustrative supported resumption path. It does not guarantee that every server stores replayable events or returns the original result. The relevant cursor belongs to the original stream. In a client consuming multiple streams, maintain the appropriate stream-specific state rather than one arbitrary global cursor that overwrites the others.
Replay is optional. A server may not emit event IDs, may not retain the needed event history or may have terminated the session. The specification does not establish an unlimited replay window or exactly-once business execution. A GET resumption attempt is not a second POST of the original tool call.
Historically, disconnection should not be interpreted as cancellation of a request. Use the applicable explicit cancellation mechanism where permitted. Connection loss and cancellation notification semantics are separate from durable business cancellation.
Acknowledgment and application processing#
Receiving an SSE event and successfully processing its contents are distinct milestones. The historical resumption header uses the last received event ID. A durable application that must tolerate crashes between receipt and processing may additionally need a local persistence and processing strategy. Do not redefine Last-Event-ID as a standardized business commit cursor or claim that transport replay alone guarantees that a workflow will never lose or duplicate application effects.
7. Outstanding requests during recovery#
If the implementation can safely preserve the original logical session and relevant stream association, it may retain the corresponding outstanding operations within a bounded deadline. Validate any recovered result using the original request context. Do not allocate a new ID for an original exchange merely because its response stream was resumed.
If the exchange cannot be recovered, resolve the local waiter with a controlled communication failure or unconfirmed outcome. Preserve enough business context to reconcile side effects when appropriate. Once a request is locally terminal, a late or duplicate response must not resolve a different operation or reverse the local terminal transition.
The historical ID non-reuse rule remains scoped to the same requestor within the same session. A physical reconnect is not permission to reset an allocator. A genuinely new session establishes a new correlation scope. Stale callbacks from the prior scope must be rejected even if their numeric IDs match new requests.
A useful local routing key is a trusted connection generation plus the typed request ID. The generation is an application concept, not an MCP header or standardized field. Multiple concurrent streams in the same session still require correct transport and message association.
Q34 develops the actual future-resolution algorithm. In this lesson the essential distinction is whether to preserve an existing pending exchange or abandon it during recovery.
8. Why an interrupted request may have succeeded#
Consider a fictional reservation tool. Its server performs the following actions:
- Accepts the authorized request.
- Commits a reservation to the authoritative inventory database.
- Attempts to send the result.
- Loses its response stream before the client receives the receipt.
From the host's perspective, no valid outcome arrived. The reservation might nevertheless exist.
| Evidence available | Safe interpretation |
|---|---|
| Verified matching successful receipt | Confirmed according to the business contract |
| Verified definitive rejection | Rejected according to the business contract |
| Proven request never admitted or transmitted under reliable local evidence | No execution attributable to that attempt under those assumptions |
| Interrupted request after possible delivery | Unconfirmed; actual execution is uncertain |
| New session successfully initialized | Communication restored, prior outcome not established |
For an uncertain write, do not automatically send the same action again. If the authoritative service supports an appropriate durable business idempotency key or status lookup, use the authorized recovery contract. A new JSON-RPC request ID is not a substitute for a durable business key.
For an observational read, a new authorized read may be acceptable under a bounded retry policy, but its result is a new observation, not proof of the old result. A tool described as read-only must actually satisfy the application's safety contract before that assumption is relied upon.
The user-facing result should preserve uncertainty. For example: "The inventory connection was interrupted before confirmation. I can't confirm whether the reservation was applied." Do not announce failure or success as established fact until trustworthy evidence resolves the outcome.
Detailed retry taxonomy and reconciliation algorithms belong to Q171 and Q230–231.
9. Reinitialize, rediscover and reject stale routing#
A new relationship may differ from the old one even if the endpoint is unchanged. A deployment could have changed the protocol revision, supported capability families, tool catalog, input schemas, resource permissions or subscriptions.
After replacement:
- Verify the endpoint and applicable authentication context.
- Complete the correct revision-specific initialization.
- Interpret the new capability declarations and perform required discovery.
- Rebuild or validate the relevant trusted route metadata.
- Re-establish supported subscriptions if the task still needs them and authorization permits.
- Admit ordinary work only after the applicable readiness checks.
A cached tool descriptor from a previous session is not enough to dispatch through its replacement. A tool named stock may have changed its input schema, become unavailable to the current user or be replaced entirely. Revalidate any queued plan and its approval binding.
For example, the old session uses numeric ID 1 for reserve, and a replacement session later uses ID 1 for availability. If a delayed callback from the old reader delivers its result after replacement, matching on numeric ID alone could attach the reservation receipt to the wrong operation. Bind the callback to the old trusted generation and reject it for the new session.
Isolation also matters for multi-server hosts. A policy server may remain healthy while an inventory stream fails. Do not suspend unrelated safe work unless the failure affects a shared dependency or task correctness requires both sources.
10. Tested Python example: model session recovery decisions#
The following dependency-free Python exercise models the client-local recovery decisions. It assumes a historical session-bearing HTTP relationship and a single relevant resumable stream. It preserves pending exchanges and the ID counter when continuity is confirmed, discards them as unconfirmed on abandonment, and gates replacement dispatch until discovery is completed.
All transport classifications and delivered response values are injected by a trusted fixture. The example does not perform real HTTP or SSE operations. Its method named session_expired represents an already classified historical session-expiry 404, not a generic handler for every HTTP 404.
Save as mcp_q43.py:
PYTHONimport unittest from dataclasses import dataclass, field @dataclass class Recovery: generation: int = 1 session: str = 's1' state: str = 'ready' next_id: int = 0 catalog: tuple = ('stock',) pending: dict = field(default_factory=dict) outcomes: dict = field(default_factory=dict) cursor: str | None = None def issue(self, operation): if self.state != 'ready' or operation not in self.catalog: raise ValueError('route_unavailable') self.next_id += 1 key = (self.generation, self.next_id) self.pending[key] = operation return key def interrupted(self, cursor=None): if self.state != 'ready': raise ValueError('unexpected_state') self.state = 'interrupted' self.cursor = cursor def resume_headers(self): if self.state != 'interrupted' or self.cursor is None: raise ValueError('resume_unavailable') return {'MCP-Session-Id': self.session, 'MCP-Protocol-Version': '2025-06-18', 'Last-Event-ID': self.cursor} def resumed(self): # Trusted transport adapter established continuity of this stream. if self.state != 'interrupted' or self.cursor is None: raise ValueError('resume_unavailable') self.state = 'ready' def response(self, key, value): if self.state != 'ready' or key not in self.pending: return False del self.pending[key] self.outcomes[key] = ('received', value) return True def abandon(self): for key in self.pending: self.outcomes[key] = ('unconfirmed', None) self.pending.clear() self.catalog = () self.cursor = None self.state = 'unavailable' def session_expired(self): # Adapter classified a 404 on a request carrying the session ID. self.abandon() self.session = '' self.generation += 1 self.next_id = 0 self.state = 'initializing' def initialize_accepted(self, session): if self.state != 'initializing' or not session: raise ValueError('unexpected_state') self.session = session self.state = 'discovering' def rediscovered(self, catalog): if self.state != 'discovering': raise ValueError('unexpected_state') self.catalog = tuple(catalog) self.state = 'ready' class Tests(unittest.TestCase): def setUp(self): self.r = Recovery() def test_interruption_blocks_dispatch(self): self.r.interrupted('e1') with self.assertRaisesRegex(ValueError, 'route_unavailable'): self.r.issue('stock') def test_resume_headers(self): self.r.interrupted('opaque-e1') self.assertEqual(self.r.resume_headers(), { 'MCP-Session-Id': 's1', 'MCP-Protocol-Version': '2025-06-18', 'Last-Event-ID': 'opaque-e1'}) def test_no_cursor(self): self.r.interrupted() with self.assertRaises(ValueError): self.r.resume_headers() def test_resume_preserves_pending_and_ids(self): key = self.r.issue('stock') self.r.interrupted('e1') self.r.resumed() self.assertTrue(self.r.response(key, 7)) self.assertEqual(self.r.issue('stock'), (1, 2)) def test_duplicate_replay(self): key = self.r.issue('stock') self.assertTrue(self.r.response(key, 7)) self.assertFalse(self.r.response(key, 9)) self.assertEqual(self.r.outcomes[key], ('received', 7)) def test_abandon_uncertain(self): key = self.r.issue('stock') self.r.interrupted() self.r.abandon() self.assertEqual(self.r.outcomes[key], ('unconfirmed', None)) self.assertFalse(self.r.pending) self.assertFalse(self.r.catalog) def test_expired_session(self): key = self.r.issue('stock') self.r.session_expired() self.assertEqual(self.r.generation, 2) self.assertEqual(self.r.session, '') self.assertEqual(self.r.outcomes[key], ('unconfirmed', None)) self.assertEqual(self.r.state, 'initializing') def test_discovery_gate(self): self.r.session_expired() self.r.initialize_accepted('s2') with self.assertRaises(ValueError): self.r.issue('stock') self.r.rediscovered(('availability',)) with self.assertRaises(ValueError): self.r.issue('stock') self.assertEqual(self.r.issue('availability'), (2, 1)) def test_stale_generation(self): old = self.r.issue('stock') self.r.session_expired() self.r.initialize_accepted('s2') self.r.rediscovered(('stock',)) new = self.r.issue('stock') self.assertEqual(old[1], new[1]) self.assertFalse(self.r.response(old, 9)) self.assertTrue(self.r.response(new, 7)) def test_no_automatic_replay(self): self.r.catalog = ('reserve',) old = self.r.issue('reserve') self.r.session_expired() self.r.initialize_accepted('s2') self.r.rediscovered(('reserve',)) self.assertFalse(self.r.pending) self.assertEqual(self.r.outcomes[old], ('unconfirmed', None)) def test_premature_rediscovery(self): self.r.session_expired() with self.assertRaises(ValueError): self.r.rediscovered(('stock',)) def test_independent_relationship(self): other = Recovery(session='other') self.r.interrupted() self.r.abandon() self.assertEqual(other.issue('stock'), (1, 1)) if __name__ == '__main__': unittest.main(verbosity=2)
Run on Python 3.10 or later:
BASHpython -m py_compile mcp_q43.py python -W error mcp_q43.py
Actual local output summary on Python 3.13.5:
Ran 12 tests in 0.000s
OKWhat the tests establish#
| Test group | Count | Demonstrated property |
|---|---|---|
| Interruption gate, resume headers and missing cursor | 3 | Affected ordinary work stops; supported cursor information is preserved |
| Resume preservation and duplicate replay | 2 | Original pending association and non-reuse of IDs survive modeled continuity |
| Abandonment and expired session | 2 | Unconfirmed outcomes retained, old catalog and pending entries cleared, session ID removed on expiry |
| Discovery gate and stale generation | 2 | Replacement requires rediscovery and cannot consume an old-generation response |
| No automatic replay, premature rediscovery and independent relationships | 3 | Old reserve request is not resent, invalid state transitions blocked and other owner unaffected |
The fixture intentionally stores the old operation's unconfirmed state instead of inventing a successful or unsuccessful business result. A fresh generation permits restarting the local counter after the modeled old session has terminated. The test_stale_generation case verifies that even when IDs match numerically, the old key cannot complete the new entry.
The resume_headers function returns only three relevant historical headers, not a complete GET request. The test verifies exact preservation of the opaque cursor. The resumed transition is an injected decision that the real transport adapter would have to establish; it does not establish continuity merely by possessing a cursor.
Deliberate limitations#
This is a synchronous in-memory policy fixture. It does not implement a full initialize exchange, actual HTTP status classification, network I/O, SSE parser, replay buffer, retry loop, real deadlines, request waiters or transport cleanup. It assumes one session with an assigned identifier, one relevant stream, trusted invocation of recovery transitions and validated typed response keys. It does not model other healthy streams delivering responses during interruption. It blocks all ordinary work while locally interrupted as a conservative policy.
It accepts a new assigned session after a trusted initialization outcome, but does not construct or send the required fresh initialize without an old session header. The state transitions assume the adapter establishes genuine new scope and successful lifecycle. A caller must not treat generation increments as proof of actual remote session loss. Repeated, concurrent or stale calls to session_expired are not guarded in this simple fixture.
The mutable local records and unbounded outcomes dictionary are educational, not a production state store. There is no durable idempotency, authorization, catalog schema validation, business execution, real event deduplication or cross-thread synchronization. The received status means a fixture value was associated with its pending key, not that any real business action was verified. The tests do not establish MCP SDK conformance or live recovery guarantees.
11. Production recovery policies and operational checks#
Use the compatible SDK and transport's documented recovery facilities rather than writing an arbitrary reconnect loop over its internals. Decide whether an operation can continue under the existing relationship, requires a new relationship or needs independent business reconciliation.
Use an overall deadline, bounded attempts and an appropriate backoff policy. Differentiate recoverable connection failures from unsupported revisions, authorization failures and permanent configuration errors. Retry backoff alone does not make a business action safe. Avoid overwhelming a restarting service with simultaneous initialization and catalog discovery. A single recovery owner per affected relationship can coalesce reconnect attempts and prevent conflicting generations.
For an illustrative host with many remote integrations, one expired session should cause recovery work only for the affected integration and its dependent tasks. Shared gateways or credentials can cause correlated failures; bound recovery concurrency across those dependencies. Avoid unbounded pending maps or event retention when peers do not resume.
Useful diagnostics include a controlled failure category, trusted route, connection generation, whether a session was replaced, whether replay was attempted, recovery duration, count of abandoned requests and unconfirmed business operations. Protect session identifiers, tokens, cursor values and private arguments; log only minimized or redacted values where necessary.
Test the real deployment with injected failures before request transmission, after delivery, after downstream commit but before response, mid-SSE stream, expired session, unsupported replay, duplicated events and delayed old-generation callbacks. Check actual SDK behavior with the selected revision and transport. Verify that recovery does not silently re-execute writes and that fresh catalog state is required where appropriate. Measure actual recovery latency and resource use rather than extrapolating from this unit test.
Interview-ready answer#
An interrupted MCP transport does not necessarily end the logical session or cancel the underlying operation. In historical 2025-06-18 Streamable HTTP, optional SSE event IDs and Last-Event-ID can support resumption of the relevant stream without replaying the original business request. If a request carrying the assigned session ID receives the applicable HTTP 404, the client must establish a new session with a fresh initialize without that old session ID. A crashed stdio server generally requires a new process and relationship. Keep pending requests only where safe continuity can be established; otherwise resolve them locally as unconfirmed, invalidate stale routes, and rediscover authorized capabilities after replacement. Preserve ID non-reuse in the same session, reject stale-generation responses, and never equate transport loss with rollback. Use bounded recovery and independent business reconciliation.
Next lesson: Q44 compares session-oriented and newer lifecycle designs across verified specification revisions. Where newer primary sources are unavailable, explicitly limit claims rather than inventing version differences.
References
- 1.MCP historical specification (2025-06-18)modelcontextprotocol.io
- 2.MCP transports (2025-06-18)modelcontextprotocol.io
- 3.MCP lifecycle (2025-06-18)modelcontextprotocol.io
- 4.MCP base protocol (2025-06-18)modelcontextprotocol.io
- 5.MCP cancellation (2025-06-18)modelcontextprotocol.io
- 6.HTML standard: Server-sent eventshtml.spec.whatwg.org
- 7.HTTP Semantics, RFC 9110rfc-editor.org
- 8.JSON-RPC 2.0 specificationjsonrpc.org
- 9.Official MCP Python SDKgithub.com
- 10.Python unittest documentationdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation