: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): per-tool drill-down on the tool quality tab (#63093)
Sam Pennington728e80e2caf5
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9a8e69465951..f0348b518a79 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3180,6 +3180,9 @@ importers:'@posthog/quill-charts':specifier: workspace:*version: link:../../packages/quill/packages/charts+ '@posthog/quill-components':+ specifier: workspace:*+ version: link:../../packages/quill/packages/components'@posthog/quill-primitives':specifier: workspace:*version: link:../../packages/quill/packages/primitives@@ -3201,6 +3204,10 @@ importers:react:specifier: 18.3.1version: 18.3.1+ devDependencies:+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected]([email protected]))products/mcp_store:dependencies:diff --git a/products/mcp_analytics/backend/templates/tool_quality.sql b/products/mcp_analytics/backend/templates/tool_quality.sqlindex 45f665f17e3f..e5dd0ceccca8 100644--- a/products/mcp_analytics/backend/templates/tool_quality.sql+++ b/products/mcp_analytics/backend/templates/tool_quality.sql@@ -18,6 +18,7 @@ SELECTround(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,round(quantile(0.5)(toFloat(properties.$mcp_duration_ms))) AS p50_duration_ms,round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_duration_ms,+ round(quantile(0.99)(toFloat(properties.$mcp_duration_ms))) AS p99_duration_ms,uniq(distinct_id) AS users,countDistinctIf(properties.$session_id, properties.$session_id != '') AS sessions,min(timestamp) AS first_seen,diff --git a/products/mcp_analytics/backend/tests/test_tool_quality_sql.py b/products/mcp_analytics/backend/tests/test_tool_quality_sql.pyindex 3405e0e05180..1b864139cb22 100644--- a/products/mcp_analytics/backend/tests/test_tool_quality_sql.py+++ b/products/mcp_analytics/backend/tests/test_tool_quality_sql.py@@ -18,6 +18,7 @@ def test_tool_quality_sql_contains_required_columns() -> None:"error_rate_pct","p50_duration_ms","p95_duration_ms",+ "p99_duration_ms","users","sessions","first_seen",diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsxindex 7a885a699b45..000bf1abaf9b 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx@@ -1,80 +1,48 @@import { useActions, useValues } from 'kea'+import { useMemo } from 'react'-import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'-import { Link } from 'lib/lemon-ui/Link'+import { IconX } from '@posthog/icons'+import { type ChartTheme } from '@posthog/quill-charts'+import { Button } from '@posthog/quill-primitives'++import { buildTheme } from 'lib/charts/utils/theme'+import { TagsCombobox } from 'lib/components/Scenes/TagsCombobox'+import { LinkPrimitive } from 'lib/lemon-ui/Link/Link'import { Tooltip } from 'lib/lemon-ui/Tooltip'-import { humanFriendlyDuration } from 'lib/utils'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { DataTable } from '~/queries/nodes/DataTable/DataTable'-import { Query } from '~/queries/Query/Query'-import { isHogQLQuery } from '~/queries/utils'+import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { mcpAnalyticsToolQualityLogic } from './mcpAnalyticsToolQualityLogic'+import { ToolQualityCharts } from './tool-quality/ToolQualityCharts'+import { ToolQualityDateFilter } from './tool-quality/ToolQualityDateFilter'+import { ToolQualityTable } from './tool-quality/ToolQualityTable'-const COLLECTION_ID = 'mcp-analytics-tool-quality'--function renderSortableTitle(- column: string,- title: string,- currentSort: { column: string; direction: 'ASC' | 'DESC' },- setSort: (column: string, direction: 'ASC' | 'DESC') => void-): JSX.Element {- const isSorted = currentSort.column === column- const handleClick = (): void => {- const next = isSorted && currentSort.direction === 'DESC' ? 'ASC' : 'DESC'- setSort(column, next)- }- return (- <span- onClick={handleClick}- style={{ cursor: 'pointer', userSelect: 'none' }}- className="flex items-center gap-1"- >- {title}- {isSorted ? (currentSort.direction === 'DESC' ? ' ▼' : ' ▲') : ''}- </span>- )-}--function formatMs(value: unknown): string {- if (value === null || value === undefined || value === '' || Number.isNaN(Number(value))) {- return '—'- }- return humanFriendlyDuration(Number(value) / 1000, { secondsFixed: 2 })-}--function errorRateClass(rate: number): string {- if (rate <= 0) {- return 'text-success'- }- if (rate < 5) {- return 'text-warning'- }- return 'text-danger'-}--function CategoryScopeBar(): JSX.Element {- const { availableCategories, availableCategoriesLoading, selectedCategories, scopeShare } =- useValues(mcpAnalyticsToolQualityLogic)- const { setSelectedCategories } = useActions(mcpAnalyticsToolQualityLogic)+function FilterBar(): JSX.Element {+ const { availableCategories, selectedCategories, scopeShare, dateFilter } = useValues(mcpAnalyticsToolQualityLogic)+ const { setSelectedCategories, setDateFilter } = useActions(mcpAnalyticsToolQualityLogic)const hasScope = selectedCategories.length > 0const sharePct = scopeShare.pct === null ? null : Math.round(scopeShare.pct * 10) / 10return (<div className="flex flex-wrap items-center gap-3">- <div className="min-w-[280px] flex-1 max-w-[480px]">- <LemonInputSelect- mode="multiple"+ <div className="min-w-[220px] max-w-[420px] flex-1">+ <TagsCombobox+ options={availableCategories}value={selectedCategories}onChange={setSelectedCategories}- options={availableCategories.map((category) => ({ key: category, label: category }))}- loading={availableCategoriesLoading}placeholder="All categories"- data-attr="mcp-tool-quality-category-scope"+ allowCustomValues={false}+ dataAttr="mcp-tool-quality-category-scope"/></div>+ <ToolQualityDateFilter+ dateFrom={dateFilter.dateFrom}+ dateTo={dateFilter.dateTo}+ onChange={(dateFrom, dateTo) => setDateFilter(dateFrom, dateTo)}+ />{hasScope && sharePct !== null ? (<Tooltiptitle={`${scopeShare.inScope.toLocaleString()} of ${scopeShare.total.toLocaleString()} MCP tool calls in the last 7 days were in the selected categories`}@@ -88,143 +56,60 @@ function CategoryScopeBar(): JSX.Element {)}+function ChartsScopeHeader(): JSX.Element {+ const { selectedTool } = useValues(mcpAnalyticsToolQualityLogic)+ const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)++ if (!selectedTool) {+ return (+ <div className="text-sm text-secondary">+ Trends across all tools in scope — select a row above to drill down.+ </div>+ )+ }++ return (+ <div className="flex items-center gap-2">+ <span className="shrink-0 text-sm text-secondary">Trends for</span>+ <span className="max-w-[28rem] truncate font-mono text-sm font-semibold" title={selectedTool}>+ {selectedTool}+ </span>+ <Button+ variant="outline"+ size="sm"+ render={<LinkPrimitive to={urls.mcpAnalyticsTool(selectedTool)} />}+ data-attr="mcp-tool-quality-full-report"+ >+ Full tool report+ </Button>+ <Button+ variant="link-muted"+ size="icon-sm"+ onClick={() => setSelectedTool(null)}+ title="Show all tools"+ data-attr="mcp-tool-quality-clear-tool"+ >+ <IconX />+ </Button>+ </div>+ )+}+export function MCPAnalyticsToolQuality(): JSX.Element {- const { toolQualityQuery, toolQualitySort, topToolsQuery, errorTrendQuery, durationTrendQuery } =- useValues(mcpAnalyticsToolQualityLogic)- const { setToolQualitySort, setDateFilter } = useActions(mcpAnalyticsToolQualityLogic)+ const { dailyChartData, dailyStatsLoading } = useValues(mcpAnalyticsToolQualityLogic)+ const { isDarkModeOn } = useValues(themeLogic)+ const { timezone } = useValues(teamLogic)++ // buildTheme() reads CSS vars from the DOM; isDarkModeOn is the dep that forces a recompute when+ // the theme flips (it isn't passed as an argument).+ const theme = useMemo<ChartTheme>(() => buildTheme(), [isDarkModeOn])return (- <div className="flex flex-col gap-4">- <CategoryScopeBar />- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">- <div className="bg-bg-light border rounded p-2 min-h-[260px] flex flex-col">- <div className="text-muted text-xs font-medium uppercase mb-2 px-2 pt-1">Top tools by calls</div>- <div className="flex-1">- <Query query={topToolsQuery} readOnly />- </div>- </div>- <div className="bg-bg-light border rounded p-2 min-h-[260px] flex flex-col">- <div className="text-muted text-xs font-medium uppercase mb-2 px-2 pt-1">Errors over time</div>- <div className="flex-1">- <Query query={errorTrendQuery} readOnly />- </div>- </div>- <div className="bg-bg-light border rounded p-2 min-h-[260px] flex flex-col">- <div className="text-muted text-xs font-medium uppercase mb-2 px-2 pt-1">Duration over time</div>- <div className="flex-1">- <Query query={durationTrendQuery} readOnly />- </div>- </div>- </div>- <DataTable- query={toolQualityQuery}- setQuery={(query) => {- if (!isHogQLQuery(query.source)) {- return- }- const filters = query.source.filters ?? {}- const dateRange = filters.dateRange ?? {}- setDateFilter(dateRange.date_from ?? null, dateRange.date_to ?? null)- }}- context={{- columns: {- tool: {- title: 'Tool',- render: function RenderTool({ value }) {- if (!value || value === 'null') {- return <span className="text-muted">Unknown tool</span>- }- const toolName = String(value)- return (- <Link- to={urls.mcpAnalyticsTool(toolName)}- className="font-mono text-sm"- data-attr="mcp-tool-quality-tool-link"- >- {toolName}- </Link>- )- },- },- total_calls: {- renderTitle: () => (- <Tooltip title="Total number of times this tool was called">- {renderSortableTitle(- 'total_calls',- 'Total calls',- toolQualitySort,- setToolQualitySort- )}- </Tooltip>- ),- },- error_rate_pct: {- renderTitle: () => (- <Tooltip title="Percentage of calls that returned $mcp_is_error = true">- {renderSortableTitle(- 'error_rate_pct',- 'Error rate',- toolQualitySort,- setToolQualitySort- )}- </Tooltip>- ),- render: function RenderErrorRate({ value }) {- const numeric = Number(value)- if (Number.isNaN(numeric)) {- return <span className="text-muted">—</span>- }- return <span className={errorRateClass(numeric)}>{numeric}%</span>- },- },- p95_duration_ms: {- renderTitle: () => (- <Tooltip title="95th-percentile $mcp_duration_ms">- {renderSortableTitle(- 'p95_duration_ms',- 'p95 duration',- toolQualitySort,- setToolQualitySort- )}- </Tooltip>- ),- render: ({ value }) => <span>{formatMs(value)}</span>,- },- p50_duration_ms: {- renderTitle: () => (- <Tooltip title="Median $mcp_duration_ms">- {renderSortableTitle(- 'p50_duration_ms',- 'p50 duration',- toolQualitySort,- setToolQualitySort- )}- </Tooltip>- ),- render: ({ value }) => <span>{formatMs(value)}</span>,- },- users: {- renderTitle: () => (- <Tooltip title="Unique users who invoked this tool">- {renderSortableTitle('users', 'Users', toolQualitySort, setToolQualitySort)}- </Tooltip>- ),- },- sessions: {- renderTitle: () => (- <Tooltip title="Unique sessions where this tool was called">- {renderSortableTitle('sessions', 'Sessions', toolQualitySort, setToolQualitySort)}- </Tooltip>- ),- },- last_seen: {- renderTitle: () =>- renderSortableTitle('last_seen', 'Last seen', toolQualitySort, setToolQualitySort),- },- },- }}- uniqueKey={COLLECTION_ID}- />+ <div className="flex flex-col gap-4" data-quill>+ <FilterBar />+ <ChartsScopeHeader />+ <ToolQualityCharts data={dailyChartData} loading={dailyStatsLoading} theme={theme} timezone={timezone} />+ <ToolQualityTable /></div>)}diff --git a/products/mcp_analytics/frontend/dashboard/formatters.ts b/products/mcp_analytics/frontend/dashboard/formatters.tsindex 8497ac9b7242..6261ff945c7c 100644--- a/products/mcp_analytics/frontend/dashboard/formatters.ts+++ b/products/mcp_analytics/frontend/dashboard/formatters.ts@@ -19,6 +19,23 @@ export function formatMs(n: number): string {return humanFriendlyDuration(n / 1000, { secondsPrecision: 1 })}+// Seconds-first duration for chart axes and tooltips: 500 → "0.5s", 1500 → "1.5s",+// 2000 → "2s". One unit for the whole scale so axis ticks stay comparable; only+// sub-100ms values keep ms, where seconds would round to a flat 0.1s.+export function formatMsAsSeconds(n: number): string {+ if (!isFinite(n)) {+ return EMPTY+ }+ if (n === 0) {+ return '0'+ }+ if (n < 100) {+ return `${Math.round(n)}ms`+ }+ const rounded = Math.round(n / 100) / 10+ return `${rounded}s`+}+export function formatDuration(seconds: number): string {if (!seconds || !isFinite(seconds)) {return EMPTYdiff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.tsnew file mode 100644index 000000000000..14f312bb1722--- /dev/null+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts@@ -0,0 +1,164 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { initKeaTests } from '~/test/init'++import { formatMsAsSeconds } from './dashboard/formatters'+import { type DailyToolStat, buildDailyChartData, mcpAnalyticsToolQualityLogic } from './mcpAnalyticsToolQualityLogic'++jest.mock('lib/api')+jest.mock('~/queries/query', () => ({+ hogqlQuery: jest.fn().mockResolvedValue({ results: [] }),+}))++const mockApi = api as jest.Mocked<typeof api>++function dailyStat(overrides: Partial<DailyToolStat> & { day: string }): DailyToolStat {+ return { calls: 0, errors: 0, p50: 0, p95: 0, p99: 0, ...overrides }+}++describe('mcpAnalyticsToolQualityLogic', () => {+ describe('buildDailyChartData', () => {+ it('fills missing days so the x-axis stays linear', () => {+ const data = buildDailyChartData([+ dailyStat({ day: '2026-06-05', calls: 100, errors: 10, p50: 200, p95: 900, p99: 2100 }),+ dailyStat({ day: '2026-06-07', calls: 50, errors: 0, p50: 150, p95: 800, p99: 1500 }),+ ])+ expect(data.labels).toEqual(['2026-06-05', '2026-06-06', '2026-06-07'])+ expect(data.calls).toEqual([100, 0, 50])+ expect(data.errors).toEqual([10, 0, 0])+ // Gap days get NaN (skipped by the chart), not a dip to zero.+ expect(data.successRate[0]).toBeCloseTo(90)+ expect(data.successRate[1]).toBeNaN()+ expect(data.p99).toEqual([2100, NaN, 1500])+ })++ it('returns empty series for no rows', () => {+ expect(buildDailyChartData([]).labels).toEqual([])+ })++ it('spans the full range when given one, zero-filling days outside the data', () => {+ const data = buildDailyChartData(+ [dailyStat({ day: '2026-06-07', calls: 50, errors: 0, p50: 150, p95: 800, p99: 1500 })],+ { start: '2026-06-05', end: '2026-06-08' }+ )+ expect(data.labels).toEqual(['2026-06-05', '2026-06-06', '2026-06-07', '2026-06-08'])+ expect(data.calls).toEqual([0, 0, 50, 0])+ expect(data.successRate[0]).toBeNaN()+ expect(data.successRate[2]).toBeCloseTo(100)+ })++ it('zero-fills the whole range when there is no data at all', () => {+ const data = buildDailyChartData([], { start: '2026-06-05', end: '2026-06-07' })+ expect(data.labels).toEqual(['2026-06-05', '2026-06-06', '2026-06-07'])+ expect(data.calls).toEqual([0, 0, 0])+ })+ })++ describe('formatMsAsSeconds', () => {+ it.each([+ [0, '0'],+ [50, '50ms'],+ [500, '0.5s'],+ [1000, '1s'],+ [99, '99ms'],+ [100, '0.1s'],+ [1500, '1.5s'],+ [2000, '2s'],+ [NaN, '—'],+ [Infinity, '—'],+ ])('formats %s ms as %s', (input, expected) => {+ expect(formatMsAsSeconds(input)).toBe(expected)+ })+ })++ describe('date range and tool filters', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] })+ })++ function queryCallsSince(callIndex: number): { query: string; filters: Record<string, any> }[] {+ return mockApi.query.mock.calls.slice(callIndex).map((call) => call[0] as any)+ }++ it('reloads the tool rows and daily stats with the new date range when the date filter changes', async () => {+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => {+ logic.actions.setDateFilter('-30d', null)+ }).toFinishAllListeners()++ const newCalls = queryCallsSince(callsBefore)+ expect(newCalls.length).toBe(2) // tool rows + daily stats+ expect(newCalls.map((call) => call.filters.dateRange)).toEqual([+ { date_from: '-30d', date_to: null },+ { date_from: '-30d', date_to: null },+ ])+ })++ it('reloads daily stats with the tool as a property filter when a tool is selected', async () => {+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => {+ logic.actions.setSelectedTool("evil'); DROP TABLE events; --")+ }).toFinishAllListeners()++ const newCalls = queryCallsSince(callsBefore)+ expect(newCalls.length).toBe(1) // daily stats only+ expect(newCalls[0].filters.properties).toEqual([+ expect.objectContaining({+ key: '$mcp_tool_name',+ value: ["evil'); DROP TABLE events; --"],+ operator: 'exact',+ type: 'event',+ }),+ ])+ // The tool value must never be interpolated into the HogQL string.+ expect(newCalls[0].query).not.toContain('DROP TABLE')+ })++ // Tool-quality row tuple as returned by the query (tool, calls, errors, then unused cols)+ const toolRowResult = (tool: string): unknown[] => [tool, 1, 0, 0, 0, 0, 0, 0, 0, '', '']++ it('clears the selected tool when a reload no longer includes it', async () => {+ mockApi.query.mockResolvedValue({ results: [toolRowResult('tool_a')] })+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSelectedTool('tool_a')+ 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()++ 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')] })+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSelectedTool('tool_a')+ await expectLogic(logic, () => {+ logic.actions.setSelectedCategories(['some-category'])+ }).toFinishAllListeners()++ expect(logic.values.selectedTool).toBe('tool_a')+ })+ })+})diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex 938b3297d51f..3992a290f734 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -1,19 +1,17 @@-import { actions, afterMount, kea, path, reducers, selectors } from 'kea'+import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { actionToUrl, router, urlToAction } from 'kea-router'-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import api from 'lib/api'+import { dayjs } from 'lib/dayjs'+import { dateStringToDayJs } from 'lib/utils'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import { hogqlQuery } from '~/queries/query'-import { DataTableNode, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'+import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'import { hogql } from '~/queries/utils'-import {- type AnyPropertyFilter,- BaseMathType,- ChartDisplayType,- PropertyFilterType,- PropertyMathType,- PropertyOperator,-} from '~/types'+import { type AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import toolQualityQueryTemplate from '../backend/templates/tool_quality.sql?raw'import type { mcpAnalyticsToolQualityLogicType } from './mcpAnalyticsToolQualityLogicType'@@ -66,9 +64,104 @@ export interface DateFilter {dateTo: string | null}+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 interface DailyToolStat {+ day: string+ calls: number+ errors: number+ p50: number+ p95: number+ p99: number+}++export interface DailyChartData {+ labels: string[]+ calls: number[]+ errors: number[]+ successRate: number[]+ p50: number[]+ p95: number[]+ p99: number[]+}+const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-7d', dateTo: null }const DEFAULT_SORT: SortState = { column: 'total_calls', direction: 'DESC' }+const EMPTY_CHART_DATA: DailyChartData = {+ labels: [],+ calls: [],+ errors: [],+ successRate: [],+ p50: [],+ p95: [],+ p99: [],+}++// Pivot per-day rows into chart series over a gap-free day axis: ClickHouse only+// returns days that had events, so missing days are filled in to keep the x-axis+// linear. Counts fill with 0 (genuinely no activity); rate and latency fill with+// NaN so the chart skips the point instead of drawing a misleading dip to zero.+// `range` spans the axis over the full selected window (so empty leading/trailing+// days still show); without it, the axis spans only the days that have data.+export function buildDailyChartData(+ dailyStats: DailyToolStat[],+ range?: { start: string; end: string }+): DailyChartData {+ let startDay: string+ let endDay: string+ if (range) {+ startDay = range.start+ endDay = range.end+ } else if (dailyStats.length > 0) {+ startDay = dailyStats[0].day+ endDay = dailyStats[dailyStats.length - 1].day+ } else {+ return EMPTY_CHART_DATA+ }+ const byDay = new Map(dailyStats.map((r) => [r.day, r]))+ const end = dayjs(endDay)+ const labels: string[] = []+ for (let day = dayjs(startDay); !day.isAfter(end); day = day.add(1, 'day')) {+ labels.push(day.format('YYYY-MM-DD'))+ }+ const rows = labels.map((day) => byDay.get(day))+ return {+ labels,+ calls: rows.map((r) => r?.calls ?? 0),+ errors: rows.map((r) => r?.errors ?? 0),+ successRate: rows.map((r) => (r && r.calls ? ((r.calls - r.errors) / r.calls) * 100 : NaN)),+ p50: rows.map((r) => (r ? r.p50 : NaN)),+ p95: rows.map((r) => (r ? r.p95 : NaN)),+ p99: rows.map((r) => (r ? r.p99 : NaN)),+ }+}++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+ })+}+export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType>([path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsToolQualityLogic']),@@ -76,6 +169,9 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypesetToolQualitySort: (column: string, direction: SortDirection) => ({ column, direction }),setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setSelectedCategories: (categories: string[]) => ({ categories }),+ setSelectedTool: (tool: string | null) => ({ tool }),+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ reloadAll: true,}),reducers({@@ -97,9 +193,21 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypesetSelectedCategories: (_, { categories }): string[] => categories,},],+ selectedTool: [+ null as string | null,+ {+ setSelectedTool: (_, { tool }): string | null => tool,+ },+ ],+ searchTerm: [+ '',+ {+ setSearchTerm: (_, { searchTerm }): string => searchTerm,+ },+ ],}),- loaders({+ loaders(({ values }) => ({availableCategories: [[] as string[],{@@ -121,7 +229,100 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType},},],- }),+ toolRows: [+ [] as ToolQualityRow[],+ {+ loadToolRows: async (_: void, breakpoint): Promise<ToolQualityRow[]> => {+ await breakpoint(100)+ // Fixed server-side order; column sorting happens client-side on the loaded set.+ const query = toolQualityQueryTemplate+ .replace('__ORDER_BY__', 'total_calls')+ .replace('__ORDER_DIRECTION__', 'DESC')+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query,+ filters: {+ dateRange: {+ date_from: values.dateFilter.dateFrom,+ date_to: values.dateFilter.dateTo,+ },+ ...(values.categoryProperties.length > 0 ? { properties: values.categoryProperties } : {}),+ },+ })) as HogQLQueryResponse+ breakpoint()+ return ((response.results as unknown[][]) ?? []).map((r) => ({+ tool: String(r[0] ?? ''),+ total_calls: Number(r[1] ?? 0),+ errors: Number(r[2] ?? 0),+ error_rate_pct: Number(r[3] ?? 0),+ p50_duration_ms: Number(r[4] ?? 0),+ p95_duration_ms: Number(r[5] ?? 0),+ p99_duration_ms: Number(r[6] ?? 0),+ users: Number(r[7] ?? 0),+ sessions: Number(r[8] ?? 0),+ first_seen: String(r[9] ?? ''),+ last_seen: String(r[10] ?? ''),+ }))+ },+ },+ ],+ dailyStats: [+ [] as DailyToolStat[],+ {+ loadDailyStats: async (_: void, breakpoint): Promise<DailyToolStat[]> => {+ await breakpoint(100)+ // The selected tool rides along as a property filter resolved by the+ // {filters} placeholder, so the value never touches the query string.+ const toolProperty: AnyPropertyFilter[] = values.selectedTool+ ? [+ {+ key: '$mcp_tool_name',+ value: [values.selectedTool],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ]+ : []+ const properties = [...values.categoryProperties, ...toolProperty]+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query: `+SELECT+ toDate(timestamp) AS day,+ count() AS calls,+ countIf(toBool(properties.$mcp_is_error)) AS errors,+ round(quantile(0.5)(toFloat(properties.$mcp_duration_ms))) AS p50,+ round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95,+ round(quantile(0.99)(toFloat(properties.$mcp_duration_ms))) AS p99+FROM events+WHERE event = 'mcp_tool_call'+ AND properties.$mcp_tool_name IS NOT NULL+ AND properties.$mcp_tool_name != ''+ AND {filters}+GROUP BY day+ORDER BY day+`,+ filters: {+ dateRange: {+ date_from: values.dateFilter.dateFrom,+ date_to: values.dateFilter.dateTo,+ },+ ...(properties.length > 0 ? { properties } : {}),+ },+ })) as HogQLQueryResponse+ breakpoint()+ return ((response.results as unknown[][]) ?? []).map((r) => ({+ day: String(r[0] ?? ''),+ calls: Number(r[1] ?? 0),+ errors: Number(r[2] ?? 0),+ p50: Number(r[3] ?? 0),+ p95: Number(r[4] ?? 0),+ p99: Number(r[5] ?? 0),+ }))+ },+ },+ ],+ })),selectors({// Event property filter applied to every query so the whole tab scopes to@@ -151,150 +352,77 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypereturn { inScope, total, pct: total > 0 ? (inScope / total) * 100 : null }},],- toolQualityQuery: [- (s) => [s.dateFilter, s.toolQualitySort, s.categoryProperties],- (dateFilter: DateFilter, sort: SortState, categoryProperties: AnyPropertyFilter[]): DataTableNode => {- const query = toolQualityQueryTemplate- .replace('__ORDER_BY__', sort.column)- .replace('__ORDER_DIRECTION__', sort.direction)-- return {- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query,- filters: {- dateRange: {- date_from: dateFilter.dateFrom,- date_to: dateFilter.dateTo,- },- ...(categoryProperties.length > 0 ? { properties: categoryProperties } : {}),- },- },- columns: [- 'tool',- 'total_calls',- 'error_rate_pct',- 'p95_duration_ms',- 'p50_duration_ms',- 'users',- 'sessions',- 'last_seen',- ],- showDateRange: true,- showReload: true,- showSearch: true,- showPropertyFilter: [- TaxonomicFilterGroupType.EventProperties,- TaxonomicFilterGroupType.PersonProperties,- TaxonomicFilterGroupType.HogQLExpression,- ],- showExport: true,- showColumnConfigurator: true,- allowSorting: true,- }+ 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)},],- topToolsQuery: [- (s) => [s.dateFilter, s.categoryProperties],- (dateFilter: DateFilter, categoryProperties: AnyPropertyFilter[]): InsightVizNode => ({- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [- {- kind: NodeKind.EventsNode,- event: 'mcp_tool_call',- name: 'mcp_tool_call',- math: BaseMathType.TotalCount,- },- ],- properties: categoryProperties,- breakdownFilter: {- breakdown_type: 'event',- breakdown: '$mcp_tool_name',- breakdown_limit: 10,- },- trendsFilter: {- display: ChartDisplayType.ActionsPie,- showLegend: false,- showValuesOnSeries: true,- showPercentStackView: true,- },- dateRange: {- date_from: dateFilter.dateFrom,- date_to: dateFilter.dateTo,- },- },- vizSpecificOptions: { ActionsPie: { hideAggregation: true } },- }),- ],- errorTrendQuery: [- (s) => [s.dateFilter, s.categoryProperties],- (dateFilter: DateFilter, categoryProperties: AnyPropertyFilter[]): InsightVizNode => ({- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [- {- kind: NodeKind.EventsNode,- event: 'mcp_tool_call',- name: 'mcp_tool_call',- math: BaseMathType.TotalCount,- },- ],- properties: categoryProperties,- breakdownFilter: {- breakdown_type: 'event',- breakdown: '$mcp_is_error',- },- trendsFilter: {- display: ChartDisplayType.ActionsLineGraph,- },- dateRange: {- date_from: dateFilter.dateFrom,- date_to: dateFilter.dateTo,- },- },- }),- ],- durationTrendQuery: [- (s) => [s.dateFilter, s.categoryProperties],- (dateFilter: DateFilter, categoryProperties: AnyPropertyFilter[]): InsightVizNode => ({- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [- {- kind: NodeKind.EventsNode,- event: 'mcp_tool_call',- name: 'p95 duration (ms)',- math: PropertyMathType.P95,- math_property: '$mcp_duration_ms',- },- {- kind: NodeKind.EventsNode,- event: 'mcp_tool_call',- name: 'p50 duration (ms)',- math: PropertyMathType.Median,- math_property: '$mcp_duration_ms',- },- ],- properties: categoryProperties,- trendsFilter: {- display: ChartDisplayType.ActionsLineGraph,- },- dateRange: {- date_from: dateFilter.dateFrom,- date_to: dateFilter.dateTo,- },- },- }),+ dailyChartData: [+ (s) => [s.dailyStats, s.dateFilter, teamLogic.selectors.timezone],+ (dailyStats: DailyToolStat[], dateFilter: DateFilter, timezone: string): DailyChartData => {+ const start = dateStringToDayJs(dateFilter.dateFrom, timezone)+ const end =+ (dateFilter.dateTo ? dateStringToDayJs(dateFilter.dateTo, timezone) : dayjs().tz(timezone)) ??+ dayjs()+ const range = start ? { start: start.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') } : undefined+ return buildDailyChartData(dailyStats, range)+ },],}),+ listeners(({ actions, values }) => ({+ // Both scope filters refetch the table and the charts+ setDateFilter: () => {+ actions.reloadAll()+ },+ setSelectedCategories: () => {+ actions.reloadAll()+ },+ 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)) {+ actions.setSelectedTool(null)+ }+ },+ })),++ actionToUrl(({ values }) => ({+ setSelectedTool: () => {+ const { currentLocation } = router.values+ const searchParams = { ...currentLocation.searchParams }+ if (values.selectedTool) {+ searchParams.tool = values.selectedTool+ } else {+ delete searchParams.tool+ }+ return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]+ },+ })),++ urlToAction(({ actions, values }) => ({+ [urls.mcpAnalyticsToolQuality()]: (_, searchParams) => {+ const tool = typeof searchParams.tool === 'string' && searchParams.tool ? searchParams.tool : null+ if (tool !== values.selectedTool) {+ actions.setSelectedTool(tool)+ }+ },+ })),+afterMount(({ actions }) => {actions.loadAvailableCategories()actions.loadCategoryCounts()+ actions.loadToolRows()+ actions.loadDailyStats()}),])diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsxnew file mode 100644index 000000000000..09332c8f36ff--- /dev/null+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx@@ -0,0 +1,134 @@+import { useMemo } from 'react'++import { LemonSkeleton } from '@posthog/lemon-ui'+import {+ ChartLegend,+ type ChartTheme,+ type Series,+ TimeSeriesLineChart,+ type TimeSeriesLineChartConfig,+ legendItemsFromSeries,+} from '@posthog/quill-charts'++import { formatPercentage } from 'lib/utils'++import { Card, CardState } from '../dashboard/Card'+import { formatMsAsSeconds } from '../dashboard/formatters'+import { type DailyChartData } from '../mcpAnalyticsToolQualityLogic'++function buildConfig(timezone: string, yAxis?: TimeSeriesLineChartConfig['yAxis']): TimeSeriesLineChartConfig {+ return {+ yAxis: { showGrid: false, ...yAxis },+ showAxisLines: true,+ xAxis: { interval: 'day', timezone },+ showCrosshair: true,+ tooltip: { placement: 'cursor' },+ }+}++function ChartCard({+ title,+ loading,+ isEmpty,+ children,+}: {+ title: string+ loading: boolean+ isEmpty: boolean+ children: React.ReactNode+}): JSX.Element {+ return (+ <Card title={title}>+ <CardState+ loading={loading}+ isEmpty={isEmpty}+ skeleton={<LemonSkeleton className="min-h-[220px] flex-1" />}+ empty={+ <div className="flex min-h-[220px] flex-1 items-center justify-center text-center text-[12px] text-secondary">+ No tool calls for this selection.+ </div>+ }+ >+ {/* Dim while refreshing so date/tool changes give visible feedback. */}+ <div className={`flex min-h-[220px] flex-1 flex-col transition-opacity ${loading ? 'opacity-50' : ''}`}>+ {children}+ </div>+ </CardState>+ </Card>+ )+}++export function ToolQualityCharts({+ data,+ loading,+ theme,+ timezone,+}: {+ data: DailyChartData+ loading: boolean+ theme: ChartTheme+ timezone: string+}): JSX.Element {+ const isEmpty = data.labels.length === 0++ const callsSeries = useMemo<Series[]>(+ () => [+ { key: 'calls', label: 'Calls', color: theme.colors[0], data: data.calls },+ { key: 'errors', label: 'Errors', color: theme.colors[4], data: data.errors },+ ],+ [data, theme]+ )+ const successSeries = useMemo<Series[]>(+ () => [{ key: 'successRate', label: 'Success rate', color: theme.colors[2], data: data.successRate }],+ [data, theme]+ )+ const latencySeries = useMemo<Series[]>(+ () => [+ { key: 'p50', label: 'p50', color: theme.colors[1], data: data.p50 },+ { key: 'p95', label: 'p95', color: theme.colors[0], data: data.p95 },+ { key: 'p99', label: 'p99', color: theme.colors[4], data: data.p99 },+ ],+ [data, theme]+ )++ const countsConfig = useMemo(() => buildConfig(timezone), [timezone])+ const percentConfig = useMemo(+ () => buildConfig(timezone, { tickFormatter: (value: number) => formatPercentage(value, { compact: true }) }),+ [timezone]+ )+ const latencyConfig = useMemo(() => buildConfig(timezone, { tickFormatter: formatMsAsSeconds }), [timezone])++ return (+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">+ <ChartCard title="Calls and errors" loading={loading} isEmpty={isEmpty}>+ <TimeSeriesLineChart+ series={callsSeries}+ labels={data.labels}+ config={countsConfig}+ theme={theme}+ dataAttr="mcp-tool-quality-calls-chart"+ />+ </ChartCard>+ <ChartCard title="Success rate" loading={loading} isEmpty={isEmpty}>+ <TimeSeriesLineChart+ series={successSeries}+ labels={data.labels}+ config={percentConfig}+ theme={theme}+ dataAttr="mcp-tool-quality-success-rate-chart"+ />+ </ChartCard>+ <ChartCard title="Latency (p50 / p95 / p99)" loading={loading} isEmpty={isEmpty}>+ <ChartLegend items={legendItemsFromSeries(latencySeries, theme)} position="top" align="end">+ <TimeSeriesLineChart+ series={latencySeries}+ labels={data.labels}+ config={latencyConfig}+ theme={theme}+ dataAttr="mcp-tool-quality-latency-chart"+ />+ </ChartLegend>+ </ChartCard>+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityDateFilter.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityDateFilter.tsxnew file mode 100644index 000000000000..e866993ca3c1--- /dev/null+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityDateFilter.tsx@@ -0,0 +1,94 @@+import { useState } from 'react'++import { IconCalendar } from '@posthog/icons'+import {+ CUSTOM_RANGE,+ DateTimePicker,+ type DateTimeRangeName,+ type DateTimeValue,+ quickRanges,+} from '@posthog/quill-components'+import { Button, Popover, PopoverContent, PopoverTrigger } from '@posthog/quill-primitives'++import { dayjs } from 'lib/dayjs'++// Quick ranges that translate to PostHog relative date strings, so queries stay+// rolling ("-7d" re-resolves on every load). Minute-level ranges are omitted on+// purpose: in PostHog date strings "m" means months, so those apply as absolute+// timestamps instead.+const RANGE_TO_RELATIVE: Partial<Record<DateTimeRangeName, string>> = {+ 'Last 1 hour': '-1h',+ 'Last 3 hours': '-3h',+ 'Last 6 hours': '-6h',+ 'Last 12 hours': '-12h',+ 'Last 24 hours': '-24h',+ 'Last 2 days': '-2d',+ 'Last 7 days': '-7d',+ 'Last 30 days': '-30d',+ 'Last 90 days': '-90d',+ 'Last 6 months': '-6m',+ 'Last 1 year': '-1y',+ 'Last 2 years': '-2y',+}++function toPickerValue(dateFrom: string | null, dateTo: string | null): DateTimeValue {+ const now = new Date()+ if (dateFrom && !dateTo) {+ const name = (Object.keys(RANGE_TO_RELATIVE) as DateTimeRangeName[]).find(+ (key) => RANGE_TO_RELATIVE[key] === dateFrom+ )+ const range = name ? quickRanges.find((r) => r.name === name) : undefined+ if (range) {+ return { start: range.rangeSetter(now), end: now, range }+ }+ }+ return {+ start: dateFrom ? dayjs(dateFrom).toDate() : dayjs(now).subtract(7, 'day').toDate(),+ end: dateTo ? dayjs(dateTo).toDate() : now,+ range: CUSTOM_RANGE,+ }+}++function formatTriggerLabel(value: DateTimeValue): string {+ if (value.range.id !== CUSTOM_RANGE.id) {+ return value.range.name+ }+ return `${dayjs(value.start).format('MMM D, HH:mm')} – ${dayjs(value.end).format('MMM D, HH:mm')}`+}++interface ToolQualityDateFilterProps {+ dateFrom: string | null+ dateTo: string | null+ onChange: (dateFrom: string | null, dateTo: string | null) => void+}++export function ToolQualityDateFilter({ dateFrom, dateTo, onChange }: ToolQualityDateFilterProps): JSX.Element {+ const [open, setOpen] = useState(false)+ const value = toPickerValue(dateFrom, dateTo)++ const handleApply = (next: DateTimeValue): void => {+ const relative = next.range.id !== CUSTOM_RANGE.id ? RANGE_TO_RELATIVE[next.range.name] : undefined+ if (relative) {+ onChange(relative, null)+ } else {+ onChange(next.start.toISOString(), next.end.toISOString())+ }+ setOpen(false)+ }++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger+ render={+ <Button variant="outline" data-attr="mcp-tool-quality-date-filter">+ <IconCalendar />+ {formatTriggerLabel(value)}+ </Button>+ }+ />+ <PopoverContent align="start" className="w-auto p-0">+ <DateTimePicker value={value} onApply={handleApply} onCancel={() => setOpen(false)} />+ </PopoverContent>+ </Popover>+ )+}diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsxnew file mode 100644index 000000000000..b5fc908afeb0--- /dev/null+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx@@ -0,0 +1,232 @@+import { useActions, useValues } from 'kea'++import { IconSearch } from '@posthog/icons'+import { LemonSkeleton } from '@posthog/lemon-ui'+import {+ Badge,+ Button,+ Card,+ CardFooter,+ CardHeader,+ CardTitle,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ InputGroupText,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@posthog/quill-primitives'++import { TZLabel } from 'lib/components/TZLabel'+import { LinkPrimitive } from 'lib/lemon-ui/Link/Link'+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { formatPercentage, pluralize } from 'lib/utils'+import { urls } from 'scenes/urls'++import { formatMs, formatNumber } from '../dashboard/formatters'+import { type SortState, type ToolQualityRow, mcpAnalyticsToolQualityLogic } from '../mcpAnalyticsToolQualityLogic'++const DESTRUCTIVE_ERROR_PCT = 5++// LIMIT in tool_quality.sql — 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+ label: string+ align?: 'left' | 'right'+ tooltip?: string+}++const SORTABLE_COLUMNS: ColumnSpec[] = [+ { key: 'total_calls', label: 'Calls', align: 'right', tooltip: 'Total number of times this tool was called' },+ {+ key: 'error_rate_pct',+ label: 'Error rate',+ align: 'right',+ tooltip: 'Percentage of calls that returned $mcp_is_error = true',+ },+ { key: 'p50_duration_ms', label: 'p50', align: 'right', tooltip: 'Median $mcp_duration_ms' },+ { key: 'p95_duration_ms', label: 'p95', align: 'right', tooltip: '95th-percentile $mcp_duration_ms' },+ { key: 'p99_duration_ms', label: 'p99', align: 'right', tooltip: '99th-percentile $mcp_duration_ms' },+ { key: 'users', label: 'Users', align: 'right', tooltip: 'Unique users who invoked this tool' },+ { key: 'sessions', label: 'Sessions', align: 'right', tooltip: 'Unique sessions where this tool was called' },+ { key: 'last_seen', label: 'Last seen' },+]++// Tool column + every sortable column, for the skeleton/empty-row colSpan+// Tool column + every sortable column + the trailing "Full report" action+const COLUMN_COUNT = SORTABLE_COLUMNS.length + 2++function ErrorRateBadge({ pct }: { pct: number }): JSX.Element {+ if (pct <= 0) {+ return <Badge variant="success">0%</Badge>+ }+ return (+ <Badge variant={pct >= DESTRUCTIVE_ERROR_PCT ? 'destructive' : 'warning'}>+ {formatPercentage(pct, { compact: true })}+ </Badge>+ )+}++function SortableHead({+ column,+ sort,+ onSort,+}: {+ column: ColumnSpec+ sort: SortState+ onSort: (column: string, direction: 'ASC' | 'DESC') => void+}): JSX.Element {+ const isSorted = sort.column === column.key+ const nextDirection = isSorted && sort.direction === 'DESC' ? 'ASC' : 'DESC'+ const head = (+ <button+ type="button"+ onClick={() => onSort(column.key, nextDirection)}+ className="inline-flex cursor-pointer select-none items-center gap-1"+ >+ {column.label}+ {isSorted ? <span className="text-[9px]">{sort.direction === 'DESC' ? '▼' : '▲'}</span> : null}+ </button>+ )+ return (+ <TableHead align={column.align}>+ {column.tooltip ? <Tooltip title={column.tooltip}>{head}</Tooltip> : head}+ </TableHead>+ )+}++function ToolRows(): JSX.Element {+ const { filteredRows, toolRowsLoading, selectedTool } = useValues(mcpAnalyticsToolQualityLogic)+ const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)++ if (toolRowsLoading && filteredRows.length === 0) {+ return (+ <TableRow>+ <TableCell colSpan={COLUMN_COUNT}>+ <div className="space-y-2 py-1">+ {Array.from({ length: 6 }).map((_, i) => (+ <LemonSkeleton key={i} className="h-3.5 w-full" />+ ))}+ </div>+ </TableCell>+ </TableRow>+ )+ }+ if (filteredRows.length === 0) {+ return (+ <TableRow>+ <TableCell colSpan={COLUMN_COUNT} align="center" className="py-6 text-secondary">+ No tool calls match the current filters.+ </TableCell>+ </TableRow>+ )+ }+ return (+ <>+ {filteredRows.map((row) => (+ <TableRow+ key={row.tool}+ data-state={row.tool === selectedTool ? 'selected' : undefined}+ className="cursor-pointer"+ onClick={() => setSelectedTool(row.tool === selectedTool ? null : row.tool)}+ data-attr="mcp-tool-quality-row"+ >+ <TableCell expand>+ <span className="font-mono">{row.tool}</span>+ </TableCell>+ <TableCell align="right">{formatNumber(row.total_calls)}</TableCell>+ <TableCell align="right">+ <ErrorRateBadge pct={row.error_rate_pct} />+ </TableCell>+ <TableCell align="right">{formatMs(row.p50_duration_ms)}</TableCell>+ <TableCell align="right">{formatMs(row.p95_duration_ms)}</TableCell>+ <TableCell align="right">{formatMs(row.p99_duration_ms)}</TableCell>+ <TableCell align="right">{formatNumber(row.users)}</TableCell>+ <TableCell align="right">{formatNumber(row.sessions)}</TableCell>+ <TableCell className="whitespace-nowrap">+ <TZLabel time={row.last_seen} />+ </TableCell>+ <TableCell align="right">+ <Button+ variant="outline"+ size="sm"+ render={<LinkPrimitive to={urls.mcpAnalyticsTool(row.tool)} />}+ onClick={(e) => e.stopPropagation()}+ data-attr="mcp-tool-quality-full-report"+ >+ Full report+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </>+ )+}++export function ToolQualityTable(): JSX.Element {+ const { toolQualitySort, toolRows, filteredRows, toolRowsLoading, searchTerm } =+ useValues(mcpAnalyticsToolQualityLogic)+ const { setToolQualitySort, setSearchTerm } = useActions(mcpAnalyticsToolQualityLogic)++ return (+ <Card size="sm" className="gap-0">+ <CardHeader className="flex flex-row flex-wrap items-center justify-between gap-2 border-b border-border pb-3">+ <CardTitle>All tools</CardTitle>+ <InputGroup className="w-[220px]">+ <InputGroupAddon align="inline-start">+ <InputGroupText>+ <IconSearch />+ </InputGroupText>+ </InputGroupAddon>+ <InputGroupInput+ type="search"+ placeholder="Search tools"+ value={searchTerm}+ onChange={(e) => setSearchTerm(e.target.value)}+ data-attr="mcp-tool-quality-search"+ />+ </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}+ onSort={setToolQualitySort}+ />+ ))}+ <TableHead />+ </TableRow>+ </TableHeader>+ <TableBody>+ <ToolRows />+ </TableBody>+ </Table>+ {!toolRowsLoading && toolRows.length > 0 && (+ <CardFooter className="border-t border-border py-2 text-xs text-secondary">+ {formatToolCount(filteredRows.length, toolRows.length)}+ </CardFooter>+ )}+ </Card>+ )+}diff --git a/products/mcp_analytics/package.json b/products/mcp_analytics/package.jsonindex 00016e6751ff..ed4f5dcf35ab 100644--- a/products/mcp_analytics/package.json+++ b/products/mcp_analytics/package.json@@ -5,11 +5,15 @@},"dependencies": {"@posthog/quill-charts": "workspace:*",+ "@posthog/quill-components": "workspace:*","@posthog/quill-primitives": "workspace:*","kea": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:"},+ "devDependencies": {+ "kea-test-utils": "catalog:"+ },"peerDependencies": {"@storybook/react": "catalog:","@types/react": "*",