Skip to content

Commit 3be2ea1

Browse files
fix(mcp): list PromQL catalog names from the tags table, without a time window (#3669)
Co-authored-by: Karl Power <85935352+karl-power@users.noreply.github.com>
1 parent b362d33 commit 3be2ea1

11 files changed

Lines changed: 218 additions & 141 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@hyperdx/api': patch
3+
---
4+
5+
fix(mcp): `clickstack_describe_source` on a PromQL source over a ClickHouse TimeSeries table reads metric names from the tags table without a time window, so it no longer runs out of memory on large tables. Label names are listed per metric with the new `metricName` argument.

‎MCP.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,8 @@ builder tools do not read it; use PromQL:
229229

230230
1. `clickstack_list_sources` shows each PromQL source with its `backend`
231231
(`prometheus` or `clickhouse`).
232-
2. `clickstack_describe_source` lists its metric names and label names.
232+
2. `clickstack_describe_source` lists its metric names, and with `metricName`
233+
that metric's label names.
233234
3. `clickstack_promql` runs an expression. A `range` query (default) returns
234235
`{ __hdx_time_bucket, series_name, value }` rows plus `seriesLabels`; an
235236
`instant` query evaluates at `endTime` and returns one row per series with a

‎packages/api/src/controllers/promql.ts‎

Lines changed: 33 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -256,33 +256,39 @@ async function fetchPrometheusData<T extends z.ZodTypeAny>(
256256

257257
export type PromqlLabelCatalog = {
258258
backend: PromqlBackend;
259-
labelNames: string[];
259+
/** Without `metricName`, only a Prometheus endpoint lists label names. */
260+
labelNames?: string[];
260261
metricNames: string[];
261262
};
262263

263264
/**
264-
* Lists the label names and metric names a PromQL source holds in
265-
* [startMs, endMs], at most `limit` of each. Returns `limit + 1` entries when
266-
* there are more, so callers can tell the list was cut. A ClickHouse source
267-
* reads them through the Prometheus HTTP API where resolveClickhouseLabelBackend
268-
* allows it, and with SQL otherwise.
265+
* Lists the metric names a PromQL source holds, and label names: of
266+
* `metricName` when given, else of every series on a Prometheus endpoint. At
267+
* most `limit` of each; returns `limit + 1` entries when there are more, so
268+
* callers can tell the list was cut.
269+
*
270+
* A Prometheus endpoint answers for [startMs, endMs]. A ClickHouse TimeSeries
271+
* table is read with SQL on its tags table, without the window, whatever
272+
* backend evaluates its queries: the window costs a pass over every series
273+
* id, on the HTTP API too, which large tables can't afford (#3648).
269274
*/
270275
export async function getPromqlLabelCatalog({
271276
teamId,
272277
source,
273278
startMs,
274279
endMs,
280+
metricName,
275281
limit,
276282
signal,
277283
}: {
278284
teamId: string;
279285
source: {
280286
connection: { toString(): string };
281287
from: { databaseName: string; tableName: string };
282-
promqlBackend?: PromqlSourceBackend;
283288
};
284289
startMs: number;
285290
endMs: number;
291+
metricName?: string;
286292
limit: number;
287293
signal?: AbortSignal;
288294
}): Promise<PromqlLabelCatalog> {
@@ -295,53 +301,32 @@ export async function getPromqlLabelCatalog({
295301
throw new Error('Connection not found');
296302
}
297303

298-
const params = {
299-
start: String(startMs / 1000),
300-
end: String(endMs / 1000),
301-
limit: String(limit + 1),
302-
};
303-
const fetchCatalog = (fetchLabels: (path: string) => Promise<string[]>) =>
304-
Promise.all([
305-
fetchLabels('/labels'),
306-
fetchLabels('/label/__name__/values'),
307-
]);
308-
309304
if (connection.isPrometheusEndpoint) {
310-
const [labelNames, metricNames] = await fetchCatalog(path =>
305+
const params = {
306+
start: String(startMs / 1000),
307+
end: String(endMs / 1000),
308+
limit: String(limit + 1),
309+
};
310+
const fetchLabels = (path: string, extra: Record<string, string> = {}) =>
311311
fetchPrometheusData(
312312
connection.host,
313313
`/api/v1${path}`,
314-
params,
314+
{ ...params, ...extra },
315315
labelListSchema,
316316
signal,
317+
);
318+
const [labelNames, metricNames] = await Promise.all([
319+
fetchLabels(
320+
'/labels',
321+
metricName != null
322+
? { 'match[]': `{__name__=${JSON.stringify(metricName)}}` }
323+
: {},
317324
),
318-
);
325+
fetchLabels('/label/__name__/values'),
326+
]);
319327
return { backend: 'prometheus', labelNames, metricNames };
320328
}
321329

322-
const { databaseName, tableName } = source.from;
323-
const labelBackend = await resolveClickhouseLabelBackend({
324-
connection,
325-
databaseName,
326-
tableName,
327-
promqlBackend: source.promqlBackend,
328-
});
329-
if (labelBackend === 'clickhouse-http') {
330-
const [labelNames, metricNames] = await fetchCatalog(path => {
331-
const { upstream, headers } = clickhousePrometheusRequest(connection);
332-
return fetchPrometheusData(
333-
upstream,
334-
`${CLICKHOUSE_PROMETHEUS_API_PREFIX}${path}`,
335-
{ ...params, database: databaseName, table: tableName },
336-
labelListSchema,
337-
signal,
338-
headers,
339-
CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE,
340-
);
341-
});
342-
return { backend: 'clickhouse', labelNames, metricNames };
343-
}
344-
345330
const args = {
346331
client: new ClickhouseClient({
347332
host: connection.host,
@@ -350,15 +335,14 @@ export async function getPromqlLabelCatalog({
350335
requestTimeout: PROMETHEUS_FETCH_TIMEOUT_MS,
351336
}),
352337
connectionId: connection.id,
353-
databaseName,
354-
tableName,
355-
startMs,
356-
endMs,
338+
databaseName: source.from.databaseName,
339+
tableName: source.from.tableName,
357340
limit: limit + 1,
358341
signal,
359342
};
343+
// No startMs/endMs: without them neither lookup reads the time ranges.
360344
const [labelNames, metricNames] = await Promise.all([
361-
queryLabelNames(args),
345+
metricName != null ? queryLabelNames({ ...args, metricName }) : undefined,
362346
queryLabelValues({ ...args, labelName: '__name__' }),
363347
]);
364348
return { backend: 'clickhouse', labelNames, metricNames };

‎packages/api/src/controllers/timeseriesEngine.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,12 +312,20 @@ export async function queryLabelValues({
312312
*/
313313
export async function queryLabelNames({
314314
limit,
315+
metricName,
315316
...args
316-
}: TimeSeriesTagsQueryArgs): Promise<string[]> {
317+
}: TimeSeriesTagsQueryArgs & {
318+
/** Only this metric's series; the tags table is sorted by metric name. */
319+
metricName?: string;
320+
}): Promise<string[]> {
317321
// The engine keeps `__name__` in `metric_name`, not `tags`, so it is folded
318322
// back in explicitly.
319323
const value = chSql`arrayJoin(arrayConcat([${{ String: '__name__' }}], mapKeys(${{ Identifier: 'tags' }})))`;
320324
const conditions = await getSeriesFilterConditions(args);
325+
if (metricName != null)
326+
conditions.push(
327+
chSql`${{ Identifier: 'metric_name' }} = ${{ String: metricName }}`,
328+
);
321329

322330
return queryDistinctTagsValues({ ...args, value, conditions, limit });
323331
}

‎packages/api/src/mcp/__tests__/promqlSources.int.test.ts‎

Lines changed: 96 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import { Source } from '@/models/source';
2121
import { callTool, createTestClient, getFirstText } from './mcpTestUtils';
2222

2323
const mockFetch = jest.mocked(global.fetch);
24-
const { realFetch } = globalThis as unknown as { realFetch: typeof fetch };
2524

2625
const TABLE = 'mcp_promql_sources';
2726

@@ -80,6 +79,13 @@ describe('MCP PromQL sources', () => {
8079
startSec: nowSec - 600,
8180
endSec: nowSec - 60,
8281
},
82+
// Two days old: outside the old 24-hour catalog window.
83+
{
84+
metricName: 'stale_metric',
85+
tags: { job: 'batch', region: 'eu' },
86+
startSec: nowSec - 3 * 86400,
87+
endSec: nowSec - 2 * 86400,
88+
},
8389
],
8490
withSamples: true,
8591
});
@@ -167,7 +173,7 @@ describe('MCP PromQL sources', () => {
167173
expect(text).toContain('up');
168174
});
169175

170-
it('describes a TimeSeries table by its label names and metric names', async () => {
176+
it('describes a TimeSeries table by its metric names, with no time window', async () => {
171177
const result = await callTool(client, 'clickstack_describe_source', {
172178
sourceId: promqlSource._id.toString(),
173179
});
@@ -180,14 +186,80 @@ describe('MCP PromQL sources', () => {
180186
backend: 'clickhouse',
181187
table: `${DEFAULT_DATABASE}.${TABLE}`,
182188
});
183-
expect(output.labelNames).toEqual(['__name__', 'instance', 'job']);
184-
expect(output.metricNames).toEqual(['http_requests_total', 'up']);
189+
expect(output.labelNames).toBeUndefined();
190+
expect(output.metricNames).toEqual([
191+
'http_requests_total',
192+
'stale_metric',
193+
'up',
194+
]);
195+
expect(output.note).toContain('metricName');
185196
expect(output.columns).toBeUndefined();
186197
expect(output.nextSteps.sql).toContain(
187198
`timeSeriesData(${DEFAULT_DATABASE}.${TABLE})`,
188199
);
189200
});
190201

202+
it("lists one metric's label names with metricName", async () => {
203+
const result = await callTool(client, 'clickstack_describe_source', {
204+
sourceId: promqlSource._id.toString(),
205+
metricName: 'stale_metric',
206+
});
207+
208+
const output = JSON.parse(getFirstText(result));
209+
expect(output.labelNames).toEqual(['__name__', 'job', 'region']);
210+
expect(output.metricNames).toContain('stale_metric');
211+
});
212+
213+
it('says so when no series has the metricName', async () => {
214+
const result = await callTool(client, 'clickstack_describe_source', {
215+
sourceId: promqlSource._id.toString(),
216+
metricName: 'no_such_metric',
217+
});
218+
219+
const output = JSON.parse(getFirstText(result));
220+
expect(output.labelNames).toEqual([]);
221+
expect(output.note).toContain(
222+
'No series has the metric name "no_such_metric".',
223+
);
224+
});
225+
226+
it('says a metric had no recent samples when an endpoint has no labels for it', async () => {
227+
const source = await createPrometheusSource();
228+
mockFetch.mockImplementation(async () => prometheusResponse([]));
229+
230+
const result = await callTool(client, 'clickstack_describe_source', {
231+
sourceId: source._id.toString(),
232+
metricName: 'idle_metric',
233+
});
234+
235+
const output = JSON.parse(getFirstText(result));
236+
expect(output.labelNames).toEqual([]);
237+
expect(output.note).toContain(
238+
'No series with the metric name "idle_metric" had samples in the last 24 hours.',
239+
);
240+
});
241+
242+
it('passes metricName to a Prometheus endpoint as a match[] selector', async () => {
243+
const source = await createPrometheusSource();
244+
mockFetch.mockImplementation(async () => prometheusResponse(['up']));
245+
246+
await callTool(client, 'clickstack_describe_source', {
247+
sourceId: source._id.toString(),
248+
metricName: 'http.server.duration',
249+
});
250+
251+
const urls = mockFetch.mock.calls.map(
252+
([input]) => new URL(String(input)),
253+
);
254+
const byPath = (path: string) => urls.find(u => u.pathname === path);
255+
expect(byPath('/api/v1/labels')?.searchParams.get('match[]')).toBe(
256+
'{__name__="http.server.duration"}',
257+
);
258+
expect(
259+
byPath('/api/v1/label/__name__/values')?.searchParams.has('match[]'),
260+
).toBe(false);
261+
});
262+
191263
it('describes a Prometheus endpoint source through its label API', async () => {
192264
const source = await createPrometheusSource();
193265
mockFetch.mockImplementation(async input =>
@@ -225,6 +297,19 @@ describe('MCP PromQL sources', () => {
225297
}
226298
});
227299

300+
it('adds no metric-name note when an endpoint has no labels in the window', async () => {
301+
const source = await createPrometheusSource();
302+
mockFetch.mockImplementation(async () => prometheusResponse([]));
303+
304+
const result = await callTool(client, 'clickstack_describe_source', {
305+
sourceId: source._id.toString(),
306+
});
307+
308+
const output = JSON.parse(getFirstText(result));
309+
expect(output.labelNames).toEqual([]);
310+
expect(output.note).toBeUndefined();
311+
});
312+
228313
it('still returns the source config when the label lookup fails', async () => {
229314
const source = await createPrometheusSource();
230315
mockFetch.mockRejectedValue(new Error('fetch failed'));
@@ -304,83 +389,24 @@ describe('MCP PromQL sources', () => {
304389
versionSpy = undefined;
305390
});
306391

307-
it("sends the label lookups with the source's table and the connection's credentials", async () => {
392+
// The handler's label lookups join every series as well (#3648).
393+
it('reads names with SQL even where the handler serves label lookups', async () => {
308394
stubServerVersion([26, 10, 0, 0]);
309-
mockFetch.mockImplementation(async input => {
310-
const { pathname } = new URL(String(input));
311-
if (pathname.endsWith('/format_query')) {
312-
return prometheusResponse('up');
313-
}
314-
return prometheusResponse(
315-
pathname.endsWith('/label/__name__/values')
316-
? ['up']
317-
: ['__name__', 'job'],
318-
);
319-
});
395+
mockFetch.mockImplementation(async () => prometheusResponse('up'));
320396

321397
const output = await describeAutoSource();
322398

323399
expect(output.source).toMatchObject({
324400
backend: 'clickhouse',
325401
table: `${DEFAULT_DATABASE}.${TABLE}`,
326402
});
327-
expect(output.labelNames).toEqual(['__name__', 'job']);
328-
expect(output.metricNames).toEqual(['up']);
329-
const urls = labelLookupUrls();
330-
expect(urls.map(u => u.pathname).sort()).toEqual([
331-
`${CLICKHOUSE_PROMETHEUS_API_PREFIX}/label/__name__/values`,
332-
`${CLICKHOUSE_PROMETHEUS_API_PREFIX}/labels`,
403+
expect(output.metricNames).toEqual([
404+
'http_requests_total',
405+
'stale_metric',
406+
'up',
333407
]);
334-
for (const url of urls) {
335-
expect(url.searchParams.getAll('database')).toEqual([
336-
DEFAULT_DATABASE,
337-
]);
338-
expect(url.searchParams.getAll('table')).toEqual([TABLE]);
339-
expect(url.searchParams.get('start')).toBeTruthy();
340-
expect(url.searchParams.get('end')).toBeTruthy();
341-
expect(url.searchParams.get('limit')).toBe('201');
342-
}
343-
for (const [input, init] of mockFetch.mock.calls) {
344-
if (new URL(String(input)).pathname.endsWith('/format_query')) {
345-
continue;
346-
}
347-
expect(init?.headers).toMatchObject({
348-
'X-ClickHouse-User': config.CLICKHOUSE_USER,
349-
'X-ClickHouse-Key': config.CLICKHOUSE_PASSWORD,
350-
'X-ClickHouse-Query-Id': expect.stringMatching(/^hdx-mcp-/),
351-
});
352-
}
353-
});
354-
355-
// 26.8's handler answers label lookups with a 400 ("not implemented").
356-
it('reads labels with SQL on ClickHouse 26.8, whose handler serves only queries', async () => {
357-
stubServerVersion([26, 8, 36, 3]);
358-
mockFetch.mockImplementation(async () => prometheusResponse('up'));
359-
360-
const output = await describeAutoSource();
361-
362-
expect(output.labelNames).toEqual(['__name__', 'instance', 'job']);
363-
expect(output.metricNames).toEqual(['http_requests_total', 'up']);
364408
expect(labelLookupUrls()).toEqual([]);
365409
});
366-
367-
// Needs ClickHouse 26.9+, whose handler serves label lookups.
368-
it('lists labels from the CI ClickHouse handler', async () => {
369-
mockFetch.mockImplementation(realFetch);
370-
371-
const output = await describeAutoSource();
372-
373-
expect(output.labelNames).toEqual(['__name__', 'instance', 'job']);
374-
expect(output.metricNames).toEqual(['http_requests_total', 'up']);
375-
expect(
376-
labelLookupUrls()
377-
.map(u => u.pathname)
378-
.sort(),
379-
).toEqual([
380-
`${CLICKHOUSE_PROMETHEUS_API_PREFIX}/label/__name__/values`,
381-
`${CLICKHOUSE_PROMETHEUS_API_PREFIX}/labels`,
382-
]);
383-
});
384410
});
385411

386412
it('keeps promqlBackend through a describe -> rename -> save round trip', async () => {

0 commit comments

Comments
 (0)