From 6db4af052376e3920e84cf64615ece6b09f4fef7 Mon Sep 17 00:00:00 2001 From: Rob Findley Date: Wed, 30 Jul 2025 15:42:23 +0000 Subject: [PATCH] mcp: reject notifications with unexpected ID field Use the new 'isRequest' field on methodInfo to also reject notifications with an unexpected ID field. For #196 --- mcp/shared.go | 5 ++++- .../{missing_fields.txtar => bad_requests.txtar} | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) rename mcp/testdata/conformance/server/{missing_fields.txtar => bad_requests.txtar} (78%) diff --git a/mcp/shared.go b/mcp/shared.go index 0bc7c793..46720eed 100644 --- a/mcp/shared.go +++ b/mcp/shared.go @@ -155,7 +155,10 @@ func checkRequest(req *jsonrpc.Request, infos map[string]methodInfo) (methodInfo return methodInfo{}, fmt.Errorf("%w: %q unsupported", jsonrpc2.ErrNotHandled, req.Method) } if info.isRequest && !req.ID.IsValid() { - return methodInfo{}, fmt.Errorf("%w: %q missing ID", jsonrpc2.ErrInvalidRequest, req.Method) + return methodInfo{}, fmt.Errorf("%w: missing ID, %q", jsonrpc2.ErrInvalidRequest, req.Method) + } + if !info.isRequest && req.ID.IsValid() { + return methodInfo{}, fmt.Errorf("%w: unexpected id for %q", jsonrpc2.ErrInvalidRequest, req.Method) } return info, nil } diff --git a/mcp/testdata/conformance/server/missing_fields.txtar b/mcp/testdata/conformance/server/bad_requests.txtar similarity index 78% rename from mcp/testdata/conformance/server/missing_fields.txtar rename to mcp/testdata/conformance/server/bad_requests.txtar index c5aa3e55..d2f278bc 100644 --- a/mcp/testdata/conformance/server/missing_fields.txtar +++ b/mcp/testdata/conformance/server/bad_requests.txtar @@ -4,6 +4,7 @@ bad requests. Fixed bugs: - No id in 'initialize' should not panic (#197). - No id in 'ping' should not panic (#194). +- Notifications with IDs should not be treated like requests. TODO: - No params in 'initialize' should not panic (#195). @@ -31,6 +32,7 @@ code_review "clientInfo": { "name": "ExampleClient", "version": "1.0.0" } } } +{"jsonrpc":"2.0", "id": 3, "method":"notifications/initialized"} {"jsonrpc":"2.0", "method":"ping"} -- server -- @@ -52,3 +54,11 @@ code_review } } } +{ + "jsonrpc": "2.0", + "id": 3, + "error": { + "code": -32600, + "message": "JSON RPC invalid request: unexpected id for \"notifications/initialized\"" + } +}