Skip to content

: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.

feat(cli): add agentic api tools (#61178)

Chris Volzer4bb59311e4aa
diff --git a/.github/workflows/ci-cli.yml b/.github/workflows/ci-cli.yml
index 8b119fcff952..ef0d6941a8a0 100644
--- a/.github/workflows/ci-cli.yml
+++ b/.github/workflows/ci-cli.yml
@@ -5,6 +5,16 @@ on:
pull_request:
paths:
- 'cli/**'
+ - 'services/mcp/src/cli/**'
+ - 'services/mcp/src/tools/**'
+ - 'services/mcp/src/api/**'
+ - 'services/mcp/schema/**'
+ - 'services/mcp/scripts/build-cli*.ts'
+ - 'services/mcp/scripts/hono-esbuild-config.ts'
+ - 'services/mcp/package.json'
+ - 'dist-workspace.toml'
+ - 'pnpm-lock.yaml'
+ - '.github/workflows/release.yml'
- '.github/workflows/ci-cli.yml'
- '.github/workflows/release-cli.yml'
@@ -73,3 +83,28 @@ jobs:
- name: Check formatting
run: cargo fmt --all -- --check
+
+ api-cli-release-bundle:
+ name: API CLI release bundle
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Setup pnpm
+ uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
+
+ - name: Setup Node.js
+ uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
+ with:
+ node-version-file: .nvmrc
+ cache: 'pnpm'
+
+ - name: Install API CLI dependencies
+ run: pnpm --filter '@posthog/mcp...' install --frozen-lockfile
+
+ - name: Build API CLI release bundle
+ run: pnpm --dir services/mcp run build:cli:release
+
+ - name: Verify API CLI release bundle
+ run: node -e "const { statSync } = require('node:fs'); if (statSync('cli/lib/posthog-api-cli.mjs').size <= 0) process.exit(1)"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 18d33bd9a009..62adcbc876ea 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -153,6 +153,19 @@ jobs:
- name: Install dependencies
run: |
${{ matrix.packages_install }}
+ - name: Setup pnpm
+ uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
+ - name: Setup Node.js
+ uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
+ with:
+ node-version-file: .nvmrc
+ cache: 'pnpm'
+ - name: Install API CLI dependencies
+ run: pnpm --filter '@posthog/mcp...' install --frozen-lockfile
+ - name: Build API CLI release bundle
+ run: pnpm --dir services/mcp run build:cli:release
+ - name: Verify API CLI release bundle
+ run: node -e "const { statSync } = require('node:fs'); if (statSync('cli/lib/posthog-api-cli.mjs').size <= 0) process.exit(1)"
- name: Build artifacts
run: |
# Actually do builds and make zips and whatnot
@@ -207,6 +220,19 @@ jobs:
pattern: artifacts-*
path: target/distrib/
merge-multiple: true
+ - name: Setup pnpm
+ uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
+ - name: Setup Node.js
+ uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
+ with:
+ node-version-file: .nvmrc
+ cache: 'pnpm'
+ - name: Install API CLI dependencies
+ run: pnpm --filter '@posthog/mcp...' install --frozen-lockfile
+ - name: Build API CLI release bundle
+ run: pnpm --dir services/mcp run build:cli:release
+ - name: Verify API CLI release bundle
+ run: node -e "const { statSync } = require('node:fs'); if (statSync('cli/lib/posthog-api-cli.mjs').size <= 0) process.exit(1)"
- id: cargo-dist
shell: bash
run: |
diff --git a/cli/CONTRIBUTING.md b/cli/CONTRIBUTING.md
index dd1d0cf42dc6..fccac3f83205 100644
--- a/cli/CONTRIBUTING.md
+++ b/cli/CONTRIBUTING.md
@@ -28,6 +28,14 @@ If you need to cut a release by hand, merge a CLI changeset to `master` and let
Do not push `posthog-cli/vX.Y.Z` tags manually; cargo-dist tag-push releases are disabled.
If cargo-dist fails after `Release CLI` commits the release bump, rerun the failed jobs from the same workflow run.
+The release workflow also builds `services/mcp` into `cli/lib/posthog-api-cli.mjs` before cargo-dist packages artifacts.
+This keeps `posthog-cli api` aligned with the generated MCP tool catalog at release time.
+To reproduce that release bundle locally, run:
+
+```bash
+pnpm --dir services/mcp run build:cli:release
+```
+
We release semi-regularly, as new features are added. If a release breaks your CI or workflow, please open an issue on GitHub, and tag one or all of the crate authors
## Running a local build
diff --git a/cli/README.md b/cli/README.md
index 87de37543a1d..7fe677ccffb6 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -55,3 +55,41 @@ Commands require different API scopes. Make sure to set these scopes on your per
| `exp endpoints push` | `endpoint:write`, `insight_variable:write` |
| `exp endpoints run` | `query:read` |
| `exp tasks` | `task:read` |
+
+## Agent-first API tools
+
+`posthog-cli api` exposes PostHog's MCP tool catalog through a shell-friendly interface for coding agents:
+
+```bash
+posthog-cli api --agent-help
+posthog-cli api search feature-flag
+posthog-cli api info feature-flag-get-all
+posthog-cli api schema query-trends series
+posthog-cli api call --json feature-flag-get-all '{"limit":5}'
+posthog-cli api call --dry-run feature-flags-bulk-delete-create '{"ids":[123]}'
+posthog-cli api skill list
+posthog-cli api skill install audit
+posthog-cli api agents-md install
+```
+
+Destructive tools require `--confirm` when executed. Use `--dry-run` before mutations.
+
+`posthog-cli api --agent-help` prints the full agent-facing guide — the same exec tool reference the PostHog MCP server serves, rewritten for CLI invocation — so agents can load it into context before interacting with PostHog APIs.
+
+### Agent steering instructions
+
+Install the PostHog CLI steering instructions into the agent instructions file for your project:
+
+```bash
+posthog-cli api agents-md install
+```
+
+By default this updates `AGENTS.md` in the current directory. If your agent reads a different instructions file, pass it explicitly:
+
+```bash
+posthog-cli api agents-md install --path path/to/AGENTS.md
+```
+
+The installed instructions come from the shared snippet at [`services/mcp/src/cli/agents-md-snippet.md`](../services/mcp/src/cli/agents-md-snippet.md), so the installer and this README point at the same source of truth.
+
+The snippet is written as a `<posthog>...</posthog>` block. Rerunning the install replaces the existing block in place, so upgrading the CLI and reinstalling refreshes stale instructions without duplicating them.
diff --git a/cli/lib/.gitignore b/cli/lib/.gitignore
new file mode 100644
index 000000000000..d6b7ef32c847
--- /dev/null
+++ b/cli/lib/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore
diff --git a/cli/src/api_proxy.rs b/cli/src/api_proxy.rs
new file mode 100644
index 000000000000..12c1689aa835
--- /dev/null
+++ b/cli/src/api_proxy.rs
@@ -0,0 +1,147 @@
+use std::env;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use anyhow::{bail, Context, Result};
+
+use crate::error::CapturedError;
+use crate::invocation_context::InvocationContext;
+
+const API_CLI_BUNDLE: &str = "posthog-api-cli.mjs";
+const ANALYTICS_HOST: &str = "https://us.i.posthog.com";
+
+fn canonicalize_file(path: &Path) -> Option<PathBuf> {
+ let resolved = path.canonicalize().ok()?;
+ if resolved.is_file() {
+ Some(resolved)
+ } else {
+ None
+ }
+}
+
+fn default_install_dir() -> Option<PathBuf> {
+ Some(dirs::home_dir()?.join(".posthog"))
+}
+
+fn find_script() -> Result<PathBuf> {
+ if let Some(path) = env::var_os("POSTHOG_API_CLI_PATH") {
+ if path.is_empty() {
+ bail!("POSTHOG_API_CLI_PATH is set but empty.");
+ }
+ let path = PathBuf::from(path);
+ let resolved = path.canonicalize().with_context(|| {
+ format!(
+ "POSTHOG_API_CLI_PATH is set to `{}`, but that file could not be found.",
+ path.display()
+ )
+ })?;
+ if !resolved.is_file() {
+ bail!(
+ "POSTHOG_API_CLI_PATH is set to `{}`, but it is not a file.",
+ resolved.display()
+ );
+ }
+ return Ok(resolved);
+ }
+
+ if let Some(install_dir) = default_install_dir() {
+ for candidate in [
+ install_dir.join("lib").join(API_CLI_BUNDLE),
+ install_dir.join("cli/lib").join(API_CLI_BUNDLE),
+ install_dir.join("api-cli").join(API_CLI_BUNDLE),
+ install_dir.join(API_CLI_BUNDLE),
+ ] {
+ if let Some(resolved) = canonicalize_file(&candidate) {
+ return Ok(resolved);
+ }
+ }
+ }
+
+ let development_bundle = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("lib")
+ .join(API_CLI_BUNDLE);
+ if let Some(resolved) = canonicalize_file(&development_bundle) {
+ return Ok(resolved);
+ }
+
+ bail!(
+ "Could not find the PostHog API CLI bundle. Reinstall posthog-cli, or set POSTHOG_API_CLI_PATH to a trusted bundle."
+ )
+}
+
+fn has_any_env(names: &[&str]) -> bool {
+ names.iter().any(|name| env::var(name).is_ok())
+}
+
+fn inject_credentials(cmd: &mut Command, invocation_context: Option<&InvocationContext>) {
+ let Some(invocation_context) = invocation_context else {
+ return;
+ };
+ let config = &invocation_context.config;
+
+ if !has_any_env(&[
+ "POSTHOG_API_KEY",
+ "POSTHOG_CLI_API_KEY",
+ "POSTHOG_CLI_TOKEN",
+ ]) {
+ cmd.env("POSTHOG_CLI_API_KEY", &config.api_key);
+ }
+
+ if !has_any_env(&[
+ "POSTHOG_PROJECT_ID",
+ "POSTHOG_CLI_PROJECT_ID",
+ "POSTHOG_CLI_ENV_ID",
+ ]) {
+ cmd.env("POSTHOG_CLI_PROJECT_ID", &config.env_id);
+ }
+
+ if !has_any_env(&["POSTHOG_HOST", "POSTHOG_CLI_HOST"]) {
+ cmd.env("POSTHOG_CLI_HOST", &config.host);
+ }
+}
+
+fn inject_analytics_env(cmd: &mut Command) {
+ if let Some(token) = option_env!("POSTHOG_API_TOKEN") {
+ if env::var_os("POSTHOG_ANALYTICS_API_KEY").is_none() {
+ cmd.env("POSTHOG_ANALYTICS_API_KEY", token);
+ }
+ if env::var_os("POSTHOG_ANALYTICS_HOST").is_none() {
+ cmd.env("POSTHOG_ANALYTICS_HOST", ANALYTICS_HOST);
+ }
+ }
+}
+
+pub fn run(
+ args: Vec<String>,
+ host_override: Option<String>,
+ invocation_context: Option<&InvocationContext>,
+) -> Result<(), CapturedError> {
+ let script = find_script().map_err(CapturedError::from)?;
+ let mut cmd = Command::new("node");
+ cmd.arg(script);
+ cmd.args(args);
+ cmd.env("POSTHOG_CLI_VERSION", env!("CARGO_PKG_VERSION"));
+
+ inject_credentials(&mut cmd, invocation_context);
+ inject_analytics_env(&mut cmd);
+
+ if let Some(host) = host_override {
+ cmd.env("POSTHOG_CLI_HOST", host);
+ }
+
+ let status = cmd
+ .status()
+ .with_context(|| {
+ format!(
+ "Failed to execute `{}`. Is Node.js installed?",
+ Path::new("node").display()
+ )
+ })
+ .map_err(CapturedError::from)?;
+
+ if !status.success() {
+ std::process::exit(status.code().unwrap_or(1));
+ }
+
+ Ok(())
+}
diff --git a/cli/src/commands.rs b/cli/src/commands.rs
index af10fe63f5ac..919e80089d89 100644
--- a/cli/src/commands.rs
+++ b/cli/src/commands.rs
@@ -2,9 +2,10 @@ use std::path::PathBuf;
use anyhow::Context;
use clap::{Parser, Subcommand};
-use tracing::{error, warn};
+use tracing::{debug, error, warn};
use crate::{
+ api_proxy,
download::SymbolSetsSubcommand,
dsym::DsymSubcommand,
error::CapturedError,
@@ -119,6 +120,32 @@ pub enum Commands {
#[command(subcommand)]
cmd: SymbolSetsSubcommand,
},
+
+ #[command(
+ about = "Agent-first PostHog API tools",
+ long_about = "Agent-first PostHog API tools.\n\n\
+ Exposes PostHog's MCP tool catalog through a shell-friendly interface so coding \
+ agents (and the humans driving them) can discover, inspect, and call PostHog API \
+ tools without loading every schema into context upfront.",
+ after_help = "Commands:\n \
+ tools List every available tool\n \
+ search <regex> Find tools by name, title, or description\n \
+ info [--json] <tool> Show a tool's description and input schema\n \
+ schema <tool> [field.path] Drill into a nested schema field\n \
+ call [--json] [--dry-run] [--confirm] <tool> '<json>' Execute a tool with JSON input\n \
+ skill list [--json] List installable PostHog agent skills\n \
+ skill install [--force] <skill-id> Install a skill into .agents/skills/\n \
+ agents-md install [--path AGENTS.md] Install the PostHog steering snippet\n\n\
+ Run `posthog-cli api --agent-help` for the full agent-facing usage guide.\n\n\
+ This command group is experimental: pass `--experimental` after `api`, or set \
+ POSTHOG_CLI_EXPERIMENTAL_API=1.\n\
+ Destructive tools require --confirm. Use --dry-run before mutations.",
+ trailing_var_arg = true
+ )]
+ Api {
+ #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
+ args: Vec<String>,
+ },
}
#[derive(Subcommand)]
@@ -221,6 +248,7 @@ impl Cli {
if !matches!(
self.command,
Commands::Login
+ | Commands::Api { .. }
| Commands::SymbolSets {
cmd: SymbolSetsSubcommand::Extract(_)
}
@@ -287,6 +315,21 @@ impl Cli {
crate::download::extract(&args)?;
}
},
+ 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
+ }
+ };
+ api_proxy::run(args, self.host, api_context)?;
+ }
Commands::Exp { cmd } => match cmd {
ExpCommand::Task {
cmd,
diff --git a/cli/src/lib.rs b/cli/src/lib.rs
index 3ea079dd8587..d58c83c5bafd 100644
--- a/cli/src/lib.rs
+++ b/cli/src/lib.rs
@@ -1,4 +1,5 @@
pub mod api;
+pub mod api_proxy;
pub mod commands;
pub mod download;
pub mod dsym;
diff --git a/dist-workspace.toml b/dist-workspace.toml
index 4f9eb8a7ebdb..e5c6cc5ed7c3 100644
--- a/dist-workspace.toml
+++ b/dist-workspace.toml
@@ -32,6 +32,8 @@ npm-scope = "@posthog"
# Publish jobs to run in CI
publish-jobs = ["npm"]
unix-archive = ".tar.gz"
+# Bundle the generated MCP-backed API CLI alongside every posthog-cli artifact.
+include = ["cli/lib"]
[dist.github-custom-runners]
# ubuntu-20.04 (the dist default) is now deprecated by github
diff --git a/services/mcp/package.json b/services/mcp/package.json
index 5e6fe49f3a50..e5d4fa0eb54f 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -24,6 +24,8 @@
"cf-typegen": "wrangler types",
"inspector": "npx @modelcontextprotocol/inspector npx -y mcp-remote@latest http://localhost:8787/mcp",
"build:hono": "tsx scripts/build-hono.ts",
+ "build:cli": "tsx scripts/build-cli.ts",
+ "build:cli:release": "tsx scripts/build-cli-release.ts",
"dev:hono": "tsx scripts/dev-hono.ts",
"test": "vitest",
"test:integration": "vitest run --config vitest.integration.config.mts",
diff --git a/services/mcp/scripts/build-cli-release.ts b/services/mcp/scripts/build-cli-release.ts
new file mode 100644
index 000000000000..3068e2f4e0c8
--- /dev/null
+++ b/services/mcp/scripts/build-cli-release.ts
@@ -0,0 +1,30 @@
+import { build } from 'esbuild'
+import { mkdir } from 'node:fs/promises'
+import { dirname, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import { cliEsbuildOptions } from './hono-esbuild-config'
+
+const scriptDir = dirname(fileURLToPath(import.meta.url))
+const mcpRoot = resolve(scriptDir, '..')
+const repoRoot = resolve(mcpRoot, '../..')
+const releaseOutfile = resolve(repoRoot, 'cli/lib/posthog-api-cli.mjs')
+
+process.chdir(mcpRoot)
+
+async function main(): Promise<void> {
+ await mkdir(dirname(releaseOutfile), { recursive: true })
+ await build(
+ cliEsbuildOptions({
+ outfile: releaseOutfile,
+ sourcemap: false,
+ })
+ )
+
+ console.info(`Built PostHog API CLI release bundle -> ${releaseOutfile}`)
+}
+
+main().catch((err: unknown) => {
+ console.error('Build failed:', err)
+ process.exit(1)
+})
diff --git a/services/mcp/scripts/build-cli.ts b/services/mcp/scripts/build-cli.ts
new file mode 100644
index 000000000000..00eb4512d44d
--- /dev/null
+++ b/services/mcp/scripts/build-cli.ts
@@ -0,0 +1,12 @@
+import { build } from 'esbuild'
+
+import { cliEsbuildOptions, cliOutfile } from './hono-esbuild-config'
+
+build(cliEsbuildOptions())
+ .then(() => {
+ console.info(`Built PostHog API CLI -> ${cliOutfile}`)
+ })
+ .catch((err: unknown) => {
+ console.error('Build failed:', err)
+ process.exit(1)
+ })
diff --git a/services/mcp/scripts/hono-esbuild-config.ts b/services/mcp/scripts/hono-esbuild-config.ts
index 276177c97680..2e7942660694 100644
--- a/services/mcp/scripts/hono-esbuild-config.ts
+++ b/services/mcp/scripts/hono-esbuild-config.ts
@@ -8,6 +8,14 @@ import type { BuildOptions, Plugin } from 'esbuild'
import { resolve } from 'path'
export const honoOutfile = resolve(process.cwd(), 'dist/hono-server.mjs')
+export const cliOutfile = resolve(process.cwd(), 'dist/posthog-api-cli.mjs')
+
+type HonoEsbuildOptions = {
+ dev?: boolean
+ extraPlugins?: Plugin[]
+ outfile?: string
+ sourcemap?: boolean
+}
const cfWorkersStub: Plugin = {
name: 'cf-workers-stub',
@@ -23,15 +31,15 @@ const cfWorkersStub: Plugin = {
},
}
-export function honoEsbuildOptions(opts: { dev?: boolean; extraPlugins?: Plugin[] } = {}): BuildOptions {
+export function honoEsbuildOptions(opts: HonoEsbuildOptions = {}): BuildOptions {
return {
entryPoints: [resolve(process.cwd(), 'src/hono/index.ts')],
bundle: true,
platform: 'node',
target: 'node22',
format: 'esm',
- outfile: honoOutfile,
- sourcemap: true,
+ outfile: opts.outfile ?? honoOutfile,
+ sourcemap: opts.sourcemap ?? true,
external: [],
plugins: [cfWorkersStub, ...(opts.extraPlugins ?? [])],
loader: { '.html': 'text', '.md': 'text', '.json': 'json' },
@@ -42,3 +50,11 @@ export function honoEsbuildOptions(opts: { dev?: boolean; extraPlugins?: Plugin[
banner: { js: `import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);` },
}
}
+
+export function cliEsbuildOptions(opts: HonoEsbuildOptions = {}): BuildOptions {
+ return {
+ ...honoEsbuildOptions(opts),
+ entryPoints: [resolve(process.cwd(), 'src/cli/index.ts')],
+ outfile: opts.outfile ?? cliOutfile,
+ }
+}
diff --git a/services/mcp/src/cli/agent-help.ts b/services/mcp/src/cli/agent-help.ts
new file mode 100644
index 000000000000..7db9cd82e4ec
--- /dev/null
+++ b/services/mcp/src/cli/agent-help.ts
@@ -0,0 +1,73 @@
+import type { QueryToolInfo, ToolInfo } from '@/lib/instructions'
+import { type InstructionsContext, InstructionsFormatter } from '@/lib/instructions-formatter'
+import { getToolDefinition } from '@/tools/toolDefinitions'
+import type { Tool, ZodObjectAny } from '@/tools/types'
+
+import { EXPERIMENTAL_API_ENV } from './experimental'
+
+const AGENT_HELP_HEADER = `# PostHog API guide for agents
+
+\`posthog-cli api\` is the agent-first interface to the PostHog API. It exposes the same tool surface as the PostHog MCP server's \`exec\` tool, so the reference below is the canonical guide for interacting with PostHog. Treat it as instructions to follow, not just documentation.
+
+The command group is experimental: pass \`--experimental\` right after \`api\`, or set \`${EXPERIMENTAL_API_ENV}=1\` in the environment.
+
+On top of the reference below, the CLI adds:
+
+- \`posthog-cli api call --dry-run <tool> '<json>'\` — validate input against the tool schema without executing. Use it before any mutation.
+- Destructive tools refuse to run without \`--confirm\`; add it only after verifying the exact target IDs.
+- \`posthog-cli api skill list\` and \`posthog-cli api skill install <skill-id>\` — install PostHog agent skills into \`.agents/skills/\`. Before starting a PostHog task, check the skill list for a match; if one exists, install it, read its \`SKILL.md\`, and follow it — skills contain task-specific workflows that individual tools do not.
+- \`posthog-cli api agents-md install [--path AGENTS.md]\` — install the PostHog steering snippet into a repository.`
+
+const EXEC_INVOCATION_PATTERN = /posthog:exec\(\{\s*"command":\s*"((?:\\.|[^"\\])*)"\s*\}\)/g
+
+function commandToCliInvocation(command: string): string {
+ const braceIndex = command.indexOf('{')
+ if (braceIndex === -1) {
+ return `posthog-cli api ${command}`
+ }
+ return `posthog-cli api ${command.slice(0, braceIndex).trimEnd()} '${command.slice(braceIndex)}'`
+}
+
+/** The MCP templates document the exec surface as \`posthog:exec({ "command": "<cmd>" })\`
+ * tool calls. The CLI exposes the identical command strings as \`posthog-cli api <cmd>\`,
+ * so rewriting invocations (instead of forking the templates) keeps one source of truth. */
+export function toCliSyntax(text: string): string {
+ return text
+ .replace(EXEC_INVOCATION_PATTERN, (_match, command: string) =>
+ commandToCliInvocation(command.replace(/\\"/g, '"'))
+ )
+ .replace('### Using the `posthog` tool', '### Using `posthog-cli api`')
+ .replace(
+ 'Pass CLI-style commands in the `command` parameter for all PostHog interactions.',
+ 'Pass CLI-style commands as arguments to `posthog-cli api` for all PostHog interactions.'
+ )
+}
+
+/** Build the full agent-facing guide for \`posthog-cli api --agent-help\` from the same
+ * exec-tool templates the MCP server serves, including the tool-domain index and the
+ * query-tool catalog derived from the bundled tool registry (no network or auth needed). */
+export function buildAgentHelp(tools: Tool<ZodObjectAny>[]): string {
+ const formatter = new InstructionsFormatter()
+ const toolInfos: ToolInfo[] = tools.map((tool) => ({
+ name: tool.name,
+ category: getToolDefinition(tool.name).category,
+ }))
+ const queryTools: QueryToolInfo[] = tools
+ .filter((tool) => tool.name.startsWith('query-'))
+ .map((tool) => {
+ const definition = getToolDefinition(tool.name)
+ return {
+ name: tool.name,
+ title: definition.title,
+ ...(definition.system_prompt_hint ? { systemPromptHint: definition.system_prompt_hint } : {}),
+ } as QueryToolInfo
+ })
+
+ const ctx: InstructionsContext = { guidelines: '', tools: toolInfos, queryTools }
+ const sections = [
+ AGENT_HELP_HEADER,
+ formatter.buildExecToolDescription(),
+ formatter.buildExecCommandReference(ctx, { stripEnvContext: false }),
+ ]
+ return toCliSyntax(sections.join('\n\n'))
+}
diff --git a/services/mcp/src/cli/agents-md-snippet.md b/services/mcp/src/cli/agents-md-snippet.md
new file mode 100644
index 000000000000..518c5a1e25cd
--- /dev/null
+++ b/services/mcp/src/cli/agents-md-snippet.md
@@ -0,0 +1,9 @@
+## PostHog
+
+Use `posthog-cli api` for all PostHog-related queries and operations. You should use `posthog-cli api` over direct MCP tool calls whenever the CLI is available. If `posthog-cli` is not installed, run it with `npx -y @posthog/cli@latest` instead (for example `npx -y @posthog/cli@latest api search feature-flag`).
+
+The `posthog-cli api` command group is experimental. If it reports that the command group is disabled, rerun commands with `POSTHOG_CLI_EXPERIMENTAL_API=1` in the environment or pass `--experimental` immediately after `api`.
+
+Before your first PostHog command in a session, run `posthog-cli api --agent-help` and load its full output into your context. It prints the complete agent guide — command reference, schema drill-down rules, data discovery workflow, and the tool index — for interacting with PostHog APIs. Treat that output as instructions to follow, not just documentation.
+
+Before starting a PostHog task, run `posthog-cli api skill list` and check for a skill matching the task. If one matches, install it with `posthog-cli api skill install <skill-id>` (add `--force` to refresh an already-installed skill), then read `.agents/skills/<skill-id>/SKILL.md` and follow it. Skills contain task-specific workflows that individual tools do not.
diff --git a/services/mcp/src/cli/agents-md.ts b/services/mcp/src/cli/agents-md.ts
new file mode 100644
index 000000000000..4f042fb953d2
--- /dev/null
+++ b/services/mcp/src/cli/agents-md.ts
@@ -0,0 +1,40 @@
+import * as fs from 'node:fs/promises'
+import * as path from 'node:path'
+
+import agentsMdPrompt from './agents-md-snippet.md'
+import { errorCode } from './utils'
+
+const OPEN_TAG = '<posthog>'
+const CLOSE_TAG = '</posthog>'
+
+export const AGENTS_MD_PROMPT = agentsMdPrompt.trim()
+/** The installed block is wrapped in XML tags so agents see a clearly delimited
+ * section and reinstalls can replace stale content in place. */
+export const AGENTS_MD_SNIPPET = `${OPEN_TAG}\n${AGENTS_MD_PROMPT}\n${CLOSE_TAG}`
+
+const MANAGED_BLOCK_PATTERN = /<posthog>[\s\S]*?<\/posthog>/
+
+export async function installAgentsMdSnippet(opts: { cwd?: string; filePath?: string } = {}): Promise<string> {
+ const targetPath = path.resolve(opts.filePath ?? path.join(opts.cwd ?? process.cwd(), 'AGENTS.md'))
+ let existing = ''
+ try {
+ existing = await fs.readFile(targetPath, 'utf-8')
+ } catch (error) {
+ if (errorCode(error) !== 'ENOENT') {
+ throw error
+ }
+ }
+
+ let next: string
+ if (MANAGED_BLOCK_PATTERN.test(existing)) {
+ next = existing.replace(MANAGED_BLOCK_PATTERN, () => AGENTS_MD_SNIPPET)
+ } else if (existing.trim()) {
+ next = `${existing.trimEnd()}\n\n${AGENTS_MD_SNIPPET}\n`
+ } else {
+ next = `${AGENTS_MD_SNIPPET}\n`
+ }
+
+ await fs.mkdir(path.dirname(targetPath), { recursive: true })
+ await fs.writeFile(targetPath, next)
+ return targetPath
+}
diff --git a/services/mcp/src/cli/args.ts b/services/mcp/src/cli/args.ts
new file mode 100644
index 000000000000..38dca641c2ce
--- /dev/null
+++ b/services/mcp/src/cli/args.ts
@@ -0,0 +1,14 @@
+export function takeOption(args: string[], flag: string): string | undefined {
+ const index = args.indexOf(flag)
+ if (index === -1) {
+ return undefined
+ }
+
+ const value = args[index + 1]
+ if (value === undefined || value.startsWith('--')) {
+ throw new Error(`Missing value for ${flag}`)
+ }
+
+ args.splice(index, 2)
+ return value
+}
diff --git a/services/mcp/src/cli/config.ts b/services/mcp/src/cli/config.ts
new file mode 100644
index 000000000000..370c3a1d1c02
--- /dev/null
+++ b/services/mcp/src/cli/config.ts
@@ -0,0 +1,50 @@
+export interface CliConfig {
+ apiKey?: string
+ host: string
+ organizationId?: string
+ projectId?: string
+ version: number
+}
+
+const DEFAULT_HOST = 'https://us.posthog.com'
+
+function firstEnv(names: string[]): string | undefined {
+ for (const name of names) {
+ const value = process.env[name]
+ if (value) {
+ return value
+ }
+ }
+ return undefined
+}
+
+function parseVersion(value: string | undefined): number {
+ if (!value) {
+ return 2
+ }
+ const parsed = Number(value)
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 2
+}
+
+export function resolveCliConfig(): CliConfig {
+ const apiKey = firstEnv(['POSTHOG_API_KEY', 'POSTHOG_CLI_API_KEY', 'POSTHOG_CLI_TOKEN'])
+ const organizationId = firstEnv(['POSTHOG_ORGANIZATION_ID', 'POSTHOG_CLI_ORGANIZATION_ID'])
+ const projectId = firstEnv(['POSTHOG_PROJECT_ID', 'POSTHOG_CLI_PROJECT_ID', 'POSTHOG_CLI_ENV_ID'])
+
+ return {
+ host: firstEnv(['POSTHOG_HOST', 'POSTHOG_CLI_HOST']) ?? DEFAULT_HOST,
+ version: parseVersion(firstEnv(['POSTHOG_MCP_VERSION', 'POSTHOG_CLI_MCP_VERSION'])),
+ ...(apiKey ? { apiKey } : {}),
+ ...(organizationId ? { organizationId } : {}),
+ ...(projectId ? { projectId } : {}),
+ }
+}
+
+export function requireApiKey(config: CliConfig): string {
+ if (!config.apiKey) {
+ throw new Error(
+ 'Missing PostHog API key. Run `posthog-cli login` or set POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID.'
+ )
+ }
+ return config.apiKey
+}
diff --git a/services/mcp/src/cli/context.ts b/services/mcp/src/cli/context.ts
new file mode 100644
index 000000000000..a65c073ab693
--- /dev/null
+++ b/services/mcp/src/cli/context.ts
@@ -0,0 +1,78 @@
+import { createHash, randomUUID } from 'node:crypto'
+
+import { ApiClient } from '@/api/client'
+import { MemoryCache } from '@/lib/cache/MemoryCache'
+import { getPostHogClient } from '@/lib/posthog'
+import { buildMCPAnalyticsGroups, buildMCPContextProperties } from '@/lib/posthog/analytics'
+import type { AnalyticsEvent } from '@/lib/posthog/analytics'
+import { SessionManager } from '@/lib/SessionManager'
+import { StateManager } from '@/lib/StateManager'
+import type { Context, Env, State } from '@/tools/types'
+
+import type { CliConfig } from './config'
+
+function cliIdentityKey(apiKey: string | undefined): string {
+ if (!apiKey) {
+ return 'anonymous'
+ }
+ return createHash('sha256').update(apiKey).digest('hex').slice(0, 16)
+}
+
+export async function buildCliContext(config: CliConfig): Promise<Context> {
+ const identityKey = cliIdentityKey(config.apiKey)
+ const fallbackDistinctId = `posthog-cli:${identityKey}`
+ const cache = new MemoryCache<State>(`cli:${identityKey}:${config.host}`)
+ await cache.setMany({
+ ...(config.organizationId ? { orgId: config.organizationId } : {}),
+ ...(config.projectId ? { projectId: config.projectId } : {}),
+ })
+
+ const api = new ApiClient({
+ apiToken: config.apiKey ?? '',
+ baseUrl: config.host.replace(/\/+$/, ''),
+ clientUserAgent: `posthog-cli api`,
+ mcpClientName: 'posthog-cli',
+ mcpClientVersion: process.env.POSTHOG_CLI_VERSION,
+ mcpConsumer: 'posthog-cli',
+ })
+ const stateManager = new StateManager(cache, api)
+ const sessionManager = new SessionManager(cache)
+ const sessionId = randomUUID()
+
+ const context: Context = {
+ api,
+ cache,
+ env: process.env as Env,
+ stateManager,
+ sessionManager,
+ getDistinctId: () => stateManager.getDistinctId(),
+ trackEvent: async (event: AnalyticsEvent, properties: Record<string, unknown> = {}) => {
+ try {
+ const [distinctId, analyticsContext] = await Promise.all([
+ stateManager.getDistinctId().catch(() => undefined),
+ stateManager.getAnalyticsContext().catch(() => undefined),
+ ])
+ const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}
+
+ getPostHogClient().capture({
+ distinctId: distinctId ?? fallbackDistinctId,
+ event,
+ ...(Object.keys(groups).length > 0 ? { groups } : {}),
+ properties: {
+ $ai_product: 'mcp',
+ $mcp_source: 'posthog_cli',
+ $mcp_client_name: 'posthog-cli',
+ $mcp_consumer: 'posthog-cli',
+ $mcp_mode: 'cli',
+ $mcp_version: config.version,
+ ...(analyticsContext ? buildMCPContextProperties(analyticsContext) : {}),
+ $session_id: await sessionManager.getSessionUuid(sessionId),
+ ...properties,
+ },
+ })
+ } catch {}
+ },
+ }
+
+ return context
+}
diff --git a/services/mcp/src/cli/experimental.ts b/services/mcp/src/cli/experimental.ts
new file mode 100644
index 000000000000..75e921897f84
--- /dev/null
+++ b/services/mcp/src/cli/experimental.ts
@@ -0,0 +1,18 @@
+export const EXPERIMENTAL_API_ENV = 'POSTHOG_CLI_EXPERIMENTAL_API'
+
+const ENABLED_VALUES = new Set(['1', 'true', 'yes', 'on'])
+
+export function isExperimentalApiEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
+ const value = env[EXPERIMENTAL_API_ENV]
+ return value ? ENABLED_VALUES.has(value.toLowerCase()) : false
+}
+
+export function requireExperimentalApiEnabled(opts: { flagEnabled?: boolean; env?: NodeJS.ProcessEnv } = {}): void {
+ if (opts.flagEnabled || isExperimentalApiEnabled(opts.env)) {
+ return
+ }
+
+ throw new Error(
+ `The \`posthog-cli api\` command group is experimental. Set ${EXPERIMENTAL_API_ENV}=1 or pass --experimental to use it.`
+ )
+}
diff --git a/services/mcp/src/cli/index.ts b/services/mcp/src/cli/index.ts
new file mode 100644
index 000000000000..5fe8215367a3
--- /dev/null
+++ b/services/mcp/src/cli/index.ts
@@ -0,0 +1,257 @@
+#!/usr/bin/env node
+import { AnalyticsEvent } from '@/lib/posthog/analytics'
+import { createExecTool } from '@/tools/exec'
+import type { Context, Tool, ZodObjectAny } from '@/tools/types'
+
+import { buildAgentHelp } from './agent-help'
+import { installAgentsMdSnippet } from './agents-md'
+import { takeOption } from './args'
+import type { CliConfig } from './config'
+import { resolveCliConfig, requireApiKey } from './config'
+import { buildCliContext } from './context'
+import { EXPERIMENTAL_API_ENV, requireExperimentalApiEnabled } from './experimental'
+import { installSkill, listSkills } from './skills'
+import { getCliTools } from './tools'
+
+const COMMAND_REFERENCE = `CLI-style command string. Supported commands:
+tools
+search <regex_pattern>
+info [--json] <tool_name>
+schema <tool_name> [field_path]
+call [--json] [--confirm] <tool_name> <json_input>`
+
+interface BuiltExec {
+ config: CliConfig
+ context: Context
+ execTool: Tool<ZodObjectAny>
+ tools: Tool<ZodObjectAny>[]
+}
+
+function usage(): string {
+ return `PostHog agent CLI
+
+Usage:
+ posthog-cli api --experimental <command>
+ posthog-cli api --agent-help
+ posthog-cli api tools
+ posthog-cli api search <regex>
+ posthog-cli api info [--json] <tool>
+ posthog-cli api schema <tool> [field.path]
+ posthog-cli api call [--json] [--dry-run] [--confirm] <tool> '<json>'
+ posthog-cli api skill list [--json]
+ posthog-cli api skill install [--force] <skill-id>
+ posthog-cli api agents-md install [--path AGENTS.md]
+
+Experimental: set ${EXPERIMENTAL_API_ENV}=1 or pass --experimental to enable this command group.
+Destructive tools require --confirm when executed. Use --dry-run before mutations.
+Agents: run \`posthog-cli api --agent-help\` and load the output into context before anything else.`
+}
+
+function takeFlag(args: string[], flag: string): boolean {
+ const index = args.indexOf(flag)
+ if (index === -1) {
+ return false
+ }
+ args.splice(index, 1)
+ return true
+}
+
+function printResult(result: unknown): void {
+ if (typeof result === 'string') {
+ process.stdout.write(result.endsWith('\n') ? result : `${result}\n`)
+ return
+ }
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)
+}
+
+async function buildExec(config: CliConfig = resolveCliConfig()): Promise<BuiltExec> {
+ const context = await buildCliContext(config)
+ const aiConsentGiven = await context.stateManager.getAiConsentGiven()
+ const tools = getCliTools({ aiConsentGiven })
+ const execTool = createExecTool(
+ tools,
+ context,
+ 'Execute a PostHog CLI command',
+ COMMAND_REFERENCE,
+ 'posthog-cli',
+ (toolName, properties) => {
+ void context.trackEvent(AnalyticsEvent.MCP_TOOL_CALL, {
+ tool_name: toolName,
+ $mcp_tool_name: toolName,
+ $mcp_duration_ms: properties.duration_ms,
+ $mcp_is_error: !properties.success,
+ output_format: properties.output_format,
+ ...(properties.error_message ? { error_message: properties.error_message } : {}),
+ })
+ },
+ [],
+ { requireDestructiveConfirmation: true }
+ )
+
+ return { config, 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 }))
+}
+
+async function runExecCommand(command: string): Promise<void> {
+ const config = resolveCliConfig()
+ if (command.startsWith('call ')) {
+ requireApiKey(config)
+ }
+ const { execTool, context } = await buildExec(config)
+ const result = await execTool.handler(context, { command })
+ printResult(result)
+}
+
+async function runDryCall(args: string[]): Promise<void> {
+ const forceJson = takeFlag(args, '--json')
+ const confirmed = takeFlag(args, '--confirm')
+ const toolName = args.shift()
+ const jsonBody = args.length > 0 ? args.join(' ') : '{}'
+ if (!toolName) {
+ throw new Error('Usage: posthog-cli api call --dry-run [--json] [--confirm] <tool> <json>')
+ }
+
+ const { tools } = await buildExec()
+ const tool = tools.find((candidate) => candidate.name === toolName)
+ if (!tool) {
+ throw new Error(`Unknown tool: "${toolName}". Run "posthog-cli api search <term>".`)
+ }
+
+ let parsed: Record<string, unknown>
+ try {
+ parsed = jsonBody ? (JSON.parse(jsonBody) as Record<string, unknown>) : {}
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error)
+ throw new Error(`Invalid JSON input: ${detail}`)
+ }
+
+ const validation = tool.schema.safeParse(parsed)
+ printResult({
+ dryRun: true,
+ tool: tool.name,
+ title: tool.title,
+ annotations: tool.annotations,
+ outputFormat: forceJson ? 'json' : 'text',
+ destructiveConfirmationRequired: tool.annotations.destructiveHint && !confirmed,
+ valid: validation.success,
+ ...(validation.success ? { input: validation.data } : { error: validation.error.message }),
+ })
+}
+
+async function runSkillCommand(args: string[]): Promise<void> {
+ const subcommand = args.shift()
+ switch (subcommand) {
+ case 'list': {
+ const json = takeFlag(args, '--json')
+ const skills = await listSkills()
+ if (json) {
+ printResult(skills)
+ return
+ }
+ for (const skill of skills) {
+ process.stdout.write(`${skill.id}\t${skill.name}\n`)
+ }
+ return
+ }
+ case 'install': {
+ const force = takeFlag(args, '--force')
+ const skillId = args.shift()
+ if (!skillId) {
+ throw new Error('Usage: posthog-cli api skill install [--force] <skill-id>')
+ }
+ printResult(await installSkill(skillId, { force }))
+ return
+ }
+ default:
+ throw new Error('Usage: posthog-cli api skill list|install')
+ }
+}
+
+async function runAgentsMdCommand(args: string[]): Promise<void> {
+ const subcommand = args.shift()
+ if (subcommand !== 'install') {
+ throw new Error('Usage: posthog-cli api agents-md install [--path AGENTS.md]')
+ }
+ const filePath = takeOption(args, '--path')
+ const installedPath = await installAgentsMdSnippet(filePath ? { filePath } : {})
+ printResult({ installed: true, path: installedPath })
+}
+
+async function main(): Promise<void> {
+ const args = process.argv.slice(2)
+ const experimental = takeFlag(args, '--experimental')
+ const command = args.shift()
+
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
+ process.stdout.write(`${usage()}\n`)
+ return
+ }
+
+ if (command === 'agent-help' || command === '--agent-help') {
+ process.stdout.write(`${await buildAgentHelpForConfig()}\n`)
+ return
+ }
+
+ requireExperimentalApiEnabled({ flagEnabled: experimental })
+
+ switch (command) {
+ case 'tools':
+ await runExecCommand('tools')
+ return
+ case 'search':
+ await runExecCommand(`search ${args.join(' ')}`)
+ return
+ case 'info': {
+ const json = takeFlag(args, '--json')
+ const toolName = args.shift()
+ if (!toolName) {
+ throw new Error('Usage: posthog-cli api info [--json] <tool>')
+ }
+ await runExecCommand(`info ${json ? '--json ' : ''}${toolName}`)
+ return
+ }
+ case 'schema': {
+ const toolName = args.shift()
+ if (!toolName) {
+ throw new Error('Usage: posthog-cli api schema <tool> [field.path]')
+ }
+ await runExecCommand(`schema ${toolName}${args[0] ? ` ${args[0]}` : ''}`)
+ return
+ }
+ case 'call': {
+ const dryRun = takeFlag(args, '--dry-run')
+ if (dryRun) {
+ await runDryCall(args)
+ return
+ }
+ const json = takeFlag(args, '--json')
+ const confirmed = takeFlag(args, '--confirm')
+ const toolName = args.shift()
+ const jsonBody = args.length > 0 ? args.join(' ') : '{}'
+ if (!toolName) {
+ throw new Error('Usage: posthog-cli api call [--json] [--dry-run] [--confirm] <tool> <json>')
+ }
+ await runExecCommand(`call ${json ? '--json ' : ''}${confirmed ? '--confirm ' : ''}${toolName} ${jsonBody}`)
+ return
+ }
+ case 'skill':
+ await runSkillCommand(args)
+ return
+ case 'agents-md':
+ await runAgentsMdCommand(args)
+ return
+ default:
+ throw new Error(`Unknown command "${command}".\n\n${usage()}`)
+ }
+}
+
+main().catch((error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error)
+ process.stderr.write(`Error: ${message}\n`)
+ process.exit(1)
+})
diff --git a/services/mcp/src/cli/skills.ts b/services/mcp/src/cli/skills.ts
new file mode 100644
index 000000000000..61a383bda748
--- /dev/null
+++ b/services/mcp/src/cli/skills.ts
@@ -0,0 +1,111 @@
+import { unzipSync } from 'fflate'
+import * as fs from 'node:fs/promises'
+import * as path from 'node:path'
+
+import { fetchContextMillResources, filterValidEntries, loadManifestFromArchive } from '@/resources/internals'
+import type { ContextMillResource } from '@/resources/manifest-types'
+
+import { errorCode } from './utils'
+
+export interface SkillListItem {
+ id: string
+ name: string
+ description: string
+ tags: string[]
+}
+
+export interface SkillInstallResult {
+ id: string
+ directory: string
+ fileCount: number
+}
+
+async function loadSkills(): Promise<{ archive: ReturnType<typeof unzipSync>; entries: ContextMillResource[] }> {
+ const archive = await fetchContextMillResources(process.env.POSTHOG_MCP_LOCAL_SKILLS_URL)
+ const manifest = loadManifestFromArchive(archive)
+ return { archive, entries: filterValidEntries(manifest.resources, archive) }
+}
+
+export async function listSkills(): Promise<SkillListItem[]> {
+ const { entries } = await loadSkills()
+ return entries
+ .map((entry) => ({
+ id: entry.id,
+ name: entry.name,
+ description: typeof entry.description === 'string' ? entry.description : entry.resource.description,
+ tags: Array.isArray(entry.tags) ? entry.tags.filter((tag): tag is string => typeof tag === 'string') : [],
+ }))
+ .sort((a, b) => a.id.localeCompare(b.id))
+}
+
+function targetSkillDirectory(targetRoot: string, skillId: string): string {
+ assertSafeSkillId(skillId)
+ const skillsRoot = path.resolve(targetRoot, '.agents', 'skills')
+ const destinationRoot = path.resolve(skillsRoot, skillId)
+ assertSafeDestination(skillsRoot, destinationRoot)
+ return destinationRoot
+}
+
+function assertSafeDestination(root: string, destination: string): void {
+ const normalizedRoot = path.resolve(root)
+ const normalizedDestination = path.resolve(destination)
+ if (normalizedDestination !== normalizedRoot && !normalizedDestination.startsWith(normalizedRoot + path.sep)) {
+ throw new Error(`Refusing to write outside ${normalizedRoot}: ${normalizedDestination}`)
+ }
+}
+
+function assertSafeSkillId(skillId: string): void {
+ if (!skillId || skillId.includes('..') || /[/\\]/.test(skillId)) {
+ throw new Error(`Invalid skill ID "${skillId}": must not contain path separators or traversal sequences.`)
+ }
+}
+
+export async function installSkill(
+ skillId: string,
+ opts: { cwd?: string; force?: boolean } = {}
+): Promise<SkillInstallResult> {
+ const cwd = opts.cwd ?? process.cwd()
+ const { archive, entries } = await loadSkills()
+ const entry = entries.find((candidate) => candidate.id === skillId)
+ if (!entry) {
+ throw new Error(`Unknown skill "${skillId}". Run "posthog-cli api skill list" to see available skills.`)
+ }
+ if (!entry.file) {
+ throw new Error(`Skill "${skillId}" has no downloadable archive.`)
+ }
+
+ const skillBytes = archive[entry.file]
+ if (!skillBytes) {
+ throw new Error(`Skill archive "${entry.file}" was not found.`)
+ }
+
+ const destinationRoot = targetSkillDirectory(cwd, skillId)
+ try {
+ await fs.access(destinationRoot)
+ if (!opts.force) {
+ throw new Error(`Skill "${skillId}" is already installed at ${destinationRoot}. Use --force to replace it.`)
+ }
+ await fs.rm(destinationRoot, { recursive: true, force: true })
+ } catch (error) {
+ if (errorCode(error) !== 'ENOENT') {
+ throw error
+ }
+ }
+
+ await fs.mkdir(destinationRoot, { recursive: true })
+ const skillArchive = unzipSync(skillBytes)
+ let fileCount = 0
+
+ for (const [fileName, bytes] of Object.entries(skillArchive)) {
+ if (fileName.endsWith('/')) {
+ continue
+ }
+ const destination = path.resolve(destinationRoot, fileName)
+ assertSafeDestination(destinationRoot, destination)
+ await fs.mkdir(path.dirname(destination), { recursive: true })
+ await fs.writeFile(destination, Buffer.from(bytes))
+ fileCount += 1
+ }
+
+ return { id: skillId, directory: destinationRoot, fileCount }
+}
diff --git a/services/mcp/src/cli/tools.ts b/services/mcp/src/cli/tools.ts
new file mode 100644
index 000000000000..32f4c7722792
--- /dev/null
+++ b/services/mcp/src/cli/tools.ts
@@ -0,0 +1,63 @@
+import { TOOL_MAP } from '@/tools'
+import { GENERATED_TOOL_MAP } from '@/tools/generated'
+import { type ToolDefinition, getToolDefinition, getToolsForFeatures } from '@/tools/toolDefinitions'
+import type { Tool, ToolBase, ZodObjectAny } from '@/tools/types'
+
+interface CliToolOptions {
+ aiConsentGiven?: boolean | undefined
+}
+
+const warnedSkippedTools = new Set<string>()
+
+function materializeTool(
+ name: string,
+ factory: () => ToolBase<ZodObjectAny>,
+ definition: ToolDefinition
+): Tool<ZodObjectAny> {
+ return {
+ ...factory(),
+ title: definition.title,
+ description: definition.description,
+ scopes: definition.required_scopes ?? [],
+ annotations: definition.annotations,
+ }
+}
+
+function warnSkippedTool(name: string, reason: unknown): void {
+ const detail = reason instanceof Error ? reason.message : String(reason)
+ const warningKey = `${name}:${detail}`
+ if (warnedSkippedTools.has(warningKey)) {
+ return
+ }
+ warnedSkippedTools.add(warningKey)
+ process.stderr.write(`Warning: Skipping PostHog API tool "${name}": ${detail}\n`)
+}
+
+export function getCliTools(options: CliToolOptions = {}): Tool<ZodObjectAny>[] {
+ const factories: Record<string, () => ToolBase<ZodObjectAny>> = {
+ ...TOOL_MAP,
+ ...GENERATED_TOOL_MAP,
+ }
+ const names = getToolsForFeatures({
+ aiConsentGiven: options.aiConsentGiven,
+ })
+
+ const tools: Tool<ZodObjectAny>[] = []
+ for (const name of names) {
+ const factory = factories[name]
+ if (!factory) {
+ warnSkippedTool(name, 'no implementation factory was registered')
+ continue
+ }
+
+ try {
+ const definition = getToolDefinition(name)
+ tools.push(materializeTool(name, () => factory(), definition))
+ } catch (error) {
+ warnSkippedTool(name, error)
+ continue
+ }
+ }
+
+ return tools.sort((a, b) => a.name.localeCompare(b.name))
+}
diff --git a/services/mcp/src/cli/utils.ts b/services/mcp/src/cli/utils.ts
new file mode 100644
index 000000000000..7973969defdd
--- /dev/null
+++ b/services/mcp/src/cli/utils.ts
@@ -0,0 +1,5 @@
+export function errorCode(error: unknown): unknown {
+ return typeof error === 'object' && error !== null && 'code' in error
+ ? (error as { code?: unknown }).code
+ : undefined
+}
diff --git a/services/mcp/src/templates/sections/cli-syntax.md b/services/mcp/src/templates/sections/cli-syntax.md
index ef5b500827f6..a271537b6798 100644
--- a/services/mcp/src/templates/sections/cli-syntax.md
+++ b/services/mcp/src/templates/sections/cli-syntax.md
@@ -5,7 +5,7 @@ tools — list available tool names
search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)
info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.
schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)
-call [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)
+call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts. --confirm is required by the CLI for destructive tools.)
```
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 863770eb9b86..c2d74ad34857 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -40,6 +40,10 @@ export interface ExecInnerCallProperties {
export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void
+export interface ExecToolOptions {
+ requireDestructiveConfirmation?: boolean
+}
+
function makeExecSchema(commandReference: string): z.ZodObject<{ command: z.ZodString }> {
return z.object({
command: z.string().describe(commandReference),
@@ -55,6 +59,29 @@ function parseCommand(input: string): { verb: string; rest: string } {
return { verb: trimmed.slice(0, idx), rest: trimmed.slice(idx + 1).trim() }
}
+function parseCallFlags(input: string): { forceJson: boolean; confirmed: boolean; rest: string } {
+ let rest = input.trim()
+ let forceJson = false
+ let confirmed = false
+
+ while (rest) {
+ const parsed = parseCommand(rest)
+ if (parsed.verb === '--json') {
+ forceJson = true
+ rest = parsed.rest
+ continue
+ }
+ if (parsed.verb === '--confirm') {
+ confirmed = true
+ rest = parsed.rest
+ continue
+ }
+ break
+ }
+
+ return { forceJson, confirmed, rest }
+}
+
// Extracts the inner tool name from an exec `call` command, e.g.
// "call my-tool {...}" → "my-tool". Returns undefined for other verbs or
// malformed input. Used by analytics to surface the real tool being invoked
@@ -64,11 +91,11 @@ export function parseExecCallInnerToolName(command: string): string | undefined
if (verb !== 'call' || !rest) {
return
}
- const argv = rest.startsWith('--json ') ? rest.slice('--json '.length).trim() : rest === '--json' ? '' : rest
- if (!argv) {
+ const callArgs = parseCallFlags(rest).rest
+ if (!callArgs) {
return
}
- const innerName = parseCommand(argv).verb
+ const innerName = parseCommand(callArgs).verb
return innerName || undefined
}
@@ -165,7 +192,8 @@ export function createExecTool(
commandReference: string,
mcpConsumer: string | undefined,
trackInnerCall?: ExecInnerCallTracker,
- scopeGatedTools: ScopeGatedTool[] = []
+ scopeGatedTools: ScopeGatedTool[] = [],
+ options: ExecToolOptions = {}
): Tool<ExecSchema> {
const ExecSchema = makeExecSchema(commandReference)
@@ -316,15 +344,19 @@ export function createExecTool(
case 'call': {
if (!rest) {
- throw new Error('Usage: call [--json] <tool_name> <json_input>')
+ throw new Error('Usage: call [--json] [--confirm] <tool_name> <json_input>')
}
- const forceJson = rest.startsWith('--json ') || rest === '--json'
- const callArgs = forceJson ? rest.slice('--json'.length).trim() : rest
+ const { forceJson, confirmed, rest: callArgs } = parseCallFlags(rest)
if (!callArgs) {
- throw new Error('Usage: call [--json] <tool_name> <json_input>')
+ throw new Error('Usage: call [--json] [--confirm] <tool_name> <json_input>')
}
const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)
const tool = findTool(allTools, toolName)
+ if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {
+ throw new Error(
+ `Tool "${tool.name}" is destructive. Re-run with "call --confirm ${tool.name} ..." after verifying the target IDs. Use "info ${tool.name}" to inspect the tool first.`
+ )
+ }
let input: Record<string, unknown>
if (!jsonBody) {
input = {}
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index 485a5e03a3af..31d0c96a52a7 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -5,7 +5,7 @@ tools — list available tool names
search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)
info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.
schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)
-call [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)
+call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts. --confirm is required by the CLI for destructive tools.)
```
**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.
diff --git a/services/mcp/tests/unit/cli-agent-help.test.ts b/services/mcp/tests/unit/cli-agent-help.test.ts
new file mode 100644
index 000000000000..e2730dd01918
--- /dev/null
+++ b/services/mcp/tests/unit/cli-agent-help.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest'
+
+import { buildAgentHelp, toCliSyntax } from '@/cli/agent-help'
+import { getCliTools } from '@/cli/tools'
+
+describe('CLI agent help', () => {
+ it('rewrites exec invocations to CLI syntax', () => {
+ expect(toCliSyntax('posthog:exec({ "command": "search dashboard" })')).toBe('posthog-cli api search dashboard')
+ expect(toCliSyntax('posthog:exec({ "command": "tools" })')).toBe('posthog-cli api tools')
+ })
+
+ it('quotes JSON payloads and unescapes embedded quotes', () => {
+ expect(
+ toCliSyntax(
+ 'posthog:exec({ "command": "call read-data-schema {\\"query\\": {\\"kind\\": \\"events\\"}}" })'
+ )
+ ).toBe(`posthog-cli api call read-data-schema '{"query": {"kind": "events"}}'`)
+ })
+
+ it('builds the agent guide from the MCP exec templates', () => {
+ const help = buildAgentHelp(getCliTools())
+
+ expect(help).toContain('posthog-cli api info <tool_name>')
+ expect(help).toContain('SCHEMA DRILL-DOWN RULE')
+ expect(help).not.toContain('posthog:exec(')
+ expect(help).toContain('POSTHOG_CLI_EXPERIMENTAL_API')
+ // Tool-domain index and query-tool catalog come from the bundled registry.
+ expect(help).toContain('query-trends')
+ })
+
+ it('does not require credentials to build', () => {
+ expect(() => buildAgentHelp(getCliTools())).not.toThrow()
+ })
+
+ it('hides AI-consent tools unless consent is confirmed', () => {
+ const withoutConsent = getCliTools().map((tool) => tool.name)
+ const withConsent = getCliTools({ aiConsentGiven: true }).map((tool) => tool.name)
+
+ expect(withoutConsent).not.toContain('llma-summarization-create')
+ expect(withConsent).toContain('llma-summarization-create')
+ })
+})
diff --git a/services/mcp/tests/unit/cli-agents-md.test.ts b/services/mcp/tests/unit/cli-agents-md.test.ts
new file mode 100644
index 000000000000..b434ab173da4
--- /dev/null
+++ b/services/mcp/tests/unit/cli-agents-md.test.ts
@@ -0,0 +1,43 @@
+import * as fs from 'node:fs/promises'
+import * as os from 'node:os'
+import * as path from 'node:path'
+import { describe, expect, it } from 'vitest'
+
+import { AGENTS_MD_SNIPPET, installAgentsMdSnippet } from '@/cli/agents-md'
+
+describe('CLI AGENTS.md installer', () => {
+ it('wraps the installed snippet in a <posthog> block', () => {
+ expect(AGENTS_MD_SNIPPET.startsWith('<posthog>\n')).toBe(true)
+ expect(AGENTS_MD_SNIPPET.endsWith('\n</posthog>')).toBe(true)
+ })
+
+ it('installs the snippet idempotently', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-agents-md-'))
+ const target = path.join(dir, 'AGENTS.md')
+ await fs.writeFile(target, '# Project\n\nExisting instructions.\n')
+
+ await installAgentsMdSnippet({ filePath: target })
+ await installAgentsMdSnippet({ filePath: target })
+
+ const content = await fs.readFile(target, 'utf-8')
+ expect(content.match(/<posthog>/g)?.length).toBe(1)
+ expect(content).toContain('Existing instructions.')
+ })
+
+ it('replaces a stale <posthog> block in place', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-agents-md-'))
+ const target = path.join(dir, 'AGENTS.md')
+ await fs.writeFile(
+ target,
+ '# Project\n\n<posthog>\nOutdated PostHog guidance.\n</posthog>\n\nTrailing instructions.\n'
+ )
+
+ await installAgentsMdSnippet({ filePath: target })
+
+ const content = await fs.readFile(target, 'utf-8')
+ expect(content).not.toContain('Outdated PostHog guidance.')
+ expect(content.match(/<posthog>/g)?.length).toBe(1)
+ expect(content.indexOf('# Project')).toBeLessThan(content.indexOf('<posthog>'))
+ expect(content.indexOf('</posthog>')).toBeLessThan(content.indexOf('Trailing instructions.'))
+ })
+})
diff --git a/services/mcp/tests/unit/cli-args.test.ts b/services/mcp/tests/unit/cli-args.test.ts
new file mode 100644
index 000000000000..90f323040b1f
--- /dev/null
+++ b/services/mcp/tests/unit/cli-args.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest'
+
+import { takeOption } from '@/cli/args'
+
+describe('CLI argument helpers', () => {
+ it('removes and returns an option value', () => {
+ const args = ['install', '--path', 'docs/AGENTS.md', '--force']
+
+ expect(takeOption(args, '--path')).toBe('docs/AGENTS.md')
+ expect(args).toEqual(['install', '--force'])
+ })
+
+ it('returns undefined when the option is absent', () => {
+ const args = ['install']
+
+ expect(takeOption(args, '--path')).toBeUndefined()
+ expect(args).toEqual(['install'])
+ })
+
+ it('rejects an option with no value', () => {
+ const args = ['install', '--path']
+
+ expect(() => takeOption(args, '--path')).toThrow('Missing value for --path')
+ })
+
+ it('rejects another flag where the option value should be', () => {
+ const args = ['install', '--path', '--force']
+
+ expect(() => takeOption(args, '--path')).toThrow('Missing value for --path')
+ })
+})
diff --git a/services/mcp/tests/unit/cli-context.test.ts b/services/mcp/tests/unit/cli-context.test.ts
new file mode 100644
index 000000000000..c2a680d101b6
--- /dev/null
+++ b/services/mcp/tests/unit/cli-context.test.ts
@@ -0,0 +1,62 @@
+import { createHash } from 'node:crypto'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { AnalyticsEvent } from '@/lib/posthog/analytics'
+
+const mocks = vi.hoisted(() => ({
+ capture: vi.fn(),
+ getAnalyticsContext: vi.fn(),
+ getDistinctId: vi.fn(),
+}))
+
+vi.mock('@/lib/posthog', () => ({
+ getPostHogClient: () => ({
+ capture: mocks.capture,
+ }),
+}))
+
+vi.mock('@/lib/StateManager', () => ({
+ StateManager: class {
+ getDistinctId = mocks.getDistinctId
+ getAnalyticsContext = mocks.getAnalyticsContext
+ },
+}))
+
+import { buildCliContext } from '@/cli/context'
+
+describe('CLI context', () => {
+ beforeEach(() => {
+ mocks.capture.mockClear()
+ mocks.getDistinctId.mockReset()
+ mocks.getAnalyticsContext.mockReset()
+ mocks.getDistinctId.mockRejectedValue(new Error('offline'))
+ mocks.getAnalyticsContext.mockRejectedValue(new Error('offline'))
+ })
+
+ it('uses an opaque analytics distinct ID when identity resolution fails', async () => {
+ const apiKey = 'phx_secret-token'
+ const context = await buildCliContext({ apiKey, host: 'https://us.posthog.com', version: 2 })
+
+ await context.trackEvent(AnalyticsEvent.MCP_TOOL_CALL)
+
+ const expectedHash = createHash('sha256').update(apiKey).digest('hex').slice(0, 16)
+ expect(mocks.capture).toHaveBeenCalledWith(
+ expect.objectContaining({
+ distinctId: `posthog-cli:${expectedHash}`,
+ })
+ )
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(apiKey)
+ })
+
+ it('uses an anonymous analytics distinct ID without an API key', async () => {
+ const context = await buildCliContext({ host: 'https://us.posthog.com', version: 2 })
+
+ await context.trackEvent(AnalyticsEvent.MCP_TOOL_CALL)
+
+ expect(mocks.capture).toHaveBeenCalledWith(
+ expect.objectContaining({
+ distinctId: 'posthog-cli:anonymous',
+ })
+ )
+ })
+})
diff --git a/services/mcp/tests/unit/cli-experimental.test.ts b/services/mcp/tests/unit/cli-experimental.test.ts
new file mode 100644
index 000000000000..109cb30c9eed
--- /dev/null
+++ b/services/mcp/tests/unit/cli-experimental.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest'
+
+import { EXPERIMENTAL_API_ENV, isExperimentalApiEnabled, requireExperimentalApiEnabled } from '@/cli/experimental'
+
+describe('CLI experimental gate', () => {
+ it('is disabled by default', () => {
+ expect(isExperimentalApiEnabled({})).toBe(false)
+ })
+
+ it('accepts explicit enabled environment values', () => {
+ for (const value of ['1', 'true', 'TRUE', 'yes', 'on']) {
+ expect(isExperimentalApiEnabled({ [EXPERIMENTAL_API_ENV]: value })).toBe(true)
+ }
+ })
+
+ it('rejects non-enabled environment values', () => {
+ for (const value of ['0', 'false', 'no', '']) {
+ expect(isExperimentalApiEnabled({ [EXPERIMENTAL_API_ENV]: value })).toBe(false)
+ }
+ })
+
+ it('allows the per-command flag override', () => {
+ expect(() => requireExperimentalApiEnabled({ flagEnabled: true, env: {} })).not.toThrow()
+ })
+
+ it('explains how to enable the command group', () => {
+ expect(() => requireExperimentalApiEnabled({ env: {} })).toThrow(EXPERIMENTAL_API_ENV)
+ expect(() => requireExperimentalApiEnabled({ env: {} })).toThrow('--experimental')
+ })
+})
diff --git a/services/mcp/tests/unit/cli-skills.test.ts b/services/mcp/tests/unit/cli-skills.test.ts
new file mode 100644
index 000000000000..381484bc1b4c
--- /dev/null
+++ b/services/mcp/tests/unit/cli-skills.test.ts
@@ -0,0 +1,68 @@
+import { zipSync, strToU8 } from 'fflate'
+import * as fs from 'node:fs/promises'
+import * as os from 'node:os'
+import * as path from 'node:path'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { ContextMillResource } from '@/resources/manifest-types'
+
+vi.mock('@/resources/internals', () => ({
+ fetchContextMillResources: vi.fn(),
+ filterValidEntries: vi.fn((entries: ContextMillResource[]) => entries),
+ loadManifestFromArchive: vi.fn(),
+}))
+
+import { installSkill } from '@/cli/skills'
+import { fetchContextMillResources, loadManifestFromArchive } from '@/resources/internals'
+
+const skillZip = zipSync({
+ 'SKILL.md': strToU8('# Test skill\n'),
+})
+
+function skillEntry(id: string): ContextMillResource {
+ return {
+ id,
+ name: 'Test skill',
+ uri: `context-mill://skills/${id}`,
+ file: 'test-skill.zip',
+ resource: {
+ mimeType: 'text/markdown',
+ description: 'A test skill',
+ text: '# Test skill',
+ },
+ }
+}
+
+function mockSkillArchive(entries: ContextMillResource[]): void {
+ vi.mocked(fetchContextMillResources).mockResolvedValue({ 'test-skill.zip': skillZip })
+ vi.mocked(loadManifestFromArchive).mockReturnValue({ version: '1', resources: entries })
+}
+
+describe('CLI skill installer', () => {
+ beforeEach(() => {
+ vi.mocked(fetchContextMillResources).mockReset()
+ vi.mocked(loadManifestFromArchive).mockReset()
+ })
+
+ it('installs a skill under .agents/skills', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-cli-skills-'))
+ mockSkillArchive([skillEntry('test-skill')])
+
+ const result = await installSkill('test-skill', { cwd: dir })
+
+ expect(result).toEqual({
+ id: 'test-skill',
+ directory: path.join(dir, '.agents', 'skills', 'test-skill'),
+ fileCount: 1,
+ })
+ await expect(fs.readFile(path.join(result.directory, 'SKILL.md'), 'utf-8')).resolves.toBe('# Test skill\n')
+ })
+
+ it('rejects skill IDs that escape .agents/skills', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-cli-skills-'))
+ mockSkillArchive([skillEntry('../../../outside')])
+
+ await expect(installSkill('../../../outside', { cwd: dir, force: true })).rejects.toThrow('Invalid skill ID')
+ await expect(fs.access(path.join(dir, 'outside'))).rejects.toMatchObject({ code: 'ENOENT' })
+ })
+})
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index d71d8634c0e9..4ace3b95a312 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -126,14 +126,49 @@ describe('exec tool', () => {
it('throws usage error for bare call', async () => {
const exec = createExec()
await expect(exec.handler(mockContext, { command: 'call' })).rejects.toThrow(
- 'Usage: call [--json] <tool_name> <json_input>'
+ 'Usage: call [--json] [--confirm] <tool_name> <json_input>'
)
})
it('throws usage error for call --json with no tool name', async () => {
const exec = createExec()
await expect(exec.handler(mockContext, { command: 'call --json' })).rejects.toThrow(
- 'Usage: call [--json] <tool_name> <json_input>'
+ 'Usage: call [--json] [--confirm] <tool_name> <json_input>'
+ )
+ })
+
+ it('allows --confirm before --json when dispatching a call', async () => {
+ const exec = createExec()
+ const result = await exec.handler(mockContext, { command: 'call --confirm --json mock-tool' })
+ const parsed = JSON.parse(result as string)
+ expect(parsed).toEqual({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] })
+ })
+
+ it('requires --confirm for destructive tools when enabled', async () => {
+ const destructive = makeMockTool({
+ annotations: {
+ destructiveHint: true,
+ idempotentHint: true,
+ openWorldHint: false,
+ readOnlyHint: false,
+ },
+ })
+ const exec = createExecTool(
+ [destructive],
+ mockContext,
+ 'test description',
+ 'test command reference',
+ undefined,
+ undefined,
+ [],
+ { requireDestructiveConfirmation: true }
+ )
+
+ await expect(exec.handler(mockContext, { command: 'call mock-tool' })).rejects.toThrow(
+ 'Tool "mock-tool" is destructive'
+ )
+ await expect(exec.handler(mockContext, { command: 'call --confirm --json mock-tool' })).resolves.toEqual(
+ JSON.stringify({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] })
)
})
@@ -774,6 +809,8 @@ describe('exec tool', () => {
['call my-tool {}', 'my-tool'],
['call my-tool', 'my-tool'],
['call --json my-tool {}', 'my-tool'],
+ ['call --confirm my-tool {}', 'my-tool'],
+ ['call --json --confirm my-tool {}', 'my-tool'],
[' call my-tool {} ', 'my-tool'],
])('extracts inner tool name from "%s"', (command, expected) => {
expect(parseExecCallInnerToolName(command)).toBe(expected)