: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): capture data catalog behavior telemetry for online evals (#77460)
Thiago Salvatoref9a2ac3d3ab4
diff --git a/products/data_catalog/docs/production-monitoring.md b/products/data_catalog/docs/production-monitoring.mdnew file mode 100644index 000000000000..bf138d37862c--- /dev/null+++ b/products/data_catalog/docs/production-monitoring.md@@ -0,0 +1,52 @@+# Production monitoring of semantic-layer agent behavior++How we validate, on live hosted-MCP traffic, that agents honor the data catalog: checking `system.information_schema.metrics` before hand-writing SQL for a metric, running canonical metrics instead of re-deriving them, proposing metrics/certifications when appropriate, and preferring certified sources and accepted relationships.++All of this lives in PostHog's internal telemetry project (US project 2), where the hosted MCP server captures its analytics. The monitoring has three layers.++## 1. Dashboard tiles (HogQL over existing telemetry)++Tile group `7 · Agent behavior` on the "Data catalog usage" dashboard (project 2, dashboard 1902365):++- `7 · Catalog-first rate for KPI sessions`: share of KPI-intent SQL sessions whose metrics-catalog lookup preceded their first data-bearing query.+- `7 · KPI sessions that skip the catalog`: KPI-intent sessions with raw SQL and no catalog lookup or `data-catalog-metric-run` call.+- `7 · Semantic-layer lookups in SQL`: weekly lookups against `information_schema.metrics`, the `certification` column on `information_schema.tables`, and `information_schema.relationships`.+- `7 · KPI derivations vs agent proposals`: derivations without catalog engagement next to sessions where an agent called a catalog write tool.++Data sources: `$mcp_tool_call` events (tool names, ordering per `$session_id`) and the per-`execute-sql` `$ai_generation` events (`$ai_output_choices` carries the SQL text; `posthog.ai_events`, ~30 day retention). Session classification is regex-heuristic: SQL matching `information_schema.metrics` is a catalog lookup, other `information_schema`/`system.` references are schema discovery, everything else is data-bearing; KPI intent is a keyword match on the agent's stated intent.++## 2. Online evaluations (AI evals, `/ai-evals` in project 2)++**Live today:** `MCP: catalog checked before KPI derivation` (Hog, trace target, inactivity settle 5 min, 100% rollout, N/A allowed). Fails a session with KPI intent and data-bearing SQL but no prior successful catalog lookup and no `data-catalog-metric-run` span. Deterministic, no LLM cost. Its Hog source mirrors the tile classification above; results land as `$ai_evaluation` events.++### Writing Hog that survives real traces++A trace evaluation runs against traces of up to 500 events under a 10 second budget and a 64 MB VM, and **any** Hog failure disables the evaluation outright (`disables_evaluation=True` on `hog_error`), so a slow evaluation stops scoring until someone re-enables it. The first version of the evaluation above was disabled within minutes by `Execution timed out (10s limit exceeded)`. Three things caused it, all worth avoiding:++- **`and` does not short-circuit.** `Operation.AND` pops every operand, so `e.event == '$ai_span' and e.properties.$ai_span_name == '...'` does the property lookups on every event regardless of type. Nest `if` blocks instead of chaining conditions.+- **Regexes are compiled per call.** `=~*` with an alternation, evaluated once per event, dominated the budget. Use `lower()` once and then `like`.+- **Stop scanning once the verdict is latched.** Guard the expensive string work behind the state that makes it irrelevant, and `return` from inside the loop when no later event can change the answer.++Memory is a separate, rarer failure: reading a global does `deepcopy(...)` onto the 64 MB stack, so an oversized trace can exceed it before any of your code runs. Traces above 500 events are skipped upstream (`trace_too_large`), which catches the worst runaways, but a trace that passes that check with large payloads can still fail, and there is no Hog-side mitigation. Validate with `llma-evaluation-test-hog` against real traces before enabling, and check the evaluation's `status_reason_detail` if it goes quiet.++**Pending `trackToolSpan` deployment** (`services/mcp/src/hono/analytics.ts`): three LLM-judge trace evaluations, sampled low (5-10%) via `rollout_percentage`:++1. **Metric bypass**: the `$ai_span` for a catalog lookup carries the results (`$ai_output_state`), so the judge sees which metrics the lookup returned. Verdict: given an approved, non-drifted metric matching the session's intent, did the client run it via `data-catalog-metric-run`, or hand-write SQL for the same number?+2. **Proposal appropriateness**: given the session's intents, SQL, and tool spans, did the agent derive a reusable business metric with no canonical definition, and if so did it propose or offer to catalog it (landing `proposed`, disclosed as such)? One-off exploration must not trigger speculative proposals.+3. **Trust adherence**: given certification/relationship metadata the agent read, did the final SQL prefer `certified` over `deprecated` sources and use accepted join keys from `information_schema.relationships`?++Evaluation definitions are per-team database rows, not repo code; this document is their source of truth. When creating or editing them, validate Hog with the evaluation test endpoint (`llma-evaluation-test-hog`) against real traces first, and spot-check judge verdicts at a tiny rollout before trusting rates.++## 3. Instrumentation contract (`services/mcp`)++- Every MCP analytics event is stamped with `mcp_data_catalog_enabled` (the evaluated `product-data-catalog` flag) for cohort splits.+- `trackExecuteSqlGeneration` captures one `$ai_generation` per `execute-sql` call with the intent and SQL text; `$ai_trace_id` is the MCP session uuid, so a session is one trace.+- `trackToolSpan` captures an `$ai_span` (args + truncated results) for every tool by default, joining the same session trace, so a trace-target evaluation sees a call's args and result. Secret-bearing fields (passwords, `client_secret`, API keys, tokens) are redacted from both input and output before capture, so defaulting every tool on never lands a credential in telemetry.+- `execute-sql` is the one exception, because its payload is the query result and it serves all traffic. Spans are captured for its metadata queries only (SQL referencing `information_schema`, ~4.5% of calls): those results are small and describe what the agent knew about the workspace before writing its next query. That covers catalog lookups of `metrics`, `certifications`, and `relationships` without the telemetry layer naming them. The gate strips SQL comments and string literals before matching, so the marker inside a comment or literal on a data query does not pull the result into telemetry.++## Known limits++- The evaluation scheduler triggers only on `$ai_generation`, so sessions with no `execute-sql` call are never evaluated; they remain visible in the dashboard tiles via `$mcp_tool_call`.+- `posthog.ai_events` retention (~30 days) bounds every SQL-text-based measure.+- A single failing trace disables the whole evaluation rather than skipping that trace, so a rare oversized trace can silently stop scoring. Watch for the auto-disable email.+- The customer's catalog contents are not directly joinable from telemetry; "a matching metric existed" is judged from lookup results in spans, not from the source of truth.diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex bde4c9718599..6716c15f164b 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -2,7 +2,7 @@ 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'+import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION, PRODUCT_DATA_CATALOG_FLAG } from '@/lib/constants'import { getPostHogClient } from '@/lib/posthog'import {buildMCPAnalyticsGroups,@@ -60,6 +60,10 @@ function buildBaseProperties(: {}),mcp_runtime: 'hono',mcp_vendor_client: clientIdentity.mcpVendorClient,+ // Stamped on every event so catalog-on vs catalog-off cohorts can be split+ // in analytics; the flag only gates instructions content, so nothing else+ // on the event reveals whether the agent was steered toward the catalog.+ mcp_data_catalog_enabled: state.toolFeatureFlags?.[PRODUCT_DATA_CATALOG_FLAG] === true,...buildMCPSessionAnalyticsProperties(state.sessionContext),}return { properties, groups }@@ -216,6 +220,127 @@ export async function trackExecuteSqlGeneration(}}+const METADATA_QUERY_MARKER = 'information_schema'+const MAX_SPAN_STATE_LENGTH = 30_000++export interface ToolSpanMeta {+ durationMs: number+ isError: boolean+ errorMessage?: string+ input?: unknown+ output?: unknown+}++// Comments and single-quoted string literals can carry the metadata marker+// without the query actually reading a metadata relation, so they're stripped+// before the check — otherwise a data query like `... WHERE 'information_schema'+// != ''` would be mis-tagged as metadata and its result captured.+function stripSqlCommentsAndLiterals(query: string): string {+ return query+ .replace(/--[^\n]*/g, ' ')+ .replace(/\/\*[\s\S]*?\*\//g, ' ')+ .replace(/'(?:''|[^'])*'/g, ' ')+}++function isMetadataQuery(query: string): boolean {+ return stripSqlCommentsAndLiterals(query).toLowerCase().includes(METADATA_QUERY_MARKER)+}++function shouldCaptureToolSpan(toolName: string, input: unknown): boolean {+ // execute-sql can't be captured wholesale: its payload is the query result,+ // which is the bulk of MCP response volume. Metadata queries are the+ // exception, because their results are small and describe what the agent+ // learned about the workspace before writing its next query, which is the+ // context an evaluation needs to judge that query.+ if (toolName !== EXECUTE_SQL_TOOL_NAME) {+ return true+ }+ const query = (input as { query?: unknown } | null | undefined)?.query+ return typeof query === 'string' && isMetadataQuery(query)+}++const REDACTED_VALUE = '[redacted]'++// Capturing every tool's raw args would land credentials in telemetry: tools+// like user-settings-update carry `password`/`current_password`, warehouse+// sources carry `client_secret`, and hog-function inputs carry `secret` values.+// Match errs toward redaction — an over-redacted eval field is harmless, a+// leaked credential is not. Deliberately excludes bare `key`/`id`/`token`, which+// are almost always identifiers or token counts an evaluation needs.+const SENSITIVE_KEY_PATTERN =+ /password|passwd|passphrase|secret|credential|private[_-]?key|access[_-]?key|api[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|authorization|bearer/i++function redactSecrets(value: unknown): unknown {+ if (Array.isArray(value)) {+ return value.map(redactSecrets)+ }+ if (value !== null && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value).map(([key, val]) => [+ key,+ SENSITIVE_KEY_PATTERN.test(key) ? REDACTED_VALUE : redactSecrets(val),+ ])+ )+ }+ return value+}++function serializeSpanState(value: unknown): string | undefined {+ if (value === undefined) {+ return undefined+ }+ try {+ const redacted = redactSecrets(value)+ const serialized = typeof redacted === 'string' ? redacted : JSON.stringify(redacted)+ return serialized?.slice(0, MAX_SPAN_STATE_LENGTH)+ } catch {+ return undefined+ }+}++/**+ * Captures an `$ai_span` for a tool call, joining the same MCP-session trace as+ * the execute-sql `$ai_generation` events. Trace-target online evaluations then+ * see a call's args AND result, neither of which `$mcp_tool_call` carries.+ *+ * Every tool is captured by default. `execute-sql` is the one exception: its+ * payload is the query result and it serves the bulk of MCP volume, so only its+ * metadata queries are captured (see {@link shouldCaptureToolSpan}).+ */+export async function trackToolSpan(toolName: string, state: ResolvedState, meta: ToolSpanMeta): Promise<void> {+ try {+ if (!shouldCaptureToolSpan(toolName, meta.input)) {+ return+ }+ const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)+ const { properties, groups } = buildBaseProperties(state, analyticsContext)+ const toolCategory = getToolCategory(toolName)+ const inputState = serializeSpanState(meta.input)+ const outputState = serializeSpanState(meta.output)++ getPostHogClient().capture({+ distinctId: state.distinctId,+ event: '$ai_span',+ groups,+ properties: {+ ...properties,+ ...(sessionUuid ? { $session_id: sessionUuid } : {}),+ $ai_trace_id: sessionUuid ?? randomUUID(),+ $ai_span_name: toolName,+ ...(toolCategory ? { $mcp_tool_category: toolCategory } : {}),+ ...(inputState !== undefined ? { $ai_input_state: inputState } : {}),+ ...(outputState !== undefined ? { $ai_output_state: outputState } : {}),+ $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 26e5d1c888ee..00cac4207629 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -24,7 +24,13 @@ import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { createRenderUiTool } from '@/tools/render-ui'import type { Context, ZodObjectAny } from '@/tools/types'-import { trackExecuteSqlGeneration, trackToolCall, trackToolsList, type ToolCallIntentMeta } from './analytics'+import {+ trackExecuteSqlGeneration,+ trackToolCall,+ trackToolSpan,+ trackToolsList,+ type ToolCallIntentMeta,+} from './analytics'import type { InstructionsBuilder } from './instructions'import { getEffectiveMCPClientContext } from './mcp-context'import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'@@ -250,6 +256,13 @@ export class ToolExecutor {)}+ void trackToolSpan(tool.name, state, {+ durationMs: duration,+ isError: false,+ input: validation.data,+ output: response,+ })+return response} catch (error: unknown) {toolCallsTotal.inc({ tool: tool.name, status: 'error' })@@ -280,6 +293,13 @@ export class ToolExecutor {)}+ void trackToolSpan(tool.name, state, {+ durationMs: Date.now() - startMs,+ isError: true,+ errorMessage: error instanceof Error ? error.message : String(error),+ input: validation.data,+ })+const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)return handleToolError(error, tool.name, state.distinctId, sessionUuid)}@@ -407,6 +427,13 @@ export class ToolExecutor {intentMeta)}+ void trackToolSpan(toolName, state, {+ durationMs: properties.duration_ms,+ isError: !properties.success,+ errorMessage: properties.error_message,+ input: properties.input,+ output: properties.output,+ })}const clientContext = getEffectiveMCPClientContext(state.requestContext, state.sessionContext)diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 4fa00aba2158..27f2f97a4fed 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -49,6 +49,12 @@ export interface ExecInnerCallProperties {input_tokens?: numberoutput_tokens?: numberinput?: Record<string, unknown>+ /**+ * The payload returned to the client, exactly as serialized. Consumed by the+ * `$ai_span` capture for data-catalog-relevant calls, which needs the tool's+ * result (e.g. which metrics a catalog lookup returned), not just its size.+ */+ output?: unknown}export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void@@ -642,6 +648,7 @@ export function createExecTool(input_tokens: estimateTokens(input),output_tokens: estimateTokens(outputText),input,+ output: outputText,})return outputText}@@ -684,6 +691,7 @@ export function createExecTool(input_tokens: estimateTokens(input),output_tokens: estimateResponseTokens(payload),input,+ output: payload,})return payload}@@ -708,6 +716,7 @@ export function createExecTool(input_tokens: estimateTokens(input),output_tokens: estimateTokens(outputText),input,+ output: outputText,})return outputText}diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex dd5f9ded0e43..ec2c12807bd4 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 { trackExecuteSqlGeneration, trackInitEvent, trackToolCall } from '@/hono/analytics'+import { trackExecuteSqlGeneration, trackInitEvent, trackToolCall, trackToolSpan } from '@/hono/analytics'import type { ResolvedState } from '@/hono/request-state-resolver'import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolDefinition } from '@/tools/toolDefinitions'@@ -310,4 +310,92 @@ describe('Hono MCP analytics contexts', () => {expect(mockCapture).not.toHaveBeenCalled()})})++ describe('trackToolSpan', () => {+ it.each([+ ['a non-execute-sql tool', 'data-catalog-metric-run', { name: 'mrr' }, true],+ ['any other non-execute-sql tool', 'query-logs', { query: 'SELECT 1' }, true],+ [+ 'execute-sql querying metadata',+ 'execute-sql',+ { query: 'SELECT name FROM system.information_schema.metrics' },+ true,+ ],+ ['execute-sql on plain data', 'execute-sql', { query: 'SELECT count() FROM events' }, false],+ [+ 'execute-sql with the marker only in a string literal',+ 'execute-sql',+ { query: "SELECT distinct_id FROM events WHERE 'information_schema' != ''" },+ false,+ ],+ [+ 'execute-sql with the marker only in a comment',+ 'execute-sql',+ { query: 'SELECT count() FROM events -- information_schema' },+ false,+ ],+ ])('gates capture for %s', async (_case, toolName, input, captured) => {+ await trackToolSpan(toolName, makeState(), { durationMs: 100, isError: false, input, output: 'rows' })++ const spanCalls = mockCapture.mock.calls.filter(([payload]) => payload.event === '$ai_span')+ expect(spanCalls).toHaveLength(captured ? 1 : 0)+ })++ it('joins the MCP session trace and truncates oversized results', async () => {+ await trackToolSpan('data-catalog-metric-run', makeState(), {+ durationMs: 1500,+ isError: false,+ input: { name: 'mrr' },+ output: 'x'.repeat(50_000),+ })++ const payload = mockCapture.mock.calls[0]![0]+ expect(payload.event).toBe('$ai_span')+ expect(payload.properties).toMatchObject({+ $ai_span_name: 'data-catalog-metric-run',+ // Must match the execute-sql generations' trace id, or the span+ // detaches from the session trace evaluations are scoped to.+ $ai_trace_id: 'session-uuid',+ $session_id: 'session-uuid',+ $ai_input_state: JSON.stringify({ name: 'mrr' }),+ $ai_latency: 1.5,+ $ai_is_error: false,+ $mcp_tool_category: 'Data catalog',+ })+ expect(payload.properties.$ai_output_state).toHaveLength(30_000)+ })++ it('records the error message on failed calls', async () => {+ await trackToolSpan('data-catalog-metric-run', makeState(), {+ durationMs: 200,+ isError: true,+ errorMessage: 'metric not found',+ input: { name: 'bogus' },+ })++ expect(mockCapture.mock.calls[0]![0].properties).toMatchObject({+ $ai_is_error: true,+ $ai_error: 'metric not found',+ })+ })++ it('redacts secret-bearing fields from captured input and output', async () => {+ // Capturing every tool by default would otherwise land user-settings /+ // warehouse-source credentials in telemetry.+ await trackToolSpan('user-settings-update', makeState(), {+ durationMs: 100,+ isError: false,+ input: { first_name: 'Ada', password: 'hunter2', payload: { client_secret: 'oauth-secret' } },+ output: { id: 1, api_key: 'phx_live_123' },+ })++ const { $ai_input_state, $ai_output_state } = mockCapture.mock.calls[0]![0].properties+ expect(JSON.parse($ai_input_state)).toEqual({+ first_name: 'Ada',+ password: '[redacted]',+ payload: { client_secret: '[redacted]' },+ })+ expect(JSON.parse($ai_output_state)).toEqual({ id: 1, api_key: '[redacted]' })+ })+ })})diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 8c51ed55781d..1e06ef90699e 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -22,6 +22,7 @@ vi.mock('@/hono/metrics', () => ({vi.mock('@/hono/analytics', () => ({trackToolCall: vi.fn(),trackExecuteSqlGeneration: vi.fn(),+ trackToolSpan: 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 410f333500a1..e7725989a5b4 100644--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts@@ -8,6 +8,7 @@ const { mockTrackToolCall, mockTrackExecuteSqlGeneration } = vi.hoisted(() => ({vi.mock('@/hono/analytics', () => ({trackToolCall: mockTrackToolCall,trackExecuteSqlGeneration: mockTrackExecuteSqlGeneration,+ trackToolSpan: vi.fn(),}))vi.mock('@/resources/internals', () => ({