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-analytics): put intent cluster detail beside the list (#84585)

Daniel Visca882e491cf2f0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 66986a928901..5eb3ebc77d17 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5088,6 +5088,10 @@ snapshots:
hash: v1.k794b7964.4344045fc1bada8b4f2067de9f83cdb38b5dbe14719e7b4d332c2a7689a5d8cd.NvfJs1mb9VLArjiQdsrspse5hcopmjfyz4HXvwD_MZA
products-data-modeling-lineage-graph--single-node--light:
hash: v1.k794b7964.965d630c09110769bac58d2fc162856dc5303d9a98e97995aec4cc48098581da.Gi_VbiOcJVaHaHybXL8911KOWXwBMAGtbHwCIA2HO0E
+ products-mcp-analytics-routingbar--all-variants--dark:
+ hash: v1.k794b7964.769a69526cf676447319f587f24ed0d2670a137098867f8d3ee87ebda3415a70.3FGS0pbxxcrZUSto8SNCNHEkxaFXH6T8shqpdg5zzlQ
+ products-mcp-analytics-routingbar--all-variants--light:
+ hash: v1.k794b7964.7f57dacddb48fbad29a8614127d42d54425501b1f7755423d84316e1e937720e.thYPF2z3eMW5QvSe5SnvYtn35l6UCvUtsyx9EBLeqxk
products-posthog-ai-composer--default--dark:
hash: v1.k794b7964.4ccf5eb666de2b3315dc3f142ded80b445748d58ce8ae2d7d154272d7b194b3b.E61uR16UwC5qC1XkQquxMh1z3bonN6IYLdYDyzcorTA
products-posthog-ai-composer--default--light:
@@ -6901,9 +6905,9 @@ snapshots:
scenes-app-mcp-analytics--dashboard-with-menu-bar--light:
hash: v1.k794b7964.0ac0bf1b02890312bdc239db7a4842f1a377468aa9c5ad67c926aecaccf510ce.V7Onp6uOX4j46-gDndut-qkT9N6LwIUCq5z4hVn-VZg
scenes-app-mcp-analytics--intent-clustering--dark:
- hash: v1.k794b7964.cb042849f291e0ec235b0261605cbe12165c559d1ca4f8de761a18908357270b.wBXNgw84NNQEI1gXsv5uFOiR7cRn5jNApZRApxKV_r0
+ hash: v1.k794b7964.64563081f2752d9d272a03b440d1d8d464e9401f7bba052ad69565ea3af0bc6e.T2vzGEgBaTrMVGr03LZiEmlTcTpJ9yApyM-oMO6RDiw
scenes-app-mcp-analytics--intent-clustering--light:
- hash: v1.k794b7964.484f20160cf83b4effbbc4e9fafeb27cce15dddd192d9e2c84c73d0d389360d1.TgrCvHQoDHfmlNJvQnch5Tgygpu5-sYcVhNems0DVEc
+ hash: v1.k794b7964.5db1fed9a3e5a5490f0d8135c781bffe4a0005510654cc3552978e21094d0d44.LJXBicQp3MWkKTBnnngZdfvu6ZZhmV1exzkPabI3rKs
scenes-app-mcp-analytics--sessions--dark:
hash: v1.k794b7964.e44b6747efcbc630753707078c16ebb36a05f9701fa89c014d8eebec1eabc4fb.i5C5Ib24E2xi_tzTLXniz3WM8UKaAFOj4aqVnMmtIiI
scenes-app-mcp-analytics--sessions--light:
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
index 411cb2ce866c..808d1391c214 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
@@ -310,6 +310,107 @@ const CLUSTER_SNAPSHOT = {
'List all custom events captured in the last 30 days.',
],
journey: null,
+ // Only this cluster carries recovery data, so the story covers both the section
+ // rendering and the other clusters, which stand in for snapshots predating it.
+ switches: [
+ { from_tool: 'query-trends', to_tool: 'execute-sql', count: 6 },
+ { from_tool: 'insight-create', to_tool: 'query-trends', count: 2 },
+ ],
+ self_retries: [{ tool: 'read-data-schema', count: 4 }],
+ },
+ ],
+ tools: [
+ {
+ tool: 'execute-sql',
+ call_count: 1720,
+ error_count: 94,
+ session_count: 61,
+ contested_score: 0.31,
+ advertised_sessions: 74,
+ called_when_advertised: 66,
+ discovery_rate_pct: 89.2,
+ description: 'Run a ClickHouse SQL query against events, persons, and warehouse tables.',
+ n_clusters_served: 3,
+ clusters: [
+ {
+ cluster_id: 1,
+ calls: 1480,
+ capture_pct: 81.3,
+ rank: 1,
+ description_fit: 0.71,
+ top_competitor: { tool: 'read-data-schema', pct: 14.3 },
+ },
+ {
+ cluster_id: 3,
+ calls: 120,
+ capture_pct: 29.3,
+ rank: 2,
+ description_fit: 0.44,
+ top_competitor: { tool: 'read-data-schema', pct: 36.6 },
+ },
+ ],
+ },
+ {
+ // Well described but rarely picked when advertised: the scatter's lower right.
+ tool: 'read-data-schema',
+ call_count: 540,
+ error_count: 5,
+ session_count: 58,
+ contested_score: 0.66,
+ advertised_sessions: 74,
+ called_when_advertised: 18,
+ discovery_rate_pct: 24.3,
+ description: 'List the events, properties, and property values available in the project.',
+ n_clusters_served: 3,
+ clusters: [
+ {
+ cluster_id: 3,
+ calls: 150,
+ capture_pct: 36.6,
+ rank: 1,
+ description_fit: 0.78,
+ top_competitor: { tool: 'execute-sql', pct: 29.3 },
+ },
+ ],
+ },
+ {
+ // No description and too few advertised sessions, so fit and discovery are unmeasurable.
+ tool: 'insight-create',
+ call_count: 370,
+ error_count: 8,
+ session_count: 30,
+ contested_score: 0.52,
+ advertised_sessions: 3,
+ called_when_advertised: 2,
+ discovery_rate_pct: null,
+ description: null,
+ n_clusters_served: 2,
+ clusters: [
+ {
+ cluster_id: 2,
+ calls: 320,
+ capture_pct: 46.4,
+ rank: 1,
+ description_fit: null,
+ top_competitor: { tool: 'query-trends', pct: 34.8 },
+ },
+ ],
+ },
+ ],
+ tool_overlaps: [
+ {
+ tool_a: 'execute-sql',
+ tool_b: 'read-data-schema',
+ contested_calls: 270,
+ sessions_with_both: 41,
+ sessions_with_either: 78,
+ },
+ {
+ tool_a: 'insight-create',
+ tool_b: 'query-trends',
+ contested_calls: 140,
+ sessions_with_both: 9,
+ sessions_with_either: 44,
},
],
}
diff --git a/products/mcp_analytics/frontend/clustering/ClusterDetailPanel.tsx b/products/mcp_analytics/frontend/clustering/ClusterDetailPanel.tsx
new file mode 100644
index 000000000000..1e5ee60dfc5b
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/ClusterDetailPanel.tsx
@@ -0,0 +1,224 @@
+import { useValues } from 'kea'
+
+import { IconArrowRight, IconRefresh, IconWarning } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+import {
+ Badge,
+ Progress,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@posthog/quill-primitives'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { MCPIntentClusterApi } from '../generated/api.schemas'
+import { ClusterJourneySankey } from './ClusterJourneySankey'
+import { EntropyBadge } from './EntropyBadge'
+import { mcpClusteringLogic } from './mcpClusteringLogic'
+
+function SectionLabel({ children, hint }: { children: string; hint?: string }): JSX.Element {
+ return (
+ <div className="flex flex-col">
+ <span className="text-xs uppercase text-muted font-medium">{children}</span>
+ {hint ? <span className="text-xs text-muted">{hint}</span> : null}
+ </div>
+ )
+}
+
+/**
+ * Everything known about the selected intent group. Lives beside the list rather than
+ * below it, so a click is always visible, and its header stays pinned while the
+ * sections scroll — the selected label is the only thing tying the two panes together.
+ */
+export function ClusterDetailPanel(): JSX.Element {
+ const { selectedCluster, clusters } = useValues(mcpClusteringLogic)
+
+ if (!selectedCluster) {
+ return (
+ <div className="flex h-full items-center justify-center rounded border border-primary bg-surface-primary p-6 text-center text-sm text-muted">
+ {clusters.length === 0
+ ? 'No intent groups in this snapshot yet.'
+ : 'Pick an intent group to see the goals behind it and the tools it routes to.'}
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex h-full min-h-0 flex-col overflow-hidden rounded border border-primary bg-surface-primary">
+ <ClusterDetailHeader cluster={selectedCluster} />
+ <div className="flex-1 min-h-0 overflow-y-auto flex flex-col gap-4 p-4" data-quill>
+ <IntentsSection cluster={selectedCluster} />
+ <RoutingSection cluster={selectedCluster} />
+ <RecoverySection cluster={selectedCluster} />
+ <section className="flex flex-col gap-2">
+ <SectionLabel>Agent journeys</SectionLabel>
+ <ClusterJourneySankey journey={selectedCluster.journey ?? null} />
+ </section>
+ </div>
+ </div>
+ )
+}
+
+function ClusterDetailHeader({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Element {
+ const worstTool = [...cluster.tool_distribution].sort((a, b) => b.error_rate_pct - a.error_rate_pct)[0]
+
+ return (
+ <header className="shrink-0 flex flex-col gap-2 border-b border-primary p-4" data-quill>
+ <div className="flex flex-col gap-1">
+ <span className="text-xs uppercase text-muted font-medium">Selected intent group</span>
+ <h3 className="text-lg font-semibold leading-tight m-0">{cluster.label}</h3>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <EntropyBadge entropy={cluster.routing_entropy} />
+ <Badge variant={cluster.error_rate_pct > 5 ? 'destructive' : 'default'}>
+ {cluster.error_rate_pct.toFixed(1)}% errors
+ </Badge>
+ <Badge variant="default">{humanFriendlyNumber(cluster.call_count)} calls</Badge>
+ <Badge variant="default">
+ {cluster.session_count} session{cluster.session_count === 1 ? '' : 's'}
+ </Badge>
+ <Badge variant="default">
+ {cluster.intent_count} intent{cluster.intent_count === 1 ? '' : 's'}
+ </Badge>
+ </div>
+ {worstTool && worstTool.error_rate_pct > 0 ? (
+ <div className="flex items-center gap-1 text-xs text-muted">
+ <IconWarning className="text-danger" />
+ Weakest tool here: <span className="font-mono">{worstTool.tool}</span>
+ <span className="text-danger ml-1">{worstTool.error_rate_pct.toFixed(1)}% errors</span>
+ </div>
+ ) : null}
+ </header>
+ )
+}
+
+function IntentsSection({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Element {
+ return (
+ <section className="flex flex-col gap-2">
+ <SectionLabel>What agents said they were doing</SectionLabel>
+ {cluster.sample_intents.length === 0 ? (
+ <div className="text-sm text-muted">No representative intents recorded.</div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ {cluster.sample_intents.map((intent, idx) => (
+ <div key={idx} className="bg-surface-secondary rounded p-2 text-xs font-mono leading-relaxed">
+ &ldquo;{intent}&rdquo;
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+ )
+}
+
+function RoutingSection({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Element {
+ return (
+ <section className="flex flex-col gap-2">
+ <SectionLabel>Tools this goal routes to</SectionLabel>
+ <Table fullWidth>
+ <TableHeader>
+ <TableRow>
+ <TableHead expand>Tool</TableHead>
+ <TableHead align="right">Calls</TableHead>
+ <TableHead>Share</TableHead>
+ <TableHead align="right">Errors</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {cluster.tool_distribution.map((row) => (
+ <TableRow key={row.tool}>
+ <TableCell expand>
+ <span className="font-mono">{row.tool}</span>
+ </TableCell>
+ <TableCell align="right">{humanFriendlyNumber(row.count)}</TableCell>
+ <TableCell>
+ <div className="flex min-w-[120px] items-center gap-2">
+ <Progress value={row.pct} className="flex-1" />
+ <span className="w-10 text-right text-xs tabular-nums text-muted">
+ {row.pct.toFixed(1)}%
+ </span>
+ </div>
+ </TableCell>
+ <TableCell align="right">
+ {row.error_rate_pct > 0 ? (
+ <span className="tabular-nums text-danger">
+ {row.error_rate_pct.toFixed(1)}%{' '}
+ <span className="text-muted">({row.errors})</span>
+ </span>
+ ) : (
+ <span className="text-muted">0%</span>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </section>
+ )
+}
+
+/**
+ * What agents did after an error. Both lists are capped by the backend, so they read
+ * as "at least this many" rather than a total.
+ *
+ * Snapshots stored before these fields existed carry neither, so both are treated as
+ * absent rather than empty — the schema marks them required, the stored JSONB doesn't.
+ */
+function RecoverySection({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Element | null {
+ const switches = cluster.switches ?? []
+ const selfRetries = cluster.self_retries ?? []
+ if (switches.length === 0 && selfRetries.length === 0) {
+ return null
+ }
+
+ return (
+ <section className="flex flex-col gap-2">
+ <SectionLabel hint="Counts are the strongest cases the run kept, not every occurrence.">
+ What agents did after an error
+ </SectionLabel>
+ {switches.length > 0 ? (
+ <div className="flex flex-col gap-1">
+ <Tooltip title="An errored call followed immediately by a different tool for the same goal. The clearest sign agents mix these tools up.">
+ <span className="text-xs text-muted cursor-help w-fit">Gave up and switched tool</span>
+ </Tooltip>
+ <div className="flex flex-wrap gap-1">
+ {switches.map((sw, idx) => (
+ <span
+ key={idx}
+ className="flex items-center gap-1 rounded bg-surface-secondary px-1.5 py-0.5 text-xs"
+ >
+ <span className="font-mono">{sw.from_tool}</span>
+ <IconArrowRight className="text-muted" />
+ <span className="font-mono">{sw.to_tool}</span>
+ <span className="text-muted tabular-nums">×{sw.count}</span>
+ </span>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ {selfRetries.length > 0 ? (
+ <div className="flex flex-col gap-1">
+ <Tooltip title="An errored call retried immediately with the same tool, which suggests the error message didn't tell the agent how to fix the call.">
+ <span className="text-xs text-muted cursor-help w-fit">Retried the same tool</span>
+ </Tooltip>
+ <div className="flex flex-wrap gap-1">
+ {selfRetries.map((retry, idx) => (
+ <span
+ key={idx}
+ className="flex items-center gap-1 rounded bg-surface-secondary px-1.5 py-0.5 text-xs"
+ >
+ <IconRefresh className="text-muted" />
+ <span className="font-mono">{retry.tool}</span>
+ <span className="text-muted tabular-nums">×{retry.count}</span>
+ </span>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ </section>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx b/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx
index 69c1aeb462ce..50d6a7bfc0c1 100644
--- a/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx
+++ b/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx
@@ -1,10 +1,14 @@
import { useMemo } from 'react'
import { Tooltip } from '@posthog/lemon-ui'
+import type { ChartTheme } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
import sankey, { sankeyLeft, sankeyLinkHorizontal } from '~/vendor/d3/sankey'
import type { MCPIntentClusterJourneyApi, MCPIntentClusterJourneyPathApi } from '../generated/api.schemas'
+import { ERROR_SERIES, PRIMARY_SERIES, seriesColor } from './seriesColors'
const WIDTH = 720
const HEIGHT = 300
@@ -31,7 +35,7 @@ function describePath(path: MCPIntentClusterJourneyPathApi): string {
return labels.filter((label, idx) => label !== ENDED_LABEL || idx === labels.indexOf(ENDED_LABEL)).join(' → ')
}
-function nodeFill(kind: NodeKind): string {
+function nodeFill(kind: NodeKind, theme: ChartTheme): string {
switch (kind) {
case 'init':
return 'var(--muted)'
@@ -40,10 +44,10 @@ function nodeFill(kind: NodeKind): string {
case 'completed':
return 'var(--success)'
case 'error':
- return 'var(--danger)'
+ return seriesColor(theme, ERROR_SERIES)
case 'tool':
default:
- return 'var(--accent)'
+ return seriesColor(theme, PRIMARY_SERIES)
}
}
@@ -111,6 +115,7 @@ interface Props {
}
export function ClusterJourneySankey({ journey }: Props): JSX.Element | null {
+ const theme = useChartTheme()
const graph = useMemo(() => (journey ? buildGraph(journey.paths) : { nodes: [], links: [] }), [journey])
const layout = useMemo(() => {
@@ -171,7 +176,7 @@ export function ClusterJourneySankey({ journey }: Props): JSX.Element | null {
<g>
{layout.links.map((link, idx) => {
const path = linkGen(link) ?? ''
- const stroke = link.outcome === 'error' ? 'var(--danger)' : 'var(--accent)'
+ const stroke = seriesColor(theme, link.outcome === 'error' ? ERROR_SERIES : PRIMARY_SERIES)
const sourceName = (link.source as unknown as JourneyNode).name
const targetName = (link.target as unknown as JourneyNode).name
const pct =
@@ -219,7 +224,7 @@ export function ClusterJourneySankey({ journey }: Props): JSX.Element | null {
height={Math.max(1, node.y1 - node.y0)}
rx={2}
// eslint-disable-next-line react/forbid-dom-props
- style={{ fill: nodeFill(node.kind) }}
+ style={{ fill: nodeFill(node.kind, theme) }}
/>
<text
x={node.x0 + (node.x1 - node.x0) / 2}
diff --git a/products/mcp_analytics/frontend/clustering/ClusterListPanel.tsx b/products/mcp_analytics/frontend/clustering/ClusterListPanel.tsx
new file mode 100644
index 000000000000..f231750408c0
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/ClusterListPanel.tsx
@@ -0,0 +1,115 @@
+import { useActions, useValues } from 'kea'
+
+import { IconSearch } from '@posthog/icons'
+import {
+ Button,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ InputGroupText,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@posthog/quill-primitives'
+
+import { useChartTheme } from 'lib/charts/hooks'
+
+import { ClusterListRow } from './ClusterListRow'
+import { ClusterSortKey, mcpClusteringLogic } from './mcpClusteringLogic'
+import { PRIMARY_SERIES, seriesColor } from './seriesColors'
+
+const SORT_OPTIONS: { value: ClusterSortKey; label: string }[] = [
+ { value: 'calls', label: 'Most calls' },
+ { value: 'errors', label: 'Worst error rate' },
+ { value: 'entropy', label: 'Most spread out' },
+ { value: 'concentration', label: 'Least focused' },
+]
+
+export function ClusterListPanel(): JSX.Element {
+ const { filteredClusters, selectedClusterId, sortKey, toolSearch, clusterFilter, totalClusterCount, clusters } =
+ useValues(mcpClusteringLogic)
+ const { selectCluster, setSortKey, setToolSearch, setClusterFilter } = useActions(mcpClusteringLogic)
+ // Resolved once here: the row component renders per cluster and the theme hook is not free.
+ const theme = useChartTheme()
+ const barColor = seriesColor(theme, PRIMARY_SERIES)
+
+ const isNarrowed = clusterFilter !== 'all' || toolSearch.trim() !== ''
+
+ return (
+ <div className="flex h-full min-h-0 flex-col overflow-hidden rounded border border-primary bg-surface-primary">
+ <div className="shrink-0 flex flex-col gap-2 border-b border-primary p-2" data-quill>
+ <div className="flex items-center gap-2">
+ <InputGroup className="flex-1">
+ <InputGroupAddon align="inline-start">
+ <InputGroupText>
+ <IconSearch />
+ </InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ type="search"
+ placeholder="Filter by tool name"
+ value={toolSearch}
+ onChange={(e) => setToolSearch(e.target.value)}
+ />
+ </InputGroup>
+ <Select value={sortKey} onValueChange={(value) => setSortKey(value as ClusterSortKey)}>
+ <SelectTrigger data-attr="mcp-clustering-sort">
+ <SelectValue>
+ {(value: ClusterSortKey) => SORT_OPTIONS.find((o) => o.value === value)?.label ?? value}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {SORT_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="flex items-center justify-between gap-2 text-xs text-muted">
+ <span>
+ {isNarrowed
+ ? `${filteredClusters.length} of ${clusters.length} shown`
+ : totalClusterCount > clusters.length
+ ? `Top ${clusters.length} of ${totalClusterCount} by call volume`
+ : `${clusters.length} intent group${clusters.length === 1 ? '' : 's'}`}
+ </span>
+ {isNarrowed ? (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ setClusterFilter('all')
+ setToolSearch('')
+ }}
+ data-attr="mcp-clustering-clear-filters"
+ >
+ Clear
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ <div className="flex-1 min-h-0 overflow-y-auto" data-attr="mcp-clustering-list">
+ {filteredClusters.length === 0 ? (
+ <div className="p-4 text-center text-sm text-secondary">No intent groups match these filters.</div>
+ ) : (
+ <ul className="flex flex-col list-none pl-0 m-0 divide-y divide-primary">
+ {filteredClusters.map((cluster) => (
+ <li key={cluster.id}>
+ <ClusterListRow
+ cluster={cluster}
+ isActive={cluster.id === selectedClusterId}
+ onSelect={selectCluster}
+ barColor={barColor}
+ />
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/ClusterListRow.tsx b/products/mcp_analytics/frontend/clustering/ClusterListRow.tsx
new file mode 100644
index 000000000000..0a3f4c6c81b8
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/ClusterListRow.tsx
@@ -0,0 +1,65 @@
+import { memo, useEffect, useRef } from 'react'
+
+import { Badge } from '@posthog/quill-primitives'
+
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { MCPIntentClusterApi } from '../generated/api.schemas'
+import { RoutingBar } from './RoutingBar'
+
+export const ClusterListRow = memo(function ClusterListRow({
+ cluster,
+ isActive,
+ onSelect,
+ barColor,
+}: {
+ cluster: MCPIntentClusterApi
+ isActive: boolean
+ onSelect: (clusterId: number) => void
+ barColor: string
+}): JSX.Element {
+ const ref = useRef<HTMLButtonElement>(null)
+
+ useEffect(() => {
+ // Sorting, filtering, and deep links can all select a row that is scrolled out
+ // of view; without this the detail pane changes with nothing visible to explain why.
+ if (isActive) {
+ ref.current?.scrollIntoView({ block: 'nearest' })
+ }
+ }, [isActive])
+
+ const topTool = cluster.tool_distribution[0]
+
+ return (
+ <button
+ ref={ref}
+ type="button"
+ data-attr="mcp-cluster-row"
+ aria-pressed={isActive}
+ onClick={() => onSelect(cluster.id)}
+ className={cn(
+ 'w-full text-left cursor-pointer border-l-2 px-2 py-1.5 text-xs flex flex-col gap-1',
+ isActive
+ ? 'border-l-accent bg-accent-highlight-secondary'
+ : 'border-l-transparent hover:bg-accent-highlight-secondary'
+ )}
+ >
+ {/* Labels run long and some are a sentence; two lines beats truncating to a stub. */}
+ <span className="font-medium line-clamp-2">{cluster.label}</span>
+ <RoutingBar cluster={cluster} color={barColor} />
+ <div className="flex items-center justify-between gap-2 text-secondary">
+ <span className="truncate font-mono">
+ {topTool ? `${topTool.tool} ${topTool.pct.toFixed(0)}%` : 'no tools recorded'}
+ </span>
+ <span className="flex shrink-0 items-center gap-1.5 tabular-nums">
+ {humanFriendlyNumber(cluster.call_count)} calls
+ {/* Pill rather than red text, matching how tool quality shows an error rate. */}
+ {cluster.error_count > 0 ? (
+ <Badge variant="destructive">{cluster.error_rate_pct.toFixed(1)}%</Badge>
+ ) : null}
+ </span>
+ </div>
+ </button>
+ )
+})
diff --git a/products/mcp_analytics/frontend/clustering/ClusterScorecards.tsx b/products/mcp_analytics/frontend/clustering/ClusterScorecards.tsx
new file mode 100644
index 000000000000..69f9e195921d
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/ClusterScorecards.tsx
@@ -0,0 +1,98 @@
+import { useActions, useValues } from 'kea'
+
+import { Card, CardContent } from '@posthog/quill-primitives'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { type ClusterFilter, type RouteShapeCounts, mcpClusteringLogic } from './mcpClusteringLogic'
+
+interface Scorecard {
+ filter: Exclude<ClusterFilter, 'all'>
+ label: string
+ description: string
+ count: (counts: RouteShapeCounts) => number
+ danger?: boolean
+}
+
+const SCORECARDS: Scorecard[] = [
+ {
+ filter: 'concentrated',
+ label: 'Concentrated',
+ description: 'One tool handles at least 80% of the calls.',
+ count: (c) => c.concentrated,
+ },
+ {
+ filter: 'mixed',
+ label: 'Mixed',
+ description: 'The top tool handles between half and 80%.',
+ count: (c) => c.mixed,
+ },
+ {
+ filter: 'spread',
+ label: 'Spread',
+ description: 'No single tool handles half the calls.',
+ count: (c) => c.spread,
+ },
+ {
+ filter: 'failing',
+ label: 'With errors',
+ description: 'Lost at least one call to an error.',
+ count: (c) => c.failing,
+ danger: true,
+ },
+]
+
+/**
+ * Each card states how many intent groups have a routing shape, and filters the list
+ * to exactly those. The counts and the filters share one predicate in the logic, so a
+ * card can't report one number and show another.
+ */
+export function ClusterScorecards(): JSX.Element {
+ const { routeShapeCounts, clusterFilter } = useValues(mcpClusteringLogic)
+ const { setClusterFilter } = useActions(mcpClusteringLogic)
+
+ return (
+ <div className="grid grid-cols-2 lg:grid-cols-4 gap-2">
+ {SCORECARDS.map((card) => {
+ const isActive = clusterFilter === card.filter
+ const count = card.count(routeShapeCounts)
+ return (
+ <button
+ key={card.filter}
+ type="button"
+ data-attr={`mcp-clustering-scorecard-${card.filter}`}
+ aria-pressed={isActive}
+ onClick={() => setClusterFilter(isActive ? 'all' : card.filter)}
+ className="w-full text-left"
+ >
+ <Card
+ size="sm"
+ className={cn(
+ 'h-full transition-colors',
+ isActive
+ ? 'border-accent bg-accent-highlight-secondary'
+ : 'hover:bg-accent-highlight-secondary'
+ )}
+ >
+ <CardContent className="flex flex-col items-start">
+ <span className="text-muted text-xs font-medium uppercase">{card.label}</span>
+ <span className="mt-1 flex items-baseline gap-1">
+ <span
+ className={cn(
+ 'text-2xl font-semibold tabular-nums',
+ card.danger && count > 0 ? 'text-danger' : ''
+ )}
+ >
+ {count}
+ </span>
+ <span className="text-muted text-sm">of {routeShapeCounts.total}</span>
+ </span>
+ <span className="text-muted mt-1 text-xs">{card.description}</span>
+ </CardContent>
+ </Card>
+ </button>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/ClusteringCoverageBanner.tsx b/products/mcp_analytics/frontend/clustering/ClusteringCoverageBanner.tsx
index b7fc6f16e73e..aec8370fe7d6 100644
--- a/products/mcp_analytics/frontend/clustering/ClusteringCoverageBanner.tsx
+++ b/products/mcp_analytics/frontend/clustering/ClusteringCoverageBanner.tsx
@@ -34,5 +34,7 @@ export function ClusteringCoverageBanner(): JSX.Element | null {
parts.push(`descriptions captured for ${meta.description_coverage_pct.toFixed(0)}% of tools`)
}
- return <div className="text-xs text-muted">{parts.join(' · ')}.</div>
+ // The leading separator belongs to this component: it follows the run timestamp in the
+ // status row and has to disappear along with it when there is no coverage to report.
+ return <span className="text-xs text-muted">· {parts.join(' · ')}.</span>
}
diff --git a/products/mcp_analytics/frontend/clustering/ClusteringSplitPane.tsx b/products/mcp_analytics/frontend/clustering/ClusteringSplitPane.tsx
new file mode 100644
index 000000000000..d7ffd006f8a7
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/ClusteringSplitPane.tsx
@@ -0,0 +1,110 @@
+import { useValues } from 'kea'
+import { useRef } from 'react'
+
+import { Resizer } from 'lib/components/Resizer/Resizer'
+import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
+import { useWindowSize } from 'lib/hooks/useWindowSize'
+import { cn } from 'lib/utils/css-classes'
+
+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
+
+interface ClusteringSplitPaneProps {
+ /** Distinguishes the persisted widths of the two clustering views. */
+ logicKey: string
+ defaultWidth: number
+ list: JSX.Element
+ detail: JSX.Element
+}
+
+/**
+ * Side-by-side list and detail, so selecting a row always changes something inside the
+ * viewport. Follows the sessions tab, which uses the same Resizer split and the same
+ * stacked fallback once the window is too narrow for two columns.
+ */
+export function ClusteringSplitPane({ logicKey, defaultWidth, list, detail }: ClusteringSplitPaneProps): JSX.Element {
+ const { sidePanelWidth } = useValues(panelLayoutLogic)
+ const { isWindowLessThan } = useWindowSize({ widthOffset: sidePanelWidth })
+ const isVerticalLayout = isWindowLessThan('xl')
+
+ return (
+ <div
+ className={cn(
+ // Viewport minus the app chrome, tab strip, status row and scorecards above it,
+ // so both panes scroll internally instead of the page scrolling as a whole.
+ 'w-full h-[calc(100vh-22rem)] min-h-[25rem] flex',
+ isVerticalLayout ? 'flex-col gap-2' : 'flex-row gap-2'
+ )}
+ >
+ {isVerticalLayout ? (
+ <VerticalLayout logicKey={logicKey} list={list} detail={detail} />
+ ) : (
+ <HorizontalLayout logicKey={logicKey} defaultWidth={defaultWidth} list={list} detail={detail} />
+ )}
+ </div>
+ )
+}
+
+function HorizontalLayout({
+ logicKey,
+ defaultWidth,
+ list,
+ detail,
+}: Omit<ClusteringSplitPaneProps, 'logicKey'> & { logicKey: string }): JSX.Element {
+ const listRef = useRef<HTMLDivElement>(null)
+ const resizerLogicProps: ResizerLogicProps = {
+ logicKey: `${logicKey}-horizontal`,
+ containerRef: listRef,
+ persistent: true,
+ placement: 'right',
+ }
+ const { desiredSize } = useValues(resizerLogic(resizerLogicProps))
+
+ return (
+ <>
+ <div
+ ref={listRef}
+ className="relative flex flex-col shrink-0"
+ // A numeric floor rather than min-content: the tool table's intrinsic width
+ // would otherwise override both the default and anything the resizer sets.
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: desiredSize ?? defaultWidth, minWidth: 280, maxWidth: '70%' }}
+ >
+ {list}
+ <Resizer {...resizerLogicProps} visible={false} offset="0.25rem" handleClassName="rounded my-1" />
+ </div>
+ <div className="flex-1 min-w-0 h-full">{detail}</div>
+ </>
+ )
+}
+
+function VerticalLayout({
+ logicKey,
+ list,
+ detail,
+}: Pick<ClusteringSplitPaneProps, 'logicKey' | 'list' | 'detail'>): JSX.Element {
+ const detailRef = useRef<HTMLDivElement>(null)
+ const resizerLogicProps: ResizerLogicProps = {
+ logicKey: `${logicKey}-vertical`,
+ containerRef: detailRef,
+ persistent: true,
+ placement: 'bottom',
+ }
+ const { desiredSize } = useValues(resizerLogic(resizerLogicProps))
+
+ return (
+ <>
+ {/* Detail on top when stacked: a list above it would push it off screen again,
+ which is the failure this layout exists to fix. */}
+ <div
+ ref={detailRef}
+ className="relative shrink-0"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height: desiredSize ?? 360, minHeight: 240 }}
+ >
+ {detail}
+ <Resizer {...resizerLogicProps} visible={false} offset="0.25rem" handleClassName="rounded mx-1" />
+ </div>
+ <div className="relative flex flex-col min-h-0 flex-1">{list}</div>
+ </>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx b/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx
index 2218ab136733..a6e53d42ac91 100644
--- a/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx
+++ b/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx
@@ -2,9 +2,11 @@ import { useValues } from 'kea'
import { Tooltip } from '@posthog/lemon-ui'
+import { useChartTheme } from 'lib/charts/hooks'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { ScatterPoint, fitDomain, mcpClusteringLogic } from './mcpClusteringLogic'
+import { PRIMARY_SERIES, seriesColor } from './seriesColors'
const WIDTH = 640
const HEIGHT = 280
@@ -35,6 +37,7 @@ function radius(callCount: number, maxCalls: number): number {
*/
export function DiscoveryScatter(): JSX.Element | null {
const { scatterPoints, tools, fitMedian, discoveryMedian } = useValues(mcpClusteringLogic)
+ const theme = useChartTheme()
if (scatterPoints.length === 0) {
return (
@@ -54,6 +57,7 @@ export function DiscoveryScatter(): JSX.Element | null {
const plotX: [number, number] = [PAD.left, WIDTH - PAD.right]
const plotY: [number, number] = [HEIGHT - PAD.bottom, PAD.top]
const unplotted = tools.length - scatterPoints.length
+ const bubbleColor = seriesColor(theme, PRIMARY_SERIES)
return (
<div className="bg-surface-primary border rounded p-4 flex flex-col gap-2">
@@ -148,9 +152,9 @@ export function DiscoveryScatter(): JSX.Element | null {
cx={scale(point.fit, xDomain, plotX)}
cy={scale(point.discoveryRatePct, [0, 100], plotY)}
r={radius(point.callCount, maxCalls)}
- fill="var(--accent)"
+ fill={bubbleColor}
fillOpacity={0.55}
- stroke="var(--accent)"
+ stroke={bubbleColor}
className="cursor-help"
/>
</Tooltip>
diff --git a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
index 60550982e281..8cca1b08ea5f 100644
--- a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
+++ b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
@@ -1,164 +1,25 @@
import { useActions, useValues } from 'kea'
-import { IconRefresh, IconSearch, IconSparkles, IconWarning } from '@posthog/icons'
-import { Tooltip } from '@posthog/lemon-ui'
-import {
- Badge,
- Button,
- InputGroup,
- InputGroupAddon,
- InputGroupInput,
- InputGroupText,
- Progress,
- Skeleton,
- Spinner,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from '@posthog/quill-primitives'
+import { IconRefresh, IconSparkles } from '@posthog/icons'
+import { Button, Skeleton, Spinner } from '@posthog/quill-primitives'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
-import type { MCPIntentClusterApi, MCPIntentClusterToolEntryApi } from '../generated/api.schemas'
+import { ClusterDetailPanel } from './ClusterDetailPanel'
import { ClusteringCoverageBanner } from './ClusteringCoverageBanner'
-import { ClusterJourneySankey } from './ClusterJourneySankey'
-import { DiscoveryScatter } from './DiscoveryScatter'
-import { EntropyBadge } from './EntropyBadge'
-import { ClusterSortKey, ClusteringViewMode, mcpClusteringLogic } from './mcpClusteringLogic'
-import { ToolIntentDetail } from './ToolIntentDetail'
-import { ToolOverlapTable } from './ToolOverlapTable'
-import { ToolPivotTable } from './ToolPivotTable'
-
-const SORT_LABELS: Record<ClusterSortKey, string> = {
- calls: 'Calls',
- errors: 'Error rate',
- entropy: 'Routing entropy',
- concentration: 'Top-tool %',
-}
+import { ClusteringSplitPane } from './ClusteringSplitPane'
+import { ClusterListPanel } from './ClusterListPanel'
+import { ClusterScorecards } from './ClusterScorecards'
+import { ClusteringViewMode, mcpClusteringLogic } from './mcpClusteringLogic'
+import { ToolDetailPanel } from './ToolDetailPanel'
+import { ToolsListPanel } from './ToolsListPanel'
const VIEW_LABELS: Record<ClusteringViewMode, string> = {
intents: 'By intent',
tools: 'By tool',
}
-function HeatmapCell({
- entry,
- size,
- rowMaxCount,
-}: {
- entry: MCPIntentClusterToolEntryApi | undefined
- size: number
- rowMaxCount: number
-}): JSX.Element {
- const sizeStyle = { width: size, height: size }
- if (!entry || entry.count === 0) {
- return (
- <div
- className="rounded-[2px] bg-surface-secondary/30"
- // eslint-disable-next-line react/forbid-dom-props
- style={sizeStyle}
- aria-hidden
- />
- )
- }
- // Scale relative to the row's max — so the most-called tool in each
- // cluster is fully dark and the rest grade down. A 1-call tool next to
- // a 50-call tool still shows up clearly thanks to the 0.3 floor.
- const intensity = rowMaxCount > 0 ? entry.count / rowMaxCount : 0
- const opacity = Math.max(0.3, Math.min(1, intensity))
- const hasErrors = entry.error_rate_pct > 0
- return (
- <Tooltip
- title={
- <div className="flex flex-col gap-0.5">
- <span className="font-semibold">{entry.tool}</span>
- <span>{entry.count.toLocaleString()} calls</span>
- <span>{entry.pct.toFixed(1)}% of cluster</span>
- {hasErrors ? <span className="text-danger">{entry.error_rate_pct.toFixed(1)}% errors</span> : null}
- </div>
- }
- >
- <div
- className="rounded-[2px] cursor-help"
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- ...sizeStyle,
- backgroundColor: hasErrors ? 'var(--danger)' : 'var(--accent)',
- opacity,
- }}
- />
- </Tooltip>
- )
-}
-
-function Scorecards(): JSX.Element {
- const { concentratedRoutes, spreadRoutes, topErrorRoute, clusters, totalClusterCount } =
- useValues(mcpClusteringLogic)
-
- const concentratedShare =
- concentratedRoutes.total > 0 ? Math.round((100 * concentratedRoutes.focused) / concentratedRoutes.total) : 0
-
- return (
- <div className="flex flex-col gap-1">
- {totalClusterCount > clusters.length ? (
- <div className="text-xs text-muted">
- Scorecards cover the top {clusters.length} of {totalClusterCount} clusters by call volume.
- </div>
- ) : null}
- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
- <div className="bg-surface-primary border rounded p-3 min-h-[88px] flex flex-col">
- <span className="text-muted text-xs font-medium uppercase">Concentrated routes</span>
- <div className="flex items-baseline gap-2 mt-1">
- <span className="text-2xl font-semibold">
- {concentratedRoutes.focused}
- <span className="text-muted text-base"> / {concentratedRoutes.total}</span>
- </span>
- <span className="text-xs text-muted">({concentratedShare}%)</span>
- </div>
- <span className="text-xs text-muted mt-1">Intent groups where one tool handles ≥80% of calls.</span>
- </div>
- <div className="bg-surface-primary border rounded p-3 min-h-[88px] flex flex-col">
- <span className="text-muted text-xs font-medium uppercase">Spread routes</span>
- <div className="flex items-baseline gap-2 mt-1">
- <span className="text-2xl font-semibold">{spreadRoutes}</span>
- <span className="text-xs text-muted">of {clusters.length}</span>
- </div>
- <span className="text-xs text-muted mt-1">
- Intent groups where no single tool covers half the calls — possible drift.
- </span>
- </div>
- <div className="bg-surface-primary border rounded p-3 min-h-[88px] flex flex-col">
- <span className="text-muted text-xs font-medium uppercase">Top error route</span>
- {topErrorRoute && topErrorRoute.error_rate_pct > 0 ? (
- <>
- <div className="flex items-baseline gap-2 mt-1">
- <span className="text-2xl font-semibold text-danger">
- {topErrorRoute.error_rate_pct.toFixed(1)}%
- </span>
- <span className="text-xs text-muted">over {topErrorRoute.call_count} calls</span>
- </div>
- <span className="text-xs text-muted mt-1 truncate" title={topErrorRoute.label}>
- {topErrorRoute.label}
- </span>
- </>
- ) : (
- <>
- <div className="flex items-baseline gap-2 mt-1">
- <span className="text-2xl font-semibold text-success">0%</span>
- </div>
- <span className="text-xs text-muted mt-1">No errors observed across clusters.</span>
- </>
- )}
- </div>
- </div>
- </div>
- )
-}
-
function ViewToggle(): JSX.Element {
const { viewMode } = useValues(mcpClusteringLogic)
const { setViewMode } = useActions(mcpClusteringLogic)
@@ -179,331 +40,10 @@ function ViewToggle(): JSX.Element {
)
}
-function ToolSearchInput(): JSX.Element {
- const { toolSearch } = useValues(mcpClusteringLogic)
- const { setToolSearch } = useActions(mcpClusteringLogic)
- return (
- <InputGroup className="w-[220px]">
- <InputGroupAddon align="inline-start">
- <InputGroupText>
- <IconSearch />
- </InputGroupText>
- </InputGroupAddon>
- <InputGroupInput
- placeholder="Filter by tool name"
- value={toolSearch}
- onChange={(e) => setToolSearch(e.target.value)}
- />
- </InputGroup>
- )
-}
-
-function SortHeader(): JSX.Element {
- const { sortKey } = useValues(mcpClusteringLogic)
- const { setSortKey } = useActions(mcpClusteringLogic)
- return (
- <div className="flex items-center justify-between gap-2 flex-wrap">
- <div className="flex items-center gap-2 flex-wrap">
- <span className="text-xs text-muted">Sort clusters by</span>
- {(Object.keys(SORT_LABELS) as ClusterSortKey[]).map((key) => (
- <Button
- key={key}
- size="sm"
- variant={sortKey === key ? 'default' : 'outline'}
- onClick={() => setSortKey(key)}
- >
- {SORT_LABELS[key]}
- </Button>
- ))}
- </div>
- <ToolSearchInput />
- </div>
- )
-}
-
-function Heatmap(): JSX.Element {
- const { visibleClusters, hiddenClusterCount, toolColumns, totalToolCount, selectedClusterId } =
- useValues(mcpClusteringLogic)
- const { selectCluster, showAllClusters } = useActions(mcpClusteringLogic)
- const { toolSearch } = useValues(mcpClusteringLogic)
-
- if (toolColumns.length === 0) {
- return (
- <div className="bg-surface-primary border rounded p-4 text-center text-muted text-sm">
- {toolSearch.trim()
- ? `No clusters call a tool matching "${toolSearch.trim()}". Clear the search to see all clusters.`
- : 'No tool calls observed in any cluster yet.'}
- </div>
- )
- }
-
- // Spacious mode: few tools and shortish names. Bigger cells, horizontal labels.
- // Compact mode: many tools or long names. Github-style with rotated labels.
- const longestName = Math.max(...toolColumns.map((t) => t.length))
- const isSpacious = toolColumns.length <= 6 && longestName <= 14
-
- const cellSize = isSpacious ? 22 : 14
- const columnWidth = isSpacious ? 0 : 18 // 0 = let CSS auto-size to label width
-
- const hiddenToolCount = totalToolCount - toolColumns.length
-
- return (
- <div className="bg-surface-primary border rounded">
- <div className="overflow-x-auto">
- <table className="text-sm border-collapse" style={{ borderSpacing: 0 }}>
- <thead>
- <tr className="bg-surface-secondary text-[10px] text-muted">
- <th className="text-left px-3 py-2 sticky left-0 bg-surface-secondary z-10 min-w-[220px] align-bottom text-xs">
- Intent cluster
- </th>
- {toolColumns.map((tool) =>
- isSpacious ? (
- <th
- key={tool}
- className="px-2 pb-1 pt-2 font-medium font-mono text-[11px] text-center align-bottom whitespace-nowrap"
- title={tool}
- >
- {tool}
- </th>
- ) : (
- <th
- key={tool}
- className="px-0 pb-1 pt-2 font-medium align-bottom"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ width: columnWidth, minWidth: columnWidth, maxWidth: columnWidth }}
- >
- <div
- className="font-mono text-[10px] mx-auto whitespace-nowrap overflow-hidden text-ellipsis"
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- writingMode: 'vertical-rl',
- transform: 'rotate(180deg)',
- height: 96,
- lineHeight: '18px',
- }}
- title={tool}
- >
- {tool}
- </div>
- </th>
- )
- )}
- <th className="px-3 py-2 text-right text-xs align-bottom">Calls</th>
- <th className="px-3 py-2 text-right text-xs align-bottom">Errors</th>
- <th className="px-3 py-2 text-left text-xs align-bottom">Routing</th>
- </tr>
- </thead>
- <tbody>
- {visibleClusters.map((cluster) => {
- const isSelected = cluster.id === selectedClusterId
- const byTool = new Map(cluster.tool_distribution.map((e) => [e.tool, e]))
- const rowMaxCount = cluster.tool_distribution.reduce(
- (max, entry) => Math.max(max, entry.count),
- 0
- )
- // Sticky cells need their own background — `tr` backgrounds don't paint
- // through to sticky-positioned children when scrolled horizontally.
- const rowBg = isSelected
- ? 'bg-accent/10'
- : 'bg-surface-primary group-hover:bg-surface-secondary/60'
- return (
- <tr
- key={cluster.id}
- onClick={() => selectCluster(cluster.id)}
- className={`group border-t border-primary cursor-pointer transition-colors ${
- isSelected ? 'bg-accent/10' : 'hover:bg-surface-secondary/60'
- }`}
- >
- <td
- className={`px-3 py-1.5 sticky left-0 z-10 min-w-[220px] max-w-[280px] transition-colors ${rowBg}`}
- >
- <div className="flex flex-col">
- <span className="font-medium truncate" title={cluster.label}>
- {cluster.label}
- </span>
- <span className="text-[10px] text-muted">
- {cluster.session_count} session
- {cluster.session_count === 1 ? '' : 's'} · {cluster.intent_count} intent
- {cluster.intent_count === 1 ? '' : 's'}
- </span>
- </div>
- </td>
- {toolColumns.map((tool) => (
- <td
- key={tool}
- className="p-0 align-middle"
- // eslint-disable-next-line react/forbid-dom-props
- style={
- isSpacious
- ? undefined
- : {
- width: columnWidth,
- minWidth: columnWidth,
- maxWidth: columnWidth,
- }
- }
- >
- <div className="flex justify-center items-center py-[2px]">
- <HeatmapCell
- entry={byTool.get(tool)}
- size={cellSize}
- rowMaxCount={rowMaxCount}
- />
- </div>
- </td>
- ))}
- <td className="px-3 py-1.5 text-right tabular-nums text-xs">
- {cluster.call_count.toLocaleString()}
- </td>
- <td
- className={`px-3 py-1.5 text-right tabular-nums text-xs ${
- cluster.error_rate_pct > 5 ? 'text-danger font-semibold' : ''
- }`}
- >
- {cluster.error_rate_pct.toFixed(1)}%
- </td>
- <td className="px-3 py-1.5">
- <EntropyBadge entropy={cluster.routing_entropy} />
- </td>
- </tr>
- )
- })}
- </tbody>
- </table>
- </div>
- {(hiddenClusterCount > 0 || hiddenToolCount > 0) && (
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-primary px-3 py-2 text-xs text-muted">
- {hiddenClusterCount > 0 ? (
- <>
- <span>
- Showing the top {visibleClusters.length} of{' '}
- {visibleClusters.length + hiddenClusterCount} clusters.
- </span>
- <Button size="sm" variant="outline" onClick={showAllClusters}>
- Show all
- </Button>
- </>
- ) : null}
- {hiddenToolCount > 0 ? (
- <span>
- Columns show the top {toolColumns.length} of {totalToolCount} tools by call volume. Select a
- cluster to see its full tool breakdown.
- </span>
- ) : null}
- </div>
- )}
- </div>
- )
-}
-
-function ClusterDetail({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Element {
- const worstTool = [...cluster.tool_distribution].sort((a, b) => b.error_rate_pct - a.error_rate_pct)[0]
- return (
- <div className="bg-surface-primary border rounded p-4 flex flex-col gap-4">
- <header className="flex flex-col gap-2">
- <div className="flex items-start justify-between gap-3">
- <div className="flex flex-col gap-1 min-w-0">
- <span className="text-xs uppercase text-muted font-medium">Selected cluster</span>
- <h3 className="text-lg font-semibold leading-tight">{cluster.label}</h3>
- </div>
- <div className="flex flex-wrap items-center gap-2 shrink-0">
- <EntropyBadge entropy={cluster.routing_entropy} />
- <Badge variant={cluster.error_rate_pct > 5 ? 'destructive' : 'default'}>
- {cluster.error_rate_pct.toFixed(1)}% errors
- </Badge>
- <Badge variant="default">{cluster.call_count.toLocaleString()} calls</Badge>
- <Badge variant="default">
- {cluster.session_count} session{cluster.session_count === 1 ? '' : 's'}
- </Badge>
- <Badge variant="default">
- {cluster.intent_count} intent{cluster.intent_count === 1 ? '' : 's'}
- </Badge>
- </div>
- </div>
- {worstTool && worstTool.error_rate_pct > 0 ? (
- <div className="flex items-center gap-1 text-xs text-muted">
- <IconWarning className="text-danger" />
- Weakest tool in this cluster: <span className="font-mono">{worstTool.tool}</span>
- <span className="text-danger ml-1">{worstTool.error_rate_pct.toFixed(1)}% errors</span>
- </div>
- ) : null}
- </header>
-
- <section className="flex flex-col gap-2">
- <span className="text-xs uppercase text-muted font-medium">Sample intents in this cluster</span>
- {cluster.sample_intents.length === 0 ? (
- <div className="text-sm text-muted">No representative intents recorded.</div>
- ) : (
- <div className="flex flex-col gap-2">
- {cluster.sample_intents.map((intent, idx) => (
- <div
- key={idx}
- className="bg-surface-secondary rounded p-2 text-xs font-mono leading-relaxed"
- >
- <span className="text-muted mr-1">&ldquo;</span>
- {intent}
- <span className="text-muted ml-1">&rdquo;</span>
- </div>
- ))}
- </div>
- )}
- </section>
-
- <section className="flex flex-col gap-2">
- <span className="text-xs uppercase text-muted font-medium">Tool routing breakdown</span>
- <div data-quill>
- <Table fullWidth>
- <TableHeader>
- <TableRow>
- <TableHead expand>Tool</TableHead>
- <TableHead align="right">Calls</TableHead>
- <TableHead>Share of cluster</TableHead>
- <TableHead align="right">Errors</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {cluster.tool_distribution.map((row) => (
- <TableRow key={row.tool}>
- <TableCell expand>
- <span className="font-mono">{row.tool}</span>
- </TableCell>
- <TableCell align="right">{row.count.toLocaleString()}</TableCell>
- <TableCell>
- <div className="flex min-w-[160px] items-center gap-2">
- <Progress value={row.pct} className="flex-1" />
- <span className="w-10 text-right text-xs tabular-nums text-muted">
- {row.pct.toFixed(1)}%
- </span>
- </div>
- </TableCell>
- <TableCell align="right">
- {row.error_rate_pct > 0 ? (
- <span className="tabular-nums text-danger">
- {row.error_rate_pct.toFixed(1)}%{' '}
- <span className="text-muted">({row.errors})</span>
- </span>
- ) : (
- <span className="text-muted">0%</span>
- )}
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </div>
- </section>
-
- <section className="flex flex-col gap-2">
- <span className="text-xs uppercase text-muted font-medium">Agent journeys</span>
- <ClusterJourneySankey journey={cluster.journey ?? null} />
- </section>
- </div>
- )
-}
-
function StatusRow(): JSX.Element | null {
- const { snapshot, isComputing, clusters, totalClusterCount } = useValues(mcpClusteringLogic)
+ const { snapshot, isComputing } = useValues(mcpClusteringLogic)
const { recompute } = useActions(mcpClusteringLogic)
+
if (snapshot.status === 'error') {
return null
}
@@ -511,45 +51,28 @@ function StatusRow(): JSX.Element | null {
return (
<div className="flex items-center gap-2 text-sm text-muted">
<Spinner />
- Embedding intents and clustering — usually 30–60 seconds.
+ Embedding intents and clustering — usually 30 to 60 seconds.
</div>
)
}
- if (snapshot.last_computed_at) {
- const meta = snapshot.computed_with
- return (
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
- <span>Last computed</span>
- <TZLabel time={snapshot.last_computed_at} />
- {meta ? (
- <>
- <span>·</span>
- <span>
- {totalClusterCount > clusters.length
- ? `top ${clusters.length} of ${totalClusterCount} clusters`
- : `${totalClusterCount} clusters`}
- </span>
- <span>·</span>
- <span>{meta.n_intents} intents</span>
- <span>·</span>
- <span>cosine threshold {meta.distance_threshold.toFixed(2)}</span>
- </>
- ) : null}
- </div>
- <Button
- variant="outline"
- size="sm"
- onClick={recompute}
- data-attr="mcp-analytics-intent-clusters-recompute"
- >
- <IconRefresh />
- Recompute
- </Button>
- </div>
- )
+ if (!snapshot.last_computed_at) {
+ return null
}
- return null
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
+ <span>Last computed</span>
+ <TZLabel time={snapshot.last_computed_at} />
+ {/* Renders nothing when the snapshot predates coverage metadata, so it
+ carries its own separator rather than leaving a dangling one here. */}
+ <ClusteringCoverageBanner />
+ </div>
+ <Button variant="outline" size="sm" onClick={recompute} data-attr="mcp-analytics-intent-clusters-recompute">
+ <IconRefresh />
+ Recompute
+ </Button>
+ </div>
+ )
}
function EmptyState(): JSX.Element {
@@ -563,16 +86,15 @@ function EmptyState(): JSX.Element {
<IconSparkles className="text-4xl text-accent" />
<h3 className="text-lg font-semibold">No intent clusters yet</h3>
<p className="text-sm text-muted max-w-md">
- Clustering groups your agents&apos; session-level goals into themes, then shows which tools each theme
- routes to. It surfaces whether your MCP sends similar goals to the same tools, and which routes are the
- most error-prone.
+ Clustering groups the goals your agents reported into themes, then shows which tools each theme routes
+ to. It surfaces whether similar goals reach the same tools, and which routes fail most.
</p>
<Button variant="default" onClick={recompute} disabled={snapshotLoading}>
{snapshotLoading ? <Spinner /> : <IconSparkles />}
Compute intent clusters
</Button>
<span className="text-xs text-muted">
- Needs sessions with a summarized intent — usually a few minutes after sessions are recorded.
+ Needs sessions whose calls carried an intent — usually a few minutes after they are recorded.
</span>
</div>
)
@@ -581,13 +103,12 @@ function EmptyState(): JSX.Element {
function ComputingSkeleton(): JSX.Element {
return (
<div className="flex flex-col gap-4">
- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
- <Skeleton className="h-24 w-full" />
- <Skeleton className="h-24 w-full" />
- <Skeleton className="h-24 w-full" />
+ <div className="grid grid-cols-2 lg:grid-cols-4 gap-2">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-24 w-full" />
+ ))}
</div>
<Skeleton className="h-96 w-full" />
- <Skeleton className="h-48 w-full" />
</div>
)
}
@@ -612,34 +133,39 @@ function ToolsViewEmptyState(): JSX.Element {
}
function ToolsView(): JSX.Element {
- const { hasToolPivot, selectedTool, clusters } = useValues(mcpClusteringLogic)
+ const { hasToolPivot } = useValues(mcpClusteringLogic)
if (!hasToolPivot) {
return <ToolsViewEmptyState />
}
+ return (
+ <ClusteringSplitPane
+ logicKey="mcp-clustering-tools"
+ // Wider than the intents list: the tool table carries seven columns. Still
+ // leaves the detail enough room for its own intents table.
+ defaultWidth={560}
+ list={<ToolsListPanel />}
+ detail={<ToolDetailPanel />}
+ />
+ )
+}
+function IntentsView(): JSX.Element {
return (
- <div className="flex flex-col gap-4">
- <div className="flex items-center justify-end">
- <ToolSearchInput />
- </div>
- <ToolPivotTable />
- {selectedTool ? (
- <ToolIntentDetail tool={selectedTool} clusters={clusters} />
- ) : (
- <div className="bg-surface-primary border rounded p-6 text-center text-muted text-sm">
- Click a tool row above to see the intents it serves and who it competes with.
- </div>
- )}
- <DiscoveryScatter />
- <ToolOverlapTable />
- </div>
+ <>
+ <ClusterScorecards />
+ <ClusteringSplitPane
+ logicKey="mcp-clustering-intents"
+ defaultWidth={360}
+ list={<ClusterListPanel />}
+ detail={<ClusterDetailPanel />}
+ />
+ </>
)
}
export function MCPAnalyticsClustering(): JSX.Element {
- const { snapshot, selectedCluster, hasSnapshot, isComputing, snapshotLoading, viewMode } =
- useValues(mcpClusteringLogic)
+ const { snapshot, hasSnapshot, isComputing, snapshotLoading, viewMode } = useValues(mcpClusteringLogic)
const { recompute } = useActions(mcpClusteringLogic)
if (snapshot.status === 'error') {
@@ -652,10 +178,6 @@ export function MCPAnalyticsClustering(): JSX.Element {
)
}
- if (!hasSnapshot && !isComputing && !snapshotLoading) {
- return <EmptyState />
- }
-
if (isComputing || (snapshotLoading && !hasSnapshot)) {
return (
<div className="flex flex-col gap-4" data-quill>
@@ -665,29 +187,15 @@ export function MCPAnalyticsClustering(): JSX.Element {
)
}
+ if (!hasSnapshot) {
+ return <EmptyState />
+ }
+
return (
<div className="flex flex-col gap-4" data-quill>
<StatusRow />
- <div className="flex items-center justify-between gap-2 flex-wrap">
- <ViewToggle />
- <ClusteringCoverageBanner />
- </div>
- {viewMode === 'tools' ? (
- <ToolsView />
- ) : (
- <>
- <Scorecards />
- <SortHeader />
- <Heatmap />
- {selectedCluster ? (
- <ClusterDetail cluster={selectedCluster} />
- ) : (
- <div className="bg-surface-primary border rounded p-6 text-center text-muted text-sm">
- Click a cluster row above to see its sample intents and tool breakdown.
- </div>
- )}
- </>
- )}
+ <ViewToggle />
+ {viewMode === 'tools' ? <ToolsView /> : <IntentsView />}
</div>
)
}
diff --git a/products/mcp_analytics/frontend/clustering/RoutingBar.stories.tsx b/products/mcp_analytics/frontend/clustering/RoutingBar.stories.tsx
new file mode 100644
index 000000000000..9bd0fd49c217
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/RoutingBar.stories.tsx
@@ -0,0 +1,106 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import type { MCPIntentClusterApi, MCPIntentClusterToolEntryApi } from '../generated/api.schemas'
+import { RoutingBar } from './RoutingBar'
+
+function tools(pairs: [string, number, number?][]): MCPIntentClusterToolEntryApi[] {
+ return pairs.map(([tool, pct, errorRatePct = 0]) => ({
+ tool,
+ count: pct,
+ pct,
+ errors: Math.round((pct * errorRatePct) / 100),
+ error_rate_pct: errorRatePct,
+ }))
+}
+
+function cluster(tool_distribution: MCPIntentClusterToolEntryApi[]): MCPIntentClusterApi {
+ return {
+ id: 1,
+ label: 'example intent group',
+ intent_count: 1,
+ session_count: 1,
+ call_count: 100,
+ error_count: 0,
+ error_rate_pct: 0,
+ routing_entropy: 0,
+ tool_distribution,
+ sample_intents: [],
+ journey: null,
+ switches: [],
+ self_retries: [],
+ }
+}
+
+const CASES: [string, MCPIntentClusterApi][] = [
+ // Single tool is the common case — most real intent groups call exactly one.
+ ['Single tool', cluster(tools([['execute-sql', 100]]))],
+ [
+ 'Concentrated',
+ cluster(
+ tools([
+ ['exec', 88],
+ ['skill-get', 12],
+ ])
+ ),
+ ],
+ [
+ 'Spread across many (remainder aggregated)',
+ cluster(
+ tools([
+ ['exec', 34],
+ ['execute-sql', 26],
+ ['read-data-schema', 22],
+ ['query-trends', 10],
+ ['insight-query', 8],
+ ])
+ ),
+ ],
+ // Error rates ride in the tooltip, not the fill — the row and detail table carry them.
+ [
+ 'With a failing tool',
+ cluster(
+ tools([
+ ['exec', 60],
+ ['cdp-functions-list', 40, 50],
+ ])
+ ),
+ ],
+ ['No tools recorded (renders nothing)', cluster([])],
+]
+
+const meta: Meta<typeof RoutingBar> = {
+ title: 'Products/MCP Analytics/RoutingBar',
+ component: RoutingBar,
+ parameters: {
+ layout: 'centered',
+ viewMode: 'story',
+ // Chromium-only keeps this consistent with the other MCP analytics stories and
+ // avoids cross-browser anti-aliasing noise on the thin coloured fill.
+ testOptions: { snapshotBrowsers: ['chromium'] },
+ },
+ // The app resolves this from the shared series palette; the story pins the same
+ // first-series colour so it renders what the list actually shows.
+ args: { color: 'var(--data-color-1)' },
+}
+export default meta
+
+type Story = StoryObj<typeof RoutingBar>
+
+/**
+ * Every routing shape in one fixed-width column. A single sized story rather than one per
+ * case: it documents the states together, and gives the snapshot runner one stable,
+ * non-empty target — a story that renders only `null` (the no-tools case) has no element
+ * to screenshot and times the runner out.
+ */
+export const AllVariants: Story = {
+ render: (args) => (
+ <div className="flex w-[360px] flex-col gap-3 p-2">
+ {CASES.map(([label, c]) => (
+ <div key={label} className="flex flex-col gap-1">
+ <span className="text-muted text-xs">{label}</span>
+ <RoutingBar {...args} cluster={c} />
+ </div>
+ ))}
+ </div>
+ ),
+}
diff --git a/products/mcp_analytics/frontend/clustering/RoutingBar.tsx b/products/mcp_analytics/frontend/clustering/RoutingBar.tsx
new file mode 100644
index 000000000000..ec495afe21a8
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/RoutingBar.tsx
@@ -0,0 +1,59 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import type { MCPIntentClusterApi } from '../generated/api.schemas'
+import { routingSegments } from './mcpClusteringLogic'
+
+// The top tool is solid and each subsequent one steps down, so the shape of a cluster's
+// routing is readable at a glance without a legend. The bar encodes the split only —
+// error rates are on the row and in the detail table.
+const SEGMENT_OPACITIES = [1, 0.6, 0.4]
+
+/**
+ * A cluster's tool routing as one dense stacked bar. Replaces the cluster × tool heatmap:
+ * it answers the same "does this goal go to one tool or many" question in a width that
+ * fits a list row beside a detail pane.
+ *
+ * Takes `color` rather than reading the chart theme itself: `useChartTheme` installs a
+ * MutationObserver per call, and this renders once per cluster in the list.
+ */
+export function RoutingBar({ cluster, color }: { cluster: MCPIntentClusterApi; color: string }): JSX.Element | null {
+ const segments = routingSegments(cluster)
+ if (segments.length === 0) {
+ return null
+ }
+
+ return (
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-0.5">
+ {segments.map((segment, i) => (
+ <span key={i}>
+ <span className="font-mono">
+ {segment.tool ?? `${segment.toolCount} more tool${segment.toolCount === 1 ? '' : 's'}`}
+ </span>{' '}
+ {segment.pct.toFixed(1)}%
+ {segment.errorRatePct > 0 ? (
+ <span className="text-danger"> · {segment.errorRatePct.toFixed(1)}% errors</span>
+ ) : null}
+ </span>
+ ))}
+ </div>
+ }
+ >
+ <div className="flex h-1.5 w-full gap-px overflow-hidden rounded-sm bg-surface-secondary">
+ {segments.map((segment, i) => (
+ <div
+ key={i}
+ // Width and colour are both data, so neither comes from a utility class.
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ width: `${segment.pct}%`,
+ backgroundColor: segment.tool === null ? 'var(--border-bold)' : color,
+ opacity: segment.tool === null ? 1 : (SEGMENT_OPACITIES[i] ?? 0.4),
+ }}
+ />
+ ))}
+ </div>
+ </Tooltip>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/ToolDetailPanel.tsx b/products/mcp_analytics/frontend/clustering/ToolDetailPanel.tsx
new file mode 100644
index 000000000000..0d7bb7b62dd8
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/ToolDetailPanel.tsx
@@ -0,0 +1,25 @@
+import { useValues } from 'kea'
+
+import { mcpClusteringLogic } from './mcpClusteringLogic'
+import { ToolIntentDetail } from './ToolIntentDetail'
+
+/** The selected tool's intents and competitors, pinned beside the tool list. */
+export function ToolDetailPanel(): JSX.Element {
+ const { selectedTool, clusters } = useValues(mcpClusteringLogic)
+
+ if (!selectedTool) {
+ return (
+ <div className="flex h-full items-center justify-center rounded border border-primary bg-surface-primary p-6 text-center text-sm text-muted">
+ Pick a tool to see the intents it serves and who it competes with.
+ </div>
+ )
+ }
+
+ return (
+ // Scrolls both ways: the intents table carries a competitor column that a narrow
+ // pane can't fit, and clipping it silently would hide the comparison it exists for.
+ <div className="h-full min-h-0 overflow-auto">
+ <ToolIntentDetail tool={selectedTool} clusters={clusters} />
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx b/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx
index 8b9ebf3887f0..bbb94142f70d 100644
--- a/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx
+++ b/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx
@@ -23,11 +23,15 @@ interface ToolSwitchRow extends MCPClusterSwitchApi {
clusterLabel: string
}
-/** Every error switch across the snapshot that involves the given tool, worst first. */
+/**
+ * Every error switch across the snapshot that involves the given tool, worst first.
+ * Clusters stored before switches were captured carry none: the schema marks the field
+ * required, the stored JSONB does not, so it has to be treated as absent.
+ */
function collectSwitches(tool: string, clusters: readonly MCPIntentClusterApi[]): ToolSwitchRow[] {
const rows: ToolSwitchRow[] = []
for (const cluster of clusters) {
- for (const sw of cluster.switches) {
+ for (const sw of cluster.switches ?? []) {
if (sw.from_tool === tool || sw.to_tool === tool) {
rows.push({ ...sw, clusterLabel: cluster.label })
}
diff --git a/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx b/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx
index cc7c3c068a5f..a811e5354bd2 100644
--- a/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx
+++ b/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx
@@ -93,7 +93,12 @@ export function ToolPivotTable(): JSX.Element {
<TableRow
key={tool.tool}
onClick={() => selectTool(tool.tool)}
- className={`cursor-pointer ${selectedToolName === tool.tool ? 'bg-accent/10' : ''}`}
+ data-state={selectedToolName === tool.tool ? 'selected' : undefined}
+ className={`cursor-pointer ${
+ selectedToolName === tool.tool
+ ? 'bg-accent-highlight-secondary'
+ : 'hover:bg-accent-highlight-secondary'
+ }`}
>
<TableCell expand>
<span className="font-mono">{tool.tool}</span>
diff --git a/products/mcp_analytics/frontend/clustering/ToolsListPanel.tsx b/products/mcp_analytics/frontend/clustering/ToolsListPanel.tsx
new file mode 100644
index 000000000000..a180c500b3ab
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/ToolsListPanel.tsx
@@ -0,0 +1,20 @@
+import { DiscoveryScatter } from './DiscoveryScatter'
+import { ToolOverlapTable } from './ToolOverlapTable'
+import { ToolPivotTable } from './ToolPivotTable'
+
+/**
+ * The whole-snapshot side of the tools view: every tool, then the two charts that only
+ * mean anything across all of them. Scrolls as one column beside the selected tool's
+ * detail, so the population and the pick stay on screen together.
+ */
+export function ToolsListPanel(): JSX.Element {
+ return (
+ // Scrolls both ways so the pane can be narrowed past the tool table's natural
+ // width instead of the table dictating how much room the detail gets.
+ <div className="flex h-full min-h-0 flex-col overflow-auto gap-4 pr-1">
+ <ToolPivotTable />
+ <DiscoveryScatter />
+ <ToolOverlapTable />
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts
index ce42ff4ce6c5..1513745bb4f6 100644
--- a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts
+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts
@@ -1,19 +1,24 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { urls } from '~/scenes/urls'
import { initKeaTests } from '~/test/init'
import { mcpAnalyticsIntentClustersRetrieve } from '../generated/api'
import type {
MCPIntentClusterApi,
MCPIntentClusterSnapshotApi,
+ MCPIntentClusterToolEntryApi,
MCPToolPivotApi,
MCPToolPivotClusterEntryApi,
} from '../generated/api.schemas'
import {
- MAX_HEATMAP_TOOL_COLUMNS,
- MAX_VISIBLE_CLUSTERS,
+ type ClusterFilter,
+ type RouteShape,
fitDomain,
mcpClusteringLogic,
+ routeShape,
+ routingSegments,
toolClusterRows,
weightedMeanFit,
} from './mcpClusteringLogic'
@@ -50,29 +55,70 @@ function cluster(id: number, overrides: Partial<MCPIntentClusterApi> = {}): MCPI
}
}
-// 5 more clusters than the visible cap, sorted-by-calls order = ascending id.
-const N_CLUSTERS = MAX_VISIBLE_CLUSTERS + 5
-const HIGH_ERROR_ID = N_CLUSTERS - 1
+/** Tool entries from `[tool, pct]` pairs; counts track pct so call-weighted maths stay checkable. */
+function dist(pairs: [string, number][], errorRatePct = 0): MCPIntentClusterToolEntryApi[] {
+ return pairs.map(([tool, pct]) => ({
+ tool,
+ count: pct,
+ pct,
+ errors: Math.round((pct * errorRatePct) / 100),
+ error_rate_pct: errorRatePct,
+ }))
+}
+
+// One cluster per route shape, so a scorecard count and its filter can be compared
+// against a set whose shapes are known by construction.
+const CONCENTRATED_ID = 1
+const SPREAD_ID = 3
+const MIXED_ID = 4
+const NO_TOOLS_ID = 5
+const FAILING_ID = 6
+
+const SHAPED_CLUSTERS: MCPIntentClusterApi[] = [
+ cluster(CONCENTRATED_ID, {
+ tool_distribution: dist([
+ ['a', 90],
+ ['b', 10],
+ ]),
+ }),
+ cluster(2, {
+ tool_distribution: dist([
+ ['a', 95],
+ ['c', 5],
+ ]),
+ }),
+ cluster(SPREAD_ID, {
+ tool_distribution: dist([
+ ['a', 40],
+ ['b', 35],
+ ['c', 25],
+ ]),
+ }),
+ cluster(MIXED_ID, {
+ tool_distribution: dist([
+ ['a', 60],
+ ['b', 40],
+ ]),
+ }),
+ cluster(NO_TOOLS_ID, { tool_distribution: [] }),
+ cluster(FAILING_ID, { tool_distribution: dist([['a', 100]], 30), error_count: 30, error_rate_pct: 30 }),
+]
const SNAPSHOT: MCPIntentClusterSnapshotApi = {
status: 'idle',
error_message: '',
last_computed_at: '2026-07-27T22:12:10Z',
last_computed_by_email: '[email protected]',
- clusters: Array.from({ length: N_CLUSTERS }, (_, i) =>
- // The last cluster has the fewest calls but the worst error rate, so it
- // only enters the visible set under the errors sort.
- cluster(i, i === HIGH_ERROR_ID ? { error_rate_pct: 50, error_count: 10 } : {})
- ),
- // The tool pivot has its own fixtures further down, so the cluster/heatmap
+ clusters: SHAPED_CLUSTERS,
+ // The tool pivot has its own fixtures further down, so the cluster
// selectors under test here see an empty one.
tools: [],
tool_overlaps: [],
computed_with: {
distance_threshold: 0.2,
embedding_model: 'test',
- n_intents: N_CLUSTERS,
- n_clusters: N_CLUSTERS,
+ n_intents: SHAPED_CLUSTERS.length,
+ n_clusters: SHAPED_CLUSTERS.length,
// Coverage metadata feeds ClusteringCoverageBanner, not these selectors.
corpus: null,
sampled_sessions: null,
@@ -106,37 +152,117 @@ describe('mcpClusteringLogic', () => {
logic.unmount()
})
- it('caps the visible clusters and expands them all on showAllClusters', () => {
- expect(logic.values.sortedClusters).toHaveLength(N_CLUSTERS)
- expect(logic.values.visibleClusters).toHaveLength(MAX_VISIBLE_CLUSTERS)
- expect(logic.values.hiddenClusterCount).toBe(N_CLUSTERS - MAX_VISIBLE_CLUSTERS)
+ // The scorecards are the entry point into the list: each one states a count and
+ // filters to that set. If the counter and the filter predicate drift apart, a card
+ // reading "1 spread route" filters to a different number of rows.
+ it.each([
+ ['concentrated' as ClusterFilter, 'concentrated' as RouteShape],
+ ['spread' as ClusterFilter, 'spread' as RouteShape],
+ ['mixed' as ClusterFilter, 'mixed' as RouteShape],
+ ])('the %s scorecard count is exactly what its filter shows', (filter, shape) => {
+ const counted = logic.values.routeShapeCounts[shape]
+
+ logic.actions.setClusterFilter(filter)
+
+ expect(logic.values.filteredClusters).toHaveLength(counted)
+ expect(logic.values.filteredClusters.every((c) => routeShape(c) === shape)).toBe(true)
+ })
+
+ it('the failing scorecard count is exactly what its filter shows', () => {
+ const counted = logic.values.routeShapeCounts.failing
+
+ logic.actions.setClusterFilter('failing')
+
+ expect(counted).toBe(1)
+ expect(logic.values.filteredClusters.map((c) => c.id)).toEqual([FAILING_ID])
+ })
+
+ // The counts also have to track the tool search, or a card reports a snapshot-wide
+ // number while its filter — which applies the search too — returns fewer rows.
+ it.each([
+ ['concentrated' as ClusterFilter, 'concentrated' as RouteShape],
+ ['spread' as ClusterFilter, 'spread' as RouteShape],
+ ['mixed' as ClusterFilter, 'mixed' as RouteShape],
+ ])('the %s scorecard count tracks the tool search its filter also applies', (filter, shape) => {
+ logic.actions.setToolSearch('b')
+
+ // Only clusters 1, 3 and 4 carry a `b` tool, so the searched set holds one of each shape.
+ expect(logic.values.routeShapeCounts.total).toBe(3)
+
+ const counted = logic.values.routeShapeCounts[shape]
+ logic.actions.setClusterFilter(filter)
+
+ expect(logic.values.filteredClusters).toHaveLength(counted)
+ expect(logic.values.filteredClusters.every((c) => routeShape(c) === shape)).toBe(true)
+ })
+
+ // Filtering used to leave the detail pane showing a cluster that is no longer in the
+ // list, so the pane contradicted the selection it was supposed to reflect.
+ it('moves the selection into the filtered set when the filter excludes it', () => {
+ logic.actions.selectCluster(CONCENTRATED_ID)
+
+ logic.actions.setClusterFilter('spread')
+
+ expect(logic.values.selectedClusterId).toBe(SPREAD_ID)
+ expect(logic.values.filteredClusters.map((c) => c.id)).toContain(logic.values.selectedClusterId)
+ })
+
+ it('keeps the selection when the filter still contains it', () => {
+ logic.actions.selectCluster(SPREAD_ID)
- logic.actions.showAllClusters()
+ logic.actions.setClusterFilter('spread')
- expect(logic.values.visibleClusters).toHaveLength(N_CLUSTERS)
- expect(logic.values.hiddenClusterCount).toBe(0)
+ expect(logic.values.selectedClusterId).toBe(SPREAD_ID)
})
- it('slices the visible set after sorting, so re-sorting surfaces clusters outside the call-count top', () => {
- // Lowest call count, so it's hidden under the default calls sort…
- expect(logic.values.visibleClusters.some((c) => c.id === HIGH_ERROR_ID)).toBe(false)
+ // Without the url round-trip, sharing a link to a cluster silently lands the
+ // recipient on whichever cluster happens to have the most calls.
+ it('round-trips the selected cluster through the url', async () => {
+ logic.actions.selectCluster(MIXED_ID)
+ // kea-router coerces numeric search params on read, so compare the value not the type.
+ expect(Number(router.values.searchParams.cluster)).toBe(MIXED_ID)
+
+ logic.unmount()
+ router.actions.push(urls.mcpAnalyticsIntentClustering(), { cluster: String(SPREAD_ID) })
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.selectedClusterId).toBe(SPREAD_ID)
+ })
- logic.actions.setSortKey('errors')
+ // A shared link opened after a recompute (or a hand-edited param) names a cluster the
+ // snapshot no longer carries. Without reconciliation the fallback stays suppressed and
+ // the detail pane lands empty; it should reselect the highest-traffic cluster instead.
+ it('falls back to the top cluster when the url names one the snapshot lacks', async () => {
+ logic.unmount()
+ router.actions.push(urls.mcpAnalyticsIntentClustering(), { cluster: '999' })
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
- // …but worst error rate, so it leads once sorted by errors.
- expect(logic.values.visibleClusters[0].id).toBe(HIGH_ERROR_ID)
- expect(logic.values.visibleClusters).toHaveLength(MAX_VISIBLE_CLUSTERS)
+ const top = [...SHAPED_CLUSTERS].sort((a, b) => b.call_count - a.call_count)[0]
+ expect(logic.values.selectedClusterId).toBe(top.id)
+ expect(logic.values.selectedCluster).not.toBeNull()
})
- it('caps heatmap tool columns by call volume and reports the full tool count', () => {
- expect(logic.values.toolColumns).toHaveLength(MAX_HEATMAP_TOOL_COLUMNS)
- // Highest-volume tool leads; the 1-call long-tail tools are what get cut.
- expect(logic.values.toolColumns[0]).toBe('tool-0')
- expect(logic.values.totalToolCount).toBe(N_CLUSTERS * 2)
+ // Polling and recompute swap the whole snapshot, and the backend reassigns cluster ids
+ // per run, so a valid selection can vanish. The pane must not keep pointing at a gone id.
+ it('reselects a top cluster when a reloaded snapshot drops the selected id', async () => {
+ logic.actions.selectCluster(FAILING_ID)
+ expect(logic.values.selectedClusterId).toBe(FAILING_ID)
+
+ const survivors = SHAPED_CLUSTERS.filter((c) => c.id !== FAILING_ID)
+ mockRetrieve.mockResolvedValue({ ...SNAPSHOT, clusters: survivors })
+ logic.actions.loadSnapshot()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(survivors.map((c) => c.id)).toContain(logic.values.selectedClusterId)
+ expect(logic.values.selectedCluster).not.toBeNull()
})
it('reports the true cluster count from computed_with when the snapshot is truncated', async () => {
- expect(logic.values.totalClusterCount).toBe(N_CLUSTERS)
+ expect(logic.values.totalClusterCount).toBe(SHAPED_CLUSTERS.length)
// The backend stores only the top clusters; n_clusters keeps the run's full count.
// Status row, scorecards, and the dashboard KPI must report that, not clusters.length.
@@ -180,6 +306,80 @@ function pivot(clusters: MCPToolPivotClusterEntryApi[]): MCPToolPivotApi {
}
describe('mcpClusteringLogic helpers', () => {
+ // A cluster with no tool distribution used to fall through to a `?? 100` default and
+ // be counted as the best-routed shape there is, inflating the headline number.
+ it.each([
+ [
+ 'one tool takes at least 80%',
+ dist([
+ ['a', 90],
+ ['b', 10],
+ ]),
+ 'concentrated',
+ ],
+ ['a single tool takes everything', dist([['a', 100]]), 'concentrated'],
+ [
+ 'no tool reaches half across several',
+ dist([
+ ['a', 40],
+ ['b', 35],
+ ['c', 25],
+ ]),
+ 'spread',
+ ],
+ [
+ 'the top tool sits between the bands',
+ dist([
+ ['a', 60],
+ ['b', 40],
+ ]),
+ 'mixed',
+ ],
+ ['there is no distribution at all', [], 'mixed'],
+ ])('routeShape is %s -> %s', (_name, tool_distribution, expected) => {
+ expect(routeShape(cluster(1, { tool_distribution }))).toBe(expected)
+ })
+
+ // The list row draws one bar per segment. A remainder emitted for a cluster that has
+ // nothing left over draws a phantom segment, and 65% of real clusters call one tool.
+ it.each([
+ ['a single tool', dist([['a', 100]]), [{ tool: 'a', pct: 100, toolCount: 1 }]],
+ [
+ 'exactly the segment cap',
+ dist([
+ ['a', 50],
+ ['b', 30],
+ ['c', 20],
+ ]),
+ [
+ { tool: 'a', pct: 50, toolCount: 1 },
+ { tool: 'b', pct: 30, toolCount: 1 },
+ { tool: 'c', pct: 20, toolCount: 1 },
+ ],
+ ],
+ [
+ 'more tools than the cap, remainder aggregated',
+ dist([
+ ['a', 40],
+ ['b', 30],
+ ['c', 20],
+ ['d', 6],
+ ['e', 4],
+ ]),
+ [
+ { tool: 'a', pct: 40, toolCount: 1 },
+ { tool: 'b', pct: 30, toolCount: 1 },
+ { tool: 'c', pct: 20, toolCount: 1 },
+ { tool: null, pct: 10, toolCount: 2 },
+ ],
+ ],
+ ['no tools', [], []],
+ ])('routingSegments over %s', (_name, tool_distribution, expected) => {
+ const segments = routingSegments(cluster(1, { tool_distribution }), 3)
+
+ expect(segments.map(({ tool, pct, toolCount }) => ({ tool, pct, toolCount }))).toEqual(expected)
+ })
+
// The scatter plots one fit value per tool; if the weighting silently broke,
// a tool's dominant intent would no longer dominate its plotted position.
it('weightedMeanFit weights each cluster fit by its call volume', () => {
diff --git a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
index bf9f09b16a1d..b2ad09f6b8c3 100644
--- a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
@@ -1,10 +1,13 @@
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from '~/scenes/urls'
+
import { mcpAnalyticsIntentClustersRecompute, mcpAnalyticsIntentClustersRetrieve } from '../generated/api'
import type {
MCPIntentClusterApi,
@@ -27,12 +30,8 @@ const EMPTY_SNAPSHOT: MCPIntentClusterSnapshotApi = {
const POLL_INTERVAL_MS = 3000
-// The heatmap renders clusters × tools cells in one synchronous pass — a large
-// snapshot (hundreds of clusters, ~200 distinct tools) produces tens of
-// thousands of DOM nodes and freezes the tab on mount. Cap the initial render;
-// "Show all" opts into the rest.
-export const MAX_VISIBLE_CLUSTERS = 30
-export const MAX_HEATMAP_TOOL_COLUMNS = 40
+/** Segments drawn on a cluster row's routing bar before the rest is aggregated. */
+export const ROUTING_BAR_SEGMENTS = 3
// The generated client types the retrieve endpoint as returning an array, but the view actually
// returns a single object. drf-spectacular assumes ViewSet `list` actions return arrays. Normalize.
@@ -52,6 +51,79 @@ export type ClusterSortKey = 'calls' | 'errors' | 'entropy' | 'concentration'
export type ToolSortKey = 'calls' | 'contested' | 'discovery'
export type ClusteringViewMode = 'intents' | 'tools'
+/** How spread out a cluster's calls are across the tools that served it. */
+export type RouteShape = 'concentrated' | 'mixed' | 'spread'
+
+export type ClusterFilter = 'all' | RouteShape | 'failing'
+
+/** Cluster counts per route shape, plus the count of clusters that lost calls to errors. */
+export interface RouteShapeCounts {
+ concentrated: number
+ mixed: number
+ spread: number
+ failing: number
+ total: number
+}
+
+/**
+ * The single definition of a cluster's route shape. Both the scorecard counts and
+ * the filter each card applies read it, so a card cannot state one number and
+ * filter to a different set.
+ */
+export function routeShape(cluster: MCPIntentClusterApi): RouteShape {
+ // A cluster with no distribution has no shape to report; calling it
+ // concentrated would count "we know nothing" as the healthiest bucket.
+ if (cluster.tool_distribution.length === 0) {
+ return 'mixed'
+ }
+ const top = cluster.tool_distribution[0].pct
+ if (top >= 80) {
+ return 'concentrated'
+ }
+ if (cluster.tool_distribution.length >= 2 && top < 50) {
+ return 'spread'
+ }
+ return 'mixed'
+}
+
+export interface RoutingSegment {
+ /** null on the aggregated remainder, which stands for `toolCount` tools. */
+ tool: string | null
+ pct: number
+ errorRatePct: number
+ toolCount: number
+}
+
+/**
+ * A cluster's tool distribution reduced to a few drawable segments, with
+ * everything past the cap folded into one remainder. Replaces the cluster × tool
+ * heatmap: the same routing read, at a width that fits beside a detail pane.
+ */
+export function routingSegments(cluster: MCPIntentClusterApi, maxSegments = ROUTING_BAR_SEGMENTS): RoutingSegment[] {
+ const ordered = [...cluster.tool_distribution].sort((a, b) => b.count - a.count)
+ const head = ordered.slice(0, maxSegments).map((entry) => ({
+ tool: entry.tool,
+ pct: entry.pct,
+ errorRatePct: entry.error_rate_pct,
+ toolCount: 1,
+ }))
+ const rest = ordered.slice(maxSegments)
+ if (rest.length === 0) {
+ return head
+ }
+ const calls = rest.reduce((sum, entry) => sum + entry.count, 0)
+ const errors = rest.reduce((sum, entry) => sum + entry.errors, 0)
+ return [
+ ...head,
+ {
+ tool: null,
+ pct: rest.reduce((sum, entry) => sum + entry.pct, 0),
+ errorRatePct: calls > 0 ? (100 * errors) / calls : 0,
+ toolCount: rest.length,
+ },
+ ]
+}
+
export interface ScatterPoint {
tool: string
fit: number
@@ -120,20 +192,17 @@ function median(values: number[]): number | null {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpClusteringLogicValues {
currentProjectId: number | string // teamLogic
- allClustersShown: boolean
+ clusterFilter: ClusterFilter
clusters: readonly MCPIntentClusterApi[]
- concentratedRoutes: {
- focused: number
- total: number
- }
discoveryMedian: number | null
filteredClusters: MCPIntentClusterApi[]
fitMedian: number | null
hasSnapshot: boolean
hasToolPivot: boolean
- hiddenClusterCount: number
isComputing: boolean
+ routeShapeCounts: RouteShapeCounts
scatterPoints: ScatterPoint[]
+ searchedClusters: MCPIntentClusterApi[]
selectedCluster: MCPIntentClusterApi | null
selectedClusterId: number | null
selectedTool: MCPToolPivotApi | null
@@ -143,21 +212,19 @@ export interface mcpClusteringLogicValues {
sortKey: ClusterSortKey
sortedClusters: MCPIntentClusterApi[]
sortedTools: MCPToolPivotApi[]
- spreadRoutes: number
- toolColumns: string[]
toolOverlaps: readonly MCPToolOverlapApi[]
toolSearch: string
toolSortKey: ToolSortKey
tools: readonly MCPToolPivotApi[]
- topErrorRoute: MCPIntentClusterApi | null
totalClusterCount: number
- totalToolCount: number
viewMode: ClusteringViewMode
- visibleClusters: MCPIntentClusterApi[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpClusteringLogicActions {
+ keepSelectionVisible: () => {
+ value: true
+ }
loadSnapshot: () => any
loadSnapshotFailure: (
error: string,
@@ -185,6 +252,9 @@ export interface mcpClusteringLogicActions {
selectTool: (toolName: string | null) => {
toolName: string | null
}
+ setClusterFilter: (clusterFilter: ClusterFilter) => {
+ clusterFilter: ClusterFilter
+ }
setSortKey: (sortKey: ClusterSortKey) => {
sortKey: ClusterSortKey
}
@@ -197,9 +267,6 @@ export interface mcpClusteringLogicActions {
setViewMode: (viewMode: ClusteringViewMode) => {
viewMode: ClusteringViewMode
}
- showAllClusters: () => {
- value: true
- }
startPolling: () => {
value: true
}
@@ -231,7 +298,11 @@ export interface mcpClusteringLogicMeta {
toolOverlaps: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPToolOverlapApi[]
hasToolPivot: (tools: readonly MCPToolPivotApi[]) => boolean
sortedClusters: (clusters: readonly MCPIntentClusterApi[], sortKey: ClusterSortKey) => MCPIntentClusterApi[]
- filteredClusters: (sortedClusters: MCPIntentClusterApi[], toolSearch: string) => MCPIntentClusterApi[]
+ searchedClusters: (sortedClusters: MCPIntentClusterApi[], toolSearch: string) => MCPIntentClusterApi[]
+ filteredClusters: (
+ searchedClusters: MCPIntentClusterApi[],
+ clusterFilter: ClusterFilter
+ ) => MCPIntentClusterApi[]
sortedTools: (
tools: readonly MCPToolPivotApi[],
toolSortKey: ToolSortKey,
@@ -241,21 +312,12 @@ export interface mcpClusteringLogicMeta {
scatterPoints: (tools: readonly MCPToolPivotApi[]) => ScatterPoint[]
fitMedian: (scatterPoints: ScatterPoint[]) => number | null
discoveryMedian: (scatterPoints: ScatterPoint[]) => number | null
- visibleClusters: (filteredClusters: MCPIntentClusterApi[], allClustersShown: boolean) => MCPIntentClusterApi[]
- hiddenClusterCount: (filteredClusters: MCPIntentClusterApi[], visibleClusters: MCPIntentClusterApi[]) => number
- toolColumns: (filteredClusters: MCPIntentClusterApi[]) => string[]
- totalToolCount: (filteredClusters: MCPIntentClusterApi[]) => number
totalClusterCount: (snapshot: MCPIntentClusterSnapshotApi) => number
selectedCluster: (
clusters: readonly MCPIntentClusterApi[],
selectedClusterId: number | null
) => MCPIntentClusterApi | null
- concentratedRoutes: (clusters: readonly MCPIntentClusterApi[]) => {
- focused: number
- total: number
- }
- spreadRoutes: (clusters: readonly MCPIntentClusterApi[]) => number
- topErrorRoute: (clusters: readonly MCPIntentClusterApi[]) => MCPIntentClusterApi | null
+ routeShapeCounts: (searchedClusters: MCPIntentClusterApi[]) => RouteShapeCounts
isComputing: (snapshot: MCPIntentClusterSnapshotApi) => boolean
hasSnapshot: (snapshot: MCPIntentClusterSnapshotApi) => boolean
}
@@ -280,7 +342,8 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
setToolSortKey: (toolSortKey: ToolSortKey) => ({ toolSortKey }),
setViewMode: (viewMode: ClusteringViewMode) => ({ viewMode }),
setToolSearch: (toolSearch: string) => ({ toolSearch }),
- showAllClusters: true,
+ setClusterFilter: (clusterFilter: ClusterFilter) => ({ clusterFilter }),
+ keepSelectionVisible: true,
recompute: true,
startPolling: true,
stopPolling: true,
@@ -344,10 +407,10 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
setToolSearch: (_, { toolSearch }) => toolSearch,
},
],
- allClustersShown: [
- false,
+ clusterFilter: [
+ 'all' as ClusterFilter,
{
- showAllClusters: () => true,
+ setClusterFilter: (_, { clusterFilter }) => clusterFilter,
},
],
}),
@@ -386,7 +449,10 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
}
},
],
- filteredClusters: [
+ // The tool search narrows the population both the scorecards count and the
+ // list filter read. Splitting it out keeps the two in lockstep: the scorecards
+ // count shapes within the searched set, and each card's filter draws from it.
+ searchedClusters: [
(s) => [s.sortedClusters, s.toolSearch],
(sortedClusters: MCPIntentClusterApi[], toolSearch: string): MCPIntentClusterApi[] => {
const query = toolSearch.trim().toLowerCase()
@@ -394,10 +460,21 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
return sortedClusters
}
return sortedClusters.filter((cluster) =>
- cluster.tool_distribution.some((entry) => entry.tool.toLowerCase().includes(query))
+ cluster.tool_distribution.some((e) => e.tool.toLowerCase().includes(query))
)
},
],
+ filteredClusters: [
+ (s) => [s.searchedClusters, s.clusterFilter],
+ (searchedClusters: MCPIntentClusterApi[], clusterFilter: ClusterFilter): MCPIntentClusterApi[] => {
+ return searchedClusters.filter((cluster) => {
+ if (clusterFilter === 'failing') {
+ return cluster.error_count > 0
+ }
+ return clusterFilter === 'all' || routeShape(cluster) === clusterFilter
+ })
+ },
+ ],
sortedTools: [
(s) => [s.tools, s.toolSortKey, s.toolSearch],
(tools: readonly MCPToolPivotApi[], toolSortKey: ToolSortKey, toolSearch: string): MCPToolPivotApi[] => {
@@ -452,47 +529,6 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
(s) => [s.scatterPoints],
(scatterPoints: ScatterPoint[]): number | null => median(scatterPoints.map((p) => p.discoveryRatePct)),
],
- // Tools across the visible clusters, ordered by total calls desc — these are the heatmap columns.
- // The heatmap rows: filtered and sliced after sorting so re-sorting or
- // narrowing the tool search can surface any cluster into the visible set.
- visibleClusters: [
- (s) => [s.filteredClusters, s.allClustersShown],
- (filteredClusters: MCPIntentClusterApi[], allClustersShown: boolean): MCPIntentClusterApi[] =>
- allClustersShown ? filteredClusters : filteredClusters.slice(0, MAX_VISIBLE_CLUSTERS),
- ],
- hiddenClusterCount: [
- (s) => [s.filteredClusters, s.visibleClusters],
- (filteredClusters: MCPIntentClusterApi[], visibleClusters: MCPIntentClusterApi[]): number =>
- filteredClusters.length - visibleClusters.length,
- ],
-
- toolColumns: [
- (s) => [s.filteredClusters],
- (filteredClusters: MCPIntentClusterApi[]): string[] => {
- const totals = new Map<string, number>()
- for (const cluster of filteredClusters) {
- for (const entry of cluster.tool_distribution) {
- totals.set(entry.tool, (totals.get(entry.tool) ?? 0) + entry.count)
- }
- }
- return [...totals.entries()]
- .sort((a, b) => b[1] - a[1])
- .slice(0, MAX_HEATMAP_TOOL_COLUMNS)
- .map(([tool]) => tool)
- },
- ],
- totalToolCount: [
- (s) => [s.filteredClusters],
- (filteredClusters: MCPIntentClusterApi[]): number => {
- const tools = new Set<string>()
- for (const cluster of filteredClusters) {
- for (const entry of cluster.tool_distribution) {
- tools.add(entry.tool)
- }
- }
- return tools.size
- },
- ],
// The true number of clusters the run found — the snapshot itself only
// carries the top MAX_SNAPSHOT_CLUSTERS by call volume, so anything
// reporting "how many clusters exist" must read this, not clusters.length.
@@ -513,32 +549,26 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
return clusters.find((c) => c.id === selectedClusterId) ?? null
},
],
- // Scorecard derivations — all from existing aggregate fields.
- concentratedRoutes: [
- (s) => [s.clusters],
- (clusters: readonly MCPIntentClusterApi[]): { focused: number; total: number } => ({
- focused: clusters.filter((c) => (c.tool_distribution[0]?.pct ?? 0) >= 80).length,
- total: clusters.length,
- }),
- ],
- spreadRoutes: [
- (s) => [s.clusters],
- (clusters: readonly MCPIntentClusterApi[]): number =>
- clusters.filter((c) => {
- const top = c.tool_distribution[0]?.pct ?? 100
- return c.tool_distribution.length >= 2 && top < 50
- }).length,
- ],
- topErrorRoute: [
- (s) => [s.clusters],
- (clusters: readonly MCPIntentClusterApi[]): MCPIntentClusterApi | null => {
- if (clusters.length === 0) {
- return null
+ // Backs the scorecards. Each count comes from the same `routeShape` the
+ // matching filter uses, over the same searched set the list draws from, so
+ // clicking a card yields exactly the number it shows — tool search active or not.
+ routeShapeCounts: [
+ (s) => [s.searchedClusters],
+ (searchedClusters: MCPIntentClusterApi[]): RouteShapeCounts => {
+ const counts: RouteShapeCounts = {
+ concentrated: 0,
+ mixed: 0,
+ spread: 0,
+ failing: 0,
+ total: searchedClusters.length,
+ }
+ for (const cluster of searchedClusters) {
+ counts[routeShape(cluster)] += 1
+ if (cluster.error_count > 0) {
+ counts.failing += 1
+ }
}
- // Highest traffic-weighted error count — the cluster that loses the most calls to errors.
- return [...clusters].sort(
- (a, b) => b.call_count * b.error_rate_pct - a.call_count * a.error_rate_pct
- )[0]
+ return counts
},
],
isComputing: [
@@ -558,13 +588,19 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
} else {
actions.stopPolling()
}
- if (values.selectedClusterId === null && snapshot.clusters.length > 0) {
- // Auto-select the highest-traffic cluster so the detail pane fills in.
+ // Fill or reconcile the selection: fall back to the highest-traffic cluster
+ // when nothing is selected, and also when the current selection is absent from
+ // this snapshot. A `?cluster=` link or a recompute that reassigned ids would
+ // otherwise leave the detail pane empty with the fallback suppressed.
+ const clusterPresent = snapshot.clusters.some((c) => c.id === values.selectedClusterId)
+ if (!clusterPresent && snapshot.clusters.length > 0) {
const top = [...snapshot.clusters].sort((a, b) => b.call_count - a.call_count)[0]
actions.selectCluster(top.id)
}
- if (values.selectedToolName === null && (snapshot.tools ?? []).length > 0) {
- const topTool = [...snapshot.tools].sort((a, b) => b.call_count - a.call_count)[0]
+ const tools = snapshot.tools ?? []
+ const toolPresent = tools.some((t) => t.tool === values.selectedToolName)
+ if (!toolPresent && tools.length > 0) {
+ const topTool = [...tools].sort((a, b) => b.call_count - a.call_count)[0]
actions.selectTool(topTool.tool)
}
},
@@ -597,6 +633,68 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
pollSnapshot: () => {
actions.loadSnapshot()
},
+ // Narrowing the list can strand the selection outside it, leaving the detail
+ // pane describing a cluster the list no longer offers. Follow the list instead.
+ setClusterFilter: () => {
+ actions.keepSelectionVisible()
+ },
+ setToolSearch: () => {
+ actions.keepSelectionVisible()
+ },
+ keepSelectionVisible: () => {
+ const { filteredClusters, selectedClusterId, sortedTools, selectedToolName } = values
+ if (filteredClusters.length > 0 && !filteredClusters.some((c) => c.id === selectedClusterId)) {
+ actions.selectCluster(filteredClusters[0].id)
+ }
+ if (sortedTools.length > 0 && !sortedTools.some((t) => t.tool === selectedToolName)) {
+ actions.selectTool(sortedTools[0].tool)
+ }
+ },
+ })),
+ // Mirror the selection and view to the url so a cluster or tool can be linked to
+ // directly, rather than the recipient landing on whichever has the most calls.
+ actionToUrl(({ values }) => {
+ const syncUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {
+ const { currentLocation } = router.values
+ const searchParams = { ...currentLocation.searchParams }
+ const params: Record<string, string | null> = {
+ view: values.viewMode === 'tools' ? 'tools' : null,
+ cluster: values.selectedClusterId === null ? null : String(values.selectedClusterId),
+ tool: values.selectedToolName,
+ }
+ for (const [key, value] of Object.entries(params)) {
+ if (value) {
+ searchParams[key] = value
+ } else {
+ delete searchParams[key]
+ }
+ }
+ return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]
+ }
+ return {
+ selectCluster: syncUrl,
+ selectTool: syncUrl,
+ setViewMode: syncUrl,
+ }
+ }),
+ urlToAction(({ actions, values }) => ({
+ [urls.mcpAnalyticsIntentClustering()]: (_, searchParams) => {
+ const viewMode: ClusteringViewMode = searchParams.view === 'tools' ? 'tools' : 'intents'
+ if (viewMode !== values.viewMode) {
+ actions.setViewMode(viewMode)
+ }
+ // Guard the empty param explicitly: Number('') is 0, which would select a real id.
+ const rawCluster = searchParams.cluster
+ const clusterId = Number(rawCluster)
+ if (rawCluster !== undefined && rawCluster !== '' && Number.isInteger(clusterId)) {
+ if (clusterId !== values.selectedClusterId) {
+ actions.selectCluster(clusterId)
+ }
+ }
+ if (typeof searchParams.tool === 'string' && searchParams.tool !== values.selectedToolName) {
+ actions.selectTool(searchParams.tool)
+ }
+ },
})),
afterMount(({ actions }) => {
actions.loadSnapshot()
diff --git a/products/mcp_analytics/frontend/clustering/seriesColors.ts b/products/mcp_analytics/frontend/clustering/seriesColors.ts
new file mode 100644
index 000000000000..4cf890730d4c
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/seriesColors.ts
@@ -0,0 +1,15 @@
+import type { ChartTheme } from '@posthog/quill-charts'
+
+/**
+ * Indices into the shared series palette, so the clustering tab draws data in the same
+ * colours as the dashboard and tool quality charts. Those tabs index the theme directly;
+ * naming the two the clustering views need keeps the choice in one place.
+ */
+export const PRIMARY_SERIES = 0
+export const ERROR_SERIES = 4
+
+export function seriesColor(theme: ChartTheme, index: number): string {
+ // The palette is short and wraps in the chart helpers; mirror that rather than
+ // returning undefined and letting a fill fall back to black.
+ return theme.colors[index % theme.colors.length]
+}