Skip to content
Merged
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.

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 in runEventPatterns can't help clickstack_query_tiles, the only place it would matter

Two of the three callers already get the right number without the inner meter. clickstack_event_patterns and clickstack_query_tile each run one pattern job per call, so their tool-level meter (tracing.ts) gives the same totals. Per-tile cost would only add something in clickstack_query_tiles, but there summarizeRows (dashboards/queryTiles.ts:79-124) only parses { result: ... } payloads. It throws away the top-level statistics that an event-pattern tile returns. Fix one of two ways: (a) teach tilePayloadSchema/summarizeRows to read the event-pattern payload's top-level statistics so the tile gets rowsRead/bytesRead, and update the MCP.md line saying event-pattern tiles report only elapsedMs; or (b) remove the inner withQueryCost and use getQueryCost() like the other two tools.

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

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);
});
});
Loading
Loading