From 8e96e0242a5bcd6766b1005fcc49514ead4253ee Mon Sep 17 00:00:00 2001 From: guglielmoc Date: Tue, 17 Nov 2026 08:20:09 +0000 Subject: [PATCH 1/2] remove deprecated mcpgodebug variables --- docs/mcpgodebug.md | 30 ++++++++++++ internal/docs/mcpgodebug.src.md | 30 ++++++++++++ internal/jsonrpc2/conn.go | 19 +------- mcp/protocol.go | 20 -------- mcp/resource.go | 19 +------- mcp/server.go | 20 ++------ mcp/shared.go | 21 +------- mcp/streamable.go | 86 +++------------------------------ mcp/streamable_client_test.go | 47 +++--------------- mcp/streamable_test.go | 64 ------------------------ mcp/transport.go | 51 +++---------------- 11 files changed, 91 insertions(+), 316 deletions(-) diff --git a/docs/mcpgodebug.md b/docs/mcpgodebug.md index 47563523..dd66b45b 100644 --- a/docs/mcpgodebug.md +++ b/docs/mcpgodebug.md @@ -79,6 +79,36 @@ Options listed below were added and will be removed in the 1.11.0 version of the upgrade from `http` to `https` on the same host with default ports is allowed) and keeps the method. +Options below were removed, according to plan: + +- `customresnotfounderrcode`. `ResourceNotFoundError` now always uses + `-32602` (Invalid Params). + +- `hintomitempty`. `ToolAnnotations` now always serializes `ReadOnlyHint` and + `IdempotentHint`. + +- `allowsessionsinstateless`. Stateless streamable HTTP servers now always + ignore session IDs and reject `DELETE` with 405. + +- `nomethodnotfoundcodeinerror`. A "method not found" error response now + always carries code `-32601`. + +- `noprotocolerrorbody`. The streamable HTTP client now always attempts to + decode the JSON-RPC error body of a non-2xx response. + +- `nowrapinvalidparams`. Params-decoding failures are now always reported with + code `-32602`. + +- `disablecompleteparamsvalidation`. `Server.complete` now always validates + the required `ref` and `argument.name` fields. + +- `plaintextstatefulrejection`. A stateful `StreamableHTTPHandler` now always + rejects per-request metadata with a JSON-RPC + `CodeUnsupportedProtocolVersion` error. + +- `blockingcancelnotify`. A cancelled call now always returns immediately and + sends `notifications/cancelled` asynchronously. + ### 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 66f36ff2..fd55e154 100644 --- a/internal/docs/mcpgodebug.src.md +++ b/internal/docs/mcpgodebug.src.md @@ -78,6 +78,36 @@ Options listed below were added and will be removed in the 1.11.0 version of the upgrade from `http` to `https` on the same host with default ports is allowed) and keeps the method. +Options below were removed, according to plan: + +- `customresnotfounderrcode`. `ResourceNotFoundError` now always uses + `-32602` (Invalid Params). + +- `hintomitempty`. `ToolAnnotations` now always serializes `ReadOnlyHint` and + `IdempotentHint`. + +- `allowsessionsinstateless`. Stateless streamable HTTP servers now always + ignore session IDs and reject `DELETE` with 405. + +- `nomethodnotfoundcodeinerror`. A "method not found" error response now + always carries code `-32601`. + +- `noprotocolerrorbody`. The streamable HTTP client now always attempts to + decode the JSON-RPC error body of a non-2xx response. + +- `nowrapinvalidparams`. Params-decoding failures are now always reported with + code `-32602`. + +- `disablecompleteparamsvalidation`. `Server.complete` now always validates + the required `ref` and `argument.name` fields. + +- `plaintextstatefulrejection`. A stateful `StreamableHTTPHandler` now always + rejects per-request metadata with a JSON-RPC + `CodeUnsupportedProtocolVersion` error. + +- `blockingcancelnotify`. A cancelled call now always returns immediately and + sends `notifications/cancelled` asynchronously. + ### 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/jsonrpc2/conn.go b/internal/jsonrpc2/conn.go index 22e6faee..34a502c9 100644 --- a/internal/jsonrpc2/conn.go +++ b/internal/jsonrpc2/conn.go @@ -14,25 +14,8 @@ import ( "time" "github.com/modelcontextprotocol/go-sdk/internal/json" - "github.com/modelcontextprotocol/go-sdk/internal/mcpgodebug" ) -// nomethodnotfoundcodeinerror is a compatibility parameter that restores the -// pre-fix behavior of [processResult], where wrapped [ErrNotHandled] or -// [ErrMethodNotFound] errors returned by request handlers were not -// recognized as "method not found" signals. The original switch statement -// compared sentinel errors with ==, which never matched errors returned via -// fmt.Errorf("%w: ...", ErrNotHandled, ...) — including the ones produced -// by checkRequest. As a result the wire error response carried code 0 -// instead of code -32601. The fix uses errors.Is to recognize wrapped -// sentinels and append the method name to the message. -// -// To restore the previous behavior, set MCPGODEBUG=nomethodnotfoundcodeinerror=1. -// This option will be removed in a future SDK version. -// See the documentation for the mcpgodebug package for instructions on how -// to use it. -var nomethodnotfoundcodeinerror = mcpgodebug.Value("nomethodnotfoundcodeinerror") - // Connection manages the jsonrpc2 protocol, connecting responses back to their // calls. Connection is bidirectional; it does not have a designated server or // client end. @@ -738,7 +721,7 @@ func (c *Connection) handleAsync() { // processResult processes the result of a request and, if appropriate, sends a response. func (c *Connection) processResult(from any, req *incomingRequest, result any, err error) error { - if nomethodnotfoundcodeinerror != "1" && (errors.Is(err, ErrNotHandled) || errors.Is(err, ErrMethodNotFound)) { + if errors.Is(err, ErrNotHandled) || errors.Is(err, ErrMethodNotFound) { err = fmt.Errorf("%w: %q", ErrMethodNotFound, req.Method) } diff --git a/mcp/protocol.go b/mcp/protocol.go index d78d2506..5aa64abf 100644 --- a/mcp/protocol.go +++ b/mcp/protocol.go @@ -2054,13 +2054,6 @@ type Tool struct { Icons []Icon `json:"icons,omitempty"` } -// hintomitempty is a compatibility parameter that restores the pre-1.7.0 -// behavior of [ToolAnnotations] JSON marshaling, where false-valued bare bool -// fields (ReadOnlyHint, IdempotentHint) were omitted from the output. -// See the documentation for the mcpgodebug package for instructions on how to -// enable it. -var hintomitempty = mcpgodebug.Value("hintomitempty") - // Additional properties describing a Tool to clients. // // NOTE: all properties in ToolAnnotations are hints. They are not @@ -2099,20 +2092,7 @@ type ToolAnnotations struct { } // MarshalJSON implements [json.Marshaler] for ToolAnnotations. -// -// To restore the previous behavior where false-valued ReadOnlyHint and -// IdempotentHint were omitted, set MCPGODEBUG=hintomitempty=1. func (t ToolAnnotations) MarshalJSON() ([]byte, error) { - if hintomitempty == "1" { - type compat struct { - DestructiveHint *bool `json:"destructiveHint,omitempty"` - IdempotentHint bool `json:"idempotentHint,omitempty"` - OpenWorldHint *bool `json:"openWorldHint,omitempty"` - ReadOnlyHint bool `json:"readOnlyHint,omitempty"` - Title string `json:"title,omitempty"` - } - return json.Marshal(compat(t)) - } type nomethod ToolAnnotations return json.Marshal(nomethod(t)) } diff --git a/mcp/resource.go b/mcp/resource.go index 66c47f9c..1474b765 100644 --- a/mcp/resource.go +++ b/mcp/resource.go @@ -15,7 +15,6 @@ import ( "path/filepath" "strings" - "github.com/modelcontextprotocol/go-sdk/internal/mcpgodebug" "github.com/modelcontextprotocol/go-sdk/internal/util" "github.com/modelcontextprotocol/go-sdk/jsonrpc" "github.com/yosida95/uritemplate/v3" @@ -38,25 +37,11 @@ type serverResourceTemplate struct { // If it cannot find the resource, it should return the result of calling [ResourceNotFoundError]. type ResourceHandler func(context.Context, *ReadResourceRequest) (*ReadResourceResult, error) -// customresnotfounderrcode is a compatibility parameter that restores the -// pre-1.7.0 behavior of [ResourceNotFoundError] and [CodeResourceNotFound], -// where the error code was a custom -32002. See the documentation for the mcpgodebug -// package for instructions on how to enable it. -// The option will be removed in the future version of the SDK. -var customresnotfounderrcode = mcpgodebug.Value("customresnotfounderrcode") - -func init() { - if customresnotfounderrcode == "1" { - CodeResourceNotFound = -32002 - } -} - // ResourceNotFoundError returns an error indicating that a resource being read could // not be found. // -// By default, the error code is -32602 (Invalid Params), as specified in the -// MCP specification (SEP-2164). To restore the pre-1.7.0 release behavior where the -// error code was -32002, set MCPGODEBUG=customresnotfounderrcode=1. +// The error code is -32602 (Invalid Params), as specified in the +// MCP specification (SEP-2164). func ResourceNotFoundError(uri string) error { data, _ := json.Marshal(struct { URI string `json:"uri"` diff --git a/mcp/server.go b/mcp/server.go index 96418d4b..5d50b54f 100644 --- a/mcp/server.go +++ b/mcp/server.go @@ -729,22 +729,12 @@ func (s *Server) capabilities() *ServerCapabilities { return caps } -// disablecompleteparamsvalidation is a compatibility parameter that restores -// the previous behavior of [Server.complete], where required fields on -// [CompleteParams] were not validated before dispatching to the completion -// handler. See the documentation for the mcpgodebug package for instructions -// how to enable it. -// The option will be removed in a future version of the SDK. -var disablecompleteparamsvalidation = mcpgodebug.Value("disablecompleteparamsvalidation") - func (s *Server) complete(ctx context.Context, req *CompleteRequest) (*CompleteResult, error) { - if disablecompleteparamsvalidation != "1" { - if req.Params.Ref == nil { - return nil, fmt.Errorf("%w: missing required 'ref' field", jsonrpc2.ErrInvalidParams) - } - if req.Params.Argument.Name == "" { - return nil, fmt.Errorf("%w: missing required 'argument.name' field", jsonrpc2.ErrInvalidParams) - } + if req.Params.Ref == nil { + return nil, fmt.Errorf("%w: missing required 'ref' field", jsonrpc2.ErrInvalidParams) + } + if req.Params.Argument.Name == "" { + return nil, fmt.Errorf("%w: missing required 'argument.name' field", jsonrpc2.ErrInvalidParams) } if s.opts.CompletionHandler == nil { return nil, jsonrpc2.ErrMethodNotFound diff --git a/mcp/shared.go b/mcp/shared.go index f61a28a7..f183e1f3 100644 --- a/mcp/shared.go +++ b/mcp/shared.go @@ -31,17 +31,6 @@ import ( "github.com/modelcontextprotocol/go-sdk/jsonrpc" ) -// nowrapinvalidparams is a compatibility parameter that restores the previous -// behavior of [methodInfo.unmarshalParams]. When unset (the default), a -// params-decoding failure is wrapped with [jsonrpc2.ErrInvalidParams] so the -// wire response carries error code -32602 ("invalid params") rather than the -// zero-value code 0. See: -// https://github.com/modelcontextprotocol/go-sdk/issues/976#issuecomment-4829124838. -// -// See the documentation for the mcpgodebug package for instructions how to enable it. -// The option will be removed in a future version of the SDK. -var nowrapinvalidparams = mcpgodebug.Value("nowrapinvalidparams") - // nointernalerrorcode is a compatibility parameter that restores the previous // behavior of [handleReceive]. When unset (the default), an error returned by // a request handler that carries no JSON-RPC error code is sent with code @@ -367,13 +356,6 @@ func newMethodInfo[P paramsPtr[T], R Result, T any](flags methodFlags) methodInf var p P if m != nil { if err := internaljson.Unmarshal(m, &p); err != nil { - // Legacy behavior: pre-fix versions surfaced this as a - // plain wrapped error, which caused the wire response to - // carry code 0 instead of -32602. Restore via - // MCPGODEBUG=nowrapinvalidparams=1. - if nowrapinvalidparams == "1" { - return nil, fmt.Errorf("unmarshaling %q into a %T: %w", m, p, err) - } // Wrap jsonrpc2.ErrInvalidParams so toWireError surfaces // code -32602 ("invalid params") while preserving the // descriptive message. @@ -452,8 +434,7 @@ const ( // CodeResourceNotFound indicates that a requested resource could not be found. // // By default, the value is -32602 (Invalid Params), as specified in the -// MCP specification (SEP-2164). To restore the pre-1.7.0 release behavior where the -// error code was -32002, set MCPGODEBUG=customresnotfounderrcode=1. +// MCP specification (SEP-2164). // // Deprecated: Use [jsonrpc.CodeInvalidParams] directly. This variable will be // removed in a future version. diff --git a/mcp/streamable.go b/mcp/streamable.go index a1b43a09..14e662d5 100644 --- a/mcp/streamable.go +++ b/mcp/streamable.go @@ -157,9 +157,7 @@ type StreamableHTTPOptions struct { // In Stateless mode, GET and DELETE requests return 405 Method Not Allowed. // // This mode aligns with the sessionless direction of the MCP spec; see - // [SEP-2567]. The previous behavior, in which stateless servers still - // honored Mcp-Session-Id, can be restored temporarily via the - // MCPGODEBUG compatibility parameter "allowsessionsinstateless=1". + // [SEP-2567]. // // [SEP-2567]: https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2567 Stateless bool @@ -233,8 +231,7 @@ type StreamableHTTPOptions struct { // The handler context cancels whenever the HTTP request context does as the // response can no longer be delivered, so cancelling the handler is safe. // - // Requests using older protocol versions (including those routed through - // the allowsessionsinstateless compatibility path) are unaffected. + // Requests using older protocol versions are unaffected. PropagateRequestCancellation bool // OnRequestSummary, when non-nil, observes redacted metadata for a single @@ -332,44 +329,12 @@ func (h *StreamableHTTPHandler) closeAll() { } } -// allowsessionsinstateless is a compatibility parameter that restores the old -// behavior of reading and using Mcp-Session-Id headers in stateless mode. When -// set to "1", stateless servers will read the session ID from the request -// header (or generate one via GetSessionID), set it on response headers, and -// accept DELETE requests. When unset (the default), stateless servers ignore -// session IDs entirely and reject DELETE with 405. -// See the documentation for the mcpgodebug package for instructions how to enable it. -// The option will be removed in the 1.9.0 version of the SDK. -var allowsessionsinstateless = mcpgodebug.Value("allowsessionsinstateless") - -// noprotocolerrorbody is a compatibility parameter that restores the previous -// behavior of [streamableClientConn.checkResponse]. When unset (the default), -// the client attempts to decode the response body of a non-2xx response as a -// JSON-RPC error. If successful, the underlying JSON-RPC error is surfaced to -// the caller and wrapped with [jsonrpc2.ErrRejected] so that per-call -// rejections do not tear down the session. When set to "1", the client -// ignores response bodies on non-2xx responses and any non-transient error -// permanently fails the connection. -var noprotocolerrorbody = mcpgodebug.Value("noprotocolerrorbody") - // fatalnewprotocolerrors is a compatibility parameter that restores the // previous behavior of permanently failing the connection when an independent // new-protocol request fails. The option will be removed in the 1.11.0 version // of the SDK. var fatalnewprotocolerrors = mcpgodebug.Value("fatalnewprotocolerrors") -// 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 -// `io.modelcontextprotocol/protocolVersion` `_meta` field, or an -// `MCP-Protocol-Version` header >= 2026-07-28). When unset (the default), the -// server responds with a JSON-RPC error of code -// [CodeUnsupportedProtocolVersion] and an [UnsupportedProtocolVersionData] -// payload listing its supported legacy versions, as required by SEP-2575. When -// set to "1", the server instead responds with a plain-text `http.Error` body -// mentioning the `StreamableHTTPOptions.Stateless` field. -var plaintextstatefulrejection = mcpgodebug.Value("plaintextstatefulrejection") - // writeJSONRPCError writes a JSON-RPC error response with the given HTTP // status code, request ID (may be a zero ID for errors that occur before the // request body has been parsed), and JSON-RPC error. @@ -437,17 +402,7 @@ func (h *StreamableHTTPHandler) validateProtocolVersion(w http.ResponseWriter, p // serveStateless handles requests for stateless servers. // Stateless servers only support POST. Each request creates a temporary // session that is closed when the request completes. -// -// When the allowsessionsinstateless compatibility flag is set, DELETE is also -// accepted (as a no-op) and session IDs are read from the request header. func (h *StreamableHTTPHandler) serveStateless(w http.ResponseWriter, req *http.Request) { - legacySessions := allowsessionsinstateless == "1" - - if req.Method == http.MethodDelete && legacySessions { - h.serveStatelessLegacyDELETE(w, req) - return - } - if req.Method != http.MethodPost { // RFC 9110 §15.5.6: 405 responses MUST include Allow header. w.Header().Set("Allow", "POST") @@ -487,15 +442,7 @@ func (h *StreamableHTTPHandler) serveStateless(w http.ResponseWriter, req *http. return } - var sessionID string - if legacySessions && !info.usesNewProtocol { - sessionID = req.Header.Get(sessionIDHeader) - if sessionID == "" { - sessionID = server.opts.GetSessionID() - } - } - - transport := h.newStreamableServerTransport(sessionID, true) + transport := h.newStreamableServerTransport("", true) transport.shouldPropagateCancellation = info.usesNewProtocol && (info.isSubscriptionsListen || h.opts.PropagateRequestCancellation) session, err := connectStreamable(req.Context(), server, transport, info.opts) @@ -509,19 +456,6 @@ func (h *StreamableHTTPHandler) serveStateless(w http.ResponseWriter, req *http. transport.ServeHTTP(w, req) } -// serveStatelessLegacyDELETE handles DELETE requests in stateless mode when the -// allowsessionsinstateless compatibility flag is set. DELETE requires a -// Mcp-Session-Id header but is otherwise a no-op since stateless servers don't -// persist sessions. -func (h *StreamableHTTPHandler) serveStatelessLegacyDELETE(w http.ResponseWriter, req *http.Request) { - sessionID := req.Header.Get(sessionIDHeader) - if sessionID == "" { - http.Error(w, "Bad Request: DELETE requires an Mcp-Session-Id header", http.StatusBadRequest) - return - } - w.WriteHeader(http.StatusNoContent) -} - type ephemeralConnectInfo struct { opts *ServerSessionOptions usesNewProtocol bool @@ -1740,13 +1674,6 @@ func (c *streamableServerConn) servePOST(w http.ResponseWriter, req *http.Reques // rejection as it should learn about the supported protocols from the // DiscoverResult response. if !c.stateless && jreq.Method != methodDiscover { - if plaintextstatefulrejection == "1" { - http.Error(w, fmt.Sprintf( - "Bad Request: protocol version %q is only supported on stateless HTTP servers (set StreamableHTTPOptions.Stateless = true)", - protocolVersion), - http.StatusBadRequest) - return - } // Advertise only the legacy versions this stateful server accepts // (i.e. exclude 2026-07-28, since that's what the request asked for // and what we're rejecting). @@ -2878,10 +2805,9 @@ func (c *streamableClientConn) checkResponse(ctx context.Context, requestSummary if isTransientHTTPStatus(resp.StatusCode) { return fmt.Errorf("%w: %s: %v", jsonrpc2.ErrRejected, requestSummary, http.StatusText(resp.StatusCode)) } - // By default, always try to decode the body and surface the underlying - // JSON-RPC error, wrapping it with ErrRejected to prevent the connection from closing. - // Setting MCPGODEBUG=noprotocolerrorbody=1 restores the previous behavior. - if noprotocolerrorbody != "1" && (resp.StatusCode < 200 || resp.StatusCode >= 300) { + // Always try to decode the body and surface the underlying JSON-RPC error, + // wrapping it with ErrRejected to prevent the connection from closing. + if resp.StatusCode < 200 || resp.StatusCode >= 300 { body, _ := io.ReadAll(resp.Body) msg, _ := jsonrpc.DecodeMessage(body) if response, ok := msg.(*jsonrpc.Response); ok && response.Error != nil { diff --git a/mcp/streamable_client_test.go b/mcp/streamable_client_test.go index 4c17b007..79b95afb 100644 --- a/mcp/streamable_client_test.go +++ b/mcp/streamable_client_test.go @@ -2077,9 +2077,7 @@ func TestStreamableClientConnect_DiscoverUnsupportedVersionNegotiation(t *testin // TestStreamableClientHandlerErrorPropagation verifies that per-call // handler-level HTTP errors carrying a JSON-RPC error body do not tear down -// the session, and that setting MCPGODEBUG=noprotocolerrorbody=1 restores the -// pre-fix behavior in which non-transient errors permanently failed the -// connection. +// the session. func TestStreamableClientHandlerErrorPropagation(t *testing.T) { ctx := context.Background() @@ -2089,14 +2087,13 @@ func TestStreamableClientHandlerErrorPropagation(t *testing.T) { } tests := []struct { - name string - callStatus int // HTTP status returned for the tools/call - callBody string // response body for the tools/call ("" for empty; may be a JSON-RPC error) - disableBodyDecode bool // if true, sets noprotocolerrorbody="1" for the duration of the test - fatalNewErrors bool // if true, sets fatalnewprotocolerrors="1" for the duration of the test - protocolVersion string // defaults to protocolVersion20260728 - wantErrRejected bool // whether the returned error should match errors.Is(err, jsonrpc2.ErrRejected) - wantSessionAlive bool // whether a subsequent call on the same session should succeed + name string + callStatus int // HTTP status returned for the tools/call + callBody string // response body for the tools/call ("" for empty; may be a JSON-RPC error) + fatalNewErrors bool // if true, sets fatalnewprotocolerrors="1" for the duration of the test + protocolVersion string // defaults to protocolVersion20260728 + wantErrRejected bool // whether the returned error should match errors.Is(err, jsonrpc2.ErrRejected) + wantSessionAlive bool // whether a subsequent call on the same session should succeed }{ { // SEP-2575 §"Missing Required Capabilities": server returns @@ -2132,29 +2129,6 @@ func TestStreamableClientHandlerErrorPropagation(t *testing.T) { wantErrRejected: false, wantSessionAlive: false, }, - { - // Same server response, but the user opted out via - // MCPGODEBUG=noprotocolerrorbody=1. The body is ignored, but - // without a session the failure still fails only the call. - name: "400 with JSON-RPC error body (noprotocolerrorbody=1)", - callStatus: http.StatusBadRequest, - callBody: jsonRPCErrorBody(1, CodeMissingRequiredClientCapabilities, "missing capability"), - disableBodyDecode: true, - wantErrRejected: true, - wantSessionAlive: true, - }, - { - // Same server response, but the user opted out via - // MCPGODEBUG=noprotocolerrorbody=1 and fatalnewprotocolerrors=1. - // Pre-fix behavior: the session is torn down. - name: "400 with JSON-RPC error body (noprotocolerrorbody=1, fatalnewprotocolerrors=1)", - callStatus: http.StatusBadRequest, - callBody: jsonRPCErrorBody(1, CodeMissingRequiredClientCapabilities, "missing capability"), - disableBodyDecode: true, - fatalNewErrors: true, - wantErrRejected: false, - wantSessionAlive: false, - }, { // SEP-2575: server returns -32601 for an unimplemented // method at HTTP 404. Must be treated as a per-call @@ -2207,11 +2181,6 @@ func TestStreamableClientHandlerErrorPropagation(t *testing.T) { if protocolVersion == "" { protocolVersion = protocolVersion20260728 } - if test.disableBodyDecode { - prev := noprotocolerrorbody - noprotocolerrorbody = "1" - t.Cleanup(func() { noprotocolerrorbody = prev }) - } if test.fatalNewErrors { prev := fatalnewprotocolerrors fatalnewprotocolerrors = "1" diff --git a/mcp/streamable_test.go b/mcp/streamable_test.go index 013c77d7..67c20016 100644 --- a/mcp/streamable_test.go +++ b/mcp/streamable_test.go @@ -3950,70 +3950,6 @@ func TestStreamableStateful_RejectsNewProtocol(t *testing.T) { } } -// TestStreamableStateful_RejectsNewProtocol_LegacyPlainText verifies that -// MCPGODEBUG=plaintextstatefulrejection=1 restores the pre-v1.8.0 plain-text -// 400 body for the stateful/new-protocol rejection. -func TestStreamableStateful_RejectsNewProtocol_LegacyPlainText(t *testing.T) { - prev := plaintextstatefulrejection - plaintextstatefulrejection = "1" - t.Cleanup(func() { plaintextstatefulrejection = prev }) - - server := NewServer(testImpl, nil) - AddTool(server, &Tool{Name: "noop"}, - func(ctx context.Context, req *CallToolRequest, args struct{}) (*CallToolResult, any, error) { - return &CallToolResult{Content: []Content{&TextContent{Text: "ok"}}}, nil, nil - }) - handler := NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, nil) - httpServer := httptest.NewServer(handler) - defer httpServer.Close() - - initBody := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}`) - initReq, err := http.NewRequest(http.MethodPost, httpServer.URL, initBody) - if err != nil { - t.Fatal(err) - } - initReq.Header.Set("Content-Type", "application/json") - initReq.Header.Set("Accept", "application/json, text/event-stream") - initResp, err := http.DefaultClient.Do(initReq) - if err != nil { - t.Fatal(err) - } - io.Copy(io.Discard, initResp.Body) - initResp.Body.Close() - sessionID := initResp.Header.Get(sessionIDHeader) - if sessionID == "" { - t.Fatalf("initialize response missing %s header", sessionIDHeader) - } - - body := newProtocolBody(t, "noop", struct{}{}) - req, err := http.NewRequest(http.MethodPost, httpServer.URL, bytes.NewReader(body)) - if err != nil { - t.Fatal(err) - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json, text/event-stream") - req.Header.Set(sessionIDHeader, sessionID) - req.Header.Set(protocolVersionHeader, protocolVersion20260728) - req.Header.Set(methodHeader, "tools/call") - req.Header.Set(nameHeader, "noop") - - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - respBody, _ := io.ReadAll(resp.Body) - if resp.StatusCode != http.StatusBadRequest { - t.Fatalf("status = %d, want 400; body = %s", resp.StatusCode, respBody) - } - if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/plain") { - t.Errorf("Content-Type = %q, want text/plain; body = %s", ct, respBody) - } - if !strings.Contains(string(respBody), "stateless") { - t.Errorf("body = %q, want a message mentioning 'stateless'", respBody) - } -} - // TestCallCancellation_FastReturn verifies that a cancelled tool call // returns as soon as its context is cancelled, even when the peer is slow // to accept the follow-up notifications/cancelled POST. diff --git a/mcp/transport.go b/mcp/transport.go index adb21906..d970be63 100644 --- a/mcp/transport.go +++ b/mcp/transport.go @@ -18,7 +18,6 @@ import ( internaljson "github.com/modelcontextprotocol/go-sdk/internal/json" "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2" - "github.com/modelcontextprotocol/go-sdk/internal/mcpgodebug" "github.com/modelcontextprotocol/go-sdk/jsonrpc" ) @@ -29,13 +28,6 @@ import ( // re-trigger expensive recovery on its behalf. See issue #882. const notifyCancellationTimeout = 5 * time.Second -// blockingcancelnotify, when set to "1" via MCPGODEBUG, restores the previous -// behavior of blocking the caller's return on delivery of the best-effort -// notifications/cancelled message (up to notifyCancellationTimeout). By -// default, the call is retired immediately and the notification is sent -// asynchronously so the caller returns as soon as its context is cancelled. -var blockingcancelnotify = mcpgodebug.Value("blockingcancelnotify") - // ErrConnectionClosed is returned when sending a message to a connection that // is closed or in the process of closing. var ErrConnectionClosed = errors.New("connection closed") @@ -319,18 +311,15 @@ func call(ctx context.Context, conn *jsonrpc2.Connection, method string, params } return fmt.Errorf("%w: calling %q", ErrConnectionClosed, method) case ctx.Err() != nil: - // The notifications/cancelled message is best-effort. Retire the call - // immediately (so an unresponsive peer cannot delay the eager - // retirement that cancelCall's docstring promises) and send the - // notification off the caller's return path so a slow or unresponsive - // peer cannot delay the caller past its own deadline. See issue #1150. + // Eagerly retire the call: by default, the jsonrpc2 library waits for + // all outgoing calls to complete on close, which can hang shutdown if + // the peer is gone (e.g. a killed streamable client that the server + // can only detect via keepalive pings). If the caller will never + // receive the response, there's no need to track it. // - // Setting MCPGODEBUG=blockingcancelnotify=1 restores the previous - // behavior of waiting synchronously for delivery inside cancelCall. - if blockingcancelnotify == "1" { - err := cancelCall(ctx, conn, call) - return errors.Join(ctx.Err(), err) - } + // The notifications/cancelled message is best-effort, so it is sent + // off the caller's return path: a slow or unresponsive peer cannot + // delay the caller past its own deadline. See issue #1150. conn.Retire(call, ctx.Err()) go func() { notifyCtx, stop := context.WithTimeout(context.WithoutCancel(ctx), notifyCancellationTimeout) @@ -370,30 +359,6 @@ func withoutClosingErrors(err error) error { } } -// cancelCall sends a "notifications/cancelled" notification for call and eagerly -// retires it from conn. -// -// By default, the jsonrpc2 library waits for graceful shutdown when the -// connection is closed, meaning it expects all outgoing and incoming requests -// to complete. However, for MCP this expectation is unrealistic, and can lead -// to hanging shutdown. For example, if a streamable client is killed, the -// server will not be able to detect this event, except via keepalive pings (if -// they are configured), and so outgoing calls may hang indefinitely. -// -// Therefore, we choose to eagerly retire calls, removing them from the -// outgoingCalls map, when the caller context is cancelled: if the caller will -// never receive the response, there's no need to track it. -func cancelCall(ctx context.Context, conn *jsonrpc2.Connection, call *jsonrpc2.AsyncCall) error { - notifyCtx, cancelNotify := context.WithTimeout(context.WithoutCancel(ctx), notifyCancellationTimeout) - defer cancelNotify() - err := conn.Notify(notifyCtx, notificationCancelled, &CancelledParams{ - Reason: ctx.Err().Error(), - RequestID: call.ID().Raw(), - }) - conn.Retire(call, ctx.Err()) - return err -} - // A LoggingTransport is a [Transport] that delegates to another transport, // writing RPC logs to an io.Writer. type LoggingTransport struct { From e508674abb08d6c131fb71ebf3e8842ed3011e23 Mon Sep 17 00:00:00 2001 From: guglielmoc Date: Tue, 17 Nov 2026 09:13:16 +0000 Subject: [PATCH 2/2] update --- docs/mcpgodebug.md | 9 +---- internal/docs/mcpgodebug.src.md | 9 +---- mcp/streamable.go | 19 ++++++++++ mcp/streamable_test.go | 64 +++++++++++++++++++++++++++++++++ mcp/transport.go | 51 +++++++++++++++++++++----- 5 files changed, 128 insertions(+), 24 deletions(-) diff --git a/docs/mcpgodebug.md b/docs/mcpgodebug.md index dd66b45b..6397c076 100644 --- a/docs/mcpgodebug.md +++ b/docs/mcpgodebug.md @@ -102,16 +102,9 @@ Options below were removed, according to plan: - `disablecompleteparamsvalidation`. `Server.complete` now always validates the required `ref` and `argument.name` fields. -- `plaintextstatefulrejection`. A stateful `StreamableHTTPHandler` now always - rejects per-request metadata with a JSON-RPC - `CodeUnsupportedProtocolVersion` error. - -- `blockingcancelnotify`. A cancelled call now always returns immediately and - sends `notifications/cancelled` asynchronously. - ### 1.8.0 -Options listed below were added and will be removed in the 1.9.0 version of the SDK. +Options listed below were added and will be removed in the 1.10.0 version of the SDK. - `plaintextstatefulrejection` added. If set to `1`, a stateful `StreamableHTTPHandler` will respond with a plain-text `http.Error` 400 body diff --git a/internal/docs/mcpgodebug.src.md b/internal/docs/mcpgodebug.src.md index fd55e154..c3ec410c 100644 --- a/internal/docs/mcpgodebug.src.md +++ b/internal/docs/mcpgodebug.src.md @@ -101,16 +101,9 @@ Options below were removed, according to plan: - `disablecompleteparamsvalidation`. `Server.complete` now always validates the required `ref` and `argument.name` fields. -- `plaintextstatefulrejection`. A stateful `StreamableHTTPHandler` now always - rejects per-request metadata with a JSON-RPC - `CodeUnsupportedProtocolVersion` error. - -- `blockingcancelnotify`. A cancelled call now always returns immediately and - sends `notifications/cancelled` asynchronously. - ### 1.8.0 -Options listed below were added and will be removed in the 1.9.0 version of the SDK. +Options listed below were added and will be removed in the 1.10.0 version of the SDK. - `plaintextstatefulrejection` added. If set to `1`, a stateful `StreamableHTTPHandler` will respond with a plain-text `http.Error` 400 body diff --git a/mcp/streamable.go b/mcp/streamable.go index 14e662d5..87e11dcf 100644 --- a/mcp/streamable.go +++ b/mcp/streamable.go @@ -335,6 +335,18 @@ func (h *StreamableHTTPHandler) closeAll() { // of the SDK. var fatalnewprotocolerrors = mcpgodebug.Value("fatalnewprotocolerrors") +// 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 +// `io.modelcontextprotocol/protocolVersion` `_meta` field, or an +// `MCP-Protocol-Version` header >= 2026-07-28). When unset (the default), the +// server responds with a JSON-RPC error of code +// [CodeUnsupportedProtocolVersion] and an [UnsupportedProtocolVersionData] +// payload listing its supported legacy versions, as required by SEP-2575. When +// set to "1", the server instead responds with a plain-text `http.Error` body +// mentioning the `StreamableHTTPOptions.Stateless` field. +var plaintextstatefulrejection = mcpgodebug.Value("plaintextstatefulrejection") + // writeJSONRPCError writes a JSON-RPC error response with the given HTTP // status code, request ID (may be a zero ID for errors that occur before the // request body has been parsed), and JSON-RPC error. @@ -1674,6 +1686,13 @@ func (c *streamableServerConn) servePOST(w http.ResponseWriter, req *http.Reques // rejection as it should learn about the supported protocols from the // DiscoverResult response. if !c.stateless && jreq.Method != methodDiscover { + if plaintextstatefulrejection == "1" { + http.Error(w, fmt.Sprintf( + "Bad Request: protocol version %q is only supported on stateless HTTP servers (set StreamableHTTPOptions.Stateless = true)", + protocolVersion), + http.StatusBadRequest) + return + } // Advertise only the legacy versions this stateful server accepts // (i.e. exclude 2026-07-28, since that's what the request asked for // and what we're rejecting). diff --git a/mcp/streamable_test.go b/mcp/streamable_test.go index 67c20016..013c77d7 100644 --- a/mcp/streamable_test.go +++ b/mcp/streamable_test.go @@ -3950,6 +3950,70 @@ func TestStreamableStateful_RejectsNewProtocol(t *testing.T) { } } +// TestStreamableStateful_RejectsNewProtocol_LegacyPlainText verifies that +// MCPGODEBUG=plaintextstatefulrejection=1 restores the pre-v1.8.0 plain-text +// 400 body for the stateful/new-protocol rejection. +func TestStreamableStateful_RejectsNewProtocol_LegacyPlainText(t *testing.T) { + prev := plaintextstatefulrejection + plaintextstatefulrejection = "1" + t.Cleanup(func() { plaintextstatefulrejection = prev }) + + server := NewServer(testImpl, nil) + AddTool(server, &Tool{Name: "noop"}, + func(ctx context.Context, req *CallToolRequest, args struct{}) (*CallToolResult, any, error) { + return &CallToolResult{Content: []Content{&TextContent{Text: "ok"}}}, nil, nil + }) + handler := NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, nil) + httpServer := httptest.NewServer(handler) + defer httpServer.Close() + + initBody := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}`) + initReq, err := http.NewRequest(http.MethodPost, httpServer.URL, initBody) + if err != nil { + t.Fatal(err) + } + initReq.Header.Set("Content-Type", "application/json") + initReq.Header.Set("Accept", "application/json, text/event-stream") + initResp, err := http.DefaultClient.Do(initReq) + if err != nil { + t.Fatal(err) + } + io.Copy(io.Discard, initResp.Body) + initResp.Body.Close() + sessionID := initResp.Header.Get(sessionIDHeader) + if sessionID == "" { + t.Fatalf("initialize response missing %s header", sessionIDHeader) + } + + body := newProtocolBody(t, "noop", struct{}{}) + req, err := http.NewRequest(http.MethodPost, httpServer.URL, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set(sessionIDHeader, sessionID) + req.Header.Set(protocolVersionHeader, protocolVersion20260728) + req.Header.Set(methodHeader, "tools/call") + req.Header.Set(nameHeader, "noop") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + respBody, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", resp.StatusCode, respBody) + } + if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/plain") { + t.Errorf("Content-Type = %q, want text/plain; body = %s", ct, respBody) + } + if !strings.Contains(string(respBody), "stateless") { + t.Errorf("body = %q, want a message mentioning 'stateless'", respBody) + } +} + // TestCallCancellation_FastReturn verifies that a cancelled tool call // returns as soon as its context is cancelled, even when the peer is slow // to accept the follow-up notifications/cancelled POST. diff --git a/mcp/transport.go b/mcp/transport.go index d970be63..adb21906 100644 --- a/mcp/transport.go +++ b/mcp/transport.go @@ -18,6 +18,7 @@ import ( internaljson "github.com/modelcontextprotocol/go-sdk/internal/json" "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2" + "github.com/modelcontextprotocol/go-sdk/internal/mcpgodebug" "github.com/modelcontextprotocol/go-sdk/jsonrpc" ) @@ -28,6 +29,13 @@ import ( // re-trigger expensive recovery on its behalf. See issue #882. const notifyCancellationTimeout = 5 * time.Second +// blockingcancelnotify, when set to "1" via MCPGODEBUG, restores the previous +// behavior of blocking the caller's return on delivery of the best-effort +// notifications/cancelled message (up to notifyCancellationTimeout). By +// default, the call is retired immediately and the notification is sent +// asynchronously so the caller returns as soon as its context is cancelled. +var blockingcancelnotify = mcpgodebug.Value("blockingcancelnotify") + // ErrConnectionClosed is returned when sending a message to a connection that // is closed or in the process of closing. var ErrConnectionClosed = errors.New("connection closed") @@ -311,15 +319,18 @@ func call(ctx context.Context, conn *jsonrpc2.Connection, method string, params } return fmt.Errorf("%w: calling %q", ErrConnectionClosed, method) case ctx.Err() != nil: - // Eagerly retire the call: by default, the jsonrpc2 library waits for - // all outgoing calls to complete on close, which can hang shutdown if - // the peer is gone (e.g. a killed streamable client that the server - // can only detect via keepalive pings). If the caller will never - // receive the response, there's no need to track it. + // The notifications/cancelled message is best-effort. Retire the call + // immediately (so an unresponsive peer cannot delay the eager + // retirement that cancelCall's docstring promises) and send the + // notification off the caller's return path so a slow or unresponsive + // peer cannot delay the caller past its own deadline. See issue #1150. // - // The notifications/cancelled message is best-effort, so it is sent - // off the caller's return path: a slow or unresponsive peer cannot - // delay the caller past its own deadline. See issue #1150. + // Setting MCPGODEBUG=blockingcancelnotify=1 restores the previous + // behavior of waiting synchronously for delivery inside cancelCall. + if blockingcancelnotify == "1" { + err := cancelCall(ctx, conn, call) + return errors.Join(ctx.Err(), err) + } conn.Retire(call, ctx.Err()) go func() { notifyCtx, stop := context.WithTimeout(context.WithoutCancel(ctx), notifyCancellationTimeout) @@ -359,6 +370,30 @@ func withoutClosingErrors(err error) error { } } +// cancelCall sends a "notifications/cancelled" notification for call and eagerly +// retires it from conn. +// +// By default, the jsonrpc2 library waits for graceful shutdown when the +// connection is closed, meaning it expects all outgoing and incoming requests +// to complete. However, for MCP this expectation is unrealistic, and can lead +// to hanging shutdown. For example, if a streamable client is killed, the +// server will not be able to detect this event, except via keepalive pings (if +// they are configured), and so outgoing calls may hang indefinitely. +// +// Therefore, we choose to eagerly retire calls, removing them from the +// outgoingCalls map, when the caller context is cancelled: if the caller will +// never receive the response, there's no need to track it. +func cancelCall(ctx context.Context, conn *jsonrpc2.Connection, call *jsonrpc2.AsyncCall) error { + notifyCtx, cancelNotify := context.WithTimeout(context.WithoutCancel(ctx), notifyCancellationTimeout) + defer cancelNotify() + err := conn.Notify(notifyCtx, notificationCancelled, &CancelledParams{ + Reason: ctx.Err().Error(), + RequestID: call.ID().Raw(), + }) + conn.Retire(call, ctx.Err()) + return err +} + // A LoggingTransport is a [Transport] that delegates to another transport, // writing RPC logs to an io.Writer. type LoggingTransport struct {