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

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

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

import type { McpContext } from '@/mcp/tools/types';
import {
getMcpSource,
getMcpSources,
getVisibleMcpSource,
getVisibleMcpSources,
} from '@/mcp/utils/sources';

const logSource = { _id: 'log-1', kind: SourceKind.Log };
const promqlSource = { _id: 'promql-1', kind: SourceKind.Promql };

const context = (promqlEnabled: boolean): McpContext => ({
teamId: 'team-1',
userId: 'user-1',
promqlEnabled,
});

describe('MCP source lookup', () => {
beforeEach(() => {
mockGetSource.mockReset();
mockGetSources.mockReset();
});

it('getMcpSource scopes the lookup to the caller team', async () => {
mockGetSource.mockResolvedValue(logSource);
await expect(getMcpSource(context(true), 'log-1')).resolves.toBe(logSource);
expect(mockGetSource).toHaveBeenCalledWith('team-1', 'log-1');
});

it('getMcpSource returns null when the source is not found', async () => {
mockGetSource.mockResolvedValue(null);
await expect(getMcpSource(context(true), 'missing')).resolves.toBeNull();
});

it('getMcpSource and getMcpSources do not hide PromQL sources', async () => {
mockGetSource.mockResolvedValue(promqlSource);
mockGetSources.mockResolvedValue([logSource, promqlSource]);
await expect(getMcpSource(context(false), 'promql-1')).resolves.toBe(
promqlSource,
);
await expect(getMcpSources(context(false))).resolves.toEqual([
logSource,
promqlSource,
]);
expect(mockGetSources).toHaveBeenCalledWith('team-1');
});

it('getVisibleMcpSources drops PromQL sources only while PromQL is off', async () => {
mockGetSources.mockResolvedValue([logSource, promqlSource]);
await expect(getVisibleMcpSources(context(false))).resolves.toEqual([
logSource,
]);
await expect(getVisibleMcpSources(context(true))).resolves.toEqual([
logSource,
promqlSource,
]);
});

it('getVisibleMcpSource returns null for a hidden or missing source', async () => {
mockGetSource.mockResolvedValue(promqlSource);
await expect(
getVisibleMcpSource(context(false), 'promql-1'),
).resolves.toBeNull();
await expect(getVisibleMcpSource(context(true), 'promql-1')).resolves.toBe(
promqlSource,
);

mockGetSource.mockResolvedValue(null);
await expect(
getVisibleMcpSource(context(true), 'missing'),
).resolves.toBeNull();
});
});
11 changes: 5 additions & 6 deletions packages/api/src/mcp/prompts/dashboards/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { z } from 'zod';

import { getConnectionsByTeam } from '@/controllers/connection';
import { getSources } from '@/controllers/sources';
import type { PromptDefinition } from '@/mcp/tools/types';
import { isHiddenSource, isPromqlEnabled } from '@/mcp/utils/promql';
import { isPromqlEnabled } from '@/mcp/utils/promql';
import { getMcpSources, getVisibleMcpSources } from '@/mcp/utils/sources';
import logger from '@/utils/logger';

