From c716d1393a2c27fbc9e3a1b06549f7da2be4f7c1 Mon Sep 17 00:00:00 2001 From: Brandon Pereira Date: Mon, 23 Nov 2026 13:49:06 -0600 Subject: [PATCH 1/2] refactor(api): look up MCP connections through one helper Add mcp/utils/connections.ts (getMcpConnections, getMcpConnection, validateMcpConnectionId) taking the full McpContext, and route every MCP tool and prompt connection lookup through it, including getMcpClickhouseClient. No behavior change. --- .../src/mcp/__tests__/mcpConnections.test.ts | 76 +++++++++++++++++++ .../api/src/mcp/prompts/dashboards/index.ts | 6 +- .../api/src/mcp/tools/dashboards/variables.ts | 4 +- .../api/src/mcp/tools/sources/listSources.ts | 19 +++-- .../api/src/mcp/tools/sources/saveSource.ts | 6 +- packages/api/src/mcp/utils/clickhouse.ts | 10 +-- packages/api/src/mcp/utils/connections.ts | 36 +++++++++ 7 files changed, 133 insertions(+), 24 deletions(-) create mode 100644 packages/api/src/mcp/__tests__/mcpConnections.test.ts create mode 100644 packages/api/src/mcp/utils/connections.ts diff --git a/packages/api/src/mcp/__tests__/mcpConnections.test.ts b/packages/api/src/mcp/__tests__/mcpConnections.test.ts new file mode 100644 index 000000000..c6c237b73 --- /dev/null +++ b/packages/api/src/mcp/__tests__/mcpConnections.test.ts @@ -0,0 +1,76 @@ +const mockGetConnectionById = jest.fn(); +const mockGetConnectionsByTeam = jest.fn(); +const mockValidateConnectionId = jest.fn(); + +jest.mock('@/controllers/connection', () => ({ + getConnectionById: (...args: unknown[]) => mockGetConnectionById(...args), + getConnectionsByTeam: (...args: unknown[]) => + mockGetConnectionsByTeam(...args), + validateConnectionId: (...args: unknown[]) => + mockValidateConnectionId(...args), +})); + +import mongoose from 'mongoose'; + +import type { McpContext } from '@/mcp/tools/types'; +import { + getMcpConnection, + getMcpConnections, + validateMcpConnectionId, +} from '@/mcp/utils/connections'; + +const teamId = new mongoose.Types.ObjectId().toString(); +const context: McpContext = { teamId, userId: 'user-1' }; +const connection = { _id: 'conn-1', name: 'Local' }; + +describe('MCP connection lookup', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('getMcpConnections scopes the lookup to the caller team', async () => { + mockGetConnectionsByTeam.mockResolvedValue([connection]); + await expect(getMcpConnections(context)).resolves.toEqual([connection]); + expect(mockGetConnectionsByTeam).toHaveBeenCalledWith(teamId); + }); + + it('getMcpConnection omits the password unless asked for it', async () => { + mockGetConnectionById.mockResolvedValue(connection); + + await expect(getMcpConnection(context, 'conn-1')).resolves.toBe(connection); + expect(mockGetConnectionById).toHaveBeenLastCalledWith( + teamId, + 'conn-1', + false, + ); + + await getMcpConnection(context, 'conn-1', { selectPassword: true }); + expect(mockGetConnectionById).toHaveBeenLastCalledWith( + teamId, + 'conn-1', + true, + ); + }); + + it('getMcpConnection returns null when the connection is not found', async () => { + mockGetConnectionById.mockResolvedValue(null); + await expect(getMcpConnection(context, 'missing')).resolves.toBeNull(); + }); + + it('validateMcpConnectionId checks against the caller team', async () => { + const failure = { + ok: false, + status: 400, + message: 'connection must be an existing connection id', + }; + mockValidateConnectionId.mockResolvedValue(failure); + + await expect(validateMcpConnectionId(context, 'conn-1')).resolves.toBe( + failure, + ); + const [connectionId, team] = mockValidateConnectionId.mock.calls[0]; + expect(connectionId).toBe('conn-1'); + expect(team).toBeInstanceOf(mongoose.Types.ObjectId); + expect(team.toString()).toBe(teamId); + }); +}); diff --git a/packages/api/src/mcp/prompts/dashboards/index.ts b/packages/api/src/mcp/prompts/dashboards/index.ts index 24480ff2b..215d98524 100644 --- a/packages/api/src/mcp/prompts/dashboards/index.ts +++ b/packages/api/src/mcp/prompts/dashboards/index.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; -import { getConnectionsByTeam } from '@/controllers/connection'; import type { PromptDefinition } from '@/mcp/tools/types'; +import { getMcpConnections } from '@/mcp/utils/connections'; import { isPromqlEnabled } from '@/mcp/utils/promql'; import { getMcpSources, getVisibleMcpSources } from '@/mcp/utils/sources'; import logger from '@/utils/logger'; @@ -48,7 +48,7 @@ const dashboardPrompts: PromptDefinition = (server, context) => { try { const [sources, connections] = await Promise.all([ getVisibleMcpSources(context), - getConnectionsByTeam(teamId), + getMcpConnections(context), ]); sourceSummary = buildSourceSummary( @@ -127,7 +127,7 @@ const dashboardPrompts: PromptDefinition = (server, context) => { try { const [sources, connections] = await Promise.all([ getMcpSources(context), - getConnectionsByTeam(teamId), + getMcpConnections(context), ]); traceSourceId = getFirstSourceId( diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index 8f9d446c5..2a7eabc72 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -21,8 +21,8 @@ import type { import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables'; import { z } from 'zod'; -import { getConnectionsByTeam } from '@/controllers/connection'; import type { McpContext } from '@/mcp/tools/types'; +import { getMcpConnections } from '@/mcp/utils/connections'; import { getMcpSources } from '@/mcp/utils/sources'; import { convertToInternalTileConfig, @@ -179,7 +179,7 @@ export async function getReferenceTargets( ): Promise { const [sources, connections] = await Promise.all([ getMcpSources(context), - getConnectionsByTeam(context.teamId), + getMcpConnections(context), ]); return { sources: sources.map(source => ({ diff --git a/packages/api/src/mcp/tools/sources/listSources.ts b/packages/api/src/mcp/tools/sources/listSources.ts index ed772f4f0..7cd53c6eb 100644 --- a/packages/api/src/mcp/tools/sources/listSources.ts +++ b/packages/api/src/mcp/tools/sources/listSources.ts @@ -12,12 +12,9 @@ import { import { SourceKind } from '@hyperdx/common-utils/dist/types'; import { z } from 'zod'; -import { - getConnectionById, - getConnectionsByTeam, -} from '@/controllers/connection'; import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; -import type { ToolRegistrar } from '@/mcp/tools/types'; +import type { McpContext, ToolRegistrar } from '@/mcp/tools/types'; +import { getMcpConnection, getMcpConnections } from '@/mcp/utils/connections'; import { PROMQL_SOURCE_USAGE } from '@/mcp/utils/promql'; import { getVisibleMcpSources } from '@/mcp/utils/sources'; import { runWithTimeout } from '@/mcp/utils/timeout'; @@ -75,10 +72,10 @@ class PreviewClickhouseClient extends ClickhouseClient { * carries metricTables + the discovery nextSteps). */ async function attachMetricNamePreviews({ - teamId, + context, entries, }: { - teamId: string; + context: McpContext; entries: Array<{ summary: Record; databaseName: string; @@ -100,7 +97,9 @@ async function attachMetricNamePreviews({ >(); await Promise.all( connectionIds.map(async connectionId => { - const connection = await getConnectionById(teamId, connectionId, true); + const connection = await getMcpConnection(context, connectionId, { + selectPassword: true, + }); if (!connection) return; const clickhouseClient = new PreviewClickhouseClient({ host: connection.host, @@ -227,7 +226,7 @@ export function registerListSources({ async () => { const [visibleSources, connections] = await Promise.all([ getVisibleMcpSources(context), - getConnectionsByTeam(teamId.toString()), + getMcpConnections(context), ]); const metricPreviewEntries: Array<{ @@ -331,7 +330,7 @@ export function registerListSources({ // Best-effort: never let preview sampling fail or stall the catalog. try { await attachMetricNamePreviews({ - teamId: teamId.toString(), + context, entries: metricPreviewEntries, }); } catch (e) { diff --git a/packages/api/src/mcp/tools/sources/saveSource.ts b/packages/api/src/mcp/tools/sources/saveSource.ts index d28c66a30..11ce20ac5 100644 --- a/packages/api/src/mcp/tools/sources/saveSource.ts +++ b/packages/api/src/mcp/tools/sources/saveSource.ts @@ -2,10 +2,10 @@ import { SourceSchemaNoId } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import * as config from '@/config'; -import { validateConnectionId } from '@/controllers/connection'; import { createSource, updateSource } from '@/controllers/sources'; import { UPSERT_TOOL } from '@/mcp/tools/annotations'; import type { McpContext, ToolRegistrar } from '@/mcp/tools/types'; +import { validateMcpConnectionId } from '@/mcp/utils/connections'; import { mcpServerError, mcpUserError, @@ -54,9 +54,9 @@ export function registerSaveSource({ // Reject a connection that isn't a valid ObjectId owned by this team // (createSource/updateSource don't check, so this avoids a 500 CastError // or a cross-team credential reference). - const connectionCheck = await validateConnectionId( + const connectionCheck = await validateMcpConnectionId( + context, input.connection, - new mongoose.Types.ObjectId(teamId), ); if (!connectionCheck.ok) { return mcpUserError(connectionCheck.message); diff --git a/packages/api/src/mcp/utils/clickhouse.ts b/packages/api/src/mcp/utils/clickhouse.ts index 997eaa583..2b549b6f9 100644 --- a/packages/api/src/mcp/utils/clickhouse.ts +++ b/packages/api/src/mcp/utils/clickhouse.ts @@ -1,8 +1,8 @@ import type { ClickhouseClientOptions } from '@hyperdx/common-utils/dist/clickhouse'; import { ClickhouseClient } from '@/clickhouse'; -import { getConnectionById } from '@/controllers/connection'; import type { McpContext } from '@/mcp/tools/types'; +import { getMcpConnection } from '@/mcp/utils/connections'; export class McpConnectionNotFoundError extends Error { constructor(readonly connectionId: string) { @@ -22,11 +22,9 @@ export async function getMcpClickhouseClient( connectionId: string, options?: Pick, ): Promise { - const connection = await getConnectionById( - context.teamId, - connectionId, - true, - ); + const connection = await getMcpConnection(context, connectionId, { + selectPassword: true, + }); if (!connection) { throw new McpConnectionNotFoundError(connectionId); } diff --git a/packages/api/src/mcp/utils/connections.ts b/packages/api/src/mcp/utils/connections.ts new file mode 100644 index 000000000..4ebf3230b --- /dev/null +++ b/packages/api/src/mcp/utils/connections.ts @@ -0,0 +1,36 @@ +import mongoose from 'mongoose'; + +import { + getConnectionById, + getConnectionsByTeam, + validateConnectionId, +} from '@/controllers/connection'; +import type { McpContext } from '@/mcp/tools/types'; + +// 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. + +/** All of the team's connections, without passwords. */ +export function getMcpConnections(context: McpContext) { + return getConnectionsByTeam(context.teamId); +} + +/** The team's connection with this ID, or null when it does not exist. */ +export function getMcpConnection( + context: McpContext, + connectionId: string, + { selectPassword = false }: { selectPassword?: boolean } = {}, +) { + return getConnectionById(context.teamId, connectionId, selectPassword); +} + +/** Checks that `connectionId` is a valid ID of one of the team's connections. */ +export function validateMcpConnectionId( + context: McpContext, + connectionId: unknown, +) { + return validateConnectionId( + connectionId, + new mongoose.Types.ObjectId(context.teamId), + ); +} From 7a63f3f29361760f9d944316c027a21ac07a2d34 Mon Sep 17 00:00:00 2001 From: Brandon Pereira Date: Mon, 23 Nov 2026 13:54:30 -0600 Subject: [PATCH 2/2] docs(api): note PromQL exception in MCP connection helpers --- packages/api/src/mcp/utils/connections.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/api/src/mcp/utils/connections.ts b/packages/api/src/mcp/utils/connections.ts index 4ebf3230b..35a53ffe5 100644 --- a/packages/api/src/mcp/utils/connections.ts +++ b/packages/api/src/mcp/utils/connections.ts @@ -7,8 +7,10 @@ import { } from '@/controllers/connection'; import type { McpContext } from '@/mcp/tools/types'; -// 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. +// 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. /** All of the team's connections, without passwords. */ export function getMcpConnections(context: McpContext) {