: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
fix(mcp-analytics): paginate tool quality results (#90981)
Lucas Faria1dd409194330
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex fce9e512a921..dc1696bc7757 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7377,9 +7377,9 @@ snapshots:scenes-app-mcp-analytics--sessions--light:hash: v1.k794b7964.8a6b42b3e994bb9f035951d84f071f2d7c20756f9745281f61e3383133bd5bb5.GxtTX98b-FQFH6zFqQLhs-oEq7qO_vVqKjJS-CBN77Uscenes-app-mcp-analytics--tool-quality--dark:- hash: v1.k794b7964.1a048a30aaedf592d08fb4a1a84d74d722e0afcdb9c72c1a001890f28530b50b.05NkieX3K7vPDZ5lVm_K5o7azAn1_9755fgJk77I9oo+ hash: v1.k794b7964.b13ac4ec3c9259eee05705bb21b0ef6e3b3a4bfb24669d7cfe27fe3b2a3977aa.HiW8YXDsI7Hq5BZ79JdEPpf9tSk-abFlPTJrdMWz5Owscenes-app-mcp-analytics--tool-quality--light:- hash: v1.k794b7964.04a9b39c28f16ad4b5a1b2625115e68768273cc7b66548fcbc5754a8f48aaac6.varhLyKH9GufBWEUlArceEOjryAzqMHvXgGzy-6VecY+ hash: v1.k794b7964.b7636f461a616a105e9578b4fbdae24c01d98431395d70152e0304ad40094da9.9Cg53WuJrHsB97CgOA555BZyzNrYCmNgAotEMaq-hMYscenes-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 5f07cd997411..ce5f4587d41e 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -10987,6 +10987,10 @@},"type": "array"},+ "totalCount": {+ "$ref": "#/definitions/integer",+ "description": "Number of tools matching the date, category, and search filters."+ },"used_data_warehouse_sources": {"description": "Connector-synced data warehouse sources referenced by this query, if any.","items": {@@ -11015,7 +11019,8 @@"last_refresh","next_allowed_client_refresh","results",- "timezone"+ "timezone",+ "totalCount"],"type": "object"},@@ -33531,7 +33536,7 @@},"MCPToolQualityRowsQuery": {"additionalProperties": false,- "description": "One row per $mcp_tool_name — call volume, error rate, latency percentiles, and reach — over the window.",+ "description": "One row per effective MCP tool name, with server-side search, sorting, and pagination.","properties": {"categories": {"description": "Restrict to these $mcp_tool_category values; empty or omitted means all categories.",@@ -33547,13 +33552,33 @@"const": "MCPToolQualityRowsQuery","type": "string"},+ "limit": {+ "$ref": "#/definitions/integer",+ "description": "Page size. The server defaults to 50 and caps this at 100."+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "offset": {+ "$ref": "#/definitions/integer",+ "description": "Number of matching tools to skip."+ },"response": {"$ref": "#/definitions/MCPToolQualityRowsQueryResponse"},+ "search": {+ "description": "Case-insensitive substring search on the effective tool name.",+ "type": "string"+ },+ "sortColumn": {+ "$ref": "#/definitions/MCPToolQualitySortColumn",+ "description": "Aggregate column used to order tools. Defaults to total_calls."+ },+ "sortDirection": {+ "$ref": "#/definitions/MCPToolQualitySortDirection",+ "description": "Sort direction. Defaults to DESC."+ },"tags": {"$ref": "#/definitions/QueryLogTags"},@@ -33605,6 +33630,10 @@},"type": "array"},+ "totalCount": {+ "$ref": "#/definitions/integer",+ "description": "Number of tools matching the date, category, and search filters."+ },"used_data_warehouse_sources": {"description": "Connector-synced data warehouse sources referenced by this query, if any.","items": {@@ -33627,9 +33656,26 @@"type": "array"}},- "required": ["results"],+ "required": ["results", "totalCount"],"type": "object"},+ "MCPToolQualitySortColumn": {+ "enum": [+ "total_calls",+ "error_rate_pct",+ "p50_duration_ms",+ "p95_duration_ms",+ "p99_duration_ms",+ "users",+ "sessions",+ "last_seen"+ ],+ "type": "string"+ },+ "MCPToolQualitySortDirection": {+ "enum": ["ASC", "DESC"],+ "type": "string"+ },"MCPToolSampleIntentItem": {"additionalProperties": false,"description": "One sampled call of a single MCP tool that carried a non-empty intent.",@@ -47779,6 +47825,10 @@},"type": "array"},+ "totalCount": {+ "$ref": "#/definitions/integer",+ "description": "Number of tools matching the date, category, and search filters."+ },"used_data_warehouse_sources": {"description": "Connector-synced data warehouse sources referenced by this query, if any.","items": {@@ -47801,7 +47851,7 @@"type": "array"}},- "required": ["results"],+ "required": ["results", "totalCount"],"type": "object"},{diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex e6ad6a996aa6..411eabd94503 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3516,16 +3516,40 @@ export interface MCPToolQualityRowItem {last_seen: string}+export type MCPToolQualitySortColumn =+ | 'total_calls'+ | 'error_rate_pct'+ | 'p50_duration_ms'+ | 'p95_duration_ms'+ | 'p99_duration_ms'+ | 'users'+ | 'sessions'+ | 'last_seen'++export type MCPToolQualitySortDirection = 'ASC' | 'DESC'+export interface MCPToolQualityRowsQueryResponse extends AnalyticsQueryResponseBase {results: MCPToolQualityRowItem[]+ /** Number of tools matching the date, category, and search filters. */+ totalCount: integer}-/** One row per $mcp_tool_name — call volume, error rate, latency percentiles, and reach — over the window. */+/** One row per effective MCP tool name, with server-side search, sorting, and pagination. */export interface MCPToolQualityRowsQuery extends DataNode<MCPToolQualityRowsQueryResponse> {kind: NodeKind.MCPToolQualityRowsQuerydateRange?: DateRange/** Restrict to these $mcp_tool_category values; empty or omitted means all categories. */categories?: string[]+ /** Case-insensitive substring search on the effective tool name. */+ search?: string+ /** Aggregate column used to order tools. Defaults to total_calls. */+ sortColumn?: MCPToolQualitySortColumn+ /** Sort direction. Defaults to DESC. */+ sortDirection?: MCPToolQualitySortDirection+ /** Page size. The server defaults to 50 and caps this at 100. */+ limit?: integer+ /** Number of matching tools to skip. */+ offset?: integer}export type CachedMCPToolQualityRowsQueryResponse = CachedQueryResponse<MCPToolQualityRowsQueryResponse>diff --git a/posthog/api/query.py b/posthog/api/query.pyindex 89d4771596f6..96dcdb06c59a 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -182,6 +182,7 @@ _QUERY_KIND_SCOPES: dict[str, list[str]] = {"MCPToolCallsAndErrorsQuery": ["query:read", "mcp_analytics:read"],"MCPToolCallBreakdownQuery": ["query:read", "mcp_analytics:read"],"MCPToolCategoryMapQuery": ["query:read", "mcp_analytics:read"],+ "MCPToolQualityRowsQuery": ["query:read", "mcp_analytics:read"],}diff --git a/posthog/schema.py b/posthog/schema.pyindex ccf7a7aa415b..d1e8af0093f9 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -176,6 +176,8 @@ from posthog.schema_enums import (MathGroupTypeIndex as MathGroupTypeIndex,MaxBillingContextBillingPeriodInterval as MaxBillingContextBillingPeriodInterval,MaxBillingContextSubscriptionLevel as MaxBillingContextSubscriptionLevel,+ MCPToolQualitySortColumn as MCPToolQualitySortColumn,+ MCPToolQualitySortDirection as MCPToolQualitySortDirection,MeanRetentionCalculation as MeanRetentionCalculation,MetaAdsConversionFallbackActionTypes as MetaAdsConversionFallbackActionTypes,MetaAdsConversionOmniActionTypes as MetaAdsConversionOmniActionTypes,@@ -12702,6 +12704,10 @@ class CachedMCPToolQualityRowsQueryResponse(BaseModel):default=None,description=("Measured timings for different parts of the query generation process"),)+ totalCount: int = Field(+ ...,+ description="Number of tools matching the date, category, and search filters.",+ )used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(default=None,description=("Connector-synced data warehouse sources referenced by this query, if any."),@@ -18234,6 +18240,10 @@ class MCPToolQualityRowsQueryResponse(BaseModel):default=None,description=("Measured timings for different parts of the query generation process"),)+ totalCount: int = Field(+ ...,+ description="Number of tools matching the date, category, and search filters.",+ )used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(default=None,description=("Connector-synced data warehouse sources referenced by this query, if any."),@@ -23293,6 +23303,10 @@ class QueryResponseAlternative104(BaseModel):default=None,description=("Measured timings for different parts of the query generation process"),)+ totalCount: int = Field(+ ...,+ description="Number of tools matching the date, category, and search filters.",+ )used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(default=None,description=("Connector-synced data warehouse sources referenced by this query, if any."),@@ -26614,8 +26628,24 @@ class MCPToolQualityRowsQuery(BaseModel):)dateRange: DateRange | None = Nonekind: Literal["MCPToolQualityRowsQuery"] = "MCPToolQualityRowsQuery"+ limit: int | None = Field(+ default=None,+ description="Page size. The server defaults to 50 and caps this at 100.",+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = Field(default=None, description="Number of matching tools to skip.")response: MCPToolQualityRowsQueryResponse | None = None+ search: str | None = Field(+ default=None,+ description="Case-insensitive substring search on the effective tool name.",+ )+ sortColumn: MCPToolQualitySortColumn | None = Field(+ default=None,+ description="Aggregate column used to order tools. Defaults to total_calls.",+ )+ sortDirection: MCPToolQualitySortDirection | None = Field(+ default=None, description="Sort direction. Defaults to DESC."+ )tags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 0d1a1879cf6e..b994c52e4ac7 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3094,6 +3094,22 @@ class NeighborDirection(StrEnum):AFTER = "after"+class MCPToolQualitySortColumn(StrEnum):+ TOTAL_CALLS = "total_calls"+ ERROR_RATE_PCT = "error_rate_pct"+ P50_DURATION_MS = "p50_duration_ms"+ P95_DURATION_MS = "p95_duration_ms"+ P99_DURATION_MS = "p99_duration_ms"+ USERS = "users"+ SESSIONS = "sessions"+ LAST_SEEN = "last_seen"+++class MCPToolQualitySortDirection(StrEnum):+ ASC = "ASC"+ DESC = "DESC"++class MarketingAnalyticsAttributionBreakdown(StrEnum):CHANNEL = "channel"SOURCE = "source"diff --git a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.pyindex 9fd9c1385a75..651a39ec4848 100644--- a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py+++ b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py@@ -1,13 +1,11 @@"""Query runners for the MCP analytics Tool quality tab.-The tab's per-tool table, aggregate activity series, and category share/counts.-Unlike the per-tool detail runners in `tool_tables.py`, these scope by the raw-`$mcp_tool_name` property (not the single-exec-resolved effective tool), matching-the tab's broad overview — the two surfaces intentionally query different populations.+The per-tool table and activity series resolve the effective tool name so exec-wrapped+calls match the per-tool detail runners. Category queries use the event-supplied category."""from functools import cached_property-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Literal, castfrom posthog.schema import (CachedMCPToolCategoriesQueryResponse,@@ -41,7 +39,11 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENT-from products.mcp_analytics.backend.hogql_queries.base import mcp_query_date_range, validate_mcp_analytics_access+from products.mcp_analytics.backend.hogql_queries.base import (+ EFFECTIVE_TOOL_SQL,+ mcp_query_date_range,+ validate_mcp_analytics_access,+)if TYPE_CHECKING:from posthog.models.user import User@@ -52,6 +54,18 @@ _P50 = "round(quantile(0.5)(toFloat(properties.$mcp_duration_ms)))"_P95 = "round(quantile(0.95)(toFloat(properties.$mcp_duration_ms)))"_P99 = "round(quantile(0.99)(toFloat(properties.$mcp_duration_ms)))"_IS_ERROR = "countIf(toBool(properties.$mcp_is_error))"+_TOOL_ROW_DEFAULT_LIMIT = 50+_TOOL_ROW_MAX_LIMIT = 100+_TOOL_SORT_COLUMNS = {+ "total_calls",+ "error_rate_pct",+ "p50_duration_ms",+ "p95_duration_ms",+ "p99_duration_ms",+ "users",+ "sessions",+ "last_seen",+}def _category_in(categories: list[str] | None) -> list[ast.Expr]:@@ -77,13 +91,19 @@ def _named_tool_where(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()}),- parse_expr("properties.$mcp_tool_name IS NOT NULL"),- parse_expr("properties.$mcp_tool_name != ''"),+ 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),]if tool_name:exprs.append(- parse_expr("properties.$mcp_tool_name = {tool}", placeholders={"tool": ast.Constant(value=tool_name)})+ parse_expr(+ "{effective_tool} = {tool}",+ placeholders={+ "effective_tool": parse_expr(EFFECTIVE_TOOL_SQL),+ "tool": ast.Constant(value=tool_name),+ },+ ))return ast.And(exprs=exprs)@@ -99,11 +119,22 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuerydef query_date_range(self) -> QueryDateRange:return mcp_query_date_range(self.team, self.query.dateRange)- def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:- return parse_select(+ def to_query(+ self, *, limit_override: int | None = None, offset_override: int | None = None+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ requested_limit = limit_override if limit_override is not None else self.query.limit+ limit = min(max(requested_limit or _TOOL_ROW_DEFAULT_LIMIT, 1), _TOOL_ROW_MAX_LIMIT)+ offset = max(offset_override if offset_override is not None else self.query.offset or 0, 0)+ search = (self.query.search or "").strip()+ sort_column = self.query.sortColumn or "total_calls"+ if sort_column not in _TOOL_SORT_COLUMNS:+ sort_column = "total_calls"+ sort_direction = cast(Literal["ASC", "DESC"], self.query.sortDirection or "DESC")++ query = parse_select("""SELECT- toString(properties.$mcp_tool_name) AS tool,+ {_EFFECTIVE_TOOL} AS tool,count() AS total_calls,{_IS_ERROR} AS errors,round({_IS_ERROR} * 100.0 / count(), 1) AS error_rate_pct,@@ -113,21 +144,34 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQueryuniq(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+ max(timestamp) AS last_seen,+ count() OVER () AS total_countFROM eventsWHERE {where}GROUP BY tool- ORDER BY total_calls DESC- LIMIT 200+ HAVING positionCaseInsensitive(tool, {search}) > 0+ ORDER BY total_calls DESC, tool ASC+ LIMIT {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),"where": _named_tool_where(self.query_date_range, self.query.categories),+ "search": ast.Constant(value=search),+ "limit": ast.Constant(value=limit),+ "offset": ast.Constant(value=offset),},)+ if isinstance(query, ast.SelectQuery):+ query.order_by = [+ ast.OrderExpr(expr=ast.Field(chain=[sort_column]), order=sort_direction),+ ast.OrderExpr(expr=ast.Field(chain=["tool"]), order="ASC"),+ ]+ return querydef _calculate(self) -> MCPToolQualityRowsQueryResponse:with tags_context(@@ -145,7 +189,20 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuerymodifiers=self.modifiers,limit_context=self.limit_context,)-+ rows = response.results or []+ total_count = int(rows[0][11] or 0) if rows else 0+ if 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),+ team=self.team,+ user=self.user,+ query_type="mcp_tool_quality_rows_query",+ timings=self.timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context,+ )+ first_row = first_row_response.results or []+ total_count = int(first_row[0][11] or 0) if first_row else 0results = [MCPToolQualityRowItem(tool=str(row[0] or ""),@@ -160,10 +217,14 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQueryfirst_seen=str(row[9] or ""),last_seen=str(row[10] or ""),)- for row in (response.results or [])+ for row in rows]return MCPToolQualityRowsQueryResponse(- results=results, timings=response.timings, hogql=response.hogql, modifiers=self.modifiers+ results=results,+ totalCount=total_count,+ timings=response.timings,+ hogql=response.hogql,+ modifiers=self.modifiers,)diff --git a/products/mcp_analytics/backend/tests/test_dashboard_series.py b/products/mcp_analytics/backend/tests/test_dashboard_series.pyindex ddebc3da1a7f..f9d42e75a75b 100644--- a/products/mcp_analytics/backend/tests/test_dashboard_series.py+++ b/products/mcp_analytics/backend/tests/test_dashboard_series.py@@ -239,7 +239,12 @@ class TestMCPDashboardSeriesGate(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTes@parameterized.expand([(kind, scopes, expected_status)- for kind in ("MCPToolCallsAndErrorsQuery", "MCPToolCallBreakdownQuery", "MCPToolCategoryMapQuery")+ for kind in (+ "MCPToolCallsAndErrorsQuery",+ "MCPToolCallBreakdownQuery",+ "MCPToolCategoryMapQuery",+ "MCPToolQualityRowsQuery",+ )for scopes, expected_status in ((["query:read"], 403),(["mcp_analytics:read"], 403),diff --git a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py b/products/mcp_analytics/backend/tests/test_tool_quality_tables.pyindex 7290291fc97d..5374403cd786 100644--- a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py+++ b/products/mcp_analytics/backend/tests/test_tool_quality_tables.py@@ -14,6 +14,7 @@ from posthog.schema import (MCPToolCategoryMapQuery,MCPToolQualityDailyStatsQuery,MCPToolQualityRowsQuery,+ MCPToolQualityRowsQueryResponse,)from products.access_control.backend.facade.user_access_control import UserAccessControlError@@ -33,6 +34,7 @@ def _emit(team: Any,*,tool_name: str = "query_run",+ exec_tool_name: str | None = None,category: str | None = None,is_error: bool = False,duration_ms: float = 100,@@ -49,6 +51,8 @@ def _emit(}if category is not None:properties["$mcp_tool_category"] = category+ if exec_tool_name is not None:+ properties["$mcp_exec_tool_call_name"] = exec_tool_name_create_event(team=team,event="$mcp_tool_call",@@ -59,35 +63,80 @@ def _emit(class TestMCPToolQualityRowsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):- def _run(self, categories: list[str] | None = None) -> list[Any]:+ def _run(self, categories: list[str] | None = None) -> MCPToolQualityRowsQueryResponse:runner = MCPToolQualityRowsQueryRunner(query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"), categories=categories),team=self.team,)- return runner.calculate().results+ return runner.calculate()def test_one_row_per_tool_ordered_by_calls_with_error_rate(self) -> None:_emit(self.team, tool_name="query_run", is_error=False)_emit(self.team, tool_name="query_run", is_error=True)+ _emit(self.team, tool_name="exec", exec_tool_name="query_run", is_error=False)_emit(self.team, tool_name="insight_get", is_error=False)flush_persons_and_events()- rows = self._run()+ rows = self._run().resultsassert [r.tool for r in rows] == ["query_run", "insight_get"]- assert rows[0].total_calls == 2+ assert rows[0].total_calls == 3assert rows[0].errors == 1- assert rows[0].error_rate_pct == 50.0+ assert rows[0].error_rate_pct == 33.3def test_category_filter_narrows_the_rows(self) -> None:_emit(self.team, tool_name="query_run", category="Data")_emit(self.team, tool_name="insight_get", category="Insights")flush_persons_and_events()- rows = self._run(categories=["Data"])+ rows = self._run(categories=["Data"]).resultsassert [r.tool for r in rows] == ["query_run"]+ def test_search_sort_and_pagination_apply_to_all_matching_tools(self) -> None:+ for _ in range(3):+ _emit(self.team, tool_name="popular_tool")+ for _ in range(2):+ _emit(self.team, tool_name="steady_tool")+ _emit(self.team, tool_name="rare_target", is_error=True)+ flush_persons_and_events()++ first_page = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"), limit=2),+ team=self.team,+ ).calculate()+ last_page = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"), limit=2, offset=2),+ team=self.team,+ ).calculate()+ out_of_range_page = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"), limit=2, offset=100),+ team=self.team,+ ).calculate()+ searched = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"), search="TARGET", limit=1),+ team=self.team,+ ).calculate()+ highest_error_rate = MCPToolQualityRowsQueryRunner(+ query=MCPToolQualityRowsQuery(+ dateRange=DateRange(date_from="-7d"),+ sortColumn="error_rate_pct",+ sortDirection="DESC",+ limit=1,+ ),+ team=self.team,+ ).calculate()++ assert [row.tool for row in first_page.results] == ["popular_tool", "steady_tool"]+ assert first_page.totalCount == 3+ assert [row.tool for row in last_page.results] == ["rare_target"]+ assert last_page.totalCount == 3+ assert out_of_range_page.results == []+ assert out_of_range_page.totalCount == 3+ assert [row.tool for row in searched.results] == ["rare_target"]+ assert searched.totalCount == 1+ assert [row.tool for row in highest_error_rate.results] == ["rare_target"]+class TestMCPToolQualityDailyStatsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):def test_buckets_by_hour_when_interval_is_hour(self) -> None:@@ -107,6 +156,7 @@ class TestMCPToolQualityDailyStatsQueryRunner(_MCPAnalyticsTeamScopedTestMixin,def test_tool_name_scopes_the_series(self) -> None:_emit(self.team, tool_name="query_run")+ _emit(self.team, tool_name="exec", exec_tool_name="query_run")_emit(self.team, tool_name="insight_get")flush_persons_and_events()@@ -116,7 +166,7 @@ class TestMCPToolQualityDailyStatsQueryRunner(_MCPAnalyticsTeamScopedTestMixin,)rows = runner.calculate().results- assert sum(r.calls for r in rows) == 1+ assert sum(r.calls for r in rows) == 2class TestMCPToolCategoryCountsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsxindex 26e86740c7a8..b496ca4cad42 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx@@ -157,13 +157,31 @@ const TOOL_CALL_LIST = {// Tool quality tab — one row per tool: tool, total_calls, errors, error_rate_pct,// p50, p95, p99, users, sessions, first_seen, last_seen.-const TOOL_QUALITY_ROWS = [+type ToolQualityStoryRow = [string, number, number, number, number, number, number, number, number, string, string]++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'],['query-trends', 540, 5, 1.0, 410, 2122, 4100, 120, 300, '2026-05-09T11:00:00Z', '2026-06-07T09:45:00Z'],['insight-create', 410, 8, 2.0, 260, 727, 1500, 95, 210, '2026-05-10T14:00:00Z', '2026-06-06T18:00:00Z'],['dashboard-create', 260, 2, 0.8, 300, 940, 1800, 70, 150, '2026-05-11T10:00:00Z', '2026-06-06T16:00:00Z'],['cohort-create', 95, 6, 6.3, 480, 1620, 3100, 40, 80, '2026-05-12T13:00:00Z', '2026-06-05T12:00:00Z'],+ ...Array.from(+ { length: 54 },+ (_, index): ToolQualityStoryRow => [+ `workflow-action-${String(index + 1).padStart(2, '0')}`,+ 90 - index,+ index % 7 === 0 ? 1 : 0,+ index % 7 === 0 ? 1.5 : 0,+ 120 + index * 5,+ 480 + index * 10,+ 900 + index * 20,+ 30 + index,+ 40 + index,+ '2026-05-12T13:00:00Z',+ '2026-06-05T12:00:00Z',+ ]+ ),]// Tool quality daily stats (selected/aggregate): day, calls, errors, p50, p95, p99.@@ -595,22 +613,44 @@ 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 search = String(body.query.search ?? '')+ .trim()+ .toLowerCase()+ const filteredRows = search+ ? rows.filter((row) => row.tool.toLowerCase().includes(search))+ : rows+ const sortColumn = String(body.query.sortColumn ?? 'total_calls')+ const sortDirection = body.query.sortDirection === 'ASC' ? 1 : -1+ filteredRows.sort((left, right) => {+ const leftValue = left[sortColumn as keyof typeof left]+ const rightValue = right[sortColumn as keyof typeof right]+ const comparison =+ typeof leftValue === 'number' && typeof rightValue === 'number'+ ? leftValue - rightValue+ : String(leftValue).localeCompare(String(rightValue))+ return comparison === 0 ? left.tool.localeCompare(right.tool) : comparison * sortDirection+ })+ const limit = Number(body.query.limit ?? 50)+ const offset = Number(body.query.offset ?? 0)+ const page = filteredRows.slice(offset, offset + limit)return [200,{- results: 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],- })),+ results: page,+ totalCount: filteredRows.length,},]}diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.tsindex 636890e5a285..695ac4029764 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts@@ -2,6 +2,7 @@ import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { formatMsAsSeconds } from './dashboard/formatters'@@ -14,6 +15,8 @@ jest.mock('~/queries/query', () => ({const mockApi = api as jest.Mocked<typeof api>+const emptyToolRowsResponse = { results: [], totalCount: 0 }+function dailyStat(overrides: Partial<DailyToolStat> & { day: string }): DailyToolStat {return { calls: 0, errors: 0, p50: 0, p95: 0, p99: 0, ...overrides }}@@ -75,7 +78,9 @@ describe('mcpAnalyticsToolQualityLogic', () => {beforeEach(() => {jest.clearAllMocks()initKeaTests()- jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] })+ jest.spyOn(mockApi, 'query').mockImplementation(async (query: any) =>+ query.kind === NodeKind.MCPToolQualityRowsQuery ? emptyToolRowsResponse : { results: [] }+ )})// An open-ended relative window always ends in the bucket that is still collecting, and a@@ -98,7 +103,9 @@ describe('mcpAnalyticsToolQualityLogic', () => {beforeEach(() => {jest.clearAllMocks()initKeaTests()- jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] })+ jest.spyOn(mockApi, 'query').mockImplementation(async (query: any) =>+ query.kind === NodeKind.MCPToolQualityRowsQuery ? emptyToolRowsResponse : { results: [] }+ )})function queryCallsSince(callIndex: number): Record<string, any>[] {@@ -157,8 +164,12 @@ describe('mcpAnalyticsToolQualityLogic', () => {last_seen: '',})- it('clears the selected tool when a reload no longer includes it', async () => {- mockApi.query.mockResolvedValue({ results: [toolRowResult('tool_a')] })+ it('clears the selected tool when the category scope changes', async () => {+ mockApi.query.mockImplementation(async (query: any) =>+ query.kind === NodeKind.MCPToolQualityRowsQuery+ ? { ...emptyToolRowsResponse, results: [toolRowResult('tool_a')], totalCount: 1 }+ : { results: [] }+ )const logic = mcpAnalyticsToolQualityLogic()logic.mount()await expectLogic(logic).toFinishAllListeners()@@ -167,7 +178,6 @@ describe('mcpAnalyticsToolQualityLogic', () => {await expectLogic(logic).toFinishAllListeners()expect(logic.values.selectedTool).toBe('tool_a')- mockApi.query.mockResolvedValue({ results: [toolRowResult('tool_b')] })await expectLogic(logic, () => {logic.actions.setSelectedCategories(['some-category'])}).toFinishAllListeners()@@ -175,20 +185,61 @@ describe('mcpAnalyticsToolQualityLogic', () => {expect(logic.values.selectedTool).toBeNull()})- it('keeps the selected tool when a reload still includes it', async () => {- mockApi.query.mockResolvedValue({ results: [toolRowResult('tool_a'), toolRowResult('tool_b')] })+ it('keeps the selected tool while searching, sorting, or changing pages', async () => {+ mockApi.query.mockImplementation(async (query: any) =>+ query.kind === NodeKind.MCPToolQualityRowsQuery+ ? { ...emptyToolRowsResponse, results: [toolRowResult('tool_b')], totalCount: 100 }+ : { results: [] }+ )const logic = mcpAnalyticsToolQualityLogic()logic.mount()await expectLogic(logic).toFinishAllListeners()logic.actions.setSelectedTool('tool_a')await expectLogic(logic, () => {- logic.actions.setSelectedCategories(['some-category'])+ logic.actions.setToolQualityPageIndex(1)+ logic.actions.setSearchTerm('tool_b')+ logic.actions.setToolQualitySort('error_rate_pct', 'DESC')}).toFinishAllListeners()expect(logic.values.selectedTool).toBe('tool_a')})+ it('sends search, global sort, and page offsets to the rows query', async () => {+ mockApi.query.mockImplementation(async (query: any) =>+ query.kind === NodeKind.MCPToolQualityRowsQuery+ ? { ...emptyToolRowsResponse, results: [toolRowResult('tool_a')], totalCount: 151 }+ : { results: [] }+ )+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ let callsBefore = mockApi.query.mock.calls.length+ await expectLogic(logic, () => {+ logic.actions.setToolQualityPageIndex(2)+ }).toFinishAllListeners()+ let rowsQuery = queryCallsSince(callsBefore).find(+ (query) => query.kind === NodeKind.MCPToolQualityRowsQuery+ )+ expect(rowsQuery).toMatchObject({ limit: 50, offset: 100 })++ callsBefore = mockApi.query.mock.calls.length+ await expectLogic(logic, () => {+ logic.actions.setSearchTerm('needle')+ }).toFinishAllListeners()+ rowsQuery = queryCallsSince(callsBefore).find((query) => query.kind === NodeKind.MCPToolQualityRowsQuery)+ expect(logic.values.toolQualityPageIndex).toBe(0)+ expect(rowsQuery).toMatchObject({ search: 'needle', limit: 50, offset: 0 })++ callsBefore = mockApi.query.mock.calls.length+ await expectLogic(logic, () => {+ logic.actions.setToolQualitySort('error_rate_pct', 'ASC')+ }).toFinishAllListeners()+ rowsQuery = queryCallsSince(callsBefore).find((query) => query.kind === NodeKind.MCPToolQualityRowsQuery)+ expect(rowsQuery).toMatchObject({ sortColumn: 'error_rate_pct', sortDirection: 'ASC', offset: 0 })+ })+it('refetches the charts at the picked grouping, leaving the table alone', async () => {const logic = mcpAnalyticsToolQualityLogic()logic.mount()diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex 55e238b05e41..91f84275d541 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -12,6 +12,7 @@ import {MCPToolCategoryItem,MCPToolQualityDailyStatItem,MCPToolQualityRowItem,+ MCPToolQualityRowsQueryResponse,NodeKind,} from '~/queries/schema/schema-general'import { IntervalType } from '~/types'@@ -40,7 +41,7 @@ export interface ScopeShare {export type SortDirection = 'ASC' | 'DESC'export interface SortState {- column: string+ column: ToolQualitySortColumndirection: SortDirection}@@ -77,19 +78,8 @@ export function mcpToolQualityUrlWithDates(dateFilter: DateFilter, interval?: Inreturn combineUrl(urls.mcpAnalyticsToolQuality(), mcpDateSearchParams(dateFilter, interval)).url}-export interface ToolQualityRow {- tool: string- total_calls: number- errors: number- error_rate_pct: number- p50_duration_ms: number- p95_duration_ms: number- p99_duration_ms: number- users: number- sessions: number- first_seen: string- last_seen: string-}+export type ToolQualityRow = MCPToolQualityRowItem+export type ToolQualitySortColumn = Exclude<keyof ToolQualityRow, 'tool' | 'errors' | 'first_seen'>export interface DailyToolStat {day: string@@ -112,6 +102,7 @@ export interface DailyChartData {const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-7d', dateTo: null }const DEFAULT_SORT: SortState = { column: 'total_calls', direction: 'DESC' }+export const TOOL_QUALITY_PAGE_SIZE = 50// Pivot per-bucket rows onto the full set of interval buckets spanning the selected window:// ClickHouse only returns buckets that had events, so `bucketKeys` (built from the window at the@@ -133,19 +124,6 @@ export function buildDailyChartData(dailyStats: DailyToolStat[], bucketKeys: str}}-function sortToolRows(rows: ToolQualityRow[], sort: SortState): ToolQualityRow[] {- const direction = sort.direction === 'ASC' ? 1 : -1- const column = sort.column as keyof ToolQualityRow- return [...rows].sort((a, b) => {- const aValue = a[column]- const bValue = b[column]- if (typeof aValue === 'number' && typeof bValue === 'number') {- return (aValue - bValue) * direction- }- return String(aValue).localeCompare(String(bValue)) * direction- })-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpAnalyticsToolQualityLogicValues {availableCategories: string[]@@ -157,7 +135,6 @@ export interface mcpAnalyticsToolQualityLogicValues {dailyStatsLoading: booleandateFilter: DateFilterdateRangeLabel: string- filteredRows: ToolQualityRow[]incompleteTail: booleaninterval: IntervalTypeintervalOptions: IntervalOption[]@@ -166,9 +143,12 @@ export interface mcpAnalyticsToolQualityLogicValues {searchTerm: stringselectedCategories: string[]selectedTool: string | null+ toolQualityPageIndex: numbertoolQualitySort: SortState- toolRows: ToolQualityRow[]- toolRowsLoading: boolean+ toolRows: MCPToolQualityRowItem[]+ toolRowsPage: MCPToolQualityRowsQueryResponse | null+ toolRowsPageLoading: boolean+ toolRowsTotalCount: number}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -218,19 +198,19 @@ export interface mcpAnalyticsToolQualityLogicActions {dailyStats: DailyToolStat[]payload?: void}- loadToolRows: (_: void) => void- loadToolRowsFailure: (+ loadToolRowsPage: (_: void) => void+ loadToolRowsPageFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any}- loadToolRowsSuccess: (- toolRows: ToolQualityRow[],+ loadToolRowsPageSuccess: (+ toolRowsPage: MCPToolQualityRowsQueryResponse,payload?: void) => {- toolRows: ToolQualityRow[]+ toolRowsPage: MCPToolQualityRowsQueryResponsepayload?: void}reloadAll: () => {@@ -255,11 +235,14 @@ export interface mcpAnalyticsToolQualityLogicActions {setSelectedTool: (tool: string | null) => {tool: string | null}+ setToolQualityPageIndex: (pageIndex: number) => {+ pageIndex: number+ }setToolQualitySort: (- column: string,+ column: ToolQualitySortColumn,direction: SortDirection) => {- column: string+ column: ToolQualitySortColumndirection: SortDirection}}@@ -271,7 +254,8 @@ export interface mcpAnalyticsToolQualityLogicMeta {intervalOptions: (dateFilter: DateFilter, timezone: string) => IntervalOption[]interval: (dateFilter: DateFilter, pinnedInterval: IntervalType | null, timezone: string) => IntervalTypescopeShare: (categoryCounts: CategoryCount[], selectedCategories: string[]) => ScopeShare- filteredRows: (toolRows: ToolQualityRow[], toolQualitySort: SortState, searchTerm: string) => ToolQualityRow[]+ toolRows: (toolRowsPage: MCPToolQualityRowsQueryResponse | null) => MCPToolQualityRowItem[]+ toolRowsTotalCount: (toolRowsPage: MCPToolQualityRowsQueryResponse | null) => numberdailyChartData: (dailyStats: DailyToolStat[],dateFilter: DateFilter,@@ -293,7 +277,8 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypepath(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsToolQualityLogic']),actions({- setToolQualitySort: (column: string, direction: SortDirection) => ({ column, direction }),+ setToolQualitySort: (column: ToolQualitySortColumn, direction: SortDirection) => ({ column, direction }),+ setToolQualityPageIndex: (pageIndex: number) => ({ pageIndex }),setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setPinnedInterval: (interval: IntervalType | null) => ({ interval }),setSelectedCategories: (categories: string[]) => ({ categories }),@@ -342,6 +327,12 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypesetSearchTerm: (_, { searchTerm }): string => searchTerm,},],+ toolQualityPageIndex: [+ 0,+ {+ setToolQualityPageIndex: (_, { pageIndex }): number => Math.max(pageIndex, 0),+ },+ ],}),loaders(({ values }) => ({@@ -370,31 +361,23 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType},},],- toolRows: [- [] as ToolQualityRow[],+ toolRowsPage: [+ null as MCPToolQualityRowsQueryResponse | null,{- loadToolRows: async (_: void, breakpoint): Promise<ToolQualityRow[]> => {- await breakpoint(100)- // Fixed server-side order (total_calls DESC); column sorting happens client-side.+ loadToolRowsPage: async (_: void, breakpoint): Promise<MCPToolQualityRowsQueryResponse> => {+ await breakpoint(300)const response = (await api.query({kind: NodeKind.MCPToolQualityRowsQuery,dateRange: { date_from: values.dateFilter.dateFrom, date_to: values.dateFilter.dateTo },categories: values.selectedCategories,- })) as { results?: MCPToolQualityRowItem[] }+ search: values.searchTerm,+ sortColumn: values.toolQualitySort.column,+ sortDirection: values.toolQualitySort.direction,+ limit: TOOL_QUALITY_PAGE_SIZE,+ offset: values.toolQualityPageIndex * TOOL_QUALITY_PAGE_SIZE,+ })) as MCPToolQualityRowsQueryResponsebreakpoint()- return (response.results ?? []).map((r) => ({- tool: r.tool,- total_calls: r.total_calls,- errors: r.errors,- error_rate_pct: r.error_rate_pct,- p50_duration_ms: r.p50_duration_ms,- p95_duration_ms: r.p95_duration_ms,- p99_duration_ms: r.p99_duration_ms,- users: r.users,- sessions: r.sessions,- first_seen: r.first_seen,- last_seen: r.last_seen,- }))+ return response},},],@@ -456,13 +439,14 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypereturn { inScope, total, pct: total > 0 ? (inScope / total) * 100 : null }},],- filteredRows: [- (s) => [s.toolRows, s.toolQualitySort, s.searchTerm],- (toolRows: ToolQualityRow[], sort: SortState, searchTerm: string): ToolQualityRow[] => {- const term = searchTerm.trim().toLowerCase()- const filtered = term ? toolRows.filter((row) => row.tool.toLowerCase().includes(term)) : toolRows- return sortToolRows(filtered, sort)- },+ toolRows: [+ (s) => [s.toolRowsPage],+ (toolRowsPage: MCPToolQualityRowsQueryResponse | null): MCPToolQualityRowItem[] =>+ toolRowsPage?.results ?? [],+ ],+ toolRowsTotalCount: [+ (s) => [s.toolRowsPage],+ (toolRowsPage: MCPToolQualityRowsQueryResponse | null): number => toolRowsPage?.totalCount ?? 0,],dailyChartData: [(s) => [s.dailyStats, s.dateFilter, s.interval, teamLogic.selectors.timezone],@@ -485,36 +469,58 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType],}),- listeners(({ actions, values }) => ({- // Both scope filters refetch the table and the charts; a date change also- // refreshes the category counts so the "share of MCP usage" headline tracks- // the same window.- setDateFilter: () => {- actions.reloadAll()- actions.loadCategoryCounts()- },- setSelectedCategories: () => {- actions.reloadAll()- },- // Only the charts bucket by interval; the table is a single-window aggregate.- setPinnedInterval: () => {- actions.loadDailyStats()- },- reloadAll: () => {- actions.loadToolRows()- actions.loadDailyStats()- },- setSelectedTool: () => {- actions.loadDailyStats()- },- // A category or date change can reload rows that no longer include the- // selected tool — drop the selection instead of charting an empty scope- loadToolRowsSuccess: ({ toolRows }) => {- if (values.selectedTool && !toolRows.some((row) => row.tool === values.selectedTool)) {+ listeners(({ actions, values }) => {+ const loadFirstToolPage = (): void => {+ if (values.toolQualityPageIndex === 0) {+ actions.loadToolRowsPage()+ } else {+ actions.setToolQualityPageIndex(0)+ }+ }+ const loadUnscopedDailyStats = (): void => {+ if (values.selectedTool) {actions.setSelectedTool(null)+ } else {+ actions.loadDailyStats()}- },- })),+ }++ return {+ setDateFilter: () => {+ loadFirstToolPage()+ loadUnscopedDailyStats()+ actions.loadCategoryCounts()+ },+ setSelectedCategories: () => {+ loadFirstToolPage()+ loadUnscopedDailyStats()+ },+ setToolQualitySort: () => {+ loadFirstToolPage()+ },+ setSearchTerm: () => {+ loadFirstToolPage()+ },+ setToolQualityPageIndex: () => {+ actions.loadToolRowsPage()+ },+ setPinnedInterval: () => {+ actions.loadDailyStats()+ },+ reloadAll: () => {+ actions.loadToolRowsPage()+ actions.loadDailyStats()+ },+ setSelectedTool: () => {+ actions.loadDailyStats()+ },+ loadToolRowsPageSuccess: ({ toolRowsPage }) => {+ if (values.toolQualityPageIndex > 0 && toolRowsPage.results.length === 0) {+ actions.setToolQualityPageIndex(0)+ }+ },+ }+ }),actionToUrl(({ values }) => {const syncUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {@@ -585,7 +591,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypeafterMount(({ actions }) => {actions.loadAvailableCategories()actions.loadCategoryCounts()- actions.loadToolRows()+ actions.loadToolRowsPage()actions.loadDailyStats()}),])diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsxindex 5de842b524fb..1cfcd0f1f45c 100644--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx@@ -13,6 +13,13 @@ import {InputGroupAddon,InputGroupInput,InputGroupText,+ Pagination,+ PaginationButton,+ PaginationContent,+ PaginationEllipsis,+ PaginationItem,+ PaginationNext,+ PaginationPrevious,Table,TableBody,TableCell,@@ -20,6 +27,8 @@ import {TableHead,TableHeader,TableRow,+ Text,+ getPaginationRange,} from '@posthog/quill-primitives'import { TZLabel } from 'lib/components/TZLabel'@@ -31,28 +40,16 @@ import { pluralize } from 'lib/utils/strings'import { formatMs, formatNumber } from '../dashboard/formatters'import {type SortState,- type ToolQualityRow,+ type ToolQualitySortColumn,+ TOOL_QUALITY_PAGE_SIZE,mcpAnalyticsToolQualityLogic,mcpToolReportUrl,} from '../mcpAnalyticsToolQualityLogic'const DESTRUCTIVE_ERROR_PCT = 5-// LIMIT in MCPToolQualityRowsQueryRunner — when the fetched set hits this, more tools may exist.-const TOOL_ROW_LIMIT = 200--function formatToolCount(filtered: number, total: number): string {- if (filtered < total) {- return `Showing ${filtered} of ${pluralize(total, 'tool')}`- }- if (total >= TOOL_ROW_LIMIT) {- return `Showing first ${pluralize(total, 'tool')}`- }- return pluralize(total, 'tool')-}-interface ColumnSpec {- key: keyof ToolQualityRow+ key: ToolQualitySortColumnlabel: stringalign?: 'left' | 'right'tooltip?: string@@ -91,17 +88,20 @@ function ErrorRateBadge({ pct }: { pct: number }): JSX.Element {function SortableHead({column,sort,+ loading,onSort,}: {column: ColumnSpecsort: SortState- onSort: (column: string, direction: 'ASC' | 'DESC') => void+ loading: boolean+ onSort: (column: ToolQualitySortColumn, direction: 'ASC' | 'DESC') => void}): JSX.Element {const isSorted = sort.column === column.keyconst nextDirection = isSorted && sort.direction === 'DESC' ? 'ASC' : 'DESC'const head = (<buttontype="button"+ disabled={loading}onClick={() => onSort(column.key, nextDirection)}className="inline-flex cursor-pointer select-none items-center gap-1">@@ -110,18 +110,21 @@ function SortableHead({</button>)return (- <TableHead align={column.align}>+ <TableHead+ align={column.align}+ aria-sort={isSorted ? (sort.direction === 'DESC' ? 'descending' : 'ascending') : 'none'}+ >{column.tooltip ? <Tooltip title={column.tooltip}>{head}</Tooltip> : head}</TableHead>)}function ToolRows(): JSX.Element {- const { filteredRows, toolRowsLoading, selectedTool, dateFilter, pinnedInterval } =+ const { toolRows, toolRowsPageLoading, selectedTool, dateFilter, pinnedInterval } =useValues(mcpAnalyticsToolQualityLogic)const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)- if (toolRowsLoading && filteredRows.length === 0) {+ if (toolRowsPageLoading) {return (<TableBody><TableRow>@@ -136,12 +139,12 @@ function ToolRows(): JSX.Element {</TableBody>)}- if (filteredRows.length === 0) {+ if (toolRows.length === 0) {return <TableEmpty className="py-6 text-secondary">No tool calls match the current filters.</TableEmpty>}return (<TableBody>- {filteredRows.map((row) => (+ {toolRows.map((row) => (<TableRowkey={row.tool}data-state={row.tool === selectedTool ? 'selected' : undefined}@@ -182,9 +185,13 @@ function ToolRows(): JSX.Element {}export function ToolQualityTable(): JSX.Element {- const { toolQualitySort, toolRows, filteredRows, toolRowsLoading, searchTerm } =+ const { toolQualitySort, toolQualityPageIndex, toolRows, toolRowsPageLoading, toolRowsTotalCount, searchTerm } =useValues(mcpAnalyticsToolQualityLogic)- const { setToolQualitySort, setSearchTerm } = useActions(mcpAnalyticsToolQualityLogic)+ const { setToolQualitySort, setToolQualityPageIndex, setSearchTerm } = useActions(mcpAnalyticsToolQualityLogic)+ const pageCount = Math.max(Math.ceil(toolRowsTotalCount / TOOL_QUALITY_PAGE_SIZE), 1)+ const pageRange = getPaginationRange(pageCount, toolQualityPageIndex)+ const firstRow = toolRowsTotalCount === 0 ? 0 : toolQualityPageIndex * TOOL_QUALITY_PAGE_SIZE + 1+ const lastRow = Math.min(firstRow + toolRows.length - 1, toolRowsTotalCount)return (<Card size="sm" className="gap-0">@@ -214,6 +221,7 @@ export function ToolQualityTable(): JSX.Element {key={column.key}column={column}sort={toolQualitySort}+ loading={toolRowsPageLoading}onSort={setToolQualitySort}/>))}@@ -222,9 +230,49 @@ export function ToolQualityTable(): JSX.Element {</TableHeader><ToolRows /></Table>- {!toolRowsLoading && toolRows.length > 0 && (- <CardFooter className="border-t border-border py-2 text-xs text-secondary">- {formatToolCount(filteredRows.length, toolRows.length)}+ {!toolRowsPageLoading && toolRowsTotalCount > 0 && (+ <CardFooter className="flex flex-row flex-wrap items-center justify-between gap-2 border-t border-border">+ <Text size="xs" variant="muted" render={<span />} className="tabular-nums">+ {firstRow}-{lastRow} of {pluralize(toolRowsTotalCount, 'tool')}+ </Text>+ {pageCount > 1 ? (+ <Pagination className="w-auto">+ <PaginationContent>+ <PaginationItem>+ <PaginationPrevious+ disabled={toolQualityPageIndex === 0}+ onClick={() => setToolQualityPageIndex(toolQualityPageIndex - 1)}+ data-attr="mcp-tool-quality-page-previous"+ />+ </PaginationItem>+ {pageRange.map((item, index) =>+ item === 'ellipsis' ? (+ <PaginationItem key={`ellipsis-${index}`}>+ <PaginationEllipsis />+ </PaginationItem>+ ) : (+ <PaginationItem key={item}>+ <PaginationButton+ isActive={item === toolQualityPageIndex}+ aria-label={`Go to page ${item + 1}`}+ onClick={() => setToolQualityPageIndex(item)}+ data-attr="mcp-tool-quality-page"+ >+ {item + 1}+ </PaginationButton>+ </PaginationItem>+ )+ )}+ <PaginationItem>+ <PaginationNext+ disabled={toolQualityPageIndex === pageCount - 1}+ onClick={() => setToolQualityPageIndex(toolQualityPageIndex + 1)}+ data-attr="mcp-tool-quality-page-next"+ />+ </PaginationItem>+ </PaginationContent>+ </Pagination>+ ) : null}</CardFooter>)}</Card>diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 373f748b3a1a..24ab6ae6235c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -44691,20 +44691,54 @@ export namespace Schemas {results: MCPToolQualityRowItem[];/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;+ /** Number of tools matching the date, category, and search filters. */+ totalCount: 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. */warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}+ export type MCPToolQualitySortColumn = typeof MCPToolQualitySortColumn[keyof typeof MCPToolQualitySortColumn];+++ export const MCPToolQualitySortColumn = {+ TotalCalls: 'total_calls',+ ErrorRatePct: 'error_rate_pct',+ P50DurationMs: 'p50_duration_ms',+ P95DurationMs: 'p95_duration_ms',+ P99DurationMs: 'p99_duration_ms',+ Users: 'users',+ Sessions: 'sessions',+ LastSeen: 'last_seen',+ } as const;++ export type MCPToolQualitySortDirection = typeof MCPToolQualitySortDirection[keyof typeof MCPToolQualitySortDirection];+++ export const MCPToolQualitySortDirection = {+ Asc: 'ASC',+ Desc: 'DESC',+ } as const;+export interface MCPToolQualityRowsQuery {/** Restrict to these $mcp_tool_category values; empty or omitted means all categories. */categories?: string[] | null;dateRange?: DateRange | null;kind?: 'MCPToolQualityRowsQuery';+ /** Page size. The server defaults to 50 and caps this at 100. */+ limit?: number | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ /** Number of matching tools to skip. */+ offset?: number | null;response?: MCPToolQualityRowsQueryResponse | null;+ /** Case-insensitive substring search on the effective tool name. */+ search?: string | null;+ /** Aggregate column used to order tools. Defaults to total_calls. */+ sortColumn?: MCPToolQualitySortColumn | null;+ /** Sort direction. Defaults to DESC. */+ sortDirection?: MCPToolQualitySortDirection | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */version?: number | null;@@ -72997,6 +73031,8 @@ export namespace Schemas {results: MCPToolQualityRowItem[];/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;+ /** Number of tools matching the date, category, and search filters. */+ totalCount: 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. */