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
19 changes: 5 additions & 14 deletions mcp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2212,30 +2212,21 @@ var nopreinitinvalidrequest = mcpgodebug.Value("nopreinitinvalidrequest")
func (ss *ServerSession) handle(ctx context.Context, req *jsonrpc.Request) (any, error) {
ss.mu.Lock()
initialized := ss.state.InitializeParams != nil
supportedVersions := ss.supportedVersions
ss.mu.Unlock()
if supportedVersions == nil || req.Method == methodDiscover {
supportedVersions = ss.server.protocolVersions
}

// Per-request protocol detection (SEP-2575): if the request carries
// `io.modelcontextprotocol/protocolVersion` in its `_meta` field, it
// follows the new sessionless protocol. The initialization gate is
// skipped for such requests.
validatedMeta, perRequestErr := validateRequestMeta(req)
validatedMeta, perRequestErr := validateRequestMeta(req, supportedVersions)
if perRequestErr != nil {
return nil, perRequestErr
}

if validatedMeta.usesNewProtocol &&
!slices.Contains(ss.server.protocolVersions, validatedMeta.initializeParams.ProtocolVersion) {
data, _ := json.Marshal(UnsupportedProtocolVersionData{
Supported: ss.server.protocolVersions,
Requested: validatedMeta.initializeParams.ProtocolVersion,
})
return nil, &jsonrpc.Error{
Code: CodeUnsupportedProtocolVersion,
Message: "unsupported protocol version",
Data: data,
}
}

// A server that supports only 2026-07-28 and later serves no legacy call,
// initialize included.
if !validatedMeta.usesNewProtocol && req.IsCall() &&
Expand Down
53 changes: 25 additions & 28 deletions mcp/shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -621,21 +621,19 @@ type validatedMeta struct {

// validateRequestMeta inspects a JSON-RPC request to detect whether it follows
// the >= 2026-07-28 protocol via the `_meta` field.
// If the request has no _meta, no protocolVersion in _meta, or a protocolVersion
// naming a supported version that predates 2026-07-28, it returns a non-nil
// validatedMeta with usesNewProtocol set to false, and a nil error: such a request
// belongs to the initialize handshake.
// If the protocolVersion names a version that is not supported at all, it returns
// usesNewProtocol set to true with initializeParams carrying only that version, so
// that the caller answers with [CodeUnsupportedProtocolVersion]. The rest of the
// `_meta` triple is not validated in that case, since the revision defining it is
// unknown.
// Otherwise, it validates the presence of clientCapabilities in _meta. If it is
// missing or invalid, it returns nil and a non-nil error. clientInfo is optional;
// if present but invalid, an error is returned. Otherwise, it returns
// usesNewProtocol set to true and the populated initializeParams.
// Notifications always report usesNewProtocol false and never error.
func validateRequestMeta(req *jsonrpc.Request) (*validatedMeta, error) {
//
// If the request is a notification, has no _meta, or has no protocolVersion in
// _meta, it returns usesNewProtocol=false and a nil error.
// If protocolVersion is not in supportedVersions, it returns a
// [CodeUnsupportedProtocolVersion] error without validating the rest of the
// `_meta` triple (since the revision defining it is unsupported).
// If protocolVersion is a supported version predating 2026-07-28, it returns
// usesNewProtocol=false and a nil error (the request belongs to the legacy
// initialize handshake).
// Otherwise, it validates clientCapabilities (required) and clientInfo
// (optional) and returns usesNewProtocol=true with the populated
// initializeParams.
func validateRequestMeta(req *jsonrpc.Request, supportedVersions []string) (*validatedMeta, error) {
// SEP-2575 defines the `_meta` triple for calls only: NotificationParams
// declares `_meta` optional with no protocolVersion, so a notification
// neither selects the new protocol nor is discarded for carrying an
Expand All @@ -653,20 +651,19 @@ func validateRequestMeta(req *jsonrpc.Request) (*validatedMeta, error) {
if !ok || protocolVersion == "" {
return &validatedMeta{usesNewProtocol: false, initializeParams: nil}, nil
}
// Classify by membership rather than by ordering: a version the SDK does not
// know sorts arbitrarily against 2026-07-28, and one that sorts below it would
// be served as a legacy handshake instead of reaching the
// CodeUnsupportedProtocolVersion check in ServerSession.handle. The
// streamable handler already applies the same membership rule to the
// Mcp-Protocol-Version header.
supported := slices.Contains(supportedProtocolVersions, protocolVersion)
if supported && protocolVersion < protocolVersion20260728 {
return &validatedMeta{usesNewProtocol: false, initializeParams: nil}, nil
if !slices.Contains(supportedVersions, protocolVersion) {
data, _ := json.Marshal(UnsupportedProtocolVersionData{
Supported: supportedVersions,
Requested: protocolVersion,
})
return nil, &jsonrpc.Error{
Code: CodeUnsupportedProtocolVersion,
Message: "unsupported protocol version",
Data: data,
}
}
if !supported {
return &validatedMeta{usesNewProtocol: true, initializeParams: &InitializeParams{
ProtocolVersion: protocolVersion,
}}, nil
if protocolVersion < protocolVersion20260728 {
return &validatedMeta{usesNewProtocol: false, initializeParams: nil}, nil
}
var clientInfo *Implementation
if _, present := meta[MetaKeyClientInfo]; present {
Expand Down
64 changes: 53 additions & 11 deletions mcp/shared_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,12 @@ func TestValidateRequestMeta(t *testing.T) {
name string
method string
params any
supported []string // defaults to supportedProtocolVersions
wantUsesNew bool
wantLogLevel LoggingLevel
wantErrCode int64 // defaults to jsonrpc.CodeInvalidParams when wantErrContains != ""
wantErrContains string
wantRequested string
}{
{
name: "no params: old protocol",
Expand Down Expand Up @@ -164,10 +167,7 @@ func TestValidateRequestMeta(t *testing.T) {
wantUsesNew: false,
},
{
// An unsupported version sorting below 2026-07-28 is still a
// new-protocol request, so that the caller can answer it with
// CodeUnsupportedProtocolVersion.
name: "unsupported version: new protocol",
name: "unsupported version: rejected directly",
method: methodCallTool,
params: map[string]any{
"_meta": map[string]any{
Expand All @@ -177,20 +177,42 @@ func TestValidateRequestMeta(t *testing.T) {
},
"name": "x",
},
wantUsesNew: true,
wantUsesNew: false,
wantErrCode: CodeUnsupportedProtocolVersion,
wantErrContains: "unsupported protocol version",
wantRequested: "1900-01-01",
},
{
// The triple is defined by a revision the SDK does not know, so an
// The triple is defined by a revision the server does not support, so an
// unsupported version is reported without validating the rest of it.
name: "unsupported version missing clientCapabilities: new protocol",
name: "unsupported version missing clientCapabilities: rejected directly",
method: methodCallTool,
params: map[string]any{
"_meta": map[string]any{
MetaKeyProtocolVersion: "1900-01-01",
},
"name": "x",
},
wantUsesNew: true,
wantUsesNew: false,
wantErrCode: CodeUnsupportedProtocolVersion,
wantErrContains: "unsupported protocol version",
wantRequested: "1900-01-01",
},
{
name: "excluded modern version: rejected directly",
method: methodCallTool,
supported: []string{protocolVersion20251125},
params: map[string]any{
"_meta": map[string]any{
MetaKeyProtocolVersion: protocolVersion20260728,
MetaKeyClientCapabilities: map[string]any{},
},
"name": "x",
},
wantUsesNew: false,
wantErrCode: CodeUnsupportedProtocolVersion,
wantErrContains: "unsupported protocol version",
wantRequested: protocolVersion20260728,
},
{
name: "new protocol with logLevel",
Expand Down Expand Up @@ -237,7 +259,11 @@ func TestValidateRequestMeta(t *testing.T) {
}
req := &jsonrpc.Request{Method: tc.method, Params: raw, ID: id}

vmeta, err := validateRequestMeta(req)
supported := tc.supported
if supported == nil {
supported = supportedProtocolVersions
}
vmeta, err := validateRequestMeta(req, supported)
usesNew := vmeta != nil && vmeta.usesNewProtocol
if usesNew != tc.wantUsesNew {
t.Errorf("usesNewProtocol = %v, want %v", usesNew, tc.wantUsesNew)
Expand All @@ -258,12 +284,28 @@ func TestValidateRequestMeta(t *testing.T) {
if !errors.As(err, &jerr) {
t.Fatalf("expected *jsonrpc.Error, got %T: %v", err, err)
}
if jerr.Code != jsonrpc.CodeInvalidParams {
t.Errorf("error code = %d, want %d", jerr.Code, jsonrpc.CodeInvalidParams)
wantCode := tc.wantErrCode
if wantCode == 0 {
wantCode = jsonrpc.CodeInvalidParams
}
if jerr.Code != wantCode {
t.Errorf("error code = %d, want %d", jerr.Code, wantCode)
}
if !strings.Contains(jerr.Message, tc.wantErrContains) {
t.Errorf("error message %q does not contain %q", jerr.Message, tc.wantErrContains)
}
if tc.wantRequested != "" {
var data UnsupportedProtocolVersionData
if err := json.Unmarshal(jerr.Data, &data); err != nil {
t.Fatalf("unmarshal error data: %v", err)
}
if data.Requested != tc.wantRequested {
t.Errorf("data.Requested = %q, want %q", data.Requested, tc.wantRequested)
}
if diff := cmp.Diff(supported, data.Supported); diff != "" {
t.Errorf("data.Supported mismatch (-want +got):\n%s", diff)
}
}
})
}
}
Expand Down
33 changes: 19 additions & 14 deletions mcp/streamable.go
Original file line number Diff line number Diff line change
Expand Up @@ -1714,18 +1714,22 @@ func (c *streamableServerConn) servePOST(w http.ResponseWriter, req *http.Reques
if meta := extractRequestMeta(jreq.Params); meta != nil {
metaVersion, _ = meta[MetaKeyProtocolVersion].(string)
}
if (jreq.IsCall() && protocolVersion >= protocolVersion20260728) || metaVersion != "" {
if protocolVersion >= protocolVersion20260728 || metaVersion >= protocolVersion20260728 {
// Extract again the protocol version from the context to see what the client
// is advertising in the Mcp-Protocol-Version HTTP header.
headerVersion := protocolVersionFromContext(req.Context())
// server/discover is exempt from the stateful
// rejection as it should learn about the supported protocols from the
// DiscoverResult response.
if !c.stateless && jreq.Method != methodDiscover {
requestedVersion := headerVersion
if requestedVersion < protocolVersion20260728 {
requestedVersion = metaVersion
}
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),
requestedVersion),
http.StatusBadRequest)
return
}
Expand All @@ -1741,14 +1745,14 @@ func (c *streamableServerConn) servePOST(w http.ResponseWriter, req *http.Reques
})
data, _ := json.Marshal(UnsupportedProtocolVersionData{
Supported: legacyVersions,
Requested: protocolVersion,
Requested: requestedVersion,
})
c.logger.Warn(fmt.Sprintf(
"rejecting request with protocol version %q: this server is stateful; set StreamableHTTPOptions.Stateless = true to accept it",
protocolVersion))
requestedVersion))
writeJSONRPCError(w, http.StatusBadRequest, jreq.ID, &jsonrpc.Error{
Code: CodeUnsupportedProtocolVersion,
Message: fmt.Sprintf("protocol version %q is not supported by this server", protocolVersion),
Message: fmt.Sprintf("protocol version %q is not supported by this server in stateful configuration", requestedVersion),
Data: data,
})
return
Expand All @@ -1763,15 +1767,16 @@ func (c *streamableServerConn) servePOST(w http.ResponseWriter, req *http.Reques
return
}
if metaVersion == "" {
writeJSONRPCError(w, http.StatusBadRequest, jreq.ID, &jsonrpc.Error{
Code: jsonrpc.CodeInvalidParams,
Message: fmt.Sprintf(
"missing or invalid _meta field %q",
MetaKeyProtocolVersion),
})
return
}
if headerVersion != metaVersion {
if jreq.IsCall() {
writeJSONRPCError(w, http.StatusBadRequest, jreq.ID, &jsonrpc.Error{
Code: jsonrpc.CodeInvalidParams,
Message: fmt.Sprintf(
"missing or invalid _meta field %q",
MetaKeyProtocolVersion),
})
return
}
} else if headerVersion != metaVersion {
writeJSONRPCError(w, http.StatusBadRequest, jreq.ID, &jsonrpc.Error{
Code: CodeHeaderMismatch,
Message: fmt.Sprintf(
Expand Down
Loading
Loading