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
7 changes: 7 additions & 0 deletions .changeset/dashboard-filter-all-option-sql-query.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/api': minor
'@hyperdx/app': minor
'@hyperdx/common-utils': minor
---

feat: add an "All" option to SQL query dashboard filters. Turn on "Include "All" option" in the filter's settings, and "All" selects every option the query returns, up to 1,000; tiles show an error above that, so add a `LIMIT` if the query can return more. Tiles wait for the options to load before running. Other filters' queries see "All" as no constraint. The external API and MCP accept `allowAll` on SQL query filters, and MCP tile runs with "All" run the filter's query to fill in its options.
5 changes: 5 additions & 0 deletions packages/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -4595,6 +4595,11 @@
"description": "Query whose first column populates the dropdown. May use the time\nmacros and other filters' variables. `$__sourceTable` and\n`$__filters` need a `sourceId`; `$__filters` expands to the\ndashboard's broadcast filter selections for that source.\n",
"example": "SELECT DISTINCT env FROM default.envs ORDER BY env"
},
"allowAll": {
"type": "boolean",
"description": "Adds an \"All\" choice to the dropdown, which selects every option\nthe query returns, up to 1,000; tiles show an error above that, so\nadd a LIMIT if the query can return more. Only allowed on\nmulti-select filters (not with maxSelections 1). With \"All\"\nselected, `$variableName` and `$__filter` use every option, and\n`$__conditionalAll` expands to 1=1.\n",
"example": true
},
"isBroadcastEnabled": {
"type": "boolean",
"enum": [
Expand Down
80 changes: 80 additions & 0 deletions packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1455,4 +1455,84 @@ describe('MCP Dashboard Tools - clickstack_query_tile', () => {
expect(getFirstText(result)).toContain('$traces variable');
});
});

describe('"All" on a SQL query filter', () => {
const saveDashboard = async (filterSql: string) => {
const connectionId = ctx.connection._id.toString();
const result = await callTool(ctx.client!, 'clickstack_save_dashboard', {
name: 'SQL query "All"',
tiles: [
{
name: 'Regions',
config: {
configType: 'sql',
displayType: 'table',
connectionId,
sqlTemplate:
"SELECT region FROM (SELECT arrayJoin(['us-east-1', 'us-west-1', 'eu-west-1']) AS region) " +
'WHERE $__filter(region, $region) ORDER BY region',
},
},
],
filters: [
{
type: 'SQL_QUERY',
name: 'Region',
connectionId,
sqlTemplate: filterSql,
allowAll: true,
variableName: 'region',
},
],
});
expect(result.isError).toBeFalsy();
return JSON.parse(getFirstText(result));
};

const queryAll = (dashboard: { id: string; tiles: { id: string }[] }) =>
callTool(ctx.client!, 'clickstack_query_tile', {
dashboardId: dashboard.id,
tileId: dashboard.tiles[0].id,
variableValues: [{ name: 'region', values: [], all: true }],
});

it("expands to the options the filter's query returns", async () => {
const dashboard = await saveDashboard(
"SELECT arrayJoin(['us-west-1', 'us-east-1'])",
);

const result = await queryAll(dashboard);

expect(result.isError).toBeFalsy();
const rows = JSON.parse(getFirstText(result)).result.data;
expect(rows.map((row: { region: string }) => row.region)).toEqual([
'us-east-1',
'us-west-1',
]);
});

it('rejects more than 1,000 options', async () => {
const dashboard = await saveDashboard(
'SELECT toString(number) FROM numbers(1001)',
);

const result = await queryAll(dashboard);

expect(result.isError).toBe(true);
expect(getFirstText(result)).toContain('covers more than 1,000 options');
});

it('reports a failing options query', async () => {
const dashboard = await saveDashboard(
'SELECT region FROM default.no_such_table',
);

const result = await queryAll(dashboard);

expect(result.isError).toBe(true);
expect(getFirstText(result)).toContain(
`Couldn't load the options for "All" on Region`,
);
});
});
});
5 changes: 3 additions & 2 deletions packages/api/src/mcp/prompts/dashboards/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1215,11 +1215,12 @@ Example (static list):
]

SQL query filter shape:
{ type: "SQL_QUERY", name, connectionId, sourceId?, sqlTemplate, variableName? }
{ type: "SQL_QUERY", name, connectionId, sourceId?, sqlTemplate, allowAll?, variableName? }

connectionId ClickHouse connection the query runs on (from clickstack_list_sources), or a CONNECTION filter's "$variableName".
sourceId Optional log, trace, session, or metric source on that connection, or a DATA_SOURCE filter's "$variableName". Needed for $__sourceTable and $__filters; $__filters expands to the dashboard's broadcast filter selections for that source.
sqlTemplate SELECT whose FIRST column becomes the dropdown values, cast to string with nulls and duplicates dropped, in row order (add ORDER BY). May use the time macros and other filters' variables, plus $__sourceTable and $__filters when sourceId is set.
allowAll Set true to add an "All" choice that selects every option the query returns, up to 1,000; tiles show an error above that, so add a LIMIT if the query can return more. Multi-select filters only. Other filters' sqlTemplates see this filter's "All" as no constraint: $__filter and $__conditionalAll expand to 1=1 there and a bare $variableName to NULL, so reference it through the macros.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is it that other filters don't see the all option like tiles do?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also leads to this misleading error message

