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
73 changes: 69 additions & 4 deletions packages/api/src/mcp/__tests__/toolDescriptions.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import {
NOT_REASONS_TO_USE_SQL,
SQL_FALLBACK_CRITERIA,
} from '@/mcp/tools/query/builderCatalog';
import { McpContext } from '@/mcp/tools/types';

import { createTestClient } from './mcpTestUtils';
Expand All @@ -9,14 +13,24 @@ describe('MCP tool descriptions', () => {
// this many UTF-8 bytes.
const CLAUDE_CODE_METADATA_LIMIT = 2048;

it('keeps tool descriptions and server instructions within the Claude Code limit', async () => {
async function getMetadata() {
const client = await createTestClient(context);
const { tools } = await client.listTools();
expect(tools.length).toBeGreaterThan(0);
return {
instructions: client.getInstructions() ?? '',
descriptions: new Map(
tools.map(tool => [tool.name, tool.description ?? '']),
),
};
}

it('keeps tool descriptions and server instructions within the Claude Code limit', async () => {
const { instructions, descriptions } = await getMetadata();
expect(descriptions.size).toBeGreaterThan(0);

const texts = [
['instructions', client.getInstructions() ?? ''] as const,
...tools.map(tool => [tool.name, tool.description ?? ''] as const),
['instructions', instructions] as const,
...Array.from(descriptions, ([name, text]) => [name, text] as const),
];

expect(
Expand All @@ -29,4 +43,55 @@ describe('MCP tool descriptions', () => {

expect(oversized).toEqual([]);
});

it('names the real SQL fallbacks and the needs builders already cover', async () => {
const { instructions, descriptions } = await getMetadata();
const sql = descriptions.get('clickstack_sql') ?? '';

for (const text of [instructions, sql]) {
expect(text).toContain(SQL_FALLBACK_CRITERIA);
expect(text).toContain(NOT_REASONS_TO_USE_SQL);
expect(text).not.toContain('CTEs');
}

expect(SQL_FALLBACK_CRITERIA).toContain('per-row ordering');
expect(SQL_FALLBACK_CRITERIA).toContain('already-aggregated result');
expect(NOT_REASONS_TO_USE_SQL).toContain('clickstack_table `having`');
expect(NOT_REASONS_TO_USE_SQL).toContain('includeLogs');
expect(NOT_REASONS_TO_USE_SQL).toContain(
'clickstack_trace_top_time_consuming_ops',
);
});

it('documents builder capabilities before the SQL nudge', async () => {
const { descriptions } = await getMetadata();
const cases = [
[
'clickstack_table',
[
'"having" filters aggregated groups',
'groupBy and valueExpression accept ClickHouse expressions',
'each select item has its own "where"',
],
],
[
'clickstack_timeseries',
[
'groupBy and valueExpression accept ClickHouse expressions',
'each select item can set its own "where"',
],
],
] as const;

for (const [name, phrases] of cases) {
const description = descriptions.get(name) ?? '';
const nudgeAt = description.indexOf('PREFER THIS over clickstack_sql');
expect(nudgeAt).toBeGreaterThan(0);
for (const phrase of phrases) {
const phraseAt = description.indexOf(phrase);
expect(phraseAt).toBeGreaterThanOrEqual(0);
expect(phraseAt).toBeLessThan(nudgeAt);
}
}
});
});
4 changes: 4 additions & 0 deletions packages/api/src/mcp/mcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import alertsTools from './tools/alerts/index';
import dashboardsTools from './tools/dashboards/index';
import {
BUILDER_TOOLS_LIST,
NOT_REASONS_TO_USE_SQL,
SQL_FALLBACK_CRITERIA,
} from './tools/query/builderCatalog';
import queryTools from './tools/query/index';
Expand All @@ -32,6 +33,9 @@ const SERVER_INSTRUCTIONS = [
'A single-source aggregation, top-N, time-series, or row browse must always',
'use a builder tool.',
'',
'NOT reasons to use SQL — builders cover these needs:',
NOT_REASONS_TO_USE_SQL,
'',
'Discovery flow: clickstack_list_sources → clickstack_describe_source → query.',
'Fetch the query_guide prompt for detailed syntax, and create_dashboard for',
'dashboard authoring.',
Expand Down
20 changes: 15 additions & 5 deletions packages/api/src/mcp/tools/query/builderCatalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,24 @@ export const BUILDER_TOOLS_LIST = [

/** When raw SQL is actually warranted. */
export const SQL_FALLBACK_CRITERIA =
'JOINs, sub-queries, CTEs, window functions, tables not registered as sources, or ' +
'summary-type metrics (the metricTables.summary table on a metric source, which the ' +
'builder tools cannot query)';
'joins across sources or tables, window functions or per-row ordering, ' +
'aggregating an already-aggregated result, unregistered tables, or ' +
'summary metrics (metricTables.summary)';

/** Needs the builder tools already cover, so they never justify raw SQL. */
export const NOT_REASONS_TO_USE_SQL = [
' • HAVING → clickstack_table `having`',
' • JSON, regex, or derived fields → groupBy / valueExpression expressions',
' • Conditional counts or two windows → per-item `where` or multiIf in groupBy',
' • One trace with its logs → clickstack_trace_waterfall (includeLogs)',
' • Child-span time breakdown → clickstack_trace_top_time_consuming_ops',
].join('\n');

/**
* Reciprocal nudge dropped into each builder tool's description. Keep it
* generic so a single string works for every builder tool.
*/
export const PREFER_BUILDER_OVER_SQL_NUDGE =
'PREFER THIS over clickstack_sql. Only drop to raw SQL for things the ' +
`builder tools cannot express — ${SQL_FALLBACK_CRITERIA}.`;
'PREFER THIS over clickstack_sql. Use SQL only for ' +
`${SQL_FALLBACK_CRITERIA}. ` +
'For needs builders already cover, see the server instructions.';
37 changes: 19 additions & 18 deletions packages/api/src/mcp/tools/query/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import { READ_ONLY_TOOL } from '@/mcp/tools/annotations';
import type { ToolRegistrar } from '@/mcp/tools/types';
import { mcpUserError } from '@/mcp/utils/errors';

import { BUILDER_TOOLS_LIST, SQL_FALLBACK_CRITERIA } from './builderCatalog';
import {
BUILDER_TOOLS_LIST,
NOT_REASONS_TO_USE_SQL,
SQL_FALLBACK_CRITERIA,
} from './builderCatalog';
import { parseTimeRange, runConfigTile } from './helpers';
import { createSourceLookup, prepareSqlQuery } from './prepareSql';
import { endTimeSchema, startTimeSchema } from './schemas';
Expand Down Expand Up @@ -100,25 +104,22 @@ export function registerSql({ context, registerTool }: ToolRegistrar) {
annotations: READ_ONLY_TOOL,
description:
'Execute raw ClickHouse SQL. LAST-RESORT TOOL — do NOT reach for this first.\n\n' +
'Default to the builder tools for querying; they are more reliable and produce ' +
'richer, structured results:\n' +
'Default to builder tools: they are more reliable and produce structured, ' +
'chart-ready results:\n' +
BUILDER_TOOLS_LIST +
'\n\n' +
'ONLY use raw SQL when the query genuinely cannot be expressed by a builder tool — ' +
`i.e. it requires ${SQL_FALLBACK_CRITERIA}. ` +
'A single-table aggregation, top-N, time-series, or row browse is ALWAYS a ' +
'builder-tool job, never raw SQL.\n\n' +
'Requires connectionId — call clickstack_list_sources to find connections. Pass sourceId ' +
'too when querying a source, so $__sourceTable resolves to its table. ' +
'Before writing SQL, get column names from clickstack_describe_source, or ' +
'clickstack_describe_table for tables that are not sources (instead of ' +
'querying system.columns / system.tables).\n\n' +
'Results are always returned as table rows — for time-series semantics, ' +
'include a time column and ORDER BY it in your SQL.\n\n' +
'To run several independent queries at once (e.g. comparing sources), pass ' +
'queries instead of sql. They run in parallel under a shared ' +
`${SQL_BATCH_DEADLINE_MS / 1000}s budget, and each result reports its own ` +
'status (ok, error, or timeout), so one failing query does not fail the others.',
`Use raw SQL only for ${SQL_FALLBACK_CRITERIA}.\n` +
'NOT reasons to use SQL — builders cover these needs:\n' +
NOT_REASONS_TO_USE_SQL +
'\n\n' +
'Needs connectionId; pass it with sourceId so $__sourceTable resolves to the ' +
"source's table. Get columns from clickstack_describe_source or " +
'clickstack_describe_table (not system.columns / system.tables).\n\n' +
'Results are table rows. For time-series semantics, include a time column ' +
'and ORDER BY it.\n\n' +
'Pass queries (instead of sql) to run independent SQL in parallel under a ' +
`shared ${SQL_BATCH_DEADLINE_MS / 1000}s budget. Each result reports ok, ` +
'error, or timeout independently.',
inputSchema: sqlSchema,
},
async input => {
Expand Down
8 changes: 5 additions & 3 deletions packages/api/src/mcp/tools/query/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,12 +264,14 @@ export function registerTable({ context, registerTool }: ToolRegistrar) {
description:
'Compute aggregated metrics as a table, single number, pie chart, or bar chart. ' +
'Use this for grouped aggregations, top-N queries, single-value KPIs, ' +
'or proportional breakdowns. For trends over time use clickstack_timeseries.\n\n' +
'or proportional breakdowns. For trends over time use clickstack_timeseries.\n' +
'"having" filters aggregated groups; groupBy and valueExpression accept ' +
'ClickHouse expressions (e.g. JSONExtractString); each select item has its own ' +
'"where" for conditional counts or cohort comparisons. Top-level "where" ' +
'scopes every select item.\n\n' +
PREFER_BUILDER_OVER_SQL_NUDGE +
'\n\n' +
'Requires sourceId — call clickstack_list_sources then clickstack_describe_source first.\n\n' +
'The top-level "where" scopes the whole query. Each select item can add its own ' +
'"where" (compiles to <aggFn>If(...)) for per-metric cohort comparisons; both are ANDed.\n\n' +
'Columns: top-level columns are PascalCase (Duration, StatusCode). ' +
"Map attributes use brackets, SpanAttributes['http.method'], and work in groupBy " +
"and valueExpression, e.g. toFloat64OrZero(SpanAttributes['key']).\n\n" +
Expand Down
5 changes: 4 additions & 1 deletion packages/api/src/mcp/tools/query/timeseries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ export function registerTimeseries({ context, registerTool }: ToolRegistrar) {
description:
'Plot metrics over time as a line or stacked bar chart. ' +
'Use this when you need to visualize trends, compare time-series, ' +
'or monitor metric changes over a time window.\n\n' +
'or monitor metric changes over a time window.\n' +
'groupBy and valueExpression accept ClickHouse expressions ' +
'(e.g. JSONExtractString); each select item can set its own "where" ' +
'for conditional series.\n\n' +
PREFER_BUILDER_OVER_SQL_NUDGE +
'\n\n' +
'Requires sourceId — call clickstack_list_sources then clickstack_describe_source first. ' +
Expand Down
Loading