From d3d7b335d00d5e645a04cb36f6521eebc030d893 Mon Sep 17 00:00:00 2001 From: Abdullah Al Mahmud Date: Sat, 26 Sep 2026 11:52:27 -0500 Subject: [PATCH 1/2] mcp: start a new session when the server answers 404 The 2025-11-25 transport requires it: "When a client receives HTTP 404 in response to a request containing an MCP-Session-Id, it MUST start a new session by sending a new InitializeRequest without a session ID attached." The streamable client treated that 404 as terminal instead, so a ClientSession that outlived a server restart or an evicted session failed every later call with ErrSessionMissing. streamableClientConn now keeps the initialize request it sent. On a 404 for a request carrying the session ID, reinitialize re-sends it without a session ID, adopts the new session ID, sends notifications/initialized and restarts the standalone SSE stream; the failed POST is then sent once more, since the server did not process it. Concurrent 404s share one re-initialization. The standalone stream triggers the same recovery. After a restart its reconnect is usually the first request to get the 404, and it used to fail the connection before the application sent anything. A call whose response stream is lost with the old session is neither resumed nor resent, since its effects may already have happened; it fails with ErrSessionMissing and the connection stays up. Resumption requests now carry the session ID of the stream they resume. The 404 stays terminal when the new session would negotiate a different protocol version, so that the ClientSession above the connection stays valid, and when the session sent resources/subscribe or logging/setLevel, whose state a new session would silently drop. Setting MCPGODEBUG=nosessionreinit=1 restores the previous behavior. Fixes #1299 Co-Authored-By: Claude Opus 5.5 --- docs/mcpgodebug.md | 11 ++ internal/docs/mcpgodebug.src.md | 11 ++ mcp/streamable.go | 298 +++++++++++++++++++++++++++-- mcp/streamable_client.go | 14 +- mcp/streamable_client_test.go | 323 ++++++++++++++++++++++++++++++++ mcp/streamable_test.go | 6 + 6 files changed, 645 insertions(+), 18 deletions(-) diff --git a/docs/mcpgodebug.md b/docs/mcpgodebug.md index 43a62ce8f..69a7e95bc 100644 --- a/docs/mcpgodebug.md +++ b/docs/mcpgodebug.md @@ -28,6 +28,17 @@ Options listed below were added and will be removed in the 1.11.0 version of the that large integers and other exact JSON values do not silently lose precision. +- `nosessionreinit` added. If set to `1`, the streamable HTTP client treats a + `404 Not Found` response to a request carrying an `Mcp-Session-Id` as + terminal, failing the connection with an error wrapping `ErrSessionMissing`, + restoring the previous behavior. The default behavior was changed to follow + the 2025-11-25 specification, which requires the client to start a new + session: the client re-sends its `initialize` request without a session ID, + adopts the new session ID and sends the failed request again. The 404 stays + terminal when the session holds server-side state that a new session would + lose (a `resources/subscribe` subscription or a `logging/setLevel` level) or + when the server negotiates a different protocol version. See issue #1299. + ### 1.8.0 Options listed below were added and will be removed in the 1.9.0 version of the SDK. diff --git a/internal/docs/mcpgodebug.src.md b/internal/docs/mcpgodebug.src.md index 8d1385f27..20fce28aa 100644 --- a/internal/docs/mcpgodebug.src.md +++ b/internal/docs/mcpgodebug.src.md @@ -27,6 +27,17 @@ Options listed below were added and will be removed in the 1.11.0 version of the that large integers and other exact JSON values do not silently lose precision. +- `nosessionreinit` added. If set to `1`, the streamable HTTP client treats a + `404 Not Found` response to a request carrying an `Mcp-Session-Id` as + terminal, failing the connection with an error wrapping `ErrSessionMissing`, + restoring the previous behavior. The default behavior was changed to follow + the 2025-11-25 specification, which requires the client to start a new + session: the client re-sends its `initialize` request without a session ID, + adopts the new session ID and sends the failed request again. The 404 stays + terminal when the session holds server-side state that a new session would + lose (a `resources/subscribe` subscription or a `logging/setLevel` level) or + when the server negotiates a different protocol version. See issue #1299. + ### 1.8.0 Options listed below were added and will be removed in the 1.9.0 version of the SDK. diff --git a/mcp/streamable.go b/mcp/streamable.go index 9f8f2234b..1224725b3 100644 --- a/mcp/streamable.go +++ b/mcp/streamable.go @@ -347,6 +347,16 @@ var allowsessionsinstateless = mcpgodebug.Value("allowsessionsinstateless") // permanently fails the connection. var noprotocolerrorbody = mcpgodebug.Value("noprotocolerrorbody") +// nosessionreinit is a compatibility parameter that restores the previous +// behavior of the streamable client when the server answers a request for a +// live session with 404 Not Found. When unset (the default), the client starts +// a new session as the 2025-11-25 specification requires and resends the +// request; see [streamableClientConn.reinitialize]. When set to "1", the 404 +// permanently fails the connection with an error wrapping [ErrSessionMissing]. +// See the documentation for the mcpgodebug package for instructions how to +// enable it. +var nosessionreinit = mcpgodebug.Value("nosessionreinit") + // plaintextstatefulrejection is a compatibility parameter that restores the // previous behavior of a stateful [StreamableHTTPHandler] when it receives a // request carrying SEP-2575 per-request metadata (i.e. an @@ -2328,6 +2338,18 @@ type streamableClientConn struct { mu sync.Mutex initializedResult *InitializeResult sessionID string + // initRequest is the initialize request that started the session, kept so + // that [streamableClientConn.reinitialize] can start a new one. + initRequest *jsonrpc.Request + // holdsServerState reports whether the session carries state on the + // server that a new session would silently drop. + holdsServerState bool + // cancelStandalone stops the current standalone SSE stream. + cancelStandalone context.CancelFunc + + // reinitMu serializes calls to reinitialize; reinits counts them. + reinitMu sync.Mutex + reinits int } var _ clientConnection = (*streamableClientConn)(nil) @@ -2363,11 +2385,21 @@ func (c *streamableClientConn) sessionUpdated(state clientSessionState) { } func (c *streamableClientConn) connectStandaloneSSE() { - resp, err := c.connectSSE(c.ctx, "", 0, true) + // Each session gets its own stream: starting a stream stops the one that + // belonged to the previous session, if any. + ctx, cancel := context.WithCancel(c.ctx) + c.mu.Lock() + if c.cancelStandalone != nil { + c.cancelStandalone() + } + c.cancelStandalone = cancel + c.mu.Unlock() + + resp, err := c.connectSSE(ctx, "", "", 0, true) if err != nil { // If the client didn't cancel the request, and failure breaks the logical // session. - if c.ctx.Err() == nil { + if ctx.Err() == nil { c.fail(fmt.Errorf("standalone SSE request failed (session ID: %v): %v", c.sessionID, err)) } return @@ -2403,11 +2435,11 @@ func (c *streamableClientConn) connectStandaloneSSE() { return } summary := "standalone SSE stream" - if err := c.checkResponse(c.ctx, summary, resp); err != nil { + if err := c.checkResponse(ctx, summary, resp); err != nil { c.fail(err) return } - go c.handleSSE(c.ctx, summary, resp, nil) + go c.handleSSE(ctx, summary, resp, nil) } // fail handles an asynchronous error while reading. @@ -2486,23 +2518,27 @@ func (c *streamableClientConn) Write(ctx context.Context, msg jsonrpc.Message) e return fmt.Errorf("%s: %v", requestSummary, err) } - doRequest := func() (*http.Request, *http.Response, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(data)) - if err != nil { - return nil, nil, err + if req, ok := msg.(*jsonrpc.Request); ok { + switch req.Method { + case methodInitialize: + c.mu.Lock() + c.initRequest = req + c.mu.Unlock() + case methodSubscribe, methodSetLevel: + c.mu.Lock() + c.holdsServerState = true + c.mu.Unlock() } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json, text/event-stream") + } - if err := c.setMCPHeaders(req, msg); err != nil { + doRequest := func() (*http.Request, *http.Response, error) { + req, err := c.newPostRequest(ctx, msg, data) + if err != nil { // Failure to set headers means that the request was not sent. // Wrap with ErrRejected so the jsonrpc2 connection doesn't set writeErr // and permanently break the connection. return nil, nil, fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err) } - // Keep this after the setMCPHeaders call to ensure that the - // protocol version header is set. - setStandardHeaders(ctx, req.Header, msg) resp, err := c.client.Do(req) if err != nil { // Any error from client.Do means the request didn't reach the server. @@ -2548,7 +2584,26 @@ func (c *streamableClientConn) Write(ctx context.Context, msg jsonrpc.Message) e } } - if err := c.checkResponse(ctx, requestSummary, resp); err != nil { + err = c.checkResponse(ctx, requestSummary, resp) + if errors.Is(err, ErrSessionMissing) { + if rerr := c.reinitialize(ctx, req.Header.Get(sessionIDHeader)); rerr == nil { + if _, ok := msg.(*jsonrpc.Response); ok { + // The server request this answers belonged to the old session. + return fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err) + } + // §2.5.3: the server answers 404 without processing the request, so + // it is safe to send it again on the new session. + if _, resp, err = doRequest(); err != nil { + return err + } + err = c.checkResponse(ctx, requestSummary, resp) + } else if ctx.Err() != nil { + // The caller gave up while the session was being re-established. + // Leave the connection intact so that a later call can retry. + return fmt.Errorf("%w: %w", err, jsonrpc2.ErrRejected) + } + } + if err != nil { if (requestMethod == methodDiscover || requestMethod == methodSubscriptionsListen) && !errors.Is(err, jsonrpc2.ErrRejected) { // Wrap the discover or subscriptions/listen failure with ErrRejected so // the jsonrpc2 layer doesn't set writeErr, which would break the connection @@ -2715,6 +2770,8 @@ func (c *streamableClientConn) handleSSE(ctx context.Context, requestSummary str // connections without making progress (#679). var prevLastEventID string retriesWithoutProgress := 0 + // The session this stream belongs to. See [streamableClientConn.reinitialize]. + sessionID := resp.Request.Header.Get(sessionIDHeader) for { lastEventID, reconnectDelay, clientClosed := c.processStream(ctx, requestSummary, resp, forCall) @@ -2747,8 +2804,14 @@ func (c *streamableClientConn) handleSSE(ctx context.Context, requestSummary str } } + if sessionID != "" && c.SessionID() != sessionID { + // The session was replaced, so the stream cannot be resumed. + c.abandonCall(forCall, fmt.Errorf("%s: session %v was terminated: %w", requestSummary, sessionID, ErrSessionMissing)) + return + } + // The stream was interrupted or ended by the server. Attempt to reconnect. - newResp, err := c.connectSSE(ctx, lastEventID, reconnectDelay, false) + newResp, err := c.connectSSE(ctx, sessionID, lastEventID, reconnectDelay, false) if err != nil { // If the client didn't cancel this request, any failure to execute it // breaks the logical MCP session. @@ -2761,12 +2824,207 @@ func (c *streamableClientConn) handleSSE(ctx context.Context, requestSummary str resp = newResp if err := c.checkResponse(ctx, requestSummary, resp); err != nil { + if errors.Is(err, ErrSessionMissing) && c.reinitialize(c.ctx, sessionID) == nil { + // The new session has its own standalone stream. A call whose + // stream was lost with the old session cannot be resumed, and + // resending it could repeat its effects, so report the loss. + c.abandonCall(forCall, err) + return + } c.fail(err) return } } } +// abandonCall reports err as the result of forCall, if it is non-nil, when +// its response can no longer arrive. +func (c *streamableClientConn) abandonCall(forCall *jsonrpc.Request, err error) { + if forCall == nil { + return + } + select { + case c.incoming <- &jsonrpc.Response{ID: forCall.ID, Error: err}: + case <-c.done: + } +} + +// newPostRequest returns a POST request carrying data, the encoding of msg. +func (c *streamableClientConn) newPostRequest(ctx context.Context, msg jsonrpc.Message, data []byte) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(data)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + if err := c.setMCPHeaders(req, msg); err != nil { + return nil, err + } + // Keep this after the setMCPHeaders call to ensure that the + // protocol version header is set. + setStandardHeaders(ctx, req.Header, msg) + return req, nil +} + +// reinitialize replaces a session that the server no longer knows, after a +// request carrying staleID got 404 Not Found. +// +// [§2.5.3] of the 2025-11-25 transport: "When a client receives HTTP 404 in +// response to a request containing an MCP-Session-Id, it MUST start a new +// session by sending a new InitializeRequest without a session ID attached." +// +// The new session is started with the same InitializeRequest as the old one, +// and replaces it only if the server negotiates the same protocol version, so +// that the [ClientSession] above this connection stays valid. A nil result +// means that the connection has a live session and the failed request can be +// sent again, either because this call started one or because a concurrent +// call already had. +// +// A session that carries state on the server (resource subscriptions or a +// logging level) is not replaced, since the new session would silently lose +// it; in that case, as in the case of any failure, the caller should treat the +// 404 as terminal. +// +// [§2.5.3]: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management +func (c *streamableClientConn) reinitialize(ctx context.Context, staleID string) error { + if nosessionreinit == "1" { + return errors.New("session re-initialization is disabled") + } + c.reinitMu.Lock() + defer c.reinitMu.Unlock() + + c.mu.Lock() + sessionID, initReq, initRes, holdsState := c.sessionID, c.initRequest, c.initializedResult, c.holdsServerState + c.mu.Unlock() + switch { + case sessionID != staleID: + return nil // a concurrent call has already replaced the session + case initReq == nil || initRes == nil || initRes.ProtocolVersion >= protocolVersion20260728: + return errors.New("no initialized session to replace") + case holdsState: + return errors.New("the session holds server state that a new session would lose") + } + + // Use an ID that cannot collide with the IDs of the jsonrpc2 connection, + // which only sends integer IDs. + c.reinits++ + id := jsonrpc2.StringID(fmt.Sprintf("reinitialize-%d", c.reinits)) + res, newID, err := c.sendInitialize(ctx, &jsonrpc.Request{ID: id, Method: methodInitialize, Params: initReq.Params}) + if err != nil { + return fmt.Errorf("starting a new session: %w", err) + } + if res.ProtocolVersion != initRes.ProtocolVersion { + return fmt.Errorf("new session uses protocol version %q, not %q", res.ProtocolVersion, initRes.ProtocolVersion) + } + c.mu.Lock() + c.sessionID = newID + c.mu.Unlock() + + initialized, err := jsonrpc2.NewNotification(notificationInitialized, &InitializedParams{}) + if err != nil { + return err + } + data, err := jsonrpc.EncodeMessage(initialized) + if err != nil { + return err + } + req, err := c.newPostRequest(ctx, initialized, data) + if err != nil { + return err + } + resp, err := c.client.Do(req) + if err != nil { + return err + } + if err := c.checkResponse(ctx, "sending \"notifications/initialized\"", resp); err != nil { + return err + } + resp.Body.Close() + + if !c.disableStandaloneSSE { + go c.connectStandaloneSSE() + } + return nil +} + +// sendInitialize sends req, an initialize request, with no session ID, and +// returns the result and the session ID that the server assigned. +func (c *streamableClientConn) sendInitialize(ctx context.Context, req *jsonrpc.Request) (*InitializeResult, string, error) { + data, err := jsonrpc.EncodeMessage(req) + if err != nil { + return nil, "", err + } + httpReq, err := c.newPostRequest(ctx, req, data) + if err != nil { + return nil, "", err + } + // Match the first initialize request, which was sent before the session + // and its protocol version existed. + httpReq.Header.Del(sessionIDHeader) + httpReq.Header.Del(protocolVersionHeader) + resp, err := c.client.Do(httpReq) + if err != nil { + return nil, "", err + } + if err := c.checkResponse(ctx, `sending "initialize"`, resp); err != nil { + return nil, "", err + } + defer resp.Body.Close() + + var response *jsonrpc.Response + switch contentType := baseMediaType(resp.Header.Get("Content-Type")); contentType { + case "application/json": + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, "", err + } + msg, err := jsonrpc.DecodeMessage(body) + if err != nil { + return nil, "", err + } + response, _ = msg.(*jsonrpc.Response) + case "text/event-stream": + for evt, err := range scanEventsLimited(resp.Body, c.maxEventSize) { + if err != nil { + return nil, "", err + } + if len(evt.Data) == 0 || (evt.Name != "" && evt.Name != "message") { + continue + } + msg, err := jsonrpc.DecodeMessage(evt.Data) + if err != nil { + return nil, "", err + } + if r, ok := msg.(*jsonrpc.Response); ok && r.ID == req.ID { + response = r + break + } + // Deliver anything else the server sends first, such as a log + // message. + select { + case c.incoming <- msg: + case <-c.done: + return nil, "", ErrConnectionClosed + case <-ctx.Done(): + return nil, "", ctx.Err() + } + } + default: + return nil, "", fmt.Errorf("unsupported content type %q", contentType) + } + if response == nil || response.ID != req.ID { + return nil, "", errors.New("no response to initialize") + } + if response.Error != nil { + return nil, "", response.Error + } + var res InitializeResult + if err := json.Unmarshal(response.Result, &res); err != nil { + return nil, "", err + } + return &res, resp.Header.Get(sessionIDHeader), nil +} + // checkResponse checks the status code of the provided response, and // translates it into an error if the request was unsuccessful. // @@ -2901,6 +3159,9 @@ func (c *streamableClientConn) processStream(ctx context.Context, requestSummary // connectSSE handles the logic of connecting a text/event-stream connection. // +// If sessionID is set, it is the session of the stream being resumed, which +// may differ from the current session. See [streamableClientConn.reinitialize]. +// // If lastEventID is set, it is the last-event ID of a stream being resumed. // // If connection fails, connectSSE retries with an exponential backoff @@ -2913,7 +3174,7 @@ func (c *streamableClientConn) processStream(ctx context.Context, requestSummary // If initial is set, this is the initial attempt. // // If connectSSE exits due to context cancellation, the result is (nil, ctx.Err()). -func (c *streamableClientConn) connectSSE(ctx context.Context, lastEventID string, reconnectDelay time.Duration, initial bool) (*http.Response, error) { +func (c *streamableClientConn) connectSSE(ctx context.Context, sessionID, lastEventID string, reconnectDelay time.Duration, initial bool) (*http.Response, error) { var finalErr error attempt := 0 if !initial { @@ -2947,6 +3208,9 @@ func (c *streamableClientConn) connectSSE(ctx context.Context, lastEventID strin if err := c.setMCPHeaders(req, nil); err != nil { return nil, err } + if sessionID != "" { + req.Header.Set(sessionIDHeader, sessionID) + } if lastEventID != "" { req.Header.Set(lastEventIDHeader, lastEventID) } diff --git a/mcp/streamable_client.go b/mcp/streamable_client.go index 74940b3ad..3ee88c5fd 100644 --- a/mcp/streamable_client.go +++ b/mcp/streamable_client.go @@ -51,6 +51,17 @@ When a session is present: - Client includes the session ID in all subsequent requests - Session ends when the client calls Close() (sends DELETE) or server returns 404 +When the server answers 404 Not Found to a request carrying the session ID, the +2025-11-25 spec requires the client to start a new session. +[streamableClientConn.reinitialize] re-sends the original initialize request +without a session ID, adopts the new session ID, sends notifications/initialized, +and restarts the standalone SSE stream. The failed POST is then sent again (the +server did not process it); a call whose response stream was lost with the old +session fails with [ErrSessionMissing] instead, as resending it could repeat its +effects. The 404 stays terminal if the session holds server state that a new +session would lose (resources/subscribe, logging/setLevel), if the server +negotiates a different protocol version, or if MCPGODEBUG=nosessionreinit=1. + [streamableClientConn] stores the session state: - [streamableClientConn.sessionID]: Server-assigned session identifier - [streamableClientConn.initializedResult]: Protocol version and server capabilities @@ -178,7 +189,8 @@ Errors are categorized and handled differently: - Triggers reconnection in [streamableClientConn.handleSSE] 2. Terminal (breaks the connection): - - 404 Not Found: Session terminated by server ([ErrSessionMissing]) + - 404 Not Found: Session terminated by server ([ErrSessionMissing]), when + the session cannot be replaced (see Sessions) - Message decode errors: Protocol violation - Context cancellation: Client closed connection - Mismatched session IDs: Protocol error (only relevant for servers that use sessions) diff --git a/mcp/streamable_client_test.go b/mcp/streamable_client_test.go index 77ff81a20..104ae2690 100644 --- a/mcp/streamable_client_test.go +++ b/mcp/streamable_client_test.go @@ -5,6 +5,7 @@ package mcp import ( + "bytes" "context" "encoding/json" "errors" @@ -2029,3 +2030,325 @@ func TestStreamableClient_StatelessSubscriptionsListen404(t *testing.T) { t.Fatal("subscriptions/listen was not called") } } + +// dropServerSessions forgets every session the handler knows about, as a +// server does when it terminates a session. Later requests carrying one of +// the dropped session IDs get 404 Not Found. +func dropServerSessions(t *testing.T, handler *StreamableHTTPHandler) { + t.Helper() + handler.mu.Lock() + defer handler.mu.Unlock() + if len(handler.sessions) != 1 { + t.Fatalf("server has %d sessions, want 1", len(handler.sessions)) + } + clear(handler.sessions) +} + +// TestStreamableClientReinitializesAfterNotFound checks the 2025-11-25 +// transport's session management rule: "When a client receives HTTP 404 in +// response to a request containing an MCP-Session-Id, it MUST start a new +// session by sending a new InitializeRequest without a session ID attached." +// See issue #1299. +func TestStreamableClientReinitializesAfterNotFound(t *testing.T) { + ctx := context.Background() + tests := []struct { + name string + before func(*ClientSession) error // runs before the server drops the session + noReinit bool // sets MCPGODEBUG=nosessionreinit=1 + wantNewSession bool + }{ + { + name: "new session", + wantNewSession: true, + }, + { + // A new session would silently drop the logging level the old one + // carried, so the 404 stays terminal. + name: "session holds a logging level", + before: func(cs *ClientSession) error { + return cs.SetLoggingLevel(ctx, &SetLoggingLevelParams{Level: "debug"}) + }, + }, + { + name: "nosessionreinit=1", + noReinit: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if test.noReinit { + prev := nosessionreinit + nosessionreinit = "1" + t.Cleanup(func() { nosessionreinit = prev }) + } + var initializes atomic.Int32 + server := NewServer(testImpl, nil) + AddTool(server, greetTool(), sayHi) + handler := NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, nil) + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + if msg, err := jsonrpc.DecodeMessage(body); err == nil { + if req, ok := msg.(*jsonrpc.Request); ok && req.Method == methodInitialize { + if got := r.Header.Get(sessionIDHeader); got != "" { + t.Errorf("initialize sent with %s %q, want none", sessionIDHeader, got) + } + initializes.Add(1) + } + } + } + handler.ServeHTTP(w, r) + })) + defer httpServer.Close() + + client := NewClient(testImpl, nil) + session, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, &ClientSessionOptions{ProtocolVersion: protocolVersion20251125}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + if test.before != nil { + if err := test.before(session); err != nil { + t.Fatal(err) + } + } + oldID := session.ID() + dropServerSessions(t, handler) + + _, err = session.CallTool(ctx, &CallToolParams{Name: "greet", Arguments: map[string]any{"Name": "user"}}) + if !test.wantNewSession { + if !errors.Is(err, ErrSessionMissing) { + t.Fatalf("CallTool after the server dropped the session: got %v, want ErrSessionMissing", err) + } + if got := initializes.Load(); got != 1 { + t.Errorf("server saw %d initialize requests, want 1", got) + } + return + } + if err != nil { + t.Fatalf("CallTool after the server dropped the session: %v", err) + } + if got := initializes.Load(); got != 2 { + t.Errorf("server saw %d initialize requests, want 2", got) + } + newID := session.ID() + if newID == "" || newID == oldID { + t.Errorf("session ID after re-initialization = %q, want a new ID (old %q)", newID, oldID) + } + // The new session keeps working. + if _, err := session.ListTools(ctx, nil); err != nil { + t.Errorf("ListTools on the new session: %v", err) + } + }) + } +} + +// TestStreamableClientReinitializesAfterServerRestart checks that the client +// recovers when the standalone SSE stream is the first request to see the +// 404, as happens when a stateful server restarts and forgets its sessions. +func TestStreamableClientReinitializesAfterServerRestart(t *testing.T) { + ctx := context.Background() + const tick = 10 * time.Millisecond + defer func(delay int64) { + reconnectInitialDelay.Store(delay) + }(reconnectInitialDelay.Load()) + reconnectInitialDelay.Store(int64(tick)) + + newHandler := func() (*Server, *StreamableHTTPHandler) { + server := NewServer(testImpl, nil) + return server, NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, nil) + } + _, handler1 := newHandler() + var current atomic.Pointer[StreamableHTTPHandler] + current.Store(handler1) + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + current.Load().ServeHTTP(w, r) + })) + defer httpServer.Close() + + toolsChanged := make(chan struct{}, 1) + client := NewClient(testImpl, &ClientOptions{ + ToolListChangedHandler: func(context.Context, *ToolListChangedRequest) { + select { + case toolsChanged <- struct{}{}: + default: + } + }, + }) + session, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, &ClientSessionOptions{ProtocolVersion: protocolVersion20251125}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + oldID := session.ID() + + // Restart: a new handler with no sessions takes over, and every open + // connection, including the standalone SSE stream, is dropped. + server2, handler2 := newHandler() + current.Store(handler2) + httpServer.CloseClientConnections() + + // Without any call from the application, the standalone stream's + // reconnect sees the 404 and starts a new session. + deadline := time.Now().Add(5 * time.Second) + for session.ID() == oldID { + if time.Now().After(deadline) { + t.Fatalf("client did not start a new session after the restart") + } + time.Sleep(tick) + } + handler2.mu.Lock() + _, ok := handler2.sessions[session.ID()] + handler2.mu.Unlock() + if !ok { + t.Fatalf("client session ID %q is unknown to the restarted server", session.ID()) + } + + // Server-initiated messages reach the client on the new session's + // standalone stream. The stream may not be registered yet, so keep + // changing the tool list until a notification arrives. + for i := 0; ; i++ { + AddTool(server2, &Tool{Name: fmt.Sprintf("tool%d", i)}, sayHi) + select { + case <-toolsChanged: + case <-time.After(10 * tick): + if time.Now().After(deadline) { + t.Fatal("no tools/list_changed notification on the new session") + } + continue + } + break + } + if _, err := session.ListTools(ctx, nil); err != nil { + t.Errorf("ListTools after the restart: %v", err) + } +} + +// TestStreamableClientReinitializeVersionMismatch checks that the client +// keeps the 404 terminal when the new session would use a different protocol +// version than the one the ClientSession negotiated. +func TestStreamableClientReinitializeVersionMismatch(t *testing.T) { + ctx := context.Background() + var initializes atomic.Int32 + var sawNewSession atomic.Bool + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + body, _ := io.ReadAll(r.Body) + msg, err := jsonrpc.DecodeMessage(body) + if err != nil { + t.Errorf("decoding request: %v", err) + return + } + req, _ := msg.(*jsonrpc.Request) + switch sid := r.Header.Get(sessionIDHeader); { + case req != nil && req.Method == methodInitialize: + res := *initResult + sid := "old" + if initializes.Add(1) > 1 { + res.ProtocolVersion = protocolVersion20250618 + sid = "new" + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set(sessionIDHeader, sid) + data, _ := jsonrpc2.EncodeMessage(&jsonrpc.Response{ID: req.ID, Result: mustMarshal(&res)}) + w.Write(data) + case sid == "old" && req != nil && req.Method == notificationInitialized: + w.WriteHeader(http.StatusAccepted) + case sid == "old": + w.WriteHeader(http.StatusNotFound) + default: + sawNewSession.Store(true) + w.WriteHeader(http.StatusAccepted) + } + })) + defer httpServer.Close() + + client := NewClient(testImpl, nil) + session, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, &ClientSessionOptions{ProtocolVersion: protocolVersion20251125}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + if _, err := session.ListTools(ctx, nil); !errors.Is(err, ErrSessionMissing) { + t.Fatalf("ListTools: got %v, want ErrSessionMissing", err) + } + if got := initializes.Load(); got != 2 { + t.Errorf("server saw %d initialize requests, want 2", got) + } + if sawNewSession.Load() { + t.Error("client used a session whose protocol version differs from the negotiated one") + } +} + +// TestStreamableClientReinitializeDuringCall checks that a call whose response +// stream is lost with its session fails with ErrSessionMissing instead of +// being resumed or resent, and that the client still starts a new session. +func TestStreamableClientReinitializeDuringCall(t *testing.T) { + ctx := context.Background() + const tick = 10 * time.Millisecond + defer func(delay int64) { + reconnectInitialDelay.Store(delay) + }(reconnectInitialDelay.Load()) + reconnectInitialDelay.Store(int64(tick)) + + started := make(chan struct{}) + release := make(chan struct{}) + defer close(release) + var calls atomic.Int32 + newHandler := func() *StreamableHTTPHandler { + server := NewServer(testImpl, nil) + AddTool(server, &Tool{Name: "block"}, func(ctx context.Context, req *CallToolRequest, _ any) (*CallToolResult, any, error) { + if calls.Add(1) == 1 { + close(started) + } + select { + case <-release: + case <-ctx.Done(): + } + return &CallToolResult{}, nil, nil + }) + // An event store makes the call's response stream resumable. + return NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, &StreamableHTTPOptions{EventStore: NewMemoryEventStore(nil)}) + } + var current atomic.Pointer[StreamableHTTPHandler] + current.Store(newHandler()) + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + current.Load().ServeHTTP(w, r) + })) + defer httpServer.Close() + + client := NewClient(testImpl, nil) + session, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL}, &ClientSessionOptions{ProtocolVersion: protocolVersion20251125}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + + errc := make(chan error, 1) + go func() { + _, err := session.CallTool(ctx, &CallToolParams{Name: "block"}) + errc <- err + }() + <-started + current.Store(newHandler()) + httpServer.CloseClientConnections() + + select { + case err := <-errc: + if !errors.Is(err, ErrSessionMissing) { + t.Errorf("CallTool across a restart: got %v, want ErrSessionMissing", err) + } + case <-time.After(5 * time.Second): + t.Fatal("CallTool did not return after the server restarted") + } + if _, err := session.ListTools(ctx, nil); err != nil { + t.Errorf("ListTools after the restart: %v", err) + } + if got := calls.Load(); got != 1 { + t.Errorf("tool ran %d times, want 1", got) + } +} diff --git a/mcp/streamable_test.go b/mcp/streamable_test.go index 7d4782bf9..803815153 100644 --- a/mcp/streamable_test.go +++ b/mcp/streamable_test.go @@ -2991,6 +2991,12 @@ data: {"jsonrpc":"2.0","method":"test2","params":{}} func Test_ExportErrSessionMissing(t *testing.T) { ctx := context.Background() + // By default the client replaces the missing session (see + // TestStreamableClientReinitializesAfterNotFound), so opt out to observe + // the error. + prev := nosessionreinit + nosessionreinit = "1" + t.Cleanup(func() { nosessionreinit = prev }) // 1. Setup server impl := &Implementation{Name: "test", Version: "1.0.0"} From 3e21beb4f6a2cd9cfd0953640ae974d7a552a2dd Mon Sep 17 00:00:00 2001 From: Abdullah Al Mahmud Date: Mon, 28 Sep 2026 06:46:34 -0500 Subject: [PATCH 2/2] mcp: treat a 404 with a JSON-RPC error body as a missing session A server that answers a dropped session's call with a 404 and a JSON-RPC error naming the call's ID was surfaced as a per-call rejection, so the client kept the dead session. A 404 on a request carrying the session ID now wraps ErrSessionMissing whatever the body says, and the client starts a new session. Fix and test from jmrplens's review. Co-Authored-By: jmrplens Co-Authored-By: Claude Opus 5.5 --- mcp/streamable.go | 5 +++ mcp/streamable_client_test.go | 74 +++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/mcp/streamable.go b/mcp/streamable.go index 1224725b3..c78502ff5 100644 --- a/mcp/streamable.go +++ b/mcp/streamable.go @@ -3047,6 +3047,11 @@ func (c *streamableClientConn) checkResponse(ctx context.Context, requestSummary body, _ := io.ReadAll(resp.Body) msg, _ := jsonrpc.DecodeMessage(body) if response, ok := msg.(*jsonrpc.Response); ok && response.Error != nil { + // A 404 on a request carrying the session ID means the session is + // gone, whatever JSON-RPC error the body carries (§2.5.3). + if sessionID := c.SessionID(); resp.StatusCode == http.StatusNotFound && sessionID != "" { + return fmt.Errorf("%s: %w: %w", requestSummary, response.Error, ErrSessionMissing) + } return fmt.Errorf("%s: %w: %w: %v", requestSummary, response.Error, jsonrpc2.ErrRejected, http.StatusText(resp.StatusCode)) } } diff --git a/mcp/streamable_client_test.go b/mcp/streamable_client_test.go index 104ae2690..bf21f5143 100644 --- a/mcp/streamable_client_test.go +++ b/mcp/streamable_client_test.go @@ -2352,3 +2352,77 @@ func TestStreamableClientReinitializeDuringCall(t *testing.T) { t.Errorf("tool ran %d times, want 1", got) } } + +// TestStreamableClientReinitializesAfterNotFoundWithErrorBody checks that a +// 404 on a request carrying the session ID starts a new session whatever +// JSON-RPC error the body carries, including one naming the request's ID. +func TestStreamableClientReinitializesAfterNotFoundWithErrorBody(t *testing.T) { + ctx := context.Background() + tests := []struct { + name string + body func(id jsonrpc.ID) string + }{ + { + name: "id null", + body: func(jsonrpc.ID) string { + return `{"jsonrpc":"2.0","error":{"code":-32001,"message":"Session not found"},"id":null}` + }, + }, + { + name: "id of the request", + body: func(id jsonrpc.ID) string { + data, err := jsonrpc.EncodeMessage(&jsonrpc.Response{ID: id, Error: &jsonrpc.Error{Code: -32001, Message: "Session not found"}}) + if err != nil { + t.Errorf("encoding the error body: %v", err) + } + return string(data) + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var ( + initializes atomic.Int32 + dropped atomic.Value // the session ID the server no longer knows + ) + server := NewServer(testImpl, nil) + AddTool(server, greetTool(), sayHi) + handler := NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, nil) + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + msg, _ := jsonrpc.DecodeMessage(body) + if req, ok := msg.(*jsonrpc.Request); ok && req.Method == methodInitialize { + initializes.Add(1) + } + if id, _ := dropped.Load().(string); id != "" && r.Header.Get(sessionIDHeader) == id { + var reqID jsonrpc.ID + if req, ok := msg.(*jsonrpc.Request); ok { + reqID = req.ID + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + io.WriteString(w, test.body(reqID)) + return + } + handler.ServeHTTP(w, r) + })) + defer httpServer.Close() + + client := NewClient(testImpl, nil) + session, err := client.Connect(ctx, &StreamableClientTransport{Endpoint: httpServer.URL, DisableStandaloneSSE: true}, &ClientSessionOptions{ProtocolVersion: protocolVersion20251125}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + dropped.Store(session.ID()) + + if _, err := session.CallTool(ctx, &CallToolParams{Name: "greet", Arguments: map[string]any{"Name": "user"}}); err != nil { + t.Fatalf("CallTool after the server dropped the session: %v", err) + } + if got := initializes.Load(); got != 2 { + t.Errorf("server saw %d initialize requests, want 2", got) + } + }) + } +}