Skip to content

: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.

fix(mcp-analytics): render tool report charts across the selected window (#71435)

Georgis Andonisa1cb6ab2f388
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 0685b422c58b..d7e97ad53bee 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -28407,11 +28407,15 @@
},
"MCPToolDailyStatsQuery": {
"additionalProperties": false,
- "description": "Per-day activity series for a single MCP tool over the last 30 days.",
+ "description": "Per-bucket activity series for a single MCP tool over the selected window.",
"properties": {
"dateRange": {
"$ref": "#/definitions/DateRange"
},
+ "interval": {
+ "$ref": "#/definitions/IntervalType",
+ "description": "Bucket granularity for the series. The frontend passes getDefaultInterval so a sub-day window buckets by hour/minute instead of collapsing to a single day point. Defaults to day."
+ },
"kind": {
"const": "MCPToolDailyStatsQuery",
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 5cfaf4ad6cd1..99fa04721fff 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2789,12 +2789,15 @@ export interface MCPToolDailyStatsQueryResponse extends AnalyticsQueryResponseBa
results: MCPToolDailyStatItem[]
}
-/** Per-day activity series for a single MCP tool over the last 30 days. */
+/** Per-bucket activity series for a single MCP tool over the selected window. */
export interface MCPToolDailyStatsQuery extends DataNode<MCPToolDailyStatsQueryResponse> {
kind: NodeKind.MCPToolDailyStatsQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
dateRange?: DateRange
+ /** Bucket granularity for the series. The frontend passes getDefaultInterval so a sub-day window
+ * buckets by hour/minute instead of collapsing to a single day point. Defaults to day. */
+ interval?: IntervalType
}
export type CachedMCPToolDailyStatsQueryResponse = CachedQueryResponse<MCPToolDailyStatsQueryResponse>
diff --git a/posthog/schema.py b/posthog/schema.py
index 2c932e653e95..530ae19ce1d2 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -24186,6 +24186,14 @@ class MCPToolDailyStatsQuery(BaseModel):
extra="forbid",
)
dateRange: DateRange | None = None
+ interval: IntervalType | None = Field(
+ default=None,
+ description=(
+ "Bucket granularity for the series. The frontend passes getDefaultInterval"
+ " so a sub-day window buckets by hour/minute instead of collapsing to a"
+ " single day point. Defaults to day."
+ ),
+ )
kind: Literal["MCPToolDailyStatsQuery"] = "MCPToolDailyStatsQuery"
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
response: MCPToolDailyStatsQueryResponse | None = None
diff --git a/products/mcp_analytics/backend/hogql_queries/tool_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_tables.py
index 5c8beb0b1a9c..00e95a858ed9 100644
--- a/products/mcp_analytics/backend/hogql_queries/tool_tables.py
+++ b/products/mcp_analytics/backend/hogql_queries/tool_tables.py
@@ -375,10 +375,17 @@ class MCPToolDailyStatsQueryRunner(AnalyticsQueryRunner[MCPToolDailyStatsQueryRe
return mcp_query_date_range(self.team, self.query.dateRange)
def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ # Bucket granularity comes from the frontend's getDefaultInterval, so a sub-day window buckets
+ # by hour/minute instead of collapsing to a single day point. dateTrunc respects the team
+ # timezone, so the buckets line up with the frontend's gap-fill keys. Defaults to day.
+ # Explicit generous LIMIT so a fine interval over a wide window (reachable via the interval
+ # field, e.g. hourly over a quarter from an MCP caller) isn't silently cut to the default 100
+ # rows — which, with ORDER BY day ASC, would drop the most recent buckets.
+ interval = self.query.interval.value if self.query.interval else "day"
return parse_select(
"""
SELECT
- toString(toDate(timestamp)) AS day,
+ toString(dateTrunc({interval}, timestamp)) AS day,
count() AS calls,
{_IS_ERROR} AS errors,
{_P50} AS p50,
@@ -389,8 +396,10 @@ class MCPToolDailyStatsQueryRunner(AnalyticsQueryRunner[MCPToolDailyStatsQueryRe
WHERE {where}
GROUP BY day
ORDER BY day
+ LIMIT 10000
""",
placeholders={
+ "interval": ast.Constant(value=interval),
"_CONVERSATION_ID": parse_expr(_CONVERSATION_ID),
"_IS_ERROR": parse_expr(_IS_ERROR),
"_P50": parse_expr(_P50),
diff --git a/products/mcp_analytics/backend/tests/test_tool_tables.py b/products/mcp_analytics/backend/tests/test_tool_tables.py
index 9f34f6df0e4e..95646d2e8958 100644
--- a/products/mcp_analytics/backend/tests/test_tool_tables.py
+++ b/products/mcp_analytics/backend/tests/test_tool_tables.py
@@ -7,6 +7,7 @@ from parameterized import parameterized
from posthog.schema import (
DateRange,
+ IntervalType,
MCPToolDailyStatsQuery,
MCPToolDescriptionsQuery,
MCPToolFailuresQuery,
@@ -337,6 +338,27 @@ class TestMCPToolDailyStatsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickho
assert rows[1].calls == 2
assert rows[1].sessions == 2
+ def test_buckets_by_hour_when_interval_is_hour(self) -> None:
+ # Two calls in the same day but different hours split into two hourly buckets — a sub-day
+ # window would otherwise collapse to a single day point. Guards the interval plumbing.
+ now = datetime.now(tz=UTC)
+ _emit_tool_call(self.team, distinct_id="d1", session_id="s1", timestamp=now - timedelta(hours=1, minutes=30))
+ _emit_tool_call(self.team, distinct_id="d2", session_id="s2", timestamp=now - timedelta(minutes=5))
+ flush_persons_and_events()
+
+ runner = MCPToolDailyStatsQueryRunner(
+ query=MCPToolDailyStatsQuery(
+ toolName="query_run", dateRange=DateRange(date_from="-6h"), interval=IntervalType.HOUR
+ ),
+ team=self.team,
+ )
+ rows = runner.calculate().results
+
+ assert len(rows) == 2
+ assert rows[0].day < rows[1].day
+ assert rows[0].calls == 1
+ assert rows[1].calls == 1
+
class TestMCPToolDescriptionsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
def _run(self, tool_name: str = "query_run") -> list[Any]:
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
index 4dd83d59e61f..958f39f4616f 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
@@ -350,8 +350,10 @@ const meta: Meta = {
return [200, { results: SESSION_RESULTS }]
}
// Tool quality tab queries — checked before the dashboard's
- // p95 tool table so the more specific markers win.
- if (query.includes('toDate(timestamp) AS day')) {
+ // p95 tool table so the more specific markers win. The daily series
+ // buckets by dateTrunc at the active interval; `AS day,` + the p99
+ // quantile uniquely identify it (the per-tool table has neither).
+ if (query.includes('quantile(0.99)') && query.includes('AS day,')) {
return [200, { results: DAILY_STATS }]
}
if (query.includes('p99_duration_ms')) {
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
index 5f8974fec5f9..4f6b2e5d9084 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -6,6 +6,7 @@ import { LemonDivider, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import {
type ChartTheme,
type Series,
+ type TimeInterval,
TimeSeriesLineChart,
type TimeSeriesLineChartConfig,
} from '@posthog/quill-charts'
@@ -36,7 +37,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { SceneExport } from '~/scenes/sceneTypes'
-import { formatBucketLabel, formatMs, formatMsAsSeconds } from './dashboard/formatters'
+import { formatMs, formatMsAsSeconds } from './dashboard/formatters'
import { HarnessLogo, HarnessPill } from './dashboard/harness'
import { MetricTile } from './dashboard/MetricTile'
import { mcpAnalyticsFeaturePreviewGate } from './featurePreviewGate'
@@ -49,6 +50,7 @@ import {
mcpAnalyticsToolDetailLogic,
} from './mcpAnalyticsToolDetailLogic'
import { mcpToolQualityUrlWithDates } from './mcpAnalyticsToolQualityLogic'
+import { formatBucketLabel } from './timeBuckets'
export const scene: SceneExport<MCPAnalyticsToolDetailLogicProps> = {
component: MCPAnalyticsToolDetail,
@@ -201,18 +203,20 @@ function StatTiles({
daily,
theme,
dateRangeLabel,
+ interval,
}: {
summary: ToolSummary | null
loading: boolean
daily: DailyChartData
theme: ChartTheme
dateRangeLabel: string
+ interval: TimeInterval
}): JSX.Element {
const calls = summary?.calls ?? 0
const errors = summary?.errors ?? 0
const errorRate = calls ? (errors / calls) * 100 : 0
const errorRateDaily = daily.calls.map((c, i) => (c ? (daily.errors[i] / c) * 100 : 0))
- const sparkLabels = daily.labels.map(formatBucketLabel)
+ const sparkLabels = daily.labels.map((label) => formatBucketLabel(label, interval))
const tiles: {
label: string
@@ -357,7 +361,11 @@ function DescriptionBlock({
)
}
-function trendChartConfig(timezone: string, yAxis?: TimeSeriesLineChartConfig['yAxis']): TimeSeriesLineChartConfig {
+function trendChartConfig(
+ timezone: string,
+ interval: TimeInterval,
+ yAxis?: TimeSeriesLineChartConfig['yAxis']
+): TimeSeriesLineChartConfig {
return {
curve: 'monotone',
showAxisLines: true,
@@ -365,7 +373,7 @@ function trendChartConfig(timezone: string, yAxis?: TimeSeriesLineChartConfig['y
showCrosshair: true,
showGrid: true,
yAxis,
- xAxis: { interval: 'day', timezone },
+ xAxis: { interval, timezone },
tooltip: { placement: 'cursor' },
}
}
@@ -460,6 +468,7 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.
topUserRowsLoading,
dateRangeLabel,
dateFilter,
+ interval,
} = useValues(mcpAnalyticsToolDetailLogic({ toolName }))
const { timezone } = useValues(teamLogic)
@@ -472,10 +481,10 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.
() => seriesFor(dailyChartData, theme, ['p50', 'p95']),
[dailyChartData, theme]
)
- const countsConfig = useChartConfig(() => trendChartConfig(timezone), [timezone])
+ const countsConfig = useChartConfig(() => trendChartConfig(timezone, interval), [timezone, interval])
const latencyConfig = useChartConfig(
- () => trendChartConfig(timezone, { tickFormatter: formatMsAsSeconds }),
- [timezone]
+ () => trendChartConfig(timezone, interval, { tickFormatter: formatMsAsSeconds }),
+ [timezone, interval]
)
return (
@@ -499,6 +508,7 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.
daily={dailyChartData}
theme={theme}
dateRangeLabel={dateRangeLabel}
+ interval={interval}
/>
</div>
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx
index 6a0789d5781d..a3140e4fb6f6 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx
@@ -93,7 +93,7 @@ function ChartsScopeHeader(): JSX.Element {
}
export function MCPAnalyticsToolQuality(): JSX.Element {
- const { dailyChartData, dailyStatsLoading } = useValues(mcpAnalyticsToolQualityLogic)
+ const { dailyChartData, dailyStatsLoading, interval } = useValues(mcpAnalyticsToolQualityLogic)
const { timezone } = useValues(teamLogic)
const theme = useChartTheme()
@@ -102,7 +102,13 @@ export function MCPAnalyticsToolQuality(): JSX.Element {
<div className="flex flex-col gap-4" data-quill>
<FilterBar />
<ChartsScopeHeader />
- <ToolQualityCharts data={dailyChartData} loading={dailyStatsLoading} theme={theme} timezone={timezone} />
+ <ToolQualityCharts
+ data={dailyChartData}
+ loading={dailyStatsLoading}
+ theme={theme}
+ timezone={timezone}
+ interval={interval}
+ />
<ToolQualityTable />
</div>
)
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts
index 29e8a7d7fca4..12514c97f276 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts
@@ -13,8 +13,8 @@ function stat(overrides: Partial<DailyToolStat> & { day: string }): DailyToolSta
}
describe('buildDailyChartData', () => {
- it('returns empty series for no rows', () => {
- expect(buildDailyChartData([])).toEqual({
+ it('returns empty series for no rows, so the empty state shows', () => {
+ expect(buildDailyChartData([], ['2026-06-01 00:00:00'])).toEqual({
labels: [],
calls: [],
errors: [],
@@ -25,32 +25,32 @@ describe('buildDailyChartData', () => {
})
})
- 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],
+ // Guards the "sparklines lose their line" regression: with one active day, projecting onto the
+ // full window's day keys pads the axis out (counts→0, latency→NaN) so the line still renders.
+ it('projects rows onto day bucket keys, padding empty days', () => {
+ const rows = [stat({ day: '2026-06-03', calls: 5, errors: 0, p50: 50, p95: 150, users: 1, sessions: 1 })]
+ const keys = ['2026-06-01 00:00:00', '2026-06-02 00:00:00', '2026-06-03 00:00:00', '2026-06-04 00:00:00']
+ expect(buildDailyChartData(rows, keys)).toEqual({
+ labels: keys,
+ calls: [0, 0, 5, 0],
+ errors: [0, 0, 0, 0],
+ p50: [NaN, NaN, 50, NaN],
+ p95: [NaN, NaN, 150, NaN],
+ users: [0, 0, 1, 0],
+ sessions: [0, 0, 1, 0],
})
})
- it('gap-fills interior missing days (counts→0, latency→NaN) with a contiguous day axis', () => {
+ // Sub-day windows bucket by hour: hourly rows must line up with hourly keys, so "12 hours
+ // collapses to a single point" can't come back.
+ it('lines up hourly rows with hourly bucket keys', () => {
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 }),
+ stat({ day: '2026-06-03 10:00:00', calls: 12, errors: 2, p50: 80, p95: 200, users: 4, sessions: 5 }),
]
- 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],
- })
+ const keys = ['2026-06-03 09:00:00', '2026-06-03 10:00:00', '2026-06-03 11:00:00']
+ const data = buildDailyChartData(rows, keys)
+ expect(data.calls).toEqual([0, 12, 0])
+ expect(data.p95).toEqual([NaN, 200, NaN])
+ expect(data.sessions).toEqual([0, 5, 0])
})
})
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
index 794f078f17c2..ba506a44c648 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
@@ -4,7 +4,7 @@ import { urlToAction } from 'kea-router'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { dateFilterToText, dateStringToDayJs } from 'lib/utils/dateFilters'
+import { dateFilterToText, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -20,8 +20,10 @@ import {
MCPToolTopUserItem,
NodeKind,
} from '~/queries/schema/schema-general'
+import { IntervalType } from '~/types'
import type { mcpAnalyticsToolDetailLogicType } from './mcpAnalyticsToolDetailLogicType'
+import { buildBucketKeys, normalizeBucket } from './timeBuckets'
export interface ToolSummary {
calls: number
@@ -74,21 +76,20 @@ const EMPTY_CHART_DATA: DailyChartData = {
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 {
+// Project the per-bucket rows onto the full set of interval buckets spanning the selected window
+// (ClickHouse only returns buckets with data). `bucketKeys` covers the whole window at the active
+// interval so the sparklines and trend charts match the chosen range — and always have enough points
+// to draw a line — even when the tool has data on only a bucket or two. Counts fill with 0; latency
+// fills with NaN so the chart skips the point instead of dipping to 0. Rows match by normalized
+// bucket key, so day, hour, and minute intervals all line up. No rows at all keeps the empty state.
+export function buildDailyChartData(rows: DailyToolStat[], bucketKeys: string[]): 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))
+ const byBucket = new Map(rows.map((r) => [normalizeBucket(r.day), r]))
+ const at = bucketKeys.map((k) => byBucket.get(k))
return {
- labels,
+ labels: bucketKeys,
calls: at.map((r) => r?.calls ?? 0),
errors: at.map((r) => r?.errors ?? 0),
p50: at.map((r) => (r ? r.p50 : NaN)),
@@ -208,12 +209,17 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
dailyStats: [
[] as DailyToolStat[],
{
- loadDailyStats: async (): Promise<DailyToolStat[]> => {
+ // Guarded with breakpoint: dailyChartData builds its bucket keys from the *live* interval,
+ // so a superseded response fetched at a different interval (e.g. day → hour on a fast
+ // back/forward) would otherwise land and collapse a day's rows into one hourly bucket.
+ loadDailyStats: async (_: void, breakpoint): Promise<DailyToolStat[]> => {
const response = (await api.query({
kind: NodeKind.MCPToolDailyStatsQuery,
toolName: props.toolName,
dateRange: values.dateRange,
+ interval: values.interval,
})) as { results?: MCPToolDailyStatItem[] }
+ breakpoint()
return (response?.results ?? []).map((r) => ({
day: r.day,
calls: r.calls,
@@ -314,8 +320,23 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
toolName: [() => [(_, props) => props.toolName], (toolName: string) => toolName],
dailyChartData: [
- (s) => [s.dailyStats],
- (dailyStats: DailyToolStat[]): DailyChartData => buildDailyChartData(dailyStats),
+ (s) => [s.dailyStats, s.dateFilter, s.interval, teamLogic.selectors.timezone],
+ (
+ dailyStats: DailyToolStat[],
+ dateFilter: DateFilter,
+ interval: IntervalType,
+ timezone: string
+ ): DailyChartData => {
+ const bucketKeys = buildBucketKeys(dateFilter.dateFrom, dateFilter.dateTo, timezone, interval)
+ return buildDailyChartData(dailyStats, bucketKeys)
+ },
+ ],
+
+ // Grouping interval for the daily series — PostHog's standard auto-choice, matching the query's
+ // dateTrunc so a sub-day window buckets by hour/minute instead of collapsing to one day point.
+ interval: [
+ (s) => [s.dateFilter],
+ (dateFilter: DateFilter): IntervalType => getDefaultInterval(dateFilter.dateFrom, dateFilter.dateTo),
],
// Resolve the `dateFilter` state (camelCase, nullable, may be relative like '-30d') into the
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts
index eee8cc53b015..d3d3cb3ef822 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts
@@ -20,39 +20,37 @@ function dailyStat(overrides: Partial<DailyToolStat> & { day: string }): DailyTo
describe('mcpAnalyticsToolQualityLogic', () => {
describe('buildDailyChartData', () => {
- it('fills missing days so the x-axis stays linear', () => {
- const data = buildDailyChartData([
- dailyStat({ day: '2026-06-05', calls: 100, errors: 10, p50: 200, p95: 900, p99: 2100 }),
- dailyStat({ day: '2026-06-07', calls: 50, errors: 0, p50: 150, p95: 800, p99: 1500 }),
- ])
- expect(data.labels).toEqual(['2026-06-05', '2026-06-06', '2026-06-07'])
+ it('projects rows onto the bucket keys, zero/NaN-filling gaps', () => {
+ const data = buildDailyChartData(
+ [
+ dailyStat({ day: '2026-06-05', calls: 100, errors: 10, p50: 200, p95: 900, p99: 2100 }),
+ dailyStat({ day: '2026-06-07', calls: 50, errors: 0, p50: 150, p95: 800, p99: 1500 }),
+ ],
+ ['2026-06-05 00:00:00', '2026-06-06 00:00:00', '2026-06-07 00:00:00']
+ )
+ expect(data.labels).toEqual(['2026-06-05 00:00:00', '2026-06-06 00:00:00', '2026-06-07 00:00:00'])
expect(data.calls).toEqual([100, 0, 50])
expect(data.errors).toEqual([10, 0, 0])
- // Gap days get NaN (skipped by the chart), not a dip to zero.
+ // Gap buckets get NaN (skipped by the chart), not a dip to zero.
expect(data.successRate[0]).toBeCloseTo(90)
expect(data.successRate[1]).toBeNaN()
expect(data.p99).toEqual([2100, NaN, 1500])
})
- it('returns empty series for no rows', () => {
- expect(buildDailyChartData([]).labels).toEqual([])
+ it('returns empty series for empty bucket keys', () => {
+ expect(buildDailyChartData([], []).labels).toEqual([])
})
- it('spans the full range when given one, zero-filling days outside the data', () => {
+ // Sub-day windows bucket by hour: rows keyed to an hour must line up with hourly keys, so the
+ // "12 hours collapses to a single point" bug can't come back.
+ it('lines up hourly rows with hourly bucket keys', () => {
const data = buildDailyChartData(
- [dailyStat({ day: '2026-06-07', calls: 50, errors: 0, p50: 150, p95: 800, p99: 1500 })],
- { start: '2026-06-05', end: '2026-06-08' }
+ [dailyStat({ day: '2026-06-07 10:00:00', calls: 12, errors: 3, p50: 80, p95: 200, p99: 400 })],
+ ['2026-06-07 09:00:00', '2026-06-07 10:00:00', '2026-06-07 11:00:00']
)
- expect(data.labels).toEqual(['2026-06-05', '2026-06-06', '2026-06-07', '2026-06-08'])
- expect(data.calls).toEqual([0, 0, 50, 0])
- expect(data.successRate[0]).toBeNaN()
- expect(data.successRate[2]).toBeCloseTo(100)
- })
-
- it('zero-fills the whole range when there is no data at all', () => {
- const data = buildDailyChartData([], { start: '2026-06-05', end: '2026-06-07' })
- expect(data.labels).toEqual(['2026-06-05', '2026-06-06', '2026-06-07'])
- expect(data.calls).toEqual([0, 0, 0])
+ expect(data.calls).toEqual([0, 12, 0])
+ expect(data.errors).toEqual([0, 3, 0])
+ expect(data.successRate[1]).toBeCloseTo(75)
})
})
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
index 781e446d5af6..0f5c6b38fd1f 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
@@ -3,18 +3,18 @@ import { loaders } from 'kea-loaders'
import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
-import { dayjs } from 'lib/dayjs'
-import { dateFilterToText, dateStringToDayJs } from 'lib/utils/dateFilters'
+import { dateFilterToText, getDefaultInterval } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { hogqlQuery } from '~/queries/query'
import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
-import { type AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+import { type AnyPropertyFilter, IntervalType, PropertyFilterType, PropertyOperator } from '~/types'
import toolQualityQueryTemplate from '../backend/templates/tool_quality.sql?raw'
import type { mcpAnalyticsToolQualityLogicType } from './mcpAnalyticsToolQualityLogicType'
+import { buildBucketKeys, normalizeBucket } from './timeBuckets'
// `$mcp_tool_category` is stamped onto every $mcp_tool_call event by the producer
// (PostHog's MCP server from its catalog; external servers via the SDK). We read
@@ -126,46 +126,17 @@ export interface DailyChartData {
const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-7d', dateTo: null }
const DEFAULT_SORT: SortState = { column: 'total_calls', direction: 'DESC' }
-const EMPTY_CHART_DATA: DailyChartData = {
- labels: [],
- calls: [],
- errors: [],
- successRate: [],
- p50: [],
- p95: [],
- p99: [],
-}
-
-// Pivot per-day rows into chart series over a gap-free day axis: ClickHouse only
-// returns days that had events, so missing days are filled in to keep the x-axis
-// linear. Counts fill with 0 (genuinely no activity); rate and latency fill with
-// NaN so the chart skips the point instead of drawing a misleading dip to zero.
-// `range` spans the axis over the full selected window (so empty leading/trailing
-// days still show); without it, the axis spans only the days that have data.
-export function buildDailyChartData(
- dailyStats: DailyToolStat[],
- range?: { start: string; end: string }
-): DailyChartData {
- let startDay: string
- let endDay: string
- if (range) {
- startDay = range.start
- endDay = range.end
- } else if (dailyStats.length > 0) {
- startDay = dailyStats[0].day
- endDay = dailyStats[dailyStats.length - 1].day
- } else {
- return EMPTY_CHART_DATA
- }
- const byDay = new Map(dailyStats.map((r) => [r.day, r]))
- const end = dayjs(endDay)
- const labels: string[] = []
- for (let day = dayjs(startDay); !day.isAfter(end); day = day.add(1, 'day')) {
- labels.push(day.format('YYYY-MM-DD'))
- }
- const rows = labels.map((day) => byDay.get(day))
+// Pivot per-bucket rows onto the full set of interval buckets spanning the selected window:
+// ClickHouse only returns buckets that had events, so `bucketKeys` (built from the window at the
+// active interval) keeps the x-axis linear and covering the whole range regardless of granularity.
+// Counts fill with 0 (genuinely no activity); rate and latency fill with NaN so the chart skips the
+// point instead of drawing a misleading dip to zero. Rows match by normalized bucket key, so day,
+// hour, and minute intervals all line up.
+export function buildDailyChartData(dailyStats: DailyToolStat[], bucketKeys: string[]): DailyChartData {
+ const byBucket = new Map(dailyStats.map((r) => [normalizeBucket(r.day), r]))
+ const rows = bucketKeys.map((k) => byBucket.get(k))
return {
- labels,
+ labels: bucketKeys,
calls: rows.map((r) => r?.calls ?? 0),
errors: rows.map((r) => r?.errors ?? 0),
successRate: rows.map((r) => (r && r.calls ? ((r.calls - r.errors) / r.calls) * 100 : NaN)),
@@ -321,9 +292,11 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType
const properties = [...values.categoryProperties, ...toolProperty]
const response = (await api.query({
kind: NodeKind.HogQLQuery,
+ // `values.interval` is a fixed IntervalType from getDefaultInterval, never user
+ // input, so interpolating it into the dateTrunc is safe.
query: `
SELECT
- toDate(timestamp) AS day,
+ dateTrunc('${values.interval}', 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,
@@ -383,6 +356,12 @@ ORDER BY day
(dateFilter: DateFilter): string =>
dateFilterToText(dateFilter.dateFrom, dateFilter.dateTo, 'the selected range') ?? 'the selected range',
],
+ // Grouping interval for the daily chart — PostHog's standard auto-choice, so a sub-day window
+ // (e.g. last 12 hours) buckets hourly instead of collapsing to a single day point.
+ interval: [
+ (s) => [s.dateFilter],
+ (dateFilter: DateFilter): IntervalType => getDefaultInterval(dateFilter.dateFrom, dateFilter.dateTo),
+ ],
scopeShare: [
(s) => [s.categoryCounts, s.selectedCategories],
(categoryCounts: CategoryCount[], selectedCategories: string[]): ScopeShare => {
@@ -403,14 +382,15 @@ ORDER BY day
},
],
dailyChartData: [
- (s) => [s.dailyStats, s.dateFilter, teamLogic.selectors.timezone],
- (dailyStats: DailyToolStat[], dateFilter: DateFilter, timezone: string): DailyChartData => {
- const start = dateStringToDayJs(dateFilter.dateFrom, timezone)
- const end =
- (dateFilter.dateTo ? dateStringToDayJs(dateFilter.dateTo, timezone) : dayjs().tz(timezone)) ??
- dayjs()
- const range = start ? { start: start.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') } : undefined
- return buildDailyChartData(dailyStats, range)
+ (s) => [s.dailyStats, s.dateFilter, s.interval, teamLogic.selectors.timezone],
+ (
+ dailyStats: DailyToolStat[],
+ dateFilter: DateFilter,
+ interval: IntervalType,
+ timezone: string
+ ): DailyChartData => {
+ const bucketKeys = buildBucketKeys(dateFilter.dateFrom, dateFilter.dateTo, timezone, interval)
+ return buildDailyChartData(dailyStats, bucketKeys)
},
],
}),
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
index cc324010045f..cd6f321f2eca 100644
--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
@@ -14,7 +14,6 @@ import { HARNESS_BY_LABEL, harnessLogo } from './dashboard/harnessRegistry'
import {
type ActivityRow,
type BucketRow,
- buildBucketKeys,
buildDailyActivity,
buildKPIs,
buildKpiWindow,
@@ -22,7 +21,6 @@ import {
deltaPct,
lastBucketIsInProgress,
mcpDashboardOverviewLogic,
- normalizeBucket,
pickNotableSessions,
type SessionRow,
type ToolDailyRow,
@@ -181,32 +179,6 @@ describe('mcpDashboardOverviewLogic', () => {
})
})
- describe('buildBucketKeys', () => {
- it('emits one key per day across the resolved window, including empty trailing days', () => {
- jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))
- try {
- expect(buildBucketKeys({ dateFrom: '-7d', dateTo: null }, 'UTC', 'day')).toEqual([
- '2026-06-11 00:00:00',
- '2026-06-12 00:00:00',
- '2026-06-13 00:00:00',
- '2026-06-14 00:00:00',
- '2026-06-15 00:00:00',
- '2026-06-16 00:00:00',
- '2026-06-17 00:00:00',
- '2026-06-18 00:00:00',
- ])
- } finally {
- jest.useRealTimers()
- }
- })
-
- it('truncates weekly buckets to ISO Monday starts (matching ClickHouse dateTrunc)', () => {
- // 2026-06-01 is a Monday; every key should land on a Monday.
- const keys = buildBucketKeys({ dateFrom: '2026-06-01', dateTo: '2026-06-21' }, 'UTC', 'week')
- expect(keys).toEqual(['2026-06-01 00:00:00', '2026-06-08 00:00:00', '2026-06-15 00:00:00'])
- })
- })
-
describe('buildDailyActivity', () => {
it('projects rows onto the bucket keys, defaulting missing buckets to zero', () => {
const rows: ActivityRow[] = [
@@ -268,34 +240,6 @@ describe('mcpDashboardOverviewLogic', () => {
})
})
- describe('normalizeBucket', () => {
- // The query API serializes dateTrunc buckets as ISO datetimes; they must come back in the
- // same format buildBucketKeys emits, otherwise the zero-fill join misses every bucket.
- it.each([
- ['2026-06-19T00:00:00Z', 'UTC', '2026-06-19 00:00:00'],
- ['2026-06-19T00:00:00+00:00', 'UTC', '2026-06-19 00:00:00'],
- ['2026-06-19T11:30:00Z', 'UTC', '2026-06-19 11:30:00'],
- ])('normalizes %s (%s) to %s', (raw, timezone, expected) => {
- expect(normalizeBucket(raw, timezone)).toBe(expected)
- })
-
- it('returns empty string for missing values', () => {
- expect(normalizeBucket(null, 'UTC')).toBe('')
- expect(normalizeBucket('', 'UTC')).toBe('')
- })
-
- it('produces keys that match buildBucketKeys so the activity join lands', () => {
- jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))
- try {
- const bucketKeys = buildBucketKeys({ dateFrom: '-7d', dateTo: null }, 'UTC', 'day')
- const normalized = normalizeBucket('2026-06-18T00:00:00Z', 'UTC')
- expect(bucketKeys).toContain(normalized)
- } finally {
- jest.useRealTimers()
- }
- })
- })
-
describe('buildKpiWindow', () => {
it.each([
['2024-01-08', '2024-01-15', 'day', '2024-01-08 00:00:00', '2023-12-31'],
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
index d48072fa0b08..be8eea351c13 100644
--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
@@ -5,7 +5,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'
import { dayjs } from 'lib/dayjs'
-import { dateStringToComponents, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'
+import { getDefaultInterval } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -15,6 +15,7 @@ import { AnyPropertyFilter, IntervalType, TeamType } from '~/types'
import { mcpClusteringLogic } from './clustering/mcpClusteringLogic'
import type { MCPIntentClusterApi } from './generated/api.schemas'
import type { mcpDashboardOverviewLogicType } from './mcpDashboardOverviewLogicType'
+import { BUCKET_FORMAT, buildBucketKeys, normalizeBucket, resolveWindow, startOfBucket } from './timeBuckets'
export interface DateFilter {
dateFrom: string | null
@@ -278,53 +279,9 @@ export function deltaPct(current: number, previous: number): number | null {
return ((current - previous) / previous) * 100
}
-// Resolve the filter to absolute bounds. Hour-level relative ranges ("-1h") are
-// rolling from now; dateStringToDayJs anchors relative dates to the start of the
-// day, which would inflate a "last hour" window to half a day. Day+ ranges keep
-// that start-of-day anchoring (the established behaviour).
-function resolveWindow(dateFilter: DateFilter, timezone: string): { start: dayjs.Dayjs; end: dayjs.Dayjs } {
- const now = dayjs().tz(timezone)
- const end = (dateFilter.dateTo ? dateStringToDayJs(dateFilter.dateTo, timezone) : now) ?? now
- const components = dateStringToComponents(dateFilter.dateFrom)
- if (components && components.unit === 'hour' && !dateFilter.dateTo) {
- // components.amount is signed (negative for the past), so add() walks backwards.
- return { start: now.add(components.amount, 'hour'), end: now }
- }
- const start = dateStringToDayJs(dateFilter.dateFrom, timezone) ?? now.subtract(7, 'day')
- return { start, end }
-}
-
-// Truncate to the start of an interval bucket the same way ClickHouse's dateTrunc does, so the keys
-// we generate line up with the query's bucket strings. dayjs' startOf covers minute/hour/day/month;
-// only 'week' differs — dateTrunc('week') is ISO (Monday-start) while dayjs defaults to Sunday.
-function startOfBucket(d: dayjs.Dayjs, interval: IntervalType): dayjs.Dayjs {
- if (interval === 'week') {
- const day = d.day() // 0 = Sunday … 6 = Saturday
- return d.startOf('day').subtract((day + 6) % 7, 'day')
- }
- return d.startOf(interval)
-}
-
-// The one format for bucket keys — must match ClickHouse dateTrunc's DateTime output so the
-// zero-fill join and the in-progress-tail comparison line up. Change it here, nowhere else.
-const BUCKET_FORMAT = 'YYYY-MM-DD HH:mm:ss'
-
-// Every bucket key across the resolved window [start, end] at the active interval, formatted to
-// match dateTrunc's DateTime output ('YYYY-MM-DD HH:mm:ss'). The activity and tool-usage series are
-// zero-filled against these so the x-axis spans the whole selected range instead of clipping to the
-// buckets that happened to have events.
-export function buildBucketKeys(dateFilter: DateFilter, timezone: string, interval: IntervalType): string[] {
- const { start, end } = resolveWindow(dateFilter, timezone)
- const last = startOfBucket(end, interval).valueOf()
- const keys: string[] = []
- let cursor = startOfBucket(start, interval)
- // Bounded dashboard windows keep this small; the cap is just a guard against a pathological range.
- for (let i = 0; cursor.valueOf() <= last && i < 100000; i++) {
- keys.push(cursor.format(BUCKET_FORMAT))
- cursor = cursor.add(1, interval)
- }
- return keys
-}
+// Window resolution, bucket keys, and the BUCKET_FORMAT contract are shared with the tab/detail
+// surfaces — see ./timeBuckets. The dashboard adds only the KPI-comparison window and in-progress
+// tail below, built on those shared primitives.
// True when the final bucket is the current, still-running interval (open-ended window), so the
// chart can dash that segment as "in progress" rather than letting the partial period read as data
@@ -342,11 +299,6 @@ export function lastBucketIsInProgress(
return bucketKeys[bucketKeys.length - 1] === currentBucket
}
-export function normalizeBucket(raw: unknown, timezone: string): string {
- const s = String(raw ?? '')
- return s ? dayjs(s).tz(timezone).format(BUCKET_FORMAT) : ''
-}
-
// Project the daily success/error rows onto the full set of buckets, defaulting empty buckets to 0.
export function buildDailyActivity(rows: ActivityRow[], bucketKeys: string[]): DailyActivity {
const byDay = new Map(rows.map((r) => [r.day, r]))
@@ -368,7 +320,7 @@ export interface KpiWindow {
// `currentStartBucket` is the cutoff `buildKPIs` splits on — formatted to match
// dateTrunc's DateTime output.
export function buildKpiWindow(dateFilter: DateFilter, timezone: string, interval: IntervalType): KpiWindow {
- const { start, end } = resolveWindow(dateFilter, timezone)
+ const { start, end } = resolveWindow(dateFilter.dateFrom, dateFilter.dateTo, timezone)
// The selected period covers the inclusive buckets [start, end] — one more than
// end.diff(start). Step the prior window back by that same count so the two
// halves of the comparison span an equal number of buckets.
@@ -627,7 +579,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([
breakpoint()
const raw = (response?.results as unknown[][]) ?? []
return raw.map((r) => ({
- day: normalizeBucket(r[0], values.timezone),
+ day: normalizeBucket(r[0]),
successes: Number(r[1] ?? 0),
errors: Number(r[2] ?? 0),
}))
@@ -646,7 +598,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([
breakpoint()
const raw = (response?.results as unknown[][]) ?? []
return raw.map((r) => ({
- day: normalizeBucket(r[0], values.timezone),
+ day: normalizeBucket(r[0]),
tool: String(r[1] ?? ''),
calls: Number(r[2] ?? 0),
}))
@@ -681,7 +633,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([
bucketKeys: [
(s) => [s.dateFilter, s.timezone, s.interval],
(dateFilter: DateFilter, timezone: string, interval: IntervalType): string[] =>
- buildBucketKeys(dateFilter, timezone, interval),
+ buildBucketKeys(dateFilter.dateFrom, dateFilter.dateTo, timezone, interval),
],
// Whether the activity chart's final bucket is the current, still-running interval — the
// chart dashes that segment so a partial period doesn't read as a drop in tool calls.
diff --git a/products/mcp_analytics/frontend/timeBuckets.test.ts b/products/mcp_analytics/frontend/timeBuckets.test.ts
new file mode 100644
index 000000000000..92a96a44051a
--- /dev/null
+++ b/products/mcp_analytics/frontend/timeBuckets.test.ts
@@ -0,0 +1,105 @@
+import { dayjs } from 'lib/dayjs'
+
+import { buildBucketKeys, formatBucketLabel, normalizeBucket } from './timeBuckets'
+
+describe('timeBuckets', () => {
+ describe('normalizeBucket', () => {
+ // Guards the flat-zero-sparkline bug: whether the query serializes the bucket as a naive
+ // datetime or a Z-stamped ISO, its wall-clock digits must survive verbatim — even when the
+ // browser sits in a different timezone than the project — or it matches no key.
+ it.each([
+ ['2026-06-18 00:00:00', '2026-06-18 00:00:00'], // naive (toString(dateTrunc))
+ ['2026-06-19T00:00:00Z', '2026-06-19 00:00:00'], // Z-stamped ISO (raw DateTime column)
+ ['2026-06-19T00:00:00+00:00', '2026-06-19 00:00:00'],
+ ['2026-06-19T11:30:00Z', '2026-06-19 11:30:00'],
+ ])('keeps %s as %s under a non-UTC browser tz', (raw, expected) => {
+ dayjs.tz.setDefault('Europe/Athens')
+ try {
+ expect(normalizeBucket(raw)).toBe(expected)
+ } finally {
+ dayjs.tz.setDefault('UTC')
+ }
+ })
+
+ it('returns empty string for missing values', () => {
+ expect(normalizeBucket(null)).toBe('')
+ expect(normalizeBucket('')).toBe('')
+ })
+ })
+
+ describe('buildBucketKeys', () => {
+ it('spans an absolute window at hour granularity, inclusive of both ends', () => {
+ expect(buildBucketKeys('2026-06-01T00:00:00Z', '2026-06-01T03:00:00Z', 'UTC', 'hour')).toEqual([
+ '2026-06-01 00:00:00',
+ '2026-06-01 01:00:00',
+ '2026-06-01 02:00:00',
+ '2026-06-01 03:00:00',
+ ])
+ })
+
+ it('emits one key per day across a relative window, including empty trailing days', () => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))
+ try {
+ expect(buildBucketKeys('-7d', null, 'UTC', 'day')).toEqual([
+ '2026-06-11 00:00:00',
+ '2026-06-12 00:00:00',
+ '2026-06-13 00:00:00',
+ '2026-06-14 00:00:00',
+ '2026-06-15 00:00:00',
+ '2026-06-16 00:00:00',
+ '2026-06-17 00:00:00',
+ '2026-06-18 00:00:00',
+ ])
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('truncates weekly buckets to ISO Monday starts (matching ClickHouse dateTrunc)', () => {
+ // 2026-06-01 is a Monday; every key should land on a Monday.
+ expect(buildBucketKeys('2026-06-01', '2026-06-21', 'UTC', 'week')).toEqual([
+ '2026-06-01 00:00:00',
+ '2026-06-08 00:00:00',
+ '2026-06-15 00:00:00',
+ ])
+ })
+
+ // Guards the DST data-drop: cumulative add on a tz-aware cursor keeps the pre-DST offset and
+ // lands short after spring-forward, dropping the last day. Re-anchoring keeps every bucket.
+ it('spans a daily window crossing a spring-forward DST boundary without dropping a bucket', () => {
+ expect(buildBucketKeys('2026-03-07', '2026-03-09', 'America/New_York', 'day')).toEqual([
+ '2026-03-07 00:00:00',
+ '2026-03-08 00:00:00',
+ '2026-03-09 00:00:00',
+ ])
+ })
+
+ it('spans a short window at minute granularity', () => {
+ expect(buildBucketKeys('2026-06-01T09:00:00Z', '2026-06-01T09:04:00Z', 'UTC', 'minute')).toEqual([
+ '2026-06-01 09:00:00',
+ '2026-06-01 09:01:00',
+ '2026-06-01 09:02:00',
+ '2026-06-01 09:03:00',
+ '2026-06-01 09:04:00',
+ ])
+ })
+
+ it('produces keys a normalized query bucket lands on', () => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))
+ try {
+ const keys = buildBucketKeys('-7d', null, 'UTC', 'day')
+ expect(keys).toContain(normalizeBucket('2026-06-18T00:00:00Z'))
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+ })
+
+ describe('formatBucketLabel', () => {
+ it('shows the time for sub-day intervals and the date otherwise', () => {
+ expect(formatBucketLabel('2026-06-01 09:30:00', 'minute')).toBe('Jun 1, 09:30')
+ expect(formatBucketLabel('2026-06-01 09:00:00', 'hour')).toBe('Jun 1, 09:00')
+ expect(formatBucketLabel('2026-06-01 00:00:00', 'day')).toBe('Jun 1')
+ })
+ })
+})
diff --git a/products/mcp_analytics/frontend/timeBuckets.ts b/products/mcp_analytics/frontend/timeBuckets.ts
new file mode 100644
index 000000000000..052ae91ff61b
--- /dev/null
+++ b/products/mcp_analytics/frontend/timeBuckets.ts
@@ -0,0 +1,91 @@
+import { dayjs } from 'lib/dayjs'
+import { dateStringToComponents, dateStringToDayJs } from 'lib/utils/dateFilters'
+
+import { IntervalType } from '~/types'
+
+// Bucket key format matching ClickHouse dateTrunc's DateTime output, so the zero-fill keys we
+// generate line up with the query's bucket strings. One format for every interval — a day bucket
+// is just midnight. Change it here, nowhere else.
+export const BUCKET_FORMAT = 'YYYY-MM-DD HH:mm:ss'
+
+// Resolve a date filter to absolute bounds. Hour/minute/second relative ranges ("-1h") roll from
+// now; dateStringToDayJs anchors day+ ranges to the start of the day (the established behaviour).
+export function resolveWindow(
+ dateFrom: string | null,
+ dateTo: string | null,
+ timezone: string
+): { start: dayjs.Dayjs; end: dayjs.Dayjs } {
+ const now = dayjs().tz(timezone)
+ const end = (dateTo ? dateStringToDayJs(dateTo, timezone) : now) ?? now
+ const components = dateStringToComponents(dateFrom)
+ if (components && ['hour', 'minute', 'second'].includes(components.unit) && !dateTo) {
+ // components.amount is signed (negative for the past), so add() walks backwards.
+ return { start: now.add(components.amount, components.unit as dayjs.ManipulateType), end: now }
+ }
+ const start = dateStringToDayJs(dateFrom, timezone) ?? now.subtract(7, 'day')
+ return { start, end }
+}
+
+// Truncate to the start of an interval bucket the way ClickHouse's dateTrunc does, so generated keys
+// line up with the query's bucket strings. dayjs' startOf covers minute/hour/day/month; only 'week'
+// differs — dateTrunc('week') is ISO (Monday-start) while dayjs defaults to Sunday.
+export function startOfBucket(d: dayjs.Dayjs, interval: IntervalType): dayjs.Dayjs {
+ if (interval === 'week') {
+ const day = d.day() // 0 = Sunday … 6 = Saturday
+ return d.startOf('day').subtract((day + 6) % 7, 'day')
+ }
+ return d.startOf(interval)
+}
+
+// Every bucket key across the resolved window [start, end] at the active interval, formatted to match
+// dateTrunc's DateTime output. Series are zero-filled against these so the x-axis spans the whole
+// selected range instead of clipping to the buckets that happened to have events.
+export function buildBucketKeys(
+ dateFrom: string | null,
+ dateTo: string | null,
+ timezone: string,
+ interval: IntervalType
+): string[] {
+ const { start, end } = resolveWindow(dateFrom, dateTo, timezone)
+ const first = startOfBucket(start, interval)
+ const last = startOfBucket(end, interval).valueOf()
+ const keys: string[] = []
+ // Re-anchor each bucket from the window start instead of cumulatively adding to a timezone-aware
+ // cursor: Day.js keeps the original UTC offset across `add`, so a range crossing a DST boundary
+ // would otherwise drop a bucket (short by an hour) or repeat one. startOf() re-resolves the offset
+ // each step; the dedupe guards the fall-back hour that wall-clock-repeats. The cap bounds a
+ // pathological range.
+ for (let i = 0; i < 100000; i++) {
+ const bucket = startOfBucket(first.add(i, interval), interval)
+ if (bucket.valueOf() > last) {
+ break
+ }
+ const key = bucket.format(BUCKET_FORMAT)
+ if (key !== keys[keys.length - 1]) {
+ keys.push(key)
+ }
+ }
+ return keys
+}
+
+// Normalize a raw bucket string from a query (a date or datetime) to BUCKET_FORMAT so it joins the
+// generated keys regardless of how ClickHouse rendered it. The value already carries the project-tz
+// wall clock — either a naive datetime (toString(dateTrunc)) or a Z-stamped ISO (a raw DateTime
+// column) — so read it in UTC to keep those digits verbatim. dayjs.tz(s, tz) would treat a Z-stamped
+// value as an instant and convert it by the project offset, shifting buckets off the axis so nothing
+// matches (flat charts for non-UTC projects). buildBucketKeys formats keys as the same wall clock.
+export function normalizeBucket(raw: unknown): string {
+ const s = String(raw ?? '')
+ return s ? dayjs.utc(s).format(BUCKET_FORMAT) : ''
+}
+
+// Human-readable axis/hover label for a bucket, showing the time only when the interval is sub-day.
+export function formatBucketLabel(bucket: string, interval: IntervalType): string {
+ const d = dayjs(bucket)
+ if (!d.isValid()) {
+ return bucket
+ }
+ return interval === 'hour' || interval === 'minute' || interval === 'second'
+ ? d.format('MMM D, HH:mm')
+ : d.format('MMM D')
+}
diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx
index 11bd148d0be1..ddba0812fc5e 100644
--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx
+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx
@@ -5,6 +5,7 @@ import {
ChartLegend,
type ChartTheme,
type Series,
+ type TimeInterval,
TimeSeriesLineChart,
type TimeSeriesLineChartConfig,
legendItemsFromSeries,
@@ -17,7 +18,11 @@ import { Card, CardState } from '../dashboard/Card'
import { formatMsAsSeconds } from '../dashboard/formatters'
import { type DailyChartData } from '../mcpAnalyticsToolQualityLogic'
-function buildConfig(timezone: string, yAxis?: TimeSeriesLineChartConfig['yAxis']): TimeSeriesLineChartConfig {
+function buildConfig(
+ timezone: string,
+ interval: TimeInterval,
+ yAxis?: TimeSeriesLineChartConfig['yAxis']
+): TimeSeriesLineChartConfig {
return {
curve: 'monotone',
showAxisLines: true,
@@ -25,7 +30,7 @@ function buildConfig(timezone: string, yAxis?: TimeSeriesLineChartConfig['yAxis'
showCrosshair: true,
showGrid: true,
yAxis,
- xAxis: { interval: 'day', timezone },
+ xAxis: { interval, timezone },
tooltip: { placement: 'cursor' },
}
}
@@ -67,11 +72,13 @@ export function ToolQualityCharts({
loading,
theme,
timezone,
+ interval,
}: {
data: DailyChartData
loading: boolean
theme: ChartTheme
timezone: string
+ interval: TimeInterval
}): JSX.Element {
const isEmpty = data.labels.length === 0
@@ -95,12 +102,18 @@ export function ToolQualityCharts({
[data, theme]
)
- const countsConfig = useChartConfig(() => buildConfig(timezone), [timezone])
+ const countsConfig = useChartConfig(() => buildConfig(timezone, interval), [timezone, interval])
const percentConfig = useChartConfig(
- () => buildConfig(timezone, { tickFormatter: (value: number) => formatPercentage(value, { compact: true }) }),
- [timezone]
+ () =>
+ buildConfig(timezone, interval, {
+ tickFormatter: (value: number) => formatPercentage(value, { compact: true }),
+ }),
+ [timezone, interval]
+ )
+ const latencyConfig = useChartConfig(
+ () => buildConfig(timezone, interval, { tickFormatter: formatMsAsSeconds }),
+ [timezone, interval]
)
- const latencyConfig = useChartConfig(() => buildConfig(timezone, { tickFormatter: formatMsAsSeconds }), [timezone])
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 77fb6eb498e3..f4c01669f2df 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -31628,6 +31628,8 @@ export namespace Schemas {
export interface MCPToolDailyStatsQuery {
dateRange?: DateRange | null;
+ /** Bucket granularity for the series. The frontend passes getDefaultInterval so a sub-day window buckets by hour/minute instead of collapsing to a single day point. Defaults to day. */
+ interval?: IntervalType | null;
kind?: 'MCPToolDailyStatsQuery';
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.ts
index d01071f0d769..17f5abd0fa8c 100644
--- a/services/mcp/src/tools/generated/mcp_analytics.ts
+++ b/services/mcp/src/tools/generated/mcp_analytics.ts
@@ -533,8 +533,13 @@ const MCPToolStatsQuery = z.object({
.describe('The effective tool name to scope to (matched against the single-exec-resolved tool name).'),
})
+const IntervalType = z.enum(['second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'])
+
const MCPToolDailyStatsQuery = z.object({
dateRange: DateRange.optional(),
+ interval: IntervalType.describe(
+ 'Bucket granularity for the series. The frontend passes getDefaultInterval so a sub-day window buckets by hour/minute instead of collapsing to a single day point. Defaults to day.'
+ ).optional(),
kind: z.literal('MCPToolDailyStatsQuery').default('MCPToolDailyStatsQuery'),
toolName: z
.string()