diff --git a/pkgs/mcpx/internal/daemon/elicit_events_test.go b/pkgs/mcpx/internal/daemon/elicit_events_test.go index 7cb5eaa952..a0b4180439 100644 --- a/pkgs/mcpx/internal/daemon/elicit_events_test.go +++ b/pkgs/mcpx/internal/daemon/elicit_events_test.go @@ -26,6 +26,7 @@ func TestElicitEventsAreSummaryOnly(t *testing.T) { defer func() { _ = broker.Close() }() r := &Registry{asks: newAskTable()} r.InstallHooks(bus, broker, nil) + noteAnswerer(t, broker) sub, _ := bus.Subscribe(events.Filter{Kinds: []string{"elicit"}}, 0) defer sub.Close() diff --git a/pkgs/mcpx/internal/daemon/hooks.go b/pkgs/mcpx/internal/daemon/hooks.go index f2ee7d14a3..22e6278ba4 100644 --- a/pkgs/mcpx/internal/daemon/hooks.go +++ b/pkgs/mcpx/internal/daemon/hooks.go @@ -223,6 +223,44 @@ func brokerRowID(server, elicitationID string) string { return strconv.Itoa(len(server)) + ":" + server + ":" + elicitationID } +// noAudience is the ask seam's truthful refusal (#2438, Phase 3 of #2434): +// the audience a question routes to has no answerer polling, so the +// request cannot be served and the server is told at once -- a -32021 +// naming the capability -- instead of waiting out the broker TTL for an +// answer nobody will give. Presence is recorded only by answerer-facing +// surfaces (the elicit CLI's list/watch, the daemon's answerer +// endpoints); absence inside that window is observed, not guessed, and +// a store error reports presence rather than inventing an absence. +func noAudience(method string, req elicit.Request) error { + aud, _ := elicit.Route(req) + capability := "elicitation" + if method == "sampling/createMessage" { + capability = "sampling" + } + return mcpclient.MissingCapabilityError( + fmt.Sprintf("Missing required client capability: no %s answerer is present for %s", aud, method), + map[string]any{capability: map[string]any{}}) +} + +// hasAnswerer reports whether anyone can answer req, so the ask seam +// refuses with -32021 only when truly nobody can (#2438). Two kinds of +// answerer exist. The call that provoked the question is one: when the +// question can be attributed to an interruptible call (req.Trace names +// it, the same correlation attach uses), it is surfaced to that call's +// caller -- inline to a modern MCP client as input_required, on the wire +// to a legacy client that declared the capability, or as an +// input-required report (exit 75, MCPX_INPUT=report) to a CLI call or +// script -- and none of those polls the broker, so broker presence +// would wrongly read as absent. Otherwise the question can only be +// answered from the broker, and recorded presence for its audience +// decides. +func (r *Registry) hasAnswerer(req elicit.Request) bool { + if req.Trace != "" { + return true + } + return r.broker.HasAudience(req, elicit.DefaultAudienceWindow) +} + func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, params json.RawMessage) (any, error) { var p struct { Mode string `json:"mode"` @@ -247,7 +285,7 @@ func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, para // stay bare. Rows opened under a bare ID before this fix are not // migrated; they expire by TTL. brokerID := brokerRowID(server, p.ElicitationID) - req, err := r.broker.OpenRequest(elicit.Request{ + req := elicit.Request{ ID: brokerID, Server: server, Mode: mode, @@ -256,7 +294,11 @@ func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, para URL: p.URL, Trace: r.askIDFor(ctx, server, key), ExpiresAt: time.Now().Add(defaults.ElicitTTL), - }) + } + if !r.hasAnswerer(req) { + return nil, noAudience("elicitation/create", req) + } + req, err := r.broker.OpenRequest(req) if err != nil { return nil, err } @@ -339,7 +381,7 @@ func (r *Registry) sampleViaBroker(ctx context.Context, server, key string, para return nil, &elicit.SamplingInvalidParams{Err: err} } - req, err := r.broker.OpenRequest(elicit.Request{ + req := elicit.Request{ Server: server, Trace: r.askIDFor(ctx, server, key), Mode: elicit.Sample, @@ -351,7 +393,11 @@ func (r *Registry) sampleViaBroker(ctx context.Context, server, key string, para Audience: elicit.ToAgent, Reason: "sampling asks a model, and the agent driving mcpx has one", ExpiresAt: time.Now().Add(defaults.ElicitTTL), - }) + } + if !r.hasAnswerer(req) { + return nil, noAudience("sampling/createMessage", req) + } + req, err := r.broker.OpenRequest(req) if err != nil { return nil, err } diff --git a/pkgs/mcpx/internal/daemon/hooks_audience_test.go b/pkgs/mcpx/internal/daemon/hooks_audience_test.go new file mode 100644 index 0000000000..495a12cb3f --- /dev/null +++ b/pkgs/mcpx/internal/daemon/hooks_audience_test.go @@ -0,0 +1,181 @@ +package daemon + +import ( + "context" + "encoding/json" + "errors" + "path/filepath" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/elicit" + "github.com/developing-today/code/pkgs/mcpx/internal/events" +) + +// The ask seam's no-audience refusal (#2438, Phase 3 of #2434): a +// question routed to an audience with no answerer polling is answered +// at once with -32021 naming the capability, instead of waiting out the +// broker TTL for an answer nobody will give. The oracle is the broker's +// own presence record: absence opens nothing, a recorded answerer opens +// the question as before. + +// audienceRig is a registry over a broker nobody has answered from yet. +func audienceRig(t *testing.T) (*Registry, *elicit.Broker) { + t.Helper() + broker, err := elicit.Open(filepath.Join(t.TempDir(), "elicit.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = broker.Close() }) + r := &Registry{asks: newAskTable()} + r.InstallHooks(events.New(0), broker, nil) + return r, broker +} + +// requiredCapabilities reads the data member of a -32021 as a client +// would: the map of capabilities it has to declare. +func requiredCapabilities(t *testing.T, err error) map[string]any { + t.Helper() + var ce interface { + RPCCode() int + RPCData() json.RawMessage + } + if !errors.As(err, &ce) { + t.Fatalf("the refusal is not a coded error: %v", err) + } + if ce.RPCCode() != -32021 { + t.Fatalf("code %d, want -32021 (-32021 MissingRequiredClientCapability)", ce.RPCCode()) + } + var body struct { + Required map[string]any `json:"requiredCapabilities"` + } + if err := json.Unmarshal(ce.RPCData(), &body); err != nil { + t.Fatalf("the -32021 data is not requiredCapabilities: %v (%s)", err, ce.RPCData()) + } + return body.Required +} + +func TestElicitWithoutAnswererIsMissingCapability(t *testing.T) { + r, broker := audienceRig(t) + _, err := r.elicitViaBroker(context.Background(), "srv", "key", + json.RawMessage(`{"mode":"form","message":"who?","requestedSchema":{"type":"object"}}`)) + required := requiredCapabilities(t, err) + if _, ok := required["elicitation"]; !ok { + t.Fatalf("requiredCapabilities %v do not name elicitation", required) + } + // Nobody was asked, so nothing may be left pending for an answerer + // that does not exist. + if ps, perr := broker.Pending(elicit.Filter{}); perr != nil || len(ps) != 0 { + t.Fatalf("pending after a no-audience refusal: %d (err %v)", len(ps), perr) + } +} + +func TestSampleWithoutAnswererIsMissingCapability(t *testing.T) { + r, broker := audienceRig(t) + _, err := r.sampleViaBroker(context.Background(), "srv", "key", + json.RawMessage(`{"messages":[{"role":"user","content":{"type":"text","text":"hi"}}],"maxTokens":7}`)) + required := requiredCapabilities(t, err) + if _, ok := required["sampling"]; !ok { + t.Fatalf("requiredCapabilities %v do not name sampling", required) + } + if ps, perr := broker.Pending(elicit.Filter{}); perr != nil || len(ps) != 0 { + t.Fatalf("pending after a no-audience refusal: %d (err %v)", len(ps), perr) + } +} + +func TestAPresentAnswererKeepsTheQuestionOpen(t *testing.T) { + r, broker := audienceRig(t) + if err := broker.NoteAnswerer(""); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := r.elicitViaBroker(context.Background(), "srv", "key", + json.RawMessage(`{"mode":"form","message":"who?","requestedSchema":{"type":"object"}}`)) + done <- err + }() + // The question reaches the broker, which is what "an answerer is + // present" buys: the ordinary await-and-answer path. + var q elicit.Request + for i := 0; i < 200 && q.ID == ""; i++ { + ps, err := broker.Pending(elicit.Filter{}) + if err != nil { + t.Fatal(err) + } + if len(ps) > 0 { + q = ps[0] + } + time.Sleep(2 * time.Millisecond) + } + if q.ID == "" { + t.Fatal("no question was opened although an answerer was present") + } + if err := broker.Respond(elicit.Answer{ID: q.ID, Action: elicit.Accept, By: "tester", Content: json.RawMessage(`{"who":"tester"}`)}); err != nil { + t.Fatal(err) + } + if err := <-done; err != nil { + t.Fatalf("the answered question failed: %v", err) + } +} + +// A question raised during an interruptible call is surfaced to that +// call's caller -- inline to an MCP client, as an input-required report +// to a CLI call or script -- so the caller is its answerer even when no +// broker poller is present. The refusal must not fire there, or a +// question the caller could answer is refused instead of surfaced. +func TestAnAttachableCallCountsAsAnAnswerer(t *testing.T) { + for _, c := range []struct { + name string + method string + params string + }{ + {"elicitation", "elicitation/create", `{"mode":"form","message":"who?","requestedSchema":{"type":"object"}}`}, + {"sampling", "sampling/createMessage", `{"messages":[{"role":"user","content":{"type":"text","text":"hi"}}],"maxTokens":7}`}, + } { + t.Run(c.name, func(t *testing.T) { + r, broker := audienceRig(t) + r.beginAsk("ask-1", "srv", "key", "") + defer r.endAsk("ask-1") + ctx := withAskCall(context.Background(), "ask-1") + done := make(chan error, 1) + go func() { + var err error + if c.method == "elicitation/create" { + _, err = r.elicitViaBroker(ctx, "srv", "key", json.RawMessage(c.params)) + } else { + _, err = r.sampleViaBroker(ctx, "srv", "key", json.RawMessage(c.params)) + } + done <- err + }() + call, ok := r.asks.get("ask-1") + if !ok { + t.Fatal("the ask call is not registered") + } + var qID, qMethod string + for i := 0; i < 500 && qID == ""; i++ { + select { + case err := <-done: + t.Fatalf("the call's question was refused instead of surfaced: %v", err) + default: + } + if qs, _ := call.snapshot(); len(qs) > 0 { + qID, qMethod = qs[0].ID, qs[0].Method + } + time.Sleep(2 * time.Millisecond) + } + if qID == "" || qMethod != c.method { + t.Fatalf("the question was not attached to the call (id %q, method %q)", qID, qMethod) + } + content := `{"who":"tester"}` + if c.method == "sampling/createMessage" { + content = `{"role":"assistant","content":{"type":"text","text":"hello"},"model":"m"}` + } + if err := broker.Respond(elicit.Answer{ID: qID, Action: elicit.Accept, By: "tester", Content: json.RawMessage(content)}); err != nil { + t.Fatal(err) + } + if err := <-done; err != nil { + t.Fatalf("the answered question failed: %v", err) + } + }) + } +} diff --git a/pkgs/mcpx/internal/daemon/hooks_sampling_test.go b/pkgs/mcpx/internal/daemon/hooks_sampling_test.go index b35462483d..886f3dfd9e 100644 --- a/pkgs/mcpx/internal/daemon/hooks_sampling_test.go +++ b/pkgs/mcpx/internal/daemon/hooks_sampling_test.go @@ -35,6 +35,7 @@ func samplingRegistry(t *testing.T) *Registry { } t.Cleanup(func() { _ = broker.Close() }) r.InstallHooks(events.New(0), broker, nil) + noteAnswerer(t, broker) return r } diff --git a/pkgs/mcpx/internal/daemon/sampling_test.go b/pkgs/mcpx/internal/daemon/sampling_test.go index 3a1d243f49..ae8cda1661 100644 --- a/pkgs/mcpx/internal/daemon/sampling_test.go +++ b/pkgs/mcpx/internal/daemon/sampling_test.go @@ -31,9 +31,21 @@ func sampleRig(t *testing.T) (*Registry, *elicit.Broker) { } t.Cleanup(func() { _ = b.Close() }) r.InstallHooks(events.New(0), b, nil) + noteAnswerer(t, b) return r, b } +// noteAnswerer records the broadest answerer presence. Every test that +// answers through Respond is simulating an answerer at the other end, +// and the ask seam only opens a question when someone is present for +// its audience (#2438). +func noteAnswerer(t *testing.T, b *elicit.Broker) { + t.Helper() + if err := b.NoteAnswerer(""); err != nil { + t.Fatal(err) + } +} + func pending(t *testing.T, b *elicit.Broker) []elicit.Request { t.Helper() ps, err := b.Pending(elicit.Filter{}) diff --git a/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go b/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go index 0c175d1e8e..d50ff039bd 100644 --- a/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go +++ b/pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go @@ -25,6 +25,7 @@ func TestBrokerKeyingServerQualified(t *testing.T) { defer func() { _ = broker.Close() }() r := &Registry{asks: newAskTable()} r.InstallHooks(events.New(0), broker, nil) + noteAnswerer(t, broker) params := json.RawMessage(`{"mode":"url","message":"sign in","url":"https://example.invalid/auth","elicitationId":"e1"}`) type outcome struct { @@ -106,6 +107,7 @@ func TestBrokerKeyingColonAmbiguity(t *testing.T) { defer func() { _ = broker.Close() }() r := &Registry{asks: newAskTable()} r.InstallHooks(events.New(0), broker, nil) + noteAnswerer(t, broker) type outcome struct { out any @@ -172,6 +174,7 @@ func TestURLElicitationsViaBroker(t *testing.T) { defer func() { _ = broker.Close() }() r := &Registry{asks: newAskTable()} r.InstallHooks(events.New(0), broker, nil) + noteAnswerer(t, broker) els := []mcpclient.URLElicitation{ {Mode: "url", URL: "https://example.invalid/a", ElicitationID: "e1", Message: "first"}, diff --git a/pkgs/mcpx/internal/e2e/conflicts_test.go b/pkgs/mcpx/internal/e2e/conflicts_test.go index e00f61ba48..040e73535e 100644 --- a/pkgs/mcpx/internal/e2e/conflicts_test.go +++ b/pkgs/mcpx/internal/e2e/conflicts_test.go @@ -99,6 +99,17 @@ func pendingQuestions(t *testing.T, e *env) []string { return ids } +// beAnswerer records answerer presence the way a real answerer does, by +// listing the broker's questions, before a test raises a question that +// only the broker can answer (one no interruptible call owns). The ask +// seam refuses such a question with -32021 when no answerer is present +// for its audience (#2438), so a test whose answerer only starts polling +// after the question was raised would see it refused, not queued. +func beAnswerer(t *testing.T, e *env) { + t.Helper() + e.run("elicit", "list") +} + func waitQuestions(t *testing.T, e *env, n int) []string { t.Helper() deadline := time.Now().Add(30 * time.Second) @@ -229,6 +240,7 @@ func TestConflicts(t *testing.T) { t.Run("mcpx/timeouts/call-budget-paused-while-a-question-is-pending", func(t *testing.T) { e := askWith(t, `{"sharing":"shared","scope":"global","callTimeout":"1s"}`) e.run("refresh") + beAnswerer(t, e) c := e.longSocketClient(t) done := make(chan map[string]any, 1) go func() { diff --git a/pkgs/mcpx/internal/e2e/nullanswer_test.go b/pkgs/mcpx/internal/e2e/nullanswer_test.go index ba1c624ed5..11df49b1d2 100644 --- a/pkgs/mcpx/internal/e2e/nullanswer_test.go +++ b/pkgs/mcpx/internal/e2e/nullanswer_test.go @@ -29,7 +29,9 @@ func TestANullSamplingAnswerIsRefusedAndTheDaemonSurvives(t *testing.T) { } // A client that declared no sampling capability, so the question goes - // to the broker, where anything that can reach the daemon may answer it. + // to the broker, where anything that can reach the daemon may answer it + // -- provided an answerer is present when it is raised (#2438). + beAnswerer(t, e) done := make(chan string, 1) go func() { b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, diff --git a/pkgs/mcpx/internal/e2e/proto_test.go b/pkgs/mcpx/internal/e2e/proto_test.go index 2ef6793e97..f5da144560 100644 --- a/pkgs/mcpx/internal/e2e/proto_test.go +++ b/pkgs/mcpx/internal/e2e/proto_test.go @@ -413,6 +413,9 @@ func TestAClientThatDeclaredNothingStillReachesTheBroker(t *testing.T) { e := askEnv(t) e.run("refresh") ep := e.endpoint(t) + // The second process below is the question's answerer; it is present + // before the question is raised, as a broker answerer must be (#2438). + beAnswerer(t, e) type outcome struct { body string diff --git a/pkgs/mcpx/internal/mcpclient/client.go b/pkgs/mcpx/internal/mcpclient/client.go index b407558608..b154f87216 100644 --- a/pkgs/mcpx/internal/mcpclient/client.go +++ b/pkgs/mcpx/internal/mcpclient/client.go @@ -1865,8 +1865,14 @@ const ( // the error's data opened before it can proceed. codeURLElicitationRequired = -32042 codeResourceNotFound = -32002 - codeInvalidParams = -32602 - codeInternalError = -32603 + // codeMissingCapability is MissingRequiredClientCapability, + // 2026-07-28. The ask seam mints it when no answerer is present for + // the audience a question routes to (#2438): the request cannot be + // served without an audience, so the server learns that instead of + // waiting out a TTL. + codeMissingCapability = -32021 + 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 @@ -1886,6 +1892,10 @@ const ( type CodedError struct { Code int Message string + // Data is the JSON-RPC error data member, when the code has one the + // client acts on -- a -32021's requiredCapabilities (#2438). Empty + // for every code that carries only a sentence. + Data json.RawMessage } func (e *CodedError) Error() string { return e.Message } @@ -1895,6 +1905,18 @@ func (e *CodedError) Error() string { return e.Message } // errors check for it by interface, with no import cycle. func (e *CodedError) RPCCode() int { return e.Code } +// RPCData is the error's data member, for the codes that carry one. +func (e *CodedError) RPCData() json.RawMessage { return e.Data } + +// MissingCapabilityError is -32021 MissingRequiredClientCapability, +// naming the capabilities the request cannot be served without. The ask +// seam uses it when no answerer is present for the audience a question +// routes to: an unmade request the server should not wait on (#2438). +func MissingCapabilityError(message string, required map[string]any) *CodedError { + data, _ := json.Marshal(map[string]any{"requiredCapabilities": required}) + return &CodedError{Code: codeMissingCapability, Message: message, Data: data} +} + // NewCodedError builds a CodedError for a spec-assigned code with no // dedicated constructor below. func NewCodedError(code int, message string) *CodedError { diff --git a/pkgs/mcpx/internal/mcpclient/missingcapability_test.go b/pkgs/mcpx/internal/mcpclient/missingcapability_test.go new file mode 100644 index 0000000000..58caa7b443 --- /dev/null +++ b/pkgs/mcpx/internal/mcpclient/missingcapability_test.go @@ -0,0 +1,28 @@ +package mcpclient + +import ( + "encoding/json" + "testing" +) + +// A -32021 minted by the ask seam must reach an upstream as -32021 with +// its requiredCapabilities, not as a sentence, and not as -32603 (#2438, +// Phase 3 of #2434). rpcErrorFor is the one place a handler error becomes +// the JSON-RPC error an upstream reads. +func TestMissingCapabilityErrorKeepsItsData(t *testing.T) { + err := MissingCapabilityError("Missing required client capability: no human answerer is present", + map[string]any{"elicitation": map[string]any{}}) + r := rpcErrorFor(err) + if r.Code != -32021 || r.Message != "Missing required client capability: no human answerer is present" { + t.Fatalf("relayed %d/%q, want -32021 with the sentence", r.Code, r.Message) + } + var body struct { + Required map[string]any `json:"requiredCapabilities"` + } + if err := json.Unmarshal(r.Data, &body); err != nil { + t.Fatalf("data is not requiredCapabilities: %v (%s)", err, r.Data) + } + if _, ok := body.Required["elicitation"]; !ok { + t.Fatalf("requiredCapabilities %v do not name elicitation", body.Required) + } +} diff --git a/pkgs/mcpx/internal/mcpclient/samplingera.go b/pkgs/mcpx/internal/mcpclient/samplingera.go index 5559097d5d..8dffb49ce4 100644 --- a/pkgs/mcpx/internal/mcpclient/samplingera.go +++ b/pkgs/mcpx/internal/mcpclient/samplingera.go @@ -2,6 +2,7 @@ package mcpclient import ( "context" + "encoding/json" "errors" ) @@ -70,7 +71,14 @@ func (c *Client) negotiatedVersion() string { func rpcErrorFor(err error) *rpcError { var coded interface{ RPCCode() int } if errors.As(err, &coded) { - return &rpcError{Code: coded.RPCCode(), Message: err.Error()} + r := &rpcError{Code: coded.RPCCode(), Message: err.Error()} + // A code that carries a data member keeps it (#2438: a -32021's + // requiredCapabilities is what the client acts on). + var datad interface{ RPCData() json.RawMessage } + if errors.As(err, &datad) { + r.Data = datad.RPCData() + } + return r } return &rpcError{Code: -32603, Message: err.Error()} }