Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(mcp): preserve numeric request IDs without rounding (#1126)

Rudy Mizrahi Celekli6962c4d6bc65
diff --git a/cli/beacon/internal/mcpserver/jsonrpc_test.go b/cli/beacon/internal/mcpserver/jsonrpc_test.go
new file mode 100644
index 00000000..baa3d6e5
--- /dev/null
+++ b/cli/beacon/internal/mcpserver/jsonrpc_test.go
@@ -0,0 +1,99 @@
+package mcpserver
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// The JSON-RPC 2.0 envelope over both transports: ids come back byte for byte, unreadable ids
+// come back as null, notifications get nothing, and each failure carries its spec error code.
+func TestJSONRPCEnvelope(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ request string
+ // wantID is the response's raw id; "" means no response at all.
+ wantID string
+ wantCode int
+ // wantResult, when set, is the exact raw result.
+ wantResult string
+ }{
+ {name: "id above 2^53", request: `{"jsonrpc":"2.0","id":9007199254740993,"method":"initialize"}`, wantID: `9007199254740993`},
+ {name: "max int64 id", request: `{"jsonrpc":"2.0","id":9223372036854775807,"method":"initialize"}`, wantID: `9223372036854775807`},
+ {name: "exponent id", request: `{"jsonrpc":"2.0","id":1e3,"method":"initialize"}`, wantID: `1e3`},
+ {name: "fractional id", request: `{"jsonrpc":"2.0","id":1.50,"method":"initialize"}`, wantID: `1.50`},
+ {name: "negative id", request: `{"jsonrpc":"2.0","id":-1,"method":"initialize"}`, wantID: `-1`},
+ {name: "string id", request: `{"jsonrpc":"2.0","id":"client-session-123","method":"initialize"}`, wantID: `"client-session-123"`},
+ {name: "null id", request: `{"jsonrpc":"2.0","id":null,"method":"initialize"}`, wantID: `null`},
+ {name: "ping", request: `{"jsonrpc":"2.0","id":7,"method":"ping"}`, wantID: `7`, wantResult: `{}`},
+ {name: "notification", request: `{"jsonrpc":"2.0","method":"notifications/initialized"}`},
+ {name: "unknown method", request: `{"jsonrpc":"2.0","id":8,"method":"no/such/method"}`, wantID: `8`, wantCode: -32601},
+ {name: "parse error", request: `{"jsonrpc":"2.0","id":9,"method":`, wantID: `null`, wantCode: -32700},
+ {name: "object id", request: `{"jsonrpc":"2.0","id":{"a":1},"method":"ping"}`, wantID: `null`, wantCode: -32600},
+ {name: "array id", request: `{"jsonrpc":"2.0","id":[1],"method":"ping"}`, wantID: `null`, wantCode: -32600},
+ {name: "boolean id", request: `{"jsonrpc":"2.0","id":true,"method":"ping"}`, wantID: `null`, wantCode: -32600},
+ } {
+ t.Run(tc.name+"/stdio", func(t *testing.T) {
+ var output bytes.Buffer
+ if err := New(Options{}).ServeStdio(context.Background(), strings.NewReader(tc.request+"\n"), &output); err != nil {
+ t.Fatal(err)
+ }
+ assertEnvelope(t, output.Bytes(), tc.wantID, tc.wantCode, tc.wantResult)
+ })
+ t.Run(tc.name+"/http", func(t *testing.T) {
+ server := httptest.NewServer(New(Options{}).HTTPHandler())
+ defer server.Close()
+ response, err := http.Post(server.URL+"/mcp", "application/json", strings.NewReader(tc.request))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ body, err := io.ReadAll(response.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := http.StatusOK
+ if tc.wantID == "" {
+ want = http.StatusAccepted
+ }
+ if response.StatusCode != want {
+ t.Fatalf("HTTP %d, want %d: %s", response.StatusCode, want, body)
+ }
+ assertEnvelope(t, body, tc.wantID, tc.wantCode, tc.wantResult)
+ })
+ }
+}
+
+func assertEnvelope(t *testing.T, body []byte, wantID string, wantCode int, wantResult string) {
+ t.Helper()
+ if wantID == "" {
+ if len(bytes.TrimSpace(body)) != 0 {
+ t.Fatalf("notification answered with %s", body)
+ }
+ return
+ }
+ var response struct {
+ ID json.RawMessage `json:"id"`
+ Result json.RawMessage `json:"result"`
+ Error *rpcError `json:"error"`
+ }
+ if err := json.Unmarshal(body, &response); err != nil {
+ t.Fatalf("%v: %s", err, body)
+ }
+ if string(response.ID) != wantID {
+ t.Fatalf("id = %q, want %q: %s", string(response.ID), wantID, body)
+ }
+ switch {
+ case wantCode == 0 && (response.Error != nil || len(response.Result) == 0):
+ t.Fatalf("want a result: %s", body)
+ case wantCode != 0 && (response.Error == nil || response.Error.Code != wantCode || len(response.Result) != 0):
+ t.Fatalf("want error %d and no result: %s", wantCode, body)
+ case wantResult != "" && string(response.Result) != wantResult:
+ t.Fatalf("result = %s, want %s", response.Result, wantResult)
+ }
+}
diff --git a/cli/beacon/internal/mcpserver/server.go b/cli/beacon/internal/mcpserver/server.go
index d4a82128..81c8012f 100644
--- a/cli/beacon/internal/mcpserver/server.go
+++ b/cli/beacon/internal/mcpserver/server.go
@@ -1,7 +1,7 @@
// Package mcpserver implements the small local MCP server surface Beacon needs
// for activity querying. It intentionally supports the server methods exercised
-// by current desktop clients and tests: initialize, tools/list, tools/call, and
-// notifications without responses.
+// by current desktop clients and tests: initialize, ping, tools/list, tools/call,
+// and notifications without responses.
package mcpserver
import (
@@ -51,12 +51,19 @@ type rpcRequest struct {
}
type rpcResponse struct {
- JSONRPC string `json:"jsonrpc"`
- ID interface{} `json:"id,omitempty"`
- Result interface{} `json:"result,omitempty"`
- Error *rpcError `json:"error,omitempty"`
+ JSONRPC string `json:"jsonrpc"`
+ // ID is the request's id echoed byte for byte; decoding it would round large numbers.
+ ID json.RawMessage `json:"id"`
+ Result interface{} `json:"result,omitempty"`
+ Error *rpcError `json:"error,omitempty"`
}
+// nullID answers a request whose id could not be read, as JSON-RPC 2.0 section 5 requires.
+var nullID = json.RawMessage("null")
+
+// errMethodNotFound marks a method this server does not implement (JSON-RPC -32601).
+var errMethodNotFound = errors.New("method not found")
+
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
@@ -188,20 +195,23 @@ func (s *Server) HTTPHandler() http.Handler {
func (s *Server) handle(ctx context.Context, data []byte) (rpcResponse, bool) {
var request rpcRequest
if err := json.Unmarshal(data, &request); err != nil {
- return errorResponse(nil, -32700, "parse error"), true
+ return errorResponse(nullID, -32700, "parse error"), true
}
- id, hasID := requestID(request.ID)
- if !hasID && strings.HasPrefix(request.Method, "notifications/") {
+ // A request without an id member is a notification, which gets no response.
+ if len(request.ID) == 0 {
return rpcResponse{}, false
}
- if !hasID {
- return rpcResponse{}, false
+ if !validID(request.ID) {
+ return errorResponse(nullID, -32600, "invalid request: id must be a string, number, or null"), true
}
result, err := s.dispatch(ctx, request)
+ if errors.Is(err, errMethodNotFound) {
+ return errorResponse(request.ID, -32601, err.Error()), true
+ }
if err != nil {
- return errorResponse(id, -32000, err.Error()), true
+ return errorResponse(request.ID, -32000, err.Error()), true
}
- return rpcResponse{JSONRPC: "2.0", ID: id, Result: result}, true
+ return rpcResponse{JSONRPC: "2.0", ID: request.ID, Result: result}, true
}
func (s *Server) dispatch(ctx context.Context, request rpcRequest) (interface{}, error) {
@@ -217,6 +227,8 @@ func (s *Server) dispatch(ctx context.Context, request rpcRequest) (interface{},
"version": version.GetVersion(),
},
}, nil
+ case "ping":
+ return map[string]interface{}{}, nil
case "tools/list":
return map[string]interface{}{"tools": s.listTools()}, nil
case "tools/call":
@@ -228,7 +240,7 @@ func (s *Server) dispatch(ctx context.Context, request rpcRequest) (interface{},
}
return s.callTool(ctx, params)
default:
- return nil, fmt.Errorf("unsupported MCP method %q", request.Method)
+ return nil, fmt.Errorf("%w: %q", errMethodNotFound, request.Method)
}
}
@@ -508,18 +520,14 @@ func objectSchema(properties map[string]interface{}, required []string, descript
return schema
}
-func requestID(raw json.RawMessage) (interface{}, bool) {
- if len(raw) == 0 {
- return nil, false
- }
- var id interface{}
- if err := json.Unmarshal(raw, &id); err != nil {
- return nil, false
- }
- return id, true
+// validID reports whether a JSON value already known to be well formed is a string, number, or
+// null: the id types JSON-RPC 2.0 allows.
+func validID(id json.RawMessage) bool {
+ c := id[0]
+ return c == '"' || c == 'n' || c == '-' || (c >= '0' && c <= '9')
}
-func errorResponse(id interface{}, code int, message string) rpcResponse {
+func errorResponse(id json.RawMessage, code int, message string) rpcResponse {
return rpcResponse{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: code, Message: message}}
}