claudetui: the first message waits for Claude Code to list magpie's tools (MinhuWang on X)

MinhuWang (X, 2116836405548916907): in the interactive mode the first
message can go before MCP has loaded, and then has none of pi's tools.

Cause: the helper's ready() took the drawn "❯ " prompt as ready. Claude
Code connects its MCP servers beside the prompt, so a message pasted at
once was answered with no mcp__magpie__ tools. Reproduced with the real
Claude Code 2.1.309 (sandbox HOME, a copy of the owner's account): an MCP
server held 8s before answering initialize got "NOTOOL" for "what is the
secret word, use your tool".

Fix: startRun gives claude-mcp-helper a third argument, a `listed` file in
the run's temp folder, which RunMCP writes after it has answered
tools/list. The helper finds that path in the run's --mcp-config
(mcpListed) and ready() waits for it as well as the prompt, inside the
same ReadyWait (45s); past it the run ends saying the tools weren't
listed. Runs without that server (warm-up, model test) don't wait.

Run (mote, at this tree):
- go test ./internal/claudetui ./internal/claudebridge: ok
- go test -run 'Claude|MCP|Bridge' ./internal/gateway: ok
- real Claude Code 2.1.309 here, a sandbox HOME with a copy of the
  account's credentials, the new helper and the real claude-mcp-helper
  behind an 8s sleep: initialize answered at 12.7s, the first turn called
  mcp__magpie__pi_secret and answered "The secret word is PELICAN".
  Without the sleep: answered at 2.1s, same answer. 2.1.309 sends
  server/discover before initialize; the helper's method-not-found answer
  is taken and initialize follows.

Broken by hand: toolsListed returning true made
TestShimFirstMessageWaitsForTools red ("echo: hello (without magpie's
tools)"); RunMCP not writing the file made TestToolsListedFileWritten
red.

Not tried: Claude Code in WSL (the path is the gateway's Windows temp
path, handed to magpie.exe as the callback path is); a Claude Code that
lists tools only on its first request (2.1.309 lists them at start),
which would now wait 45s and fail saying so instead of answering
without tools; the full gateway suite (run after the next commits).
This commit is contained in:
yetone
2026-11-01 23:26:57 +08:00
parent 79f83798fd
commit bee3ea6753
7 changed files with 185 additions and 6 deletions
+13 -1
View File
@@ -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
+16 -2
View File
@@ -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()
+57
View File
@@ -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()
}
+8
View File
@@ -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"
+54 -2
View File
@@ -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()
+34
View File
@@ -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" {
+3 -1
View File
@@ -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 {