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): track insight views and display changes in ui apps (#111326)

Sam Pennington19cf9ad0ea11
diff --git a/common/storybook/.storybook/plugins/vite-frontend-resolve-plugin.ts b/common/storybook/.storybook/plugins/vite-frontend-resolve-plugin.ts
index 39306898c6c5..84dc57d85ddb 100644
--- a/common/storybook/.storybook/plugins/vite-frontend-resolve-plugin.ts
+++ b/common/storybook/.storybook/plugins/vite-frontend-resolve-plugin.ts
@@ -25,6 +25,8 @@ export function frontendResolvePlugin(repoRoot: string): Plugin {
const anchors = [
path.join(repoRoot, 'frontend', 'src', 'index.tsx'),
path.join(repoRoot, 'packages', 'quill', 'packages', 'quill', 'src', 'index.ts'),
+ // Deps of mcp ui-apps source that neither the app nor quill installs.
+ path.join(repoRoot, 'common', 'storybook', 'package.json'),
]
return {
diff --git a/common/storybook/package.json b/common/storybook/package.json
index 2402e3a329f7..9363723779a1 100644
--- a/common/storybook/package.json
+++ b/common/storybook/package.json
@@ -29,6 +29,7 @@
"history": "^5.0.1",
"jest-image-snapshot": "^6.4.0",
"mockdate": "^3.0.5",
+ "posthog-js-lite": "4.12.1",
"sass": "^1.26.2",
"storybook": "catalog:",
"storybook-addon-pseudo-states": "^10.4.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 284144c7bea4..4b48bc6b04bd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -532,6 +532,9 @@ importers:
mockdate:
specifier: ^3.0.5
version: 3.0.5
+ posthog-js-lite:
+ specifier: 4.12.1
+ version: 4.12.1
sass:
specifier: ^1.26.2
version: 1.56.0
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 4164287e0f2a..13334f229034 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -56,7 +56,7 @@ import {
type ToolCallAnalyticsMeta,
} from './analytics'
import type { InstructionsBuilder } from './instructions'
-import { getEffectiveMCPClientContext, resolveSessionKey } from './mcp-context'
+import { getEffectiveMCPClientContext, getEffectiveMCPClientIdentity, resolveSessionKey } from './mcp-context'
import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'
import type { ResolvedState } from './request-state-resolver'
import type { SkillCatalogService } from './skill-catalog-service'
@@ -483,6 +483,8 @@ export class ToolExecutor {
renderUiEnabled: state.renderUiEnabled,
}),
distinctId,
+ mcpClientName: getEffectiveMCPClientIdentity(state.requestContext, state.sessionContext)
+ .mcpClientName,
})
}
@@ -859,6 +861,7 @@ export class ToolExecutor {
state.scopeGatedTools,
{
isInlineExecUiHost: state.clientProfile.isInlineExecUiHost(),
+ mcpClientName: getEffectiveMCPClientIdentity(state.requestContext, state.sessionContext).mcpClientName,
learnCatalog: this.instructionsBuilder.buildExecLearnCatalog(
state,
this.skillCatalogService?.getCatalog()
@@ -887,7 +890,11 @@ export class ToolExecutor {
state: ResolvedState,
analyticsMeta?: ToolCallAnalyticsMeta
): Promise<unknown> {
- const renderUiTool = createRenderUiTool(state.allTools, state.context)
+ const renderUiTool = createRenderUiTool(
+ state.allTools,
+ state.context,
+ getEffectiveMCPClientIdentity(state.requestContext, state.sessionContext).mcpClientName
+ )
if (!renderUiTool) {
return {
content: [{ type: 'text', text: 'render-ui is not available — no tool has a UI app' }],
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.ts
index e355909f8aad..4c1ab3a0c31c 100644
--- a/services/mcp/src/lib/build-tool-result.ts
+++ b/services/mcp/src/lib/build-tool-result.ts
@@ -36,6 +36,7 @@ export interface BuildToolResultOptions {
includeAppData?: boolean | undefined
/** PostHog distinctId for analytics metadata (only read when a UI resource is present). */
distinctId?: string | undefined
+ mcpClientName?: string | undefined
/**
* When set, the inner tool's `_meta.ui.resourceUri` is placed on the response payload
* under both the new (`ui.resourceUri`) and legacy (`ui/resourceUri`) keys. Used by the
@@ -157,6 +158,7 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult
forceUiDataToMeta,
includeAppData,
distinctId,
+ mcpClientName,
includeUiResponseMeta,
includeRenderNote,
} = opts
@@ -196,6 +198,7 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult
const analyticsMetadata: AnalyticsMetadata = {
distinctId: distinctId ?? '',
toolName,
+ ...(mcpClientName ? { mcpClientName } : {}),
}
structuredContent = {
...(rawResult as Record<string, unknown>),
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 5bdd274f2eb4..7ca81d72af24 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -225,6 +225,7 @@ export interface ExecToolOptions {
* re-homed onto `_meta`. Computed from the client profile at the call site.
*/
isInlineExecUiHost?: boolean
+ mcpClientName?: string | undefined
/**
* Resolves the caller's third-party MCP tools (see `lib/gateway-tools.ts`). Awaited
* lazily by the commands that need a tool roster, so a session that never reaches for
@@ -2109,6 +2110,7 @@ export function createExecTool(
forceUiDataToMeta: true,
includeAppData,
distinctId,
+ mcpClientName: options.mcpClientName,
includeUiResponseMeta: isInlineUiAppHost,
includeRenderNote: isInlineUiAppHost,
})
diff --git a/services/mcp/src/tools/render-ui.ts b/services/mcp/src/tools/render-ui.ts
index 7096164d799b..49ae10191926 100644
--- a/services/mcp/src/tools/render-ui.ts
+++ b/services/mcp/src/tools/render-ui.ts
@@ -65,7 +65,11 @@ type RenderUiSchema = ReturnType<typeof makeRenderUiSchema>
* the inner tool: it emits a render directive (`{ tool_name, tool_input, app_key }`
* + the render-ui resourceUri) and the UI app fetches its own data.
*/
-export function createRenderUiTool(allTools: Tool<ZodObjectAny>[], context: Context): Tool<RenderUiSchema> | null {
+export function createRenderUiTool(
+ allTools: Tool<ZodObjectAny>[],
+ context: Context,
+ mcpClientName?: string
+): Tool<RenderUiSchema> | null {
const renderableNames = getRenderableToolNames(allTools)
if (renderableNames.length === 0) {
return null
@@ -112,7 +116,7 @@ export function createRenderUiTool(allTools: Tool<ZodObjectAny>[], context: Cont
tool_name: tool.name,
tool_input: toolInput,
app_key: appKey,
- _analytics: { distinctId, toolName: RENDER_UI_TOOL_NAME },
+ _analytics: { distinctId, toolName: RENDER_UI_TOOL_NAME, ...(mcpClientName ? { mcpClientName } : {}) },
},
_meta: {
ui: { resourceUri: RENDER_UI_RESOURCE_URI },
diff --git a/services/mcp/src/ui-apps/analytics/posthog.ts b/services/mcp/src/ui-apps/analytics/posthog.ts
index 9b4481a49da6..6694cff76cbf 100644
--- a/services/mcp/src/ui-apps/analytics/posthog.ts
+++ b/services/mcp/src/ui-apps/analytics/posthog.ts
@@ -66,12 +66,16 @@ function newInstanceId(): string {
/**
* Identify the user with their PostHog distinct ID from the MCP server.
*/
-export function identifyUser(distinctId: string, toolName?: string): void {
+export function identifyUser(distinctId: string, toolName?: string, mcpClientName?: string): void {
if (!client) {
log('PostHog client not initialized while attempting to identify user', { distinctId, toolName })
return
}
+ if (mcpClientName) {
+ client.register({ $mcp_client_name: mcpClientName })
+ }
+
if (currentDistinctId === distinctId) {
log('User already identified', { distinctId })
return
@@ -185,6 +189,29 @@ export function captureHostContextChanged(params: {
})
}
+export function captureInsightViewed(params: {
+ queryKind?: string | undefined
+ querySourceKind?: string | undefined
+ display?: string | undefined
+ funnelVizType?: string | undefined
+ isSupported: boolean
+}): void {
+ capture('mcp_ui_app_insight_viewed', {
+ query_kind: params.queryKind,
+ query_source_kind: params.querySourceKind,
+ display: params.display,
+ funnel_viz_type: params.funnelVizType,
+ is_supported: params.isSupported,
+ })
+}
+
+export function captureInsightDisplayChanged(params: { from: string; to: string }): void {
+ capture('mcp_ui_app_insight_display_changed', {
+ from_display: params.from,
+ to_display: params.to,
+ })
+}
+
/**
* Capture link opened via host.
*/
diff --git a/services/mcp/src/ui-apps/components/Component.tsx b/services/mcp/src/ui-apps/components/Component.tsx
index a25292bbe7da..62b8cc237fea 100644
--- a/services/mcp/src/ui-apps/components/Component.tsx
+++ b/services/mcp/src/ui-apps/components/Component.tsx
@@ -1,8 +1,9 @@
-import type { ReactElement } from 'react'
+import { type ReactElement, useEffect } from 'react'
import { emptyStateIllustration } from '@posthog/mcp-ui'
import { Card, CardContent, Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'
+import { captureInsightViewed } from '../analytics/posthog'
import { ChartHeader } from './ChartHeader'
import { FunnelVisualizer } from './FunnelVisualizer'
import { inferVisualizationType } from './infer-visualization'
@@ -27,6 +28,7 @@ import type {
TrendsQuery,
TrendsResult,
} from './types'
+import { insightQueryProperties } from './utils'
/** Data payload from MCP tools */
interface DataPayload {
@@ -46,6 +48,8 @@ interface DataPayload {
| RetentionResult
| PathsResult
| HogQLResult
+ /** Saved insight from `insight-query`; its `query` keeps the wrapper node that `query` drops */
+ insight?: { query?: unknown }
_posthogUrl?: string
}
@@ -56,6 +60,19 @@ export interface ComponentProps {
export function Component({ data }: ComponentProps): ReactElement {
const payload = data as DataPayload
const visualizationType = inferVisualizationType(data)
+ const { queryKind, querySourceKind, display, funnelVizType } = insightQueryProperties(
+ payload?.insight?.query ?? payload?.query
+ )
+
+ useEffect(() => {
+ captureInsightViewed({
+ queryKind,
+ querySourceKind,
+ display,
+ funnelVizType,
+ isSupported: visualizationType !== null,
+ })
+ }, [data, visualizationType, queryKind, querySourceKind, display, funnelVizType])
if (!visualizationType) {
return (
diff --git a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
index dc9c8f79baac..0a5ee78f8b36 100644
--- a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
+++ b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
@@ -22,6 +22,7 @@ import {
buildTrendsSeries,
} from 'products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms'
+import { captureInsightDisplayChanged } from '../analytics/posthog'
import { ChartHeader } from './ChartHeader'
import { BigNumber, Select } from './charts'
import { colorAt, useMcpChartTheme } from './charts/theme'
@@ -30,6 +31,7 @@ import {
type ChartType,
chartConfigFromTrendsFilter,
defaultChartType,
+ displayForChartType,
isBarFamily,
resolveChartView,
supportsPercentStack,
@@ -133,6 +135,11 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea
incompleteEnd: !!item.incomplete_end,
}))
const { slopeAvailable, effectiveType } = resolveChartView(chartType, labels.length)
+ const handleChartTypeChange = (next: ChartType): void => {
+ const from = effectiveType === defaultChartType(displayType) ? displayType : displayForChartType(effectiveType)
+ captureInsightDisplayChanged({ from, to: displayForChartType(next) })
+ setChartType(next)
+ }
const chartTypeOptions = slopeAvailable ? [...CHART_TYPE_OPTIONS, SLOPE_TYPE_OPTION] : CHART_TYPE_OPTIONS
// Area auto-stacks, so derived overlays would draw against the stacked totals — disable them.
@@ -215,7 +222,7 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea
<div>
<ChartHeader title={TITLE}>
{/* eslint-disable-next-line react/forbid-elements */}
- <Select value={effectiveType} onChange={setChartType} options={chartTypeOptions} />
+ <Select value={effectiveType} onChange={handleChartTypeChange} options={chartTypeOptions} />
{effectiveType !== 'slope' && (
<ChartSettings
family={isBarFamily(effectiveType) ? 'bar' : 'line'}
diff --git a/services/mcp/src/ui-apps/components/chartSettingsConfig.ts b/services/mcp/src/ui-apps/components/chartSettingsConfig.ts
index f69a4aecf5f4..c8204239ffc1 100644
--- a/services/mcp/src/ui-apps/components/chartSettingsConfig.ts
+++ b/services/mcp/src/ui-apps/components/chartSettingsConfig.ts
@@ -63,6 +63,18 @@ export function defaultChartType(displayType: ChartDisplayType): ChartType {
return 'line'
}
+const DISPLAY_FOR_CHART_TYPE: Record<ChartType, ChartDisplayType> = {
+ line: 'ActionsLineGraph',
+ area: 'ActionsAreaGraph',
+ bar: 'ActionsUnstackedBar',
+ 'stacked-bar': 'ActionsBar',
+ slope: 'SlopeGraph',
+}
+
+export function displayForChartType(chartType: ChartType): ChartDisplayType {
+ return DISPLAY_FOR_CHART_TYPE[chartType]
+}
+
export function isBarFamily(chartType: ChartType): boolean {
return chartType === 'bar' || chartType === 'stacked-bar'
}
diff --git a/services/mcp/src/ui-apps/components/utils.ts b/services/mcp/src/ui-apps/components/utils.ts
index ed4267b73578..c587011784e6 100644
--- a/services/mcp/src/ui-apps/components/utils.ts
+++ b/services/mcp/src/ui-apps/components/utils.ts
@@ -4,6 +4,30 @@ export function getDisplayType(query: TrendsQuery | undefined): ChartDisplayType
return query?.trendsFilter?.display || 'ActionsLineGraph'
}
+export interface InsightQueryProperties {
+ queryKind?: string
+ querySourceKind?: string
+ display?: string
+ funnelVizType?: string
+}
+
+export function insightQueryProperties(query: unknown): InsightQueryProperties {
+ if (typeof query !== 'object' || query === null) {
+ return {}
+ }
+ const node = query as Record<string, unknown>
+ const hasSource = typeof node.source === 'object' && node.source !== null
+ const source = (hasSource ? node.source : node) as Record<string, any>
+ const defaultDisplay =
+ source.kind === 'TrendsQuery' || source.kind === 'StickinessQuery' ? 'ActionsLineGraph' : undefined
+ return {
+ queryKind: typeof node.kind === 'string' ? node.kind : undefined,
+ querySourceKind: hasSource && typeof source.kind === 'string' ? source.kind : undefined,
+ display: source.trendsFilter?.display ?? source.stickinessFilter?.display ?? defaultDisplay,
+ funnelVizType: source.funnelsFilter?.funnelVizType,
+ }
+}
+
export function formatNumber(value: number): string {
if (value >= 1_000_000) {
return `${(value / 1_000_000).toFixed(1)}M`
diff --git a/services/mcp/src/ui-apps/hooks/useToolResult.ts b/services/mcp/src/ui-apps/hooks/useToolResult.ts
index fc4948a68f11..e80f17819d9c 100644
--- a/services/mcp/src/ui-apps/hooks/useToolResult.ts
+++ b/services/mcp/src/ui-apps/hooks/useToolResult.ts
@@ -246,7 +246,7 @@ export function useToolResult<T = unknown>({
// Extract analytics metadata and identify the user
const analytics = extractAnalytics(parsed)
if (analytics) {
- identifyUser(analytics.distinctId, analytics.toolName)
+ identifyUser(analytics.distinctId, analytics.toolName, analytics.mcpClientName)
}
// `hasAppData` and `rendered` separate a healthy result that rode the
diff --git a/services/mcp/src/ui-apps/types.ts b/services/mcp/src/ui-apps/types.ts
index 0fb549bd0a1d..b8be3ffecf42 100644
--- a/services/mcp/src/ui-apps/types.ts
+++ b/services/mcp/src/ui-apps/types.ts
@@ -18,6 +18,8 @@ export interface AnalyticsMetadata {
distinctId: string
/** The name of the tool that generated this result */
toolName?: string
+ /** Same value as `$mcp_client_name` on server-side MCP events */
+ mcpClientName?: string
}
/**
diff --git a/services/mcp/tests/unit/insight-visualizations.test.ts b/services/mcp/tests/unit/insight-visualizations.test.ts
index 3cf3278e530b..9ec8c58f4fd1 100644
--- a/services/mcp/tests/unit/insight-visualizations.test.ts
+++ b/services/mcp/tests/unit/insight-visualizations.test.ts
@@ -16,6 +16,7 @@ import {
formatPercent,
getDisplayType,
getSeriesLabel,
+ insightQueryProperties,
normalizeFunnelSteps,
} from '@/ui-apps/components/utils'
@@ -246,6 +247,26 @@ describe('insight visualizations', () => {
})
})
+ describe('insightQueryProperties', () => {
+ it.each([
+ [
+ 'bare trends without a display',
+ { kind: 'TrendsQuery' },
+ { queryKind: 'TrendsQuery', display: 'ActionsLineGraph' },
+ ],
+ [
+ 'trends wrapped in InsightVizNode',
+ {
+ kind: 'InsightVizNode',
+ source: { kind: 'TrendsQuery', trendsFilter: { display: 'BoldNumber' } },
+ },
+ { queryKind: 'InsightVizNode', querySourceKind: 'TrendsQuery', display: 'BoldNumber' },
+ ],
+ ])('%s', (_, query, expected) => {
+ expect(insightQueryProperties(query)).toEqual(expected)
+ })
+ })
+
describe('normalizeFunnelSteps', () => {
const steps = [
{ name: '$pageview', order: 0, count: 100 },