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(hog): browse and call the posthog api tools with hog api (#125199)

Rafael Audibert6698865c9470
diff --git a/hog/README.md b/hog/README.md
index 6f2dc0fa3cc6..0198082d5b87 100644
--- a/hog/README.md
+++ b/hog/README.md
@@ -11,23 +11,27 @@ It is not published yet.
`hog` has no `exp` namespace.
The commands `posthog-cli` keeps under `exp` (`query`, `endpoints`, `logs`, `tasks`, `schema`) are top-level commands in `hog`.
-| Command | Status |
-| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
-| `hog auth login` | Logs in through the browser and saves a personal API key. Agents finish with `hog auth login --wait`. |
-| `hog auth status` | Shows whether hog is logged in, whose key it is, and where the key comes from. Exits with code 1 without a working key. |
-| `hog auth logout` | Removes the stored key. The key stays valid in PostHog until you delete it there. |
-| `hog query run <query>` | Runs a HogQL query. `-` reads the query from stdin. |
-| `hog query check <query>` | Checks a query without running it. Exits with code 1 when the query has errors. |
-| `hog error-tracking inject [paths...]` | Adds chunk IDs to JavaScript bundles and their sourcemaps. `hog et` is an alias for `hog error-tracking`. |
-| `hog error-tracking clone <from> <to>` | Copies the chunk ID from Metro's map to the map Hermes composed, for React Native. |
-| `hog error-tracking upload [paths...]` | Uploads symbols for readable stack traces: JavaScript sourcemaps, Hermes maps, ProGuard mappings, dSYMs and ELF files. |
-| `hog error-tracking process [paths...]` | Runs `inject`, then `upload`. Use it in CI after the build. |
-| `hog error-tracking release` | Finds or creates the release for this build. `-o text` prints just its ID. |
-| `hog error-tracking download <id/ref>` | Downloads a symbol set from PostHog and unpacks it. |
-| `hog error-tracking extract <file>` | Unpacks a symbol set file. |
-| `hog config check`, `hog config schema` | Check `posthog.json` against its schema, or print the schema. |
-| `hog commands` | Lists every command, its arguments, options and scopes. |
-| Everything else | Not ported yet. Exits with code 1 and prints the `posthog-cli` command to run instead, with the same arguments. |
+| Command | Status |
+| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
+| `hog auth login` | Logs in through the browser and saves a personal API key. Agents finish with `hog auth login --wait`. |
+| `hog auth status` | Shows whether hog is logged in, whose key it is, and where the key comes from. Exits with code 1 without a working key. |
+| `hog auth logout` | Removes the stored key. The key stays valid in PostHog until you delete it there. |
+| `hog query run <query>` | Runs a HogQL query. `-` reads the query from stdin. |
+| `hog query check <query>` | Checks a query without running it. Exits with code 1 when the query has errors. |
+| `hog api groups`, `hog api tools [group]` | List the PostHog MCP tools by group, with the scopes the key is missing for each. |
+| `hog api search`, `info`, `schema` | Find a tool, see what it does and the input it takes. |
+| `hog api call <tool> [input]` | Calls a tool with JSON input. `--dry-run` only checks the input, and destructive tools need `--confirm`. |
+| `hog api access` | Shows the key's scopes and the missing scopes that block the most tools. |
+| `hog error-tracking inject [paths...]` | Adds chunk IDs to JavaScript bundles and their sourcemaps. `hog et` is an alias for `hog error-tracking`. |
+| `hog error-tracking clone <from> <to>` | Copies the chunk ID from Metro's map to the map Hermes composed, for React Native. |
+| `hog error-tracking upload [paths...]` | Uploads symbols for readable stack traces: JavaScript sourcemaps, Hermes maps, ProGuard mappings, dSYMs and ELF files. |
+| `hog error-tracking process [paths...]` | Runs `inject`, then `upload`. Use it in CI after the build. |
+| `hog error-tracking release` | Finds or creates the release for this build. `-o text` prints just its ID. |
+| `hog error-tracking download <id/ref>` | Downloads a symbol set from PostHog and unpacks it. |
+| `hog error-tracking extract <file>` | Unpacks a symbol set file. |
+| `hog config check`, `hog config schema` | Check `posthog.json` against its schema, or print the schema. |
+| `hog commands` | Lists every command, its arguments, options and scopes. |
+| Everything else | Not ported yet. Exits with code 1 and prints the `posthog-cli` command to run instead, with the same arguments. |
## What's left
@@ -35,7 +39,7 @@ hog replaces posthog-cli once everything below is done.
First, the commands that make hog a complete CLI:
-- [ ] `hog api`: the agent-first MCP tool catalog, with `tools`, `search`, `info`, `schema`, `call`, `skill` and `agents-md`. posthog-cli runs an embedded JavaScript bundle through Node. hog can import the bundle and drop the Node requirement.
+- [ ] `hog api skill` and `hog api agents-md`, which install PostHog agent skills and the AGENTS.md snippet.
- [ ] `hog endpoints`: `list`, `get`, `open`, `run`, `push`, `pull` and `diff`.
- [ ] `hog schema`: `pull` and `status`, which download event definitions and generate a typed SDK.
diff --git a/hog/package.json b/hog/package.json
index f3102dff950a..6ecaaf68a51a 100644
--- a/hog/package.json
+++ b/hog/package.json
@@ -9,13 +9,15 @@
"type": "module",
"scripts": {
"hog": "bun --no-env-file src/index.ts",
- "compile": "bun build --compile --no-compile-autoload-dotenv --no-compile-autoload-bunfig src/index.ts --outfile dist/hog",
+ "compile": "pnpm run build:mcp && bun build --compile --no-compile-autoload-dotenv --no-compile-autoload-bunfig src/index.ts --outfile dist/hog",
"typecheck": "tsc --noEmit",
"unit": "bun test",
- "schema": "bun scripts/write-schema.ts"
+ "schema": "bun scripts/write-schema.ts",
+ "build:mcp": "pnpm --filter @posthog/mcp build:cli:library"
},
"dependencies": {
"@clack/prompts": "1.8.1",
+ "@posthog/mcp": "workspace:*",
"cli-table3": "0.6.5",
"commander": "15.0.0",
"pako": "2.1.0",
diff --git a/hog/src/cli.test.ts b/hog/src/cli.test.ts
index d9433301ec02..2dc45c75d6f4 100644
--- a/hog/src/cli.test.ts
+++ b/hog/src/cli.test.ts
@@ -99,6 +99,15 @@ describe('hog', () => {
'query run',
'query check',
'query editor',
+ 'api groups',
+ 'api tools',
+ 'api search',
+ 'api info',
+ 'api schema',
+ 'api call',
+ 'api access',
+ 'api skill',
+ 'api agents-md',
'error-tracking inject',
'error-tracking clone',
'error-tracking upload',
diff --git a/hog/src/commands/api/access.ts b/hog/src/commands/api/access.ts
new file mode 100644
index 000000000000..2818cc190b5d
--- /dev/null
+++ b/hog/src/commands/api/access.ts
@@ -0,0 +1,102 @@
+import type { ApiKeyAccess, ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
+
+import { defineCommand } from '@/core/command'
+import type { Context } from '@/core/context'
+import { plural } from '@/core/text'
+import { ApiError } from '@/posthog/api'
+import { apiConnection, groupSlug, unwrap } from '@/posthog/api-tools'
+
+const TOP_SCOPES = 10
+
+// A key can be limited to projects or to organizations. An organization limit needs the project's organization.
+// Null when that can't be checked.
+async function reachesProject(
+ ctx: Context,
+ library: ApiToolLibrary,
+ access: ApiKeyAccess,
+ projectId: string
+): Promise<boolean | null> {
+ if (access.scopedTeams.length > 0) {
+ return access.scopedTeams.includes(Number(projectId))
+ }
+ if (access.scopedOrganizations.length === 0) {
+ return true
+ }
+ try {
+ const api = await ctx.posthog()
+ const project = await api.get<{ organization: string }>(`/api/projects/${projectId}/`)
+ return access.scopedOrganizations.includes(project.organization)
+ } catch (error) {
+ // Without project:read the lookup fails for any project, so a 403 says nothing about the limit.
+ if (error instanceof ApiError && error.status === 403) {
+ return library.missingScopes(access.scopes, ['project:read']).length === 0 ? false : null
+ }
+ if (error instanceof ApiError && error.status === 404) {
+ return false
+ }
+ throw error
+ }
+}
+
+export default defineCommand({
+ description: 'Show what the personal API key can reach, and the scopes that would unlock more tools',
+ notes: 'Each missing scope counts the tools it blocks. A tool can need more than one scope.',
+ examples: ['hog api access', 'hog api access -o json'],
+
+ async run({ ctx }) {
+ const library = await ctx.apiTools()
+ const connection = await apiConnection(ctx)
+ const access = unwrap(await library.keyAccess(connection))
+ const projectId = connection.projectId ?? ''
+ const blocked = new Map<string, { tools: number; groups: Set<string> }>()
+ let usable = 0
+ const tools = library.tools()
+ for (const tool of tools) {
+ const missing = library.missingScopes(access.scopes, tool.requiredScopes)
+ usable += missing.length === 0 ? 1 : 0
+ for (const scope of missing) {
+ const entry = blocked.get(scope) ?? { tools: 0, groups: new Set<string>() }
+ entry.tools += 1
+ entry.groups.add(groupSlug(tool.group))
+ blocked.set(scope, entry)
+ }
+ }
+ return {
+ scopes: access.scopes,
+ projectId: connection.projectId ?? null,
+ projectAllowed: await reachesProject(ctx, library, access, projectId),
+ scopedProjects: access.scopedTeams,
+ scopedOrganizations: access.scopedOrganizations,
+ tools: tools.length,
+ usable,
+ missingScopes: [...blocked.entries()]
+ .map(([scope, entry]) => ({ scope, tools: entry.tools, groups: [...entry.groups].sort() }))
+ .sort((a, b) => b.tools - a.tools || a.scope.localeCompare(b.scope)),
+ }
+ },
+
+ human({ result, out }) {
+ if (result.projectAllowed === false) {
+ const reach =
+ result.scopedProjects.length > 0
+ ? `projects ${result.scopedProjects.join(', ')}`
+ : `organizations ${result.scopedOrganizations.join(', ')}`
+ out.line(out.style(`The key can't reach project ${result.projectId}. It only reaches ${reach}.`, 'yellow'))
+ }
+ out.line(`Scopes: ${result.scopes.join(', ') || 'none'}`)
+ out.line(`Usable tools: ${result.usable} of ${result.tools}`)
+ if (result.missingScopes.length > 0) {
+ out.line()
+ out.table(
+ ['missing scope', 'tools', 'groups'],
+ result.missingScopes
+ .slice(0, TOP_SCOPES)
+ .map((entry) => [entry.scope, entry.tools, entry.groups.join(', ')])
+ )
+ const more = result.missingScopes.length - TOP_SCOPES
+ if (more > 0) {
+ out.line(out.style(`${plural(more, 'more missing scope')}. \`-o json\` lists them all.`, 'dim'))
+ }
+ }
+ },
+})
diff --git a/hog/src/commands/api/api.test.ts b/hog/src/commands/api/api.test.ts
new file mode 100644
index 000000000000..09d13c90d20b
--- /dev/null
+++ b/hog/src/commands/api/api.test.ts
@@ -0,0 +1,216 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { ApiConnection, ApiToolLibrary, ApiToolResult, ApiToolSummary } from '@posthog/mcp/src/cli/library-types'
+
+import { runHog, TEST_CREDENTIALS } from '@/testing'
+
+const tool = (
+ name: string,
+ group: string,
+ scopes: string[],
+ kind: 'read' | 'write' | 'destructive'
+): ApiToolSummary => ({
+ name,
+ title: name,
+ summary: `Summary of ${name}`,
+ description: `Description of ${name}`,
+ group,
+ feature: group,
+ requiredScopes: scopes,
+ readOnly: kind === 'read',
+ destructive: kind === 'destructive',
+ idempotent: kind === 'read',
+ openWorld: true,
+ requiresAiConsent: false,
+})
+
+const TOOLS = [
+ tool('flag-list', 'Feature flags', ['feature_flag:read'], 'read'),
+ tool('flag-delete', 'Feature flags', ['feature_flag:write'], 'destructive'),
+ tool('insight-create', 'Insights & analytics', ['insight:write', 'query:read'], 'write'),
+]
+
+interface FakeLibrary extends ApiToolLibrary {
+ calls: { tool: string; input: Record<string, unknown>; connection: ApiConnection; confirm: boolean }[]
+}
+
+interface FakeLibraryOptions {
+ callResult?: ApiToolResult<unknown>
+ scopedOrganizations?: string[]
+ lookupFails?: boolean
+}
+
+function fakeLibrary(scopes: string[], options: FakeLibraryOptions = {}): FakeLibrary {
+ const { callResult = { ok: true, value: { ok: 1 } }, scopedOrganizations = [], lookupFails = false } = options
+ const calls: FakeLibrary['calls'] = []
+ return {
+ calls,
+ tools: () => TOOLS,
+ search: async (query) => ({
+ names: TOOLS.filter((t) => t.name.includes(query)).map((t) => t.name),
+ truncated: false,
+ }),
+ schema: async () => ({ type: 'object', properties: {} }),
+ validate: (_name, input) =>
+ 'limit' in input && typeof input.limit !== 'number'
+ ? { valid: false, error: 'parameter "limit" must be of type number' }
+ : { valid: true, input },
+ missingScopes: (granted, required) => required.filter((scope) => !granted.includes(scope)),
+ keyAccess: async () =>
+ lookupFails
+ ? { ok: false, error: { code: 'api_error', message: 'Server error', status: 500 } }
+ : { ok: true, value: { scopes, scopedTeams: [], scopedOrganizations } },
+ call: async (name, input, connection, confirm) => {
+ calls.push({ tool: name, input, connection, confirm })
+ return callResult
+ },
+ flush: async () => {},
+ }
+}
+
+describe('hog api', () => {
+ test('groups count the tools the key can use', async () => {
+ const result = await runHog(['api', 'groups'], {
+ env: TEST_CREDENTIALS,
+ apiTools: fakeLibrary(['feature_flag:read', 'query:read']),
+ })
+ expect(result.stdout).toBe(
+ '{"group":"feature-flags","name":"Feature flags","tools":2,"usable":1}\n' +
+ '{"group":"insights-analytics","name":"Insights & analytics","tools":1,"usable":0}\n'
+ )
+ })
+
+ test.each([
+ ['without credentials', {}, fakeLibrary([])],
+ ['when the key lookup fails', { env: TEST_CREDENTIALS }, fakeLibrary([], { lookupFails: true })],
+ ])('tools are browsable %s', async (_name, options, library) => {
+ const result = await runHog(['api', 'tools', 'Feature flags'], { ...options, apiTools: library })
+ expect(result.exitCode).toBe(0)
+ expect(result.stdout).toBe(
+ '{"group":"feature-flags","kind":"read","missingScopes":null,"name":"flag-list","summary":"Summary of flag-list","usable":null}\n' +
+ '{"group":"feature-flags","kind":"destructive","missingScopes":null,"name":"flag-delete","summary":"Summary of flag-delete","usable":null}\n'
+ )
+ })
+
+ test.each([
+ ['an unknown group', ['api', 'tools', 'nope'], 'unknown_group', 1],
+ ['an unknown tool', ['api', 'call', 'nope'], 'unknown_tool', 1],
+ ['input that is not JSON', ['api', 'call', 'flag-list', '{limit'], 'invalid_json', 2],
+ ['input that is not an object', ['api', 'call', 'flag-list', '[1]'], 'invalid_json', 2],
+ ['input the schema rejects', ['api', 'call', 'flag-list', '{"limit":"x"}'], 'invalid_input', 2],
+ ['a destructive tool without --confirm', ['api', 'call', 'flag-delete', '{"id":1}'], 'needs_confirmation', 1],
+ ['an empty --project-id', ['api', 'call', 'flag-list', '{}', '--project-id', ''], 'invalid_input', 2],
+ [
+ 'an empty --organization-id',
+ ['api', 'call', 'flag-list', '{}', '--organization-id', ' '],
+ 'invalid_input',
+ 2,
+ ],
+ ])('call refuses %s before calling PostHog', async (_name, argv, code, exitCode) => {
+ const library = fakeLibrary(['*'])
+ const result = await runHog(argv, { env: TEST_CREDENTIALS, apiTools: library })
+ expect(result.exitCode).toBe(exitCode)
+ expect(result.error().code).toBe(code)
+ expect(library.calls).toEqual([])
+ })
+
+ test.each([
+ [
+ '--dry-run checks the input without calling',
+ ['--dry-run'],
+ { input: { limit: 2 }, tool: 'flag-list', valid: true },
+ [],
+ ],
+ [
+ 'an organization override drops the saved project',
+ ['--organization-id', 'org-b'],
+ { ok: 1 },
+ [
+ {
+ tool: 'flag-list',
+ input: { limit: 2 },
+ connection: {
+ apiKey: 'phx_test',
+ host: 'https://ph.example.com',
+ organizationId: 'org-b',
+ clientName: 'hog',
+ clientVersion: expect.any(String),
+ },
+ confirm: false,
+ },
+ ],
+ ],
+ [
+ 'a call runs as hog in the chosen project',
+ ['--project-id', '9'],
+ { ok: 1 },
+ [
+ {
+ tool: 'flag-list',
+ input: { limit: 2 },
+ connection: {
+ apiKey: 'phx_test',
+ host: 'https://ph.example.com',
+ projectId: '9',
+ clientName: 'hog',
+ clientVersion: expect.any(String),
+ },
+ confirm: false,
+ },
+ ],
+ ],
+ ])('call: %s', async (_name, flags, output, calls) => {
+ const library = fakeLibrary(['*'])
+ const result = await runHog(['api', 'call', 'flag-list', '{"limit":2}', ...flags], {
+ env: TEST_CREDENTIALS,
+ apiTools: library,
+ })
+ expect(result.exitCode).toBe(0)
+ expect(result.json()).toEqual(output)
+ expect(library.calls).toEqual(calls)
+ })
+
+ test.each([
+ ['names every scope the key is missing', false, 'insight:write, query:read'],
+ ['keeps the scope PostHog named when the key lookup fails', true, 'insight:write'],
+ ])('a refused call %s', async (_name, lookupFails, scopes) => {
+ const library = fakeLibrary(['feature_flag:read'], {
+ lookupFails,
+ callResult: {
+ ok: false,
+ error: { code: 'permission_denied', message: 'denied', status: 403, missingScope: 'insight:write' },
+ },
+ })
+ const result = await runHog(['api', 'call', 'insight-create', '{}'], {
+ env: TEST_CREDENTIALS,
+ apiTools: library,
+ })
+ expect(result.error()).toMatchObject({
+ code: 'missing_scopes',
+ message: `The personal API key needs ${scopes} to call insight-create.`,
+ })
+ })
+
+ test.each([
+ ['an unlimited key reaches the project', [], 200, undefined, true],
+ ["a key limited to the project's organization reaches it", ['org-a'], 200, 'org-a', true],
+ ['a key limited to another organization does not', ['org-b'], 200, 'org-a', false],
+ ["a key without project:read can't tell", ['org-a'], 403, undefined, null],
+ ])('access: %s', async (_name, scopedOrganizations, status, projectOrganization, projectAllowed) => {
+ const result = await runHog(['api', 'access'], {
+ env: TEST_CREDENTIALS,
+ apiTools: fakeLibrary(['feature_flag:read', 'feature_flag:write'], { scopedOrganizations }),
+ respond: () => ({ status, body: status === 200 ? { id: 7, organization: projectOrganization } : {} }),
+ })
+
+ expect(result.json()).toMatchObject({
+ usable: 2,
+ tools: 3,
+ projectAllowed,
+ missingScopes: [
+ { scope: 'insight:write', tools: 1, groups: ['insights-analytics'] },
+ { scope: 'query:read', tools: 1, groups: ['insights-analytics'] },
+ ],
+ })
+ })
+})
diff --git a/hog/src/commands/api/call.ts b/hog/src/commands/api/call.ts
new file mode 100644
index 000000000000..08291c873075
--- /dev/null
+++ b/hog/src/commands/api/call.ts
@@ -0,0 +1,93 @@
+import { defineCommand } from '@/core/command'
+import { EXIT_USAGE, HogError } from '@/core/errors'
+import { apiConnection, findTool, grantedScopes, missingScopesError, toHogError } from '@/posthog/api-tools'
+
+function parseInput(text: string | undefined): Record<string, unknown> {
+ if (text === undefined) {
+ return {}
+ }
+ let input: unknown
+ try {
+ input = JSON.parse(text)
+ } catch (error) {
+ throw new HogError(
+ 'invalid_json',
+ `The input isn't valid JSON: ${(error as Error).message}`,
+ 'Pass one JSON object, like \'{"limit": 10}\'.',
+ EXIT_USAGE
+ )
+ }
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
+ throw new HogError(
+ 'invalid_json',
+ 'The input must be a JSON object.',
+ 'Pass one JSON object, like \'{"limit": 10}\'.',
+ EXIT_USAGE
+ )
+ }
+ return input as Record<string, unknown>
+}
+
+export default defineCommand({
+ description: 'Call an API tool with JSON input and print its result',
+ args: {
+ tool: { description: 'The tool name, as `hog api tools` lists it' },
+ input: { description: 'The input as a JSON object, or - to read it from stdin', optional: true, stdin: true },
+ },
+ options: {
+ dryRun: { type: 'boolean', description: 'Check the input against the schema without calling the tool' },
+ confirm: { type: 'boolean', description: 'Allow a tool that changes or deletes data it cannot restore' },
+ projectId: { type: 'string', placeholder: 'id', description: 'Call the tool in this project instead' },
+ organizationId: {
+ type: 'string',
+ placeholder: 'id',
+ description: 'The organization for organization-level tools',
+ },
+ },
+ notes: 'The tool decides the scopes. `hog api info <tool>` lists them, and a refusal names the ones the key is missing.',
+ examples: [
+ 'hog api call feature-flag-get-all \'{"limit": 5}\'',
+ 'echo \'{"key": "beta"}\' | hog api call create-feature-flag - --dry-run',
+ 'hog api call delete-feature-flag \'{"id": 12}\' --confirm',
+ ],
+
+ async run({ args, options, ctx }) {
+ const library = await ctx.apiTools()
+ const tool = findTool(library, args.tool)
+ const validation = library.validate(tool.name, parseInput(args.input))
+ if (!validation.valid) {
+ throw new HogError(
+ 'invalid_input',
+ validation.error,
+ `Run \`hog api schema ${tool.name}\` to see the input it takes.`,
+ EXIT_USAGE
+ )
+ }
+ if (options.dryRun) {
+ return { tool: tool.name, valid: true, input: validation.input }
+ }
+ if (tool.destructive && !options.confirm) {
+ throw new HogError(
+ 'needs_confirmation',
+ `${tool.name} changes or deletes data it cannot restore.`,
+ 'Run it again with --confirm.'
+ )
+ }
+
+ const connection = await apiConnection(ctx, options)
+ const result = await library.call(tool.name, validation.input, connection, options.confirm === true)
+ await library.flush()
+ if (result.ok) {
+ return result.value
+ }
+ // PostHog names one missing scope per refusal, so look up the key to name all of them.
+ if (result.error.code === 'permission_denied') {
+ const granted = await grantedScopes(ctx, library)
+ const missing = granted ? library.missingScopes(granted, tool.requiredScopes) : []
+ if (missing.length > 0) {
+ throw missingScopesError(tool.name, missing)
+ }
+ }
+ throw toHogError(result.error, tool.name)
+ },
+})
diff --git a/hog/src/commands/api/groups.ts b/hog/src/commands/api/groups.ts
new file mode 100644
index 000000000000..e9fcec311236
--- /dev/null
+++ b/hog/src/commands/api/groups.ts
@@ -0,0 +1,34 @@
+import { defineCommand } from '@/core/command'
+import { grantedScopes, groupTools } from '@/posthog/api-tools'
+
+export default defineCommand({
+ description: 'List the groups of API tools, with how many each holds',
+ notes: 'With credentials, `usable` counts the tools the personal API key has the scopes for.',
+ examples: ['hog api groups', 'hog api tools feature-flags'],
+
+ async run({ ctx }) {
+ const library = await ctx.apiTools()
+ const granted = await grantedScopes(ctx, library)
+ return groupTools(library.tools()).map((group) => ({
+ group: group.slug,
+ name: group.name,
+ tools: group.tools.length,
+ usable: granted
+ ? group.tools.filter((tool) => library.missingScopes(granted, tool.requiredScopes).length === 0).length
+ : null,
+ }))
+ },
+
+ human({ result, out }) {
+ const known = result.some((group) => group.usable !== null)
+ out.table(
+ known ? ['group', 'tools', 'usable'] : ['group', 'tools'],
+ result.map((group) => (known ? [group.group, group.tools, group.usable] : [group.group, group.tools]))
+ )
+ out.line(out.style('Run `hog api tools <group>` to list the tools in a group.', 'dim'))
+ },
+
+ agent({ result, out }) {
+ out.jsonLines(result)
+ },
+})
diff --git a/hog/src/commands/api/index.ts b/hog/src/commands/api/index.ts
new file mode 100644
index 000000000000..84aca8dba16f
--- /dev/null
+++ b/hog/src/commands/api/index.ts
@@ -0,0 +1,27 @@
+import { defineGroup, defineLegacy } from '@/core/command'
+
+import access from './access'
+import call from './call'
+import groups from './groups'
+import info from './info'
+import schema from './schema'
+import search from './search'
+import tools from './tools'
+
+export default defineGroup({
+ description: 'Browse and call the PostHog API through the tools the PostHog MCP server offers',
+ commands: {
+ groups,
+ tools,
+ search,
+ info,
+ schema,
+ call,
+ access,
+ skill: defineLegacy({ description: 'List and install PostHog agent skills', use: 'posthog-cli api skill' }),
+ 'agents-md': defineLegacy({
+ description: 'Install the PostHog steering snippet in AGENTS.md',
+ use: 'posthog-cli api agents-md',
+ }),
+ },
+})
diff --git a/hog/src/commands/api/info.ts b/hog/src/commands/api/info.ts
new file mode 100644
index 000000000000..66ef9193fddb
--- /dev/null
+++ b/hog/src/commands/api/info.ts
@@ -0,0 +1,63 @@
+import { defineCommand } from '@/core/command'
+import { findTool, grantedScopes, groupSlug, toolKind } from '@/posthog/api-tools'
+
+interface InputSchema {
+ properties?: Record<string, { type?: string; description?: string }>
+ required?: string[]
+}
+
+export default defineCommand({
+ description: 'Show what an API tool does, the scopes it needs, and the input it takes',
+ args: {
+ tool: { description: 'The tool name, as `hog api tools` lists it' },
+ },
+ examples: ['hog api info feature-flag-get-all'],
+
+ async run({ args, ctx }) {
+ const library = await ctx.apiTools()
+ const tool = findTool(library, args.tool)
+ const [granted, schema] = await Promise.all([grantedScopes(ctx, library), library.schema(tool.name)])
+ return {
+ name: tool.name,
+ title: tool.title,
+ description: tool.description,
+ group: groupSlug(tool.group),
+ kind: toolKind(tool),
+ idempotent: tool.idempotent,
+ requiresAiConsent: tool.requiresAiConsent,
+ requiredScopes: tool.requiredScopes,
+ missingScopes: granted ? library.missingScopes(granted, tool.requiredScopes) : null,
+ input: schema,
+ }
+ },
+
+ human({ result, out }) {
+ out.line(out.style(`${result.name}: ${result.title}`, 'bold'))
+ out.line(result.description)
+ out.line()
+ out.line(`Group: ${result.group}`)
+ out.line(`Kind: ${result.kind}${result.kind === 'destructive' ? ', needs --confirm' : ''}`)
+ out.line(`Scopes: ${result.requiredScopes.join(', ') || 'none'}`)
+ if (result.requiresAiConsent) {
+ out.line('Sends data to an AI provider, so the organization must allow AI data processing.')
+ }
+ if (result.missingScopes?.length) {
+ out.line(out.style(`Missing scopes: ${result.missingScopes.join(', ')}`, 'red'))
+ }
+ const schema = result.input as InputSchema
+ const fields = Object.entries(schema.properties ?? {})
+ if (fields.length > 0) {
+ out.line()
+ out.table(
+ ['field', 'type', 'required', 'description'],
+ fields.map(([name, field]) => [
+ name,
+ field.type ?? null,
+ schema.required?.includes(name) ?? false,
+ field.description ?? null,
+ ])
+ )
+ }
+ out.line(out.style(`Run \`hog api schema ${result.name} <field>\` to see a nested field.`, 'dim'))
+ },
+})
diff --git a/hog/src/commands/api/schema.ts b/hog/src/commands/api/schema.ts
new file mode 100644
index 000000000000..7ff04212a57a
--- /dev/null
+++ b/hog/src/commands/api/schema.ts
@@ -0,0 +1,16 @@
+import { defineCommand } from '@/core/command'
+import { findTool } from '@/posthog/api-tools'
+
+export default defineCommand({
+ description: "Print an API tool's input schema, or one field of it",
+ args: {
+ tool: { description: 'The tool name, as `hog api tools` lists it' },
+ field: { description: 'A dotted path to a nested field, like filters.groups', optional: true },
+ },
+ examples: ['hog api schema feature-flag-get-all', 'hog api schema create-feature-flag filters.groups'],
+
+ async run({ args, ctx }) {
+ const library = await ctx.apiTools()
+ return library.schema(findTool(library, args.tool).name, args.field)
+ },
+})
diff --git a/hog/src/commands/api/search.ts b/hog/src/commands/api/search.ts
new file mode 100644
index 000000000000..97e13e7179de
--- /dev/null
+++ b/hog/src/commands/api/search.ts
@@ -0,0 +1,30 @@
+import { defineCommand } from '@/core/command'
+import { findTool, grantedScopes, toolRow } from '@/posthog/api-tools'
+
+import { toolTable } from './tools'
+
+export default defineCommand({
+ description: 'Find API tools by name, title or description',
+ args: {
+ pattern: { description: 'Words or a regular expression to match', variadic: true },
+ },
+ examples: ['hog api search feature flag', 'hog api search "^insight-"'],
+
+ async run({ args, ctx }) {
+ const library = await ctx.apiTools()
+ const { names, truncated } = await library.search(args.pattern.join(' '))
+ const granted = await grantedScopes(ctx, library)
+ return { tools: names.map((name) => toolRow(library, findTool(library, name), granted)), truncated }
+ },
+
+ human({ result, out }) {
+ toolTable(out, result.tools)
+ if (result.truncated) {
+ out.line(out.style('More tools match. Use more specific words to see them.', 'dim'))
+ }
+ },
+
+ agent({ result, out }) {
+ out.jsonLines(result.tools)
+ },
+})
diff --git a/hog/src/commands/api/tools.ts b/hog/src/commands/api/tools.ts
new file mode 100644
index 000000000000..586d4e5caa9d
--- /dev/null
+++ b/hog/src/commands/api/tools.ts
@@ -0,0 +1,36 @@
+import { defineCommand } from '@/core/command'
+import type { Output } from '@/core/output'
+import { findGroup, grantedScopes, toolRow, type ToolRow } from '@/posthog/api-tools'
+
+export function toolTable(out: Output, rows: readonly ToolRow[]): void {
+ const known = rows.some((row) => row.usable !== null)
+ out.table(
+ known ? ['tool', 'kind', 'usable', 'summary'] : ['tool', 'kind', 'summary'],
+ rows.map((row) => (known ? [row.name, row.kind, row.usable, row.summary] : [row.name, row.kind, row.summary]))
+ )
+}
+
+export default defineCommand({
+ description: 'List the API tools, or the tools in one group',
+ args: {
+ group: { description: 'A group from `hog api groups`', optional: true },
+ },
+ notes: 'Each tool shows whether it reads, writes or deletes, and which scopes the personal API key is missing for it.',
+ examples: ['hog api tools feature-flags', 'hog api tools -o json'],
+
+ async run({ args, ctx }) {
+ const library = await ctx.apiTools()
+ const tools = args.group ? findGroup(library, args.group).tools : library.tools()
+ const granted = await grantedScopes(ctx, library)
+ return tools.map((tool) => toolRow(library, tool, granted))
+ },
+
+ human({ result, out }) {
+ toolTable(out, result)
+ out.line(out.style('Run `hog api info <tool>` to see what a tool does and the input it takes.', 'dim'))
+ },
+
+ agent({ result, out }) {
+ out.jsonLines(result)
+ },
+})
diff --git a/hog/src/commands/index.ts b/hog/src/commands/index.ts
index edf798ea2b7a..08a3093a7868 100644
--- a/hog/src/commands/index.ts
+++ b/hog/src/commands/index.ts
@@ -1,5 +1,6 @@
import type { CommandTree } from '@/core/command'
+import api from './api'
import auth from './auth'
import commands from './commands'
import config from './config'
@@ -10,6 +11,7 @@ import query from './query'
export const COMMANDS: CommandTree = {
auth,
query,
+ api,
'error-tracking': errorTracking,
config,
commands,
diff --git a/hog/src/commands/legacy.ts b/hog/src/commands/legacy.ts
index f337c7015812..48e8a151a243 100644
--- a/hog/src/commands/legacy.ts
+++ b/hog/src/commands/legacy.ts
@@ -1,7 +1,6 @@
import { defineLegacy, type CommandTree } from '@/core/command'
export const LEGACY_COMMANDS: CommandTree = {
- api: defineLegacy({ description: 'Agent-first PostHog API tools', use: 'posthog-cli api' }),
endpoints: defineLegacy({ description: 'Manage PostHog endpoints', use: 'posthog-cli exp endpoints' }),
logs: defineLegacy({
description: 'Import historical logs from another log store into PostHog',
diff --git a/hog/src/core/context.ts b/hog/src/core/context.ts
index 663794dd7206..4e8b65e7e796 100644
--- a/hog/src/core/context.ts
+++ b/hog/src/core/context.ts
@@ -1,3 +1,5 @@
+import type { ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
+
import { PostHogApi } from '@/posthog/api'
import { resolveCredentials, type ResolvedCredentials } from '@/posthog/credentials'
@@ -39,6 +41,7 @@ export class Context {
private api?: PostHogApi
private resolved?: ResolvedCredentials
private loaded?: Promise<LoadedConfig | undefined>
+ private tools?: Promise<ApiToolLibrary>
constructor(
readonly runtime: Runtime,
@@ -68,6 +71,11 @@ export class Context {
return this.loaded
}
+ apiTools(): Promise<ApiToolLibrary> {
+ this.tools ??= this.runtime.loadApiTools()
+ return this.tools
+ }
+
// Throws `not_authenticated` when there are none.
async credentials(): Promise<ResolvedCredentials> {
this.resolved ??= await resolveCredentials(this.runtime, this.globals)
diff --git a/hog/src/core/runtime.ts b/hog/src/core/runtime.ts
index b576baf6f384..ed8b4ec4c581 100644
--- a/hog/src/core/runtime.ts
+++ b/hog/src/core/runtime.ts
@@ -3,6 +3,9 @@ import { access, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises
import { homedir } from 'node:os'
import { dirname } from 'node:path'
+import type { ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
+
+import { HogError } from './errors'
import { clackPrompts, type Prompts } from './prompts'
export type Env = Readonly<Record<string, string | undefined>>
@@ -30,6 +33,8 @@ export interface Runtime {
// Resolves to false when no browser could be started, for example on a server without one.
openUrl: (url: string) => Promise<boolean>
prompts: Prompts
+ // The MCP server's tool catalog, which `hog api` browses and calls. Loaded on first use: it is large.
+ loadApiTools: () => Promise<ApiToolLibrary>
}
const BROWSER_LAUNCH_MS = 1000
@@ -107,5 +112,20 @@ export function processRuntime(): Runtime {
}
},
prompts: clackPrompts(),
+ loadApiTools: async () => {
+ try {
+ const { createApiToolLibrary } = await import('@posthog/mcp/dist/cli-library.mjs')
+ return createApiToolLibrary()
+ } catch (error) {
+ if ((error as { code?: string }).code === 'ERR_MODULE_NOT_FOUND') {
+ throw new HogError(
+ 'api_tools_missing',
+ "hog couldn't find the API tool catalog.",
+ 'Run `pnpm --filter @posthog/hog build:mcp`, then run the command again.'
+ )
+ }
+ throw error
+ }
+ },
}
}
diff --git a/hog/src/posthog/api-tools.ts b/hog/src/posthog/api-tools.ts
new file mode 100644
index 000000000000..186d1d5aec30
--- /dev/null
+++ b/hog/src/posthog/api-tools.ts
@@ -0,0 +1,206 @@
+import type {
+ ApiConnection,
+ ApiToolError,
+ ApiToolLibrary,
+ ApiToolResult,
+ ApiToolSummary,
+} from '@posthog/mcp/src/cli/library-types'
+
+import type { Context } from '@/core/context'
+import { EXIT_USAGE, HogError } from '@/core/errors'
+import { VERSION } from '@/version'
+
+import { ApiError } from './api'
+
+export interface ToolGroup {
+ slug: string
+ name: string
+ tools: ApiToolSummary[]
+}
+
+export type ToolKind = 'read' | 'write' | 'destructive'
+
+// One tool as `hog api tools` and `hog api search` list it. `usable` and `missingScopes` are
+// null without credentials, so people can browse before `hog auth login`.
+export interface ToolRow {
+ name: string
+ group: string
+ kind: ToolKind
+ summary: string
+ usable: boolean | null
+ missingScopes: string[] | null
+}
+
+const SCOPES_HINT =
+ 'Run `hog auth login` to create a key with the scopes the API tools need, or add the scopes to the key in PostHog under Settings, Personal API keys.'
+
+// "Events & properties" becomes "events-properties".
+export function groupSlug(name: string): string {
+ return name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '')
+}
+
+export function groupTools(tools: readonly ApiToolSummary[]): ToolGroup[] {
+ const groups = new Map<string, ToolGroup>()
+ for (const tool of tools) {
+ const slug = groupSlug(tool.group)
+ const group = groups.get(slug) ?? { slug, name: tool.group, tools: [] }
+ group.tools.push(tool)
+ groups.set(slug, group)
+ }
+ return [...groups.values()].sort((a, b) => a.slug.localeCompare(b.slug))
+}
+
+// Takes the slug or the group's name, so `feature-flags` and "Feature flags" both work.
+export function findGroup(library: ApiToolLibrary, query: string): ToolGroup {
+ const group = groupTools(library.tools()).find((candidate) => candidate.slug === groupSlug(query))
+ if (!group) {
+ throw new HogError(
+ 'unknown_group',
+ `There is no tool group named "${query}".`,
+ 'Run `hog api groups` to list them.'
+ )
+ }
+ return group
+}
+
+export function findTool(library: ApiToolLibrary, name: string): ApiToolSummary {
+ const tool = library.tools().find((candidate) => candidate.name === name)
+ if (!tool) {
+ throw new HogError(
+ 'unknown_tool',
+ `There is no tool named "${name}".`,
+ 'Run `hog api search <words>` to find tools by name and description.'
+ )
+ }
+ return tool
+}
+
+export function toolKind(tool: ApiToolSummary): ToolKind {
+ return tool.destructive ? 'destructive' : tool.readOnly ? 'read' : 'write'
+}
+
+export function toolRow(library: ApiToolLibrary, tool: ApiToolSummary, granted: string[] | undefined): ToolRow {
+ const missingScopes = granted ? library.missingScopes(granted, tool.requiredScopes) : null
+ return {
+ name: tool.name,
+ group: groupSlug(tool.group),
+ kind: toolKind(tool),
+ summary: tool.summary,
+ usable: missingScopes ? missingScopes.length === 0 : null,
+ missingScopes,
+ }
+}
+
+export async function apiConnection(
+ ctx: Context,
+ scope: { projectId?: string | undefined; organizationId?: string | undefined } = {}
+): Promise<ApiConnection> {
+ // An empty ID, often an unset shell variable, would fall back to another project silently.
+ for (const [flag, value] of [
+ ['--project-id', scope.projectId],
+ ['--organization-id', scope.organizationId],
+ ] as const) {
+ if (value !== undefined && value.trim() === '') {
+ throw new HogError('invalid_input', `${flag} is empty.`, `Pass an ID, or leave out ${flag}.`, EXIT_USAGE)
+ }
+ }
+ const credentials = await ctx.credentials()
+ // The saved project can belong to another organization, so an organization override drops it.
+ const projectId = scope.projectId ?? (scope.organizationId ? undefined : credentials.projectId)
+ return {
+ apiKey: credentials.apiKey,
+ host: credentials.host,
+ ...(projectId ? { projectId } : {}),
+ ...(scope.organizationId ? { organizationId: scope.organizationId } : {}),
+ clientName: 'hog',
+ clientVersion: VERSION,
+ }
+}
+
+export function missingScopesError(tool: string, scopes: readonly string[]): HogError {
+ return new HogError(
+ 'missing_scopes',
+ `The personal API key needs ${scopes.join(', ')} to call ${tool}.`,
+ SCOPES_HINT
+ )
+}
+
+export function toHogError(error: ApiToolError, tool?: string): HogError {
+ switch (error.code) {
+ case 'permission_denied':
+ return error.missingScope && tool
+ ? missingScopesError(tool, [error.missingScope])
+ : new ApiError(403, undefined, 'permission_denied', error.message, SCOPES_HINT)
+ case 'validation_error':
+ case 'invalid_input':
+ return new HogError(
+ error.code,
+ error.message,
+ tool ? `Run \`hog api schema ${tool}\` to see the input it takes.` : undefined
+ )
+ case 'needs_confirmation':
+ return new HogError(error.code, error.message, 'Run it again with --confirm.')
+ case 'ai_consent_required':
+ return new HogError(
+ error.code,
+ error.message,
+ 'An organization admin can allow AI data processing in PostHog under Organization settings.'
+ )
+ case 'rate_limited':
+ return new ApiError(429, undefined, error.code, error.message, 'Wait a minute, then run it again.')
+ case 'unreachable':
+ return new HogError(error.code, error.message, 'Check the host and your network connection.')
+ case 'api_error': {
+ const hints: Record<number, string> = {
+ 401: 'Check that the personal API key is valid.',
+ 404: 'Check the IDs in the input, and the project ID.',
+ }
+ const status = error.status ?? 500
+ return new ApiError(status, undefined, `http_${status}`, error.message, hints[status])
+ }
+ case 'tool_error':
+ return new HogError(error.code, error.message)
+ }
+}
+
+export function unwrap<T>(result: ApiToolResult<T>, tool?: string): T {
+ if (!result.ok) {
+ throw toHogError(result.error, tool)
+ }
+ return result.value
+}
+
+const SCOPE_LOOKUP_MS = 10_000
+
+// Undefined when the scopes are unknown, so browsing still works on a failed or stalled lookup.
+export async function grantedScopes(ctx: Context, library: ApiToolLibrary): Promise<string[] | undefined> {
+ let connection: ApiConnection
+ try {
+ connection = await apiConnection(ctx)
+ } catch (error) {
+ if (error instanceof HogError && error.code === 'not_authenticated') {
+ return undefined
+ }
+ throw error
+ }
+ // The abort also ends the request, so a stalled lookup doesn't keep the process alive after the output.
+ const deadline = new AbortController()
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const stalled = new Promise<undefined>((resolve) => {
+ timer = setTimeout(() => {
+ deadline.abort()
+ resolve(undefined)
+ }, SCOPE_LOOKUP_MS)
+ })
+ const lookup = library
+ .keyAccess(connection, { signal: deadline.signal })
+ .then((result) => (result.ok ? result.value.scopes : undefined))
+ try {
+ return await Promise.race([lookup, stalled])
+ } finally {
+ clearTimeout(timer)
+ }
+}
diff --git a/hog/src/testing.ts b/hog/src/testing.ts
index bea016fe0b94..03339fa92bb8 100644
--- a/hog/src/testing.ts
+++ b/hog/src/testing.ts
@@ -1,5 +1,7 @@
import { existsSync, readFileSync } from 'node:fs'
+import type { ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
+
import type { Prompts } from '@/core/prompts'
import type { Env, Runtime } from '@/core/runtime'
@@ -19,6 +21,8 @@ export interface FakeRuntimeOptions {
// Answers every API request. Without it, requests fail with HTTP 500. A string body is sent
// as is, for JSON that JSON.stringify can't produce.
respond?: (url: string, body: unknown) => { status: number; body: unknown }
+ // The MCP tool catalog `hog api` loads. Without it, loading the catalog fails the test.
+ apiTools?: ApiToolLibrary
}
export interface FakeRuntime extends Runtime {
@@ -107,6 +111,12 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
return true
},
prompts: fakePrompts([...(options.answers ?? [])]),
+ loadApiTools: async () => {
+ if (!options.apiTools) {
+ throw new Error('This test loads the API tools without passing apiTools')
+ }
+ return options.apiTools
+ },
stdout: () => stdout,
stderr: () => stderr,
requests,
diff --git a/hog/src/types/mcp-library.d.ts b/hog/src/types/mcp-library.d.ts
new file mode 100644
index 000000000000..853648dfef59
--- /dev/null
+++ b/hog/src/types/mcp-library.d.ts
@@ -0,0 +1,5 @@
+// The tool catalog bundle `pnpm --filter @posthog/mcp build:cli:library` writes. Its contract lives
+// in a file with no imports, so hog type-checks without compiling the MCP sources.
+declare module '@posthog/mcp/dist/cli-library.mjs' {
+ export function createApiToolLibrary(): import('@posthog/mcp/src/cli/library-types').ApiToolLibrary
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 344e89d0347d..e3493e0f684e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1523,6 +1523,9 @@ importers:
'@clack/prompts':
specifier: 1.8.1
version: 1.8.1
+ '@posthog/mcp':
+ specifier: workspace:*
+ version: link:../services/mcp
cli-table3:
specifier: 0.6.5
version: 0.6.5