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
76 changes: 76 additions & 0 deletions packages/api/src/mcp/__tests__/mcpConnections.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
6 changes: 3 additions & 3 deletions packages/api/src/mcp/prompts/dashboards/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -48,7 +48,7 @@ const dashboardPrompts: PromptDefinition = (server, context) => {
try {
const [sources, connections] = await Promise.all([
getVisibleMcpSources(context),
getConnectionsByTeam(teamId),
getMcpConnections(context),
]);

sourceSummary = buildSourceSummary(
Expand Down Expand Up @@ -127,7 +127,7 @@ const dashboardPrompts: PromptDefinition = (server, context) => {
try {
const [sources, connections] = await Promise.all([
getMcpSources(context),
getConnectionsByTeam(teamId),
getMcpConnections(context),
]);

traceSourceId = getFirstSourceId(
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/mcp/tools/dashboards/variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -179,7 +179,7 @@ export async function getReferenceTargets(
): Promise<ReferenceTargets> {
const [sources, connections] = await Promise.all([
getMcpSources(context),
getConnectionsByTeam(context.teamId),
getMcpConnections(context),
]);
return {
sources: sources.map(source => ({
Expand Down
19 changes: 9 additions & 10 deletions packages/api/src/mcp/tools/sources/listSources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string, unknown>;
databaseName: string;
Expand All @@ -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,
Expand Down Expand Up @@ -227,7 +226,7 @@ export function registerListSources({
async () => {
const [visibleSources, connections] = await Promise.all([
getVisibleMcpSources(context),
getConnectionsByTeam(teamId.toString()),
getMcpConnections(context),
]);

const metricPreviewEntries: Array<{
Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/mcp/tools/sources/saveSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down
10 changes: 4 additions & 6 deletions packages/api/src/mcp/utils/clickhouse.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -22,11 +22,9 @@ export async function getMcpClickhouseClient(
connectionId: string,
options?: Pick<ClickhouseClientOptions, 'requestTimeout'>,
): Promise<ClickhouseClient> {
const connection = await getConnectionById(
context.teamId,
connectionId,
true,
);
const connection = await getMcpConnection(context, connectionId, {
selectPassword: true,
});
if (!connection) {
throw new McpConnectionNotFoundError(connectionId);
}
Expand Down
38 changes: 38 additions & 0 deletions packages/api/src/mcp/utils/connections.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import mongoose from 'mongoose';

import {
getConnectionById,
getConnectionsByTeam,
validateConnectionId,
} 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.

/** 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),
);
}
Loading