diff --git a/docs/mcpgodebug.md b/docs/mcpgodebug.md index 47563523..6397c076 100644 --- a/docs/mcpgodebug.md +++ b/docs/mcpgodebug.md @@ -79,9 +79,32 @@ 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. + ### 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 66f36ff2..c3ec410c 100644 --- a/internal/docs/mcpgodebug.src.md +++ b/internal/docs/mcpgodebug.src.md @@ -78,9 +78,32 @@ 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. + ### 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/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..87e11dcf 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,26 +329,6 @@ 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 @@ -437,17 +414,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 +454,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 +468,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 @@ -2878,10 +2824,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"