Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/mcp-filter-roundtrip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hyperdx/api': patch
---

fix: MCP dashboard filters and tiles from `clickstack_get_dashboard` and `clickstack_get_dashboard_tile` can be passed back unchanged to `clickstack_save_dashboard` and `clickstack_patch_dashboard`. MCP output now leaves out the filter fields a filter type fixes to one value, which the save schema rejects, and `clickstack_patch_dashboard` accepts an optional `tile.id` that must match `tileId`.
129 changes: 128 additions & 1 deletion packages/api/src/mcp/__tests__/dashboards/getDashboard.int.test.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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', {
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 = [
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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', {
Expand Down Expand Up @@ -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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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',
});

Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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]);

Expand Down
46 changes: 46 additions & 0 deletions packages/api/src/mcp/__tests__/dashboards/variables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
type ReferenceTargets,
resolveDashboardVariables,
resolveTileVariableReferences,
toMcpOutputFilters,
withResolvedFilterVariableNames,
} from '@/mcp/tools/dashboards/variables';
import type {
Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading