From 7d10fe1c73eb9cfc084f9bbb5a36534dd888c466 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Wed, 25 Nov 2026 08:42:46 +0100 Subject: [PATCH 1/2] feat(mcp): report each tile's wall time and read counts in query_tiles Agents could not tell an expensive dashboard tile from a cheap one: query_tiles kept only status, hasData and rowCount. Each tile that ran now reports elapsedMs (measured from when it starts, so time waiting in the queue doesn't count, and on failures too, since slow tiles are often the ones that fail), plus ClickHouse's rowsRead and bytesRead when the tile's result carries them. PromQL results get elapsedMs as well: the Prometheus API returns no read counts, so wall time is the only cost signal there. Part of #3649. --- .changeset/query-tiles-cost.md | 7 ++++ .../dashboards/promqlQueryTile.int.test.ts | 2 ++ .../dashboards/queryTiles.int.test.ts | 3 ++ .../dashboards/queryTilesHandler.test.ts | 3 ++ .../queryTilesSummarizeRows.test.ts | 15 ++++++++ .../mcp/__tests__/promqlQueryTool.int.test.ts | 3 +- .../src/mcp/tools/dashboards/queryTiles.ts | 35 +++++++++++++++++-- packages/api/src/mcp/tools/query/helpers.ts | 20 ++++++----- packages/api/src/mcp/tools/query/promql.ts | 4 ++- 9 files changed, 79 insertions(+), 13 deletions(-) create mode 100644 .changeset/query-tiles-cost.md diff --git a/.changeset/query-tiles-cost.md b/.changeset/query-tiles-cost.md new file mode 100644 index 0000000000..7aec237d59 --- /dev/null +++ b/.changeset/query-tiles-cost.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +--- + +feat(mcp): `clickstack_query_tiles` reports each tile's wall time (`elapsedMs`), +and rows and bytes read for builder and SQL tiles; PromQL results from +`clickstack_promql` and `clickstack_query_tile` carry `elapsedMs` diff --git a/packages/api/src/mcp/__tests__/dashboards/promqlQueryTile.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/promqlQueryTile.int.test.ts index 31960fe982..f5e30666cb 100644 --- a/packages/api/src/mcp/__tests__/dashboards/promqlQueryTile.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/promqlQueryTile.int.test.ts @@ -331,8 +331,10 @@ describe('MCP query_tile - PromQL tiles', () => { tileId: 'promql-tile', status: 'ok', hasData: true, + elapsedMs: expect.any(Number), }), ]); + expect(tiles[0]).not.toHaveProperty('rowsRead'); }); it('does not find a PromQL tile with PromQL disabled', async () => { diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts index 6b154c40e5..d6077e4fd9 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts @@ -243,6 +243,9 @@ describe('MCP Dashboard Tools - clickstack_query_tiles', () => { expect(tile.status).toBe('ok'); expect(tile.hasData).toBe(true); expect(tile.rowCount).toBeGreaterThan(0); + expect(tile.elapsedMs).toEqual(expect.any(Number)); + expect(tile.rowsRead).toBeGreaterThan(0); + expect(tile.bytesRead).toBeGreaterThan(0); }); it('skips a markdown tile passed explicitly in tileIds', async () => { diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts index 8834085252..148fadb095 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts @@ -123,6 +123,9 @@ describe('clickstack_query_tiles handler — per-tile failure isolation', () => expect(good.status).toBe('ok'); expect(boom.status).toBe('error'); expect(boom.error).toContain('source lookup exploded'); + // Failed tiles report their time too: the slow ones often fail. + expect(good.elapsedMs).toEqual(expect.any(Number)); + expect(boom.elapsedMs).toEqual(expect.any(Number)); }); it('does not issue a query for tiles scheduled after the deadline has passed', async () => { diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts index 8a01a97ad4..95dcd4d8c6 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts @@ -11,6 +11,21 @@ describe('summarizeRows', () => { expect(summarizeRows(text)).toEqual({ hasData: true, rowCount: 1 }); }); + it("reports ClickHouse's read counts when the result carries statistics", () => { + const text = JSON.stringify({ + result: { + data: [{ a: 1 }], + statistics: { elapsed: 0.01, rows_read: 50, bytes_read: 483 }, + }, + }); + expect(summarizeRows(text)).toEqual({ + hasData: true, + rowCount: 1, + rowsRead: 50, + bytesRead: 483, + }); + }); + it('reports hasData=false and rowCount=0 for an empty result set', () => { expect(summarizeRows(JSON.stringify({ result: [] }))).toEqual({ hasData: false, diff --git a/packages/api/src/mcp/__tests__/promqlQueryTool.int.test.ts b/packages/api/src/mcp/__tests__/promqlQueryTool.int.test.ts index d9918ba018..03a55ad3b3 100644 --- a/packages/api/src/mcp/__tests__/promqlQueryTool.int.test.ts +++ b/packages/api/src/mcp/__tests__/promqlQueryTool.int.test.ts @@ -104,7 +104,8 @@ describe('MCP clickstack_promql', () => { }); expect(result.isError ? getFirstText(result) : '').toBe(''); - const { data, seriesLabels } = parseResult(result); + const { data, seriesLabels, elapsedMs } = parseResult(result); + expect(elapsedMs).toEqual(expect.any(Number)); expect(seriesLabels).toEqual({ '{instance="checkout-0"}': { instance: 'checkout-0' }, '{instance="checkout-1"}': { instance: 'checkout-1' }, diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index bbde9c0dd2..6c034196e5 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -71,6 +71,11 @@ function isMarkdownTile(tile: ExternalDashboardTileWithId): boolean { return tile.config.displayType === 'markdown'; } +const readStatisticsSchema = z.object({ + rows_read: z.number(), + bytes_read: z.number(), +}); + /** * Derive a compact data summary from a successful tile query payload. The * payload shape is `{ result: , ... }` where `` is either an array @@ -83,6 +88,8 @@ function isMarkdownTile(tile: ExternalDashboardTileWithId): boolean { export function summarizeRows(text: string): { hasData?: boolean; rowCount?: number; + rowsRead?: number; + bytesRead?: number; } { let parsed: unknown; try { @@ -106,7 +113,19 @@ export function summarizeRows(text: string): { rows = result.data; } if (rows == null) return {}; - return { hasData: rows.length > 0, rowCount: rows.length }; + // ClickHouse's own read counts, present on builder and raw SQL tiles. + const stats = readStatisticsSchema.safeParse( + result != null && typeof result === 'object' && 'statistics' in result + ? result.statistics + : undefined, + ); + return { + hasData: rows.length > 0, + rowCount: rows.length, + ...(stats.success + ? { rowsRead: stats.data.rows_read, bytesRead: stats.data.bytes_read } + : {}), + }; } type TileSummary = { @@ -116,6 +135,10 @@ type TileSummary = { status: 'ok' | 'error' | 'skipped'; hasData?: boolean; rowCount?: number; + /** Wall time of the tile's query, from when it started (not queued). */ + elapsedMs?: number; + rowsRead?: number; + bytesRead?: number; error?: string; warnings?: string[]; }; @@ -144,7 +167,10 @@ export function registerQueryTiles({ 'unrecognized tile IDs come back as unknownTileIds rather than failing. ' + 'At most 50 tiles run per call; any beyond that are returned as ' + 'unrunTileIds — call again with those as tileIds to run the remainder. ' + - 'Drill into a specific failing tile with clickstack_query_tile.', + 'Drill into a specific failing tile with clickstack_query_tile. ' + + 'Each tile that ran reports elapsedMs, its wall time; builder and SQL ' + + 'tiles also report rowsRead and bytesRead. PromQL tiles report only ' + + 'elapsedMs: the Prometheus API returns no read counts.', inputSchema: z.object({ dashboardId: objectIdSchema.describe( 'Dashboard ID, from clickstack_get_dashboard (no id lists dashboards) ' + @@ -278,6 +304,8 @@ export function registerQueryTiles({ // results; the try/catch covers an unexpected throw or a deadline // timeout, folding either into a status:'error' entry so one // misbehaving tile never rejects the whole batch. + const started = Date.now(); + const elapsed = () => ({ elapsedMs: Date.now() - started }); try { const result = await withDeadline( signal => @@ -295,6 +323,7 @@ export function registerQueryTiles({ return { ...base, status: 'error', + ...elapsed(), error: result.content?.[0]?.text ?? 'Unknown error', }; } @@ -310,6 +339,7 @@ export function registerQueryTiles({ return { ...base, status: 'ok', + ...elapsed(), ...summarizeRows(text), ...(warnings.length > 0 ? { warnings } : {}), }; @@ -317,6 +347,7 @@ export function registerQueryTiles({ return { ...base, status: 'error', + ...elapsed(), error: err instanceof Error ? err.message : String(err), }; } diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index 0f1467df9f..2bcba36a7e 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -746,15 +746,17 @@ export async function runConfigTile( // PromQL is evaluated by the Prometheus API, not the SQL renderer. if (isPromqlSavedChartConfig(savedConfig)) { try { - return formatQueryResult( - await runPromqlTile({ - context, - config: savedConfig, - dateRange: [startDate, endDate], - variables: options?.variables, - signal: options?.abortSignal, - }), - ); + const started = Date.now(); + const result = await runPromqlTile({ + context, + config: savedConfig, + dateRange: [startDate, endDate], + variables: options?.variables, + signal: options?.abortSignal, + }); + // The Prometheus API returns no read counts (unlike the JSON statistics + // of a SQL query), so wall time is the cost signal. + return formatQueryResult({ ...result, elapsedMs: Date.now() - started }); } catch (e) { if (e instanceof PromQLQueryError) { return e.category === 'user' diff --git a/packages/api/src/mcp/tools/query/promql.ts b/packages/api/src/mcp/tools/query/promql.ts index 712c71e8ae..5a5c00e702 100644 --- a/packages/api/src/mcp/tools/query/promql.ts +++ b/packages/api/src/mcp/tools/query/promql.ts @@ -64,7 +64,9 @@ export function registerPromql({ context, registerTool }: ToolRegistrar) { 'A range query (the default) returns rows { __hdx_time_bucket, ' + 'series_name, value } plus seriesLabels, which maps each series_name to ' + 'its labels once. An instant query returns one row per series with a ' + - 'column per label plus Value, capped at 10,000 series.\n\n' + + 'column per label plus Value, capped at 10,000 series. Both carry ' + + "elapsedMs, the query's wall time; the Prometheus API returns no rows " + + 'or bytes read.\n\n' + 'Counters need rate() or increase(), e.g. ' + 'sum by (job) (rate(http_requests_total[$__rate_interval])). Percentiles ' + 'from histograms: histogram_quantile(0.95, sum by (le) ' + From ab3eea39a5a2ae3763a321d4a155d90612572bbd Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Wed, 25 Nov 2026 09:23:12 +0100 Subject: [PATCH 2/2] fix(mcp): no elapsedMs for a tile the deadline skipped Start a tile's clock inside the work withDeadline runs, so a tile that never started reports no time instead of 0, which reads as cheap. Time with performance.now(), and describe the PromQL elapsedMs as the call's wall time: it includes the source lookup and backend probe. Test statistics without bytes_read. --- .../dashboards/queryTilesHandler.test.ts | 2 ++ .../queryTilesSummarizeRows.test.ts | 7 +++++ .../src/mcp/tools/dashboards/queryTiles.ts | 30 +++++++++++-------- packages/api/src/mcp/tools/query/helpers.ts | 10 +++++-- packages/api/src/mcp/tools/query/promql.ts | 2 +- 5 files changed, 34 insertions(+), 17 deletions(-) diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts index 148fadb095..9bcf9dec8e 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts @@ -179,6 +179,8 @@ describe('clickstack_query_tiles handler — per-tile failure isolation', () => ); expect(overflow.status).toBe('error'); expect(overflow.error).toContain('deadline'); + // It never ran, so it reports no time (0 would read as cheap). + expect(overflow).not.toHaveProperty('elapsedMs'); const queriedIds = mockRunConfigTile.mock.calls.map((call: unknown[]) => { const t = call[1]; return t && typeof t === 'object' && 'id' in t ? t.id : undefined; diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts index 95dcd4d8c6..0256cb03af 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts @@ -26,6 +26,13 @@ describe('summarizeRows', () => { }); }); + it('omits both read counts when statistics are incomplete', () => { + const text = JSON.stringify({ + result: { data: [{ a: 1 }], statistics: { rows_read: 50 } }, + }); + expect(summarizeRows(text)).toEqual({ hasData: true, rowCount: 1 }); + }); + it('reports hasData=false and rowCount=0 for an empty result set', () => { expect(summarizeRows(JSON.stringify({ result: [] }))).toEqual({ hasData: false, diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index 6c034196e5..038af13f10 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -304,20 +304,24 @@ export function registerQueryTiles({ // results; the try/catch covers an unexpected throw or a deadline // timeout, folding either into a status:'error' entry so one // misbehaving tile never rejects the whole batch. - const started = Date.now(); - const elapsed = () => ({ elapsedMs: Date.now() - started }); + // Set when the query starts, so a tile the deadline skipped + // reports no time rather than 0. + let started: number | undefined; + const elapsed = () => + started === undefined + ? {} + : { elapsedMs: Math.round(performance.now() - started) }; try { - const result = await withDeadline( - signal => - runConfigTile( - context, - resolvedTile.tile, - startDate, - endDate, - { abortSignal: signal, variables }, - ), - deadlineAt, - ); + const result = await withDeadline(signal => { + started = performance.now(); + return runConfigTile( + context, + resolvedTile.tile, + startDate, + endDate, + { abortSignal: signal, variables }, + ); + }, deadlineAt); if ('isError' in result && result.isError) { return { diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index 2bcba36a7e..b722186c29 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -746,7 +746,7 @@ export async function runConfigTile( // PromQL is evaluated by the Prometheus API, not the SQL renderer. if (isPromqlSavedChartConfig(savedConfig)) { try { - const started = Date.now(); + const started = performance.now(); const result = await runPromqlTile({ context, config: savedConfig, @@ -755,8 +755,12 @@ export async function runConfigTile( signal: options?.abortSignal, }); // The Prometheus API returns no read counts (unlike the JSON statistics - // of a SQL query), so wall time is the cost signal. - return formatQueryResult({ ...result, elapsedMs: Date.now() - started }); + // of a SQL query), so wall time is the cost signal. It covers the whole + // tile: the source lookup and backend probe as well as the queries. + return formatQueryResult({ + ...result, + elapsedMs: Math.round(performance.now() - started), + }); } catch (e) { if (e instanceof PromQLQueryError) { return e.category === 'user' diff --git a/packages/api/src/mcp/tools/query/promql.ts b/packages/api/src/mcp/tools/query/promql.ts index 5a5c00e702..a4403ba818 100644 --- a/packages/api/src/mcp/tools/query/promql.ts +++ b/packages/api/src/mcp/tools/query/promql.ts @@ -65,7 +65,7 @@ export function registerPromql({ context, registerTool }: ToolRegistrar) { 'series_name, value } plus seriesLabels, which maps each series_name to ' + 'its labels once. An instant query returns one row per series with a ' + 'column per label plus Value, capped at 10,000 series. Both carry ' + - "elapsedMs, the query's wall time; the Prometheus API returns no rows " + + "elapsedMs, the call's wall time; the Prometheus API returns no rows " + 'or bytes read.\n\n' + 'Counters need rate() or increase(), e.g. ' + 'sum by (job) (rate(http_requests_total[$__rate_interval])). Percentiles ' +