: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): persist date filter from tool quality tab into tool report (#71090)
Georgis Andonis729c1e6de9cd
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsxindex 245b6a649d96..5f8974fec5f9 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx@@ -30,7 +30,6 @@ import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { humanFriendlyNumber } from 'lib/utils/numbers'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { teamLogic } from 'scenes/teamLogic'-import { urls } from 'scenes/urls'import { FeaturePreviewSceneGate } from '~/layout/scenes/components/FeaturePreviewSceneGate'import { SceneContent } from '~/layout/scenes/components/SceneContent'@@ -49,6 +48,7 @@ import {ToolSummary,mcpAnalyticsToolDetailLogic,} from './mcpAnalyticsToolDetailLogic'+import { mcpToolQualityUrlWithDates } from './mcpAnalyticsToolQualityLogic'export const scene: SceneExport<MCPAnalyticsToolDetailLogicProps> = {component: MCPAnalyticsToolDetail,@@ -116,7 +116,7 @@ function ResultTable({rows,loading,columns,- emptyMessage = 'No data for the last 7 days.',+ emptyMessage = 'No data for the selected date range.',}: {title?: React.ReactNodedescription?: React.ReactNode@@ -190,12 +190,9 @@ function SectionHeader({ title, subtitle }: { title: string; subtitle?: string })}-// 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.+// Coalesce latency gaps (NaN) to 0 so the sparkline draws a continuous line over the window.function spark(values: number[]): number[] {- return values.slice(-SPARKLINE_DAYS).map((v) => (Number.isFinite(v) ? v : 0))+ return values.map((v) => (Number.isFinite(v) ? v : 0))}function StatTiles({@@ -203,17 +200,19 @@ function StatTiles({loading,daily,theme,+ dateRangeLabel,}: {summary: ToolSummary | nullloading: booleandaily: DailyChartDatatheme: ChartTheme+ dateRangeLabel: string}): JSX.Element {const calls = summary?.calls ?? 0const errors = summary?.errors ?? 0const errorRate = calls ? (errors / calls) * 100 : 0const errorRateDaily = daily.calls.map((c, i) => (c ? (daily.errors[i] / c) * 100 : 0))- const sparkLabels = daily.labels.slice(-SPARKLINE_DAYS).map(formatBucketLabel)+ const sparkLabels = daily.labels.map(formatBucketLabel)const tiles: {label: string@@ -282,7 +281,7 @@ function StatTiles({loading={loading}labels={sparkLabels}theme={theme}- restingSubtitle="Last 7 days"+ restingSubtitle={dateRangeLabel}sparklineHeight={40}/>))}@@ -413,7 +412,7 @@ function TrendChart({<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.+ No data for the selected date range.</div>) : (<TimeSeriesLineChart@@ -459,6 +458,8 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.byHarnessRowsLoading,topUserRows,topUserRowsLoading,+ dateRangeLabel,+ dateFilter,} = useValues(mcpAnalyticsToolDetailLogic({ toolName }))const { timezone } = useValues(teamLogic)@@ -485,20 +486,26 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.resourceType={{ type: 'mcp_analytics' }}forceBackTo={{name: 'Tool quality',- path: urls.mcpAnalyticsToolQuality(),+ path: mcpToolQualityUrlWithDates(dateFilter),key: 'mcp-analytics-tool-quality',}}/><div className="flex flex-col gap-3 px-4 pb-4"><DescriptionBlock descriptions={descriptions} loading={descriptionsLoading} />- <StatTiles summary={summary} loading={summaryLoading} daily={dailyChartData} theme={theme} />+ <StatTiles+ summary={summary}+ loading={summaryLoading}+ daily={dailyChartData}+ theme={theme}+ dateRangeLabel={dateRangeLabel}+ /></div><LemonDivider /><div className="flex flex-col gap-3 px-4 pb-4">- <SectionHeader title="Reliability" subtitle="Last 30 days" />+ <SectionHeader title="Reliability" subtitle={dateRangeLabel} /><div className="grid grid-cols-1 lg:grid-cols-2 gap-4"><TrendCharttitle="Calls and errors"@@ -531,7 +538,7 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.action={<IntentCoverageTag coverage={intentCoverage} loading={intentCoverageLoading} />}rows={sampleIntentRows}loading={sampleIntentRowsLoading}- emptyMessage="No intents captured in the last 7 days."+ emptyMessage="No intents captured for the selected date range."columns={[{ header: 'When', render: (r) => <TZLabel time={String(r[0])} /> },{ header: 'Intent', expand: true, render: (r) => <span>{String(r[1] ?? '')}</span> },@@ -643,7 +650,7 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.description="Errored calls of this tool grouped by error type and HTTP status. Sourced from the $mcp_is_error flag on $mcp_tool_call events, the same source as the error rate above."rows={failureRows}loading={failureRowsLoading}- emptyMessage="No errored calls recorded for this tool in the last 7 days."+ emptyMessage="No errored calls recorded for this tool in the selected date range."columns={[{header: 'Error type',diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsxindex 66f4b017ce06..6a0789d5781d 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx@@ -8,10 +8,9 @@ import { TagsCombobox } from 'lib/components/Scenes/TagsCombobox'import { LinkPrimitive } from 'lib/lemon-ui/Link/Link'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { teamLogic } from 'scenes/teamLogic'-import { urls } from 'scenes/urls'import { McpDateFilter } from './components/McpDateFilter'-import { mcpAnalyticsToolQualityLogic } from './mcpAnalyticsToolQualityLogic'+import { mcpAnalyticsToolQualityLogic, mcpToolReportUrl } from './mcpAnalyticsToolQualityLogic'import { ToolQualityCharts } from './tool-quality/ToolQualityCharts'import { ToolQualityTable } from './tool-quality/ToolQualityTable'@@ -55,7 +54,7 @@ function FilterBar(): JSX.Element {}function ChartsScopeHeader(): JSX.Element {- const { selectedTool } = useValues(mcpAnalyticsToolQualityLogic)+ const { selectedTool, dateFilter } = useValues(mcpAnalyticsToolQualityLogic)const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)if (!selectedTool) {@@ -75,7 +74,7 @@ function ChartsScopeHeader(): JSX.Element {<Buttonvariant="outline"size="sm"- render={<LinkPrimitive to={urls.mcpAnalyticsTool(selectedTool)} />}+ render={<LinkPrimitive to={mcpToolReportUrl(selectedTool, dateFilter)} />}data-attr="mcp-tool-quality-full-report">Full tool reportdiff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.tsindex 67f2ce196ec5..794f078f17c2 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts@@ -1,10 +1,15 @@-import { afterMount, kea, key, path, props, selectors } from 'kea'+import { actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { urlToAction } from 'kea-router'import api from 'lib/api'import { dayjs } from 'lib/dayjs'+import { dateFilterToText, dateStringToDayJs } from 'lib/utils/dateFilters'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import {+ DateRange,MCPHarnessBreakdownItem,MCPToolDailyStatItem,MCPToolDescriptionItem,@@ -97,20 +102,27 @@ export interface MCPAnalyticsToolDetailLogicProps {toolName: string}-// Absolute from/to for an exact N*24h window. A relative '-Nd' would be rounded to the start-// of the day by the backend's QueryDateRange, widening the window and letting per-section-// counts drift apart after midnight; the sections must share one window to stay consistent.-function windowDays(days: number): { date_from: string; date_to: string } {- return { date_from: dayjs().subtract(days, 'day').toISOString(), date_to: dayjs().toISOString() }+export interface DateFilter {+ dateFrom: string | null+ dateTo: string | null}+// The window carries over from the Tool quality tab via date_from / date_to search params+// (see mcpAnalyticsToolQualityLogic). Without them — e.g. opening a tool page directly — we+// default to the last 30 days.+const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-30d', dateTo: null }+// Tools most often called immediately before/after this one within the same conversation.-async function neighborRows(toolName: string, direction: 'before' | 'after'): Promise<ResultRows> {+async function neighborRows(+ toolName: string,+ direction: 'before' | 'after',+ dateRange: DateRange+): Promise<ResultRows> {const response = (await api.query({kind: NodeKind.MCPToolNeighborsQuery,toolName,neighborDirection: direction,- dateRange: windowDays(7),+ dateRange,})) as { results?: MCPToolNeighborItem[] }return (response?.results ?? []).map((r) => [r.neighbor_tool, r.co_occurrences])}@@ -120,7 +132,21 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(key((props: MCPAnalyticsToolDetailLogicProps) => props.toolName),props({} as MCPAnalyticsToolDetailLogicProps),- loaders(({ props }) => ({+ actions({+ setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ loadAllSections: true,+ }),++ reducers({+ dateFilter: [+ DEFAULT_DATE_FILTER,+ {+ setDateFilter: (_, { dateFrom, dateTo }): DateFilter => ({ dateFrom, dateTo }),+ },+ ],+ }),++ loaders(({ props, values }) => ({summary: [null as ToolSummary | null,{@@ -128,7 +154,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(const response = (await api.query({kind: NodeKind.MCPToolStatsQuery,toolName: props.toolName,- dateRange: windowDays(7),+ dateRange: values.dateRange,})) as { results?: MCPToolStatsItem[] }const row = response?.results?.[0]if (!row) {@@ -152,7 +178,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(const response = (await api.query({kind: NodeKind.MCPToolDescriptionsQuery,toolName: props.toolName,- dateRange: windowDays(30),+ dateRange: values.dateRange,})) as { results?: MCPToolDescriptionItem[] }return (response?.results ?? []).map((r) => ({description: r.description,@@ -169,7 +195,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(const response = (await api.query({kind: NodeKind.MCPToolStatsQuery,toolName: props.toolName,- dateRange: windowDays(7),+ dateRange: values.dateRange,})) as { results?: MCPToolStatsItem[] }const row = response?.results?.[0]if (!row) {@@ -186,7 +212,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(const response = (await api.query({kind: NodeKind.MCPToolDailyStatsQuery,toolName: props.toolName,- dateRange: windowDays(30),+ dateRange: values.dateRange,})) as { results?: MCPToolDailyStatItem[] }return (response?.results ?? []).map((r) => ({day: r.day,@@ -207,7 +233,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(const response = (await api.query({kind: NodeKind.MCPToolFailuresQuery,toolName: props.toolName,- dateRange: windowDays(7),+ dateRange: values.dateRange,})) as { results?: MCPToolFailureItem[] }return (response?.results ?? []).map((r) => [r.message, r.occurrences, r.last_seen, r.harnesses])},@@ -220,7 +246,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(const response = (await api.query({kind: NodeKind.MCPToolSampleIntentsQuery,toolName: props.toolName,- dateRange: windowDays(7),+ dateRange: values.dateRange,})) as { results?: MCPToolSampleIntentItem[] }return (response?.results ?? []).map((r) => [r.timestamp, r.intent, r.intent_source, r.harness])},@@ -229,13 +255,15 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(neighborsBeforeRows: [[] as ResultRows,{- loadNeighborsBeforeRows: async (): Promise<ResultRows> => neighborRows(props.toolName, 'before'),+ loadNeighborsBeforeRows: async (): Promise<ResultRows> =>+ neighborRows(props.toolName, 'before', values.dateRange),},],neighborsAfterRows: [[] as ResultRows,{- loadNeighborsAfterRows: async (): Promise<ResultRows> => neighborRows(props.toolName, 'after'),+ loadNeighborsAfterRows: async (): Promise<ResultRows> =>+ neighborRows(props.toolName, 'after', values.dateRange),},],byHarnessRows: [@@ -247,7 +275,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(const response = (await api.query({kind: NodeKind.MCPHarnessBreakdownQuery,toolName: props.toolName,- dateRange: windowDays(7),+ dateRange: values.dateRange,})) as { results?: MCPHarnessBreakdownItem[] }return (response?.results ?? []).map((r) => [r.harness,@@ -267,7 +295,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(const response = (await api.query({kind: NodeKind.MCPToolTopUsersQuery,toolName: props.toolName,- dateRange: windowDays(7),+ dateRange: values.dateRange,})) as { results?: MCPToolTopUserItem[] }return (response?.results ?? []).map((r) => [[r.distinct_id, '', r.person_properties],@@ -289,18 +317,58 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>((s) => [s.dailyStats],(dailyStats: DailyToolStat[]): DailyChartData => buildDailyChartData(dailyStats),],- }),- afterMount(({ actions }) => {- actions.loadSummary()- actions.loadDescriptions()- actions.loadIntentCoverage()- actions.loadDailyStats()- actions.loadFailureRows()- actions.loadSampleIntentRows()- actions.loadNeighborsBeforeRows()- actions.loadNeighborsAfterRows()- actions.loadByHarnessRows()- actions.loadTopUserRows()+ // Resolve the `dateFilter` state (camelCase, nullable, may be relative like '-30d') into the+ // absolute snake_case `DateRange` the query API takes. Done once so every section queries the+ // exact same window — a relative '-Nd' would re-resolve per section and drift after midnight.+ dateRange: [+ (s) => [s.dateFilter, teamLogic.selectors.timezone],+ (dateFilter: DateFilter, timezone: string): DateRange => {+ const to = dateStringToDayJs(dateFilter.dateTo, timezone) ?? dayjs().tz(timezone)+ const from =+ dateStringToDayJs(dateFilter.dateFrom, timezone) ?? dayjs().tz(timezone).subtract(30, 'day')+ return { date_from: from.toISOString(), date_to: to.toISOString() }+ },+ ],++ dateRangeLabel: [+ (s) => [s.dateFilter],+ (dateFilter: DateFilter): string =>+ dateFilterToText(dateFilter.dateFrom, dateFilter.dateTo, 'the selected range') ?? 'the selected range',+ ],}),++ listeners(({ actions }) => ({+ loadAllSections: () => {+ actions.loadSummary()+ actions.loadDescriptions()+ actions.loadIntentCoverage()+ actions.loadDailyStats()+ actions.loadFailureRows()+ actions.loadSampleIntentRows()+ actions.loadNeighborsBeforeRows()+ actions.loadNeighborsAfterRows()+ actions.loadByHarnessRows()+ actions.loadTopUserRows()+ },+ })),++ // The window rides along in the URL from the Tool quality tab. Reading it here (rather than once+ // in afterMount) keeps the page in sync when only date_from / date_to change for the same tool —+ // e.g. browser back/forward — since the logic is keyed by toolName and wouldn't remount.+ urlToAction(({ actions, values, cache }) => ({+ [`${urls.mcpAnalyticsToolQuality()}/:toolName`]: (_, searchParams) => {+ const dateFrom =+ typeof searchParams.date_from === 'string' ? searchParams.date_from : DEFAULT_DATE_FILTER.dateFrom+ const dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : null+ const dateChanged = dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo+ if (dateChanged) {+ actions.setDateFilter(dateFrom, dateTo)+ }+ if (dateChanged || !cache.hasLoaded) {+ actions.loadAllSections()+ }+ cache.hasLoaded = true+ },+ })),])diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex 900a93c90635..781e446d5af6 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -1,6 +1,6 @@import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { actionToUrl, router, urlToAction } from 'kea-router'+import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'import api from 'lib/api'import { dayjs } from 'lib/dayjs'@@ -66,6 +66,30 @@ export interface DateFilter {dateTo: string | null}+// Carry the selected window across navigation as date_from / date_to, mirroring the tab's+// actionToUrl. Only set them when present so a cleared range stays out of the URL.+export function mcpDateSearchParams(dateFilter: DateFilter): Record<string, string> {+ const params: Record<string, string> = {}+ if (dateFilter.dateFrom) {+ params.date_from = dateFilter.dateFrom+ }+ if (dateFilter.dateTo) {+ params.date_to = dateFilter.dateTo+ }+ return params+}++// Link from the Tool quality tab to an individual tool's report, keeping the date filter so+// the tool page opens on the same window.+export function mcpToolReportUrl(tool: string, dateFilter: DateFilter): string {+ return combineUrl(urls.mcpAnalyticsTool(tool), mcpDateSearchParams(dateFilter)).url+}++// Link back from a tool report to the Tool quality tab, restoring the date filter.+export function mcpToolQualityUrlWithDates(dateFilter: DateFilter): string {+ return combineUrl(urls.mcpAnalyticsToolQuality(), mcpDateSearchParams(dateFilter)).url+}+export interface ToolQualityRow {tool: stringtotal_calls: numberdiff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsxindex 51adbb28556c..ce379c2d2118 100644--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx@@ -27,10 +27,14 @@ import { LinkPrimitive } from 'lib/lemon-ui/Link/Link'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { formatPercentage } from 'lib/utils/numbers'import { pluralize } from 'lib/utils/strings'-import { urls } from 'scenes/urls'import { formatMs, formatNumber } from '../dashboard/formatters'-import { type SortState, type ToolQualityRow, mcpAnalyticsToolQualityLogic } from '../mcpAnalyticsToolQualityLogic'+import {+ type SortState,+ type ToolQualityRow,+ mcpAnalyticsToolQualityLogic,+ mcpToolReportUrl,+} from '../mcpAnalyticsToolQualityLogic'const DESTRUCTIVE_ERROR_PCT = 5@@ -113,7 +117,7 @@ function SortableHead({}function ToolRows(): JSX.Element {- const { filteredRows, toolRowsLoading, selectedTool } = useValues(mcpAnalyticsToolQualityLogic)+ const { filteredRows, toolRowsLoading, selectedTool, dateFilter } = useValues(mcpAnalyticsToolQualityLogic)const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)if (toolRowsLoading && filteredRows.length === 0) {@@ -163,7 +167,7 @@ function ToolRows(): JSX.Element {<Buttonvariant="outline"size="sm"- render={<LinkPrimitive to={urls.mcpAnalyticsTool(row.tool)} />}+ render={<LinkPrimitive to={mcpToolReportUrl(row.tool, dateFilter)} />}onClick={(e) => e.stopPropagation()}data-attr="mcp-tool-quality-full-report">