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
58 changes: 58 additions & 0 deletions pkgs/mcpx/internal/mcpclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
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[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
Expand Down
35 changes: 28 additions & 7 deletions pkgs/mcpx/internal/mcpserver/ask.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
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 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
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
58 changes: 58 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"},
"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) {
Expand Down Expand Up @@ -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) {
Expand Down
Loading