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(mcp): surface inner exec tool description and bump @posthog/mcp (#58499)

Lucas Faria0c4a7b1318fb
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index 29b7c640da53..18e67425b462 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -1840,6 +1840,30 @@
"label": "MCP duration (ms)",
"type": "Numeric"
},
+ "$mcp_exec_inner_tool_names": {
+ "description": "Array of every inner tool name available to the agent at the time of a tools/list request. Stored as a JSON array \u2014 filter with `contains` against a single tool name (e.g. 'execute-sql'). Only stamped on mcp_tools_list events when running in single-exec mode (in multi-tool mode the SDK's $mcp_listed_tool_names already carries the catalog). Lets you compute zombie tools by diffing against $mcp_exec_tool_call_name from mcp_tool_call events.",
+ "examples": [
+ "execute-sql",
+ "feature-flag-get-all"
+ ],
+ "label": "MCP exec inner tool catalog"
+ },
+ "$mcp_exec_tool_call_description": {
+ "description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so the SDK's $mcp_tool_description is the dispatcher's static text on every call. This property carries the description of the inner tool the agent was actually invoking via 'call <tool> ...' \u2014 derived server-side by parsing the exec command and looking the inner tool up in our catalog. Only present when an exec call targets a recognized inner tool.",
+ "examples": [
+ "Run a HogQL/SQL query against PostHog.",
+ "List feature flags in the project."
+ ],
+ "label": "MCP exec inner tool description"
+ },
+ "$mcp_exec_tool_call_name": {
+ "description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so by itself it doesn't tell you which inner tool the agent was actually invoking. This property carries the inner tool's name \u2014 derived server-side by parsing the exec command's `call <tool> ...` form and looking it up in our catalog. Use it for breakdowns / funnels that should pivot on the real tool rather than the dispatcher. Only present when an exec call targets a recognized inner tool.",
+ "examples": [
+ "execute-sql",
+ "feature-flag-get-all"
+ ],
+ "label": "MCP exec inner tool name"
+ },
"$mcp_intent": {
"description": "Free-text description of why the agent is calling this tool, written by the agent itself. Comes from a context argument the client supplied at call time, or \u2014 if none was supplied \u2014 from an intentFallback the MCP server provides.",
"examples": [
@@ -1890,6 +1914,14 @@
],
"label": "MCP source"
},
+ "$mcp_tool_description": {
+ "description": "The MCP tool's description as advertised to the agent at the time of the call. Useful when triaging errors to see what the agent thought the tool would do \u2014 descriptions change over time, so the value captured here is the version the agent actually saw. Only present on mcp_tool_call and the paired $exception event.",
+ "examples": [
+ "Run a HogQL/SQL query against PostHog.",
+ "Fetch the trace referenced by an LLM analytics URL."
+ ],
+ "label": "MCP tool description"
+ },
"$mcp_tool_name": {
"description": "The name of the MCP tool that was invoked. Only present on mcp_tool_call.",
"examples": [
@@ -5640,6 +5672,30 @@
"label": "MCP duration (ms)",
"type": "Numeric"
},
+ "$mcp_exec_inner_tool_names": {
+ "description": "Array of every inner tool name available to the agent at the time of a tools/list request. Stored as a JSON array \u2014 filter with `contains` against a single tool name (e.g. 'execute-sql'). Only stamped on mcp_tools_list events when running in single-exec mode (in multi-tool mode the SDK's $mcp_listed_tool_names already carries the catalog). Lets you compute zombie tools by diffing against $mcp_exec_tool_call_name from mcp_tool_call events.",
+ "examples": [
+ "execute-sql",
+ "feature-flag-get-all"
+ ],
+ "label": "MCP exec inner tool catalog"
+ },
+ "$mcp_exec_tool_call_description": {
+ "description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so the SDK's $mcp_tool_description is the dispatcher's static text on every call. This property carries the description of the inner tool the agent was actually invoking via 'call <tool> ...' \u2014 derived server-side by parsing the exec command and looking the inner tool up in our catalog. Only present when an exec call targets a recognized inner tool.",
+ "examples": [
+ "Run a HogQL/SQL query against PostHog.",
+ "List feature flags in the project."
+ ],
+ "label": "MCP exec inner tool description"
+ },
+ "$mcp_exec_tool_call_name": {
+ "description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so by itself it doesn't tell you which inner tool the agent was actually invoking. This property carries the inner tool's name \u2014 derived server-side by parsing the exec command's `call <tool> ...` form and looking it up in our catalog. Use it for breakdowns / funnels that should pivot on the real tool rather than the dispatcher. Only present when an exec call targets a recognized inner tool.",
+ "examples": [
+ "execute-sql",
+ "feature-flag-get-all"
+ ],
+ "label": "MCP exec inner tool name"
+ },
"$mcp_intent": {
"description": "Free-text description of why the agent is calling this tool, written by the agent itself. Comes from a context argument the client supplied at call time, or \u2014 if none was supplied \u2014 from an intentFallback the MCP server provides.",
"examples": [
@@ -5690,6 +5746,14 @@
],
"label": "MCP source"
},
+ "$mcp_tool_description": {
+ "description": "The MCP tool's description as advertised to the agent at the time of the call. Useful when triaging errors to see what the agent thought the tool would do \u2014 descriptions change over time, so the value captured here is the version the agent actually saw. Only present on mcp_tool_call and the paired $exception event.",
+ "examples": [
+ "Run a HogQL/SQL query against PostHog.",
+ "Fetch the trace referenced by an LLM analytics URL."
+ ],
+ "label": "MCP tool description"
+ },
"$mcp_tool_name": {
"description": "The name of the MCP tool that was invoked. Only present on mcp_tool_call.",
"examples": [
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b800863df2bc..43f489bfbb9f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3479,8 +3479,8 @@ importers:
specifier: ^1.29.0
version: 1.29.0(@cfworker/[email protected])([email protected])
'@posthog/mcp-analytics':
- specifier: npm:@posthog/[email protected]
- version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])'
+ specifier: npm:@posthog/[email protected]
+ version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])'
'@posthog/quill':
specifier: workspace:*
version: link:../../packages/quill/packages/quill
@@ -9085,8 +9085,8 @@ packages:
react: 18.3.1
react-dom: 18.3.1
- '@posthog/[email protected]':
- resolution: {integrity: sha512-Nscfg6XmDIlFLfBxhpE2uZKuWdW7GPwa1ri9oMViSNh0A00W1whca5y0N4zsI1e2a7rBPyTZs+A8ihk4elPIMw==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-emcvEZzyq8U4ct6a8ndPwlL+Gv5y33a/O8kt9oIJxp3oZ/pAa7v8lxUU04feOSZbI9SmWtH5N8EuZeuWV4z5/g==}
engines: {node: '>=22.22.0'}
peerDependencies:
'@modelcontextprotocol/sdk': ^1.29.0
@@ -32179,7 +32179,7 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
posthog-node: 5.33.3([email protected])
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 76bd9ff81a46..6214139e32d2 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2529,6 +2529,14 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"description": "The name of the MCP tool that was invoked. Only present on mcp_tool_call.",
"examples": ["execute-sql", "feature-flag-get-all"],
},
+ "$mcp_tool_description": {
+ "label": "MCP tool description",
+ "description": "The MCP tool's description as advertised to the agent at the time of the call. Useful when triaging errors to see what the agent thought the tool would do — descriptions change over time, so the value captured here is the version the agent actually saw. Only present on mcp_tool_call and the paired $exception event.",
+ "examples": [
+ "Run a HogQL/SQL query against PostHog.",
+ "Fetch the trace referenced by an LLM analytics URL.",
+ ],
+ },
"$mcp_resource_name": {
"label": "MCP resource name",
"description": "The name of the MCP resource, prompt, or tool the event refers to.",
@@ -2585,6 +2593,24 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
# PostHog-specific MCP properties added by the PostHog MCP server on top of the SDK's core
# set. They identify which deployment, transport, and consumer produced the event. The
# @posthog/mcp SDK will continue to carry these — they're not on a deprecation path.
+ "$mcp_exec_tool_call_name": {
+ "label": "MCP exec inner tool name",
+ "description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so by itself it doesn't tell you which inner tool the agent was actually invoking. This property carries the inner tool's name — derived server-side by parsing the exec command's `call <tool> ...` form and looking it up in our catalog. Use it for breakdowns / funnels that should pivot on the real tool rather than the dispatcher. Only present when an exec call targets a recognized inner tool.",
+ "examples": ["execute-sql", "feature-flag-get-all"],
+ },
+ "$mcp_exec_tool_call_description": {
+ "label": "MCP exec inner tool description",
+ "description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so the SDK's $mcp_tool_description is the dispatcher's static text on every call. This property carries the description of the inner tool the agent was actually invoking via 'call <tool> ...' — derived server-side by parsing the exec command and looking the inner tool up in our catalog. Only present when an exec call targets a recognized inner tool.",
+ "examples": [
+ "Run a HogQL/SQL query against PostHog.",
+ "List feature flags in the project.",
+ ],
+ },
+ "$mcp_exec_inner_tool_names": {
+ "label": "MCP exec inner tool catalog",
+ "description": "Array of every inner tool name available to the agent at the time of a tools/list request. Stored as a JSON array — filter with `contains` against a single tool name (e.g. 'execute-sql'). Only stamped on mcp_tools_list events when running in single-exec mode (in multi-tool mode the SDK's $mcp_listed_tool_names already carries the catalog). Lets you compute zombie tools by diffing against $mcp_exec_tool_call_name from mcp_tool_call events.",
+ "examples": ["execute-sql", "feature-flag-get-all"],
+ },
"mcp_protocol_version": {
"label": "MCP protocol version",
"description": "The MCP protocol version negotiated during initialize.",
diff --git a/services/mcp/package.json b/services/mcp/package.json
index 8f5fb04d7695..3902e264fcf0 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -37,7 +37,7 @@
"dependencies": {
"@modelcontextprotocol/ext-apps": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.29.0",
- "@posthog/mcp-analytics": "npm:@posthog/[email protected]",
+ "@posthog/mcp-analytics": "npm:@posthog/[email protected]",
"@posthog/quill": "workspace:*",
"@toon-format/toon": "^2.1.0",
"agents": "0.10.2",
diff --git a/services/mcp/src/lib/posthog-mcp-analytics.ts b/services/mcp/src/lib/posthog-mcp-analytics.ts
index d1bd7f8f79ce..5eabb1986ec2 100644
--- a/services/mcp/src/lib/posthog-mcp-analytics.ts
+++ b/services/mcp/src/lib/posthog-mcp-analytics.ts
@@ -12,6 +12,25 @@ export type PostHogMcpAnalyticsOptions = {
// catalog. In single-exec mode the wrapper handles every call, so the
// signal has nothing to map to and the extra slot is just noise.
reportMissingEnabled: boolean
+ // In single-exec mode, every event's `$mcp_tool_name` is `exec` — the real
+ // tool the LLM was invoking lives inside `arguments.command`. This callback
+ // lets the caller resolve that inner tool's name + description from the
+ // request so they can be surfaced as `$mcp_exec_tool_call_name` /
+ // `$mcp_exec_tool_call_description`. Returns undefined when the request
+ // isn't an exec call or the inner tool isn't recognized. Type accepts
+ // `| undefined` explicitly so callers can pass the value through
+ // unconditionally under `exactOptionalPropertyTypes: true`.
+ resolveExecInnerToolCall?:
+ | ((request: unknown) => { name: string; description: string } | undefined)
+ | undefined
+ // In single-exec mode the SDK's $mcp_listed_tool_names on mcp_tools_list
+ // collapses to just the dispatcher's name (`exec`) because that's the
+ // only tool the server actually advertises over MCP. Passing the full
+ // inner-tool catalog here lets us attach the inner names on tools/list
+ // events as $mcp_exec_inner_tool_names so dashboards can compute the
+ // "advertised but never called" diff against $mcp_exec_tool_call_name
+ // from mcp_tool_call events.
+ execInnerToolNames?: readonly string[] | undefined
}
export type PostHogMcpAnalyticsInitResult =
@@ -143,7 +162,26 @@ export async function initPostHogMcpAnalytics(
},
reportMissing: options.reportMissingEnabled,
eventTags: async () => buildEventTags(identity),
- eventProperties: async () => buildEventProperties(identity),
+ eventProperties: async (request) => {
+ const base = await buildEventProperties(identity)
+ const innerToolCall = options.resolveExecInnerToolCall?.(request)
+ const isListToolsRequest =
+ (request as { method?: unknown })?.method === 'tools/list' &&
+ !!options.execInnerToolNames &&
+ options.execInnerToolNames.length > 0
+ return {
+ ...base,
+ ...(innerToolCall
+ ? {
+ $mcp_exec_tool_call_name: innerToolCall.name,
+ $mcp_exec_tool_call_description: innerToolCall.description,
+ }
+ : {}),
+ ...(isListToolsRequest
+ ? { $mcp_exec_inner_tool_names: [...(options.execInnerToolNames ?? [])] }
+ : {}),
+ }
+ },
redactSensitiveInformation: (text) => Promise.resolve(redactSensitiveInformation(text)),
})
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index 6c914298573c..cc8dca1c9d89 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -37,7 +37,7 @@ import { registerPrompts } from '@/prompts'
import { registerResources } from '@/resources'
import { registerUiAppResources } from '@/resources/ui-apps'
import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'
-import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'
+import { createExecInnerToolCallResolver, createExecTool, type ExecInnerCallTracker } from '@/tools/exec'
import { getToolDefinition } from '@/tools/toolDefinitions'
import { type CloudRegion, type Context, type State, type Tool } from '@/tools/types'
@@ -788,9 +788,26 @@ export class MCP extends McpAgent<Env> {
// single-exec mode the wrapper handles every call, so the missing-tool
// signal has nothing to map to and the extra slot is pure noise.
if (posthogMcpAnalyticsOn) {
+ // In single-exec mode every event's `$mcp_tool_name` is `exec`, so the
+ // SDK's `$mcp_tool_description` would be the dispatcher's static text on
+ // every call. Resolve the inner tool the agent was actually invoking
+ // from the command and surface its name + description as
+ // `$mcp_exec_tool_call_name` / `$mcp_exec_tool_call_description`.
+ const resolveExecInnerToolCall = useSingleExec ? createExecInnerToolCallResolver(allTools) : undefined
+
+ // In single-exec mode the SDK's $mcp_listed_tool_names collapses to
+ // just `exec`, so we can't compute "advertised but never called"
+ // (zombie tools) from SDK data alone. Pass the inner-tool catalog
+ // here so analytics can attach it as $mcp_exec_inner_tool_names on
+ // mcp_tools_list events. Dashboards can then diff it against
+ // $mcp_exec_tool_call_name from mcp_tool_call.
+ const execInnerToolNames = useSingleExec ? allTools.map((t) => t.name) : undefined
+
const initResult = await initPostHogMcpAnalytics(this.server, mcpAnalyticsIdentity, {
contextEnabled: true,
reportMissingEnabled: !useSingleExec,
+ resolveExecInnerToolCall,
+ execInnerToolNames,
})
Object.assign(this.requestProperties, {
posthogMcpAnalyticsInitAction: initResult.action,
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 9c54f6a7048f..6948a6ab31d6 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -40,6 +40,45 @@ function parseCommand(input: string): { verb: string; rest: string } {
return { verb: trimmed.slice(0, idx), rest: trimmed.slice(idx + 1).trim() }
}
+// 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
+// in single-exec mode, where the outer call always shows as `exec`.
+export function parseExecCallInnerToolName(command: string): string | undefined {
+ const { verb, rest } = parseCommand(command)
+ if (verb !== 'call' || !rest) {
+ return
+ }
+ const argv = rest.startsWith('--json ') ? rest.slice('--json '.length).trim() : rest === '--json' ? '' : rest
+ if (!argv) {
+ return
+ }
+ const innerName = parseCommand(argv).verb
+ return innerName || undefined
+}
+
+// Builds the resolver mcp.ts hands to initPostHogMcpAnalytics in single-exec
+// mode: given a request, return the inner tool's { name, description } when
+// the agent invoked it via `call <tool> ...`, or undefined otherwise. Lives
+// here (alongside parseExecCallInnerToolName) so tests can import the exact
+// same factory the production code uses — no copy-pasted resolver lambda.
+export function createExecInnerToolCallResolver(
+ allTools: ReadonlyArray<Tool<ZodObjectAny>>
+): (request: unknown) => { name: string; description: string } | undefined {
+ return (request: unknown) => {
+ const params = (request as { params?: { name?: unknown; arguments?: { command?: unknown } } })?.params
+ if (params?.name !== 'exec' || typeof params.arguments?.command !== 'string') {
+ return
+ }
+ const innerName = parseExecCallInnerToolName(params.arguments.command)
+ if (!innerName) {
+ return
+ }
+ const tool = allTools.find((t) => t.name === innerName)
+ return tool ? { name: tool.name, description: tool.description } : undefined
+ }
+}
+
// Tools removed from v2 (single-exec) MCP. When the model attempts to call one,
// surface a targeted redirect to the v2 replacement instead of dumping the full
// tool catalog. Sourced from tools marked `new_mcp: false` in
diff --git a/services/mcp/tests/unit/exec-description-emission.test.ts b/services/mcp/tests/unit/exec-description-emission.test.ts
new file mode 100644
index 000000000000..07748313c48a
--- /dev/null
+++ b/services/mcp/tests/unit/exec-description-emission.test.ts
@@ -0,0 +1,187 @@
+// Real end-to-end check that $mcp_exec_tool_call_name and
+// $mcp_exec_tool_call_description actually land on the captured PostHog event
+// when an agent runs `exec("call <tool> {}")`. Bypasses the global
+// @posthog/mcp-analytics mock (set in tests/setup.ts) and drives the real SDK
+// with a stub posthog-node client to capture events.
+import { vi } from 'vitest'
+vi.unmock('@posthog/mcp-analytics')
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js'
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
+import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js'
+import { track } from '@posthog/mcp-analytics'
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+
+import { createExecInnerToolCallResolver, createExecTool } from '@/tools/exec'
+import type { Context, Tool, ZodObjectAny } from '@/tools/types'
+
+type CapturedEvent = { event: string; properties: Record<string, unknown> }
+
+type StubPostHogClient = {
+ capture: (msg: { event: string; properties?: Record<string, unknown> }) => void
+ flush: () => Promise<void>
+ shutdown: () => Promise<void>
+}
+
+function makeStubPostHogClient(events: CapturedEvent[]): StubPostHogClient {
+ return {
+ capture: ({ event, properties }) => {
+ events.push({ event, properties: properties ?? {} })
+ },
+ flush: async () => {},
+ shutdown: async () => {},
+ }
+}
+
+function makeTool(overrides: Partial<Tool<ZodObjectAny>>): Tool<ZodObjectAny> {
+ return {
+ name: 'mock-tool',
+ title: 'Mock tool',
+ description: 'A mock tool for testing',
+ schema: z.object({}),
+ scopes: [],
+ annotations: {
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ readOnlyHint: true,
+ },
+ handler: async () => 'ok',
+ ...overrides,
+ }
+}
+
+const mockContext = { getDistinctId: async () => 'distinct-1' } as unknown as Context
+
+type ExecHarness = {
+ client: Client
+ events: CapturedEvent[]
+ cleanup: () => Promise<void>
+}
+
+async function buildExecHarness(allTools: Tool<ZodObjectAny>[]): Promise<ExecHarness> {
+ const events: CapturedEvent[] = []
+ const server = new McpServer({ name: 'test-mcp', version: '1.0.0' })
+
+ const execTool = createExecTool(allTools, mockContext, 'exec tool', 'command reference', undefined)
+ server.registerTool(
+ execTool.name,
+ { title: execTool.title, description: execTool.description, inputSchema: execTool.schema.shape },
+ (async (params: { command: string }) => {
+ const result = await execTool.handler(mockContext, params)
+ return { content: [{ type: 'text' as const, text: String(result) }] }
+ }) as Parameters<typeof server.registerTool>[2]
+ )
+
+ const resolveExecInnerToolCall = createExecInnerToolCallResolver(allTools)
+
+ track(server, {
+ apiKey: 'phc_test',
+ posthogClient: makeStubPostHogClient(events),
+ posthogOptions: { flushAt: 1, flushInterval: 0, host: 'https://test.posthog.com' },
+ enableTracing: true,
+ eventProperties: (request) => {
+ const innerCall = resolveExecInnerToolCall(request)
+ return innerCall
+ ? {
+ $mcp_exec_tool_call_name: innerCall.name,
+ $mcp_exec_tool_call_description: innerCall.description,
+ }
+ : {}
+ },
+ })
+
+ const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: {} })
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
+ await Promise.all([client.connect(clientTransport), server.server.connect(serverTransport)])
+
+ return {
+ client,
+ events,
+ cleanup: async () => {
+ await clientTransport.close?.()
+ await serverTransport.close?.()
+ },
+ }
+}
+
+// Poll the captured events for a matching record instead of sleeping a fixed
+// duration — flushAt:1 makes capture effectively immediate, but timer-based
+// waits are flake-prone under CI load.
+async function waitForEvent(
+ events: CapturedEvent[],
+ predicate: (event: CapturedEvent) => boolean,
+ timeoutMs = 1000
+): Promise<CapturedEvent | undefined> {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ const match = events.find(predicate)
+ if (match) {
+ return match
+ }
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ }
+ return events.find(predicate)
+}
+
+describe('$mcp_exec_tool_call_* end-to-end', () => {
+ it('lands on the mcp_tool_call event when exec invokes a known inner tool', async () => {
+ const allTools = [
+ makeTool({ name: 'execute-sql', description: 'Run a HogQL/SQL query against PostHog.' }),
+ makeTool({ name: 'feature-flag-get-all', description: 'List feature flags in the project.' }),
+ ]
+ const { client, events, cleanup } = await buildExecHarness(allTools)
+
+ try {
+ await client.request(
+ {
+ method: 'tools/call',
+ params: { name: 'exec', arguments: { command: 'call execute-sql {}' } },
+ },
+ CallToolResultSchema
+ )
+
+ const toolCallEvent = await waitForEvent(events, (e) => e.event === 'mcp_tool_call')
+
+ expect(toolCallEvent, 'mcp_tool_call event should be captured').not.toBeUndefined()
+ expect(toolCallEvent?.properties.$mcp_tool_name).toBe('exec')
+ // The SDK property reports the *outer* tool's description (exec) — which is
+ // exactly the uninformative case the dotcom properties exist to fix.
+ expect(toolCallEvent?.properties.$mcp_tool_description).toBe('exec tool')
+ // The dotcom-side properties carry the real inner-tool name + description.
+ expect(toolCallEvent?.properties.$mcp_exec_tool_call_name).toBe('execute-sql')
+ expect(toolCallEvent?.properties.$mcp_exec_tool_call_description).toBe(
+ 'Run a HogQL/SQL query against PostHog.'
+ )
+ } finally {
+ await cleanup()
+ }
+ })
+
+ it('omits $mcp_exec_tool_call_* for non-call verbs', async () => {
+ const allTools = [makeTool({ name: 'execute-sql', description: 'Run a HogQL/SQL query against PostHog.' })]
+ const { client, events, cleanup } = await buildExecHarness(allTools)
+
+ try {
+ // `info` verb references a tool but doesn't invoke it — should NOT
+ // emit the inner-call name or description.
+ await client.request(
+ {
+ method: 'tools/call',
+ params: { name: 'exec', arguments: { command: 'info execute-sql' } },
+ },
+ CallToolResultSchema
+ )
+
+ const toolCallEvent = await waitForEvent(events, (e) => e.event === 'mcp_tool_call')
+
+ expect(toolCallEvent).not.toBeUndefined()
+ expect(toolCallEvent?.properties).not.toHaveProperty('$mcp_exec_tool_call_name')
+ expect(toolCallEvent?.properties).not.toHaveProperty('$mcp_exec_tool_call_description')
+ } finally {
+ await cleanup()
+ }
+ })
+})
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 2fcb12566448..5ce80667fdf0 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -9,7 +9,7 @@ import { z } from 'zod'
import { InstructionsFormatter } from '@/lib/instructions-formatter'
import { SessionManager } from '@/lib/SessionManager'
import { getToolsFromContext } from '@/tools'
-import { createExecTool, type ExecInnerCallProperties } from '@/tools/exec'
+import { createExecTool, type ExecInnerCallProperties, parseExecCallInnerToolName } from '@/tools/exec'
import { getToolDefinition } from '@/tools/toolDefinitions'
import {
POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,
@@ -340,6 +340,33 @@ describe('exec tool', () => {
})
})
+ describe('parseExecCallInnerToolName', () => {
+ it.each([
+ ['call my-tool {}', 'my-tool'],
+ ['call my-tool', 'my-tool'],
+ ['call --json my-tool {}', 'my-tool'],
+ [' call my-tool {} ', 'my-tool'],
+ ])('extracts inner tool name from "%s"', (command, expected) => {
+ expect(parseExecCallInnerToolName(command)).toBe(expected)
+ })
+
+ // Non-call verbs (info/schema/search/tools) are intentionally undefined —
+ // the resolver only fires for real invocations, not for browsing/inspection.
+ it.each([
+ ['info my-tool'],
+ ['schema my-tool'],
+ ['search query-'],
+ ['tools'],
+ ['call'],
+ ['call '],
+ ['call --json'],
+ [''],
+ [' '],
+ ])('returns undefined for "%s"', (command) => {
+ expect(parseExecCallInnerToolName(command)).toBeUndefined()
+ })
+ })
+
describe('schema snapshot', () => {
function createSnapshotContext(): Context {
return {
diff --git a/services/mcp/tests/unit/posthog-mcp-analytics.test.ts b/services/mcp/tests/unit/posthog-mcp-analytics.test.ts
index 3efdc5b310f6..00a83de4d502 100644
--- a/services/mcp/tests/unit/posthog-mcp-analytics.test.ts
+++ b/services/mcp/tests/unit/posthog-mcp-analytics.test.ts
@@ -48,13 +48,13 @@ describe('initPostHogMcpAnalytics', () => {
function getTrackOptions(): {
identify: () => Promise<unknown>
eventTags: () => Promise<Record<string, string>>
- eventProperties: () => Promise<Record<string, unknown>>
+ eventProperties: (request?: unknown) => Promise<Record<string, unknown>>
} {
const call = vi.mocked(track).mock.calls[0]!
return call[1] as {
identify: () => Promise<unknown>
eventTags: () => Promise<Record<string, string>>
- eventProperties: () => Promise<Record<string, unknown>>
+ eventProperties: (request?: unknown) => Promise<Record<string, unknown>>
}
}
@@ -213,6 +213,116 @@ describe('initPostHogMcpAnalytics', () => {
})
})
+ it.each<{
+ scenario: string
+ resolverReturn: { name: string; description: string } | undefined
+ expectedProperties: Record<string, unknown>
+ absentProperties: string[]
+ }>([
+ {
+ scenario: 'adds name + description when the resolver returns an inner tool',
+ resolverReturn: { name: 'execute-sql', description: 'Run a HogQL/SQL query.' },
+ expectedProperties: {
+ $mcp_exec_tool_call_name: 'execute-sql',
+ $mcp_exec_tool_call_description: 'Run a HogQL/SQL query.',
+ },
+ absentProperties: [],
+ },
+ {
+ scenario: 'omits both properties when the resolver returns undefined',
+ resolverReturn: undefined,
+ expectedProperties: {},
+ absentProperties: ['$mcp_exec_tool_call_name', '$mcp_exec_tool_call_description'],
+ },
+ ])('eventProperties $scenario', async ({ resolverReturn, expectedProperties, absentProperties }) => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+ const resolveExecInnerToolCall = vi.fn().mockReturnValue(resolverReturn)
+
+ await initPostHogMcpAnalytics(server, identity, {
+ contextEnabled: false,
+ reportMissingEnabled: false,
+ resolveExecInnerToolCall,
+ })
+
+ const fakeRequest = { params: { name: 'exec', arguments: { command: 'call execute-sql {}' } } }
+ const properties = await getTrackOptions().eventProperties(fakeRequest)
+
+ expect(resolveExecInnerToolCall).toHaveBeenCalledWith(fakeRequest)
+ for (const [key, value] of Object.entries(expectedProperties)) {
+ expect(properties[key]).toBe(value)
+ }
+ for (const key of absentProperties) {
+ expect(properties).not.toHaveProperty(key)
+ }
+ // Identity-derived properties should always be there regardless of resolver outcome.
+ expect(properties.$mcp_organization_id).toBe('org-789')
+ })
+
+ it('eventProperties does not call the resolver when none is configured', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ await initPostHogMcpAnalytics(server, identity)
+
+ const properties = await getTrackOptions().eventProperties({
+ params: { name: 'exec', arguments: { command: 'call execute-sql {}' } },
+ })
+
+ expect(properties).not.toHaveProperty('$mcp_exec_tool_call_name')
+ expect(properties).not.toHaveProperty('$mcp_exec_tool_call_description')
+ })
+
+ it('eventProperties attaches $mcp_exec_inner_tool_names on tools/list when execInnerToolNames is configured', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+ const execInnerToolNames = ['execute-sql', 'feature-flag-get-all', 'insight-get']
+
+ await initPostHogMcpAnalytics(server, identity, {
+ contextEnabled: false,
+ reportMissingEnabled: false,
+ execInnerToolNames,
+ })
+
+ const listRequest = { method: 'tools/list', params: {} }
+ const properties = await getTrackOptions().eventProperties(listRequest)
+
+ expect(properties.$mcp_exec_inner_tool_names).toEqual(execInnerToolNames)
+ // Other inner-call properties should be absent since this isn't a `call` request.
+ expect(properties).not.toHaveProperty('$mcp_exec_tool_call_name')
+ })
+
+ it('eventProperties does not attach $mcp_exec_inner_tool_names on non-list methods', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ await initPostHogMcpAnalytics(server, identity, {
+ contextEnabled: false,
+ reportMissingEnabled: false,
+ execInnerToolNames: ['execute-sql'],
+ })
+
+ const callRequest = { method: 'tools/call', params: { name: 'exec', arguments: { command: 'call execute-sql {}' } } }
+ const properties = await getTrackOptions().eventProperties(callRequest)
+
+ expect(properties).not.toHaveProperty('$mcp_exec_inner_tool_names')
+ })
+
+ it('eventProperties does not attach $mcp_exec_inner_tool_names when execInnerToolNames is empty', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ await initPostHogMcpAnalytics(server, identity, {
+ contextEnabled: false,
+ reportMissingEnabled: false,
+ execInnerToolNames: [],
+ })
+
+ const properties = await getTrackOptions().eventProperties({ method: 'tools/list', params: {} })
+
+ expect(properties).not.toHaveProperty('$mcp_exec_inner_tool_names')
+ })
+
it('eventProperties callback omits $groups when analytics context is unavailable', async () => {
const server = new McpServer({ name: 'test', version: '1.0.0' })
const identity = createMockIdentity({