: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): port pages to quill design system (#63411)
Sam Pennington3a6a9b329690
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3f456f4c3ad7..15bebdb2e788 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5439,7 +5439,7 @@ snapshots:scenes-app-mcp-analytics--dashboard--light:hash: v1.k794b7964.c64d5d43c4eaa79d3008e9dd40857d9bee879832e68a8f8e9464657ff670773f.yKxStICPwIMCMEnf_zQhK0BuXu5BIxaUKmgPYHAEzYoscenes-app-mcp-analytics--sessions--dark:- hash: v1.k794b7964.a033f7dca28cc0bfea783c71c6c2cbed6c58f87d705aa4772742c6f7136a437a.vFUlACgvfOrTJfC2Ogf7u7myI9SL_njtFgyBD88-TqE+ hash: v1.k794b7964.c316f0028a9cc9b6a8e2b85d95b5e5ab65548805d4069f001c5cbbbcfbac970c.u4rZzVUZRlEBb11eUbRTRsVFfH_5gb3qRI5BEuAN7qwscenes-app-mcp-analytics--sessions--light:hash: v1.k794b7964.497d9ae69307438f3ef9ebfc80bb948ffd70d285eda4192f6b2e21f1a66d3eba.XI5y0bJbIitncOcXS_6Gxcr4pgGCK1moA7JIAstwuL4scenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--dark:diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.pyindex 98d3358b36bf..2054b7ed2bbd 100644--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py@@ -10,9 +10,12 @@ 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+from posthog.models.scoping import team_scopefrom posthog.models.team.team import Teamfrom posthog.models.utils import uuid7+from products.mcp_analytics.backend.models import MCPSession+TOOL_NAMES = ["query_run","insight_get",@@ -24,6 +27,32 @@ TOOL_NAMES = ["error_tracking_issue_get",]+# Marks events as coming from the new MCP SDK — the tool detail page filters on this.+NEW_SDK_SOURCE = "posthog_mcp_analytics"++# $mcp_tool_category powers the dashboard "share of calls by category" and the tool quality scope filter.+TOOL_CATEGORIES = {+ "query_run": "Querying",+ "insight_get": "Product analytics",+ "dashboard_get": "Product analytics",+ "feature_flag_get": "Feature flags",+ "experiment_get": "Experiments",+ "person_get": "Persons",+ "session_recording_get": "Session replay",+ "error_tracking_issue_get": "Error tracking",+}++TOOL_DESCRIPTIONS = {+ "query_run": "Run a HogQL query against the project's events and return rows.",+ "insight_get": "Fetch a saved insight's definition and computed results.",+ "dashboard_get": "Fetch a dashboard and the insights tiled on it.",+ "feature_flag_get": "Look up a feature flag's configuration and rollout conditions.",+ "experiment_get": "Fetch an experiment's setup and current results.",+ "person_get": "Look up a person and their properties by distinct id.",+ "session_recording_get": "Fetch metadata for a session recording.",+ "error_tracking_issue_get": "Fetch an error-tracking issue and its impact.",+}+# 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.@@ -107,6 +136,19 @@ SESSION_INTENTS: list[str] = ["Pull the latest exception issue tied to the deploy so on-call can triage the regression.",]+# Paired with a fraction of failing tool calls so the tool detail "Failures" table+# (which reads $exception events) has something to show.+EXCEPTION_MESSAGES: list[str] = [+ "TimeoutError: upstream query exceeded 30s deadline",+ "ValidationError: missing required parameter 'project_id'",+ "PermissionError: API key lacks scope for this resource",+ "ConnectionError: ClickHouse connection reset by peer",+ "KeyError: '$mcp_tool_name' not present in event payload",+]++# Fraction of failing tool calls that also emit a paired $exception event.+EXCEPTION_PAIR_PROBABILITY = 0.6+class Command(BaseCommand):help = "Seed mcp_tool_call events into ClickHouse for local testing of MCP analytics."@@ -150,49 +192,61 @@ class Command(BaseCommand):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",+ f"ALTER TABLE {EVENTS_DATA_TABLE()} DELETE WHERE team_id = %(team_id)s "+ "AND (event = 'mcp_tool_call' OR (event = '$exception' AND JSONExtractString(properties, '$mcp_tool_name') != '')) "+ "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}."))+ with team_scope(team_id):+ MCPSession.objects.filter(team=team).delete()+ self.stdout.write(self.style.WARNING(f"Cleared existing MCP events for team {team_id}."))rng = random.Random(seed)now = datetime.now(tz=UTC)total_events = 0- # Create the identified personas. We write each one to BOTH Postgres- # (Person + PersonDistinctId) and ClickHouse (via create_person) so the- # distinct_id -> Person lookup in list_mcp_sessions can resolve name/email.- for persona in IDENTIFIED_PERSONAS:- properties = {- "email": persona["email"],- "name": persona["name"],- "role": persona["role"],- }- existing_person = get_person_by_distinct_id(team_id=team.id, distinct_id=persona["distinct_id"])+ # distinct_id -> (person_uuid, person_properties). Events carry person_id so the+ # person-on-events join (Top users table) keeps them — without a real person the+ # inner join drops every row.+ person_cache: dict[str, tuple[str, dict[str, Any]]] = {}++ def ensure_person(+ distinct_id: str, properties: dict[str, Any], is_identified: bool+ ) -> tuple[str, dict[str, Any]]:+ if distinct_id in person_cache:+ return person_cache[distinct_id]+ existing_person = get_person_by_distinct_id(team_id=team.id, distinct_id=distinct_id)if existing_person:person = existing_person- person.properties = properties- person.is_identified = True- person.save(update_fields=["properties", "is_identified"])+ if properties:+ person.properties = properties+ person.is_identified = is_identified+ person.save(update_fields=["properties", "is_identified"])else:person = Person.objects.create( # nosemgrep: no-direct-persons-db-orm- team=team, properties=properties, is_identified=True+ team=team, properties=properties, is_identified=is_identified)PersonDistinctId.objects.create( # nosemgrep: no-direct-persons-db-orm- team=team, distinct_id=persona["distinct_id"], person=person+ team=team, distinct_id=distinct_id, person=person)person_uuid = str(person.uuid)create_person(team_id=team.id,uuid=person_uuid,version=0,- is_identified=True,+ is_identified=is_identified,properties=properties,)- create_person_distinct_id(- team_id=team.id,- distinct_id=persona["distinct_id"],- person_id=person_uuid,+ create_person_distinct_id(team_id=team.id, distinct_id=distinct_id, person_id=person_uuid)+ person_cache[distinct_id] = (person_uuid, properties)+ return person_cache[distinct_id]++ # Create the identified personas up front (anonymous visitors are created lazily below).+ for persona in IDENTIFIED_PERSONAS:+ ensure_person(+ persona["distinct_id"],+ {"email": persona["email"], "name": persona["name"], "role": persona["role"]},+ is_identified=True,)for session_idx in range(session_count):@@ -208,6 +262,7 @@ class Command(BaseCommand):distinct_id = persona["distinct_id"]else:distinct_id = f"anon_{uuid.uuid4().hex[:8]}"+ person_uuid, person_props = ensure_person(distinct_id, {}, is_identified=False)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@@ -224,6 +279,10 @@ class Command(BaseCommand):session_end_offset_min = rng.randint(31, 59)session_start = now - timedelta(minutes=session_end_offset_min) - total_call_duration+ # One coherent intent per session so the clustering page has themes to group.+ primary_tool = rng.choice(TOOL_NAMES)+ session_intent = rng.choice(INTENTS_BY_TOOL.get(primary_tool, [DEFAULT_INTENT]))+cumulative_offset_s = 0for call_idx in range(calls):cumulative_offset_s += call_intervals[call_idx]@@ -236,18 +295,23 @@ class Command(BaseCommand):duration_ms = max(1, int(rng.gauss(base_latency, base_latency * 0.4)))if is_error:duration_ms = int(duration_ms * rng.uniform(1.5, 3.0))- intent = rng.choice(INTENTS_BY_TOOL.get(tool_name, [DEFAULT_INTENT]))create_event(event_uuid=uuid.uuid4(),event="mcp_tool_call",team=team,distinct_id=distinct_id,timestamp=timestamp,+ person_id=uuid.UUID(person_uuid),+ person_properties=person_props,properties={"$session_id": session_id,"$mcp_session_id": mcp_session_id,+ "$mcp_source": NEW_SDK_SOURCE,"$mcp_tool_name": tool_name,- "$mcp_intent": intent,+ "$mcp_tool_category": TOOL_CATEGORIES.get(tool_name, "Other"),+ "$mcp_tool_description": TOOL_DESCRIPTIONS.get(tool_name, ""),+ "$mcp_intent": session_intent,+ "$mcp_intent_source": rng.choices(["context_parameter", "inferred"], weights=[7, 3], k=1)[0],"$mcp_error_message": "Upstream returned 500" if is_error else "","$mcp_client_name": client_name,"$mcp_client_version": "1.0.0",@@ -259,8 +323,34 @@ class Command(BaseCommand):)total_events += 1- # Don't write to MCPSession (it's dormant) — the listing derives sessions- # on the fly from the events we just captured, grouped by $mcp_session_id.+ # Pair some failures with an $exception event so the tool detail+ # "Failures" table (which reads $exception events) has data.+ if is_error and rng.random() < EXCEPTION_PAIR_PROBABILITY:+ create_event(+ event_uuid=uuid.uuid4(),+ event="$exception",+ team=team,+ distinct_id=distinct_id,+ timestamp=timestamp,+ person_id=uuid.UUID(person_uuid),+ person_properties=person_props,+ properties={+ "$session_id": session_id,+ "$mcp_session_id": mcp_session_id,+ "$mcp_tool_name": tool_name,+ "$mcp_client_name": client_name,+ "$exception_message": rng.choice(EXCEPTION_MESSAGES),+ },+ )+ total_events += 1++ # The session listing derives sessions on the fly from the events above,+ # but intent clustering reads MCPSession.intent (keyed by $session_id), so+ # store one row per session to give the clustering page something to group.+ with team_scope(team_id):+ MCPSession.objects.update_or_create(+ team=team, session_id=session_id, defaults={"intent": session_intent}+ )self.stdout.write(f" session {session_idx + 1}/{session_count}: {calls} tool calls (mcp_session_id={mcp_session_id})")diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsxindex e8ea2e244cf0..a9098b422bd9 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx@@ -1,24 +1,50 @@import { useValues } from 'kea'+import { useMemo } from 'react'import { IconArrowLeft, IconArrowRight } from '@posthog/icons'-import { LemonButton, LemonDivider, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'+import { LemonDivider, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'+import {+ type ChartTheme,+ MetricCard,+ type Series,+ TimeSeriesLineChart,+ type TimeSeriesLineChartConfig,+} from '@posthog/quill-charts'+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@posthog/quill-primitives'+import { buildTheme } from 'lib/charts/utils/theme'import { TZLabel } from 'lib/components/TZLabel'-import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'-import { humanFriendlyDuration, humanFriendlyNumber } from 'lib/utils'+import { humanFriendlyNumber } from 'lib/utils'import { PersonDisplay } from 'scenes/persons/PersonDisplay'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { Query } from '~/queries/Query/Query'import { SceneExport } from '~/scenes/sceneTypes'-import { HarnessPill } from './dashboard/harness'+import { formatMs, formatMsAsSeconds } from './dashboard/formatters'+import { HarnessLogo, HarnessPill } from './dashboard/harness'import {+ type DailyChartData,IntentCoverage,MCPAnalyticsToolDetailLogicProps,+ type ResultRows,ToolSummary,mcpAnalyticsToolDetailLogic,} from './mcpAnalyticsToolDetailLogic'@@ -32,92 +58,182 @@ export const scene: SceneExport<MCPAnalyticsToolDetailLogicProps> = {}),}-function percentDelta(current: number, previous: number): number | null {- if (!previous) {- return null- }- return ((current - previous) / previous) * 100-}--function DeltaTag({ value, invertColor = false }: { value: number | null; invertColor?: boolean }): JSX.Element | null {- if (value == null || !isFinite(value) || Math.abs(value) < 1) {- return null- }- const positive = value > 0- // For error rate, "up" is bad — invert color semantics.- const goodDirection = invertColor ? !positive : positive- const Icon = positive ? IconArrowUp : IconArrowDown- return (- <span- className={`inline-flex items-center gap-0.5 text-xs leading-none ${- goodDirection ? 'text-success' : 'text-danger'- }`}- >- <Icon className="text-sm" />- {Math.abs(Math.round(value))}%- </span>- )-}--function Stat({+function StatTile({label,value,- delta,- deltaInvertColor,+ formatValue,+ data,+ theme,+ color,+ goodDirection,loading,- tooltip,}: {label: string- value: React.ReactNode- delta?: number | null- deltaInvertColor?: boolean- loading?: boolean- tooltip?: string+ value: number+ formatValue: (n: number) => string+ data?: number[]+ theme: ChartTheme+ color?: string+ goodDirection?: 'up' | 'down'+ loading: boolean}): JSX.Element {- const content = (- <div className="flex flex-col gap-1 min-w-[110px]">- <span className="text-[11px] uppercase tracking-wider text-secondary">{label}</span>+ return (+ <Card size="sm" className="flex-1">{loading ? (- <LemonSkeleton className="h-6 w-16" />+ <CardContent className="flex flex-col gap-2">+ <Skeleton className="h-3 w-16" />+ <Skeleton className="h-7 w-20" />+ </CardContent>) : (- <div className="flex items-baseline gap-2">- <span className="text-2xl font-semibold leading-none">{value}</span>- <DeltaTag value={delta ?? null} invertColor={deltaInvertColor} />- </div>+ <CardContent>+ <MetricCard+ className="text-primary"+ title={label}+ value={value}+ data={data}+ theme={theme}+ color={color}+ formatValue={formatValue}+ goodDirection={goodDirection}+ sparklineHeight={40}+ sparklineClassName="mt-2 -mx-3 -mb-3"+ />+ </CardContent>)}- </div>+ </Card>)- return tooltip ? <Tooltip title={tooltip}>{content}</Tooltip> : content}// Renderer for the "person" column in the Top users table. The query selects// `argMax(tuple(distinct_id, person.created_at, person.properties), timestamp)`,// which deserialises as a 3-element array. Wrap it back into the shape PersonDisplay expects.-const topUserPersonColumn = {- title: 'User',- render: function RenderPerson({ value }: { value: unknown }) {- if (!Array.isArray(value) || value.length === 0) {- return <span className="text-muted">—</span>- }- const [distinctId, , propertiesRaw] = value as [string, unknown, unknown]- let properties: Record<string, unknown> | undefined- if (propertiesRaw && typeof propertiesRaw === 'object') {- properties = propertiesRaw as Record<string, unknown>- } else if (typeof propertiesRaw === 'string') {- try {- properties = JSON.parse(propertiesRaw)- } catch {- properties = undefined- }+function renderPersonCell(value: unknown): JSX.Element {+ if (!Array.isArray(value) || value.length === 0) {+ return <span className="text-muted">—</span>+ }+ const [distinctId, , propertiesRaw] = value as [string, unknown, unknown]+ let properties: Record<string, unknown> | undefined+ if (propertiesRaw && typeof propertiesRaw === 'object') {+ properties = propertiesRaw as Record<string, unknown>+ } else if (typeof propertiesRaw === 'string') {+ try {+ properties = JSON.parse(propertiesRaw)+ } catch {+ properties = undefined}- return (- <PersonDisplay- person={{ distinct_id: distinctId, properties: properties ?? {} }}- withIcon- noPopover={false}- />+ }+ return (+ <PersonDisplay person={{ distinct_id: distinctId, properties: properties ?? {} }} withIcon noPopover={false} />+ )+}++// Deduped harness logos so the column stays one line instead of wrapping.+function HarnessLogos({ value }: { value: string }): JSX.Element {+ const categories = Array.from(+ new Set(+ value+ .split(',')+ .map((raw) => categorizeHarness(raw.trim()))+ .filter(Boolean))- },+ )+ if (categories.length === 0) {+ return <span className="text-muted">—</span>+ }+ return (+ <div className="flex items-center gap-1">+ {categories.map((category) => (+ <HarnessLogo key={category} category={category} />+ ))}+ </div>+ )+}++interface ResultColumn {+ header: string+ align?: 'left' | 'right'+ expand?: boolean+ render: (row: unknown[]) => React.ReactNode+}++const neighborColumns: ResultColumn[] = [+ { header: 'Tool', expand: true, render: (r) => <span className="font-mono">{String(r[0] ?? '')}</span> },+ { header: 'In same conversation', align: 'right', render: (r) => humanFriendlyNumber(Number(r[1] ?? 0)) },+]++// Card-wrapped quill table matching the dashboard table cards.+function ResultTable({+ title,+ description,+ action,+ rows,+ loading,+ columns,+ emptyMessage = 'No data for the last 7 days.',+}: {+ title?: React.ReactNode+ description?: React.ReactNode+ action?: React.ReactNode+ rows: ResultRows+ loading: boolean+ columns: ResultColumn[]+ emptyMessage?: string+}): JSX.Element {+ return (+ <Card size="sm" className="gap-0">+ {title != null && (+ <CardHeader+ className={`border-b border-border pb-3${+ action != null ? ' !flex flex-row items-center justify-between gap-2' : ''+ }`}+ >+ <CardTitle>{title}</CardTitle>+ {description != null && <CardDescription>{description}</CardDescription>}+ {action}+ </CardHeader>+ )}+ <Table fullWidth>+ <TableHeader>+ <TableRow>+ {columns.map((col, i) => (+ <TableHead key={i} align={col.align} expand={col.expand}>+ {col.header}+ </TableHead>+ ))}+ </TableRow>+ </TableHeader>+ <TableBody>+ {loading && rows.length === 0 ? (+ <TableRow>+ <TableCell colSpan={columns.length}>+ <div className="space-y-2 py-1">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-3.5 w-full" />+ ))}+ </div>+ </TableCell>+ </TableRow>+ ) : rows.length === 0 ? (+ <TableRow>+ <TableCell colSpan={columns.length} align="center" className="py-6 text-secondary">+ {emptyMessage}+ </TableCell>+ </TableRow>+ ) : (+ rows.map((row, i) => (+ <TableRow key={i}>+ {columns.map((col, ci) => (+ <TableCell key={ci} align={col.align} expand={col.expand}>+ {col.render(row)}+ </TableCell>+ ))}+ </TableRow>+ ))+ )}+ </TableBody>+ </Table>+ </Card>+ )}function SectionHeader({ title, subtitle }: { title: string; subtitle?: string }): JSX.Element {@@ -129,46 +245,91 @@ function SectionHeader({ title, subtitle }: { title: string; subtitle?: string })}-function formatDurationMs(ms: number | null): string {- if (ms == null) {- return '—'- }- if (ms < 1000) {- return `${Math.round(ms)} ms`- }- return humanFriendlyDuration(ms / 1000, { secondsFixed: 2 })+// Tile sparkline window — the trailing slice of the 30-day daily series.+const SPARKLINE_DAYS = 7++// Trailing window of a daily series, coalescing latency gaps (NaN) to 0 for the sparkline.+function spark(values: number[]): number[] {+ return values.slice(-SPARKLINE_DAYS).map((v) => (Number.isFinite(v) ? v : 0))}-function StatStrip({ summary, loading }: { summary: ToolSummary | null; loading: boolean }): JSX.Element {+function StatTiles({+ summary,+ loading,+ daily,+ theme,+}: {+ summary: ToolSummary | null+ loading: boolean+ daily: DailyChartData+ theme: ChartTheme+}): JSX.Element {const calls = summary?.calls ?? 0const errors = summary?.errors ?? 0const errorRate = calls ? (errors / calls) * 100 : 0- const errorRatePrev = summary && summary.calls_prev ? (summary.errors_prev / summary.calls_prev) * 100 : 0+ const errorRateDaily = daily.calls.map((c, i) => (c ? (daily.errors[i] / c) * 100 : 0))+return (- <div className="flex flex-wrap items-end gap-x-10 gap-y-4 py-1">- <Stat+ <div className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-6" data-quill>+ <StatTilelabel="Calls"loading={loading}- value={humanFriendlyNumber(calls)}- delta={summary ? percentDelta(calls, summary.calls_prev) : null}- tooltip="Last 7 days vs prior 7 days."+ value={calls}+ formatValue={humanFriendlyNumber}+ data={spark(daily.calls)}+ theme={theme}+ color={theme.colors[0]}+ goodDirection="up"/>- <Stat+ <StatTilelabel="Error rate"loading={loading}- value={`${errorRate.toFixed(1)}%`}- delta={summary ? percentDelta(errorRate, errorRatePrev) : null}- deltaInvertColor- tooltip="Share of calls with $mcp_is_error = true."+ value={errorRate}+ formatValue={(n) => `${n.toFixed(1)}%`}+ data={spark(errorRateDaily)}+ theme={theme}+ color={theme.colors[4]}+ goodDirection="down"+ />+ <StatTile+ label="p50 latency"+ loading={loading}+ value={summary?.p50_ms ?? 0}+ formatValue={formatMs}+ data={spark(daily.p50)}+ theme={theme}+ color={theme.colors[0]}+ goodDirection="down"+ />+ <StatTile+ label="p95 latency"+ loading={loading}+ value={summary?.p95_ms ?? 0}+ formatValue={formatMs}+ data={spark(daily.p95)}+ theme={theme}+ color={theme.colors[0]}+ goodDirection="down"+ />+ <StatTile+ label="Users"+ loading={loading}+ value={summary?.users ?? 0}+ formatValue={humanFriendlyNumber}+ data={spark(daily.users)}+ theme={theme}+ color={theme.colors[0]}+ goodDirection="up"/>- <Stat label="p50 latency" loading={loading} value={formatDurationMs(summary?.p50_ms ?? null)} />- <Stat label="p95 latency" loading={loading} value={formatDurationMs(summary?.p95_ms ?? null)} />- <Stat label="Users" loading={loading} value={humanFriendlyNumber(summary?.users ?? 0)} />- <Stat+ <StatTilelabel="Sessions"loading={loading}- value={humanFriendlyNumber(summary?.conversations ?? 0)}- tooltip="Unique $mcp_session_id values, falling back to $session_id where missing."+ value={summary?.conversations ?? 0}+ formatValue={humanFriendlyNumber}+ data={spark(daily.sessions)}+ theme={theme}+ color={theme.colors[6]}+ goodDirection="up"/></div>)@@ -242,23 +403,112 @@ function DescriptionBlock({)}+function trendChartConfig(timezone: string, yAxis?: TimeSeriesLineChartConfig['yAxis']): TimeSeriesLineChartConfig {+ return {+ yAxis: { showGrid: false, ...yAxis },+ showAxisLines: true,+ xAxis: { interval: 'day', timezone },+ showCrosshair: true,+ tooltip: { placement: 'cursor' },+ }+}++type TrendSeriesKey = 'calls' | 'errors' | 'p50' | 'p95'+const SERIES_META: Record<TrendSeriesKey, { label: string; colorIndex: number }> = {+ calls: { label: 'Calls', colorIndex: 0 },+ errors: { label: 'Errors', colorIndex: 4 },+ p50: { label: 'p50', colorIndex: 1 },+ p95: { label: 'p95', colorIndex: 0 },+}++function seriesFor(data: DailyChartData, theme: ChartTheme, keys: TrendSeriesKey[]): Series[] {+ return keys.map((key) => ({+ key,+ label: SERIES_META[key].label,+ color: theme.colors[SERIES_META[key].colorIndex],+ data: data[key],+ }))+}++function TrendChart({+ title,+ series,+ labels,+ config,+ theme,+ loading,+ dataAttr,+}: {+ title: string+ series: Series[]+ labels: string[]+ config: TimeSeriesLineChartConfig+ theme: ChartTheme+ loading: boolean+ dataAttr: string+}): JSX.Element {+ return (+ <div className="flex flex-col rounded border bg-bg-light p-2" style={{ height: 240 }} data-quill>+ <div className="mb-1 px-2 pt-1 text-xs font-medium uppercase text-secondary">{title}</div>+ <div className="flex min-h-0 flex-1 flex-col">+ {loading && labels.length === 0 ? (+ <Skeleton className="flex-1" />+ ) : labels.length === 0 ? (+ <div className="flex flex-1 items-center justify-center text-[12px] text-secondary">+ No data for the last 7 days.+ </div>+ ) : (+ <TimeSeriesLineChart+ series={series}+ labels={labels}+ config={config}+ theme={theme}+ dataAttr={dataAttr}+ />+ )}+ </div>+ </div>+ )+}+export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.Element {const {summary,summaryLoading,descriptions,descriptionsLoading,- callsTrendQuery,- latencyTrendQuery,- failuresQuery,- sampleIntentsQuery,+ dailyChartData,+ dailyStatsLoading,+ failureRows,+ failureRowsLoading,+ sampleIntentRows,+ sampleIntentRowsLoading,intentCoverage,intentCoverageLoading,- neighborsBeforeQuery,- neighborsAfterQuery,- byHarnessQuery,- topUsersQuery,+ neighborsBeforeRows,+ neighborsBeforeRowsLoading,+ neighborsAfterRows,+ neighborsAfterRowsLoading,+ byHarnessRows,+ byHarnessRowsLoading,+ topUserRows,+ topUserRowsLoading,} = useValues(mcpAnalyticsToolDetailLogic({ toolName }))+ const { isDarkModeOn } = useValues(themeLogic)+ const { timezone } = useValues(teamLogic)++ // buildTheme() reads CSS vars from the DOM; isDarkModeOn forces a recompute on theme flip.+ const theme = useMemo<ChartTheme>(() => buildTheme(), [isDarkModeOn])+ const callsSeries = useMemo<Series[]>(+ () => seriesFor(dailyChartData, theme, ['calls', 'errors']),+ [dailyChartData, theme]+ )+ const latencySeries = useMemo<Series[]>(+ () => seriesFor(dailyChartData, theme, ['p50', 'p95']),+ [dailyChartData, theme]+ )+ const countsConfig = useMemo(() => trendChartConfig(timezone), [timezone])+ const latencyConfig = useMemo(() => trendChartConfig(timezone, { tickFormatter: formatMsAsSeconds }), [timezone])return (<SceneContent>@@ -266,44 +516,41 @@ export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.name={toolName}description={null}resourceType={{ type: 'llm_analytics' }}- actions={- <LemonButton- icon={<IconArrowLeft />}- type="secondary"- size="small"- to={urls.mcpAnalyticsToolQuality()}- >- Back to Tool quality- </LemonButton>- }+ forceBackTo={{+ name: 'Tool quality',+ path: urls.mcpAnalyticsToolQuality(),+ key: 'mcp-analytics-tool-quality',+ }}/><div className="flex flex-col gap-3 px-4 pb-4"><DescriptionBlock descriptions={descriptions} loading={descriptionsLoading} />- <StatStrip summary={summary} loading={summaryLoading} />+ <StatTiles summary={summary} loading={summaryLoading} daily={dailyChartData} theme={theme} /></div><LemonDivider /><div className="flex flex-col gap-3 px-4 pb-4">- <SectionHeader title="Reliability" subtitle="Last 7 days" />+ <SectionHeader title="Reliability" subtitle="Last 30 days" /><div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <div className="flex flex-col bg-bg-light border rounded p-2" style={{ height: 240 }}>- <div className="text-secondary text-xs font-medium uppercase mb-1 px-2 pt-1">- Calls (broken down by error)- </div>- <div className="InsightCard__viz">- <Query query={callsTrendQuery} readOnly embedded />- </div>- </div>- <div className="flex flex-col bg-bg-light border rounded p-2" style={{ height: 240 }}>- <div className="text-secondary text-xs font-medium uppercase mb-1 px-2 pt-1">- Duration (p50 / p95)- </div>- <div className="InsightCard__viz">- <Query query={latencyTrendQuery} readOnly embedded />- </div>- </div>+ <TrendChart+ title="Calls and errors"+ series={callsSeries}+ labels={dailyChartData.labels}+ config={countsConfig}+ theme={theme}+ loading={dailyStatsLoading}+ dataAttr="mcp-tool-detail-calls-chart"+ />+ <TrendChart+ title="Duration (p50 / p95)"+ series={latencySeries}+ labels={dailyChartData.labels}+ config={latencyConfig}+ theme={theme}+ loading={dailyStatsLoading}+ dataAttr="mcp-tool-detail-latency-chart"+ /></div></div>@@ -312,44 +559,44 @@ export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.<div className="flex flex-col gap-3 px-4 pb-4"><SectionHeader title="Usage flow" /><div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <div className="flex flex-col gap-2 bg-bg-light border rounded p-3">- <div className="flex items-center justify-between gap-2">- <span className="text-xs font-medium uppercase text-secondary">Sample intents</span>- <IntentCoverageTag coverage={intentCoverage} loading={intentCoverageLoading} />- </div>- <Query- query={sampleIntentsQuery}- readOnly- context={{- columns: {- intent_source: { title: 'Intent source' },- },- }}+ <ResultTable+ title="Sample intents"+ action={<IntentCoverageTag coverage={intentCoverage} loading={intentCoverageLoading} />}+ rows={sampleIntentRows}+ loading={sampleIntentRowsLoading}+ emptyMessage="No intents captured in the last 7 days."+ columns={[+ { header: 'When', render: (r) => <TZLabel time={String(r[0])} /> },+ { header: 'Intent', expand: true, render: (r) => <span>{String(r[1] ?? '')}</span> },+ { header: 'Intent source', render: (r) => <span>{String(r[2] ?? '')}</span> },+ { header: 'Harness', render: (r) => <span>{String(r[3] ?? '')}</span> },+ ]}+ />+ <div className="flex flex-col gap-4">+ <ResultTable+ title={+ <span className="flex items-center gap-1">+ <IconArrowLeft className="text-base" />+ Often called before (same conversation)+ </span>+ }+ rows={neighborsBeforeRows}+ loading={neighborsBeforeRowsLoading}+ emptyMessage="No tools commonly precede this one."+ columns={neighborColumns}+ />+ <ResultTable+ title={+ <span className="flex items-center gap-1">+ <IconArrowRight className="text-base" />+ Often called after (same conversation)+ </span>+ }+ rows={neighborsAfterRows}+ loading={neighborsAfterRowsLoading}+ emptyMessage="No tools commonly follow this one."+ columns={neighborColumns}/>- </div>- <div className="flex flex-col gap-3">- <div className="bg-bg-light border rounded p-3 flex flex-col gap-2">- <div className="flex items-center gap-1 text-xs font-medium uppercase text-secondary">- <IconArrowLeft className="text-base" />- Often called before (same conversation)- </div>- <Query- query={neighborsBeforeQuery}- readOnly- context={{ columns: { co_occurrences: { title: 'In same conversation' } } }}- />- </div>- <div className="bg-bg-light border rounded p-3 flex flex-col gap-2">- <div className="flex items-center gap-1 text-xs font-medium uppercase text-secondary">- <IconArrowRight className="text-base" />- Often called after (same conversation)- </div>- <Query- query={neighborsAfterQuery}- readOnly- context={{ columns: { co_occurrences: { title: 'In same conversation' } } }}- />- </div></div></div></div>@@ -359,53 +606,95 @@ export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.<div className="flex flex-col gap-3 px-4 pb-4"><SectionHeader title="Who uses it" /><div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <div className="bg-bg-light border rounded p-3 flex flex-col gap-2">- <span className="text-xs font-medium uppercase text-secondary">By harness</span>- <Query- query={byHarnessQuery}- readOnly- context={{- columns: {- harness: {- title: 'Harness',- render: function RenderHarness({ value }) {- const raw = String(value ?? '')- if (!raw) {- return <span className="text-muted">Unknown</span>- }- return <HarnessPill category={categorizeHarness(raw)} title={raw} />- },- },- error_rate_pct: { title: 'Error rate (%)' },+ <ResultTable+ title="By harness"+ rows={byHarnessRows}+ loading={byHarnessRowsLoading}+ columns={[+ {+ header: 'Harness',+ expand: true,+ render: (r) => {+ const raw = String(r[0] ?? '')+ return raw ? (+ <HarnessPill category={categorizeHarness(raw)} title={raw} />+ ) : (+ <span className="text-muted">Unknown</span>+ )},- }}- />- </div>- <div className="bg-bg-light border rounded p-3 flex flex-col gap-2">- <span className="text-xs font-medium uppercase text-secondary">Top users</span>- <Query- query={topUsersQuery}- readOnly- context={{- columns: {- person: topUserPersonColumn,- error_rate_pct: { title: 'Error rate (%)' },- last_seen: { title: 'Last seen' },- },- }}- />- </div>+ },+ {+ header: 'Calls',+ align: 'right',+ render: (r) => humanFriendlyNumber(Number(r[1] ?? 0)),+ },+ {+ header: 'Errors',+ align: 'right',+ render: (r) => humanFriendlyNumber(Number(r[2] ?? 0)),+ },+ { header: 'Error rate', align: 'right', render: (r) => `${Number(r[3] ?? 0)}%` },+ {+ header: 'Users',+ align: 'right',+ render: (r) => humanFriendlyNumber(Number(r[4] ?? 0)),+ },+ ]}+ />+ <ResultTable+ title="Top users"+ rows={topUserRows}+ loading={topUserRowsLoading}+ columns={[+ { header: 'User', expand: true, render: (r) => renderPersonCell(r[0]) },+ {+ header: 'Calls',+ align: 'right',+ render: (r) => humanFriendlyNumber(Number(r[1] ?? 0)),+ },+ {+ header: 'Errors',+ align: 'right',+ render: (r) => humanFriendlyNumber(Number(r[2] ?? 0)),+ },+ { header: 'Error rate', align: 'right', render: (r) => `${Number(r[3] ?? 0)}%` },+ {+ header: 'Harnesses',+ render: (r) => <HarnessLogos value={String(r[4] ?? '')} />,+ },+ { header: 'Last seen', render: (r) => <TZLabel time={String(r[5])} /> },+ ]}+ /></div></div><LemonDivider /><div className="flex flex-col gap-3 px-4 pb-4">- <SectionHeader+ <ResultTabletitle="Failures"- subtitle="Top exception messages paired with this tool. Sourced from $exception events."+ description="Top exception messages paired with this tool. Sourced from $exception events."+ rows={failureRows}+ loading={failureRowsLoading}+ emptyMessage="No exceptions recorded for this tool in the last 7 days."+ columns={[+ {+ header: 'Message',+ expand: true,+ render: (r) => <span className="font-mono text-xs">{String(r[0] ?? '')}</span>,+ },+ {+ header: 'Occurrences',+ align: 'right',+ render: (r) => humanFriendlyNumber(Number(r[1] ?? 0)),+ },+ { header: 'Last seen', render: (r) => <TZLabel time={String(r[2])} /> },+ {+ header: 'Harnesses',+ render: (r) => <HarnessLogos value={String(r[3] ?? '')} />,+ },+ ]}/>- <Query query={failuresQuery} readOnly context={{ columns: { last_seen: { title: 'Last seen' } } }} /></div></SceneContent>)diff --git a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsxindex 4ef4e5c923f9..2e4229aede73 100644--- a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx+++ b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx@@ -1,12 +1,23 @@import { useActions, useValues } from 'kea'import { IconRefresh, IconSparkles, IconWarning } from '@posthog/icons'-import { LemonButton, LemonSkeleton, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'+import { Tooltip } from '@posthog/lemon-ui'+import {+ Badge,+ Button,+ Progress,+ Skeleton,+ Spinner,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@posthog/quill-primitives'import { TZLabel } from 'lib/components/TZLabel'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'-import { LemonProgress } from 'lib/lemon-ui/LemonProgress'-import { Spinner } from 'lib/lemon-ui/Spinner'import type { MCPIntentClusterApi, MCPIntentClusterToolEntryApi } from '../generated/api.schemas'import { ClusterJourneySankey } from './ClusterJourneySankey'@@ -23,18 +34,18 @@ function EntropyBadge({ entropy }: { entropy: number }): JSX.Element {if (entropy < 0.3) {return (<Tooltip title={`Routing entropy ${entropy.toFixed(2)} — one tool dominates this cluster's calls.`}>- <LemonTag type="success" size="small">- Concentrated · {entropy.toFixed(2)}- </LemonTag>+ <span>+ <Badge variant="success">Concentrated · {entropy.toFixed(2)}</Badge>+ </span></Tooltip>)}if (entropy < 0.6) {return (<Tooltip title={`Routing entropy ${entropy.toFixed(2)} — calls split between a few tools.`}>- <LemonTag type="warning" size="small">- Mixed · {entropy.toFixed(2)}- </LemonTag>+ <span>+ <Badge variant="warning">Mixed · {entropy.toFixed(2)}</Badge>+ </span></Tooltip>)}@@ -42,9 +53,9 @@ function EntropyBadge({ entropy }: { entropy: number }): JSX.Element {<Tooltiptitle={`Routing entropy ${entropy.toFixed(2)} — calls spread across many tools. Either a real multi-step workflow or the agent is improvising; the aggregate alone can't tell.`}>- <LemonTag type="danger" size="small">- Spread · {entropy.toFixed(2)}- </LemonTag>+ <span>+ <Badge variant="destructive">Spread · {entropy.toFixed(2)}</Badge>+ </span></Tooltip>)}@@ -162,14 +173,14 @@ function SortHeader(): JSX.Element {<div className="flex items-center gap-2 flex-wrap"><span className="text-xs text-muted">Sort clusters by</span>{(Object.keys(SORT_LABELS) as ClusterSortKey[]).map((key) => (- <LemonButton+ <Buttonkey={key}- size="xsmall"- type={sortKey === key ? 'primary' : 'tertiary'}+ size="sm"+ variant={sortKey === key ? 'default' : 'outline'}onClick={() => setSortKey(key)}>{SORT_LABELS[key]}- </LemonButton>+ </Button>))}</div>)@@ -329,18 +340,16 @@ function ClusterDetail({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Eleme</div><div className="flex flex-wrap items-center gap-2 shrink-0"><EntropyBadge entropy={cluster.routing_entropy} />- <LemonTag type={cluster.error_rate_pct > 5 ? 'danger' : 'muted'} size="small">+ <Badge variant={cluster.error_rate_pct > 5 ? 'destructive' : 'default'}>{cluster.error_rate_pct.toFixed(1)}% errors- </LemonTag>- <LemonTag type="muted" size="small">- {cluster.call_count.toLocaleString()} calls- </LemonTag>- <LemonTag type="muted" size="small">+ </Badge>+ <Badge variant="default">{cluster.call_count.toLocaleString()} calls</Badge>+ <Badge variant="default">{cluster.session_count} session{cluster.session_count === 1 ? '' : 's'}- </LemonTag>- <LemonTag type="muted" size="small">+ </Badge>+ <Badge variant="default">{cluster.intent_count} intent{cluster.intent_count === 1 ? '' : 's'}- </LemonTag>+ </Badge></div></div>{worstTool && worstTool.error_rate_pct > 0 ? (@@ -374,51 +383,46 @@ function ClusterDetail({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Eleme<section className="flex flex-col gap-2"><span className="text-xs uppercase text-muted font-medium">Tool routing breakdown</span>- <LemonTable- embedded- size="small"- dataSource={[...cluster.tool_distribution]}- rowKey={(row) => row.tool}- columns={[- {- title: 'Tool',- key: 'tool',- render: (_, row) => <span className="font-mono">{row.tool}</span>,- },- {- title: 'Calls',- key: 'count',- align: 'right',- render: (_, row) => row.count.toLocaleString(),- },- {- title: 'Share of cluster',- key: 'pct',- render: (_, row) => (- <div className="flex items-center gap-2 min-w-[160px]">- <LemonProgress percent={row.pct} className="flex-1" />- <span className="text-xs text-muted tabular-nums w-10 text-right">- {row.pct.toFixed(1)}%- </span>- </div>- ),- },- {- title: 'Errors',- key: 'errors',- align: 'right',- render: (_, row) =>- row.error_rate_pct > 0 ? (- <span className="text-danger tabular-nums">- {row.error_rate_pct.toFixed(1)}%{' '}- <span className="text-muted">({row.errors})</span>- </span>- ) : (- <span className="text-muted">0%</span>- ),- },- ]}- />+ <div data-quill>+ <Table fullWidth>+ <TableHeader>+ <TableRow>+ <TableHead expand>Tool</TableHead>+ <TableHead align="right">Calls</TableHead>+ <TableHead>Share of cluster</TableHead>+ <TableHead align="right">Errors</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {cluster.tool_distribution.map((row) => (+ <TableRow key={row.tool}>+ <TableCell expand>+ <span className="font-mono">{row.tool}</span>+ </TableCell>+ <TableCell align="right">{row.count.toLocaleString()}</TableCell>+ <TableCell>+ <div className="flex min-w-[160px] items-center gap-2">+ <Progress value={row.pct} className="flex-1" />+ <span className="w-10 text-right text-xs tabular-nums text-muted">+ {row.pct.toFixed(1)}%+ </span>+ </div>+ </TableCell>+ <TableCell align="right">+ {row.error_rate_pct > 0 ? (+ <span className="tabular-nums text-danger">+ {row.error_rate_pct.toFixed(1)}%{' '}+ <span className="text-muted">({row.errors})</span>+ </span>+ ) : (+ <span className="text-muted">0%</span>+ )}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div></section><section className="flex flex-col gap-2">@@ -461,15 +465,15 @@ function StatusRow(): JSX.Element | null {</>) : null}</div>- <LemonButton- type="secondary"- size="small"- icon={<IconRefresh />}+ <Button+ variant="outline"+ size="sm"onClick={recompute}data-attr="mcp-analytics-intent-clusters-recompute">+ <IconRefresh />Recompute- </LemonButton>+ </Button></div>)}@@ -480,7 +484,10 @@ function EmptyState(): JSX.Element {const { recompute } = useActions(mcpClusteringLogic)const { snapshotLoading } = useValues(mcpClusteringLogic)return (- <div className="bg-surface-primary border rounded p-8 flex flex-col items-center text-center gap-3 max-w-2xl mx-auto">+ <div+ className="bg-surface-primary border rounded p-8 flex flex-col items-center text-center gap-3 max-w-2xl mx-auto"+ data-quill+ ><IconSparkles className="text-4xl text-accent" /><h3 className="text-lg font-semibold">No intent clusters yet</h3><p className="text-sm text-muted max-w-md">@@ -488,9 +495,10 @@ function EmptyState(): JSX.Element {routes to. It surfaces whether your MCP sends similar goals to the same tools, and which routes are themost error-prone.</p>- <LemonButton type="primary" icon={<IconSparkles />} onClick={recompute} loading={snapshotLoading}>+ <Button variant="default" onClick={recompute} disabled={snapshotLoading}>+ {snapshotLoading ? <Spinner /> : <IconSparkles />}Compute intent clusters- </LemonButton>+ </Button><span className="text-xs text-muted">Needs sessions with a summarized intent — usually a few minutes after sessions are recorded.</span>@@ -502,12 +510,12 @@ function ComputingSkeleton(): JSX.Element {return (<div className="flex flex-col gap-4"><div className="grid grid-cols-1 lg:grid-cols-3 gap-4">- <LemonSkeleton className="h-24 w-full" />- <LemonSkeleton className="h-24 w-full" />- <LemonSkeleton className="h-24 w-full" />+ <Skeleton className="h-24 w-full" />+ <Skeleton className="h-24 w-full" />+ <Skeleton className="h-24 w-full" /></div>- <LemonSkeleton className="h-96 w-full" />- <LemonSkeleton className="h-48 w-full" />+ <Skeleton className="h-96 w-full" />+ <Skeleton className="h-48 w-full" /></div>)}@@ -532,7 +540,7 @@ export function MCPAnalyticsClustering(): JSX.Element {if (isComputing || (snapshotLoading && !hasSnapshot)) {return (- <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-4" data-quill><StatusRow /><ComputingSkeleton /></div>@@ -540,7 +548,7 @@ export function MCPAnalyticsClustering(): JSX.Element {}return (- <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-4" data-quill><StatusRow /><Scorecards /><SortHeader />diff --git a/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx b/products/mcp_analytics/frontend/dashboard/ActivityChart.tsxindex 206301eeeac5..c82c4d57f106 100644--- a/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx@@ -1,12 +1,12 @@import { useMemo } from 'react'-import { LemonSkeleton } from '@posthog/lemon-ui'import {type ChartTheme,type Series,TimeSeriesLineChart,type TimeSeriesLineChartConfig,} from '@posthog/quill-charts'+import { Skeleton } from '@posthog/quill-primitives'import { type DailyActivity } from '../mcpDashboardOverviewLogic'import { Card, CardState } from './Card'@@ -46,7 +46,7 @@ export function ActivityChart({<CardStateloading={loading}isEmpty={daily.labels.length === 0}- skeleton={<LemonSkeleton className="min-h-[300px] flex-1" />}+ skeleton={<Skeleton 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.diff --git a/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx b/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsxindex d8f24d95fc71..f19af3940dc8 100644--- a/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx+++ b/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx@@ -1,6 +1,5 @@import { useCallback, useMemo } from 'react'-import { LemonSkeleton } from '@posthog/lemon-ui'import {type ChartTheme,PieChart,@@ -9,6 +8,7 @@ import {type TooltipContext,useRadialLayout,} from '@posthog/quill-charts'+import { Skeleton } from '@posthog/quill-primitives'import { formatPercentage } from 'lib/utils'@@ -111,7 +111,7 @@ export function HarnessDonut({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" />+ <Skeleton className="h-[180px] w-[180px] rounded-full" /></div></Card>)diff --git a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsxindex 8215b935cf4b..0d92b50b3f39 100644--- a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx+++ b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx@@ -1,6 +1,6 @@-import { LemonSkeleton, Link } from '@posthog/lemon-ui'+import { Link } from '@posthog/lemon-ui'import { type ChartTheme, MetricCard } from '@posthog/quill-charts'-import { Card, CardContent } from '@posthog/quill-primitives'+import { Card, CardContent, Skeleton } from '@posthog/quill-primitives'import { formatPercentage } from 'lib/utils'import { urls } from 'scenes/urls'@@ -27,8 +27,8 @@ function KPITile({ tile, theme }: { tile: TileSpec; theme: ChartTheme }): JSX.El<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" />+ <Skeleton className="h-3 w-16" />+ <Skeleton className="h-7 w-20" /></CardContent>) : (<CardContent>diff --git a/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx b/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsxindex 98d1b45d7655..c5b864d5626a 100644--- a/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx+++ b/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx@@ -1,10 +1,11 @@-import { LemonSkeleton, Link } from '@posthog/lemon-ui'+import { Link } from '@posthog/lemon-ui'import {Badge,Card,CardFooter,CardHeader,CardTitle,+ Skeleton,Table,TableBody,TableCell,@@ -48,7 +49,7 @@ function SessionRows({ sessions, loading }: { sessions: NotableSession[]; loadin<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" />+ <Skeleton key={i} className="h-3.5 w-full" />))}</div></TableCell>diff --git a/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx b/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsxindex 92087cb3db6a..39c29432553f 100644--- a/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx@@ -1,6 +1,5 @@import { useCallback, useMemo } from 'react'-import { LemonSkeleton } from '@posthog/lemon-ui'import {BarChart,type BarChartConfig,@@ -9,6 +8,7 @@ import {type TooltipContext,ValueLabels,} from '@posthog/quill-charts'+import { Skeleton } from '@posthog/quill-primitives'import { formatPercentage } from 'lib/utils'@@ -90,7 +90,7 @@ export function ToolErrorRateChart({skeleton={<div className="space-y-2 py-3">{Array.from({ length: 5 }).map((_, i) => (- <LemonSkeleton key={i} className="h-7 w-full" />+ <Skeleton key={i} className="h-7 w-full" />))}</div>}diff --git a/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx b/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsxindex b390a27c5aab..00009ce84def 100644--- a/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx@@ -1,7 +1,7 @@import { useMemo } from 'react'-import { LemonSkeleton } from '@posthog/lemon-ui'import { type ChartTheme, type Series, TimeSeriesBarChart, type TimeSeriesBarChartConfig } from '@posthog/quill-charts'+import { Skeleton } from '@posthog/quill-primitives'import { type ToolDailySeries } from '../mcpDashboardOverviewLogic'import { Card, CardState } from './Card'@@ -44,7 +44,7 @@ export function ToolUsageChart({<CardStateloading={loading}isEmpty={data.labels.length === 0}- skeleton={<LemonSkeleton className="h-[260px] w-full" />}+ skeleton={<Skeleton 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">diff --git a/products/mcp_analytics/frontend/dashboard/harness.tsx b/products/mcp_analytics/frontend/dashboard/harness.tsxindex 9824ab629d8f..8122672bb7f2 100644--- a/products/mcp_analytics/frontend/dashboard/harness.tsx+++ b/products/mcp_analytics/frontend/dashboard/harness.tsx@@ -33,18 +33,28 @@ export function harnessSliceColor(theme: ChartTheme, category: string, fallbackIreturn theme.colors[index % theme.colors.length]}-export function HarnessPill({ category, title }: { category: string; title?: string }): JSX.Element {+// A single harness logo (or a neutral dot when no logo is known for the category).+export function HarnessLogo({+ category,+ className = 'h-4 w-4',+}: {+ category: string+ className?: string+}): JSX.Element {const logo = HARNESS_LOGOS[category]+ if (logo) {+ return <img src={logo.src} alt={category} title={category} className={`${className} shrink-0 object-contain`} />+ }+ return <span title={category} className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-secondary" aria-hidden />+}++export function HarnessPill({ category, title }: { category: string; title?: string }): JSX.Element {return (<spanclassName="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 />- )}+ <HarnessLogo category={category} className="h-3.5 w-3.5" /><span className="truncate">{category}</span></span>)diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.tsnew file mode 100644index 000000000000..29e8a7d7fca4--- /dev/null+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts@@ -0,0 +1,56 @@+import { buildDailyChartData, type DailyToolStat } from './mcpAnalyticsToolDetailLogic'++function stat(overrides: Partial<DailyToolStat> & { day: string }): DailyToolStat {+ return {+ calls: 0,+ errors: 0,+ p50: 0,+ p95: 0,+ users: 0,+ sessions: 0,+ ...overrides,+ }+}++describe('buildDailyChartData', () => {+ it('returns empty series for no rows', () => {+ expect(buildDailyChartData([])).toEqual({+ labels: [],+ calls: [],+ errors: [],+ p50: [],+ p95: [],+ users: [],+ sessions: [],+ })+ })++ it('passes a single day through unchanged', () => {+ const rows = [stat({ day: '2026-06-01', calls: 10, errors: 2, p50: 100, p95: 300, users: 3, sessions: 4 })]+ expect(buildDailyChartData(rows)).toEqual({+ labels: ['2026-06-01'],+ calls: [10],+ errors: [2],+ p50: [100],+ p95: [300],+ users: [3],+ sessions: [4],+ })+ })++ it('gap-fills interior missing days (counts→0, latency→NaN) with a contiguous day axis', () => {+ const rows = [+ stat({ day: '2026-06-01', calls: 10, errors: 1, p50: 100, p95: 200, users: 2, sessions: 3 }),+ stat({ day: '2026-06-03', calls: 5, errors: 0, p50: 50, p95: 150, users: 1, sessions: 1 }),+ ]+ expect(buildDailyChartData(rows)).toEqual({+ labels: ['2026-06-01', '2026-06-02', '2026-06-03'],+ calls: [10, 0, 5],+ errors: [1, 0, 0],+ p50: [100, NaN, 50],+ p95: [200, NaN, 150],+ users: [2, 0, 1],+ sessions: [3, 0, 1],+ })+ })+})diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.tsindex a45fd72c5c86..ec0fe2347064 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts@@ -2,9 +2,9 @@ import { afterMount, kea, key, path, props, selectors } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'+import { dayjs } from 'lib/dayjs'-import { DataTableNode, HogQLQueryResponse, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'-import { BaseMathType, ChartDisplayType, PropertyFilterType, PropertyMathType } from '~/types'+import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'import type { mcpAnalyticsToolDetailLogicType } from './mcpAnalyticsToolDetailLogicType'@@ -15,8 +15,6 @@ export interface ToolSummary {p95_ms: number | nullusers: numberconversations: number- calls_prev: number- errors_prev: number}export interface DescriptionRevision {@@ -29,14 +27,68 @@ export interface IntentCoverage {total: number}+export interface DailyToolStat {+ day: string+ calls: number+ errors: number+ p50: number+ p95: number+ users: number+ sessions: number+}++export interface DailyChartData {+ labels: string[]+ calls: number[]+ errors: number[]+ p50: number[]+ p95: number[]+ users: number[]+ sessions: number[]+}++const EMPTY_CHART_DATA: DailyChartData = {+ labels: [],+ calls: [],+ errors: [],+ p50: [],+ p95: [],+ users: [],+ sessions: [],+}++export type ResultRows = unknown[][]++// Gap-fill the per-day rows into a continuous day axis (ClickHouse only returns days with data).+// Counts fill with 0; latency fills with NaN so the chart skips the point instead of dipping to 0.+export function buildDailyChartData(rows: DailyToolStat[]): DailyChartData {+ if (rows.length === 0) {+ return EMPTY_CHART_DATA+ }+ const byDay = new Map(rows.map((r) => [r.day, r]))+ const end = dayjs(rows[rows.length - 1].day)+ const labels: string[] = []+ for (let day = dayjs(rows[0].day); !day.isAfter(end); day = day.add(1, 'day')) {+ labels.push(day.format('YYYY-MM-DD'))+ }+ const at = labels.map((day) => byDay.get(day))+ return {+ labels,+ calls: at.map((r) => r?.calls ?? 0),+ errors: at.map((r) => r?.errors ?? 0),+ p50: at.map((r) => (r ? r.p50 : NaN)),+ p95: at.map((r) => (r ? r.p95 : NaN)),+ users: at.map((r) => r?.users ?? 0),+ sessions: at.map((r) => r?.sessions ?? 0),+ }+}+export interface MCPAnalyticsToolDetailLogicProps {toolName: string}const NEW_SDK_SOURCE = 'posthog_mcp_analytics'-const DATE_FROM_CURRENT = '-7d'-// HogQL expression that resolves to the *effective* tool name for new-SDK events:// the inner tool when the call went through the single-exec wrapper, otherwise// the directly-registered tool name. Use anywhere we need to filter/group by tool.@@ -49,6 +101,45 @@ function escapeHogQLString(value: string): string {return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}+// Standard "this tool, new-SDK only" filter shared by the mcp_tool_call queries.+function buildToolFilter(toolName: string): string {+ return `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}' AND ${NEW_SDK_FILTER}`+}++async function queryRows(query: string): Promise<ResultRows> {+ const response = (await api.query({ kind: NodeKind.HogQLQuery, query })) as HogQLQueryResponse+ return (response.results ?? []) as ResultRows+}++// Tools most often called immediately before/after this one within the same conversation.+function buildNeighborQuery(toolName: string, direction: 'before' | 'after'): string {+ const windowFn = direction === 'before' ? 'lagInFrame' : 'leadInFrame'+ return `+WITH tool_calls AS (+ SELECT+ coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)) AS conv_id,+ timestamp,+ ${EFFECTIVE_TOOL_HOGQL} AS tool+ FROM events+ WHERE event = 'mcp_tool_call'+ AND timestamp >= now() - INTERVAL 7 DAY+ AND ${NEW_SDK_FILTER}+ AND notEmpty(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)))+)+SELECT neighbor_tool, count() AS co_occurrences+FROM (+ SELECT+ tool,+ ${windowFn}(tool) OVER (PARTITION BY conv_id ORDER BY timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS neighbor_tool+ FROM tool_calls+)+WHERE tool = '${escapeHogQLString(toolName)}' AND neighbor_tool IS NOT NULL AND neighbor_tool != '' AND neighbor_tool != tool+GROUP BY neighbor_tool+ORDER BY co_occurrences DESC+LIMIT 5+`+}+export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>([path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsToolDetailLogic']),key((props: MCPAnalyticsToolDetailLogicProps) => props.toolName),@@ -59,22 +150,20 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(null as ToolSummary | null,{loadSummary: async (): Promise<ToolSummary | null> => {- const toolFilter = `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(props.toolName)}' AND ${NEW_SDK_FILTER}`+ const toolFilter = buildToolFilter(props.toolName)const response = (await api.query({kind: NodeKind.HogQLQuery,query: `SELECT- countIf(timestamp >= now() - INTERVAL 7 DAY) AS calls,- countIf(timestamp >= now() - INTERVAL 7 DAY AND toBool(properties.$mcp_is_error)) AS errors,- round(quantileIf(0.5)(toFloat(properties.$mcp_duration_ms), timestamp >= now() - INTERVAL 7 DAY)) AS p50_ms,- round(quantileIf(0.95)(toFloat(properties.$mcp_duration_ms), timestamp >= now() - INTERVAL 7 DAY)) AS p95_ms,- uniqIf(distinct_id, timestamp >= now() - INTERVAL 7 DAY) AS users,- uniqIf(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)), timestamp >= now() - INTERVAL 7 DAY) AS conversations,- countIf(timestamp >= now() - INTERVAL 14 DAY AND timestamp < now() - INTERVAL 7 DAY) AS calls_prev,- countIf(timestamp >= now() - INTERVAL 14 DAY AND timestamp < now() - INTERVAL 7 DAY AND toBool(properties.$mcp_is_error)) AS errors_prev+ count() AS calls,+ countIf(toBool(properties.$mcp_is_error)) AS errors,+ round(quantile(0.5)(toFloat(properties.$mcp_duration_ms))) AS p50_ms,+ round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_ms,+ uniq(distinct_id) AS users,+ uniq(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id))) AS conversationsFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL 14 DAY+ AND timestamp >= now() - INTERVAL 7 DAYAND ${toolFilter}`,})) as HogQLQueryResponse@@ -89,8 +178,6 @@ WHERE event = 'mcp_tool_call'p95_ms: row[3] == null ? null : Number(row[3]),users: Number(row[4]) || 0,conversations: Number(row[5]) || 0,- calls_prev: Number(row[6]) || 0,- errors_prev: Number(row[7]) || 0,}},},@@ -99,7 +186,7 @@ WHERE event = 'mcp_tool_call'[] as DescriptionRevision[],{loadDescriptions: async (): Promise<DescriptionRevision[]> => {- const toolFilter = `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(props.toolName)}' AND ${NEW_SDK_FILTER}`+ const toolFilter = buildToolFilter(props.toolName)const response = (await api.query({kind: NodeKind.HogQLQuery,query: `@@ -127,7 +214,7 @@ LIMIT 5null as IntentCoverage | null,{loadIntentCoverage: async (): Promise<IntentCoverage | null> => {- const toolFilter = `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(props.toolName)}' AND ${NEW_SDK_FILTER}`+ const toolFilter = buildToolFilter(props.toolName)const response = (await api.query({kind: NodeKind.HogQLQuery,query: `@@ -148,129 +235,70 @@ WHERE event = 'mcp_tool_call'},},],- })),-- selectors({- toolName: [() => [(_, props) => props.toolName], (toolName: string) => toolName],-- toolFilterClause: [- (s) => [s.toolName],- (toolName: string) => `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}' AND ${NEW_SDK_FILTER}`,- ],-- callsTrendQuery: [- (s) => [s.toolName],- (toolName: string): InsightVizNode => ({- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [- {- kind: NodeKind.EventsNode,- event: 'mcp_tool_call',- name: 'Calls',- math: BaseMathType.TotalCount,- properties: [- {- type: PropertyFilterType.HogQL,- key: `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}'`,- },- {- type: PropertyFilterType.HogQL,- key: NEW_SDK_FILTER,- },- ],- },- ],- breakdownFilter: {- breakdown_type: 'event',- breakdown: '$mcp_is_error',- },- trendsFilter: {- display: ChartDisplayType.ActionsLineGraph,- },- dateRange: { date_from: DATE_FROM_CURRENT, date_to: null },- },- }),- ],-- latencyTrendQuery: [- (s) => [s.toolName],- (toolName: string): 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',- properties: [- {- type: PropertyFilterType.HogQL,- key: `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}'`,- },- { type: PropertyFilterType.HogQL, key: NEW_SDK_FILTER },- ],- },- {- kind: NodeKind.EventsNode,- event: 'mcp_tool_call',- name: 'p50 duration (ms)',- math: PropertyMathType.Median,- math_property: '$mcp_duration_ms',- properties: [- {- type: PropertyFilterType.HogQL,- key: `${EFFECTIVE_TOOL_HOGQL} = '${escapeHogQLString(toolName)}'`,- },- { type: PropertyFilterType.HogQL, key: NEW_SDK_FILTER },- ],- },- ],- trendsFilter: { display: ChartDisplayType.ActionsLineGraph },- dateRange: { date_from: DATE_FROM_CURRENT, date_to: null },+ dailyStats: [+ [] as DailyToolStat[],+ {+ loadDailyStats: async (): Promise<DailyToolStat[]> => {+ const toolFilter = buildToolFilter(props.toolName)+ 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,+ uniq(distinct_id) AS users,+ uniq(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id))) AS sessions+FROM events+WHERE event = 'mcp_tool_call'+ AND timestamp >= now() - INTERVAL 30 DAY+ AND ${toolFilter}+GROUP BY day+ORDER BY day+`,+ })) as HogQLQueryResponse+ return (response.results ?? []).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),+ users: Number(r[5] ?? 0),+ sessions: Number(r[6] ?? 0),+ }))},- }),+ },],-- failuresQuery: [- (s) => [s.toolName],- (toolName: string): DataTableNode => ({- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query: `+ failureRows: [+ [] as ResultRows,+ {+ loadFailureRows: async (): Promise<ResultRows> =>+ queryRows(`SELECTsubstring(toString(properties.$exception_message), 1, 200) AS message,count() AS occurrences,max(timestamp) AS last_seen,arrayStringConcat(arraySort(arrayDistinct(groupArray(toString(properties.$mcp_client_name)))), ', ') AS harnessesFROM events+-- $exception events don't carry the new-SDK markers ($mcp_source / $mcp_exec_tool_call_name), so+-- unlike the mcp_tool_call queries this matches the raw $mcp_tool_name without EFFECTIVE_TOOL_HOGQL/NEW_SDK_FILTER.WHERE event = '$exception'AND timestamp >= now() - INTERVAL 7 DAY- AND toString(properties.$mcp_tool_name) = '${escapeHogQLString(toolName)}'+ AND toString(properties.$mcp_tool_name) = '${escapeHogQLString(props.toolName)}'AND notEmpty(toString(properties.$exception_message))GROUP BY messageORDER BY occurrences DESCLIMIT 20-`,- },- columns: ['message', 'occurrences', 'last_seen', 'harnesses'],- showSearch: false,- showOpenEditorButton: true,- }),+`),+ },],-- sampleIntentsQuery: [- (s) => [s.toolFilterClause],- (toolFilter): DataTableNode => ({- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query: `+ sampleIntentRows: [+ [] as ResultRows,+ {+ loadSampleIntentRows: async (): Promise<ResultRows> =>+ queryRows(`SELECTtimestamp,toString(properties.$mcp_intent) AS intent,@@ -279,112 +307,33 @@ SELECTFROM eventsWHERE event = 'mcp_tool_call'AND timestamp >= now() - INTERVAL 7 DAY- AND ${toolFilter}+ AND ${buildToolFilter(props.toolName)}AND notEmpty(toString(properties.$mcp_intent))AND toString(properties.$mcp_intent) != '{}'ORDER BY timestamp DESCLIMIT 5-`,- },- columns: ['timestamp', 'intent', 'source', 'harness'],- showSearch: false,- showOpenEditorButton: true,- }),+`),+ },],-- neighborsBeforeQuery: [- (s) => [s.toolName],- (toolName: string): DataTableNode => ({- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query: `-WITH tool_calls AS (- SELECT- coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)) AS conv_id,- timestamp,- ${EFFECTIVE_TOOL_HOGQL} AS tool- FROM events- WHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL 7 DAY- AND ${NEW_SDK_FILTER}- AND notEmpty(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)))-)-SELECT- prev_tool AS tool,- count() AS co_occurrences-FROM (- SELECT- conv_id,- tool,- lagInFrame(tool) OVER (PARTITION BY conv_id ORDER BY timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS prev_tool- FROM tool_calls-)-WHERE tool = '${escapeHogQLString(toolName)}'- AND prev_tool IS NOT NULL- AND prev_tool != ''- AND prev_tool != tool-GROUP BY prev_tool-ORDER BY co_occurrences DESC-LIMIT 5-`,- },- columns: ['tool', 'co_occurrences'],- showSearch: false,- showOpenEditorButton: true,- }),+ neighborsBeforeRows: [+ [] as ResultRows,+ {+ loadNeighborsBeforeRows: async (): Promise<ResultRows> =>+ queryRows(buildNeighborQuery(props.toolName, 'before')),+ },],-- neighborsAfterQuery: [- (s) => [s.toolName],- (toolName: string): DataTableNode => ({- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query: `-WITH tool_calls AS (- SELECT- coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)) AS conv_id,- timestamp,- ${EFFECTIVE_TOOL_HOGQL} AS tool- FROM events- WHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL 7 DAY- AND ${NEW_SDK_FILTER}- AND notEmpty(coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id)))-)-SELECT- next_tool AS tool,- count() AS co_occurrences-FROM (- SELECT- conv_id,- tool,- leadInFrame(tool) OVER (PARTITION BY conv_id ORDER BY timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next_tool- FROM tool_calls-)-WHERE tool = '${escapeHogQLString(toolName)}'- AND next_tool IS NOT NULL- AND next_tool != ''- AND next_tool != tool-GROUP BY next_tool-ORDER BY co_occurrences DESC-LIMIT 5-`,- },- columns: ['tool', 'co_occurrences'],- showSearch: false,- showOpenEditorButton: true,- }),+ neighborsAfterRows: [+ [] as ResultRows,+ {+ loadNeighborsAfterRows: async (): Promise<ResultRows> =>+ queryRows(buildNeighborQuery(props.toolName, 'after')),+ },],-- byHarnessQuery: [- (s) => [s.toolFilterClause],- (toolFilter): DataTableNode => ({- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query: `+ byHarnessRows: [+ [] as ResultRows,+ {+ loadByHarnessRows: async (): Promise<ResultRows> =>+ queryRows(`SELECTtoString(properties.$mcp_client_name) AS harness,count() AS calls,@@ -394,26 +343,19 @@ SELECTFROM eventsWHERE event = 'mcp_tool_call'AND timestamp >= now() - INTERVAL 7 DAY- AND ${toolFilter}+ AND ${buildToolFilter(props.toolName)}AND notEmpty(toString(properties.$mcp_client_name))GROUP BY harnessORDER BY calls DESCLIMIT 10-`,- },- columns: ['harness', 'calls', 'errors', 'error_rate_pct', 'users'],- showSearch: false,- showOpenEditorButton: true,- }),+`),+ },],-- topUsersQuery: [- (s) => [s.toolFilterClause],- (toolFilter): DataTableNode => ({- kind: NodeKind.DataTableNode,- source: {- kind: NodeKind.HogQLQuery,- query: `+ topUserRows: [+ [] as ResultRows,+ {+ loadTopUserRows: async (): Promise<ResultRows> =>+ queryRows(`SELECTargMax(tuple(distinct_id, person.created_at, person.properties), timestamp) AS person,count() AS calls,@@ -424,16 +366,21 @@ SELECTFROM eventsWHERE event = 'mcp_tool_call'AND timestamp >= now() - INTERVAL 7 DAY- AND ${toolFilter}+ AND ${buildToolFilter(props.toolName)}GROUP BY distinct_idORDER BY calls DESC-LIMIT 10-`,- },- columns: ['person', 'calls', 'errors', 'error_rate_pct', 'harnesses', 'last_seen'],- showSearch: false,- showOpenEditorButton: true,- }),+LIMIT 5+`),+ },+ ],+ })),++ selectors({+ toolName: [() => [(_, props) => props.toolName], (toolName: string) => toolName],++ dailyChartData: [+ (s) => [s.dailyStats],+ (dailyStats: DailyToolStat[]): DailyChartData => buildDailyChartData(dailyStats),],}),@@ -441,5 +388,12 @@ LIMIT 10actions.loadSummary()actions.loadDescriptions()actions.loadIntentCoverage()+ actions.loadDailyStats()+ actions.loadFailureRows()+ actions.loadSampleIntentRows()+ actions.loadNeighborsBeforeRows()+ actions.loadNeighborsAfterRows()+ actions.loadByHarnessRows()+ actions.loadTopUserRows()}),])diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsxindex c778084eb0d2..76175e70a92b 100644--- a/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx+++ b/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx@@ -1,15 +1,26 @@import { useActions, useValues } from 'kea'import { useRef } from 'react'-import { IconBolt, IconClock, IconRefresh, IconSparkles } from '@posthog/icons'-import { LemonButton, LemonSelect } from '@posthog/lemon-ui'+import { IconBolt, IconClock, IconRefresh, IconSearch, IconSparkles } from '@posthog/icons'+import {+ Button,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ InputGroupText,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Skeleton,+ Spinner,+} from '@posthog/quill-primitives'import { Resizer } from 'lib/components/Resizer/Resizer'import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'import { TZLabel } from 'lib/components/TZLabel'import { useWindowSize } from 'lib/hooks/useWindowSize'-import { LemonInput } from 'lib/lemon-ui/LemonInput'-import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { cn } from 'lib/utils/css-classes'import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'@@ -128,36 +139,54 @@ function SessionsListPanel(): JSX.Element {return (<div className="flex flex-col h-full min-h-0 overflow-hidden rounded border border-primary bg-surface-primary"><div className="shrink-0 flex flex-col gap-2 border-b border-primary p-2">- <LemonInput- type="search"- fullWidth- size="small"- placeholder="Search by session id, client, or tool"- onChange={(value) => setFilters({ search: value })}- value={filters.search}- />- <div className="flex items-center justify-between gap-2">- <LemonSelect- size="xsmall"- value={sortingToValue(sorting)}- options={SORT_OPTIONS}- onChange={(value) => setSorting(valueToSorting(value))}- data-attr="mcp-sessions-sort"- />- <LemonButton- type="secondary"- size="xsmall"- icon={<IconRefresh />}- onClick={() => loadSessions()}- loading={sessionsLoading}- tooltip="Reload sessions"- />+ <div className="flex flex-col gap-2" data-quill>+ <InputGroup className="w-full">+ <InputGroupAddon align="inline-start">+ <InputGroupText>+ <IconSearch />+ </InputGroupText>+ </InputGroupAddon>+ <InputGroupInput+ type="search"+ placeholder="Search by session id, client, or tool"+ onChange={(e) => setFilters({ search: e.target.value })}+ value={filters.search}+ />+ </InputGroup>+ <div className="flex items-center justify-between gap-2">+ <Select+ value={sortingToValue(sorting)}+ onValueChange={(value) => setSorting(valueToSorting(value as MCPSessionOrderBy))}+ >+ <SelectTrigger size="sm" data-attr="mcp-sessions-sort">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {SORT_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Button+ variant="outline"+ size="icon-sm"+ onClick={() => loadSessions()}+ disabled={sessionsLoading}+ title="Reload sessions"+ >+ {sessionsLoading ? <Spinner /> : <IconRefresh />}+ </Button>+ </div></div></div><div className="flex-1 min-h-0 overflow-y-auto" data-attr="mcp-sessions-list">{sessionsLoading && sessions.length === 0 ? (- <div className="flex flex-col gap-2 p-2">- <LemonSkeleton repeat={6} className="h-12 w-full" />+ <div className="flex flex-col gap-2 p-2" data-quill>+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} className="h-12 w-full" />+ ))}</div>) : sessions.length === 0 ? (<div className="p-4 text-center text-sm text-secondary">No MCP sessions yet</div>@@ -171,15 +200,16 @@ function SessionsListPanel(): JSX.Element {))}</ul>{hasNext ? (- <div className="flex justify-center py-2">- <LemonButton- type="secondary"- size="xsmall"+ <div className="flex justify-center py-2" data-quill>+ <Button+ variant="outline"+ size="sm"onClick={() => loadMoreSessions()}- loading={sessionsLoading}+ disabled={sessionsLoading}>+ {sessionsLoading ? <Spinner /> : null}Load more- </LemonButton>+ </Button></div>) : null}</>