Repository navigation
mcp: return errors with omitted IDs 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
4
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.
+232
−1
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
4779e9b
mcp: return null-ID errors for rejected request identities
skosovsky 3e9420c
jsonrpc2: accept explicit null-ID error responses
skosovsky 10b0d70
test: remove redundant phase comments per review
skosovsky 6b17534
jsonrpc2: omit unknown IDs in MCP error responses
skosovsky 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,86 @@ | ||
| // 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 fields["id"] != nil || fields["error"] == nil || fields["result"] != nil { | ||
| t.Fatalf("invalid error response: %s", wire) | ||
| } | ||
| } | ||
|
|
||
| func TestUnknownIDErrorResponseRoundTrip(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","id":null,"error":{"code":-32600,"message":"bad"}}`, | ||
| `{"jsonrpc":"2.0","result":{}}`, | ||
| `{"jsonrpc":"2.0","error":null}`, | ||
| `{"jsonrpc":"2.0","result":{},"error":{"code":-32600,"message":"bad"}}`, | ||
| `{"jsonrpc":"2.0","result":null,"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","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 || envelope.ID != nil || 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 envelope.ID != nil || envelope.Error.Code != -32600 { | ||
| t.Fatal("invalid frame error") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestIOUnknownIDErrorResponse(t *testing.T) { | ||
| data := `{"jsonrpc":"2.0","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.
I would not modify anything here.
MCP Spec & Schema (JSONRPCErrorResponse): Unlike base JSON-RPC 2.0, the MCP specification explicitly forbids null IDs (RequestId is string | integer) and specifies id?: RequestId on JSONRPCErrorResponse (omitting id when it cannot be read, rather than emitting "id": null, which fails MCP JSON Schema validation).
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.
You're right — I conflated base JSON-RPC with MCP. Fixed in 6b17534.
Unknown-ID errors now omit
id. The decoder accepts an error-only response with noid, while still rejecting explicitid: null, success responses without an ID, and mixedresult/errorresponses without an ID. Simply reverting the decoder would have broken round-tripping of the corrected response.I updated the wire expectations and retained the HTTP session-continuation and IO recovery regressions. Verified against the 2025-11-25 and 2026-07-28 JSON schemas. Local checks passed on Go 1.27.1: focused regressions,
go test ./...,go test -race ./...,go vet ./...,go build ./..., gofmt, andgit diff --check.