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
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
const mockGetSource = jest.fn();
const mockGetConnectionById = jest.fn();

jest.mock('@/controllers/sources', () => ({
getSource: (...args: unknown[]) => mockGetSource(...args),
}));
jest.mock('@/controllers/connection', () => ({
getConnectionById: (...args: unknown[]) => mockGetConnectionById(...args),
}));

import { SourceKind } from '@hyperdx/common-utils/dist/types';

import {
getPromqlLabelCatalog,
resolvePromqlTarget,
} from '@/controllers/promql';

const promqlSource = {
kind: SourceKind.Promql,
connection: 'conn-1',
from: { databaseName: 'db', tableName: 'ts' },
};
const connection = { id: 'conn-1', host: 'http://ch:8123' };

describe('PromQL connection lookup', () => {
beforeEach(() => {
jest.clearAllMocks();
mockGetSource.mockResolvedValue(promqlSource);
});

it('resolvePromqlTarget defaults to the team-scoped lookup', async () => {
mockGetConnectionById.mockResolvedValue(connection);

const target = await resolvePromqlTarget('team-1', 'source-1', {
selectPassword: false,
});

expect(target).toMatchObject({ connection, databaseName: 'db' });
expect(mockGetConnectionById).toHaveBeenCalledWith(
'team-1',
'conn-1',
false,
);
});

it('resolvePromqlTarget uses the given lookup instead', async () => {
const getConnection = jest.fn().mockResolvedValue(connection);

const target = await resolvePromqlTarget('team-1', 'source-1', {
selectPassword: true,
getConnection,
});

expect(target).toMatchObject({ connection });
expect(getConnection).toHaveBeenCalledWith('conn-1', {
selectPassword: true,
});
expect(mockGetConnectionById).not.toHaveBeenCalled();
});

it('resolvePromqlTarget returns 404 when the lookup finds nothing', async () => {
await expect(
resolvePromqlTarget('team-1', 'source-1', {
selectPassword: true,
getConnection: async () => null,
}),
).resolves.toEqual({ status: 404, error: 'Connection not found' });
});

it('getPromqlLabelCatalog uses the given lookup, with the password', async () => {
const getConnection = jest.fn().mockResolvedValue(null);

await expect(
getPromqlLabelCatalog({
teamId: 'team-1',
source: promqlSource,
startMs: 0,
endMs: 1000,
limit: 10,
getConnection,
}),
).rejects.toThrow('Connection not found');
expect(getConnection).toHaveBeenCalledWith('conn-1', {
selectPassword: true,
});
expect(mockGetConnectionById).not.toHaveBeenCalled();
});
});
38 changes: 27 additions & 11 deletions packages/api/src/controllers/promql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,21 @@ async function fetchPrometheusData<T extends z.ZodTypeAny>(
return data.data;
}

type PromqlConnection = NonNullable<
Awaited<ReturnType<typeof getConnectionById>>
>;

/** Looks up a connection by ID. Defaults to the team-scoped controller lookup. */
export type PromqlConnectionLookup = (
connectionId: string,
options: { selectPassword: boolean },
) => PromiseLike<PromqlConnection | null>;

const teamConnectionLookup =
(teamId: string): PromqlConnectionLookup =>
(connectionId, { selectPassword }) =>
getConnectionById(teamId, connectionId, selectPassword);

