Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/streamable.go

raw symbols SCIP
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 // NOTE: see streamable_server.go and streamable_client.go for detailed
6 // documentation of the streamable server design.
7 // TODO: move the client and server logic into those files.
8
9 package mcp
10
11 import (
12 "bytes"
13 "context"
14 crand "crypto/rand"
15 "encoding/json"
16 "errors"
17 "fmt"
18 "io"
19 "log/slog"
20 "maps"
21 "math"
22 "math/rand/v2"
23 "mime"
24 "net"
25 "net/http"
26 "slices"
27 "strconv"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "time"
32
33 "github.com/modelcontextprotocol/go-sdk/auth"
34 internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
35 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
36 "github.com/modelcontextprotocol/go-sdk/internal/mcpgodebug"
37 "github.com/modelcontextprotocol/go-sdk/internal/util"
38 "github.com/modelcontextprotocol/go-sdk/internal/xcontext"
39 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
40 )
41
42 // A StreamableHTTPHandler is an http.Handler that serves streamable MCP
43 // sessions, as defined by the [MCP spec].
44 //
45 // [MCP spec]: https://modelcontextprotocol.io/2025/03/26/streamable-http-transport.html
46 type StreamableHTTPHandler struct {
47 getServer func(*http.Request) *Server
48 opts StreamableHTTPOptions
49
50 onTransportDeletion func(sessionID string) // for testing
51
52 mu sync.Mutex
53 sessions map[string]*sessionInfo // keyed by session ID
54 }
55
56 type sessionInfo struct {
57 session *ServerSession
58 transport *StreamableServerTransport
59 // userID is the user ID from the TokenInfo when the session was created.
60 // If non-empty, subsequent requests must have the same user ID to prevent
61 // session hijacking.
62 userID string
63
64 // If timeout is set, automatically close the session after an idle period.
65 timeout time.Duration
66 timerMu sync.Mutex
67 refs int // reference count
68 timer *time.Timer
69 }
70
71 // startPOST signals that a POST request for this session is starting (which
72 // carries a client->server message), pausing the session timeout if it was
73 // running.
74 //
75 // TODO: we may want to also pause the timer when resuming non-standalone SSE
76 // streams, but that is tricy to implement. Clients should generally make
77 // keepalive pings if they want to keep the session live.
78 func (i *sessionInfo) startPOST() {
79 if i.timeout <= 0 {
80 return
81 }
82
83 i.timerMu.Lock()
84 defer i.timerMu.Unlock()
85
86 if i.timer == nil {
87 return // timer stopped permanently
88 }
89 if i.refs == 0 {
90 i.timer.Stop()
91 }
92 i.refs++
93 }
94
95 // endPOST signals that a request for this session is ending, starting the
96 // timeout if there are no other requests running.
97 func (i *sessionInfo) endPOST() {
98 if i.timeout <= 0 {
99 return
100 }
101
102 i.timerMu.Lock()
103 defer i.timerMu.Unlock()
104
105 if i.timer == nil {
106 return // timer stopped permanently
107 }
108
109 i.refs--
110 assert(i.refs >= 0, "negative ref count")
111 if i.refs == 0 {
112 i.timer.Reset(i.timeout)
113 }
114 }
115
116 // stopTimer stops the inactivity timer permanently.
117 func (i *sessionInfo) stopTimer() {
118 i.timerMu.Lock()
119 defer i.timerMu.Unlock()
120 if i.timer != nil {
121 i.timer.Stop()
122 i.timer = nil
123 }
124 }
125
126 // StreamableHTTPOptions configures the StreamableHTTPHandler.
127 type StreamableHTTPOptions struct {
128 // Stateless controls whether the session is 'stateless'.
129 //
130 // A stateless server does not validate the Mcp-Session-Id header, and uses a
131 // temporary session with default initialization parameters. Any
132 // server->client request is rejected immediately as there's no way for the
133 // client to respond. Server->Client notifications may reach the client if
134 // they are made in the context of an incoming request, as described in the
135 // documentation for [StreamableServerTransport].
136 Stateless bool
137
138 // TODO(#148): support session retention (?)
139
140 // JSONResponse causes streamable responses to return application/json rather
141 // than text/event-stream ([§2.1.5] of the spec).
142 //
143 // [§2.1.5]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#sending-messages-to-the-server
144 JSONResponse bool
145
146 // Logger specifies the logger to use.
147 // If nil, do not log.
148 Logger *slog.Logger
149
150 // EventStore enables stream resumption.
151 //
152 // If set, EventStore will be used to persist stream events and replay them
153 // upon stream resumption.
154 EventStore EventStore
155
156 // SessionTimeout configures a timeout for idle sessions.
157 //
158 // When sessions receive no new HTTP requests from the client for this
159 // duration, they are automatically closed.
160 //
161 // If SessionTimeout is the zero value, idle sessions are never closed.
162 SessionTimeout time.Duration
163
164 // DisableLocalhostProtection disables automatic DNS rebinding protection.
165 // By default, requests arriving via a localhost address (127.0.0.1, [::1])
166 // that have a non-localhost Host header are rejected with 403 Forbidden.
167 // This protects against DNS rebinding attacks regardless of whether the
168 // server is listening on localhost specifically or on 0.0.0.0.
169 //
170 // Only disable this if you understand the security implications.
171 // See: https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise
172 DisableLocalhostProtection bool
173
174 // CrossOriginProtection allows to customize cross-origin protection.
175 // The deny handler set in the CrossOriginProtection through SetDenyHandler
176 // is ignored.
177 // If nil, no cross-origin protection is applied. Use the `enableoriginverification`
178 // MCPGODEBUG compatibility parameter to enable the default protection until v1.8.0.
179 //
180 // Deprecated: wrap the handler with cross-origin protection middleware
181 // instead. For example:
182 //
183 // handler := mcp.NewStreamableHTTPHandler(...)
184 // protection := http.NewCrossOriginProtection()
185 // protectedHandler := protection.Handler(handler)
186 CrossOriginProtection *http.CrossOriginProtection
187 }
188
189 // NewStreamableHTTPHandler returns a new [StreamableHTTPHandler].
190 //
191 // The getServer function is used to create or look up servers for new
192 // sessions. It is OK for getServer to return the same server multiple times.
193 // If getServer returns nil, a 400 Bad Request will be served.
194 func NewStreamableHTTPHandler(getServer func(*http.Request) *Server, opts *StreamableHTTPOptions) *StreamableHTTPHandler {
195 h := &StreamableHTTPHandler{
196 getServer: getServer,
197 sessions: make(map[string]*sessionInfo),
198 }
199 if opts != nil {
200 h.opts = *opts
201 }
202
203 h.opts.Logger = ensureLogger(h.opts.Logger)
204
205 if h.opts.CrossOriginProtection == nil && enableoriginverification == "1" {
206 h.opts.CrossOriginProtection = &http.CrossOriginProtection{}
207 }
208
209 return h
210 }
211
212 // closeAll closes all ongoing sessions, for tests.
213 //
214 // TODO(rfindley): investigate the best API for callers to configure their
215 // session lifecycle. (?)
216 //
217 // Should we allow passing in a session store? That would allow the handler to
218 // be stateless.
219 func (h *StreamableHTTPHandler) closeAll() {
220 // TODO: if we ever expose this outside of tests, we'll need to do better
221 // than simply collecting sessions while holding the lock: we need to prevent
222 // new sessions from being added.
223 //
224 // Currently, sessions remove themselves from h.sessions when closed, so we
225 // can't call Close while holding the lock.
226 h.mu.Lock()
227 sessionInfos := slices.Collect(maps.Values(h.sessions))
228 h.sessions = nil
229 h.mu.Unlock()
230 for _, s := range sessionInfos {
231 s.session.Close()
232 }
233 }
234
235 // disablelocalhostprotection is a compatibility parameter that allows to disable
236 // DNS rebinding protection, which was added in the 1.4.0 version of the SDK.
237 // See the documentation for the mcpgodebug package for instructions how to enable it.
238 // The option will be removed in the 1.8.0 version of the SDK.
239 var disablelocalhostprotection = mcpgodebug.Value("disablelocalhostprotection")
240
241 // enableoriginverification is a compatibility parameter that restores the
242 // default cross-origin protection behavior from v1.4.1-v1.5.0. When set to
243 // "1", a zero-value CrossOriginProtection will be applied if none is
244 // explicitly provided in StreamableHTTPOptions.
245 // See the documentation for the mcpgodebug package for instructions how to enable it.
246 // The option will be removed in the 1.8.0 version of the SDK.
247 var enableoriginverification = mcpgodebug.Value("enableoriginverification")
248
249 // disablecontenttypecheck is a compatibility parameter that allows to disable
250 // Content-Type validation on POST requests.
251 // See the documentation for the mcpgodebug package for instructions how to enable it.
252 // The option will be removed in the 1.8.0 version of the SDK.
253 var disablecontenttypecheck = mcpgodebug.Value("disablecontenttypecheck")
254
255 func (h *StreamableHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
256 // DNS rebinding protection: auto-enabled for localhost servers.
257 // See: https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise
258 if !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1" {
259 if localAddr, ok := req.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && localAddr != nil {
260 if util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) {
261 http.Error(w, fmt.Sprintf("Forbidden: invalid Host header %q", req.Host), http.StatusForbidden)
262 return
263 }
264 }
265 }
266
267 if h.opts.CrossOriginProtection != nil {
268 // Verify the 'Origin' header to protect against CSRF attacks.
269 if err := h.opts.CrossOriginProtection.Check(req); err != nil {
270 http.Error(w, err.Error(), http.StatusForbidden)
271 return
272 }
273 }
274
275 // Validate 'Content-Type' header.
276 if disablecontenttypecheck != "1" && req.Method == http.MethodPost && baseMediaType(req.Header.Get("Content-Type")) != "application/json" {
277 http.Error(w, "Content-Type must be 'application/json'", http.StatusUnsupportedMediaType)
278 return
279 }
280
281 // Allow multiple 'Accept' headers.
282 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept#syntax
283 jsonOK, streamOK := streamableAccepts(req.Header.Values("Accept"))
284
285 if req.Method == http.MethodGet {
286 if !streamOK {
287 http.Error(w, "Accept must contain 'text/event-stream' for GET requests", http.StatusBadRequest)
288 return
289 }
290 } else if (!jsonOK || !streamOK) && req.Method != http.MethodDelete { // TODO: consolidate with handling of http method below.
291 http.Error(w, "Accept must contain both 'application/json' and 'text/event-stream'", http.StatusBadRequest)
292 return
293 }
294
295 sessionID := req.Header.Get(sessionIDHeader)
296 var sessInfo *sessionInfo
297 if sessionID != "" {
298 h.mu.Lock()
299 sessInfo = h.sessions[sessionID]
300 h.mu.Unlock()
301 if sessInfo == nil && !h.opts.Stateless {
302 // Unless we're in 'stateless' mode, which doesn't perform any Session-ID
303 // validation, we require that the session ID matches a known session.
304 //
305 // In stateless mode, a temporary transport is be created below.
306 http.Error(w, "session not found", http.StatusNotFound)
307 return
308 }
309 // Prevent session hijacking: if the session was created with a user ID,
310 // verify that subsequent requests come from the same user.
311 if sessInfo != nil && sessInfo.userID != "" {
312 tokenInfo := auth.TokenInfoFromContext(req.Context())
313 if tokenInfo == nil || tokenInfo.UserID != sessInfo.userID {
314 http.Error(w, "session user mismatch", http.StatusForbidden)
315 return
316 }
317 }
318 }
319
320 if req.Method == http.MethodDelete {
321 if sessionID == "" {
322 http.Error(w, "Bad Request: DELETE requires an Mcp-Session-Id header", http.StatusBadRequest)
323 return
324 }
325 if sessInfo != nil { // sessInfo may be nil in stateless mode
326 // Closing the session also removes it from h.sessions, due to the
327 // onClose callback.
328 sessInfo.session.Close()
329 }
330 w.WriteHeader(http.StatusNoContent)
331 return
332 }
333
334 switch req.Method {
335 case http.MethodPost, http.MethodGet:
336 if req.Method == http.MethodGet && (h.opts.Stateless || sessionID == "") {
337 if h.opts.Stateless {
338 // Per MCP spec: server MUST return 405 if it doesn't offer SSE stream.
339 // In stateless mode, GET (SSE streaming) is not supported.
340 // RFC 9110 §15.5.6: 405 responses MUST include Allow header.
341 w.Header().Set("Allow", "POST")
342 http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
343 } else {
344 // In stateful mode, GET is supported but requires a session ID.
345 // This is a precondition error, similar to DELETE without session.
346 http.Error(w, "Bad Request: GET requires an Mcp-Session-Id header", http.StatusBadRequest)
347 }
348 return
349 }
350 default:
351 // RFC 9110 §15.5.6: 405 responses MUST include Allow header.
352 if h.opts.Stateless {
353 w.Header().Set("Allow", "POST")
354 } else {
355 w.Header().Set("Allow", "GET, POST, DELETE")
356 }
357 http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
358 return
359 }
360
361 // [§2.7] of the spec (2025-06-18) states:
362 //
363 // "If using HTTP, the client MUST include the MCP-Protocol-Version:
364 // <protocol-version> HTTP header on all subsequent requests to the MCP
365 // server, allowing the MCP server to respond based on the MCP protocol
366 // version.
367 //
368 // For example: MCP-Protocol-Version: 2025-06-18
369 // The protocol version sent by the client SHOULD be the one negotiated during
370 // initialization.
371 //
372 // For backwards compatibility, if the server does not receive an
373 // MCP-Protocol-Version header, and has no other way to identify the version -
374 // for example, by relying on the protocol version negotiated during
375 // initialization - the server SHOULD assume protocol version 2025-03-26.
376 //
377 // If the server receives a request with an invalid or unsupported
378 // MCP-Protocol-Version, it MUST respond with 400 Bad Request."
379 //
380 // Since this wasn't present in the 2025-03-26 version of the spec, this
381 // effectively means:
382 // 1. IF the client provides a version header, it must be a supported
383 // version.
384 // 2. In stateless mode, where we've lost the state of the initialize
385 // request, we assume that whatever the client tells us is the truth (or
386 // assume 2025-03-26 if the client doesn't say anything).
387 //
388 // This logic matches the typescript SDK.
389 //
390 // [§2.7]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#protocol-version-header
391 protocolVersion := req.Header.Get(protocolVersionHeader)
392 if protocolVersion == "" {
393 protocolVersion = protocolVersion20250326
394 }
395 if !slices.Contains(supportedProtocolVersions, protocolVersion) {
396 http.Error(w, fmt.Sprintf("Bad Request: Unsupported protocol version (supported versions: %s)", strings.Join(supportedProtocolVersions, ",")), http.StatusBadRequest)
397 return
398 }
399
400 if sessInfo == nil {
401 server := h.getServer(req)
402 if server == nil {
403 // The getServer argument to NewStreamableHTTPHandler returned nil.
404 http.Error(w, "no server available", http.StatusBadRequest)
405 return
406 }
407 if sessionID == "" {
408 // In stateless mode, sessionID may be nonempty even if there's no
409 // existing transport.
410 sessionID = server.opts.GetSessionID()
411 }
412 transport := &StreamableServerTransport{
413 SessionID: sessionID,
414 Stateless: h.opts.Stateless,
415 EventStore: h.opts.EventStore,
416 jsonResponse: h.opts.JSONResponse,
417 logger: h.opts.Logger,
418 }
419
420 // Sessions without a session ID are also stateless: there's no way to
421 // address them.
422 stateless := h.opts.Stateless || sessionID == ""
423 // To support stateless mode, we initialize the session with a default
424 // state, so that it doesn't reject subsequent requests.
425 var connectOpts *ServerSessionOptions
426 if stateless {
427 // Peek at the body to see if it is initialize or initialized.
428 // We want those to be handled as usual.
429 var hasInitialize, hasInitialized bool
430 {
431 // TODO: verify that this allows protocol version negotiation for
432 // stateless servers.
433 body, err := io.ReadAll(req.Body)
434 if err != nil {
435 http.Error(w, "failed to read body", http.StatusBadRequest)
436 return
437 }
438 req.Body.Close()
439
440 // Reset the body so that it can be read later.
441 req.Body = io.NopCloser(bytes.NewBuffer(body))
442
443 msgs, _, err := readBatch(body)
444 if err == nil {
445 for _, msg := range msgs {
446 if req, ok := msg.(*jsonrpc.Request); ok {
447 switch req.Method {
448 case methodInitialize:
449 hasInitialize = true
450 case notificationInitialized:
451 hasInitialized = true
452 }
453 }
454 }
455 }
456 }
457
458 // If we don't have InitializeParams or InitializedParams in the request,
459 // set the initial state to a default value.
460 state := new(ServerSessionState)
461 if !hasInitialize {
462 state.InitializeParams = &InitializeParams{
463 ProtocolVersion: protocolVersion,
464 }
465 }
466 if !hasInitialized {
467 state.InitializedParams = new(InitializedParams)
468 }
469 state.LogLevel = "info"
470 connectOpts = &ServerSessionOptions{
471 State: state,
472 }
473 } else {
474 // Cleanup is only required in stateful mode, as transportation is
475 // not stored in the map otherwise.
476 connectOpts = &ServerSessionOptions{
477 onClose: func() {
478 h.mu.Lock()
479 defer h.mu.Unlock()
480 if info, ok := h.sessions[transport.SessionID]; ok {
481 info.stopTimer()
482 delete(h.sessions, transport.SessionID)
483 if h.onTransportDeletion != nil {
484 h.onTransportDeletion(transport.SessionID)
485 }
486 }
487 },
488 }
489 }
490
491 // Pass req.Context() here, to allow middleware to add context values.
492 // The context is detached in the jsonrpc2 library when handling the
493 // long-running stream.
494 session, err := server.Connect(req.Context(), transport, connectOpts)
495 if err != nil {
496 http.Error(w, "failed connection", http.StatusInternalServerError)
497 return
498 }
499 // Capture the user ID from the token info to enable session hijacking
500 // prevention on subsequent requests.
501 var userID string
502 if tokenInfo := auth.TokenInfoFromContext(req.Context()); tokenInfo != nil {
503 userID = tokenInfo.UserID
504 }
505 sessInfo = &sessionInfo{
506 session: session,
507 transport: transport,
508 userID: userID,
509 }
510
511 if stateless {
512 // Stateless mode: close the session when the request exits.
513 defer session.Close() // close the fake session after handling the request
514 } else {
515 // Otherwise, save the transport so that it can be reused
516
517 // Clean up the session when it times out.
518 //
519 // Note that the timer here may fire multiple times, but
520 // sessInfo.session.Close is idempotent.
521 if h.opts.SessionTimeout > 0 {
522 sessInfo.timeout = h.opts.SessionTimeout
523 sessInfo.timer = time.AfterFunc(sessInfo.timeout, func() {
524 sessInfo.session.Close()
525 })
526 }
527 h.mu.Lock()
528 h.sessions[transport.SessionID] = sessInfo
529 h.mu.Unlock()
530 defer func() {
531 // If initialization failed, clean up the session (#578).
532 if session.InitializeParams() == nil {
533 // Initialization failed.
534 session.Close()
535 }
536 }()
537 }
538 }
539
540 if req.Method == http.MethodPost {
541 sessInfo.startPOST()
542 defer sessInfo.endPOST()
543 }
544
545 sessInfo.transport.ServeHTTP(w, req)
546 }
547
548 func streamableAccepts(values []string) (jsonOK, streamOK bool) {
549 for _, value := range values {
550 for _, raw := range strings.Split(value, ",") {
551 token := strings.TrimSpace(raw)
552 // Ignore Accept parameters like ";charset=utf-8"; match the base media type.
553 base, _, _ := strings.Cut(token, ";")
554 switch strings.ToLower(strings.TrimSpace(base)) {
555 case "application/json", "application/*":
556 jsonOK = true
557 case "text/event-stream", "text/*":
558 streamOK = true
559 case "*/*":
560 jsonOK = true
561 streamOK = true
562 }
563 }
564 }
565 return jsonOK, streamOK
566 }
567
568 func baseMediaType(value string) string {
569 mediaType, _, err := mime.ParseMediaType(value)
570 if err != nil {
571 return ""
572 }
573 return mediaType
574 }
575
576 // A StreamableServerTransport implements the server side of the MCP streamable
577 // transport.
578 //
579 // Each StreamableServerTransport must be connected (via [Server.Connect]) at
580 // most once, since [StreamableServerTransport.ServeHTTP] serves messages to
581 // the connected session.
582 //
583 // Reads from the streamable server connection receive messages from http POST
584 // requests from the client. Writes to the streamable server connection are
585 // sent either to the related stream, or to the standalone SSE stream,
586 // according to the following rules:
587 // - JSON-RPC responses to incoming requests are always routed to the
588 // appropriate HTTP response.
589 // - Requests or notifications made with a context.Context value derived from
590 // an incoming request handler, are routed to the HTTP response
591 // corresponding to that request, unless it has already terminated, in
592 // which case they are routed to the standalone SSE stream.
593 // - Requests or notifications made with a detached context.Context value are
594 // routed to the standalone SSE stream.
595 type StreamableServerTransport struct {
596 // SessionID is the ID of this session.
597 //
598 // If SessionID is the empty string, this is a 'stateless' session, which has
599 // limited ability to communicate with the client. Otherwise, the session ID
600 // must be globally unique, that is, different from any other session ID
601 // anywhere, past and future. (We recommend using a crypto random number
602 // generator to produce one, as with [crypto/rand.Text].)
603 SessionID string
604
605 // Stateless controls whether the eventstore is 'Stateless'. Server sessions
606 // connected to a stateless transport are disallowed from making outgoing
607 // requests.
608 //
609 // See also [StreamableHTTPOptions.Stateless].
610 Stateless bool
611
612 // EventStore enables stream resumption.
613 //
614 // If set, EventStore will be used to persist stream events and replay them
615 // upon stream resumption.
616 EventStore EventStore
617
618 // jsonResponse, if set, tells the server to prefer to respond to requests
619 // using application/json responses rather than text/event-stream.
620 //
621 // Specifically, responses will be application/json whenever incoming POST
622 // request contain only a single message. In this case, notifications or
623 // requests made within the context of a server request will be sent to the
624 // standalone SSE stream, if any.
625 //
626 // TODO(rfindley): jsonResponse should be exported, since
627 // StreamableHTTPOptions.JSONResponse is exported, and we want to allow users
628 // to write their own streamable HTTP handler.
629 jsonResponse bool
630
631 // optional logger provided through the [StreamableHTTPOptions.Logger].
632 //
633 // TODO(rfindley): logger should be exported, since we want to allow users
634 // to write their own streamable HTTP handler.
635 logger *slog.Logger
636
637 // connection is non-nil if and only if the transport has been connected.
638 connection *streamableServerConn
639 }
640
641 // Connect implements the [Transport] interface.
642 func (t *StreamableServerTransport) Connect(ctx context.Context) (Connection, error) {
643 if t.connection != nil {
644 return nil, fmt.Errorf("transport already connected")
645 }
646 t.connection = &streamableServerConn{
647 sessionID: t.SessionID,
648 stateless: t.Stateless,
649 eventStore: t.EventStore,
650 jsonResponse: t.jsonResponse,
651 logger: ensureLogger(t.logger), // see #556: must be non-nil
652 incoming: make(chan jsonrpc.Message, 10),
653 done: make(chan struct{}),
654 streams: make(map[string]*stream),
655 requestStreams: make(map[jsonrpc.ID]string),
656 }
657 // Stream 0 corresponds to the standalone SSE stream.
658 //
659 // It is always text/event-stream, since it must carry arbitrarily many
660 // messages.
661 var err error
662 t.connection.streams[""], err = t.connection.newStream(ctx, nil, "")
663 if err != nil {
664 return nil, err
665 }
666 return t.connection, nil
667 }
668
669 type streamableServerConn struct {
670 sessionID string
671 stateless bool
672 jsonResponse bool
673 eventStore EventStore
674
675 logger *slog.Logger
676
677 incoming chan jsonrpc.Message // messages from the client to the server
678
679 mu sync.Mutex // guards all fields below
680
681 // Sessions are closed exactly once.
682 isDone bool
683 done chan struct{}
684
685 // Sessions can have multiple logical connections (which we call streams),
686 // corresponding to HTTP requests. Additionally, streams may be resumed by
687 // subsequent HTTP requests, when the HTTP connection is terminated
688 // unexpectedly.
689 //
690 // Therefore, we use a logical stream ID to key the stream state, and
691 // perform the accounting described below when incoming HTTP requests are
692 // handled.
693
694 // streams holds the logical streams for this session, keyed by their ID.
695 //
696 // Lifecycle: streams persist until all of their responses are received from
697 // the server.
698 streams map[string]*stream
699
700 // requestStreams maps incoming requests to their logical stream ID.
701 //
702 // Lifecycle: requestStreams persist until their response is received.
703 requestStreams map[jsonrpc.ID]string
704 }
705
706 func (c *streamableServerConn) SessionID() string {
707 return c.sessionID
708 }
709
710 // A stream is a single logical stream of SSE events within a server session.
711 // A stream begins with a client request, or with a client GET that has
712 // no Last-Event-ID header.
713 //
714 // A stream ends only when its session ends; we cannot determine its end otherwise,
715 // since a client may send a GET with a Last-Event-ID that references the stream
716 // at any time.
717 type stream struct {
718 // id is the logical ID for the stream, unique within a session.
719 //
720 // The standalone SSE stream has id "".
721 id string
722
723 // logger is used for logging errors during stream operations.
724 logger *slog.Logger
725
726 // mu guards the fields below, as well as storage of new messages in the
727 // connection's event store (if any).
728 mu sync.Mutex
729
730 // If pendingJSONMessages is non-nil, this is a JSON stream and messages are
731 // collected here until the stream is complete, at which point they are
732 // flushed as a single JSON response. Note that the non-nilness of this field
733 // is significant, as it signals the expected content type.
734 //
735 // Note: if we remove support for batching, this could just be a bool.
736 pendingJSONMessages []json.RawMessage
737
738 // w is the HTTP response writer for this stream. A non-nil w indicates
739 // that the stream is claimed by an HTTP request (the hanging POST or GET);
740 // it is set to nil when the request completes.
741 w http.ResponseWriter
742
743 // done is closed to release the hanging HTTP request.
744 //
745 // Invariant: a non-nil done implies w is also non-nil, though the converse
746 // is not necessarily true: done is set to nil when it is closed, to avoid
747 // duplicate closure.
748 done chan struct{}
749
750 // lastIdx is the index of the last written SSE event, for event ID generation.
751 // It starts at -1 since indices start at 0.
752 lastIdx int
753
754 // protocolVersion is the protocol version for this stream.
755 protocolVersion string
756
757 // requests is the set of unanswered incoming requests for the stream.
758 //
759 // Requests are removed when their response has been received.
760 // In practice, there is only one request, but in the 2025-03-26 version of
761 // the spec and earlier there was a concept of batching, in which POST
762 // payloads could hold multiple requests or responses.
763 requests map[jsonrpc.ID]struct{}
764 }
765
766 // close sends a 'close' event to the client (if protocolVersion >= 2025-11-25
767 // and reconnectAfter > 0) and closes the done channel.
768 //
769 // The done channel is set to nil after closing, so that done != nil implies
770 // the stream is active and done is open. This simplifies checks elsewhere.
771 func (s *stream) close(reconnectAfter time.Duration) {
772 s.mu.Lock()
773 defer s.mu.Unlock()
774 if s.done == nil {
775 return // stream not connected or already closed
776 }
777 if s.protocolVersion >= protocolVersion20251125 && reconnectAfter > 0 {
778 reconnectStr := strconv.FormatInt(reconnectAfter.Milliseconds(), 10)
779 if _, err := writeEvent(s.w, Event{
780 Name: "close",
781 Retry: reconnectStr,
782 }); err != nil {
783 s.logger.Warn(fmt.Sprintf("Writing close event: %v", err))
784 }
785 }
786 close(s.done)
787 s.done = nil
788 }
789
790 // release releases the stream from its HTTP request, allowing it to be
791 // claimed by another request (e.g., for resumption).
792 func (s *stream) release() {
793 s.mu.Lock()
794 defer s.mu.Unlock()
795 s.w = nil
796 s.done = nil // may already be nil, if the stream is done or closed
797 }
798
799 // deliverLocked writes data to the stream (for SSE) or stores it in
800 // pendingJSONMessages (for JSON mode). The eventID is used for SSE event ID;
801 // pass "" to omit.
802 //
803 // If responseTo is valid, it is removed from the requests map. When all
804 // requests have been responded to, the done channel is closed and set to nil.
805 //
806 // Returns true if the stream is now done (all requests have been responded to).
807 // The done value is always accurate, even if an error is returned.
808 //
809 // s.mu must be held when calling this method.
810 func (s *stream) deliverLocked(data []byte, eventID string, responseTo jsonrpc.ID) (done bool, err error) {
811 // First, record the response. We must do this *before* returning an error
812 // below, as even if the stream is disconnected we want to update our
813 // accounting.
814 if responseTo.IsValid() {
815 delete(s.requests, responseTo)
816 }
817 // Now, try to deliver the message to the client.
818 done = len(s.requests) == 0 && s.id != ""
819 if s.done == nil {
820 return done, fmt.Errorf("stream not connected or already closed")
821 }
822 if done {
823 defer func() { close(s.done); s.done = nil }()
824 }
825 // Try to write to the response.
826 //
827 // If we get here, the request is still hanging (because s.done != nil
828 // implies s.w != nil), but may have been cancelled by the client/http layer:
829 // there's a brief race between request cancellation and releasing the
830 // stream.
831 if s.pendingJSONMessages != nil {
832 s.pendingJSONMessages = append(s.pendingJSONMessages, data)
833 if done {
834 // Flush all pending messages as JSON response.
835 var toWrite []byte
836 if len(s.pendingJSONMessages) == 1 {
837 toWrite = s.pendingJSONMessages[0]
838 } else {
839 toWrite, err = json.Marshal(s.pendingJSONMessages)
840 if err != nil {
841 return done, err
842 }
843 }
844 if _, err := s.w.Write(toWrite); err != nil {
845 return done, err
846 }
847 }
848 } else {
849 // SSE mode: write event to response writer.
850 s.lastIdx++
851 if _, err := writeEvent(s.w, Event{Name: "message", Data: data, ID: eventID}); err != nil {
852 return done, err
853 }
854 }
855 return done, nil
856 }
857
858 // doneLocked reports whether the stream is logically complete.
859 //
860 // s.requests was populated when reading the POST body, requests are deleted as
861 // they are responded to. Once all requests have been responded to, the stream
862 // is done.
863 //
864 // s.mu must be held while calling this function.
865 func (s *stream) doneLocked() bool {
866 return len(s.requests) == 0 && s.id != ""
867 }
868
869 func (c *streamableServerConn) newStream(ctx context.Context, requests map[jsonrpc.ID]struct{}, id string) (*stream, error) {
870 if c.eventStore != nil {
871 if err := c.eventStore.Open(ctx, c.sessionID, id); err != nil {
872 return nil, err
873 }
874 }
875 return &stream{
876 id: id,
877 requests: requests,
878 lastIdx: -1, // indices start at 0, incremented before each write
879 logger: c.logger,
880 }, nil
881 }
882
883 // We track the incoming request ID inside the handler context using
884 // idContextValue, so that notifications and server->client calls that occur in
885 // the course of handling incoming requests are correlated with the incoming
886 // request that caused them, and can be dispatched as server-sent events to the
887 // correct HTTP request.
888 //
889 // Currently, this is implemented in [ServerSession.handle]. This is not ideal,
890 // because it means that a user of the MCP package couldn't implement the
891 // streamable transport, as they'd lack this privileged access.
892 //
893 // If we ever wanted to expose this mechanism, we have a few options:
894 // 1. Make ServerSession an interface, and provide an implementation of
895 // ServerSession to handlers that closes over the incoming request ID.
896 // 2. Expose a 'HandlerTransport' interface that allows transports to provide
897 // a handler middleware, so that we don't hard-code this behavior in
898 // ServerSession.handle.
899 // 3. Add a `func ForRequest(context.Context) jsonrpc.ID` accessor that lets
900 // any transport access the incoming request ID.
901 //
902 // For now, by giving only the StreamableServerTransport access to the request
903 // ID, we avoid having to make this API decision.
904 type idContextKey struct{}
905
906 // ServeHTTP handles a single HTTP request for the session.
907 func (t *StreamableServerTransport) ServeHTTP(w http.ResponseWriter, req *http.Request) {
908 if t.connection == nil {
909 http.Error(w, "transport not connected", http.StatusInternalServerError)
910 return
911 }
912 switch req.Method {
913 case http.MethodGet:
914 t.connection.serveGET(w, req)
915 case http.MethodPost:
916 t.connection.servePOST(w, req)
917 default:
918 // Should not be reached, as this is checked in StreamableHTTPHandler.ServeHTTP.
919 w.Header().Set("Allow", "GET, POST")
920 http.Error(w, "unsupported method", http.StatusMethodNotAllowed)
921 return
922 }
923 }
924
925 // serveGET streams messages to a hanging http GET, with stream ID and last
926 // message parsed from the Last-Event-ID header.
927 //
928 // It returns an HTTP status code and error message.
929 func (c *streamableServerConn) serveGET(w http.ResponseWriter, req *http.Request) {
930 // streamID "" corresponds to the default GET request.
931 streamID := ""
932 // By default, we haven't seen a last index. Since indices start at 0, we represent
933 // that by -1. This is incremented just before each event is written.
934 lastIdx := -1
935 if len(req.Header.Values(lastEventIDHeader)) > 0 {
936 eid := req.Header.Get(lastEventIDHeader)
937 var ok bool
938 streamID, lastIdx, ok = parseEventID(eid)
939 if !ok {
940 http.Error(w, fmt.Sprintf("malformed Last-Event-ID %q", eid), http.StatusBadRequest)
941 return
942 }
943 if c.eventStore == nil {
944 http.Error(w, "stream replay unsupported", http.StatusBadRequest)
945 return
946 }
947 }
948
949 ctx := req.Context()
950
951 // Read the protocol version from the header. For GET requests, this should
952 // always be present since GET only happens after initialization.
953 protocolVersion := req.Header.Get(protocolVersionHeader)
954 if protocolVersion == "" {
955 protocolVersion = protocolVersion20250326
956 }
957
958 stream, done := c.acquireStream(ctx, w, streamID, lastIdx, protocolVersion)
959 if stream == nil {
960 return
961 }
962 defer stream.release()
963 c.hangResponse(ctx, done)
964 }
965
966 // hangResponse blocks the HTTP response until one of three conditions is met:
967 // - ctx is cancelled (the client disconnected or the request timed out)
968 // - done is closed (all responses have been sent, or the stream was explicitly closed)
969 // - the session is closed
970 //
971 // This keeps the HTTP connection open so that server-sent events can be
972 // written to the response.
973 func (c *streamableServerConn) hangResponse(ctx context.Context, done <-chan struct{}) {
974 select {
975 case <-ctx.Done():
976 case <-done:
977 case <-c.done:
978 }
979 }
980
981 // acquireStream replays all events since lastIdx, and acquires the ongoing
982 // stream, if any. If non-nil, the resulting stream will be registered for
983 // receiving new messages, and the stream's done channel will be closed when
984 // all related messages have been delivered.
985 //
986 // If any errors occur, they will be written to w and the resulting stream will
987 // be nil. The resulting stream may also be nil if the stream is complete.
988 //
989 // Importantly, this function must hold the stream mutex until done replaying
990 // all messages, so that no delivery or storage of new messages occurs while
991 // the stream is still replaying.
992 //
993 // protocolVersion is the protocol version for this stream, used to determine
994 // feature support (e.g. prime and close events were added in 2025-11-25).
995 func (c *streamableServerConn) acquireStream(ctx context.Context, w http.ResponseWriter, streamID string, lastIdx int, protocolVersion string) (*stream, chan struct{}) {
996 // if tempStream is set, the stream is done and we're just replaying messages.
997 //
998 // We record a temporary stream to claim exclusive replay rights. The spec
999 // (https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#resumability-and-redelivery)
1000 // does not explicitly require exclusive replay, but we enforce it defensively.
1001 tempStream := false
1002 c.mu.Lock()
1003 s, ok := c.streams[streamID]
1004 if !ok {
1005 // The stream is logically done, but claim exclusive rights to replay it by
1006 // adding a temporary entry in the streams map.
1007 //
1008 // We create this entry with a non-nil w, to ensure it isn't claimed by
1009 // another request before we lock it below.
1010 tempStream = true
1011 s = &stream{
1012 id: streamID,
1013 w: w,
1014 }
1015 c.streams[streamID] = s
1016
1017 // Since this stream is transient, we must clean up after replaying.
1018 defer func() {
1019 c.mu.Lock()
1020 delete(c.streams, streamID)
1021 c.mu.Unlock()
1022 }()
1023 }
1024 c.mu.Unlock()
1025
1026 s.mu.Lock()
1027 defer s.mu.Unlock()
1028
1029 // Check that this stream wasn't claimed by another request.
1030 if !tempStream && s.w != nil {
1031 http.Error(w, "stream ID conflicts with ongoing stream", http.StatusConflict)
1032 return nil, nil
1033 }
1034
1035 // Collect events to replay. Collect them all before writing, so that we
1036 // have an opportunity to set the HTTP status code on an error.
1037 //
1038 // As indicated above, we must do that while holding stream.mu, so that no
1039 // new messages are added to the eventstore until we've replayed all previous
1040 // messages, and registered our delivery function.
1041 var toReplay [][]byte
1042 if c.eventStore != nil {
1043 for data, err := range c.eventStore.After(ctx, c.SessionID(), s.id, lastIdx) {
1044 if err != nil {
1045 // We can't replay events, perhaps because the underlying event store
1046 // has garbage collected its storage.
1047 //
1048 // We must be careful here: any 404 will signal to the client that the
1049 // *session* is not found, rather than the stream.
1050 //
1051 // 400 is not really accurate, but should at least have no side effects.
1052 // Other SDKs (typescript) do not have a mechanism for events to be purged.
1053 http.Error(w, "failed to replay events", http.StatusBadRequest)
1054 return nil, nil
1055 }
1056 if len(data) > 0 {
1057 toReplay = append(toReplay, data)
1058 }
1059 }
1060 }
1061
1062 w.Header().Set("Cache-Control", "no-cache, no-transform")
1063 w.Header().Set("Content-Type", "text/event-stream") // Accept checked in [StreamableHTTPHandler]
1064 w.Header().Set("Connection", "keep-alive")
1065
1066 if s.id == "" {
1067 // Issue #410: the standalone SSE stream is likely not to receive messages
1068 // for a long time. Ensure that headers are flushed.
1069 w.WriteHeader(http.StatusOK)
1070 rc := http.NewResponseController(w)
1071 // Ignore returned error as flushing is best-effort.
1072 _ = rc.Flush()
1073 }
1074
1075 for _, data := range toReplay {
1076 lastIdx++
1077 e := Event{Name: "message", Data: data}
1078 if c.eventStore != nil {
1079 e.ID = formatEventID(s.id, lastIdx)
1080 }
1081 if _, err := writeEvent(w, e); err != nil {
1082 return nil, nil
1083 }
1084 }
1085
1086 if tempStream || s.doneLocked() {
1087 // Nothing more to do.
1088 return nil, nil
1089 }
1090
1091 // The stream is not done: set up delivery state before the stream is
1092 // unlocked, allowing the connection to write new events.
1093 s.w = w
1094 s.done = make(chan struct{})
1095 s.lastIdx = lastIdx
1096 s.protocolVersion = protocolVersion
1097 return s, s.done
1098 }
1099
1100 // servePOST handles an incoming message, and replies with either an outgoing
1101 // message stream or single response object, depending on whether the
1102 // jsonResponse option is set.
1103 //
1104 // It returns an HTTP status code and error message.
1105 func (c *streamableServerConn) servePOST(w http.ResponseWriter, req *http.Request) {
1106 if len(req.Header.Values(lastEventIDHeader)) > 0 {
1107 http.Error(w, "can't send Last-Event-ID for POST request", http.StatusBadRequest)
1108 return
1109 }
1110
1111 // Read incoming messages.
1112 body, err := io.ReadAll(req.Body)
1113 if err != nil {
1114 http.Error(w, "failed to read body", http.StatusBadRequest)
1115 return
1116 }
1117 if len(body) == 0 {
1118 http.Error(w, "POST requires a non-empty body", http.StatusBadRequest)
1119 return
1120 }
1121 // TODO(#674): once we've documented the support matrix for 2025-03-26 and
1122 // earlier, drop support for matching entirely; that will simplify this
1123 // logic.
1124 incoming, isBatch, err := readBatch(body)
1125 if err != nil {
1126 http.Error(w, fmt.Sprintf("malformed payload: %v", err), http.StatusBadRequest)
1127 return
1128 }
1129
1130 protocolVersion := req.Header.Get(protocolVersionHeader)
1131 if protocolVersion == "" {
1132 protocolVersion = protocolVersion20250326
1133 }
1134
1135 if isBatch && protocolVersion >= protocolVersion20250618 {
1136 http.Error(w, fmt.Sprintf("JSON-RPC batching is not supported in %s and later (request version: %s)", protocolVersion20250618, protocolVersion), http.StatusBadRequest)
1137 return
1138 }
1139
1140 // TODO(rfindley): no tests fail if we reject batch JSON requests entirely.
1141 // We need to test this with older protocol versions.
1142 // if isBatch && c.jsonResponse {
1143 // http.Error(w, "server does not support batch requests", http.StatusBadRequest)
1144 // return
1145 // }
1146
1147 calls := make(map[jsonrpc.ID]struct{})
1148 tokenInfo := auth.TokenInfoFromContext(req.Context())
1149 isInitialize := false
1150 var initializeProtocolVersion string
1151 for _, msg := range incoming {
1152 if jreq, ok := msg.(*jsonrpc.Request); ok {
1153 // Preemptively check that this is a valid request, so that we can fail
1154 // the HTTP request. If we didn't do this, a request with a bad method or
1155 // missing ID could be silently swallowed.
1156 if _, err := checkRequest(jreq, serverMethodInfos); err != nil {
1157 http.Error(w, err.Error(), http.StatusBadRequest)
1158 return
1159 }
1160 if jreq.Method == methodInitialize {
1161 isInitialize = true
1162 // Extract the protocol version from InitializeParams.
1163 var params InitializeParams
1164 if err := internaljson.Unmarshal(jreq.Params, &params); err == nil {
1165 initializeProtocolVersion = params.ProtocolVersion
1166 }
1167 }
1168 // Include metadata for all requests (including notifications).
1169 jreq.Extra = &RequestExtra{
1170 TokenInfo: tokenInfo,
1171 Header: req.Header,
1172 }
1173 if jreq.IsCall() {
1174 calls[jreq.ID] = struct{}{}
1175 // See the doc for CloseSSEStream: allow the request handler to
1176 // explicitly close the ongoing stream.
1177 jreq.Extra.(*RequestExtra).CloseSSEStream = func(args CloseSSEStreamArgs) {
1178 c.mu.Lock()
1179 streamID, ok := c.requestStreams[jreq.ID]
1180 var stream *stream
1181 if ok {
1182 stream = c.streams[streamID]
1183 }
1184 c.mu.Unlock()
1185
1186 if stream != nil {
1187 stream.close(args.RetryAfter)
1188 }
1189 }
1190 }
1191 }
1192 }
1193
1194 // Validate MCP standard headers (Mcp-Method, Mcp-Name)
1195 if !isBatch && len(incoming) == 1 {
1196 if err := validateMcpHeaders(req.Header, incoming[0]); err != nil {
1197 resp := &jsonrpc.Response{
1198 Error: jsonrpc2.NewError(CodeHeaderMismatch, err.Error()),
1199 }
1200 if jreq, ok := incoming[0].(*jsonrpc.Request); ok {
1201 resp.ID = jreq.ID
1202 }
1203 w.Header().Set("Content-Type", "application/json")
1204 w.WriteHeader(http.StatusBadRequest)
1205 if data, err := jsonrpc2.EncodeMessage(resp); err == nil {
1206 w.Write(data)
1207 }
1208 return
1209 }
1210 }
1211
1212 // The prime and close events were added in protocol version 2025-11-25 (SEP-1699).
1213 // Use the version from InitializeParams if this is an initialize request,
1214 // otherwise use the protocol version header.
1215 effectiveVersion := protocolVersion
1216 if isInitialize && initializeProtocolVersion != "" {
1217 effectiveVersion = initializeProtocolVersion
1218 }
1219
1220 // If we don't have any calls, we can just publish the incoming messages and return.
1221 // No need to track a logical stream.
1222 //
1223 // See section [§2.1.4] of the spec: "If the server accepts the input, the
1224 // server MUST return HTTP status code 202 Accepted with no body."
1225 //
1226 // [§2.1.4]: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server
1227 if len(calls) == 0 {
1228 for _, msg := range incoming {
1229 select {
1230 case c.incoming <- msg:
1231 case <-c.done:
1232 // The session is closing. Since we haven't yet written any data to the
1233 // response, we can signal to the client that the session is gone.
1234 http.Error(w, "session is closing", http.StatusNotFound)
1235 return
1236 }
1237 }
1238 w.WriteHeader(http.StatusAccepted)
1239 return
1240 }
1241
1242 // Invariant: we have at least one call.
1243 //
1244 // Create a logical stream to track its responses.
1245 // Important: don't publish the incoming messages until the stream is
1246 // registered, as the server may attempt to respond to incoming messages as
1247 // soon as they're published.
1248 stream, err := c.newStream(req.Context(), calls, crand.Text())
1249 if err != nil {
1250 http.Error(w, fmt.Sprintf("storing stream: %v", err), http.StatusInternalServerError)
1251 return
1252 }
1253
1254 // Set response headers. Accept was checked in [StreamableHTTPHandler].
1255 w.Header().Set("Cache-Control", "no-cache, no-transform")
1256 if c.jsonResponse {
1257 w.Header().Set("Content-Type", "application/json")
1258 } else {
1259 w.Header().Set("Content-Type", "text/event-stream")
1260 w.Header().Set("Connection", "keep-alive")
1261 }
1262 if c.sessionID != "" && isInitialize {
1263 w.Header().Set(sessionIDHeader, c.sessionID)
1264 }
1265
1266 // Set up stream delivery state.
1267 stream.w = w
1268 done := make(chan struct{})
1269 stream.done = done
1270 stream.protocolVersion = effectiveVersion
1271 if c.jsonResponse {
1272 // JSON mode: collect messages in pendingJSONMessages until done.
1273 // Set pendingJSONMessages to a non-nil value to signal that this is an
1274 // application/json stream.
1275 stream.pendingJSONMessages = []json.RawMessage{}
1276 } else {
1277 // SSE mode: write a priming event if supported.
1278 if c.eventStore != nil && effectiveVersion >= protocolVersion20251125 {
1279 // Write a priming event, as defined by [§2.1.6] of the spec.
1280 //
1281 // [§2.1.6]: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server
1282 //
1283 // We must also write it to the event store in order for indexes to
1284 // align.
1285 if err := c.eventStore.Append(req.Context(), c.sessionID, stream.id, nil); err != nil {
1286 c.logger.Warn(fmt.Sprintf("Storing priming event: %v", err))
1287 }
1288 stream.lastIdx++
1289 e := Event{Name: "prime", ID: formatEventID(stream.id, stream.lastIdx)}
1290 if _, err := writeEvent(w, e); err != nil {
1291 c.logger.Warn(fmt.Sprintf("Writing priming event: %v", err))
1292 }
1293 }
1294 }
1295
1296 // TODO(rfindley): if we have no event store, we should really cancel all
1297 // remaining requests here, since the client will never get the results.
1298 defer stream.release()
1299
1300 // The stream is now set up to deliver messages.
1301 //
1302 // Register it before publishing incoming messages.
1303 c.mu.Lock()
1304 c.streams[stream.id] = stream
1305 for reqID := range calls {
1306 c.requestStreams[reqID] = stream.id
1307 }
1308 c.mu.Unlock()
1309
1310 // Publish incoming messages.
1311 for _, msg := range incoming {
1312 select {
1313 case c.incoming <- msg:
1314 // Note: don't select on req.Context().Done() here, since we've already
1315 // received the requests and may have already published a response message
1316 // or notification. The client could resume the stream.
1317 //
1318 // In fact, this send could be in a separate goroutine.
1319 case <-c.done:
1320 // Session closed: we don't know if any data has been written, so it's
1321 // too late to write a status code here.
1322 return
1323 }
1324 }
1325
1326 c.hangResponse(req.Context(), done)
1327 }
1328
1329 // Event IDs: encode both the logical connection ID and the index, as
1330 // <streamID>_<idx>, to be consistent with the typescript implementation.
1331
1332 // formatEventID returns the event ID to use for the logical connection ID
1333 // streamID and message index idx.
1334 //
1335 // See also [parseEventID].
1336 func formatEventID(sid string, idx int) string {
1337 return fmt.Sprintf("%s_%d", sid, idx)
1338 }
1339
1340 // parseEventID parses a Last-Event-ID value into a logical stream id and
1341 // index.
1342 //
1343 // See also [formatEventID].
1344 func parseEventID(eventID string) (streamID string, idx int, ok bool) {
1345 parts := strings.Split(eventID, "_")
1346 if len(parts) != 2 {
1347 return "", 0, false
1348 }
1349 streamID = parts[0]
1350 idx, err := strconv.Atoi(parts[1])
1351 if err != nil || idx < 0 {
1352 return "", 0, false
1353 }
1354 return streamID, idx, true
1355 }
1356
1357 // Read implements the [Connection] interface.
1358 func (c *streamableServerConn) Read(ctx context.Context) (jsonrpc.Message, error) {
1359 select {
1360 case <-ctx.Done():
1361 return nil, ctx.Err()
1362 case msg, ok := <-c.incoming:
1363 if !ok {
1364 return nil, io.EOF
1365 }
1366 return msg, nil
1367 case <-c.done:
1368 return nil, io.EOF
1369 }
1370 }
1371
1372 // Write implements the [Connection] interface.
1373 func (c *streamableServerConn) Write(ctx context.Context, msg jsonrpc.Message) error {
1374 // Throughout this function, note that any error that wraps ErrRejected
1375 // indicates a does not cause the connection to break.
1376 //
1377 // Most errors don't break the connection: unlike a true bidirectional
1378 // stream, a failure to deliver to a stream is not an indication that the
1379 // logical session is broken.
1380 data, err := jsonrpc2.EncodeMessage(msg)
1381 if err != nil {
1382 return err
1383 }
1384
1385 if req, ok := msg.(*jsonrpc.Request); ok && req.IsCall() && (c.stateless || c.sessionID == "") {
1386 // Requests aren't possible with stateless servers, or when there's no session ID.
1387 return fmt.Errorf("%w: stateless servers cannot make requests", jsonrpc2.ErrRejected)
1388 }
1389
1390 // Find the incoming request that this write relates to, if any.
1391 var (
1392 relatedRequest jsonrpc.ID
1393 responseTo jsonrpc.ID // if valid, the message is a response to this request
1394 )
1395 if resp, ok := msg.(*jsonrpc.Response); ok {
1396 // If the message is a response, it relates to its request (of course).
1397 relatedRequest = resp.ID
1398 responseTo = resp.ID
1399 } else {
1400 // Otherwise, we check to see if it request was made in the context of an
1401 // ongoing request. This may not be the case if the request was made with
1402 // an unrelated context.
1403 if v := ctx.Value(idContextKey{}); v != nil {
1404 relatedRequest = v.(jsonrpc.ID)
1405 }
1406 }
1407
1408 // If the stream is application/json, but the message is not a response, we
1409 // must send it out of band to the standalone SSE stream.
1410 if c.jsonResponse && !responseTo.IsValid() {
1411 relatedRequest = jsonrpc.ID{}
1412 }
1413
1414 // Write the message to the stream.
1415 var s *stream
1416 c.mu.Lock()
1417 if relatedRequest.IsValid() {
1418 if streamID, ok := c.requestStreams[relatedRequest]; ok {
1419 s = c.streams[streamID]
1420 }
1421 } else {
1422 s = c.streams[""] // standalone SSE stream
1423 }
1424 if responseTo.IsValid() {
1425 // Once we've responded to a request, disallow related messages by removing
1426 // the stream association. This also releases memory.
1427 delete(c.requestStreams, responseTo)
1428 }
1429 sessionClosed := c.isDone
1430 c.mu.Unlock()
1431
1432 if s == nil {
1433 // The request was made in the context of an ongoing request, but that
1434 // request is complete.
1435 //
1436 // In the future, we could be less strict and allow the request to land on
1437 // the standalone SSE stream.
1438 return fmt.Errorf("%w: write to closed stream", jsonrpc2.ErrRejected)
1439 }
1440 if sessionClosed {
1441 return errors.New("session is closed")
1442 }
1443
1444 s.mu.Lock()
1445 defer s.mu.Unlock()
1446
1447 // Store in eventStore before delivering.
1448 // TODO(rfindley): we should only append if the response is SSE, not JSON, by
1449 // pushing down into the delivery layer.
1450 delivered := false
1451 var errs []error
1452 if c.eventStore != nil {
1453 if err := c.eventStore.Append(ctx, c.sessionID, s.id, data); err != nil {
1454 errs = append(errs, err)
1455 } else {
1456 delivered = true
1457 }
1458 }
1459
1460 // Compute eventID for SSE streams with event store.
1461 // Use s.lastIdx + 1 because deliverLocked increments before writing.
1462 var eventID string
1463 if c.eventStore != nil {
1464 eventID = formatEventID(s.id, s.lastIdx+1)
1465 }
1466
1467 done, err := s.deliverLocked(data, eventID, responseTo)
1468 if err != nil {
1469 errs = append(errs, err)
1470 } else {
1471 delivered = true
1472 }
1473
1474 if done {
1475 c.mu.Lock()
1476 delete(c.streams, s.id)
1477 c.mu.Unlock()
1478 }
1479
1480 if !delivered {
1481 return fmt.Errorf("%w: undelivered message: %v", jsonrpc2.ErrRejected, errors.Join(errs...))
1482 }
1483 return nil
1484 }
1485
1486 // Close implements the [Connection] interface.
1487 func (c *streamableServerConn) Close() error {
1488 c.mu.Lock()
1489 defer c.mu.Unlock()
1490 if !c.isDone {
1491 c.isDone = true
1492 close(c.done)
1493 if c.eventStore != nil {
1494 // TODO: find a way to plumb a context here, or an event store with a long-running
1495 // close operation can take arbitrary time. Alternative: impose a fixed timeout here.
1496 return c.eventStore.SessionClosed(context.TODO(), c.sessionID)
1497 }
1498 }
1499 return nil
1500 }
1501
1502 // A StreamableClientTransport is a [Transport] that can communicate with an MCP
1503 // endpoint serving the streamable HTTP transport defined by the 2025-03-26
1504 // version of the spec.
1505 type StreamableClientTransport struct {
1506 Endpoint string
1507 HTTPClient *http.Client
1508 // MaxRetries is the maximum number of times to attempt a reconnect before giving up.
1509 // It defaults to 5. To disable retries, use a negative number.
1510 MaxRetries int
1511
1512 // DisableStandaloneSSE controls whether the client establishes a standalone SSE stream
1513 // for receiving server-initiated messages.
1514 //
1515 // When false (the default), after initialization the client sends an HTTP GET request
1516 // to establish a persistent server-sent events (SSE) connection. This allows the server
1517 // to send messages to the client at any time, such as ToolListChangedNotification or
1518 // other server-initiated requests and notifications. The connection persists for the
1519 // lifetime of the session and automatically reconnects if interrupted.
1520 //
1521 // When true, the client does not establish the standalone SSE stream. The client will
1522 // only receive responses to its own POST requests. Server-initiated messages will not
1523 // be received.
1524 //
1525 // According to the MCP specification, the standalone SSE stream is optional.
1526 // Setting DisableStandaloneSSE to true is useful when:
1527 // - You only need request-response communication and don't need server-initiated notifications
1528 // - The server doesn't properly handle GET requests for SSE streams
1529 // - You want to avoid maintaining a persistent connection
1530 DisableStandaloneSSE bool
1531
1532 // OAuthHandler is an optional field that, if provided, will be used to authorize the requests.
1533 OAuthHandler auth.OAuthHandler
1534
1535 // TODO(rfindley): propose exporting these.
1536 // If strict is set, the transport is in 'strict mode', where any violation
1537 // of the MCP spec causes a failure.
1538 strict bool
1539 // If logger is set, it is used to log aspects of the transport, such as spec
1540 // violations that were ignored.
1541 logger *slog.Logger
1542 }
1543
1544 // These settings are not (yet) exposed to the user in
1545 // StreamableClientTransport.
1546 const (
1547 // reconnectGrowFactor is the multiplicative factor by which the delay increases after each attempt.
1548 // A value of 1.0 results in a constant delay, while a value of 2.0 would double it each time.
1549 // It must be 1.0 or greater if MaxRetries is greater than 0.
1550 reconnectGrowFactor = 1.5
1551 // reconnectMaxDelay caps the backoff delay, preventing it from growing indefinitely.
1552 reconnectMaxDelay = 30 * time.Second
1553 )
1554
1555 var (
1556 // reconnectInitialDelay is the base delay for the first reconnect attempt.
1557 //
1558 // Mutable for testing.
1559 reconnectInitialDelay atomic.Int64
1560 )
1561
1562 func init() {
1563 reconnectInitialDelay.Store(int64(1 * time.Second))
1564 }
1565
1566 // Connect implements the [Transport] interface.
1567 //
1568 // The resulting [Connection] writes messages via POST requests to the
1569 // transport URL with the Mcp-Session-Id header set, and reads messages from
1570 // hanging requests.
1571 //
1572 // When closed, the connection issues a DELETE request to terminate the logical
1573 // session.
1574 func (t *StreamableClientTransport) Connect(ctx context.Context) (Connection, error) {
1575 client := t.HTTPClient
1576 if client == nil {
1577 client = http.DefaultClient
1578 }
1579 maxRetries := t.MaxRetries
1580 if maxRetries == 0 {
1581 maxRetries = 5
1582 } else if maxRetries < 0 {
1583 maxRetries = 0
1584 }
1585 // Create a new cancellable context that will manage the connection's lifecycle.
1586 // This is crucial for cleanly shutting down the background SSE listener by
1587 // cancelling its blocking network operations, which prevents hangs on exit.
1588 //
1589 // This context should be detached from the incoming context: the standalone
1590 // SSE request should not break when the connection context is done.
1591 //
1592 // For example, consider that the user may want to wait at most 5s to connect
1593 // to the server, and therefore uses a context with a 5s timeout when calling
1594 // client.Connect. Let's suppose that Connect returns after 1s, and the user
1595 // starts using the resulting session. If we didn't detach here, the session
1596 // would break after 4s, when the background SSE stream is terminated.
1597 //
1598 // Instead, creating a cancellable context detached from the incoming context
1599 // allows us to preserve context values (which may be necessary for auth
1600 // middleware), yet only cancel the standalone stream when the connection is closed.
1601 connCtx, cancel := context.WithCancel(xcontext.Detach(ctx))
1602 conn := &streamableClientConn{
1603 url: t.Endpoint,
1604 client: client,
1605 incoming: make(chan jsonrpc.Message, 10),
1606 done: make(chan struct{}),
1607 maxRetries: maxRetries,
1608 strict: t.strict,
1609 logger: ensureLogger(t.logger), // must be non-nil for safe logging
1610 ctx: connCtx,
1611 cancel: cancel,
1612 failed: make(chan struct{}),
1613 disableStandaloneSSE: t.DisableStandaloneSSE,
1614 oauthHandler: t.OAuthHandler,
1615 }
1616 return conn, nil
1617 }
1618
1619 type streamableClientConn struct {
1620 url string
1621 client *http.Client
1622 ctx context.Context // connection context, detached from Connect
1623 cancel context.CancelFunc // cancels ctx
1624 incoming chan jsonrpc.Message
1625 maxRetries int
1626 strict bool // from [StreamableClientTransport.strict]
1627 logger *slog.Logger // from [StreamableClientTransport.logger]
1628
1629 // disableStandaloneSSE controls whether to disable the standalone SSE stream
1630 // for receiving server-to-client notifications when no request is in flight.
1631 disableStandaloneSSE bool // from [StreamableClientTransport.DisableStandaloneSSE]
1632
1633 // oauthHandler is the OAuth handler for the connection.
1634 oauthHandler auth.OAuthHandler // from [StreamableClientTransport.OAuthHandler]
1635
1636 // Guard calls to Close, as it may be called multiple times.
1637 closeOnce sync.Once
1638 closeErr error
1639 done chan struct{} // signal graceful termination
1640
1641 // Logical reads are distributed across multiple http requests. Whenever any
1642 // of them fails to process their response, we must break the connection, by
1643 // failing the pending Read.
1644 //
1645 // Achieve this by storing the failure message, and signalling when reads are
1646 // broken. See also [streamableClientConn.fail] and
1647 // [streamableClientConn.failure].
1648 failOnce sync.Once
1649 _failure error
1650 failed chan struct{} // signal failure
1651
1652 // Guard the initialization state.
1653 mu sync.Mutex
1654 initializedResult *InitializeResult
1655 sessionID string
1656 }
1657
1658 var _ clientConnection = (*streamableClientConn)(nil)
1659
1660 func (c *streamableClientConn) sessionUpdated(state clientSessionState) {
1661 c.mu.Lock()
1662 c.initializedResult = state.InitializeResult
1663 c.mu.Unlock()
1664
1665 // Start the standalone SSE stream as soon as we have the initialized
1666 // result, if continuous listening is enabled.
1667 //
1668 // § 2.2: The client MAY issue an HTTP GET to the MCP endpoint. This can be
1669 // used to open an SSE stream, allowing the server to communicate to the
1670 // client, without the client first sending data via HTTP POST.
1671 //
1672 // We have to wait for initialized, because until we've received
1673 // initialized, we don't know whether the server requires a sessionID.
1674 //
1675 // § 2.5: A server using the Streamable HTTP transport MAY assign a session
1676 // ID at initialization time, by including it in a Mcp-Session-Id header
1677 // on the HTTP response containing the InitializeResult.
1678 if !c.disableStandaloneSSE {
1679 c.connectStandaloneSSE()
1680 }
1681 }
1682
1683 func (c *streamableClientConn) connectStandaloneSSE() {
1684 resp, err := c.connectSSE(c.ctx, "", 0, true)
1685 if err != nil {
1686 // If the client didn't cancel the request, and failure breaks the logical
1687 // session.
1688 if c.ctx.Err() == nil {
1689 c.fail(fmt.Errorf("standalone SSE request failed (session ID: %v): %v", c.sessionID, err))
1690 }
1691 return
1692 }
1693
1694 // [§2.2.3]: "The server MUST either return Content-Type:
1695 // text/event-stream in response to this HTTP GET, or else return HTTP
1696 // 405 Method Not Allowed, indicating that the server does not offer an
1697 // SSE stream at this endpoint."
1698 //
1699 // [§2.2.3]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#listening-for-messages-from-the-server
1700 if resp.StatusCode == http.StatusMethodNotAllowed {
1701 // The server doesn't support the standalone SSE stream.
1702 resp.Body.Close()
1703 return
1704 }
1705 if baseMediaType(resp.Header.Get("Content-Type")) != "text/event-stream" {
1706 // modelcontextprotocol/go-sdk#736: some servers return 200 OK or redirect with
1707 // non-SSE content type instead of text/event-stream for the standalone
1708 // SSE stream.
1709 c.logger.Warn(fmt.Sprintf("got Content-Type %s instead of text/event-stream for standalone SSE stream", resp.Header.Get("Content-Type")))
1710 resp.Body.Close()
1711 return
1712 }
1713 if resp.StatusCode >= 400 && resp.StatusCode < 500 && !c.strict {
1714 // modelcontextprotocol/go-sdk#393,#610: some servers return NotFound or
1715 // other status codes instead of MethodNotAllowed for the standalone SSE
1716 // stream.
1717 //
1718 // Treat this like MethodNotAllowed in non-strict mode.
1719 c.logger.Warn(fmt.Sprintf("got %d instead of 405 for standalone SSE stream", resp.StatusCode))
1720 resp.Body.Close()
1721 return
1722 }
1723 summary := "standalone SSE stream"
1724 if err := c.checkResponse(summary, resp); err != nil {
1725 c.fail(err)
1726 return
1727 }
1728 go c.handleSSE(c.ctx, summary, resp, nil)
1729 }
1730
1731 // fail handles an asynchronous error while reading.
1732 //
1733 // If err is non-nil, it is terminal, and subsequent (or pending) Reads will
1734 // fail.
1735 //
1736 // If err wraps ErrSessionMissing, the failure indicates that the session is no
1737 // longer present on the server, and no final DELETE will be performed when
1738 // closing the connection.
1739 func (c *streamableClientConn) fail(err error) {
1740 if err != nil {
1741 c.failOnce.Do(func() {
1742 c._failure = err
1743 close(c.failed)
1744 })
1745 }
1746 }
1747
1748 func (c *streamableClientConn) failure() error {
1749 select {
1750 case <-c.failed:
1751 return c._failure
1752 default:
1753 return nil
1754 }
1755 }
1756
1757 func (c *streamableClientConn) SessionID() string {
1758 c.mu.Lock()
1759 defer c.mu.Unlock()
1760 return c.sessionID
1761 }
1762
1763 // Read implements the [Connection] interface.
1764 func (c *streamableClientConn) Read(ctx context.Context) (jsonrpc.Message, error) {
1765 if err := c.failure(); err != nil {
1766 return nil, err
1767 }
1768 select {
1769 case <-ctx.Done():
1770 return nil, ctx.Err()
1771 case <-c.failed:
1772 return nil, c.failure()
1773 case <-c.done:
1774 return nil, io.EOF
1775 case msg := <-c.incoming:
1776 return msg, nil
1777 }
1778 }
1779
1780 // Write implements the [Connection] interface.
1781 func (c *streamableClientConn) Write(ctx context.Context, msg jsonrpc.Message) error {
1782 if err := c.failure(); err != nil {
1783 return err
1784 }
1785
1786 var requestSummary string
1787 var forCall *jsonrpc.Request
1788 switch msg := msg.(type) {
1789 case *jsonrpc.Request:
1790 requestSummary = fmt.Sprintf("sending %q", msg.Method)
1791 if msg.IsCall() {
1792 forCall = msg
1793 }
1794 case *jsonrpc.Response:
1795 requestSummary = fmt.Sprintf("sending jsonrpc response #%d", msg.ID)
1796 default:
1797 panic("unreachable")
1798 }
1799
1800 data, err := jsonrpc.EncodeMessage(msg)
1801 if err != nil {
1802 return fmt.Errorf("%s: %v", requestSummary, err)
1803 }
1804
1805 doRequest := func() (*http.Request, *http.Response, error) {
1806 req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(data))
1807 if err != nil {
1808 return nil, nil, err
1809 }
1810 req.Header.Set("Content-Type", "application/json")
1811 req.Header.Set("Accept", "application/json, text/event-stream")
1812 if err := c.setMCPHeaders(req); err != nil {
1813 // Failure to set headers means that the request was not sent.
1814 // Wrap with ErrRejected so the jsonrpc2 connection doesn't set writeErr
1815 // and permanently break the connection.
1816 return nil, nil, fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err)
1817 }
1818 // Keep this after the setMCPHeaders call to ensure that the
1819 // protocol version header is set.
1820 setStandardHeaders(req.Header, msg)
1821 resp, err := c.client.Do(req)
1822 if err != nil {
1823 // Any error from client.Do means the request didn't reach the server.
1824 // Wrap with ErrRejected so the jsonrpc2 connection doesn't set writeErr
1825 // and permanently break the connection.
1826 err = fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err)
1827 }
1828 return req, resp, err
1829 }
1830
1831 req, resp, err := doRequest()
1832 if err != nil {
1833 return err
1834 }
1835
1836 if (resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden) && c.oauthHandler != nil {
1837 if err := c.oauthHandler.Authorize(ctx, req, resp); err != nil {
1838 // If the caller's context was cancelled while we were running the
1839 // authorization flow, treat the connection as failed so subsequent
1840 // operations on it (e.g. the cancellation notify the call layer
1841 // sends in response to ctx cancellation) short-circuit instead of
1842 // re-invoking the OAuth handler. Otherwise the user gets prompted
1843 // to authorize a request they have already abandoned. See #882.
1844 //
1845 // We check ctx.Err() rather than the error returned by Authorize,
1846 // because the handler is user-implemented and may return an error
1847 // that does not wrap context.Canceled (e.g. a custom sentinel or
1848 // a fmt.Errorf with %v). The context itself is the authoritative
1849 // source for whether the caller abandoned the request.
1850 ctxErr := ctx.Err()
1851 if errors.Is(ctxErr, context.Canceled) || errors.Is(ctxErr, context.DeadlineExceeded) {
1852 c.fail(fmt.Errorf("%s: authorization cancelled: %w", requestSummary, err))
1853 }
1854 // Wrap with ErrRejected so the jsonrpc2 connection doesn't set writeErr
1855 // and permanently break the connection.
1856 // Wrap the authorization error as well for client inspection.
1857 return fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err)
1858 }
1859 // Retry the request after successful authorization.
1860 _, resp, err = doRequest()
1861 if err != nil {
1862 return err
1863 }
1864 }
1865
1866 if err := c.checkResponse(requestSummary, resp); err != nil {
1867 // Only fail the connection for non-transient errors.
1868 // Transient errors (wrapped with ErrRejected) should not break the connection.
1869 if !errors.Is(err, jsonrpc2.ErrRejected) {
1870 c.fail(err)
1871 }
1872 return err
1873 }
1874
1875 if sessionID := resp.Header.Get(sessionIDHeader); sessionID != "" {
1876 c.mu.Lock()
1877 hadSessionID := c.sessionID
1878 if hadSessionID == "" {
1879 c.sessionID = sessionID
1880 }
1881 c.mu.Unlock()
1882 if hadSessionID != "" && hadSessionID != sessionID {
1883 resp.Body.Close()
1884 return fmt.Errorf("mismatching session IDs %q and %q", hadSessionID, sessionID)
1885 }
1886 }
1887
1888 if forCall == nil {
1889 resp.Body.Close()
1890
1891 // [§2.1.4]: "If the input is a JSON-RPC response or notification:
1892 // If the server accepts the input, the server MUST return HTTP status code 202 Accepted with no body."
1893 //
1894 // [§2.1.4]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#listening-for-messages-from-the-server
1895 if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusAccepted {
1896 errMsg := fmt.Sprintf("unexpected status code %d from non-call", resp.StatusCode)
1897 // Some servers return 200, even with an empty json body.
1898 //
1899 // In strict mode, return an error to the caller.
1900 c.logger.Warn(errMsg)
1901 if c.strict {
1902 return errors.New(errMsg)
1903 }
1904 }
1905 return nil
1906 }
1907
1908 contentType := baseMediaType(resp.Header.Get("Content-Type"))
1909 switch contentType {
1910 case "application/json":
1911 go c.handleJSON(requestSummary, resp)
1912
1913 case "text/event-stream":
1914 var forCall *jsonrpc.Request
1915 if jsonReq, ok := msg.(*jsonrpc.Request); ok && jsonReq.IsCall() {
1916 forCall = jsonReq
1917 }
1918 // Handle the resulting stream. Note that ctx comes from the call, and
1919 // therefore is already cancelled when the JSON-RPC request is cancelled
1920 // (or rather, context cancellation is what *triggers* JSON-RPC
1921 // cancellation)
1922 go c.handleSSE(ctx, requestSummary, resp, forCall)
1923
1924 default:
1925 resp.Body.Close()
1926 return fmt.Errorf("%s: unsupported content type %q", requestSummary, contentType)
1927 }
1928 return nil
1929 }
1930
1931 func (c *streamableClientConn) setMCPHeaders(req *http.Request) error {
1932 c.mu.Lock()
1933 defer c.mu.Unlock()
1934
1935 if c.oauthHandler != nil {
1936 ts, err := c.oauthHandler.TokenSource(c.ctx)
1937 if err != nil {
1938 return err
1939 }
1940 if ts != nil {
1941 token, err := ts.Token()
1942 if err != nil {
1943 return err
1944 }
1945 if token != nil {
1946 req.Header.Set("Authorization", "Bearer "+token.AccessToken)
1947 }
1948 }
1949 }
1950 if c.initializedResult != nil {
1951 req.Header.Set(protocolVersionHeader, c.initializedResult.ProtocolVersion)
1952 }
1953 if c.sessionID != "" {
1954 req.Header.Set(sessionIDHeader, c.sessionID)
1955 }
1956
1957 return nil
1958 }
1959
1960 func (c *streamableClientConn) handleJSON(requestSummary string, resp *http.Response) {
1961 body, err := io.ReadAll(resp.Body)
1962 resp.Body.Close()
1963 if err != nil {
1964 c.fail(fmt.Errorf("%s: failed to read body: %v", requestSummary, err))
1965 return
1966 }
1967 msg, err := jsonrpc.DecodeMessage(body)
1968 if err != nil {
1969 c.fail(fmt.Errorf("%s: failed to decode response: %v", requestSummary, err))
1970 return
1971 }
1972 select {
1973 case c.incoming <- msg:
1974 case <-c.done:
1975 // The connection was closed by the client; exit gracefully.
1976 }
1977 }
1978
1979 // handleSSE manages the lifecycle of an SSE connection. It can be either
1980 // persistent (for the main GET listener) or temporary (for a POST response).
1981 //
1982 // If forCall is set, it is the call that initiated the stream, and the
1983 // stream is complete when we receive its response. Otherwise, this is the
1984 // standalone stream.
1985 func (c *streamableClientConn) handleSSE(ctx context.Context, requestSummary string, resp *http.Response, forCall *jsonrpc2.Request) {
1986 // Track the last event ID to detect progress.
1987 // The retry counter is only reset when progress is made (lastEventID advances).
1988 // This prevents infinite retry loops when a server repeatedly terminates
1989 // connections without making progress (#679).
1990 var prevLastEventID string
1991 retriesWithoutProgress := 0
1992
1993 for {
1994 lastEventID, reconnectDelay, clientClosed := c.processStream(ctx, requestSummary, resp, forCall)
1995
1996 // If the connection was closed by the client, we're done.
1997 if clientClosed {
1998 return
1999 }
2000 // If we don't have a last event ID, we can never get the call response, so
2001 // there's nothing to resume. For the standalone stream, we can reconnect,
2002 // but we may just miss messages.
2003 if lastEventID == "" && forCall != nil {
2004 return
2005 }
2006
2007 // Check if we made progress (lastEventID advanced).
2008 // Only reset the retry counter when actual progress is made.
2009 if lastEventID != "" && lastEventID != prevLastEventID {
2010 // Progress was made: reset the retry counter.
2011 retriesWithoutProgress = 0
2012 prevLastEventID = lastEventID
2013 } else {
2014 // No progress: increment the retry counter.
2015 retriesWithoutProgress++
2016 if retriesWithoutProgress > c.maxRetries {
2017 if ctx.Err() == nil {
2018 c.fail(fmt.Errorf("%s: exceeded %d retries without progress (session ID: %v)", requestSummary, c.maxRetries, c.sessionID))
2019 }
2020 return
2021 }
2022 }
2023
2024 // The stream was interrupted or ended by the server. Attempt to reconnect.
2025 newResp, err := c.connectSSE(ctx, lastEventID, reconnectDelay, false)
2026 if err != nil {
2027 // If the client didn't cancel this request, any failure to execute it
2028 // breaks the logical MCP session.
2029 if ctx.Err() == nil {
2030 // All reconnection attempts failed: fail the connection.
2031 c.fail(fmt.Errorf("%s: failed to reconnect (session ID: %v): %v", requestSummary, c.sessionID, err))
2032 }
2033 return
2034 }
2035
2036 resp = newResp
2037 if err := c.checkResponse(requestSummary, resp); err != nil {
2038 c.fail(err)
2039 return
2040 }
2041 }
2042 }
2043
2044 // checkResponse checks the status code of the provided response, and
2045 // translates it into an error if the request was unsuccessful.
2046 //
2047 // The response body is close if a non-nil error is returned.
2048 func (c *streamableClientConn) checkResponse(requestSummary string, resp *http.Response) (err error) {
2049 defer func() {
2050 if err != nil {
2051 resp.Body.Close()
2052 }
2053 }()
2054 // §2.5.3: "The server MAY terminate the session at any time, after
2055 // which it MUST respond to requests containing that session ID with HTTP
2056 // 404 Not Found."
2057 if resp.StatusCode == http.StatusNotFound {
2058 // Return an ErrSessionMissing to avoid sending a redundant DELETE when the
2059 // session is already gone.
2060 return fmt.Errorf("%s: failed to connect (session ID: %v): %w", requestSummary, c.sessionID, ErrSessionMissing)
2061 }
2062 // Transient server errors (502, 503, 504, 429) should not break the connection.
2063 // Wrap them with ErrRejected so the jsonrpc2 layer doesn't set writeErr.
2064 if isTransientHTTPStatus(resp.StatusCode) {
2065 return fmt.Errorf("%w: %s: %v", jsonrpc2.ErrRejected, requestSummary, http.StatusText(resp.StatusCode))
2066 }
2067 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
2068 return fmt.Errorf("%s: %v", requestSummary, http.StatusText(resp.StatusCode))
2069 }
2070 return nil
2071 }
2072
2073 // processStream reads from a single response body, sending events to the
2074 // incoming channel. It returns the ID of the last processed event and a flag
2075 // indicating if the connection was closed by the client. If resp is nil, it
2076 // returns "", false.
2077 func (c *streamableClientConn) processStream(ctx context.Context, requestSummary string, resp *http.Response, forCall *jsonrpc.Request) (lastEventID string, reconnectDelay time.Duration, clientClosed bool) {
2078 defer func() {
2079 // Drain any remaining unprocessed body. This allows the connection to be re-used after closing.
2080 io.Copy(io.Discard, resp.Body)
2081 resp.Body.Close()
2082 }()
2083 for evt, err := range scanEvents(resp.Body) {
2084 if err != nil {
2085 if ctx.Err() != nil {
2086 return "", 0, true // don't reconnect: client cancelled
2087 }
2088
2089 // Malformed events are hard errors that indicate corrupted data or protocol
2090 // violations. These should fail the connection permanently.
2091 if errors.Is(err, errMalformedEvent) {
2092 c.fail(fmt.Errorf("%s: %v", requestSummary, err))
2093 return "", 0, true
2094 }
2095
2096 break
2097 }
2098
2099 if evt.ID != "" {
2100 lastEventID = evt.ID
2101 }
2102
2103 if evt.Retry != "" {
2104 if n, err := strconv.ParseInt(evt.Retry, 10, 64); err == nil {
2105 reconnectDelay = time.Duration(n) * time.Millisecond
2106 }
2107 }
2108
2109 // According to SSE specification
2110 // (https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation)
2111 // events with an empty data buffer are allowed.
2112 // In MCP these can be priming events (SEP-1699) that carry only a Last-Event-ID for stream resumption.
2113 if len(evt.Data) == 0 {
2114 continue
2115 }
2116
2117 // According to SSE spec, events with no name default to "message"
2118 if evt.Name != "" && evt.Name != "message" {
2119 continue
2120 }
2121
2122 msg, err := jsonrpc.DecodeMessage(evt.Data)
2123 if err != nil {
2124 c.fail(fmt.Errorf("%s: failed to decode event: %v", requestSummary, err))
2125 return "", 0, true
2126 }
2127
2128 select {
2129 case c.incoming <- msg:
2130 // Check if this is the response to our call, which terminates the request.
2131 // (it could also be a server->client request or notification).
2132 if jsonResp, ok := msg.(*jsonrpc.Response); ok && forCall != nil {
2133 // TODO: we should never get a response when forReq is nil (the standalone SSE request).
2134 // We should detect this case.
2135 if jsonResp.ID == forCall.ID {
2136 return "", 0, true
2137 }
2138 }
2139
2140 case <-c.done:
2141 // The connection was closed by the client; exit gracefully.
2142 return "", 0, true
2143 }
2144 }
2145 // The loop finished without an error, indicating the server closed the stream.
2146 //
2147 // If the lastEventID is "", the stream is not retryable and we should
2148 // report a synthetic error for the call.
2149 //
2150 // Note that this is different from the cancellation case above, since the
2151 // caller is still waiting for a response that will never come.
2152 if lastEventID == "" && forCall != nil {
2153 errmsg := &jsonrpc2.Response{
2154 ID: forCall.ID,
2155 Error: fmt.Errorf("request terminated without response"),
2156 }
2157 select {
2158 case c.incoming <- errmsg:
2159 case <-c.done:
2160 }
2161 }
2162 return lastEventID, reconnectDelay, false
2163 }
2164
2165 // connectSSE handles the logic of connecting a text/event-stream connection.
2166 //
2167 // If lastEventID is set, it is the last-event ID of a stream being resumed.
2168 //
2169 // If connection fails, connectSSE retries with an exponential backoff
2170 // strategy. It returns a new, valid HTTP response if successful, or an error
2171 // if all retries are exhausted.
2172 //
2173 // reconnectDelay is the delay set by the server using the SSE retry field, or
2174 // 0.
2175 //
2176 // If initial is set, this is the initial attempt.
2177 //
2178 // If connectSSE exits due to context cancellation, the result is (nil, ctx.Err()).
2179 func (c *streamableClientConn) connectSSE(ctx context.Context, lastEventID string, reconnectDelay time.Duration, initial bool) (*http.Response, error) {
2180 var finalErr error
2181 attempt := 0
2182 if !initial {
2183 // We've already connected successfully once, so delay subsequent
2184 // reconnections. Otherwise, if the server returns 200 but terminates the
2185 // connection, we'll reconnect as fast as we can, ad infinitum.
2186 //
2187 // TODO: we should consider also setting a limit on total attempts for one
2188 // logical request.
2189 attempt = 1
2190 }
2191 delay := calculateReconnectDelay(attempt)
2192 if reconnectDelay > 0 {
2193 delay = reconnectDelay // honor the server's requested initial delay
2194 }
2195 for ; attempt <= c.maxRetries; attempt++ {
2196 select {
2197 case <-c.done:
2198 return nil, fmt.Errorf("connection closed by client during reconnect")
2199
2200 case <-ctx.Done():
2201 // If the connection context is canceled, the request below will not
2202 // succeed anyway.
2203 return nil, ctx.Err()
2204
2205 case <-time.After(delay):
2206 req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil)
2207 if err != nil {
2208 return nil, err
2209 }
2210 if err := c.setMCPHeaders(req); err != nil {
2211 return nil, err
2212 }
2213 if lastEventID != "" {
2214 req.Header.Set(lastEventIDHeader, lastEventID)
2215 }
2216 req.Header.Set("Accept", "text/event-stream")
2217 resp, err := c.client.Do(req)
2218 if err != nil {
2219 finalErr = err // Store the error and try again.
2220 delay = calculateReconnectDelay(attempt + 1)
2221 continue
2222 }
2223 return resp, nil
2224 }
2225 }
2226 // If the loop completes, all retries have failed, or the client is closing.
2227 if finalErr != nil {
2228 return nil, fmt.Errorf("connection failed after %d attempts: %w", c.maxRetries, finalErr)
2229 }
2230 return nil, fmt.Errorf("connection aborted after %d attempts", c.maxRetries)
2231 }
2232
2233 // Close implements the [Connection] interface.
2234 func (c *streamableClientConn) Close() error {
2235 c.closeOnce.Do(func() {
2236 if errors.Is(c.failure(), ErrSessionMissing) {
2237 // If the session is missing, no need to delete it.
2238 } else {
2239 req, err := http.NewRequestWithContext(c.ctx, http.MethodDelete, c.url, nil)
2240 if err != nil {
2241 c.closeErr = err
2242 } else {
2243 if err := c.setMCPHeaders(req); err != nil {
2244 c.closeErr = err
2245 } else if _, err := c.client.Do(req); err != nil {
2246 c.closeErr = err
2247 }
2248 }
2249 }
2250
2251 // Cancel any hanging network requests after cleanup.
2252 c.cancel()
2253 close(c.done)
2254 })
2255 return c.closeErr
2256 }
2257
2258 // calculateReconnectDelay calculates a delay using exponential backoff with full jitter.
2259 func calculateReconnectDelay(attempt int) time.Duration {
2260 if attempt == 0 {
2261 return 0
2262 }
2263 // Calculate the exponential backoff using the grow factor.
2264 backoffDuration := time.Duration(float64(reconnectInitialDelay.Load()) * math.Pow(reconnectGrowFactor, float64(attempt-1)))
2265 // Cap the backoffDuration at maxDelay.
2266 backoffDuration = min(backoffDuration, reconnectMaxDelay)
2267
2268 // Use a full jitter using backoffDuration
2269 jitter := rand.N(backoffDuration)
2270
2271 return backoffDuration + jitter
2272 }
2273
2274 // isTransientHTTPStatus reports whether the HTTP status code indicates a
2275 // transient server error that should not permanently break the connection.
2276 func isTransientHTTPStatus(statusCode int) bool {
2277 switch statusCode {
2278 case http.StatusInternalServerError, // 500
2279 http.StatusBadGateway, // 502
2280 http.StatusServiceUnavailable, // 503
2281 http.StatusGatewayTimeout, // 504
2282 http.StatusTooManyRequests: // 429
2283 return true
2284 }
2285 return false
2286 }