: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
fix(experiments/mcp): Strip bulk fields from experiment-results-get (#59599)
Marcel Poelker251cb34f2572
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 28a9ea71e8a1..6ea6e3042f58 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -17,7 +17,7 @@}},"experiment-results-get": {- "description": "Get experiment metric results and exposure data in one call. Each row in `metrics.primary.results` and `metrics.secondary.results` carries a self-describing `metric` summary: `uuid`, `name` (the label users see in the experiment UI), `metric_type`, `goal`, and `source` — `inline` for metrics defined on the experiment, `shared` for metrics attached via a saved metric. For `shared` rows, `saved_metric_id` and `saved_metric_name` identify the underlying saved metric; both are `null` for `inline` rows. Rows are ordered to match the experiment UI (`primary_metrics_ordered_uuids` / `secondary_metrics_ordered_uuids`). A row whose underlying metric query failed is kept with `data: null` so positions stay aligned with the ordered UUIDs — check `data === null` to detect failures. The raw source surfaces (`experiment.metrics`, `experiment.metrics_secondary`, `experiment.saved_metrics`) are preserved on the response for callers who want to audit them, but you do not need to reconcile them yourself — the result rows already merge inline and shared. Only works with new experiments (not legacy `ExperimentTrendsQuery` / `ExperimentFunnelsQuery`).",+ "description": "Get experiment metric results and exposure data in one call. Each row in `metrics.primary.results` and `metrics.secondary.results` carries a self-describing `metric` summary: `uuid`, `name` (the label users see in the experiment UI), `metric_type`, `goal`, and `source` — `inline` for metrics defined on the experiment, `shared` for metrics attached via a saved metric. For `shared` rows, `saved_metric_id` and `saved_metric_name` identify the underlying saved metric; both are `null` for `inline` rows. Rows are ordered to match the experiment UI (`primary_metrics_ordered_uuids` / `secondary_metrics_ordered_uuids`). A row whose underlying metric query failed is kept with `data: null` so positions stay aligned with the ordered UUIDs — check `data === null` to detect failures. The raw source surfaces (`experiment.metrics`, `experiment.metrics_secondary`, `experiment.saved_metrics`) are preserved on the response for callers who want to audit them, but you do not need to reconcile them yourself — the result rows already merge inline and shared. UI-only bulk fields are stripped from each `data` payload: `clickhouse_sql`, `hogql`, the legacy `insight` visualization payload, and the per-funnel-step session samples — `step_sessions` is removed from `baseline`, each `variant_results` entry, and from `baseline` / `variants[]` inside every `breakdown_results` entry. Statistical fields (`sum`, `sum_squares`, `step_counts`, `number_of_samples`, `credible_intervals`, per-breakdown stats, etc.) are preserved. Only works with new experiments (not legacy `ExperimentTrendsQuery` / `ExperimentFunnelsQuery`).","category": "Experiments","feature": "experiments","summary": "Get experiment metric and exposure results with self-describing per-metric metadata.",diff --git a/services/mcp/src/schema/experiments.ts b/services/mcp/src/schema/experiments.tsindex feeec95bfd79..ada8a92ef6dd 100644--- a/services/mcp/src/schema/experiments.ts+++ b/services/mcp/src/schema/experiments.ts@@ -245,6 +245,76 @@ export function buildMetricEntries(experiment: Experiment, slot: 'primary' | 'sereturn [...entries].sort((a, b) => position(a) - position(b))}+/**+ * Strip UI-only bulk fields from a query response. The compiled SQL bodies and the+ * per-step session samples can together account for ~90% of the payload. None of it+ * is usable by an MCP caller — `step_sessions` powers the frontend's funnel step-bar+ * "view sessions" linkbacks, `insight` is the rendered visualization payload for+ * the legacy trends/funnels charts, and anyone debugging a compiled query should+ * hit the dedicated query API directly. Statistical fields (sum, sum_squares,+ * step_counts, number_of_samples, credible_intervals, etc.) are left untouched,+ * including per-breakdown statistics in `breakdown_results` — the sessions inside+ * each breakdown entry are stripped, but the breakdown stats themselves are kept+ * because they are real per-segment analysis data.+ */+function stripBulkFields(data: unknown): unknown {+ if (data === null || typeof data !== 'object') {+ return data+ }+ const {+ clickhouse_sql: _omitSql,+ hogql: _omitHogql,+ insight: _omitInsight,+ baseline: rawBaseline,+ variant_results: rawVariantResults,+ breakdown_results: rawBreakdownResults,+ ...rest+ } = data as Record<string, unknown>++ const stripVariantBulk = (variant: unknown): unknown => {+ if (variant === null || typeof variant !== 'object') {+ return variant+ }+ const { step_sessions: _omitStepSessions, ...variantRest } = variant as Record<string, unknown>+ return variantRest+ }++ const stripBreakdownBulk = (entry: unknown): unknown => {+ if (entry === null || typeof entry !== 'object') {+ return entry+ }+ const { baseline: bdBaseline, variants: bdVariants, ...bdRest } = entry as Record<string, unknown>+ return {+ ...bdRest,+ ...(bdBaseline !== undefined ? { baseline: stripVariantBulk(bdBaseline) } : {}),+ ...(bdVariants !== undefined+ ? {+ variants: Array.isArray(bdVariants) ? bdVariants.map(stripVariantBulk) : bdVariants,+ }+ : {}),+ }+ }++ return {+ ...rest,+ ...(rawBaseline !== undefined ? { baseline: stripVariantBulk(rawBaseline) } : {}),+ ...(rawVariantResults !== undefined+ ? {+ variant_results: Array.isArray(rawVariantResults)+ ? rawVariantResults.map(stripVariantBulk)+ : rawVariantResults,+ }+ : {}),+ ...(rawBreakdownResults !== undefined+ ? {+ breakdown_results: Array.isArray(rawBreakdownResults)+ ? rawBreakdownResults.map(stripBreakdownBulk)+ : rawBreakdownResults,+ }+ : {}),+ }+}+export function transformExperimentResults(input: {experiment: Experimentexposures: ExperimentExposureQueryResponse@@ -297,7 +367,7 @@ export function transformExperimentResults(input: {results: results.map((result, index) => ({index,metric: entries[index]!.summary,- data: result,+ data: stripBulkFields(result),})),}}diff --git a/services/mcp/tests/unit/experiments-results-transform.test.ts b/services/mcp/tests/unit/experiments-results-transform.test.tsindex 70e5fbfa9ea5..a0d9be6c2a32 100644--- a/services/mcp/tests/unit/experiments-results-transform.test.ts+++ b/services/mcp/tests/unit/experiments-results-transform.test.ts@@ -11,6 +11,10 @@* - inline and shared metrics are merged into one ordered result stream,* with `source` tagged so callers can tell them apart* - row order follows `*_metrics_ordered_uuids` (the canonical UI ordering)+ * - UI-only bulk fields (`clickhouse_sql`, `hogql`, `insight`, and+ * `step_sessions` — including the copies inside each `breakdown_results`+ * entry) are stripped from each row's `data`, while statistical fields+ * (including per-breakdown stats) are preserved*/import { describe, expect, it } from 'vitest'@@ -249,4 +253,149 @@ describe('transformExperimentResults', () => {expect(result.metrics.primary.results[1]?.metric.name).toBe('Failed')expect(result.metrics.primary.results.map((r) => r.metric.uuid)).toEqual(['p-1', 'p-2', 'p-3'])})++ it('strips UI-only bulk fields (SQL bodies, step_sessions) but keeps statistical data', () => {+ // step_sessions is only used by the frontend's funnel step-bar, MCP callers can't+ // act on those event ids. clickhouse_sql / hogql are also debug-only. Strip both,+ // keep statistical fields intact.+ const experiment = makeExperiment({+ metrics: [{ uuid: 'p-1', name: 'Primary', metric_type: 'funnel' }],+ primary_metrics_ordered_uuids: ['p-1'],+ })+ const longSql = 'SELECT * FROM events WHERE 1=1'.repeat(2000)+ const stepSessions = [+ Array.from({ length: 100 }, (_, i) => ({ event_uuid: `e-${i}`, session_id: `s-${i}` })),+ Array.from({ length: 100 }, (_, i) => ({ event_uuid: `e2-${i}`, session_id: `s2-${i}` })),+ ]++ const result = transformExperimentResults({+ experiment,+ exposures: baseExposures,+ primaryMetricEntries: buildMetricEntries(experiment, 'primary'),+ secondaryMetricEntries: [],+ primaryMetricsResults: [+ {+ baseline: {+ key: 'control',+ sum: 100,+ sum_squares: 100,+ step_counts: [100, 50],+ step_sessions: stepSessions,+ },+ variant_results: [+ {+ key: 'test',+ sum: 95,+ sum_squares: 95,+ step_counts: [95, 48],+ step_sessions: stepSessions,+ },+ ],+ clickhouse_sql: longSql,+ hogql: longSql,+ },+ ],+ secondaryMetricsResults: [],+ })++ const data = result.metrics.primary.results[0]?.data as Record<string, unknown>+ expect(data.clickhouse_sql).toBeUndefined()+ expect(data.hogql).toBeUndefined()+ const baseline = data.baseline as Record<string, unknown>+ expect(baseline.step_sessions).toBeUndefined()+ // Statistical fields must survive — they're what an MCP caller actually needs.+ expect(baseline.sum).toBe(100)+ expect(baseline.step_counts).toEqual([100, 50])+ const variants = data.variant_results as Array<Record<string, unknown>>+ expect(variants[0]?.step_sessions).toBeUndefined()+ expect(variants[0]?.sum).toBe(95)+ })++ it('strips the legacy `insight` visualization payload from each row', () => {+ // `insight` is a rendered visualization payload (list[dict[str, Any]]) used by+ // legacy trends/funnels charts+ const experiment = makeExperiment({+ metrics: [{ uuid: 'p-1', name: 'Primary', metric_type: 'mean' }],+ primary_metrics_ordered_uuids: ['p-1'],+ })++ const result = transformExperimentResults({+ experiment,+ exposures: baseExposures,+ primaryMetricEntries: buildMetricEntries(experiment, 'primary'),+ secondaryMetricEntries: [],+ primaryMetricsResults: [+ {+ baseline: { key: 'control', sum: 100, sum_squares: 100 },+ insight: [{ breakdown_value: 'control', data: [1, 2, 3] }],+ },+ ],+ secondaryMetricsResults: [],+ })++ const data = result.metrics.primary.results[0]?.data as Record<string, unknown>+ expect(data.insight).toBeUndefined()+ expect((data.baseline as Record<string, unknown>).sum).toBe(100)+ })++ it('strips step_sessions from inside breakdown_results entries while preserving per-breakdown stats', () => {+ // breakdown_results carries stats that we keep. But each entry's+ // baseline/variants embed their own step_sessions which we strip.+ const experiment = makeExperiment({+ metrics: [{ uuid: 'p-1', name: 'Primary', metric_type: 'funnel' }],+ primary_metrics_ordered_uuids: ['p-1'],+ })+ const stepSessions = [Array.from({ length: 50 }, (_, i) => ({ event_uuid: `e-${i}` }))]++ const result = transformExperimentResults({+ experiment,+ exposures: baseExposures,+ primaryMetricEntries: buildMetricEntries(experiment, 'primary'),+ secondaryMetricEntries: [],+ primaryMetricsResults: [+ {+ baseline: { key: 'control', sum: 100, sum_squares: 100 },+ variant_results: [{ key: 'test', sum: 95, sum_squares: 95 }],+ breakdown_results: [+ {+ breakdown_value: ['MacOS'],+ baseline: {+ key: 'control',+ sum: 60,+ sum_squares: 60,+ step_counts: [60, 30],+ step_sessions: stepSessions,+ },+ variants: [+ {+ key: 'test',+ sum: 55,+ sum_squares: 55,+ step_counts: [55, 27],+ step_sessions: stepSessions,+ },+ ],+ },+ ],+ },+ ],+ secondaryMetricsResults: [],+ })++ const data = result.metrics.primary.results[0]?.data as Record<string, unknown>+ const breakdowns = data.breakdown_results as Array<Record<string, unknown>>+ expect(breakdowns).toHaveLength(1)+ expect(breakdowns[0]?.breakdown_value).toEqual(['MacOS'])++ const bdBaseline = breakdowns[0]?.baseline as Record<string, unknown>+ expect(bdBaseline.step_sessions).toBeUndefined()+ // Per-breakdown stats must survive — they're the whole point of breakdown_results.+ expect(bdBaseline.sum).toBe(60)+ expect(bdBaseline.step_counts).toEqual([60, 30])++ const bdVariants = breakdowns[0]?.variants as Array<Record<string, unknown>>+ expect(bdVariants[0]?.step_sessions).toBeUndefined()+ expect(bdVariants[0]?.sum).toBe(55)+ expect(bdVariants[0]?.step_counts).toEqual([55, 27])+ })})