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
43 changes: 35 additions & 8 deletions pkgs/mcpx/internal/mcpclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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...)
Expand Down
2 changes: 1 addition & 1 deletion pkgs/mcpx/internal/mcpclient/listen.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}

Expand Down
17 changes: 15 additions & 2 deletions pkgs/mcpx/internal/mcpclient/modern.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
171 changes: 171 additions & 0 deletions pkgs/mcpx/internal/mcpclient/pg07_pc08_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}