import {
Expand Down Expand Up @@ -46,11 +46,10 @@ const dashboardPrompts: PromptDefinition = (server, context) => {
let logSourceId: string;

try {
const [allSources, connections] = await Promise.all([
getSources(teamId),
const [sources, connections] = await Promise.all([
getVisibleMcpSources(context),
getConnectionsByTeam(teamId),
]);
const sources = allSources.filter(s => !isHiddenSource(context, s));

sourceSummary = buildSourceSummary(
sources.map(s => ({
Expand Down Expand Up @@ -127,7 +126,7 @@ const dashboardPrompts: PromptDefinition = (server, context) => {

try {
const [sources, connections] = await Promise.all([
getSources(teamId),
getMcpSources(context),
getConnectionsByTeam(teamId),
]);

Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/mcp/tools/dashboards/queryTile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export function registerQueryTile({
externalDashboard.filters,
variableValues,
externalDashboard.savedFilterValues,
await getReferenceTargets(teamId.toString()),
await getReferenceTargets(context),
);
if ('error' in resolvedTile) {
return mcpUserError(resolvedTile.error);
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 @@ -235,7 +235,7 @@ export function registerQueryTiles({
.slice(MAX_TILES_PER_CALL)
.map(t => t.id);

const referenceTargets = await getReferenceTargets(teamId.toString());
const referenceTargets = await getReferenceTargets(context);

// Fix one shared deadline for the whole batch that every tile races.
const deadlineAt = Date.now() + BATCH_DEADLINE_MS;
Expand Down
9 changes: 5 additions & 4 deletions packages/api/src/mcp/tools/dashboards/variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables';
import { z } from 'zod';

import { getConnectionsByTeam } from '@/controllers/connection';
import { getSources } from '@/controllers/sources';
import type { McpContext } from '@/mcp/tools/types';
import { getMcpSources } from '@/mcp/utils/sources';
import {
convertToInternalTileConfig,
type ExternalDashboard,
Expand Down Expand Up @@ -174,11 +175,11 @@ export type ReferenceTargets = {
};

export async function getReferenceTargets(
teamId: string,
context: McpContext,
): Promise<ReferenceTargets> {
const [sources, connections] = await Promise.all([
getSources(teamId),
getConnectionsByTeam(teamId),
getMcpSources(context),
getConnectionsByTeam(context.teamId),
]);
return {
sources: sources.map(source => ({
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/mcp/tools/query/denoise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ import type { ChartConfigWithDateRange } from '@hyperdx/common-utils/dist/types'
import { DisplayType } from '@hyperdx/common-utils/dist/types';

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 { getMcpSource } from '@/mcp/utils/sources';
import { MCP_QUERY_MAX_EXECUTION_SEC } from '@/mcp/utils/timeout';

import { resolveBodyExpression } from './helpers';
Expand Down Expand Up @@ -65,7 +65,7 @@ export async function denoiseSearchResults(
}

// ── Resolve source & connection ──
const source = await getSource(context.teamId, sourceId);
const source = await getMcpSource(context, sourceId);
if (!source) {
return { rows, removedPatterns: [], skipped: 'source_not_found' };
}
Expand Down
6 changes: 2 additions & 4 deletions packages/api/src/mcp/tools/query/eventDeltas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ import {
import { z } from 'zod';

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 { getMcpSource } from '@/mcp/utils/sources';
import { MCP_QUERY_MAX_EXECUTION_SEC } from '@/mcp/utils/timeout';
import { trimToolResponse } from '@/utils/trimToolResponse';

Expand Down Expand Up @@ -161,8 +161,6 @@ function topDeltasForProperty(
// ─── Tool definition ─────────────────────────────────────────────────────────

export function registerEventDeltas({ context, registerTool }: ToolRegistrar) {
const { teamId } = context;

registerTool(
'clickstack_event_deltas',
{
Expand Down Expand Up @@ -242,7 +240,7 @@ export function registerEventDeltas({ context, registerTool }: ToolRegistrar) {
);
}

const source = await getSource(teamId.toString(), input.sourceId);
const source = await getMcpSource(context, input.sourceId);
if (!source) {
return mcpUserError(
`Source not found: ${input.sourceId}. Call clickstack_list_sources to find available source IDs.`,
Expand Down
10 changes: 5 additions & 5 deletions packages/api/src/mcp/tools/query/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ import ms from 'ms';

import type { ClickhouseClient } from '@/clickhouse';
import { PromQLQueryError } from '@/controllers/promql';
import { getSource } from '@/controllers/sources';
import type { McpContext } from '@/mcp/tools/types';
import {
getMcpClickhouseClient,
McpConnectionNotFoundError,
} from '@/mcp/utils/clickhouse';
import type { McpErrorResult } from '@/mcp/utils/errors';
import { mcpServerError, mcpUserError } from '@/mcp/utils/errors';
import { getMcpSource } from '@/mcp/utils/sources';
import {
MCP_QUERY_MAX_EXECUTION_SEC,
MCP_TIMEOUT_GRACE_MS,
Expand Down Expand Up @@ -475,7 +475,7 @@ export function assertSourceKindMatchesSelect(
// ─── Tile execution ──────────────────────────────────────────────────────────

/**
* `getSource` returns a hydrated Mongoose document, so `source.metricTables`
* `getMcpSource` returns a hydrated Mongoose document, so `source.metricTables`
* is a live subdocument rather than a plain object. Downstream render paths
* may clone the chart config — notably `convertToCategoricalChartConfig`
* (pie/bar) runs it through `structuredClone`, which cannot clone a Mongoose
Expand Down Expand Up @@ -510,7 +510,7 @@ export async function runConfigTile(
/** SQL LIMIT for builder tiles that aren't searches (MCP table tool). */
limit?: number;
/** Source lookup for raw SQL tiles, so a batch can share one per-call cache. */
lookupSource?: (sourceId: string) => ReturnType<typeof getSource>;
lookupSource?: (sourceId: string) => ReturnType<typeof getMcpSource>;
/**
* Search tiles only: scan newest-first under a time budget and return
* partial rows instead of a timeout (MCP search tool).
Expand Down Expand Up @@ -569,7 +569,7 @@ export async function runConfigTile(
);
}

const source = await getSource(teamId, builderConfig.source);
const source = await getMcpSource(context, builderConfig.source);
if (!source) {
return mcpUserError(
`Source not found: ${builderConfig.source}. Call clickstack_list_sources to discover available source IDs.`,
Expand Down Expand Up @@ -781,7 +781,7 @@ export async function runConfigTile(
if (savedConfig.source) {
const source = await (options?.lookupSource
? options.lookupSource(savedConfig.source)
: getSource(teamId, savedConfig.source));
: getMcpSource(context, savedConfig.source));
if (source) {
sourceFields = {
from: source.from,
Expand Down
13 changes: 8 additions & 5 deletions packages/api/src/mcp/tools/query/prepareSql.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,28 @@
import { hasMacro } from '@hyperdx/common-utils/dist/macros';
import { hasVariableMacro } from '@hyperdx/common-utils/dist/variables';

import { getSource } from '@/controllers/sources';
import type { McpContext } from '@/mcp/tools/types';
import type { McpErrorResult } from '@/mcp/utils/errors';
import { mcpUserError } from '@/mcp/utils/errors';
import { getMcpSource } from '@/mcp/utils/sources';
import type { ExternalDashboardTileWithId } from '@/utils/zod';

import { buildTile } from './helpers';

export type SourceLookup = (sourceId: string) => ReturnType<typeof getSource>;
export type SourceLookup = (
sourceId: string,
) => ReturnType<typeof getMcpSource>;

/**
* Source lookup memoized for one tool call, so a batch of queries against the
* same source reads it from Mongo once.
*/
export function createSourceLookup(teamId: string): SourceLookup {
const cache = new Map<string, ReturnType<typeof getSource>>();
export function createSourceLookup(context: McpContext): SourceLookup {
const cache = new Map<string, ReturnType<typeof getMcpSource>>();
return sourceId => {
let pending = cache.get(sourceId);
if (!pending) {
pending = getSource(teamId, sourceId);
pending = getMcpSource(context, sourceId);
cache.set(sourceId, pending);
}
return pending;
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/mcp/tools/query/runEventPatterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import { DisplayType, SourceKind } from '@hyperdx/common-utils/dist/types';
import { trace } from '@opentelemetry/api';

import type { ClickhouseClient } from '@/clickhouse';
import { getSource } from '@/controllers/sources';
import type { McpContext } from '@/mcp/tools/types';
import {
getMcpClickhouseClient,
Expand All @@ -31,6 +30,7 @@ import {
mcpServerError,
mcpUserError,
} from '@/mcp/utils/errors';
import { getMcpSource } from '@/mcp/utils/sources';
import { MCP_QUERY_MAX_EXECUTION_SEC } from '@/mcp/utils/timeout';
import { getCounter } from '@/utils/instrumentation';
import logger from '@/utils/logger';
Expand Down Expand Up @@ -104,7 +104,7 @@ export async function mineWindowPatterns(
const sampleSize = options?.sampleSize ?? 10_000;
const trendBuckets = options?.trendBuckets ?? 0;

const source = await getSource(teamId, sourceId);
const source = await getMcpSource(context, sourceId);
if (!source) {
return {
error: mcpUserError(
Expand Down
4 changes: 1 addition & 3 deletions packages/api/src/mcp/tools/query/serviceHealth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ export function registerServiceHealth({
context,
registerTool,
}: ToolRegistrar) {
const teamId = context.teamId.toString();

registerTool(
TOOL_NAME,
{
Expand All @@ -95,7 +93,7 @@ export function registerServiceHealth({
);
}

const source = await loadHealthSource(teamId, input.sourceId, TOOL_NAME);
const source = await loadHealthSource(context, input.sourceId, TOOL_NAME);
if ('isError' in source) return source;
let client: ClickhouseClient;
try {
Expand Down
13 changes: 7 additions & 6 deletions packages/api/src/mcp/tools/query/serviceHealth/source.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { SourceKind } from '@hyperdx/common-utils/dist/types';

import { getSource, getSources } from '@/controllers/sources';
import type { McpContext } from '@/mcp/tools/types';
import type { McpErrorResult } from '@/mcp/utils/errors';
import { mcpUserError } from '@/mcp/utils/errors';
import { getMcpSource, getMcpSources } from '@/mcp/utils/sources';

import type { HealthSource } from './queries';

Expand All @@ -13,11 +14,11 @@ const MAX_LISTED_SOURCES = 10;
* the exact ID when the input names one trace source, else list the options.
*/
async function sourceNotFound(
teamId: string,
context: McpContext,
sourceId: string,
toolName: string,
): Promise<McpErrorResult> {
const traces = (await getSources(teamId)).filter(
const traces = (await getMcpSources(context)).filter(
s => s.kind === SourceKind.Trace,
);
const needle = sourceId.trim().toLowerCase();
Expand Down Expand Up @@ -50,12 +51,12 @@ async function sourceNotFound(

/** Load a trace source and check it has the fields the tool needs. */
export async function loadHealthSource(
teamId: string,
context: McpContext,
sourceId: string,
toolName: string,
): Promise<HealthSource | McpErrorResult> {
const doc = await getSource(teamId, sourceId);
if (!doc) return sourceNotFound(teamId, sourceId, toolName);
const doc = await getMcpSource(context, sourceId);
if (!doc) return sourceNotFound(context, sourceId, toolName);
if (doc.kind !== SourceKind.Trace) {
return mcpUserError(
`Source ${sourceId} is kind="${doc.kind}". ${toolName} requires a source of kind="trace".`,
Expand Down
Loading
Loading