diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 49e0de9fa..09d6c1ca0 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -53,6 +53,18 @@ to use an http:// proxy. The `settings.json` env that magpie writes for the user's own Claude Code sessions leaves a SOCKS proxy out (see [Providers and accounts](providers-accounts.md)). +The helper offers each of the client's tools under `bridgeToolName` +(`bridgeTools`), which Claude Code calls `mcp__magpie__`. Claude Code +keeps only `[A-Za-z0-9_-]` of an MCP tool's name, so a name it would change +(`spawn.agent`, `fs/read`), one longer than 51 (64 with the prefix) or one +ending as a changed name ends (`_` and 12 hex digits) is cut, made of those +characters and given a hash of the whole name: unique (`a.b` and `a_b` +stay apart), the same in every run, so a resumed session, the history +(`renderParts`) and the tool-choice line (`toolChoiceAsk`) name it as the +run was offered it. `subscriptionRun.names` (`bridgeNames`) maps it back +to the declared name in `toolStart`, for streamed and whole messages, and +in `mcpCall` (#2649). + The run's MCP server is magpie itself (`magpie claude-mcp-helper`, `internal/claudebridge`), which hands each tool call back to the gateway at `POST /_magpie/claude-mcp/` (`mcpCall`), where the call is @@ -535,6 +547,7 @@ go test -tags nogui ./internal/claudecode/ -count=1 go test -tags nogui ./internal/gateway/ -run '^TestClaudeCodeGivenTheBridgeForASOCKSProxy$' -count=1 go test -tags nogui ./internal/provider/ -run '^TestClaudeSignInBridgesASOCKSProxy$' -count=1 go test -tags nogui ./internal/netproxy/ -run '^TestEnvForBunWith' -count=1 +go test -tags nogui ./internal/gateway/ -run '^TestClaudeToolNamesComeBackAsDeclared$' -count=1 go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn' -count=1 ``` diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 448dc0e52..0532121e3 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -148,6 +148,9 @@ type subscriptionRun struct { // the tools its agent was told of, as it started and since tools map[string]bool + // names is the caller's name of each tool by the name the run's agent + // has it under (bridgeToolName), for those it differs: under r.mu + names map[string]string mu sync.Mutex // sending is held across a send to the segment and taken before it is @@ -739,6 +742,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, cmd.Stdout, cmd.Stderr = stdoutW, stderrW run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, schema: len(req.Format.schema()) > 0, pending: map[string]chan mcpToolResult{}, stdin: stdin, owner: owner, effort: req.Effort, sessions: sessions} + run.names = bridgeNames(req.Tools) run.safeguardBeta = req.SafeguardBeta run.clientMarks = req.clientCache != nil run.lean = req.leanPrompt @@ -2118,6 +2122,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { } name, ok := strings.CutPrefix(name, "mcp__magpie__") r.mu.Lock() + name = declaredName(r.names, name) search := r.search != nil && name == r.searchName r.mu.Unlock() // magpie answers its own web search, as Claude Code does @@ -2777,7 +2782,53 @@ func historyEnd(msgs []Message) int { // "Bash is disabled for this session, in subagents as well as here.", // which the model takes for a fact and gives up (#958). func bridgeName(name string) string { - return "mcp__magpie__" + name + return "mcp__magpie__" + bridgeToolName(name) +} + +// bridgeToolName is the name the MCP helper offers a tool of the caller's +// under. Claude Code takes an MCP tool's name as [A-Za-z0-9_-] only, with +// mcp__magpie__ before it in at most 64: it made "spawn.agent" its +// spawn_agent, which the client never offered (#2649). A name it would +// change, or one ending as a changed name ends, is told apart by a hash of +// it, the same in every run, so a resumed session and a conversation's +// history name the tool as before; declaredName maps it back. +func bridgeToolName(name string) string { + if bridgeToolNameOK.MatchString(name) && !bridgeToolNameHashed.MatchString(name) { + return name + } + sum := sha256.Sum256([]byte(name)) + short := bridgeToolNameBad.ReplaceAllString(name, "_") + if len(short) > 38 { + short = short[:38] + } + return short + "_" + hex.EncodeToString(sum[:6]) +} + +var ( + bridgeToolNameOK = regexp.MustCompile(`^[A-Za-z0-9_-]{1,51}$`) + bridgeToolNameBad = regexp.MustCompile(`[^A-Za-z0-9_-]`) + bridgeToolNameHashed = regexp.MustCompile(`_[0-9a-f]{12}$`) +) + +// bridgeNames is the caller's name of each of tools by the name the MCP +// helper offers it under, for those that differ (bridgeToolName). +func bridgeNames(tools []Tool) map[string]string { + names := map[string]string{} + for _, t := range tools { + if b := bridgeToolName(t.Name); b != t.Name { + names[b] = t.Name + } + } + return names +} + +// declaredName is the caller's name of the tool the run's agent called +// name, by the names it was offered under (bridgeNames). +func declaredName(names map[string]string, name string) string { + if n, ok := names[name]; ok { + return n + } + return name } // offeredTools is the names of the caller's tools, whose past calls a run @@ -3442,6 +3493,7 @@ func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) { return } run.mu.Lock() + call.Name = declaredName(run.names, call.Name) search, searchName := run.search, run.searchName run.mu.Unlock() if search != nil && call.Name == searchName { @@ -4088,6 +4140,10 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from for _, t := range req.Tools { run.tools[t.Name] = true } + if run.names == nil { + run.names = map[string]string{} + } + maps.Copy(run.names, bridgeNames(req.Tools)) run.mu.Unlock() } if err == nil { @@ -4318,7 +4374,7 @@ func bridgeTools(req *Request) []bridgeTool { if len(schema) == 0 { schema = json.RawMessage(`{"type":"object","properties":{}}`) } - tools = append(tools, bridgeTool{Name: t.Name, Description: t.Description, InputSchema: schema}) + tools = append(tools, bridgeTool{Name: bridgeToolName(t.Name), Description: t.Description, InputSchema: schema}) } return tools } diff --git a/internal/gateway/claude_tool_names_test.go b/internal/gateway/claude_tool_names_test.go new file mode 100644 index 000000000..223f9ad64 --- /dev/null +++ b/internal/gateway/claude_tool_names_test.go @@ -0,0 +1,159 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "runtime" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// #2649 (tsy0716): a tool the client named "spawn.agent" came back as +// "spawn_agent", a tool it never offered: Claude Code takes an MCP tool's +// name as [A-Za-z0-9_-] only, and changed it. Each tool is offered under a +// name Claude Code keeps, unique and short enough with mcp__magpie__ before +// it, and its calls are handed back under the name the client declared, on +// every API the bridge serves, streamed or whole. +func TestClaudeToolNamesComeBackAsDeclared(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + long := "tools.example.com/" + strings.Repeat("very_long_segment.", 5) + "end" + declared := []string{"spawn.agent", "fs/read", "has space", long, "a.b", "a_b"} + + dir := t.TempDir() + offered := filepath.Join(dir, "offered") + // Claude Code as it treats an MCP tool's name: what isn't + // [A-Za-z0-9_-] becomes "_". It calls every tool it was offered, in + // one message of its stream, or whole when asked to. + script := `#!/bin/sh +for a in "$@"; do + case "$a" in *mcpServers*) tp=$(printf '%s' "$a" | sed 's/.*"\([^"]*tools\.json\)".*/\1/');; esac +done +while read -r line; do + grep -o '"name":"[^"]*"' "$tp" | sed 's/"name":"//; s/"$//' > ` + offered + ` + names=$(tr -c 'A-Za-z0-9_\n-' '_' < ` + offered + `) + case "$line" in + *wholeplease*) + content="" i=0 + for n in $names; do + i=$((i+1)) + [ -n "$content" ] && content="$content," + content="$content"'{"type":"tool_use","id":"toolu_'$i'","name":"mcp__magpie__'$n'","input":{"n":'$i'}}' + done + echo '{"type":"assistant","message":{"id":"m","model":"claude-sonnet-5","content":['"$content"'],"stop_reason":"tool_use","usage":{"output_tokens":3}}}' ;; + *) + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}' + i=0 + for n in $names; do + echo '{"type":"stream_event","event":{"type":"content_block_start","index":'$i',"content_block":{"type":"tool_use","id":"toolu_'$i'","name":"mcp__magpie__'$n'"}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":'$i',"delta":{"type":"input_json_delta","partial_json":"{\"n\":'$i'}"}}}' + echo '{"type":"stream_event","event":{"type":"content_block_stop","index":'$i'}}' + i=$((i+1)) + done + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":3}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' ;; + esac +done +` + testenv.Program(t, filepath.Join(dir, "claude"), script) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + runsEndWithTest(t, dir) + + tools := func(f func(string) string) string { + var out []string + for _, n := range declared { + q, _ := json.Marshal(n) + out = append(out, f(string(q))) + } + return strings.Join(out, ",") + } + bodies := map[provider.Protocol]func(say string, stream bool) string{ + provider.Anthropic: func(say string, stream bool) string { + return fmt.Sprintf(`{"model":"claude-sonnet-5","max_tokens":100,"stream":%t,"messages":[{"role":"user","content":%q}],"tools":[%s]}`, stream, say, + tools(func(q string) string { return `{"name":` + q + `,"input_schema":{"type":"object"}}` })) + }, + provider.Chat: func(say string, stream bool) string { + return fmt.Sprintf(`{"model":"claude-sonnet-5","stream":%t,"messages":[{"role":"user","content":%q}],"tools":[%s]}`, stream, say, + tools(func(q string) string { + return `{"type":"function","function":{"name":` + q + `,"parameters":{"type":"object"}}}` + })) + }, + provider.Responses: func(say string, stream bool) string { + return fmt.Sprintf(`{"model":"claude-sonnet-5","stream":%t,"input":%q,"tools":[%s]}`, stream, say, + tools(func(q string) string { return `{"type":"function","name":` + q + `,"parameters":{"type":"object"}}` })) + }, + } + paths := map[provider.Protocol]string{provider.Anthropic: "/v1/messages", provider.Chat: "/v1/chat/completions", provider.Responses: "/v1/responses"} + nameRe := regexp.MustCompile(`"name":"((?:[^"\\]|\\.)*)"`) + validRe := regexp.MustCompile(`^[A-Za-z0-9_-]{1,51}$`) + p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}} + for _, from := range []provider.Protocol{provider.Anthropic, provider.Chat, provider.Responses} { + for _, stream := range []bool{false, true} { + for _, say := range []string{"call them", "call them wholeplease"} { + what := fmt.Sprintf("%s stream=%t %q", from, stream, say) + s := New() + body := bodies[from](say, stream) + rec := httptest.NewRecorder() + var u Usage + if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", paths[from], strings.NewReader(body)), from, p, "claude-sonnet-5", []byte(body), &u); code != 200 { + s.subscription.abortAll() + t.Fatalf("%s: %d %s", what, code, msg) + } + s.subscription.abortAll() + var got []string + for _, m := range nameRe.FindAllStringSubmatch(rec.Body.String(), -1) { + var n string + _ = json.Unmarshal([]byte(`"`+m[1]+`"`), &n) + if !slices.Contains(got, n) { + got = append(got, n) + } + } + slices.Sort(got) + want := slices.Sorted(slices.Values(declared)) + if !slices.Equal(got, want) { + t.Errorf("%s: the calls name %q, want the declared %q: %s", what, got, want, rec.Body) + } + b, _ := os.ReadFile(offered) + names := strings.Fields(strings.ReplaceAll(string(b), " ", "\x00")) + seen := map[string]bool{} + for _, n := range names { + if !validRe.MatchString(n) || seen[n] { + t.Errorf("%s: Claude Code was offered %q, which isn't a valid, unique MCP tool name of at most 51: %q", what, n, names) + } + seen[n] = true + } + if len(names) != len(declared) { + t.Errorf("%s: offered %d tools, want %d: %q", what, len(names), len(declared), names) + } + } + } + } + + // the run is told the client's earlier calls, and its tool choice, + // under the names it was offered them by + req := &Request{Tools: []Tool{{Name: "a.b"}, {Name: "a_b"}, {Name: long}}, ToolChoice: "name:a.b"} + offer := bridgeTools(req) + if len(offer) != 1 || !validRe.MatchString(offer[0].Name) || offer[0].Name == "a_b" { + t.Fatalf("tool_choice a.b offers %+v", offer) + } + if got, want := toolChoiceAsk(req), "You must call the mcp__magpie__"+offer[0].Name+" tool."; !strings.Contains(got, want) { + t.Errorf("tool choice %q, want %q", got, want) + } + var text strings.Builder + renderParts(nil, &text, []Part{{Kind: ToolCall, ID: "c1", Name: "a.b", Args: json.RawMessage(`{}`)}, {Kind: ToolCall, ID: "c2", Name: long, Args: json.RawMessage(`{}`)}}, offeredTools(req.Tools)) + if !strings.Contains(text.String(), "[tool call mcp__magpie__"+offer[0].Name+" id=c1 ") { + t.Errorf("history tells a.b otherwise than it is offered (%s): %q", offer[0].Name, text.String()) + } + if !strings.Contains(text.String(), "[tool call mcp__magpie__"+bridgeToolName(long)+" id=c2 ") || len("mcp__magpie__"+bridgeToolName(long)) > 64 { + t.Errorf("history tells the long name as %q", text.String()) + } +}