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
8 changes: 8 additions & 0 deletions .changeset/mcp-sql-batch-queries.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@hyperdx/api': patch
---

feat(mcp): `clickstack_sql` accepts a `queries` array to run up to 10
independent queries in parallel under a shared 60s deadline. Each query reports
its own `ok`/`error`/`timeout` status, so one failing query does not fail the
others. Single-query calls with `sql` behave as before.
2 changes: 1 addition & 1 deletion MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ with:
| `clickstack_event_patterns` | Discover the most common log messages and event patterns using Drain clustering |
| `clickstack_event_deltas` | Compare two row groups and rank properties by how their value distributions differ |
| `clickstack_emerging_signals` | Detect NEW or GONE log/event patterns between a baseline and a current window (two-window Drain novelty diff) |
| `clickstack_sql` | Execute raw ClickHouse SQL for advanced queries (JOINs, CTEs, sub-queries) |
| `clickstack_sql` | Execute raw ClickHouse SQL for advanced queries (JOINs, CTEs, sub-queries); pass `queries` to run up to 10 in parallel |
| `clickstack_get_dashboard` | List all dashboards or get full detail for a specific dashboard |
| `clickstack_save_dashboard` | Create or update a dashboard with tiles (charts, tables, numbers, search, markdown) |
| `clickstack_delete_dashboard` | Permanently delete a dashboard and its attached alerts |
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
summarizeRows,
TileDeadlineError,
withDeadline,
} from '@/mcp/tools/dashboards/queryTiles';
import { summarizeRows } from '@/mcp/tools/dashboards/queryTiles';

