Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion docs/mcpgodebug.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 24 additions & 1 deletion internal/docs/mcpgodebug.src.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 1 addition & 18 deletions internal/jsonrpc2/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
}

Expand Down
20 changes: 0 additions & 20 deletions mcp/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
}
Expand Down
19 changes: 2 additions & 17 deletions mcp/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"`
Expand Down
20 changes: 5 additions & 15 deletions mcp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 1 addition & 20 deletions mcp/shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
67 changes: 6 additions & 61 deletions mcp/streamable.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading