: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): flag error rate and p95 regressions on tool quality (#106656)
Lucas Fariabc554e788e9c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6956221f2b4c..ba1431d4f35d 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.32dd20a9e219241b31e4a8e2b5d215f355793c9fe8273721c0ed8ba7bcdd35a2.1qt6pH0OhiHa-algJ0wt0xzUqqVUIuwewEGCHgtzRKI+ hash: v1.k794b7964.642dca04a5c6cb07edc0f125e9c7e0426a5a5dba0f2d121dd7b9bad9fd2709c9.a8J-gQWdL8aNFNlZuBxwf86m16C4h99rTH0vTEJE4Tcscenes-app-mcp-analytics--tool-quality--light:- hash: v1.k794b7964.303e6787271f98d787a49c93a381e370753c4e17ddb566324d856d9fc9db6a4d.0G4z2IuMALIvTPtVicec5BXwMA7cuum_zYLb0aEH4PA+ hash: v1.k794b7964.8dbab167c718fb85171e2970e2f1bca8d7fd33ef1a5f99f31f45d9c87fa8bcfd.P8hWCPXmKWCxoka2Uebtt_is6LzR79LQXW7CAVDpAz0scenes-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 24f7ef41692c..598f1f918ba2 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -11559,6 +11559,10 @@"format": "date-time","type": "string"},+ "previousTotalSessions": {+ "$ref": "#/definitions/integer",+ "description": "The same total for the previous period, the denominator for each row's previous session share."+ },"query_metadata": {"type": "object"},@@ -11629,6 +11633,7 @@"is_cached","last_refresh","next_allowed_client_refresh",+ "previousTotalSessions","results","timezone","totalCount",@@ -33609,6 +33614,18 @@"$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."},+ "previous_errors": {+ "$ref": "#/definitions/integer",+ "description": "Errored calls in the previous period."+ },+ "previous_p95_duration_ms": {+ "description": "p95 duration in the previous period, or null when no previous call carried a duration.",+ "type": ["number", "null"]+ },+ "previous_sessions": {+ "$ref": "#/definitions/integer",+ "description": "Distinct sessions that called the tool in the previous period."+ },"sessions": {"$ref": "#/definitions/integer"},@@ -33639,7 +33656,10 @@"sessions","first_seen","last_seen",- "trend_score"+ "trend_score",+ "previous_errors",+ "previous_p95_duration_ms",+ "previous_sessions"],"type": "object"},@@ -33723,6 +33743,10 @@"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "previousTotalSessions": {+ "$ref": "#/definitions/integer",+ "description": "The same total for the previous period, the denominator for each row's previous session share."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -33778,7 +33802,7 @@"type": "array"}},- "required": ["results", "totalCount", "totalSessions"],+ "required": ["previousTotalSessions", "results", "totalCount", "totalSessions"],"type": "object"},"MCPToolQualitySortColumn": {@@ -48351,6 +48375,10 @@"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "previousTotalSessions": {+ "$ref": "#/definitions/integer",+ "description": "The same total for the previous period, the denominator for each row's previous session share."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -48406,7 +48434,7 @@"type": "array"}},- "required": ["results", "totalCount", "totalSessions"],+ "required": ["previousTotalSessions", "results", "totalCount", "totalSessions"],"type": "object"},{diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 926495ee4dd9..d053a6e85e98 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3749,6 +3749,12 @@ export interface MCPToolQualityRowItem {/** 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+ /** Errored calls in the previous period. */+ previous_errors: integer+ /** p95 duration in the previous period, or null when no previous call carried a duration. */+ previous_p95_duration_ms: number | null+ /** Distinct sessions that called the tool in the previous period. */+ previous_sessions: integer}export type MCPToolQualitySortColumn =@@ -3770,6 +3776,8 @@ export interface MCPToolQualityRowsQueryResponse extends AnalyticsQueryResponseBtotalCount: 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+ /** The same total for the previous period, the denominator for each row's previous session share. */+ previousTotalSessions: 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 3ecadb3a349c..dfca74cf177a 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -6097,6 +6097,15 @@ class MCPToolQualityRowItem(BaseModel):" previous unit."),)+ previous_errors: int = Field(..., description="Errored calls in the previous period.")+ previous_p95_duration_ms: float | None = Field(+ ...,+ description=("p95 duration in the previous period, or null when no previous call carried a duration."),+ )+ previous_sessions: int = Field(+ ...,+ description="Distinct sessions that called the tool in the previous period.",+ )sessions: inttool: strtotal_calls: int@@ -13183,6 +13192,10 @@ class CachedMCPToolQualityRowsQueryResponse(BaseModel):last_refresh: AwareDatetimemodifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetime+ previousTotalSessions: int = Field(+ ...,+ description=("The same total for the previous period, the denominator for each row's previous session share."),+ )query_metadata: dict[str, Any] | None = Nonequery_scan: QueryScanSummary | None = Field(default=None,@@ -19117,6 +19130,10 @@ class MCPToolQualityRowsQueryResponse(BaseModel):)hogql: str | None = Field(default=None, description="Generated HogQL query.")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ previousTotalSessions: int = Field(+ ...,+ description=("The same total for the previous period, the denominator for each row's previous session share."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -24262,6 +24279,10 @@ class QueryResponseAlternative104(BaseModel):)hogql: str | None = Field(default=None, description="Generated HogQL query.")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ previousTotalSessions: int = Field(+ ...,+ description=("The same total for the previous period, the denominator for each row's previous session share."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),diff --git a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.pyindex 0cf612d8b35d..1f379590e268 100644--- a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py+++ b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py@@ -189,7 +189,6 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuerysort_direction = cast(Literal["ASC", "DESC"], self.query.sortDirection or "DESC")current_range = self.query_date_range- previous = self.previous_windowquery = parse_select("""@@ -209,18 +208,24 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuery(total_calls - previous_calls)/ (previous_calls + greatest({_min_k}, round({_volume_fraction} * sum(total_calls) OVER ())))AS trend_score,- count() OVER () AS total_count+ count() OVER () AS total_count,+ previous_errors,+ if(previous_calls = 0 OR isNaN(previous_p95), NULL, previous_p95) AS previous_p95_duration_ms,+ previous_sessionsFROM (SELECTtool,countIf(is_current) AS total_calls,countIf(NOT is_current) AS previous_calls,countIf(is_current AND is_error) AS errors,+ countIf(NOT is_current AND is_error) AS previous_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.95)(duration_ms, NOT is_current)) AS previous_p95,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,+ uniqIf(session_id, NOT is_current) AS previous_sessions,minIf(timestamp, is_current) AS first_seen,maxIf(timestamp, is_current) AS last_seenFROM (@@ -250,16 +255,7 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuery"_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(- 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._both_windows(),self.query.categories,self.team,self.query.properties,@@ -277,18 +273,31 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuery]return query+ def _both_windows(self) -> ast.Expr:+ previous = self.previous_window+ return ast.Or(+ exprs=[+ _within(_hogql_datetime(previous.date_from), _hogql_datetime(previous.date_to), exclusive_end=True),+ _within(self.query_date_range.date_from_as_hogql(), self.query_date_range.date_to_as_hogql()),+ ]+ )+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}+ SELECT uniqIf(session_id, is_current), uniqIf(session_id, NOT is_current)+ FROM (+ SELECT nullIf({conversation_id}, '') AS session_id, timestamp >= {current_from} AS is_current+ FROM events+ WHERE {where}+ )""",placeholders={"conversation_id": parse_expr(CONVERSATION_ID_SQL),+ "current_from": self.query_date_range.date_from_as_hogql(),"where": _named_tool_where(- _within(self.query_date_range.date_from_as_hogql(), self.query_date_range.date_to_as_hogql()),+ self._both_windows(),None,self.team,self.query.properties,@@ -336,6 +345,7 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuerymodifiers=self.modifiers,limit_context=self.limit_context,)+ total_sessions_row = (total_sessions_response.results or [[0, 0]])[0]results = [MCPToolQualityRowItem(tool=str(row[0] or ""),@@ -351,13 +361,17 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQueryfirst_seen=str(row[10] or ""),last_seen=str(row[11] or ""),trend_score=float(row[12] or 0),+ previous_errors=int(row[14] or 0),+ previous_p95_duration_ms=None if row[15] is None else float(row[15]),+ previous_sessions=int(row[16] 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),+ totalSessions=int(total_sessions_row[0] or 0),+ previousTotalSessions=int(total_sessions_row[1] or 0),timings=response.timings,hogql=response.hogql,modifiers=self.modifiers,diff --git a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py b/products/mcp_analytics/backend/tests/test_tool_quality_tables.pyindex d78aa261034b..a3df486947cf 100644--- a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py+++ b/products/mcp_analytics/backend/tests/test_tool_quality_tables.py@@ -44,7 +44,7 @@ def _emit(exec_tool_name: str | None = None,category: str | None = None,is_error: bool = False,- duration_ms: float = 100,+ duration_ms: float | None = 100,session_id: str = "s1",mcp_session_id: str | None = None,distinct_id: str = "d1",@@ -54,11 +54,12 @@ def _emit("$mcp_tool_name": tool_name,"$mcp_source": NEW_SDK_SOURCE,"$mcp_is_error": is_error,- "$mcp_duration_ms": duration_ms,"$session_id": session_id,}if mcp_session_id is not None:properties["$mcp_session_id"] = mcp_session_id+ if duration_ms is not None:+ properties["$mcp_duration_ms"] = duration_msif category is not None:properties["$mcp_tool_category"] = categoryif exec_tool_name is not None:@@ -252,6 +253,40 @@ class TestMCPToolQualityRowsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickhassert (response.results[0].sessions, response.totalSessions) == (2, 2)+ def test_previous_sessions_and_previous_total_sessions(self) -> None:+ now = datetime.now(tz=UTC)+ previous_window = now - timedelta(days=10)+ _emit(self.team, tool_name="query_run", session_id="old_1", timestamp=previous_window)+ _emit(self.team, tool_name="insight_get", session_id="old_2", timestamp=previous_window)+ _emit(self.team, tool_name="insight_get", session_id="old_3", timestamp=previous_window)+ _emit(self.team, tool_name="query_run", session_id="new_1", timestamp=now)+ flush_persons_and_events()++ response = self._run()++ assert [(row.tool, row.sessions, row.previous_sessions) for row in response.results] == [("query_run", 1, 1)]+ assert (response.totalSessions, response.previousTotalSessions) == (1, 3)++ def test_previous_error_rate_and_p95_come_from_the_previous_window_only(self) -> None:+ now = datetime.now(tz=UTC)+ previous_window = now - timedelta(days=10)+ _emit(self.team, tool_name="steady_tool", is_error=True, duration_ms=1000, timestamp=previous_window)+ for _ in range(3):+ _emit(self.team, tool_name="steady_tool", duration_ms=1000, timestamp=previous_window)+ _emit(self.team, tool_name="steady_tool", duration_ms=100, timestamp=now)+ _emit(self.team, tool_name="new_tool", timestamp=now)+ _emit(self.team, tool_name="untimed_tool", duration_ms=None, timestamp=previous_window)+ _emit(self.team, tool_name="untimed_tool", timestamp=now)+ flush_persons_and_events()++ rows = {row.tool: row for row in self._run().results}++ assert (rows["steady_tool"].errors, rows["steady_tool"].previous_errors) == (0, 1)+ assert (rows["steady_tool"].p95_duration_ms, rows["steady_tool"].previous_p95_duration_ms) == (100, 1000)+ assert (rows["new_tool"].previous_errors, rows["new_tool"].previous_p95_duration_ms) == (0, None)+ # Previous calls exist but none carried a duration, so there is no previous p95 to compare.+ assert rows["untimed_tool"].previous_p95_duration_ms is None+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))diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsxindex c16b8618b754..b84c36ab7ec9 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx@@ -170,6 +170,10 @@ const PREVIOUS_CALLS: Record<string, number> = {'cohort-create': 0,}const TOTAL_SESSIONS = 720+const PREVIOUS_TOTAL_SESSIONS = 680+// Previous-period values that trigger the regression markers: an error-rate jump and a p95 slowdown.+const PREVIOUS_ERRORS: Record<string, number> = { 'execute-sql': 40 }+const PREVIOUS_P95_MS: Record<string, number> = { 'insight-create': 400 }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'],@@ -727,6 +731,9 @@ const meta: Meta = {total_calls: r[1],previous_calls: previousCalls,trend_score: (r[1] - previousCalls) / (previousCalls + 10),+ previous_errors: PREVIOUS_ERRORS[r[0]] ?? Math.round((r[2] * previousCalls) / r[1]),+ previous_p95_duration_ms: previousCalls ? (PREVIOUS_P95_MS[r[0]] ?? r[5]) : null,+ previous_sessions: Math.round(r[8] * 0.9),errors: r[2],error_rate_pct: r[3],p50_duration_ms: r[4],@@ -764,6 +771,7 @@ const meta: Meta = {results: page,totalCount: filteredRows.length,totalSessions: TOTAL_SESSIONS,+ previousTotalSessions: PREVIOUS_TOTAL_SESSIONS,},]}diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex 4c75fcd1f392..42b8b3fcfaa3 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -174,6 +174,7 @@ export interface mcpAnalyticsToolQualityLogicValues {toolRows: MCPToolQualityRowItem[]toolRowsPage: ToolRowsPage | nulltoolRowsPageLoading: boolean+ toolRowsPreviousTotalSessions: numbertoolRowsTotalCount: numbertoolRowsTotalSessions: number}@@ -298,6 +299,7 @@ export interface mcpAnalyticsToolQualityLogicMeta {toolRows: (toolRowsPage: ToolRowsPage | null) => MCPToolQualityRowItem[]toolRowsTotalCount: (toolRowsPage: ToolRowsPage | null) => numbertoolRowsTotalSessions: (toolRowsPage: ToolRowsPage | null) => number+ toolRowsPreviousTotalSessions: (toolRowsPage: ToolRowsPage | null) => numberdailyChartData: (dailyStats: DailyToolStat[],dateFilter: DateFilter,@@ -510,6 +512,10 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType(s) => [s.toolRowsPage],(toolRowsPage: ToolRowsPage | null): number => toolRowsPage?.totalSessions ?? 0,],+ toolRowsPreviousTotalSessions: [+ (s) => [s.toolRowsPage],+ (toolRowsPage: ToolRowsPage | null): number => toolRowsPage?.previousTotalSessions ?? 0,+ ],dailyChartData: [(s) => [s.dailyStats, s.dateFilter, s.interval, teamLogic.selectors.timezone],(diff --git a/products/mcp_analytics/frontend/tool-quality/QualityChangeMarker.tsx b/products/mcp_analytics/frontend/tool-quality/QualityChangeMarker.tsxnew file mode 100644index 000000000000..949b23a51d1b--- /dev/null+++ b/products/mcp_analytics/frontend/tool-quality/QualityChangeMarker.tsx@@ -0,0 +1,24 @@+import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import type { QualityChange } from './qualityChange'++export function QualityChangeMarker({ change }: { change: QualityChange | null }): JSX.Element | null {+ if (!change) {+ return null+ }+ const Icon = change.worse ? IconArrowUp : IconArrowDown+ const description = `${change.worse ? 'Up' : 'Down'} ${change.label} from ${change.previous} in the previous period`+ return (+ <Tooltip title={`Was ${change.previous} in the previous period`}>+ <span+ tabIndex={0}+ aria-label={description}+ className={`ml-1 inline-flex items-center gap-0.5 text-xs tabular-nums ${change.worse ? 'text-danger' : 'text-success'}`}+ >+ <Icon />+ {change.label}+ </span>+ </Tooltip>+ )+}diff --git a/products/mcp_analytics/frontend/tool-quality/SessionsCell.tsx b/products/mcp_analytics/frontend/tool-quality/SessionsCell.tsxnew file mode 100644index 000000000000..13d883f0beb4--- /dev/null+++ b/products/mcp_analytics/frontend/tool-quality/SessionsCell.tsx@@ -0,0 +1,33 @@+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { formatPercentage } from 'lib/utils/numbers'++import { formatNumber } from '../dashboard/formatters'++export function SessionsCell({+ sessions,+ totalSessions,+ previousSessions,+ previousTotalSessions,+}: {+ sessions: number+ totalSessions: number+ previousSessions: number+ previousTotalSessions: number+}): JSX.Element {+ const hasPreviousPeriod = previousTotalSessions > 0+ const cell = (+ <span className="whitespace-nowrap" tabIndex={hasPreviousPeriod ? 0 : undefined}>+ <span className="tabular-nums">{formatNumber(sessions)}</span>+ {totalSessions > 0 ? (+ <span className="text-secondary tabular-nums">+ {` · ${formatPercentage((sessions / totalSessions) * 100, { compact: true })}`}+ </span>+ ) : null}+ </span>+ )+ if (!hasPreviousPeriod) {+ return cell+ }+ const previousShare = formatPercentage((previousSessions / previousTotalSessions) * 100, { compact: true })+ return <Tooltip title={`Was ${previousShare} of sessions in the previous period`}>{cell}</Tooltip>+}diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsxindex f5dad97fcb8f..5d9febc7c536 100644--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx@@ -46,6 +46,9 @@ import {mcpAnalyticsToolQualityLogic,mcpToolReportUrl,} from '../mcpAnalyticsToolQualityLogic'+import { errorRateChange, p95Change } from './qualityChange'+import { QualityChangeMarker } from './QualityChangeMarker'+import { SessionsCell } from './SessionsCell'import { TrendCell } from './TrendCell'const DESTRUCTIVE_ERROR_PCT = 5@@ -70,9 +73,16 @@ const SORTABLE_COLUMNS: ColumnSpec[] = [key: 'error_rate_pct',label: 'Error rate',align: 'right',- tooltip: 'Percentage of calls that returned $mcp_is_error = true',+ tooltip:+ 'Percentage of calls that returned $mcp_is_error = true. An arrow marks a meaningful change versus the previous period, for tools with at least 20 calls in both.',+ },+ {+ key: 'p95_duration_ms',+ label: 'p95',+ align: 'right',+ tooltip:+ '95th-percentile $mcp_duration_ms. An arrow marks a meaningful change versus the previous period, for tools with at least 20 calls in both.',},- { key: 'p95_duration_ms', label: 'p95', align: 'right', tooltip: '95th-percentile $mcp_duration_ms' },{ key: 'users', label: 'Users', align: 'right', tooltip: 'Unique users who invoked this tool' },{key: 'sessions',@@ -131,8 +141,15 @@ function SortableHead({}function ToolRows(): JSX.Element {- const { toolRows, toolRowsTotalSessions, toolRowsPageLoading, selectedTool, dateFilter, pinnedInterval } =- useValues(mcpAnalyticsToolQualityLogic)+ const {+ toolRows,+ toolRowsTotalSessions,+ toolRowsPreviousTotalSessions,+ toolRowsPageLoading,+ selectedTool,+ dateFilter,+ pinnedInterval,+ } = useValues(mcpAnalyticsToolQualityLogic)const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)if (toolRowsPageLoading && toolRows.length === 0) {@@ -171,17 +188,25 @@ function ToolRows(): JSX.Element {<TrendCell totalCalls={row.total_calls} previousCalls={row.previous_calls} /></TableCell><TableCell align="right">- <ErrorRateBadge pct={row.error_rate_pct} />+ <span className="inline-flex items-center whitespace-nowrap">+ <ErrorRateBadge pct={row.error_rate_pct} />+ <QualityChangeMarker change={errorRateChange(row)} />+ </span>+ </TableCell>+ <TableCell align="right">+ <span className="inline-flex items-center whitespace-nowrap">+ <span className="tabular-nums">{formatMs(row.p95_duration_ms)}</span>+ <QualityChangeMarker change={p95Change(row)} />+ </span></TableCell>- <TableCell align="right">{formatMs(row.p95_duration_ms)}</TableCell><TableCell align="right">{formatNumber(row.users)}</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}+ <SessionsCell+ sessions={row.sessions}+ totalSessions={toolRowsTotalSessions}+ previousSessions={row.previous_sessions}+ previousTotalSessions={toolRowsPreviousTotalSessions}+ /></TableCell><TableCell className="whitespace-nowrap"><TZLabel time={row.last_seen} />diff --git a/products/mcp_analytics/frontend/tool-quality/TrendCell.tsx b/products/mcp_analytics/frontend/tool-quality/TrendCell.tsxindex 5d57acaa2991..ceca6274fcfe 100644--- a/products/mcp_analytics/frontend/tool-quality/TrendCell.tsx+++ b/products/mcp_analytics/frontend/tool-quality/TrendCell.tsx@@ -14,7 +14,7 @@ export function TrendCell({ totalCalls, previousCalls }: { totalCalls: number; pif (previousCalls === 0) {return (<Tooltip title={`${calls}, none in the previous period`}>- <span>+ <span tabIndex={0}><Badge variant="info">New</Badge></span></Tooltip>@@ -24,7 +24,7 @@ export function TrendCell({ totalCalls, previousCalls }: { totalCalls: number; pconst label = `${pctChange > 0 ? '+' : ''}${pctChange.toLocaleString()}%`return (<Tooltip title={`${calls} vs ${formatNumber(previousCalls)} in the previous period`}>- <span className="tabular-nums">+ <span className="tabular-nums" tabIndex={0}>{pctChange >= BIG_GROWTH_PCT || pctChange <= BIG_DROP_PCT ? (<Badge variant="info">{label}</Badge>) : (diff --git a/products/mcp_analytics/frontend/tool-quality/qualityChange.test.ts b/products/mcp_analytics/frontend/tool-quality/qualityChange.test.tsnew file mode 100644index 000000000000..ce59092cab4f--- /dev/null+++ b/products/mcp_analytics/frontend/tool-quality/qualityChange.test.ts@@ -0,0 +1,45 @@+import { errorRateChange, p95Change } from './qualityChange'++const row = (+ overrides: Partial<Parameters<typeof errorRateChange>[0]> = {}+): Parameters<typeof errorRateChange>[0] => ({+ total_calls: 100,+ previous_calls: 100,+ errors: 0,+ previous_errors: 0,+ p95_duration_ms: 500,+ previous_p95_duration_ms: 500,+ ...overrides,+})++describe('qualityChange', () => {+ it.each([+ ['below 20 calls in the current period', row({ total_calls: 19, errors: 10 }), null],+ ['below 20 calls in the previous period', row({ previous_calls: 19, errors: 30 }), null],+ [+ 'a 5pp move that is still noise at 20 calls',+ row({ total_calls: 20, previous_calls: 20, errors: 3, previous_errors: 2 }),+ null,+ ],+ [+ 'a 2pp move on 5,000 calls',+ row({ total_calls: 5000, previous_calls: 5000, errors: 250, previous_errors: 150 }),+ { worse: true, label: '2pp', previous: '3%' },+ ],+ ['a large drop', row({ errors: 5, previous_errors: 30 }), { worse: false, label: '25pp', previous: '30%' }],+ ['a flat rate', row({ errors: 10, previous_errors: 10 }), null],+ ])('error rate: %s', (_name, input, expected) => {+ expect(errorRateChange(input)).toEqual(expected)+ })++ it.each([+ ['exactly 25% slower', row({ p95_duration_ms: 625 }), { worse: true, label: '25%', previous: '500ms' }],+ ['24% slower', row({ p95_duration_ms: 620 }), null],+ ['exactly 20% faster', row({ p95_duration_ms: 400 }), { worse: false, label: '20%', previous: '500ms' }],+ ['no previous p95', row({ previous_p95_duration_ms: null }), null],+ ['no current timing data', row({ p95_duration_ms: 0 }), null],+ ['below 20 calls', row({ total_calls: 5, p95_duration_ms: 5000 }), null],+ ])('p95: %s', (_name, input, expected) => {+ expect(p95Change(input)).toEqual(expected)+ })+})diff --git a/products/mcp_analytics/frontend/tool-quality/qualityChange.ts b/products/mcp_analytics/frontend/tool-quality/qualityChange.tsnew file mode 100644index 000000000000..4e9cbeae162a--- /dev/null+++ b/products/mcp_analytics/frontend/tool-quality/qualityChange.ts@@ -0,0 +1,62 @@+import { formatPercentage } from 'lib/utils/numbers'++import type { MCPToolQualityRowItem } from '~/queries/schema/schema-general'++import { formatMs } from '../dashboard/formatters'++// Below this many calls in either period, one error or one slow call swings the numbers too much.+export const MIN_CALLS_FOR_CHANGE = 20+// Starting points, not tuned: flag an error rate that moved 2 points, or a p95 that got 25% slower+// (or 20% faster, the same ratio in reverse).+const ERROR_RATE_CHANGE_POINTS = 2+const P95_SLOWER_RATIO = 1.25+// Two-proportion z-score an error rate change must also clear (about 95% confidence), so normal+// period-to-period noise on a busy tool is not flagged as a regression.+const ERROR_RATE_MIN_Z = 2++export interface QualityChange {+ worse: boolean+ label: string+ previous: string+}++type Row = Pick<+ MCPToolQualityRowItem,+ 'total_calls' | 'previous_calls' | 'errors' | 'previous_errors' | 'p95_duration_ms' | 'previous_p95_duration_ms'+>++function hasEnoughCalls(row: Row): boolean {+ return Math.min(row.total_calls, row.previous_calls) >= MIN_CALLS_FOR_CHANGE+}++export function errorRateChange(row: Row): QualityChange | null {+ if (!hasEnoughCalls(row)) {+ return null+ }+ const current = row.errors / row.total_calls+ const previous = row.previous_errors / row.previous_calls+ const pooled = (row.errors + row.previous_errors) / (row.total_calls + row.previous_calls)+ const standardError = Math.sqrt(pooled * (1 - pooled) * (1 / row.total_calls + 1 / row.previous_calls))+ const diff = current - previous+ if (Math.abs(diff) * 100 < ERROR_RATE_CHANGE_POINTS || Math.abs(diff) < ERROR_RATE_MIN_Z * standardError) {+ return null+ }+ return {+ worse: diff > 0,+ label: `${Math.round(Math.abs(diff) * 1000) / 10}pp`,+ previous: formatPercentage(previous * 100, { compact: true }),+ }+}++export function p95Change(row: Row): QualityChange | null {+ const previous = row.previous_p95_duration_ms+ // A p95 of 0 means no call in that period carried a duration, not an instant tool.+ if (!hasEnoughCalls(row) || !previous || !row.p95_duration_ms) {+ return null+ }+ const ratio = row.p95_duration_ms / previous+ if (ratio < P95_SLOWER_RATIO && ratio > 1 / P95_SLOWER_RATIO) {+ return null+ }+ return { worse: ratio > 1, label: `${Math.round(Math.abs(ratio - 1) * 100)}%`, previous: formatMs(previous) }+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5c0932f4a377..02a32f836f1f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53151,6 +53151,12 @@ export namespace Schemas {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;+ /** Errored calls in the previous period. */+ previous_errors: number;+ /** p95 duration in the previous period, or null when no previous call carried a duration. */+ previous_p95_duration_ms: number | null;+ /** Distinct sessions that called the tool in the previous period. */+ previous_sessions: number;sessions: number;tool: string;total_calls: number;@@ -53166,6 +53172,8 @@ export namespace Schemas {hogql?: string | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ /** The same total for the previous period, the denominator for each row's previous session share. */+ previousTotalSessions: number;/** Query status indicates whether next to the provided data, a query is still running. */query_status?: QueryStatus | null;/** The resolved previous/comparison period date range, when comparing against another period */@@ -85101,6 +85109,8 @@ export namespace Schemas {hogql?: string | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ /** The same total for the previous period, the denominator for each row's previous session share. */+ previousTotalSessions: number;/** Query status indicates whether next to the provided data, a query is still running. */query_status?: QueryStatus | null;/** The resolved previous/comparison period date range, when comparing against another period */