Screenshot 2026-11-30 at 1 49 38 PM


Use it when the values live in a lookup table, dictionary, or join that no single source column covers; otherwise prefer QUERY_EXPRESSION. Like a static filter it is variable-only, so tiles pass the column explicitly: $__filter(<expression>, $<variableName>).

Expand Down Expand Up @@ -1352,7 +1353,7 @@ VALIDATING
clickstack_query_tile and clickstack_query_tiles expand variables with an EMPTY selection by default, which is what a freshly-opened dashboard looks like. Optionally, pass variableValues to check that a tile narrows correctly once something is picked:
variableValues: [{ name: "service", values: ["checkout"] }]
For a STATIC_LIST filter's variable, every supplied value must be one of the filter's declared options; the dashboard UI can never select anything else, so other values are rejected.
For a filter with allowAll, simulate "All" with { name, values: [], all: true }.
For a filter with allowAll, simulate "All" with { name, values: [], all: true }. For a SQL_QUERY filter, the tools run the filter's query to fill in its options, as the dashboard does.
Both tools report variable problems under "warnings". Alerts on a tile always evaluate with every variable empty, so a tile carrying an alert must stay correct with nothing selected.

== TABLE TILE LINKING (config.onClick) ==
Expand Down
15 changes: 14 additions & 1 deletion packages/api/src/mcp/tools/dashboards/queryTile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Dashboard from '@/models/dashboard';
import { convertToExternalDashboard } from '@/routers/external-api/v2/utils/dashboards';
import { objectIdSchema } from '@/utils/zod';

