From fdd8b9e851613616a5c1771c94180a6745eece0d Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 18:49:52 -0600 Subject: [PATCH] mcpx: structured upstream-error carriage + local-error origin marker (#2435) Phase 1 of #2434: daemonAsker.Poll prefers reply.Upstream (code/message/data whole), text parse demoted to fallback for older daemons; mintLocalError + marshal-time stamp of data.mcpx.origin=local on locally minted MCP errors, relayed peer errors untouched. --- pkgs/mcpx/internal/cli/serve_ask.go | 10 ++- .../internal/cli/serve_ask_upstream_test.go | 87 ++++++++++++++++++ pkgs/mcpx/internal/mcpserver/capability.go | 2 +- pkgs/mcpx/internal/mcpserver/local_error.go | 88 +++++++++++++++++++ .../internal/mcpserver/local_error_test.go | 75 ++++++++++++++++ pkgs/mcpx/internal/mcpserver/server.go | 15 ++-- 6 files changed, 269 insertions(+), 8 deletions(-) create mode 100644 pkgs/mcpx/internal/cli/serve_ask_upstream_test.go create mode 100644 pkgs/mcpx/internal/mcpserver/local_error.go create mode 100644 pkgs/mcpx/internal/mcpserver/local_error_test.go diff --git a/pkgs/mcpx/internal/cli/serve_ask.go b/pkgs/mcpx/internal/cli/serve_ask.go index 18ed4ca163..96007db004 100644 --- a/pkgs/mcpx/internal/cli/serve_ask.go +++ b/pkgs/mcpx/internal/cli/serve_ask.go @@ -266,7 +266,15 @@ func (d daemonAsker) Poll(ctx context.Context, callID string, wait time.Duration out.Text, out.IsError = reply.Error, true // The protocol layer relays this as the error itself when the // tool is a pass-through upstream's, and ignores it otherwise. - out.Upstream = upstreamError(errors.New(reply.Error)) + // Prefer the daemon's structured carriage of the upstream + // error: it keeps the code, message and data (a -32021's + // requiredCapabilities) intact. The text parse is the fallback + // for a reply from a daemon too old to send the field. + if reply.Upstream != nil { + out.Upstream = &mcpserver.UpstreamError{Code: reply.Upstream.Code, Message: reply.Upstream.Message, Data: reply.Upstream.Data} + } else { + out.Upstream = upstreamError(errors.New(reply.Error)) + } // Classified for the two methods whose failure is a protocol // error; which one applies is the caller's to pick, since the // same upstream -32602 means not-found for a read and a bad diff --git a/pkgs/mcpx/internal/cli/serve_ask_upstream_test.go b/pkgs/mcpx/internal/cli/serve_ask_upstream_test.go new file mode 100644 index 0000000000..e13ec19157 --- /dev/null +++ b/pkgs/mcpx/internal/cli/serve_ask_upstream_test.go @@ -0,0 +1,87 @@ +package cli + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/daemon" + "github.com/developing-today/code/pkgs/mcpx/internal/mcpserver" +) + +// Oracle: the #2434 Phase 1 parity contract — an upstream error that +// reaches the client through the gateway (the ask path) must arrive +// with the same code, message and data as the pass-through error +// itself; a daemon reply without the structured field (the older +// shape) still surfaces through the text fallback. + +func pollAgainst(t *testing.T, reply string) mcpserver.Outcome { + t.Helper() + daemonSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(reply)) + })) + defer daemonSrv.Close() + app := &App{client: NewClientAt(daemon.Paths{}, "", daemonSrv.URL), connected: true} + out, err := daemonAsker{app: app}.Poll(context.Background(), "call-1", time.Millisecond) + if err != nil { + t.Fatal(err) + } + return out +} + +func TestAskPollPrefersStructuredUpstreamError(t *testing.T) { + reply := `{"done":true,"error":"mcp error -32021: missing",` + + `"upstream":{"code":-32021,"message":"missing",` + + `"data":{"requiredCapabilities":{"sampling":{}}}}}` + out := pollAgainst(t, reply) + if !out.IsError { + t.Fatal("a failed upstream call is an error outcome") + } + if out.Upstream == nil || out.Upstream.Code != -32021 || + out.Upstream.Message != "missing" || + string(out.Upstream.Data) != `{"requiredCapabilities":{"sampling":{}}}` { + t.Fatalf("upstream = %+v, want the structured error carried whole", out.Upstream) + } + // The -32021 protocol-error classification uses the same structured + // error, with its data intact and no serve_ask special case. + if out.Err == nil || out.Err.Error() != "missing" { + t.Fatalf("Err = %v, want the structured -32021", out.Err) + } +} + +func TestAskPollStructuredErrorMatchesPassThrough(t *testing.T) { + // The pass-through shape: the same error as a daemon CallErrorBody + // carries it, which relayedFault turns into the client-facing error. + body, _ := json.Marshal(daemon.CallErrorBody{Error: "mcp error -32021", + Upstream: &daemon.UpstreamError{Code: -32021, Message: "missing", + Data: json.RawMessage(`{"requiredCapabilities":{"sampling":{}}}`)}}) + var parsed daemon.CallErrorBody + if err := json.Unmarshal(body, &parsed); err != nil { + t.Fatal(err) + } + reply := `{"done":true,"error":"mcp error -32021: missing",` + + `"upstream":{"code":-32021,"message":"missing",` + + `"data":{"requiredCapabilities":{"sampling":{}}}}}` + out := pollAgainst(t, reply) + if out.Upstream == nil || out.Upstream.Code != parsed.Upstream.Code || + out.Upstream.Message != parsed.Upstream.Message || + string(out.Upstream.Data) != string(parsed.Upstream.Data) { + t.Fatalf("gateway error %+v != pass-through %+v", out.Upstream, parsed.Upstream) + } +} + +func TestAskPollFallsBackToTextForOlderDaemonReply(t *testing.T) { + // No "upstream" field: the pre-Phase-1 reply shape. + reply := `{"done":true,"error":"mcp error -32603: boom"}` + out := pollAgainst(t, reply) + if !out.IsError { + t.Fatal("a failed upstream call is an error outcome") + } + if out.Upstream == nil || out.Upstream.Code != -32603 || + out.Upstream.Message != "boom" || len(out.Upstream.Data) != 0 { + t.Fatalf("upstream = %+v, want the text-parsed fallback", out.Upstream) + } +} diff --git a/pkgs/mcpx/internal/mcpserver/capability.go b/pkgs/mcpx/internal/mcpserver/capability.go index 000380c988..86e84c9490 100644 --- a/pkgs/mcpx/internal/mcpserver/capability.go +++ b/pkgs/mcpx/internal/mcpserver/capability.go @@ -66,5 +66,5 @@ func (e *UpstreamError) relay(id json.RawMessage) *response { if len(e.Data) > 0 { data = e.Data } - return &response{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: e.Code, Message: e.Message, Data: data}} + return &response{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: e.Code, Message: e.Message, Data: data, relayed: true}} } diff --git a/pkgs/mcpx/internal/mcpserver/local_error.go b/pkgs/mcpx/internal/mcpserver/local_error.go new file mode 100644 index 0000000000..61fa7b5da1 --- /dev/null +++ b/pkgs/mcpx/internal/mcpserver/local_error.go @@ -0,0 +1,88 @@ +package mcpserver + +import "encoding/json" + +// Error honesty (#2434 Phase 1): a client must be able to tell an error +// mcpx minted itself from an error mcpx is relaying for an upstream +// peer. Every locally minted error on the MCP surface therefore carries +// {"mcpx": {"origin": "local"}} in its data, merged into any data the +// error already has; a relayed peer error carries no marker, so the +// absence of the marker means the error came from somewhere else. + +// mintLocalError is the minting helper for mcpx's own errors on the MCP +// surface. The origin marker itself is stamped at marshal time (see +// MarshalJSON below), so errors minted as bare rpcError literals are +// stamped too; the helper exists so new mint sites have one obvious +// constructor to reach for. +func mintLocalError(code int, message string, data any) *rpcError { + return &rpcError{Code: code, Message: message, Data: data} +} + +// withLocalOrigin returns data with the local origin marker merged in. +// Existing keys survive, including any other keys under "mcpx"; a +// non-object payload is carried under "data" so the marker still has +// an object to live in. +func withLocalOrigin(data any) any { + mark := func(m map[string]any) map[string]any { + if inner, ok := m["mcpx"].(map[string]any); ok { + merged := make(map[string]any, len(inner)+1) + for k, v := range inner { + merged[k] = v + } + merged["origin"] = "local" + m["mcpx"] = merged + } else { + m["mcpx"] = map[string]any{"origin": "local"} + } + return m + } + switch d := data.(type) { + case nil: + return mark(map[string]any{}) + case map[string]any: + out := make(map[string]any, len(d)+1) + for k, v := range d { + out[k] = v + } + return mark(out) + case json.RawMessage: + if len(d) == 0 { + return mark(map[string]any{}) + } + var v any + if err := json.Unmarshal(d, &v); err != nil { + return data + } + return withLocalOrigin(v) + default: + raw, err := json.Marshal(d) + if err != nil { + return data + } + var v any + if err := json.Unmarshal(raw, &v); err != nil { + return data + } + if _, isObj := v.(map[string]any); isObj { + return withLocalOrigin(v) + } + return mark(map[string]any{"data": v}) + } +} + +// MarshalJSON stamps the local origin marker into a locally minted +// error's data. An error marked relayed -- one that arrived from an +// upstream peer and is answered verbatim, see UpstreamError.relay -- +// is marshalled untouched. +func (e *rpcError) MarshalJSON() ([]byte, error) { + type wire struct { + Code int `json:"code"` + Message string `json:"message"` + Data any `json:"data,omitempty"` + } + data := e.Data + if !e.relayed { + data = withLocalOrigin(data) + } + return json.Marshal(wire{Code: e.Code, Message: e.Message, Data: data}) +} diff --git a/pkgs/mcpx/internal/mcpserver/local_error_test.go b/pkgs/mcpx/internal/mcpserver/local_error_test.go new file mode 100644 index 0000000000..4ed14dffab --- /dev/null +++ b/pkgs/mcpx/internal/mcpserver/local_error_test.go @@ -0,0 +1,75 @@ +package mcpserver + +import ( + "encoding/json" + "strings" + "testing" +) + +// Oracle: the #2434 Phase 1 contract — an error mcpx mints itself is +// recognisable by {"mcpx":{"origin":"local"}} in its data; an error +// relayed from an upstream peer is answered verbatim, marker-free. + +func errorData(t *testing.T, raw []byte) map[string]any { + t.Helper() + var resp struct { + Error struct { + Code int `json:"code"` + Message string `json:"message"` + Data map[string]any `json:"data"` + } `json:"error"` + } + if err := json.Unmarshal(raw, &resp); err != nil { + t.Fatalf("unmarshal %s: %v", raw, err) + } + return resp.Error.Data +} + +func TestLocallyMintedErrorCarriesOriginMarker(t *testing.T) { + resp := &response{JSONRPC: "2.0", ID: json.RawMessage(`1`), + Error: mintLocalError(codeInternal, "boom", nil)} + raw, err := json.Marshal(resp) + if err != nil { + t.Fatal(err) + } + data := errorData(t, raw) + mcpx, ok := data["mcpx"].(map[string]any) + if !ok || mcpx["origin"] != "local" { + t.Fatalf("data = %v, want mcpx.origin=local (%s)", data, raw) + } +} + +func TestLocalOriginMarkerMergesIntoExistingData(t *testing.T) { + resp := &response{JSONRPC: "2.0", ID: json.RawMessage(`1`), + Error: &rpcError{Code: codeUnsupportedVersion, Message: "nope", + Data: map[string]any{"supported": []string{"2026-07-28"}, + "mcpx": map[string]any{"surface": "gateway"}}}} + raw, err := json.Marshal(resp) + if err != nil { + t.Fatal(err) + } + data := errorData(t, raw) + if _, ok := data["supported"]; !ok { + t.Fatalf("existing data lost: %v", data) + } + mcpx, ok := data["mcpx"].(map[string]any) + if !ok || mcpx["origin"] != "local" || mcpx["surface"] != "gateway" { + t.Fatalf("mcpx data = %v, want origin=local merged with surface=gateway", data["mcpx"]) + } +} + +func TestRelayedUpstreamErrorCarriesNoOriginMarker(t *testing.T) { + up := &UpstreamError{Code: -32021, Message: "missing", + Data: json.RawMessage(`{"requiredCapabilities":{"sampling":{}}}`)} + raw, err := json.Marshal(up.relay(json.RawMessage(`7`))) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), `"mcpx"`) { + t.Fatalf("relayed error gained a local marker: %s", raw) + } + data := errorData(t, raw) + if _, ok := data["requiredCapabilities"]; !ok { + t.Fatalf("relayed data lost: %s", raw) + } +} diff --git a/pkgs/mcpx/internal/mcpserver/server.go b/pkgs/mcpx/internal/mcpserver/server.go index 91c1a0526f..1f4dde066b 100644 --- a/pkgs/mcpx/internal/mcpserver/server.go +++ b/pkgs/mcpx/internal/mcpserver/server.go @@ -443,6 +443,11 @@ type rpcError struct { Code int `json:"code"` Message string `json:"message"` Data any `json:"data,omitempty"` + // relayed marks an error that arrived from an upstream peer and is + // being relayed verbatim; locally minted errors leave it false and + // are stamped with the local origin marker when marshalled (see + // local_error.go). + relayed bool } // Error codes from the JSON-RPC specification. Using the standard ones means @@ -484,14 +489,12 @@ var ErrInvalidParams = errors.New("invalid params") // the modern era reaches here -- a legacy initialize with an unknown version // is answered with a version, not refused (see negotiate). func unsupportedVersion(id json.RawMessage, params json.RawMessage) *response { - return &response{JSONRPC: "2.0", ID: id, Error: &rpcError{ - Code: codeUnsupportedVersion, - Message: "Unsupported protocol version", - Data: map[string]any{ + return &response{JSONRPC: "2.0", ID: id, Error: mintLocalError( + codeUnsupportedVersion, "Unsupported protocol version", + map[string]any{ "supported": Supported, "requested": requestVersion(params), - }, - }} + })} } // Tool is one exposed function.