Skip to content

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

feat(mcp-analytics): add mcp analytics (#58407)

Thomas Obermüllerddfdb4e5cd26
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index adb0ee09a1a8..0935a4ab0b4c 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -165,6 +165,8 @@ rules:
|MessageRecipientPreference
|MessageTemplate
|MCPAnalyticsSubmission
+ |MCPIntentClusterSnapshot
+ |MCPSession
|OptOutSyncConfig
|Node
|NotificationEvent
@@ -384,6 +386,8 @@ rules:
|MessageCategory
|MessageRecipientPreference
|MessageTemplate
+ |MCPIntentClusterSnapshot
+ |MCPSession
|OptOutSyncConfig
|Node
|NotificationEvent
diff --git a/frontend/src/layout/navigation-3000/navigationLogic.tsx b/frontend/src/layout/navigation-3000/navigationLogic.tsx
index defdd38961f5..392cda070f63 100644
--- a/frontend/src/layout/navigation-3000/navigationLogic.tsx
+++ b/frontend/src/layout/navigation-3000/navigationLogic.tsx
@@ -610,6 +610,15 @@ export const navigation3000Logic = kea<navigation3000LogicType>([
to: urls.llmAnalyticsDashboard(),
tooltipDocLink: 'https://posthog.com/docs/llm-analytics/dashboard',
},
+ featureFlags[FEATURE_FLAGS.MCP_ANALYTICS]
+ ? {
+ identifier: 'MCPAnalytics',
+ label: 'MCP analytics',
+ icon: <IconLlmAnalytics />,
+ to: urls.mcpAnalyticsDashboard(),
+ tooltipDocLink: 'https://posthog.com/docs/mcp-analytics/installation',
+ }
+ : null,
{
identifier: Scene.Logs,
label: 'Logs',
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index 4a9ffd192691..6b50dec24ffd 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -48,6 +48,9 @@ import type { projectTreeDataLogicType } from './projectTreeDataLogicType'
const MOVE_ALERT_LIMIT = 50
const DELETE_ALERT_LIMIT = 0
export const PAGINATION_LIMIT = 100
+const PRODUCTS_SHOWN_WITH_SELECTED_PRODUCTS: Record<string, string[]> = {
+ 'LLM analytics': ['MCP analytics'],
+}
// Returns `shortcuts` reordered to match `orderedIds`. Any shortcut not referenced in
// `orderedIds` is appended at the end so a partial input never silently drops items.
@@ -1101,14 +1104,29 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
const allProducts = getDefaultTreeProducts()
const productMap = new Map<string, FileSystemImport>(allProducts.map((p) => [p.path, p]))
const customProductMap = new Map(customProducts.map((item) => [item.product_path, item]))
+ const selectedProductPaths = new Set<string>()
+ const orderedSelectedProductPaths: string[] = []
+
+ for (const item of customProducts) {
+ for (const productPath of [
+ item.product_path,
+ ...(PRODUCTS_SHOWN_WITH_SELECTED_PRODUCTS[item.product_path] ?? []),
+ ]) {
+ if (selectedProductPaths.has(productPath)) {
+ continue
+ }
+ selectedProductPaths.add(productPath)
+ orderedSelectedProductPaths.push(productPath)
+ }
+ }
- const selectedProducts = customProducts
- .map((item) => {
- const product = productMap.get(item.product_path)
+ const selectedProducts = orderedSelectedProductPaths
+ .map((productPath) => {
+ const product = productMap.get(productPath)
if (!product) {
return null
}
- const customProduct = customProductMap.get(item.product_path)
+ const customProduct = customProductMap.get(productPath)
return {
...product,
reason: customProduct?.reason,
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 8aaf3e0d3b57..309afbc1b9b3 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -373,6 +373,8 @@ export const FEATURE_FLAGS = {
MAX_AI_INSIGHT_SEARCH: 'max-ai-insight-search', // owner: #team-posthog-ai
MAX_BILLING_CONTEXT: 'max-billing-context', // owner: @pawel-cebula #team-billing
MAX_DEEP_RESEARCH: 'max-deep-research', // owner: @kappa90 #team-posthog-ai
+ MCP_ANALYTICS: 'mcp-analytics', // owner: #project-mcp-analytics
+ MCP_ANALYTICS_INTENT_ROUTING: 'mcp-analytics-intent-routing', // owner: #project-mcp-analytics
MCP_HINTS: 'mcp-hints', // owner: @rafaeelaudibert #team-growth, gates in-app MCP hint toasts and empty-state cards
MCP_SERVERS: 'mcp-servers', // owner: #team-posthog-ai
MESSAGING_SES: 'messaging-ses', // owner #team-workflows
diff --git a/frontend/src/products.json b/frontend/src/products.json
index 72f1cdd1cf2b..02e5ebf747fe 100644
--- a/frontend/src/products.json
+++ b/frontend/src/products.json
@@ -156,6 +156,13 @@
"type": null,
"intents": ["marketing_analytics"]
},
+ {
+ "path": "MCP analytics",
+ "category": "AI engineering",
+ "iconType": null,
+ "type": "mcp_analytics",
+ "intents": ["llm_analytics"]
+ },
{ "path": "Metrics", "category": "Unreleased", "iconType": "metrics", "type": null, "intents": ["metrics"] },
{
"path": "Product analytics",
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 26458eee5d2e..e3a488508bb5 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -119,6 +119,8 @@ export const productScenes: Record<string, () => Promise<any>> = {
import('../../products/logs/frontend/scenes/LogsSamplingDetailScene/LogsSamplingDetailScene'),
ManagedMigration: () => import('../../products/managed_migrations/frontend/ManagedMigration'),
ManagedMigrationNew: () => import('../../products/managed_migrations/frontend/ManagedMigration'),
+ MCPAnalytics: () => import('../../products/mcp_analytics/frontend/MCPAnalyticsScene'),
+ MCPAnalyticsToolDetail: () => import('../../products/mcp_analytics/frontend/MCPAnalyticsToolDetail'),
Metrics: () => import('../../products/metrics/frontend/MetricsScene'),
ReplayVision: () => import('../../products/replay_vision/frontend/replay_lenses/ReplayLensesScene'),
ReplayVisionLens: () => import('../../products/replay_vision/frontend/replay_lenses/ReplayLens'),
@@ -234,6 +236,11 @@ export const productRoutes: Record<string, [string, string]> = {
'/logs/drop-rules/:id': ['LogsSamplingDetail', 'logsSamplingDetail'],
'/managed_migrations': ['ManagedMigration', 'managedMigration'],
'/managed_migrations/new': ['ManagedMigration', 'managedMigration'],
+ '/mcp-analytics/dashboard': ['MCPAnalytics', 'mcpAnalyticsDashboard'],
+ '/mcp-analytics/sessions': ['MCPAnalytics', 'mcpAnalyticsSessions'],
+ '/mcp-analytics/tool-quality': ['MCPAnalytics', 'mcpAnalyticsToolQuality'],
+ '/mcp-analytics/tool-quality/:toolName': ['MCPAnalyticsToolDetail', 'mcpAnalyticsTool'],
+ '/mcp-analytics/intent-clustering': ['MCPAnalytics', 'mcpAnalyticsIntentClustering'],
'/metrics': ['Metrics', 'metrics'],
'/replay-vision': ['ReplayVision', 'replayVision'],
'/replay-vision/:id': ['ReplayVisionLens', 'replayVision'],
@@ -565,6 +572,19 @@ export const productConfiguration: Record<string, any> = {
},
ManagedMigration: { name: 'Managed migrations', projectBased: true },
ManagedMigrationNew: { name: 'Managed migrations', projectBased: true },
+ MCPAnalytics: {
+ projectBased: true,
+ name: 'MCP analytics',
+ layout: 'app-container',
+ description: 'Capture user intent and behaviour patterns to understand what AI users need from your tools.',
+ iconType: 'llm_analytics',
+ },
+ MCPAnalyticsToolDetail: {
+ projectBased: true,
+ name: 'MCP tool',
+ layout: 'app-container',
+ iconType: 'llm_analytics',
+ },
Metrics: {
name: 'Metrics',
projectBased: true,
@@ -922,6 +942,11 @@ export const productUrls = {
managedMigration: (): string => '/managed_migrations',
managedMigrationNew: (): string => '/managed_migrations/new',
marketingAnalyticsApp: (): string => '/marketing',
+ mcpAnalyticsDashboard: (): string => '/mcp-analytics/dashboard',
+ mcpAnalyticsSessions: (): string => '/mcp-analytics/sessions',
+ mcpAnalyticsToolQuality: (): string => '/mcp-analytics/tool-quality',
+ mcpAnalyticsTool: (toolName: string): string => `/mcp-analytics/tool-quality/${encodeURIComponent(toolName)}`,
+ mcpAnalyticsIntentClustering: (): string => '/mcp-analytics/intent-clustering',
metrics: (): string => '/metrics',
notebooks: (): string => '/notebooks',
notebook: (shortId: string): string => `/notebooks/${shortId}`,
@@ -1659,6 +1684,20 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
sceneKey: 'Logs',
sceneKeys: ['Logs', 'LogsAlertDetail', 'LogsSamplingNew', 'LogsSamplingDetail'],
},
+ {
+ path: 'MCP analytics',
+ intents: [ProductKey.LLM_ANALYTICS],
+ category: ProductItemCategory.AI_ENGINEERING,
+ visualOrder: 2,
+ type: 'mcp_analytics',
+ iconType: 'llm_analytics' as FileSystemIconType,
+ iconColor: ['var(--color-product-llm-analytics-light)'] as FileSystemIconColor,
+ href: urls.mcpAnalyticsDashboard(),
+ flag: FEATURE_FLAGS.MCP_ANALYTICS,
+ tags: ['alpha'],
+ sceneKey: 'MCPAnalytics',
+ sceneKeys: ['MCPAnalytics', 'MCPAnalyticsToolDetail'],
+ },
{
path: 'Marketing analytics',
intents: [ProductKey.MARKETING_ANALYTICS],
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index eaf886bc1588..bc4cbce18412 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2967,7 +2967,23 @@ importers:
products/marketing_analytics: {}
- products/mcp_analytics: {}
+ products/mcp_analytics:
+ dependencies:
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.5([email protected])
+ kea-loaders:
+ specifier: 'catalog:'
+ kea-router:
+ specifier: 'catalog:'
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
products/mcp_store:
dependencies:
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 406d55d41380..b42a76d6f1ff 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -84,6 +84,14 @@ from posthog.temporal.llm_analytics import (
TAGGER_WORKFLOWS as LLM_ANALYTICS_TAGGER_WORKFLOWS,
WORKFLOWS as LLM_ANALYTICS_WORKFLOWS,
)
+from posthog.temporal.mcp_analytics.backfill_sessions import (
+ MCP_ANALYTICS_BACKFILL_SESSIONS_ACTIVITIES,
+ MCP_ANALYTICS_BACKFILL_SESSIONS_WORKFLOWS,
+)
+from posthog.temporal.mcp_analytics.summarize_session_intents import (
+ MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_ACTIVITIES,
+ MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_WORKFLOWS,
+)
from posthog.temporal.messaging import (
ACTIVITIES as MESSAGING_ACTIVITIES,
WORKFLOWS as MESSAGING_WORKFLOWS,
@@ -230,7 +238,9 @@ _task_queue_specs = [
+ EXPERIMENTS_WORKFLOWS
+ CLEANUP_PROPDEFS_WORKFLOWS
+ INGESTION_ACCEPTANCE_TEST_WORKFLOWS
- + WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS,
+ + WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS
+ + MCP_ANALYTICS_BACKFILL_SESSIONS_WORKFLOWS
+ + MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_WORKFLOWS,
PROXY_SERVICE_ACTIVITIES
+ DELETE_PERSONS_ACTIVITIES
+ QUOTA_LIMITING_ACTIVITIES
@@ -242,7 +252,9 @@ _task_queue_specs = [
+ EXPERIMENTS_ACTIVITIES
+ CLEANUP_PROPDEFS_ACTIVITIES
+ INGESTION_ACCEPTANCE_TEST_ACTIVITIES
- + WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES,
+ + WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES
+ + MCP_ANALYTICS_BACKFILL_SESSIONS_ACTIVITIES
+ + MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_ACTIVITIES,
),
(
settings.HEALTH_CHECK_TASK_QUEUE,
diff --git a/posthog/temporal/mcp_analytics/__init__.py b/posthog/temporal/mcp_analytics/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/__init__.py b/posthog/temporal/mcp_analytics/backfill_sessions/__init__.py
new file mode 100644
index 000000000000..747298a14f8d
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/backfill_sessions/__init__.py
@@ -0,0 +1,8 @@
+from posthog.temporal.mcp_analytics.backfill_sessions.activities import aggregate_and_upsert_mcp_sessions
+from posthog.temporal.mcp_analytics.backfill_sessions.workflow import BackfillMCPSessionsWorkflow
+
+MCP_ANALYTICS_BACKFILL_SESSIONS_WORKFLOWS = [
+ BackfillMCPSessionsWorkflow,
+]
+
+MCP_ANALYTICS_BACKFILL_SESSIONS_ACTIVITIES = [aggregate_and_upsert_mcp_sessions]
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/activities.py b/posthog/temporal/mcp_analytics/backfill_sessions/activities.py
new file mode 100644
index 000000000000..fa1aa5217bca
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/backfill_sessions/activities.py
@@ -0,0 +1,107 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from temporalio import activity
+
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.clickhouse import get_client
+from posthog.temporal.common.logger import get_write_only_logger
+from posthog.temporal.mcp_analytics.backfill_sessions.types import BackfillMCPSessionsInput
+
+from products.mcp_analytics.backend.models import MCPSession
+
+LOGGER = get_write_only_logger()
+
+
+# Two-pass aggregate:
+# 1. Inner subquery (cheap) — list conversation ids that received any mcp_tool_call event
+# in the last lookback_hours. These are the only sessions whose Postgres row could be
+# stale.
+# 2. Outer query — re-aggregate the FULL history of each active conversation id (bounded
+# only by the retention window) so the upsert reflects the complete picture, not just
+# what landed in the lookback. Avoids the corruption that a naive lookback-window
+# aggregate would cause when a long-lived session gets a fresh event late.
+# The grouping key is $mcp_conversation_id, which the MCP service stamps onto every event in
+# the same conversation. We persist it as MCPSession.session_id since that is the
+# product-facing identifier of an MCP session.
+_AGGREGATE_QUERY = """
+SELECT
+ team_id,
+ JSONExtractString(properties, '$mcp_conversation_id') AS session_id,
+ toString(min(timestamp)) AS session_start,
+ toString(max(timestamp)) AS session_end,
+ count() AS tool_call_count,
+ groupUniqArrayIf(JSONExtractString(properties, '$mcp_tool_name'), JSONExtractString(properties, '$mcp_tool_name') != '') AS tools_used,
+ argMax(distinct_id, timestamp) AS distinct_id,
+ argMax(JSONExtractString(properties, '$mcp_client_name'), timestamp) AS mcp_client_name
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND JSONExtractString(properties, '$mcp_conversation_id') IN (
+ SELECT DISTINCT JSONExtractString(properties, '$mcp_conversation_id')
+ FROM events
+ WHERE event = 'mcp_tool_call'
+ AND JSONExtractString(properties, '$mcp_conversation_id') != ''
+ AND timestamp >= now() - INTERVAL %(lookback_hours)s HOUR
+ )
+ AND timestamp >= now() - INTERVAL %(retention_days)s DAY
+GROUP BY team_id, session_id
+LIMIT 100000
+FORMAT JSONEachRow
+"""
+
+# How far back we'll look when re-aggregating an active session. Bounded so the outer query
+# can prune events partitions; anything older than this is effectively frozen anyway.
+_RETENTION_DAYS = 7
+
+
+def _parse_clickhouse_ts(value: str) -> datetime:
+ parsed = datetime.fromisoformat(value)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed
+
+
+@database_sync_to_async
+def _upsert_session(row: dict[str, Any]) -> None:
+ session_start = _parse_clickhouse_ts(row["session_start"])
+ session_end = _parse_clickhouse_ts(row["session_end"])
+
+ # Cross-team activity — backfills sessions for every team in a single ClickHouse pass.
+ MCPSession.objects.unscoped().update_or_create(
+ team_id=int(row["team_id"]),
+ session_id=row["session_id"],
+ defaults={
+ "session_start": session_start,
+ "session_end": session_end,
+ "duration_seconds": max(0, int((session_end - session_start).total_seconds())),
+ "tool_call_count": int(row.get("tool_call_count") or 0),
+ "tools_used": [tool for tool in (row.get("tools_used") or []) if tool],
+ "distinct_id": row.get("distinct_id") or "",
+ "mcp_client_name": row.get("mcp_client_name") or "",
+ },
+ )
+
+
[email protected](name="aggregate-and-upsert-mcp-sessions")
+async def aggregate_and_upsert_mcp_sessions(input: BackfillMCPSessionsInput) -> None:
+ logger = LOGGER.bind(activity="aggregate-and-upsert-mcp-sessions")
+ logger.info("Aggregating MCP sessions from ClickHouse", lookback_hours=input.lookback_hours)
+
+ tag_queries(product=Product.MCP, feature=Feature.QUERY, name="mcp_sessions_backfill")
+
+ async with get_client() as client:
+ rows = await client.read_query_as_jsonl(
+ _AGGREGATE_QUERY,
+ query_parameters={
+ "lookback_hours": int(input.lookback_hours),
+ "retention_days": _RETENTION_DAYS,
+ },
+ )
+
+ upserted = 0
+ for row in rows:
+ await _upsert_session(row)
+ upserted += 1
+
+ logger.info("MCP session backfill complete", rows_seen=len(rows), upserted=upserted)
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/types.py b/posthog/temporal/mcp_analytics/backfill_sessions/types.py
new file mode 100644
index 000000000000..9b341faa0d33
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/backfill_sessions/types.py
@@ -0,0 +1,10 @@
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class BackfillMCPSessionsInput:
+ # How far back to look for *active* mcp_tool_call events on each run. Sessions
+ # that received any event in this window get re-aggregated from their full
+ # history, so this only needs to span the longest plausible "still-mutating"
+ # gap between events on a live session.
+ lookback_hours: int = 1
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/workflow.py b/posthog/temporal/mcp_analytics/backfill_sessions/workflow.py
new file mode 100644
index 000000000000..e6370f481506
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/backfill_sessions/workflow.py
@@ -0,0 +1,25 @@
+from datetime import timedelta
+
+from temporalio import common, workflow
+
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.mcp_analytics.backfill_sessions.activities import aggregate_and_upsert_mcp_sessions
+from posthog.temporal.mcp_analytics.backfill_sessions.types import BackfillMCPSessionsInput
+
+
[email protected](name="backfill-mcp-sessions")
+class BackfillMCPSessionsWorkflow(PostHogWorkflow):
+ inputs_cls = BackfillMCPSessionsInput
+ inputs_optional = True
+
+ @workflow.run
+ async def run(self, input: BackfillMCPSessionsInput) -> None:
+ await workflow.execute_activity(
+ aggregate_and_upsert_mcp_sessions,
+ input,
+ start_to_close_timeout=timedelta(minutes=10),
+ retry_policy=common.RetryPolicy(
+ maximum_attempts=3,
+ initial_interval=timedelta(seconds=30),
+ ),
+ )
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/__init__.py b/posthog/temporal/mcp_analytics/summarize_session_intents/__init__.py
new file mode 100644
index 000000000000..da1137b5e304
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/summarize_session_intents/__init__.py
@@ -0,0 +1,8 @@
+from posthog.temporal.mcp_analytics.summarize_session_intents.activities import summarize_mcp_session_intents
+from posthog.temporal.mcp_analytics.summarize_session_intents.workflow import SummarizeMCPSessionIntentsWorkflow
+
+MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_WORKFLOWS = [
+ SummarizeMCPSessionIntentsWorkflow,
+]
+
+MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_ACTIVITIES = [summarize_mcp_session_intents]
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py b/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py
new file mode 100644
index 000000000000..e8c235a0546c
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py
@@ -0,0 +1,192 @@
+import os
+import asyncio
+from datetime import timedelta
+
+from django.db import connection
+from django.utils import timezone
+
+import structlog
+from temporalio import activity
+
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.clickhouse import get_client
+from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
+
+from products.mcp_analytics.backend.models import MCPSession
+
+logger = structlog.get_logger(__name__)
+
+# PostHog's own team — summarised ahead of everyone else so internal dogfooding
+# is never starved by external traffic.
+_PRIORITY_TEAM_ID = 2
+
+# Per-team cap for non-priority teams in a single batch. Stops one team from
+# monopolising the global LLM budget by emitting many unique conversation ids.
+_PER_TEAM_CAP = 10
+
+SYSTEM_PROMPT = (
+ "You summarise what an AI agent was trying to accomplish during a single MCP session. "
+ "You are given the per-tool-call intents the agent recorded, in chronological order. "
+ "Reply with at most two sentences in third person. "
+ "Be concrete: name the actual product, metric, person, or workflow involved — not generic phrases "
+ "like 'analytics question' or 'enhance user experience'. "
+ "If the intents span unrelated tasks, lead with the dominant one. "
+ "Do not list individual tools, do not echo the input verbatim, and do not pad with filler."
+)
+
+_TOOL_CALL_INTENTS_QUERY = """
+SELECT JSONExtractString(properties, '$mcp_intent') AS intent
+FROM events
+WHERE team_id = %(team_id)s
+ AND event = 'mcp_tool_call'
+ AND JSONExtractString(properties, '$mcp_conversation_id') = %(session_id)s
+ AND JSONExtractString(properties, '$mcp_intent') != ''
+ORDER BY timestamp ASC
+LIMIT 200
+FORMAT JSONEachRow
+"""
+
+
+def _build_user_prompt(intents: list[str]) -> str:
+ numbered = "\n".join(f"{i + 1}. {intent}" for i, intent in enumerate(intents))
+ return f"Per-tool-call intents (chronological):\n{numbered}\n\nSummarise the agent's overall goal in 2-3 sentences."
+
+
+def _summarize_intents_sync(intents: list[str]) -> str | None:
+ """Blocking OpenAI call; callers wrap in asyncio.to_thread for concurrency."""
+ if not os.environ.get("OPENAI_API_KEY"):
+ logger.warning("openai_api_key_not_set", count=len(intents))
+ return None
+
+ # Local import keeps the activity importable without the optional dep when the
+ # key is unset; we only need OpenAI at the point of an actual summarisation.
+ from posthoganalytics.ai.openai import OpenAI
+
+ client = OpenAI(max_retries=2)
+ response = client.chat.completions.create(
+ model="gpt-4o-mini",
+ temperature=0.2,
+ max_tokens=120,
+ timeout=30,
+ messages=[
+ {"role": "system", "content": SYSTEM_PROMPT},
+ {"role": "user", "content": _build_user_prompt(intents)},
+ ],
+ )
+ content = response.choices[0].message.content if response.choices else None
+ if not content:
+ return None
+ return content.strip()
+
+
+_PENDING_SESSIONS_SQL = """
+WITH ranked AS (
+ SELECT
+ team_id,
+ session_id,
+ session_end,
+ ROW_NUMBER() OVER (PARTITION BY team_id ORDER BY session_end DESC) AS rn,
+ (team_id = %(priority_team_id)s) AS is_priority
+ FROM posthog_mcp_session
+ WHERE intent IS NULL AND session_end < %(cutoff)s
+)
+SELECT team_id, session_id
+FROM ranked
+WHERE is_priority OR rn <= %(per_team_cap)s
+ORDER BY is_priority DESC, session_end DESC
+LIMIT %(batch_size)s
+"""
+
+
+@database_sync_to_async
+def _take_pending_sessions(batch_size: int, idle_minutes: int) -> list[tuple[int, str]]:
+ """Pick sessions that are eligible for summarisation.
+
+ Eligible = intent is unset AND last event landed more than idle_minutes ago,
+ so we don't summarise sessions that may still be receiving tool calls.
+ Priority team rows come first; other teams are capped per batch so one noisy
+ team can't monopolise the LLM budget.
+ """
+ cutoff = timezone.now() - timedelta(minutes=idle_minutes)
+ with connection.cursor() as cursor:
+ cursor.execute(
+ _PENDING_SESSIONS_SQL,
+ {
+ "priority_team_id": _PRIORITY_TEAM_ID,
+ "cutoff": cutoff,
+ "per_team_cap": _PER_TEAM_CAP,
+ "batch_size": batch_size,
+ },
+ )
+ return [(int(team_id), session_id) for team_id, session_id in cursor.fetchall()]
+
+
+@database_sync_to_async
+def _save_intent(team_id: int, session_id: str, intent: str) -> None:
+ # Cross-team activity — picks pending rows across all teams in one pass.
+ MCPSession.objects.unscoped().filter(team_id=team_id, session_id=session_id).update(intent=intent)
+
+
+async def _fetch_tool_call_intents(team_id: int, session_id: str) -> list[str]:
+ async with get_client() as client:
+ rows = await client.read_query_as_jsonl(
+ _TOOL_CALL_INTENTS_QUERY,
+ query_parameters={"team_id": team_id, "session_id": session_id},
+ )
+ return [row["intent"] for row in rows if row.get("intent")]
+
+
+async def _summarise_one(
+ team_id: int,
+ session_id: str,
+ semaphore: asyncio.Semaphore,
+) -> str:
+ """Process one session: fetch intents, call LLM, save. Returns outcome label."""
+ async with semaphore:
+ intents = await _fetch_tool_call_intents(team_id, session_id)
+ if not intents:
+ await _save_intent(team_id, session_id, "No agent intent was recorded for this session.")
+ return "no_intents"
+
+ summary = await asyncio.to_thread(_summarize_intents_sync, intents)
+ if not summary:
+ return "llm_skipped"
+
+ await _save_intent(team_id, session_id, summary)
+ return "summarised"
+
+
[email protected](name="summarize-mcp-session-intents")
+async def summarize_mcp_session_intents(input: SummarizeMCPSessionIntentsInput) -> None:
+ log = logger.bind(activity="summarize-mcp-session-intents")
+ tag_queries(product=Product.MCP, feature=Feature.QUERY, name="mcp_session_intent_summary")
+
+ pending = await _take_pending_sessions(input.batch_size, input.idle_minutes)
+ log.info(
+ "Found sessions awaiting intent summary",
+ count=len(pending),
+ idle_minutes=input.idle_minutes,
+ concurrency=input.concurrency,
+ )
+
+ if not pending:
+ log.info("MCP session intent summary complete", summarised=0, skipped=0)
+ return
+
+ semaphore = asyncio.Semaphore(max(1, input.concurrency))
+ outcomes = await asyncio.gather(
+ *(_summarise_one(team_id, session_id, semaphore) for team_id, session_id in pending),
+ return_exceptions=False,
+ )
+
+ summarised = sum(1 for o in outcomes if o == "summarised")
+ no_intents = sum(1 for o in outcomes if o == "no_intents")
+ llm_skipped = sum(1 for o in outcomes if o == "llm_skipped")
+
+ log.info(
+ "MCP session intent summary complete",
+ summarised=summarised,
+ no_intents=no_intents,
+ llm_skipped=llm_skipped,
+ )
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/types.py b/posthog/temporal/mcp_analytics/summarize_session_intents/types.py
new file mode 100644
index 000000000000..2962e72a776b
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/summarize_session_intents/types.py
@@ -0,0 +1,18 @@
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class SummarizeMCPSessionIntentsInput:
+ # How many sessions to summarize per workflow run. The activity dispatches
+ # OpenAI calls in parallel up to `concurrency`, so this cap mostly controls
+ # OpenAI spend per tick.
+ batch_size: int = 100
+
+ # Maximum concurrent OpenAI requests in flight inside the activity. Higher
+ # values trade memory + risk of OpenAI rate limits for shorter wall-clock.
+ concurrency: int = 8
+
+ # Skip sessions whose last event is too recent — they may still be active and
+ # would have to be re-summarised. Only candidate sessions whose session_end is
+ # older than this many minutes are eligible.
+ idle_minutes: int = 30
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/workflow.py b/posthog/temporal/mcp_analytics/summarize_session_intents/workflow.py
new file mode 100644
index 000000000000..57e8cbefe9c8
--- /dev/null
+++ b/posthog/temporal/mcp_analytics/summarize_session_intents/workflow.py
@@ -0,0 +1,25 @@
+from datetime import timedelta
+
+from temporalio import common, workflow
+
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.mcp_analytics.summarize_session_intents.activities import summarize_mcp_session_intents
+from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
+
+
[email protected](name="summarize-mcp-session-intents")
+class SummarizeMCPSessionIntentsWorkflow(PostHogWorkflow):
+ inputs_cls = SummarizeMCPSessionIntentsInput
+ inputs_optional = True
+
+ @workflow.run
+ async def run(self, input: SummarizeMCPSessionIntentsInput) -> None:
+ await workflow.execute_activity(
+ summarize_mcp_session_intents,
+ input,
+ start_to_close_timeout=timedelta(minutes=10),
+ retry_policy=common.RetryPolicy(
+ maximum_attempts=2,
+ initial_interval=timedelta(seconds=30),
+ ),
+ )
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 7f9e0f28423d..a558acf798f9 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -57,6 +57,8 @@ from posthog.temporal.llm_analytics.trace_summarization.schedule import (
create_batch_trace_summarization_schedule,
)
from posthog.temporal.logs_alerting.schedule import create_logs_alert_check_schedule
+from posthog.temporal.mcp_analytics.backfill_sessions.types import BackfillMCPSessionsInput
+from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
from posthog.temporal.messaging.schedule import create_all_realtime_cohort_calculation_schedules
from posthog.temporal.product_analytics.upgrade_queries_workflow import UpgradeQueriesWorkflowInputs
from posthog.temporal.quota_limiting.run_quota_limiting import RunQuotaLimitingInputs
@@ -486,6 +488,74 @@ async def create_replay_count_metrics_schedule(client: Client):
)
+async def create_mcp_sessions_backfill_schedule(client: Client):
+ """Create or update the schedule that backfills the MCPSession Postgres table.
+
+ Runs every 5 minutes; each run aggregates mcp_tool_call events seen in the last
+ 24 hours and upserts one row per (team, session_id) into Postgres so the
+ sessions list endpoint can read from Postgres instead of ClickHouse.
+ """
+ mcp_sessions_backfill_schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ "backfill-mcp-sessions",
+ BackfillMCPSessionsInput(),
+ id="backfill-mcp-sessions-schedule",
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ retry_policy=common.RetryPolicy(
+ maximum_attempts=3,
+ ),
+ ),
+ spec=ScheduleSpec(
+ intervals=[ScheduleIntervalSpec(every=timedelta(minutes=5))],
+ ),
+ )
+
+ if await a_schedule_exists(client, "backfill-mcp-sessions-schedule"):
+ await a_update_schedule(client, "backfill-mcp-sessions-schedule", mcp_sessions_backfill_schedule)
+ else:
+ await a_create_schedule(
+ client,
+ "backfill-mcp-sessions-schedule",
+ mcp_sessions_backfill_schedule,
+ trigger_immediately=False,
+ )
+
+
+async def create_mcp_session_intent_summary_schedule(client: Client):
+ """Create or update the schedule that backfills MCPSession.intent with an LLM summary.
+
+ Runs every 5 minutes (matches the backfill cadence so new sessions become
+ 'complete' quickly). Each run picks up to 100 MCPSession rows whose intent is
+ unset and whose last event is older than 30 minutes (so we don't summarise
+ sessions that may still be receiving tool calls), then dispatches the LLM
+ calls in parallel inside the activity.
+ """
+ summary_schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ "summarize-mcp-session-intents",
+ SummarizeMCPSessionIntentsInput(),
+ id="summarize-mcp-session-intents-schedule",
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ retry_policy=common.RetryPolicy(
+ maximum_attempts=2,
+ ),
+ ),
+ spec=ScheduleSpec(
+ intervals=[ScheduleIntervalSpec(every=timedelta(minutes=5))],
+ ),
+ )
+
+ if await a_schedule_exists(client, "summarize-mcp-session-intents-schedule"):
+ await a_update_schedule(client, "summarize-mcp-session-intents-schedule", summary_schedule)
+ else:
+ await a_create_schedule(
+ client,
+ "summarize-mcp-session-intents-schedule",
+ summary_schedule,
+ trigger_immediately=False,
+ )
+
+
async def cleanup_legacy_session_summarization_schedules(client: Client):
"""Delete legacy schedules. Any in-flight runs die on their own execution_timeout."""
legacy_schedule_ids = [
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 804d61d9d45d..e4cb31b10200 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -79,6 +79,7 @@ from products.dashboards.backend.api.dashboard_template_json_schema_parser impor
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text
from products.llm_analytics.backend.dashboard_templates import get_llm_analytics_default_template
+from products.mcp_analytics.backend.dashboard_templates import get_mcp_analytics_default_template
from ee.hogai.utils.aio import async_to_sync
@@ -1037,7 +1038,10 @@ class DashboardsViewSet(
permission_classes = [CanEditDashboard]
renderer_classes = [SafeJSONRenderer, ServerSentEventRenderer]
- TEMPLATE_MAP = {"llm-analytics": get_llm_analytics_default_template}
+ TEMPLATE_MAP = {
+ "llm-analytics": get_llm_analytics_default_template,
+ "mcp-analytics": get_mcp_analytics_default_template,
+ }
@tracer.start_as_current_span("DashboardViewSet.get_serializer_context")
def get_serializer_context(self) -> dict[str, Any]:
diff --git a/products/mcp_analytics/backend/dashboard_templates.py b/products/mcp_analytics/backend/dashboard_templates.py
new file mode 100644
index 000000000000..31e6a845ff7d
--- /dev/null
+++ b/products/mcp_analytics/backend/dashboard_templates.py
@@ -0,0 +1,129 @@
+from products.dashboards.backend.models.dashboard_templates import DashboardTemplate
+
+
+def get_mcp_analytics_default_template() -> DashboardTemplate:
+ """Default dashboard template for MCP analytics."""
+ return DashboardTemplate(
+ template_name="MCP Analytics Default",
+ dashboard_description="Overview of your MCP usage.",
+ dashboard_filters={"date_from": "-7d"},
+ tiles=[
+ {
+ "type": "INSIGHT",
+ "name": "MCP clients",
+ "description": "",
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [
+ {
+ "event": "mcp_initialize",
+ "name": "mcp_initialize",
+ "kind": "EventsNode",
+ }
+ ],
+ "breakdownFilter": {
+ "breakdown_type": "event",
+ "breakdown": "$mcp_client_name",
+ },
+ "trendsFilter": {
+ "display": "ActionsPie",
+ "showLegend": False,
+ "showPercentStackView": True,
+ "showValuesOnSeries": True,
+ },
+ "dateRange": {
+ "date_from": "-7d",
+ },
+ },
+ "vizSpecificOptions": {"ActionsPie": {"hideAggregation": True}},
+ },
+ "layouts": {
+ "sm": {"h": 4, "w": 4, "x": 0, "y": 0, "minH": 4, "minW": 4},
+ "xs": {"h": 4, "w": 1, "x": 0, "y": 0, "minH": 4, "minW": 1},
+ },
+ },
+ {
+ "type": "INSIGHT",
+ "name": "MCP users and sessions",
+ "description": "",
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [
+ {
+ "kind": "EventsNode",
+ "event": "mcp_initialize",
+ "name": "mcp_initialize",
+ "custom_name": "users",
+ "math": "hogql",
+ "math_hogql": "count(DISTINCT person_id)",
+ },
+ {
+ "kind": "EventsNode",
+ "event": "mcp_initialize",
+ "name": "mcp_initialize",
+ "custom_name": "sessions",
+ "math": "hogql",
+ "math_hogql": "count(DISTINCT properties.$session_id)",
+ },
+ ],
+ "trendsFilter": {},
+ "version": 2,
+ "tags": {
+ "productKey": "product_analytics",
+ },
+ },
+ "full": True,
+ },
+ "layouts": {
+ "sm": {"h": 4, "w": 4, "x": 4, "y": 0, "minH": 4, "minW": 4},
+ "xs": {"h": 4, "w": 1, "x": 0, "y": 4, "minH": 4, "minW": 1},
+ },
+ },
+ {
+ "type": "INSIGHT",
+ "name": "MCP tool calls by error status",
+ "description": "",
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [
+ {
+ "kind": "EventsNode",
+ "event": "mcp_tool_call",
+ "name": "mcp_tool_call",
+ "math": "total",
+ }
+ ],
+ "trendsFilter": {
+ "display": "ActionsUnstackedBar",
+ },
+ "version": 2,
+ "tags": {
+ "productKey": "product_analytics",
+ },
+ "breakdownFilter": {
+ "breakdowns": [
+ {
+ "property": "$mcp_is_error",
+ "type": "event",
+ }
+ ],
+ },
+ },
+ "full": True,
+ },
+ "layouts": {
+ "sm": {"h": 4, "w": 4, "x": 8, "y": 0, "minH": 4, "minW": 4},
+ "xs": {"h": 4, "w": 1, "x": 0, "y": 8, "minH": 4, "minW": 1},
+ },
+ },
+ ],
+ tags=["mcp-analytics"],
+ scope=DashboardTemplate.Scope.GLOBAL,
+ availability_contexts=["mcp-analytics"],
+ )
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.py
index 6057461e054b..a82ee297a3cb 100644
--- a/products/mcp_analytics/backend/facade/api.py
+++ b/products/mcp_analytics/backend/facade/api.py
@@ -46,3 +46,40 @@ def create_missing_capability_submission(
team: Team, created_by: User | None, submission: contracts.CreateMissingCapabilitySubmission
) -> contracts.Submission:
return _to_submission(logic.create_missing_capability_submission(team, created_by, submission))
+
+
+def list_mcp_sessions(
+ team: Team, limit: int, offset: int, search: str = "", order_by: str = ""
+) -> list[contracts.MCPSession]:
+ return logic.list_mcp_sessions(team, limit=limit, offset=offset, search=search, order_by=order_by)
+
+
+def list_mcp_tool_calls(team: Team, session_id: str) -> list[contracts.MCPToolCall]:
+ return logic.list_mcp_tool_calls(team, session_id=session_id)
+
+
+def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:
+ return logic.get_intent_cluster_snapshot(team)
+
+
+def trigger_intent_cluster_recompute(team: Team, user: User | None) -> None:
+ """Kick off the intent cluster recompute Celery task.
+
+ Returns immediately. Use ``get_intent_cluster_snapshot`` to poll status.
+ """
+ # Imports here to avoid loading Celery at module import time.
+ from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot
+ from products.mcp_analytics.backend.tasks.tasks import compute_intent_clusters
+
+ # Flip to COMPUTING before enqueuing so the 202 response and any
+ # immediate poll see consistent state. The task re-asserts COMPUTING
+ # on pickup; both writes are idempotent.
+ MCPIntentClusterSnapshot.objects.update_or_create(
+ team=team,
+ defaults={
+ "status": MCPIntentClusterSnapshot.Status.COMPUTING,
+ "error_message": "",
+ "last_computed_by": user,
+ },
+ )
+ compute_intent_clusters.delay(team.id, user.id if user else None)
diff --git a/products/mcp_analytics/backend/facade/contracts.py b/products/mcp_analytics/backend/facade/contracts.py
index d5bde99398b4..1d3329443a61 100644
--- a/products/mcp_analytics/backend/facade/contracts.py
+++ b/products/mcp_analytics/backend/facade/contracts.py
@@ -1,4 +1,4 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import datetime
from uuid import UUID
@@ -49,3 +49,85 @@ class CreateMissingCapabilitySubmission:
missing_capability: str
blocked: bool = True
context: SubmissionContext = SubmissionContext()
+
+
+@dataclass(frozen=True)
+class MCPSession:
+ session_id: str
+ tool_calls: int
+ session_start: datetime
+ session_end: datetime
+ distinct_id_count: int
+ tools_used: list[str]
+ mcp_client_name: str
+ distinct_id: str
+ person_email: str
+ person_name: str
+ intent: str
+
+
+@dataclass(frozen=True)
+class MCPToolCall:
+ event_id: str
+ timestamp: datetime
+ tool_name: str
+ intent: str
+ is_error: bool
+ error_message: str
+ duration_ms: int | None
+
+
+@dataclass(frozen=True)
+class IntentClusterToolEntry:
+ tool: str
+ count: int
+ pct: float
+ errors: int
+ error_rate_pct: float
+
+
+@dataclass(frozen=True)
+class IntentClusterJourneyPath:
+ steps: list[str | None]
+ outcome: str
+ count: int
+
+
+@dataclass(frozen=True)
+class IntentClusterJourney:
+ paths: list[IntentClusterJourneyPath]
+ total_sessions: int
+ leak: IntentClusterJourneyPath | None
+
+
+@dataclass(frozen=True)
+class IntentCluster:
+ id: int
+ label: str
+ intent_count: int
+ session_count: int
+ call_count: int
+ error_count: int
+ error_rate_pct: float
+ routing_entropy: float
+ tool_distribution: list[IntentClusterToolEntry]
+ sample_intents: list[str]
+ journey: IntentClusterJourney | None = None
+
+
+@dataclass(frozen=True)
+class IntentClusterSnapshotMeta:
+ distance_threshold: float
+ embedding_model: str
+ n_intents: int
+ n_clusters: int
+
+
+@dataclass(frozen=True)
+class IntentClusterSnapshot:
+ status: str
+ error_message: str
+ last_computed_at: datetime | None
+ last_computed_by_email: str
+ clusters: list[IntentCluster] = field(default_factory=list)
+ computed_with: IntentClusterSnapshotMeta | None = None
diff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.py
new file mode 100644
index 000000000000..006386b6b640
--- /dev/null
+++ b/products/mcp_analytics/backend/intent_clustering.py
@@ -0,0 +1,467 @@
+"""Intent clustering pipeline for MCP analytics.
+
+Four pure functions, each independently testable, that together build a cluster
+snapshot of MCP intents. The Celery task in ``tasks.py`` orchestrates them and
+persists the result.
+
+Why pure functions: the algorithm is the riskiest part of this feature. Keeping
+each stage as a pure function over numpy arrays / dataclasses makes the
+algorithm validatable without touching ClickHouse, Postgres, or the embedding
+service.
+
+Why ``$mcp_intent`` per-event for v1: a session-level summarised-intent table is
+being built in parallel. ``fetch_intent_corpus`` is the only function that needs
+to change when that table lands — swap its body to read from the new source.
+"""
+
+import math
+import asyncio
+from collections import Counter, defaultdict
+from dataclasses import dataclass, field
+from typing import Any
+
+import numpy as np
+from sklearn.cluster import AgglomerativeClustering
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.api.embedding_worker import EmbeddingResponse, async_generate_embedding
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team.team import Team
+
+from products.mcp_analytics.backend.models import MCPSession
+
+# Constants
+EMBEDDING_MODEL = "text-embedding-3-small-1536"
+EMBEDDING_PREFIX = "User intent: "
+DEFAULT_LOOKBACK_DAYS = 7
+DEFAULT_TOP_N_INTENTS = 500
+DEFAULT_DISTANCE_THRESHOLD = 0.2
+MAX_SAMPLE_INTENTS_PER_CLUSTER = 3
+
+# How many tool-call steps to show in the per-cluster Sankey before the
+# outcome column. Sessions with fewer steps pad with None so the column
+# count stays fixed; the UI renders those as an "Ended" node.
+JOURNEY_DEPTH = 4
+MAX_JOURNEY_PATHS_PER_CLUSTER = 10
+
+
+@dataclass(frozen=True)
+class IntentRecord:
+ """One unique intent text, with the tool-call statistics observed for it."""
+
+ intent_text: str
+ frequency: int
+ session_count: int = 0
+ tool_counts: dict[str, int] = field(default_factory=dict)
+ error_counts: dict[str, int] = field(default_factory=dict)
+
+
+# Intent corpus -----------------------------------------------------------
+
+# Per-session tool stats: for each session_id we know about in Postgres, what
+# tools were called and how often. Joined in Python with the session→intent
+# map from Postgres so the same intent string can aggregate across sessions.
+# TODO(mcp-sessions): when the parallel-team posthog_mcp_session table ships,
+# change MCPSession.objects.filter(...) below to point at the real model.
+# TODO(intent-routing): chaining is by $session_id today; swap to
+# $conversation_id once tool calls carry it.
+_SESSION_TOOL_STATS_SQL = """
+SELECT
+ properties.$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
+FROM events
+WHERE event = {event}
+ AND properties.$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
+"""
+
+# Per-session ordered tool sequence + whether any call errored. arrayMap +
+# arraySort on (timestamp, tool) tuples preserves call order.
+_SESSION_JOURNEY_SQL = """
+SELECT
+ properties.$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
+FROM events
+WHERE event = {event}
+ AND properties.$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
+"""
+
+
+def fetch_intent_corpus(
+ 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.
+
+ The intent text comes from posthog_mcp_session (Postgres), one row per
+ MCP session. 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.
+ """
+ session_rows = list(MCPSession.objects.filter(team=team).values_list("session_id", "intent"))
+ if not session_rows:
+ return [], {}
+
+ # Map session_id -> intent_text (last write wins per session).
+ intent_by_session: dict[str, str] = {}
+ for session_id, intent_text in session_rows:
+ text = (intent_text or "").strip()
+ if not session_id or not text:
+ continue
+ intent_by_session[session_id] = text
+
+ if not intent_by_session:
+ return [], {}
+
+ session_ids = list(intent_by_session.keys())
+ query = parse_select(
+ _SESSION_TOOL_STATS_SQL,
+ placeholders={
+ "event": ast.Constant(value="mcp_tool_call"),
+ "session_ids": ast.Tuple(exprs=[ast.Constant(value=sid) for sid in session_ids]),
+ "lookback_days": ast.Constant(value=lookback_days),
+ },
+ )
+ 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"],
+ )
+ )
+
+ records.sort(key=lambda r: r.frequency, reverse=True)
+ return records[:top_n], intent_by_session
+
+
+# Journeys ----------------------------------------------------------------
+
+
+def fetch_session_journeys(
+ 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}}``.
+
+ Tool calls are sorted by timestamp so the sequence reflects the order
+ the agent invoked them.
+ """
+ if not session_ids:
+ return {}
+ query = parse_select(
+ _SESSION_JOURNEY_SQL,
+ placeholders={
+ "event": ast.Constant(value="mcp_tool_call"),
+ "session_ids": ast.Tuple(exprs=[ast.Constant(value=sid) for sid in session_ids]),
+ "lookback_days": ast.Constant(value=lookback_days),
+ },
+ )
+ with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):
+ response = execute_hogql_query(query=query, team=team)
+
+ 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:
+ continue
+ out[session_id] = {"tool_sequence": tool_sequence, "had_error": had_error}
+ return out
+
+
+def aggregate_journeys_per_cluster(
+ records: list[IntentRecord],
+ labels: np.ndarray,
+ session_journeys: dict[str, dict[str, Any]],
+ intent_to_sessions: dict[str, list[str]],
+) -> 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).
+ """
+ journeys_by_cluster: dict[int, Counter[tuple[tuple[str | None, ...], str]]] = defaultdict(Counter)
+
+ 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:
+ 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": [
+ {"steps": list(steps), "outcome": outcome, "count": count}
+ for (steps, outcome), count in ranked[:MAX_JOURNEY_PATHS_PER_CLUSTER]
+ ],
+ "total_sessions": total_sessions,
+ "leak": leak_path,
+ }
+ return result
+
+
+# Embeddings --------------------------------------------------------------
+
+
+async def _embed_one(team: Team, text: str) -> EmbeddingResponse | None:
+ try:
+ return await async_generate_embedding(team, EMBEDDING_PREFIX + text, model=EMBEDDING_MODEL)
+ except Exception:
+ return None
+
+
+async def embed_intents_async(team: Team, texts: list[str]) -> tuple[np.ndarray, list[int]]:
+ """Embed a list of intent texts concurrently.
+
+ Returns (embeddings, valid_indices) where ``valid_indices`` are the indices
+ into ``texts`` for which embedding succeeded. Skipped indices have no row
+ in the returned matrix. Callers must align downstream data structures with
+ ``valid_indices``.
+ """
+ if not texts:
+ return np.zeros((0, 0), dtype=np.float32), []
+
+ responses = await asyncio.gather(*[_embed_one(team, t) for t in texts])
+
+ vectors: list[list[float]] = []
+ valid_indices: list[int] = []
+ for i, response in enumerate(responses):
+ if response is None:
+ continue
+ vectors.append(response.embedding)
+ valid_indices.append(i)
+
+ if not vectors:
+ return np.zeros((0, 0), dtype=np.float32), []
+
+ return np.asarray(vectors, dtype=np.float32), valid_indices
+
+
+# Clustering --------------------------------------------------------------
+
+
+def cluster_embeddings(
+ embeddings: np.ndarray,
+ distance_threshold: float = DEFAULT_DISTANCE_THRESHOLD,
+) -> np.ndarray:
+ """Run agglomerative clustering on embedding vectors.
+
+ Uses average linkage and cosine distance. ``distance_threshold`` is the
+ user-facing knob: smaller -> tighter clusters, more of them.
+ Output: an integer label per embedding, all >= 0 (no noise sentinel).
+ """
+ n = len(embeddings)
+ if n == 0:
+ return np.array([], dtype=np.int64)
+ if n == 1:
+ return np.array([0], dtype=np.int64)
+
+ clusterer = AgglomerativeClustering(
+ metric="cosine",
+ linkage="average",
+ distance_threshold=distance_threshold,
+ n_clusters=None,
+ )
+ return clusterer.fit_predict(embeddings)
+
+
+# Snapshot building -------------------------------------------------------
+
+
+def _routing_entropy(tool_counts: dict[str, int]) -> float:
+ """Shannon entropy of the tool distribution, normalised to [0, 1].
+
+ 0 = perfectly consistent (one tool dominates), 1 = uniformly spread.
+ Single-tool clusters return 0.
+ """
+ total = sum(tool_counts.values())
+ if total <= 0:
+ return 0.0
+ probabilities = [count / total for count in tool_counts.values() if count > 0]
+ if len(probabilities) <= 1:
+ return 0.0
+ entropy = -sum(p * math.log(p) for p in probabilities)
+ return entropy / math.log(len(probabilities))
+
+
+def _medoid_index(embeddings: np.ndarray, indices: list[int]) -> int:
+ """Return the index (into ``indices``) whose embedding is closest to the
+ cluster centroid by cosine distance."""
+ if len(indices) == 1:
+ return indices[0]
+ cluster_matrix = embeddings[indices]
+ centroid = cluster_matrix.mean(axis=0)
+ centroid_norm = np.linalg.norm(centroid) or 1.0
+ row_norms = np.linalg.norm(cluster_matrix, axis=1)
+ row_norms = np.where(row_norms == 0, 1.0, row_norms)
+ cosine_sims = (cluster_matrix @ centroid) / (row_norms * centroid_norm)
+ best_local = int(np.argmax(cosine_sims))
+ return indices[best_local]
+
+
+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,
+) -> 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.
+ """
+ if len(records) == 0:
+ return _empty_snapshot(distance_threshold, n_intents=0)
+ assert len(records) == len(labels) == len(embeddings), (
+ f"records ({len(records)}), labels ({len(labels)}), and embeddings ({len(embeddings)}) must be the same length"
+ )
+
+ clusters_by_label: dict[int, list[int]] = defaultdict(list)
+ for i, label in enumerate(labels.tolist()):
+ clusters_by_label[int(label)].append(i)
+
+ clusters: list[dict[str, Any]] = []
+ for cluster_id, member_idx in clusters_by_label.items():
+ members = [records[i] for i in member_idx]
+
+ tool_counts: Counter[str] = Counter()
+ error_counts: Counter[str] = Counter()
+ for record in members:
+ tool_counts.update(record.tool_counts)
+ error_counts.update(record.error_counts)
+
+ total_calls = sum(tool_counts.values())
+ tool_distribution = [
+ {
+ "tool": tool,
+ "count": count,
+ "pct": round(100.0 * count / total_calls, 1) if total_calls else 0.0,
+ "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,
+ }
+ for tool, count in tool_counts.most_common()
+ ]
+
+ medoid_pos = _medoid_index(embeddings, member_idx)
+ sample_intents = [
+ record.intent_text
+ for record in sorted(members, key=lambda r: r.frequency, reverse=True)[:MAX_SAMPLE_INTENTS_PER_CLUSTER]
+ ]
+
+ 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)),
+ "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,
+ "tool_distribution": tool_distribution,
+ "sample_intents": sample_intents,
+ "routing_entropy": round(_routing_entropy(tool_counts), 3),
+ "journey": (journeys_by_cluster or {}).get(cluster_id),
+ }
+ )
+
+ # Sort clusters by call volume desc so the UI shows the most impactful first.
+ clusters.sort(key=lambda c: c["call_count"], reverse=True)
+
+ return {
+ "clusters": clusters,
+ "computed_with": {
+ "distance_threshold": distance_threshold,
+ "embedding_model": EMBEDDING_MODEL,
+ "n_intents": len(records),
+ "n_clusters": len(clusters),
+ },
+ }
+
+
+def _empty_snapshot(distance_threshold: float, n_intents: int) -> dict[str, Any]:
+ return {
+ "clusters": [],
+ "computed_with": {
+ "distance_threshold": distance_threshold,
+ "embedding_model": EMBEDDING_MODEL,
+ "n_intents": n_intents,
+ "n_clusters": 0,
+ },
+ }
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index f1ba6bf4320a..8074fb56c26a 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -1,16 +1,289 @@
-from django.db.models import QuerySet
+from datetime import timedelta
+from typing import Any
+from django.db.models import CharField, F, Func, Q, QuerySet, Value
+from django.utils import timezone
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.person import Person
+from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.models.team.team import Team
from posthog.models.user import User
from products.mcp_analytics.backend.facade import contracts, enums
-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession
+
+MCP_TOOL_CALL_EVENT = "mcp_tool_call"
+
+# How long a snapshot may sit in COMPUTING before we assume the task died and
+# auto-recover. Generous because a real recompute completes in well under a
+# minute even at the top_n=500 cap; anything past 10 minutes is a dead task.
+STALE_COMPUTING_THRESHOLD = timedelta(minutes=10)
+
+_MCP_TOOL_CALLS_SQL = """
+SELECT
+ uuid AS event_id,
+ timestamp,
+ toString(properties.$mcp_tool_name) AS tool_name,
+ toString(properties.$mcp_intent) AS intent,
+ toString(properties.$mcp_is_error) AS is_error_raw,
+ toString(properties.$mcp_error_message) AS error_message,
+ toString(properties.$mcp_duration_ms) AS duration_ms_raw
+FROM events
+WHERE event = {event}
+ AND properties.$mcp_conversation_id = {session_id}
+ORDER BY timestamp ASC
+LIMIT 500
+"""
def list_submissions(team: Team, kind: enums.SubmissionKind) -> QuerySet[MCPAnalyticsSubmission]:
return MCPAnalyticsSubmission.objects.filter(team=team, kind=kind).order_by("-created_at")
+SESSION_SORT_FIELDS: frozenset[str] = frozenset(
+ {
+ "session_id",
+ "session_start",
+ "session_end",
+ "duration_seconds",
+ "tool_call_count",
+ "mcp_client_name",
+ "distinct_id",
+ }
+)
+DEFAULT_SESSION_ORDER_BY = "-session_end"
+
+
+def _normalise_order_by(order_by: str) -> str:
+ """Validate and normalise the order_by query param.
+
+ Accepts a single column with an optional leading '-' for descending. Falls
+ back to the default if the field isn't whitelisted; we don't want a stray
+ query param to ORDER BY an arbitrary column.
+ """
+ raw = (order_by or "").strip()
+ if not raw:
+ return DEFAULT_SESSION_ORDER_BY
+ descending = raw.startswith("-")
+ field = raw.lstrip("-")
+ if field not in SESSION_SORT_FIELDS:
+ return DEFAULT_SESSION_ORDER_BY
+ return f"-{field}" if descending else field
+
+
+def list_mcp_sessions(
+ team: Team,
+ limit: int,
+ offset: int,
+ search: str = "",
+ order_by: str = "",
+) -> list[contracts.MCPSession]:
+ """Read the denormalized session metadata that the Temporal backfill maintains.
+
+ Person email/name are resolved on the fly by joining MCPSession.distinct_id to
+ the Person model (routed through personhog), matching how SessionRecording
+ handles it. event_count is approximated by the size of tools_used since the
+ new table does not carry a per-call counter.
+
+ ``search`` does case-insensitive substring matching across session_id,
+ distinct_id, mcp_client_name, and any element of tools_used.
+
+ ``order_by`` is a whitelisted column name; prefix with '-' for descending.
+ """
+ queryset: QuerySet[MCPSession] = MCPSession.objects.filter(team=team)
+ term = search.strip()
+ if term:
+ # tools_used is a Postgres array; flatten it to a single string so a single
+ # ILIKE catches the substring match across all tool names.
+ queryset = queryset.annotate(
+ _tools_used_text=Func(
+ F("tools_used"),
+ Value(" "),
+ function="array_to_string",
+ output_field=CharField(),
+ )
+ ).filter(
+ Q(session_id__icontains=term)
+ | Q(distinct_id__icontains=term)
+ | Q(mcp_client_name__icontains=term)
+ | Q(_tools_used_text__icontains=term)
+ )
+ rows = list(queryset.order_by(_normalise_order_by(order_by))[offset : offset + limit])
+ persons_by_distinct_id = _resolve_persons(team.id, rows)
+ return [_to_session_contract(row, persons_by_distinct_id) for row in rows]
+
+
+def _resolve_persons(team_id: int, rows: list[MCPSession]) -> dict[str, Person]:
+ distinct_ids = list({row.distinct_id for row in rows if row.distinct_id})
+ if not distinct_ids:
+ return {}
+ return get_persons_mapped_by_distinct_id(team_id, distinct_ids)
+
+
+def _person_display(person: Person | None) -> dict[str, str]:
+ if person is None:
+ return {"email": "", "name": ""}
+ props = person.properties or {}
+ return {
+ "email": str(props.get("email") or ""),
+ "name": str(props.get("name") or ""),
+ }
+
+
+def _to_session_contract(row: MCPSession, persons_by_distinct_id: dict[str, Person]) -> contracts.MCPSession:
+ person_display = _person_display(persons_by_distinct_id.get(row.distinct_id))
+ tools_used = list(row.tools_used or [])
+ return contracts.MCPSession(
+ session_id=row.session_id,
+ tool_calls=row.tool_call_count,
+ session_start=row.session_start,
+ session_end=row.session_end,
+ distinct_id_count=0,
+ tools_used=tools_used,
+ mcp_client_name=row.mcp_client_name or "",
+ distinct_id=row.distinct_id or "",
+ person_email=person_display["email"],
+ person_name=person_display["name"],
+ intent=row.intent or "",
+ )
+
+
+def list_mcp_tool_calls(team: Team, session_id: str) -> list[contracts.MCPToolCall]:
+ query = parse_select(
+ _MCP_TOOL_CALLS_SQL,
+ placeholders={
+ "event": ast.Constant(value=MCP_TOOL_CALL_EVENT),
+ "session_id": ast.Constant(value=session_id),
+ },
+ )
+ with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):
+ response = execute_hogql_query(query=query, team=team)
+ return [
+ contracts.MCPToolCall(
+ event_id=str(row[0]) if row[0] else "",
+ timestamp=row[1],
+ tool_name=row[2] or "",
+ intent=row[3] or "",
+ is_error=str(row[4]).lower() in ("true", "1"),
+ error_message=row[5] or "",
+ duration_ms=_parse_int(row[6]),
+ )
+ for row in (response.results or [])
+ ]
+
+
+def _parse_int(value: str | int | None) -> int | None:
+ if value is None or value == "" or value == "null":
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:
+ """Return the current intent cluster snapshot for a team.
+
+ When no snapshot exists yet, returns an empty IDLE one so callers can
+ render the "compute" CTA without distinguishing "missing" from "empty".
+
+ Defensive side effect: any row stuck in COMPUTING past
+ STALE_COMPUTING_THRESHOLD is auto-flipped to ERROR so the UI can offer
+ a retry. The Celery task may have died between writing COMPUTING and
+ writing its final status (worker restart, OOM, etc.) and otherwise has
+ no path back to a usable state.
+ """
+ MCPIntentClusterSnapshot.objects.filter(
+ team=team,
+ status=MCPIntentClusterSnapshot.Status.COMPUTING,
+ updated_at__lt=timezone.now() - STALE_COMPUTING_THRESHOLD,
+ ).update(
+ status=MCPIntentClusterSnapshot.Status.ERROR,
+ error_message="Recompute task did not complete within the expected window. Retry to try again.",
+ )
+
+ snapshot = MCPIntentClusterSnapshot.objects.filter(team=team).select_related("last_computed_by").first()
+ if snapshot is None:
+ return contracts.IntentClusterSnapshot(
+ status=MCPIntentClusterSnapshot.Status.IDLE,
+ error_message="",
+ last_computed_at=None,
+ last_computed_by_email="",
+ clusters=[],
+ computed_with=None,
+ )
+
+ blob = snapshot.clusters or {}
+ clusters_raw = blob.get("clusters", []) if isinstance(blob, dict) else []
+ meta_raw = blob.get("computed_with") if isinstance(blob, dict) else None
+
+ return contracts.IntentClusterSnapshot(
+ status=snapshot.status,
+ error_message=snapshot.error_message,
+ last_computed_at=snapshot.last_computed_at,
+ 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,
+ )
+
+
+def _to_cluster_dto(item: dict[str, Any]) -> contracts.IntentCluster:
+ journey_raw = item.get("journey")
+ return contracts.IntentCluster(
+ id=int(item.get("id", 0)),
+ label=str(item.get("label", "")),
+ intent_count=int(item.get("intent_count", 0)),
+ session_count=int(item.get("session_count", 0)),
+ call_count=int(item.get("call_count", 0)),
+ error_count=int(item.get("error_count", 0)),
+ error_rate_pct=float(item.get("error_rate_pct", 0.0)),
+ routing_entropy=float(item.get("routing_entropy", 0.0)),
+ tool_distribution=[
+ contracts.IntentClusterToolEntry(
+ tool=str(entry.get("tool", "")),
+ count=int(entry.get("count", 0)),
+ pct=float(entry.get("pct", 0.0)),
+ errors=int(entry.get("errors", 0)),
+ error_rate_pct=float(entry.get("error_rate_pct", 0.0)),
+ )
+ for entry in item.get("tool_distribution", [])
+ if isinstance(entry, dict)
+ ],
+ 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,
+ )
+
+
+def _to_journey_path_dto(path: dict[str, Any]) -> contracts.IntentClusterJourneyPath:
+ return contracts.IntentClusterJourneyPath(
+ steps=[str(s) if s is not None else None for s in path.get("steps", [])],
+ outcome=str(path.get("outcome", "completed")),
+ count=int(path.get("count", 0)),
+ )
+
+
+def _to_journey_dto(journey: dict[str, Any]) -> contracts.IntentClusterJourney:
+ return contracts.IntentClusterJourney(
+ paths=[_to_journey_path_dto(p) for p in journey.get("paths", []) if isinstance(p, dict)],
+ total_sessions=int(journey.get("total_sessions", 0)),
+ leak=(_to_journey_path_dto(journey["leak"]) if isinstance(journey.get("leak"), dict) else None),
+ )
+
+
+def _to_meta_dto(meta: dict[str, Any]) -> contracts.IntentClusterSnapshotMeta:
+ return contracts.IntentClusterSnapshotMeta(
+ distance_threshold=float(meta.get("distance_threshold", 0.0)),
+ embedding_model=str(meta.get("embedding_model", "")),
+ n_intents=int(meta.get("n_intents", 0)),
+ n_clusters=int(meta.get("n_clusters", 0)),
+ )
+
+
def create_feedback_submission(
team: Team, created_by: User | None, submission: contracts.CreateFeedbackSubmission
) -> MCPAnalyticsSubmission:
diff --git a/products/mcp_analytics/backend/management/__init__.py b/products/mcp_analytics/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_analytics/backend/management/commands/__init__.py b/products/mcp_analytics/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py b/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py
new file mode 100644
index 000000000000..1968b6a0fa75
--- /dev/null
+++ b/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py
@@ -0,0 +1,96 @@
+"""Manual end-to-end validation for the intent clustering pipeline.
+
+Runs the same Celery task that powers the API, synchronously, against a
+real team's ClickHouse data, and pretty-prints the resulting snapshot.
+"""
+
+import json
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandParser
+
+from posthog.models.scoping import team_scope
+from posthog.models.team.team import Team
+
+from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot
+from products.mcp_analytics.backend.tasks.tasks import compute_intent_clusters
+
+
+class Command(BaseCommand):
+ help = "Run intent clustering for a team and pretty-print the resulting snapshot."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True, help="Team ID to cluster intents for.")
+ parser.add_argument(
+ "--raw",
+ action="store_true",
+ help="Print the raw JSON snapshot instead of the human-readable summary.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_id: int = options["team_id"]
+ raw: bool = options["raw"]
+
+ try:
+ Team.objects.get(pk=team_id)
+ except Team.DoesNotExist:
+ self.stderr.write(self.style.ERROR(f"Team {team_id} does not exist."))
+ return
+
+ self.stdout.write(f"Running intent clustering for team {team_id}...")
+ compute_intent_clusters.apply(args=[team_id, None]).get()
+
+ with team_scope(team_id):
+ snapshot = MCPIntentClusterSnapshot.objects.filter(team_id=team_id).first()
+ if snapshot is None:
+ self.stderr.write(self.style.ERROR("No snapshot was produced."))
+ return
+
+ if snapshot.status == MCPIntentClusterSnapshot.Status.ERROR:
+ self.stderr.write(self.style.ERROR(f"Clustering failed: {snapshot.error_message}"))
+ return
+
+ if raw:
+ self.stdout.write(json.dumps(snapshot.clusters, indent=2))
+ return
+
+ self._print_summary(snapshot)
+
+ def _print_summary(self, snapshot: MCPIntentClusterSnapshot) -> None:
+ blob = snapshot.clusters or {}
+ clusters = blob.get("clusters", [])
+ meta = blob.get("computed_with", {}) or {}
+
+ self.stdout.write(self.style.SUCCESS("✔ Clustering complete"))
+ self.stdout.write(
+ f" computed_at: {snapshot.last_computed_at.isoformat() if snapshot.last_computed_at else '—'}"
+ )
+ self.stdout.write(f" embedding_model: {meta.get('embedding_model', '—')}")
+ self.stdout.write(f" distance_threshold: {meta.get('distance_threshold', '—')}")
+ self.stdout.write(f" n_intents in corpus: {meta.get('n_intents', 0)}")
+ self.stdout.write(f" n_clusters produced: {meta.get('n_clusters', 0)}")
+
+ if not clusters:
+ self.stdout.write(self.style.WARNING("\nNo clusters — likely no mcp_tool_call events with $mcp_intent."))
+ self.stdout.write("Try: ./manage.py seed_mcp_sessions --team-id N")
+ return
+
+ self.stdout.write("\nClusters (sorted by call volume):\n")
+ for cluster in clusters:
+ self.stdout.write(self.style.HTTP_INFO(f" [{cluster['id']}] {cluster['label']!r}"))
+ self.stdout.write(
+ f" intents: {cluster['intent_count']} calls: {cluster['call_count']} "
+ f"errors: {cluster['error_count']} ({cluster['error_rate_pct']}%) "
+ f"routing_entropy: {cluster['routing_entropy']}"
+ )
+ tool_rows = cluster.get("tool_distribution", [])
+ for entry in tool_rows[:5]:
+ self.stdout.write(
+ f" → {entry['tool']}: {entry['count']} calls "
+ f"({entry['pct']}%), errors {entry['errors']} ({entry['error_rate_pct']}%)"
+ )
+ if len(tool_rows) > 5:
+ self.stdout.write(f" … and {len(tool_rows) - 5} more tools")
+ for sample in cluster.get("sample_intents", []):
+ self.stdout.write(f" ✎ {sample}")
+ self.stdout.write("")
diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
new file mode 100644
index 000000000000..53b2881b7494
--- /dev/null
+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
@@ -0,0 +1,245 @@
+import uuid
+import random
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandParser
+
+from posthog.models.event.util import create_event
+from posthog.models.person import Person, PersonDistinctId
+from posthog.models.person.util import create_person, create_person_distinct_id, get_person_by_distinct_id
+from posthog.models.team.team import Team
+from posthog.models.utils import uuid7
+
+TOOL_NAMES = [
+ "query_run",
+ "insight_get",
+ "dashboard_get",
+ "feature_flag_get",
+ "experiment_get",
+ "person_get",
+ "session_recording_get",
+ "error_tracking_issue_get",
+]
+
+CLIENT_NAMES = ["Claude Desktop", "Cursor", "Windsurf", "Cline"]
+
+# Identified personas. About 70% of sessions are attached to one of these;
+# the rest stay anonymous with throwaway distinct_ids.
+IDENTIFIED_PERSONAS: list[dict[str, str]] = [
+ {
+ "distinct_id": "[email protected]",
+ "email": "[email protected]",
+ "name": "Alice Hedgehog",
+ "role": "Product engineer",
+ },
+ {"distinct_id": "[email protected]", "email": "[email protected]", "name": "Ben Hedgehog", "role": "Data scientist"},
+ {
+ "distinct_id": "[email protected]",
+ "email": "[email protected]",
+ "name": "Carol Hedgehog",
+ "role": "Product manager",
+ },
+ {
+ "distinct_id": "[email protected]",
+ "email": "[email protected]",
+ "name": "Dan Hedgehog",
+ "role": "Engineering manager",
+ },
+]
+IDENTIFIED_PROBABILITY = 0.7
+
+INTENTS_BY_TOOL: dict[str, list[str]] = {
+ "query_run": [
+ "Investigating yesterday's spike in checkout failures by querying revenue and error events for the last 24 hours.",
+ "Pulling the funnel conversion numbers for the new pricing page to share in the product weekly review.",
+ "Validating that the latest deploy did not regress signup completion rate before announcing the release.",
+ ],
+ "insight_get": [
+ "Fetching the active users dashboard insight to summarise growth trends in the leadership Slack channel.",
+ "Loading the retention curve insight so we can compare last cohort to the previous one in the product review.",
+ ],
+ "dashboard_get": [
+ "Opening the platform health dashboard to triage user-reported latency complaints from this morning.",
+ ],
+ "feature_flag_get": [
+ "Checking whether the new pricing flag is rolled out to the cohort experiencing the support issue.",
+ ],
+ "experiment_get": [
+ "Reviewing the running pricing experiment to decide whether we have enough power to call a winner this week.",
+ ],
+ "person_get": [
+ "Looking up the reporter of a paid plan billing complaint to confirm their plan history before refunding.",
+ ],
+ "session_recording_get": [
+ "Replaying the session where the user got stuck on signup to understand the friction point before filing a bug.",
+ ],
+ "error_tracking_issue_get": [
+ "Pulling the latest exception issue tied to the deploy so the on-call can triage the regression quickly.",
+ ],
+}
+DEFAULT_INTENT = "Helping the user investigate a recent product-analytics question without a specific recorded intent."
+
+
+# Session-level summarised intents. These intentionally repeat themes so the
+# clustering pipeline has something to cluster: variants of "check a feature
+# flag rollout" should land in one cluster, variants of "look up the reporter
+# of a billing issue" in another, etc.
+SESSION_INTENTS: list[str] = [
+ "Investigate yesterday's spike in checkout failures using revenue and error events.",
+ "Look into the unusual drop in checkout completion that started overnight.",
+ "Pull funnel conversion numbers for the new pricing page for the weekly product review.",
+ "Compare pricing page funnel performance week over week ahead of the product review.",
+ "Check whether the new pricing feature flag is fully rolled out to the affected cohort.",
+ "Confirm rollout status of the pricing feature flag for a support escalation.",
+ "Review the active pricing experiment and decide whether we have the power to call a winner.",
+ "Pull active users metrics to share growth trends in the leadership Slack channel.",
+ "Compare last cohort's retention curve to the previous one for the product review.",
+ "Triage user-reported latency complaints from this morning using the platform health dashboard.",
+ "Look up the reporter of a paid plan billing complaint before processing a refund.",
+ "Replay the signup session where the user got stuck so we can file a precise bug report.",
+ "Pull the latest exception issue tied to the deploy so on-call can triage the regression.",
+]
+
+
+class Command(BaseCommand):
+ help = "Seed mcp_tool_call events into ClickHouse for local testing of MCP analytics."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True, help="Team ID to seed events for.")
+ parser.add_argument("--sessions", type=int, default=10, help="Number of sessions to create.")
+ parser.add_argument("--min-calls", type=int, default=4, help="Minimum tool calls per session (inclusive).")
+ parser.add_argument("--max-calls", type=int, default=6, help="Maximum tool calls per session (inclusive).")
+ parser.add_argument("--seed", type=int, default=None, help="Optional random seed for reproducible output.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_id: int = options["team_id"]
+ session_count: int = options["sessions"]
+ min_calls: int = options["min_calls"]
+ max_calls: int = options["max_calls"]
+ seed: int | None = options["seed"]
+
+ if min_calls > max_calls:
+ self.stderr.write(self.style.ERROR("--min-calls must be <= --max-calls"))
+ return
+
+ try:
+ team = Team.objects.get(pk=team_id)
+ except Team.DoesNotExist:
+ self.stderr.write(self.style.ERROR(f"Team {team_id} does not exist."))
+ return
+
+ rng = random.Random(seed)
+ now = datetime.now(tz=UTC)
+ total_events = 0
+
+ # Create the identified personas. We write each one to BOTH Postgres
+ # (Person + PersonDistinctId) and ClickHouse (via create_person) so the
+ # distinct_id -> Person lookup in list_mcp_sessions can resolve name/email.
+ for persona in IDENTIFIED_PERSONAS:
+ properties = {
+ "email": persona["email"],
+ "name": persona["name"],
+ "role": persona["role"],
+ }
+ existing_person = get_person_by_distinct_id(team_id=team.id, distinct_id=persona["distinct_id"])
+ if existing_person:
+ person = existing_person
+ person.properties = properties
+ person.is_identified = True
+ person.save(update_fields=["properties", "is_identified"])
+ else:
+ person = Person.objects.create( # nosemgrep: no-direct-persons-db-orm
+ team=team, properties=properties, is_identified=True
+ )
+ PersonDistinctId.objects.create( # nosemgrep: no-direct-persons-db-orm
+ team=team, distinct_id=persona["distinct_id"], person=person
+ )
+ person_uuid = str(person.uuid)
+ create_person(
+ team_id=team.id,
+ uuid=person_uuid,
+ version=0,
+ is_identified=True,
+ properties=properties,
+ )
+ create_person_distinct_id(
+ team_id=team.id,
+ distinct_id=persona["distinct_id"],
+ person_id=person_uuid,
+ )
+
+ for session_idx in range(session_count):
+ # $mcp_conversation_id is the canonical session grouping key emitted by the MCP
+ # service. Use uuid4 because that's the format the real service emits (e.g.
+ # ba10420e-7ff2-4253-a6ac-3e404f14f8be).
+ conversation_id = str(uuid.uuid4())
+ # $session_id keeps the PostHog uuid7 convention so session-replay-style
+ # consumers don't choke on it.
+ session_id = str(uuid7())
+ if rng.random() < IDENTIFIED_PROBABILITY:
+ persona = rng.choice(IDENTIFIED_PERSONAS)
+ distinct_id = persona["distinct_id"]
+ else:
+ distinct_id = f"anon_{uuid.uuid4().hex[:8]}"
+ client_name = rng.choice(CLIENT_NAMES)
+ calls = rng.randint(min_calls, max_calls)
+ # Anchor each session so it is in the sweet spot for BOTH workflows on the
+ # next scheduled tick:
+ # * Backfill discover window = last 1 hour → session must have at
+ # least one event in the last hour, so session_end >= now - 1h.
+ # * Summariser idle filter = >= 30 min → session_end <= now - 30 min.
+ # Picking session_end uniformly in 31-59 minutes ago places every seeded
+ # session in that overlap, so a single seed run yields an immediately
+ # backfill-able and immediately summarise-able fixture.
+ call_intervals = [rng.randint(15, 90) for _ in range(calls)]
+ total_call_duration = timedelta(seconds=sum(call_intervals))
+ session_end_offset_min = rng.randint(31, 59)
+ session_start = now - timedelta(minutes=session_end_offset_min) - total_call_duration
+
+ cumulative_offset_s = 0
+ for call_idx in range(calls):
+ cumulative_offset_s += call_intervals[call_idx]
+ timestamp = session_start + timedelta(seconds=cumulative_offset_s)
+ tool_name = rng.choice(TOOL_NAMES)
+ # Skew error rate and latency per tool so the Tool quality tab has variation.
+ tool_error_rate = (hash(tool_name) % 30) / 100.0
+ is_error = rng.random() < tool_error_rate
+ base_latency = 80 + (hash(tool_name) % 400)
+ duration_ms = max(1, int(rng.gauss(base_latency, base_latency * 0.4)))
+ if is_error:
+ duration_ms = int(duration_ms * rng.uniform(1.5, 3.0))
+ intent = rng.choice(INTENTS_BY_TOOL.get(tool_name, [DEFAULT_INTENT]))
+ create_event(
+ event_uuid=uuid.uuid4(),
+ event="mcp_tool_call",
+ team=team,
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties={
+ "$session_id": session_id,
+ "$mcp_conversation_id": conversation_id,
+ "$mcp_tool_name": tool_name,
+ "$mcp_intent": intent,
+ "$mcp_error_message": "Upstream returned 500" if is_error else "",
+ "$mcp_client_name": client_name,
+ "$mcp_client_version": "1.0.0",
+ "$mcp_protocol_version": "2025-03-26",
+ "$mcp_transport": "streamable_http",
+ "$mcp_duration_ms": duration_ms,
+ "$mcp_is_error": is_error,
+ },
+ )
+ total_events += 1
+
+ # Don't write to MCPSession directly — the backfill Temporal activity is
+ # the source of truth and will derive the row from the events we just
+ # captured. Pre-populating here would produce duplicates keyed on the
+ # uuid7 $session_id instead of the uuid4 $mcp_conversation_id.
+ self.stdout.write(
+ f" session {session_idx + 1}/{session_count}: {calls} tool calls (conversation_id={conversation_id})"
+ )
+
+ self.stdout.write(
+ self.style.SUCCESS(f"Seeded {session_count} sessions ({total_events} events) for team {team_id}.")
+ )
diff --git a/products/mcp_analytics/backend/migrations/0002_mcpsession.py b/products/mcp_analytics/backend/migrations/0002_mcpsession.py
new file mode 100644
index 000000000000..7963638e21bc
--- /dev/null
+++ b/products/mcp_analytics/backend/migrations/0002_mcpsession.py
@@ -0,0 +1,70 @@
+# Generated by Django 5.2.13 on 2026-05-14 01:59
+
+import django.db.models.deletion
+import django.contrib.postgres.fields
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mcp_analytics", "0001_initial"),
+ ("posthog", "1152_fix_device_bucketing_persist_across_auth"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="MCPSession",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("session_id", models.CharField(max_length=64)),
+ ("session_start", models.DateTimeField()),
+ ("session_end", models.DateTimeField()),
+ ("duration_seconds", models.IntegerField()),
+ (
+ "tools_used",
+ django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(max_length=200),
+ blank=True,
+ default=list,
+ size=None,
+ ),
+ ),
+ (
+ "distinct_id",
+ models.CharField(blank=True, default="", max_length=400),
+ ),
+ (
+ "mcp_client_name",
+ models.CharField(blank=True, default="", max_length=200),
+ ),
+ ("intent", models.TextField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_mcp_session",
+ "ordering": ["-session_end"],
+ "indexes": [
+ models.Index(
+ fields=["team", "-session_end"],
+ name="posthog_mcp_team_id_b561f4_idx",
+ )
+ ],
+ "constraints": [models.UniqueConstraint(fields=("team", "session_id"), name="unique_mcp_session")],
+ },
+ ),
+ ]
diff --git a/products/mcp_analytics/backend/migrations/0003_mcpsession_tool_call_count.py b/products/mcp_analytics/backend/migrations/0003_mcpsession_tool_call_count.py
new file mode 100644
index 000000000000..fff811cf9094
--- /dev/null
+++ b/products/mcp_analytics/backend/migrations/0003_mcpsession_tool_call_count.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.13 on 2026-05-14 02:54
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mcp_analytics", "0002_mcpsession"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="mcpsession",
+ name="tool_call_count",
+ field=models.IntegerField(default=0),
+ ),
+ ]
diff --git a/products/mcp_analytics/backend/migrations/0004_mcpintentclustersnapshot.py b/products/mcp_analytics/backend/migrations/0004_mcpintentclustersnapshot.py
new file mode 100644
index 000000000000..bad204fc0b7b
--- /dev/null
+++ b/products/mcp_analytics/backend/migrations/0004_mcpintentclustersnapshot.py
@@ -0,0 +1,61 @@
+# Generated by Django 5.2.13 on 2026-05-14 01:11
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mcp_analytics", "0003_mcpsession_tool_call_count"),
+ ("posthog", "1152_fix_device_bucketing_persist_across_auth"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="MCPIntentClusterSnapshot",
+ fields=[
+ (
+ "team",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ related_name="mcp_intent_cluster_snapshot",
+ serialize=False,
+ to="posthog.team",
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("idle", "Idle"),
+ ("computing", "Computing"),
+ ("error", "Error"),
+ ],
+ default="idle",
+ max_length=16,
+ ),
+ ),
+ ("error_message", models.TextField(blank=True, default="")),
+ ("clusters", models.JSONField(default=dict)),
+ ("last_computed_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "last_computed_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_mcp_analytics_intent_cluster_snapshot",
+ },
+ ),
+ ]
diff --git a/products/mcp_analytics/backend/migrations/max_migration.txt b/products/mcp_analytics/backend/migrations/max_migration.txt
index cbab66dde92a..94ca7122ec1f 100644
--- a/products/mcp_analytics/backend/migrations/max_migration.txt
+++ b/products/mcp_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0004_mcpintentclustersnapshot
diff --git a/products/mcp_analytics/backend/models.py b/products/mcp_analytics/backend/models.py
index bfb991e58d8e..c42ac391687e 100644
--- a/products/mcp_analytics/backend/models.py
+++ b/products/mcp_analytics/backend/models.py
@@ -1,10 +1,39 @@
"""Django models for mcp_analytics."""
+from django.contrib.postgres.fields import ArrayField
from django.db import models
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDModel
+class MCPIntentClusterSnapshot(TeamScopedRootMixin):
+ class Status(models.TextChoices):
+ IDLE = "idle", "Idle"
+ COMPUTING = "computing", "Computing"
+ ERROR = "error", "Error"
+
+ team = models.OneToOneField(
+ "posthog.Team",
+ on_delete=models.CASCADE,
+ primary_key=True,
+ related_name="mcp_intent_cluster_snapshot",
+ )
+ last_computed_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
+ )
+ status = models.CharField(max_length=16, choices=Status.choices, default=Status.IDLE)
+ error_message = models.TextField(blank=True, default="")
+ # Full denormalized snapshot: {clusters: [{id, label, intent_count, ...}], computed_with: {...}}
+ clusters = models.JSONField(default=dict)
+ last_computed_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "posthog_mcp_analytics_intent_cluster_snapshot"
+
+
class MCPAnalyticsSubmission(UUIDModel):
class Kind(models.TextChoices):
FEEDBACK = "feedback", "Feedback"
@@ -46,3 +75,31 @@ class MCPAnalyticsSubmission(UUIDModel):
models.Index(fields=["team", "mcp_session_id"]),
models.Index(fields=["team", "mcp_trace_id"]),
]
+
+
+class MCPSession(UUIDModel, TeamScopedRootMixin):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+ session_id = models.CharField(max_length=64)
+
+ session_start = models.DateTimeField()
+ session_end = models.DateTimeField()
+ duration_seconds = models.IntegerField()
+
+ tools_used = ArrayField(models.CharField(max_length=200), default=list, blank=True)
+ tool_call_count = models.IntegerField(default=0)
+ distinct_id = models.CharField(max_length=400, blank=True, default="")
+ mcp_client_name = models.CharField(max_length=200, blank=True, default="")
+ intent = models.TextField(null=True, blank=True)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "posthog_mcp_session"
+ ordering = ["-session_end"]
+ constraints = [
+ models.UniqueConstraint(fields=["team", "session_id"], name="unique_mcp_session"),
+ ]
+ indexes = [
+ models.Index(fields=["team", "-session_end"]),
+ ]
diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.py
index 5b28e800ce4a..3ab3cd015092 100644
--- a/products/mcp_analytics/backend/presentation/serializers.py
+++ b/products/mcp_analytics/backend/presentation/serializers.py
@@ -122,6 +122,198 @@ class MCPFeedbackCreateSerializer(MCPAnalyticsSubmissionContextSerializer):
)
+class MCPToolCallSerializer(serializers.Serializer):
+ event_id = serializers.CharField(read_only=True, help_text="ClickHouse uuid of the mcp_tool_call event.")
+ timestamp = serializers.DateTimeField(read_only=True, help_text="When the tool call was captured.")
+ tool_name = serializers.CharField(read_only=True, help_text="Tool that was invoked ($mcp_tool_name).")
+ intent = serializers.CharField(
+ read_only=True,
+ help_text="Agent intent for this tool call ($mcp_intent). Empty when the SDK did not capture context.",
+ )
+ is_error = serializers.BooleanField(read_only=True, help_text="Whether the tool call resulted in an error.")
+ error_message = serializers.CharField(
+ read_only=True, help_text="Error message when is_error is true, otherwise empty."
+ )
+ duration_ms = serializers.IntegerField(
+ read_only=True, allow_null=True, help_text="Duration of the tool call in milliseconds when captured."
+ )
+
+
+class MCPSessionSerializer(serializers.Serializer):
+ session_id = serializers.CharField(
+ read_only=True, help_text="PostHog $session_id grouping all mcp_tool_call events."
+ )
+ tool_calls = serializers.IntegerField(
+ read_only=True, help_text="Total number of mcp_tool_call events in the session."
+ )
+ session_start = serializers.DateTimeField(
+ read_only=True, help_text="Timestamp of the first mcp_tool_call event in the session."
+ )
+ session_end = serializers.DateTimeField(
+ read_only=True, help_text="Timestamp of the most recent mcp_tool_call event in the session."
+ )
+ distinct_id_count = serializers.IntegerField(
+ read_only=True, help_text="Number of distinct PostHog distinct_ids that produced events in the session."
+ )
+ tools_used = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text="Distinct $mcp_tool_name values seen in the session.",
+ )
+ mcp_client_name = serializers.CharField(
+ read_only=True, help_text="Most recent $mcp_client_name observed in the session."
+ )
+ distinct_id = serializers.CharField(
+ read_only=True,
+ help_text="Most recent distinct_id observed for the session. Stable identifier the SDK tagged the events with.",
+ )
+ person_email = serializers.CharField(
+ read_only=True,
+ help_text="email property of the Person resolved from distinct_id; empty when no Person is mapped.",
+ )
+ person_name = serializers.CharField(
+ read_only=True,
+ help_text="name property of the Person resolved from distinct_id; empty when no Person is mapped.",
+ )
+ intent = serializers.CharField(
+ read_only=True,
+ help_text="LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until the summary workflow runs.",
+ )
+
+
+class MCPIntentClusterToolEntrySerializer(serializers.Serializer):
+ tool = serializers.CharField(read_only=True, help_text="MCP tool name that received calls for this cluster.")
+ count = serializers.IntegerField(
+ read_only=True, help_text="Number of tool calls routed to this tool across the cluster."
+ )
+ pct = serializers.FloatField(
+ read_only=True, help_text="Percentage of the cluster's calls that went to this tool, 0–100."
+ )
+ errors = serializers.IntegerField( # type: ignore[assignment]
+ read_only=True, help_text="Number of error responses observed for this tool within the cluster."
+ )
+ error_rate_pct = serializers.FloatField(
+ read_only=True, help_text="Error rate for this tool within the cluster, 0–100."
+ )
+
+
+class MCPIntentClusterJourneyPathSerializer(serializers.Serializer):
+ steps = serializers.ListField(
+ child=serializers.CharField(allow_null=True),
+ read_only=True,
+ help_text=(
+ "Ordered tool names called during the path. Length is fixed; null entries "
+ "indicate the session ended before this step."
+ ),
+ )
+ outcome = serializers.ChoiceField(
+ choices=[("completed", "Completed"), ("error", "Error")],
+ read_only=True,
+ help_text="Terminal outcome of the sessions following this path.",
+ )
+ count = serializers.IntegerField(
+ read_only=True, help_text="Number of sessions in this cluster that followed this exact path."
+ )
+
+
+class MCPIntentClusterJourneySerializer(serializers.Serializer):
+ paths = MCPIntentClusterJourneyPathSerializer(
+ many=True,
+ read_only=True,
+ help_text="Top paths by session count, capped at MAX_JOURNEY_PATHS_PER_CLUSTER.",
+ )
+ total_sessions = serializers.IntegerField(
+ read_only=True, help_text="Total session count represented across all paths in this cluster."
+ )
+ leak = MCPIntentClusterJourneyPathSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="Highest-volume non-completed path. Null when every path completed successfully.",
+ )
+
+
+class MCPIntentClusterSerializer(serializers.Serializer):
+ id = serializers.IntegerField(read_only=True, help_text="Stable cluster identifier within this snapshot.")
+ label = serializers.CharField( # type: ignore[assignment]
+ read_only=True,
+ help_text="Representative intent text for the cluster (the medoid intent closest to the cluster centroid).",
+ )
+ intent_count = serializers.IntegerField(
+ read_only=True, help_text="Number of distinct intent texts that belong to this cluster."
+ )
+ session_count = serializers.IntegerField(
+ read_only=True, help_text="Number of MCP sessions whose summarised intent belongs to this cluster."
+ )
+ call_count = serializers.IntegerField(
+ read_only=True, help_text="Total number of mcp_tool_call events represented by this cluster."
+ )
+ error_count = serializers.IntegerField(
+ read_only=True, help_text="Total number of error responses observed across the cluster."
+ )
+ error_rate_pct = serializers.FloatField(
+ read_only=True, help_text="Aggregate error rate across all tool calls in the cluster, 0–100."
+ )
+ routing_entropy = serializers.FloatField(
+ read_only=True,
+ help_text=(
+ "Normalised Shannon entropy of the tool distribution. 0 means perfectly consistent routing "
+ "(one tool dominates); 1 means uniformly spread across all tools called for this intent cluster."
+ ),
+ )
+ tool_distribution = MCPIntentClusterToolEntrySerializer(
+ many=True, read_only=True, help_text="Per-tool breakdown of calls and errors within the cluster."
+ )
+ sample_intents = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text="Up to three representative intent strings from the cluster, ordered by frequency desc.",
+ )
+ journey = MCPIntentClusterJourneySerializer(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "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."
+ ),
+ )
+
+
+class MCPIntentClusterSnapshotMetaSerializer(serializers.Serializer):
+ distance_threshold = serializers.FloatField(
+ read_only=True, help_text="Cosine distance threshold used by the clustering algorithm."
+ )
+ embedding_model = serializers.CharField(read_only=True, help_text="Embedding model used to vectorise intents.")
+ n_intents = serializers.IntegerField(
+ 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.")
+
+
+class MCPIntentClusterSnapshotSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=[("idle", "Idle"), ("computing", "Computing"), ("error", "Error")],
+ read_only=True,
+ help_text="Whether a snapshot is current (idle), being recomputed (computing), or failed (error).",
+ )
+ error_message = serializers.CharField(
+ read_only=True, allow_blank=True, help_text="Error message from the most recent failed run, otherwise empty."
+ )
+ last_computed_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the latest snapshot finished computing."
+ )
+ last_computed_by_email = serializers.CharField(
+ read_only=True,
+ allow_blank=True,
+ 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.")
+ 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.",
+ )
+
+
class MCPMissingCapabilityCreateSerializer(MCPAnalyticsSubmissionContextSerializer):
goal = serializers.CharField(max_length=MAX_GOAL_LENGTH, help_text="The user's intended outcome when using MCP.")
missing_capability = serializers.CharField(
diff --git a/products/mcp_analytics/backend/presentation/urls.py b/products/mcp_analytics/backend/presentation/urls.py
index e12e2af00071..768f72aad919 100644
--- a/products/mcp_analytics/backend/presentation/urls.py
+++ b/products/mcp_analytics/backend/presentation/urls.py
@@ -2,9 +2,11 @@
from rest_framework.routers import DefaultRouter
-from .views import MCPFeedbackViewSet, MCPMissingCapabilityViewSet
+from .views import MCPFeedbackViewSet, MCPIntentClusterViewSet, MCPMissingCapabilityViewSet, MCPSessionViewSet
router = DefaultRouter()
router.register(r"feedback", MCPFeedbackViewSet, basename="mcp-analytics-feedback")
router.register(r"missing_capabilities", MCPMissingCapabilityViewSet, basename="mcp-analytics-missing-capability")
+router.register(r"sessions", MCPSessionViewSet, basename="mcp-analytics-sessions")
+router.register(r"intent_clusters", MCPIntentClusterViewSet, basename="mcp-analytics-intent-clusters")
urlpatterns = router.urls
diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.py
index 9cf40b0ff2b8..d69cd6520931 100644
--- a/products/mcp_analytics/backend/presentation/views.py
+++ b/products/mcp_analytics/backend/presentation/views.py
@@ -1,7 +1,11 @@
from typing import Any, cast
-from drf_spectacular.utils import OpenApiResponse, extend_schema
+from django.db.models import QuerySet
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import status, viewsets
+from rest_framework.decorators import action
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
@@ -15,11 +19,15 @@ from posthog.permissions import SingleTenancyOrAdmin
from products.mcp_analytics.backend import logic
from products.mcp_analytics.backend.facade import api, contracts, enums
+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
from .serializers import (
MCPAnalyticsSubmissionSerializer,
MCPFeedbackCreateSerializer,
+ MCPIntentClusterSnapshotSerializer,
MCPMissingCapabilityCreateSerializer,
+ MCPSessionSerializer,
+ MCPToolCallSerializer,
)
@@ -103,6 +111,106 @@ class MCPFeedbackViewSet(BaseMCPAnalyticsSubmissionViewSet):
return self._list_response(request, enums.SubmissionKind.FEEDBACK)
+@extend_schema(tags=["mcp_analytics"])
+class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ serializer_class = MCPSessionSerializer
+ permission_classes = [IsAuthenticated, SingleTenancyOrAdmin]
+ scope_object = "INTERNAL"
+ pagination_class = MCPAnalyticsPagination
+
+ def dangerously_get_queryset(self) -> QuerySet:
+ # Sessions are aggregated from ClickHouse events, not from a Django model.
+ # Returning an empty queryset satisfies DRF's GenericViewSet plumbing.
+ return MCPAnalyticsSubmission.objects.none()
+
+ @extend_schema(
+ operation_id="mcp_analytics_sessions_list",
+ description="List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_conversation_id. Ordered by most recent activity first by default.",
+ parameters=[
+ OpenApiParameter(
+ name="search",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Case-insensitive substring filter matched against session_id, distinct_id, mcp_client_name, and tools_used.",
+ ),
+ OpenApiParameter(
+ name="order_by",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Sort column. Allowed: session_id, session_start, session_end, "
+ "duration_seconds, tool_call_count, mcp_client_name, distinct_id. "
+ "Prefix with '-' for descending. Defaults to '-session_end'."
+ ),
+ ),
+ ],
+ responses={200: MCPSessionSerializer(many=True)},
+ )
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ paginator = self.pagination_class()
+ limit = paginator.get_limit(request) or paginator.default_limit
+ offset = paginator.get_offset(request)
+ search = request.query_params.get("search", "")
+ order_by = request.query_params.get("order_by", "")
+ sessions = api.list_mcp_sessions(self.team, limit=limit, offset=offset, search=search, order_by=order_by)
+ serializer = self.get_serializer(sessions, many=True)
+ return Response({"results": serializer.data})
+
+ @extend_schema(
+ operation_id="mcp_analytics_sessions_tool_calls",
+ description="List all mcp_tool_call events that belong to a given $session_id, in chronological order.",
+ responses={200: MCPToolCallSerializer(many=True)},
+ )
+ @action(detail=True, methods=["get"], url_path="tool_calls")
+ def tool_calls(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:
+ tool_calls = api.list_mcp_tool_calls(self.team, session_id=str(pk or ""))
+ serializer = MCPToolCallSerializer(tool_calls, many=True)
+ return Response({"results": serializer.data})
+
+
+@extend_schema(tags=["mcp_analytics"])
+class MCPIntentClusterViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ serializer_class = MCPIntentClusterSnapshotSerializer
+ permission_classes = [IsAuthenticated, SingleTenancyOrAdmin]
+ scope_object = "INTERNAL"
+ pagination_class = None
+
+ def dangerously_get_queryset(self) -> QuerySet:
+ # Snapshots are read directly via the facade; this satisfies GenericViewSet plumbing.
+ return MCPAnalyticsSubmission.objects.none()
+
+ @extend_schema(
+ operation_id="mcp_analytics_intent_clusters_retrieve",
+ description=(
+ "Return the most recent intent cluster snapshot for the current project. "
+ "Returns an empty IDLE snapshot when no clustering run has happened yet."
+ ),
+ responses={200: MCPIntentClusterSnapshotSerializer},
+ )
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ snapshot = api.get_intent_cluster_snapshot(self.team)
+ serializer = self.get_serializer(snapshot)
+ return Response(serializer.data)
+
+ @extend_schema(
+ operation_id="mcp_analytics_intent_clusters_recompute",
+ description=(
+ "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')."
+ ),
+ request=None,
+ responses={202: MCPIntentClusterSnapshotSerializer},
+ )
+ @action(detail=False, methods=["post"], url_path="recompute")
+ def recompute(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ api.trigger_intent_cluster_recompute(self.team, cast(User, request.user))
+ snapshot = api.get_intent_cluster_snapshot(self.team)
+ serializer = self.get_serializer(snapshot)
+ return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
+
+
class MCPMissingCapabilityViewSet(BaseMCPAnalyticsSubmissionViewSet):
user_action_name = "mcp analytics missing capability reported"
diff --git a/products/mcp_analytics/backend/tasks/__init__.py b/products/mcp_analytics/backend/tasks/__init__.py
index e69de29bb2d1..31aea54bd54b 100644
--- a/products/mcp_analytics/backend/tasks/__init__.py
+++ b/products/mcp_analytics/backend/tasks/__init__.py
@@ -0,0 +1,7 @@
+# Re-export tasks for Celery autodiscover. autodiscover_tasks() imports the
+# `tasks` package (this __init__.py), not its submodules, so any @shared_task
+# defined inside `tasks/tasks.py` needs to be re-exported here to be visible
+# to the worker.
+from products.mcp_analytics.backend.tasks.tasks import compute_intent_clusters
+
+__all__ = ["compute_intent_clusters"]
diff --git a/products/mcp_analytics/backend/tasks/tasks.py b/products/mcp_analytics/backend/tasks/tasks.py
index 81963eb7e2a7..69a8de3135ac 100644
--- a/products/mcp_analytics/backend/tasks/tasks.py
+++ b/products/mcp_analytics/backend/tasks/tasks.py
@@ -1,8 +1,138 @@
-"""
-Celery tasks for mcp_analytics.
+"""Celery tasks for mcp_analytics.
-Async entrypoints that call the facade (facade/api.py).
-Keep task functions thin - only call facade methods.
+Async entrypoints that orchestrate the intent clustering pipeline. Task
+functions stay thin: they coordinate state transitions and call into the pure
+clustering module.
"""
-# from celery import shared_task
-# from ..facade import api
+
+import asyncio
+from typing import Any
+
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+from celery import shared_task
+
+from posthog.models.scoping import with_team_scope
+
+logger = structlog.get_logger(__name__)
+
+
+@shared_task(
+ name="products.mcp_analytics.backend.tasks.compute_intent_clusters",
+ bind=True,
+ ignore_result=True,
+ acks_late=True,
+ max_retries=2,
+)
+@with_team_scope()
+def compute_intent_clusters(self: Any, team_id: int, user_id: int | None = None) -> None:
+ """Recompute the intent cluster snapshot for a team.
+
+ Flow:
+ 1. Mark the snapshot as ``computing`` (creates a row on first run).
+ 2. Fetch the intent corpus, embed it, cluster it, build the snapshot.
+ 3. Persist the snapshot atomically and mark ``idle``.
+ 4. On failure, mark ``error`` with the message; rely on Celery retry.
+ """
+ # Imports inside the task so Celery autoimport doesn't pull heavy deps
+ # (numpy/sklearn/httpx) at worker startup.
+ from posthog.models.team.team import Team
+
+ from products.mcp_analytics.backend import intent_clustering
+ from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot
+
+ try:
+ team = Team.objects.get(pk=team_id)
+ except Team.DoesNotExist:
+ logger.warning("mcp_analytics.intent_clusters.team_not_found", team_id=team_id)
+ return
+
+ user = None
+ if user_id is not None:
+ from posthog.models.user import User
+
+ user = User.objects.filter(pk=user_id).first()
+
+ snapshot, _ = MCPIntentClusterSnapshot.objects.update_or_create(
+ team=team,
+ defaults={
+ "status": MCPIntentClusterSnapshot.Status.COMPUTING,
+ "error_message": "",
+ "last_computed_by": user,
+ },
+ )
+
+ try:
+ records, intent_by_session = intent_clustering.fetch_intent_corpus(team)
+ if not records:
+ _save_empty_snapshot(snapshot)
+ logger.info("mcp_analytics.intent_clusters.no_intents_found", team_id=team_id)
+ return
+
+ embeddings, valid_indices = asyncio.run(
+ intent_clustering.embed_intents_async(team, [r.intent_text for r in records])
+ )
+ if len(valid_indices) == 0:
+ raise RuntimeError("All embedding requests failed")
+
+ aligned_records = [records[i] for i in valid_indices]
+ labels = intent_clustering.cluster_embeddings(embeddings)
+
+ # Fetch ordered tool-call sequences for every session and aggregate
+ # them per cluster so the UI can render a Sankey of agent journeys.
+ session_journeys = intent_clustering.fetch_session_journeys(team, list(intent_by_session.keys()))
+ 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
+ )
+
+ clusters_blob = intent_clustering.build_snapshot(
+ aligned_records, labels, embeddings, journeys_by_cluster=journeys_by_cluster
+ )
+
+ with transaction.atomic():
+ snapshot.clusters = clusters_blob
+ snapshot.status = MCPIntentClusterSnapshot.Status.IDLE
+ snapshot.error_message = ""
+ snapshot.last_computed_at = timezone.now()
+ snapshot.save(update_fields=["clusters", "status", "error_message", "last_computed_at", "updated_at"])
+
+ logger.info(
+ "mcp_analytics.intent_clusters.computed",
+ team_id=team_id,
+ n_intents=len(aligned_records),
+ n_clusters=len(clusters_blob.get("clusters", [])),
+ )
+
+ except Exception as exc:
+ logger.exception("mcp_analytics.intent_clusters.failed", team_id=team_id, error=str(exc))
+ snapshot.status = MCPIntentClusterSnapshot.Status.ERROR
+ snapshot.error_message = str(exc)[:5000]
+ snapshot.save(update_fields=["status", "error_message", "updated_at"])
+ if self.request.retries < self.max_retries:
+ raise self.retry(exc=exc, countdown=60)
+ raise
+
+
+def _save_empty_snapshot(snapshot: Any) -> None:
+ # Importing the module avoids a circular import at worker startup.
+ from products.mcp_analytics.backend.intent_clustering import DEFAULT_DISTANCE_THRESHOLD, EMBEDDING_MODEL
+ from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot
+
+ snapshot.clusters = {
+ "clusters": [],
+ "computed_with": {
+ "distance_threshold": DEFAULT_DISTANCE_THRESHOLD,
+ "embedding_model": EMBEDDING_MODEL,
+ "n_intents": 0,
+ "n_clusters": 0,
+ },
+ }
+ snapshot.status = MCPIntentClusterSnapshot.Status.IDLE
+ snapshot.error_message = ""
+ snapshot.last_computed_at = timezone.now()
+ snapshot.save(update_fields=["clusters", "status", "error_message", "last_computed_at", "updated_at"])
diff --git a/products/mcp_analytics/backend/templates/tool_quality.sql b/products/mcp_analytics/backend/templates/tool_quality.sql
new file mode 100644
index 000000000000..45f665f17e3f
--- /dev/null
+++ b/products/mcp_analytics/backend/templates/tool_quality.sql
@@ -0,0 +1,32 @@
+/*
+-- Per-tool quality metrics for the MCP analytics Tool quality tab.
+-- One row per $mcp_tool_name with call volume, error rate, latency percentiles,
+-- and reach (unique users / sessions / first / last seen).
+--
+-- Source events: `mcp_tool_call`, emitted by the MCP analytics SDK on every
+-- tool invocation. Expected properties:
+-- $mcp_tool_name string
+-- $mcp_is_error boolean
+-- $mcp_duration_ms number (milliseconds)
+-- $session_id string
+*/
+
+SELECT
+ properties.$mcp_tool_name AS tool,
+ count() AS total_calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,
+ round(quantile(0.5)(toFloat(properties.$mcp_duration_ms))) AS p50_duration_ms,
+ round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_duration_ms,
+ uniq(distinct_id) AS users,
+ countDistinctIf(properties.$session_id, properties.$session_id != '') AS sessions,
+ min(timestamp) AS first_seen,
+ max(timestamp) AS last_seen
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND properties.$mcp_tool_name IS NOT NULL
+ AND properties.$mcp_tool_name != ''
+ AND {filters}
+GROUP BY tool
+ORDER BY __ORDER_BY__ __ORDER_DIRECTION__
+LIMIT 200
diff --git a/products/mcp_analytics/backend/tests/__init__.py b/products/mcp_analytics/backend/tests/__init__.py
index e69de29bb2d1..ed249aad4e57 100644
--- a/products/mcp_analytics/backend/tests/__init__.py
+++ b/products/mcp_analytics/backend/tests/__init__.py
@@ -0,0 +1,27 @@
+from contextlib import AbstractContextManager
+
+from posthog.models.scoping import team_scope
+
+
+class _MCPAnalyticsTeamScopedTestMixin:
+ """Wrap setUp/tearDown with team_scope so direct queries against the
+ fail-closed MCPSession / MCPIntentClusterSnapshot managers find a scope.
+ Place this BEFORE the TestCase base in the MRO so its setUp creates
+ self.team first.
+ """
+
+ _team_scope_cm: AbstractContextManager[None] | None = None
+
+ def setUp(self) -> None:
+ super().setUp() # type: ignore[misc]
+ cm = team_scope(self.team.id) # type: ignore[attr-defined]
+ cm.__enter__()
+ self._team_scope_cm = cm
+
+ def tearDown(self) -> None:
+ if self._team_scope_cm is not None:
+ try:
+ self._team_scope_cm.__exit__(None, None, None)
+ finally:
+ self._team_scope_cm = None
+ super().tearDown() # type: ignore[misc]
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index 0b588cc11809..eb096c5c2f8e 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -1,7 +1,12 @@
+from datetime import UTC, datetime, timedelta
+
from posthog.test.base import APIBaseTest
+from posthog.models.utils import uuid7
+
from products.mcp_analytics.backend.facade import api, contracts, enums
-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPSession
+from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
class TestMCPAnalyticsFacade(APIBaseTest):
@@ -52,3 +57,160 @@ class TestMCPAnalyticsFacade(APIBaseTest):
assert len(submissions) == 1
assert submissions[0].kind == enums.SubmissionKind.MISSING_CAPABILITY
+
+
+class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):
+ def _create_session(
+ self,
+ session_id: str,
+ tools_used: list[str],
+ client_name: str = "Claude Desktop",
+ distinct_id: str = "anon_seed",
+ session_start: datetime | None = None,
+ session_end: datetime | None = None,
+ ) -> MCPSession:
+ session_start = session_start or datetime.now(tz=UTC) - timedelta(minutes=5)
+ session_end = session_end or datetime.now(tz=UTC)
+ return MCPSession.objects.create(
+ team=self.team,
+ session_id=session_id,
+ session_start=session_start,
+ session_end=session_end,
+ duration_seconds=int((session_end - session_start).total_seconds()),
+ tools_used=tools_used,
+ distinct_id=distinct_id,
+ mcp_client_name=client_name,
+ )
+
+ def test_lists_sessions_in_newest_first_order(self) -> None:
+ session_a = str(uuid7())
+ session_b = str(uuid7())
+ now = datetime.now(tz=UTC)
+
+ self._create_session(
+ session_a,
+ tools_used=["query_run", "insight_get"],
+ session_start=now - timedelta(minutes=10),
+ session_end=now - timedelta(minutes=8),
+ )
+ self._create_session(
+ session_b,
+ tools_used=["dashboard_get", "query_run"],
+ client_name="Cursor",
+ session_start=now - timedelta(minutes=5),
+ session_end=now - timedelta(minutes=4),
+ )
+
+ sessions = api.list_mcp_sessions(self.team, limit=50, offset=0)
+
+ assert len(sessions) == 2
+ # Newest session_end first
+ assert sessions[0].session_id == session_b
+ assert sessions[0].mcp_client_name == "Cursor"
+ assert sorted(sessions[0].tools_used) == ["dashboard_get", "query_run"]
+ # tool_calls reflects the persisted total from the backfill activity
+ assert sessions[0].tool_calls == 0
+
+ assert sessions[1].session_id == session_a
+ assert sessions[1].mcp_client_name == "Claude Desktop"
+ assert sorted(sessions[1].tools_used) == ["insight_get", "query_run"]
+ assert sessions[1].tool_calls == 0
+
+ def test_returns_empty_list_when_no_sessions(self) -> None:
+ assert api.list_mcp_sessions(self.team, limit=50, offset=0) == []
+
+ def test_search_filters_across_multiple_columns(self) -> None:
+ alice_id = str(uuid7())
+ bob_id = str(uuid7())
+ misc_id = str(uuid7())
+
+ self._create_session(
+ alice_id,
+ tools_used=["query_run", "insight_get"],
+ client_name="Claude Desktop",
+ distinct_id="[email protected]",
+ )
+ self._create_session(
+ bob_id,
+ tools_used=["dashboard_get"],
+ client_name="Cursor",
+ distinct_id="[email protected]",
+ )
+ self._create_session(
+ misc_id,
+ tools_used=["feature_flag_get"],
+ client_name="Windsurf",
+ distinct_id="anon_dead",
+ )
+
+ def search(term: str) -> set[str]:
+ return {s.session_id for s in api.list_mcp_sessions(self.team, limit=50, offset=0, search=term)}
+
+ # distinct_id substring
+ assert search("hedgehog") == {alice_id}
+ # client name, case-insensitive
+ assert search("CURSOR") == {bob_id}
+ # tool name inside the tools_used array
+ assert search("query_run") == {alice_id}
+ # session_id substring — use suffix because uuid7 prefixes (timestamp) collide
+ # when sessions are created microseconds apart.
+ assert search(alice_id[-12:]) == {alice_id}
+ # empty search returns everything we created (DB may contain other rows from
+ # earlier test runs if transactions aren't isolating; subset is enough).
+ assert {alice_id, bob_id, misc_id}.issubset(search(""))
+ # no match
+ assert search("zzzz") == set()
+
+ def test_order_by_whitelist(self) -> None:
+ old_id = str(uuid7())
+ new_id = str(uuid7())
+ big_id = str(uuid7())
+ now = datetime.now(tz=UTC)
+
+ self._create_session(
+ old_id,
+ tools_used=["query_run"],
+ session_start=now - timedelta(minutes=120),
+ session_end=now - timedelta(minutes=110),
+ )
+ old_row = MCPSession.objects.get(session_id=old_id)
+ old_row.tool_call_count = 3
+ old_row.save(update_fields=["tool_call_count"])
+ self._create_session(
+ new_id,
+ tools_used=["dashboard_get"],
+ session_start=now - timedelta(minutes=20),
+ session_end=now - timedelta(minutes=10),
+ )
+ new_row = MCPSession.objects.get(session_id=new_id)
+ new_row.tool_call_count = 1
+ new_row.save(update_fields=["tool_call_count"])
+ self._create_session(
+ big_id,
+ tools_used=["insight_get"],
+ session_start=now - timedelta(minutes=60),
+ session_end=now - timedelta(minutes=50),
+ )
+ big_row = MCPSession.objects.get(session_id=big_id)
+ big_row.tool_call_count = 99
+ big_row.save(update_fields=["tool_call_count"])
+
+ # Restrict to the three we just created so other rows don't interfere.
+ target = {old_id, new_id, big_id}
+
+ def order(value: str) -> list[str]:
+ return [
+ s.session_id
+ for s in api.list_mcp_sessions(self.team, limit=50, offset=0, order_by=value)
+ if s.session_id in target
+ ]
+
+ # Default sort: most-recent session_end first
+ assert order("") == [new_id, big_id, old_id]
+ # Ascending session_end
+ assert order("session_end") == [old_id, big_id, new_id]
+ # By tool_call_count desc
+ assert order("-tool_call_count") == [big_id, old_id, new_id]
+ # Unknown / unsafe column falls back to default
+ assert order("password") == [new_id, big_id, old_id]
+ assert order("-DROP TABLE") == [new_id, big_id, old_id]
diff --git a/products/mcp_analytics/backend/tests/test_dashboard_templates.py b/products/mcp_analytics/backend/tests/test_dashboard_templates.py
new file mode 100644
index 000000000000..b9a18a967593
--- /dev/null
+++ b/products/mcp_analytics/backend/tests/test_dashboard_templates.py
@@ -0,0 +1,83 @@
+from products.mcp_analytics.backend.dashboard_templates import get_mcp_analytics_default_template
+
+
+def test_mcp_analytics_default_template_includes_oauth_client_pie_chart() -> None:
+ template = get_mcp_analytics_default_template()
+
+ assert template.tags == ["mcp-analytics"]
+ assert template.tiles is not None
+ assert len(template.tiles) == 3
+
+ tile = template.tiles[0]
+ source = tile["query"]["source"]
+
+ assert tile["name"] == "MCP clients"
+ assert source["series"][0]["event"] == "mcp_initialize"
+ assert source["breakdownFilter"] == {
+ "breakdown_type": "event",
+ "breakdown": "$mcp_client_name",
+ }
+ assert source["trendsFilter"]["display"] == "ActionsPie"
+
+
+def test_mcp_analytics_default_template_includes_users_and_sessions() -> None:
+ template = get_mcp_analytics_default_template()
+
+ assert template.tiles is not None
+ tile = template.tiles[1]
+ source = tile["query"]["source"]
+
+ assert tile["name"] == "MCP users and sessions"
+ assert tile["query"]["full"] is True
+ assert source["kind"] == "TrendsQuery"
+ assert source["version"] == 2
+ assert source["tags"] == {"productKey": "product_analytics"}
+ assert source["series"] == [
+ {
+ "kind": "EventsNode",
+ "event": "mcp_initialize",
+ "name": "mcp_initialize",
+ "custom_name": "users",
+ "math": "hogql",
+ "math_hogql": "count(DISTINCT person_id)",
+ },
+ {
+ "kind": "EventsNode",
+ "event": "mcp_initialize",
+ "name": "mcp_initialize",
+ "custom_name": "sessions",
+ "math": "hogql",
+ "math_hogql": "count(DISTINCT properties.$session_id)",
+ },
+ ]
+
+
+def test_mcp_analytics_default_template_includes_tool_calls_by_error_status() -> None:
+ template = get_mcp_analytics_default_template()
+
+ assert template.tiles is not None
+ tile = template.tiles[2]
+ source = tile["query"]["source"]
+
+ assert tile["name"] == "MCP tool calls by error status"
+ assert tile["query"]["full"] is True
+ assert source["kind"] == "TrendsQuery"
+ assert source["version"] == 2
+ assert source["tags"] == {"productKey": "product_analytics"}
+ assert source["series"] == [
+ {
+ "kind": "EventsNode",
+ "event": "mcp_tool_call",
+ "name": "mcp_tool_call",
+ "math": "total",
+ }
+ ]
+ assert source["trendsFilter"] == {"display": "ActionsUnstackedBar"}
+ assert source["breakdownFilter"] == {
+ "breakdowns": [
+ {
+ "property": "$mcp_is_error",
+ "type": "event",
+ }
+ ],
+ }
diff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.py
new file mode 100644
index 000000000000..60d494057f85
--- /dev/null
+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py
@@ -0,0 +1,293 @@
+"""Tests for the pure functions in intent_clustering.
+
+These tests are intentionally light on Django/ClickHouse and heavy on the
+algorithm. They cover the math (clustering, entropy, medoid) and the snapshot
+shape we promise the frontend.
+"""
+
+import math
+import uuid
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+
+import numpy as np
+
+from products.mcp_analytics.backend.intent_clustering import (
+ DEFAULT_DISTANCE_THRESHOLD,
+ IntentRecord,
+ _medoid_index,
+ _routing_entropy,
+ build_snapshot,
+ cluster_embeddings,
+ fetch_intent_corpus,
+)
+from products.mcp_analytics.backend.models import MCPSession
+from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
+
+# Helpers
+
+
+def _unit(vec: list[float]) -> np.ndarray:
+ arr = np.asarray(vec, dtype=np.float32)
+ return arr / np.linalg.norm(arr)
+
+
+# cluster_embeddings ------------------------------------------------------
+
+
+class TestClusterEmbeddings:
+ def test_returns_empty_array_on_empty_input(self) -> None:
+ labels = cluster_embeddings(np.zeros((0, 4), dtype=np.float32))
+ assert labels.shape == (0,)
+
+ def test_single_intent_yields_one_label(self) -> None:
+ labels = cluster_embeddings(np.array([[1.0, 0.0, 0.0]], dtype=np.float32))
+ assert labels.tolist() == [0]
+
+ def test_two_tight_groups_yield_two_clusters(self) -> None:
+ # Two well-separated groups in cosine space.
+ embeddings = np.array(
+ [
+ _unit([1.0, 0.0, 0.0]),
+ _unit([0.99, 0.05, 0.0]),
+ _unit([0.0, 1.0, 0.0]),
+ _unit([0.05, 0.99, 0.0]),
+ ]
+ )
+ labels = cluster_embeddings(embeddings, distance_threshold=0.2)
+ assert labels[0] == labels[1]
+ assert labels[2] == labels[3]
+ assert labels[0] != labels[2]
+
+ def test_threshold_zero_makes_every_point_its_own_cluster(self) -> None:
+ embeddings = np.array(
+ [
+ _unit([1.0, 0.0, 0.0]),
+ _unit([0.0, 1.0, 0.0]),
+ _unit([0.0, 0.0, 1.0]),
+ ]
+ )
+ labels = cluster_embeddings(embeddings, distance_threshold=0.0)
+ assert len(set(labels.tolist())) == 3
+
+ def test_high_threshold_collapses_to_one_cluster(self) -> None:
+ embeddings = np.array(
+ [
+ _unit([1.0, 0.0, 0.0]),
+ _unit([0.0, 1.0, 0.0]),
+ _unit([0.0, 0.0, 1.0]),
+ ]
+ )
+ labels = cluster_embeddings(embeddings, distance_threshold=2.0)
+ assert len(set(labels.tolist())) == 1
+
+
+# _routing_entropy --------------------------------------------------------
+
+
+class TestRoutingEntropy:
+ def test_single_tool_is_zero(self) -> None:
+ assert _routing_entropy({"query_run": 10}) == 0.0
+
+ def test_empty_is_zero(self) -> None:
+ assert _routing_entropy({}) == 0.0
+
+ def test_perfectly_uniform_is_one(self) -> None:
+ assert _routing_entropy({"a": 5, "b": 5}) == pytest.approx(1.0)
+ assert _routing_entropy({"a": 1, "b": 1, "c": 1}) == pytest.approx(1.0)
+
+ def test_skewed_distribution_is_between(self) -> None:
+ # 90/10 split should be much less than uniform but well above zero.
+ value = _routing_entropy({"a": 90, "b": 10})
+ assert 0.0 < value < 1.0
+ # Sanity-check against Shannon formula directly.
+ p = [0.9, 0.1]
+ expected = -sum(x * math.log(x) for x in p) / math.log(2)
+ assert value == pytest.approx(expected)
+
+
+# _medoid_index -----------------------------------------------------------
+
+
+class TestMedoidIndex:
+ def test_single_member_returns_itself(self) -> None:
+ embeddings = np.array([_unit([1.0, 0.0])])
+ assert _medoid_index(embeddings, [0]) == 0
+
+ def test_picks_centermost_member(self) -> None:
+ # The middle vector is the centroid of the three; should be the medoid.
+ embeddings = np.array(
+ [
+ _unit([1.0, 0.0]),
+ _unit([0.5, 0.5]), # closer to centroid (sum direction)
+ _unit([0.0, 1.0]),
+ ]
+ )
+ assert _medoid_index(embeddings, [0, 1, 2]) == 1
+
+
+# build_snapshot ----------------------------------------------------------
+
+
+class TestBuildSnapshot:
+ def test_empty_corpus_returns_empty_snapshot(self) -> None:
+ snapshot = build_snapshot([], np.array([], dtype=np.int64), np.zeros((0, 4), dtype=np.float32))
+ assert snapshot["clusters"] == []
+ assert snapshot["computed_with"]["n_clusters"] == 0
+
+ def test_aggregates_tool_counts_across_member_intents(self) -> None:
+ records = [
+ IntentRecord(
+ intent_text="check feature flag rollout",
+ frequency=10,
+ tool_counts={"feature_flag_get": 8, "query_run": 2},
+ error_counts={"feature_flag_get": 1},
+ ),
+ IntentRecord(
+ intent_text="look up feature flag status",
+ frequency=4,
+ tool_counts={"feature_flag_get": 4},
+ error_counts={},
+ ),
+ ]
+ labels = np.array([0, 0], dtype=np.int64)
+ embeddings = np.array([_unit([1.0, 0.1]), _unit([1.0, 0.0])], dtype=np.float32)
+
+ snapshot = build_snapshot(records, labels, embeddings)
+
+ assert len(snapshot["clusters"]) == 1
+ cluster = snapshot["clusters"][0]
+ assert cluster["intent_count"] == 2
+ assert cluster["call_count"] == 14
+ assert cluster["error_count"] == 1
+ # tool_distribution is sorted by count desc
+ assert cluster["tool_distribution"][0]["tool"] == "feature_flag_get"
+ assert cluster["tool_distribution"][0]["count"] == 12
+ assert cluster["tool_distribution"][1]["tool"] == "query_run"
+ assert cluster["tool_distribution"][1]["count"] == 2
+ # Error rate is per-tool
+ assert cluster["tool_distribution"][0]["error_rate_pct"] == pytest.approx(8.3, abs=0.1)
+ # Routing entropy is between 0 and 1; this is skewed so should be low.
+ assert 0.0 < cluster["routing_entropy"] < 0.7
+
+ def test_sorts_clusters_by_call_count(self) -> None:
+ records = [
+ IntentRecord(intent_text="rare intent", frequency=1, tool_counts={"tool_a": 1}),
+ IntentRecord(intent_text="popular intent", frequency=100, tool_counts={"tool_b": 100}),
+ ]
+ labels = np.array([0, 1], dtype=np.int64)
+ embeddings = np.array([_unit([1.0, 0.0]), _unit([0.0, 1.0])], dtype=np.float32)
+
+ snapshot = build_snapshot(records, labels, embeddings)
+
+ assert snapshot["clusters"][0]["label"] == "popular intent"
+ assert snapshot["clusters"][1]["label"] == "rare intent"
+
+ def test_sample_intents_capped_and_sorted_by_frequency(self) -> None:
+ records = [
+ IntentRecord(intent_text=f"intent_{i}", frequency=10 - i, tool_counts={"tool_a": 10 - i}) for i in range(5)
+ ]
+ labels = np.array([0] * 5, dtype=np.int64)
+ embeddings = np.array([_unit([1.0, 0.0])] * 5, dtype=np.float32)
+
+ snapshot = build_snapshot(records, labels, embeddings)
+
+ cluster = snapshot["clusters"][0]
+ assert cluster["sample_intents"] == ["intent_0", "intent_1", "intent_2"]
+
+ def test_medoid_is_used_as_cluster_label(self) -> None:
+ records = [
+ IntentRecord(intent_text="edge_a", frequency=1, tool_counts={"tool_a": 1}),
+ IntentRecord(intent_text="center", frequency=1, tool_counts={"tool_a": 1}),
+ IntentRecord(intent_text="edge_b", frequency=1, tool_counts={"tool_a": 1}),
+ ]
+ labels = np.array([0, 0, 0], dtype=np.int64)
+ embeddings = np.array(
+ [
+ _unit([1.0, 0.0]),
+ _unit([0.5, 0.5]),
+ _unit([0.0, 1.0]),
+ ],
+ dtype=np.float32,
+ )
+
+ snapshot = build_snapshot(records, labels, embeddings, distance_threshold=DEFAULT_DISTANCE_THRESHOLD)
+
+ assert snapshot["clusters"][0]["label"] == "center"
+
+ def test_misaligned_inputs_raise(self) -> None:
+ records = [IntentRecord(intent_text="a", frequency=1, tool_counts={"tool_a": 1})]
+ with pytest.raises(AssertionError):
+ build_snapshot(records, np.array([0, 0], dtype=np.int64), np.array([_unit([1.0, 0.0])]))
+
+
+# fetch_intent_corpus -----------------------------------------------------
+
+
+class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, BaseTest):
+ """End-to-end: posthog_mcp_session in Postgres + mcp_tool_call in ClickHouse."""
+
+ def _seed_session(self, session_id: str, intent: str) -> None:
+ start = datetime.now(tz=UTC) - timedelta(hours=1)
+ MCPSession.objects.create(
+ team=self.team,
+ session_id=session_id,
+ session_start=start,
+ session_end=start + timedelta(minutes=5),
+ duration_seconds=300,
+ intent=intent,
+ )
+
+ def _seed_tool_call(self, session_id: str, tool_name: str, is_error: bool = False) -> None:
+ _create_event(
+ event_uuid=uuid.uuid4(),
+ event="mcp_tool_call",
+ team=self.team,
+ distinct_id="seed",
+ timestamp=datetime.now(tz=UTC) - timedelta(hours=1),
+ properties={
+ "$session_id": session_id,
+ "$mcp_tool_name": tool_name,
+ "$mcp_is_error": is_error,
+ },
+ )
+
+ 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
diff --git a/products/mcp_analytics/backend/tests/test_logic.py b/products/mcp_analytics/backend/tests/test_logic.py
index c7943feb1624..8fd83fd7fa19 100644
--- a/products/mcp_analytics/backend/tests/test_logic.py
+++ b/products/mcp_analytics/backend/tests/test_logic.py
@@ -1,11 +1,14 @@
from posthog.test.base import APIBaseTest
+from django.utils import timezone
+
from products.mcp_analytics.backend import logic
from products.mcp_analytics.backend.facade import contracts, enums
-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot
+from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
-class TestMCPAnalyticsLogic(APIBaseTest):
+class TestMCPAnalyticsLogic(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):
def test_create_feedback_submission(self) -> None:
submission = logic.create_feedback_submission(
self.team,
@@ -59,3 +62,95 @@ class TestMCPAnalyticsLogic(APIBaseTest):
submissions = logic.list_submissions(self.team, enums.SubmissionKind.FEEDBACK)
assert [submission.kind for submission in submissions] == [MCPAnalyticsSubmission.Kind.FEEDBACK]
+
+
+class TestGetIntentClusterSnapshot(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):
+ def test_returns_empty_idle_snapshot_when_no_row_exists(self) -> None:
+ snapshot = logic.get_intent_cluster_snapshot(self.team)
+
+ assert snapshot.status == MCPIntentClusterSnapshot.Status.IDLE
+ assert snapshot.clusters == []
+ assert snapshot.last_computed_at is None
+ assert snapshot.last_computed_by_email == ""
+ assert snapshot.computed_with is None
+
+ def test_maps_stored_snapshot_to_dto(self) -> None:
+ now = timezone.now()
+ MCPIntentClusterSnapshot.objects.create(
+ team=self.team,
+ status=MCPIntentClusterSnapshot.Status.IDLE,
+ last_computed_at=now,
+ last_computed_by=self.user,
+ clusters={
+ "clusters": [
+ {
+ "id": 0,
+ "label": "check feature flag rollout",
+ "intent_count": 2,
+ "call_count": 14,
+ "error_count": 1,
+ "error_rate_pct": 7.1,
+ "routing_entropy": 0.1,
+ "tool_distribution": [
+ {"tool": "feature_flag_get", "count": 12, "pct": 85.7, "errors": 1, "error_rate_pct": 8.3},
+ {"tool": "query_run", "count": 2, "pct": 14.3, "errors": 0, "error_rate_pct": 0.0},
+ ],
+ "sample_intents": ["check feature flag rollout", "look up feature flag status"],
+ }
+ ],
+ "computed_with": {
+ "distance_threshold": 0.2,
+ "embedding_model": "text-embedding-3-small-1536",
+ "n_intents": 2,
+ "n_clusters": 1,
+ },
+ },
+ )
+
+ snapshot = logic.get_intent_cluster_snapshot(self.team)
+
+ assert snapshot.status == MCPIntentClusterSnapshot.Status.IDLE
+ assert snapshot.last_computed_by_email == self.user.email
+ assert len(snapshot.clusters) == 1
+ cluster = snapshot.clusters[0]
+ assert cluster.label == "check feature flag rollout"
+ assert cluster.intent_count == 2
+ assert cluster.call_count == 14
+ assert len(cluster.tool_distribution) == 2
+ assert cluster.tool_distribution[0].tool == "feature_flag_get"
+ assert cluster.tool_distribution[0].error_rate_pct == 8.3
+ assert snapshot.computed_with is not None
+ assert snapshot.computed_with.n_clusters == 1
+
+ def test_stale_computing_snapshot_is_auto_flipped_to_error(self) -> None:
+ from datetime import timedelta
+
+ from products.mcp_analytics.backend.logic import STALE_COMPUTING_THRESHOLD
+
+ row = MCPIntentClusterSnapshot.objects.create(
+ team=self.team,
+ status=MCPIntentClusterSnapshot.Status.COMPUTING,
+ )
+ # Backdate updated_at past the threshold so the read should auto-recover.
+ stale = timezone.now() - STALE_COMPUTING_THRESHOLD - timedelta(seconds=30)
+ MCPIntentClusterSnapshot.objects.filter(pk=row.pk).update(updated_at=stale)
+
+ snapshot = logic.get_intent_cluster_snapshot(self.team)
+
+ assert snapshot.status == MCPIntentClusterSnapshot.Status.ERROR
+ assert "did not complete" in snapshot.error_message
+
+ row.refresh_from_db()
+ assert row.status == MCPIntentClusterSnapshot.Status.ERROR
+
+ def test_fresh_computing_snapshot_is_left_alone(self) -> None:
+ MCPIntentClusterSnapshot.objects.create(
+ team=self.team,
+ status=MCPIntentClusterSnapshot.Status.COMPUTING,
+ )
+
+ snapshot = logic.get_intent_cluster_snapshot(self.team)
+
+ # Recently updated COMPUTING rows pass through unmodified.
+ assert snapshot.status == MCPIntentClusterSnapshot.Status.COMPUTING
+ assert snapshot.error_message == ""
diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.py
index 6b1ff27c5e80..594cbc657fc1 100644
--- a/products/mcp_analytics/backend/tests/test_presentation.py
+++ b/products/mcp_analytics/backend/tests/test_presentation.py
@@ -1,12 +1,14 @@
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot
+from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
-class TestMCPAnalyticsPresentation(APIBaseTest):
+class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):
@parameterized.expand(
[
("feedback_create", "post", "feedback/", {"goal": "understand usage", "feedback": "Need clearer results"}),
@@ -130,6 +132,70 @@ class TestMCPAnalyticsPresentation(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == field
+ def test_intent_clusters_returns_empty_idle_when_no_snapshot(self) -> None:
+ 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()
+ assert data["status"] == "idle"
+ assert data["clusters"] == []
+ assert data["last_computed_at"] is None
+ assert data["computed_with"] is None
+
+ def test_intent_clusters_returns_stored_snapshot(self) -> None:
+ MCPIntentClusterSnapshot.objects.create(
+ team=self.team,
+ status=MCPIntentClusterSnapshot.Status.IDLE,
+ clusters={
+ "clusters": [
+ {
+ "id": 0,
+ "label": "check feature flag rollout",
+ "intent_count": 2,
+ "call_count": 14,
+ "error_count": 1,
+ "error_rate_pct": 7.1,
+ "routing_entropy": 0.1,
+ "tool_distribution": [
+ {"tool": "feature_flag_get", "count": 12, "pct": 85.7, "errors": 1, "error_rate_pct": 8.3},
+ ],
+ "sample_intents": ["check feature flag rollout"],
+ }
+ ],
+ "computed_with": {
+ "distance_threshold": 0.2,
+ "embedding_model": "text-embedding-3-small-1536",
+ "n_intents": 2,
+ "n_clusters": 1,
+ },
+ },
+ )
+
+ 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()
+ assert data["status"] == "idle"
+ assert len(data["clusters"]) == 1
+ assert data["clusters"][0]["label"] == "check feature flag rollout"
+ assert data["computed_with"]["n_clusters"] == 1
+
+ def test_intent_clusters_recompute_enqueues_task_and_returns_computing(self) -> None:
+ # Mock only the Celery dispatch so the synchronous COMPUTING write
+ # still runs. The 202 body should reflect the new state, not the
+ # stale pre-trigger state.
+ with patch("products.mcp_analytics.backend.tasks.tasks.compute_intent_clusters.delay") as mock_delay:
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/mcp_analytics/intent_clusters/recompute/", {}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ assert response.json()["status"] == "computing"
+ mock_delay.assert_called_once_with(self.team.id, self.user.id)
+ snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)
+ assert snapshot.status == MCPIntentClusterSnapshot.Status.COMPUTING
+ assert snapshot.last_computed_by_id == self.user.id
+
def test_feedback_list_is_team_scoped(self) -> None:
MCPAnalyticsSubmission.objects.create(
team=self.team,
diff --git a/products/mcp_analytics/backend/tests/test_tasks.py b/products/mcp_analytics/backend/tests/test_tasks.py
index 556c4792b07a..959aac86acd0 100644
--- a/products/mcp_analytics/backend/tests/test_tasks.py
+++ b/products/mcp_analytics/backend/tests/test_tasks.py
@@ -1,5 +1,81 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+import numpy as np
+
+from products.mcp_analytics.backend import intent_clustering
+from products.mcp_analytics.backend.models import MCPIntentClusterSnapshot
from products.mcp_analytics.backend.tasks import tasks
+from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
+
+
+class TestComputeIntentClusters(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):
+ def _stub_corpus(self) -> list[intent_clustering.IntentRecord]:
+ return [
+ intent_clustering.IntentRecord(
+ intent_text="check feature flag rollout",
+ frequency=10,
+ tool_counts={"feature_flag_get": 10},
+ error_counts={},
+ ),
+ intent_clustering.IntentRecord(
+ intent_text="look up feature flag status",
+ frequency=4,
+ tool_counts={"feature_flag_get": 4},
+ error_counts={},
+ ),
+ ]
+
+ def _stub_embeddings(self) -> tuple[np.ndarray, list[int]]:
+ # Two near-identical unit vectors so they cluster together.
+ vectors = np.array(
+ [
+ [1.0, 0.0, 0.0],
+ [0.99, 0.05, 0.0],
+ ],
+ dtype=np.float32,
+ )
+ vectors = vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
+ return vectors, [0, 1]
+
+ def test_writes_snapshot_on_success(self) -> None:
+ with (
+ patch.object(intent_clustering, "fetch_intent_corpus", return_value=(self._stub_corpus(), {})),
+ patch.object(intent_clustering, "embed_intents_async") as mock_embed,
+ patch.object(intent_clustering, "fetch_session_journeys", return_value={}),
+ ):
+ # asyncio.run unwraps the coroutine; emulate the awaited result.
+ async def fake_embed(team, texts): # noqa: ARG001
+ return self._stub_embeddings()
+
+ mock_embed.side_effect = fake_embed
+ tasks.compute_intent_clusters.apply(args=[self.team.id, self.user.id]).get()
+
+ snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)
+ assert snapshot.status == MCPIntentClusterSnapshot.Status.IDLE
+ assert snapshot.error_message == ""
+ assert snapshot.last_computed_at is not None
+ assert snapshot.last_computed_by_id == self.user.id
+ assert len(snapshot.clusters["clusters"]) == 1
+ assert snapshot.clusters["clusters"][0]["call_count"] == 14
+
+ def test_empty_corpus_writes_empty_snapshot(self) -> None:
+ with patch.object(intent_clustering, "fetch_intent_corpus", return_value=([], {})):
+ tasks.compute_intent_clusters.apply(args=[self.team.id, self.user.id]).get()
+
+ snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)
+ assert snapshot.status == MCPIntentClusterSnapshot.Status.IDLE
+ assert snapshot.clusters["clusters"] == []
+ assert snapshot.clusters["computed_with"]["n_intents"] == 0
+ def test_records_error_on_failure(self) -> None:
+ with patch.object(intent_clustering, "fetch_intent_corpus", side_effect=RuntimeError("boom")):
+ try:
+ tasks.compute_intent_clusters.apply(args=[self.team.id, self.user.id]).get()
+ except Exception:
+ # We expect the task to re-raise after marking error and exhausting retries.
+ pass
-def test_tasks_module_imports() -> None:
- assert tasks is not None
+ snapshot = MCPIntentClusterSnapshot.objects.get(team=self.team)
+ assert snapshot.status == MCPIntentClusterSnapshot.Status.ERROR
+ assert "boom" in snapshot.error_message
diff --git a/products/mcp_analytics/backend/tests/test_tool_quality_sql.py b/products/mcp_analytics/backend/tests/test_tool_quality_sql.py
new file mode 100644
index 000000000000..3405e0e05180
--- /dev/null
+++ b/products/mcp_analytics/backend/tests/test_tool_quality_sql.py
@@ -0,0 +1,43 @@
+from pathlib import Path
+
+TEMPLATES_DIR = Path(__file__).resolve().parents[1] / "templates"
+TOOL_QUALITY_SQL_PATH = TEMPLATES_DIR / "tool_quality.sql"
+
+
+def test_tool_quality_sql_exists() -> None:
+ assert TOOL_QUALITY_SQL_PATH.is_file()
+
+
+def test_tool_quality_sql_contains_required_columns() -> None:
+ sql = TOOL_QUALITY_SQL_PATH.read_text()
+
+ # Aliased output columns the frontend table relies on.
+ for column in (
+ "tool",
+ "total_calls",
+ "error_rate_pct",
+ "p50_duration_ms",
+ "p95_duration_ms",
+ "users",
+ "sessions",
+ "first_seen",
+ "last_seen",
+ ):
+ assert f" {column}" in sql, f"missing column alias '{column}' in tool_quality.sql"
+
+
+def test_tool_quality_sql_supports_filters_and_sort_placeholders() -> None:
+ sql = TOOL_QUALITY_SQL_PATH.read_text()
+
+ # The HogQL engine resolves {filters} from the wrapping HogQLQuery node.
+ assert "{filters}" in sql
+ # The frontend logic does .replace() on these markers before sending the query.
+ assert "__ORDER_BY__" in sql
+ assert "__ORDER_DIRECTION__" in sql
+
+
+def test_tool_quality_sql_targets_mcp_tool_call_event() -> None:
+ sql = TOOL_QUALITY_SQL_PATH.read_text()
+
+ assert "event = 'mcp_tool_call'" in sql
+ assert "$mcp_tool_name" in sql
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.tsx
new file mode 100644
index 000000000000..b249a86aef3d
--- /dev/null
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.tsx
@@ -0,0 +1,5 @@
+import { MCPAnalyticsDashboardOverview } from './MCPAnalyticsDashboardOverview'
+
+export function MCPAnalyticsDashboard(): JSX.Element {
+ return <MCPAnalyticsDashboardOverview />
+}
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx
new file mode 100644
index 000000000000..f0250577d29d
--- /dev/null
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx
@@ -0,0 +1,558 @@
+import { useValues } from 'kea'
+
+import { IconBolt } from '@posthog/icons'
+import { LemonSkeleton, Link } from '@posthog/lemon-ui'
+
+import { humanFriendlyDuration, humanFriendlyNumber } from 'lib/utils'
+import { urls } from 'scenes/urls'
+
+import claudeLogo from './harness-logos/claude.svg'
+import cursorLogo from './harness-logos/cursor.svg'
+import openaiLogo from './harness-logos/openai.svg'
+import vscodeLogo from './harness-logos/vscode.svg'
+import { HarnessRow, KPIMetric, NotableSession, ToolRow, mcpDashboardOverviewLogic } from './mcpDashboardOverviewLogic'
+
+const HARNESS_LOGOS: Record<string, string> = {
+ 'Claude Code': claudeLogo,
+ 'Claude.ai': claudeLogo,
+ 'OpenAI Codex': openaiLogo,
+ Cursor: cursorLogo,
+ 'VS Code': vscodeLogo,
+}
+
+export function HarnessPill({ category, title }: { category: string; title?: string }): JSX.Element {
+ const logo = HARNESS_LOGOS[category]
+ return (
+ <span
+ className="inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary bg-surface-primary px-2 py-0.5 text-xs"
+ title={title}
+ >
+ {logo ? (
+ <img src={logo} alt="" className="h-3.5 w-3.5 shrink-0 object-contain" />
+ ) : (
+ <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-secondary" aria-hidden />
+ )}
+ <span className="truncate">{category}</span>
+ </span>
+ )
+}
+
+type TileColor = 'blue' | 'red' | 'green'
+
+interface TileSpec {
+ label: string
+ metric: KPIMetric
+ href: string
+ format: (n: number) => string
+ color: TileColor
+ loading: boolean
+}
+
+const COLOR_STROKE: Record<TileColor, string> = {
+ blue: '#185FA5',
+ red: '#A32D2D',
+ green: '#0F6E56',
+}
+
+function formatNumber(n: number): string {
+ if (!isFinite(n)) {
+ return '—'
+ }
+ return humanFriendlyNumber(Math.round(n))
+}
+
+function formatPercent(n: number): string {
+ if (!isFinite(n)) {
+ return '—'
+ }
+ return `${n.toFixed(n >= 10 ? 0 : 1)}%`
+}
+
+function formatMs(n: number): string {
+ if (!isFinite(n) || n === 0) {
+ return '—'
+ }
+ if (n < 1000) {
+ return `${Math.round(n)}ms`
+ }
+ return humanFriendlyDuration(n / 1000, { secondsPrecision: 1 })
+}
+
+function Sparkline({ values, stroke }: { values: number[]; stroke: string }): JSX.Element {
+ const width = 60
+ const height = 18
+ if (values.length === 0) {
+ return <svg width={width} height={height} aria-hidden />
+ }
+ const max = Math.max(...values, 1)
+ const min = Math.min(...values, 0)
+ const range = max - min || 1
+ const stepX = values.length > 1 ? width / (values.length - 1) : width
+ const points = values
+ .map((v, i) => {
+ const x = i * stepX
+ const y = height - ((v - min) / range) * height
+ return `${x.toFixed(1)},${y.toFixed(1)}`
+ })
+ .join(' ')
+ return (
+ <svg width={width} height={height} aria-hidden>
+ <polyline fill="none" stroke={stroke} strokeWidth="1.2" points={points} />
+ </svg>
+ )
+}
+
+function DeltaPill({ metric }: { metric: KPIMetric }): JSX.Element {
+ if (metric.deltaPct === null) {
+ return <span className="text-[11px] font-medium text-secondary">—</span>
+ }
+ const rounded = Math.round(metric.deltaPct)
+ if (rounded === 0) {
+ return <span className="text-[11px] font-medium text-secondary">0%</span>
+ }
+ const isUp = rounded > 0
+ const isGood = isUp ? metric.goodDirection === 'up' : metric.goodDirection === 'down'
+ const colorClass = isGood ? 'text-success' : 'text-danger'
+ const arrow = isUp ? '↑' : '↓'
+ return (
+ <span className={`text-[11px] font-medium ${colorClass}`}>
+ {arrow} {Math.abs(rounded)}%
+ </span>
+ )
+}
+
+function KPITile({ tile }: { tile: TileSpec }): JSX.Element {
+ return (
+ <Link
+ to={tile.href}
+ className="flex flex-col gap-1 rounded-md bg-surface-secondary px-3.5 py-3 transition-colors hover:bg-surface-tertiary"
+ >
+ <div className="text-[11px] text-secondary">{tile.label}</div>
+ {tile.loading ? (
+ <LemonSkeleton className="h-5 w-16" />
+ ) : (
+ <div className="text-xl font-medium leading-tight">{tile.format(tile.metric.value)}</div>
+ )}
+ <div className="mt-1 flex items-center justify-between">
+ <Sparkline values={tile.metric.sparkline} stroke={COLOR_STROKE[tile.color]} />
+ <DeltaPill metric={tile.metric} />
+ </div>
+ </Link>
+ )
+}
+
+export function MCPAnalyticsDashboardOverview(): JSX.Element {
+ const {
+ kpis,
+ kpisLoading,
+ intentClusterCount,
+ topToolRows,
+ toolRowsLoading,
+ toolRowsTotal,
+ notableSessions,
+ sessionRowsLoading,
+ harnessRows,
+ harnessRawRowsLoading,
+ } = useValues(mcpDashboardOverviewLogic)
+
+ const tiles: TileSpec[] = [
+ {
+ label: 'Sessions',
+ metric: kpis.sessions,
+ href: urls.mcpAnalyticsSessions(),
+ format: formatNumber,
+ color: 'blue',
+ loading: kpisLoading,
+ },
+ {
+ label: 'Tool calls',
+ metric: kpis.toolCalls,
+ href: urls.mcpAnalyticsToolQuality(),
+ format: formatNumber,
+ color: 'blue',
+ loading: kpisLoading,
+ },
+ {
+ label: 'Error rate',
+ metric: kpis.errorRatePct,
+ href: urls.mcpAnalyticsSessions(),
+ format: formatPercent,
+ color: 'red',
+ loading: kpisLoading,
+ },
+ {
+ label: 'p95 latency',
+ metric: kpis.p95LatencyMs,
+ href: urls.mcpAnalyticsToolQuality(),
+ format: formatMs,
+ color: 'blue',
+ loading: kpisLoading,
+ },
+ {
+ label: 'Intent clusters',
+ metric: intentClusterCount,
+ href: urls.mcpAnalyticsIntentClustering(),
+ format: formatNumber,
+ color: 'green',
+ loading: false,
+ },
+ ]
+
+ return (
+ <div className="flex flex-col gap-[22px]">
+ <BrandingStrip />
+ <Block kicker="Health" question="Is the MCP healthy right now?">
+ <div className="grid grid-cols-2 gap-3 md:grid-cols-5">
+ {tiles.map((tile) => (
+ <KPITile key={tile.label} tile={tile} />
+ ))}
+ </div>
+ </Block>
+ <Block kicker="Tool quality" question="Which tools are the weak links?">
+ <ToolReliabilityMatrix rows={topToolRows} loading={toolRowsLoading} totalTools={toolRowsTotal} />
+ </Block>
+ <Block kicker="Surface" question="Which harnesses are calling the MCP?">
+ <HarnessBreakdown rows={harnessRows} loading={harnessRawRowsLoading} />
+ </Block>
+ <Block kicker="Triage" question="Which sessions should I look at?">
+ <NotableSessionsTable sessions={notableSessions} loading={sessionRowsLoading} />
+ </Block>
+ </div>
+ )
+}
+
+function BrandingStrip(): JSX.Element {
+ return (
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className="flex h-[22px] w-[22px] items-center justify-center rounded bg-warning text-white">
+ <IconBolt className="h-3 w-3" />
+ </span>
+ <span className="text-[13px] font-medium">PostHog for Agents</span>
+ <span
+ className="rounded px-1.5 py-0.5 text-[10px] font-medium"
+ style={{ background: '#E6F1FB', color: '#0C447C' }}
+ >
+ Preview
+ </span>
+ </div>
+ <span className="text-[11px] text-tertiary">Last 7 days</span>
+ </div>
+ )
+}
+
+function Block({
+ kicker,
+ question,
+ children,
+}: {
+ kicker: string
+ question: string
+ children: React.ReactNode
+}): JSX.Element {
+ return (
+ <section className="flex flex-col">
+ <div className="text-[11px] text-secondary mb-1">{kicker}</div>
+ <h1 className="text-sm font-medium mb-3">{question}</h1>
+ {children}
+ </section>
+ )
+}
+
+function Card({ children }: { children: React.ReactNode }): JSX.Element {
+ return <div className="rounded-lg border border-primary bg-surface-primary px-3.5 py-3">{children}</div>
+}
+
+type ErrorBucket = 'green' | 'amber' | 'red'
+
+function errorBucket(pct: number): ErrorBucket {
+ if (pct < 1) {
+ return 'green'
+ }
+ if (pct <= 5) {
+ return 'amber'
+ }
+ return 'red'
+}
+
+const ERROR_PILL_CLASS: Record<ErrorBucket, string> = {
+ green: 'text-[#27500A] bg-[#EAF3DE]',
+ amber: 'text-[#633806] bg-[#FAEEDA]',
+ red: 'text-[#791F1F] bg-[#FCEBEB]',
+}
+
+function ErrorRatePill({ pct }: { pct: number }): JSX.Element {
+ const bucket = errorBucket(pct)
+ return (
+ <span
+ className={`inline-flex h-[14px] items-center justify-center rounded-[3px] px-1.5 text-[10px] font-medium ${ERROR_PILL_CLASS[bucket]}`}
+ >
+ {pct.toFixed(pct >= 10 ? 0 : 1)}%
+ </span>
+ )
+}
+
+function ToolRowItem({ row, maxVolume, isLast }: { row: ToolRow; maxVolume: number; isLast: boolean }): JSX.Element {
+ const callsPct = maxVolume ? (row.total_calls / maxVolume) * 100 : 0
+ const errorsPct = maxVolume ? (row.errors / maxVolume) * 100 : 0
+ const successPct = Math.max(callsPct - errorsPct, 0)
+ const nameClass = row.error_rate_pct > 5 ? 'text-[#791F1F]' : 'text-primary'
+ return (
+ <div
+ className="grid items-center gap-2.5 py-1.5"
+ style={{
+ gridTemplateColumns: '140px 1fr 60px 56px',
+ borderBottom: isLast ? 'none' : '0.5px solid var(--color-border-tertiary)',
+ }}
+ >
+ <Link
+ to={urls.mcpAnalyticsTool(row.tool)}
+ className={`truncate font-mono text-xs ${nameClass}`}
+ title={row.tool}
+ >
+ {row.tool}
+ </Link>
+ <div
+ className="relative flex h-[14px] overflow-hidden rounded-[3px] bg-surface-secondary"
+ title={`${row.total_calls} calls · ${row.errors} errors`}
+ >
+ <div className="h-full bg-[#B5D4F4]" style={{ width: `${successPct}%` }} />
+ <div className="h-full bg-[#F09595]" style={{ width: `${errorsPct}%` }} />
+ </div>
+ <ErrorRatePill pct={row.error_rate_pct} />
+ <span className="text-right font-mono text-xs text-primary">
+ {row.p95_duration_ms ? `${Math.round(row.p95_duration_ms)}ms` : '—'}
+ </span>
+ </div>
+ )
+}
+
+function ToolReliabilityMatrix({
+ rows,
+ loading,
+ totalTools,
+}: {
+ rows: ToolRow[]
+ loading: boolean
+ totalTools: number
+}): JSX.Element {
+ const maxVolume = rows.length ? Math.max(...rows.map((r) => r.total_calls)) : 0
+
+ return (
+ <Card>
+ <div
+ className="grid items-center gap-2.5 pb-1.5 text-[11px] text-secondary"
+ style={{
+ gridTemplateColumns: '140px 1fr 60px 56px',
+ borderBottom: '0.5px solid var(--color-border-secondary)',
+ }}
+ >
+ <span>Tool</span>
+ <span>
+ <span className="text-[#185FA5]">Calls</span>
+ <span className="mx-1">·</span>
+ <span className="text-[#A32D2D]">errors</span>
+ </span>
+ <span>Err</span>
+ <span className="text-right">p95</span>
+ </div>
+ {loading && rows.length === 0 ? (
+ <div className="space-y-2 py-3">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <LemonSkeleton key={i} className="h-3.5 w-full" />
+ ))}
+ </div>
+ ) : rows.length === 0 ? (
+ <div className="py-6 text-center text-[12px] text-secondary">No tool calls yet.</div>
+ ) : (
+ rows.map((row, i) => (
+ <ToolRowItem key={row.tool} row={row} maxVolume={maxVolume} isLast={i === rows.length - 1} />
+ ))
+ )}
+ {rows.length > 0 && (
+ <div className="mt-1.5 flex justify-end">
+ <Link to={urls.mcpAnalyticsToolQuality()} className="text-[10px]">
+ View all {totalTools} tools ↗
+ </Link>
+ </div>
+ )}
+ </Card>
+ )
+}
+
+const HARNESS_GRID_TEMPLATE = '160px 1fr 56px 56px'
+
+function HarnessBreakdown({ rows, loading }: { rows: HarnessRow[]; loading: boolean }): JSX.Element {
+ const maxCalls = rows.length ? Math.max(...rows.map((r) => r.total_calls)) : 0
+ const totalCalls = rows.reduce((acc, r) => acc + r.total_calls, 0)
+
+ return (
+ <Card>
+ <div
+ className="grid items-center gap-2.5 pb-1.5 text-[11px] text-secondary"
+ style={{
+ gridTemplateColumns: HARNESS_GRID_TEMPLATE,
+ borderBottom: '0.5px solid var(--color-border-secondary)',
+ }}
+ >
+ <span>Harness</span>
+ <span>
+ <span className="text-[#185FA5]">Calls</span>
+ <span className="mx-1">·</span>
+ <span className="text-[#A32D2D]">errors</span>
+ </span>
+ <span>Err</span>
+ <span className="text-right">Share</span>
+ </div>
+ {loading && rows.length === 0 ? (
+ <div className="space-y-2 py-3">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <LemonSkeleton key={i} className="h-3.5 w-full" />
+ ))}
+ </div>
+ ) : rows.length === 0 ? (
+ <div className="py-6 text-center text-[12px] text-secondary">No harness data yet.</div>
+ ) : (
+ rows.map((row, i) => {
+ const callsPct = maxCalls ? (row.total_calls / maxCalls) * 100 : 0
+ const errorsPct = maxCalls ? (row.errors / maxCalls) * 100 : 0
+ const successPct = Math.max(callsPct - errorsPct, 0)
+ const share = totalCalls ? (row.total_calls / totalCalls) * 100 : 0
+ const tooltip = row.raw_clients.slice(0, 8).join(', ')
+ return (
+ <div
+ key={row.category}
+ className="grid items-center gap-2.5 py-1.5"
+ style={{
+ gridTemplateColumns: HARNESS_GRID_TEMPLATE,
+ borderBottom:
+ i === rows.length - 1 ? 'none' : '0.5px solid var(--color-border-tertiary)',
+ }}
+ >
+ <HarnessPill category={row.category} title={tooltip} />
+ <div
+ className="relative flex h-[14px] overflow-hidden rounded-[3px] bg-surface-secondary"
+ title={`${row.total_calls} calls · ${row.errors} errors · ${row.sessions} sessions`}
+ >
+ <div className="h-full bg-[#B5D4F4]" style={{ width: `${successPct}%` }} />
+ <div className="h-full bg-[#F09595]" style={{ width: `${errorsPct}%` }} />
+ </div>
+ <ErrorRatePill pct={row.error_rate_pct} />
+ <span className="text-right font-mono text-xs text-primary">
+ {share.toFixed(share >= 10 ? 0 : 1)}%
+ </span>
+ </div>
+ )
+ })
+ )}
+ </Card>
+ )
+}
+
+function truncateSessionId(id: string): string {
+ if (id.length <= 12) {
+ return id
+ }
+ return `${id.slice(0, 4)}…${id.slice(-4)}`
+}
+
+function formatDuration(seconds: number): string {
+ if (!seconds || !isFinite(seconds)) {
+ return '—'
+ }
+ if (seconds < 60) {
+ return `${seconds}s`
+ }
+ return humanFriendlyDuration(seconds, { secondsPrecision: 0 })
+}
+
+function StatusPill({ errorRatePct }: { errorRatePct: number }): JSX.Element {
+ if (errorRatePct >= 100) {
+ return (
+ <span className="inline-flex h-[14px] items-center rounded-[3px] bg-[#FCEBEB] px-1.5 text-[10px] font-medium text-[#791F1F]">
+ 100% err
+ </span>
+ )
+ }
+ if (errorRatePct > 0) {
+ const bucket = errorBucket(errorRatePct)
+ return (
+ <span
+ className={`inline-flex h-[14px] items-center rounded-[3px] px-1.5 text-[10px] font-medium ${ERROR_PILL_CLASS[bucket]}`}
+ >
+ {errorRatePct.toFixed(errorRatePct >= 10 ? 0 : 1)}% err
+ </span>
+ )
+ }
+ return (
+ <span className="inline-flex h-[14px] items-center rounded-[3px] bg-[#EAF3DE] px-1.5 text-[10px] font-medium text-[#27500A]">
+ Success
+ </span>
+ )
+}
+
+const NOTABLE_GRID_TEMPLATE = '22% 12% 14% 18% 1fr'
+
+function NotableSessionsTable({ sessions, loading }: { sessions: NotableSession[]; loading: boolean }): JSX.Element {
+ return (
+ <Card>
+ <div
+ className="grid items-center gap-2.5 pb-1.5 text-[11px] text-secondary"
+ style={{
+ gridTemplateColumns: NOTABLE_GRID_TEMPLATE,
+ borderBottom: '0.5px solid var(--color-border-secondary)',
+ }}
+ >
+ <span>Session</span>
+ <span>Calls</span>
+ <span>Duration</span>
+ <span>Status</span>
+ <span>Why notable</span>
+ </div>
+ {loading && sessions.length === 0 ? (
+ <div className="space-y-2 py-3">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <LemonSkeleton key={i} className="h-3.5 w-full" />
+ ))}
+ </div>
+ ) : sessions.length === 0 ? (
+ <div className="py-6 text-center text-[12px] text-secondary">
+ No notable sessions in the last 7 days.
+ </div>
+ ) : (
+ sessions.map((entry, i) => (
+ <div
+ key={entry.session.session_id}
+ className="grid items-center gap-2.5 py-1.5"
+ style={{
+ gridTemplateColumns: NOTABLE_GRID_TEMPLATE,
+ borderBottom:
+ i === sessions.length - 1 ? 'none' : '0.5px solid var(--color-border-tertiary)',
+ }}
+ >
+ <Link
+ to={urls.mcpAnalyticsSessions()}
+ className="truncate font-mono text-[11px]"
+ title={entry.session.session_id}
+ >
+ {truncateSessionId(entry.session.session_id)}
+ </Link>
+ <span className="text-[11px]">{entry.session.tool_calls}</span>
+ <span className="text-[11px]">{formatDuration(entry.session.duration_seconds)}</span>
+ <StatusPill errorRatePct={entry.session.error_rate_pct} />
+ <span className="truncate text-[11px] text-primary" title={entry.label}>
+ {entry.label}
+ </span>
+ </div>
+ ))
+ )}
+ {sessions.length > 0 && (
+ <div className="mt-1.5 flex justify-end">
+ <Link to={urls.mcpAnalyticsSessions()} className="text-[10px]">
+ Open all flagged sessions in Sessions tab ↗
+ </Link>
+ </div>
+ )}
+ </Card>
+ )
+}
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx b/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx
new file mode 100644
index 000000000000..a77161454fbc
--- /dev/null
+++ b/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx
@@ -0,0 +1,75 @@
+import { useValues } from 'kea'
+import { router, combineUrl } from 'kea-router'
+
+import { LemonButton, LemonTab, LemonTabs } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { SceneExport } from '~/scenes/sceneTypes'
+
+import { MCPAnalyticsClustering } from './clustering/MCPAnalyticsClustering'
+import { MCPAnalyticsDashboard } from './MCPAnalyticsDashboard'
+import { MCPAnalyticsTab, TAB_DESCRIPTIONS, mcpAnalyticsSceneLogic } from './mcpAnalyticsSceneLogic'
+import { MCPAnalyticsToolQuality } from './MCPAnalyticsToolQuality'
+import { MCPSessionsTable } from './sessions/MCPSessionsTable'
+
+export const scene: SceneExport = {
+ component: MCPAnalyticsScene,
+ logic: mcpAnalyticsSceneLogic,
+}
+
+const DEFAULT_DOCS_URL = 'https://posthog.com/docs/mcp-analytics/installation'
+
+export function MCPAnalyticsScene(): JSX.Element {
+ const { searchParams } = useValues(router)
+ const { activeTab } = useValues(mcpAnalyticsSceneLogic)
+
+ const tabs: LemonTab<MCPAnalyticsTab>[] = [
+ {
+ key: 'dashboard',
+ label: 'Dashboard',
+ content: <MCPAnalyticsDashboard />,
+ link: combineUrl(urls.mcpAnalyticsDashboard(), searchParams).url,
+ 'data-attr': 'mcp-analytics-dashboard-tab',
+ },
+ {
+ key: 'sessions',
+ label: 'Sessions',
+ content: <MCPSessionsTable />,
+ link: combineUrl(urls.mcpAnalyticsSessions(), searchParams).url,
+ 'data-attr': 'mcp-analytics-sessions-tab',
+ },
+ {
+ key: 'tool-quality',
+ label: 'Tool quality',
+ content: <MCPAnalyticsToolQuality />,
+ link: combineUrl(urls.mcpAnalyticsToolQuality(), searchParams).url,
+ 'data-attr': 'mcp-analytics-tool-quality-tab',
+ },
+ {
+ key: 'intent-clustering',
+ label: 'Intent clustering',
+ content: <MCPAnalyticsClustering />,
+ link: combineUrl(urls.mcpAnalyticsIntentClustering(), searchParams).url,
+ 'data-attr': 'mcp-analytics-intent-clustering-tab',
+ },
+ ]
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="MCP analytics"
+ description={TAB_DESCRIPTIONS[activeTab]}
+ resourceType={{ type: 'llm_analytics' }}
+ actions={
+ <LemonButton to={DEFAULT_DOCS_URL} type="secondary" targetBlank size="small">
+ Documentation
+ </LemonButton>
+ }
+ />
+ <LemonTabs activeKey={activeTab} data-attr="mcp-analytics-tabs" tabs={tabs} sceneInset />
+ </SceneContent>
+ )
+}
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
new file mode 100644
index 000000000000..9e44c39d8098
--- /dev/null
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -0,0 +1,411 @@
+import { useValues } from 'kea'
+
+import { IconArrowLeft, IconArrowRight } from '@posthog/icons'
+import { LemonButton, LemonDivider, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'
+import { humanFriendlyDuration, humanFriendlyNumber } from 'lib/utils'
+import { PersonDisplay } from 'scenes/persons/PersonDisplay'
+import { urls } from 'scenes/urls'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { Query } from '~/queries/Query/Query'
+import { SceneExport } from '~/scenes/sceneTypes'
+
+import { HarnessPill } from './MCPAnalyticsDashboardOverview'
+import {
+ IntentCoverage,
+ MCPAnalyticsToolDetailLogicProps,
+ ToolSummary,
+ mcpAnalyticsToolDetailLogic,
+} from './mcpAnalyticsToolDetailLogic'
+import { categorizeHarness } from './mcpDashboardOverviewLogic'
+
+export const scene: SceneExport<MCPAnalyticsToolDetailLogicProps> = {
+ component: MCPAnalyticsToolDetail,
+ logic: mcpAnalyticsToolDetailLogic,
+ paramsToProps: ({ params: { toolName } }) => ({
+ toolName: decodeURIComponent(toolName ?? ''),
+ }),
+}
+
+function percentDelta(current: number, previous: number): number | null {
+ if (!previous) {
+ return null
+ }
+ return ((current - previous) / previous) * 100
+}
+
+function DeltaTag({ value, invertColor = false }: { value: number | null; invertColor?: boolean }): JSX.Element | null {
+ if (value == null || !isFinite(value) || Math.abs(value) < 1) {
+ return null
+ }
+ const positive = value > 0
+ // For error rate, "up" is bad — invert color semantics.
+ const goodDirection = invertColor ? !positive : positive
+ const Icon = positive ? IconArrowUp : IconArrowDown
+ return (
+ <span
+ className={`inline-flex items-center gap-0.5 text-xs leading-none ${
+ goodDirection ? 'text-success' : 'text-danger'
+ }`}
+ >
+ <Icon className="text-sm" />
+ {Math.abs(Math.round(value))}%
+ </span>
+ )
+}
+
+function Stat({
+ label,
+ value,
+ delta,
+ deltaInvertColor,
+ loading,
+ tooltip,
+}: {
+ label: string
+ value: React.ReactNode
+ delta?: number | null
+ deltaInvertColor?: boolean
+ loading?: boolean
+ tooltip?: string
+}): JSX.Element {
+ const content = (
+ <div className="flex flex-col gap-1 min-w-[110px]">
+ <span className="text-[11px] uppercase tracking-wider text-secondary">{label}</span>
+ {loading ? (
+ <LemonSkeleton className="h-6 w-16" />
+ ) : (
+ <div className="flex items-baseline gap-2">
+ <span className="text-2xl font-semibold leading-none">{value}</span>
+ <DeltaTag value={delta ?? null} invertColor={deltaInvertColor} />
+ </div>
+ )}
+ </div>
+ )
+ return tooltip ? <Tooltip title={tooltip}>{content}</Tooltip> : content
+}
+
+// Renderer for the "person" column in the Top users table. The query selects
+// `argMax(tuple(distinct_id, person.created_at, person.properties), timestamp)`,
+// which deserialises as a 3-element array. Wrap it back into the shape PersonDisplay expects.
+const topUserPersonColumn = {
+ title: 'User',
+ render: function RenderPerson({ value }: { value: unknown }) {
+ if (!Array.isArray(value) || value.length === 0) {
+ return <span className="text-muted">—</span>
+ }
+ const [distinctId, , propertiesRaw] = value as [string, unknown, unknown]
+ let properties: Record<string, unknown> | undefined
+ if (propertiesRaw && typeof propertiesRaw === 'object') {
+ properties = propertiesRaw as Record<string, unknown>
+ } else if (typeof propertiesRaw === 'string') {
+ try {
+ properties = JSON.parse(propertiesRaw)
+ } catch {
+ properties = undefined
+ }
+ }
+ return (
+ <PersonDisplay
+ person={{ distinct_id: distinctId, properties: properties ?? {} }}
+ withIcon
+ noPopover={false}
+ />
+ )
+ },
+}
+
+function SectionHeader({ title, subtitle }: { title: string; subtitle?: string }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-0.5">
+ <h2 className="text-base font-semibold mb-0">{title}</h2>
+ {subtitle ? <span className="text-xs text-secondary">{subtitle}</span> : null}
+ </div>
+ )
+}
+
+function formatDurationMs(ms: number | null): string {
+ if (ms == null) {
+ return '—'
+ }
+ if (ms < 1000) {
+ return `${Math.round(ms)} ms`
+ }
+ return humanFriendlyDuration(ms / 1000, { secondsFixed: 2 })
+}
+
+function StatStrip({ summary, loading }: { summary: ToolSummary | null; loading: boolean }): JSX.Element {
+ const calls = summary?.calls ?? 0
+ const errors = summary?.errors ?? 0
+ const errorRate = calls ? (errors / calls) * 100 : 0
+ const errorRatePrev = summary && summary.calls_prev ? (summary.errors_prev / summary.calls_prev) * 100 : 0
+ return (
+ <div className="flex flex-wrap items-end gap-x-10 gap-y-4 py-1">
+ <Stat
+ label="Calls"
+ loading={loading}
+ value={humanFriendlyNumber(calls)}
+ delta={summary ? percentDelta(calls, summary.calls_prev) : null}
+ tooltip="Last 7 days vs prior 7 days."
+ />
+ <Stat
+ label="Error rate"
+ loading={loading}
+ value={`${errorRate.toFixed(1)}%`}
+ delta={summary ? percentDelta(errorRate, errorRatePrev) : null}
+ deltaInvertColor
+ tooltip="Share of calls with $mcp_is_error = true."
+ />
+ <Stat label="p50 latency" loading={loading} value={formatDurationMs(summary?.p50_ms ?? null)} />
+ <Stat label="p95 latency" loading={loading} value={formatDurationMs(summary?.p95_ms ?? null)} />
+ <Stat label="Users" loading={loading} value={humanFriendlyNumber(summary?.users ?? 0)} />
+ <Stat
+ label="Conversations"
+ loading={loading}
+ value={humanFriendlyNumber(summary?.conversations ?? 0)}
+ tooltip="Unique $mcp_conversation_id values, falling back to $session_id where missing."
+ />
+ </div>
+ )
+}
+
+function IntentCoverageTag({
+ coverage,
+ loading,
+}: {
+ coverage: IntentCoverage | null
+ loading: boolean
+}): JSX.Element | null {
+ if (loading) {
+ return <LemonSkeleton className="h-4 w-32" />
+ }
+ if (!coverage || !coverage.total) {
+ return null
+ }
+ const pct = Math.round((coverage.with_intent / coverage.total) * 100)
+ return (
+ <Tooltip title="Share of calls where $mcp_intent was captured. Inferred intents are server fallbacks; context_parameter intents come from the client.">
+ <span className="text-[11px] text-secondary">
+ {humanFriendlyNumber(coverage.with_intent)} of {humanFriendlyNumber(coverage.total)} calls captured
+ intent ({pct}%)
+ </span>
+ </Tooltip>
+ )
+}
+
+function DescriptionBlock({
+ descriptions,
+ loading,
+}: {
+ descriptions: { description: string; last_seen: string }[]
+ loading: boolean
+}): JSX.Element | null {
+ if (loading) {
+ return <LemonSkeleton className="h-8 w-2/3 mt-2" />
+ }
+ if (!descriptions.length) {
+ return null
+ }
+ const [latest, ...older] = descriptions
+ return (
+ <div className="flex flex-col gap-1 max-w-3xl">
+ <span className="text-[11px] uppercase tracking-wider text-secondary">Description</span>
+ <p className="text-sm leading-snug m-0">{latest.description}</p>
+ {older.length > 0 ? (
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-2 max-w-md">
+ {older.map((d) => (
+ <div key={d.last_seen} className="text-xs">
+ <div className="text-secondary mb-0.5">
+ last seen <TZLabel time={d.last_seen} />
+ </div>
+ <div>{d.description}</div>
+ </div>
+ ))}
+ </div>
+ }
+ >
+ <span className="text-[11px] text-secondary underline decoration-dotted cursor-help w-fit">
+ + {older.length} previous version{older.length === 1 ? '' : 's'}
+ </span>
+ </Tooltip>
+ ) : null}
+ </div>
+ )
+}
+
+export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.Element {
+ const {
+ summary,
+ summaryLoading,
+ descriptions,
+ descriptionsLoading,
+ callsTrendQuery,
+ latencyTrendQuery,
+ failuresQuery,
+ sampleIntentsQuery,
+ intentCoverage,
+ intentCoverageLoading,
+ neighborsBeforeQuery,
+ neighborsAfterQuery,
+ byHarnessQuery,
+ topUsersQuery,
+ } = useValues(mcpAnalyticsToolDetailLogic({ toolName }))
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name={toolName}
+ description={null}
+ resourceType={{ type: 'llm_analytics' }}
+ actions={
+ <LemonButton
+ icon={<IconArrowLeft />}
+ type="secondary"
+ size="small"
+ to={urls.mcpAnalyticsToolQuality()}
+ >
+ Back to Tool quality
+ </LemonButton>
+ }
+ />
+
+ <div className="flex flex-col gap-3 px-4 pb-4">
+ <DescriptionBlock descriptions={descriptions} loading={descriptionsLoading} />
+ <StatStrip summary={summary} loading={summaryLoading} />
+ </div>
+
+ <LemonDivider />
+
+ <div className="flex flex-col gap-3 px-4 pb-4">
+ <SectionHeader title="Reliability" subtitle="Last 7 days" />
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ <div className="flex flex-col bg-bg-light border rounded p-2" style={{ height: 240 }}>
+ <div className="text-secondary text-xs font-medium uppercase mb-1 px-2 pt-1">
+ Calls (broken down by error)
+ </div>
+ <div className="InsightCard__viz">
+ <Query query={callsTrendQuery} readOnly embedded />
+ </div>
+ </div>
+ <div className="flex flex-col bg-bg-light border rounded p-2" style={{ height: 240 }}>
+ <div className="text-secondary text-xs font-medium uppercase mb-1 px-2 pt-1">
+ Duration (p50 / p95)
+ </div>
+ <div className="InsightCard__viz">
+ <Query query={latencyTrendQuery} readOnly embedded />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <LemonDivider />
+
+ <div className="flex flex-col gap-3 px-4 pb-4">
+ <SectionHeader title="Usage flow" />
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ <div className="flex flex-col gap-2 bg-bg-light border rounded p-3">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium uppercase text-secondary">Sample intents</span>
+ <IntentCoverageTag coverage={intentCoverage} loading={intentCoverageLoading} />
+ </div>
+ <Query
+ query={sampleIntentsQuery}
+ readOnly
+ context={{
+ columns: {
+ intent_source: { title: 'Intent source' },
+ },
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-3">
+ <div className="bg-bg-light border rounded p-3 flex flex-col gap-2">
+ <div className="flex items-center gap-1 text-xs font-medium uppercase text-secondary">
+ <IconArrowLeft className="text-base" />
+ Often called before (same conversation)
+ </div>
+ <Query
+ query={neighborsBeforeQuery}
+ readOnly
+ context={{ columns: { co_occurrences: { title: 'In same conversation' } } }}
+ />
+ </div>
+ <div className="bg-bg-light border rounded p-3 flex flex-col gap-2">
+ <div className="flex items-center gap-1 text-xs font-medium uppercase text-secondary">
+ <IconArrowRight className="text-base" />
+ Often called after (same conversation)
+ </div>
+ <Query
+ query={neighborsAfterQuery}
+ readOnly
+ context={{ columns: { co_occurrences: { title: 'In same conversation' } } }}
+ />
+ </div>
+ </div>
+ </div>
+ </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">
+ <div className="bg-bg-light border rounded p-3 flex flex-col gap-2">
+ <span className="text-xs font-medium uppercase text-secondary">By harness</span>
+ <Query
+ query={byHarnessQuery}
+ readOnly
+ context={{
+ columns: {
+ harness: {
+ title: 'Harness',
+ render: function RenderHarness({ value }) {
+ const raw = String(value ?? '')
+ if (!raw) {
+ return <span className="text-muted">Unknown</span>
+ }
+ return <HarnessPill category={categorizeHarness(raw)} title={raw} />
+ },
+ },
+ error_rate_pct: { title: 'Error rate (%)' },
+ },
+ }}
+ />
+ </div>
+ <div className="bg-bg-light border rounded p-3 flex flex-col gap-2">
+ <span className="text-xs font-medium uppercase text-secondary">Top users</span>
+ <Query
+ query={topUsersQuery}
+ readOnly
+ context={{
+ columns: {
+ person: topUserPersonColumn,
+ error_rate_pct: { title: 'Error rate (%)' },
+ last_seen: { title: 'Last seen' },
+ },
+ }}
+ />
+ </div>
+ </div>
+ </div>
+
+ <LemonDivider />
+
+ <div className="flex flex-col gap-3 px-4 pb-4">
+ <SectionHeader
+ title="Failures"
+ subtitle="Top exception messages paired with this tool. Sourced from $exception events."
+ />
+ <Query query={failuresQuery} readOnly context={{ columns: { last_seen: { title: 'Last seen' } } }} />
+ </div>
+ </SceneContent>
+ )
+}
+
+export default MCPAnalyticsToolDetail
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx
new file mode 100644
index 000000000000..5d8e80af2618
--- /dev/null
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx
@@ -0,0 +1,194 @@
+import { useActions, useValues } from 'kea'
+
+import { Link } from 'lib/lemon-ui/Link'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { humanFriendlyDuration } from 'lib/utils'
+import { urls } from 'scenes/urls'
+
+import { DataTable } from '~/queries/nodes/DataTable/DataTable'
+import { Query } from '~/queries/Query/Query'
+import { isHogQLQuery } from '~/queries/utils'
+
+import { mcpAnalyticsToolQualityLogic } from './mcpAnalyticsToolQualityLogic'
+
+const COLLECTION_ID = 'mcp-analytics-tool-quality'
+
+function renderSortableTitle(
+ column: string,
+ title: string,
+ currentSort: { column: string; direction: 'ASC' | 'DESC' },
+ setSort: (column: string, direction: 'ASC' | 'DESC') => void
+): JSX.Element {
+ const isSorted = currentSort.column === column
+ const handleClick = (): void => {
+ const next = isSorted && currentSort.direction === 'DESC' ? 'ASC' : 'DESC'
+ setSort(column, next)
+ }
+ return (
+ <span
+ onClick={handleClick}
+ style={{ cursor: 'pointer', userSelect: 'none' }}
+ className="flex items-center gap-1"
+ >
+ {title}
+ {isSorted ? (currentSort.direction === 'DESC' ? ' ▼' : ' ▲') : ''}
+ </span>
+ )
+}
+
+function formatMs(value: unknown): string {
+ if (value === null || value === undefined || value === '' || Number.isNaN(Number(value))) {
+ return '—'
+ }
+ return humanFriendlyDuration(Number(value) / 1000, { secondsFixed: 2 })
+}
+
+function errorRateClass(rate: number): string {
+ if (rate <= 0) {
+ return 'text-success'
+ }
+ if (rate < 5) {
+ return 'text-warning'
+ }
+ return 'text-danger'
+}
+
+export function MCPAnalyticsToolQuality(): JSX.Element {
+ const { toolQualityQuery, toolQualitySort, topToolsQuery, errorTrendQuery, durationTrendQuery } =
+ useValues(mcpAnalyticsToolQualityLogic)
+ const { setToolQualitySort, setDateFilter } = useActions(mcpAnalyticsToolQualityLogic)
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
+ <div className="bg-bg-light border rounded p-2 min-h-[260px] flex flex-col">
+ <div className="text-muted text-xs font-medium uppercase mb-2 px-2 pt-1">Top tools by calls</div>
+ <div className="flex-1">
+ <Query query={topToolsQuery} readOnly />
+ </div>
+ </div>
+ <div className="bg-bg-light border rounded p-2 min-h-[260px] flex flex-col">
+ <div className="text-muted text-xs font-medium uppercase mb-2 px-2 pt-1">Errors over time</div>
+ <div className="flex-1">
+ <Query query={errorTrendQuery} readOnly />
+ </div>
+ </div>
+ <div className="bg-bg-light border rounded p-2 min-h-[260px] flex flex-col">
+ <div className="text-muted text-xs font-medium uppercase mb-2 px-2 pt-1">Duration over time</div>
+ <div className="flex-1">
+ <Query query={durationTrendQuery} readOnly />
+ </div>
+ </div>
+ </div>
+ <DataTable
+ query={toolQualityQuery}
+ setQuery={(query) => {
+ if (!isHogQLQuery(query.source)) {
+ return
+ }
+ const filters = query.source.filters ?? {}
+ const dateRange = filters.dateRange ?? {}
+ setDateFilter(dateRange.date_from ?? null, dateRange.date_to ?? null)
+ }}
+ context={{
+ columns: {
+ tool: {
+ title: 'Tool',
+ render: function RenderTool({ value }) {
+ if (!value || value === 'null') {
+ return <span className="text-muted">Unknown tool</span>
+ }
+ const toolName = String(value)
+ return (
+ <Link
+ to={urls.mcpAnalyticsTool(toolName)}
+ className="font-mono text-sm"
+ data-attr="mcp-tool-quality-tool-link"
+ >
+ {toolName}
+ </Link>
+ )
+ },
+ },
+ total_calls: {
+ renderTitle: () => (
+ <Tooltip title="Total number of times this tool was called">
+ {renderSortableTitle(
+ 'total_calls',
+ 'Total calls',
+ toolQualitySort,
+ setToolQualitySort
+ )}
+ </Tooltip>
+ ),
+ },
+ error_rate_pct: {
+ renderTitle: () => (
+ <Tooltip title="Percentage of calls that returned $mcp_is_error = true">
+ {renderSortableTitle(
+ 'error_rate_pct',
+ 'Error rate',
+ toolQualitySort,
+ setToolQualitySort
+ )}
+ </Tooltip>
+ ),
+ render: function RenderErrorRate({ value }) {
+ const numeric = Number(value)
+ if (Number.isNaN(numeric)) {
+ return <span className="text-muted">—</span>
+ }
+ return <span className={errorRateClass(numeric)}>{numeric}%</span>
+ },
+ },
+ p95_duration_ms: {
+ renderTitle: () => (
+ <Tooltip title="95th-percentile $mcp_duration_ms">
+ {renderSortableTitle(
+ 'p95_duration_ms',
+ 'p95 duration',
+ toolQualitySort,
+ setToolQualitySort
+ )}
+ </Tooltip>
+ ),
+ render: ({ value }) => <span>{formatMs(value)}</span>,
+ },
+ p50_duration_ms: {
+ renderTitle: () => (
+ <Tooltip title="Median $mcp_duration_ms">
+ {renderSortableTitle(
+ 'p50_duration_ms',
+ 'p50 duration',
+ toolQualitySort,
+ setToolQualitySort
+ )}
+ </Tooltip>
+ ),
+ render: ({ value }) => <span>{formatMs(value)}</span>,
+ },
+ users: {
+ renderTitle: () => (
+ <Tooltip title="Unique users who invoked this tool">
+ {renderSortableTitle('users', 'Users', toolQualitySort, setToolQualitySort)}
+ </Tooltip>
+ ),
+ },
+ sessions: {
+ renderTitle: () => (
+ <Tooltip title="Unique sessions where this tool was called">
+ {renderSortableTitle('sessions', 'Sessions', toolQualitySort, setToolQualitySort)}
+ </Tooltip>
+ ),
+ },
+ last_seen: {
+ renderTitle: () =>
+ renderSortableTitle('last_seen', 'Last seen', toolQualitySort, setToolQualitySort),
+ },
+ },
+ }}
+ uniqueKey={COLLECTION_ID}
+ />
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx b/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx
new file mode 100644
index 000000000000..987852158c5e
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx
@@ -0,0 +1,254 @@
+import { useMemo } from 'react'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import sankey, { sankeyLeft, sankeyLinkHorizontal } from 'lib/d3/sankey'
+
+import type { MCPIntentClusterJourneyApi, MCPIntentClusterJourneyPathApi } from '../generated/api.schemas'
+
+const WIDTH = 720
+const HEIGHT = 300
+const COLUMN_LABELS = ['Init', '1st tool', '2nd tool', '3rd tool', '4th tool', 'Outcome']
+const ENDED_LABEL = 'Ended'
+
+type NodeKind = 'init' | 'tool' | 'ended' | 'completed' | 'error'
+
+interface JourneyNode {
+ name: string
+ column: number
+ kind: NodeKind
+}
+
+interface JourneyLink {
+ source: number
+ target: number
+ value: number
+ outcome: 'completed' | 'error'
+}
+
+function describePath(path: MCPIntentClusterJourneyPathApi): string {
+ const labels = path.steps.map((step) => step ?? ENDED_LABEL)
+ return labels.filter((label, idx) => label !== ENDED_LABEL || idx === labels.indexOf(ENDED_LABEL)).join(' → ')
+}
+
+function nodeFill(kind: NodeKind): string {
+ switch (kind) {
+ case 'init':
+ return 'var(--muted)'
+ case 'ended':
+ return 'var(--muted-3000)'
+ case 'completed':
+ return 'var(--success)'
+ case 'error':
+ return 'var(--danger)'
+ case 'tool':
+ default:
+ return 'var(--accent)'
+ }
+}
+
+function buildGraph(paths: readonly MCPIntentClusterJourneyPathApi[]): {
+ nodes: JourneyNode[]
+ links: JourneyLink[]
+} {
+ const nodeIndex = new Map<string, number>()
+ const nodes: JourneyNode[] = []
+
+ const getNode = (column: number, name: string, kind: NodeKind): number => {
+ const key = `${column}::${name}`
+ const existing = nodeIndex.get(key)
+ if (existing !== undefined) {
+ return existing
+ }
+ const idx = nodes.length
+ nodeIndex.set(key, idx)
+ nodes.push({ name, column, kind })
+ return idx
+ }
+
+ const linkMap = new Map<string, JourneyLink>()
+ const initIdx = getNode(0, 'Init', 'init')
+
+ for (const path of paths) {
+ const columns: { name: string; kind: NodeKind }[] = [{ name: 'Init', kind: 'init' }]
+ for (const step of path.steps) {
+ if (step === null) {
+ columns.push({ name: ENDED_LABEL, kind: 'ended' })
+ } else {
+ columns.push({ name: step, kind: 'tool' })
+ }
+ }
+ columns.push({
+ name: path.outcome === 'error' ? 'Error' : 'Completed',
+ kind: path.outcome === 'error' ? 'error' : 'completed',
+ })
+
+ for (let i = 0; i < columns.length - 1; i++) {
+ const sourceCol = i === 0 ? 0 : i
+ const targetCol = sourceCol + 1
+ const src = sourceCol === 0 ? initIdx : getNode(sourceCol, columns[i].name, columns[i].kind)
+ const tgt = getNode(targetCol, columns[i + 1].name, columns[i + 1].kind)
+ const linkKey = `${src}->${tgt}::${path.outcome}`
+ const existing = linkMap.get(linkKey)
+ if (existing) {
+ existing.value += path.count
+ } else {
+ linkMap.set(linkKey, {
+ source: src,
+ target: tgt,
+ value: path.count,
+ outcome: path.outcome === 'error' ? 'error' : 'completed',
+ })
+ }
+ }
+ }
+
+ return { nodes, links: Array.from(linkMap.values()) }
+}
+
+interface Props {
+ journey: MCPIntentClusterJourneyApi | null | undefined
+}
+
+export function ClusterJourneySankey({ journey }: Props): JSX.Element | null {
+ const graph = useMemo(() => (journey ? buildGraph(journey.paths) : { nodes: [], links: [] }), [journey])
+
+ const layout = useMemo(() => {
+ if (graph.nodes.length === 0 || graph.links.length === 0) {
+ return null
+ }
+ // d3-sankey mutates the inputs, so deep-copy before passing.
+ const layoutFn = sankey<JourneyNode, JourneyLink>()
+ .nodeWidth(18)
+ .nodePadding(10)
+ .nodeAlign(sankeyLeft)
+ .extent([
+ [4, 14],
+ [WIDTH - 4, HEIGHT - 14],
+ ])
+ return layoutFn({
+ nodes: graph.nodes.map((n) => ({ ...n })),
+ links: graph.links.map((l) => ({ ...l })),
+ })
+ }, [graph])
+
+ if (!journey || !layout) {
+ return (
+ <div className="bg-surface-secondary rounded p-4 text-xs text-muted">
+ Not enough session data yet to plot a journey. Recompute after more sessions are summarised.
+ </div>
+ )
+ }
+
+ const linkGen = sankeyLinkHorizontal<JourneyNode, JourneyLink>()
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="text-xs text-muted">
+ {journey.total_sessions} session{journey.total_sessions === 1 ? '' : 's'} · top {journey.paths.length}{' '}
+ path{journey.paths.length === 1 ? '' : 's'}
+ </div>
+ <div className="overflow-x-auto">
+ <svg width={WIDTH} height={HEIGHT} className="block">
+ <g>
+ {COLUMN_LABELS.map((label, idx) => {
+ const colWidth = (WIDTH - 8) / COLUMN_LABELS.length
+ const x = 4 + colWidth * idx + colWidth / 2
+ return (
+ <text
+ key={label}
+ x={x}
+ y={10}
+ textAnchor="middle"
+ className="fill-[var(--muted)]"
+ fontSize={9}
+ >
+ {label}
+ </text>
+ )
+ })}
+ </g>
+ <g>
+ {layout.links.map((link, idx) => {
+ const path = linkGen(link) ?? ''
+ const stroke = link.outcome === 'error' ? 'var(--danger)' : 'var(--accent)'
+ const sourceName = (link.source as unknown as JourneyNode).name
+ const targetName = (link.target as unknown as JourneyNode).name
+ const pct =
+ journey.total_sessions > 0
+ ? Math.round((link.value / journey.total_sessions) * 1000) / 10
+ : 0
+ return (
+ <Tooltip
+ key={idx}
+ title={
+ <div className="flex flex-col gap-0.5">
+ <span className="font-semibold">
+ {sourceName} → {targetName}
+ </span>
+ <span>
+ {link.value} session{link.value === 1 ? '' : 's'} ({pct}%)
+ </span>
+ <span className="text-muted">
+ Outcome: {link.outcome === 'error' ? 'error' : 'completed'}
+ </span>
+ </div>
+ }
+ >
+ <path
+ d={path}
+ fill="none"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ stroke,
+ strokeOpacity: 0.45,
+ strokeWidth: Math.max(1, link.width),
+ }}
+ />
+ </Tooltip>
+ )
+ })}
+ </g>
+ <g>
+ {layout.nodes.map((node, idx) => (
+ <g key={idx}>
+ <rect
+ x={node.x0}
+ y={node.y0}
+ width={node.x1 - node.x0}
+ height={Math.max(1, node.y1 - node.y0)}
+ rx={2}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ fill: nodeFill(node.kind) }}
+ />
+ <text
+ x={node.x0 + (node.x1 - node.x0) / 2}
+ y={node.y1 + 10}
+ textAnchor="middle"
+ className="fill-[var(--text-primary)]"
+ fontSize={10}
+ >
+ <tspan>{node.name}</tspan>
+ </text>
+ </g>
+ ))}
+ </g>
+ </svg>
+ </div>
+ {journey.leak ? (
+ <div className="text-xs text-muted leading-relaxed">
+ <span className="text-danger font-medium">Biggest leak:</span>{' '}
+ <span>
+ {describePath(journey.leak)} drains{' '}
+ <span className="font-medium">
+ {journey.leak.count} session{journey.leak.count === 1 ? '' : 's'}
+ </span>{' '}
+ into {journey.leak.outcome === 'error' ? 'Error' : 'Other'}.
+ </span>
+ </div>
+ ) : (
+ <div className="text-xs text-muted">No failing paths in this cluster.</div>
+ )}
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
new file mode 100644
index 000000000000..4ef4e5c923f9
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
@@ -0,0 +1,557 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh, IconSparkles, IconWarning } from '@posthog/icons'
+import { LemonButton, LemonSkeleton, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+import type { MCPIntentClusterApi, MCPIntentClusterToolEntryApi } from '../generated/api.schemas'
+import { ClusterJourneySankey } from './ClusterJourneySankey'
+import { ClusterSortKey, mcpClusteringLogic } from './mcpClusteringLogic'
+
+const SORT_LABELS: Record<ClusterSortKey, string> = {
+ calls: 'Calls',
+ errors: 'Error rate',
+ entropy: 'Routing entropy',
+ 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.`}>
+ <LemonTag type="success" size="small">
+ Concentrated · {entropy.toFixed(2)}
+ </LemonTag>
+ </Tooltip>
+ )
+ }
+ if (entropy < 0.6) {
+ return (
+ <Tooltip title={`Routing entropy ${entropy.toFixed(2)} — calls split between a few tools.`}>
+ <LemonTag type="warning" size="small">
+ Mixed · {entropy.toFixed(2)}
+ </LemonTag>
+ </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.`}
+ >
+ <LemonTag type="danger" size="small">
+ Spread · {entropy.toFixed(2)}
+ </LemonTag>
+ </Tooltip>
+ )
+}
+
+function HeatmapCell({
+ entry,
+ size,
+ rowMaxCount,
+}: {
+ entry: MCPIntentClusterToolEntryApi | undefined
+ size: number
+ rowMaxCount: number
+}): JSX.Element {
+ const sizeStyle = { width: size, height: size }
+ if (!entry || entry.count === 0) {
+ return (
+ <div
+ className="rounded-[2px] bg-surface-secondary/30"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={sizeStyle}
+ aria-hidden
+ />
+ )
+ }
+ // Scale relative to the row's max — so the most-called tool in each
+ // cluster is fully dark and the rest grade down. A 1-call tool next to
+ // a 50-call tool still shows up clearly thanks to the 0.3 floor.
+ const intensity = rowMaxCount > 0 ? entry.count / rowMaxCount : 0
+ const opacity = Math.max(0.3, Math.min(1, intensity))
+ const hasErrors = entry.error_rate_pct > 0
+ return (
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-0.5">
+ <span className="font-semibold">{entry.tool}</span>
+ <span>{entry.count.toLocaleString()} calls</span>
+ <span>{entry.pct.toFixed(1)}% of cluster</span>
+ {hasErrors ? <span className="text-danger">{entry.error_rate_pct.toFixed(1)}% errors</span> : null}
+ </div>
+ }
+ >
+ <div
+ className="rounded-[2px] cursor-help"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ ...sizeStyle,
+ backgroundColor: hasErrors ? 'var(--danger)' : 'var(--accent)',
+ opacity,
+ }}
+ />
+ </Tooltip>
+ )
+}
+
+function Scorecards(): JSX.Element {
+ const { concentratedRoutes, spreadRoutes, topErrorRoute, clusters } = useValues(mcpClusteringLogic)
+
+ const concentratedShare =
+ concentratedRoutes.total > 0 ? Math.round((100 * concentratedRoutes.focused) / concentratedRoutes.total) : 0
+
+ return (
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
+ <div className="bg-surface-primary border rounded p-3 min-h-[88px] flex flex-col">
+ <span className="text-muted text-xs font-medium uppercase">Concentrated routes</span>
+ <div className="flex items-baseline gap-2 mt-1">
+ <span className="text-2xl font-semibold">
+ {concentratedRoutes.focused}
+ <span className="text-muted text-base"> / {concentratedRoutes.total}</span>
+ </span>
+ <span className="text-xs text-muted">({concentratedShare}%)</span>
+ </div>
+ <span className="text-xs text-muted mt-1">Intent groups where one tool handles ≥80% of calls.</span>
+ </div>
+ <div className="bg-surface-primary border rounded p-3 min-h-[88px] flex flex-col">
+ <span className="text-muted text-xs font-medium uppercase">Spread routes</span>
+ <div className="flex items-baseline gap-2 mt-1">
+ <span className="text-2xl font-semibold">{spreadRoutes}</span>
+ <span className="text-xs text-muted">of {clusters.length}</span>
+ </div>
+ <span className="text-xs text-muted mt-1">
+ Intent groups where no single tool covers half the calls — possible drift.
+ </span>
+ </div>
+ <div className="bg-surface-primary border rounded p-3 min-h-[88px] flex flex-col">
+ <span className="text-muted text-xs font-medium uppercase">Top error route</span>
+ {topErrorRoute && topErrorRoute.error_rate_pct > 0 ? (
+ <>
+ <div className="flex items-baseline gap-2 mt-1">
+ <span className="text-2xl font-semibold text-danger">
+ {topErrorRoute.error_rate_pct.toFixed(1)}%
+ </span>
+ <span className="text-xs text-muted">over {topErrorRoute.call_count} calls</span>
+ </div>
+ <span className="text-xs text-muted mt-1 truncate" title={topErrorRoute.label}>
+ {topErrorRoute.label}
+ </span>
+ </>
+ ) : (
+ <>
+ <div className="flex items-baseline gap-2 mt-1">
+ <span className="text-2xl font-semibold text-success">0%</span>
+ </div>
+ <span className="text-xs text-muted mt-1">No errors observed across clusters.</span>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
+
+function SortHeader(): JSX.Element {
+ const { sortKey } = useValues(mcpClusteringLogic)
+ const { setSortKey } = 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) => (
+ <LemonButton
+ key={key}
+ size="xsmall"
+ type={sortKey === key ? 'primary' : 'tertiary'}
+ onClick={() => setSortKey(key)}
+ >
+ {SORT_LABELS[key]}
+ </LemonButton>
+ ))}
+ </div>
+ )
+}
+
+function Heatmap(): JSX.Element {
+ const { sortedClusters, toolColumns, selectedClusterId } = useValues(mcpClusteringLogic)
+ const { selectCluster } = useActions(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.
+ </div>
+ )
+ }
+
+ // Spacious mode: few tools and shortish names. Bigger cells, horizontal labels.
+ // Compact mode: many tools or long names. Github-style with rotated labels.
+ const longestName = Math.max(...toolColumns.map((t) => t.length))
+ const isSpacious = toolColumns.length <= 6 && longestName <= 14
+
+ const cellSize = isSpacious ? 22 : 14
+ const columnWidth = isSpacious ? 0 : 18 // 0 = let CSS auto-size to label width
+
+ return (
+ <div className="bg-surface-primary border rounded overflow-x-auto">
+ <table className="text-sm border-collapse" style={{ borderSpacing: 0 }}>
+ <thead>
+ <tr className="bg-surface-secondary text-[10px] text-muted">
+ <th className="text-left px-3 py-2 sticky left-0 bg-surface-secondary z-10 min-w-[220px] align-bottom text-xs">
+ Intent cluster
+ </th>
+ {toolColumns.map((tool) =>
+ isSpacious ? (
+ <th
+ key={tool}
+ className="px-2 pb-1 pt-2 font-medium font-mono text-[11px] text-center align-bottom whitespace-nowrap"
+ title={tool}
+ >
+ {tool}
+ </th>
+ ) : (
+ <th
+ key={tool}
+ className="px-0 pb-1 pt-2 font-medium align-bottom"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: columnWidth, minWidth: columnWidth, maxWidth: columnWidth }}
+ >
+ <div
+ className="font-mono text-[10px] mx-auto whitespace-nowrap overflow-hidden text-ellipsis"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ writingMode: 'vertical-rl',
+ transform: 'rotate(180deg)',
+ height: 96,
+ lineHeight: '18px',
+ }}
+ title={tool}
+ >
+ {tool}
+ </div>
+ </th>
+ )
+ )}
+ <th className="px-3 py-2 text-right text-xs align-bottom">Calls</th>
+ <th className="px-3 py-2 text-right text-xs align-bottom">Errors</th>
+ <th className="px-3 py-2 text-left text-xs align-bottom">Routing</th>
+ </tr>
+ </thead>
+ <tbody>
+ {sortedClusters.map((cluster) => {
+ const isSelected = cluster.id === selectedClusterId
+ const byTool = new Map(cluster.tool_distribution.map((e) => [e.tool, e]))
+ const rowMaxCount = cluster.tool_distribution.reduce(
+ (max, entry) => Math.max(max, entry.count),
+ 0
+ )
+ // Sticky cells need their own background — `tr` backgrounds don't paint
+ // through to sticky-positioned children when scrolled horizontally.
+ const rowBg = isSelected
+ ? 'bg-accent/10'
+ : 'bg-surface-primary group-hover:bg-surface-secondary/60'
+ return (
+ <tr
+ key={cluster.id}
+ onClick={() => selectCluster(cluster.id)}
+ className={`group border-t border-primary cursor-pointer transition-colors ${
+ isSelected ? 'bg-accent/10' : 'hover:bg-surface-secondary/60'
+ }`}
+ >
+ <td
+ className={`px-3 py-1.5 sticky left-0 z-10 min-w-[220px] max-w-[280px] transition-colors ${rowBg}`}
+ >
+ <div className="flex flex-col">
+ <span className="font-medium truncate" title={cluster.label}>
+ {cluster.label}
+ </span>
+ <span className="text-[10px] text-muted">
+ {cluster.session_count} session
+ {cluster.session_count === 1 ? '' : 's'} · {cluster.intent_count} intent
+ {cluster.intent_count === 1 ? '' : 's'}
+ </span>
+ </div>
+ </td>
+ {toolColumns.map((tool) => (
+ <td
+ key={tool}
+ className="p-0 align-middle"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={
+ isSpacious
+ ? undefined
+ : { width: columnWidth, minWidth: columnWidth, maxWidth: columnWidth }
+ }
+ >
+ <div className="flex justify-center items-center py-[2px]">
+ <HeatmapCell
+ entry={byTool.get(tool)}
+ size={cellSize}
+ rowMaxCount={rowMaxCount}
+ />
+ </div>
+ </td>
+ ))}
+ <td className="px-3 py-1.5 text-right tabular-nums text-xs">
+ {cluster.call_count.toLocaleString()}
+ </td>
+ <td
+ className={`px-3 py-1.5 text-right tabular-nums text-xs ${
+ cluster.error_rate_pct > 5 ? 'text-danger font-semibold' : ''
+ }`}
+ >
+ {cluster.error_rate_pct.toFixed(1)}%
+ </td>
+ <td className="px-3 py-1.5">
+ <EntropyBadge entropy={cluster.routing_entropy} />
+ </td>
+ </tr>
+ )
+ })}
+ </tbody>
+ </table>
+ </div>
+ )
+}
+
+function ClusterDetail({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Element {
+ const worstTool = [...cluster.tool_distribution].sort((a, b) => b.error_rate_pct - a.error_rate_pct)[0]
+ return (
+ <div className="bg-surface-primary border rounded p-4 flex flex-col gap-4">
+ <header className="flex flex-col gap-2">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex flex-col gap-1 min-w-0">
+ <span className="text-xs uppercase text-muted font-medium">Selected cluster</span>
+ <h3 className="text-lg font-semibold leading-tight">{cluster.label}</h3>
+ </div>
+ <div className="flex flex-wrap items-center gap-2 shrink-0">
+ <EntropyBadge entropy={cluster.routing_entropy} />
+ <LemonTag type={cluster.error_rate_pct > 5 ? 'danger' : 'muted'} size="small">
+ {cluster.error_rate_pct.toFixed(1)}% errors
+ </LemonTag>
+ <LemonTag type="muted" size="small">
+ {cluster.call_count.toLocaleString()} calls
+ </LemonTag>
+ <LemonTag type="muted" size="small">
+ {cluster.session_count} session{cluster.session_count === 1 ? '' : 's'}
+ </LemonTag>
+ <LemonTag type="muted" size="small">
+ {cluster.intent_count} intent{cluster.intent_count === 1 ? '' : 's'}
+ </LemonTag>
+ </div>
+ </div>
+ {worstTool && worstTool.error_rate_pct > 0 ? (
+ <div className="flex items-center gap-1 text-xs text-muted">
+ <IconWarning className="text-danger" />
+ Weakest tool in this cluster: <span className="font-mono">{worstTool.tool}</span>
+ <span className="text-danger ml-1">{worstTool.error_rate_pct.toFixed(1)}% errors</span>
+ </div>
+ ) : null}
+ </header>
+
+ <section className="flex flex-col gap-2">
+ <span className="text-xs uppercase text-muted font-medium">Sample intents in this cluster</span>
+ {cluster.sample_intents.length === 0 ? (
+ <div className="text-sm text-muted">No representative intents recorded.</div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ {cluster.sample_intents.map((intent, idx) => (
+ <div
+ key={idx}
+ className="bg-surface-secondary rounded p-2 text-xs font-mono leading-relaxed"
+ >
+ <span className="text-muted mr-1">&ldquo;</span>
+ {intent}
+ <span className="text-muted ml-1">&rdquo;</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+
+ <section className="flex flex-col gap-2">
+ <span className="text-xs uppercase text-muted font-medium">Tool routing breakdown</span>
+ <LemonTable
+ embedded
+ size="small"
+ dataSource={[...cluster.tool_distribution]}
+ rowKey={(row) => row.tool}
+ columns={[
+ {
+ title: 'Tool',
+ key: 'tool',
+ render: (_, row) => <span className="font-mono">{row.tool}</span>,
+ },
+ {
+ title: 'Calls',
+ key: 'count',
+ align: 'right',
+ render: (_, row) => row.count.toLocaleString(),
+ },
+ {
+ title: 'Share of cluster',
+ key: 'pct',
+ render: (_, row) => (
+ <div className="flex items-center gap-2 min-w-[160px]">
+ <LemonProgress percent={row.pct} className="flex-1" />
+ <span className="text-xs text-muted tabular-nums w-10 text-right">
+ {row.pct.toFixed(1)}%
+ </span>
+ </div>
+ ),
+ },
+ {
+ title: 'Errors',
+ key: 'errors',
+ align: 'right',
+ render: (_, row) =>
+ row.error_rate_pct > 0 ? (
+ <span className="text-danger tabular-nums">
+ {row.error_rate_pct.toFixed(1)}%{' '}
+ <span className="text-muted">({row.errors})</span>
+ </span>
+ ) : (
+ <span className="text-muted">0%</span>
+ ),
+ },
+ ]}
+ />
+ </section>
+
+ <section className="flex flex-col gap-2">
+ <span className="text-xs uppercase text-muted font-medium">Agent journeys</span>
+ <ClusterJourneySankey journey={cluster.journey ?? null} />
+ </section>
+ </div>
+ )
+}
+
+function StatusRow(): JSX.Element | null {
+ const { snapshot, isComputing } = useValues(mcpClusteringLogic)
+ const { recompute } = useActions(mcpClusteringLogic)
+ if (snapshot.status === 'error') {
+ return null
+ }
+ if (isComputing) {
+ return (
+ <div className="flex items-center gap-2 text-sm text-muted">
+ <Spinner />
+ Embedding intents and clustering — usually 30–60 seconds.
+ </div>
+ )
+ }
+ if (snapshot.last_computed_at) {
+ const meta = snapshot.computed_with
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
+ <span>Last computed</span>
+ <TZLabel time={snapshot.last_computed_at} />
+ {meta ? (
+ <>
+ <span>·</span>
+ <span>{meta.n_clusters} clusters</span>
+ <span>·</span>
+ <span>{meta.n_intents} intents</span>
+ <span>·</span>
+ <span>cosine threshold {meta.distance_threshold.toFixed(2)}</span>
+ </>
+ ) : null}
+ </div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconRefresh />}
+ onClick={recompute}
+ data-attr="mcp-analytics-intent-clusters-recompute"
+ >
+ Recompute
+ </LemonButton>
+ </div>
+ )
+ }
+ return null
+}
+
+function EmptyState(): 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 intent clusters yet</h3>
+ <p className="text-sm text-muted max-w-md">
+ Clustering groups your agents&apos; session-level goals into themes, then shows which tools each theme
+ routes to. It surfaces whether your MCP sends similar goals to the same tools, and which routes are the
+ most error-prone.
+ </p>
+ <LemonButton type="primary" icon={<IconSparkles />} onClick={recompute} loading={snapshotLoading}>
+ Compute intent clusters
+ </LemonButton>
+ <span className="text-xs text-muted">
+ Needs sessions with a summarized intent — usually a few minutes after sessions are recorded.
+ </span>
+ </div>
+ )
+}
+
+function ComputingSkeleton(): JSX.Element {
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
+ <LemonSkeleton className="h-24 w-full" />
+ <LemonSkeleton className="h-24 w-full" />
+ <LemonSkeleton className="h-24 w-full" />
+ </div>
+ <LemonSkeleton className="h-96 w-full" />
+ <LemonSkeleton className="h-48 w-full" />
+ </div>
+ )
+}
+
+export function MCPAnalyticsClustering(): JSX.Element {
+ const { snapshot, selectedCluster, hasSnapshot, isComputing, snapshotLoading } = useValues(mcpClusteringLogic)
+ const { recompute } = useActions(mcpClusteringLogic)
+
+ if (snapshot.status === 'error') {
+ return (
+ <div className="flex flex-col gap-3">
+ <LemonBanner type="error" action={{ children: 'Retry', onClick: recompute }}>
+ {snapshot.error_message || 'The last clustering run failed.'}
+ </LemonBanner>
+ </div>
+ )
+ }
+
+ if (!hasSnapshot && !isComputing && !snapshotLoading) {
+ return <EmptyState />
+ }
+
+ if (isComputing || (snapshotLoading && !hasSnapshot)) {
+ return (
+ <div className="flex flex-col gap-4">
+ <StatusRow />
+ <ComputingSkeleton />
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <StatusRow />
+ <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/mcpClusteringLogic.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
new file mode 100644
index 000000000000..c16ac74631f0
--- /dev/null
+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
@@ -0,0 +1,213 @@
+import { actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+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 { mcpClusteringLogicType } from './mcpClusteringLogicType'
+
+const EMPTY_SNAPSHOT: MCPIntentClusterSnapshotApi = {
+ status: 'idle',
+ error_message: '',
+ last_computed_at: null,
+ last_computed_by_email: '',
+ clusters: [],
+ computed_with: null,
+}
+
+const POLL_INTERVAL_MS = 3000
+
+// 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
+}
+
+export type ClusterSortKey = 'calls' | 'errors' | 'entropy' | 'concentration'
+
+export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
+ path(['products', 'mcp_analytics', 'frontend', 'clustering', 'mcpClusteringLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+ actions({
+ selectCluster: (clusterId: number | null) => ({ clusterId }),
+ setSortKey: (sortKey: ClusterSortKey) => ({ sortKey }),
+ recompute: true,
+ startPolling: true,
+ stopPolling: true,
+ pollSnapshot: true,
+ }),
+ loaders(({ values }) => ({
+ snapshot: [
+ EMPTY_SNAPSHOT as MCPIntentClusterSnapshotApi,
+ {
+ loadSnapshot: async () => {
+ if (!values.currentProjectId) {
+ return EMPTY_SNAPSHOT
+ }
+ const response = await mcpAnalyticsIntentClustersRetrieve(String(values.currentProjectId))
+ return normalizeSnapshot(response)
+ },
+ triggerRecompute: async () => {
+ if (!values.currentProjectId) {
+ return EMPTY_SNAPSHOT
+ }
+ const response = await mcpAnalyticsIntentClustersRecompute(String(values.currentProjectId))
+ return normalizeSnapshot(response)
+ },
+ },
+ ],
+ })),
+ reducers({
+ selectedClusterId: [
+ null as number | null,
+ {
+ selectCluster: (_, { clusterId }) => clusterId,
+ },
+ ],
+ sortKey: [
+ 'calls' as ClusterSortKey,
+ {
+ setSortKey: (_, { sortKey }) => sortKey,
+ },
+ ],
+ }),
+ selectors({
+ clusters: [(s) => [s.snapshot], (snapshot): readonly MCPIntentClusterApi[] => snapshot.clusters],
+ sortedClusters: [
+ (s) => [s.clusters, s.sortKey],
+ (clusters, sortKey): MCPIntentClusterApi[] => {
+ const arr = [...clusters]
+ switch (sortKey) {
+ case 'errors':
+ return arr.sort((a, b) => b.error_rate_pct - a.error_rate_pct)
+ case 'entropy':
+ return arr.sort((a, b) => b.routing_entropy - a.routing_entropy)
+ case 'concentration':
+ return arr.sort(
+ (a, b) => (a.tool_distribution[0]?.pct ?? 0) - (b.tool_distribution[0]?.pct ?? 0)
+ )
+ case 'calls':
+ default:
+ return arr.sort((a, b) => b.call_count - a.call_count)
+ }
+ },
+ ],
+ // Tools across the whole snapshot, ordered by total calls desc — these are the heatmap columns.
+ toolColumns: [
+ (s) => [s.clusters],
+ (clusters): string[] => {
+ const totals = new Map<string, number>()
+ for (const cluster of clusters) {
+ for (const entry of cluster.tool_distribution) {
+ totals.set(entry.tool, (totals.get(entry.tool) ?? 0) + entry.count)
+ }
+ }
+ return [...totals.entries()].sort((a, b) => b[1] - a[1]).map(([tool]) => tool)
+ },
+ ],
+ selectedCluster: [
+ (s) => [s.clusters, s.selectedClusterId],
+ (clusters, selectedClusterId): MCPIntentClusterApi | null => {
+ if (selectedClusterId === null) {
+ return null
+ }
+ return clusters.find((c) => c.id === selectedClusterId) ?? null
+ },
+ ],
+ // Scorecard derivations — all from existing aggregate fields.
+ concentratedRoutes: [
+ (s) => [s.clusters],
+ (clusters): { focused: number; total: number } => ({
+ focused: clusters.filter((c) => (c.tool_distribution[0]?.pct ?? 0) >= 80).length,
+ total: clusters.length,
+ }),
+ ],
+ spreadRoutes: [
+ (s) => [s.clusters],
+ (clusters): number =>
+ clusters.filter((c) => {
+ const top = c.tool_distribution[0]?.pct ?? 100
+ return c.tool_distribution.length >= 2 && top < 50
+ }).length,
+ ],
+ topErrorRoute: [
+ (s) => [s.clusters],
+ (clusters): MCPIntentClusterApi | null => {
+ if (clusters.length === 0) {
+ return null
+ }
+ // Highest traffic-weighted error count — the cluster that loses the most calls to errors.
+ return [...clusters].sort(
+ (a, b) => b.call_count * b.error_rate_pct - a.call_count * a.error_rate_pct
+ )[0]
+ },
+ ],
+ isComputing: [(s) => [s.snapshot], (snapshot): boolean => snapshot.status === 'computing'],
+ hasSnapshot: [
+ (s) => [s.snapshot],
+ (snapshot): boolean => snapshot.last_computed_at !== null || snapshot.clusters.length > 0,
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ loadSnapshotSuccess: ({ snapshot }) => {
+ if (snapshot.status === 'computing') {
+ actions.startPolling()
+ } else {
+ actions.stopPolling()
+ }
+ if (values.selectedClusterId === null && snapshot.clusters.length > 0) {
+ // Auto-select the highest-traffic cluster so the detail pane fills in.
+ const top = [...snapshot.clusters].sort((a, b) => b.call_count - a.call_count)[0]
+ actions.selectCluster(top.id)
+ }
+ },
+ triggerRecomputeSuccess: ({ snapshot }) => {
+ lemonToast.info('Clustering started — this usually takes 30–60 seconds.')
+ if (snapshot.status === 'computing') {
+ actions.startPolling()
+ }
+ },
+ triggerRecomputeFailure: ({ error }) => {
+ lemonToast.error(`Could not start clustering: ${error ?? 'unknown error'}`)
+ },
+ recompute: () => {
+ actions.triggerRecompute()
+ },
+ startPolling: () => {
+ if (cache.pollHandle) {
+ return
+ }
+ cache.pollHandle = window.setInterval(() => {
+ actions.pollSnapshot()
+ }, POLL_INTERVAL_MS)
+ },
+ stopPolling: () => {
+ if (cache.pollHandle) {
+ window.clearInterval(cache.pollHandle)
+ cache.pollHandle = null
+ }
+ },
+ pollSnapshot: () => {
+ actions.loadSnapshot()
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadSnapshot()
+ }),
+ beforeUnmount(({ actions }) => {
+ actions.stopPolling()
+ }),
+])
diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.ts
index 008b8a59faa6..65d02b9b02a8 100644
--- a/products/mcp_analytics/frontend/generated/api.schemas.ts
+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts
@@ -141,6 +141,123 @@ export interface MCPFeedbackCreateApi {
category?: MCPFeedbackCreateCategoryEnumApi
}
+/**
+ * * `idle` - Idle
+ * `computing` - Computing
+ * `error` - Error
+ */
+export type MCPIntentClusterSnapshotStatusEnumApi =
+ (typeof MCPIntentClusterSnapshotStatusEnumApi)[keyof typeof MCPIntentClusterSnapshotStatusEnumApi]
+
+export const MCPIntentClusterSnapshotStatusEnumApi = {
+ Idle: 'idle',
+ Computing: 'computing',
+ Error: 'error',
+} as const
+
+export interface MCPIntentClusterToolEntryApi {
+ /** MCP tool name that received calls for this cluster. */
+ readonly tool: string
+ /** Number of tool calls routed to this tool across the cluster. */
+ readonly count: number
+ /** Percentage of the cluster's calls that went to this tool, 0–100. */
+ readonly pct: number
+ /** Number of error responses observed for this tool within the cluster. */
+ readonly errors: number
+ /** Error rate for this tool within the cluster, 0–100. */
+ readonly error_rate_pct: number
+}
+
+/**
+ * * `completed` - Completed
+ * `error` - Error
+ */
+export type OutcomeEnumApi = (typeof OutcomeEnumApi)[keyof typeof OutcomeEnumApi]
+
+export const OutcomeEnumApi = {
+ Completed: 'completed',
+ Error: 'error',
+} as const
+
+export interface MCPIntentClusterJourneyPathApi {
+ /** Ordered tool names called during the path. Length is fixed; null entries indicate the session ended before this step. */
+ readonly steps: readonly (string | null)[]
+ /** Terminal outcome of the sessions following this path.
+
+ * `completed` - Completed
+ * `error` - Error */
+ readonly outcome: OutcomeEnumApi
+ /** Number of sessions in this cluster that followed this exact path. */
+ readonly count: number
+}
+
+export interface MCPIntentClusterJourneyApi {
+ /** Top paths by session count, capped at MAX_JOURNEY_PATHS_PER_CLUSTER. */
+ readonly paths: readonly MCPIntentClusterJourneyPathApi[]
+ /** Total session count represented across all paths in this cluster. */
+ readonly total_sessions: number
+ /** Highest-volume non-completed path. Null when every path completed successfully. */
+ readonly leak: MCPIntentClusterJourneyPathApi | null
+}
+
+export interface MCPIntentClusterApi {
+ /** Stable cluster identifier within this snapshot. */
+ readonly id: number
+ /** Representative intent text for the cluster (the medoid intent closest to the cluster centroid). */
+ readonly label: string
+ /** Number of distinct intent texts that belong to this cluster. */
+ readonly intent_count: number
+ /** Number of MCP sessions whose summarised intent belongs to this cluster. */
+ readonly session_count: number
+ /** Total number of mcp_tool_call events represented by this cluster. */
+ readonly call_count: number
+ /** Total number of error responses observed across the cluster. */
+ readonly error_count: number
+ /** Aggregate error rate across all tool calls in the cluster, 0–100. */
+ readonly error_rate_pct: number
+ /** Normalised Shannon entropy of the tool distribution. 0 means perfectly consistent routing (one tool dominates); 1 means uniformly spread across all tools called for this intent cluster. */
+ readonly routing_entropy: number
+ /** Per-tool breakdown of calls and errors within the cluster. */
+ readonly tool_distribution: readonly MCPIntentClusterToolEntryApi[]
+ /** Up to three representative intent strings from the cluster, ordered by frequency desc. */
+ 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
+}
+
+export interface MCPIntentClusterSnapshotMetaApi {
+ /** Cosine distance threshold used by the clustering algorithm. */
+ readonly distance_threshold: number
+ /** Embedding model used to vectorise intents. */
+ readonly embedding_model: string
+ /** Number of distinct intents that fed into the clustering run. */
+ readonly n_intents: number
+ /** Number of clusters produced by the run. */
+ readonly n_clusters: number
+}
+
+export interface MCPIntentClusterSnapshotApi {
+ /** Whether a snapshot is current (idle), being recomputed (computing), or failed (error).
+
+ * `idle` - Idle
+ * `computing` - Computing
+ * `error` - Error */
+ readonly status: MCPIntentClusterSnapshotStatusEnumApi
+ /** Error message from the most recent failed run, otherwise empty. */
+ readonly error_message: string
+ /**
+ * When the latest snapshot finished computing.
+ * @nullable
+ */
+ readonly last_computed_at: string | null
+ /** Email of the user who triggered the latest recompute, empty for system-triggered runs. */
+ 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. */
+ readonly computed_with: MCPIntentClusterSnapshotMetaApi | null
+}
+
export interface MCPMissingCapabilityCreateApi {
/**
* The tool the user tried before leaving feedback, if known.
@@ -191,6 +308,69 @@ export interface MCPMissingCapabilityCreateApi {
blocked?: boolean
}
+export interface MCPSessionApi {
+ /** PostHog $session_id grouping all mcp_tool_call events. */
+ readonly session_id: string
+ /** Total number of mcp_tool_call events in the session. */
+ readonly tool_calls: number
+ /** Timestamp of the first mcp_tool_call event in the session. */
+ readonly session_start: string
+ /** Timestamp of the most recent mcp_tool_call event in the session. */
+ readonly session_end: string
+ /** Number of distinct PostHog distinct_ids that produced events in the session. */
+ readonly distinct_id_count: number
+ /** Distinct $mcp_tool_name values seen in the session. */
+ readonly tools_used: readonly string[]
+ /** Most recent $mcp_client_name observed in the session. */
+ readonly mcp_client_name: string
+ /** Most recent distinct_id observed for the session. Stable identifier the SDK tagged the events with. */
+ readonly distinct_id: string
+ /** email property of the Person resolved from distinct_id; empty when no Person is mapped. */
+ readonly person_email: string
+ /** name property of the Person resolved from distinct_id; empty when no Person is mapped. */
+ readonly person_name: string
+ /** LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until the summary workflow runs. */
+ readonly intent: string
+}
+
+export interface PaginatedMCPSessionListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: MCPSessionApi[]
+}
+
+export interface MCPToolCallApi {
+ /** ClickHouse uuid of the mcp_tool_call event. */
+ readonly event_id: string
+ /** When the tool call was captured. */
+ readonly timestamp: string
+ /** Tool that was invoked ($mcp_tool_name). */
+ readonly tool_name: string
+ /** Agent intent for this tool call ($mcp_intent). Empty when the SDK did not capture context. */
+ readonly intent: string
+ /** Whether the tool call resulted in an error. */
+ readonly is_error: boolean
+ /** Error message when is_error is true, otherwise empty. */
+ readonly error_message: string
+ /**
+ * Duration of the tool call in milliseconds when captured.
+ * @nullable
+ */
+ readonly duration_ms: number | null
+}
+
+export interface PaginatedMCPToolCallListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: MCPToolCallApi[]
+}
+
export type McpAnalyticsFeedbackListParams = {
/**
* Number of results to return per page.
@@ -212,3 +392,33 @@ export type McpAnalyticsMissingCapabilitiesListParams = {
*/
offset?: number
}
+
+export type McpAnalyticsSessionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Sort column. Allowed: session_id, session_start, session_end, duration_seconds, tool_call_count, mcp_client_name, distinct_id. Prefix with '-' for descending. Defaults to '-session_end'.
+ */
+ order_by?: string
+ /**
+ * Case-insensitive substring filter matched against session_id, distinct_id, mcp_client_name, and tools_used.
+ */
+ search?: string
+}
+
+export type McpAnalyticsSessionsToolCallsParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.ts
index 9334e7bc8f4d..aa7b60815d28 100644
--- a/products/mcp_analytics/frontend/generated/api.ts
+++ b/products/mcp_analytics/frontend/generated/api.ts
@@ -11,10 +11,15 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
MCPAnalyticsSubmissionApi,
MCPFeedbackCreateApi,
+ MCPIntentClusterSnapshotApi,
MCPMissingCapabilityCreateApi,
McpAnalyticsFeedbackListParams,
McpAnalyticsMissingCapabilitiesListParams,
+ McpAnalyticsSessionsListParams,
+ McpAnalyticsSessionsToolCallsParams,
PaginatedMCPAnalyticsSubmissionListApi,
+ PaginatedMCPSessionListApi,
+ PaginatedMCPToolCallListApi,
} from './api.schemas'
export const getMcpAnalyticsFeedbackListUrl = (projectId: string, params?: McpAnalyticsFeedbackListParams) => {
@@ -67,6 +72,40 @@ export const mcpAnalyticsFeedbackCreate = async (
})
}
+export const getMcpAnalyticsIntentClustersRetrieveUrl = (projectId: string) => {
+ return `/api/environments/${projectId}/mcp_analytics/intent_clusters/`
+}
+
+/**
+ * Return the most recent intent cluster snapshot for the current project. Returns an empty IDLE snapshot when no clustering run has happened yet.
+ */
+export const mcpAnalyticsIntentClustersRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<MCPIntentClusterSnapshotApi[]> => {
+ return apiMutator<MCPIntentClusterSnapshotApi[]>(getMcpAnalyticsIntentClustersRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMcpAnalyticsIntentClustersRecomputeUrl = (projectId: string) => {
+ return `/api/environments/${projectId}/mcp_analytics/intent_clusters/recompute/`
+}
+
+/**
+ * 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').
+ */
+export const mcpAnalyticsIntentClustersRecompute = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<MCPIntentClusterSnapshotApi> => {
+ return apiMutator<MCPIntentClusterSnapshotApi>(getMcpAnalyticsIntentClustersRecomputeUrl(projectId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getMcpAnalyticsMissingCapabilitiesListUrl = (
projectId: string,
params?: McpAnalyticsMissingCapabilitiesListParams
@@ -122,3 +161,68 @@ export const mcpAnalyticsMissingCapabilitiesCreate = async (
body: JSON.stringify(mCPMissingCapabilityCreateApi),
})
}
+
+export const getMcpAnalyticsSessionsListUrl = (projectId: string, params?: McpAnalyticsSessionsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/mcp_analytics/sessions/?${stringifiedParams}`
+ : `/api/environments/${projectId}/mcp_analytics/sessions/`
+}
+
+/**
+ * List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_conversation_id. Ordered by most recent activity first by default.
+ */
+export const mcpAnalyticsSessionsList = async (
+ projectId: string,
+ params?: McpAnalyticsSessionsListParams,
+ options?: RequestInit
+): Promise<PaginatedMCPSessionListApi> => {
+ return apiMutator<PaginatedMCPSessionListApi>(getMcpAnalyticsSessionsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMcpAnalyticsSessionsToolCallsUrl = (
+ projectId: string,
+ id: string,
+ params?: McpAnalyticsSessionsToolCallsParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/mcp_analytics/sessions/${id}/tool_calls/?${stringifiedParams}`
+ : `/api/environments/${projectId}/mcp_analytics/sessions/${id}/tool_calls/`
+}
+
+/**
+ * List all mcp_tool_call events that belong to a given $session_id, in chronological order.
+ */
+export const mcpAnalyticsSessionsToolCalls = async (
+ projectId: string,
+ id: string,
+ params?: McpAnalyticsSessionsToolCallsParams,
+ options?: RequestInit
+): Promise<PaginatedMCPToolCallListApi> => {
+ return apiMutator<PaginatedMCPToolCallListApi>(getMcpAnalyticsSessionsToolCallsUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/mcp_analytics/frontend/harness-logos/claude.svg b/products/mcp_analytics/frontend/harness-logos/claude.svg
new file mode 100644
index 000000000000..29bb61bb9eed
--- /dev/null
+++ b/products/mcp_analytics/frontend/harness-logos/claude.svg
@@ -0,0 +1 @@
+<svg fill="#D97757" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Claude</title><path d="m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z"/></svg>
\ No newline at end of file
diff --git a/products/mcp_analytics/frontend/harness-logos/cursor.svg b/products/mcp_analytics/frontend/harness-logos/cursor.svg
new file mode 100644
index 000000000000..14085aac899f
--- /dev/null
+++ b/products/mcp_analytics/frontend/harness-logos/cursor.svg
@@ -0,0 +1 @@
+<svg fill="#000000" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cursor</title><path d="M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23"/></svg>
\ No newline at end of file
diff --git a/products/mcp_analytics/frontend/harness-logos/openai.svg b/products/mcp_analytics/frontend/harness-logos/openai.svg
new file mode 100644
index 000000000000..2312a7744253
--- /dev/null
+++ b/products/mcp_analytics/frontend/harness-logos/openai.svg
@@ -0,0 +1,10 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 2406 2406">
+ <path d="M1 578.4C1 259.5 259.5 1 578.4 1h1249.1c319 0 577.5 258.5 577.5 577.4V2406H578.4C259.5 2406 1 2147.5 1 1828.6V578.4z" fill="#74aa9c"/>
+ <path id="a" d="M1107.3 299.1c-197.999 0-373.9 127.3-435.2 315.3L650 743.5v427.9c0 21.4 11 40.4 29.4 51.4l344.5 198.515V833.3h.1v-27.9L1372.7 604c33.715-19.52 70.44-32.857 108.47-39.828L1447.6 450.3C1361 353.5 1237.1 298.5 1107.3 299.1zm0 117.5-.6.6c79.699 0 156.3 27.5 217.6 78.4-2.5 1.2-7.4 4.3-11 6.1L952.8 709.3c-18.4 10.4-29.4 30-29.4 51.4V1248l-155.1-89.4V755.8c-.1-187.099 151.601-338.9 339-339.2z" fill="#fff"/>
+ <use xlink:href="#a" transform="rotate(60 1203 1203)"/>
+ <use xlink:href="#a" transform="rotate(120 1203 1203)"/>
+ <use xlink:href="#a" transform="rotate(180 1203 1203)"/>
+ <use xlink:href="#a" transform="rotate(240 1203 1203)"/>
+ <use xlink:href="#a" transform="rotate(300 1203 1203)"/>
+
+</svg>
\ No newline at end of file
diff --git a/products/mcp_analytics/frontend/harness-logos/vscode.svg b/products/mcp_analytics/frontend/harness-logos/vscode.svg
new file mode 100644
index 000000000000..0557c2cb3a10
--- /dev/null
+++ b/products/mcp_analytics/frontend/harness-logos/vscode.svg
@@ -0,0 +1,41 @@
+<svg viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<mask id="mask0" mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="100" height="100">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M70.9119 99.3171C72.4869 99.9307 74.2828 99.8914 75.8725 99.1264L96.4608 89.2197C98.6242 88.1787 100 85.9892 100 83.5872V16.4133C100 14.0113 98.6243 11.8218 96.4609 10.7808L75.8725 0.873756C73.7862 -0.130129 71.3446 0.11576 69.5135 1.44695C69.252 1.63711 69.0028 1.84943 68.769 2.08341L29.3551 38.0415L12.1872 25.0096C10.589 23.7965 8.35363 23.8959 6.86933 25.2461L1.36303 30.2549C-0.452552 31.9064 -0.454633 34.7627 1.35853 36.417L16.2471 50.0001L1.35853 63.5832C-0.454633 65.2374 -0.452552 68.0938 1.36303 69.7453L6.86933 74.7541C8.35363 76.1043 10.589 76.2037 12.1872 74.9905L29.3551 61.9587L68.769 97.9167C69.3925 98.5406 70.1246 99.0104 70.9119 99.3171ZM75.0152 27.2989L45.1091 50.0001L75.0152 72.7012V27.2989Z" fill="white"/>
+</mask>
+<g mask="url(#mask0)">
+<path d="M96.4614 10.7962L75.8569 0.875542C73.4719 -0.272773 70.6217 0.211611 68.75 2.08333L1.29858 63.5832C-0.515693 65.2373 -0.513607 68.0937 1.30308 69.7452L6.81272 74.754C8.29793 76.1042 10.5347 76.2036 12.1338 74.9905L93.3609 13.3699C96.086 11.3026 100 13.2462 100 16.6667V16.4275C100 14.0265 98.6246 11.8378 96.4614 10.7962Z" fill="#0065A9"/>
+<g filter="url(#filter0_d)">
+<path d="M96.4614 89.2038L75.8569 99.1245C73.4719 100.273 70.6217 99.7884 68.75 97.9167L1.29858 36.4169C-0.515693 34.7627 -0.513607 31.9063 1.30308 30.2548L6.81272 25.246C8.29793 23.8958 10.5347 23.7964 12.1338 25.0095L93.3609 86.6301C96.086 88.6974 100 86.7538 100 83.3334V83.5726C100 85.9735 98.6246 88.1622 96.4614 89.2038Z" fill="#007ACC"/>
+</g>
+<g filter="url(#filter1_d)">
+<path d="M75.8578 99.1263C73.4721 100.274 70.6219 99.7885 68.75 97.9166C71.0564 100.223 75 98.5895 75 95.3278V4.67213C75 1.41039 71.0564 -0.223106 68.75 2.08329C70.6219 0.211402 73.4721 -0.273666 75.8578 0.873633L96.4587 10.7807C98.6234 11.8217 100 14.0112 100 16.4132V83.5871C100 85.9891 98.6234 88.1786 96.4586 89.2196L75.8578 99.1263Z" fill="#1F9CF0"/>
+</g>
+<g style="mix-blend-mode:overlay" opacity="0.25">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M70.8511 99.3171C72.4261 99.9306 74.2221 99.8913 75.8117 99.1264L96.4 89.2197C98.5634 88.1787 99.9392 85.9892 99.9392 83.5871V16.4133C99.9392 14.0112 98.5635 11.8217 96.4001 10.7807L75.8117 0.873695C73.7255 -0.13019 71.2838 0.115699 69.4527 1.44688C69.1912 1.63705 68.942 1.84937 68.7082 2.08335L29.2943 38.0414L12.1264 25.0096C10.5283 23.7964 8.29285 23.8959 6.80855 25.246L1.30225 30.2548C-0.513334 31.9064 -0.515415 34.7627 1.29775 36.4169L16.1863 50L1.29775 63.5832C-0.515415 65.2374 -0.513334 68.0937 1.30225 69.7452L6.80855 74.754C8.29285 76.1042 10.5283 76.2036 12.1264 74.9905L29.2943 61.9586L68.7082 97.9167C69.3317 98.5405 70.0638 99.0104 70.8511 99.3171ZM74.9544 27.2989L45.0483 50L74.9544 72.7012V27.2989Z" fill="url(#paint0_linear)"/>
+</g>
+</g>
+<defs>
+<filter id="filter0_d" x="-8.39411" y="15.8291" width="116.727" height="92.2456" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/>
+<feOffset/>
+<feGaussianBlur stdDeviation="4.16667"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
+<feBlend mode="overlay" in2="BackgroundImageFix" result="effect1_dropShadow"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/>
+</filter>
+<filter id="filter1_d" x="60.4167" y="-8.07558" width="47.9167" height="116.151" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/>
+<feOffset/>
+<feGaussianBlur stdDeviation="4.16667"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
+<feBlend mode="overlay" in2="BackgroundImageFix" result="effect1_dropShadow"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/>
+</filter>
+<linearGradient id="paint0_linear" x1="49.9392" y1="0.257812" x2="49.9392" y2="99.7423" gradientUnits="userSpaceOnUse">
+<stop stop-color="white"/>
+<stop offset="1" stop-color="white" stop-opacity="0"/>
+</linearGradient>
+</defs>
+</svg>
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts
new file mode 100644
index 000000000000..a44ef102af28
--- /dev/null
+++ b/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts
@@ -0,0 +1,38 @@
+import { connect, kea, path, selectors } from 'kea'
+
+import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
+
+import { sceneLogic } from '~/scenes/sceneLogic'
+
+import type { mcpAnalyticsSceneLogicType } from './mcpAnalyticsSceneLogicType'
+
+export type MCPAnalyticsTab = 'dashboard' | 'sessions' | 'tool-quality' | 'intent-clustering'
+
+export const TAB_DESCRIPTIONS: Record<MCPAnalyticsTab, string> = {
+ dashboard: 'Overview of your MCP usage.',
+ sessions: 'Sessions where users interacted with your MCP tools.',
+ 'tool-quality': 'Understand how reliably your MCP tools support user workflows.',
+ 'intent-clustering':
+ 'Cluster semantically similar user intents and see which tools each cluster routes to. Highlights inconsistent routing.',
+}
+
+const SCENE_KEY_TO_TAB: Record<string, MCPAnalyticsTab> = {
+ mcpAnalyticsDashboard: 'dashboard',
+ mcpAnalyticsSessions: 'sessions',
+ mcpAnalyticsToolQuality: 'tool-quality',
+ mcpAnalyticsIntentClustering: 'intent-clustering',
+}
+
+export const mcpAnalyticsSceneLogic = kea<mcpAnalyticsSceneLogicType>([
+ path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsSceneLogic']),
+ tabAwareScene(),
+ connect(() => ({
+ values: [sceneLogic, ['sceneKey']],
+ })),
+ selectors({
+ activeTab: [
+ (s) => [s.sceneKey],
+ (sceneKey: string): MCPAnalyticsTab => SCENE_KEY_TO_TAB[sceneKey] ?? 'dashboard',
+ ],
+ }),
+])
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
new file mode 100644
index 000000000000..c8ea5c67f135
--- /dev/null
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
@@ -0,0 +1,445 @@
+import { afterMount, kea, key, path, props, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+
+import { DataTableNode, HogQLQueryResponse, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
+import { BaseMathType, ChartDisplayType, PropertyFilterType, PropertyMathType } from '~/types'
+
+import type { mcpAnalyticsToolDetailLogicType } from './mcpAnalyticsToolDetailLogicType'
+
+export interface ToolSummary {
+ calls: number
+ errors: number
+ p50_ms: number | null
+ p95_ms: number | null
+ users: number
+ conversations: number
+ calls_prev: number
+ errors_prev: number
+}
+
+export interface DescriptionRevision {
+ description: string
+ last_seen: string
+}
+
+export interface IntentCoverage {
+ with_intent: number
+ total: number
+}
+
+export interface MCPAnalyticsToolDetailLogicProps {
+ toolName: string
+}
+
+const NEW_SDK_SOURCE = 'posthog_mcp_analytics'
+
+const DATE_FROM_CURRENT = '-7d'
+
+// HogQL expression that resolves to the *effective* tool name for new-SDK events:
+// the inner tool when the call went through the single-exec wrapper, otherwise
+// the directly-registered tool name. Use anywhere we need to filter/group by tool.
+const EFFECTIVE_TOOL_HOGQL =
+ "coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name))"
+
+const NEW_SDK_FILTER = `properties.$mcp_source = '${NEW_SDK_SOURCE}'`
+
+function escapeHogQLString(value: string): string {
+ return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
+}
+
+export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>([
+ path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsToolDetailLogic']),
+ key((props: MCPAnalyticsToolDetailLogicProps) => props.toolName),
+ props({} as MCPAnalyticsToolDetailLogicProps),
+
+ loaders(({ props }) => ({
+ summary: [
+ null as ToolSummary | null,
+ {
+ loadSummary: async (): Promise<ToolSummary | null> => {
+ const toolFilter = `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(props.toolName)}' AND ${NEW_SDK_FILTER}`
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: `
+SELECT
+ countIf(timestamp >= now() - INTERVAL 7 DAY) AS calls,
+ countIf(timestamp >= now() - INTERVAL 7 DAY AND toBool(properties.$mcp_is_error)) AS errors,
+ round(quantileIf(0.5)(toFloat(properties.$mcp_duration_ms), timestamp >= now() - INTERVAL 7 DAY)) AS p50_ms,
+ round(quantileIf(0.95)(toFloat(properties.$mcp_duration_ms), timestamp >= now() - INTERVAL 7 DAY)) AS p95_ms,
+ uniqIf(distinct_id, timestamp >= now() - INTERVAL 7 DAY) AS users,
+ uniqIf(coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)), timestamp >= now() - INTERVAL 7 DAY) AS conversations,
+ countIf(timestamp >= now() - INTERVAL 14 DAY AND timestamp < now() - INTERVAL 7 DAY) AS calls_prev,
+ countIf(timestamp >= now() - INTERVAL 14 DAY AND timestamp < now() - INTERVAL 7 DAY AND toBool(properties.$mcp_is_error)) AS errors_prev
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL 14 DAY
+ AND ${toolFilter}
+`,
+ })) as HogQLQueryResponse
+ const row = (response.results ?? [])[0]
+ if (!row) {
+ return null
+ }
+ return {
+ calls: Number(row[0]) || 0,
+ errors: Number(row[1]) || 0,
+ p50_ms: row[2] == null ? null : Number(row[2]),
+ p95_ms: row[3] == null ? null : Number(row[3]),
+ users: Number(row[4]) || 0,
+ conversations: Number(row[5]) || 0,
+ calls_prev: Number(row[6]) || 0,
+ errors_prev: Number(row[7]) || 0,
+ }
+ },
+ },
+ ],
+ descriptions: [
+ [] as DescriptionRevision[],
+ {
+ loadDescriptions: async (): Promise<DescriptionRevision[]> => {
+ const toolFilter = `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(props.toolName)}' AND ${NEW_SDK_FILTER}`
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: `
+SELECT
+ toString(properties.$mcp_tool_description) AS description,
+ toString(max(timestamp)) AS last_seen
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL 30 DAY
+ AND ${toolFilter}
+ AND notEmpty(toString(properties.$mcp_tool_description))
+GROUP BY description
+ORDER BY last_seen DESC
+LIMIT 5
+`,
+ })) as HogQLQueryResponse
+ return (response.results ?? []).map((row) => ({
+ description: String(row[0] ?? ''),
+ last_seen: String(row[1] ?? ''),
+ }))
+ },
+ },
+ ],
+ intentCoverage: [
+ null as IntentCoverage | null,
+ {
+ loadIntentCoverage: async (): Promise<IntentCoverage | null> => {
+ const toolFilter = `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(props.toolName)}' AND ${NEW_SDK_FILTER}`
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: `
+SELECT
+ countIf(notEmpty(toString(properties.$mcp_intent)) AND toString(properties.$mcp_intent) != '{}') AS with_intent,
+ count() AS total
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL 7 DAY
+ AND ${toolFilter}
+`,
+ })) as HogQLQueryResponse
+ const row = (response.results ?? [])[0]
+ if (!row) {
+ return null
+ }
+ return { with_intent: Number(row[0]) || 0, total: Number(row[1]) || 0 }
+ },
+ },
+ ],
+ })),
+
+ selectors({
+ toolName: [() => [(_, props) => props.toolName], (toolName: string) => toolName],
+
+ toolFilterClause: [
+ (s) => [s.toolName],
+ (toolName: string) => `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}' AND ${NEW_SDK_FILTER}`,
+ ],
+
+ callsTrendQuery: [
+ (s) => [s.toolName],
+ (toolName: string): InsightVizNode => ({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: 'mcp_tool_call',
+ name: 'Calls',
+ math: BaseMathType.TotalCount,
+ properties: [
+ {
+ type: PropertyFilterType.HogQL,
+ key: `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}'`,
+ },
+ {
+ type: PropertyFilterType.HogQL,
+ key: NEW_SDK_FILTER,
+ },
+ ],
+ },
+ ],
+ breakdownFilter: {
+ breakdown_type: 'event',
+ breakdown: '$mcp_is_error',
+ },
+ trendsFilter: {
+ display: ChartDisplayType.ActionsLineGraph,
+ },
+ dateRange: { date_from: DATE_FROM_CURRENT, date_to: null },
+ },
+ }),
+ ],
+
+ latencyTrendQuery: [
+ (s) => [s.toolName],
+ (toolName: string): InsightVizNode => ({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: 'mcp_tool_call',
+ name: 'p95 duration (ms)',
+ math: PropertyMathType.P95,
+ math_property: '$mcp_duration_ms',
+ properties: [
+ {
+ type: PropertyFilterType.HogQL,
+ key: `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}'`,
+ },
+ { type: PropertyFilterType.HogQL, key: NEW_SDK_FILTER },
+ ],
+ },
+ {
+ kind: NodeKind.EventsNode,
+ event: 'mcp_tool_call',
+ name: 'p50 duration (ms)',
+ math: PropertyMathType.Median,
+ math_property: '$mcp_duration_ms',
+ properties: [
+ {
+ type: PropertyFilterType.HogQL,
+ key: `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}'`,
+ },
+ { type: PropertyFilterType.HogQL, key: NEW_SDK_FILTER },
+ ],
+ },
+ ],
+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph },
+ dateRange: { date_from: DATE_FROM_CURRENT, date_to: null },
+ },
+ }),
+ ],
+
+ failuresQuery: [
+ (s) => [s.toolName],
+ (toolName: string): DataTableNode => ({
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: `
+SELECT
+ substring(toString(properties.$exception_message), 1, 200) AS message,
+ count() AS occurrences,
+ max(timestamp) AS last_seen,
+ arrayStringConcat(arraySort(arrayDistinct(groupArray(toString(properties.$mcp_client_name)))), ', ') AS harnesses
+FROM events
+WHERE event = '$exception'
+ AND timestamp >= now() - INTERVAL 7 DAY
+ AND toString(properties.$mcp_tool_name) = '${escapeHogQLString(toolName)}'
+ AND notEmpty(toString(properties.$exception_message))
+GROUP BY message
+ORDER BY occurrences DESC
+LIMIT 20
+`,
+ },
+ columns: ['message', 'occurrences', 'last_seen', 'harnesses'],
+ showSearch: false,
+ showOpenEditorButton: true,
+ }),
+ ],
+
+ sampleIntentsQuery: [
+ (s) => [s.toolFilterClause],
+ (toolFilter): DataTableNode => ({
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: `
+SELECT
+ timestamp,
+ toString(properties.$mcp_intent) AS intent,
+ toString(properties.$mcp_intent_source) AS source,
+ toString(properties.$mcp_client_name) AS harness
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL 7 DAY
+ AND ${toolFilter}
+ AND notEmpty(toString(properties.$mcp_intent))
+ AND toString(properties.$mcp_intent) != '{}'
+ORDER BY timestamp DESC
+LIMIT 5
+`,
+ },
+ columns: ['timestamp', 'intent', 'source', 'harness'],
+ showSearch: false,
+ showOpenEditorButton: true,
+ }),
+ ],
+
+ neighborsBeforeQuery: [
+ (s) => [s.toolName],
+ (toolName: string): DataTableNode => ({
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: `
+WITH tool_calls AS (
+ SELECT
+ coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)) AS conv_id,
+ timestamp,
+ ${EFFECTIVE_TOOL_HOGQL} AS tool
+ FROM events
+ WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL 7 DAY
+ AND ${NEW_SDK_FILTER}
+ AND notEmpty(coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)))
+)
+SELECT
+ prev_tool AS tool,
+ count() AS co_occurrences
+FROM (
+ SELECT
+ conv_id,
+ tool,
+ lagInFrame(tool) OVER (PARTITION BY conv_id ORDER BY timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS prev_tool
+ FROM tool_calls
+)
+WHERE tool = '${escapeHogQLString(toolName)}'
+ AND prev_tool IS NOT NULL
+ AND prev_tool != ''
+ AND prev_tool != tool
+GROUP BY prev_tool
+ORDER BY co_occurrences DESC
+LIMIT 5
+`,
+ },
+ columns: ['tool', 'co_occurrences'],
+ showSearch: false,
+ showOpenEditorButton: true,
+ }),
+ ],
+
+ neighborsAfterQuery: [
+ (s) => [s.toolName],
+ (toolName: string): DataTableNode => ({
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: `
+WITH tool_calls AS (
+ SELECT
+ coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)) AS conv_id,
+ timestamp,
+ ${EFFECTIVE_TOOL_HOGQL} AS tool
+ FROM events
+ WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL 7 DAY
+ AND ${NEW_SDK_FILTER}
+ AND notEmpty(coalesce(nullIf(toString(properties.$mcp_conversation_id), ''), toString(properties.$session_id)))
+)
+SELECT
+ next_tool AS tool,
+ count() AS co_occurrences
+FROM (
+ SELECT
+ conv_id,
+ tool,
+ leadInFrame(tool) OVER (PARTITION BY conv_id ORDER BY timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next_tool
+ FROM tool_calls
+)
+WHERE tool = '${escapeHogQLString(toolName)}'
+ AND next_tool IS NOT NULL
+ AND next_tool != ''
+ AND next_tool != tool
+GROUP BY next_tool
+ORDER BY co_occurrences DESC
+LIMIT 5
+`,
+ },
+ columns: ['tool', 'co_occurrences'],
+ showSearch: false,
+ showOpenEditorButton: true,
+ }),
+ ],
+
+ byHarnessQuery: [
+ (s) => [s.toolFilterClause],
+ (toolFilter): DataTableNode => ({
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: `
+SELECT
+ toString(properties.$mcp_client_name) AS harness,
+ count() AS calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,
+ uniq(distinct_id) AS users
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL 7 DAY
+ AND ${toolFilter}
+ AND notEmpty(toString(properties.$mcp_client_name))
+GROUP BY harness
+ORDER BY calls DESC
+LIMIT 10
+`,
+ },
+ columns: ['harness', 'calls', 'errors', 'error_rate_pct', 'users'],
+ showSearch: false,
+ showOpenEditorButton: true,
+ }),
+ ],
+
+ topUsersQuery: [
+ (s) => [s.toolFilterClause],
+ (toolFilter): DataTableNode => ({
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: `
+SELECT
+ argMax(tuple(distinct_id, person.created_at, person.properties), timestamp) AS person,
+ count() AS calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,
+ arrayStringConcat(arraySort(arrayDistinct(groupArray(toString(properties.$mcp_client_name)))), ', ') AS harnesses,
+ max(timestamp) AS last_seen
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL 7 DAY
+ AND ${toolFilter}
+GROUP BY distinct_id
+ORDER BY calls DESC
+LIMIT 10
+`,
+ },
+ columns: ['person', 'calls', 'errors', 'error_rate_pct', 'harnesses', 'last_seen'],
+ showSearch: false,
+ showOpenEditorButton: true,
+ }),
+ ],
+ }),
+
+ afterMount(({ actions }) => {
+ actions.loadSummary()
+ actions.loadDescriptions()
+ actions.loadIntentCoverage()
+ }),
+])
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
new file mode 100644
index 000000000000..de6b992fd001
--- /dev/null
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
@@ -0,0 +1,187 @@
+import { actions, kea, path, reducers, selectors } from 'kea'
+
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { DataTableNode, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
+import { BaseMathType, ChartDisplayType, PropertyMathType } from '~/types'
+
+import toolQualityQueryTemplate from '../backend/templates/tool_quality.sql?raw'
+import type { mcpAnalyticsToolQualityLogicType } from './mcpAnalyticsToolQualityLogicType'
+
+export type SortDirection = 'ASC' | 'DESC'
+
+export interface SortState {
+ column: string
+ direction: SortDirection
+}
+
+export interface DateFilter {
+ dateFrom: string | null
+ dateTo: string | null
+}
+
+const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-7d', dateTo: null }
+const DEFAULT_SORT: SortState = { column: 'total_calls', direction: 'DESC' }
+
+export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType>([
+ path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsToolQualityLogic']),
+
+ actions({
+ setToolQualitySort: (column: string, direction: SortDirection) => ({ column, direction }),
+ setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ }),
+
+ reducers({
+ toolQualitySort: [
+ DEFAULT_SORT,
+ {
+ setToolQualitySort: (_, { column, direction }): SortState => ({ column, direction }),
+ },
+ ],
+ dateFilter: [
+ DEFAULT_DATE_FILTER,
+ {
+ setDateFilter: (_, { dateFrom, dateTo }): DateFilter => ({ dateFrom, dateTo }),
+ },
+ ],
+ }),
+
+ selectors({
+ toolQualityQuery: [
+ (s) => [s.dateFilter, s.toolQualitySort],
+ (dateFilter: DateFilter, sort: SortState): DataTableNode => {
+ const query = toolQualityQueryTemplate
+ .replace('__ORDER_BY__', sort.column)
+ .replace('__ORDER_DIRECTION__', sort.direction)
+
+ return {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query,
+ filters: {
+ dateRange: {
+ date_from: dateFilter.dateFrom,
+ date_to: dateFilter.dateTo,
+ },
+ },
+ },
+ columns: [
+ 'tool',
+ 'total_calls',
+ 'error_rate_pct',
+ 'p95_duration_ms',
+ 'p50_duration_ms',
+ 'users',
+ 'sessions',
+ 'last_seen',
+ ],
+ showDateRange: true,
+ showReload: true,
+ showSearch: true,
+ showPropertyFilter: [
+ TaxonomicFilterGroupType.EventProperties,
+ TaxonomicFilterGroupType.PersonProperties,
+ TaxonomicFilterGroupType.HogQLExpression,
+ ],
+ showExport: true,
+ showColumnConfigurator: true,
+ allowSorting: true,
+ }
+ },
+ ],
+ topToolsQuery: [
+ (s) => [s.dateFilter],
+ (dateFilter: DateFilter): InsightVizNode => ({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: 'mcp_tool_call',
+ name: 'mcp_tool_call',
+ math: BaseMathType.TotalCount,
+ },
+ ],
+ breakdownFilter: {
+ breakdown_type: 'event',
+ breakdown: '$mcp_tool_name',
+ breakdown_limit: 10,
+ },
+ trendsFilter: {
+ display: ChartDisplayType.ActionsPie,
+ showLegend: false,
+ showValuesOnSeries: true,
+ showPercentStackView: true,
+ },
+ dateRange: {
+ date_from: dateFilter.dateFrom,
+ date_to: dateFilter.dateTo,
+ },
+ },
+ vizSpecificOptions: { ActionsPie: { hideAggregation: true } },
+ }),
+ ],
+ errorTrendQuery: [
+ (s) => [s.dateFilter],
+ (dateFilter: DateFilter): InsightVizNode => ({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: 'mcp_tool_call',
+ name: 'mcp_tool_call',
+ math: BaseMathType.TotalCount,
+ },
+ ],
+ breakdownFilter: {
+ breakdown_type: 'event',
+ breakdown: '$mcp_is_error',
+ },
+ trendsFilter: {
+ display: ChartDisplayType.ActionsLineGraph,
+ },
+ dateRange: {
+ date_from: dateFilter.dateFrom,
+ date_to: dateFilter.dateTo,
+ },
+ },
+ }),
+ ],
+ durationTrendQuery: [
+ (s) => [s.dateFilter],
+ (dateFilter: DateFilter): InsightVizNode => ({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: 'mcp_tool_call',
+ name: 'p95 duration (ms)',
+ math: PropertyMathType.P95,
+ math_property: '$mcp_duration_ms',
+ },
+ {
+ kind: NodeKind.EventsNode,
+ event: 'mcp_tool_call',
+ name: 'p50 duration (ms)',
+ math: PropertyMathType.Median,
+ math_property: '$mcp_duration_ms',
+ },
+ ],
+ trendsFilter: {
+ display: ChartDisplayType.ActionsLineGraph,
+ },
+ dateRange: {
+ date_from: dateFilter.dateFrom,
+ date_to: dateFilter.dateTo,
+ },
+ },
+ }),
+ ],
+ }),
+])
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
new file mode 100644
index 000000000000..6bc234118837
--- /dev/null
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
@@ -0,0 +1,455 @@
+import { afterMount, connect, kea, path, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { hogqlQuery } from '~/queries/query'
+import { hogql } from '~/queries/utils'
+
+import { mcpClusteringLogic } from './clustering/mcpClusteringLogic'
+import type { MCPIntentClusterApi } from './generated/api.schemas'
+import type { mcpDashboardOverviewLogicType } from './mcpDashboardOverviewLogicType'
+
+const LOOKBACK_DAYS = 7
+
+const KPI_QUERY = hogql`
+SELECT
+ toDate(timestamp) AS bucket,
+ countDistinctIf(toString(properties.$session_id), toString(properties.$session_id) != '') AS sessions,
+ count() AS tool_calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95,
+ timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS))} DAY AS in_current
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS * 2))} DAY
+ AND properties.$mcp_tool_name IS NOT NULL
+ AND properties.$mcp_tool_name != ''
+GROUP BY bucket, in_current
+ORDER BY bucket
+`
+
+// Per-session rollup powering the Notable sessions block. The selector
+// applies fixed rules over this set; no per-rule SQL.
+const SESSION_ROWS_QUERY = hogql`
+SELECT
+ toString(properties.$session_id) AS session_id,
+ count() AS tool_calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,
+ dateDiff('second', min(timestamp), max(timestamp)) AS duration_seconds,
+ uniq(toString(properties.$mcp_tool_name)) AS distinct_tools,
+ max(timestamp) AS last_seen
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS))} DAY
+ AND properties.$session_id IS NOT NULL
+ AND properties.$session_id != ''
+ AND properties.$mcp_tool_name IS NOT NULL
+ AND properties.$mcp_tool_name != ''
+GROUP BY session_id
+HAVING tool_calls >= 1
+ORDER BY tool_calls DESC
+LIMIT 500
+`
+
+// Mirrors products/mcp_analytics/backend/templates/tool_quality.sql for the
+// compact reliability matrix on the overview. Limited columns + 50 rows.
+const TOOL_ROWS_QUERY = hogql`
+SELECT
+ toString(properties.$mcp_tool_name) AS tool,
+ count() AS total_calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,
+ round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_duration_ms
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS))} DAY
+ AND properties.$mcp_tool_name IS NOT NULL
+ AND properties.$mcp_tool_name != ''
+GROUP BY tool
+ORDER BY total_calls DESC
+LIMIT 50
+`
+
+const HARNESS_ROWS_QUERY = hogql`
+SELECT
+ toString(properties.$mcp_client_name) AS client,
+ count() AS total_calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ countDistinctIf(toString(properties.$session_id), toString(properties.$session_id) != '') AS sessions
+FROM events
+WHERE event = 'mcp_tool_call'
+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS))} DAY
+ AND properties.$mcp_client_name IS NOT NULL
+ AND properties.$mcp_client_name != ''
+GROUP BY client
+`
+
+interface BucketRow {
+ bucket: string
+ sessions: number
+ tool_calls: number
+ errors: number
+ p95: number
+ in_current: boolean
+}
+
+export interface KPIMetric {
+ value: number
+ previousValue: number
+ deltaPct: number | null
+ sparkline: number[]
+ goodDirection: 'up' | 'down'
+}
+
+export interface KPIData {
+ sessions: KPIMetric
+ toolCalls: KPIMetric
+ errorRatePct: KPIMetric
+ p95LatencyMs: KPIMetric
+}
+
+export interface ToolRow {
+ tool: string
+ total_calls: number
+ errors: number
+ error_rate_pct: number
+ p95_duration_ms: number
+}
+
+export interface HarnessRawRow {
+ client: string
+ total_calls: number
+ errors: number
+ sessions: number
+}
+
+export interface HarnessRow {
+ category: string
+ total_calls: number
+ errors: number
+ error_rate_pct: number
+ sessions: number
+ raw_clients: string[]
+}
+
+export interface SessionRow {
+ session_id: string
+ tool_calls: number
+ errors: number
+ error_rate_pct: number
+ duration_seconds: number
+ distinct_tools: number
+ last_seen: string
+}
+
+export type NotableRule = 'worst_error_rate' | 'all_fail' | 'most_exploratory' | 'exemplar'
+
+export interface NotableSession {
+ rule: NotableRule
+ label: string
+ session: SessionRow
+}
+
+const EMPTY_METRIC: KPIMetric = { value: 0, previousValue: 0, deltaPct: null, sparkline: [], goodDirection: 'up' }
+const EMPTY_KPIS: KPIData = {
+ sessions: { ...EMPTY_METRIC, goodDirection: 'up' },
+ toolCalls: { ...EMPTY_METRIC, goodDirection: 'up' },
+ errorRatePct: { ...EMPTY_METRIC, goodDirection: 'down' },
+ p95LatencyMs: { ...EMPTY_METRIC, goodDirection: 'down' },
+}
+
+// Harness categories derived from sampling the top 50 distinct $mcp_client_name
+// values seen in production over the past 30 days. We normalize the
+// "(via mcp-remote …)" suffix that mcp-remote injects so the underlying client
+// folds into its real harness bucket.
+const HARNESS_CATEGORIES: { category: string; match: (name: string) => boolean }[] = [
+ { category: 'Claude Code', match: (n) => n.startsWith('claude-code') },
+ {
+ category: 'Claude.ai',
+ match: (n) => n === 'claude-ai' || n === 'anthropic/claudeai',
+ },
+ { category: 'Anthropic API', match: (n) => n === 'anthropic/api' },
+ {
+ category: 'OpenAI Codex',
+ match: (n) => n.startsWith('codex') || n.startsWith('openai-mcp'),
+ },
+ { category: 'Cursor', match: (n) => n.startsWith('cursor') },
+ { category: 'VS Code', match: (n) => n.startsWith('visual studio code') },
+ { category: 'Windsurf', match: (n) => n === 'windsurf' },
+ { category: 'Replit', match: (n) => n.startsWith('replit') },
+ { category: 'Lovable', match: (n) => n.startsWith('lovable') },
+ { category: 'Manus', match: (n) => n === 'manus' },
+ { category: 'CodeRabbit', match: (n) => n === 'coderabbit' },
+ { category: 'Notion', match: (n) => n.startsWith('notion') },
+ { category: 'Poke', match: (n) => n === 'poke' },
+ { category: 'opencode', match: (n) => n === 'opencode' },
+ { category: 'Kiro', match: (n) => n.startsWith('kiro') },
+ { category: 'Desktop Commander', match: (n) => n.startsWith('desktop-commander') },
+]
+
+export function categorizeHarness(raw: string): string {
+ const stripped = raw
+ .replace(/\s*\(via mcp-remote[^)]*\)\s*/i, '')
+ .trim()
+ .toLowerCase()
+ if (!stripped) {
+ return 'Other'
+ }
+ for (const entry of HARNESS_CATEGORIES) {
+ if (entry.match(stripped)) {
+ return entry.category
+ }
+ }
+ return 'Other'
+}
+
+function aggregateHarnessRows(raw: HarnessRawRow[]): HarnessRow[] {
+ const byCategory = new Map<string, HarnessRow>()
+ for (const row of raw) {
+ const category = categorizeHarness(row.client)
+ const existing = byCategory.get(category)
+ if (existing) {
+ existing.total_calls += row.total_calls
+ existing.errors += row.errors
+ existing.sessions += row.sessions
+ existing.raw_clients.push(row.client)
+ } else {
+ byCategory.set(category, {
+ category,
+ total_calls: row.total_calls,
+ errors: row.errors,
+ error_rate_pct: 0,
+ sessions: row.sessions,
+ raw_clients: [row.client],
+ })
+ }
+ }
+ const result = [...byCategory.values()]
+ for (const r of result) {
+ r.error_rate_pct = r.total_calls ? Math.round((r.errors / r.total_calls) * 1000) / 10 : 0
+ }
+ result.sort((a, b) => b.total_calls - a.total_calls)
+ return result
+}
+
+function deltaPct(current: number, previous: number): number | null {
+ if (previous === 0) {
+ return current === 0 ? 0 : null
+ }
+ return ((current - previous) / previous) * 100
+}
+
+function parseRows(rawRows: unknown[][]): BucketRow[] {
+ return rawRows.map((r) => ({
+ bucket: String(r[0]),
+ sessions: Number(r[1] ?? 0),
+ tool_calls: Number(r[2] ?? 0),
+ errors: Number(r[3] ?? 0),
+ p95: Number(r[4] ?? 0),
+ in_current: Boolean(r[5]),
+ }))
+}
+
+function buildKPIs(rows: BucketRow[]): KPIData {
+ const current = rows.filter((r) => r.in_current).sort((a, b) => a.bucket.localeCompare(b.bucket))
+ const previous = rows.filter((r) => !r.in_current)
+
+ const curSessions = current.reduce((acc, r) => acc + r.sessions, 0)
+ const curCalls = current.reduce((acc, r) => acc + r.tool_calls, 0)
+ const curErrors = current.reduce((acc, r) => acc + r.errors, 0)
+ const curP95 = current.length ? Math.max(...current.map((r) => r.p95)) : 0
+
+ const prevSessions = previous.reduce((acc, r) => acc + r.sessions, 0)
+ const prevCalls = previous.reduce((acc, r) => acc + r.tool_calls, 0)
+ const prevErrors = previous.reduce((acc, r) => acc + r.errors, 0)
+ const prevP95 = previous.length ? Math.max(...previous.map((r) => r.p95)) : 0
+
+ const curErrorRate = curCalls ? (curErrors / curCalls) * 100 : 0
+ const prevErrorRate = prevCalls ? (prevErrors / prevCalls) * 100 : 0
+
+ return {
+ sessions: {
+ value: curSessions,
+ previousValue: prevSessions,
+ deltaPct: deltaPct(curSessions, prevSessions),
+ sparkline: current.map((r) => r.sessions),
+ goodDirection: 'up',
+ },
+ toolCalls: {
+ value: curCalls,
+ previousValue: prevCalls,
+ deltaPct: deltaPct(curCalls, prevCalls),
+ sparkline: current.map((r) => r.tool_calls),
+ goodDirection: 'up',
+ },
+ errorRatePct: {
+ value: curErrorRate,
+ previousValue: prevErrorRate,
+ deltaPct: deltaPct(curErrorRate, prevErrorRate),
+ sparkline: current.map((r) => (r.tool_calls ? (r.errors / r.tool_calls) * 100 : 0)),
+ goodDirection: 'down',
+ },
+ p95LatencyMs: {
+ value: curP95,
+ previousValue: prevP95,
+ deltaPct: deltaPct(curP95, prevP95),
+ sparkline: current.map((r) => r.p95),
+ goodDirection: 'down',
+ },
+ }
+}
+
+export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([
+ path(['products', 'mcp_analytics', 'frontend', 'mcpDashboardOverviewLogic']),
+ connect(() => ({
+ values: [mcpClusteringLogic, ['clusters', 'hasSnapshot']],
+ })),
+ loaders({
+ kpis: [
+ EMPTY_KPIS,
+ {
+ loadKPIs: async () => {
+ const response = await hogqlQuery(KPI_QUERY)
+ const rows = parseRows((response?.results as unknown[][]) ?? [])
+ return buildKPIs(rows)
+ },
+ },
+ ],
+ toolRows: [
+ [] as ToolRow[],
+ {
+ loadToolRows: async () => {
+ const response = await hogqlQuery(TOOL_ROWS_QUERY)
+ const raw = (response?.results as unknown[][]) ?? []
+ return raw.map((r) => ({
+ tool: String(r[0] ?? ''),
+ total_calls: Number(r[1] ?? 0),
+ errors: Number(r[2] ?? 0),
+ error_rate_pct: Number(r[3] ?? 0),
+ p95_duration_ms: Number(r[4] ?? 0),
+ }))
+ },
+ },
+ ],
+ sessionRows: [
+ [] as SessionRow[],
+ {
+ loadSessionRows: async () => {
+ const response = await hogqlQuery(SESSION_ROWS_QUERY)
+ const raw = (response?.results as unknown[][]) ?? []
+ return raw.map((r) => ({
+ session_id: String(r[0] ?? ''),
+ tool_calls: Number(r[1] ?? 0),
+ errors: Number(r[2] ?? 0),
+ error_rate_pct: Number(r[3] ?? 0),
+ duration_seconds: Number(r[4] ?? 0),
+ distinct_tools: Number(r[5] ?? 0),
+ last_seen: String(r[6] ?? ''),
+ }))
+ },
+ },
+ ],
+ harnessRawRows: [
+ [] as HarnessRawRow[],
+ {
+ loadHarnessRows: async () => {
+ const response = await hogqlQuery(HARNESS_ROWS_QUERY)
+ const raw = (response?.results as unknown[][]) ?? []
+ return raw.map((r) => ({
+ client: String(r[0] ?? ''),
+ total_calls: Number(r[1] ?? 0),
+ errors: Number(r[2] ?? 0),
+ sessions: Number(r[3] ?? 0),
+ }))
+ },
+ },
+ ],
+ }),
+ selectors({
+ topToolRows: [(s) => [s.toolRows], (toolRows: ToolRow[]): ToolRow[] => toolRows.slice(0, 5)],
+ toolRowsTotal: [(s) => [s.toolRows], (toolRows: ToolRow[]): number => toolRows.length],
+ harnessRows: [(s) => [s.harnessRawRows], (raw: HarnessRawRow[]): HarnessRow[] => aggregateHarnessRows(raw)],
+ notableSessions: [
+ (s) => [s.sessionRows],
+ (sessionRows: SessionRow[]): NotableSession[] => pickNotableSessions(sessionRows),
+ ],
+ intentClusterCount: [
+ (s) => [s.clusters],
+ (clusters: readonly MCPIntentClusterApi[]): KPIMetric => ({
+ value: clusters.length,
+ previousValue: 0,
+ deltaPct: null,
+ sparkline: [],
+ goodDirection: 'up',
+ }),
+ ],
+ }),
+ afterMount(({ actions }) => {
+ actions.loadKPIs()
+ actions.loadToolRows()
+ actions.loadSessionRows()
+ actions.loadHarnessRows()
+ }),
+])
+
+function median(values: number[]): number {
+ if (values.length === 0) {
+ return 0
+ }
+ const sorted = [...values].sort((a, b) => a - b)
+ const mid = Math.floor(sorted.length / 2)
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
+}
+
+// Pick at most one session per rule. Thresholds relax automatically when the
+// data is small so something demo-worthy always shows.
+function pickNotableSessions(rows: SessionRow[]): NotableSession[] {
+ if (rows.length === 0) {
+ return []
+ }
+
+ const medianCalls = median(rows.map((r) => r.tool_calls))
+ const medianDuration = median(rows.map((r) => r.duration_seconds))
+ const used = new Set<string>()
+ const picked: NotableSession[] = []
+
+ const take = (rule: NotableRule, label: string, candidate: SessionRow | undefined): void => {
+ if (!candidate || used.has(candidate.session_id)) {
+ return
+ }
+ used.add(candidate.session_id)
+ picked.push({ rule, label, session: candidate })
+ }
+
+ // 1. Worst error rate at high volume — top err% among above-median-volume sessions
+ const highVolume = rows.filter((r) => r.tool_calls >= Math.max(medianCalls, 3) && r.error_rate_pct > 0)
+ take(
+ 'worst_error_rate',
+ 'Worst error rate at high volume',
+ [...highVolume].sort((a, b) => b.error_rate_pct - a.error_rate_pct || b.tool_calls - a.tool_calls)[0]
+ )
+
+ // 2. All-fail session — error_rate_pct === 100 AND tool_calls >= 3
+ const allFail = rows.filter((r) => r.error_rate_pct >= 100 && r.tool_calls >= 3)
+ take(
+ 'all_fail',
+ 'Every call failed — likely auth scope',
+ [...allFail].sort((a, b) => b.tool_calls - a.tool_calls)[0]
+ )
+
+ // 3. Most exploratory — highest distinct_tools count (multi-step journey)
+ take(
+ 'most_exploratory',
+ 'Most exploratory journey',
+ [...rows].sort((a, b) => b.distinct_tools - a.distinct_tools || b.tool_calls - a.tool_calls)[0]
+ )
+
+ // 4. Exemplar — zero errors, above-median calls, faster than median duration
+ const exemplars = rows.filter(
+ (r) =>
+ r.error_rate_pct === 0 && r.tool_calls >= Math.max(medianCalls, 3) && r.duration_seconds <= medianDuration
+ )
+ take('exemplar', 'Exemplar — concise success', [...exemplars].sort((a, b) => b.tool_calls - a.tool_calls)[0])
+
+ return picked
+}
diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx
new file mode 100644
index 000000000000..bc7c0a7c53c4
--- /dev/null
+++ b/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx
@@ -0,0 +1,176 @@
+import { useValues } from 'kea'
+
+import { IconBolt, IconClock, IconSparkles, IconUser, IconWarning } from '@posthog/icons'
+import { LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
+
+import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
+
+import { mcpSessionsLogic } from './mcpSessionsLogic'
+import { formatDuration, formatRelativeOffset, sessionDurationMs, shortenSessionId } from './utils'
+
+function MetaBadge({ icon, label }: { icon: React.ReactNode; label: React.ReactNode }): JSX.Element {
+ return (
+ <span className="inline-flex items-center gap-1 rounded-full bg-surface-secondary px-2 py-0.5 text-[11px] text-secondary">
+ <span className="text-[11px] leading-none">{icon}</span>
+ {label}
+ </span>
+ )
+}
+
+export function MCPSessionDetail(): JSX.Element {
+ const { selectedSession, toolCalls, toolCallsLoading } = useValues(mcpSessionsLogic)
+
+ if (!selectedSession) {
+ return (
+ <div className="flex h-full items-center justify-center text-sm text-secondary p-6 text-center">
+ Pick a session on the left to step through its tool calls.
+ </div>
+ )
+ }
+
+ const durationMs = sessionDurationMs(selectedSession.session_start, selectedSession.session_end)
+ const calls = selectedSession.tool_calls
+ const identifiedPerson = !!(selectedSession.person_name || selectedSession.person_email)
+ const primaryLabel = identifiedPerson
+ ? selectedSession.person_name || selectedSession.person_email || selectedSession.distinct_id
+ : selectedSession.distinct_id || 'unknown'
+
+ return (
+ <div className="flex flex-col">
+ <header className="flex flex-col gap-2 shrink-0 border-b border-primary px-3 pt-3 pb-2">
+ <div className="flex items-center gap-2 min-w-0">
+ <div
+ className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full ${
+ identifiedPerson ? 'bg-accent/20 text-accent' : 'bg-surface-secondary text-secondary'
+ }`}
+ >
+ <IconUser className="text-2xl" />
+ </div>
+ <div className="flex flex-col min-w-0 flex-1">
+ <span
+ className={`truncate font-semibold ${
+ identifiedPerson ? 'text-default text-sm' : 'font-mono text-xs text-secondary'
+ }`}
+ >
+ {primaryLabel}
+ </span>
+ {selectedSession.distinct_id ? (
+ <CopyToClipboardInline
+ explicitValue={selectedSession.distinct_id}
+ description="distinct id"
+ iconSize="xsmall"
+ className="truncate font-mono text-[11px] text-secondary"
+ >
+ {selectedSession.distinct_id}
+ </CopyToClipboardInline>
+ ) : null}
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-1.5">
+ {selectedSession.mcp_client_name ? (
+ <MetaBadge icon={<IconSparkles />} label={selectedSession.mcp_client_name} />
+ ) : null}
+ <MetaBadge icon={<IconBolt />} label={`${calls} tool call${calls === 1 ? '' : 's'}`} />
+ <MetaBadge icon={<IconClock />} label={formatDuration(durationMs)} />
+ <span
+ className="inline-flex items-center gap-1 rounded-full bg-surface-secondary px-2 py-0.5 text-[11px] text-secondary font-mono"
+ title={selectedSession.session_id}
+ >
+ <CopyToClipboardInline
+ explicitValue={selectedSession.session_id}
+ description="session id"
+ iconSize="xsmall"
+ className="font-mono"
+ >
+ {shortenSessionId(selectedSession.session_id)}
+ </CopyToClipboardInline>
+ </span>
+ </div>
+ </header>
+
+ <section className="px-3 py-3" style={{ overflowY: 'scroll', maxHeight: 'calc(100vh - 32rem)' }}>
+ {toolCallsLoading && toolCalls.length === 0 ? (
+ <div className="flex flex-col gap-2">
+ {[0, 1, 2].map((i) => (
+ <LemonSkeleton key={i} className="h-16 w-full" />
+ ))}
+ </div>
+ ) : toolCalls.length === 0 ? (
+ <div className="text-sm text-secondary">No tool calls captured for this session.</div>
+ ) : (
+ <ol className="flex flex-col gap-2 list-none pl-0">
+ {toolCalls.map((toolCall, idx) => (
+ <li
+ key={toolCall.event_id || `${toolCall.timestamp}-${idx}`}
+ className={`relative flex flex-col gap-1 rounded border bg-surface-primary px-2 py-1.5 transition-colors hover:bg-surface-secondary ${
+ toolCall.is_error
+ ? 'border-danger border-l-2'
+ : 'border-primary border-l-2 border-l-accent/60'
+ }`}
+ >
+ <div className="flex items-center justify-between gap-2 text-xs">
+ <div className="flex items-center gap-1.5 min-w-0">
+ {toolCall.is_error ? (
+ <IconWarning className="text-danger shrink-0 text-xs" />
+ ) : (
+ <IconBolt className="text-accent shrink-0 text-xs" />
+ )}
+ <span className="font-mono font-semibold truncate">
+ {toolCall.tool_name || 'unknown'}
+ </span>
+ {toolCall.is_error ? (
+ <LemonTag type="danger" size="small">
+ error
+ </LemonTag>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-2 text-secondary whitespace-nowrap font-mono text-[11px]">
+ {toolCall.duration_ms != null ? (
+ <span>{formatDuration(toolCall.duration_ms)} ·</span>
+ ) : null}
+ <span>
+ {formatRelativeOffset(selectedSession.session_start, toolCall.timestamp)}
+ </span>
+ </div>
+ </div>
+
+ <div className="text-xs leading-snug pl-5">
+ {toolCall.intent || (
+ <span className="text-secondary italic">No intent captured.</span>
+ )}
+ </div>
+
+ {toolCall.is_error && toolCall.error_message ? (
+ <div className="text-xs text-danger font-mono pl-5 break-all">
+ {toolCall.error_message}
+ </div>
+ ) : null}
+ </li>
+ ))}
+ </ol>
+ )}
+ </section>
+
+ <hr className="shrink-0 border-t border-primary my-0" />
+
+ <footer className="shrink-0 bg-gradient-to-br from-accent/15 via-accent/5 to-surface-primary px-3 py-3">
+ <div className="flex items-center gap-2 mb-1.5">
+ <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-accent/20 text-accent">
+ <IconSparkles className="text-xs" />
+ </div>
+ <span className="text-[10px] uppercase tracking-wider font-semibold text-accent">
+ Session intent
+ </span>
+ </div>
+ <p className="text-xs leading-relaxed text-default">
+ {selectedSession.intent || (
+ <span className="text-secondary italic">
+ Summary will appear once the intent workflow runs.
+ </span>
+ )}
+ </p>
+ </footer>
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionsTable.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionsTable.tsx
new file mode 100644
index 000000000000..55cf45ef0597
--- /dev/null
+++ b/products/mcp_analytics/frontend/sessions/MCPSessionsTable.tsx
@@ -0,0 +1,121 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh } from '@posthog/icons'
+import { LemonButton, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+
+import type { MCPSessionApi } from '../generated/api.schemas'
+import { MCPSessionDetail } from './MCPSessionDetail'
+import { mcpSessionsLogic, type MCPSessionSortColumn } from './mcpSessionsLogic'
+import { formatDuration, sessionDurationMs } from './utils'
+
+export function MCPSessionsTable(): JSX.Element {
+ const { setFilters, loadSessions, selectSession, setSorting } = useActions(mcpSessionsLogic)
+ const { sessions, sessionsLoading, filters, selectedSessionId, sorting } = useValues(mcpSessionsLogic)
+
+ const columns: LemonTableColumns<MCPSessionApi> = [
+ {
+ title: 'Person',
+ key: 'distinct_id',
+ render: (_, record) => {
+ const label = record.person_name || record.person_email
+ if (label) {
+ return <span className="text-xs font-medium truncate">{label}</span>
+ }
+ if (record.distinct_id) {
+ return <span className="text-xs font-mono text-secondary truncate">{record.distinct_id}</span>
+ }
+ return <span className="text-secondary">—</span>
+ },
+ sorter: true,
+ },
+ {
+ title: 'Started',
+ key: 'session_start',
+ render: (_, record) => <TZLabel time={record.session_start} />,
+ sorter: true,
+ },
+ {
+ title: 'Tool calls',
+ key: 'tool_call_count',
+ dataIndex: 'tool_calls',
+ align: 'right',
+ render: (_, record) => <span className="text-xs whitespace-nowrap">{record.tool_calls}</span>,
+ sorter: true,
+ },
+ {
+ title: 'Duration',
+ key: 'duration_seconds',
+ align: 'right',
+ render: (_, record) => (
+ <span className="text-xs whitespace-nowrap">
+ {formatDuration(sessionDurationMs(record.session_start, record.session_end))}
+ </span>
+ ),
+ sorter: true,
+ },
+ ]
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex justify-between gap-2 flex-wrap">
+ <LemonInput
+ type="search"
+ className="w-96 !max-w-none"
+ placeholder="Search by session id, client, or tool"
+ onChange={(value) => setFilters({ search: value })}
+ value={filters.search}
+ />
+ <LemonButton
+ type="secondary"
+ icon={<IconRefresh />}
+ onClick={() => loadSessions()}
+ loading={sessionsLoading}
+ size="small"
+ >
+ Reload
+ </LemonButton>
+ </div>
+ <div className="flex flex-col gap-3 lg:flex-row lg:items-start">
+ <div className="flex-1 min-w-0">
+ <LemonTable
+ data-attr="mcp-sessions-table"
+ size="small"
+ pagination={{ pageSize: 20 }}
+ dataSource={sessions}
+ rowKey="session_id"
+ columns={columns}
+ loading={sessionsLoading}
+ sorting={sorting ? { columnKey: sorting.column, order: sorting.order } : null}
+ onSort={(newSorting) =>
+ setSorting(
+ newSorting
+ ? {
+ column: newSorting.columnKey as MCPSessionSortColumn,
+ order: newSorting.order,
+ }
+ : null
+ )
+ }
+ useURLForSorting={false}
+ emptyState="No MCP sessions yet — try the seed_mcp_sessions management command for local data."
+ nouns={['session', 'sessions']}
+ onRow={(record) => ({
+ onClick: () => selectSession(record.session_id),
+ })}
+ rowClassName={(record) =>
+ record.session_id === selectedSessionId
+ ? 'cursor-pointer bg-accent-highlight-secondary'
+ : 'cursor-pointer'
+ }
+ />
+ </div>
+ <aside className="w-full lg:w-[480px] flex flex-col rounded border border-primary bg-surface-primary overflow-hidden">
+ <MCPSessionDetail />
+ </aside>
+ </div>
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
new file mode 100644
index 000000000000..232e34805bf2
--- /dev/null
+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
@@ -0,0 +1,151 @@
+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { mcpAnalyticsSessionsList, mcpAnalyticsSessionsToolCalls } from '../generated/api'
+import type { MCPSessionApi, MCPToolCallApi } from '../generated/api.schemas'
+import type { mcpSessionsLogicType } from './mcpSessionsLogicType'
+
+export interface MCPSessionsFilters {
+ search: string
+}
+
+const DEFAULT_FILTERS: MCPSessionsFilters = {
+ search: '',
+}
+
+const SEARCH_DEBOUNCE_MS = 300
+
+// Must stay aligned with SESSION_SORT_FIELDS on the backend (logic.py).
+export type MCPSessionSortColumn =
+ | 'session_id'
+ | 'session_start'
+ | 'session_end'
+ | 'duration_seconds'
+ | 'tool_call_count'
+ | 'mcp_client_name'
+ | 'distinct_id'
+
+export interface MCPSessionSorting {
+ column: MCPSessionSortColumn
+ order: 1 | -1
+}
+
+const DEFAULT_SORTING: MCPSessionSorting = { column: 'session_end', order: -1 }
+
+export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
+ path(['products', 'mcp_analytics', 'frontend', 'sessions', 'mcpSessionsLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+ actions({
+ // Declared explicitly so kea-typegen emits a no-arg signature for the loader
+ // action below — without this, the `(_, breakpoint)` loader signature forces
+ // every call site to pass a placeholder argument.
+ loadSessions: true,
+ setFilters: (filters: Partial<MCPSessionsFilters>) => ({ filters }),
+ setSorting: (sorting: MCPSessionSorting | null) => ({ sorting }),
+ selectSession: (sessionId: string | null) => ({ sessionId }),
+ }),
+ loaders(({ values }) => ({
+ sessions: [
+ [] as MCPSessionApi[],
+ {
+ loadSessions: async (_, breakpoint) => {
+ // Debounce keystroke-driven loads. afterMount fires loadSessions with no
+ // payload, in which case we still want the initial fetch to be fast — so
+ // only honour the debounce when there is a search term.
+ if (values.filters.search) {
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ }
+ if (!values.currentProjectId) {
+ return []
+ }
+ const sorting = values.sorting
+ const orderBy = sorting ? `${sorting.order === -1 ? '-' : ''}${sorting.column}` : undefined
+ const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
+ search: values.filters.search || undefined,
+ order_by: orderBy,
+ })
+ return [...(response.results ?? [])]
+ },
+ },
+ ],
+ toolCalls: [
+ [] as MCPToolCallApi[],
+ {
+ loadToolCalls: async (sessionId: string) => {
+ if (!values.currentProjectId || !sessionId) {
+ return []
+ }
+ const response = await mcpAnalyticsSessionsToolCalls(String(values.currentProjectId), sessionId)
+ return [...(response.results ?? [])]
+ },
+ },
+ ],
+ })),
+ reducers({
+ filters: [
+ DEFAULT_FILTERS,
+ {
+ setFilters: (state, { filters }) => ({ ...state, ...filters }),
+ },
+ ],
+ selectedSessionId: [
+ null as string | null,
+ {
+ selectSession: (_, { sessionId }) => sessionId,
+ },
+ ],
+ sorting: [
+ DEFAULT_SORTING as MCPSessionSorting | null,
+ {
+ setSorting: (_, { sorting }) => sorting,
+ },
+ ],
+ }),
+ selectors({
+ selectedSession: [
+ (s) => [s.sessions, s.selectedSessionId],
+ (sessions, selectedSessionId): MCPSessionApi | null => {
+ if (!selectedSessionId) {
+ return null
+ }
+ return sessions.find((session) => session.session_id === selectedSessionId) ?? null
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ setFilters: () => {
+ actions.loadSessions()
+ },
+ setSorting: () => {
+ actions.loadSessions()
+ },
+ selectSession: ({ sessionId }) => {
+ if (sessionId) {
+ actions.loadToolCalls(sessionId)
+ }
+ },
+ loadSessionsSuccess: ({ sessions }) => {
+ // Auto-select the first session whenever results come back. If the user
+ // had a session pinned that is no longer in the filtered set, clear it.
+ if (sessions.length === 0) {
+ if (values.selectedSessionId) {
+ actions.selectSession(null)
+ }
+ return
+ }
+ const stillVisible = values.selectedSessionId
+ ? sessions.some((s) => s.session_id === values.selectedSessionId)
+ : false
+ if (!stillVisible) {
+ actions.selectSession(sessions[0].session_id)
+ }
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadSessions()
+ }),
+])
diff --git a/products/mcp_analytics/frontend/sessions/utils.ts b/products/mcp_analytics/frontend/sessions/utils.ts
new file mode 100644
index 000000000000..52c11f2bba56
--- /dev/null
+++ b/products/mcp_analytics/frontend/sessions/utils.ts
@@ -0,0 +1,54 @@
+export function shortenSessionId(sessionId: string): string {
+ if (sessionId.length <= 13) {
+ return sessionId
+ }
+ return `${sessionId.slice(0, 8)}…${sessionId.slice(-4)}`
+}
+
+export function sessionDurationMs(firstSeen: string, lastSeen: string): number {
+ const first = Date.parse(firstSeen)
+ const last = Date.parse(lastSeen)
+ if (Number.isNaN(first) || Number.isNaN(last)) {
+ return 0
+ }
+ return Math.max(0, last - first)
+}
+
+export function formatRelativeOffset(start: string, at: string): string {
+ const startMs = Date.parse(start)
+ const atMs = Date.parse(at)
+ if (Number.isNaN(startMs) || Number.isNaN(atMs)) {
+ return '—'
+ }
+ const totalSeconds = Math.max(0, Math.round((atMs - startMs) / 1000))
+ const hours = Math.floor(totalSeconds / 3600)
+ const minutes = Math.floor((totalSeconds % 3600) / 60)
+ const seconds = totalSeconds % 60
+ const mm = String(minutes).padStart(2, '0')
+ const ss = String(seconds).padStart(2, '0')
+ if (hours > 0) {
+ return `${String(hours).padStart(2, '0')}:${mm}:${ss}`
+ }
+ return `${mm}:${ss}`
+}
+
+export function formatDuration(ms: number | null | undefined): string {
+ if (ms === null || ms === undefined) {
+ return '—'
+ }
+ if (ms < 1000) {
+ return `${ms}ms`
+ }
+ const seconds = ms / 1000
+ if (seconds < 60) {
+ return `${seconds.toFixed(seconds < 10 ? 1 : 0)}s`
+ }
+ const minutes = Math.floor(seconds / 60)
+ const remainingSeconds = Math.round(seconds - minutes * 60)
+ if (minutes < 60) {
+ return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`
+ }
+ const hours = Math.floor(minutes / 60)
+ const remainingMinutes = minutes - hours * 60
+ return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`
+}
diff --git a/products/mcp_analytics/manifest.tsx b/products/mcp_analytics/manifest.tsx
index 454fc583f3a2..f7589a35fad3 100644
--- a/products/mcp_analytics/manifest.tsx
+++ b/products/mcp_analytics/manifest.tsx
@@ -3,21 +3,66 @@
*
* Defines scenes, routes, URLs, and navigation for this product.
*/
+import { FEATURE_FLAGS } from 'lib/constants'
+import { urls } from 'scenes/urls'
+
+import { FileSystemIconType, ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
+
+import { FileSystemIconColor } from '../../frontend/src/types'
import { ProductManifest } from '../../frontend/src/types'
export const manifest: ProductManifest = {
name: 'MCP analytics',
scenes: {
// Define scenes here
+ MCPAnalytics: {
+ import: () => import('./frontend/MCPAnalyticsScene'),
+ projectBased: true,
+ name: 'MCP analytics',
+ layout: 'app-container',
+ description: 'Capture user intent and behaviour patterns to understand what AI users need from your tools.',
+ iconType: 'llm_analytics',
+ },
+ MCPAnalyticsToolDetail: {
+ import: () => import('./frontend/MCPAnalyticsToolDetail'),
+ projectBased: true,
+ name: 'MCP tool',
+ layout: 'app-container',
+ iconType: 'llm_analytics',
+ },
},
routes: {
// Define routes here
+ '/mcp-analytics/dashboard': ['MCPAnalytics', 'mcpAnalyticsDashboard'],
+ '/mcp-analytics/sessions': ['MCPAnalytics', 'mcpAnalyticsSessions'],
+ '/mcp-analytics/tool-quality': ['MCPAnalytics', 'mcpAnalyticsToolQuality'],
+ '/mcp-analytics/tool-quality/:toolName': ['MCPAnalyticsToolDetail', 'mcpAnalyticsTool'],
+ '/mcp-analytics/intent-clustering': ['MCPAnalytics', 'mcpAnalyticsIntentClustering'],
},
redirects: {},
urls: {
// Define URL helpers here
+ mcpAnalyticsDashboard: (): string => '/mcp-analytics/dashboard',
+ mcpAnalyticsSessions: (): string => '/mcp-analytics/sessions',
+ mcpAnalyticsToolQuality: (): string => '/mcp-analytics/tool-quality',
+ mcpAnalyticsTool: (toolName: string): string => `/mcp-analytics/tool-quality/${encodeURIComponent(toolName)}`,
+ mcpAnalyticsIntentClustering: (): string => '/mcp-analytics/intent-clustering',
},
fileSystemTypes: {},
treeItemsNew: [],
- treeItemsProducts: [],
+ treeItemsProducts: [
+ {
+ path: 'MCP analytics',
+ intents: [ProductKey.LLM_ANALYTICS],
+ category: ProductItemCategory.AI_ENGINEERING,
+ visualOrder: 2,
+ type: 'mcp_analytics',
+ iconType: 'llm_analytics' as FileSystemIconType,
+ iconColor: ['var(--color-product-llm-analytics-light)'] as FileSystemIconColor,
+ href: urls.mcpAnalyticsDashboard(),
+ flag: FEATURE_FLAGS.MCP_ANALYTICS,
+ tags: ['alpha'],
+ sceneKey: 'MCPAnalytics',
+ },
+ ],
}
diff --git a/products/mcp_analytics/mcp/tools.yaml b/products/mcp_analytics/mcp/tools.yaml
index 564ec1c890ed..18765bebc3ba 100644
--- a/products/mcp_analytics/mcp/tools.yaml
+++ b/products/mcp_analytics/mcp/tools.yaml
@@ -9,6 +9,18 @@ feature: mcp_analytics
url_prefix: /mcp-analytics
ui_apps: {}
tools:
+ mcp-analytics-intent-clusters-recompute:
+ operation: mcp_analytics_intent_clusters_recompute
+ enabled: false
+ mcp-analytics-intent-clusters-retrieve:
+ operation: mcp_analytics_intent_clusters_retrieve
+ enabled: false
+ mcp-analytics-sessions-list:
+ operation: mcp_analytics_sessions_list
+ enabled: false
+ mcp-analytics-sessions-tool-calls:
+ operation: mcp_analytics_sessions_tool_calls
+ enabled: false
mcp-feedback-list:
operation: mcp_analytics_feedback_list
enabled: false
diff --git a/products/mcp_analytics/package.json b/products/mcp_analytics/package.json
index 39c48a68a730..5356e9be31a1 100644
--- a/products/mcp_analytics/package.json
+++ b/products/mcp_analytics/package.json
@@ -1,7 +1,15 @@
{
"name": "@posthog/products-mcp-analytics",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
- "backend:contract-check": "echo 'Contract files unchanged'"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-loaders": "catalog:",
+ "kea-router": "catalog:"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "*"
}
}
diff --git a/products/mcp_analytics/turbo.json b/products/mcp_analytics/turbo.json
index 34a16b3d30ce..44865e1b7931 100644
--- a/products/mcp_analytics/turbo.json
+++ b/products/mcp_analytics/turbo.json
@@ -1,10 +1,3 @@
{
- "extends": ["//"],
- "tasks": {
- "backend:contract-check": {
- "inputs": ["backend/facade/**", "backend/presentation/**"],
- "outputs": [],
- "cache": true
- }
- }
+ "extends": ["//"]
}
diff --git a/pyproject.toml b/pyproject.toml
index 133a79b05a5a..d43e6cb74dda 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -472,6 +472,7 @@ ignore_imports = [
"products.**.backend.presentation.** -> products.**.backend.presentation.**",
# TODO: existing violations — fix by routing through facade
"products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.logic",
+ "products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.models",
"products.mcp_analytics.backend.presentation.serializers -> products.mcp_analytics.backend.models",
"products.mcp_store.backend.presentation.views -> products.mcp_store.backend.models",
"products.mcp_store.backend.presentation.views -> products.mcp_store.backend.oauth",
diff --git a/scripts/drain_mcp_intent_summary.py b/scripts/drain_mcp_intent_summary.py
new file mode 100644
index 000000000000..7d2812cb013d
--- /dev/null
+++ b/scripts/drain_mcp_intent_summary.py
@@ -0,0 +1,51 @@
+"""Drain all NULL-intent MCPSession rows by repeatedly invoking the summary activity.
+
+Loops the activity until no rows are pending, capped at MAX_ITERATIONS for safety.
+
+Usage:
+ flox activate -- python scripts/drain_mcp_intent_summary.py
+"""
+
+import os
+import sys
+import asyncio
+
+import django
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+django.setup()
+
+MAX_ITERATIONS = 10
+BATCH_SIZE = 25
+
+
+async def main() -> None:
+ from asgiref.sync import sync_to_async
+
+ from posthog.temporal.mcp_analytics.summarize_session_intents.activities import summarize_mcp_session_intents
+ from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
+
+ from products.mcp_analytics.backend.models import MCPSession
+
+ pending_count = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
+ sys.stdout.write(f"Sessions pending intent: {pending_count}\n")
+
+ for iteration in range(MAX_ITERATIONS):
+ if pending_count == 0:
+ break
+ sys.stdout.write(f"\nIteration {iteration + 1}: summarising up to {BATCH_SIZE} sessions...\n")
+ await summarize_mcp_session_intents(SummarizeMCPSessionIntentsInput(batch_size=BATCH_SIZE))
+ new_pending = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
+ sys.stdout.write(f" pending after: {new_pending}\n")
+ if new_pending >= pending_count:
+ sys.stdout.write(" No progress made; stopping to avoid infinite loop.\n")
+ break
+ pending_count = new_pending
+
+ final_pending = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
+ total = await sync_to_async(MCPSession.objects.unscoped().count)()
+ sys.stdout.write(f"\nDone. pending={final_pending} total={total}\n")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/scripts/validate_mcp_backfill.py b/scripts/validate_mcp_backfill.py
new file mode 100644
index 000000000000..7bebb8e77341
--- /dev/null
+++ b/scripts/validate_mcp_backfill.py
@@ -0,0 +1,48 @@
+"""Quick local validation for the MCP sessions backfill activity.
+
+Runs the same code path the Temporal activity uses, end-to-end:
+ ClickHouse aggregate -> Postgres upsert.
+
+Usage:
+ flox activate -- python scripts/validate_mcp_backfill.py
+"""
+
+import os
+import sys
+import asyncio
+
+import django
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+django.setup()
+
+
+async def main() -> None:
+ from asgiref.sync import sync_to_async
+
+ from posthog.temporal.mcp_analytics.backfill_sessions.activities import aggregate_and_upsert_mcp_sessions
+ from posthog.temporal.mcp_analytics.backfill_sessions.types import BackfillMCPSessionsInput
+
+ from products.mcp_analytics.backend.models import MCPSession
+
+ before = await sync_to_async(MCPSession.objects.unscoped().count)()
+ sys.stdout.write(f"MCPSession rows BEFORE: {before}\n")
+
+ await aggregate_and_upsert_mcp_sessions(BackfillMCPSessionsInput(lookback_hours=72))
+
+ after = await sync_to_async(MCPSession.objects.unscoped().count)()
+ sys.stdout.write(f"MCPSession rows AFTER: {after}\n")
+ sys.stdout.write(f"Delta: {after - before}\n")
+
+ sys.stdout.write("\nFirst 5 rows:\n")
+ rows = await sync_to_async(lambda: list(MCPSession.objects.unscoped().order_by("-session_end")[:5]))()
+ for row in rows:
+ sys.stdout.write(
+ f" team={row.team_id} session_id={row.session_id} "
+ f"duration={row.duration_seconds}s tools={row.tools_used} "
+ f"distinct_id={row.distinct_id!r} client={row.mcp_client_name!r}\n"
+ )
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/scripts/validate_mcp_intent_summary.py b/scripts/validate_mcp_intent_summary.py
new file mode 100644
index 000000000000..84e0c6e5dc0a
--- /dev/null
+++ b/scripts/validate_mcp_intent_summary.py
@@ -0,0 +1,50 @@
+"""End-to-end smoke test for the MCP session intent summary activity.
+
+Runs the same code path the Temporal activity uses:
+ Postgres pick -> ClickHouse fetch -> OpenAI -> Postgres update.
+
+Requires OPENAI_API_KEY to be set in the environment.
+
+Usage:
+ flox activate -- python scripts/validate_mcp_intent_summary.py
+"""
+
+import os
+import sys
+import asyncio
+
+import django
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+django.setup()
+
+
+async def main() -> None:
+ from asgiref.sync import sync_to_async
+
+ from posthog.temporal.mcp_analytics.summarize_session_intents.activities import summarize_mcp_session_intents
+ from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
+
+ from products.mcp_analytics.backend.models import MCPSession
+
+ pending_before = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
+ sys.stdout.write(f"Sessions awaiting intent BEFORE: {pending_before}\n")
+
+ if not os.environ.get("OPENAI_API_KEY"):
+ sys.stdout.write("OPENAI_API_KEY is not set; activity will mark sessions without intents only.\n")
+
+ await summarize_mcp_session_intents(SummarizeMCPSessionIntentsInput(batch_size=5))
+
+ pending_after = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
+ sys.stdout.write(f"Sessions awaiting intent AFTER: {pending_after}\n")
+
+ sys.stdout.write("\nMost recent summaries:\n")
+ rows = await sync_to_async(
+ lambda: list(MCPSession.objects.unscoped().filter(intent__isnull=False).order_by("-updated_at")[:5])
+ )()
+ for row in rows:
+ sys.stdout.write(f" {row.session_id[:24]}\n {row.intent}\n")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9910f4998110..72dbf5451375 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20564,6 +20564,124 @@ export namespace Schemas {
category?: MCPFeedbackCreateCategoryEnum;
}
+ export interface MCPIntentClusterToolEntry {
+ /** MCP tool name that received calls for this cluster. */
+ readonly tool: string;
+ /** Number of tool calls routed to this tool across the cluster. */
+ readonly count: number;
+ /** Percentage of the cluster's calls that went to this tool, 0–100. */
+ readonly pct: number;
+ /** Number of error responses observed for this tool within the cluster. */
+ readonly errors: number;
+ /** Error rate for this tool within the cluster, 0–100. */
+ readonly error_rate_pct: number;
+ }
+
+ /**
+ * * `completed` - Completed
+ * `error` - Error
+ */
+ export type OutcomeEnum = typeof OutcomeEnum[keyof typeof OutcomeEnum];
+
+
+ export const OutcomeEnum = {
+ Completed: 'completed',
+ Error: 'error',
+ } as const;
+
+ export interface MCPIntentClusterJourneyPath {
+ /** Ordered tool names called during the path. Length is fixed; null entries indicate the session ended before this step. */
+ readonly steps: readonly (string | null)[];
+ /** Terminal outcome of the sessions following this path.
+
+ * `completed` - Completed
+ * `error` - Error */
+ readonly outcome: OutcomeEnum;
+ /** Number of sessions in this cluster that followed this exact path. */
+ readonly count: number;
+ }
+
+ export interface MCPIntentClusterJourney {
+ /** Top paths by session count, capped at MAX_JOURNEY_PATHS_PER_CLUSTER. */
+ readonly paths: readonly MCPIntentClusterJourneyPath[];
+ /** Total session count represented across all paths in this cluster. */
+ readonly total_sessions: number;
+ /** Highest-volume non-completed path. Null when every path completed successfully. */
+ readonly leak: MCPIntentClusterJourneyPath | null;
+ }
+
+ export interface MCPIntentCluster {
+ /** Stable cluster identifier within this snapshot. */
+ readonly id: number;
+ /** Representative intent text for the cluster (the medoid intent closest to the cluster centroid). */
+ readonly label: string;
+ /** Number of distinct intent texts that belong to this cluster. */
+ readonly intent_count: number;
+ /** Number of MCP sessions whose summarised intent belongs to this cluster. */
+ readonly session_count: number;
+ /** Total number of mcp_tool_call events represented by this cluster. */
+ readonly call_count: number;
+ /** Total number of error responses observed across the cluster. */
+ readonly error_count: number;
+ /** Aggregate error rate across all tool calls in the cluster, 0–100. */
+ readonly error_rate_pct: number;
+ /** Normalised Shannon entropy of the tool distribution. 0 means perfectly consistent routing (one tool dominates); 1 means uniformly spread across all tools called for this intent cluster. */
+ readonly routing_entropy: number;
+ /** Per-tool breakdown of calls and errors within the cluster. */
+ readonly tool_distribution: readonly MCPIntentClusterToolEntry[];
+ /** Up to three representative intent strings from the cluster, ordered by frequency desc. */
+ 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;
+ }
+
+ /**
+ * * `idle` - Idle
+ * `computing` - Computing
+ * `error` - Error
+ */
+ export type MCPIntentClusterSnapshotStatusEnum = typeof MCPIntentClusterSnapshotStatusEnum[keyof typeof MCPIntentClusterSnapshotStatusEnum];
+
+
+ export const MCPIntentClusterSnapshotStatusEnum = {
+ Idle: 'idle',
+ Computing: 'computing',
+ Error: 'error',
+ } as const;
+
+ export interface MCPIntentClusterSnapshotMeta {
+ /** Cosine distance threshold used by the clustering algorithm. */
+ readonly distance_threshold: number;
+ /** Embedding model used to vectorise intents. */
+ readonly embedding_model: string;
+ /** Number of distinct intents that fed into the clustering run. */
+ readonly n_intents: number;
+ /** Number of clusters produced by the run. */
+ readonly n_clusters: number;
+ }
+
+ export interface MCPIntentClusterSnapshot {
+ /** Whether a snapshot is current (idle), being recomputed (computing), or failed (error).
+
+ * `idle` - Idle
+ * `computing` - Computing
+ * `error` - Error */
+ readonly status: MCPIntentClusterSnapshotStatusEnum;
+ /** Error message from the most recent failed run, otherwise empty. */
+ readonly error_message: string;
+ /**
+ * When the latest snapshot finished computing.
+ * @nullable
+ */
+ readonly last_computed_at: string | null;
+ /** Email of the user who triggered the latest recompute, empty for system-triggered runs. */
+ 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. */
+ readonly computed_with: MCPIntentClusterSnapshotMeta | null;
+ }
+
export interface MCPMissingCapabilityCreate {
/**
* The tool the user tried before leaving feedback, if known.
@@ -20702,6 +20820,51 @@ export namespace Schemas {
category?: MCPServerTemplateCategoryEnum;
}
+ export interface MCPSession {
+ /** PostHog $session_id grouping all mcp_tool_call events. */
+ readonly session_id: string;
+ /** Total number of mcp_tool_call events in the session. */
+ readonly tool_calls: number;
+ /** Timestamp of the first mcp_tool_call event in the session. */
+ readonly session_start: string;
+ /** Timestamp of the most recent mcp_tool_call event in the session. */
+ readonly session_end: string;
+ /** Number of distinct PostHog distinct_ids that produced events in the session. */
+ readonly distinct_id_count: number;
+ /** Distinct $mcp_tool_name values seen in the session. */
+ readonly tools_used: readonly string[];
+ /** Most recent $mcp_client_name observed in the session. */
+ readonly mcp_client_name: string;
+ /** Most recent distinct_id observed for the session. Stable identifier the SDK tagged the events with. */
+ readonly distinct_id: string;
+ /** email property of the Person resolved from distinct_id; empty when no Person is mapped. */
+ readonly person_email: string;
+ /** name property of the Person resolved from distinct_id; empty when no Person is mapped. */
+ readonly person_name: string;
+ /** LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until the summary workflow runs. */
+ readonly intent: string;
+ }
+
+ export interface MCPToolCall {
+ /** ClickHouse uuid of the mcp_tool_call event. */
+ readonly event_id: string;
+ /** When the tool call was captured. */
+ readonly timestamp: string;
+ /** Tool that was invoked ($mcp_tool_name). */
+ readonly tool_name: string;
+ /** Agent intent for this tool call ($mcp_intent). Empty when the SDK did not capture context. */
+ readonly intent: string;
+ /** Whether the tool call resulted in an error. */
+ readonly is_error: boolean;
+ /** Error message when is_error is true, otherwise empty. */
+ readonly error_message: string;
+ /**
+ * Duration of the tool call in milliseconds when captured.
+ * @nullable
+ */
+ readonly duration_ms: number | null;
+ }
+
export interface MarkToleratedInput {
snapshot_id: string;
}
@@ -22479,6 +22642,24 @@ export namespace Schemas {
results: MCPServerTemplate[];
}
+ export interface PaginatedMCPSessionList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: MCPSession[];
+ }
+
+ export interface PaginatedMCPToolCallList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: MCPToolCall[];
+ }
+
export interface PaginatedMaterializedColumnSlotList {
count: number;
/** @nullable */
@@ -40231,6 +40412,36 @@ export namespace Schemas {
offset?: number;
};
+ export type McpAnalyticsSessionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Sort column. Allowed: session_id, session_start, session_end, duration_seconds, tool_call_count, mcp_client_name, distinct_id. Prefix with '-' for descending. Defaults to '-session_end'.
+ */
+ order_by?: string;
+ /**
+ * Case-insensitive substring filter matched against session_id, distinct_id, mcp_client_name, and tools_used.
+ */
+ search?: string;
+ };
+
+ export type McpAnalyticsSessionsToolCallsParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type McpServerInstallationsListParams = {
/**
* Number of results to return per page.
diff --git a/tach.toml b/tach.toml
index a4d25068ec54..33a3aa50a1bc 100644
--- a/tach.toml
+++ b/tach.toml
@@ -98,6 +98,7 @@ depends_on = [
"products.tracing",
"products.user_interviews",
"products.visual_review",
+ "products.mcp_analytics",
"products.warehouse_sources_queue",
"products.web_analytics",
"products.workflows",
@@ -159,6 +160,7 @@ depends_on = [
"ee",
"posthog",
"products.llm_analytics",
+ "products.mcp_analytics",
]
layer = "modules"
@@ -310,6 +312,7 @@ layer = "modules"
path = "products.mcp_analytics"
depends_on = [
"posthog",
+ "products.dashboards",
]
layer = "modules"
@@ -580,6 +583,19 @@ from = [
"products.tracing",
]
+# TODO: legacy leaks — posthog/temporal/mcp_analytics/* and the dashboard
+# integration import models / dashboard_templates directly. Move those into
+# the product (and through the facade) so this interface can shrink back to
+# the isolated default.
+[[interfaces]]
+expose = [
+ "backend\\.dashboard_templates.*",
+ "backend\\.models.*",
+]
+from = [
+ "products.mcp_analytics",
+]
+
[[modules]]
path = "products.legal_documents"
depends_on = [