:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): emit $ai_generation events for execute-sql tool calls (#68656)
Andy Zhao3758ee1ebf9f
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex e99f3f230c04..6eea5501a662 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto'+import type { MCPAnalyticsIntentSource } from '@posthog/mcp-analytics'import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'@@ -8,6 +10,7 @@ import {MCP_ANALYTICS_VERSION,type MCPAnalyticsContext,} from '@/lib/posthog/analytics'+import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { getToolCategory } from '@/tools/toolDefinitions'import { buildMCPSessionAnalyticsProperties } from './mcp-context'@@ -141,6 +144,59 @@ export async function trackToolCall(}}+export interface ExecuteSqlGenerationMeta {+ durationMs: number+ isError: boolean+ errorMessage?: string+}++/**+ * Manually captures an `$ai_generation` per `execute-sql` call — the client's LLM+ * authored the query; this server is the observer that sees intent and output+ * together. Lands in LLM analytics, where online evaluations (LLM judge / Hog) can+ * score it for anti-patterns on live traffic. `$ai_trace_id` is the MCP session+ * uuid, so a session's queries group into one trace.+ */+export async function trackExecuteSqlGeneration(+ toolName: string,+ args: unknown,+ state: ResolvedState,+ meta: ExecuteSqlGenerationMeta,+ intentMeta?: ToolCallIntentMeta+): Promise<void> {+ if (toolName !== EXECUTE_SQL_TOOL_NAME) {+ return+ }+ const query = (args as { query?: unknown } | null | undefined)?.query+ if (typeof query !== 'string' || query.length === 0) {+ return+ }+ try {+ const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)+ const { properties, groups } = buildBaseProperties(state, analyticsContext)++ getPostHogClient().capture({+ distinctId: state.distinctId,+ event: '$ai_generation',+ groups,+ properties: {+ ...properties,+ ...(sessionUuid ? { $session_id: sessionUuid } : {}),+ $ai_trace_id: sessionUuid ?? randomUUID(),+ $ai_span_name: EXECUTE_SQL_TOOL_NAME,+ $ai_input: [{ role: 'user', content: intentMeta?.intent ?? '' }],+ $ai_output_choices: [{ role: 'assistant', content: query }],+ $ai_latency: meta.durationMs / 1000,+ $ai_is_error: meta.isError,+ ...(meta.errorMessage ? { $ai_error: meta.errorMessage } : {}),+ },+ })+ } catch {+ // never break the request for analytics+ }+}+export async function trackToolsList(toolNames: string[], state: ResolvedState): Promise<void> {try {const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 0b04e5ff9979..a79bd4fbc86c 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -19,10 +19,11 @@ import {import { estimateTokens } from '@/lib/estimate-tokens'import { getPostHogClient } from '@/lib/posthog'import { createExecTool, formatInputValidationError, type ExecInnerCallTracker } from '@/tools/exec'+import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { createRenderUiTool } from '@/tools/render-ui'import type { Context, ZodObjectAny } from '@/tools/types'-import { trackToolCall, trackToolsList, type ToolCallIntentMeta } from './analytics'+import { trackExecuteSqlGeneration, trackToolCall, trackToolsList, type ToolCallIntentMeta } from './analytics'import type { InstructionsBuilder } from './instructions'import { getEffectiveMCPClientContext } from './mcp-context'import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'@@ -83,7 +84,7 @@ export class ToolExecutor {const filteredTools = this.catalog.getPreBuiltEntries().filter((e) => nameSet.has(e.name))return filteredTools.map((entry) => {- if (entry.name === 'execute-sql') {+ if (entry.name === EXECUTE_SQL_TOOL_NAME) {return {...entry,description: this.instructionsBuilder.formatExecuteSqlDescription(state.toolFeatureFlags),@@ -225,6 +226,16 @@ export class ToolExecutor {intentMeta)+ if (tool.name === EXECUTE_SQL_TOOL_NAME) {+ void trackExecuteSqlGeneration(+ tool.name,+ validation.data,+ state,+ { durationMs: duration, isError: false },+ intentMeta+ )+ }+return response} catch (error: unknown) {toolCallsTotal.inc({ tool: tool.name, status: 'error' })@@ -240,6 +251,20 @@ export class ToolExecutor {intentMeta)+ if (tool.name === EXECUTE_SQL_TOOL_NAME) {+ void trackExecuteSqlGeneration(+ tool.name,+ validation.data,+ state,+ {+ durationMs: Date.now() - startMs,+ isError: true,+ errorMessage: error instanceof Error ? error.message : String(error),+ },+ intentMeta+ )+ }+const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)return handleToolError(error, tool.name, state.distinctId, sessionUuid)}@@ -251,7 +276,7 @@ export class ToolExecutor {intentMeta?: ToolCallIntentMeta): Promise<unknown> {const execMetrics: ExecMetricState = { innerToolName: undefined }- const resolved = this.resolveExecTool(state, execMetrics)+ const resolved = this.resolveExecTool(state, execMetrics, intentMeta)const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>const validation = resolved.schema.safeParse(toolArgs, { reportInput: true })@@ -328,7 +353,11 @@ export class ToolExecutor {}}- private resolveExecTool(state: ResolvedState, execMetrics: ExecMetricState): ResolvedTool {+ private resolveExecTool(+ state: ResolvedState,+ execMetrics: ExecMetricState,+ intentMeta?: ToolCallIntentMeta+ ): ResolvedTool {const commandReference = this.instructionsBuilder.buildExecCommandReference(state)const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {@@ -346,6 +375,19 @@ export class ToolExecutor {if (!properties.validation_error) {toolCallDurationSeconds.observe({ tool: toolName, status }, properties.duration_ms / 1000)}+ if (toolName === EXECUTE_SQL_TOOL_NAME && properties.input) {+ void trackExecuteSqlGeneration(+ toolName,+ properties.input,+ state,+ {+ durationMs: properties.duration_ms,+ isError: !properties.success,+ errorMessage: properties.error_message,+ },+ intentMeta+ )+ }}const clientContext = getEffectiveMCPClientContext(state.requestContext, state.sessionContext)@@ -353,7 +395,7 @@ export class ToolExecutor {// Override it with the same flag-aware prompt tools-mode advertises, so the// information_schema steering (or its absence) matches across both modes.const execTools = state.allTools.map((tool) =>- tool.name === 'execute-sql'+ tool.name === EXECUTE_SQL_TOOL_NAME? {...tool,description: this.instructionsBuilder.formatExecuteSqlDescription(state.toolFeatureFlags),diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex cfccfd517326..3d8da7885cdc 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -8,8 +8,8 @@ import { estimateTokens } from '@/lib/estimate-tokens'import { formatResponse } from '@/lib/response'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'-import type { ScopeGatedTool } from './toolDefinitions'import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'+import type { ScopeGatedTool } from './toolDefinitions'import {POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,POSTHOG_META_KEY,@@ -41,6 +41,7 @@ export interface ExecInnerCallProperties {*/input_tokens?: numberoutput_tokens?: number+ input?: Record<string, unknown>}export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void@@ -437,6 +438,7 @@ export function createExecTool(success: false,output_format: useJson ? 'json' : 'text',error_message: err instanceof Error ? err.message : String(err),+ input,})throw err}@@ -472,6 +474,7 @@ export function createExecTool(output_format: 'structured',input_tokens: estimateTokens(input),output_tokens: estimateResponseTokens(payload),+ input,})return payload}@@ -499,6 +502,7 @@ export function createExecTool(output_format: useJson ? 'json' : 'text',input_tokens: estimateTokens(input),output_tokens: estimateTokens(outputText),+ input,})return outputText}diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex 1c10dc35d5f4..112dd61b9a78 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -23,6 +23,7 @@ import notebookEdit from './notebooks/edit'import setActiveOrganization from './organizations/setActive'// PostHog AI toolsimport {+ EXECUTE_SQL_TOOL_NAME,executeSql,externalDataSourcesDbSchema,externalDataSourcesJobs,@@ -90,7 +91,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {'agent-resolve-resource': resolveResource,// PostHog AI tools- 'execute-sql': executeSql,+ [EXECUTE_SQL_TOOL_NAME]: executeSql,'read-data-schema': readDataSchema,'read-data-warehouse-schema': readDataWarehouseSchema,diff --git a/services/mcp/src/tools/posthogAiTools/executeSql.ts b/services/mcp/src/tools/posthogAiTools/executeSql.tsindex 580b86bee234..326afa6a0347 100644--- a/services/mcp/src/tools/posthogAiTools/executeSql.ts+++ b/services/mcp/src/tools/posthogAiTools/executeSql.ts@@ -5,6 +5,8 @@ import type { Context, ToolBase } from '@/tools/types'import { invokeMcpTool } from './invokeTool'+export const EXECUTE_SQL_TOOL_NAME = 'execute-sql'+const schema = ExecuteSQLSchematype Params = z.infer<typeof schema>@@ -27,7 +29,7 @@ export const executeSqlHandler: ToolBase<typeof schema, string>['handler'] = asy}const tool = (): ToolBase<typeof schema, string> => ({- name: 'execute-sql',+ name: EXECUTE_SQL_TOOL_NAME,schema,handler: executeSqlHandler,})diff --git a/services/mcp/src/tools/posthogAiTools/index.ts b/services/mcp/src/tools/posthogAiTools/index.tsindex aa7ec1bf9820..406e768c1091 100644--- a/services/mcp/src/tools/posthogAiTools/index.ts+++ b/services/mcp/src/tools/posthogAiTools/index.ts@@ -1,4 +1,4 @@-export { default as executeSql } from './executeSql'+export { default as executeSql, EXECUTE_SQL_TOOL_NAME } from './executeSql'export { default as externalDataSourcesDbSchema } from './externalDataSourcesDbSchema'export { default as externalDataSourcesJobs } from './externalDataSourcesJobs'export { default as externalDataSourcesPreview } from './externalDataSourcesPreview'diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex c6cdbad017e8..fde500e83b43 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -15,7 +15,7 @@ vi.mock('@/lib/posthog', () => ({})),}))-import { trackInitEvent, trackToolCall } from '@/hono/analytics'+import { trackExecuteSqlGeneration, trackInitEvent, trackToolCall } from '@/hono/analytics'import type { ResolvedState } from '@/hono/request-state-resolver'function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {@@ -125,4 +125,56 @@ describe('Hono MCP analytics contexts', () => {expect(mockCaptureToolCall.mock.calls[0]![0].properties).not.toHaveProperty('$mcp_tool_category')})++ describe('trackExecuteSqlGeneration', () => {+ it('emits an $ai_generation carrying the intent as input and the HogQL as output', async () => {+ await trackExecuteSqlGeneration(+ 'execute-sql',+ { query: 'SELECT count() FROM events' },+ makeState(),+ { durationMs: 1500, isError: false },+ { intent: 'count yesterday signups' }+ )++ expect(mockCapture).toHaveBeenCalledTimes(1)+ const payload = mockCapture.mock.calls[0]![0]+ expect(payload.event).toBe('$ai_generation')+ expect(payload.distinctId).toBe('distinct-id')+ expect(payload.properties).toMatchObject({+ $ai_span_name: 'execute-sql',+ $ai_trace_id: 'session-uuid',+ $session_id: 'session-uuid',+ $ai_input: [{ role: 'user', content: 'count yesterday signups' }],+ $ai_output_choices: [{ role: 'assistant', content: 'SELECT count() FROM events' }],+ $ai_latency: 1.5,+ $ai_is_error: false,+ // Rides the same base MCP context as every other event, so+ // evaluations can condition on client/session properties.+ $mcp_client_name: 'Claude Desktop',+ })+ })++ it('flags failed calls so evaluations can target errored SQL too', async () => {+ await trackExecuteSqlGeneration('execute-sql', { query: 'SELECT bogus' }, makeState(), {+ durationMs: 200,+ isError: true,+ errorMessage: 'Unknown table',+ })++ expect(mockCapture.mock.calls[0]![0].properties).toMatchObject({+ $ai_is_error: true,+ $ai_error: 'Unknown table',+ })+ })++ it.each([+ ['a different tool', 'query-logs', { query: 'SELECT 1' }],+ ['a missing query', 'execute-sql', {}],+ ['a non-string query', 'execute-sql', { query: 42 }],+ ])('does not emit for %s', async (_case, toolName, args) => {+ await trackExecuteSqlGeneration(toolName, args, makeState(), { durationMs: 5, isError: false })++ expect(mockCapture).not.toHaveBeenCalled()+ })+ })})diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex d755cecf11c1..4562de03ae2c 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -21,6 +21,7 @@ vi.mock('@/hono/metrics', () => ({vi.mock('@/hono/analytics', () => ({trackToolCall: vi.fn(),+ trackExecuteSqlGeneration: vi.fn(),}))vi.mock('@/resources/internals', () => ({diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.tsindex cf161d89cd90..2975f971d841 100644--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts@@ -1,9 +1,13 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-const { mockTrackToolCall } = vi.hoisted(() => ({ mockTrackToolCall: vi.fn() }))+const { mockTrackToolCall, mockTrackExecuteSqlGeneration } = vi.hoisted(() => ({+ mockTrackToolCall: vi.fn(),+ mockTrackExecuteSqlGeneration: vi.fn(),+}))vi.mock('@/hono/analytics', () => ({trackToolCall: mockTrackToolCall,+ trackExecuteSqlGeneration: mockTrackExecuteSqlGeneration,}))vi.mock('@/resources/internals', () => ({@@ -99,12 +103,42 @@ describe('ToolExecutor token estimates', () => {beforeEach(async () => {mockTrackToolCall.mockClear()+ mockTrackExecuteSqlGeneration.mockClear()catalog = new ToolCatalog()await catalog.warmup()executor = new ToolExecutor(catalog, new InstructionsBuilder(''))})describe('direct tool calls', () => {+ it('emits the execute-sql generation with the validated args', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue({+ name: 'execute-sql',+ base: {+ schema: z.object({ query: z.string() }),+ handler: vi.fn().mockResolvedValue('ok'),+ },+ } as any)++ await executor.handleToolCall(+ { name: 'execute-sql', arguments: { query: 'SELECT 1' } },+ makeState([{ name: 'execute-sql' }])+ )++ expect(mockTrackExecuteSqlGeneration).toHaveBeenCalledTimes(1)+ const [toolName, args, , meta] = mockTrackExecuteSqlGeneration.mock.calls[0]!+ expect(toolName).toBe('execute-sql')+ expect(args).toEqual({ query: 'SELECT 1' })+ expect(meta.isError).toBe(false)+ })++ it('does not emit a generation for other tools', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('my-tool') as any)++ await executor.handleToolCall({ name: 'my-tool', arguments: {} }, makeState([{ name: 'my-tool' }]))++ expect(mockTrackExecuteSqlGeneration).not.toHaveBeenCalled()+ })+it('measures output tokens from the returned text, not the re-serialized payload', async () => {const handlerResult = {rows: [diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 49730906932d..a6051b1eb612 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -230,14 +230,14 @@ describe('exec tool', () => {calls.push({ toolName, properties })}const exec = createExecTool(- [makeMockTool()],+ [makeMockTool({ schema: z.object({ query: z.string() }) })],mockContext,'test description','test command reference',undefined,tracker)- await exec.handler(mockContext, { command: 'call --json mock-tool' })+ await exec.handler(mockContext, { command: 'call --json mock-tool {"query":"SELECT 1"}' })expect(calls).toHaveLength(1)expect(calls[0]!.toolName).toBe('mock-tool')expect(calls[0]!.properties.success).toBe(true)@@ -245,6 +245,7 @@ describe('exec tool', () => {expect(typeof calls[0]!.properties.duration_ms).toBe('number')expect(calls[0]!.properties.input_tokens).toBeGreaterThan(0)expect(calls[0]!.properties.output_tokens).toBeGreaterThan(0)+ expect(calls[0]!.properties.input).toEqual({ query: 'SELECT 1' })})it('estimates inner output tokens from the serialized output (TOON vs JSON)', async () => {