: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
refactor(mcp-analytics): rewire dashboard harness tile onto the query runner (#65399)
Paul D'Ambra7ac5a796f0fd
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsxindex 40978afcf767..98995e048ec2 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx@@ -39,12 +39,14 @@ const SESSION_RESULTS = [['0193f2a1-aaaa-bbbb-cccc-000000000006', 22, 3, 13.6, 410, 6, '2026-06-06T16:20:00Z'],]+// MCPHarnessBreakdownQuery returns already-labelled rows (the runner resolves the+// harness server-side), so these are customer labels, not raw client strings.const HARNESS_RESULTS = [- ['claude-code/1.2.0', 6200, 240, 820],- ['cursor-vscode/0.42', 2100, 96, 410],- ['codex-cli', 980, 71, 180],- ['claude-ai', 760, 22, 240],- ['visual studio code', 540, 12, 120],+ { harness: 'Claude Code', total_calls: 6200, errors: 240, error_rate_pct: 3.9, sessions: 820 },+ { harness: 'Cursor', total_calls: 2100, errors: 96, error_rate_pct: 4.6, sessions: 410 },+ { harness: 'OpenAI Codex', total_calls: 980, errors: 71, error_rate_pct: 7.2, sessions: 180 },+ { harness: 'Claude.ai', total_calls: 760, errors: 22, error_rate_pct: 2.9, sessions: 240 },+ { harness: 'VS Code', total_calls: 540, errors: 12, error_rate_pct: 2.2, sessions: 120 },]const SESSION_LIST = {@@ -306,10 +308,9 @@ const meta: Meta = {'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>const query: string = body?.query?.query ?? ''- // The harness breakdown resolves the client from several signals and- // aliases the result `AS client`; match that output alias rather than any- // one input property so the mock survives changes to the resolution.- if (query.includes('AS client')) {+ // The harness tile sends a typed MCPHarnessBreakdownQuery node (the runner+ // resolves the harness server-side) — match on its kind, not a SQL string.+ if (body?.query?.kind === 'MCPHarnessBreakdownQuery') {return [200, { results: HARNESS_RESULTS }]}if (query.includes('AS session_id')) {diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsxindex 6b57326529e5..66b409a51b7e 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx@@ -28,7 +28,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {notableSessions,sessionRowsLoading,harnessRows,- harnessRawRowsLoading,+ harnessRowsLoading,dailyActivity,activityRowsLoading,toolDailySeries,@@ -95,7 +95,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {interval={interval}/></div>- <HarnessDonut rows={harnessRows} loading={harnessRawRowsLoading} theme={theme} />+ <HarnessDonut rows={harnessRows} loading={harnessRowsLoading} theme={theme} /></div><div className="grid grid-cols-1 gap-[22px] lg:grid-cols-2"><ToolErrorRateChart rows={toolRows} loading={toolRowsLoading} theme={theme} />diff --git a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsxindex 6463f9265dd7..3ef69e389ef8 100644--- a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx+++ b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx@@ -48,11 +48,11 @@ const TOOL_ROWS: ToolRow[] = []const HARNESS_ROWS: HarnessRow[] = [- { category: 'Claude Code', total_calls: 6200, errors: 240, error_rate_pct: 3.9, sessions: 820, raw_clients: [] },- { category: 'Cursor', total_calls: 2100, errors: 96, error_rate_pct: 4.6, sessions: 410, raw_clients: [] },- { category: 'OpenAI Codex', total_calls: 980, errors: 71, error_rate_pct: 7.2, sessions: 180, raw_clients: [] },- { category: 'Claude.ai', total_calls: 760, errors: 22, error_rate_pct: 2.9, sessions: 240, raw_clients: [] },- { category: 'VS Code', total_calls: 540, errors: 12, error_rate_pct: 2.2, sessions: 120, raw_clients: [] },+ { category: 'Claude Code', total_calls: 6200, errors: 240, error_rate_pct: 3.9, sessions: 820 },+ { category: 'Cursor', total_calls: 2100, errors: 96, error_rate_pct: 4.6, sessions: 410 },+ { category: 'OpenAI Codex', total_calls: 980, errors: 71, error_rate_pct: 7.2, sessions: 180 },+ { category: 'Claude.ai', total_calls: 760, errors: 22, error_rate_pct: 2.9, sessions: 240 },+ { category: 'VS Code', total_calls: 540, errors: 12, error_rate_pct: 2.2, sessions: 120 },]const NOTABLE_SESSIONS: NotableSession[] = [diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.tsindex e24377d505ac..338227764a15 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts@@ -13,7 +13,6 @@ import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/typesimport { harnessLogo } from './dashboard/harnessRegistry'import {type ActivityRow,- aggregateHarnessRows,type BucketRow,buildBucketKeys,buildDailyActivity,@@ -22,7 +21,6 @@ import {buildToolDailySeries,categorizeHarness,deltaPct,- type HarnessRawRow,mcpDashboardOverviewLogic,normalizeBucket,pickNotableSessions,@@ -135,27 +133,6 @@ describe('mcpDashboardOverviewLogic', () => {})})- describe('aggregateHarnessRows', () => {- it('folds raw clients into categories, sums counts, and sorts by volume', () => {- const raw: HarnessRawRow[] = [- { client: 'claude-code/1.0', total_calls: 100, errors: 10, sessions: 5 },- { client: 'claude-code/2.0', total_calls: 50, errors: 5, sessions: 3 },- { client: 'cursor/0.4', total_calls: 40, errors: 0, sessions: 2 },- ]- const result = aggregateHarnessRows(raw)- expect(result).toHaveLength(2)- expect(result[0]).toEqual({- category: 'Claude Code',- total_calls: 150,- errors: 15,- error_rate_pct: 10,- sessions: 8,- raw_clients: ['claude-code/1.0', 'claude-code/2.0'],- })- expect(result[1]).toMatchObject({ category: 'Cursor', total_calls: 40, error_rate_pct: 0 })- })- })-describe('buildToolDailySeries', () => {it('pivots flat rows into sorted day labels and per-tool series ordered by volume', () => {const rows: ToolDailyRow[] = [@@ -433,10 +410,15 @@ describe('mcpDashboardOverviewLogic', () => {jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] } as any)})- function reloadCallsSince(callIndex: number): { query: string; filters: Record<string, any> }[] {+ function reloadCallsSince(callIndex: number): any[] {return mockApi.query.mock.calls.slice(callIndex).map((call) => call[0] as any)}+ // HogQL query nodes carry filters under `.filters`; the typed+ // MCPHarnessBreakdownQuery node carries dateRange/properties/filterTestAccounts+ // at the top level. This reads whichever shape a reload used.+ const filtersOf = (call: any): Record<string, any> => call.filters ?? call+it('reloads every tile when the date filter changes', async () => {const logic = mcpDashboardOverviewLogic()logic.mount()@@ -451,10 +433,10 @@ describe('mcpDashboardOverviewLogic', () => {// Six tiles: KPI + the five breakdown queries.expect(reloads.length).toBe(6)// The five breakdowns pass the raw selected range straight through.- const breakdowns = reloads.filter((call) => call.filters.dateRange.date_from === '-30d')+ const breakdowns = reloads.filter((call) => filtersOf(call).dateRange?.date_from === '-30d')expect(breakdowns).toHaveLength(5)// The KPI tile widens to an absolute doubled window so it can compare against the prior period.- const kpi = reloads.find((call) => call.query.includes('AS bucket'))+ const kpi = reloads.find((call) => call.query?.includes('AS bucket'))expect(kpi?.filters.dateRange.date_from).not.toBe('-30d')expect(dayjs(kpi?.filters.dateRange.date_from).isValid()).toBe(true)})@@ -474,7 +456,7 @@ describe('mcpDashboardOverviewLogic', () => {const reloads = reloadCallsSince(callsBefore)expect(reloads.length).toBe(6)- expect(reloads.every((call) => call.filters.filterTestAccounts === enabled)).toBe(true)+ expect(reloads.every((call) => filtersOf(call).filterTestAccounts === enabled)).toBe(true)})it('defaults the filter from the team test_account_filters_default_checked setting', async () => {@@ -487,7 +469,7 @@ describe('mcpDashboardOverviewLogic', () => {// No explicit toggle, yet every tile filters internal users because the team default is on.const reloads = mockApi.query.mock.calls.map((call) => call[0] as any)expect(reloads.length).toBeGreaterThanOrEqual(6)- expect(reloads.every((call) => call.filters.filterTestAccounts === true)).toBe(true)+ expect(reloads.every((call) => filtersOf(call).filterTestAccounts === true)).toBe(true)})const EVENT_FILTER: AnyPropertyFilter = {@@ -519,9 +501,9 @@ describe('mcpDashboardOverviewLogic', () => {const reloads = reloadCallsSince(callsBefore)expect(reloads.length).toBe(6)- expect(reloads.every((call) => JSON.stringify(call.filters.properties) === JSON.stringify([filter]))).toBe(- true- )+ expect(+ reloads.every((call) => JSON.stringify(filtersOf(call).properties) === JSON.stringify([filter]))+ ).toBe(true)})it('syncs property filters to the URL and clears the param when emptied', async () => {diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.tsindex d9da724669e3..eebcfcdf4629 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts@@ -9,7 +9,7 @@ import { dateStringToComponents, dateStringToDayJs, getDefaultInterval } from 'limport { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { HogQLFilters, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { HogQLFilters, HogQLQueryResponse, MCPHarnessBreakdownItem, NodeKind } from '~/queries/schema/schema-general'import { AnyPropertyFilter, IntervalType, TeamType } from '~/types'import { mcpClusteringLogic } from './clustering/mcpClusteringLogic'@@ -91,66 +91,10 @@ ORDER BY total_calls DESCLIMIT 50`-// Resolve an effective client per tool call from the strongest identity signal-// available. The order matters and each step exists for a measured reason:-//-// 1. x-anthropic-client header (mcp_vendor_client). Anthropic pools every UI-// surface behind one transport that self-reports the generic clientInfo.name-// "Anthropic/ClaudeAI", so this header is the only thing that separates-// Cowork / Claude.ai / Claude Design. It is absent for every non-Anthropic-// client and for Claude Code's CLI/SDK/IDE builds (whose surface rides in the-// User-Agent instead), so resolving it first never masks a finer signal.-// 2. Claude Code's User-Agent surface. Every Claude Code build reports the same-// clientInfo.name ("claude-code"); the build (cli / sdk-ts / claude-vscode /-// claude-desktop) lives only in the User-Agent parenthetical. Lift it out so-// the SDK/IDE/Desktop split survives. Gated on the claude-code product token-// because other clients' User-Agents are often bare HTTP libraries (node,-// undici) that must not win over a real clientInfo.name.-// 3. The session-pinned clientInfo.name (mcp_session_client_name). The per-request-// $mcp_client_name is stamped only on $mcp_initialize, never on $mcp_tool_call,-// so reading it here bucketed every self-identifying client — Codex, Cursor,-// opencode, … — as "Other". The generic "mcp" SDK default is dropped so those-// rows fall through to the User-Agent.-// 4. The User-Agent product token + first parenthetical, for hosted clients that-// send a product User-Agent but no clientInfo.name (e.g. "openai-mcp/1.0.0").-// 5. The OAuth client_name from token introspection, the only identity an-// OAuth-registered client (vibe-coding platforms, ChatGPT) carries per request.-//-// The version segment is dropped so claude-code/2.1.x folds to one token;-// categorizeHarness then buckets surface-specific tokens and folds the rest.-//-// The User-Agent token is the leading product name plus the first parenthetical-// (the surface, e.g. "cli"); steps 2 and 4 both need it, so it lives here once.-// HogQL has no scalar WITH alias, but this is a JS template literal — interpolating-// a const keeps the source DRY while the generated SQL stays identical.-const UA_PRODUCT = `extract(toString(properties.$mcp_client_user_agent), '^([^/]+)')`-const UA_TOKEN = `trim(concat(${UA_PRODUCT}, ' ', extract(toString(properties.$mcp_client_user_agent), '[(]([^,)]+)')))`-const HARNESS_ROWS_QUERY = `-SELECT- coalesce(- multiIf(- lower(toString(properties.mcp_vendor_client)) = 'claudecode', 'claude-code',- lower(toString(properties.mcp_vendor_client)) = 'claudeai', 'claude-ai',- lower(toString(properties.mcp_vendor_client)) = 'cowork', 'cowork',- lower(toString(properties.mcp_vendor_client)) = 'claudedesign', 'claude-design',- NULL- ),- if(lower(${UA_PRODUCT}) = 'claude-code', ${UA_TOKEN}, NULL),- nullIf(nullIf(toString(properties.mcp_session_client_name), ''), 'mcp'),- nullIf(${UA_TOKEN}, ''),- nullIf(toString(properties.$mcp_oauth_client_name), ''),- ''- ) AS client,- count() AS total_calls,- countIf(toBool(properties.$mcp_is_error)) AS errors,- countDistinctIf($session_id, $session_id != '') AS sessions-FROM events-WHERE event = '$mcp_tool_call'- AND {filters}-GROUP BY client-ORDER BY total_calls DESC-LIMIT 200-`+// The harness breakdown is resolved server-side by the MCPHarnessBreakdownQuery+// runner (products/mcp_analytics/backend/hogql_queries/harness_breakdown.py) — the+// single source of truth for client → harness labelling — so the tile reads typed,+// already-bucketed rows rather than re-deriving the labels in the browser.// Daily success/error split powering the activity time-series bar chart.const ACTIVITY_QUERY = `@@ -214,13 +158,6 @@ export interface ToolRow {p95_duration_ms: number}-export interface HarnessRawRow {- client: string- total_calls: number- errors: number- sessions: number-}-export interface ActivityRow {day: stringsuccesses: number@@ -250,7 +187,6 @@ export interface HarnessRow {errors: numbererror_rate_pct: numbersessions: number- raw_clients: string[]}export interface SessionRow {@@ -282,35 +218,6 @@ const EMPTY_KPIS: KPIData = {p95LatencyMs: { ...EMPTY_METRIC, goodDirection: 'down' },}-export function aggregateHarnessRows(raw: HarnessRawRow[]): HarnessRow[] {- const byCategory = new Map<string, HarnessRow>()- for (const row of raw) {- const category = categorizeHarness(row.client)- const existing = byCategory.get(category)- if (existing) {- existing.total_calls += row.total_calls- existing.errors += row.errors- existing.sessions += row.sessions- existing.raw_clients.push(row.client)- } else {- byCategory.set(category, {- category,- total_calls: row.total_calls,- errors: row.errors,- error_rate_pct: 0,- sessions: row.sessions,- raw_clients: [row.client],- })- }- }- const result = [...byCategory.values()]- for (const r of result) {- r.error_rate_pct = r.total_calls ? Math.round((r.errors / r.total_calls) * 1000) / 10 : 0- }- result.sort((a, b) => b.total_calls - a.total_calls)- return result-}-// Keep the stacked bar legible: only the busiest tools get their own segment; the long tail is// folded into a single "Other" series so the chart can't sprout dozens of repeating-colour bands.const TOOL_SERIES_LIMIT = 8@@ -592,22 +499,24 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([},},],- harnessRawRows: [- [] as HarnessRawRow[],+ harnessRows: [+ [] as HarnessRow[],{loadHarnessRows: async (_: void, breakpoint) => {+ const { dateRange, properties, filterTestAccounts } = values.queryFiltersconst response = (await api.query({- kind: NodeKind.HogQLQuery,- query: HARNESS_ROWS_QUERY,- filters: values.queryFilters,- })) as HogQLQueryResponse+ kind: NodeKind.MCPHarnessBreakdownQuery,+ dateRange,+ properties,+ filterTestAccounts,+ })) as { results?: MCPHarnessBreakdownItem[] }breakpoint()- const raw = (response?.results as unknown[][]) ?? []- return raw.map((r) => ({- client: String(r[0] ?? ''),- total_calls: Number(r[1] ?? 0),- errors: Number(r[2] ?? 0),- sessions: Number(r[3] ?? 0),+ return (response?.results ?? []).map((r) => ({+ category: r.harness,+ total_calls: r.total_calls,+ errors: r.errors,+ error_rate_pct: r.error_rate_pct,+ sessions: r.sessions,}))},},@@ -680,7 +589,6 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([(dateFilter: DateFilter, timezone: string, interval: IntervalType): string[] =>buildBucketKeys(dateFilter, timezone, interval),],- harnessRows: [(s) => [s.harnessRawRows], (raw: HarnessRawRow[]): HarnessRow[] => aggregateHarnessRows(raw)],dailyActivity: [(s) => [s.activityRows, s.bucketKeys],(rows: ActivityRow[], bucketKeys: string[]): DailyActivity => buildDailyActivity(rows, bucketKeys),