: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): improve paginated tool quality table (#91188)
Lucas Faria907b25708a45
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsxindex 8c462e7d00dd..6c23d6d87810 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx@@ -67,6 +67,7 @@ const meta: Meta = {FEATURE_FLAGS.CUSTOMER_ANALYTICS_TRACK_RULES,],pageUrl: `${urls.customerAnalyticsConfiguration()}?tab=customer-analytics-track-rules`,+ mockDate: '2026-08-29T12:00:00Z',testOptions: {waitForSelector: '[data-attr="account-track-rules"]',},diff --git a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.pyindex 651a39ec4848..d50be5360c60 100644--- a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py+++ b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py@@ -85,8 +85,9 @@ def _named_tool_where(categories: list[str] | None,*,tool_name: str | None = None,+ search: str | None = None,) -> ast.Expr:- """WHERE for tool-name-bearing $mcp_tool_call events in the window, filtered by category/tool."""+ """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()}),@@ -105,6 +106,16 @@ def _named_tool_where(},))+ if search:+ exprs.append(+ parse_expr(+ "positionCaseInsensitive({effective_tool}, {search}) > 0",+ placeholders={+ "effective_tool": parse_expr(EFFECTIVE_TOOL_SQL),+ "search": ast.Constant(value=search),+ },+ )+ )return ast.And(exprs=exprs)@@ -149,7 +160,6 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQueryFROM eventsWHERE {where}GROUP BY tool- HAVING positionCaseInsensitive(tool, {search}) > 0ORDER BY total_calls DESC, tool ASCLIMIT {limit}OFFSET {offset}@@ -160,8 +170,7 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuery"_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),+ "where": _named_tool_where(self.query_date_range, self.query.categories, search=search),"limit": ast.Constant(value=limit),"offset": ast.Constant(value=offset),},diff --git a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py b/products/mcp_analytics/backend/tests/test_tool_quality_tables.pyindex 5374403cd786..1a77e0fcc575 100644--- a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py+++ b/products/mcp_analytics/backend/tests/test_tool_quality_tables.py@@ -17,6 +17,8 @@ from posthog.schema import (MCPToolQualityRowsQueryResponse,)+from posthog.hogql import ast+from products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.mcp_analytics.backend.hogql_queries.tool_quality_tables import (MCPToolCategoriesQueryRunner,@@ -113,10 +115,12 @@ class TestMCPToolQualityRowsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickhquery=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"), limit=2, offset=100),team=self.team,).calculate()- searched = MCPToolQualityRowsQueryRunner(+ searched_runner = MCPToolQualityRowsQueryRunner(query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"), search="TARGET", limit=1),team=self.team,- ).calculate()+ )+ searched_query = searched_runner.to_query()+ searched = searched_runner.calculate()highest_error_rate = MCPToolQualityRowsQueryRunner(query=MCPToolQualityRowsQuery(dateRange=DateRange(date_from="-7d"),@@ -133,6 +137,8 @@ class TestMCPToolQualityRowsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickhassert last_page.totalCount == 3assert out_of_range_page.results == []assert out_of_range_page.totalCount == 3+ assert isinstance(searched_query, ast.SelectQuery)+ assert searched_query.having is Noneassert [row.tool for row in searched.results] == ["rare_target"]assert searched.totalCount == 1assert [row.tool for row in highest_error_rate.results] == ["rare_target"]diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.tsindex 695ac4029764..96dcf2d05b27 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts@@ -205,6 +205,31 @@ describe('mcpAnalyticsToolQualityLogic', () => {expect(logic.values.selectedTool).toBe('tool_a')})+ it('keeps the current rows visible while another page loads', async () => {+ mockApi.query.mockImplementation(async (query: any) => {+ if (query.kind !== NodeKind.MCPToolQualityRowsQuery) {+ return { results: [] }+ }+ const tool = query.offset === 0 ? 'page-one-tool' : 'page-two-tool'+ return { ...emptyToolRowsResponse, results: [toolRowResult(tool)], totalCount: 100 }+ })+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.toolRows.map((row) => row.tool)).toEqual(['page-one-tool'])++ logic.actions.setToolQualityPageIndex(1)++ expect(logic.values.toolRowsPageLoading).toBe(true)+ expect(logic.values.loadedToolQualityPageIndex).toBe(0)+ expect(logic.values.toolRows.map((row) => row.tool)).toEqual(['page-one-tool'])++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.loadedToolQualityPageIndex).toBe(1)+ expect(logic.values.toolRows.map((row) => row.tool)).toEqual(['page-two-tool'])+ })+it('sends search, global sort, and page offsets to the rows query', async () => {mockApi.query.mockImplementation(async (query: any) =>query.kind === NodeKind.MCPToolQualityRowsQuerydiff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex 91f84275d541..70afb51a5335 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -50,6 +50,10 @@ export interface DateFilter {dateTo: string | null}+interface ToolRowsPage extends MCPToolQualityRowsQueryResponse {+ pageIndex: number+}+// Carry the selected window across navigation as date_from / date_to, plus the grouping interval// when one is pinned, mirroring the tab's actionToUrl. Only set them when present so a cleared range// and an auto interval stay out of the URL.@@ -138,6 +142,7 @@ export interface mcpAnalyticsToolQualityLogicValues {incompleteTail: booleaninterval: IntervalTypeintervalOptions: IntervalOption[]+ loadedToolQualityPageIndex: numberpinnedInterval: IntervalType | nullscopeShare: ScopeSharesearchTerm: string@@ -146,7 +151,7 @@ export interface mcpAnalyticsToolQualityLogicValues {toolQualityPageIndex: numbertoolQualitySort: SortStatetoolRows: MCPToolQualityRowItem[]- toolRowsPage: MCPToolQualityRowsQueryResponse | null+ toolRowsPage: ToolRowsPage | nulltoolRowsPageLoading: booleantoolRowsTotalCount: number}@@ -207,10 +212,10 @@ export interface mcpAnalyticsToolQualityLogicActions {errorObject?: any}loadToolRowsPageSuccess: (- toolRowsPage: MCPToolQualityRowsQueryResponse,+ toolRowsPage: ToolRowsPage,payload?: void) => {- toolRowsPage: MCPToolQualityRowsQueryResponse+ toolRowsPage: ToolRowsPagepayload?: void}reloadAll: () => {@@ -254,8 +259,9 @@ export interface mcpAnalyticsToolQualityLogicMeta {intervalOptions: (dateFilter: DateFilter, timezone: string) => IntervalOption[]interval: (dateFilter: DateFilter, pinnedInterval: IntervalType | null, timezone: string) => IntervalTypescopeShare: (categoryCounts: CategoryCount[], selectedCategories: string[]) => ScopeShare- toolRows: (toolRowsPage: MCPToolQualityRowsQueryResponse | null) => MCPToolQualityRowItem[]- toolRowsTotalCount: (toolRowsPage: MCPToolQualityRowsQueryResponse | null) => number+ loadedToolQualityPageIndex: (toolRowsPage: ToolRowsPage | null) => number+ toolRows: (toolRowsPage: ToolRowsPage | null) => MCPToolQualityRowItem[]+ toolRowsTotalCount: (toolRowsPage: ToolRowsPage | null) => numberdailyChartData: (dailyStats: DailyToolStat[],dateFilter: DateFilter,@@ -362,10 +368,11 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType},],toolRowsPage: [- null as MCPToolQualityRowsQueryResponse | null,+ null as ToolRowsPage | null,{- loadToolRowsPage: async (_: void, breakpoint): Promise<MCPToolQualityRowsQueryResponse> => {+ loadToolRowsPage: async (_: void, breakpoint): Promise<ToolRowsPage> => {await breakpoint(300)+ const pageIndex = values.toolQualityPageIndexconst response = (await api.query({kind: NodeKind.MCPToolQualityRowsQuery,dateRange: { date_from: values.dateFilter.dateFrom, date_to: values.dateFilter.dateTo },@@ -374,10 +381,10 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypesortColumn: values.toolQualitySort.column,sortDirection: values.toolQualitySort.direction,limit: TOOL_QUALITY_PAGE_SIZE,- offset: values.toolQualityPageIndex * TOOL_QUALITY_PAGE_SIZE,+ offset: pageIndex * TOOL_QUALITY_PAGE_SIZE,})) as MCPToolQualityRowsQueryResponsebreakpoint()- return response+ return { ...response, pageIndex }},},],@@ -439,14 +446,17 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypereturn { inScope, total, pct: total > 0 ? (inScope / total) * 100 : null }},],+ loadedToolQualityPageIndex: [+ (s) => [s.toolRowsPage],+ (toolRowsPage: ToolRowsPage | null): number => toolRowsPage?.pageIndex ?? 0,+ ],toolRows: [(s) => [s.toolRowsPage],- (toolRowsPage: MCPToolQualityRowsQueryResponse | null): MCPToolQualityRowItem[] =>- toolRowsPage?.results ?? [],+ (toolRowsPage: ToolRowsPage | null): MCPToolQualityRowItem[] => toolRowsPage?.results ?? [],],toolRowsTotalCount: [(s) => [s.toolRowsPage],- (toolRowsPage: MCPToolQualityRowsQueryResponse | null): number => toolRowsPage?.totalCount ?? 0,+ (toolRowsPage: ToolRowsPage | null): number => toolRowsPage?.totalCount ?? 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 1cfcd0f1f45c..a9839af9f0ed 100644--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx@@ -20,6 +20,7 @@ import {PaginationItem,PaginationNext,PaginationPrevious,+ Spinner,Table,TableBody,TableCell,@@ -71,7 +72,6 @@ const SORTABLE_COLUMNS: ColumnSpec[] = [{ key: 'last_seen', label: 'Last seen' },]-// Tool column + every sortable column + the trailing "Full report" action, for the skeleton-row colSpanconst COLUMN_COUNT = SORTABLE_COLUMNS.length + 2function ErrorRateBadge({ pct }: { pct: number }): JSX.Element {@@ -124,7 +124,7 @@ function ToolRows(): JSX.Element {useValues(mcpAnalyticsToolQualityLogic)const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)- if (toolRowsPageLoading) {+ if (toolRowsPageLoading && toolRows.length === 0) {return (<TableBody><TableRow>@@ -185,12 +185,19 @@ function ToolRows(): JSX.Element {}export function ToolQualityTable(): JSX.Element {- const { toolQualitySort, toolQualityPageIndex, toolRows, toolRowsPageLoading, toolRowsTotalCount, searchTerm } =- useValues(mcpAnalyticsToolQualityLogic)+ const {+ toolQualitySort,+ toolQualityPageIndex,+ loadedToolQualityPageIndex,+ toolRows,+ toolRowsPageLoading,+ toolRowsTotalCount,+ searchTerm,+ } = useValues(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 firstRow = toolRowsTotalCount === 0 ? 0 : loadedToolQualityPageIndex * TOOL_QUALITY_PAGE_SIZE + 1const lastRow = Math.min(firstRow + toolRows.length - 1, toolRowsTotalCount)return (@@ -212,25 +219,32 @@ export function ToolQualityTable(): JSX.Element {/></InputGroup></CardHeader>- <Table fullWidth stickyHeader className="max-h-[44rem]">- <TableHeader>- <TableRow>- <TableHead expand>Tool</TableHead>- {SORTABLE_COLUMNS.map((column) => (- <SortableHead- key={column.key}- column={column}- sort={toolQualitySort}- loading={toolRowsPageLoading}- onSort={setToolQualitySort}- />- ))}- <TableHead />- </TableRow>- </TableHeader>- <ToolRows />- </Table>- {!toolRowsPageLoading && toolRowsTotalCount > 0 && (+ <div className="relative">+ <Table fullWidth stickyHeader className="max-h-[44rem]" aria-busy={toolRowsPageLoading}>+ <TableHeader>+ <TableRow>+ <TableHead expand>Tool</TableHead>+ {SORTABLE_COLUMNS.map((column) => (+ <SortableHead+ key={column.key}+ column={column}+ sort={toolQualitySort}+ loading={toolRowsPageLoading}+ onSort={setToolQualitySort}+ />+ ))}+ <TableHead />+ </TableRow>+ </TableHeader>+ <ToolRows />+ </Table>+ {toolRowsPageLoading ? (+ <div className="absolute inset-0 z-10 flex items-center justify-center bg-background/60">+ <Spinner className="size-5" />+ </div>+ ) : null}+ </div>+ {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')}@@ -240,7 +254,7 @@ export function ToolQualityTable(): JSX.Element {<PaginationContent><PaginationItem><PaginationPrevious- disabled={toolQualityPageIndex === 0}+ disabled={toolRowsPageLoading || toolQualityPageIndex === 0}onClick={() => setToolQualityPageIndex(toolQualityPageIndex - 1)}data-attr="mcp-tool-quality-page-previous"/>@@ -254,6 +268,7 @@ export function ToolQualityTable(): JSX.Element {<PaginationItem key={item}><PaginationButtonisActive={item === toolQualityPageIndex}+ disabled={toolRowsPageLoading}aria-label={`Go to page ${item + 1}`}onClick={() => setToolQualityPageIndex(item)}data-attr="mcp-tool-quality-page"@@ -265,7 +280,7 @@ export function ToolQualityTable(): JSX.Element {)}<PaginationItem><PaginationNext- disabled={toolQualityPageIndex === pageCount - 1}+ disabled={toolRowsPageLoading || toolQualityPageIndex === pageCount - 1}onClick={() => setToolQualityPageIndex(toolQualityPageIndex + 1)}data-attr="mcp-tool-quality-page-next"/>