| 1 | // Copyright 2025 The Go MCP SDK Authors. All rights reserved. |
| 2 | // Use of this source code is governed by an MIT-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // TODO: move client-side streamable HTTP logic from streamable.go to this file. |
| 6 | |
| 7 | package mcp |
| 8 | |
| 9 | /* |
| 10 | Streamable HTTP Client Design |
| 11 | |
| 12 | This document describes the client-side implementation of the MCP streamable |
| 13 | HTTP transport, as defined by the MCP spec: |
| 14 | https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#streamable-http |
| 15 | |
| 16 | # Overview |
| 17 | |
| 18 | The client-side streamable transport allows an MCP client to communicate with a |
| 19 | server over HTTP, sending messages via POST and receiving responses via either |
| 20 | JSON or server-sent events (SSE). The implementation consists of two main |
| 21 | components: |
| 22 | |
| 23 | ┌─────────────────────────────────────────────────────────────────┐ |
| 24 | │ [StreamableClientTransport] │ |
| 25 | │ Transport configuration; creates connections via Connect() │ |
| 26 | └─────────────────────────────────────────────────────────────────┘ |
| 27 | │ |
| 28 | ▼ |
| 29 | ┌─────────────────────────────────────────────────────────────────┐ |
| 30 | │ [streamableClientConn] │ |
| 31 | │ Connection implementation; handles HTTP request/response │ |
| 32 | └─────────────────────────────────────────────────────────────────┘ |
| 33 | │ |
| 34 | ├──────────────────────────────────────┐ |
| 35 | ▼ ▼ |
| 36 | ┌─────────────────────────────────────────┐ ┌────────────────────────────────────┐ |
| 37 | │ POST request handlers │ │ Standalone SSE stream │ |
| 38 | │ (one per outgoing message/call) │ │ (server-initiated messages) │ |
| 39 | └─────────────────────────────────────────┘ └────────────────────────────────────┘ |
| 40 | |
| 41 | # Sessions |
| 42 | |
| 43 | The client maintains a session with the server, identified by a session ID |
| 44 | (Mcp-Session-Id header): |
| 45 | |
| 46 | - Session ID is received from the server after initialization |
| 47 | - Client includes the session ID in all subsequent requests |
| 48 | - Session ends when the client calls Close() (sends DELETE) or server returns 404 |
| 49 | |
| 50 | [streamableClientConn] stores the session state: |
| 51 | - [streamableClientConn.sessionID]: Server-assigned session identifier |
| 52 | - [streamableClientConn.initializedResult]: Protocol version and server capabilities |
| 53 | |
| 54 | # Connection Lifecycle |
| 55 | |
| 56 | 1. Connect: [StreamableClientTransport.Connect] creates a [streamableClientConn] |
| 57 | with a detached context for the connection's lifetime. The context is detached |
| 58 | to prevent the standalone SSE stream from being cancelled when the original |
| 59 | Connect context times out. |
| 60 | |
| 61 | 2. Initialize: The MCP client sends initialize/initialized messages. Upon |
| 62 | receiving [InitializeResult], the connection: |
| 63 | - Stores the negotiated protocol version for the Mcp-Protocol-Version header |
| 64 | - Captures the session ID from the Mcp-Session-Id response header |
| 65 | - Starts the standalone SSE stream via [streamableClientConn.connectStandaloneSSE] |
| 66 | |
| 67 | 3. Operation: Messages are sent via POST, responses received via JSON or SSE. |
| 68 | |
| 69 | 4. Close: [streamableClientConn.Close] sends a DELETE request to terminate |
| 70 | the session (unless the session is already gone), then cancels the connection |
| 71 | context to clean up the standalone SSE stream. |
| 72 | |
| 73 | # Sending Messages (Write) |
| 74 | |
| 75 | [streamableClientConn.Write] sends all outgoing messages via HTTP POST: |
| 76 | |
| 77 | POST /endpoint |
| 78 | Content-Type: application/json |
| 79 | Accept: application/json, text/event-stream |
| 80 | Mcp-Protocol-Version: <negotiated version> |
| 81 | Mcp-Session-Id: <session ID, if established> |
| 82 | |
| 83 | <JSON-RPC message> |
| 84 | |
| 85 | The server may respond with: |
| 86 | - 202 Accepted: Message received, no response body (notifications/responses) |
| 87 | - 200 OK with application/json: Single JSON-RPC response |
| 88 | - 200 OK with text/event-stream: SSE stream of responses |
| 89 | |
| 90 | # Receiving Messages (Read) |
| 91 | |
| 92 | [streamableClientConn.Read] returns messages from the [streamableClientConn.incoming] |
| 93 | channel, which is populated by multiple concurrent goroutines: |
| 94 | |
| 95 | 1. POST response handlers ([streamableClientConn.handleJSON] and |
| 96 | [streamableClientConn.handleSSE]): Process responses from POST requests |
| 97 | |
| 98 | 2. Standalone SSE stream: Receives server-initiated requests and notifications |
| 99 | |
| 100 | The client handles both response formats: |
| 101 | - JSON: [streamableClientConn.handleJSON] reads body, decodes message |
| 102 | - SSE: [streamableClientConn.handleSSE] scans events, decodes each message |
| 103 | |
| 104 | # Standalone SSE Stream |
| 105 | |
| 106 | After initialization, [streamableClientConn.sessionUpdated] triggers |
| 107 | [streamableClientConn.connectStandaloneSSE] to open a GET request for |
| 108 | server-initiated messages: |
| 109 | |
| 110 | GET /endpoint |
| 111 | Accept: text/event-stream |
| 112 | Mcp-Session-Id: <session ID> |
| 113 | |
| 114 | Stream behavior: |
| 115 | - Optional: Server may return 405 Method Not Allowed (spec-compliant) or |
| 116 | other 4xx errors (tolerated in non-strict mode for compatibility) |
| 117 | - Persistent: Runs for the connection lifetime in a background goroutine |
| 118 | - Resumable: Uses Last-Event-ID header on reconnection if server provides event IDs |
| 119 | - Reconnects: Automatic reconnection with exponential backoff on interruption |
| 120 | |
| 121 | # Stream Resumption |
| 122 | |
| 123 | When an SSE stream (standalone or POST response) is interrupted, the client |
| 124 | attempts to reconnect using [streamableClientConn.connectSSE]: |
| 125 | |
| 126 | Event ID tracking: |
| 127 | - [streamableClientConn.processStream] tracks the last received event ID |
| 128 | - On reconnection, the Last-Event-ID header is set to resume from that point |
| 129 | - Server replays missed events if it has an [EventStore] configured |
| 130 | |
| 131 | See [calculateReconnectDelay] for the reconnect delay details. |
| 132 | |
| 133 | Server-initiated reconnection (SEP-1699) |
| 134 | - SSE retry field: Sets the delay for the next reconnect attempt |
| 135 | - If server doesn't provide event IDs, non-standalone streams don't reconnect |
| 136 | |
| 137 | # Response Formats |
| 138 | |
| 139 | The client must handle two response formats from POST requests: |
| 140 | |
| 141 | 1. application/json: Single JSON-RPC response |
| 142 | - Body contains one JSON-RPC message |
| 143 | - Handled by [streamableClientConn.handleJSON] |
| 144 | - Simpler but doesn't support streaming or server-initiated messages |
| 145 | |
| 146 | 2. text/event-stream: SSE stream of messages |
| 147 | - Body contains SSE events with JSON-RPC messages |
| 148 | - Handled by [streamableClientConn.handleSSE] |
| 149 | - Supports multiple messages and server-initiated communication |
| 150 | - Stream completes when the response to the originating call is received |
| 151 | |
| 152 | # HTTP Methods |
| 153 | |
| 154 | - POST: Send JSON-RPC messages (requests, responses, notifications) |
| 155 | - Used by [streamableClientConn.Write] |
| 156 | - Response may be JSON or SSE |
| 157 | |
| 158 | - GET: Open or resume SSE stream for server-initiated messages |
| 159 | - Used by [streamableClientConn.connectSSE] |
| 160 | - Always expects text/event-stream response (or 405) |
| 161 | |
| 162 | - DELETE: Terminate the session |
| 163 | - Used by [streamableClientConn.Close] |
| 164 | - Skipped if session is already known to be gone ([ErrSessionMissing]) |
| 165 | |
| 166 | # Error Handling |
| 167 | |
| 168 | Errors are categorized and handled differently: |
| 169 | |
| 170 | 1. Transient (recoverable via reconnection): |
| 171 | - Network interruption during SSE streaming |
| 172 | - Connection reset or timeout |
| 173 | - Triggers reconnection in [streamableClientConn.handleSSE] |
| 174 | |
| 175 | 2. Terminal (breaks the connection): |
| 176 | - 404 Not Found: Session terminated by server ([ErrSessionMissing]) |
| 177 | - Message decode errors: Protocol violation |
| 178 | - Context cancellation: Client closed connection |
| 179 | - Mismatched session IDs: Protocol error |
| 180 | - See issue #683: our terminal errors are too strict. |
| 181 | |
| 182 | Terminal errors are stored via [streamableClientConn.fail] and returned by |
| 183 | subsequent [streamableClientConn.Read] calls. The [streamableClientConn.failed] |
| 184 | channel signals that the connection is broken. |
| 185 | |
| 186 | Special case: [ErrSessionMissing] indicates the server has terminated the session, |
| 187 | so [streamableClientConn.Close] skips the DELETE request. |
| 188 | |
| 189 | # Protocol Version Header |
| 190 | |
| 191 | After initialization, all requests include: |
| 192 | |
| 193 | Mcp-Protocol-Version: <negotiated version> |
| 194 | |
| 195 | This header (set by [streamableClientConn.setMCPHeaders]): |
| 196 | - Allows the server to handle requests per the negotiated protocol |
| 197 | - Is omitted before initialization completes |
| 198 | - Uses the version from [streamableClientConn.initializedResult] |
| 199 | |
| 200 | # Key Implementation Details |
| 201 | |
| 202 | [StreamableClientTransport] configuration: |
| 203 | - [StreamableClientTransport.Endpoint]: URL of the MCP server |
| 204 | - [StreamableClientTransport.HTTPClient]: Custom HTTP client (optional) |
| 205 | - [StreamableClientTransport.MaxRetries]: Reconnection attempts (default 5) |
| 206 | |
| 207 | [streamableClientConn] handles the [Connection] interface: |
| 208 | - [streamableClientConn.Read]: Returns messages from incoming channel |
| 209 | - [streamableClientConn.Write]: Sends messages via POST, starts response handlers |
| 210 | - [streamableClientConn.Close]: Sends DELETE, cancels context, closes done channel |
| 211 | |
| 212 | State management: |
| 213 | - [streamableClientConn.incoming]: Buffered channel for received messages |
| 214 | - [streamableClientConn.sessionID]: Server-assigned session identifier |
| 215 | - [streamableClientConn.initializedResult]: Cached for protocol version header |
| 216 | - [streamableClientConn.failed]: Channel closed on terminal error |
| 217 | - [streamableClientConn.done]: Channel closed on graceful shutdown |
| 218 | - [streamableClientConn.ctx]: Detached context for connection lifetime |
| 219 | - [streamableClientConn.cancel]: Cancels ctx to terminate SSE streams |
| 220 | |
| 221 | Context handling: |
| 222 | - Connection context is detached from [StreamableClientTransport.Connect] context |
| 223 | using [xcontext.Detach] to preserve context values (for auth middleware) while |
| 224 | preventing premature cancellation of the standalone SSE stream |
| 225 | - Individual POST requests use caller-provided contexts for cancellation |
| 226 | */ |