From 6b36ff57d799f5cdb5c84daac025163b5a3f355d Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Thu, 12 Nov 2026 13:28:43 -0600 Subject: [PATCH] mcpx: correlate -32042 retries with the suspended call via requestState (#2897) Both -32042 triggers (entry and in-loop ErrNoPush) mint a signed requestState bound to the call and the request binding and carry it in the error data; no state mintable means no -32042 rather than an uncorrelated retry invitation. The broker keeps the pending questions (no Abandon, #2080 preserved). mcpx client echoes the token on its out-of-band retry in params._meta under dev.mcpx/requestState -- 2025-11-25 defines no requestState parameter and strict frame validation rejects one -- and mcpserver resumeOf accepts that vehicle alongside the top-level field. Exactly-once proven by tests: post-completion and pre-completion retries resume the original call (began == 1) on both server triggers, and the client retry carries the token. Core salvaged verbatim from uncommitted changes found parked in the laptop primary clone; completed and verified by lane any-a, task 8931. --- pkgs/mcpx/internal/mcpclient/client.go | 58 +++++++++++++++++++ .../mcpclient/url_elicitation_32042_test.go | 33 +++++++++++ pkgs/mcpx/internal/mcpserver/ask.go | 35 ++++++++--- pkgs/mcpx/internal/mcpserver/url_required.go | 10 +++- .../internal/mcpserver/url_required_test.go | 58 +++++++++++++++++++ 5 files changed, 184 insertions(+), 10 deletions(-) diff --git a/pkgs/mcpx/internal/mcpclient/client.go b/pkgs/mcpx/internal/mcpclient/client.go index 829c83dd98..293e94ab96 100644 --- a/pkgs/mcpx/internal/mcpclient/client.go +++ b/pkgs/mcpx/internal/mcpclient/client.go @@ -708,6 +708,63 @@ 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 +} + +// MetaRequestState is the _meta key a -32042 requestState is echoed +// under on the retry (#2897). Repeated here rather than imported from +// mcpserver so the two halves of mcpx do not depend on each other. +// 2025-11-25 defines no requestState request parameter, so the token +// travels in _meta, the open extension object: a top-level field would +// fail strict schema validation of the retry frame. +const MetaRequestState = "dev.mcpx/requestState" + +// withRequestState adds the requestState to a request's params _meta so +// the retry resumes the original call rather than starting a second +// one. 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, ok := m["_meta"]; ok { + _ = json.Unmarshal(raw, &meta) + } + meta[MetaRequestState] = b + mb, err := json.Marshal(meta) + if err != nil { + return params + } + m["_meta"] = mb + 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 @@ -1757,6 +1814,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/url_elicitation_32042_test.go b/pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go index 8ed393aa33..1ac0fdd3fc 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[mcpclient.MetaRequestState].(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..3a2e69142c 100644 --- a/pkgs/mcpx/internal/mcpserver/ask.go +++ b/pkgs/mcpx/internal/mcpserver/ask.go @@ -103,13 +103,30 @@ func (s *Server) canAsk(ctx context.Context, c *Conn, p Peer) bool { p.eligibleURLElicitationRequired() } +// MetaRequestState is the _meta key a 2025-11-25 host echoes a -32042 +// requestState under on its retry (#2897). That revision's request +// schemas define no requestState parameter -- the modern MRTR field +// exists only in 2026-07-28 -- so the token travels in _meta, the open +// extension object every revision carries, under mcpx's own prefix +// (compare MetaSession). A host that validated its frames against the +// 2025-11-25 schema would reject a top-level requestState it does not +// define; _meta it must accept. +const MetaRequestState = "dev.mcpx/requestState" + // resumeOf reads the two fields a modern client sends when answering. func resumeOf(params json.RawMessage) (state string, answers map[string]json.RawMessage, ok bool) { 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 { + return "", nil, false } - if json.Unmarshal(params, &p) != nil || p.RequestState == "" { + if p.RequestState == "" { + _ = json.Unmarshal(p.Meta[MetaRequestState], &p.RequestState) + } + if p.RequestState == "" { return "", nil, false } return p.RequestState, p.InputResponses, true @@ -202,8 +219,10 @@ 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 { - return resp + if state, err := s.states().mint(callID, requestBinding(req)); err == nil { + if resp := urlRequiredResponse(req, peer, out.Questions, state); resp != nil { + return resp + } } } sendable := sendableTo(out.Questions, peer) @@ -305,11 +324,13 @@ 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 { - if len(answers) > 0 { - _ = s.Ask.Reply(ctx, callID, answers) + if state, err := s.states().mint(callID, requestBinding(req)); err == nil { + if resp := urlRequiredResponse(req, peer, sendable, state); resp != nil { + if len(answers) > 0 { + _ = s.Ask.Reply(ctx, callID, answers) + } + return resp } - return resp } } if len(answers) > 0 { diff --git a/pkgs/mcpx/internal/mcpserver/url_required.go b/pkgs/mcpx/internal/mcpserver/url_required.go index c5055a0929..4e6d22debd 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 requestState on that retry so it resumes this call rather than starting +// a second upstream operation: in params._meta under MetaRequestState at +// 2025-11-25 (that revision defines no requestState parameter), or as the +// top-level requestState field where a later revision defines one. +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..ad24c2ea73 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"}, + "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"}, + "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) { @@ -125,6 +163,26 @@ func TestURLRequiredWhenPushFailsInLoop(t *testing.T) { if asker.abandoned != 0 { t.Errorf("abandoned %d, want 0", asker.abandoned) } + // The in-loop -32042 must carry the same correlation as the entry + // trigger's (#2897): a host retrying with this requestState after + // completing the URL flow out of band resumes the original call + // instead of starting a second upstream operation. + if out.Error.Data.RequestState == "" { + t.Fatal("in-loop -32042 must carry a requestState that correlates the host retry") + } + asker.answers["u3"] = json.RawMessage(`{"action":"accept"}`) + // The legacy wire vehicle: 2025-11-25 defines no requestState + // parameter, so the host echoes the token in _meta (MetaRequestState). + retry := 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{mcpserver.MetaRequestState: out.Error.Data.RequestState}, + })) + if retry == nil || retry.Error != nil { + t.Fatalf("correlated in-loop retry failed: %+v", retry) + } + if asker.began != 1 { + t.Fatalf("retried operation began %d times, want exactly once", asker.began) + } } func TestURLRequiredWhenPushFailsBehindFormQuestion(t *testing.T) {