Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mcp-analytics): cap intent cluster snapshot and heatmap render (#75075)

Daniel Visca2e3d8b8651ab
diff --git a/products/mcp_analytics/backend/constants.py b/products/mcp_analytics/backend/constants.py
index 99fe926a5e37..b13b07bf3cbe 100644
--- a/products/mcp_analytics/backend/constants.py
+++ b/products/mcp_analytics/backend/constants.py
@@ -2,3 +2,11 @@
# (frozen, pre-2026-06-16 history) would double-count every call.
MCP_TOOL_CALL_EVENT = "$mcp_tool_call"
MCP_MISSING_CAPABILITY_EVENT = "$mcp_missing_capability"
+
+# Intent cluster snapshots are stored as one JSON blob and served unpaginated,
+# so cap how many clusters (ranked by call volume) a snapshot carries. A
+# degenerate clustering run can label nearly every intent as its own cluster —
+# hundreds of near-singleton clusters make a multi-MB payload the UI then has
+# to render in one go. Lives here (not intent_clustering.py) so the API read
+# path can import it without pulling sklearn/numpy into the request path.
+MAX_SNAPSHOT_CLUSTERS = 100
diff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.py
index 35a35eee4b74..43482d7083f7 100644
--- a/products/mcp_analytics/backend/intent_clustering.py
+++ b/products/mcp_analytics/backend/intent_clustering.py
@@ -40,7 +40,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models.team.team import Team
from posthog.sync import database_sync_to_async
-from products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENT
+from products.mcp_analytics.backend.constants import MAX_SNAPSHOT_CLUSTERS, MCP_TOOL_CALL_EVENT
from products.mcp_analytics.backend.models import MCPIntentEmbeddingCache, MCPSession
logger = structlog.get_logger(__name__)
@@ -636,13 +636,18 @@ def build_snapshot(
# Sort clusters by call volume desc so the UI shows the most impactful first.
clusters.sort(key=lambda c: c["call_count"], reverse=True)
+ # Persist only the highest-volume clusters; ``n_clusters`` keeps the full
+ # count so the UI can say how many the run actually found.
+ n_clusters_total = len(clusters)
+ del clusters[MAX_SNAPSHOT_CLUSTERS:]
+
return {
"clusters": clusters,
"computed_with": {
"distance_threshold": distance_threshold,
"embedding_model": EMBEDDING_MODEL,
"n_intents": len(records),
- "n_clusters": len(clusters),
+ "n_clusters": n_clusters_total,
},
}
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index 1f4c66758ff3..40ac3886fce9 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -23,7 +23,11 @@ from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.utils import generate_cache_key
from products.mcp_analytics.backend import intent_generation
-from products.mcp_analytics.backend.constants import MCP_MISSING_CAPABILITY_EVENT, MCP_TOOL_CALL_EVENT
+from products.mcp_analytics.backend.constants import (
+ MAX_SNAPSHOT_CLUSTERS,
+ MCP_MISSING_CAPABILITY_EVENT,
+ MCP_TOOL_CALL_EVENT,
+)
from products.mcp_analytics.backend.facade import contracts, enums
from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession
@@ -678,6 +682,16 @@ def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:
clusters_raw = blob.get("clusters", []) if isinstance(blob, dict) else []
meta_raw = blob.get("computed_with") if isinstance(blob, dict) else None
+ # Snapshots persisted before build_snapshot capped its output can hold
+ # hundreds of clusters — cap at read time too, keeping the highest-volume
+ # ones (the same ranking build_snapshot persists).
+ if len(clusters_raw) > MAX_SNAPSHOT_CLUSTERS:
+ clusters_raw = sorted(
+ (item for item in clusters_raw if isinstance(item, dict)),
+ key=lambda item: int(item.get("call_count", 0) or 0),
+ reverse=True,
+ )[:MAX_SNAPSHOT_CLUSTERS]
+
return contracts.IntentClusterSnapshot(
status=snapshot.status,
error_message=snapshot.error_message,
diff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.py
index 7a2815c59093..096996085d2d 100644
--- a/products/mcp_analytics/backend/tests/test_intent_clustering.py
+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py
@@ -24,6 +24,7 @@ from posthog.hogql.constants import DEFAULT_RETURNED_ROWS
from posthog.api.embedding_worker import EmbeddingResponse
from products.mcp_analytics.backend import intent_clustering
+from products.mcp_analytics.backend.constants import MAX_SNAPSHOT_CLUSTERS
from products.mcp_analytics.backend.intent_clustering import (
DEFAULT_DISTANCE_THRESHOLD,
EMBEDDING_MODEL,
@@ -240,6 +241,25 @@ class TestBuildSnapshot:
with pytest.raises(AssertionError):
build_snapshot(records, np.array([0, 0], dtype=np.int64), np.array([_unit([1.0, 0.0])]))
+ def test_caps_stored_clusters_and_keeps_the_full_count_in_meta(self) -> None:
+ # A degenerate run (tight threshold, diverse corpus) can label almost every
+ # intent as its own cluster; without the cap the persisted blob and the
+ # unpaginated API response grow unbounded.
+ n_total = MAX_SNAPSHOT_CLUSTERS + 5
+ records = [
+ IntentRecord(intent_text=f"intent_{i}", frequency=i + 1, tool_counts={"tool_a": i + 1})
+ for i in range(n_total)
+ ]
+ labels = np.arange(n_total, dtype=np.int64)
+ embeddings = np.array([_unit([1.0, float(i + 1)]) for i in range(n_total)], dtype=np.float32)
+
+ snapshot = build_snapshot(records, labels, embeddings)
+
+ assert len(snapshot["clusters"]) == MAX_SNAPSHOT_CLUSTERS
+ assert snapshot["computed_with"]["n_clusters"] == n_total
+ # The highest-volume clusters are the ones kept (call counts 1..n_total; the 5 smallest drop).
+ assert min(cluster["call_count"] for cluster in snapshot["clusters"]) == 6
+
# fetch_intent_corpus -----------------------------------------------------
diff --git a/products/mcp_analytics/backend/tests/test_logic.py b/products/mcp_analytics/backend/tests/test_logic.py
index 7e2b06559490..c169886ecca8 100644
--- a/products/mcp_analytics/backend/tests/test_logic.py
+++ b/products/mcp_analytics/backend/tests/test_logic.py
@@ -3,6 +3,7 @@ from posthog.test.base import APIBaseTest
from django.utils import timezone
from products.mcp_analytics.backend import logic
+from products.mcp_analytics.backend.constants import MAX_SNAPSHOT_CLUSTERS
from products.mcp_analytics.backend.facade import contracts, enums
from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot
from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
@@ -122,6 +123,49 @@ class TestGetIntentClusterSnapshot(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest
assert snapshot.computed_with is not None
assert snapshot.computed_with.n_clusters == 1
+ def test_caps_clusters_from_an_oversized_stored_blob(self) -> None:
+ # Snapshots persisted before the build-side cap can hold hundreds of
+ # clusters; the read path must not return them all in one response.
+ def cluster_item(i: int) -> dict:
+ return {
+ "id": i,
+ "label": f"intent {i}",
+ "intent_count": 1,
+ "session_count": 1,
+ "call_count": i + 1,
+ "error_count": 0,
+ "error_rate_pct": 0.0,
+ "routing_entropy": 0.0,
+ "tool_distribution": [],
+ "sample_intents": [],
+ }
+
+ n_total = MAX_SNAPSHOT_CLUSTERS + 10
+ # Stored lowest-volume first to prove the read path ranks by call count
+ # instead of trusting blob order.
+ MCPIntentClusterSnapshot.objects.create(
+ team=self.team,
+ status=MCPIntentClusterSnapshot.Status.IDLE,
+ last_computed_at=timezone.now(),
+ clusters={
+ "clusters": [cluster_item(i) for i in range(n_total)],
+ "computed_with": {
+ "distance_threshold": 0.2,
+ "embedding_model": "text-embedding-3-small-1536",
+ "n_intents": n_total,
+ "n_clusters": n_total,
+ },
+ },
+ )
+
+ snapshot = logic.get_intent_cluster_snapshot(self.team)
+
+ assert len(snapshot.clusters) == MAX_SNAPSHOT_CLUSTERS
+ assert snapshot.clusters[0].call_count == n_total
+ assert min(cluster.call_count for cluster in snapshot.clusters) == 11
+ assert snapshot.computed_with is not None
+ assert snapshot.computed_with.n_clusters == n_total
+
def test_stale_computing_snapshot_is_auto_flipped_to_error(self) -> None:
from datetime import timedelta
diff --git a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
index 2e4229aede73..356cbc8d1ad3 100644
--- a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
+++ b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
@@ -111,56 +111,64 @@ function HeatmapCell({
}
function Scorecards(): JSX.Element {
- const { concentratedRoutes, spreadRoutes, topErrorRoute, clusters } = useValues(mcpClusteringLogic)
+ const { concentratedRoutes, spreadRoutes, topErrorRoute, clusters, totalClusterCount } =
+ useValues(mcpClusteringLogic)
const concentratedShare =
concentratedRoutes.total > 0 ? Math.round((100 * concentratedRoutes.focused) / concentratedRoutes.total) : 0
return (
- <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 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>
- <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>
+ ) : 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>
- <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)}%
+ <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>
- <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 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>
)
@@ -187,8 +195,9 @@ function SortHeader(): JSX.Element {
}
function Heatmap(): JSX.Element {
- const { sortedClusters, toolColumns, selectedClusterId } = useValues(mcpClusteringLogic)
- const { selectCluster } = useActions(mcpClusteringLogic)
+ const { visibleClusters, hiddenClusterCount, toolColumns, totalToolCount, selectedClusterId } =
+ useValues(mcpClusteringLogic)
+ const { selectCluster, showAllClusters } = useActions(mcpClusteringLogic)
if (toolColumns.length === 0) {
return (
@@ -206,124 +215,153 @@ function Heatmap(): JSX.Element {
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 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',
- }}
+ <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}
- </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>
- {sortedClusters.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
+ </th>
+ ) : (
+ <th
key={tool}
- className="p-0 align-middle"
+ className="px-0 pb-1 pt-2 font-medium align-bottom"
// eslint-disable-next-line react/forbid-dom-props
- style={
- isSpacious
- ? undefined
- : { width: columnWidth, minWidth: columnWidth, maxWidth: columnWidth }
- }
+ style={{ 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
+ 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>
- </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' : ''
+ </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'
}`}
>
- {cluster.error_rate_pct.toFixed(1)}%
- </td>
- <td className="px-3 py-1.5">
- <EntropyBadge entropy={cluster.routing_entropy} />
- </td>
- </tr>
- )
- })}
- </tbody>
- </table>
+ <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>
)
}
@@ -434,7 +472,7 @@ function ClusterDetail({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Eleme
}
function StatusRow(): JSX.Element | null {
- const { snapshot, isComputing } = useValues(mcpClusteringLogic)
+ const { snapshot, isComputing, clusters, totalClusterCount } = useValues(mcpClusteringLogic)
const { recompute } = useActions(mcpClusteringLogic)
if (snapshot.status === 'error') {
return null
@@ -457,7 +495,11 @@ function StatusRow(): JSX.Element | null {
{meta ? (
<>
<span>·</span>
- <span>{meta.n_clusters} clusters</span>
+ <span>
+ {totalClusterCount > clusters.length
+ ? `top ${clusters.length} of ${totalClusterCount} clusters`
+ : `${totalClusterCount} clusters`}
+ </span>
<span>·</span>
<span>{meta.n_intents} intents</span>
<span>·</span>
diff --git a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts
new file mode 100644
index 000000000000..793571162f2b
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts
@@ -0,0 +1,120 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { mcpAnalyticsIntentClustersRetrieve } from '../generated/api'
+import type { MCPIntentClusterApi, MCPIntentClusterSnapshotApi } from '../generated/api.schemas'
+import { MAX_HEATMAP_TOOL_COLUMNS, MAX_VISIBLE_CLUSTERS, mcpClusteringLogic } from './mcpClusteringLogic'
+
+jest.mock('lib/api')
+jest.mock('../generated/api', () => ({
+ mcpAnalyticsIntentClustersRetrieve: jest.fn(),
+ mcpAnalyticsIntentClustersRecompute: jest.fn(),
+}))
+
+const mockRetrieve = mcpAnalyticsIntentClustersRetrieve as jest.Mock
+
+function cluster(id: number, overrides: Partial<MCPIntentClusterApi> = {}): MCPIntentClusterApi {
+ return {
+ id,
+ label: `intent ${id}`,
+ intent_count: 1,
+ session_count: 1,
+ call_count: 100 - id,
+ error_count: 0,
+ error_rate_pct: 0,
+ routing_entropy: 0,
+ // Two tools per cluster: a high-volume one unique to the cluster and a
+ // 1-call long-tail one, so the snapshot carries 2× clusters distinct tools.
+ tool_distribution: [
+ { tool: `tool-${id}`, count: 100 - id, pct: 99, errors: 0, error_rate_pct: 0 },
+ { tool: `tail-${id}`, count: 1, pct: 1, errors: 0, error_rate_pct: 0 },
+ ],
+ sample_intents: [`intent ${id}`],
+ journey: null,
+ ...overrides,
+ }
+}
+
+// 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
+
+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 } : {})
+ ),
+ computed_with: {
+ distance_threshold: 0.2,
+ embedding_model: 'test',
+ n_intents: N_CLUSTERS,
+ n_clusters: N_CLUSTERS,
+ },
+}
+
+describe('mcpClusteringLogic', () => {
+ let logic: ReturnType<typeof mcpClusteringLogic.build>
+
+ beforeEach(async () => {
+ jest.clearAllMocks()
+ initKeaTests()
+ mockRetrieve.mockResolvedValue(SNAPSHOT)
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ 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)
+
+ logic.actions.showAllClusters()
+
+ expect(logic.values.visibleClusters).toHaveLength(N_CLUSTERS)
+ expect(logic.values.hiddenClusterCount).toBe(0)
+ })
+
+ 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)
+
+ logic.actions.setSortKey('errors')
+
+ // …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)
+ })
+
+ 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)
+ })
+
+ it('reports the true cluster count from computed_with when the snapshot is truncated', async () => {
+ expect(logic.values.totalClusterCount).toBe(N_CLUSTERS)
+
+ // 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.
+ mockRetrieve.mockResolvedValue({
+ ...SNAPSHOT,
+ computed_with: { ...SNAPSHOT.computed_with!, n_clusters: 500 },
+ })
+ logic.actions.loadSnapshot()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.totalClusterCount).toBe(500)
+ })
+})
diff --git a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
index 4279f1dbdf6d..7e4801029471 100644
--- a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
@@ -1,15 +1,4 @@
-import {
- MakeLogicType,
- actions,
- afterMount,
- beforeUnmount,
- connect,
- kea,
- listeners,
- path,
- reducers,
- selectors,
-} from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
@@ -30,6 +19,13 @@ 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
+
// 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.
function normalizeSnapshot(
@@ -49,12 +45,14 @@ export type ClusterSortKey = 'calls' | 'errors' | 'entropy' | 'concentration'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpClusteringLogicValues {
currentProjectId: number | string // teamLogic
+ allClustersShown: boolean
clusters: readonly MCPIntentClusterApi[]
concentratedRoutes: {
focused: number
total: number
}
hasSnapshot: boolean
+ hiddenClusterCount: number
isComputing: boolean
selectedCluster: MCPIntentClusterApi | null
selectedClusterId: number | null
@@ -65,6 +63,9 @@ export interface mcpClusteringLogicValues {
spreadRoutes: number
toolColumns: string[]
topErrorRoute: MCPIntentClusterApi | null
+ totalClusterCount: number
+ totalToolCount: number
+ visibleClusters: MCPIntentClusterApi[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -96,6 +97,9 @@ export interface mcpClusteringLogicActions {
setSortKey: (sortKey: ClusterSortKey) => {
sortKey: ClusterSortKey
}
+ showAllClusters: () => {
+ value: true
+ }
startPolling: () => {
value: true
}
@@ -124,7 +128,11 @@ export interface mcpClusteringLogicMeta {
__keaTypeGenInternalSelectorTypes: {
clusters: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPIntentClusterApi[]
sortedClusters: (clusters: readonly MCPIntentClusterApi[], sortKey: ClusterSortKey) => MCPIntentClusterApi[]
+ visibleClusters: (sortedClusters: MCPIntentClusterApi[], allClustersShown: boolean) => MCPIntentClusterApi[]
+ hiddenClusterCount: (sortedClusters: MCPIntentClusterApi[], visibleClusters: MCPIntentClusterApi[]) => number
toolColumns: (clusters: readonly MCPIntentClusterApi[]) => string[]
+ totalToolCount: (clusters: readonly MCPIntentClusterApi[]) => number
+ totalClusterCount: (snapshot: MCPIntentClusterSnapshotApi) => number
selectedCluster: (
clusters: readonly MCPIntentClusterApi[],
selectedClusterId: number | null
@@ -155,6 +163,7 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
actions({
selectCluster: (clusterId: number | null) => ({ clusterId }),
setSortKey: (sortKey: ClusterSortKey) => ({ sortKey }),
+ showAllClusters: true,
recompute: true,
startPolling: true,
stopPolling: true,
@@ -194,6 +203,12 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
setSortKey: (_, { sortKey }) => sortKey,
},
],
+ allClustersShown: [
+ false,
+ {
+ showAllClusters: () => true,
+ },
+ ],
}),
selectors({
clusters: [
@@ -219,7 +234,20 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
}
},
],
- // Tools across the whole snapshot, ordered by total calls desc — these are the heatmap columns.
+ // The heatmap rows: sliced after sorting so re-sorting can surface any
+ // cluster into the visible set.
+ visibleClusters: [
+ (s) => [s.sortedClusters, s.allClustersShown],
+ (sortedClusters: MCPIntentClusterApi[], allClustersShown: boolean): MCPIntentClusterApi[] =>
+ allClustersShown ? sortedClusters : sortedClusters.slice(0, MAX_VISIBLE_CLUSTERS),
+ ],
+ hiddenClusterCount: [
+ (s) => [s.sortedClusters, s.visibleClusters],
+ (sortedClusters: MCPIntentClusterApi[], visibleClusters: MCPIntentClusterApi[]): number =>
+ sortedClusters.length - visibleClusters.length,
+ ],
+ // Tools across the whole snapshot, ordered by total calls desc — these are
+ // the heatmap columns, capped so a wide tool set can't explode the table.
toolColumns: [
(s) => [s.clusters],
(clusters: readonly MCPIntentClusterApi[]): string[] => {
@@ -229,9 +257,32 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
totals.set(entry.tool, (totals.get(entry.tool) ?? 0) + entry.count)
}
}
- return [...totals.entries()].sort((a, b) => b[1] - a[1]).map(([tool]) => tool)
+ return [...totals.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, MAX_HEATMAP_TOOL_COLUMNS)
+ .map(([tool]) => tool)
+ },
+ ],
+ totalToolCount: [
+ (s) => [s.clusters],
+ (clusters: readonly MCPIntentClusterApi[]): number => {
+ const tools = new Set<string>()
+ for (const cluster of clusters) {
+ 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.
+ totalClusterCount: [
+ (s) => [s.snapshot],
+ (snapshot: MCPIntentClusterSnapshotApi): number =>
+ Math.max(snapshot.computed_with?.n_clusters ?? 0, snapshot.clusters.length),
+ ],
selectedCluster: [
(s) => [s.clusters, s.selectedClusterId],
(
@@ -308,18 +359,18 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
actions.triggerRecompute()
},
startPolling: () => {
- if (cache.pollHandle) {
- return
- }
- cache.pollHandle = window.setInterval(() => {
- actions.pollSnapshot()
- }, POLL_INTERVAL_MS)
+ // Keyed add replaces any existing poller, and the disposables plugin
+ // pauses it while the tab is hidden — no full-snapshot refetches in
+ // background tabs — and cleans it up on unmount.
+ cache.disposables.add(() => {
+ const intervalId = window.setInterval(() => {
+ actions.pollSnapshot()
+ }, POLL_INTERVAL_MS)
+ return () => window.clearInterval(intervalId)
+ }, 'snapshotPoll')
},
stopPolling: () => {
- if (cache.pollHandle) {
- window.clearInterval(cache.pollHandle)
- cache.pollHandle = null
- }
+ cache.disposables.dispose('snapshotPoll')
},
pollSnapshot: () => {
actions.loadSnapshot()
@@ -328,7 +379,4 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
afterMount(({ actions }) => {
actions.loadSnapshot()
}),
- beforeUnmount(({ actions }) => {
- actions.stopPolling()
- }),
])
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
index 45e6c0e4a201..e08408226429 100644
--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
@@ -432,6 +432,7 @@ export function buildKPIs(rows: BucketRow[], currentStartBucket: string): KPIDat
export interface mcpDashboardOverviewLogicValues {
clusters: readonly MCPIntentClusterApi[] // mcpClusteringLogic
hasSnapshot: boolean // mcpClusteringLogic
+ totalClusterCount: number // mcpClusteringLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
timezone: string // teamLogic
activityIncompleteTail: boolean
@@ -645,7 +646,7 @@ export interface mcpDashboardOverviewLogicMeta {
dailyActivity: (activityRows: ActivityRow[], bucketKeys: string[]) => DailyActivity
toolDailySeries: (toolDailyRows: ToolDailyRow[], bucketKeys: string[]) => ToolDailySeries
notableSessions: (sessionRows: SessionRow[]) => NotableSession[]
- intentClusterCount: (clusters: readonly MCPIntentClusterApi[]) => KPIMetric
+ intentClusterCount: (totalClusterCount: number) => KPIMetric
}
}
@@ -659,7 +660,12 @@ export type mcpDashboardOverviewLogicType = MakeLogicType<
export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([
path(['products', 'mcp_analytics', 'frontend', 'mcpDashboardOverviewLogic']),
connect(() => ({
- values: [mcpClusteringLogic, ['clusters', 'hasSnapshot'], teamLogic, ['timezone', 'currentTeam']],
+ values: [
+ mcpClusteringLogic,
+ ['clusters', 'hasSnapshot', 'totalClusterCount'],
+ teamLogic,
+ ['timezone', 'currentTeam'],
+ ],
})),
actions({
setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
@@ -896,9 +902,11 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([
(sessionRows: SessionRow[]): NotableSession[] => pickNotableSessions(sessionRows),
],
intentClusterCount: [
- (s) => [s.clusters],
- (clusters: readonly MCPIntentClusterApi[]): KPIMetric => ({
- value: clusters.length,
+ // The snapshot only stores the top clusters by call volume — report
+ // the run's true count, not the length of the truncated list.
+ (s) => [s.totalClusterCount],
+ (totalClusterCount: number): KPIMetric => ({
+ value: totalClusterCount,
previousValue: 0,
deltaPct: null,
sparkline: [],