diff --git a/.changeset/mcp-filter-roundtrip.md b/.changeset/mcp-filter-roundtrip.md new file mode 100644 index 000000000..aeb3fe5bd --- /dev/null +++ b/.changeset/mcp-filter-roundtrip.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/api': patch +--- + +fix: MCP dashboard filters from `clickstack_get_dashboard` can be saved back with `clickstack_save_dashboard` unchanged. MCP output now leaves out the fields a filter type fixes to one value (the mode flags on every type but QUERY_EXPRESSION, and the selection limits on data source and connection variables), which the save schema rejects. diff --git a/.changeset/mcp-patch-tile-id.md b/.changeset/mcp-patch-tile-id.md new file mode 100644 index 000000000..264bf36cd --- /dev/null +++ b/.changeset/mcp-patch-tile-id.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/api': patch +--- + +fix: `clickstack_patch_dashboard` accepts a tile from `clickstack_get_dashboard` or `clickstack_get_dashboard_tile` passed back unchanged. Its `tile` now takes an optional `id`, which must match `tileId`. diff --git a/packages/api/src/mcp/__tests__/dashboards/getDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/getDashboard.int.test.ts index b01553b73..e72fd7044 100644 --- a/packages/api/src/mcp/__tests__/dashboards/getDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/getDashboard.int.test.ts @@ -1,5 +1,12 @@ -import { callTool, getFirstText } from '@/mcp/__tests__/mcpTestUtils'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; + +import { + callTool, + getFirstText, + getToolSchemaErrors, +} from '@/mcp/__tests__/mcpTestUtils'; import Dashboard from '@/models/dashboard'; +import { Source } from '@/models/source'; import { setupDashboardTests } from './setup'; @@ -86,6 +93,126 @@ describe('MCP Dashboard Tools - clickstack_get_dashboard', () => { }); }); + describe('filter round trip', () => { + beforeEach(() => ctx.reconnect({ promqlEnabled: true })); + + /** Creates a dashboard with one filter of each type and returns its get output. */ + const createWithEveryFilterType = async () => { + const traceSourceId = ctx.traceSource._id.toString(); + const promqlSource = await Source.create({ + kind: SourceKind.Promql, + team: ctx.team._id, + connection: ctx.connection._id, + name: 'Metrics', + from: { databaseName: 'default', tableName: 'promql_metrics' }, + timestampValueExpression: 'timestamp', + }); + const created = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Every filter type', + tiles: [], + // Explicit variable names, so saving the derived ones back changes nothing. + filters: [ + { + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + sourceId: traceSourceId, + whereLanguage: 'sql', + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'service', + }, + { + type: 'STATIC_LIST', + name: 'Environment', + options: ['prod', 'staging'], + variableName: 'env', + }, + { + type: 'SQL_QUERY', + name: 'Region', + connectionId: ctx.connection._id.toString(), + sqlTemplate: 'SELECT 1', + variableName: 'region', + }, + { + type: 'PROMETHEUS_LABEL', + name: 'Job', + sourceId: promqlSource._id.toString(), + label: 'job', + variableName: 'job', + }, + { + type: 'ADHOC', + name: 'Conditions', + sourceType: 'sql', + sources: [traceSourceId], + variableName: 'conditions', + }, + { type: 'CONNECTION', name: 'Connection', variableName: 'conn' }, + { + type: 'DATA_SOURCE', + name: 'Traces source', + allowedSourceKinds: [SourceKind.Trace], + variableName: 'traces', + }, + ], + }); + expect(created.isError).toBeFalsy(); + const { id } = JSON.parse(getFirstText(created)); + return JSON.parse( + getFirstText( + await callTool(ctx.client!, 'clickstack_get_dashboard', { id }), + ), + ); + }; + + it('returns filters that clickstack_save_dashboard accepts unchanged', async () => { + const fetched = await createWithEveryFilterType(); + const saveArgs = { + id: fetched.id, + name: fetched.name, + tiles: fetched.tiles, + filters: fetched.filters, + }; + + expect( + await getToolSchemaErrors( + ctx.client!, + 'clickstack_save_dashboard', + saveArgs, + ), + ).toEqual([]); + + const storedBefore = await Dashboard.findById(fetched.id).lean(); + const saved = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + saveArgs, + ); + expect(saved.isError).toBeFalsy(); + expect(JSON.parse(getFirstText(saved)).filters).toEqual(fetched.filters); + const storedAfter = await Dashboard.findById(fetched.id).lean(); + expect(storedAfter?.filters).toEqual(storedBefore?.filters); + }); + + it('omits fixed mode flags but keeps those a query expression filter sets', async () => { + const { filters } = await createWithEveryFilterType(); + const byType = new Map( + filters.map((f: { type: string }) => [f.type, f] as const), + ); + + expect(byType.get('QUERY_EXPRESSION')).toMatchObject({ + isBroadcastEnabled: false, + isVariableEnabled: true, + }); + expect(byType.get('STATIC_LIST')).not.toHaveProperty( + 'isBroadcastEnabled', + ); + expect(byType.get('STATIC_LIST')).not.toHaveProperty('isVariableEnabled'); + }); + }); + it('should return error for non-existent dashboard id', async () => { const fakeId = '000000000000000000000000'; const result = await callTool(ctx.client!, 'clickstack_get_dashboard', { diff --git a/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts index b1758c53e..6d88a396e 100644 --- a/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts @@ -1,7 +1,11 @@ import { MetricsDataType, SourceKind } from '@hyperdx/common-utils/dist/types'; import { DEFAULT_DATABASE, DEFAULT_METRICS_TABLE } from '@/fixtures'; -import { callTool, getFirstText } from '@/mcp/__tests__/mcpTestUtils'; +import { + callTool, + getFirstText, + getToolSchemaErrors, +} from '@/mcp/__tests__/mcpTestUtils'; import Dashboard from '@/models/dashboard'; import { Source } from '@/models/source'; import type { ExternalDashboardTileWithId } from '@/utils/zod'; @@ -655,6 +659,77 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => { ]); }); + describe('tile from clickstack_get_dashboard_tile', () => { + const createDashboardWithTile = async () => { + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Tile round trip', + tiles: [ + { + name: 'Original', + config: { + displayType: 'line', + sourceId: ctx.traceSource._id.toString(), + select: [{ aggFn: 'count' }], + }, + }, + ], + }); + const created = JSON.parse(getFirstText(result)); + return { dashboardId: created.id, tileId: created.tiles[0].id }; + }; + const getTile = async (dashboardId: string, tileId: string) => + JSON.parse( + getFirstText( + await callTool(ctx.client!, 'clickstack_get_dashboard_tile', { + dashboardId, + tileId, + }), + ), + ); + + it('accepts the tile passed back unchanged', async () => { + const { dashboardId, tileId } = await createDashboardWithTile(); + const fetched = await getTile(dashboardId, tileId); + const patchArgs = { + dashboardId, + tileId, + tile: { ...fetched, name: 'Renamed' }, + }; + + expect( + await getToolSchemaErrors( + ctx.client!, + 'clickstack_patch_dashboard', + patchArgs, + ), + ).toEqual([]); + const result = await callTool( + ctx.client!, + 'clickstack_patch_dashboard', + patchArgs, + ); + expect(result.isError).toBeFalsy(); + expect(await getTile(dashboardId, tileId)).toEqual({ + ...fetched, + name: 'Renamed', + }); + }); + + it('rejects a tile id that does not match tileId', async () => { + const { dashboardId, tileId } = await createDashboardWithTile(); + const fetched = await getTile(dashboardId, tileId); + + const result = await callTool(ctx.client!, 'clickstack_patch_dashboard', { + dashboardId, + tileId, + tile: { ...fetched, id: 'other-tile' }, + }); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain('does not match tileId'); + }); + }); + it('should preserve raw SQL number tile colorRules across a get/patch round trip', async () => { const connectionId = ctx.connection._id.toString(); const colorRules = [ diff --git a/packages/api/src/mcp/__tests__/dashboards/promqlTiles.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/promqlTiles.int.test.ts index 61250c8c0..9b5e8e0ab 100644 --- a/packages/api/src/mcp/__tests__/dashboards/promqlTiles.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/promqlTiles.int.test.ts @@ -1,4 +1,5 @@ import { DisplayType, SourceKind } from '@hyperdx/common-utils/dist/types'; +import { omit } from 'lodash'; import { callTool, getFirstText } from '@/mcp/__tests__/mcpTestUtils'; import Dashboard from '@/models/dashboard'; @@ -76,6 +77,14 @@ describe('MCP Dashboard Tools - PromQL tiles and label filters', () => { variableName: `${sourceType}_conditions`, }); + // MCP output leaves out the mode flags the filter type fixes. + const returnedAdhocFilter = (sourceType: 'sql' | 'promql') => + omit( + storedAdhocFilter(sourceType), + 'isBroadcastEnabled', + 'isVariableEnabled', + ); + const createStoredDashboard = () => new Dashboard({ name: 'PromQL dashboard', @@ -245,13 +254,7 @@ describe('MCP Dashboard Tools - PromQL tiles and label filters', () => { }); expect(created.isError).toBeFalsy(); const { id, filters } = parseOutput(created); - expect(filters).toEqual([ - expect.objectContaining({ - ...filter, - isBroadcastEnabled: false, - isVariableEnabled: true, - }), - ]); + expect(filters).toEqual([expect.objectContaining(filter)]); const saved = await callTool(ctx.client!, 'clickstack_save_dashboard', { id, @@ -282,7 +285,7 @@ describe('MCP Dashboard Tools - PromQL tiles and label filters', () => { const { id, filters, warnings } = parseOutput(created); expect(warnings ?? []).toEqual([]); expect(filters).toEqual([ - { ...storedAdhocFilter('promql'), id: expect.any(String) }, + { ...returnedAdhocFilter('promql'), id: expect.any(String) }, ]); const saved = await callTool(ctx.client!, 'clickstack_save_dashboard', { @@ -523,7 +526,7 @@ describe('MCP Dashboard Tools - PromQL tiles and label filters', () => { }); expect(result.isError).toBeFalsy(); - expect(parseOutput(result).filters).toEqual([storedAdhocFilter('sql')]); + expect(parseOutput(result).filters).toEqual([returnedAdhocFilter('sql')]); }); it('keeps hidden PromQL ad hoc filters when clickstack_save_dashboard updates the dashboard', async () => { diff --git a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts index b750454e5..5f8182a4d 100644 --- a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts @@ -2835,8 +2835,6 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { expect(created.filters[0]).toMatchObject({ type: 'STATIC_LIST', options: ['prod', 'staging', 'dev'], - isBroadcastEnabled: false, - isVariableEnabled: true, variableName: 'env', }); expect(created.filters[0].id).toBeDefined(); @@ -2850,8 +2848,6 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { expect(fetched.filters[0]).toMatchObject({ type: 'STATIC_LIST', options: ['prod', 'staging', 'dev'], - isBroadcastEnabled: false, - isVariableEnabled: true, variableName: 'env', }); @@ -2913,8 +2909,10 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { ); expect(result.isError).toBeFalsy(); - const created = JSON.parse(getFirstText(result)); - expect(created.filters[0]).toMatchObject({ + const stored = await Dashboard.findById( + JSON.parse(getFirstText(result)).id, + ).lean(); + expect(stored?.filters?.[0]).toMatchObject({ isBroadcastEnabled: false, isVariableEnabled: true, }); @@ -4062,12 +4060,7 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { await callTool(ctx.client!, 'clickstack_get_dashboard', { id }), ); expect(read.filters).toEqual([ - { - ...adhocFilter(), - id: expect.any(String), - isBroadcastEnabled: true, - isVariableEnabled: true, - }, + { ...adhocFilter(), id: expect.any(String) }, ]); expect(read.savedFilterValues).toEqual([adhocValue]); diff --git a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts index d50a56e33..7c45e7a54 100644 --- a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts @@ -6,6 +6,7 @@ import { type ReferenceTargets, resolveDashboardVariables, resolveTileVariableReferences, + toMcpOutputFilters, withResolvedFilterVariableNames, } from '@/mcp/tools/dashboards/variables'; import type { @@ -330,6 +331,51 @@ describe('withResolvedFilterVariableNames', () => { }); }); +describe('toMcpOutputFilters', () => { + it('keeps the mode flags on a query expression filter', () => { + expect(toMcpOutputFilters([variableFilter])).toEqual([variableFilter]); + }); + + it('drops the fixed mode flags after resolving the variable name', () => { + const unnamed = staticFilter({ + name: 'Deploy Env', + variableName: undefined, + }); + + expect(toMcpOutputFilters([unnamed])).toEqual([ + { + id: unnamed.id, + type: 'STATIC_LIST', + name: 'Deploy Env', + options: ['prod', 'staging', 'dev'], + variableName: 'Deploy_Env', + }, + ]); + }); + + it('drops the fixed selection limits of a reference variable', () => { + const connection: ExternalDashboardFilterWithId = { + id: 'conn', + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + expect(toMcpOutputFilters([connection])).toEqual([ + { + id: 'conn', + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + }, + ]); + }); +}); + describe('resolveTileVariableReferences', () => { const objectId = () => new mongoose.Types.ObjectId().toString(); const connectionId = objectId(); diff --git a/packages/api/src/mcp/__tests__/mcpTestUtils.ts b/packages/api/src/mcp/__tests__/mcpTestUtils.ts index f878c7c59..e10bc3ce6 100644 --- a/packages/api/src/mcp/__tests__/mcpTestUtils.ts +++ b/packages/api/src/mcp/__tests__/mcpTestUtils.ts @@ -4,6 +4,8 @@ import { type CallToolResult, CallToolResultSchema, } from '@modelcontextprotocol/sdk/types.js'; +import type { ErrorObject } from 'ajv'; +import Ajv2020 from 'ajv/dist/2020'; import { createServer } from '@/mcp/mcpServer'; import { McpContext } from '@/mcp/tools/types'; @@ -51,3 +53,23 @@ export function getFirstText(result: CallToolResult): string { } return item.text; } + +/** + * Errors a client raises when it checks `args` against the tool's advertised + * input schema before calling it. The server drops unknown nested keys + * without an error, so calling the tool can't catch these. + */ +export async function getToolSchemaErrors( + c: Client, + name: string, + args: Record, +): Promise { + const { tools } = await c.listTools(); + const tool = tools.find(t => t.name === name); + if (!tool) throw new Error(`Unknown tool: ${name}`); + // Ajv2020 can't resolve the draft-07 `$schema` the SDK stamps on. + const { $schema: _$schema, ...schema } = tool.inputSchema; + const validate = new Ajv2020({ strict: false }).compile(schema); + validate(args); + return validate.errors ?? []; +} diff --git a/packages/api/src/mcp/tools/dashboards/getDashboard.ts b/packages/api/src/mcp/tools/dashboards/getDashboard.ts index 1eee46833..6ff162035 100644 --- a/packages/api/src/mcp/tools/dashboards/getDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/getDashboard.ts @@ -10,7 +10,7 @@ import { isPromqlEnabled } from '@/mcp/utils/promql'; import Dashboard from '@/models/dashboard'; import { convertToExternalDashboard } from '@/routers/external-api/v2/utils/dashboards'; -import { withResolvedFilterVariableNames } from './variables'; +import { toMcpOutputFilters } from './variables'; export function registerGetDashboard({ context, @@ -71,9 +71,7 @@ export function registerGetDashboard({ text: JSON.stringify( { ...externalDashboard, - filters: withResolvedFilterVariableNames( - externalDashboard.filters ?? [], - ), + filters: toMcpOutputFilters(externalDashboard.filters ?? []), ...(frontendUrl ? { url: `${frontendUrl}/dashboards/${dashboard._id}` } : {}), diff --git a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts index c19c9d871..119ca9f72 100644 --- a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts @@ -77,6 +77,11 @@ export function registerPatchDashboard({ 'tileId and tile must both be provided or both omitted.', ); } + if (inputTile?.id !== undefined && inputTile.id !== tileId) { + return mcpUserError( + `tile.id "${inputTile.id}" does not match tileId "${tileId}". A patch cannot change a tile's ID.`, + ); + } const existingDashboard = await Dashboard.findOne({ _id: dashboardId, diff --git a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts index 796b721f1..05cfc0e2f 100644 --- a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts @@ -43,7 +43,7 @@ import { getSavedFilterValueWarnings, getTileVariableWarnings, } from './validation'; -import { withResolvedFilterVariableNames } from './variables'; +import { toMcpOutputFilters } from './variables'; export function registerSaveDashboard({ context, @@ -244,9 +244,7 @@ async function createDashboard({ text: JSON.stringify( { ...externalDashboard, - filters: withResolvedFilterVariableNames( - externalDashboard.filters ?? [], - ), + filters: toMcpOutputFilters(externalDashboard.filters ?? []), ...(frontendUrl ? { url: `${frontendUrl}/dashboards/${newDashboard._id}` } : {}), @@ -460,9 +458,7 @@ async function updateDashboard({ text: JSON.stringify( { ...externalDashboard, - filters: withResolvedFilterVariableNames( - externalDashboard.filters ?? [], - ), + filters: toMcpOutputFilters(externalDashboard.filters ?? []), ...(frontendUrl ? { url: `${frontendUrl}/dashboards/${updatedDashboard._id}` } : {}), diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index 11d58d369..577560025 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -1540,6 +1540,10 @@ const mcpPatchTileLayoutSchema = z.object({ .min(1) .optional() .describe('Height in grid rows. Omit to keep the existing height.'), + id: mcpTileLayoutSchema.shape.id.describe( + 'Optional. Must equal tileId when set. Accepted so a tile from ' + + 'clickstack_get_dashboard or clickstack_get_dashboard_tile can be passed back unchanged.', + ), containerId: z .string() .min(1) diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index a20432df5..e0c549d3e 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -13,12 +13,14 @@ import { isSourceOfferedByVariable, parseVariableReference, } from '@hyperdx/common-utils/dist/referenceVariables'; -import type { - ChartVariable, - SavedChartConfig, - SourceKind, +import { + type ChartVariable, + DashboardFilterSchema, + type SavedChartConfig, + type SourceKind, } from '@hyperdx/common-utils/dist/types'; import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables'; +import { omit } from 'lodash'; import { z } from 'zod/v3'; import type { McpContext } from '@/mcp/tools/types'; @@ -377,3 +379,30 @@ export function withResolvedFilterVariableNames( : filter, ); } + +/** + * Fields each filter type pins to one value, such as the mode flags of every + * type but QUERY_EXPRESSION. The MCP filter schemas don't accept them, and + * saving fills them in. REST responses keep them for existing clients. + */ +const FIXED_FILTER_FIELDS_BY_TYPE = new Map( + DashboardFilterSchema.options.map(({ shape }) => [ + shape.type.value, + Object.entries(shape) + .filter( + ([key, schema]) => key !== 'type' && schema instanceof z.ZodLiteral, + ) + .map(([key]) => key), + ]), +); + +/** + * Filters as MCP tools return them: valid input to clickstack_save_dashboard, + * with variable names resolved. + */ +export function toMcpOutputFilters(filters: ExternalDashboardFilterWithId[]) { + // Fixed fields go last: name resolution reads isVariableEnabled. + return withResolvedFilterVariableNames(filters).map(filter => + omit(filter, FIXED_FILTER_FIELDS_BY_TYPE.get(filter.type) ?? []), + ); +}