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
1 change: 1 addition & 0 deletions pkgs/mcpx/internal/daemon/elicit_events_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
54 changes: 50 additions & 4 deletions pkgs/mcpx/internal/daemon/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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,
Expand All @@ -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
}
Expand Down Expand Up @@ -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,
Expand All @@ -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
}
Expand Down
181 changes: 181 additions & 0 deletions pkgs/mcpx/internal/daemon/hooks_audience_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
1 change: 1 addition & 0 deletions pkgs/mcpx/internal/daemon/hooks_sampling_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
12 changes: 12 additions & 0 deletions pkgs/mcpx/internal/daemon/sampling_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{})
Expand Down
3 changes: 3 additions & 0 deletions pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"},
Expand Down
12 changes: 12 additions & 0 deletions pkgs/mcpx/internal/e2e/conflicts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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() {
Expand Down
4 changes: 3 additions & 1 deletion pkgs/mcpx/internal/e2e/nullanswer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions pkgs/mcpx/internal/e2e/proto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading