From d224f3a923587ea86f6ca99c372eaece1266665f Mon Sep 17 00:00:00 2001 From: sdairs Date: Wed, 4 Nov 2026 09:41:13 +0000 Subject: [PATCH 1/4] feat(cli): add cloud mcp add to register the Cloud MCP server in coding agents (#1212) Registers https://mcp.clickhouse.cloud/mcp for the user through the agent's own CLI (claude, codex, gemini, opencode, pi), then starts that agent's OAuth sign-in. Needs no clickhousectl credentials; Cloud-wide flags are rejected. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- crates/clickhousectl/src/cloud/cli.rs | 25 ++ crates/clickhousectl/src/cloud/mcp.rs | 407 ++++++++++++++++++ crates/clickhousectl/src/cloud/mod.rs | 6 + crates/clickhousectl/src/cloud/permissions.rs | 1 + crates/clickhousectl/src/main.rs | 58 +++ .../clickhousectl/tests/cloud_mcp_add_test.rs | 157 +++++++ docs/README.md | 1 + docs/guides/cloud-mcp.md | 37 ++ scripts/classify-cloud-integration.py | 2 + scripts/classify-install-integration.py | 1 + .../test_classify_install_integration.py | 1 + 12 files changed, 703 insertions(+), 1 deletion(-) create mode 100644 crates/clickhousectl/src/cloud/mcp.rs create mode 100644 crates/clickhousectl/tests/cloud_mcp_add_test.rs create mode 100644 docs/guides/cloud-mcp.md diff --git a/README.md b/README.md index b01aebe25..de58d9c87 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ - **[ClickPipes](https://clickhouse.com/cloud/clickpipes)** ingests data into ClickHouse Cloud from object storage, streams, and databases through change data capture. Create, inspect, update, scale, and troubleshoot pipelines. - **[ClickStack](https://clickhouse.com/clickstack)** combines ClickHouse, OpenTelemetry, and the HyperDX UI for observability. Manage sources, roles, saved searches, dashboards, alerts, and webhooks for an existing [Managed ClickStack](https://clickhouse.com/cloud/clickstack) service. -The CLI also manages organization access and installs official ClickHouse skills for coding agents. +The CLI also manages organization access, installs official ClickHouse skills for coding agents, and connects them to the hosted Cloud MCP server. ## Install @@ -229,6 +229,12 @@ clickhousectl skills --agent claude --agent codex The common `.agents/skills/` directory is always included. Run `skills` without flags for interactive selection; unattended installs require `--agent`, `--all`, or `--detected-only`. +Register the read-only [Cloud MCP server](docs/guides/cloud-mcp.md) in an agent and sign in. Sign-in opens a browser: + +```bash +clickhousectl cloud mcp add claude +``` + Structured commands support `--json` and select it automatically for detected coding agents. SQL and native clients retain command-specific formats. Always check the exit status and distinguish an accepted request from a completed operation. See [automation and output contracts](docs/reference/automation.md). ## Documentation diff --git a/crates/clickhousectl/src/cloud/cli.rs b/crates/clickhousectl/src/cloud/cli.rs index 1f3c27048..41e354469 100644 --- a/crates/clickhousectl/src/cloud/cli.rs +++ b/crates/clickhousectl/src/cloud/cli.rs @@ -15,6 +15,7 @@ pub(crate) use crate::cloud::clickpipes::{ ObjectStorageCreateArgs, PostgresCreateArgs, }; pub(crate) use crate::cloud::clickstack::ClickStackCommands; +pub(crate) use crate::cloud::mcp::McpCommands; pub(crate) use crate::cloud::organizations::{InvitationCommands, MemberCommands, OrgCommands}; pub(crate) use crate::cloud::query_api_endpoints::QueryApiEndpointArgs; pub(crate) use crate::cloud::saved_queries::SavedQueryArgs; @@ -81,6 +82,23 @@ impl CloudArgs { ) } + /// A Cloud-wide flag passed to `mcp add`, which never uses clickhousectl + /// credentials or an organization: the agent signs in by itself. + pub fn mcp_flag_conflict(&self) -> Option<&'static str> { + if !matches!(self.command, CloudCommands::Mcp { .. }) { + return None; + } + [ + (self.org_id.is_some(), "--org-id"), + (self.org_name.is_some(), "--org-name"), + (self.api_key.is_some(), "--api-key"), + (self.api_secret.is_some(), "--api-secret"), + (self.url.is_some(), "--url"), + ] + .into_iter() + .find_map(|(set, flag)| set.then_some(flag)) + } + /// The schema-discovery source's usage error, checked before credentials. pub fn clickpipe_schema_discover_validation_error(&self) -> Option<(&'static str, String)> { let CloudCommands::ClickPipe { command } = &self.command else { @@ -273,6 +291,12 @@ CONTEXT FOR AGENTS: #[command(subcommand)] command: crate::cloud::postgres::PostgresCommands, }, + + /// Connect coding agents to the Cloud MCP server + Mcp { + #[command(subcommand)] + command: McpCommands, + }, } impl CloudCommands { @@ -298,6 +322,7 @@ impl CloudCommands { CloudCommands::Postgres { command } => command.is_write(), CloudCommands::ClickPipe { command } => command.is_write(), CloudCommands::ClickStack { command } => command.is_write(), + CloudCommands::Mcp { command } => command.is_write(), } } } diff --git a/crates/clickhousectl/src/cloud/mcp.rs b/crates/clickhousectl/src/cloud/mcp.rs new file mode 100644 index 000000000..7dda90ff2 --- /dev/null +++ b/crates/clickhousectl/src/cloud/mcp.rs @@ -0,0 +1,407 @@ +//! Register the hosted ClickHouse Cloud MCP server in a coding agent. +//! +//! Each agent's own CLI does the registration and the OAuth sign-in, so the +//! agent keeps its token and clickhousectl never handles it. + +use super::output::eprint_line; +use super::permissions::Declaration as Permission; +use crate::error::{Error, Result}; +use clap::{Args, Subcommand, ValueEnum}; +use serde::Serialize; +use std::process::{Command, Stdio}; + +pub(super) const PERMISSIONS: &[Permission] = &[Permission::non_api( + "mcp add", + "Runs the agent's own CLI; no Cloud API call.", +)]; + +/// ClickHouse Cloud's hosted MCP server. +pub const CLOUD_MCP_URL: &str = "https://mcp.clickhouse.cloud/mcp"; + +#[derive(Subcommand, Debug)] +pub enum McpCommands { + /// Register the Cloud MCP server in a coding agent and sign in + #[command(after_help = "\ +CONTEXT FOR AGENTS: + Registers the read-only Cloud MCP server for the user, in all projects, using the agent's own CLI. + Then starts that agent's OAuth sign-in, which opens a browser and blocks until a human finishes it; + with an existing Cloud browser session it can finish in seconds. + gemini has no sign-in command: run `/mcp auth ` inside Gemini CLI afterwards. + Needs the agent's CLI on PATH, not clickhousectl credentials. Safe to rerun to sign in again. + The server's tools appear in new agent sessions, not the one that ran this.")] + Add(AddArgs), +} + +impl McpCommands { + pub fn is_write(&self) -> bool { + match self { + McpCommands::Add(_) => false, + } + } +} + +#[derive(Args, Debug)] +pub struct AddArgs { + /// Coding agent to register the server in + #[arg(value_enum)] + pub agent: Agent, + + /// Server name in the agent's config + #[arg(long, default_value = "clickhouse-cloud")] + pub name: String, +} + +#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum Agent { + /// Claude Code + Claude, + /// OpenAI Codex CLI + Codex, + /// Gemini CLI + Gemini, + /// OpenCode + Opencode, + /// Pi coding agent + Pi, +} + +impl Agent { + fn display_name(self) -> &'static str { + match self { + Agent::Claude => "Claude Code", + Agent::Codex => "Codex", + Agent::Gemini => "Gemini CLI", + Agent::Opencode => "OpenCode", + Agent::Pi => "Pi", + } + } + + fn program(self) -> &'static str { + match self { + Agent::Claude => "claude", + Agent::Codex => "codex", + Agent::Gemini => "gemini", + Agent::Opencode => "opencode", + Agent::Pi => "pi", + } + } +} + +/// How an agent signs in to the server once it is registered. +#[derive(Debug, PartialEq, Eq)] +enum SignIn { + /// A separate command, run after `add`. + Command(Vec), + /// `add` signs in by itself when the server supports OAuth. + DuringAdd, + /// Only from inside an agent session, with this slash command. + InSession(String), +} + +/// The agent CLI calls that register `name` for the user and sign in. +#[derive(Debug, PartialEq, Eq)] +struct Plan { + /// Exits 0 when `name` is already registered. Only for agents whose `add` + /// refuses an existing name; the others replace the entry. + exists: Option>, + add: Vec, + sign_in: SignIn, +} + +fn argv(parts: &[&str]) -> Vec { + parts.iter().map(|part| (*part).to_owned()).collect() +} + +fn plan(agent: Agent, name: &str) -> Plan { + let url = CLOUD_MCP_URL; + match agent { + Agent::Claude => Plan { + exists: Some(argv(&["mcp", "get", name])), + add: argv(&[ + "mcp", + "add", + "--transport", + "http", + "--scope", + "user", + name, + url, + ]), + sign_in: SignIn::Command(argv(&["mcp", "login", name])), + }, + Agent::Codex => Plan { + exists: None, + add: argv(&["mcp", "add", name, "--url", url]), + sign_in: SignIn::DuringAdd, + }, + Agent::Gemini => Plan { + exists: None, + add: argv(&[ + "mcp", + "add", + "--scope", + "user", + "--transport", + "http", + name, + url, + ]), + sign_in: SignIn::InSession(format!("/mcp auth {name}")), + }, + Agent::Opencode => Plan { + exists: None, + add: argv(&["mcp", "add", name, "--url", url, "--global"]), + sign_in: SignIn::Command(argv(&["mcp", "auth", name])), + }, + Agent::Pi => Plan { + exists: None, + add: argv(&["mcp", "add", name, "--url", url]), + sign_in: SignIn::Command(argv(&["mcp", "login", name])), + }, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +enum Registration { + Added, + AlreadyRegistered, +} + +#[derive(Debug, Serialize)] +struct AddOutput { + agent: Agent, + name: String, + url: &'static str, + registration: Registration, + signed_in: bool, + /// What the user runs inside the agent to sign in, when the agent's CLI can't. + #[serde(skip_serializing_if = "Option::is_none")] + sign_in_command: Option, +} + +pub fn run(command: McpCommands, debug: bool, json: bool) -> Result<()> { + match command { + McpCommands::Add(args) => add(args, debug, json), + } +} + +fn add(args: AddArgs, debug: bool, json: bool) -> Result<()> { + let agent = args.agent; + let plan = plan(agent, &args.name); + + let already_registered = match &plan.exists { + Some(exists) => spawn(agent, exists, debug, ChildOutput::Discard)?.success(), + None => false, + }; + let registration = if already_registered { + Registration::AlreadyRegistered + } else { + check(spawn(agent, &plan.add, debug, ChildOutput::ToStderr)?)?; + Registration::Added + }; + + let (signed_in, sign_in_command) = match plan.sign_in { + SignIn::Command(login) => { + eprint_line(format!( + "Signing in to {} from {}; finish in the browser.", + args.name, + agent.display_name() + )); + check(spawn(agent, &login, debug, ChildOutput::ToStderr)?)?; + (true, None) + } + SignIn::DuringAdd => (registration == Registration::Added, None), + SignIn::InSession(command) => (false, Some(command)), + }; + + let output = AddOutput { + agent, + name: args.name, + url: CLOUD_MCP_URL, + registration, + signed_in, + sign_in_command, + }; + if json { + println!("{}", serde_json::to_string_pretty(&output)?); + } else { + print_human(&output); + } + Ok(()) +} + +fn print_human(output: &AddOutput) { + let agent = output.agent.display_name(); + match output.registration { + Registration::Added => println!("Registered {} in {agent} for all projects.", output.name), + Registration::AlreadyRegistered => { + println!("{} is already registered in {agent}.", output.name) + } + } + if let Some(command) = &output.sign_in_command { + println!("To sign in, run `{command}` in {agent}."); + } else if output.signed_in { + println!("Signed in. Start a new {agent} session to use it."); + } +} + +#[derive(Clone, Copy)] +enum ChildOutput { + Discard, + /// Keep the agent's messages, sign-in URL included, off stdout so it holds + /// only this command's own output. + ToStderr, +} + +fn spawn( + agent: Agent, + args: &[String], + debug: bool, + output: ChildOutput, +) -> Result { + let program = agent.program(); + if debug { + eprint_line(format!("[debug] running: {program} {}", args.join(" "))); + } + let mut command = Command::new(program); + command.args(args).stdin(Stdio::inherit()); + match output { + ChildOutput::Discard => { + command.stdout(Stdio::null()).stderr(Stdio::null()); + } + ChildOutput::ToStderr => { + command + .stdout(Stdio::from(std::io::stderr())) + .stderr(Stdio::inherit()); + } + } + command.status().map_err(|error| match error.kind() { + std::io::ErrorKind::NotFound => Error::Cloud(format!( + "`{program}` was not found on PATH; install {} first", + agent.display_name() + )), + _ => Error::Cloud(format!("failed to run `{program}`: {error}")), + }) +} + +/// A failed agent CLI has already explained itself on stderr; keep its status. +fn check(status: std::process::ExitStatus) -> Result<()> { + if status.success() { + Ok(()) + } else { + Err(Error::ChildExit(status.code().unwrap_or(1))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cli::{Cli, Commands}; + use clap::Parser; + + fn parse_add(args: &[&str]) -> AddArgs { + let cli = Cli::try_parse_from(["chctl", "cloud", "mcp", "add"].iter().chain(args)).unwrap(); + let Commands::Cloud(cloud) = cli.command else { + panic!("expected cloud command"); + }; + let crate::cloud::cli::CloudCommands::Mcp { + command: McpCommands::Add(add), + } = cloud.command + else { + panic!("expected cloud mcp add"); + }; + add + } + + #[test] + fn add_takes_a_positional_agent_and_defaults_the_name() { + let add = parse_add(&["claude"]); + assert_eq!(add.agent, Agent::Claude); + assert_eq!(add.name, "clickhouse-cloud"); + + let add = parse_add(&["opencode", "--name", "ch"]); + assert_eq!(add.agent, Agent::Opencode); + assert_eq!(add.name, "ch"); + } + + #[test] + fn add_requires_a_known_agent() { + let missing = Cli::try_parse_from(["chctl", "cloud", "mcp", "add"]) + .err() + .unwrap(); + assert_eq!( + missing.kind(), + clap::error::ErrorKind::MissingRequiredArgument + ); + let unknown = Cli::try_parse_from(["chctl", "cloud", "mcp", "add", "cursor"]) + .err() + .unwrap(); + assert_eq!(unknown.kind(), clap::error::ErrorKind::InvalidValue); + } + + #[test] + fn add_is_not_a_write() { + let add = parse_add(&["codex"]); + assert!(!McpCommands::Add(add).is_write()); + } + + #[test] + fn plans_register_for_the_user_with_the_cloud_url() { + for agent in Agent::value_variants() { + let plan = plan(*agent, "ch"); + assert!(plan.add.iter().any(|arg| arg == CLOUD_MCP_URL), "{agent:?}"); + assert!(plan.add.iter().any(|arg| arg == "ch"), "{agent:?}"); + } + assert!( + plan(Agent::Claude, "ch") + .add + .windows(2) + .any(|w| w == ["--scope", "user"]) + ); + assert!( + plan(Agent::Gemini, "ch") + .add + .windows(2) + .any(|w| w == ["--scope", "user"]) + ); + assert!( + plan(Agent::Opencode, "ch") + .add + .contains(&"--global".to_owned()) + ); + } + + #[test] + fn plans_sign_in_the_way_each_agent_supports() { + assert_eq!( + plan(Agent::Claude, "ch").sign_in, + SignIn::Command(argv(&["mcp", "login", "ch"])) + ); + assert_eq!(plan(Agent::Codex, "ch").sign_in, SignIn::DuringAdd); + assert_eq!( + plan(Agent::Gemini, "ch").sign_in, + SignIn::InSession("/mcp auth ch".into()) + ); + assert_eq!( + plan(Agent::Opencode, "ch").sign_in, + SignIn::Command(argv(&["mcp", "auth", "ch"])) + ); + assert_eq!( + plan(Agent::Pi, "ch").sign_in, + SignIn::Command(argv(&["mcp", "login", "ch"])) + ); + } + + #[test] + fn only_claude_checks_for_an_existing_entry() { + assert_eq!( + plan(Agent::Claude, "ch").exists, + Some(argv(&["mcp", "get", "ch"])) + ); + for agent in [Agent::Codex, Agent::Gemini, Agent::Opencode, Agent::Pi] { + assert_eq!(plan(agent, "ch").exists, None, "{agent:?}"); + } + } +} diff --git a/crates/clickhousectl/src/cloud/mod.rs b/crates/clickhousectl/src/cloud/mod.rs index acda62e5e..1e65a4409 100644 --- a/crates/clickhousectl/src/cloud/mod.rs +++ b/crates/clickhousectl/src/cloud/mod.rs @@ -9,6 +9,7 @@ pub mod clickstack; pub mod client; pub(crate) mod config; pub mod credentials; +pub(crate) mod mcp; pub mod organizations; pub mod output; pub(crate) mod permissions; @@ -71,6 +72,8 @@ pub async fn run(args: CloudArgs, json: bool) -> Result<()> { ) .await; } + // Runs the agent's CLI; it needs no Cloud credentials. + CloudCommands::Mcp { command } => return mcp::run(command, args.debug, json), command => command, }; @@ -179,6 +182,9 @@ async fn dispatch(client: &CloudClient, command: CloudCommands, json: bool) -> c CloudCommands::Postgres { command } => postgres::run(client, command, json).await, CloudCommands::ClickPipe { command } => clickpipes::run(client, *command, json).await, CloudCommands::ClickStack { command } => clickstack::run(client, command, json).await, + CloudCommands::Mcp { .. } => { + unreachable!("mcp commands are handled before a client is built") + } } } diff --git a/crates/clickhousectl/src/cloud/permissions.rs b/crates/clickhousectl/src/cloud/permissions.rs index f458dcc72..78c5bd33d 100644 --- a/crates/clickhousectl/src/cloud/permissions.rs +++ b/crates/clickhousectl/src/cloud/permissions.rs @@ -109,6 +109,7 @@ fn declarations() -> impl Iterator { super::clickpipe_endpoints::PERMISSIONS, super::clickpipes::PERMISSIONS, super::clickstack::PERMISSIONS, + super::mcp::PERMISSIONS, super::organizations::PERMISSIONS, super::postgres::PERMISSIONS, super::query_api_endpoints::PERMISSIONS, diff --git a/crates/clickhousectl/src/main.rs b/crates/clickhousectl/src/main.rs index a2c6b95c3..f15144815 100644 --- a/crates/clickhousectl/src/main.rs +++ b/crates/clickhousectl/src/main.rs @@ -218,6 +218,18 @@ fn validate_post_parse(cli: &Cli, cmd: &mut clap::Command) -> std::result::Resul return Err(login.error(kind, message)); } + if let Some(flag) = args.mcp_flag_conflict() { + let add = cmd + .find_subcommand_mut("cloud") + .and_then(|cloud| cloud.find_subcommand_mut("mcp")) + .and_then(|mcp| mcp.find_subcommand_mut("add")) + .expect("cloud mcp add command must exist"); + return Err(add.error( + ErrorKind::ArgumentConflict, + format!("{flag} cannot be used with `cloud mcp add`; the agent signs in to the MCP server itself"), + )); + } + if args.has_explicit_json_format_conflict() { // clap validates each subcommand before propagating values supplied for a // global argument at a parent level, so this cross-level conflict needs a @@ -601,6 +613,52 @@ mod tests { Ok(cli) } + #[test] + fn mcp_add_rejects_cloud_credential_and_org_flags_at_any_level() { + for (flag, value) in [ + ("--org-id", "org-1"), + ("--org-name", "Acme"), + ("--api-key", "key"), + ("--api-secret", "secret"), + ("--url", "https://api.example.com"), + ] { + for args in [ + vec![ + "clickhousectl", + "cloud", + flag, + value, + "mcp", + "add", + "claude", + ], + vec![ + "clickhousectl", + "cloud", + "mcp", + "add", + "claude", + flag, + value, + ], + ] { + let error = parse_and_validate(&args).err().unwrap(); + assert_eq!(error.kind(), ErrorKind::ArgumentConflict, "{args:?}"); + assert!(error.to_string().contains(flag), "{args:?}"); + } + } + parse_and_validate(&[ + "clickhousectl", + "cloud", + "--json", + "--debug", + "mcp", + "add", + "claude", + ]) + .unwrap(); + } + #[test] fn service_query_rejects_explicit_json_with_format_in_both_orders() { for args in [ diff --git a/crates/clickhousectl/tests/cloud_mcp_add_test.rs b/crates/clickhousectl/tests/cloud_mcp_add_test.rs new file mode 100644 index 000000000..2672ec82d --- /dev/null +++ b/crates/clickhousectl/tests/cloud_mcp_add_test.rs @@ -0,0 +1,157 @@ +//! `cloud mcp add` drives the agent's own CLI. Fake agent binaries on PATH +//! record their arguments, so these tests check call order, exit statuses and +//! that stdout holds only clickhousectl's output. +#![cfg(unix)] + +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::{Command, Output, Stdio}; + +const URL: &str = "https://mcp.clickhouse.cloud/mcp"; + +/// A fake agent CLI: logs its arguments, prints to stdout, and exits with +/// `FAKE__EXIT` (default 0) for `mcp `. +fn install_fake(bin: &Path, program: &str) { + let path = bin.join(program); + std::fs::write( + &path, + format!( + "#!/bin/sh\n\ + echo \"{program} $*\" >> \"$CALL_LOG\"\n\ + echo \"fake {program} output\"\n\ + case \"$2\" in\n\ + get) exit \"${{FAKE_GET_EXIT:-0}}\" ;;\n\ + add) exit \"${{FAKE_ADD_EXIT:-0}}\" ;;\n\ + *) exit \"${{FAKE_LOGIN_EXIT:-0}}\" ;;\n\ + esac\n" + ), + ) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); +} + +struct Run { + output: Output, + calls: Vec, +} + +fn run(fakes: &[&str], env: &[(&str, &str)], args: &[&str]) -> Run { + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + for program in fakes { + install_fake(&bin, program); + } + let log = dir.path().join("calls.log"); + let output = Command::new(env!("CARGO_BIN_EXE_clickhousectl")) + .env_clear() + .env("HOME", dir.path()) + .env("PATH", &bin) + .env("DO_NOT_TRACK", "1") + .env("CALL_LOG", &log) + .envs(env.iter().copied()) + .current_dir(dir.path()) + .args(["cloud", "mcp", "add"]) + .args(args) + .stdin(Stdio::null()) + .output() + .unwrap(); + let calls = std::fs::read_to_string(&log) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect(); + Run { output, calls } +} + +fn json(run: &Run) -> serde_json::Value { + assert!(run.output.status.success(), "{:?}", run.output); + serde_json::from_slice(&run.output.stdout).expect("stdout is only the JSON result") +} + +#[test] +fn claude_registers_for_the_user_then_signs_in() { + let run = run( + &["claude"], + &[("FAKE_GET_EXIT", "1")], + &["claude", "--json"], + ); + assert_eq!( + run.calls, + [ + "claude mcp get clickhouse-cloud".to_owned(), + format!("claude mcp add --transport http --scope user clickhouse-cloud {URL}"), + "claude mcp login clickhouse-cloud".to_owned(), + ] + ); + let value = json(&run); + assert_eq!(value["agent"], "claude"); + assert_eq!(value["name"], "clickhouse-cloud"); + assert_eq!(value["url"], URL); + assert_eq!(value["registration"], "added"); + assert_eq!(value["signed_in"], true); + assert!(value.get("sign_in_command").is_none()); + // The agent's own output goes to stderr, keeping stdout parseable. + assert!(String::from_utf8_lossy(&run.output.stderr).contains("fake claude output")); +} + +#[test] +fn claude_with_an_existing_entry_skips_add_and_signs_in_again() { + let run = run(&["claude"], &[], &["claude", "--name", "ch", "--json"]); + assert_eq!(run.calls, ["claude mcp get ch", "claude mcp login ch"]); + let value = json(&run); + assert_eq!(value["registration"], "already_registered"); + assert_eq!(value["signed_in"], true); +} + +#[test] +fn codex_signs_in_during_add() { + let run = run(&["codex"], &[], &["codex", "--json"]); + assert_eq!( + run.calls, + [format!("codex mcp add clickhouse-cloud --url {URL}")] + ); + let value = json(&run); + assert_eq!(value["registration"], "added"); + assert_eq!(value["signed_in"], true); +} + +#[test] +fn gemini_registers_and_returns_the_in_session_sign_in_command() { + let run = run(&["gemini"], &[], &["gemini", "--json"]); + assert_eq!( + run.calls, + [format!( + "gemini mcp add --scope user --transport http clickhouse-cloud {URL}" + )] + ); + let value = json(&run); + assert_eq!(value["signed_in"], false); + assert_eq!(value["sign_in_command"], "/mcp auth clickhouse-cloud"); +} + +#[test] +fn a_failed_agent_step_passes_its_exit_status_through() { + let failed_login = run(&["pi"], &[("FAKE_LOGIN_EXIT", "7")], &["pi", "--json"]); + assert_eq!(failed_login.output.status.code(), Some(7)); + assert_eq!(failed_login.calls.len(), 2); + assert!(failed_login.output.stdout.is_empty()); + + let failed_add = run(&["opencode"], &[("FAKE_ADD_EXIT", "3")], &["opencode"]); + assert_eq!(failed_add.output.status.code(), Some(3)); + assert_eq!(failed_add.calls.len(), 1, "no sign-in after a failed add"); +} + +#[test] +fn a_missing_agent_cli_is_an_error() { + let run = run(&[], &[], &["claude", "--json"]); + assert_eq!(run.output.status.code(), Some(1)); + assert!(run.output.stdout.is_empty()); + let error: serde_json::Value = serde_json::from_slice(&run.output.stderr).unwrap(); + assert!( + error["error"]["message"] + .as_str() + .unwrap() + .contains("claude") + ); +} diff --git a/docs/README.md b/docs/README.md index 29108d44b..b58f6231c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ Start with the [README](../README.md) for installation and product examples. The | Load object storage or replicate Postgres, then verify ingestion | [ClickPipes](guides/clickpipes.md) | | Create and safely replace a ClickStack dashboard | [ClickStack](guides/clickstack.md) | | Test an executable UDF locally, then deploy and update it in Cloud | [User-defined functions](guides/user-defined-functions.md) | +| Connect a coding agent to the hosted Cloud MCP server | [Cloud MCP server](guides/cloud-mcp.md) | ## Reference diff --git a/docs/guides/cloud-mcp.md b/docs/guides/cloud-mcp.md new file mode 100644 index 000000000..3b812f306 --- /dev/null +++ b/docs/guides/cloud-mcp.md @@ -0,0 +1,37 @@ +# Connect a coding agent to the Cloud MCP server + +[All documentation](../README.md) + +The [ClickHouse Cloud MCP server](https://clickhouse.com/docs/products/cloud/features/ai-ml/mcp/remote-mcp) gives an agent read-only access to your organizations, services and data at `https://mcp.clickhouse.cloud/mcp`. `cloud mcp add` registers it in a coding agent and starts that agent's sign-in in one step. + +You need the agent's CLI on your `PATH` and a ClickHouse Cloud account. You don't need to sign in to clickhousectl: the agent signs in to the MCP server itself and keeps its own token. Cloud-wide flags such as `--org-id` and `--api-key` are rejected, because clickhousectl doesn't authenticate to the MCP server. + +## Register and sign in + +```bash +clickhousectl cloud mcp add claude +``` + +The server is registered for your user, so it's available in every project. Sign-in then opens your browser and waits until you finish it. If you're already signed in to ClickHouse Cloud in that browser, it can finish in a few seconds. Start a new agent session to use the server's tools. + +| Agent | Registers with | Signs in with | +| --- | --- | --- | +| `claude` | `claude mcp add --transport http --scope user` | `claude mcp login` | +| `codex` | `codex mcp add --url` | `codex mcp add`, which signs in itself | +| `opencode` | `opencode mcp add --url --global` | `opencode mcp auth` | +| `pi` | `pi mcp add --url` | `pi mcp login` | +| `gemini` | `gemini mcp add --scope user --transport http` | None. Run `/mcp auth clickhouse-cloud` inside Gemini CLI | + +The server is named `clickhouse-cloud`; use `--name` to choose another name. + +## Rerun or remove + +Rerunning is safe and signs in again, for example after you sign out or a token expires. Claude Code keeps an existing entry with the same name; the other agents replace it. + +To remove the server, use the agent's own command, such as `claude mcp remove clickhouse-cloud -s user` or `codex mcp remove clickhouse-cloud`. + +## Use it from scripts and agents + +With `--json`, or when clickhousectl detects a coding agent, stdout holds one object with `agent`, `name`, `url`, `registration` (`added` or `already_registered`) and `signed_in`. For Gemini CLI, `sign_in_command` holds the command to run in a session. The agent CLI's own messages, including any sign-in URL, go to stderr. If the agent CLI fails, clickhousectl exits with its exit code. + +Sign-in blocks until a person finishes it in the browser, including when a coding agent runs the command. diff --git a/scripts/classify-cloud-integration.py b/scripts/classify-cloud-integration.py index de4143f15..6a9c3611b 100644 --- a/scripts/classify-cloud-integration.py +++ b/scripts/classify-cloud-integration.py @@ -17,6 +17,7 @@ "crates/clickhousectl/src/stdout.rs": NO_SUITES, "crates/clickhousectl/src/cloud/clickstack.rs": NO_SUITES, "crates/clickhousectl/src/cloud/config.rs": NO_SUITES, + "crates/clickhousectl/src/cloud/mcp.rs": NO_SUITES, "crates/clickhousectl/src/cloud/permissions.rs": NO_SUITES, "crates/clickhousectl/src/cloud/query_api_endpoints.rs": NO_SUITES, "crates/clickhousectl/src/cloud/saved_queries.rs": NO_SUITES, @@ -116,6 +117,7 @@ "crates/clickhouse-openapi-analyzer/tests/fixtures/operation_contracts/after.json": NO_SUITES, "crates/clickhousectl/tests/local_docker_status_test.rs": NO_SUITES, "crates/clickhousectl/tests/skills_usage_test.rs": NO_SUITES, + "crates/clickhousectl/tests/cloud_mcp_add_test.rs": NO_SUITES, "crates/clickhousectl/tests/local_client_output_contract_test.rs": NO_SUITES, "crates/clickhousectl/tests/local_postgres_client_input_test.rs": NO_SUITES, "crates/clickhouse-cloud-api/tests/clickpipes/driver.rs": NO_SUITES, diff --git a/scripts/classify-install-integration.py b/scripts/classify-install-integration.py index 133edba1c..e02988a04 100644 --- a/scripts/classify-install-integration.py +++ b/scripts/classify-install-integration.py @@ -104,6 +104,7 @@ "crates/clickhousectl/tests/telemetry_test.rs", "crates/clickhousectl/tests/local_stdout_test.rs", "crates/clickhousectl/tests/skills_usage_test.rs", + "crates/clickhousectl/tests/cloud_mcp_add_test.rs", } ) diff --git a/scripts/tests/test_classify_install_integration.py b/scripts/tests/test_classify_install_integration.py index 868d49bc1..a6aa4aa14 100644 --- a/scripts/tests/test_classify_install_integration.py +++ b/scripts/tests/test_classify_install_integration.py @@ -179,6 +179,7 @@ def test_exact_path_mappings(self): "crates/clickhousectl/tests/telemetry_test.rs", "crates/clickhousectl/tests/local_stdout_test.rs", "crates/clickhousectl/tests/skills_usage_test.rs", + "crates/clickhousectl/tests/cloud_mcp_add_test.rs", } ), ) From a6ac2f09d6202b9488f19d1c640a03f504efe109 Mon Sep 17 00:00:00 2001 From: sdairs Date: Wed, 4 Nov 2026 10:00:17 +0000 Subject: [PATCH 2/4] feat(cli): hide rejected Cloud-wide flags from cloud mcp help (#1212) cloud mcp rejects --org-id, --org-name, --api-key, --api-secret and --url. Hidden copies on the mcp subcommand stop clap propagating the visible ones there, so other Cloud commands are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/clickhousectl/src/cli.rs | 20 +++++++++++++++----- crates/clickhousectl/src/cloud/cli.rs | 9 +++++---- crates/clickhousectl/src/cloud/mcp.rs | 19 +++++++++++++++++++ 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/clickhousectl/src/cli.rs b/crates/clickhousectl/src/cli.rs index 0992ebef2..aed5164d7 100644 --- a/crates/clickhousectl/src/cli.rs +++ b/crates/clickhousectl/src/cli.rs @@ -39,13 +39,13 @@ pub struct Cli { // Parsing and all help consumers use the same decorated command tree. impl clap::CommandFactory for Cli { fn command() -> clap::Command { - crate::cloud::permissions::decorate(Self::augment_args(clap::Command::new("clickhousectl"))) + let command = Self::augment_args(clap::Command::new("clickhousectl")); + crate::cloud::mcp::hide_rejected_cloud_flags(crate::cloud::permissions::decorate(command)) } fn command_for_update() -> clap::Command { - crate::cloud::permissions::decorate(Self::augment_args_for_update(clap::Command::new( - "clickhousectl", - ))) + let command = Self::augment_args_for_update(clap::Command::new("clickhousectl")); + crate::cloud::mcp::hide_rejected_cloud_flags(crate::cloud::permissions::decorate(command)) } } @@ -467,13 +467,23 @@ mod tests { } else { &[] }; + // `cloud mcp` rejects the credential and organization flags, so it hides them. + let mcp_hidden: &[&str] = if path.starts_with("clickhousectl cloud mcp") { + &["org-id", "org-name", "api-key", "api-secret", "url"] + } else { + &[] + }; for flag in required { let arg = command .get_arguments() .find(|arg| arg.get_long() == Some(flag)) .unwrap_or_else(|| panic!("{path}: missing inherited --{flag}")); - if *flag == "url" { + if mcp_hidden.contains(flag) { + assert!(arg.is_hide_set(), "{path}: --{flag}"); + } else if *flag == "url" { assert_eq!(arg.is_hide_set(), !cfg!(debug_assertions), "{path}"); + } else { + assert!(!arg.is_hide_set(), "{path}: --{flag}"); } } }); diff --git a/crates/clickhousectl/src/cloud/cli.rs b/crates/clickhousectl/src/cloud/cli.rs index 41e354469..5b26fa97d 100644 --- a/crates/clickhousectl/src/cloud/cli.rs +++ b/crates/clickhousectl/src/cloud/cli.rs @@ -394,7 +394,8 @@ pub(crate) mod tests { #[test] fn org_id_is_global_and_visible_throughout_cloud_hierarchy() { - fn walk(command: &clap::Command) { + // `cloud mcp` rejects --org-id, so only that subtree hides it. + fn walk(command: &clap::Command, under_mcp: bool) { let selectors: Vec<_> = command .get_arguments() .filter(|arg| arg.get_id() == "org_id") @@ -402,7 +403,7 @@ pub(crate) mod tests { assert_eq!(selectors.len(), 1, "{}", command.get_name()); let selector = selectors[0]; assert!(selector.is_global_set()); - assert!(!selector.is_hide_set()); + assert_eq!(selector.is_hide_set(), under_mcp, "{}", command.get_name()); assert!(!selector.is_required_set()); assert_eq!(selector.get_long(), Some("org-id")); assert!( @@ -414,13 +415,13 @@ pub(crate) mod tests { .get_subcommands() .filter(|child| child.get_name() != "help") { - walk(child); + walk(child, under_mcp || child.get_name() == "mcp"); } } let mut command = Cli::command(); command.build(); assert!(!command.get_arguments().any(|arg| arg.get_id() == "org_id")); - walk(command.find_subcommand("cloud").unwrap()); + walk(command.find_subcommand("cloud").unwrap(), false); assert!( Cli::try_parse_from(["chctl", "--org-id", "org-1", "cloud", "org", "get"]).is_err() ); diff --git a/crates/clickhousectl/src/cloud/mcp.rs b/crates/clickhousectl/src/cloud/mcp.rs index 7dda90ff2..6a746e60d 100644 --- a/crates/clickhousectl/src/cloud/mcp.rs +++ b/crates/clickhousectl/src/cloud/mcp.rs @@ -18,6 +18,25 @@ pub(super) const PERMISSIONS: &[Permission] = &[Permission::non_api( /// ClickHouse Cloud's hosted MCP server. pub const CLOUD_MCP_URL: &str = "https://mcp.clickhouse.cloud/mcp"; +/// Cloud-wide flags that `mcp` commands reject, because the agent signs in to +/// the MCP server itself (see `CloudArgs::mcp_flag_conflict`). +const REJECTED_CLOUD_FLAGS: [&str; 5] = ["org_id", "org_name", "api_key", "api_secret", "url"]; + +/// Hide the rejected Cloud-wide flags from `cloud mcp` help. clap propagates a +/// global flag only into subcommands without an arg of the same ID, so hidden +/// copies on `mcp` replace the visible ones there and nowhere else. The copies +/// stay global, so a value given after `mcp add` still reaches `CloudArgs`. +pub(crate) fn hide_rejected_cloud_flags(root: clap::Command) -> clap::Command { + root.mut_subcommand("cloud", |cloud| { + let hidden: Vec = cloud + .get_arguments() + .filter(|arg| REJECTED_CLOUD_FLAGS.contains(&arg.get_id().as_str())) + .map(|arg| arg.clone().hide(true)) + .collect(); + cloud.mut_subcommand("mcp", |mcp| mcp.args(hidden)) + }) +} + #[derive(Subcommand, Debug)] pub enum McpCommands { /// Register the Cloud MCP server in a coding agent and sign in From ddacd41ff3824c5820d57b05177b921441b397f8 Mon Sep 17 00:00:00 2001 From: sdairs Date: Wed, 4 Nov 2026 10:02:26 +0000 Subject: [PATCH 3/4] docs(cli): explain why cloud mcp copies the Cloud-wide flags (#1212) Co-Authored-By: Claude Opus 5.5 --- crates/clickhousectl/src/cloud/mcp.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/clickhousectl/src/cloud/mcp.rs b/crates/clickhousectl/src/cloud/mcp.rs index 6a746e60d..f0e3a5b78 100644 --- a/crates/clickhousectl/src/cloud/mcp.rs +++ b/crates/clickhousectl/src/cloud/mcp.rs @@ -22,10 +22,14 @@ pub const CLOUD_MCP_URL: &str = "https://mcp.clickhouse.cloud/mcp"; /// the MCP server itself (see `CloudArgs::mcp_flag_conflict`). const REJECTED_CLOUD_FLAGS: [&str; 5] = ["org_id", "org_name", "api_key", "api_secret", "url"]; -/// Hide the rejected Cloud-wide flags from `cloud mcp` help. clap propagates a -/// global flag only into subcommands without an arg of the same ID, so hidden -/// copies on `mcp` replace the visible ones there and nowhere else. The copies -/// stay global, so a value given after `mcp add` still reaches `CloudArgs`. +/// Hide the rejected Cloud-wide flags from `cloud mcp` help, and nothing else. +/// +/// The copies added to `mcp` exist only to override the global flags so they +/// can be hidden there: clap propagates a global flag only into subcommands +/// without an arg of the same ID, so these hidden copies replace the visible +/// ones under `mcp` and leave every other Cloud command unchanged. They add no +/// behaviour. Rejecting the flags is `CloudArgs::mcp_flag_conflict`'s job, and +/// the copies stay global so a value given after `mcp add` still reaches it. pub(crate) fn hide_rejected_cloud_flags(root: clap::Command) -> clap::Command { root.mut_subcommand("cloud", |cloud| { let hidden: Vec = cloud From 3a54621cc122118e6c236ed41e0433024d023a9b Mon Sep 17 00:00:00 2001 From: sdairs Date: Wed, 4 Nov 2026 10:11:26 +0000 Subject: [PATCH 4/4] feat(cli): skip Claude sign-in when stdin isn't a terminal (#1212) claude mcp login exits 1 without a terminal, which is how coding agents and scripts run commands. Register the server, skip sign-in, and return /mcp as the sign-in command instead of failing after a partial success. Co-Authored-By: Claude Opus 5.5 --- crates/clickhousectl/src/cloud/mcp.rs | 102 ++++++++++++++++-- .../clickhousectl/tests/cloud_mcp_add_test.rs | 16 +-- docs/guides/cloud-mcp.md | 6 +- 3 files changed, 104 insertions(+), 20 deletions(-) diff --git a/crates/clickhousectl/src/cloud/mcp.rs b/crates/clickhousectl/src/cloud/mcp.rs index f0e3a5b78..7dabc69da 100644 --- a/crates/clickhousectl/src/cloud/mcp.rs +++ b/crates/clickhousectl/src/cloud/mcp.rs @@ -8,6 +8,7 @@ use super::permissions::Declaration as Permission; use crate::error::{Error, Result}; use clap::{Args, Subcommand, ValueEnum}; use serde::Serialize; +use std::io::IsTerminal; use std::process::{Command, Stdio}; pub(super) const PERMISSIONS: &[Permission] = &[Permission::non_api( @@ -49,7 +50,8 @@ CONTEXT FOR AGENTS: Registers the read-only Cloud MCP server for the user, in all projects, using the agent's own CLI. Then starts that agent's OAuth sign-in, which opens a browser and blocks until a human finishes it; with an existing Cloud browser session it can finish in seconds. - gemini has no sign-in command: run `/mcp auth ` inside Gemini CLI afterwards. + Sign-in is skipped for gemini (no sign-in command) and for claude when stdin isn't a terminal; + the output then names the command to run inside the agent, such as `/mcp`. Needs the agent's CLI on PATH, not clickhousectl credentials. Safe to rerun to sign in again. The server's tools appear in new agent sessions, not the one that ran this.")] Add(AddArgs), @@ -116,6 +118,12 @@ impl Agent { enum SignIn { /// A separate command, run after `add`. Command(Vec), + /// A separate command that the agent's CLI refuses to run unless stdin is + /// a terminal. Without one, sign in inside the agent with `in_session`. + CommandNeedingTerminal { + login: Vec, + in_session: String, + }, /// `add` signs in by itself when the server supports OAuth. DuringAdd, /// Only from inside an agent session, with this slash command. @@ -151,7 +159,12 @@ fn plan(agent: Agent, name: &str) -> Plan { name, url, ]), - sign_in: SignIn::Command(argv(&["mcp", "login", name])), + // `claude mcp login` exits 1 when stdin isn't a terminal, even + // though its browser sign-in doesn't read stdin. + sign_in: SignIn::CommandNeedingTerminal { + login: argv(&["mcp", "login", name]), + in_session: "/mcp".into(), + }, }, Agent::Codex => Plan { exists: None, @@ -185,6 +198,30 @@ fn plan(agent: Agent, name: &str) -> Plan { } } +/// What `add` does about sign-in once the server is registered. +#[derive(Debug, PartialEq, Eq)] +enum SignInStep { + Run(Vec), + /// `add` already signed in. + Done, + /// The user signs in inside the agent with this command. + InSession(String), + /// Skipped for lack of a terminal; the user signs in inside the agent with + /// this command or reruns in a terminal. + NoTerminal(String), +} + +fn sign_in_step(sign_in: SignIn, stdin_is_terminal: bool) -> SignInStep { + match sign_in { + SignIn::Command(login) => SignInStep::Run(login), + SignIn::CommandNeedingTerminal { login, .. } if stdin_is_terminal => SignInStep::Run(login), + SignIn::CommandNeedingTerminal { in_session, .. } => SignInStep::NoTerminal(in_session), + // These agents have no existence check, so `add` always ran. + SignIn::DuringAdd => SignInStep::Done, + SignIn::InSession(command) => SignInStep::InSession(command), + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] enum Registration { @@ -202,6 +239,9 @@ struct AddOutput { /// What the user runs inside the agent to sign in, when the agent's CLI can't. #[serde(skip_serializing_if = "Option::is_none")] sign_in_command: Option, + /// Sign-in was skipped because stdin isn't a terminal. + #[serde(skip)] + no_terminal: bool, } pub fn run(command: McpCommands, debug: bool, json: bool) -> Result<()> { @@ -225,18 +265,26 @@ fn add(args: AddArgs, debug: bool, json: bool) -> Result<()> { Registration::Added }; - let (signed_in, sign_in_command) = match plan.sign_in { - SignIn::Command(login) => { + let step = sign_in_step(plan.sign_in, std::io::stdin().is_terminal()); + let (signed_in, sign_in_command, no_terminal) = match step { + SignInStep::Run(login) => { eprint_line(format!( "Signing in to {} from {}; finish in the browser.", args.name, agent.display_name() )); check(spawn(agent, &login, debug, ChildOutput::ToStderr)?)?; - (true, None) + (true, None, false) + } + SignInStep::Done => (true, None, false), + SignInStep::InSession(command) => (false, Some(command), false), + SignInStep::NoTerminal(command) => { + eprint_line(format!( + "Skipped sign-in: {} signs in only from a terminal, and stdin isn't one.", + agent.display_name() + )); + (false, Some(command), true) } - SignIn::DuringAdd => (registration == Registration::Added, None), - SignIn::InSession(command) => (false, Some(command)), }; let output = AddOutput { @@ -246,6 +294,7 @@ fn add(args: AddArgs, debug: bool, json: bool) -> Result<()> { registration, signed_in, sign_in_command, + no_terminal, }; if json { println!("{}", serde_json::to_string_pretty(&output)?); @@ -264,7 +313,13 @@ fn print_human(output: &AddOutput) { } } if let Some(command) = &output.sign_in_command { - println!("To sign in, run `{command}` in {agent}."); + if output.no_terminal { + println!( + "To sign in, run `{command}` in {agent}, or rerun this command in a terminal." + ); + } else { + println!("To sign in, run `{command}` in {agent}."); + } } else if output.signed_in { println!("Signed in. Start a new {agent} session to use it."); } @@ -400,7 +455,10 @@ mod tests { fn plans_sign_in_the_way_each_agent_supports() { assert_eq!( plan(Agent::Claude, "ch").sign_in, - SignIn::Command(argv(&["mcp", "login", "ch"])) + SignIn::CommandNeedingTerminal { + login: argv(&["mcp", "login", "ch"]), + in_session: "/mcp".into(), + } ); assert_eq!(plan(Agent::Codex, "ch").sign_in, SignIn::DuringAdd); assert_eq!( @@ -417,6 +475,32 @@ mod tests { ); } + #[test] + fn only_a_terminal_bound_sign_in_depends_on_stdin() { + for terminal in [true, false] { + assert_eq!( + sign_in_step(plan(Agent::Pi, "ch").sign_in, terminal), + SignInStep::Run(argv(&["mcp", "login", "ch"])) + ); + assert_eq!( + sign_in_step(plan(Agent::Codex, "ch").sign_in, terminal), + SignInStep::Done + ); + assert_eq!( + sign_in_step(plan(Agent::Gemini, "ch").sign_in, terminal), + SignInStep::InSession("/mcp auth ch".into()) + ); + } + assert_eq!( + sign_in_step(plan(Agent::Claude, "ch").sign_in, true), + SignInStep::Run(argv(&["mcp", "login", "ch"])) + ); + assert_eq!( + sign_in_step(plan(Agent::Claude, "ch").sign_in, false), + SignInStep::NoTerminal("/mcp".into()) + ); + } + #[test] fn only_claude_checks_for_an_existing_entry() { assert_eq!( diff --git a/crates/clickhousectl/tests/cloud_mcp_add_test.rs b/crates/clickhousectl/tests/cloud_mcp_add_test.rs index 2672ec82d..49cbc1c49 100644 --- a/crates/clickhousectl/tests/cloud_mcp_add_test.rs +++ b/crates/clickhousectl/tests/cloud_mcp_add_test.rs @@ -1,6 +1,7 @@ //! `cloud mcp add` drives the agent's own CLI. Fake agent binaries on PATH //! record their arguments, so these tests check call order, exit statuses and -//! that stdout holds only clickhousectl's output. +//! that stdout holds only clickhousectl's output. stdin is never a terminal +//! here, so Claude's sign-in is always skipped; unit tests cover the other case. #![cfg(unix)] use std::os::unix::fs::PermissionsExt; @@ -70,7 +71,7 @@ fn json(run: &Run) -> serde_json::Value { } #[test] -fn claude_registers_for_the_user_then_signs_in() { +fn claude_without_a_terminal_registers_and_skips_sign_in() { let run = run( &["claude"], &[("FAKE_GET_EXIT", "1")], @@ -81,7 +82,6 @@ fn claude_registers_for_the_user_then_signs_in() { [ "claude mcp get clickhouse-cloud".to_owned(), format!("claude mcp add --transport http --scope user clickhouse-cloud {URL}"), - "claude mcp login clickhouse-cloud".to_owned(), ] ); let value = json(&run); @@ -89,19 +89,19 @@ fn claude_registers_for_the_user_then_signs_in() { assert_eq!(value["name"], "clickhouse-cloud"); assert_eq!(value["url"], URL); assert_eq!(value["registration"], "added"); - assert_eq!(value["signed_in"], true); - assert!(value.get("sign_in_command").is_none()); + assert_eq!(value["signed_in"], false); + assert_eq!(value["sign_in_command"], "/mcp"); // The agent's own output goes to stderr, keeping stdout parseable. assert!(String::from_utf8_lossy(&run.output.stderr).contains("fake claude output")); } #[test] -fn claude_with_an_existing_entry_skips_add_and_signs_in_again() { +fn claude_with_an_existing_entry_skips_add() { let run = run(&["claude"], &[], &["claude", "--name", "ch", "--json"]); - assert_eq!(run.calls, ["claude mcp get ch", "claude mcp login ch"]); + assert_eq!(run.calls, ["claude mcp get ch"]); let value = json(&run); assert_eq!(value["registration"], "already_registered"); - assert_eq!(value["signed_in"], true); + assert_eq!(value["signed_in"], false); } #[test] diff --git a/docs/guides/cloud-mcp.md b/docs/guides/cloud-mcp.md index 3b812f306..9b95518cb 100644 --- a/docs/guides/cloud-mcp.md +++ b/docs/guides/cloud-mcp.md @@ -16,7 +16,7 @@ The server is registered for your user, so it's available in every project. Sign | Agent | Registers with | Signs in with | | --- | --- | --- | -| `claude` | `claude mcp add --transport http --scope user` | `claude mcp login` | +| `claude` | `claude mcp add --transport http --scope user` | `claude mcp login`, from a terminal only. Otherwise run `/mcp` inside Claude Code | | `codex` | `codex mcp add --url` | `codex mcp add`, which signs in itself | | `opencode` | `opencode mcp add --url --global` | `opencode mcp auth` | | `pi` | `pi mcp add --url` | `pi mcp login` | @@ -32,6 +32,6 @@ To remove the server, use the agent's own command, such as `claude mcp remove cl ## Use it from scripts and agents -With `--json`, or when clickhousectl detects a coding agent, stdout holds one object with `agent`, `name`, `url`, `registration` (`added` or `already_registered`) and `signed_in`. For Gemini CLI, `sign_in_command` holds the command to run in a session. The agent CLI's own messages, including any sign-in URL, go to stderr. If the agent CLI fails, clickhousectl exits with its exit code. +With `--json`, or when clickhousectl detects a coding agent, stdout holds one object with `agent`, `name`, `url`, `registration` (`added` or `already_registered`) and `signed_in`. When sign-in is left to the agent, `sign_in_command` holds the command to run in a session. The agent CLI's own messages, including any sign-in URL, go to stderr. If the agent CLI fails, clickhousectl exits with its exit code. -Sign-in blocks until a person finishes it in the browser, including when a coding agent runs the command. +Sign-in blocks until a person finishes it in the browser, including when a coding agent runs the command. Claude Code signs in only from a terminal, so when stdin isn't one, for example when an agent or script runs the command, clickhousectl registers the server, skips sign-in and returns `/mcp` as `sign_in_command`.