diff --git a/.changeset/mcp-cost-meter.md b/.changeset/mcp-cost-meter.md new file mode 100644 index 0000000000..eca2e31f21 --- /dev/null +++ b/.changeset/mcp-cost-meter.md @@ -0,0 +1,10 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/api': patch +--- + +feat(mcp): `clickstack_event_patterns`, `clickstack_emerging_signals` and +`clickstack_describe_source` return `statistics` (`elapsed`, `rows_read`, +`bytes_read`, `queries`), summed over the ClickHouse queries of the call. A +query cost meter in the node ClickHouse client (`withQueryCost`) adds up the +statistics of each JSON result. diff --git a/MCP.md b/MCP.md index ea99bd3160..41d6e27439 100644 --- a/MCP.md +++ b/MCP.md @@ -185,6 +185,16 @@ and PromQL tiles report the cost of the call: rows returned or the size of the response. Builder and SQL tiles report them when available. PromQL and event-pattern tiles report only `elapsedMs`. - A successful PromQL response carries its time at `result.elapsedMs`. +- `clickstack_event_patterns`, `clickstack_emerging_signals` and + `clickstack_describe_source` return `statistics` in the shape + `clickstack_table` uses (`elapsed` in seconds, `rows_read`, `bytes_read`), + summed over the ClickHouse queries of the call, and `queries`, how many + queries reported them. Only JSON results carry statistics: a result read as a + stream, like the primary key values `clickstack_describe_source` reads from + the index, is not counted. `elapsed` is ClickHouse time, so queries that run + at the same time add up to more than the wall time. A cached schema lookup + runs no query and adds nothing. An event-pattern tile in + `clickstack_query_tile` reports only its own queries. ### Metric Sources diff --git a/packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts b/packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts index fb72744460..9db1fd9f5b 100644 --- a/packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts +++ b/packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts @@ -196,6 +196,10 @@ describe('MCP Emerging Signals Tool', () => { expect(output.summary.currentWindow.sampled).toBeGreaterThan(0); expect(output.summary.baselineWindow.sampled).toBeGreaterThan(0); expect(output.summary.warning).toBeUndefined(); + // What ClickHouse read for the call. + expect(output.statistics.queries).toBeGreaterThan(0); + expect(output.statistics.rows_read).toBeGreaterThan(0); + expect(output.statistics.bytes_read).toBeGreaterThan(0); // The shadow-eval template must appear in the emerging list as "new". expect(output.emerging.length).toBeGreaterThan(0); diff --git a/packages/api/src/mcp/__tests__/queryTool.int.test.ts b/packages/api/src/mcp/__tests__/queryTool.int.test.ts index 0169fe6c1e..5e25708c31 100644 --- a/packages/api/src/mcp/__tests__/queryTool.int.test.ts +++ b/packages/api/src/mcp/__tests__/queryTool.int.test.ts @@ -798,6 +798,10 @@ describe('MCP Query Tools', () => { expect(output).toHaveProperty('summary'); expect(output).toHaveProperty('patterns'); expect(output.summary).toHaveProperty('totalCount'); + // What ClickHouse read for the call. + expect(output.statistics.queries).toBeGreaterThan(0); + expect(output.statistics.rows_read).toBeGreaterThan(0); + expect(output.statistics.bytes_read).toBeGreaterThan(0); expect(output.summary).toHaveProperty('sampledCount'); expect(output.summary).toHaveProperty('sampleMultiplier'); expect(output.summary).toHaveProperty('bodyColumn', 'Body'); diff --git a/packages/api/src/mcp/__tests__/sources.int.test.ts b/packages/api/src/mcp/__tests__/sources.int.test.ts index a72dd60777..7c0574d0d3 100644 --- a/packages/api/src/mcp/__tests__/sources.int.test.ts +++ b/packages/api/src/mcp/__tests__/sources.int.test.ts @@ -445,6 +445,10 @@ describe('MCP Source Tools', () => { expect(output.source.columns[0]).toHaveProperty('name'); expect(output.source.columns[0]).toHaveProperty('type'); expect(output.source.columns[0]).toHaveProperty('jsType'); + // What ClickHouse read for the call. + expect(output.statistics.queries).toBeGreaterThan(0); + expect(output.statistics.rows_read).toBeGreaterThan(0); + expect(output.statistics.bytes_read).toBeGreaterThan(0); }); it('should return full column schema for a log source', async () => { diff --git a/packages/api/src/mcp/tools/query/emergingSignals.ts b/packages/api/src/mcp/tools/query/emergingSignals.ts index ad2fc5b20a..4786fbee3a 100644 --- a/packages/api/src/mcp/tools/query/emergingSignals.ts +++ b/packages/api/src/mcp/tools/query/emergingSignals.ts @@ -1,3 +1,4 @@ +import { getQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node'; import { flattenBody, TemplateMiner, @@ -587,6 +588,7 @@ export function registerEmergingSignals({ }, emerging: emerging.slice(0, input.topN).map(fmt), disappeared: disappeared.slice(0, input.topN).map(fmt), + statistics: getQueryCost(), usage: 'emerging = patterns newly present or >= minShareRatioĂ— more frequent ' + '(by share of window) now vs baseline; status "new" means absent from ' + diff --git a/packages/api/src/mcp/tools/query/runEventPatterns.ts b/packages/api/src/mcp/tools/query/runEventPatterns.ts index 23462a51de..0fa697f75e 100644 --- a/packages/api/src/mcp/tools/query/runEventPatterns.ts +++ b/packages/api/src/mcp/tools/query/runEventPatterns.ts @@ -1,3 +1,4 @@ +import { withQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node'; import { getMetadata } from '@hyperdx/common-utils/dist/core/metadata'; import { getSourceTableFilters } from '@hyperdx/common-utils/dist/core/searchChartConfig'; import { @@ -451,12 +452,9 @@ export async function runEventPatterns( // conversion, sampleMultiplier usage). The helper wraps minePatterns in // try/catch and returns an {error} union, so a thrown Drain error surfaces as // a clean MCP error here rather than escaping. - const mined = await mineWindowPatterns( - context, - sourceId, - startDate, - endDate, - { + // Its own meter, so a dashboard tile reports only its own queries. + const { result: mined, cost: statistics } = await withQueryCost(() => + mineWindowPatterns(context, sourceId, startDate, endDate, { where: options?.where, whereLanguage: options?.whereLanguage, bodyExpression: options?.bodyExpression, @@ -466,7 +464,7 @@ export async function runEventPatterns( abortSignal: options?.abortSignal, variables: options?.variables, includeDrilldownWhere: true, - }, + }), ); if ('error' in mined) return mined.error; @@ -503,6 +501,7 @@ export async function runEventPatterns( timeRange, }, patterns: [], + statistics, hint: 'No data found in the queried time range. Try setting startTime to a wider window (e.g. 24 hours ago) or check that filters match existing data.', }, null, @@ -604,6 +603,7 @@ export async function runEventPatterns( }, }, patterns, + statistics, usage: 'totalCount is exact. sampleCount is the number of sampled rows in the pattern. ' + 'estimatedCount = sampleCount * sampleMultiplier, an extrapolation, not a count; ' + diff --git a/packages/api/src/mcp/tools/sources/describePromqlSource.ts b/packages/api/src/mcp/tools/sources/describePromqlSource.ts index 9317f9678d..3a68e28bbb 100644 --- a/packages/api/src/mcp/tools/sources/describePromqlSource.ts +++ b/packages/api/src/mcp/tools/sources/describePromqlSource.ts @@ -1,3 +1,4 @@ +import { getQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node'; import { quoteIdentifierIfNeeded } from '@hyperdx/common-utils/dist/core/metadata'; import { getPromqlLabelCatalog } from '@/controllers/promql'; @@ -129,6 +130,7 @@ function toResult( query: PROMQL_QUERY_USAGE, ...(sqlUsage ? { sql: sqlUsage } : {}), }, + statistics: getQueryCost(), }, null, 2, diff --git a/packages/api/src/mcp/tools/sources/describeSource.ts b/packages/api/src/mcp/tools/sources/describeSource.ts index bd4ff88eb9..2353a8a9bc 100644 --- a/packages/api/src/mcp/tools/sources/describeSource.ts +++ b/packages/api/src/mcp/tools/sources/describeSource.ts @@ -3,6 +3,7 @@ import { filterColumnMetaByType, JSDataType, } from '@hyperdx/common-utils/dist/clickhouse'; +import { getQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node'; import { getMetadata, tcFromSource, @@ -203,6 +204,7 @@ async function describeSourceSchema( nextSteps: { query: `Use clickstack_timeseries, clickstack_table, or clickstack_search with sourceId "${sourceId}".`, }, + statistics: getQueryCost(), }, null, 2, @@ -552,6 +554,7 @@ function formatDescribeResult({ "Use bracket syntax for map columns: ResourceAttributes['service.name'], SpanAttributes['http.method']", ...(discoveryNextStep && { discovery: discoveryNextStep }), }, + statistics: getQueryCost(), }); const finalOutput = isTrimmed diff --git a/packages/api/src/mcp/utils/tracing.ts b/packages/api/src/mcp/utils/tracing.ts index 48ae9d9b3f..98d780045c 100644 --- a/packages/api/src/mcp/utils/tracing.ts +++ b/packages/api/src/mcp/utils/tracing.ts @@ -1,4 +1,7 @@ -import { withQueryAttribution } from '@hyperdx/common-utils/dist/clickhouse/node'; +import { + withQueryAttribution, + withQueryCost, +} from '@hyperdx/common-utils/dist/clickhouse/node'; import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { recordOnboardingTaskCompletion } from '@/controllers/user'; @@ -110,14 +113,15 @@ export function withToolTracing( try { // Around the whole handler, so every query the tool makes carries - // the tool name and who called it. + // the tool name and who called it, and tools can report the call's + // cost with getQueryCost(). const result = await withQueryAttribution( { surface: 'mcp', label: toolName, trace: getActiveTraceId(), }, - async () => handler(args), + async () => (await withQueryCost(async () => handler(args))).result, ); const durationMs = Date.now() - startTime; const responseBytes = getResponseSizeBytes(result.content); diff --git a/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts b/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts new file mode 100644 index 0000000000..57febf2714 --- /dev/null +++ b/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts @@ -0,0 +1,100 @@ +import type { ClickHouseClient as NodeClickHouseClient } from '@clickhouse/client'; + +import { + ClickhouseClient, + getQueryCost, + withQueryCost, +} from '@/clickhouse/node'; + +/** Answers every query with the statistics `statsFor` gives for its SQL. */ +class FakeServerClient extends ClickhouseClient { + constructor(private statsFor: (query: string) => object | undefined) { + super({ host: 'http://localhost:8123' }); + } + + protected getClient(): NodeClickHouseClient { + return { + query: async ({ query }: { query: string }) => ({ + json: async () => ({ data: [], statistics: this.statsFor(query) }), + }), + } as unknown as NodeClickHouseClient; + } +} + +const run = async (client: ClickhouseClient, query: string) => + (await client.query({ query, shouldSkipApplySettings: true })).json(); + +const client = new FakeServerClient(query => { + if (query === 'SELECT none') return undefined; + if (query === 'SELECT tenth') { + return { elapsed: 0.1, rows_read: 1, bytes_read: 1 }; + } + if (query === 'SELECT malformed') { + return { elapsed: 0.5, rows_read: '10', bytes_read: 100 }; + } + return { elapsed: 0.5, rows_read: 10, bytes_read: 100 }; +}); + +describe('withQueryCost', () => { + it('sums the statistics of the JSON results read in it', async () => { + const { result, cost } = await withQueryCost(async () => { + await run(client, 'SELECT 1'); + await run(client, 'SELECT 2'); + // No complete statistics in the body: not counted. + await run(client, 'SELECT none'); + await run(client, 'SELECT malformed'); + return getQueryCost(); + }); + + const expected = { elapsed: 1, rows_read: 20, bytes_read: 200, queries: 2 }; + expect(result).toEqual(expected); + expect(cost).toEqual(expected); + }); + + it('adds a nested meter to the enclosing one, not the reverse', async () => { + const { result: inner, cost: outer } = await withQueryCost(async () => { + await run(client, 'SELECT outer'); + const { cost } = await withQueryCost(() => run(client, 'SELECT inner')); + return cost; + }); + + expect(inner).toMatchObject({ rows_read: 10, queries: 1 }); + expect(outer).toMatchObject({ rows_read: 20, queries: 2 }); + }); + + it('rounds elapsed to microseconds', async () => { + const { result, cost } = await withQueryCost(async () => { + // 0.1 + 0.1 + 0.1 is 0.30000000000000004 in floating point. + for (let i = 0; i < 3; i++) await run(client, 'SELECT tenth'); + return getQueryCost(); + }); + + expect(result?.elapsed).toBe(0.3); + expect(cost.elapsed).toBe(0.3); + }); + + it('keeps concurrent meters apart', async () => { + const [one, two] = await Promise.all([ + withQueryCost(() => run(client, 'SELECT 1')), + withQueryCost(async () => { + await run(client, 'SELECT 1'); + await run(client, 'SELECT 2'); + }), + ]); + + expect(one.cost.queries).toBe(1); + expect(two.cost.queries).toBe(2); + }); + + it('counts nothing outside a meter', async () => { + const resultSet = await client.query({ + query: 'SELECT 1', + shouldSkipApplySettings: true, + }); + expect(getQueryCost()).toBeUndefined(); + + // Read inside a meter, but issued outside one. + const { cost } = await withQueryCost(() => resultSet.json()); + expect(cost.queries).toBe(0); + }); +}); diff --git a/packages/common-utils/src/clickhouse/node.ts b/packages/common-utils/src/clickhouse/node.ts index 6fd48afb1d..add25d3854 100644 --- a/packages/common-utils/src/clickhouse/node.ts +++ b/packages/common-utils/src/clickhouse/node.ts @@ -7,6 +7,7 @@ import type { DataFormat, } from '@clickhouse/client'; import { createClient } from '@clickhouse/client'; +import { z } from 'zod/v3'; import { mergeQueryAttribution, QueryAttribution } from './attribution'; import { @@ -47,6 +48,62 @@ export function getCurrentQueryAttribution(): QueryAttribution | undefined { return attributionStore.getStore(); } +/** ClickHouse's own numbers, summed over the queries that reported them. */ +export type QueryCost = { + /** Server time in seconds; concurrent queries add up past wall time. */ + elapsed: number; + rows_read: number; + bytes_read: number; + /** How many queries reported statistics (JSON results read with json()). */ + queries: number; +}; + +const statisticsBodySchema = z.object({ + statistics: z.object({ + elapsed: z.number(), + rows_read: z.number(), + bytes_read: z.number(), + }), +}); + +// Every meter in effect, innermost last: a query adds to all of them. +const costStore = new AsyncLocalStorage(); + +/** + * Sums the `statistics` of every JSON query `fn` issues, including queries in + * nested meters. A query whose body has no complete statistics is not counted. + * Read the totals with getQueryCost() inside `fn`, or from the returned + * `cost`, which holds the results read before `fn` resolved. + */ +export async function withQueryCost( + fn: () => Promise, +): Promise<{ result: T; cost: QueryCost }> { + const cost: QueryCost = { + elapsed: 0, + rows_read: 0, + bytes_read: 0, + queries: 0, + }; + const result = await costStore.run( + [...(costStore.getStore() ?? []), cost], + fn, + ); + return { result, cost: readCost(cost) }; +} + +// The running total stays exact; a copy for output drops float noise. +const readCost = (cost: QueryCost): QueryCost => ({ + ...cost, + elapsed: Math.round(cost.elapsed * 1e6) / 1e6, +}); + +/** The innermost meter's totals so far, if a meter is in effect. */ +export function getQueryCost(): QueryCost | undefined { + const meters = costStore.getStore(); + const cost = meters?.[meters.length - 1]; + return cost && readCost(cost); +} + export class ClickhouseClient extends BaseClickhouseClient { constructor(options: ClickhouseClientOptions) { super(options); @@ -113,14 +170,36 @@ export class ClickhouseClient extends BaseClickhouseClient { } // TODO: Custom error handling - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- client library type mismatch - return this.getClient().query({ + const resultSet = await this.getClient().query({ query, query_params, format, abort_signal, clickhouse_settings: clickhouseSettings, query_id: queryId, - }) as unknown as Promise>; + }); + const meters = costStore.getStore(); + if (meters) { + // A JSON body ends with the query's statistics, so count them when the + // caller reads it. + const json = resultSet.json.bind(resultSet); + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- same method, wrapped + resultSet.json = (async () => { + const body = await json(); + const parsed = statisticsBodySchema.safeParse(body); + if (parsed.success) { + const stats = parsed.data.statistics; + for (const cost of meters) { + cost.elapsed += stats.elapsed; + cost.rows_read += stats.rows_read; + cost.bytes_read += stats.bytes_read; + cost.queries++; + } + } + return body; + }) as typeof resultSet.json; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- client library type mismatch + return resultSet as unknown as BaseResultSet; } }