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): draw explain-chart evidence from its queries (#125114)

Sam Pennington298c5af9ab10
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ae69fef4f87d..9c2c77383281 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6263,7 +6263,7 @@ snapshots:
mcp-apps-explain-chart--summary--light:
hash: v1.k794b7964.8e544f3f6c9e2e43bf03efd6bf30e402e2f24a41ec060922b5e3068643ce4c86.BQcCbMIGeBusavfXWYInYZD6jMZfnN4zr-HV9oOAFHg
mcp-apps-explain-chart-evidence-chart--line--light:
- hash: v1.k794b7964.d18367c8e6c0db146a8a61c780cca48fd38f21268db89318114be3fb65130bf8.vtgJK_jbQZbEXfmqXJhYI7BnuwvNkc68bAjvqAAlh_E
+ hash: v1.k794b7964.e156c5ef2fc16c7fed1cb75eb29fcf31d62be8a83f073485b45df5a64d8d9d9c.jJXZhCThRdf2Pr6sdNHVpa-njosNVK1Fn6S3fLI3kGI
mcp-apps-feature-flags--boolean-flag--light:
hash: v1.k794b7964.f3ee0e724e30f350166b5a87d46cd36ba9f982735aa9d7e322aeaf28bc4c9b1c.KzlRVALZdoWS2mlKcnTJRTOo4SmFvIZzKhj6SodWt3I
mcp-apps-feature-flags--flag-list--light:
diff --git a/products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart.stories.tsx b/products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart.stories.tsx
index fd0821dccf54..5c63b55447d9 100644
--- a/products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart.stories.tsx
+++ b/products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart.stories.tsx
@@ -4,6 +4,7 @@ import type { ReactElement } from 'react'
import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
import { useChartTheme } from '@posthog/quill-charts'
+import { sqlEvidenceChart } from './sqlEvidenceChart'
import { StoryEvidenceChart } from './StoryEvidenceChart'
// The chart measures its box with a ResizeObserver, so give it a definite width.
@@ -22,26 +23,24 @@ export default meta
type Story = StoryObj<{}>
+const HOURS = [
+ '2026-10-26 21:00:00',
+ '2026-10-26 22:00:00',
+ '2026-10-26 23:00:00',
+ '2026-10-27 00:00:00',
+ '2026-10-27 01:00:00',
+]
+
function LineChart(): ReactElement {
+ const rows = HOURS.flatMap((hour, index) => [
+ [hour, 'EU', [0.91, 0.9, 0.55, 0.62, 0.7][index]],
+ ...(index === 2 ? [] : [[hour, 'US', [0.88, 0.89, 0.52, 0.6, 0.69][index]]]),
+ ])
return (
<StoryEvidenceChart
className="h-[260px]"
theme={useChartTheme()}
- chart={{
- type: 'line',
- labels: [
- 'Oct 26 18:00',
- 'Oct 26 19:00',
- 'Oct 26 20:00',
- 'Oct 26 21:00',
- 'Oct 26 22:00',
- 'Oct 26 23:00',
- ],
- series: [
- { name: 'EU hit rate', values: [0.91, 0.9, 0.55, 0.62, 0.7, 0.78] },
- { name: 'US hit rate', values: [0.88, 0.89, 0.52, 0.6, 0.69, 0.8] },
- ],
- }}
+ chart={sqlEvidenceChart(['hour', 'region', 'hit_rate'], rows)!}
/>
)
}
diff --git a/products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart.tsx b/products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart.tsx
index 1d3ca24121fb..9aac5214dc8c 100644
--- a/products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart.tsx
+++ b/products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart.tsx
@@ -4,7 +4,7 @@ import { buildYTickFormatter, type ChartTheme, TimeSeriesBarChart, TimeSeriesLin
import type { StoryEvidenceChartData } from './explainChartTypes'
-const Y_AXIS = { tickFormatter: buildYTickFormatter({ format: 'short' }), showGrid: true }
+const Y_TICK_FORMATTER = buildYTickFormatter({ format: 'short' })
export interface StoryEvidenceChartProps {
chart: StoryEvidenceChartData
@@ -13,23 +13,33 @@ export interface StoryEvidenceChartProps {
}
export function StoryEvidenceChart({ chart, theme, className }: StoryEvidenceChartProps): ReactElement {
- const series = chart.series.map((item, index) => ({ key: String(index), label: item.name, data: item.values }))
+ const series = chart.series.map((item, index) => ({
+ key: String(index),
+ label: item.name,
+ data: item.values.map((value) => value ?? NaN),
+ }))
+ // quill-charts positions points by label, so a repeated label would send the line backwards.
+ const keys = chart.labels.map((_, index) => String(index))
+ // Results saved before `ticks` existed carry only `labels`.
+ const xAxis = { tickFormatter: (key: string): string => (chart.ticks ?? chart.labels)[Number(key)] ?? key }
+ const yAxis = { tickFormatter: Y_TICK_FORMATTER, showGrid: true, label: chart.yAxisLabel ?? undefined }
+ const tooltip = { labelFormatter: (key: string): string => chart.labels[Number(key)] ?? key }
const legend = { show: series.length > 1 }
return (
<div className={`flex w-full flex-col ${className}`} data-attr="explain-chart-evidence-inline-chart">
{chart.type === 'bar' ? (
<TimeSeriesBarChart
series={series}
- labels={chart.labels}
+ labels={keys}
theme={theme}
- config={{ yAxis: Y_AXIS, legend, barLayout: 'grouped' }}
+ config={{ xAxis, yAxis, tooltip, legend, barLayout: 'grouped' }}
/>
) : (
<TimeSeriesLineChart
series={series}
- labels={chart.labels}
+ labels={keys}
theme={theme}
- config={{ yAxis: Y_AXIS, legend, showCrosshair: true }}
+ config={{ xAxis, yAxis, tooltip, legend, showCrosshair: true }}
/>
)}
</div>
diff --git a/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts b/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts
index 88d67f3c6568..1c42457808d7 100644
--- a/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts
+++ b/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts
@@ -3,13 +3,18 @@ export type StoryConfidence = 'high' | 'medium' | 'low'
export interface StoryEvidenceChartData {
type: 'line' | 'bar'
labels: string[]
- series: { name: string; values: number[] }[]
+ /** The axis label of each point, which leaves out a date that repeats. */
+ ticks?: string[]
+ /** Null where a breakdown value has no row for that point. */
+ series: { name: string; values: (number | null)[] }[]
+ yAxisLabel: string | null
}
export interface StoryEvidence {
text: string
url: string | null
query?: Record<string, unknown> | null
+ queryTool?: string | null
chart?: StoryEvidenceChartData | null
}
diff --git a/products/product_analytics/mcp/apps/explainChart/sqlEvidenceChart.ts b/products/product_analytics/mcp/apps/explainChart/sqlEvidenceChart.ts
new file mode 100644
index 000000000000..d15819c3e51a
--- /dev/null
+++ b/products/product_analytics/mcp/apps/explainChart/sqlEvidenceChart.ts
@@ -0,0 +1,110 @@
+import type { StoryEvidenceChartData } from './explainChartTypes'
+
+type Series = StoryEvidenceChartData['series']
+
+interface Points {
+ points: string[]
+ series: Series
+}
+
+const MAX_BREAKDOWN_SERIES = 10
+const TIMESTAMP = /^\d{4}-(?<month>\d{2})-(?<day>\d{2})(?:[T ](?<time>\d{2}:\d{2})(?::(?<seconds>\d{2}))?)?/
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+
+function numberOrNull(value: unknown): number | null {
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
+}
+
+function isNumberColumn(rows: unknown[][], index: number): boolean {
+ return (
+ rows.some((row) => numberOrNull(row[index]) !== null) &&
+ rows.every((row) => row[index] === null || numberOrNull(row[index]) !== null)
+ )
+}
+
+function isLongShape(rows: unknown[][]): boolean {
+ return rows[0]!.length >= 3 && !isNumberColumn(rows, 1) && isNumberColumn(rows, 2)
+}
+
+/** `hour, safari, chrome`: one series per number column. */
+function wideSeries(columns: string[], rows: unknown[][]): Points {
+ const valueColumns = columns.map((_, index) => index).filter((index) => index > 0 && isNumberColumn(rows, index))
+ return {
+ points: rows.map((row) => String(row[0])),
+ series: valueColumns.map((index) => ({
+ name: columns[index]!,
+ values: rows.map((row) => numberOrNull(row[index])),
+ })),
+ }
+}
+
+/** `hour, browser, failures`: one series per browser, with a gap where a browser has no row for an hour. */
+function longSeries(rows: unknown[][]): Points {
+ const points = [...new Set(rows.map((row) => String(row[0])))]
+ const valuesByName = new Map<string, Map<string, number | null>>()
+ const totals = new Map<string, number>()
+ for (const [x, rawName, value] of rows) {
+ const name = String(rawName ?? 'None')
+ const values = valuesByName.get(name) ?? new Map<string, number | null>()
+ values.set(String(x), numberOrNull(value))
+ valuesByName.set(name, values)
+ totals.set(name, (totals.get(name) ?? 0) + (numberOrNull(value) ?? 0))
+ }
+ const topNames = [...totals]
+ .sort(([, left], [, right]) => right - left)
+ .slice(0, MAX_BREAKDOWN_SERIES)
+ .map(([name]) => name)
+ return {
+ points,
+ series: topNames.map((name) => ({
+ name,
+ values: points.map((point) => valuesByName.get(name)!.get(point) ?? null),
+ })),
+ }
+}
+
+/** HogQL returns times in the project's timezone, so the labels keep the wall-clock time as written. */
+function dateLabels(points: string[]): { labels: string[]; ticks: string[] } | null {
+ const dates = points.map((point) => TIMESTAMP.exec(point)?.groups)
+ if (dates.some((date) => !date)) {
+ return null
+ }
+ const dayOf = (index: number): string => `${MONTHS[Number(dates[index]!.month) - 1]} ${Number(dates[index]!.day)}`
+ const showSeconds = dates.some((date) => (date!.seconds ?? '00') !== '00')
+ const timeOf = (index: number): string => {
+ const { time = '00:00', seconds = '00' } = dates[index]!
+ return showSeconds ? `${time}:${seconds}` : time
+ }
+ const midnight = showSeconds ? '00:00:00' : '00:00'
+ const showTime = dates.some((_, index) => timeOf(index) !== midnight)
+
+ const labels = points.map((_, index) => (showTime ? `${dayOf(index)} ${timeOf(index)}` : dayOf(index)))
+ const ticks = labels.map((label, index) =>
+ showTime && index > 0 && dayOf(index - 1) === dayOf(index) ? timeOf(index) : label
+ )
+ return { labels, ticks }
+}
+
+/** Draws SQL rows as a chart, with the first column as the x-axis. */
+export function sqlEvidenceChart(columns: string[], rows: unknown[][]): StoryEvidenceChartData | null {
+ if (columns.length < 2 || rows.length === 0) {
+ return null
+ }
+ const long = isLongShape(rows)
+ // A breakdown draws one number, so a second number column would be dropped without a word.
+ if (long && columns.length > 3) {
+ return null
+ }
+ const { points, series } = long ? longSeries(rows) : wideSeries(columns, rows)
+ if (!series.length) {
+ return null
+ }
+ const dates = dateLabels(points)
+ return {
+ type: dates ? 'line' : 'bar',
+ labels: dates?.labels ?? points,
+ ticks: dates?.ticks ?? points,
+ series,
+ yAxisLabel: long ? columns[2]! : series.length === 1 ? series[0]!.name : null,
+ }
+}
diff --git a/products/product_analytics/skills/investigate-metric/SKILL.md b/products/product_analytics/skills/investigate-metric/SKILL.md
index 124b64bb968c..82c35dd928e6 100644
--- a/products/product_analytics/skills/investigate-metric/SKILL.md
+++ b/products/product_analytics/skills/investigate-metric/SKILL.md
@@ -96,9 +96,8 @@ For anything else, such as a metric you queried on your own, the findings go in
When it is a chart explanation:
- Add "Show the chart explanation (Step 5)" as the last item of your plan or to-do list.
-- Keep the `TrendsQuery` behind each finding, such as an event count with a breakdown or a property filter.
- The chart explanation draws a `TrendsQuery` as a chart beside the finding, and any other query only as a link.
- Use SQL for the findings that a `TrendsQuery` cannot express, and pass its numbers as the evidence's `chart` so they draw too.
+- Keep the query behind each finding. The chart explanation runs it again and draws the result beside the finding.
+ Prefer an insight query, such as a `TrendsQuery` with a breakdown or a property filter, and use SQL only for what an insight query cannot express.
## Step 2 — Common opening moves
@@ -160,9 +159,13 @@ Map the investigation onto it:
of `summary`.
- **Likely cause** and **Confidence** → `cause`, `confidence` and `confidence_reason`.
- **Evidence** → `evidence`, each finding with the `query` that produced it, or a `url`
- for a commit or a deploy. Pass the `TrendsQuery` you ran where you have one: the
- chart explanation draws it as a chart, while any other query only becomes a link.
- For a finding from SQL, also pass `chart` with the numbers from its result: `line` over time or `bar` per label, the `labels`, and one `series` per line.
+ for a commit or a deploy. The chart explanation runs each query and draws it: an insight
+ query with its insight chart, and a `HogQLQuery` from its rows. Shape the SQL for the chart,
+ with the x-axis column first, then optionally one text column to break down by, then the numbers.
+ Prefer a series over time to a before-and-after comparison, so the user sees when the change happened.
+- **Zoomed-in evidence** → when the metric moved suddenly, add one finding that zooms in on the change.
+ Use the insight's own query with a `dateRange` around the change, at the interval that shows it best, from `minute` to `day`.
+ Filter it to the segment the cause points at, such as the affected browser or region.
- A **headline** of one sentence with no numbers sums up the whole chart.
Wrap each name behind a moment, such as the referrer of a spike or the country behind a rise, in `**double asterisks**` so the chart explanation highlights it.
Do the same in each `cause`.
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index da8ff1b2b7ec..9909f186b798 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -772,57 +772,13 @@
"description": "One finding in one sentence, with the numbers from the query that found it. Mark the name that matters with **double asterisks**."
},
"query": {
- "description": "The query that found this, as you ran it (for example a TrendsQuery with a breakdown). It becomes a link to that chart, and a TrendsQuery also draws as a chart in the explanation.",
+ "description": "The query that found this, as you ran it. The explanation runs it again and draws the result beside the finding. An insight query (`TrendsQuery`, `FunnelsQuery`, `RetentionQuery`, `StickinessQuery`, `PathsQuery` or `LifecycleQuery`) draws with its insight chart. A `HogQLQuery` draws from its rows: select the x-axis column first (a time bucket or a label), then either the numbers to draw, or one text column to break down by followed by one number. Order by the x-axis column. SQL returns 100 rows unless it sets a `LIMIT`.",
"type": "object",
"propertyNames": {
"type": "string"
},
"additionalProperties": {}
},
- "chart": {
- "description": "Numbers to draw beside this finding when its query is not a TrendsQuery, such as SQL. Copy them from the result you got.",
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "enum": ["line", "bar"],
- "description": "`line` for values over time, `bar` for a value per label."
- },
- "labels": {
- "minItems": 1,
- "maxItems": 200,
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "The x-axis labels in order, such as hours or referrers, written as the person should read them."
- },
- "series": {
- "minItems": 1,
- "maxItems": 6,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 80
- },
- "values": {
- "type": "array",
- "items": {
- "type": "number"
- },
- "description": "One value per label, in the same order."
- }
- },
- "required": ["name", "values"]
- }
- }
- },
- "required": ["type", "labels", "series"]
- },
"url": {
"description": "A link to the source when it is not a query, for example a commit, a pull request or a deploy.",
"type": "string",
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 1ed9355d3619..c9f318c5f2a9 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -62,6 +62,19 @@ function isAbortError(error: unknown): boolean {
return (error instanceof Error && error.name === 'AbortError') || isTimeoutError(error)
}
+/** A caller's cancellation also ends a wait before a retry, so its deadline holds across retries. */
+function waitUnlessAborted(ms: number, signal: AbortSignal | null | undefined): Promise<void> {
+ return new Promise((resolve) => {
+ const done = (): void => {
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', done)
+ resolve()
+ }
+ const timer = setTimeout(done, ms)
+ signal?.addEventListener('abort', done)
+ })
+}
+
// Per-attempt deadline for a JSON API request. Without it, an upstream request that
// never answers holds the tool call open until the MCP client gives up, and a batch
// waits on its slowest call. A timeout returns an error that says whether a retry is
@@ -343,6 +356,8 @@ export class ApiClient {
responseType?: 'json' | 'text'
/** Per-attempt deadline for a JSON response. Defaults to the path-based deadline. */
timeoutMs?: number
+ /** Cancels the request, including any wait before a retry. */
+ signal?: AbortSignal
}): Promise<T> {
const pathname = opts.path.split(/[?#]/, 1)[0]!
if (
@@ -376,6 +391,7 @@ export class ApiClient {
method: opts.method,
...(opts.body ? { body: JSON.stringify(opts.body) } : {}),
...(opts.headers ? { headers: opts.headers } : {}),
+ ...(opts.signal ? { signal: opts.signal } : {}),
}
if (opts.responseType === 'text') {
@@ -655,6 +671,18 @@ export class ApiClient {
const timeoutMs = timeoutOverrideMs ?? apiRequestTimeoutMs(url)
for (;;) {
+ if (options?.signal?.aborted) {
+ return {
+ success: false,
+ error: new PostHogTransportError({
+ url,
+ method,
+ attempts: transportRetries + rateLimitRetries + 1,
+ retryable: false,
+ cause: options.signal.reason,
+ }),
+ }
+ }
let response: Response
let bodyText: string
const deadline = new AbortController()
@@ -698,7 +726,7 @@ export class ApiClient {
console.warn(
`[API] Transport failure on ${method} ${url}: ${String(error)}. Retrying in ${Math.round(delayMs)}ms (attempt ${transportRetries}/${TRANSPORT_MAX_RETRIES})`
)
- await new Promise((resolve) => setTimeout(resolve, delayMs))
+ await waitUnlessAborted(delayMs, options?.signal)
continue
} finally {
clearTimeout(timer)
@@ -742,7 +770,7 @@ export class ApiClient {
console.warn(
`[API] Rate limited (429) on ${method} ${url}. Retrying in ${Math.round(delayMs)}ms (attempt ${rateLimitRetries}/${RATE_LIMIT_MAX_RETRIES})`
)
- await new Promise((resolve) => setTimeout(resolve, delayMs))
+ await waitUnlessAborted(delayMs, options?.signal)
continue
}
@@ -1622,8 +1650,10 @@ export class ApiClient {
runQuery: async ({
query,
+ signal,
}: {
query: Record<string, unknown>
+ signal?: AbortSignal
}): Promise<{
results: unknown
columns?: unknown[] | null
@@ -1643,6 +1673,7 @@ export class ApiClient {
method: 'POST',
path: `/api/environments/${projectId}/query/`,
body: { query: normalizeQuery(query) },
+ signal,
})
},
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 5c9c9e42721e..eb664342ea7e 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -585,34 +585,7 @@ const ExplainChartEvidenceSchema = z.object({
.record(z.string(), z.unknown())
.optional()
.describe(
- 'The query that found this, as you ran it (for example a TrendsQuery with a breakdown). It becomes a link to that chart, and a TrendsQuery also draws as a chart in the explanation.'
- ),
- chart: z
- .object({
- type: z.enum(['line', 'bar']).describe('`line` for values over time, `bar` for a value per label.'),
- labels: z
- .array(z.string())
- .min(1)
- .max(200)
- .describe(
- 'The x-axis labels in order, such as hours or referrers, written as the person should read them.'
- ),
- series: z
- .array(
- z.object({
- name: z.string().min(1).max(80),
- values: z.array(z.number()).describe('One value per label, in the same order.'),
- })
- )
- .min(1)
- .max(6),
- })
- .refine((chart) => chart.series.every((item) => item.values.length === chart.labels.length), {
- message: 'Each series needs one value per label.',
- })
- .optional()
- .describe(
- 'Numbers to draw beside this finding when its query is not a TrendsQuery, such as SQL. Copy them from the result you got.'
+ 'The query that found this, as you ran it. The explanation runs it again and draws the result beside the finding. An insight query (`TrendsQuery`, `FunnelsQuery`, `RetentionQuery`, `StickinessQuery`, `PathsQuery` or `LifecycleQuery`) draws with its insight chart. A `HogQLQuery` draws from its rows: select the x-axis column first (a time bucket or a label), then either the numbers to draw, or one text column to break down by followed by one number. Order by the x-axis column. SQL returns 100 rows unless it sets a `LIMIT`.'
),
url: z
.string()
diff --git a/services/mcp/src/tools/insights/explainChart.ts b/services/mcp/src/tools/insights/explainChart.ts
index 74b26c771339..418c1c1c8fb0 100644
--- a/services/mcp/src/tools/insights/explainChart.ts
+++ b/services/mcp/src/tools/insights/explainChart.ts
@@ -10,9 +10,11 @@ import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, type ToolBase } f
import type {
ExplainChartData,
StoryChapter,
+ StoryEvidenceChartData,
StorySeriesResult,
StoryTrendsQuery,
} from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import { sqlEvidenceChart } from 'products/product_analytics/mcp/apps/explainChart/sqlEvidenceChart'
import { analyzeQuery } from '../shared'
import { findStoryRange, lastBucketInProgress } from './storyRanges'
@@ -55,9 +57,85 @@ const NOT_TRENDS = 'This tool only explains trends charts. For other kinds, writ
const NOT_OVER_TIME =
'This tool explains a trends chart that shows one value over time, and this chart does not. Write the explanation in the chat instead.'
-// The explanation redraws evidence through `query-trends`, whose schema is narrower than a TrendsQuery's, so evidence
-// it would refuse keeps its link and no chart.
-const redrawSchema = GENERATED_TOOLS['query-trends']!().schema
+// The explanation redraws insight evidence through the query tool for its kind. A tool's schema is narrower than the
+// query's, so evidence the tool would refuse keeps its link and no chart.
+const REDRAW_TOOLS = new Map(
+ (
+ [
+ ['TrendsQuery', 'query-trends'],
+ ['FunnelsQuery', 'query-funnel'],
+ ['RetentionQuery', 'query-retention'],
+ ['StickinessQuery', 'query-stickiness'],
+ ['PathsQuery', 'query-paths'],
+ ['LifecycleQuery', 'query-lifecycle'],
+ ] as const
+ ).map(([kind, tool]) => [kind as string, { tool, schema: GENERATED_TOOLS[tool]!().schema }])
+)
+
+function redrawToolFor(query: Record<string, unknown> | undefined): string | null {
+ // A trends query may leave out `kind`, which the trends tool fills in.
+ const kind = query?.kind ?? 'TrendsQuery'
+ const redraw = query && typeof kind === 'string' ? REDRAW_TOOLS.get(kind) : undefined
+ return redraw && redraw.schema.safeParse(query).success ? redraw.tool : null
+}
+
+type SqlEvidence = { chart: StoryEvidenceChartData | null } | { error: string }
+
+const SQL_EVIDENCE_TIME_LIMIT_MS = 60_000
+
+function isSqlQuery(query: Record<string, unknown> | undefined): query is Record<string, unknown> {
+ return query?.kind === 'HogQLQuery' && typeof query.query === 'string'
+}
+
+async function runSqlEvidence(
+ context: Context,
+ projectId: string,
+ chapters: Params['chapters']
+): Promise<Map<string, SqlEvidence>> {
+ const queries = new Map<string, Record<string, unknown>>()
+ for (const item of chapters.flatMap((chapter) => chapter.evidence ?? [])) {
+ if (isSqlQuery(item.query)) {
+ queries.set(JSON.stringify(item.query), item.query)
+ }
+ }
+ // One at a time, so the evidence does not use up the team's concurrent query limit, within one shared time limit.
+ const signal = AbortSignal.timeout(SQL_EVIDENCE_TIME_LIMIT_MS)
+ const results = new Map<string, SqlEvidence>()
+ for (const [key, query] of queries) {
+ if (signal.aborted) {
+ results.set(key, { error: 'it did not finish in time' })
+ continue
+ }
+ try {
+ const response = await context.api.query({ projectId }).runQuery({ query, signal })
+ const columns = (response.columns ?? []).map(String)
+ const rows = Array.isArray(response.results) ? (response.results as unknown[][]) : []
+ results.set(key, { chart: sqlEvidenceChart(columns, rows) })
+ } catch (error) {
+ results.set(key, { error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ return results
+}
+
+function sqlProblems(chapters: Params['chapters'], sqlEvidence: Map<string, SqlEvidence>): string[] {
+ return chapters.flatMap((chapter) =>
+ (chapter.evidence ?? []).flatMap((item) => {
+ const result = isSqlQuery(item.query) ? sqlEvidence.get(JSON.stringify(item.query)) : undefined
+ if (!result) {
+ return []
+ }
+ if ('error' in result) {
+ return [`The SQL behind "${item.text}" failed, so it shows as a link only: ${result.error}`]
+ }
+ return result.chart
+ ? []
+ : [
+ `The SQL behind "${item.text}" returned nothing to draw, so it shows as a link only. Select the x-axis column first, then either the numbers to draw, or one text column to break down by followed by one number.`,
+ ]
+ })
+ )
+}
interface StoryChart {
query: StoryTrendsQuery
@@ -121,7 +199,8 @@ function describeResult(
series: StorySeriesResult,
chapters: Params['chapters'],
missed: string[],
- warnings: unknown[]
+ warnings: unknown[],
+ evidenceProblems: string[]
): string {
const name = chart.insightName ?? series.label ?? 'the chart'
const lines = [`The explanation of "${name}" has ${chapters.length} chapters.`]
@@ -135,6 +214,7 @@ function describeResult(
} without a highlight. Use dates from the chart's \`days\` and call this tool again.`
)
}
+ lines.push(...evidenceProblems)
return lines.join(' ')
}
@@ -156,6 +236,7 @@ export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = a
)
}
+ const sqlEvidence = await runSqlEvidence(context, projectId, params.chapters)
const baseUrl = context.api.getProjectBaseUrl(projectId)
const interval = chart.query.interval ?? 'day'
const { timezone, warnings = [] } = response as { timezone?: string; warnings?: unknown[] | null }
@@ -172,12 +253,17 @@ export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = a
cause: chapter.cause ?? null,
confidence: chapter.confidence ?? null,
confidenceReason: chapter.confidence_reason ?? null,
- evidence: (chapter.evidence ?? []).map((item) => ({
- text: item.text,
- url: item.query ? `${baseUrl}${newInsightPath(item.query)}` : (item.url ?? null),
- query: item.query && redrawSchema.safeParse(item.query).success ? item.query : null,
- chart: item.chart ?? null,
- })),
+ evidence: (chapter.evidence ?? []).map((item) => {
+ const queryTool = redrawToolFor(item.query)
+ const sql = isSqlQuery(item.query) ? sqlEvidence.get(JSON.stringify(item.query)) : undefined
+ return {
+ text: item.text,
+ url: item.query ? `${baseUrl}${newInsightPath(item.query)}` : (item.url ?? null),
+ query: queryTool ? item.query : null,
+ queryTool,
+ chart: sql && 'chart' in sql ? sql.chart : null,
+ }
+ }),
}
})
@@ -196,7 +282,8 @@ export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = a
series,
params.chapters,
missed,
- warnings ?? []
+ warnings ?? [],
+ sqlProblems(params.chapters, sqlEvidence)
),
}
}
diff --git a/services/mcp/src/ui-apps/components/Component.tsx b/services/mcp/src/ui-apps/components/Component.tsx
index 35e26425a4a6..e1295358832c 100644
--- a/services/mcp/src/ui-apps/components/Component.tsx
+++ b/services/mcp/src/ui-apps/components/Component.tsx
@@ -5,62 +5,16 @@ import { Card, CardContent, Empty, EmptyDescription, EmptyHeader, EmptyMedia } f
import { captureInsightViewed } from '../analytics/posthog'
import { ChartHeader } from './ChartHeader'
-import { FunnelVisualizer } from './FunnelVisualizer'
import { inferVisualizationType } from './infer-visualization'
-import { LifecycleVisualizer } from './LifecycleVisualizer'
-import { PathsVisualizer } from './PathsVisualizer'
-import { RetentionVisualizer } from './RetentionVisualizer'
-import { StickinessVisualizer } from './StickinessVisualizer'
-import { TableVisualizer } from './TableVisualizer'
-import { TrendsVisualizer } from './TrendsVisualizer'
-import type {
- FunnelResult,
- FunnelsQuery,
- HogQLResult,
- LifecycleQuery,
- LifecycleResult,
- PathsQuery,
- PathsResult,
- RetentionQuery,
- RetentionResult,
- StickinessQuery,
- StickinessResult,
- TrendsQuery,
- TrendsResult,
-} from './types'
-import { insightQueryProperties, toTableResult } from './utils'
-
-/** Data payload from MCP tools */
-interface DataPayload {
- query?:
- | TrendsQuery
- | StickinessQuery
- | FunnelsQuery
- | LifecycleQuery
- | RetentionQuery
- | PathsQuery
- | Record<string, unknown>
- results:
- | TrendsResult
- | StickinessResult
- | FunnelResult
- | LifecycleResult
- | RetentionResult
- | PathsResult
- | HogQLResult
- /** Saved insight from `insight-query`; its `query` keeps the wrapper node that `query` drops */
- insight?: { query?: unknown }
- /** Column names for table-shaped results such as `WebStatsTableQuery` */
- columns?: string[]
- _posthogUrl?: string
-}
+import { QueryVisualization, type QueryDataPayload } from './QueryVisualization'
+import { insightQueryProperties } from './utils'
export interface ComponentProps {
data: unknown
}
export function Component({ data }: ComponentProps): ReactElement {
- const payload = data as DataPayload
+ const payload = data as QueryDataPayload
const visualizationType = inferVisualizationType(data)
const { queryKind, querySourceKind, display, funnelVizType } = insightQueryProperties(
payload?.insight?.query ?? payload?.query
@@ -94,65 +48,11 @@ export function Component({ data }: ComponentProps): ReactElement {
)
}
- const renderVisualization = (): ReactElement => {
- switch (visualizationType) {
- case 'trends':
- return (
- <TrendsVisualizer
- // The host updates `data` in place, so key on the query to re-seed state per result.
- key={JSON.stringify(payload.query)}
- query={payload.query as TrendsQuery}
- results={payload.results as TrendsResult}
- />
- )
-
- case 'funnel':
- return (
- <FunnelVisualizer query={payload.query as FunnelsQuery} results={payload.results as FunnelResult} />
- )
-
- case 'stickiness':
- return (
- <StickinessVisualizer
- // The host updates `data` in place, so key on the query to re-seed state per result.
- key={JSON.stringify(payload.query)}
- query={payload.query as StickinessQuery}
- results={payload.results as StickinessResult}
- />
- )
-
- case 'lifecycle':
- return (
- <LifecycleVisualizer
- query={payload.query as LifecycleQuery}
- results={payload.results as LifecycleResult}
- />
- )
-
- case 'retention':
- return (
- <RetentionVisualizer
- // The host updates `data` in place, so key on the query to re-seed state per result.
- key={JSON.stringify(payload.query)}
- query={payload.query as RetentionQuery}
- results={payload.results as RetentionResult}
- />
- )
-
- case 'paths':
- return <PathsVisualizer results={payload.results as PathsResult} />
-
- case 'table':
- return <TableVisualizer results={toTableResult(payload.query, payload.results, payload.columns)} />
-
- default:
- return <div className="text-muted-foreground">Unknown visualization type: {visualizationType}</div>
- }
- }
-
return (
<Card>
- <CardContent>{renderVisualization()}</CardContent>
+ <CardContent>
+ <QueryVisualization data={data} />
+ </CardContent>
</Card>
)
}
diff --git a/services/mcp/src/ui-apps/components/QueryVisualization.tsx b/services/mcp/src/ui-apps/components/QueryVisualization.tsx
new file mode 100644
index 000000000000..9b6409dd123e
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/QueryVisualization.tsx
@@ -0,0 +1,110 @@
+import type { ReactElement } from 'react'
+
+import { FunnelVisualizer } from './FunnelVisualizer'
+import { inferVisualizationType } from './infer-visualization'
+import { LifecycleVisualizer } from './LifecycleVisualizer'
+import { PathsVisualizer } from './PathsVisualizer'
+import { RetentionVisualizer } from './RetentionVisualizer'
+import { StickinessVisualizer } from './StickinessVisualizer'
+import { TableVisualizer } from './TableVisualizer'
+import { TrendsVisualizer } from './TrendsVisualizer'
+import type {
+ FunnelResult,
+ FunnelsQuery,
+ HogQLResult,
+ LifecycleQuery,
+ LifecycleResult,
+ PathsQuery,
+ PathsResult,
+ RetentionQuery,
+ RetentionResult,
+ StickinessQuery,
+ StickinessResult,
+ TrendsQuery,
+ TrendsResult,
+} from './types'
+import { toTableResult } from './utils'
+
+/** Data payload from MCP tools */
+export interface QueryDataPayload {
+ query?:
+ | TrendsQuery
+ | StickinessQuery
+ | FunnelsQuery
+ | LifecycleQuery
+ | RetentionQuery
+ | PathsQuery
+ | Record<string, unknown>
+ results:
+ | TrendsResult
+ | StickinessResult
+ | FunnelResult
+ | LifecycleResult
+ | RetentionResult
+ | PathsResult
+ | HogQLResult
+ /** Saved insight from `insight-query`; its `query` keeps the wrapper node that `query` drops */
+ insight?: { query?: unknown }
+ /** Column names for table-shaped results such as `WebStatsTableQuery` */
+ columns?: string[]
+ _posthogUrl?: string
+}
+
+export interface QueryVisualizationProps {
+ data: unknown
+}
+
+export function QueryVisualization({ data }: QueryVisualizationProps): ReactElement | null {
+ const payload = data as QueryDataPayload
+ switch (inferVisualizationType(data)) {
+ case 'trends':
+ return (
+ <TrendsVisualizer
+ // The host updates `data` in place, so key on the query to re-seed state per result.
+ key={JSON.stringify(payload.query)}
+ query={payload.query as TrendsQuery}
+ results={payload.results as TrendsResult}
+ />
+ )
+
+ case 'funnel':
+ return <FunnelVisualizer query={payload.query as FunnelsQuery} results={payload.results as FunnelResult} />
+
+ case 'stickiness':
+ return (
+ <StickinessVisualizer
+ // The host updates `data` in place, so key on the query to re-seed state per result.
+ key={JSON.stringify(payload.query)}
+ query={payload.query as StickinessQuery}
+ results={payload.results as StickinessResult}
+ />
+ )
+
+ case 'lifecycle':
+ return (
+ <LifecycleVisualizer
+ query={payload.query as LifecycleQuery}
+ results={payload.results as LifecycleResult}
+ />
+ )
+
+ case 'retention':
+ return (
+ <RetentionVisualizer
+ // The host updates `data` in place, so key on the query to re-seed state per result.
+ key={JSON.stringify(payload.query)}
+ query={payload.query as RetentionQuery}
+ results={payload.results as RetentionResult}
+ />
+ )
+
+ case 'paths':
+ return <PathsVisualizer results={payload.results as PathsResult} />
+
+ case 'table':
+ return <TableVisualizer results={toTableResult(payload.query, payload.results, payload.columns)} />
+
+ default:
+ return null
+ }
+}
diff --git a/services/mcp/src/ui-apps/hooks/useEvidenceCharts.tsx b/services/mcp/src/ui-apps/hooks/useEvidenceCharts.tsx
index 62b81f2d04a3..fa1849f1d36b 100644
--- a/services/mcp/src/ui-apps/hooks/useEvidenceCharts.tsx
+++ b/services/mcp/src/ui-apps/hooks/useEvidenceCharts.tsx
@@ -12,6 +12,7 @@ import { capture } from '../analytics/posthog'
import { loadRenderUiData } from '../apps/render-ui-data'
import { AppLoadingState } from '../components/AppLoadingState'
import { useMcpChartTheme } from '../components/charts/theme'
+import { QueryVisualization } from '../components/QueryVisualization'
import { TrendsVisualizer } from '../components/TrendsVisualizer'
import type { TrendsQuery, TrendsResult, TrendsResultItem } from '../components/types'
import { getSeriesLabel } from '../components/utils'
@@ -19,18 +20,19 @@ import { getSeriesLabel } from '../components/utils'
type EvidenceChart =
| { status: 'loading' }
| { status: 'error' }
- | { status: 'ready'; query: TrendsQuery; results: TrendsResult }
+ | { status: 'ready'; payload: { query?: Record<string, unknown>; results: unknown[] } }
-function seriesNames(item: TrendsResultItem, index: number): string[] {
- return [getSeriesLabel(item, index), ...[item.breakdown_value ?? []].flat().map(String)]
+interface Redraw {
+ tool: string
+ query: Record<string, unknown>
}
-function isTrendsQuery(query: Record<string, unknown>): boolean {
- return query.kind === 'TrendsQuery' || (query.kind === undefined && Array.isArray(query.series))
+function seriesNames(item: TrendsResultItem, index: number): string[] {
+ return [getSeriesLabel(item, index), ...[item.breakdown_value ?? []].flat().map(String)]
}
-function trendsQueryOf(item: StoryEvidence): Record<string, unknown> | null {
- return item.query && isTrendsQuery(item.query) ? item.query : null
+function redrawOf(item: StoryEvidence): Redraw | null {
+ return !item.chart && item.query && item.queryTool ? { tool: item.queryTool, query: item.query } : null
}
export function useEvidenceCharts(app: App | null, chartClassName: string): StoryEvidenceCharts | undefined {
@@ -39,7 +41,7 @@ export function useEvidenceCharts(app: App | null, chartClassName: string): Stor
const requested = useRef(new Set<string>())
const load = useCallback(
- (query: Record<string, unknown>): void => {
+ ({ tool, query }: Redraw): void => {
const key = JSON.stringify(query)
if (!app || requested.current.has(key)) {
return
@@ -53,17 +55,16 @@ export function useEvidenceCharts(app: App | null, chartClassName: string): Stor
}
setCharts((current) => ({ ...current, [key]: chart }))
}
- loadRenderUiData(app, 'query-trends', query, 'query-results').then(
+ loadRenderUiData(app, tool, query, 'query-results').then(
(result) => {
const payload = result.structuredContent as
- | { query?: TrendsQuery; results?: TrendsResult }
+ | { query?: Record<string, unknown>; results?: unknown[] }
| undefined
settle(
!result.isError && payload?.results?.length
? {
status: 'ready',
- query: payload.query ?? (query as unknown as TrendsQuery),
- results: payload.results,
+ payload: { ...payload, query: payload.query ?? query, results: payload.results },
}
: { status: 'error' }
)
@@ -77,9 +78,9 @@ export function useEvidenceCharts(app: App | null, chartClassName: string): Stor
const prefetch = useCallback(
(items: StoryEvidence[]): void =>
items.forEach((item) => {
- const query = trendsQueryOf(item)
- if (query && !item.chart) {
- load(query)
+ const redraw = redrawOf(item)
+ if (redraw) {
+ load(redraw)
}
}),
[load]
@@ -90,16 +91,16 @@ export function useEvidenceCharts(app: App | null, chartClassName: string): Stor
return undefined
}
return {
- canShow: (item) => !!item.chart || !!trendsQueryOf(item),
+ canShow: (item) => !!item.chart || !!redrawOf(item),
prefetch,
onShow: (item) => {
- const query = item.chart ? null : trendsQueryOf(item)
+ const redraw = redrawOf(item)
capture('mcp_ui_app_explain_chart_evidence_chart_shown', {
- was_loaded: !query || charts[JSON.stringify(query)]?.status === 'ready',
+ was_loaded: !redraw || charts[JSON.stringify(redraw.query)]?.status === 'ready',
inline: !!item.chart,
})
- if (query) {
- load(query)
+ if (redraw) {
+ load(redraw)
}
},
render: (item) => {
@@ -113,23 +114,27 @@ export function useEvidenceCharts(app: App | null, chartClassName: string): Stor
/>
)
}
- const query = trendsQueryOf(item)
- if (!query) {
+ const redraw = redrawOf(item)
+ if (!redraw) {
return null
}
- const chart = charts[JSON.stringify(query)]
+ const chart = charts[JSON.stringify(redraw.query)]
if (chart?.status === 'ready') {
+ if (redraw.tool !== 'query-trends') {
+ return <QueryVisualization key={JSON.stringify(redraw.query)} data={chart.payload} />
+ }
+ const results = chart.payload.results as TrendsResult
return (
<TrendsVisualizer
- key={JSON.stringify(query)}
- query={chart.query}
- results={chart.results}
- highlightedSeries={chart.results.flatMap((result, index) =>
+ key={JSON.stringify(redraw.query)}
+ query={chart.payload.query as unknown as TrendsQuery}
+ results={results}
+ highlightedSeries={results.flatMap((result, index) =>
isSeriesNamedIn(seriesNames(result, index), item.text) ? [index] : []
)}
showControls={false}
showTitle={false}
- showLegend={chart.results.length > 1}
+ showLegend={results.length > 1}
chartClassName={chartClassName}
/>
)
@@ -144,7 +149,7 @@ export function useEvidenceCharts(app: App | null, chartClassName: string): Stor
<Button
variant="outline"
size="xs"
- onClick={() => load(query)}
+ onClick={() => load(redraw)}
data-attr="explain-chart-evidence-retry"
>
Try again
diff --git a/services/mcp/tests/unit/explain-chart.test.ts b/services/mcp/tests/unit/explain-chart.test.ts
index 5e2a47d0f812..b5be39dae35a 100644
--- a/services/mcp/tests/unit/explain-chart.test.ts
+++ b/services/mcp/tests/unit/explain-chart.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
-import { ExplainChartInputSchema } from '@/schema/tool-inputs'
import { explainChartHandler } from '@/tools/insights/explainChart'
import { findStoryRange, lastBucketInProgress } from '@/tools/insights/storyRanges'
import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'
@@ -132,25 +131,38 @@ describe('explain-chart', () => {
})
})
- const hitRate = {
- type: 'line' as const,
- labels: ['20:00', '21:00'],
- series: [{ name: 'hit rate', values: [0.9, 0.55] }],
- }
-
- it('keeps a chart only for evidence that query-trends can draw again', async () => {
+ it('draws each piece of evidence from the query behind it', async () => {
const series = [{ kind: 'EventsNode', event: 'signed_up' }]
- const drawable = {
- kind: 'TrendsQuery',
- series,
- breakdownFilter: { breakdowns: [{ property: '$browser', type: 'event' }] },
- }
- const linkOnly = {
- kind: 'TrendsQuery',
- series,
- breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
+ const sqlResults: Record<string, { columns: string[]; results: unknown[][] }> = {
+ by_hour: {
+ columns: ['hour', 'browser', 'failures'],
+ results: [
+ ['2026-10-02 23:00:00', 'Safari', 4],
+ ['2026-10-03 00:00:00', 'Safari', 9],
+ ['2026-10-03 00:00:00', 'Chrome', 1],
+ ],
+ },
+ by_browser: { columns: ['browser', 'failures'], results: [['Safari', 13]] },
+ no_numbers: { columns: ['browser', 'version'], results: [['Safari', '17']] },
+ two_metrics: {
+ columns: ['hour', 'browser', 'failures', 'requests'],
+ results: [['2026-10-02 23:00:00', 'Safari', 4, 10]],
+ },
}
const context = createContext({ kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] } })
+ vi.mocked(context.api.query({ projectId: '1' }).runQuery).mockImplementation(
+ async ({ query }: { query: Record<string, unknown> }) => {
+ if (query.kind !== 'HogQLQuery') {
+ return { results: [{ label: 'signed_up', data: [5, 50, 6, 5, 4], days: DAYS }] }
+ }
+ const result = sqlResults[query.query as string]
+ if (!result) {
+ throw new Error('Unknown column "oops"')
+ }
+ return result
+ }
+ )
+ const sql = (query: string): Record<string, unknown> => ({ kind: 'HogQLQuery', query })
const result = await explainChartHandler(context, {
insightId: 'abc12345',
@@ -161,41 +173,77 @@ describe('explain-chart', () => {
title: 'A spike on October 2',
start: '2026-10-02',
evidence: [
- { text: 'Chrome sent most of it.', query: drawable },
- { text: 'Safari stayed flat.', query: linkOnly },
{
- text: 'The hit rate fell.',
- query: { kind: 'HogQLQuery', query: 'SELECT 1' },
- chart: hitRate,
+ text: 'Chrome sent most of it.',
+ query: {
+ kind: 'TrendsQuery',
+ series,
+ breakdownFilter: { breakdowns: [{ property: '$browser', type: 'event' }] },
+ },
},
+ {
+ text: 'Safari stayed flat.',
+ query: {
+ kind: 'TrendsQuery',
+ series,
+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
+ },
+ },
+ { text: 'Failures by hour.', query: sql('by_hour') },
+ { text: 'Failures by browser.', query: sql('by_browser') },
+ { text: 'Versions.', query: sql('no_numbers') },
+ { text: 'Two metrics.', query: sql('two_metrics') },
+ { text: 'No kind.', query: { series } },
+ { text: 'A broken query.', query: sql('oops') },
+ { text: 'An unknown kind.', query: { kind: '__proto__' } },
],
},
],
})
- expect(
- result.chapters[0]!.evidence.map((item) => [item.query !== null, item.chart ?? null, item.url !== null])
- ).toEqual([
- [true, null, true],
- [false, null, true],
- [false, hitRate, true],
- ])
- })
-
- it('refuses a chart whose series do not have one value per label', () => {
- const parsed = ExplainChartInputSchema.safeParse({
- insightId: 'abc12345',
- headline: 'One day stands out.',
- chapters: [
+ expect(result.chapters[0]!.evidence.map((item) => [item.queryTool, item.chart, item.url !== null])).toEqual([
+ ['query-trends', null, true],
+ [null, null, true],
+ [
+ null,
{
- title: 'A spike on October 2',
- start: '2026-10-02',
- evidence: [{ text: 'The hit rate fell.', chart: { ...hitRate, labels: ['20:00'] } }],
+ type: 'line',
+ labels: ['Oct 2 23:00', 'Oct 3 00:00'],
+ ticks: ['Oct 2 23:00', 'Oct 3 00:00'],
+ series: [
+ { name: 'Safari', values: [4, 9] },
+ { name: 'Chrome', values: [null, 1] },
+ ],
+ yAxisLabel: 'failures',
+ },
+ true,
+ ],
+ [
+ null,
+ {
+ type: 'bar',
+ labels: ['Safari'],
+ ticks: ['Safari'],
+ series: [{ name: 'failures', values: [13] }],
+ yAxisLabel: 'failures',
},
+ true,
],
+ [null, null, true],
+ [null, null, true],
+ ['query-trends', null, true],
+ [null, null, true],
+ [null, null, true],
+ ])
+ expect(context.api.query({ projectId: '1' }).runQuery).toHaveBeenCalledWith({
+ query: sql('by_hour'),
+ signal: expect.any(AbortSignal),
})
-
- expect(parsed.success).toBe(false)
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toContain('"Versions." returned nothing to draw')
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toContain('"Two metrics." returned nothing to draw')
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toContain(
+ '"A broken query." failed, so it shows as a link only: Unknown column "oops"'
+ )
})
it.each([
diff --git a/services/mcp/tests/unit/rate-limit-errors.test.ts b/services/mcp/tests/unit/rate-limit-errors.test.ts
index 1550c96bc4b2..40f5ec00723a 100644
--- a/services/mcp/tests/unit/rate-limit-errors.test.ts
+++ b/services/mcp/tests/unit/rate-limit-errors.test.ts
@@ -153,6 +153,22 @@ describe('outbound 429 handling', () => {
expect(mockFetch).toHaveBeenCalledTimes(4)
})
+ it('stops waiting to retry once the caller aborts', async () => {
+ const mockFetch = stubFetch(build429({ 'Retry-After': '10' }))
+ const controller = new AbortController()
+
+ const outcome = buildClient()
+ .query({ projectId: '1' })
+ .runQuery({ query: { kind: 'HogQLQuery', query: 'SELECT 1' }, signal: controller.signal })
+ .catch((error: unknown) => error)
+ await vi.advanceTimersByTimeAsync(1000)
+ controller.abort()
+
+ await expect(outcome).resolves.toBeInstanceOf(Error)
+
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+
it('fails fast without sleeping when Retry-After exceeds the wait budget', async () => {
const mockFetch = stubFetch(build429({ 'Retry-After': '3600' }))