diff --git a/.changeset/mcp-saved-filter-values.md b/.changeset/mcp-saved-filter-values.md new file mode 100644 index 0000000000..cb452dd467 --- /dev/null +++ b/.changeset/mcp-saved-filter-values.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/api': minor +--- + +feat(mcp): support setting a dashboard's `savedFilterValues` via the MCP dashboard tools 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 73141b1f28..4940948fd0 100644 --- a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts @@ -3684,4 +3684,347 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { expect(getFirstText(result)).toContain('only valid for gauge metrics'); }); }); + + describe('savedFilterValues', () => { + const tile = (sourceId: string) => ({ + name: 'Volume', + config: { + displayType: 'line' as const, + sourceId, + select: [{ aggFn: 'count' as const, where: '' }], + }, + }); + + it('persists savedFilterValues on create and echoes them back', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Defaults on create', + tiles: [tile(sourceId)], + filters: [ + { + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + sourceId, + whereLanguage: 'sql', + isVariableEnabled: true, + variableName: 'service', + }, + ], + savedFilterValues: [ + { type: 'sql', condition: "ServiceName IN ('api')" }, + { type: 'variable', name: 'service', values: ['api', 'web'] }, + ], + }); + + expect(result.isError).toBeFalsy(); + const created = JSON.parse(getFirstText(result)); + expect(created.savedFilterValues).toEqual([ + { type: 'sql', condition: "ServiceName IN ('api')" }, + { type: 'variable', name: 'service', values: ['api', 'web'] }, + ]); + + const stored = await Dashboard.findById(created.id); + expect(stored?.savedFilterValues).toEqual([ + { type: 'sql', condition: "ServiceName IN ('api')" }, + { type: 'variable', name: 'service', values: ['api', 'web'] }, + ]); + }); + + it('defaults an omitted type to sql on a condition entry', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Implicit sql type', + tiles: [tile(sourceId)], + savedFilterValues: [{ condition: "ServiceName IN ('api')" }], + }); + + expect(result.isError).toBeFalsy(); + const created = JSON.parse(getFirstText(result)); + expect(created.savedFilterValues).toEqual([ + { type: 'sql', condition: "ServiceName IN ('api')" }, + ]); + }); + + it('returns savedFilterValues from clickstack_get_dashboard', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Defaults readable on get', + tiles: [tile(sourceId)], + savedFilterValues: [{ type: 'sql', condition: 'StatusCode = 200' }], + }, + ); + const created = JSON.parse(getFirstText(createResult)); + + const getResult = await callTool( + ctx.client!, + 'clickstack_get_dashboard', + { id: created.id }, + ); + const fetched = JSON.parse(getFirstText(getResult)); + expect(fetched.savedFilterValues).toEqual([ + { type: 'sql', condition: 'StatusCode = 200' }, + ]); + }); + + it('leaves saved defaults untouched when the update omits the field', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Keep defaults on update', + tiles: [tile(sourceId)], + savedFilterValues: [{ type: 'sql', condition: 'StatusCode = 200' }], + }, + ); + const created = JSON.parse(getFirstText(createResult)); + + const updateResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + id: created.id, + name: 'Keep defaults on update (renamed)', + tiles: [tile(sourceId)], + }, + ); + expect(updateResult.isError).toBeFalsy(); + const updated = JSON.parse(getFirstText(updateResult)); + expect(updated.savedFilterValues).toEqual([ + { type: 'sql', condition: 'StatusCode = 200' }, + ]); + }); + + it('clears saved defaults when the update passes an empty array', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Clear defaults on update', + tiles: [tile(sourceId)], + savedFilterValues: [{ type: 'sql', condition: 'StatusCode = 200' }], + }, + ); + const created = JSON.parse(getFirstText(createResult)); + + const updateResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + id: created.id, + name: 'Clear defaults on update', + tiles: [tile(sourceId)], + savedFilterValues: [], + }, + ); + expect(updateResult.isError).toBeFalsy(); + const updated = JSON.parse(getFirstText(updateResult)); + expect(updated.savedFilterValues).toEqual([]); + + const stored = await Dashboard.findById(created.id); + expect(stored?.savedFilterValues).toEqual([]); + }); + + it('sets savedFilterValues via clickstack_patch_dashboard', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Patch defaults', + tiles: [tile(sourceId)], + }, + ); + const created = JSON.parse(getFirstText(createResult)); + + const patchResult = await callTool( + ctx.client!, + 'clickstack_patch_dashboard', + { + dashboardId: created.id, + savedFilterValues: [ + { type: 'sql', condition: "ServiceName IN ('api')" }, + ], + }, + ); + expect(patchResult.isError).toBeFalsy(); + const patched = JSON.parse(getFirstText(patchResult)); + expect(patched.savedFilterValues).toEqual([ + { type: 'sql', condition: "ServiceName IN ('api')" }, + ]); + + const stored = await Dashboard.findById(created.id); + expect(stored?.savedFilterValues).toEqual([ + { type: 'sql', condition: "ServiceName IN ('api')" }, + ]); + + // Tiles are preserved by the targeted patch. + expect(stored?.tiles).toHaveLength(1); + }); + + it('patches a tile and savedFilterValues in the same call', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { name: 'Combined patch', tiles: [tile(sourceId)] }, + ); + const created = JSON.parse(getFirstText(createResult)); + const tileId = created.tiles[0].id; + + const patchResult = await callTool( + ctx.client!, + 'clickstack_patch_dashboard', + { + dashboardId: created.id, + savedFilterValues: [ + { type: 'sql', condition: "ServiceName IN ('api')" }, + ], + tileId, + tile: { + config: { + displayType: 'table', + sourceId, + select: [{ aggFn: 'count', where: '' }], + }, + }, + }, + ); + expect(patchResult.isError).toBeFalsy(); + const patched = JSON.parse(getFirstText(patchResult)); + expect(patched.savedFilterValues).toEqual([ + { type: 'sql', condition: "ServiceName IN ('api')" }, + ]); + expect(patched.patchedTile.config.displayType).toBe('table'); + + // Both the tile and the saved values changed in the database. + const stored = await Dashboard.findById(created.id); + expect(stored?.tiles).toHaveLength(1); + expect(stored?.tiles[0].id).toBe(tileId); + expect(stored?.tiles[0].config.displayType).toBe('table'); + expect(stored?.savedFilterValues).toEqual([ + { type: 'sql', condition: "ServiceName IN ('api')" }, + ]); + }); + + it('warns when a variable saved value names no declared filter', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable default typo', + tiles: [tile(sourceId)], + filters: [ + { + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + sourceId, + whereLanguage: 'sql', + isVariableEnabled: true, + variableName: 'service', + }, + ], + savedFilterValues: [ + { type: 'variable', name: 'srvice', values: ['api'] }, + ], + }); + + expect(result.isError).toBeFalsy(); + const created = JSON.parse(getFirstText(result)); + expect(created.warnings).toEqual( + expect.arrayContaining([expect.stringContaining('$srvice')]), + ); + }); + + it('does not warn when a variable saved value matches a declared filter', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable default match', + tiles: [tile(sourceId)], + filters: [ + { + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + sourceId, + whereLanguage: 'sql', + isVariableEnabled: true, + variableName: 'service', + }, + ], + savedFilterValues: [ + { type: 'variable', name: 'service', values: ['api'] }, + ], + }); + + expect(result.isError).toBeFalsy(); + const created = JSON.parse(getFirstText(result)); + const savedValueWarnings = (created.warnings ?? []).filter((w: string) => + w.includes('savedFilterValues'), + ); + expect(savedValueWarnings).toEqual([]); + }); + + it('warns on a patch whose variable saved value names no declared filter', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { name: 'Patch variable typo', tiles: [tile(sourceId)] }, + ); + const created = JSON.parse(getFirstText(createResult)); + + const patchResult = await callTool( + ctx.client!, + 'clickstack_patch_dashboard', + { + dashboardId: created.id, + savedFilterValues: [ + { type: 'variable', name: 'ghost', values: ['api'] }, + ], + }, + ); + expect(patchResult.isError).toBeFalsy(); + const patched = JSON.parse(getFirstText(patchResult)); + expect(patched.warnings).toEqual( + expect.arrayContaining([expect.stringContaining('$ghost')]), + ); + }); + + it('rejects a patch with no updatable fields', async () => { + const sourceId = ctx.traceSource._id.toString(); + + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Empty patch', + tiles: [tile(sourceId)], + }, + ); + const created = JSON.parse(getFirstText(createResult)); + + const patchResult = await callTool( + ctx.client!, + 'clickstack_patch_dashboard', + { dashboardId: created.id }, + ); + expect(patchResult.isError).toBe(true); + expect(getFirstText(patchResult)).toContain('savedFilterValues'); + }); + }); }); diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index 69c8f4eb17..f33fc89fbd 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -120,6 +120,8 @@ Apply these before calling clickstack_save_dashboard. Each rule is enforced by t 9f. MAKE A FILTER SINGLE-SELECT WHEN A TILE ONLY MAKES SENSE FOR ONE VALUE. maxSelections: 1 limits the dropdown to one value at a time, for example a host picker feeding a per-host detail view. +9g. SET savedFilterValues TO GIVE THE DASHBOARD A DEFAULT SELECTION. Pass savedFilterValues on clickstack_save_dashboard or clickstack_patch_dashboard to pre-select filter values whenever the dashboard opens. Pair this with a required filter (9e) so the dashboard opens scoped rather than blocked. + 10. UPDATE IS REPLACE, NOT MERGE. clickstack_save_dashboard with an id overwrites tiles, containers, and filters in their entirety. Call clickstack_get_dashboard first when you only want to add or rename one entry; do not send a partial set or you will silently drop everything you omitted. 11. GROUP RELATED TILES INTO CONTAINERS. REQUIRED at five or more tiles, no exceptions. An ungrouped wall of nine or ten tiles is a readability failure even when each tile is correct in isolation. Containers are the right way to introduce structure; markdown tiles for section labels are not. diff --git a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts index 5e43adfd10..aeea54d7bd 100644 --- a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts @@ -15,6 +15,7 @@ import { isConfigTile, validateDashboardTiles, } from '@/routers/external-api/v2/utils/dashboards'; +import { getExternalCompatibleFilterValues } from '@/utils/externalApi'; import type { ExternalDashboardTileWithId } from '@/utils/zod'; import { externalDashboardTileSchemaWithId } from '@/utils/zod'; @@ -22,6 +23,7 @@ import { buildMcpPatchDashboardSchema } from './schemas'; import { getRawSqlMissingSourceError, getRawSqlTileMacroWarnings, + getSavedFilterValueWarnings, getTileVariableWarnings, } from './validation'; @@ -40,7 +42,7 @@ export function registerPatchDashboard({ annotations: IDEMPOTENT_DESTRUCTIVE_TOOL, description: 'Make targeted updates to a dashboard without resubmitting the full object. ' + - 'You can update dashboard-level fields (name, tags) and/or replace a single ' + + 'You can update dashboard-level fields (name, tags, savedFilterValues) and/or replace a single ' + 'tile by tileId \u2014 all in one call. Unmentioned tiles and fields are preserved. ' + "Replacing a tile overwrites its whole config; the old config's fields are not merged in. " + 'If the new config cannot carry alerts (anything other than a line, ' + @@ -50,17 +52,25 @@ export function registerPatchDashboard({ 'IMPORTANT: After patching a tile, run clickstack_query_tile to confirm the query still works.', inputSchema: buildMcpPatchDashboardSchema(promqlEnabled), }, - async ({ dashboardId, name, tags, tileId, tile: inputTile }) => { + async ({ + dashboardId, + name, + tags, + savedFilterValues, + tileId, + tile: inputTile, + }) => { // Cross-field validation (kept in handler so the inputSchema // stays a plain z.object and its properties are visible in the // JSON Schema that the MCP SDK exposes to LLMs). if ( name === undefined && tags === undefined && + savedFilterValues === undefined && (tileId === undefined || inputTile === undefined) ) { return mcpUserError( - 'Provide at least one of: name, tags, or tileId+tile to patch.', + 'Provide at least one of: name, tags, savedFilterValues, or tileId+tile to patch.', ); } if ((tileId === undefined) !== (inputTile === undefined)) { @@ -92,6 +102,9 @@ export function registerPatchDashboard({ if (tags !== undefined) { setPayload.tags = uniq(tags); } + if (savedFilterValues !== undefined) { + setPayload.savedFilterValues = savedFilterValues; + } let patchedTile: ExternalDashboardTileWithId | undefined; @@ -224,7 +237,7 @@ export function registerPatchDashboard({ if (tileId !== undefined) { return mcpUserError( `Tile ${tileId} was not found at write time (it may have been removed by a concurrent update). ` + - 'The entire update was rejected — name/tags changes (if any) were not applied. Resubmit.', + 'The entire update was rejected — dashboard-level changes (name/tags/savedFilterValues, if any) were not applied. Resubmit.', ); } return mcpUserError('Dashboard not found'); @@ -256,21 +269,37 @@ export function registerPatchDashboard({ id: updatedDashboard._id.toString(), name: updatedDashboard.name, tags: updatedDashboard.tags, + ...(savedFilterValues !== undefined + ? { + savedFilterValues: getExternalCompatibleFilterValues( + updatedDashboard.savedFilterValues, + ), + } + : {}), ...(frontendUrl ? { url: `${frontendUrl}/dashboards/${updatedDashboard._id}` } : {}), }; + const warnings: string[] = []; + if (savedFilterValues !== undefined) { + warnings.push( + ...getSavedFilterValueWarnings( + savedFilterValues, + existingDashboard.filters, + ), + ); + } if (patchedTile) { output.patchedTile = patchedTile; output.hint = 'Use clickstack_query_tile to test the patched tile query.'; - const macroWarnings = [ + warnings.push( ...getRawSqlTileMacroWarnings([patchedTile]), ...getTileVariableWarnings([patchedTile], existingDashboard.filters), - ]; - if (macroWarnings.length > 0) { - output.warnings = macroWarnings; - } + ); + } + if (warnings.length > 0) { + output.warnings = warnings; } return { diff --git a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts index cdaa34beac..ba0c0d21e3 100644 --- a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts @@ -29,16 +29,18 @@ import { import type { ExternalDashboardTileWithId } from '@/utils/zod'; import { objectIdSchema, tagsSchema } from '@/utils/zod'; -import type { McpDashboardFilter } from './schemas'; +import type { McpDashboardFilter, McpSavedFilterValues } from './schemas'; import { buildMcpFiltersParam, buildMcpTilesParam, mcpContainersParam, + mcpSavedFilterValuesParam, } from './schemas'; import { getFilterVariableWarnings, getRawSqlMissingSourceError, getRawSqlTileMacroWarnings, + getSavedFilterValueWarnings, getTileVariableWarnings, } from './validation'; import { withResolvedFilterVariableNames } from './variables'; @@ -77,6 +79,7 @@ export function registerSaveDashboard({ ), containers: mcpContainersParam.optional(), filters: buildMcpFiltersParam(promqlEnabled).optional(), + savedFilterValues: mcpSavedFilterValuesParam.optional(), }), }, async ({ @@ -86,6 +89,7 @@ export function registerSaveDashboard({ tags, containers, filters: inputFilters, + savedFilterValues, }) => { if (!dashboardId) { return createDashboard({ @@ -98,6 +102,7 @@ export function registerSaveDashboard({ tags, containers, inputFilters, + savedFilterValues, }); } return updateDashboard({ @@ -111,6 +116,7 @@ export function registerSaveDashboard({ tags, containers, inputFilters, + savedFilterValues, }); }, ); @@ -157,6 +163,7 @@ async function createDashboard({ tags, containers, inputFilters, + savedFilterValues, }: { teamId: string; userId: string | undefined; @@ -167,6 +174,7 @@ async function createDashboard({ tags: string[] | undefined; containers: DashboardContainer[] | undefined; inputFilters: McpDashboardFilter[] | undefined; + savedFilterValues: McpSavedFilterValues | undefined; }) { const parsed = createDashboardBodySchema.safeParse({ name, @@ -174,6 +182,7 @@ async function createDashboard({ tags, containers, filters: stripFilterIds(inputFilters), + savedFilterValues, }); if (!parsed.success) { return mcpUserError(`Validation error:\n${formatZodIssues(parsed.error)}`); @@ -201,6 +210,7 @@ async function createDashboard({ ...getRawSqlTileMacroWarnings(tilesWithId), ...getTileVariableWarnings(tilesWithId, filters), ...getFilterVariableWarnings(filters), + ...getSavedFilterValueWarnings(parsed.data.savedFilterValues, filters), ]; const internalTiles = convertExternalTilesToInternal(tilesWithId); @@ -264,6 +274,7 @@ async function updateDashboard({ tags, containers, inputFilters, + savedFilterValues, }: { teamId: string; userId: string | undefined; @@ -275,6 +286,7 @@ async function updateDashboard({ tags: string[] | undefined; containers: DashboardContainer[] | undefined; inputFilters: McpDashboardFilter[] | undefined; + savedFilterValues: McpSavedFilterValues | undefined; }) { const parsed = updateDashboardBodySchema.safeParse({ name, @@ -282,6 +294,7 @@ async function updateDashboard({ tags, containers, filters: assignFilterIds(inputFilters), + savedFilterValues, }); if (!parsed.success) { return mcpUserError(`Validation error:\n${formatZodIssues(parsed.error)}`); @@ -327,6 +340,10 @@ async function updateDashboard({ // persisted dependent filter the agent did not touch is noise it cannot // act on from a tiles-only update. ...getFilterVariableWarnings(filters), + ...getSavedFilterValueWarnings( + parsed.data.savedFilterValues, + effectiveFilters, + ), ]; const existingTileIds = new Set( diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index 5695a41836..f9e40efe58 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -33,7 +33,12 @@ import { mcpQuantileLevelSchema, } from '@/mcp/tools/query/schemas'; import { QUERYABLE_METRIC_KINDS } from '@/mcp/tools/sources/metricKinds'; -import { objectIdSchema, tagsSchema } from '@/utils/zod'; +import { + externalSqlSavedFilterValueSchema, + externalVariableSavedFilterValueSchema, + objectIdSchema, + tagsSchema, +} from '@/utils/zod'; /** * Metric type values exposed on dashboard tile select items. Restricted to @@ -1895,6 +1900,48 @@ export function buildMcpFiltersParam(promqlEnabled: boolean) { .describe(`${mcpFiltersParam.description}${PROMQL_FILTERS_EXAMPLE}`); } +// Validation rules come from the external schemas so MCP and REST stay in +// lockstep; only the descriptions live here. +const sqlValueShape = externalSqlSavedFilterValueSchema.shape; +const mcpSqlSavedFilterValueSchema = externalSqlSavedFilterValueSchema.extend({ + type: sqlValueShape.type.describe( + 'Entry kind. Defaults to "sql"; a predicate broadcast to tiles.', + ), + condition: sqlValueShape.condition.describe( + 'Raw SQL predicate applied to every tile (SQL, not Lucene). Example: ' + + '"ServiceName IN (\'api\')".', + ), +}); + +const variableValueShape = externalVariableSavedFilterValueSchema.shape; +const mcpVariableSavedFilterValueSchema = + externalVariableSavedFilterValueSchema.extend({ + type: variableValueShape.type.describe( + 'Entry kind: a selection for a variable-enabled filter.', + ), + name: variableValueShape.name.describe( + 'The variableName of the variable-enabled filter this selection belongs ' + + "to. Must match a filter's variableName declared in `filters` (see " + + 'clickstack_get_dashboard for the resolved names); an unknown name is ' + + 'ignored when the dashboard loads.', + ), + values: variableValueShape.values.describe( + 'Selected values for the variable, e.g. ["api", "web"].', + ), + }); + +export const mcpSavedFilterValuesParam = z + .array( + z.union([mcpSqlSavedFilterValueSchema, mcpVariableSavedFilterValueSchema]), + ) + .describe( + 'Default filter selections restored every time the dashboard is opened. ' + + 'Replaces the whole saved set on write; pass [] to clear the defaults. ' + + 'Omit to leave the saved defaults untouched.', + ); + +export type McpSavedFilterValues = z.infer; + const mcpPatchDashboardSchema = z.object({ dashboardId: objectIdSchema.describe( 'ID of the dashboard to patch, from clickstack_get_dashboard (no id lists ' + @@ -1908,6 +1955,7 @@ const mcpPatchDashboardSchema = z.object({ tags: tagsSchema.describe( 'New tag list; replaces all existing tags. Omit to keep the current tags.', ), + savedFilterValues: mcpSavedFilterValuesParam.optional(), tileId: z .string() .optional() diff --git a/packages/api/src/mcp/tools/dashboards/validation.ts b/packages/api/src/mcp/tools/dashboards/validation.ts index e6298a026d..987ab6ad2f 100644 --- a/packages/api/src/mcp/tools/dashboards/validation.ts +++ b/packages/api/src/mcp/tools/dashboards/validation.ts @@ -36,6 +36,8 @@ import { } from '@/routers/external-api/v2/utils/dashboards'; import type { ExternalDashboardTileWithId } from '@/utils/zod'; +import type { McpSavedFilterValues } from './schemas'; + /** * Returns one entry per raw SQL tile that uses a source-dependent macro but * does not set a `sourceId`, recording which macro(s) triggered it so callers @@ -244,6 +246,37 @@ export function getFilterVariableWarnings( return warnings; } +/** + * Non-blocking check: a saved filter value of type 'variable' whose `name` + * matches no variable-enabled filter is silently ignored when the dashboard + * loads, so a typo'd variable name looks like a saved default but never + * applies. Warn so the agent can fix the name or add the filter. + */ +export function getSavedFilterValueWarnings( + savedFilterValues: McpSavedFilterValues | undefined, + filters: FilterForVariableDeclaration[] | undefined, +): string[] { + if (!savedFilterValues?.length) return []; + const declaredNames = new Set( + getDashboardVariableDeclarations(filters).map( + declaration => declaration.name, + ), + ); + const warnings: string[] = []; + for (const value of savedFilterValues) { + if (value.type !== 'variable') continue; + const name = value.name.trim(); + if (!name || declaredNames.has(name)) continue; + warnings.push( + `savedFilterValues references variable $${name}, which no variable-enabled ` + + 'filter declares. This default is ignored when the dashboard loads: add a ' + + `filter with isVariableEnabled: true and variableName: "${name}", or remove ` + + 'the entry.', + ); + } + return warnings; +} + function variableIssueSubject(language: TemplateLanguage): string { switch (language) { case 'sql': diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index f4510fb74e..d14d34849d 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -221,12 +221,17 @@ export type ExternalDashboardFilter = z.infer< * One entry in a dashboard's `savedFilterValues`: either a rendered SQL * predicate, or a selection addressed by the dashboard variable it belongs to. */ +export const externalSqlSavedFilterValueSchema = z.object({ + type: z.literal('sql').optional().default('sql'), + condition: z.string().max(10000), +}); + +export const externalVariableSavedFilterValueSchema = + VariableFilterValueSchema.strict(); + export const externalDashboardSavedFilterValueSchema = z.union([ - z.object({ - type: z.literal('sql').optional().default('sql'), - condition: z.string().max(10000), - }), - VariableFilterValueSchema.strict(), + externalSqlSavedFilterValueSchema, + externalVariableSavedFilterValueSchema, ]); // ================================