export type PromqlLabelCatalog = {
backend: PromqlBackend;
labelNames: string[];
Expand All @@ -274,6 +289,7 @@ export async function getPromqlLabelCatalog({
endMs,
limit,
signal,
getConnection = teamConnectionLookup(teamId),
}: {
teamId: string;
source: {
Expand All @@ -285,12 +301,11 @@ export async function getPromqlLabelCatalog({
endMs: number;
limit: number;
signal?: AbortSignal;
getConnection?: PromqlConnectionLookup;
}): Promise<PromqlLabelCatalog> {
const connection = await getConnectionById(
teamId,
source.connection.toString(),
true,
);
const connection = await getConnection(source.connection.toString(), {
selectPassword: true,
});
if (!connection) {
throw new Error('Connection not found');
}
Expand Down Expand Up @@ -365,7 +380,7 @@ export async function getPromqlLabelCatalog({
}

type PromqlTarget = {
connection: NonNullable<Awaited<ReturnType<typeof getConnectionById>>>;
connection: PromqlConnection;
databaseName: string;
tableName: string;
/** The source's scrape interval floor, e.g. "1 minute". */
Expand All @@ -382,7 +397,10 @@ type PromqlTarget = {
export async function resolvePromqlTarget(
teamId: string,
sourceId: string | undefined,
{ selectPassword }: { selectPassword: boolean },
{
selectPassword,
getConnection = teamConnectionLookup(teamId),
}: { selectPassword: boolean; getConnection?: PromqlConnectionLookup },
): Promise<PromqlTarget | { status: 400 | 404; error: string }> {
if (!sourceId) {
return { status: 400, error: 'missing required parameter: sourceId' };
Expand All @@ -394,11 +412,9 @@ export async function resolvePromqlTarget(
return { status: 404, error: 'Source not found' };
}

const connection = await getConnectionById(
teamId,
source.connection.toString(),
const connection = await getConnection(source.connection.toString(), {
selectPassword,
);
});

if (!connection) {
return { status: 404, error: 'Connection not found' };
Expand Down
15 changes: 15 additions & 0 deletions packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,21 @@ describe('clickstack_describe_source deadline', () => {
.mockResolvedValue(promqlSource);
});

it('looks the connection up through the MCP connection helper', async () => {
jest.mocked(getPromqlLabelCatalog).mockResolvedValue({
backend: 'clickhouse',
labelNames: [],
metricNames: [],
});

await runWithClock(0);

const { getConnection } = jest.mocked(getPromqlLabelCatalog).mock
.calls[0][0];
await getConnection!('conn-1', { selectPassword: true });
expect(getConnectionById).toHaveBeenCalledWith('team-1', 'conn-1', true);
});

it('aborts the label lookup at the deadline', async () => {
jest
.mocked(getPromqlLabelCatalog)
Expand Down
51 changes: 51 additions & 0 deletions packages/api/src/mcp/__tests__/promqlTileConnection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const mockGetConnectionById = jest.fn();
const mockResolvePromqlTarget = jest.fn();

jest.mock('@/controllers/connection', () => ({
getConnectionById: (...args: unknown[]) => mockGetConnectionById(...args),
}));
jest.mock('@/controllers/promql', () => ({
...jest.requireActual('@/controllers/promql'),
resolvePromqlTarget: (...args: unknown[]) => mockResolvePromqlTarget(...args),
}));

import { DisplayType } from '@hyperdx/common-utils/dist/types';
import { fromPartial } from '@total-typescript/shoehorn';

import { PromQLQueryError } from '@/controllers/promql';
import { runPromqlTile } from '@/mcp/tools/query/promqlTile';
import type { McpContext } from '@/mcp/tools/types';

const context: McpContext = { teamId: 'team-1', userId: 'user-1' };

describe('runPromqlTile connection lookup', () => {
it('looks the connection up through the MCP connection helper', async () => {
mockResolvePromqlTarget.mockResolvedValue({
status: 404,
error: 'Source not found',
});

await expect(
runPromqlTile({
context,
config: fromPartial({
source: 'source-1',
promqlExpression: 'up',
displayType: DisplayType.Line,
}),
dateRange: [new Date(0), new Date(60_000)],
}),
).rejects.toBeInstanceOf(PromQLQueryError);

const [teamId, sourceId, { getConnection }] =
mockResolvePromqlTarget.mock.calls[0];
expect([teamId, sourceId]).toEqual(['team-1', 'source-1']);

await getConnection('conn-1', { selectPassword: true });
expect(mockGetConnectionById).toHaveBeenCalledWith(
'team-1',
'conn-1',
true,
);
});
});
3 changes: 1 addition & 2 deletions packages/api/src/mcp/tools/query/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,6 @@ export async function runConfigTile(
partialSearchResults?: boolean;
},
) {
const { teamId } = context;
if (!isConfigTile(tile)) {
return mcpUserError('Invalid tile: config field missing');
}
Expand Down Expand Up @@ -749,7 +748,7 @@ export async function runConfigTile(
try {
return formatQueryResult(
await runPromqlTile({
teamId,
context,
config: savedConfig,
dateRange: [startDate, endDate],
variables: options?.variables,
Expand Down
10 changes: 7 additions & 3 deletions packages/api/src/mcp/tools/query/promqlTile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import {
resolvePromqlTarget,
runPromqlQuery,
} from '@/controllers/promql';
import type { McpContext } from '@/mcp/tools/types';
import { getMcpConnection } from '@/mcp/utils/connections';

/** The tile fields that decide what a PromQL tile queries and how its result is shaped. */
type PromqlTileConfig = Pick<
Expand Down Expand Up @@ -110,20 +112,22 @@ export function toPromqlTileResult(
* the tile can't draw, and ClickHouse errors from the table-function backend.
*/
export async function runPromqlTile({
teamId,
context,
config,
dateRange,
variables,
signal,
}: {
teamId: string;
context: McpContext;
config: PromqlTileConfig & Pick<PromqlSavedChartConfig, 'source'>;
dateRange: [Date, Date];
variables?: ChartVariable[];
signal?: AbortSignal;
}) {
const target = await resolvePromqlTarget(teamId, config.source, {
const target = await resolvePromqlTarget(context.teamId, config.source, {
selectPassword: true,
getConnection: (connectionId, options) =>
getMcpConnection(context, connectionId, options),
});
if ('error' in target) {
throw new PromQLQueryError(
Expand Down
13 changes: 8 additions & 5 deletions packages/api/src/mcp/tools/sources/describePromqlSource.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { quoteIdentifierIfNeeded } from '@hyperdx/common-utils/dist/core/metadata';

import { getPromqlLabelCatalog } from '@/controllers/promql';
import type { ToolResult } from '@/mcp/tools/types';
import type { McpContext, ToolResult } from '@/mcp/tools/types';
import { getMcpConnection } from '@/mcp/utils/connections';
import { PROMQL_QUERY_USAGE, timeSeriesSqlUsage } from '@/mcp/utils/promql';
import logger from '@/utils/logger';

Expand All @@ -15,13 +16,13 @@ const MAX_METRIC_NAMES = 200;
* Prometheus-compatible endpoint.
*/
export async function describePromqlSource({
teamId,
context,
source,
meta,
signal,
progress,
}: {
teamId: string;
context: McpContext;
source: Parameters<typeof getPromqlLabelCatalog>[0]['source'];
meta: Record<string, unknown>;
signal: AbortSignal;
Expand All @@ -39,12 +40,14 @@ export async function describePromqlSource({
const endMs = Date.now();
try {
const catalog = await getPromqlLabelCatalog({
teamId,
teamId: context.teamId,
source,
startMs: endMs - LABEL_LOOKBACK_MS,
endMs,
limit: Math.max(MAX_LABEL_NAMES, MAX_METRIC_NAMES),
signal,
getConnection: (connectionId, options) =>
getMcpConnection(context, connectionId, options),
});
const truncated =
catalog.labelNames.length > MAX_LABEL_NAMES ||
Expand Down Expand Up @@ -72,7 +75,7 @@ export async function describePromqlSource({
);
} catch (e) {
logger.warn(
{ teamId, error: e },
{ teamId: context.teamId, error: e },
'Failed to list labels for a PromQL source',
);
progress.partial = true;
Expand Down
3 changes: 1 addition & 2 deletions packages/api/src/mcp/tools/sources/describeSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ async function describeSourceSchema(
signal: AbortSignal,
progress: DescribeProgress,
): Promise<ToolResult> {
const { teamId } = context;
const source = await getVisibleMcpSource(context, sourceId);
if (!source) {
return mcpUserError(
Expand All @@ -123,7 +122,7 @@ async function describeSourceSchema(
}

if (source.kind === SourceKind.Promql) {
return describePromqlSource({ teamId, source, meta, signal, progress });
return describePromqlSource({ context, source, meta, signal, progress });
}

if (
Expand Down
7 changes: 3 additions & 4 deletions packages/api/src/mcp/utils/connections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import {
} from '@/controllers/connection';
import type { McpContext } from '@/mcp/tools/types';

// MCP tools and prompts look up connections through these helpers, so rules
// about which connections an MCP caller can use live in one place. Exception:
// PromQL tools get their connection inside controllers/promql.ts
// (resolvePromqlTarget, getPromqlLabelCatalog), which the REST API shares.
// Every MCP tool and prompt looks up connections through these helpers, so
// rules about which connections an MCP caller can use live in one place.
// PromQL tools pass getMcpConnection into the shared controllers/promql.ts.

/** All of the team's connections, without passwords. */
export function getMcpConnections(context: McpContext) {
Expand Down
Loading