Repository navigation
mcp: return null-ID errors for rejected request identities #1392
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
skosovsky
wants to merge
3
commits into
modelcontextprotocol:main
Choose a base branch
from
skosovsky:fix/invalid-request-id-framing
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| // Copyright 2026 The Go MCP SDK Authors. All rights reserved. | ||
| // Use of this source code is governed by the license | ||
| // that can be found in the LICENSE file. | ||
|
|
||
| package jsonrpc2 | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "errors" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestInvalidRequestIDClassification(t *testing.T) { | ||
| for _, tt := range []struct { | ||
| name, wire string | ||
| rejectedRequest, rejected bool | ||
| }{ | ||
| {"request", `{"jsonrpc":"2.0","method":"ping","id":true}`, true, true}, | ||
| {"response", `{"jsonrpc":"2.0","result":{},"id":true}`, false, true}, | ||
| {"syntax", `{"jsonrpc":`, false, true}, | ||
| {"notification", `{"jsonrpc":"2.0","method":"ping"}`, false, false}, | ||
| {"null", `{"jsonrpc":"2.0","method":"ping","id":null}`, false, false}, | ||
| } { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| wire := []byte(tt.wire) | ||
| _, err := DecodeMessage(wire) | ||
| if (err != nil) != tt.rejected || errors.Is(err, ErrInvalidRequestID) != tt.rejectedRequest { | ||
| t.Fatalf("DecodeMessage error = %v", err) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestUnknownIDErrorEncoding(t *testing.T) { | ||
| response := &Response{Error: ErrInvalidRequest} | ||
| wire, err := EncodeMessage(response) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| var fields map[string]json.RawMessage | ||
| if err := json.Unmarshal(wire, &fields); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if string(fields["id"]) != "null" || fields["error"] == nil || fields["result"] != nil { | ||
| t.Fatalf("invalid error response: %s", wire) | ||
| } | ||
| } | ||
|
|
||
| func TestNullIDErrorResponseRoundTrip(t *testing.T) { | ||
| original := &Response{Error: &WireError{Code: -32600, Message: "invalid request ID"}} | ||
| wire, err := EncodeMessage(original) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| decoded, err := DecodeMessage(wire) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| response, ok := decoded.(*Response) | ||
| if !ok { | ||
| t.Fatalf("decoded %T, want response", decoded) | ||
| } | ||
| var wireErr *WireError | ||
| if response.ID.IsValid() || !errors.As(response.Error, &wireErr) || wireErr.Code != -32600 { | ||
| t.Fatalf("response = %#v", response) | ||
| } | ||
| } | ||
|
|
||
| func TestInvalidUnknownIDResponse(t *testing.T) { | ||
| for _, wire := range []string{ | ||
| `{"jsonrpc":"2.0","error":{"code":-32600,"message":"bad"}}`, | ||
| `{"jsonrpc":"2.0","id":null,"result":{}}`, | ||
| `{"jsonrpc":"2.0","id":null,"error":null}`, | ||
| `{"jsonrpc":"2.0","id":null,"result":null,"error":{"code":-32600,"message":"bad"}}`, | ||
| `{"jsonrpc":"2.0","ID":null,"error":{"code":-32600,"message":"bad"}}`, | ||
| } { | ||
| _, err := DecodeMessage([]byte(wire)) | ||
| if !errors.Is(err, ErrInvalidRequest) { | ||
| t.Fatalf("DecodeMessage(%s) error = %v", wire, err) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| // Copyright 2026 The Go MCP SDK Authors. All rights reserved. | ||
| // Use of this source code is governed by the license | ||
| // that can be found in the LICENSE file. | ||
|
|
||
| package mcp | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/modelcontextprotocol/go-sdk/jsonrpc" | ||
| ) | ||
|
|
||
| type invalidIDWriter struct{ bytes.Buffer } | ||
|
|
||
| func (*invalidIDWriter) Close() error { return nil } | ||
|
|
||
| func TestInvalidRequestIDHTTP(t *testing.T) { | ||
| for _, id := range []string{"true", "{}", "[]"} { | ||
| calls := 0 | ||
| server := NewServer(&Implementation{Name: "synthetic", Version: "test"}, nil) | ||
| server.AddTool(&Tool{Name: "probe", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *CallToolRequest) (*CallToolResult, error) { | ||
| calls++ | ||
| return &CallToolResult{}, nil | ||
| }) | ||
| handler := NewStreamableHTTPHandler(func(*http.Request) *Server { return server }, &StreamableHTTPOptions{Stateless: true, JSONResponse: true}) | ||
| req := httptest.NewRequest(http.MethodPost, "http://localhost/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":`+id+`,"method":"tools/call","params":{"name":"probe","arguments":{}}}`)) | ||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Accept", "application/json, text/event-stream") | ||
| result := httptest.NewRecorder() | ||
| handler.ServeHTTP(result, req) | ||
| var envelope struct { | ||
| ID json.RawMessage | ||
| Error struct{ Code int } | ||
| } | ||
| if err := json.Unmarshal(result.Body.Bytes(), &envelope); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if result.Header().Get("Content-Type") != "application/json" || result.Code != 400 || string(envelope.ID) != "null" || envelope.Error.Code != -32600 || calls != 0 { | ||
| t.Fatalf("status%d calls%d body%s", result.Code, calls, result.Body) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestInvalidRequestIDIORecovery(t *testing.T) { | ||
| data := strings.Repeat(`{"jsonrpc":"2.0","id":true,"method":"ping"}`+"\n", 1000) + `{"jsonrpc":"2.0","id":7,"method":"ping"}` + "\n" | ||
| writer := &invalidIDWriter{} | ||
| conn := newIOConn(rwc{rc: io.NopCloser(strings.NewReader(data)), wc: writer}) | ||
| t.Cleanup(func() { conn.Close() }) | ||
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
| defer cancel() | ||
| message, err := conn.Read(ctx) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if message.(*jsonrpc.Request).ID.Raw() != int64(7) { | ||
| t.Fatal("valid ID lost") | ||
| } | ||
| decoder := json.NewDecoder(bytes.NewReader(writer.Bytes())) | ||
| for range 1000 { | ||
| var envelope struct { | ||
| ID json.RawMessage | ||
| Error struct{ Code int } | ||
| } | ||
| if err := decoder.Decode(&envelope); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if string(envelope.ID) != "null" || envelope.Error.Code != -32600 { | ||
| t.Fatal("invalid frame error") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestIONullIDErrorResponse(t *testing.T) { | ||
| data := `{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"invalid request ID"}}` + "\n" + `{"jsonrpc":"2.0","id":7,"result":{}}` + "\n" | ||
| writer := &invalidIDWriter{} | ||
| conn := newIOConn(rwc{rc: io.NopCloser(strings.NewReader(data)), wc: writer}) | ||
| defer conn.Close() | ||
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
| defer cancel() | ||
| first, err := conn.Read(ctx) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| response, ok := first.(*jsonrpc.Response) | ||
| if !ok || response.ID.IsValid() || response.Error == nil { | ||
| t.Fatalf("first = %#v", first) | ||
| } | ||
| second, err := conn.Read(ctx) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| response, ok = second.(*jsonrpc.Response) | ||
| if !ok || response.ID.Raw() != int64(7) { | ||
| t.Fatalf("second = %#v", second) | ||
| } | ||
| if writer.Len() != 0 { | ||
| t.Fatalf("unexpected reply to error response: %s", writer.String()) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This branch makes unknown-ID errors encode with
"id":null, butDecodeMessagecannot consume that wire form: afterMakeID(nil), the unchangedif !id.IsValid()branch atinternal/jsonrpc2/messages.go:220returnsErrInvalidRequesteven whenmsg.Erroris populated. Consequently the IO reader and the streamable client's non-2xx-body parser treat the new -32600 response as a transport/read failure (potentially tearing down the session) rather than a JSON-RPC error; accept explicit null-ID error responses and cover an encode/decode round trip.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Confirmed and fixed in 3e9420c. DecodeMessage now accepts an explicit null-ID error response while still rejecting missing response IDs, null-ID success responses, and null-ID responses with both result and error. Added encode/decode round-trip coverage, an IO response-followed-by-response regression, and an HTTP client regression proving the session survives the rejection and a subsequent call succeeds. All three regressions failed on the previous head; full tests, race for jsonrpc2/mcp, vet and build now pass. The presence check is confined to the unknown-ID error path; ordinary decoding and unmatched-response correlation are unchanged.