describe('summarizeRows', () => {
it('reads a top-level array result as rows', () => {
Expand Down Expand Up @@ -46,61 +42,3 @@ describe('summarizeRows', () => {
expect(summarizeRows('123')).toEqual({});
});
});

describe('withDeadline', () => {
it('resolves work that finishes before the deadline', async () => {
await expect(
withDeadline(() => Promise.resolve('done'), Date.now() + 1000),
).resolves.toBe('done');
});

it('rejects with TileDeadlineError when work exceeds the deadline', async () => {
const slow = () =>
new Promise<string>(resolve => setTimeout(() => resolve('too late'), 50));
await expect(withDeadline(slow, Date.now() + 5)).rejects.toBeInstanceOf(
TileDeadlineError,
);
});

it('does not start the work when the shared deadline is already in the past', async () => {
// A tile scheduled after the batch budget is spent must fail fast WITHOUT
// invoking the thunk — this is what keeps the post-deadline drain from
// issuing any (un-cancellable) ClickHouse queries.
const start = jest.fn(() => Promise.resolve('too late'));
await expect(withDeadline(start, Date.now() - 1)).rejects.toBeInstanceOf(
TileDeadlineError,
);
expect(start).not.toHaveBeenCalled();
});

it('propagates a rejection from the underlying work', async () => {
const boom = () => Promise.reject(new Error('boom'));
await expect(withDeadline(boom, Date.now() + 1000)).rejects.toThrow('boom');
});

it('aborts the signal handed to the work when the deadline fires', async () => {
// The signal must fire so the in-flight ClickHouse query is cancelled
// server-side rather than left running after the batch gives up on it.
let captured: AbortSignal | undefined;
const slow = (signal: AbortSignal) => {
captured = signal;
return new Promise<string>(resolve =>
setTimeout(() => resolve('too late'), 50),
);
};
await expect(withDeadline(slow, Date.now() + 5)).rejects.toBeInstanceOf(
TileDeadlineError,
);
expect(captured?.aborted).toBe(true);
});

it('aborts the signal once work resolves so no query outlives the call', async () => {
let captured: AbortSignal | undefined;
const work = (signal: AbortSignal) => {
captured = signal;
return Promise.resolve('done');
};
await expect(withDeadline(work, Date.now() + 1000)).resolves.toBe('done');
expect(captured?.aborted).toBe(true);
});
});
107 changes: 106 additions & 1 deletion packages/api/src/mcp/__tests__/queryTool.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,11 @@ describe('MCP Query Tools', () => {
expect(props).toContain('sql');
expect(props).toContain('startTime');
expect(props).toContain('endTime');
expect(props).toContain('queries');
expect(tool!.inputSchema.required).toContain('connectionId');
expect(tool!.inputSchema.required).toContain('sql');
// sql and queries are alternatives, so neither is required by the schema.
expect(tool!.inputSchema.required).not.toContain('sql');
expect(tool!.inputSchema.required).not.toContain('queries');
});

it('exposes an optional sourceId on clickstack_sql', async () => {
Expand Down Expand Up @@ -1004,6 +1007,108 @@ describe('MCP Query Tools', () => {
{ value: 1, label: 'a' },
]);
});

describe('queries (batch mode)', () => {
it('runs each query and reports its own status', async () => {
const result = await callTool(client, 'clickstack_sql', {
connectionId: connection._id.toString(),
queries: [
{ id: 'one', sql: 'SELECT 1 AS value' },
{ id: 'bad', sql: 'SELECTT 1' },
{ id: 'two', sql: 'SELECT 2 AS value' },
],
});

expect(result.isError).toBeFalsy();
const parsed = JSON.parse(getFirstText(result));
expect(parsed.summary).toEqual({
total: 3,
ok: 2,
error: 1,
timeout: 0,
});
const [one, bad, two] = parsed.results;
expect(one).toMatchObject({ index: 0, id: 'one', status: 'ok' });
expect(one.result.data).toEqual([{ value: 1 }]);
expect(bad).toMatchObject({ index: 1, id: 'bad', status: 'error' });
expect(bad.error).toMatch(/syntax/i);
expect(two.result.data).toEqual([{ value: 2 }]);
});

it("expands $__sourceTable per query from that query's sourceId", async () => {
const now = Date.now();
await bulkInsertLogs(
[1, 2].map(minutesAgo => ({
Body: 'batch source',
ServiceName: 'sql-batch-source',
SeverityText: 'INFO',
Timestamp: new Date(now - minutesAgo * 60 * 1000),
})),
);

const result = await callTool(client, 'clickstack_sql', {
connectionId: connection._id.toString(),
queries: [
{
id: 'logs',
sourceId: logSource._id.toString(),
sql:
'SELECT count() AS n FROM $__sourceTable ' +
"WHERE $__timeFilter(Timestamp) AND ServiceName = 'sql-batch-source'",
},
{ id: 'noSource', sql: 'SELECT count() FROM $__sourceTable' },
],
startTime: new Date(now - 60 * 60 * 1000).toISOString(),
endTime: new Date(now).toISOString(),
});

const parsed = JSON.parse(getFirstText(result));
expect(parsed.results[0].result.data).toEqual([{ n: '2' }]);
expect(parsed.results[1].status).toBe('error');
expect(parsed.results[1].error).toContain(
'$__sourceTable needs a sourceId',
);
});

it('keeps readonly enforcement for every query', async () => {
const result = await callTool(client, 'clickstack_sql', {
connectionId: connection._id.toString(),
queries: [
{
sql: `INSERT INTO ${DEFAULT_DATABASE}.${DEFAULT_LOGS_TABLE} (Body) VALUES ('x')`,
},
],
});

expect(result.isError).toBe(true);
const parsed = JSON.parse(getFirstText(result));
expect(parsed.results[0].status).toBe('error');
expect(parsed.results[0].error).toMatch(/readonly/i);
});

it('rejects passing both sql and queries', async () => {
const result = await callTool(client, 'clickstack_sql', {
connectionId: connection._id.toString(),
sql: 'SELECT 1',
queries: [{ sql: 'SELECT 2' }],
});

expect(result.isError).toBe(true);
expect(getFirstText(result)).toContain('exactly one of sql');
});

it('rejects more than 10 queries at the schema', async () => {
const result = await callTool(client, 'clickstack_sql', {
connectionId: connection._id.toString(),
queries: Array.from({ length: 11 }, (_, i) => ({
sql: `SELECT ${i}`,
})),
});

expect(result.isError).toBe(true);
expect(getFirstText(result)).toContain('Input validation error');
});
});
});

// ─── ClickHouse query errors ──────────────────────────────────────────────────
Expand Down
Loading
Loading