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
76 changes: 76 additions & 0 deletions packages/api/src/mcp/__tests__/clickhouseClient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const mockGetConnectionById = jest.fn();
const mockClickhouseClient = jest.fn();

jest.mock('@/controllers/connection', () => ({
getConnectionById: (...args: unknown[]) => mockGetConnectionById(...args),
}));
jest.mock('@/clickhouse', () => ({ ClickhouseClient: mockClickhouseClient }));

import type { McpContext } from '@/mcp/tools/types';
import {
getMcpClickhouseClient,
McpConnectionNotFoundError,
} from '@/mcp/utils/clickhouse';

const context: McpContext = { teamId: 'team-1', userId: 'user-1' };
const connection = {
host: 'http://ch:8123',
username: 'default',
password: 'secret',
};

describe('getMcpClickhouseClient', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('looks the connection up for the calling team, with its password', async () => {
mockGetConnectionById.mockResolvedValue(connection);

const client = await getMcpClickhouseClient(context, 'conn-1');

expect(mockGetConnectionById).toHaveBeenCalledWith(
'team-1',
'conn-1',
true,
);
expect(client).toBe(mockClickhouseClient.mock.instances[0]);
expect(mockClickhouseClient.mock.calls[0][0]).toStrictEqual({
host: 'http://ch:8123',
username: 'default',
password: 'secret',
});
});

it('passes requestTimeout through to the client', async () => {
mockGetConnectionById.mockResolvedValue(connection);

await getMcpClickhouseClient(context, 'conn-1', { requestTimeout: 5000 });

expect(mockClickhouseClient.mock.calls[0][0]).toStrictEqual({
host: 'http://ch:8123',
username: 'default',
password: 'secret',
requestTimeout: 5000,
});
});

it('throws McpConnectionNotFoundError when the team has no such connection', async () => {
mockGetConnectionById.mockResolvedValue(null);

const result = getMcpClickhouseClient(context, 'conn-1');

await expect(result).rejects.toBeInstanceOf(McpConnectionNotFoundError);
await expect(result).rejects.toMatchObject({ connectionId: 'conn-1' });
expect(mockClickhouseClient).not.toHaveBeenCalled();
});

it('propagates lookup failures unchanged', async () => {
const failure = new Error('db down');
mockGetConnectionById.mockRejectedValue(failure);

await expect(getMcpClickhouseClient(context, 'conn-1')).rejects.toBe(
failure,
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ describe('clickstack_query_tiles handler — dashboard variables', () => {
});

expect(mockRunConfigTile).toHaveBeenCalledWith(
'team-1',
expect.objectContaining({ teamId: 'team-1' }),
expect.objectContaining({ id: 't1' }),
expect.any(Date),
expect.any(Date),
Expand All @@ -239,7 +239,7 @@ describe('clickstack_query_tiles handler — dashboard variables', () => {
});

expect(mockRunConfigTile).toHaveBeenCalledWith(
'team-1',
expect.objectContaining({ teamId: 'team-1' }),
expect.anything(),
expect.any(Date),
expect.any(Date),
Expand Down
10 changes: 3 additions & 7 deletions packages/api/src/mcp/tools/dashboards/queryTile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,9 @@ export function registerQueryTile({
}
const { tile } = resolvedTile;

const result = await runConfigTile(
teamId.toString(),
tile,
startDate,
endDate,
{ variables: resolvedVariables.variables },
);
const result = await runConfigTile(context, tile, startDate, endDate, {
variables: resolvedVariables.variables,
});

// Surface non-blocking missing macro and variable warnings alongside
// the successful result so the agent can spot a tile that runs but
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/mcp/tools/dashboards/queryTiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ export function registerQueryTiles({
const result = await withDeadline(
signal =>
runConfigTile(
teamId.toString(),
context,
resolvedTile.tile,
startDate,
endDate,
Expand Down
32 changes: 16 additions & 16 deletions packages/api/src/mcp/tools/query/denoise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ import {
import type { ChartConfigWithDateRange } from '@hyperdx/common-utils/dist/types';
import { DisplayType } from '@hyperdx/common-utils/dist/types';

import { ClickhouseClient } from '@/clickhouse';
import { getConnectionById } from '@/controllers/connection';
import type { ClickhouseClient } from '@/clickhouse';
import { getSource } from '@/controllers/sources';
import type { McpContext } from '@/mcp/tools/types';
import {
getMcpClickhouseClient,
McpConnectionNotFoundError,
} from '@/mcp/utils/clickhouse';
import { MCP_QUERY_MAX_EXECUTION_SEC } from '@/mcp/utils/timeout';

import { resolveBodyExpression } from './helpers';
Expand Down Expand Up @@ -46,7 +50,7 @@ export interface DenoiseResult {
* the shared TypeScript Drain implementation.
*/
export async function denoiseSearchResults(
teamId: string,
context: McpContext,
sourceId: string,
startDate: Date,
endDate: Date,
Expand All @@ -61,7 +65,7 @@ export async function denoiseSearchResults(
}

// ── Resolve source & connection ──
const source = await getSource(teamId, sourceId);
const source = await getSource(context.teamId, sourceId);
if (!source) {
return { rows, removedPatterns: [], skipped: 'source_not_found' };
}
Expand All @@ -71,20 +75,16 @@ export async function denoiseSearchResults(
return { rows, removedPatterns: [], skipped: 'no_body_column' };
}

const connection = await getConnectionById(
teamId,
source.connection.toString(),
true,
);
if (!connection) {
let clickhouseClient: ClickhouseClient;
try {
clickhouseClient = await getMcpClickhouseClient(
context,
source.connection.toString(),
);
} catch (e) {
if (!(e instanceof McpConnectionNotFoundError)) throw e;
return { rows, removedPatterns: [], skipped: 'connection_not_found' };
}

const clickhouseClient = new ClickhouseClient({
host: connection.host,
username: connection.username,
password: connection.password,
});
const metadata = getMetadata(clickhouseClient);

const tsExpr = getFirstTimestampValueExpression(
Expand Down
6 changes: 2 additions & 4 deletions packages/api/src/mcp/tools/query/emergingSignals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,6 @@ export function registerEmergingSignals({
context,
registerTool,
}: ToolRegistrar) {
const { teamId } = context;

registerTool(
'clickstack_emerging_signals',
{
Expand Down Expand Up @@ -210,14 +208,14 @@ export function registerEmergingSignals({

const [curRes, baseRes] = await Promise.all([
mineWindowPatterns(
teamId.toString(),
context,
input.sourceId,
cur.startDate,
cur.endDate,
opts,
),
mineWindowPatterns(
teamId.toString(),
context,
input.sourceId,
base.startDate,
base.endDate,
Expand Down
27 changes: 13 additions & 14 deletions packages/api/src/mcp/tools/query/eventDeltas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@ import {
} from '@hyperdx/common-utils/dist/types';
import { z } from 'zod';

import { ClickhouseClient } from '@/clickhouse';
import { getConnectionById } from '@/controllers/connection';
import type { ClickhouseClient } from '@/clickhouse';
import { getSource } from '@/controllers/sources';
import { READ_ONLY_TOOL } from '@/mcp/tools/annotations';
import type { ToolRegistrar } from '@/mcp/tools/types';
import {
getMcpClickhouseClient,
McpConnectionNotFoundError,
} from '@/mcp/utils/clickhouse';
import { mcpUserError } from '@/mcp/utils/errors';
import { MCP_QUERY_MAX_EXECUTION_SEC } from '@/mcp/utils/timeout';
import { trimToolResponse } from '@/utils/trimToolResponse';
Expand Down Expand Up @@ -251,22 +254,18 @@ export function registerEventDeltas({ context, registerTool }: ToolRegistrar) {
);
}

const connection = await getConnectionById(
teamId.toString(),
source.connection.toString(),
true,
);
if (!connection) {
let clickhouseClient: ClickhouseClient;
try {
clickhouseClient = await getMcpClickhouseClient(
context,
source.connection.toString(),
);
} catch (e) {
if (!(e instanceof McpConnectionNotFoundError)) throw e;
return mcpUserError(
`Connection not found for source: ${input.sourceId}`,
);
}

const clickhouseClient = new ClickhouseClient({
host: connection.host,
username: connection.username,
password: connection.password,
});
const metadata = getMetadata(clickhouseClient);

// Build a stable per-source ORDER BY for sampling (matches what the
Expand Down
24 changes: 8 additions & 16 deletions packages/api/src/mcp/tools/query/eventPatterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@ export function registerEventPatterns({
context,
registerTool,
}: ToolRegistrar) {
const { teamId } = context;

registerTool(
'clickstack_event_patterns',
{
Expand Down Expand Up @@ -115,20 +113,14 @@ export function registerEventPatterns({
}
const { startDate, endDate } = timeRange;

return runEventPatterns(
teamId.toString(),
input.sourceId,
startDate,
endDate,
{
where: input.where,
whereLanguage: input.whereLanguage,
bodyExpression: input.bodyExpression,
sampleSize: input.sampleSize,
topN: input.topN,
trendBuckets: input.trendBuckets,
},
);
return runEventPatterns(context, input.sourceId, startDate, endDate, {
where: input.where,
whereLanguage: input.whereLanguage,
bodyExpression: input.bodyExpression,
sampleSize: input.sampleSize,
topN: input.topN,
trendBuckets: input.trendBuckets,
});
},
);
}
Loading
Loading