From 2e86d656e98cbf6180d2d2a58c693de80bf60534 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 12:23:49 +0000 Subject: [PATCH 01/26] Add aitools mcp list and remove `list` groups the installed servers by profile and shows each agent entry as installed, missing on disk or modified. It reports profiles that are gone or re-pointed, and lists Databricks entries in agent configs that this CLI did not write. It needs no network and exits 0 when entries have drifted. `remove` takes --names, --profile or --all, with --agents to narrow the agents. It deletes only entries that run this CLI's serve command, skips the others, prunes state records whose entry is already gone, and needs no network. Co-authored-by: Isaac --- .../mcp/drift-profile-missing/.databrickscfg | 7 + .../dogfood-moved.databrickscfg | 3 + .../dogfood-only.databrickscfg | 3 + .../mcp/drift-profile-missing/out.test.toml | 1 + .../mcp/drift-profile-missing/output.txt | 84 +++++ .../aitools/mcp/drift-profile-missing/script | 19 ++ .../mcp/list-and-remove/.databrickscfg | 7 + .../aitools/mcp/list-and-remove/out.test.toml | 1 + .../aitools/mcp/list-and-remove/output.txt | 158 +++++++++ .../cmd/aitools/mcp/list-and-remove/script | 32 ++ cmd/aitools/mcp.go | 2 + cmd/aitools/mcp_list.go | 306 ++++++++++++++++++ cmd/aitools/mcp_list_test.go | 134 ++++++++ cmd/aitools/mcp_remove.go | 284 ++++++++++++++++ cmd/aitools/mcp_remove_test.go | 209 ++++++++++++ cmd/aitools/mcp_test.go | 2 +- 16 files changed, 1251 insertions(+), 1 deletion(-) create mode 100644 acceptance/cmd/aitools/mcp/drift-profile-missing/.databrickscfg create mode 100644 acceptance/cmd/aitools/mcp/drift-profile-missing/dogfood-moved.databrickscfg create mode 100644 acceptance/cmd/aitools/mcp/drift-profile-missing/dogfood-only.databrickscfg create mode 100644 acceptance/cmd/aitools/mcp/drift-profile-missing/out.test.toml create mode 100644 acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt create mode 100644 acceptance/cmd/aitools/mcp/drift-profile-missing/script create mode 100644 acceptance/cmd/aitools/mcp/list-and-remove/.databrickscfg create mode 100644 acceptance/cmd/aitools/mcp/list-and-remove/out.test.toml create mode 100644 acceptance/cmd/aitools/mcp/list-and-remove/output.txt create mode 100644 acceptance/cmd/aitools/mcp/list-and-remove/script create mode 100644 cmd/aitools/mcp_list.go create mode 100644 cmd/aitools/mcp_list_test.go create mode 100644 cmd/aitools/mcp_remove.go create mode 100644 cmd/aitools/mcp_remove_test.go diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/.databrickscfg b/acceptance/cmd/aitools/mcp/drift-profile-missing/.databrickscfg new file mode 100644 index 00000000000..f685e4656ff --- /dev/null +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/.databrickscfg @@ -0,0 +1,7 @@ +[logfood] +host = $DATABRICKS_HOST +token = test-token-logfood + +[dogfood] +host = $DATABRICKS_HOST +token = test-token-dogfood diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/dogfood-moved.databrickscfg b/acceptance/cmd/aitools/mcp/drift-profile-missing/dogfood-moved.databrickscfg new file mode 100644 index 00000000000..da10ba7e01a --- /dev/null +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/dogfood-moved.databrickscfg @@ -0,0 +1,3 @@ +[dogfood] +host = https://adb-2.test +token = test-token-dogfood diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/dogfood-only.databrickscfg b/acceptance/cmd/aitools/mcp/drift-profile-missing/dogfood-only.databrickscfg new file mode 100644 index 00000000000..91c0e3709ed --- /dev/null +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/dogfood-only.databrickscfg @@ -0,0 +1,3 @@ +[dogfood] +host = $DATABRICKS_HOST +token = test-token-dogfood diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/out.test.toml b/acceptance/cmd/aitools/mcp/drift-profile-missing/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt b/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt new file mode 100644 index 00000000000..8e872be443d --- /dev/null +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt @@ -0,0 +1,84 @@ + +=== Both profiles get a server + +>>> [CLI] aitools mcp add --profile logfood --names system.ai.genie_one_mcp --agents claude-code +Profile logfood ([DATABRICKS_URL]) +Agents (named with --agents): claude-code + +genie_one_mcp-logfood system.ai.genie_one_mcp + claude-code installed [TEST_TMP_DIR]/home/.claude.json + +>>> [CLI] aitools mcp add --profile dogfood --names system.ai.genie_one_mcp --agents claude-code +Profile dogfood ([DATABRICKS_URL]) +Agents (named with --agents): claude-code + +genie_one_mcp-dogfood system.ai.genie_one_mcp + claude-code installed [TEST_TMP_DIR]/home/.claude.json + +=== logfood is deleted from the Databricks config file: list reports it and exits 0 + +>>> [CLI] aitools mcp list +Profile dogfood ([DATABRICKS_URL]) + genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code + +Profile logfood (profile not found in .databrickscfg) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code + broken: run `databricks aitools mcp remove --profile logfood` or `databricks auth login --host [DATABRICKS_URL] --profile logfood` + +=== dogfood now points at another host: list reports the host change + +>>> [CLI] aitools mcp list --output json +{ + "profiles": [ + { + "profile": "dogfood", + "host": "https://adb-2.test", + "status": "host_changed", + "servers": [ + { + "name": "genie_one_mcp-dogfood", + "service": "system.ai.genie_one_mcp", + "sign_in_required": false, + "agents": [ + { + "name": "claude-code", + "path": "[TEST_TMP_DIR]/home/.claude.json", + "status": "installed" + } + ] + } + ] + }, + { + "profile": "logfood", + "host": "[DATABRICKS_URL]", + "status": "profile_missing", + "servers": [ + { + "name": "genie_one_mcp-logfood", + "service": "system.ai.genie_one_mcp", + "sign_in_required": false, + "agents": [ + { + "name": "claude-code", + "path": "[TEST_TMP_DIR]/home/.claude.json", + "status": "installed" + } + ] + } + ] + } + ], + "unmanaged": [] +} + +=== The same change in text + +>>> [CLI] aitools mcp list +Profile dogfood (host changed, now https://adb-2.test) + genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code + broken: run `databricks aitools mcp remove --profile dogfood` and add the servers again + +Profile logfood (profile not found in .databrickscfg) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code + broken: run `databricks aitools mcp remove --profile logfood` or `databricks auth login --host [DATABRICKS_URL] --profile logfood` diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/script b/acceptance/cmd/aitools/mcp/drift-profile-missing/script new file mode 100644 index 00000000000..df22dc7f9dd --- /dev/null +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/script @@ -0,0 +1,19 @@ +# Isolate HOME so the agent config files and the state file land in this test directory. +sethome home +envsubst < .databrickscfg > out && mv out .databrickscfg +export DATABRICKS_CONFIG_FILE=.databrickscfg + +title "Both profiles get a server" +trace $CLI aitools mcp add --profile logfood --names system.ai.genie_one_mcp --agents claude-code +trace $CLI aitools mcp add --profile dogfood --names system.ai.genie_one_mcp --agents claude-code + +title "logfood is deleted from the Databricks config file: list reports it and exits 0" +envsubst < dogfood-only.databrickscfg > out && mv out .databrickscfg +trace $CLI aitools mcp list + +title "dogfood now points at another host: list reports the host change" +envsubst < dogfood-moved.databrickscfg > out && mv out .databrickscfg +trace $CLI aitools mcp list --output json + +title "The same change in text" +trace $CLI aitools mcp list diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/.databrickscfg b/acceptance/cmd/aitools/mcp/list-and-remove/.databrickscfg new file mode 100644 index 00000000000..f685e4656ff --- /dev/null +++ b/acceptance/cmd/aitools/mcp/list-and-remove/.databrickscfg @@ -0,0 +1,7 @@ +[logfood] +host = $DATABRICKS_HOST +token = test-token-logfood + +[dogfood] +host = $DATABRICKS_HOST +token = test-token-dogfood diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/out.test.toml b/acceptance/cmd/aitools/mcp/list-and-remove/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/aitools/mcp/list-and-remove/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt new file mode 100644 index 00000000000..5fe0e212e09 --- /dev/null +++ b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt @@ -0,0 +1,158 @@ + +=== Two profiles, add twice: logfood gets two services, dogfood gets one + +>>> [CLI] aitools mcp add --profile logfood --names system.ai.genie_one_mcp,system.ai.github --agents claude-code +Profile logfood ([DATABRICKS_URL]) +Agents (named with --agents): claude-code + +genie_one_mcp-logfood system.ai.genie_one_mcp + claude-code installed [TEST_TMP_DIR]/home/.claude.json + +github-logfood system.ai.github + claude-code installed [TEST_TMP_DIR]/home/.claude.json +system.ai.github needs sign-in. Run: databricks aitools mcp login system.ai.github --profile logfood + +>>> [CLI] aitools mcp add --profile dogfood --names system.ai.genie_one_mcp --agents claude-code +Profile dogfood ([DATABRICKS_URL]) +Agents (named with --agents): claude-code + +genie_one_mcp-dogfood system.ai.genie_one_mcp + claude-code installed [TEST_TMP_DIR]/home/.claude.json + +=== list groups the servers by profile + +>>> [CLI] aitools mcp list +Profile dogfood ([DATABRICKS_URL]) + genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code + +Profile logfood ([DATABRICKS_URL]) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code + github-logfood system.ai.github Claude Code + +=== list as JSON + +>>> [CLI] aitools mcp list --output json +{ + "profiles": [ + { + "profile": "dogfood", + "host": "[DATABRICKS_URL]", + "status": "ok", + "servers": [ + { + "name": "genie_one_mcp-dogfood", + "service": "system.ai.genie_one_mcp", + "sign_in_required": false, + "agents": [ + { + "name": "claude-code", + "path": "[TEST_TMP_DIR]/home/.claude.json", + "status": "installed" + } + ] + } + ] + }, + { + "profile": "logfood", + "host": "[DATABRICKS_URL]", + "status": "ok", + "servers": [ + { + "name": "genie_one_mcp-logfood", + "service": "system.ai.genie_one_mcp", + "sign_in_required": false, + "agents": [ + { + "name": "claude-code", + "path": "[TEST_TMP_DIR]/home/.claude.json", + "status": "installed" + } + ] + }, + { + "name": "github-logfood", + "service": "system.ai.github", + "sign_in_required": true, + "agents": [ + { + "name": "claude-code", + "path": "[TEST_TMP_DIR]/home/.claude.json", + "status": "installed" + } + ] + } + ] + } + ], + "unmanaged": [] +} + +=== remove --profile removes that profile only + +>>> [CLI] aitools mcp remove --profile dogfood +Removed genie_one_mcp-dogfood system.ai.genie_one_mcp profile dogfood (Claude Code) + +>>> [CLI] aitools mcp list +Profile logfood ([DATABRICKS_URL]) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code + github-logfood system.ai.github Claude Code + +=== A hand-edited entry is listed as modified; an unmanaged ug entry is listed and never changed + +>>> [CLI] aitools mcp list +Profile logfood ([DATABRICKS_URL]) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code + github-logfood system.ai.github Claude Code (modified) + +Unmanaged Databricks MCP entries (not changed by this command): + Claude Code web_search ug mcp-proxy + +=== remove leaves the modified entry in place and says why + +>>> [CLI] aitools mcp remove --names github-logfood,genie_one_mcp-logfood +Removed genie_one_mcp-logfood system.ai.genie_one_mcp profile logfood (Claude Code) +Skipped github-logfood: Claude Code has an entry named github-logfood that was changed outside this CLI; left in place + +>>> jq .mcpServers | keys home/.claude.json +[ + "github-logfood", + "web_search" +] + +>>> jq [.servers[] | {name, profile, agents: (.agents | keys)}] home/.databricks/aitools/mcp/state.json +[ + { + "name": "github-logfood", + "profile": "logfood", + "agents": [ + "claude-code" + ] + } +] + +=== remove --all removes what this CLI wrote and nothing else + +>>> [CLI] aitools mcp remove --all --output json +{ + "removed": [], + "skipped": [ + { + "name": "github-logfood", + "reason": "Claude Code has an entry named github-logfood that was changed outside this CLI; left in place" + } + ] +} + +>>> jq .mcpServers | keys home/.claude.json +[ + "github-logfood", + "web_search" +] + +>>> [CLI] aitools mcp list +Profile logfood ([DATABRICKS_URL]) + github-logfood system.ai.github Claude Code (modified) + +Unmanaged Databricks MCP entries (not changed by this command): + Claude Code web_search ug mcp-proxy diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/script b/acceptance/cmd/aitools/mcp/list-and-remove/script new file mode 100644 index 00000000000..50928a0bde5 --- /dev/null +++ b/acceptance/cmd/aitools/mcp/list-and-remove/script @@ -0,0 +1,32 @@ +# Isolate HOME so the agent config files and the state file land in this test directory. +sethome home +envsubst < .databrickscfg > out && mv out .databrickscfg +export DATABRICKS_CONFIG_FILE=.databrickscfg + +title "Two profiles, add twice: logfood gets two services, dogfood gets one" +trace $CLI aitools mcp add --profile logfood --names system.ai.genie_one_mcp,system.ai.github --agents claude-code +trace $CLI aitools mcp add --profile dogfood --names system.ai.genie_one_mcp --agents claude-code + +title "list groups the servers by profile" +trace $CLI aitools mcp list + +title "list as JSON" +trace $CLI aitools mcp list --output json + +title "remove --profile removes that profile only" +trace $CLI aitools mcp remove --profile dogfood +trace $CLI aitools mcp list + +title "A hand-edited entry is listed as modified; an unmanaged ug entry is listed and never changed" +jq '.mcpServers["github-logfood"].command = "/usr/bin/other" | .mcpServers.web_search = {"command": "ug", "args": ["mcp-proxy"]}' home/.claude.json > home/claude.tmp && mv home/claude.tmp home/.claude.json +trace $CLI aitools mcp list + +title "remove leaves the modified entry in place and says why" +trace $CLI aitools mcp remove --names github-logfood,genie_one_mcp-logfood +trace jq '.mcpServers | keys' home/.claude.json +trace jq '[.servers[] | {name, profile, agents: (.agents | keys)}]' home/.databricks/aitools/mcp/state.json + +title "remove --all removes what this CLI wrote and nothing else" +trace $CLI aitools mcp remove --all --output json +trace jq '.mcpServers | keys' home/.claude.json +trace $CLI aitools mcp list diff --git a/cmd/aitools/mcp.go b/cmd/aitools/mcp.go index 20c296c7457..69a7f872166 100644 --- a/cmd/aitools/mcp.go +++ b/cmd/aitools/mcp.go @@ -37,6 +37,8 @@ func NewMcpCmd() *cobra.Command { Hidden: true, } cmd.AddCommand(NewMcpAddCmd()) + cmd.AddCommand(NewMcpListCmd()) + cmd.AddCommand(NewMcpRemoveCmd()) return cmd } diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go new file mode 100644 index 00000000000..4fedb5a5e9e --- /dev/null +++ b/cmd/aitools/mcp_list.go @@ -0,0 +1,306 @@ +package aitools + +import ( + "context" + "fmt" + "maps" + "slices" + "strings" + + "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/aitools/mcp/agentconfig" + "github.com/databricks/cli/libs/aitools/mcpconfig" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/databrickscfg/profile" + "github.com/spf13/cobra" +) + +// Agent entry statuses of `mcp list`. Profile statuses are the drift kinds of mcp.Reconcile, plus ok. +const ( + agentStatusInstalled = "installed" + agentStatusMissingOnDisk = "missing_on_disk" + agentStatusModified = "modified" + profileStatusOK = "ok" +) + +// Unmanaged entry kinds of `mcp list`. +const ( + unmanagedKindUGProxy = "ug-proxy" + unmanagedKindAIGateway = "ai-gateway-url" +) + +// mcpListOutput is the `mcp list` document. +type mcpListOutput struct { + Profiles []mcpListProfile `json:"profiles"` + Unmanaged []mcpListUnmanaged `json:"unmanaged"` + + // configPath is the Databricks config file, named in the text of a missing profile. + configPath string +} + +type mcpListProfile struct { + Profile string `json:"profile"` + Host string `json:"host"` + Status string `json:"status"` + Servers []mcpListServer `json:"servers"` +} + +type mcpListServer struct { + Name string `json:"name"` + Service string `json:"service"` + SignInRequired bool `json:"sign_in_required"` + Agents []mcpListAgent `json:"agents"` +} + +type mcpListAgent struct { + Name string `json:"name"` + Path string `json:"path"` + Status string `json:"status"` +} + +type mcpListUnmanaged struct { + Agent string `json:"agent"` + Name string `json:"name"` + Kind string `json:"kind"` +} + +// NewMcpListCmd returns `aitools mcp list`. It reads the state file and the agent configs only, so it +// needs no network. Drift is reported, not failed: the command exits 0 when a profile is missing. +func NewMcpListCmd() *cobra.Command { + return &cobra.Command{ + Use: "list", + Short: "List Databricks managed MCP servers installed by this CLI", + Long: `List Databricks managed MCP servers installed by this CLI, grouped by profile, with the +coding agents each one is in. Entries that drifted from their profile or from the agent config are +reported. Entries in agent configs that this CLI did not write are listed as unmanaged and never changed. + +This command makes no network calls and always exits 0 when entries have drifted.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + out, err := buildMcpList(ctx) + if err != nil { + return err + } + if installOutputIsJSON(cmd) { + return renderJSON(cmd.OutOrStdout(), out) + } + renderMcpList(ctx, out) + return nil + }, + } +} + +func buildMcpList(ctx context.Context) (mcpListOutput, error) { + out := mcpListOutput{Profiles: []mcpListProfile{}, Unmanaged: []mcpListUnmanaged{}} + + state, err := mcp.LoadState(ctx) + if err != nil { + return out, err + } + profiler := profile.GetProfiler(ctx) + drifts, err := mcp.Reconcile(ctx, profiler, state) + if err != nil { + return out, err + } + out.configPath, err = profiler.GetPath(ctx) + if err != nil { + return out, err + } + disk, err := readAgentEntries(ctx) + if err != nil { + return out, err + } + + // A missing profile is reported before a changed host, since it has no host to compare. + drift := map[string]mcp.Drift{} + for _, d := range drifts { + if prev, ok := drift[d.Entry.Profile]; ok && prev.Kind == mcp.DriftProfileMissing { + continue + } + drift[d.Entry.Profile] = d + } + + var profileNames []string + for _, e := range state.Servers { + if !slices.Contains(profileNames, e.Profile) { + profileNames = append(profileNames, e.Profile) + } + } + slices.Sort(profileNames) + + for _, name := range profileNames { + p := mcpListProfile{Profile: name, Status: profileStatusOK, Servers: []mcpListServer{}} + for _, e := range state.Servers { + if e.Profile != name { + continue + } + if p.Host == "" { + p.Host = e.Host + } + s := mcpListServer{Name: e.Name, Service: e.Service, SignInRequired: e.SignInRequired, Agents: []mcpListAgent{}} + for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { + s.Agents = append(s.Agents, mcpListAgent{ + Name: agentName, + Path: e.Agents[agentName].Path, + Status: entryStatus(e, agentName, disk), + }) + } + p.Servers = append(p.Servers, s) + } + if d, ok := drift[name]; ok { + p.Status = string(d.Kind) + if d.Kind == mcp.DriftHostChanged { + p.Host = d.CurrentHost + } + } + out.Profiles = append(out.Profiles, p) + } + + for _, a := range agents.MCPAgents() { + entries := disk[a.Name] + for _, name := range slices.Sorted(maps.Keys(entries)) { + kind := unmanagedKind(entries[name]) + if kind == "" || recordedFor(state, a.Name, name) { + continue + } + out.Unmanaged = append(out.Unmanaged, mcpListUnmanaged{Agent: a.Name, Name: name, Kind: kind}) + } + } + return out, nil +} + +// readAgentEntries returns the MCP server entries of every MCP-capable agent, keyed by agent name then +// server name. A config that cannot be parsed fails the command: the listing would otherwise be wrong. +func readAgentEntries(ctx context.Context) (map[string]map[string]map[string]any, error) { + disk := map[string]map[string]map[string]any{} + for _, a := range agents.MCPAgents() { + entries, err := agentconfig.Read(ctx, a) + if err != nil { + return nil, err + } + disk[a.Name] = entries + } + return disk, nil +} + +// entryStatus compares the agent's entry for rec with the agent config on disk. +func entryStatus(rec mcp.Entry, agentName string, disk map[string]map[string]map[string]any) string { + current, ok := disk[agentName][rec.Name] + switch { + case !ok: + return agentStatusMissingOnDisk + case isOwnedEntry(current, rec): + return agentStatusInstalled + } + return agentStatusModified +} + +// isOwnedEntry reports whether an on-disk entry is the one this CLI wrote for rec: it runs +// `databricks aitools mcp serve` and its command is the recorded one. +func isOwnedEntry(current map[string]any, rec mcp.Entry) bool { + argv, ok := mcpconfig.Argv(current) + return ok && mcpconfig.IsDatabricksEntry(current) && argv[0] == rec.Command +} + +// unmanagedKind names how an entry reaches managed MCP servers without being written by this CLI, or +// returns "" for any other entry. +func unmanagedKind(entry map[string]any) string { + if !agentconfig.IsUnmanaged(entry) { + return "" + } + if argv, ok := mcpconfig.Argv(entry); ok && len(argv) > 1 && argv[1] == "mcp-proxy" { + return unmanagedKindUGProxy + } + return unmanagedKindAIGateway +} + +// recordedFor reports whether state has a server with this name installed for the agent. +func recordedFor(state *mcp.State, agentName, serverName string) bool { + return slices.ContainsFunc(state.Servers, func(e mcp.Entry) bool { + _, ok := e.Agents[agentName] + return ok && e.Name == serverName + }) +} + +// mcpAgentList joins the display names of agents, in the order given. +func mcpAgentList(names []string) string { + display := make([]string, 0, len(names)) + for _, name := range names { + display = append(display, agentDisplayName(name)) + } + return strings.Join(display, ", ") +} + +func renderMcpList(ctx context.Context, out mcpListOutput) { + if len(out.Profiles) == 0 && len(out.Unmanaged) == 0 { + cmdio.LogString(ctx, "No Databricks MCP servers installed by this CLI.") + return + } + for i, p := range out.Profiles { + if i > 0 { + cmdio.LogString(ctx, "") + } + cmdio.LogString(ctx, profileHeader(p, out.configPath)) + for _, s := range p.Servers { + cmdio.LogString(ctx, fmt.Sprintf(" %-24s %-30s %s", s.Name, s.Service, listAgentsText(s.Agents))) + } + if hint := profileHint(p); hint != "" { + cmdio.LogString(ctx, " "+hint) + } + } + if len(out.Unmanaged) == 0 { + return + } + if len(out.Profiles) > 0 { + cmdio.LogString(ctx, "") + } + cmdio.LogString(ctx, "Unmanaged Databricks MCP entries (not changed by this command):") + for _, u := range out.Unmanaged { + cmdio.LogString(ctx, fmt.Sprintf(" %-14s %-20s %s", agentDisplayName(u.Agent), u.Name, unmanagedKindText(u.Kind))) + } +} + +func profileHeader(p mcpListProfile, configPath string) string { + switch mcp.DriftKind(p.Status) { + case mcp.DriftProfileMissing: + return fmt.Sprintf("Profile %s (profile not found in %s)", p.Profile, configPath) + case mcp.DriftHostChanged: + return fmt.Sprintf("Profile %s (host changed, now %s)", p.Profile, p.Host) + } + return fmt.Sprintf("Profile %s (%s)", p.Profile, p.Host) +} + +// profileHint tells the user how to repair a profile whose servers no longer work. +func profileHint(p mcpListProfile) string { + switch mcp.DriftKind(p.Status) { + case mcp.DriftProfileMissing: + return fmt.Sprintf("broken: run `databricks aitools mcp remove --profile %s` or `databricks auth login --host %s --profile %s`", p.Profile, p.Host, p.Profile) + case mcp.DriftHostChanged: + return fmt.Sprintf("broken: run `databricks aitools mcp remove --profile %s` and add the servers again", p.Profile) + } + return "" +} + +func listAgentsText(agentList []mcpListAgent) string { + parts := make([]string, 0, len(agentList)) + for _, a := range agentList { + text := agentDisplayName(a.Name) + switch a.Status { + case agentStatusMissingOnDisk: + text += " (missing on disk)" + case agentStatusModified: + text += " (modified)" + } + parts = append(parts, text) + } + return strings.Join(parts, ", ") +} + +func unmanagedKindText(kind string) string { + if kind == unmanagedKindUGProxy { + return "ug mcp-proxy" + } + return "/ai-gateway/mcp-services/ URL" +} diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go new file mode 100644 index 00000000000..90bf4284094 --- /dev/null +++ b/cmd/aitools/mcp_list_test.go @@ -0,0 +1,134 @@ +package aitools + +import ( + "os" + "path/filepath" + "testing" + + "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/aitools/mcp/agentconfig" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const testDatabricksCommand = "/opt/databricks/bin/databricks" + +// seedInstall writes the server for an agent with Upsert, as `add` does, and returns the state record. +func seedInstall(t *testing.T, a *agents.Agent, name, service, profileName, host string) mcp.Entry { + t.Helper() + args := []string{"aitools", "mcp", "serve", "--profile", profileName, "--service", service, "--agent", a.Name} + path, _, err := agentconfig.Upsert(t.Context(), a, name, testDatabricksCommand, args, nil, false) + require.NoError(t, err) + return mcp.Entry{ + Name: name, + Service: service, + Profile: profileName, + Host: host, + Command: testDatabricksCommand, + Agents: map[string]mcp.AgentRecord{a.Name: {Path: path, Scope: "user"}}, + } +} + +func saveState(t *testing.T, entries ...mcp.Entry) { + t.Helper() + require.NoError(t, mcp.SaveState(t.Context(), &mcp.State{Servers: entries})) +} + +func TestEntryStatus(t *testing.T) { + rec := mcp.Entry{Name: "github-logfood", Command: testDatabricksCommand} + ours := map[string]any{"command": testDatabricksCommand, "args": []any{"aitools", "mcp", "serve"}} + otherCommand := map[string]any{"command": "/usr/bin/other", "args": []any{"aitools", "mcp", "serve"}} + disk := map[string]map[string]map[string]any{ + "claude-code": {"github-logfood": ours}, + "codex": {"github-logfood": otherCommand}, + } + + assert.Equal(t, agentStatusInstalled, entryStatus(rec, "claude-code", disk)) + assert.Equal(t, agentStatusMissingOnDisk, entryStatus(rec, "cursor", disk)) + assert.Equal(t, agentStatusModified, entryStatus(rec, "codex", disk), "a different command is not ours") + + moved := rec + moved.Command = "/usr/local/bin/databricks" + assert.Equal(t, agentStatusModified, entryStatus(moved, "claude-code", disk), "a recorded command that no longer matches is modified") +} + +func TestUnmanagedKind(t *testing.T) { + assert.Equal(t, unmanagedKindUGProxy, unmanagedKind(map[string]any{"command": "ug", "args": []any{"mcp-proxy", "web"}})) + assert.Equal(t, unmanagedKindUGProxy, unmanagedKind(map[string]any{"command": []any{"ug", "mcp-proxy"}})) + assert.Equal(t, unmanagedKindAIGateway, unmanagedKind(map[string]any{"url": "https://adb-1.test/ai-gateway/mcp-services/github"})) + assert.Empty(t, unmanagedKind(map[string]any{"command": "npx", "args": []any{"some-server"}})) + assert.Empty(t, unmanagedKind(map[string]any{"command": testDatabricksCommand, "args": []any{"aitools", "mcp", "serve"}})) +} + +func TestBuildMcpListDriftAndUnmanaged(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, `[logfood] +host = https://adb-1.test +token = t + +[dogfood] +host = https://adb-2.test +token = t +`) + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + // A server this CLI did not write, reached through ug, next to ours. + require.NoError(t, os.WriteFile(claudePath, []byte(`{"mcpServers":{"web_search":{"command":"ug","args":["mcp-proxy"]}}}`), 0o600)) + + genie := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + github := seedInstall(t, claude, "github-logfood", "system.ai.github", "logfood", "https://adb-old.test") + dogfood := seedInstall(t, claude, "genie_one_mcp-dogfood", "system.ai.genie_one_mcp", "dogfood", "https://adb-2.test") + // Recorded for claude-code but never written to its config file. + absent := mcp.Entry{ + Name: "dbsql-dogfood", Service: "system.ai.dbsql", Profile: "dogfood", Host: "https://adb-2.test", Command: testDatabricksCommand, + Agents: map[string]mcp.AgentRecord{"claude-code": {Path: claudePath, Scope: "user"}}, + } + // Written for a profile that is then removed from the config file, and changed by hand afterwards. + gone := seedInstall(t, claude, "dbsql-old", "system.ai.dbsql", "old", "https://adb-3.test") + _, _, err := agentconfig.Upsert(t.Context(), claude, "dbsql-old", "/usr/bin/other", []string{"aitools", "mcp", "serve"}, nil, true) + require.NoError(t, err) + + saveState(t, genie, github, dogfood, absent, gone) + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + + require.Len(t, out.Profiles, 3) + + dogfoodProfile := out.Profiles[0] + assert.Equal(t, "dogfood", dogfoodProfile.Profile) + assert.Equal(t, profileStatusOK, dogfoodProfile.Status) + assert.Equal(t, "https://adb-2.test", dogfoodProfile.Host) + assert.Equal(t, []mcpListAgent{{Name: "claude-code", Path: claudePath, Status: agentStatusInstalled}}, dogfoodProfile.Servers[0].Agents) + assert.Equal(t, []mcpListAgent{{Name: "claude-code", Path: claudePath, Status: agentStatusMissingOnDisk}}, dogfoodProfile.Servers[1].Agents) + + logfood := out.Profiles[1] + assert.Equal(t, "logfood", logfood.Profile) + assert.Equal(t, "host_changed", logfood.Status) + assert.Equal(t, "https://adb-1.test", logfood.Host, "a changed host shows the current host of the profile") + require.Len(t, logfood.Servers, 2) + assert.Equal(t, agentStatusInstalled, logfood.Servers[0].Agents[0].Status) + assert.Equal(t, agentStatusInstalled, logfood.Servers[1].Agents[0].Status) + + old := out.Profiles[2] + assert.Equal(t, "old", old.Profile) + assert.Equal(t, "profile_missing", old.Status) + assert.Equal(t, "https://adb-3.test", old.Host, "a missing profile shows the recorded host") + assert.Equal(t, agentStatusModified, old.Servers[0].Agents[0].Status) + + assert.Equal(t, []mcpListUnmanaged{{Agent: "claude-code", Name: "web_search", Kind: unmanagedKindUGProxy}}, out.Unmanaged) + assert.Equal(t, os.Getenv("DATABRICKS_CONFIG_FILE"), out.configPath) +} + +func TestBuildMcpListEmpty(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "") + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + assert.NotNil(t, out.Profiles, "an empty listing is [] in JSON, not null") + assert.NotNil(t, out.Unmanaged) + assert.Empty(t, out.Profiles) + assert.Empty(t, out.Unmanaged) +} diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go new file mode 100644 index 00000000000..4dad828a70b --- /dev/null +++ b/cmd/aitools/mcp_remove.go @@ -0,0 +1,284 @@ +package aitools + +import ( + "context" + "errors" + "fmt" + "maps" + "slices" + "strings" + + "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/aitools/mcp/agentconfig" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/telemetry/protos" + "github.com/spf13/cobra" +) + +type mcpRemoveFlags struct { + names string + agents string + all bool +} + +// removeOutput is the `mcp remove --output json` document. +type removeOutput struct { + Removed []removeRemoved `json:"removed"` + Skipped []removeSkipped `json:"skipped"` + Error string `json:"error,omitempty"` + ErrorCategory protos.AitoolsErrorCategory `json:"error_category,omitempty"` +} + +type removeRemoved struct { + Name string `json:"name"` + Service string `json:"service"` + Profile string `json:"profile"` + Agents []string `json:"agents"` +} + +type removeSkipped struct { + Name string `json:"name"` + Reason string `json:"reason"` +} + +// removeOutcome is what happened to one server in one agent config. +type removeOutcome int + +const ( + // removeDeleted means the entry was removed from the agent config. + removeDeleted removeOutcome = iota + // removePruned means the entry was already gone from the agent config, so only the state record goes. + removePruned + // removeKept means the entry on disk is not the one this CLI wrote, so it is left in place. + removeKept +) + +// recordDrop names one agent record to delete from state, identified by service and profile. +type recordDrop struct { + service string + profile string + agent string +} + +// NewMcpRemoveCmd returns `aitools mcp remove`. It needs no network. +func NewMcpRemoveCmd() *cobra.Command { + var f mcpRemoveFlags + cmd := &cobra.Command{ + Use: "remove", + Short: "Remove Databricks managed MCP servers from coding agents", + Long: `Remove Databricks managed MCP servers that this CLI installed. + +Choose servers with --names (server names as listed by 'aitools mcp list', or service names), +--profile, or --all. --profile narrows --all or --names to one profile, and --agents narrows +them to some agents. Interactive selection is not available yet, so one of --names, --profile +or --all is required. + +Only entries this CLI wrote are removed. An entry that was changed outside this CLI is left in +place and reported. Provider credentials are not deleted.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + jsonMode := installOutputIsJSON(cmd) + if jsonMode { + // JSON mode writes only the result document to stdout. + ctx = cmdio.WithQuiet(ctx) + } + + out := &removeOutput{Removed: []removeRemoved{}, Skipped: []removeSkipped{}} + runErr := runMcpRemove(ctx, cmd, f, jsonMode, out) + if !jsonMode { + return runErr + } + + // The document carries a top-level failure; per-agent failures are already in skipped. + if top := topLevelFailure(runErr); top != nil { + out.Error = top.Error() + out.ErrorCategory = errorCategory(top) + } + if err := renderJSON(cmd.OutOrStdout(), out); err != nil { + return err + } + if runErr != nil { + return root.ErrAlreadyPrinted + } + return nil + }, + } + + cmd.Flags().StringVar(&f.names, "names", "", "Servers to remove: server names or service names, comma-separated") + cmd.Flags().StringVar(&f.agents, "agents", "", "Agents to remove from, comma-separated (default: every agent the server is installed for)") + cmd.Flags().BoolVar(&f.all, "all", false, "Remove every server this CLI installed") + return cmd +} + +// runMcpRemove removes the chosen servers from the agent configs and records the result. An agent +// failure is reported in skipped; it is returned as an agentErrors only when --agents named the agent. +func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jsonMode bool, out *removeOutput) error { + names := splitAndTrim(f.names) + agentNames := splitAndTrim(f.agents) + profileName := profileFlag(cmd) + if err := validateMCPRemoveFlags(f.all, names, profileName); err != nil { + return err + } + + // A nil targets means every agent a server is installed for. + var targets []*agents.Agent + if len(agentNames) > 0 { + var err error + targets, err = resolveMCPAgents(agentNames) + if err != nil { + return err + } + } + + state, err := mcp.LoadState(ctx) + if err != nil { + return err + } + selected, err := selectInstalls(state, names, profileName) + if err != nil { + return err + } + + var drops []recordDrop + var agentErrs []error + for _, e := range selected { + removed := removeRemoved{Name: e.Name, Service: e.Service, Profile: e.Profile, Agents: []string{}} + for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { + if targets != nil && !slices.ContainsFunc(targets, func(a *agents.Agent) bool { return a.Name == agentName }) { + continue + } + outcome, err := removeAgentEntry(ctx, e, agentName) + if err != nil { + agentErrs = append(agentErrs, err) + out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Reason: fmt.Sprintf("could not update %s: %s", agentDisplayName(agentName), err)}) + continue + } + if outcome == removeKept { + out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Reason: fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place", agentDisplayName(agentName), e.Name)}) + continue + } + removed.Agents = append(removed.Agents, agentName) + drops = append(drops, recordDrop{service: e.Service, profile: e.Profile, agent: agentName}) + } + if len(removed.Agents) > 0 { + out.Removed = append(out.Removed, removed) + } + } + + if len(drops) > 0 { + if err := dropRecords(ctx, drops); err != nil { + return err + } + } + if !jsonMode { + printRemoveResults(ctx, out) + } + if len(targets) > 0 && len(agentErrs) > 0 { + return &agentErrors{err: errors.Join(agentErrs...)} + } + return nil +} + +// validateMCPRemoveFlags rejects a choice of servers that cannot run, before anything is read or written. +func validateMCPRemoveFlags(all bool, names []string, profileName string) error { + if all && len(names) > 0 { + return failure(protos.AitoolsErrorCategoryInvalidFlags, nil, "--all cannot be combined with --names") + } + if !all && len(names) == 0 && profileName == "" { + return failure(protos.AitoolsErrorCategoryInvalidFlags, nil, "pass --names, --profile or --all; interactive selection is not available yet") + } + return nil +} + +// selectInstalls returns the state entries named by names (server or service names), or every entry +// when names is empty. profileName, when set, narrows the choice to that profile. A name that matches +// nothing is an error, so a typo does not look like a successful removal. +func selectInstalls(state *mcp.State, names []string, profileName string) ([]mcp.Entry, error) { + var inProfile, selected []mcp.Entry + for _, e := range state.Servers { + if profileName == "" || e.Profile == profileName { + inProfile = append(inProfile, e) + } + } + for _, e := range inProfile { + if len(names) == 0 || slices.ContainsFunc(names, func(n string) bool { return matchesInstall(e, n) }) { + selected = append(selected, e) + } + } + where := "" + if profileName != "" { + where = " on profile " + profileName + } + for _, name := range names { + if !slices.ContainsFunc(inProfile, func(e mcp.Entry) bool { return matchesInstall(e, name) }) { + return nil, failure(categoryServiceNotFound, nil, "no installed MCP server named %s%s", name, where) + } + } + return selected, nil +} + +// matchesInstall reports whether a --names value means the entry: its server name, or its service name. +func matchesInstall(e mcp.Entry, name string) bool { + return e.Name == name || strings.EqualFold(e.Service, name) +} + +// removeAgentEntry removes the server from one agent config, but only when the entry there is the one +// this CLI wrote. The config is read first, so a config that cannot be parsed is an error, not a removal. +func removeAgentEntry(ctx context.Context, e mcp.Entry, agentName string) (removeOutcome, error) { + a := agents.ByName(agentName) + if a == nil { + return 0, fmt.Errorf("%s is not a known agent", agentName) + } + entries, err := agentconfig.Read(ctx, a) + if err != nil { + return 0, err + } + current, found := entries[e.Name] + switch { + case !found: + return removePruned, nil + case !isOwnedEntry(current, e): + return removeKept, nil + } + if _, err := agentconfig.Remove(ctx, a, e.Name); err != nil { + return 0, err + } + return removeDeleted, nil +} + +// dropRecords deletes the agent records from state and then the entries left without any agent. The +// state file is re-read first, so entries written since the selection are kept. +func dropRecords(ctx context.Context, drops []recordDrop) error { + state, err := mcp.LoadState(ctx) + if err != nil { + return err + } + for _, d := range drops { + i := slices.IndexFunc(state.Servers, func(e mcp.Entry) bool { + return e.Service == d.service && e.Profile == d.profile + }) + if i >= 0 { + delete(state.Servers[i].Agents, d.agent) + } + } + state.Servers = slices.DeleteFunc(state.Servers, func(e mcp.Entry) bool { + return len(e.Agents) == 0 + }) + return mcp.SaveState(ctx, state) +} + +func printRemoveResults(ctx context.Context, out *removeOutput) { + if len(out.Removed) == 0 && len(out.Skipped) == 0 { + cmdio.LogString(ctx, "No Databricks MCP servers to remove.") + return + } + for _, r := range out.Removed { + cmdio.LogString(ctx, fmt.Sprintf("Removed %s %s profile %s (%s)", r.Name, r.Service, r.Profile, mcpAgentList(r.Agents))) + } + for _, s := range out.Skipped { + cmdio.LogString(ctx, fmt.Sprintf("Skipped %s: %s", s.Name, s.Reason)) + } +} diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go new file mode 100644 index 00000000000..5eb1479cd28 --- /dev/null +++ b/cmd/aitools/mcp_remove_test.go @@ -0,0 +1,209 @@ +package aitools + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/aitools/mcp/agentconfig" + "github.com/databricks/cli/libs/flags" + "github.com/databricks/cli/libs/telemetry/protos" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestValidateMCPRemoveFlags(t *testing.T) { + assert.NoError(t, validateMCPRemoveFlags(false, []string{"github-logfood"}, "")) + assert.NoError(t, validateMCPRemoveFlags(false, nil, "logfood")) + assert.NoError(t, validateMCPRemoveFlags(true, nil, "")) + assert.NoError(t, validateMCPRemoveFlags(true, nil, "logfood")) + + err := validateMCPRemoveFlags(false, nil, "") + require.Error(t, err) + assert.Equal(t, "pass --names, --profile or --all; interactive selection is not available yet", err.Error()) + assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, errorCategory(err)) + + err = validateMCPRemoveFlags(true, []string{"github-logfood"}, "") + require.Error(t, err) + assert.Equal(t, "--all cannot be combined with --names", err.Error()) +} + +func TestSelectInstalls(t *testing.T) { + state := &mcp.State{Servers: []mcp.Entry{ + {Name: "github-logfood", Service: "system.ai.github", Profile: "logfood"}, + {Name: "github-dogfood", Service: "system.ai.github", Profile: "dogfood"}, + {Name: "genie_one_mcp-logfood", Service: "system.ai.genie_one_mcp", Profile: "logfood"}, + }} + + all, err := selectInstalls(state, nil, "") + require.NoError(t, err) + assert.Len(t, all, 3) + + byProfile, err := selectInstalls(state, nil, "logfood") + require.NoError(t, err) + require.Len(t, byProfile, 2) + assert.Equal(t, "github-logfood", byProfile[0].Name) + + // A service name matches every profile of that service, unless narrowed. + byService, err := selectInstalls(state, []string{"SYSTEM.AI.GITHUB"}, "") + require.NoError(t, err) + assert.Len(t, byService, 2) + + byName, err := selectInstalls(state, []string{"github-dogfood"}, "") + require.NoError(t, err) + require.Len(t, byName, 1) + assert.Equal(t, "dogfood", byName[0].Profile) + + _, err = selectInstalls(state, []string{"github-dogfood"}, "logfood") + require.Error(t, err) + assert.Equal(t, "no installed MCP server named github-dogfood on profile logfood", err.Error()) + assert.Equal(t, protos.AitoolsErrorCategory("MCP_SERVICE_NOT_FOUND"), errorCategory(err)) +} + +// newRemoveTestCmd runs `mcp remove` with args and returns its stdout. +func newRemoveTestCmd(t *testing.T, args ...string) (*bytes.Buffer, error) { + t.Helper() + parent := &cobra.Command{Use: "databricks", SilenceErrors: true, SilenceUsage: true} + output := flags.OutputText + parent.PersistentFlags().VarP(&output, "output", "o", "output type: text or json") + parent.PersistentFlags().StringP("profile", "p", "", "profile") + parent.AddCommand(NewMcpCmd()) + + var stdout bytes.Buffer + parent.SetOut(&stdout) + parent.SetErr(&bytes.Buffer{}) + parent.SetArgs(append([]string{"mcp", "remove"}, args...)) + return &stdout, parent.ExecuteContext(t.Context()) +} + +func readJSONFile(t *testing.T, path string) map[string]any { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err) + var doc map[string]any + require.NoError(t, json.Unmarshal(data, &doc)) + return doc +} + +func TestMcpRemoveDeletesOwnedEntriesAndPrunesMissing(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + require.NoError(t, os.WriteFile(claudePath, []byte(`{"numStartups": 3, "mcpServers": {"web_search": {"command": "ug", "args": ["mcp-proxy"]}}}`), 0o600)) + + genie := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + // Recorded but never written: remove prunes it without touching the file. + absent := mcp.Entry{ + Name: "dbsql-logfood", Service: "system.ai.dbsql", Profile: "logfood", Host: "https://adb-1.test", Command: testDatabricksCommand, + Agents: map[string]mcp.AgentRecord{"claude-code": {Path: claudePath, Scope: "user"}}, + } + other := seedInstall(t, claude, "github-dogfood", "system.ai.github", "dogfood", "https://adb-2.test") + saveState(t, genie, absent, other) + + stdout, err := newRemoveTestCmd(t, "--names", "genie_one_mcp-logfood,dbsql-logfood", "--output", "json") + require.NoError(t, err) + + var out removeOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + assert.Equal(t, []removeRemoved{ + {Name: "genie_one_mcp-logfood", Service: "system.ai.genie_one_mcp", Profile: "logfood", Agents: []string{"claude-code"}}, + {Name: "dbsql-logfood", Service: "system.ai.dbsql", Profile: "logfood", Agents: []string{"claude-code"}}, + }, out.Removed) + assert.Empty(t, out.Skipped) + + doc := readJSONFile(t, claudePath) + assert.EqualValues(t, 3, doc["numStartups"], "keys outside mcpServers are kept") + servers := doc["mcpServers"].(map[string]any) + assert.Contains(t, servers, "web_search", "entries we did not write are kept") + assert.Contains(t, servers, "github-dogfood", "other servers are kept") + assert.NotContains(t, servers, "genie_one_mcp-logfood") + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + require.Len(t, state.Servers, 1) + assert.Equal(t, "github-dogfood", state.Servers[0].Name) +} + +func TestMcpRemoveSkipsEntryChangedOutsideCLI(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + // Someone points the same name at another command. It is no longer ours. + _, _, err := agentconfig.Upsert(t.Context(), claude, "genie_one_mcp-logfood", "/usr/bin/other", []string{"serve"}, nil, true) + require.NoError(t, err) + before, err := os.ReadFile(claudePath) + require.NoError(t, err) + + stdout, err := newRemoveTestCmd(t, "--names", "genie_one_mcp-logfood", "--output", "json") + require.NoError(t, err) + + var out removeOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + assert.Empty(t, out.Removed) + require.Len(t, out.Skipped, 1) + assert.Equal(t, "genie_one_mcp-logfood", out.Skipped[0].Name) + + after, err := os.ReadFile(claudePath) + require.NoError(t, err) + assert.Equal(t, before, after, "the agent config is not written") + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Contains(t, state.Servers[0].Agents, "claude-code", "the record stays, so list keeps showing the entry") +} + +func TestMcpRemoveExplicitAgentFailureIsAnError(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + codex := agents.ByName("codex") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + codexPath := filepath.Join(home, ".codex", "config.toml") + require.NoError(t, os.MkdirAll(filepath.Dir(codexPath), 0o755)) + require.NoError(t, os.WriteFile(codexPath, []byte("[mcp_servers.broken\n"), 0o600)) + entry.Agents[codex.Name] = mcp.AgentRecord{Path: codexPath, Scope: "user"} + saveState(t, entry) + + stdout, err := newRemoveTestCmd(t, "--names", "genie_one_mcp-logfood", "--agents", "claude-code,codex", "--output", "json") + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + + var out removeOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + require.Len(t, out.Removed, 1) + assert.Equal(t, []string{"claude-code"}, out.Removed[0].Agents) + require.Len(t, out.Skipped, 1) + assert.Contains(t, out.Skipped[0].Reason, "could not update Codex CLI") + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + require.Len(t, state.Servers, 1) + assert.Equal(t, []string{"codex"}, keysOf(state.Servers[0].Agents)) +} + +func TestMcpRemoveFailsWithoutSelection(t *testing.T) { + withHome(t) + stdout, err := newRemoveTestCmd(t, "--output", "json") + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + + var out removeOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, out.ErrorCategory) + assert.Equal(t, "pass --names, --profile or --all; interactive selection is not available yet", out.Error) + assert.Empty(t, out.Removed) + assert.Empty(t, out.Skipped) +} + +func keysOf(m map[string]mcp.AgentRecord) []string { + var keys []string + for k := range m { + keys = append(keys, k) + } + return keys +} diff --git a/cmd/aitools/mcp_test.go b/cmd/aitools/mcp_test.go index ed571a8032d..6625a722351 100644 --- a/cmd/aitools/mcp_test.go +++ b/cmd/aitools/mcp_test.go @@ -31,7 +31,7 @@ func TestMcpCommandIsHidden(t *testing.T) { for _, c := range mcp.Commands() { names = append(names, c.Name()) } - assert.Equal(t, []string{"add"}, names) + assert.Equal(t, []string{"add", "list", "remove"}, names) for _, c := range NewAitoolsCmd().Commands() { if c.Name() == "mcp" { From 8e9f4617f43159b47f886ed6d88bdb80e07e0e47 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 14:35:04 +0000 Subject: [PATCH 02/26] Edit the hand-changed server in list and remove tests by hand The tests made a server look changed outside the CLI by writing it with agentconfig.Upsert and a command that is not the databricks binary. Upsert now refuses such a command, so the tests edit the Claude Code config file directly instead. Co-authored-by: Isaac --- cmd/aitools/mcp_list_test.go | 16 ++++++++++++++-- cmd/aitools/mcp_remove_test.go | 4 +--- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index 90bf4284094..0ae4570f6a7 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -1,6 +1,7 @@ package aitools import ( + "encoding/json" "os" "path/filepath" "testing" @@ -30,6 +31,18 @@ func seedInstall(t *testing.T, a *agents.Agent, name, service, profileName, host } } +// repointEntry sets the command of a Claude Code server in its config file, as a user editing the file +// by hand would. Upsert refuses a command that is not the databricks binary, so it cannot write this. +func repointEntry(t *testing.T, path, name, command string) { + t.Helper() + doc := readJSONFile(t, path) + server := doc["mcpServers"].(map[string]any)[name].(map[string]any) + server["command"] = command + data, err := json.MarshalIndent(doc, "", " ") + require.NoError(t, err) + require.NoError(t, os.WriteFile(path, data, 0o600)) +} + func saveState(t *testing.T, entries ...mcp.Entry) { t.Helper() require.NoError(t, mcp.SaveState(t.Context(), &mcp.State{Servers: entries})) @@ -86,8 +99,7 @@ token = t } // Written for a profile that is then removed from the config file, and changed by hand afterwards. gone := seedInstall(t, claude, "dbsql-old", "system.ai.dbsql", "old", "https://adb-3.test") - _, _, err := agentconfig.Upsert(t.Context(), claude, "dbsql-old", "/usr/bin/other", []string{"aitools", "mcp", "serve"}, nil, true) - require.NoError(t, err) + repointEntry(t, claudePath, "dbsql-old", "/usr/bin/other") saveState(t, genie, github, dogfood, absent, gone) diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index 5eb1479cd28..59d8026bdae 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -10,7 +10,6 @@ import ( "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" - "github.com/databricks/cli/libs/aitools/mcp/agentconfig" "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/telemetry/protos" "github.com/spf13/cobra" @@ -137,8 +136,7 @@ func TestMcpRemoveSkipsEntryChangedOutsideCLI(t *testing.T) { entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") saveState(t, entry) // Someone points the same name at another command. It is no longer ours. - _, _, err := agentconfig.Upsert(t.Context(), claude, "genie_one_mcp-logfood", "/usr/bin/other", []string{"serve"}, nil, true) - require.NoError(t, err) + repointEntry(t, claudePath, "genie_one_mcp-logfood", "/usr/bin/other") before, err := os.ReadFile(claudePath) require.NoError(t, err) From 3d8de31d33cf895485e3b2c129c47c8f5f3790a0 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 14:35:05 +0000 Subject: [PATCH 03/26] Create the Claude Code config dir in the list and remove acceptance cases mcp add now refuses an agent named with --agents whose config directory is missing. These two cases add for claude-code in a fresh HOME, so they create the directory first, as the other add cases do. Their goldens do not change. Co-authored-by: Isaac --- acceptance/cmd/aitools/mcp/drift-profile-missing/script | 1 + acceptance/cmd/aitools/mcp/list-and-remove/script | 1 + 2 files changed, 2 insertions(+) diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/script b/acceptance/cmd/aitools/mcp/drift-profile-missing/script index df22dc7f9dd..613e86f5ff2 100644 --- a/acceptance/cmd/aitools/mcp/drift-profile-missing/script +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/script @@ -1,5 +1,6 @@ # Isolate HOME so the agent config files and the state file land in this test directory. sethome home +mkdir -p home/.claude envsubst < .databrickscfg > out && mv out .databrickscfg export DATABRICKS_CONFIG_FILE=.databrickscfg diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/script b/acceptance/cmd/aitools/mcp/list-and-remove/script index 50928a0bde5..eedcf57862d 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/script +++ b/acceptance/cmd/aitools/mcp/list-and-remove/script @@ -1,5 +1,6 @@ # Isolate HOME so the agent config files and the state file land in this test directory. sethome home +mkdir -p home/.claude envsubst < .databrickscfg > out && mv out .databrickscfg export DATABRICKS_CONFIG_FILE=.databrickscfg From 1f6e234f14c412a2befa737229568b7b50e27fcb Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 17:06:54 +0000 Subject: [PATCH 04/26] Show list drift when mcp.Reconcile cannot check an entry Card 03 removed the profile.Profiler argument from mcp.Reconcile and made it return the drifts of the entries it could check, with a joined error for the others. `mcp list` keeps those drifts, renders as before, and then returns the error, so an unreadable config file is reported and the command exits non-zero. The list test entries are pinned to DATABRICKS_CONFIG_FILE, as `add` records them. Unpinned entries now check ~/.databrickscfg. Co-authored-by: Isaac --- cmd/aitools/mcp_list.go | 20 +++++++++------- cmd/aitools/mcp_list_test.go | 45 ++++++++++++++++++++++++++++++------ 2 files changed, 50 insertions(+), 15 deletions(-) diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index 4fedb5a5e9e..59207a79f40 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -37,6 +37,10 @@ type mcpListOutput struct { // configPath is the Databricks config file, named in the text of a missing profile. configPath string + + // checkErr is the error of mcp.Reconcile for entries it could not check. The drifts of the other + // entries are still listed; the command returns checkErr after rendering. + checkErr error } type mcpListProfile struct { @@ -84,10 +88,13 @@ This command makes no network calls and always exits 0 when entries have drifted return err } if installOutputIsJSON(cmd) { - return renderJSON(cmd.OutOrStdout(), out) + if err := renderJSON(cmd.OutOrStdout(), out); err != nil { + return err + } + return out.checkErr } renderMcpList(ctx, out) - return nil + return out.checkErr }, } } @@ -99,12 +106,9 @@ func buildMcpList(ctx context.Context) (mcpListOutput, error) { if err != nil { return out, err } - profiler := profile.GetProfiler(ctx) - drifts, err := mcp.Reconcile(ctx, profiler, state) - if err != nil { - return out, err - } - out.configPath, err = profiler.GetPath(ctx) + drifts, checkErr := mcp.Reconcile(ctx, state) + out.checkErr = checkErr + out.configPath, err = profile.GetProfiler(ctx).GetPath(ctx) if err != nil { return out, err } diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index 0ae4570f6a7..2516c02a944 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -16,18 +16,20 @@ import ( const testDatabricksCommand = "/opt/databricks/bin/databricks" // seedInstall writes the server for an agent with Upsert, as `add` does, and returns the state record. +// Like `add`, the record is pinned to DATABRICKS_CONFIG_FILE when that is set. func seedInstall(t *testing.T, a *agents.Agent, name, service, profileName, host string) mcp.Entry { t.Helper() args := []string{"aitools", "mcp", "serve", "--profile", profileName, "--service", service, "--agent", a.Name} path, _, err := agentconfig.Upsert(t.Context(), a, name, testDatabricksCommand, args, nil, false) require.NoError(t, err) return mcp.Entry{ - Name: name, - Service: service, - Profile: profileName, - Host: host, - Command: testDatabricksCommand, - Agents: map[string]mcp.AgentRecord{a.Name: {Path: path, Scope: "user"}}, + Name: name, + Service: service, + Profile: profileName, + Host: host, + Command: testDatabricksCommand, + ConfigFile: os.Getenv("DATABRICKS_CONFIG_FILE"), + Agents: map[string]mcp.AgentRecord{a.Name: {Path: path, Scope: "user"}}, } } @@ -95,7 +97,8 @@ token = t // Recorded for claude-code but never written to its config file. absent := mcp.Entry{ Name: "dbsql-dogfood", Service: "system.ai.dbsql", Profile: "dogfood", Host: "https://adb-2.test", Command: testDatabricksCommand, - Agents: map[string]mcp.AgentRecord{"claude-code": {Path: claudePath, Scope: "user"}}, + ConfigFile: os.Getenv("DATABRICKS_CONFIG_FILE"), + Agents: map[string]mcp.AgentRecord{"claude-code": {Path: claudePath, Scope: "user"}}, } // Written for a profile that is then removed from the config file, and changed by hand afterwards. gone := seedInstall(t, claude, "dbsql-old", "system.ai.dbsql", "old", "https://adb-3.test") @@ -133,6 +136,34 @@ token = t assert.Equal(t, os.Getenv("DATABRICKS_CONFIG_FILE"), out.configPath) } +// TestBuildMcpListReportsDriftWithCheckError checks that an entry whose config file cannot be read does +// not hide the drift of the other entries, and that the error is kept for the command to return. +func TestBuildMcpListReportsDriftWithCheckError(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "") + broken := filepath.Join(t.TempDir(), "broken.cfg") + require.NoError(t, os.WriteFile(broken, []byte("[logfood\n"), 0o600)) + + claude := agents.ByName("claude-code") + gone := seedInstall(t, claude, "dbsql-old", "system.ai.dbsql", "old", "https://adb-3.test") + unreadable := mcp.Entry{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", + Command: testDatabricksCommand, ConfigFile: broken, + } + saveState(t, gone, unreadable) + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + require.Error(t, out.checkErr) + assert.ErrorContains(t, out.checkErr, "MCP server github-logfood") + + require.Len(t, out.Profiles, 2) + assert.Equal(t, "logfood", out.Profiles[0].Profile) + assert.Equal(t, profileStatusOK, out.Profiles[0].Status) + assert.Equal(t, "old", out.Profiles[1].Profile) + assert.Equal(t, "profile_missing", out.Profiles[1].Status) +} + func TestBuildMcpListEmpty(t *testing.T) { withHome(t) writeDatabricksCfg(t, "") From 30bcd721cf27e4f4b07cdc5f3e5962b7d7744505 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 17:06:55 +0000 Subject: [PATCH 05/26] Read the MCP state from the shared skills state file in list acceptance Card 03 moved MCP records into the `mcp` section of ~/.databricks/aitools/skills/.state.json. The list-and-remove script read the old path and its top-level `servers` array. Co-authored-by: Isaac --- acceptance/cmd/aitools/mcp/list-and-remove/output.txt | 2 +- acceptance/cmd/aitools/mcp/list-and-remove/script | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt index 5fe0e212e09..13ee25b93e7 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt +++ b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt @@ -120,7 +120,7 @@ Skipped github-logfood: Claude Code has an entry named github-logfood that was c "web_search" ] ->>> jq [.servers[] | {name, profile, agents: (.agents | keys)}] home/.databricks/aitools/mcp/state.json +>>> jq .mcp | [.servers[] | {name, profile, agents: (.agents | keys)}] home/.databricks/aitools/skills/.state.json [ { "name": "github-logfood", diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/script b/acceptance/cmd/aitools/mcp/list-and-remove/script index eedcf57862d..cc98d246ac6 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/script +++ b/acceptance/cmd/aitools/mcp/list-and-remove/script @@ -25,7 +25,7 @@ trace $CLI aitools mcp list title "remove leaves the modified entry in place and says why" trace $CLI aitools mcp remove --names github-logfood,genie_one_mcp-logfood trace jq '.mcpServers | keys' home/.claude.json -trace jq '[.servers[] | {name, profile, agents: (.agents | keys)}]' home/.databricks/aitools/mcp/state.json +trace jq '.mcp | [.servers[] | {name, profile, agents: (.agents | keys)}]' home/.databricks/aitools/skills/.state.json title "remove --all removes what this CLI wrote and nothing else" trace $CLI aitools mcp remove --all --output json From 13fec1e14a957d8e12fa9d32f7a5c7f84bea20cb Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 19:35:59 +0000 Subject: [PATCH 06/26] Adapt list and remove to the reviewed add command Rename the list reader, since add now has its own readAgentEntries, and seed the services in the list acceptance scripts through the fake workspace, which add's tests now use instead of a static listing. Co-authored-by: Isaac --- acceptance/cmd/aitools/mcp/drift-profile-missing/script | 4 ++++ acceptance/cmd/aitools/mcp/list-and-remove/script | 6 ++++++ cmd/aitools/mcp_list.go | 6 +++--- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/script b/acceptance/cmd/aitools/mcp/drift-profile-missing/script index 613e86f5ff2..9e384e52081 100644 --- a/acceptance/cmd/aitools/mcp/drift-profile-missing/script +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/script @@ -4,6 +4,10 @@ mkdir -p home/.claude envsubst < .databrickscfg > out && mv out .databrickscfg export DATABRICKS_CONFIG_FILE=.databrickscfg +# The service, created in the fake workspace. The fake keeps one workspace per token, so each profile gets its own copy. +MSYS_NO_PATHCONV=1 $CLI api post "/api/2.1/unity-catalog/mcp-services?parent=schemas/system.ai&mcp_service_id=genie_one_mcp" --profile logfood --json '{"comment": "Ask questions about your data"}' &> LOG.create-genie_one_mcp-logfood +MSYS_NO_PATHCONV=1 $CLI api post "/api/2.1/unity-catalog/mcp-services?parent=schemas/system.ai&mcp_service_id=genie_one_mcp" --profile dogfood --json '{"comment": "Ask questions about your data"}' &> LOG.create-genie_one_mcp-dogfood + title "Both profiles get a server" trace $CLI aitools mcp add --profile logfood --names system.ai.genie_one_mcp --agents claude-code trace $CLI aitools mcp add --profile dogfood --names system.ai.genie_one_mcp --agents claude-code diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/script b/acceptance/cmd/aitools/mcp/list-and-remove/script index cc98d246ac6..6a087c07452 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/script +++ b/acceptance/cmd/aitools/mcp/list-and-remove/script @@ -4,6 +4,12 @@ mkdir -p home/.claude envsubst < .databrickscfg > out && mv out .databrickscfg export DATABRICKS_CONFIG_FILE=.databrickscfg +# The services of system.ai, created in the fake workspace. The fake keeps one workspace per token, so each profile +# gets its own copy. +MSYS_NO_PATHCONV=1 $CLI api post "/api/2.1/unity-catalog/mcp-services?parent=schemas/system.ai&mcp_service_id=genie_one_mcp" --profile logfood --json '{"comment": "Ask questions about your data"}' &> LOG.create-genie_one_mcp-logfood +MSYS_NO_PATHCONV=1 $CLI api post "/api/2.1/unity-catalog/mcp-services?parent=schemas/system.ai&mcp_service_id=github" --profile logfood --json '{"comment": "Repositories, issues, pull requests", "config": {"source_connection": {"name": "connections/github", "options": {"oauth_provider": "OAUTH_PROVIDER_GITHUB_MCP"}}}}' &> LOG.create-github-logfood +MSYS_NO_PATHCONV=1 $CLI api post "/api/2.1/unity-catalog/mcp-services?parent=schemas/system.ai&mcp_service_id=genie_one_mcp" --profile dogfood --json '{"comment": "Ask questions about your data"}' &> LOG.create-genie_one_mcp-dogfood + title "Two profiles, add twice: logfood gets two services, dogfood gets one" trace $CLI aitools mcp add --profile logfood --names system.ai.genie_one_mcp,system.ai.github --agents claude-code trace $CLI aitools mcp add --profile dogfood --names system.ai.genie_one_mcp --agents claude-code diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index 59207a79f40..e6427247f25 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -112,7 +112,7 @@ func buildMcpList(ctx context.Context) (mcpListOutput, error) { if err != nil { return out, err } - disk, err := readAgentEntries(ctx) + disk, err := readListEntries(ctx) if err != nil { return out, err } @@ -175,9 +175,9 @@ func buildMcpList(ctx context.Context) (mcpListOutput, error) { return out, nil } -// readAgentEntries returns the MCP server entries of every MCP-capable agent, keyed by agent name then +// readListEntries returns the MCP server entries of every MCP-capable agent, keyed by agent name then // server name. A config that cannot be parsed fails the command: the listing would otherwise be wrong. -func readAgentEntries(ctx context.Context) (map[string]map[string]map[string]any, error) { +func readListEntries(ctx context.Context) (map[string]map[string]map[string]any, error) { disk := map[string]map[string]map[string]any{} for _, a := range agents.MCPAgents() { entries, err := agentconfig.Read(ctx, a) From 72c090a3f1b7194f02ce598f3f1c210a0ad3e166 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 19:52:40 +0000 Subject: [PATCH 07/26] Export the MCP helpers that list and remove reuse SamePath, RemoveNamesCommand and RecreateCommand are exported from libs/aitools/mcp, and agentconfig.Path returns an agent's config path. Drift gets a NoHost flag for a profile whose section has no host. profileGoneError builds its recreate hint with RecreateCommand; its output does not change. Co-authored-by: Isaac --- libs/aitools/mcp/agentconfig/writer.go | 9 +++++++++ libs/aitools/mcp/binding.go | 22 +++++++++++++++++++--- libs/aitools/mcp/configfile.go | 4 ++-- libs/aitools/mcp/configfile_test.go | 4 ++-- libs/aitools/mcp/entry.go | 2 +- libs/aitools/mcp/state.go | 5 ++++- 6 files changed, 37 insertions(+), 9 deletions(-) diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index 74f632a99ea..0a9d52204b5 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -210,6 +210,15 @@ func Read(ctx context.Context, a *agents.Agent) (map[string]map[string]any, erro return entries, nil } +// Path returns the absolute path of agent a's MCP config file, as Read and Remove use it. It does not read the file. +func Path(ctx context.Context, a *agents.Agent) (string, error) { + spec, err := specOf(a) + if err != nil { + return "", err + } + return spec.Path(ctx) +} + // checkName refuses a name that no agent would accept. Upsert and Remove both // check it, so a name that cannot be written is never looked up either. func checkName(name string) error { diff --git a/libs/aitools/mcp/binding.go b/libs/aitools/mcp/binding.go index 0b4a2741c73..d18804c366a 100644 --- a/libs/aitools/mcp/binding.go +++ b/libs/aitools/mcp/binding.go @@ -187,6 +187,21 @@ func removeCommand(profileName string) string { return mcpRemoveCommand + " --profile " + shellquote.BashArg(profileName) } +// RemoveNamesCommand returns the command that removes the server named name. Server names are unique in the state. +func RemoveNamesCommand(name string) string { + return mcpRemoveCommand + " --names " + shellquote.BashArg(name) +} + +// RecreateCommand returns the command that logs in to host for profileName again. A server pinned to a config file +// passes that file as pinnedPath, so the login writes to the file the server reads; pass "" for an unpinned server. +func RecreateCommand(host, profileName, pinnedPath string) string { + command := authLoginCommand + " --host " + shellquote.BashArg(host) + " --profile " + shellquote.BashArg(profileName) + if pinnedPath != "" { + command = "DATABRICKS_CONFIG_FILE=" + shellquote.BashArg(pinnedPath) + " " + command + } + return command +} + // profileGoneError builds the PROFILE_NOT_FOUND error for a profile that the config file does not // name with a host, either because it is absent or because its section has no host. problem completes // the sentence "which ... in ". Without a state entry nothing was set up for the profile, so the @@ -198,10 +213,11 @@ func profileGoneError(name, profileName, path string, entry *Entry, problem stri message := fmt.Sprintf("MCP server %s needs Databricks profile \"%s\", which %s in %s. Set it up with: %s", name, profileName, problem, path, login) return &BindError{Category: BindProfileNotFound, message: message} } - recreate := authLoginCommand + " --host " + shellquote.BashArg(entry.Host) + " --profile " + shellquote.BashArg(profileName) + pinnedPath := "" if entry.ConfigFile != "" { - recreate = "DATABRICKS_CONFIG_FILE=" + shellquote.BashArg(path) + " " + recreate + pinnedPath = path } + recreate := RecreateCommand(entry.Host, profileName, pinnedPath) message := fmt.Sprintf("MCP server %s is bound to Databricks profile \"%s\", which %s in %s. Recreate it with: %s or remove the server with: %s", name, profileName, problem, path, recreate, removeCommand(profileName)) return &BindError{Category: BindProfileNotFound, message: message} @@ -259,7 +275,7 @@ func FindEntry(ctx context.Context, state *State, service, profileName, configFi unresolved = errors.Join(unresolved, fmt.Errorf("MCP server %s: %w", entry.Name, err)) continue } - if samePath(path, configFile) { + if SamePath(path, configFile) { return entry, nil } if other == nil { diff --git a/libs/aitools/mcp/configfile.go b/libs/aitools/mcp/configfile.go index 8e2b7346d5d..3d85e58dc6a 100644 --- a/libs/aitools/mcp/configfile.go +++ b/libs/aitools/mcp/configfile.go @@ -47,10 +47,10 @@ func AbsoluteAsWritten(path string) (string, error) { return wd + string(filepath.Separator) + path, nil } -// samePath reports whether two resolved config file paths name the same file. Existing files are +// SamePath reports whether two resolved config file paths name the same file. Existing files are // compared by identity, which also matches hard links and case variants on case-insensitive file // systems. Paths that do not exist are compared as text. -func samePath(a, b string) bool { +func SamePath(a, b string) bool { fa, errA := os.Stat(a) fb, errB := os.Stat(b) if errA == nil && errB == nil { diff --git a/libs/aitools/mcp/configfile_test.go b/libs/aitools/mcp/configfile_test.go index 7660a8a98cf..92286c1e21c 100644 --- a/libs/aitools/mcp/configfile_test.go +++ b/libs/aitools/mcp/configfile_test.go @@ -81,6 +81,6 @@ func TestSamePathComparesExistingFilesByIdentity(t *testing.T) { t.Skipf("cannot create hard link: %v", err) } - assert.True(t, samePath(a, b)) - assert.False(t, samePath(filepath.Join(dir, "x"), filepath.Join(dir, "X"))) + assert.True(t, SamePath(a, b)) + assert.False(t, SamePath(filepath.Join(dir, "x"), filepath.Join(dir, "X"))) } diff --git a/libs/aitools/mcp/entry.go b/libs/aitools/mcp/entry.go index 5b1161089e7..509e5055ff2 100644 --- a/libs/aitools/mcp/entry.go +++ b/libs/aitools/mcp/entry.go @@ -27,7 +27,7 @@ func EntryServes(ctx context.Context, entry map[string]any, service, profileName if err != nil { return false, fmt.Errorf("MCP server entry for %s on profile %s: %w", service, profileName, err) } - return samePath(path, configFile), nil + return SamePath(path, configFile), nil } // flagValue returns the value that follows flag in argv, or "" when flag is absent. diff --git a/libs/aitools/mcp/state.go b/libs/aitools/mcp/state.go index 9516442eac5..c373f0a7dc0 100644 --- a/libs/aitools/mcp/state.go +++ b/libs/aitools/mcp/state.go @@ -48,6 +48,9 @@ type Drift struct { // CurrentWorkspaceID is the workspace the profile names when Kind is DriftHostChanged: its // workspace_id, else the workspace in its host query. It is "" when the profile names none. CurrentWorkspaceID string + // NoHost is set when Kind is DriftProfileMissing because the profile's section has no host, not + // because the section is absent. + NoHost bool } // LoadState reads the MCP section of the aitools state file. A missing file or section @@ -112,7 +115,7 @@ func checkEntry(ctx context.Context, files configFiles, entry Entry) (*Drift, er } p, err := files.profile(path, entry.Profile) if errors.Is(err, errProfileMissing) || errors.Is(err, errProfileNoHost) { - return &Drift{Kind: DriftProfileMissing, Entry: entry}, nil + return &Drift{Kind: DriftProfileMissing, Entry: entry, NoHost: errors.Is(err, errProfileNoHost)}, nil } if err != nil { return nil, err From 33005c0e8270f0217208b3cf5f5da52929774ad2 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 20:02:38 +0000 Subject: [PATCH 08/26] Fix review findings in aitools mcp list and remove list and remove use the agent's current config path. An entry whose config moved is path_changed in list and is kept by remove, so an entry in a file the agent no longer reads is never pruned. Ownership of an entry is decided with mcp.EntryServes against the record's service, profile and config file, not the exact command. A re-add from another binary no longer makes the other agents' entries modified, and a hand-edited profile, service or pinned config file is modified. list groups profiles by name and resolved config file, reports drift per server (JSON adds config_file and a per-server status), and prints one hint per broken server with remove --names. The missing-profile text names the file that was checked and says when the section has no host. Hints come from the mcp command builders and keep DATABRICKS_CONFIG_FILE for pinned servers. Entries and agent configs that cannot be checked are warnings and status unknown; list exits 0. Entries that run serve without a record are listed as unmanaged (no-record); remove leaves them. remove reads each agent config once, drops records by server name, refuses a --profile with no servers and an --agents agent that no selected server has, fails when a server was removed from no agent, reports skipped entries with their agent, and prints results before a state save error. Tests: unit tests for each finding, and an acceptance scenario for path changes, unreadable configs, orphan entries and the refusals. Co-authored-by: Isaac --- .../mcp/drift-profile-missing/output.txt | 19 +- .../aitools/mcp/list-and-remove/output.txt | 9 +- .../mcp/repair-and-warnings/.databrickscfg | 3 + .../mcp/repair-and-warnings/out.test.toml | 1 + .../mcp/repair-and-warnings/output.txt | 66 +++ .../aitools/mcp/repair-and-warnings/script | 31 ++ cmd/aitools/mcp_list.go | 376 ++++++++++----- cmd/aitools/mcp_list_test.go | 454 +++++++++++++++--- cmd/aitools/mcp_remove.go | 172 ++++--- cmd/aitools/mcp_remove_test.go | 247 ++++++++-- 10 files changed, 1073 insertions(+), 305 deletions(-) create mode 100644 acceptance/cmd/aitools/mcp/repair-and-warnings/.databrickscfg create mode 100644 acceptance/cmd/aitools/mcp/repair-and-warnings/out.test.toml create mode 100644 acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt create mode 100644 acceptance/cmd/aitools/mcp/repair-and-warnings/script diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt b/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt index 8e872be443d..17d9ed9231b 100644 --- a/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt @@ -21,9 +21,9 @@ genie_one_mcp-dogfood system.ai.genie_one_mcp Profile dogfood ([DATABRICKS_URL]) genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code -Profile logfood (profile not found in .databrickscfg) +Profile logfood (profile not found in [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code - broken: run `databricks aitools mcp remove --profile logfood` or `databricks auth login --host [DATABRICKS_URL] --profile logfood` + broken: run `databricks aitools mcp remove --names genie_one_mcp-logfood` or `DATABRICKS_CONFIG_FILE=[TEST_TMP_DIR]/.databrickscfg databricks auth login --host [DATABRICKS_URL] --profile logfood` === dogfood now points at another host: list reports the host change @@ -33,12 +33,14 @@ Profile logfood (profile not found in .databrickscfg) { "profile": "dogfood", "host": "https://adb-2.test", + "config_file": "[TEST_TMP_DIR]/.databrickscfg", "status": "host_changed", "servers": [ { "name": "genie_one_mcp-dogfood", "service": "system.ai.genie_one_mcp", "sign_in_required": false, + "status": "host_changed", "agents": [ { "name": "claude-code", @@ -52,12 +54,14 @@ Profile logfood (profile not found in .databrickscfg) { "profile": "logfood", "host": "[DATABRICKS_URL]", + "config_file": "[TEST_TMP_DIR]/.databrickscfg", "status": "profile_missing", "servers": [ { "name": "genie_one_mcp-logfood", "service": "system.ai.genie_one_mcp", "sign_in_required": false, + "status": "profile_missing", "agents": [ { "name": "claude-code", @@ -69,16 +73,17 @@ Profile logfood (profile not found in .databrickscfg) ] } ], - "unmanaged": [] + "unmanaged": [], + "warnings": [] } === The same change in text >>> [CLI] aitools mcp list -Profile dogfood (host changed, now https://adb-2.test) +Profile dogfood (https://adb-2.test) genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code - broken: run `databricks aitools mcp remove --profile dogfood` and add the servers again + broken: it was set up for [DATABRICKS_URL], but profile dogfood now points at https://adb-2.test; run `databricks aitools mcp remove --names genie_one_mcp-dogfood` and add it again -Profile logfood (profile not found in .databrickscfg) +Profile logfood (profile not found in [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code - broken: run `databricks aitools mcp remove --profile logfood` or `databricks auth login --host [DATABRICKS_URL] --profile logfood` + broken: run `databricks aitools mcp remove --names genie_one_mcp-logfood` or `DATABRICKS_CONFIG_FILE=[TEST_TMP_DIR]/.databrickscfg databricks auth login --host [DATABRICKS_URL] --profile logfood` diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt index 13ee25b93e7..57aa6685e07 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt +++ b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt @@ -37,12 +37,14 @@ Profile logfood ([DATABRICKS_URL]) { "profile": "dogfood", "host": "[DATABRICKS_URL]", + "config_file": "[TEST_TMP_DIR]/.databrickscfg", "status": "ok", "servers": [ { "name": "genie_one_mcp-dogfood", "service": "system.ai.genie_one_mcp", "sign_in_required": false, + "status": "ok", "agents": [ { "name": "claude-code", @@ -56,12 +58,14 @@ Profile logfood ([DATABRICKS_URL]) { "profile": "logfood", "host": "[DATABRICKS_URL]", + "config_file": "[TEST_TMP_DIR]/.databrickscfg", "status": "ok", "servers": [ { "name": "genie_one_mcp-logfood", "service": "system.ai.genie_one_mcp", "sign_in_required": false, + "status": "ok", "agents": [ { "name": "claude-code", @@ -74,6 +78,7 @@ Profile logfood ([DATABRICKS_URL]) "name": "github-logfood", "service": "system.ai.github", "sign_in_required": true, + "status": "ok", "agents": [ { "name": "claude-code", @@ -85,7 +90,8 @@ Profile logfood ([DATABRICKS_URL]) ] } ], - "unmanaged": [] + "unmanaged": [], + "warnings": [] } === remove --profile removes that profile only @@ -139,6 +145,7 @@ Skipped github-logfood: Claude Code has an entry named github-logfood that was c "skipped": [ { "name": "github-logfood", + "agent": "claude-code", "reason": "Claude Code has an entry named github-logfood that was changed outside this CLI; left in place" } ] diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/.databrickscfg b/acceptance/cmd/aitools/mcp/repair-and-warnings/.databrickscfg new file mode 100644 index 00000000000..0369be633c5 --- /dev/null +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/.databrickscfg @@ -0,0 +1,3 @@ +[logfood] +host = $DATABRICKS_HOST +token = test-token-logfood diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/out.test.toml b/acceptance/cmd/aitools/mcp/repair-and-warnings/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt new file mode 100644 index 00000000000..9ec7dbadd8e --- /dev/null +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt @@ -0,0 +1,66 @@ + +=== Claude Code and Codex get the server + +>>> [CLI] aitools mcp add --profile logfood --names system.ai.genie_one_mcp --agents claude-code,codex +Profile logfood ([DATABRICKS_URL]) +Agents (named with --agents): claude-code, codex + +genie_one_mcp-logfood system.ai.genie_one_mcp + claude-code installed [TEST_TMP_DIR]/home/.claude.json + codex installed [TEST_TMP_DIR]/home/.codex/config.toml + +=== Claude Code reads its config from another directory: list says path changed, and remove keeps the entry + +>>> [CLI] aitools mcp list +Profile logfood ([DATABRICKS_URL]) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code (path changed), Codex CLI + +>>> [CLI] aitools mcp remove --names genie_one_mcp-logfood --agents claude-code +Skipped genie_one_mcp-logfood: Claude Code reads its config from [TEST_TMP_DIR]/home/moved-claude/.claude.json now, but genie_one_mcp-logfood was written to [TEST_TMP_DIR]/home/.claude.json; left in place, and its record kept + +>>> jq .mcpServers | keys home/.claude.json +[ + "genie_one_mcp-logfood" +] + +=== A Codex config that cannot be parsed is a warning: list exits 0 and shows Claude Code + +>>> [CLI] aitools mcp list +Profile logfood ([DATABRICKS_URL]) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code, Codex CLI (unknown) +Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 2: expected '.' or ']' to end table name, but got '\n' instead + +=== An entry that runs aitools mcp serve without an install record is unmanaged, and remove does not touch it + +>>> jq .mcpServers.orphan = {"command": "databricks", "args": ["aitools", "mcp", "serve", "--profile", "logfood", "--service", "system.ai.genie_one_mcp", "--agent", "claude-code"]} home/.claude.json + +>>> [CLI] aitools mcp list +Profile logfood ([DATABRICKS_URL]) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code, Codex CLI (unknown) + +Unmanaged Databricks MCP entries (not changed by this command): + Claude Code orphan databricks aitools mcp serve, no install record +Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 2: expected '.' or ']' to end table name, but got '\n' instead + +>>> [CLI] aitools mcp remove --names orphan +Error: no installed MCP server named orphan + +Exit code: 1 + +>>> jq .mcpServers | keys home/.claude.json +[ + "genie_one_mcp-logfood", + "orphan" +] + +=== A profile or an agent with nothing installed is refused + +>>> [CLI] aitools mcp remove --profile typo +Error: no installed MCP servers on profile typo + +Exit code: 1 + +>>> [CLI] aitools mcp remove --names genie_one_mcp-logfood --agents cursor +Error: no selected MCP server is installed for Cursor + +Exit code: 1 diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/script b/acceptance/cmd/aitools/mcp/repair-and-warnings/script new file mode 100644 index 00000000000..216c71fa871 --- /dev/null +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/script @@ -0,0 +1,31 @@ +# Isolate HOME so the agent config files and the state file land in this test directory. +sethome home +mkdir -p home/.claude home/.codex +envsubst < .databrickscfg > out && mv out .databrickscfg +export DATABRICKS_CONFIG_FILE=.databrickscfg + +MSYS_NO_PATHCONV=1 $CLI api post "/api/2.1/unity-catalog/mcp-services?parent=schemas/system.ai&mcp_service_id=genie_one_mcp" --profile logfood --json '{"comment": "Ask questions about your data"}' &> LOG.create-genie_one_mcp-logfood + +title "Claude Code and Codex get the server" +trace $CLI aitools mcp add --profile logfood --names system.ai.genie_one_mcp --agents claude-code,codex + +title "Claude Code reads its config from another directory: list says path changed, and remove keeps the entry" +export CLAUDE_CONFIG_DIR=$PWD/home/moved-claude +trace $CLI aitools mcp list +trace $CLI aitools mcp remove --names genie_one_mcp-logfood --agents claude-code +unset CLAUDE_CONFIG_DIR +trace jq '.mcpServers | keys' home/.claude.json + +title "A Codex config that cannot be parsed is a warning: list exits 0 and shows Claude Code" +echo "[mcp_servers.broken" > home/.codex/config.toml +trace $CLI aitools mcp list + +title "An entry that runs aitools mcp serve without an install record is unmanaged, and remove does not touch it" +trace jq '.mcpServers.orphan = {"command": "databricks", "args": ["aitools", "mcp", "serve", "--profile", "logfood", "--service", "system.ai.genie_one_mcp", "--agent", "claude-code"]}' home/.claude.json > home/claude.tmp && mv home/claude.tmp home/.claude.json +trace $CLI aitools mcp list +errcode trace $CLI aitools mcp remove --names orphan +trace jq '.mcpServers | keys' home/.claude.json + +title "A profile or an agent with nothing installed is refused" +errcode trace $CLI aitools mcp remove --profile typo +errcode trace $CLI aitools mcp remove --names genie_one_mcp-logfood --agents cursor diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index e6427247f25..3aaf2c6ecde 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -1,9 +1,11 @@ package aitools import ( + "cmp" "context" "fmt" "maps" + "path/filepath" "slices" "strings" @@ -12,49 +14,60 @@ import ( "github.com/databricks/cli/libs/aitools/mcp/agentconfig" "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/cmdio" - "github.com/databricks/cli/libs/databrickscfg/profile" "github.com/spf13/cobra" ) -// Agent entry statuses of `mcp list`. Profile statuses are the drift kinds of mcp.Reconcile, plus ok. +// Agent entry statuses of `mcp list`. Server statuses are the drift kinds of mcp.Reconcile, plus statusOK and +// statusUnknown, which is an entry or config that could not be checked. const ( agentStatusInstalled = "installed" agentStatusMissingOnDisk = "missing_on_disk" agentStatusModified = "modified" - profileStatusOK = "ok" + agentStatusPathChanged = "path_changed" + statusUnknown = "unknown" + statusOK = "ok" ) // Unmanaged entry kinds of `mcp list`. const ( unmanagedKindUGProxy = "ug-proxy" unmanagedKindAIGateway = "ai-gateway-url" + unmanagedKindNoRecord = "no-record" ) // mcpListOutput is the `mcp list` document. type mcpListOutput struct { Profiles []mcpListProfile `json:"profiles"` Unmanaged []mcpListUnmanaged `json:"unmanaged"` - - // configPath is the Databricks config file, named in the text of a missing profile. - configPath string - - // checkErr is the error of mcp.Reconcile for entries it could not check. The drifts of the other - // entries are still listed; the command returns checkErr after rendering. - checkErr error + // Warnings name the entries and agent configs that could not be checked. The rest is still listed. + Warnings []string `json:"warnings"` } +// mcpListProfile groups the servers that bind to one profile in one config file. type mcpListProfile struct { - Profile string `json:"profile"` - Host string `json:"host"` - Status string `json:"status"` - Servers []mcpListServer `json:"servers"` + Profile string `json:"profile"` + Host string `json:"host"` + // ConfigFile is the config file the servers are pinned to. It is set only when a server is pinned. + ConfigFile string `json:"config_file,omitempty"` + Status string `json:"status"` + Servers []mcpListServer `json:"servers"` + + // configPath is the config file the profile is read from, resolved. The text names it when the profile is missing. + configPath string + // noHost is set when Status is profile_missing because the profile's section has no host. + noHost bool } type mcpListServer struct { Name string `json:"name"` Service string `json:"service"` SignInRequired bool `json:"sign_in_required"` + Status string `json:"status"` Agents []mcpListAgent `json:"agents"` + + // entry is the state record, and drift the drift of the server from its profile, when it has one. + entry mcp.Entry + drift *mcp.Drift } type mcpListAgent struct { @@ -69,8 +82,14 @@ type mcpListUnmanaged struct { Kind string `json:"kind"` } +// profileKey groups the servers of one profile name in one resolved config file. +type profileKey struct { + profile string + path string +} + // NewMcpListCmd returns `aitools mcp list`. It reads the state file and the agent configs only, so it -// needs no network. Drift is reported, not failed: the command exits 0 when a profile is missing. +// needs no network. Drift and unreadable entries are reported, not failed: the command exits 0. func NewMcpListCmd() *cobra.Command { return &cobra.Command{ Use: "list", @@ -78,8 +97,10 @@ func NewMcpListCmd() *cobra.Command { Long: `List Databricks managed MCP servers installed by this CLI, grouped by profile, with the coding agents each one is in. Entries that drifted from their profile or from the agent config are reported. Entries in agent configs that this CLI did not write are listed as unmanaged and never changed. +Entries that run 'aitools mcp serve' but have no install record are listed as unmanaged too. -This command makes no network calls and always exits 0 when entries have drifted.`, +This command makes no network calls. It always exits 0 when entries have drifted or cannot be checked; +an entry or agent config that cannot be checked is a warning.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() @@ -88,130 +109,206 @@ This command makes no network calls and always exits 0 when entries have drifted return err } if installOutputIsJSON(cmd) { - if err := renderJSON(cmd.OutOrStdout(), out); err != nil { - return err - } - return out.checkErr + return renderJSON(cmd.OutOrStdout(), out) } renderMcpList(ctx, out) - return out.checkErr + return nil }, } } func buildMcpList(ctx context.Context) (mcpListOutput, error) { - out := mcpListOutput{Profiles: []mcpListProfile{}, Unmanaged: []mcpListUnmanaged{}} + out := mcpListOutput{Profiles: []mcpListProfile{}, Unmanaged: []mcpListUnmanaged{}, Warnings: []string{}} state, err := mcp.LoadState(ctx) if err != nil { return out, err } - drifts, checkErr := mcp.Reconcile(ctx, state) - out.checkErr = checkErr - out.configPath, err = profile.GetProfiler(ctx).GetPath(ctx) - if err != nil { - return out, err - } - disk, err := readListEntries(ctx) - if err != nil { - return out, err + // The configs of the agents named in the state are read too, so that a record for an agent outside the + // registry is reported as unknown, not as a moved config. + names := mcpAgentNames() + for _, e := range state.Servers { + for name := range e.Agents { + if !slices.Contains(names, name) { + names = append(names, name) + } + } } - - // A missing profile is reported before a changed host, since it has no host to compare. - drift := map[string]mcp.Drift{} - for _, d := range drifts { - if prev, ok := drift[d.Entry.Profile]; ok && prev.Kind == mcp.DriftProfileMissing { - continue + configs := readAgentConfigs(ctx, names) + for _, name := range names { + if cfg := configs[name]; cfg.err != nil { + out.Warnings = append(out.Warnings, fmt.Sprintf("could not read the %s config: %s", agentDisplayName(name), cfg.err)) } - drift[d.Entry.Profile] = d } - var profileNames []string + groups := map[profileKey]*mcpListProfile{} for _, e := range state.Servers { - if !slices.Contains(profileNames, e.Profile) { - profileNames = append(profileNames, e.Profile) + path, err := mcp.ResolveConfigFile(ctx, e.ConfigFile) + if err != nil { + // The entry cannot be checked, so it is grouped under its file as written. + path = e.ConfigFile } - } - slices.Sort(profileNames) - - for _, name := range profileNames { - p := mcpListProfile{Profile: name, Status: profileStatusOK, Servers: []mcpListServer{}} - for _, e := range state.Servers { - if e.Profile != name { - continue - } - if p.Host == "" { - p.Host = e.Host - } - s := mcpListServer{Name: e.Name, Service: e.Service, SignInRequired: e.SignInRequired, Agents: []mcpListAgent{}} - for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { - s.Agents = append(s.Agents, mcpListAgent{ - Name: agentName, - Path: e.Agents[agentName].Path, - Status: entryStatus(e, agentName, disk), - }) + key := profileKey{profile: e.Profile, path: path} + p, ok := groups[key] + if !ok { + p = &mcpListProfile{Profile: e.Profile, Host: e.Host, Status: statusOK, Servers: []mcpListServer{}, configPath: path} + groups[key] = p + } + if e.ConfigFile != "" { + p.ConfigFile = filepath.ToSlash(path) + } + s := mcpListServer{Name: e.Name, Service: e.Service, SignInRequired: e.SignInRequired, Status: statusOK, Agents: []mcpListAgent{}, entry: e} + drift, err := checkServer(ctx, e) + switch { + case err != nil: + s.Status = statusUnknown + out.Warnings = append(out.Warnings, err.Error()) + case drift != nil: + s.Status = string(drift.Kind) + s.drift = drift + p.Status = worseStatus(p.Status, s.Status) + p.noHost = p.noHost || drift.NoHost + if drift.Kind == mcp.DriftHostChanged { + p.Host = drift.CurrentHost } - p.Servers = append(p.Servers, s) } - if d, ok := drift[name]; ok { - p.Status = string(d.Kind) - if d.Kind == mcp.DriftHostChanged { - p.Host = d.CurrentHost + for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { + // A config that cannot be read is warned about once, for the agent; here its entries are unknown. + status := statusUnknown + if cfg := configs[agentName]; cfg.err == nil { + var err error + status, err = agentStatus(ctx, e, agentName, cfg) + if err != nil { + out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: could not check %s: %s", e.Name, agentDisplayName(agentName), err)) + } } + s.Agents = append(s.Agents, mcpListAgent{ + Name: agentName, + Path: filepath.ToSlash(e.Agents[agentName].Path), + Status: status, + }) } - out.Profiles = append(out.Profiles, p) + p.Servers = append(p.Servers, s) + } + + keys := slices.Collect(maps.Keys(groups)) + slices.SortFunc(keys, func(a, b profileKey) int { + return cmp.Or(strings.Compare(a.profile, b.profile), strings.Compare(a.path, b.path)) + }) + for _, key := range keys { + out.Profiles = append(out.Profiles, *groups[key]) } - for _, a := range agents.MCPAgents() { - entries := disk[a.Name] - for _, name := range slices.Sorted(maps.Keys(entries)) { - kind := unmanagedKind(entries[name]) - if kind == "" || recordedFor(state, a.Name, name) { + for _, name := range mcpAgentNames() { + cfg := configs[name] + if cfg.err != nil { + continue + } + for _, entryName := range slices.Sorted(maps.Keys(cfg.entries)) { + kind := unmanagedKind(cfg.entries[entryName]) + if kind == "" || recordedFor(state, name, entryName) { continue } - out.Unmanaged = append(out.Unmanaged, mcpListUnmanaged{Agent: a.Name, Name: name, Kind: kind}) + out.Unmanaged = append(out.Unmanaged, mcpListUnmanaged{Agent: name, Name: entryName, Kind: kind}) } } return out, nil } -// readListEntries returns the MCP server entries of every MCP-capable agent, keyed by agent name then -// server name. A config that cannot be parsed fails the command: the listing would otherwise be wrong. -func readListEntries(ctx context.Context) (map[string]map[string]map[string]any, error) { - disk := map[string]map[string]map[string]any{} - for _, a := range agents.MCPAgents() { - entries, err := agentconfig.Read(ctx, a) - if err != nil { - return nil, err - } - disk[a.Name] = entries +// checkServer returns the drift of one state entry from its profile, or nil when the profile still names the +// recorded host and workspace. err is set when the entry cannot be checked. +func checkServer(ctx context.Context, e mcp.Entry) (*mcp.Drift, error) { + drifts, err := mcp.Reconcile(ctx, &mcp.State{Servers: []mcp.Entry{e}}) + if err != nil || len(drifts) == 0 { + return nil, err } - return disk, nil + return &drifts[0], nil } -// entryStatus compares the agent's entry for rec with the agent config on disk. -func entryStatus(rec mcp.Entry, agentName string, disk map[string]map[string]map[string]any) string { - current, ok := disk[agentName][rec.Name] - switch { - case !ok: - return agentStatusMissingOnDisk - case isOwnedEntry(current, rec): - return agentStatusInstalled +// worseStatus returns the more serious of two server statuses, for the status of a profile. +func worseStatus(a, b string) string { + rank := map[string]int{statusOK: 0, string(mcp.DriftHostChanged): 1, string(mcp.DriftProfileMissing): 2} + if rank[b] > rank[a] { + return b + } + return a +} + +// agentConfig is one agent's MCP config, read once for a command. err is set when the config cannot be located or +// parsed; entries is nil then. +type agentConfig struct { + agent *agents.Agent + path string + entries map[string]map[string]any + err error +} + +// readAgentConfigs reads the MCP configs of the named agents, keyed by name. A config that cannot be read is an error +// of its agent, so the command can report it and go on with the others. +func readAgentConfigs(ctx context.Context, names []string) map[string]agentConfig { + configs := make(map[string]agentConfig, len(names)) + for _, name := range names { + configs[name] = readAgentConfig(ctx, name) + } + return configs +} + +func readAgentConfig(ctx context.Context, name string) agentConfig { + a := agents.ByName(name) + if a == nil { + return agentConfig{err: fmt.Errorf("%s is not a known agent", name)} + } + path, err := agentconfig.Path(ctx, a) + if err != nil { + return agentConfig{agent: a, err: err} + } + entries, err := agentconfig.Read(ctx, a) + if err != nil { + return agentConfig{agent: a, path: path, err: err} + } + return agentConfig{agent: a, path: path, entries: entries} +} + +// agentStatus compares the server's entry for one agent with that agent's config, which must have been read. An +// agent whose config moved is path_changed: the entry is in the file the record names, which this command does +// not read. err is set when the entry cannot be checked for ownership. +func agentStatus(ctx context.Context, rec mcp.Entry, agentName string, cfg agentConfig) (string, error) { + if !mcp.SamePath(rec.Agents[agentName].Path, cfg.path) { + return agentStatusPathChanged, nil + } + current, ok := cfg.entries[rec.Name] + if !ok { + return agentStatusMissingOnDisk, nil } - return agentStatusModified + owned, err := ownedBy(ctx, rec, current) + if err != nil { + return statusUnknown, err + } + if !owned { + return agentStatusModified, nil + } + return agentStatusInstalled, nil } -// isOwnedEntry reports whether an on-disk entry is the one this CLI wrote for rec: it runs -// `databricks aitools mcp serve` and its command is the recorded one. -func isOwnedEntry(current map[string]any, rec mcp.Entry) bool { - argv, ok := mcpconfig.Argv(current) - return ok && mcpconfig.IsDatabricksEntry(current) && argv[0] == rec.Command +// ownedBy reports whether the entry on disk is the one this CLI wrote for rec: a `databricks aitools mcp serve` +// for the record's service and profile, through the record's config file. The command is not compared, because +// an add from another binary replaces the record's command for every agent. err is set when the record's config +// file cannot be resolved. +func ownedBy(ctx context.Context, rec mcp.Entry, current map[string]any) (bool, error) { + configFile, err := mcp.ResolveConfigFile(ctx, rec.ConfigFile) + if err != nil { + return false, err + } + return mcp.EntryServes(ctx, current, rec.Service, rec.Profile, configFile) } -// unmanagedKind names how an entry reaches managed MCP servers without being written by this CLI, or -// returns "" for any other entry. +// unmanagedKind names how an entry reaches managed MCP servers without being recorded for its agent, or returns "" +// for any other entry. An entry that runs `aitools mcp serve` and is not recorded has no install record. func unmanagedKind(entry map[string]any) string { - if !agentconfig.IsUnmanaged(entry) { + switch { + case mcpconfig.IsDatabricksEntry(entry): + return unmanagedKindNoRecord + case !agentconfig.IsUnmanaged(entry): return "" } if argv, ok := mcpconfig.Argv(entry); ok && len(argv) > 1 && argv[1] == "mcp-proxy" { @@ -240,51 +337,67 @@ func mcpAgentList(names []string) string { func renderMcpList(ctx context.Context, out mcpListOutput) { if len(out.Profiles) == 0 && len(out.Unmanaged) == 0 { cmdio.LogString(ctx, "No Databricks MCP servers installed by this CLI.") - return } for i, p := range out.Profiles { if i > 0 { cmdio.LogString(ctx, "") } - cmdio.LogString(ctx, profileHeader(p, out.configPath)) + cmdio.LogString(ctx, profileHeader(p)) for _, s := range p.Servers { cmdio.LogString(ctx, fmt.Sprintf(" %-24s %-30s %s", s.Name, s.Service, listAgentsText(s.Agents))) + if hint := serverHint(p, s); hint != "" { + cmdio.LogString(ctx, " "+hint) + } } - if hint := profileHint(p); hint != "" { - cmdio.LogString(ctx, " "+hint) - } - } - if len(out.Unmanaged) == 0 { - return } - if len(out.Profiles) > 0 { - cmdio.LogString(ctx, "") + if len(out.Unmanaged) > 0 { + if len(out.Profiles) > 0 { + cmdio.LogString(ctx, "") + } + cmdio.LogString(ctx, "Unmanaged Databricks MCP entries (not changed by this command):") + for _, u := range out.Unmanaged { + cmdio.LogString(ctx, fmt.Sprintf(" %-14s %-20s %s", agentDisplayName(u.Agent), u.Name, unmanagedKindText(u.Kind))) + } } - cmdio.LogString(ctx, "Unmanaged Databricks MCP entries (not changed by this command):") - for _, u := range out.Unmanaged { - cmdio.LogString(ctx, fmt.Sprintf(" %-14s %-20s %s", agentDisplayName(u.Agent), u.Name, unmanagedKindText(u.Kind))) + for _, w := range out.Warnings { + cmdio.LogString(ctx, "Warning: "+w) } } -func profileHeader(p mcpListProfile, configPath string) string { - switch mcp.DriftKind(p.Status) { - case mcp.DriftProfileMissing: - return fmt.Sprintf("Profile %s (profile not found in %s)", p.Profile, configPath) - case mcp.DriftHostChanged: - return fmt.Sprintf("Profile %s (host changed, now %s)", p.Profile, p.Host) +func profileHeader(p mcpListProfile) string { + if p.Status == string(mcp.DriftProfileMissing) { + problem := "profile not found in" + if p.noHost { + problem = "profile has no host in" + } + return fmt.Sprintf("Profile %s (%s %s)", p.Profile, problem, filepath.ToSlash(p.configPath)) } return fmt.Sprintf("Profile %s (%s)", p.Profile, p.Host) } -// profileHint tells the user how to repair a profile whose servers no longer work. -func profileHint(p mcpListProfile) string { - switch mcp.DriftKind(p.Status) { - case mcp.DriftProfileMissing: - return fmt.Sprintf("broken: run `databricks aitools mcp remove --profile %s` or `databricks auth login --host %s --profile %s`", p.Profile, p.Host, p.Profile) - case mcp.DriftHostChanged: - return fmt.Sprintf("broken: run `databricks aitools mcp remove --profile %s` and add the servers again", p.Profile) +// serverHint tells the user how to repair a server whose profile no longer serves it. The remove command names the +// server, so that the other servers of the profile are kept. +func serverHint(p mcpListProfile, s mcpListServer) string { + if s.Status == statusUnknown { + return "unchecked: see the warning below" + } + if s.drift == nil { + return "" + } + remove := mcp.RemoveNamesCommand(s.Name) + if s.drift.Kind == mcp.DriftProfileMissing { + pinned := "" + if s.entry.ConfigFile != "" { + pinned = p.configPath + } + return fmt.Sprintf("broken: run `%s` or `%s`", remove, mcp.RecreateCommand(s.entry.Host, p.Profile, pinned)) + } + if mcp.NormalizeHost(s.entry.Host) != mcp.NormalizeHost(s.drift.CurrentHost) { + return fmt.Sprintf("broken: it was set up for %s, but profile %s now points at %s; run `%s` and add it again", + s.entry.Host, p.Profile, s.drift.CurrentHost, remove) } - return "" + return fmt.Sprintf("broken: it was set up for workspace %s, but profile %s now points at workspace %s; run `%s` and add it again", + s.entry.WorkspaceID, p.Profile, s.drift.CurrentWorkspaceID, remove) } func listAgentsText(agentList []mcpListAgent) string { @@ -296,6 +409,10 @@ func listAgentsText(agentList []mcpListAgent) string { text += " (missing on disk)" case agentStatusModified: text += " (modified)" + case agentStatusPathChanged: + text += " (path changed)" + case statusUnknown: + text += " (unknown)" } parts = append(parts, text) } @@ -303,8 +420,11 @@ func listAgentsText(agentList []mcpListAgent) string { } func unmanagedKindText(kind string) string { - if kind == unmanagedKindUGProxy { + switch kind { + case unmanagedKindUGProxy: return "ug mcp-proxy" + case unmanagedKindNoRecord: + return "databricks aitools mcp serve, no install record" } return "/ai-gateway/mcp-services/ URL" } diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index 2516c02a944..e2813a5e9f3 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -1,6 +1,7 @@ package aitools import ( + "bytes" "encoding/json" "os" "path/filepath" @@ -9,71 +10,350 @@ import ( "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/aitools/mcp/agentconfig" + "github.com/databricks/cli/libs/aitools/mcpconfig" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/flags" + "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const testDatabricksCommand = "/opt/databricks/bin/databricks" -// seedInstall writes the server for an agent with Upsert, as `add` does, and returns the state record. -// Like `add`, the record is pinned to DATABRICKS_CONFIG_FILE when that is set. -func seedInstall(t *testing.T, a *agents.Agent, name, service, profileName, host string) mcp.Entry { +// seed describes one server as `add` writes it: its binding, the command it runs and the config file it is pinned to. +type seed struct { + name, service, profile, host, command, configFile string +} + +// seedInstallEntry writes the server for an agent with Upsert and returns the state record. Like `add`, the entry +// and the record are pinned to configFile when it is set. +func seedInstallEntry(t *testing.T, a *agents.Agent, s seed) mcp.Entry { t.Helper() - args := []string{"aitools", "mcp", "serve", "--profile", profileName, "--service", service, "--agent", a.Name} - path, _, err := agentconfig.Upsert(t.Context(), a, name, testDatabricksCommand, args, nil, false) + args := []string{"aitools", "mcp", "serve", "--profile", s.profile, "--service", s.service, "--agent", a.Name} + var env map[string]string + if s.configFile != "" { + env = map[string]string{mcpconfig.ConfigFileEnv: s.configFile} + } + path, _, err := agentconfig.Upsert(t.Context(), a, s.name, s.command, args, env, false) require.NoError(t, err) return mcp.Entry{ - Name: name, - Service: service, - Profile: profileName, - Host: host, - Command: testDatabricksCommand, - ConfigFile: os.Getenv("DATABRICKS_CONFIG_FILE"), + Name: s.name, + Service: s.service, + Profile: s.profile, + Host: s.host, + Command: s.command, + ConfigFile: s.configFile, Agents: map[string]mcp.AgentRecord{a.Name: {Path: path, Scope: "user"}}, } } -// repointEntry sets the command of a Claude Code server in its config file, as a user editing the file -// by hand would. Upsert refuses a command that is not the databricks binary, so it cannot write this. -func repointEntry(t *testing.T, path, name, command string) { +// seedInstall writes the server for an agent with the test command, pinned to DATABRICKS_CONFIG_FILE when it is set. +func seedInstall(t *testing.T, a *agents.Agent, name, service, profileName, host string) mcp.Entry { + t.Helper() + return seedInstallEntry(t, a, seed{name, service, profileName, host, testDatabricksCommand, os.Getenv("DATABRICKS_CONFIG_FILE")}) +} + +// editEntry changes the server name in the agent config at path, as a user editing the file by hand would. +func editEntry(t *testing.T, path, name string, edit func(server map[string]any)) { t.Helper() doc := readJSONFile(t, path) - server := doc["mcpServers"].(map[string]any)[name].(map[string]any) - server["command"] = command + edit(doc["mcpServers"].(map[string]any)[name].(map[string]any)) data, err := json.MarshalIndent(doc, "", " ") require.NoError(t, err) require.NoError(t, os.WriteFile(path, data, 0o600)) } +// repointEntry sets the command of a Claude Code server, as a user editing the file by hand would. Upsert refuses a +// command that is not the databricks binary, so it cannot write this. +func repointEntry(t *testing.T, path, name, command string) { + t.Helper() + editEntry(t, path, name, func(server map[string]any) { server["command"] = command }) +} + +// setServeFlag changes the value of a `serve` flag in the argument list of a hand-edited entry. +func setServeFlag(t *testing.T, server map[string]any, flag, value string) { + t.Helper() + args, ok := server["args"].([]any) + require.True(t, ok) + for i := range args { + if args[i] == flag { + args[i+1] = value + return + } + } + require.Failf(t, "flag not found", "%s", flag) +} + func saveState(t *testing.T, entries ...mcp.Entry) { t.Helper() require.NoError(t, mcp.SaveState(t.Context(), &mcp.State{Servers: entries})) } -func TestEntryStatus(t *testing.T) { - rec := mcp.Entry{Name: "github-logfood", Command: testDatabricksCommand} - ours := map[string]any{"command": testDatabricksCommand, "args": []any{"aitools", "mcp", "serve"}} - otherCommand := map[string]any{"command": "/usr/bin/other", "args": []any{"aitools", "mcp", "serve"}} - disk := map[string]map[string]map[string]any{ - "claude-code": {"github-logfood": ours}, - "codex": {"github-logfood": otherCommand}, +// runMcpCmd runs `mcp list` or `mcp remove` with args and returns its stdout and stderr. +func runMcpCmd(t *testing.T, args ...string) (stdout, stderr *bytes.Buffer, err error) { + t.Helper() + parent := &cobra.Command{Use: "databricks", SilenceErrors: true, SilenceUsage: true} + output := flags.OutputText + parent.PersistentFlags().VarP(&output, "output", "o", "output type: text or json") + parent.PersistentFlags().StringP("profile", "p", "", "profile") + parent.AddCommand(NewMcpCmd()) + + ctx, stderrBuf := cmdio.NewTestContextWithStderr(t.Context()) + var stdoutBuf bytes.Buffer + parent.SetOut(&stdoutBuf) + parent.SetErr(&bytes.Buffer{}) + parent.SetArgs(append([]string{"mcp"}, args...)) + return &stdoutBuf, stderrBuf, parent.ExecuteContext(ctx) +} + +func TestMcpHandEditedEntryIsModified(t *testing.T) { + cases := []struct { + name string + edit func(t *testing.T, server map[string]any) + }{ + {"profile", func(t *testing.T, server map[string]any) { + setServeFlag(t, server, "--profile", "other") + }}, + {"service", func(t *testing.T, server map[string]any) { + setServeFlag(t, server, "--service", "system.ai.github") + }}, + {"pinned config file", func(t *testing.T, server map[string]any) { + server["env"] = map[string]any{mcpconfig.ConfigFileEnv: filepath.Join(t.TempDir(), "other.cfg")} + }}, } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + editEntry(t, claudePath, entry.Name, func(server map[string]any) { tc.edit(t, server) }) - assert.Equal(t, agentStatusInstalled, entryStatus(rec, "claude-code", disk)) - assert.Equal(t, agentStatusMissingOnDisk, entryStatus(rec, "cursor", disk)) - assert.Equal(t, agentStatusModified, entryStatus(rec, "codex", disk), "a different command is not ours") + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + require.Len(t, out.Profiles, 1) + require.Len(t, out.Profiles[0].Servers, 1) + require.Len(t, out.Profiles[0].Servers[0].Agents, 1) + assert.Equal(t, agentStatusModified, out.Profiles[0].Servers[0].Agents[0].Status, "an entry that serves another binding is not ours") - moved := rec - moved.Command = "/usr/local/bin/databricks" - assert.Equal(t, agentStatusModified, entryStatus(moved, "claude-code", disk), "a recorded command that no longer matches is modified") + stdout, _, err := runMcpCmd(t, "remove", "--names", entry.Name, "--output", "json") + require.NoError(t, err) + var removed removeOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &removed), stdout.String()) + assert.Empty(t, removed.Removed) + require.Len(t, removed.Skipped, 1) + assert.Equal(t, claude.Name, removed.Skipped[0].Agent) + assert.Contains(t, readJSONFile(t, claudePath)["mcpServers"], entry.Name, "the hand-edited entry is kept") + }) + } } -func TestUnmanagedKind(t *testing.T) { - assert.Equal(t, unmanagedKindUGProxy, unmanagedKind(map[string]any{"command": "ug", "args": []any{"mcp-proxy", "web"}})) - assert.Equal(t, unmanagedKindUGProxy, unmanagedKind(map[string]any{"command": []any{"ug", "mcp-proxy"}})) - assert.Equal(t, unmanagedKindAIGateway, unmanagedKind(map[string]any{"url": "https://adb-1.test/ai-gateway/mcp-services/github"})) - assert.Empty(t, unmanagedKind(map[string]any{"command": "npx", "args": []any{"some-server"}})) - assert.Empty(t, unmanagedKind(map[string]any{"command": testDatabricksCommand, "args": []any{"aitools", "mcp", "serve"}})) +func TestMcpReAddFromAnotherBinaryKeepsOtherAgentsRemovable(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + codex := agents.ByName("codex") + require.NoError(t, os.MkdirAll(filepath.Join(home, ".codex"), 0o755)) + + const name = "genie_one_mcp-logfood" + const service = "system.ai.genie_one_mcp" + first := seedInstall(t, claude, name, service, "logfood", "https://adb-1.test") + // `add` for codex ran from another binary, and the record keeps the command of the last add. + second := seedInstallEntry(t, codex, seed{name, service, "logfood", "https://adb-1.test", "/opt/other/databricks", first.ConfigFile}) + first.Agents[codex.Name] = second.Agents[codex.Name] + first.Command = "/opt/other/databricks" + saveState(t, first) + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + require.Len(t, out.Profiles, 1) + for _, a := range out.Profiles[0].Servers[0].Agents { + assert.Equal(t, agentStatusInstalled, a.Status, a.Name) + } + + stdout, _, err := runMcpCmd(t, "remove", "--names", name, "--output", "json") + require.NoError(t, err) + var removed removeOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &removed), stdout.String()) + require.Len(t, removed.Removed, 1) + assert.ElementsMatch(t, []string{"claude-code", "codex"}, removed.Removed[0].Agents) + assert.Empty(t, removed.Skipped) +} + +func TestBuildMcpListGroupsProfilesByConfigFile(t *testing.T) { + withHome(t) + dir := t.TempDir() + first := filepath.Join(dir, "first.cfg") + second := filepath.Join(dir, "second.cfg") + // The profile of the first file now names another host. The second file is healthy. + require.NoError(t, os.WriteFile(first, []byte("[logfood]\nhost = https://adb-9.test\ntoken = t\n"), 0o600)) + require.NoError(t, os.WriteFile(second, []byte("[logfood]\nhost = https://adb-2.test\ntoken = t\n"), 0o600)) + t.Setenv("DATABRICKS_CONFIG_FILE", first) + + claude := agents.ByName("claude-code") + // One server recorded against the old host, one added later against the new host, and one in the second file. + drifted := seedInstallEntry(t, claude, seed{"genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test", testDatabricksCommand, first}) + current := seedInstallEntry(t, claude, seed{"github-logfood", "system.ai.github", "logfood", "https://adb-9.test", testDatabricksCommand, first}) + healthy := seedInstallEntry(t, claude, seed{"genie_one_mcp-other", "system.ai.genie_one_mcp", "logfood", "https://adb-2.test", testDatabricksCommand, second}) + saveState(t, drifted, current, healthy) + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + require.Len(t, out.Profiles, 2, "one profile name in two config files is two groups") + + firstPath, err := mcp.ResolveConfigFile(t.Context(), first) + require.NoError(t, err) + secondPath, err := mcp.ResolveConfigFile(t.Context(), second) + require.NoError(t, err) + + pFirst := out.Profiles[0] + assert.Equal(t, filepath.ToSlash(firstPath), pFirst.ConfigFile) + assert.Equal(t, "host_changed", pFirst.Status, "the group status is the worst of its servers") + assert.Equal(t, "https://adb-9.test", pFirst.Host) + require.Len(t, pFirst.Servers, 2) + assert.Equal(t, "host_changed", pFirst.Servers[0].Status) + assert.Equal(t, "ok", pFirst.Servers[1].Status, "a server added against the new host is not broken") + + pSecond := out.Profiles[1] + assert.Equal(t, filepath.ToSlash(secondPath), pSecond.ConfigFile) + assert.Equal(t, "ok", pSecond.Status) + require.Len(t, pSecond.Servers, 1) + assert.Equal(t, "ok", pSecond.Servers[0].Status) +} + +func TestBuildMcpListReportsAgentPathChanged(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + recordedPath := filepath.Join(home, ".claude.json") + + // The agent config now lives elsewhere, so the entry is in a file this command does not read. + t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir()) + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + require.Len(t, out.Profiles, 1) + require.Len(t, out.Profiles[0].Servers, 1) + assert.Equal(t, []mcpListAgent{{Name: "claude-code", Path: filepath.ToSlash(recordedPath), Status: agentStatusPathChanged}}, out.Profiles[0].Servers[0].Agents) +} + +// TestBuildMcpListRecordForUnknownAgentIsUnknown checks that a record for an agent outside the registry is unknown, +// with a warning, rather than a config that moved. +func TestBuildMcpListRecordForUnknownAgentIsUnknown(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "") + saveState(t, mcp.Entry{ + Name: "genie_one_mcp-logfood", Service: "system.ai.genie_one_mcp", Profile: "logfood", Host: "https://adb-1.test", + Command: testDatabricksCommand, Agents: map[string]mcp.AgentRecord{"retired-agent": {Path: "/x/config.json", Scope: "user"}}, + }) + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + require.Len(t, out.Profiles, 1) + require.Len(t, out.Profiles[0].Servers, 1) + require.Len(t, out.Profiles[0].Servers[0].Agents, 1) + assert.Equal(t, statusUnknown, out.Profiles[0].Servers[0].Agents[0].Status) + assert.Contains(t, out.Warnings, "could not read the retired-agent config: retired-agent is not a known agent") +} + +func TestBuildMcpListUnknownServerIsWarnedNotOK(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "") + broken := filepath.Join(t.TempDir(), "broken.cfg") + require.NoError(t, os.WriteFile(broken, []byte("[logfood\n"), 0o600)) + + claude := agents.ByName("claude-code") + gone := seedInstall(t, claude, "dbsql-old", "system.ai.dbsql", "old", "https://adb-3.test") + unreadable := mcp.Entry{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", + Command: testDatabricksCommand, ConfigFile: broken, + } + saveState(t, gone, unreadable) + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + require.NotEmpty(t, out.Warnings) + assert.Contains(t, out.Warnings[0], "MCP server github-logfood") + + require.Len(t, out.Profiles, 2) + logfood := out.Profiles[0] + assert.Equal(t, "logfood", logfood.Profile) + assert.Equal(t, statusOK, logfood.Status) + require.Len(t, logfood.Servers, 1) + assert.Equal(t, statusUnknown, logfood.Servers[0].Status, "an entry that could not be checked is not reported as ok") + assert.Equal(t, "old", out.Profiles[1].Profile) + assert.Equal(t, "profile_missing", out.Profiles[1].Status) +} + +func TestMcpListExitsZeroWhenAnEntryCannotBeChecked(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "") + broken := filepath.Join(t.TempDir(), "broken.cfg") + require.NoError(t, os.WriteFile(broken, []byte("[logfood\n"), 0o600)) + saveState(t, mcp.Entry{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", + Command: testDatabricksCommand, ConfigFile: broken, + }) + + stdout, _, err := runMcpCmd(t, "list", "--output", "json") + require.NoError(t, err, "an entry that cannot be checked is a warning, not a failure") + var out mcpListOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + require.Len(t, out.Profiles, 1) + require.Len(t, out.Profiles[0].Servers, 1) + assert.Equal(t, statusUnknown, out.Profiles[0].Servers[0].Status) + assert.NotEmpty(t, out.Warnings) +} + +func TestBuildMcpListWarnsForUnreadableAgentConfig(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + codex := agents.ByName("codex") + require.NoError(t, os.MkdirAll(filepath.Join(home, ".codex"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".codex", "config.toml"), []byte("[mcp_servers.broken\n"), 0o600)) + claudePath := filepath.Join(home, ".claude.json") + require.NoError(t, os.WriteFile(claudePath, []byte(`{"mcpServers":{"web_search":{"command":"ug","args":["mcp-proxy"]}}}`), 0o600)) + + genie := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + // Recorded for codex, whose config cannot be read. + github := mcp.Entry{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", + Command: testDatabricksCommand, ConfigFile: os.Getenv("DATABRICKS_CONFIG_FILE"), + Agents: map[string]mcp.AgentRecord{codex.Name: {Path: filepath.Join(home, ".codex", "config.toml"), Scope: "user"}}, + } + saveState(t, genie, github) + + out, err := buildMcpList(t.Context()) + require.NoError(t, err, "one unreadable agent does not fail the listing") + require.Len(t, out.Warnings, 1) + assert.Contains(t, out.Warnings[0], "Codex CLI") + + require.Len(t, out.Profiles, 1) + servers := out.Profiles[0].Servers + require.Len(t, servers, 2) + require.Len(t, servers[0].Agents, 1) + require.Len(t, servers[1].Agents, 1) + assert.Equal(t, agentStatusInstalled, servers[0].Agents[0].Status, "the readable agent is listed") + assert.Equal(t, statusUnknown, servers[1].Agents[0].Status, "the recorded server in the unreadable agent is unknown") + assert.Equal(t, []mcpListUnmanaged{{Agent: "claude-code", Name: "web_search", Kind: unmanagedKindUGProxy}}, out.Unmanaged) +} + +func TestBuildMcpListReportsOrphanDatabricksEntry(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "") + claude := agents.ByName("claude-code") + // Written by this CLI, but its state record is gone. + seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + assert.Empty(t, out.Profiles) + assert.Equal(t, []mcpListUnmanaged{{Agent: "claude-code", Name: "genie_one_mcp-logfood", Kind: unmanagedKindNoRecord}}, out.Unmanaged) } func TestBuildMcpListDriftAndUnmanaged(t *testing.T) { @@ -108,70 +388,118 @@ token = t out, err := buildMcpList(t.Context()) require.NoError(t, err) - require.Len(t, out.Profiles, 3) dogfoodProfile := out.Profiles[0] assert.Equal(t, "dogfood", dogfoodProfile.Profile) - assert.Equal(t, profileStatusOK, dogfoodProfile.Status) + assert.Equal(t, statusOK, dogfoodProfile.Status) assert.Equal(t, "https://adb-2.test", dogfoodProfile.Host) - assert.Equal(t, []mcpListAgent{{Name: "claude-code", Path: claudePath, Status: agentStatusInstalled}}, dogfoodProfile.Servers[0].Agents) - assert.Equal(t, []mcpListAgent{{Name: "claude-code", Path: claudePath, Status: agentStatusMissingOnDisk}}, dogfoodProfile.Servers[1].Agents) + require.Len(t, dogfoodProfile.Servers, 2) + assert.Equal(t, []mcpListAgent{{Name: "claude-code", Path: filepath.ToSlash(claudePath), Status: agentStatusInstalled}}, dogfoodProfile.Servers[0].Agents) + assert.Equal(t, []mcpListAgent{{Name: "claude-code", Path: filepath.ToSlash(claudePath), Status: agentStatusMissingOnDisk}}, dogfoodProfile.Servers[1].Agents) logfood := out.Profiles[1] assert.Equal(t, "logfood", logfood.Profile) assert.Equal(t, "host_changed", logfood.Status) assert.Equal(t, "https://adb-1.test", logfood.Host, "a changed host shows the current host of the profile") require.Len(t, logfood.Servers, 2) + assert.Equal(t, "ok", logfood.Servers[0].Status) + require.Len(t, logfood.Servers[0].Agents, 1) assert.Equal(t, agentStatusInstalled, logfood.Servers[0].Agents[0].Status) + assert.Equal(t, "host_changed", logfood.Servers[1].Status, "github-logfood was recorded against the old host") + require.Len(t, logfood.Servers[1].Agents, 1) assert.Equal(t, agentStatusInstalled, logfood.Servers[1].Agents[0].Status) old := out.Profiles[2] assert.Equal(t, "old", old.Profile) assert.Equal(t, "profile_missing", old.Status) assert.Equal(t, "https://adb-3.test", old.Host, "a missing profile shows the recorded host") + require.Len(t, old.Servers, 1) + require.Len(t, old.Servers[0].Agents, 1) assert.Equal(t, agentStatusModified, old.Servers[0].Agents[0].Status) assert.Equal(t, []mcpListUnmanaged{{Agent: "claude-code", Name: "web_search", Kind: unmanagedKindUGProxy}}, out.Unmanaged) - assert.Equal(t, os.Getenv("DATABRICKS_CONFIG_FILE"), out.configPath) + pinned, err := mcp.ResolveConfigFile(t.Context(), os.Getenv("DATABRICKS_CONFIG_FILE")) + require.NoError(t, err) + assert.Equal(t, filepath.ToSlash(pinned), out.Profiles[0].ConfigFile, "a pinned profile names its config file") } -// TestBuildMcpListReportsDriftWithCheckError checks that an entry whose config file cannot be read does -// not hide the drift of the other entries, and that the error is kept for the command to return. -func TestBuildMcpListReportsDriftWithCheckError(t *testing.T) { +func TestBuildMcpListEmpty(t *testing.T) { withHome(t) writeDatabricksCfg(t, "") - broken := filepath.Join(t.TempDir(), "broken.cfg") - require.NoError(t, os.WriteFile(broken, []byte("[logfood\n"), 0o600)) - claude := agents.ByName("claude-code") - gone := seedInstall(t, claude, "dbsql-old", "system.ai.dbsql", "old", "https://adb-3.test") - unreadable := mcp.Entry{ - Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", - Command: testDatabricksCommand, ConfigFile: broken, + out, err := buildMcpList(t.Context()) + require.NoError(t, err) + assert.NotNil(t, out.Profiles, "an empty listing is [] in JSON, not null") + assert.NotNil(t, out.Unmanaged) + assert.NotNil(t, out.Warnings) + assert.Empty(t, out.Profiles) + assert.Empty(t, out.Unmanaged) +} + +func TestUnmanagedKind(t *testing.T) { + cases := []struct { + name string + entry map[string]any + want string + }{ + {"ug mcp-proxy", map[string]any{"command": "ug", "args": []any{"mcp-proxy", "web"}}, unmanagedKindUGProxy}, + {"ug mcp-proxy as a command array", map[string]any{"command": []any{"ug", "mcp-proxy"}}, unmanagedKindUGProxy}, + {"ai gateway URL", map[string]any{"url": "https://adb-1.test/ai-gateway/mcp-services/github"}, unmanagedKindAIGateway}, + {"other command", map[string]any{"command": "npx", "args": []any{"some-server"}}, ""}, + {"databricks serve without a record", map[string]any{"command": testDatabricksCommand, "args": []any{"aitools", "mcp", "serve"}}, unmanagedKindNoRecord}, } - saveState(t, gone, unreadable) + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, unmanagedKind(tc.entry)) + }) + } +} + +// TestRenderMcpListNamesTheFileAndTheRepair checks the text of the drifts: the file that was checked, the pinned +// variable in the repair hints, and the shell quoting of the profile. +func TestRenderMcpListNamesTheFileAndTheRepair(t *testing.T) { + withHome(t) + dir := t.TempDir() + pinned := filepath.Join(dir, "pinned.cfg") + require.NoError(t, os.WriteFile(pinned, []byte("[logfood]\nhost = https://adb-1.test\nworkspace_id = 222\ntoken = t\n\n[nohost]\ntoken = t\n"), 0o600)) + pinnedPath, err := mcp.ResolveConfigFile(t.Context(), pinned) + require.NoError(t, err) + claude := agents.ByName("claude-code") + + workspaceMoved := seedInstallEntry(t, claude, seed{"genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test", testDatabricksCommand, pinned}) + workspaceMoved.WorkspaceID = "111" + // The profile is not in the file at all, and the profile name needs quoting in the hint. + missing := seedInstallEntry(t, claude, seed{"github-gone", "system.ai.github", "gone profile", "https://adb-old.test", testDatabricksCommand, pinned}) + noHost := seedInstallEntry(t, claude, seed{"dbsql-nohost", "system.ai.dbsql", "nohost", "https://adb-4.test", testDatabricksCommand, pinned}) + saveState(t, workspaceMoved, missing, noHost) out, err := buildMcpList(t.Context()) require.NoError(t, err) - require.Error(t, out.checkErr) - assert.ErrorContains(t, out.checkErr, "MCP server github-logfood") - require.Len(t, out.Profiles, 2) - assert.Equal(t, "logfood", out.Profiles[0].Profile) - assert.Equal(t, profileStatusOK, out.Profiles[0].Status) - assert.Equal(t, "old", out.Profiles[1].Profile) - assert.Equal(t, "profile_missing", out.Profiles[1].Status) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + renderMcpList(ctx, out) + text := stderr.String() + + shownPath := filepath.ToSlash(pinnedPath) + assert.Contains(t, text, "Profile logfood (https://adb-1.test)") + assert.Contains(t, text, "broken: it was set up for workspace 111, but profile logfood now points at workspace 222; run `databricks aitools mcp remove --names genie_one_mcp-logfood` and add it again") + assert.Contains(t, text, "Profile gone profile (profile not found in "+shownPath+")") + assert.Contains(t, text, "broken: run `databricks aitools mcp remove --names github-gone` or `DATABRICKS_CONFIG_FILE="+pinnedPath+" databricks auth login --host https://adb-old.test --profile 'gone profile'`") + assert.Contains(t, text, "Profile nohost (profile has no host in "+shownPath+")") + assert.NotContains(t, text, "host changed") + assert.NotContains(t, text, "Warning", "every entry in this test can be checked") } -func TestBuildMcpListEmpty(t *testing.T) { +func TestRenderMcpListWarnsAndNamesUnmanagedRecords(t *testing.T) { withHome(t) writeDatabricksCfg(t, "") + claude := agents.ByName("claude-code") + seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") out, err := buildMcpList(t.Context()) require.NoError(t, err) - assert.NotNil(t, out.Profiles, "an empty listing is [] in JSON, not null") - assert.NotNil(t, out.Unmanaged) - assert.Empty(t, out.Profiles) - assert.Empty(t, out.Unmanaged) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + renderMcpList(ctx, out) + assert.Contains(t, stderr.String(), " Claude Code genie_one_mcp-logfood databricks aitools mcp serve, no install record") } diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 4dad828a70b..a56b5f9bcb0 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "maps" + "path/filepath" "slices" "strings" @@ -17,6 +18,9 @@ import ( "github.com/spf13/cobra" ) +// removeFlagsHint is the error for a run that names no servers. Tests check it too. +const removeFlagsHint = "pass --names, --profile or --all; interactive selection is not available yet" + type mcpRemoveFlags struct { names string agents string @@ -38,8 +42,11 @@ type removeRemoved struct { Agents []string `json:"agents"` } +// removeSkipped is one server that was left in one agent: the agent is named, since a server can be removed from +// some agents and skipped in others. type removeSkipped struct { Name string `json:"name"` + Agent string `json:"agent"` Reason string `json:"reason"` } @@ -51,15 +58,14 @@ const ( removeDeleted removeOutcome = iota // removePruned means the entry was already gone from the agent config, so only the state record goes. removePruned - // removeKept means the entry on disk is not the one this CLI wrote, so it is left in place. + // removeKept means the entry is left in place, because it is not the one this CLI wrote or the agent config moved. removeKept ) -// recordDrop names one agent record to delete from state, identified by service and profile. +// recordDrop names one agent record to delete from state: the server's name and the agent. type recordDrop struct { - service string - profile string - agent string + name string + agent string } // NewMcpRemoveCmd returns `aitools mcp remove`. It needs no network. @@ -75,8 +81,10 @@ Choose servers with --names (server names as listed by 'aitools mcp list', or se them to some agents. Interactive selection is not available yet, so one of --names, --profile or --all is required. -Only entries this CLI wrote are removed. An entry that was changed outside this CLI is left in -place and reported. Provider credentials are not deleted.`, +Only entries this CLI wrote are removed. An entry that was changed outside this CLI, or whose agent +config moved, is left in place and reported. Entries that run 'aitools mcp serve' without an install +record are not chosen by any flag; 'aitools mcp list' shows them as unmanaged. Provider credentials +are not deleted.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() @@ -98,7 +106,7 @@ place and reported. Provider credentials are not deleted.`, out.ErrorCategory = errorCategory(top) } if err := renderJSON(cmd.OutOrStdout(), out); err != nil { - return err + return errors.Join(runErr, err) } if runErr != nil { return root.ErrAlreadyPrinted @@ -113,8 +121,9 @@ place and reported. Provider credentials are not deleted.`, return cmd } -// runMcpRemove removes the chosen servers from the agent configs and records the result. An agent -// failure is reported in skipped; it is returned as an agentErrors only when --agents named the agent. +// runMcpRemove removes the chosen servers from the agent configs and records the result. Results are printed +// before a state failure is returned. An agent failure fails the command when --agents named the agent, or when a +// selected server was removed from no agent; otherwise it is reported in skipped. func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jsonMode bool, out *removeOutput) error { names := splitAndTrim(f.names) agentNames := splitAndTrim(f.agents) @@ -141,42 +150,61 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso if err != nil { return err } + if err := checkTargetsInstalled(selected, targets); err != nil { + return err + } + // Each agent config is read once, when the first selected server needs it. + configs := map[string]agentConfig{} var drops []recordDrop var agentErrs []error for _, e := range selected { removed := removeRemoved{Name: e.Name, Service: e.Service, Profile: e.Profile, Agents: []string{}} + var errs []error for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { if targets != nil && !slices.ContainsFunc(targets, func(a *agents.Agent) bool { return a.Name == agentName }) { continue } - outcome, err := removeAgentEntry(ctx, e, agentName) + cfg, ok := configs[agentName] + if !ok { + cfg = readAgentConfig(ctx, agentName) + configs[agentName] = cfg + } + outcome, reason, err := removeAgentEntry(ctx, e, agentName, cfg) if err != nil { - agentErrs = append(agentErrs, err) - out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Reason: fmt.Sprintf("could not update %s: %s", agentDisplayName(agentName), err)}) + errs = append(errs, err) + out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Agent: agentName, Reason: fmt.Sprintf("could not update %s: %s", agentDisplayName(agentName), err)}) continue } if outcome == removeKept { - out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Reason: fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place", agentDisplayName(agentName), e.Name)}) + out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Agent: agentName, Reason: reason}) continue } removed.Agents = append(removed.Agents, agentName) - drops = append(drops, recordDrop{service: e.Service, profile: e.Profile, agent: agentName}) + drops = append(drops, recordDrop{name: e.Name, agent: agentName}) } if len(removed.Agents) > 0 { out.Removed = append(out.Removed, removed) } + // A server that no agent gave up on is a failure. So is any agent failure when --agents named the agent. + if len(errs) > 0 && (len(removed.Agents) == 0 || targets != nil) { + for _, err := range errs { + agentErrs = appendDistinct(agentErrs, err) + } + } } + var saveErr error if len(drops) > 0 { - if err := dropRecords(ctx, drops); err != nil { - return err - } + saveErr = dropRecords(ctx, drops) } if !jsonMode { printRemoveResults(ctx, out) } - if len(targets) > 0 && len(agentErrs) > 0 { + if saveErr != nil { + return saveErr + } + if len(agentErrs) > 0 { return &agentErrors{err: errors.Join(agentErrs...)} } return nil @@ -188,69 +216,103 @@ func validateMCPRemoveFlags(all bool, names []string, profileName string) error return failure(protos.AitoolsErrorCategoryInvalidFlags, nil, "--all cannot be combined with --names") } if !all && len(names) == 0 && profileName == "" { - return failure(protos.AitoolsErrorCategoryInvalidFlags, nil, "pass --names, --profile or --all; interactive selection is not available yet") + return failure(protos.AitoolsErrorCategoryInvalidFlags, nil, removeFlagsHint) } return nil } -// selectInstalls returns the state entries named by names (server or service names), or every entry -// when names is empty. profileName, when set, narrows the choice to that profile. A name that matches -// nothing is an error, so a typo does not look like a successful removal. +// selectInstalls returns the state entries named by names (server or service names), or every entry when names is +// empty. profileName, when set, narrows the choice to that profile. A name that matches nothing, and a profile with no +// installed server, are errors, so a typo does not look like a successful removal. func selectInstalls(state *mcp.State, names []string, profileName string) ([]mcp.Entry, error) { - var inProfile, selected []mcp.Entry + where := "" + if profileName != "" { + where = " on profile " + profileName + } + var selected []mcp.Entry + found := make([]bool, len(names)) + inProfile := 0 for _, e := range state.Servers { - if profileName == "" || e.Profile == profileName { - inProfile = append(inProfile, e) + if profileName != "" && e.Profile != profileName { + continue } - } - for _, e := range inProfile { - if len(names) == 0 || slices.ContainsFunc(names, func(n string) bool { return matchesInstall(e, n) }) { + inProfile++ + chosen := len(names) == 0 + for i, name := range names { + if matchesInstall(e, name) { + found[i] = true + chosen = true + } + } + if chosen { selected = append(selected, e) } } - where := "" - if profileName != "" { - where = " on profile " + profileName - } - for _, name := range names { - if !slices.ContainsFunc(inProfile, func(e mcp.Entry) bool { return matchesInstall(e, name) }) { + for i, name := range names { + if !found[i] { return nil, failure(categoryServiceNotFound, nil, "no installed MCP server named %s%s", name, where) } } + if profileName != "" && inProfile == 0 { + return nil, failure(categoryServiceNotFound, nil, "no installed MCP servers on profile %s", profileName) + } return selected, nil } +// checkTargetsInstalled refuses an --agents agent that none of the selected servers is installed for. With no +// selected server there is nothing to check, so removing everything from an empty state stays a no-op. +func checkTargetsInstalled(selected []mcp.Entry, targets []*agents.Agent) error { + if len(selected) == 0 { + return nil + } + for _, a := range targets { + if !slices.ContainsFunc(selected, func(e mcp.Entry) bool { + _, ok := e.Agents[a.Name] + return ok + }) { + return failure(categoryServiceNotFound, nil, "no selected MCP server is installed for %s", a.DisplayName) + } + } + return nil +} + // matchesInstall reports whether a --names value means the entry: its server name, or its service name. func matchesInstall(e mcp.Entry, name string) bool { return e.Name == name || strings.EqualFold(e.Service, name) } -// removeAgentEntry removes the server from one agent config, but only when the entry there is the one -// this CLI wrote. The config is read first, so a config that cannot be parsed is an error, not a removal. -func removeAgentEntry(ctx context.Context, e mcp.Entry, agentName string) (removeOutcome, error) { - a := agents.ByName(agentName) - if a == nil { - return 0, fmt.Errorf("%s is not a known agent", agentName) +// removeAgentEntry removes the server from one agent config, but only when the entry there is the one this CLI +// wrote. The config was read by the caller; a config that could not be read is an error, not a removal. A config +// that moved is kept, since the entry may be in the file the record names. +func removeAgentEntry(ctx context.Context, e mcp.Entry, agentName string, cfg agentConfig) (removeOutcome, string, error) { + if cfg.err != nil { + return 0, "", cfg.err + } + recorded := e.Agents[agentName].Path + if !mcp.SamePath(recorded, cfg.path) { + return removeKept, fmt.Sprintf("%s reads its config from %s now, but %s was written to %s; left in place, and its record kept", + agentDisplayName(agentName), filepath.ToSlash(cfg.path), e.Name, filepath.ToSlash(recorded)), nil + } + current, found := cfg.entries[e.Name] + if !found { + return removePruned, "", nil } - entries, err := agentconfig.Read(ctx, a) + owned, err := ownedBy(ctx, e, current) if err != nil { - return 0, err + return 0, "", err } - current, found := entries[e.Name] - switch { - case !found: - return removePruned, nil - case !isOwnedEntry(current, e): - return removeKept, nil + if !owned { + return removeKept, fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place", agentDisplayName(agentName), e.Name), nil } - if _, err := agentconfig.Remove(ctx, a, e.Name); err != nil { - return 0, err + if _, err := agentconfig.Remove(ctx, cfg.agent, e.Name); err != nil { + return 0, "", err } - return removeDeleted, nil + return removeDeleted, "", nil } -// dropRecords deletes the agent records from state and then the entries left without any agent. The -// state file is re-read first, so entries written since the selection are kept. +// dropRecords deletes the agent records from state and then the entries left without any agent. Each record is +// matched by the name of its server, which is unique in state. The state file is re-read first, so entries written +// since the selection are kept. func dropRecords(ctx context.Context, drops []recordDrop) error { state, err := mcp.LoadState(ctx) if err != nil { @@ -258,7 +320,7 @@ func dropRecords(ctx context.Context, drops []recordDrop) error { } for _, d := range drops { i := slices.IndexFunc(state.Servers, func(e mcp.Entry) bool { - return e.Service == d.service && e.Profile == d.profile + return e.Name == d.name }) if i >= 0 { delete(state.Servers[i].Agents, d.agent) diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index 59d8026bdae..03379d45bc0 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -1,36 +1,52 @@ package aitools import ( - "bytes" "encoding/json" + "maps" "os" "path/filepath" + "slices" "testing" "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/aitools/mcp" - "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/telemetry/protos" - "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestValidateMCPRemoveFlags(t *testing.T) { - assert.NoError(t, validateMCPRemoveFlags(false, []string{"github-logfood"}, "")) - assert.NoError(t, validateMCPRemoveFlags(false, nil, "logfood")) - assert.NoError(t, validateMCPRemoveFlags(true, nil, "")) - assert.NoError(t, validateMCPRemoveFlags(true, nil, "logfood")) + names := []string{"github-logfood"} + cases := []struct { + name string + all bool + names []string + profile string + want string + }{ + {"names", false, names, "", ""}, + {"profile", false, nil, "logfood", ""}, + {"all", true, nil, "", ""}, + {"all with profile", true, nil, "logfood", ""}, + {"nothing", false, nil, "", removeFlagsHint}, + {"all with names", true, names, "", "--all cannot be combined with --names"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := validateMCPRemoveFlags(tc.all, tc.names, tc.profile) + if tc.want == "" { + assert.NoError(t, err) + return + } + require.Error(t, err) + assert.Equal(t, tc.want, err.Error()) + }) + } err := validateMCPRemoveFlags(false, nil, "") - require.Error(t, err) - assert.Equal(t, "pass --names, --profile or --all; interactive selection is not available yet", err.Error()) assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, errorCategory(err)) - - err = validateMCPRemoveFlags(true, []string{"github-logfood"}, "") - require.Error(t, err) - assert.Equal(t, "--all cannot be combined with --names", err.Error()) } func TestSelectInstalls(t *testing.T) { @@ -62,23 +78,17 @@ func TestSelectInstalls(t *testing.T) { _, err = selectInstalls(state, []string{"github-dogfood"}, "logfood") require.Error(t, err) assert.Equal(t, "no installed MCP server named github-dogfood on profile logfood", err.Error()) - assert.Equal(t, protos.AitoolsErrorCategory("MCP_SERVICE_NOT_FOUND"), errorCategory(err)) -} + assert.Equal(t, categoryServiceNotFound, errorCategory(err)) -// newRemoveTestCmd runs `mcp remove` with args and returns its stdout. -func newRemoveTestCmd(t *testing.T, args ...string) (*bytes.Buffer, error) { - t.Helper() - parent := &cobra.Command{Use: "databricks", SilenceErrors: true, SilenceUsage: true} - output := flags.OutputText - parent.PersistentFlags().VarP(&output, "output", "o", "output type: text or json") - parent.PersistentFlags().StringP("profile", "p", "", "profile") - parent.AddCommand(NewMcpCmd()) - - var stdout bytes.Buffer - parent.SetOut(&stdout) - parent.SetErr(&bytes.Buffer{}) - parent.SetArgs(append([]string{"mcp", "remove"}, args...)) - return &stdout, parent.ExecuteContext(t.Context()) + // A profile with no installed server is a typo or an empty profile, not an empty removal. + _, err = selectInstalls(state, nil, "typo") + require.Error(t, err) + assert.Equal(t, "no installed MCP servers on profile typo", err.Error()) + assert.Equal(t, categoryServiceNotFound, errorCategory(err)) + + none, err := selectInstalls(&mcp.State{}, nil, "") + require.NoError(t, err, "--all on an empty state is a no-op") + assert.Empty(t, none) } func readJSONFile(t *testing.T, path string) map[string]any { @@ -90,6 +100,14 @@ func readJSONFile(t *testing.T, path string) map[string]any { return doc } +// readRemoveOutput decodes the JSON document of `mcp remove`. +func readRemoveOutput(t *testing.T, stdout string) removeOutput { + t.Helper() + var out removeOutput + require.NoError(t, json.Unmarshal([]byte(stdout), &out), stdout) + return out +} + func TestMcpRemoveDeletesOwnedEntriesAndPrunesMissing(t *testing.T) { home := withHome(t) claude := agents.ByName("claude-code") @@ -105,11 +123,10 @@ func TestMcpRemoveDeletesOwnedEntriesAndPrunesMissing(t *testing.T) { other := seedInstall(t, claude, "github-dogfood", "system.ai.github", "dogfood", "https://adb-2.test") saveState(t, genie, absent, other) - stdout, err := newRemoveTestCmd(t, "--names", "genie_one_mcp-logfood,dbsql-logfood", "--output", "json") + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood,dbsql-logfood", "--output", "json") require.NoError(t, err) - var out removeOutput - require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + out := readRemoveOutput(t, stdout.String()) assert.Equal(t, []removeRemoved{ {Name: "genie_one_mcp-logfood", Service: "system.ai.genie_one_mcp", Profile: "logfood", Agents: []string{"claude-code"}}, {Name: "dbsql-logfood", Service: "system.ai.dbsql", Profile: "logfood", Agents: []string{"claude-code"}}, @@ -140,14 +157,14 @@ func TestMcpRemoveSkipsEntryChangedOutsideCLI(t *testing.T) { before, err := os.ReadFile(claudePath) require.NoError(t, err) - stdout, err := newRemoveTestCmd(t, "--names", "genie_one_mcp-logfood", "--output", "json") + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood", "--output", "json") require.NoError(t, err) - var out removeOutput - require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + out := readRemoveOutput(t, stdout.String()) assert.Empty(t, out.Removed) require.Len(t, out.Skipped, 1) assert.Equal(t, "genie_one_mcp-logfood", out.Skipped[0].Name) + assert.Equal(t, "claude-code", out.Skipped[0].Agent) after, err := os.ReadFile(claudePath) require.NoError(t, err) @@ -155,9 +172,38 @@ func TestMcpRemoveSkipsEntryChangedOutsideCLI(t *testing.T) { state, err := mcp.LoadState(t.Context()) require.NoError(t, err) + require.Len(t, state.Servers, 1) assert.Contains(t, state.Servers[0].Agents, "claude-code", "the record stays, so list keeps showing the entry") } +func TestMcpRemoveKeepsEntryWhenAgentConfigMoved(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + + // The agent now reads its config from another directory. The entry is still in the file it was written to. + moved := t.TempDir() + t.Setenv("CLAUDE_CONFIG_DIR", moved) + + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood", "--output", "json") + require.NoError(t, err) + + out := readRemoveOutput(t, stdout.String()) + assert.Empty(t, out.Removed, "a file the agent no longer reads is not pruned") + require.Len(t, out.Skipped, 1) + assert.Equal(t, "claude-code", out.Skipped[0].Agent) + assert.Contains(t, out.Skipped[0].Reason, filepath.ToSlash(claudePath), "the reason names the file the entry was written to") + assert.Contains(t, out.Skipped[0].Reason, filepath.ToSlash(filepath.Join(moved, ".claude.json")), "and the file the agent reads now") + + assert.Contains(t, readJSONFile(t, claudePath)["mcpServers"], "genie_one_mcp-logfood", "the entry in the old file is kept") + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + require.Len(t, state.Servers, 1) + assert.Contains(t, state.Servers[0].Agents, "claude-code", "the record is kept, so list can show the path change") +} + func TestMcpRemoveExplicitAgentFailureIsAnError(t *testing.T) { home := withHome(t) claude := agents.ByName("claude-code") @@ -169,39 +215,138 @@ func TestMcpRemoveExplicitAgentFailureIsAnError(t *testing.T) { entry.Agents[codex.Name] = mcp.AgentRecord{Path: codexPath, Scope: "user"} saveState(t, entry) - stdout, err := newRemoveTestCmd(t, "--names", "genie_one_mcp-logfood", "--agents", "claude-code,codex", "--output", "json") + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood", "--agents", "claude-code,codex", "--output", "json") require.ErrorIs(t, err, root.ErrAlreadyPrinted) - var out removeOutput - require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + out := readRemoveOutput(t, stdout.String()) require.Len(t, out.Removed, 1) assert.Equal(t, []string{"claude-code"}, out.Removed[0].Agents) require.Len(t, out.Skipped, 1) + assert.Equal(t, "codex", out.Skipped[0].Agent) assert.Contains(t, out.Skipped[0].Reason, "could not update Codex CLI") state, err := mcp.LoadState(t.Context()) require.NoError(t, err) require.Len(t, state.Servers, 1) - assert.Equal(t, []string{"codex"}, keysOf(state.Servers[0].Agents)) + assert.Equal(t, []string{"codex"}, slices.Sorted(maps.Keys(state.Servers[0].Agents))) } -func TestMcpRemoveFailsWithoutSelection(t *testing.T) { +func TestMcpRemoveFailsWhenNoAgentWasRemoved(t *testing.T) { + home := withHome(t) + codex := agents.ByName("codex") + codexPath := filepath.Join(home, ".codex", "config.toml") + require.NoError(t, os.MkdirAll(filepath.Dir(codexPath), 0o755)) + require.NoError(t, os.WriteFile(codexPath, []byte("[mcp_servers.broken\n"), 0o600)) + saveState(t, mcp.Entry{ + Name: "genie_one_mcp-logfood", Service: "system.ai.genie_one_mcp", Profile: "logfood", Host: "https://adb-1.test", + Command: testDatabricksCommand, Agents: map[string]mcp.AgentRecord{codex.Name: {Path: codexPath, Scope: "user"}}, + }) + + // No --agents: the failure is only a warning when another agent was removed. Here none was. + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood", "--output", "json") + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + + out := readRemoveOutput(t, stdout.String()) + assert.Empty(t, out.Removed) + require.Len(t, out.Skipped, 1) + assert.Equal(t, "codex", out.Skipped[0].Agent) +} + +func TestMcpRemoveRefusesProfileAndAgentWithNothingInstalled(t *testing.T) { withHome(t) - stdout, err := newRemoveTestCmd(t, "--output", "json") + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + + stdout, _, err := runMcpCmd(t, "remove", "--profile", "typo", "--output", "json") require.ErrorIs(t, err, root.ErrAlreadyPrinted) + out := readRemoveOutput(t, stdout.String()) + assert.Equal(t, "no installed MCP servers on profile typo", out.Error) + assert.Equal(t, categoryServiceNotFound, out.ErrorCategory) - var out removeOutput - require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) - assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, out.ErrorCategory) - assert.Equal(t, "pass --names, --profile or --all; interactive selection is not available yet", out.Error) + stdout, _, err = runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood", "--agents", "cursor", "--output", "json") + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + out = readRemoveOutput(t, stdout.String()) + assert.Equal(t, "no selected MCP server is installed for Cursor", out.Error) + assert.Equal(t, categoryServiceNotFound, out.ErrorCategory) + + // Nothing was removed by either refusal. + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + require.Len(t, state.Servers, 1) + assert.Contains(t, state.Servers[0].Agents, "claude-code") +} + +func TestMcpRemoveReportsResultsWhenStateCannotBeSaved(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + + // The agent entry is deleted first; then the state directory cannot take the new state file. + stateDir, err := installer.GlobalSkillsDir(t.Context()) + require.NoError(t, err) + require.NoError(t, os.Chmod(stateDir, 0o500)) + t.Cleanup(func() { _ = os.Chmod(stateDir, 0o700) }) + + stdout, stderr, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood") + require.Error(t, err) + assert.Empty(t, stdout.String()) + assert.Contains(t, stderr.String(), "Removed genie_one_mcp-logfood", "the results are printed before the error") + assert.NotContains(t, readJSONFile(t, claudePath)["mcpServers"], "genie_one_mcp-logfood") +} + +func TestMcpRemoveDropsRecordOfNamedEntry(t *testing.T) { + withHome(t) + claude := agents.ByName("claude-code") + dir := t.TempDir() + first := filepath.Join(dir, "first.cfg") + second := filepath.Join(dir, "second.cfg") + for _, path := range []string{first, second} { + require.NoError(t, os.WriteFile(path, []byte("[logfood]\nhost = https://adb-1.test\ntoken = t\n"), 0o600)) + } + + // Two servers of one service and profile, each pinned to its own config file. + kept := seedInstallEntry(t, claude, seed{"genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test", testDatabricksCommand, first}) + removed := seedInstallEntry(t, claude, seed{"genie_one_mcp-logfood-2", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test", testDatabricksCommand, second}) + saveState(t, kept, removed) + + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood-2", "--output", "json") + require.NoError(t, err) + assert.Len(t, readRemoveOutput(t, stdout.String()).Removed, 1) + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + require.Len(t, state.Servers, 1) + assert.Equal(t, "genie_one_mcp-logfood", state.Servers[0].Name) + assert.Contains(t, state.Servers[0].Agents, "claude-code", "the record of the other server is kept") +} + +func TestMcpRemoveLeavesEntriesWithoutRecord(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + // Written by this CLI, but the state that recorded it is gone. Remove does not know it, so it stays. + seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + + stdout, _, err := runMcpCmd(t, "remove", "--all", "--output", "json") + require.NoError(t, err) + out := readRemoveOutput(t, stdout.String()) assert.Empty(t, out.Removed) assert.Empty(t, out.Skipped) + assert.Contains(t, readJSONFile(t, claudePath)["mcpServers"], "genie_one_mcp-logfood") } -func keysOf(m map[string]mcp.AgentRecord) []string { - var keys []string - for k := range m { - keys = append(keys, k) - } - return keys +func TestMcpRemoveFailsWithoutSelection(t *testing.T) { + withHome(t) + stdout, _, err := runMcpCmd(t, "remove", "--output", "json") + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + + out := readRemoveOutput(t, stdout.String()) + assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, out.ErrorCategory) + assert.Equal(t, removeFlagsHint, out.Error) + assert.Empty(t, out.Removed) + assert.Empty(t, out.Skipped) } From ee97746448d3e12f80a6a3d5f61f210f8aed6d24 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 20:24:53 +0000 Subject: [PATCH 09/26] aitools mcp: name the server in serve drift hints, add per-entry checks The serve errors for a drifted entry told the user to run `mcp remove --profile`, which removes every server of the profile in every config file. They now name the server (`mcp remove --names`), as `mcp list` does. The drift wording of the serve errors moves to DriftMessage, which `mcp list` also uses, so the workspace named in a host's query is shown, not an empty ID. CheckEntries returns one result per entry, reading each config file once, and Reconcile is built on it. IsUGProxy is the single definition of the ug bridge. ReadAt and RemoveAt work on the file a record names, so that `mcp remove` can clean up an entry whose agent config moved. Co-authored-by: Isaac --- libs/aitools/mcp/agentconfig/unmanaged.go | 9 +++- .../aitools/mcp/agentconfig/unmanaged_test.go | 8 +++ libs/aitools/mcp/agentconfig/writer.go | 22 ++++++-- libs/aitools/mcp/agentconfig/writer_test.go | 52 +++++++++++++++++++ libs/aitools/mcp/binding.go | 30 +++++------ libs/aitools/mcp/binding_test.go | 16 +++--- libs/aitools/mcp/state.go | 47 +++++++++++------ libs/aitools/mcp/state_test.go | 46 ++++++++++++++-- 8 files changed, 181 insertions(+), 49 deletions(-) diff --git a/libs/aitools/mcp/agentconfig/unmanaged.go b/libs/aitools/mcp/agentconfig/unmanaged.go index a4aad7e6ffe..c0681f8d1b5 100644 --- a/libs/aitools/mcp/agentconfig/unmanaged.go +++ b/libs/aitools/mcp/agentconfig/unmanaged.go @@ -6,13 +6,18 @@ import ( "github.com/databricks/cli/libs/aitools/mcpconfig" ) +// IsUGProxy reports whether entry runs the `ug mcp-proxy` bridge: a ug binary whose first argument is mcp-proxy. +func IsUGProxy(entry map[string]any) bool { + argv, ok := mcpconfig.Argv(entry) + return ok && len(argv) > 1 && mcpconfig.IsBinary(argv[0], "ug", "ug.exe") && argv[1] == "mcp-proxy" +} + // IsUnmanaged reports whether entry connects to Databricks managed MCP servers // without having been written by this CLI: the `ug mcp-proxy` bridge, or a // direct /ai-gateway/mcp-services/ URL. Such entries are listed by `list`, and // Upsert replaces one only with force. func IsUnmanaged(entry map[string]any) bool { - if argv, ok := mcpconfig.Argv(entry); ok && len(argv) > 1 && - mcpconfig.IsBinary(argv[0], "ug", "ug.exe") && argv[1] == "mcp-proxy" { + if IsUGProxy(entry) { return true } // Remote entries name their URL differently per agent: url (Cursor, Claude diff --git a/libs/aitools/mcp/agentconfig/unmanaged_test.go b/libs/aitools/mcp/agentconfig/unmanaged_test.go index 3c4f2f4590c..f61bcfc37b6 100644 --- a/libs/aitools/mcp/agentconfig/unmanaged_test.go +++ b/libs/aitools/mcp/agentconfig/unmanaged_test.go @@ -58,3 +58,11 @@ func TestIsUnmanaged(t *testing.T) { }) } } + +// TestIsUGProxy checks that only a ug binary running mcp-proxy is the ug bridge: an mcp-proxy argument under another +// command is not. +func TestIsUGProxy(t *testing.T) { + assert.True(t, IsUGProxy(map[string]any{"command": "/usr/local/bin/ug", "args": []any{"mcp-proxy"}})) + assert.False(t, IsUGProxy(map[string]any{"command": "npx", "args": []any{"mcp-proxy"}})) + assert.False(t, IsUGProxy(map[string]any{"command": "npx", "args": []any{"mcp-proxy"}, "url": "https://adb-1.test/ai-gateway/mcp-services/x"})) +} diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index 0a9d52204b5..a8eec302940 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -156,11 +156,20 @@ func Remove(ctx context.Context, a *agents.Agent, name string) (bool, error) { if err := checkName(name); err != nil { return false, err } - spec, err := specOf(a) + path, err := Path(ctx, a) if err != nil { return false, err } - path, err := spec.Path(ctx) + return RemoveAt(a, path, name) +} + +// RemoveAt is Remove for the config file at path. The file need not be the one the spec names now: a record names +// the file an entry was written to, and the agent's config may have moved since. A missing file has no entry. +func RemoveAt(a *agents.Agent, path, name string) (bool, error) { + if err := checkName(name); err != nil { + return false, err + } + spec, err := specOf(a) if err != nil { return false, err } @@ -191,11 +200,16 @@ func Remove(ctx context.Context, a *agents.Agent, name string) (bool, error) { // Read returns every server entry in agent a's config, keyed by name. A missing // file has no entries. func Read(ctx context.Context, a *agents.Agent) (map[string]map[string]any, error) { - spec, err := specOf(a) + path, err := Path(ctx, a) if err != nil { return nil, err } - path, err := spec.Path(ctx) + return ReadAt(a, path) +} + +// ReadAt is Read for the config file at path, which need not be the one the spec names now. See RemoveAt. +func ReadAt(a *agents.Agent, path string) (map[string]map[string]any, error) { + spec, err := specOf(a) if err != nil { return nil, err } diff --git a/libs/aitools/mcp/agentconfig/writer_test.go b/libs/aitools/mcp/agentconfig/writer_test.go index 4819ff495f7..f3dc076d1df 100644 --- a/libs/aitools/mcp/agentconfig/writer_test.go +++ b/libs/aitools/mcp/agentconfig/writer_test.go @@ -784,3 +784,55 @@ func TestUpsertRefusesEnvThatIsNotATable(t *testing.T) { require.ErrorIs(t, err, ErrConfigInvalid) assert.Equal(t, data, string(readFile(t, path))) } + +// TestPathIsTheFileTheSpecNames checks that Path returns the file the spec names, without creating or reading it. +func TestPathIsTheFileTheSpecNames(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + a := testAgent(path, mcpconfig.FormatJSON, "mcpServers") + + got, err := Path(t.Context(), a) + require.NoError(t, err) + assert.Equal(t, path, got) + _, err = os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestPathFailsForAgentWithoutMCP(t *testing.T) { + _, err := Path(t.Context(), &agents.Agent{Name: "pi", DisplayName: "Pi"}) + require.Error(t, err) +} + +// TestReadAtAndRemoveAtUseTheGivenFile checks that ReadAt and RemoveAt work on the file they are given, not on the +// file the agent's spec names now. The entry is written to one file, and the spec names another. +func TestReadAtAndRemoveAtUseTheGivenFile(t *testing.T) { + recorded := filepath.Join(t.TempDir(), "recorded.json") + current := filepath.Join(t.TempDir(), "current.json") + _, _, err := Upsert(t.Context(), testAgent(recorded, mcpconfig.FormatJSON, "mcpServers"), testName, testCmd, testArgs("test"), nil, false) + require.NoError(t, err) + a := testAgent(current, mcpconfig.FormatJSON, "mcpServers") + + entries, err := ReadAt(a, recorded) + require.NoError(t, err) + assert.Contains(t, entries, testName) + + entries, err = Read(t.Context(), a) + require.NoError(t, err) + assert.Empty(t, entries, "the spec's file does not have the entry") + + removed, err := RemoveAt(a, recorded, testName) + require.NoError(t, err) + assert.True(t, removed) + entries, err = ReadAt(a, recorded) + require.NoError(t, err) + assert.Empty(t, entries) + _, err = os.Stat(current) + assert.ErrorIs(t, err, os.ErrNotExist, "RemoveAt does not write the spec's file") +} + +// TestReadAtMissingFileHasNoEntries checks that a file that no longer exists reads as having no entries. +func TestReadAtMissingFileHasNoEntries(t *testing.T) { + a := testAgent(filepath.Join(t.TempDir(), "current.json"), mcpconfig.FormatJSON, "mcpServers") + entries, err := ReadAt(a, filepath.Join(t.TempDir(), "gone.json")) + require.NoError(t, err) + assert.Empty(t, entries) +} diff --git a/libs/aitools/mcp/binding.go b/libs/aitools/mcp/binding.go index d18804c366a..8b628b9be9e 100644 --- a/libs/aitools/mcp/binding.go +++ b/libs/aitools/mcp/binding.go @@ -182,11 +182,6 @@ func uncategorizedError(err error) error { return &BindError{Category: BindUncategorized, message: err.Error(), cause: err} } -// removeCommand returns the command that removes the server bound to profileName. -func removeCommand(profileName string) string { - return mcpRemoveCommand + " --profile " + shellquote.BashArg(profileName) -} - // RemoveNamesCommand returns the command that removes the server named name. Server names are unique in the state. func RemoveNamesCommand(name string) string { return mcpRemoveCommand + " --names " + shellquote.BashArg(name) @@ -219,22 +214,25 @@ func profileGoneError(name, profileName, path string, entry *Entry, problem stri } recreate := RecreateCommand(entry.Host, profileName, pinnedPath) message := fmt.Sprintf("MCP server %s is bound to Databricks profile \"%s\", which %s in %s. Recreate it with: %s or remove the server with: %s", - name, profileName, problem, path, recreate, removeCommand(profileName)) + name, profileName, problem, path, recreate, RemoveNamesCommand(name)) return &BindError{Category: BindProfileNotFound, message: message} } -// driftError is the PROFILE_HOST_CHANGED error for an entry whose profile now names another host, -// or another workspace on the same host. -func driftError(name, profileName string, entry Entry, drift Drift) error { +// DriftMessage tells how the profile of entry, which is named profileName, now differs from what the entry recorded: its +// host, or its workspace when the host is the same. subject starts the sentence, for example "MCP server github-logfood" +// or "it". The serve errors and `mcp list` both word a drift with it. +func DriftMessage(subject string, entry Entry, profileName string, drift Drift) string { recordedHost, recordedWorkspaceID := recordedTarget(entry) - var message string if NormalizeHost(recordedHost) != NormalizeHost(drift.CurrentHost) { - message = fmt.Sprintf("MCP server %s was set up for %s, but profile \"%s\" now points at %s. Run: %s and add it again", - name, recordedHost, profileName, drift.CurrentHost, removeCommand(profileName)) - } else { - message = fmt.Sprintf("MCP server %s was set up for workspace %s, but profile \"%s\" now points at workspace %s. Run: %s and add it again", - name, recordedWorkspaceID, profileName, drift.CurrentWorkspaceID, removeCommand(profileName)) + return fmt.Sprintf("%s was set up for %s, but profile \"%s\" now points at %s", subject, recordedHost, profileName, drift.CurrentHost) } + return fmt.Sprintf("%s was set up for workspace %s, but profile \"%s\" now points at workspace %s", subject, recordedWorkspaceID, profileName, drift.CurrentWorkspaceID) +} + +// driftError is the PROFILE_HOST_CHANGED error for an entry whose profile now names another host, +// or another workspace on the same host. +func driftError(name, profileName string, entry Entry, drift Drift) error { + message := fmt.Sprintf("%s. Run: %s and add it again", DriftMessage("MCP server "+name, entry, profileName, drift), RemoveNamesCommand(name)) return &BindError{Category: BindProfileHostChanged, message: message} } @@ -242,7 +240,7 @@ func driftError(name, profileName string, entry Entry, drift Drift) error { // use. The profile may name the same host there, but the server was set up against the recorded file. func configFileError(name, profileName, recordedPath, currentPath string) error { message := fmt.Sprintf("MCP server %s was set up with config file %s, but profile \"%s\" is read from %s now. Run: %s and add it again, or set DATABRICKS_CONFIG_FILE to %s", - name, recordedPath, profileName, currentPath, removeCommand(profileName), shellquote.BashArg(recordedPath)) + name, recordedPath, profileName, currentPath, RemoveNamesCommand(name), shellquote.BashArg(recordedPath)) return &BindError{Category: BindProfileHostChanged, message: message} } diff --git a/libs/aitools/mcp/binding_test.go b/libs/aitools/mcp/binding_test.go index 1ab27abf006..b15625832db 100644 --- a/libs/aitools/mcp/binding_test.go +++ b/libs/aitools/mcp/binding_test.go @@ -127,7 +127,7 @@ func TestBindProfileAbsent(t *testing.T) { Host: bindingTestHost, ConfigFile: path, }}}, - want: fmt.Sprintf(`MCP server github-gone is bound to Databricks profile "gone", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile gone or remove the server with: databricks aitools mcp remove --profile gone`, filepath.ToSlash(path), filepath.ToSlash(path)), + want: fmt.Sprintf(`MCP server github-gone is bound to Databricks profile "gone", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile gone or remove the server with: databricks aitools mcp remove --names github-gone`, filepath.ToSlash(path), filepath.ToSlash(path)), }, { name: "without state entry", @@ -175,12 +175,12 @@ func TestBindHostChanged(t *testing.T) { { name: "host", entry: "https://adb-999.test", - want: "MCP server github-logfood was set up for https://adb-999.test, but profile \"logfood\" now points at https://adb-123.test. Run: databricks aitools mcp remove --profile logfood and add it again", + want: "MCP server github-logfood was set up for https://adb-999.test, but profile \"logfood\" now points at https://adb-123.test. Run: databricks aitools mcp remove --names github-logfood and add it again", }, { name: "host with a query naming another workspace on the same host", entry: "https://adb-999.test/?o=111", - want: "MCP server github-logfood was set up for https://adb-999.test, but profile \"logfood\" now points at https://adb-123.test. Run: databricks aitools mcp remove --profile logfood and add it again", + want: "MCP server github-logfood was set up for https://adb-999.test, but profile \"logfood\" now points at https://adb-123.test. Run: databricks aitools mcp remove --names github-logfood and add it again", }, } for _, tt := range tests { @@ -219,7 +219,7 @@ func TestBindHostChangedDoesNotContactNewHost(t *testing.T) { } func TestBindWorkspaceChanged(t *testing.T) { - const want = "MCP server github-logfood was set up for workspace 111, but profile \"logfood\" now points at workspace 222. Run: databricks aitools mcp remove --profile logfood and add it again" + const want = "MCP server github-logfood was set up for workspace 111, but profile \"logfood\" now points at workspace 222. Run: databricks aitools mcp remove --names github-logfood and add it again" tests := []struct { name string entryHost string @@ -423,7 +423,7 @@ func TestBindWorkspaceFromHostQueryChanged(t *testing.T) { Stderr: &bytes.Buffer{}, }) requireBindError(t, err, mcp.BindProfileHostChanged) - assert.Equal(t, "MCP server github-logfood was set up for workspace 111, but profile \"logfood\" now points at workspace 222. Run: databricks aitools mcp remove --profile logfood and add it again", err.Error()) + assert.Equal(t, "MCP server github-logfood was set up for workspace 111, but profile \"logfood\" now points at workspace 222. Run: databricks aitools mcp remove --names github-logfood and add it again", err.Error()) }) } } @@ -663,7 +663,7 @@ func TestBindProfileWithoutHost(t *testing.T) { }) requireBindError(t, err, mcp.BindProfileNotFound) resolved := filepath.ToSlash(bindingTestResolved(t, path)) - assert.Equal(t, fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "logfood", which has no host in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile logfood or remove the server with: databricks aitools mcp remove --profile logfood`, resolved, resolved), err.Error()) + assert.Equal(t, fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "logfood", which has no host in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile logfood or remove the server with: databricks aitools mcp remove --names github-logfood`, resolved, resolved), err.Error()) } // TestBindHostMetadataFailureIsNotAuthFailure checks that a host whose metadata cannot be fetched does @@ -776,7 +776,7 @@ func TestBindRecreateHintQuotesValues(t *testing.T) { Stderr: &bytes.Buffer{}, }) requireBindError(t, err, mcp.BindProfileNotFound) - want := fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "my profile", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile 'my profile' or remove the server with: databricks aitools mcp remove --profile 'my profile'`, + want := fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "my profile", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile 'my profile' or remove the server with: databricks aitools mcp remove --names github-logfood`, filepath.ToSlash(bindingTestResolved(t, cfgPath)), filepath.ToSlash(bindingTestResolved(t, cfgPath))) assert.Equal(t, want, err.Error()) } @@ -801,7 +801,7 @@ func TestCheckBindingMatchesBind(t *testing.T) { _, err := bindingTestCheck(t, state) requireBindError(t, err, mcp.BindProfileHostChanged) - assert.Equal(t, "MCP server github-logfood was set up for https://adb-123.test, but profile \"logfood\" now points at "+server.URL+". Run: databricks aitools mcp remove --profile logfood and add it again", err.Error()) + assert.Equal(t, "MCP server github-logfood was set up for https://adb-123.test, but profile \"logfood\" now points at "+server.URL+". Run: databricks aitools mcp remove --names github-logfood and add it again", err.Error()) } func TestCheckBindingPassesWhenEntryMatchesOrIsAbsent(t *testing.T) { diff --git a/libs/aitools/mcp/state.go b/libs/aitools/mcp/state.go index c373f0a7dc0..e25b658e3e9 100644 --- a/libs/aitools/mcp/state.go +++ b/libs/aitools/mcp/state.go @@ -80,27 +80,42 @@ func SaveState(ctx context.Context, state *State) error { return installer.SaveMCPState(dir, state) } +// EntryCheck is the result of checking one state entry. Drift is nil when the entry's profile still names the recorded +// host and workspace. Err is set when the entry cannot be checked. +type EntryCheck struct { + Drift *Drift + Err error +} + +// CheckEntries checks each entry of state against its profile and returns one result per entry, in state order. Each +// entry is checked against the config file it is pinned to; an entry with no pinned file is checked against the default +// file, ~/.databrickscfg, whatever the environment names. Each config file is read once for all the entries. An entry +// that cannot be checked, such as one whose "~" path has no home directory to resolve, does not stop the others. +func CheckEntries(ctx context.Context, state *State) []EntryCheck { + files := configFiles{} + checks := make([]EntryCheck, len(state.Servers)) + for i, entry := range state.Servers { + drift, err := checkEntry(ctx, files, entry) + checks[i] = EntryCheck{Drift: drift, Err: err} + } + return checks +} + // Reconcile reports entries whose profile is gone or has no host, and entries whose profile now -// names another host, or another workspace when both the entry and the profile name one. Each -// entry is checked against the config file it is pinned to; an entry with no pinned file is checked -// against the default file, ~/.databrickscfg, whatever the environment names. Each config file is -// read once. +// names another host, or another workspace when both the entry and the profile name one. See +// CheckEntries for how each entry is checked. // -// An entry that cannot be checked, such as one whose "~" path has no home directory to resolve, does -// not stop the others. Its error is joined into the returned error, and the drifts of the other -// entries are still returned. +// An entry that cannot be checked does not stop the others. Its error is joined into the returned +// error, and the drifts of the other entries are still returned. func Reconcile(ctx context.Context, state *State) ([]Drift, error) { - files := configFiles{} var drifts []Drift var errs []error - for _, entry := range state.Servers { - drift, err := checkEntry(ctx, files, entry) - if err != nil { - errs = append(errs, fmt.Errorf("MCP server %s: %w", entry.Name, err)) - continue - } - if drift != nil { - drifts = append(drifts, *drift) + for i, check := range CheckEntries(ctx, state) { + switch { + case check.Err != nil: + errs = append(errs, fmt.Errorf("MCP server %s: %w", state.Servers[i].Name, check.Err)) + case check.Drift != nil: + drifts = append(drifts, *check.Drift) } } return drifts, errors.Join(errs...) diff --git a/libs/aitools/mcp/state_test.go b/libs/aitools/mcp/state_test.go index 06cca4350d7..ee108f559fe 100644 --- a/libs/aitools/mcp/state_test.go +++ b/libs/aitools/mcp/state_test.go @@ -309,20 +309,35 @@ func TestNormalizeHostIgnoresSchemeCaseAndTrailingSlash(t *testing.T) { func TestReconcileProfileWithEmptyHostIsMissing(t *testing.T) { ctx, _ := stateTestCtx(t) path := bindingTestWriteConfig(t, "[logfood]\nhost =\nauth_type = pat\ntoken = dapi-profile-token\n") - ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", path) + // The entry is pinned to the file that has the section, so the check reads that file. entry := stateTestEntry() + entry.ConfigFile = path state := &mcp.State{Servers: []mcp.Entry{entry}} drifts, err := mcp.Reconcile(ctx, state) require.NoError(t, err) - assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry}}, drifts) + assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry, NoHost: true}}, drifts) } func TestReconcileProfileWithoutHostIsMissing(t *testing.T) { ctx, _ := stateTestCtx(t) path := bindingTestWriteConfig(t, "[logfood]\nauth_type = pat\ntoken = dapi-profile-token\n") - ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", path) entry := stateTestEntry() + entry.ConfigFile = path + state := &mcp.State{Servers: []mcp.Entry{entry}} + + drifts, err := mcp.Reconcile(ctx, state) + require.NoError(t, err) + assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry, NoHost: true}}, drifts) +} + +// TestReconcileAbsentSectionIsMissingWithoutNoHost checks that a file with no section of the profile's name is +// reported as missing, not as a section with no host. +func TestReconcileAbsentSectionIsMissingWithoutNoHost(t *testing.T) { + ctx, _ := stateTestCtx(t) + path := bindingTestWriteConfig(t, "[other]\nhost = https://adb-456.test\ntoken = dapi-profile-token\n") + entry := stateTestEntry() + entry.ConfigFile = path state := &mcp.State{Servers: []mcp.Entry{entry}} drifts, err := mcp.Reconcile(ctx, state) @@ -352,3 +367,28 @@ func TestReconcileReportsEntryErrorAndKeepsOthers(t *testing.T) { CurrentWorkspaceID: stateTestWorkspaceID, }}, drifts) } + +// TestCheckEntriesKeepsEachResultOnItsEntry checks that CheckEntries returns one result per entry, in state order, +// and that an entry that cannot be checked does not take the result of another entry with it. +func TestCheckEntriesKeepsEachResultOnItsEntry(t *testing.T) { + ctx, _ := stateTestCtx(t) + ctx = env.WithUserHomeDir(ctx, "") + unresolvable := stateTestEntry() + unresolvable.Name = "github-home" + unresolvable.ConfigFile = "~/.databrickscfg" + healthy := stateTestEntry() + healthy.ConfigFile = bindingTestWriteConfig(t, fmt.Sprintf("[%s]\nhost = %s\nworkspace_id = %s\nauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestHost, stateTestWorkspaceID, bindingTestToken)) + changed := stateTestEntryWith(bindingTestProfile, "https://adb-999.test", stateTestWorkspaceID) + changed.ConfigFile = healthy.ConfigFile + state := &mcp.State{Servers: []mcp.Entry{unresolvable, healthy, changed}} + + checks := mcp.CheckEntries(ctx, state) + require.Len(t, checks, 3) + require.ErrorIs(t, checks[0].Err, env.ErrNoHomeEnv) + assert.Nil(t, checks[0].Drift) + assert.NoError(t, checks[1].Err) + assert.Nil(t, checks[1].Drift) + assert.NoError(t, checks[2].Err) + require.NotNil(t, checks[2].Drift) + assert.Equal(t, mcp.DriftHostChanged, checks[2].Drift.Kind) +} From 475bc2884bb61dac12592e60275de1eba12bf6a3 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 20:30:37 +0000 Subject: [PATCH 10/26] aitools mcp list and remove: fix review findings (pass 2) list: - --profile lists that profile only; the unmanaged section is skipped, since those entries have no profile, and an empty profile says so. - Drift hints are built from mcp.DriftMessage, with the workspace from the host query and the profile quoted; the pinned file is shown with slashes. - A profile with a server that cannot be checked is unknown, not ok. - An entry whose config file cannot be resolved is warned once, not once per agent. Each entry is checked through mcp.CheckEntries. - JSON carries error and error_category when the state cannot be read. - An entry that runs an mcp-proxy argument under another command is not labeled ug-proxy: agentconfig.IsUGProxy decides. remove: - --names accepts the leaf of a service name, case-insensitively. A leaf that names services in two schemas is refused with the full names. - A record for an agent this CLI cannot edit (outside the registry, or without MCP support) is dropped and listed with record_only, not a failure. - A moved agent config is cleaned in the file the record names; a record whose file is gone is pruned. The record goes with the entry. - Only the selected entries left without an agent are dropped from state. A named entry with no agent is removed. - The save of the state is a variable, so the save failure test does not depend on file permissions. The quiet context in JSON mode is removed. acceptance: the expected failures use musterr; the broken Codex config is a fixture; list --profile is shown; goldens regenerated and reviewed. Co-authored-by: Isaac --- .../mcp/drift-profile-missing/output.txt | 2 +- .../aitools/mcp/list-and-remove/output.txt | 7 + .../cmd/aitools/mcp/list-and-remove/script | 3 + .../broken-codex-config.toml | 1 + .../mcp/repair-and-warnings/output.txt | 25 +-- .../aitools/mcp/repair-and-warnings/script | 10 +- cmd/aitools/mcp_list.go | 118 ++++++---- cmd/aitools/mcp_list_test.go | 119 ++++++++-- cmd/aitools/mcp_remove.go | 207 ++++++++++++------ cmd/aitools/mcp_remove_test.go | 161 ++++++++++++-- 10 files changed, 479 insertions(+), 174 deletions(-) create mode 100644 acceptance/cmd/aitools/mcp/repair-and-warnings/broken-codex-config.toml diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt b/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt index 17d9ed9231b..0c4cbc28695 100644 --- a/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt @@ -82,7 +82,7 @@ Profile logfood (profile not found in [TEST_TMP_DIR]/.databrickscfg) >>> [CLI] aitools mcp list Profile dogfood (https://adb-2.test) genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code - broken: it was set up for [DATABRICKS_URL], but profile dogfood now points at https://adb-2.test; run `databricks aitools mcp remove --names genie_one_mcp-dogfood` and add it again + broken: it was set up for [DATABRICKS_URL], but profile "dogfood" now points at https://adb-2.test; run `databricks aitools mcp remove --names genie_one_mcp-dogfood` and add it again Profile logfood (profile not found in [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt index 57aa6685e07..01167751da7 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt +++ b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt @@ -114,6 +114,13 @@ Profile logfood ([DATABRICKS_URL]) Unmanaged Databricks MCP entries (not changed by this command): Claude Code web_search ug mcp-proxy +=== --profile lists that profile only, without the unmanaged entries + +>>> [CLI] aitools mcp list --profile logfood +Profile logfood ([DATABRICKS_URL]) + genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code + github-logfood system.ai.github Claude Code (modified) + === remove leaves the modified entry in place and says why >>> [CLI] aitools mcp remove --names github-logfood,genie_one_mcp-logfood diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/script b/acceptance/cmd/aitools/mcp/list-and-remove/script index 6a087c07452..2b6481b7e36 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/script +++ b/acceptance/cmd/aitools/mcp/list-and-remove/script @@ -28,6 +28,9 @@ title "A hand-edited entry is listed as modified; an unmanaged ug entry is liste jq '.mcpServers["github-logfood"].command = "/usr/bin/other" | .mcpServers.web_search = {"command": "ug", "args": ["mcp-proxy"]}' home/.claude.json > home/claude.tmp && mv home/claude.tmp home/.claude.json trace $CLI aitools mcp list +title "--profile lists that profile only, without the unmanaged entries" +trace $CLI aitools mcp list --profile logfood + title "remove leaves the modified entry in place and says why" trace $CLI aitools mcp remove --names github-logfood,genie_one_mcp-logfood trace jq '.mcpServers | keys' home/.claude.json diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/broken-codex-config.toml b/acceptance/cmd/aitools/mcp/repair-and-warnings/broken-codex-config.toml new file mode 100644 index 00000000000..1d88ef25b79 --- /dev/null +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/broken-codex-config.toml @@ -0,0 +1 @@ +[mcp_servers.broken diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt index 9ec7dbadd8e..78d015dc511 100644 --- a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt @@ -9,25 +9,23 @@ genie_one_mcp-logfood system.ai.genie_one_mcp claude-code installed [TEST_TMP_DIR]/home/.claude.json codex installed [TEST_TMP_DIR]/home/.codex/config.toml -=== Claude Code reads its config from another directory: list says path changed, and remove keeps the entry +=== Claude Code reads its config from another directory: list says path changed, and remove takes the entry out of the file it was written to >>> [CLI] aitools mcp list Profile logfood ([DATABRICKS_URL]) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code (path changed), Codex CLI >>> [CLI] aitools mcp remove --names genie_one_mcp-logfood --agents claude-code -Skipped genie_one_mcp-logfood: Claude Code reads its config from [TEST_TMP_DIR]/home/moved-claude/.claude.json now, but genie_one_mcp-logfood was written to [TEST_TMP_DIR]/home/.claude.json; left in place, and its record kept +Removed genie_one_mcp-logfood system.ai.genie_one_mcp profile logfood (Claude Code) >>> jq .mcpServers | keys home/.claude.json -[ - "genie_one_mcp-logfood" -] +[] === A Codex config that cannot be parsed is a warning: list exits 0 and shows Claude Code >>> [CLI] aitools mcp list Profile logfood ([DATABRICKS_URL]) - genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code, Codex CLI (unknown) + genie_one_mcp-logfood system.ai.genie_one_mcp Codex CLI (unknown) Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 2: expected '.' or ']' to end table name, but got '\n' instead === An entry that runs aitools mcp serve without an install record is unmanaged, and remove does not touch it @@ -36,31 +34,24 @@ Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config. >>> [CLI] aitools mcp list Profile logfood ([DATABRICKS_URL]) - genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code, Codex CLI (unknown) + genie_one_mcp-logfood system.ai.genie_one_mcp Codex CLI (unknown) Unmanaged Databricks MCP entries (not changed by this command): Claude Code orphan databricks aitools mcp serve, no install record Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 2: expected '.' or ']' to end table name, but got '\n' instead ->>> [CLI] aitools mcp remove --names orphan +>>> musterr [CLI] aitools mcp remove --names orphan Error: no installed MCP server named orphan -Exit code: 1 - >>> jq .mcpServers | keys home/.claude.json [ - "genie_one_mcp-logfood", "orphan" ] === A profile or an agent with nothing installed is refused ->>> [CLI] aitools mcp remove --profile typo +>>> musterr [CLI] aitools mcp remove --profile typo Error: no installed MCP servers on profile typo -Exit code: 1 - ->>> [CLI] aitools mcp remove --names genie_one_mcp-logfood --agents cursor +>>> musterr [CLI] aitools mcp remove --names genie_one_mcp-logfood --agents cursor Error: no selected MCP server is installed for Cursor - -Exit code: 1 diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/script b/acceptance/cmd/aitools/mcp/repair-and-warnings/script index 216c71fa871..b84f5045248 100644 --- a/acceptance/cmd/aitools/mcp/repair-and-warnings/script +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/script @@ -9,7 +9,7 @@ MSYS_NO_PATHCONV=1 $CLI api post "/api/2.1/unity-catalog/mcp-services?parent=sch title "Claude Code and Codex get the server" trace $CLI aitools mcp add --profile logfood --names system.ai.genie_one_mcp --agents claude-code,codex -title "Claude Code reads its config from another directory: list says path changed, and remove keeps the entry" +title "Claude Code reads its config from another directory: list says path changed, and remove takes the entry out of the file it was written to" export CLAUDE_CONFIG_DIR=$PWD/home/moved-claude trace $CLI aitools mcp list trace $CLI aitools mcp remove --names genie_one_mcp-logfood --agents claude-code @@ -17,15 +17,15 @@ unset CLAUDE_CONFIG_DIR trace jq '.mcpServers | keys' home/.claude.json title "A Codex config that cannot be parsed is a warning: list exits 0 and shows Claude Code" -echo "[mcp_servers.broken" > home/.codex/config.toml +cp broken-codex-config.toml home/.codex/config.toml trace $CLI aitools mcp list title "An entry that runs aitools mcp serve without an install record is unmanaged, and remove does not touch it" trace jq '.mcpServers.orphan = {"command": "databricks", "args": ["aitools", "mcp", "serve", "--profile", "logfood", "--service", "system.ai.genie_one_mcp", "--agent", "claude-code"]}' home/.claude.json > home/claude.tmp && mv home/claude.tmp home/.claude.json trace $CLI aitools mcp list -errcode trace $CLI aitools mcp remove --names orphan +trace musterr $CLI aitools mcp remove --names orphan trace jq '.mcpServers | keys' home/.claude.json title "A profile or an agent with nothing installed is refused" -errcode trace $CLI aitools mcp remove --profile typo -errcode trace $CLI aitools mcp remove --names genie_one_mcp-logfood --agents cursor +trace musterr $CLI aitools mcp remove --profile typo +trace musterr $CLI aitools mcp remove --names genie_one_mcp-logfood --agents cursor diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index 3aaf2c6ecde..087fbd92cbb 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -3,17 +3,20 @@ package aitools import ( "cmp" "context" + "errors" "fmt" "maps" "path/filepath" "slices" "strings" + "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/aitools/mcp/agentconfig" "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/telemetry/protos" "github.com/spf13/cobra" ) @@ -41,6 +44,9 @@ type mcpListOutput struct { Unmanaged []mcpListUnmanaged `json:"unmanaged"` // Warnings name the entries and agent configs that could not be checked. The rest is still listed. Warnings []string `json:"warnings"` + // Error and ErrorCategory are set when the state cannot be read. The listing is then empty. + Error string `json:"error,omitempty"` + ErrorCategory protos.AitoolsErrorCategory `json:"error_category,omitempty"` } // mcpListProfile groups the servers that bind to one profile in one config file. @@ -99,25 +105,42 @@ coding agents each one is in. Entries that drifted from their profile or from th reported. Entries in agent configs that this CLI did not write are listed as unmanaged and never changed. Entries that run 'aitools mcp serve' but have no install record are listed as unmanaged too. +--profile lists the servers of that profile only. Unmanaged entries have no profile, so they are not +listed then. + This command makes no network calls. It always exits 0 when entries have drifted or cannot be checked; an entry or agent config that cannot be checked is a warning.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() - out, err := buildMcpList(ctx) + profileName := profileFlag(cmd) + out, err := buildMcpList(ctx, profileName) + if !installOutputIsJSON(cmd) { + if err != nil { + return err + } + renderMcpList(ctx, out, profileName) + return nil + } + // The document carries the failure, as add and remove write theirs. if err != nil { - return err + out.Error = err.Error() + out.ErrorCategory = errorCategory(err) + } + if renderErr := renderJSON(cmd.OutOrStdout(), out); renderErr != nil { + return errors.Join(err, renderErr) } - if installOutputIsJSON(cmd) { - return renderJSON(cmd.OutOrStdout(), out) + if err != nil { + return root.ErrAlreadyPrinted } - renderMcpList(ctx, out) return nil }, } } -func buildMcpList(ctx context.Context) (mcpListOutput, error) { +// buildMcpList reads the state and the agent configs and returns the listing. profileName, when set, lists the +// servers of that profile only. +func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error) { out := mcpListOutput{Profiles: []mcpListProfile{}, Unmanaged: []mcpListUnmanaged{}, Warnings: []string{}} state, err := mcp.LoadState(ctx) @@ -141,8 +164,15 @@ func buildMcpList(ctx context.Context) (mcpListOutput, error) { } } - groups := map[profileKey]*mcpListProfile{} + var entries []mcp.Entry for _, e := range state.Servers { + if profileName == "" || e.Profile == profileName { + entries = append(entries, e) + } + } + checks := mcp.CheckEntries(ctx, &mcp.State{Servers: entries}) + groups := map[profileKey]*mcpListProfile{} + for i, e := range entries { path, err := mcp.ResolveConfigFile(ctx, e.ConfigFile) if err != nil { // The entry cannot be checked, so it is grouped under its file as written. @@ -158,18 +188,19 @@ func buildMcpList(ctx context.Context) (mcpListOutput, error) { p.ConfigFile = filepath.ToSlash(path) } s := mcpListServer{Name: e.Name, Service: e.Service, SignInRequired: e.SignInRequired, Status: statusOK, Agents: []mcpListAgent{}, entry: e} - drift, err := checkServer(ctx, e) + check := checks[i] switch { - case err != nil: + case check.Err != nil: s.Status = statusUnknown - out.Warnings = append(out.Warnings, err.Error()) - case drift != nil: - s.Status = string(drift.Kind) - s.drift = drift + p.Status = worseStatus(p.Status, statusUnknown) + out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: %s", e.Name, check.Err)) + case check.Drift != nil: + s.Status = string(check.Drift.Kind) + s.drift = check.Drift p.Status = worseStatus(p.Status, s.Status) - p.noHost = p.noHost || drift.NoHost - if drift.Kind == mcp.DriftHostChanged { - p.Host = drift.CurrentHost + p.noHost = p.noHost || check.Drift.NoHost + if check.Drift.Kind == mcp.DriftHostChanged { + p.Host = check.Drift.CurrentHost } } for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { @@ -178,7 +209,8 @@ func buildMcpList(ctx context.Context) (mcpListOutput, error) { if cfg := configs[agentName]; cfg.err == nil { var err error status, err = agentStatus(ctx, e, agentName, cfg) - if err != nil { + // When the entry itself could not be checked, its warning already names the cause. + if err != nil && check.Err == nil { out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: could not check %s: %s", e.Name, agentDisplayName(agentName), err)) } } @@ -199,6 +231,10 @@ func buildMcpList(ctx context.Context) (mcpListOutput, error) { out.Profiles = append(out.Profiles, *groups[key]) } + // Unmanaged entries have no profile, so a --profile listing has none. + if profileName != "" { + return out, nil + } for _, name := range mcpAgentNames() { cfg := configs[name] if cfg.err != nil { @@ -215,19 +251,10 @@ func buildMcpList(ctx context.Context) (mcpListOutput, error) { return out, nil } -// checkServer returns the drift of one state entry from its profile, or nil when the profile still names the -// recorded host and workspace. err is set when the entry cannot be checked. -func checkServer(ctx context.Context, e mcp.Entry) (*mcp.Drift, error) { - drifts, err := mcp.Reconcile(ctx, &mcp.State{Servers: []mcp.Entry{e}}) - if err != nil || len(drifts) == 0 { - return nil, err - } - return &drifts[0], nil -} - -// worseStatus returns the more serious of two server statuses, for the status of a profile. +// worseStatus returns the more serious of two server statuses, for the status of a profile. A server that could not be +// checked makes its profile unknown, which is worse than ok and less serious than a drift. func worseStatus(a, b string) string { - rank := map[string]int{statusOK: 0, string(mcp.DriftHostChanged): 1, string(mcp.DriftProfileMissing): 2} + rank := map[string]int{statusOK: 0, statusUnknown: 1, string(mcp.DriftHostChanged): 2, string(mcp.DriftProfileMissing): 3} if rank[b] > rank[a] { return b } @@ -237,7 +264,6 @@ func worseStatus(a, b string) string { // agentConfig is one agent's MCP config, read once for a command. err is set when the config cannot be located or // parsed; entries is nil then. type agentConfig struct { - agent *agents.Agent path string entries map[string]map[string]any err error @@ -260,13 +286,13 @@ func readAgentConfig(ctx context.Context, name string) agentConfig { } path, err := agentconfig.Path(ctx, a) if err != nil { - return agentConfig{agent: a, err: err} + return agentConfig{err: err} } - entries, err := agentconfig.Read(ctx, a) + entries, err := agentconfig.ReadAt(a, path) if err != nil { - return agentConfig{agent: a, path: path, err: err} + return agentConfig{path: path, err: err} } - return agentConfig{agent: a, path: path, entries: entries} + return agentConfig{path: path, entries: entries} } // agentStatus compares the server's entry for one agent with that agent's config, which must have been read. An @@ -308,13 +334,12 @@ func unmanagedKind(entry map[string]any) string { switch { case mcpconfig.IsDatabricksEntry(entry): return unmanagedKindNoRecord - case !agentconfig.IsUnmanaged(entry): - return "" - } - if argv, ok := mcpconfig.Argv(entry); ok && len(argv) > 1 && argv[1] == "mcp-proxy" { + case agentconfig.IsUGProxy(entry): return unmanagedKindUGProxy + case agentconfig.IsUnmanaged(entry): + return unmanagedKindAIGateway } - return unmanagedKindAIGateway + return "" } // recordedFor reports whether state has a server with this name installed for the agent. @@ -334,8 +359,12 @@ func mcpAgentList(names []string) string { return strings.Join(display, ", ") } -func renderMcpList(ctx context.Context, out mcpListOutput) { +func renderMcpList(ctx context.Context, out mcpListOutput, profileName string) { if len(out.Profiles) == 0 && len(out.Unmanaged) == 0 { + if profileName != "" { + cmdio.LogString(ctx, fmt.Sprintf("No Databricks MCP servers installed by this CLI on profile %s.", profileName)) + return + } cmdio.LogString(ctx, "No Databricks MCP servers installed by this CLI.") } for i, p := range out.Profiles { @@ -388,16 +417,11 @@ func serverHint(p mcpListProfile, s mcpListServer) string { if s.drift.Kind == mcp.DriftProfileMissing { pinned := "" if s.entry.ConfigFile != "" { - pinned = p.configPath + pinned = filepath.ToSlash(p.configPath) } return fmt.Sprintf("broken: run `%s` or `%s`", remove, mcp.RecreateCommand(s.entry.Host, p.Profile, pinned)) } - if mcp.NormalizeHost(s.entry.Host) != mcp.NormalizeHost(s.drift.CurrentHost) { - return fmt.Sprintf("broken: it was set up for %s, but profile %s now points at %s; run `%s` and add it again", - s.entry.Host, p.Profile, s.drift.CurrentHost, remove) - } - return fmt.Sprintf("broken: it was set up for workspace %s, but profile %s now points at workspace %s; run `%s` and add it again", - s.entry.WorkspaceID, p.Profile, s.drift.CurrentWorkspaceID, remove) + return fmt.Sprintf("broken: %s; run `%s` and add it again", mcp.DriftMessage("it", s.entry, p.Profile, *s.drift), remove) } func listAgentsText(agentList []mcpListAgent) string { diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index e2813a5e9f3..5b86709573d 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -5,14 +5,18 @@ import ( "encoding/json" "os" "path/filepath" + "strings" "testing" + "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/aitools/mcp/agentconfig" "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/flags" + "github.com/databricks/cli/libs/telemetry/protos" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -131,7 +135,7 @@ func TestMcpHandEditedEntryIsModified(t *testing.T) { saveState(t, entry) editEntry(t, claudePath, entry.Name, func(server map[string]any) { tc.edit(t, server) }) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.Len(t, out.Profiles, 1) require.Len(t, out.Profiles[0].Servers, 1) @@ -166,7 +170,7 @@ func TestMcpReAddFromAnotherBinaryKeepsOtherAgentsRemovable(t *testing.T) { first.Command = "/opt/other/databricks" saveState(t, first) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.Len(t, out.Profiles, 1) for _, a := range out.Profiles[0].Servers[0].Agents { @@ -199,7 +203,7 @@ func TestBuildMcpListGroupsProfilesByConfigFile(t *testing.T) { healthy := seedInstallEntry(t, claude, seed{"genie_one_mcp-other", "system.ai.genie_one_mcp", "logfood", "https://adb-2.test", testDatabricksCommand, second}) saveState(t, drifted, current, healthy) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.Len(t, out.Profiles, 2, "one profile name in two config files is two groups") @@ -234,7 +238,7 @@ func TestBuildMcpListReportsAgentPathChanged(t *testing.T) { // The agent config now lives elsewhere, so the entry is in a file this command does not read. t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir()) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.Len(t, out.Profiles, 1) require.Len(t, out.Profiles[0].Servers, 1) @@ -251,7 +255,7 @@ func TestBuildMcpListRecordForUnknownAgentIsUnknown(t *testing.T) { Command: testDatabricksCommand, Agents: map[string]mcp.AgentRecord{"retired-agent": {Path: "/x/config.json", Scope: "user"}}, }) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.Len(t, out.Profiles, 1) require.Len(t, out.Profiles[0].Servers, 1) @@ -274,7 +278,7 @@ func TestBuildMcpListUnknownServerIsWarnedNotOK(t *testing.T) { } saveState(t, gone, unreadable) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.NotEmpty(t, out.Warnings) assert.Contains(t, out.Warnings[0], "MCP server github-logfood") @@ -282,7 +286,7 @@ func TestBuildMcpListUnknownServerIsWarnedNotOK(t *testing.T) { require.Len(t, out.Profiles, 2) logfood := out.Profiles[0] assert.Equal(t, "logfood", logfood.Profile) - assert.Equal(t, statusOK, logfood.Status) + assert.Equal(t, statusUnknown, logfood.Status, "a profile with an entry that could not be checked is not ok") require.Len(t, logfood.Servers, 1) assert.Equal(t, statusUnknown, logfood.Servers[0].Status, "an entry that could not be checked is not reported as ok") assert.Equal(t, "old", out.Profiles[1].Profile) @@ -328,7 +332,7 @@ func TestBuildMcpListWarnsForUnreadableAgentConfig(t *testing.T) { } saveState(t, genie, github) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err, "one unreadable agent does not fail the listing") require.Len(t, out.Warnings, 1) assert.Contains(t, out.Warnings[0], "Codex CLI") @@ -350,7 +354,7 @@ func TestBuildMcpListReportsOrphanDatabricksEntry(t *testing.T) { // Written by this CLI, but its state record is gone. seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) assert.Empty(t, out.Profiles) assert.Equal(t, []mcpListUnmanaged{{Agent: "claude-code", Name: "genie_one_mcp-logfood", Kind: unmanagedKindNoRecord}}, out.Unmanaged) @@ -386,7 +390,7 @@ token = t saveState(t, genie, github, dogfood, absent, gone) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.Len(t, out.Profiles, 3) @@ -428,7 +432,7 @@ func TestBuildMcpListEmpty(t *testing.T) { withHome(t) writeDatabricksCfg(t, "") - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) assert.NotNil(t, out.Profiles, "an empty listing is [] in JSON, not null") assert.NotNil(t, out.Unmanaged) @@ -447,6 +451,7 @@ func TestUnmanagedKind(t *testing.T) { {"ug mcp-proxy as a command array", map[string]any{"command": []any{"ug", "mcp-proxy"}}, unmanagedKindUGProxy}, {"ai gateway URL", map[string]any{"url": "https://adb-1.test/ai-gateway/mcp-services/github"}, unmanagedKindAIGateway}, {"other command", map[string]any{"command": "npx", "args": []any{"some-server"}}, ""}, + {"mcp-proxy under another command with an ai gateway URL", map[string]any{"command": "npx", "args": []any{"mcp-proxy"}, "url": "https://adb-1.test/ai-gateway/mcp-services/github"}, unmanagedKindAIGateway}, {"databricks serve without a record", map[string]any{"command": testDatabricksCommand, "args": []any{"aitools", "mcp", "serve"}}, unmanagedKindNoRecord}, } for _, tc := range cases { @@ -469,25 +474,29 @@ func TestRenderMcpListNamesTheFileAndTheRepair(t *testing.T) { workspaceMoved := seedInstallEntry(t, claude, seed{"genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test", testDatabricksCommand, pinned}) workspaceMoved.WorkspaceID = "111" + // The workspace is named in the host's query, not in workspace_id. + workspaceFromQuery := seedInstallEntry(t, claude, seed{"genie_one_mcp-query", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test/?o=111", testDatabricksCommand, pinned}) + hostMoved := seedInstallEntry(t, claude, seed{"github-moved", "system.ai.github", "logfood", "https://adb-old.test", testDatabricksCommand, pinned}) // The profile is not in the file at all, and the profile name needs quoting in the hint. missing := seedInstallEntry(t, claude, seed{"github-gone", "system.ai.github", "gone profile", "https://adb-old.test", testDatabricksCommand, pinned}) noHost := seedInstallEntry(t, claude, seed{"dbsql-nohost", "system.ai.dbsql", "nohost", "https://adb-4.test", testDatabricksCommand, pinned}) - saveState(t, workspaceMoved, missing, noHost) + saveState(t, workspaceMoved, workspaceFromQuery, hostMoved, missing, noHost) - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) - renderMcpList(ctx, out) + renderMcpList(ctx, out, "") text := stderr.String() shownPath := filepath.ToSlash(pinnedPath) assert.Contains(t, text, "Profile logfood (https://adb-1.test)") - assert.Contains(t, text, "broken: it was set up for workspace 111, but profile logfood now points at workspace 222; run `databricks aitools mcp remove --names genie_one_mcp-logfood` and add it again") + assert.Contains(t, text, "broken: it was set up for workspace 111, but profile \"logfood\" now points at workspace 222; run `databricks aitools mcp remove --names genie_one_mcp-logfood` and add it again") + assert.Contains(t, text, "broken: it was set up for workspace 111, but profile \"logfood\" now points at workspace 222; run `databricks aitools mcp remove --names genie_one_mcp-query` and add it again") + assert.Contains(t, text, "broken: it was set up for https://adb-old.test, but profile \"logfood\" now points at https://adb-1.test; run `databricks aitools mcp remove --names github-moved` and add it again") assert.Contains(t, text, "Profile gone profile (profile not found in "+shownPath+")") - assert.Contains(t, text, "broken: run `databricks aitools mcp remove --names github-gone` or `DATABRICKS_CONFIG_FILE="+pinnedPath+" databricks auth login --host https://adb-old.test --profile 'gone profile'`") + assert.Contains(t, text, "broken: run `databricks aitools mcp remove --names github-gone` or `DATABRICKS_CONFIG_FILE="+shownPath+" databricks auth login --host https://adb-old.test --profile 'gone profile'`") assert.Contains(t, text, "Profile nohost (profile has no host in "+shownPath+")") - assert.NotContains(t, text, "host changed") assert.NotContains(t, text, "Warning", "every entry in this test can be checked") } @@ -497,9 +506,81 @@ func TestRenderMcpListWarnsAndNamesUnmanagedRecords(t *testing.T) { claude := agents.ByName("claude-code") seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") - out, err := buildMcpList(t.Context()) + out, err := buildMcpList(t.Context(), "") require.NoError(t, err) ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) - renderMcpList(ctx, out) + renderMcpList(ctx, out, "") assert.Contains(t, stderr.String(), " Claude Code genie_one_mcp-logfood databricks aitools mcp serve, no install record") } + +// TestMcpListFiltersToProfile checks that --profile lists the servers of that profile only, with no unmanaged entries, +// since those have no profile, and says so when the profile has no server. +func TestMcpListFiltersToProfile(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n\n[dogfood]\nhost = https://adb-2.test\ntoken = t\n") + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + genie := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + other := seedInstall(t, claude, "github-dogfood", "system.ai.github", "dogfood", "https://adb-2.test") + saveState(t, genie, other) + doc := readJSONFile(t, claudePath) + doc["mcpServers"].(map[string]any)["web_search"] = map[string]any{"command": "ug", "args": []any{"mcp-proxy"}} + data, err := json.Marshal(doc) + require.NoError(t, err) + require.NoError(t, os.WriteFile(claudePath, data, 0o600)) + + stdout, _, err := runMcpCmd(t, "list", "--profile", "logfood", "--output", "json") + require.NoError(t, err) + var out mcpListOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + require.Len(t, out.Profiles, 1) + assert.Equal(t, "logfood", out.Profiles[0].Profile) + assert.Empty(t, out.Unmanaged) + + _, stderr, err := runMcpCmd(t, "list", "--profile", "typo") + require.NoError(t, err) + assert.Contains(t, stderr.String(), "No Databricks MCP servers installed by this CLI on profile typo.") +} + +// TestMcpListJSONReportsStateError checks that a state file that cannot be read is a JSON document with the error, +// as remove writes it. +func TestMcpListJSONReportsStateError(t *testing.T) { + withHome(t) + dir, err := installer.GlobalSkillsDir(t.Context()) + require.NoError(t, err) + require.NoError(t, os.MkdirAll(dir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".state.json"), []byte("{not json"), 0o600)) + + stdout, _, err := runMcpCmd(t, "list", "--output", "json") + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + var out mcpListOutput + require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) + assert.NotEmpty(t, out.Error) + assert.Equal(t, protos.AitoolsErrorCategoryUncategorized, out.ErrorCategory) + assert.Empty(t, out.Profiles) +} + +// TestBuildMcpListWarnsOnceForUnresolvableConfigFile checks that an entry whose config file cannot be resolved gets one +// warning, for the server, not another for each agent it is installed in. The name has a NUL byte, which no file system +// accepts, on every platform. +func TestBuildMcpListWarnsOnceForUnresolvableConfigFile(t *testing.T) { + withHome(t) + claude := agents.ByName("claude-code") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + entry.ConfigFile = "unresolvable\x00.cfg" + saveState(t, entry) + + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + var warnings []string + for _, w := range out.Warnings { + if strings.Contains(w, "genie_one_mcp-logfood") { + warnings = append(warnings, w) + } + } + require.Len(t, warnings, 1, "one cause, one warning: %v", out.Warnings) + assert.Contains(t, warnings[0], "MCP server genie_one_mcp-logfood: ") + require.Len(t, out.Profiles, 1) + assert.Equal(t, statusUnknown, out.Profiles[0].Servers[0].Status) + assert.Equal(t, statusUnknown, out.Profiles[0].Servers[0].Agents[0].Status) +} diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index a56b5f9bcb0..d32ac50d9bd 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "maps" - "path/filepath" "slices" "strings" @@ -40,6 +39,8 @@ type removeRemoved struct { Service string `json:"service"` Profile string `json:"profile"` Agents []string `json:"agents"` + // RecordOnly names the agents whose record was dropped without an edit, because this CLI cannot edit their config. + RecordOnly []string `json:"record_only,omitempty"` } // removeSkipped is one server that was left in one agent: the agent is named, since a server can be removed from @@ -58,10 +59,13 @@ const ( removeDeleted removeOutcome = iota // removePruned means the entry was already gone from the agent config, so only the state record goes. removePruned - // removeKept means the entry is left in place, because it is not the one this CLI wrote or the agent config moved. + // removeKept means the entry is left in place, because it is not the one this CLI wrote. removeKept ) +// saveMCPState writes the MCP state. It is a variable so that a test can make the save fail. +var saveMCPState = mcp.SaveState + // recordDrop names one agent record to delete from state: the server's name and the agent. type recordDrop struct { name string @@ -76,23 +80,19 @@ func NewMcpRemoveCmd() *cobra.Command { Short: "Remove Databricks managed MCP servers from coding agents", Long: `Remove Databricks managed MCP servers that this CLI installed. -Choose servers with --names (server names as listed by 'aitools mcp list', or service names), ---profile, or --all. --profile narrows --all or --names to one profile, and --agents narrows -them to some agents. Interactive selection is not available yet, so one of --names, --profile -or --all is required. +Choose servers with --names (server names as listed by 'aitools mcp list', or service names; the +last part of a service name, such as github, is enough when only one schema has it), --profile, or +--all. --profile narrows --all or --names to one profile, and --agents narrows them to some agents. +Interactive selection is not available yet, so one of --names, --profile or --all is required. -Only entries this CLI wrote are removed. An entry that was changed outside this CLI, or whose agent -config moved, is left in place and reported. Entries that run 'aitools mcp serve' without an install -record are not chosen by any flag; 'aitools mcp list' shows them as unmanaged. Provider credentials -are not deleted.`, +Only entries this CLI wrote are removed. An entry that was changed outside this CLI is left in place +and reported. When an agent's config moved, the entry is removed from the file it was written to. +Entries that run 'aitools mcp serve' without an install record are not chosen by any flag; +'aitools mcp list' shows them as unmanaged. Provider credentials are not deleted.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() jsonMode := installOutputIsJSON(cmd) - if jsonMode { - // JSON mode writes only the result document to stdout. - ctx = cmdio.WithQuiet(ctx) - } out := &removeOutput{Removed: []removeRemoved{}, Skipped: []removeSkipped{}} runErr := runMcpRemove(ctx, cmd, f, jsonMode, out) @@ -154,8 +154,8 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso return err } - // Each agent config is read once, when the first selected server needs it. - configs := map[string]agentConfig{} + // Each agent config file is read once, when the first selected server needs it. + files := map[recordedFileKey]recordedFile{} var drops []recordDrop var agentErrs []error for _, e := range selected { @@ -165,12 +165,22 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso if targets != nil && !slices.ContainsFunc(targets, func(a *agents.Agent) bool { return a.Name == agentName }) { continue } - cfg, ok := configs[agentName] + a := agents.ByName(agentName) + if a == nil || !a.SupportsMCP() { + // There is no config this CLI can edit for the agent, so only the record can go. + removed.Agents = append(removed.Agents, agentName) + removed.RecordOnly = append(removed.RecordOnly, agentName) + drops = append(drops, recordDrop{name: e.Name, agent: agentName}) + continue + } + rec := e.Agents[agentName] + key := recordedFileKey{agent: agentName, path: rec.Path} + file, ok := files[key] if !ok { - cfg = readAgentConfig(ctx, agentName) - configs[agentName] = cfg + file = readRecordedFile(a, rec.Path) + files[key] = file } - outcome, reason, err := removeAgentEntry(ctx, e, agentName, cfg) + outcome, reason, err := removeAgentEntry(ctx, e, a, rec.Path, file) if err != nil { errs = append(errs, err) out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Agent: agentName, Reason: fmt.Sprintf("could not update %s: %s", agentDisplayName(agentName), err)}) @@ -183,7 +193,8 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso removed.Agents = append(removed.Agents, agentName) drops = append(drops, recordDrop{name: e.Name, agent: agentName}) } - if len(removed.Agents) > 0 { + // A server with no agent left in state is removed from state too, so it is reported as removed. + if len(removed.Agents) > 0 || len(e.Agents) == 0 { out.Removed = append(out.Removed, removed) } // A server that no agent gave up on is a failure. So is any agent failure when --agents named the agent. @@ -195,8 +206,8 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso } var saveErr error - if len(drops) > 0 { - saveErr = dropRecords(ctx, drops) + if len(drops) > 0 || slices.ContainsFunc(selected, func(e mcp.Entry) bool { return len(e.Agents) == 0 }) { + saveErr = dropRecords(ctx, drops, selected) } if !jsonMode { printRemoveResults(ctx, out) @@ -221,42 +232,78 @@ func validateMCPRemoveFlags(all bool, names []string, profileName string) error return nil } -// selectInstalls returns the state entries named by names (server or service names), or every entry when names is -// empty. profileName, when set, narrows the choice to that profile. A name that matches nothing, and a profile with no +// selectInstalls returns the state entries that names pick, in state order, or every entry in scope when names is +// empty. profileName, when set, narrows the scope to that profile. A name that matches nothing, and a profile with no // installed server, are errors, so a typo does not look like a successful removal. func selectInstalls(state *mcp.State, names []string, profileName string) ([]mcp.Entry, error) { + var scope []mcp.Entry + for _, e := range state.Servers { + if profileName == "" || e.Profile == profileName { + scope = append(scope, e) + } + } where := "" if profileName != "" { where = " on profile " + profileName } - var selected []mcp.Entry - found := make([]bool, len(names)) - inProfile := 0 - for _, e := range state.Servers { - if profileName != "" && e.Profile != profileName { - continue + chosen := make([]bool, len(scope)) + for _, name := range names { + matched, err := matchInstalls(scope, name) + if err != nil { + return nil, err } - inProfile++ - chosen := len(names) == 0 - for i, name := range names { - if matchesInstall(e, name) { - found[i] = true - chosen = true - } + if len(matched) == 0 { + return nil, failure(categoryServiceNotFound, nil, "no installed MCP server named %s%s", name, where) + } + for _, i := range matched { + chosen[i] = true } - if chosen { + } + if profileName != "" && len(scope) == 0 { + return nil, failure(categoryServiceNotFound, nil, "no installed MCP servers on profile %s", profileName) + } + if len(names) == 0 { + return scope, nil + } + var selected []mcp.Entry + for i, e := range scope { + if chosen[i] { selected = append(selected, e) } } - for i, name := range names { - if !found[i] { - return nil, failure(categoryServiceNotFound, nil, "no installed MCP server named %s%s", name, where) + return selected, nil +} + +// matchInstalls returns the indexes of the entries of scope that name means: a server name, a full service name, or +// the leaf of a service name (its last part), all without case. A leaf is refused when the entries it matches are of +// more than one service, since then it does not say which one is meant. +func matchInstalls(scope []mcp.Entry, name string) ([]int, error) { + var matched []int + var services []string + for i, e := range scope { + if !matchesInstall(e, name) { + continue + } + matched = append(matched, i) + if !slices.ContainsFunc(services, func(s string) bool { return strings.EqualFold(s, e.Service) }) { + services = append(services, e.Service) } } - if profileName != "" && inProfile == 0 { - return nil, failure(categoryServiceNotFound, nil, "no installed MCP servers on profile %s", profileName) + if len(services) > 1 && !strings.Contains(name, ".") { + return nil, failure(protos.AitoolsErrorCategoryInvalidFlags, nil, "%s matches more than one MCP service (%s); pass the full service name", + name, strings.Join(services, ", ")) } - return selected, nil + return matched, nil +} + +// matchesInstall reports whether a --names value means the entry: its server name, its service name, or the leaf of its +// service name when the value has no dot. Names compare without case. +func matchesInstall(e mcp.Entry, name string) bool { + if strings.EqualFold(e.Name, name) || strings.EqualFold(e.Service, name) { + return true + } + leaf := e.Service[strings.LastIndex(e.Service, ".")+1:] + return !strings.Contains(name, ".") && strings.EqualFold(leaf, name) } // checkTargetsInstalled refuses an --agents agent that none of the selected servers is installed for. With no @@ -276,24 +323,32 @@ func checkTargetsInstalled(selected []mcp.Entry, targets []*agents.Agent) error return nil } -// matchesInstall reports whether a --names value means the entry: its server name, or its service name. -func matchesInstall(e mcp.Entry, name string) bool { - return e.Name == name || strings.EqualFold(e.Service, name) +// recordedFile is an agent config file that a record names, read once for a command. err is set when it cannot be +// read; a file that does not exist has no entries. +type recordedFile struct { + entries map[string]map[string]any + err error } -// removeAgentEntry removes the server from one agent config, but only when the entry there is the one this CLI -// wrote. The config was read by the caller; a config that could not be read is an error, not a removal. A config -// that moved is kept, since the entry may be in the file the record names. -func removeAgentEntry(ctx context.Context, e mcp.Entry, agentName string, cfg agentConfig) (removeOutcome, string, error) { - if cfg.err != nil { - return 0, "", cfg.err - } - recorded := e.Agents[agentName].Path - if !mcp.SamePath(recorded, cfg.path) { - return removeKept, fmt.Sprintf("%s reads its config from %s now, but %s was written to %s; left in place, and its record kept", - agentDisplayName(agentName), filepath.ToSlash(cfg.path), e.Name, filepath.ToSlash(recorded)), nil +// recordedFileKey names a recordedFile: the agent and the path its record gives. +type recordedFileKey struct { + agent string + path string +} + +func readRecordedFile(a *agents.Agent, path string) recordedFile { + entries, err := agentconfig.ReadAt(a, path) + return recordedFile{entries: entries, err: err} +} + +// removeAgentEntry removes the server from the agent config file its record names, but only when the entry there is +// the one this CLI wrote. The file is the one add wrote the entry to, even when the agent reads its config from +// elsewhere now. A file that no longer exists, or has no entry of the name, is pruned. +func removeAgentEntry(ctx context.Context, e mcp.Entry, a *agents.Agent, path string, file recordedFile) (removeOutcome, string, error) { + if file.err != nil { + return 0, "", file.err } - current, found := cfg.entries[e.Name] + current, found := file.entries[e.Name] if !found { return removePruned, "", nil } @@ -302,18 +357,18 @@ func removeAgentEntry(ctx context.Context, e mcp.Entry, agentName string, cfg ag return 0, "", err } if !owned { - return removeKept, fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place", agentDisplayName(agentName), e.Name), nil + return removeKept, fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place", agentDisplayName(a.Name), e.Name), nil } - if _, err := agentconfig.Remove(ctx, cfg.agent, e.Name); err != nil { + if _, err := agentconfig.RemoveAt(a, path, e.Name); err != nil { return 0, "", err } return removeDeleted, "", nil } -// dropRecords deletes the agent records from state and then the entries left without any agent. Each record is -// matched by the name of its server, which is unique in state. The state file is re-read first, so entries written -// since the selection are kept. -func dropRecords(ctx context.Context, drops []recordDrop) error { +// dropRecords deletes the agent records in drops from state, then the entries that were selected or dropped and have +// no agent left. Each record is matched by the name of its server, which is unique in state. The state file is re-read +// first, so entries written since the selection are kept, and an entry that was not selected is never removed here. +func dropRecords(ctx context.Context, drops []recordDrop, selected []mcp.Entry) error { state, err := mcp.LoadState(ctx) if err != nil { return err @@ -326,10 +381,17 @@ func dropRecords(ctx context.Context, drops []recordDrop) error { delete(state.Servers[i].Agents, d.agent) } } + touched := map[string]bool{} + for _, d := range drops { + touched[d.name] = true + } + for _, e := range selected { + touched[e.Name] = true + } state.Servers = slices.DeleteFunc(state.Servers, func(e mcp.Entry) bool { - return len(e.Agents) == 0 + return touched[e.Name] && len(e.Agents) == 0 }) - return mcp.SaveState(ctx, state) + return saveMCPState(ctx, state) } func printRemoveResults(ctx context.Context, out *removeOutput) { @@ -338,7 +400,14 @@ func printRemoveResults(ctx context.Context, out *removeOutput) { return } for _, r := range out.Removed { - cmdio.LogString(ctx, fmt.Sprintf("Removed %s %s profile %s (%s)", r.Name, r.Service, r.Profile, mcpAgentList(r.Agents))) + line := fmt.Sprintf("Removed %s %s profile %s", r.Name, r.Service, r.Profile) + if len(r.Agents) > 0 { + line += fmt.Sprintf(" (%s)", mcpAgentList(r.Agents)) + } + cmdio.LogString(ctx, line) + for _, name := range r.RecordOnly { + cmdio.LogString(ctx, fmt.Sprintf(" only the record of %s was dropped: this CLI has no MCP config to edit for it", agentDisplayName(name))) + } } for _, s := range out.Skipped { cmdio.LogString(ctx, fmt.Sprintf("Skipped %s: %s", s.Name, s.Reason)) diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index 03379d45bc0..52e7a0efc6a 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -1,7 +1,9 @@ package aitools import ( + "context" "encoding/json" + "errors" "maps" "os" "path/filepath" @@ -10,7 +12,6 @@ import ( "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" - "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/telemetry/protos" "github.com/stretchr/testify/assert" @@ -91,6 +92,36 @@ func TestSelectInstalls(t *testing.T) { assert.Empty(t, none) } +func TestSelectInstallsLeafAndCaseRules(t *testing.T) { + state := &mcp.State{Servers: []mcp.Entry{ + {Name: "github-logfood", Service: "system.ai.github", Profile: "logfood"}, + {Name: "github-dogfood", Service: "system.ai.github", Profile: "dogfood"}, + {Name: "github-team", Service: "team.ai.github", Profile: "logfood"}, + }} + + // Server names compare without case. + byName, err := selectInstalls(state, []string{"GITHUB-LOGFOOD"}, "") + require.NoError(t, err) + require.Len(t, byName, 1) + + // A leaf is the last part of the service name. Here it names services in two schemas, so it is refused. + _, err = selectInstalls(state, []string{"github"}, "") + require.Error(t, err) + assert.Equal(t, "github matches more than one MCP service (system.ai.github, team.ai.github); pass the full service name", err.Error()) + assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, errorCategory(err)) + + // Narrowed to a profile where only one schema is installed, the leaf is unambiguous. + byLeaf, err := selectInstalls(state, []string{"github"}, "dogfood") + require.NoError(t, err) + require.Len(t, byLeaf, 1) + assert.Equal(t, "dogfood", byLeaf[0].Profile) + + // A name with a dot is a full service name, not a leaf. + full, err := selectInstalls(state, []string{"team.ai.github"}, "") + require.NoError(t, err) + require.Len(t, full, 1) +} + func readJSONFile(t *testing.T, path string) map[string]any { t.Helper() data, err := os.ReadFile(path) @@ -176,14 +207,16 @@ func TestMcpRemoveSkipsEntryChangedOutsideCLI(t *testing.T) { assert.Contains(t, state.Servers[0].Agents, "claude-code", "the record stays, so list keeps showing the entry") } -func TestMcpRemoveKeepsEntryWhenAgentConfigMoved(t *testing.T) { +// TestMcpRemoveRemovesEntryFromRecordedFileWhenAgentConfigMoved checks that an agent whose config moved loses its entry +// from the file the record names, the file this CLI wrote, and that the record goes with it. +func TestMcpRemoveRemovesEntryFromRecordedFileWhenAgentConfigMoved(t *testing.T) { home := withHome(t) claude := agents.ByName("claude-code") claudePath := filepath.Join(home, ".claude.json") entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") saveState(t, entry) - // The agent now reads its config from another directory. The entry is still in the file it was written to. + // The agent now reads its config from another directory. moved := t.TempDir() t.Setenv("CLAUDE_CONFIG_DIR", moved) @@ -191,17 +224,115 @@ func TestMcpRemoveKeepsEntryWhenAgentConfigMoved(t *testing.T) { require.NoError(t, err) out := readRemoveOutput(t, stdout.String()) - assert.Empty(t, out.Removed, "a file the agent no longer reads is not pruned") - require.Len(t, out.Skipped, 1) - assert.Equal(t, "claude-code", out.Skipped[0].Agent) - assert.Contains(t, out.Skipped[0].Reason, filepath.ToSlash(claudePath), "the reason names the file the entry was written to") - assert.Contains(t, out.Skipped[0].Reason, filepath.ToSlash(filepath.Join(moved, ".claude.json")), "and the file the agent reads now") + require.Len(t, out.Removed, 1) + assert.Equal(t, []string{"claude-code"}, out.Removed[0].Agents) + assert.Empty(t, out.Skipped) + assert.NotContains(t, readJSONFile(t, claudePath)["mcpServers"], "genie_one_mcp-logfood") + _, err = os.Stat(filepath.Join(moved, ".claude.json")) + assert.ErrorIs(t, err, os.ErrNotExist, "the agent's current file is not written") + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Empty(t, state.Servers, "the record went with the entry") +} + +// TestMcpRemovePrunesWhenRecordedFileIsGone checks that a record whose file no longer exists is pruned, even when the +// agent's config moved to a directory that is not the recorded one. +func TestMcpRemovePrunesWhenRecordedFileIsGone(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + require.NoError(t, os.Remove(claudePath)) + t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir()) + + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood", "--output", "json") + require.NoError(t, err) + + out := readRemoveOutput(t, stdout.String()) + require.Len(t, out.Removed, 1) + assert.Equal(t, []string{"claude-code"}, out.Removed[0].Agents) + assert.Empty(t, out.Skipped) + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Empty(t, state.Servers) +} + +// TestMcpRemoveDropsRecordOfAgentThatCannotBeEdited checks that a record for an agent this CLI cannot edit, one +// outside the registry or one without MCP support, is dropped and reported, not left to fail every remove --all. +func TestMcpRemoveDropsRecordOfAgentThatCannotBeEdited(t *testing.T) { + withHome(t) + claude := agents.ByName("claude-code") + genie := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + retired := mcp.Entry{ + Name: "dbsql-logfood", Service: "system.ai.dbsql", Profile: "logfood", Host: "https://adb-1.test", Command: testDatabricksCommand, + Agents: map[string]mcp.AgentRecord{"retired-agent": {Path: "/x/config.json", Scope: "user"}, "pi": {Path: "/x/pi.json", Scope: "user"}}, + } + saveState(t, genie, retired) + + stdout, _, err := runMcpCmd(t, "remove", "--all", "--output", "json") + require.NoError(t, err, "a record that cannot be edited is not a failure") + + out := readRemoveOutput(t, stdout.String()) + assert.Empty(t, out.Error) + assert.Empty(t, out.Skipped) + require.Len(t, out.Removed, 2) + assert.Equal(t, []string{"pi", "retired-agent"}, out.Removed[1].Agents) + assert.Equal(t, []string{"pi", "retired-agent"}, out.Removed[1].RecordOnly, "only the record of these agents was dropped") + assert.Equal(t, []string{"claude-code"}, out.Removed[0].Agents) + assert.Empty(t, out.Removed[0].RecordOnly) + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Empty(t, state.Servers) +} + +// TestMcpRemoveDropsNamedEntryWithoutAgents checks that a named entry left with no agents is removed from state. +func TestMcpRemoveDropsNamedEntryWithoutAgents(t *testing.T) { + withHome(t) + saveState(t, mcp.Entry{Name: "dangling", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", Command: testDatabricksCommand}) + + stdout, _, err := runMcpCmd(t, "remove", "--names", "dangling", "--output", "json") + require.NoError(t, err) + out := readRemoveOutput(t, stdout.String()) + require.Len(t, out.Removed, 1) + assert.Equal(t, "dangling", out.Removed[0].Name) + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Empty(t, state.Servers) +} + +// TestMcpRemoveKeepsUnselectedEntryWithoutAgents checks that removing one server does not drop another entry that +// has no agents: only the entries this run selected or emptied are dropped. +func TestMcpRemoveKeepsUnselectedEntryWithoutAgents(t *testing.T) { + withHome(t) + claude := agents.ByName("claude-code") + genie := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, genie, mcp.Entry{Name: "keep-me", Service: "system.ai.dbsql", Profile: "logfood", Host: "https://adb-1.test", Command: testDatabricksCommand}) + + _, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood") + require.NoError(t, err) - assert.Contains(t, readJSONFile(t, claudePath)["mcpServers"], "genie_one_mcp-logfood", "the entry in the old file is kept") state, err := mcp.LoadState(t.Context()) require.NoError(t, err) require.Len(t, state.Servers, 1) - assert.Contains(t, state.Servers[0].Agents, "claude-code", "the record is kept, so list can show the path change") + assert.Equal(t, "keep-me", state.Servers[0].Name) +} + +// TestMcpRemoveNamesAcceptsLeafService checks that --names takes the leaf of a service name, as add does. +func TestMcpRemoveNamesAcceptsLeafService(t *testing.T) { + withHome(t) + claude := agents.ByName("claude-code") + github := seedInstall(t, claude, "github-logfood", "system.ai.github", "logfood", "https://adb-1.test") + saveState(t, github) + + stdout, _, err := runMcpCmd(t, "remove", "--names", "github", "--output", "json") + require.NoError(t, err) + out := readRemoveOutput(t, stdout.String()) + require.Len(t, out.Removed, 1) + assert.Equal(t, "github-logfood", out.Removed[0].Name) } func TestMcpRemoveExplicitAgentFailureIsAnError(t *testing.T) { @@ -285,14 +416,12 @@ func TestMcpRemoveReportsResultsWhenStateCannotBeSaved(t *testing.T) { entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") saveState(t, entry) - // The agent entry is deleted first; then the state directory cannot take the new state file. - stateDir, err := installer.GlobalSkillsDir(t.Context()) - require.NoError(t, err) - require.NoError(t, os.Chmod(stateDir, 0o500)) - t.Cleanup(func() { _ = os.Chmod(stateDir, 0o700) }) + // The agent entry is deleted first; then the state cannot be written. + saveMCPState = func(context.Context, *mcp.State) error { return errors.New("state file is read-only") } + t.Cleanup(func() { saveMCPState = mcp.SaveState }) stdout, stderr, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood") - require.Error(t, err) + require.ErrorContains(t, err, "state file is read-only") assert.Empty(t, stdout.String()) assert.Contains(t, stderr.String(), "Removed genie_one_mcp-logfood", "the results are printed before the error") assert.NotContains(t, readJSONFile(t, claudePath)["mcpServers"], "genie_one_mcp-logfood") From 149114f4d61e4870baf9c857b024ebd8cffc2a70 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 20:51:06 +0000 Subject: [PATCH 11/26] aitools mcp: refactor list and remove helpers (pass 3) Remove mcp.Reconcile, which has no caller since list uses CheckEntries; its tests run on CheckEntries. Export mcp.LeafOf and use it in remove's name matching. EntryCheck carries the resolved config file, so list groups and checks ownership against the file that was checked. agentconfig.Remove is a thin wrapper over Path and RemoveAt. add reads the agent configs through readAgentConfig. No behavior change. Co-authored-by: Isaac --- cmd/aitools/mcp_add.go | 6 +- cmd/aitools/mcp_list.go | 22 +++++--- cmd/aitools/mcp_remove.go | 3 +- libs/aitools/mcp/agentconfig/writer.go | 5 +- libs/aitools/mcp/discovery.go | 2 +- libs/aitools/mcp/naming.go | 4 +- libs/aitools/mcp/state.go | 51 ++++++----------- libs/aitools/mcp/state_test.go | 77 ++++++++++++-------------- 8 files changed, 72 insertions(+), 98 deletions(-) diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index 960c5b2d458..d2c2a84947b 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -567,11 +567,9 @@ type agentEntries map[*agents.Agent]map[string]map[string]any func readAgentEntries(ctx context.Context, targets []*agents.Agent) agentEntries { held := make(agentEntries, len(targets)) for _, a := range targets { - entries, err := agentconfig.Read(ctx, a) - if err != nil { - continue + if cfg := readAgentConfig(ctx, a.Name); cfg.err == nil { + held[a] = cfg.entries } - held[a] = entries } return held } diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index 087fbd92cbb..289a2458d84 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -20,7 +20,7 @@ import ( "github.com/spf13/cobra" ) -// Agent entry statuses of `mcp list`. Server statuses are the drift kinds of mcp.Reconcile, plus statusOK and +// Agent entry statuses of `mcp list`. Server statuses are the drift kinds of mcp.CheckEntries, plus statusOK and // statusUnknown, which is an entry or config that could not be checked. const ( agentStatusInstalled = "installed" @@ -173,9 +173,10 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error checks := mcp.CheckEntries(ctx, &mcp.State{Servers: entries}) groups := map[profileKey]*mcpListProfile{} for i, e := range entries { - path, err := mcp.ResolveConfigFile(ctx, e.ConfigFile) - if err != nil { - // The entry cannot be checked, so it is grouped under its file as written. + check := checks[i] + path := check.Path + if path == "" { + // The file cannot be resolved, so the entry is grouped under its file as written. path = e.ConfigFile } key := profileKey{profile: e.Profile, path: path} @@ -188,7 +189,6 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error p.ConfigFile = filepath.ToSlash(path) } s := mcpListServer{Name: e.Name, Service: e.Service, SignInRequired: e.SignInRequired, Status: statusOK, Agents: []mcpListAgent{}, entry: e} - check := checks[i] switch { case check.Err != nil: s.Status = statusUnknown @@ -208,7 +208,7 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error status := statusUnknown if cfg := configs[agentName]; cfg.err == nil { var err error - status, err = agentStatus(ctx, e, agentName, cfg) + status, err = agentStatus(ctx, e, agentName, cfg, check) // When the entry itself could not be checked, its warning already names the cause. if err != nil && check.Err == nil { out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: could not check %s: %s", e.Name, agentDisplayName(agentName), err)) @@ -297,8 +297,9 @@ func readAgentConfig(ctx context.Context, name string) agentConfig { // agentStatus compares the server's entry for one agent with that agent's config, which must have been read. An // agent whose config moved is path_changed: the entry is in the file the record names, which this command does -// not read. err is set when the entry cannot be checked for ownership. -func agentStatus(ctx context.Context, rec mcp.Entry, agentName string, cfg agentConfig) (string, error) { +// not read. check is the entry's check, whose Path is the config file the record is pinned to. err is set when the +// entry cannot be checked for ownership. +func agentStatus(ctx context.Context, rec mcp.Entry, agentName string, cfg agentConfig, check mcp.EntryCheck) (string, error) { if !mcp.SamePath(rec.Agents[agentName].Path, cfg.path) { return agentStatusPathChanged, nil } @@ -306,7 +307,10 @@ func agentStatus(ctx context.Context, rec mcp.Entry, agentName string, cfg agent if !ok { return agentStatusMissingOnDisk, nil } - owned, err := ownedBy(ctx, rec, current) + if check.Path == "" { + return statusUnknown, check.Err + } + owned, err := mcp.EntryServes(ctx, current, rec.Service, rec.Profile, check.Path) if err != nil { return statusUnknown, err } diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index d32ac50d9bd..b19c0176e56 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -302,8 +302,7 @@ func matchesInstall(e mcp.Entry, name string) bool { if strings.EqualFold(e.Name, name) || strings.EqualFold(e.Service, name) { return true } - leaf := e.Service[strings.LastIndex(e.Service, ".")+1:] - return !strings.Contains(name, ".") && strings.EqualFold(leaf, name) + return !strings.Contains(name, ".") && strings.EqualFold(mcp.LeafOf(e.Service), name) } // checkTargetsInstalled refuses an --agents agent that none of the selected servers is installed for. With no diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index a8eec302940..43696c8f3df 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -153,9 +153,6 @@ func Upsert(ctx context.Context, a *agents.Agent, name, cmd string, args []strin // writing, when there is no such entry, and refuses an entry this CLI did not // write. func Remove(ctx context.Context, a *agents.Agent, name string) (bool, error) { - if err := checkName(name); err != nil { - return false, err - } path, err := Path(ctx, a) if err != nil { return false, err @@ -233,7 +230,7 @@ func Path(ctx context.Context, a *agents.Agent) (string, error) { return spec.Path(ctx) } -// checkName refuses a name that no agent would accept. Upsert and Remove both +// checkName refuses a name that no agent would accept. Upsert and RemoveAt both // check it, so a name that cannot be written is never looked up either. func checkName(name string) error { if !mcpconfig.ValidServerName(name) { diff --git a/libs/aitools/mcp/discovery.go b/libs/aitools/mcp/discovery.go index bf34adc7d6b..6c448d2543b 100644 --- a/libs/aitools/mcp/discovery.go +++ b/libs/aitools/mcp/discovery.go @@ -146,7 +146,7 @@ func oauthProvider(svc *catalog.McpService) string { // returned name. func newService(svc *catalog.McpService) Service { fullName := strings.TrimPrefix(svc.Name, mcpServicePrefix) - leaf := leafOf(fullName) + leaf := LeafOf(fullName) provider := oauthProvider(svc) s := Service{ diff --git a/libs/aitools/mcp/naming.go b/libs/aitools/mcp/naming.go index 4fa910c7daa..29ee269b3db 100644 --- a/libs/aitools/mcp/naming.go +++ b/libs/aitools/mcp/naming.go @@ -34,7 +34,7 @@ func Sanitize(s string) string { func ServerName(fullName, profile string) string { parts := strings.Split(fullName, ".") if inSystemAI(fullName) { - parts = []string{leafOf(fullName)} + parts = []string{LeafOf(fullName)} } var name []string @@ -47,7 +47,7 @@ func ServerName(fullName, profile string) string { } // leafOf returns the service name after the last ".". Unity Catalog names cannot contain ".". -func leafOf(fullName string) string { +func LeafOf(fullName string) string { return fullName[strings.LastIndex(fullName, ".")+1:] } diff --git a/libs/aitools/mcp/state.go b/libs/aitools/mcp/state.go index e25b658e3e9..30e444cd085 100644 --- a/libs/aitools/mcp/state.go +++ b/libs/aitools/mcp/state.go @@ -12,7 +12,7 @@ import ( "github.com/databricks/databricks-sdk-go/config" ) -// Drift kinds reported by Reconcile. +// Drift kinds reported by CheckEntries. const ( DriftProfileMissing DriftKind = "profile_missing" DriftHostChanged DriftKind = "host_changed" @@ -81,10 +81,12 @@ func SaveState(ctx context.Context, state *State) error { } // EntryCheck is the result of checking one state entry. Drift is nil when the entry's profile still names the recorded -// host and workspace. Err is set when the entry cannot be checked. +// host and workspace. Err is set when the entry cannot be checked. Path is the config file the entry is checked against, +// resolved; it is "" when that file cannot be resolved, and Err says why. type EntryCheck struct { Drift *Drift Err error + Path string } // CheckEntries checks each entry of state against its profile and returns one result per entry, in state order. Each @@ -95,47 +97,28 @@ func CheckEntries(ctx context.Context, state *State) []EntryCheck { files := configFiles{} checks := make([]EntryCheck, len(state.Servers)) for i, entry := range state.Servers { - drift, err := checkEntry(ctx, files, entry) - checks[i] = EntryCheck{Drift: drift, Err: err} + checks[i] = checkEntry(ctx, files, entry) } return checks } -// Reconcile reports entries whose profile is gone or has no host, and entries whose profile now -// names another host, or another workspace when both the entry and the profile name one. See -// CheckEntries for how each entry is checked. -// -// An entry that cannot be checked does not stop the others. Its error is joined into the returned -// error, and the drifts of the other entries are still returned. -func Reconcile(ctx context.Context, state *State) ([]Drift, error) { - var drifts []Drift - var errs []error - for i, check := range CheckEntries(ctx, state) { - switch { - case check.Err != nil: - errs = append(errs, fmt.Errorf("MCP server %s: %w", state.Servers[i].Name, check.Err)) - case check.Drift != nil: - drifts = append(drifts, *check.Drift) - } - } - return drifts, errors.Join(errs...) -} - -// checkEntry returns the drift of one entry, or nil when its profile still names the recorded host -// and workspace. The entry's profile is read from the config file the entry is pinned to. -func checkEntry(ctx context.Context, files configFiles, entry Entry) (*Drift, error) { +// checkEntry checks one entry against the profile in the config file it is pinned to. +func checkEntry(ctx context.Context, files configFiles, entry Entry) EntryCheck { path, err := ResolveConfigFile(ctx, entry.ConfigFile) if err != nil { - return nil, err + return EntryCheck{Err: err} } + check := EntryCheck{Path: path} p, err := files.profile(path, entry.Profile) - if errors.Is(err, errProfileMissing) || errors.Is(err, errProfileNoHost) { - return &Drift{Kind: DriftProfileMissing, Entry: entry, NoHost: errors.Is(err, errProfileNoHost)}, nil - } - if err != nil { - return nil, err + switch { + case errors.Is(err, errProfileMissing) || errors.Is(err, errProfileNoHost): + check.Drift = &Drift{Kind: DriftProfileMissing, Entry: entry, NoHost: errors.Is(err, errProfileNoHost)} + case err != nil: + check.Err = err + default: + check.Drift = driftOf(entry, p) } - return driftOf(entry, p), nil + return check } // configFiles holds the config files that one lookup has read, by resolved path, so that each file is diff --git a/libs/aitools/mcp/state_test.go b/libs/aitools/mcp/state_test.go index ee108f559fe..6b6b87e71d0 100644 --- a/libs/aitools/mcp/state_test.go +++ b/libs/aitools/mcp/state_test.go @@ -3,6 +3,7 @@ package mcp_test import ( "context" "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -132,7 +133,7 @@ func TestSaveStateUpgradesV2FileToV3(t *testing.T) { // stateTestProfiles is the profiles file used by the drift tests. The profiles named // spog-query, spog-none, spog-both and spog-abc name their workspace in the host query instead of // workspace_id. -// stateTestWriteProfiles writes the profiles that the Reconcile tests check to the default config file +// stateTestWriteProfiles writes the profiles that the CheckEntries tests check to the default config file // of the test home directory. func stateTestWriteProfiles(t *testing.T, ctx context.Context) { t.Helper() @@ -160,7 +161,22 @@ host = https://spog.test/?o=abc&w=222 `, bindingTestProfile, bindingTestHost, stateTestWorkspaceID, stateTestOtherProfile, stateTestOtherHost)) } -func TestReconcile(t *testing.T) { +// driftsOf returns the drifts of checks in state order, and the errors of the entries that cannot be checked. +func driftsOf(checks []mcp.EntryCheck) ([]mcp.Drift, error) { + var drifts []mcp.Drift + var errs []error + for _, c := range checks { + if c.Err != nil { + errs = append(errs, c.Err) + } + if c.Drift != nil { + drifts = append(drifts, *c.Drift) + } + } + return drifts, errors.Join(errs...) +} + +func TestCheckEntries(t *testing.T) { ctx, _ := stateTestCtx(t) stateTestWriteProfiles(t, ctx) tests := []struct { @@ -236,7 +252,7 @@ func TestReconcile(t *testing.T) { t.Run(tt.name, func(t *testing.T) { state := &mcp.State{Servers: []mcp.Entry{tt.entry}} - drifts, err := mcp.Reconcile(ctx, state) + drifts, err := driftsOf(mcp.CheckEntries(ctx, state)) require.NoError(t, err) if tt.wantKind == "" { assert.Empty(t, drifts) @@ -252,34 +268,34 @@ func TestReconcile(t *testing.T) { } } -func TestReconcileWithoutConfigFileReportsEveryProfileMissing(t *testing.T) { +func TestCheckEntriesWithoutConfigFileReportsEveryProfileMissing(t *testing.T) { ctx, _ := stateTestCtx(t) ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) entry := stateTestEntry() state := &mcp.State{Servers: []mcp.Entry{entry}} - drifts, err := mcp.Reconcile(ctx, state) + drifts, err := driftsOf(mcp.CheckEntries(ctx, state)) require.NoError(t, err) assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry}}, drifts) } -// TestReconcileChecksEntryAgainstPinnedConfigFile checks that an entry pinned to a config file +// TestCheckEntriesChecksEntryAgainstPinnedConfigFile checks that an entry pinned to a config file // is checked against that file, not the one the environment names. -func TestReconcileChecksEntryAgainstPinnedConfigFile(t *testing.T) { +func TestCheckEntriesChecksEntryAgainstPinnedConfigFile(t *testing.T) { pinned := bindingTestWriteConfig(t, bindingTestProfileContents(bindingTestToken)) ctx := env.Set(t.Context(), "DATABRICKS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) entry := stateTestEntry() entry.ConfigFile = pinned state := &mcp.State{Servers: []mcp.Entry{entry}} - drifts, err := mcp.Reconcile(ctx, state) + drifts, err := driftsOf(mcp.CheckEntries(ctx, state)) require.NoError(t, err) assert.Empty(t, drifts) } -// TestReconcileUnpinnedEntryChecksDefaultConfigFile checks that an entry with no pinned config file +// TestCheckEntriesUnpinnedEntryChecksDefaultConfigFile checks that an entry with no pinned config file // is checked against ~/.databrickscfg, even when DATABRICKS_CONFIG_FILE names another file. -func TestReconcileUnpinnedEntryChecksDefaultConfigFile(t *testing.T) { +func TestCheckEntriesUnpinnedEntryChecksDefaultConfigFile(t *testing.T) { ctx, _ := stateTestCtx(t) home, err := env.UserHomeDir(ctx) require.NoError(t, err) @@ -288,7 +304,7 @@ func TestReconcileUnpinnedEntryChecksDefaultConfigFile(t *testing.T) { ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", ambient) state := &mcp.State{Servers: []mcp.Entry{stateTestEntry()}} - drifts, err := mcp.Reconcile(ctx, state) + drifts, err := driftsOf(mcp.CheckEntries(ctx, state)) require.NoError(t, err) assert.Equal(t, []mcp.Drift{{ Kind: mcp.DriftHostChanged, @@ -303,10 +319,10 @@ func TestNormalizeHostIgnoresSchemeCaseAndTrailingSlash(t *testing.T) { assert.NotEqual(t, mcp.NormalizeHost("https://adb-123.test"), mcp.NormalizeHost("https://adb-456.test")) } -// TestReconcileProfileWithoutHostIsMissing checks that a profile section with no host is reported as +// TestCheckEntriesProfileWithoutHostIsMissing checks that a profile section with no host is reported as // missing, since it names no host to compare. It reads a real file, because the in-memory profiler // does not model sections without a host. -func TestReconcileProfileWithEmptyHostIsMissing(t *testing.T) { +func TestCheckEntriesProfileWithEmptyHostIsMissing(t *testing.T) { ctx, _ := stateTestCtx(t) path := bindingTestWriteConfig(t, "[logfood]\nhost =\nauth_type = pat\ntoken = dapi-profile-token\n") // The entry is pinned to the file that has the section, so the check reads that file. @@ -314,60 +330,37 @@ func TestReconcileProfileWithEmptyHostIsMissing(t *testing.T) { entry.ConfigFile = path state := &mcp.State{Servers: []mcp.Entry{entry}} - drifts, err := mcp.Reconcile(ctx, state) + drifts, err := driftsOf(mcp.CheckEntries(ctx, state)) require.NoError(t, err) assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry, NoHost: true}}, drifts) } -func TestReconcileProfileWithoutHostIsMissing(t *testing.T) { +func TestCheckEntriesProfileWithoutHostIsMissing(t *testing.T) { ctx, _ := stateTestCtx(t) path := bindingTestWriteConfig(t, "[logfood]\nauth_type = pat\ntoken = dapi-profile-token\n") entry := stateTestEntry() entry.ConfigFile = path state := &mcp.State{Servers: []mcp.Entry{entry}} - drifts, err := mcp.Reconcile(ctx, state) + drifts, err := driftsOf(mcp.CheckEntries(ctx, state)) require.NoError(t, err) assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry, NoHost: true}}, drifts) } -// TestReconcileAbsentSectionIsMissingWithoutNoHost checks that a file with no section of the profile's name is +// TestCheckEntriesAbsentSectionIsMissingWithoutNoHost checks that a file with no section of the profile's name is // reported as missing, not as a section with no host. -func TestReconcileAbsentSectionIsMissingWithoutNoHost(t *testing.T) { +func TestCheckEntriesAbsentSectionIsMissingWithoutNoHost(t *testing.T) { ctx, _ := stateTestCtx(t) path := bindingTestWriteConfig(t, "[other]\nhost = https://adb-456.test\ntoken = dapi-profile-token\n") entry := stateTestEntry() entry.ConfigFile = path state := &mcp.State{Servers: []mcp.Entry{entry}} - drifts, err := mcp.Reconcile(ctx, state) + drifts, err := driftsOf(mcp.CheckEntries(ctx, state)) require.NoError(t, err) assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry}}, drifts) } -// TestReconcileReportsEntryErrorAndKeepsOthers checks that an entry that cannot be checked, here a "~" -// path with no home directory, is reported as an error without stopping the check of the other entries. -func TestReconcileReportsEntryErrorAndKeepsOthers(t *testing.T) { - ctx, _ := stateTestCtx(t) - ctx = env.WithUserHomeDir(ctx, "") - unresolvable := stateTestEntry() - unresolvable.Name = "github-home" - unresolvable.ConfigFile = "~/.databrickscfg" - changed := stateTestEntryWith(bindingTestProfile, "https://adb-999.test", stateTestWorkspaceID) - changed.ConfigFile = bindingTestWriteConfig(t, fmt.Sprintf("[%s]\nhost = %s\nworkspace_id = %s\nauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestHost, stateTestWorkspaceID, bindingTestToken)) - state := &mcp.State{Servers: []mcp.Entry{unresolvable, changed}} - - drifts, err := mcp.Reconcile(ctx, state) - require.ErrorIs(t, err, env.ErrNoHomeEnv) - assert.Contains(t, err.Error(), "MCP server github-home: ") - assert.Equal(t, []mcp.Drift{{ - Kind: mcp.DriftHostChanged, - Entry: changed, - CurrentHost: bindingTestHost, - CurrentWorkspaceID: stateTestWorkspaceID, - }}, drifts) -} - // TestCheckEntriesKeepsEachResultOnItsEntry checks that CheckEntries returns one result per entry, in state order, // and that an entry that cannot be checked does not take the result of another entry with it. func TestCheckEntriesKeepsEachResultOnItsEntry(t *testing.T) { From 660c40156a9a3000378b61a17f22b80fc28b1462 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 20:52:38 +0000 Subject: [PATCH 12/26] aitools mcp remove: server name wins, absolute config paths, and the moved file A --names value equal to a server name selects that server only, and is not refused as ambiguous when another schema has the same leaf. Service and leaf matching apply only when no server has the name. agentconfig records absolute config paths: a relative CLAUDE_CONFIG_DIR, CODEX_HOME or COPILOT_HOME is made absolute at add time, so remove from another directory edits the same file. When the recorded file no longer holds the entry and the agent now reads another file, remove takes the owned entry out of that file and drops the record. The entry is pruned only when neither file holds it. Co-authored-by: Isaac --- cmd/aitools/mcp_remove.go | 72 ++++++++++++++----- cmd/aitools/mcp_remove_test.go | 96 +++++++++++++++++++++++++- libs/aitools/mcp/agentconfig/writer.go | 16 ++++- 3 files changed, 162 insertions(+), 22 deletions(-) diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index b19c0176e56..8d3be56357b 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -173,14 +173,13 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso drops = append(drops, recordDrop{name: e.Name, agent: agentName}) continue } - rec := e.Agents[agentName] - key := recordedFileKey{agent: agentName, path: rec.Path} - file, ok := files[key] - if !ok { - file = readRecordedFile(a, rec.Path) - files[key] = file + path, file, err := entryFile(ctx, e, a, e.Agents[agentName].Path, files) + if err != nil { + errs = append(errs, err) + out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Agent: agentName, Reason: fmt.Sprintf("could not update %s: %s", agentDisplayName(agentName), err)}) + continue } - outcome, reason, err := removeAgentEntry(ctx, e, a, rec.Path, file) + outcome, reason, err := removeAgentEntry(ctx, e, a, path, file) if err != nil { errs = append(errs, err) out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Agent: agentName, Reason: fmt.Sprintf("could not update %s: %s", agentDisplayName(agentName), err)}) @@ -274,14 +273,19 @@ func selectInstalls(state *mcp.State, names []string, profileName string) ([]mcp return selected, nil } -// matchInstalls returns the indexes of the entries of scope that name means: a server name, a full service name, or -// the leaf of a service name (its last part), all without case. A leaf is refused when the entries it matches are of -// more than one service, since then it does not say which one is meant. +// matchInstalls returns the indexes of the entries of scope that name means. A server name is unique in state, so a +// name equal to one selects that server and nothing else. Only when no server has the name, it means the service: the +// full service name, or the leaf of a service name (its last part, when the name has no dot). All comparisons ignore +// case. A leaf is refused when the entries it matches are of more than one service, since then it does not say which +// one is meant. func matchInstalls(scope []mcp.Entry, name string) ([]int, error) { + if i := slices.IndexFunc(scope, func(e mcp.Entry) bool { return strings.EqualFold(e.Name, name) }); i >= 0 { + return []int{i}, nil + } var matched []int var services []string for i, e := range scope { - if !matchesInstall(e, name) { + if !matchesService(e, name) { continue } matched = append(matched, i) @@ -290,16 +294,16 @@ func matchInstalls(scope []mcp.Entry, name string) ([]int, error) { } } if len(services) > 1 && !strings.Contains(name, ".") { - return nil, failure(protos.AitoolsErrorCategoryInvalidFlags, nil, "%s matches more than one MCP service (%s); pass the full service name", + return nil, failure(protos.AitoolsErrorCategoryInvalidFlags, nil, "%s matches more than one MCP service (%s); pass the full service name or a server name", name, strings.Join(services, ", ")) } return matched, nil } -// matchesInstall reports whether a --names value means the entry: its server name, its service name, or the leaf of its -// service name when the value has no dot. Names compare without case. -func matchesInstall(e mcp.Entry, name string) bool { - if strings.EqualFold(e.Name, name) || strings.EqualFold(e.Service, name) { +// matchesService reports whether a --names value means the entry's service: its full name, or the leaf of its service +// name when the value has no dot. Names compare without case. +func matchesService(e mcp.Entry, name string) bool { + if strings.EqualFold(e.Service, name) { return true } return !strings.Contains(name, ".") && strings.EqualFold(mcp.LeafOf(e.Service), name) @@ -335,14 +339,44 @@ type recordedFileKey struct { path string } +// readRecordedFile reads the agent config file at path, which a record names. A file that does not exist has no entries. func readRecordedFile(a *agents.Agent, path string) recordedFile { entries, err := agentconfig.ReadAt(a, path) return recordedFile{entries: entries, err: err} } -// removeAgentEntry removes the server from the agent config file its record names, but only when the entry there is -// the one this CLI wrote. The file is the one add wrote the entry to, even when the agent reads its config from -// elsewhere now. A file that no longer exists, or has no entry of the name, is pruned. +// cachedRecordedFile returns the agent config file at path from files, reading it on first use. +func cachedRecordedFile(files map[recordedFileKey]recordedFile, a *agents.Agent, path string) recordedFile { + key := recordedFileKey{agent: a.Name, path: path} + file, ok := files[key] + if !ok { + file = readRecordedFile(a, path) + files[key] = file + } + return file +} + +// entryFile returns the config file that holds the server's entry for the agent, and its contents. That is the file the +// record names, unless the file does not hold the entry and the agent now reads its config from another file: then that +// file, which may hold it, since the user may have moved the config with the agent's directory. A recorded file that +// cannot be read is returned as it is, so the error is reported for it. +func entryFile(ctx context.Context, e mcp.Entry, a *agents.Agent, recorded string, files map[recordedFileKey]recordedFile) (string, recordedFile, error) { + file := cachedRecordedFile(files, a, recorded) + if _, found := file.entries[e.Name]; found || file.err != nil { + return recorded, file, nil + } + current, err := agentconfig.Path(ctx, a) + if err != nil { + return "", recordedFile{}, err + } + if mcp.SamePath(current, recorded) { + return recorded, file, nil + } + return current, cachedRecordedFile(files, a, current), nil +} + +// removeAgentEntry removes the server from the config file at path, but only when the entry there is the one this CLI +// wrote. A file that has no entry of the name is pruned: the record goes without an edit. func removeAgentEntry(ctx context.Context, e mcp.Entry, a *agents.Agent, path string, file recordedFile) (removeOutcome, string, error) { if file.err != nil { return 0, "", file.err diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index 52e7a0efc6a..d6ee1064ffa 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -107,7 +107,7 @@ func TestSelectInstallsLeafAndCaseRules(t *testing.T) { // A leaf is the last part of the service name. Here it names services in two schemas, so it is refused. _, err = selectInstalls(state, []string{"github"}, "") require.Error(t, err) - assert.Equal(t, "github matches more than one MCP service (system.ai.github, team.ai.github); pass the full service name", err.Error()) + assert.Equal(t, "github matches more than one MCP service (system.ai.github, team.ai.github); pass the full service name or a server name", err.Error()) assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, errorCategory(err)) // Narrowed to a profile where only one schema is installed, the leaf is unambiguous. @@ -479,3 +479,97 @@ func TestMcpRemoveFailsWithoutSelection(t *testing.T) { assert.Empty(t, out.Removed) assert.Empty(t, out.Skipped) } + +// TestSelectInstallsServerNameWins checks that a --names value equal to a server name selects that server only: it is +// not also a service or a leaf of other servers, and it is not refused as ambiguous when another schema has the leaf. +func TestSelectInstallsServerNameWins(t *testing.T) { + cases := []struct { + name string + state []mcp.Entry + want []string + }{ + { + name: "server name does not also remove the other profile's server of the same service", + state: []mcp.Entry{ + {Name: "github", Service: "system.ai.github", Profile: "logfood"}, + {Name: "github-dogfood", Service: "system.ai.github", Profile: "dogfood"}, + }, + want: []string{"github"}, + }, + { + name: "server name is not refused as ambiguous when another schema has the leaf", + state: []mcp.Entry{ + {Name: "github", Service: "system.ai.github", Profile: "logfood"}, + {Name: "gh-team", Service: "team.ai.github", Profile: "logfood"}, + }, + want: []string{"github"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + selected, err := selectInstalls(&mcp.State{Servers: tc.state}, []string{"github"}, "") + require.NoError(t, err) + var names []string + for _, e := range selected { + names = append(names, e.Name) + } + assert.Equal(t, tc.want, names) + }) + } +} + +// TestMcpRemoveFromAnotherDirectoryFindsConfigSetRelative checks that a relative config dir given at add time is +// recorded as an absolute path, so that remove run from another directory still edits the file the entry is in. +func TestMcpRemoveFromAnotherDirectoryFindsConfigSetRelative(t *testing.T) { + withHome(t) + work := t.TempDir() + t.Chdir(work) + require.NoError(t, os.MkdirAll(filepath.Join(work, "cfg"), 0o755)) + t.Setenv("CLAUDE_CONFIG_DIR", "cfg") + claude := agents.ByName("claude-code") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + claudePath := filepath.Join(work, "cfg", ".claude.json") + require.Contains(t, readJSONFile(t, claudePath)["mcpServers"], "genie_one_mcp-logfood") + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + require.Len(t, state.Servers, 1) + assert.True(t, filepath.IsAbs(state.Servers[0].Agents["claude-code"].Path), "recorded path: %s", state.Servers[0].Agents["claude-code"].Path) + + t.Chdir(t.TempDir()) + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood", "--output", "json") + require.NoError(t, err) + out := readRemoveOutput(t, stdout.String()) + require.Len(t, out.Removed, 1) + assert.Empty(t, out.Skipped) + assert.NotContains(t, readJSONFile(t, claudePath)["mcpServers"], "genie_one_mcp-logfood", "the entry is removed from the file it was written to") +} + +// TestMcpRemoveTakesEntryFromFileAgentNowReads checks that when the recorded file no longer holds the entry, because the +// user moved the file into the directory the agent now reads, the entry is removed from that file and the record goes. +// It is pruned only when neither file holds it. +func TestMcpRemoveTakesEntryFromFileAgentNowReads(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + claudePath := filepath.Join(home, ".claude.json") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + + moved := t.TempDir() + require.NoError(t, os.Rename(claudePath, filepath.Join(moved, ".claude.json"))) + t.Setenv("CLAUDE_CONFIG_DIR", moved) + + stdout, _, err := runMcpCmd(t, "remove", "--names", "genie_one_mcp-logfood", "--output", "json") + require.NoError(t, err) + + out := readRemoveOutput(t, stdout.String()) + require.Len(t, out.Removed, 1) + assert.Equal(t, []string{"claude-code"}, out.Removed[0].Agents) + assert.Empty(t, out.Skipped) + assert.NotContains(t, readJSONFile(t, filepath.Join(moved, ".claude.json"))["mcpServers"], "genie_one_mcp-logfood", "the entry is gone from the file the agent reads") + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Empty(t, state.Servers, "the record went with the entry") +} diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index 43696c8f3df..c2612e2b2c9 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -19,6 +19,7 @@ import ( "strings" "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/atomicfile" ) @@ -100,7 +101,7 @@ func Upsert(ctx context.Context, a *agents.Agent, name, cmd string, args []strin if !mcpconfig.IsDatabricksEntry(ours) { return "", "", fmt.Errorf("server %q: args must start with aitools mcp serve", name) } - path, err := spec.Path(ctx) + path, err := configPath(ctx, spec) if err != nil { return "", "", err } @@ -227,7 +228,18 @@ func Path(ctx context.Context, a *agents.Agent) (string, error) { if err != nil { return "", err } - return spec.Path(ctx) + return configPath(ctx, spec) +} + +// configPath returns the absolute path of the config file of spec. A config dir set to a relative path is made absolute +// here, not when the path is used, so that a record of the path works from any directory. The path is not cleaned, as +// mcp.AbsoluteAsWritten keeps it, so that a ".." after a symlink still resolves through the link. +func configPath(ctx context.Context, spec *mcpconfig.Spec) (string, error) { + path, err := spec.Path(ctx) + if err != nil { + return "", err + } + return mcp.AbsoluteAsWritten(path) } // checkName refuses a name that no agent would accept. Upsert and RemoveAt both From a63dd15e8559dc07f35f0bf43b5b02b513a94800 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 20:55:30 +0000 Subject: [PATCH 13/26] aitools mcp list: profile filter, login hint, warnings, and changed entries --profile reads the configs of the agents the profile's servers are recorded for, not every agent. Warnings come in agent-name order, not map order. A login hint for an unpinned server whose profile is missing names the file the entry is checked against when DATABRICKS_CONFIG_FILE names another file, since login writes there. A profile listing with no server still prints its warnings in text. Each server's JSON carries the host it was set up for (additive). A pinned profile group's header names its config file, so two groups of one profile and host are told apart. A changed entry (modified) gets a hint with the file and the way out. remove gives the same way out in its skipped reason. A profile named DEFAULT whose section has no keys is missing, not a section with no host. Co-authored-by: Isaac --- cmd/aitools/mcp_list.go | 74 +++++++++++++------ cmd/aitools/mcp_list_test.go | 128 ++++++++++++++++++++++++++++++++- cmd/aitools/mcp_remove.go | 9 ++- cmd/aitools/mcp_remove_test.go | 3 + libs/aitools/mcp/binding.go | 10 +-- libs/aitools/mcp/state.go | 5 ++ libs/aitools/mcp/state_test.go | 14 ++++ 7 files changed, 214 insertions(+), 29 deletions(-) diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index 289a2458d84..e1ac9922b69 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -16,6 +16,7 @@ import ( "github.com/databricks/cli/libs/aitools/mcp/agentconfig" "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/telemetry/protos" "github.com/spf13/cobra" ) @@ -65,8 +66,10 @@ type mcpListProfile struct { } type mcpListServer struct { - Name string `json:"name"` - Service string `json:"service"` + Name string `json:"name"` + Service string `json:"service"` + // Host is the host the server was set up for. The profile's host can differ after a change. + Host string `json:"host"` SignInRequired bool `json:"sign_in_required"` Status string `json:"status"` Agents []mcpListAgent `json:"agents"` @@ -147,11 +150,20 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error if err != nil { return out, err } - // The configs of the agents named in the state are read too, so that a record for an agent outside the - // registry is reported as unknown, not as a moved config. - names := mcpAgentNames() + var entries []mcp.Entry for _, e := range state.Servers { - for name := range e.Agents { + if profileName == "" || e.Profile == profileName { + entries = append(entries, e) + } + } + // Without --profile, the configs of every registry agent are read. The agents that the listed servers are recorded + // for are read too, so that a record for an agent outside the registry is reported as unknown, not as a moved config. + var names []string + if profileName == "" { + names = mcpAgentNames() + } + for _, e := range entries { + for _, name := range slices.Sorted(maps.Keys(e.Agents)) { if !slices.Contains(names, name) { names = append(names, name) } @@ -164,12 +176,6 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error } } - var entries []mcp.Entry - for _, e := range state.Servers { - if profileName == "" || e.Profile == profileName { - entries = append(entries, e) - } - } checks := mcp.CheckEntries(ctx, &mcp.State{Servers: entries}) groups := map[profileKey]*mcpListProfile{} for i, e := range entries { @@ -188,7 +194,7 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error if e.ConfigFile != "" { p.ConfigFile = filepath.ToSlash(path) } - s := mcpListServer{Name: e.Name, Service: e.Service, SignInRequired: e.SignInRequired, Status: statusOK, Agents: []mcpListAgent{}, entry: e} + s := mcpListServer{Name: e.Name, Service: e.Service, Host: e.Host, SignInRequired: e.SignInRequired, Status: statusOK, Agents: []mcpListAgent{}, entry: e} switch { case check.Err != nil: s.Status = statusUnknown @@ -367,9 +373,9 @@ func renderMcpList(ctx context.Context, out mcpListOutput, profileName string) { if len(out.Profiles) == 0 && len(out.Unmanaged) == 0 { if profileName != "" { cmdio.LogString(ctx, fmt.Sprintf("No Databricks MCP servers installed by this CLI on profile %s.", profileName)) - return + } else { + cmdio.LogString(ctx, "No Databricks MCP servers installed by this CLI.") } - cmdio.LogString(ctx, "No Databricks MCP servers installed by this CLI.") } for i, p := range out.Profiles { if i > 0 { @@ -378,9 +384,15 @@ func renderMcpList(ctx context.Context, out mcpListOutput, profileName string) { cmdio.LogString(ctx, profileHeader(p)) for _, s := range p.Servers { cmdio.LogString(ctx, fmt.Sprintf(" %-24s %-30s %s", s.Name, s.Service, listAgentsText(s.Agents))) - if hint := serverHint(p, s); hint != "" { + if hint := serverHint(ctx, p, s); hint != "" { cmdio.LogString(ctx, " "+hint) } + for _, a := range s.Agents { + if a.Status == agentStatusModified { + cmdio.LogString(ctx, fmt.Sprintf(" changed outside this CLI in %s: delete the entry from %s by hand and run `%s` again, or add the server again with --force", + agentDisplayName(a.Name), a.Path, mcp.RemoveNamesCommand(s.Name))) + } + } } } if len(out.Unmanaged) > 0 { @@ -405,12 +417,15 @@ func profileHeader(p mcpListProfile) string { } return fmt.Sprintf("Profile %s (%s %s)", p.Profile, problem, filepath.ToSlash(p.configPath)) } + if p.ConfigFile != "" { + return fmt.Sprintf("Profile %s (%s, config file %s)", p.Profile, p.Host, p.ConfigFile) + } return fmt.Sprintf("Profile %s (%s)", p.Profile, p.Host) } // serverHint tells the user how to repair a server whose profile no longer serves it. The remove command names the // server, so that the other servers of the profile are kept. -func serverHint(p mcpListProfile, s mcpListServer) string { +func serverHint(ctx context.Context, p mcpListProfile, s mcpListServer) string { if s.Status == statusUnknown { return "unchecked: see the warning below" } @@ -419,15 +434,30 @@ func serverHint(p mcpListProfile, s mcpListServer) string { } remove := mcp.RemoveNamesCommand(s.Name) if s.drift.Kind == mcp.DriftProfileMissing { - pinned := "" - if s.entry.ConfigFile != "" { - pinned = filepath.ToSlash(p.configPath) - } - return fmt.Sprintf("broken: run `%s` or `%s`", remove, mcp.RecreateCommand(s.entry.Host, p.Profile, pinned)) + return fmt.Sprintf("broken: run `%s` or `%s`", remove, mcp.RecreateCommand(s.entry.Host, p.Profile, loginFile(ctx, p, s.entry))) } return fmt.Sprintf("broken: %s; run `%s` and add it again", mcp.DriftMessage("it", s.entry, p.Profile, *s.drift), remove) } +// loginFile returns the config file that a login hint for a server with a missing profile must name, or "" when the +// login's default file is that file. A pinned server logs in to the file it is pinned to. An unpinned server is checked +// against ~/.databrickscfg, and login writes to the file DATABRICKS_CONFIG_FILE names, so the hint names the checked +// file when the environment names another one, or one that cannot be resolved. +func loginFile(ctx context.Context, p mcpListProfile, entry mcp.Entry) string { + if entry.ConfigFile != "" { + return filepath.ToSlash(p.configPath) + } + environment := env.Get(ctx, mcpconfig.ConfigFileEnv) + if environment == "" { + return "" + } + path, err := mcp.ResolveConfigFile(ctx, environment) + if err == nil && mcp.SamePath(path, p.configPath) { + return "" + } + return filepath.ToSlash(p.configPath) +} + func listAgentsText(agentList []mcpListAgent) string { parts := make([]string, 0, len(agentList)) for _, a := range agentList { diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index 5b86709573d..c46b2693dcf 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -410,7 +410,9 @@ token = t assert.Equal(t, "ok", logfood.Servers[0].Status) require.Len(t, logfood.Servers[0].Agents, 1) assert.Equal(t, agentStatusInstalled, logfood.Servers[0].Agents[0].Status) + assert.Equal(t, "https://adb-1.test", logfood.Servers[0].Host, "a server shows the host it was set up for") assert.Equal(t, "host_changed", logfood.Servers[1].Status, "github-logfood was recorded against the old host") + assert.Equal(t, "https://adb-old.test", logfood.Servers[1].Host, "the recorded host, not the profile's new one") require.Len(t, logfood.Servers[1].Agents, 1) assert.Equal(t, agentStatusInstalled, logfood.Servers[1].Agents[0].Status) @@ -490,7 +492,7 @@ func TestRenderMcpListNamesTheFileAndTheRepair(t *testing.T) { text := stderr.String() shownPath := filepath.ToSlash(pinnedPath) - assert.Contains(t, text, "Profile logfood (https://adb-1.test)") + assert.Contains(t, text, "Profile logfood (https://adb-1.test, config file "+shownPath+")") assert.Contains(t, text, "broken: it was set up for workspace 111, but profile \"logfood\" now points at workspace 222; run `databricks aitools mcp remove --names genie_one_mcp-logfood` and add it again") assert.Contains(t, text, "broken: it was set up for workspace 111, but profile \"logfood\" now points at workspace 222; run `databricks aitools mcp remove --names genie_one_mcp-query` and add it again") assert.Contains(t, text, "broken: it was set up for https://adb-old.test, but profile \"logfood\" now points at https://adb-1.test; run `databricks aitools mcp remove --names github-moved` and add it again") @@ -584,3 +586,127 @@ func TestBuildMcpListWarnsOnceForUnresolvableConfigFile(t *testing.T) { assert.Equal(t, statusUnknown, out.Profiles[0].Servers[0].Status) assert.Equal(t, statusUnknown, out.Profiles[0].Servers[0].Agents[0].Status) } + +// TestRenderMcpListLoginHintNamesCheckedFile checks the login hint of an unpinned server whose profile is missing from +// ~/.databrickscfg. The entry is checked against that file, so the hint names it when DATABRICKS_CONFIG_FILE names +// another file: login would otherwise write the profile to the environment's file. +func TestRenderMcpListLoginHintNamesCheckedFile(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "") + claude := agents.ByName("claude-code") + checked, err := mcp.ResolveConfigFile(t.Context(), "") + require.NoError(t, err) + shownChecked := filepath.ToSlash(checked) + saveState(t, seedInstallEntry(t, claude, seed{"github-logfood", "system.ai.github", "logfood", "https://adb-1.test", testDatabricksCommand, ""})) + + cases := []struct { + name, environment, login string + }{ + { + name: "environment names another file", + environment: filepath.Join(t.TempDir(), "other.cfg"), + login: "`DATABRICKS_CONFIG_FILE=" + shownChecked + " databricks auth login --host https://adb-1.test --profile logfood`", + }, + { + name: "environment names no file", + environment: "", + login: "`databricks auth login --host https://adb-1.test --profile logfood`", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("DATABRICKS_CONFIG_FILE", tc.environment) + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + renderMcpList(ctx, out, "") + assert.Contains(t, stderr.String(), "or "+tc.login) + }) + } +} + +// TestRenderMcpListPrintsWarningsWhenEmpty checks that a listing with no server and no unmanaged entry still prints its +// warnings in text, as JSON does, for a profile with no server and for no profile. +func TestRenderMcpListPrintsWarningsWhenEmpty(t *testing.T) { + warning := "could not read the Codex CLI config: broken" + for _, profileName := range []string{"typo", ""} { + out := mcpListOutput{Profiles: []mcpListProfile{}, Unmanaged: []mcpListUnmanaged{}, Warnings: []string{warning}} + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + renderMcpList(ctx, out, profileName) + assert.Contains(t, stderr.String(), "Warning: "+warning, "profile %q", profileName) + } +} + +// TestBuildMcpListWithProfileReadsOnlyItsAgents checks that --profile reads the configs of the agents the profile's +// servers are recorded for, so a broken config of an agent that the profile does not use is not warned about. +func TestBuildMcpListWithProfileReadsOnlyItsAgents(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + require.NoError(t, os.MkdirAll(filepath.Join(home, ".codex"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".codex", "config.toml"), []byte("[mcp_servers.broken\n"), 0o600)) + saveState(t, seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test")) + + out, err := buildMcpList(t.Context(), "logfood") + require.NoError(t, err) + assert.Empty(t, out.Warnings, "codex is not used by logfood, so its config is not read") + require.Len(t, out.Profiles, 1) + + all, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + require.Len(t, all.Warnings, 1) + assert.Contains(t, all.Warnings[0], "Codex CLI") +} + +// TestBuildMcpListWarnsInStableOrderForUnknownAgents checks that the warnings for two records of agents outside the +// registry come in name order, not in the order a map yields them. The map is iterated many times, so an unstable +// order would show. +func TestBuildMcpListWarnsInStableOrderForUnknownAgents(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "") + for range 20 { + saveState(t, mcp.Entry{ + Name: "genie_one_mcp-logfood", Service: "system.ai.genie_one_mcp", Profile: "logfood", Host: "https://adb-1.test", + Command: testDatabricksCommand, Agents: map[string]mcp.AgentRecord{ + "zeta-agent": {Path: "/x/zeta.json", Scope: "user"}, + "alpha-agent": {Path: "/x/alpha.json", Scope: "user"}, + }, + }) + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + require.Len(t, out.Warnings, 2) + assert.Equal(t, "could not read the alpha-agent config: alpha-agent is not a known agent", out.Warnings[0]) + assert.Equal(t, "could not read the zeta-agent config: zeta-agent is not a known agent", out.Warnings[1]) + } +} + +// TestRenderMcpListSaysHowToClearChangedEntry checks that a server with an entry changed outside this CLI says in list how +// to get it out, the same way remove says it. +func TestRenderMcpListSaysHowToClearChangedEntry(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + claudePath := filepath.Join(home, ".claude.json") + repointEntry(t, claudePath, entry.Name, "/usr/bin/other") + + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + renderMcpList(ctx, out, "") + assert.Contains(t, stderr.String(), " changed outside this CLI in Claude Code: delete the entry from "+filepath.ToSlash(claudePath)+ + " by hand and run `databricks aitools mcp remove --names genie_one_mcp-logfood` again, or add the server again with --force\n") +} + +// TestProfileHeaderNamesPinnedConfigFile checks that two groups of one profile and host, in different config files, have +// different headers: a pinned group names its file. +func TestProfileHeaderNamesPinnedConfigFile(t *testing.T) { + first := mcpListProfile{Profile: "logfood", Host: "https://adb-1.test", ConfigFile: "/cfg/first.cfg", Status: statusOK} + second := mcpListProfile{Profile: "logfood", Host: "https://adb-1.test", ConfigFile: "/cfg/second.cfg", Status: statusOK} + unpinned := mcpListProfile{Profile: "logfood", Host: "https://adb-1.test", Status: statusOK} + + assert.Equal(t, "Profile logfood (https://adb-1.test, config file /cfg/first.cfg)", profileHeader(first)) + assert.NotEqual(t, profileHeader(first), profileHeader(second)) + assert.Equal(t, "Profile logfood (https://adb-1.test)", profileHeader(unpinned)) +} diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 8d3be56357b..8a5905e9f17 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "maps" + "path/filepath" "slices" "strings" @@ -375,6 +376,12 @@ func entryFile(ctx context.Context, e mcp.Entry, a *agents.Agent, recorded strin return current, cachedRecordedFile(files, a, current), nil } +// keptReason says why an entry is left in place, and how to get it out: by hand, or by adding the server again with --force. +func keptReason(e mcp.Entry, a *agents.Agent, path string) string { + return fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place. To remove it, delete the entry from %s by hand and run remove again, or add the server again with --force", + agentDisplayName(a.Name), e.Name, filepath.ToSlash(path)) +} + // removeAgentEntry removes the server from the config file at path, but only when the entry there is the one this CLI // wrote. A file that has no entry of the name is pruned: the record goes without an edit. func removeAgentEntry(ctx context.Context, e mcp.Entry, a *agents.Agent, path string, file recordedFile) (removeOutcome, string, error) { @@ -390,7 +397,7 @@ func removeAgentEntry(ctx context.Context, e mcp.Entry, a *agents.Agent, path st return 0, "", err } if !owned { - return removeKept, fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place", agentDisplayName(a.Name), e.Name), nil + return removeKept, keptReason(e, a, path), nil } if _, err := agentconfig.RemoveAt(a, path, e.Name); err != nil { return 0, "", err diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index d6ee1064ffa..09c3f5c5dbd 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -196,6 +196,9 @@ func TestMcpRemoveSkipsEntryChangedOutsideCLI(t *testing.T) { require.Len(t, out.Skipped, 1) assert.Equal(t, "genie_one_mcp-logfood", out.Skipped[0].Name) assert.Equal(t, "claude-code", out.Skipped[0].Agent) + assert.Equal(t, "Claude Code has an entry named genie_one_mcp-logfood that was changed outside this CLI; left in place. "+ + "To remove it, delete the entry from "+filepath.ToSlash(claudePath)+" by hand and run remove again, "+ + "or add the server again with --force", out.Skipped[0].Reason) after, err := os.ReadFile(claudePath) require.NoError(t, err) diff --git a/libs/aitools/mcp/binding.go b/libs/aitools/mcp/binding.go index 8b628b9be9e..20f68088306 100644 --- a/libs/aitools/mcp/binding.go +++ b/libs/aitools/mcp/binding.go @@ -187,12 +187,12 @@ func RemoveNamesCommand(name string) string { return mcpRemoveCommand + " --names " + shellquote.BashArg(name) } -// RecreateCommand returns the command that logs in to host for profileName again. A server pinned to a config file -// passes that file as pinnedPath, so the login writes to the file the server reads; pass "" for an unpinned server. -func RecreateCommand(host, profileName, pinnedPath string) string { +// RecreateCommand returns the command that logs in to host for profileName again. configFile is the file the login must +// write, passed as DATABRICKS_CONFIG_FILE; pass "" when the login's default file is that file. +func RecreateCommand(host, profileName, configFile string) string { command := authLoginCommand + " --host " + shellquote.BashArg(host) + " --profile " + shellquote.BashArg(profileName) - if pinnedPath != "" { - command = "DATABRICKS_CONFIG_FILE=" + shellquote.BashArg(pinnedPath) + " " + command + if configFile != "" { + command = "DATABRICKS_CONFIG_FILE=" + shellquote.BashArg(configFile) + " " + command } return command } diff --git a/libs/aitools/mcp/state.go b/libs/aitools/mcp/state.go index 30e444cd085..fc06480bcd7 100644 --- a/libs/aitools/mcp/state.go +++ b/libs/aitools/mcp/state.go @@ -10,6 +10,7 @@ import ( "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/databrickscfg/profile" "github.com/databricks/databricks-sdk-go/config" + "gopkg.in/ini.v1" ) // Drift kinds reported by CheckEntries. @@ -149,6 +150,10 @@ func (c configFiles) profile(path, name string) (profile.Profile, error) { return profile.Profile{}, errProfileMissing } keys := section.KeysHash() + if len(keys) == 0 && name == ini.DefaultSection { + // The INI parser always has a DEFAULT section, so an empty one means the file has no such profile. + return profile.Profile{}, errProfileMissing + } if keys["host"] == "" { return profile.Profile{}, errProfileNoHost } diff --git a/libs/aitools/mcp/state_test.go b/libs/aitools/mcp/state_test.go index 6b6b87e71d0..d6881dd754f 100644 --- a/libs/aitools/mcp/state_test.go +++ b/libs/aitools/mcp/state_test.go @@ -385,3 +385,17 @@ func TestCheckEntriesKeepsEachResultOnItsEntry(t *testing.T) { require.NotNil(t, checks[2].Drift) assert.Equal(t, mcp.DriftHostChanged, checks[2].Drift.Kind) } + +// TestCheckEntriesDefaultSectionWithoutKeysIsMissing checks that a profile named DEFAULT is missing when the file has no +// [DEFAULT] keys. The INI parser always has a DEFAULT section, so an empty one is not a section with no host. +func TestCheckEntriesDefaultSectionWithoutKeysIsMissing(t *testing.T) { + ctx, _ := stateTestCtx(t) + path := bindingTestWriteConfig(t, "[logfood]\nhost = https://adb-1.test\n") + entry := stateTestEntry() + entry.Profile = "DEFAULT" + entry.ConfigFile = path + + drifts, err := driftsOf(mcp.CheckEntries(ctx, &mcp.State{Servers: []mcp.Entry{entry}})) + require.NoError(t, err) + assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry}}, drifts) +} From 5e53303f813fb23cb01c80b0f611f264d8560645 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 20:56:50 +0000 Subject: [PATCH 14/26] aitools mcp: doc comments for list and remove helpers, scenario title Doc comments for readAgentConfig, renderMcpList, profileHeader, listAgentsText, unmanagedKindText, printRemoveResults and readRecordedFile. The repair-and-warnings scenario title named Claude Code, which that step does not list; it now names Codex CLI. Goldens updated: pinned profile headers name the config file, list JSON servers carry host, and the new modified hint and remove reason. Co-authored-by: Isaac --- .../mcp/drift-profile-missing/output.txt | 6 +++-- .../aitools/mcp/list-and-remove/output.txt | 22 ++++++++++++------- .../mcp/repair-and-warnings/output.txt | 8 +++---- .../aitools/mcp/repair-and-warnings/script | 2 +- cmd/aitools/mcp_list.go | 8 +++++++ cmd/aitools/mcp_remove.go | 1 + 6 files changed, 32 insertions(+), 15 deletions(-) diff --git a/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt b/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt index 0c4cbc28695..7746d060f10 100644 --- a/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt +++ b/acceptance/cmd/aitools/mcp/drift-profile-missing/output.txt @@ -18,7 +18,7 @@ genie_one_mcp-dogfood system.ai.genie_one_mcp === logfood is deleted from the Databricks config file: list reports it and exits 0 >>> [CLI] aitools mcp list -Profile dogfood ([DATABRICKS_URL]) +Profile dogfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code Profile logfood (profile not found in [TEST_TMP_DIR]/.databrickscfg) @@ -39,6 +39,7 @@ Profile logfood (profile not found in [TEST_TMP_DIR]/.databrickscfg) { "name": "genie_one_mcp-dogfood", "service": "system.ai.genie_one_mcp", + "host": "[DATABRICKS_URL]", "sign_in_required": false, "status": "host_changed", "agents": [ @@ -60,6 +61,7 @@ Profile logfood (profile not found in [TEST_TMP_DIR]/.databrickscfg) { "name": "genie_one_mcp-logfood", "service": "system.ai.genie_one_mcp", + "host": "[DATABRICKS_URL]", "sign_in_required": false, "status": "profile_missing", "agents": [ @@ -80,7 +82,7 @@ Profile logfood (profile not found in [TEST_TMP_DIR]/.databrickscfg) === The same change in text >>> [CLI] aitools mcp list -Profile dogfood (https://adb-2.test) +Profile dogfood (https://adb-2.test, config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code broken: it was set up for [DATABRICKS_URL], but profile "dogfood" now points at https://adb-2.test; run `databricks aitools mcp remove --names genie_one_mcp-dogfood` and add it again diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt index 01167751da7..248be55bb3e 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt +++ b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt @@ -22,10 +22,10 @@ genie_one_mcp-dogfood system.ai.genie_one_mcp === list groups the servers by profile >>> [CLI] aitools mcp list -Profile dogfood ([DATABRICKS_URL]) +Profile dogfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-dogfood system.ai.genie_one_mcp Claude Code -Profile logfood ([DATABRICKS_URL]) +Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code github-logfood system.ai.github Claude Code @@ -43,6 +43,7 @@ Profile logfood ([DATABRICKS_URL]) { "name": "genie_one_mcp-dogfood", "service": "system.ai.genie_one_mcp", + "host": "[DATABRICKS_URL]", "sign_in_required": false, "status": "ok", "agents": [ @@ -64,6 +65,7 @@ Profile logfood ([DATABRICKS_URL]) { "name": "genie_one_mcp-logfood", "service": "system.ai.genie_one_mcp", + "host": "[DATABRICKS_URL]", "sign_in_required": false, "status": "ok", "agents": [ @@ -77,6 +79,7 @@ Profile logfood ([DATABRICKS_URL]) { "name": "github-logfood", "service": "system.ai.github", + "host": "[DATABRICKS_URL]", "sign_in_required": true, "status": "ok", "agents": [ @@ -100,16 +103,17 @@ Profile logfood ([DATABRICKS_URL]) Removed genie_one_mcp-dogfood system.ai.genie_one_mcp profile dogfood (Claude Code) >>> [CLI] aitools mcp list -Profile logfood ([DATABRICKS_URL]) +Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code github-logfood system.ai.github Claude Code === A hand-edited entry is listed as modified; an unmanaged ug entry is listed and never changed >>> [CLI] aitools mcp list -Profile logfood ([DATABRICKS_URL]) +Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code github-logfood system.ai.github Claude Code (modified) + changed outside this CLI in Claude Code: delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run `databricks aitools mcp remove --names github-logfood` again, or add the server again with --force Unmanaged Databricks MCP entries (not changed by this command): Claude Code web_search ug mcp-proxy @@ -117,15 +121,16 @@ Unmanaged Databricks MCP entries (not changed by this command): === --profile lists that profile only, without the unmanaged entries >>> [CLI] aitools mcp list --profile logfood -Profile logfood ([DATABRICKS_URL]) +Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code github-logfood system.ai.github Claude Code (modified) + changed outside this CLI in Claude Code: delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run `databricks aitools mcp remove --names github-logfood` again, or add the server again with --force === remove leaves the modified entry in place and says why >>> [CLI] aitools mcp remove --names github-logfood,genie_one_mcp-logfood Removed genie_one_mcp-logfood system.ai.genie_one_mcp profile logfood (Claude Code) -Skipped github-logfood: Claude Code has an entry named github-logfood that was changed outside this CLI; left in place +Skipped github-logfood: Claude Code has an entry named github-logfood that was changed outside this CLI; left in place. To remove it, delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run remove again, or add the server again with --force >>> jq .mcpServers | keys home/.claude.json [ @@ -153,7 +158,7 @@ Skipped github-logfood: Claude Code has an entry named github-logfood that was c { "name": "github-logfood", "agent": "claude-code", - "reason": "Claude Code has an entry named github-logfood that was changed outside this CLI; left in place" + "reason": "Claude Code has an entry named github-logfood that was changed outside this CLI; left in place. To remove it, delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run remove again, or add the server again with --force" } ] } @@ -165,8 +170,9 @@ Skipped github-logfood: Claude Code has an entry named github-logfood that was c ] >>> [CLI] aitools mcp list -Profile logfood ([DATABRICKS_URL]) +Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) github-logfood system.ai.github Claude Code (modified) + changed outside this CLI in Claude Code: delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run `databricks aitools mcp remove --names github-logfood` again, or add the server again with --force Unmanaged Databricks MCP entries (not changed by this command): Claude Code web_search ug mcp-proxy diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt index 78d015dc511..8c672232552 100644 --- a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt @@ -12,7 +12,7 @@ genie_one_mcp-logfood system.ai.genie_one_mcp === Claude Code reads its config from another directory: list says path changed, and remove takes the entry out of the file it was written to >>> [CLI] aitools mcp list -Profile logfood ([DATABRICKS_URL]) +Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Claude Code (path changed), Codex CLI >>> [CLI] aitools mcp remove --names genie_one_mcp-logfood --agents claude-code @@ -21,10 +21,10 @@ Removed genie_one_mcp-logfood system.ai.genie_one_mcp profile logfood (Claude >>> jq .mcpServers | keys home/.claude.json [] -=== A Codex config that cannot be parsed is a warning: list exits 0 and shows Claude Code +=== A Codex config that cannot be parsed is a warning: list exits 0 and shows Codex CLI as unknown >>> [CLI] aitools mcp list -Profile logfood ([DATABRICKS_URL]) +Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Codex CLI (unknown) Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 2: expected '.' or ']' to end table name, but got '\n' instead @@ -33,7 +33,7 @@ Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config. >>> jq .mcpServers.orphan = {"command": "databricks", "args": ["aitools", "mcp", "serve", "--profile", "logfood", "--service", "system.ai.genie_one_mcp", "--agent", "claude-code"]} home/.claude.json >>> [CLI] aitools mcp list -Profile logfood ([DATABRICKS_URL]) +Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Codex CLI (unknown) Unmanaged Databricks MCP entries (not changed by this command): diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/script b/acceptance/cmd/aitools/mcp/repair-and-warnings/script index b84f5045248..9880e55b4fd 100644 --- a/acceptance/cmd/aitools/mcp/repair-and-warnings/script +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/script @@ -16,7 +16,7 @@ trace $CLI aitools mcp remove --names genie_one_mcp-logfood --agents claude-code unset CLAUDE_CONFIG_DIR trace jq '.mcpServers | keys' home/.claude.json -title "A Codex config that cannot be parsed is a warning: list exits 0 and shows Claude Code" +title "A Codex config that cannot be parsed is a warning: list exits 0 and shows Codex CLI as unknown" cp broken-codex-config.toml home/.codex/config.toml trace $CLI aitools mcp list diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index e1ac9922b69..8d8497f6a1b 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -285,6 +285,8 @@ func readAgentConfigs(ctx context.Context, names []string) map[string]agentConfi return configs } +// readAgentConfig reads the MCP config of the agent named name. A failure is kept in the result, not returned, so that +// the caller can report it for that agent and go on with the others. func readAgentConfig(ctx context.Context, name string) agentConfig { a := agents.ByName(name) if a == nil { @@ -369,6 +371,8 @@ func mcpAgentList(names []string) string { return strings.Join(display, ", ") } +// renderMcpList writes the text listing: the profiles, the unmanaged entries, then the warnings. profileName is the +// --profile value, which only changes the message for an empty listing. func renderMcpList(ctx context.Context, out mcpListOutput, profileName string) { if len(out.Profiles) == 0 && len(out.Unmanaged) == 0 { if profileName != "" { @@ -409,6 +413,8 @@ func renderMcpList(ctx context.Context, out mcpListOutput, profileName string) { } } +// profileHeader names a profile group: its host, or the config file it was not found in when the profile is missing. +// A pinned group also names its config file, so that groups of one profile and host are told apart. func profileHeader(p mcpListProfile) string { if p.Status == string(mcp.DriftProfileMissing) { problem := "profile not found in" @@ -458,6 +464,7 @@ func loginFile(ctx context.Context, p mcpListProfile, entry mcp.Entry) string { return filepath.ToSlash(p.configPath) } +// listAgentsText lists the agents of a server, with the status of each entry that needs a word. func listAgentsText(agentList []mcpListAgent) string { parts := make([]string, 0, len(agentList)) for _, a := range agentList { @@ -477,6 +484,7 @@ func listAgentsText(agentList []mcpListAgent) string { return strings.Join(parts, ", ") } +// unmanagedKindText describes an unmanaged entry kind for the text listing. func unmanagedKindText(kind string) string { switch kind { case unmanagedKindUGProxy: diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 8a5905e9f17..e4885b17653 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -434,6 +434,7 @@ func dropRecords(ctx context.Context, drops []recordDrop, selected []mcp.Entry) return saveMCPState(ctx, state) } +// printRemoveResults writes the text result: each removed server, then each skipped entry with its reason. func printRemoveResults(ctx context.Context, out *removeOutput) { if len(out.Removed) == 0 && len(out.Skipped) == 0 { cmdio.LogString(ctx, "No Databricks MCP servers to remove.") From 03c084387ca90ca0d923e91d35a6e34b6841c2d5 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 20:58:20 +0000 Subject: [PATCH 15/26] aitools mcp remove: return the recorded file's read error from entryFile Behavior is the same: an unreadable recorded file is still reported for its agent, as could not update. golangci-lint nilerr flagged the nil return on that branch. Co-authored-by: Isaac --- cmd/aitools/mcp_remove.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index e4885b17653..0ca50c58dc4 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -360,10 +360,13 @@ func cachedRecordedFile(files map[recordedFileKey]recordedFile, a *agents.Agent, // entryFile returns the config file that holds the server's entry for the agent, and its contents. That is the file the // record names, unless the file does not hold the entry and the agent now reads its config from another file: then that // file, which may hold it, since the user may have moved the config with the agent's directory. A recorded file that -// cannot be read is returned as it is, so the error is reported for it. +// cannot be read is an error, since it may be the one that holds the entry. func entryFile(ctx context.Context, e mcp.Entry, a *agents.Agent, recorded string, files map[recordedFileKey]recordedFile) (string, recordedFile, error) { file := cachedRecordedFile(files, a, recorded) - if _, found := file.entries[e.Name]; found || file.err != nil { + if file.err != nil { + return "", recordedFile{}, file.err + } + if _, found := file.entries[e.Name]; found { return recorded, file, nil } current, err := agentconfig.Path(ctx, a) From 2e7b747bc8c212f6d27a6fdda4603d24973fe0b2 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:02:23 +0000 Subject: [PATCH 16/26] Use a broken Codex config whose parse error ignores line endings Git checks the fixture out with CRLF on Windows, where the old content failed on the '\r' instead of the '\n' and the golden differed. The new content fails on a character inside the line. Co-authored-by: Isaac --- .../aitools/mcp/repair-and-warnings/broken-codex-config.toml | 2 +- acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/broken-codex-config.toml b/acceptance/cmd/aitools/mcp/repair-and-warnings/broken-codex-config.toml index 1d88ef25b79..88e1fe9610b 100644 --- a/acceptance/cmd/aitools/mcp/repair-and-warnings/broken-codex-config.toml +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/broken-codex-config.toml @@ -1 +1 @@ -[mcp_servers.broken +[mcp_servers.broken]] diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt index 8c672232552..b57da8bcbf0 100644 --- a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt @@ -26,7 +26,7 @@ Removed genie_one_mcp-logfood system.ai.genie_one_mcp profile logfood (Claude >>> [CLI] aitools mcp list Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) genie_one_mcp-logfood system.ai.genie_one_mcp Codex CLI (unknown) -Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 2: expected '.' or ']' to end table name, but got '\n' instead +Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 1 (last key "mcp_servers.broken"): expected a top-level item to end with a newline, comment, or EOF, but got ']' instead === An entry that runs aitools mcp serve without an install record is unmanaged, and remove does not touch it @@ -38,7 +38,7 @@ Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) Unmanaged Databricks MCP entries (not changed by this command): Claude Code orphan databricks aitools mcp serve, no install record -Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 2: expected '.' or ']' to end table name, but got '\n' instead +Warning: could not read the Codex CLI config: [TEST_TMP_DIR]/home/.codex/config.toml: agent config file cannot be parsed: toml: line 1 (last key "mcp_servers.broken"): expected a top-level item to end with a newline, comment, or EOF, but got ']' instead >>> musterr [CLI] aitools mcp remove --names orphan Error: no installed MCP server named orphan From 54c3a825fdace50022f227496dde471a06eb08da Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:20:59 +0000 Subject: [PATCH 17/26] aitools mcp: move AbsoluteAsWritten to mcpconfig agentconfig imported libs/aitools/mcp (the installer, databrickscfg and the SDK) only for this helper, which reversed the layering. mcpconfig is below both packages, so the helper moves there. No behavior change. Co-authored-by: Isaac --- cmd/aitools/mcp_binary.go | 4 ++-- libs/aitools/mcp/agentconfig/writer.go | 5 ++--- libs/aitools/mcp/configfile.go | 19 ++----------------- libs/aitools/mcpconfig/abspath.go | 22 ++++++++++++++++++++++ libs/aitools/mcpconfig/abspath_test.go | 26 ++++++++++++++++++++++++++ 5 files changed, 54 insertions(+), 22 deletions(-) create mode 100644 libs/aitools/mcpconfig/abspath.go create mode 100644 libs/aitools/mcpconfig/abspath_test.go diff --git a/cmd/aitools/mcp_binary.go b/cmd/aitools/mcp_binary.go index 1b5f2659d6a..a92497c60ac 100644 --- a/cmd/aitools/mcp_binary.go +++ b/cmd/aitools/mcp_binary.go @@ -6,7 +6,7 @@ import ( "path/filepath" "strings" - "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/aitools/mcpconfig" ) // binaryArg0 is the name the CLI was started with. It is a variable so that tests can set it. @@ -28,7 +28,7 @@ func binaryPathFor(arg0 string, lookPath func(string) (string, error)) (string, } if filepath.Base(arg0) != arg0 { // A leading "./" names the working directory, which the join already gives. - abs, err := mcp.AbsoluteAsWritten(strings.TrimPrefix(arg0, "."+string(filepath.Separator))) + abs, err := mcpconfig.AbsoluteAsWritten(strings.TrimPrefix(arg0, "."+string(filepath.Separator))) if err != nil { return arg0, false } diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index c2612e2b2c9..f41ae7187df 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -19,7 +19,6 @@ import ( "strings" "github.com/databricks/cli/libs/aitools/agents" - "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/atomicfile" ) @@ -233,13 +232,13 @@ func Path(ctx context.Context, a *agents.Agent) (string, error) { // configPath returns the absolute path of the config file of spec. A config dir set to a relative path is made absolute // here, not when the path is used, so that a record of the path works from any directory. The path is not cleaned, as -// mcp.AbsoluteAsWritten keeps it, so that a ".." after a symlink still resolves through the link. +// mcpconfig.AbsoluteAsWritten keeps it, so that a ".." after a symlink still resolves through the link. func configPath(ctx context.Context, spec *mcpconfig.Spec) (string, error) { path, err := spec.Path(ctx) if err != nil { return "", err } - return mcp.AbsoluteAsWritten(path) + return mcpconfig.AbsoluteAsWritten(path) } // checkName refuses a name that no agent would accept. Upsert and RemoveAt both diff --git a/libs/aitools/mcp/configfile.go b/libs/aitools/mcp/configfile.go index 3d85e58dc6a..428b7ad78c1 100644 --- a/libs/aitools/mcp/configfile.go +++ b/libs/aitools/mcp/configfile.go @@ -3,11 +3,11 @@ package mcp import ( "context" "errors" - "fmt" "io/fs" "os" "path/filepath" + "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/databrickscfg" ) @@ -26,27 +26,12 @@ func ResolveConfigFile(ctx context.Context, name string) (string, error) { case err == nil: return filepath.Abs(resolved) case errors.Is(err, fs.ErrNotExist): - return AbsoluteAsWritten(path) + return mcpconfig.AbsoluteAsWritten(path) default: return "", err } } -// AbsoluteAsWritten makes path absolute by joining it to the working directory, without cleaning it, so that a -// ".." after a symlink still resolves through the link's target. Slashes become the OS separator, as cleaning would -// make them: "~/.databrickscfg" expands to the home directory joined with "/" on Windows too. -func AbsoluteAsWritten(path string) (string, error) { - path = filepath.FromSlash(path) - if filepath.IsAbs(path) { - return path, nil - } - wd, err := os.Getwd() - if err != nil { - return "", fmt.Errorf("failed to determine working directory: %w", err) - } - return wd + string(filepath.Separator) + path, nil -} - // SamePath reports whether two resolved config file paths name the same file. Existing files are // compared by identity, which also matches hard links and case variants on case-insensitive file // systems. Paths that do not exist are compared as text. diff --git a/libs/aitools/mcpconfig/abspath.go b/libs/aitools/mcpconfig/abspath.go new file mode 100644 index 00000000000..965f929849b --- /dev/null +++ b/libs/aitools/mcpconfig/abspath.go @@ -0,0 +1,22 @@ +package mcpconfig + +import ( + "fmt" + "os" + "path/filepath" +) + +// AbsoluteAsWritten makes path absolute by joining it to the working directory, without cleaning it, so that a +// ".." after a symlink still resolves through the link's target. Slashes become the OS separator, as cleaning would +// make them: "~/.databrickscfg" expands to the home directory joined with "/" on Windows too. +func AbsoluteAsWritten(path string) (string, error) { + path = filepath.FromSlash(path) + if filepath.IsAbs(path) { + return path, nil + } + wd, err := os.Getwd() + if err != nil { + return "", fmt.Errorf("failed to determine working directory: %w", err) + } + return wd + string(filepath.Separator) + path, nil +} diff --git a/libs/aitools/mcpconfig/abspath_test.go b/libs/aitools/mcpconfig/abspath_test.go new file mode 100644 index 00000000000..45e2426a9ee --- /dev/null +++ b/libs/aitools/mcpconfig/abspath_test.go @@ -0,0 +1,26 @@ +package mcpconfig + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAbsoluteAsWrittenKeepsAbsolutePaths(t *testing.T) { + abs := filepath.Join(t.TempDir(), "config.json") + got, err := AbsoluteAsWritten(abs) + require.NoError(t, err) + assert.Equal(t, abs, got) +} + +func TestAbsoluteAsWrittenJoinsRelativePathToWorkingDirectory(t *testing.T) { + wd, err := os.Getwd() + require.NoError(t, err) + got, err := AbsoluteAsWritten("cfg/../.claude.json") + require.NoError(t, err) + // Not cleaned: the ".." stays, so that it resolves through a symlink as the OS does. + assert.Equal(t, wd+string(filepath.Separator)+filepath.FromSlash("cfg/../.claude.json"), got) +} From c8a2c7ce356469134bae96754d721cb18de9f2ea Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:21:31 +0000 Subject: [PATCH 18/26] aitools mcp: a root-relative config path keeps the working directory's volume On Windows, a path such as \claude is not absolute, so AbsoluteAsWritten joined it to the whole working directory: CLAUDE_CONFIG_DIR=\claude recorded and wrote C:\work\claude\.claude.json instead of C:\claude\.claude.json. The path now takes the working directory's volume. The table test expects the volume through filepath only, and fails on Linux with the old join too ("C:/work/project//claude"). Co-authored-by: Isaac --- libs/aitools/mcpconfig/abspath.go | 12 ++++++++++- libs/aitools/mcpconfig/abspath_test.go | 28 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/libs/aitools/mcpconfig/abspath.go b/libs/aitools/mcpconfig/abspath.go index 965f929849b..975520d897e 100644 --- a/libs/aitools/mcpconfig/abspath.go +++ b/libs/aitools/mcpconfig/abspath.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "strings" ) // AbsoluteAsWritten makes path absolute by joining it to the working directory, without cleaning it, so that a @@ -18,5 +19,14 @@ func AbsoluteAsWritten(path string) (string, error) { if err != nil { return "", fmt.Errorf("failed to determine working directory: %w", err) } - return wd + string(filepath.Separator) + path, nil + return joinWorkingDir(path, wd), nil +} + +// joinWorkingDir joins a relative path to wd. A root-relative path, one that starts with a separator but has no volume +// (such as "\claude" on Windows), is on the volume of wd, so it is joined to that volume, not to the whole directory. +func joinWorkingDir(path, wd string) string { + if strings.HasPrefix(path, string(filepath.Separator)) { + return filepath.VolumeName(wd) + path + } + return wd + string(filepath.Separator) + path } diff --git a/libs/aitools/mcpconfig/abspath_test.go b/libs/aitools/mcpconfig/abspath_test.go index 45e2426a9ee..265199f995c 100644 --- a/libs/aitools/mcpconfig/abspath_test.go +++ b/libs/aitools/mcpconfig/abspath_test.go @@ -24,3 +24,31 @@ func TestAbsoluteAsWrittenJoinsRelativePathToWorkingDirectory(t *testing.T) { // Not cleaned: the ".." stays, so that it resolves through a symlink as the OS does. assert.Equal(t, wd+string(filepath.Separator)+filepath.FromSlash("cfg/../.claude.json"), got) } + +// TestJoinWorkingDirKeepsTheVolumeOfRootRelativePaths checks a path that starts with a separator but has no volume, such as +// "\claude" on Windows. It is on the working directory's volume, not under the whole directory. The expectations use +// filepath only, so the table means the same on every OS. +func TestJoinWorkingDirKeepsTheVolumeOfRootRelativePaths(t *testing.T) { + wd := filepath.FromSlash("C:/work/project") + cases := []struct { + name string + path string + want string + }{ + { + name: "relative path joins the working directory", + path: "cfg/../.claude.json", + want: wd + string(filepath.Separator) + filepath.FromSlash("cfg/../.claude.json"), + }, + { + name: "root-relative path takes the working directory's volume", + path: "/claude", + want: filepath.VolumeName(wd) + filepath.FromSlash("/claude"), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, joinWorkingDir(filepath.FromSlash(tc.path), wd)) + }) + } +} From 4c070e333713c7bcdc1599d53e54178237e3b10d Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:22:06 +0000 Subject: [PATCH 19/26] aitools mcp agentconfig: drop Read and Remove, which had no production caller The commands use Path with ReadAt and RemoveAt, which take the file a record names. The agentconfig tests call the same pair through a small helper. No behavior change. Co-authored-by: Isaac --- libs/aitools/mcp/agentconfig/toml_test.go | 20 +++---- libs/aitools/mcp/agentconfig/writer.go | 30 +++-------- libs/aitools/mcp/agentconfig/writer_test.go | 60 +++++++++++++-------- 3 files changed, 55 insertions(+), 55 deletions(-) diff --git a/libs/aitools/mcp/agentconfig/toml_test.go b/libs/aitools/mcp/agentconfig/toml_test.go index 96e720a244a..c2aa6157f07 100644 --- a/libs/aitools/mcp/agentconfig/toml_test.go +++ b/libs/aitools/mcp/agentconfig/toml_test.go @@ -52,7 +52,7 @@ func TestTOMLRemoveDeletesOnlyOwnedTables(t *testing.T) { writeFile(t, path, []byte(before), 0o600) a := testAgent(path, mcpconfig.FormatTOML, "mcp_servers") - removed, err := Remove(t.Context(), a, testName) + removed, err := removeAgent(t.Context(), a, testName) require.NoError(t, err) assert.True(t, removed) assert.Equal(t, "# keep\nmodel = \"x\"\n\n[mcp_servers.other]\ncommand = \"npx\"\n", string(readFile(t, path))) @@ -79,7 +79,7 @@ func TestTOMLRefusesServerWithoutOwnTables(t *testing.T) { assert.ErrorContains(t, err, testName) assert.Equal(t, tc.data, string(readFile(t, path))) - _, err = Remove(t.Context(), a, testName) + _, err = removeAgent(t.Context(), a, testName) require.Error(t, err) assert.Equal(t, tc.data, string(readFile(t, path))) }) @@ -167,7 +167,7 @@ func TestTOMLEnvTablesLayout(t *testing.T) { assert.Equal(t, StatusAdded, status) got := string(readFile(t, path)) requireTidyTOML(t, got) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Equal(t, map[string]any{"DATABRICKS_CONFIG_FILE": "one"}, entries[testName]["env"]) assert.Contains(t, entries, "other") @@ -207,7 +207,7 @@ func TestTOMLEnvTablesLayout(t *testing.T) { writeFile(t, path, []byte(blockFor("test")+"\n"+envTable+"\n"+other), 0o600) a := testAgent(path, mcpconfig.FormatTOML, "mcp_servers") - removed, err := Remove(t.Context(), a, testName) + removed, err := removeAgent(t.Context(), a, testName) require.NoError(t, err) assert.True(t, removed) assert.Equal(t, other, string(readFile(t, path))) @@ -218,7 +218,7 @@ func TestTOMLEnvTablesLayout(t *testing.T) { writeFile(t, path, []byte(blockFor("test")+"\n"+other), 0o600) a := testAgent(path, mcpconfig.FormatTOML, "mcp_servers") - removed, err := Remove(t.Context(), a, testName) + removed, err := removeAgent(t.Context(), a, testName) require.NoError(t, err) assert.True(t, removed) assert.Equal(t, other, string(readFile(t, path))) @@ -234,7 +234,7 @@ func TestTOMLQuotedDottedNameIsAnotherServer(t *testing.T) { writeFile(t, path, []byte(before), 0o600) a := testAgent(path, mcpconfig.FormatTOML, "mcp_servers") - removed, err := Remove(t.Context(), a, testName) + removed, err := removeAgent(t.Context(), a, testName) require.NoError(t, err) assert.False(t, removed) assert.Equal(t, before, string(readFile(t, path))) @@ -260,7 +260,7 @@ func TestTOMLHeaderLikeLineInMultilineString(t *testing.T) { assert.Equal(t, notes+"\n"+strings.Replace(testBlock, testName, "genie", 1), string(readFile(t, path))) // Removing our server leaves the string as it was. - removed, err := Remove(t.Context(), a, "genie") + removed, err := removeAgent(t.Context(), a, "genie") require.NoError(t, err) assert.True(t, removed) assert.Equal(t, notes, string(readFile(t, path))) @@ -284,7 +284,7 @@ func TestTOMLRemoveKeepsOneSeparator(t *testing.T) { writeFile(t, path, []byte(tc.before), 0o600) a := testAgent(path, mcpconfig.FormatTOML, "mcp_servers") - removed, err := Remove(t.Context(), a, testName) + removed, err := removeAgent(t.Context(), a, testName) require.NoError(t, err) assert.True(t, removed) got := string(readFile(t, path)) @@ -308,7 +308,7 @@ func TestTOMLEditWithNonFiniteFloatElsewhere(t *testing.T) { _, status, err = Upsert(t.Context(), a, testName, testCmd, testArgs("other"), nil, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - removed, err := Remove(t.Context(), a, testName) + removed, err := removeAgent(t.Context(), a, testName) require.NoError(t, err) assert.True(t, removed) assert.Equal(t, before, string(readFile(t, path))) @@ -345,7 +345,7 @@ func TestTOMLAddThenRemoveRestoresBytes(t *testing.T) { _, _, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), nil, false) require.NoError(t, err) - removed, err := Remove(t.Context(), a, testName) + removed, err := removeAgent(t.Context(), a, testName) require.NoError(t, err) assert.True(t, removed) assert.Equal(t, tc.before, string(readFile(t, path))) diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index f41ae7187df..c4129f75abf 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -149,18 +149,8 @@ func Upsert(ctx context.Context, a *agents.Agent, name, cmd string, args []strin return path, status, nil } -// Remove deletes server name from agent a's config. It reports false, without -// writing, when there is no such entry, and refuses an entry this CLI did not -// write. -func Remove(ctx context.Context, a *agents.Agent, name string) (bool, error) { - path, err := Path(ctx, a) - if err != nil { - return false, err - } - return RemoveAt(a, path, name) -} - -// RemoveAt is Remove for the config file at path. The file need not be the one the spec names now: a record names +// RemoveAt deletes server name from the config file at path, and refuses an entry this CLI did not write. It reports +// false, without writing, when there is no such entry. The file need not be the one the spec names now: a record names // the file an entry was written to, and the agent's config may have moved since. A missing file has no entry. func RemoveAt(a *agents.Agent, path, name string) (bool, error) { if err := checkName(name); err != nil { @@ -194,17 +184,9 @@ func RemoveAt(a *agents.Agent, path, name string) (bool, error) { return true, nil } -// Read returns every server entry in agent a's config, keyed by name. A missing -// file has no entries. -func Read(ctx context.Context, a *agents.Agent) (map[string]map[string]any, error) { - path, err := Path(ctx, a) - if err != nil { - return nil, err - } - return ReadAt(a, path) -} - -// ReadAt is Read for the config file at path, which need not be the one the spec names now. See RemoveAt. +// ReadAt returns every server entry in the config file at path, keyed by name. A missing file has no entries. The file +// need not be the one the spec names now: a record names the file an entry was written to, and the agent's config may +// have moved since. func ReadAt(a *agents.Agent, path string) (map[string]map[string]any, error) { spec, err := specOf(a) if err != nil { @@ -221,7 +203,7 @@ func ReadAt(a *agents.Agent, path string) (map[string]map[string]any, error) { return entries, nil } -// Path returns the absolute path of agent a's MCP config file, as Read and Remove use it. It does not read the file. +// Path returns the absolute path of agent a's MCP config file, where Upsert writes. It does not read the file. func Path(ctx context.Context, a *agents.Agent) (string, error) { spec, err := specOf(a) if err != nil { diff --git a/libs/aitools/mcp/agentconfig/writer_test.go b/libs/aitools/mcp/agentconfig/writer_test.go index f3dc076d1df..b9cf3520b88 100644 --- a/libs/aitools/mcp/agentconfig/writer_test.go +++ b/libs/aitools/mcp/agentconfig/writer_test.go @@ -120,13 +120,13 @@ func TestRoundTripPerAgent(t *testing.T) { assert.Equal(t, StatusUnchanged, status) assert.Equal(t, after, readFile(t, path)) - entries, err := Read(ctx, a) + entries, err := readAgent(ctx, a) require.NoError(t, err) require.Contains(t, entries, testName) assert.True(t, mcpconfig.IsDatabricksEntry(entries[testName])) assert.Contains(t, entries, "other") - removed, err := Remove(ctx, a, testName) + removed, err := removeAgent(ctx, a, testName) require.NoError(t, err) assert.True(t, removed) assert.Equal(t, semantic(t, a.MCP.Format, before), semantic(t, a.MCP.Format, readFile(t, path))) @@ -159,7 +159,7 @@ func TestUpsertRefusesUnparsableFile(t *testing.T) { _, _, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), nil, true) require.ErrorIs(t, err, ErrConfigInvalid) assert.ErrorContains(t, err, filepath.ToSlash(path)) - _, err = Remove(t.Context(), a, testName) + _, err = removeAgent(t.Context(), a, testName) require.ErrorIs(t, err, ErrConfigInvalid) assert.Equal(t, tc.data, string(readFile(t, path))) @@ -180,7 +180,7 @@ func TestUpsertRefusesEntryWeDidNotWrite(t *testing.T) { _, status, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), nil, true) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.True(t, mcpconfig.IsDatabricksEntry(entries[testName])) } @@ -205,7 +205,7 @@ func TestUpsertUpdatesOwnedEntry(t *testing.T) { _, status, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), nil, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Equal(t, testArgs("test"), toStrings(t, entries[testName]["args"])) }) @@ -251,7 +251,7 @@ func TestUpsertRefusesCommandThatIsNotDatabricks(t *testing.T) { func TestReadMissingFileHasNoEntries(t *testing.T) { a := testAgent(filepath.Join(t.TempDir(), "missing.toml"), mcpconfig.FormatTOML, "mcp_servers") - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Empty(t, entries) } @@ -262,7 +262,7 @@ func TestRemoveRefusesEntryWeDidNotWrite(t *testing.T) { writeFile(t, path, []byte(other), 0o600) a := testAgent(path, mcpconfig.FormatJSON, "mcpServers") - _, err := Remove(t.Context(), a, testName) + _, err := removeAgent(t.Context(), a, testName) require.ErrorIs(t, err, ErrNotOwned) assert.Equal(t, other, string(readFile(t, path))) } @@ -271,7 +271,7 @@ func TestRemoveAbsentEntryDoesNotCreateFile(t *testing.T) { path := filepath.Join(t.TempDir(), "missing.json") a := testAgent(path, mcpconfig.FormatJSON, "mcpServers") - removed, err := Remove(t.Context(), a, testName) + removed, err := removeAgent(t.Context(), a, testName) require.NoError(t, err) assert.False(t, removed) _, err = os.Stat(path) @@ -338,7 +338,7 @@ func TestUpsertWritesThroughSymlink(t *testing.T) { info, err := os.Lstat(link) require.NoError(t, err) assert.NotZero(t, info.Mode()&os.ModeSymlink, "link is replaced by a regular file") - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Contains(t, entries, testName) } @@ -379,7 +379,7 @@ func TestWindowsCommandPathRoundTrip(t *testing.T) { require.NoError(t, err) assert.Contains(t, string(readFile(t, path)), tc.want) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) require.Contains(t, entries, testName) assert.Equal(t, winCmd, entries[testName]["command"]) @@ -437,7 +437,7 @@ func TestUpsertKeepsUserKeysJSON(t *testing.T) { _, status, err = Upsert(t.Context(), a, testName, testCmd, testArgs("other"), nil, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Equal(t, testArgs("other"), toStrings(t, entries[testName]["args"])) assert.Equal(t, true, entries[testName]["disabled"]) @@ -448,7 +448,7 @@ func TestUpsertKeepsUserKeysJSON(t *testing.T) { _, status, err = Upsert(t.Context(), testAgent(foreign, mcpconfig.FormatJSON, "mcpServers"), testName, testCmd, testArgs("test"), nil, true) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err = Read(t.Context(), testAgent(foreign, mcpconfig.FormatJSON, "mcpServers")) + entries, err = readAgent(t.Context(), testAgent(foreign, mcpconfig.FormatJSON, "mcpServers")) require.NoError(t, err) assert.NotContains(t, entries[testName], "disabled") } @@ -469,7 +469,7 @@ func TestUpsertKeepsUserKeysTOML(t *testing.T) { _, status, err = Upsert(t.Context(), a, testName, testCmd, testArgs("other"), nil, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Equal(t, testArgs("other"), toStrings(t, entries[testName]["args"])) assert.Equal(t, false, entries[testName]["enabled"]) @@ -496,7 +496,7 @@ func TestUpsertKeepsToolsNarrowedByUser(t *testing.T) { _, status, err = Upsert(t.Context(), a, testName, testCmd, testArgs("other"), nil, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Equal(t, []any{"search"}, entries[testName]["tools"]) } @@ -565,7 +565,7 @@ func TestUpsertUpdateAddsAndRemovesLaunchKeys(t *testing.T) { _, status, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), map[string]string{mcpconfig.ConfigFileEnv: "/cfg"}, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Equal(t, map[string]any{mcpconfig.ConfigFileEnv: "/cfg"}, entries[testName]["env"]) requireStrictJSON(t, string(readFile(t, path))) @@ -573,7 +573,7 @@ func TestUpsertUpdateAddsAndRemovesLaunchKeys(t *testing.T) { _, status, err = Upsert(t.Context(), a, testName, testCmd, testArgs("test"), nil, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err = Read(t.Context(), a) + entries, err = readAgent(t.Context(), a) require.NoError(t, err) assert.NotContains(t, entries[testName], "env") requireStrictJSON(t, string(readFile(t, path))) @@ -591,7 +591,7 @@ func TestTOMLUpdateKeepsUserTables(t *testing.T) { _, status, err := Upsert(t.Context(), a, testName, testCmd, testArgs("other"), nil, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) - entries, err := Read(t.Context(), a) + entries, err := readAgent(t.Context(), a) require.NoError(t, err) assert.Equal(t, map[string]any{"search": map[string]any{"approval_mode": "approve"}}, entries[testName]["tools"]) } @@ -615,7 +615,7 @@ func TestUpsertAndRemoveRefuseDuplicateKeysJSON(t *testing.T) { _, _, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), nil, true) require.ErrorIs(t, err, ErrConfigInvalid) - _, err = Remove(t.Context(), a, testName) + _, err = removeAgent(t.Context(), a, testName) require.ErrorIs(t, err, ErrConfigInvalid) assert.Equal(t, data, string(readFile(t, path))) }) @@ -642,7 +642,7 @@ func TestRemoveRefusesInvalidServerName(t *testing.T) { writeFile(t, path, []byte(data), 0o600) a := testAgent(path, mcpconfig.FormatJSON, "mcpServers") - _, err := Remove(t.Context(), a, "genie.one") + _, err := removeAgent(t.Context(), a, "genie.one") assert.ErrorContains(t, err, "must contain only letters, digits, '-' and '_'") assert.Equal(t, data, string(readFile(t, path))) } @@ -650,7 +650,7 @@ func TestRemoveRefusesInvalidServerName(t *testing.T) { // entryOf returns the entry of server name in agent a's config. func entryOf(t *testing.T, ctx context.Context, a *agents.Agent, name string) map[string]any { t.Helper() - entries, err := Read(ctx, a) + entries, err := readAgent(ctx, a) require.NoError(t, err) require.Contains(t, entries, name) return entries[name] @@ -815,7 +815,7 @@ func TestReadAtAndRemoveAtUseTheGivenFile(t *testing.T) { require.NoError(t, err) assert.Contains(t, entries, testName) - entries, err = Read(t.Context(), a) + entries, err = readAgent(t.Context(), a) require.NoError(t, err) assert.Empty(t, entries, "the spec's file does not have the entry") @@ -836,3 +836,21 @@ func TestReadAtMissingFileHasNoEntries(t *testing.T) { require.NoError(t, err) assert.Empty(t, entries) } + +// readAgent reads the entries of agent a's config at the path Path names, as the commands read the config. +func readAgent(ctx context.Context, a *agents.Agent) (map[string]map[string]any, error) { + path, err := Path(ctx, a) + if err != nil { + return nil, err + } + return ReadAt(a, path) +} + +// removeAgent removes server name from agent a's config at the path Path names. +func removeAgent(ctx context.Context, a *agents.Agent, name string) (bool, error) { + path, err := Path(ctx, a) + if err != nil { + return false, err + } + return RemoveAt(a, path, name) +} From a9c51be71135c39c4d50bb4f2f01fedee7ed6477 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:24:55 +0000 Subject: [PATCH 20/26] aitools mcp list and remove: one reader for agent configs and one ownership check list and remove read agent configs through two separate readers, and decided ownership in two ways (a re-resolved config file in remove, an inlined EntryServes in list). Remove also called agentconfig.Path and resolved the binding file once per agent. Now: - agentFiles reads each agent's current path once and each config file once per command, for list, remove and add's entry read. - bindingFile resolves a server's config file once, and owns() is the one ownership check for both commands. - Small cleanups: worseRank is package-level, the two skip branches of remove share one path, the test root helper is shared, LeafOf's comment names LeafOf, and the agent name comes from agentDisplayName. No behavior change; the existing tests pass unchanged apart from the helper rename. Co-authored-by: Isaac --- cmd/aitools/mcp_add.go | 3 +- cmd/aitools/mcp_add_test.go | 8 +-- cmd/aitools/mcp_entries.go | 101 ++++++++++++++++++++++++++++++++ cmd/aitools/mcp_entries_test.go | 61 +++++++++++++++++++ cmd/aitools/mcp_list.go | 97 +++++++++--------------------- cmd/aitools/mcp_list_test.go | 9 +-- cmd/aitools/mcp_remove.go | 75 +++++++----------------- libs/aitools/mcp/naming.go | 2 +- 8 files changed, 220 insertions(+), 136 deletions(-) create mode 100644 cmd/aitools/mcp_entries.go create mode 100644 cmd/aitools/mcp_entries_test.go diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index d2c2a84947b..288e884a0b9 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -566,8 +566,9 @@ type agentEntries map[*agents.Agent]map[string]map[string]any func readAgentEntries(ctx context.Context, targets []*agents.Agent) agentEntries { held := make(agentEntries, len(targets)) + files := newAgentFiles() for _, a := range targets { - if cfg := readAgentConfig(ctx, a.Name); cfg.err == nil { + if cfg := files.current(ctx, a); cfg.err == nil { held[a] = cfg.entries } } diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index 981c350d3c5..6169d390538 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -598,9 +598,9 @@ func TestCursorApprovalHintNamesBinary(t *testing.T) { cursorApprovalHint("github-logfood")) } -// newAddTestRoot returns a root command with the persistent --profile and --output flags that root +// newMCPTestRoot returns a root command with the persistent --profile and --output flags that root // defines, and the mcp group. -func newAddTestRoot() *cobra.Command { +func newMCPTestRoot() *cobra.Command { parent := &cobra.Command{Use: "databricks", SilenceErrors: true, SilenceUsage: true} output := flags.OutputText parent.PersistentFlags().VarP(&output, "output", "o", "output type: text or json") @@ -612,7 +612,7 @@ func newAddTestRoot() *cobra.Command { // newAddTestCmd runs `aitools mcp add` under a root, as root does. func newAddTestCmd(t *testing.T, args ...string) (*bytes.Buffer, error) { t.Helper() - parent := newAddTestRoot() + parent := newMCPTestRoot() var stdout bytes.Buffer parent.SetOut(&stdout) parent.SetErr(&bytes.Buffer{}) @@ -723,7 +723,7 @@ func TestMcpAddRejectsUnknownAgentBeforeProfile(t *testing.T) { func TestMcpAddJSONWriteFailureKeepsRunError(t *testing.T) { withHome(t) withDatabricksBinary(t) - parent := newAddTestRoot() + parent := newMCPTestRoot() parent.SetOut(failingWriter{}) parent.SetErr(&bytes.Buffer{}) parent.SetArgs([]string{"mcp", "add", "--names", "github", "--output", "json"}) diff --git a/cmd/aitools/mcp_entries.go b/cmd/aitools/mcp_entries.go new file mode 100644 index 00000000000..0dc0c89c9e6 --- /dev/null +++ b/cmd/aitools/mcp_entries.go @@ -0,0 +1,101 @@ +package aitools + +import ( + "context" + + "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/aitools/mcp/agentconfig" +) + +// agentFile is an agent config file as a command reads it: the server entries it holds, or why it cannot be read. A +// file that does not exist holds no entries. +type agentFile struct { + entries map[string]map[string]any + err error +} + +// agentFiles reads the agent config files of one command. An agent's current config path is found once, and each file +// is read once, so the file a record names and the file the agent reads now are each read at most once. +type agentFiles struct { + paths map[string]agentPath + files map[agentFileKey]agentFile +} + +// agentPath is the path of an agent's config file as the agent reads it now. err is set when the path cannot be found. +type agentPath struct { + path string + err error +} + +// agentFileKey names a file read: the agent it is read for, and its path. +type agentFileKey struct { + agent string + path string +} + +func newAgentFiles() *agentFiles { + return &agentFiles{paths: map[string]agentPath{}, files: map[agentFileKey]agentFile{}} +} + +// currentPath returns the path of agent a's config file as the agent reads it now. +func (f *agentFiles) currentPath(ctx context.Context, a *agents.Agent) (string, error) { + p, ok := f.paths[a.Name] + if !ok { + p.path, p.err = agentconfig.Path(ctx, a) + f.paths[a.Name] = p + } + return p.path, p.err +} + +// current returns agent a's config file as the agent reads it now. +func (f *agentFiles) current(ctx context.Context, a *agents.Agent) agentFile { + path, err := f.currentPath(ctx, a) + if err != nil { + return agentFile{err: err} + } + return f.file(a, path) +} + +// file returns agent a's config file at path. A record names the file an entry was written to, which need not be the +// file the agent reads now. The file is read on first use. +func (f *agentFiles) file(a *agents.Agent, path string) agentFile { + key := agentFileKey{agent: a.Name, path: path} + file, ok := f.files[key] + if !ok { + entries, err := agentconfig.ReadAt(a, path) + file = agentFile{entries: entries, err: err} + f.files[key] = file + } + return file +} + +// bindingFile is the config file that a server is bound to, resolved once for the server. err is set when the file +// cannot be resolved, and then none of the server's entries can be checked for ownership. +type bindingFile struct { + path string + err error +} + +// resolveBinding resolves the config file that e is pinned to, or the default file when it pins none. +func resolveBinding(ctx context.Context, e mcp.Entry) bindingFile { + path, err := mcp.ResolveConfigFile(ctx, e.ConfigFile) + return bindingFile{path: path, err: err} +} + +// checkedBinding returns the binding file of a checked server: the file the check resolved, or the error that stopped it. +func checkedBinding(check mcp.EntryCheck) bindingFile { + if check.Path == "" { + return bindingFile{err: check.Err} + } + return bindingFile{path: check.Path} +} + +// owns reports whether current, the entry under e's name in an agent config, is the one this CLI wrote for e: a +// `serve` entry for its service and profile, through the binding's config file. See mcp.EntryServes. +func (b bindingFile) owns(ctx context.Context, e mcp.Entry, current map[string]any) (bool, error) { + if b.err != nil { + return false, b.err + } + return mcp.EntryServes(ctx, current, e.Service, e.Profile, b.path) +} diff --git a/cmd/aitools/mcp_entries_test.go b/cmd/aitools/mcp_entries_test.go new file mode 100644 index 00000000000..0ceeeb8bfaf --- /dev/null +++ b/cmd/aitools/mcp_entries_test.go @@ -0,0 +1,61 @@ +package aitools + +import ( + "os" + "path/filepath" + "testing" + + "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestAgentFilesReadsEachFileOnce checks that a file is read on first use and then served from the cache: a second read +// in the same command returns what the first read saw, even when the file has changed since. +func TestAgentFilesReadsEachFileOnce(t *testing.T) { + home := withHome(t) + claude := agents.ByName("claude-code") + path := filepath.Join(home, ".claude.json") + require.NoError(t, os.WriteFile(path, []byte(`{"mcpServers":{"first":{"command":"ug","args":["mcp-proxy"]}}}`), 0o600)) + + files := newAgentFiles() + before := files.file(claude, path) + require.NoError(t, before.err) + require.Contains(t, before.entries, "first") + + require.NoError(t, os.WriteFile(path, []byte(`{"mcpServers":{"second":{"command":"ug","args":["mcp-proxy"]}}}`), 0o600)) + assert.Equal(t, before, files.file(claude, path), "the same command reads the file once") + + fresh := newAgentFiles().file(claude, path) + require.NoError(t, fresh.err) + assert.Contains(t, fresh.entries, "second", "a new command reads the file again") +} + +// TestAgentFilesFindsCurrentPathOnce checks that an agent's current config path is found once: the agent's +// directory, changed after the first lookup, does not move the path for the rest of the command. +func TestAgentFilesFindsCurrentPathOnce(t *testing.T) { + withHome(t) + claude := agents.ByName("claude-code") + first := t.TempDir() + t.Setenv("CLAUDE_CONFIG_DIR", first) + + files := newAgentFiles() + path, err := files.currentPath(t.Context(), claude) + require.NoError(t, err) + assert.Equal(t, filepath.Join(first, ".claude.json"), path) + + t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir()) + again, err := files.currentPath(t.Context(), claude) + require.NoError(t, err) + assert.Equal(t, path, again) +} + +// TestCheckedBindingKeepsTheCheckError checks that a server whose config file could not be resolved has no binding +// file, and that its ownership check reports the check's error. +func TestCheckedBindingKeepsTheCheckError(t *testing.T) { + checkErr := assert.AnError + binding := checkedBinding(mcp.EntryCheck{Err: checkErr}) + _, err := binding.owns(t.Context(), mcp.Entry{}, nil) + assert.ErrorIs(t, err, checkErr) +} diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index 8d8497f6a1b..c18ef0541ee 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -169,9 +169,14 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error } } } - configs := readAgentConfigs(ctx, names) + files := newAgentFiles() for _, name := range names { - if cfg := configs[name]; cfg.err != nil { + a := agents.ByName(name) + if a == nil { + out.Warnings = append(out.Warnings, fmt.Sprintf("could not read the %s config: %s is not a known agent", name, name)) + continue + } + if cfg := files.current(ctx, a); cfg.err != nil { out.Warnings = append(out.Warnings, fmt.Sprintf("could not read the %s config: %s", agentDisplayName(name), cfg.err)) } } @@ -212,9 +217,9 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { // A config that cannot be read is warned about once, for the agent; here its entries are unknown. status := statusUnknown - if cfg := configs[agentName]; cfg.err == nil { + if a := agents.ByName(agentName); a != nil && files.current(ctx, a).err == nil { var err error - status, err = agentStatus(ctx, e, agentName, cfg, check) + status, err = agentStatus(ctx, files, e, a, checkedBinding(check)) // When the entry itself could not be checked, its warning already names the cause. if err != nil && check.Err == nil { out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: could not check %s: %s", e.Name, agentDisplayName(agentName), err)) @@ -241,84 +246,50 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error if profileName != "" { return out, nil } - for _, name := range mcpAgentNames() { - cfg := configs[name] + for _, a := range agents.MCPAgents() { + cfg := files.current(ctx, a) if cfg.err != nil { continue } for _, entryName := range slices.Sorted(maps.Keys(cfg.entries)) { kind := unmanagedKind(cfg.entries[entryName]) - if kind == "" || recordedFor(state, name, entryName) { + if kind == "" || recordedFor(state, a.Name, entryName) { continue } - out.Unmanaged = append(out.Unmanaged, mcpListUnmanaged{Agent: name, Name: entryName, Kind: kind}) + out.Unmanaged = append(out.Unmanaged, mcpListUnmanaged{Agent: a.Name, Name: entryName, Kind: kind}) } } return out, nil } -// worseStatus returns the more serious of two server statuses, for the status of a profile. A server that could not be -// checked makes its profile unknown, which is worse than ok and less serious than a drift. +// worseRank orders the statuses of a profile group. A server that could not be checked makes its profile unknown, +// which is worse than ok and less serious than a drift. +var worseRank = map[string]int{statusOK: 0, statusUnknown: 1, string(mcp.DriftHostChanged): 2, string(mcp.DriftProfileMissing): 3} + +// worseStatus returns the more serious of two server statuses, for the status of a profile. func worseStatus(a, b string) string { - rank := map[string]int{statusOK: 0, statusUnknown: 1, string(mcp.DriftHostChanged): 2, string(mcp.DriftProfileMissing): 3} - if rank[b] > rank[a] { + if worseRank[b] > worseRank[a] { return b } return a } -// agentConfig is one agent's MCP config, read once for a command. err is set when the config cannot be located or -// parsed; entries is nil then. -type agentConfig struct { - path string - entries map[string]map[string]any - err error -} - -// readAgentConfigs reads the MCP configs of the named agents, keyed by name. A config that cannot be read is an error -// of its agent, so the command can report it and go on with the others. -func readAgentConfigs(ctx context.Context, names []string) map[string]agentConfig { - configs := make(map[string]agentConfig, len(names)) - for _, name := range names { - configs[name] = readAgentConfig(ctx, name) - } - return configs -} - -// readAgentConfig reads the MCP config of the agent named name. A failure is kept in the result, not returned, so that -// the caller can report it for that agent and go on with the others. -func readAgentConfig(ctx context.Context, name string) agentConfig { - a := agents.ByName(name) - if a == nil { - return agentConfig{err: fmt.Errorf("%s is not a known agent", name)} - } - path, err := agentconfig.Path(ctx, a) +// agentStatus compares the server's entry for agent a with the agent's config, which must have been read. An agent +// whose config moved is path_changed: the entry is in the file the record names, which this command does not read. +// pin is the server's binding file, which decides ownership. err is set when the entry cannot be checked for ownership. +func agentStatus(ctx context.Context, files *agentFiles, rec mcp.Entry, a *agents.Agent, pin bindingFile) (string, error) { + current, err := files.currentPath(ctx, a) if err != nil { - return agentConfig{err: err} - } - entries, err := agentconfig.ReadAt(a, path) - if err != nil { - return agentConfig{path: path, err: err} + return statusUnknown, err } - return agentConfig{path: path, entries: entries} -} - -// agentStatus compares the server's entry for one agent with that agent's config, which must have been read. An -// agent whose config moved is path_changed: the entry is in the file the record names, which this command does -// not read. check is the entry's check, whose Path is the config file the record is pinned to. err is set when the -// entry cannot be checked for ownership. -func agentStatus(ctx context.Context, rec mcp.Entry, agentName string, cfg agentConfig, check mcp.EntryCheck) (string, error) { - if !mcp.SamePath(rec.Agents[agentName].Path, cfg.path) { + if !mcp.SamePath(rec.Agents[a.Name].Path, current) { return agentStatusPathChanged, nil } - current, ok := cfg.entries[rec.Name] + entry, ok := files.file(a, current).entries[rec.Name] if !ok { return agentStatusMissingOnDisk, nil } - if check.Path == "" { - return statusUnknown, check.Err - } - owned, err := mcp.EntryServes(ctx, current, rec.Service, rec.Profile, check.Path) + owned, err := pin.owns(ctx, rec, entry) if err != nil { return statusUnknown, err } @@ -328,18 +299,6 @@ func agentStatus(ctx context.Context, rec mcp.Entry, agentName string, cfg agent return agentStatusInstalled, nil } -// ownedBy reports whether the entry on disk is the one this CLI wrote for rec: a `databricks aitools mcp serve` -// for the record's service and profile, through the record's config file. The command is not compared, because -// an add from another binary replaces the record's command for every agent. err is set when the record's config -// file cannot be resolved. -func ownedBy(ctx context.Context, rec mcp.Entry, current map[string]any) (bool, error) { - configFile, err := mcp.ResolveConfigFile(ctx, rec.ConfigFile) - if err != nil { - return false, err - } - return mcp.EntryServes(ctx, current, rec.Service, rec.Profile, configFile) -} - // unmanagedKind names how an entry reaches managed MCP servers without being recorded for its agent, or returns "" // for any other entry. An entry that runs `aitools mcp serve` and is not recorded has no install record. func unmanagedKind(entry map[string]any) string { diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index c46b2693dcf..6d9fe0142a9 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -15,9 +15,7 @@ import ( "github.com/databricks/cli/libs/aitools/mcp/agentconfig" "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/cmdio" - "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/telemetry/protos" - "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -96,12 +94,7 @@ func saveState(t *testing.T, entries ...mcp.Entry) { // runMcpCmd runs `mcp list` or `mcp remove` with args and returns its stdout and stderr. func runMcpCmd(t *testing.T, args ...string) (stdout, stderr *bytes.Buffer, err error) { t.Helper() - parent := &cobra.Command{Use: "databricks", SilenceErrors: true, SilenceUsage: true} - output := flags.OutputText - parent.PersistentFlags().VarP(&output, "output", "o", "output type: text or json") - parent.PersistentFlags().StringP("profile", "p", "", "profile") - parent.AddCommand(NewMcpCmd()) - + parent := newMCPTestRoot() ctx, stderrBuf := cmdio.NewTestContextWithStderr(t.Context()) var stdoutBuf bytes.Buffer parent.SetOut(&stdoutBuf) diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 0ca50c58dc4..31cc2ce5bbe 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -155,12 +155,13 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso return err } - // Each agent config file is read once, when the first selected server needs it. - files := map[recordedFileKey]recordedFile{} + // Each agent config file is read once per command, and each server's config file is resolved once. + files := newAgentFiles() var drops []recordDrop var agentErrs []error for _, e := range selected { removed := removeRemoved{Name: e.Name, Service: e.Service, Profile: e.Profile, Agents: []string{}} + pin := resolveBinding(ctx, e) var errs []error for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { if targets != nil && !slices.ContainsFunc(targets, func(a *agents.Agent) bool { return a.Name == agentName }) { @@ -174,13 +175,7 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso drops = append(drops, recordDrop{name: e.Name, agent: agentName}) continue } - path, file, err := entryFile(ctx, e, a, e.Agents[agentName].Path, files) - if err != nil { - errs = append(errs, err) - out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Agent: agentName, Reason: fmt.Sprintf("could not update %s: %s", agentDisplayName(agentName), err)}) - continue - } - outcome, reason, err := removeAgentEntry(ctx, e, a, path, file) + outcome, reason, err := removeFromAgent(ctx, files, e, a, pin) if err != nil { errs = append(errs, err) out.Skipped = append(out.Skipped, removeSkipped{Name: e.Name, Agent: agentName, Reason: fmt.Sprintf("could not update %s: %s", agentDisplayName(agentName), err)}) @@ -321,62 +316,34 @@ func checkTargetsInstalled(selected []mcp.Entry, targets []*agents.Agent) error _, ok := e.Agents[a.Name] return ok }) { - return failure(categoryServiceNotFound, nil, "no selected MCP server is installed for %s", a.DisplayName) + return failure(categoryServiceNotFound, nil, "no selected MCP server is installed for %s", agentDisplayName(a.Name)) } } return nil } -// recordedFile is an agent config file that a record names, read once for a command. err is set when it cannot be -// read; a file that does not exist has no entries. -type recordedFile struct { - entries map[string]map[string]any - err error -} - -// recordedFileKey names a recordedFile: the agent and the path its record gives. -type recordedFileKey struct { - agent string - path string -} - -// readRecordedFile reads the agent config file at path, which a record names. A file that does not exist has no entries. -func readRecordedFile(a *agents.Agent, path string) recordedFile { - entries, err := agentconfig.ReadAt(a, path) - return recordedFile{entries: entries, err: err} -} - -// cachedRecordedFile returns the agent config file at path from files, reading it on first use. -func cachedRecordedFile(files map[recordedFileKey]recordedFile, a *agents.Agent, path string) recordedFile { - key := recordedFileKey{agent: a.Name, path: path} - file, ok := files[key] - if !ok { - file = readRecordedFile(a, path) - files[key] = file - } - return file -} - -// entryFile returns the config file that holds the server's entry for the agent, and its contents. That is the file the +// entryFile returns the config file that holds the server's entry for agent a, and its entries. That is the file the // record names, unless the file does not hold the entry and the agent now reads its config from another file: then that // file, which may hold it, since the user may have moved the config with the agent's directory. A recorded file that // cannot be read is an error, since it may be the one that holds the entry. -func entryFile(ctx context.Context, e mcp.Entry, a *agents.Agent, recorded string, files map[recordedFileKey]recordedFile) (string, recordedFile, error) { - file := cachedRecordedFile(files, a, recorded) +func entryFile(ctx context.Context, files *agentFiles, e mcp.Entry, a *agents.Agent) (string, agentFile, error) { + recorded := e.Agents[a.Name].Path + file := files.file(a, recorded) if file.err != nil { - return "", recordedFile{}, file.err + return "", agentFile{}, file.err } if _, found := file.entries[e.Name]; found { return recorded, file, nil } - current, err := agentconfig.Path(ctx, a) + current, err := files.currentPath(ctx, a) if err != nil { - return "", recordedFile{}, err + return "", agentFile{}, err } if mcp.SamePath(current, recorded) { return recorded, file, nil } - return current, cachedRecordedFile(files, a, current), nil + file = files.file(a, current) + return current, file, file.err } // keptReason says why an entry is left in place, and how to get it out: by hand, or by adding the server again with --force. @@ -385,17 +352,19 @@ func keptReason(e mcp.Entry, a *agents.Agent, path string) string { agentDisplayName(a.Name), e.Name, filepath.ToSlash(path)) } -// removeAgentEntry removes the server from the config file at path, but only when the entry there is the one this CLI -// wrote. A file that has no entry of the name is pruned: the record goes without an edit. -func removeAgentEntry(ctx context.Context, e mcp.Entry, a *agents.Agent, path string, file recordedFile) (removeOutcome, string, error) { - if file.err != nil { - return 0, "", file.err +// removeFromAgent removes the server's entry for agent a, but only when the entry there is the one this CLI wrote. The +// entry is looked for as entryFile finds it. A file that has no entry of the name is pruned: the record goes without an +// edit. +func removeFromAgent(ctx context.Context, files *agentFiles, e mcp.Entry, a *agents.Agent, pin bindingFile) (removeOutcome, string, error) { + path, file, err := entryFile(ctx, files, e, a) + if err != nil { + return 0, "", err } current, found := file.entries[e.Name] if !found { return removePruned, "", nil } - owned, err := ownedBy(ctx, e, current) + owned, err := pin.owns(ctx, e, current) if err != nil { return 0, "", err } diff --git a/libs/aitools/mcp/naming.go b/libs/aitools/mcp/naming.go index 29ee269b3db..b7b011e3709 100644 --- a/libs/aitools/mcp/naming.go +++ b/libs/aitools/mcp/naming.go @@ -46,7 +46,7 @@ func ServerName(fullName, profile string) string { return strings.Join(name, "-") } -// leafOf returns the service name after the last ".". Unity Catalog names cannot contain ".". +// LeafOf returns the service name after the last ".". Unity Catalog names cannot contain ".". func LeafOf(fullName string) string { return fullName[strings.LastIndex(fullName, ".")+1:] } From 877ae5b64cfef3c34bc7c0da3011fd2cedffc256 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:26:30 +0000 Subject: [PATCH 21/26] aitools mcp: cache a config file that cannot be read, so each lookup reads it once configFiles cached only files that parsed. An unreadable ~/.databrickscfg was parsed again for every server in a list, and each parse could differ. The failure is now cached with the file, and every profile of the file reports the same error. The test is internal (configFiles is unexported) and fails on the old code, where the second lookup reads the file again and succeeds. Co-authored-by: Isaac --- libs/aitools/mcp/configfiles_test.go | 25 +++++++++++++++ libs/aitools/mcp/state.go | 47 ++++++++++++++++++---------- 2 files changed, 56 insertions(+), 16 deletions(-) create mode 100644 libs/aitools/mcp/configfiles_test.go diff --git a/libs/aitools/mcp/configfiles_test.go b/libs/aitools/mcp/configfiles_test.go new file mode 100644 index 00000000000..37d1559b55f --- /dev/null +++ b/libs/aitools/mcp/configfiles_test.go @@ -0,0 +1,25 @@ +package mcp + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestConfigFilesCachesAFailedRead checks that a config file which cannot be read is read once per lookup: later +// profiles of the same file get the same failure, without a second read that could differ. +func TestConfigFilesCachesAFailedRead(t *testing.T) { + path := filepath.Join(t.TempDir(), ".databrickscfg") + require.NoError(t, os.WriteFile(path, []byte("[broken\n"), 0o600)) + + files := configFiles{} + _, first := files.profile(path, "logfood") + require.Error(t, first) + + require.NoError(t, os.WriteFile(path, []byte("[logfood]\nhost = https://adb-1.test\n"), 0o600)) + _, second := files.profile(path, "logfood") + assert.Equal(t, first, second, "the failure of the file is kept for the lookup") +} diff --git a/libs/aitools/mcp/state.go b/libs/aitools/mcp/state.go index fc06480bcd7..4e55a8e678e 100644 --- a/libs/aitools/mcp/state.go +++ b/libs/aitools/mcp/state.go @@ -122,30 +122,33 @@ func checkEntry(ctx context.Context, files configFiles, entry Entry) EntryCheck return check } -// configFiles holds the config files that one lookup has read, by resolved path, so that each file is -// parsed once. A nil file is one that does not exist. -type configFiles map[string]*config.File +// configFiles holds the config files that one lookup has read, by resolved path, so that each file is parsed once. A +// file that cannot be read keeps its error, which every profile of that file then reports. +type configFiles map[string]configFile + +// configFile is one config file as a lookup read it: the parsed file, which is nil when the file does not exist, or the +// error that reading it gave. +type configFile struct { + file *config.File + err error +} // profile returns the profile named name from the config file at path. It returns errProfileMissing // when the file does not exist or has no section of that name, and errProfileNoHost when the section // has no host or an empty one. func (c configFiles) profile(path, name string) (profile.Profile, error) { - file, ok := c[path] + f, ok := c[path] if !ok { - loaded, err := config.LoadFile(path) - switch { - case errors.Is(err, fs.ErrNotExist): - loaded = nil - case err != nil: - return profile.Profile{}, fmt.Errorf("failed to read Databricks profiles: %w", err) - } - file = loaded - c[path] = file - } - if file == nil { + f = readConfigFile(path) + c[path] = f + } + if f.err != nil { + return profile.Profile{}, f.err + } + if f.file == nil { return profile.Profile{}, errProfileMissing } - section, err := file.GetSection(name) + section, err := f.file.GetSection(name) if err != nil { return profile.Profile{}, errProfileMissing } @@ -160,6 +163,18 @@ func (c configFiles) profile(path, name string) (profile.Profile, error) { return profile.Profile{Name: name, Host: keys["host"], WorkspaceID: keys["workspace_id"]}, nil } +// readConfigFile reads the config file at path. A file that does not exist is read as nil, with no error. +func readConfigFile(path string) configFile { + file, err := config.LoadFile(path) + switch { + case errors.Is(err, fs.ErrNotExist): + return configFile{} + case err != nil: + return configFile{err: fmt.Errorf("failed to read Databricks profiles: %w", err)} + } + return configFile{file: file} +} + // driftOf returns the drift of an entry against the profile it names, or nil when the profile still // names the recorded host and workspace. func driftOf(entry Entry, p profile.Profile) *Drift { From d85eb6a91b65c7556cb34c0d593a6627a7c38bb6 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:28:28 +0000 Subject: [PATCH 22/26] aitools mcp remove: exact server name first, --agents skips agentless records, clear hint - --names matches a server name exactly before it matches without case. State can hold names that differ only in case, and the first case-insensitive match was taken. Several case-only matches are now refused as ambiguous. Tests: TestSelectInstallsExactServerNameWins (failed before: the first match was taken). - --agents selects only servers installed for those agents. An entry with no agent left was reported as removed and dropped from state. Test: TestMcpRemoveWithAgentsSkipsRecordWithoutAgents (failed before). - The kept reason offers --force only for an entry that is not a Databricks entry, the one case add can replace. For a Databricks entry that serves another binding, the reason says to delete it by hand and run remove again. The hint is changedEntryFix, shared with list. Test: TestMcpRemoveKeptReasonForDatabricksEntryOmitsForce (failed before). Co-authored-by: Isaac --- cmd/aitools/mcp_entries.go | 14 +++++++ cmd/aitools/mcp_remove.go | 42 +++++++++++++------ cmd/aitools/mcp_remove_test.go | 73 +++++++++++++++++++++++++++++++++- 3 files changed, 116 insertions(+), 13 deletions(-) diff --git a/cmd/aitools/mcp_entries.go b/cmd/aitools/mcp_entries.go index 0dc0c89c9e6..6879f303918 100644 --- a/cmd/aitools/mcp_entries.go +++ b/cmd/aitools/mcp_entries.go @@ -2,10 +2,13 @@ package aitools import ( "context" + "fmt" + "path/filepath" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/aitools/mcp/agentconfig" + "github.com/databricks/cli/libs/aitools/mcpconfig" ) // agentFile is an agent config file as a command reads it: the server entries it holds, or why it cannot be read. A @@ -99,3 +102,14 @@ func (b bindingFile) owns(ctx context.Context, e mcp.Entry, current map[string]a } return mcp.EntryServes(ctx, current, e.Service, e.Profile, b.path) } + +// changedEntryFix says how to clear an entry that was changed outside this CLI, so that remove can take the server out +// of the agent. add replaces an entry this CLI did not write only with --force. It refuses a Databricks entry that serves +// another binding whatever --force says, so that entry is deleted by hand. +func changedEntryFix(name, path string, entry map[string]any) string { + fix := fmt.Sprintf("delete the entry from %s by hand and run `%s` again", filepath.ToSlash(path), mcp.RemoveNamesCommand(name)) + if mcpconfig.IsDatabricksEntry(entry) { + return fix + } + return fix + ", or add the server again with --force" +} diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 31cc2ce5bbe..3dbb6deffc9 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "maps" - "path/filepath" "slices" "strings" @@ -154,6 +153,10 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso if err := checkTargetsInstalled(selected, targets); err != nil { return err } + if targets != nil { + // --agents chooses the servers installed for those agents, so a server with no agent left is not chosen. + selected = slices.DeleteFunc(selected, func(e mcp.Entry) bool { return len(e.Agents) == 0 }) + } // Each agent config file is read once per command, and each server's config file is resolved once. files := newAgentFiles() @@ -269,15 +272,30 @@ func selectInstalls(state *mcp.State, names []string, profileName string) ([]mcp return selected, nil } -// matchInstalls returns the indexes of the entries of scope that name means. A server name is unique in state, so a -// name equal to one selects that server and nothing else. Only when no server has the name, it means the service: the -// full service name, or the leaf of a service name (its last part, when the name has no dot). All comparisons ignore -// case. A leaf is refused when the entries it matches are of more than one service, since then it does not say which -// one is meant. +// matchInstalls returns the indexes of the entries of scope that name means. A server name selects that server: an +// exact match first, and otherwise a match without case, which is refused when several servers match that way, since +// state can hold names that differ only in case. Only when no server has the name, it means the service: the full +// service name, or the leaf of a service name (its last part, when the name has no dot). A leaf is refused when the +// entries it matches are of more than one service, since then it does not say which one is meant. func matchInstalls(scope []mcp.Entry, name string) ([]int, error) { - if i := slices.IndexFunc(scope, func(e mcp.Entry) bool { return strings.EqualFold(e.Name, name) }); i >= 0 { + if i := slices.IndexFunc(scope, func(e mcp.Entry) bool { return e.Name == name }); i >= 0 { return []int{i}, nil } + var byName []int + var serverNames []string + for i, e := range scope { + if strings.EqualFold(e.Name, name) { + byName = append(byName, i) + serverNames = append(serverNames, e.Name) + } + } + if len(byName) > 1 { + return nil, failure(protos.AitoolsErrorCategoryInvalidFlags, nil, "%s matches more than one MCP server (%s); pass the exact server name", + name, strings.Join(serverNames, ", ")) + } + if len(byName) == 1 { + return byName, nil + } var matched []int var services []string for i, e := range scope { @@ -346,10 +364,10 @@ func entryFile(ctx context.Context, files *agentFiles, e mcp.Entry, a *agents.Ag return current, file, file.err } -// keptReason says why an entry is left in place, and how to get it out: by hand, or by adding the server again with --force. -func keptReason(e mcp.Entry, a *agents.Agent, path string) string { - return fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place. To remove it, delete the entry from %s by hand and run remove again, or add the server again with --force", - agentDisplayName(a.Name), e.Name, filepath.ToSlash(path)) +// keptReason says why an entry is left in place, and how to clear it. +func keptReason(e mcp.Entry, a *agents.Agent, path string, entry map[string]any) string { + return fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place. To remove it, %s", + agentDisplayName(a.Name), e.Name, changedEntryFix(e.Name, path, entry)) } // removeFromAgent removes the server's entry for agent a, but only when the entry there is the one this CLI wrote. The @@ -369,7 +387,7 @@ func removeFromAgent(ctx context.Context, files *agentFiles, e mcp.Entry, a *age return 0, "", err } if !owned { - return removeKept, keptReason(e, a, path), nil + return removeKept, keptReason(e, a, path, current), nil } if _, err := agentconfig.RemoveAt(a, path, e.Name); err != nil { return 0, "", err diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index 09c3f5c5dbd..4e537b0ecf3 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -197,7 +197,7 @@ func TestMcpRemoveSkipsEntryChangedOutsideCLI(t *testing.T) { assert.Equal(t, "genie_one_mcp-logfood", out.Skipped[0].Name) assert.Equal(t, "claude-code", out.Skipped[0].Agent) assert.Equal(t, "Claude Code has an entry named genie_one_mcp-logfood that was changed outside this CLI; left in place. "+ - "To remove it, delete the entry from "+filepath.ToSlash(claudePath)+" by hand and run remove again, "+ + "To remove it, delete the entry from "+filepath.ToSlash(claudePath)+" by hand and run `databricks aitools mcp remove --names genie_one_mcp-logfood` again, "+ "or add the server again with --force", out.Skipped[0].Reason) after, err := os.ReadFile(claudePath) @@ -576,3 +576,74 @@ func TestMcpRemoveTakesEntryFromFileAgentNowReads(t *testing.T) { require.NoError(t, err) assert.Empty(t, state.Servers, "the record went with the entry") } + +// TestSelectInstallsExactServerNameWins checks that --names matches a server name exactly before it matches without +// case. State can hold names that differ only in case, since add adopts the name an agent entry already has. +func TestSelectInstallsExactServerNameWins(t *testing.T) { + state := &mcp.State{Servers: []mcp.Entry{ + {Name: "Github", Service: "system.ai.github", Profile: "logfood"}, + {Name: "github", Service: "system.ai.github", Profile: "dogfood"}, + }} + + exact, err := selectInstalls(state, []string{"github"}, "") + require.NoError(t, err) + require.Len(t, exact, 1) + assert.Equal(t, "github", exact[0].Name) + + _, err = selectInstalls(state, []string{"GITHUB"}, "") + require.Error(t, err) + assert.Equal(t, "GITHUB matches more than one MCP server (Github, github); pass the exact server name", err.Error()) + assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, errorCategory(err)) + + // Narrowed to one profile, the case-insensitive name is unambiguous again. + one, err := selectInstalls(state, []string{"GITHUB"}, "logfood") + require.NoError(t, err) + require.Len(t, one, 1) + assert.Equal(t, "Github", one[0].Name) +} + +// TestMcpRemoveWithAgentsSkipsRecordWithoutAgents checks that --agents selects only servers installed for those agents. +// An entry with no agent left is not chosen, so it is neither reported as removed nor dropped from state. +func TestMcpRemoveWithAgentsSkipsRecordWithoutAgents(t *testing.T) { + withHome(t) + claude := agents.ByName("claude-code") + genie := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + dangling := mcp.Entry{Name: "dangling", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", Command: testDatabricksCommand} + saveState(t, genie, dangling) + + stdout, _, err := runMcpCmd(t, "remove", "--all", "--agents", "claude-code", "--output", "json") + require.NoError(t, err) + out := readRemoveOutput(t, stdout.String()) + require.Len(t, out.Removed, 1) + assert.Equal(t, "genie_one_mcp-logfood", out.Removed[0].Name) + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + require.Len(t, state.Servers, 1) + assert.Equal(t, "dangling", state.Servers[0].Name) + + // Named explicitly, the same entry is a refusal: no selected server is installed for the agent. + _, _, err = runMcpCmd(t, "remove", "--names", "dangling", "--agents", "claude-code") + require.ErrorContains(t, err, "no selected MCP server is installed for Claude Code") +} + +// TestMcpRemoveKeptReasonForDatabricksEntryOmitsForce checks that an entry this CLI wrote, but that serves another +// binding now, is cleared by hand. add refuses such an entry whatever --force says, so the reason does not offer it. +func TestMcpRemoveKeptReasonForDatabricksEntryOmitsForce(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + claudePath := filepath.Join(home, ".claude.json") + editEntry(t, claudePath, entry.Name, func(server map[string]any) { setServeFlag(t, server, "--profile", "other") }) + + stdout, _, err := runMcpCmd(t, "remove", "--names", entry.Name, "--output", "json") + require.NoError(t, err) + out := readRemoveOutput(t, stdout.String()) + require.Len(t, out.Skipped, 1) + assert.Equal(t, "Claude Code has an entry named genie_one_mcp-logfood that was changed outside this CLI; left in place. "+ + "To remove it, delete the entry from "+filepath.ToSlash(claudePath)+" by hand and run `databricks aitools mcp remove --names genie_one_mcp-logfood` again", + out.Skipped[0].Reason) + assert.NotContains(t, out.Skipped[0].Reason, "--force") +} From f0090d0f150b3130240e6e475c99dcf49c51f96e Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:34:36 +0000 Subject: [PATCH 23/26] aitools mcp list: report the entry remove acts on, one warning per cause, clear hints - Moved config (P5): list finds an entry the way remove does (locateEntry): in the file the record names when that file holds it, otherwise in the file the agent reads now. An entry found in the current file is installed or modified there, not path_changed. path_changed is for an entry in a record's file that the agent no longer reads. Remove uses the same lookup. Test: TestBuildMcpListAndRemoveAgreeAfterConfigMoved (the current-file case failed before: path_changed). - Hints (P1): a modified Databricks entry says to delete it by hand and run remove again, with no --force, since add refuses it whatever --force says. A foreign entry keeps the --force alternative. Test: TestRenderMcpListHintForDatabricksEntryOmitsForce (failed before). - An agent that takes no MCP servers (P10): a record for it is unknown, with a warning that says so, and no "could not read the config" warning. Remove drops such a record as before. Test: TestBuildMcpListRecordForAgentWithoutMCPIsUnknown (failed before). - An unreadable config file is one warning for the file, not one per server (P11). Test: TestBuildMcpListWarnsOncePerUnreadableProfileFile (failed before: two warnings). TestBuildMcpListUnknownServerIsWarnedNotOK now expects the file warning, which names the file. - An ownership error is warned about unless the entry check or the agent's config already reported that same error (P12). Test: TestBuildMcpListWarnsForOwnershipErrorWithAnotherCause (failed before: no warning). - Login hint expectations quote the config path with shellquote.BashArg, as the code does (P15). A Windows temp path with a tilde is quoted. Co-authored-by: Isaac --- cmd/aitools/mcp_entries.go | 38 ++++++++ cmd/aitools/mcp_list.go | 74 ++++++++++------ cmd/aitools/mcp_list_test.go | 167 ++++++++++++++++++++++++++++++++++- cmd/aitools/mcp_remove.go | 39 ++------ 4 files changed, 258 insertions(+), 60 deletions(-) diff --git a/cmd/aitools/mcp_entries.go b/cmd/aitools/mcp_entries.go index 6879f303918..285e76c5e3d 100644 --- a/cmd/aitools/mcp_entries.go +++ b/cmd/aitools/mcp_entries.go @@ -73,6 +73,44 @@ func (f *agentFiles) file(a *agents.Agent, path string) agentFile { return file } +// entryLocation is where remove finds a server's entry in one agent config, and what the entry holds. +type entryLocation struct { + // path is the file the entry was found in, or the record's file when no file holds it. + path string + // entry is the entry, when found is set. + entry map[string]any + found bool + // recorded is set when the entry is in the file the record names. + recorded bool +} + +// locateEntry finds the server's entry for agent a as remove does: in the file its record names, when that file holds +// it. Otherwise it is in the file the agent reads now, since the user may have moved the agent's config directory. A +// file that cannot be read is an error, since it may be the one that holds the entry. +func (f *agentFiles) locateEntry(ctx context.Context, e mcp.Entry, a *agents.Agent) (entryLocation, error) { + recorded := e.Agents[a.Name].Path + file := f.file(a, recorded) + if file.err != nil { + return entryLocation{}, file.err + } + if entry, found := file.entries[e.Name]; found { + return entryLocation{path: recorded, entry: entry, found: true, recorded: true}, nil + } + current, err := f.currentPath(ctx, a) + if err != nil { + return entryLocation{}, err + } + if mcp.SamePath(current, recorded) { + return entryLocation{path: recorded}, nil + } + file = f.file(a, current) + if file.err != nil { + return entryLocation{}, file.err + } + entry, found := file.entries[e.Name] + return entryLocation{path: current, entry: entry, found: found}, nil +} + // bindingFile is the config file that a server is bound to, resolved once for the server. err is set when the file // cannot be resolved, and then none of the server's entries can be checked for ownership. type bindingFile struct { diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index c18ef0541ee..d80972d75cc 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -83,6 +83,8 @@ type mcpListAgent struct { Name string `json:"name"` Path string `json:"path"` Status string `json:"status"` + // fix says how to clear a modified entry, for the text listing. + fix string } type mcpListUnmanaged struct { @@ -176,6 +178,10 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error out.Warnings = append(out.Warnings, fmt.Sprintf("could not read the %s config: %s is not a known agent", name, name)) continue } + if !a.SupportsMCP() { + // Its records are warned about with their servers, since the agent has no config to read. + continue + } if cfg := files.current(ctx, a); cfg.err != nil { out.Warnings = append(out.Warnings, fmt.Sprintf("could not read the %s config: %s", agentDisplayName(name), cfg.err)) } @@ -183,6 +189,8 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error checks := mcp.CheckEntries(ctx, &mcp.State{Servers: entries}) groups := map[profileKey]*mcpListProfile{} + // A config file that cannot be read is warned about once, for every server that reads it. + warnedFiles := map[string]bool{} for i, e := range entries { check := checks[i] path := check.Path @@ -204,7 +212,12 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error case check.Err != nil: s.Status = statusUnknown p.Status = worseStatus(p.Status, statusUnknown) - out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: %s", e.Name, check.Err)) + if check.Path == "" { + out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: %s", e.Name, check.Err)) + } else if !warnedFiles[check.Path] { + warnedFiles[check.Path] = true + out.Warnings = append(out.Warnings, fmt.Sprintf("%s: %s", filepath.ToSlash(check.Path), check.Err)) + } case check.Drift != nil: s.Status = string(check.Drift.Kind) s.drift = check.Drift @@ -215,20 +228,26 @@ func buildMcpList(ctx context.Context, profileName string) (mcpListOutput, error } } for _, agentName := range slices.Sorted(maps.Keys(e.Agents)) { - // A config that cannot be read is warned about once, for the agent; here its entries are unknown. - status := statusUnknown - if a := agents.ByName(agentName); a != nil && files.current(ctx, a).err == nil { + // An agent whose config cannot be read is warned about once, for the agent; here its entries are unknown. + a := agents.ByName(agentName) + status, path, fix := statusUnknown, e.Agents[agentName].Path, "" + switch { + case a == nil: + case !a.SupportsMCP(): + out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: %s does not take MCP servers; remove drops this record", e.Name, agentDisplayName(agentName))) + default: var err error - status, err = agentStatus(ctx, files, e, a, checkedBinding(check)) - // When the entry itself could not be checked, its warning already names the cause. - if err != nil && check.Err == nil { + status, path, fix, err = agentStatus(ctx, files, e, a, checkedBinding(check)) + // An error the entry check or the agent's config already reported is not warned about again. + if err != nil && !errors.Is(err, check.Err) && !errors.Is(err, files.current(ctx, a).err) { out.Warnings = append(out.Warnings, fmt.Sprintf("MCP server %s: could not check %s: %s", e.Name, agentDisplayName(agentName), err)) } } s.Agents = append(s.Agents, mcpListAgent{ Name: agentName, - Path: filepath.ToSlash(e.Agents[agentName].Path), + Path: filepath.ToSlash(path), Status: status, + fix: fix, }) } p.Servers = append(p.Servers, s) @@ -274,29 +293,35 @@ func worseStatus(a, b string) string { return a } -// agentStatus compares the server's entry for agent a with the agent's config, which must have been read. An agent -// whose config moved is path_changed: the entry is in the file the record names, which this command does not read. -// pin is the server's binding file, which decides ownership. err is set when the entry cannot be checked for ownership. -func agentStatus(ctx context.Context, files *agentFiles, rec mcp.Entry, a *agents.Agent, pin bindingFile) (string, error) { - current, err := files.currentPath(ctx, a) +// agentStatus compares the server's entry for agent a with the entry that remove acts on (see locateEntry). It returns +// the status, the path of the file the entry is in, and how to clear a modified entry. A recorded entry is path_changed +// when the agent now reads another file: the record names the file the entry was written to, which the agent no longer +// reads. pin decides ownership. err is set when the entry cannot be located or checked. +func agentStatus(ctx context.Context, files *agentFiles, rec mcp.Entry, a *agents.Agent, pin bindingFile) (status, path, fix string, err error) { + loc, err := files.locateEntry(ctx, rec, a) if err != nil { - return statusUnknown, err + return statusUnknown, rec.Agents[a.Name].Path, "", err } - if !mcp.SamePath(rec.Agents[a.Name].Path, current) { - return agentStatusPathChanged, nil + if !loc.found { + return agentStatusMissingOnDisk, loc.path, "", nil } - entry, ok := files.file(a, current).entries[rec.Name] - if !ok { - return agentStatusMissingOnDisk, nil + if loc.recorded { + current, err := files.currentPath(ctx, a) + if err != nil { + return statusUnknown, loc.path, "", err + } + if !mcp.SamePath(loc.path, current) { + return agentStatusPathChanged, loc.path, "", nil + } } - owned, err := pin.owns(ctx, rec, entry) + owned, err := pin.owns(ctx, rec, loc.entry) if err != nil { - return statusUnknown, err + return statusUnknown, loc.path, "", err } if !owned { - return agentStatusModified, nil + return agentStatusModified, loc.path, changedEntryFix(rec.Name, loc.path, loc.entry), nil } - return agentStatusInstalled, nil + return agentStatusInstalled, loc.path, "", nil } // unmanagedKind names how an entry reaches managed MCP servers without being recorded for its agent, or returns "" @@ -352,8 +377,7 @@ func renderMcpList(ctx context.Context, out mcpListOutput, profileName string) { } for _, a := range s.Agents { if a.Status == agentStatusModified { - cmdio.LogString(ctx, fmt.Sprintf(" changed outside this CLI in %s: delete the entry from %s by hand and run `%s` again, or add the server again with --force", - agentDisplayName(a.Name), a.Path, mcp.RemoveNamesCommand(s.Name))) + cmdio.LogString(ctx, fmt.Sprintf(" changed outside this CLI in %s: %s", agentDisplayName(a.Name), a.fix)) } } } diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index 6d9fe0142a9..0df2dd38e8d 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -15,6 +15,7 @@ import ( "github.com/databricks/cli/libs/aitools/mcp/agentconfig" "github.com/databricks/cli/libs/aitools/mcpconfig" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/shellquote" "github.com/databricks/cli/libs/telemetry/protos" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -274,7 +275,7 @@ func TestBuildMcpListUnknownServerIsWarnedNotOK(t *testing.T) { out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.NotEmpty(t, out.Warnings) - assert.Contains(t, out.Warnings[0], "MCP server github-logfood") + assert.Contains(t, out.Warnings[0], filepath.ToSlash(broken)+": failed to read Databricks profiles", "the file is warned about once, by name") require.Len(t, out.Profiles, 2) logfood := out.Profiles[0] @@ -490,7 +491,8 @@ func TestRenderMcpListNamesTheFileAndTheRepair(t *testing.T) { assert.Contains(t, text, "broken: it was set up for workspace 111, but profile \"logfood\" now points at workspace 222; run `databricks aitools mcp remove --names genie_one_mcp-query` and add it again") assert.Contains(t, text, "broken: it was set up for https://adb-old.test, but profile \"logfood\" now points at https://adb-1.test; run `databricks aitools mcp remove --names github-moved` and add it again") assert.Contains(t, text, "Profile gone profile (profile not found in "+shownPath+")") - assert.Contains(t, text, "broken: run `databricks aitools mcp remove --names github-gone` or `DATABRICKS_CONFIG_FILE="+shownPath+" databricks auth login --host https://adb-old.test --profile 'gone profile'`") + // The config path is quoted when it has characters a shell would read, such as the colon of a Windows drive. + assert.Contains(t, text, "broken: run `databricks aitools mcp remove --names github-gone` or `DATABRICKS_CONFIG_FILE="+shellquote.BashArg(shownPath)+" databricks auth login --host https://adb-old.test --profile 'gone profile'`") assert.Contains(t, text, "Profile nohost (profile has no host in "+shownPath+")") assert.NotContains(t, text, "Warning", "every entry in this test can be checked") } @@ -598,7 +600,7 @@ func TestRenderMcpListLoginHintNamesCheckedFile(t *testing.T) { { name: "environment names another file", environment: filepath.Join(t.TempDir(), "other.cfg"), - login: "`DATABRICKS_CONFIG_FILE=" + shownChecked + " databricks auth login --host https://adb-1.test --profile logfood`", + login: "`DATABRICKS_CONFIG_FILE=" + shellquote.BashArg(shownChecked) + " databricks auth login --host https://adb-1.test --profile logfood`", }, { name: "environment names no file", @@ -703,3 +705,162 @@ func TestProfileHeaderNamesPinnedConfigFile(t *testing.T) { assert.NotEqual(t, profileHeader(first), profileHeader(second)) assert.Equal(t, "Profile logfood (https://adb-1.test)", profileHeader(unpinned)) } + +// TestRenderMcpListHintForDatabricksEntryOmitsForce checks the hint for an entry this CLI wrote that serves another +// binding now: add refuses it whatever --force says, so the hint says to delete it by hand and does not offer --force. +func TestRenderMcpListHintForDatabricksEntryOmitsForce(t *testing.T) { + home := withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + saveState(t, entry) + claudePath := filepath.Join(home, ".claude.json") + editEntry(t, claudePath, entry.Name, func(server map[string]any) { setServeFlag(t, server, "--profile", "other") }) + + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + renderMcpList(ctx, out, "") + assert.Contains(t, stderr.String(), " changed outside this CLI in Claude Code: delete the entry from "+filepath.ToSlash(claudePath)+ + " by hand and run `databricks aitools mcp remove --names genie_one_mcp-logfood` again\n") + assert.NotContains(t, stderr.String(), "--force") +} + +// TestBuildMcpListWarnsOncePerUnreadableProfileFile checks that a config file which cannot be read is one warning, however +// many servers read it. Both servers here read the default file. +func TestBuildMcpListWarnsOncePerUnreadableProfileFile(t *testing.T) { + home := withHome(t) + require.NoError(t, os.WriteFile(filepath.Join(home, ".databrickscfg"), []byte("[broken\n"), 0o600)) + saveState(t, + mcp.Entry{Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", Command: testDatabricksCommand}, + mcp.Entry{Name: "github-dogfood", Service: "system.ai.github", Profile: "dogfood", Host: "https://adb-2.test", Command: testDatabricksCommand}, + ) + + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + var warnings []string + for _, w := range out.Warnings { + if strings.Contains(w, "failed to read Databricks profiles") { + warnings = append(warnings, w) + } + } + require.Len(t, warnings, 1, "one file, one warning: %v", out.Warnings) + assert.NotContains(t, warnings[0], "genie", "the warning is for the file, not for a server") + for _, p := range out.Profiles { + assert.Equal(t, statusUnknown, p.Status, "every profile of the file is unknown") + } +} + +// TestBuildMcpListWarnsForOwnershipErrorWithAnotherCause checks that an ownership error is warned about when the entry +// check failed for another reason. Here the profile file cannot be read, and the agent's entry pins a file whose name +// cannot be resolved: two causes, so two warnings. +func TestBuildMcpListWarnsForOwnershipErrorWithAnotherCause(t *testing.T) { + home := withHome(t) + require.NoError(t, os.WriteFile(filepath.Join(home, ".databrickscfg"), []byte("[broken\n"), 0o600)) + claude := agents.ByName("claude-code") + entry := seedInstall(t, claude, "github-logfood", "system.ai.github", "logfood", "https://adb-1.test") + saveState(t, entry) + claudePath := filepath.Join(home, ".claude.json") + editEntry(t, claudePath, entry.Name, func(server map[string]any) { + server["env"] = map[string]any{mcpconfig.ConfigFileEnv: "unresolvable\x00.cfg"} + }) + + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + var ownership []string + for _, w := range out.Warnings { + if strings.Contains(w, "MCP server github-logfood: could not check Claude Code") { + ownership = append(ownership, w) + } + } + require.Len(t, ownership, 1, "the agent's check has its own cause: %v", out.Warnings) + assert.Equal(t, statusUnknown, out.Profiles[0].Servers[0].Agents[0].Status) +} + +// TestBuildMcpListRecordForAgentWithoutMCPIsUnknown checks a record for a registry agent that takes no MCP servers. It +// is not a config that failed to read: the warning says the agent takes no servers, and remove drops the record. +func TestBuildMcpListRecordForAgentWithoutMCPIsUnknown(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + pi := agents.ByName("pi") + require.NotNil(t, pi) + require.False(t, pi.SupportsMCP()) + saveState(t, mcp.Entry{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-1.test", Command: testDatabricksCommand, + Agents: map[string]mcp.AgentRecord{pi.Name: {Path: "/x/pi.json", Scope: "user"}}, + }) + + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + assert.Equal(t, []string{"MCP server github-logfood: Pi does not take MCP servers; remove drops this record"}, out.Warnings) + require.Len(t, out.Profiles, 1) + require.Len(t, out.Profiles[0].Servers, 1) + assert.Equal(t, statusUnknown, out.Profiles[0].Servers[0].Agents[0].Status) +} + +// TestBuildMcpListAndRemoveAgreeAfterConfigMoved checks that list reports the entry where remove acts on it, when the +// agent's config directory moved. The entry is either in the file the record names, which the agent no longer reads, or +// in the file the agent reads now, with the record naming the old file. +func TestBuildMcpListAndRemoveAgreeAfterConfigMoved(t *testing.T) { + cases := []struct { + name string + // entryIn is the file that holds the entry: "recorded" or "current". + entryIn string + status string + // holds is the file that keeps the entry after remove: "" when no file keeps it. + removedFrom string + }{ + {name: "entry in the recorded file", entryIn: "recorded", status: agentStatusPathChanged, removedFrom: "recorded"}, + {name: "entry in the file the agent reads now", entryIn: "current", status: agentStatusInstalled, removedFrom: "current"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + withHome(t) + writeDatabricksCfg(t, "[logfood]\nhost = https://adb-1.test\ntoken = t\n") + claude := agents.ByName("claude-code") + oldDir := t.TempDir() + t.Setenv("CLAUDE_CONFIG_DIR", oldDir) + entry := seedInstall(t, claude, "genie_one_mcp-logfood", "system.ai.genie_one_mcp", "logfood", "https://adb-1.test") + oldPath := entry.Agents[claude.Name].Path + saveState(t, entry) + + newDir := t.TempDir() + newPath := filepath.Join(newDir, ".claude.json") + t.Setenv("CLAUDE_CONFIG_DIR", newDir) + if tc.entryIn == "current" { + // The user moved the config with the directory: the entry is in the new file and the old one is gone. + data, err := os.ReadFile(oldPath) + require.NoError(t, err) + require.NoError(t, os.WriteFile(newPath, data, 0o600)) + require.NoError(t, os.Remove(oldPath)) + } else { + require.NoError(t, os.WriteFile(newPath, []byte("{}"), 0o600)) + } + + out, err := buildMcpList(t.Context(), "") + require.NoError(t, err) + require.Len(t, out.Profiles, 1) + listed := out.Profiles[0].Servers[0].Agents[0] + assert.Equal(t, tc.status, listed.Status) + wantPath := filepath.ToSlash(oldPath) + if tc.removedFrom == "current" { + wantPath = filepath.ToSlash(newPath) + } + assert.Equal(t, wantPath, listed.Path, "list names the file remove acts on") + + stdout, _, err := runMcpCmd(t, "remove", "--names", entry.Name, "--output", "json") + require.NoError(t, err) + removed := readRemoveOutput(t, stdout.String()) + require.Len(t, removed.Removed, 1, "remove takes the entry from the file list named") + assert.Empty(t, removed.Skipped) + + acted := oldPath + if tc.removedFrom == "current" { + acted = newPath + } + if data, err := os.ReadFile(acted); err == nil { + assert.NotContains(t, string(data), entry.Name, "the entry is gone from %s", acted) + } + }) + } +} diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 3dbb6deffc9..eba147d5ffe 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -340,30 +340,6 @@ func checkTargetsInstalled(selected []mcp.Entry, targets []*agents.Agent) error return nil } -// entryFile returns the config file that holds the server's entry for agent a, and its entries. That is the file the -// record names, unless the file does not hold the entry and the agent now reads its config from another file: then that -// file, which may hold it, since the user may have moved the config with the agent's directory. A recorded file that -// cannot be read is an error, since it may be the one that holds the entry. -func entryFile(ctx context.Context, files *agentFiles, e mcp.Entry, a *agents.Agent) (string, agentFile, error) { - recorded := e.Agents[a.Name].Path - file := files.file(a, recorded) - if file.err != nil { - return "", agentFile{}, file.err - } - if _, found := file.entries[e.Name]; found { - return recorded, file, nil - } - current, err := files.currentPath(ctx, a) - if err != nil { - return "", agentFile{}, err - } - if mcp.SamePath(current, recorded) { - return recorded, file, nil - } - file = files.file(a, current) - return current, file, file.err -} - // keptReason says why an entry is left in place, and how to clear it. func keptReason(e mcp.Entry, a *agents.Agent, path string, entry map[string]any) string { return fmt.Sprintf("%s has an entry named %s that was changed outside this CLI; left in place. To remove it, %s", @@ -371,25 +347,24 @@ func keptReason(e mcp.Entry, a *agents.Agent, path string, entry map[string]any) } // removeFromAgent removes the server's entry for agent a, but only when the entry there is the one this CLI wrote. The -// entry is looked for as entryFile finds it. A file that has no entry of the name is pruned: the record goes without an -// edit. +// entry is looked for where locateEntry finds it. An agent config that holds no entry is pruned: the record goes without +// an edit. func removeFromAgent(ctx context.Context, files *agentFiles, e mcp.Entry, a *agents.Agent, pin bindingFile) (removeOutcome, string, error) { - path, file, err := entryFile(ctx, files, e, a) + loc, err := files.locateEntry(ctx, e, a) if err != nil { return 0, "", err } - current, found := file.entries[e.Name] - if !found { + if !loc.found { return removePruned, "", nil } - owned, err := pin.owns(ctx, e, current) + owned, err := pin.owns(ctx, e, loc.entry) if err != nil { return 0, "", err } if !owned { - return removeKept, keptReason(e, a, path, current), nil + return removeKept, keptReason(e, a, loc.path, loc.entry), nil } - if _, err := agentconfig.RemoveAt(a, path, e.Name); err != nil { + if _, err := agentconfig.RemoveAt(a, loc.path, e.Name); err != nil { return 0, "", err } return removeDeleted, "", nil From 5436af545ed47bc631e55c6331f37bdc7dc4e306 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 21:34:44 +0000 Subject: [PATCH 24/26] aitools mcp tests: quote config paths in hint expectations, and regenerate list-and-remove Login hints quote a config path that a shell would read differently, such as a Windows temp path with a tilde. The binding and list tests expect the quoted form (shellquote.BashArg), as the code writes it. The acceptance drift scenario's golden has the bare path, so test.toml strips the quotes around a [TEST_TMP_DIR] path. The list-and-remove golden shows the remove skip reason, which now names the remove command in backticks. Co-authored-by: Isaac --- acceptance/cmd/aitools/mcp/list-and-remove/output.txt | 4 ++-- acceptance/cmd/aitools/mcp/test.toml | 5 +++++ libs/aitools/mcp/binding_test.go | 7 ++++--- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt index 248be55bb3e..145ee12df94 100644 --- a/acceptance/cmd/aitools/mcp/list-and-remove/output.txt +++ b/acceptance/cmd/aitools/mcp/list-and-remove/output.txt @@ -130,7 +130,7 @@ Profile logfood ([DATABRICKS_URL], config file [TEST_TMP_DIR]/.databrickscfg) >>> [CLI] aitools mcp remove --names github-logfood,genie_one_mcp-logfood Removed genie_one_mcp-logfood system.ai.genie_one_mcp profile logfood (Claude Code) -Skipped github-logfood: Claude Code has an entry named github-logfood that was changed outside this CLI; left in place. To remove it, delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run remove again, or add the server again with --force +Skipped github-logfood: Claude Code has an entry named github-logfood that was changed outside this CLI; left in place. To remove it, delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run `databricks aitools mcp remove --names github-logfood` again, or add the server again with --force >>> jq .mcpServers | keys home/.claude.json [ @@ -158,7 +158,7 @@ Skipped github-logfood: Claude Code has an entry named github-logfood that was c { "name": "github-logfood", "agent": "claude-code", - "reason": "Claude Code has an entry named github-logfood that was changed outside this CLI; left in place. To remove it, delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run remove again, or add the server again with --force" + "reason": "Claude Code has an entry named github-logfood that was changed outside this CLI; left in place. To remove it, delete the entry from [TEST_TMP_DIR]/home/.claude.json by hand and run `databricks aitools mcp remove --names github-logfood` again, or add the server again with --force" } ] } diff --git a/acceptance/cmd/aitools/mcp/test.toml b/acceptance/cmd/aitools/mcp/test.toml index 340a89ac46e..b1d08986b6a 100644 --- a/acceptance/cmd/aitools/mcp/test.toml +++ b/acceptance/cmd/aitools/mcp/test.toml @@ -13,3 +13,8 @@ Env.APPDATA = "" [[Repls]] Old = '\\\\' New = '/' + +# The login hint quotes a config path that a shell would read differently, such as the colon of a Windows drive. +[[Repls]] +Old = "'(\\[TEST_TMP_DIR\\][^']*)'" +New = "$1" diff --git a/libs/aitools/mcp/binding_test.go b/libs/aitools/mcp/binding_test.go index b15625832db..2d58a95d138 100644 --- a/libs/aitools/mcp/binding_test.go +++ b/libs/aitools/mcp/binding_test.go @@ -13,6 +13,7 @@ import ( "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/shellquote" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -127,7 +128,7 @@ func TestBindProfileAbsent(t *testing.T) { Host: bindingTestHost, ConfigFile: path, }}}, - want: fmt.Sprintf(`MCP server github-gone is bound to Databricks profile "gone", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile gone or remove the server with: databricks aitools mcp remove --names github-gone`, filepath.ToSlash(path), filepath.ToSlash(path)), + want: fmt.Sprintf(`MCP server github-gone is bound to Databricks profile "gone", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile gone or remove the server with: databricks aitools mcp remove --names github-gone`, filepath.ToSlash(path), shellquote.BashArg(filepath.ToSlash(path))), }, { name: "without state entry", @@ -663,7 +664,7 @@ func TestBindProfileWithoutHost(t *testing.T) { }) requireBindError(t, err, mcp.BindProfileNotFound) resolved := filepath.ToSlash(bindingTestResolved(t, path)) - assert.Equal(t, fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "logfood", which has no host in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile logfood or remove the server with: databricks aitools mcp remove --names github-logfood`, resolved, resolved), err.Error()) + assert.Equal(t, fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "logfood", which has no host in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile logfood or remove the server with: databricks aitools mcp remove --names github-logfood`, resolved, shellquote.BashArg(resolved)), err.Error()) } // TestBindHostMetadataFailureIsNotAuthFailure checks that a host whose metadata cannot be fetched does @@ -777,7 +778,7 @@ func TestBindRecreateHintQuotesValues(t *testing.T) { }) requireBindError(t, err, mcp.BindProfileNotFound) want := fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "my profile", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile 'my profile' or remove the server with: databricks aitools mcp remove --names github-logfood`, - filepath.ToSlash(bindingTestResolved(t, cfgPath)), filepath.ToSlash(bindingTestResolved(t, cfgPath))) + filepath.ToSlash(bindingTestResolved(t, cfgPath)), shellquote.BashArg(filepath.ToSlash(bindingTestResolved(t, cfgPath)))) assert.Equal(t, want, err.Error()) } From f1d49a50eca112f51c2967c9c72c879cc46bbfff Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Thu, 12 Nov 2026 22:00:00 +0000 Subject: [PATCH 25/26] Compare the unreadable-profile warning with the resolved path The warning names the config file as resolved, which on Windows expands the short name of the temp directory, so the test resolves it the same way. Co-authored-by: Isaac --- cmd/aitools/mcp_list_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index 0df2dd38e8d..b614e3d9e0d 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -275,7 +275,10 @@ func TestBuildMcpListUnknownServerIsWarnedNotOK(t *testing.T) { out, err := buildMcpList(t.Context(), "") require.NoError(t, err) require.NotEmpty(t, out.Warnings) - assert.Contains(t, out.Warnings[0], filepath.ToSlash(broken)+": failed to read Databricks profiles", "the file is warned about once, by name") + // The warning names the resolved file, which on Windows expands the short name of the temp directory. + resolved, err := filepath.EvalSymlinks(broken) + require.NoError(t, err) + assert.Contains(t, out.Warnings[0], filepath.ToSlash(resolved)+": failed to read Databricks profiles", "the file is warned about once, by name") require.Len(t, out.Profiles, 2) logfood := out.Profiles[0] From 95c5e542fba634246505a7ec12d9a21bbd222eb6 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Fri, 13 Nov 2026 14:48:06 +0000 Subject: [PATCH 26/26] Expect STATE_INVALID for an unreadable state file in mcp list Main classifies a StateError as STATE_INVALID, so a state file that does not parse reports that category in the JSON listing rather than UNCATEGORIZED. Co-authored-by: Isaac --- cmd/aitools/mcp_list_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/aitools/mcp_list_test.go b/cmd/aitools/mcp_list_test.go index b614e3d9e0d..c09a9b36202 100644 --- a/cmd/aitools/mcp_list_test.go +++ b/cmd/aitools/mcp_list_test.go @@ -556,7 +556,7 @@ func TestMcpListJSONReportsStateError(t *testing.T) { var out mcpListOutput require.NoError(t, json.Unmarshal(stdout.Bytes(), &out), stdout.String()) assert.NotEmpty(t, out.Error) - assert.Equal(t, protos.AitoolsErrorCategoryUncategorized, out.ErrorCategory) + assert.Equal(t, protos.AitoolsErrorCategoryStateInvalid, out.ErrorCategory) assert.Empty(t, out.Profiles) }