Skip to content
Closed
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
52 changes: 50 additions & 2 deletions pkgs/mcpx/internal/mcpclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the task relay token across the correlated retry

For a legacy task-required tool that returns -32042 with a requestState, callers requesting progress can lose notifications after the retry. The first callToolAsLegacyTask invocation unregisters its relay through defer done(), and this second invocation registers a newly generated progress token. Since the retry now resumes the original operation rather than starting another one, progress emitted against the original token is rejected by acceptProgress in relay.go. Keep the relay registration and progress token alive across the bounded retry, as the plain-call path does.

Useful? React with 👍 / 👎.

} else {
err = rerr
}
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion pkgs/mcpx/internal/mcpclient/tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 33 additions & 0 deletions pkgs/mcpx/internal/mcpclient/url_elicitation_32042_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 18 additions & 3 deletions pkgs/mcpx/internal/mcpserver/ask.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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)
}
Expand Down
10 changes: 7 additions & 3 deletions pkgs/mcpx/internal/mcpserver/url_required.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,12 @@ func urlQuestionsOf(qs []Question) []Question {
// the required elicitationId ("mcpx-<id>") 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
Expand All @@ -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
}
Expand Down
38 changes: 38 additions & 0 deletions pkgs/mcpx/internal/mcpserver/url_required_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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) {
Expand Down
Loading