:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp-analytics): activity tab for mcp analytics (#68708)
Lucas Faria65c06e12dec4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d2842f774b81..29a6a6b764ed 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6227,9 +6227,9 @@ snapshots:scenes-app-mcp-analytics--intent-clustering--light:hash: v1.k794b7964.ef2b5829c6089a3de0ad09c44f8dbeaf2195187569a83422b32ff21712e68251.JCSWUIyzmDcXs1lun_Ym3-i7Z0YBcusaI-amLEFlXs0scenes-app-mcp-analytics--sessions--dark:- hash: v1.k794b7964.001e96fe0191212c3d231d8753dcf40e60c9373a7a05fcc0efa8793665502fa0.i5RsvfroCUclToXiYznW-9-yaRTTBMJN1FPZBA05dEw+ hash: v1.k794b7964.e44b6747efcbc630753707078c16ebb36a05f9701fa89c014d8eebec1eabc4fb.i5C5Ib24E2xi_tzTLXniz3WM8UKaAFOj4aqVnMmtIiIscenes-app-mcp-analytics--sessions--light:- hash: v1.k794b7964.b78645db1a2e4b320ebf5f43885441640993a18af5647e10fdd6cac569ad6219.WJ-5Nl8Jn1h7glwL0SoJj7RvvqwEIE01JupXj4U9zlo+ hash: v1.k794b7964.8a6b42b3e994bb9f035951d84f071f2d7c20756f9745281f61e3383133bd5bb5.GxtTX98b-FQFH6zFqQLhs-oEq7qO_vVqKjJS-CBN77Uscenes-app-mcp-analytics--tool-quality--dark:hash: v1.k794b7964.6f5a4a5ffb216309a2db8c0e3f27560058f556e93624699e25a960efb03c569b.CZfkEDjT7nwC_oOWfYXVWwuB6LK1LpYCitM8ot_YfhMscenes-app-mcp-analytics--tool-quality--light:diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex d4590d595f8a..d84893e98c80 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -287,6 +287,7 @@ export const productRoutes: Record<string, [string, string]> = {'/logs/drop-rules/:id': ['LogsSamplingDetail', 'logsSamplingDetail'],'/managed_migrations': ['ManagedMigration', 'managedMigration'],'/managed_migrations/new': ['ManagedMigration', 'managedMigration'],+ '/mcp-analytics/activity': ['MCPAnalytics', 'mcpAnalyticsActivity'],'/mcp-analytics/dashboard': ['MCPAnalytics', 'mcpAnalyticsDashboard'],'/mcp-analytics/sessions': ['MCPAnalytics', 'mcpAnalyticsSessions'],'/mcp-analytics/tool-quality': ['MCPAnalytics', 'mcpAnalyticsToolQuality'],@@ -477,7 +478,7 @@ export const productRedirects: Record<'/logs/sampling/:id': (params, searchParams, hashParams) =>combineUrl(`/logs/drop-rules/${params.id}`, searchParams, hashParams).url,'/mcp-analytics': (_params, searchParams, hashParams) =>- combineUrl(urls.mcpAnalyticsDashboard(), searchParams, hashParams).url,+ combineUrl(urls.mcpAnalyticsDashboard(), { ...searchParams, landing: 'auto' }, hashParams).url,'/replay-vision/templates': '/replay-vision/new/template','/prompt-management/skills': (_params, searchParams, hashParams) =>combineUrl(urls.skills(), searchParams, hashParams).url,@@ -1208,6 +1209,7 @@ export const productUrls = {managedMigration: (): string => '/managed_migrations',managedMigrationNew: (): string => '/managed_migrations/new',marketingAnalyticsApp: (): string => '/marketing',+ mcpAnalyticsActivity: (): string => '/mcp-analytics/activity',mcpAnalyticsDashboard: (): string => '/mcp-analytics/dashboard',mcpAnalyticsSessions: (): string => '/mcp-analytics/sessions',mcpAnalyticsToolQuality: (): string => '/mcp-analytics/tool-quality',diff --git a/products/mcp_analytics/backend/constants.py b/products/mcp_analytics/backend/constants.pyindex d381db068750..99fe926a5e37 100644--- a/products/mcp_analytics/backend/constants.py+++ b/products/mcp_analytics/backend/constants.py@@ -1,3 +1,4 @@# Key on this canonical event only — also matching the legacy `mcp_tool_call` alias# (frozen, pre-2026-06-16 history) would double-count every call.MCP_TOOL_CALL_EVENT = "$mcp_tool_call"+MCP_MISSING_CAPABILITY_EVENT = "$mcp_missing_capability"diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.pyindex 86034cdbac96..11c592ae6e70 100644--- a/products/mcp_analytics/backend/facade/api.py+++ b/products/mcp_analytics/backend/facade/api.py@@ -87,6 +87,24 @@ def generate_session_intent(team: Team, session_id: str, date_from: datetime | Nreturn logic.generate_session_intent(team, session_id=session_id, date_from=date_from)+def generate_intent_digest(team: Team) -> contracts.IntentDigest:+ """Generate (or return the cached) project-level digest of what agents are trying to do.++ Powers the dashboard's low-volume activity stage. Content-addressed cache: only+ regenerates when new intents arrive.+ """+ return logic.generate_intent_digest(team)+++def get_activity_overview(team: Team) -> contracts.ActivityOverview:+ """Compute the activity view's aggregates and recent-call feed in one pass.++ Bounded to the last 30 days; always computed fresh (the view polls to watch+ data arrive).+ """+ return logic.get_activity_overview(team)++def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:return logic.get_intent_cluster_snapshot(team)diff --git a/products/mcp_analytics/backend/facade/contracts.py b/products/mcp_analytics/backend/facade/contracts.pyindex d60525246260..5bed5d1c45d4 100644--- a/products/mcp_analytics/backend/facade/contracts.py+++ b/products/mcp_analytics/backend/facade/contracts.py@@ -151,3 +151,60 @@ class IntentClusterSnapshot:last_computed_by_email: strclusters: list[IntentCluster] = field(default_factory=list)computed_with: IntentClusterSnapshotMeta | None = None+++@dataclass(frozen=True)+class IntentDigest:+ """Project-level LLM digest of what agents are trying to do with the MCP server."""++ # Null when the project has no recorded intents to summarise yet.+ digest: str | None+ intent_count: int+++@dataclass(frozen=True)+class ActivityStats:+ """Aggregate counters over the activity window, for the dashboard's activity stage."""++ total_calls: int+ distinct_tools: int+ distinct_sessions: int+ distinct_clients: int+ calls_with_intent: int+ error_calls: int+ missing_capability_reports: int+++@dataclass(frozen=True)+class ActivityToolRow:+ tool: str+ calls: int+ errors: int+++@dataclass(frozen=True)+class ActivityClientRow:+ client: str+ calls: int+++@dataclass(frozen=True)+class ActivityRecentCall:+ timestamp: datetime+ tool: str+ intent: str | None+ is_error: bool+ # Human-readable message extracted from the tool's error response, when the call failed.+ error_message: str | None+ duration_ms: float | None+ client_name: str | None+++@dataclass(frozen=True)+class ActivityOverview:+ """Everything the activity view renders, computed server-side in one request."""++ stats: ActivityStats+ top_tools: list[ActivityToolRow] = field(default_factory=list)+ clients: list[ActivityClientRow] = field(default_factory=list)+ recent_calls: list[ActivityRecentCall] = field(default_factory=list)diff --git a/products/mcp_analytics/backend/intent_generation.py b/products/mcp_analytics/backend/intent_generation.pyindex 54ac4ab8883a..cf2fa8abc185 100644--- a/products/mcp_analytics/backend/intent_generation.py+++ b/products/mcp_analytics/backend/intent_generation.py@@ -86,14 +86,23 @@ def _build_user_prompt(intents: list[str]) -> str:return f"Per-tool-call intents (chronological):\n{numbered}\n\nSummarise the agent's overall goal in at most two short, concrete sentences."+def _ensure_llm_available(team: Team) -> None:+ """Intents are user-authored text, so sending them to the LLM requires the+ organization's AI data processing consent, same as every other AI-backed flow."""+ if not settings.OPENAI_API_KEY:+ raise IntentGenerationUnavailable("OPENAI_API_KEY is not configured")+ if not team.organization.is_ai_data_processing_approved:+ raise IntentGenerationUnavailable("AI data processing is not approved for this organization")++def summarize_intents(intents: list[str], team: Team) -> str:"""Condense the intents via the LLM. Blocking — the endpoint runs it inline.- Raises ``IntentGenerationUnavailable`` when the LLM is unconfigured or the request fails,- so the endpoint can answer with a clean 503 rather than a 500.+ Raises ``IntentGenerationUnavailable`` when the LLM is unconfigured, the organization+ has not approved AI data processing, or the request fails, so the endpoint can answer+ with a clean 503 rather than a 500."""- if not settings.OPENAI_API_KEY:- raise IntentGenerationUnavailable("OPENAI_API_KEY is not configured")+ _ensure_llm_available(team)client = OpenAI(posthog_client=posthoganalytics.default_client, base_url=settings.OPENAI_BASE_URL)try:@@ -116,3 +125,86 @@ def summarize_intents(intents: list[str], team: Team) -> str:if not summary:raise IntentGenerationUnavailable("LLM returned an empty summary")return summary+++# Project-level activity digest: what agents are trying to do across the whole+# server, for the dashboard's low-volume activity stage.+MAX_DIGEST_INTENTS = 100+# Bounds the intent scan so the events sort key can prune it. Generous because+# activity-stage servers are low-volume and their history is short by definition.+DIGEST_LOOKBACK = timedelta(days=90)++DIGEST_SYSTEM_PROMPT = (+ "You are given the per-tool-call intents AI agents recorded while using one MCP server, "+ "most recent first. Summarise what agents are trying to do with this server in at most "+ "three short sentences. Group similar intents into themes and lead with the most common one. "+ "Be concrete: name the actual workflows, products, or entities involved — never generic "+ "phrases like 'various tasks' or 'data exploration'. Do not list tools, echo the input, or add filler."+)++_PROJECT_INTENTS_SQL = """+SELECT toString(properties.$mcp_intent) AS intent+FROM events+WHERE event = {event}+ AND timestamp >= {date_from}+ AND coalesce(properties.$mcp_intent, '') != ''+ORDER BY timestamp DESC+LIMIT {limit}+"""+++def fetch_recent_project_intents(team: Team) -> list[str]:+ """Return the project's most recent ``$mcp_intent``s across all sessions, newest first."""+ query = parse_select(+ _PROJECT_INTENTS_SQL,+ placeholders={+ "event": ast.Constant(value=MCP_TOOL_CALL_EVENT),+ "date_from": ast.Constant(value=timezone.now() - DIGEST_LOOKBACK),+ "limit": ast.Constant(value=MAX_DIGEST_INTENTS),+ },+ )+ with tags_context(+ product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name="mcp_analytics_intent_digest"+ ):+ response = execute_hogql_query(query=query, team=team)+ return [str(row[0]) for row in (response.results or []) if row[0]]+++def _build_digest_prompt(intents: list[str]) -> str:+ numbered = "\n".join(f"{i + 1}. {intent}" for i, intent in enumerate(intents))+ return (+ f"Per-tool-call intents (most recent first):\n{numbered}\n\n"+ "Summarise what agents are trying to do with this server, in at most three short sentences."+ )+++def summarize_project_intents(intents: list[str], team: Team) -> str:+ """Condense the project's intents into an activity digest. Blocking — the endpoint runs it inline.++ Raises ``IntentGenerationUnavailable`` when the LLM is unconfigured, the organization+ has not approved AI data processing, or the request fails, so the endpoint can answer+ with a clean 503 rather than a 500.+ """+ _ensure_llm_available(team)++ client = OpenAI(posthog_client=posthoganalytics.default_client, base_url=settings.OPENAI_BASE_URL)+ try:+ response = client.chat.completions.create( # type: ignore+ model=INTENT_MODEL,+ temperature=0,+ max_tokens=140,+ timeout=30,+ messages=[+ {"role": "system", "content": DIGEST_SYSTEM_PROMPT},+ {"role": "user", "content": _build_digest_prompt(intents)},+ ],+ user=f"team/{team.id}/mcp-analytics-intent-digest",+ posthog_properties={"ai_product": "mcp_analytics", "ai_feature": "activity-intent-digest"},+ )+ except openai.OpenAIError as e:+ raise IntentGenerationUnavailable("LLM request failed") from e+ content = response.choices[0].message.content if response.choices else None+ digest = (content or "").strip()+ if not digest:+ raise IntentGenerationUnavailable("LLM returned an empty digest")+ return digestdiff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.pyindex e1fa6b8c47be..de69fe773502 100644--- a/products/mcp_analytics/backend/logic.py+++ b/products/mcp_analytics/backend/logic.py@@ -1,3 +1,5 @@+import json+import hashlibfrom datetime import datetime, timedeltafrom typing import Any@@ -21,7 +23,7 @@ from posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.utils import generate_cache_keyfrom products.mcp_analytics.backend import intent_generation-from products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENT+from products.mcp_analytics.backend.constants import MCP_MISSING_CAPABILITY_EVENT, MCP_TOOL_CALL_EVENTfrom products.mcp_analytics.backend.facade import contracts, enumsfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession@@ -332,6 +334,216 @@ def generate_session_intent(team: Team, session_id: str, date_from: datetime | Nreturn summary+INTENT_DIGEST_CACHE_TTL = 60 * 60+++def generate_intent_digest(team: Team) -> contracts.IntentDigest:+ """Return a project-level LLM digest of what agents are trying to do, for the activity stage.++ Content-addressed cache: the digest is keyed by the current intent corpus, so it only+ regenerates when new intents arrive (and at most refreshes hourly via the TTL). A project+ with no recorded intents returns a null digest without an LLM call, so the frontend can+ fall back to its verbatim list. Raises ``contracts.IntentGenerationUnavailable`` if the+ LLM is unreachable.+ """+ intents = intent_generation.fetch_recent_project_intents(team)+ if not intents:+ return contracts.IntentDigest(digest=None, intent_count=0)++ corpus_hash = hashlib.sha256("\n".join(intents).encode()).hexdigest()+ cache_key = generate_cache_key(team.pk, f"mcp_intent_digest/{corpus_hash}")+ cached = cache.get(cache_key)+ if cached:+ return contracts.IntentDigest(digest=cached, intent_count=len(intents))++ digest = intent_generation.summarize_project_intents(intents, team)+ cache.set(cache_key, digest, INTENT_DIGEST_CACHE_TTL)+ return contracts.IntentDigest(digest=digest, intent_count=len(intents))+++# The activity queries read `properties.*`, which decompresses the properties column for+# every matching row, and the view is reachable at any project volume. 30 days is+# effectively all-time for the low-volume servers the activity stage exists for, and a+# hard cap on the scan for high-volume projects that open the tab.+ACTIVITY_WINDOW = timedelta(days=30)+ACTIVITY_TOP_TOOLS_LIMIT = 5+ACTIVITY_CLIENTS_LIMIT = 6+ACTIVITY_RECENT_CALLS_LIMIT = 20++_ACTIVITY_STATS_SQL = """+SELECT+ countIf(event = {tool_call_event}) AS total_calls,+ uniqIf(properties.$mcp_tool_name, event = {tool_call_event}) AS distinct_tools,+ uniqIf($session_id, event = {tool_call_event} AND $session_id != '') AS distinct_sessions,+ uniqIf(properties.$mcp_client_name, event = {tool_call_event} AND coalesce(properties.$mcp_client_name, '') != '') AS distinct_clients,+ countIf(event = {tool_call_event} AND coalesce(properties.$mcp_intent, '') != '') AS calls_with_intent,+ countIf(event = {tool_call_event} AND toString(properties.$mcp_is_error) IN ('true', '1')) AS error_calls,+ countIf(event = {missing_capability_event}) AS missing_capability_reports+FROM events+WHERE event IN ({tool_call_event}, {missing_capability_event}) AND timestamp >= {date_from}+"""++_ACTIVITY_TOP_TOOLS_SQL = """+SELECT+ properties.$mcp_tool_name AS tool,+ count() AS calls,+ countIf(toString(properties.$mcp_is_error) IN ('true', '1')) AS errors+FROM events+WHERE event = {tool_call_event} AND properties.$mcp_tool_name IS NOT NULL AND timestamp >= {date_from}+GROUP BY tool+ORDER BY calls DESC+LIMIT {limit}+"""++_ACTIVITY_CLIENTS_SQL = """+SELECT+ properties.$mcp_client_name AS client,+ count() AS calls+FROM events+WHERE event = {tool_call_event} AND timestamp >= {date_from}+GROUP BY client+ORDER BY calls DESC+LIMIT {limit}+"""++_ACTIVITY_RECENT_CALLS_SQL = """+SELECT+ timestamp,+ properties.$mcp_tool_name AS tool,+ properties.$mcp_intent AS intent,+ toString(properties.$mcp_is_error) IN ('true', '1') AS is_error,+ if(toString(properties.$mcp_is_error) IN ('true', '1'),+ coalesce(nullIf(toString(properties.$mcp_error_message), ''), toString(properties.$mcp_response)),+ NULL) AS error_raw,+ toFloat(properties.$mcp_duration_ms) AS duration_ms,+ properties.$mcp_client_name AS client_name+FROM events+WHERE event = {tool_call_event} AND timestamp >= {date_from}+ORDER BY timestamp DESC+LIMIT {limit}+"""+++def _extract_error_message(raw: Any) -> str | None:+ """Pull the human-readable text out of a failed call's error payload.++ ``$mcp_error_message`` is used verbatim when the SDK set it; otherwise ``$mcp_response``+ is an MCP content envelope ({"content": [{"type": "text", "text": ...}]}) to unwrap.+ """+ value = str(raw).strip() if raw is not None else ""+ if not value:+ return None+ try:+ parsed = json.loads(value)+ except (json.JSONDecodeError, ValueError):+ # HogQL's property accessor strips a string value's outer quotes but keeps the+ # inner escapes; re-wrap to unescape, then parse the payload it encodes.+ try:+ parsed = json.loads(json.loads(f'"{value}"'))+ except (json.JSONDecodeError, ValueError):+ return value+ if isinstance(parsed, dict):+ content = parsed.get("content")+ if isinstance(content, list):+ for chunk in content:+ if isinstance(chunk, dict) and chunk.get("type") == "text" and isinstance(chunk.get("text"), str):+ return chunk["text"] or None+ message = parsed.get("message")+ if isinstance(message, str) and message:+ return message+ return value+++def _run_activity_query(team: Team, sql: str, name: str, placeholders: dict[str, ast.Constant]) -> list[Any]:+ query = parse_select(sql, placeholders={**placeholders})+ with tags_context(product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name=name):+ response = execute_hogql_query(query=query, team=team)+ return response.results or []+++def get_activity_overview(team: Team) -> contracts.ActivityOverview:+ """Compute everything the activity view renders, bounded to ``ACTIVITY_WINDOW``.++ Always computed fresh: the view's whole point is watching data arrive, so callers+ poll this endpoint rather than a stale cache.+ """+ date_from = ast.Constant(value=timezone.now() - ACTIVITY_WINDOW)+ tool_call_event = ast.Constant(value=MCP_TOOL_CALL_EVENT)++ stats_rows = _run_activity_query(+ team,+ _ACTIVITY_STATS_SQL,+ "mcp_analytics_activity_stats",+ {+ "tool_call_event": tool_call_event,+ "missing_capability_event": ast.Constant(value=MCP_MISSING_CAPABILITY_EVENT),+ "date_from": date_from,+ },+ )+ stats_row = stats_rows[0] if stats_rows else [0] * 7+ stats = contracts.ActivityStats(+ total_calls=_parse_int(stats_row[0]) or 0,+ distinct_tools=_parse_int(stats_row[1]) or 0,+ distinct_sessions=_parse_int(stats_row[2]) or 0,+ distinct_clients=_parse_int(stats_row[3]) or 0,+ calls_with_intent=_parse_int(stats_row[4]) or 0,+ error_calls=_parse_int(stats_row[5]) or 0,+ missing_capability_reports=_parse_int(stats_row[6]) or 0,+ )++ top_tools = [+ contracts.ActivityToolRow(tool=str(row[0] or ""), calls=_parse_int(row[1]) or 0, errors=_parse_int(row[2]) or 0)+ for row in _run_activity_query(+ team,+ _ACTIVITY_TOP_TOOLS_SQL,+ "mcp_analytics_activity_top_tools",+ {+ "tool_call_event": tool_call_event,+ "date_from": date_from,+ "limit": ast.Constant(value=ACTIVITY_TOP_TOOLS_LIMIT),+ },+ )+ ]++ clients = [+ contracts.ActivityClientRow(client=str(row[0]) if row[0] else "", calls=_parse_int(row[1]) or 0)+ for row in _run_activity_query(+ team,+ _ACTIVITY_CLIENTS_SQL,+ "mcp_analytics_activity_clients",+ {+ "tool_call_event": tool_call_event,+ "date_from": date_from,+ "limit": ast.Constant(value=ACTIVITY_CLIENTS_LIMIT),+ },+ )+ ]++ recent_calls = [+ contracts.ActivityRecentCall(+ timestamp=row[0],+ tool=str(row[1] or ""),+ intent=str(row[2]) if row[2] else None,+ is_error=bool(row[3]),+ error_message=_extract_error_message(row[4]),+ duration_ms=float(row[5]) if row[5] is not None else None,+ client_name=str(row[6]) if row[6] else None,+ )+ for row in _run_activity_query(+ team,+ _ACTIVITY_RECENT_CALLS_SQL,+ "mcp_analytics_activity_recent_calls",+ {+ "tool_call_event": tool_call_event,+ "date_from": date_from,+ "limit": ast.Constant(value=ACTIVITY_RECENT_CALLS_LIMIT),+ },+ )+ ]++ return contracts.ActivityOverview(stats=stats, top_tools=top_tools, clients=clients, recent_calls=recent_calls)++def _resolve_persons(team_id: int, distinct_ids: list[str]) -> dict[str, Person]:unique_ids = list({distinct_id for distinct_id in distinct_ids if distinct_id})if not unique_ids:diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.pyindex 0dd43601b127..95b0b08cc15b 100644--- a/products/mcp_analytics/backend/presentation/serializers.py+++ b/products/mcp_analytics/backend/presentation/serializers.py@@ -303,6 +303,99 @@ class MCPSessionIntentSerializer(serializers.Serializer):)+class MCPIntentDigestSerializer(serializers.Serializer):+ digest = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text=(+ "LLM-generated digest (at most three sentences) of what agents are trying to do with this MCP "+ "server, derived from the most recent recorded $mcp_intents across all sessions. Null when the "+ "project has no recorded intents yet."+ ),+ )+ intent_count = serializers.IntegerField(+ read_only=True,+ help_text="How many recorded intents (the most recent, capped at 100) the digest was derived from.",+ )+++class MCPActivityStatsSerializer(serializers.Serializer):+ total_calls = serializers.IntegerField(+ read_only=True, help_text="$mcp_tool_call events captured in the last 30 days."+ )+ distinct_tools = serializers.IntegerField(+ read_only=True, help_text="Distinct tools ($mcp_tool_name) called in the window."+ )+ distinct_sessions = serializers.IntegerField(+ read_only=True, help_text="Distinct $session_ids seen on tool calls in the window."+ )+ distinct_clients = serializers.IntegerField(+ read_only=True, help_text="Distinct agent clients ($mcp_client_name) seen in the window."+ )+ calls_with_intent = serializers.IntegerField(+ read_only=True, help_text="Tool calls that carried an $mcp_intent, for intent-coverage checks."+ )+ error_calls = serializers.IntegerField(+ read_only=True, help_text="Tool calls flagged as errors ($mcp_is_error) in the window."+ )+ missing_capability_reports = serializers.IntegerField(+ read_only=True, help_text="$mcp_missing_capability events captured in the window."+ )+++class MCPActivityToolRowSerializer(serializers.Serializer):+ tool = serializers.CharField(read_only=True, help_text="MCP tool name ($mcp_tool_name).")+ calls = serializers.IntegerField(read_only=True, help_text="Tool calls in the window.")+ # The name shadows Serializer.errors, which is fine for a read-only output field.+ errors = serializers.IntegerField( # type: ignore[assignment]+ read_only=True, help_text="Of those calls, how many errored."+ )+++class MCPActivityClientRowSerializer(serializers.Serializer):+ client = serializers.CharField(+ read_only=True,+ allow_blank=True,+ help_text="Agent client name ($mcp_client_name). Empty when the SDK did not capture it.",+ )+ calls = serializers.IntegerField(read_only=True, help_text="Tool calls from this client in the window.")+++class MCPActivityRecentCallSerializer(serializers.Serializer):+ timestamp = serializers.DateTimeField(read_only=True, help_text="When the tool call was captured.")+ tool = serializers.CharField(read_only=True, help_text="Tool that was invoked ($mcp_tool_name).")+ intent = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="Agent intent for this tool call ($mcp_intent). Null 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,+ allow_null=True,+ help_text="Human-readable error extracted from the tool's response when is_error is true, otherwise null.",+ )+ duration_ms = serializers.FloatField(+ read_only=True, allow_null=True, help_text="Duration of the tool call in milliseconds when captured."+ )+ client_name = serializers.CharField(+ read_only=True, allow_null=True, help_text="Agent client name ($mcp_client_name) when captured."+ )+++class MCPActivityOverviewSerializer(serializers.Serializer):+ stats = MCPActivityStatsSerializer(read_only=True, help_text="Aggregate counters over the last 30 days.")+ top_tools = MCPActivityToolRowSerializer(+ many=True, read_only=True, help_text="Most-called tools in the window, top 5 by call count."+ )+ clients = MCPActivityClientRowSerializer(+ many=True, read_only=True, help_text="Agent clients in the window, top 6 by call count."+ )+ recent_calls = MCPActivityRecentCallSerializer(+ many=True, read_only=True, help_text="The 20 most recent tool calls, newest first."+ )++class MCPIntentClusterToolEntrySerializer(serializers.Serializer):tool = serializers.CharField(read_only=True, help_text="MCP tool name that received calls for this cluster.")count = serializers.IntegerField(diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.pyindex 8ce741c9b895..be4467929685 100644--- a/products/mcp_analytics/backend/presentation/views.py+++ b/products/mcp_analytics/backend/presentation/views.py@@ -25,9 +25,11 @@ from products.mcp_analytics.backend.models import MCPAnalyticsSubmissionfrom .serializers import (MCP_SESSION_LIST_DEFAULT_LIMIT,MCP_SESSION_LIST_MAX_LIMIT,+ MCPActivityOverviewSerializer,MCPAnalyticsSubmissionSerializer,MCPFeedbackCreateSerializer,MCPIntentClusterSnapshotSerializer,+ MCPIntentDigestSerializer,MCPMissingCapabilityCreateSerializer,MCPSessionIntentSerializer,MCPSessionListQuerySerializer,@@ -157,11 +159,11 @@ class MCPFeedbackViewSet(BaseMCPAnalyticsSubmissionViewSet):class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer_class = MCPSessionSerializerscope_object = "mcp_analytics"- # tool_calls is a detail GET (read); generate_intent is a POST that computes + persists the- # intent summary, so it maps to the write scope. The default read/write action lists don't- # cover custom @action names, so APIScopePermission would otherwise reject token access.- scope_object_read_actions = ["list", "retrieve", "tool_calls"]- scope_object_write_actions = ["generate_intent"]+ # tool_calls and activity_overview are GETs (read); generate_intent is a POST that computes ++ # persists the intent summary, so it maps to the write scope. The default read/write action+ # lists don't cover custom @action names, so APIScopePermission would otherwise reject token access.+ scope_object_read_actions = ["list", "retrieve", "tool_calls", "activity_overview"]+ scope_object_write_actions = ["generate_intent", "intent_digest"]posthog_feature_flag = "mcp-analytics"permission_classes = [PostHogFeatureFlagPermission]pagination_class = MCPSessionPagination@@ -251,6 +253,44 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer = MCPSessionIntentSerializer({"session_id": session_id, "intent": intent})return Response(serializer.data)+ @extend_schema(+ operation_id="mcp_analytics_sessions_intent_digest",+ description=(+ "Generate (or return the cached) LLM digest of what agents are trying to do with this MCP server, "+ "derived from the most recent recorded $mcp_intents across all sessions. Content-addressed cache: "+ "only regenerates when new intents arrive. Powers the dashboard's low-volume activity stage."+ ),+ request=None,+ responses={+ 200: MCPIntentDigestSerializer,+ 503: OpenApiResponse(description="Intent digest generation is unavailable (LLM not configured)."),+ },+ )+ @action(detail=False, methods=["post"], url_path="intent_digest")+ def intent_digest(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ try:+ digest = api.generate_intent_digest(self.team)+ except contracts.IntentGenerationUnavailable:+ return Response(+ {"detail": "Intent digest generation is unavailable (LLM not configured)."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ return Response(MCPIntentDigestSerializer(digest).data)++ @extend_schema(+ operation_id="mcp_analytics_sessions_activity_overview",+ description=(+ "Aggregate counters, top tools, agent clients, and the most recent tool calls for the last 30 days, "+ "computed in one request. Powers the dashboard's activity view; always computed fresh so polling "+ "callers watch data arrive."+ ),+ responses={200: MCPActivityOverviewSerializer},+ )+ @action(detail=False, methods=["get"], url_path="activity_overview", pagination_class=None)+ def activity_overview(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ overview = api.get_activity_overview(self.team)+ return Response(MCPActivityOverviewSerializer(overview).data)+class MCPIntentClusterViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer_class = MCPIntentClusterSnapshotSerializerdiff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.pyindex 0659cff29d06..1452d48fdaa7 100644--- a/products/mcp_analytics/backend/tests/test_api.py+++ b/products/mcp_analytics/backend/tests/test_api.py@@ -441,6 +441,129 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,assert [c.tool_name for c in page.results] == ["before_window", "in_window"]+class TestGenerateIntentDigest(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):+ def _seed_intent_event(self, intent: str) -> None:+ _create_event(+ team=self.team,+ event="$mcp_tool_call",+ distinct_id="seed",+ timestamp=datetime.now(tz=UTC),+ properties={"$session_id": str(uuid7()), "$mcp_tool_name": "query_run", "$mcp_intent": intent},+ )++ def test_no_intents_returns_null_digest_without_llm(self) -> None:+ with patch.object(intent_generation, "summarize_project_intents") as mock_summarize:+ result = api.generate_intent_digest(self.team)++ assert result == contracts.IntentDigest(digest=None, intent_count=0)+ mock_summarize.assert_not_called()++ def test_generates_then_serves_from_cache_for_same_corpus(self) -> None:+ cache.clear()+ self._seed_intent_event("check the signups funnel")+ self._seed_intent_event("compare to last week")++ with patch.object(+ intent_generation, "summarize_project_intents", return_value="Signup funnel investigation."+ ) as mock_summarize:+ first = api.generate_intent_digest(self.team)+ again = api.generate_intent_digest(self.team)++ assert first.digest == "Signup funnel investigation."+ assert first.intent_count == 2+ assert again == first+ mock_summarize.assert_called_once()+++class TestLLMConsentGate(APIBaseTest):+ @parameterized.expand(+ [+ ("session_summary", intent_generation.summarize_intents),+ ("project_digest", intent_generation.summarize_project_intents),+ ]+ )+ def test_refuses_without_ai_data_processing_consent(self, _name, summarize) -> None:+ self.organization.is_ai_data_processing_approved = False+ self.organization.save()++ with (+ self.settings(OPENAI_API_KEY="sk-test"),+ patch.object(intent_generation, "OpenAI") as mock_client,+ self.assertRaises(contracts.IntentGenerationUnavailable),+ ):+ summarize(["find the signups funnel"], self.team)+ mock_client.assert_not_called()+++class TestActivityOverview(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):+ def test_aggregates_window_and_extracts_error_messages(self) -> None:+ session_id = str(uuid7())+ _create_event(+ team=self.team,+ event="$mcp_tool_call",+ distinct_id="agent-1",+ timestamp=datetime.now(tz=UTC) - timedelta(hours=2),+ properties={+ "$session_id": session_id,+ "$mcp_tool_name": "query_run",+ "$mcp_intent": "check signups",+ "$mcp_client_name": "Claude Code",+ "$mcp_duration_ms": 120,+ },+ )+ _create_event(+ team=self.team,+ event="$mcp_tool_call",+ distinct_id="agent-1",+ timestamp=datetime.now(tz=UTC) - timedelta(hours=1),+ properties={+ "$session_id": session_id,+ "$mcp_tool_name": "docs_search",+ "$mcp_is_error": "true",+ "$mcp_response": '{"content": [{"type": "text", "text": "index unavailable"}]}',+ "$mcp_client_name": "Claude Code",+ },+ )+ _create_event(+ team=self.team,+ event="$mcp_missing_capability",+ distinct_id="agent-1",+ timestamp=datetime.now(tz=UTC) - timedelta(hours=1),+ properties={},+ )+ # Outside the 30-day window: must not count anywhere.+ _create_event(+ team=self.team,+ event="$mcp_tool_call",+ distinct_id="agent-1",+ timestamp=datetime.now(tz=UTC) - timedelta(days=40),+ properties={"$session_id": str(uuid7()), "$mcp_tool_name": "query_run"},+ )++ overview = api.get_activity_overview(self.team)++ assert overview.stats == contracts.ActivityStats(+ total_calls=2,+ distinct_tools=2,+ distinct_sessions=1,+ distinct_clients=1,+ calls_with_intent=1,+ error_calls=1,+ missing_capability_reports=1,+ )+ assert {(row.tool, row.calls, row.errors) for row in overview.top_tools} == {+ ("query_run", 1, 0),+ ("docs_search", 1, 1),+ }+ assert overview.clients == [contracts.ActivityClientRow(client="Claude Code", calls=2)]+ assert [call.tool for call in overview.recent_calls] == ["docs_search", "query_run"]+ error_call = overview.recent_calls[0]+ assert error_call.is_error is True+ assert error_call.error_message == "index unavailable"+ assert overview.recent_calls[1].duration_ms == 120.0+ assert overview.recent_calls[1].intent == "check signups"++class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):def setUp(self) -> None:super().setUp()diff --git a/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx b/products/mcp_analytics/frontend/MCPAnalyticsScene.tsxindex 60b14dc829a5..c80396ccd934 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx@@ -13,6 +13,7 @@ import { SceneExport } from '~/scenes/sceneTypes'import { askPostHogAI } from './askPostHogAI'import { MCPAnalyticsClustering } from './clustering/MCPAnalyticsClustering'+import { MCPAnalyticsActivityDashboard } from './earlyData/MCPAnalyticsEarlyData'import { mcpAnalyticsFeaturePreviewGate } from './featurePreviewGate'import { MCPAnalyticsDashboard } from './MCPAnalyticsDashboard'import { MCPAnalyticsLoading, MCPAnalyticsOnboarding } from './MCPAnalyticsOnboarding'@@ -40,19 +41,31 @@ export function MCPAnalyticsScene(): JSX.Element {function MCPAnalyticsSceneContent(): JSX.Element {const { searchParams } = useValues(router)const { activeTab } = useValues(mcpAnalyticsSceneLogic)- const { onboardingState, signals } = useValues(mcpAnalyticsOnboardingLogic)+ const { onboardingState, signals, dashboardStage } = useValues(mcpAnalyticsOnboardingLogic)// search is Sessions-only — drop it when leaving the tab; the date range stays shared.const { search: _search, ...sharedParams } = searchParams+ const activityTab: LemonTab<MCPAnalyticsTab> = {+ key: 'activity',+ label: 'Activity',+ content: <MCPAnalyticsActivityDashboard />,+ link: combineUrl(urls.mcpAnalyticsActivity(), sharedParams).url,+ 'data-attr': 'mcp-analytics-activity-tab',+ }+ const dashboardTab: LemonTab<MCPAnalyticsTab> = {+ key: 'dashboard',+ label: 'Dashboard',+ content: <MCPAnalyticsDashboard />,+ link: combineUrl(urls.mcpAnalyticsDashboard(), sharedParams).url,+ 'data-attr': 'mcp-analytics-dashboard-tab',+ }+const tabs: LemonTab<MCPAnalyticsTab>[] = [- {- key: 'dashboard',- label: 'Dashboard',- content: <MCPAnalyticsDashboard />,- link: combineUrl(urls.mcpAnalyticsDashboard(), sharedParams).url,- 'data-attr': 'mcp-analytics-dashboard-tab',- },+ // The default landing tab leads: Activity while the project is low-volume,+ // Dashboard once it graduates — matching the landing redirect so the first+ // tab is always the one you arrive on.+ ...(dashboardStage === 'activity' ? [activityTab, dashboardTab] : [dashboardTab, activityTab]),{key: 'sessions',label: 'Sessions',diff --git a/products/mcp_analytics/frontend/dashboard/Card.tsx b/products/mcp_analytics/frontend/dashboard/Card.tsxindex 02b2d2af5b48..4aa3c36aaec0 100644--- a/products/mcp_analytics/frontend/dashboard/Card.tsx+++ b/products/mcp_analytics/frontend/dashboard/Card.tsx@@ -3,14 +3,17 @@ import { Card as QuillCard, CardContent, CardHeader, CardTitle } from '@posthog/export function Card({children,className,+ flush = false,title,}: {children: React.ReactNodeclassName?: string+ /** Let a full-bleed child (table, chart) reach the card's edges, with no header-to-content gap. */+ flush?: booleantitle?: string}): JSX.Element {return (- <QuillCard size="sm" className={className}>+ <QuillCard size="sm" flush={flush} className={className}>{title ? (<CardHeader><CardTitle>{title}</CardTitle>diff --git a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsxnew file mode 100644index 000000000000..d40313e54171--- /dev/null+++ b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx@@ -0,0 +1,296 @@+import { useActions, useValues } from 'kea'++import { IconCheckCircle, IconClock, IconRefresh, IconWarning } from '@posthog/icons'+import { LemonButton, LemonSkeleton, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'++import { ExplorerHog } from 'lib/components/hedgehogs'+import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { urls } from 'scenes/urls'++import { Card } from '../dashboard/Card'+import { formatMs, formatNumber } from '../dashboard/formatters'+import { HarnessLogo } from '../dashboard/harness'+import { METRICS_UNLOCK_LIFETIME_CALLS, mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'+import type { ChecklistItem, EarlyRecentCall } from './mcpEarlyDataLogic'+import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'++// Raw `$mcp_client_name` values don't match the backend-resolved harness labels the+// logo registry is keyed by; this maps the common spellings so rows get a logo.+// Unknown clients fall back to HarnessLogo's neutral dot.+const CLIENT_LABEL_RULES: Array<[RegExp, string]> = [+ [/claude[ ._-]?code/i, 'Claude Code'],+ [/claude[ ._-]?desktop/i, 'Claude Desktop'],+ [/claude[ ._-]?ai/i, 'Claude.ai'],+ [/claude/i, 'Claude.ai'],+ [/chatgpt/i, 'ChatGPT'],+ [/codex/i, 'OpenAI Codex'],+ [/openai/i, 'OpenAI'],+ [/cursor/i, 'Cursor'],+ [/windsurf/i, 'Windsurf'],+]++function guessHarnessLabel(clientName: string): string {+ return CLIENT_LABEL_RULES.find(([pattern]) => pattern.test(clientName))?.[1] ?? clientName+}++/**+ * The Activity tab: answers "what are agents doing with my server?" — a+ * plain-language summary instead of KPI tiles, the live feed as the hero, an+ * AI digest of agent intents, and an instrumentation checklist. It refreshes+ * live and is the default landing tab for low-volume projects, where the+ * windowed metrics dashboard would be noise; higher-volume projects land on+ * the Dashboard tab but can always come here for recency.+ */+export function MCPAnalyticsActivityDashboard(): JSX.Element {+ return (+ <div className="flex flex-col gap-4" data-attr="mcp-analytics-activity">+ <SummaryCard />+ <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">+ <div className="lg:col-span-3">+ <LiveActivityCard />+ </div>+ <div className="flex flex-col gap-4">+ <IntentsCard />+ <ClientsCard />+ <ChecklistCard />+ </div>+ </div>+ </div>+ )+}++function SummaryCard(): JSX.Element {+ const { signals, dashboardStage } = useValues(mcpAnalyticsOnboardingLogic)+ const { summary, isRefreshing } = useValues(mcpEarlyDataLogic)+ const { refreshAll } = useActions(mcpEarlyDataLogic)++ return (+ // Same accent gradient as the first-look hero, so the product's intro+ // surfaces share a visual identity across stages.+ <Card className="bg-gradient-to-br from-accent/15 via-accent/5 to-surface-primary">+ <div className="flex items-center justify-between gap-4 flex-wrap">+ <div className="flex items-center gap-4 min-w-0">+ <ExplorerHog className="h-20 w-20 shrink-0 hidden sm:block" />+ <div className="min-w-0">+ <h3 className="text-xl font-semibold m-0">+ {summary}+ {/* Omitted on day one — "since today" is noise. */}+ {signals?.firstCallAt && !dayjs(signals.firstCallAt).isSame(dayjs(), 'day') ? (+ <span className="text-muted font-normal">+ {' '}+ since {dayjs(signals.firstCallAt).format('MMM D')}+ </span>+ ) : null}+ </h3>+ <p className="text-muted text-base m-0 mt-1">+ This view fills in live as agents use your server.+ {dashboardStage === 'activity' ? (+ <>+ {' '}+ Charts and trends live in the{' '}+ <Link to={urls.mcpAnalyticsDashboard()}>Dashboard tab</Link> — they get meaningful+ as usage grows (~{formatNumber(METRICS_UNLOCK_LIFETIME_CALLS)} calls).+ </>+ ) : null}+ </p>+ </div>+ </div>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconRefresh />}+ loading={isRefreshing}+ onClick={refreshAll}+ data-attr="mcp-analytics-activity-refresh"+ >+ Refresh+ </LemonButton>+ </div>+ </Card>+ )+}++function LiveActivityCard(): JSX.Element {+ const { recentCalls, overviewLoading } = useValues(mcpEarlyDataLogic)++ return (+ <Card title="Live activity" className="h-full" flush>+ {/* Roughly the top 10 rows visible; the rest scroll. */}+ <div className="max-h-[36rem] overflow-y-auto">+ <LemonTable<EarlyRecentCall>+ embedded+ dataSource={recentCalls}+ loading={overviewLoading && recentCalls.length === 0}+ rowKey={(row, index) => `${row.timestamp}-${row.tool}-${index}`}+ emptyState="Waiting for the next tool call…"+ columns={[+ {+ title: 'When',+ key: 'timestamp',+ width: 130,+ render: (_, row) => <TZLabel time={row.timestamp} />,+ },+ {+ title: 'Tool',+ key: 'tool',+ render: (_, row) => (+ <span className="flex items-center gap-1 font-mono text-sm">+ {row.tool}+ {row.isError ? <LemonTag type="danger">error</LemonTag> : null}+ </span>+ ),+ },+ {+ title: 'Agent intent',+ key: 'intent',+ render: (_, row) => (+ <div>+ {row.intent ? (+ <span className="text-base">{row.intent}</span>+ ) : (+ <span className="text-muted text-base">—</span>+ )}+ {row.errorMessage ? (+ <div+ className="text-danger text-sm mt-0.5 line-clamp-2"+ title={row.errorMessage}+ >+ {row.errorMessage}+ </div>+ ) : null}+ </div>+ ),+ },+ {+ title: 'Duration',+ key: 'duration',+ width: 90,+ align: 'right',+ render: (_, row) => (row.durationMs == null ? '—' : formatMs(row.durationMs)),+ },+ {+ title: 'Client',+ key: 'client',+ width: 150,+ render: (_, row) =>+ row.clientName ? (+ <span className="flex items-center gap-1.5">+ <HarnessLogo+ category={guessHarnessLabel(row.clientName)}+ className="h-3.5 w-3.5"+ />+ <span className="truncate">{row.clientName}</span>+ </span>+ ) : (+ <span className="text-muted">unknown</span>+ ),+ },+ ]}+ />+ </div>+ </Card>+ )+}++// The AI digest is the product here: real intents are all worded differently, so+// verbatim grouping can't answer "what are agents trying to do". The raw list is+// strictly the degraded state for when generation is unavailable (no LLM key).+function IntentsCard(): JSX.Element {+ const { intentDigest, intentDigestLoading, intentThemes } = useValues(mcpEarlyDataLogic)++ return (+ <Card title="What agents are trying to do">+ {intentDigest?.digest ? (+ <div className="flex flex-col gap-2">+ <p className="text-base m-0">{intentDigest.digest}</p>+ <span className="text-muted text-sm">+ AI summary of the last {formatNumber(intentDigest.intentCount)} agent intents+ </span>+ </div>+ ) : intentDigestLoading ? (+ <div className="flex flex-col gap-2">+ <LemonSkeleton className="h-4 w-full" />+ <LemonSkeleton className="h-4 w-5/6" />+ <LemonSkeleton className="h-4 w-2/3" />+ <span className="text-muted text-sm">Summarizing recent agent intents…</span>+ </div>+ ) : intentThemes.length === 0 ? (+ <span className="text-muted text-base">+ No agent intents captured yet — they show up here as agents explain what they're doing.+ </span>+ ) : (+ <div className="flex flex-col gap-2">+ <ul className="flex flex-col gap-2 m-0 pl-4">+ {intentThemes.map(({ intent, count }) => (+ <li key={intent} className="text-base">+ {intent}+ {count > 1 ? <span className="text-muted text-sm"> ×{count}</span> : null}+ </li>+ ))}+ </ul>+ <span className="text-muted text-sm">+ AI summary unavailable — showing the most recent intents verbatim.+ </span>+ </div>+ )}+ </Card>+ )+}++function ClientsCard(): JSX.Element {+ const { clients } = useValues(mcpEarlyDataLogic)+ const maxCalls = clients[0]?.calls ?? 0++ return (+ <Card title="Clients calling your server">+ {clients.length === 0 ? (+ <span className="text-muted text-base">No client info captured yet</span>+ ) : (+ <div className="flex flex-col gap-2">+ {clients.map((row) => (+ <div key={row.client}>+ <div className="flex justify-between text-base">+ <span className="flex items-center gap-1.5">+ <HarnessLogo category={guessHarnessLabel(row.client)} className="h-3.5 w-3.5" />+ {row.client}+ </span>+ <span className="text-muted">{formatNumber(row.calls)}</span>+ </div>+ <LemonProgress percent={maxCalls > 0 ? (row.calls / maxCalls) * 100 : 0} />+ </div>+ ))}+ </div>+ )}+ </Card>+ )+}++const CHECKLIST_ICONS: Record<ChecklistItem['status'], JSX.Element> = {+ ok: <IconCheckCircle className="text-success shrink-0 mt-0.5" />,+ warning: <IconWarning className="text-warning shrink-0 mt-0.5" />,+ pending: <IconClock className="text-muted shrink-0 mt-0.5" />,+}++function ChecklistCard(): JSX.Element {+ const { checklist } = useValues(mcpEarlyDataLogic)++ return (+ <Card title="Instrumentation checklist">+ <div className="flex flex-col gap-3">+ {checklist.map((item) => (+ <div key={item.key} className="flex gap-2">+ {CHECKLIST_ICONS[item.status]}+ <div>+ <div className="text-base font-medium">{item.title}</div>+ <div className="text-muted text-sm">+ {item.detail} {item.status !== 'ok' ? <Link to={item.docsUrl}>Learn more</Link> : null}+ </div>+ </div>+ </div>+ ))}+ </div>+ </Card>+ )+}diff --git a/products/mcp_analytics/frontend/earlyData/activitySummary.ts b/products/mcp_analytics/frontend/earlyData/activitySummary.tsnew file mode 100644index 000000000000..10ce8d77a458--- /dev/null+++ b/products/mcp_analytics/frontend/earlyData/activitySummary.ts@@ -0,0 +1,41 @@+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'++export interface ActivitySummaryInput {+ totalCalls: number+ distinctClients: number+ errorCalls: number+ /** The busiest tool's name, when known. */+ topTool: string | null+}++/**+ * The activity stage's "key metric" is a sentence, not a tile grid: at low+ * volume the user's question is "what are agents doing with my server?", and a+ * plain-language answer beats six sparse KPIs. Serves the same intro job as the+ * one-time first-look hero, but persistent and tailored to early data.+ */+export function buildActivitySummary(input: ActivitySummaryInput): string {+ const { totalCalls, distinctClients, errorCalls, topTool } = input++ if (totalCalls === 0) {+ return 'Waiting for your first tool call…'+ }+ if (totalCalls <= 5) {+ return totalCalls === 1+ ? "Your first tool call arrived — here's what the agent tried."+ : `Your first ${totalCalls} tool calls arrived — here's what agents tried.`+ }++ const parts = [`${humanFriendlyLargeNumber(totalCalls)} tool calls`]+ if (distinctClients > 0) {+ parts.push(`from ${distinctClients} client${distinctClients === 1 ? '' : 's'}`)+ }+ let summary = `${parts.join(' ')} so far`+ if (topTool) {+ summary += ` — ${topTool} is the favorite`+ }+ if (errorCalls > 0) {+ summary += `${topTool ? ',' : ' —'} ${errorCalls} failure${errorCalls === 1 ? '' : 's'} worth a look`+ }+ return summary+}diff --git a/products/mcp_analytics/frontend/earlyData/earlyData.test.ts b/products/mcp_analytics/frontend/earlyData/earlyData.test.tsnew file mode 100644index 000000000000..76c4fd8465a0--- /dev/null+++ b/products/mcp_analytics/frontend/earlyData/earlyData.test.ts@@ -0,0 +1,56 @@+import { buildActivitySummary } from './activitySummary'+import { buildChecklist, EarlyStats } from './earlyDataChecklist'++const stats = (overrides: Partial<EarlyStats>): EarlyStats => ({+ totalCalls: 0,+ distinctTools: 0,+ distinctSessions: 0,+ distinctClients: 0,+ callsWithIntent: 0,+ errorCalls: 0,+ missingCapabilityReports: 0,+ ...overrides,+})++describe('early data derivations', () => {+ it.each([+ // First calls get the celebratory copy, not a stats sentence.+ [{ totalCalls: 1, distinctClients: 1, errorCalls: 0, topTool: null }, /first tool call arrived/],+ [{ totalCalls: 4, distinctClients: 1, errorCalls: 1, topTool: 'search' }, /first 4 tool calls arrived/],+ // The full sentence composes favorite + failures with correct punctuation.+ [+ { totalCalls: 42, distinctClients: 3, errorCalls: 4, topTool: 'search_docs' },+ /^42 tool calls from 3 clients so far — search_docs is the favorite, 4 failures worth a look$/,+ ],+ // Failures read grammatically even without a favorite tool.+ [+ { totalCalls: 42, distinctClients: 0, errorCalls: 1, topTool: null },+ /^42 tool calls so far — 1 failure worth a look$/,+ ],+ [{ totalCalls: 42, distinctClients: 1, errorCalls: 0, topTool: null }, /^42 tool calls from 1 client so far$/],+ ])('summarizes %j', (input, expected) => {+ expect(buildActivitySummary(input)).toMatch(expected)+ })++ it.each([+ // Under 10 calls ratios are noise: hold judgment instead of warning.+ [stats({ totalCalls: 5, callsWithIntent: 0, distinctSessions: 5 }), 'pending', 'pending'],+ // Intent wired + sessions grouping: both healthy.+ [stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 8 }), 'ok', 'ok'],+ // No intent + one session per call (stateless server): both warn.+ [stats({ totalCalls: 40, callsWithIntent: 2, distinctSessions: 40 }), 'warning', 'warning'],+ // 90% of calls being sessions is already degenerate, not just 100%.+ [stats({ totalCalls: 100, callsWithIntent: 90, distinctSessions: 90 }), 'ok', 'warning'],+ ])('checklist grades intent/sessions for %j as %s/%s', (input, intentStatus, sessionsStatus) => {+ const checklist = buildChecklist(input)+ expect(checklist.find((i) => i.key === 'intent')?.status).toBe(intentStatus)+ expect(checklist.find((i) => i.key === 'sessions')?.status).toBe(sessionsStatus)+ })++ it('flips unmet-demand reporting to ok once any report exists', () => {+ expect(buildChecklist(stats({})).find((i) => i.key === 'missing-capability')?.status).toBe('pending')+ expect(+ buildChecklist(stats({ missingCapabilityReports: 2 })).find((i) => i.key === 'missing-capability')?.status+ ).toBe('ok')+ })+})diff --git a/products/mcp_analytics/frontend/earlyData/earlyDataChecklist.ts b/products/mcp_analytics/frontend/earlyData/earlyDataChecklist.tsnew file mode 100644index 000000000000..061e7a257a51--- /dev/null+++ b/products/mcp_analytics/frontend/earlyData/earlyDataChecklist.ts@@ -0,0 +1,78 @@+export interface EarlyStats {+ totalCalls: number+ distinctTools: number+ distinctSessions: number+ distinctClients: number+ callsWithIntent: number+ errorCalls: number+ missingCapabilityReports: number+}++export type ChecklistStatus = 'ok' | 'warning' | 'pending'++export interface ChecklistItem {+ key: string+ title: string+ detail: string+ status: ChecklistStatus+ docsUrl: string+}++const DOCS = {+ intent: 'https://posthog.com/docs/mcp-analytics/intent',+ conversationId: 'https://posthog.com/docs/mcp-analytics/conversation-id',+ missingCapability: 'https://posthog.com/docs/mcp-analytics/missing-capability',+}++/** Below this, instrumentation ratios are noise — hold judgment rather than warn. */+const MIN_CALLS_FOR_SIGNAL = 10++/**+ * Instrumentation-quality checks for the early-data view. At low volume, better+ * instrumentation is the highest-leverage thing a user can do — every later feature+ * (intent summaries, clustering, sessions) depends on these being wired correctly.+ */+export function buildChecklist(stats: EarlyStats): ChecklistItem[] {+ const enoughSignal = stats.totalCalls >= MIN_CALLS_FOR_SIGNAL++ const intentShare = stats.totalCalls > 0 ? stats.callsWithIntent / stats.totalCalls : 0+ const intentOk = intentShare >= 0.5++ // One session per call means no session state survives between calls+ // (stateless/serverless server) — sessions degrade to singletons.+ const sessionsDegenerate = enoughSignal && stats.distinctSessions >= Math.max(2, Math.floor(stats.totalCalls * 0.9))++ return [+ {+ key: 'intent',+ title: 'Intent capture',+ detail: intentOk+ ? `${Math.round(intentShare * 100)}% of tool calls carry agent intent.`+ : 'Few or no tool calls carry agent intent. Enable the context parameter so you can see what agents are trying to do.',+ status: !enoughSignal ? 'pending' : intentOk ? 'ok' : 'warning',+ docsUrl: DOCS.intent,+ },+ {+ key: 'sessions',+ title: 'Session stitching',+ // Deliberately informational: conversation IDs are opt-in (the echo-back loop+ // can read as prompt injection to some agents), so we describe the tradeoff+ // via docs instead of prescribing it.+ detail: sessionsDegenerate+ ? 'Almost every tool call starts a new session — typical for stateless or serverless servers. Session views will treat each call separately.'+ : 'Tool calls are grouping into sessions.',+ status: !enoughSignal ? 'pending' : sessionsDegenerate ? 'warning' : 'ok',+ docsUrl: DOCS.conversationId,+ },+ {+ key: 'missing-capability',+ title: 'Unmet demand reporting',+ detail:+ stats.missingCapabilityReports > 0+ ? `Agents have filed ${stats.missingCapabilityReports} missing-capability report${stats.missingCapabilityReports === 1 ? '' : 's'}.`+ : 'No missing-capability reports yet. Enable reportMissing so agents can tell you which tools they wish you had.',+ status: stats.missingCapabilityReports > 0 ? 'ok' : 'pending',+ docsUrl: DOCS.missingCapability,+ },+ ]+}diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.tsnew file mode 100644index 000000000000..e54bd3366e2f--- /dev/null+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts@@ -0,0 +1,200 @@+import { actions, afterMount, connect, kea, listeners, path, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { mcpAnalyticsSessionsActivityOverview, mcpAnalyticsSessionsIntentDigest } from '../generated/api'+import type { MCPActivityOverviewApi } from '../generated/api.schemas'+import { mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'+import { buildActivitySummary } from './activitySummary'+import { ChecklistItem, EarlyStats, buildChecklist } from './earlyDataChecklist'+import type { mcpEarlyDataLogicType } from './mcpEarlyDataLogicType'++export type { ChecklistItem, EarlyStats } from './earlyDataChecklist'++export interface EarlyRecentCall {+ timestamp: string+ tool: string+ intent: string | null+ isError: boolean+ /** Short human-readable error extracted from the tool's response, when the call failed. */+ errorMessage: string | null+ durationMs: number | null+ clientName: string | null+}++export interface IntentTheme {+ intent: string+ count: number+}++export interface IntentDigest {+ digest: string | null+ intentCount: number+}++export interface EarlyToolRow {+ tool: string+ calls: number+ errors: number+}++export interface EarlyClientRow {+ client: string+ calls: number+}++const EMPTY_STATS: EarlyStats = {+ totalCalls: 0,+ distinctTools: 0,+ distinctSessions: 0,+ distinctClients: 0,+ callsWithIntent: 0,+ errorCalls: 0,+ missingCapabilityReports: 0,+}++// Refresh cadence for the early view. Slower than the onboarding signal poll: the+// overview aggregates 30 days of property-reading queries server-side, and "within+// a minute" is live enough.+const REFRESH_INTERVAL_MS = 60000++export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([+ path(['products', 'mcp_analytics', 'frontend', 'earlyData', 'mcpEarlyDataLogic']),+ connect(() => ({+ values: [mcpAnalyticsOnboardingLogic, ['signals'], teamLogic, ['currentProjectId']],+ // loadSignals is dispatched from refreshAll so the summary's totalCalls+ // (max of both sources) advances together with the overview.+ actions: [mcpAnalyticsOnboardingLogic, ['loadSignals']],+ })),+ actions({+ refreshAll: true,+ }),+ loaders(({ values }) => ({+ intentDigest: {+ __default: null as IntentDigest | null,+ loadIntentDigest: async (_: void, breakpoint): Promise<IntentDigest | null> => {+ if (!values.currentProjectId) {+ return null+ }+ try {+ const response = await mcpAnalyticsSessionsIntentDigest(String(values.currentProjectId))+ breakpoint()+ return { digest: response.digest, intentCount: response.intent_count }+ } catch {+ // LLM unconfigured (503) or transient failure — the card falls back+ // to the verbatim intent list.+ return null+ }+ },+ },+ overview: {+ __default: null as MCPActivityOverviewApi | null,+ loadOverview: async (_: void, breakpoint): Promise<MCPActivityOverviewApi | null> => {+ if (!values.currentProjectId) {+ return null+ }+ const response = await mcpAnalyticsSessionsActivityOverview(String(values.currentProjectId))+ breakpoint()+ return response+ },+ },+ })),+ selectors({+ stats: [+ (s) => [s.overview],+ (overview): EarlyStats =>+ overview+ ? {+ totalCalls: overview.stats.total_calls,+ distinctTools: overview.stats.distinct_tools,+ distinctSessions: overview.stats.distinct_sessions,+ distinctClients: overview.stats.distinct_clients,+ callsWithIntent: overview.stats.calls_with_intent,+ errorCalls: overview.stats.error_calls,+ missingCapabilityReports: overview.stats.missing_capability_reports,+ }+ : EMPTY_STATS,+ ],+ topTools: [+ (s) => [s.overview],+ (overview): EarlyToolRow[] =>+ (overview?.top_tools ?? []).map((row) => ({ tool: row.tool, calls: row.calls, errors: row.errors })),+ ],+ clients: [+ (s) => [s.overview],+ (overview): EarlyClientRow[] =>+ (overview?.clients ?? []).map((row) => ({ client: row.client || 'Unknown client', calls: row.calls })),+ ],+ recentCalls: [+ (s) => [s.overview],+ (overview): EarlyRecentCall[] =>+ (overview?.recent_calls ?? []).map((row) => ({+ timestamp: row.timestamp,+ tool: row.tool,+ intent: row.intent,+ isError: row.is_error,+ errorMessage: row.error_message,+ durationMs: row.duration_ms,+ clientName: row.client_name,+ })),+ ],+ // The onboarding signal poll and the overview query run on different cadences,+ // so during active ingestion they can briefly disagree. One number drives+ // the summary so the view never contradicts itself.+ totalCalls: [+ (s) => [s.signals, s.stats],+ (signals, stats): number => Math.max(stats.totalCalls, signals?.toolCallsTotal ?? 0),+ ],+ summary: [+ (s) => [s.totalCalls, s.stats, s.topTools],+ (totalCalls, stats, topTools): string =>+ buildActivitySummary({+ totalCalls,+ distinctClients: stats.distinctClients,+ errorCalls: stats.errorCalls,+ topTool: totalCalls > 10 ? (topTools[0]?.tool ?? null) : null,+ }),+ ],+ // Verbatim agent intents grouped by frequency — the fallback when no AI+ // digest is available. At low volume, reading what agents actually tried+ // beats any lossy aggregation of it.+ intentThemes: [+ (s) => [s.recentCalls],+ (recentCalls): IntentTheme[] => {+ const counts = new Map<string, number>()+ for (const call of recentCalls) {+ if (call.intent) {+ counts.set(call.intent, (counts.get(call.intent) ?? 0) + 1)+ }+ }+ return [...counts.entries()]+ .map(([intent, count]) => ({ intent, count }))+ .sort((a, b) => b.count - a.count)+ .slice(0, 6)+ },+ ],+ checklist: [(s) => [s.stats], (stats): ChecklistItem[] => buildChecklist(stats)],+ isRefreshing: [+ (s) => [s.overviewLoading, s.intentDigestLoading],+ (overviewLoading, intentDigestLoading): boolean => overviewLoading || intentDigestLoading,+ ],+ }),+ listeners(({ actions }) => ({+ refreshAll: () => {+ actions.loadSignals()+ actions.loadOverview()+ // Server-side the digest is content-addressed, so this only reaches the+ // LLM when new intents have actually arrived.+ actions.loadIntentDigest()+ },+ })),+ afterMount(({ actions, cache }) => {+ actions.loadOverview()+ actions.loadIntentDigest()+ cache.disposables.add(() => {+ const id = window.setInterval(() => actions.refreshAll(), REFRESH_INTERVAL_MS)+ return () => clearInterval(id)+ }, 'refresh')+ }),+])diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.tsindex 950cb8d8b90f..75ca7824bdeb 100644--- a/products/mcp_analytics/frontend/generated/api.schemas.ts+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts@@ -372,6 +372,89 @@ export interface PaginatedMCPToolCallListApi {has_next: boolean}+export interface MCPActivityStatsApi {+ /** $mcp_tool_call events captured in the last 30 days. */+ readonly total_calls: number+ /** Distinct tools ($mcp_tool_name) called in the window. */+ readonly distinct_tools: number+ /** Distinct $session_ids seen on tool calls in the window. */+ readonly distinct_sessions: number+ /** Distinct agent clients ($mcp_client_name) seen in the window. */+ readonly distinct_clients: number+ /** Tool calls that carried an $mcp_intent, for intent-coverage checks. */+ readonly calls_with_intent: number+ /** Tool calls flagged as errors ($mcp_is_error) in the window. */+ readonly error_calls: number+ /** $mcp_missing_capability events captured in the window. */+ readonly missing_capability_reports: number+}++export interface MCPActivityToolRowApi {+ /** MCP tool name ($mcp_tool_name). */+ readonly tool: string+ /** Tool calls in the window. */+ readonly calls: number+ /** Of those calls, how many errored. */+ readonly errors: number+}++export interface MCPActivityClientRowApi {+ /** Agent client name ($mcp_client_name). Empty when the SDK did not capture it. */+ readonly client: string+ /** Tool calls from this client in the window. */+ readonly calls: number+}++export interface MCPActivityRecentCallApi {+ /** When the tool call was captured. */+ readonly timestamp: string+ /** Tool that was invoked ($mcp_tool_name). */+ readonly tool: string+ /**+ * Agent intent for this tool call ($mcp_intent). Null when the SDK did not capture context.+ * @nullable+ */+ readonly intent: string | null+ /** Whether the tool call resulted in an error. */+ readonly is_error: boolean+ /**+ * Human-readable error extracted from the tool's response when is_error is true, otherwise null.+ * @nullable+ */+ readonly error_message: string | null+ /**+ * Duration of the tool call in milliseconds when captured.+ * @nullable+ */+ readonly duration_ms: number | null+ /**+ * Agent client name ($mcp_client_name) when captured.+ * @nullable+ */+ readonly client_name: string | null+}++export interface MCPActivityOverviewApi {+ /** Aggregate counters over the last 30 days. */+ readonly stats: MCPActivityStatsApi+ /** Most-called tools in the window, top 5 by call count. */+ readonly top_tools: readonly MCPActivityToolRowApi[]+ /** Agent clients in the window, top 6 by call count. */+ readonly clients: readonly MCPActivityClientRowApi[]+ /** The 20 most recent tool calls, newest first. */+ readonly recent_calls: readonly MCPActivityRecentCallApi[]+}++export interface MCPIntentDigestApi {+ /**+ * LLM-generated digest (at most three sentences) of what agents are trying to do with this MCP server, derived from the most recent recorded $mcp_intents across all sessions. Null when the project has no recorded intents yet.+ * @nullable+ */+ readonly digest: string | null+ /** How many recorded intents (the most recent, capped at 100) the digest was derived from. */+ readonly intent_count: number+}+export type McpAnalyticsFeedbackListParams = {/*** Number of results to return per page.diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.tsindex 7aef539a5424..ef5bdda7bba9 100644--- a/products/mcp_analytics/frontend/generated/api.ts+++ b/products/mcp_analytics/frontend/generated/api.ts@@ -9,9 +9,11 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ MCPActivityOverviewApi,MCPAnalyticsSubmissionApi,MCPFeedbackCreateApi,MCPIntentClusterSnapshotApi,+ MCPIntentDigestApi,MCPMissingCapabilityCreateApi,MCPSessionIntentApi,McpAnalyticsFeedbackListParams,@@ -263,3 +265,37 @@ export const mcpAnalyticsSessionsToolCalls = async (method: 'GET',})}++export const getMcpAnalyticsSessionsActivityOverviewUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_analytics/sessions/activity_overview/`+}++/**+ * Aggregate counters, top tools, agent clients, and the most recent tool calls for the last 30 days, computed in one request. Powers the dashboard's activity view; always computed fresh so polling callers watch data arrive.+ */+export const mcpAnalyticsSessionsActivityOverview = async (+ projectId: string,+ options?: RequestInit+): Promise<MCPActivityOverviewApi> => {+ return apiMutator<MCPActivityOverviewApi>(getMcpAnalyticsSessionsActivityOverviewUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getMcpAnalyticsSessionsIntentDigestUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_analytics/sessions/intent_digest/`+}++/**+ * Generate (or return the cached) LLM digest of what agents are trying to do with this MCP server, derived from the most recent recorded $mcp_intents across all sessions. Content-addressed cache: only regenerates when new intents arrive. Powers the dashboard's low-volume activity stage.+ */+export const mcpAnalyticsSessionsIntentDigest = async (+ projectId: string,+ options?: RequestInit+): Promise<MCPIntentDigestApi> => {+ return apiMutator<MCPIntentDigestApi>(getMcpAnalyticsSessionsIntentDigestUrl(projectId), {+ ...options,+ method: 'POST',+ })+}diff --git a/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.tsindex 924004e4baf3..c4e44aea6453 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.ts@@ -10,6 +10,7 @@ jest.mock('lib/api')const mockApi = api as jest.Mocked<typeof api>+// Signal row shape: [has_initialize, tool_calls_total, tool_calls_7d, first_call_at]describe('mcpAnalyticsOnboardingLogic', () => {beforeEach(() => {jest.clearAllMocks()@@ -24,7 +25,7 @@ describe('mcpAnalyticsOnboardingLogic', () => {}it('forces a fresh calculation so an ingestion-gap cached [0,0] never sticks', async () => {- const logic = mountWith([[1, 1]])+ const logic = mountWith([[1, 1, 1, '2026-07-01T00:00:00Z']])await expectLogic(logic).toFinishAllListeners()// The onboarding poll must bypass the cache (force_blocking). Otherwise a// pre-ingestion [0,0] cached during the capture->queryable gap keeps the page@@ -33,9 +34,9 @@ describe('mcpAnalyticsOnboardingLogic', () => {})it.each([- [[[1, 1]], 'onboarded'],- [[[1, 0]], 'connected-no-calls'],- [[[0, 0]], 'not-instrumented'],+ [[[1, 1, 1, '2026-07-01T00:00:00Z']], 'onboarded'],+ [[[1, 0, 0, '1970-01-01T00:00:00Z']], 'connected-no-calls'],+ [[[0, 0, 0, '1970-01-01T00:00:00Z']], 'not-instrumented'],])('maps signal row %j to state %s', async (results, expected) => {const logic = mountWith(results)await expectLogic(logic).toFinishAllListeners()@@ -44,8 +45,28 @@ describe('mcpAnalyticsOnboardingLogic', () => {})it('treats a stringified "0" as false (no false-positive onboarding)', async () => {- const logic = mountWith([['0', '0']])+ const logic = mountWith([['0', '0', '0', '1970-01-01T00:00:00Z']])await expectLogic(logic).toFinishAllListeners()expect(logic.values.onboardingState).toBe('not-instrumented')})++ it.each([+ // Below both thresholds: the live-feed activity stage.+ [1, 1, 'activity'],+ [299, 100, 'activity'],+ // Lifetime volume unlocks metrics even with a quiet week.+ [300, 0, 'metrics'],+ // Sustained density unlocks metrics even with low lifetime volume.+ [260, 250, 'metrics'],+ ])('stages %i lifetime / %i weekly calls as %s', async (total, last7d, expected) => {+ const logic = mountWith([[1, total, last7d, '2026-07-01T00:00:00Z']])+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.dashboardStage).toBe(expected)+ })++ it('discards the epoch sentinel minIf() returns when there are no tool calls', async () => {+ const logic = mountWith([[1, 0, 0, '1970-01-01T00:00:00Z']])+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.signals?.firstCallAt).toBeNull()+ })})diff --git a/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.tsindex 852085434d5f..2d1c61f06b72 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts@@ -7,32 +7,57 @@ import { addProductIntent } from 'lib/utils/product-intents'import { HogQLQueryResponse, NodeKind, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import type { mcpAnalyticsOnboardingLogicType } from './mcpAnalyticsOnboardingLogicType'+import { asNumber } from './queryResultParsers'export type MCPOnboardingState = 'not-instrumented' | 'connected-no-calls' | 'onboarded'+/**+ * Which question the dashboard answers, by volume. `activity` is for "what are+ * agents doing with my server?" — a live feed, verbatim intents, and an+ * instrumentation checklist; windowed metrics would be noise at this volume.+ * `metrics` is the standard dashboard for "is it healthy?". Volume-gated rather+ * than time-gated so a low-traffic server never regresses to an empty dashboard.+ */+export type MCPDashboardStage = 'activity' | 'metrics'++/** Metrics and trends unlock on lifetime volume… */+export const METRICS_UNLOCK_LIFETIME_CALLS = 300+/** …or on sustained density, whichever comes first. */+export const METRICS_UNLOCK_7D_CALLS = 250+export interface MCPOnboardingSignals {/** A client has completed the MCP handshake — proves the SDK wrap is live. */hasInitialize: boolean/** A tool has actually been called — the server is in use. */hasToolCall: boolean+ /** Lifetime `$mcp_tool_call` count — drives the activity/metrics stage gate. */+ toolCallsTotal: number+ /** `$mcp_tool_call` count over the last 7 days — the density half of the gate. */+ toolCalls7d: number+ /** Timestamp of the first tool call, for "since June 30" copy. Null before the first call. */+ firstCallAt: string | null}-// Two-signal funnel over all history. `$mcp_initialize` fires when an agent-// connects (before any tool call), so it distinguishes "instrumented but no-// traffic yet" from "not instrumented at all" — without it, a freshly-wired-// server that hasn't been called looks identical to one that was never set up.-// Filtering on the two event names hits the events sort key, so this stays cheap.+// Signal funnel over all history. `$mcp_initialize` fires when an agent connects+// (before any tool call), so it distinguishes "instrumented but no traffic yet"+// from "not instrumented at all". Counts (not booleans) so the same query drives+// the activity/metrics stage gate. Deliberately no `properties.*` access: event-name ++// timestamp filters hit the events sort key, so this stays cheap even on projects+// with millions of MCP events — property-derived stats live in mcpEarlyDataLogic,+// whose queries are time-bounded.const ONBOARDING_SIGNAL_QUERY = `SELECTcountIf(event = '$mcp_initialize') > 0 AS has_initialize,- countIf(event = '$mcp_tool_call') > 0 AS has_tool_call+ countIf(event = '$mcp_tool_call') AS tool_calls_total,+ countIf(event = '$mcp_tool_call' AND timestamp >= now() - INTERVAL 7 DAY) AS tool_calls_7d,+ minIf(timestamp, event = '$mcp_tool_call') AS first_call_atFROM eventsWHERE event IN ('$mcp_initialize', '$mcp_tool_call')`-// While the user is still onboarding we re-check on a timer so the page flips to-// the dashboard on its own the moment the first events land. The disposables-// plugin pauses this on hidden tabs and tears it down on unmount.+// While the user is onboarding (or watching the activity stage fill in) we re-check+// on a timer so the page advances on its own as events land. The disposables plugin+// pauses this on hidden tabs and tears it down on unmount.const POLL_INTERVAL_MS = 20000export const mcpAnalyticsOnboardingLogic = kea<mcpAnalyticsOnboardingLogicType>([@@ -46,9 +71,10 @@ export const mcpAnalyticsOnboardingLogic = kea<mcpAnalyticsOnboardingLogicType>(// during that gap caches `[0,0]` — and with the default cache TTL the page// would then keep serving that stale "not onboarded" answer for up to a// minute after the data is actually queryable, dulling the "you're connected!"- // moment. Forcing keeps the flip near-instant. Polling stops as soon as we're- // onboarded (see loadSignalsSuccess), so this is bounded to the onboarding- // window, and the query itself is cheap (two event-name counts on the sort key).+ // moment. Forcing keeps the flip near-instant. Polling stops once the project+ // graduates to the full dashboard (see loadSignalsSuccess), so this is bounded+ // to the onboarding + activity window, and the query itself is cheap (event-name+ // counts on the sort key).const response = (await api.query({kind: NodeKind.HogQLQuery,@@ -58,10 +84,16 @@ export const mcpAnalyticsOnboardingLogic = kea<mcpAnalyticsOnboardingLogicType>()) as HogQLQueryResponsebreakpoint()const row = (response?.results?.[0] as unknown[] | undefined) ?? []- // ClickHouse returns the `> 0` comparisons as 0/1; coerce numerically so a- // stringified "0" can never read as truthy (Boolean("0") would).- const truthy = (value: unknown): boolean => Number(value) > 0- return { hasInitialize: truthy(row[0]), hasToolCall: truthy(row[1]) }+ const toolCallsTotal = asNumber(row[1])+ return {+ hasInitialize: asNumber(row[0]) > 0,+ hasToolCall: toolCallsTotal > 0,+ toolCallsTotal,+ toolCalls7d: asNumber(row[2]),+ // minIf() returns the epoch sentinel when nothing matched — only trust it+ // once we know at least one call exists.+ firstCallAt: toolCallsTotal > 0 && typeof row[3] === 'string' ? row[3] : null,+ }},},}),@@ -82,6 +114,18 @@ export const mcpAnalyticsOnboardingLogic = kea<mcpAnalyticsOnboardingLogicType>(},],isOnboarded: [(s) => [s.onboardingState], (onboardingState): boolean => onboardingState === 'onboarded'],+ dashboardStage: [+ (s) => [s.signals],+ (signals): MCPDashboardStage | null => {+ if (!signals || !signals.hasToolCall) {+ return null+ }+ return signals.toolCallsTotal >= METRICS_UNLOCK_LIFETIME_CALLS ||+ signals.toolCalls7d >= METRICS_UNLOCK_7D_CALLS+ ? 'metrics'+ : 'activity'+ },+ ],}),listeners(({ values, cache }) => ({loadSignalsSuccess: () => {@@ -96,8 +140,9 @@ export const mcpAnalyticsOnboardingLogic = kea<mcpAnalyticsOnboardingLogicType>(intent_context: ProductIntentContext.MCP_ANALYTICS_CONNECTED,})}- // Once tool calls show up the gate flips for good — stop polling.- if (values.isOnboarded) {+ // Keep polling through the activity stage so the summary advances live;+ // stop for good once the volume gate graduates the project to metrics.+ if (values.dashboardStage === 'metrics') {cache.disposables.dispose('poll')}},diff --git a/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.tsindex 534bb388306b..c7a0ba4062a0 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts@@ -1,5 +1,5 @@import { connect, kea, listeners, path, selectors } from 'kea'-import { router } from 'kea-router'+import { combineUrl, router } from 'kea-router'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -11,9 +11,10 @@ import { OnboardingStepKey } from '~/types'import { mcpAnalyticsOnboardingLogic } from './mcpAnalyticsOnboardingLogic'import type { mcpAnalyticsSceneLogicType } from './mcpAnalyticsSceneLogicType'-export type MCPAnalyticsTab = 'dashboard' | 'sessions' | 'tool-quality' | 'intent-clustering'+export type MCPAnalyticsTab = 'activity' | 'dashboard' | 'sessions' | 'tool-quality' | 'intent-clustering'export const TAB_DESCRIPTIONS: Record<MCPAnalyticsTab, string> = {+ activity: 'Live feed of tool calls and what agents are trying to do with your MCP server.',dashboard: 'Tool call volume, error rates, and latency across your MCP server.',sessions: 'Sessions where users interacted with your MCP tools.','tool-quality': 'Understand how reliably your MCP tools support user workflows.',@@ -23,6 +24,8 @@ export const TAB_DESCRIPTIONS: Record<MCPAnalyticsTab, string> = {// Per-tab question seeded into PostHog AI so the answer is grounded in what the user is looking at.export const TAB_AI_PROMPTS: Record<MCPAnalyticsTab, string> = {+ activity:+ 'What have agents done with my MCP server recently? Look at the latest $mcp_tool_call events — tools, intents, failures.',dashboard:"Summarize how agents are using my MCP server from $mcp_tool_call events — top tools, error rates, and what they're trying to do.",sessions:@@ -34,6 +37,7 @@ export const TAB_AI_PROMPTS: Record<MCPAnalyticsTab, string> = {}const SCENE_KEY_TO_TAB: Record<string, MCPAnalyticsTab> = {+ mcpAnalyticsActivity: 'activity',mcpAnalyticsDashboard: 'dashboard',mcpAnalyticsSessions: 'sessions',mcpAnalyticsToolQuality: 'tool-quality',@@ -58,7 +62,7 @@ export const mcpAnalyticsSceneLogic = kea<mcpAnalyticsSceneLogicType>([(sceneKey: string): MCPAnalyticsTab => SCENE_KEY_TO_TAB[sceneKey] ?? 'dashboard',],}),- listeners(({ values }) => ({+ listeners(({ values, cache }) => ({// Send never-set-up projects straight into the polished onboarding flow,// rather than the bare in-scene card. Guarded on `has_completed_onboarding_for`// so the post-onboarding return to the dashboard doesn't bounce back here —@@ -69,6 +73,19 @@ export const mcpAnalyticsSceneLogic = kea<mcpAnalyticsSceneLogicType>([router.actions.replace(urls.onboarding({ productKey: ProductKey.MCP_ANALYTICS, stepKey: OnboardingStepKey.INSTALL }))+ return+ }+ // Volume decides the default landing tab. Only fires when the manifest's+ // bare-URL redirect tagged the navigation with `landing=auto` — a deep link+ // to /dashboard never re-routes, and an explicit tab click is never overridden.+ const { landing, ...restParams } = router.values.searchParams+ if (landing === 'auto' && values.activeTab === 'dashboard' && !cache.landingResolved) {+ cache.landingResolved = true+ const target =+ mcpAnalyticsOnboardingLogic.values.dashboardStage === 'activity'+ ? urls.mcpAnalyticsActivity()+ : urls.mcpAnalyticsDashboard()+ router.actions.replace(combineUrl(target, restParams).url)}},})),diff --git a/products/mcp_analytics/frontend/queryResultParsers.ts b/products/mcp_analytics/frontend/queryResultParsers.tsnew file mode 100644index 000000000000..be75f4c9eb9a--- /dev/null+++ b/products/mcp_analytics/frontend/queryResultParsers.ts@@ -0,0 +1,4 @@+// HogQL results arrive untyped; ClickHouse returns booleans as 0/1 and numbers+// possibly stringified. Coerce numerically so a stringified "0" can never read+// as truthy.+export const asNumber = (value: unknown): number => Number(value) || 0diff --git a/products/mcp_analytics/manifest.tsx b/products/mcp_analytics/manifest.tsxindex 97582e5b1b41..a937afb63391 100644--- a/products/mcp_analytics/manifest.tsx+++ b/products/mcp_analytics/manifest.tsx@@ -35,6 +35,7 @@ export const manifest: ProductManifest = {},routes: {// Define routes here+ '/mcp-analytics/activity': ['MCPAnalytics', 'mcpAnalyticsActivity'],'/mcp-analytics/dashboard': ['MCPAnalytics', 'mcpAnalyticsDashboard'],'/mcp-analytics/sessions': ['MCPAnalytics', 'mcpAnalyticsSessions'],'/mcp-analytics/tool-quality': ['MCPAnalytics', 'mcpAnalyticsToolQuality'],@@ -42,11 +43,14 @@ export const manifest: ProductManifest = {'/mcp-analytics/intent-clustering': ['MCPAnalytics', 'mcpAnalyticsIntentClustering'],},redirects: {+ // `landing=auto` marks "arrived via the bare URL": the scene resolves it to the+ // volume-appropriate default tab, and deep links to /dashboard stay untouched.'/mcp-analytics': (_params, searchParams, hashParams) =>- combineUrl(urls.mcpAnalyticsDashboard(), searchParams, hashParams).url,+ combineUrl(urls.mcpAnalyticsDashboard(), { ...searchParams, landing: 'auto' }, hashParams).url,},urls: {// Define URL helpers here+ mcpAnalyticsActivity: (): string => '/mcp-analytics/activity',mcpAnalyticsDashboard: (): string => '/mcp-analytics/dashboard',mcpAnalyticsSessions: (): string => '/mcp-analytics/sessions',mcpAnalyticsToolQuality: (): string => '/mcp-analytics/tool-quality',diff --git a/products/mcp_analytics/mcp/tools.yaml b/products/mcp_analytics/mcp/tools.yamlindex 99d64642fd0f..8c4a90eae8f9 100644--- a/products/mcp_analytics/mcp/tools.yaml+++ b/products/mcp_analytics/mcp/tools.yaml@@ -40,6 +40,9 @@ tools:with its tool distribution, error rate, routing entropy, and journey paths. Returns an empty idle snapshotwhen no clustering run has happened yet — trigger one with mcp-analytics-intent-clusters-recompute.feature_flag: mcp-analytics+ mcp-analytics-sessions-activity-overview:+ operation: mcp_analytics_sessions_activity_overview+ enabled: falsemcp-analytics-sessions-generate-intent:operation: mcp_analytics_sessions_generate_intentenabled: true@@ -56,6 +59,9 @@ tools:summary.requires_ai_consent: truefeature_flag: mcp-analytics+ mcp-analytics-sessions-intent-digest:+ operation: mcp_analytics_sessions_intent_digest+ enabled: falsemcp-analytics-sessions-list:operation: mcp_analytics_sessions_listenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 82db6a070fe5..f33c08065e1a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -30432,6 +30432,79 @@ export namespace Schemas {readonly updated_at: string | null;}+ export interface MCPActivityClientRow {+ /** Agent client name ($mcp_client_name). Empty when the SDK did not capture it. */+ readonly client: string;+ /** Tool calls from this client in the window. */+ readonly calls: number;+ }++ export interface MCPActivityStats {+ /** $mcp_tool_call events captured in the last 30 days. */+ readonly total_calls: number;+ /** Distinct tools ($mcp_tool_name) called in the window. */+ readonly distinct_tools: number;+ /** Distinct $session_ids seen on tool calls in the window. */+ readonly distinct_sessions: number;+ /** Distinct agent clients ($mcp_client_name) seen in the window. */+ readonly distinct_clients: number;+ /** Tool calls that carried an $mcp_intent, for intent-coverage checks. */+ readonly calls_with_intent: number;+ /** Tool calls flagged as errors ($mcp_is_error) in the window. */+ readonly error_calls: number;+ /** $mcp_missing_capability events captured in the window. */+ readonly missing_capability_reports: number;+ }++ export interface MCPActivityToolRow {+ /** MCP tool name ($mcp_tool_name). */+ readonly tool: string;+ /** Tool calls in the window. */+ readonly calls: number;+ /** Of those calls, how many errored. */+ readonly errors: number;+ }++ export interface MCPActivityRecentCall {+ /** When the tool call was captured. */+ readonly timestamp: string;+ /** Tool that was invoked ($mcp_tool_name). */+ readonly tool: string;+ /**+ * Agent intent for this tool call ($mcp_intent). Null when the SDK did not capture context.+ * @nullable+ */+ readonly intent: string | null;+ /** Whether the tool call resulted in an error. */+ readonly is_error: boolean;+ /**+ * Human-readable error extracted from the tool's response when is_error is true, otherwise null.+ * @nullable+ */+ readonly error_message: string | null;+ /**+ * Duration of the tool call in milliseconds when captured.+ * @nullable+ */+ readonly duration_ms: number | null;+ /**+ * Agent client name ($mcp_client_name) when captured.+ * @nullable+ */+ readonly client_name: string | null;+ }++ export interface MCPActivityOverview {+ /** Aggregate counters over the last 30 days. */+ readonly stats: MCPActivityStats;+ /** Most-called tools in the window, top 5 by call count. */+ readonly top_tools: readonly MCPActivityToolRow[];+ /** Agent clients in the window, top 6 by call count. */+ readonly clients: readonly MCPActivityClientRow[];+ /** The 20 most recent tool calls, newest first. */+ readonly recent_calls: readonly MCPActivityRecentCall[];+ }+/*** * `feedback` - Feedback* * `missing_capability` - Missing capability@@ -30687,6 +30760,16 @@ export namespace Schemas {readonly computed_with: MCPIntentClusterSnapshotMeta | null;}+ export interface MCPIntentDigest {+ /**+ * LLM-generated digest (at most three sentences) of what agents are trying to do with this MCP server, derived from the most recent recorded $mcp_intents across all sessions. Null when the project has no recorded intents yet.+ * @nullable+ */+ readonly digest: string | null;+ /** How many recorded intents (the most recent, capped at 100) the digest was derived from. */+ readonly intent_count: number;+ }+export interface MCPMissingCapabilityCreate {/*** The tool the user tried before leaving feedback, if known.