From aee19c970aa10d6f65de0627a693b09df2421015 Mon Sep 17 00:00:00 2001 From: Brandon Pereira Date: Mon, 23 Nov 2026 14:07:31 -0600 Subject: [PATCH 1/2] refactor(api): route MCP PromQL connection lookups through the MCP helper resolvePromqlTarget and getPromqlLabelCatalog take an optional getConnection lookup that defaults to the team-scoped controller lookup, so the REST /prometheus router is unchanged. The MCP PromQL tile and describe_source paths pass getMcpConnection, so every MCP connection lookup now goes through mcp/utils/connections.ts. --- .../__tests__/promqlConnectionLookup.test.ts | 88 +++++++++++++++++++ packages/api/src/controllers/promql.ts | 38 +++++--- .../__tests__/describeSourceTimeout.test.ts | 15 ++++ packages/api/src/mcp/tools/query/helpers.ts | 3 +- .../api/src/mcp/tools/query/promqlTile.ts | 10 ++- .../mcp/tools/sources/describePromqlSource.ts | 13 +-- .../src/mcp/tools/sources/describeSource.ts | 3 +- packages/api/src/mcp/utils/connections.ts | 7 +- 8 files changed, 150 insertions(+), 27 deletions(-) create mode 100644 packages/api/src/controllers/__tests__/promqlConnectionLookup.test.ts diff --git a/packages/api/src/controllers/__tests__/promqlConnectionLookup.test.ts b/packages/api/src/controllers/__tests__/promqlConnectionLookup.test.ts new file mode 100644 index 0000000000..ad38063c36 --- /dev/null +++ b/packages/api/src/controllers/__tests__/promqlConnectionLookup.test.ts @@ -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(); + }); +}); diff --git a/packages/api/src/controllers/promql.ts b/packages/api/src/controllers/promql.ts index 59ed8a33e7..cdc433c5ef 100644 --- a/packages/api/src/controllers/promql.ts +++ b/packages/api/src/controllers/promql.ts @@ -254,6 +254,21 @@ async function fetchPrometheusData( return data.data; } +type PromqlConnection = NonNullable< + Awaited> +>; + +/** Looks up a connection by ID. Defaults to the team-scoped controller lookup. */ +export type PromqlConnectionLookup = ( + connectionId: string, + options: { selectPassword: boolean }, +) => PromiseLike; + +const teamConnectionLookup = + (teamId: string): PromqlConnectionLookup => + (connectionId, { selectPassword }) => + getConnectionById(teamId, connectionId, selectPassword); + export type PromqlLabelCatalog = { backend: PromqlBackend; labelNames: string[]; @@ -274,6 +289,7 @@ export async function getPromqlLabelCatalog({ endMs, limit, signal, + getConnection = teamConnectionLookup(teamId), }: { teamId: string; source: { @@ -285,12 +301,11 @@ export async function getPromqlLabelCatalog({ endMs: number; limit: number; signal?: AbortSignal; + getConnection?: PromqlConnectionLookup; }): Promise { - 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'); } @@ -365,7 +380,7 @@ export async function getPromqlLabelCatalog({ } type PromqlTarget = { - connection: NonNullable>>; + connection: PromqlConnection; databaseName: string; tableName: string; /** The source's scrape interval floor, e.g. "1 minute". */ @@ -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 { if (!sourceId) { return { status: 400, error: 'missing required parameter: sourceId' }; @@ -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' }; diff --git a/packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts b/packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts index 8e33f47f69..a2f8da5c28 100644 --- a/packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts +++ b/packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts @@ -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) diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index 4a43e0f6d6..0f1467df9f 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -518,7 +518,6 @@ export async function runConfigTile( partialSearchResults?: boolean; }, ) { - const { teamId } = context; if (!isConfigTile(tile)) { return mcpUserError('Invalid tile: config field missing'); } @@ -749,7 +748,7 @@ export async function runConfigTile( try { return formatQueryResult( await runPromqlTile({ - teamId, + context, config: savedConfig, dateRange: [startDate, endDate], variables: options?.variables, diff --git a/packages/api/src/mcp/tools/query/promqlTile.ts b/packages/api/src/mcp/tools/query/promqlTile.ts index e332c068e2..6edaa35f60 100644 --- a/packages/api/src/mcp/tools/query/promqlTile.ts +++ b/packages/api/src/mcp/tools/query/promqlTile.ts @@ -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< @@ -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; 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( diff --git a/packages/api/src/mcp/tools/sources/describePromqlSource.ts b/packages/api/src/mcp/tools/sources/describePromqlSource.ts index 44c8fdd2fc..213121371e 100644 --- a/packages/api/src/mcp/tools/sources/describePromqlSource.ts +++ b/packages/api/src/mcp/tools/sources/describePromqlSource.ts @@ -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'; @@ -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[0]['source']; meta: Record; signal: AbortSignal; @@ -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 || @@ -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; diff --git a/packages/api/src/mcp/tools/sources/describeSource.ts b/packages/api/src/mcp/tools/sources/describeSource.ts index 0f7f3261d3..a3ac5c61cc 100644 --- a/packages/api/src/mcp/tools/sources/describeSource.ts +++ b/packages/api/src/mcp/tools/sources/describeSource.ts @@ -99,7 +99,6 @@ async function describeSourceSchema( signal: AbortSignal, progress: DescribeProgress, ): Promise { - const { teamId } = context; const source = await getVisibleMcpSource(context, sourceId); if (!source) { return mcpUserError( @@ -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 ( diff --git a/packages/api/src/mcp/utils/connections.ts b/packages/api/src/mcp/utils/connections.ts index 35a53ffe51..a73af7db44 100644 --- a/packages/api/src/mcp/utils/connections.ts +++ b/packages/api/src/mcp/utils/connections.ts @@ -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) { From 12d0cf07fbd0988f06e01453a3a993cb0f62f714 Mon Sep 17 00:00:00 2001 From: Brandon Pereira Date: Mon, 23 Nov 2026 15:11:09 -0600 Subject: [PATCH 2/2] test(api): check PromQL tiles look up connections through the MCP helper --- .../__tests__/promqlTileConnection.test.ts | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 packages/api/src/mcp/__tests__/promqlTileConnection.test.ts diff --git a/packages/api/src/mcp/__tests__/promqlTileConnection.test.ts b/packages/api/src/mcp/__tests__/promqlTileConnection.test.ts new file mode 100644 index 0000000000..1b0f709fbe --- /dev/null +++ b/packages/api/src/mcp/__tests__/promqlTileConnection.test.ts @@ -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, + ); + }); +});