From 442fe58f137af0846297294e59d4d61fa463edcf Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Fri, 13 Nov 2026 15:00:02 +0000 Subject: [PATCH 01/16] Add interactive pickers to aitools mcp add and remove mcp add and mcp remove prompt for the profile, the services and the location when run in a terminal without flags. The agent picker and the proceed prompt are shared with install. The picker prompts use one help text, and a declined prompt ends with the same cancelled message. Main's install flow keeps its own scope title and plan output. The mcp add picker uses the global scope, which is the scope mcp add reports. Co-authored-by: Isaac --- acceptance/cmd/aitools/mcp/hidden/output.txt | 34 +- .../mcp/repair-and-warnings/output.txt | 2 +- cmd/aitools/install.go | 21 + cmd/aitools/mcp.go | 2 +- cmd/aitools/mcp_add.go | 503 ++++++++++--- cmd/aitools/mcp_add_test.go | 668 +++++++++++++++++- cmd/aitools/mcp_list.go | 15 +- cmd/aitools/mcp_login.go | 7 +- cmd/aitools/mcp_pickers.go | 346 +++++++++ cmd/aitools/mcp_pickers_test.go | 584 +++++++++++++++ cmd/aitools/mcp_remove.go | 55 +- cmd/aitools/mcp_remove_test.go | 135 +++- cmd/aitools/uninstall.go | 2 +- libs/aitools/mcp/agentconfig/writer.go | 22 + libs/aitools/mcp/binding.go | 21 +- libs/aitools/mcp/binding_test.go | 40 ++ libs/cmdio/io.go | 6 +- libs/cmdio/prompt.go | 2 +- libs/cmdio/select.go | 2 +- 19 files changed, 2275 insertions(+), 192 deletions(-) create mode 100644 cmd/aitools/mcp_pickers.go create mode 100644 cmd/aitools/mcp_pickers_test.go diff --git a/acceptance/cmd/aitools/mcp/hidden/output.txt b/acceptance/cmd/aitools/mcp/hidden/output.txt index add4178e1bb..f6d269ce565 100644 --- a/acceptance/cmd/aitools/mcp/hidden/output.txt +++ b/acceptance/cmd/aitools/mcp/hidden/output.txt @@ -38,11 +38,13 @@ Install Databricks managed MCP servers into coding agents, bound to a Databricks Each server runs through 'databricks aitools mcp serve' with that profile's credentials. Services come from --names: full names such as system.ai.github, or leaf names such as github. Leaf names -resolve in --location, which defaults to system.ai, or to the one schema that the full names in --names share when there are no leaf names. -Agents come from --agents. Without it, every detected MCP-capable agent is used. +resolve in --location, which defaults to system.ai, or to the one schema that the full names in --names share. +Agents come from --agents. -Interactive selection is not available yet: in a terminal, pass both --names and --agents. -With --output json, both are required. +In a terminal, the command asks for whatever is not given: the profile, the servers and the agents (detected +agents are pre-checked). It confirms the plan when it asked for any of them, and it asks before each sign-in unless +--login or --no-login is given. Without a terminal, --names is required and the agents default to every detected +MCP-capable agent. With --output json, --names and --agents are required. Supported agents: claude-code, cursor, codex, opencode, copilot, antigravity, gemini @@ -54,17 +56,17 @@ Examples: databricks aitools mcp add --names github,web_search --agents claude-code,cursor --profile dogfood Flags: - --agents string Agents to install for, comma-separated (default: every detected MCP-capable agent) - --force[=true|false] Overwrite an existing server with the same name that this CLI did not write - -h, --help[=true|false] help for add - --location string Schema to resolve leaf names in, as . (default: system.ai, or the one schema that the full names in --names share when there are no leaf names) - --login[=true|false] Sign in to each sign-in-required server that was installed, after the installs - --name string Server name to use instead of the generated one; only with exactly one service - --names string Services to install: full names (system.ai.github) or leaf names (github), comma-separated - --no-login[=true|false] Do not sign in; print the login commands for sign-in-required servers (default) + --agents string Agents to install for, comma-separated (default: a picker in a terminal; otherwise every detected MCP-capable agent) + --force Overwrite an existing server with the same name that this CLI did not write + -h, --help help for add + --location string Schema to resolve leaf names in, as . (default: system.ai, or the one schema that the full names in --names share) + --login Sign in to each sign-in-required server that was installed, after the installs + --name string Server name to use instead of the generated one; only with exactly one service + --names string Services to install: full names (system.ai.github) or leaf names (github), comma-separated + --no-login Do not sign in; print the login commands for sign-in-required servers (default without a terminal; in a terminal, the default asks for each one) Global Flags: - --debug[=true|false] enable debug logging - -o, --output type output type: text or json (default text) - -p, --profile string ~/.databrickscfg profile - -t, --target string bundle target to use (if applicable) + --debug enable debug logging + -o, --output type output type: text or json (default text) + -p, --profile string ~/.databrickscfg profile + -t, --target string bundle target to use (if applicable) diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt index e49fd48e191..e1e7992e138 100644 --- a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt @@ -55,4 +55,4 @@ Error: no installed MCP server named orphan; Claude Code has an entry named orph No Databricks MCP servers to remove. >>> musterr [CLI] aitools mcp remove --names genie_one_mcp-logfood --agents cursor -Error: no selected MCP server is installed for Cursor +Error: no MCP server is installed for Cursor diff --git a/cmd/aitools/install.go b/cmd/aitools/install.go index 2e792a82b9c..74521eeff64 100644 --- a/cmd/aitools/install.go +++ b/cmd/aitools/install.go @@ -20,10 +20,19 @@ import ( "github.com/spf13/cobra" ) +// Prompt text shared by install, uninstall and the mcp commands. +const ( + // multiSelectHelp is the description of the multi-select prompts of install and mcp add and remove. + multiSelectHelp = "space to toggle, enter to confirm" + // cancelledMessage is printed when the user declines at a prompt, and the command ends without a change. + cancelledMessage = "Cancelled." +) + // Package-level seams for testability. Tests override these via helpers in // install_test.go. var ( promptAgentSelection = defaultPromptAgentSelection + promptProceed = defaultPromptProceed installSkillsForAgentsFn = installer.InstallSkillsForAgents installPluginForAgentFn = installer.InstallPluginForAgent recordPluginInstallsFn = installer.RecordPluginInstalls @@ -509,6 +518,18 @@ func agentStateLabel(s agents.DisplayState) string { } } +func defaultPromptProceed() (bool, error) { + proceed := true + err := huh.NewConfirm(). + Title("Proceed?"). + Value(&proceed). + Run() + if err != nil { + return false, err + } + return proceed, nil +} + func defaultPromptAgentSelection(_ context.Context, scope string, choices []agentChoice) ([]*agents.Agent, error) { options := make([]huh.Option[string], 0, len(choices)) byName := make(map[string]*agents.Agent, len(choices)) diff --git a/cmd/aitools/mcp.go b/cmd/aitools/mcp.go index 961969a0c07..ff57cdd3df9 100644 --- a/cmd/aitools/mcp.go +++ b/cmd/aitools/mcp.go @@ -130,7 +130,7 @@ func resolveProfile(ctx context.Context, flagValue string) (string, error) { case 1: return profiles[0].Name, nil } - return "", failure(categoryProfileRequired, "several workspace profiles exist; pass --profile. Found: %s", strings.Join(profiles.Names(), ", ")) + return "", failureWithCause(categoryProfileRequired, &profileChoice{profiles: profiles}, "several workspace profiles exist; pass --profile. Found: %s", strings.Join(profiles.Names(), ", ")) } // mcpWorkspaceProfile reports whether auto-detect may pick p. It accepts the profiles that --profile accepts: a diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index 4488e1349a9..4305c6020eb 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -27,6 +27,7 @@ import ( "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/apierr" "github.com/databricks/databricks-sdk-go/config" + "github.com/databricks/databricks-sdk-go/service/catalog" "github.com/spf13/cobra" ) @@ -95,16 +96,31 @@ type addAgentOutput struct { } // addPlan is one service to install for the profile. failed holds the agents that cannot take the server, with the -// reason; they are not written. note explains the name when it got a suffix. replaced holds the agents whose entry -// --force replaces. +// reason; they are not written. type addPlan struct { - service mcp.Service - name string - failed map[*agents.Agent]error - note string + service mcp.Service + name string + failed map[*agents.Agent]error + // note explains the name when it got a suffix. + note string + // reasserted holds the agents whose config already has this server as the write would leave it. + reasserted map[*agents.Agent]bool + // updated holds the agents whose config has a Databricks entry for this server under its name that the write changes. + updated map[*agents.Agent]bool + // replaced holds the agents whose config has an entry under this name that this CLI did not write. Under --force + // the write replaces it. replaced map[*agents.Agent]bool } +// agentSource says where the agents of an add came from. It is shown in the header. +type agentSource string + +const ( + agentsNamed agentSource = "named with --agents" + agentsDetected agentSource = "detected" + agentsPicked agentSource = "selected" +) + // addRequest is what one `mcp add` run applies to every server. type addRequest struct { // jsonMode suppresses the text output; the JSON document is the only output. @@ -113,7 +129,7 @@ type addRequest struct { host string workspaceID string agents []*agents.Agent - explicit bool + agentSource agentSource force bool binary string // configFile is the resolved config file that the servers bind to. @@ -122,11 +138,12 @@ type addRequest struct { pinned string // env is the entry env: DATABRICKS_CONFIG_FILE when it was set. env map[string]string - // refused holds the agents named with --agents that are not installed, with the reason. Their - // config is not written. + // refused holds the agents that are not installed or whose config cannot be read, with the reason. Their config is not written. refused map[*agents.Agent]error // login signs in to the sign-in-required servers after they are installed. login bool + // askLogin asks, per sign-in-required server, whether to sign in after it is installed. + askLogin bool } // slashPaths rewrites the agent config paths of the document to forward slashes, as the text output @@ -151,10 +168,12 @@ Each server runs through 'databricks aitools mcp serve' with that profile's cred Services come from --names: full names such as system.ai.github, or leaf names such as github. Leaf names resolve in --location, which defaults to system.ai, or to the one schema that the full names in --names share when there are no leaf names. -Agents come from --agents. Without it, every detected MCP-capable agent is used. +Agents come from --agents. -Interactive selection is not available yet: in a terminal, pass both --names and --agents. -With --output json, both are required. +In a terminal, the command asks for whatever is not given: the profile, the servers and the agents (detected +agents are pre-checked). It confirms the plan when it asked for any of them, and it asks before each sign-in unless +--login or --no-login is given. Without a terminal, --names is required and the agents default to every detected +MCP-capable agent. With --output json, --names and --agents are required. Supported agents: ` + strings.Join(mcpAgentNames(), ", "), Example: ` # Install GitHub and web search for Claude Code and Cursor, bound to the dogfood profile @@ -191,23 +210,29 @@ Supported agents: ` + strings.Join(mcpAgentNames(), ", "), cmd.Flags().StringVar(&f.names, "names", "", "Services to install: full names (system.ai.github) or leaf names (github), comma-separated") cmd.Flags().StringVar(&f.location, "location", "", "Schema to resolve leaf names in, as . (default: system.ai, or the one schema that the full names in --names share when there are no leaf names)") - cmd.Flags().StringVar(&f.agents, "agents", "", "Agents to install for, comma-separated (default: every detected MCP-capable agent)") + cmd.Flags().StringVar(&f.agents, "agents", "", "Agents to install for, comma-separated (default: a picker in a terminal; otherwise every detected MCP-capable agent)") cmd.Flags().StringVar(&f.name, "name", "", "Server name to use instead of the generated one; only with exactly one service") cmd.Flags().BoolVar(&f.force, "force", false, "Overwrite an existing server with the same name that this CLI did not write") cmd.Flags().BoolVar(&f.login, "login", false, "Sign in to each sign-in-required server that was installed, after the installs") - cmd.Flags().BoolVar(&f.noLogin, "no-login", false, "Do not sign in; print the login commands for sign-in-required servers (default)") + cmd.Flags().BoolVar(&f.noLogin, "no-login", false, "Do not sign in; print the login commands for sign-in-required servers (default without a terminal; in a terminal, the default asks for each one)") return cmd } -// runMcpAdd installs the requested servers and fills out. Refusals that need no request come before the first one. -// Named agents' failures are returned as agentErrors; detected agents only report theirs. A server that reaches no agent -// fails the run. +// runMcpAdd installs the requested servers and fills out. Every refusal that needs no request comes before +// the first one: the flags, the agents named with --agents, the binary name, the binding of each service that a +// recorded entry holds, and the server names. A server that no agent can take is refused the same way, unless a +// detected or picked agent can take it. A failure of an agent named with --agents is returned as an agentErrors; +// detected and picked agents only report theirs. A server that reaches no agent fails the run. +// +// Without --names, in a terminal, the services are picked from the workspace, so the workspace is read before the +// plan. The services named with --names are planned first, and the workspace is read after that. func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode bool, out *addOutput) error { names := splitAndTrim(f.names) agentNames := splitAndTrim(f.agents) if err := validateMCPAddFlags(ctx, f, names, agentNames, jsonMode); err != nil { return err } + interactive := !jsonMode && cmdio.IsPromptSupported(ctx) location, fullNames, err := resolveServices(f.location, names) if err != nil { return err @@ -215,36 +240,43 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode if f.name != "" && len(fullNames) != 1 { return failure(protos.AitoolsErrorCategoryInvalidFlags, "--name needs exactly one service in --names") } - targets, explicit, detectErrs, err := targetAgents(ctx, agentNames) - if err != nil { - return err + var named []*agents.Agent + if len(agentNames) > 0 { + if named, err = resolveMCPAgents(agentNames); err != nil { + return err + } + } + // Without a terminal the agents are chosen before the binary and the profile are checked, so that a run with no + // agent reports that first. A terminal chooses them once the profile is known. + var targets []*agents.Agent + var source agentSource + var detectErrs map[*agents.Agent]error + if !interactive { + if targets, source, detectErrs, err = chooseAgents(ctx, named, false); err != nil { + return err + } } binary, absolute := mcpBinaryPath() if !mcpconfig.IsDatabricksBinary(binary) { return failure(protos.AitoolsErrorCategoryUncategorized, "%s is not the databricks binary; coding agents start MCP servers with databricks or databricks.exe", filepath.ToSlash(binary)) } - held, unreadable := readAgentEntries(ctx, targets) - var refused map[*agents.Agent]error - if explicit { - refused = refusedAgents(ctx, targets) - } - for a, err := range unreadable { - if refused == nil { - refused = map[*agents.Agent]error{} - } - refused[a] = err + // A named agent that is not installed, and a detected agent whose detection failed, are refused before any request. + // Nothing can be written when every agent is refused, so the refusals end the run. A terminal that picks its agents + // checks them once the pick is made. + refused := map[*agents.Agent]error{} + if len(named) > 0 { + refused = refusedAgents(ctx, named) } for a, err := range detectErrs { - if refused == nil { - refused = map[*agents.Agent]error{} - } refused[a] = err } - // Nothing can be written when every agent is refused, so the refusals end the run before any request. Detected - // agents are refused only for an unreadable config, and that ends the run the same way. - if len(refused) == len(targets) { + checked := targets + if len(named) > 0 { + checked = named + } + if len(checked) > 0 && len(refused) == len(checked) { var errs []error - for _, a := range targets { + for _, a := range checked { errs = append(errs, refused[a]) } return withCategory(errors.Join(errs...), errorCategory(errs[0])) @@ -257,7 +289,7 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode return err } ctx = env.Set(ctx, mcpconfig.ConfigFileEnv, configFile) - profileName, err := resolveProfile(ctx, profileFlag(cmd)) + profileName, profilePicked, err := chooseProfile(ctx, profileFlag(cmd), interactive) if err != nil { return err } @@ -267,19 +299,60 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode if err != nil { return err } - for _, name := range fullNames { - if _, err := mcp.CheckBinding(ctx, state, name, profileName, configFile); err != nil { + // Until the services are known, nothing reaches the workspace. A run that picks its services checks the profile here, + // and the agents are chosen before the first request. + pickingServices := len(names) == 0 + var w *databricks.WorkspaceClient + var workspaceID string + var picked []mcp.Service + if pickingServices { + if err := mcp.CheckProfile(profileName, configFile); err != nil { return withExistingProfiles(ctx, state, profileName, err) } + } else if err := checkBindings(ctx, state, fullNames, profileName, configFile); err != nil { + return withExistingProfiles(ctx, state, profileName, err) + } + if interactive { + if targets, source, _, err = chooseAgents(ctx, named, true); err != nil { + return err + } + } + held, unreadable := readAgentEntries(ctx, targets) + for a, err := range unreadable { + refused[a] = err + } + // Nothing can be written when every agent is refused, so the refusals end the run before any request. + if len(refused) == len(targets) { + var errs []error + for _, a := range targets { + errs = append(errs, refused[a]) + } + return withCategory(errors.Join(errs...), errorCategory(errs[0])) + } + // Without --names the services are picked from the workspace, and then checked like the named ones. + if pickingServices { + w, workspaceID, err = connectWorkspace(ctx, out, profileName, configFile, pinned) + if err != nil { + return err + } + if picked, err = chooseServices(ctx, w, addBinding{profile: profileName, configFile: configFile}, pinned, location, state); err != nil { + return err + } + fullNames = serviceFullNames(picked) + if err := checkBindings(ctx, state, fullNames, profileName, configFile); err != nil { + return err + } } in := planInput{ binding: addBinding{profile: profileName, configFile: configFile}, nameFlag: f.name, force: f.force, - explicit: explicit, + explicit: source == agentsNamed, targets: targets, held: held, refused: refused, + binary: binary, + env: pinnedEnv(pinned), } plans, err := planAdds(ctx, in, state, fullNames) if err != nil { @@ -289,23 +362,18 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode return err } - w, err := profileClient(ctx, profileName, configFile, pinned) - if err != nil { - return err - } - out.Host = w.Config.Host - workspaceID, err := auth.ResolveWorkspaceID(ctx, w) - if err != nil { - return describeRequestError(profileName, pinned, fmt.Errorf("cannot read the workspace ID of %s: %w", w.Config.Host, err)) - } - - services, err := mcp.Discover(ctx, w, location) - if err != nil { - return describeRequestError(profileName, pinned, err) - } - picked, err := pickServices(location, fullNames, services) - if err != nil { - return err + if !pickingServices { + w, workspaceID, err = connectWorkspace(ctx, out, profileName, configFile, pinned) + if err != nil { + return err + } + services, err := mcp.Discover(ctx, w, location) + if err != nil { + return describeRequestError(profileName, pinned, err) + } + if picked, err = pickServices(location, fullNames, services); err != nil { + return err + } } for i := range plans { plans[i].service = picked[i] @@ -317,22 +385,34 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode host: w.Config.Host, workspaceID: workspaceID, agents: targets, - explicit: explicit, + agentSource: source, force: f.force, binary: binary, configFile: configFile, pinned: pinned, refused: refused, login: f.login, - } - if pinned != "" { - req.env = map[string]string{mcpconfig.ConfigFileEnv: pinned} + askLogin: interactive && !f.login && !f.noLogin, + env: pinnedEnv(pinned), } if !absolute && !jsonMode { cmdio.LogString(ctx, "Note: databricks is not an absolute path; coding agents must find it on PATH to start the MCP servers.") } printAddHeader(ctx, req) + // A run that names everything asks no question, except the sign-in question of a sign-in-required server. + // The plan is confirmed only when a picker made one of the choices. + if interactive && (profilePicked || pickingServices || source == agentsPicked) { + printAddPlan(ctx, req, plans) + proceed, err := promptProceed() + if err != nil { + return err + } + if !proceed { + cmdio.LogString(ctx, cancelledMessage) + return nil + } + } servers := make([]addServerOutput, 0, len(plans)) for _, plan := range plans { servers = append(servers, installServer(ctx, req, plan)) @@ -344,12 +424,58 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode recordErr := recordInstalls(ctx, req, plans, servers) printAddResults(ctx, req, servers) var signErr error - if req.login { + if req.login || req.askLogin { signErr = signInInstalled(ctx, cmd.ErrOrStderr(), w, req, plans, servers) } return errors.Join(recordErr, signErr, agentFailureError(req, servers)) } +// serviceFullNames returns the full names of services, in order. +func serviceFullNames(services []mcp.Service) []string { + names := make([]string, 0, len(services)) + for _, s := range services { + names = append(names, s.FullName) + } + return names +} + +// connectWorkspace returns a client for the profile and the ID of its workspace, and sets the host in out. +func connectWorkspace(ctx context.Context, out *addOutput, profileName, configFile, pinned string) (*databricks.WorkspaceClient, string, error) { + w, err := profileClient(ctx, profileName, configFile, pinned) + if err != nil { + return nil, "", err + } + out.Host = w.Config.Host + workspaceID, err := auth.ResolveWorkspaceID(ctx, w) + if err != nil { + return nil, "", describeRequestError(profileName, pinned, fmt.Errorf("cannot read the workspace ID of %s: %w", w.Config.Host, err)) + } + return w, workspaceID, nil +} + +// checkBindings returns the first failure of CheckBinding for the services, which makes no request. +func checkBindings(ctx context.Context, state *mcp.State, fullNames []string, profileName, configFile string) error { + for _, name := range fullNames { + if _, err := mcp.CheckBinding(ctx, state, name, profileName, configFile); err != nil { + return err + } + } + return nil +} + +// chooseServices returns the services the user checks in the picker, from the services of location. The services +// the profile already has are rows marked installed, unchecked, so that they can be added to another agent. +func chooseServices(ctx context.Context, w *databricks.WorkspaceClient, b addBinding, pinned, location string, state *mcp.State) ([]mcp.Service, error) { + list := func(ctx context.Context, location string) ([]mcp.Service, error) { + services, err := mcp.Discover(ctx, w, location) + if err != nil { + return nil, describeRequestError(b.profile, pinned, err) + } + return services, nil + } + return pickServicesInteractively(ctx, b, location, state, list) +} + // validateMCPAddFlags rejects flag combinations that cannot run, before anything is read or written. func validateMCPAddFlags(ctx context.Context, f mcpAddFlags, names, agentNames []string, jsonMode bool) error { // A value that names no agent, such as ",", must not fall back to every detected agent. @@ -384,15 +510,13 @@ func validateMCPAddFlags(ctx context.Context, f mcpAddFlags, names, agentNames [ } return nil } - if cmdio.IsPromptSupported(ctx) { - if len(names) == 0 || len(agentNames) == 0 { - return failure(protos.AitoolsErrorCategoryInvalidFlags, "interactive selection is not available yet; pass --names and --agents") - } - return nil - } - if len(names) == 0 { + if len(names) == 0 && !cmdio.IsPromptSupported(ctx) { return failure(protos.AitoolsErrorCategoryInvalidFlags, "--names is required so the command runs without interactive prompts") } + // The picker chooses services in a terminal, and --name needs exactly one of them, which only --names can give. + if f.name != "" && len(names) == 0 { + return failure(protos.AitoolsErrorCategoryInvalidFlags, "--name needs exactly one service; leave out --name to pick services in the picker") + } return nil } @@ -496,13 +620,24 @@ func describeListError(profileName string, err error) error { return withCategory(fmt.Errorf("profile %s: %w", profileName, listErr), category) } -// targetAgents returns the agents named by --agents, or else every detected MCP-capable agent. -// explicit reports whether the names were given. -// detectErrs holds the agents whose detection failed. They are not written, and each reports its failure. -func targetAgents(ctx context.Context, names []string) ([]*agents.Agent, bool, map[*agents.Agent]error, error) { - if len(names) > 0 { - list, err := resolveMCPAgents(names) - return list, true, nil, err +// chooseAgents returns the agents to install for: the ones named with --agents, else the ones the user checks in the +// picker when the session is interactive, else every detected MCP-capable agent. In a terminal with no agent installed +// for MCP, the run is refused here, with the agents that were not found, before any request. detectErrs holds the agents +// whose detection failed. They are not written, and each reports its failure. +func chooseAgents(ctx context.Context, named []*agents.Agent, interactive bool) ([]*agents.Agent, agentSource, map[*agents.Agent]error, error) { + if len(named) > 0 { + return named, agentsNamed, nil, nil + } + if interactive { + choices, notFound := mcpAgentChoices(ctx) + if len(notFound) > 0 { + cmdio.LogString(ctx, "Not found: "+strings.Join(notFound, ", ")) + } + if len(choices) == 0 { + return nil, "", nil, noAgentsError() + } + picked, err := promptAgentSelection(ctx, installer.ScopeGlobal, choices) + return picked, agentsPicked, nil, err } var detected []*agents.Agent var detectErrs map[*agents.Agent]error @@ -520,9 +655,14 @@ func targetAgents(ctx context.Context, names []string) ([]*agents.Agent, bool, m } } if len(detected) == 0 { - return nil, false, nil, failure(protos.AitoolsErrorCategoryUnknownAgent, "no MCP-capable coding agents detected; pass --agents with one of: %s", strings.Join(mcpAgentNames(), ", ")) + return nil, "", nil, noAgentsError() } - return detected, false, detectErrs, nil + return detected, agentsDetected, detectErrs, nil +} + +// noAgentsError is the refusal of a run that finds no MCP-capable agent to install for. +func noAgentsError() error { + return failure(protos.AitoolsErrorCategoryUnknownAgent, "no MCP-capable coding agents detected; pass --agents with one of: %s", strings.Join(mcpAgentNames(), ", ")) } // resolveMCPAgents maps --agents names to MCP-capable agents. Unknown and non-MCP agents are errors. @@ -683,18 +823,15 @@ type addBinding struct { // config cannot be read has none here: its write reports the failure. type agentEntries map[*agents.Agent]map[string]map[string]any -// readAgentEntries returns the entries of each target agent's config. An agent whose config cannot be read is -// returned in unreadable, and has no entries here. +// readAgentEntries returns the server entries of each target agent, and the agents whose config could not be read, with +// the reason. func readAgentEntries(ctx context.Context, targets []*agents.Agent) (agentEntries, map[*agents.Agent]error) { held := make(agentEntries, len(targets)) - var unreadable map[*agents.Agent]error + unreadable := map[*agents.Agent]error{} files := newAgentFiles() for _, a := range targets { cfg := files.current(ctx, a) if cfg.err != nil { - if unreadable == nil { - unreadable = map[*agents.Agent]error{} - } unreadable[a] = cfg.err continue } @@ -703,6 +840,19 @@ func readAgentEntries(ctx context.Context, targets []*agents.Agent) (agentEntrie return held, unreadable } +// pinnedEnv returns the entry env that pins the config file, or nil when it is not pinned. +func pinnedEnv(pinned string) map[string]string { + if pinned == "" { + return nil + } + return map[string]string{mcpconfig.ConfigFileEnv: pinned} +} + +// serveArgs returns the arguments of the entry that runs service for agent through profile. +func serveArgs(profile, service, agent string) []string { + return append(slices.Clone(mcpconfig.ServeCommand), mcpconfig.ProfileFlag, profile, mcpconfig.ServiceFlag, service, mcpconfig.AgentFlag, agent) +} + // planInput is what planAdds plans the servers of one run against. type planInput struct { binding addBinding @@ -715,6 +865,9 @@ type planInput struct { held agentEntries // refused are the agents that will not be written, so a conflict in them does not refuse the run. refused map[*agents.Agent]error + // binary and env are the command and env of the entries the write makes. + binary string + env map[string]string } // planAdds chooses the server name of each service before anything is written, and refuses what would overwrite @@ -744,7 +897,37 @@ func planAdds(ctx context.Context, in planInput, state *mcp.State, fullNames []s } chosen[name] = true taken[name] = true - plans = append(plans, addPlan{service: mcp.Service{FullName: fullName}, name: name, failed: failed, note: note, replaced: replacedByForce(in, name)}) + plan := addPlan{ + service: mcp.Service{FullName: fullName}, + name: name, + failed: failed, + note: note, + reasserted: map[*agents.Agent]bool{}, + updated: map[*agents.Agent]bool{}, + replaced: map[*agents.Agent]bool{}, + } + for _, a := range in.targets { + entry, held := in.held[a][name] + if !held || failed[a] != nil { + continue + } + // A foreign entry is replaced. A Databricks entry is re-asserted when the write leaves it as it is, and updated + // when the write changes it. + if !mcpconfig.IsDatabricksEntry(entry) { + plan.replaced[a] = true + continue + } + same, err := agentconfig.Unchanged(a, in.binary, serveArgs(in.binding.profile, fullName, a.Name), in.env, entry) + if err != nil { + return nil, err + } + if same { + plan.reasserted[a] = true + } else { + plan.updated[a] = true + } + } + plans = append(plans, plan) } return plans, nil } @@ -837,20 +1020,6 @@ func suffixNote(in planInput, base, name string) string { return fmt.Sprintf("%s is taken in %s; using %s", base, strings.Join(holders, ", "), name) } -// replacedByForce returns the target agents that hold name as an entry this CLI did not write, which --force replaces. -func replacedByForce(in planInput, name string) map[*agents.Agent]bool { - replaced := map[*agents.Agent]bool{} - if !in.force { - return replaced - } - for _, a := range in.targets { - if entry, ok := in.held[a][name]; ok && !mcpconfig.IsDatabricksEntry(entry) { - replaced[a] = true - } - } - return replaced -} - // stateHolds reports whether a state entry other than self holds name. self is nil when no entry is excluded. func stateHolds(state *mcp.State, name string, self *mcp.Entry) bool { for i := range state.Servers { @@ -978,7 +1147,7 @@ func installServer(ctx context.Context, req addRequest, plan addPlan) addServerO err = plan.failed[a] } if err == nil { - args := append(slices.Clone(mcpconfig.ServeCommand), mcpconfig.ProfileFlag, req.profile, mcpconfig.ServiceFlag, plan.service.FullName, mcpconfig.AgentFlag, a.Name) + args := serveArgs(req.profile, plan.service.FullName, a.Name) path, status, err = agentconfig.Upsert(ctx, a, plan.name, req.binary, args, req.env, req.force) // A detected agent was not named, so --agents is no way out for it. if req.explicit { @@ -1018,11 +1187,11 @@ func installServer(ctx context.Context, req addRequest, plan addPlan) addServerO return out } -// refusedAgents returns the agents named with --agents that are not installed, with the reason for each. -// It runs once, before any request, so each service reports the same refusal without another check. -func refusedAgents(ctx context.Context, targets []*agents.Agent) map[*agents.Agent]error { +// refusedAgents returns the agents of named, the ones given with --agents, that are not installed, with the reason for +// each. It runs once, before any request, so each service reports the same refusal without another check. +func refusedAgents(ctx context.Context, named []*agents.Agent) map[*agents.Agent]error { refused := map[*agents.Agent]error{} - for _, a := range targets { + for _, a := range named { if err := requireInstalled(ctx, a); err != nil { refused[a] = err } @@ -1030,8 +1199,8 @@ func refusedAgents(ctx context.Context, targets []*agents.Agent) map[*agents.Age return refused } -// requireInstalled fails when an agent named with --agents is not installed. Writing its config would create -// the agent's directory, so the agent is refused instead. +// requireInstalled fails when an agent is not installed. Writing its config would create the agent's +// directory, so the agent is refused instead. func requireInstalled(ctx context.Context, a *agents.Agent) error { installed, err := a.InstalledForMCP(ctx) if err != nil { @@ -1040,13 +1209,19 @@ func requireInstalled(ctx context.Context, a *agents.Agent) error { if installed { return nil } - return failure(protos.AitoolsErrorCategoryUnknownAgent, "%s is not installed; install it first or leave it out of --agents", a.DisplayName) + return failureWithCause(protos.AitoolsErrorCategoryUnknownAgent, errNotInstalled, "%s is not installed; install it first or leave it out of --agents", a.DisplayName) } +// errNotInstalled is the cause of the refusal of an agent that is not installed. A failed check has another cause. +var errNotInstalled = errors.New("agent is not installed") + // signInInstalled signs in to each sign-in-required server that reached an agent, in order, and records the sign-in of -// each server in servers. A failure does not stop the others, and the failures are joined. The servers are installed -// either way. A failure names the command to run next when a sign-in can fix it, as the timeout and failed errors do. -// Other failures get no hint, since logging in again would not fix them. +// each server in servers. A sign-in failure does not stop the others: the failures are joined, and the servers are +// installed either way. An abort at a question (Ctrl+C) stops the rest. The servers from the one asked about on get +// their login hint, which the results did not print, and the abort is returned. +// +// In a terminal without --login, each server that is not already signed in is asked about first; a declined one gets +// the login command. func signInInstalled(ctx context.Context, errOut io.Writer, w *databricks.WorkspaceClient, req addRequest, plans []addPlan, servers []addServerOutput) error { var errs []error for i := range servers { @@ -1058,6 +1233,24 @@ func signInInstalled(ctx context.Context, errOut io.Writer, w *databricks.Worksp if !installedAnywhere(*server) { continue } + if req.askLogin { + // A caller already signed in is recorded as such, with no question and no second read of the credential. + if signedIn(ctx, w, plans[i].service.FullName) { + server.SignIn = &addSignInOutput{State: signInStateActive} + reportSignedIn(errOut, plans[i].service, req.profile, true) + continue + } + yes, err := promptSignInNow(server.Service) + if err != nil { + errs = append(errs, err) + printSignInHints(ctx, req, servers[i:]) + break + } + if !yes { + cmdio.LogString(ctx, signInHint(server.Service, req.profile, req.pinned)) + continue + } + } state := signInStateFailed url, err := mcp.SignInURL(w.Config.Host, plans[i].service.FullName, req.workspaceID) if err == nil { @@ -1073,6 +1266,27 @@ func signInInstalled(ctx context.Context, errOut io.Writer, w *databricks.Worksp return errors.Join(errs...) } +// signedIn reports whether the caller's sign-in to service is ACTIVE, so that no question is asked about it. The read is +// bounded by profileCheckTimeout, as the --check reads are. A read that fails or times out does not count as signed in; +// the sign-in reads it again and reports the failure. +func signedIn(ctx context.Context, w *databricks.WorkspaceClient, service string) bool { + ctx, cancel := context.WithTimeout(ctx, profileCheckTimeout) + defer cancel() + state, err := mcp.CredentialState(ctx, w, service) + return err == nil && state == catalog.ProvisioningInfoStateActive +} + +// printSignInHints prints the login hint of each server from the given one on that needs sign-in and reached an agent. +// It runs when an abort ends the sign-ins. It makes no request, since a credential read can wait out the SDK's retries +// and hold up the abort. So a server that is already signed in can get the hint too. +func printSignInHints(ctx context.Context, req addRequest, servers []addServerOutput) { + for i := range servers { + if servers[i].SignInRequired && installedAnywhere(servers[i]) { + cmdio.LogString(ctx, signInHint(servers[i].Service, req.profile, req.pinned)) + } + } +} + // signInHint returns the sentence that says a sign-in-required service needs sign-in, with the command that signs the // profile in. func signInHint(service, profileName, pinnedFile string) string { @@ -1161,7 +1375,7 @@ func recordServer(ctx context.Context, state *mcp.State, req addRequest, plan ad // service is reported once. func agentFailureError(req addRequest, servers []addServerOutput) error { var errs []error - fail := req.explicit + fail := req.agentSource == agentsNamed for _, server := range servers { for _, a := range server.Agents { if a.err != nil { @@ -1188,11 +1402,66 @@ func printAddHeader(ctx context.Context, req addRequest) { for _, a := range req.agents { names = append(names, a.Name) } - source := "named with --agents" - if !req.explicit { - source = "detected" + cmdio.LogString(ctx, fmt.Sprintf("Agents (%s): %s", req.agentSource, strings.Join(names, ", "))) +} + +// printAddPlan lists what each agent gets, before the confirm of an interactive add. +func printAddPlan(ctx context.Context, req addRequest, plans []addPlan) { + cmdio.LogString(ctx, "") + for _, line := range addPlanLines(req, plans) { + cmdio.LogString(ctx, line) + } + cmdio.LogString(ctx, "") +} + +// addPlanLines returns the plan: one line per agent, with the servers it gets as new entries, the servers it already +// has as the write would leave them (re-asserted), the Databricks entries the write changes (updated), the foreign +// entries it replaces, and the servers it cannot take. An agent whose config cannot be read gets one line saying so. +func addPlanLines(req addRequest, plans []addPlan) []string { + lines := []string{"Plan (profile " + req.profile + "):"} + for _, a := range req.agents { + if err := req.refused[a]; err != nil { + reason := "not installed" + if !errors.Is(err, errNotInstalled) { + reason = "cannot be checked: " + err.Error() + } + lines = append(lines, fmt.Sprintf(" %-14s %s; skipped", a.DisplayName, reason)) + continue + } + var added, reasserted, updated, replaced, skipped []string + for _, p := range plans { + switch { + case p.failed[a] != nil: + skipped = append(skipped, p.name) + case p.reasserted[a]: + reasserted = append(reasserted, p.name) + case p.updated[a]: + updated = append(updated, p.name) + case p.replaced[a]: + replaced = append(replaced, p.name) + default: + added = append(added, p.name) + } + } + var parts []string + if len(added) > 0 { + parts = append(parts, "add "+strings.Join(added, ", ")) + } + if len(reasserted) > 0 { + parts = append(parts, "re-assert "+strings.Join(reasserted, ", ")) + } + if len(updated) > 0 { + parts = append(parts, "update "+strings.Join(updated, ", ")) + } + if len(replaced) > 0 { + parts = append(parts, "replace "+strings.Join(replaced, ", ")) + } + if len(skipped) > 0 { + parts = append(parts, "skip "+strings.Join(skipped, ", ")) + } + lines = append(lines, fmt.Sprintf(" %-14s %s", a.DisplayName, strings.Join(parts, "; "))) } - cmdio.LogString(ctx, fmt.Sprintf("Agents (%s): %s", source, strings.Join(names, ", "))) + return lines } // printAddResults prints each server, its agents, and the follow-up steps the server needs. The Cursor approval @@ -1214,7 +1483,7 @@ func printAddResults(ctx context.Context, req addRequest, servers []addServerOut cursorServers = append(cursorServers, server.Name) } } - if server.SignInRequired && installedAnywhere(server) && !req.login { + if server.SignInRequired && installedAnywhere(server) && !req.login && !req.askLogin { cmdio.LogString(ctx, " "+signInHint(server.Service, req.profile, req.pinned)) } if server.note != "" && installedAnywhere(server) { diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index 1a4d1012465..af26c145ca9 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -14,16 +14,21 @@ import ( "path/filepath" "strconv" "strings" + "sync/atomic" "testing" + "time" + "github.com/charmbracelet/huh" "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/databrickscfg/profile" "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/telemetry/protos" + "github.com/databricks/databricks-sdk-go" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -384,10 +389,10 @@ func TestInstallServerRefusesUndetectedExplicitAgent(t *testing.T) { home := withHome(t) require.NoError(t, os.MkdirAll(filepath.Join(home, ".claude"), 0o700)) req := addRequest{ - profile: "logfood", - explicit: true, - agents: []*agents.Agent{agents.ByName("codex"), agents.ByName("claude-code")}, - binary: "databricks", + profile: "logfood", + agentSource: agentsNamed, + agents: []*agents.Agent{agents.ByName("codex"), agents.ByName("claude-code")}, + binary: "databricks", } req.refused = refusedAgents(ctx, req.agents) plan := addPlan{service: mcp.Service{FullName: "system.ai.github"}, name: "github"} @@ -414,10 +419,15 @@ func defaultBinding(t *testing.T, profile string) addBinding { } // planNames runs planAdds for the services with the agent entries read as the command reads them. +// readHeld returns the server entries of the targets that readAgentEntries reads, for tests that do not check unreadable configs. +func readHeld(ctx context.Context, targets []*agents.Agent) agentEntries { + held, _ := readAgentEntries(ctx, targets) + return held +} + func planNames(t *testing.T, nameFlag string, b addBinding, state *mcp.State, fullNames []string, targets []*agents.Agent) ([]addPlan, error) { t.Helper() - held, _ := readAgentEntries(t.Context(), targets) - in := planInput{binding: b, nameFlag: nameFlag, targets: targets, held: held} + in := planInput{binding: b, nameFlag: nameFlag, targets: targets, held: readHeld(t.Context(), targets)} return planAdds(t.Context(), in, state, fullNames) } @@ -790,7 +800,7 @@ func TestInstallServerReassertsFromAgentFile(t *testing.T) { home := withHome(t) require.NoError(t, os.MkdirAll(filepath.Join(home, ".claude"), 0o700)) - req := addRequest{profile: "logfood", explicit: true, agents: []*agents.Agent{agents.ByName("claude-code")}, binary: "databricks"} + req := addRequest{profile: "logfood", agentSource: agentsNamed, agents: []*agents.Agent{agents.ByName("claude-code")}, binary: "databricks"} plan := addPlan{service: mcp.Service{FullName: "system.ai.github"}, name: "github-logfood"} first := installServer(t.Context(), req, plan) @@ -870,8 +880,8 @@ func TestAgentFailureErrorWhenAServiceReachedNoAgent(t *testing.T) { assert.ErrorContains(t, err, "bad config") // Agents named with --agents fail the command on any failure. - assert.Error(t, agentFailureError(addRequest{explicit: true}, []addServerOutput{installed, mixed})) - assert.NoError(t, agentFailureError(addRequest{explicit: true}, []addServerOutput{installed})) + assert.Error(t, agentFailureError(addRequest{agentSource: agentsNamed}, []addServerOutput{installed, mixed})) + assert.NoError(t, agentFailureError(addRequest{agentSource: agentsNamed}, []addServerOutput{installed})) } func TestErrorCategoryMapsTypedFailures(t *testing.T) { @@ -1448,7 +1458,7 @@ func TestAgentFailureErrorKeepsEveryDistinctFailure(t *testing.T) { {Agents: []addAgentOutput{{Name: "claude-code", Status: statusFailed, err: refusal}}}, } - err := agentFailureError(addRequest{explicit: true}, servers) + err := agentFailureError(addRequest{agentSource: agentsNamed}, servers) require.Error(t, err) assert.ErrorContains(t, err, "write ~/.claude.json") assert.Equal(t, 1, strings.Count(err.Error(), "claude-code is not installed"), err.Error()) @@ -1478,8 +1488,7 @@ func TestPlanAddsDetectedAgentConflictFailsOnlyThatAgent(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(home, ".claude.json"), []byte(`{"mcpServers":{"github-logfood":`+claudeEntry("system.ai.other", "logfood", "")+`}}`), 0o600)) state := &mcp.State{Servers: []mcp.Entry{{Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-123.test"}}} targets := []*agents.Agent{claude, codex} - held, _ := readAgentEntries(ctx, targets) - in := planInput{binding: defaultBinding(t, "logfood"), targets: targets, held: held} + in := planInput{binding: defaultBinding(t, "logfood"), targets: targets, held: readHeld(ctx, targets)} plans, err := planAdds(ctx, in, state, []string{"system.ai.github"}) require.NoError(t, err) @@ -1496,8 +1505,7 @@ func TestPlanAddsDetectedAgentConflictFailsOnlyThatAgent(t *testing.T) { assert.Equal(t, categoryNameConflict, errorCategory(err)) onlyClaude := []*agents.Agent{claude} - heldClaude, _ := readAgentEntries(ctx, onlyClaude) - in = planInput{binding: defaultBinding(t, "logfood"), targets: onlyClaude, held: heldClaude} + in = planInput{binding: defaultBinding(t, "logfood"), targets: onlyClaude, held: readHeld(ctx, onlyClaude)} plans, err = planAdds(ctx, in, state, []string{"system.ai.github"}) require.NoError(t, err) refusal := planningRefusals(plans, onlyClaude, nil) @@ -1603,7 +1611,7 @@ func TestInstallServerWritesOnlyAgentsInstalledForMCP(t *testing.T) { fakeBinsOnPath(t, agents.ByName(tt.agent).Binary) } - req := addRequest{profile: "logfood", explicit: true, agents: []*agents.Agent{agents.ByName(tt.agent)}, binary: "databricks"} + req := addRequest{profile: "logfood", agentSource: agentsNamed, agents: []*agents.Agent{agents.ByName(tt.agent)}, binary: "databricks"} req.refused = refusedAgents(ctx, req.agents) out := installServer(ctx, req, addPlan{service: mcp.Service{FullName: "system.ai.github"}, name: "github"}) require.Len(t, out.Agents, 1) @@ -1639,3 +1647,633 @@ func TestPlanningRefusalsCountsRefusedAgents(t *testing.T) { assert.NoError(t, planningRefusals(plans, targets, nil)) } + +// runInteractiveAdd runs `aitools mcp add` as a terminal does. The prompts are the seams, which the test overrides. +func runInteractiveAdd(t *testing.T, args ...string) error { + t.Helper() + return runInteractive(t, append([]string{"mcp", "add"}, args...)...) +} + +// runInteractive runs the aitools command with args as a terminal does, under the mcp group. +func runInteractive(t *testing.T, args ...string) error { + t.Helper() + withDatabricksBinary(t) + ctx, test := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) + t.Cleanup(test.Done) + go drainReader(test.Stdout) + go drainReader(test.Stderr) + parent := newMCPTestRoot() + parent.SetOut(&bytes.Buffer{}) + parent.SetErr(&bytes.Buffer{}) + parent.SetArgs(args) + return parent.ExecuteContext(ctx) +} + +// TestMcpAddNameOnThePickerPathIsRefusedBeforeConnecting checks that --name without --names is refused before the +// profile is read, so no request reaches the workspace. +func TestMcpAddNameOnThePickerPathIsRefusedBeforeConnecting(t *testing.T) { + home := withHome(t) + server := noRequestServer(t) + writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nauth_type = pat\ntoken = dapi-logfood\n") + failOnPrompt(t) + + err := runInteractiveAdd(t, "--profile", "logfood", "--name", "github") + require.Error(t, err) + assert.Equal(t, "--name needs exactly one service; leave out --name to pick services in the picker", err.Error()) + assert.NoFileExists(t, filepath.Join(home, ".claude.json")) +} + +// TestMcpAddPickerRefusesRepointedHostOfPickedServiceBeforeWriting checks that a run that picks its services lists the +// workspace, then refuses a picked service whose recorded entry names another host, before anything is written. +func TestMcpAddPickerRefusesRepointedHostOfPickedServiceBeforeWriting(t *testing.T) { + home := withHome(t) + server := listingServer(t, "system.ai.github") + writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") + require.NoError(t, mcp.SaveState(t.Context(), &mcp.State{Servers: []mcp.Entry{{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", Host: "https://adb-123.test", + }}})) + failOnPrompt(t) + promptServiceSelection = func(string, []serviceRow) (servicePick, error) { + return servicePick{services: []mcp.Service{{FullName: "system.ai.github", Leaf: "github"}}}, nil + } + + err := runInteractiveAdd(t, "--profile", "logfood", "--agents", "claude-code") + require.Error(t, err) + assert.Equal(t, protos.AitoolsErrorCategory(mcp.BindProfileHostChanged), errorCategory(err)) + assert.Contains(t, err.Error(), "was set up for https://adb-123.test, but profile \"logfood\" now points at "+server.URL) + assert.NoFileExists(t, filepath.Join(home, ".claude.json")) +} + +// schemaListingServer returns a workspace whose schemas list the services named for them, by the parent of the listing. +// Each service is a full name, none sign-in-required. +func schemaListingServer(t *testing.T, schemas map[string][]string) *httptest.Server { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if !strings.HasPrefix(r.URL.Path, "/api/") { + w.WriteHeader(http.StatusNotFound) + return + } + if r.URL.Path != "/api/2.1/unity-catalog/mcp-services" { + t.Errorf("unexpected request: %s %s", r.Method, r.URL) + w.WriteHeader(http.StatusInternalServerError) + return + } + var services []string + for _, name := range schemas[strings.TrimPrefix(r.URL.Query().Get("parent"), "schemas/")] { + services = append(services, `{"name":"mcp-services/`+name+`"}`) + } + _, _ = w.Write([]byte(`{"mcp_services":[` + strings.Join(services, ",") + `]}`)) + })) + t.Cleanup(server.Close) + return server +} + +// TestMcpAddPickerInstallsAcrossSchemas checks that a terminal run with a profile and no --names installs the services it +// picks in two schemas, reached through "Another schema...": both entries reach the agent file and the state. +func TestMcpAddPickerInstallsAcrossSchemas(t *testing.T) { + home := withHome(t) + server := schemaListingServer(t, map[string][]string{ + "system.ai": {"system.ai.github"}, + "main.tools": {"main.tools.slack"}, + }) + writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") + failOnPrompt(t) + promptServiceSelection = func(location string, _ []serviceRow) (servicePick, error) { + if location == "system.ai" { + return servicePick{services: []mcp.Service{{FullName: "system.ai.github", Leaf: "github"}}, another: true}, nil + } + return servicePick{services: []mcp.Service{{FullName: "main.tools.slack", Leaf: "slack"}}}, nil + } + promptLocation = func() (string, error) { return "main.tools", nil } + promptAgentSelection = func(_ context.Context, _ string, choices []agentChoice) ([]*agents.Agent, error) { + return []*agents.Agent{choices[0].agent}, nil + } + proceeds := 0 + promptProceed = func() (bool, error) { + proceeds++ + return true, nil + } + + require.NoError(t, runInteractiveAdd(t, "--profile", "logfood")) + assert.Equal(t, 1, proceeds, "the picked plan is confirmed once") + + agentFile, err := os.ReadFile(filepath.Join(home, ".claude.json")) + require.NoError(t, err) + assert.Contains(t, string(agentFile), `"github-logfood"`) + assert.Contains(t, string(agentFile), `"main-tools-slack-logfood"`) + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + var recorded []string + for _, e := range state.Servers { + recorded = append(recorded, e.Service) + } + assert.ElementsMatch(t, []string{"system.ai.github", "main.tools.slack"}, recorded) +} + +// TestMcpAddPickerRefusesMissingProfileBeforeAnyRequest checks that a run that picks its services reports a profile the +// config file does not have, or has with no host, as PROFILE_NOT_FOUND, before any request. +func TestMcpAddPickerRefusesMissingProfileBeforeAnyRequest(t *testing.T) { + home := withHome(t) + server := noRequestServer(t) + writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nauth_type = pat\ntoken = dapi-logfood\n") + failOnPrompt(t) + + err := runInteractiveAdd(t, "--profile", "logfdood", "--agents", "claude-code") + require.Error(t, err) + assert.Equal(t, protos.AitoolsErrorCategory(mcp.BindProfileNotFound), errorCategory(err)) + assert.Contains(t, err.Error(), "Databricks profile \"logfdood\", which does not exist in ") + assert.Contains(t, err.Error(), "Set it up with: databricks auth login --profile logfdood") + + writeHomeConfig(t, home, "[logfood]\nhost =\nauth_type = pat\ntoken = dapi-logfood\n") + err = runInteractiveAdd(t, "--profile", "logfood", "--agents", "claude-code") + require.Error(t, err) + assert.Equal(t, protos.AitoolsErrorCategory(mcp.BindProfileNotFound), errorCategory(err)) + assert.Contains(t, err.Error(), "Databricks profile \"logfood\", which has no host in ") +} + +// TestMcpAddPickerWithNoAgentMakesNoRequest checks that a run that picks its services ends when no agent is detected, +// before the workspace is contacted. +func TestMcpAddPickerWithNoAgentMakesNoRequest(t *testing.T) { + home := withHome(t) + require.NoError(t, os.RemoveAll(filepath.Join(home, ".claude"))) + server := noRequestServer(t) + writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") + failOnPrompt(t) + + err := runInteractiveAdd(t, "--profile", "logfood") + require.Error(t, err) + assert.Equal(t, protos.AitoolsErrorCategoryUnknownAgent, errorCategory(err)) + assert.Contains(t, err.Error(), "no MCP-capable coding agents detected") +} + +// TestMcpAddWithoutTerminalReportsNoAgentBeforeProfile checks that a run without a terminal and with no agent reports +// that before the profile, which here would be ambiguous with two profiles. +func TestMcpAddWithoutTerminalReportsNoAgentBeforeProfile(t *testing.T) { + home := withHome(t) + require.NoError(t, os.RemoveAll(filepath.Join(home, ".claude"))) + writeHomeConfig(t, home, "[logfood]\nhost = https://logfood.test\nauth_type = pat\ntoken = dapi-logfood\n"+ + "[dogfood]\nhost = https://dogfood.test\nauth_type = pat\ntoken = dapi-dogfood\n") + + err := runAdd(t, "--names", "github") + require.Error(t, err) + assert.Equal(t, protos.AitoolsErrorCategoryUnknownAgent, errorCategory(err)) + assert.Contains(t, err.Error(), "no MCP-capable coding agents detected") +} + +// TestMcpAddInTerminalRefusesWhenAgentCheckFails checks that a terminal with no agent installed for MCP, and an agent +// whose check fails, is refused in chooseAgents: the failure is named, nothing is picked and the check is not repeated. +func TestMcpAddInTerminalRefusesWhenAgentCheckFails(t *testing.T) { + withHome(t) + t.Setenv(env.HomeEnvVar(), "") + for _, name := range agentHomeEnv { + t.Setenv(name, "") + } + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + origPrompt := promptAgentSelection + t.Cleanup(func() { promptAgentSelection = origPrompt }) + promptAgentSelection = func(context.Context, string, []agentChoice) ([]*agents.Agent, error) { + t.Error("the run asked for agents with none installed") + return nil, nil + } + + claude := agents.ByName(agents.NameClaudeCode) + _, checkErr := claude.InstalledForMCP(ctx) + require.Error(t, checkErr, "the check needs a home directory") + + _, _, _, err := chooseAgents(ctx, nil, true) + require.Error(t, err) + assert.Equal(t, protos.AitoolsErrorCategoryUnknownAgent, errorCategory(err)) + assert.Contains(t, err.Error(), "no MCP-capable coding agents detected") + assert.Contains(t, stderr.String(), fmt.Sprintf("Not found: %s (%s)", claude.DisplayName, checkErr)) +} + +// failOnPrompt makes every picker and question of an interactive run fail the test, so a test can show what a +// run asks. It restores the seams when the test ends. +func failOnPrompt(t *testing.T) { + t.Helper() + origProceed, origAgents, origServices, origProfile := promptProceed, promptAgentSelection, promptServiceSelection, selectProfile + origSignIn := promptSignInNow + t.Cleanup(func() { + promptProceed, promptAgentSelection, promptServiceSelection, selectProfile = origProceed, origAgents, origServices, origProfile + promptSignInNow = origSignIn + }) + promptProceed = func() (bool, error) { t.Error("the run asked to confirm the plan"); return false, nil } + promptAgentSelection = func(context.Context, string, []agentChoice) ([]*agents.Agent, error) { + t.Error("the run asked for agents") + return nil, nil + } + promptServiceSelection = func(string, []serviceRow) (servicePick, error) { + t.Error("the run asked for services") + return servicePick{}, nil + } + selectProfile = func(context.Context, profile.SelectConfig) (string, error) { + t.Error("the run asked for a profile") + return "", nil + } + promptSignInNow = func(string) (bool, error) { + t.Error("the run asked to sign in") + return false, nil + } +} + +// listingServer returns a workspace whose schema lists the MCP services in names, none of them sign-in-required. +// A run that binds a profile with a workspace_id lists the services and makes no other call. +func listingServer(t *testing.T, names ...string) *httptest.Server { + t.Helper() + services := make([]string, 0, len(names)) + for _, name := range names { + services = append(services, `{"name":"mcp-services/`+name+`"}`) + } + return listingServerJSON(t, services...) +} + +// signInListingServer returns a workspace whose schema lists the sign-in-required service name, whose source connection +// has an OAuth provider. The service is not signed in, so its credential read answers NOT_FOUND. +func signInListingServer(t *testing.T, name string) *httptest.Server { + t.Helper() + return listingServerJSON(t, `{"name":"mcp-services/`+name+`","config":{"source_connection":{"name":"github","options":{"oauth_provider":"github"}}}}`) +} + +// listingServerJSON returns a workspace whose schema lists services, each a JSON MCP service. A credential read answers +// NOT_FOUND, as for a caller not signed in; any other request is a failure. +func listingServerJSON(t *testing.T, services ...string) *httptest.Server { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if !strings.HasPrefix(r.URL.Path, "/api/") { + // The SDK reads host metadata before it calls the API; there is none here. + w.WriteHeader(http.StatusNotFound) + return + } + if strings.HasSuffix(r.URL.Path, "/user-credentials") { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error_code":"NOT_FOUND","message":"not found"}`)) + return + } + if r.URL.Path != "/api/2.1/unity-catalog/mcp-services" { + t.Errorf("unexpected request: %s %s", r.Method, r.URL) + w.WriteHeader(http.StatusInternalServerError) + return + } + _, _ = w.Write([]byte(`{"mcp_services":[` + strings.Join(services, ",") + `]}`)) + })) + t.Cleanup(server.Close) + return server +} + +// TestMcpAddFullySpecifiedRunAsksNothing checks that a terminal run with the profile, the services and the agents +// given asks for nothing and installs. +func TestMcpAddFullySpecifiedRunAsksNothing(t *testing.T) { + home := withHome(t) + server := listingServer(t, "system.ai.dbsql") + writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") + failOnPrompt(t) + + require.NoError(t, runInteractiveAdd(t, "--profile", "logfood", "--names", "dbsql", "--agents", "claude-code")) + claude, err := os.ReadFile(filepath.Join(home, ".claude.json")) + require.NoError(t, err) + assert.Contains(t, string(claude), "dbsql-logfood") +} + +// TestMcpAddFullySpecifiedRunAsksOnlyTheSignInQuestion checks that a terminal run with the profile, the services and the +// agents given asks the sign-in question of a sign-in-required server, and nothing else. +func TestMcpAddFullySpecifiedRunAsksOnlyTheSignInQuestion(t *testing.T) { + home := withHome(t) + server := signInListingServer(t, "system.ai.github") + writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") + failOnPrompt(t) + var asked []string + promptSignInNow = func(service string) (bool, error) { + asked = append(asked, service) + return false, nil + } + + require.NoError(t, runInteractiveAdd(t, "--profile", "logfood", "--names", "github", "--agents", "claude-code")) + assert.Equal(t, []string{"system.ai.github"}, asked) + claude, err := os.ReadFile(filepath.Join(home, ".claude.json")) + require.NoError(t, err) + assert.Contains(t, string(claude), "github-logfood") +} + +// TestMcpAddDeclinedPlanWritesNothing checks that declining the confirm of a picked agent leaves the agent's +// config unwritten. +func TestMcpAddDeclinedPlanWritesNothing(t *testing.T) { + home := withHome(t) + server := listingServer(t, "system.ai.dbsql") + writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") + failOnPrompt(t) + origAgents, origProceed := promptAgentSelection, promptProceed + t.Cleanup(func() { promptAgentSelection, promptProceed = origAgents, origProceed }) + promptAgentSelection = func(_ context.Context, _ string, choices []agentChoice) ([]*agents.Agent, error) { + return []*agents.Agent{agents.ByName(agents.NameClaudeCode)}, nil + } + var confirmed bool + promptProceed = func() (bool, error) { + confirmed = true + return false, nil + } + + require.NoError(t, runInteractiveAdd(t, "--profile", "logfood", "--names", "dbsql")) + assert.True(t, confirmed) + assert.NoFileExists(t, filepath.Join(home, ".claude.json")) + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Empty(t, state.Servers) +} + +// credentialServer returns a workspace whose credential reads of the services in active answer ACTIVE, and that counts +// its API reads in reads. The others answer NOT_FOUND, as the API does until the caller signs in. +func credentialServer(t *testing.T, reads *atomic.Int32, active ...string) *httptest.Server { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if !strings.HasPrefix(r.URL.Path, "/api/") { + w.WriteHeader(http.StatusNotFound) + return + } + reads.Add(1) + for _, service := range active { + if r.URL.Path == "/api/2.1/unity-catalog/mcp-services/"+service+"/user-credentials" { + _, _ = w.Write([]byte(`{"provisioning_info":{"state":"ACTIVE"}}`)) + return + } + } + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error_code":"NOT_FOUND","message":"not found"}`)) + })) + t.Cleanup(server.Close) + return server +} + +// signInRun returns the requests and plans of two sign-in-required servers that reached claude-code, and the workspace +// they sign in to. The servers are github and genie_one_mcp. +func signInRun(t *testing.T, reads *atomic.Int32, active ...string) (*databricks.WorkspaceClient, addRequest, []addPlan, []addServerOutput) { + t.Helper() + server := credentialServer(t, reads, active...) + w, err := databricks.NewWorkspaceClient(&databricks.Config{Host: server.URL, Token: "test-token"}) + require.NoError(t, err) + req := addRequest{profile: "logfood", workspaceID: "123", agents: []*agents.Agent{agents.ByName(agents.NameClaudeCode)}} + plans := []addPlan{ + {service: mcp.Service{FullName: "system.ai.github", SignInRequired: true}}, + {service: mcp.Service{FullName: "system.ai.genie_one_mcp", SignInRequired: true}}, + } + installed := []addAgentOutput{{Name: agents.NameClaudeCode, Status: statusInstalled}} + servers := []addServerOutput{ + {Name: "github-logfood", Service: "system.ai.github", SignInRequired: true, Agents: installed}, + {Name: "genie-logfood", Service: "system.ai.genie_one_mcp", SignInRequired: true, Agents: installed}, + } + return w, req, plans, servers +} + +// askSignIn overrides the sign-in question for a test, and returns the services it was asked about. +func askSignIn(t *testing.T, answer func(service string) (bool, error)) *[]string { + t.Helper() + orig := promptSignInNow + t.Cleanup(func() { promptSignInNow = orig }) + var asked []string + promptSignInNow = func(service string) (bool, error) { + asked = append(asked, service) + return answer(service) + } + return &asked +} + +// TestSignInInstalledAsksEachServer checks that each server not signed in is asked about in order, and that a declined +// one keeps its server installed and prints the login command. +func TestSignInInstalledAsksEachServer(t *testing.T) { + w, req, plans, servers := signInRun(t, new(atomic.Int32)) + req.askLogin = true + asked := askSignIn(t, func(string) (bool, error) { return false, nil }) + + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + require.NoError(t, signInInstalled(ctx, io.Discard, w, req, plans, servers)) + assert.Equal(t, []string{"system.ai.github", "system.ai.genie_one_mcp"}, *asked) + assert.Contains(t, stderr.String(), "system.ai.github needs sign-in. Run: ") + assert.Contains(t, stderr.String(), "system.ai.genie_one_mcp needs sign-in. Run: ") +} + +// TestSignInInstalledSkipsTheQuestionWhenSignedIn checks that a server already signed in is not asked about, and +// that its sign-in is recorded as ACTIVE. +func TestSignInInstalledSkipsTheQuestionWhenSignedIn(t *testing.T) { + var reads atomic.Int32 + w, req, plans, servers := signInRun(t, &reads, "system.ai.github") + req.askLogin = true + asked := askSignIn(t, func(string) (bool, error) { return false, nil }) + + ctx, _ := cmdio.NewTestContextWithStderr(t.Context()) + var errOut bytes.Buffer + require.NoError(t, signInInstalled(ctx, &errOut, w, req, plans, servers)) + assert.Equal(t, []string{"system.ai.genie_one_mcp"}, *asked) + require.NotNil(t, servers[0].SignIn) + assert.Equal(t, signInStateActive, servers[0].SignIn.State) + assert.Equal(t, "Already signed in to system.ai.github on profile logfood.\n", errOut.String()) + // Each server is read once, for its question. The sign-in of the signed-in server is not started, so it is not read again. + assert.Equal(t, int32(2), reads.Load()) +} + +// TestSignInInstalledAbortPrintsTheRestOfTheHints checks that an abort at the question ends the sign-ins, prints the +// login hint of each server not signed in, and returns the abort. +// TestSignedInGivesUpOnAHungCredentialRead checks that a credential read that never answers ends at profileCheckTimeout, +// so the sign-in question is asked, instead of holding it for the SDK's whole retry budget. +func TestSignedInGivesUpOnAHungCredentialRead(t *testing.T) { + origTimeout := profileCheckTimeout + profileCheckTimeout = 100 * time.Millisecond + t.Cleanup(func() { profileCheckTimeout = origTimeout }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Only the credential read hangs; the SDK's host metadata read at setup answers at once. + if !strings.HasSuffix(r.URL.Path, "/user-credentials") { + w.WriteHeader(http.StatusNotFound) + return + } + <-r.Context().Done() + })) + t.Cleanup(server.Close) + w, err := databricks.NewWorkspaceClient(&databricks.Config{Host: server.URL, Token: "dapi-test"}) + require.NoError(t, err) + + start := time.Now() + assert.False(t, signedIn(t.Context(), w, "system.ai.github")) + assert.Less(t, time.Since(start), 10*time.Second) +} + +func TestSignInInstalledAbortPrintsTheRestOfTheHints(t *testing.T) { + var reads atomic.Int32 + w, req, plans, servers := signInRun(t, &reads) + req.askLogin = true + asked := askSignIn(t, func(string) (bool, error) { return false, huh.ErrUserAborted }) + + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + err := signInInstalled(ctx, io.Discard, w, req, plans, servers) + require.ErrorIs(t, err, huh.ErrUserAborted) + assert.Equal(t, protos.AitoolsErrorCategoryUserAborted, errorCategory(err)) + assert.Equal(t, []string{"system.ai.github"}, *asked, "the sign-ins stop at the abort") + // The only read is the one that asked about github: the hints of the rest are printed without a request. + assert.Equal(t, int32(1), reads.Load()) + assert.Contains(t, stderr.String(), "system.ai.github needs sign-in. Run: ") + assert.Contains(t, stderr.String(), "system.ai.genie_one_mcp needs sign-in. Run: ") +} + +// TestPlanAddsReplacesAForeignEntryAndReassertsOwnEntry checks that a plan names what the write does to an entry the +// agent already holds: a replace for an entry this CLI did not write, a re-assert for one of this binding. +func TestPlanAddsReplacesAForeignEntryAndReassertsOwnEntry(t *testing.T) { + home := withHome(t) + claude := agents.ByName(agents.NameClaudeCode) + targets := []*agents.Agent{claude} + config := filepath.Join(home, ".claude.json") + b := defaultBinding(t, "logfood") + + // A foreign entry under the name, replaced under --force. + require.NoError(t, os.WriteFile(config, []byte(`{"mcpServers":{"github-logfood":{"type":"stdio","command":"other"}}}`), 0o600)) + in := planInput{binding: b, nameFlag: "github-logfood", force: true, targets: targets, held: readHeld(t.Context(), targets)} + plans, err := planAdds(t.Context(), in, &mcp.State{}, []string{"system.ai.github"}) + require.NoError(t, err) + require.Len(t, plans, 1) + assert.True(t, plans[0].replaced[claude]) + assert.False(t, plans[0].reasserted[claude]) + req := addRequest{profile: "logfood", agents: targets} + assert.Equal(t, []string{"Plan (profile logfood):", fmt.Sprintf(" %-14s %s", claude.DisplayName, "replace github-logfood")}, addPlanLines(req, plans)) + + // An entry of this binding under the name is re-asserted. + require.NoError(t, os.WriteFile(config, []byte(`{"mcpServers":{"github-logfood":`+claudeEntry("system.ai.github", "logfood", "")+`}}`), 0o600)) + in.held = readHeld(t.Context(), targets) + in.nameFlag = "" + in.force = false + in.binary = "databricks" + plans, err = planAdds(t.Context(), in, &mcp.State{}, []string{"system.ai.github"}) + require.NoError(t, err) + require.Len(t, plans, 1) + assert.True(t, plans[0].reasserted[claude]) + assert.False(t, plans[0].replaced[claude]) + assert.False(t, plans[0].updated[claude]) + + // The same entry under a binary that moved is updated, not re-asserted: the write changes its command. + in.binary = "/opt/databricks/bin/databricks" + plans, err = planAdds(t.Context(), in, &mcp.State{}, []string{"system.ai.github"}) + require.NoError(t, err) + require.Len(t, plans, 1) + assert.True(t, plans[0].updated[claude]) + assert.False(t, plans[0].reasserted[claude]) + req = addRequest{profile: "logfood", agents: targets} + assert.Equal(t, []string{"Plan (profile logfood):", fmt.Sprintf(" %-14s %s", claude.DisplayName, "update github-logfood")}, addPlanLines(req, plans)) +} + +// TestValidateMCPAddFlagsNameNeedsServicesFromNames checks that --name without --names is refused before the +// workspace is read, in a terminal too, where the picker would otherwise choose the services. +func TestValidateMCPAddFlagsNameNeedsServicesFromNames(t *testing.T) { + ctx, test := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) + defer test.Done() + err := validateMCPAddFlags(ctx, mcpAddFlags{name: "github"}, nil, nil, false) + require.Error(t, err) + assert.Equal(t, "--name needs exactly one service; leave out --name to pick services in the picker", err.Error()) + assert.NoError(t, validateMCPAddFlags(ctx, mcpAddFlags{name: "github"}, []string{"github"}, nil, false)) +} + +func TestChooseAgentsSources(t *testing.T) { + withHome(t) + fakeBinsOnPath(t, agents.ByName(agents.NameCodex).Binary) + ctx := cmdio.MockDiscard(t.Context()) + origPrompt := promptAgentSelection + t.Cleanup(func() { promptAgentSelection = origPrompt }) + + var offered []agentChoice + promptAgentSelection = func(_ context.Context, _ string, choices []agentChoice) ([]*agents.Agent, error) { + offered = choices + return []*agents.Agent{choices[0].agent}, nil + } + + named := []*agents.Agent{agents.ByName(agents.NameCodex)} + got, source, _, err := chooseAgents(ctx, named, true) + require.NoError(t, err) + assert.Equal(t, agentsNamed, source) + assert.Equal(t, named, got) + assert.Empty(t, offered, "named agents are not asked for") + + got, source, _, err = chooseAgents(ctx, nil, true) + require.NoError(t, err) + assert.Equal(t, agentsPicked, source) + require.Len(t, got, 1) + // The picker offers installed agents only. + require.NotEmpty(t, offered) + for _, c := range offered { + installed, err := c.agent.InstalledForMCP(ctx) + require.NoError(t, err) + assert.True(t, installed, c.agent.Name) + } +} + +// TestChooseAgentsNamesTheAgentsNotFound checks that the picker lists the installed agents and names the others above it. +func TestChooseAgentsNamesTheAgentsNotFound(t *testing.T) { + withHome(t) + fakeBinsOnPath(t, agents.ByName(agents.NameCodex).Binary) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + origPrompt := promptAgentSelection + t.Cleanup(func() { promptAgentSelection = origPrompt }) + promptAgentSelection = func(_ context.Context, _ string, choices []agentChoice) ([]*agents.Agent, error) { + return []*agents.Agent{choices[0].agent}, nil + } + + _, _, _, err := chooseAgents(ctx, nil, true) + require.NoError(t, err) + assert.Contains(t, stderr.String(), "Not found: ") + assert.Contains(t, stderr.String(), agents.ByName(agents.NameCursor).DisplayName) +} + +// TestAddPlanLinesSayWhenConfigCannotBeRead checks that an agent whose config cannot be read is shown as such, with the +// write that will fail, not as an add. +func TestAddPlanLinesSayWhenConfigCannotBeRead(t *testing.T) { + claude := agents.ByName(agents.NameClaudeCode) + req := addRequest{ + profile: "logfood", + agents: []*agents.Agent{claude}, + unreadable: map[*agents.Agent]error{claude: errors.New("parse error")}, + } + plans := []addPlan{{service: mcp.Service{FullName: "system.ai.github"}, name: "github-logfood"}} + assert.Equal(t, []string{"Plan (profile logfood):", fmt.Sprintf(" %-14s cannot be read: parse error; the write will fail", claude.DisplayName)}, addPlanLines(req, plans)) +} + +func TestAddPlanLines(t *testing.T) { + claude := agents.ByName(agents.NameClaudeCode) + codex := agents.ByName(agents.NameCodex) + req := addRequest{profile: "logfood", agents: []*agents.Agent{claude, codex}} + plans := []addPlan{ + {service: mcp.Service{FullName: "system.ai.github"}, name: "github-logfood"}, + { + service: mcp.Service{FullName: "system.ai.genie_one_mcp"}, + name: "genie_one_mcp-logfood", + reasserted: map[*agents.Agent]bool{claude: true}, + }, + } + want := []string{ + "Plan (profile logfood):", + fmt.Sprintf(" %-14s %s", claude.DisplayName, "add github-logfood; re-assert genie_one_mcp-logfood"), + fmt.Sprintf(" %-14s %s", codex.DisplayName, "add github-logfood, genie_one_mcp-logfood"), + } + assert.Equal(t, want, addPlanLines(req, plans)) + + // A server that an agent cannot take is skipped for that agent, and a refused agent is not written. + req.refused = map[*agents.Agent]error{codex: errNotInstalled} + plans[0].failed = map[*agents.Agent]error{claude: errors.New("conflict")} + want = []string{ + "Plan (profile logfood):", + fmt.Sprintf(" %-14s %s", claude.DisplayName, "re-assert genie_one_mcp-logfood; skip github-logfood"), + fmt.Sprintf(" %-14s %s", codex.DisplayName, "not installed; skipped"), + } + assert.Equal(t, want, addPlanLines(req, plans)) + + // An agent whose check failed is refused with the reason, not as not installed. + req.refused = map[*agents.Agent]error{codex: errors.New("no home")} + want = []string{ + "Plan (profile logfood):", + fmt.Sprintf(" %-14s %s", claude.DisplayName, "re-assert genie_one_mcp-logfood; skip github-logfood"), + fmt.Sprintf(" %-14s %s", codex.DisplayName, "cannot be checked: no home; skipped"), + } + assert.Equal(t, want, addPlanLines(req, plans)) +} + +func TestValidateMCPAddFlagsInTerminalAsksForMissingChoices(t *testing.T) { + ctx, test := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) + defer test.Done() + require.NoError(t, validateMCPAddFlags(ctx, mcpAddFlags{}, nil, nil, false)) +} diff --git a/cmd/aitools/mcp_list.go b/cmd/aitools/mcp_list.go index b535caa53ba..676395271d4 100644 --- a/cmd/aitools/mcp_list.go +++ b/cmd/aitools/mcp_list.go @@ -390,7 +390,7 @@ func agentStatus(ctx context.Context, files *agentFiles, rec mcp.Entry, a *agent } // The entry is this CLI's, so it is only changed when add would write it differently. argv, _ := mcpconfig.Argv(loc.entry) - changed, err := agentconfig.Changed(a, loc.entry, argv[0], serveArgs(rec, a.Name), pinnedEnv(rec)) + changed, err := agentconfig.Changed(a, loc.entry, argv[0], serveArgs(rec.Profile, rec.Service, a.Name), pinnedEnv(rec.ConfigFile)) if err != nil { return statusUnknown, loc.path, "", err } @@ -400,19 +400,6 @@ func agentStatus(ctx context.Context, files *agentFiles, rec mcp.Entry, a *agent return agentStatusInstalled, loc.path, "", nil } -// serveArgs returns the arguments that add gives the entry of rec's server for the agent named agentName. -func serveArgs(rec mcp.Entry, agentName string) []string { - return []string{"aitools", "mcp", "serve", mcpconfig.ProfileFlag, rec.Profile, mcpconfig.ServiceFlag, rec.Service, mcpconfig.AgentFlag, agentName} -} - -// pinnedEnv returns the environment that add gives the entry of rec: its config file, when the record pins one. -func pinnedEnv(rec mcp.Entry) map[string]string { - if rec.ConfigFile == "" { - return nil - } - return map[string]string{mcpconfig.ConfigFileEnv: rec.ConfigFile} -} - // profileCheckTimeout bounds each --check request of a profile, so that a host that never answers ends the profile's // checks while a profile with many servers still gets every answer. Tests shorten it. var profileCheckTimeout = 5 * time.Second diff --git a/cmd/aitools/mcp_login.go b/cmd/aitools/mcp_login.go index 56bf44d9bd6..8ca8e83b642 100644 --- a/cmd/aitools/mcp_login.go +++ b/cmd/aitools/mcp_login.go @@ -291,6 +291,12 @@ func signIn(ctx context.Context, errOut io.Writer, w *databricks.WorkspaceClient return "", false, urlShown, describeRequestError(profileName, pinnedFile, err) } + reportSignedIn(errOut, svc, profileName, alreadySignedIn) + return signInStateActive, alreadySignedIn, urlShown, nil +} + +// reportSignedIn prints that the profile is signed in to svc, and the note that the service has for its users. +func reportSignedIn(errOut io.Writer, svc mcp.Service, profileName string, alreadySignedIn bool) { if alreadySignedIn { fmt.Fprintf(errOut, "Already signed in to %s on profile %s.\n", svc.FullName, profileName) } else { @@ -299,5 +305,4 @@ func signIn(ctx context.Context, errOut io.Writer, w *databricks.WorkspaceClient if svc.Known != nil && svc.Known.Note != "" { fmt.Fprintln(errOut, svc.Known.Note) } - return signInStateActive, alreadySignedIn, urlShown, nil } diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go new file mode 100644 index 00000000000..1b32ceab155 --- /dev/null +++ b/cmd/aitools/mcp_pickers.go @@ -0,0 +1,346 @@ +package aitools + +import ( + "context" + "errors" + "fmt" + "slices" + "strings" + + "github.com/charmbracelet/huh" + "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/databrickscfg/profile" + "github.com/databricks/cli/libs/telemetry/protos" +) + +// Package-level seams for the interactive pickers of `mcp add` and `mcp remove`. Tests override +// them. The agent picker and the plan confirm are shared with `install` (promptAgentSelection and +// promptProceed in install.go). +var ( + selectProfile = profile.SelectProfile + promptServiceSelection = defaultPromptServiceSelection + promptLocation = defaultPromptLocation + promptRemoveSelection = defaultPromptRemoveSelection + promptSignInNow = defaultPromptSignInNow +) + +// anotherSchemaValue is the value of the "Another schema..." row. It has no dots, so it cannot be +// a service full name. +const anotherSchemaValue = "(another schema)" + +// serviceLister lists the MCP services of a schema. +type serviceLister func(ctx context.Context, location string) ([]mcp.Service, error) + +// serviceRow is one row of the service picker: a service of the schema, whether the profile already has it +// installed, and whether it starts checked. +type serviceRow struct { + service mcp.Service + installed bool + checked bool +} + +// servicePick is what the service picker returns: the rows checked, and whether "Another schema..." +// was checked. +type servicePick struct { + services []mcp.Service + another bool +} + +// profileChoice is the cause of the failure that resolveProfile returns when several workspace profiles exist and none +// is the default. It holds those profiles, so that the picker offers the same ones. +type profileChoice struct { + profiles profile.Profiles +} + +func (e *profileChoice) Error() string { return "several workspace profiles" } + +// promptProfile asks which of the profiles the servers bind to. Ctrl+C reads as the abort of the other pickers. +func promptProfile(ctx context.Context, profiles profile.Profiles) (string, error) { + name, err := selectProfile(ctx, profile.SelectConfig{ + Label: "Which Databricks profile should these MCP servers use?", + Profiles: profiles, + }) + if errors.Is(err, cmdio.ErrCtrlC) { + return "", huh.ErrUserAborted + } + return name, err +} + +// chooseProfile returns the profile for an add, and whether a picker chose it. A terminal resolves the profile as a +// non-interactive run does: --profile, DATABRICKS_CONFIG_PROFILE, the default profile, then the only workspace profile. +// The picker runs only where that stops with several profiles. +func chooseProfile(ctx context.Context, flagValue string, interactive bool) (string, bool, error) { + name, err := resolveProfile(ctx, flagValue) + if err == nil || !interactive { + return name, false, err + } + choice, ok := errors.AsType[*profileChoice](err) + if !ok { + return name, false, err + } + name, err = promptProfile(ctx, choice.profiles) + return name, true, err +} + +// mcpAgentChoices returns the agent picker rows: the MCP-capable agents installed for MCP, all checked. It also returns +// the MCP-capable agents the picker does not list, each with the reason when its check failed, as a named agent reports it. +func mcpAgentChoices(ctx context.Context) (choices []agentChoice, notFound []string) { + for _, a := range agents.MCPAgents() { + installed, err := a.InstalledForMCP(ctx) + switch { + case err != nil: + notFound = append(notFound, fmt.Sprintf("%s (%s)", a.DisplayName, err)) + case !installed: + notFound = append(notFound, a.DisplayName) + default: + choices = append(choices, agentChoice{agent: a, label: a.DisplayName, preselect: true}) + } + } + return choices, notFound +} + +// pickServicesInteractively lists the services of location and returns the ones the user checks. +// "Another schema..." asks for a catalog and schema and lists that one next; an empty answer stops browsing and keeps +// the picks. A schema is listed once per session, and a schema shown again starts with its checks, which the new page +// replaces. A schema that cannot be listed after the first one is reported and asked for again, with the checks kept. +// Services already installed for the profile are rows too, unchecked and marked installed, so that they can be added to +// another agent; they are also named above the picker. +func pickServicesInteractively(ctx context.Context, b addBinding, location string, state *mcp.State, list serviceLister) ([]mcp.Service, error) { + // checks holds the services checked on each schema page, listings the services of each schema listed, and schemas + // the pages in the order shown. + checks := map[string][]mcp.Service{} + listings := map[string][]mcp.Service{} + var schemas []string + for { + services, listed := listings[location] + if !listed { + var err error + if services, err = list(ctx, location); err != nil { + if len(schemas) == 0 { + return nil, err + } + cmdio.LogString(ctx, fmt.Sprintf("Cannot list MCP servers in %s: %s", location, err)) + if location, err = promptLocation(); err != nil { + return nil, err + } + if location == "" { + break + } + continue + } + listings[location] = services + cmdio.LogString(ctx, fmt.Sprintf("Discovering MCP servers in %s on profile %s... %d found.", location, b.profile, len(services))) + } + // A page shown first starts with the recommended services that are not installed checked; a page shown + // again starts with its checks. + firstVisit := !slices.Contains(schemas, location) + var installed []string + rows := make([]serviceRow, 0, len(services)) + for _, s := range services { + // An entry this profile cannot bind through, as one recorded under another config file, is not shown as + // installed. The check of the picked services reports it, and one service's entry does not stop the list. + entry, err := mcp.FindEntry(ctx, state, s.FullName, b.profile, b.configFile) + isInstalled := err == nil && entry != nil + if isInstalled { + installed = append(installed, s.Leaf) + } + // A row whose entry cannot be read is refused by the run, so it is not checked. + checked := err == nil && !isInstalled && s.Known != nil && s.Known.Recommended + if !firstVisit { + checked = slices.ContainsFunc(checks[location], func(p mcp.Service) bool { return p.FullName == s.FullName }) + } + rows = append(rows, serviceRow{service: s, installed: isInstalled, checked: checked}) + } + if len(installed) > 0 { + cmdio.LogString(ctx, fmt.Sprintf("Already installed for profile %s: %s", b.profile, strings.Join(installed, ", "))) + } + pick, err := promptServiceSelection(location, rows) + if err != nil { + return nil, err + } + if firstVisit { + schemas = append(schemas, location) + } + checks[location] = pick.services + if !pick.another { + break + } + if location, err = promptLocation(); err != nil { + return nil, err + } + if location == "" { + break + } + } + + var picked []mcp.Service + for _, schema := range schemas { + picked = append(picked, checks[schema]...) + } + if len(picked) == 0 { + return nil, failure(protos.AitoolsErrorCategoryInvalidFlags, "select at least one MCP service") + } + return picked, nil +} + +// typedLocation returns a catalog and schema typed by the user in the form --location takes: trimmed and +// in lowercase. +func typedLocation(s string) string { + return strings.ToLower(strings.TrimSpace(s)) +} + +// serviceChoiceLabel is a service picker row: the leaf name, its description and its tags. The +// CLI's own description wins for a known system.ai service; otherwise the API comment is shown. +func serviceChoiceLabel(s mcp.Service) string { + desc := s.Comment + var tags []string + if k := s.Known; k != nil { + desc = k.Summary + if k.Recommended { + tags = append(tags, "recommended") + } + if k.Beta { + tags = append(tags, "beta") + } + } + if s.SignInRequired { + tags = append(tags, "sign-in required") + } + label := s.Leaf + if desc != "" { + label += " " + desc + } + if len(tags) > 0 { + label += " (" + strings.Join(tags, ", ") + ")" + } + return label +} + +// serviceRowLabel is the label of a service picker row. A service the profile has installed is marked so. +func serviceRowLabel(r serviceRow) string { + if r.installed { + return serviceChoiceLabel(r.service) + " (installed)" + } + return serviceChoiceLabel(r.service) +} + +// defaultPromptServiceSelection is the huh multi-select over the rows of a schema. +func defaultPromptServiceSelection(location string, rows []serviceRow) (servicePick, error) { + options := make([]huh.Option[string], 0, len(rows)+1) + for _, r := range rows { + options = append(options, huh.NewOption(serviceRowLabel(r), r.service.FullName).Selected(r.checked)) + } + options = append(options, huh.NewOption("Another schema...", anotherSchemaValue)) + + var selected []string + err := huh.NewMultiSelect[string](). + Title("Select MCP servers in " + location). + Description(multiSelectHelp). + Options(options...). + Value(&selected). + Run() + if err != nil { + return servicePick{}, err + } + + var pick servicePick + for _, name := range selected { + if name == anotherSchemaValue { + pick.another = true + continue + } + i := slices.IndexFunc(rows, func(r serviceRow) bool { return r.service.FullName == name }) + pick.services = append(pick.services, rows[i].service) + } + return pick, nil +} + +// defaultPromptLocation asks for the catalog and schema to list next. +func defaultPromptLocation() (string, error) { + var location string + err := huh.NewInput(). + Title("Catalog and schema to list MCP servers from (leave empty to stop)"). + Value(&location). + Validate(func(s string) error { + if typed := typedLocation(s); typed != "" && validateLocation(typed) != nil { + return errors.New("enter .") + } + return nil + }). + Run() + return typedLocation(location), err +} + +// chooseRemovals runs the remove picker over the installed servers for targets: only the servers installed for the +// named agents, or every server when targets is nil. Only the agents named with --agents lose a pick, so the picks +// need no agent check. offered is false when no server is offered, and then nothing is asked. +func chooseRemovals(state *mcp.State, targets []*agents.Agent) (picks []mcp.Entry, offered bool, err error) { + var entries []mcp.Entry + for _, e := range state.Servers { + if targets == nil || slices.ContainsFunc(targets, func(a *agents.Agent) bool { + _, ok := e.Agents[a.Name] + return ok + }) { + entries = append(entries, e) + } + } + if len(entries) == 0 { + return nil, false, nil + } + picks, err = promptRemoveSelection(entries, targets) + return picks, true, err +} + +// removeChoiceLabel is a remove picker row: server name, service, profile and the agents the pick is removed from, +// which are the named agents when --agents is set. +func removeChoiceLabel(e mcp.Entry, targets []*agents.Agent) string { + var names []string + for name := range e.Agents { + if targets == nil || slices.ContainsFunc(targets, func(a *agents.Agent) bool { return a.Name == name }) { + names = append(names, name) + } + } + slices.Sort(names) + return fmt.Sprintf("%s %s %s %s", e.Name, e.Service, e.Profile, mcpAgentList(names)) +} + +// defaultPromptRemoveSelection is the huh multi-select over the installed servers. +func defaultPromptRemoveSelection(entries []mcp.Entry, targets []*agents.Agent) ([]mcp.Entry, error) { + options := make([]huh.Option[int], 0, len(entries)) + for i, e := range entries { + options = append(options, huh.NewOption(removeChoiceLabel(e, targets), i)) + } + + var selected []int + err := huh.NewMultiSelect[int](). + Title("Select MCP servers to remove"). + Description(multiSelectHelp). + Options(options...). + Value(&selected). + Run() + if err != nil { + return nil, err + } + + chosen := make([]mcp.Entry, 0, len(selected)) + for _, i := range selected { + chosen = append(chosen, entries[i]) + } + return chosen, nil +} + +// defaultPromptSignInNow asks whether to start the sign-in of a service now. The default is yes. The sign-in names the +// profile once it starts, so the question does not. +func defaultPromptSignInNow(service string) (bool, error) { + yes := true + err := huh.NewConfirm(). + Title(service + " needs a one-time sign-in. Sign in now?"). + Value(&yes). + Run() + if err != nil { + return false, err + } + return yes, nil +} diff --git a/cmd/aitools/mcp_pickers_test.go b/cmd/aitools/mcp_pickers_test.go new file mode 100644 index 00000000000..15ffce73b5f --- /dev/null +++ b/cmd/aitools/mcp_pickers_test.go @@ -0,0 +1,584 @@ +package aitools + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/charmbracelet/huh" + "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/databrickscfg/profile" + "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/telemetry/protos" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPickServicesInteractivelyKeepsChecksAcrossSchemas(t *testing.T) { + ctx := cmdio.MockDiscard(t.Context()) + state := &mcp.State{Servers: []mcp.Entry{{Name: "github-logfood", Service: "system.ai.github", Profile: "logfood"}}} + schemas := map[string][]mcp.Service{ + "system.ai": {{FullName: "system.ai.github", Leaf: "github"}, {FullName: "system.ai.dbsql", Leaf: "dbsql"}}, + "analytics.tools": {{FullName: "analytics.tools.search", Leaf: "search"}}, + } + var listed []string + list := func(_ context.Context, location string) ([]mcp.Service, error) { + listed = append(listed, location) + return schemas[location], nil + } + + var rowsPerPage [][]string + origPick := promptServiceSelection + t.Cleanup(func() { promptServiceSelection = origPick }) + promptServiceSelection = func(location string, rows []serviceRow) (servicePick, error) { + var names []string + for _, r := range rows { + names = append(names, r.service.FullName) + // The installed github row is shown, marked installed and unchecked. + if r.service.FullName == "system.ai.github" { + assert.True(t, r.installed) + assert.False(t, r.checked) + } + } + rowsPerPage = append(rowsPerPage, names) + if location == "system.ai" { + // Checks dbsql, then asks for another schema. + return servicePick{services: []mcp.Service{rows[1].service}, another: true}, nil + } + return servicePick{services: []mcp.Service{rows[0].service}}, nil + } + origLocation := promptLocation + t.Cleanup(func() { promptLocation = origLocation }) + promptLocation = func() (string, error) { return "analytics.tools", nil } + + picked, err := pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "system.ai", state, list) + require.NoError(t, err) + assert.Equal(t, []string{"system.ai", "analytics.tools"}, listed) + assert.Equal(t, [][]string{{"system.ai.github", "system.ai.dbsql"}, {"analytics.tools.search"}}, rowsPerPage) + var names []string + for _, s := range picked { + names = append(names, s.FullName) + } + assert.Equal(t, []string{"system.ai.dbsql", "analytics.tools.search"}, names) +} + +// TestPickServicesInteractivelyRevisitShowsAndReplacesChecks checks that a schema shown again starts with the +// services checked on it before, and that its new page replaces them, so an unchecked service is dropped. +func TestPickServicesInteractivelyRevisitShowsAndReplacesChecks(t *testing.T) { + ctx := cmdio.MockDiscard(t.Context()) + schemas := map[string][]mcp.Service{ + "system.ai": {{FullName: "system.ai.github", Leaf: "github"}, {FullName: "system.ai.dbsql", Leaf: "dbsql"}}, + "analytics.tools": {{FullName: "analytics.tools.search", Leaf: "search"}}, + } + listed := map[string]int{} + list := func(_ context.Context, location string) ([]mcp.Service, error) { + listed[location]++ + return schemas[location], nil + } + + // Each page answers with the rows it is given, checked or not, and the schema sequence the user typed. + type page struct { + location string + checked map[string]bool + pick []string + another bool + } + pages := []page{ + {location: "system.ai", checked: map[string]bool{"system.ai.github": false, "system.ai.dbsql": false}, pick: []string{"system.ai.dbsql"}, another: true}, + {location: "analytics.tools", checked: map[string]bool{"analytics.tools.search": false}, pick: []string{"analytics.tools.search"}, another: true}, + // Back on system.ai, dbsql is shown checked; the user unchecks it and checks github. + {location: "system.ai", checked: map[string]bool{"system.ai.github": false, "system.ai.dbsql": true}, pick: []string{"system.ai.github"}, another: true}, + // Back on analytics.tools, search is shown checked and the user finishes there. + {location: "analytics.tools", checked: map[string]bool{"analytics.tools.search": true}, pick: []string{"analytics.tools.search"}}, + } + origPick := promptServiceSelection + t.Cleanup(func() { promptServiceSelection = origPick }) + promptServiceSelection = func(location string, rows []serviceRow) (servicePick, error) { + require.NotEmpty(t, pages, "more pages than expected") + want := pages[0] + pages = pages[1:] + require.Equal(t, want.location, location) + for _, r := range rows { + assert.Equal(t, want.checked[r.service.FullName], r.checked, r.service.FullName) + } + var picked []mcp.Service + for _, name := range want.pick { + for _, s := range schemas[location] { + if s.FullName == name { + picked = append(picked, s) + } + } + } + return servicePick{services: picked, another: want.another}, nil + } + locations := []string{"analytics.tools", "system.ai", "analytics.tools"} + origLocation := promptLocation + t.Cleanup(func() { promptLocation = origLocation }) + promptLocation = func() (string, error) { + next := locations[0] + locations = locations[1:] + return next, nil + } + + picked, err := pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "system.ai", &mcp.State{}, list) + require.NoError(t, err) + require.Empty(t, pages, "every page was shown") + var names []string + for _, s := range picked { + names = append(names, s.FullName) + } + assert.Equal(t, []string{"system.ai.github", "analytics.tools.search"}, names) + // A schema shown again is not listed again. + assert.Equal(t, map[string]int{"system.ai": 1, "analytics.tools": 1}, listed) +} + +// TestPickServicesInteractivelyEmptyLocationStopsAndKeepsPicks checks that an empty answer to "Another schema" stops +// browsing: the picks of every page so far are kept, and no other schema is listed. +func TestPickServicesInteractivelyEmptyLocationStopsAndKeepsPicks(t *testing.T) { + ctx := cmdio.MockDiscard(t.Context()) + list := func(_ context.Context, location string) ([]mcp.Service, error) { + require.Equal(t, "system.ai", location, "no schema is listed after the empty answer") + return []mcp.Service{{FullName: "system.ai.github", Leaf: "github"}, {FullName: "system.ai.dbsql", Leaf: "dbsql"}}, nil + } + origPick := promptServiceSelection + t.Cleanup(func() { promptServiceSelection = origPick }) + promptServiceSelection = func(_ string, rows []serviceRow) (servicePick, error) { + return servicePick{services: []mcp.Service{rows[0].service}, another: true}, nil + } + origLocation := promptLocation + t.Cleanup(func() { promptLocation = origLocation }) + asked := 0 + promptLocation = func() (string, error) { + asked++ + return "", nil + } + + picked, err := pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "system.ai", &mcp.State{}, list) + require.NoError(t, err) + assert.Equal(t, 1, asked) + require.Len(t, picked, 1) + assert.Equal(t, "system.ai.github", picked[0].FullName) +} + +// TestPickServicesInteractivelyKeepsPicksWhenAnotherSchemaFails checks that a schema that cannot be listed is +// reported and asked for again, and that the services picked before are kept. A failure on the first schema +// ends the run, since nothing is picked yet. +func TestPickServicesInteractivelyKeepsPicksWhenAnotherSchemaFails(t *testing.T) { + ctx := cmdio.MockDiscard(t.Context()) + list := func(_ context.Context, location string) ([]mcp.Service, error) { + switch location { + case "system.ai": + return []mcp.Service{{FullName: "system.ai.github", Leaf: "github"}}, nil + case "analytics.tools": + return []mcp.Service{{FullName: "analytics.tools.search", Leaf: "search"}}, nil + } + return nil, errors.New("schema not found") + } + origPick := promptServiceSelection + t.Cleanup(func() { promptServiceSelection = origPick }) + promptServiceSelection = func(_ string, rows []serviceRow) (servicePick, error) { + return servicePick{services: []mcp.Service{rows[0].service}, another: rows[0].service.FullName == "system.ai.github"}, nil + } + // The user types a typo first, then the schema that exists. The prompt returns the location trimmed and in lowercase. + typed := []string{"analytcs.tools", "analytics.tools"} + origLocation := promptLocation + t.Cleanup(func() { promptLocation = origLocation }) + promptLocation = func() (string, error) { + next := typed[0] + typed = typed[1:] + return next, nil + } + + picked, err := pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "system.ai", &mcp.State{}, list) + require.NoError(t, err) + var names []string + for _, s := range picked { + names = append(names, s.FullName) + } + assert.Equal(t, []string{"system.ai.github", "analytics.tools.search"}, names) + + // A failure on the first schema is returned, since nothing is picked yet. + _, err = pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "missing.schema", &mcp.State{}, list) + assert.EqualError(t, err, "schema not found") +} + +// TestPickServicesInteractivelyEntryUnderOtherConfigFile checks that a service recorded under another config file does +// not stop the picker for the other services: its row is not marked installed, and the check of the picked services +// reports the binding. +func TestPickServicesInteractivelyEntryUnderOtherConfigFile(t *testing.T) { + ctx := cmdio.MockDiscard(t.Context()) + state := &mcp.State{Servers: []mcp.Entry{{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", ConfigFile: filepath.Join(t.TempDir(), "other.cfg"), + }}} + list := func(context.Context, string) ([]mcp.Service, error) { + return []mcp.Service{{FullName: "system.ai.github", Leaf: "github"}, {FullName: "system.ai.dbsql", Leaf: "dbsql"}}, nil + } + origPick := promptServiceSelection + t.Cleanup(func() { promptServiceSelection = origPick }) + promptServiceSelection = func(_ string, rows []serviceRow) (servicePick, error) { + require.Len(t, rows, 2) + assert.False(t, rows[0].installed) + assert.False(t, rows[1].installed) + return servicePick{services: []mcp.Service{rows[1].service}}, nil + } + + picked, err := pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "system.ai", state, list) + require.NoError(t, err) + require.Len(t, picked, 1) + assert.Equal(t, "system.ai.dbsql", picked[0].FullName) +} + +// TestPickServicesInteractivelyUncheckableEntryIsNotChecked checks that a recommended service whose entry cannot be read +// is not checked: the run refuses it, so the picker must not offer it as a pick. +func TestPickServicesInteractivelyUncheckableEntryIsNotChecked(t *testing.T) { + ctx := cmdio.MockDiscard(t.Context()) + state := &mcp.State{Servers: []mcp.Entry{{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", ConfigFile: filepath.Join(t.TempDir(), "other.cfg"), + }}} + list := func(context.Context, string) ([]mcp.Service, error) { + return []mcp.Service{ + {FullName: "system.ai.github", Leaf: "github", Known: &mcp.KnownService{Recommended: true}}, + {FullName: "system.ai.dbsql", Leaf: "dbsql", Known: &mcp.KnownService{Recommended: true}}, + }, nil + } + origPick := promptServiceSelection + t.Cleanup(func() { promptServiceSelection = origPick }) + promptServiceSelection = func(_ string, rows []serviceRow) (servicePick, error) { + require.Len(t, rows, 2) + assert.False(t, rows[0].checked, "the entry under another config file must not start checked") + assert.True(t, rows[1].checked) + return servicePick{services: []mcp.Service{rows[1].service}}, nil + } + + _, err := pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "system.ai", state, list) + require.NoError(t, err) +} + +// TestPickServicesInteractivelyAnnouncesEachListingOnce checks that the discovery line is printed for each listing that +// runs, and not again when a schema is shown again. +func TestPickServicesInteractivelyAnnouncesEachListingOnce(t *testing.T) { + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + schemas := map[string][]mcp.Service{ + "system.ai": {{FullName: "system.ai.github", Leaf: "github"}}, + "analytics.tools": {{FullName: "analytics.tools.search", Leaf: "search"}}, + } + list := func(_ context.Context, location string) ([]mcp.Service, error) { + return schemas[location], nil + } + origPick := promptServiceSelection + t.Cleanup(func() { promptServiceSelection = origPick }) + pages := []struct { + another bool + }{{another: true}, {another: true}, {}} + promptServiceSelection = func(_ string, rows []serviceRow) (servicePick, error) { + page := pages[0] + pages = pages[1:] + return servicePick{services: []mcp.Service{rows[0].service}, another: page.another}, nil + } + locations := []string{"analytics.tools", "system.ai"} + origLocation := promptLocation + t.Cleanup(func() { promptLocation = origLocation }) + promptLocation = func() (string, error) { + next := locations[0] + locations = locations[1:] + return next, nil + } + + _, err := pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "system.ai", &mcp.State{}, list) + require.NoError(t, err) + assert.Empty(t, pages) + assert.Equal(t, 2, strings.Count(stderr.String(), "Discovering MCP servers in "), stderr.String()) +} + +func TestPickServicesInteractivelyNeedsOneService(t *testing.T) { + ctx := cmdio.MockDiscard(t.Context()) + list := func(context.Context, string) ([]mcp.Service, error) { + return []mcp.Service{{FullName: "system.ai.dbsql", Leaf: "dbsql"}}, nil + } + origPick := promptServiceSelection + t.Cleanup(func() { promptServiceSelection = origPick }) + promptServiceSelection = func(string, []serviceRow) (servicePick, error) { + return servicePick{}, nil + } + + _, err := pickServicesInteractively(ctx, defaultBinding(t, "logfood"), "system.ai", &mcp.State{}, list) + require.Error(t, err) + assert.Equal(t, "select at least one MCP service", err.Error()) + assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, errorCategory(err)) +} + +func TestServiceChoiceLabel(t *testing.T) { + cases := []struct { + name string + service mcp.Service + want string + }{ + { + name: "known and recommended", + service: mcp.Service{Leaf: "genie_one_mcp", Comment: "api text", Known: &mcp.KnownService{ + Summary: "Ask questions about your data", Recommended: true, + }}, + want: "genie_one_mcp Ask questions about your data (recommended)", + }, + { + name: "sign-in required uses the API comment", + service: mcp.Service{Leaf: "search", Comment: "Search docs", SignInRequired: true}, + want: "search Search docs (sign-in required)", + }, + { + name: "no description", + service: mcp.Service{Leaf: "bare"}, + want: "bare", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, serviceChoiceLabel(tc.service)) + }) + } +} + +func TestChooseProfileDefaultIsNotAsked(t *testing.T) { + writeDatabricksCfg(t, "[__settings__]\ndefault_profile = dogfood\n\n[logfood]\nhost = https://logfood.test\n\n[dogfood]\nhost = https://dogfood.test\n") + + origSelect := selectProfile + t.Cleanup(func() { selectProfile = origSelect }) + selectProfile = func(context.Context, profile.SelectConfig) (string, error) { + t.Fatal("the picker must not run when the default profile is configured") + return "", nil + } + + name, picked, err := chooseProfile(t.Context(), "", true) + require.NoError(t, err) + assert.Equal(t, "dogfood", name) + assert.False(t, picked) +} + +func TestChooseProfilePickerListsEveryProfile(t *testing.T) { + writeDatabricksCfg(t, "[logfood]\nhost = https://logfood.test\n\n[dogfood]\nhost = https://dogfood.test\n") + + origSelect := selectProfile + t.Cleanup(func() { selectProfile = origSelect }) + var got profile.SelectConfig + selectProfile = func(_ context.Context, cfg profile.SelectConfig) (string, error) { + got = cfg + return "logfood", nil + } + + name, picked, err := chooseProfile(t.Context(), "", true) + require.NoError(t, err) + assert.Equal(t, "logfood", name) + assert.True(t, picked) + assert.Len(t, got.Profiles, 2) +} + +// TestChooseProfileCtrlCIsTheOtherPickersAbort checks that Ctrl+C at the profile picker aborts as the other pickers do: +// the same error, categorized as USER_ABORTED. +func TestChooseProfileCtrlCIsTheOtherPickersAbort(t *testing.T) { + writeDatabricksCfg(t, "[logfood]\nhost = https://logfood.test\n\n[dogfood]\nhost = https://dogfood.test\n") + + origSelect := selectProfile + t.Cleanup(func() { selectProfile = origSelect }) + selectProfile = func(context.Context, profile.SelectConfig) (string, error) { + return "", cmdio.ErrCtrlC + } + + _, picked, err := chooseProfile(t.Context(), "", true) + require.ErrorIs(t, err, huh.ErrUserAborted) + assert.True(t, picked) + assert.Equal(t, "user aborted", err.Error()) + assert.Equal(t, protos.AitoolsErrorCategoryUserAborted, errorCategory(err)) +} + +func TestChooseProfileSingleProfileIsNotAsked(t *testing.T) { + writeDatabricksCfg(t, "[logfood]\nhost = https://logfood.test\n") + + origSelect := selectProfile + t.Cleanup(func() { selectProfile = origSelect }) + selectProfile = func(context.Context, profile.SelectConfig) (string, error) { + t.Fatal("the picker must not run with one workspace profile") + return "", nil + } + + name, picked, err := chooseProfile(t.Context(), "", true) + require.NoError(t, err) + assert.Equal(t, "logfood", name) + assert.False(t, picked) +} + +func TestChooseProfileNoProfiles(t *testing.T) { + writeDatabricksCfg(t, "") + _, _, err := chooseProfile(t.Context(), "", true) + require.Error(t, err) + assert.Contains(t, err.Error(), "no workspace profiles in") +} + +func TestChooseProfileWithoutTerminalDoesNotPrompt(t *testing.T) { + writeDatabricksCfg(t, "[logfood]\nhost = https://logfood.test\n\n[dogfood]\nhost = https://dogfood.test\n") + + origSelect := selectProfile + t.Cleanup(func() { selectProfile = origSelect }) + selectProfile = func(context.Context, profile.SelectConfig) (string, error) { + t.Fatal("the picker must not run without a terminal") + return "", nil + } + + _, _, err := chooseProfile(t.Context(), "", false) + require.Error(t, err) + assert.Contains(t, err.Error(), "several workspace profiles exist; pass --profile") + + name, picked, err := chooseProfile(t.Context(), "dogfood", true) + require.NoError(t, err) + assert.Equal(t, "dogfood", name) + assert.False(t, picked) +} + +// TestChooseProfileEnvironmentIsAnExplicitChoice checks that DATABRICKS_CONFIG_PROFILE chooses the profile in a +// terminal too, as --profile does: the picker does not run, and the profile resolves as it does without a terminal. +func TestChooseProfileEnvironmentIsAnExplicitChoice(t *testing.T) { + writeDatabricksCfg(t, "[logfood]\nhost = https://logfood.test\n\n[dogfood]\nhost = https://dogfood.test\n") + t.Setenv("DATABRICKS_CONFIG_PROFILE", "dogfood") + + origSelect := selectProfile + t.Cleanup(func() { selectProfile = origSelect }) + selectProfile = func(context.Context, profile.SelectConfig) (string, error) { + t.Fatal("the picker must not run when DATABRICKS_CONFIG_PROFILE is set") + return "", nil + } + + name, picked, err := chooseProfile(t.Context(), "", true) + require.NoError(t, err) + assert.Equal(t, "dogfood", name) + assert.False(t, picked) + + // A variable that names a profile missing from the file is what a non-interactive run gets too. + t.Setenv("DATABRICKS_CONFIG_PROFILE", "missing") + interactive, _, err := chooseProfile(t.Context(), "", true) + require.NoError(t, err) + plain, _, err := chooseProfile(t.Context(), "", false) + require.NoError(t, err) + assert.Equal(t, "missing", interactive) + assert.Equal(t, plain, interactive) +} + +func TestMcpAgentChoicesListInstalledAgents(t *testing.T) { + withHome(t) + fakeBinsOnPath(t, agents.ByName(agents.NameCodex).Binary) + choices, notFound := mcpAgentChoices(t.Context()) + + var listed []string + for _, c := range choices { + assert.True(t, c.agent.SupportsMCP(), c.agent.Name) + assert.True(t, c.preselect, c.agent.Name) + listed = append(listed, c.agent.Name) + } + assert.Contains(t, listed, agents.NameCodex) + assert.NotContains(t, listed, agents.NameCursor) + assert.Contains(t, notFound, agents.ByName(agents.NameCursor).DisplayName) + assert.NotContains(t, notFound, agents.ByName(agents.NameCodex).DisplayName) +} + +// TestMcpAgentChoicesFollowInstalledForMCP checks that an agent is listed when InstalledForMCP says so: Codex on PATH +// counts as installed for MCP, even without a ~/.codex directory, and with CODEX_HOME set only that directory counts. +// TestMcpAgentChoicesNamesAgentWhoseCheckFailed checks that an agent whose installed check fails is not offered, and is +// named as not found with that error, as a named agent reports it. +func TestMcpAgentChoicesNamesAgentWhoseCheckFailed(t *testing.T) { + t.Setenv(env.HomeEnvVar(), "") + t.Setenv("PATH", t.TempDir()) + for _, name := range agentHomeEnv { + t.Setenv(name, "") + } + ctx := cmdio.MockDiscard(t.Context()) + claude := agents.ByName(agents.NameClaudeCode) + _, checkErr := claude.InstalledForMCP(ctx) + require.Error(t, checkErr, "the check needs a home directory") + + choices, notFound := mcpAgentChoices(ctx) + for _, c := range choices { + assert.NotEqual(t, claude, c.agent) + } + assert.Contains(t, notFound, fmt.Sprintf("%s (%s)", claude.DisplayName, checkErr)) +} + +func TestMcpAgentChoicesFollowInstalledForMCP(t *testing.T) { + home := withHome(t) + fakeBinsOnPath(t, agents.ByName(agents.NameCodex).Binary) + assert.True(t, listsAgent(t, agents.NameCodex)) + + // The binary on PATH does not count when CODEX_HOME names a directory that is not there, and nothing is created. + missing := filepath.Join(home, "missing-codex-home") + t.Setenv(codexHomeEnv, missing) + assert.False(t, listsAgent(t, agents.NameCodex)) + assert.NoDirExists(t, missing) +} + +// listsAgent reports whether the agent picker lists the agent named name. +func listsAgent(t *testing.T, name string) bool { + t.Helper() + choices, _ := mcpAgentChoices(t.Context()) + return slices.ContainsFunc(choices, func(c agentChoice) bool { return c.agent.Name == name }) +} + +func TestChooseRemovals(t *testing.T) { + origRemove := promptRemoveSelection + t.Cleanup(func() { promptRemoveSelection = origRemove }) + promptRemoveSelection = func([]mcp.Entry, []*agents.Agent) ([]mcp.Entry, error) { + t.Fatal("the picker must not run with nothing installed") + return nil, nil + } + got, offered, err := chooseRemovals(&mcp.State{}, nil) + require.NoError(t, err) + assert.False(t, offered) + assert.Empty(t, got) + + state := &mcp.State{Servers: []mcp.Entry{ + {Name: "github-logfood", Service: "system.ai.github", Profile: "logfood"}, + {Name: "github-dogfood", Service: "system.ai.github", Profile: "dogfood"}, + }} + promptRemoveSelection = func(entries []mcp.Entry, _ []*agents.Agent) ([]mcp.Entry, error) { + assert.Len(t, entries, 2) + return entries[1:], nil + } + got, offered, err = chooseRemovals(state, nil) + require.NoError(t, err) + assert.True(t, offered) + require.Len(t, got, 1) + assert.Equal(t, "github-dogfood", got[0].Name) + + // --agents narrows the picker to the servers installed for those agents. + state.Servers[0].Agents = map[string]mcp.AgentRecord{agents.NameCodex: {}} + state.Servers[1].Agents = map[string]mcp.AgentRecord{agents.NameClaudeCode: {}} + promptRemoveSelection = func(entries []mcp.Entry, _ []*agents.Agent) ([]mcp.Entry, error) { + require.Len(t, entries, 1) + assert.Equal(t, "github-logfood", entries[0].Name) + return entries, nil + } + got, offered, err = chooseRemovals(state, []*agents.Agent{agents.ByName(agents.NameCodex)}) + require.NoError(t, err) + assert.True(t, offered) + require.Len(t, got, 1) + assert.Equal(t, "github-logfood", got[0].Name) + + // No server for those agents: nothing is offered. + _, offered, err = chooseRemovals(state, []*agents.Agent{agents.ByName(agents.NameCursor)}) + require.NoError(t, err) + assert.False(t, offered) +} + +func TestRemoveChoiceLabel(t *testing.T) { + entry := mcp.Entry{ + Name: "github-logfood", Service: "system.ai.github", Profile: "logfood", + Agents: map[string]mcp.AgentRecord{agents.NameCodex: {}, agents.NameClaudeCode: {}}, + } + assert.Equal(t, "github-logfood system.ai.github logfood Claude Code, Codex CLI", removeChoiceLabel(entry, nil)) + + // With --agents, the label names only the agents the pick is removed from. + codex := []*agents.Agent{agents.ByName(agents.NameCodex)} + assert.Equal(t, "github-logfood system.ai.github logfood Codex CLI", removeChoiceLabel(entry, codex)) +} diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index edcd9f94c15..6802f56da76 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -18,7 +18,7 @@ import ( ) // 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" +const removeFlagsHint = "pass --names, --profile or --all so the command runs without interactive prompts" type mcpRemoveFlags struct { names string @@ -83,7 +83,8 @@ func NewMcpRemoveCmd() *cobra.Command { 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. +In a terminal, with none of --names, --profile or --all, the command shows the installed servers to +choose from. Without a terminal, one of them is required. With --profile or --all and nothing installed to remove, the command succeeds and removes nothing. Only entries this CLI wrote are removed. An entry that was changed outside this CLI is left in place @@ -133,7 +134,8 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso names := splitAndTrim(f.names) agentNames := splitAndTrim(f.agents) profileName := profileFlag(cmd) - if err := validateMCPRemoveFlags(f.all, names, profileName); err != nil { + interactive := !jsonMode && cmdio.IsPromptSupported(ctx) + if err := validateMCPRemoveFlags(f.all, names, profileName, interactive); err != nil { return err } @@ -151,12 +153,40 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso if err != nil { return err } - selected, err := selectInstalls(state, names, profileName) - if err != nil { - return withAdoptHint(ctx, err, state) - } - if err := checkTargetsInstalled(selected, targets); err != nil { - return err + var selected []mcp.Entry + if interactive && !f.all && len(names) == 0 && profileName == "" { + // An agent with no installed server is refused as it is without a terminal, before the picker offers nothing for it. + if err := checkTargetsInstalled(state.Servers, targets); err != nil { + return err + } + var offered bool + selected, offered, err = chooseRemovals(state, targets) + if err != nil { + return err + } + if offered && len(selected) == 0 { + cmdio.LogString(ctx, "No servers selected; nothing removed.") + return nil + } + if offered { + // The picker chose the servers, so the removal is confirmed, as add confirms its plan and uninstall its removal. + proceed, err := promptProceed() + if err != nil { + return err + } + if !proceed { + cmdio.LogString(ctx, cancelledMessage) + return nil + } + } + } else { + selected, err = selectInstalls(state, names, profileName) + if err != nil { + return withAdoptHint(ctx, err, state) + } + 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. @@ -225,11 +255,12 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso } // validateMCPRemoveFlags rejects a choice of servers that cannot run, before anything is read or written. -func validateMCPRemoveFlags(all bool, names []string, profileName string) error { +// Without a choice, a terminal run shows the picker; any other run needs one. +func validateMCPRemoveFlags(all bool, names []string, profileName string, interactive bool) error { if all && len(names) > 0 { return failure(protos.AitoolsErrorCategoryInvalidFlags, "--all cannot be combined with --names") } - if !all && len(names) == 0 && profileName == "" { + if !all && len(names) == 0 && profileName == "" && !interactive { return failure(protos.AitoolsErrorCategoryInvalidFlags, "%s", removeFlagsHint) } return nil @@ -372,7 +403,7 @@ func checkTargetsInstalled(selected []mcp.Entry, targets []*agents.Agent) error _, ok := e.Agents[a.Name] return ok }) { - return failure(categoryServiceNotFound, "no selected MCP server is installed for %s", agentDisplayName(a.Name)) + return failure(categoryServiceNotFound, "no MCP server is installed for %s", agentDisplayName(a.Name)) } } return nil diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index c9ca0e5b1be..6ecb45de9b6 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -36,7 +36,7 @@ func TestValidateMCPRemoveFlags(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - err := validateMCPRemoveFlags(tc.all, tc.names, tc.profile) + err := validateMCPRemoveFlags(tc.all, tc.names, tc.profile, false) if tc.want == "" { assert.NoError(t, err) return @@ -46,7 +46,10 @@ func TestValidateMCPRemoveFlags(t *testing.T) { }) } - err := validateMCPRemoveFlags(false, nil, "") + // In a terminal, no choice opens the picker instead of failing. + assert.NoError(t, validateMCPRemoveFlags(false, nil, "", true)) + + err := validateMCPRemoveFlags(false, nil, "", false) assert.Equal(t, protos.AitoolsErrorCategoryInvalidFlags, errorCategory(err)) } @@ -462,7 +465,7 @@ func TestMcpRemoveRefusesAgentWithNothingInstalled(t *testing.T) { 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, "no MCP server is installed for Cursor", out.Error) assert.Equal(t, categoryServiceNotFound, out.ErrorCategory) // Nothing was removed by the refusal. @@ -682,9 +685,9 @@ func TestMcpRemoveWithAgentsSkipsRecordWithoutAgents(t *testing.T) { 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. + // Named explicitly, the same entry is a refusal: no 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") + require.ErrorContains(t, err, "no MCP server is installed for Claude Code") } // TestMcpRemoveKeptReasonForDatabricksEntryOmitsForce checks that an entry this CLI wrote, but that serves another @@ -715,3 +718,125 @@ func jsonServers(t *testing.T, path string) map[string]any { servers, _ := readJSONFile(t, path)["mcpServers"].(map[string]any) return servers } + +// TestMcpRemovePickerRemovesTheChosenServers checks that the remove picker, shown in a terminal with no choice given, +// removes the servers that are checked and keeps the others. +func TestMcpRemovePickerRemovesTheChosenServers(t *testing.T) { + home := withHome(t) + claudePath := filepath.Join(home, ".claude.json") + require.NoError(t, os.WriteFile(claudePath, []byte(`{"mcpServers": {`+ + `"github-logfood": `+claudeEntry("system.ai.github", "logfood", "")+`, `+ + `"dbsql-logfood": `+claudeEntry("system.ai.dbsql", "logfood", "")+`}}`), 0o600)) + saveState(t, claudeServerEntry(claudePath, "github-logfood", "system.ai.github"), claudeServerEntry(claudePath, "dbsql-logfood", "system.ai.dbsql")) + + origRemove, origProceed := promptRemoveSelection, promptProceed + t.Cleanup(func() { promptRemoveSelection, promptProceed = origRemove, origProceed }) + promptRemoveSelection = func(entries []mcp.Entry, _ []*agents.Agent) ([]mcp.Entry, error) { + require.Len(t, entries, 2) + return entries[1:], nil + } + promptProceed = func() (bool, error) { return true, nil } + + require.NoError(t, runInteractive(t, "mcp", "remove")) + servers := readJSONFile(t, claudePath)["mcpServers"].(map[string]any) + assert.Contains(t, servers, "github-logfood") + assert.NotContains(t, servers, "dbsql-logfood") + + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + require.Len(t, state.Servers, 1) + assert.Equal(t, "github-logfood", state.Servers[0].Name) +} + +// TestMcpRemovePickerRefusesAgentWithNoServer checks that --agents naming an agent with no installed server is refused +// before the picker runs, as a run without a terminal refuses it. +func TestMcpRemovePickerRefusesAgentWithNoServer(t *testing.T) { + withHome(t) + saveState(t, claudeServerEntry("", "github-logfood", "system.ai.github")) + + origRemove := promptRemoveSelection + t.Cleanup(func() { promptRemoveSelection = origRemove }) + promptRemoveSelection = func([]mcp.Entry, []*agents.Agent) ([]mcp.Entry, error) { + t.Error("the picker ran for an agent with no installed server") + return nil, nil + } + + err := runInteractive(t, "mcp", "remove", "--agents", "codex") + require.Error(t, err) + assert.Equal(t, "no MCP server is installed for "+agents.ByName(agents.NameCodex).DisplayName, err.Error()) + assert.Equal(t, categoryServiceNotFound, errorCategory(err)) + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Len(t, state.Servers, 1) +} + +// TestMcpRemovePickerWithTwoAgentsNeedsOnePickPerServer checks that --agents with two agents accepts a pick installed for +// only one of them: the pick is removed from that agent, and the server installed for the other agent, which is not +// picked, stays. +func TestMcpRemovePickerWithTwoAgentsNeedsOnePickPerServer(t *testing.T) { + home := withHome(t) + claudePath := filepath.Join(home, ".claude.json") + require.NoError(t, os.WriteFile(claudePath, []byte(`{"mcpServers": {`+ + `"github-logfood": `+claudeEntry("system.ai.github", "logfood", "")+`, `+ + `"dbsql-logfood": `+claudeEntry("system.ai.dbsql", "logfood", "")+`}}`), 0o600)) + dbsql := claudeServerEntry(claudePath, "dbsql-logfood", "system.ai.dbsql") + dbsql.Agents[agents.NameCodex] = mcp.AgentRecord{Path: filepath.Join(home, ".codex", "config.toml"), Scope: "user"} + saveState(t, claudeServerEntry(claudePath, "github-logfood", "system.ai.github"), dbsql) + + origRemove, origProceed := promptRemoveSelection, promptProceed + t.Cleanup(func() { promptRemoveSelection, promptProceed = origRemove, origProceed }) + promptRemoveSelection = func(entries []mcp.Entry, targets []*agents.Agent) ([]mcp.Entry, error) { + require.Len(t, targets, 2) + require.Len(t, entries, 2) + return entries[:1], nil + } + promptProceed = func() (bool, error) { return true, nil } + + require.NoError(t, runInteractive(t, "mcp", "remove", "--agents", "claude-code,codex")) + servers := readJSONFile(t, claudePath)["mcpServers"].(map[string]any) + assert.NotContains(t, servers, "github-logfood") + assert.Contains(t, servers, "dbsql-logfood") +} + +// TestMcpRemovePickerDeclinedRemovesNothing checks that a picked removal the user declines at Proceed? removes nothing. +func TestMcpRemovePickerDeclinedRemovesNothing(t *testing.T) { + withHome(t) + saveState(t, claudeServerEntry("", "github-logfood", "system.ai.github")) + + origRemove, origProceed := promptRemoveSelection, promptProceed + t.Cleanup(func() { promptRemoveSelection, promptProceed = origRemove, origProceed }) + promptRemoveSelection = func(entries []mcp.Entry, _ []*agents.Agent) ([]mcp.Entry, error) { + return entries, nil + } + promptProceed = func() (bool, error) { return false, nil } + + require.NoError(t, runInteractive(t, "mcp", "remove")) + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Len(t, state.Servers, 1) +} + +// TestMcpRemovePickerEmptyPickRemovesNothing checks that a picker closed with nothing checked removes nothing. +func TestMcpRemovePickerEmptyPickRemovesNothing(t *testing.T) { + withHome(t) + saveState(t, claudeServerEntry("", "github-logfood", "system.ai.github")) + + origRemove := promptRemoveSelection + t.Cleanup(func() { promptRemoveSelection = origRemove }) + promptRemoveSelection = func([]mcp.Entry, []*agents.Agent) ([]mcp.Entry, error) { + return nil, nil + } + + require.NoError(t, runInteractive(t, "mcp", "remove")) + state, err := mcp.LoadState(t.Context()) + require.NoError(t, err) + assert.Len(t, state.Servers, 1) +} + +// claudeServerEntry is the state entry of a server installed for Claude Code, in the config file at claudePath. +func claudeServerEntry(claudePath, name, service string) mcp.Entry { + return mcp.Entry{ + Name: name, Service: service, Profile: "logfood", Host: "https://adb-1.test", Command: testDatabricksCommand, + Agents: map[string]mcp.AgentRecord{agents.NameClaudeCode: {Path: claudePath, Scope: "user"}}, + } +} diff --git a/cmd/aitools/uninstall.go b/cmd/aitools/uninstall.go index 787156ff519..d043a4a39c5 100644 --- a/cmd/aitools/uninstall.go +++ b/cmd/aitools/uninstall.go @@ -89,7 +89,7 @@ The command exits with code 1 when every removal it attempts fails.`, return err } if !proceed { - cmdio.LogString(ctx, "Cancelled.") + cmdio.LogString(ctx, cancelledMessage) funnel.finishWith(ctx, protos.AitoolsCommandOutcomeCancelled, protos.AitoolsErrorCategoryUnspecified) return nil } diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index 7a101c935ec..a9ef9f9a2c4 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -581,6 +581,28 @@ func withoutServer(doc map[string]any, root []string, name string) map[string]an return out } +// Unchanged reports whether Upsert would leave the entry current as it is: current is a Databricks entry whose launch +// keys already match the entry Upsert writes for cmd, args and env. Upsert uses the same comparison. +func Unchanged(a *agents.Agent, cmd string, args []string, env map[string]string, current map[string]any) (bool, error) { + spec, err := specOf(a) + if err != nil { + return false, err + } + ours, err := normalize(spec.Entry(cmd, args, env)) + if err != nil { + return false, err + } + if !mcpconfig.IsDatabricksEntry(current) { + return false, nil + } + keys := ownedKeys(spec) + merged, err := keepUserKeys(current, ours, keys) + if err != nil { + return false, err + } + return sameEntry(launchOf(current, keys), launchOf(merged, keys)) +} + // sameEntry compares two entries as JSON values, so the in-memory Go types of a // freshly built entry and one decoded from a file compare equal. func sameEntry(a, b map[string]any) (bool, error) { diff --git a/libs/aitools/mcp/binding.go b/libs/aitools/mcp/binding.go index 641b41ad870..1e65ec3cced 100644 --- a/libs/aitools/mcp/binding.go +++ b/libs/aitools/mcp/binding.go @@ -155,6 +155,14 @@ func PinnedFile(entry *Entry, configFile string) string { return "" } +// CheckProfile returns the PROFILE_NOT_FOUND error for a profile that configFile does not name with a host, or nil when +// it does. It is CheckBinding for a caller that has no service yet, so its message names the profile and no server. It +// reads the config files only and makes no request. +func CheckProfile(profileName, configFile string) error { + _, err := profileFor("", profileName, configFile, nil) + return err +} + // CheckBinding returns the state entry for service and profileName bound to configFile, the config file the caller // resolved with ResolveConfigFile, or nil when there is none. It returns the error Bind returns when the profile does not // match: the profile is gone or has no host, or with an entry, its host or workspace changed. The profile is checked @@ -180,7 +188,8 @@ func CheckBinding(ctx context.Context, state *State, service, profileName, confi } // profileFor returns the profile profileName in configFile, or the PROFILE_NOT_FOUND error that says it -// is gone. name and entry describe the state entry the profile serves; entry is nil without one. +// is gone. name and entry describe the state entry the profile serves; entry is nil without one, and name is +// "" when no server is chosen yet. func profileFor(name, profileName, configFile string, entry *Entry) (profile.Profile, error) { p, err := configFiles{}.profile(configFile, profileName) switch { @@ -234,12 +243,16 @@ func ConfigFileCommand(configFile, command string) string { // 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 -// message only says how to set the profile up, without a host. An entry pinned to a config file puts that -// file in the recreate hint. +// message only says how to set the profile up, without a host, and it names the server only when name is set. An entry +// pinned to a config file puts that file in the recreate hint. func profileGoneError(name, profileName, path string, entry *Entry, problem string, cause error) error { if entry == nil { login := authLoginCommand + " --profile " + shellquote.BashArg(profileName) - message := fmt.Sprintf("MCP server %s needs Databricks profile \"%s\", which %s in %s. Set it up with: %s", name, profileName, problem, path, login) + subject := "Databricks profile \"" + profileName + "\"" + if name != "" { + subject = "MCP server " + name + " needs " + subject + } + message := fmt.Sprintf("%s, which %s in %s. Set it up with: %s", subject, problem, path, login) return &BindError{Category: BindProfileNotFound, message: message, cause: cause} } pinnedPath := "" diff --git a/libs/aitools/mcp/binding_test.go b/libs/aitools/mcp/binding_test.go index 5171a8f095a..8ad13e5244b 100644 --- a/libs/aitools/mcp/binding_test.go +++ b/libs/aitools/mcp/binding_test.go @@ -880,6 +880,46 @@ func TestCheckBindingChecksProfileWithoutEntry(t *testing.T) { } } +// TestCheckProfileWithoutServer checks the profile check of a run that has no service yet. A missing profile and a +// profile with no host name the profile and no server, and an unreadable config file is uncategorized. +func TestCheckProfileWithoutServer(t *testing.T) { + login := "databricks auth login --profile " + bindingTestProfile + tests := []struct { + name string + contents string + want string + category mcp.BindCategory + }{ + { + name: "missing", + contents: "[other]\nhost = https://other.test\n", + want: "Databricks profile \"logfood\", which does not exist in %s. Set it up with: " + login, + category: mcp.BindProfileNotFound, + }, + { + name: "no host", + contents: "[" + bindingTestProfile + "]\naccount_id = 123\n", + want: "Databricks profile \"logfood\", which has no host in %s. Set it up with: " + login, + category: mcp.BindProfileNotFound, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := bindingTestResolved(t, bindingTestWriteConfig(t, tt.contents)) + + err := mcp.CheckProfile(bindingTestProfile, path) + requireBindError(t, err, tt.category) + assert.Equal(t, fmt.Sprintf(tt.want, filepath.ToSlash(path)), err.Error()) + }) + } + + t.Run("unreadable", func(t *testing.T) { + // A directory cannot be read as a config file. + err := mcp.CheckProfile(bindingTestProfile, bindingTestResolved(t, t.TempDir())) + requireBindError(t, err, mcp.BindUncategorized) + }) +} + func TestAuthErrorNamesPinnedConfigFile(t *testing.T) { cause := errors.New("Invalid access token.") assert.EqualError(t, mcp.AuthError("logfood", "/work/cfg/logfood.cfg", cause), diff --git a/libs/cmdio/io.go b/libs/cmdio/io.go index 7f0dd853e8c..ea1cde703c8 100644 --- a/libs/cmdio/io.go +++ b/libs/cmdio/io.go @@ -11,9 +11,9 @@ import ( "github.com/databricks/cli/libs/flags" ) -// errCtrlC is returned when the user cancels a TUI prompt with Ctrl+C. The +// ErrCtrlC is returned when the user cancels a TUI prompt with Ctrl+C. The // "^C" string matches the historical wire format; goldens depend on it. -var errCtrlC = errors.New("^C") +var ErrCtrlC = errors.New("^C") // runTUI runs a tea.Program through cmdIO's tea program slot so spinners and // pagers can't fight a prompt for the terminal. Blocks until the model quits. @@ -21,7 +21,7 @@ func (c *cmdIO) runTUI(m tea.Model) (tea.Model, error) { p := tea.NewProgram(m, tea.WithInput(c.in), tea.WithOutput(c.err), - // Ctrl+C is delivered as a key event so the model can return errCtrlC. + // Ctrl+C is delivered as a key event so the model can return ErrCtrlC. tea.WithoutSignalHandler(), ) c.acquireTeaProgram(p) diff --git a/libs/cmdio/prompt.go b/libs/cmdio/prompt.go index 4469465e972..3f84d18a2ff 100644 --- a/libs/cmdio/prompt.go +++ b/libs/cmdio/prompt.go @@ -259,7 +259,7 @@ func (c *cmdIO) runPromptModel(m *promptModel) (string, error) { pm := final.(*promptModel) switch { case pm.cancelled: - return "", errCtrlC + return "", ErrCtrlC case pm.deleted: return "", io.EOF } diff --git a/libs/cmdio/select.go b/libs/cmdio/select.go index 2d481139bae..c4a9a710c3f 100644 --- a/libs/cmdio/select.go +++ b/libs/cmdio/select.go @@ -521,7 +521,7 @@ func (c *cmdIO) runSelectModel(m *selectModel) (int, error) { } sm := final.(*selectModel) if sm.cancelled { - return 0, errCtrlC + return 0, ErrCtrlC } return sm.originalIndex(), nil } From 6d81bf875c34e2a4c4458da0dbfa4ee3cab30d12 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Mon, 16 Nov 2026 12:42:16 +0000 Subject: [PATCH 02/16] Regenerate the hidden help golden for pflag 1.1 boolean flags main bumped github.com/spf13/pflag to 1.1.0 (#7635), which prints boolean flags as --force[=true|false] in help output and widens the flag column. Co-authored-by: Isaac --- acceptance/cmd/aitools/mcp/hidden/output.txt | 24 ++++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/acceptance/cmd/aitools/mcp/hidden/output.txt b/acceptance/cmd/aitools/mcp/hidden/output.txt index f6d269ce565..b3bf21deb53 100644 --- a/acceptance/cmd/aitools/mcp/hidden/output.txt +++ b/acceptance/cmd/aitools/mcp/hidden/output.txt @@ -56,17 +56,17 @@ Examples: databricks aitools mcp add --names github,web_search --agents claude-code,cursor --profile dogfood Flags: - --agents string Agents to install for, comma-separated (default: a picker in a terminal; otherwise every detected MCP-capable agent) - --force Overwrite an existing server with the same name that this CLI did not write - -h, --help help for add - --location string Schema to resolve leaf names in, as . (default: system.ai, or the one schema that the full names in --names share) - --login Sign in to each sign-in-required server that was installed, after the installs - --name string Server name to use instead of the generated one; only with exactly one service - --names string Services to install: full names (system.ai.github) or leaf names (github), comma-separated - --no-login Do not sign in; print the login commands for sign-in-required servers (default without a terminal; in a terminal, the default asks for each one) + --agents string Agents to install for, comma-separated (default: a picker in a terminal; otherwise every detected MCP-capable agent) + --force[=true|false] Overwrite an existing server with the same name that this CLI did not write + -h, --help[=true|false] help for add + --location string Schema to resolve leaf names in, as . (default: system.ai, or the one schema that the full names in --names share) + --login[=true|false] Sign in to each sign-in-required server that was installed, after the installs + --name string Server name to use instead of the generated one; only with exactly one service + --names string Services to install: full names (system.ai.github) or leaf names (github), comma-separated + --no-login[=true|false] Do not sign in; print the login commands for sign-in-required servers (default without a terminal; in a terminal, the default asks for each one) Global Flags: - --debug enable debug logging - -o, --output type output type: text or json (default text) - -p, --profile string ~/.databrickscfg profile - -t, --target string bundle target to use (if applicable) + --debug[=true|false] enable debug logging + -o, --output type output type: text or json (default text) + -p, --profile string ~/.databrickscfg profile + -t, --target string bundle target to use (if applicable) From 3d0d1a9484e9f2bd2f84a24b5906226a45c65857 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Mon, 16 Nov 2026 14:20:25 +0000 Subject: [PATCH 03/16] Regenerate the list and remove help golden for the remove picker remove now shows a picker in a terminal, so its help in the help golden says how the servers are chosen there. Co-authored-by: Isaac --- acceptance/cmd/aitools/mcp/help/output.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/acceptance/cmd/aitools/mcp/help/output.txt b/acceptance/cmd/aitools/mcp/help/output.txt index 888f1a8129c..b0a42531033 100644 --- a/acceptance/cmd/aitools/mcp/help/output.txt +++ b/acceptance/cmd/aitools/mcp/help/output.txt @@ -47,7 +47,8 @@ Remove Databricks managed MCP servers that this CLI installed. 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. +In a terminal, with none of --names, --profile or --all, the command shows the installed servers to +choose from. Without a terminal, one of them is required. With --profile or --all and nothing installed to remove, the command succeeds and removes nothing. Only entries this CLI wrote are removed. An entry that was changed outside this CLI is left in place From abc995902bc43f603ab69e0dcb4c6251cf09d06e Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Mon, 16 Nov 2026 13:31:59 +0000 Subject: [PATCH 04/16] Keep each service picker row on one line The service picker wrapped rows that had long API comments, and huh counts one line per option, so the cursor left the screen past about row 14 at 80x24 and never scrolled back. A row is now the leaf name, a description and its tags, on one line of at most the terminal width. The description falls back from the CLI's Summary to its Label to the first sentence of the API comment, with markdown links removed, and it is cut with an ellipsis when the row is too long. The tags always show. Co-authored-by: Isaac --- cmd/aitools/mcp_pickers.go | 103 +++++++++++++++++++++++++------- cmd/aitools/mcp_pickers_test.go | 86 ++++++++++++++++++++++++-- 2 files changed, 163 insertions(+), 26 deletions(-) diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go index 1b32ceab155..914827566bb 100644 --- a/cmd/aitools/mcp_pickers.go +++ b/cmd/aitools/mcp_pickers.go @@ -4,15 +4,19 @@ import ( "context" "errors" "fmt" + "os" + "regexp" "slices" "strings" "github.com/charmbracelet/huh" + "github.com/charmbracelet/x/ansi" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/databrickscfg/profile" "github.com/databricks/cli/libs/telemetry/protos" + "golang.org/x/term" ) // Package-level seams for the interactive pickers of `mcp add` and `mcp remove`. Tests override @@ -191,13 +195,40 @@ func typedLocation(s string) string { return strings.ToLower(strings.TrimSpace(s)) } -// serviceChoiceLabel is a service picker row: the leaf name, its description and its tags. The -// CLI's own description wins for a known system.ai service; otherwise the API comment is shown. -func serviceChoiceLabel(s mcp.Service) string { - desc := s.Comment +// serviceRowChrome is the width the picker takes around a row's label: the border, the cursor and the checkbox. +const serviceRowChrome = 8 + +var ( + // markdownLink matches a [text](url) link, and bareURL a URL that is not in a link. + markdownLink = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`) + bareURL = regexp.MustCompile(`https?://\S+`) +) + +// serviceDescription is the description of a service row: the CLI's Summary for a known system.ai service, else its +// Label, else the first sentence of the API comment. +func serviceDescription(s mcp.Service) string { + if k := s.Known; k != nil { + if k.Summary != "" { + return k.Summary + } + if k.Label != "" { + return k.Label + } + } + text := markdownLink.ReplaceAllString(s.Comment, "$1") + text = bareURL.ReplaceAllString(text, "") + text = strings.Join(strings.Fields(text), " ") + if i := strings.Index(text, ". "); i >= 0 { + text = text[:i+1] + } + return text +} + +// serviceChoiceLabel is a service picker row: the leaf name, its description and its tags, on one line of at most +// width columns (no limit when width is 0). The description is cut to make room for the tags, which always show. +func serviceChoiceLabel(s mcp.Service, installed bool, width int) string { var tags []string if k := s.Known; k != nil { - desc = k.Summary if k.Recommended { tags = append(tags, "recommended") } @@ -208,40 +239,68 @@ func serviceChoiceLabel(s mcp.Service) string { if s.SignInRequired { tags = append(tags, "sign-in required") } + var suffix string + if len(tags) > 0 { + suffix += " (" + strings.Join(tags, ", ") + ")" + } + if installed { + suffix += " (installed)" + } + label := s.Leaf - if desc != "" { - label += " " + desc + desc := serviceDescription(s) + if desc == "" { + return label + suffix } - if len(tags) > 0 { - label += " (" + strings.Join(tags, ", ") + ")" + if width > 0 { + room := width - ansi.StringWidth(label+suffix) - 2 + if room <= 0 { + return label + suffix + } + desc = ansi.Truncate(desc, room, "…") } - return label + return label + " " + desc + suffix } // serviceRowLabel is the label of a service picker row. A service the profile has installed is marked so. -func serviceRowLabel(r serviceRow) string { - if r.installed { - return serviceChoiceLabel(r.service) + " (installed)" - } - return serviceChoiceLabel(r.service) +func serviceRowLabel(r serviceRow, width int) string { + return serviceChoiceLabel(r.service, r.installed, width) } -// defaultPromptServiceSelection is the huh multi-select over the rows of a schema. -func defaultPromptServiceSelection(location string, rows []serviceRow) (servicePick, error) { +// serviceSelectField is the multi-select over the rows of a schema, whose rows fit width columns when width is set. +// Its values go to selected. +func serviceSelectField(location string, rows []serviceRow, width int, selected *[]string) *huh.MultiSelect[string] { + if width > 0 { + width -= serviceRowChrome + } options := make([]huh.Option[string], 0, len(rows)+1) for _, r := range rows { - options = append(options, huh.NewOption(serviceRowLabel(r), r.service.FullName).Selected(r.checked)) + options = append(options, huh.NewOption(serviceRowLabel(r, width), r.service.FullName).Selected(r.checked)) } options = append(options, huh.NewOption("Another schema...", anotherSchemaValue)) - var selected []string - err := huh.NewMultiSelect[string](). + return huh.NewMultiSelect[string](). Title("Select MCP servers in " + location). Description(multiSelectHelp). Options(options...). - Value(&selected). - Run() + Value(selected) +} + +// terminalWidth is the width of the terminal the pickers draw in, or 0 when stdout is not a terminal, which leaves +// the rows whole. +func terminalWidth() int { + width, _, err := term.GetSize(int(os.Stdout.Fd())) if err != nil { + return 0 + } + return width +} + +// defaultPromptServiceSelection is the huh multi-select over the rows of a schema. +func defaultPromptServiceSelection(location string, rows []serviceRow) (servicePick, error) { + var selected []string + field := serviceSelectField(location, rows, terminalWidth(), &selected) + if err := huh.NewForm(huh.NewGroup(field)).WithShowHelp(false).Run(); err != nil { return servicePick{}, err } diff --git a/cmd/aitools/mcp_pickers_test.go b/cmd/aitools/mcp_pickers_test.go index 15ffce73b5f..ae9736d51ca 100644 --- a/cmd/aitools/mcp_pickers_test.go +++ b/cmd/aitools/mcp_pickers_test.go @@ -9,7 +9,9 @@ import ( "strings" "testing" + tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/huh" + "github.com/charmbracelet/x/ansi" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/cmdio" @@ -315,9 +317,11 @@ func TestPickServicesInteractivelyNeedsOneService(t *testing.T) { func TestServiceChoiceLabel(t *testing.T) { cases := []struct { - name string - service mcp.Service - want string + name string + service mcp.Service + installed bool + width int + want string }{ { name: "known and recommended", @@ -336,10 +340,44 @@ func TestServiceChoiceLabel(t *testing.T) { service: mcp.Service{Leaf: "bare"}, want: "bare", }, + { + name: "known label without summary", + service: mcp.Service{Leaf: "atlassian", Known: &mcp.KnownService{Label: "Jira and Confluence"}}, + want: "atlassian Jira and Confluence", + }, + { + name: "first sentence of the comment, without links", + service: mcp.Service{Leaf: "workiq", Comment: "Connects to a third-party service. Verify the terms. [Documentation](https://docs.example.test/x)"}, + want: "workiq Connects to a third-party service.", + }, + { + name: "a bare link is dropped", + service: mcp.Service{Leaf: "bare_link", Comment: "See https://docs.example.test/x for details"}, + want: "bare_link See for details", + }, + { + name: "installed", + service: mcp.Service{Leaf: "slack", Known: &mcp.KnownService{Summary: "Channels and messages"}, SignInRequired: true}, + installed: true, + want: "slack Channels and messages (sign-in required) (installed)", + }, + { + name: "description is cut with an ellipsis to fit the width", + service: mcp.Service{Leaf: "workiq", Comment: "Connects to a third-party service. Verify the terms.", SignInRequired: true}, + width: 42, + want: "workiq Connects to a… (sign-in required)", + }, + { + name: "no room for the description keeps the tags", + service: mcp.Service{Leaf: "a_long_service_name", Comment: "Description", SignInRequired: true}, + installed: true, + width: 30, + want: "a_long_service_name (sign-in required) (installed)", + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, serviceChoiceLabel(tc.service)) + assert.Equal(t, tc.want, serviceChoiceLabel(tc.service, tc.installed, tc.width)) }) } } @@ -582,3 +620,43 @@ func TestRemoveChoiceLabel(t *testing.T) { codex := []*agents.Agent{agents.ByName(agents.NameCodex)} assert.Equal(t, "github-logfood system.ai.github logfood Codex CLI", removeChoiceLabel(entry, codex)) } + +// TestServiceSelectKeepsCursorInView checks that the service picker follows the cursor down to "Another schema...", +// the last row, in a terminal of 80x24 and of 60x20. The rows have long API comments, as services outside the table do. +func TestServiceSelectKeepsCursorInView(t *testing.T) { + const comment = "Connects to a third-party service. Verify that the provider's terms meet your organization's " + + "compliance requirements. [Documentation](https://docs.databricks.com/aws/en/agents/mcp-tools/built-in-mcp-services#external-services)" + var rows []serviceRow + for i := range 17 { + leaf := fmt.Sprintf("service_%02d", i) + rows = append(rows, serviceRow{service: mcp.Service{FullName: "system.ai." + leaf, Leaf: leaf, Comment: comment, SignInRequired: true}}) + } + rows = append(rows, serviceRow{service: mcp.Service{FullName: "system.ai.last", Leaf: "last", Comment: comment}, installed: true}) + + for _, size := range []struct{ width, height int }{{80, 24}, {60, 20}} { + t.Run(fmt.Sprintf("%dx%d", size.width, size.height), func(t *testing.T) { + var selected []string + form := huh.NewForm(huh.NewGroup(serviceSelectField("system.ai", rows, size.width, &selected))).WithShowHelp(false) + form.Init() + form.Update(tea.WindowSizeMsg{Width: size.width, Height: size.height}) + for range len(rows) { + form.Update(tea.KeyMsg{Type: tea.KeyDown}) + } + + view := form.View() + assert.LessOrEqual(t, strings.Count(view, "\n")+1, size.height, "the picker must fit the terminal") + for line := range strings.SplitSeq(view, "\n") { + assert.LessOrEqual(t, ansi.StringWidth(line), size.width, "a row must not wrap: %q", line) + } + var cursorRows []string + for line := range strings.SplitSeq(view, "\n") { + if strings.Contains(line, "> ") { + cursorRows = append(cursorRows, line) + } + } + if assert.Len(t, cursorRows, 1) { + assert.Contains(t, cursorRows[0], "Another schema...") + } + }) + } +} From c6c450621df6d1dcb4be0f19560875e7e6d4993d Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Mon, 16 Nov 2026 13:32:50 +0000 Subject: [PATCH 05/16] Open the service picker at the top, with recommended services first The picker opened on its first pre-checked row, and huh scrolled that row into view. Recommended services sit below the others in the API order, so on a profile with eighteen services the first seven were hidden with nothing to show they were there. Recommended services now come first, in API order within each group, so the picker opens at the top with them still pre-checked. Co-authored-by: Isaac --- cmd/aitools/mcp_pickers.go | 17 ++++++++++++++++- cmd/aitools/mcp_pickers_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go index 914827566bb..0afbeef30d8 100644 --- a/cmd/aitools/mcp_pickers.go +++ b/cmd/aitools/mcp_pickers.go @@ -1,6 +1,7 @@ package aitools import ( + "cmp" "context" "errors" "fmt" @@ -267,14 +268,28 @@ func serviceRowLabel(r serviceRow, width int) string { return serviceChoiceLabel(r.service, r.installed, width) } +// recommendedRank orders the rows of the service picker: 0 for a recommended service, else 1. +func recommendedRank(r serviceRow) int { + if r.service.Known != nil && r.service.Known.Recommended { + return 0 + } + return 1 +} + // serviceSelectField is the multi-select over the rows of a schema, whose rows fit width columns when width is set. // Its values go to selected. func serviceSelectField(location string, rows []serviceRow, width int, selected *[]string) *huh.MultiSelect[string] { if width > 0 { width -= serviceRowChrome } + // The recommended rows come first, so the picker opens at the top with the pre-checked ones in view. The API + // order holds within each group. + ordered := slices.Clone(rows) + slices.SortStableFunc(ordered, func(a, b serviceRow) int { + return cmp.Compare(recommendedRank(a), recommendedRank(b)) + }) options := make([]huh.Option[string], 0, len(rows)+1) - for _, r := range rows { + for _, r := range ordered { options = append(options, huh.NewOption(serviceRowLabel(r, width), r.service.FullName).Selected(r.checked)) } options = append(options, huh.NewOption("Another schema...", anotherSchemaValue)) diff --git a/cmd/aitools/mcp_pickers_test.go b/cmd/aitools/mcp_pickers_test.go index ae9736d51ca..8361a52a54a 100644 --- a/cmd/aitools/mcp_pickers_test.go +++ b/cmd/aitools/mcp_pickers_test.go @@ -660,3 +660,28 @@ func TestServiceSelectKeepsCursorInView(t *testing.T) { }) } } + +// TestServiceSelectOpensAtTheTop checks that a recommended service, pre-checked, does not scroll the picker down: the +// services above it stay in view. The recommended service is the eighth of eighteen, as on dogfood. +func TestServiceSelectOpensAtTheTop(t *testing.T) { + var rows []serviceRow + for i := range 18 { + leaf := fmt.Sprintf("service_%02d", i) + s := mcp.Service{FullName: "system.ai." + leaf, Leaf: leaf, Comment: "A service."} + if i == 7 { + s = mcp.Service{FullName: "system.ai.genie_one_mcp", Leaf: "genie_one_mcp", Known: &mcp.KnownService{Summary: "Ask questions about your data", Recommended: true}} + rows = append(rows, serviceRow{service: s, checked: true}) + continue + } + rows = append(rows, serviceRow{service: s}) + } + + var selected []string + form := huh.NewForm(huh.NewGroup(serviceSelectField("system.ai", rows, 80, &selected))).WithShowHelp(false) + form.Init() + form.Update(tea.WindowSizeMsg{Width: 80, Height: 24}) + view := form.View() + assert.Contains(t, view, "service_00", "the first service must be in view when the picker opens") + assert.Contains(t, view, "> ") + assert.Contains(t, view, "genie_one_mcp") +} From 4467e2604de32fda4969a13627d6be1a78f29515 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Mon, 16 Nov 2026 13:34:14 +0000 Subject: [PATCH 06/16] List what the remove picker removes before its confirm Proceed? came after the picker with nothing to say what it would remove, and the result only appeared afterwards. The remove picker now prints a plan first, in the style of the add plan: one line per agent, with the servers removed from it. With --agents, only the named agents are listed. Co-authored-by: Isaac --- cmd/aitools/mcp_pickers_test.go | 26 ++++++++++++++++++++++++++ cmd/aitools/mcp_remove.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/cmd/aitools/mcp_pickers_test.go b/cmd/aitools/mcp_pickers_test.go index 8361a52a54a..68c96ef0260 100644 --- a/cmd/aitools/mcp_pickers_test.go +++ b/cmd/aitools/mcp_pickers_test.go @@ -685,3 +685,29 @@ func TestServiceSelectOpensAtTheTop(t *testing.T) { assert.Contains(t, view, "> ") assert.Contains(t, view, "genie_one_mcp") } + +// TestRemovePlanLines checks that the plan before the remove picker's confirm names each server and the agents it is +// removed from, one line per agent. With --agents, only the named agents are listed. +func TestRemovePlanLines(t *testing.T) { + gmail := mcp.Entry{ + Name: "gmail-dogfood", Service: "system.ai.gmail", Profile: "dogfood", + Agents: map[string]mcp.AgentRecord{agents.NameCursor: {}, agents.NameClaudeCode: {}}, + } + tableau := mcp.Entry{ + Name: "tableau-dogfood", Service: "system.ai.tableau", Profile: "dogfood", + Agents: map[string]mcp.AgentRecord{agents.NameCursor: {}}, + } + selected := []mcp.Entry{gmail, tableau} + + assert.Equal(t, []string{ + "Plan:", + " Claude Code remove gmail-dogfood", + " Cursor remove gmail-dogfood, tableau-dogfood", + }, removePlanLines(selected, nil)) + + cursor := []*agents.Agent{agents.ByName(agents.NameCursor)} + assert.Equal(t, []string{ + "Plan:", + " Cursor remove gmail-dogfood, tableau-dogfood", + }, removePlanLines(selected, cursor)) +} diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 6802f56da76..dda61a53ef9 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -170,6 +170,7 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso } if offered { // The picker chose the servers, so the removal is confirmed, as add confirms its plan and uninstall its removal. + printRemovePlan(ctx, selected, targets) proceed, err := promptProceed() if err != nil { return err @@ -468,6 +469,34 @@ func dropRecords(ctx context.Context, drops []recordDrop, selected []mcp.Entry) return saveMCPState(ctx, state) } +// printRemovePlan lists what the picked servers are removed from, before the confirm of an interactive remove. +func printRemovePlan(ctx context.Context, selected []mcp.Entry, targets []*agents.Agent) { + cmdio.LogString(ctx, "") + for _, line := range removePlanLines(selected, targets) { + cmdio.LogString(ctx, line) + } + cmdio.LogString(ctx, "") +} + +// removePlanLines returns the plan of a remove: one line per agent, with the servers removed from it. Only the agents +// named with --agents, when it is set, get a line. +func removePlanLines(selected []mcp.Entry, targets []*agents.Agent) []string { + servers := map[string][]string{} + for _, e := range selected { + for name := range e.Agents { + if targets != nil && !slices.ContainsFunc(targets, func(a *agents.Agent) bool { return a.Name == name }) { + continue + } + servers[name] = append(servers[name], e.Name) + } + } + lines := []string{"Plan:"} + for _, name := range slices.Sorted(maps.Keys(servers)) { + lines = append(lines, fmt.Sprintf(" %-14s remove %s", agentDisplayName(name), strings.Join(servers[name], ", "))) + } + return lines +} + // 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 { From 68542180e8fa54a4ebdf529ada3ed5ae43943ca7 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Mon, 16 Nov 2026 13:37:51 +0000 Subject: [PATCH 07/16] Make Esc cancel the MCP pickers and name the search keys in their help MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Esc did nothing in the service, remove and sign-in pickers and the location prompt, so only Ctrl+C left them. Esc now cancels them as Ctrl+C does, with the same user aborted result. While a multi-select searches, the first Esc only leaves the search. The help line of a multi-select now says that typed keys go to the search, and how to leave it, and it shows the schema in the help line rather than in the title. The title used to read "in system.ai/drive" once the search was left, since huh shows an applied filter after the title. The profile picker's rows show the host on every row, and the active row has the ▸ marker and underline that the cmdio select uses. Co-authored-by: Isaac --- cmd/aitools/mcp_pickers.go | 117 +++++++++++++++++++++++++++----- cmd/aitools/mcp_pickers_test.go | 114 +++++++++++++++++++++++++++++++ 2 files changed, 215 insertions(+), 16 deletions(-) diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go index 0afbeef30d8..dc76aa2125f 100644 --- a/cmd/aitools/mcp_pickers.go +++ b/cmd/aitools/mcp_pickers.go @@ -10,6 +10,7 @@ import ( "slices" "strings" + tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/huh" "github.com/charmbracelet/x/ansi" "github.com/databricks/cli/libs/aitools/agents" @@ -61,11 +62,20 @@ type profileChoice struct { func (e *profileChoice) Error() string { return "several workspace profiles" } +// profilePickerActive and profilePickerInactive are the rows of the profile picker. Both show the host, so that every +// profile reads alike, and the active row has the ▸ marker and underline of the cmdio select. +const ( + profilePickerActive = `{{ "▸" | bold }} {{ .Name | underline }}{{ if .IsDefault }} {{ "[default]" | green }}{{ end }}{{ if .Host }} ({{ .Host | faint }}){{ end }}` + profilePickerInactive = ` {{ .Name }}{{ if .IsDefault }} [default]{{ end }}{{ if .Host }} ({{ .Host | faint }}){{ end }}` +) + // promptProfile asks which of the profiles the servers bind to. Ctrl+C reads as the abort of the other pickers. func promptProfile(ctx context.Context, profiles profile.Profiles) (string, error) { name, err := selectProfile(ctx, profile.SelectConfig{ - Label: "Which Databricks profile should these MCP servers use?", - Profiles: profiles, + Label: "Which Databricks profile should these MCP servers use?", + Profiles: profiles, + ActiveTemplate: profilePickerActive, + InactiveTemplate: profilePickerInactive, }) if errors.Is(err, cmdio.ErrCtrlC) { return "", huh.ErrUserAborted @@ -276,6 +286,83 @@ func recommendedRank(r serviceRow) int { return 1 } +// multiSelectSearchHelp is the help line of a multi-select while it searches: the keys type into the search, so a +// space is typed, and enter or esc leaves the search before space toggles a row. +const multiSelectSearchHelp = "type to search, enter or esc ends the search, then space toggles" + +// multiSelectDescription is the help line of a multi-select, after the scope it picks in ("" for none). It names the +// search keys while the multi-select searches. +func multiSelectDescription(scope string, searching bool) string { + help := multiSelectHelp + if searching { + help = multiSelectSearchHelp + } + if scope == "" { + return help + } + return scope + ": " + help +} + +// pickerModel is the program of a picker's form, which runs as huh's Run does. Esc cancels the picker as Ctrl+C does, +// except while the multi-select searches: then Esc is the form's, which leaves the search. +type pickerModel struct { + form *huh.Form + // searching reports whether the multi-select searches; nil for a picker with no search. + searching func() bool + // onKey runs after each message the form takes; nil when nothing depends on the keys. + onKey func() + cancelled bool +} + +// newPicker returns the picker of a form. Run sets the commands that submit and cancel a form, and the picker sets +// them too, since it runs the form without Run. +func newPicker(form *huh.Form) *pickerModel { + form.SubmitCmd = tea.Quit + form.CancelCmd = tea.Interrupt + return &pickerModel{form: form} +} + +// newMultiSelectPicker returns the picker of a multi-select in location ("" for none). Its help line follows the +// search. +func newMultiSelectPicker[T comparable](field *huh.MultiSelect[T], location string) *pickerModel { + p := newPicker(huh.NewForm(huh.NewGroup(field)).WithShowHelp(false)) + p.searching = field.GetFiltering + p.onKey = func() { + field.Description(multiSelectDescription(location, field.GetFiltering())) + } + return p +} + +func (m *pickerModel) Init() tea.Cmd { return m.form.Init() } + +func (m *pickerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + if key, ok := msg.(tea.KeyMsg); ok && key.Type == tea.KeyEsc && (m.searching == nil || !m.searching()) { + m.cancelled = true + return m, tea.Quit + } + next, cmd := m.form.Update(msg) + m.form = next.(*huh.Form) + if m.onKey != nil { + m.onKey() + // The form renders its fields as it takes a message, so an empty one shows the help line that onKey set. + next, refresh := m.form.Update(nil) + m.form = next.(*huh.Form) + return m, tea.Batch(cmd, refresh) + } + return m, cmd +} + +func (m *pickerModel) View() string { return m.form.View() } + +// runPicker runs the picker and returns huh.ErrUserAborted when the user cancels it, with Esc or Ctrl+C. +func runPicker(m *pickerModel) error { + _, err := tea.NewProgram(m).Run() + if m.cancelled || errors.Is(err, tea.ErrInterrupted) { + return huh.ErrUserAborted + } + return err +} + // serviceSelectField is the multi-select over the rows of a schema, whose rows fit width columns when width is set. // Its values go to selected. func serviceSelectField(location string, rows []serviceRow, width int, selected *[]string) *huh.MultiSelect[string] { @@ -295,8 +382,8 @@ func serviceSelectField(location string, rows []serviceRow, width int, selected options = append(options, huh.NewOption("Another schema...", anotherSchemaValue)) return huh.NewMultiSelect[string](). - Title("Select MCP servers in " + location). - Description(multiSelectHelp). + Title("Select MCP servers"). + Description(multiSelectDescription(location, false)). Options(options...). Value(selected) } @@ -315,7 +402,7 @@ func terminalWidth() int { func defaultPromptServiceSelection(location string, rows []serviceRow) (servicePick, error) { var selected []string field := serviceSelectField(location, rows, terminalWidth(), &selected) - if err := huh.NewForm(huh.NewGroup(field)).WithShowHelp(false).Run(); err != nil { + if err := runPicker(newMultiSelectPicker(field, location)); err != nil { return servicePick{}, err } @@ -334,7 +421,7 @@ func defaultPromptServiceSelection(location string, rows []serviceRow) (serviceP // defaultPromptLocation asks for the catalog and schema to list next. func defaultPromptLocation() (string, error) { var location string - err := huh.NewInput(). + input := huh.NewInput(). Title("Catalog and schema to list MCP servers from (leave empty to stop)"). Value(&location). Validate(func(s string) error { @@ -342,8 +429,8 @@ func defaultPromptLocation() (string, error) { return errors.New("enter .") } return nil - }). - Run() + }) + err := runPicker(newPicker(huh.NewForm(huh.NewGroup(input)).WithShowHelp(false))) return typedLocation(location), err } @@ -388,13 +475,12 @@ func defaultPromptRemoveSelection(entries []mcp.Entry, targets []*agents.Agent) } var selected []int - err := huh.NewMultiSelect[int](). + field := huh.NewMultiSelect[int](). Title("Select MCP servers to remove"). Description(multiSelectHelp). Options(options...). - Value(&selected). - Run() - if err != nil { + Value(&selected) + if err := runPicker(newMultiSelectPicker(field, "")); err != nil { return nil, err } @@ -409,11 +495,10 @@ func defaultPromptRemoveSelection(entries []mcp.Entry, targets []*agents.Agent) // profile once it starts, so the question does not. func defaultPromptSignInNow(service string) (bool, error) { yes := true - err := huh.NewConfirm(). + confirm := huh.NewConfirm(). Title(service + " needs a one-time sign-in. Sign in now?"). - Value(&yes). - Run() - if err != nil { + Value(&yes) + if err := runPicker(newPicker(huh.NewForm(huh.NewGroup(confirm)).WithShowHelp(false))); err != nil { return false, err } return yes, nil diff --git a/cmd/aitools/mcp_pickers_test.go b/cmd/aitools/mcp_pickers_test.go index 68c96ef0260..d74134d4057 100644 --- a/cmd/aitools/mcp_pickers_test.go +++ b/cmd/aitools/mcp_pickers_test.go @@ -8,6 +8,7 @@ import ( "slices" "strings" "testing" + "text/template" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/huh" @@ -711,3 +712,116 @@ func TestRemovePlanLines(t *testing.T) { " Cursor remove gmail-dogfood, tableau-dogfood", }, removePlanLines(selected, cursor)) } + +// TestPickerEscCancelsLikeCtrlC checks that Esc cancels a picker as Ctrl+C does, and that while a multi-select is +// searching, Esc only leaves the search. +func TestPickerEscCancelsLikeCtrlC(t *testing.T) { + var selected []string + field := serviceSelectField("system.ai", []serviceRow{{service: mcp.Service{FullName: "system.ai.a", Leaf: "a"}}}, 0, &selected) + m := newMultiSelectPicker(field, "system.ai") + m.form.Init() + m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("/")}) + require.True(t, field.GetFiltering()) + + m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + assert.False(t, m.cancelled, "the first Esc leaves the search") + assert.False(t, field.GetFiltering()) + + m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + assert.True(t, m.cancelled, "Esc outside the search cancels the picker") + + confirm := newPicker(huh.NewForm(huh.NewGroup(huh.NewConfirm().Title("Proceed?"))).WithShowHelp(false)) + confirm.form.Init() + confirm.Update(tea.KeyMsg{Type: tea.KeyEsc}) + assert.True(t, confirm.cancelled, "Esc cancels a confirm") +} + +// TestPickerEnterSubmitsAndCtrlCInterrupts checks that Enter on the last field of a picker quits the program, and that +// Ctrl+C interrupts it, so that runPicker returns. Without the commands that newPicker sets, neither quits. +func TestPickerEnterSubmitsAndCtrlCInterrupts(t *testing.T) { + var selected []int + field := huh.NewMultiSelect[int]().Options(huh.NewOption("a", 0), huh.NewOption("b", 1)).Value(&selected) + m := newMultiSelectPicker(field, "") + m.Init() + m.Update(tea.WindowSizeMsg{Width: 80, Height: 24}) + m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(" ")}) + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + assert.Equal(t, tea.QuitMsg{}, quitMsg(m, cmd, 10)) + assert.Equal(t, []int{0}, selected) + + m = newMultiSelectPicker(huh.NewMultiSelect[int]().Options(huh.NewOption("a", 0)).Value(&selected), "") + m.Init() + _, cmd = m.Update(tea.KeyMsg{Type: tea.KeyCtrlC}) + assert.Equal(t, tea.InterruptMsg{}, quitMsg(m, cmd, 10)) +} + +// quitMsg runs cmd, and the commands it leads to, feeding their messages to m. It returns the message that quits the +// program, or nil when none does within depth steps. +func quitMsg(m tea.Model, cmd tea.Cmd, depth int) tea.Msg { + if cmd == nil || depth == 0 { + return nil + } + msg := cmd() + switch msg := msg.(type) { + case tea.QuitMsg, tea.InterruptMsg: + return msg + case tea.BatchMsg: + for _, c := range msg { + if q := quitMsg(m, c, depth-1); q != nil { + return q + } + } + return nil + } + _, next := m.Update(msg) + return quitMsg(m, next, depth-1) +} + +// TestMultiSelectHelpFollowsSearch checks that the help line of a searching multi-select says how to leave the search, +// and that it reads the keys again once the search is left. +func TestMultiSelectHelpFollowsSearch(t *testing.T) { + var selected []string + field := serviceSelectField("system.ai", []serviceRow{{service: mcp.Service{FullName: "system.ai.a", Leaf: "a"}}}, 0, &selected) + m := newMultiSelectPicker(field, "system.ai") + m.form.Init() + m.Update(tea.WindowSizeMsg{Width: 80, Height: 24}) + assert.Contains(t, m.View(), "system.ai: space to toggle, enter to confirm") + + m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("/")}) + assert.Contains(t, m.View(), multiSelectSearchHelp) + + m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + assert.False(t, field.GetFiltering()) + assert.Contains(t, m.View(), "system.ai: space to toggle, enter to confirm") +} + +// TestPromptProfileRowsShowHostAndMarker checks that every row of the profile picker shows its host, and that the +// active row has the ▸ marker and the underline of the cmdio select. +func TestPromptProfileRowsShowHostAndMarker(t *testing.T) { + ctx := cmdio.MockDiscard(t.Context()) + var cfg profile.SelectConfig + origSelect := selectProfile + t.Cleanup(func() { selectProfile = origSelect }) + selectProfile = func(_ context.Context, c profile.SelectConfig) (string, error) { + cfg = c + return "", nil + } + _, err := promptProfile(ctx, profile.Profiles{ + {Name: "dogfood", Host: "https://dogfood.test"}, + {Name: "fake-a", Host: "https://fake-a.test"}, + }) + require.NoError(t, err) + + type row struct { + profile.Profile + IsDefault bool + } + render := func(tmpl string, p profile.Profile) string { + tp := template.Must(template.New("row").Funcs(cmdio.RenderFuncMap(ctx)).Parse(tmpl)) + var b strings.Builder + require.NoError(t, tp.Execute(&b, row{Profile: p})) + return b.String() + } + assert.Equal(t, "▸ dogfood (https://dogfood.test)", render(cfg.ActiveTemplate, profile.Profile{Name: "dogfood", Host: "https://dogfood.test"})) + assert.Equal(t, " fake-a (https://fake-a.test)", render(cfg.InactiveTemplate, profile.Profile{Name: "fake-a", Host: "https://fake-a.test"})) +} From 44defdc63182d4416819a60857854105bded6834 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Mon, 16 Nov 2026 15:47:55 +0000 Subject: [PATCH 08/16] Call SignInRequired as a method in the service picker and its tests Card 02 replaced the SignInRequired field of mcp.Service with a method derived from OAuthProvider. Test services that need sign-in now set an OAuthProvider. Co-authored-by: Isaac --- cmd/aitools/mcp_add_test.go | 4 ++-- cmd/aitools/mcp_pickers.go | 2 +- cmd/aitools/mcp_pickers_test.go | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index af26c145ca9..68be5e2d379 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -2016,8 +2016,8 @@ func signInRun(t *testing.T, reads *atomic.Int32, active ...string) (*databricks require.NoError(t, err) req := addRequest{profile: "logfood", workspaceID: "123", agents: []*agents.Agent{agents.ByName(agents.NameClaudeCode)}} plans := []addPlan{ - {service: mcp.Service{FullName: "system.ai.github", SignInRequired: true}}, - {service: mcp.Service{FullName: "system.ai.genie_one_mcp", SignInRequired: true}}, + {service: mcp.Service{FullName: "system.ai.github", OAuthProvider: "OAUTH_PROVIDER_TEST"}}, + {service: mcp.Service{FullName: "system.ai.genie_one_mcp", OAuthProvider: "OAUTH_PROVIDER_TEST"}}, } installed := []addAgentOutput{{Name: agents.NameClaudeCode, Status: statusInstalled}} servers := []addServerOutput{ diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go index dc76aa2125f..0d01033d693 100644 --- a/cmd/aitools/mcp_pickers.go +++ b/cmd/aitools/mcp_pickers.go @@ -247,7 +247,7 @@ func serviceChoiceLabel(s mcp.Service, installed bool, width int) string { tags = append(tags, "beta") } } - if s.SignInRequired { + if s.SignInRequired() { tags = append(tags, "sign-in required") } var suffix string diff --git a/cmd/aitools/mcp_pickers_test.go b/cmd/aitools/mcp_pickers_test.go index d74134d4057..155dd65dea1 100644 --- a/cmd/aitools/mcp_pickers_test.go +++ b/cmd/aitools/mcp_pickers_test.go @@ -333,7 +333,7 @@ func TestServiceChoiceLabel(t *testing.T) { }, { name: "sign-in required uses the API comment", - service: mcp.Service{Leaf: "search", Comment: "Search docs", SignInRequired: true}, + service: mcp.Service{Leaf: "search", Comment: "Search docs", OAuthProvider: "OAUTH_PROVIDER_TEST"}, want: "search Search docs (sign-in required)", }, { @@ -358,19 +358,19 @@ func TestServiceChoiceLabel(t *testing.T) { }, { name: "installed", - service: mcp.Service{Leaf: "slack", Known: &mcp.KnownService{Summary: "Channels and messages"}, SignInRequired: true}, + service: mcp.Service{Leaf: "slack", Known: &mcp.KnownService{Summary: "Channels and messages"}, OAuthProvider: "OAUTH_PROVIDER_TEST"}, installed: true, want: "slack Channels and messages (sign-in required) (installed)", }, { name: "description is cut with an ellipsis to fit the width", - service: mcp.Service{Leaf: "workiq", Comment: "Connects to a third-party service. Verify the terms.", SignInRequired: true}, + service: mcp.Service{Leaf: "workiq", Comment: "Connects to a third-party service. Verify the terms.", OAuthProvider: "OAUTH_PROVIDER_TEST"}, width: 42, want: "workiq Connects to a… (sign-in required)", }, { name: "no room for the description keeps the tags", - service: mcp.Service{Leaf: "a_long_service_name", Comment: "Description", SignInRequired: true}, + service: mcp.Service{Leaf: "a_long_service_name", Comment: "Description", OAuthProvider: "OAUTH_PROVIDER_TEST"}, installed: true, width: 30, want: "a_long_service_name (sign-in required) (installed)", @@ -630,7 +630,7 @@ func TestServiceSelectKeepsCursorInView(t *testing.T) { var rows []serviceRow for i := range 17 { leaf := fmt.Sprintf("service_%02d", i) - rows = append(rows, serviceRow{service: mcp.Service{FullName: "system.ai." + leaf, Leaf: leaf, Comment: comment, SignInRequired: true}}) + rows = append(rows, serviceRow{service: mcp.Service{FullName: "system.ai." + leaf, Leaf: leaf, Comment: comment, OAuthProvider: "OAUTH_PROVIDER_TEST"}}) } rows = append(rows, serviceRow{service: mcp.Service{FullName: "system.ai.last", Leaf: "last", Comment: comment}, installed: true}) From bd9635a51b9275012c54a52a354abbbabb82e306 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Tue, 17 Nov 2026 10:40:34 +0000 Subject: [PATCH 09/16] Refuse unreadable agent configs through refused in aitools mcp add An agent whose config cannot be read is refused like an uninstalled one, through the refused map, so the picker's agents are refused too and no request is sent for them. The plan line test follows that, and the merge uses maps.Copy. Co-authored-by: Isaac --- cmd/aitools/mcp_add.go | 5 ++--- cmd/aitools/mcp_add_test.go | 10 +++++----- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index 4305c6020eb..3a37d2bfda6 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "maps" "path/filepath" "slices" "strings" @@ -318,9 +319,7 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode } } held, unreadable := readAgentEntries(ctx, targets) - for a, err := range unreadable { - refused[a] = err - } + maps.Copy(refused, unreadable) // Nothing can be written when every agent is refused, so the refusals end the run before any request. if len(refused) == len(targets) { var errs []error diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index 68be5e2d379..62bf1f1fd63 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -2221,16 +2221,16 @@ func TestChooseAgentsNamesTheAgentsNotFound(t *testing.T) { } // TestAddPlanLinesSayWhenConfigCannotBeRead checks that an agent whose config cannot be read is shown as such, with the -// write that will fail, not as an add. +// reason, not as an add. func TestAddPlanLinesSayWhenConfigCannotBeRead(t *testing.T) { claude := agents.ByName(agents.NameClaudeCode) req := addRequest{ - profile: "logfood", - agents: []*agents.Agent{claude}, - unreadable: map[*agents.Agent]error{claude: errors.New("parse error")}, + profile: "logfood", + agents: []*agents.Agent{claude}, + refused: map[*agents.Agent]error{claude: errors.New("parse error")}, } plans := []addPlan{{service: mcp.Service{FullName: "system.ai.github"}, name: "github-logfood"}} - assert.Equal(t, []string{"Plan (profile logfood):", fmt.Sprintf(" %-14s cannot be read: parse error; the write will fail", claude.DisplayName)}, addPlanLines(req, plans)) + assert.Equal(t, []string{"Plan (profile logfood):", fmt.Sprintf(" %-14s cannot be checked: parse error; skipped", claude.DisplayName)}, addPlanLines(req, plans)) } func TestAddPlanLines(t *testing.T) { From 832a8a73655458119d42653a1b955610f1cbe122 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Tue, 17 Nov 2026 10:58:14 +0000 Subject: [PATCH 10/16] Give mcp add and remove their own Proceed confirm that Esc cancels The mcp commands confirmed their plan through the confirm that install uses, which did not read Esc. Esc did nothing at Proceed?, so only Ctrl+C left it. mcp add and mcp remove now ask through promptMCPProceed, a picker that defaults to yes and cancels on Esc as Ctrl+C does, and its help line says so. The confirm was the only caller of promptProceed on this base, so the install copy is removed rather than left unused, which the linter rejects. Co-authored-by: Isaac --- cmd/aitools/install.go | 13 ------------- cmd/aitools/mcp_add.go | 2 +- cmd/aitools/mcp_add_test.go | 14 +++++++------- cmd/aitools/mcp_pickers.go | 24 ++++++++++++++++++++++-- cmd/aitools/mcp_pickers_test.go | 25 +++++++++++++++++++++++++ cmd/aitools/mcp_remove.go | 2 +- cmd/aitools/mcp_remove_test.go | 18 +++++++++--------- 7 files changed, 65 insertions(+), 33 deletions(-) diff --git a/cmd/aitools/install.go b/cmd/aitools/install.go index 74521eeff64..0f1f749027e 100644 --- a/cmd/aitools/install.go +++ b/cmd/aitools/install.go @@ -32,7 +32,6 @@ const ( // install_test.go. var ( promptAgentSelection = defaultPromptAgentSelection - promptProceed = defaultPromptProceed installSkillsForAgentsFn = installer.InstallSkillsForAgents installPluginForAgentFn = installer.InstallPluginForAgent recordPluginInstallsFn = installer.RecordPluginInstalls @@ -518,18 +517,6 @@ func agentStateLabel(s agents.DisplayState) string { } } -func defaultPromptProceed() (bool, error) { - proceed := true - err := huh.NewConfirm(). - Title("Proceed?"). - Value(&proceed). - Run() - if err != nil { - return false, err - } - return proceed, nil -} - func defaultPromptAgentSelection(_ context.Context, scope string, choices []agentChoice) ([]*agents.Agent, error) { options := make([]huh.Option[string], 0, len(choices)) byName := make(map[string]*agents.Agent, len(choices)) diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index 3a37d2bfda6..ac16f626094 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -403,7 +403,7 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode // The plan is confirmed only when a picker made one of the choices. if interactive && (profilePicked || pickingServices || source == agentsPicked) { printAddPlan(ctx, req, plans) - proceed, err := promptProceed() + proceed, err := promptMCPProceed() if err != nil { return err } diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index 62bf1f1fd63..26c42cda279 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -1750,7 +1750,7 @@ func TestMcpAddPickerInstallsAcrossSchemas(t *testing.T) { return []*agents.Agent{choices[0].agent}, nil } proceeds := 0 - promptProceed = func() (bool, error) { + promptMCPProceed = func() (bool, error) { proceeds++ return true, nil } @@ -1853,13 +1853,13 @@ func TestMcpAddInTerminalRefusesWhenAgentCheckFails(t *testing.T) { // run asks. It restores the seams when the test ends. func failOnPrompt(t *testing.T) { t.Helper() - origProceed, origAgents, origServices, origProfile := promptProceed, promptAgentSelection, promptServiceSelection, selectProfile + origProceed, origAgents, origServices, origProfile := promptMCPProceed, promptAgentSelection, promptServiceSelection, selectProfile origSignIn := promptSignInNow t.Cleanup(func() { - promptProceed, promptAgentSelection, promptServiceSelection, selectProfile = origProceed, origAgents, origServices, origProfile + promptMCPProceed, promptAgentSelection, promptServiceSelection, selectProfile = origProceed, origAgents, origServices, origProfile promptSignInNow = origSignIn }) - promptProceed = func() (bool, error) { t.Error("the run asked to confirm the plan"); return false, nil } + promptMCPProceed = func() (bool, error) { t.Error("the run asked to confirm the plan"); return false, nil } promptAgentSelection = func(context.Context, string, []agentChoice) ([]*agents.Agent, error) { t.Error("the run asked for agents") return nil, nil @@ -1964,13 +1964,13 @@ func TestMcpAddDeclinedPlanWritesNothing(t *testing.T) { server := listingServer(t, "system.ai.dbsql") writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") failOnPrompt(t) - origAgents, origProceed := promptAgentSelection, promptProceed - t.Cleanup(func() { promptAgentSelection, promptProceed = origAgents, origProceed }) + origAgents, origProceed := promptAgentSelection, promptMCPProceed + t.Cleanup(func() { promptAgentSelection, promptMCPProceed = origAgents, origProceed }) promptAgentSelection = func(_ context.Context, _ string, choices []agentChoice) ([]*agents.Agent, error) { return []*agents.Agent{agents.ByName(agents.NameClaudeCode)}, nil } var confirmed bool - promptProceed = func() (bool, error) { + promptMCPProceed = func() (bool, error) { confirmed = true return false, nil } diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go index 0d01033d693..93af3add5cc 100644 --- a/cmd/aitools/mcp_pickers.go +++ b/cmd/aitools/mcp_pickers.go @@ -22,14 +22,15 @@ import ( ) // Package-level seams for the interactive pickers of `mcp add` and `mcp remove`. Tests override -// them. The agent picker and the plan confirm are shared with `install` (promptAgentSelection and -// promptProceed in install.go). +// them. The agent picker is shared with `install` (promptAgentSelection in install.go); the plan confirm is the mcp +// commands' own (promptMCPProceed). var ( selectProfile = profile.SelectProfile promptServiceSelection = defaultPromptServiceSelection promptLocation = defaultPromptLocation promptRemoveSelection = defaultPromptRemoveSelection promptSignInNow = defaultPromptSignInNow + promptMCPProceed = defaultPromptMCPProceed ) // anotherSchemaValue is the value of the "Another schema..." row. It has no dots, so it cannot be @@ -503,3 +504,22 @@ func defaultPromptSignInNow(service string) (bool, error) { } return yes, nil } + +// newProceedPicker returns the picker of the plan confirm, which defaults to yes and writes the answer to proceed. +func newProceedPicker(proceed *bool) *pickerModel { + confirm := huh.NewConfirm(). + Title("Proceed?"). + Description("enter to confirm, esc to cancel"). + Value(proceed) + return newPicker(huh.NewForm(huh.NewGroup(confirm)).WithShowHelp(false)) +} + +// defaultPromptMCPProceed asks whether to carry out the plan of mcp add or mcp remove. The default is yes. Esc cancels +// as Ctrl+C does. +func defaultPromptMCPProceed() (bool, error) { + proceed := true + if err := runPicker(newProceedPicker(&proceed)); err != nil { + return false, err + } + return proceed, nil +} diff --git a/cmd/aitools/mcp_pickers_test.go b/cmd/aitools/mcp_pickers_test.go index 155dd65dea1..fa4b960120d 100644 --- a/cmd/aitools/mcp_pickers_test.go +++ b/cmd/aitools/mcp_pickers_test.go @@ -825,3 +825,28 @@ func TestPromptProfileRowsShowHostAndMarker(t *testing.T) { assert.Equal(t, "▸ dogfood (https://dogfood.test)", render(cfg.ActiveTemplate, profile.Profile{Name: "dogfood", Host: "https://dogfood.test"})) assert.Equal(t, " fake-a (https://fake-a.test)", render(cfg.InactiveTemplate, profile.Profile{Name: "fake-a", Host: "https://fake-a.test"})) } + +// TestProceedPickerEscCancelsLikeCtrlC checks that the plan confirm of mcp add and remove defaults to yes, that Enter +// confirms it, and that Esc cancels it as Ctrl+C does. +func TestProceedPickerEscCancelsLikeCtrlC(t *testing.T) { + proceed := true + m := newProceedPicker(&proceed) + m.Init() + m.Update(tea.WindowSizeMsg{Width: 80, Height: 24}) + assert.Contains(t, m.View(), "Proceed?") + assert.Contains(t, m.View(), "esc to cancel") + + m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + assert.True(t, m.cancelled, "Esc cancels the confirm") + + m = newProceedPicker(&proceed) + m.Init() + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyCtrlC}) + assert.Equal(t, tea.InterruptMsg{}, quitMsg(m, cmd, 10), "Ctrl+C interrupts the confirm") + + m = newProceedPicker(&proceed) + m.Init() + _, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + assert.Equal(t, tea.QuitMsg{}, quitMsg(m, cmd, 10), "Enter confirms the confirm") + assert.True(t, proceed, "the default answer is yes") +} diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index dda61a53ef9..e847e11f746 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -171,7 +171,7 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso if offered { // The picker chose the servers, so the removal is confirmed, as add confirms its plan and uninstall its removal. printRemovePlan(ctx, selected, targets) - proceed, err := promptProceed() + proceed, err := promptMCPProceed() if err != nil { return err } diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index 6ecb45de9b6..be1b68c74cb 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -729,13 +729,13 @@ func TestMcpRemovePickerRemovesTheChosenServers(t *testing.T) { `"dbsql-logfood": `+claudeEntry("system.ai.dbsql", "logfood", "")+`}}`), 0o600)) saveState(t, claudeServerEntry(claudePath, "github-logfood", "system.ai.github"), claudeServerEntry(claudePath, "dbsql-logfood", "system.ai.dbsql")) - origRemove, origProceed := promptRemoveSelection, promptProceed - t.Cleanup(func() { promptRemoveSelection, promptProceed = origRemove, origProceed }) + origRemove, origProceed := promptRemoveSelection, promptMCPProceed + t.Cleanup(func() { promptRemoveSelection, promptMCPProceed = origRemove, origProceed }) promptRemoveSelection = func(entries []mcp.Entry, _ []*agents.Agent) ([]mcp.Entry, error) { require.Len(t, entries, 2) return entries[1:], nil } - promptProceed = func() (bool, error) { return true, nil } + promptMCPProceed = func() (bool, error) { return true, nil } require.NoError(t, runInteractive(t, "mcp", "remove")) servers := readJSONFile(t, claudePath)["mcpServers"].(map[string]any) @@ -783,14 +783,14 @@ func TestMcpRemovePickerWithTwoAgentsNeedsOnePickPerServer(t *testing.T) { dbsql.Agents[agents.NameCodex] = mcp.AgentRecord{Path: filepath.Join(home, ".codex", "config.toml"), Scope: "user"} saveState(t, claudeServerEntry(claudePath, "github-logfood", "system.ai.github"), dbsql) - origRemove, origProceed := promptRemoveSelection, promptProceed - t.Cleanup(func() { promptRemoveSelection, promptProceed = origRemove, origProceed }) + origRemove, origProceed := promptRemoveSelection, promptMCPProceed + t.Cleanup(func() { promptRemoveSelection, promptMCPProceed = origRemove, origProceed }) promptRemoveSelection = func(entries []mcp.Entry, targets []*agents.Agent) ([]mcp.Entry, error) { require.Len(t, targets, 2) require.Len(t, entries, 2) return entries[:1], nil } - promptProceed = func() (bool, error) { return true, nil } + promptMCPProceed = func() (bool, error) { return true, nil } require.NoError(t, runInteractive(t, "mcp", "remove", "--agents", "claude-code,codex")) servers := readJSONFile(t, claudePath)["mcpServers"].(map[string]any) @@ -803,12 +803,12 @@ func TestMcpRemovePickerDeclinedRemovesNothing(t *testing.T) { withHome(t) saveState(t, claudeServerEntry("", "github-logfood", "system.ai.github")) - origRemove, origProceed := promptRemoveSelection, promptProceed - t.Cleanup(func() { promptRemoveSelection, promptProceed = origRemove, origProceed }) + origRemove, origProceed := promptRemoveSelection, promptMCPProceed + t.Cleanup(func() { promptRemoveSelection, promptMCPProceed = origRemove, origProceed }) promptRemoveSelection = func(entries []mcp.Entry, _ []*agents.Agent) ([]mcp.Entry, error) { return entries, nil } - promptProceed = func() (bool, error) { return false, nil } + promptMCPProceed = func() (bool, error) { return false, nil } require.NoError(t, runInteractive(t, "mcp", "remove")) state, err := mcp.LoadState(t.Context()) From 7904bcc3eaf66476bceb9ac138a472fc29f6d623 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Tue, 17 Nov 2026 12:31:15 +0000 Subject: [PATCH 11/16] Name the agent source in the read-only add test that card 04 added This card replaces addRequest.explicit with agentSource. Co-authored-by: Isaac --- cmd/aitools/mcp_add_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index 26c42cda279..eb773b6614d 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -827,7 +827,7 @@ func TestInstallServerNamesAgentsForReadOnlyConfig(t *testing.T) { t.Cleanup(func() { _ = os.Chmod(path, 0o600) }) require.NoError(t, os.Chmod(path, 0o400)) - req := addRequest{profile: "logfood", explicit: true, agents: []*agents.Agent{a}, binary: "databricks"} + req := addRequest{profile: "logfood", agentSource: agentsNamed, agents: []*agents.Agent{a}, binary: "databricks"} plan := addPlan{service: mcp.Service{FullName: "system.ai.github"}, name: "github"} out := installServer(t.Context(), req, plan) From a7e2f0429724a538f1b7011d6f690b95119c1c33 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Tue, 17 Nov 2026 14:46:18 +0000 Subject: [PATCH 12/16] Update the hidden help golden for the card 04 review's --location text The --location help and the Long help name the case with no leaf names, as the review changed them. The golden for the help comes from the review, so it is regenerated here. Co-authored-by: Isaac --- acceptance/cmd/aitools/mcp/hidden/output.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/acceptance/cmd/aitools/mcp/hidden/output.txt b/acceptance/cmd/aitools/mcp/hidden/output.txt index b3bf21deb53..4edc2611950 100644 --- a/acceptance/cmd/aitools/mcp/hidden/output.txt +++ b/acceptance/cmd/aitools/mcp/hidden/output.txt @@ -38,7 +38,7 @@ Install Databricks managed MCP servers into coding agents, bound to a Databricks Each server runs through 'databricks aitools mcp serve' with that profile's credentials. Services come from --names: full names such as system.ai.github, or leaf names such as github. Leaf names -resolve in --location, which defaults to system.ai, or to the one schema that the full names in --names share. +resolve in --location, which defaults to system.ai, or to the one schema that the full names in --names share when there are no leaf names. Agents come from --agents. In a terminal, the command asks for whatever is not given: the profile, the servers and the agents (detected @@ -59,7 +59,7 @@ Flags: --agents string Agents to install for, comma-separated (default: a picker in a terminal; otherwise every detected MCP-capable agent) --force[=true|false] Overwrite an existing server with the same name that this CLI did not write -h, --help[=true|false] help for add - --location string Schema to resolve leaf names in, as . (default: system.ai, or the one schema that the full names in --names share) + --location string Schema to resolve leaf names in, as . (default: system.ai, or the one schema that the full names in --names share when there are no leaf names) --login[=true|false] Sign in to each sign-in-required server that was installed, after the installs --name string Server name to use instead of the generated one; only with exactly one service --names string Services to install: full names (system.ai.github) or leaf names (github), comma-separated From 828e6f7a3020345b24c3b81bc949a14b404565b2 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Tue, 17 Nov 2026 14:59:09 +0000 Subject: [PATCH 13/16] Name --agents for a read-only config only for agents named with --agents This card replaces addRequest.explicit with agentSource. Picked and detected agents keep the writer's own read-only message. Co-authored-by: Isaac --- cmd/aitools/mcp_add.go | 2 +- cmd/aitools/mcp_add_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index ac16f626094..2c08baf6421 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -1149,7 +1149,7 @@ func installServer(ctx context.Context, req addRequest, plan addPlan) addServerO args := serveArgs(req.profile, plan.service.FullName, a.Name) path, status, err = agentconfig.Upsert(ctx, a, plan.name, req.binary, args, req.env, req.force) // A detected agent was not named, so --agents is no way out for it. - if req.explicit { + if req.agentSource == agentsNamed { err = withAgentsHint(err, a.Name) } } diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index eb773b6614d..d78f28e88ac 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -852,7 +852,7 @@ func TestInstallServerDoesNotNameDetectedAgentForReadOnlyConfig(t *testing.T) { t.Cleanup(func() { _ = os.Chmod(path, 0o600) }) require.NoError(t, os.Chmod(path, 0o400)) - req := addRequest{profile: "logfood", explicit: false, agents: []*agents.Agent{a}, binary: "databricks"} + req := addRequest{profile: "logfood", agentSource: agentsDetected, agents: []*agents.Agent{a}, binary: "databricks"} plan := addPlan{service: mcp.Service{FullName: "system.ai.github"}, name: "github"} out := installServer(t.Context(), req, plan) From f9f290370c960bc9fc0fb5a428c2179c78611239 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Tue, 17 Nov 2026 17:24:58 +0000 Subject: [PATCH 14/16] Apply the agent prompt policy to the MCP pickers and fix the plan's comparison mcp add and remove now skip their prompts for a coding agent, as install does, and draw the pickers on stderr, so a redirected stdout no longer hides a prompt. The plan compares a Databricks entry with agentconfig.Changed instead of a copy of its comparison, and a bad entry fails only its own agent. The remove refusal says "selected" again, since it is also true when the agent has other servers, and the regexps compile on first use. Co-authored-by: Isaac --- .../mcp/repair-and-warnings/output.txt | 2 +- cmd/aitools/mcp_add.go | 16 +++++++------- cmd/aitools/mcp_pickers.go | 16 ++++++++------ cmd/aitools/mcp_remove.go | 4 ++-- cmd/aitools/mcp_remove_test.go | 6 ++--- libs/aitools/mcp/agentconfig/writer.go | 22 ------------------- 6 files changed, 23 insertions(+), 43 deletions(-) diff --git a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt index e1e7992e138..e49fd48e191 100644 --- a/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt +++ b/acceptance/cmd/aitools/mcp/repair-and-warnings/output.txt @@ -55,4 +55,4 @@ Error: no installed MCP server named orphan; Claude Code has an entry named orph No Databricks MCP servers to remove. >>> musterr [CLI] aitools mcp remove --names genie_one_mcp-logfood --agents cursor -Error: no MCP server is installed for Cursor +Error: no selected MCP server is installed for Cursor diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index 2c08baf6421..03b6348b3bb 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -233,7 +233,7 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode if err := validateMCPAddFlags(ctx, f, names, agentNames, jsonMode); err != nil { return err } - interactive := !jsonMode && cmdio.IsPromptSupported(ctx) + interactive := !jsonMode && installPromptsSupported(ctx) location, fullNames, err := resolveServices(f.location, names) if err != nil { return err @@ -268,9 +268,7 @@ func runMcpAdd(ctx context.Context, cmd *cobra.Command, f mcpAddFlags, jsonMode if len(named) > 0 { refused = refusedAgents(ctx, named) } - for a, err := range detectErrs { - refused[a] = err - } + maps.Copy(refused, detectErrs) checked := targets if len(named) > 0 { checked = named @@ -509,7 +507,7 @@ func validateMCPAddFlags(ctx context.Context, f mcpAddFlags, names, agentNames [ } return nil } - if len(names) == 0 && !cmdio.IsPromptSupported(ctx) { + if len(names) == 0 && !installPromptsSupported(ctx) { return failure(protos.AitoolsErrorCategoryInvalidFlags, "--names is required so the command runs without interactive prompts") } // The picker chooses services in a terminal, and --name needs exactly one of them, which only --names can give. @@ -916,11 +914,13 @@ func planAdds(ctx context.Context, in planInput, state *mcp.State, fullNames []s plan.replaced[a] = true continue } - same, err := agentconfig.Unchanged(a, in.binary, serveArgs(in.binding.profile, fullName, a.Name), in.env, entry) + changed, err := agentconfig.Changed(a, entry, in.binary, serveArgs(in.binding.profile, fullName, a.Name), in.env) if err != nil { - return nil, err + // A bad entry fails only its own agent, as Upsert reports it, and the other agents are still written. + failed[a] = fmt.Errorf("server %q: %w", name, err) + continue } - if same { + if !changed { plan.reasserted[a] = true } else { plan.updated[a] = true diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go index 93af3add5cc..d66932bbddd 100644 --- a/cmd/aitools/mcp_pickers.go +++ b/cmd/aitools/mcp_pickers.go @@ -9,6 +9,7 @@ import ( "regexp" "slices" "strings" + "sync" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/huh" @@ -210,10 +211,11 @@ func typedLocation(s string) string { // serviceRowChrome is the width the picker takes around a row's label: the border, the cursor and the checkbox. const serviceRowChrome = 8 +// markdownLink matches a [text](url) link, and bareURL a URL that is not in a link. They are compiled on first use, not +// in a package-level var, so that every databricks invocation does not pay for them. var ( - // markdownLink matches a [text](url) link, and bareURL a URL that is not in a link. - markdownLink = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`) - bareURL = regexp.MustCompile(`https?://\S+`) + markdownLink = sync.OnceValue(func() *regexp.Regexp { return regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`) }) + bareURL = sync.OnceValue(func() *regexp.Regexp { return regexp.MustCompile(`https?://\S+`) }) ) // serviceDescription is the description of a service row: the CLI's Summary for a known system.ai service, else its @@ -227,8 +229,8 @@ func serviceDescription(s mcp.Service) string { return k.Label } } - text := markdownLink.ReplaceAllString(s.Comment, "$1") - text = bareURL.ReplaceAllString(text, "") + text := markdownLink().ReplaceAllString(s.Comment, "$1") + text = bareURL().ReplaceAllString(text, "") text = strings.Join(strings.Fields(text), " ") if i := strings.Index(text, ". "); i >= 0 { text = text[:i+1] @@ -357,7 +359,7 @@ func (m *pickerModel) View() string { return m.form.View() } // runPicker runs the picker and returns huh.ErrUserAborted when the user cancels it, with Esc or Ctrl+C. func runPicker(m *pickerModel) error { - _, err := tea.NewProgram(m).Run() + _, err := tea.NewProgram(m, tea.WithOutput(os.Stderr)).Run() if m.cancelled || errors.Is(err, tea.ErrInterrupted) { return huh.ErrUserAborted } @@ -392,7 +394,7 @@ func serviceSelectField(location string, rows []serviceRow, width int, selected // terminalWidth is the width of the terminal the pickers draw in, or 0 when stdout is not a terminal, which leaves // the rows whole. func terminalWidth() int { - width, _, err := term.GetSize(int(os.Stdout.Fd())) + width, _, err := term.GetSize(int(os.Stderr.Fd())) if err != nil { return 0 } diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index e847e11f746..830d84cabd2 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -134,7 +134,7 @@ func runMcpRemove(ctx context.Context, cmd *cobra.Command, f mcpRemoveFlags, jso names := splitAndTrim(f.names) agentNames := splitAndTrim(f.agents) profileName := profileFlag(cmd) - interactive := !jsonMode && cmdio.IsPromptSupported(ctx) + interactive := !jsonMode && installPromptsSupported(ctx) if err := validateMCPRemoveFlags(f.all, names, profileName, interactive); err != nil { return err } @@ -404,7 +404,7 @@ func checkTargetsInstalled(selected []mcp.Entry, targets []*agents.Agent) error _, ok := e.Agents[a.Name] return ok }) { - return failure(categoryServiceNotFound, "no MCP server is installed for %s", agentDisplayName(a.Name)) + return failure(categoryServiceNotFound, "no selected MCP server is installed for %s", agentDisplayName(a.Name)) } } return nil diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index be1b68c74cb..720ad1a7710 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -465,7 +465,7 @@ func TestMcpRemoveRefusesAgentWithNothingInstalled(t *testing.T) { 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 MCP server is installed for Cursor", out.Error) + assert.Equal(t, "no selected MCP server is installed for Cursor", out.Error) assert.Equal(t, categoryServiceNotFound, out.ErrorCategory) // Nothing was removed by the refusal. @@ -687,7 +687,7 @@ func TestMcpRemoveWithAgentsSkipsRecordWithoutAgents(t *testing.T) { // Named explicitly, the same entry is a refusal: no server is installed for the agent. _, _, err = runMcpCmd(t, "remove", "--names", "dangling", "--agents", "claude-code") - require.ErrorContains(t, err, "no MCP server is installed for 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 @@ -763,7 +763,7 @@ func TestMcpRemovePickerRefusesAgentWithNoServer(t *testing.T) { err := runInteractive(t, "mcp", "remove", "--agents", "codex") require.Error(t, err) - assert.Equal(t, "no MCP server is installed for "+agents.ByName(agents.NameCodex).DisplayName, err.Error()) + assert.Equal(t, "no selected MCP server is installed for "+agents.ByName(agents.NameCodex).DisplayName, err.Error()) assert.Equal(t, categoryServiceNotFound, errorCategory(err)) state, err := mcp.LoadState(t.Context()) require.NoError(t, err) diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index a9ef9f9a2c4..7a101c935ec 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -581,28 +581,6 @@ func withoutServer(doc map[string]any, root []string, name string) map[string]an return out } -// Unchanged reports whether Upsert would leave the entry current as it is: current is a Databricks entry whose launch -// keys already match the entry Upsert writes for cmd, args and env. Upsert uses the same comparison. -func Unchanged(a *agents.Agent, cmd string, args []string, env map[string]string, current map[string]any) (bool, error) { - spec, err := specOf(a) - if err != nil { - return false, err - } - ours, err := normalize(spec.Entry(cmd, args, env)) - if err != nil { - return false, err - } - if !mcpconfig.IsDatabricksEntry(current) { - return false, nil - } - keys := ownedKeys(spec) - merged, err := keepUserKeys(current, ours, keys) - if err != nil { - return false, err - } - return sameEntry(launchOf(current, keys), launchOf(merged, keys)) -} - // sameEntry compares two entries as JSON values, so the in-memory Go types of a // freshly built entry and one decoded from a file compare equal. func sameEntry(a, b map[string]any) (bool, error) { From c083f4831fa9dbf8d5ac4c59497891e160c2341b Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Tue, 17 Nov 2026 17:37:47 +0000 Subject: [PATCH 15/16] Keep bad entries reported by the write and isolate the MCP picker tests from the host agent mcp add's plan shows a Databricks entry that cannot be compared as an update and leaves the error to the write, which names the file, so the run no longer stops before its requests. The picker tests start from an empty environment, so a test run inside a coding agent sees no terminal prompts. The terminal width comment names stderr. Co-authored-by: Isaac --- cmd/aitools/mcp_add.go | 4 ++-- cmd/aitools/mcp_add_test.go | 9 +++++++++ cmd/aitools/mcp_pickers.go | 2 +- cmd/aitools/mcp_remove_test.go | 5 +++++ 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index 03b6348b3bb..553d7f90289 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -916,8 +916,8 @@ func planAdds(ctx context.Context, in planInput, state *mcp.State, fullNames []s } changed, err := agentconfig.Changed(a, entry, in.binary, serveArgs(in.binding.profile, fullName, a.Name), in.env) if err != nil { - // A bad entry fails only its own agent, as Upsert reports it, and the other agents are still written. - failed[a] = fmt.Errorf("server %q: %w", name, err) + // The write reports a bad entry with its file, so the plan only has to show that it changes. + plan.updated[a] = true continue } if !changed { diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index d78f28e88ac..22c8ebfba98 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -1672,6 +1672,7 @@ func runInteractive(t *testing.T, args ...string) error { // TestMcpAddNameOnThePickerPathIsRefusedBeforeConnecting checks that --name without --names is refused before the // profile is read, so no request reaches the workspace. func TestMcpAddNameOnThePickerPathIsRefusedBeforeConnecting(t *testing.T) { + isolateAgents(t) home := withHome(t) server := noRequestServer(t) writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nauth_type = pat\ntoken = dapi-logfood\n") @@ -1686,6 +1687,7 @@ func TestMcpAddNameOnThePickerPathIsRefusedBeforeConnecting(t *testing.T) { // TestMcpAddPickerRefusesRepointedHostOfPickedServiceBeforeWriting checks that a run that picks its services lists the // workspace, then refuses a picked service whose recorded entry names another host, before anything is written. func TestMcpAddPickerRefusesRepointedHostOfPickedServiceBeforeWriting(t *testing.T) { + isolateAgents(t) home := withHome(t) server := listingServer(t, "system.ai.github") writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") @@ -1732,6 +1734,7 @@ func schemaListingServer(t *testing.T, schemas map[string][]string) *httptest.Se // TestMcpAddPickerInstallsAcrossSchemas checks that a terminal run with a profile and no --names installs the services it // picks in two schemas, reached through "Another schema...": both entries reach the agent file and the state. func TestMcpAddPickerInstallsAcrossSchemas(t *testing.T) { + isolateAgents(t) home := withHome(t) server := schemaListingServer(t, map[string][]string{ "system.ai": {"system.ai.github"}, @@ -1775,6 +1778,7 @@ func TestMcpAddPickerInstallsAcrossSchemas(t *testing.T) { // TestMcpAddPickerRefusesMissingProfileBeforeAnyRequest checks that a run that picks its services reports a profile the // config file does not have, or has with no host, as PROFILE_NOT_FOUND, before any request. func TestMcpAddPickerRefusesMissingProfileBeforeAnyRequest(t *testing.T) { + isolateAgents(t) home := withHome(t) server := noRequestServer(t) writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nauth_type = pat\ntoken = dapi-logfood\n") @@ -1796,6 +1800,7 @@ func TestMcpAddPickerRefusesMissingProfileBeforeAnyRequest(t *testing.T) { // TestMcpAddPickerWithNoAgentMakesNoRequest checks that a run that picks its services ends when no agent is detected, // before the workspace is contacted. func TestMcpAddPickerWithNoAgentMakesNoRequest(t *testing.T) { + isolateAgents(t) home := withHome(t) require.NoError(t, os.RemoveAll(filepath.Join(home, ".claude"))) server := noRequestServer(t) @@ -1940,6 +1945,7 @@ func TestMcpAddFullySpecifiedRunAsksNothing(t *testing.T) { // TestMcpAddFullySpecifiedRunAsksOnlyTheSignInQuestion checks that a terminal run with the profile, the services and the // agents given asks the sign-in question of a sign-in-required server, and nothing else. func TestMcpAddFullySpecifiedRunAsksOnlyTheSignInQuestion(t *testing.T) { + isolateAgents(t) home := withHome(t) server := signInListingServer(t, "system.ai.github") writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") @@ -1960,6 +1966,7 @@ func TestMcpAddFullySpecifiedRunAsksOnlyTheSignInQuestion(t *testing.T) { // TestMcpAddDeclinedPlanWritesNothing checks that declining the confirm of a picked agent leaves the agent's // config unwritten. func TestMcpAddDeclinedPlanWritesNothing(t *testing.T) { + isolateAgents(t) home := withHome(t) server := listingServer(t, "system.ai.dbsql") writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") @@ -2162,6 +2169,7 @@ func TestPlanAddsReplacesAForeignEntryAndReassertsOwnEntry(t *testing.T) { // TestValidateMCPAddFlagsNameNeedsServicesFromNames checks that --name without --names is refused before the // workspace is read, in a terminal too, where the picker would otherwise choose the services. func TestValidateMCPAddFlagsNameNeedsServicesFromNames(t *testing.T) { + isolateAgents(t) ctx, test := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) defer test.Done() err := validateMCPAddFlags(ctx, mcpAddFlags{name: "github"}, nil, nil, false) @@ -2273,6 +2281,7 @@ func TestAddPlanLines(t *testing.T) { } func TestValidateMCPAddFlagsInTerminalAsksForMissingChoices(t *testing.T) { + isolateAgents(t) ctx, test := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) defer test.Done() require.NoError(t, validateMCPAddFlags(ctx, mcpAddFlags{}, nil, nil, false)) diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go index d66932bbddd..04517c3d48e 100644 --- a/cmd/aitools/mcp_pickers.go +++ b/cmd/aitools/mcp_pickers.go @@ -391,7 +391,7 @@ func serviceSelectField(location string, rows []serviceRow, width int, selected Value(selected) } -// terminalWidth is the width of the terminal the pickers draw in, or 0 when stdout is not a terminal, which leaves +// terminalWidth is the width of the terminal the pickers draw in, or 0 when stderr is not a terminal, which leaves // the rows whole. func terminalWidth() int { width, _, err := term.GetSize(int(os.Stderr.Fd())) diff --git a/cmd/aitools/mcp_remove_test.go b/cmd/aitools/mcp_remove_test.go index 720ad1a7710..3d38716e501 100644 --- a/cmd/aitools/mcp_remove_test.go +++ b/cmd/aitools/mcp_remove_test.go @@ -722,6 +722,7 @@ func jsonServers(t *testing.T, path string) map[string]any { // TestMcpRemovePickerRemovesTheChosenServers checks that the remove picker, shown in a terminal with no choice given, // removes the servers that are checked and keeps the others. func TestMcpRemovePickerRemovesTheChosenServers(t *testing.T) { + isolateAgents(t) home := withHome(t) claudePath := filepath.Join(home, ".claude.json") require.NoError(t, os.WriteFile(claudePath, []byte(`{"mcpServers": {`+ @@ -751,6 +752,7 @@ func TestMcpRemovePickerRemovesTheChosenServers(t *testing.T) { // TestMcpRemovePickerRefusesAgentWithNoServer checks that --agents naming an agent with no installed server is refused // before the picker runs, as a run without a terminal refuses it. func TestMcpRemovePickerRefusesAgentWithNoServer(t *testing.T) { + isolateAgents(t) withHome(t) saveState(t, claudeServerEntry("", "github-logfood", "system.ai.github")) @@ -774,6 +776,7 @@ func TestMcpRemovePickerRefusesAgentWithNoServer(t *testing.T) { // only one of them: the pick is removed from that agent, and the server installed for the other agent, which is not // picked, stays. func TestMcpRemovePickerWithTwoAgentsNeedsOnePickPerServer(t *testing.T) { + isolateAgents(t) home := withHome(t) claudePath := filepath.Join(home, ".claude.json") require.NoError(t, os.WriteFile(claudePath, []byte(`{"mcpServers": {`+ @@ -800,6 +803,7 @@ func TestMcpRemovePickerWithTwoAgentsNeedsOnePickPerServer(t *testing.T) { // TestMcpRemovePickerDeclinedRemovesNothing checks that a picked removal the user declines at Proceed? removes nothing. func TestMcpRemovePickerDeclinedRemovesNothing(t *testing.T) { + isolateAgents(t) withHome(t) saveState(t, claudeServerEntry("", "github-logfood", "system.ai.github")) @@ -818,6 +822,7 @@ func TestMcpRemovePickerDeclinedRemovesNothing(t *testing.T) { // TestMcpRemovePickerEmptyPickRemovesNothing checks that a picker closed with nothing checked removes nothing. func TestMcpRemovePickerEmptyPickRemovesNothing(t *testing.T) { + isolateAgents(t) withHome(t) saveState(t, claudeServerEntry("", "github-logfood", "system.ai.github")) From b77efcea59ed9be65a4e2a0ea38f93d73faa8419 Mon Sep 17 00:00:00 2001 From: Simon Faltum Date: Tue, 17 Nov 2026 17:44:01 +0000 Subject: [PATCH 16/16] Fit each remove picker row on one line and isolate the fully specified add test The remove picker's labels wrapped at 80x24, which hid the cursor when scrolling. Each label now fits the terminal width, as the service picker's rows do. The fully specified add test also starts from an empty agent environment, as the other terminal tests do. Co-authored-by: Isaac --- cmd/aitools/mcp_add_test.go | 1 + cmd/aitools/mcp_pickers.go | 12 +++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/cmd/aitools/mcp_add_test.go b/cmd/aitools/mcp_add_test.go index 22c8ebfba98..f34851490c0 100644 --- a/cmd/aitools/mcp_add_test.go +++ b/cmd/aitools/mcp_add_test.go @@ -1931,6 +1931,7 @@ func listingServerJSON(t *testing.T, services ...string) *httptest.Server { // TestMcpAddFullySpecifiedRunAsksNothing checks that a terminal run with the profile, the services and the agents // given asks for nothing and installs. func TestMcpAddFullySpecifiedRunAsksNothing(t *testing.T) { + isolateAgents(t) home := withHome(t) server := listingServer(t, "system.ai.dbsql") writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nworkspace_id = 222\nauth_type = pat\ntoken = dapi-logfood\n") diff --git a/cmd/aitools/mcp_pickers.go b/cmd/aitools/mcp_pickers.go index 04517c3d48e..86619b37356 100644 --- a/cmd/aitools/mcp_pickers.go +++ b/cmd/aitools/mcp_pickers.go @@ -470,11 +470,21 @@ func removeChoiceLabel(e mcp.Entry, targets []*agents.Agent) string { return fmt.Sprintf("%s %s %s %s", e.Name, e.Service, e.Profile, mcpAgentList(names)) } +// fitRow cuts a row label to the terminal width, so that each row stays on one line and the cursor stays in view. A +// width of 0 leaves the label whole. +func fitRow(label string, width int) string { + if width <= 0 { + return label + } + return ansi.Truncate(label, width-serviceRowChrome, "…") +} + // defaultPromptRemoveSelection is the huh multi-select over the installed servers. func defaultPromptRemoveSelection(entries []mcp.Entry, targets []*agents.Agent) ([]mcp.Entry, error) { + width := terminalWidth() options := make([]huh.Option[int], 0, len(entries)) for i, e := range entries { - options = append(options, huh.NewOption(removeChoiceLabel(e, targets), i)) + options = append(options, huh.NewOption(fitRow(removeChoiceLabel(e, targets), width), i)) } var selected []int