Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/mcp-cost-meter.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 10 additions & 0 deletions MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions packages/api/src/mcp/__tests__/queryTool.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
4 changes: 4 additions & 0 deletions packages/api/src/mcp/__tests__/sources.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/mcp/tools/query/emergingSignals.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node';
import {
flattenBody,
TemplateMiner,
Expand Down Expand Up @@ -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 ' +
Expand Down
14 changes: 7 additions & 7 deletions packages/api/src/mcp/tools/query/runEventPatterns.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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(() =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — The nested meter's totals are thrown away on the one path where they differ from the call's meter

The nested withQueryCost gives different numbers from the call-level meter only inside clickstack_query_tiles, where several tiles share one call. But that path runs the tile output through summarizeRows (packages/api/src/mcp/tools/dashboards/queryTiles.ts:79-125). Its tilePayloadSchema only reads result.statistics, and the event-pattern payload is {summary, patterns, statistics} with no result key, so those per-tile numbers are dropped. In clickstack_event_patterns and clickstack_query_tile the inner and outer meters count the same queries. Fix: have summarizeRows also accept a top-level statistics and map it to rowsRead/bytesRead, then update the queryTiles description ('event-pattern tiles do not') and MCP.md:186. If that is out of scope, remove the nested meter and use getQueryCost().

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True for now: clickstack_query_tiles is unchanged in this PR (see Limits in the description), so its summary drops these numbers. The nested meter means that a later change only has to read statistics in summarizeRows to get per-tile numbers. Without it, each tile would report the whole call's total so far.

mineWindowPatterns(context, sourceId, startDate, endDate, {
where: options?.where,
whereLanguage: options?.whereLanguage,
bodyExpression: options?.bodyExpression,
Expand All @@ -466,7 +464,7 @@ export async function runEventPatterns(
abortSignal: options?.abortSignal,
variables: options?.variables,
includeDrilldownWhere: true,
},
}),
);
if ('error' in mined) return mined.error;

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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; ' +
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/mcp/tools/sources/describePromqlSource.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -129,6 +130,7 @@ function toResult(
query: PROMQL_QUERY_USAGE,
...(sqlUsage ? { sql: sqlUsage } : {}),
},
statistics: getQueryCost(),
},
null,
2,
Expand Down
3 changes: 3 additions & 0 deletions packages/api/src/mcp/tools/sources/describeSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -203,6 +204,7 @@ async function describeSourceSchema(
nextSteps: {
query: `Use clickstack_timeseries, clickstack_table, or clickstack_search with sourceId "${sourceId}".`,
},
statistics: getQueryCost(),
},
null,
2,
Expand Down Expand Up @@ -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
Expand Down
10 changes: 7 additions & 3 deletions packages/api/src/mcp/utils/tracing.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -110,14 +113,15 @@ export function withToolTracing<TArgs>(

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);
Expand Down
100 changes: 100 additions & 0 deletions packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
85 changes: 82 additions & 3 deletions packages/common-utils/src/clickhouse/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<QueryCost[]>();

/**
* 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<T>(
fn: () => Promise<T>,
): 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);
Expand Down Expand Up @@ -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<BaseResultSet<ReadableStream, Format>>;
});
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — Adding up elapsed as floats puts long decimal tails in agent-facing output

Adding ClickHouse's elapsed seconds as floats (e.g. 0.001234 + 0.002345 = 0.0035790000000000006) puts rounding noise into the statistics that the three tools serialise. Round once where the cost is read, in getQueryCost() and in the cost copy that withQueryCost returns, e.g. Math.round(elapsed * 1e6) / 1e6. Keep the running total unrounded.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 488d433: getQueryCost() and the returned cost round elapsed to microseconds; the running total stays exact.

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<ReadableStream, Format>;
}
}
Loading