:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cli): quiet agent api discovery commands (#64754)
Chris Volzer8c030733b14a
diff --git a/cli/.sampo/changesets/fabled-princess-lempo.md b/cli/.sampo/changesets/fabled-princess-lempo.mdnew file mode 100644index 000000000000..8b528eaf4cc2--- /dev/null+++ b/cli/.sampo/changesets/fabled-princess-lempo.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Quiet agent API discovery commandsdiff --git a/cli/src/commands.rs b/cli/src/commands.rsindex a946f6e4be16..d406e482d374 100644--- a/cli/src/commands.rs+++ b/cli/src/commands.rs@@ -79,6 +79,33 @@ fn dry_run_skipped_command(command: &Commands) -> Option<&'static str> {}}+// These are the API key env vars recognized by the Node `posthog-cli api` bundle.+// Rust auth only reads the POSTHOG_CLI_* aliases; this check is deliberately about+// whether the child process already has a usable key, so we avoid loading and mixing+// stored credentials.+const API_KEY_ENV_VARS: &[&str] = &[+ "POSTHOG_API_KEY",+ "POSTHOG_CLI_API_KEY",+ "POSTHOG_CLI_TOKEN",+];++fn api_command_needs_stored_credentials_with_env(+ args: &[String],+ has_env: impl Fn(&str) -> bool,+) -> bool {+ let Some(command) = args.first().map(String::as_str) else {+ return false;+ };++ command == "call"+ && !args.iter().skip(1).any(|arg| arg == "--dry-run")+ && !API_KEY_ENV_VARS.iter().any(|name| has_env(name))+}++fn api_command_needs_stored_credentials(args: &[String]) -> bool {+ api_command_needs_stored_credentials_with_env(args, |name| std::env::var_os(name).is_some())+}+#[derive(Subcommand)]pub enum Commands {/// Interactively authenticate with PostHog, storing a personal API token locally. You can also use the@@ -318,17 +345,21 @@ impl Cli {}},Commands::Api { args } => {- let api_context = match init_context(- self.host.clone(),- self.skip_ssl_verification,- self.rate_limit,- self.env_file.clone(),- ) {- Ok(_) => Some(context()),- Err(error) => {- debug!("API CLI proxy running without invocation context: {error:?}");- None+ let api_context = if api_command_needs_stored_credentials(&args) {+ match init_context(+ self.host.clone(),+ self.skip_ssl_verification,+ self.rate_limit,+ self.env_file.clone(),+ ) {+ Ok(_) => Some(context()),+ Err(error) => {+ debug!("API CLI proxy running without invocation context: {error:?}");+ None+ }}+ } else {+ None};api_proxy::run(args, self.host, api_context)?;}@@ -478,6 +509,60 @@ mod tests {}}+ #[test]+ fn api_metadata_commands_do_not_need_stored_credentials() {+ let cases: &[&[&str]] = &[+ &[],+ &["--agent-help"],+ &["tools"],+ &["search", "feature-flag"],+ &["info", "feature-flag-get-all"],+ &["schema", "query-trends", "series"],+ &["skill", "list"],+ &["agents-md", "install"],+ ];++ for argv in cases {+ let args = argv.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();+ assert!(+ !api_command_needs_stored_credentials_with_env(&args, |_| false),+ "metadata command should not load stored credentials: {argv:?}"+ );+ }+ }++ #[test]+ fn api_call_uses_stored_credentials_only_when_needed() {+ let call_args = ["call", "--json", "feature-flag-get-all", "{\"limit\":5}"]+ .iter()+ .map(|arg| arg.to_string())+ .collect::<Vec<_>>();++ assert!(api_command_needs_stored_credentials_with_env(+ &call_args,+ |_| false+ ));+ assert!(!api_command_needs_stored_credentials_with_env(+ &call_args,+ |name| name == "POSTHOG_API_KEY"+ ));++ let dry_run_args = [+ "call",+ "--dry-run",+ "feature-flags-bulk-delete-create",+ "{\"ids\":[123]}",+ ]+ .iter()+ .map(|arg| arg.to_string())+ .collect::<Vec<_>>();++ assert!(!api_command_needs_stored_credentials_with_env(+ &dry_run_args,+ |_| false+ ));+ }+#[test]fn endpoints_dry_run_is_independent_of_top_level_flag() {// The `exp endpoints` commands have their own `--dry-run` (preview). The top-level flag isdiff --git a/cli/src/invocation_context.rs b/cli/src/invocation_context.rsindex ab2c5284aabf..25ac0f3e8c74 100644--- a/cli/src/invocation_context.rs+++ b/cli/src/invocation_context.rs@@ -12,7 +12,7 @@ use std::{sync::{Mutex, OnceLock},thread::JoinHandle,};-use tracing::{debug, info, warn};+use tracing::debug;use crate::{api::client::PHClient,@@ -64,7 +64,7 @@ pub fn init_context(.expect("Building PH config succeeds");posthog_rs::init_global(ph_config).expect("Initializing PostHog client");} else {- warn!("Posthog api token not set at build time - is this a debug build?");+ debug!("Posthog api token not set at build time - is this a debug build?");};Ok(())@@ -155,14 +155,10 @@ impl InvocationContext {}pub fn finish(&self) {- info!("Finishing up....");-self.handles.lock().unwrap().drain(..).for_each(|handle| handle.join().unwrap());-- info!("Finished!")}}diff --git a/cli/src/main.rs b/cli/src/main.rsindex e7a945666456..3cfc0bb56222 100644--- a/cli/src/main.rs+++ b/cli/src/main.rs@@ -1,6 +1,5 @@use posthog_cli::cmd;use rayon::ThreadPoolBuilder;-use tracing::info;fn main() {let subscriber = tracing_subscriber::fmt()@@ -21,7 +20,7 @@ fn main() {tracing::subscriber::set_global_default(subscriber).expect("Failed to set tracing subscriber");match cmd::Cli::run() {- Ok(_) => info!("All done, happy hogging!"),+ Ok(_) => {}Err(e) => {match e.exception_id {Some(id) => {diff --git a/cli/src/utils/auth.rs b/cli/src/utils/auth.rsindex 39fc176a5051..741b55e10992 100644--- a/cli/src/utils/auth.rs+++ b/cli/src/utils/auth.rs@@ -4,7 +4,7 @@ use anyhow::{Context, Error};use inquire::{validator::Validation, CustomUserError};use reqwest::Url;use std::path::PathBuf;-use tracing::{info, warn};+use tracing::{debug, warn};use serde::{Deserialize, Serialize};@@ -165,7 +165,7 @@ pub fn get_token(env_file: Option<PathBuf>) -> Result<Token, Error> {let env = EnvVarProvider { env_file };let env_err = match env.get_credentials() {Ok(token) => {- info!(+ debug!("Using token from environment or --dotenv-file, for environment {}",token.env_id);@@ -176,7 +176,7 @@ pub fn get_token(env_file: Option<PathBuf>) -> Result<Token, Error> {let provider = HomeDirProvider;let dir_err = match provider.get_credentials() {Ok(token) => {- info!(+ debug!("Using token from: {}, for environment {}",provider.report_location(),token.env_iddiff --git a/services/mcp/src/cli/index.ts b/services/mcp/src/cli/index.tsindex 627c9b45bdd9..f44e0ec62cd1 100644--- a/services/mcp/src/cli/index.ts+++ b/services/mcp/src/cli/index.ts@@ -20,12 +20,16 @@ schema <tool_name> [field_path]call [--json] [--confirm] <tool_name> <json_input>`interface BuiltExec {- config: CliConfigcontext: ContextexecTool: Tool<ZodObjectAny>tools: Tool<ZodObjectAny>[]}+interface BuiltStaticExec {+ execTool: Tool<ZodObjectAny>+ tools: Tool<ZodObjectAny>[]+}+function usage(): string {return `PostHog agent CLI@@ -61,6 +65,22 @@ function printResult(result: unknown): void {process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)}+function buildStaticExec(): BuiltStaticExec {+ const tools = getCliTools()+ const execTool = createExecTool(+ tools,+ undefined,+ 'Execute a PostHog CLI command',+ COMMAND_REFERENCE,+ 'posthog-cli',+ undefined,+ [],+ { requireDestructiveConfirmation: true }+ )++ return { execTool, tools }+}+async function buildExec(config: CliConfig = resolveCliConfig()): Promise<BuiltExec> {const context = await buildCliContext(config)const aiConsentGiven = await context.stateManager.getAiConsentGiven()@@ -85,13 +105,17 @@ async function buildExec(config: CliConfig = resolveCliConfig()): Promise<BuiltE{ requireDestructiveConfirmation: true })- return { config, context, execTool, tools }+ return { context, execTool, tools }}-async function buildAgentHelpForConfig(config: CliConfig = resolveCliConfig()): Promise<string> {- const context = await buildCliContext(config)- const aiConsentGiven = await context.stateManager.getAiConsentGiven()- return buildAgentHelp(getCliTools({ aiConsentGiven }))+function buildAgentHelpForStaticCatalog(): string {+ return buildAgentHelp(getCliTools())+}++async function runStaticExecCommand(command: string): Promise<void> {+ const { execTool } = buildStaticExec()+ const result = await execTool.handler(undefined as unknown as Context, { command })+ printResult(result)}async function runExecCommand(command: string): Promise<void> {@@ -113,7 +137,7 @@ async function runDryCall(args: string[]): Promise<void> {throw new Error('Usage: posthog-cli api call --dry-run [--json] [--confirm] <tool> <json>')}- const { tools } = await buildExec()+ const { tools } = buildStaticExec()const tool = tools.find((candidate) => candidate.name === toolName)if (!tool) {throw new Error(`Unknown tool: "${toolName}". Run "posthog-cli api search <term>".`)@@ -189,16 +213,16 @@ async function main(): Promise<void> {}if (command === 'agent-help' || command === '--agent-help') {- process.stdout.write(`${await buildAgentHelpForConfig()}\n`)+ process.stdout.write(`${buildAgentHelpForStaticCatalog()}\n`)return}switch (command) {case 'tools':- await runExecCommand('tools')+ await runStaticExecCommand('tools')returncase 'search':- await runExecCommand(`search ${args.join(' ')}`)+ await runStaticExecCommand(`search ${args.join(' ')}`)returncase 'info': {const json = takeFlag(args, '--json')@@ -206,7 +230,7 @@ async function main(): Promise<void> {if (!toolName) {throw new Error('Usage: posthog-cli api info [--json] <tool>')}- await runExecCommand(`info ${json ? '--json ' : ''}${toolName}`)+ await runStaticExecCommand(`info ${json ? '--json ' : ''}${toolName}`)return}case 'schema': {@@ -214,7 +238,7 @@ async function main(): Promise<void> {if (!toolName) {throw new Error('Usage: posthog-cli api schema <tool> [field.path]')}- await runExecCommand(`schema ${toolName}${args[0] ? ` ${args[0]}` : ''}`)+ await runStaticExecCommand(`schema ${toolName}${args[0] ? ` ${args[0]}` : ''}`)return}case 'call': {diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex c2d74ad34857..51da1a052533 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -187,7 +187,7 @@ function findTool(tools: Tool<ZodObjectAny>[], name: string): Tool<ZodObjectAny>export function createExecTool(allTools: Tool<ZodObjectAny>[],- context: Context,+ context: Context | undefined,toolDescription: string,commandReference: string,mcpConsumer: string | undefined,@@ -346,6 +346,9 @@ export function createExecTool(if (!rest) {throw new Error('Usage: call [--json] [--confirm] <tool_name> <json_input>')}+ if (!context) {+ throw new Error('Cannot call PostHog tools without an API context')+ }const { forceJson, confirmed, rest: callArgs } = parseCallFlags(rest)if (!callArgs) {throw new Error('Usage: call [--json] [--confirm] <tool_name> <json_input>')