: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
chore(mcp): extract insights visualization dispatch into pure modules (#63161)
Sam Pennington82e53e3caa7d
diff --git a/products/product_analytics/mcp/apps/InsightActorsView.tsx b/products/product_analytics/mcp/apps/InsightActorsView.tsxindex 1c3ad26e85dc..993406b66e81 100644--- a/products/product_analytics/mcp/apps/InsightActorsView.tsx+++ b/products/product_analytics/mcp/apps/InsightActorsView.tsx@@ -3,41 +3,9 @@ import { type ReactElement, type ReactNode, useMemo } from 'react'import { DataTable, type DataTableColumn } from '@posthog/mcp-ui'import { Badge, Button } from '@posthog/quill'-export interface InsightActorsData {- query: Record<string, unknown>- results: {- columns: string[]- results: (string | number | null | string[])[][]- }- hasMore: boolean- offset: number- _posthogUrl?: string-}--interface ActorRow {- distinct_id: string | null- email: string | null- name: string | null- event_count: number | null- recordings: string[]-}+import { type ActorRow, type InsightActorsData, toActorRows } from './insightActorsTransforms'-function toActorRows(data: InsightActorsData): ActorRow[] {- const { columns, results } = data.results- return results.map((row) => {- const obj: Record<string, unknown> = {}- columns.forEach((col, i) => {- obj[col] = row[i]- })- return {- distinct_id: (obj.distinct_id as string) ?? null,- email: (obj.email as string) ?? null,- name: (obj.name as string) ?? null,- event_count: (obj.event_count as number) ?? null,- recordings: Array.isArray(obj.recordings) ? (obj.recordings as string[]) : [],- }- })-}+export type { InsightActorsData }interface InsightActorsViewProps {data: InsightActorsDatadiff --git a/products/product_analytics/mcp/apps/insightActorsTransforms.ts b/products/product_analytics/mcp/apps/insightActorsTransforms.tsnew file mode 100644index 000000000000..8d761765c303--- /dev/null+++ b/products/product_analytics/mcp/apps/insightActorsTransforms.ts@@ -0,0 +1,35 @@+export interface InsightActorsData {+ query: Record<string, unknown>+ results: {+ columns: string[]+ results: (string | number | null | string[])[][]+ }+ hasMore: boolean+ offset: number+ _posthogUrl?: string+}++export interface ActorRow {+ distinct_id: string | null+ email: string | null+ name: string | null+ event_count: number | null+ recordings: string[]+}++export function toActorRows(data: InsightActorsData): ActorRow[] {+ const { columns, results } = data.results+ return results.map((row) => {+ const obj: Record<string, unknown> = {}+ columns.forEach((col, i) => {+ obj[col] = row[i]+ })+ return {+ distinct_id: (obj.distinct_id as string) ?? null,+ email: (obj.email as string) ?? null,+ name: (obj.name as string) ?? null,+ event_count: (obj.event_count as number) ?? null,+ recordings: Array.isArray(obj.recordings) ? (obj.recordings as string[]) : [],+ }+ })+}diff --git a/services/mcp/src/ui-apps/components/Component.tsx b/services/mcp/src/ui-apps/components/Component.tsxindex 21b1b2e61485..3873adf9b138 100644--- a/services/mcp/src/ui-apps/components/Component.tsx+++ b/services/mcp/src/ui-apps/components/Component.tsx@@ -4,6 +4,7 @@ import { emptyStateIllustration } from '@posthog/mcp-ui'import { Card, CardContent, Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'import { FunnelVisualizer } from './FunnelVisualizer'+import { inferVisualizationType } from './infer-visualization'import { LifecycleVisualizer } from './LifecycleVisualizer'import { PathsVisualizer } from './PathsVisualizer'import { RetentionVisualizer } from './RetentionVisualizer'@@ -23,182 +24,6 @@ import type {TrendsResult,} from './types'-type VisualizationType = 'trends' | 'funnel' | 'lifecycle' | 'retention' | 'paths' | 'table'--/**- * Lifecycle results share the trends shape but each item carries a `status` field- * (`new` / `returning` / `resurrecting` / `dormant`), and dormant counts come back- * negated from the backend so they render below zero.- */-function isLifecycleResult(results: unknown): results is LifecycleResult {- if (!Array.isArray(results) || results.length === 0) {- return false- }- const first = results[0] as Record<string, unknown>- if (typeof first !== 'object' || first === null) {- return false- }- const status = first.status- return (- typeof status === 'string' &&- (status === 'new' || status === 'returning' || status === 'resurrecting' || status === 'dormant')- )-}--/**- * Check if results look like TrendsResult (array of items with data/labels arrays).- */-function isTrendsResult(results: unknown): results is TrendsResult {- if (!Array.isArray(results) || results.length === 0) {- return false- }-- // TrendsResult items have: data (number[]), labels or days (string[])- const first = results[0] as Record<string, unknown>- return (- typeof first === 'object' &&- first !== null &&- (Array.isArray(first.data) || Array.isArray(first.labels) || Array.isArray(first.days))- )-}--/**- * Check if results look like FunnelResult (array of steps with count/order/name).- */-function isFunnelResult(results: unknown): results is FunnelResult {- if (!Array.isArray(results) || results.length === 0) {- return false- }-- // Handle both flat array and nested array formats- const items = Array.isArray(results[0]) ? (results[0] as unknown[]) : results- if (items.length === 0) {- return false- }-- // FunnelResult items have: name, count, order- const first = items[0] as Record<string, unknown>- return (- typeof first === 'object' &&- first !== null &&- 'count' in first &&- ('order' in first || 'action_id' in first || 'name' in first)- )-}--/**- * Retention results are arrays of cohorts where each item has `values: [{ count, ... }]`- * and a `date`/`label`. Distinct from trends (which uses `data`/`labels`/`days`).- */-function isRetentionResult(results: unknown): results is RetentionResult {- if (!Array.isArray(results) || results.length === 0) {- return false- }- const first = results[0] as Record<string, unknown>- if (typeof first !== 'object' || first === null) {- return false- }- if (!Array.isArray(first.values) || !('date' in first)) {- return false- }- // A brand-new cohort can legitimately have an empty `values` array — accept it as long as- // the surrounding shape is right. Only validate the inner `count` field when there's a row.- if (first.values.length === 0) {- return true- }- const firstValue = first.values[0] as Record<string, unknown>- return typeof firstValue === 'object' && firstValue !== null && 'count' in firstValue-}--/**- * Paths results are an array of edges, each with string `source`/`target` node keys- * (`<stepIndex>_<value>`) and a numeric `value` (user count).- */-function isPathsResult(results: unknown): results is PathsResult {- if (!Array.isArray(results) || results.length === 0) {- return false- }- const first = results[0] as Record<string, unknown>- return (- typeof first === 'object' &&- first !== null &&- typeof first.source === 'string' &&- typeof first.target === 'string' &&- typeof first.value === 'number'- )-}--/**- * Check if results look like HogQLResult (object with columns and results arrays).- */-function isHogQLResult(results: unknown): results is HogQLResult {- if (typeof results !== 'object' || results === null) {- return false- }-- const r = results as Record<string, unknown>- return 'columns' in r && 'results' in r && Array.isArray(r.columns) && Array.isArray(r.results)-}--/**- * Infer the visualization type from the data structure.- * This mimics how the main PostHog app determines visualization from query/results.- */-function inferVisualizationType(data: unknown): VisualizationType | null {- if (typeof data !== 'object' || data === null) {- return null- }-- const d = data as Record<string, unknown>- const results = d.results-- // Infer from results structure first (most reliable)- if (isHogQLResult(results)) {- return 'table'- }- // Retention must come before trends — its cohort rows could otherwise be misread.- if (isRetentionResult(results)) {- return 'retention'- }- // Lifecycle must come before trends — its rows pass `isTrendsResult` too.- if (isLifecycleResult(results)) {- return 'lifecycle'- }- // Paths must come before trends/funnel — its edge rows match neither, but keep it explicit.- if (isPathsResult(results)) {- return 'paths'- }- if (isTrendsResult(results)) {- return 'trends'- }- if (isFunnelResult(results)) {- return 'funnel'- }-- // Infer from query kind as fallback- const query = d.query as Record<string, unknown> | undefined- if (query?.kind === 'LifecycleQuery') {- return 'lifecycle'- }- if (query?.kind === 'TrendsQuery') {- return 'trends'- }- if (query?.kind === 'FunnelsQuery') {- return 'funnel'- }- if (query?.kind === 'RetentionQuery') {- return 'retention'- }- if (query?.kind === 'PathsQuery') {- return 'paths'- }- if (query?.kind === 'HogQLQuery') {- return 'table'- }-- return null-}-/** Data payload from MCP tools */interface DataPayload {query?: TrendsQuery | FunnelsQuery | LifecycleQuery | RetentionQuery | PathsQuery | Record<string, unknown>diff --git a/services/mcp/src/ui-apps/components/infer-visualization.ts b/services/mcp/src/ui-apps/components/infer-visualization.tsnew file mode 100644index 000000000000..e375da266f61--- /dev/null+++ b/services/mcp/src/ui-apps/components/infer-visualization.ts@@ -0,0 +1,177 @@+import type { FunnelResult, HogQLResult, LifecycleResult, PathsResult, RetentionResult, TrendsResult } from './types'++export type VisualizationType = 'trends' | 'funnel' | 'lifecycle' | 'retention' | 'paths' | 'table'++/**+ * Lifecycle results share the trends shape but each item carries a `status` field+ * (`new` / `returning` / `resurrecting` / `dormant`), and dormant counts come back+ * negated from the backend so they render below zero.+ */+export function isLifecycleResult(results: unknown): results is LifecycleResult {+ if (!Array.isArray(results) || results.length === 0) {+ return false+ }+ const first = results[0] as Record<string, unknown>+ if (typeof first !== 'object' || first === null) {+ return false+ }+ const status = first.status+ return (+ typeof status === 'string' &&+ (status === 'new' || status === 'returning' || status === 'resurrecting' || status === 'dormant')+ )+}++/**+ * Check if results look like TrendsResult (array of items with data/labels arrays).+ */+export function isTrendsResult(results: unknown): results is TrendsResult {+ if (!Array.isArray(results) || results.length === 0) {+ return false+ }++ // TrendsResult items have: data (number[]), labels or days (string[])+ const first = results[0] as Record<string, unknown>+ return (+ typeof first === 'object' &&+ first !== null &&+ (Array.isArray(first.data) || Array.isArray(first.labels) || Array.isArray(first.days))+ )+}++/**+ * Check if results look like FunnelResult (array of steps with count/order/name).+ */+export function isFunnelResult(results: unknown): results is FunnelResult {+ if (!Array.isArray(results) || results.length === 0) {+ return false+ }++ // Handle both flat array and nested array formats+ const items = Array.isArray(results[0]) ? (results[0] as unknown[]) : results+ if (items.length === 0) {+ return false+ }++ // FunnelResult items have: name, count, order+ const first = items[0] as Record<string, unknown>+ return (+ typeof first === 'object' &&+ first !== null &&+ 'count' in first &&+ ('order' in first || 'action_id' in first || 'name' in first)+ )+}++/**+ * Retention results are arrays of cohorts where each item has `values: [{ count, ... }]`+ * and a `date`/`label`. Distinct from trends (which uses `data`/`labels`/`days`).+ */+export function isRetentionResult(results: unknown): results is RetentionResult {+ if (!Array.isArray(results) || results.length === 0) {+ return false+ }+ const first = results[0] as Record<string, unknown>+ if (typeof first !== 'object' || first === null) {+ return false+ }+ if (!Array.isArray(first.values) || !('date' in first)) {+ return false+ }+ // A brand-new cohort can legitimately have an empty `values` array — accept it as long as+ // the surrounding shape is right. Only validate the inner `count` field when there's a row.+ if (first.values.length === 0) {+ return true+ }+ const firstValue = first.values[0] as Record<string, unknown>+ return typeof firstValue === 'object' && firstValue !== null && 'count' in firstValue+}++/**+ * Paths results are an array of edges, each with string `source`/`target` node keys+ * (`<stepIndex>_<value>`) and a numeric `value` (user count).+ */+export function isPathsResult(results: unknown): results is PathsResult {+ if (!Array.isArray(results) || results.length === 0) {+ return false+ }+ const first = results[0] as Record<string, unknown>+ return (+ typeof first === 'object' &&+ first !== null &&+ typeof first.source === 'string' &&+ typeof first.target === 'string' &&+ typeof first.value === 'number'+ )+}++/**+ * Check if results look like HogQLResult (object with columns and results arrays).+ */+export function isHogQLResult(results: unknown): results is HogQLResult {+ if (typeof results !== 'object' || results === null) {+ return false+ }++ const r = results as Record<string, unknown>+ return 'columns' in r && 'results' in r && Array.isArray(r.columns) && Array.isArray(r.results)+}++/**+ * Infer the visualization type from the data structure.+ * This mimics how the main PostHog app determines visualization from query/results.+ */+export function inferVisualizationType(data: unknown): VisualizationType | null {+ if (typeof data !== 'object' || data === null) {+ return null+ }++ const d = data as Record<string, unknown>+ const results = d.results++ // Infer from results structure first (most reliable)+ if (isHogQLResult(results)) {+ return 'table'+ }+ // Retention must come before trends — its cohort rows could otherwise be misread.+ if (isRetentionResult(results)) {+ return 'retention'+ }+ // Lifecycle must come before trends — its rows pass `isTrendsResult` too.+ if (isLifecycleResult(results)) {+ return 'lifecycle'+ }+ // Paths must come before trends/funnel — its edge rows match neither, but keep it explicit.+ if (isPathsResult(results)) {+ return 'paths'+ }+ if (isTrendsResult(results)) {+ return 'trends'+ }+ if (isFunnelResult(results)) {+ return 'funnel'+ }++ // Infer from query kind as fallback+ const query = d.query as Record<string, unknown> | undefined+ if (query?.kind === 'LifecycleQuery') {+ return 'lifecycle'+ }+ if (query?.kind === 'TrendsQuery') {+ return 'trends'+ }+ if (query?.kind === 'FunnelsQuery') {+ return 'funnel'+ }+ if (query?.kind === 'RetentionQuery') {+ return 'retention'+ }+ if (query?.kind === 'PathsQuery') {+ return 'paths'+ }+ if (query?.kind === 'HogQLQuery') {+ return 'table'+ }++ return null+}