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.

fix(mcp): render DataVisualizationNode insights in optimized output (#63537)

Georgiy Tarasov1c3ed6130d6f
diff --git a/services/mcp/src/tools/insights/query.ts b/services/mcp/src/tools/insights/query.ts
index c8b332296c2a..ef5743b741c2 100644
--- a/services/mcp/src/tools/insights/query.ts
+++ b/services/mcp/src/tools/insights/query.ts
@@ -4,7 +4,7 @@ import { withUiApp } from '@/resources/ui-apps'
import type { Insight } from '@/schema/insights'
import { InsightQueryInputSchema } from '@/schema/tool-inputs'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
-import type { Context, ToolBase } from '@/tools/types'
+import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, type ToolBase } from '@/tools/types'
import { analyzeQuery } from '../shared'
@@ -12,7 +12,12 @@ const schema = InsightQueryInputSchema
type Params = z.infer<typeof schema>
-type Result = WithPostHogUrl<{ query: unknown; insight: Insight & { url: string }; results: unknown }>
+type Result = WithPostHogUrl<{
+ query: unknown
+ insight: Insight & { url: string }
+ results: unknown
+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]?: string
+}>
// Accept either a pre-encoded JSON string or a plain object for the override
// params. LLM agents reading the insight-get response see `variables` as an
@@ -64,52 +69,35 @@ export const queryHandler: ToolBase<typeof schema, Result>['handler'] = async (c
const fullUrl = `${context.api.getProjectBaseUrl(projectId)}${path}`
const queryInfo = analyzeQuery(insightResult.data.query)
- const useFormatted = output_format === 'optimized' && queryResult.data.formatted_results != null
-
- if (useFormatted) {
- return withPostHogUrl(
- context,
- {
- query: queryInfo.innerQuery || insightResult.data.query,
- insight: {
- url: fullUrl,
- ...insightResult.data,
- },
- results: queryResult.data.formatted_results,
- },
- path
- )
- }
-
- // JSON format or no formatter available — return raw results
- if (queryInfo.visualization === 'trends' || queryInfo.visualization === 'funnel') {
- return withPostHogUrl(
- context,
- {
- query: queryInfo.innerQuery || insightResult.data.query,
- insight: {
- url: fullUrl,
- ...insightResult.data,
- },
- results: queryResult.data.results,
- },
- path
- )
- }
+ // Trends/funnel UI visualizers consume the raw results array; every other
+ // visualization (HogQL/table, retention, lifecycle, paths) expects the
+ // `{ columns, results }` shape the structural guards look for.
+ const isSeries = queryInfo.visualization === 'trends' || queryInfo.visualization === 'funnel'
+ const results = isSeries
+ ? queryResult.data.results
+ : {
+ columns: queryResult.data.columns || [],
+ results: queryResult.data.results || [],
+ }
+
+ // Optimized output surfaces the server-formatted summary as the model-facing text, but the
+ // UI app still needs the structured results in structuredContent. Carry the formatted string
+ // under the override key (which build-tool-result strips from structuredContent and uses as
+ // the text payload) rather than overwriting `results` with it — mirrors query-wrapper-factory.
+ const surfaceFormatted = output_format === 'optimized' && queryResult.data.formatted_results != null
- // HogQL/table results have columns and results arrays
return withPostHogUrl(
context,
{
- query: insightResult.data.query,
+ query: queryInfo.innerQuery || insightResult.data.query,
insight: {
url: fullUrl,
...insightResult.data,
},
- results: {
- columns: queryResult.data.columns || [],
- results: queryResult.data.results || [],
- },
+ results,
+ ...(surfaceFormatted
+ ? { [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: queryResult.data.formatted_results }
+ : {}),
},
path
)
diff --git a/services/mcp/src/ui-apps/components/infer-visualization.ts b/services/mcp/src/ui-apps/components/infer-visualization.ts
index e375da266f61..32edfa200d73 100644
--- a/services/mcp/src/ui-apps/components/infer-visualization.ts
+++ b/services/mcp/src/ui-apps/components/infer-visualization.ts
@@ -152,26 +152,48 @@ export function inferVisualizationType(data: unknown): VisualizationType | null
return 'funnel'
}
- // Infer from query kind as fallback
+ // Infer from query kind as fallback. Wrapper nodes (`DataVisualizationNode` for
+ // HogQL/SQL insights, `InsightVizNode` for standard insights) carry the real query
+ // kind on `source.kind` — unwrap so a formatted-results payload (where the structural
+ // guards above can't match) still resolves to the right visualization.
const query = d.query as Record<string, unknown> | undefined
- if (query?.kind === 'LifecycleQuery') {
+ const kind = unwrapQueryKind(query)
+ if (kind === 'LifecycleQuery') {
return 'lifecycle'
}
- if (query?.kind === 'TrendsQuery') {
+ if (kind === 'TrendsQuery') {
return 'trends'
}
- if (query?.kind === 'FunnelsQuery') {
+ if (kind === 'FunnelsQuery') {
return 'funnel'
}
- if (query?.kind === 'RetentionQuery') {
+ if (kind === 'RetentionQuery') {
return 'retention'
}
- if (query?.kind === 'PathsQuery') {
+ if (kind === 'PathsQuery') {
return 'paths'
}
- if (query?.kind === 'HogQLQuery') {
+ if (kind === 'HogQLQuery') {
return 'table'
}
return null
}
+
+/**
+ * Resolve the effective query kind, unwrapping the wrapper nodes that carry their real
+ * query on `source.kind`: `DataVisualizationNode` (HogQL/SQL insights) and `InsightVizNode`
+ * (standard insights). Returns the wrapper's own kind when there's nothing to unwrap.
+ */
+function unwrapQueryKind(query: Record<string, unknown> | undefined): string | undefined {
+ if (!query) {
+ return undefined
+ }
+ if (query.kind === 'DataVisualizationNode' || query.kind === 'InsightVizNode') {
+ const source = query.source as Record<string, unknown> | undefined
+ if (source && typeof source.kind === 'string') {
+ return source.kind
+ }
+ }
+ return typeof query.kind === 'string' ? query.kind : undefined
+}
diff --git a/services/mcp/tests/tools/insights.integration.test.ts b/services/mcp/tests/tools/insights.integration.test.ts
index ebd15a647a97..3840c8d53291 100644
--- a/services/mcp/tests/tools/insights.integration.test.ts
+++ b/services/mcp/tests/tools/insights.integration.test.ts
@@ -16,7 +16,7 @@ import {
} from '@/shared/test-utils'
import { GENERATED_TOOLS } from '@/tools/generated/product_analytics'
import queryInsightTool from '@/tools/insights/query'
-import type { Context } from '@/tools/types'
+import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'
const insightGetTool = GENERATED_TOOLS['insight-get']!()
const insightCreateTool = GENERATED_TOOLS['insight-create']!()
@@ -145,9 +145,11 @@ describe('Insights', { concurrent: false }, () => {
expect(Array.isArray(response.results.results)).toBe(true)
})
- it('HogQL query with output_format=optimized returns a formatted string', async () => {
- // The API client always sends X-PostHog-Client: mcp, so the backend
- // runs the SQLResultsFormatter and returns formatted_results as a string.
+ it('HogQL query with output_format=optimized keeps structured results and surfaces the formatted string', async () => {
+ // The API client always sends X-PostHog-Client: mcp, so the backend runs the
+ // SQLResultsFormatter and returns formatted_results. `results` stays structured so the
+ // UI app can render it; the formatted summary rides under the override key (which
+ // build-tool-result strips from structuredContent and uses as the model-facing text).
const insight = await createTestInsight(generateUniqueKey('HogQL Optimized Shape'))
const result = await queryTool.handler(context, {
@@ -157,7 +159,11 @@ describe('Insights', { concurrent: false }, () => {
const response = parseToolResponse(result)
expect(response).toHaveProperty('results')
- expect(typeof response.results).toBe('string')
+ expect(response.results).toHaveProperty('columns')
+ expect(response.results).toHaveProperty('results')
+ expect(Array.isArray(response.results.columns)).toBe(true)
+ expect(Array.isArray(response.results.results)).toBe(true)
+ expect(typeof response[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBe('string')
})
it('TrendsQuery with output_format=json returns an array of series', async () => {
@@ -173,9 +179,11 @@ describe('Insights', { concurrent: false }, () => {
expect(Array.isArray(response.results)).toBe(true)
})
- it('TrendsQuery with output_format=optimized returns a formatted string', async () => {
- // The API client always sends X-PostHog-Client: mcp, so the backend
- // runs the TrendsResultsFormatter and returns formatted_results as a string.
+ it('TrendsQuery with output_format=optimized keeps the series array and surfaces the formatted string', async () => {
+ // The API client always sends X-PostHog-Client: mcp, so the backend runs the
+ // TrendsResultsFormatter and returns formatted_results. Trends visualizers consume the
+ // raw series array, so `results` stays an array; the formatted summary rides under the
+ // override key for the model-facing text.
const insight = await createTestTrendsInsight(generateUniqueKey('Trends Optimized Shape'))
const result = await queryTool.handler(context, {
@@ -185,7 +193,8 @@ describe('Insights', { concurrent: false }, () => {
const response = parseToolResponse(result)
expect(response).toHaveProperty('results')
- expect(typeof response.results).toBe('string')
+ expect(Array.isArray(response.results)).toBe(true)
+ expect(typeof response[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBe('string')
})
})
})
diff --git a/services/mcp/tests/unit/insight-visualizations.test.ts b/services/mcp/tests/unit/insight-visualizations.test.ts
index 98261a2b0088..5a5575104f17 100644
--- a/services/mcp/tests/unit/insight-visualizations.test.ts
+++ b/services/mcp/tests/unit/insight-visualizations.test.ts
@@ -78,12 +78,28 @@ describe('insight visualizations', () => {
})
it('falls back to the query kind when results is a formatted string', () => {
- // insight-query with output_format=optimized currently puts the server-side
- // formatted summary (a string) into `results`; only the kind fallback fires.
+ // If a formatted summary (a string) ever reaches the UI app as `results`, the
+ // structural guards can't match and only the kind fallback can classify it.
const data = queryPayload('Date | $pageview\n2025-06-01 | 10', 'TrendsQuery')
expect(inferVisualizationType(data)).toBe('trends')
})
+ it.each([
+ ['DataVisualizationNode wrapping HogQLQuery', 'DataVisualizationNode', 'HogQLQuery', 'table'],
+ ['InsightVizNode wrapping TrendsQuery', 'InsightVizNode', 'TrendsQuery', 'trends'],
+ ['InsightVizNode wrapping RetentionQuery', 'InsightVizNode', 'RetentionQuery', 'retention'],
+ ] as const)('unwraps %s to its inner kind', (_label, wrapperKind, sourceKind, expected) => {
+ // Wrapper nodes carry the real query kind on `source.kind`; the fallback must
+ // unwrap so a formatted-string payload still resolves to the right visualization.
+ const data = { query: { kind: wrapperKind, source: { kind: sourceKind } }, results: 'col\n1' }
+ expect(inferVisualizationType(data)).toBe(expected)
+ })
+
+ it('returns null for a wrapper node with no source kind', () => {
+ const data = { query: { kind: 'DataVisualizationNode' }, results: 'col\n1' }
+ expect(inferVisualizationType(data)).toBeNull()
+ })
+
it('returns null for StickinessQuery with empty results', () => {
// Known gap: query-stickiness ships the query-results UI app but the dispatcher
// has no StickinessQuery fallback — empty stickiness results show "unsupported".
diff --git a/services/mcp/tests/unit/insights-query-handler.test.ts b/services/mcp/tests/unit/insights-query-handler.test.ts
index 6a1dadea930e..a5ec8bb1ac06 100644
--- a/services/mcp/tests/unit/insights-query-handler.test.ts
+++ b/services/mcp/tests/unit/insights-query-handler.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { queryHandler } from '@/tools/insights/query'
-import type { Context } from '@/tools/types'
+import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'
const filtersOverrideObject = { date_from: '-7d' }
const variablesOverrideObject = {
@@ -24,10 +24,16 @@ interface MockHandles {
insightsQuery: ReturnType<typeof vi.fn>
}
-function createContext(): MockHandles {
+interface QueryResult {
+ query: unknown
+ results: unknown
+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]?: string
+}
+
+function createContext(overrides?: { getData?: unknown; queryData?: unknown }): MockHandles {
const insightsGet = vi.fn().mockResolvedValue({
success: true,
- data: {
+ data: overrides?.getData ?? {
id: 42,
short_id: 'abc12345',
query: { kind: 'HogQLQuery', query: 'select 1' },
@@ -35,7 +41,7 @@ function createContext(): MockHandles {
})
const insightsQuery = vi.fn().mockResolvedValue({
success: true,
- data: { columns: ['c'], results: [[1]] },
+ data: overrides?.queryData ?? { columns: ['c'], results: [[1]] },
})
const context = {
api: {
@@ -126,3 +132,65 @@ describe('queryHandler — overrides forwarding', () => {
expect(call.filters_override).toBe(filters_override)
})
})
+
+describe('queryHandler — result shape for UI rendering', () => {
+ const formatted = 'c\n1'
+
+ it('keeps structured results for a HogQL insight in optimized output', async () => {
+ const { context } = createContext({
+ queryData: { columns: ['c'], results: [[1]], formatted_results: formatted },
+ })
+
+ const result = (await queryHandler(context, { insightId: '42', output_format: 'optimized' })) as QueryResult
+
+ // The UI app's structuredContent must carry the structured shape its guards expect,
+ // not the formatted string — otherwise the table can't render.
+ expect(result.results).toEqual({ columns: ['c'], results: [[1]] })
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBe(formatted)
+ })
+
+ it('keeps structured results for a DataVisualizationNode-wrapped HogQL insight in optimized output', async () => {
+ const { context } = createContext({
+ getData: {
+ id: 42,
+ short_id: 'abc12345',
+ query: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'select 1' } },
+ },
+ queryData: { columns: ['org_id', 'cost'], results: [['a', 1]], formatted_results: formatted },
+ })
+
+ const result = (await queryHandler(context, { insightId: '42', output_format: 'optimized' })) as QueryResult
+
+ expect(result.results).toEqual({ columns: ['org_id', 'cost'], results: [['a', 1]] })
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBe(formatted)
+ })
+
+ it('does not surface the formatted override in json output', async () => {
+ const { context } = createContext({
+ queryData: { columns: ['c'], results: [[1]], formatted_results: formatted },
+ })
+
+ const result = (await queryHandler(context, { insightId: '42', output_format: 'json' })) as QueryResult
+
+ expect(result.results).toEqual({ columns: ['c'], results: [[1]] })
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBeUndefined()
+ })
+
+ it('passes the raw results array through for trends insights', async () => {
+ const trendsResults = [{ data: [1, 2], labels: ['a', 'b'] }]
+ const { context } = createContext({
+ getData: {
+ id: 42,
+ short_id: 'abc12345',
+ query: { kind: 'InsightVizNode', source: { kind: 'TrendsQuery' } },
+ },
+ queryData: { results: trendsResults, formatted_results: formatted },
+ })
+
+ const result = (await queryHandler(context, { insightId: '42', output_format: 'optimized' })) as QueryResult
+
+ expect(result.results).toBe(trendsResults)
+ expect(result.query).toEqual({ kind: 'TrendsQuery' })
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBe(formatted)
+ })
+})