import { expandSqlQueryAllVariables } from './sqlQueryAllValues';
import {
getRawSqlTileMacroWarnings,
getTileVariableWarnings,
Expand Down Expand Up @@ -98,6 +99,18 @@ export function registerQueryTile({
if ('error' in resolvedVariables) {
return mcpUserError(resolvedVariables.error);
}
const expandedVariables = await expandSqlQueryAllVariables(
context,
externalDashboard,
{
variables: resolvedVariables.variables,
variableValues,
dateRange: [startDate, endDate],
},
);
if ('error' in expandedVariables) {
return mcpUserError(expandedVariables.error);
}

const resolvedTile = resolveTileVariableReferences(
storedTile,
Expand All @@ -112,7 +125,7 @@ export function registerQueryTile({
const { tile } = resolvedTile;

const result = await runConfigTile(context, tile, startDate, endDate, {
variables: resolvedVariables.variables,
variables: expandedVariables.variables,
});

// Surface non-blocking missing macro and variable warnings alongside
Expand Down
15 changes: 14 additions & 1 deletion packages/api/src/mcp/tools/dashboards/queryTiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
import type { ExternalDashboardTileWithId } from '@/utils/zod';
import { objectIdSchema } from '@/utils/zod';

import { expandSqlQueryAllVariables } from './sqlQueryAllValues';
import {
getRawSqlTileMacroWarnings,
getTileVariableWarnings,
Expand Down Expand Up @@ -222,7 +223,19 @@ export function registerQueryTiles({
if ('error' in resolved) {
return mcpUserError(resolved.error);
}
const { variables } = resolved;
const expanded = await expandSqlQueryAllVariables(
context,
externalDashboard,
{
variables: resolved.variables,
variableValues,
dateRange: [startDate, endDate],
},
);
if ('error' in expanded) {
return mcpUserError(expanded.error);
}
const { variables } = expanded;

// Resolve the target tiles. An explicit `tileIds` array is honored
// whenever the field is present — including an empty array, which
Expand Down
7 changes: 7 additions & 0 deletions packages/api/src/mcp/tools/dashboards/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1859,6 +1859,13 @@ const mcpSqlQueryFilterSchema = z
"dashboard's broadcast filter selections for that source. Without a sourceId, " +
'name tables explicitly. Example: "SELECT DISTINCT env FROM default.envs ORDER BY env".',
),
allowAll: SqlQueryDashboardFilterSchema.shape.allowAll.describe(
'Set true to add an "All" choice to the dropdown, which selects every ' +
'option the query returns, up to 1,000; tiles show an error above that, ' +
'so add a LIMIT if the query can return more. Multi-select filters only ' +
'(rejected with maxSelections: 1). With "All" selected, $variableName and ' +
'$__filter use every option, and $__conditionalAll expands to 1=1.',
),
})
.describe(
'A variable-only filter whose dropdown lists the first column of a ClickHouse ' +
Expand Down
159 changes: 159 additions & 0 deletions packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import {
getFilterVariableName,
isSqlQueryFilter,
renderSqlQueryFilterValuesQuery,
SQL_QUERY_FILTER_VALUES_SETTINGS,
toSqlQueryFilterValues,
} from '@hyperdx/common-utils/dist/filters';
import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables';
import {
type ChartVariable,
SourceKind,
} from '@hyperdx/common-utils/dist/types';
import {
ALL_SELECTION_MAX_OPTIONS,
expandAllSelections,
tooManyOptionsForAllMessage,
} from '@hyperdx/common-utils/dist/variableSelection';

import {
MCP_CLICKHOUSE_SETTINGS,
MCP_REQUEST_TIMEOUT,
toPlainMetricTables,
} from '@/mcp/tools/query/helpers';
import type { McpContext } from '@/mcp/tools/types';
import {
getMcpClickhouseClient,
McpConnectionNotFoundError,
} from '@/mcp/utils/clickhouse';
import { getMcpSource } from '@/mcp/utils/sources';
import type { ExternalDashboard } from '@/routers/external-api/v2/utils/dashboards';
import type {
ExternalDashboardFilter,
ExternalDashboardFilterWithId,
} from '@/utils/zod';

import { getVariableSelections, type McpVariableValues } from './variables';

type ExternalFilter = ExternalDashboardFilter | ExternalDashboardFilterWithId;

type DashboardState = {
variables: ChartVariable[];
/** Selected values by variable name, for `$name` connection and source references. */
selections: ReadonlyMap<string, string[]>;
dateRange: [Date, Date];
};

/**
* Expand "All" on SQL query filter variables by running each filter's values
* query, as the dashboard does. The queries see the variables with "All"
* unexpanded, as the dashboard's dropdowns do.
*/
export async function expandSqlQueryAllVariables(
context: McpContext,
dashboard: Pick<ExternalDashboard, 'filters' | 'savedFilterValues'>,
{
variables,
variableValues,
dateRange,
}: {
/** From `resolveDashboardVariables`. */
variables: ChartVariable[];
variableValues: McpVariableValues | undefined;
dateRange: [Date, Date];
},
): Promise<{ variables: ChartVariable[] } | { error: string }> {
const allNames = new Set(
variables.filter(variable => variable.all).map(({ name }) => name),
);
const state: DashboardState = {
variables,
selections: getVariableSelections(
dashboard.savedFilterValues,
variableValues,
),
dateRange,
};
const optionsByName = new Map<string, string[]>();
for (const filter of (dashboard.filters ?? []).filter(isSqlQueryFilter)) {
const name = getFilterVariableName(filter);
if (!name || !allNames.has(name)) continue;
const result = await loadOptions(context, filter, state);
if ('error' in result) {
return {
error: `Couldn't load the options for "All" on ${filter.name}: ${result.error}`,
};
}
if (result.values.length > ALL_SELECTION_MAX_OPTIONS) {
return { error: tooManyOptionsForAllMessage(filter.name) };
}
optionsByName.set(name, result.values);
}
return { variables: expandAllSelections(variables, optionsByName) };
}

async function loadOptions(
context: McpContext,
filter: Extract<ExternalFilter, { type: 'SQL_QUERY' }>,
{ variables, selections, dateRange }: DashboardState,
): Promise<{ values: string[] } | { error: string }> {
const resolve = (value: string | undefined) => {
const name = parseVariableReference(value);
return name == null ? value : selections.get(name)?.[0];
};
const noSelection = (reference: string) => ({
error: `${reference} has no selection. Pass one ID for it in variableValues, or save a selection on the dashboard.`,
});
const connectionId = resolve(filter.connectionId);
if (!connectionId) return noSelection(filter.connectionId);
const sourceId = resolve(filter.sourceId);
if (filter.sourceId && !sourceId) return noSelection(filter.sourceId);

const source = sourceId ? await getMcpSource(context, sourceId) : undefined;
if (sourceId && !source) return { error: `source ${sourceId} not found` };
if (source && source.connection.toString() !== connectionId) {
return { error: `source ${source.name} is not on the filter's connection` };
}

let rendered: ReturnType<typeof renderSqlQueryFilterValuesQuery>;
try {
rendered = renderSqlQueryFilterValuesQuery({
sqlTemplate: filter.sqlTemplate,
variables,
dateRange,
sourceTables: source
? {
from: source.from,
metricTables:
source.kind === SourceKind.Metric
? toPlainMetricTables(source.metricTables)
: undefined,
}
: undefined,
});
} catch (e) {
return { error: e instanceof Error ? e.message : String(e) };
}

try {
const client = await getMcpClickhouseClient(context, connectionId, {
requestTimeout: MCP_REQUEST_TIMEOUT,
});
const response = await client.query<'JSON'>({
query: rendered.sql,
query_params: rendered.params,
format: 'JSON',
clickhouse_settings: {
...MCP_CLICKHOUSE_SETTINGS,
...SQL_QUERY_FILTER_VALUES_SETTINGS,
},
});
const result = await response.json<{ value: string | null }>();
return { values: toSqlQueryFilterValues(result.data ?? []) };
} catch (e) {
if (e instanceof McpConnectionNotFoundError) {
return { error: `connection ${connectionId} not found` };
}
return { error: e instanceof Error ? e.message : String(e) };
}
}
Loading
Loading