diff --git a/pkgs/mcpx/internal/cli/serve_ask.go b/pkgs/mcpx/internal/cli/serve_ask.go index 18ed4ca163..59d5e5a5a4 100644 --- a/pkgs/mcpx/internal/cli/serve_ask.go +++ b/pkgs/mcpx/internal/cli/serve_ask.go @@ -266,7 +266,16 @@ 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)) + // The structured carriage is the error as it arrived -- code, + // message and data. The text heuristic below survives only for + // replies without it: it recovers a code and a message from the + // rendered string, and data (a -32021's requiredCapabilities, + // say) is unrecoverable from text (#2435). + 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..333e1b448b --- /dev/null +++ b/pkgs/mcpx/internal/cli/serve_ask_upstream_test.go @@ -0,0 +1,92 @@ +package cli + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/daemon" + "github.com/developing-today/code/pkgs/mcpx/internal/mcpserver" +) + +// pollWith serves one fixed ask-poll reply from a fake daemon and +// returns the Outcome Poll makes of it. +func pollWith(t *testing.T, reply string) mcpserver.Outcome { + t.Helper() + daemonSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v1/ask/") { + _, _ = w.Write([]byte(reply)) + return + } + http.Error(w, `{"error":"unexpected"}`, http.StatusNotFound) + })) + 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.Fatalf("Poll: %v", err) + } + return out +} + +// #2435 (a): when the daemon's reply carries the structured upstream +// error, the ask path relays it verbatim -- code, message and data -- +// instead of reconstructing what it can from the rendered text (the +// heuristic cannot recover data at all). +func TestAskPollPrefersTheStructuredUpstreamError(t *testing.T) { + out := pollWith(t, `{"done":true,`+ + `"error":"mcp error -32602: the text rendering of the failure",`+ + `"upstream":{"code":-32602,"message":"structured message","data":{"hint":"verbatim"}}}`) + if !out.IsError { + t.Fatalf("the failed call is not a tool error: %+v", out) + } + if out.Upstream == nil { + t.Fatal("no upstream error on the outcome") + } + if out.Upstream.Code != -32602 || out.Upstream.Message != "structured message" { + t.Fatalf("upstream not verbatim: %+v", out.Upstream) + } + if string(out.Upstream.Data) != `{"hint":"verbatim"}` { + t.Fatalf("upstream data lost or altered: %s", out.Upstream.Data) + } +} + +// #2435 (a): the -32021 classification keeps the structured data -- +// requiredCapabilities is what the client acts on. +func TestAskPollMissingCapabilityKeepsItsData(t *testing.T) { + out := pollWith(t, `{"done":true,"error":"call failed",`+ + `"upstream":{"code":-32021,"message":"MissingRequiredClientCapabilityError",`+ + `"data":{"requiredCapabilities":{"sampling":{}}}}}`) + up, ok := out.Err.(*mcpserver.UpstreamError) + if !ok { + t.Fatalf("Err = %T, want the structured UpstreamError", out.Err) + } + var data struct { + Required map[string]any `json:"requiredCapabilities"` + } + if err := json.Unmarshal(up.Data, &data); err != nil || data.Required == nil { + t.Fatalf("-32021 data lost: %s (%v)", up.Data, err) + } + if out.Upstream == nil || string(out.Upstream.Data) != string(up.Data) { + t.Fatalf("outcome upstream not verbatim: %+v", out.Upstream) + } +} + +// #2435 (a): a reply without the structured field falls back to the +// text heuristic, exactly as before. +func TestAskPollFallsBackToTheTextHeuristic(t *testing.T) { + out := pollWith(t, `{"done":true,"error":"mcp error -32602: no such tool"}`) + if out.Upstream == nil { + t.Fatal("no upstream error on the outcome") + } + if out.Upstream.Code != -32602 || out.Upstream.Message != "no such tool" { + t.Fatalf("heuristic reconstruction changed: %+v", out.Upstream) + } + if len(out.Upstream.Data) != 0 { + t.Fatalf("the heuristic must not invent data: %s", out.Upstream.Data) + } +} 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/origin_marker_codex_test.go b/pkgs/mcpx/internal/mcpserver/origin_marker_codex_test.go new file mode 100644 index 0000000000..8205a4a450 --- /dev/null +++ b/pkgs/mcpx/internal/mcpserver/origin_marker_codex_test.go @@ -0,0 +1,174 @@ +package mcpserver_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/mcpserver" +) + +// Codex review on PR #9038 (issue #2435), finding 1: relay provenance +// must survive task execution. A peer error that reaches the client +// through a task -- eagerly, through tasks/result, or through an +// asked task -- is still a peer error: code, message and data exactly +// as the upstream sent them, and never stamped with mcpx's +// local-origin marker. Oracle: issue #2435's acceptance ("no relayed +// peer error carries the marker"). + +func relayedDataUnchanged(t *testing.T, m map[string]any) { + t.Helper() + e, _ := m["error"].(map[string]any) + if e == nil { + t.Fatalf("want an error response, got %v", m) + } + data, _ := e["data"].(map[string]any) + if len(data) != 1 || data["peer"] != "data" { + t.Fatalf("relayed error's data was altered or marked local: %v", e) + } +} + +func TestARelayedPeerErrorThroughAnEagerTaskKeepsItsData(t *testing.T) { + up := &mcpserver.UpstreamError{Code: -32603, Message: "as designed", + Data: json.RawMessage(`{"peer":"data"}`)} + u := &taskUpstream{fakeBackend: newBackend(), callErr: up, + tools: map[string][]mcpserver.Tool{"tasks": {supportTool("relay_job", "optional")}}} + s := taskServer(u, "tasks") + s.Timing.TaskEager = 5 * time.Second + + m := handle(t, s, "tools/call", callTool(extCaps, "relay_job")) + if errCode(m) != -32603 { + t.Fatalf("eager task: want the upstream's -32603, got %v", m) + } + relayedDataUnchanged(t, m) +} + +func TestARelayedPeerErrorThroughTasksResultKeepsItsData(t *testing.T) { + up := &mcpserver.UpstreamError{Code: -32603, Message: "as designed", + Data: json.RawMessage(`{"peer":"data"}`)} + u := &taskUpstream{fakeBackend: newBackend(), callErr: up, delay: 200 * time.Millisecond, + tools: map[string][]mcpserver.Tool{"tasks": {supportTool("relay_job", "optional")}}} + s := taskServer(u, "tasks") + s.Timing.TaskEager = 50 * time.Millisecond + + r := resultOf(t, handle(t, s, "tools/call", callTool(extCaps, "relay_job"))) + id, _ := r["taskId"].(string) + if id == "" { + t.Fatalf("want a task, got %v", r) + } + waitTask(t, s, id, terminal) + + m := handle(t, s, "tasks/result", map[string]any{"taskId": id}) + if errCode(m) != -32603 { + t.Fatalf("tasks/result: want the upstream's -32603, got %v", m) + } + relayedDataUnchanged(t, m) +} + +func TestARelayedPeerErrorThroughAnAskedTaskKeepsItsData(t *testing.T) { + a := &timedAsker{workAfter: 300 * time.Millisecond, + upstream: &mcpserver.UpstreamError{Code: -32603, Message: "as designed", + Data: json.RawMessage(`{"peer":"data"}`)}} + s := askingServer(a, "protocol_error_job") + r := resultOf(t, handle(t, s, "tools/call", callTool(extAskCaps, "protocol_error_job"))) + id, _ := r["taskId"].(string) + if id == "" { + t.Fatalf("want a task, got %v", r) + } + waitTask(t, s, id, terminal) + + m := handle(t, s, "tasks/result", map[string]any{"taskId": id}) + if errCode(m) != -32603 { + t.Fatalf("asked task tasks/result: want the upstream's -32603, got %v", m) + } + relayedDataUnchanged(t, m) +} + +// Codex review on PR #9038 (issue #2435), finding 2: the transport's +// own pre-dispatch error responses bypass HandleOn, so the marker +// must be stamped where they are minted. This table is the class +// guard: every pre-dispatch error family the HTTP transport mints +// carries the local-origin marker. Oracle: issue #2435's acceptance +// ("every error mcpx mints itself on the MCP surface"). + +func serveRaw(s *mcpserver.Server, method string, headers map[string]string, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, "/mcp", strings.NewReader(body)) + for k, v := range headers { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + s.ServeHTTP(w, r) + return w +} + +// firstErrorData decodes the first error's data from a response body +// that is either one response object or a batch reply array. +func firstErrorData(t *testing.T, body []byte) map[string]any { + t.Helper() + var raw json.RawMessage = body + var arr []json.RawMessage + if err := json.Unmarshal(body, &arr); err == nil && len(arr) > 0 { + raw = arr[0] + } + var resp struct { + Error *struct { + Data map[string]any `json:"data"` + } `json:"error"` + } + if err := json.Unmarshal(raw, &resp); err != nil || resp.Error == nil { + t.Fatalf("response carries no error: %s", body) + } + return resp.Error.Data +} + +func TestTransportLocalErrorsCarryTheLocalOriginMarker(t *testing.T) { + plain := func() *mcpserver.Server { return mcpserver.New(newBackend(), "mcpx", "test") } + origined := func() *mcpserver.Server { + s := plain() + s.Origins = mcpserver.OriginPolicy{Hosts: []string{"localhost", "127.0.0.1", "::1"}, + Origins: []string{"https://app.example.com"}} + return s + } + oneCall := `[{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}]` + cases := []struct { + name string + server func() *mcpserver.Server + method string + headers map[string]string + body string + }{ + {"rejected Origin", origined, http.MethodPost, + map[string]string{"Origin": "https://evil.example"}, + string(frame(1, "tools/list", nil))}, + {"empty batch", plain, http.MethodPost, nil, `[]`}, + {"modern batch refused", plain, http.MethodPost, + map[string]string{"MCP-Protocol-Version": "2026-07-28"}, oneCall}, + {"batch refused for 2025-06-18", plain, http.MethodPost, + map[string]string{"MCP-Protocol-Version": "2025-06-18"}, oneCall}, + {"batch with an unknown session", plain, http.MethodPost, + map[string]string{"Mcp-Session-Id": "no-such"}, oneCall}, + {"batch element framing", plain, http.MethodPost, nil, `[123]`}, + {"batch element is initialize", plain, http.MethodPost, nil, + `[{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}]`}, + {"DELETE without a session", plain, http.MethodDelete, nil, ""}, + {"DELETE with an unknown session", plain, http.MethodDelete, + map[string]string{"Mcp-Session-Id": "no-such"}, ""}, + {"GET without a session", plain, http.MethodGet, nil, ""}, + {"GET with an unknown session", plain, http.MethodGet, + map[string]string{"Mcp-Session-Id": "no-such"}, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + w := serveRaw(tc.server(), tc.method, tc.headers, tc.body) + data := firstErrorData(t, w.Body.Bytes()) + mcpx, ok := data["mcpx"].(map[string]any) + if !ok || mcpx["origin"] != "local" { + t.Fatalf("%s: transport-local error lacks the origin marker: status %d, data = %v (%s)", + tc.name, w.Code, data, w.Body.String()) + } + }) + } +} diff --git a/pkgs/mcpx/internal/mcpserver/origin_marker_test.go b/pkgs/mcpx/internal/mcpserver/origin_marker_test.go new file mode 100644 index 0000000000..7ea0a96bdf --- /dev/null +++ b/pkgs/mcpx/internal/mcpserver/origin_marker_test.go @@ -0,0 +1,108 @@ +package mcpserver_test + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/mcpserver" +) + +// #2435: an error mcpx mints itself carries the local-origin marker, +// merged into whatever data the error already has. + +// errReadBackend fails every resource read, so the answer is mcpx's +// own notFound, whose data is the URI. +type errReadBackend struct { + *fakeBackend +} + +func (errReadBackend) ReadResource(context.Context, string) ([]mcpserver.ResourceContents, error) { + return nil, fmt.Errorf("%w: no such resource", mcpserver.ErrResourceNotFound) +} + +func TestALocallyMintedErrorCarriesTheLocalOriginMarker(t *testing.T) { + s := mcpserver.New(&errReadBackend{fakeBackend: newBackend()}, "mcpx", "test") + w := post(s, frame(7, "resources/read", + modernWith(`{}`, map[string]any{"uri": "file:///no-such-resource"})), + modernHeaders("resources/read", "file:///no-such-resource")) + 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(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("response is not JSON: %v (%s)", err, w.Body.String()) + } + if resp.Error == nil { + t.Fatalf("expected an error response, got %s", w.Body.String()) + } + if resp.Error.Data["uri"] != "file:///no-such-resource" { + t.Fatalf("the error's own data was lost: %v", resp.Error.Data) + } + mcpx, ok := resp.Error.Data["mcpx"].(map[string]any) + if !ok || mcpx["origin"] != "local" { + t.Fatalf("locally minted error lacks the origin marker: data = %v", resp.Error.Data) + } +} + +// The marker is also stamped when the error carries no data at all: a +// prompts/get the backend refuses with ErrInvalidParams is classified +// and answered by mcpx itself. +func TestALocallyMintedErrorWithoutDataIsMarkedToo(t *testing.T) { + s := mcpserver.New(newBackend(), "mcpx", "test") + w := post(s, frame(8, "prompts/get", + modernWith(`{}`, map[string]any{"name": "nosuch"})), + modernHeaders("prompts/get", "nosuch")) + var resp struct { + Error *struct { + Code int `json:"code"` + Data map[string]any `json:"data"` + } `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("response is not JSON: %v (%s)", err, w.Body.String()) + } + if resp.Error == nil { + t.Fatalf("expected an error response, got %s", w.Body.String()) + } + mcpx, ok := resp.Error.Data["mcpx"].(map[string]any) + if !ok || mcpx["origin"] != "local" { + t.Fatalf("locally minted error lacks the origin marker: data = %v", resp.Error.Data) + } +} + +// #2435: a peer's error is relayed untouched -- code, message and data +// exactly as the upstream sent them, and never marked local. +func TestARelayedPeerErrorIsNeverMarkedLocal(t *testing.T) { + b := newRelay() + b.err = &mcpserver.UpstreamError{Code: -32602, Message: "no tool named \"greet\"", + Data: json.RawMessage(`{"peer":"data"}`)} + s := mcpserver.New(b, "mcpx", "test") + s.Passthrough = []string{"up"} + + w := post(s, frame(9, "tools/call", modernWith(`{"elicitation":{}}`, + map[string]any{"name": "greet", "arguments": map[string]any{}})), modernHeaders("tools/call", "greet")) + var resp struct { + Error *struct { + Code int `json:"code"` + Message string `json:"message"` + Data json.RawMessage `json:"data"` + } `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("response is not JSON: %v (%s)", err, w.Body.String()) + } + if resp.Error == nil { + t.Fatalf("expected the relayed error, got %s", w.Body.String()) + } + if resp.Error.Code != -32602 || resp.Error.Message != `no tool named "greet"` { + t.Fatalf("relayed error altered: %+v", resp.Error) + } + if string(resp.Error.Data) != `{"peer":"data"}` { + t.Fatalf("relayed data altered or marked: %s", resp.Error.Data) + } +} diff --git a/pkgs/mcpx/internal/mcpserver/server.go b/pkgs/mcpx/internal/mcpserver/server.go index 461ad2c6a3..ea1b96eda1 100644 --- a/pkgs/mcpx/internal/mcpserver/server.go +++ b/pkgs/mcpx/internal/mcpserver/server.go @@ -443,6 +443,42 @@ type rpcError struct { Code int `json:"code"` Message string `json:"message"` Data any `json:"data,omitempty"` + + // relayed marks an error that is a peer's, carried verbatim + // (UpstreamError.relay). It is never serialized; it exists so the + // local-origin marker below is stamped only on errors mcpx minted + // itself (#2435). + relayed bool +} + +// withLocalOrigin stamps e's data with the local-origin marker, +// "mcpx": {"origin": "local"}, merged into whatever data the error +// already carries (#2435). It answers the client's first diagnostic +// question -- did mcpx mint this error, or is it relaying a peer's? -- +// for every error mcpx mints itself on the MCP surface: its name +// checks, its internal failures, its policy refusals. A peer's error +// is relayed untouched and never marked (see relayed above). Data +// that is not a JSON object has nowhere to merge a key into and is +// left as it is; every current local mint carries nil or object data. +func withLocalOrigin(e *rpcError) *rpcError { + marker := map[string]any{"origin": "local"} + switch d := e.Data.(type) { + case nil: + e.Data = map[string]any{"mcpx": marker} + case map[string]any: + if inner, ok := d["mcpx"].(map[string]any); ok { + inner["origin"] = "local" + } else if _, taken := d["mcpx"]; !taken { + d["mcpx"] = marker + } + case json.RawMessage: + var m map[string]any + if len(d) > 0 && json.Unmarshal(d, &m) == nil && m != nil { + e.Data = m + return withLocalOrigin(e) + } + } + return e } // Error codes from the JSON-RPC specification. Using the standard ones means @@ -749,6 +785,12 @@ func (s *Server) HandleOn(ctx context.Context, c *Conn, req request) *response { ctx = withIdentity(ctx, c.identityFor(req.Params)) resp := s.handle(ctx, c, req) if resp == nil || resp.Error != nil { + if resp != nil && resp.Error != nil && !resp.Error.relayed { + // An error mcpx minted itself, anywhere in the dispatch + // below: stamp its local origin (#2435). A relayed peer + // error keeps the peer's data exactly as it arrived. + resp.Error = withLocalOrigin(resp.Error) + } return resp } if peer.Modern { @@ -1871,12 +1913,12 @@ func (s *Server) ServeStdio(ctx context.Context, in io.Reader, out io.Writer) er var req request if err := json.Unmarshal([]byte(line), &req); err != nil { _ = enc.Encode(response{JSONRPC: "2.0", - Error: &rpcError{Code: codeParse, Message: err.Error()}}) + Error: withLocalOrigin(&rpcError{Code: codeParse, Message: err.Error()})}) continue } if req.JSONRPC != "" && req.JSONRPC != "2.0" { _ = enc.Encode(response{JSONRPC: "2.0", ID: req.ID, - Error: &rpcError{Code: codeInvalidRequest, Message: "unsupported jsonrpc version"}}) + Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, Message: "unsupported jsonrpc version"})}) continue } if len(req.ID) == 0 || req.Method == "initialize" { @@ -1936,11 +1978,11 @@ func (s *Server) ServeStdio(ctx context.Context, in io.Reader, out io.Writer) er func (s *Server) stdioBatch(ctx context.Context, c *Conn, line []byte) any { var elems []json.RawMessage if err := json.Unmarshal(line, &elems); err != nil { - return response{JSONRPC: "2.0", Error: &rpcError{Code: codeParse, Message: err.Error()}} + return response{JSONRPC: "2.0", Error: withLocalOrigin(&rpcError{Code: codeParse, Message: err.Error()})} } if len(elems) == 0 { - return response{JSONRPC: "2.0", Error: &rpcError{Code: codeInvalidRequest, - Message: "an empty batch is not a request"}} + return response{JSONRPC: "2.0", Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, + Message: "an empty batch is not a request"})} } v := c.Version() if v == "" { @@ -2019,8 +2061,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // surface as it has always been. r = r.WithContext(withCodemode(r.Context(), r.URL.Query().Get("codemode") == "false")) if !s.originAllowed(r.Header.Get("Origin")) { - writeJSON(w, http.StatusForbidden, response{JSONRPC: "2.0", Error: &rpcError{ - Code: codeInvalidRequest, Message: "Origin " + r.Header.Get("Origin") + " is not allowed"}}) + writeJSON(w, http.StatusForbidden, response{JSONRPC: "2.0", Error: withLocalOrigin(&rpcError{ + Code: codeInvalidRequest, Message: "Origin " + r.Header.Get("Origin") + " is not allowed"})}) return } switch r.Method { @@ -2053,14 +2095,14 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // goroutine with its stream still open. if id, result, rerr, ok := replyOf(body); ok { if modernHeaderVersion(hv) { - writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", Error: &rpcError{ - Code: codeInvalidRequest, Message: "2026-07-28 clients send no responses"}}) + writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", Error: withLocalOrigin(&rpcError{ + Code: codeInvalidRequest, Message: "2026-07-28 clients send no responses"})}) return } c, found := s.session(r.Header.Get(sessionHeader)) if !found || !c.deliver(id, result, rerr) { - writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", Error: &rpcError{ - Code: codeInvalidRequest, Message: "no request is waiting for that id on this session"}}) + writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", Error: withLocalOrigin(&rpcError{ + Code: codeInvalidRequest, Message: "no request is waiting for that id on this session"})}) return } w.WriteHeader(http.StatusAccepted) @@ -2070,7 +2112,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { var req request if err := json.Unmarshal(body, &req); err != nil { writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", - Error: &rpcError{Code: codeParse, Message: err.Error()}}) + Error: withLocalOrigin(&rpcError{Code: codeParse, Message: err.Error()})}) return } if requestVersion(req.Params) != "" || modernHeaderVersion(hv) { @@ -2083,10 +2125,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // serveModern answers one 2026-07-28 POST. func (s *Server) serveModern(w http.ResponseWriter, r *http.Request, req request) { if bad := checkModernHeaders(r, req); bad != nil { + bad.Error = withLocalOrigin(bad.Error) writeJSON(w, http.StatusBadRequest, bad) return } if bad := s.checkParamHeaders(r, req); bad != nil { + bad.Error = withLocalOrigin(bad.Error) writeJSON(w, http.StatusBadRequest, bad) return } @@ -2114,6 +2158,7 @@ func (s *Server) serveLegacy(w http.ResponseWriter, r *http.Request, req request if hv != "" && (!supports(hv) || Modern(hv)) { bad := unsupportedVersion(req.ID, nil) bad.Error.Data = map[string]any{"supported": LegacySupported(), "requested": hv} + bad.Error = withLocalOrigin(bad.Error) writeJSON(w, http.StatusBadRequest, bad) return } @@ -2122,8 +2167,8 @@ func (s *Server) serveLegacy(w http.ResponseWriter, r *http.Request, req request // Unknown, expired or DELETEd. The client MUST then start a new // session with an initialize that carries no session id. writeJSON(w, http.StatusNotFound, response{JSONRPC: "2.0", ID: req.ID, - Error: &rpcError{Code: codeInvalidRequest, - Message: "no such session; send initialize without " + sessionHeader + " to start one"}}) + Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, + Message: "no such session; send initialize without " + sessionHeader + " to start one"})}) return } } @@ -2200,12 +2245,12 @@ func (s *Server) serveBatch(w http.ResponseWriter, r *http.Request, body []byte, var elems []json.RawMessage if err := json.Unmarshal(body, &elems); err != nil { writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", - Error: &rpcError{Code: codeParse, Message: err.Error()}}) + Error: withLocalOrigin(&rpcError{Code: codeParse, Message: err.Error()})}) return } if len(elems) == 0 { writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", - Error: &rpcError{Code: codeInvalidRequest, Message: "an empty batch is not a request"}}) + Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, Message: "an empty batch is not a request"})}) return } var c *Conn @@ -2216,7 +2261,7 @@ func (s *Server) serveBatch(w http.ResponseWriter, r *http.Request, body []byte, sc, ok := s.session(id) if !ok { writeJSON(w, http.StatusNotFound, response{JSONRPC: "2.0", - Error: &rpcError{Code: codeInvalidRequest, Message: "no such session"}}) + Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, Message: "no such session"})}) return } c, tracked, ctx = sc, true, context.WithoutCancel(ctx) @@ -2254,13 +2299,13 @@ func (s *Server) serveBatch(w http.ResponseWriter, r *http.Request, body []byte, func (s *Server) serveDELETE(w http.ResponseWriter, r *http.Request) { id := r.Header.Get(sessionHeader) if id == "" { - writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", Error: &rpcError{ - Code: codeInvalidRequest, Message: "DELETE ends a session; name it in " + sessionHeader}}) + writeJSON(w, http.StatusBadRequest, response{JSONRPC: "2.0", Error: withLocalOrigin(&rpcError{ + Code: codeInvalidRequest, Message: "DELETE ends a session; name it in " + sessionHeader})}) return } if _, ok := s.session(id); !ok { - writeJSON(w, http.StatusNotFound, response{JSONRPC: "2.0", Error: &rpcError{ - Code: codeInvalidRequest, Message: "no such session"}}) + writeJSON(w, http.StatusNotFound, response{JSONRPC: "2.0", Error: withLocalOrigin(&rpcError{ + Code: codeInvalidRequest, Message: "no such session"})}) return } s.dropSession(id) diff --git a/pkgs/mcpx/internal/mcpserver/tasks.go b/pkgs/mcpx/internal/mcpserver/tasks.go index 36fac0b4b8..25fb63646f 100644 --- a/pkgs/mcpx/internal/mcpserver/tasks.go +++ b/pkgs/mcpx/internal/mcpserver/tasks.go @@ -109,7 +109,7 @@ func (s *Server) startTask(ctx context.Context, owner string, ttl int64, fn func t, err := s.tasks().Start(tasks.Caller(identity), ttl, func(ctx context.Context) (any, *tasks.Fault) { result, err := fn(ctx) if err != nil { - return nil, &tasks.Fault{Code: err.Code, Message: err.Message, Data: err.Data} + return nil, &tasks.Fault{Code: err.Code, Message: err.Message, Data: err.Data, Relayed: err.relayed} } return result, nil }) @@ -366,7 +366,7 @@ func (s *Server) maybeTask(ctx context.Context, c *Conn, req request, peer Peer) // stays in the store until its TTL, harmlessly; nobody holds its id. if fault != nil { return &response{JSONRPC: "2.0", ID: req.ID, - Error: &rpcError{Code: fault.Code, Message: fault.Message, Data: fault.Data}} + Error: &rpcError{Code: fault.Code, Message: fault.Message, Data: fault.Data, relayed: fault.Relayed}} } return &response{JSONRPC: "2.0", ID: req.ID, Result: result} } @@ -468,7 +468,7 @@ func (s *Server) driveAsked(ctx context.Context, req request, peer Peer, callID if out.Done { resp := finishedAsk(req, out, peer, true) if resp.Error != nil { - return nil, &tasks.Fault{Code: resp.Error.Code, Message: resp.Error.Message, Data: resp.Error.Data} + return nil, &tasks.Fault{Code: resp.Error.Code, Message: resp.Error.Message, Data: resp.Error.Data, Relayed: resp.Error.relayed} } return resp.Result, nil } @@ -697,7 +697,7 @@ func (s *Server) handleTask(ctx context.Context, c *Conn, req request, peer Peer return fail(codeInternal, "the request ended before the task did") case fault != nil: return &response{JSONRPC: "2.0", ID: req.ID, - Error: &rpcError{Code: fault.Code, Message: fault.Message, Data: fault.Data}} + Error: &rpcError{Code: fault.Code, Message: fault.Message, Data: fault.Data, relayed: fault.Relayed}} } // 2025-11-25: the tasks/result response MUST carry the // related-task _meta naming its task, since the result itself is diff --git a/pkgs/mcpx/internal/mcpserver/transport.go b/pkgs/mcpx/internal/mcpserver/transport.go index 9271cc08a5..6a8f871cbc 100644 --- a/pkgs/mcpx/internal/mcpserver/transport.go +++ b/pkgs/mcpx/internal/mcpserver/transport.go @@ -123,9 +123,9 @@ func isBatch(body []byte) bool { // them, and the modern revisions define a POST body and a stdio line as one // message. An id cannot be named because there are several. func batchRefused(version string) *response { - return &response{JSONRPC: "2.0", Error: &rpcError{Code: codeInvalidRequest, + return &response{JSONRPC: "2.0", Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, Message: "JSON-RPC batches exist only in 2025-03-26, not in protocol version " + version + - ", so send one message at a time"}} + ", so send one message at a time"})} } // runBatch answers every element of a 2025-03-26 batch. @@ -146,20 +146,20 @@ func (s *Server) runBatch(ctx context.Context, c *Conn, elems []json.RawMessage, var req request if err := json.Unmarshal(raw, &req); err != nil { out[i] = &response{JSONRPC: "2.0", - Error: &rpcError{Code: codeInvalidRequest, Message: err.Error()}} + Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, Message: err.Error()})} continue } if req.Method == "initialize" { // 2025-03-26 lifecycle: "The initialization phase MUST be the // first interaction ... the initialize request MUST NOT be part // of a JSON-RPC batch." - out[i] = &response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{ - Code: codeInvalidRequest, Message: "initialize must not be sent in a batch"}} + out[i] = &response{JSONRPC: "2.0", ID: req.ID, Error: withLocalOrigin(&rpcError{ + Code: codeInvalidRequest, Message: "initialize must not be sent in a batch"})} continue } if requestVersion(req.Params) != "" { - out[i] = &response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{ - Code: codeInvalidRequest, Message: "a per-request-metadata message cannot be batched"}} + out[i] = &response{JSONRPC: "2.0", ID: req.ID, Error: withLocalOrigin(&rpcError{ + Code: codeInvalidRequest, Message: "a per-request-metadata message cannot be batched"})} continue } wg.Add(1) @@ -502,7 +502,7 @@ func (s *Server) serveGET(w http.ResponseWriter, r *http.Request) { notAllowed := func(why string) { w.Header().Set("Allow", "POST, DELETE") writeJSON(w, http.StatusMethodNotAllowed, response{JSONRPC: "2.0", - Error: &rpcError{Code: codeInvalidRequest, Message: why}}) + Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, Message: why})}) } if modernHeaderVersion(r.Header.Get("MCP-Protocol-Version")) { notAllowed("2026-07-28 has no GET stream; open one with subscriptions/listen") @@ -517,7 +517,7 @@ func (s *Server) serveGET(w http.ResponseWriter, r *http.Request) { c, ok := s.session(id) if !ok { writeJSON(w, http.StatusNotFound, response{JSONRPC: "2.0", - Error: &rpcError{Code: codeInvalidRequest, Message: "no such session"}}) + Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, Message: "no such session"})}) return } f := asFlusher(w) @@ -533,7 +533,7 @@ func (s *Server) serveGET(w http.ResponseWriter, r *http.Request) { // broadcasting a message across them, and a second stream a client // opened by accident would silently take half its notifications. writeJSON(w, http.StatusConflict, response{JSONRPC: "2.0", - Error: &rpcError{Code: codeInvalidRequest, Message: "this session already has a GET stream open"}}) + Error: withLocalOrigin(&rpcError{Code: codeInvalidRequest, Message: "this session already has a GET stream open"})}) return } c.stream = st diff --git a/pkgs/mcpx/internal/tasks/tasks.go b/pkgs/mcpx/internal/tasks/tasks.go index 86cee963ce..14fb180c9c 100644 --- a/pkgs/mcpx/internal/tasks/tasks.go +++ b/pkgs/mcpx/internal/tasks/tasks.go @@ -163,6 +163,14 @@ type Fault struct { Code int `json:"code"` Message string `json:"message"` Data any `json:"data,omitempty"` + + // Relayed marks a fault that is a peer's error carried verbatim, + // as opposed to one minted by the carrier itself. It rides the + // fault JSON so the provenance survives the store, including its + // database persistence; a consumer rendering a fault back into a + // protocol error uses it to leave a peer's error untouched + // (#2435). + Relayed bool `json:"relayed,omitempty"` } func (f *Fault) Error() string { return f.Message }