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
62 changes: 60 additions & 2 deletions pkgs/mcpx/internal/daemon/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"os"
"path/filepath"
"strconv"
"time"

"github.com/dezren39/mcpx/internal/defaults"
Expand Down Expand Up @@ -60,7 +61,7 @@ func (r *Registry) InstallHooks(bus *events.Bus, broker *elicit.Broker, roots []
// on it should hear so now rather than at its deadline.
if r.broker != nil {
_ = r.broker.Respond(elicit.Answer{
ID: id, Action: elicit.Accept, By: "server:" + server,
ID: brokerRowID(server, id), Action: elicit.Accept, By: "server:" + server,
})
}
r.publish(events.Event{
Expand All @@ -70,6 +71,9 @@ func (r *Registry) InstallHooks(bus *events.Bus, broker *elicit.Broker, roots []
},
Elicit: r.answerServer,
}
if broker != nil {
hooks.URLElicitation = r.urlElicitationsViaBroker
}
r.upstreamHooks(hooks)
// Under r.mu: Reload reads r.hooks and replaces r.pools under it.
r.mu.Lock()
Expand Down Expand Up @@ -159,6 +163,20 @@ func (r *Registry) answerServer(ctx context.Context, server, key, method string,
return nil, fmt.Errorf("mcpx does not implement %s", method)
}

// brokerRowID is the broker row key for a server-supplied elicitation
// ID: the (server, elicitationId) pair, length-prefixed so the encoding
// is unambiguous. Plain concatenation would collide whenever a server
// name or an elicitation ID contains ":" -- server "a" with ID "b:c"
// and server "a:b" with ID "c" would share one row, and a completion
// from one could settle the other's question. An empty elicitationId
// (a minted ID, already unique) stays bare.
func brokerRowID(server, elicitationID string) string {
if elicitationID == "" {
return elicitationID
}
return strconv.Itoa(len(server)) + ":" + server + ":" + elicitationID
}

func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, params json.RawMessage) (any, error) {
var p struct {
Mode string `json:"mode"`
Expand All @@ -174,8 +192,17 @@ func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, para
if p.Mode == "url" {
mode = elicit.URL
}
// Broker rows are keyed by ID alone, and elicitationId is the
// upstream's own choice: two servers can pick the same one and the
// second OpenRequest would fail on the primary key (ELI-09). A
// server-supplied ID is therefore stored under brokerRowID;
// OnElicitationComplete composes the same row ID before it
// responds. Minted IDs (empty elicitationId) are already unique and
// 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{
ID: p.ElicitationID,
ID: brokerID,
Server: server,
Mode: mode,
Message: p.Message,
Expand Down Expand Up @@ -209,6 +236,37 @@ func (r *Registry) elicitViaBroker(ctx context.Context, server, key string, para
return out, nil
}

// urlElicitationsViaBroker opens the URL elicitations an upstream's
// -32042 tools/call error named (#2079, Phase 2 of #2077). Each entry
// runs the existing elicitation/create path with synthesised url-mode
// params -- no second URL flow -- sequentially, because elicitViaBroker
// blocks on the broker answer. Every entry must be accepted before the
// client retries the call; the first decline, cancel, or expiry stops
// here with a named error and the remaining entries are never opened.
func (r *Registry) urlElicitationsViaBroker(ctx context.Context, server, key string, elicitations []mcpclient.URLElicitation) (bool, error) {
if r.broker == nil {
return false, fmt.Errorf("mcpx cannot open URL elicitations from %s: no broker", server)
}
for _, e := range elicitations {
params, err := json.Marshal(map[string]any{
"mode": "url", "url": e.URL, "elicitationId": e.ElicitationID, "message": e.Message,
})
if err != nil {
return false, err
}
out, err := r.elicitViaBroker(ctx, server, key, params)
if err != nil {
return false, err
}
res, _ := out.(map[string]any)
action, _ := res["action"].(string)
if action != string(elicit.Accept) {
return false, fmt.Errorf("the URL elicitation %s from %s was %s", e.ElicitationID, server, action)
}
}
return true, nil
}

// sampleViaBroker turns a sampling request into a question for whatever is
// driving mcpx.
//
Expand Down
239 changes: 239 additions & 0 deletions pkgs/mcpx/internal/daemon/url_elicitation_32042_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
package daemon

import (
"context"
"encoding/json"
"path/filepath"
"strings"
"testing"
"time"

"github.com/dezren39/mcpx/internal/elicit"
"github.com/dezren39/mcpx/internal/events"
"github.com/dezren39/mcpx/internal/mcpclient"
)

// #2079 / ELI-09: broker rows are keyed by ID alone, and elicitationId
// is the upstream's own choice, so server-supplied IDs are stored
// server-qualified. Two upstreams choosing the same elicitationId hold
// distinct rows, and an answer settles only its own server's row.
func TestBrokerKeyingServerQualified(t *testing.T) {
broker, err := elicit.Open(filepath.Join(t.TempDir(), "elicit.db"))
if err != nil {
t.Fatal(err)
}
defer broker.Close()
r := &Registry{asks: newAskTable()}
r.InstallHooks(events.New(0), broker, nil)

params := json.RawMessage(`{"mode":"url","message":"sign in","url":"https://example.invalid/auth","elicitationId":"e1"}`)
type outcome struct {
out any
err error
}
results := map[string]chan outcome{}
for _, srv := range []string{"srvA", "srvB"} {
ch := make(chan outcome, 1)
results[srv] = ch
go func(srv string, ch chan<- outcome) {
out, err := r.elicitViaBroker(context.Background(), srv, "key", params)
ch <- outcome{out, err}
}(srv, ch)
}

waitRow := func(id string) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if _, ok, err := broker.Get(id); err == nil && ok {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("broker row %q never appeared", id)
}
waitRow(brokerRowID("srvA", "e1"))
waitRow(brokerRowID("srvB", "e1"))
if _, ok, err := broker.Get("e1"); err != nil || ok {
t.Fatalf("a bare e1 row exists (ok=%v err=%v): the collision is back", ok, err)
}

// Answering srvA's row settles only srvA's waiter.
if err := broker.Respond(elicit.Answer{ID: brokerRowID("srvA", "e1"), Action: elicit.Accept, By: "test"}); err != nil {
t.Fatal(err)
}
select {
case o := <-results["srvA"]:
if o.err != nil {
t.Fatal(o.err)
}
if a, _ := o.out.(map[string]any)["action"].(string); a != "accept" {
t.Fatalf("srvA outcome = %v, want accept", o.out)
}
case <-time.After(5 * time.Second):
t.Fatal("srvA waiter never returned")
}
select {
case o := <-results["srvB"]:
t.Fatalf("srvB waiter returned early with %v: an answer crossed servers", o)
case <-time.After(300 * time.Millisecond):
}

if err := broker.Respond(elicit.Answer{ID: brokerRowID("srvB", "e1"), Action: elicit.Decline, By: "test"}); err != nil {
t.Fatal(err)
}
select {
case o := <-results["srvB"]:
if a, _ := o.out.(map[string]any)["action"].(string); a != "decline" {
t.Fatalf("srvB outcome = %v, want decline", o.out)
}
case <-time.After(5 * time.Second):
t.Fatal("srvB waiter never returned")
}
}

// Codex finding on PR #2760: the pair encoding must stay unambiguous
// when the parts themselves contain ":". Server "a" with ID "b:c" and
// server "a:b" with ID "c" collided under plain concatenation.
func TestBrokerKeyingColonAmbiguity(t *testing.T) {
if brokerRowID("a", "b:c") == brokerRowID("a:b", "c") {
t.Fatalf("row IDs collide: %q", brokerRowID("a", "b:c"))
}
broker, err := elicit.Open(filepath.Join(t.TempDir(), "elicit.db"))
if err != nil {
t.Fatal(err)
}
defer broker.Close()
r := &Registry{asks: newAskTable()}
r.InstallHooks(events.New(0), broker, nil)

type outcome struct {
out any
err error
}
results := map[string]chan outcome{}
for _, tc := range []struct{ srv, id string }{{"a", "b:c"}, {"a:b", "c"}} {
params := json.RawMessage(`{"mode":"url","message":"sign in","url":"https://example.invalid/auth","elicitationId":"` + tc.id + `"}`)
ch := make(chan outcome, 1)
results[tc.srv] = ch
go func(srv string, ch chan<- outcome) {
out, err := r.elicitViaBroker(context.Background(), srv, "key", params)
ch <- outcome{out, err}
}(tc.srv, ch)
}
deadline := time.Now().Add(5 * time.Second)
for _, tc := range []struct{ srv, id string }{{"a", "b:c"}, {"a:b", "c"}} {
row := brokerRowID(tc.srv, tc.id)
for {
if _, ok, err := broker.Get(row); err == nil && ok {
break
}
if time.Now().After(deadline) {
t.Fatalf("broker row %q never appeared", row)
}
time.Sleep(10 * time.Millisecond)
}
}
// Settling a's row must not settle a:b's waiter.
if err := broker.Respond(elicit.Answer{ID: brokerRowID("a", "b:c"), Action: elicit.Accept, By: "test"}); err != nil {
t.Fatal(err)
}
select {
case o := <-results["a"]:
if o.err != nil {
t.Fatal(o.err)
}
case <-time.After(5 * time.Second):
t.Fatal("a waiter never returned")
}
select {
case o := <-results["a:b"]:
t.Fatalf("a:b waiter returned early with %v: an answer crossed the colon boundary", o)
case <-time.After(300 * time.Millisecond):
}
if err := broker.Respond(elicit.Answer{ID: brokerRowID("a:b", "c"), Action: elicit.Decline, By: "test"}); err != nil {
t.Fatal(err)
}
select {
case <-results["a:b"]:
case <-time.After(5 * time.Second):
t.Fatal("a:b waiter never returned")
}
}

// #2079: the -32042 handler runs each listed entry through the existing
// broker path in order; every entry must accept, and the first decline
// stops the flow with a named error, later entries unopened.
func TestURLElicitationsViaBroker(t *testing.T) {
broker, err := elicit.Open(filepath.Join(t.TempDir(), "elicit.db"))
if err != nil {
t.Fatal(err)
}
defer broker.Close()
r := &Registry{asks: newAskTable()}
r.InstallHooks(events.New(0), broker, nil)

els := []mcpclient.URLElicitation{
{Mode: "url", URL: "https://example.invalid/a", ElicitationID: "e1", Message: "first"},
{Mode: "url", URL: "https://example.invalid/b", ElicitationID: "e2", Message: "second"},
}
type outcome struct {
ok bool
err error
}
done := make(chan outcome, 1)
go func() {
ok, err := r.urlElicitationsViaBroker(context.Background(), "srv", "key", els)
done <- outcome{ok, err}
}()

answer := func(id string, action elicit.Action) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if _, ok, err := broker.Get(id); err == nil && ok {
if err := broker.Respond(elicit.Answer{ID: id, Action: action, By: "test"}); err != nil {
t.Fatal(err)
}
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("broker row %q never appeared", id)
}
answer(brokerRowID("srv", "e1"), elicit.Accept)
answer(brokerRowID("srv", "e2"), elicit.Decline)

select {
case o := <-done:
if o.ok || o.err == nil || !strings.Contains(o.err.Error(), "e2") || !strings.Contains(o.err.Error(), "decline") {
t.Fatalf("want (false, a named decline error for e2), got %v", o)
}
case <-time.After(5 * time.Second):
t.Fatal("the handler never returned")
}

// First-entry decline: the second entry is never opened. (Fresh IDs:
// broker IDs are primary keys, so a settled row cannot be reopened.)
els2 := []mcpclient.URLElicitation{
{Mode: "url", URL: "https://example.invalid/c", ElicitationID: "e3", Message: "third"},
{Mode: "url", URL: "https://example.invalid/d", ElicitationID: "e4", Message: "fourth"},
}
done2 := make(chan outcome, 1)
go func() {
ok, err := r.urlElicitationsViaBroker(context.Background(), "srv", "key", els2)
done2 <- outcome{ok, err}
}()
answer(brokerRowID("srv", "e3"), elicit.Decline)
select {
case o := <-done2:
if o.ok || o.err == nil {
t.Fatalf("want (false, error) on first decline, got %v", o)
}
case <-time.After(5 * time.Second):
t.Fatal("the handler never returned after the first decline")
}
if _, ok, err := broker.Get(brokerRowID("srv", "e4")); err != nil || ok {
t.Fatalf("srv e4 exists (ok=%v err=%v): a later entry was opened after a first-entry decline", ok, err)
}
}
Loading
Loading