: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): surface trending tools on tool quality (#106040)
Lucas Fariaf8a03141b0ea
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6f9094a2a952..6956221f2b4c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10273,9 +10273,9 @@ snapshots:scenes-app-mcp-analytics--sessions--light:hash: v1.k794b7964.d2363c5259b989b50bf770f821715c3782dbb35641a7f308555f31198583e392.OgecAQt-4DF27Tyv3e7qfOkwpT6kDr1sSuN-9OS0iAMscenes-app-mcp-analytics--tool-quality--dark:- hash: v1.k794b7964.3ad8d8cd5279b4a71f6c5f92cae80fa1b23ab125c30a1ca04b1f3b7ee7a9c8f0.08GjLTK6WJtlxDfcmYZhOKAsud2lE7V4CakPEJ0hjjA+ hash: v1.k794b7964.32dd20a9e219241b31e4a8e2b5d215f355793c9fe8273721c0ed8ba7bcdd35a2.1qt6pH0OhiHa-algJ0wt0xzUqqVUIuwewEGCHgtzRKIscenes-app-mcp-analytics--tool-quality--light:- hash: v1.k794b7964.4e8b2fca4956be4651ecd15ec8ad844b1826118d6f5d59a2863567635e78946d.NGRUE9aboCDK--rhOUUwTQdBBRPlimxuvYz34uOc54o+ hash: v1.k794b7964.303e6787271f98d787a49c93a381e370753c4e17ddb566324d856d9fc9db6a4d.0G4z2IuMALIvTPtVicec5BXwMA7cuum_zYLb0aEH4PAscenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--dark:hash: v1.k794b7964.7302f068e1b6a63086ac35ffb7e7e1b9d10b8608cb7c6bb7033d341638e2d695.51PNQHMCZinl1fgHrAFmryj0im81JG1jIjU-DQc0oPYscenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--light:diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex a3de9e9639e5..24f7ef41692c 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -11598,6 +11598,10 @@"$ref": "#/definitions/integer","description": "Number of tools matching the date, category, and search filters."},+ "totalSessions": {+ "$ref": "#/definitions/integer",+ "description": "Distinct sessions with any tool call in the window, ignoring category and search filters. The denominator for each row's session share."+ },"used_data_warehouse_sources": {"description": "Connector-synced data warehouse sources referenced by this query, if any.","items": {@@ -11627,7 +11631,8 @@"next_allowed_client_refresh","results","timezone",- "totalCount"+ "totalCount",+ "totalSessions"],"type": "object"},@@ -33600,6 +33605,10 @@"p99_duration_ms": {"type": "number"},+ "previous_calls": {+ "$ref": "#/definitions/integer",+ "description": "Calls in the previous period: the same length of time right before the window, or for a to-date range (\"This month\") the same part of the previous unit."+ },"sessions": {"$ref": "#/definitions/integer"},@@ -33609,6 +33618,10 @@"total_calls": {"$ref": "#/definitions/integer"},+ "trend_score": {+ "description": "Sort key ranking growth relative to volume, so a small tool's spike doesn't outrank a large tool's surge. Not a percentage; only meaningful for ordering.",+ "type": "number"+ },"users": {"$ref": "#/definitions/integer"}@@ -33616,6 +33629,7 @@"required": ["tool","total_calls",+ "previous_calls","errors","error_rate_pct","p50_duration_ms",@@ -33624,7 +33638,8 @@"users","sessions","first_seen",- "last_seen"+ "last_seen",+ "trend_score"],"type": "object"},@@ -33737,6 +33752,10 @@"$ref": "#/definitions/integer","description": "Number of tools matching the date, category, and search filters."},+ "totalSessions": {+ "$ref": "#/definitions/integer",+ "description": "Distinct sessions with any tool call in the window, ignoring category and search filters. The denominator for each row's session share."+ },"used_data_warehouse_sources": {"description": "Connector-synced data warehouse sources referenced by this query, if any.","items": {@@ -33759,7 +33778,7 @@"type": "array"}},- "required": ["results", "totalCount"],+ "required": ["results", "totalCount", "totalSessions"],"type": "object"},"MCPToolQualitySortColumn": {@@ -33771,7 +33790,8 @@"p99_duration_ms","users","sessions",- "last_seen"+ "last_seen",+ "trend_score"],"type": "string"},@@ -48360,6 +48380,10 @@"$ref": "#/definitions/integer","description": "Number of tools matching the date, category, and search filters."},+ "totalSessions": {+ "$ref": "#/definitions/integer",+ "description": "Distinct sessions with any tool call in the window, ignoring category and search filters. The denominator for each row's session share."+ },"used_data_warehouse_sources": {"description": "Connector-synced data warehouse sources referenced by this query, if any.","items": {@@ -48382,7 +48406,7 @@"type": "array"}},- "required": ["results", "totalCount"],+ "required": ["results", "totalCount", "totalSessions"],"type": "object"},{diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 6f75d289560b..926495ee4dd9 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3735,6 +3735,8 @@ export type CachedMCPToolDailyStatsQueryResponse = CachedQueryResponse<MCPToolDaexport interface MCPToolQualityRowItem {tool: stringtotal_calls: integer+ /** Calls in the previous period: the same length of time right before the window, or for a to-date range ("This month") the same part of the previous unit. */+ previous_calls: integererrors: integererror_rate_pct: numberp50_duration_ms: number@@ -3744,6 +3746,9 @@ export interface MCPToolQualityRowItem {sessions: integerfirst_seen: stringlast_seen: string+ /** Sort key ranking growth relative to volume, so a small tool's spike doesn't outrank a+ * large tool's surge. Not a percentage; only meaningful for ordering. */+ trend_score: number}export type MCPToolQualitySortColumn =@@ -3755,6 +3760,7 @@ export type MCPToolQualitySortColumn =| 'users'| 'sessions'| 'last_seen'+ | 'trend_score'export type MCPToolQualitySortDirection = 'ASC' | 'DESC'@@ -3762,6 +3768,8 @@ export interface MCPToolQualityRowsQueryResponse extends AnalyticsQueryResponseBresults: MCPToolQualityRowItem[]/** Number of tools matching the date, category, and search filters. */totalCount: integer+ /** Distinct sessions with any tool call in the window, ignoring category and search filters. The denominator for each row's session share. */+ totalSessions: integer}/** One row per effective MCP tool name, with server-side search, sorting, and pagination. */diff --git a/posthog/schema.py b/posthog/schema.pyindex 5a584b0631a0..3ecadb3a349c 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -6089,9 +6089,25 @@ class MCPToolQualityRowItem(BaseModel):p50_duration_ms: floatp95_duration_ms: floatp99_duration_ms: float+ previous_calls: int = Field(+ ...,+ description=(+ "Calls in the previous period: the same length of time right before the"+ ' window, or for a to-date range ("This month") the same part of the'+ " previous unit."+ ),+ )sessions: inttool: strtotal_calls: int+ trend_score: float = Field(+ ...,+ description=(+ "Sort key ranking growth relative to volume, so a small tool's spike"+ " doesn't outrank a large tool's surge. Not a percentage; only meaningful"+ " for ordering."+ ),+ )users: int@@ -13193,6 +13209,13 @@ class CachedMCPToolQualityRowsQueryResponse(BaseModel):...,description="Number of tools matching the date, category, and search filters.",)+ totalSessions: int = Field(+ ...,+ description=(+ "Distinct sessions with any tool call in the window, ignoring category and"+ " search filters. The denominator for each row's session share."+ ),+ )used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(default=None,description=("Connector-synced data warehouse sources referenced by this query, if any."),@@ -19114,6 +19137,13 @@ class MCPToolQualityRowsQueryResponse(BaseModel):...,description="Number of tools matching the date, category, and search filters.",)+ totalSessions: int = Field(+ ...,+ description=(+ "Distinct sessions with any tool call in the window, ignoring category and"+ " search filters. The denominator for each row's session share."+ ),+ )used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(default=None,description=("Connector-synced data warehouse sources referenced by this query, if any."),@@ -24252,6 +24282,13 @@ class QueryResponseAlternative104(BaseModel):...,description="Number of tools matching the date, category, and search filters.",)+ totalSessions: int = Field(+ ...,+ description=(+ "Distinct sessions with any tool call in the window, ignoring category and"+ " search filters. The denominator for each row's session share."+ ),+ )used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(default=None,description=("Connector-synced data warehouse sources referenced by this query, if any."),diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 06b594ced8a6..5635bac4de9b 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -1823,6 +1823,7 @@ class MCPToolQualitySortColumn(StrEnum):USERS = "users"SESSIONS = "sessions"LAST_SEEN = "last_seen"+ TREND_SCORE = "trend_score"class MCPToolQualitySortDirection(StrEnum):diff --git a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.pyindex aa2d6ed7555d..0cf612d8b35d 100644--- a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py+++ b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py@@ -5,6 +5,7 @@ calls match the per-tool detail runners. Category queries use the event-supplied"""from collections.abc import Sequence+from datetime import datetimefrom functools import cached_propertyfrom typing import TYPE_CHECKING, Literal, cast@@ -37,10 +38,12 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner-from posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.hogql_queries.utils.query_date_range import DateRangeBounds, QueryDateRange+from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRangefrom products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENTfrom products.mcp_analytics.backend.hogql_queries.base import (+ CONVERSATION_ID_SQL,EFFECTIVE_TOOL_SQL,mcp_query_date_range,shared_filter_exprs,@@ -70,7 +73,13 @@ _TOOL_SORT_COLUMNS = {"users","sessions","last_seen",+ "trend_score",}+# Smoothing for the trend sort key, (calls - previous) / (previous + k). Without it a tool going+# from 2 to 40 calls outranks one going from 200 to 5,000. k scales with overall volume so the+# same ranking holds for small and large projects.+_TREND_SCORE_MIN_K = 10+_TREND_SCORE_VOLUME_FRACTION = 0.0001def _category_in(categories: list[str] | None) -> list[ast.Expr]:@@ -85,8 +94,21 @@ def _category_in(categories: list[str] | None) -> list[ast.Expr]:]+def _within(date_from: ast.Expr, date_to: ast.Expr, *, exclusive_end: bool = False) -> ast.Expr:+ return parse_expr(+ "timestamp >= {date_from} AND timestamp < {date_to}"+ if exclusive_end+ else "timestamp >= {date_from} AND timestamp <= {date_to}",+ placeholders={"date_from": date_from, "date_to": date_to},+ )+++def _hogql_datetime(value: datetime) -> ast.Expr:+ return ast.Call(name="toDateTime", args=[ast.Constant(value=value.strftime("%Y-%m-%d %H:%M:%S"))])++def _named_tool_where(- date_range: QueryDateRange,+ time_window: ast.Expr,categories: list[str] | None,team: "Team",properties: "Sequence[AnyPropertyFilterDiscriminated] | None" = None,@@ -98,8 +120,7 @@ def _named_tool_where("""Apply tool-name filters before aggregation so non-matching events skip the percentile and distinct aggregates."""exprs: list[ast.Expr] = [parse_expr("event = {event}", placeholders={"event": ast.Constant(value=MCP_TOOL_CALL_EVENT)}),- parse_expr("timestamp >= {date_from}", placeholders={"date_from": date_range.date_from_as_hogql()}),- parse_expr("timestamp <= {date_to}", placeholders={"date_to": date_range.date_to_as_hogql()}),+ time_window,parse_expr("{tool} IS NOT NULL", placeholders={"tool": parse_expr(EFFECTIVE_TOOL_SQL)}),parse_expr("{tool} != ''", placeholders={"tool": parse_expr(EFFECTIVE_TOOL_SQL)}),*_category_in(categories),@@ -139,6 +160,22 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuerydef query_date_range(self) -> QueryDateRange:return mcp_query_date_range(self.team, self.query.dateRange)+ @cached_property+ def previous_window(self) -> DateRangeBounds:+ """The period the Trend column compares against, as a half-open [date_from, date_to).++ To-date ranges ("This month") compare against the same part of the previous unit. Every+ other range compares against the same length of time right before the current window.+ """+ current_from = self.query_date_range.date_from()+ current_to = self.query_date_range.date_to()+ calendar = QueryPreviousPeriodDateRange(+ date_range=self.query.dateRange, team=self.team, interval=None, now=self.query_date_range.now_with_timezone+ ).previous_calendar_period(current_from, current_to)+ if calendar is not None:+ return calendar+ return DateRangeBounds(date_from=current_from - (current_to - current_from), date_to=current_from)+def to_query(self, *, limit_override: int | None = None, offset_override: int | None = None) -> ast.SelectQuery | ast.SelectSetQuery:@@ -151,36 +188,78 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuerysort_column = "total_calls"sort_direction = cast(Literal["ASC", "DESC"], self.query.sortDirection or "DESC")+ current_range = self.query_date_range+ previous = self.previous_window+query = parse_select("""SELECT- {_EFFECTIVE_TOOL} AS tool,- count() AS total_calls,- {_IS_ERROR} AS errors,- round({_IS_ERROR} * 100.0 / count(), 1) AS error_rate_pct,- {_P50} AS p50_duration_ms,- {_P95} AS p95_duration_ms,- {_P99} AS p99_duration_ms,- uniq(distinct_id) AS users,- countDistinctIf(toString(properties.$session_id), toString(properties.$session_id) != '') AS sessions,- min(timestamp) AS first_seen,- max(timestamp) AS last_seen,+ tool,+ total_calls,+ previous_calls,+ errors,+ round(errors * 100.0 / total_calls, 1) AS error_rate_pct,+ p50_duration_ms,+ p95_duration_ms,+ p99_duration_ms,+ users,+ sessions,+ first_seen,+ last_seen,+ (total_calls - previous_calls)+ / (previous_calls + greatest({_min_k}, round({_volume_fraction} * sum(total_calls) OVER ())))+ AS trend_score,count() OVER () AS total_count- FROM events- WHERE {where}- GROUP BY tool+ FROM (+ SELECT+ tool,+ countIf(is_current) AS total_calls,+ countIf(NOT is_current) AS previous_calls,+ countIf(is_current AND is_error) AS errors,+ round(quantileIf(0.5)(duration_ms, is_current)) AS p50_duration_ms,+ round(quantileIf(0.95)(duration_ms, is_current)) AS p95_duration_ms,+ round(quantileIf(0.99)(duration_ms, is_current)) AS p99_duration_ms,+ uniqIf(distinct_id, is_current) AS users,+ uniqIf(session_id, is_current) AS sessions,+ minIf(timestamp, is_current) AS first_seen,+ maxIf(timestamp, is_current) AS last_seen+ FROM (+ SELECT+ {_EFFECTIVE_TOOL} AS tool,+ timestamp >= {current_from} AS is_current,+ toBool(properties.$mcp_is_error) AS is_error,+ toFloat(properties.$mcp_duration_ms) AS duration_ms,+ nullIf({conversation_id}, '') AS session_id,+ distinct_id,+ timestamp+ FROM events+ WHERE {where}+ )+ GROUP BY tool+ HAVING countIf(is_current) > 0+ )ORDER BY total_calls DESC, tool ASCLIMIT {limit}OFFSET {offset}""",placeholders={"_EFFECTIVE_TOOL": parse_expr(EFFECTIVE_TOOL_SQL),- "_IS_ERROR": parse_expr(_IS_ERROR),- "_P50": parse_expr(_P50),- "_P95": parse_expr(_P95),- "_P99": parse_expr(_P99),+ "current_from": current_range.date_from_as_hogql(),+ "conversation_id": parse_expr(CONVERSATION_ID_SQL),+ "_min_k": ast.Constant(value=_TREND_SCORE_MIN_K),+ "_volume_fraction": ast.Constant(value=_TREND_SCORE_VOLUME_FRACTION),+ # Scans only the two windows, so every row outside the current one is a previous call."where": _named_tool_where(- self.query_date_range,+ ast.Or(+ exprs=[+ _within(+ _hogql_datetime(previous.date_from),+ _hogql_datetime(previous.date_to),+ exclusive_end=True,+ ),+ _within(current_range.date_from_as_hogql(), current_range.date_to_as_hogql()),+ ]+ ),self.query.categories,self.team,self.query.properties,@@ -198,6 +277,26 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuery]return query+ def _total_sessions_query(self) -> ast.SelectQuery | ast.SelectSetQuery:+ # Ignores category and search so that narrowing the table does not turn a tool's share into 100%.+ return parse_select(+ """+ SELECT uniq(nullIf({conversation_id}, ''))+ FROM events+ WHERE {where}+ """,+ placeholders={+ "conversation_id": parse_expr(CONVERSATION_ID_SQL),+ "where": _named_tool_where(+ _within(self.query_date_range.date_from_as_hogql(), self.query_date_range.date_to_as_hogql()),+ None,+ self.team,+ self.query.properties,+ self.query.filterTestAccounts,+ ),+ },+ )+def _calculate(self) -> MCPToolQualityRowsQueryResponse:with tags_context(product=Product.MCP_ANALYTICS,@@ -215,7 +314,7 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuerylimit_context=self.limit_context,)rows = response.results or []- total_count = int(rows[0][11] or 0) if rows else 0+ total_count = int(rows[0][13] or 0) if rows else 0if not rows and (self.query.offset or 0) > 0:first_row_response = execute_hogql_query(query=self.to_query(limit_override=1, offset_override=0),@@ -227,26 +326,38 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuerylimit_context=self.limit_context,)first_row = first_row_response.results or []- total_count = int(first_row[0][11] or 0) if first_row else 0+ total_count = int(first_row[0][13] or 0) if first_row else 0+ total_sessions_response = execute_hogql_query(+ query=self._total_sessions_query(),+ team=self.team,+ user=self.user,+ query_type="mcp_tool_quality_total_sessions_query",+ timings=self.timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context,+ )results = [MCPToolQualityRowItem(tool=str(row[0] or ""),total_calls=int(row[1] or 0),- errors=int(row[2] or 0),- error_rate_pct=float(row[3] or 0),- p50_duration_ms=float(row[4] or 0),- p95_duration_ms=float(row[5] or 0),- p99_duration_ms=float(row[6] or 0),- users=int(row[7] or 0),- sessions=int(row[8] or 0),- first_seen=str(row[9] or ""),- last_seen=str(row[10] or ""),+ previous_calls=int(row[2] or 0),+ errors=int(row[3] or 0),+ error_rate_pct=float(row[4] or 0),+ p50_duration_ms=float(row[5] or 0),+ p95_duration_ms=float(row[6] or 0),+ p99_duration_ms=float(row[7] or 0),+ users=int(row[8] or 0),+ sessions=int(row[9] or 0),+ first_seen=str(row[10] or ""),+ last_seen=str(row[11] or ""),+ trend_score=float(row[12] or 0),)for row in rows]return MCPToolQualityRowsQueryResponse(results=results,totalCount=total_count,+ totalSessions=int((total_sessions_response.results or [[0]])[0][0] or 0),timings=response.timings,hogql=response.hogql,modifiers=self.modifiers,@@ -292,7 +403,7 @@ class MCPToolQualityDailyStatsQueryRunner(AnalyticsQueryRunner[MCPToolQualityDai"_P95": parse_expr(_P95),"_P99": parse_expr(_P99),"where": _named_tool_where(- self.query_date_range,+ _within(self.query_date_range.date_from_as_hogql(), self.query_date_range.date_to_as_hogql()),self.query.categories,self.team,self.query.properties,diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.pyindex e88264355edc..7fe28fbff396 100644--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py@@ -78,6 +78,12 @@ def session_id_from_conversation(conversation_id: str) -> str:return f"ses_{_fnv1a_hex(conversation_id)}{_fnv1a_hex(f'{conversation_id}::salt')}"+# --surge-tool: share of calls that go to the surge tool in the most recent quarter of --days,+# and in older sessions, so it shows a large increase on the Tool quality tab.+SURGE_RECENT_CALL_PROBABILITY = 0.3+SURGE_OLDER_CALL_PROBABILITY = 0.005++def stable_hash(value: str) -> int:# Not hash(): that's salted per process, which would change how many RNG draws# each session consumes and break --seed reproducibility across invocations.@@ -733,6 +739,15 @@ class Command(BaseCommand):help=f"Number of send_feedback reports ($mcp_feedback events), at most {MAX_FEEDBACK_PER_SESSION} "f"per session. Defaults to {DEFAULT_FEEDBACK_COUNT}, clamped to what --sessions allows.",)+ parser.add_argument(+ "--surge-tool",+ type=str,+ default=None,+ # Feedback generation looks up templates by tool name, so only built-in tools are seedable.+ choices=TOOL_NAMES,+ help="Tool name to spike in the most recent quarter of --days, so it trends on the Tool quality tab "+ "(for example with --days 14 and the default 7-day filter). Older sessions rarely call it. Needs --days.",+ )parser.add_argument("--seed", type=int, default=None, help="Optional random seed for reproducible output.")parser.add_argument("--clear",@@ -748,6 +763,7 @@ class Command(BaseCommand):min_calls: int = options["min_calls"]max_calls: int = options["max_calls"]days: int = options["days"]+ surge_tool: str | None = options["surge_tool"] if days > 0 else None# An explicit value is validated against --sessions; the default clamps instead,# so low-volume smoke runs (--sessions 5) work without extra flags.explicit_missing_capabilities: int | None = options["missing_capabilities"]@@ -922,6 +938,11 @@ class Command(BaseCommand):session_end_offset_min = rng.randint(31, 59)session_start = now - timedelta(minutes=session_end_offset_min) - total_call_durationsession_start_ms = int(session_start.timestamp() * 1000)+ surge_probability = (+ SURGE_RECENT_CALL_PROBABILITY+ if session_end_offset_min <= days * 24 * 60 // 4+ else SURGE_OLDER_CALL_PROBABILITY+ )# The SDK mints a uuidv7 conversation handle on the first tool call and derives# $session_id from it, so every call in the conversation shares one session.@@ -1014,7 +1035,12 @@ class Command(BaseCommand):cumulative_offset_s += call_intervals[call_idx]timestamp = session_start + timedelta(seconds=cumulative_offset_s)is_retry = retry_tool is not None- tool_name = retry_tool or rng.choices(TOOL_NAMES, weights=list(TOOL_WEIGHTS.values()), k=1)[0]+ if retry_tool:+ tool_name = retry_tool+ elif surge_tool and rng.random() < surge_probability:+ tool_name = surge_tool+ else:+ tool_name = rng.choices(TOOL_NAMES, weights=list(TOOL_WEIGHTS.values()), k=1)[0]# Skew error rate and latency per tool so the Tool quality tab has variation.tool_error_rate = (stable_hash(tool_name) % 30) / 100.0is_error = rng.random() < tool_error_ratediff --git a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py b/products/mcp_analytics/backend/tests/test_tool_quality_tables.pyindex bf15e8ce0aff..d78aa261034b 100644--- a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py+++ b/products/mcp_analytics/backend/tests/test_tool_quality_tables.py@@ -1,6 +1,8 @@from datetime import UTC, datetime, timedeltafrom typing import Any+import pytest+import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom parameterized import parameterized@@ -44,6 +46,7 @@ def _emit(is_error: bool = False,duration_ms: float = 100,session_id: str = "s1",+ mcp_session_id: str | None = None,distinct_id: str = "d1",timestamp: datetime | None = None,) -> None:@@ -54,6 +57,8 @@ def _emit("$mcp_duration_ms": duration_ms,"$session_id": session_id,}+ if mcp_session_id is not None:+ properties["$mcp_session_id"] = mcp_session_idif category is not None:properties["$mcp_tool_category"] = categoryif exec_tool_name is not None:@@ -146,6 +151,169 @@ class TestMCPToolQualityRowsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickhassert searched.totalCount == 1assert [row.tool for row in highest_error_rate.results] == ["rare_target"]+ def test_previous_calls_and_current_metrics_split_by_window(self) -> None:+ now = datetime.now(tz=UTC)+ previous_window = now - timedelta(days=10)+ # Previous-window calls use a different session/user and are all errors, so any leakage+ # into the current-window aggregates (errors, users, sessions, first/last seen) shows up.+ for _ in range(3):+ _emit(+ self.team,+ tool_name="steady_tool",+ is_error=True,+ session_id="previous_session",+ distinct_id="previous_user",+ timestamp=previous_window,+ )+ _emit(self.team, tool_name="steady_tool", is_error=False, session_id="s1", distinct_id="d1", timestamp=now)+ _emit(self.team, tool_name="steady_tool", is_error=False, session_id="s1", distinct_id="d1", timestamp=now)+ flush_persons_and_events()++ row = self._run().results[0]++ assert row.tool == "steady_tool"+ assert row.total_calls == 2+ assert row.previous_calls == 3+ assert row.errors == 0+ assert row.error_rate_pct == 0+ assert row.users == 1+ assert row.sessions == 1++ @parameterized.expand(+ [+ ("seven_days", "-7d", datetime(2026, 9, 17, 6, tzinfo=UTC), datetime(2026, 9, 14, tzinfo=UTC)),+ ("fourteen_days", "-14d", datetime(2026, 9, 10, 6, tzinfo=UTC), datetime(2026, 9, 1, tzinfo=UTC)),+ ("thirty_days", "-30d", datetime(2026, 8, 25, 6, tzinfo=UTC), datetime(2026, 8, 10, tzinfo=UTC)),+ ]+ )+ @time_machine.travel(datetime(2026, 9, 24, 12, tzinfo=UTC), tick=False)+ def test_first_day_of_the_window_counts_only_as_current(+ self, _name: str, date_from: str, first_current_day: datetime, previous_day: datetime+ ) -> None:+ _emit(self.team, tool_name="steady_tool", timestamp=first_current_day)+ _emit(self.team, tool_name="steady_tool", timestamp=previous_day)+ flush_persons_and_events()++ runner = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from=date_from)), team=self.team+ )+ row = runner.calculate().results[0]++ assert (row.total_calls, row.previous_calls) == (1, 1)++ @time_machine.travel(datetime(2026, 9, 24, 12, tzinfo=UTC), tick=False)+ def test_windows_have_the_same_length_on_the_default_range(self) -> None:+ # -7d runs from Sep 17 00:00 to now, 180 hours. One call every hour on the half hour across+ # 360 hours puts 180 in each window only if the previous window is also 180 hours long.+ now = datetime(2026, 9, 24, 12, tzinfo=UTC)+ for hour in range(360):+ _emit(self.team, tool_name="steady_tool", timestamp=now - timedelta(hours=hour + 0.5))+ flush_persons_and_events()++ row = self._run().results[0]++ assert (row.total_calls, row.previous_calls) == (180, 180)++ @time_machine.travel(datetime(2026, 9, 10, 12, tzinfo=UTC), tick=False)+ def test_to_date_range_compares_against_the_same_part_of_the_previous_unit(self) -> None:+ _emit(self.team, tool_name="steady_tool", timestamp=datetime(2026, 8, 5, tzinfo=UTC))+ # Inside last month but after its first ten days, so outside the previous period.+ _emit(self.team, tool_name="steady_tool", timestamp=datetime(2026, 8, 20, tzinfo=UTC))+ _emit(self.team, tool_name="steady_tool", timestamp=datetime(2026, 9, 5, tzinfo=UTC))+ flush_persons_and_events()++ runner = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="mStart")), team=self.team+ )+ row = runner.calculate().results[0]++ assert row.total_calls == 1+ assert row.previous_calls == 1++ def test_total_sessions_ignores_search_and_counts_each_session_once(self) -> None:+ _emit(self.team, tool_name="query_run", session_id="s1")+ _emit(self.team, tool_name="insight_get", session_id="s1")+ _emit(self.team, tool_name="insight_get", session_id="s2")+ flush_persons_and_events()++ response = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"), search="query_run"), team=self.team+ ).calculate()++ assert [(row.tool, row.sessions) for row in response.results] == [("query_run", 1)]+ assert response.totalSessions == 2++ def test_sessions_count_the_mcp_session_id_when_there_is_no_posthog_session(self) -> None:+ _emit(self.team, tool_name="query_run", session_id="", mcp_session_id="conv_1")+ _emit(self.team, tool_name="query_run", session_id="", mcp_session_id="conv_2")+ flush_persons_and_events()++ response = self._run()++ assert (response.results[0].sessions, response.totalSessions) == (2, 2)++ def test_tool_with_only_previous_calls_is_absent_and_excluded_from_total_count(self) -> None:+ now = datetime.now(tz=UTC)+ _emit(self.team, tool_name="old_only_tool", timestamp=now - timedelta(days=10))+ _emit(self.team, tool_name="current_tool", timestamp=now)+ flush_persons_and_events()++ response = self._run()++ assert [row.tool for row in response.results] == ["current_tool"]+ assert response.totalCount == 1+ assert response.results[0].previous_calls == 0++ @parameterized.expand(+ [+ # k is floored at 10 because these volumes are tiny.+ ("growth", 2, 6, 4 / 12),+ ("decline", 6, 2, -4 / 16),+ ("flat", 3, 3, 0.0),+ ("new", 0, 5, 5 / 10),+ ]+ )+ def test_trend_score(self, _name: str, previous: int, current: int, expected: float) -> None:+ now = datetime.now(tz=UTC)+ for _ in range(previous):+ _emit(self.team, tool_name="steady_tool", timestamp=now - timedelta(days=10))+ for _ in range(current):+ _emit(self.team, tool_name="steady_tool", timestamp=now)+ flush_persons_and_events()++ row = self._run().results[0]++ assert row.trend_score == pytest.approx(expected)++ def test_sort_by_trend_score_ranks_volume_weighted_surge_above_raw_percent(self) -> None:+ # Raw percent change favours tool_a (2900% vs 900%), but tool_a's growth is 1 -> 30 calls+ # while tool_b's is a real surge, 20 -> 200. The smoothed trend_score (k floored at 10+ # since total current-window calls here is small) ranks tool_b's larger absolute surge+ # above tool_a's tiny-volume spike: 180/30=6 vs 29/11=2.6.+ now = datetime.now(tz=UTC)+ previous_window = now - timedelta(days=10)+ _emit(self.team, tool_name="tool_a", timestamp=previous_window)+ for _ in range(30):+ _emit(self.team, tool_name="tool_a", timestamp=now)+ for _ in range(20):+ _emit(self.team, tool_name="tool_b", timestamp=previous_window)+ for _ in range(200):+ _emit(self.team, tool_name="tool_b", timestamp=now)+ flush_persons_and_events()++ runner = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(+ dateRange=DateRange(date_from="-7d"), sortColumn="trend_score", sortDirection="DESC"+ ),+ team=self.team,+ )+ results = runner.calculate().results++ assert [(row.tool, row.total_calls, row.previous_calls) for row in results] == [+ ("tool_b", 200, 20),+ ("tool_a", 30, 1),+ ]+class TestMCPToolQualityDailyStatsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):def test_buckets_by_hour_when_interval_is_hour(self) -> None:diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsxindex 22be32aefdac..c16b8618b754 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx@@ -163,6 +163,14 @@ const TOOL_CALL_LIST = {// p50, p95, p99, users, sessions, first_seen, last_seen.type ToolQualityStoryRow = [string, number, number, number, number, number, number, number, number, string, string]+// Previous-period calls for the Trend column: a surge, a new tool, and a decline; the rest stay near flat.+const PREVIOUS_CALLS: Record<string, number> = {+ 'read-data-schema': 120,+ 'query-trends': 600,+ 'cohort-create': 0,+}+const TOTAL_SESSIONS = 720+const TOOL_QUALITY_ROWS: ToolQualityStoryRow[] = [['execute-sql', 1480, 144, 9.7, 820, 3525, 9800, 210, 540, '2026-05-08T09:00:00Z', '2026-06-07T10:04:00Z'],['read-data-schema', 760, 3, 0.4, 180, 1298, 2600, 160, 410, '2026-05-08T08:00:00Z', '2026-06-07T10:00:00Z'],@@ -712,19 +720,24 @@ const meta: Meta = {}// Tool quality tab runners return typed item rows — match on kind, not a SQL string.if (body?.query?.kind === 'MCPToolQualityRowsQuery') {- const rows = TOOL_QUALITY_ROWS.map((r) => ({- tool: r[0],- total_calls: r[1],- errors: r[2],- error_rate_pct: r[3],- p50_duration_ms: r[4],- p95_duration_ms: r[5],- p99_duration_ms: r[6],- users: r[7],- sessions: r[8],- first_seen: r[9],- last_seen: r[10],- }))+ const rows = TOOL_QUALITY_ROWS.map((r) => {+ const previousCalls = PREVIOUS_CALLS[r[0]] ?? Math.round(r[1] * 0.95)+ return {+ tool: r[0],+ total_calls: r[1],+ previous_calls: previousCalls,+ trend_score: (r[1] - previousCalls) / (previousCalls + 10),+ errors: r[2],+ error_rate_pct: r[3],+ p50_duration_ms: r[4],+ p95_duration_ms: r[5],+ p99_duration_ms: r[6],+ users: r[7],+ sessions: r[8],+ first_seen: r[9],+ last_seen: r[10],+ }+ })const search = String(body.query.search ?? '').trim().toLowerCase()@@ -750,6 +763,7 @@ const meta: Meta = {{results: page,totalCount: filteredRows.length,+ totalSessions: TOTAL_SESSIONS,},]}diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsxindex 1bf5775065da..9a5368b8c62c 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx@@ -62,7 +62,7 @@ function ChartsScopeHeader(): JSX.Element {if (!selectedTool) {return (<div className="text-sm text-secondary">- Trends across all tools in scope — select a row above to drill down.+ Trends across all tools in scope. Select a tool in the table below to drill down.</div>)}diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex 07bb0e91200c..4c75fcd1f392 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -22,6 +22,7 @@ import {MCPToolQualityDailyStatItem,MCPToolQualityRowItem,MCPToolQualityRowsQueryResponse,+ MCPToolQualitySortColumn,NodeKind,} from '~/queries/schema/schema-general'import { IntervalType } from '~/types'@@ -102,7 +103,7 @@ export function mcpToolQualityUrlWithDates(dateFilter: DateFilter, interval?: In}export type ToolQualityRow = MCPToolQualityRowItem-export type ToolQualitySortColumn = Exclude<keyof ToolQualityRow, 'tool' | 'errors' | 'first_seen'>+export type ToolQualitySortColumn = MCPToolQualitySortColumnexport interface DailyToolStat {day: string@@ -174,6 +175,7 @@ export interface mcpAnalyticsToolQualityLogicValues {toolRowsPage: ToolRowsPage | nulltoolRowsPageLoading: booleantoolRowsTotalCount: number+ toolRowsTotalSessions: number}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -280,7 +282,7 @@ export interface mcpAnalyticsToolQualityLogicActions {column: ToolQualitySortColumn,direction: SortDirection) => {- column: ToolQualitySortColumn+ column: MCPToolQualitySortColumndirection: SortDirection}}@@ -295,6 +297,7 @@ export interface mcpAnalyticsToolQualityLogicMeta {loadedToolQualityPageIndex: (toolRowsPage: ToolRowsPage | null) => numbertoolRows: (toolRowsPage: ToolRowsPage | null) => MCPToolQualityRowItem[]toolRowsTotalCount: (toolRowsPage: ToolRowsPage | null) => number+ toolRowsTotalSessions: (toolRowsPage: ToolRowsPage | null) => numberdailyChartData: (dailyStats: DailyToolStat[],dateFilter: DateFilter,@@ -503,6 +506,10 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType(s) => [s.toolRowsPage],(toolRowsPage: ToolRowsPage | null): number => toolRowsPage?.totalCount ?? 0,],+ toolRowsTotalSessions: [+ (s) => [s.toolRowsPage],+ (toolRowsPage: ToolRowsPage | null): number => toolRowsPage?.totalSessions ?? 0,+ ],dailyChartData: [(s) => [s.dailyStats, s.dateFilter, s.interval, teamLogic.selectors.timezone],(diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsxindex a9839af9f0ed..f5dad97fcb8f 100644--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx@@ -46,6 +46,7 @@ import {mcpAnalyticsToolQualityLogic,mcpToolReportUrl,} from '../mcpAnalyticsToolQualityLogic'+import { TrendCell } from './TrendCell'const DESTRUCTIVE_ERROR_PCT = 5@@ -58,17 +59,27 @@ interface ColumnSpec {const SORTABLE_COLUMNS: ColumnSpec[] = [{ key: 'total_calls', label: 'Calls', align: 'right', tooltip: 'Total number of times this tool was called' },+ {+ key: 'trend_score',+ label: 'Trend',+ align: 'right',+ tooltip:+ "Change in calls versus the previous period of the same length. Sorting ranks by growth relative to volume, so small tools don't dominate.",+ },{key: 'error_rate_pct',label: 'Error rate',align: 'right',tooltip: 'Percentage of calls that returned $mcp_is_error = true',},- { key: 'p50_duration_ms', label: 'p50', align: 'right', tooltip: 'Median $mcp_duration_ms' },{ key: 'p95_duration_ms', label: 'p95', align: 'right', tooltip: '95th-percentile $mcp_duration_ms' },- { key: 'p99_duration_ms', label: 'p99', align: 'right', tooltip: '99th-percentile $mcp_duration_ms' },{ key: 'users', label: 'Users', align: 'right', tooltip: 'Unique users who invoked this tool' },- { key: 'sessions', label: 'Sessions', align: 'right', tooltip: 'Unique sessions where this tool was called' },+ {+ key: 'sessions',+ label: 'Sessions',+ align: 'right',+ tooltip: 'Unique sessions where this tool was called, and their share of all sessions in the period',+ },{ key: 'last_seen', label: 'Last seen' },]@@ -120,7 +131,7 @@ function SortableHead({}function ToolRows(): JSX.Element {- const { toolRows, toolRowsPageLoading, selectedTool, dateFilter, pinnedInterval } =+ const { toolRows, toolRowsTotalSessions, toolRowsPageLoading, selectedTool, dateFilter, pinnedInterval } =useValues(mcpAnalyticsToolQualityLogic)const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)@@ -156,14 +167,22 @@ function ToolRows(): JSX.Element {<span className="font-mono">{row.tool}</span></TableCell><TableCell align="right">{formatNumber(row.total_calls)}</TableCell>+ <TableCell align="right">+ <TrendCell totalCalls={row.total_calls} previousCalls={row.previous_calls} />+ </TableCell><TableCell align="right"><ErrorRateBadge pct={row.error_rate_pct} /></TableCell>- <TableCell align="right">{formatMs(row.p50_duration_ms)}</TableCell><TableCell align="right">{formatMs(row.p95_duration_ms)}</TableCell>- <TableCell align="right">{formatMs(row.p99_duration_ms)}</TableCell><TableCell align="right">{formatNumber(row.users)}</TableCell>- <TableCell align="right">{formatNumber(row.sessions)}</TableCell>+ <TableCell align="right">+ <span className="tabular-nums">{formatNumber(row.sessions)}</span>+ {toolRowsTotalSessions > 0 ? (+ <span className="text-secondary tabular-nums">+ {` · ${formatPercentage((row.sessions / toolRowsTotalSessions) * 100, { compact: true })}`}+ </span>+ ) : null}+ </TableCell><TableCell className="whitespace-nowrap"><TZLabel time={row.last_seen} /></TableCell>diff --git a/products/mcp_analytics/frontend/tool-quality/TrendCell.tsx b/products/mcp_analytics/frontend/tool-quality/TrendCell.tsxnew file mode 100644index 000000000000..5d57acaa2991--- /dev/null+++ b/products/mcp_analytics/frontend/tool-quality/TrendCell.tsx@@ -0,0 +1,36 @@+import { Badge } from '@posthog/quill-primitives'++import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { pluralize } from 'lib/utils/strings'++import { formatNumber } from '../dashboard/formatters'++// Doubling and halving are the same size of change, so both earn the badge.+const BIG_GROWTH_PCT = 100+const BIG_DROP_PCT = -50++export function TrendCell({ totalCalls, previousCalls }: { totalCalls: number; previousCalls: number }): JSX.Element {+ const calls = pluralize(totalCalls, 'call')+ if (previousCalls === 0) {+ return (+ <Tooltip title={`${calls}, none in the previous period`}>+ <span>+ <Badge variant="info">New</Badge>+ </span>+ </Tooltip>+ )+ }+ const pctChange = Math.round(((totalCalls - previousCalls) / previousCalls) * 100)+ const label = `${pctChange > 0 ? '+' : ''}${pctChange.toLocaleString()}%`+ return (+ <Tooltip title={`${calls} vs ${formatNumber(previousCalls)} in the previous period`}>+ <span className="tabular-nums">+ {pctChange >= BIG_GROWTH_PCT || pctChange <= BIG_DROP_PCT ? (+ <Badge variant="info">{label}</Badge>+ ) : (+ label+ )}+ </span>+ </Tooltip>+ )+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 22c7c9076908..5c0932f4a377 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53149,9 +53149,13 @@ export namespace Schemas {p50_duration_ms: number;p95_duration_ms: number;p99_duration_ms: number;+ /** Calls in the previous period: the same length of time right before the window, or for a to-date range ("This month") the same part of the previous unit. */+ previous_calls: number;sessions: number;tool: string;total_calls: number;+ /** Sort key ranking growth relative to volume, so a small tool's spike doesn't outrank a large tool's surge. Not a percentage; only meaningful for ordering. */+ trend_score: number;users: number;}@@ -53173,6 +53177,8 @@ export namespace Schemas {timings?: QueryTiming[] | null;/** Number of tools matching the date, category, and search filters. */totalCount: number;+ /** Distinct sessions with any tool call in the window, ignoring category and search filters. The denominator for each row's session share. */+ totalSessions: number;/** Connector-synced data warehouse sources referenced by this query, if any. */used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;/** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */@@ -53191,6 +53197,7 @@ export namespace Schemas {Users: 'users',Sessions: 'sessions',LastSeen: 'last_seen',+ TrendScore: 'trend_score',} as const;export type MCPToolQualitySortDirection = typeof MCPToolQualitySortDirection[keyof typeof MCPToolQualitySortDirection];@@ -85105,6 +85112,8 @@ export namespace Schemas {timings?: QueryTiming[] | null;/** Number of tools matching the date, category, and search filters. */totalCount: number;+ /** Distinct sessions with any tool call in the window, ignoring category and search filters. The denominator for each row's session share. */+ totalSessions: number;/** Connector-synced data warehouse sources referenced by this query, if any. */used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;/** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */