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.

refactor(mcp-analytics): defer tool-detail data and harness labels to the backend (#66090)

Paul D'Ambrac66100d845a8
diff --git a/products/mcp_analytics/backend/mcp_harness.py b/products/mcp_analytics/backend/mcp_harness.py
index 5ef2a791dc91..19fbdeb159eb 100644
--- a/products/mcp_analytics/backend/mcp_harness.py
+++ b/products/mcp_analytics/backend/mcp_harness.py
@@ -13,14 +13,12 @@ query-time computation:
`HARNESS_TOKEN_SQL`.
2. Bucket that token into a customer label — `harness_label_sql`.
-This module is being established as the single source of truth. Today the same
-label logic still lives in two other places that must move in lockstep until they
-are consolidated onto this runner: the frontend's own `categorizeHarness` +
-`HARNESS_REGISTRY` in `products/mcp_analytics/frontend/dashboard/harnessRegistry.ts`
-(its category keys also drive logos/colours), and the documented query in the
-`querying-posthog-data` skill's `models-mcp.md`. Rewiring the dashboard onto this
-runner (and the registry down to logos-by-label) is a follow-up; a cross-language
-test pinning the registry keys to `HARNESS_LABELS` lands with that rewire.
+This module is the single source of truth for harness classification. The frontend no
+longer classifies — `products/mcp_analytics/frontend/dashboard/harnessRegistry.ts` keeps
+only a label-to-logo/colour map (`HARNESS_BY_LABEL`), keyed by the labels this module
+emits, and a cross-language test pins those keys to `HARNESS_LABELS`. The one remaining
+copy that must move in lockstep is the documented query in the `querying-posthog-data`
+skill's `models-mcp.md`.
Because the token appears many times in the bucketing `multiIf`, callers compute
it once as a column (`{HARNESS_TOKEN_SQL} AS h`, or `argMax(..., timestamp)` for a
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
index ada054aebfa5..b34993bd0d2f 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -49,7 +49,6 @@ import {
ToolSummary,
mcpAnalyticsToolDetailLogic,
} from './mcpAnalyticsToolDetailLogic'
-import { categorizeHarness } from './mcpDashboardOverviewLogic'
export const scene: SceneExport<MCPAnalyticsToolDetailLogicProps> = {
component: MCPAnalyticsToolDetail,
@@ -105,9 +104,9 @@ function StatTile({
)
}
-// Renderer for the "person" column in the Top users table. The query selects
-// `argMax(tuple(distinct_id, person.created_at, person.properties), timestamp)`,
-// which deserialises as a 3-element array. Wrap it back into the shape PersonDisplay expects.
+// Renderer for the "person" column in the Top users table. The loader maps each row's
+// person into a [distinct_id, _, person_properties] array. Wrap it back into the shape
+// PersonDisplay expects.
function renderPersonCell(value: unknown): JSX.Element {
if (!Array.isArray(value) || value.length === 0) {
return <span className="text-muted">—</span>
@@ -128,22 +127,15 @@ function renderPersonCell(value: unknown): JSX.Element {
)
}
-// Deduped harness logos so the column stays one line instead of wrapping.
-function HarnessLogos({ value }: { value: string }): JSX.Element {
- const categories = Array.from(
- new Set(
- value
- .split(',')
- .map((raw) => categorizeHarness(raw.trim()))
- .filter(Boolean)
- )
- )
- if (categories.length === 0) {
+// Harness logos for a row. Labels are resolved (deduped + sorted) server-side; the column
+// just maps each label to its logo and stays on one line.
+function HarnessLogos({ labels }: { labels: string[] }): JSX.Element {
+ if (labels.length === 0) {
return <span className="text-muted">—</span>
}
return (
<div className="flex items-center gap-1">
- {categories.map((category) => (
+ {labels.map((category) => (
<HarnessLogo key={category} category={category} />
))}
</div>
@@ -659,7 +651,7 @@ export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.
{ header: 'Error rate', align: 'right', render: (r) => `${Number(r[3] ?? 0)}%` },
{
header: 'Harnesses',
- render: (r) => <HarnessLogos value={String(r[4] ?? '')} />,
+ render: (r) => <HarnessLogos labels={(r[4] as string[]) ?? []} />,
},
{ header: 'Last seen', render: (r) => <TZLabel time={String(r[5])} /> },
]}
@@ -690,7 +682,7 @@ export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.
{ header: 'Last seen', render: (r) => <TZLabel time={String(r[2])} /> },
{
header: 'Harnesses',
- render: (r) => <HarnessLogos value={String(r[3] ?? '')} />,
+ render: (r) => <HarnessLogos labels={(r[3] as string[]) ?? []} />,
},
]}
/>
diff --git a/products/mcp_analytics/frontend/dashboard/harnessRegistry.ts b/products/mcp_analytics/frontend/dashboard/harnessRegistry.ts
index 55ef59c0ec97..f31b9863ff4c 100644
--- a/products/mcp_analytics/frontend/dashboard/harnessRegistry.ts
+++ b/products/mcp_analytics/frontend/dashboard/harnessRegistry.ts
@@ -22,154 +22,54 @@ export interface HarnessLogo {
}
interface HarnessDescriptor {
- category: string
- // Matches against the normalized client token: lowercased, with the
- // "(via mcp-remote …)" suffix stripped (see categorizeHarness).
- match: (normalized: string) => boolean
logo?: HarnessLogo
// Index into the data-viz palette, chosen so the logo drawn on top keeps
// enough contrast against its slice.
colorIndex?: number
}
-// Single source of truth for harness identity — how a normalized client token maps
-// to a display category, its logo, and its slice colour. Adding a new harness is one
-// entry here. Categories were derived from sampling the top distinct client
-// identifiers seen in production (clientInfo.name, the x-anthropic-client vendor
-// header, and User-Agent product tokens) over the past 30 days. The bucket list
-// mirrors the HogQL in products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md
-// — keep the two in sync until a materialized $mcp_harness property exists.
-//
-// The normalized token can carry a surface suffix the query lifts out of the
-// User-Agent's parenthetical, e.g. "claude-code cli", "claude-code claude-desktop",
-// "openai-mcp chatgpt". List surface-specific entries before the generic prefix
-// match so they win; clients whose parenthetical is platform/arch noise (e.g.
-// "cursor darwin arm64") still fold to one bucket via the generic startsWith.
-const HARNESS_REGISTRY: HarnessDescriptor[] = [
- {
- category: 'Claude Desktop',
- match: (n) => n === 'claude-code claude-desktop',
- logo: { src: claudeLogo, alt: 'Claude Desktop logo' },
- colorIndex: 5,
- },
- {
- category: 'Claude Code (VS Code)',
- match: (n) => n === 'claude-code claude-vscode',
- logo: { src: claudeLogo, alt: 'Claude Code logo' },
- colorIndex: 6,
- },
- {
- category: 'Claude Agent SDK',
- match: (n) => n.startsWith('claude-code sdk'),
- logo: { src: claudeLogo, alt: 'Claude Agent SDK logo' },
- colorIndex: 7,
- },
- {
- category: 'Claude Code',
- match: (n) => n.startsWith('claude-code'),
- logo: { src: claudeLogo, alt: 'Claude Code logo' },
- colorIndex: 0,
- },
- {
- category: 'Claude.ai',
- match: (n) => n === 'claude-ai' || n === 'anthropic/claudeai' || n === 'claude-user',
- logo: { src: claudeLogo, alt: 'Claude.ai logo' },
- colorIndex: 2,
- },
- { category: 'Anthropic API', match: (n) => n === 'anthropic/api' },
- { category: 'Cowork', match: (n) => n === 'cowork', logo: { src: claudeLogo, alt: 'Cowork logo' }, colorIndex: 3 },
- {
- category: 'Claude Design',
- match: (n) => n === 'claude-design',
- logo: { src: claudeLogo, alt: 'Claude Design logo' },
- colorIndex: 4,
- },
- {
- category: 'ChatGPT',
- match: (n) => n === 'openai-mcp chatgpt',
- logo: { src: openaiLogo, alt: 'ChatGPT logo' },
- colorIndex: 8,
- },
- {
- category: 'OpenAI Agent Builder',
- match: (n) => n === 'openai-mcp agent builder',
- logo: { src: openaiLogo, alt: 'OpenAI Agent Builder logo' },
- colorIndex: 9,
- },
- {
- category: 'OpenAI Responses API',
- match: (n) => n === 'openai-mcp responses api',
- logo: { src: openaiLogo, alt: 'OpenAI Responses API logo' },
- colorIndex: 10,
- },
- {
- category: 'OpenAI',
- match: (n) => n.startsWith('openai-mcp'),
- logo: { src: openaiLogo, alt: 'OpenAI logo' },
- colorIndex: 1,
- },
- {
- category: 'OpenAI Codex',
- match: (n) => n.startsWith('codex'),
- logo: { src: openaiLogo, alt: 'OpenAI Codex logo' },
- colorIndex: 13,
- },
- {
- category: 'Cursor',
- match: (n) => n.startsWith('cursor'),
- logo: { src: cursorLogo, alt: 'Cursor logo' },
- colorIndex: 12,
- },
- {
- category: 'VS Code',
- match: (n) => n.startsWith('visual studio code'),
- logo: { src: vscodeLogo, alt: 'VS Code logo' },
- colorIndex: 11,
- },
- { category: 'Windsurf', match: (n) => n === 'windsurf', logo: { src: windsurfLogo, alt: 'Windsurf logo' } },
- { category: 'Replit', match: (n) => n.startsWith('replit'), logo: { src: replitLogo, alt: 'Replit logo' } },
- { category: 'Lovable', match: (n) => n.startsWith('lovable'), logo: { src: lovableLogo, alt: 'Lovable logo' } },
- { category: 'Manus', match: (n) => n === 'manus', logo: { src: manusLogo, alt: 'Manus logo' } },
- { category: 'CodeRabbit', match: (n) => n === 'coderabbit', logo: { src: coderabbitLogo, alt: 'CodeRabbit logo' } },
- { category: 'Notion', match: (n) => n.startsWith('notion'), logo: { src: notionLogo, alt: 'Notion logo' } },
- { category: 'Linear', match: (n) => n.startsWith('linear'), logo: { src: linearLogo, alt: 'Linear logo' } },
- {
- category: 'LibreChat',
- match: (n) => n.includes('librechat'),
- logo: { src: librechatLogo, alt: 'LibreChat logo' },
- },
- { category: 'Pi', match: (n) => n.startsWith('pi-client'), logo: { src: piLogo, alt: 'Pi logo' } },
- {
- category: 'Antigravity',
- match: (n) => n.startsWith('antigravity'),
- logo: { src: antigravityLogo, alt: 'Antigravity logo' },
- },
- { category: 'Poke', match: (n) => n === 'poke' },
- { category: 'opencode', match: (n) => n === 'opencode', logo: { src: opencodeLogo, alt: 'opencode logo' } },
- { category: 'Kiro', match: (n) => n.startsWith('kiro') },
- { category: 'Desktop Commander', match: (n) => n.startsWith('desktop-commander') },
-]
-
-const HARNESS_BY_CATEGORY: Record<string, HarnessDescriptor> = Object.fromEntries(
- HARNESS_REGISTRY.map((entry) => [entry.category, entry])
-)
-
-export function categorizeHarness(raw: string): string {
- const stripped = raw
- .replace(/\s*\(via mcp-remote[^)]*\)\s*/i, '')
- .trim()
- .toLowerCase()
- if (!stripped) {
- return 'Other'
- }
- return HARNESS_REGISTRY.find((entry) => entry.match(stripped))?.category ?? 'Other'
+// Maps a *resolved* harness label to its logo and slice colour. The label itself is
+// produced server-side by the backend classifier (products/mcp_analytics/backend/mcp_harness.py,
+// the single source of truth); this map owns only the frontend-specific concerns the backend
+// has no opinion on. Keys must match HARNESS_LABELS / harness_label_sql in mcp_harness.py.
+// Exported so tests can assert coverage against the backend HARNESS_LABELS tuple.
+export const HARNESS_BY_LABEL: Record<string, HarnessDescriptor> = {
+ 'Claude Desktop': { logo: { src: claudeLogo, alt: 'Claude Desktop logo' }, colorIndex: 5 },
+ 'Claude Code (VS Code)': { logo: { src: claudeLogo, alt: 'Claude Code logo' }, colorIndex: 6 },
+ 'Claude Agent SDK': { logo: { src: claudeLogo, alt: 'Claude Agent SDK logo' }, colorIndex: 7 },
+ 'Claude Code': { logo: { src: claudeLogo, alt: 'Claude Code logo' }, colorIndex: 0 },
+ 'Claude.ai': { logo: { src: claudeLogo, alt: 'Claude.ai logo' }, colorIndex: 2 },
+ 'Anthropic API': {},
+ Cowork: { logo: { src: claudeLogo, alt: 'Cowork logo' }, colorIndex: 3 },
+ 'Claude Design': { logo: { src: claudeLogo, alt: 'Claude Design logo' }, colorIndex: 4 },
+ ChatGPT: { logo: { src: openaiLogo, alt: 'ChatGPT logo' }, colorIndex: 8 },
+ 'OpenAI Agent Builder': { logo: { src: openaiLogo, alt: 'OpenAI Agent Builder logo' }, colorIndex: 9 },
+ 'OpenAI Responses API': { logo: { src: openaiLogo, alt: 'OpenAI Responses API logo' }, colorIndex: 10 },
+ OpenAI: { logo: { src: openaiLogo, alt: 'OpenAI logo' }, colorIndex: 1 },
+ 'OpenAI Codex': { logo: { src: openaiLogo, alt: 'OpenAI Codex logo' }, colorIndex: 13 },
+ Cursor: { logo: { src: cursorLogo, alt: 'Cursor logo' }, colorIndex: 12 },
+ 'VS Code': { logo: { src: vscodeLogo, alt: 'VS Code logo' }, colorIndex: 11 },
+ Windsurf: { logo: { src: windsurfLogo, alt: 'Windsurf logo' } },
+ Replit: { logo: { src: replitLogo, alt: 'Replit logo' } },
+ Lovable: { logo: { src: lovableLogo, alt: 'Lovable logo' } },
+ Manus: { logo: { src: manusLogo, alt: 'Manus logo' } },
+ CodeRabbit: { logo: { src: coderabbitLogo, alt: 'CodeRabbit logo' } },
+ Notion: { logo: { src: notionLogo, alt: 'Notion logo' } },
+ Linear: { logo: { src: linearLogo, alt: 'Linear logo' } },
+ LibreChat: { logo: { src: librechatLogo, alt: 'LibreChat logo' } },
+ Pi: { logo: { src: piLogo, alt: 'Pi logo' } },
+ Antigravity: { logo: { src: antigravityLogo, alt: 'Antigravity logo' } },
+ Poke: {},
+ opencode: { logo: { src: opencodeLogo, alt: 'opencode logo' } },
+ Kiro: {},
+ 'Desktop Commander': {},
}
-export function harnessLogo(category: string): HarnessLogo | undefined {
- return HARNESS_BY_CATEGORY[category]?.logo
+export function harnessLogo(label: string): HarnessLogo | undefined {
+ return HARNESS_BY_LABEL[label]?.logo
}
-export function harnessSliceColor(theme: ChartTheme, category: string, fallbackIndex: number): string {
- const index = HARNESS_BY_CATEGORY[category]?.colorIndex ?? fallbackIndex
+export function harnessSliceColor(theme: ChartTheme, label: string, fallbackIndex: number): string {
+ const index = HARNESS_BY_LABEL[label]?.colorIndex ?? fallbackIndex
return theme.colors[index % theme.colors.length]
}
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
index 810f5c96cf4f..67f2ce196ec5 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
@@ -4,8 +4,17 @@ import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { HogQLQueryResponse, MCPHarnessBreakdownItem, NodeKind } from '~/queries/schema/schema-general'
-import { PropertyFilterType } from '~/types'
+import {
+ MCPHarnessBreakdownItem,
+ MCPToolDailyStatItem,
+ MCPToolDescriptionItem,
+ MCPToolFailureItem,
+ MCPToolNeighborItem,
+ MCPToolSampleIntentItem,
+ MCPToolStatsItem,
+ MCPToolTopUserItem,
+ NodeKind,
+} from '~/queries/schema/schema-general'
import type { mcpAnalyticsToolDetailLogicType } from './mcpAnalyticsToolDetailLogicType'
@@ -88,57 +97,22 @@ export interface MCPAnalyticsToolDetailLogicProps {
toolName: string
}
-const NEW_SDK_SOURCE = 'posthog_mcp_analytics'
-
-// HogQL expression that resolves to the *effective* tool name for new-SDK events:
-// the inner tool when the call went through the single-exec wrapper, otherwise
-// the directly-registered tool name. Use anywhere we need to filter/group by tool.
-const EFFECTIVE_TOOL_HOGQL =
- "coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name))"
-
-const NEW_SDK_FILTER = `properties.$mcp_source = '${NEW_SDK_SOURCE}'`
-
-function escapeHogQLString(value: string): string {
- return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
-}
-
-// Standard "this tool, new-SDK only" filter shared by the $mcp_tool_call queries.
-function buildToolFilter(toolName: string): string {
- return `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}' AND ${NEW_SDK_FILTER}`
-}
-
-async function queryRows(query: string): Promise<ResultRows> {
- const response = (await api.query({ kind: NodeKind.HogQLQuery, query })) as HogQLQueryResponse
- return (response.results ?? []) as ResultRows
+// Absolute from/to for an exact N*24h window. A relative '-Nd' would be rounded to the start
+// of the day by the backend's QueryDateRange, widening the window and letting per-section
+// counts drift apart after midnight; the sections must share one window to stay consistent.
+function windowDays(days: number): { date_from: string; date_to: string } {
+ return { date_from: dayjs().subtract(days, 'day').toISOString(), date_to: dayjs().toISOString() }
}
// Tools most often called immediately before/after this one within the same conversation.
-function buildNeighborQuery(toolName: string, direction: 'before' | 'after'): string {
- const windowFn = direction === 'before' ? 'lagInFrame' : 'leadInFrame'
- return `
-WITH tool_calls AS (
- SELECT
- coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)) AS conv_id,
- timestamp,
- ${EFFECTIVE_TOOL_HOGQL} AS tool
- FROM events
- WHERE event = '$mcp_tool_call'
- AND timestamp >= now() - INTERVAL 7 DAY
- AND ${NEW_SDK_FILTER}
- AND notEmpty(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)))
-)
-SELECT neighbor_tool, count() AS co_occurrences
-FROM (
- SELECT
- tool,
- ${windowFn}(tool) OVER (PARTITION BY conv_id ORDER BY timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS neighbor_tool
- FROM tool_calls
-)
-WHERE tool = '${escapeHogQLString(toolName)}' AND neighbor_tool IS NOT NULL AND neighbor_tool != '' AND neighbor_tool != tool
-GROUP BY neighbor_tool
-ORDER BY co_occurrences DESC
-LIMIT 5
-`
+async function neighborRows(toolName: string, direction: 'before' | 'after'): Promise<ResultRows> {
+ const response = (await api.query({
+ kind: NodeKind.MCPToolNeighborsQuery,
+ toolName,
+ neighborDirection: direction,
+ dateRange: windowDays(7),
+ })) as { results?: MCPToolNeighborItem[] }
+ return (response?.results ?? []).map((r) => [r.neighbor_tool, r.co_occurrences])
}
export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>([
@@ -151,34 +125,22 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
null as ToolSummary | null,
{
loadSummary: async (): Promise<ToolSummary | null> => {
- const toolFilter = buildToolFilter(props.toolName)
const response = (await api.query({
- kind: NodeKind.HogQLQuery,
- query: `
-SELECT
- count() AS calls,
- countIf(toBool(properties.$mcp_is_error)) AS errors,
- round(quantile(0.5)(toFloat(properties.$mcp_duration_ms))) AS p50_ms,
- round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_ms,
- uniq(distinct_id) AS users,
- uniq(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id))) AS conversations
-FROM events
-WHERE event = '$mcp_tool_call'
- AND timestamp >= now() - INTERVAL 7 DAY
- AND ${toolFilter}
-`,
- })) as HogQLQueryResponse
- const row = (response.results ?? [])[0]
+ kind: NodeKind.MCPToolStatsQuery,
+ toolName: props.toolName,
+ dateRange: windowDays(7),
+ })) as { results?: MCPToolStatsItem[] }
+ const row = response?.results?.[0]
if (!row) {
return null
}
return {
- calls: Number(row[0]) || 0,
- errors: Number(row[1]) || 0,
- p50_ms: row[2] == null ? null : Number(row[2]),
- p95_ms: row[3] == null ? null : Number(row[3]),
- users: Number(row[4]) || 0,
- conversations: Number(row[5]) || 0,
+ calls: row.calls,
+ errors: row.errors,
+ p50_ms: row.p50_ms,
+ p95_ms: row.p95_ms,
+ users: row.users,
+ conversations: row.conversations,
}
},
},
@@ -187,26 +149,14 @@ WHERE event = '$mcp_tool_call'
[] as DescriptionRevision[],
{
loadDescriptions: async (): Promise<DescriptionRevision[]> => {
- const toolFilter = buildToolFilter(props.toolName)
const response = (await api.query({
- kind: NodeKind.HogQLQuery,
- query: `
-SELECT
- toString(properties.$mcp_tool_description) AS description,
- toString(max(timestamp)) AS last_seen
-FROM events
-WHERE event = '$mcp_tool_call'
- AND timestamp >= now() - INTERVAL 30 DAY
- AND ${toolFilter}
- AND notEmpty(toString(properties.$mcp_tool_description))
-GROUP BY description
-ORDER BY last_seen DESC
-LIMIT 5
-`,
- })) as HogQLQueryResponse
- return (response.results ?? []).map((row) => ({
- description: String(row[0] ?? ''),
- last_seen: String(row[1] ?? ''),
+ kind: NodeKind.MCPToolDescriptionsQuery,
+ toolName: props.toolName,
+ dateRange: windowDays(30),
+ })) as { results?: MCPToolDescriptionItem[] }
+ return (response?.results ?? []).map((r) => ({
+ description: r.description,
+ last_seen: r.last_seen,
}))
},
},
@@ -214,25 +164,18 @@ LIMIT 5
intentCoverage: [
null as IntentCoverage | null,
{
+ // Reads the same MCPToolStatsQuery as `summary`; the coverage denominator is the call count.
loadIntentCoverage: async (): Promise<IntentCoverage | null> => {
- const toolFilter = buildToolFilter(props.toolName)
const response = (await api.query({
- kind: NodeKind.HogQLQuery,
- query: `
-SELECT
- countIf(notEmpty(toString(properties.$mcp_intent)) AND toString(properties.$mcp_intent) != '{}') AS with_intent,
- count() AS total
-FROM events
-WHERE event = '$mcp_tool_call'
- AND timestamp >= now() - INTERVAL 7 DAY
- AND ${toolFilter}
-`,
- })) as HogQLQueryResponse
- const row = (response.results ?? [])[0]
+ kind: NodeKind.MCPToolStatsQuery,
+ toolName: props.toolName,
+ dateRange: windowDays(7),
+ })) as { results?: MCPToolStatsItem[] }
+ const row = response?.results?.[0]
if (!row) {
return null
}
- return { with_intent: Number(row[0]) || 0, total: Number(row[1]) || 0 }
+ return { with_intent: row.with_intent, total: row.calls }
},
},
],
@@ -240,34 +183,19 @@ WHERE event = '$mcp_tool_call'
[] as DailyToolStat[],
{
loadDailyStats: async (): Promise<DailyToolStat[]> => {
- const toolFilter = buildToolFilter(props.toolName)
const response = (await api.query({
- kind: NodeKind.HogQLQuery,
- query: `
-SELECT
- toDate(timestamp) AS day,
- count() AS calls,
- countIf(toBool(properties.$mcp_is_error)) AS errors,
- round(quantile(0.5)(toFloat(properties.$mcp_duration_ms))) AS p50,
- round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95,
- uniq(distinct_id) AS users,
- uniq(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id))) AS sessions
-FROM events
-WHERE event = '$mcp_tool_call'
- AND timestamp >= now() - INTERVAL 30 DAY
- AND ${toolFilter}
-GROUP BY day
-ORDER BY day
-`,
- })) as HogQLQueryResponse
- return (response.results ?? []).map((r) => ({
- day: String(r[0] ?? ''),
- calls: Number(r[1] ?? 0),
- errors: Number(r[2] ?? 0),
- p50: Number(r[3] ?? 0),
- p95: Number(r[4] ?? 0),
- users: Number(r[5] ?? 0),
- sessions: Number(r[6] ?? 0),
+ kind: NodeKind.MCPToolDailyStatsQuery,
+ toolName: props.toolName,
+ dateRange: windowDays(30),
+ })) as { results?: MCPToolDailyStatItem[] }
+ return (response?.results ?? []).map((r) => ({
+ day: r.day,
+ calls: r.calls,
+ errors: r.errors,
+ p50: r.p50,
+ p95: r.p95,
+ users: r.users,
+ sessions: r.sessions,
}))
},
},
@@ -275,79 +203,51 @@ ORDER BY day
failureRows: [
[] as ResultRows,
{
- loadFailureRows: async (): Promise<ResultRows> =>
- queryRows(`
-SELECT
- substring(toString(properties.$exception_message), 1, 200) AS message,
- count() AS occurrences,
- max(timestamp) AS last_seen,
- arrayStringConcat(arraySort(arrayDistinct(groupArray(toString(properties.$mcp_client_name)))), ', ') AS harnesses
-FROM events
--- $exception events don't carry the new-SDK markers ($mcp_source / $mcp_exec_tool_call_name), so
--- unlike the $mcp_tool_call queries this matches the raw $mcp_tool_name without EFFECTIVE_TOOL_HOGQL/NEW_SDK_FILTER.
-WHERE event = '$exception'
- AND timestamp >= now() - INTERVAL 7 DAY
- AND toString(properties.$mcp_tool_name) = '${escapeHogQLString(props.toolName)}'
- AND notEmpty(toString(properties.$exception_message))
-GROUP BY message
-ORDER BY occurrences DESC
-LIMIT 20
-`),
+ loadFailureRows: async (): Promise<ResultRows> => {
+ const response = (await api.query({
+ kind: NodeKind.MCPToolFailuresQuery,
+ toolName: props.toolName,
+ dateRange: windowDays(7),
+ })) as { results?: MCPToolFailureItem[] }
+ return (response?.results ?? []).map((r) => [r.message, r.occurrences, r.last_seen, r.harnesses])
+ },
},
],
sampleIntentRows: [
[] as ResultRows,
{
- loadSampleIntentRows: async (): Promise<ResultRows> =>
- queryRows(`
-SELECT
- timestamp,
- toString(properties.$mcp_intent) AS intent,
- toString(properties.$mcp_intent_source) AS source,
- toString(properties.$mcp_client_name) AS harness
-FROM events
-WHERE event = '$mcp_tool_call'
- AND timestamp >= now() - INTERVAL 7 DAY
- AND ${buildToolFilter(props.toolName)}
- AND notEmpty(toString(properties.$mcp_intent))
- AND toString(properties.$mcp_intent) != '{}'
-ORDER BY timestamp DESC
-LIMIT 5
-`),
+ loadSampleIntentRows: async (): Promise<ResultRows> => {
+ const response = (await api.query({
+ kind: NodeKind.MCPToolSampleIntentsQuery,
+ toolName: props.toolName,
+ dateRange: windowDays(7),
+ })) as { results?: MCPToolSampleIntentItem[] }
+ return (response?.results ?? []).map((r) => [r.timestamp, r.intent, r.intent_source, r.harness])
+ },
},
],
neighborsBeforeRows: [
[] as ResultRows,
{
- loadNeighborsBeforeRows: async (): Promise<ResultRows> =>
- queryRows(buildNeighborQuery(props.toolName, 'before')),
+ loadNeighborsBeforeRows: async (): Promise<ResultRows> => neighborRows(props.toolName, 'before'),
},
],
neighborsAfterRows: [
[] as ResultRows,
{
- loadNeighborsAfterRows: async (): Promise<ResultRows> =>
- queryRows(buildNeighborQuery(props.toolName, 'after')),
+ loadNeighborsAfterRows: async (): Promise<ResultRows> => neighborRows(props.toolName, 'after'),
},
],
byHarnessRows: [
[] as ResultRows,
{
- // Server-resolved harness labels via the same runner as the dashboard, so the
- // pill matches the dashboard's bucketing exactly. The per-tool, new-SDK filter
- // rides along as a HogQL property so the runner applies it inside its WHERE.
+ // Server-resolved harness labels via the same runner as the dashboard (scoped to this
+ // tool's new-SDK calls by toolName), so the pill matches the dashboard's bucketing exactly.
loadByHarnessRows: async (): Promise<ResultRows> => {
const response = (await api.query({
kind: NodeKind.MCPHarnessBreakdownQuery,
- // Absolute from/to give an exact 168h window. A relative '-7d' is rounded to
- // the start of that day by QueryDateRange, which would widen this table's
- // window past the page's other `now() - INTERVAL 7 DAY` queries and let its
- // counts drift from the summary / Top users sections after midnight.
- dateRange: {
- date_from: dayjs().subtract(7, 'day').toISOString(),
- date_to: dayjs().toISOString(),
- },
- properties: [{ type: PropertyFilterType.HogQL, key: buildToolFilter(props.toolName) }],
+ toolName: props.toolName,
+ dateRange: windowDays(7),
})) as { results?: MCPHarnessBreakdownItem[] }
return (response?.results ?? []).map((r) => [
r.harness,
@@ -362,23 +262,22 @@ LIMIT 5
topUserRows: [
[] as ResultRows,
{
- loadTopUserRows: async (): Promise<ResultRows> =>
- queryRows(`
-SELECT
- argMax(tuple(distinct_id, person.created_at, person.properties), timestamp) AS person,
- count() AS calls,
- countIf(toBool(properties.$mcp_is_error)) AS errors,
- round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,
- arrayStringConcat(arraySort(arrayDistinct(groupArray(toString(properties.$mcp_client_name)))), ', ') AS harnesses,
- max(timestamp) AS last_seen
-FROM events
-WHERE event = '$mcp_tool_call'
- AND timestamp >= now() - INTERVAL 7 DAY
- AND ${buildToolFilter(props.toolName)}
-GROUP BY distinct_id
-ORDER BY calls DESC
-LIMIT 5
-`),
+ // The person tuple is rebuilt into the [distinct_id, _, properties] shape renderPersonCell expects.
+ loadTopUserRows: async (): Promise<ResultRows> => {
+ const response = (await api.query({
+ kind: NodeKind.MCPToolTopUsersQuery,
+ toolName: props.toolName,
+ dateRange: windowDays(7),
+ })) as { results?: MCPToolTopUserItem[] }
+ return (response?.results ?? []).map((r) => [
+ [r.distinct_id, '', r.person_properties],
+ r.calls,
+ r.errors,
+ r.error_rate_pct,
+ r.harnesses,
+ r.last_seen,
+ ])
+ },
},
],
})),
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
index 338227764a15..a539d53d3663 100644
--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
@@ -10,7 +10,7 @@ import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
-import { harnessLogo } from './dashboard/harnessRegistry'
+import { HARNESS_BY_LABEL, harnessLogo } from './dashboard/harnessRegistry'
import {
type ActivityRow,
type BucketRow,
@@ -19,7 +19,6 @@ import {
buildKPIs,
buildKpiWindow,
buildToolDailySeries,
- categorizeHarness,
deltaPct,
mcpDashboardOverviewLogic,
normalizeBucket,
@@ -49,50 +48,44 @@ function session(overrides: Partial<SessionRow> & { session_id: string }): Sessi
}
describe('mcpDashboardOverviewLogic', () => {
- describe('categorizeHarness', () => {
- it.each([
- ['claude-code/1.0.0', 'Claude Code'],
- ['claude-code cli', 'Claude Code'],
- ['claude-code claude-desktop', 'Claude Desktop'],
- ['claude-code claude-vscode', 'Claude Code (VS Code)'],
- ['claude-code sdk-ts', 'Claude Agent SDK'],
- ['claude-ai', 'Claude.ai'],
- ['anthropic/claudeai', 'Claude.ai'],
- ['cowork', 'Cowork'],
- ['claude-design', 'Claude Design'],
- ['claude-user', 'Claude.ai'],
- ['openai-mcp', 'OpenAI'],
- ['openai-mcp chatgpt', 'ChatGPT'],
- ['openai-mcp agent builder', 'OpenAI Agent Builder'],
- ['openai-mcp responses api', 'OpenAI Responses API'],
- ['cursor/0.42', 'Cursor'],
- ['cursor darwin arm64', 'Cursor'],
- ['codex-cli', 'OpenAI Codex'],
- // Raw clientInfo.name tokens the harness coalesce now surfaces from
- // mcp_session_client_name (these clients send no useful User-Agent).
- ['codex-mcp-client', 'OpenAI Codex'],
- ['cursor-vscode', 'Cursor'],
- ['opencode', 'opencode'],
- ['Lovable MCP Client', 'Lovable'],
- ['linear-agent', 'Linear'],
- ['@librechat/api-client', 'LibreChat'],
- ['pi-client', 'Pi'],
- ['antigravity-client', 'Antigravity'],
- ['coderabbit', 'CodeRabbit'],
- ['notion-mcp-client', 'Notion'],
- ['replit-agent-mcp-client', 'Replit'],
- ['windsurf', 'Windsurf'],
- ['claude-code sdk-cli', 'Claude Agent SDK'],
- ['claude-code sdk-py', 'Claude Agent SDK'],
- ['visual studio code', 'VS Code'],
- ['something-nobody-knows', 'Other'],
- ['', 'Other'],
- ])('maps %s -> %s', (raw, expected) => {
- expect(categorizeHarness(raw)).toBe(expected)
- })
+ describe('harnessLogo', () => {
+ // The expected labels mirror HARNESS_LABELS in mcp_harness.py, minus "Other".
+ // If the backend renames or adds a label, update this list to keep it in sync
+ // and add the corresponding entry to HARNESS_BY_LABEL in harnessRegistry.ts.
+ const EXPECTED_HARNESS_LABELS = [
+ 'Claude Desktop',
+ 'Claude Code (VS Code)',
+ 'Claude Agent SDK',
+ 'Claude Code',
+ 'Claude.ai',
+ 'Anthropic API',
+ 'Cowork',
+ 'Claude Design',
+ 'ChatGPT',
+ 'OpenAI Agent Builder',
+ 'OpenAI Responses API',
+ 'OpenAI',
+ 'OpenAI Codex',
+ 'Cursor',
+ 'VS Code',
+ 'Windsurf',
+ 'Replit',
+ 'Lovable',
+ 'Manus',
+ 'CodeRabbit',
+ 'Notion',
+ 'Linear',
+ 'LibreChat',
+ 'Pi',
+ 'Antigravity',
+ 'Poke',
+ 'opencode',
+ 'Kiro',
+ 'Desktop Commander',
+ ]
- it('strips the "(via mcp-remote …)" suffix before matching', () => {
- expect(categorizeHarness('claude-code (via mcp-remote 1.2.3)')).toBe('Claude Code')
+ it.each(EXPECTED_HARNESS_LABELS)('HARNESS_BY_LABEL has an entry for backend label %s', (label) => {
+ expect(Object.prototype.hasOwnProperty.call(HARNESS_BY_LABEL, label)).toBe(true)
})
it.each([
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
index eebcfcdf4629..e9245c7c9328 100644
--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
@@ -13,12 +13,9 @@ import { HogQLFilters, HogQLQueryResponse, MCPHarnessBreakdownItem, NodeKind } f
import { AnyPropertyFilter, IntervalType, TeamType } from '~/types'
import { mcpClusteringLogic } from './clustering/mcpClusteringLogic'
-import { categorizeHarness } from './dashboard/harnessRegistry'
import type { MCPIntentClusterApi } from './generated/api.schemas'
import type { mcpDashboardOverviewLogicType } from './mcpDashboardOverviewLogicType'
-export { categorizeHarness }
-
export interface DateFilter {
dateFrom: string | null
dateTo: string | null