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 stickiness as a percentage distribution in UI app (#64822)

Georgis Andonisbef5e2d8c17e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8223edff6a9c..ebff97d5eb2c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4158,6 +4158,10 @@ snapshots:
hash: v1.k794b7964.6d00ea357f1a270a0b0a6a4d61339c00a298f946d4f7a8fe9ed70b289aa3b60b.6ijtbv39zAumhoMFY5BSCxCkLHO9rYpeBUjUykvvgK8
mcp-apps-retention-actors--daily--light:
hash: v1.k794b7964.0a701acbd2d9dac54c345d22841a6d92b6c2b3728421e8fa5fd574a769514e04.Rhb4Qb0bfRbA3ZB2_4f4WM5507JnwCgoox1RbE9y8Ks
+ mcp-apps-stickiness--multiple-series--light:
+ hash: v1.k794b7964.9ffcba3452bbcd678c11f0d873b02a32a97ad071d5fc55f2c00681df9bdc7141.0G-r5IrknmUdR0cBBeCfTQjKKC2nBiE3-F4F0PgX9FQ
+ mcp-apps-stickiness--single-series--light:
+ hash: v1.k794b7964.d1536728712178593de0eeb14f682a2bd5ccccd7b9d693d0605a4e738dace476.NeZoFm3eCYh_b5vTlASuNX6vM7aoJgZd-V09STOVp9o
mcp-apps-surveys--active-popover--light:
hash: v1.k794b7964.c47633461e9a437f0761e09f795eb793b02ed0bac4489ce757a5837dbaa3f847.wclUgXFjBkoHXJLNP2R3ncawfRArgVyVEUWbIiQve0o
mcp-apps-surveys--completed--light:
diff --git a/services/mcp/src/ui-apps/components/Component.tsx b/services/mcp/src/ui-apps/components/Component.tsx
index fb7572b8f6b6..a25292bbe7da 100644
--- a/services/mcp/src/ui-apps/components/Component.tsx
+++ b/services/mcp/src/ui-apps/components/Component.tsx
@@ -9,6 +9,7 @@ import { inferVisualizationType } from './infer-visualization'
import { LifecycleVisualizer } from './LifecycleVisualizer'
import { PathsVisualizer } from './PathsVisualizer'
import { RetentionVisualizer } from './RetentionVisualizer'
+import { StickinessVisualizer } from './StickinessVisualizer'
import { TableVisualizer } from './TableVisualizer'
import { TrendsVisualizer } from './TrendsVisualizer'
import type {
@@ -21,14 +22,30 @@ import type {
PathsResult,
RetentionQuery,
RetentionResult,
+ StickinessQuery,
+ StickinessResult,
TrendsQuery,
TrendsResult,
} from './types'
/** Data payload from MCP tools */
interface DataPayload {
- query?: TrendsQuery | FunnelsQuery | LifecycleQuery | RetentionQuery | PathsQuery | Record<string, unknown>
- results: TrendsResult | FunnelResult | LifecycleResult | RetentionResult | PathsResult | HogQLResult
+ query?:
+ | TrendsQuery
+ | StickinessQuery
+ | FunnelsQuery
+ | LifecycleQuery
+ | RetentionQuery
+ | PathsQuery
+ | Record<string, unknown>
+ results:
+ | TrendsResult
+ | StickinessResult
+ | FunnelResult
+ | LifecycleResult
+ | RetentionResult
+ | PathsResult
+ | HogQLResult
_posthogUrl?: string
}
@@ -75,6 +92,16 @@ export function Component({ data }: ComponentProps): ReactElement {
<FunnelVisualizer query={payload.query as FunnelsQuery} results={payload.results as FunnelResult} />
)
+ case 'stickiness':
+ return (
+ <StickinessVisualizer
+ // The host updates `data` in place, so key on the query to re-seed state per result.
+ key={JSON.stringify(payload.query)}
+ query={payload.query as StickinessQuery}
+ results={payload.results as StickinessResult}
+ />
+ )
+
case 'lifecycle':
return (
<LifecycleVisualizer
diff --git a/services/mcp/src/ui-apps/components/Stickiness.stories.tsx b/services/mcp/src/ui-apps/components/Stickiness.stories.tsx
new file mode 100644
index 000000000000..af2fecc622b2
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/Stickiness.stories.tsx
@@ -0,0 +1,55 @@
+import type { Meta, StoryFn, StoryObj } from '@storybook/react'
+import type { ReactElement } from 'react'
+
+import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
+
+import { StickinessVisualizer } from './StickinessVisualizer'
+import type { StickinessQuery, StickinessResult } from './types'
+
+// Stickiness distribution: how many intervals (here, days) users were active in the period.
+// `count` is the series total (the denominator for the percentage Y-axis); `data` are the raw
+// per-bucket actor counts the visualizer converts to a share of `count`.
+const DAYS = ['1', '2', '3', '4', '5', '6', '7']
+const LABELS = ['1 day', '2 days', '3 days', '4 days', '5 days', '6 days', '7 days']
+
+const RESULTS: StickinessResult = [
+ { label: 'Pageview', count: 1000, data: [620, 180, 90, 50, 30, 18, 12], days: DAYS, labels: LABELS },
+]
+
+const MULTI_SERIES: StickinessResult = [
+ { label: 'Pageview', count: 1000, data: [620, 180, 90, 50, 30, 18, 12], days: DAYS, labels: LABELS },
+ { label: 'Autocapture', count: 400, data: [300, 60, 20, 10, 5, 3, 2], days: DAYS, labels: LABELS },
+]
+
+const stickinessQuery: StickinessQuery = { kind: 'StickinessQuery', interval: 'day' }
+
+// The visualizer sizes its canvas off a ResizeObserver, so give it a definite width — a `w-full` box
+// can measure 0 at mount in the headless snapshot runner and paint nothing.
+const FixedWidth = (Story: StoryFn): ReactElement => (
+ <div className="w-[680px]">
+ <Story />
+ </div>
+)
+
+const meta: Meta = {
+ title: 'MCP Apps/Stickiness',
+ decorators: [McpThemeDecorator, FixedWidth],
+ parameters: {
+ testOptions: {
+ skipDarkMode: true,
+ },
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+export const SingleSeries: Story = {
+ render: () => <StickinessVisualizer query={stickinessQuery} results={RESULTS} />,
+ name: 'Single series',
+}
+
+export const MultipleSeries: Story = {
+ render: () => <StickinessVisualizer query={stickinessQuery} results={MULTI_SERIES} />,
+ name: 'Multiple series',
+}
diff --git a/services/mcp/src/ui-apps/components/StickinessVisualizer.tsx b/services/mcp/src/ui-apps/components/StickinessVisualizer.tsx
new file mode 100644
index 000000000000..68e22379dc6c
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/StickinessVisualizer.tsx
@@ -0,0 +1,90 @@
+import { type ReactElement } from 'react'
+
+import { emptyStateIllustration } from '@posthog/mcp-ui'
+import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'
+import {
+ DefaultTooltip,
+ type Series,
+ TimeSeriesLineChart,
+ type TimeSeriesLineChartConfig,
+ type TooltipContext,
+} from '@posthog/quill-charts'
+
+import { ChartHeader } from './ChartHeader'
+import { colorAt, useMcpChartTheme } from './charts/theme'
+import type { StickinessVisualizerProps } from './types'
+import { getSeriesLabel } from './utils'
+
+const TITLE = 'Stickiness'
+
+const STICKINESS_TOOLTIP_CONFIG = { pinnable: true, placement: 'top' as const }
+
+// The backend returns absolute actor counts per bucket; stickiness reads each bucket as its share
+// of the series' total users (`count`). A zero-total series contributes 0% — never a raw count —
+// so it can't plot unscaled values onto the percentage axis.
+function toPercent(value: number, count: number): number {
+ return count ? (value / count) * 100 : 0
+}
+
+function formatPercent(value: number): string {
+ return `${value.toFixed(1)}%`
+}
+
+const renderStickinessTooltip = (ctx: TooltipContext): ReactElement => (
+ <DefaultTooltip {...ctx} valueFormatter={(value) => formatPercent(value)} />
+)
+
+export function StickinessVisualizer({ query, results }: StickinessVisualizerProps): ReactElement {
+ const theme = useMcpChartTheme()
+
+ const hasData = results?.some((item) => item.count !== 0 && (item.data?.length ?? 0) > 0)
+ if (!results || results.length === 0 || !hasData) {
+ return (
+ <div>
+ <ChartHeader title={TITLE} />
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia>{emptyStateIllustration('chart')}</EmptyMedia>
+ <EmptyDescription>No data available</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </div>
+ )
+ }
+
+ // X-axis is the interval-count distribution ("1 day", "2 days", …), not a time series. Prefer the
+ // API's own bucket labels; synthesize "N {interval}s" from `days` when they're absent.
+ const interval = query?.interval ?? 'day'
+ const labels =
+ results[0]?.labels ?? results[0]?.days?.map((d) => `${d} ${interval}${Number(d) === 1 ? '' : 's'}`) ?? []
+
+ const series: Series[] = results.map((item, i) => ({
+ key: String(i),
+ label: getSeriesLabel(item, i),
+ data: (item.data ?? []).map((value) => toPercent(value, item.count)),
+ color: colorAt(i),
+ }))
+
+ const config: TimeSeriesLineChartConfig = {
+ // No xAxis date config — labels are interval-count buckets, rendered verbatim.
+ yAxis: { tickFormatter: formatPercent, showGrid: true },
+ showCrosshair: true,
+ tooltip: STICKINESS_TOOLTIP_CONFIG,
+ legend: { show: series.length > 1, position: 'bottom' },
+ }
+
+ return (
+ <div>
+ <ChartHeader title={TITLE} />
+ <div className="flex flex-col w-full h-[400px]">
+ <TimeSeriesLineChart
+ series={series}
+ labels={labels}
+ theme={theme}
+ config={config}
+ tooltip={renderStickinessTooltip}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/services/mcp/src/ui-apps/components/infer-visualization.ts b/services/mcp/src/ui-apps/components/infer-visualization.ts
index 32edfa200d73..c6da8b42430c 100644
--- a/services/mcp/src/ui-apps/components/infer-visualization.ts
+++ b/services/mcp/src/ui-apps/components/infer-visualization.ts
@@ -1,6 +1,6 @@
import type { FunnelResult, HogQLResult, LifecycleResult, PathsResult, RetentionResult, TrendsResult } from './types'
-export type VisualizationType = 'trends' | 'funnel' | 'lifecycle' | 'retention' | 'paths' | 'table'
+export type VisualizationType = 'trends' | 'stickiness' | 'funnel' | 'lifecycle' | 'retention' | 'paths' | 'table'
/**
* Lifecycle results share the trends shape but each item carries a `status` field
@@ -129,6 +129,13 @@ export function inferVisualizationType(data: unknown): VisualizationType | null
const d = data as Record<string, unknown>
const results = d.results
+ // Resolve the query kind up front. 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 below
+ // can't match) still resolves to the right visualization.
+ const query = d.query as Record<string, unknown> | undefined
+ const kind = unwrapQueryKind(query)
+
// Infer from results structure first (most reliable)
if (isHogQLResult(results)) {
return 'table'
@@ -145,6 +152,12 @@ export function inferVisualizationType(data: unknown): VisualizationType | null
if (isPathsResult(results)) {
return 'paths'
}
+ // Stickiness rows are structurally identical to trends (`data`/`labels`/`days`), so the query
+ // kind is the only reliable signal — it must be checked before the `isTrendsResult` guard.
+ // Stickiness renders a percentage-of-users distribution, not a raw-count time series.
+ if (kind === 'StickinessQuery') {
+ return 'stickiness'
+ }
if (isTrendsResult(results)) {
return 'trends'
}
@@ -152,12 +165,8 @@ export function inferVisualizationType(data: unknown): VisualizationType | null
return 'funnel'
}
- // 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
- const kind = unwrapQueryKind(query)
+ // Fall back to the query kind when the structural guards above can't match (e.g. a
+ // formatted-results payload). Stickiness is handled above, ahead of the trends shape guard.
if (kind === 'LifecycleQuery') {
return 'lifecycle'
}
diff --git a/services/mcp/src/ui-apps/components/types.ts b/services/mcp/src/ui-apps/components/types.ts
index 49ef273574d2..c2444b5f6d9c 100644
--- a/services/mcp/src/ui-apps/components/types.ts
+++ b/services/mcp/src/ui-apps/components/types.ts
@@ -80,6 +80,21 @@ export interface LifecycleQuery {
}
}
+export interface StickinessQuery {
+ kind: 'StickinessQuery'
+ /** Interval unit the X-axis counts (`day`, `week`, …) — labels the buckets ("N days"). */
+ interval?: string
+ series?: Array<{
+ event?: string
+ name?: string
+ custom_name?: string
+ }>
+ stickinessFilter?: {
+ display?: string
+ showValuesOnSeries?: boolean
+ }
+}
+
export interface HogQLQuery {
kind: 'HogQLQuery'
query: string
@@ -112,6 +127,16 @@ export interface LifecycleResultItem extends TrendsResultItem {
export type LifecycleResult = LifecycleResultItem[]
+/**
+ * Stickiness rows share the trends shape, but `count` (the total distinct users for the series)
+ * is always present and is the denominator for the percentage-of-users Y-axis the chart renders.
+ */
+export interface StickinessResultItem extends TrendsResultItem {
+ count: number
+}
+
+export type StickinessResult = StickinessResultItem[]
+
export interface FunnelStep {
name?: string
custom_name?: string
@@ -235,6 +260,11 @@ export interface LifecycleVisualizerProps {
results: LifecycleResult
}
+export interface StickinessVisualizerProps {
+ query: StickinessQuery | undefined
+ results: StickinessResult
+}
+
export interface TableVisualizerProps {
results: HogQLResult
}
diff --git a/services/mcp/tests/unit/insight-visualizations.test.ts b/services/mcp/tests/unit/insight-visualizations.test.ts
index b7b8102ff79e..3cf3278e530b 100644
--- a/services/mcp/tests/unit/insight-visualizations.test.ts
+++ b/services/mcp/tests/unit/insight-visualizations.test.ts
@@ -67,6 +67,7 @@ describe('insight visualizations', () => {
describe('fallback to query kind', () => {
it.each([
['TrendsQuery', 'trends'],
+ ['StickinessQuery', 'stickiness'],
['FunnelsQuery', 'funnel'],
['LifecycleQuery', 'lifecycle'],
['RetentionQuery', 'retention'],
@@ -86,6 +87,7 @@ describe('insight visualizations', () => {
it.each([
['DataVisualizationNode wrapping HogQLQuery', 'DataVisualizationNode', 'HogQLQuery', 'table'],
['InsightVizNode wrapping TrendsQuery', 'InsightVizNode', 'TrendsQuery', 'trends'],
+ ['InsightVizNode wrapping StickinessQuery', 'InsightVizNode', 'StickinessQuery', 'stickiness'],
['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
@@ -99,15 +101,11 @@ describe('insight visualizations', () => {
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".
- expect(inferVisualizationType(queryPayload([], 'StickinessQuery'))).toBeNull()
- })
-
- it('classifies non-empty stickiness results as trends via the shape check', () => {
+ it('classifies stickiness results as stickiness, not trends, via the query kind', () => {
+ // Stickiness rows duck-type as trends, so the kind check must win — otherwise the
+ // chart renders raw counts instead of the percentage-of-users distribution.
expect(inferVisualizationType(queryPayload(insightResults.stickiness, 'StickinessQuery'))).toBe(
- 'trends'
+ 'stickiness'
)
})