Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion pkgs/mcpx/internal/cli/serve_ask.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
92 changes: 92 additions & 0 deletions pkgs/mcpx/internal/cli/serve_ask_upstream_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
2 changes: 1 addition & 1 deletion pkgs/mcpx/internal/mcpserver/capability.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}}
}
174 changes: 174 additions & 0 deletions pkgs/mcpx/internal/mcpserver/origin_marker_codex_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
})
}
}
Loading
Loading