Skip to content

Commit e7bf95e

Browse files
chore(api): steer MCP agents to builder tools over raw SQL (#3853)
## Summary Agents were reaching for `clickstack_sql` for work the builder tools already handle. The SQL fallback list named CTEs and subqueries broadly, so an agent could write a CTE for an aggregation and then cite that list as the reason for SQL. In a 14-day aggregate review of request intent across 212 teams, about 18% cited HAVING and about 37% said the builders could not extract JSON or regex. The server instructions, `clickstack_sql`, and the shared builder-tool nudge now draw a sharper line. SQL is reserved for joins across sources or tables, window functions or per-row ordering, aggregation over an already-aggregated result, unregistered tables, and summary metrics. A shared "not reasons" list maps the common needs to the tool that covers them: HAVING, JSON/regex and derived fields, conditional counts and two-window comparisons, one trace with logs, and child-span time breakdowns. `clickstack_table` and `clickstack_timeseries` state their `having`, expression-valued `groupBy`/`valueExpression`, and per-item `where` support up front. Descriptions stay under the 2048-byte client limit. No tool parameters or query behavior changed. ### How to reproduce **Starting point:** an MCP client connected to a ClickStack instance. **On `main`:** 1. Ask an agent to filter grouped results with HAVING, extract a JSON field, or compare counts across two windows. The generic CTE/subquery fallback wording invites raw SQL, while the builder descriptions only document HAVING and expression support in individual field schemas. **On this branch:** 1. Run the same prompts. The server instructions and tool descriptions name the builder tool for each need and reserve SQL for cases builders cannot express. ### How to test on Vercel preview N/A — non-UI change. ### References - Aggregate review: 18% of 212 teams cited HAVING; 37% said builders could not extract JSON or regex (14-day window). --- > [!NOTE] > **Low Risk** > Metadata and test-only changes; no tool parameters or query execution paths are modified. > > **Overview** > Updates **MCP copy only** so agents default to builder query tools instead of `clickstack_sql`. Shared `SQL_FALLBACK_CRITERIA` in `builderCatalog` is narrowed (drops broad CTE/subquery wording; names joins, window/per-row ordering, already-aggregated results, unregistered tables, and summary metrics). A new **`NOT_REASONS_TO_USE_SQL`** list maps common needs (HAVING, JSON/regex via expressions, per-item `where`, trace waterfall/logs, child-span breakdown) to the right builder tools. > > That guidance is wired into **server instructions**, the **`clickstack_sql`** description, and the shared **PREFER builder** nudge. **`clickstack_table`** and **`clickstack_timeseries`** now call out `having`, expression `groupBy`/`valueExpression`, and per-select `where` **before** the SQL nudge. > > Tests in `toolDescriptions.test.ts` assert the 2048-byte Claude limit, that instructions/SQL omit “CTEs” but include both policy strings, and that builder capability phrases precede the SQL nudge. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit db0af2e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
1 parent 29d2af0 commit e7bf95e

6 files changed

Lines changed: 116 additions & 31 deletions

File tree

‎packages/api/src/mcp/__tests__/toolDescriptions.test.ts‎

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import {
2+
NOT_REASONS_TO_USE_SQL,
3+
SQL_FALLBACK_CRITERIA,
4+
} from '@/mcp/tools/query/builderCatalog';
15
import { McpContext } from '@/mcp/tools/types';
26

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

12-
it('keeps tool descriptions and server instructions within the Claude Code limit', async () => {
16+
async function getMetadata() {
1317
const client = await createTestClient(context);
1418
const { tools } = await client.listTools();
15-
expect(tools.length).toBeGreaterThan(0);
19+
return {
20+
instructions: client.getInstructions() ?? '',
21+
descriptions: new Map(
22+
tools.map(tool => [tool.name, tool.description ?? '']),
23+
),
24+
};
25+
}
26+
27+
it('keeps tool descriptions and server instructions within the Claude Code limit', async () => {
28+
const { instructions, descriptions } = await getMetadata();
29+
expect(descriptions.size).toBeGreaterThan(0);
1630

1731
const texts = [
18-
['instructions', client.getInstructions() ?? ''] as const,
19-
...tools.map(tool => [tool.name, tool.description ?? ''] as const),
32+
['instructions', instructions] as const,
33+
...Array.from(descriptions, ([name, text]) => [name, text] as const),
2034
];
2135

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

3044
expect(oversized).toEqual([]);
3145
});
46+
47+
it('names the real SQL fallbacks and the needs builders already cover', async () => {
48+
const { instructions, descriptions } = await getMetadata();
49+
const sql = descriptions.get('clickstack_sql') ?? '';
50+
51+
for (const text of [instructions, sql]) {
52+
expect(text).toContain(SQL_FALLBACK_CRITERIA);
53+
expect(text).toContain(NOT_REASONS_TO_USE_SQL);
54+
expect(text).not.toContain('CTEs');
55+
}
56+
57+
expect(SQL_FALLBACK_CRITERIA).toContain('per-row ordering');
58+
expect(SQL_FALLBACK_CRITERIA).toContain('already-aggregated result');
59+
expect(NOT_REASONS_TO_USE_SQL).toContain('clickstack_table `having`');
60+
expect(NOT_REASONS_TO_USE_SQL).toContain('includeLogs');
61+
expect(NOT_REASONS_TO_USE_SQL).toContain(
62+
'clickstack_trace_top_time_consuming_ops',
63+
);
64+
});
65+
66+
it('documents builder capabilities before the SQL nudge', async () => {
67+
const { descriptions } = await getMetadata();
68+
const cases = [
69+
[
70+
'clickstack_table',
71+
[
72+
'"having" filters aggregated groups',
73+
'groupBy and valueExpression accept ClickHouse expressions',
74+
'each select item has its own "where"',
75+
],
76+
],
77+
[
78+
'clickstack_timeseries',
79+
[
80+
'groupBy and valueExpression accept ClickHouse expressions',
81+
'each select item can set its own "where"',
82+
],
83+
],
84+
] as const;
85+
86+
for (const [name, phrases] of cases) {
87+
const description = descriptions.get(name) ?? '';
88+
const nudgeAt = description.indexOf('PREFER THIS over clickstack_sql');
89+
expect(nudgeAt).toBeGreaterThan(0);
90+
for (const phrase of phrases) {
91+
const phraseAt = description.indexOf(phrase);
92+
expect(phraseAt).toBeGreaterThanOrEqual(0);
93+
expect(phraseAt).toBeLessThan(nudgeAt);
94+
}
95+
}
96+
});
3297
});

‎packages/api/src/mcp/mcpServer.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import alertsTools from './tools/alerts/index';
88
import dashboardsTools from './tools/dashboards/index';
99
import {
1010
BUILDER_TOOLS_LIST,
11+
NOT_REASONS_TO_USE_SQL,
1112
SQL_FALLBACK_CRITERIA,
1213
} from './tools/query/builderCatalog';
1314
import queryTools from './tools/query/index';
@@ -32,6 +33,9 @@ const SERVER_INSTRUCTIONS = [
3233
'A single-source aggregation, top-N, time-series, or row browse must always',
3334
'use a builder tool.',
3435
'',
36+
'NOT reasons to use SQL — builders cover these needs:',
37+
NOT_REASONS_TO_USE_SQL,
38+
'',
3539
'Discovery flow: clickstack_list_sources → clickstack_describe_source → query.',
3640
'Fetch the query_guide prompt for detailed syntax, and create_dashboard for',
3741
'dashboard authoring.',

‎packages/api/src/mcp/tools/query/builderCatalog.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,24 @@ export const BUILDER_TOOLS_LIST = [
1919

2020
/** When raw SQL is actually warranted. */
2121
export const SQL_FALLBACK_CRITERIA =
22-
'JOINs, sub-queries, CTEs, window functions, tables not registered as sources, or ' +
23-
'summary-type metrics (the metricTables.summary table on a metric source, which the ' +
24-
'builder tools cannot query)';
22+
'joins across sources or tables, window functions or per-row ordering, ' +
23+
'aggregating an already-aggregated result, unregistered tables, or ' +
24+
'summary metrics (metricTables.summary)';
25+
26+
/** Needs the builder tools already cover, so they never justify raw SQL. */
27+
export const NOT_REASONS_TO_USE_SQL = [
28+
' • HAVING → clickstack_table `having`',
29+
' • JSON, regex, or derived fields → groupBy / valueExpression expressions',
30+
' • Conditional counts or two windows → per-item `where` or multiIf in groupBy',
31+
' • One trace with its logs → clickstack_trace_waterfall (includeLogs)',
32+
' • Child-span time breakdown → clickstack_trace_top_time_consuming_ops',
33+
].join('\n');
2534

2635
/**
2736
* Reciprocal nudge dropped into each builder tool's description. Keep it
2837
* generic so a single string works for every builder tool.
2938
*/
3039
export const PREFER_BUILDER_OVER_SQL_NUDGE =
31-
'PREFER THIS over clickstack_sql. Only drop to raw SQL for things the ' +
32-
`builder tools cannot express — ${SQL_FALLBACK_CRITERIA}.`;
40+
'PREFER THIS over clickstack_sql. Use SQL only for ' +
41+
`${SQL_FALLBACK_CRITERIA}. ` +
42+
'For needs builders already cover, see the server instructions.';

‎packages/api/src/mcp/tools/query/sql.ts‎

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@ import { READ_ONLY_TOOL } from '@/mcp/tools/annotations';
55
import type { ToolRegistrar } from '@/mcp/tools/types';
66
import { mcpUserError } from '@/mcp/utils/errors';
77

8-
import { BUILDER_TOOLS_LIST, SQL_FALLBACK_CRITERIA } from './builderCatalog';
8+
import {
9+
BUILDER_TOOLS_LIST,
10+
NOT_REASONS_TO_USE_SQL,
11+
SQL_FALLBACK_CRITERIA,
12+
} from './builderCatalog';
913
import { parseTimeRange, runConfigTile } from './helpers';
1014
import { createSourceLookup, prepareSqlQuery } from './prepareSql';
1115
import { endTimeSchema, startTimeSchema } from './schemas';
@@ -100,25 +104,22 @@ export function registerSql({ context, registerTool }: ToolRegistrar) {
100104
annotations: READ_ONLY_TOOL,
101105
description:
102106
'Execute raw ClickHouse SQL. LAST-RESORT TOOL — do NOT reach for this first.\n\n' +
103-
'Default to the builder tools for querying; they are more reliable and produce ' +
104-
'richer, structured results:\n' +
107+
'Default to builder tools: they are more reliable and produce structured, ' +
108+
'chart-ready results:\n' +
105109
BUILDER_TOOLS_LIST +
106110
'\n\n' +
107-
'ONLY use raw SQL when the query genuinely cannot be expressed by a builder tool — ' +
108-
`i.e. it requires ${SQL_FALLBACK_CRITERIA}. ` +
109-
'A single-table aggregation, top-N, time-series, or row browse is ALWAYS a ' +
110-
'builder-tool job, never raw SQL.\n\n' +
111-
'Requires connectionId — call clickstack_list_sources to find connections. Pass sourceId ' +
112-
'too when querying a source, so $__sourceTable resolves to its table. ' +
113-
'Before writing SQL, get column names from clickstack_describe_source, or ' +
114-
'clickstack_describe_table for tables that are not sources (instead of ' +
115-
'querying system.columns / system.tables).\n\n' +
116-
'Results are always returned as table rows — for time-series semantics, ' +
117-
'include a time column and ORDER BY it in your SQL.\n\n' +
118-
'To run several independent queries at once (e.g. comparing sources), pass ' +
119-
'queries instead of sql. They run in parallel under a shared ' +
120-
`${SQL_BATCH_DEADLINE_MS / 1000}s budget, and each result reports its own ` +
121-
'status (ok, error, or timeout), so one failing query does not fail the others.',
111+
`Use raw SQL only for ${SQL_FALLBACK_CRITERIA}.\n` +
112+
'NOT reasons to use SQL — builders cover these needs:\n' +
113+
NOT_REASONS_TO_USE_SQL +
114+
'\n\n' +
115+
'Needs connectionId; pass it with sourceId so $__sourceTable resolves to the ' +
116+
"source's table. Get columns from clickstack_describe_source or " +
117+
'clickstack_describe_table (not system.columns / system.tables).\n\n' +
118+
'Results are table rows. For time-series semantics, include a time column ' +
119+
'and ORDER BY it.\n\n' +
120+
'Pass queries (instead of sql) to run independent SQL in parallel under a ' +
121+
`shared ${SQL_BATCH_DEADLINE_MS / 1000}s budget. Each result reports ok, ` +
122+
'error, or timeout independently.',
122123
inputSchema: sqlSchema,
123124
},
124125
async input => {

‎packages/api/src/mcp/tools/query/table.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,12 +264,14 @@ export function registerTable({ context, registerTool }: ToolRegistrar) {
264264
description:
265265
'Compute aggregated metrics as a table, single number, pie chart, or bar chart. ' +
266266
'Use this for grouped aggregations, top-N queries, single-value KPIs, ' +
267-
'or proportional breakdowns. For trends over time use clickstack_timeseries.\n\n' +
267+
'or proportional breakdowns. For trends over time use clickstack_timeseries.\n' +
268+
'"having" filters aggregated groups; groupBy and valueExpression accept ' +
269+
'ClickHouse expressions (e.g. JSONExtractString); each select item has its own ' +
270+
'"where" for conditional counts or cohort comparisons. Top-level "where" ' +
271+
'scopes every select item.\n\n' +
268272
PREFER_BUILDER_OVER_SQL_NUDGE +
269273
'\n\n' +
270274
'Requires sourceId — call clickstack_list_sources then clickstack_describe_source first.\n\n' +
271-
'The top-level "where" scopes the whole query. Each select item can add its own ' +
272-
'"where" (compiles to <aggFn>If(...)) for per-metric cohort comparisons; both are ANDed.\n\n' +
273275
'Columns: top-level columns are PascalCase (Duration, StatusCode). ' +
274276
"Map attributes use brackets, SpanAttributes['http.method'], and work in groupBy " +
275277
"and valueExpression, e.g. toFloat64OrZero(SpanAttributes['key']).\n\n" +

‎packages/api/src/mcp/tools/query/timeseries.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,10 @@ export function registerTimeseries({ context, registerTool }: ToolRegistrar) {
8080
description:
8181
'Plot metrics over time as a line or stacked bar chart. ' +
8282
'Use this when you need to visualize trends, compare time-series, ' +
83-
'or monitor metric changes over a time window.\n\n' +
83+
'or monitor metric changes over a time window.\n' +
84+
'groupBy and valueExpression accept ClickHouse expressions ' +
85+
'(e.g. JSONExtractString); each select item can set its own "where" ' +
86+
'for conditional series.\n\n' +
8487
PREFER_BUILDER_OVER_SQL_NUDGE +
8588
'\n\n' +
8689
'Requires sourceId — call clickstack_list_sources then clickstack_describe_source first. ' +

0 commit comments

Comments
 (0)