:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp-analytics): tool-centric intent analytics with per-call attribution (#74074)
Daniel Visca594a3543f600
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 54058553a25c..1594e717e3fd 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6467,9 +6467,9 @@ snapshots:scenes-app-mcp-analytics--dashboard-with-menu-bar--light:hash: v1.k794b7964.0ac0bf1b02890312bdc239db7a4842f1a377468aa9c5ad67c926aecaccf510ce.V7Onp6uOX4j46-gDndut-qkT9N6LwIUCq5z4hVn-VZgscenes-app-mcp-analytics--intent-clustering--dark:- hash: v1.k794b7964.93cb428637db03234a4d0d09b51ef886d95ab801bb3e4dc6ca0f1ba3824b9fe3.JeUzojRsSPumu87KUEx7WXtojxL5GEF98Ps9CVS7WAY+ hash: v1.k794b7964.cb042849f291e0ec235b0261605cbe12165c559d1ca4f8de761a18908357270b.wBXNgw84NNQEI1gXsv5uFOiR7cRn5jNApZRApxKV_r0scenes-app-mcp-analytics--intent-clustering--light:- hash: v1.k794b7964.ef2b5829c6089a3de0ad09c44f8dbeaf2195187569a83422b32ff21712e68251.JCSWUIyzmDcXs1lun_Ym3-i7Z0YBcusaI-amLEFlXs0+ hash: v1.k794b7964.484f20160cf83b4effbbc4e9fafeb27cce15dddd192d9e2c84c73d0d389360d1.TgrCvHQoDHfmlNJvQnch5Tgygpu5-sYcVhNems0DVEcscenes-app-mcp-analytics--sessions--dark:hash: v1.k794b7964.e44b6747efcbc630753707078c16ebb36a05f9701fa89c014d8eebec1eabc4fb.i5C5Ib24E2xi_tzTLXniz3WM8UKaAFOj4aqVnMmtIiIscenes-app-mcp-analytics--sessions--light:diff --git a/posthog/temporal/mcp_analytics/intent_clustering/activities.py b/posthog/temporal/mcp_analytics/intent_clustering/activities.pyindex 65a20660903f..ed78cb141a15 100644--- a/posthog/temporal/mcp_analytics/intent_clustering/activities.py+++ b/posthog/temporal/mcp_analytics/intent_clustering/activities.py@@ -109,13 +109,25 @@ async def compute_intent_clusters_activity(inputs: IntentClusteringWorkflowInputsnapshot = await _mark_computing(team, user)try:- records, intent_by_session = await database_sync_to_async(intent_clustering.fetch_intent_corpus)(- team, lookback_days=inputs.lookback_days, top_n=inputs.top_n+ session_ids = await database_sync_to_async(intent_clustering.sample_corpus_sessions)(+ team, lookback_days=inputs.lookback_days+ )+ call_rows = await database_sync_to_async(intent_clustering.fetch_session_calls)(+ team, session_ids, lookback_days=inputs.lookback_days+ )+ records, calls_by_session, corpus_stats = intent_clustering.build_call_corpus(+ call_rows, top_n=inputs.top_n+ )+ # Fetched before the empty-corpus return so that path can still report+ # what the window held: "0% of calls carried an intent" is actionable,+ # an all-null snapshot is indistinguishable from having no traffic.+ window_stats = await database_sync_to_async(intent_clustering.fetch_window_stats)(+ team, lookback_days=inputs.lookback_days)activity.heartbeat("fetched corpus")if not records:- await database_sync_to_async(_save_empty_blob)(snapshot)+ await database_sync_to_async(_save_empty_blob)(snapshot, corpus_stats, window_stats)logger.info("mcpa.intent_clustering.no_intents_found",team_id=inputs.team_id,@@ -125,7 +137,7 @@ async def compute_intent_clusters_activity(inputs: IntentClusteringWorkflowInputteam_id=inputs.team_id, n_intents=0, n_clusters=0, computed_at=timezone.now().isoformat())- embeddings, valid_indices = await intent_clustering.embed_intents_async(+ embeddings, valid_indices = await intent_clustering.embed_texts_async(team, [r.intent_text for r in records])if len(valid_indices) == 0:@@ -139,16 +151,28 @@ async def compute_intent_clusters_activity(inputs: IntentClusteringWorkflowInputlabels = await asyncio.to_thread(intent_clustering.cluster_embeddings, embeddings)activity.heartbeat("clustered")- session_journeys = await database_sync_to_async(intent_clustering.fetch_session_journeys)(- team, list(intent_by_session.keys()), lookback_days=inputs.lookback_days+ # Corpus sessions, not sampled ones: the row cap can drop whole+ # sessions after their ids were sampled, and those contribute no calls+ # to any discovery numerator.+ advertised_by_session = await database_sync_to_async(intent_clustering.fetch_advertised_tools)(+ team, list(calls_by_session), lookback_days=inputs.lookback_days)- intent_to_sessions: dict[str, list[str]] = {}- for sid, intent_text in intent_by_session.items():- intent_to_sessions.setdefault(intent_text, []).append(sid)- journeys_by_cluster = intent_clustering.aggregate_journeys_per_cluster(- aligned_records, labels, session_journeys, intent_to_sessions+ # Bound the description aggregation and embedding fan-out to the tools+ # that can appear in the snapshot; see top_corpus_tools for why.+ tool_descriptions = await database_sync_to_async(intent_clustering.fetch_tool_descriptions)(+ team, intent_clustering.top_corpus_tools(aligned_records), lookback_days=inputs.lookback_days)- activity.heartbeat("journeys")+ described = sorted(tool_descriptions.items())+ description_matrix, described_valid = await intent_clustering.embed_texts_async(+ team,+ [text for _, text in described],+ prefix=intent_clustering.DESCRIPTION_EMBEDDING_PREFIX,+ )+ description_embeddings = {+ described[original_index][0]: description_matrix[row]+ for row, original_index in enumerate(described_valid)+ }+ activity.heartbeat("context")# Same blocking-loop concern as cluster_embeddings — pure-numpy# aggregation over the labelled corpus.@@ -157,7 +181,12 @@ async def compute_intent_clusters_activity(inputs: IntentClusteringWorkflowInputaligned_records,labels,embeddings,- journeys_by_cluster=journeys_by_cluster,+ calls_by_session=calls_by_session,+ advertised_by_session=advertised_by_session,+ tool_descriptions=tool_descriptions,+ description_embeddings=description_embeddings,+ corpus_stats=corpus_stats,+ window_stats=window_stats,)await _persist_clusters(snapshot, clusters_blob)@@ -184,21 +213,22 @@ async def compute_intent_clusters_activity(inputs: IntentClusteringWorkflowInputraise-def _save_empty_blob(snapshot: MCPIntentClusterSnapshot) -> None:+def _save_empty_blob(+ snapshot: MCPIntentClusterSnapshot,+ corpus_stats: intent_clustering.CorpusStats | None = None,+ window_stats: intent_clustering.WindowStats | None = None,+) -> None:"""Synchronous helper to write an empty snapshot when the corpus is empty.Lives outside the async activity body so ``database_sync_to_async`` canwrap it without re-entrancy from inside an async context."""- snapshot.clusters = {- "clusters": [],- "computed_with": {- "distance_threshold": intent_clustering.DEFAULT_DISTANCE_THRESHOLD,- "embedding_model": intent_clustering.EMBEDDING_MODEL,- "n_intents": 0,- "n_clusters": 0,- },- }+ snapshot.clusters = intent_clustering.empty_snapshot(+ intent_clustering.DEFAULT_DISTANCE_THRESHOLD,+ n_intents=0,+ corpus_stats=corpus_stats,+ window_stats=window_stats,+ )snapshot.status = MCPIntentClusterSnapshot.Status.IDLEsnapshot.error_message = ""snapshot.last_computed_at = timezone.now()diff --git a/products/mcp_analytics/backend/constants.py b/products/mcp_analytics/backend/constants.pyindex b13b07bf3cbe..cd89b5a4854f 100644--- a/products/mcp_analytics/backend/constants.py+++ b/products/mcp_analytics/backend/constants.py@@ -2,6 +2,8 @@# (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"+# Emitted per tools/list response; carries $mcp_listed_tool_names (the advertised catalog).+MCP_TOOLS_LIST_EVENT = "$mcp_tools_list"# Intent cluster snapshots are stored as one JSON blob and served unpaginated,# so cap how many clusters (ranked by call volume) a snapshot carries. Adiff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.pyindex de18f977df77..f7984bc9c7eb 100644--- a/products/mcp_analytics/backend/facade/api.py+++ b/products/mcp_analytics/backend/facade/api.py@@ -107,8 +107,9 @@ def get_activity_overview(team: Team) -> contracts.ActivityOverview:return logic.get_activity_overview(team)-def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:- return logic.get_intent_cluster_snapshot(team)+def get_intent_cluster_snapshot(team: Team, tool: str | None = None) -> contracts.IntentClusterSnapshot:+ """The latest snapshot, optionally narrowed to one tool's slice of it."""+ return logic.get_intent_cluster_snapshot(team, tool=tool)def trigger_intent_cluster_recompute(team: Team, user: User | None) -> None:diff --git a/products/mcp_analytics/backend/facade/contracts.py b/products/mcp_analytics/backend/facade/contracts.pyindex a8705c1d65c0..27fac2506f0c 100644--- a/products/mcp_analytics/backend/facade/contracts.py+++ b/products/mcp_analytics/backend/facade/contracts.py@@ -120,6 +120,19 @@ class IntentClusterJourney:leak: IntentClusterJourneyPath | None+@dataclass(frozen=True)+class ClusterSwitch:+ from_tool: str+ to_tool: str+ count: int+++@dataclass(frozen=True)+class ClusterSelfRetry:+ tool: str+ count: int++@dataclass(frozen=True)class IntentCluster:id: int@@ -133,6 +146,53 @@ class IntentCluster:tool_distribution: list[IntentClusterToolEntry]sample_intents: list[str]journey: IntentClusterJourney | None = None+ switches: list[ClusterSwitch] = field(default_factory=list)+ self_retries: list[ClusterSelfRetry] = field(default_factory=list)+++@dataclass(frozen=True)+class ToolPivotCompetitor:+ tool: str+ pct: float+++@dataclass(frozen=True)+class ToolPivotClusterEntry:+ """One tool's slice of one cluster. Deliberately carries no per-cluster+ constants — the cluster's label, totals, and entropy are joined on+ ``cluster_id`` so the blob doesn't repeat them once per tool."""++ cluster_id: int+ calls: int+ capture_pct: float+ rank: int+ description_fit: float | None = None+ top_competitor: ToolPivotCompetitor | None = None+++@dataclass(frozen=True)+class ToolPivot:+ tool: str+ call_count: int+ error_count: int+ session_count: int+ contested_score: float | None+ advertised_sessions: int+ called_when_advertised: int+ discovery_rate_pct: float | None+ description: str | None+ n_clusters_served: int = 0+ clusters: list[ToolPivotClusterEntry] = field(default_factory=list)+++@dataclass(frozen=True)+class ToolOverlap:+ tool_a: str+ tool_b: str+ contested_calls: int+ sessions_with_both: int+ sessions_with_either: int+ top_cluster_id: int@dataclass(frozen=True)@@ -141,6 +201,20 @@ class IntentClusterSnapshotMeta:embedding_model: strn_intents: intn_clusters: int+ # v2 (per-call corpus) coverage fields; None on snapshots computed before v2.+ corpus: str | None = None+ sampled_sessions: int | None = None+ window_sessions: int | None = None+ session_coverage_pct: float | None = None+ intent_coverage_pct: float | None = None+ imputed_call_pct: float | None = None+ unattributed_call_pct: float | None = None+ corpus_call_coverage_pct: float | None = None+ advertisement_coverage_pct: float | None = None+ n_tools: int | None = None+ dropped_tools: int | None = None+ dropped_overlap_pairs: int | None = None+ description_coverage_pct: float | None = None@dataclass(frozen=True)@@ -151,6 +225,8 @@ class IntentClusterSnapshot:last_computed_by_email: strclusters: list[IntentCluster] = field(default_factory=list)computed_with: IntentClusterSnapshotMeta | None = None+ tools: list[ToolPivot] = field(default_factory=list)+ tool_overlaps: list[ToolOverlap] = field(default_factory=list)@dataclass(frozen=True)diff --git a/products/mcp_analytics/backend/hogql_queries/base.py b/products/mcp_analytics/backend/hogql_queries/base.pyindex cd1485d50044..f757cd49ec16 100644--- a/products/mcp_analytics/backend/hogql_queries/base.py+++ b/products/mcp_analytics/backend/hogql_queries/base.py@@ -33,6 +33,14 @@ MCP_ANALYTICS_FEATURE_FLAG = "mcp-analytics"EFFECTIVE_TOOL_SQL = ("coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name))")+# The description of the *effective* tool: for single-exec calls the inner tool's+# $mcp_exec_tool_call_description, else the directly-registered $mcp_tool_description.+# Without this, an inner tool's description would resolve to the exec wrapper's text+# (another tool's description) — a tool-level disclosure.+EFFECTIVE_DESCRIPTION_SQL = (+ "coalesce(nullIf(toString(properties.$mcp_exec_tool_call_description), ''), "+ "toString(properties.$mcp_tool_description))"+)# Marker the posthog-node MCP analytics SDK stamps on the events it sends.NEW_SDK_SOURCE = "posthog_mcp_analytics"diff --git a/products/mcp_analytics/backend/hogql_queries/tool_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_tables.pyindex ecd43f709ab0..14eade6c9328 100644--- a/products/mcp_analytics/backend/hogql_queries/tool_tables.py+++ b/products/mcp_analytics/backend/hogql_queries/tool_tables.py@@ -56,6 +56,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.mcp_analytics.backend import mcp_harnessfrom products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENTfrom products.mcp_analytics.backend.hogql_queries.base import (+ EFFECTIVE_DESCRIPTION_SQL,EFFECTIVE_TOOL_SQL,NEW_SDK_SOURCE,mcp_query_date_range,@@ -66,14 +67,9 @@ from products.mcp_analytics.backend.hogql_queries.base import (if TYPE_CHECKING:from posthog.models.user import User-# The description of the *effective* tool: for single-exec calls the inner tool's-# $mcp_exec_tool_call_description, else the directly-registered $mcp_tool_description.-# Without this, an inner tool's Descriptions table would show the exec wrapper's text-# (another tool's description) — a tool-level disclosure.-_EFFECTIVE_DESCRIPTION = (- "coalesce(nullIf(toString(properties.$mcp_exec_tool_call_description), ''), "- "toString(properties.$mcp_tool_description))"-)+# The effective-description expression lives in base.py so the intent-clustering+# pipeline resolves descriptions identically to the Descriptions table here.+_EFFECTIVE_DESCRIPTION = EFFECTIVE_DESCRIPTION_SQL# A per-row distinct-and-sorted list of resolved harness labels, collected from the# token computed in the inner subquery. groupArray evaluates the label per row, so thediff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.pyindex 43482d7083f7..1caba22daee2 100644--- a/products/mcp_analytics/backend/intent_clustering.py+++ b/products/mcp_analytics/backend/intent_clustering.py@@ -1,6 +1,6 @@"""Intent clustering pipeline for MCP analytics.-Four pure functions, each independently testable, that together build a cluster+Pure functions, each independently testable, that together build a clustersnapshot of MCP intents. The Temporal activity in``posthog/temporal/mcp_analytics/intent_clustering/activities.py`` orchestratesthem and persists the result.@@ -10,29 +10,36 @@ each stage as a pure function over numpy arrays / dataclasses makes thealgorithm validatable without touching ClickHouse, Postgres, or the embeddingservice.-Intent sources: the corpus is built from the ``$mcp_intent`` recorded on tool-call-events (the first intent of each session, sampled from ClickHouse), overlaid with-the LLM-generated session summaries from ``posthog_mcp_session`` where those exist.-Event intents give scale without any LLM dependency; summaries, generated on-demand, win per session because they condense the whole session's intents.+Intent sources: the corpus is per tool call, and events are its only source.+Each call carries its own ``$mcp_intent``; calls without one inherit the most+recent prior intent in the same session (last observation carried forward), so+tools are credited to the intent they actually served rather than to the+session's opening statement. The on-demand ``MCPSession.intent`` LLM summaries+are deliberately *not* overlaid: a summary describes a whole session, so+attributing it to each of that session's calls is the smear this corpus exists+to remove. Sessions whose intent was only ever summarised therefore sit outside+clustering; ``intent_coverage_pct`` reports how much of the window that leaves+out.+The snapshot also carries a tool-centric pivot: per tool, which intent clusters+it serves, its share of each (capture), how contested those clusters are, and,+where a ``$mcp_tools_list`` catalog was observed, how often agents discover the+tool when it is advertised."""import mathimport asyncioimport hashlibfrom collections import Counter, defaultdict+from collections.abc import Collectionfrom dataclasses import dataclass, field-from datetime import timedeltafrom typing import Any-from django.utils import timezone-import numpy as npimport structlogfrom sklearn.cluster import AgglomerativeClusteringfrom posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.api.embedding_worker import EmbeddingResponse, async_generate_embedding@@ -40,22 +47,47 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.team.team import Teamfrom posthog.sync import database_sync_to_async-from products.mcp_analytics.backend.constants import MAX_SNAPSHOT_CLUSTERS, MCP_TOOL_CALL_EVENT-from products.mcp_analytics.backend.models import MCPIntentEmbeddingCache, MCPSession+from products.mcp_analytics.backend.constants import MAX_SNAPSHOT_CLUSTERS, MCP_TOOL_CALL_EVENT, MCP_TOOLS_LIST_EVENT+from products.mcp_analytics.backend.hogql_queries.base import EFFECTIVE_DESCRIPTION_SQL, EFFECTIVE_TOOL_SQL+from products.mcp_analytics.backend.models import MCPIntentEmbeddingCachelogger = structlog.get_logger(__name__)# Constants+SNAPSHOT_VERSION = 2EMBEDDING_MODEL = "text-embedding-3-small-1536"EMBEDDING_PREFIX = "User intent: "+# Descriptions share the intent embedding cache; the prefix keys them apart so+# identical text embedded as an intent and as a description never collides.+DESCRIPTION_EMBEDDING_PREFIX = "Tool description: "DEFAULT_LOOKBACK_DAYS = 7-DEFAULT_TOP_N_INTENTS = 500+DEFAULT_TOP_N_INTENTS = 1000DEFAULT_DISTANCE_THRESHOLD = 0.2MAX_SAMPLE_INTENTS_PER_CLUSTER = 3-# Placeholder previously written by the (now-removed) summariser job for sessions with no-# recordable tool-call intents. Still filtered out of the corpus so it doesn't form a-# meaningless pseudo-cluster of "empty" sessions.+# Mirrors the capture-side clip in services/mcp (MAX_CAPTURED_DESCRIPTION_LENGTH);+# re-applied here because external SDKs may stamp longer values.+MAX_DESCRIPTION_LENGTH = 512+# Below this many advertised sessions a discovery rate is noise, so it stays null.+MIN_ADVERTISED_SESSIONS = 5+# Payload bounds for the snapshot blob. Only the two top-level caps report what they+# dropped (`dropped_tools`, `dropped_overlap_pairs` in computed_with); the per-cluster+# caps below truncate silently, so `computed_with` is not a completeness check for them.+# The per-tool cluster cap is the exception: `n_clusters_served` carries the pre-cap+# count, so a tool showing 20 entries can still say how many it really serves.+MAX_TOOLS_IN_SNAPSHOT = 300+MAX_CLUSTERS_PER_TOOL = 20+MAX_SWITCHES_PER_CLUSTER = 10+MAX_SELF_RETRIES_PER_CLUSTER = 5+MAX_CONFUSION_PAIRS = 50+# Pair expansion is O(n^2) in a cluster's tool count, and event senders control+# tool names, so only each cluster's highest-volume tools enter it. Tail tools+# contribute at most their own tiny min(count) anyway.+MAX_OVERLAP_TOOLS_PER_CLUSTER = 20++# Placeholder the session summariser writes when a session has no recordable intent.+# No event ever carries it, so this only bites if a summary is ever fed back into the+# corpus — kept as a guard so that path can't form a pseudo-cluster of "empty" sessions.NO_INTENT_RECORDED_FALLBACK = "No agent intent was recorded for this session."# Embedding cache + concurrency@@ -74,7 +106,7 @@ MAX_JOURNEY_PATHS_PER_CLUSTER = 10@dataclass(frozen=True)class IntentRecord:- """One unique intent text, with the tool-call statistics observed for it."""+ """One unique intent text, with the per-call tool statistics attributed to it."""intent_text: strfrequency: int@@ -83,37 +115,88 @@ class IntentRecord:error_counts: dict[str, int] = field(default_factory=dict)+@dataclass(frozen=True)+class CallRecord:+ """One tool call after intent attribution. ``intent_text`` is None when the+ call happened before its session's first recorded intent."""++ session_id: str+ tool: str+ intent_text: str | None+ is_error: bool+++@dataclass(frozen=True)+class CorpusStats:+ """Attribution accounting for the sampled corpus, surfaced in computed_with+ so the UI can state how much of the traffic the clusters actually explain."""++ total_calls: int+ attributed_calls: int+ imputed_calls: int+ kept_calls: int+++@dataclass(frozen=True)+class WindowStats:+ """Whole-window aggregates (not sampled) used for coverage reporting."""++ total_calls: int+ calls_with_intent: int+ sessions: int++# Intent corpus -----------------------------------------------------------# Bound on sessions sampled from ClickHouse for the corpus. Keeps the IN-tuple-# in the two per-session queries below at a sane size; with-# DEFAULT_TOP_N_INTENTS=500 a larger sample only adds long-tail singletons.+# in the per-session queries below at a sane size; a larger sample mostly adds+# long-tail singleton intents past DEFAULT_TOP_N_INTENTS anyway.MAX_CORPUS_SESSIONS = 2000# execute_hogql_query injects LIMIT 100 into any query without an explicit-# LIMIT — far below what the per-session stats and journey queries return at-# production scale (one-plus rows per corpus session). Cap explicitly at the-# HogQL per-query maximum so results are never silently truncated.+# LIMIT — far below what the per-session queries return at production scale+# (one-plus rows per corpus session). Cap explicitly at the HogQL per-query+# maximum so results are never silently truncated.MAX_QUERY_ROWS = 50_000# Event-sourced intents are free text written by the calling agent — clip them# so one oversized value can't blow up embedding requests (the worker's model# has a token ceiling) or bloat the snapshot blob. Real intents are one or two-# sentences; anything past this length adds no clustering signal.+# sentences; anything past this length adds no clustering signal. Clipping+# happens inside the corpus SQL (HogQL left → leftUTF8) so oversized values+# never leave ClickHouse — up to MAX_QUERY_ROWS of them would otherwise+# materialize in worker memory; build_call_corpus re-clips as defense for+# callers that feed it rows from elsewhere.MAX_INTENT_TEXT_LENGTH = 1000-# First (chronological) $mcp_intent per session — the agent's opening task-# statement, used as the session's representative intent unless an on-demand-# LLM summary exists in Postgres. Ordering by cityHash64(session_id) is a-# deterministic pseudo-random sample: unbiased across the window (newest-first-# would collapse the corpus to the last few hours at production volume) and-# stable across reruns, so repeat runs re-hit the embedding cache.+# Tool names are sender-controlled too, so they get the same SQL-boundary clip.+# Must be applied identically across the calls, descriptions, and+# advertised-catalog queries, or pivot and discovery keys stop matching for+# oversized names. Real tool names are well under 100 chars.+MAX_TOOL_NAME_LENGTH = 256++# The advertised catalog is a sender-controlled array inside a sender-controlled number+# of $mcp_tools_list events, and the union aggregates both. Clipping name *length* alone+# leaves two unbounded dimensions, so each event's array is sliced and each session's+# events are capped before the union materializes. A real catalog is a few hundred tools+# listed once or twice per session, so both bounds sit far above honest traffic.+MAX_TOOLS_PER_ADVERTISED_LIST = 500+MAX_ADVERTISED_LIST_EVENTS_PER_SESSION = 20+# The two caps above still multiply (events x names, across every sampled session), so+# the distinct union itself is also bounded per session. This is the bound that limits+# what leaves ClickHouse and lands in worker memory; the honest case (a few hundred+# distinct tools per catalog) sits comfortably under it.+MAX_ADVERTISED_TOOLS_PER_SESSION = 1000++# Sessions that recorded at least one $mcp_intent, sampled deterministically.+# Ordering by cityHash64(session_id) is a pseudo-random sample: unbiased across+# the window (newest-first would collapse the corpus to the last few hours at+# production volume) and stable across reruns, so repeat runs re-hit the+# embedding cache.# NB: `$session_id` is the materialised events column ('' when absent), NOT the# `properties.` accessor — same rationale as logic.py's session SQL.-_SESSION_FIRST_INTENT_SQL = """-SELECT- $session_id AS session_id,- argMin(toString(properties.$mcp_intent), timestamp) AS first_intent+_CORPUS_SESSION_SAMPLE_SQL = """+SELECT $session_id AS session_idFROM eventsWHERE event = {event}AND timestamp >= now() - INTERVAL {lookback_days} DAY@@ -124,257 +207,412 @@ ORDER BY cityHash64(session_id)LIMIT {max_sessions}"""-# Per-session tool stats: for each session in the corpus, what tools were-# called and how often. Joined in Python with the session→intent map so the-# same intent string can aggregate across sessions.-# TODO(intent-routing): chaining is by $session_id today; swap to-# $mcp_session_id once tool calls carry it consistently.-_SESSION_TOOL_STATS_SQL = """+# Every tool call of the sampled sessions, in call order, with the call's own+# intent (may be empty; attribution happens in build_call_corpus). The+# effective-tool coalesce matches every other MCP analytics surface, so+# exec-wrapped inner calls resolve to the inner tool here too.+_SESSION_CALLS_SQL = """SELECT$session_id AS session_id,- toString(properties.$mcp_tool_name) AS tool_name,- countIf(toString(properties.$mcp_is_error) NOT IN ('true', '1')) AS success_count,- countIf(toString(properties.$mcp_is_error) IN ('true', '1')) AS error_count+ left({tool_expr}, {max_tool_len}) AS tool,+ left(coalesce(toString(properties.$mcp_intent), ''), {max_intent_len}) AS intent,+ toString(properties.$mcp_is_error) IN ('true', '1') AS is_errorFROM eventsWHERE event = {event}AND $session_id IN {session_ids}- AND properties.$mcp_tool_name IS NOT NULL- AND properties.$mcp_tool_name != ''AND timestamp >= now() - INTERVAL {lookback_days} DAY-GROUP BY session_id, tool_name+ AND notEmpty({tool_expr_where})+ORDER BY session_id, timestampLIMIT {max_rows}"""-# Per-session ordered tool sequence + whether any call errored. arrayMap +-# arraySort on (timestamp, tool) tuples preserves call order.-_SESSION_JOURNEY_SQL = """+# Union of $mcp_listed_tool_names across a session's $mcp_tools_list events —+# the catalog the agent actually saw, which is the denominator for discovery+# rates. The coalesce to '[]' matters: the property accessor is Nullable and+# JSONExtract of a Nullable into Array(String) is a ClickHouse type error.+_SESSION_ADVERTISED_TOOLS_SQL = """SELECT- $session_id AS session_id,- arrayMap(- x -> x.2,- arraySort(- x -> x.1,- groupArray(tuple(timestamp, toString(properties.$mcp_tool_name)))- )- ) AS tool_sequence,- countIf(toString(properties.$mcp_is_error) IN ('true', '1')) > 0 AS had_error+ session_id,+ arraySlice(+ arrayDistinct(arrayMap(x -> left(x, {max_tool_len}), arrayFlatten(groupArray(listed)))),+ 1,+ {max_advertised_tools}+ ) AS advertised_tools+FROM (+ SELECT+ $session_id AS session_id,+ arraySlice(+ JSONExtract(coalesce(toString(properties.$mcp_listed_tool_names), '[]'), 'Array(String)'),+ 1,+ {max_tools_per_list}+ ) AS listed+ FROM events+ WHERE event = {event}+ AND $session_id IN {session_ids}+ AND timestamp >= now() - INTERVAL {lookback_days} DAY+ AND $session_id != ''+ ORDER BY timestamp+ LIMIT {max_list_events} BY session_id+)+GROUP BY session_id+LIMIT {max_rows}+"""++# Whole-window totals for the coverage metrics in computed_with. One cheap+# aggregate row; deliberately unsampled so the UI can honestly relate the+# sampled corpus to the traffic it represents. The notEmpty tool predicate+# mirrors _SESSION_CALLS_SQL — the coverage banner reads these percentages+# against the corpus, so both have to describe the same population.+_WINDOW_STATS_SQL = """+SELECT+ count() AS total_calls,+ countIf(coalesce(toString(properties.$mcp_intent), '') != '') AS calls_with_intent,+ uniq($session_id) AS sessionsFROM eventsWHERE event = {event}- AND $session_id IN {session_ids}- AND properties.$mcp_tool_name IS NOT NULL- AND properties.$mcp_tool_name != ''AND timestamp >= now() - INTERVAL {lookback_days} DAY-GROUP BY session_id+ AND $session_id != ''+ AND notEmpty({tool_expr_where})+"""++# Latest observed description per effective tool. argMax(description, timestamp)+# picks the newest revision, which is the one agents currently see.+# The tool filter is applied before GROUP BY so aggregate state only exists for the+# bounded corpus tool set — without it, a sender emitting unique tool names per call+# forces argMax state for every name before LIMIT applies.+_TOOL_DESCRIPTIONS_SQL = """+SELECT+ left({tool_expr}, {max_tool_len}) AS tool,+ argMax(left({description_expr}, {max_desc_len}), timestamp) AS description+FROM events+WHERE event = {event}+ AND timestamp >= now() - INTERVAL {lookback_days} DAY+ AND left({tool_expr_where}, {max_tool_len}) IN {tools}+ AND notEmpty({description_expr_where})+GROUP BY toolLIMIT {max_rows}"""-def fetch_intent_corpus(+def _run_corpus_query(team: Team, query: ast.SelectQuery | ast.SelectSetQuery) -> list[Any]:+ with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):+ response = execute_hogql_query(query=query, team=team)+ return response.results or []+++def _session_ids_tuple(session_ids: list[str]) -> ast.Tuple:+ return ast.Tuple(exprs=[ast.Constant(value=sid) for sid in session_ids])+++def sample_corpus_sessions(team: Team,lookback_days: int = DEFAULT_LOOKBACK_DAYS,- top_n: int = DEFAULT_TOP_N_INTENTS,-) -> tuple[list[IntentRecord], dict[str, str]]:- """Return ``(records, intent_by_session)`` for clustering.-- Each session's intent text is the first ``$mcp_intent`` it recorded (sampled- from ClickHouse, capped at ``MAX_CORPUS_SESSIONS``), overridden by the- on-demand LLM summary from posthog_mcp_session where one exists — the- summary condenses the whole session, so it wins. Tool stats come from- ClickHouse $mcp_tool_call events joined by session_id. Same intent string- repeated across sessions aggregates.-- ``intent_by_session`` is exposed so callers can later join session-level- data (e.g. journey aggregation) back to the cluster a session belongs to.-- ``lookback_days`` bounds both stores to the same window: event queries- filter by timestamp, and session intent rows are filtered by ``created_at``- (when the intent was generated, since intents are produced on demand).- """- intent_query = parse_select(- _SESSION_FIRST_INTENT_SQL,+ max_sessions: int = MAX_CORPUS_SESSIONS,+) -> list[str]:+ """Deterministically sample sessions that recorded at least one intent."""+ query = parse_select(+ _CORPUS_SESSION_SAMPLE_SQL,placeholders={"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),"lookback_days": ast.Constant(value=lookback_days),- "max_sessions": ast.Constant(value=MAX_CORPUS_SESSIONS),+ "max_sessions": ast.Constant(value=max_sessions),},)- with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):- intent_response = execute_hogql_query(query=intent_query, team=team)-- # Map session_id -> intent_text. Skip the summariser's "no intents- # recorded" placeholder — clustering it produces a meaningless- # pseudo-cluster of sessions with nothing in common except that their- # tool calls had no $mcp_intent property.- intent_by_session: dict[str, str] = {}- for row in intent_response.results or []:- session_id = str(row[0] or "")- text = str(row[1] or "").strip()[:MAX_INTENT_TEXT_LENGTH]- if not session_id or not text or text == NO_INTENT_RECORDED_FALLBACK:- continue- intent_by_session[session_id] = text-- # Overlay LLM-generated session summaries, and include summarised sessions- # the event sample missed (e.g. generated for a session whose events sit- # just outside the sampled set).- window_start = timezone.now() - timedelta(days=lookback_days)- session_rows = MCPSession.objects.filter(team=team, created_at__gte=window_start).values_list(- "session_id", "intent"- )- for session_id, intent_text in session_rows:- text = (intent_text or "").strip()[:MAX_INTENT_TEXT_LENGTH]- if not session_id or not text or text == NO_INTENT_RECORDED_FALLBACK:- continue- intent_by_session[session_id] = text+ return [str(row[0]) for row in _run_corpus_query(team, query) if row[0]]- if not intent_by_session:- return [], {}- session_ids = list(intent_by_session.keys())+def fetch_session_calls(+ team: Team,+ session_ids: list[str],+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,+) -> list[tuple[str, str, str, bool]]:+ """Return ``(session_id, tool, raw_intent, is_error)`` rows in call order."""+ if not session_ids:+ return []query = parse_select(- _SESSION_TOOL_STATS_SQL,+ _SESSION_CALLS_SQL,placeholders={"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),- "session_ids": ast.Tuple(exprs=[ast.Constant(value=sid) for sid in session_ids]),+ "tool_expr": parse_expr(EFFECTIVE_TOOL_SQL),+ "tool_expr_where": parse_expr(EFFECTIVE_TOOL_SQL),+ "session_ids": _session_ids_tuple(session_ids),"lookback_days": ast.Constant(value=lookback_days),"max_rows": ast.Constant(value=MAX_QUERY_ROWS),+ "max_tool_len": ast.Constant(value=MAX_TOOL_NAME_LENGTH),+ "max_intent_len": ast.Constant(value=MAX_INTENT_TEXT_LENGTH),},)- with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):- response = execute_hogql_query(query=query, team=team)-- # Aggregate per intent_text across all sessions that share it.- rollup: dict[str, dict[str, Any]] = {}- # Seed rollup with every intent we saw in Postgres so intents with no- # tool calls yet still surface (as a singleton, zero-call cluster).- session_count: Counter[str] = Counter()- for intent_text in intent_by_session.values():- session_count[intent_text] += 1- rollup.setdefault(intent_text, {"tool_counts": {}, "error_counts": {}})-- for row in response.results or []:- session_id = row[0] or ""- tool_name = row[1] or ""- success = int(row[2] or 0)- errors = int(row[3] or 0)- intent_text = intent_by_session.get(session_id)- if not intent_text or not tool_name:- continue- bucket = rollup[intent_text]- bucket["tool_counts"][tool_name] = bucket["tool_counts"].get(tool_name, 0) + success + errors- if errors:- bucket["error_counts"][tool_name] = bucket["error_counts"].get(tool_name, 0) + errors-- records: list[IntentRecord] = []- for text, data in rollup.items():- total_calls = sum(data["tool_counts"].values())- # Use session count as the ranking signal when no tool calls exist yet;- # otherwise total calls dominate.- frequency = total_calls or session_count[text]- records.append(- IntentRecord(- intent_text=text,- frequency=frequency,- session_count=session_count[text],- tool_counts=data["tool_counts"],- error_counts=data["error_counts"],- )+ rows = [+ (str(row[0] or ""), str(row[1] or ""), str(row[2] or ""), bool(row[3]))+ for row in _run_corpus_query(team, query)+ ]+ if len(rows) >= MAX_QUERY_ROWS:+ # The window's calls exceeded the per-query cap: the corpus silently+ # under-represents the sampled sessions. Surface it rather than let the+ # coverage numbers lie.+ logger.warning(+ "mcpa.intent_clustering.session_calls_truncated",+ team_id=team.id,+ max_rows=MAX_QUERY_ROWS,+ sessions=len(session_ids),)-- records.sort(key=lambda r: r.frequency, reverse=True)- return records[:top_n], intent_by_session+ return rows-# Journeys -------------------------------------------------------------------def fetch_session_journeys(+def fetch_advertised_tools(team: Team,session_ids: list[str],lookback_days: int = DEFAULT_LOOKBACK_DAYS,-) -> dict[str, dict[str, Any]]:- """Return ``{session_id: {tool_sequence: [...], had_error: bool}}``.+) -> dict[str, set[str]]:+ """Return ``{session_id: advertised tool names}`` for sessions with a tools-list event.- Tool calls are sorted by timestamp so the sequence reflects the order- the agent invoked them.+ Sessions with no ``$mcp_tools_list`` event are absent from the result, not+ empty — absence means "advertisement unknown", which callers must exclude+ from discovery denominators rather than treat as "nothing advertised"."""if not session_ids:return {}query = parse_select(- _SESSION_JOURNEY_SQL,+ _SESSION_ADVERTISED_TOOLS_SQL,+ placeholders={+ "event": ast.Constant(value=MCP_TOOLS_LIST_EVENT),+ "session_ids": _session_ids_tuple(session_ids),+ "lookback_days": ast.Constant(value=lookback_days),+ "max_rows": ast.Constant(value=MAX_QUERY_ROWS),+ "max_tool_len": ast.Constant(value=MAX_TOOL_NAME_LENGTH),+ "max_tools_per_list": ast.Constant(value=MAX_TOOLS_PER_ADVERTISED_LIST),+ "max_list_events": ast.Constant(value=MAX_ADVERTISED_LIST_EVENTS_PER_SESSION),+ "max_advertised_tools": ast.Constant(value=MAX_ADVERTISED_TOOLS_PER_SESSION),+ },+ )+ out: dict[str, set[str]] = {}+ for row in _run_corpus_query(team, query):+ session_id = str(row[0] or "")+ tools = {str(tool) for tool in (row[1] or []) if tool}+ if session_id and tools:+ out[session_id] = tools+ return out+++def fetch_window_stats(team: Team, lookback_days: int = DEFAULT_LOOKBACK_DAYS) -> WindowStats:+ """Whole-window call/intent/session totals for coverage reporting."""+ query = parse_select(+ _WINDOW_STATS_SQL,placeholders={"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),- "session_ids": ast.Tuple(exprs=[ast.Constant(value=sid) for sid in session_ids]),+ "tool_expr_where": parse_expr(EFFECTIVE_TOOL_SQL),+ "lookback_days": ast.Constant(value=lookback_days),+ },+ )+ rows = _run_corpus_query(team, query)+ if not rows:+ return WindowStats(total_calls=0, calls_with_intent=0, sessions=0)+ row = rows[0]+ return WindowStats(+ total_calls=int(row[0] or 0),+ calls_with_intent=int(row[1] or 0),+ sessions=int(row[2] or 0),+ )+++def fetch_tool_descriptions(+ team: Team, tools: Collection[str], lookback_days: int = DEFAULT_LOOKBACK_DAYS+) -> dict[str, str]:+ """Latest observed description per effective tool, clipped for embedding.++ ``tools`` bounds the aggregation: only the given (already clipped) tool names+ enter the GROUP BY, so sender-invented names never build aggregate state.+ """+ if not tools:+ return {}+ query = parse_select(+ _TOOL_DESCRIPTIONS_SQL,+ placeholders={+ "event": ast.Constant(value=MCP_TOOL_CALL_EVENT),+ "tool_expr": parse_expr(EFFECTIVE_TOOL_SQL),+ "tool_expr_where": parse_expr(EFFECTIVE_TOOL_SQL),+ "description_expr": parse_expr(EFFECTIVE_DESCRIPTION_SQL),+ "description_expr_where": parse_expr(EFFECTIVE_DESCRIPTION_SQL),+ "tools": ast.Tuple(exprs=[ast.Constant(value=tool) for tool in sorted(tools)]),"lookback_days": ast.Constant(value=lookback_days),"max_rows": ast.Constant(value=MAX_QUERY_ROWS),+ "max_tool_len": ast.Constant(value=MAX_TOOL_NAME_LENGTH),+ "max_desc_len": ast.Constant(value=MAX_DESCRIPTION_LENGTH),},)- with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):- response = execute_hogql_query(query=query, team=team)+ return {+ str(row[0]): str(row[1])[:MAX_DESCRIPTION_LENGTH] for row in _run_corpus_query(team, query) if row[0] and row[1]+ }- out: dict[str, dict[str, Any]] = {}- for row in response.results or []:- session_id = row[0] or ""- tool_sequence = list(row[1] or [])- had_error = bool(row[2])- if not session_id:++def build_call_corpus(+ rows: list[tuple[str, str, str, bool]],+ top_n: int = DEFAULT_TOP_N_INTENTS,+) -> tuple[list[IntentRecord], dict[str, list[CallRecord]], CorpusStats]:+ """Attribute each call to an intent and roll up per-intent tool statistics.++ Attribution is per call: a call's own ``$mcp_intent`` when present, else the+ most recent prior intent in the same session (last observation carried+ forward — agents typically state a goal once and then chain calls under it).+ Calls before a session's first intent stay unattributed; they remain in+ ``calls_by_session`` but never enter records, journeys, or switch counts.++ ``rows`` must be in call order within each session (the SQL guarantees it);+ LOCF depends on that ordering.+ """+ calls_by_session: dict[str, list[CallRecord]] = {}+ last_intent: dict[str, str] = {}+ total_calls = attributed_calls = imputed_calls = 0++ for session_id, tool, raw_intent, is_error in rows:+ if not session_id or not tool:continue- out[session_id] = {"tool_sequence": tool_sequence, "had_error": had_error}- return out+ total_calls += 1+ text = str(raw_intent or "").strip()+ # Guards against a summariser placeholder reaching the corpus; see the+ # constant. It is not an intent, and clustering it forms a pseudo-cluster.+ if text == NO_INTENT_RECORDED_FALLBACK:+ text = ""+ text = text[:MAX_INTENT_TEXT_LENGTH]++ intent_text: str | None+ if text:+ intent_text = text+ last_intent[session_id] = text+ else:+ intent_text = last_intent.get(session_id)+ if intent_text is not None:+ imputed_calls += 1+ if intent_text is not None:+ attributed_calls += 1++ calls_by_session.setdefault(session_id, []).append(+ CallRecord(session_id=session_id, tool=tool, intent_text=intent_text, is_error=is_error)+ )++ rollup: dict[str, dict[str, dict[str, int]]] = {}+ sessions_by_intent: dict[str, set[str]] = defaultdict(set)+ for session_id, calls in calls_by_session.items():+ for call in calls:+ if call.intent_text is None:+ continue+ bucket = rollup.setdefault(call.intent_text, {"tool_counts": {}, "error_counts": {}})+ bucket["tool_counts"][call.tool] = bucket["tool_counts"].get(call.tool, 0) + 1+ if call.is_error:+ bucket["error_counts"][call.tool] = bucket["error_counts"].get(call.tool, 0) + 1+ sessions_by_intent[call.intent_text].add(session_id)++ records = [+ IntentRecord(+ intent_text=text,+ frequency=sum(data["tool_counts"].values()),+ session_count=len(sessions_by_intent[text]),+ tool_counts=data["tool_counts"],+ error_counts=data["error_counts"],+ )+ for text, data in rollup.items()+ ]+ # Secondary key keeps the cut deterministic when frequencies tie.+ records.sort(key=lambda r: (-r.frequency, r.intent_text))+ kept = records[:top_n]++ stats = CorpusStats(+ total_calls=total_calls,+ attributed_calls=attributed_calls,+ imputed_calls=imputed_calls,+ kept_calls=sum(r.frequency for r in kept),+ )+ return kept, calls_by_session, stats+++# Cluster flows -------------------------------------------------------------def aggregate_journeys_per_cluster(+def compute_cluster_flows(records: list[IntentRecord],labels: np.ndarray,- session_journeys: dict[str, dict[str, Any]],- intent_to_sessions: dict[str, list[str]],+ calls_by_session: dict[str, list[CallRecord]],) -> dict[int, dict[str, Any]]:- """For each cluster id, build a Sankey-shaped journey aggregation.-- Walks each session in each cluster, takes the first ``JOURNEY_DEPTH``- ordered tool calls (padded with ``None`` for shorter sessions), pairs- them with an ``error``/``completed`` outcome, and counts unique paths.- Returns a per-cluster dict with ``paths`` (top N), ``total_sessions``,- and ``leak`` (highest-volume non-completed path).+ """Per-cluster journeys, error switches, self-retries, and session sets.++ A session belongs to every cluster its attributed calls touch; each+ cluster's journey and outcome come from that session's *own* calls for the+ cluster (its C-subsequence), so an error on an unrelated intent in the same+ session cannot mark this cluster's journey as errored. A switch is an+ errored call immediately followed, within the subsequence, by a call to a+ different tool; the same tool again is a self-retry."""- journeys_by_cluster: dict[int, Counter[tuple[tuple[str | None, ...], str]]] = defaultdict(Counter)+ intent_to_cluster = {records[i].intent_text: int(labels[i]) for i in range(len(records))}++ path_counts: dict[int, Counter[tuple[tuple[str | None, ...], str]]] = defaultdict(Counter)+ switch_counts: dict[int, Counter[tuple[str, str]]] = defaultdict(Counter)+ retry_counts: dict[int, Counter[str]] = defaultdict(Counter)+ session_ids: dict[int, set[str]] = defaultdict(set)- for i, record in enumerate(records):- cluster_id = int(labels[i])- for session_id in intent_to_sessions.get(record.intent_text, []):- journey = session_journeys.get(session_id)- if not journey:+ for session_id, calls in calls_by_session.items():+ per_cluster: dict[int, list[CallRecord]] = defaultdict(list)+ for call in calls:+ if call.intent_text is None:continue- raw_sequence = journey["tool_sequence"][:JOURNEY_DEPTH]- padded: list[str | None] = [str(t) for t in raw_sequence] + [None] * (JOURNEY_DEPTH - len(raw_sequence))- outcome = "error" if journey.get("had_error") else "completed"- journeys_by_cluster[cluster_id][(tuple(padded), outcome)] += 1-- result: dict[int, dict[str, Any]] = {}- for cluster_id, path_counts in journeys_by_cluster.items():- ranked = path_counts.most_common()- total_sessions = sum(path_counts.values())- leak_path: dict[str, Any] | None = None- for (steps, outcome), count in ranked:- if outcome != "completed":- leak_path = {"steps": list(steps), "outcome": outcome, "count": count}- break- result[cluster_id] = {- "paths": [+ cluster_id = intent_to_cluster.get(call.intent_text)+ if cluster_id is None:+ continue+ per_cluster[cluster_id].append(call)++ for cluster_id, subsequence in per_cluster.items():+ session_ids[cluster_id].add(session_id)+ steps: list[str | None] = [call.tool for call in subsequence[:JOURNEY_DEPTH]]+ steps += [None] * (JOURNEY_DEPTH - len(steps))+ outcome = "error" if any(call.is_error for call in subsequence) else "completed"+ path_counts[cluster_id][(tuple(steps), outcome)] += 1++ for prev, nxt in zip(subsequence, subsequence[1:]):+ if not prev.is_error:+ continue+ if nxt.tool == prev.tool:+ retry_counts[cluster_id][prev.tool] += 1+ else:+ switch_counts[cluster_id][(prev.tool, nxt.tool)] += 1++ flows: dict[int, dict[str, Any]] = {}+ for cluster_id in session_ids:+ ranked = path_counts[cluster_id].most_common()+ leak = next(+ ({"steps": list(steps), "outcome": outcome, "count": count}- for (steps, outcome), count in ranked[:MAX_JOURNEY_PATHS_PER_CLUSTER]+ for (steps, outcome), count in ranked+ if outcome != "completed"+ ),+ None,+ )+ flows[cluster_id] = {+ "journey": {+ "paths": [+ {"steps": list(steps), "outcome": outcome, "count": count}+ for (steps, outcome), count in ranked[:MAX_JOURNEY_PATHS_PER_CLUSTER]+ ],+ "total_sessions": sum(path_counts[cluster_id].values()),+ "leak": leak,+ },+ "switches": [+ {"from_tool": from_tool, "to_tool": to_tool, "count": count}+ for (from_tool, to_tool), count in switch_counts[cluster_id].most_common(MAX_SWITCHES_PER_CLUSTER)],- "total_sessions": total_sessions,- "leak": leak_path,+ "self_retries": [+ {"tool": tool, "count": count}+ for tool, count in retry_counts[cluster_id].most_common(MAX_SELF_RETRIES_PER_CLUSTER)+ ],+ "session_ids": session_ids[cluster_id],}- return result+ return flows# Embeddings ---------------------------------------------------------------def _content_hash(text: str) -> str:+def _content_hash(text: str, prefix: str = EMBEDDING_PREFIX) -> str:"""SHA-256 of the prefixed text — what we actually embed."""- return hashlib.sha256((EMBEDDING_PREFIX + text).encode("utf-8")).hexdigest()+ return hashlib.sha256((prefix + text).encode("utf-8")).hexdigest()def _encode_embedding(vector: list[float]) -> bytes:@@ -423,6 +661,7 @@ async def _embed_one_with_cache(content_hash: str,semaphore: asyncio.Semaphore,cached: dict[str, np.ndarray],+ prefix: str,) -> np.ndarray | None:"""Return the embedding for ``text``, hitting the cache when possible.@@ -435,9 +674,7 @@ async def _embed_one_with_cache(return hitasync with semaphore:try:- response: EmbeddingResponse = await async_generate_embedding(- team, EMBEDDING_PREFIX + text, model=EMBEDDING_MODEL- )+ response: EmbeddingResponse = await async_generate_embedding(team, prefix + text, model=EMBEDDING_MODEL)except Exception:return Nonetry:@@ -450,8 +687,14 @@ async def _embed_one_with_cache(return np.asarray(response.embedding, dtype=np.float32)-async def embed_intents_async(team: Team, texts: list[str]) -> tuple[np.ndarray, list[int]]:- """Embed a list of intent texts concurrently, with a per-team cache.+async def embed_texts_async(+ team: Team, texts: list[str], prefix: str = EMBEDDING_PREFIX+) -> tuple[np.ndarray, list[int]]:+ """Embed a list of texts concurrently, with a per-team cache.++ ``prefix`` names the embedding kind (intent vs tool description) and is part+ of the cache key, so identical text embedded under two prefixes gets two+ cache rows.Returns (embeddings, valid_indices) where ``valid_indices`` are the indicesinto ``texts`` for which embedding succeeded. Skipped indices have no row@@ -465,13 +708,13 @@ async def embed_intents_async(team: Team, texts: list[str]) -> tuple[np.ndarray,if not texts:return np.zeros((0, 0), dtype=np.float32), []- hashes = [_content_hash(t) for t in texts]+ hashes = [_content_hash(t, prefix) for t in texts]cached = await _load_cached_embeddings(team, hashes, EMBEDDING_MODEL)semaphore = asyncio.Semaphore(EMBED_CONCURRENCY)results = await asyncio.gather(*[- _embed_one_with_cache(team, text, content_hash, semaphore, cached)+ _embed_one_with_cache(team, text, content_hash, semaphore, cached, prefix)for text, content_hash in zip(texts, hashes)])@@ -564,27 +807,253 @@ def _medoid_index(embeddings: np.ndarray, indices: list[int]) -> int:return indices[best_local]+def top_corpus_tools(records: list[IntentRecord], max_tools: int = MAX_TOOLS_IN_SNAPSHOT) -> set[str]:+ """The top ``max_tools`` corpus tools by attributed call volume — the same+ population and cap the tool pivot uses. Everything description-related+ (the ClickHouse aggregation, the embedding fan-out) is bounded to this set."""+ totals: Counter[str] = Counter()+ for record in records:+ for tool, count in record.tool_counts.items():+ totals[tool] += count+ return {tool for tool, _ in sorted(totals.items(), key=lambda item: (-item[1], item[0]))[:max_tools]}+++def compute_description_fit(+ embeddings: np.ndarray,+ labels: np.ndarray,+ description_embeddings: dict[str, np.ndarray],+) -> dict[str, dict[int, float]]:+ """Cosine similarity between each tool's description and each cluster centroid.++ Returns ``{tool: {cluster_id: fit}}``; tools without a description embedding+ are absent. High fit + low capture is the "agents should find this tool for+ this intent but don't" signal.+ """+ if not description_embeddings or len(embeddings) == 0:+ return {}++ centroids: dict[int, np.ndarray] = {}+ for cluster_id in {int(label) for label in labels.tolist()}:+ member_matrix = embeddings[labels == cluster_id]+ centroid = member_matrix.mean(axis=0)+ centroids[cluster_id] = centroid / (np.linalg.norm(centroid) or 1.0)++ fit: dict[str, dict[int, float]] = {}+ for tool, vector in description_embeddings.items():+ unit = np.asarray(vector, dtype=np.float32)+ unit = unit / (np.linalg.norm(unit) or 1.0)+ fit[tool] = {cluster_id: round(float(unit @ centroid), 3) for cluster_id, centroid in centroids.items()}+ return fit+++def compute_tool_pivot(+ clusters: list[dict[str, Any]],+ calls_by_session: dict[str, list[CallRecord]],+ advertised_by_session: dict[str, set[str]],+ tool_descriptions: dict[str, str],+ description_fit: dict[str, dict[int, float]],+ max_tools: int = MAX_TOOLS_IN_SNAPSHOT,+ max_clusters_per_tool: int = MAX_CLUSTERS_PER_TOOL,+ snapshot_cluster_ids: Collection[int] | None = None,+) -> tuple[list[dict[str, Any]], int]:+ """Pivot the built clusters into a per-tool view.++ Per tool: total attributed calls/errors, the clusters it serves (with its+ capture share, rank, and strongest competitor in each), a call-weighted+ contested score, and a discovery rate against the sessions that advertised+ the tool (null below ``MIN_ADVERTISED_SESSIONS`` — not enough signal).+ Returns ``(tools, dropped_count)`` with tools capped at ``max_tools`` by+ call volume.++ Totals cover every cluster in ``clusters``. ``snapshot_cluster_ids``, when+ given, restricts which clusters get a per-cluster *entry*: callers pass the+ ids that survived the snapshot's cluster cap so every ``cluster_id`` in the+ blob still resolves against a cluster the blob carries, while the totals+ keep counting the calls of the clusters the cap dropped. ``n_clusters_served``+ is the pre-cap count, so the UI can say when an entry list is partial.++ Entries deliberately carry no per-cluster constants (label, cluster totals,+ entropy): repeating them per tool x cluster is what turns this pivot into a+ multi-megabyte blob. Clients join on ``cluster_id``.+ """+ per_tool_clusters: dict[str, list[dict[str, Any]]] = defaultdict(list)+ call_totals: Counter[str] = Counter()+ error_totals: Counter[str] = Counter()+ clusters_served: Counter[str] = Counter()+ weighted_entropy: dict[str, float] = defaultdict(float)++ for cluster in clusters:+ distribution = cluster["tool_distribution"]+ in_snapshot = snapshot_cluster_ids is None or cluster["id"] in snapshot_cluster_ids+ for rank, entry in enumerate(distribution, start=1):+ tool = entry["tool"]+ call_totals[tool] += entry["count"]+ error_totals[tool] += entry["errors"]+ clusters_served[tool] += 1+ weighted_entropy[tool] += entry["count"] * cluster["routing_entropy"]+ if not in_snapshot:+ continue+ competitor = next(+ ({"tool": other["tool"], "pct": other["pct"]} for other in distribution if other["tool"] != tool),+ None,+ )+ per_tool_clusters[tool].append(+ {+ "cluster_id": cluster["id"],+ "calls": entry["count"],+ "capture_pct": entry["pct"],+ "rank": rank,+ "description_fit": description_fit.get(tool, {}).get(cluster["id"]),+ "top_competitor": competitor,+ }+ )++ # Attributed calls only, matching call_count and the session sets+ # compute_tool_overlaps builds. Counting unattributed calls here would let a+ # tool post a healthy discovery rate off calls that never entered a cluster.+ sessions_calling: dict[str, set[str]] = defaultdict(set)+ for session_id, calls in calls_by_session.items():+ for call in calls:+ if call.intent_text is None:+ continue+ sessions_calling[call.tool].add(session_id)++ # Inverted once rather than per tool: the tool set is sender-controlled and uncapped+ # at this point, so scanning every advertised session for each of them is O(tools x+ # sessions) on values a caller chooses.+ # Only corpus sessions count. A session the row cap dropped contributes nothing to+ # the numerator, so leaving it in the denominator biases discovery rates down+ # precisely when truncation fires.+ advertised_sessions_by_tool: dict[str, set[str]] = defaultdict(set)+ for session_id, advertised in advertised_by_session.items():+ if session_id not in calls_by_session:+ continue+ for advertised_tool in advertised:+ advertised_sessions_by_tool[advertised_tool].add(session_id)++ tools: list[dict[str, Any]] = []+ for tool, call_count in call_totals.items():+ advertised_sessions = advertised_sessions_by_tool[tool]+ called_when_advertised = len(advertised_sessions & sessions_calling[tool])+ discovery_rate_pct = (+ round(100.0 * called_when_advertised / len(advertised_sessions), 1)+ if len(advertised_sessions) >= MIN_ADVERTISED_SESSIONS+ else None+ )+ tools.append(+ {+ "tool": tool,+ "call_count": call_count,+ "error_count": error_totals[tool],+ "session_count": len(sessions_calling[tool]),+ "contested_score": round(weighted_entropy[tool] / call_count, 3) if call_count else None,+ "n_clusters_served": clusters_served[tool],+ "advertised_sessions": len(advertised_sessions),+ "called_when_advertised": called_when_advertised,+ "discovery_rate_pct": discovery_rate_pct,+ "description": tool_descriptions.get(tool),+ "clusters": sorted(per_tool_clusters[tool], key=lambda entry: entry["calls"], reverse=True)[+ :max_clusters_per_tool+ ],+ }+ )++ tools.sort(key=lambda t: (-t["call_count"], t["tool"]))+ dropped = max(0, len(tools) - max_tools)+ return tools[:max_tools], dropped+++def compute_tool_overlaps(+ clusters: list[dict[str, Any]],+ calls_by_session: dict[str, list[CallRecord]],+ max_pairs: int = MAX_CONFUSION_PAIRS,+ max_tools_per_cluster: int = MAX_OVERLAP_TOOLS_PER_CLUSTER,+) -> tuple[list[dict[str, Any]], int]:+ """Tool pairs competing for the same intents.++ ``contested_calls`` is the sum over clusters of ``min(calls_a, calls_b)`` —+ the volume both tools could plausibly have taken. The session counts split+ substitution from cooperation: pairs used together in the same sessions are+ workflows, pairs whose sessions pick one or the other are confusion.+ Returns ``(pairs, dropped_count)`` capped at ``max_pairs``; only each+ cluster's top ``max_tools_per_cluster`` tools enter pair expansion.+ """+ contested: dict[tuple[str, str], int] = defaultdict(int)+ top_cluster: dict[tuple[str, str], tuple[int, int]] = {}++ for cluster in clusters:+ # tool_distribution is sorted by count desc, so this keeps the head.+ distribution = cluster["tool_distribution"][:max_tools_per_cluster]+ for i in range(len(distribution)):+ for j in range(i + 1, len(distribution)):+ tool_i, tool_j = str(distribution[i]["tool"]), str(distribution[j]["tool"])+ pair = (tool_i, tool_j) if tool_i <= tool_j else (tool_j, tool_i)+ overlap = min(distribution[i]["count"], distribution[j]["count"])+ if overlap <= 0:+ continue+ contested[pair] += overlap+ best = top_cluster.get(pair)+ if best is None or overlap > best[0]:+ top_cluster[pair] = (overlap, cluster["id"])++ session_tools = {+ session_id: {call.tool for call in calls if call.intent_text is not None}+ for session_id, calls in calls_by_session.items()+ }++ ranked = sorted(contested.items(), key=lambda item: (-item[1], item[0]))+ pairs: list[dict[str, Any]] = []+ for (tool_a, tool_b), contested_calls in ranked[:max_pairs]:+ pairs.append(+ {+ "tool_a": tool_a,+ "tool_b": tool_b,+ "contested_calls": contested_calls,+ "sessions_with_both": sum(1 for tools in session_tools.values() if tool_a in tools and tool_b in tools),+ "sessions_with_either": sum(+ 1 for tools in session_tools.values() if tool_a in tools or tool_b in tools+ ),+ "top_cluster_id": top_cluster[(tool_a, tool_b)][1],+ }+ )+ dropped = max(0, len(ranked) - max_pairs)+ return pairs, dropped+++def _pct(numerator: float, denominator: float) -> float:+ return round(100.0 * numerator / denominator, 1) if denominator else 0.0++def build_snapshot(records: list[IntentRecord],labels: np.ndarray,embeddings: np.ndarray,distance_threshold: float = DEFAULT_DISTANCE_THRESHOLD,- journeys_by_cluster: dict[int, dict[str, Any]] | None = None,+ calls_by_session: dict[str, list[CallRecord]] | None = None,+ advertised_by_session: dict[str, set[str]] | None = None,+ tool_descriptions: dict[str, str] | None = None,+ description_embeddings: dict[str, np.ndarray] | None = None,+ corpus_stats: CorpusStats | None = None,+ window_stats: WindowStats | None = None,) -> dict[str, Any]:"""Aggregate clusters into the JSONB snapshot shape persisted in Postgres.``records``, ``labels``, and ``embeddings`` must be aligned: position ``i``in each refers to the same intent.- ``journeys_by_cluster`` is the output of ``aggregate_journeys_per_cluster``- keyed by cluster id. Optional; clusters without an entry get a null journey.+ All keyword arguments are optional so degraded runs still snapshot: without+ ``calls_by_session`` there are no journeys, switches, pivot, or overlaps;+ without descriptions there is no fit. Missing coverage inputs serialize as+ null meta fields, never as fabricated zeros."""if len(records) == 0:- return _empty_snapshot(distance_threshold, n_intents=0)+ return empty_snapshot(distance_threshold, n_intents=0, corpus_stats=corpus_stats, window_stats=window_stats)assert len(records) == len(labels) == len(embeddings), (f"records ({len(records)}), labels ({len(labels)}), and embeddings ({len(embeddings)}) must be the same length")+ flows = compute_cluster_flows(records, labels, calls_by_session or {})+clusters_by_label: dict[int, list[int]] = defaultdict(list)for i, label in enumerate(labels.tolist()):clusters_by_label[int(label)].append(i)@@ -604,9 +1073,9 @@ def build_snapshot({"tool": tool,"count": count,- "pct": round(100.0 * count / total_calls, 1) if total_calls else 0.0,+ "pct": _pct(count, total_calls),"errors": int(error_counts.get(tool, 0)),- "error_rate_pct": round(100.0 * error_counts.get(tool, 0) / count, 1) if count else 0.0,+ "error_rate_pct": _pct(error_counts.get(tool, 0), count),}for tool, count in tool_counts.most_common()]@@ -617,19 +1086,28 @@ def build_snapshot(for record in sorted(members, key=lambda r: r.frequency, reverse=True)[:MAX_SAMPLE_INTENTS_PER_CLUSTER]]+ flow = flows.get(cluster_id, {})+ # Distinct sessions when call data is available; the per-record sum+ # double-counts sessions whose calls span several member intents.+ session_count = (+ len(flow["session_ids"]) if "session_ids" in flow else int(sum(r.session_count for r in members))+ )+clusters.append({"id": cluster_id,"label": records[medoid_pos].intent_text,"intent_count": len(members),- "session_count": int(sum(r.session_count for r in members)),+ "session_count": session_count,"call_count": total_calls,"error_count": int(sum(error_counts.values())),- "error_rate_pct": round(100.0 * sum(error_counts.values()) / total_calls, 1) if total_calls else 0.0,+ "error_rate_pct": _pct(sum(error_counts.values()), total_calls),"tool_distribution": tool_distribution,"sample_intents": sample_intents,"routing_entropy": round(_routing_entropy(tool_counts), 3),- "journey": (journeys_by_cluster or {}).get(cluster_id),+ "journey": flow.get("journey"),+ "switches": flow.get("switches", []),+ "self_retries": flow.get("self_retries", []),})@@ -639,26 +1117,110 @@ def build_snapshot(# 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:]+ snapshot_clusters = clusters[:MAX_SNAPSHOT_CLUSTERS]++ fit = compute_description_fit(embeddings, labels, description_embeddings or {})+ if calls_by_session is not None:+ # The pivot totals read every cluster so the cap above never quietly+ # removes calls from a tool's counts, while its entries stay restricted+ # to the clusters this blob carries. Overlaps stay on the persisted+ # clusters because ``top_cluster_id`` has to resolve within the blob.+ tools, dropped_tools = compute_tool_pivot(+ clusters,+ calls_by_session,+ advertised_by_session or {},+ tool_descriptions or {},+ fit,+ snapshot_cluster_ids={cluster["id"] for cluster in snapshot_clusters},+ )+ tool_overlaps, dropped_pairs = compute_tool_overlaps(snapshot_clusters, calls_by_session)+ else:+ tools, dropped_tools, tool_overlaps, dropped_pairs = [], 0, [], 0++ described_tools = sum(1 for tool in tools if tool["description"])+ meta: dict[str, Any] = {+ "distance_threshold": distance_threshold,+ "embedding_model": EMBEDDING_MODEL,+ "n_intents": len(records),+ "n_clusters": n_clusters_total,+ "corpus": "per_call",+ "sampled_sessions": len(calls_by_session) if calls_by_session is not None else None,+ "window_sessions": window_stats.sessions if window_stats else None,+ "session_coverage_pct": (+ _pct(len(calls_by_session), window_stats.sessions)+ if calls_by_session is not None and window_stats+ else None+ ),+ "intent_coverage_pct": _pct(window_stats.calls_with_intent, window_stats.total_calls) if window_stats else None,+ "imputed_call_pct": _pct(corpus_stats.imputed_calls, corpus_stats.attributed_calls) if corpus_stats else None,+ "unattributed_call_pct": (+ _pct(corpus_stats.total_calls - corpus_stats.attributed_calls, corpus_stats.total_calls)+ if corpus_stats+ else None+ ),+ "corpus_call_coverage_pct": (+ _pct(corpus_stats.kept_calls, corpus_stats.attributed_calls) if corpus_stats else None+ ),+ "advertisement_coverage_pct": (+ _pct(len(set(advertised_by_session) & set(calls_by_session)), len(calls_by_session))+ if calls_by_session and advertised_by_session is not None+ else None+ ),+ "n_tools": len(tools),+ "dropped_tools": dropped_tools,+ "dropped_overlap_pairs": dropped_pairs,+ "description_coverage_pct": _pct(described_tools, len(tools)) if tools else None,+ }return {- "clusters": clusters,- "computed_with": {- "distance_threshold": distance_threshold,- "embedding_model": EMBEDDING_MODEL,- "n_intents": len(records),- "n_clusters": n_clusters_total,- },+ "version": SNAPSHOT_VERSION,+ "clusters": snapshot_clusters,+ "tools": tools,+ "tool_overlaps": tool_overlaps,+ "computed_with": meta,}-def _empty_snapshot(distance_threshold: float, n_intents: int) -> dict[str, Any]:+def empty_snapshot(+ distance_threshold: float,+ n_intents: int,+ corpus_stats: CorpusStats | None = None,+ window_stats: WindowStats | None = None,+) -> dict[str, Any]:+ """The no-clusters blob, keeping whatever coverage the run did establish.++ A window full of traffic that carried no attributable intent must not read+ the same as a window with no traffic at all: "0% of calls carried an intent"+ is the actionable message, all-null is a dead end.+ """return {+ "version": SNAPSHOT_VERSION,"clusters": [],+ "tools": [],+ "tool_overlaps": [],"computed_with": {"distance_threshold": distance_threshold,"embedding_model": EMBEDDING_MODEL,"n_intents": n_intents,"n_clusters": 0,+ "corpus": "per_call",+ "sampled_sessions": None,+ "window_sessions": window_stats.sessions if window_stats else None,+ "session_coverage_pct": None,+ "intent_coverage_pct": (+ _pct(window_stats.calls_with_intent, window_stats.total_calls) if window_stats else None+ ),+ "imputed_call_pct": None,+ "unattributed_call_pct": (+ _pct(corpus_stats.total_calls - corpus_stats.attributed_calls, corpus_stats.total_calls)+ if corpus_stats+ else None+ ),+ "corpus_call_coverage_pct": None,+ "advertisement_coverage_pct": None,+ "n_tools": 0,+ "dropped_tools": 0,+ "dropped_overlap_pairs": 0,+ "description_coverage_pct": None,},}diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.pyindex e670a01c7f8d..9e15fed7fde2 100644--- a/products/mcp_analytics/backend/logic.py+++ b/products/mcp_analytics/backend/logic.py@@ -703,9 +703,45 @@ def _parse_int(value: str | int | None) -> int | None:return None-def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:+def _scope_blob_to_tool(+ clusters_raw: list[Any], tools_raw: list[Any], overlaps_raw: list[Any], tool: str+) -> tuple[list[Any], list[Any], list[Any]]:+ """Narrow a snapshot blob to one tool's slice of it.++ Keeps the tool's pivot entry, the clusters that entry references, the clusters+ whose error switches name the tool (the detail panel lists those), and the+ overlap pairs it belongs to. Everything else is other tools' data that a+ single-tool view would download and discard.+ """+ tools = [item for item in tools_raw if isinstance(item, dict) and item.get("tool") == tool]+ wanted_cluster_ids = {+ entry.get("cluster_id") for item in tools for entry in item.get("clusters", []) if isinstance(entry, dict)+ }+ clusters = [+ item+ for item in clusters_raw+ if isinstance(item, dict)+ and (+ item.get("id") in wanted_cluster_ids+ or any(+ isinstance(switch, dict) and tool in (switch.get("from_tool"), switch.get("to_tool"))+ for switch in item.get("switches", [])+ )+ )+ ]+ overlaps = [+ item for item in overlaps_raw if isinstance(item, dict) and tool in (item.get("tool_a"), item.get("tool_b"))+ ]+ return clusters, tools, overlaps+++def get_intent_cluster_snapshot(team: Team, tool: str | None = None) -> contracts.IntentClusterSnapshot:"""Return the current intent cluster snapshot for a team.+ ``tool`` narrows clusters, pivot, and overlaps to that tool's slice; the+ coverage meta stays whole-snapshot because it describes the run. Surfaces+ that render one tool use it so they don't download the full blob.+When no snapshot exists yet, returns an empty IDLE one so callers canrender the "compute" CTA without distinguishing "missing" from "empty".@@ -737,6 +773,8 @@ def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:blob = snapshot.clusters or {}clusters_raw = blob.get("clusters", []) if isinstance(blob, dict) else []+ tools_raw = blob.get("tools", []) if isinstance(blob, dict) else []+ overlaps_raw = blob.get("tool_overlaps", []) 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@@ -749,6 +787,9 @@ def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:reverse=True,)[:MAX_SNAPSHOT_CLUSTERS]+ if tool is not None:+ clusters_raw, tools_raw, overlaps_raw = _scope_blob_to_tool(clusters_raw, tools_raw, overlaps_raw, tool)+return contracts.IntentClusterSnapshot(status=snapshot.status,error_message=snapshot.error_message,@@ -756,9 +797,21 @@ def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:last_computed_by_email=snapshot.last_computed_by.email if snapshot.last_computed_by else "",clusters=[_to_cluster_dto(item) for item in clusters_raw if isinstance(item, dict)],computed_with=_to_meta_dto(meta_raw) if isinstance(meta_raw, dict) else None,+ tools=[_to_tool_pivot_dto(item) for item in tools_raw if isinstance(item, dict)],+ tool_overlaps=[_to_overlap_dto(item) for item in overlaps_raw if isinstance(item, dict)],)+# bool is a subclass of int, so the isinstance check has to exclude it explicitly —+# otherwise a boolean in the blob silently coerces to 1.0 / 1 instead of being rejected.+def _opt_float(value: Any) -> float | None:+ return float(value) if isinstance(value, int | float) and not isinstance(value, bool) else None+++def _opt_int(value: Any) -> int | None:+ return int(value) if isinstance(value, int | float) and not isinstance(value, bool) else None++def _to_cluster_dto(item: dict[str, Any]) -> contracts.IntentCluster:journey_raw = item.get("journey")return contracts.IntentCluster(@@ -783,6 +836,67 @@ def _to_cluster_dto(item: dict[str, Any]) -> contracts.IntentCluster:],sample_intents=[str(s) for s in item.get("sample_intents", []) if isinstance(s, str)],journey=_to_journey_dto(journey_raw) if isinstance(journey_raw, dict) else None,+ switches=[+ contracts.ClusterSwitch(+ from_tool=str(entry.get("from_tool", "")),+ to_tool=str(entry.get("to_tool", "")),+ count=int(entry.get("count", 0)),+ )+ for entry in item.get("switches", [])+ if isinstance(entry, dict)+ ],+ self_retries=[+ contracts.ClusterSelfRetry(tool=str(entry.get("tool", "")), count=int(entry.get("count", 0)))+ for entry in item.get("self_retries", [])+ if isinstance(entry, dict)+ ],+ )+++def _to_tool_pivot_dto(item: dict[str, Any]) -> contracts.ToolPivot:+ return contracts.ToolPivot(+ tool=str(item.get("tool", "")),+ call_count=int(item.get("call_count", 0)),+ error_count=int(item.get("error_count", 0)),+ session_count=int(item.get("session_count", 0)),+ contested_score=_opt_float(item.get("contested_score")),+ advertised_sessions=int(item.get("advertised_sessions", 0)),+ called_when_advertised=int(item.get("called_when_advertised", 0)),+ discovery_rate_pct=_opt_float(item.get("discovery_rate_pct")),+ description=str(item["description"]) if item.get("description") else None,+ # Pre-cap count, so the UI never presents a capped entry list as the whole+ # story. Blobs written before it existed fall back to the entries they have.+ n_clusters_served=_opt_int(item.get("n_clusters_served")) or len(item.get("clusters", [])),+ clusters=[_to_tool_pivot_cluster_dto(entry) for entry in item.get("clusters", []) if isinstance(entry, dict)],+ )+++def _to_tool_pivot_cluster_dto(entry: dict[str, Any]) -> contracts.ToolPivotClusterEntry:+ competitor_raw = entry.get("top_competitor")+ return contracts.ToolPivotClusterEntry(+ cluster_id=int(entry.get("cluster_id", 0)),+ calls=int(entry.get("calls", 0)),+ capture_pct=float(entry.get("capture_pct", 0.0)),+ rank=int(entry.get("rank", 0)),+ description_fit=_opt_float(entry.get("description_fit")),+ top_competitor=(+ contracts.ToolPivotCompetitor(+ tool=str(competitor_raw.get("tool", "")), pct=float(competitor_raw.get("pct", 0.0))+ )+ if isinstance(competitor_raw, dict)+ else None+ ),+ )+++def _to_overlap_dto(item: dict[str, Any]) -> contracts.ToolOverlap:+ return contracts.ToolOverlap(+ tool_a=str(item.get("tool_a", "")),+ tool_b=str(item.get("tool_b", "")),+ contested_calls=int(item.get("contested_calls", 0)),+ sessions_with_both=int(item.get("sessions_with_both", 0)),+ sessions_with_either=int(item.get("sessions_with_either", 0)),+ top_cluster_id=int(item.get("top_cluster_id", 0)),)@@ -808,6 +922,19 @@ def _to_meta_dto(meta: dict[str, Any]) -> contracts.IntentClusterSnapshotMeta:embedding_model=str(meta.get("embedding_model", "")),n_intents=int(meta.get("n_intents", 0)),n_clusters=int(meta.get("n_clusters", 0)),+ corpus=str(meta["corpus"]) if meta.get("corpus") else None,+ sampled_sessions=_opt_int(meta.get("sampled_sessions")),+ window_sessions=_opt_int(meta.get("window_sessions")),+ session_coverage_pct=_opt_float(meta.get("session_coverage_pct")),+ intent_coverage_pct=_opt_float(meta.get("intent_coverage_pct")),+ imputed_call_pct=_opt_float(meta.get("imputed_call_pct")),+ unattributed_call_pct=_opt_float(meta.get("unattributed_call_pct")),+ corpus_call_coverage_pct=_opt_float(meta.get("corpus_call_coverage_pct")),+ advertisement_coverage_pct=_opt_float(meta.get("advertisement_coverage_pct")),+ n_tools=_opt_int(meta.get("n_tools")),+ dropped_tools=_opt_int(meta.get("dropped_tools")),+ dropped_overlap_pairs=_opt_int(meta.get("dropped_overlap_pairs")),+ description_coverage_pct=_opt_float(meta.get("description_coverage_pct")),)diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.pyindex c621d6e9a816..3b30b318dafb 100644--- a/products/mcp_analytics/backend/presentation/serializers.py+++ b/products/mcp_analytics/backend/presentation/serializers.py@@ -479,6 +479,115 @@ class MCPIntentClusterJourneySerializer(serializers.Serializer):)+class MCPClusterSwitchSerializer(serializers.Serializer):+ from_tool = serializers.CharField(read_only=True, help_text="Tool whose errored call the agent abandoned.")+ to_tool = serializers.CharField(read_only=True, help_text="Different tool the agent tried immediately after.")+ count = serializers.IntegerField(+ read_only=True, help_text="How many times this exact error-then-switch happened within the cluster."+ )+++class MCPClusterSelfRetrySerializer(serializers.Serializer):+ tool = serializers.CharField(read_only=True, help_text="Tool the agent retried immediately after its own error.")+ count = serializers.IntegerField(read_only=True, help_text="Number of immediate same-tool retries after an error.")+++class MCPToolPivotCompetitorSerializer(serializers.Serializer):+ tool = serializers.CharField(+ read_only=True, help_text="The other tool with the largest share of this cluster's calls."+ )+ pct = serializers.FloatField(read_only=True, help_text="That competitor's share of the cluster's calls, 0-100.")+++class MCPToolPivotClusterEntrySerializer(serializers.Serializer):+ cluster_id = serializers.IntegerField(+ read_only=True,+ help_text="Cluster this entry refers to, within the snapshot. The cluster's own label, totals, and entropy live on that cluster — join on this id rather than expecting them here.",+ )+ calls = serializers.IntegerField(read_only=True, help_text="Calls routed to this tool for this intent cluster.")+ capture_pct = serializers.FloatField(+ read_only=True,+ help_text="Share of the cluster's calls this tool captured, 0-100. Low capture on a well-fitting description suggests agents are not finding the tool for this intent.",+ )+ rank = serializers.IntegerField(+ read_only=True,+ help_text="This tool's position in the cluster's tool distribution; 1 is the cluster's top tool.",+ )+ description_fit = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Cosine similarity between the tool's description embedding and the cluster centroid, -1 to 1. Null when no description has been captured for the tool.",+ )+ top_competitor = MCPToolPivotCompetitorSerializer(+ read_only=True,+ allow_null=True,+ help_text="The strongest other tool in this cluster. Null when this tool is the only one.",+ )+++class MCPToolPivotSerializer(serializers.Serializer):+ tool = serializers.CharField(read_only=True, help_text="Effective MCP tool name.")+ call_count = serializers.IntegerField(+ read_only=True,+ help_text="Intent-attributed calls to this tool across the sampled corpus, counting every cluster the run produced — including clusters the snapshot's cluster cap left out.",+ )+ error_count = serializers.IntegerField(read_only=True, help_text="Errored attributed calls across the corpus.")+ session_count = serializers.IntegerField(+ read_only=True,+ help_text="Sampled sessions with at least one intent-attributed call to this tool. Same population as call_count.",+ )+ contested_score = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Call-weighted mean routing entropy of the clusters this tool serves, 0-1. High means the tool's intents are regularly split with other tools. Null when the tool has no attributed calls.",+ )+ advertised_sessions = serializers.IntegerField(+ read_only=True,+ help_text="Sampled sessions whose tools-list catalog included this tool. Only sessions with an observed $mcp_tools_list event count.",+ )+ called_when_advertised = serializers.IntegerField(+ read_only=True, help_text="Of the advertised sessions, how many actually called the tool."+ )+ discovery_rate_pct = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="called_when_advertised / advertised_sessions as a percentage. Null when the tool was advertised in fewer than 5 sampled sessions, which is not enough signal to compute a rate.",+ )+ description = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="Latest description observed for the tool (clipped to 512 characters). Null when calls never carried one.",+ )+ n_clusters_served = serializers.IntegerField(+ read_only=True,+ help_text="How many intent clusters this tool serves in total, before the per-tool entry cap. Compare against len(clusters) to tell whether the entry list below is complete.",+ )+ clusters = MCPToolPivotClusterEntrySerializer(+ many=True,+ read_only=True,+ help_text="Intent clusters this tool serves, by call volume desc, capped at 20 and limited to clusters the snapshot carries. Use n_clusters_served for the true count.",+ )+++class MCPToolOverlapSerializer(serializers.Serializer):+ tool_a = serializers.CharField(read_only=True, help_text="First tool of the pair (lexicographic order).")+ tool_b = serializers.CharField(read_only=True, help_text="Second tool of the pair.")+ contested_calls = serializers.IntegerField(+ read_only=True,+ help_text="Sum over shared clusters of the smaller tool's calls: the volume both tools plausibly compete for.",+ )+ sessions_with_both = serializers.IntegerField(+ read_only=True,+ help_text="Sampled sessions that called both tools. High relative to sessions_with_either suggests the pair is a workflow, not confusion.",+ )+ sessions_with_either = serializers.IntegerField(+ read_only=True, help_text="Sampled sessions that called at least one of the pair."+ )+ top_cluster_id = serializers.IntegerField(+ read_only=True, help_text="The cluster contributing the most contested calls for this pair."+ )++class MCPIntentClusterSerializer(serializers.Serializer):id = serializers.IntegerField(read_only=True, help_text="Stable cluster identifier within this snapshot.")label = serializers.CharField( # type: ignore[assignment]@@ -523,6 +632,16 @@ class MCPIntentClusterSerializer(serializers.Serializer):"four ordered tool calls plus a completed/error outcome. Null when journey data is unavailable."),)+ switches = MCPClusterSwitchSerializer(+ many=True,+ read_only=True,+ help_text="Errored call immediately followed by a different tool for the same intent: the strongest evidence agents mix the tools up. Top 10 by count.",+ )+ self_retries = MCPClusterSelfRetrySerializer(+ many=True,+ read_only=True,+ help_text="Errored call immediately retried with the same tool. Top 5 by count.",+ )class MCPIntentClusterSnapshotMetaSerializer(serializers.Serializer):@@ -534,6 +653,63 @@ class MCPIntentClusterSnapshotMetaSerializer(serializers.Serializer):read_only=True, help_text="Number of distinct intents that fed into the clustering run.")n_clusters = serializers.IntegerField(read_only=True, help_text="Number of clusters produced by the run.")+ corpus = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="Corpus granularity. 'per_call' when each call was attributed to its own intent; null on snapshots computed before the per-call pipeline.",+ )+ sampled_sessions = serializers.IntegerField(+ read_only=True, allow_null=True, help_text="Sessions sampled into the corpus. Null on pre-v2 snapshots."+ )+ window_sessions = serializers.IntegerField(+ read_only=True,+ allow_null=True,+ help_text="Total sessions with tool calls in the lookback window (unsampled).",+ )+ session_coverage_pct = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="sampled_sessions / window_sessions as a percentage: how much of the window the corpus represents.",+ )+ intent_coverage_pct = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Share of the window's calls that carried an $mcp_intent. Low coverage makes capture rates less reliable.",+ )+ imputed_call_pct = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Share of attributed calls whose intent was carried forward from an earlier call in the session rather than stated on the call itself.",+ )+ unattributed_call_pct = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Share of sampled calls with no attributable intent (before the session's first stated intent). These calls are excluded from clusters.",+ )+ corpus_call_coverage_pct = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Share of attributed calls whose intent made the top-N cut that feeds clustering.",+ )+ advertisement_coverage_pct = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Share of sampled sessions with an observed $mcp_tools_list catalog. Discovery rates only draw on those sessions.",+ )+ n_tools = serializers.IntegerField(read_only=True, allow_null=True, help_text="Tools included in the tool pivot.")+ dropped_tools = serializers.IntegerField(+ read_only=True,+ allow_null=True,+ help_text="Tools dropped from the pivot by the volume cap. Zero means the pivot is complete.",+ )+ dropped_overlap_pairs = serializers.IntegerField(+ read_only=True, allow_null=True, help_text="Overlap pairs dropped by the pair cap."+ )+ description_coverage_pct = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Share of pivot tools with a captured description. Description fit is only available for those.",+ )class MCPIntentClusterSnapshotSerializer(serializers.Serializer):@@ -554,10 +730,20 @@ class MCPIntentClusterSnapshotSerializer(serializers.Serializer):help_text="Email of the user who triggered the latest recompute, empty for system-triggered runs.",)clusters = MCPIntentClusterSerializer(many=True, read_only=True, help_text="All clusters in the snapshot.")+ tools = MCPToolPivotSerializer(+ many=True,+ read_only=True,+ help_text="Tool-centric pivot of the clusters: per tool, the intents it serves, capture per cluster, contested score, discovery rate, and description fit. Empty on snapshots computed before the per-call pipeline; recompute to populate.",+ )+ tool_overlaps = MCPToolOverlapSerializer(+ many=True,+ read_only=True,+ help_text="Tool pairs competing for the same intent clusters, by contested call volume desc, capped at 50.",+ )computed_with = MCPIntentClusterSnapshotMetaSerializer(read_only=True,allow_null=True,- help_text="Settings used to produce the snapshot. Null when no snapshot has been computed yet.",+ help_text="Settings and coverage of the snapshot's corpus. Null when no snapshot has been computed yet.",)diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.pyindex 576054cf4616..ceba9ff7f11d 100644--- a/products/mcp_analytics/backend/presentation/views.py+++ b/products/mcp_analytics/backend/presentation/views.py@@ -317,10 +317,24 @@ class MCPIntentClusterViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"Return the most recent intent cluster snapshot for the current project. ""Returns an empty IDLE snapshot when no clustering run has happened yet."),+ parameters=[+ OpenApiParameter(+ name="tool",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description=(+ "Narrow the response to one tool: its pivot entry, the clusters it serves or switches "+ "with, and the overlap pairs it belongs to. Coverage meta stays whole-snapshot. Use "+ "this for single-tool views so they don't download every cluster and pivot to render "+ "one row. An unknown tool returns empty sections, not a 404."+ ),+ )+ ],responses={200: MCPIntentClusterSnapshotSerializer},)def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:- snapshot = api.get_intent_cluster_snapshot(self.team)+ snapshot = api.get_intent_cluster_snapshot(self.team, tool=request.query_params.get("tool") or None)serializer = self.get_serializer(snapshot)return Response(serializer.data)diff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.pyindex 096996085d2d..9c61e9899001 100644--- a/products/mcp_analytics/backend/tests/test_intent_clustering.py+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py@@ -27,22 +27,44 @@ from products.mcp_analytics.backend import intent_clusteringfrom products.mcp_analytics.backend.constants import MAX_SNAPSHOT_CLUSTERSfrom products.mcp_analytics.backend.intent_clustering import (DEFAULT_DISTANCE_THRESHOLD,+ DESCRIPTION_EMBEDDING_PREFIX,EMBEDDING_MODEL,+ JOURNEY_DEPTH,+ MAX_ADVERTISED_LIST_EVENTS_PER_SESSION,+ MAX_ADVERTISED_TOOLS_PER_SESSION,+ MAX_DESCRIPTION_LENGTH,MAX_INTENT_TEXT_LENGTH,+ MAX_TOOL_NAME_LENGTH,+ MAX_TOOLS_IN_SNAPSHOT,+ MAX_TOOLS_PER_ADVERTISED_LIST,+ MIN_ADVERTISED_SESSIONS,NO_INTENT_RECORDED_FALLBACK,+ SNAPSHOT_VERSION,+ CallRecord,+ CorpusStats,IntentRecord,+ WindowStats,_content_hash,_decode_embedding,_encode_embedding,_medoid_index,_routing_entropy,+ build_call_corpus,build_snapshot,cluster_embeddings,- embed_intents_async,- fetch_intent_corpus,- fetch_session_journeys,+ compute_cluster_flows,+ compute_description_fit,+ compute_tool_overlaps,+ compute_tool_pivot,+ embed_texts_async,+ fetch_advertised_tools,+ fetch_session_calls,+ fetch_tool_descriptions,+ fetch_window_stats,+ sample_corpus_sessions,+ top_corpus_tools,)-from products.mcp_analytics.backend.models import MCPIntentEmbeddingCache, MCPSession+from products.mcp_analytics.backend.models import MCPIntentEmbeddingCachefrom products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin# Helpers@@ -260,23 +282,586 @@ class TestBuildSnapshot:# 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+ def test_pivot_totals_survive_the_cluster_cap(self) -> None:+ # The cluster cap runs before the pivot, so without care every per-tool+ # total silently loses the calls of the clusters it dropped.+ 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, calls_by_session={})++ tool = snapshot["tools"][0]+ assert tool["call_count"] == sum(range(1, n_total + 1))+ assert tool["n_clusters_served"] == n_total+ assert {entry["cluster_id"] for entry in tool["clusters"]} <= {c["id"] for c in snapshot["clusters"]}++ def test_pivot_tools_match_the_population_descriptions_are_fetched_for(self) -> None:+ # Descriptions are only fetched for top_corpus_tools(records). If the pivot+ # ranks a different population, a tool that made the pivot never has a+ # description fetched and renders as "none captured" for no visible reason.+ n_tools = MAX_TOOLS_IN_SNAPSHOT + 5+ records = [+ IntentRecord(intent_text=f"intent_{i}", frequency=i + 1, tool_counts={f"tool_{i:04d}": i + 1})+ for i in range(n_tools)+ ]+ labels = np.arange(n_tools, dtype=np.int64)+ embeddings = np.array([_unit([1.0, float(i + 1)]) for i in range(n_tools)], dtype=np.float32)++ snapshot = build_snapshot(records, labels, embeddings, calls_by_session={})++ assert {tool["tool"] for tool in snapshot["tools"]} == top_corpus_tools(records)++ def test_empty_corpus_keeps_the_coverage_it_does_know(self) -> None:+ # A run that saw traffic but could attribute none of it must not look+ # identical to a run that saw nothing at all — "0% of calls carried an+ # intent" is the message that tells the owner what to fix.+ snapshot = build_snapshot(+ [],+ np.array([], dtype=np.int64),+ np.zeros((0, 4), dtype=np.float32),+ window_stats=WindowStats(total_calls=400, calls_with_intent=0, sessions=25),+ )++ assert snapshot["clusters"] == []+ assert snapshot["computed_with"]["window_sessions"] == 25+ assert snapshot["computed_with"]["intent_coverage_pct"] == pytest.approx(0.0)++ def test_snapshot_is_versioned_and_v1_style_invocation_degrades(self) -> None:+ records = [IntentRecord(intent_text="a", frequency=1, tool_counts={"tool_a": 1})]+ snapshot = build_snapshot(records, np.array([0], dtype=np.int64), np.array([_unit([1.0, 0.0])]))++ assert snapshot["version"] == SNAPSHOT_VERSION+ assert snapshot["tools"] == []+ assert snapshot["tool_overlaps"] == []+ assert snapshot["clusters"][0]["switches"] == []+ assert snapshot["clusters"][0]["self_retries"] == []+ assert snapshot["computed_with"]["sampled_sessions"] is None+ assert snapshot["computed_with"]["intent_coverage_pct"] is None++ def test_full_v2_snapshot_carries_pivot_overlaps_and_meta(self) -> None:+ records = [+ IntentRecord(intent_text="check flags", frequency=3, session_count=1, tool_counts={"flag_get": 3}),+ IntentRecord(+ intent_text="run a query",+ frequency=3,+ session_count=1,+ tool_counts={"sql_run": 2, "flag_get": 1},+ error_counts={"sql_run": 1},+ ),+ ]+ labels = np.array([0, 1], dtype=np.int64)+ embeddings = np.array([_unit([1.0, 0.0]), _unit([0.0, 1.0])], dtype=np.float32)+ calls_by_session = {+ "s1": [+ CallRecord(session_id="s1", tool="flag_get", intent_text="check flags", is_error=False),+ CallRecord(session_id="s1", tool="flag_get", intent_text="check flags", is_error=False),+ CallRecord(session_id="s1", tool="flag_get", intent_text="check flags", is_error=False),+ CallRecord(session_id="s1", tool="sql_run", intent_text="run a query", is_error=True),+ CallRecord(session_id="s1", tool="sql_run", intent_text="run a query", is_error=False),+ CallRecord(session_id="s1", tool="flag_get", intent_text="run a query", is_error=False),+ ],+ }+ snapshot = build_snapshot(+ records,+ labels,+ embeddings,+ calls_by_session=calls_by_session,+ advertised_by_session={"s1": {"flag_get", "sql_run"}},+ tool_descriptions={"flag_get": "Reads a feature flag"},+ description_embeddings={"flag_get": _unit([1.0, 0.0])},+ corpus_stats=CorpusStats(total_calls=8, attributed_calls=6, imputed_calls=1, kept_calls=6),+ window_stats=WindowStats(total_calls=100, calls_with_intent=90, sessions=50),+ )++ assert snapshot["version"] == SNAPSHOT_VERSION+ tools = {t["tool"]: t for t in snapshot["tools"]}+ assert set(tools) == {"flag_get", "sql_run"}+ assert tools["flag_get"]["call_count"] == 4+ assert tools["flag_get"]["description"] == "Reads a feature flag"+ assert tools["sql_run"]["description"] is None+ assert len(snapshot["tool_overlaps"]) == 1++ meta = snapshot["computed_with"]+ assert meta["corpus"] == "per_call"+ assert meta["sampled_sessions"] == 1+ assert meta["window_sessions"] == 50+ assert meta["session_coverage_pct"] == pytest.approx(2.0)+ assert meta["intent_coverage_pct"] == pytest.approx(90.0)+ assert meta["imputed_call_pct"] == pytest.approx(100.0 * 1 / 6, abs=0.1)+ assert meta["unattributed_call_pct"] == pytest.approx(25.0)+ assert meta["corpus_call_coverage_pct"] == pytest.approx(100.0)+ assert meta["advertisement_coverage_pct"] == pytest.approx(100.0)+ assert meta["n_tools"] == 2+ assert meta["description_coverage_pct"] == pytest.approx(50.0)+++# build_call_corpus --------------------------------------------------------+++class TestBuildCallCorpus:+ def test_attributes_tool_counts_to_the_calls_own_intent(self) -> None:+ # The v1 pipeline smeared the session's first intent across every call in+ # the session, so tools used for a later intent were mis-credited.+ rows = [+ ("s1", "flag_get", "check flags", False),+ ("s1", "sql_run", "run a query", False),+ ]++ records, _, _ = build_call_corpus(rows)++ by_text = {r.intent_text: r for r in records}+ assert by_text["check flags"].tool_counts == {"flag_get": 1}+ assert by_text["run a query"].tool_counts == {"sql_run": 1}++ def test_locf_carries_intent_within_but_not_across_sessions(self) -> None:+ rows = [+ ("s1", "flag_get", "check flags", False),+ ("s1", "sql_run", "", False),+ ("s2", "insight_get", "", False),+ ("s2", "sql_run", "run a query", False),+ ]++ records, calls_by_session, stats = build_call_corpus(rows)++ by_text = {r.intent_text: r for r in records}+ assert by_text["check flags"].tool_counts == {"flag_get": 1, "sql_run": 1}+ assert by_text["run a query"].tool_counts == {"sql_run": 1}+ assert [c.intent_text for c in calls_by_session["s2"]] == [None, "run a query"]+ assert stats.total_calls == 4+ assert stats.attributed_calls == 3+ assert stats.imputed_calls == 1++ def test_error_counts_and_distinct_session_count(self) -> None:+ rows = [+ ("s1", "flag_get", "check flags", True),+ ("s2", "flag_get", "check flags", False),+ ("s2", "flag_get", "check flags", True),+ ]++ records, _, _ = build_call_corpus(rows)++ assert len(records) == 1+ assert records[0].frequency == 3+ assert records[0].session_count == 2+ assert records[0].error_counts == {"flag_get": 2}++ @parameterized.expand(+ [+ ("placeholder", NO_INTENT_RECORDED_FALLBACK),+ ("padded_placeholder", f" {NO_INTENT_RECORDED_FALLBACK} "),+ ("empty", ""),+ ("whitespace", " "),+ ]+ )+ def test_non_intents_are_treated_as_absent(self, _name: str, raw_intent: str) -> None:+ records, calls_by_session, stats = build_call_corpus([("s1", "flag_get", raw_intent, False)])++ assert records == []+ assert calls_by_session["s1"][0].intent_text is None+ assert stats.attributed_calls == 0++ def test_oversized_intent_is_clipped_before_grouping(self) -> None:+ records, _, _ = build_call_corpus([("s1", "flag_get", "x" * (MAX_INTENT_TEXT_LENGTH * 3), False)])++ assert [len(r.intent_text) for r in records] == [MAX_INTENT_TEXT_LENGTH]++ def test_top_n_keeps_highest_call_count_intents_and_reports_kept_calls(self) -> None:+ rows = [("s1", "t", "popular", False)] * 3 + [("s2", "t", "middling", False)] * 2 + [("s3", "t", "rare", False)]-# fetch_intent_corpus -----------------------------------------------------+ records, _, stats = build_call_corpus(rows, top_n=2)+ assert [r.intent_text for r in records] == ["popular", "middling"]+ assert stats.attributed_calls == 6+ assert stats.kept_calls == 5-class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, BaseTest):- """End-to-end: posthog_mcp_session in Postgres + $mcp_tool_call in ClickHouse."""- def _seed_session(+# compute_cluster_flows ----------------------------------------------------+++def _record(intent: str) -> IntentRecord:+ return IntentRecord(intent_text=intent, frequency=1, tool_counts={})+++class TestComputeClusterFlows:+ def test_journeys_use_only_the_clusters_own_calls(self) -> None:+ # One session serving two intents: each cluster's journey and outcome must+ # come from its own calls, not the whole session (an error on the other+ # intent's call must not mark this cluster's journey as errored).+ records = [_record("intent a"), _record("intent b")]+ labels = np.array([0, 1], dtype=np.int64)+ calls_by_session = {+ "s1": [+ CallRecord(session_id="s1", tool="tool_x", intent_text="intent a", is_error=False),+ CallRecord(session_id="s1", tool="tool_z", intent_text="intent b", is_error=True),+ CallRecord(session_id="s1", tool="tool_y", intent_text="intent a", is_error=False),+ ],+ }++ flows = compute_cluster_flows(records, labels, calls_by_session)++ journey_a = flows[0]["journey"]+ assert journey_a["paths"] == [{"steps": ["tool_x", "tool_y", None, None], "outcome": "completed", "count": 1}]+ journey_b = flows[1]["journey"]+ assert journey_b["paths"][0]["outcome"] == "error"+ assert flows[0]["session_ids"] == {"s1"}++ def test_journey_clips_to_depth(self) -> None:+ records = [_record("intent a")]+ labels = np.array([0], dtype=np.int64)+ calls = [+ CallRecord(session_id="s1", tool=f"tool_{i}", intent_text="intent a", is_error=False)+ for i in range(JOURNEY_DEPTH + 2)+ ]++ flows = compute_cluster_flows(records, labels, {"s1": calls})++ steps = flows[0]["journey"]["paths"][0]["steps"]+ assert len(steps) == JOURNEY_DEPTH+ assert steps == [f"tool_{i}" for i in range(JOURNEY_DEPTH)]++ @parameterized.expand(+ [+ (+ "error_then_other_tool_is_a_switch",+ True,+ "tool_b",+ [{"from_tool": "tool_a", "to_tool": "tool_b", "count": 1}],+ [],+ ),+ ("error_then_same_tool_is_a_retry", True, "tool_a", [], [{"tool": "tool_a", "count": 1}]),+ ("success_then_other_tool_is_neither", False, "tool_b", [], []),+ ]+ )+ def test_switch_and_retry_extraction(self,- session_id: str,- intent: str,- *,- created_at_offset: timedelta = timedelta(minutes=-55),+ _name: str,+ first_errors: bool,+ second_tool: str,+ expected_switches: list[dict],+ expected_retries: list[dict],) -> None:- session = MCPSession.objects.create(team=self.team, session_id=session_id, intent=intent)- # created_at is auto_now_add, so override it directly to position the row in the lookback window.- MCPSession.objects.filter(pk=session.pk).update(created_at=datetime.now(tz=UTC) + created_at_offset)+ records = [_record("intent a")]+ labels = np.array([0], dtype=np.int64)+ calls_by_session = {+ "s1": [+ CallRecord(session_id="s1", tool="tool_a", intent_text="intent a", is_error=first_errors),+ CallRecord(session_id="s1", tool=second_tool, intent_text="intent a", is_error=False),+ ],+ }++ flows = compute_cluster_flows(records, labels, calls_by_session)++ assert flows[0]["switches"] == expected_switches+ assert flows[0]["self_retries"] == expected_retries++ def test_unattributed_calls_are_invisible_to_flows(self) -> None:+ records = [_record("intent a")]+ labels = np.array([0], dtype=np.int64)+ calls_by_session = {+ "s1": [+ CallRecord(session_id="s1", tool="tool_a", intent_text="intent a", is_error=True),+ CallRecord(session_id="s1", tool="stray", intent_text=None, is_error=False),+ CallRecord(session_id="s1", tool="tool_b", intent_text="intent a", is_error=False),+ ],+ }++ flows = compute_cluster_flows(records, labels, calls_by_session)++ assert flows[0]["journey"]["paths"][0]["steps"] == ["tool_a", "tool_b", None, None]+ assert flows[0]["switches"] == [{"from_tool": "tool_a", "to_tool": "tool_b", "count": 1}]+++# top_corpus_tools ----------------------------------------------------------+++class TestTopCorpusTools:+ def test_caps_to_the_highest_volume_corpus_tools(self) -> None:+ # A caller emitting unique tool names per call could otherwise turn one+ # recompute into one embedding request per unique name.+ records = [+ IntentRecord(intent_text="a", frequency=5, tool_counts={"busy": 5}),+ IntentRecord(intent_text="b", frequency=3, tool_counts={"quiet": 1, "busy": 2}),+ ]++ assert top_corpus_tools(records, max_tools=1) == {"busy"}+++# compute_description_fit --------------------------------------------------+++class TestComputeDescriptionFit:+ def test_fit_is_cosine_to_cluster_centroid(self) -> None:+ embeddings = np.array([_unit([1.0, 0.0]), _unit([1.0, 0.0]), _unit([0.0, 1.0])], dtype=np.float32)+ labels = np.array([0, 0, 1], dtype=np.int64)++ fit = compute_description_fit(embeddings, labels, {"tool_a": _unit([1.0, 0.0])})++ assert fit["tool_a"][0] == pytest.approx(1.0)+ assert fit["tool_a"][1] == pytest.approx(0.0, abs=1e-6)++ def test_tools_without_embeddings_are_absent(self) -> None:+ embeddings = np.array([_unit([1.0, 0.0])], dtype=np.float32)+ labels = np.array([0], dtype=np.int64)++ assert compute_description_fit(embeddings, labels, {}) == {}+++# compute_tool_pivot -------------------------------------------------------+++def _cluster_fixture() -> list[dict[str, Any]]:+ return [+ {+ "id": 0,+ "label": "check flags",+ "call_count": 10,+ "routing_entropy": 0.5,+ "tool_distribution": [+ {"tool": "t1", "count": 6, "pct": 60.0, "errors": 1, "error_rate_pct": 16.7},+ {"tool": "t2", "count": 4, "pct": 40.0, "errors": 0, "error_rate_pct": 0.0},+ ],+ },+ {+ "id": 1,+ "label": "run queries",+ "call_count": 4,+ "routing_entropy": 0.0,+ "tool_distribution": [+ {"tool": "t1", "count": 4, "pct": 100.0, "errors": 0, "error_rate_pct": 0.0},+ ],+ },+ ]+++def _attributed_call(session: str, tool: str, intent: str = "check flags") -> CallRecord:+ return CallRecord(session_id=session, tool=tool, intent_text=intent, is_error=False)+++class TestComputeToolPivot:+ def test_capture_rank_competitor_and_contested_score(self) -> None:+ pivot, dropped = compute_tool_pivot(+ _cluster_fixture(),+ calls_by_session={"s1": [_attributed_call("s1", "t1"), _attributed_call("s1", "t2")]},+ advertised_by_session={},+ tool_descriptions={},+ description_fit={},+ )++ assert dropped == 0+ by_tool = {t["tool"]: t for t in pivot}+ t1 = by_tool["t1"]+ assert t1["call_count"] == 10+ assert t1["error_count"] == 1+ # Call-weighted mean of cluster entropies: (6*0.5 + 4*0.0) / 10.+ assert t1["contested_score"] == pytest.approx(0.3)+ assert [c["cluster_id"] for c in t1["clusters"]] == [0, 1]+ first = t1["clusters"][0]+ assert first["capture_pct"] == pytest.approx(60.0)+ assert first["rank"] == 1+ assert first["top_competitor"] == {"tool": "t2", "pct": 40.0}+ t2 = by_tool["t2"]+ assert t2["clusters"][0]["rank"] == 2+ assert t2["clusters"][0]["top_competitor"] == {"tool": "t1", "pct": 60.0}+ assert by_tool["t1"]["clusters"][1]["top_competitor"] is None++ def test_advertised_denominator_ignores_sessions_absent_from_the_corpus(self) -> None:+ # The row cap can drop whole sessions after their ids were sampled. Leaving+ # them in the advertised denominator with nothing in the numerator drags+ # every discovery rate down exactly when the truncation warning fires.+ advertised = {f"s{i}": {"t1"} for i in range(MIN_ADVERTISED_SESSIONS + 3)}+ calls = {f"s{i}": [_attributed_call(f"s{i}", "t1")] for i in range(MIN_ADVERTISED_SESSIONS)}++ pivot, _ = compute_tool_pivot(+ _cluster_fixture(),+ calls_by_session=calls,+ advertised_by_session=advertised,+ tool_descriptions={},+ description_fit={},+ )++ t1 = {t["tool"]: t for t in pivot}["t1"]+ assert t1["advertised_sessions"] == MIN_ADVERTISED_SESSIONS+ assert t1["discovery_rate_pct"] == pytest.approx(100.0)++ def test_discovery_rate_needs_the_advertised_floor(self) -> None:+ # t1 advertised in 5 corpus sessions and called in 3 of them: measurable at+ # exactly the floor. t2 advertised in only 1 session: below the floor, so+ # null. The other two sessions are in the corpus for a different tool.+ advertised = {f"s{i}": {"t1"} for i in range(MIN_ADVERTISED_SESSIONS)}+ advertised["s0"] = {"t1", "t2"}+ calls = {f"s{i}": [_attributed_call(f"s{i}", "t1")] for i in range(3)}+ calls |= {f"s{i}": [_attributed_call(f"s{i}", "t2")] for i in (3, 4)}++ pivot, _ = compute_tool_pivot(+ _cluster_fixture(),+ calls_by_session=calls,+ advertised_by_session=advertised,+ tool_descriptions={},+ description_fit={},+ )++ by_tool = {t["tool"]: t for t in pivot}+ assert by_tool["t1"]["advertised_sessions"] == 5+ assert by_tool["t1"]["called_when_advertised"] == 3+ assert by_tool["t1"]["discovery_rate_pct"] == pytest.approx(60.0)+ assert by_tool["t2"]["advertised_sessions"] == 1+ assert by_tool["t2"]["discovery_rate_pct"] is None++ def test_description_and_fit_are_attached(self) -> None:+ pivot, _ = compute_tool_pivot(+ _cluster_fixture(),+ calls_by_session={},+ advertised_by_session={},+ tool_descriptions={"t1": "Reads a flag"},+ description_fit={"t1": {0: 0.42}},+ )++ by_tool = {t["tool"]: t for t in pivot}+ assert by_tool["t1"]["description"] == "Reads a flag"+ assert by_tool["t1"]["clusters"][0]["description_fit"] == pytest.approx(0.42)+ assert by_tool["t1"]["clusters"][1]["description_fit"] is None+ assert by_tool["t2"]["description"] is None++ def test_max_tools_cap_drops_lowest_volume_tools(self) -> None:+ pivot, dropped = compute_tool_pivot(+ _cluster_fixture(),+ calls_by_session={},+ advertised_by_session={},+ tool_descriptions={},+ description_fit={},+ max_tools=1,+ )++ assert [t["tool"] for t in pivot] == ["t1"]+ assert dropped == 1++ def test_entries_carry_no_per_cluster_constants(self) -> None:+ # label, cluster call count, and entropy are constants of the cluster, and+ # a tool x cluster entry repeats them once per tool. At the caps this file+ # sets that is megabytes of duplicated intent text in one JSONB blob, which+ # is exactly what the cluster cap exists to prevent. The client joins the+ # cluster's own fields on cluster_id instead.+ pivot, _ = compute_tool_pivot(+ _cluster_fixture(),+ calls_by_session={},+ advertised_by_session={},+ tool_descriptions={},+ description_fit={},+ )++ assert set(pivot[0]["clusters"][0]) == {+ "cluster_id",+ "calls",+ "capture_pct",+ "rank",+ "description_fit",+ "top_competitor",+ }++ def test_totals_span_every_cluster_while_entries_stay_joinable(self) -> None:+ # Clusters past the snapshot cap are dropped from the blob, but their calls+ # still happened: per-tool totals must count them, or the pivot silently+ # under-reports. Entries stay restricted to persisted clusters so every+ # cluster_id still resolves client-side.+ pivot, _ = compute_tool_pivot(+ _cluster_fixture(),+ calls_by_session={},+ advertised_by_session={},+ tool_descriptions={},+ description_fit={},+ snapshot_cluster_ids={0},+ )++ t1 = {t["tool"]: t for t in pivot}["t1"]+ assert t1["call_count"] == 10+ assert t1["n_clusters_served"] == 2+ assert [entry["cluster_id"] for entry in t1["clusters"]] == [0]++ def test_session_count_counts_only_intent_attributed_calls(self) -> None:+ # call_count is attributed calls only, and compute_tool_overlaps builds its+ # session sets the same way. Counting unattributed calls here lets a tool+ # show a healthy discovery rate driven entirely by calls that never entered+ # a cluster.+ calls = {+ "s-attributed": [_attributed_call("s-attributed", "t1")],+ "s-unattributed": [CallRecord(session_id="s-unattributed", tool="t1", intent_text=None, is_error=False)],+ }++ pivot, _ = compute_tool_pivot(+ _cluster_fixture(),+ calls_by_session=calls,+ advertised_by_session={"s-attributed": {"t1"}, "s-unattributed": {"t1"}},+ tool_descriptions={},+ description_fit={},+ )++ t1 = {t["tool"]: t for t in pivot}["t1"]+ assert t1["session_count"] == 1+ assert t1["called_when_advertised"] == 1+++# compute_tool_overlaps ----------------------------------------------------+++class TestComputeToolOverlaps:+ def test_contested_calls_sum_min_across_clusters(self) -> None:+ calls_by_session = {+ "s1": [_attributed_call("s1", "t1"), _attributed_call("s1", "t2")],+ "s2": [_attributed_call("s2", "t1")],+ }++ overlaps, dropped = compute_tool_overlaps(_cluster_fixture(), calls_by_session)++ assert dropped == 0+ assert overlaps == [+ {+ "tool_a": "t1",+ "tool_b": "t2",+ "contested_calls": 4,+ "sessions_with_both": 1,+ "sessions_with_either": 2,+ "top_cluster_id": 0,+ }+ ]++ def test_max_pairs_cap_reports_dropped(self) -> None:+ overlaps, dropped = compute_tool_overlaps(_cluster_fixture(), {}, max_pairs=0)++ assert overlaps == []+ assert dropped == 1++ def test_pair_expansion_only_considers_each_clusters_head(self) -> None:+ # An event sender controls tool names, so one intent can carry thousands of+ # distinct tools; expanding all O(n^2) pairs before ranking would blow up+ # the recompute. Only the head of each distribution enters pair expansion.+ distribution: list[dict[str, Any]] = [+ {"tool": f"t{i}", "count": 100 - i, "pct": 1.0, "errors": 0, "error_rate_pct": 0.0} for i in range(4)+ ]+ clusters = [+ {+ "id": 0,+ "label": "x",+ "call_count": sum(entry["count"] for entry in distribution),+ "routing_entropy": 0.5,+ "tool_distribution": distribution,+ }+ ]++ overlaps, _ = compute_tool_overlaps(clusters, {}, max_tools_per_cluster=2)++ assert [(o["tool_a"], o["tool_b"]) for o in overlaps] == [("t0", "t1")]+++# Corpus queries (ClickHouse-backed) ---------------------------------------+++class TestCorpusQueries(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, BaseTest):+ """End-to-end coverage of the ClickHouse corpus queries behind the v2 pipeline."""def _seed_tool_call(self,@@ -285,6 +870,8 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixiis_error: bool = False,intent: str | None = None,timestamp: datetime | None = None,+ exec_tool_name: str | None = None,+ description: str | None = None,) -> None:properties: dict[str, Any] = {"$session_id": session_id,@@ -293,6 +880,10 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixi}if intent is not None:properties["$mcp_intent"] = intent+ if exec_tool_name is not None:+ properties["$mcp_exec_tool_call_name"] = exec_tool_name+ if description is not None:+ properties["$mcp_tool_description"] = description_create_event(event_uuid=uuid.uuid4(),event="$mcp_tool_call",@@ -302,179 +893,165 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixiproperties=properties,)- def test_returns_empty_when_no_sessions(self) -> None:- records, intent_by_session = fetch_intent_corpus(self.team)- assert records == []- assert intent_by_session == {}-- def test_aggregates_tool_calls_across_sessions_with_matching_intent(self) -> None:- self._seed_session("session-a", "check feature flag rollout")- self._seed_session("session-b", "check feature flag rollout")- self._seed_tool_call("session-a", "feature_flag_get")- self._seed_tool_call("session-a", "feature_flag_get")- self._seed_tool_call("session-b", "feature_flag_get", is_error=True)- self._seed_tool_call("session-b", "query_run")- flush_persons_and_events()-- records, intent_by_session = fetch_intent_corpus(self.team)-- assert len(records) == 1- assert records[0].intent_text == "check feature flag rollout"- assert records[0].tool_counts == {"feature_flag_get": 3, "query_run": 1}- assert records[0].error_counts == {"feature_flag_get": 1}- assert records[0].frequency == 4- assert intent_by_session == {- "session-a": "check feature flag rollout",- "session-b": "check feature flag rollout",- }-- def test_keeps_intents_without_tool_calls_as_zero_call_records(self) -> None:- # A session was logged but no events flowed through yet — we should- # still surface the intent so the UI can show "no calls yet".- self._seed_session("session-quiet", "quiet intent with no events")-- records, _ = fetch_intent_corpus(self.team)-- assert len(records) == 1- assert records[0].intent_text == "quiet intent with no events"- assert records[0].tool_counts == {}- assert records[0].frequency == 1-- def test_lookback_days_excludes_sessions_outside_the_window(self) -> None:- # In-window session (intent generated ~55 min ago).- self._seed_session("recent", "recent intent")- # Out-of-window session (intent generated 10 days ago, beyond the 7-day default).- self._seed_session("old", "old intent", created_at_offset=timedelta(days=-10))+ def _seed_tools_list(self, session_id: str, tool_names: list[str]) -> None:+ _create_event(+ event_uuid=uuid.uuid4(),+ event="$mcp_tools_list",+ team=self.team,+ distinct_id="seed",+ timestamp=datetime.now(tz=UTC) - timedelta(hours=1),+ properties={"$session_id": session_id, "$mcp_listed_tool_names": tool_names},+ )- records, intent_by_session = fetch_intent_corpus(self.team)+ def test_sample_returns_only_sessions_that_recorded_an_intent(self) -> None:+ self._seed_tool_call("session-a", "execute_sql", intent="find slow queries")+ self._seed_tool_call("session-quiet", "execute_sql")+ # Sessionless intent events must not enter the corpus.+ self._seed_tool_call("", "execute_sql", intent="orphan intent")+ flush_persons_and_events()- assert {r.intent_text for r in records} == {"recent intent"}- assert intent_by_session == {"recent": "recent intent"}+ assert sample_corpus_sessions(self.team) == ["session-a"]@parameterized.expand([("default_7_excludes_old", 7, []),- ("override_30_includes_old", 30, ["old intent"]),+ ("override_30_includes_old", 30, ["session-old"]),])- def test_lookback_days_argument_is_respected(- self, _name: str, lookback_days: int, expected_intents: list[str]- ) -> None:- # Intent generated 10 days ago: excluded at 7 days, included at 30.- self._seed_session("old", "old intent", created_at_offset=timedelta(days=-10))-- records, _ = fetch_intent_corpus(self.team, lookback_days=lookback_days)+ def test_sample_respects_lookback_window(self, _name: str, lookback_days: int, expected: list[str]) -> None:+ self._seed_tool_call(+ "session-old",+ "execute_sql",+ intent="old event intent",+ timestamp=datetime.now(tz=UTC) - timedelta(days=10),+ )+ flush_persons_and_events()- assert [r.intent_text for r in records] == expected_intents+ assert sample_corpus_sessions(self.team, lookback_days=lookback_days) == expected- def test_builds_corpus_from_event_intents_without_session_rows(self) -> None:- # Two intents in one session: the chronologically first one represents it.+ def test_session_calls_are_ordered_and_use_the_effective_tool_name(self) -> None:+ base = datetime.now(tz=UTC) - timedelta(hours=2)self._seed_tool_call(- "session-a",- "execute_sql",- intent="find slow queries",- timestamp=datetime.now(tz=UTC) - timedelta(hours=2),+ "session-a", "exec", intent="find slow queries", timestamp=base, exec_tool_name="execute_sql")- self._seed_tool_call("session-a", "query_trends", intent="chart the slow queries")- # Calls without an intent still count toward the session's tool stats.- self._seed_tool_call("session-a", "insight_create")- self._seed_tool_call("session-b", "feature_flag_get", intent="check flag rollout", is_error=True)- # Sessionless intent events must not enter the corpus.- self._seed_tool_call("", "execute_sql", intent="orphan intent")+ self._seed_tool_call("session-a", "query_trends", timestamp=base + timedelta(minutes=1), is_error=True)+ self._seed_tool_call("session-b", "feature_flag_get", intent="check flags")flush_persons_and_events()- records, intent_by_session = fetch_intent_corpus(self.team)+ rows = fetch_session_calls(self.team, ["session-a", "session-b"])- assert intent_by_session == {- "session-a": "find slow queries",- "session-b": "check flag rollout",- }- by_text = {r.intent_text: r for r in records}- assert by_text["find slow queries"].tool_counts == {- "execute_sql": 1,- "query_trends": 1,- "insight_create": 1,- }- assert by_text["check flag rollout"].error_counts == {"feature_flag_get": 1}+ by_session: dict[str, list] = {}+ for row in rows:+ by_session.setdefault(row[0], []).append(row)+ assert [(r[1], r[2], r[3]) for r in by_session["session-a"]] == [+ ("execute_sql", "find slow queries", False),+ ("query_trends", "", True),+ ]+ assert [(r[1], r[2], r[3]) for r in by_session["session-b"]] == [("feature_flag_get", "check flags", False)]++ def test_oversized_sender_strings_are_clipped_at_the_sql_boundary(self) -> None:+ # A sender with the capture token controls these strings; without the SQL+ # clip a recompute materializes up to 50k full-size values in worker memory.+ long_tool = "t" * (MAX_TOOL_NAME_LENGTH + 50)+ long_intent = "i" * (MAX_INTENT_TEXT_LENGTH + 50)+ self._seed_tool_call("session-a", long_tool, intent=long_intent)+ self._seed_tools_list("session-a", [long_tool])+ flush_persons_and_events()- def test_llm_summary_overrides_event_intent(self) -> None:- self._seed_tool_call("session-a", "execute_sql", intent="raw first intent")+ rows = fetch_session_calls(self.team, ["session-a"])+ advertised = fetch_advertised_tools(self.team, ["session-a"])++ assert rows[0][1] == long_tool[:MAX_TOOL_NAME_LENGTH]+ assert rows[0][2] == long_intent[:MAX_INTENT_TEXT_LENGTH]+ # Discovery matching depends on the calls and advertised-catalog queries+ # clipping tool names identically.+ assert advertised["session-a"] == {rows[0][1]}++ def test_advertised_tools_union_across_tools_list_events(self) -> None:+ self._seed_tools_list("session-a", ["exec", "render-ui"])+ self._seed_tools_list("session-a", ["exec", "query_trends"])+ self._seed_tools_list("session-other", ["exec"])flush_persons_and_events()- self._seed_session("session-a", "Condensed LLM summary of the session")- records, intent_by_session = fetch_intent_corpus(self.team)+ advertised = fetch_advertised_tools(self.team, ["session-a", "session-no-list"])- assert intent_by_session == {"session-a": "Condensed LLM summary of the session"}- assert [r.intent_text for r in records] == ["Condensed LLM summary of the session"]+ assert advertised == {"session-a": {"exec", "render-ui", "query_trends"}}- def test_oversized_event_intent_is_clipped(self) -> None:- # Agents control the intent text — an unbounded value would flow into- # embedding requests and the snapshot blob.- self._seed_tool_call("session-big", "execute_sql", intent="x" * (MAX_INTENT_TEXT_LENGTH * 5))+ def test_advertised_catalog_is_bounded_per_list_and_per_session(self) -> None:+ # Both the array and the number of tools-list events are sender-controlled, and the+ # union aggregates both — without the SQL bounds one session can make the+ # advertised-catalog aggregation arbitrarily large in ClickHouse memory.+ oversized = [f"tool-{i}" for i in range(MAX_TOOLS_PER_ADVERTISED_LIST + 50)]+ self._seed_tools_list("session-wide", oversized)+ for i in range(MAX_ADVERTISED_LIST_EVENTS_PER_SESSION + 5):+ self._seed_tools_list("session-chatty", [f"chatty-{i}"])flush_persons_and_events()- records, intent_by_session = fetch_intent_corpus(self.team)+ # A third session pushes the distinct union past the per-session bound with+ # events that each stay under the per-event and per-session-event caps.+ for i in range(3):+ self._seed_tools_list("session-union", [f"union-{i}-{j}" for j in range(400)])+ flush_persons_and_events()- assert intent_by_session == {"session-big": "x" * MAX_INTENT_TEXT_LENGTH}- assert [len(r.intent_text) for r in records] == [MAX_INTENT_TEXT_LENGTH]+ advertised = fetch_advertised_tools(self.team, ["session-wide", "session-chatty", "session-union"])- @parameterized.expand(- [- ("default_7_excludes_old", 7, {}),- ("override_30_includes_old", 30, {"session-old": "old event intent"}),- ]- )- def test_event_intents_respect_lookback_window(- self, _name: str, lookback_days: int, expected: dict[str, str]- ) -> None:- self._seed_tool_call(- "session-old",- "execute_sql",- intent="old event intent",- timestamp=datetime.now(tz=UTC) - timedelta(days=10),- )+ assert len(advertised["session-wide"]) == MAX_TOOLS_PER_ADVERTISED_LIST+ assert len(advertised["session-chatty"]) <= MAX_ADVERTISED_LIST_EVENTS_PER_SESSION+ assert len(advertised["session-union"]) == MAX_ADVERTISED_TOOLS_PER_SESSION++ def test_window_stats_count_calls_intents_and_sessions(self) -> None:+ self._seed_tool_call("session-a", "execute_sql", intent="find slow queries")+ self._seed_tool_call("session-a", "query_trends")+ self._seed_tool_call("session-b", "feature_flag_get")+ # The corpus query requires a tool name, so nameless calls must stay out of+ # these denominators too — intent_coverage_pct is read against the corpus.+ self._seed_tool_call("session-a", "")+ self._seed_tool_call("session-nameless", "")flush_persons_and_events()- _, intent_by_session = fetch_intent_corpus(self.team, lookback_days=lookback_days)+ stats = fetch_window_stats(self.team)- assert intent_by_session == expected+ assert stats == WindowStats(total_calls=3, calls_with_intent=1, sessions=2)- @parameterized.expand(- [- ("raw", NO_INTENT_RECORDED_FALLBACK),- ("padded_whitespace", f" {NO_INTENT_RECORDED_FALLBACK} "),- ]- )- def test_summariser_fallback_intent_is_excluded(self, _name: str, placeholder_text: str) -> None:- # Session whose intent column holds the summariser's "nothing here"- # placeholder — must be excluded so it doesn't form its own cluster.- # Whitespace variants must also be excluded after .strip().- self._seed_session("placeholder", placeholder_text)- self._seed_session("real", "look up feature flag rollout")+ def test_tool_descriptions_take_the_latest_and_clip(self) -> None:+ base = datetime.now(tz=UTC) - timedelta(hours=3)+ self._seed_tool_call("s1", "execute_sql", description="old description", timestamp=base)+ self._seed_tool_call(+ "s1",+ "execute_sql",+ description="new " + "x" * MAX_DESCRIPTION_LENGTH,+ timestamp=base + timedelta(minutes=5),+ )+ self._seed_tool_call("s1", "query_trends", timestamp=base)+ flush_persons_and_events()- records, intent_by_session = fetch_intent_corpus(self.team)+ descriptions = fetch_tool_descriptions(self.team, ["execute_sql"])- assert [r.intent_text for r in records] == ["look up feature flag rollout"]- assert intent_by_session == {"real": "look up feature flag rollout"}+ # query_trends has calls in the window but is outside the requested set, so+ # it never enters the aggregation; execute_sql resolves to its newest text.+ assert set(descriptions) == {"execute_sql"}+ assert descriptions["execute_sql"].startswith("new ")+ assert len(descriptions["execute_sql"]) == MAX_DESCRIPTION_LENGTH+ assert fetch_tool_descriptions(self.team, []) == {}- def test_tool_stats_and_journeys_are_not_truncated_at_the_default_hogql_limit(self) -> None:+ def test_corpus_queries_are_not_truncated_at_the_default_hogql_limit(self) -> None:# execute_hogql_query injects LIMIT 100 into any query without an explicit- # LIMIT. The per-session tool-stats and journey queries return one-plus rows- # per corpus session, so a corpus above 100 sessions silently lost tool- # counts and journeys for everything past the first 100 rows.+ # LIMIT; every corpus query returns one-plus rows per sampled session, so a+ # corpus above 100 sessions would silently lose calls and advertisements.n_sessions = DEFAULT_RETURNED_ROWS + 20for i in range(n_sessions):self._seed_tool_call(f"session-{i}", "execute_sql", intent=f"unique intent {i}")+ self._seed_tools_list(f"session-{i}", ["execute_sql"])flush_persons_and_events()- records, intent_by_session = fetch_intent_corpus(self.team)+ session_ids = sample_corpus_sessions(self.team)+ assert len(session_ids) == n_sessions- assert len(intent_by_session) == n_sessions- assert len(records) == n_sessions- assert all(r.tool_counts == {"execute_sql": 1} for r in records)+ rows = fetch_session_calls(self.team, session_ids)+ assert len(rows) == n_sessions- journeys = fetch_session_journeys(self.team, list(intent_by_session.keys()))- assert len(journeys) == n_sessions+ advertised = fetch_advertised_tools(self.team, session_ids)+ assert len(advertised) == n_sessions# Embedding helpers -----------------------------------------------------@@ -486,6 +1063,11 @@ class TestEmbeddingHelpers:assert _content_hash("hello") != _content_hash("ello")assert _content_hash("hello") == _content_hash("hello") # stable+ def test_content_hash_separates_embedding_kinds(self) -> None:+ # Intent and description embeddings share one cache table; identical text+ # under different prefixes must never collide into one cache row.+ assert _content_hash("hello", prefix=DESCRIPTION_EMBEDDING_PREFIX) != _content_hash("hello")+def test_encode_decode_round_trips_to_float32(self) -> None:vec = [0.1, -0.2, 0.5, 1.5e-3]blob = _encode_embedding(vec)@@ -494,7 +1076,7 @@ class TestEmbeddingHelpers:assert np.allclose(decoded, np.asarray(vec, dtype=np.float32))-# embed_intents_async (cache integration, mocked ORM) ------------------------+# embed_texts_async (cache integration, mocked ORM) ------------------------def _fake_embedding(text: str) -> EmbeddingResponse:@@ -505,7 +1087,7 @@ def _fake_embedding(text: str) -> EmbeddingResponse:return EmbeddingResponse(embedding=vec.tolist(), tokens_used=0, did_truncate=False)-class TestEmbedIntentsAsyncCacheLogic:+class TestEmbedTextsAsyncCacheLogic:"""Cache hit/miss logic with the Postgres helpers mocked.The ORM round-trip is covered separately by ``TestEmbeddingCacheModel``@@ -529,7 +1111,7 @@ class TestEmbedIntentsAsyncCacheLogic:):# A stub with an `id` stands in for Team — the failure-path log# reads team.id, and the cache IO that needs a real team is mocked.- return asyncio.run(embed_intents_async(SimpleNamespace(id=0), texts)) # type: ignore[arg-type]+ return asyncio.run(embed_texts_async(SimpleNamespace(id=0), texts)) # type: ignore[arg-type]def test_first_run_populates_cache(self) -> None:cached: dict[str, np.ndarray] = {}@@ -585,8 +1167,8 @@ class TestEmbedIntentsAsyncCacheLogic:def test_duplicate_texts_each_call_the_worker(self) -> None:# Documents intentional production behaviour: dedup happens upstream- # (fetch_intent_corpus aggregates by distinct intent_text), so- # embed_intents_async itself does not dedup. If the caller passes the+ # (build_call_corpus aggregates by distinct intent_text), so+ # embed_texts_async itself does not dedup. If the caller passes the# same text twice, each call independently misses the in-memory cache# and hits the worker. The unique constraint on the cache row makes# the persist-side race harmless.diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.pyindex bd8dbb51782d..86defd6646f7 100644--- a/products/mcp_analytics/backend/tests/test_presentation.py+++ b/products/mcp_analytics/backend/tests/test_presentation.py@@ -31,6 +31,48 @@ from products.mcp_analytics.backend.presentation.serializers import (from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin+def _cluster_blob(cluster_id: int, label: str, switches: list[dict[str, str]] | None = None) -> dict:+ return {+ "id": cluster_id,+ "label": label,+ "intent_count": 1,+ "call_count": 10,+ "error_count": 0,+ "error_rate_pct": 0.0,+ "routing_entropy": 0.1,+ "tool_distribution": [{"tool": "flag_get", "count": 10, "pct": 100.0, "errors": 0, "error_rate_pct": 0.0}],+ "sample_intents": [label],+ "switches": [{**switch, "count": 2} for switch in switches or []],+ "self_retries": [],+ }+++def _tool_blob(tool: str, cluster_ids: list[int]) -> dict:+ return {+ "tool": tool,+ "call_count": 10,+ "error_count": 0,+ "session_count": 2,+ "contested_score": 0.1,+ "n_clusters_served": len(cluster_ids),+ "advertised_sessions": 0,+ "called_when_advertised": 0,+ "discovery_rate_pct": None,+ "description": None,+ "clusters": [+ {+ "cluster_id": cluster_id,+ "calls": 10,+ "capture_pct": 100.0,+ "rank": 1,+ "description_fit": None,+ "top_competitor": None,+ }+ for cluster_id in cluster_ids+ ],+ }++class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):# The mcp-analytics feature flag is enabled for the whole test by the mixin's setUp.@parameterized.expand(@@ -205,6 +247,172 @@ class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTestassert len(data["clusters"]) == 1assert data["clusters"][0]["label"] == "check feature flag rollout"assert data["computed_with"]["n_clusters"] == 1+ # A pre-v2 blob (no version, no tool sections) must keep rendering:+ # the pivot comes back empty and the coverage meta null, never a 500.+ assert data["tools"] == []+ assert data["tool_overlaps"] == []+ assert data["computed_with"]["sampled_sessions"] is None+ assert data["clusters"][0]["switches"] == []++ def test_intent_clusters_returns_v2_tool_sections(self) -> None:+ MCPIntentClusterSnapshot.objects.create(+ team=self.team,+ status=MCPIntentClusterSnapshot.Status.IDLE,+ clusters={+ "version": 2,+ "clusters": [],+ "tools": [+ {+ "tool": "feature_flag_get",+ "call_count": 12,+ "error_count": 1,+ "session_count": 4,+ "contested_score": 0.31,+ "advertised_sessions": 3,+ "called_when_advertised": 2,+ "discovery_rate_pct": None,+ "description": None,+ "n_clusters_served": 3,+ "clusters": [+ {+ "cluster_id": 0,+ "calls": 12,+ "capture_pct": 85.7,+ "rank": 1,+ "description_fit": None,+ "top_competitor": {"tool": "query_run", "pct": 14.3},+ }+ ],+ }+ ],+ "tool_overlaps": [+ {+ "tool_a": "feature_flag_get",+ "tool_b": "query_run",+ "contested_calls": 2,+ "sessions_with_both": 1,+ "sessions_with_either": 4,+ "top_cluster_id": 0,+ }+ ],+ "computed_with": {+ "distance_threshold": 0.2,+ "embedding_model": "text-embedding-3-small-1536",+ "n_intents": 2,+ "n_clusters": 1,+ "corpus": "per_call",+ "sampled_sessions": 5,+ "window_sessions": 100,+ "session_coverage_pct": 5.0,+ "intent_coverage_pct": 91.4,+ },+ },+ )++ with patch("posthoganalytics.feature_enabled", return_value=True):+ response = self.client.get(f"/api/environments/{self.team.id}/mcp_analytics/intent_clusters/")++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ tool = data["tools"][0]+ assert tool["tool"] == "feature_flag_get"+ assert tool["contested_score"] == 0.31+ # Nulls must survive the DTO + serializer round trip as null, not 0 or "".+ assert tool["discovery_rate_pct"] is None+ assert tool["description"] is None+ assert tool["clusters"][0]["top_competitor"] == {"tool": "query_run", "pct": 14.3}+ assert data["tool_overlaps"][0]["contested_calls"] == 2+ assert data["computed_with"]["sampled_sessions"] == 5+ assert data["computed_with"]["intent_coverage_pct"] == 91.4+ # Coverage fields the blob omitted come back null rather than erroring.+ assert data["computed_with"]["description_coverage_pct"] is None+ # The entry list is capped, so the honest "how many intents does this serve"+ # answer has to come off the pivot, not len(clusters).+ assert tool["n_clusters_served"] == 3+ assert len(tool["clusters"]) == 1++ def test_intent_clusters_can_be_scoped_to_one_tool(self) -> None:+ # The tool detail page renders a single tool's section. Unscoped, it pulls the+ # whole snapshot — every cluster and every other tool's pivot — to do it.+ MCPIntentClusterSnapshot.objects.create(+ team=self.team,+ status=MCPIntentClusterSnapshot.Status.IDLE,+ clusters={+ "version": 2,+ "clusters": [+ _cluster_blob(0, "check feature flag rollout"),+ _cluster_blob(1, "run a query", switches=[{"from_tool": "query_run", "to_tool": "flag_get"}]),+ _cluster_blob(2, "unrelated intent"),+ ],+ "tools": [+ _tool_blob("flag_get", cluster_ids=[0]),+ _tool_blob("query_run", cluster_ids=[1, 2]),+ ],+ "tool_overlaps": [+ {+ "tool_a": "flag_get",+ "tool_b": "query_run",+ "contested_calls": 2,+ "sessions_with_both": 1,+ "sessions_with_either": 4,+ "top_cluster_id": 0,+ },+ {+ "tool_a": "docs_search",+ "tool_b": "query_run",+ "contested_calls": 1,+ "sessions_with_both": 0,+ "sessions_with_either": 2,+ "top_cluster_id": 2,+ },+ ],+ "computed_with": {+ "distance_threshold": 0.2,+ "embedding_model": "text-embedding-3-small-1536",+ "n_intents": 3,+ "n_clusters": 3,+ },+ },+ )++ with patch("posthoganalytics.feature_enabled", return_value=True):+ response = self.client.get(f"/api/environments/{self.team.id}/mcp_analytics/intent_clusters/?tool=flag_get")++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert [tool["tool"] for tool in data["tools"]] == ["flag_get"]+ # Cluster 0 because the pivot references it, cluster 1 because its switch+ # names the tool — the detail panel renders both. Cluster 2 is neither.+ assert sorted(cluster["id"] for cluster in data["clusters"]) == [0, 1]+ assert [(o["tool_a"], o["tool_b"]) for o in data["tool_overlaps"]] == [("flag_get", "query_run")]+ # Coverage meta stays whole-snapshot: it describes the run, not the tool.+ assert data["computed_with"]["n_clusters"] == 3++ def test_intent_clusters_scoped_to_an_unknown_tool_is_empty_not_an_error(self) -> None:+ MCPIntentClusterSnapshot.objects.create(+ team=self.team,+ status=MCPIntentClusterSnapshot.Status.IDLE,+ clusters={+ "version": 2,+ "clusters": [_cluster_blob(0, "check feature flag rollout")],+ "tools": [_tool_blob("flag_get", cluster_ids=[0])],+ "tool_overlaps": [],+ "computed_with": {+ "distance_threshold": 0.2,+ "embedding_model": "text-embedding-3-small-1536",+ "n_intents": 1,+ "n_clusters": 1,+ },+ },+ )++ with patch("posthoganalytics.feature_enabled", return_value=True):+ response = self.client.get(f"/api/environments/{self.team.id}/mcp_analytics/intent_clusters/?tool=nope")++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["tools"] == []+ assert data["clusters"] == []def test_intent_clusters_recompute_starts_workflow_and_returns_computing(self) -> None:# Mock async_connect to return a client whose start_workflow is andiff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsxindex fbffdc03bb12..0288442637c2 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx@@ -39,6 +39,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import type { MCPToolFailureOccurrenceItem } from '~/queries/schema/schema-general'import { SceneExport } from '~/scenes/sceneTypes'+import { ToolDetailIntentsSection } from './clustering/ToolDetailIntentsSection'import { formatMs, formatMsAsSeconds } from './dashboard/formatters'import { HarnessLogo, HarnessPill } from './dashboard/harness'import { MetricTile } from './dashboard/MetricTile'@@ -624,6 +625,13 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.<LemonDivider />+ <div className="flex flex-col gap-3 px-4 pb-4">+ <SectionHeader title="Intents served" subtitle="From the latest intent cluster snapshot" />+ <ToolDetailIntentsSection toolName={toolName} />+ </div>++ <LemonDivider />+<div className="flex flex-col gap-3 px-4 pb-4"><SectionHeader title="Who uses it" /><div className="grid grid-cols-1 lg:grid-cols-2 gap-4">diff --git a/products/mcp_analytics/frontend/clustering/ClusteringCoverageBanner.tsx b/products/mcp_analytics/frontend/clustering/ClusteringCoverageBanner.tsxnew file mode 100644index 000000000000..b7fc6f16e73e--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/ClusteringCoverageBanner.tsx@@ -0,0 +1,38 @@+import { useValues } from 'kea'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import { mcpClusteringLogic } from './mcpClusteringLogic'++/**+ * States what the snapshot's sample actually covers so the percentages on this+ * tab are read as sample statistics, not census numbers.+ */+export function ClusteringCoverageBanner(): JSX.Element | null {+ const { snapshot } = useValues(mcpClusteringLogic)+ const meta = snapshot.computed_with++ if (!meta || meta.sampled_sessions === null || meta.sampled_sessions === undefined) {+ return null+ }++ const parts: string[] = []+ if (meta.window_sessions !== null && meta.window_sessions !== undefined) {+ parts.push(+ `Based on ${humanFriendlyNumber(meta.sampled_sessions)} sampled sessions out of ${humanFriendlyNumber(meta.window_sessions)} in the window`+ )+ } else {+ parts.push(`Based on ${humanFriendlyNumber(meta.sampled_sessions)} sampled sessions`)+ }+ if (meta.intent_coverage_pct !== null && meta.intent_coverage_pct !== undefined) {+ parts.push(`${meta.intent_coverage_pct.toFixed(0)}% of calls carried an intent`)+ }+ if (meta.advertisement_coverage_pct !== null && meta.advertisement_coverage_pct !== undefined) {+ parts.push(`advertisement data for ${meta.advertisement_coverage_pct.toFixed(0)}% of sampled sessions`)+ }+ if (meta.description_coverage_pct !== null && meta.description_coverage_pct !== undefined) {+ parts.push(`descriptions captured for ${meta.description_coverage_pct.toFixed(0)}% of tools`)+ }++ return <div className="text-xs text-muted">{parts.join(' · ')}.</div>+}diff --git a/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx b/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsxnew file mode 100644index 000000000000..2218ab136733--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx@@ -0,0 +1,167 @@+import { useValues } from 'kea'++import { Tooltip } from '@posthog/lemon-ui'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import { ScatterPoint, fitDomain, mcpClusteringLogic } from './mcpClusteringLogic'++const WIDTH = 640+const HEIGHT = 280+const PAD = { top: 16, right: 16, bottom: 36, left: 44 }++function scale(value: number, domain: [number, number], range: [number, number]): number {+ const [d0, d1] = domain+ const [r0, r1] = range+ if (d1 === d0) {+ return (r0 + r1) / 2+ }+ return r0 + ((value - d0) / (d1 - d0)) * (r1 - r0)+}++function radius(callCount: number, maxCalls: number): number {+ if (maxCalls <= 0) {+ return 5+ }+ return 4 + 10 * Math.sqrt(callCount / maxCalls)+}++/**+ * Discovery rate vs description fit, one bubble per tool, sized by call volume.+ * The quadrant lines sit at the medians of the plotted tools. The bottom-right+ * quadrant (fits the intent, rarely picked) is where description work pays off+ * most; the top-left (picked despite a poor fit) usually means the description+ * undersells what the tool does.+ */+export function DiscoveryScatter(): JSX.Element | null {+ const { scatterPoints, tools, fitMedian, discoveryMedian } = useValues(mcpClusteringLogic)++ if (scatterPoints.length === 0) {+ return (+ <div className="bg-surface-primary border rounded p-4 text-sm text-muted">+ <span className="font-medium text-default">Discovery vs description fit</span>+ <p className="mt-1 mb-0">+ This chart needs tools with both a captured description and enough advertised sessions to measure+ discovery. Descriptions accumulate as new calls are captured; check back after a few days of+ traffic.+ </p>+ </div>+ )+ }++ const xDomain = fitDomain(scatterPoints.map((p) => p.fit))+ const maxCalls = Math.max(...scatterPoints.map((p) => p.callCount))+ const plotX: [number, number] = [PAD.left, WIDTH - PAD.right]+ const plotY: [number, number] = [HEIGHT - PAD.bottom, PAD.top]+ const unplotted = tools.length - scatterPoints.length++ return (+ <div className="bg-surface-primary border rounded p-4 flex flex-col gap-2">+ <div className="flex flex-col">+ <span className="text-xs uppercase text-muted font-medium">Discovery vs description fit</span>+ <span className="text-xs text-muted">+ Tools in the lower right fit their intents but rarely get picked when advertised: the strongest+ candidates for a description rewrite.+ </span>+ </div>+ <svg viewBox={`0 0 ${WIDTH} ${HEIGHT}`} className="w-full max-w-[720px]" role="img">+ <line+ x1={PAD.left}+ y1={HEIGHT - PAD.bottom}+ x2={WIDTH - PAD.right}+ y2={HEIGHT - PAD.bottom}+ stroke="var(--border-primary)"+ />+ <line+ x1={PAD.left}+ y1={PAD.top}+ x2={PAD.left}+ y2={HEIGHT - PAD.bottom}+ stroke="var(--border-primary)"+ />+ {fitMedian !== null ? (+ <line+ x1={scale(fitMedian, xDomain, plotX)}+ y1={PAD.top}+ x2={scale(fitMedian, xDomain, plotX)}+ y2={HEIGHT - PAD.bottom}+ stroke="var(--border-primary)"+ strokeDasharray="4 4"+ />+ ) : null}+ {discoveryMedian !== null ? (+ <line+ x1={PAD.left}+ y1={scale(discoveryMedian, [0, 100], plotY)}+ x2={WIDTH - PAD.right}+ y2={scale(discoveryMedian, [0, 100], plotY)}+ stroke="var(--border-primary)"+ strokeDasharray="4 4"+ />+ ) : null}+ {/* The x-domain brackets the observed fits rather than starting at 0,+ so the ends have to be labelled for the spread to mean anything. */}+ <text x={PAD.left} y={HEIGHT - PAD.bottom + 14} className="fill-current text-muted" fontSize={9}>+ {xDomain[0].toFixed(2)}+ </text>+ <text+ x={WIDTH - PAD.right}+ y={HEIGHT - PAD.bottom + 14}+ textAnchor="end"+ className="fill-current text-muted"+ fontSize={9}+ >+ {xDomain[1].toFixed(2)}+ </text>+ <text+ x={(PAD.left + WIDTH - PAD.right) / 2}+ y={HEIGHT - 8}+ textAnchor="middle"+ className="fill-current text-muted"+ fontSize={10}+ >+ Description fit (cosine similarity to served intents)+ </text>+ <text+ x={12}+ y={(PAD.top + HEIGHT - PAD.bottom) / 2}+ textAnchor="middle"+ transform={`rotate(-90 12 ${(PAD.top + HEIGHT - PAD.bottom) / 2})`}+ className="fill-current text-muted"+ fontSize={10}+ >+ Discovery rate %+ </text>+ {scatterPoints.map((point: ScatterPoint) => (+ <Tooltip+ key={point.tool}+ title={+ <div className="flex flex-col gap-0.5">+ <span className="font-semibold font-mono">{point.tool}</span>+ <span>Description fit {point.fit.toFixed(2)}</span>+ <span>Discovery rate {point.discoveryRatePct.toFixed(1)}%</span>+ <span>{humanFriendlyNumber(point.callCount)} calls</span>+ </div>+ }+ >+ <circle+ cx={scale(point.fit, xDomain, plotX)}+ cy={scale(point.discoveryRatePct, [0, 100], plotY)}+ r={radius(point.callCount, maxCalls)}+ fill="var(--accent)"+ fillOpacity={0.55}+ stroke="var(--accent)"+ className="cursor-help"+ />+ </Tooltip>+ ))}+ </svg>+ {unplotted > 0 ? (+ <span className="text-[10px] text-muted">+ {unplotted} tool{unplotted === 1 ? ' is' : 's are'} not plotted: they lack a captured description or+ enough advertised sessions to measure discovery.+ </span>+ ) : null}+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/clustering/EntropyBadge.tsx b/products/mcp_analytics/frontend/clustering/EntropyBadge.tsxnew file mode 100644index 000000000000..7cca98c71508--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/EntropyBadge.tsx@@ -0,0 +1,72 @@+import { Tooltip } from '@posthog/lemon-ui'+import { Badge } from '@posthog/quill-primitives'++// Shared thresholds for reading a routing-entropy-scaled score: below 0.3 one+// tool dominates, above 0.6 calls spread across many tools. Used for both a+// cluster's entropy and a tool's contested score, so the two read the same.+export function EntropyBadge({ entropy }: { entropy: number }): JSX.Element {+ if (entropy < 0.3) {+ return (+ <Tooltip title={`Routing entropy ${entropy.toFixed(2)} — one tool dominates this cluster's calls.`}>+ <span>+ <Badge variant="success">Concentrated · {entropy.toFixed(2)}</Badge>+ </span>+ </Tooltip>+ )+ }+ if (entropy < 0.6) {+ return (+ <Tooltip title={`Routing entropy ${entropy.toFixed(2)} — calls split between a few tools.`}>+ <span>+ <Badge variant="warning">Mixed · {entropy.toFixed(2)}</Badge>+ </span>+ </Tooltip>+ )+ }+ return (+ <Tooltip+ title={`Routing entropy ${entropy.toFixed(2)} — calls spread across many tools. Either a real multi-step workflow or the agent is improvising; the aggregate alone can't tell.`}+ >+ <span>+ <Badge variant="destructive">Spread · {entropy.toFixed(2)}</Badge>+ </span>+ </Tooltip>+ )+}++// A tool's contested score is entropy-scaled, so it reuses the same bands with+// tool-appropriate wording.+export function ContestedBadge({ score }: { score: number | null }): JSX.Element {+ if (score === null) {+ return <span className="text-muted">—</span>+ }+ if (score < 0.3) {+ return (+ <Tooltip title={`Contested score ${score.toFixed(2)}. This tool is the clear choice for its intents.`}>+ <span>+ <Badge variant="success">Clear · {score.toFixed(2)}</Badge>+ </span>+ </Tooltip>+ )+ }+ if (score < 0.6) {+ return (+ <Tooltip+ title={`Contested score ${score.toFixed(2)}. Some of this tool's intents also route to other tools.`}+ >+ <span>+ <Badge variant="warning">Shared · {score.toFixed(2)}</Badge>+ </span>+ </Tooltip>+ )+ }+ return (+ <Tooltip+ title={`Contested score ${score.toFixed(2)}. The intents this tool serves are regularly split across several tools.`}+ >+ <span>+ <Badge variant="destructive">Contested · {score.toFixed(2)}</Badge>+ </span>+ </Tooltip>+ )+}diff --git a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsxindex 356cbc8d1ad3..60550982e281 100644--- a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx+++ b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx@@ -1,10 +1,14 @@import { useActions, useValues } from 'kea'-import { IconRefresh, IconSparkles, IconWarning } from '@posthog/icons'+import { IconRefresh, IconSearch, IconSparkles, IconWarning } from '@posthog/icons'import { Tooltip } from '@posthog/lemon-ui'import {Badge,Button,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ InputGroupText,Progress,Skeleton,Spinner,@@ -20,8 +24,14 @@ import { TZLabel } from 'lib/components/TZLabel'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import type { MCPIntentClusterApi, MCPIntentClusterToolEntryApi } from '../generated/api.schemas'+import { ClusteringCoverageBanner } from './ClusteringCoverageBanner'import { ClusterJourneySankey } from './ClusterJourneySankey'-import { ClusterSortKey, mcpClusteringLogic } from './mcpClusteringLogic'+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',@@ -30,34 +40,9 @@ const SORT_LABELS: Record<ClusterSortKey, string> = {concentration: 'Top-tool %',}-function EntropyBadge({ entropy }: { entropy: number }): JSX.Element {- if (entropy < 0.3) {- return (- <Tooltip title={`Routing entropy ${entropy.toFixed(2)} — one tool dominates this cluster's calls.`}>- <span>- <Badge variant="success">Concentrated · {entropy.toFixed(2)}</Badge>- </span>- </Tooltip>- )- }- if (entropy < 0.6) {- return (- <Tooltip title={`Routing entropy ${entropy.toFixed(2)} — calls split between a few tools.`}>- <span>- <Badge variant="warning">Mixed · {entropy.toFixed(2)}</Badge>- </span>- </Tooltip>- )- }- return (- <Tooltip- title={`Routing entropy ${entropy.toFixed(2)} — calls spread across many tools. Either a real multi-step workflow or the agent is improvising; the aggregate alone can't tell.`}- >- <span>- <Badge variant="destructive">Spread · {entropy.toFixed(2)}</Badge>- </span>- </Tooltip>- )+const VIEW_LABELS: Record<ClusteringViewMode, string> = {+ intents: 'By intent',+ tools: 'By tool',}function HeatmapCell({@@ -174,35 +159,80 @@ function Scorecards(): JSX.Element {)}-function SortHeader(): JSX.Element {- const { sortKey } = useValues(mcpClusteringLogic)- const { setSortKey } = useActions(mcpClusteringLogic)+function ViewToggle(): JSX.Element {+ const { viewMode } = useValues(mcpClusteringLogic)+ const { setViewMode } = useActions(mcpClusteringLogic)return (- <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) => (+ <div className="flex items-center gap-2">+ {(Object.keys(VIEW_LABELS) as ClusteringViewMode[]).map((key) => (<Buttonkey={key}size="sm"- variant={sortKey === key ? 'default' : 'outline'}- onClick={() => setSortKey(key)}+ variant={viewMode === key ? 'default' : 'outline'}+ onClick={() => setViewMode(key)}+ data-attr={`mcp-analytics-clustering-view-${key}`}>- {SORT_LABELS[key]}+ {VIEW_LABELS[key]}</Button>))}</div>)}+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">- No tool calls observed in any cluster yet.+ {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>)}@@ -562,8 +592,54 @@ function ComputingSkeleton(): JSX.Element {)}+function ToolsViewEmptyState(): JSX.Element {+ const { recompute } = useActions(mcpClusteringLogic)+ const { snapshotLoading } = useValues(mcpClusteringLogic)+ return (+ <div className="bg-surface-primary border rounded p-8 flex flex-col items-center text-center gap-3 max-w-2xl mx-auto">+ <IconSparkles className="text-4xl text-accent" />+ <h3 className="text-lg font-semibold">No tool-level data in this snapshot</h3>+ <p className="text-sm text-muted max-w-md">+ This snapshot was computed before tool-level analytics existed. Recompute to see which intents each tool+ serves, how often agents discover it, and which tools compete for the same intents.+ </p>+ <Button variant="default" onClick={recompute} disabled={snapshotLoading}>+ {snapshotLoading ? <Spinner /> : <IconRefresh />}+ Recompute clusters+ </Button>+ </div>+ )+}++function ToolsView(): JSX.Element {+ const { hasToolPivot, selectedTool, clusters } = useValues(mcpClusteringLogic)++ if (!hasToolPivot) {+ return <ToolsViewEmptyState />+ }++ 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>+ )+}+export function MCPAnalyticsClustering(): JSX.Element {- const { snapshot, selectedCluster, hasSnapshot, isComputing, snapshotLoading } = useValues(mcpClusteringLogic)+ const { snapshot, selectedCluster, hasSnapshot, isComputing, snapshotLoading, viewMode } =+ useValues(mcpClusteringLogic)const { recompute } = useActions(mcpClusteringLogic)if (snapshot.status === 'error') {@@ -592,15 +668,25 @@ export function MCPAnalyticsClustering(): JSX.Element {return (<div className="flex flex-col gap-4" data-quill><StatusRow />- <Scorecards />- <SortHeader />- <Heatmap />- {selectedCluster ? (- <ClusterDetail cluster={selectedCluster} />+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <ViewToggle />+ <ClusteringCoverageBanner />+ </div>+ {viewMode === 'tools' ? (+ <ToolsView />) : (- <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>+ <>+ <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>+ )}+ </>)}</div>)diff --git a/products/mcp_analytics/frontend/clustering/ToolDetailIntentsSection.tsx b/products/mcp_analytics/frontend/clustering/ToolDetailIntentsSection.tsxnew file mode 100644index 000000000000..ec79ef9600bf--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/ToolDetailIntentsSection.tsx@@ -0,0 +1,61 @@+import { useValues } from 'kea'++import { LinkPrimitive } from 'lib/lemon-ui/Link/Link'++import { urls } from '~/scenes/urls'++import { mcpToolIntentsLogic } from './mcpToolIntentsLogic'+import { ToolIntentDetail } from './ToolIntentDetail'++/**+ * The "Intents served" panel on the tool detail page: this tool's slice of the+ * latest intent cluster snapshot. Reads the same snapshot the clustering tab+ * shows — scoped to this tool by the API — so the numbers always agree between+ * the two surfaces without the page downloading every other tool's pivot.+ */+export function ToolDetailIntentsSection({ toolName }: { toolName: string }): JSX.Element {+ const { tool, clusters, hasSnapshot, snapshotLoading, snapshot } = useValues(mcpToolIntentsLogic({ toolName }))++ if (tool) {+ return <ToolIntentDetail tool={tool} clusters={clusters} showToolLink={false} />+ }++ // Mirror the clustering tab's error handling: a failed run must not read as+ // "never computed", or the owner keeps hitting compute with no idea why it fails.+ if (snapshot.status === 'error' && !snapshotLoading) {+ return (+ <div className="bg-surface-primary border rounded p-6 text-center text-muted text-sm">+ The last intent clustering run failed+ {snapshot.error_message ? `: ${snapshot.error_message}` : '.'}{' '}+ <LinkPrimitive to={urls.mcpAnalyticsIntentClustering()} className="text-accent">+ Retry from the clustering tab+ </LinkPrimitive>+ .+ </div>+ )+ }++ return (+ <div className="bg-surface-primary border rounded p-6 text-center text-muted text-sm">+ {snapshotLoading ? (+ 'Loading intent clusters…'+ ) : hasSnapshot ? (+ <>+ This tool has no intent-attributed calls in the latest cluster snapshot.{' '}+ <LinkPrimitive to={urls.mcpAnalyticsIntentClustering()} className="text-accent">+ Recompute clusters+ </LinkPrimitive>{' '}+ to include recent traffic.+ </>+ ) : (+ <>+ Intent clustering shows which goals agents pursue when they call this tool.{' '}+ <LinkPrimitive to={urls.mcpAnalyticsIntentClustering()} className="text-accent">+ Compute clusters+ </LinkPrimitive>{' '}+ to see them here.+ </>+ )}+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx b/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsxnew file mode 100644index 000000000000..8b9ebf3887f0--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx@@ -0,0 +1,195 @@+import { IconArrowRight } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'+import {+ Badge,+ Progress,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@posthog/quill-primitives'++import { LinkPrimitive } from 'lib/lemon-ui/Link/Link'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import { urls } from '~/scenes/urls'++import type { MCPClusterSwitchApi, MCPIntentClusterApi, MCPToolPivotApi } from '../generated/api.schemas'+import { toolClusterRows } from './mcpClusteringLogic'++interface ToolSwitchRow extends MCPClusterSwitchApi {+ clusterLabel: string+}++/** Every error switch across the snapshot that involves the given tool, worst first. */+function collectSwitches(tool: string, clusters: readonly MCPIntentClusterApi[]): ToolSwitchRow[] {+ const rows: ToolSwitchRow[] = []+ for (const cluster of clusters) {+ for (const sw of cluster.switches) {+ if (sw.from_tool === tool || sw.to_tool === tool) {+ rows.push({ ...sw, clusterLabel: cluster.label })+ }+ }+ }+ return rows.sort((a, b) => b.count - a.count).slice(0, 10)+}++export function ToolIntentDetail({+ tool,+ clusters,+ showToolLink = true,+}: {+ tool: MCPToolPivotApi+ /** The snapshot's clusters — the pivot's entries carry only ids and join against these. */+ clusters: readonly MCPIntentClusterApi[]+ showToolLink?: boolean+}): JSX.Element {+ const switches = collectSwitches(tool.tool, clusters)+ const clusterRows = toolClusterRows(tool, clusters)++ return (+ <div className="bg-surface-primary border rounded p-4 flex flex-col gap-4" data-quill>+ <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 tool</span>+ {showToolLink ? (+ <LinkPrimitive to={urls.mcpAnalyticsTool(tool.tool)}>+ <h3 className="text-lg font-semibold leading-tight font-mono">{tool.tool}</h3>+ </LinkPrimitive>+ ) : (+ <h3 className="text-lg font-semibold leading-tight font-mono">{tool.tool}</h3>+ )}+ </div>+ <div className="flex flex-wrap items-center gap-2 shrink-0">+ <Badge variant="default">{humanFriendlyNumber(tool.call_count)} calls</Badge>+ <Badge variant="default">+ {tool.session_count} session{tool.session_count === 1 ? '' : 's'}+ </Badge>+ {tool.discovery_rate_pct !== null ? (+ <Tooltip+ title={`Called in ${tool.called_when_advertised} of the ${tool.advertised_sessions} sampled sessions that advertised it.`}+ >+ <span>+ <Badge variant={tool.discovery_rate_pct < 25 ? 'destructive' : 'default'}>+ {tool.discovery_rate_pct.toFixed(1)}% discovery+ </Badge>+ </span>+ </Tooltip>+ ) : null}+ </div>+ </div>+ {tool.description ? (+ <p className="text-xs text-muted font-mono bg-surface-secondary rounded p-2 mb-0">+ {tool.description}+ </p>+ ) : (+ <p className="text-xs text-muted mb-0">+ No description captured for this tool yet, so description fit can't be scored. Descriptions+ appear as new calls are captured.+ </p>+ )}+ </header>++ <section className="flex flex-col gap-2">+ <span className="text-xs uppercase text-muted font-medium">+ Intents this tool serves+ {tool.n_clusters_served > clusterRows.length+ ? ` · top ${clusterRows.length} of ${tool.n_clusters_served}`+ : ''}+ </span>+ <Table fullWidth>+ <TableHeader>+ <TableRow>+ <TableHead expand>Intent</TableHead>+ <TableHead align="right">Calls</TableHead>+ <TableHead>Capture</TableHead>+ <TableHead>Strongest competitor</TableHead>+ <TableHead align="right">Description fit</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {clusterRows.map(({ entry, cluster }) => (+ <TableRow key={entry.cluster_id}>+ <TableCell expand>+ <div className="flex flex-col">+ <span className="truncate max-w-[360px]" title={cluster.label}>+ {cluster.label}+ </span>+ <span className="text-[10px] text-muted">+ {entry.rank === 1+ ? 'Top tool for this intent'+ : `Rank ${entry.rank} for this intent`}+ {' · '}+ {humanFriendlyNumber(cluster.call_count)} calls in cluster+ </span>+ </div>+ </TableCell>+ <TableCell align="right">+ <span className="tabular-nums">{humanFriendlyNumber(entry.calls)}</span>+ </TableCell>+ <TableCell>+ <div className="flex min-w-[140px] items-center gap-2">+ <Progress value={entry.capture_pct} className="flex-1" />+ <span className="w-10 text-right text-xs tabular-nums text-muted">+ {entry.capture_pct.toFixed(1)}%+ </span>+ </div>+ </TableCell>+ <TableCell>+ {entry.top_competitor ? (+ <span className="text-xs">+ <span className="font-mono">{entry.top_competitor.tool}</span>+ <span className="text-muted">+ {' '}+ takes {entry.top_competitor.pct.toFixed(1)}%+ </span>+ </span>+ ) : (+ <span className="text-muted text-xs">Only tool for this intent</span>+ )}+ </TableCell>+ <TableCell align="right">+ {entry.description_fit !== null ? (+ <span className="tabular-nums">{entry.description_fit.toFixed(2)}</span>+ ) : (+ <span className="text-muted">—</span>+ )}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </section>++ {switches.length > 0 ? (+ <section className="flex flex-col gap-2">+ <span className="text-xs uppercase text-muted font-medium">Error switches involving this tool</span>+ <div className="flex flex-col gap-1">+ {switches.map((row, index) => (+ <div key={index} className="flex items-center gap-2 text-xs">+ <span className={`font-mono ${row.from_tool === tool.tool ? 'text-danger' : ''}`}>+ {row.from_tool}+ </span>+ <IconArrowRight className="text-muted" />+ <span className={`font-mono ${row.to_tool === tool.tool ? 'text-success' : ''}`}>+ {row.to_tool}+ </span>+ <span className="text-muted">+ ×{row.count} after errors, for "{row.clusterLabel}"+ </span>+ </div>+ ))}+ </div>+ <span className="text-[10px] text-muted">+ An errored call immediately followed by a different tool for the same intent. Switches away from+ this tool suggest agents fall back elsewhere when it fails; switches into it suggest it picks up+ after other tools fail.+ </span>+ </section>+ ) : null}+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/clustering/ToolOverlapTable.tsx b/products/mcp_analytics/frontend/clustering/ToolOverlapTable.tsxnew file mode 100644index 000000000000..1679b498f6e4--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/ToolOverlapTable.tsx@@ -0,0 +1,96 @@+import { useValues } from 'kea'++import { Tooltip } from '@posthog/lemon-ui'+import { Badge, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@posthog/quill-primitives'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import type { MCPToolOverlapApi } from '../generated/api.schemas'+import { mcpClusteringLogic } from './mcpClusteringLogic'++function RelationshipBadge({ overlap }: { overlap: MCPToolOverlapApi }): JSX.Element {+ if (overlap.sessions_with_either === 0) {+ return <span className="text-muted">—</span>+ }+ const togetherShare = overlap.sessions_with_both / overlap.sessions_with_either+ if (togetherShare >= 0.5) {+ return (+ <Tooltip+ title={`${overlap.sessions_with_both} of ${overlap.sessions_with_either} sessions used both tools, so this pair looks like a workflow rather than confusion.`}+ >+ <span>+ <Badge variant="default">Used together</Badge>+ </span>+ </Tooltip>+ )+ }+ return (+ <Tooltip+ title={`Only ${overlap.sessions_with_both} of ${overlap.sessions_with_either} sessions used both tools. Agents usually pick one or the other for these intents, which suggests the tools compete.`}+ >+ <span>+ <Badge variant="warning">One or the other</Badge>+ </span>+ </Tooltip>+ )+}++/**+ * Tool pairs competing for the same intent clusters. This is also the pre and+ * post check for description rewrites: a rewrite that wins one intent can pull+ * traffic from the tool that should own another.+ */+export function ToolOverlapTable(): JSX.Element | null {+ const { toolOverlaps } = useValues(mcpClusteringLogic)++ if (toolOverlaps.length === 0) {+ return null+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-col">+ <span className="text-xs uppercase text-muted font-medium">Tools competing for the same intents</span>+ <span className="text-xs text-muted">+ Contested calls is the volume both tools plausibly compete for across shared intent clusters.+ </span>+ </div>+ <div className="bg-surface-primary border rounded" data-quill>+ <Table fullWidth>+ <TableHeader>+ <TableRow>+ <TableHead expand>Pair</TableHead>+ <TableHead align="right">Contested calls</TableHead>+ <TableHead align="right">Sessions with both</TableHead>+ <TableHead align="right">Sessions with either</TableHead>+ <TableHead>Relationship</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {toolOverlaps.map((overlap) => (+ <TableRow key={`${overlap.tool_a}|${overlap.tool_b}`}>+ <TableCell expand>+ <span className="font-mono">{overlap.tool_a}</span>+ <span className="text-muted"> + </span>+ <span className="font-mono">{overlap.tool_b}</span>+ </TableCell>+ <TableCell align="right">+ <span className="tabular-nums">{humanFriendlyNumber(overlap.contested_calls)}</span>+ </TableCell>+ <TableCell align="right">+ <span className="tabular-nums">{overlap.sessions_with_both}</span>+ </TableCell>+ <TableCell align="right">+ <span className="tabular-nums">{overlap.sessions_with_either}</span>+ </TableCell>+ <TableCell>+ <RelationshipBadge overlap={overlap} />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx b/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsxnew file mode 100644index 000000000000..cc7c3c068a5f--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx@@ -0,0 +1,132 @@+import { useActions, useValues } from 'kea'++import { Tooltip } from '@posthog/lemon-ui'+import { Button, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@posthog/quill-primitives'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import type { MCPToolPivotApi } from '../generated/api.schemas'+import { ContestedBadge } from './EntropyBadge'+import { ToolSortKey, mcpClusteringLogic, weightedMeanFit } from './mcpClusteringLogic'++const SORT_LABELS: Record<ToolSortKey, string> = {+ calls: 'Calls',+ contested: 'Contested',+ discovery: 'Discovery rate',+}++function DiscoveryCell({ tool }: { tool: MCPToolPivotApi }): JSX.Element {+ if (tool.discovery_rate_pct === null) {+ return (+ <Tooltip+ title={+ tool.advertised_sessions === 0+ ? 'No sampled session with a tools-list catalog advertised this tool, so there is no denominator to measure discovery against.'+ : `Advertised in only ${tool.advertised_sessions} sampled session${tool.advertised_sessions === 1 ? '' : 's'}, which is not enough to measure a rate.`+ }+ >+ <span className="text-muted cursor-help">—</span>+ </Tooltip>+ )+ }+ return (+ <Tooltip+ title={`Called in ${tool.called_when_advertised} of the ${tool.advertised_sessions} sampled sessions that advertised it.`}+ >+ <span className={`tabular-nums cursor-help ${tool.discovery_rate_pct < 25 ? 'text-danger' : ''}`}>+ {tool.discovery_rate_pct.toFixed(1)}%+ </span>+ </Tooltip>+ )+}++function FitCell({ tool }: { tool: MCPToolPivotApi }): JSX.Element {+ const fit = weightedMeanFit(tool)+ if (fit === null) {+ return (+ <Tooltip title="No description has been captured for this tool yet, so its fit to the intents can't be scored.">+ <span className="text-muted cursor-help">—</span>+ </Tooltip>+ )+ }+ return (+ <Tooltip title="Call-weighted cosine similarity between the tool's description and the intents that route to it. Higher means the description matches what agents actually use the tool for.">+ <span className="tabular-nums cursor-help">{fit.toFixed(2)}</span>+ </Tooltip>+ )+}++export function ToolPivotTable(): JSX.Element {+ const { sortedTools, toolSortKey, selectedToolName } = useValues(mcpClusteringLogic)+ const { selectTool, setToolSortKey } = useActions(mcpClusteringLogic)++ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-xs text-muted">Sort tools by</span>+ {(Object.keys(SORT_LABELS) as ToolSortKey[]).map((key) => (+ <Button+ key={key}+ size="sm"+ variant={toolSortKey === key ? 'default' : 'outline'}+ onClick={() => setToolSortKey(key)}+ >+ {SORT_LABELS[key]}+ </Button>+ ))}+ </div>+ <div className="bg-surface-primary border rounded" data-quill>+ <Table fullWidth>+ <TableHeader>+ <TableRow>+ <TableHead expand>Tool</TableHead>+ <TableHead align="right">Calls</TableHead>+ <TableHead align="right">Errors</TableHead>+ <TableHead align="right">Intents served</TableHead>+ <TableHead>Routing</TableHead>+ <TableHead align="right">Discovery</TableHead>+ <TableHead align="right">Description fit</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {sortedTools.map((tool) => (+ <TableRow+ key={tool.tool}+ onClick={() => selectTool(tool.tool)}+ className={`cursor-pointer ${selectedToolName === tool.tool ? 'bg-accent/10' : ''}`}+ >+ <TableCell expand>+ <span className="font-mono">{tool.tool}</span>+ </TableCell>+ <TableCell align="right">+ <span className="tabular-nums">{humanFriendlyNumber(tool.call_count)}</span>+ </TableCell>+ <TableCell align="right">+ {tool.error_count > 0 ? (+ <span className="tabular-nums text-danger">+ {humanFriendlyNumber(tool.error_count)}+ </span>+ ) : (+ <span className="text-muted">0</span>+ )}+ </TableCell>+ <TableCell align="right">+ <span className="tabular-nums">{humanFriendlyNumber(tool.n_clusters_served)}</span>+ </TableCell>+ <TableCell>+ <ContestedBadge score={tool.contested_score} />+ </TableCell>+ <TableCell align="right">+ <DiscoveryCell tool={tool} />+ </TableCell>+ <TableCell align="right">+ <FitCell tool={tool} />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.tsindex 793571162f2b..ce42ff4ce6c5 100644--- a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts@@ -3,8 +3,20 @@ 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'+import type {+ MCPIntentClusterApi,+ MCPIntentClusterSnapshotApi,+ MCPToolPivotApi,+ MCPToolPivotClusterEntryApi,+} from '../generated/api.schemas'+import {+ MAX_HEATMAP_TOOL_COLUMNS,+ MAX_VISIBLE_CLUSTERS,+ fitDomain,+ mcpClusteringLogic,+ toolClusterRows,+ weightedMeanFit,+} from './mcpClusteringLogic'jest.mock('lib/api')jest.mock('../generated/api', () => ({@@ -32,6 +44,8 @@ function cluster(id: number, overrides: Partial<MCPIntentClusterApi> = {}): MCPI],sample_intents: [`intent ${id}`],journey: null,+ switches: [],+ self_retries: [],...overrides,}}@@ -50,11 +64,29 @@ const SNAPSHOT: MCPIntentClusterSnapshotApi = {// 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+ // 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,+ // Coverage metadata feeds ClusteringCoverageBanner, not these selectors.+ corpus: null,+ sampled_sessions: null,+ window_sessions: null,+ session_coverage_pct: null,+ intent_coverage_pct: null,+ imputed_call_pct: null,+ unattributed_call_pct: null,+ corpus_call_coverage_pct: null,+ advertisement_coverage_pct: null,+ n_tools: null,+ dropped_tools: null,+ dropped_overlap_pairs: null,+ description_coverage_pct: null,},}@@ -118,3 +150,95 @@ describe('mcpClusteringLogic', () => {expect(logic.values.totalClusterCount).toBe(500)})})++function entry(overrides: Partial<MCPToolPivotClusterEntryApi>): MCPToolPivotClusterEntryApi {+ return {+ cluster_id: 0,+ calls: 1,+ capture_pct: 100,+ rank: 1,+ description_fit: null,+ top_competitor: null,+ ...overrides,+ }+}++function pivot(clusters: MCPToolPivotClusterEntryApi[]): MCPToolPivotApi {+ return {+ tool: 't',+ call_count: clusters.reduce((sum, c) => sum + c.calls, 0),+ error_count: 0,+ session_count: 1,+ contested_score: null,+ advertised_sessions: 0,+ called_when_advertised: 0,+ discovery_rate_pct: null,+ description: null,+ n_clusters_served: clusters.length,+ clusters,+ }+}++describe('mcpClusteringLogic helpers', () => {+ // 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', () => {+ const tool = pivot([+ entry({ cluster_id: 0, calls: 9, description_fit: 1.0 }),+ entry({ cluster_id: 1, calls: 1, description_fit: 0.0 }),+ ])+ expect(weightedMeanFit(tool)).toBeCloseTo(0.9)+ })++ it.each([+ ['no cluster has a fit', [entry({ description_fit: null })]],+ ['no clusters at all', [] as MCPToolPivotClusterEntryApi[]],+ ['fits exist but carry zero calls', [entry({ calls: 0, description_fit: 0.5 })]],+ ])('weightedMeanFit is null when %s', (_name, clusters) => {+ expect(weightedMeanFit(pivot(clusters))).toBeNull()+ })++ it('weightedMeanFit ignores fitless clusters instead of treating them as zero', () => {+ const tool = pivot([+ entry({ cluster_id: 0, calls: 1, description_fit: 0.8 }),+ entry({ cluster_id: 1, calls: 99, description_fit: null }),+ ])+ expect(weightedMeanFit(tool)).toBeCloseTo(0.8)+ })++ // The pivot no longer ships the cluster's label with every entry, so a broken+ // join renders the intents table with blank rows instead of intent text.+ it('toolClusterRows joins each entry to the cluster it points at', () => {+ const rows = toolClusterRows(pivot([entry({ cluster_id: 3 }), entry({ cluster_id: 1 })]), [+ cluster(1),+ cluster(3),+ ])++ expect(rows.map((row) => row.cluster.label)).toEqual(['intent 3', 'intent 1'])+ })++ it('toolClusterRows drops entries with no matching cluster rather than rendering them blank', () => {+ expect(toolClusterRows(pivot([entry({ cluster_id: 99 })]), [cluster(1)])).toEqual([])+ })++ // Fits for one server's tools sit in a narrow band; anchoring the axis at 0+ // piles every bubble against the right edge and puts the median line through+ // the pile, which is exactly the quadrant read the chart promises.+ it('fitDomain brackets the observed band instead of anchoring at zero', () => {+ const [low, high] = fitDomain([0.55, 0.7, 0.85])++ expect(low).toBeGreaterThan(0.4)+ expect(low).toBeLessThan(0.55)+ expect(high).toBeGreaterThan(0.85)+ expect(high).toBeLessThanOrEqual(1)+ })++ it.each([+ ['every tool has the same fit', [0.7, 0.7]],+ ['there is a single tool', [0.7]],+ ])('fitDomain keeps a usable span when %s', (_name, fits) => {+ const [low, high] = fitDomain(fits)++ expect(high - low).toBeGreaterThan(0)+ })+})diff --git a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.tsindex 7e4801029471..bf9f09b16a1d 100644--- a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts@@ -6,7 +6,13 @@ import { lemonToast } from '@posthog/lemon-ui'import { teamLogic } from 'scenes/teamLogic'import { mcpAnalyticsIntentClustersRecompute, mcpAnalyticsIntentClustersRetrieve } from '../generated/api'-import type { MCPIntentClusterApi, MCPIntentClusterSnapshotApi } from '../generated/api.schemas'+import type {+ MCPIntentClusterApi,+ MCPIntentClusterSnapshotApi,+ MCPToolOverlapApi,+ MCPToolPivotApi,+ MCPToolPivotClusterEntryApi,+} from '../generated/api.schemas'const EMPTY_SNAPSHOT: MCPIntentClusterSnapshotApi = {status: 'idle',@@ -14,6 +20,8 @@ const EMPTY_SNAPSHOT: MCPIntentClusterSnapshotApi = {last_computed_at: null,last_computed_by_email: '',clusters: [],+ tools: [],+ tool_overlaps: [],computed_with: null,}@@ -41,6 +49,73 @@ function normalizeSnapshot(}export type ClusterSortKey = 'calls' | 'errors' | 'entropy' | 'concentration'+export type ToolSortKey = 'calls' | 'contested' | 'discovery'+export type ClusteringViewMode = 'intents' | 'tools'++export interface ScatterPoint {+ tool: string+ fit: number+ discoveryRatePct: number+ callCount: number+}++/** Call-weighted mean description fit across a tool's cluster entries, or null when no entry has one. */+export function weightedMeanFit(tool: MCPToolPivotApi): number | null {+ const withFit = tool.clusters.filter((entry) => entry.description_fit !== null)+ if (withFit.length === 0) {+ return null+ }+ const totalCalls = withFit.reduce((sum, entry) => sum + entry.calls, 0)+ if (totalCalls === 0) {+ return null+ }+ return withFit.reduce((sum, entry) => sum + (entry.description_fit as number) * entry.calls, 0) / totalCalls+}++/** An entry joined to the cluster it points at, so the pivot doesn't have to carry a copy. */+export interface ToolClusterRow {+ entry: MCPToolPivotClusterEntryApi+ cluster: MCPIntentClusterApi+}++/**+ * Join a tool's pivot entries to their clusters. Entries whose cluster is absent+ * are dropped rather than rendered label-less: the backend only emits entries for+ * clusters the snapshot carries, so a miss means the two came from different runs.+ */+export function toolClusterRows(tool: MCPToolPivotApi, clusters: readonly MCPIntentClusterApi[]): ToolClusterRow[] {+ const byId = new Map(clusters.map((cluster) => [cluster.id, cluster]))+ return tool.clusters.flatMap((entry) => {+ const cluster = byId.get(entry.cluster_id)+ return cluster ? [{ entry, cluster }] : []+ })+}++// Cosine fits for one server's tools against its own intent centroids sit in a+// narrow band. Anchoring the axis at 0 pushes every bubble against the right edge+// and runs the median line through the pile, defeating the quadrant read.+const FIT_DOMAIN_MIN_SPAN = 0.1+const FIT_DOMAIN_PADDING = 0.1++/** Padded x-domain around the observed fits, with a floor on the span so a single point can't collapse it. */+export function fitDomain(fits: number[]): [number, number] {+ if (fits.length === 0) {+ return [0, 1]+ }+ const low = Math.min(...fits)+ const high = Math.max(...fits)+ const pad = Math.max((high - low) * FIT_DOMAIN_PADDING, FIT_DOMAIN_MIN_SPAN / 2)+ return [Math.max(-1, low - pad), Math.min(1, high + pad)]+}++function median(values: number[]): number | null {+ if (values.length === 0) {+ return null+ }+ const sorted = [...values].sort((a, b) => a - b)+ const middle = Math.floor(sorted.length / 2)+ return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2+}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpClusteringLogicValues {@@ -51,20 +126,33 @@ export interface mcpClusteringLogicValues {focused: numbertotal: number}+ discoveryMedian: number | null+ filteredClusters: MCPIntentClusterApi[]+ fitMedian: number | nullhasSnapshot: boolean+ hasToolPivot: booleanhiddenClusterCount: numberisComputing: boolean+ scatterPoints: ScatterPoint[]selectedCluster: MCPIntentClusterApi | nullselectedClusterId: number | null+ selectedTool: MCPToolPivotApi | null+ selectedToolName: string | nullsnapshot: MCPIntentClusterSnapshotApisnapshotLoading: booleansortKey: ClusterSortKeysortedClusters: MCPIntentClusterApi[]+ sortedTools: MCPToolPivotApi[]spreadRoutes: numbertoolColumns: string[]+ toolOverlaps: readonly MCPToolOverlapApi[]+ toolSearch: string+ toolSortKey: ToolSortKey+ tools: readonly MCPToolPivotApi[]topErrorRoute: MCPIntentClusterApi | nulltotalClusterCount: numbertotalToolCount: number+ viewMode: ClusteringViewModevisibleClusters: MCPIntentClusterApi[]}@@ -94,9 +182,21 @@ export interface mcpClusteringLogicActions {selectCluster: (clusterId: number | null) => {clusterId: number | null}+ selectTool: (toolName: string | null) => {+ toolName: string | null+ }setSortKey: (sortKey: ClusterSortKey) => {sortKey: ClusterSortKey}+ setToolSearch: (toolSearch: string) => {+ toolSearch: string+ }+ setToolSortKey: (toolSortKey: ToolSortKey) => {+ toolSortKey: ToolSortKey+ }+ setViewMode: (viewMode: ClusteringViewMode) => {+ viewMode: ClusteringViewMode+ }showAllClusters: () => {value: true}@@ -127,11 +227,24 @@ export interface mcpClusteringLogicActions {export interface mcpClusteringLogicMeta {__keaTypeGenInternalSelectorTypes: {clusters: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPIntentClusterApi[]+ tools: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPToolPivotApi[]+ toolOverlaps: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPToolOverlapApi[]+ hasToolPivot: (tools: readonly MCPToolPivotApi[]) => booleansortedClusters: (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+ filteredClusters: (sortedClusters: MCPIntentClusterApi[], toolSearch: string) => MCPIntentClusterApi[]+ sortedTools: (+ tools: readonly MCPToolPivotApi[],+ toolSortKey: ToolSortKey,+ toolSearch: string+ ) => MCPToolPivotApi[]+ selectedTool: (tools: readonly MCPToolPivotApi[], selectedToolName: string | null) => MCPToolPivotApi | null+ 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[]) => numbertotalClusterCount: (snapshot: MCPIntentClusterSnapshotApi) => numberselectedCluster: (clusters: readonly MCPIntentClusterApi[],@@ -162,7 +275,11 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([})),actions({selectCluster: (clusterId: number | null) => ({ clusterId }),+ selectTool: (toolName: string | null) => ({ toolName }),setSortKey: (sortKey: ClusterSortKey) => ({ sortKey }),+ setToolSortKey: (toolSortKey: ToolSortKey) => ({ toolSortKey }),+ setViewMode: (viewMode: ClusteringViewMode) => ({ viewMode }),+ setToolSearch: (toolSearch: string) => ({ toolSearch }),showAllClusters: true,recompute: true,startPolling: true,@@ -197,12 +314,36 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([selectCluster: (_, { clusterId }) => clusterId,},],+ selectedToolName: [+ null as string | null,+ {+ selectTool: (_, { toolName }) => toolName,+ },+ ],sortKey: ['calls' as ClusterSortKey,{setSortKey: (_, { sortKey }) => sortKey,},],+ toolSortKey: [+ 'calls' as ToolSortKey,+ {+ setToolSortKey: (_, { toolSortKey }) => toolSortKey,+ },+ ],+ viewMode: [+ 'intents' as ClusteringViewMode,+ {+ setViewMode: (_, { viewMode }) => viewMode,+ },+ ],+ toolSearch: [+ '',+ {+ setToolSearch: (_, { toolSearch }) => toolSearch,+ },+ ],allClustersShown: [false,{@@ -215,6 +356,17 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([(s) => [s.snapshot],(snapshot: MCPIntentClusterSnapshotApi): readonly MCPIntentClusterApi[] => snapshot.clusters,],+ tools: [+ (s) => [s.snapshot],+ (snapshot: MCPIntentClusterSnapshotApi): readonly MCPToolPivotApi[] => snapshot.tools ?? [],+ ],+ toolOverlaps: [+ (s) => [s.snapshot],+ (snapshot: MCPIntentClusterSnapshotApi): readonly MCPToolOverlapApi[] => snapshot.tool_overlaps ?? [],+ ],+ // Snapshots computed before the per-call pipeline have no tool sections;+ // the tools view offers a recompute instead of rendering empty tables.+ hasToolPivot: [(s) => [s.tools], (tools: readonly MCPToolPivotApi[]): boolean => tools.length > 0],sortedClusters: [(s) => [s.clusters, s.sortKey],(clusters: readonly MCPIntentClusterApi[], sortKey: ClusterSortKey): MCPIntentClusterApi[] => {@@ -234,25 +386,91 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([}},],- // The heatmap rows: sliced after sorting so re-sorting can surface any- // cluster into the visible set.+ filteredClusters: [+ (s) => [s.sortedClusters, s.toolSearch],+ (sortedClusters: MCPIntentClusterApi[], toolSearch: string): MCPIntentClusterApi[] => {+ const query = toolSearch.trim().toLowerCase()+ if (!query) {+ return sortedClusters+ }+ return sortedClusters.filter((cluster) =>+ cluster.tool_distribution.some((entry) => entry.tool.toLowerCase().includes(query))+ )+ },+ ],+ sortedTools: [+ (s) => [s.tools, s.toolSortKey, s.toolSearch],+ (tools: readonly MCPToolPivotApi[], toolSortKey: ToolSortKey, toolSearch: string): MCPToolPivotApi[] => {+ const query = toolSearch.trim().toLowerCase()+ const arr = tools.filter((tool) => !query || tool.tool.toLowerCase().includes(query))+ switch (toolSortKey) {+ case 'contested':+ return arr.sort((a, b) => (b.contested_score ?? -1) - (a.contested_score ?? -1))+ case 'discovery':+ // Nulls sink to the bottom so measurable rates lead.+ return arr.sort((a, b) => (b.discovery_rate_pct ?? -1) - (a.discovery_rate_pct ?? -1))+ case 'calls':+ default:+ return arr.sort((a, b) => b.call_count - a.call_count)+ }+ },+ ],+ selectedTool: [+ (s) => [s.tools, s.selectedToolName],+ (tools: readonly MCPToolPivotApi[], selectedToolName: string | null): MCPToolPivotApi | null => {+ if (selectedToolName === null) {+ return null+ }+ return tools.find((tool) => tool.tool === selectedToolName) ?? null+ },+ ],+ scatterPoints: [+ (s) => [s.tools],+ (tools: readonly MCPToolPivotApi[]): ScatterPoint[] =>+ tools.flatMap((tool) => {+ const fit = weightedMeanFit(tool)+ if (fit === null || tool.discovery_rate_pct === null) {+ return []+ }+ return [+ {+ tool: tool.tool,+ fit,+ discoveryRatePct: tool.discovery_rate_pct,+ callCount: tool.call_count,+ },+ ]+ }),+ ],+ // Quadrant lines sit at the medians of the plotted tools: data-derived,+ // so no tuned threshold decides what counts as "well described".+ fitMedian: [+ (s) => [s.scatterPoints],+ (scatterPoints: ScatterPoint[]): number | null => median(scatterPoints.map((p) => p.fit)),+ ],+ discoveryMedian: [+ (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.sortedClusters, s.allClustersShown],- (sortedClusters: MCPIntentClusterApi[], allClustersShown: boolean): MCPIntentClusterApi[] =>- allClustersShown ? sortedClusters : sortedClusters.slice(0, MAX_VISIBLE_CLUSTERS),+ (s) => [s.filteredClusters, s.allClustersShown],+ (filteredClusters: MCPIntentClusterApi[], allClustersShown: boolean): MCPIntentClusterApi[] =>+ allClustersShown ? filteredClusters : filteredClusters.slice(0, MAX_VISIBLE_CLUSTERS),],hiddenClusterCount: [- (s) => [s.sortedClusters, s.visibleClusters],- (sortedClusters: MCPIntentClusterApi[], visibleClusters: MCPIntentClusterApi[]): number =>- sortedClusters.length - visibleClusters.length,+ (s) => [s.filteredClusters, s.visibleClusters],+ (filteredClusters: MCPIntentClusterApi[], visibleClusters: MCPIntentClusterApi[]): number =>+ filteredClusters.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[] => {+ (s) => [s.filteredClusters],+ (filteredClusters: MCPIntentClusterApi[]): string[] => {const totals = new Map<string, number>()- for (const cluster of clusters) {+ for (const cluster of filteredClusters) {for (const entry of cluster.tool_distribution) {totals.set(entry.tool, (totals.get(entry.tool) ?? 0) + entry.count)}@@ -264,10 +482,10 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([},],totalToolCount: [- (s) => [s.clusters],- (clusters: readonly MCPIntentClusterApi[]): number => {+ (s) => [s.filteredClusters],+ (filteredClusters: MCPIntentClusterApi[]): number => {const tools = new Set<string>()- for (const cluster of clusters) {+ for (const cluster of filteredClusters) {for (const entry of cluster.tool_distribution) {tools.add(entry.tool)}@@ -345,6 +563,10 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([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]+ actions.selectTool(topTool.tool)+ }},triggerRecomputeSuccess: ({ snapshot }) => {lemonToast.info('Clustering started — this usually takes 30–60 seconds.')diff --git a/products/mcp_analytics/frontend/clustering/mcpToolIntentsLogic.ts b/products/mcp_analytics/frontend/clustering/mcpToolIntentsLogic.tsnew file mode 100644index 000000000000..fce606e4d1a1--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/mcpToolIntentsLogic.ts@@ -0,0 +1,132 @@+import { MakeLogicType, afterMount, connect, kea, key, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { mcpAnalyticsIntentClustersRetrieve } from '../generated/api'+import type { MCPIntentClusterApi, MCPIntentClusterSnapshotApi, MCPToolPivotApi } from '../generated/api.schemas'++export interface MCPToolIntentsLogicProps {+ toolName: string+}++const EMPTY_SNAPSHOT: MCPIntentClusterSnapshotApi = {+ status: 'idle',+ error_message: '',+ last_computed_at: null,+ last_computed_by_email: '',+ clusters: [],+ tools: [],+ tool_overlaps: [],+ computed_with: null,+}++// 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(+ response: MCPIntentClusterSnapshotApi | readonly MCPIntentClusterSnapshotApi[] | null | undefined+): MCPIntentClusterSnapshotApi {+ if (!response) {+ return EMPTY_SNAPSHOT+ }+ if (Array.isArray(response)) {+ return response[0] ?? EMPTY_SNAPSHOT+ }+ return response as MCPIntentClusterSnapshotApi+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpToolIntentsLogicValues {+ currentProjectId: number | string // teamLogic+ clusters: readonly MCPIntentClusterApi[]+ hasSnapshot: boolean+ snapshot: MCPIntentClusterSnapshotApi+ snapshotLoading: boolean+ tool: MCPToolPivotApi | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpToolIntentsLogicActions {+ loadSnapshot: () => any+ loadSnapshotFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSnapshotSuccess: (+ snapshot: MCPIntentClusterSnapshotApi,+ payload?: any+ ) => {+ snapshot: MCPIntentClusterSnapshotApi+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpToolIntentsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ tool: (snapshot: MCPIntentClusterSnapshotApi) => MCPToolPivotApi | null+ clusters: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPIntentClusterApi[]+ hasSnapshot: (snapshot: MCPIntentClusterSnapshotApi) => boolean+ }+}++export type mcpToolIntentsLogicType = MakeLogicType<+ mcpToolIntentsLogicValues,+ mcpToolIntentsLogicActions,+ MCPToolIntentsLogicProps,+ mcpToolIntentsLogicMeta+>++/**+ * One tool's slice of the intent cluster snapshot, for the tool detail page.+ *+ * Separate from mcpClusteringLogic on purpose: that logic loads the whole+ * snapshot — every cluster plus every tool's pivot — and starts a poll while a+ * run is computing. Mounting it to render one section made every tool page view+ * pay for the entire blob, so this asks the API for the tool's slice instead.+ */+export const mcpToolIntentsLogic = kea<mcpToolIntentsLogicType>([+ path(['products', 'mcp_analytics', 'frontend', 'clustering', 'mcpToolIntentsLogic']),+ key((props: MCPToolIntentsLogicProps) => props.toolName),+ props({} as MCPToolIntentsLogicProps),+ connect(() => ({+ values: [teamLogic, ['currentProjectId']],+ })),+ loaders(({ props, values }) => ({+ snapshot: [+ EMPTY_SNAPSHOT as MCPIntentClusterSnapshotApi,+ {+ loadSnapshot: async () => {+ if (!values.currentProjectId) {+ return EMPTY_SNAPSHOT+ }+ const response = await mcpAnalyticsIntentClustersRetrieve(String(values.currentProjectId), {+ tool: props.toolName,+ })+ return normalizeSnapshot(response)+ },+ },+ ],+ })),+ selectors({+ tool: [+ (s) => [s.snapshot],+ (snapshot: MCPIntentClusterSnapshotApi): MCPToolPivotApi | null => snapshot.tools?.[0] ?? null,+ ],+ clusters: [+ (s) => [s.snapshot],+ (snapshot: MCPIntentClusterSnapshotApi): readonly MCPIntentClusterApi[] => snapshot.clusters,+ ],+ hasSnapshot: [+ (s) => [s.snapshot],+ (snapshot: MCPIntentClusterSnapshotApi): boolean => snapshot.last_computed_at !== null,+ ],+ }),+ afterMount(({ actions }) => {+ actions.loadSnapshot()+ }),+])diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.tsindex 0d58a6705354..20c1360150ca 100644--- a/products/mcp_analytics/frontend/generated/api.schemas.ts+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts@@ -200,6 +200,22 @@ export interface MCPIntentClusterJourneyApi {readonly leak: MCPIntentClusterJourneyPathApi | null}+export interface MCPClusterSwitchApi {+ /** Tool whose errored call the agent abandoned. */+ readonly from_tool: string+ /** Different tool the agent tried immediately after. */+ readonly to_tool: string+ /** How many times this exact error-then-switch happened within the cluster. */+ readonly count: number+}++export interface MCPClusterSelfRetryApi {+ /** Tool the agent retried immediately after its own error. */+ readonly tool: string+ /** Number of immediate same-tool retries after an error. */+ readonly count: number+}+export interface MCPIntentClusterApi {/** Stable cluster identifier within this snapshot. */readonly id: number@@ -223,6 +239,84 @@ export interface MCPIntentClusterApi {readonly sample_intents: readonly string[]/** Top Sankey-shaped paths the agents took within this cluster. Each path is up to four ordered tool calls plus a completed/error outcome. Null when journey data is unavailable. */readonly journey: MCPIntentClusterJourneyApi | null+ /** Errored call immediately followed by a different tool for the same intent: the strongest evidence agents mix the tools up. Top 10 by count. */+ readonly switches: readonly MCPClusterSwitchApi[]+ /** Errored call immediately retried with the same tool. Top 5 by count. */+ readonly self_retries: readonly MCPClusterSelfRetryApi[]+}++export interface MCPToolPivotCompetitorApi {+ /** The other tool with the largest share of this cluster's calls. */+ readonly tool: string+ /** That competitor's share of the cluster's calls, 0-100. */+ readonly pct: number+}++export interface MCPToolPivotClusterEntryApi {+ /** Cluster this entry refers to, within the snapshot. The cluster's own label, totals, and entropy live on that cluster — join on this id rather than expecting them here. */+ readonly cluster_id: number+ /** Calls routed to this tool for this intent cluster. */+ readonly calls: number+ /** Share of the cluster's calls this tool captured, 0-100. Low capture on a well-fitting description suggests agents are not finding the tool for this intent. */+ readonly capture_pct: number+ /** This tool's position in the cluster's tool distribution; 1 is the cluster's top tool. */+ readonly rank: number+ /**+ * Cosine similarity between the tool's description embedding and the cluster centroid, -1 to 1. Null when no description has been captured for the tool.+ * @nullable+ */+ readonly description_fit: number | null+ /** The strongest other tool in this cluster. Null when this tool is the only one. */+ readonly top_competitor: MCPToolPivotCompetitorApi | null+}++export interface MCPToolPivotApi {+ /** Effective MCP tool name. */+ readonly tool: string+ /** Intent-attributed calls to this tool across the sampled corpus, counting every cluster the run produced — including clusters the snapshot's cluster cap left out. */+ readonly call_count: number+ /** Errored attributed calls across the corpus. */+ readonly error_count: number+ /** Sampled sessions with at least one intent-attributed call to this tool. Same population as call_count. */+ readonly session_count: number+ /**+ * Call-weighted mean routing entropy of the clusters this tool serves, 0-1. High means the tool's intents are regularly split with other tools. Null when the tool has no attributed calls.+ * @nullable+ */+ readonly contested_score: number | null+ /** Sampled sessions whose tools-list catalog included this tool. Only sessions with an observed $mcp_tools_list event count. */+ readonly advertised_sessions: number+ /** Of the advertised sessions, how many actually called the tool. */+ readonly called_when_advertised: number+ /**+ * called_when_advertised / advertised_sessions as a percentage. Null when the tool was advertised in fewer than 5 sampled sessions, which is not enough signal to compute a rate.+ * @nullable+ */+ readonly discovery_rate_pct: number | null+ /**+ * Latest description observed for the tool (clipped to 512 characters). Null when calls never carried one.+ * @nullable+ */+ readonly description: string | null+ /** How many intent clusters this tool serves in total, before the per-tool entry cap. Compare against len(clusters) to tell whether the entry list below is complete. */+ readonly n_clusters_served: number+ /** Intent clusters this tool serves, by call volume desc, capped at 20 and limited to clusters the snapshot carries. Use n_clusters_served for the true count. */+ readonly clusters: readonly MCPToolPivotClusterEntryApi[]+}++export interface MCPToolOverlapApi {+ /** First tool of the pair (lexicographic order). */+ readonly tool_a: string+ /** Second tool of the pair. */+ readonly tool_b: string+ /** Sum over shared clusters of the smaller tool's calls: the volume both tools plausibly compete for. */+ readonly contested_calls: number+ /** Sampled sessions that called both tools. High relative to sessions_with_either suggests the pair is a workflow, not confusion. */+ readonly sessions_with_both: number+ /** Sampled sessions that called at least one of the pair. */+ readonly sessions_with_either: number+ /** The cluster contributing the most contested calls for this pair. */+ readonly top_cluster_id: number}export interface MCPIntentClusterSnapshotMetaApi {@@ -234,6 +328,71 @@ export interface MCPIntentClusterSnapshotMetaApi {readonly n_intents: number/** Number of clusters produced by the run. */readonly n_clusters: number+ /**+ * Corpus granularity. 'per_call' when each call was attributed to its own intent; null on snapshots computed before the per-call pipeline.+ * @nullable+ */+ readonly corpus: string | null+ /**+ * Sessions sampled into the corpus. Null on pre-v2 snapshots.+ * @nullable+ */+ readonly sampled_sessions: number | null+ /**+ * Total sessions with tool calls in the lookback window (unsampled).+ * @nullable+ */+ readonly window_sessions: number | null+ /**+ * sampled_sessions / window_sessions as a percentage: how much of the window the corpus represents.+ * @nullable+ */+ readonly session_coverage_pct: number | null+ /**+ * Share of the window's calls that carried an $mcp_intent. Low coverage makes capture rates less reliable.+ * @nullable+ */+ readonly intent_coverage_pct: number | null+ /**+ * Share of attributed calls whose intent was carried forward from an earlier call in the session rather than stated on the call itself.+ * @nullable+ */+ readonly imputed_call_pct: number | null+ /**+ * Share of sampled calls with no attributable intent (before the session's first stated intent). These calls are excluded from clusters.+ * @nullable+ */+ readonly unattributed_call_pct: number | null+ /**+ * Share of attributed calls whose intent made the top-N cut that feeds clustering.+ * @nullable+ */+ readonly corpus_call_coverage_pct: number | null+ /**+ * Share of sampled sessions with an observed $mcp_tools_list catalog. Discovery rates only draw on those sessions.+ * @nullable+ */+ readonly advertisement_coverage_pct: number | null+ /**+ * Tools included in the tool pivot.+ * @nullable+ */+ readonly n_tools: number | null+ /**+ * Tools dropped from the pivot by the volume cap. Zero means the pivot is complete.+ * @nullable+ */+ readonly dropped_tools: number | null+ /**+ * Overlap pairs dropped by the pair cap.+ * @nullable+ */+ readonly dropped_overlap_pairs: number | null+ /**+ * Share of pivot tools with a captured description. Description fit is only available for those.+ * @nullable+ */+ readonly description_coverage_pct: number | null}export interface MCPIntentClusterSnapshotApi {@@ -254,7 +413,11 @@ export interface MCPIntentClusterSnapshotApi {readonly last_computed_by_email: string/** All clusters in the snapshot. */readonly clusters: readonly MCPIntentClusterApi[]- /** Settings used to produce the snapshot. Null when no snapshot has been computed yet. */+ /** Tool-centric pivot of the clusters: per tool, the intents it serves, capture per cluster, contested score, discovery rate, and description fit. Empty on snapshots computed before the per-call pipeline; recompute to populate. */+ readonly tools: readonly MCPToolPivotApi[]+ /** Tool pairs competing for the same intent clusters, by contested call volume desc, capped at 50. */+ readonly tool_overlaps: readonly MCPToolOverlapApi[]+ /** Settings and coverage of the snapshot's corpus. Null when no snapshot has been computed yet. */readonly computed_with: MCPIntentClusterSnapshotMetaApi | null}@@ -481,6 +644,13 @@ export type McpAnalyticsFeedbackListParams = {offset?: number}+export type McpAnalyticsIntentClustersRetrieveParams = {+ /**+ * Narrow the response to one tool: its pivot entry, the clusters it serves or switches with, and the overlap pairs it belongs to. Coverage meta stays whole-snapshot. Use this for single-tool views so they don't download every cluster and pivot to render one row. An unknown tool returns empty sections, not a 404.+ */+ tool?: string+}+export type McpAnalyticsMissingCapabilitiesListParams = {/*** Number of results to return per page.diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.tsindex b65e816b9c5c..d74428a3890e 100644--- a/products/mcp_analytics/frontend/generated/api.ts+++ b/products/mcp_analytics/frontend/generated/api.ts@@ -17,6 +17,7 @@ import type {MCPMissingCapabilityCreateApi,MCPSessionIntentApi,McpAnalyticsFeedbackListParams,+ McpAnalyticsIntentClustersRetrieveParams,McpAnalyticsMissingCapabilitiesListParams,McpAnalyticsSessionsGenerateIntentParams,McpAnalyticsSessionsListParams,@@ -76,8 +77,23 @@ export const mcpAnalyticsFeedbackCreate = async (})}-export const getMcpAnalyticsIntentClustersRetrieveUrl = (projectId: string) => {- return `/api/projects/${projectId}/mcp_analytics/intent_clusters/`+export const getMcpAnalyticsIntentClustersRetrieveUrl = (+ projectId: string,+ params?: McpAnalyticsIntentClustersRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/mcp_analytics/intent_clusters/?${stringifiedParams}`+ : `/api/projects/${projectId}/mcp_analytics/intent_clusters/`}/**@@ -85,9 +101,10 @@ export const getMcpAnalyticsIntentClustersRetrieveUrl = (projectId: string) => {*/export const mcpAnalyticsIntentClustersRetrieve = async (projectId: string,+ params?: McpAnalyticsIntentClustersRetrieveParams,options?: RequestInit): Promise<MCPIntentClusterSnapshotApi[]> => {- return apiMutator<MCPIntentClusterSnapshotApi[]>(getMcpAnalyticsIntentClustersRetrieveUrl(projectId), {+ return apiMutator<MCPIntentClusterSnapshotApi[]>(getMcpAnalyticsIntentClustersRetrieveUrl(projectId, params), {...options,method: 'GET',})diff --git a/products/mcp_analytics/mcp/tools.yaml b/products/mcp_analytics/mcp/tools.yamlindex 24dc3f864b8d..f704098a1a9f 100644--- a/products/mcp_analytics/mcp/tools.yaml+++ b/products/mcp_analytics/mcp/tools.yaml@@ -20,8 +20,9 @@ tools:idempotent: falsetitle: Recompute intent clustersdescription: >- Trigger an asynchronous recompute of the intent-cluster snapshot: embed the project's recorded agent intents- and re-cluster them. Returns immediately with status 'computing'; poll+ Trigger an asynchronous recompute of the intent-cluster snapshot: sample recent sessions, attribute each+ tool call to its own agent intent, embed and cluster the intents, and derive the tool pivot (capture rates,+ discovery rates, description fit, overlaps). Returns immediately with status 'computing'; pollmcp-analytics-intent-clusters-retrieve for progress (status becomes 'idle' or 'error').requires_ai_consent: truefeature_flag: mcp-analytics@@ -36,9 +37,13 @@ tools:idempotent: truetitle: Get intent cluster snapshotdescription: >- Return the most recent intent-clustering snapshot for the project: clusters of similar agent intents, each- with its tool distribution, error rate, routing entropy, and journey paths. Returns an empty idle snapshot- when no clustering run has happened yet — trigger one with mcp-analytics-intent-clusters-recompute.+ Return the most recent intent-clustering snapshot for the project: clusters of similar agent intents (tool+ distribution, error rate, routing entropy, journey paths, error switches) plus a tool-centric pivot (per+ tool: the intent clusters it serves with capture share and rank, discovery rate against the advertised+ tools-list catalog, description-to-intent fit, contested score) and tool-overlap pairs competing for the+ same intents. computed_with carries sample-coverage percentages; treat counts as sample statistics. Returns+ an empty idle snapshot when no clustering run has happened yet — trigger one with+ mcp-analytics-intent-clusters-recompute.feature_flag: mcp-analyticsmcp-analytics-sessions-activity-overview:operation: mcp_analytics_sessions_activity_overviewdiff --git a/products/mcp_analytics/skills/exploring-mcp-intent-clusters/SKILL.md b/products/mcp_analytics/skills/exploring-mcp-intent-clusters/SKILL.mdindex d1c3bad1640c..219c91da42fa 100644--- a/products/mcp_analytics/skills/exploring-mcp-intent-clusters/SKILL.md+++ b/products/mcp_analytics/skills/exploring-mcp-intent-clusters/SKILL.md@@ -2,19 +2,27 @@name: exploring-mcp-intent-clustersdescription: >Explore PostHog MCP intent clusters — agent goals grouped by semantic- similarity, with each cluster's tool distribution and error rates. Use when the- user asks "what are agents trying to do with the MCP?", "group the intents",- "which goals fail most?", "what does each cluster route to?", wants to- recompute the clustering, or pastes an MCP analytics intent-clustering URL.+ similarity, with each cluster's tool distribution and error rates, plus the+ tool-centric pivot (capture rate per intent, discovery rate against the+ advertised catalog, description fit, tool overlaps). Use when the user asks+ "what are agents trying to do with the MCP?", "group the intents", "which+ goals fail most?", "what does each cluster route to?", "when agents have this+ intent do they find my tool?", "which tools get mixed up?", wants to recompute+ the clustering, or pastes an MCP analytics intent-clustering URL.---# Exploring MCP intent clustersIntent clustering takes the free-text `$mcp_intent` values agents attach totheir tool calls, embeds them, and groups semantically similar goals into-clusters. Each cluster carries its tool distribution, call counts, and error-rates — answering "what are people _trying_ to do, and does it work?" rather-than "which tool was called".+clusters. Attribution is per call: each call is credited to its own intent+(calls without one inherit the most recent prior intent in the same session),+so a tool's counts reflect the intent it actually served. Each cluster carries+its tool distribution, call counts, and error rates — answering "what are+people _trying_ to do, and does it work?" rather than "which tool was called".+The snapshot also carries a tool-centric pivot answering the reverse question:+for a given tool, which intents drive its usage, how often do agents find it,+and who does it compete with.Unlike tool quality and sessions (which ultimately aggregate `$mcp_tool_call`),clustering needs embeddings and is **not expressible in SQL**. It is served by@@ -35,10 +43,15 @@ posthog:mcp-analytics-intent-clusters-retrieve```Returns a snapshot with `status`, `last_computed_at`, `computed_with` (the-embedding model and clustering parameters), and a `clusters` array. Each cluster-has a `label`, `intent_count`, `call_count`, `error_count`, `error_rate_pct`,-`routing_entropy`, a `tool_distribution` (which tools that goal routes to, with-per-tool error rates), and `sample_intents`.+embedding model, clustering parameters, and sample-coverage percentages), a+`clusters` array, a `tools` array (the tool pivot), and `tool_overlaps`. Each+cluster has a `label`, `intent_count`, `call_count`, `error_count`,+`error_rate_pct`, `routing_entropy`, a `tool_distribution` (which tools that+goal routes to, with per-tool error rates), `sample_intents`, plus `switches`+(errored call immediately followed by a different tool for the same intent —+the strongest "agents mix these tools up" evidence) and `self_retries`+(errored call immediately retried with the same tool — a sign the tool's+error messages aren't helping agents self-correct).Read clusters by `call_count` for "what are agents mostly doing", or by`error_rate_pct` for "which goals are failing" — a high error rate on a cluster@@ -48,6 +61,54 @@ points at a class of agent goals the tools serve badly.one goal reliably maps to one tool; high entropy means agents are casting aroundfor the right tool for that goal (often a missing-capability signal).+## Workflow: answer "is my tool discoverable?" from the tool pivot++Each entry in `tools` carries:++- `clusters` — the intent clusters the tool serves, each with `capture_pct`+ (its share of the cluster's calls), `rank`, `top_competitor` (the strongest+ other tool and its share), and `description_fit` (cosine similarity between+ the tool's description and the cluster centroid; null until descriptions are+ captured). Entries carry only `cluster_id`, not the cluster's own label or+ totals — join them against the top-level `clusters` array on that id+- `n_clusters_served` — how many clusters the tool serves in total. The entry+ list above is capped, so compare the two before saying "this tool serves N+ intents"+- `discovery_rate_pct` — of the sampled sessions whose `$mcp_tools_list`+ catalog advertised the tool, the share that actually called it; null when the+ tool was advertised in fewer than 5 sampled sessions+- `contested_score` — call-weighted mean entropy of its clusters: how often its+ intents are split with other tools++High `description_fit` with low `capture_pct` is the discoverability failure:+agents should find the tool for that intent but pick something else. Low fit+with high capture means the description undersells what the tool actually does.+`tool_overlaps` lists pairs competing for the same intents; use+`sessions_with_both` vs `sessions_with_either` to separate workflows (used+together) from confusion (one or the other).++Read coverage before quoting numbers: `computed_with.sampled_sessions` /+`session_coverage_pct` say how much of the window the corpus represents, and+`advertisement_coverage_pct` bounds what discovery rates can see. Only sessions+with an observed tools-list catalog enter discovery denominators, and sessions+in exec-wrapper mode advertise only the wrapper, so per-tool discovery is+measured on full-catalog sessions.++`computed_with` is not a completeness check for everything, though. Only the+top-level tool and overlap-pair caps report what they dropped, via+`dropped_tools` and `dropped_overlap_pairs`. The per-cluster lists are capped+silently, so treat a cluster showing 10 switches or 5 self-retries as "at least+that many", not "exactly". A tool's cluster entries are capped too, but there+`n_clusters_served` gives you the real count.++Clustering reads events only. The on-demand session summaries+(`MCPSession.intent`, what "generate intent" writes) are deliberately left out:+a summary describes a whole session, and spreading it across that session's+calls is the mis-attribution the per-call corpus exists to remove. So a session+whose intent was only ever summarised is not in any cluster — check+`intent_coverage_pct` for how much of the window that leaves out, and read+session summaries directly when you need them.+## Workflow: handle an empty or stale snapshot- **Empty / idle with no clusters** (`status: idle`, `clusters: []`): no run hasdiff --git a/products/mcp_analytics/skills/improving-mcp-tools/SKILL.md b/products/mcp_analytics/skills/improving-mcp-tools/SKILL.mdindex 8510938c54ff..cb71204fbddf 100644--- a/products/mcp_analytics/skills/improving-mcp-tools/SKILL.md+++ b/products/mcp_analytics/skills/improving-mcp-tools/SKILL.md@@ -92,7 +92,12 @@ These are not suggestions; violating any of them ends the campaign pass.## Failure modes to expect- A description change that helps one intent can steal traffic from the right- tool for another — that's why the no-regression sample is mandatory.+ tool for another — that's why the no-regression sample is mandatory. The+ intent-cluster snapshot's `tool_overlaps` (see+ [`exploring-mcp-intent-clusters`](../exploring-mcp-intent-clusters/SKILL.md))+ lists exactly which pairs compete for which intents: snapshot it before a+ description rewrite and recompute after, and treat a capture shift in an+ overlapping pair as the regression signal.- Probe latency varies with stack warmth; compare medians across ≥3 runsbefore attributing a latency change to your fix.- Tool-presence misses can be feature-flag gating, not catalog absence —diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.mdindex 2a2d1c7e8391..5f7caa46025f 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md@@ -51,7 +51,7 @@ And two tools cover what SQL can't express at all: `posthog:mcp-analytics-intent| `$mcp_intent` | The agent's stated intent for the call, when supplied. || `$mcp_client_name` | Raw client string (e.g. `claude-code/1.2.3`). Bucketed into harnesses **server-side** by `products/mcp_analytics/backend/mcp_harness.py` (`HARNESS_TOKEN_SQL` / `harness_label_sql`) — the single source of truth. The frontend only maps the resolved label to a logo. There is no `category` column. || `$mcp_tool_category` | Tool category, when tagged. |-| `$mcp_tool_description` | Tool description as seen by the agent (revisions over time). |+| `$mcp_tool_description` | Tool description as seen by the agent (revisions over time), clipped to 512 chars on capture. Gap warning: the hono migration silently dropped this stamp, so there is a window (roughly Jun–Jul 2026) with no descriptions on PostHog's hosted server; `notEmpty(...)` filters are mandatory. |**Effective tool name.** New-SDK events wrap the real tool in a single-exec call, so to filter/group by the tool the agent actually invoked, use:@@ -59,6 +59,14 @@ And two tools cover what SQL can't express at all: `posthog:mcp-analytics-intentcoalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name))```+**The advertised catalog: `$mcp_tools_list`.** Each tools/list response emits a `$mcp_tools_list` event whose `$mcp_listed_tool_names` property holds the advertised tool names as a JSON array, with `tool_count` alongside. This is the denominator for "advertised but never called" analysis. Only about half of tool-call sessions carry a tools-list event, and sessions in exec-wrapper mode advertise just the wrapper (`['exec', 'render-ui']`), so condition per-tool discovery cuts on sessions where the catalog was actually observed. Extract the array with:++```sql+JSONExtract(coalesce(toString(properties.$mcp_listed_tool_names), '[]'), 'Array(String)')+```++The `coalesce(..., '[]')` is required: the property accessor is Nullable, and `JSONExtract` of a Nullable into `Array(String)` is a ClickHouse type error.+**Failures with detail.** `$mcp_tool_call` carries `$mcp_is_error` plus a semantic `$mcp_error_type` and, for HTTP failures, `$mcp_error_status`. `posthog:query-mcp-tool-failures` groups errored tool calls by these two fields and returns each bucket's raw `error_type`/`error_status`; pass those to `posthog:query-mcp-tool-failure-occurrences` for individual errored calls with the free-text `$mcp_error_message` (sanitized, truncated to 2048 chars — empty on events captured before PostHog's server started emitting it). `$mcp_response` stays empty on PostHog's hosted server. PostHog's own tool calls also don't emit `$exception` events — those only exist for separately-instrumented MCP servers.## Example queriesdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex f4b1f09fb551..ffb9df41ddb5 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6191,7 +6191,7 @@"feature_flag": "marketing-analytics-mcp"},"mcp-analytics-intent-clusters-recompute": {- "description": "Trigger an asynchronous recompute of the intent-cluster snapshot: embed the project's recorded agent intents and re-cluster them. Returns immediately with status 'computing'; poll mcp-analytics-intent-clusters-retrieve for progress (status becomes 'idle' or 'error').",+ "description": "Trigger an asynchronous recompute of the intent-cluster snapshot: sample recent sessions, attribute each tool call to its own agent intent, embed and cluster the intents, and derive the tool pivot (capture rates, discovery rates, description fit, overlaps). Returns immediately with status 'computing'; poll mcp-analytics-intent-clusters-retrieve for progress (status becomes 'idle' or 'error').","category": "MCP analytics","feature": "mcp_analytics","summary": "Recompute intent clusters",@@ -6207,7 +6207,7 @@"feature_flag": "mcp-analytics"},"mcp-analytics-intent-clusters-retrieve": {- "description": "Return the most recent intent-clustering snapshot for the project: clusters of similar agent intents, each with its tool distribution, error rate, routing entropy, and journey paths. Returns an empty idle snapshot when no clustering run has happened yet — trigger one with mcp-analytics-intent-clusters-recompute.",+ "description": "Return the most recent intent-clustering snapshot for the project: clusters of similar agent intents (tool distribution, error rate, routing entropy, journey paths, error switches) plus a tool-centric pivot (per tool: the intent clusters it serves with capture share and rank, discovery rate against the advertised tools-list catalog, description-to-intent fit, contested score) and tool-overlap pairs competing for the same intents. computed_with carries sample-coverage percentages; treat counts as sample statistics. Returns an empty idle snapshot when no clustering run has happened yet — trigger one with mcp-analytics-intent-clusters-recompute.","category": "MCP analytics","feature": "mcp_analytics","summary": "Get intent cluster snapshot",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 91b16a6fe878..b05b23d38f78 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6641,7 +6641,7 @@"feature_flag": "marketing-analytics-mcp"},"mcp-analytics-intent-clusters-recompute": {- "description": "Trigger an asynchronous recompute of the intent-cluster snapshot: embed the project's recorded agent intents and re-cluster them. Returns immediately with status 'computing'; poll mcp-analytics-intent-clusters-retrieve for progress (status becomes 'idle' or 'error').",+ "description": "Trigger an asynchronous recompute of the intent-cluster snapshot: sample recent sessions, attribute each tool call to its own agent intent, embed and cluster the intents, and derive the tool pivot (capture rates, discovery rates, description fit, overlaps). Returns immediately with status 'computing'; poll mcp-analytics-intent-clusters-retrieve for progress (status becomes 'idle' or 'error').","category": "MCP analytics","feature": "mcp_analytics","summary": "Recompute intent clusters",@@ -6657,7 +6657,7 @@"feature_flag": "mcp-analytics"},"mcp-analytics-intent-clusters-retrieve": {- "description": "Return the most recent intent-clustering snapshot for the project: clusters of similar agent intents, each with its tool distribution, error rate, routing entropy, and journey paths. Returns an empty idle snapshot when no clustering run has happened yet — trigger one with mcp-analytics-intent-clusters-recompute.",+ "description": "Return the most recent intent-clustering snapshot for the project: clusters of similar agent intents (tool distribution, error rate, routing entropy, journey paths, error switches) plus a tool-centric pivot (per tool: the intent clusters it serves with capture share and rank, discovery rate against the advertised tools-list catalog, description-to-intent fit, contested score) and tool-overlap pairs competing for the same intents. computed_with carries sample-coverage percentages; treat counts as sample statistics. Returns an empty idle snapshot when no clustering run has happened yet — trigger one with mcp-analytics-intent-clusters-recompute.","category": "MCP analytics","feature": "mcp_analytics","summary": "Get intent cluster snapshot",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6c67277b9ee4..48c26571e26e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -40218,6 +40218,22 @@ export namespace Schemas {Oauth: 'oauth',} as const;+ export interface MCPClusterSelfRetry {+ /** Tool the agent retried immediately after its own error. */+ readonly tool: string;+ /** Number of immediate same-tool retries after an error. */+ readonly count: number;+ }++ export interface MCPClusterSwitch {+ /** Tool whose errored call the agent abandoned. */+ readonly from_tool: string;+ /** Different tool the agent tried immediately after. */+ readonly to_tool: string;+ /** How many times this exact error-then-switch happened within the cluster. */+ readonly count: number;+ }+/*** * `results` - Results* * `usability` - Usability@@ -40446,6 +40462,10 @@ export namespace Schemas {readonly sample_intents: readonly string[];/** Top Sankey-shaped paths the agents took within this cluster. Each path is up to four ordered tool calls plus a completed/error outcome. Null when journey data is unavailable. */readonly journey: MCPIntentClusterJourney | null;+ /** Errored call immediately followed by a different tool for the same intent: the strongest evidence agents mix the tools up. Top 10 by count. */+ readonly switches: readonly MCPClusterSwitch[];+ /** Errored call immediately retried with the same tool. Top 5 by count. */+ readonly self_retries: readonly MCPClusterSelfRetry[];}/**@@ -40462,6 +40482,80 @@ export namespace Schemas {Error: 'error',} as const;+ export interface MCPToolPivotCompetitor {+ /** The other tool with the largest share of this cluster's calls. */+ readonly tool: string;+ /** That competitor's share of the cluster's calls, 0-100. */+ readonly pct: number;+ }++ export interface MCPToolPivotClusterEntry {+ /** Cluster this entry refers to, within the snapshot. The cluster's own label, totals, and entropy live on that cluster — join on this id rather than expecting them here. */+ readonly cluster_id: number;+ /** Calls routed to this tool for this intent cluster. */+ readonly calls: number;+ /** Share of the cluster's calls this tool captured, 0-100. Low capture on a well-fitting description suggests agents are not finding the tool for this intent. */+ readonly capture_pct: number;+ /** This tool's position in the cluster's tool distribution; 1 is the cluster's top tool. */+ readonly rank: number;+ /**+ * Cosine similarity between the tool's description embedding and the cluster centroid, -1 to 1. Null when no description has been captured for the tool.+ * @nullable+ */+ readonly description_fit: number | null;+ /** The strongest other tool in this cluster. Null when this tool is the only one. */+ readonly top_competitor: MCPToolPivotCompetitor | null;+ }++ export interface MCPToolPivot {+ /** Effective MCP tool name. */+ readonly tool: string;+ /** Intent-attributed calls to this tool across the sampled corpus, counting every cluster the run produced — including clusters the snapshot's cluster cap left out. */+ readonly call_count: number;+ /** Errored attributed calls across the corpus. */+ readonly error_count: number;+ /** Sampled sessions with at least one intent-attributed call to this tool. Same population as call_count. */+ readonly session_count: number;+ /**+ * Call-weighted mean routing entropy of the clusters this tool serves, 0-1. High means the tool's intents are regularly split with other tools. Null when the tool has no attributed calls.+ * @nullable+ */+ readonly contested_score: number | null;+ /** Sampled sessions whose tools-list catalog included this tool. Only sessions with an observed $mcp_tools_list event count. */+ readonly advertised_sessions: number;+ /** Of the advertised sessions, how many actually called the tool. */+ readonly called_when_advertised: number;+ /**+ * called_when_advertised / advertised_sessions as a percentage. Null when the tool was advertised in fewer than 5 sampled sessions, which is not enough signal to compute a rate.+ * @nullable+ */+ readonly discovery_rate_pct: number | null;+ /**+ * Latest description observed for the tool (clipped to 512 characters). Null when calls never carried one.+ * @nullable+ */+ readonly description: string | null;+ /** How many intent clusters this tool serves in total, before the per-tool entry cap. Compare against len(clusters) to tell whether the entry list below is complete. */+ readonly n_clusters_served: number;+ /** Intent clusters this tool serves, by call volume desc, capped at 20 and limited to clusters the snapshot carries. Use n_clusters_served for the true count. */+ readonly clusters: readonly MCPToolPivotClusterEntry[];+ }++ export interface MCPToolOverlap {+ /** First tool of the pair (lexicographic order). */+ readonly tool_a: string;+ /** Second tool of the pair. */+ readonly tool_b: string;+ /** Sum over shared clusters of the smaller tool's calls: the volume both tools plausibly compete for. */+ readonly contested_calls: number;+ /** Sampled sessions that called both tools. High relative to sessions_with_either suggests the pair is a workflow, not confusion. */+ readonly sessions_with_both: number;+ /** Sampled sessions that called at least one of the pair. */+ readonly sessions_with_either: number;+ /** The cluster contributing the most contested calls for this pair. */+ readonly top_cluster_id: number;+ }+export interface MCPIntentClusterSnapshotMeta {/** Cosine distance threshold used by the clustering algorithm. */readonly distance_threshold: number;@@ -40471,6 +40565,71 @@ export namespace Schemas {readonly n_intents: number;/** Number of clusters produced by the run. */readonly n_clusters: number;+ /**+ * Corpus granularity. 'per_call' when each call was attributed to its own intent; null on snapshots computed before the per-call pipeline.+ * @nullable+ */+ readonly corpus: string | null;+ /**+ * Sessions sampled into the corpus. Null on pre-v2 snapshots.+ * @nullable+ */+ readonly sampled_sessions: number | null;+ /**+ * Total sessions with tool calls in the lookback window (unsampled).+ * @nullable+ */+ readonly window_sessions: number | null;+ /**+ * sampled_sessions / window_sessions as a percentage: how much of the window the corpus represents.+ * @nullable+ */+ readonly session_coverage_pct: number | null;+ /**+ * Share of the window's calls that carried an $mcp_intent. Low coverage makes capture rates less reliable.+ * @nullable+ */+ readonly intent_coverage_pct: number | null;+ /**+ * Share of attributed calls whose intent was carried forward from an earlier call in the session rather than stated on the call itself.+ * @nullable+ */+ readonly imputed_call_pct: number | null;+ /**+ * Share of sampled calls with no attributable intent (before the session's first stated intent). These calls are excluded from clusters.+ * @nullable+ */+ readonly unattributed_call_pct: number | null;+ /**+ * Share of attributed calls whose intent made the top-N cut that feeds clustering.+ * @nullable+ */+ readonly corpus_call_coverage_pct: number | null;+ /**+ * Share of sampled sessions with an observed $mcp_tools_list catalog. Discovery rates only draw on those sessions.+ * @nullable+ */+ readonly advertisement_coverage_pct: number | null;+ /**+ * Tools included in the tool pivot.+ * @nullable+ */+ readonly n_tools: number | null;+ /**+ * Tools dropped from the pivot by the volume cap. Zero means the pivot is complete.+ * @nullable+ */+ readonly dropped_tools: number | null;+ /**+ * Overlap pairs dropped by the pair cap.+ * @nullable+ */+ readonly dropped_overlap_pairs: number | null;+ /**+ * Share of pivot tools with a captured description. Description fit is only available for those.+ * @nullable+ */+ readonly description_coverage_pct: number | null;}export interface MCPIntentClusterSnapshot {@@ -40491,7 +40650,11 @@ export namespace Schemas {readonly last_computed_by_email: string;/** All clusters in the snapshot. */readonly clusters: readonly MCPIntentCluster[];- /** Settings used to produce the snapshot. Null when no snapshot has been computed yet. */+ /** Tool-centric pivot of the clusters: per tool, the intents it serves, capture per cluster, contested score, discovery rate, and description fit. Empty on snapshots computed before the per-call pipeline; recompute to populate. */+ readonly tools: readonly MCPToolPivot[];+ /** Tool pairs competing for the same intent clusters, by contested call volume desc, capped at 50. */+ readonly tool_overlaps: readonly MCPToolOverlap[];+ /** Settings and coverage of the snapshot's corpus. Null when no snapshot has been computed yet. */readonly computed_with: MCPIntentClusterSnapshotMeta | null;}@@ -81299,6 +81462,13 @@ export namespace Schemas {offset?: number;};+ export type McpAnalyticsIntentClustersRetrieveParams = {+ /**+ * Narrow the response to one tool: its pivot entry, the clusters it serves or switches with, and the overlap pairs it belongs to. Coverage meta stays whole-snapshot. Use this for single-tool views so they don't download every cluster and pivot to render one row. An unknown tool returns empty sections, not a 404.+ */+ tool?: string;+ };+export type McpAnalyticsMissingCapabilitiesListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/cli/tool-call-properties.ts b/services/mcp/src/cli/tool-call-properties.tsindex 175b7d19faf7..d9392a67fb9b 100644--- a/services/mcp/src/cli/tool-call-properties.ts+++ b/services/mcp/src/cli/tool-call-properties.ts@@ -1,22 +1,29 @@import type { ExecInnerCallProperties } from '@/tools/exec'+import { getToolCategory, getToolDescription } from '@/tools/toolDefinitions'/*** `$mcp_tool_call` properties for the CLI. Value-free by design: raw error* messages and inputs can carry caller-supplied content and API response* bodies, which must never reach usage analytics. Mirrors the hosted server,* whose tool-call events carry only the error flag — plus a bounded- * classification so failures stay diagnosable.+ * classification so failures stay diagnosable. Category and clipped+ * description come from the tool catalog (never the caller), matching the+ * hosted server's stamps so per-tool analytics see one schema.*/export function buildToolCallProperties(toolName: string,properties: ExecInnerCallProperties): Record<string, unknown> {+ const category = getToolCategory(toolName)+ const description = getToolDescription(toolName)return {tool_name: toolName,$mcp_tool_name: toolName,$mcp_duration_ms: properties.duration_ms,$mcp_is_error: !properties.success,output_format: properties.output_format,+ ...(category ? { $mcp_tool_category: category } : {}),+ ...(description ? { $mcp_tool_description: description } : {}),...(properties.success ? {} : { error_class: errorClass(properties) }),...(properties.error_status !== undefined ? { error_status: properties.error_status } : {}),}diff --git a/services/mcp/src/generated/mcp_analytics/api.ts b/services/mcp/src/generated/mcp_analytics/api.tsindex fe309a35c04d..b676e62afd1b 100644--- a/services/mcp/src/generated/mcp_analytics/api.ts+++ b/services/mcp/src/generated/mcp_analytics/api.ts@@ -112,6 +112,15 @@ export const McpAnalyticsIntentClustersRetrieveParams = /* @__PURE__ */ zod.obje),})+export const McpAnalyticsIntentClustersRetrieveQueryParams = /* @__PURE__ */ zod.object({+ tool: zod+ .string()+ .optional()+ .describe(+ "Narrow the response to one tool: its pivot entry, the clusters it serves or switches with, and the overlap pairs it belongs to. Coverage meta stays whole-snapshot. Use this for single-tool views so they don't download every cluster and pivot to render one row. An unknown tool returns empty sections, not a 404."+ ),+})+/*** Trigger an asynchronous recompute of the intent cluster snapshot. The task runs in the background; poll the GET endpoint for progress (status transitions to 'idle' or 'error').*/diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 6eea5501a662..16a18bb462c0 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -11,7 +11,7 @@ import {type MCPAnalyticsContext,} from '@/lib/posthog/analytics'import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'-import { getToolCategory } from '@/tools/toolDefinitions'+import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolCategory, getToolDescription } from '@/tools/toolDefinitions'import { buildMCPSessionAnalyticsProperties } from './mcp-context'import type { ResolvedState } from './request-state-resolver'@@ -104,7 +104,8 @@ export async function trackToolCall(isError: boolean,state: ResolvedState,extraProperties?: Record<string, unknown>,- intentMeta?: ToolCallIntentMeta+ intentMeta?: ToolCallIntentMeta,+ servedDescription?: string): Promise<void> {try {const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)@@ -117,6 +118,16 @@ export async function trackToolCall(// (it never maps tool→category itself). Omitted when unknown (e.g. the `exec`// wrapper), which the dashboard buckets as "Uncategorized".const toolCategory = getToolCategory(toolName)+ // The description the agent saw when it picked this tool, clipped. Powers the+ // tool-detail Descriptions table and description-vs-intent fit in MCP+ // analytics. Callers pass servedDescription when the advertised text differs+ // from the catalog (execute-sql's is formatted per request); otherwise the+ // catalog text is what was served. Inner exec calls reach here with the+ // resolved inner tool name, so the fallback lands on the inner tool's own+ // description.+ const toolDescription = servedDescription+ ? servedDescription.slice(0, MAX_CAPTURED_DESCRIPTION_LENGTH)+ : getToolDescription(toolName)// Emits `$mcp_tool_call` (+ `$mcp_is_error`). The SDK maps `toolName` →// `$mcp_tool_name`, `durationMs` → `$mcp_duration_ms`, `isError` →@@ -136,6 +147,7 @@ export async function trackToolCall(...properties,tool_name: toolName,...(toolCategory ? { $mcp_tool_category: toolCategory } : {}),+ ...(toolDescription ? { $mcp_tool_description: toolDescription } : {}),...extraProperties,},})diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 3b0b33ff4805..26e5d1c888ee 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -141,6 +141,18 @@ export class ToolExecutor {)}+ // execute-sql is the one tool whose advertised description is formatted per+ // request (the schema-discovery splice varies by feature flag) instead of served+ // from the catalog, on both the native tools/list path and exec's `info` output.+ // trackToolCall stamps the catalog text by default, so it needs the served text+ // for this tool or $mcp_tool_description records words the agent never saw.+ private servedToolDescription(toolName: string, state: ResolvedState): string | undefined {+ if (toolName === EXECUTE_SQL_TOOL_NAME) {+ return this.instructionsBuilder.formatExecuteSqlDescription(state.toolFeatureFlags)+ }+ return undefined+ }+// Pull the agent's stated intent off the injected `context` arg and strip it so// tool schemas/handlers never see it (validation is `.strict()` in places). The// intent rides through to `$mcp_intent` on the captured event. Guarded: analytics@@ -224,7 +236,8 @@ export class ToolExecutor {input_tokens: estimateTokens(validation.data),output_tokens: estimateResponseTokens(response),},- intentMeta+ intentMeta,+ this.servedToolDescription(tool.name, state))if (tool.name === EXECUTE_SQL_TOOL_NAME) {@@ -249,7 +262,8 @@ export class ToolExecutor {true,state,errorAnalyticsProperties(classification, error),- intentMeta+ intentMeta,+ this.servedToolDescription(tool.name, state))if (tool.name === EXECUTE_SQL_TOOL_NAME) {@@ -325,7 +339,8 @@ export class ToolExecutor {input_tokens: estimateTokens(validation.data),output_tokens: estimateResponseTokens(response),},- intentMeta+ intentMeta,+ this.servedToolDescription(execToolName(), state))return response@@ -344,7 +359,8 @@ export class ToolExecutor {true,state,errorAnalyticsProperties(classification, error),- intentMeta+ intentMeta,+ this.servedToolDescription(metricTool, state))const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.tsindex d1013a46adfc..079b7df8529e 100644--- a/services/mcp/src/tools/generated/mcp_analytics.ts+++ b/services/mcp/src/tools/generated/mcp_analytics.ts@@ -4,6 +4,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {McpAnalyticsFeedbackCreateBody,+ McpAnalyticsIntentClustersRetrieveQueryParams,McpAnalyticsMissingCapabilitiesCreateBody,McpAnalyticsSessionsGenerateIntentParams,McpAnalyticsSessionsGenerateIntentQueryParams,@@ -34,7 +35,7 @@ const mcpAnalyticsIntentClustersRecompute = (): ToolBase<},})-const McpAnalyticsIntentClustersRetrieveSchema = z.object({})+const McpAnalyticsIntentClustersRetrieveSchema = McpAnalyticsIntentClustersRetrieveQueryParamsconst mcpAnalyticsIntentClustersRetrieve = (): ToolBase<typeof McpAnalyticsIntentClustersRetrieveSchema,@@ -42,12 +43,14 @@ const mcpAnalyticsIntentClustersRetrieve = (): ToolBase<> => ({name: 'mcp-analytics-intent-clusters-retrieve',schema: McpAnalyticsIntentClustersRetrieveSchema,- // eslint-disable-next-line no-unused-varshandler: async (context: Context, params: z.infer<typeof McpAnalyticsIntentClustersRetrieveSchema>) => {const projectId = await context.stateManager.getProjectId()const result = await context.api.request<Schemas.MCPIntentClusterSnapshot[]>({method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/mcp_analytics/intent_clusters/`,+ query: {+ tool: params.tool,+ },})return result},diff --git a/services/mcp/src/tools/toolDefinitions.ts b/services/mcp/src/tools/toolDefinitions.tsindex b5ef6b91993d..102fb3b52b4f 100644--- a/services/mcp/src/tools/toolDefinitions.ts+++ b/services/mcp/src/tools/toolDefinitions.ts@@ -66,6 +66,7 @@ const toolDefinitionsSchema = z.record(z.string(), ToolDefinitionSchema)let _toolDefinitions: ToolDefinitions | undefined = undefinedlet _generatedToolDefinitions: ToolDefinitions | undefined = undefined+let _mergedToolDefinitions: ToolDefinitions | undefined = undefinedfunction getGeneratedToolDefinitions(): ToolDefinitions {if (!_generatedToolDefinitions) {@@ -74,12 +75,17 @@ function getGeneratedToolDefinitions(): ToolDefinitions {return _generatedToolDefinitions}+// Both sources are immutable module JSON, so the merge is memoised alongside them:+// the analytics hot path calls this twice per tool call (category + description),+// and rebuilding the whole record each time is pure waste.export function getToolDefinitions(): ToolDefinitions {- const generated = getGeneratedToolDefinitions()- if (!_toolDefinitions) {- _toolDefinitions = toolDefinitionsSchema.parse(toolDefinitionsJson)+ if (!_mergedToolDefinitions) {+ if (!_toolDefinitions) {+ _toolDefinitions = toolDefinitionsSchema.parse(toolDefinitionsJson)+ }+ _mergedToolDefinitions = { ..._toolDefinitions, ...getGeneratedToolDefinitions() }}- return { ..._toolDefinitions, ...generated }+ return _mergedToolDefinitions}let _advertisedOAuthScopes: readonly string[] | undefined = undefined@@ -128,6 +134,23 @@ export function getToolCategory(toolName: string): string | undefined {return getToolDefinitions()[toolName]?.category}+/**+ * Catalogued descriptions run to ~13 KB (the query tools embed full usage guides), which+ * is too heavy to stamp on every analytics event. The first 512 characters carry the+ * lead paragraph, which is the part that describes what the tool is for.+ */+export const MAX_CAPTURED_DESCRIPTION_LENGTH = 512++/**+ * The description a tool advertises to agents, clipped for analytics capture, or+ * undefined for tools without a catalogued definition (e.g. the `exec` wrapper).+ * Like {@link getToolCategory} this never throws, so it is safe to call from the+ * analytics hot path where a missing definition must not break the request.+ */+export function getToolDescription(toolName: string): string | undefined {+ return getToolDefinitions()[toolName]?.description?.slice(0, MAX_CAPTURED_DESCRIPTION_LENGTH)+}+export interface ToolFilterOptions {features?: string[] | undefinedtools?: string[] | undefineddiff --git a/services/mcp/tests/cli/tool-call-properties.test.ts b/services/mcp/tests/cli/tool-call-properties.test.tsindex 70ff22093c6d..5769deed9549 100644--- a/services/mcp/tests/cli/tool-call-properties.test.ts+++ b/services/mcp/tests/cli/tool-call-properties.test.ts@@ -2,11 +2,14 @@ import { describe, expect, it } from 'vitest'import { buildToolCallProperties } from '@/cli/tool-call-properties'import type { ExecInnerCallProperties } from '@/tools/exec'+import { getToolCategory, getToolDescription } from '@/tools/toolDefinitions'// The CLI flushes these events on the error path, so anything value-carrying// here (raw error messages, inputs) would ship caller content and API response// bodies to usage analytics. `toEqual` pins the exact shape: reintroducing-// `error_message` or `input` fails every case below.+// `error_message` or `input` fails every case below. Catalog metadata+// (category, clipped description) is safe by construction: it comes from the+// tool registry, never from the caller.describe('buildToolCallProperties', () => {const base: ExecInnerCallProperties = {duration_ms: 42,@@ -16,6 +19,13 @@ describe('buildToolCallProperties', () => {input: { markdown: 'private caller-supplied text' },}+ function catalogMetadata(toolName: string): Record<string, unknown> {+ return {+ $mcp_tool_category: getToolCategory(toolName),+ $mcp_tool_description: getToolDescription(toolName),+ }+ }+it('never forwards error_message or input, only a value-free classification', () => {expect(buildToolCallProperties('notebook-edit', base)).toEqual({tool_name: 'notebook-edit',@@ -24,6 +34,7 @@ describe('buildToolCallProperties', () => {$mcp_is_error: true,output_format: 'text',error_class: 'error',+ ...catalogMetadata('notebook-edit'),})})@@ -37,6 +48,7 @@ describe('buildToolCallProperties', () => {$mcp_duration_ms: 42,$mcp_is_error: true,output_format: 'text',+ ...catalogMetadata('feature-flag-get-all'),...expected,})})@@ -48,6 +60,19 @@ describe('buildToolCallProperties', () => {$mcp_duration_ms: 42,$mcp_is_error: false,output_format: 'text',+ ...catalogMetadata('feature-flag-get-all'),})})++ it('stamps catalog metadata on catalogued tools and omits it for unknown names', () => {+ // The CLI path silently shipped without category or description while the+ // hosted server stamped both; this pins the two paths to the same catalog.+ const catalogued = buildToolCallProperties('feature-flag-get-all', { ...base, success: true })+ expect(catalogued.$mcp_tool_category).toBeTruthy()+ expect(catalogued.$mcp_tool_description).toBeTruthy()++ const unknown = buildToolCallProperties('not-a-real-tool', { ...base, success: true })+ expect(unknown).not.toHaveProperty('$mcp_tool_category')+ expect(unknown).not.toHaveProperty('$mcp_tool_description')+ })})diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex 4b2f67e34149..94c2b5a8b010 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -17,6 +17,7 @@ vi.mock('@/lib/posthog', () => ({import { trackExecuteSqlGeneration, trackInitEvent, trackToolCall } from '@/hono/analytics'import type { ResolvedState } from '@/hono/request-state-resolver'+import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolDefinition } from '@/tools/toolDefinitions'function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {return {@@ -116,16 +117,36 @@ describe('Hono MCP analytics contexts', () => {expect(properties.mcp_session_vendor_client).toBeUndefined()})- it('stamps $mcp_tool_category from the catalogued tool definition', async () => {+ it('stamps $mcp_tool_category and $mcp_tool_description from the catalogued tool definition', async () => {await trackToolCall('query-logs', 5, false, makeState())- expect(mockCaptureToolCall.mock.calls[0]![0].properties.$mcp_tool_category).toBe('Logs')+ const properties = mockCaptureToolCall.mock.calls[0]![0].properties+ expect(properties.$mcp_tool_category).toBe('Logs')+ // query-logs' catalogued description is ~13 KB, so this assertion also locks in+ // the capture-side clip. Description capture died silently once before (the hono+ // migration dropped it while the category stamp survived), so the two are asserted+ // together at the same call site.+ expect(properties.$mcp_tool_description).toBe(+ getToolDefinition('query-logs').description.slice(0, MAX_CAPTURED_DESCRIPTION_LENGTH)+ )+ expect((properties.$mcp_tool_description as string).length).toBe(MAX_CAPTURED_DESCRIPTION_LENGTH)})- it('omits $mcp_tool_category for tools without a catalogued definition', async () => {+ it('omits $mcp_tool_category and $mcp_tool_description for tools without a catalogued definition', async () => {await trackToolCall('exec', 5, false, makeState())expect(mockCaptureToolCall.mock.calls[0]![0].properties).not.toHaveProperty('$mcp_tool_category')+ expect(mockCaptureToolCall.mock.calls[0]![0].properties).not.toHaveProperty('$mcp_tool_description')+ })++ it('prefers the served description over the catalog text, clipped', async () => {+ // execute-sql advertises a per-request formatted description, so stamping+ // the catalog text would record words the agent never saw.+ const served = 'served '.repeat(200)+ await trackToolCall('query-logs', 5, false, makeState(), undefined, undefined, served)++ const properties = mockCaptureToolCall.mock.calls[0]![0].properties+ expect(properties.$mcp_tool_description).toBe(served.slice(0, MAX_CAPTURED_DESCRIPTION_LENGTH))})describe('trackExecuteSqlGeneration', () => {diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex 9d3fd3f13138..8f0b75b583e1 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -26,6 +26,7 @@ import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'import { getPostHogClient } from '@/lib/posthog'+import { MAX_CAPTURED_DESCRIPTION_LENGTH } from '@/tools/toolDefinitions'function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {return {@@ -155,6 +156,43 @@ describe('ToolExecutor intent capture', () => {captureSpy.mockRestore()})+ // execute-sql is the one tool whose advertised description is formatted per+ // request rather than served from the catalog; the stamped+ // $mcp_tool_description must be the formatted text the agent saw. One case+ // per dispatch path, since each wires the served description independently.+ // (Both handlers fail against the harness's empty api; the error path still+ // captures the event, which is the shape being pinned.)+ it.each([+ {+ label: 'native path',+ call: { name: 'execute-sql', arguments: { query: 'SELECT 1' } },+ state: () => makeState([{ name: 'execute-sql' }]),+ },+ {+ label: 'exec path',+ call: { name: 'exec', arguments: { command: 'call execute-sql {"query": "SELECT 1"}' } },+ state: () =>+ makeState(+ catalog.getFilteredTools({ scopes: ['*'] }).filter((tool) => tool.name === 'execute-sql'),+ { useSingleExec: false }+ ),+ },+ ])('stamps the formatted execute-sql description on the $label', async ({ call, state }) => {+ const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})++ await executor.handleToolCall(call, state())++ // trackToolCall is fire-and-forget; wait for the capture to land so the+ // assertion (and the spy restore) never race the pending promise.+ await vi.waitFor(() => expect(captureSpy).toHaveBeenCalledTimes(1))+ const arg = captureSpy.mock.calls[0]![0]+ expect(arg.toolName).toBe('execute-sql')+ const expected = new InstructionsBuilder('').formatExecuteSqlDescription(undefined)+ expect(arg.properties?.$mcp_tool_description).toBe(expected.slice(0, MAX_CAPTURED_DESCRIPTION_LENGTH))++ captureSpy.mockRestore()+ })+// Old-schema / old-client compatibility: an agent that doesn't know about the// injected context arg calls with just the tool's own args. The call is handled// exactly as before (a graceful result, never a thrown error) and no intent is