From de72fa921262795b286671ad84c1b11d46e92268 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 01:22:24 -0500 Subject: [PATCH] fix(mcpx client): truthful cancellation reason; paginate templates/list; surface prompts/list errors (#1924) The two remaining rows of #1924. PC-08: Client.cancelled hard-coded reason timeout for every cancellation, including a caller cancelling for their own reasons; it now takes the cause from its call sites (roundTripOnce send + wait paths pass ctx.Err(), the listen close passes its cancelled context) and cancelReason maps DeadlineExceeded to timeout and anything else to the actual cause. Era rules unchanged (never initialize, never modern HTTP). PG-07: ListResourceTemplates made one unpaginated call while every other list paged; it now delegates to a new ListResourceTemplatesWithHints that loops nextCursor to defaults.ListPageLimit merging hints, matching ListTools/ListResources. ListPromptsWithHints swallowed every prompts/list error as an absence; it now swallows only -32601 method-not-found and surfaces the rest. Tests in pg07_pc08_test.go: two-page templates list, prompts/list -32603 surfaces, caller-cancel sends reason context canceled and deadline sends timeout (recorded off a hanging transport). Full mcpclient package passes on the laptop. --- pkgs/mcpx/internal/mcpclient/client.go | 43 ++++- pkgs/mcpx/internal/mcpclient/listen.go | 2 +- pkgs/mcpx/internal/mcpclient/modern.go | 17 +- .../mcpx/internal/mcpclient/pg07_pc08_test.go | 171 ++++++++++++++++++ 4 files changed, 222 insertions(+), 11 deletions(-) create mode 100644 pkgs/mcpx/internal/mcpclient/pg07_pc08_test.go diff --git a/pkgs/mcpx/internal/mcpclient/client.go b/pkgs/mcpx/internal/mcpclient/client.go index e7ecc5f25c..e6681fad83 100644 --- a/pkgs/mcpx/internal/mcpclient/client.go +++ b/pkgs/mcpx/internal/mcpclient/client.go @@ -882,11 +882,32 @@ func (c *Client) UnsubscribeResource(ctx context.Context, uri string) error { // ListResourceTemplates returns the server's parameterised resources. func (c *Client) ListResourceTemplates(ctx context.Context) ([]Resource, error) { - var tres resourceTemplatesListResult - if err := c.call(ctx, "resources/templates/list", json.RawMessage(`{}`), &tres); err != nil { - return nil, err + all, _, err := c.ListResourceTemplatesWithHints(ctx) + return all, err +} + +// ListResourceTemplatesWithHints is ListResourceTemplates plus the cache +// hints the server declared on the pages it returned. It pages like the +// other list calls (PG-07, #1924): templates past page 1 used to be +// silently dropped by the single unpaginated call this replaces. +func (c *Client) ListResourceTemplatesWithHints(ctx context.Context) ([]Resource, CacheHints, error) { + var all []Resource + var hints CacheHints + var cursor *string + for i := 0; i < defaults.ListPageLimit; i++ { + var tres resourceTemplatesListResult + if err := c.call(ctx, "resources/templates/list", pageParams(cursor), &tres); err != nil { + return all, hints, err + } + hints.merge(tres.TTLMs, tres.CacheScope) + all = append(all, tres.ResourceTemplates...) + next, more := c.nextPage(tres.NextCursor, cursor) + if !more { + break + } + cursor = &next } - return tres.ResourceTemplates, nil + return all, hints, nil } // SetLogLevel asks the server to send messages at or above a level. @@ -1168,7 +1189,7 @@ func (c *Client) roundTripOnce(ctx context.Context, method string, params json.R // The HTTP transport's Send lasts until the response headers // arrive, so a server that is slow to start answering is timed // out here, not below -- and was never told. - c.cancelled(method, id) + c.cancelled(method, id, ctx.Err()) } return nil, err } @@ -1178,7 +1199,7 @@ func (c *Client) roundTripOnce(ctx context.Context, method string, params json.R c.mu.Lock() delete(c.pending, id) c.mu.Unlock() - c.cancelled(method, id) + c.cancelled(method, id, ctx.Err()) return nil, ctx.Err() case resp := <-ch: if resp.Error != nil { @@ -1379,8 +1400,14 @@ func (c *Client) ListPromptsWithHints(ctx context.Context) ([]Prompt, CacheHints if err := c.call(ctx, "prompts/list", pageParams(cursor), &res); err != nil { // A server without prompts answers method-not-found, which is an // absence rather than a failure. Treating it as an error would - // make every listing fail on the majority of servers. - return all, hints, nil + // make every listing fail on the majority of servers. Every + // OTHER error is a real failure and surfaces (PG-07, #1924): + // swallowing it made a broken server look prompt-less. + var re *rpcError + if errors.As(err, &re) && re.Code == -32601 { + return all, hints, nil + } + return all, hints, err } hints.merge(res.TTLMs, res.CacheScope) all = append(all, res.Prompts...) diff --git a/pkgs/mcpx/internal/mcpclient/listen.go b/pkgs/mcpx/internal/mcpclient/listen.go index 6ea08f7b22..6c33d1fd3c 100644 --- a/pkgs/mcpx/internal/mcpclient/listen.go +++ b/pkgs/mcpx/internal/mcpclient/listen.go @@ -152,7 +152,7 @@ func (l *listener) open(f ListenFilter) (int64, <-chan *rpcResponse, func()) { gotID, ch := c.beginID(ctx, id, "subscriptions/listen", params) return gotID, ch, func() { cancel() - c.cancelled("subscriptions/listen", gotID) + c.cancelled("subscriptions/listen", gotID, ctx.Err()) } } diff --git a/pkgs/mcpx/internal/mcpclient/modern.go b/pkgs/mcpx/internal/mcpclient/modern.go index a03305b9f1..a8eedf7538 100644 --- a/pkgs/mcpx/internal/mcpclient/modern.go +++ b/pkgs/mcpx/internal/mcpclient/modern.go @@ -537,14 +537,27 @@ func applyDefaults(out any, params json.RawMessage) any { // notification is sent, on its own context so it outlives the request. // // https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/cancellation -func (c *Client) cancelled(method string, id int64) { +// cancelled's reason is the truth about why the request died (PC-08, +// #1924): a deadline is "timeout"; anything the caller did to their own +// context is reported as what it was, not dressed up as a timeout. +func cancelReason(cause error) string { + switch { + case errors.Is(cause, context.DeadlineExceeded): + return "timeout" + case cause != nil: + return cause.Error() + } + return "cancelled" +} + +func (c *Client) cancelled(method string, id int64, cause error) { if method == "initialize" { return } if _, isHTTP := c.t.(*HTTPTransport); isHTTP && c.metaVersion != "" { return } - cp, _ := json.Marshal(map[string]any{"requestId": id, "reason": "timeout"}) + cp, _ := json.Marshal(map[string]any{"requestId": id, "reason": cancelReason(cause)}) ctx, cancel := context.WithTimeout(context.Background(), defaults.UpstreamCancelSendTimeout) defer cancel() _ = c.notify(ctx, "notifications/cancelled", cp) diff --git a/pkgs/mcpx/internal/mcpclient/pg07_pc08_test.go b/pkgs/mcpx/internal/mcpclient/pg07_pc08_test.go new file mode 100644 index 0000000000..53803d7da9 --- /dev/null +++ b/pkgs/mcpx/internal/mcpclient/pg07_pc08_test.go @@ -0,0 +1,171 @@ +package mcpclient_test + +import ( + "context" + "encoding/json" + "strings" + "sync" + "testing" + "time" + + "github.com/dezren39/mcpx/internal/mcpclient" +) + +// PG-07 (#1924): ListResourceTemplates pages like every other list call. +func TestListResourceTemplatesPages(t *testing.T) { + s := newScripted(func(method string, params map[string]any) any { + switch method { + case "server/discover": + return modernDiscover(params) + case "resources/templates/list": + if params["cursor"] == nil { + return map[string]any{ + "resultType": "complete", + "resourceTemplates": []any{map[string]any{"uriTemplate": "demo://t/{id}", "name": "t1"}}, + "nextCursor": "t2", + } + } + return map[string]any{ + "resultType": "complete", + "resourceTemplates": []any{map[string]any{"uriTemplate": "demo://u/{id}", "name": "t2"}}, + } + } + return nil + }) + c := dialModern(t, s, mcpclient.Options{}) + got, err := c.ListResourceTemplates(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[0].Name != "t1" || got[1].Name != "t2" { + t.Fatalf("templates = %+v, want both pages (t1, t2)", got) + } +} + +// hangTransport answers server/discover, never answers tools/list, fails +// prompts/list with a real (non method-not-found) error, and records every +// frame — enough to watch the cancellation notification the client sends. +type hangTransport struct { + mu sync.Mutex + in chan []byte + frames []map[string]any + closed bool +} + +func newHangTransport() *hangTransport { return &hangTransport{in: make(chan []byte, 64)} } + +func (h *hangTransport) Send(_ context.Context, msg []byte) error { + var f map[string]any + _ = json.Unmarshal(msg, &f) + h.mu.Lock() + h.frames = append(h.frames, f) + h.mu.Unlock() + method, _ := f["method"].(string) + if f["id"] == nil { + return nil // a notification: recorded above, nothing to answer + } + reply := func(key string, v any) { + b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": f["id"], key: v}) + h.in <- b + } + switch method { + case "server/discover": + reply("result", modernDiscover(nil)) + case "prompts/list": + reply("error", map[string]any{"code": -32603, "message": "prompts exploded"}) + } + // tools/list is never answered: the call hangs until its ctx ends. + return nil +} + +func (h *hangTransport) Recv() ([]byte, error) { + msg, ok := <-h.in + if !ok { + return nil, context.Canceled + } + return msg, nil +} + +func (h *hangTransport) Info() string { return "hang" } + +func (h *hangTransport) Close() error { + h.mu.Lock() + defer h.mu.Unlock() + if !h.closed { + h.closed = true + close(h.in) + } + return nil +} + +func (h *hangTransport) cancelReasons() []string { + h.mu.Lock() + defer h.mu.Unlock() + var out []string + for _, f := range h.frames { + if f["method"] == "notifications/cancelled" { + if p, ok := f["params"].(map[string]any); ok { + r, _ := p["reason"].(string) + out = append(out, r) + } + } + } + return out +} + +func dialHang(t *testing.T, h *hangTransport) *mcpclient.Client { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + c, err := mcpclient.NewWithOptions(ctx, h, mcpclient.Options{ + ClientName: "mcpx", ClientVersion: "test", Preference: mcpclient.ForceModern, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return c +} + +// PG-07 (#1924): a prompts/list failure that is not method-not-found +// surfaces instead of reading as "this server has no prompts". +func TestListPromptsSurfacesRealErrors(t *testing.T) { + c := dialHang(t, newHangTransport()) + _, _, err := c.ListPromptsWithHints(context.Background()) + if err == nil || !strings.Contains(err.Error(), "prompts exploded") { + t.Fatalf("err = %v, want the server's prompts/list failure", err) + } +} + +// PC-08 (#1924): the cancellation reason is the truth — a caller's own +// cancel is not reported as a timeout, and a deadline still is. +func TestCancellationReasonIsTruthful(t *testing.T) { + h := newHangTransport() + c := dialHang(t, h) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, err := c.ListTools(ctx) + done <- err + }() + time.Sleep(100 * time.Millisecond) + cancel() + if err := <-done; err == nil { + t.Fatal("the hung call should have failed on cancel") + } + if got := h.cancelReasons(); len(got) != 1 || got[0] != "context canceled" { + t.Fatalf("cancel reasons = %v, want [context canceled]", got) + } + + h2 := newHangTransport() + c2 := dialHang(t, h2) + dctx, dcancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer dcancel() + if _, err := c2.ListTools(dctx); err == nil { + t.Fatal("the hung call should have failed on deadline") + } + if got := h2.cancelReasons(); len(got) != 1 || got[0] != "timeout" { + t.Fatalf("cancel reasons = %v, want [timeout]", got) + } +}