: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): move dashboard overview to quill-charts (#62149)
Sam Penningtond1c9f85178ad
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 46b40b12c6e9..f14c59b1d365 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5331,13 +5331,37 @@ snapshots:scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:hash: v1.k794b7964.4ebf2f848b10c8b2859630215a9be1ff91fb825fc334005207556310261d3a5c.UcqJY3dqyJNbi3x7oYaZ2rEu95LAEdbGmMyEpI-Wlgcscenes-app-mcp-analytics--dashboard--dark:- hash: v1.k794b7964.3c6b02398e9549974a8f79fd1a2d33c994c561817036e93fdf931f6209bebead.SfSciYNGfgRXpksGf8rxFEKBp30Czke2bKIseYIBLrk+ hash: v1.k794b7964.83c70580c95196511976b284e12102c4fc4b60bfe0c4b5b84ede14177c0f0fc1.ghImisZOBWjSVAnytJWdTHks5jIe2jn032_4NF_-g-cscenes-app-mcp-analytics--dashboard--light:- hash: v1.k794b7964.09589f49fe0b959b79652e6dadf9e38981aecdf5fa383dc7a1bbfd4c1e0649aa.abSoArXwTLreeJ_FkcqqbgT3I2mTbbgPy_uvrfYJous+ hash: v1.k794b7964.c64d5d43c4eaa79d3008e9dd40857d9bee879832e68a8f8e9464657ff670773f.yKxStICPwIMCMEnf_zQhK0BuXu5BIxaUKmgPYHAEzYoscenes-app-mcp-analytics--sessions--dark:hash: v1.k794b7964.a033f7dca28cc0bfea783c71c6c2cbed6c58f87d705aa4772742c6f7136a437a.vFUlACgvfOrTJfC2Ogf7u7myI9SL_njtFgyBD88-TqEscenes-app-mcp-analytics--sessions--light:hash: v1.k794b7964.497d9ae69307438f3ef9ebfc80bb948ffd70d285eda4192f6b2e21f1a66d3eba.XI5y0bJbIitncOcXS_6Gxcr4pgGCK1moA7JIAstwuL4+ scenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--dark:+ hash: v1.k794b7964.695d298349258e60b3b8f0c8775e1554ffd9ad3a3b9d4d750df124550bf65c51.cpBNQ-OwnkymJacZsj27ScYkVTr_36Yb8Z27xINlTN8+ scenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--light:+ hash: v1.k794b7964.3dfc5ce2265a673956f3eab4e61f354d521843fa67e204a55b00d9a477059dff.5usCphh504ZrBw5hriydx544vV8-RLHdGmrR-lJipNU+ scenes-app-mcp-analytics-dashboard-cards--daily-tool-breakdown--dark:+ hash: v1.k794b7964.830c208da94ba09d6c4ebbf829d48e8d8647ac7e6f10005d0ece25d8b1452826.H6z3crTfy2qeI7IGNmP1sVidoSC2oOUayUHiftQFGK4+ scenes-app-mcp-analytics-dashboard-cards--daily-tool-breakdown--light:+ hash: v1.k794b7964.08616349eeae04cabd327dde6ab1cf6bd40a19a609f175554044ac2c0bceb271.qccwqFpHII7zSOEe3-1rqQpODEHCZ4B5uOyojP6oO9Y+ scenes-app-mcp-analytics-dashboard-cards--error-rate-by-tool--dark:+ hash: v1.k794b7964.6d0c0cd5cbb382903fee3b31192a515c1aeaf19d17ef3626f300815b1d0ce3aa.czfgUIwTwO7B3tJ874cZj9pvjWCdKI9wQLAkIl5LIhU+ scenes-app-mcp-analytics-dashboard-cards--error-rate-by-tool--light:+ hash: v1.k794b7964.6316d94634f57953534f1f850f7e4b2996a1d8352764079f95b5854b5eda290d.ewSfhCd5QZsVhibDpQTGKyFK6swQn_gxQuNmPmWHS-M+ scenes-app-mcp-analytics-dashboard-cards--flagged-sessions--dark:+ hash: v1.k794b7964.37e85662ee40e1f94bb57b4fd77c76597ece70a6f17058a454635fde2bdeb3be.i019UVgAa48DZSAgEdHhYseiA0vJ4CULAVN_wkw5Ilk+ scenes-app-mcp-analytics-dashboard-cards--flagged-sessions--light:+ hash: v1.k794b7964.52a1b29f817077e0d8452260716e950f063e206bd90d35c7be58ba72e93f13de.awEggL6KzFFucKT1Dd055i2oacGHM1WnHCSYHOwxQIo+ scenes-app-mcp-analytics-dashboard-cards--key-metrics--dark:+ hash: v1.k794b7964.a8702a279540c2b5948595e182262c46a5aab9cfa8ed7537835771f4bf72542c.2VmeQEIAddJRjB0JGkg3gy-SPb5xiNeRrjUdPUyI0O0+ scenes-app-mcp-analytics-dashboard-cards--key-metrics--light:+ hash: v1.k794b7964.c78e0996ca8f257caa690c14f798aa30a3d6c184e268a4e66258d8e35248238d.--SI4BHWCCEKaTk33AtDEjh5BifMpWBcPFmO2FF4EfE+ scenes-app-mcp-analytics-dashboard-cards--share-by-harness--dark:+ hash: v1.k794b7964.91754923c079ce0c9fc46b83fe672ee4f967701bde08562b80fee6cacdbeeb01.eWYTt2AnIb5vZmQehDXCSkxR03Ld6ryyA6rYoyG-J1g+ scenes-app-mcp-analytics-dashboard-cards--share-by-harness--light:+ hash: v1.k794b7964.10747a2c1ad93039c1443ce8ca55ea8c6db2916d88aed4ec779102fff3b1d80e.WHnFkQAppqq7lyAW8c3ikAB7FjYB2l_6ac5_R8GiLMEscenes-app-notebooks--bullet-list--dark:hash: v1.k794b7964.92b730d52ab36684be26e6553326b5325ec30479049b955e0c21b680786a1b0a.DxqaNZeZRaXD6cbT74fO1NrIXGkrJt3Q_x5kz2xkgIIscenes-app-notebooks--bullet-list--light:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex efb434ba8135..a2c4619fdc81 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3165,6 +3165,9 @@ importers:'@posthog/quill-charts':specifier: workspace:*version: link:../../packages/quill/packages/charts+ '@posthog/quill-primitives':+ specifier: workspace:*+ version: link:../../packages/quill/packages/primitives'@storybook/react':specifier: 'catalog:'version: 8.6.18(@storybook/[email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.pyindex 59e44c35f681..98d3358b36bf 100644--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py@@ -5,6 +5,8 @@ from typing import Anyfrom django.core.management.base import BaseCommand, CommandParser+from posthog.clickhouse.client import sync_execute+from posthog.models.event.sql import EVENTS_DATA_TABLEfrom posthog.models.event.util import create_eventfrom posthog.models.person import Person, PersonDistinctIdfrom posthog.models.person.util import create_person, create_person_distinct_id, get_person_by_distinct_id@@ -22,7 +24,11 @@ TOOL_NAMES = ["error_tracking_issue_get",]-CLIENT_NAMES = ["Claude Desktop", "Cursor", "Windsurf", "Cline"]+# Raw $mcp_client_name values that categorizeHarness() folds into the popular, logo-backed+# harness buckets (Claude Code, OpenAI Codex, Cursor, Claude.ai, VS Code). Weighted toward the+# most common agents so the breakdown looks realistic.+CLIENT_NAMES = ["claude-code", "codex", "cursor", "claude-ai", "visual studio code"]+CLIENT_WEIGHTS = [38, 26, 22, 9, 5]# Identified personas. About 70% of sessions are attached to one of these;# the rest stay anonymous with throwaway distinct_ids.@@ -110,14 +116,27 @@ class Command(BaseCommand):parser.add_argument("--sessions", type=int, default=101, help="Number of sessions to create.")parser.add_argument("--min-calls", type=int, default=4, help="Minimum tool calls per session (inclusive).")parser.add_argument("--max-calls", type=int, default=50, help="Maximum tool calls per session (inclusive).")+ parser.add_argument(+ "--days",+ type=int,+ default=0,+ help="Spread sessions across the last N days (for trend charts). 0 keeps everything in the last hour.",+ )parser.add_argument("--seed", type=int, default=None, help="Optional random seed for reproducible output.")+ parser.add_argument(+ "--clear",+ action="store_true",+ help="Delete existing mcp_tool_call events for the team before seeding (clean slate).",+ )def handle(self, *args: Any, **options: Any) -> None:team_id: int = options["team_id"]session_count: int = options["sessions"]min_calls: int = options["min_calls"]max_calls: int = options["max_calls"]+ days: int = options["days"]seed: int | None = options["seed"]+ clear: bool = options["clear"]if min_calls > max_calls:self.stderr.write(self.style.ERROR("--min-calls must be <= --max-calls"))@@ -129,6 +148,13 @@ class Command(BaseCommand):self.stderr.write(self.style.ERROR(f"Team {team_id} does not exist."))return+ if clear:+ sync_execute(+ f"ALTER TABLE {EVENTS_DATA_TABLE()} DELETE WHERE team_id = %(team_id)s AND event = 'mcp_tool_call' SETTINGS mutations_sync=1",+ {"team_id": team_id},+ )+ self.stdout.write(self.style.WARNING(f"Cleared existing mcp_tool_call events for team {team_id}."))+rng = random.Random(seed)now = datetime.now(tz=UTC)total_events = 0@@ -182,7 +208,7 @@ class Command(BaseCommand):distinct_id = persona["distinct_id"]else:distinct_id = f"anon_{uuid.uuid4().hex[:8]}"- client_name = rng.choice(CLIENT_NAMES)+ client_name = rng.choices(CLIENT_NAMES, weights=CLIENT_WEIGHTS, k=1)[0]calls = rng.randint(min_calls, max_calls)# Anchor each session within the listing's default 24h window so it shows# up on the next request. The listing aggregates recent events on the fly,@@ -190,7 +216,12 @@ class Command(BaseCommand):# clearly "in the past" without flirting with the window edge.call_intervals = [rng.randint(15, 90) for _ in range(calls)]total_call_duration = timedelta(seconds=sum(call_intervals))- session_end_offset_min = rng.randint(31, 59)+ if days > 0:+ # Spread session_end across the last N days so trend charts (bucketed+ # by date over a 7-day window) show a curve instead of a single spike.+ session_end_offset_min = rng.randint(31, days * 24 * 60)+ else:+ session_end_offset_min = rng.randint(31, 59)session_start = now - timedelta(minutes=session_end_offset_min) - total_call_durationcumulative_offset_s = 0diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsxindex 708acb1fc44a..6d66ed335cfb 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx@@ -1,540 +1,76 @@import { useValues } from 'kea'import { useMemo } from 'react'-import { IconBolt } from '@posthog/icons'-import { LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'-import { type ChartTheme, MetricCard } from '@posthog/quill-charts'+import { type ChartTheme } from '@posthog/quill-charts'import { buildTheme } from 'lib/charts/utils/theme'-import { humanFriendlyDuration, humanFriendlyLargeNumber } from 'lib/utils'-import { urls } from 'scenes/urls'+import { teamLogic } from 'scenes/teamLogic'import { themeLogic } from '~/layout/navigation-3000/themeLogic'-import claudeLogo from './harness-logos/claude.svg'-import cursorLogo from './harness-logos/cursor.svg'-import openaiLogo from './harness-logos/openai.svg'-import vscodeLogo from './harness-logos/vscode.svg'-import { HarnessRow, KPIMetric, NotableSession, ToolRow, mcpDashboardOverviewLogic } from './mcpDashboardOverviewLogic'--const HARNESS_LOGOS: Record<string, string> = {- 'Claude Code': claudeLogo,- 'Claude.ai': claudeLogo,- 'OpenAI Codex': openaiLogo,- Cursor: cursorLogo,- 'VS Code': vscodeLogo,-}--export function HarnessPill({ category, title }: { category: string; title?: string }): JSX.Element {- const logo = HARNESS_LOGOS[category]- return (- <span- className="inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary bg-surface-primary px-2 py-0.5 text-xs"- title={title}- >- {logo ? (- <img src={logo} alt="" className="h-3.5 w-3.5 shrink-0 object-contain" />- ) : (- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-secondary" aria-hidden />- )}- <span className="truncate">{category}</span>- </span>- )-}--interface TileSpec {- label: string- metric: KPIMetric- href: string- format: (n: number) => string- /** Sparkline color, picked from the shared data-viz palette (theme.colors). */- color: string- loading: boolean-}--function formatNumber(n: number): string {- if (!isFinite(n)) {- return '—'- }- return humanFriendlyLargeNumber(n)-}--function formatPercent(n: number): string {- if (!isFinite(n)) {- return '—'- }- return `${n.toFixed(n >= 10 ? 0 : 1)}%`-}--function formatMs(n: number): string {- if (!isFinite(n) || n === 0) {- return '—'- }- if (n < 1000) {- return `${Math.round(n)}ms`- }- return humanFriendlyDuration(n / 1000, { secondsPrecision: 1 })-}--function KPITile({ tile, theme }: { tile: TileSpec; theme: ChartTheme }): JSX.Element {- const { metric } = tile- const hasSparkline = metric.sparkline.length > 0- const hasComparison = metric.deltaPct !== null-- return (- <Link- to={tile.href}- subtle- className="flex flex-col rounded-lg border border-primary bg-surface-primary px-3.5 py-3 shadow-sm transition-all hover:border-secondary hover:shadow-md"- >- {tile.loading ? (- <div className="flex flex-col gap-2">- <LemonSkeleton className="h-3 w-16" />- <LemonSkeleton className="h-7 w-20" />- </div>- ) : (- <MetricCard- className="text-primary"- title={tile.label}- value={metric.value}- data={hasSparkline ? metric.sparkline : undefined}- theme={theme}- color={tile.color}- goodDirection={metric.goodDirection}- formatValue={tile.format}- subtitle={hasComparison ? `vs. ${tile.format(metric.previousValue)} prior` : undefined}- sparklineHeight={50}- sparklineClassName="mt-3 -mx-3.5 -mb-3"- />- )}- </Link>- )-}+import { ActivityChart } from './dashboard/ActivityChart'+import { HarnessDonut } from './dashboard/HarnessDonut'+import { KpiTiles } from './dashboard/KpiTiles'+import { NotableSessionsTable } from './dashboard/NotableSessionsTable'+import { ToolErrorRateChart } from './dashboard/ToolErrorRateChart'+import { ToolUsageChart } from './dashboard/ToolUsageChart'+import { mcpDashboardOverviewLogic } from './mcpDashboardOverviewLogic'export function MCPAnalyticsDashboardOverview(): JSX.Element {const {kpis,kpisLoading,intentClusterCount,- topToolRows,- toolRowsLoading,- toolRowsTotal,notableSessions,sessionRowsLoading,harnessRows,harnessRawRowsLoading,+ dailyActivity,+ activityRowsLoading,+ toolDailySeries,+ toolDailyRowsLoading,+ toolRows,+ toolRowsLoading,} = useValues(mcpDashboardOverviewLogic)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])- const tiles: TileSpec[] = [- {- label: 'Sessions',- metric: kpis.sessions,- href: urls.mcpAnalyticsSessions(),- format: formatNumber,- color: theme.colors[0], // --data-color-1 (blue)- loading: kpisLoading,- },- {- label: 'Tool calls',- metric: kpis.toolCalls,- href: urls.mcpAnalyticsToolQuality(),- format: formatNumber,- color: theme.colors[0], // --data-color-1 (blue)- loading: kpisLoading,- },- {- label: 'Error rate',- metric: kpis.errorRatePct,- href: urls.mcpAnalyticsSessions(),- format: formatPercent,- color: theme.colors[4], // --data-color-5 (red)- loading: kpisLoading,- },- {- label: 'p95 latency',- metric: kpis.p95LatencyMs,- href: urls.mcpAnalyticsToolQuality(),- format: formatMs,- color: theme.colors[0], // --data-color-1 (blue)- loading: kpisLoading,- },- {- label: 'Intent clusters',- metric: intentClusterCount,- href: urls.mcpAnalyticsIntentClustering(),- format: formatNumber,- color: theme.colors[6], // --data-color-7 (green)- loading: false,- },- ]-- return (- <div className="flex flex-col gap-[22px]">- <BrandingStrip />- <Block kicker="Health" question="Is the MCP healthy right now?">- <div className="grid grid-cols-2 gap-3 md:grid-cols-5">- {tiles.map((tile) => (- <KPITile key={tile.label} tile={tile} theme={theme} />- ))}- </div>- </Block>- <Block kicker="Tool quality" question="Which tools are the weak links?">- <ToolReliabilityMatrix rows={topToolRows} loading={toolRowsLoading} totalTools={toolRowsTotal} />- </Block>- <Block kicker="Surface" question="Which harnesses are calling the MCP?">- <HarnessBreakdown rows={harnessRows} loading={harnessRawRowsLoading} />- </Block>- <Block kicker="Triage" question="Which sessions should I look at?">- <NotableSessionsTable sessions={notableSessions} loading={sessionRowsLoading} />- </Block>- </div>- )-}--function BrandingStrip(): JSX.Element {- return (- <div className="flex items-center justify-between">- <div className="flex items-center gap-2">- <span className="flex h-[22px] w-[22px] items-center justify-center rounded bg-warning text-white">- <IconBolt className="h-3 w-3" />- </span>- <span className="text-[13px] font-medium">PostHog for Agents</span>- <LemonTag type="completion" size="small">- Alpha- </LemonTag>- </div>- <span className="text-[11px] text-tertiary">Last 7 days</span>- </div>- )-}--function Block({- kicker,- question,- children,-}: {- kicker: string- question: string- children: React.ReactNode-}): JSX.Element {return (- <section className="flex flex-col">- <div className="text-[11px] text-secondary mb-1">{kicker}</div>- <h1 className="text-sm font-medium mb-3">{question}</h1>- {children}- </section>- )-}--function Card({ children }: { children: React.ReactNode }): JSX.Element {- return <div className="rounded-lg border border-primary bg-surface-primary px-3.5 py-3">{children}</div>-}--type ErrorBucket = 'green' | 'amber' | 'red'--function errorBucket(pct: number): ErrorBucket {- if (pct < 1) {- return 'green'- }- if (pct <= 5) {- return 'amber'- }- return 'red'-}--const ERROR_PILL_CLASS: Record<ErrorBucket, string> = {- green: 'text-success bg-fill-success-highlight',- amber: 'text-warning bg-fill-warning-highlight',- red: 'text-error bg-fill-error-highlight',-}--function ErrorRatePill({ pct }: { pct: number }): JSX.Element {- const bucket = errorBucket(pct)- return (- <span- className={`inline-flex h-[14px] items-center justify-center rounded-[3px] px-1.5 text-[10px] font-medium ${ERROR_PILL_CLASS[bucket]}`}- >- {pct.toFixed(pct >= 10 ? 0 : 1)}%- </span>- )-}--const VOLUME_COLOR = 'var(--data-color-1)'-const ERROR_COLOR = 'var(--data-color-5)'--function VolumeBar({ totalPct, errorPct, title }: { totalPct: number; errorPct: number; title: string }): JSX.Element {- const errorStartPct = (Math.max(totalPct - errorPct, 0) / (totalPct || 1)) * 100- return (- <div className="relative h-[14px] overflow-hidden rounded-[3px] bg-surface-secondary" title={title}>- <div- className="h-full opacity-40"- style={{- width: `${totalPct}%`,- background: `linear-gradient(to right, ${VOLUME_COLOR} ${errorStartPct}%, ${ERROR_COLOR} ${errorStartPct}%)`,- }}- />- </div>- )-}--function ToolRowItem({ row, maxVolume, isLast }: { row: ToolRow; maxVolume: number; isLast: boolean }): JSX.Element {- const callsPct = maxVolume ? (row.total_calls / maxVolume) * 100 : 0- const errorsPct = maxVolume ? (row.errors / maxVolume) * 100 : 0- const nameClass = row.error_rate_pct > 5 ? 'text-error' : 'text-primary'- return (- <div- className="grid items-center gap-2.5 py-1.5"- style={{- gridTemplateColumns: '140px 1fr 60px 56px',- borderBottom: isLast ? 'none' : '0.5px solid var(--color-border-tertiary)',- }}- >- <Link- to={urls.mcpAnalyticsTool(row.tool)}- className={`truncate font-mono text-xs ${nameClass}`}- title={row.tool}- >- {row.tool}- </Link>- <VolumeBar- totalPct={callsPct}- errorPct={errorsPct}- title={`${row.total_calls} calls · ${row.errors} errors`}- />- <ErrorRatePill pct={row.error_rate_pct} />- <span className="text-right font-mono text-xs text-primary">- {row.p95_duration_ms ? `${Math.round(row.p95_duration_ms)}ms` : '—'}- </span>- </div>- )-}--function ToolReliabilityMatrix({- rows,- loading,- totalTools,-}: {- rows: ToolRow[]- loading: boolean- totalTools: number-}): JSX.Element {- const maxVolume = rows.length ? Math.max(...rows.map((r) => r.total_calls)) : 0-- return (- <Card>- <div- className="grid items-center gap-2.5 pb-1.5 text-[11px] text-secondary"- style={{- gridTemplateColumns: '140px 1fr 60px 56px',- borderBottom: '0.5px solid var(--color-border-secondary)',- }}- >- <span>Tool</span>- <span>- <span style={{ color: VOLUME_COLOR }}>Calls</span>- <span className="mx-1">·</span>- <span style={{ color: ERROR_COLOR }}>errors</span>- </span>- <span>Err</span>- <span className="text-right">p95</span>- </div>- {loading && rows.length === 0 ? (- <div className="space-y-2 py-3">- {Array.from({ length: 5 }).map((_, i) => (- <LemonSkeleton key={i} className="h-3.5 w-full" />- ))}- </div>- ) : rows.length === 0 ? (- <div className="py-6 text-center text-[12px] text-secondary">No tool calls yet.</div>- ) : (- rows.map((row, i) => (- <ToolRowItem key={row.tool} row={row} maxVolume={maxVolume} isLast={i === rows.length - 1} />- ))- )}- {rows.length > 0 && (- <div className="mt-1.5 flex justify-end">- <Link to={urls.mcpAnalyticsToolQuality()} className="text-[10px]">- View all {totalTools} tools ↗- </Link>- </div>- )}- </Card>- )-}--const HARNESS_GRID_TEMPLATE = '160px 1fr 56px 56px'--function HarnessBreakdown({ rows, loading }: { rows: HarnessRow[]; loading: boolean }): JSX.Element {- const maxCalls = rows.length ? Math.max(...rows.map((r) => r.total_calls)) : 0- const totalCalls = rows.reduce((acc, r) => acc + r.total_calls, 0)-- return (- <Card>- <div- className="grid items-center gap-2.5 pb-1.5 text-[11px] text-secondary"- style={{- gridTemplateColumns: HARNESS_GRID_TEMPLATE,- borderBottom: '0.5px solid var(--color-border-secondary)',- }}- >- <span>Harness</span>- <span>- <span style={{ color: VOLUME_COLOR }}>Calls</span>- <span className="mx-1">·</span>- <span style={{ color: ERROR_COLOR }}>errors</span>- </span>- <span>Err</span>- <span className="text-right">Share</span>- </div>- {loading && rows.length === 0 ? (- <div className="space-y-2 py-3">- {Array.from({ length: 5 }).map((_, i) => (- <LemonSkeleton key={i} className="h-3.5 w-full" />- ))}- </div>- ) : rows.length === 0 ? (- <div className="py-6 text-center text-[12px] text-secondary">No harness data yet.</div>- ) : (- rows.map((row, i) => {- const callsPct = maxCalls ? (row.total_calls / maxCalls) * 100 : 0- const errorsPct = maxCalls ? (row.errors / maxCalls) * 100 : 0- const share = totalCalls ? (row.total_calls / totalCalls) * 100 : 0- const tooltip = row.raw_clients.slice(0, 8).join(', ')- return (- <div- key={row.category}- className="grid items-center gap-2.5 py-1.5"- style={{- gridTemplateColumns: HARNESS_GRID_TEMPLATE,- borderBottom:- i === rows.length - 1 ? 'none' : '0.5px solid var(--color-border-tertiary)',- }}- >- <HarnessPill category={row.category} title={tooltip} />- <VolumeBar- totalPct={callsPct}- errorPct={errorsPct}- title={`${row.total_calls} calls · ${row.errors} errors · ${row.sessions} sessions`}+ <div className="flex flex-col gap-10" data-quill>+ <section>+ <h2 className="mb-4 text-xl font-semibold text-primary">This week's key metrics</h2>+ <KpiTiles kpis={kpis} intentClusterCount={intentClusterCount} kpisLoading={kpisLoading} theme={theme} />+ </section>+ <section>+ <h2 className="mb-4 text-xl font-semibold text-primary">Last month's usage</h2>+ <div className="flex flex-col gap-[22px]">+ <div className="grid grid-cols-1 gap-[22px] lg:grid-cols-3">+ <div className="flex lg:col-span-2">+ <ActivityChart+ daily={dailyActivity}+ loading={activityRowsLoading}+ theme={theme}+ timezone={timezone}/>- <ErrorRatePill pct={row.error_rate_pct} />- <span className="text-right font-mono text-xs text-primary">- {share.toFixed(share >= 10 ? 0 : 1)}%- </span></div>- )- })- )}- </Card>- )-}--function truncateSessionId(id: string): string {- if (id.length <= 12) {- return id- }- return `${id.slice(0, 4)}…${id.slice(-4)}`-}--function formatDuration(seconds: number): string {- if (!seconds || !isFinite(seconds)) {- return '—'- }- if (seconds < 60) {- return `${seconds}s`- }- return humanFriendlyDuration(seconds, { secondsPrecision: 0 })-}--function StatusPill({ errorRatePct }: { errorRatePct: number }): JSX.Element {- if (errorRatePct >= 100) {- return (- <span className="inline-flex h-[14px] items-center rounded-[3px] bg-fill-error-highlight px-1.5 text-[10px] font-medium text-error">- 100% err- </span>- )- }- if (errorRatePct > 0) {- const bucket = errorBucket(errorRatePct)- return (- <span- className={`inline-flex h-[14px] items-center rounded-[3px] px-1.5 text-[10px] font-medium ${ERROR_PILL_CLASS[bucket]}`}- >- {errorRatePct.toFixed(errorRatePct >= 10 ? 0 : 1)}% err- </span>- )- }- return (- <span className="inline-flex h-[14px] items-center rounded-[3px] bg-fill-success-highlight px-1.5 text-[10px] font-medium text-success">- Success- </span>- )-}--const NOTABLE_GRID_TEMPLATE = '22% 12% 14% 18% 1fr'--function NotableSessionsTable({ sessions, loading }: { sessions: NotableSession[]; loading: boolean }): JSX.Element {- return (- <Card>- <div- className="grid items-center gap-2.5 pb-1.5 text-[11px] text-secondary"- style={{- gridTemplateColumns: NOTABLE_GRID_TEMPLATE,- borderBottom: '0.5px solid var(--color-border-secondary)',- }}- >- <span>Session</span>- <span>Calls</span>- <span>Duration</span>- <span>Status</span>- <span>Why notable</span>- </div>- {loading && sessions.length === 0 ? (- <div className="space-y-2 py-3">- {Array.from({ length: 4 }).map((_, i) => (- <LemonSkeleton key={i} className="h-3.5 w-full" />- ))}- </div>- ) : sessions.length === 0 ? (- <div className="py-6 text-center text-[12px] text-secondary">- No notable sessions in the last 7 days.- </div>- ) : (- sessions.map((entry, i) => (- <div- key={entry.session.session_id}- className="grid items-center gap-2.5 py-1.5"- style={{- gridTemplateColumns: NOTABLE_GRID_TEMPLATE,- borderBottom:- i === sessions.length - 1 ? 'none' : '0.5px solid var(--color-border-tertiary)',- }}- >- <Link- to={urls.mcpAnalyticsSessions()}- className="truncate font-mono text-[11px]"- title={entry.session.session_id}- >- {truncateSessionId(entry.session.session_id)}- </Link>- <span className="text-[11px]">{entry.session.tool_calls}</span>- <span className="text-[11px]">{formatDuration(entry.session.duration_seconds)}</span>- <StatusPill errorRatePct={entry.session.error_rate_pct} />- <span className="truncate text-[11px] text-primary" title={entry.label}>- {entry.label}- </span>+ <HarnessDonut rows={harnessRows} loading={harnessRawRowsLoading} theme={theme} /></div>- ))- )}- {sessions.length > 0 && (- <div className="mt-1.5 flex justify-end">- <Link to={urls.mcpAnalyticsSessions()} className="text-[10px]">- Open all flagged sessions in Sessions tab ↗- </Link>+ <div className="grid grid-cols-1 gap-[22px] lg:grid-cols-2">+ <ToolErrorRateChart rows={toolRows} loading={toolRowsLoading} theme={theme} />+ <NotableSessionsTable sessions={notableSessions} loading={sessionRowsLoading} />+ </div>+ <ToolUsageChart+ data={toolDailySeries}+ loading={toolDailyRowsLoading}+ theme={theme}+ timezone={timezone}+ /></div>- )}- </Card>+ </section>+ </div>)}diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsxindex 8470aaf77295..e8ea2e244cf0 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx@@ -15,7 +15,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { Query } from '~/queries/Query/Query'import { SceneExport } from '~/scenes/sceneTypes'-import { HarnessPill } from './MCPAnalyticsDashboardOverview'+import { HarnessPill } from './dashboard/harness'import {IntentCoverage,MCPAnalyticsToolDetailLogicProps,diff --git a/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx b/products/mcp_analytics/frontend/dashboard/ActivityChart.tsxnew file mode 100644index 000000000000..206301eeeac5--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx@@ -0,0 +1,62 @@+import { useMemo } from 'react'++import { LemonSkeleton } from '@posthog/lemon-ui'+import {+ type ChartTheme,+ type Series,+ TimeSeriesLineChart,+ type TimeSeriesLineChartConfig,+} from '@posthog/quill-charts'++import { type DailyActivity } from '../mcpDashboardOverviewLogic'+import { Card, CardState } from './Card'++export function ActivityChart({+ daily,+ loading,+ theme,+ timezone,+}: {+ daily: DailyActivity+ loading: boolean+ theme: ChartTheme+ timezone: string+}): JSX.Element {+ const series = useMemo<Series[]>(() => {+ const totals = daily.successes.map((s, i) => s + (daily.errors[i] ?? 0))+ return [+ { key: 'calls', label: 'Tool calls', color: theme.colors[0], data: totals },+ { key: 'errors', label: 'Errors', color: theme.colors[4], data: daily.errors },+ ]+ }, [daily, theme])+ // quill's built-in date tick formatter only kicks in when both interval and timezone are set.+ const config = useMemo<TimeSeriesLineChartConfig>(+ () => ({+ yAxis: { showGrid: false },+ showAxisLines: true,+ xAxis: { interval: 'day', timezone },+ showCrosshair: true,+ tooltip: { placement: 'cursor' },+ }),+ [timezone]+ )++ return (+ <Card className="flex flex-1 flex-col" title="Daily tool calls and errors">+ <CardState+ loading={loading}+ isEmpty={daily.labels.length === 0}+ skeleton={<LemonSkeleton className="min-h-[300px] flex-1" />}+ empty={+ <div className="flex flex-1 items-center justify-center py-6 text-center text-[12px] text-secondary">+ No activity yet.+ </div>+ }+ >+ <div className="flex min-h-[300px] flex-1 flex-col">+ <TimeSeriesLineChart series={series} labels={daily.labels} config={config} theme={theme} />+ </div>+ </CardState>+ </Card>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/Card.tsx b/products/mcp_analytics/frontend/dashboard/Card.tsxnew file mode 100644index 000000000000..02b2d2af5b48--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/Card.tsx@@ -0,0 +1,46 @@+import { Card as QuillCard, CardContent, CardHeader, CardTitle } from '@posthog/quill-primitives'++export function Card({+ children,+ className,+ title,+}: {+ children: React.ReactNode+ className?: string+ title?: string+}): JSX.Element {+ return (+ <QuillCard size="sm" className={className}>+ {title ? (+ <CardHeader>+ <CardTitle>{title}</CardTitle>+ </CardHeader>+ ) : null}+ <CardContent className="flex flex-1 flex-col">{children}</CardContent>+ </QuillCard>+ )+}++// Picks the right card body: a skeleton while the first load is in flight, an empty message when+// there's no data, otherwise the content. Guard clauses instead of a nested ternary at each call site.+export function CardState({+ loading,+ isEmpty,+ skeleton,+ empty,+ children,+}: {+ loading: boolean+ isEmpty: boolean+ skeleton: React.ReactNode+ empty: React.ReactNode+ children: React.ReactNode+}): JSX.Element {+ if (loading && isEmpty) {+ return <>{skeleton}</>+ }+ if (isEmpty) {+ return <>{empty}</>+ }+ return <>{children}</>+}diff --git a/products/mcp_analytics/frontend/dashboard/ChartTooltip.tsx b/products/mcp_analytics/frontend/dashboard/ChartTooltip.tsxnew file mode 100644index 000000000000..43b2a1a9d92b--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/ChartTooltip.tsx@@ -0,0 +1,13 @@+export function ChartTooltip({ title, rows }: { title: string; rows: [string, string][] }): JSX.Element {+ return (+ <div className="rounded-md border border-primary bg-surface-primary px-2.5 py-2 text-xs shadow-md">+ <div className="mb-1 font-medium text-primary">{title}</div>+ {rows.map(([label, value]) => (+ <div key={label} className="flex justify-between gap-4 text-secondary">+ <span>{label}</span>+ <span className="font-mono text-primary">{value}</span>+ </div>+ ))}+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsxnew file mode 100644index 000000000000..07700d375935--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx@@ -0,0 +1,174 @@+import { Meta, StoryObj } from '@storybook/react'++import { type ChartTheme } from '@posthog/quill-charts'++import { buildTheme } from 'lib/charts/utils/theme'++import {+ type DailyActivity,+ type HarnessRow,+ type KPIData,+ type KPIMetric,+ type NotableSession,+ type ToolDailySeries,+ type ToolRow,+} from '../mcpDashboardOverviewLogic'+import { ActivityChart } from './ActivityChart'+import { HarnessDonut } from './HarnessDonut'+import { KpiTiles } from './KpiTiles'+import { NotableSessionsTable } from './NotableSessionsTable'+import { ToolErrorRateChart } from './ToolErrorRateChart'+import { ToolUsageChart } from './ToolUsageChart'++const DAYS = ['Jun 1', 'Jun 2', 'Jun 3', 'Jun 4', 'Jun 5', 'Jun 6', 'Jun 7']++const DAILY_ACTIVITY: DailyActivity = {+ labels: DAYS,+ successes: [4180, 4360, 4560, 4430, 4720, 4920, 5130],+ errors: [120, 140, 160, 170, 180, 176, 168],+}++const TOOL_DAILY: ToolDailySeries = {+ labels: DAYS,+ tools: [+ { tool: 'exec', data: [720, 760, 800, 740, 820, 880, 910] },+ { tool: 'execute-sql', data: [210, 230, 250, 240, 260, 280, 300] },+ { tool: 'read-data-schema', data: [110, 120, 95, 130, 140, 150, 120] },+ { tool: 'query-trends', data: [60, 80, 70, 90, 100, 80, 110] },+ ],+}++const TOOL_ROWS: ToolRow[] = [+ { tool: 'cohort-create', total_calls: 95, errors: 6, error_rate_pct: 28, p95_duration_ms: 1620 },+ { tool: 'execute-sql', total_calls: 1480, errors: 144, error_rate_pct: 13, p95_duration_ms: 3525 },+ { tool: 'exec', total_calls: 5200, errors: 208, error_rate_pct: 9.3, p95_duration_ms: 2290 },+ { tool: 'insight-create', total_calls: 410, errors: 8, error_rate_pct: 2, p95_duration_ms: 727 },+ { tool: 'query-trends', total_calls: 540, errors: 5, error_rate_pct: 1, p95_duration_ms: 2122 },+ { tool: 'read-data-schema', total_calls: 760, errors: 3, error_rate_pct: 0.4, p95_duration_ms: 1298 },+]++const HARNESS_ROWS: HarnessRow[] = [+ { category: 'Claude Code', total_calls: 6200, errors: 240, error_rate_pct: 3.9, sessions: 820, raw_clients: [] },+ { category: 'Cursor', total_calls: 2100, errors: 96, error_rate_pct: 4.6, sessions: 410, raw_clients: [] },+ { category: 'OpenAI Codex', total_calls: 980, errors: 71, error_rate_pct: 7.2, sessions: 180, raw_clients: [] },+ { category: 'Claude.ai', total_calls: 760, errors: 22, error_rate_pct: 2.9, sessions: 240, raw_clients: [] },+ { category: 'VS Code', total_calls: 540, errors: 12, error_rate_pct: 2.2, sessions: 120, raw_clients: [] },+]++const NOTABLE_SESSIONS: NotableSession[] = [+ {+ rule: 'worst_error_rate',+ label: 'Worst error rate at high volume',+ session: {+ session_id: '0193f2a1aaaabbbbcccc000000000001',+ tool_calls: 42,+ errors: 18,+ error_rate_pct: 42.9,+ duration_seconds: 610,+ distinct_tools: 7,+ last_seen: '',+ },+ },+ {+ rule: 'all_fail',+ label: 'Every call failed — likely auth scope',+ session: {+ session_id: '0193f2a1aaaabbbbcccc000000000002',+ tool_calls: 6,+ errors: 6,+ error_rate_pct: 100,+ duration_seconds: 95,+ distinct_tools: 2,+ last_seen: '',+ },+ },+ {+ rule: 'exemplar',+ label: 'Exemplar — concise success',+ session: {+ session_id: '0193f2a1aaaabbbbcccc000000000003',+ tool_calls: 31,+ errors: 0,+ error_rate_pct: 0,+ duration_seconds: 240,+ distinct_tools: 11,+ last_seen: '',+ },+ },+]++function metric(value: number, previousValue: number, sparkline: number[], goodDirection: 'up' | 'down'): KPIMetric {+ return {+ value,+ previousValue,+ deltaPct: previousValue ? ((value - previousValue) / previousValue) * 100 : null,+ sparkline,+ goodDirection,+ }+}++const KPIS: KPIData = {+ sessions: metric(2480, 2210, [320, 340, 355, 372, 360, 388, 401], 'up'),+ toolCalls: metric(31420, 27800, [4100, 4300, 4500, 4720, 4600, 4900, 5100], 'up'),+ errorRatePct: metric(3.6, 4.1, [4.2, 3.9, 3.5, 3.3, 3.7, 3.4, 3.2], 'down'),+ p95LatencyMs: metric(2240, 2380, [1900, 2050, 2100, 2080, 2200, 2150, 2240], 'down'),+}++const meta: Meta = {+ title: 'Scenes-App/MCP Analytics/Dashboard Cards',+ parameters: { layout: 'padded' },+ decorators: [+ (Story) => (+ <div data-quill>+ <Story />+ </div>+ ),+ ],+}+export default meta++type Story = StoryObj++function withTheme(render: (theme: ChartTheme) => JSX.Element): () => JSX.Element {+ // Charts size themselves from their container via ResizeObserver, so the wrapper needs a+ // definite width (not just max-width) — otherwise the card collapses in the shrink-to-fit+ // snapshot runtime. Mirrors quill's own `Stage` story helper.+ return () => <div className="w-[680px]">{render(buildTheme())}</div>+}++export const KeyMetrics: Story = {+ render: () => (+ <div className="w-[960px]">+ <KpiTiles+ kpis={KPIS}+ intentClusterCount={metric(6, 0, [], 'up')}+ kpisLoading={false}+ theme={buildTheme()}+ />+ </div>+ ),+}++export const DailyCallsAndErrors: Story = {+ render: withTheme((theme) => <ActivityChart daily={DAILY_ACTIVITY} loading={false} theme={theme} timezone="UTC" />),+}++export const ShareByHarness: Story = {+ render: withTheme((theme) => <HarnessDonut rows={HARNESS_ROWS} loading={false} theme={theme} />),+}++export const ErrorRateByTool: Story = {+ render: withTheme((theme) => <ToolErrorRateChart rows={TOOL_ROWS} loading={false} theme={theme} />),+}++export const DailyToolBreakdown: Story = {+ render: withTheme((theme) => <ToolUsageChart data={TOOL_DAILY} loading={false} theme={theme} timezone="UTC" />),+}++export const FlaggedSessions: Story = {+ render: () => (+ <div className="w-[680px]">+ <NotableSessionsTable sessions={NOTABLE_SESSIONS} loading={false} />+ </div>+ ),+}diff --git a/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx b/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsxnew file mode 100644index 000000000000..d8f24d95fc71--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx@@ -0,0 +1,149 @@+import { useCallback, useMemo } from 'react'++import { LemonSkeleton } from '@posthog/lemon-ui'+import {+ type ChartTheme,+ PieChart,+ type PieChartConfig,+ type Series,+ type TooltipContext,+ useRadialLayout,+} from '@posthog/quill-charts'++import { formatPercentage } from 'lib/utils'++import { type HarnessRow } from '../mcpDashboardOverviewLogic'+import { Card } from './Card'+import { ChartTooltip } from './ChartTooltip'+import { formatNumber } from './formatters'+import { HARNESS_LOGOS, HarnessPill, harnessSliceColor } from './harness'++const HARNESS_DONUT_CONFIG: PieChartConfig = {+ innerRadiusRatio: 0.6,+ // Built-in text labels are off — HarnessSliceLabels draws logo pills instead.+ showLabelOnSlice: false,+ showValueOnSlice: false,+}++// Slices smaller than this don't get a logo overlay — it wouldn't fit on the arc.+const MIN_LABELLED_SLICE_FRACTION = 0.05++// Rendered as a PieChart child so it can read the slice geometry from the radial layout context.+function HarnessSliceLabels(): JSX.Element | null {+ const { layout } = useRadialLayout()+ const midRadius = layout.innerRadius + (layout.outerRadius - layout.innerRadius) / 2+ return (+ <>+ {layout.slices.map((slice) => {+ if (slice.fraction < MIN_LABELLED_SLICE_FRACTION) {+ return null+ }+ const x = layout.cx + Math.sin(slice.centroidAngle) * midRadius+ const y = layout.cy - Math.cos(slice.centroidAngle) * midRadius+ const category = slice.series.label+ const logo = HARNESS_LOGOS[category]+ return (+ <div+ key={slice.series.key}+ className="pointer-events-none absolute"+ style={{ left: x, top: y, transform: 'translate(-50%, -50%)' }}+ >+ {logo ? (+ <img+ src={logo.src}+ alt={logo.alt}+ title={category}+ className="h-7 w-7 object-contain"+ style={{ filter: 'drop-shadow(0 1px 2px rgba(0, 0, 0, 0.45))' }}+ />+ ) : (+ <HarnessPill category={category} />+ )}+ </div>+ )+ })}+ </>+ )+}++export function HarnessDonut({+ rows,+ loading,+ theme,+}: {+ rows: HarnessRow[]+ loading: boolean+ theme: ChartTheme+}): JSX.Element {+ const totalCalls = rows.reduce((acc, r) => acc + r.total_calls, 0)+ const series = useMemo<Series<HarnessRow>[]>(+ () =>+ rows.map((r, i) => ({+ key: r.category,+ label: r.category,+ color: harnessSliceColor(theme, r.category, i),+ data: [r.total_calls],+ meta: r,+ })),+ [rows, theme]+ )+ const renderTooltip = useCallback((ctx: TooltipContext<HarnessRow>): JSX.Element | null => {+ const entry = ctx.seriesData[0]+ const row = entry?.series.meta+ if (!row) {+ return null+ }+ const share = entry.fraction !== undefined ? entry.fraction * 100 : 0+ return (+ <ChartTooltip+ title={row.category}+ rows={[+ ['Calls', String(row.total_calls)],+ ['Share', formatPercentage(share, { compact: true })],+ ['Sessions', String(row.sessions)],+ ['Error rate', formatPercentage(row.error_rate_pct, { compact: true })],+ ]}+ />+ )+ }, [])++ if (loading && rows.length === 0) {+ return (+ <Card className="flex flex-1 flex-col" title="Share of calls by harness">+ <div className="flex min-h-[300px] flex-1 items-center justify-center">+ <LemonSkeleton className="h-[180px] w-[180px] rounded-full" />+ </div>+ </Card>+ )+ }+ if (rows.length === 0) {+ return (+ <Card className="flex flex-1 flex-col" title="Share of calls by harness">+ <div className="flex min-h-[300px] flex-1 items-center justify-center text-[12px] text-secondary">+ No harness data yet.+ </div>+ </Card>+ )+ }++ return (+ <Card className="flex flex-1 flex-col" title="Share of calls by harness">+ <div className="flex min-h-[300px] flex-1 flex-col">+ <PieChart<HarnessRow>+ series={series}+ theme={theme}+ config={HARNESS_DONUT_CONFIG}+ tooltip={renderTooltip}+ centerLabel={+ <div className="text-center">+ <div className="text-3xl font-semibold text-primary">{formatNumber(totalCalls)}</div>+ <div className="text-xs text-secondary">calls</div>+ </div>+ }+ >+ <HarnessSliceLabels />+ </PieChart>+ </div>+ </Card>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsxnew file mode 100644index 000000000000..8215b935cf4b--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx@@ -0,0 +1,116 @@+import { LemonSkeleton, Link } from '@posthog/lemon-ui'+import { type ChartTheme, MetricCard } from '@posthog/quill-charts'+import { Card, CardContent } from '@posthog/quill-primitives'++import { formatPercentage } from 'lib/utils'+import { urls } from 'scenes/urls'++import { type KPIData, KPIMetric } from '../mcpDashboardOverviewLogic'+import { formatMs, formatNumber } from './formatters'++interface TileSpec {+ label: string+ metric: KPIMetric+ href: string+ format: (n: number) => string+ color: string+ loading: boolean+}++function KPITile({ tile, theme }: { tile: TileSpec; theme: ChartTheme }): JSX.Element {+ const { metric } = tile+ const hasSparkline = metric.sparkline.length > 0+ const hasComparison = metric.deltaPct !== null++ return (+ <Link to={tile.href} subtle className="group/tile flex h-full">+ <Card size="sm" className="flex-1 transition-transform group-hover/tile:-translate-y-0.5">+ {tile.loading ? (+ <CardContent className="flex flex-col gap-2">+ <LemonSkeleton className="h-3 w-16" />+ <LemonSkeleton className="h-7 w-20" />+ </CardContent>+ ) : (+ <CardContent>+ <MetricCard+ className="text-primary"+ title={tile.label}+ value={metric.value}+ data={hasSparkline ? metric.sparkline : undefined}+ theme={theme}+ color={tile.color}+ goodDirection={metric.goodDirection}+ formatValue={tile.format}+ subtitle={hasComparison ? `vs. ${tile.format(metric.previousValue)} prior` : undefined}+ sparklineHeight={50}+ sparklineClassName="mt-3 -mx-3 -mb-3"+ />+ </CardContent>+ )}+ </Card>+ </Link>+ )+}++export function KpiTiles({+ kpis,+ intentClusterCount,+ kpisLoading,+ theme,+}: {+ kpis: KPIData+ intentClusterCount: KPIMetric+ kpisLoading: boolean+ theme: ChartTheme+}): JSX.Element {+ const tiles: TileSpec[] = [+ {+ label: 'Sessions',+ metric: kpis.sessions,+ href: urls.mcpAnalyticsSessions(),+ format: formatNumber,+ color: theme.colors[0],+ loading: kpisLoading,+ },+ {+ label: 'Tool calls',+ metric: kpis.toolCalls,+ href: urls.mcpAnalyticsToolQuality(),+ format: formatNumber,+ color: theme.colors[0],+ loading: kpisLoading,+ },+ {+ label: 'Error rate',+ metric: kpis.errorRatePct,+ href: urls.mcpAnalyticsSessions(),+ format: (n) => formatPercentage(n, { compact: true }),+ color: theme.colors[4],+ loading: kpisLoading,+ },+ {+ label: 'p95 latency',+ metric: kpis.p95LatencyMs,+ href: urls.mcpAnalyticsToolQuality(),+ format: formatMs,+ color: theme.colors[0],+ loading: kpisLoading,+ },+ {+ label: 'Intent clusters',+ metric: intentClusterCount,+ href: urls.mcpAnalyticsIntentClustering(),+ format: formatNumber,+ color: theme.colors[6],+ loading: false,+ },+ ]++ return (+ <div className="grid grid-cols-2 gap-3 md:grid-cols-5">+ {tiles.map((tile) => (+ <KPITile key={tile.label} tile={tile} theme={theme} />+ ))}+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx b/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsxnew file mode 100644index 000000000000..a645f140fda6--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx@@ -0,0 +1,125 @@+import { LemonSkeleton, Link } from '@posthog/lemon-ui'+import {+ Badge,+ Card,+ CardFooter,+ CardHeader,+ CardTitle,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@posthog/quill-primitives'++import { formatPercentage } from 'lib/utils'+import { urls } from 'scenes/urls'++import { type NotableSession } from '../mcpDashboardOverviewLogic'+import { formatDuration, truncateSessionId } from './formatters'++const DESTRUCTIVE_ERROR_PCT = 5+const WARNING_ERROR_PCT = 1++function statusVariant(errorRatePct: number): 'destructive' | 'warning' | 'success' {+ if (errorRatePct > DESTRUCTIVE_ERROR_PCT) {+ return 'destructive'+ }+ if (errorRatePct >= WARNING_ERROR_PCT) {+ return 'warning'+ }+ return 'success'+}++function StatusPill({ errorRatePct }: { errorRatePct: number }): JSX.Element {+ if (errorRatePct === 0) {+ return <Badge variant="success">Healthy</Badge>+ }+ return (+ <Badge variant={statusVariant(errorRatePct)}>{formatPercentage(errorRatePct, { compact: true })} errors</Badge>+ )+}++function SessionRows({ sessions, loading }: { sessions: NotableSession[]; loading: boolean }): JSX.Element {+ if (loading && sessions.length === 0) {+ return (+ <TableRow>+ <TableCell colSpan={5}>+ <div className="space-y-2 py-1">+ {Array.from({ length: 4 }).map((_, i) => (+ <LemonSkeleton key={i} className="h-3.5 w-full" />+ ))}+ </div>+ </TableCell>+ </TableRow>+ )+ }+ if (sessions.length === 0) {+ return (+ <TableRow>+ <TableCell colSpan={5} align="center" className="py-6 text-secondary">+ No notable sessions in the last 30 days.+ </TableCell>+ </TableRow>+ )+ }+ return (+ <>+ {sessions.map((entry) => (+ <TableRow key={entry.session.session_id}>+ <TableCell className="whitespace-nowrap">+ <Link to={urls.mcpAnalyticsSessions()} className="font-mono" title={entry.session.session_id}>+ {truncateSessionId(entry.session.session_id)}+ </Link>+ </TableCell>+ <TableCell align="right">{entry.session.tool_calls}</TableCell>+ <TableCell align="right">{formatDuration(entry.session.duration_seconds)}</TableCell>+ <TableCell>+ <StatusPill errorRatePct={entry.session.error_rate_pct} />+ </TableCell>+ <TableCell expand className="text-primary" title={entry.label}>+ {entry.label}+ </TableCell>+ </TableRow>+ ))}+ </>+ )+}++export function NotableSessionsTable({+ sessions,+ loading,+}: {+ sessions: NotableSession[]+ loading: boolean+}): JSX.Element {+ return (+ <Card size="sm" className="self-start gap-0">+ <CardHeader className="border-b border-border pb-3">+ <CardTitle>Sessions flagged for review</CardTitle>+ </CardHeader>+ <Table fullWidth>+ <TableHeader>+ <TableRow>+ <TableHead>Session</TableHead>+ <TableHead align="right">Calls</TableHead>+ <TableHead align="right">Duration</TableHead>+ <TableHead>Status</TableHead>+ <TableHead expand>Why notable</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ <SessionRows sessions={sessions} loading={loading} />+ </TableBody>+ </Table>+ {sessions.length > 0 && (+ <CardFooter className="justify-end">+ <Link to={urls.mcpAnalyticsSessions()} className="text-[10px]">+ Open all flagged sessions in Sessions tab ↗+ </Link>+ </CardFooter>+ )}+ </Card>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx b/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsxnew file mode 100644index 000000000000..93cfa00460fb--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx@@ -0,0 +1,105 @@+import { useCallback, useMemo } from 'react'++import { LemonSkeleton } from '@posthog/lemon-ui'+import {+ BarChart,+ type BarChartConfig,+ type ChartTheme,+ type Series,+ type TooltipContext,+ ValueLabels,+} from '@posthog/quill-charts'++import { formatPercentage } from 'lib/utils'++import { type ToolRow } from '../mcpDashboardOverviewLogic'+import { Card, CardState } from './Card'+import { ChartTooltip } from './ChartTooltip'++// Upper bound for the error-rate track: a bit above the worst tool's rate, rounded up to a clean 10 —+// so the track ends just past the data (a 30% max gives a 50% track) rather than an empty-looking 100%.+function niceErrorAxisMax(maxRate: number): number {+ return Math.min(100, Math.max(10, Math.ceil((maxRate * 1.4) / 10) * 10))+}++export function ToolErrorRateChart({+ rows,+ loading,+ theme,+}: {+ rows: ToolRow[]+ loading: boolean+ theme: ChartTheme+}): JSX.Element {+ const sorted = useMemo(() => [...rows].sort((a, b) => b.error_rate_pct - a.error_rate_pct), [rows])+ const labels = useMemo(() => sorted.map((r) => r.tool), [sorted])+ const series = useMemo<Series[]>(+ () => [+ {+ key: 'errorRate',+ label: 'Error rate',+ color: theme.colors[4],+ data: sorted.map((r) => r.error_rate_pct),+ },+ ],+ [sorted, theme]+ )+ const config = useMemo<BarChartConfig>(() => {+ const axisMax = niceErrorAxisMax(sorted[0]?.error_rate_pct ?? 0)+ return {+ axisOrientation: 'horizontal',+ barLayout: 'grouped',+ showGrid: false,+ showAxisLines: false,+ tooltip: { placement: 'cursor' },+ margins: { top: 4, right: 20, bottom: 22 },+ bars: { cornerRadius: 3, minBandSize: 30, track: { hover: false }, valueDomain: [0, axisMax] },+ }+ }, [sorted])+ const byTool = useMemo(() => new Map(sorted.map((r) => [r.tool, r])), [sorted])+ const renderTooltip = useCallback(+ (ctx: TooltipContext): JSX.Element | null => {+ const row = byTool.get(ctx.label)+ if (!row) {+ return null+ }+ return (+ <ChartTooltip+ title={row.tool}+ rows={[+ ['Error rate', formatPercentage(row.error_rate_pct, { compact: true })],+ ['Errors', String(row.errors)],+ ['Calls', String(row.total_calls)],+ ]}+ />+ )+ },+ [byTool]+ )++ return (+ <Card title="Tools with the highest error rate">+ <CardState+ loading={loading}+ isEmpty={rows.length === 0}+ skeleton={+ <div className="space-y-2 py-3">+ {Array.from({ length: 5 }).map((_, i) => (+ <LemonSkeleton key={i} className="h-7 w-full" />+ ))}+ </div>+ }+ empty={<div className="py-6 text-center text-[12px] text-secondary">No tool calls yet.</div>}+ >+ <div className="flex flex-col">+ <BarChart series={series} labels={labels} config={config} theme={theme} tooltip={renderTooltip}>+ <ValueLabels+ valueFormatter={(value) => formatPercentage(value, { compact: true })}+ offset={6}+ />+ </BarChart>+ </div>+ </CardState>+ </Card>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx b/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsxnew file mode 100644index 000000000000..b390a27c5aab--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx@@ -0,0 +1,56 @@+import { useMemo } from 'react'++import { LemonSkeleton } from '@posthog/lemon-ui'+import { type ChartTheme, type Series, TimeSeriesBarChart, type TimeSeriesBarChartConfig } from '@posthog/quill-charts'++import { type ToolDailySeries } from '../mcpDashboardOverviewLogic'+import { Card, CardState } from './Card'++export function ToolUsageChart({+ data,+ loading,+ theme,+ timezone,+}: {+ data: ToolDailySeries+ loading: boolean+ theme: ChartTheme+ timezone: string+}): JSX.Element {+ const series = useMemo<Series[]>(+ () =>+ data.tools.map((t, i) => ({+ key: t.tool,+ label: t.tool,+ color: theme.colors[i % theme.colors.length],+ data: t.data,+ })),+ [data, theme]+ )+ const config = useMemo<TimeSeriesBarChartConfig>(+ () => ({+ barLayout: 'stacked',+ barCornerRadius: 2,+ yAxis: { showGrid: false },+ showAxisLines: true,+ xAxis: { interval: 'day', timezone },+ tooltip: { placement: 'cursor' },+ }),+ [timezone]+ )++ return (+ <Card title="Daily breakdown of tool calls">+ <CardState+ loading={loading}+ isEmpty={data.labels.length === 0}+ skeleton={<LemonSkeleton className="h-[260px] w-full" />}+ empty={<div className="py-6 text-center text-[12px] text-secondary">No tool calls yet.</div>}+ >+ <div className="flex h-[260px] flex-col">+ <TimeSeriesBarChart series={series} labels={data.labels} config={config} theme={theme} />+ </div>+ </CardState>+ </Card>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/formatters.ts b/products/mcp_analytics/frontend/dashboard/formatters.tsnew file mode 100644index 000000000000..8497ac9b7242--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/formatters.ts@@ -0,0 +1,37 @@+import { humanFriendlyDuration, humanFriendlyLargeNumber } from 'lib/utils'++const EMPTY = '—'++export function formatNumber(n: number): string {+ if (!isFinite(n)) {+ return EMPTY+ }+ return humanFriendlyLargeNumber(n)+}++export function formatMs(n: number): string {+ if (!isFinite(n) || n === 0) {+ return EMPTY+ }+ if (n < 1000) {+ return `${Math.round(n)}ms`+ }+ return humanFriendlyDuration(n / 1000, { secondsPrecision: 1 })+}++export function formatDuration(seconds: number): string {+ if (!seconds || !isFinite(seconds)) {+ return EMPTY+ }+ if (seconds < 60) {+ return `${seconds}s`+ }+ return humanFriendlyDuration(seconds, { secondsPrecision: 0 })+}++export function truncateSessionId(id: string): string {+ if (id.length <= 12) {+ return id+ }+ return `${id.slice(0, 4)}…${id.slice(-4)}`+}diff --git a/products/mcp_analytics/frontend/dashboard/harness.tsx b/products/mcp_analytics/frontend/dashboard/harness.tsxnew file mode 100644index 000000000000..9824ab629d8f--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/harness.tsx@@ -0,0 +1,51 @@+import { type ChartTheme } from '@posthog/quill-charts'++import claudeLogo from '../harness-logos/claude.svg'+import cursorLogo from '../harness-logos/cursor.svg'+import openaiLogo from '../harness-logos/openai.svg'+import vscodeLogo from '../harness-logos/vscode.svg'++interface HarnessLogo {+ src: string+ alt: string+}++export const HARNESS_LOGOS: Record<string, HarnessLogo> = {+ 'Claude Code': { src: claudeLogo, alt: 'Claude Code logo' },+ 'Claude.ai': { src: claudeLogo, alt: 'Claude.ai logo' },+ 'OpenAI Codex': { src: openaiLogo, alt: 'OpenAI Codex logo' },+ Cursor: { src: cursorLogo, alt: 'Cursor logo' },+ 'VS Code': { src: vscodeLogo, alt: 'VS Code logo' },+}++// Per-harness slice color (index into the data-viz palette), chosen so the logo drawn on top keeps+// enough contrast against its slice.+const HARNESS_SLICE_COLOR_INDEX: Record<string, number> = {+ 'Claude Code': 0,+ 'Claude.ai': 2,+ 'OpenAI Codex': 1,+ Cursor: 12,+ 'VS Code': 11,+}++export function harnessSliceColor(theme: ChartTheme, category: string, fallbackIndex: number): string {+ const index = HARNESS_SLICE_COLOR_INDEX[category] ?? fallbackIndex+ return theme.colors[index % theme.colors.length]+}++export function HarnessPill({ category, title }: { category: string; title?: string }): JSX.Element {+ const logo = HARNESS_LOGOS[category]+ return (+ <span+ className="inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary bg-surface-primary px-2 py-0.5 text-xs"+ title={title}+ >+ {logo ? (+ <img src={logo.src} alt="" className="h-3.5 w-3.5 shrink-0 object-contain" />+ ) : (+ <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-secondary" aria-hidden />+ )}+ <span className="truncate">{category}</span>+ </span>+ )+}diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.tsnew file mode 100644index 000000000000..1f967bc538bb--- /dev/null+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts@@ -0,0 +1,220 @@+import {+ aggregateHarnessRows,+ type BucketRow,+ buildKPIs,+ buildToolDailySeries,+ categorizeHarness,+ deltaPct,+ type HarnessRawRow,+ pickNotableSessions,+ type SessionRow,+ type ToolDailyRow,+} from './mcpDashboardOverviewLogic'++function session(overrides: Partial<SessionRow> & { session_id: string }): SessionRow {+ return {+ tool_calls: 0,+ errors: 0,+ error_rate_pct: 0,+ duration_seconds: 0,+ distinct_tools: 0,+ last_seen: '',+ ...overrides,+ }+}++describe('mcpDashboardOverviewLogic helpers', () => {+ describe('categorizeHarness', () => {+ it.each([+ ['claude-code/1.0.0', 'Claude Code'],+ ['claude-ai', 'Claude.ai'],+ ['anthropic/claudeai', 'Claude.ai'],+ ['cursor/0.42', 'Cursor'],+ ['codex-cli', 'OpenAI Codex'],+ ['visual studio code', 'VS Code'],+ ['something-nobody-knows', 'Other'],+ ['', 'Other'],+ ])('maps %s -> %s', (raw, expected) => {+ expect(categorizeHarness(raw)).toBe(expected)+ })++ it('strips the "(via mcp-remote …)" suffix before matching', () => {+ expect(categorizeHarness('claude-code (via mcp-remote 1.2.3)')).toBe('Claude Code')+ })+ })++ describe('deltaPct', () => {+ it.each([+ [150, 100, 50],+ [50, 100, -50],+ [0, 0, 0],+ [100, 0, null],+ ])('deltaPct(%s, %s) = %s', (current, previous, expected) => {+ expect(deltaPct(current, previous)).toBe(expected)+ })+ })++ describe('aggregateHarnessRows', () => {+ it('folds raw clients into categories, sums counts, and sorts by volume', () => {+ const raw: HarnessRawRow[] = [+ { client: 'claude-code/1.0', total_calls: 100, errors: 10, sessions: 5 },+ { client: 'claude-code/2.0', total_calls: 50, errors: 5, sessions: 3 },+ { client: 'cursor/0.4', total_calls: 40, errors: 0, sessions: 2 },+ ]+ const result = aggregateHarnessRows(raw)+ expect(result).toHaveLength(2)+ expect(result[0]).toEqual({+ category: 'Claude Code',+ total_calls: 150,+ errors: 15,+ error_rate_pct: 10,+ sessions: 8,+ raw_clients: ['claude-code/1.0', 'claude-code/2.0'],+ })+ expect(result[1]).toMatchObject({ category: 'Cursor', total_calls: 40, error_rate_pct: 0 })+ })+ })++ describe('buildToolDailySeries', () => {+ it('pivots flat rows into sorted day labels and per-tool series ordered by volume', () => {+ const rows: ToolDailyRow[] = [+ { day: '2024-01-02', tool: 'a', calls: 5 },+ { day: '2024-01-01', tool: 'a', calls: 3 },+ { day: '2024-01-01', tool: 'b', calls: 10 },+ ]+ expect(buildToolDailySeries(rows)).toEqual({+ labels: ['2024-01-01', '2024-01-02'],+ tools: [+ { tool: 'b', data: [10, 0] },+ { tool: 'a', data: [3, 5] },+ ],+ })+ })++ it('keeps the top 8 tools and folds the rest into a single "Other" series', () => {+ // 10 tools on one day, each with a distinct volume (tool-0 busiest … tool-9 quietest).+ const rows: ToolDailyRow[] = Array.from({ length: 10 }, (_, i) => ({+ day: '2024-01-01',+ tool: `tool-${i}`,+ calls: 100 - i,+ }))+ const { tools } = buildToolDailySeries(rows)+ expect(tools).toHaveLength(9) // 8 named + Other+ expect(tools.slice(0, 8).map((t) => t.tool)).toEqual([+ 'tool-0',+ 'tool-1',+ 'tool-2',+ 'tool-3',+ 'tool-4',+ 'tool-5',+ 'tool-6',+ 'tool-7',+ ])+ // Other = tool-8 (92) + tool-9 (91)+ expect(tools[8]).toEqual({ tool: 'Other', data: [183] })+ })+ })++ describe('buildKPIs', () => {+ it('splits current vs prior buckets and computes values, deltas, and sparklines', () => {+ const rows: BucketRow[] = [+ { bucket: '2024-01-09', sessions: 20, tool_calls: 200, errors: 15, p95: 300, in_current: true },+ { bucket: '2024-01-08', sessions: 10, tool_calls: 100, errors: 5, p95: 200, in_current: true },+ { bucket: '2024-01-01', sessions: 5, tool_calls: 50, errors: 5, p95: 150, in_current: false },+ ]+ const kpis = buildKPIs(rows)++ expect(kpis.sessions).toEqual({+ value: 30,+ previousValue: 5,+ deltaPct: 500,+ sparkline: [10, 20], // current sorted by bucket+ goodDirection: 'up',+ })+ expect(kpis.toolCalls).toMatchObject({+ value: 300,+ previousValue: 50,+ deltaPct: 500,+ sparkline: [100, 200],+ })+ expect(kpis.p95LatencyMs).toMatchObject({+ value: 300,+ previousValue: 150,+ deltaPct: 100,+ goodDirection: 'down',+ })+ expect(kpis.errorRatePct.value).toBeCloseTo(6.667, 2)+ expect(kpis.errorRatePct.previousValue).toBeCloseTo(10, 5)+ expect(kpis.errorRatePct.goodDirection).toBe('down')+ })++ it('returns null deltas when there is no prior-period data', () => {+ const rows: BucketRow[] = [+ { bucket: '2024-01-08', sessions: 10, tool_calls: 100, errors: 0, p95: 200, in_current: true },+ ]+ expect(buildKPIs(rows).sessions.deltaPct).toBeNull()+ })+ })++ describe('pickNotableSessions', () => {+ it('returns nothing for an empty set', () => {+ expect(pickNotableSessions([])).toEqual([])+ })++ it('picks one session per rule, then tops up with the busiest, capped and deduped', () => {+ const rows: SessionRow[] = [+ session({+ session_id: 'A',+ tool_calls: 20,+ errors: 10,+ error_rate_pct: 50,+ duration_seconds: 100,+ distinct_tools: 2,+ }),+ session({+ session_id: 'B',+ tool_calls: 5,+ errors: 5,+ error_rate_pct: 100,+ duration_seconds: 30,+ distinct_tools: 1,+ }),+ session({+ session_id: 'C',+ tool_calls: 8,+ errors: 1,+ error_rate_pct: 12,+ duration_seconds: 40,+ distinct_tools: 9,+ }),+ session({+ session_id: 'D',+ tool_calls: 15,+ errors: 0,+ error_rate_pct: 0,+ duration_seconds: 5,+ distinct_tools: 3,+ }),+ session({+ session_id: 'E',+ tool_calls: 12,+ errors: 1,+ error_rate_pct: 8,+ duration_seconds: 60,+ distinct_tools: 2,+ }),+ ]+ const picked = pickNotableSessions(rows)+ expect(picked.map((p) => ({ id: p.session.session_id, rule: p.rule }))).toEqual([+ { id: 'A', rule: 'worst_error_rate' },+ { id: 'B', rule: 'all_fail' },+ { id: 'C', rule: 'most_exploratory' },+ { id: 'D', rule: 'exemplar' },+ { id: 'E', rule: 'high_activity' },+ ])+ // never more than the cap, never the same session twice+ expect(picked).toHaveLength(5)+ expect(new Set(picked.map((p) => p.session.session_id)).size).toBe(5)+ })+ })+})diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.tsindex ca9e16c57ccb..280cd87391da 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts@@ -8,7 +8,10 @@ import { mcpClusteringLogic } from './clustering/mcpClusteringLogic'import type { MCPIntentClusterApi } from './generated/api.schemas'import type { mcpDashboardOverviewLogicType } from './mcpDashboardOverviewLogicType'+// KPI tiles compare this week against the prior week.const LOOKBACK_DAYS = 7+// Breakdowns and trends (activity, tools, harnesses, notable sessions) use a longer 30-day window.+const BREAKDOWN_DAYS = 30const KPI_QUERY = hogql`SELECT@@ -40,7 +43,7 @@ SELECTmax(timestamp) AS last_seenFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS))} DAY+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAYAND properties.$mcp_session_id IS NOT NULLAND properties.$mcp_session_id != ''AND properties.$mcp_tool_name IS NOT NULL@@ -62,7 +65,7 @@ SELECTround(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_duration_msFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS))} DAY+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAYAND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''GROUP BY tool@@ -78,13 +81,46 @@ SELECTcountDistinctIf(toString(properties.$mcp_session_id), toString(properties.$mcp_session_id) != '') AS sessionsFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS))} DAY+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAYAND properties.$mcp_client_name IS NOT NULLAND properties.$mcp_client_name != ''GROUP BY client+ORDER BY total_calls DESC+LIMIT 200+`++// Daily success/error split powering the activity time-series bar chart.+const ACTIVITY_QUERY = hogql`+SELECT+ toDate(timestamp) AS day,+ countIf(NOT toBool(properties.$mcp_is_error)) AS successes,+ countIf(toBool(properties.$mcp_is_error)) AS errors+FROM events+WHERE event = 'mcp_tool_call'+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAY+ AND properties.$mcp_tool_name IS NOT NULL+ AND properties.$mcp_tool_name != ''+GROUP BY day+ORDER BY day`-interface BucketRow {+// Daily call counts per tool, powering the tool-usage stacked bar (one segment per tool).+const TOOL_DAILY_QUERY = hogql`+SELECT+ toDate(timestamp) AS day,+ toString(properties.$mcp_tool_name) AS tool,+ count() AS calls+FROM events+WHERE event = 'mcp_tool_call'+ AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAY+ AND properties.$mcp_tool_name IS NOT NULL+ AND properties.$mcp_tool_name != ''+GROUP BY day, tool+ORDER BY day+LIMIT 10000+`++export interface BucketRow {bucket: stringsessions: numbertool_calls: number@@ -123,6 +159,29 @@ export interface HarnessRawRow {sessions: number}+export interface ActivityRow {+ day: string+ successes: number+ errors: number+}++export interface DailyActivity {+ labels: string[]+ successes: number[]+ errors: number[]+}++export interface ToolDailyRow {+ day: string+ tool: string+ calls: number+}++export interface ToolDailySeries {+ labels: string[]+ tools: { tool: string; data: number[] }[]+}+export interface HarnessRow {category: stringtotal_calls: number@@ -142,7 +201,10 @@ export interface SessionRow {last_seen: string}-export type NotableRule = 'worst_error_rate' | 'all_fail' | 'most_exploratory' | 'exemplar'+export type NotableRule = 'worst_error_rate' | 'all_fail' | 'most_exploratory' | 'exemplar' | 'high_activity'++// Fill the table out to this many rows: the rule-based picks first, then the busiest remaining sessions.+const NOTABLE_SESSION_TARGET = 8export interface NotableSession {rule: NotableRule@@ -203,7 +265,7 @@ export function categorizeHarness(raw: string): string {return 'Other'}-function aggregateHarnessRows(raw: HarnessRawRow[]): HarnessRow[] {+export function aggregateHarnessRows(raw: HarnessRawRow[]): HarnessRow[] {const byCategory = new Map<string, HarnessRow>()for (const row of raw) {const category = categorizeHarness(row.client)@@ -232,7 +294,36 @@ function aggregateHarnessRows(raw: HarnessRawRow[]): HarnessRow[] {return result}-function deltaPct(current: number, previous: number): number | null {+// Keep the stacked bar legible: only the busiest tools get their own segment; the long tail is+// folded into a single "Other" series so the chart can't sprout dozens of repeating-colour bands.+const TOOL_SERIES_LIMIT = 8++// Pivot flat (day, tool, calls) rows into a label array + one data series per tool, tools ordered+// by total volume (biggest first) so the stack and legend read consistently.+export function buildToolDailySeries(rows: ToolDailyRow[]): ToolDailySeries {+ const days = [...new Set(rows.map((r) => r.day))].sort()+ const totalByTool = new Map<string, number>()+ const byToolDay = new Map<string, Map<string, number>>()+ for (const row of rows) {+ totalByTool.set(row.tool, (totalByTool.get(row.tool) ?? 0) + row.calls)+ let dayMap = byToolDay.get(row.tool)+ if (!dayMap) {+ dayMap = new Map<string, number>()+ byToolDay.set(row.tool, dayMap)+ }+ dayMap.set(row.day, (dayMap.get(row.day) ?? 0) + row.calls)+ }+ const seriesFor = (tool: string): number[] => days.map((day) => byToolDay.get(tool)!.get(day) ?? 0)+ const ranked = [...totalByTool.entries()].sort((a, b) => b[1] - a[1]).map(([tool]) => tool)+ const tools = ranked.slice(0, TOOL_SERIES_LIMIT).map((tool) => ({ tool, data: seriesFor(tool) }))+ const rest = ranked.slice(TOOL_SERIES_LIMIT)+ if (rest.length > 0) {+ tools.push({ tool: 'Other', data: days.map((_, i) => rest.reduce((sum, t) => sum + seriesFor(t)[i], 0)) })+ }+ return { labels: days, tools }+}++export function deltaPct(current: number, previous: number): number | null {if (previous === 0) {return current === 0 ? 0 : null}@@ -250,7 +341,7 @@ function parseRows(rawRows: unknown[][]): BucketRow[] {}))}-function buildKPIs(rows: BucketRow[]): KPIData {+export function buildKPIs(rows: BucketRow[]): KPIData {const current = rows.filter((r) => r.in_current).sort((a, b) => a.bucket.localeCompare(b.bucket))const previous = rows.filter((r) => !r.in_current)@@ -364,11 +455,49 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([},},],+ activityRows: [+ [] as ActivityRow[],+ {+ loadActivityRows: async (): Promise<ActivityRow[]> => {+ const response = await hogqlQuery(ACTIVITY_QUERY)+ const raw = (response?.results as unknown[][]) ?? []+ return raw.map((r) => ({+ day: String(r[0] ?? ''),+ successes: Number(r[1] ?? 0),+ errors: Number(r[2] ?? 0),+ }))+ },+ },+ ],+ toolDailyRows: [+ [] as ToolDailyRow[],+ {+ loadToolDailyRows: async (): Promise<ToolDailyRow[]> => {+ const response = await hogqlQuery(TOOL_DAILY_QUERY)+ const raw = (response?.results as unknown[][]) ?? []+ return raw.map((r) => ({+ day: String(r[0] ?? ''),+ tool: String(r[1] ?? ''),+ calls: Number(r[2] ?? 0),+ }))+ },+ },+ ],}),selectors({- topToolRows: [(s) => [s.toolRows], (toolRows: ToolRow[]): ToolRow[] => toolRows.slice(0, 5)],- toolRowsTotal: [(s) => [s.toolRows], (toolRows: ToolRow[]): number => toolRows.length],harnessRows: [(s) => [s.harnessRawRows], (raw: HarnessRawRow[]): HarnessRow[] => aggregateHarnessRows(raw)],+ dailyActivity: [+ (s) => [s.activityRows],+ (rows: ActivityRow[]): DailyActivity => ({+ labels: rows.map((r) => r.day),+ successes: rows.map((r) => r.successes),+ errors: rows.map((r) => r.errors),+ }),+ ],+ toolDailySeries: [+ (s) => [s.toolDailyRows],+ (rows: ToolDailyRow[]): ToolDailySeries => buildToolDailySeries(rows),+ ],notableSessions: [(s) => [s.sessionRows],(sessionRows: SessionRow[]): NotableSession[] => pickNotableSessions(sessionRows),@@ -389,6 +518,8 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([actions.loadToolRows()actions.loadSessionRows()actions.loadHarnessRows()+ actions.loadActivityRows()+ actions.loadToolDailyRows()}),])@@ -403,7 +534,7 @@ function median(values: number[]): number {// Pick at most one session per rule. Thresholds relax automatically when the// data is small so something demo-worthy always shows.-function pickNotableSessions(rows: SessionRow[]): NotableSession[] {+export function pickNotableSessions(rows: SessionRow[]): NotableSession[] {if (rows.length === 0) {return []}@@ -451,5 +582,15 @@ function pickNotableSessions(rows: SessionRow[]): NotableSession[] {)take('exemplar', 'Exemplar — concise success', [...exemplars].sort((a, b) => b.tool_calls - a.tool_calls)[0])+ // Top up to the target with the busiest sessions not already chosen, so the table reads as a+ // fuller list rather than a sparse handful.+ const byVolume = [...rows].sort((a, b) => b.tool_calls - a.tool_calls)+ for (const candidate of byVolume) {+ if (picked.length >= NOTABLE_SESSION_TARGET) {+ break+ }+ take('high_activity', 'High activity', candidate)+ }+return picked}diff --git a/products/mcp_analytics/package.json b/products/mcp_analytics/package.jsonindex 8441b3f587ac..00016e6751ff 100644--- a/products/mcp_analytics/package.json+++ b/products/mcp_analytics/package.json@@ -5,6 +5,7 @@},"dependencies": {"@posthog/quill-charts": "workspace:*",+ "@posthog/quill-primitives": "workspace:*","kea": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:"