diff --git a/packages/api/src/mcp/__tests__/mcpSources.test.ts b/packages/api/src/mcp/__tests__/mcpSources.test.ts new file mode 100644 index 000000000..738a2cee9 --- /dev/null +++ b/packages/api/src/mcp/__tests__/mcpSources.test.ts @@ -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(); + }); +}); diff --git a/packages/api/src/mcp/prompts/dashboards/index.ts b/packages/api/src/mcp/prompts/dashboards/index.ts index 69b6f6047..24480ff2b 100644 --- a/packages/api/src/mcp/prompts/dashboards/index.ts +++ b/packages/api/src/mcp/prompts/dashboards/index.ts @@ -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 { @@ -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 => ({ @@ -127,7 +126,7 @@ const dashboardPrompts: PromptDefinition = (server, context) => { try { const [sources, connections] = await Promise.all([ - getSources(teamId), + getMcpSources(context), getConnectionsByTeam(teamId), ]); diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index 1589353f9..2a1ef8998 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -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); diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index 297932f98..ffc8dcb26 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -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; diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index 7f5e91cb9..8f9d446c5 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -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, @@ -174,11 +175,11 @@ export type ReferenceTargets = { }; export async function getReferenceTargets( - teamId: string, + context: McpContext, ): Promise { const [sources, connections] = await Promise.all([ - getSources(teamId), - getConnectionsByTeam(teamId), + getMcpSources(context), + getConnectionsByTeam(context.teamId), ]); return { sources: sources.map(source => ({ diff --git a/packages/api/src/mcp/tools/query/denoise.ts b/packages/api/src/mcp/tools/query/denoise.ts index 7c6aacf5b..6e9f82ace 100644 --- a/packages/api/src/mcp/tools/query/denoise.ts +++ b/packages/api/src/mcp/tools/query/denoise.ts @@ -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'; @@ -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' }; } diff --git a/packages/api/src/mcp/tools/query/eventDeltas.ts b/packages/api/src/mcp/tools/query/eventDeltas.ts index 94ac4d32e..fad5c860c 100644 --- a/packages/api/src/mcp/tools/query/eventDeltas.ts +++ b/packages/api/src/mcp/tools/query/eventDeltas.ts @@ -12,7 +12,6 @@ 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 { @@ -20,6 +19,7 @@ import { 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'; @@ -161,8 +161,6 @@ function topDeltasForProperty( // ─── Tool definition ───────────────────────────────────────────────────────── export function registerEventDeltas({ context, registerTool }: ToolRegistrar) { - const { teamId } = context; - registerTool( 'clickstack_event_deltas', { @@ -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.`, diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index 526c6e32e..4a43e0f6d 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -28,7 +28,6 @@ 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, @@ -36,6 +35,7 @@ import { } 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, @@ -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 @@ -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; + lookupSource?: (sourceId: string) => ReturnType; /** * Search tiles only: scan newest-first under a time budget and return * partial rows instead of a timeout (MCP search tool). @@ -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.`, @@ -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, diff --git a/packages/api/src/mcp/tools/query/prepareSql.ts b/packages/api/src/mcp/tools/query/prepareSql.ts index 1ead7c0db..56ca98928 100644 --- a/packages/api/src/mcp/tools/query/prepareSql.ts +++ b/packages/api/src/mcp/tools/query/prepareSql.ts @@ -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; +export type SourceLookup = ( + sourceId: string, +) => ReturnType; /** * 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>(); +export function createSourceLookup(context: McpContext): SourceLookup { + const cache = new Map>(); return sourceId => { let pending = cache.get(sourceId); if (!pending) { - pending = getSource(teamId, sourceId); + pending = getMcpSource(context, sourceId); cache.set(sourceId, pending); } return pending; diff --git a/packages/api/src/mcp/tools/query/runEventPatterns.ts b/packages/api/src/mcp/tools/query/runEventPatterns.ts index 7791ffd76..547ac2e12 100644 --- a/packages/api/src/mcp/tools/query/runEventPatterns.ts +++ b/packages/api/src/mcp/tools/query/runEventPatterns.ts @@ -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, @@ -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'; @@ -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( diff --git a/packages/api/src/mcp/tools/query/serviceHealth/index.ts b/packages/api/src/mcp/tools/query/serviceHealth/index.ts index 078aa79e6..8927a0145 100644 --- a/packages/api/src/mcp/tools/query/serviceHealth/index.ts +++ b/packages/api/src/mcp/tools/query/serviceHealth/index.ts @@ -68,8 +68,6 @@ export function registerServiceHealth({ context, registerTool, }: ToolRegistrar) { - const teamId = context.teamId.toString(); - registerTool( TOOL_NAME, { @@ -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 { diff --git a/packages/api/src/mcp/tools/query/serviceHealth/source.ts b/packages/api/src/mcp/tools/query/serviceHealth/source.ts index 4e7553693..16af1b218 100644 --- a/packages/api/src/mcp/tools/query/serviceHealth/source.ts +++ b/packages/api/src/mcp/tools/query/serviceHealth/source.ts @@ -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'; @@ -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 { - const traces = (await getSources(teamId)).filter( + const traces = (await getMcpSources(context)).filter( s => s.kind === SourceKind.Trace, ); const needle = sourceId.trim().toLowerCase(); @@ -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 { - 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".`, diff --git a/packages/api/src/mcp/tools/query/sql.ts b/packages/api/src/mcp/tools/query/sql.ts index ccf8d2c72..bd5477ffd 100644 --- a/packages/api/src/mcp/tools/query/sql.ts +++ b/packages/api/src/mcp/tools/query/sql.ts @@ -92,8 +92,6 @@ const SQL_OR_QUERIES_ERROR = // ─── Tool registration ─────────────────────────────────────────────────────── export function registerSql({ context, registerTool }: ToolRegistrar) { - const { teamId } = context; - registerTool( 'clickstack_sql', { @@ -158,7 +156,7 @@ export function registerSql({ context, registerTool }: ToolRegistrar) { connectionId: input.connectionId, sourceId: input.sourceId, }, - createSourceLookup(teamId.toString()), + createSourceLookup(context), ); if ('error' in prepared) { return prepared.error; diff --git a/packages/api/src/mcp/tools/query/sqlBatch.ts b/packages/api/src/mcp/tools/query/sqlBatch.ts index 8ec5578de..806e641df 100644 --- a/packages/api/src/mcp/tools/query/sqlBatch.ts +++ b/packages/api/src/mcp/tools/query/sqlBatch.ts @@ -185,7 +185,7 @@ export async function runSqlBatch({ SQL_SINGLE_RESPONSE_LIMIT, Math.floor(SQL_BATCH_RESPONSE_BUDGET / queries.length), ); - const lookupSource = createSourceLookup(context.teamId); + const lookupSource = createSourceLookup(context); const queue = new PQueue({ concurrency: SQL_BATCH_CONCURRENCY }); // Fixed before anything is queued so every query races the same budget. const deadlineAt = Date.now() + SQL_BATCH_DEADLINE_MS; diff --git a/packages/api/src/mcp/tools/savedSearches/saveSavedSearch.ts b/packages/api/src/mcp/tools/savedSearches/saveSavedSearch.ts index a507b007c..1f2665238 100644 --- a/packages/api/src/mcp/tools/savedSearches/saveSavedSearch.ts +++ b/packages/api/src/mcp/tools/savedSearches/saveSavedSearch.ts @@ -4,7 +4,6 @@ import { getSavedSearch, updateSavedSearch, } from '@/controllers/savedSearch'; -import { getSource } from '@/controllers/sources'; import { UPSERT_TOOL } from '@/mcp/tools/annotations'; import type { ToolRegistrar } from '@/mcp/tools/types'; import { @@ -12,6 +11,7 @@ import { mcpUserError, validateObjectId, } from '@/mcp/utils/errors'; +import { getMcpSource } from '@/mcp/utils/sources'; import { mcpSaveSavedSearchSchema } from './schemas'; @@ -50,7 +50,7 @@ export function registerSaveSavedSearch({ } // ── Validate sourceId (format validated by Zod schema, check existence) ── - const source = await getSource(teamId, input.sourceId); + const source = await getMcpSource(context, input.sourceId); if (!source) { return mcpUserError('Source not found'); } diff --git a/packages/api/src/mcp/tools/sources/deleteSource.ts b/packages/api/src/mcp/tools/sources/deleteSource.ts index c3c064301..6a900d7e8 100644 --- a/packages/api/src/mcp/tools/sources/deleteSource.ts +++ b/packages/api/src/mcp/tools/sources/deleteSource.ts @@ -1,10 +1,10 @@ import { z } from 'zod'; -import { deleteSource, getSource } from '@/controllers/sources'; +import { deleteSource } from '@/controllers/sources'; import { IDEMPOTENT_DESTRUCTIVE_TOOL } from '@/mcp/tools/annotations'; import type { ToolRegistrar } from '@/mcp/tools/types'; import { mcpUserError } from '@/mcp/utils/errors'; -import { isHiddenSource } from '@/mcp/utils/promql'; +import { getVisibleMcpSource } from '@/mcp/utils/sources'; import { objectIdSchema } from '@/utils/zod'; export function registerDeleteSource({ @@ -30,8 +30,7 @@ export function registerDeleteSource({ }), }, async ({ id: sourceId }) => { - const source = await getSource(teamId, sourceId); - if (source && isHiddenSource(context, source)) { + if (!(await getVisibleMcpSource(context, sourceId))) { return mcpUserError('Source not found'); } diff --git a/packages/api/src/mcp/tools/sources/describeMetric.ts b/packages/api/src/mcp/tools/sources/describeMetric.ts index cf4c83df6..dd6bfea85 100644 --- a/packages/api/src/mcp/tools/sources/describeMetric.ts +++ b/packages/api/src/mcp/tools/sources/describeMetric.ts @@ -11,7 +11,6 @@ import { SourceKind } from '@hyperdx/common-utils/dist/types'; import { z } from 'zod'; import type { ClickhouseClient } from '@/clickhouse'; -import { getSource } from '@/controllers/sources'; import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; import { clickHouseErrorResult, @@ -27,6 +26,7 @@ import { mcpUserError, sanitizeFetchError, } from '@/mcp/utils/errors'; +import { getMcpSource } from '@/mcp/utils/sources'; import { MCP_TOOL_TIMEOUT_MS, runWithTimeout } from '@/mcp/utils/timeout'; import logger from '@/utils/logger'; import { trimToolResponse } from '@/utils/trimToolResponse'; @@ -475,8 +475,7 @@ async function describeMetricImpl( input: z.infer, signal: AbortSignal, ) { - const { teamId } = context; - const source = await getSource(teamId, input.sourceId); + const source = await getMcpSource(context, input.sourceId); if (!source) { return mcpUserError( `Source "${input.sourceId}" not found. Call clickstack_list_sources to see available source IDs.`, diff --git a/packages/api/src/mcp/tools/sources/describeSource.ts b/packages/api/src/mcp/tools/sources/describeSource.ts index b12caa23f..0f7f3261d 100644 --- a/packages/api/src/mcp/tools/sources/describeSource.ts +++ b/packages/api/src/mcp/tools/sources/describeSource.ts @@ -13,7 +13,6 @@ import SqlString from 'sqlstring'; import { z } from 'zod'; import type { ClickhouseClient } from '@/clickhouse'; -import { getSource } from '@/controllers/sources'; import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; import type { McpContext, ToolRegistrar, ToolResult } from '@/mcp/tools/types'; import { @@ -21,7 +20,7 @@ import { McpConnectionNotFoundError, } from '@/mcp/utils/clickhouse'; import { mcpServerError, mcpUserError } from '@/mcp/utils/errors'; -import { isHiddenSource } from '@/mcp/utils/promql'; +import { getVisibleMcpSource } from '@/mcp/utils/sources'; import { MCP_QUERY_MAX_EXECUTION_SEC, MCP_TIMEOUT_GRACE_MS, @@ -101,8 +100,8 @@ async function describeSourceSchema( progress: DescribeProgress, ): Promise { const { teamId } = context; - const source = await getSource(teamId, sourceId); - if (!source || isHiddenSource(context, source)) { + const source = await getVisibleMcpSource(context, sourceId); + if (!source) { return mcpUserError( `Source "${sourceId}" not found. Call clickstack_list_sources to see available source IDs.`, ); diff --git a/packages/api/src/mcp/tools/sources/listMetrics.ts b/packages/api/src/mcp/tools/sources/listMetrics.ts index 0594c6673..dbcb0956c 100644 --- a/packages/api/src/mcp/tools/sources/listMetrics.ts +++ b/packages/api/src/mcp/tools/sources/listMetrics.ts @@ -4,7 +4,6 @@ import { trace } from '@opentelemetry/api'; import { z } from 'zod'; import type { ClickhouseClient } from '@/clickhouse'; -import { getSource } from '@/controllers/sources'; import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; import { parseTimeRange } from '@/mcp/tools/query/helpers'; import type { McpContext, ToolRegistrar } from '@/mcp/tools/types'; @@ -13,6 +12,7 @@ import { McpConnectionNotFoundError, } from '@/mcp/utils/clickhouse'; import { mcpServerError, mcpUserError } from '@/mcp/utils/errors'; +import { getMcpSource } from '@/mcp/utils/sources'; import { MCP_TOOL_TIMEOUT_MS, runWithTimeout } from '@/mcp/utils/timeout'; import logger from '@/utils/logger'; @@ -104,8 +104,7 @@ async function listMetricsImpl( deadlineAt: number, signal: AbortSignal, ) { - const { teamId } = context; - const source = await getSource(teamId, input.sourceId); + const source = await getMcpSource(context, input.sourceId); if (!source) { return mcpUserError( `Source "${input.sourceId}" not found. Call clickstack_list_sources to see available source IDs.`, diff --git a/packages/api/src/mcp/tools/sources/listSources.ts b/packages/api/src/mcp/tools/sources/listSources.ts index 9ec04b200..ed772f4f0 100644 --- a/packages/api/src/mcp/tools/sources/listSources.ts +++ b/packages/api/src/mcp/tools/sources/listSources.ts @@ -16,10 +16,10 @@ import { getConnectionById, getConnectionsByTeam, } from '@/controllers/connection'; -import { getSources } from '@/controllers/sources'; import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; import type { ToolRegistrar } from '@/mcp/tools/types'; -import { isHiddenSource, PROMQL_SOURCE_USAGE } from '@/mcp/utils/promql'; +import { PROMQL_SOURCE_USAGE } from '@/mcp/utils/promql'; +import { getVisibleMcpSources } from '@/mcp/utils/sources'; import { runWithTimeout } from '@/mcp/utils/timeout'; import logger from '@/utils/logger'; @@ -225,8 +225,8 @@ export function registerListSources({ inputSchema: z.object({}), }, async () => { - const [sources, connections] = await Promise.all([ - getSources(teamId.toString()), + const [visibleSources, connections] = await Promise.all([ + getVisibleMcpSources(context), getConnectionsByTeam(teamId.toString()), ]); @@ -244,7 +244,6 @@ export function registerListSources({ .map(c => c._id.toString()), ); - const visibleSources = sources.filter(s => !isHiddenSource(context, s)); const sourceSummaries = visibleSources.map(s => { const meta: Record = { id: s._id.toString(), diff --git a/packages/api/src/mcp/tools/sources/saveSource.ts b/packages/api/src/mcp/tools/sources/saveSource.ts index ed90ed4ef..d28c66a30 100644 --- a/packages/api/src/mcp/tools/sources/saveSource.ts +++ b/packages/api/src/mcp/tools/sources/saveSource.ts @@ -3,15 +3,16 @@ import mongoose from 'mongoose'; import * as config from '@/config'; import { validateConnectionId } from '@/controllers/connection'; -import { createSource, getSource, updateSource } from '@/controllers/sources'; +import { createSource, updateSource } from '@/controllers/sources'; import { UPSERT_TOOL } from '@/mcp/tools/annotations'; -import type { ToolRegistrar } from '@/mcp/tools/types'; +import type { McpContext, ToolRegistrar } from '@/mcp/tools/types'; import { mcpServerError, mcpUserError, validateObjectId, } from '@/mcp/utils/errors'; import { isPromqlEnabled } from '@/mcp/utils/promql'; +import { getMcpSource } from '@/mcp/utils/sources'; import { isDuplicateKeyError } from '@/utils/errors'; import { buildMcpSaveSourceSchema, buildSourceInput } from './schemas'; @@ -74,7 +75,7 @@ export function registerSaveSource({ const sourceData = parsed.data as Parameters[1]; const correlatedIdError = await validateCorrelatedSourceIds( - teamId, + context, parsed.data as Record, sourceId, ); @@ -125,7 +126,7 @@ const CORRELATED_SOURCE_ID_FIELDS = [ * user-facing error string, or null when all references are valid. */ async function validateCorrelatedSourceIds( - teamId: string, + context: McpContext, parsed: Record, selfId: string | undefined, ): Promise { @@ -133,7 +134,7 @@ async function validateCorrelatedSourceIds( const value = parsed[field]; if (typeof value !== 'string' || value.length === 0) continue; if (selfId != null && value === selfId) continue; - const referenced = await getSource(teamId, value); + const referenced = await getMcpSource(context, value); if (!referenced) { return `${field} must reference an existing source in this team`; } diff --git a/packages/api/src/mcp/tools/trace/breakdown.ts b/packages/api/src/mcp/tools/trace/breakdown.ts index f96c1fbad..7a71f7681 100644 --- a/packages/api/src/mcp/tools/trace/breakdown.ts +++ b/packages/api/src/mcp/tools/trace/breakdown.ts @@ -20,7 +20,6 @@ import { getMetadata } from '@hyperdx/common-utils/dist/core/metadata'; import { SourceKind } from '@hyperdx/common-utils/dist/types'; import type { ClickhouseClient } from '@/clickhouse'; -import { getSource } from '@/controllers/sources'; import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; import { clickHouseErrorResult, @@ -45,6 +44,7 @@ import { McpConnectionNotFoundError, } from '@/mcp/utils/clickhouse'; import { mcpUserError } from '@/mcp/utils/errors'; +import { getMcpSource } from '@/mcp/utils/sources'; // The child stage looks spans up by TraceId, which is not in the sort key, so // it reads every span in the window regardless of how few parents matched. @@ -64,8 +64,6 @@ export function registerTraceBreakdown({ context, registerTool, }: ToolRegistrar) { - const { teamId } = context; - registerTool( 'clickstack_trace_top_time_consuming_ops', { @@ -83,7 +81,7 @@ export function registerTraceBreakdown({ } const { startDate, endDate } = timeRange; - 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.`, diff --git a/packages/api/src/mcp/tools/trace/waterfall.ts b/packages/api/src/mcp/tools/trace/waterfall.ts index b2113116f..3fe5e789e 100644 --- a/packages/api/src/mcp/tools/trace/waterfall.ts +++ b/packages/api/src/mcp/tools/trace/waterfall.ts @@ -11,7 +11,6 @@ import { import { z } from 'zod'; import type { ClickhouseClient } from '@/clickhouse'; -import { getSource } from '@/controllers/sources'; import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; import { clickHouseErrorResult, @@ -31,6 +30,7 @@ import { McpConnectionNotFoundError, } from '@/mcp/utils/clickhouse'; import { mcpUserError } from '@/mcp/utils/errors'; +import { getMcpSource } from '@/mcp/utils/sources'; import logger from '@/utils/logger'; // ─── Schema ────────────────────────────────────────────────────────────────── @@ -347,7 +347,7 @@ export function registerTraceWaterfall({ } const { startDate, endDate } = timeRange; - 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.`, @@ -674,10 +674,7 @@ export function registerTraceWaterfall({ let logsTruncated = false; let logsNote: string | undefined; if (input.includeLogs && source.logSourceId) { - const logSource = await getSource( - teamId.toString(), - source.logSourceId, - ); + const logSource = await getMcpSource(context, source.logSourceId); if (!logSource) { logsNote = `logSourceId ${source.logSourceId} configured but source not found`; } else if (logSource.kind !== SourceKind.Log) { diff --git a/packages/api/src/mcp/utils/sources.ts b/packages/api/src/mcp/utils/sources.ts new file mode 100644 index 000000000..94834f1dc --- /dev/null +++ b/packages/api/src/mcp/utils/sources.ts @@ -0,0 +1,31 @@ +import { getSource, getSources } from '@/controllers/sources'; +import type { McpContext } from '@/mcp/tools/types'; +import { isHiddenSource } from '@/mcp/utils/promql'; + +// Every MCP tool and prompt resolves sources through these helpers, so +// rules about which sources an MCP caller can see live in one place. + +/** The team's source with this ID, or null when it does not exist. */ +export function getMcpSource(context: McpContext, sourceId: string) { + return getSource(context.teamId, sourceId); +} + +/** All of the team's sources, including ones hidden from the agent. */ +export function getMcpSources(context: McpContext) { + return getSources(context.teamId); +} + +/** The team's sources minus those `isHiddenSource` hides from the agent. */ +export async function getVisibleMcpSources(context: McpContext) { + const sources = await getMcpSources(context); + return sources.filter(s => !isHiddenSource(context, s)); +} + +/** Like `getMcpSource`, but null when the source is hidden from the agent. */ +export async function getVisibleMcpSource( + context: McpContext, + sourceId: string, +) { + const source = await getMcpSource(context, sourceId); + return source && !isHiddenSource(context, source) ? source : null; +}