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.

feat(mcp): retention chart UI app (#58130)

Georgis Andonis4bab7bedd840
diff --git a/services/mcp/src/ui-apps/components/Component.tsx b/services/mcp/src/ui-apps/components/Component.tsx
index d3bfbbd02227..c5e73d32ce61 100644
--- a/services/mcp/src/ui-apps/components/Component.tsx
+++ b/services/mcp/src/ui-apps/components/Component.tsx
@@ -4,6 +4,7 @@ import { EmptyState } from '@posthog/mosaic'
import { FunnelVisualizer } from './FunnelVisualizer'
import { LifecycleVisualizer } from './LifecycleVisualizer'
+import { RetentionVisualizer } from './RetentionVisualizer'
import { TableVisualizer } from './TableVisualizer'
import { TrendsVisualizer } from './TrendsVisualizer'
import type {
@@ -12,11 +13,13 @@ import type {
HogQLResult,
LifecycleQuery,
LifecycleResult,
+ RetentionQuery,
+ RetentionResult,
TrendsQuery,
TrendsResult,
} from './types'
-type VisualizationType = 'trends' | 'funnel' | 'lifecycle' | 'table'
+type VisualizationType = 'trends' | 'funnel' | 'lifecycle' | 'retention' | 'table'
/**
* Lifecycle results share the trends shape but each item carries a `status` field
@@ -79,6 +82,30 @@ function isFunnelResult(results: unknown): results is FunnelResult {
)
}
+/**
+ * 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
+}
+
/**
* Check if results look like HogQLResult (object with columns and results arrays).
*/
@@ -107,6 +134,10 @@ function inferVisualizationType(data: unknown): VisualizationType | null {
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'
@@ -129,6 +160,9 @@ function inferVisualizationType(data: unknown): VisualizationType | null {
if (query?.kind === 'FunnelsQuery') {
return 'funnel'
}
+ if (query?.kind === 'RetentionQuery') {
+ return 'retention'
+ }
if (query?.kind === 'HogQLQuery') {
return 'table'
}
@@ -138,8 +172,8 @@ function inferVisualizationType(data: unknown): VisualizationType | null {
/** Data payload from MCP tools */
interface DataPayload {
- query?: TrendsQuery | FunnelsQuery | LifecycleQuery | Record<string, unknown>
- results: TrendsResult | FunnelResult | LifecycleResult | HogQLResult
+ query?: TrendsQuery | FunnelsQuery | LifecycleQuery | RetentionQuery | Record<string, unknown>
+ results: TrendsResult | FunnelResult | LifecycleResult | RetentionResult | HogQLResult
_posthogUrl?: string
}
@@ -199,6 +233,14 @@ export function Component({ data }: ComponentProps): ReactElement {
/>
)
+ case 'retention':
+ return (
+ <RetentionVisualizer
+ query={payload.query as RetentionQuery}
+ results={payload.results as RetentionResult}
+ />
+ )
+
case 'table':
return <TableVisualizer results={payload.results as HogQLResult} />
@@ -219,6 +261,8 @@ export function Component({ data }: ComponentProps): ReactElement {
return 'Funnel'
case 'lifecycle':
return 'Lifecycle'
+ case 'retention':
+ return 'Retention'
case 'table':
return 'Query results'
default:
diff --git a/services/mcp/src/ui-apps/components/RetentionVisualizer.tsx b/services/mcp/src/ui-apps/components/RetentionVisualizer.tsx
new file mode 100644
index 000000000000..3abf4a65b207
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/RetentionVisualizer.tsx
@@ -0,0 +1,190 @@
+import { type ReactElement, useMemo, useState } from 'react'
+
+import { EmptyState } from '@posthog/mosaic'
+
+import { BarChart, LineChart, Select, type Series } from './charts'
+import type {
+ RetentionAggregationType,
+ RetentionPeriod,
+ RetentionReference,
+ RetentionResult,
+ RetentionResultItem,
+ RetentionVisualizerProps,
+} from './types'
+
+type ChartMode = 'line' | 'bar'
+
+const CHART_MODE_OPTIONS = [
+ { value: 'line' as const, label: 'Line' },
+ { value: 'bar' as const, label: 'Bar' },
+]
+
+function formatStartDate(cohort: RetentionResultItem, period: RetentionPeriod): string | null {
+ if (!cohort.date) {
+ return null
+ }
+ const d = new Date(cohort.date)
+ if (Number.isNaN(d.getTime())) {
+ return null
+ }
+ if (period === 'Hour') {
+ return d.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric' })
+ }
+ if (period === 'Month') {
+ return d.toLocaleDateString('en-US', { month: 'short', year: 'numeric' })
+ }
+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
+}
+
+function formatCohortLegendLabel(cohort: RetentionResultItem, cohortNumber: number, period: RetentionPeriod): string {
+ const startDate = formatStartDate(cohort, period)
+ const breakdown =
+ cohort.breakdown_value !== undefined && cohort.breakdown_value !== null && cohort.breakdown_value !== ''
+ ? String(cohort.breakdown_value)
+ : null
+ const base = `Cohort ${cohortNumber}`
+ if (breakdown) {
+ return startDate ? `${base} (${breakdown}, ${startDate})` : `${base} (${breakdown})`
+ }
+ return startDate ? `${base} (${startDate})` : base
+}
+
+// Mirrors the math in `retentionLogic.ts`: each cohort's interval values become a percentage of the
+// reference cohort size (`total` = day-0, `previous` = preceding interval). For non-count aggregations
+// we surface `aggregation_value` directly without normalization.
+function computeSeriesValue(
+ values: RetentionResultItem['values'],
+ intervalIndex: number,
+ aggregationType: RetentionAggregationType,
+ reference: RetentionReference
+): number {
+ const current = values[intervalIndex]
+ if (!current) {
+ return 0
+ }
+ if (aggregationType !== 'count') {
+ return current.aggregation_value ?? 0
+ }
+ if (reference === 'previous') {
+ if (intervalIndex === 0) {
+ return 100
+ }
+ const prev = values[intervalIndex - 1]
+ if (!prev || prev.count === 0) {
+ return 0
+ }
+ return (current.count / prev.count) * 100
+ }
+ const baseline = values[0]?.count ?? 0
+ if (baseline === 0) {
+ return 0
+ }
+ return (current.count / baseline) * 100
+}
+
+function buildXAxisLabels(numIntervals: number, period: RetentionPeriod): string[] {
+ return Array.from({ length: numIntervals }, (_, i) => `${period} ${i}`)
+}
+
+// Sort chronologically so "Cohort 1" is the earliest start date. Cohorts without a parseable date
+// preserve their original order at the end of the list.
+function sortCohorts(results: RetentionResult): RetentionResult {
+ return [...results].sort((a, b) => {
+ const ta = a.date ? new Date(a.date).getTime() : Number.POSITIVE_INFINITY
+ const tb = b.date ? new Date(b.date).getTime() : Number.POSITIVE_INFINITY
+ // `ta`/`tb` can each be a finite ms timestamp, NaN (invalid `date`), or POSITIVE_INFINITY
+ // (missing `date`). `ta - tb` returns NaN whenever both are non-finite (Inf-Inf or NaN-*),
+ // which violates the sort comparator contract — handle those pairings explicitly.
+ const aMissing = Number.isNaN(ta) || !Number.isFinite(ta)
+ const bMissing = Number.isNaN(tb) || !Number.isFinite(tb)
+ if (aMissing && bMissing) {
+ return 0
+ }
+ if (aMissing) {
+ return 1
+ }
+ if (bMissing) {
+ return -1
+ }
+ return ta - tb
+ })
+}
+
+// Cap at the size of the shared chart palette so each cohort gets its own distinct color rather
+// than cycling — beyond this the lines blur into noise anyway.
+const MAX_COHORTS = 8
+
+export function RetentionVisualizer({ query, results }: RetentionVisualizerProps): ReactElement {
+ const aggregationType: RetentionAggregationType = query?.retentionFilter?.aggregationType ?? 'count'
+ const reference: RetentionReference = query?.retentionFilter?.retentionReference ?? 'total'
+ const period: RetentionPeriod = query?.retentionFilter?.period ?? 'Day'
+ const isPercentage = aggregationType === 'count'
+
+ const [chartMode, setChartMode] = useState<ChartMode>('line')
+
+ const { series, labels, maxValue, totalCohorts } = useMemo(() => {
+ if (!results || results.length === 0) {
+ return { series: [] as Series[], labels: [] as string[], maxValue: 0, totalCohorts: 0 }
+ }
+ const sorted = sortCohorts(results)
+ // Cap to MAX_COHORTS so each line gets a distinct palette color rather than wrapping back
+ // to the first color. Older cohorts have the most observed intervals so we keep those.
+ const limited = sorted.slice(0, MAX_COHORTS)
+ const numIntervals = limited.reduce((m, c) => Math.max(m, c.values.length), 0)
+ const xLabels = buildXAxisLabels(numIntervals, period)
+ let computedMax = 0
+
+ const built: Series[] = limited.map((cohort, idx) => {
+ const points = Array.from({ length: numIntervals }, (_, i) => {
+ const y = computeSeriesValue(cohort.values, i, aggregationType, reference)
+ if (y > computedMax) {
+ computedMax = y
+ }
+ return { x: i, y, label: xLabels[i] ?? `${i}` }
+ })
+ return {
+ label: formatCohortLegendLabel(cohort, idx + 1, period),
+ points,
+ }
+ })
+
+ return {
+ series: built,
+ labels: xLabels,
+ maxValue: computedMax || 1,
+ totalCohorts: sorted.length,
+ }
+ }, [results, aggregationType, reference, period])
+
+ if (!results || results.length === 0 || series.length === 0 || labels.length === 0) {
+ return <EmptyState icon="chart" description="No retention data available" />
+ }
+
+ const yAxisLabel = isPercentage ? 'Retention %' : aggregationType === 'sum' ? 'Sum' : 'Avg'
+ const truncationNotice =
+ totalCohorts > MAX_COHORTS ? `Showing first ${MAX_COHORTS} of ${totalCohorts} cohorts (oldest first)` : null
+
+ return (
+ <div>
+ <div
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '0.5rem',
+ }}
+ >
+ <span style={{ fontSize: '0.75rem', color: 'var(--color-text-secondary, #6b7280)' }}>
+ {truncationNotice}
+ </span>
+ {/* eslint-disable-next-line react/forbid-elements */}
+ <Select value={chartMode} onChange={setChartMode} options={CHART_MODE_OPTIONS} />
+ </div>
+ {chartMode === 'bar' ? (
+ <BarChart series={series} labels={labels} maxValue={maxValue} yAxisLabel={yAxisLabel} />
+ ) : (
+ <LineChart series={series} labels={labels} maxValue={maxValue} yAxisLabel={yAxisLabel} />
+ )}
+ </div>
+ )
+}
diff --git a/services/mcp/src/ui-apps/components/charts/BarChart.tsx b/services/mcp/src/ui-apps/components/charts/BarChart.tsx
index a9d474361d2b..da8997f0fccd 100644
--- a/services/mcp/src/ui-apps/components/charts/BarChart.tsx
+++ b/services/mcp/src/ui-apps/components/charts/BarChart.tsx
@@ -7,11 +7,14 @@ const CHART_WIDTH = 400
const PADDING = { top: 20, right: 20, bottom: 40, left: 50 }
const COLORS = [
- 'var(--posthog-chart-1, #1d4ed8)',
- 'var(--posthog-chart-2, #7c3aed)',
- 'var(--posthog-chart-3, #059669)',
- 'var(--posthog-chart-4, #dc2626)',
- 'var(--posthog-chart-5, #ea580c)',
+ 'var(--posthog-chart-1, #1d4aff)',
+ 'var(--posthog-chart-2, #621da6)',
+ 'var(--posthog-chart-3, #42827e)',
+ 'var(--posthog-chart-4, #ce0e74)',
+ 'var(--posthog-chart-5, #f14f58)',
+ 'var(--posthog-chart-6, #7c440e)',
+ 'var(--posthog-chart-7, #529a0a)',
+ 'var(--posthog-chart-8, #0476fb)',
]
export interface DataPoint {
diff --git a/services/mcp/src/ui-apps/components/charts/LineChart.tsx b/services/mcp/src/ui-apps/components/charts/LineChart.tsx
index 6537172ab7fa..fb0266d6ce40 100644
--- a/services/mcp/src/ui-apps/components/charts/LineChart.tsx
+++ b/services/mcp/src/ui-apps/components/charts/LineChart.tsx
@@ -7,11 +7,14 @@ const CHART_WIDTH = 400
const PADDING = { top: 20, right: 20, bottom: 40, left: 50 }
const COLORS = [
- 'var(--posthog-chart-1, #1d4ed8)',
- 'var(--posthog-chart-2, #7c3aed)',
- 'var(--posthog-chart-3, #059669)',
- 'var(--posthog-chart-4, #dc2626)',
- 'var(--posthog-chart-5, #ea580c)',
+ 'var(--posthog-chart-1, #1d4aff)',
+ 'var(--posthog-chart-2, #621da6)',
+ 'var(--posthog-chart-3, #42827e)',
+ 'var(--posthog-chart-4, #ce0e74)',
+ 'var(--posthog-chart-5, #f14f58)',
+ 'var(--posthog-chart-6, #7c440e)',
+ 'var(--posthog-chart-7, #529a0a)',
+ 'var(--posthog-chart-8, #0476fb)',
]
export interface DataPoint {
diff --git a/services/mcp/src/ui-apps/components/index.ts b/services/mcp/src/ui-apps/components/index.ts
index 7676675c2efa..2e252ddde451 100644
--- a/services/mcp/src/ui-apps/components/index.ts
+++ b/services/mcp/src/ui-apps/components/index.ts
@@ -4,6 +4,8 @@ export { Component } from './Component'
// Smart visualizers - transform structured data for rendering
export { TrendsVisualizer } from './TrendsVisualizer'
export { FunnelVisualizer } from './FunnelVisualizer'
+export { LifecycleVisualizer } from './LifecycleVisualizer'
+export { RetentionVisualizer } from './RetentionVisualizer'
export { TableVisualizer } from './TableVisualizer'
// Dumb chart components - receive pre-processed data
export * from './charts'
diff --git a/services/mcp/src/ui-apps/components/types.ts b/services/mcp/src/ui-apps/components/types.ts
index 04c01cf363f7..cd1c9d6a6217 100644
--- a/services/mcp/src/ui-apps/components/types.ts
+++ b/services/mcp/src/ui-apps/components/types.ts
@@ -114,6 +114,37 @@ export interface HogQLResult {
results?: unknown[][]
}
+export type RetentionAggregationType = 'count' | 'sum' | 'avg'
+export type RetentionReference = 'total' | 'previous'
+export type RetentionPeriod = 'Hour' | 'Day' | 'Week' | 'Month'
+
+export interface RetentionFilter {
+ aggregationType?: RetentionAggregationType | null
+ period?: RetentionPeriod | null
+ retentionReference?: RetentionReference | null
+ showTrendLines?: boolean | null
+ totalIntervals?: number | null
+}
+
+export interface RetentionQuery {
+ kind: 'RetentionQuery'
+ retentionFilter?: RetentionFilter
+}
+
+export interface RetentionValueItem {
+ count: number
+ aggregation_value?: number | null
+}
+
+export interface RetentionResultItem {
+ date: string
+ label: string
+ breakdown_value?: string | number | null
+ values: RetentionValueItem[]
+}
+
+export type RetentionResult = RetentionResultItem[]
+
// ============================================================================
// Tool result payloads
// The visualization type is inferred from the data structure, not a discriminator
@@ -139,6 +170,11 @@ export interface TablePayload extends BasePayload {
results: HogQLResult
}
+export interface RetentionPayload extends BasePayload {
+ query: RetentionQuery
+ results: RetentionResult
+}
+
// ============================================================================
// Component props
// ============================================================================
@@ -161,3 +197,8 @@ export interface LifecycleVisualizerProps {
export interface TableVisualizerProps {
results: HogQLResult
}
+
+export interface RetentionVisualizerProps {
+ query: RetentionQuery | undefined
+ results: RetentionResult
+}
diff --git a/services/mcp/src/ui-apps/components/utils.ts b/services/mcp/src/ui-apps/components/utils.ts
index 8a8177cfb4df..f3da0adb0698 100644
--- a/services/mcp/src/ui-apps/components/utils.ts
+++ b/services/mcp/src/ui-apps/components/utils.ts
@@ -22,9 +22,16 @@ export function formatPercent(value: number): string {
return `${(value * 100).toFixed(1)}%`
}
+// Only format strings that look like ISO dates — `new Date(...)` is permissive enough that
+// labels like "Day 1" silently parse to Jan 1 2001, mangling pre-formatted axis labels.
+const ISO_DATE_PREFIX = /^\d{4}-\d{2}-\d{2}/
+
export function formatDate(dateStr: string): string {
+ if (!ISO_DATE_PREFIX.test(dateStr)) {
+ return dateStr
+ }
const date = new Date(dateStr)
- if (isNaN(date.getTime())) {
+ if (Number.isNaN(date.getTime())) {
return dateStr
}
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
diff --git a/services/mcp/src/ui-apps/styles/base.css b/services/mcp/src/ui-apps/styles/base.css
index ebdd5d9cb093..a0683e2e68e4 100644
--- a/services/mcp/src/ui-apps/styles/base.css
+++ b/services/mcp/src/ui-apps/styles/base.css
@@ -23,12 +23,15 @@
--border-radius-md: 0.375rem;
--border-radius-lg: 0.5rem;
- /* PostHog custom chart colors (not part of ext-apps spec, we define our own) */
- --posthog-chart-1: #1d4ed8;
- --posthog-chart-2: #7c3aed;
- --posthog-chart-3: #059669;
- --posthog-chart-4: #dc2626;
- --posthog-chart-5: #ea580c;
+ /* PostHog custom chart colors (mirrors --data-color-* in frontend/src/styles/base.scss) */
+ --posthog-chart-1: #1d4aff;
+ --posthog-chart-2: #621da6;
+ --posthog-chart-3: #42827e;
+ --posthog-chart-4: #ce0e74;
+ --posthog-chart-5: #f14f58;
+ --posthog-chart-6: #7c440e;
+ --posthog-chart-7: #529a0a;
+ --posthog-chart-8: #0476fb;
}
/* Dark mode defaults */
@@ -43,12 +46,15 @@
--color-border-primary: #374151;
--color-border-secondary: #4b5563;
- /* Dark mode chart colors */
- --posthog-chart-1: #60a5fa;
- --posthog-chart-2: #a78bfa;
- --posthog-chart-3: #34d399;
- --posthog-chart-4: #f87171;
- --posthog-chart-5: #fb923c;
+ /* Dark mode chart colors (lighter shades for contrast on dark backgrounds) */
+ --posthog-chart-1: #5d80ff;
+ --posthog-chart-2: #7f26d9;
+ --posthog-chart-3: #3e7a76;
+ --posthog-chart-4: #bf0d6c;
+ --posthog-chart-5: #f0474f;
+ --posthog-chart-6: #b36114;
+ --posthog-chart-7: #84cc16;
+ --posthog-chart-8: #38bdf8;
}
}