diff --git a/pkgs/mcpx/internal/mcpclient/client.go b/pkgs/mcpx/internal/mcpclient/client.go index 829c83dd98..efcf929cd2 100644 --- a/pkgs/mcpx/internal/mcpclient/client.go +++ b/pkgs/mcpx/internal/mcpclient/client.go @@ -708,6 +708,53 @@ func (c *Client) SetSessionSettledHook(fn func()) { c.mu.Unlock() } +// requestStateOf returns the requestState a -32042 error's data carries, +// the server's handle for the still-suspended call (#2897), or "". +func requestStateOf(err error) string { + var re *rpcError + if !errors.As(err, &re) { + return "" + } + var d struct { + RequestState string `json:"requestState"` + } + if json.Unmarshal(re.Data, &d) != nil { + return "" + } + return d.RequestState +} + +// withRequestState adds the server-specific correlation handle in _meta, +// which legacy request schemas allow extensions to use. A server that sent +// none (or params that are not an object) is left as is. +func withRequestState(params json.RawMessage, state string) json.RawMessage { + if state == "" { + return params + } + m := map[string]json.RawMessage{} + if json.Unmarshal(params, &m) != nil { + return params + } + b, err := json.Marshal(state) + if err != nil { + return params + } + meta := map[string]json.RawMessage{} + if raw := m["_meta"]; len(raw) > 0 { + _ = json.Unmarshal(raw, &meta) + } + meta["mcpx/requestState"] = b + m["_meta"], err = json.Marshal(meta) + if err != nil { + return params + } + out, err := json.Marshal(m) + if err != nil { + return params + } + return out +} + // 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 @@ -1707,14 +1754,14 @@ func (c *Client) CallTool(ctx context.Context, name string, args any) (json.RawM // task answer is polled to its terminal result before returning. support := c.resolveTaskSupport(name) if support == taskSupportRequired && c.modernEra() == EraLegacy { - raw, err := c.callToolAsLegacyTask(ctx, name, args) + raw, err := c.callToolAsLegacyTask(ctx, name, args, "") if err != nil { // A -32042 can surface from the task-augmented call itself // or from tasks/result at the end of the poll; it gets the // same one-shot URL-elicitation recovery as the plain path // below (#1556 Codex review). if retry, rerr := c.urlElicitationRetry(ctx, name, err); retry { - raw, err = c.callToolAsLegacyTask(ctx, name, args) + raw, err = c.callToolAsLegacyTask(ctx, name, args, requestStateOf(err)) } else { err = rerr } @@ -1757,6 +1804,7 @@ func (c *Client) CallTool(ctx context.Context, name string, args any) (json.RawM retry, rerr := c.urlElicitationRetry(ctx, name, err) if retry { retried32042 = true + params = withRequestState(params, requestStateOf(err)) continue } err = rerr diff --git a/pkgs/mcpx/internal/mcpclient/tasks.go b/pkgs/mcpx/internal/mcpclient/tasks.go index 84404270cd..b03e408ebe 100644 --- a/pkgs/mcpx/internal/mcpclient/tasks.go +++ b/pkgs/mcpx/internal/mcpclient/tasks.go @@ -202,13 +202,14 @@ type legacyTask struct { // way: task-augmented tools/call, tasks/get polls, tasks/result for the // terminal payload. Faults surface through tasks/result, whose error is // the server's own rpcError -- the client's existing error shape. -func (c *Client) callToolAsLegacyTask(ctx context.Context, name string, args any) (json.RawMessage, error) { +func (c *Client) callToolAsLegacyTask(ctx context.Context, name string, args any, requestState string) (json.RawMessage, error) { params, err := json.Marshal(map[string]any{ "name": name, "arguments": args, "task": map[string]any{}, }) if err != nil { return nil, err } + params = withRequestState(params, requestState) // The relay a downstream caller attached rides this call exactly as // it rides the plain path: beginRelay merges its _meta (progress // token, trace) into the request and keeps its callbacks registered diff --git a/pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go b/pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go index 8ed393aa33..269e095c71 100644 --- a/pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go +++ b/pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go @@ -38,6 +38,39 @@ func dial32042(t *testing.T, rev string, handler mcpclient.URLElicitationHandler return dialWire(t, w, mcpclient.ForceLegacy, mcpclient.Options{OnURLElicitationRequired: handler}) } +// #2897: the retry carries the requestState the -32042 handed out, so the +// server resumes the suspended call instead of starting a second one. +func TestURLElicitationRetryCarriesRequestState(t *testing.T) { + var seen []string + var n atomic.Int32 + w := newWire(t, "2025-11-25", func(m string, p map[string]any) (any, map[string]any) { + switch m { + case "initialize": + return initResult("2025-11-25", nil), nil + case "tools/call": + meta, _ := p["_meta"].(map[string]any) + st, _ := meta["mcpx/requestState"].(string) + seen = append(seen, st) + if n.Add(1) == 1 { + d := urlElicitationData() + d["requestState"] = "tok-1" + return nil, rpcErr(-32042, "url elicitation required", d) + } + return map[string]any{"content": []any{}}, nil + } + return nil, nil + }) + c := dialWire(t, w, mcpclient.ForceLegacy, mcpclient.Options{OnURLElicitationRequired: func(context.Context, []mcpclient.URLElicitation) (bool, error) { + return true, nil + }}) + if _, err := c.CallTool(ctx5(), "x", nil); err != nil { + t.Fatal(err) + } + if len(seen) != 2 || seen[0] != "" || seen[1] != "tok-1" { + t.Fatalf("requestState per tools/call = %q, want [\"\" \"tok-1\"]", seen) + } +} + func TestURLElicitationRequiredRetry(t *testing.T) { t.Run("accepted-then-retry-succeeds-exactly-once", func(t *testing.T) { var got []mcpclient.URLElicitation diff --git a/pkgs/mcpx/internal/mcpserver/ask.go b/pkgs/mcpx/internal/mcpserver/ask.go index cf0cfe7c64..6fcd0450e0 100644 --- a/pkgs/mcpx/internal/mcpserver/ask.go +++ b/pkgs/mcpx/internal/mcpserver/ask.go @@ -108,8 +108,15 @@ func resumeOf(params json.RawMessage) (state string, answers map[string]json.Raw var p struct { RequestState string `json:"requestState"` InputResponses map[string]json.RawMessage `json:"inputResponses"` + Meta map[string]json.RawMessage `json:"_meta"` } - if json.Unmarshal(params, &p) != nil || p.RequestState == "" { + if json.Unmarshal(params, &p) != nil { + return "", nil, false + } + if p.RequestState == "" { + _ = json.Unmarshal(p.Meta["mcpx/requestState"], &p.RequestState) + } + if p.RequestState == "" { return "", nil, false } return p.RequestState, p.InputResponses, true @@ -202,7 +209,11 @@ func (s *Server) viaAsk(ctx context.Context, c *Conn, req request, peer Peer) *r // completes them out of band and retries, mirroring the client // flow of #2079. if senderFrom(ctx) == nil && !c.canPush() { - if resp := urlRequiredResponse(req, peer, out.Questions); resp != nil { + state, err := s.states().mint(callID, requestBinding(req)) + if err != nil { + return fail(codeInternal, err.Error()) + } + if resp := urlRequiredResponse(req, peer, out.Questions, state); resp != nil { return resp } } @@ -305,7 +316,11 @@ func (s *Server) viaAsk(ctx context.Context, c *Conn, req request, peer Peer) *r // elicitation.url. Answer -32042 with this call's pending // URL questions instead of waiting out the timeout and // failing generically; the broker keeps the questions. - if resp := urlRequiredResponse(req, peer, sendable); resp != nil { + state, err := s.states().mint(callID, requestBinding(req)) + if err != nil { + return fail(codeInternal, err.Error()) + } + if resp := urlRequiredResponse(req, peer, sendable, state); resp != nil { if len(answers) > 0 { _ = s.Ask.Reply(ctx, callID, answers) } diff --git a/pkgs/mcpx/internal/mcpserver/url_required.go b/pkgs/mcpx/internal/mcpserver/url_required.go index c5055a0929..9e6f022b3c 100644 --- a/pkgs/mcpx/internal/mcpserver/url_required.go +++ b/pkgs/mcpx/internal/mcpserver/url_required.go @@ -53,8 +53,12 @@ func urlQuestionsOf(qs []Question) []Question { // the required elicitationId ("mcpx-") where the upstream sent // none. The caller returns the response WITHOUT abandoning the call: // the broker keeps the questions, the host completes them out of -// band and retries, mirroring the client-side flow of #2079. -func urlRequiredResponse(req request, p Peer, qs []Question) *response { +// band and retries, mirroring the client-side flow of #2079. The host must +// echo the token as _meta["mcpx/requestState"] on that retry (or as the +// protocol requestState field) so it resumes this call rather than starting a +// second upstream operation. A retry before completion remains on this call +// and receives -32042 again; it never silently begins duplicate work. +func urlRequiredResponse(req request, p Peer, qs []Question, requestState string) *response { urls := urlQuestionsOf(qs) if !p.eligibleURLElicitationRequired() || len(urls) == 0 { return nil @@ -67,7 +71,7 @@ func urlRequiredResponse(req request, p Peer, qs []Question) *response { } els = append(els, params) } - data, err := json.Marshal(map[string]any{"elicitations": els}) + data, err := json.Marshal(map[string]any{"elicitations": els, "requestState": requestState}) if err != nil { return nil } diff --git a/pkgs/mcpx/internal/mcpserver/url_required_test.go b/pkgs/mcpx/internal/mcpserver/url_required_test.go index 755534b203..4f83011f30 100644 --- a/pkgs/mcpx/internal/mcpserver/url_required_test.go +++ b/pkgs/mcpx/internal/mcpserver/url_required_test.go @@ -26,6 +26,7 @@ type urlRequiredReply struct { ElicitationID string `json:"elicitationId"` Message string `json:"message"` } `json:"elicitations"` + RequestState string `json:"requestState"` } `json:"data"` } `json:"error"` Result map[string]any `json:"result"` @@ -90,6 +91,43 @@ func TestURLRequiredWhenNoChannelToAskOn(t *testing.T) { if asker.abandoned != 0 { t.Errorf("the call must NOT be abandoned: the broker keeps the questions (abandoned %d)", asker.abandoned) } + if out.Error.Data.RequestState == "" { + t.Fatal("-32042 must carry a requestState that correlates the host retry") + } + + // A retry that arrives before out-of-band completion remains suspended on + // the original call and receives -32042 again; it does not start a duplicate. + early := s.Handle(context.Background(), mcpserver.Request(2, "tools/call", map[string]any{ + "name": "mcpx_call", "arguments": map[string]any{"namespace": "x", "tool": "y"}, + "_meta": map[string]any{"mcpx/requestState": out.Error.Data.RequestState}, + })) + if early == nil || early.Error == nil || early.Error.Code != -32042 { + t.Fatalf("retry before completion must remain -32042, got %+v", early) + } + earlyData, _ := json.Marshal(early.Error.Data) + var earlyReply struct { + RequestState string `json:"requestState"` + } + if err := json.Unmarshal(earlyData, &earlyReply); err != nil { + t.Fatal(err) + } + if asker.began != 1 { + t.Fatalf("early retry began operation %d times, want exactly once", asker.began) + } + + // The host completed the URL flow out of band. Retrying with the latest + // token resumes the original Asker call; it must not invoke the operation again. + asker.answers["u1"] = json.RawMessage(`{"action":"accept"}`) + retry := s.Handle(context.Background(), mcpserver.Request(3, "tools/call", map[string]any{ + "name": "mcpx_call", "arguments": map[string]any{"namespace": "x", "tool": "y"}, + "_meta": map[string]any{"mcpx/requestState": earlyReply.RequestState}, + })) + if retry == nil || retry.Error != nil { + t.Fatalf("correlated retry failed: %+v", retry) + } + if asker.began != 1 { + t.Fatalf("retried operation began %d times, want exactly once", asker.began) + } } func TestURLRequiredListsOnlyURLQuestions(t *testing.T) {