Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5846 fix(agent): stop launching CodeBuddy with MCP disabled (#6556)
Bohan Jiang9914d510402d
diff --git a/server/internal/daemon/runtime_mcp.go b/server/internal/daemon/runtime_mcp.goindex 9e48f2362c..d3519c7e10 100644--- a/server/internal/daemon/runtime_mcp.go+++ b/server/internal/daemon/runtime_mcp.go@@ -3,6 +3,7 @@ package daemonimport ("bytes""encoding/json"+ "errors""fmt""os""path/filepath"@@ -77,6 +78,167 @@ func mergeRuntimeAndAgentMcpConfig(provider string, agentConfig json.RawMessage)return raw, nil}+// codebuddyUserMcpConfigPath returns the user-scope MCP config file CodeBuddy+// actually reads.+//+// CodeBuddy is a Claude Code fork but resolves its own config, so `~/.claude.json`+// is never consulted. Its config directory is `$CODEBUDDY_CONFIG_DIR`, defaulting+// to `~/.codebuddy`, and the user-scope MCP file is the FIRST of these that+// exists — the list is a fallback chain, not a merge:+//+// <configDir>/.mcp.json (what `codebuddy mcp add --scope user` writes)+// <configDir>/mcp.json+// ~/.codebuddy.json+//+// When none exist the first candidate is returned so the caller's read fails+// with os.ErrNotExist and is treated as "no runtime servers", matching the+// other providers. Verified against CodeBuddy 2.x by writing each file in turn+// and reading back `codebuddy mcp list`.+func codebuddyUserMcpConfigPath(home string) string {+ configDir := strings.TrimSpace(os.Getenv("CODEBUDDY_CONFIG_DIR"))+ if configDir == "" {+ configDir = filepath.Join(home, ".codebuddy")+ }+ candidates := []string{+ filepath.Join(configDir, ".mcp.json"),+ filepath.Join(configDir, "mcp.json"),+ filepath.Join(home, ".codebuddy.json"),+ }+ for _, candidate := range candidates {+ if info, err := os.Stat(candidate); err == nil && !info.IsDir() {+ return candidate+ }+ }+ return candidates[0]+}++// unmarshalRuntimeMcpConfig decodes one runtime's config file. "jsonc" is JSON+// with comments and trailing commas, which CodeBuddy accepts in its MCP files —+// parsing those as strict JSON would drop every server behind a single `//`.+func unmarshalRuntimeMcpConfig(raw []byte, format string) (map[string]any, error) {+ var cfg map[string]any+ switch format {+ case "toml":+ if err := toml.Unmarshal(raw, &cfg); err != nil {+ return nil, fmt.Errorf("parse runtime MCP config: %w", err)+ }+ case "jsonc":+ stripped, err := stripJSONC(raw)+ if err != nil {+ return nil, fmt.Errorf("parse runtime MCP config: %w", err)+ }+ if err := json.Unmarshal(stripped, &cfg); err != nil {+ return nil, fmt.Errorf("parse runtime MCP config: %w", err)+ }+ default:+ if err := json.Unmarshal(raw, &cfg); err != nil {+ return nil, fmt.Errorf("parse runtime MCP config: %w", err)+ }+ }+ return cfg, nil+}++// stripJSONC rewrites JSONC into strict JSON: `//` and `/* */` comments become+// spaces and a single trailing comma before `}` / `]` is dropped. String+// literals are copied verbatim, so a `//` or a comma inside a command argument+// survives.+//+// Output is always the same length as the input — comments and the dropped+// comma are blanked, never deleted — so a parse-error offset still points at+// the byte the user actually wrote.+//+// Only the LAST comma before a closer is blanked, so genuinely malformed input+// stays malformed: `[1,,,]` does not silently become `[1]`. This is a+// pragmatic subset of JSONC covering what CodeBuddy's MCP files use in+// practice; anything it cannot repair is reported as a parse error rather than+// guessed at.+//+// An unterminated `/*` is an error rather than a blank-to-EOF, so the Agent >+// MCP tab cannot list servers out of a file CodeBuddy itself rejects. Verified:+// the CLI reports "No MCP servers configured" for both an unterminated comment+// and the `/*/` near-miss, where the opener's `*` must not double as the+// closer's.+func stripJSONC(raw []byte) ([]byte, error) {+ out := make([]byte, 0, len(raw))+ // Offset into out of the one comma still eligible for removal, or -1.+ // Reset by any value token, so only a genuinely trailing comma is dropped.+ lastComma := -1+ inString := false+ escaped := false++ for i := 0; i < len(raw); i++ {+ c := raw[i]++ if inString {+ out = append(out, c)+ switch {+ case escaped:+ escaped = false+ case c == '\\':+ escaped = true+ case c == '"':+ inString = false+ }+ continue+ }++ switch {+ case c == '"':+ inString = true+ lastComma = -1+ out = append(out, c)+ case c == '/' && i+1 < len(raw) && raw[i+1] == '/':+ // Blank through end of line, preserving the newline itself.+ for i < len(raw) && raw[i] != '\n' {+ out = append(out, ' ')+ i+++ }+ if i < len(raw) {+ out = append(out, raw[i])+ }+ case c == '/' && i+1 < len(raw) && raw[i+1] == '*':+ // Consume the opener first so `/*/` cannot reuse its own `*` as the+ // closer's, then blank the body, newlines included, so line numbers+ // and the total byte count both survive.+ out = append(out, ' ', ' ')+ i += 2+ closed := false+ for i < len(raw) {+ if raw[i] == '*' && i+1 < len(raw) && raw[i+1] == '/' {+ out = append(out, ' ', ' ')+ i++ // consume '*'; the loop's i++ consumes '/'+ closed = true+ break+ }+ if raw[i] == '\n' {+ out = append(out, '\n')+ } else {+ out = append(out, ' ')+ }+ i+++ }+ if !closed {+ return nil, errors.New("unterminated block comment")+ }+ case c == ',':+ lastComma = len(out)+ out = append(out, c)+ case c == '}' || c == ']':+ if lastComma >= 0 {+ out[lastComma] = ' '+ }+ lastComma = -1+ out = append(out, c)+ case c == ' ' || c == '\t' || c == '\n' || c == '\r':+ out = append(out, c)+ default:+ lastComma = -1+ out = append(out, c)+ }+ }+ return out, nil+}+// loadRuntimeMcpServerConfigs returns full, secret-bearing runtime MCP entries// for task-local merging. Callers must never send the result to the server or// logs; the public capabilities endpoint continues to use the redacted summary@@ -89,8 +251,14 @@ func loadRuntimeMcpServerConfigs(provider string) (map[string]any, bool, error)var path, key, format stringswitch provider {- case "claude", "codebuddy":+ case "claude":path, key, format = filepath.Join(home, ".claude.json"), "mcpServers", "json"+ // codebuddy is deliberately absent. CodeBuddy loads its own user, project+ // and local scopes on every launch (codebuddy.go never passes+ // --strict-mcp-config), and a managed entry already wins a same-name+ // collision, so the daemon pre-merging them would only duplicate what the+ // CLI does natively — while losing the scope precedence and the approval+ // gate that protects project-scope servers.case "codex":codexHome := strings.TrimSpace(os.Getenv("CODEX_HOME"))if codexHome == "" {@@ -122,13 +290,9 @@ func loadRuntimeMcpServerConfigs(provider string) (map[string]any, bool, error)servers := map[string]any{}raw, err := os.ReadFile(path)if err == nil {- var cfg map[string]any- if format == "toml" {- if err := toml.Unmarshal(raw, &cfg); err != nil {- return nil, true, fmt.Errorf("parse runtime MCP config: %w", err)- }- } else if err := json.Unmarshal(raw, &cfg); err != nil {- return nil, true, fmt.Errorf("parse runtime MCP config: %w", err)+ cfg, err := unmarshalRuntimeMcpConfig(raw, format)+ if err != nil {+ return nil, true, err}if configured, ok := nestedRuntimeMcpMap(cfg, key); ok {for name, entry := range configured {@@ -139,7 +303,7 @@ func loadRuntimeMcpServerConfigs(provider string) (map[string]any, bool, error)return nil, true, fmt.Errorf("read runtime MCP config: %w", err)}- if provider == "claude" || provider == "codebuddy" {+ if provider == "claude" {// User configuration has the same precedence Claude uses: plugin// servers only fill names not already defined by the user.for name, entry := range loadClaudePluginMcpServerConfigs(home) {@@ -213,8 +377,20 @@ func listRuntimeLocalMcpServers(provider string) ([]runtimeLocalMcpServerSummaryvar path, key, source stringvar format stringswitch provider {- case "claude", "codebuddy":+ case "claude":path, key, source, format = filepath.Join(home, ".claude.json"), "mcpServers", "User config", "json"+ case "codebuddy":+ path, key, source, format = codebuddyUserMcpConfigPath(home), "mcpServers", "User config", "jsonc"+ case "kimi":+ // Inventory only — kimi is deliberately absent from+ // loadRuntimeMcpServerConfigs. `kimi acp` merges this file with the+ // ephemeral `mcpServers` we send in session/new, so merging it in+ // again would spawn every user server twice.+ kimiHome := strings.TrimSpace(os.Getenv("KIMI_CODE_HOME"))+ if kimiHome == "" {+ kimiHome = filepath.Join(home, ".kimi-code")+ }+ path, key, source, format = filepath.Join(kimiHome, "mcp.json"), "mcpServers", "User config", "json"case "codex":codexHome := strings.TrimSpace(os.Getenv("CODEX_HOME"))if codexHome == "" {@@ -246,13 +422,9 @@ func listRuntimeLocalMcpServers(provider string) ([]runtimeLocalMcpServerSummaryout := make([]runtimeLocalMcpServerSummary, 0)raw, err := os.ReadFile(path)if err == nil {- var cfg map[string]any- if format == "toml" {- if err := toml.Unmarshal(raw, &cfg); err != nil {- return nil, true, fmt.Errorf("parse runtime MCP config: %w", err)- }- } else if err := json.Unmarshal(raw, &cfg); err != nil {- return nil, true, fmt.Errorf("parse runtime MCP config: %w", err)+ cfg, err := unmarshalRuntimeMcpConfig(raw, format)+ if err != nil {+ return nil, true, err}if servers, ok := nestedRuntimeMcpMap(cfg, key); ok {out = append(out, runtimeMcpSummaries(servers, source)...)@@ -261,7 +433,7 @@ func listRuntimeLocalMcpServers(provider string) ([]runtimeLocalMcpServerSummaryreturn nil, true, fmt.Errorf("read runtime MCP config: %w", err)}- if provider == "claude" || provider == "codebuddy" {+ if provider == "claude" {out = append(out, listClaudePluginMcpServers(home)...)}diff --git a/server/internal/daemon/runtime_mcp_test.go b/server/internal/daemon/runtime_mcp_test.goindex b6c0a25cf0..c08e03267b 100644--- a/server/internal/daemon/runtime_mcp_test.go+++ b/server/internal/daemon/runtime_mcp_test.go@@ -2,6 +2,7 @@ package daemonimport ("encoding/json"+ "fmt""os""path/filepath""testing"@@ -181,3 +182,287 @@ func TestMergeRuntimeAndAgentMcpConfigNullKeepsNativeInheritance(t *testing.T) {}}}++// CodeBuddy resolves its own config: `$CODEBUDDY_CONFIG_DIR` (default+// `~/.codebuddy`), user-scope MCP from the first existing of+// `<configDir>/.mcp.json` -> `<configDir>/mcp.json` -> `~/.codebuddy.json`,+// parsed as JSONC. `~/.claude.json` is never consulted (MUL-5846).+func TestCodebuddyUserMcpConfigPathPrecedence(t *testing.T) {+ home := t.TempDir()+ t.Setenv("CODEBUDDY_CONFIG_DIR", "")+ configDir := filepath.Join(home, ".codebuddy")+ if err := os.MkdirAll(configDir, 0o755); err != nil {+ t.Fatal(err)+ }+ write := func(path string) {+ if err := os.WriteFile(path, []byte(`{"mcpServers":{}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ }++ // Nothing on disk: the caller must still get a stable path so the read+ // fails with ErrNotExist rather than the provider looking unsupported.+ if got, want := codebuddyUserMcpConfigPath(home), filepath.Join(configDir, ".mcp.json"); got != want {+ t.Fatalf("no files: got %q, want %q", got, want)+ }++ legacy := filepath.Join(home, ".codebuddy.json")+ write(legacy)+ if got := codebuddyUserMcpConfigPath(home); got != legacy {+ t.Fatalf("legacy only: got %q, want %q", got, legacy)+ }++ plain := filepath.Join(configDir, "mcp.json")+ write(plain)+ if got := codebuddyUserMcpConfigPath(home); got != plain {+ t.Fatalf("mcp.json must win over ~/.codebuddy.json: got %q", got)+ }++ dotted := filepath.Join(configDir, ".mcp.json")+ write(dotted)+ if got := codebuddyUserMcpConfigPath(home); got != dotted {+ t.Fatalf(".mcp.json must win over mcp.json: got %q", got)+ }+}++func TestCodebuddyUserMcpConfigPathHonorsConfigDirEnv(t *testing.T) {+ home := t.TempDir()+ configDir := t.TempDir()+ t.Setenv("CODEBUDDY_CONFIG_DIR", configDir)+ want := filepath.Join(configDir, ".mcp.json")+ if err := os.WriteFile(want, []byte(`{"mcpServers":{}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ if got := codebuddyUserMcpConfigPath(home); got != want {+ t.Fatalf("got %q, want %q", got, want)+ }+}++func TestListRuntimeLocalMcpServersCodebuddyReadsItsOwnConfig(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("CODEBUDDY_CONFIG_DIR", "")+ configDir := filepath.Join(home, ".codebuddy")+ if err := os.MkdirAll(configDir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(home, ".claude.json"), []byte(`{"mcpServers":{"claude-only":{"command":"claude-cmd"}}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ // JSONC: a comment and a trailing comma must not lose the server.+ jsonc := "{\n // user scope\n \"mcpServers\": {\n \"buddy\": { \"command\": \"buddy-cmd\", },\n },\n}\n"+ if err := os.WriteFile(filepath.Join(configDir, ".mcp.json"), []byte(jsonc), 0o600); err != nil {+ t.Fatal(err)+ }+ // A Claude plugin server must not be attributed to CodeBuddy either:+ // CodeBuddy plugins live under <configDir>/plugins, not ~/.claude/plugins.+ installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", true)+ if err := os.WriteFile(filepath.Join(installPath, "mcp.json"), []byte(`{"mcpServers":{"paper":{"type":"http","url":"http://127.0.0.1:29979/mcp"}}}`), 0o600); err != nil {+ t.Fatal(err)+ }++ servers, supported, err := listRuntimeLocalMcpServers("codebuddy")+ if err != nil {+ t.Fatal(err)+ }+ if !supported || len(servers) != 1 || servers[0].Name != "buddy" {+ t.Fatalf("supported=%v servers=%#v", supported, servers)+ }+}++// CodeBuddy loads its own user/project/local scopes on every launch, so the+// daemon must NOT pre-merge them: doing so would duplicate the CLI's own work+// while losing scope precedence and the project-scope approval gate.+func TestMergeRuntimeAndAgentMcpConfigCodebuddyIsPassthrough(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("CODEBUDDY_CONFIG_DIR", "")+ configDir := filepath.Join(home, ".codebuddy")+ if err := os.MkdirAll(configDir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(configDir, ".mcp.json"), []byte(`{"mcpServers":{"local-only":{"command":"local-cmd"}}}`), 0o600); err != nil {+ t.Fatal(err)+ }++ agentConfig := json.RawMessage(`{"mcpServers":{"agent-only":{"command":"agent-cmd"}}}`)+ merged, err := mergeRuntimeAndAgentMcpConfig("codebuddy", agentConfig)+ if err != nil {+ t.Fatal(err)+ }+ if string(merged) != string(agentConfig) {+ t.Fatalf("codebuddy merge must be a passthrough, got %s", merged)+ }+}++func TestStripJSONC(t *testing.T) {+ cases := []struct {+ name string+ in string+ want map[string]any+ }{+ {"line comment", "{\n// hi\n\"a\":1\n}", map[string]any{"a": float64(1)}},+ {"block comment", "{/* hi */\"a\":1}", map[string]any{"a": float64(1)}},+ {"trailing comma object", `{"a":1,}`, map[string]any{"a": float64(1)}},+ {"trailing comma nested", `{"a":{"b":1,},}`, map[string]any{"a": map[string]any{"b": float64(1)}}},+ {+ "comment-like text inside a string is preserved",+ `{"a":"http://x//y, /* not a comment */"}`,+ map[string]any{"a": "http://x//y, /* not a comment */"},+ },+ {"escaped quote in string", `{"a":"say \"//\" ok"}`, map[string]any{"a": `say "//" ok`}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ stripped, err := stripJSONC([]byte(tc.in))+ if err != nil {+ t.Fatalf("stripJSONC %q: %v", tc.in, err)+ }+ var got map[string]any+ if err := json.Unmarshal(stripped, &got); err != nil {+ t.Fatalf("unmarshal %q -> %q: %v", tc.in, stripped, err)+ }+ if fmt.Sprintf("%v", got) != fmt.Sprintf("%v", tc.want) {+ t.Fatalf("got %#v, want %#v", got, tc.want)+ }+ })+ }+}++// A trailing comma that is NOT trailing must survive: blanking it would merge+// two array elements into one.+func TestStripJSONCKeepsSeparatorCommas(t *testing.T) {+ stripped, err := stripJSONC([]byte(`["a","b",]`))+ if err != nil {+ t.Fatal(err)+ }+ var got []any+ if err := json.Unmarshal(stripped, &got); err != nil {+ t.Fatal(err)+ }+ if len(got) != 2 || got[0] != "a" || got[1] != "b" {+ t.Fatalf("got %#v, want [a b]", got)+ }+}++// Repairing only a genuine trailing comma keeps malformed input malformed —+// a config the CLI would reject must not be silently accepted here.+func TestStripJSONCLeavesMalformedInputInvalid(t *testing.T) {+ for _, in := range []string{`[1,,,]`, `{"a":1,,}`, `[1,,2]`} {+ stripped, err := stripJSONC([]byte(in))+ if err != nil {+ continue+ }+ var got any+ if err := json.Unmarshal(stripped, &got); err == nil {+ t.Fatalf("%q must stay invalid, got %#v", in, got)+ }+ }+}++// Comments and the dropped comma are blanked, never deleted, so a parse-error+// offset still points at the byte the user wrote.+func TestStripJSONCPreservesByteLength(t *testing.T) {+ for _, in := range []string{+ "{\n // c\n \"a\": 1,\n}\n",+ `{/* block */"a":1,}`,+ `{"a":"// not a comment"}`,+ `{/**/"a":1}`,+ "{}",+ } {+ stripped, err := stripJSONC([]byte(in))+ if err != nil {+ t.Fatalf("stripJSONC %q: %v", in, err)+ }+ if got, want := len(stripped), len(in); got != want {+ t.Fatalf("%q: length %d, want %d (%q)", in, got, want, stripped)+ }+ }+}++// A file CodeBuddy itself rejects must not produce an inventory listing. The+// CLI answers "No MCP servers configured" for both of these; blanking an+// unterminated comment to EOF would instead have turned the first into valid+// JSON, and letting the opener's `*` double as the closer's would have made+// `/*/` a complete comment.+func TestStripJSONCRejectsUnterminatedBlockComment(t *testing.T) {+ cases := map[string]string{+ "unterminated": `{"mcpServers":{}} /* oops`,+ "opener not closer": `/*/ {"mcpServers":{}}`,+ "unterminated after opener": `/*`,+ }+ for name, in := range cases {+ t.Run(name, func(t *testing.T) {+ if stripped, err := stripJSONC([]byte(in)); err == nil {+ t.Fatalf("%q must fail to parse, got %q", in, stripped)+ }+ })+ }+}++// The same input must reach the caller as a parse error, so the inventory+// surfaces the problem rather than silently reporting zero servers.+func TestListRuntimeLocalMcpServersCodebuddyRejectsUnterminatedComment(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("CODEBUDDY_CONFIG_DIR", "")+ configDir := filepath.Join(home, ".codebuddy")+ if err := os.MkdirAll(configDir, 0o755); err != nil {+ t.Fatal(err)+ }+ broken := `{"mcpServers":{"buddy":{"command":"buddy-cmd"}}} /* oops`+ if err := os.WriteFile(filepath.Join(configDir, ".mcp.json"), []byte(broken), 0o600); err != nil {+ t.Fatal(err)+ }++ if _, _, err := listRuntimeLocalMcpServers("codebuddy"); err == nil {+ t.Fatal("expected a parse error for a config CodeBuddy itself rejects")+ }+}++func TestListRuntimeLocalMcpServersKimi(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("KIMI_CODE_HOME", "")+ kimiHome := filepath.Join(home, ".kimi-code")+ if err := os.MkdirAll(kimiHome, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(kimiHome, "mcp.json"), []byte(`{"mcpServers":{"paper":{"url":"https://paper.example/mcp"}}}`), 0o600); err != nil {+ t.Fatal(err)+ }++ servers, supported, err := listRuntimeLocalMcpServers("kimi")+ if err != nil {+ t.Fatal(err)+ }+ if !supported || len(servers) != 1 || servers[0].Name != "paper" {+ t.Fatalf("supported=%v servers=%#v", supported, servers)+ }+}++// kimi merges <KIMI_CODE_HOME>/mcp.json with the ephemeral `mcpServers` array+// the ACP backend sends in session/new, and a duplicate name spawns the server+// twice. So kimi is inventory-only: the task-local merge must leave the agent's+// config untouched.+func TestMergeRuntimeAndAgentMcpConfigKimiIsPassthrough(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("KIMI_CODE_HOME", "")+ kimiHome := filepath.Join(home, ".kimi-code")+ if err := os.MkdirAll(kimiHome, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(kimiHome, "mcp.json"), []byte(`{"mcpServers":{"paper":{"url":"https://paper.example/mcp"}}}`), 0o600); err != nil {+ t.Fatal(err)+ }++ agentConfig := json.RawMessage(`{"mcpServers":{"agent-only":{"command":"agent-cmd"}}}`)+ merged, err := mergeRuntimeAndAgentMcpConfig("kimi", agentConfig)+ if err != nil {+ t.Fatal(err)+ }+ if string(merged) != string(agentConfig) {+ t.Fatalf("kimi merge must be a passthrough, got %s", merged)+ }+}diff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.goindex 240118d2bb..a4224dc7ef 100644--- a/server/pkg/agent/codebuddy.go+++ b/server/pkg/agent/codebuddy.go@@ -41,7 +41,6 @@ func buildCodebuddyArgs(opts ExecOptions, logger *slog.Logger) []string {"--output-format", "stream-json","--input-format", "stream-json","--verbose",- "--strict-mcp-config","--permission-mode", "bypassPermissions",// CodeBuddy's interactive tools have no UI to render in under the// daemon's headless stream-json transport. AskUserQuestion and@@ -60,6 +59,20 @@ func buildCodebuddyArgs(opts ExecOptions, logger *slog.Logger) []string {// would match nothing despite what the CLI's own help text claims."--disallowedTools", "AskUserQuestion", "EnterPlanMode", "ExitPlanMode",}+ // NOTE: --strict-mcp-config is deliberately never passed. It means "only+ // use servers from --mcp-config", which drops CodeBuddy's user, project+ // AND local scopes. Measured against CodeBuddy 2.x with one real MCP+ // server registered per scope, using process spawns as the oracle:+ //+ // --mcp-config only ....... managed + user + local <- what we want+ // --mcp-config + strict ... managed only+ // strict only ............. nothing at all+ //+ // The union is also what mergeRuntimeAndAgentMcpConfig promises: adding+ // one managed server must not disable the user's own. CodeBuddy applies+ // it natively, and a managed entry already wins a same-name collision+ // (verified), so the daemon does not pre-merge — see the codebuddy note+ // in loadRuntimeMcpServerConfigs.if opts.Model != "" {args = append(args, "--model", opts.Model)}@@ -94,11 +107,18 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Execargs := buildCodebuddyArgs(opts, b.cfg.Logger)- // If the caller provided an MCP config, write it to a temp file and pass- // --mcp-config <path> so the agent uses a controlled set of MCP servers.+ // A managed agent config is written to a temp file and added with+ // --mcp-config, which ADDS to whatever CodeBuddy loads from its own user,+ // project and local scopes — buildCodebuddyArgs never passes+ // --strict-mcp-config, so those stay on. A managed entry wins a same-name+ // collision natively.+ //+ // Three-state, as everywhere else: a JSON `null` means "inherit the runtime+ // configuration" and skips the flag entirely, while an explicitly empty+ // object is a managed set that happens to contain no servers.var mcpConfigPath stringvar mcpFileCleanup func()- if len(opts.McpConfig) > 0 {+ if hasManagedMcpConfig(opts.McpConfig) {path, err := writeMcpConfigToTemp(opts.McpConfig)if err != nil {cancel()diff --git a/server/pkg/agent/codebuddy_test.go b/server/pkg/agent/codebuddy_test.goindex bc2a4888cd..10e38bff27 100644--- a/server/pkg/agent/codebuddy_test.go+++ b/server/pkg/agent/codebuddy_test.go@@ -26,7 +26,6 @@ func TestBuildCodebuddyArgs_Basic(t *testing.T) {"--output-format", "stream-json","--input-format", "stream-json","--verbose",- "--strict-mcp-config","--permission-mode", "bypassPermissions","--disallowedTools", "AskUserQuestion", "EnterPlanMode", "ExitPlanMode","--model", "claude-sonnet-4-20250514",@@ -44,6 +43,29 @@ func TestBuildCodebuddyArgs_Basic(t *testing.T) {}}+// --strict-mcp-config must never be passed, with or without a managed config.+// It means "only use servers from --mcp-config" and drops CodeBuddy's user,+// project and local scopes; measured against the real CLI, strict + a managed+// config loaded ONLY the managed server, and strict alone loaded nothing at+// all. The union is what mergeRuntimeAndAgentMcpConfig promises (MUL-5846).+func TestBuildCodebuddyArgsNeverPassesStrictMCP(t *testing.T) {+ t.Parallel()++ for _, mcpConfig := range []json.RawMessage{+ nil,+ json.RawMessage("null"),+ json.RawMessage(`{}`),+ json.RawMessage(`{"mcpServers":{"paper":{"command":"paper"}}}`),+ } {+ args := buildCodebuddyArgs(ExecOptions{McpConfig: mcpConfig}, slog.Default())+ for _, arg := range args {+ if arg == "--strict-mcp-config" {+ t.Fatalf("mcp_config %q must not disable CodeBuddy's own MCP scopes, got %v", string(mcpConfig), args)+ }+ }+ }+}+func TestBuildCodebuddyArgs_DisallowsInteractiveTools(t *testing.T) {t.Parallel()diff --git a/server/pkg/agent/kimi_integration_test.go b/server/pkg/agent/kimi_integration_test.goindex bb91529acf..9125f4f782 100644--- a/server/pkg/agent/kimi_integration_test.go+++ b/server/pkg/agent/kimi_integration_test.go@@ -3,10 +3,15 @@package agentimport (+ "bytes""context"+ "encoding/json"+ "fmt""log/slog""os""os/exec"+ "path/filepath"+ "runtime""strings""testing""time"@@ -88,3 +93,112 @@ func kimiSmokeModel() string {}return ""}++// TestKimiRealMcpConfigReachesSessionSmoke drives the real `kimi acp` binary+// through this package's own backend with a Multica-shaped agent.mcp_config+// and asserts the server is actually connected and callable.+//+// Users reported that MCP configured in Multica "never reaches kimi", pointing+// at the bare `kimi acp` launch line as evidence (MUL-5846). That line carries+// no MCP flags because the CLI has none — kimi takes MCP over ACP session/new+// instead — so only an end-to-end run against the real binary can settle it.+// The oracle is the MCP server process itself: it appends to a log when spawned+// and returns a sentinel from its one tool, so neither a hand-written ACP+// fixture nor the model's own description of its tools can fake a pass.+func TestKimiRealMcpConfigReachesSessionSmoke(t *testing.T) {+ requireRealAgentSmoke(t)+ if testing.Short() {+ t.Skip("skipping real-binary smoke test in -short mode")+ }+ if runtime.GOOS == "windows" {+ t.Skip("shell-script MCP fixture is POSIX-only")+ }+ path, err := exec.LookPath("kimi")+ if err != nil {+ t.Skip("kimi not on PATH; skipping real-binary smoke test")+ }+ if version, err := exec.Command(path, "--version").CombinedOutput(); err == nil {+ t.Logf("kimi CLI version: %s", strings.TrimSpace(string(version)))+ }++ dir := t.TempDir()+ spawnLog := filepath.Join(dir, "spawned.log")+ serverPath := filepath.Join(dir, "mcp-probe")+ writeTestExecutable(t, serverPath, []byte(stdioMcpProbeScript(spawnLog)))++ backend, err := New("kimi", Config{ExecutablePath: path, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new kimi backend: %v", err)+ }++ // Exactly the shape the daemon forwards from agent.mcp_config.+ mcpConfig := fmt.Sprintf(`{"mcpServers":{"multicaprobe":{"command":%q,"args":[],"env":{}}}}`, serverPath)++ ctx, cancel := context.WithTimeout(context.Background(), 240*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx,+ "Call the multica_probe_ping tool and reply with exactly what it returned. Do nothing else.",+ ExecOptions{+ Timeout: 210 * time.Second,+ Cwd: dir,+ Model: kimiSmokeModel(),+ McpConfig: json.RawMessage(mcpConfig),+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ result := <-session.Result+ t.Logf("status=%q error=%q output=%q", result.Status, result.Error, result.Output)++ // Ground truth: did kimi actually start the MCP server we configured?+ spawned, err := os.ReadFile(spawnLog)+ t.Logf("MCP server saw:\n%s", spawned)+ if err != nil || !bytes.Contains(spawned, []byte("SPAWNED")) {+ t.Fatalf("MCP server was never started by kimi (log=%q err=%v) — the managed mcp_config did not reach the session", spawned, err)+ }+ if !bytes.Contains(spawned, []byte("tools/list")) {+ t.Fatalf("kimi started the MCP server but never listed its tools: %q", spawned)+ }+ if !strings.Contains(result.Output, "MULTICA_MCP_OK") {+ t.Fatalf("agent output does not contain the tool's sentinel: %q", result.Output)+ }+}++// stdioMcpProbeScript returns a minimal POSIX-sh MCP stdio server. It records+// every request it receives in spawnLog so the test can assert on the process+// rather than on anything the model says.+func stdioMcpProbeScript(spawnLog string) string {+ return `#!/bin/sh+LOG=` + fmt.Sprintf("%q", spawnLog) + `+echo SPAWNED >> "$LOG"+while IFS= read -r line; do+ echo "$line" >> "$LOG"+ id=` + "`" + `printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p'` + "`" + `+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{"listChanged":false}},"serverInfo":{"name":"multica-probe","version":"1.0.0"}}}\n' "$id"+ ;;+ *'"method":"tools/list"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"multica_probe_ping","description":"Returns MULTICA_MCP_OK.","inputSchema":{"type":"object","properties":{},"additionalProperties":false}}]}}\n' "$id"+ ;;+ *'"method":"tools/call"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"content":[{"type":"text","text":"MULTICA_MCP_OK"}],"isError":false}}\n' "$id"+ ;;+ *'"method":"resources/list"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"resources":[]}}\n' "$id"+ ;;+ *'"method":"prompts/list"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"prompts":[]}}\n' "$id"+ ;;+ *'"id"'*)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"method not found"}}\n' "$id"+ ;;+ esac+done+`+}diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.goindex 553c3c647f..0de17c94fa 100644--- a/server/pkg/agent/kimi_test.go+++ b/server/pkg/agent/kimi_test.go@@ -370,6 +370,57 @@ func TestKimiResumeIncludesMcpServers(t *testing.T) {}}+// TestKimiFreshSessionIncludesMcpServers is the session/new counterpart to the+// resume test above: a fresh Kimi task must carry the managed MCP set too.+// Kimi takes MCP over ACP rather than as a CLI flag, so a bare `kimi acp`+// launch line is not evidence that the servers were dropped (MUL-5846) — this+// pins the payload that actually carries them.+func TestKimiFreshSessionIncludesMcpServers(t *testing.T) {+ t.Parallel()++ recordPath := filepath.Join(t.TempDir(), "frames.jsonl")+ fakePath := filepath.Join(t.TempDir(), "kimi")+ writeTestExecutable(t, fakePath, []byte(fakeACPRecordingScript(recordPath, "ses_new", `{}`)))++ backend, err := New("kimi", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new kimi backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Timeout: 5 * time.Second,+ McpConfig: json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}`),+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ select {+ case <-session.Result:+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }++ frame := findRecordedFrame(t, recordPath, "session/new")+ params := frame["params"].(map[string]any)+ servers, ok := params["mcpServers"].([]any)+ if !ok {+ t.Fatalf("session/new.mcpServers: got %T, want []any", params["mcpServers"])+ }+ if len(servers) != 1 {+ t.Fatalf("session/new.mcpServers: got %d entries, want 1", len(servers))+ }+ entry := servers[0].(map[string]any)+ if entry["name"] != "fetch" || entry["command"] != "uvx" {+ t.Fatalf("session/new.mcpServers[0]: got %v, want {name:fetch,command:uvx,...}", entry)+ }+}+// TestKimiDrainsNotificationsAfterPromptResponse pins the trailing-notification// drain. kimi ACP can emit a final session update just after the// session/prompt response returns; closing stdin and cancelling the context at