diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 8d04489f5..9b20507d3 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -347,7 +347,19 @@ after which every run went `-p` for up to a day; that mark is no longer written or read, and one left on disk does nothing. The helper answers the bridge's `initialize` only once the prompt is -shown, so the bridge waits for it `tuiInitWait` (`ReadyWait` and twice a +shown and Claude Code has listed the tools of magpie's MCP server. Claude +Code connects its MCP servers beside its prompt, and a first message sent +at the prompt was answered without the agent's tools (MinhuWang on X, a pi +agent whose tool server was slow to load; with the server held 8s, the +real 2.1.309 answered as if it had none). So `startRun` gives +`claude-mcp-helper` a third argument, `listed` in the run's temp folder, +which it writes once it has answered `tools/list` +(`claudetui.MCPCommand`), and `ready` reads that path from the run's +`--mcp-config` (`mcpListed`) and waits for the file as well as the prompt, +within the same 45 seconds; past them it ends, saying the tools weren't +listed. The model test's and warm-up's runs have no such server and don't +wait. `TestShimFirstMessageWaitsForTools` and +`TestToolsListedFileWritten` hold it. So the bridge waits for it `tuiInitWait` (`ReadyWait` and twice a control request's 10s), not the 10s of any other control request. With 10s, a Claude Code slower than that to start (2 vCPU in Docker) was ended as the helper waited, and every try was answered 502 "Claude Code has diff --git a/internal/claudebridge/mcp.go b/internal/claudebridge/mcp.go index fc03b0fc3..529ab9e7d 100644 --- a/internal/claudebridge/mcp.go +++ b/internal/claudebridge/mcp.go @@ -52,17 +52,26 @@ type callbackResponse struct { var listWait = 5 * time.Second // RunMCP runs the hidden stdio MCP subprocess. args are callback URL and tools -// JSON path, or, for an agent whose MCP servers are set once for every run +// JSON path, and for Claude Code's interactive mode a file written once +// Claude Code has listed the tools, which its first message waits for +// (claudetui.MCPCommand); or, for an agent whose MCP servers are set once for every run // (Grok), MAGPIE_MCP_CALLBACK and MAGPIE_MCP_TOOLS in the environment it // hands down. It intentionally implements only the MCP methods Claude Code needs. func RunMCP(args []string) error { if len(args) == 0 && os.Getenv("MAGPIE_MCP_CALLBACK") != "" { args = []string{os.Getenv("MAGPIE_MCP_CALLBACK"), os.Getenv("MAGPIE_MCP_TOOLS")} } - if len(args) != 2 { + if len(args) != 2 && len(args) != 3 { return errors.New("claude MCP helper expects callback URL and tools file") } callbackURL, toolsPath := args[0], args[1] + var listedOnce sync.Once + listedFile := func() {} + if len(args) == 3 { + listedFile = func() { + listedOnce.Do(func() { _ = os.WriteFile(args[2], nil, 0o600) }) + } + } if !strings.HasPrefix(callbackURL, "http://") && !strings.HasPrefix(callbackURL, "https://") { // the file magpie wrote it in, which keeps its token off the // command line @@ -198,6 +207,11 @@ func RunMCP(args []string) error { response["result"] = result } respond(response) + if req.Method == "tools/list" { + // after the answer: Claude Code has the tools as the + // interactive mode's first message is sent + listedFile() + } }(req) } return in.Err() diff --git a/internal/claudebridge/mcp_test.go b/internal/claudebridge/mcp_test.go index d413eeb14..ed3e2ec78 100644 --- a/internal/claudebridge/mcp_test.go +++ b/internal/claudebridge/mcp_test.go @@ -89,3 +89,60 @@ func TestNewToolsListedBeforeTheAnswer(t *testing.T) { } inW.Close() } + +// Told a file for it, the helper writes it once it has answered Claude +// Code's tools/list, and not before: the interactive mode's first message +// waits for it (claudetui.MCPCommand; MinhuWang on X). +func TestToolsListedFileWritten(t *testing.T) { + dir := t.TempDir() + toolsPath := filepath.Join(dir, "tools.json") + os.WriteFile(toolsPath, []byte(`[{"name":"read","inputSchema":{"type":"object"}}]`), 0o600) + listed := filepath.Join(dir, "listed") + inR, inW, _ := os.Pipe() + outR, outW, _ := os.Pipe() + oldIn, oldOut := os.Stdin, os.Stdout + os.Stdin, os.Stdout = inR, outW + defer func() { os.Stdin, os.Stdout = oldIn, oldOut }() + ended := make(chan error, 1) + go func() { ended <- RunMCP([]string{"http://127.0.0.1:9/x", toolsPath, listed}); outW.Close() }() + sc := bufio.NewScanner(outR) + next := func() map[string]any { + t.Helper() + got := make(chan map[string]any, 1) + go func() { + var m map[string]any + if sc.Scan() { + _ = json.Unmarshal(sc.Bytes(), &m) + } + got <- m + }() + select { + case m := <-got: + return m + case err := <-ended: + t.Fatalf("the helper ended: %v", err) + case <-time.After(3 * time.Second): + t.Fatal("no message from the helper") + } + return nil + } + inW.Write([]byte(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}` + "\n")) + next() + if _, err := os.Stat(listed); err == nil { + t.Fatal("written before the tools were listed") + } + inW.Write([]byte(`{"jsonrpc":"2.0","id":2,"method":"tools/list"}` + "\n")) + if m := next(); m["id"] != float64(2) { + t.Fatalf("tools/list answered %v", m) + } + for by := time.Now().Add(3 * time.Second); ; { + if _, err := os.Stat(listed); err == nil { + break + } + if time.Now().After(by) { + t.Fatal("the listed file wasn't written") + } + time.Sleep(10 * time.Millisecond) + } + inW.Close() +} diff --git a/internal/claudetui/command.go b/internal/claudetui/command.go index 282e947dd..80c400c86 100644 --- a/internal/claudetui/command.go +++ b/internal/claudetui/command.go @@ -24,3 +24,11 @@ type WSL struct { // Projects is Claude Code's projects folder, as Windows reads it Projects string `json:"projects"` } + +// MCPCommand is the hidden subcommand of magpie's tool server, the MCP +// server a run's --mcp-config names "magpie" (claudebridge.RunMCP). Its +// arguments are the callback's file, the tools' file and, for the +// interactive mode, a file it writes once Claude Code has listed its +// tools: the first message waits for it (MinhuWang on X: a first message +// sent before then had none of the agent's tools). +const MCPCommand = "claude-mcp-helper" diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index 8090cca4d..ccf9c42d6 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -99,6 +99,10 @@ type shim struct { // what Claude Code is given for it tap *tap env []string + + // listed is the file magpie's tool server writes once Claude Code has + // listed its tools (mcpListed), "" for a run without it + listed string } // Run runs Claude Code at path, args being the bridge's `claude -p` ones, @@ -126,7 +130,7 @@ func Run(args []string) error { return fmt.Errorf("Claude Code's interactive mode didn't run: %s", why) } args = interactiveArgs(pargs[len(wslArgs(wsl)):]) - s := &shim{out: os.Stdout, changed: make(chan struct{}, 1), rowsCh: make(chan struct{}, 1), exited: make(chan struct{}), wsl: wsl} + s := &shim{out: os.Stdout, changed: make(chan struct{}, 1), rowsCh: make(chan struct{}, 1), exited: make(chan struct{}), wsl: wsl, listed: mcpListed(args)} resume := "" for i, a := range args { if a == "--resume" && i+1 < len(args) { @@ -326,6 +330,7 @@ var firstRun = regexp.MustCompile(`Security notes:.*Press Enter to continue`) func (s *shim) ready() error { deadline := time.After(readyWait) answered := 0 + prompted := false var yesAt, downAt time.Time for { p := s.plain() @@ -370,7 +375,16 @@ func (s *shim) ready() error { s.clearScreen() _, _ = io.WriteString(s.pty, "\r") case strings.Contains(p, "❯ "): - // drawn: a moment for its input to be listened to + if !s.toolsListed() { + // drawn before Claude Code has its MCP servers' tools: it + // connects them as the prompt shows, and a message sent + // now is answered without the agent's tools, which + // magpie's tool server carries (MinhuWang on X) + prompted = true + break + } + // drawn: a moment for its input to be listened to, and for + // the tools just listed to be taken up time.Sleep(300 * time.Millisecond) return nil } @@ -380,11 +394,49 @@ func (s *shim) ready() error { case <-s.exited: return fmt.Errorf("Claude Code ended before it showed its prompt (%v): %s", s.exit, s.lastScreen()) case <-deadline: + if prompted { + return fmt.Errorf("Claude Code showed its prompt, but hadn't listed the tools of magpie's tool server in %s", readyWait) + } return fmt.Errorf("Claude Code showed no prompt in %s: %s", readyWait, s.lastScreen()) } } } +// toolsListed is whether Claude Code has listed magpie's tool server's +// tools, or the run has no such server. +func (s *shim) toolsListed() bool { + if s.listed == "" { + return true + } + _, err := os.Stat(s.listed) + return err == nil +} + +// mcpListed is the file magpie's tool server (MCPCommand) is told, in the +// --mcp-config of args, to write once Claude Code has listed its tools; +// "" when it isn't told one. +func mcpListed(args []string) string { + for i, a := range args { + if a != "--mcp-config" || i+1 >= len(args) { + continue + } + var c struct { + Servers map[string]struct { + Args []string `json:"args"` + } `json:"mcpServers"` + } + if json.Unmarshal([]byte(args[i+1]), &c) != nil { + continue + } + for _, srv := range c.Servers { + if len(srv.Args) == 4 && srv.Args[0] == MCPCommand { + return srv.Args[3] + } + } + } + return "" +} + func (s *shim) emit(v any) { b, _ := json.Marshal(v) s.outMu.Lock() diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 5fc230073..2093a9530 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -132,6 +132,13 @@ func fakeClaude(args []string) { _, _ = tapped.WriteString(`{"tap":"on"}` + "\n") } } + // FAKE_MCP_DELAY: magpie's tool server is listed that long after the + // prompt shows, as Claude Code connects its MCP servers beside it; a + // message sent before then is answered without the tools + listed := mcpListed(args) + if d, err := time.ParseDuration(os.Getenv("FAKE_MCP_DELAY")); err == nil && listed != "" { + time.AfterFunc(d, func() { _ = os.WriteFile(listed, nil, 0o600) }) + } streams := 0 fmt.Print("\r\n❯ ") // the prompt's words; an image file's path pasted alone is read a @@ -188,6 +195,11 @@ func fakeClaude(args []string) { line := typed.String() typed.Reset() mu.Unlock() + if listed != "" { + if _, err := os.Stat(listed); err != nil { + line += " (without magpie's tools)" + } + } if tapped != nil { streams++ n := streams @@ -479,6 +491,28 @@ func TestShimNeverPrints(t *testing.T) { } } +// The first message waits for Claude Code to have listed the tools of +// magpie's tool server, which it connects as its prompt shows: sent at +// the prompt, it was answered without the agent's tools (MinhuWang on X, +// a pi agent, the MCP server slow to load). +func TestShimFirstMessageWaitsForTools(t *testing.T) { + listed := filepath.Join(t.TempDir(), "listed") + cfg, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{ + "magpie": map[string]any{"command": "magpie", "args": []string{MCPCommand, "callback", "tools.json", listed}}, + }}) + args := slices.Clone(pArgs) + args[slices.Index(args, "--mcp-config")+1] = string(cfg) + start := time.Now() + out := runShim(t, []string{"FAKE_MCP_DELAY=2s"}, append([]string{fakePath(t)}, args...), []string{"hello"}, 3) + b, _ := json.Marshal(out[1]["message"]) + if out[1]["type"] != "assistant" || !strings.Contains(string(b), "echo: hello") || strings.Contains(string(b), "without magpie's tools") { + t.Fatalf("the first turn said %s", b) + } + if d := time.Since(start); d < 2*time.Second { + t.Fatalf("answered in %s, before the tools were listed", d) + } +} + func TestShimTrustsWhenTold(t *testing.T) { out := runShim(t, []string{"FAKE_TRUST=1", TrustEnv + "=1"}, append([]string{fakePath(t)}, pArgs...), []string{"hello"}, 3) if out[0]["subtype"] != "init" || out[1]["type"] != "assistant" { diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 3721b6541..d084342a9 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -813,8 +813,10 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, cleanup() return nil, nil, err } + // the interactive mode's first message waits for the file the tool + // server writes once Claude Code has listed its tools (MinhuWang on X) mcpConfig, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{ - "magpie": map[string]any{"command": exe, "args": []string{"claude-mcp-helper", callbackPath, toolsPath}}, + "magpie": map[string]any{"command": exe, "args": []string{claudetui.MCPCommand, callbackPath, toolsPath, filepath.Join(tmp, "listed")}}, }}) args := claudeCLIArgs(model, string(mcpConfig), req.Effort, req.WebSearch) if req.ThinkOff {