From a89a18090e270ac7d85565b5515ca1b872874322 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 09:04:54 -0500 Subject: [PATCH 1/2] =?UTF-8?q?feat(mcpx):=20handle=20upstream=20-32042=20?= =?UTF-8?q?in=20CallTool=20=E2=80=94=20broker=20URL=20elicitations,=20retr?= =?UTF-8?q?y=20once=20(#2079)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/mcpx/internal/daemon/hooks.go | 50 ++++- .../daemon/url_elicitation_32042_test.go | 170 +++++++++++++++ pkgs/mcpx/internal/mcpclient/client.go | 105 +++++++-- pkgs/mcpx/internal/mcpclient/modern.go | 4 + .../mcpclient/url_elicitation_32042_test.go | 200 ++++++++++++++++++ pkgs/mcpx/internal/pool/pool.go | 17 +- 6 files changed, 530 insertions(+), 16 deletions(-) create mode 100644 pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go create mode 100644 pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go diff --git a/pkgs/mcpx/internal/daemon/hooks.go b/pkgs/mcpx/internal/daemon/hooks.go index 870046ec93..ea830818eb 100644 --- a/pkgs/mcpx/internal/daemon/hooks.go +++ b/pkgs/mcpx/internal/daemon/hooks.go @@ -60,7 +60,7 @@ func (r *Registry) InstallHooks(bus *events.Bus, broker *elicit.Broker, roots [] // on it should hear so now rather than at its deadline. if r.broker != nil { _ = r.broker.Respond(elicit.Answer{ - ID: id, Action: elicit.Accept, By: "server:" + server, + ID: server + ":" + id, Action: elicit.Accept, By: "server:" + server, }) } r.publish(events.Event{ @@ -70,6 +70,9 @@ func (r *Registry) InstallHooks(bus *events.Bus, broker *elicit.Broker, roots [] }, Elicit: r.answerServer, } + if broker != nil { + hooks.URLElicitation = r.urlElicitationsViaBroker + } r.upstreamHooks(hooks) // Under r.mu: Reload reads r.hooks and replaces r.pools under it. r.mu.Lock() @@ -174,8 +177,20 @@ func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, para if p.Mode == "url" { mode = elicit.URL } + // Broker rows are keyed by ID alone, and elicitationId is the + // upstream's own choice: two servers can pick the same one and the + // second OpenRequest would fail on the primary key (ELI-09). A + // server-supplied ID is therefore stored server-qualified; + // OnElicitationComplete composes the same qualified ID before it + // responds. Minted IDs (empty elicitationId) are already unique and + // stay bare. Rows opened under a bare ID before this fix are not + // migrated; they expire by TTL. + brokerID := p.ElicitationID + if brokerID != "" { + brokerID = server + ":" + brokerID + } req, err := r.broker.OpenRequest(elicit.Request{ - ID: p.ElicitationID, + ID: brokerID, Server: server, Mode: mode, Message: p.Message, @@ -209,6 +224,37 @@ func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, para return out, nil } +// urlElicitationsViaBroker opens the URL elicitations an upstream's +// -32042 tools/call error named (#2079, Phase 2 of #2077). Each entry +// runs the existing elicitation/create path with synthesised url-mode +// params -- no second URL flow -- sequentially, because elicitViaBroker +// blocks on the broker answer. Every entry must be accepted before the +// client retries the call; the first decline, cancel, or expiry stops +// here with a named error and the remaining entries are never opened. +func (r *Registry) urlElicitationsViaBroker(ctx context.Context, server, key string, elicitations []mcpclient.URLElicitation) (bool, error) { + if r.broker == nil { + return false, fmt.Errorf("mcpx cannot open URL elicitations from %s: no broker", server) + } + for _, e := range elicitations { + params, err := json.Marshal(map[string]any{ + "mode": "url", "url": e.URL, "elicitationId": e.ElicitationID, "message": e.Message, + }) + if err != nil { + return false, err + } + out, err := r.elicitViaBroker(ctx, server, key, params) + if err != nil { + return false, err + } + res, _ := out.(map[string]any) + action, _ := res["action"].(string) + if action != string(elicit.Accept) { + return false, fmt.Errorf("the URL elicitation %s from %s was %s", e.ElicitationID, server, action) + } + } + return true, nil +} + // sampleViaBroker turns a sampling request into a question for whatever is // driving mcpx. // diff --git a/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go b/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go new file mode 100644 index 0000000000..74c49f1dbb --- /dev/null +++ b/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go @@ -0,0 +1,170 @@ +package daemon + +import ( + "context" + "encoding/json" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/dezren39/mcpx/internal/elicit" + "github.com/dezren39/mcpx/internal/events" + "github.com/dezren39/mcpx/internal/mcpclient" +) + +// #2079 / ELI-09: broker rows are keyed by ID alone, and elicitationId +// is the upstream's own choice, so server-supplied IDs are stored +// server-qualified. Two upstreams choosing the same elicitationId hold +// distinct rows, and an answer settles only its own server's row. +func TestBrokerKeyingServerQualified(t *testing.T) { + broker, err := elicit.Open(filepath.Join(t.TempDir(), "elicit.db")) + if err != nil { + t.Fatal(err) + } + defer broker.Close() + r := &Registry{asks: newAskTable()} + r.InstallHooks(events.New(0), broker, nil) + + params := json.RawMessage(`{"mode":"url","message":"sign in","url":"https://example.invalid/auth","elicitationId":"e1"}`) + type outcome struct { + out any + err error + } + results := map[string]chan outcome{} + for _, srv := range []string{"srvA", "srvB"} { + ch := make(chan outcome, 1) + results[srv] = ch + go func(srv string, ch chan<- outcome) { + out, err := r.elicitViaBroker(context.Background(), srv, "key", params) + ch <- outcome{out, err} + }(srv, ch) + } + + waitRow := func(id string) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if _, ok, err := broker.Get(id); err == nil && ok { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("broker row %q never appeared", id) + } + waitRow("srvA:e1") + waitRow("srvB:e1") + if _, ok, err := broker.Get("e1"); err != nil || ok { + t.Fatalf("a bare e1 row exists (ok=%v err=%v): the collision is back", ok, err) + } + + // Answering srvA's row settles only srvA's waiter. + if err := broker.Respond(elicit.Answer{ID: "srvA:e1", Action: elicit.Accept, By: "test"}); err != nil { + t.Fatal(err) + } + select { + case o := <-results["srvA"]: + if o.err != nil { + t.Fatal(o.err) + } + if a, _ := o.out.(map[string]any)["action"].(string); a != "accept" { + t.Fatalf("srvA outcome = %v, want accept", o.out) + } + case <-time.After(5 * time.Second): + t.Fatal("srvA waiter never returned") + } + select { + case o := <-results["srvB"]: + t.Fatalf("srvB waiter returned early with %v: an answer crossed servers", o) + case <-time.After(300 * time.Millisecond): + } + + if err := broker.Respond(elicit.Answer{ID: "srvB:e1", Action: elicit.Decline, By: "test"}); err != nil { + t.Fatal(err) + } + select { + case o := <-results["srvB"]: + if a, _ := o.out.(map[string]any)["action"].(string); a != "decline" { + t.Fatalf("srvB outcome = %v, want decline", o.out) + } + case <-time.After(5 * time.Second): + t.Fatal("srvB waiter never returned") + } +} + +// #2079: the -32042 handler runs each listed entry through the existing +// broker path in order; every entry must accept, and the first decline +// stops the flow with a named error, later entries unopened. +func TestURLElicitationsViaBroker(t *testing.T) { + broker, err := elicit.Open(filepath.Join(t.TempDir(), "elicit.db")) + if err != nil { + t.Fatal(err) + } + defer broker.Close() + r := &Registry{asks: newAskTable()} + r.InstallHooks(events.New(0), broker, nil) + + els := []mcpclient.URLElicitation{ + {Mode: "url", URL: "https://example.invalid/a", ElicitationID: "e1", Message: "first"}, + {Mode: "url", URL: "https://example.invalid/b", ElicitationID: "e2", Message: "second"}, + } + type outcome struct { + ok bool + err error + } + done := make(chan outcome, 1) + go func() { + ok, err := r.urlElicitationsViaBroker(context.Background(), "srv", "key", els) + done <- outcome{ok, err} + }() + + answer := func(id string, action elicit.Action) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if _, ok, err := broker.Get(id); err == nil && ok { + if err := broker.Respond(elicit.Answer{ID: id, Action: action, By: "test"}); err != nil { + t.Fatal(err) + } + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("broker row %q never appeared", id) + } + answer("srv:e1", elicit.Accept) + answer("srv:e2", elicit.Decline) + + select { + case o := <-done: + if o.ok || o.err == nil || !strings.Contains(o.err.Error(), "e2") || !strings.Contains(o.err.Error(), "decline") { + t.Fatalf("want (false, a named decline error for e2), got %v", o) + } + case <-time.After(5 * time.Second): + t.Fatal("the handler never returned") + } + + // First-entry decline: the second entry is never opened. (Fresh IDs: + // broker IDs are primary keys, so a settled row cannot be reopened.) + els2 := []mcpclient.URLElicitation{ + {Mode: "url", URL: "https://example.invalid/c", ElicitationID: "e3", Message: "third"}, + {Mode: "url", URL: "https://example.invalid/d", ElicitationID: "e4", Message: "fourth"}, + } + done2 := make(chan outcome, 1) + go func() { + ok, err := r.urlElicitationsViaBroker(context.Background(), "srv", "key", els2) + done2 <- outcome{ok, err} + }() + answer("srv:e3", elicit.Decline) + select { + case o := <-done2: + if o.ok || o.err == nil { + t.Fatalf("want (false, error) on first decline, got %v", o) + } + case <-time.After(5 * time.Second): + t.Fatal("the handler never returned after the first decline") + } + if _, ok, err := broker.Get("srv:e4"); err != nil || ok { + t.Fatalf("srv:e4 exists (ok=%v err=%v): a later entry was opened after a first-entry decline", ok, err) + } +} diff --git a/pkgs/mcpx/internal/mcpclient/client.go b/pkgs/mcpx/internal/mcpclient/client.go index 0cd5c63470..4973ccc858 100644 --- a/pkgs/mcpx/internal/mcpclient/client.go +++ b/pkgs/mcpx/internal/mcpclient/client.go @@ -114,6 +114,10 @@ type Client struct { reqMu sync.Mutex sessionSampling *windowCounter server *ServerRequestLimiter + + // onURLElicitationRequired opens the URL elicitations a -32042 + // tools/call error names, when something (the daemon broker) can. + onURLElicitationRequired URLElicitationHandler // notif holds notification handlers. notif Notifications // roots are the directories servers may work within. @@ -353,16 +357,17 @@ func NewWithPreference(ctx context.Context, t Transport, clientName, clientVersi func newClient(ctx context.Context, t Transport, o Options) (*Client, error) { c := &Client{ - t: t, - pending: map[int64]chan *rpcResponse{}, - closeCh: make(chan struct{}), - clientName: o.ClientName, - clientVersion: o.ClientVersion, - onElicit: o.OnServerRequest, - roots: append([]Root(nil), o.Roots...), - modernVersions: o.ModernVersions, - probeTimeout: o.ProbeTimeout, - loopDone: make(chan struct{}), + t: t, + pending: map[int64]chan *rpcResponse{}, + closeCh: make(chan struct{}), + clientName: o.ClientName, + clientVersion: o.ClientVersion, + onElicit: o.OnServerRequest, + onURLElicitationRequired: o.OnURLElicitationRequired, + roots: append([]Root(nil), o.Roots...), + modernVersions: o.ModernVersions, + probeTimeout: o.ProbeTimeout, + loopDone: make(chan struct{}), } if len(c.modernVersions) == 0 { c.modernVersions = ModernVersions @@ -609,6 +614,50 @@ func (c *Client) SetElicitHandler(h ElicitHandler) { c.mu.Unlock() } +// URLElicitation is one entry of a -32042 (UrlElicitationRequired) +// error's data.elicitations: a URL-mode elicitation the server needs +// opened before the failed tool call can proceed (2025-11-25). +type URLElicitation struct { + Mode string `json:"mode"` + URL string `json:"url"` + ElicitationID string `json:"elicitationId"` + Message string `json:"message"` +} + +// URLElicitationHandler opens the URL elicitations a -32042 names. It +// reports true only when every entry was accepted; false or an error +// fails the call with no retry. A nil handler (the default) means +// -32042 propagates untouched, exactly as a client with nobody to open +// URLs behaved before this existed. +type URLElicitationHandler func(ctx context.Context, elicitations []URLElicitation) (bool, error) + +// SetURLElicitationHandler installs the -32042 handler after connect. +func (c *Client) SetURLElicitationHandler(h URLElicitationHandler) { + c.mu.Lock() + c.onURLElicitationRequired = h + c.mu.Unlock() +} + +// parseURLElicitations reads a -32042 error's data. ok is false for any +// malformed shape: unparseable data, an empty list, a non-url entry, or +// an entry with no elicitationId. In every such case the caller returns +// the original error unmodified, because guessing at a server's +// question is worse than failing its call. +func parseURLElicitations(data json.RawMessage) ([]URLElicitation, bool) { + var d struct { + Elicitations []URLElicitation `json:"elicitations"` + } + if len(data) == 0 || json.Unmarshal(data, &d) != nil || len(d.Elicitations) == 0 { + return nil, false + } + for _, e := range d.Elicitations { + if e.Mode != "url" || e.ElicitationID == "" { + return nil, false + } + } + return d.Elicitations, true +} + // handleServerRequest answers a request the server sent to us. // // Always answers a legacy server; a 2026-07-28 one has no business sending @@ -1497,6 +1546,7 @@ func (c *Client) CallTool(ctx context.Context, name string, args any) (json.RawM defer done() var raw json.RawMessage allowReissue := false + retried32042 := false for attempt := 0; ; attempt++ { hctx, err := c.toolCallHeaders(ctx, name, args, attempt > 0) if err != nil { @@ -1512,6 +1562,31 @@ func (c *Client) CallTool(ctx context.Context, name string, args any) (json.RawM if attempt == 0 && errors.As(err, &re) && re.Code == codeHeaderMismatch && c.mirrorsHeaders() { continue } + // A -32042 on a 2025-11-25 connection names URL elicitations to + // open before the call can proceed (#2079). The retry is gated + // on its own flag, not the attempt index: the -32020 continue + // above already spends attempts, and the -32042 retry must + // happen exactly once regardless. Malformed data, or no handler + // installed, leaves the original error untouched; any other + // negotiated version is untouched too. + if !retried32042 && err != nil && c.Negotiated == "2025-11-25" && + errors.As(err, &re) && re.Code == codeURLElicitationRequired { + els, wellFormed := parseURLElicitations(re.Data) + c.mu.Lock() + h := c.onURLElicitationRequired + c.mu.Unlock() + if wellFormed && h != nil { + accepted, herr := h(ctx, els) + if herr != nil { + return nil, herr + } + if !accepted { + return nil, fmt.Errorf("mcpx: the URL elicitations required by tool %s were declined or expired", name) + } + retried32042 = true + continue + } + } if err != nil { return nil, err } @@ -1540,9 +1615,13 @@ func (c *Client) ReadResource(ctx context.Context, uri string) (json.RawMessage, } const ( - codeResourceNotFound = -32002 - codeInvalidParams = -32602 - codeInternalError = -32603 + // codeURLElicitationRequired is -32042 UrlElicitationRequired + // (2025-11-25): the tool call needs the URL-mode elicitations in + // the error's data opened before it can proceed. + codeURLElicitationRequired = -32042 + codeResourceNotFound = -32002 + codeInvalidParams = -32602 + codeInternalError = -32603 // codeUserRejected is the code the sampling error table assigns to a // person refusing a sampling request (2025-11-25 client/sampling // error handling: "User rejected sampling request: -1"). It is not a diff --git a/pkgs/mcpx/internal/mcpclient/modern.go b/pkgs/mcpx/internal/mcpclient/modern.go index f83c081f96..e05e2287ee 100644 --- a/pkgs/mcpx/internal/mcpclient/modern.go +++ b/pkgs/mcpx/internal/mcpclient/modern.go @@ -31,6 +31,10 @@ type Options struct { // handshake: a handler added later cannot be declared, so a server // would never learn it exists. OnServerRequest ElicitHandler + // OnURLElicitationRequired opens the URL elicitations a -32042 + // tools/call error names (2025-11-25 only). Nil propagates -32042 + // untouched. + OnURLElicitationRequired URLElicitationHandler // Roots are the directories servers may work within, served from the // first request rather than from whenever they happen to be set. Roots []Root diff --git a/pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go b/pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go new file mode 100644 index 0000000000..8604fb7b2f --- /dev/null +++ b/pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go @@ -0,0 +1,200 @@ +package mcpclient_test + +import ( + "context" + "errors" + "strings" + "sync/atomic" + "testing" + + "github.com/dezren39/mcpx/internal/mcpclient" +) + +// #2079 (Phase 2 of #2077): a -32042 UrlElicitationRequired from a +// 2025-11-25 upstream names URL elicitations in its error data. The +// client hands them to the installed handler and, only when every one +// is accepted, retries the original call exactly once. + +func urlElicitationData() map[string]any { + return map[string]any{"elicitations": []any{ + map[string]any{"mode": "url", "url": "https://example.invalid/auth", "elicitationId": "e1", "message": "sign in"}, + }} +} + +// dial32042 builds a legacy client at rev whose tools/call answers are +// served by call (n is the 1-based call count). handler may be nil. +func dial32042(t *testing.T, rev string, handler mcpclient.URLElicitationHandler, call func(n int32) (any, map[string]any)) *mcpclient.Client { + t.Helper() + var calls atomic.Int32 + w := newWire(t, rev, func(m string, p map[string]any) (any, map[string]any) { + switch m { + case "initialize": + return initResult(rev, nil), nil + case "tools/call": + return call(calls.Add(1)) + } + return nil, nil + }) + return dialWire(t, w, mcpclient.ForceLegacy, mcpclient.Options{OnURLElicitationRequired: handler}) +} + +func TestURLElicitationRequiredRetry(t *testing.T) { + t.Run("accepted-then-retry-succeeds-exactly-once", func(t *testing.T) { + var got []mcpclient.URLElicitation + c := dial32042(t, "2025-11-25", func(_ context.Context, els []mcpclient.URLElicitation) (bool, error) { + got = els + return true, nil + }, func(n int32) (any, map[string]any) { + if n == 1 { + return nil, rpcErr(-32042, "url elicitation required", urlElicitationData()) + } + return map[string]any{"content": []any{}}, nil + }) + if _, err := c.CallTool(ctx5(), "x", nil); err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].ElicitationID != "e1" || got[0].URL != "https://example.invalid/auth" || got[0].Mode != "url" { + t.Fatalf("handler saw %v", got) + } + }) + + t.Run("second-32042-surfaces-no-third-call", func(t *testing.T) { + var calls atomic.Int32 + c := dial32042(t, "2025-11-25", func(_ context.Context, _ []mcpclient.URLElicitation) (bool, error) { + return true, nil + }, func(n int32) (any, map[string]any) { + calls.Store(n) + return nil, rpcErr(-32042, "url elicitation required", urlElicitationData()) + }) + _, err := c.CallTool(ctx5(), "x", nil) + if err == nil || !strings.Contains(err.Error(), "-32042") { + t.Fatalf("want the second -32042 to surface, got %v", err) + } + if calls.Load() != 2 { + t.Fatalf("tools/call ran %d times, want exactly 2 (original + one retry)", calls.Load()) + } + }) + + t.Run("declined-fails-without-retry", func(t *testing.T) { + var calls atomic.Int32 + c := dial32042(t, "2025-11-25", func(_ context.Context, _ []mcpclient.URLElicitation) (bool, error) { + return false, nil + }, func(n int32) (any, map[string]any) { + calls.Store(n) + return nil, rpcErr(-32042, "url elicitation required", urlElicitationData()) + }) + _, err := c.CallTool(ctx5(), "x", nil) + if err == nil || !strings.Contains(err.Error(), "declined or expired") { + t.Fatalf("want a named decline error, got %v", err) + } + if calls.Load() != 1 { + t.Fatalf("tools/call ran %d times, want 1 (no retry after decline)", calls.Load()) + } + }) + + t.Run("handler-error-surfaces-without-retry", func(t *testing.T) { + c := dial32042(t, "2025-11-25", func(_ context.Context, _ []mcpclient.URLElicitation) (bool, error) { + return false, errors.New("the URL elicitation e1 from srv was decline") + }, func(n int32) (any, map[string]any) { + return nil, rpcErr(-32042, "url elicitation required", urlElicitationData()) + }) + _, err := c.CallTool(ctx5(), "x", nil) + if err == nil || !strings.Contains(err.Error(), "was decline") { + t.Fatalf("want the handler error to surface, got %v", err) + } + }) + + t.Run("no-handler-propagates-untouched", func(t *testing.T) { + var calls atomic.Int32 + c := dial32042(t, "2025-11-25", nil, func(n int32) (any, map[string]any) { + calls.Store(n) + return nil, rpcErr(-32042, "url elicitation required", urlElicitationData()) + }) + _, err := c.CallTool(ctx5(), "x", nil) + if err == nil || !strings.Contains(err.Error(), "-32042") { + t.Fatalf("want -32042 to propagate, got %v", err) + } + if calls.Load() != 1 { + t.Fatalf("tools/call ran %d times, want 1", calls.Load()) + } + }) +} + +func TestURLElicitationRequiredMalformed(t *testing.T) { + cases := map[string]any{ + "unparseable-data": "junk", + "empty-list": map[string]any{"elicitations": []any{}}, + "form-mode-entry": map[string]any{"elicitations": []any{map[string]any{"mode": "form", "elicitationId": "e1"}}}, + "missing-id-entry": map[string]any{"elicitations": []any{map[string]any{"mode": "url", "url": "https://example.invalid/a"}}}, + "no-elicitations": map[string]any{"other": 1}, + "data-absent": nil, + } + for name, data := range cases { + t.Run(name, func(t *testing.T) { + called := false + var calls atomic.Int32 + c := dial32042(t, "2025-11-25", func(_ context.Context, _ []mcpclient.URLElicitation) (bool, error) { + called = true + return true, nil + }, func(n int32) (any, map[string]any) { + calls.Store(n) + return nil, rpcErr(-32042, "url elicitation required", data) + }) + _, err := c.CallTool(ctx5(), "x", nil) + if err == nil || !strings.Contains(err.Error(), "-32042") { + t.Fatalf("want the original -32042 unmodified, got %v", err) + } + if called { + t.Fatal("the handler must not run for malformed data") + } + if calls.Load() != 1 { + t.Fatalf("tools/call ran %d times, want 1", calls.Load()) + } + }) + } +} + +func TestURLElicitationRequiredEraGate(t *testing.T) { + t.Run("2025-06-18-propagates", func(t *testing.T) { + called := false + c := dial32042(t, "2025-06-18", func(_ context.Context, _ []mcpclient.URLElicitation) (bool, error) { + called = true + return true, nil + }, func(n int32) (any, map[string]any) { + return nil, rpcErr(-32042, "url elicitation required", urlElicitationData()) + }) + _, err := c.CallTool(ctx5(), "x", nil) + if err == nil || !strings.Contains(err.Error(), "-32042") { + t.Fatalf("want -32042 to propagate at 2025-06-18, got %v", err) + } + if called { + t.Fatal("the handler must not run outside 2025-11-25") + } + }) + + t.Run("2026-propagates", func(t *testing.T) { + called := false + w := newWire(t, "2026-07-28", func(m string, p map[string]any) (any, map[string]any) { + switch m { + case "server/discover": + return discoverWith(map[string]any{"tools": map[string]any{}}), nil + case "tools/call": + return nil, rpcErr(-32042, "url elicitation required", urlElicitationData()) + } + return nil, nil + }) + c := dialWire(t, w, mcpclient.ForceModern, mcpclient.Options{ + OnURLElicitationRequired: func(_ context.Context, _ []mcpclient.URLElicitation) (bool, error) { + called = true + return true, nil + }, + }) + _, err := c.CallTool(ctx5(), "x", nil) + if err == nil || !strings.Contains(err.Error(), "-32042") { + t.Fatalf("want -32042 to propagate at 2026, got %v", err) + } + if called { + t.Fatal("the handler must not run at 2026") + } + }) +} diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index b2952fd5a0..d3e010a042 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -522,6 +522,16 @@ func (p *Pool) installServerHooks(opts *mcpclient.Options, ref *instanceRef) { return h.Elicit(ctx, p.cfg.Name, ref.key(), method, params) } } + if h.URLElicitation != nil { + opts.OnURLElicitationRequired = func(ctx context.Context, elicitations []mcpclient.URLElicitation) (bool, error) { + // Same budget pause as OnServerRequest: while a person or + // agent answers, the interrupted call is not using its budget. + if in := ref.ptr.Load(); in != nil { + defer in.questions.asking()() + } + return h.URLElicitation(ctx, p.cfg.Name, ref.key(), elicitations) + } + } opts.Roots = h.Roots opts.ProbeTimeout = h.ProbeTimeout opts.ServerName = p.cfg.Name @@ -1131,7 +1141,12 @@ type Hooks struct { // connection serves one key, so whoever is calling on that key is who // the server is asking. Elicit func(ctx context.Context, server, key, method string, params json.RawMessage) (any, error) - Roots []mcpclient.Root + // URLElicitation opens the URL elicitations an upstream's -32042 + // tools/call error names, parallel to Elicit: server and key say + // which connection's call was interrupted. True only when every + // entry was accepted; anything else fails the call with no retry. + URLElicitation func(ctx context.Context, server, key string, elicitations []mcpclient.URLElicitation) (bool, error) + Roots []mcpclient.Root // LogLevel is requested from every server that supports logging. LogLevel string // Protocol is the era preference for a server whose config names none. From f3cd69193c985b6d4df5f96a62391c3255d1714a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 15:15:17 -0500 Subject: [PATCH 2/2] fix(mcpx): unambiguous broker row IDs and atomic negotiated read (Codex PR #2760 findings) brokerRowID length-prefixes the (server, elicitationId) pair so server "a"/ID "b:c" and server "a:b"/ID "c" no longer collide on one broker row; OnElicitationComplete composes the same ID. The -32042 gate in CallTool now reads c.negotiatedVersion() (the atomic mirror every writer publishes) instead of the plain Negotiated field, which races reinitializeLegacy/finishLegacy writes during session recovery. Adds TestBrokerKeyingColonAmbiguity. --- pkgs/mcpx/internal/daemon/hooks.go | 26 ++++-- .../daemon/url_elicitation_32042_test.go | 87 +++++++++++++++++-- pkgs/mcpx/internal/mcpclient/client.go | 2 +- 3 files changed, 98 insertions(+), 17 deletions(-) diff --git a/pkgs/mcpx/internal/daemon/hooks.go b/pkgs/mcpx/internal/daemon/hooks.go index ea830818eb..fadc360af7 100644 --- a/pkgs/mcpx/internal/daemon/hooks.go +++ b/pkgs/mcpx/internal/daemon/hooks.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "strconv" "time" "github.com/dezren39/mcpx/internal/defaults" @@ -60,7 +61,7 @@ func (r *Registry) InstallHooks(bus *events.Bus, broker *elicit.Broker, roots [] // on it should hear so now rather than at its deadline. if r.broker != nil { _ = r.broker.Respond(elicit.Answer{ - ID: server + ":" + id, Action: elicit.Accept, By: "server:" + server, + ID: brokerRowID(server, id), Action: elicit.Accept, By: "server:" + server, }) } r.publish(events.Event{ @@ -162,6 +163,20 @@ func (r *Registry) answerServer(ctx context.Context, server, key, method string, return nil, fmt.Errorf("mcpx does not implement %s", method) } +// brokerRowID is the broker row key for a server-supplied elicitation +// ID: the (server, elicitationId) pair, length-prefixed so the encoding +// is unambiguous. Plain concatenation would collide whenever a server +// name or an elicitation ID contains ":" -- server "a" with ID "b:c" +// and server "a:b" with ID "c" would share one row, and a completion +// from one could settle the other's question. An empty elicitationId +// (a minted ID, already unique) stays bare. +func brokerRowID(server, elicitationID string) string { + if elicitationID == "" { + return elicitationID + } + return strconv.Itoa(len(server)) + ":" + server + ":" + elicitationID +} + func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, params json.RawMessage) (any, error) { var p struct { Mode string `json:"mode"` @@ -180,15 +195,12 @@ func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, para // Broker rows are keyed by ID alone, and elicitationId is the // upstream's own choice: two servers can pick the same one and the // second OpenRequest would fail on the primary key (ELI-09). A - // server-supplied ID is therefore stored server-qualified; - // OnElicitationComplete composes the same qualified ID before it + // server-supplied ID is therefore stored under brokerRowID; + // OnElicitationComplete composes the same row ID before it // responds. Minted IDs (empty elicitationId) are already unique and // stay bare. Rows opened under a bare ID before this fix are not // migrated; they expire by TTL. - brokerID := p.ElicitationID - if brokerID != "" { - brokerID = server + ":" + brokerID - } + brokerID := brokerRowID(server, p.ElicitationID) req, err := r.broker.OpenRequest(elicit.Request{ ID: brokerID, Server: server, diff --git a/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go b/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go index 74c49f1dbb..d29665c74f 100644 --- a/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go +++ b/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go @@ -52,14 +52,14 @@ func TestBrokerKeyingServerQualified(t *testing.T) { } t.Fatalf("broker row %q never appeared", id) } - waitRow("srvA:e1") - waitRow("srvB:e1") + waitRow(brokerRowID("srvA", "e1")) + waitRow(brokerRowID("srvB", "e1")) if _, ok, err := broker.Get("e1"); err != nil || ok { t.Fatalf("a bare e1 row exists (ok=%v err=%v): the collision is back", ok, err) } // Answering srvA's row settles only srvA's waiter. - if err := broker.Respond(elicit.Answer{ID: "srvA:e1", Action: elicit.Accept, By: "test"}); err != nil { + if err := broker.Respond(elicit.Answer{ID: brokerRowID("srvA", "e1"), Action: elicit.Accept, By: "test"}); err != nil { t.Fatal(err) } select { @@ -79,7 +79,7 @@ func TestBrokerKeyingServerQualified(t *testing.T) { case <-time.After(300 * time.Millisecond): } - if err := broker.Respond(elicit.Answer{ID: "srvB:e1", Action: elicit.Decline, By: "test"}); err != nil { + if err := broker.Respond(elicit.Answer{ID: brokerRowID("srvB", "e1"), Action: elicit.Decline, By: "test"}); err != nil { t.Fatal(err) } select { @@ -92,6 +92,75 @@ func TestBrokerKeyingServerQualified(t *testing.T) { } } +// Codex finding on PR #2760: the pair encoding must stay unambiguous +// when the parts themselves contain ":". Server "a" with ID "b:c" and +// server "a:b" with ID "c" collided under plain concatenation. +func TestBrokerKeyingColonAmbiguity(t *testing.T) { + if brokerRowID("a", "b:c") == brokerRowID("a:b", "c") { + t.Fatalf("row IDs collide: %q", brokerRowID("a", "b:c")) + } + broker, err := elicit.Open(filepath.Join(t.TempDir(), "elicit.db")) + if err != nil { + t.Fatal(err) + } + defer broker.Close() + r := &Registry{asks: newAskTable()} + r.InstallHooks(events.New(0), broker, nil) + + type outcome struct { + out any + err error + } + results := map[string]chan outcome{} + for _, tc := range []struct{ srv, id string }{{"a", "b:c"}, {"a:b", "c"}} { + params := json.RawMessage(`{"mode":"url","message":"sign in","url":"https://example.invalid/auth","elicitationId":"` + tc.id + `"}`) + ch := make(chan outcome, 1) + results[tc.srv] = ch + go func(srv string, ch chan<- outcome) { + out, err := r.elicitViaBroker(context.Background(), srv, "key", params) + ch <- outcome{out, err} + }(tc.srv, ch) + } + deadline := time.Now().Add(5 * time.Second) + for _, tc := range []struct{ srv, id string }{{"a", "b:c"}, {"a:b", "c"}} { + row := brokerRowID(tc.srv, tc.id) + for { + if _, ok, err := broker.Get(row); err == nil && ok { + break + } + if time.Now().After(deadline) { + t.Fatalf("broker row %q never appeared", row) + } + time.Sleep(10 * time.Millisecond) + } + } + // Settling a's row must not settle a:b's waiter. + if err := broker.Respond(elicit.Answer{ID: brokerRowID("a", "b:c"), Action: elicit.Accept, By: "test"}); err != nil { + t.Fatal(err) + } + select { + case o := <-results["a"]: + if o.err != nil { + t.Fatal(o.err) + } + case <-time.After(5 * time.Second): + t.Fatal("a waiter never returned") + } + select { + case o := <-results["a:b"]: + t.Fatalf("a:b waiter returned early with %v: an answer crossed the colon boundary", o) + case <-time.After(300 * time.Millisecond): + } + if err := broker.Respond(elicit.Answer{ID: brokerRowID("a:b", "c"), Action: elicit.Decline, By: "test"}); err != nil { + t.Fatal(err) + } + select { + case <-results["a:b"]: + case <-time.After(5 * time.Second): + t.Fatal("a:b waiter never returned") + } +} + // #2079: the -32042 handler runs each listed entry through the existing // broker path in order; every entry must accept, and the first decline // stops the flow with a named error, later entries unopened. @@ -132,8 +201,8 @@ func TestURLElicitationsViaBroker(t *testing.T) { } t.Fatalf("broker row %q never appeared", id) } - answer("srv:e1", elicit.Accept) - answer("srv:e2", elicit.Decline) + answer(brokerRowID("srv", "e1"), elicit.Accept) + answer(brokerRowID("srv", "e2"), elicit.Decline) select { case o := <-done: @@ -155,7 +224,7 @@ func TestURLElicitationsViaBroker(t *testing.T) { ok, err := r.urlElicitationsViaBroker(context.Background(), "srv", "key", els2) done2 <- outcome{ok, err} }() - answer("srv:e3", elicit.Decline) + answer(brokerRowID("srv", "e3"), elicit.Decline) select { case o := <-done2: if o.ok || o.err == nil { @@ -164,7 +233,7 @@ func TestURLElicitationsViaBroker(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("the handler never returned after the first decline") } - if _, ok, err := broker.Get("srv:e4"); err != nil || ok { - t.Fatalf("srv:e4 exists (ok=%v err=%v): a later entry was opened after a first-entry decline", ok, err) + if _, ok, err := broker.Get(brokerRowID("srv", "e4")); err != nil || ok { + t.Fatalf("srv e4 exists (ok=%v err=%v): a later entry was opened after a first-entry decline", ok, err) } } diff --git a/pkgs/mcpx/internal/mcpclient/client.go b/pkgs/mcpx/internal/mcpclient/client.go index 4973ccc858..53d24b07b0 100644 --- a/pkgs/mcpx/internal/mcpclient/client.go +++ b/pkgs/mcpx/internal/mcpclient/client.go @@ -1569,7 +1569,7 @@ func (c *Client) CallTool(ctx context.Context, name string, args any) (json.RawM // happen exactly once regardless. Malformed data, or no handler // installed, leaves the original error untouched; any other // negotiated version is untouched too. - if !retried32042 && err != nil && c.Negotiated == "2025-11-25" && + if !retried32042 && err != nil && c.negotiatedVersion() == "2025-11-25" && errors.As(err, &re) && re.Code == codeURLElicitationRequired { els, wellFormed := parseURLElicitations(re.Data) c.mu.Lock()