diff --git a/.changeset/mcp-tool-descriptions.md b/.changeset/mcp-tool-descriptions.md new file mode 100644 index 0000000000..68455c9e4e --- /dev/null +++ b/.changeset/mcp-tool-descriptions.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/api': patch +'@hyperdx/common-utils': patch +--- + +fix(mcp): describe every MCP tool input, drop descriptions that restate schema constraints, and keep tool descriptions under Claude Code's 2 KB limit diff --git a/packages/api/src/mcp/__tests__/toolDescriptions.test.ts b/packages/api/src/mcp/__tests__/toolDescriptions.test.ts new file mode 100644 index 0000000000..a9e268e125 --- /dev/null +++ b/packages/api/src/mcp/__tests__/toolDescriptions.test.ts @@ -0,0 +1,32 @@ +import { McpContext } from '@/mcp/tools/types'; + +import { createTestClient } from './mcpTestUtils'; + +describe('MCP tool descriptions', () => { + const context: McpContext = { teamId: 'team-id', userId: 'user-id' }; + + // Claude Code truncates tool descriptions and server instructions past + // this many UTF-8 bytes. + const CLAUDE_CODE_METADATA_LIMIT = 2048; + + it('keeps tool descriptions and server instructions within the Claude Code limit', async () => { + const client = await createTestClient(context); + const { tools } = await client.listTools(); + expect(tools.length).toBeGreaterThan(0); + + const texts = [ + ['instructions', client.getInstructions() ?? ''] as const, + ...tools.map(tool => [tool.name, tool.description ?? ''] as const), + ]; + + expect( + texts.filter(([, text]) => text.trim() === '').map(([name]) => name), + ).toEqual([]); + + const oversized = texts + .map(([name, text]) => [name, Buffer.byteLength(text, 'utf8')] as const) + .filter(([, bytes]) => bytes > CLAUDE_CODE_METADATA_LIMIT); + + expect(oversized).toEqual([]); + }); +}); diff --git a/packages/api/src/mcp/__tests__/toolSchemas.test.ts b/packages/api/src/mcp/__tests__/toolSchemas.test.ts index 5ff25cb983..24cef4892d 100644 --- a/packages/api/src/mcp/__tests__/toolSchemas.test.ts +++ b/packages/api/src/mcp/__tests__/toolSchemas.test.ts @@ -79,10 +79,25 @@ describe('MCP tool input schemas', () => { expect(tools.length).toBeGreaterThan(0); - const offenders = tools.flatMap(tool => walk(tool.inputSchema, tool.name)); + const offenders = tools.flatMap(tool => + walk(tool.inputSchema, tool.name, providerRejections), + ); expect(offenders).toEqual([]); }); + + it('describe every input property', async () => { + const client = await createTestClient(context); + const { tools } = await client.listTools(); + + expect(tools.length).toBeGreaterThan(0); + + const missing = tools.flatMap(tool => + walk(tool.inputSchema, tool.name, undescribedProperties), + ); + + expect(missing).toEqual([]); + }); }); function isRecord(value: unknown): value is Record { @@ -93,13 +108,26 @@ function isUnknownArray(value: unknown): value is unknown[] { return Array.isArray(value); } -/** JSON pointer path -> problem, for every offending node under `node`. */ -function walk(node: unknown, path: string): string[] { +type SchemaCheck = (node: Record, path: string) => string[]; + +/** JSON pointer path -> problem, for every node under `node` that fails `check`. */ +function walk(node: unknown, path: string, check: SchemaCheck): string[] { if (isUnknownArray(node)) { - return node.flatMap((child, i) => walk(child, `${path}/${i}`)); + return node.flatMap((child, i) => walk(child, `${path}/${i}`, check)); } if (!isRecord(node)) return []; + const found = check(node, path); + for (const [key, value] of Object.entries(node)) { + found.push(...walk(value, `${path}/${key}`, check)); + } + return found; +} + +function providerRejections( + node: Record, + path: string, +): string[] { const found: string[] = []; const enumValues = node.enum; @@ -120,9 +148,22 @@ function walk(node: unknown, path: string): string[] { ); } - for (const [key, value] of Object.entries(node)) { - found.push(...walk(value, `${path}/${key}`)); - } - return found; } + +function undescribedProperties( + node: Record, + path: string, +): string[] { + if (!isRecord(node.properties)) return []; + return Object.entries(node.properties).flatMap(([key, prop]) => { + if (!isRecord(prop)) return []; + // zod-to-json-schema dedupes a reused schema into a bare $ref pointer; + // the description lives on the referenced definition. + if (Object.keys(prop).length === 1 && '$ref' in prop) return []; + const { description } = prop; + return typeof description === 'string' && description.trim() !== '' + ? [] + : [`${path}/properties/${key}: missing description`]; + }); +} diff --git a/packages/api/src/mcp/tools/alerts/deleteWebhook.ts b/packages/api/src/mcp/tools/alerts/deleteWebhook.ts index ef96eb6bdc..ff5265fcac 100644 --- a/packages/api/src/mcp/tools/alerts/deleteWebhook.ts +++ b/packages/api/src/mcp/tools/alerts/deleteWebhook.ts @@ -22,7 +22,9 @@ export function registerDeleteWebhook({ 'references it — reassign or delete those alerts first. Use ' + 'clickstack_get_webhook to list available webhook IDs.', inputSchema: z.object({ - id: objectIdSchema.describe('Webhook ID to delete.'), + id: objectIdSchema.describe( + 'ID of the webhook to delete, from clickstack_get_webhook.', + ), }), }, async ({ id: webhookId }) => { diff --git a/packages/api/src/mcp/tools/alerts/getAlert.ts b/packages/api/src/mcp/tools/alerts/getAlert.ts index 28c90ae091..d9e223a120 100644 --- a/packages/api/src/mcp/tools/alerts/getAlert.ts +++ b/packages/api/src/mcp/tools/alerts/getAlert.ts @@ -38,14 +38,15 @@ export function registerGetAlert({ .string() .optional() .describe( - 'Alert ID. Omit to list all alerts, provide to get full detail.', + 'Alert ID from a previous list call or clickstack_save_alert. ' + + 'Omit to list all alerts, provide to get full detail.', ), state: z .enum(['ALERT', 'OK', 'DISABLED', 'INSUFFICIENT_DATA']) .optional() .describe( - 'Filter list by alert state (only applies when id is omitted). ' + - 'Use "ALERT" to find currently firing alerts.', + 'List only alerts currently in this state; ignored when id is ' + + 'provided. Use ALERT to find alerts that are firing now.', ), }), }, diff --git a/packages/api/src/mcp/tools/alerts/saveAlert.ts b/packages/api/src/mcp/tools/alerts/saveAlert.ts index 190476eea9..e687ed9be8 100644 --- a/packages/api/src/mcp/tools/alerts/saveAlert.ts +++ b/packages/api/src/mcp/tools/alerts/saveAlert.ts @@ -47,12 +47,18 @@ export function registerSaveAlert({ 'Create a new alert (omit id) or update an existing one (provide id). ' + 'Alerts monitor a saved search, a dashboard tile, or an inline chart ' + 'config (source "inline" + chartConfig — no saved search or dashboard ' + - 'needed) and fire when the metric crosses a threshold. At least one ' + - 'webhook notification channel ' + - 'is required: pass "channels" for 1-10 targets, or the legacy singular ' + - '"channel" for one. Updates replace the alert configuration rather than ' + - 'merging it, so read the alert first and resend its full "channels" ' + - 'array to avoid dropping channels you did not mean to remove.', + 'needed) and fire when the metric crosses a threshold. Once saved, the ' + + 'alert is evaluated every interval and notifies its webhook channels ' + + 'when it fires and when it resolves. At least one webhook channel is ' + + 'required: pass "channels", or the legacy singular "channel" for one ' + + '(webhook IDs come from clickstack_get_webhook). Updates replace the ' + + 'alert configuration rather than merging it: channels you do not resend are ' + + 'removed, omitted name and message are cleared, omitted displayName and tags ' + + 'are re-derived from the source, and settings this tool cannot set ' + + '(note, consecutive-window count) are cleared. Omitting both ' + + 'scheduleStartAt and scheduleOffsetMinutes keeps the stored schedule; ' + + 'clearing scheduleStartAt without an offset resets the offset to 0. Read the alert with ' + + 'clickstack_get_alert first and resend every field you want to keep.', inputSchema: mcpSaveAlertSchema, }, async input => { diff --git a/packages/api/src/mcp/tools/alerts/saveWebhook.ts b/packages/api/src/mcp/tools/alerts/saveWebhook.ts index e8e33590f7..163d31e2ee 100644 --- a/packages/api/src/mcp/tools/alerts/saveWebhook.ts +++ b/packages/api/src/mcp/tools/alerts/saveWebhook.ts @@ -29,9 +29,16 @@ const mcpSaveWebhookSchema = z.object({ .string() .optional() .describe( - 'Webhook ID. Omit to create a new webhook, provide to update an existing one.', + 'Webhook ID from clickstack_get_webhook. Omit to create a new ' + + 'webhook, provide to update an existing one.', + ), + name: z + .string() + .min(1) + .describe( + "Display name for the webhook. Must be unique among the team's " + + 'webhooks of the same service.', ), - name: z.string().min(1).describe('Human-friendly webhook name.'), service: z .enum(WEBHOOK_SERVICES) .describe( @@ -48,14 +55,14 @@ const mcpSaveWebhookSchema = z.object({ .string() .optional() .describe( - 'Optional description shown in the UI. On update this is a full replace: ' + + 'Description shown in the UI. On update this is a full replace: ' + 'omitting it clears the stored description.', ), headers: z .record(z.string(), z.string()) .optional() .describe( - 'Optional HTTP headers (key -> value). Not supported for the slack ' + + 'HTTP headers sent with each request. Not supported for the slack ' + 'service. On update these are write-only: omitting them PRESERVES the ' + 'stored values; send an empty object ({}) to clear them. If the ' + 'destination (url or service) changes, omitted headers are cleared.', @@ -64,14 +71,14 @@ const mcpSaveWebhookSchema = z.object({ .record(z.string(), z.string()) .optional() .describe( - 'Optional query parameters (key -> value). Not supported for the slack ' + + 'Query parameters appended to the URL. Not supported for the slack ' + 'service. Same write-only update semantics as headers.', ), body: z .string() .optional() .describe( - 'Optional Handlebars request body template. Not supported for the ' + + 'Handlebars template for the request body. Not supported for the ' + 'slack service. Rejected if it does not compile or calls a helper ' + 'other than eq and the Handlebars built-ins. Write string ' + 'arguments inside {{ }} with plain or single quotes, e.g. ' + @@ -94,12 +101,14 @@ export function registerSaveWebhook({ description: 'Create a new webhook (omit id) or update an existing one (provide ' + 'id). Use the returned id as the webhookId when creating alerts with ' + - 'clickstack_save_alert. Required: name, service (slack, generic, or ' + - 'incidentio), and url. For the slack service the url host must end in ' + - 'slack.com and headers/queryParams/body are not supported. On update, ' + - 'readable fields (description, body) are a full replace while ' + - 'write-only headers/queryParams are preserved when omitted (send {} to ' + - 'clear); changing the destination clears omitted write-only secrets.', + 'clickstack_save_alert. For the slack service the url host must end ' + + 'in slack.com and headers/queryParams/body are not supported. On ' + + 'update, every alert using this webhook sends its next notifications ' + + 'with the new settings, including a changed url. description and body ' + + 'are a full replace (omitting them clears them), while write-only ' + + 'headers/queryParams are preserved when omitted (send {} to clear); ' + + 'changing url or service clears omitted headers/queryParams. ' + + 'url, headers, and queryParams are never returned.', inputSchema: mcpSaveWebhookSchema, }, async input => { diff --git a/packages/api/src/mcp/tools/alerts/schemas.ts b/packages/api/src/mcp/tools/alerts/schemas.ts index d218390b08..65503aa072 100644 --- a/packages/api/src/mcp/tools/alerts/schemas.ts +++ b/packages/api/src/mcp/tools/alerts/schemas.ts @@ -55,7 +55,12 @@ const mcpAlertChartLevelWhereSchema = z .optional() .describe( 'Chart-level filter applied to every select item (combined with each ' + - "item's own `where` via AND). Lucene syntax by default.", + "item's own `where` via AND). Write it in the language set by whereLanguage.", + ); + +const mcpAlertChartLevelWhereLanguageSchema = + SearchConditionTrimmedLanguageSchema.optional().describe( + 'Query language the chart-level `where` is written in. Lucene when omitted.', ); const rejectedRawSqlAlertWhereField = z @@ -73,22 +78,22 @@ const mcpAlertChartConfigSchema = z mcpLineTileSchema.shape.config.extend({ name: mcpAlertChartConfigNameSchema, where: mcpAlertChartLevelWhereSchema, - whereLanguage: SearchConditionTrimmedLanguageSchema.optional(), + whereLanguage: mcpAlertChartLevelWhereLanguageSchema, }), mcpBarTileSchema.shape.config.extend({ name: mcpAlertChartConfigNameSchema, where: mcpAlertChartLevelWhereSchema, - whereLanguage: SearchConditionTrimmedLanguageSchema.optional(), + whereLanguage: mcpAlertChartLevelWhereLanguageSchema, }), mcpStackedLineTileSchema.shape.config.extend({ name: mcpAlertChartConfigNameSchema, where: mcpAlertChartLevelWhereSchema, - whereLanguage: SearchConditionTrimmedLanguageSchema.optional(), + whereLanguage: mcpAlertChartLevelWhereLanguageSchema, }), mcpNumberTileSchema.shape.config.extend({ name: mcpAlertChartConfigNameSchema, where: mcpAlertChartLevelWhereSchema, - whereLanguage: SearchConditionTrimmedLanguageSchema.optional(), + whereLanguage: mcpAlertChartLevelWhereLanguageSchema, }), mcpSqlTileSchema.shape.config.omit({ onClick: true }).extend({ name: mcpAlertChartConfigNameSchema, @@ -112,21 +117,23 @@ const mcpAlertChartConfigSchema = z const mcpAlertChannelSchema = z .object({ - type: z - .literal('webhook') - .describe('Channel type for alert notifications.'), + type: z.literal('webhook').describe('Notification channel kind.'), webhookId: z .string() - .describe('Webhook destination ID (required for webhook channel).'), + .describe( + 'ID of the webhook to notify. Get it from clickstack_get_webhook, or ' + + 'create one with clickstack_save_webhook.', + ), }) - .describe('Alert notification channel configuration.'); + .describe("A webhook that receives this alert's notifications."); export const mcpSaveAlertSchema = z.object({ id: z .string() .optional() .describe( - 'Alert ID. Omit to create a new alert, provide to update an existing one.', + 'Alert ID from clickstack_get_alert. Omit to create a new alert, ' + + 'provide to update an existing one.', ), // Source @@ -140,25 +147,46 @@ export const mcpSaveAlertSchema = z.object({ savedSearchId: z .string() .optional() - .describe('Saved search ID (required when source is saved_search).'), + .describe( + 'Saved search to monitor (required when source is saved_search). Get ' + + 'the ID from clickstack_get_saved_search.', + ), dashboardId: z .string() .optional() - .describe('Dashboard ID (required when source is tile).'), + .describe( + 'Dashboard containing the tile to monitor (required when source is ' + + 'tile). Get the ID from clickstack_get_dashboard.', + ), tileId: z .string() .optional() .describe( - 'Tile ID within the dashboard (required when source is tile). Must be a line, stacked bar, or number tile.', + 'Tile to monitor within the dashboard (required when source is tile). ' + + 'Get the ID from clickstack_get_dashboard with the dashboard ID. Must ' + + 'be a line, stacked line, stacked bar, or number tile.', ), groupBy: z .string() .optional() - .describe('Group-by key for saved search alerts.'), + .describe( + 'Saved search alerts only (ignored for other sources): a column or ' + + 'expression, e.g. ServiceName, that splits the matching-event count ' + + 'into one series per value. Each group is checked against the ' + + 'threshold and tracked separately. Tile and inline alerts group via ' + + 'their chart config instead.', + ), chartConfig: mcpAlertChartConfigSchema.optional(), // Threshold - threshold: z.number().describe('Threshold value for triggering the alert.'), + threshold: z + .number() + .describe( + 'Value the alert metric is compared against each interval window. For ' + + 'saved_search alerts the metric is the number of matching events in ' + + 'the window; for tile and inline alerts it is the chart value. Lower ' + + 'bound for between/not_between.', + ), thresholdType: z .enum([ 'above', @@ -170,18 +198,30 @@ export const mcpSaveAlertSchema = z.object({ 'between', 'not_between', ]) - .describe('How the metric value is compared against the threshold.'), + .describe( + 'Comparison that fires the alert: above is value >= threshold, ' + + 'above_exclusive is >, below is <, below_or_equal is <=, equal is ===, ' + + 'not_equal is !== (exact match, so avoid them for averaged or rate ' + + 'values). between ' + + 'fires when threshold <= value <= thresholdMax; not_between fires ' + + 'outside that range.', + ), thresholdMax: z .number() .optional() .describe( - 'Upper bound (required when thresholdType is between or not_between, must be >= threshold).', + 'Upper bound of the range for between/not_between (required for ' + + 'those, must be >= threshold). Ignored and cleared for other ' + + 'threshold types.', ), // Schedule interval: z .enum(['1m', '5m', '15m', '30m', '1h', '6h', '12h', '1d']) - .describe('Evaluation interval.'), + .describe( + 'How often the alert is evaluated; also the size of each evaluated ' + + 'time window.', + ), scheduleOffsetMinutes: z .number() .int() @@ -189,14 +229,20 @@ export const mcpSaveAlertSchema = z.object({ .max(1439) .optional() .describe( - 'Offset from the interval boundary in minutes (must be < interval).', + 'Shifts each evaluation window this many minutes past the interval ' + + 'boundary. Must be less than the interval. Ignored when ' + + 'scheduleStartAt is set.', ), scheduleStartAt: z .string() .datetime() .nullable() .optional() - .describe('Absolute UTC anchor for window alignment (ISO 8601).'), + .describe( + 'UTC timestamp that evaluation windows are aligned to; when set, ' + + 'scheduleOffsetMinutes is ignored. On update, omit to keep the ' + + 'stored value or send null to clear it.', + ), // Channel channel: mcpAlertChannelSchema.optional(), @@ -206,7 +252,9 @@ export const mcpSaveAlertSchema = z.object({ .max(MAX_ALERT_CHANNELS) .optional() .describe( - `Notification channels (1-${MAX_ALERT_CHANNELS}). Provide this or "channel"; if both, "channel" must match the first entry.`, + 'Webhooks notified when the alert fires or resolves. Provide this or ' + + '"channel"; if both, "channel" must match the first entry. Entries ' + + 'must be unique.', ), // Metadata @@ -215,13 +263,16 @@ export const mcpSaveAlertSchema = z.object({ .min(1) .max(512) .optional() - .describe('Alert title template (supports Handlebars syntax).'), + .describe( + 'Handlebars template for the notification title. When omitted, a ' + + 'default title based on the display name is used.', + ), message: z .string() .min(1) .max(4096) .optional() - .describe('Alert message template (supports Handlebars syntax).'), + .describe('Handlebars template for the notification body.'), displayName: alertDisplayNameSchema.describe( 'Display name shown for the alert in the UI. Defaults to the saved search name, dashboard tile name, or inline chartConfig name when omitted. Overridden by the "name" field in alert notifications when provided.', ), diff --git a/packages/api/src/mcp/tools/dashboards/deleteDashboard.ts b/packages/api/src/mcp/tools/dashboards/deleteDashboard.ts index d7d7be4ac6..54499e0701 100644 --- a/packages/api/src/mcp/tools/dashboards/deleteDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/deleteDashboard.ts @@ -22,7 +22,10 @@ export function registerDeleteDashboard({ 'Permanently delete a dashboard by ID. Also removes any alerts attached to its tiles. ' + 'Use clickstack_get_dashboard (without an ID) to list available dashboard IDs.', inputSchema: z.object({ - id: objectIdSchema.describe('Dashboard ID to delete.'), + id: objectIdSchema.describe( + 'ID of the dashboard to delete, from clickstack_get_dashboard (no id ' + + 'lists dashboards) or clickstack_search_dashboards.', + ), }), }, async ({ id: dashboardId }) => { diff --git a/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts b/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts index db72ab89df..6493406349 100644 --- a/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts +++ b/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts @@ -20,10 +20,16 @@ export function registerGetDashboardTile({ description: 'Retrieve a single tile from a dashboard by tileId. ' + 'Useful for inspecting one tile without loading the full dashboard. ' + + 'Returns the tile as JSON in the same shape clickstack_get_dashboard uses ' + + 'for tiles: id, name, x, y, w, h, containerId/tabId when set, and config. ' + + 'An unknown tileId returns an error listing the available tile IDs and names. ' + 'Use clickstack_get_dashboard (without an ID) to list dashboards, ' + 'then clickstack_get_dashboard (with an ID) to see all tile IDs.', inputSchema: z.object({ - dashboardId: objectIdSchema.describe('Dashboard ID.'), + dashboardId: objectIdSchema.describe( + 'Dashboard ID, from clickstack_get_dashboard (no id lists dashboards) ' + + 'or clickstack_search_dashboards.', + ), tileId: z .string() .describe( diff --git a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts index 171d203512..05689c80af 100644 --- a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts @@ -38,6 +38,10 @@ export function registerPatchDashboard({ 'Make targeted updates to a dashboard without resubmitting the full object. ' + 'You can update dashboard-level fields (name, tags) 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, ' + + 'stacked_line, stacked_bar, or number tile), alerts attached to that ' + + 'tile are permanently deleted. ' + 'Use clickstack_get_dashboard_tile to inspect a tile before patching it. ' + 'IMPORTANT: After patching a tile, run clickstack_query_tile to confirm the query still works.', inputSchema: mcpPatchDashboardSchema, diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index dcb852094c..77024d98fb 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -28,9 +28,17 @@ export function registerQueryTile({ 'Execute the query for a specific tile on an existing dashboard. ' + 'Useful for validating that a tile returns data or for spot-checking results ' + 'without rebuilding the query from scratch. ' + + 'Returns JSON with `result` (the query output rows), plus `note` when the ' + + 'result was trimmed for size, `hints` when no data matched, and `warnings` ' + + 'for missing raw SQL macros or dashboard-variable reference problems. Event-pattern tiles ' + + 'return pattern-mining output like clickstack_event_patterns; markdown tiles ' + + 'return a plain "no query" message. Query failures come back as tool errors. ' + 'Use clickstack_get_dashboard with an ID to find tile IDs.', inputSchema: z.object({ - dashboardId: objectIdSchema.describe('Dashboard ID.'), + dashboardId: objectIdSchema.describe( + 'Dashboard ID, from clickstack_get_dashboard (no id lists dashboards) ' + + 'or clickstack_search_dashboards.', + ), tileId: z .string() .describe( diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index d4b9e3dc48..35b71c66f5 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -182,15 +182,17 @@ export function registerQueryTiles({ 'unrunTileIds — call again with those as tileIds to run the remainder. ' + 'Drill into a specific failing tile with clickstack_query_tile.', inputSchema: z.object({ - dashboardId: objectIdSchema.describe('Dashboard ID.'), + dashboardId: objectIdSchema.describe( + 'Dashboard ID, from clickstack_get_dashboard (no id lists dashboards) ' + + 'or clickstack_search_dashboards.', + ), tileIds: z .array(z.string()) .max(MAX_TILE_IDS_INPUT) .optional() .describe( - 'Tile IDs to run. Default: every non-markdown tile on the ' + - 'dashboard. Obtain IDs from clickstack_get_dashboard. ' + - `At most ${MAX_TILE_IDS_INPUT} IDs per call.`, + 'Tile IDs to run, from clickstack_get_dashboard. When omitted, every ' + + 'non-markdown tile on the dashboard runs; an empty array runs none.', ), startTime: z .string() diff --git a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts index 6ca8a6cee3..f757ac576a 100644 --- a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts @@ -19,12 +19,7 @@ import { validateDashboardTiles, } from '@/routers/external-api/v2/utils/dashboards'; import type { ExternalDashboardTileWithId } from '@/utils/zod'; -import { - MAX_TAG_LENGTH, - MAX_TAGS, - objectIdSchema, - tagsSchema, -} from '@/utils/zod'; +import { objectIdSchema, tagsSchema } from '@/utils/zod'; import type { McpDashboardFilter } from './schemas'; import { mcpContainersParam, mcpFiltersParam, mcpTilesParam } from './schemas'; @@ -65,7 +60,7 @@ export function registerSaveDashboard({ name: z.string().describe('Dashboard name'), tiles: mcpTilesParam, tags: tagsSchema.describe( - `Dashboard tags. Up to ${MAX_TAGS} tags, each at most ${MAX_TAG_LENGTH} characters.`, + 'Labels for organizing the dashboard; clickstack_search_dashboards can filter by them.', ), containers: mcpContainersParam.optional(), filters: mcpFiltersParam.optional(), diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index afacdf390f..9701313801 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -8,7 +8,6 @@ import { ChartPaletteTokenSchema, DASHBOARD_CONTAINER_ID_MAX, DASHBOARD_MAX_CONTAINERS, - DASHBOARD_STATIC_FILTER_MAX_OPTIONS, DASHBOARD_VARIABLE_NAME_MAX_LENGTH, DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED, DashboardContainerSchema, @@ -25,12 +24,7 @@ import { mcpQuantileLevelSchema, } from '@/mcp/tools/query/schemas'; import { QUERYABLE_METRIC_KINDS } from '@/mcp/tools/sources/metricKinds'; -import { - MAX_TAG_LENGTH, - MAX_TAGS, - objectIdSchema, - tagsSchema, -} from '@/utils/zod'; +import { objectIdSchema, tagsSchema } from '@/utils/zod'; /** * Metric type values exposed on dashboard tile select items. Restricted to @@ -66,16 +60,19 @@ const rejectTileWhereMessage = 'item\'s `where` instead (that is the tile\'s visible "Where" box); use a ' + 'dashboard-level filter to scope the whole dashboard.'; -const rejectedTileWhereField = z - .never({ invalid_type_error: rejectTileWhereMessage }) - .optional() - .describe( - "Not supported on this tile type. Filter via each select item's `where`.", - ); - const rejectedTileWhereFields = { - where: rejectedTileWhereField, - whereLanguage: rejectedTileWhereField, + where: z + .never({ invalid_type_error: rejectTileWhereMessage }) + .optional() + .describe( + "Not supported on this tile type; any value is rejected. Put the filter on each select item's `where` instead.", + ), + whereLanguage: z + .never({ invalid_type_error: rejectTileWhereMessage }) + .optional() + .describe( + 'Not supported on this tile type; any value is rejected. Set `whereLanguage` on each select item instead.', + ), }; // A variable reference expands in either language; only the two variable @@ -105,42 +102,54 @@ const timeChartSeriesLimitDescription = 'Maximum number of series to fetch (the "Series Limit" display setting). ' + 'Keeps the top-N groups by aggregated value over the queried range and ' + 'drops the rest. Requires `groupBy`; ignored on a chart without one. ' + - 'Three-state: omit to apply the default render cap, 0 for unlimited, or a ' + - 'positive N to keep the top N.'; + 'Omit to apply the default render cap; 0 means unlimited.'; + +const timeChartFillNullsDescription = + 'Fill time buckets that have no data with zero (the "Fill Missing ' + + 'Intervals with Zero" display setting). false leaves gaps instead.'; + +const timeChartAlignDateRangeDescription = + 'The "Show Complete Intervals" display setting. When omitted or true, the ' + + 'dashboard widens the queried range to whole granularity buckets so the ' + + 'first and last buckets are complete; false queries the exact selected range.'; + +const whereLanguageDescription = (owner: 'tile' | 'item') => + `Query language of this ${owner}'s \`where\`. Use sql for the $__filter / ` + + '$__conditionalAll variable macros.'; + +const tileWhereLanguageDescription = whereLanguageDescription('tile'); + +const asRatioDescription = + 'Return select[0] divided by select[1] as a single ratio series instead of ' + + 'the two operands. Requires exactly two select items; cannot be combined ' + + 'with formulas.'; const seriesLimitSchema = z.number().int().nonnegative().optional(); const numberTileColorDescription = - 'Static color for the displayed number, as a palette token such as ' + - '"chart-blue", "chart-green", or "chart-success" (see the enum for the ' + - 'full set). Applied unless a colorRules entry matches the value.'; + 'Static palette color for the displayed number. Applied unless a ' + + 'colorRules entry matches the value.'; const numberTileColorRulesDescription = 'Conditional colors for the number, evaluated in array order with the ' + 'last matching rule winning; falls back to color (then the default text ' + - 'color) when none match. Up to 10 rules. Each rule is ' + - '{ operator, value, color, label? }: operator gt | gte | lt | lte with a ' + - 'number value, between with a [min, max] value, or eq | neq with a number ' + - 'or string value. color is a palette token. Example: ' + + 'color) when none match. Rules compare the raw query value, before ' + + 'numberFormat is applied (a 0.5 shown as 50% matches value 0.5). Example: ' + '[{ operator: "gte", value: 500, color: "chart-error", label: "Critical" }].'; const rawSqlNumberTileColorDescription = - 'Static color for the displayed number, as a palette token such as ' + - '"chart-blue" or "chart-success". Valid only when displayType is ' + - '"number", ignored otherwise. Applied unless a colorRules entry matches ' + - 'the value.'; + `${numberTileColorDescription} Valid only when displayType is ` + + '"number", ignored otherwise.'; const rawSqlNumberTileColorRulesDescription = `${numberTileColorRulesDescription} Valid only when displayType is ` + '"number", ignored otherwise.'; const numberTileBackgroundChartDescription = - 'Optional background trend sparkline drawn behind the number, derived ' + + 'Background trend sparkline drawn behind the number, derived ' + 'from a time-bucketed version of the same query (useful for SLO / ' + 'error-budget tiles where the trend over the window matters). ' + - '{ type, color? }: type is "line" or "area"; color is an optional ' + - 'palette token override (the sparkline inherits the tile color when ' + - 'unset). Builder number tiles only; raw SQL number tiles have no time ' + + 'Builder number tiles only; raw SQL number tiles have no time ' + 'dimension to bucket. Example: { type: "area", color: "chart-blue" }.'; const mcpNumberFormatSchema = z.object({ @@ -156,26 +165,26 @@ const mcpNumberFormatSchema = z.object({ 'throughput', ]) .describe( - 'Format category. "duration" auto-formats elapsed times as e.g. "1.2s" (use factor for input unit). ' + + 'How to render the value. "duration" auto-formats elapsed times as e.g. "1.2s" (use factor for input unit). ' + '"time" formats clock-style durations. "byte" formats as KB/MB/GB. ' + '"data_rate" formats as bytes/sec. "throughput" formats as count/sec. ' + - '"currency" prepends a symbol. "percent" appends %, and divides the value by 100 (0.5 becomes 50%).', + '"currency" prepends a symbol. "percent" multiplies the value by 100 and appends % (0.5 becomes 50%).', ), mantissa: z .number() .int() .optional() .describe( - 'Decimal places (0–10). Not used for "time" or "duration" output.', + 'Number of decimal places, 0 to 10. Not used for "time" or "duration" output.', ), thousandSeparated: z .boolean() .optional() - .describe('Separate thousands (e.g. 1,234,567)'), + .describe('Insert thousands separators, e.g. 1,234,567.'), average: z .boolean() .optional() - .describe('Abbreviate large numbers (e.g. 1.2m)'), + .describe('Abbreviate large numbers, e.g. 1.2m.'), decimalBytes: z .boolean() .optional() @@ -247,8 +256,9 @@ const mcpTileSelectItemSchema = z 'Lucene syntax by default. Example: "level:error"\n\n' + variableMacroDescription, ), - whereLanguage: - SearchConditionTrimmedLanguageSchema.optional().default('lucene'), + whereLanguage: SearchConditionTrimmedLanguageSchema.optional() + .default('lucene') + .describe(whereLanguageDescription('item')), alias: z .string() .optional() @@ -286,7 +296,7 @@ const mcpTileSelectItemSchema = z .optional() .describe( 'METRIC SOURCES ONLY (gauge metrics). When true, computes the Prometheus-style ' + - 'delta over each bucket. Default false.', + 'delta over each bucket instead of the raw gauge value.', ), // The REST v2 dialect's spelling of the same flag. Accepted so a select // item read back from the external API (or clickstack_get_alert / @@ -391,7 +401,7 @@ const mcpShowOperandSeriesSchema = z .describe( 'Only meaningful with `formulas`: when false, only the formula series ' + 'are returned and the raw operand series (the select items) are hidden. ' + - 'Defaults to true (operands shown alongside the formula).', + 'When omitted, operands are shown alongside the formula.', ); // ─── OnClick (link-out) schemas for table tiles ────────────────────────────── @@ -399,7 +409,9 @@ const mcpOnClickFilterTemplateSchema = z .object({ kind: z .literal('expressionTemplate') - .describe('Literal "expressionTemplate"; only kind supported today.'), + .describe( + 'Filter kind: an expression matched against a value rendered from the clicked row.', + ), expression: z .string() .min(1) @@ -430,14 +442,16 @@ const mcpOnClickTargetSchema = z .discriminatedUnion('mode', [ z .object({ - mode: z.literal('id'), + mode: z + .literal('id') + .describe('Resolve the destination from a fixed ID.'), id: z .string() .min(1) .describe( 'Concrete source ID (for type=search) or dashboard ID (for type=dashboard). ' + 'Get source IDs from clickstack_list_sources; get dashboard IDs from ' + - 'clickstack_get_dashboard (no id arg returns the list). ' + + 'clickstack_get_dashboard (no id arg returns the list) or clickstack_search_dashboards. ' + 'For type=search the source kind must be "log" or "trace"; the /search ' + 'page does not render metric/session sources.', ), @@ -445,7 +459,11 @@ const mcpOnClickTargetSchema = z .describe('Link to a specific source or dashboard by its concrete ID.'), z .object({ - mode: z.literal('template'), + mode: z + .literal('template') + .describe( + 'Resolve the destination by name, rendered from the clicked row.', + ), template: z .string() .min(1) @@ -464,7 +482,7 @@ const mcpOnClickTargetSchema = z ]) .describe( 'Destination resolver. mode="id" pins a specific source/dashboard; ' + - 'mode="template" picks one at click time from a row column.' + + 'mode="template" picks one at click time from a row column. ' + "Linking by ID is preferred, but using a template is valid when the destination dashboard depends on the clicked row's content", ); @@ -479,23 +497,22 @@ const mcpOnClickSearchSchema = z .max(10000) .optional() .describe( - 'Optional Handlebars-style WHERE template rendered against the clicked row ' + + 'Handlebars-style WHERE template rendered against the clicked row ' + "and placed in the destination's `where` query param. " + 'Example: "ServiceName = \'{{service.name}}\'" pulls service.name from the row. ' + 'Use Lucene or SQL syntax matching `whereLanguage`. Prefer `filters` (below) ' + 'for simple equality; filters merge nicely on the destination.', ), whereLanguage: SearchConditionTrimmedLanguageSchema.describe( - 'Filter language for `whereTemplate` and `filters` ("lucene" or "sql"). ' + - 'Optional, but set it explicitly so the destination knows how to parse rendered ' + - 'whereTemplate / filter values.', + 'Query language of `whereTemplate` and `filters`. Set it explicitly so the ' + + 'destination knows how to parse the rendered values.', ), filters: z .array(mcpOnClickFilterTemplateSchema) .max(50) .optional() .describe( - 'Optional list of templated equality filters. Each filter becomes an ' + + 'Templated equality filters. Each filter becomes an ' + "`expression IN ('rendered-value')` clause on the destination; filters that " + 'share an expression are merged into one IN clause.', ), @@ -516,21 +533,20 @@ const mcpOnClickDashboardSchema = z .max(10000) .optional() .describe( - 'Optional Handlebars-style WHERE template applied to the destination ' + + 'Handlebars-style WHERE template rendered against the clicked row and applied to the destination ' + "dashboard's global filter. Useful when the target dashboard exposes a single " + 'global scope rather than per-tile filters.', ), whereLanguage: SearchConditionTrimmedLanguageSchema.describe( - 'Filter language for `whereTemplate` and `filters` ("lucene" or "sql"). ' + - 'Optional, but set it explicitly so the destination knows how to parse rendered ' + - 'whereTemplate / filter values.', + 'Query language of `whereTemplate` and `filters`. Set it explicitly so the ' + + 'destination knows how to parse the rendered values.', ), filters: z .array(mcpOnClickFilterTemplateSchema) .max(50) .optional() .describe( - 'Optional list of templated equality filters. The destination dashboard ' + + 'Templated equality filters. The destination dashboard ' + 'auto-populates its filter list with these (matched by expression), so prefer ' + 'this over whereTemplate when the target dashboard already declares the same ' + 'filter expressions. ' + @@ -599,6 +615,37 @@ const mcpOnClickSchema = z '"https://grafana.example.com/d/abc?var-service={{ServiceName}}" }', ); +const mcpTimeChartDisplayFields = { + fillNulls: z + .boolean() + .optional() + .default(true) + .describe(timeChartFillNullsDescription), + alignDateRangeToGranularity: z + .boolean() + .optional() + .describe(timeChartAlignDateRangeDescription), + asRatio: z.boolean().optional().describe(asRatioDescription), + numberFormat: mcpNumberFormatSchema + .optional() + .describe(tileLevelNumberFormatDescription), +}; + +const mcpRowListSourceFields = { + sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + where: z + .string() + .optional() + .default('') + .describe( + 'Row filter, in the language set by whereLanguage (Lucene by default). Example: "level:error"\n\n' + + variableMacroDescription, + ), + whereLanguage: SearchConditionTrimmedLanguageSchema.optional() + .default('lucene') + .describe(tileWhereLanguageDescription), +}; + const mcpTileLayoutSchema = z.object({ name: z.string().min(1).describe('Tile title shown on the dashboard'), x: z @@ -607,13 +654,13 @@ const mcpTileLayoutSchema = z.object({ .max(23) .optional() .default(0) - .describe('Horizontal grid position (0–23). Default 0'), + .describe("Grid column of the tile's left edge, counted from the left."), y: z .number() .min(0) .optional() .default(0) - .describe('Vertical grid position. Default 0'), + .describe("Grid row of the tile's top edge, counted from the top."), w: z .number() .min(1) @@ -621,7 +668,7 @@ const mcpTileLayoutSchema = z.object({ .optional() .default(12) .describe( - 'Width in grid columns (1-24; a full row is 24). Default 12. ' + + 'Width in grid columns; a full row is 24. ' + 'Match the width to the displayType: number 6-8 (three or four KPIs per row), ' + 'line / stacked_bar / pie 8-12, heatmap 12, table / search 12-24 (often the full row). ' + 'A markdown note is usually full-width (24).', @@ -632,7 +679,7 @@ const mcpTileLayoutSchema = z.object({ .optional() .default(4) .describe( - 'Height in grid rows. Default 4. ' + + 'Height in grid rows. ' + 'Match the height to the displayType so content is not clipped: number 3-4, ' + 'line / stacked_bar / pie 4-6, heatmap 5-6, table / search 6-10 (taller when more rows are expected), ' + 'markdown 2-3 for a short note (h: 1 clips the text).', @@ -641,7 +688,11 @@ const mcpTileLayoutSchema = z.object({ .string() .max(36) .optional() - .describe('Tile ID (auto-generated if omitted)'), + .describe( + 'Tile ID, generated when omitted. When updating a dashboard, keep each ' + + "existing tile's ID from clickstack_get_dashboard: a tile whose ID " + + 'disappears is treated as removed and its alerts are deleted.', + ), containerId: z .string() .min(1) @@ -665,253 +716,274 @@ const mcpTileLayoutSchema = z.object({ }); export const mcpLineTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - ...rejectedTileWhereFields, - displayType: z.literal('line').describe('Line chart over time'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - select: z - .array(mcpTileSelectItemSchema) - .min(1) - .max(20) - .describe('Metrics to plot (one series per item)'), - groupBy: z - .string() - .optional() - .describe( - 'Column to split/group by. ' + - 'Top-level columns use PascalCase (e.g. "SpanName", "StatusCode"). ' + - "Span attributes: SpanAttributes['key'] (e.g. SpanAttributes['http.method']). " + - "Resource attributes: ResourceAttributes['key'] (e.g. ResourceAttributes['service.name']).", - ), - fillNulls: z.boolean().optional().default(true), - alignDateRangeToGranularity: z.boolean().optional(), - asRatio: z - .boolean() - .optional() - .describe( - 'Plot as ratio of two metrics (requires exactly 2 select items)', - ), - numberFormat: mcpNumberFormatSchema - .optional() - .describe(tileLevelNumberFormatDescription), - compareToPreviousPeriod: z - .boolean() - .optional() - .describe('Overlay the previous period as a dashed comparison series.'), - fitYAxisToData: z - .boolean() - .optional() - .describe( - 'Scale the y-axis to the data range instead of starting at zero.', - ), - seriesLimit: seriesLimitSchema.describe(timeChartSeriesLimitDescription), - formulas: mcpTileFormulasSchema, - showOperandSeries: mcpShowOperandSeriesSchema, - }), + config: z + .object({ + ...rejectedTileWhereFields, + displayType: z.literal('line').describe('Line chart over time'), + sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + select: z + .array(mcpTileSelectItemSchema) + .min(1) + .max(20) + .describe('Metrics to plot (one series per item)'), + groupBy: z + .string() + .optional() + .describe( + 'Column to split/group by. ' + + 'Top-level columns use PascalCase (e.g. "SpanName", "StatusCode"). ' + + "Span attributes: SpanAttributes['key'] (e.g. SpanAttributes['http.method']). " + + "Resource attributes: ResourceAttributes['key'] (e.g. ResourceAttributes['service.name']).", + ), + ...mcpTimeChartDisplayFields, + compareToPreviousPeriod: z + .boolean() + .optional() + .describe('Overlay the previous period as a dashed comparison series.'), + fitYAxisToData: z + .boolean() + .optional() + .describe( + 'Scale the y-axis to the data range instead of starting at zero.', + ), + seriesLimit: seriesLimitSchema.describe(timeChartSeriesLimitDescription), + formulas: mcpTileFormulasSchema, + showOperandSeries: mcpShowOperandSeriesSchema, + }) + .describe('Line chart query and display settings.'), }); const mcpStackedTimeChartConfigFields = { sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - select: z.array(mcpTileSelectItemSchema).min(1).max(20), - groupBy: z.string().optional(), - fillNulls: z.boolean().optional().default(true), - alignDateRangeToGranularity: z.boolean().optional(), - asRatio: z.boolean().optional(), - numberFormat: mcpNumberFormatSchema + select: z + .array(mcpTileSelectItemSchema) + .min(1) + .max(20) + .describe('Metrics to plot (one series per item; series are stacked).'), + groupBy: z + .string() .optional() - .describe(tileLevelNumberFormatDescription), + .describe( + 'Column to split/group by; each group value becomes a stacked series. ' + + 'Top-level columns use PascalCase (e.g. "SpanName"). ' + + "For attributes: SpanAttributes['key'] or ResourceAttributes['key'].", + ), + ...mcpTimeChartDisplayFields, seriesLimit: seriesLimitSchema.describe(timeChartSeriesLimitDescription), formulas: mcpTileFormulasSchema, showOperandSeries: mcpShowOperandSeriesSchema, }; export const mcpBarTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - ...rejectedTileWhereFields, - displayType: z - .literal('stacked_bar') - .describe('Stacked bar chart over time'), - ...mcpStackedTimeChartConfigFields, - }), + config: z + .object({ + ...rejectedTileWhereFields, + displayType: z + .literal('stacked_bar') + .describe('Stacked bar chart over time'), + ...mcpStackedTimeChartConfigFields, + }) + .describe('Stacked bar chart query and display settings.'), }); export const mcpStackedLineTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - ...rejectedTileWhereFields, - displayType: z - .literal('stacked_line') - .describe('Stacked line (area) chart over time'), - ...mcpStackedTimeChartConfigFields, - }), + config: z + .object({ + ...rejectedTileWhereFields, + displayType: z + .literal('stacked_line') + .describe('Stacked line (area) chart over time'), + ...mcpStackedTimeChartConfigFields, + }) + .describe('Stacked line chart query and display settings.'), }); const mcpTableTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - ...rejectedTileWhereFields, - displayType: z.literal('table').describe('Tabular aggregated data'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - select: z.array(mcpTileSelectItemSchema).min(1).max(20), - groupBy: z - .string() - .optional() - .describe( - 'Group rows by this column. Use PascalCase for top-level columns (e.g. "SpanName"). ' + - "For attributes: SpanAttributes['key'] or ResourceAttributes['key'].", - ), - having: z - .string() - .max(10000) - .optional() - .describe( - 'Post-aggregation SQL HAVING expression. Example: "Count > 100" to drop ' + - 'groups with few rows, or "StatusMessage != \'\'" to drop empty-message rows ' + - 'from a groupBy: "StatusMessage" table. Mirrors the same field on the REST ' + - 'table chart config in `externalDashboardTableChartConfigSchema`.\n\n' + - sqlOnlyVariableMacroDescription, - ), - orderBy: z - .string() - .optional() - .describe( - 'Sort results by this column. ' + - 'When ordering by an alias that contains spaces or special characters, ' + - `wrap the alias in quotes: e.g. '"P95 Latency" DESC'.`, - ), - asRatio: z.boolean().optional(), - groupByColumnsOnLeft: z - .boolean() - .optional() - .describe( - 'Render Group By columns on the left side of the table, before the series columns. ' + - 'Default false (Group By columns on the right).', - ), - numberFormat: mcpNumberFormatSchema - .optional() - .describe(tileLevelNumberFormatDescription), - onClick: mcpOnClickSchema.optional(), - formulas: mcpTileFormulasSchema, - showOperandSeries: mcpShowOperandSeriesSchema, - }), + config: z + .object({ + ...rejectedTileWhereFields, + displayType: z.literal('table').describe('Tabular aggregated data'), + sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + select: z + .array(mcpTileSelectItemSchema) + .min(1) + .max(20) + .describe('Aggregations to compute (one column per item).'), + groupBy: z + .string() + .optional() + .describe( + 'Group rows by this column. Use PascalCase for top-level columns (e.g. "SpanName"). ' + + "For attributes: SpanAttributes['key'] or ResourceAttributes['key'].", + ), + having: z + .string() + .max(10000) + .optional() + .describe( + 'Post-aggregation SQL HAVING expression. Example: "Count > 100" to drop ' + + 'groups with few rows, or "StatusMessage != \'\'" to drop empty-message rows ' + + 'from a groupBy: "StatusMessage" table.\n\n' + + sqlOnlyVariableMacroDescription, + ), + orderBy: z + .string() + .optional() + .describe( + 'Sort results by this column. ' + + 'When ordering by an alias that contains spaces or special characters, ' + + `wrap the alias in quotes: e.g. '"P95 Latency" DESC'.`, + ), + asRatio: z.boolean().optional().describe(asRatioDescription), + groupByColumnsOnLeft: z + .boolean() + .optional() + .describe( + 'Render Group By columns on the left side of the table, before the series columns. ' + + 'When omitted or false, they render on the right.', + ), + numberFormat: mcpNumberFormatSchema + .optional() + .describe(tileLevelNumberFormatDescription), + onClick: mcpOnClickSchema.optional(), + formulas: mcpTileFormulasSchema, + showOperandSeries: mcpShowOperandSeriesSchema, + }) + .describe('Table query and display settings.'), }); export const mcpNumberTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - ...rejectedTileWhereFields, - displayType: z.literal('number').describe('Single aggregate scalar value'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - select: z - .array(mcpTileSelectItemSchema) - .min(1) - .max(20) - .describe( - 'Exactly one metric to display — unless `formulas` is set, in which ' + - 'case the select items are the formula operands and the (single) ' + - 'formula value is displayed instead.', + config: z + .object({ + ...rejectedTileWhereFields, + displayType: z + .literal('number') + .describe('Single aggregate scalar value'), + sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + select: z + .array(mcpTileSelectItemSchema) + .min(1) + .max(20) + .describe( + 'Exactly one metric to display — unless `formulas` is set, in which ' + + 'case the select items are the formula operands and the (single) ' + + 'formula value is displayed instead.', + ), + numberFormat: mcpNumberFormatSchema + .optional() + .describe(tileLevelNumberFormatDescription), + formulas: z + .array(mcpFormulaSchema) + .max(1) + .optional() + .describe( + `${tileFormulasDescription} Number tiles support a single formula ` + + 'and always display the formula value (operand series are hidden).', + ), + color: ChartPaletteTokenSchema.optional().describe( + numberTileColorDescription, ), - numberFormat: mcpNumberFormatSchema - .optional() - .describe(tileLevelNumberFormatDescription), - formulas: z - .array(mcpFormulaSchema) - .max(1) - .optional() - .describe( - `${tileFormulasDescription} Number tiles support a single formula ` + - 'and always display the formula value (operand series are hidden).', + colorRules: z + .array(NumberTileColorConditionSchema) + .max(10) + .optional() + .describe(numberTileColorRulesDescription), + backgroundChart: BackgroundChartSchema.optional().describe( + numberTileBackgroundChartDescription, ), - color: ChartPaletteTokenSchema.optional().describe( - numberTileColorDescription, - ), - colorRules: z - .array(NumberTileColorConditionSchema) - .max(10) - .optional() - .describe(numberTileColorRulesDescription), - backgroundChart: BackgroundChartSchema.optional().describe( - numberTileBackgroundChartDescription, - ), - }), + }) + .describe('Number tile query and display settings.'), }); const mcpPieTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - ...rejectedTileWhereFields, - displayType: z.literal('pie').describe('Pie chart'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - select: z.array(mcpTileSelectItemSchema).length(1), - groupBy: z - .string() - .optional() - .describe( - 'Column that defines pie slices. Use PascalCase for top-level columns. ' + - "For attributes: SpanAttributes['key'] or ResourceAttributes['key'].", - ), - orderBy: z - .string() - .optional() - .describe( - 'Optional custom SQL ORDER BY expression. Overrides the default ' + - 'value-descending ordering and, combined with `limit`, controls which ' + - 'slices are kept. When ordering by an alias that contains spaces or ' + - `special characters, wrap the alias in quotes: e.g. '"P95 Latency" DESC'.`, - ), - numberFormat: mcpNumberFormatSchema - .optional() - .describe(tileLevelNumberFormatDescription), - limit: z - .number() - .int() - .nonnegative() - .optional() - .describe( - 'Maximum number of slices (SQL LIMIT). Without a custom `orderBy`, keeps ' + - 'the top-N groups by the aggregated value, descending; with an `orderBy` ' + - 'keeps the first N in that order. Omit or set 0 to fetch all groups.', - ), - }), + config: z + .object({ + ...rejectedTileWhereFields, + displayType: z.literal('pie').describe('Pie chart'), + sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + select: z + .array(mcpTileSelectItemSchema) + .length(1) + .describe('The aggregation that sizes each slice.'), + groupBy: z + .string() + .optional() + .describe( + 'Column that defines pie slices. Use PascalCase for top-level columns. ' + + "For attributes: SpanAttributes['key'] or ResourceAttributes['key'].", + ), + orderBy: z + .string() + .optional() + .describe( + 'Optional custom SQL ORDER BY expression. Overrides the default ' + + 'value-descending ordering and, combined with `limit`, controls which ' + + 'slices are kept. When ordering by an alias that contains spaces or ' + + `special characters, wrap the alias in quotes: e.g. '"P95 Latency" DESC'.`, + ), + numberFormat: mcpNumberFormatSchema + .optional() + .describe(tileLevelNumberFormatDescription), + limit: z + .number() + .int() + .nonnegative() + .optional() + .describe( + 'Maximum number of slices (SQL LIMIT). Without a custom `orderBy`, keeps ' + + 'the top-N groups by the aggregated value, descending; with an `orderBy` ' + + 'keeps the first N in that order. Omit or set 0 to fetch all groups.', + ), + }) + .describe('Pie chart query and display settings.'), }); // Categorical bar charts ('bar') behave exactly like pie charts: one // aggregated select item, optional groupBy, no time bucketing. Distinct // from 'stacked_bar', which is a time series. const mcpCategoricalBarTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - ...rejectedTileWhereFields, - displayType: z - .literal('bar') - .describe('Bar chart — one bar per group value (not a time series)'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - select: z.array(mcpTileSelectItemSchema).length(1), - groupBy: z - .string() - .optional() - .describe( - 'Column(s) that define the bars. Use PascalCase for top-level columns. ' + - "For attributes: SpanAttributes['key'] or ResourceAttributes['key'].", - ), - orderBy: z - .string() - .optional() - .describe( - 'Optional custom SQL ORDER BY expression. Overrides the default ' + - 'value-descending ordering and, combined with `limit`, controls which ' + - 'bars are kept. When ordering by an alias that contains spaces or ' + - `special characters, wrap the alias in quotes: e.g. '"P95 Latency" DESC'.`, - ), - numberFormat: mcpNumberFormatSchema - .optional() - .describe(tileLevelNumberFormatDescription), - limit: z - .number() - .int() - .nonnegative() - .optional() - .describe( - 'Maximum number of bars (SQL LIMIT). Without a custom `orderBy`, keeps ' + - 'the top-N groups by the aggregated value, descending; with an `orderBy` ' + - 'keeps the first N in that order. Omit or set 0 to fetch all groups.', - ), - }), + config: z + .object({ + ...rejectedTileWhereFields, + displayType: z + .literal('bar') + .describe('Bar chart — one bar per group value (not a time series)'), + sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + select: z + .array(mcpTileSelectItemSchema) + .length(1) + .describe('The aggregation that sets each bar height.'), + groupBy: z + .string() + .optional() + .describe( + 'Column(s) that define the bars. Use PascalCase for top-level columns. ' + + "For attributes: SpanAttributes['key'] or ResourceAttributes['key'].", + ), + orderBy: z + .string() + .optional() + .describe( + 'Optional custom SQL ORDER BY expression. Overrides the default ' + + 'value-descending ordering and, combined with `limit`, controls which ' + + 'bars are kept. When ordering by an alias that contains spaces or ' + + `special characters, wrap the alias in quotes: e.g. '"P95 Latency" DESC'.`, + ), + numberFormat: mcpNumberFormatSchema + .optional() + .describe(tileLevelNumberFormatDescription), + limit: z + .number() + .int() + .nonnegative() + .optional() + .describe( + 'Maximum number of bars (SQL LIMIT). Without a custom `orderBy`, keeps ' + + 'the top-N groups by the aggregated value, descending; with an `orderBy` ' + + 'keeps the first N in that order. Omit or set 0 to fetch all groups.', + ), + }) + .describe('Bar chart query and display settings.'), }); // Heatmap tiles use a dedicated select-item shape: heatmap aggregation is @@ -926,19 +998,19 @@ const mcpHeatmapSelectItemSchema = z.object({ .string() .min(1) .describe( - 'Numeric column or expression to bucket. Required and must be non-empty. ' + + 'Numeric column or expression to bucket. ' + 'Use "Duration" for trace latency heatmaps, or any other numeric column.', ), countExpression: z .string() .optional() .describe( - 'Custom count expression (e.g. "count()"). Optional; defaults are applied by the renderer.', + 'Custom count expression (e.g. "count()"). The renderer applies a default when omitted.', ), heatmapScaleType: z .enum(['log', 'linear']) .optional() - .describe('Color scale: "log" or "linear"'), + .describe('Scale of the y axis (the bucketed value).'), }); // Distribution heatmap tiles are builder-only and restricted to Trace sources @@ -946,175 +1018,179 @@ const mcpHeatmapSelectItemSchema = z.object({ // The save path runs `getHeatmapTilesWithIncompatibleSources` after schema // validation to enforce that, mirroring the REST handler. const mcpHeatmapTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - displayType: z - .literal('heatmap') - .describe( - 'Heatmap chart. Without `heatmapMode` it is a distribution heatmap, ' + - 'which buckets a numeric value on the y-axis and requires a Trace source', - ), - heatmapMode: z - .literal('distribution') - .optional() - .describe('Omit for a distribution heatmap'), - sourceId: z - .string() - .describe( - 'Source ID. Must be a Trace source today; use clickstack_list_sources and ' + - 'pick one whose kind is "trace".', - ), - select: z - .array(mcpHeatmapSelectItemSchema) - .length(1) - .describe('Exactly one heatmap series'), - where: z - .string() - .optional() - .default('') - .describe( - 'Row-level filter applied before bucketing. Example: "level:error"\n\n' + - variableMacroDescription, - ), - whereLanguage: - SearchConditionTrimmedLanguageSchema.optional().default('lucene'), - numberFormat: mcpNumberFormatSchema - .optional() - .describe( - 'Display formatting for bucket values. Example: { output: "duration", factor: 0.000000001 } ' + - 'to format nanosecond durations as human-readable time.', - ), - }), + config: z + .object({ + displayType: z + .literal('heatmap') + .describe( + 'Heatmap chart. Without `heatmapMode` it is a distribution heatmap, ' + + 'which buckets a numeric value on the y-axis and requires a Trace source', + ), + heatmapMode: z + .literal('distribution') + .optional() + .describe( + 'Distribution mode; may be omitted. For a series heatmap use heatmapMode "series" instead.', + ), + sourceId: z + .string() + .describe( + 'Source ID. Must be a Trace source today; use clickstack_list_sources and ' + + 'pick one whose kind is "trace".', + ), + select: z + .array(mcpHeatmapSelectItemSchema) + .length(1) + .describe('The value to bucket.'), + where: z + .string() + .optional() + .default('') + .describe( + 'Row-level filter applied before bucketing. Example: "level:error"\n\n' + + variableMacroDescription, + ), + whereLanguage: SearchConditionTrimmedLanguageSchema.optional() + .default('lucene') + .describe(tileWhereLanguageDescription), + numberFormat: mcpNumberFormatSchema + .optional() + .describe( + 'Display formatting for bucket values. Example: { output: "duration", factor: 0.000000001 } ' + + 'to format nanosecond durations as human-readable time.', + ), + }) + .describe('Distribution heatmap query and display settings.'), }); const mcpHeatmapSeriesTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - ...rejectedTileWhereFields, - displayType: z - .literal('heatmap') - .describe( - 'Series heatmap: one row per groupBy value, each cell colored by the ' + - 'aggregated value over time', - ), - heatmapMode: z - .literal('series') - .describe('Must be "series" for a series heatmap'), - sourceId: z - .string() - .describe( - 'Source ID of a Trace, Log, or Metric source - call clickstack_list_sources', - ), - select: z - .array(mcpTileSelectItemSchema) - .length(1) - .describe( - 'Defines the aggregate value displayed for each heatmap series.', - ), - groupBy: z - .string() - .optional() - .describe( - 'SQL GROUP BY expression defining the series shown in the heatmap.', - ), - numberFormat: mcpNumberFormatSchema - .optional() - .describe(tileLevelNumberFormatDescription), - }), + config: z + .object({ + ...rejectedTileWhereFields, + displayType: z + .literal('heatmap') + .describe( + 'Series heatmap: one row per groupBy value, each cell colored by the ' + + 'aggregated value over time', + ), + heatmapMode: z + .literal('series') + .describe( + 'Selects the series heatmap: one row per groupBy value over time.', + ), + sourceId: z + .string() + .describe( + 'Source ID of a Trace, Log, or Metric source - call clickstack_list_sources', + ), + select: z + .array(mcpTileSelectItemSchema) + .length(1) + .describe( + 'Defines the aggregate value displayed for each heatmap series.', + ), + groupBy: z + .string() + .optional() + .describe( + 'SQL GROUP BY expression defining the series shown in the heatmap.', + ), + numberFormat: mcpNumberFormatSchema + .optional() + .describe(tileLevelNumberFormatDescription), + }) + .describe('Series heatmap query and display settings.'), }); const mcpSearchTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - displayType: z.literal('search').describe('Log/event search results list'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - where: z - .string() - .optional() - .default('') - .describe( - 'Filter in Lucene syntax. Example: "level:error"\n\n' + - variableMacroDescription, - ), - whereLanguage: - SearchConditionTrimmedLanguageSchema.optional().default('lucene'), - select: z - .string() - .optional() - .default('') - .describe( - 'Columns to display (empty = defaults). Example: "body,service.name,duration"', - ), - }), + config: z + .object({ + displayType: z + .literal('search') + .describe('Log/event search results list'), + ...mcpRowListSourceFields, + select: z + .string() + .optional() + .default('') + .describe( + 'Columns to display (empty = defaults). Example: "body,service.name,duration"', + ), + }) + .describe('Search results list query settings.'), }); const mcpEventPatternsTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - displayType: z - .literal('event_patterns') - .describe('Event pattern mining tile'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - where: z - .string() - .optional() - .default('') - .describe( - 'Filter in Lucene syntax. Example: "level:error"\n\n' + - variableMacroDescription, - ), - whereLanguage: - SearchConditionTrimmedLanguageSchema.optional().default('lucene'), - select: z - .string() - .optional() - .default('') - .describe( - 'Pattern expression — column or expression to mine patterns from. ' + - 'Leave empty to use the source default (Body for logs, SpanName for traces). ' + - 'Example: "Body", "SpanName", "SpanAttributes[\'http.url\']"', - ), - }), + config: z + .object({ + displayType: z + .literal('event_patterns') + .describe('Event pattern mining tile'), + ...mcpRowListSourceFields, + select: z + .string() + .optional() + .default('') + .describe( + 'Pattern expression — column or expression to mine patterns from. ' + + 'Leave empty to use the source default (Body for logs, SpanName for traces). ' + + 'Example: "Body", "SpanName", "SpanAttributes[\'http.url\']"', + ), + }) + .describe('Event pattern mining query settings.'), }); const mcpMarkdownTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - displayType: z.literal('markdown').describe('Free-form Markdown text tile'), - markdown: z.string().optional().default(''), - }), + config: z + .object({ + displayType: z + .literal('markdown') + .describe('Free-form Markdown text tile'), + markdown: z + .string() + .optional() + .default('') + .describe('Markdown text rendered in the tile.'), + }) + .describe('Markdown tile content.'), }); export const mcpSqlTileSchema = mcpTileLayoutSchema.extend({ - config: z.object({ - configType: z - .literal('sql') - .describe( - 'Must be "sql" for raw SQL tiles. ' + - 'ADVANCED: Only use raw SQL tiles when the builder tile types cannot express the query you need.', - ), - displayType: z - .enum([ - 'line', - 'stacked_bar', - 'stacked_line', - 'table', - 'number', - 'pie', - 'bar', - ]) - .describe('How to render the SQL results'), - connectionId: z - .string() - .describe( - 'Connection ID (not sourceId) – call clickstack_list_sources to find available connections', - ), - sourceId: z - .string() - .optional() - .describe( - 'Source ID for the table this query reads from (call clickstack_list_sources). ' + - 'ALWAYS set this for raw SQL tiles UNLESS the query reads from multiple tables ' + - '(e.g. JOINs or sub-queries spanning several sources), in which case omit it. ' + - 'sourceId is REQUIRED by two macros: $__filters and $__sourceTable. ' + - 'The sourceId must belong to the same connection as connectionId.', - ), - sqlTemplate: z.string().describe(` + config: z + .object({ + configType: z + .literal('sql') + .describe( + 'Marks this as a raw SQL tile. ' + + 'ADVANCED: Only use raw SQL tiles when the builder tile types cannot express the query you need.', + ), + displayType: z + .enum([ + 'line', + 'stacked_bar', + 'stacked_line', + 'table', + 'number', + 'pie', + 'bar', + ]) + .describe('How to render the SQL results'), + connectionId: z + .string() + .describe( + 'Connection ID (not sourceId) – call clickstack_list_sources to find available connections', + ), + sourceId: z + .string() + .optional() + .describe( + 'Source ID for the table this query reads from (call clickstack_list_sources). ' + + 'ALWAYS set this for raw SQL tiles UNLESS the query reads from multiple tables ' + + '(e.g. JOINs or sub-queries spanning several sources), in which case omit it. ' + + 'sourceId is REQUIRED by two macros: $__filters and $__sourceTable. ' + + 'The sourceId must belong to the same connection as connectionId.', + ), + sqlTemplate: z.string().describe(` Raw ClickHouse SQL query. SQL guidelines: 1. ALWAYS include a LIMIT clause to avoid excessive data. @@ -1142,35 +1218,46 @@ WHERE $__timeFilter(TimestampTime) AND $__filters GROUP BY ServiceName, ts `), - fillNulls: z.boolean().optional(), - alignDateRangeToGranularity: z.boolean().optional(), - numberFormat: mcpNumberFormatSchema - .optional() - .describe(tileLevelNumberFormatDescription), - compareToPreviousPeriod: z - .boolean() - .optional() - .describe( - 'Overlay the previous period as a dashed comparison series. ' + - 'Valid only when displayType is "line", ignored otherwise.', + fillNulls: z + .boolean() + .optional() + .describe( + `${timeChartFillNullsDescription} Time-series display types only.`, + ), + alignDateRangeToGranularity: z + .boolean() + .optional() + .describe( + `${timeChartAlignDateRangeDescription} Time-series display types only.`, + ), + numberFormat: mcpNumberFormatSchema + .optional() + .describe(tileLevelNumberFormatDescription), + compareToPreviousPeriod: z + .boolean() + .optional() + .describe( + 'Overlay the previous period as a dashed comparison series. ' + + 'Valid only when displayType is "line", ignored otherwise.', + ), + fitYAxisToData: z + .boolean() + .optional() + .describe( + 'Scale the y-axis to the data range instead of starting at zero. ' + + 'Valid only when displayType is "line", ignored otherwise.', + ), + color: ChartPaletteTokenSchema.optional().describe( + rawSqlNumberTileColorDescription, ), - fitYAxisToData: z - .boolean() - .optional() - .describe( - 'Scale the y-axis to the data range instead of starting at zero. ' + - 'Valid only when displayType is "line", ignored otherwise.', - ), - color: ChartPaletteTokenSchema.optional().describe( - rawSqlNumberTileColorDescription, - ), - colorRules: z - .array(NumberTileColorConditionSchema) - .max(10) - .optional() - .describe(rawSqlNumberTileColorRulesDescription), - onClick: mcpOnClickSchema.optional(), - }), + colorRules: z + .array(NumberTileColorConditionSchema) + .max(10) + .optional() + .describe(rawSqlNumberTileColorRulesDescription), + onClick: mcpOnClickSchema.optional(), + }) + .describe('Raw SQL tile query and display settings.'), }); const mcpTileSchema = z.union([ @@ -1198,12 +1285,52 @@ const mcpPatchTileLayoutSchema = z.object({ .min(1) .optional() .describe('Tile title. Omit to keep the existing title.'), - x: z.number().min(0).max(23).optional(), - y: z.number().min(0).optional(), - w: z.number().min(1).max(24).optional(), - h: z.number().min(1).optional(), - containerId: z.string().min(1).max(DASHBOARD_CONTAINER_ID_MAX).optional(), - tabId: z.string().min(1).max(DASHBOARD_CONTAINER_ID_MAX).optional(), + x: z + .number() + .min(0) + .max(23) + .optional() + .describe( + "Grid column of the tile's left edge. Omit to keep the existing position.", + ), + y: z + .number() + .min(0) + .optional() + .describe( + "Grid row of the tile's top edge. Omit to keep the existing position.", + ), + w: z + .number() + .min(1) + .max(24) + .optional() + .describe( + 'Width in grid columns; a full row is 24. Omit to keep the existing width.', + ), + h: z + .number() + .min(1) + .optional() + .describe('Height in grid rows. Omit to keep the existing height.'), + containerId: z + .string() + .min(1) + .max(DASHBOARD_CONTAINER_ID_MAX) + .optional() + .describe( + "Container to place the tile in; must be the id of one of the dashboard's " + + 'containers. Omit to keep the tile in its current container.', + ), + tabId: z + .string() + .min(1) + .max(DASHBOARD_CONTAINER_ID_MAX) + .optional() + .describe( + "Tab to place the tile in; must be a tab id on the tile's container. " + + 'Omit to keep the current tab.', + ), }); // Build the patch tile union by extending the default-free layout with @@ -1265,9 +1392,7 @@ export const mcpTilesParam = z const VARIABLE_NAME_DESCRIPTION = "Token that tiles reference this filter's selected value by, eg. $variableName. " + - 'Must start with a letter and may contain only letters, numbers, and ' + - `underscores, up to ${DASHBOARD_VARIABLE_NAME_MAX_LENGTH} characters. ` + - 'A default is determined based on the display name. ' + + 'A default is derived from the display name when omitted. ' + "Must be unique across the dashboard's variable-enabled filters."; const variableNameSchema = z @@ -1309,8 +1434,8 @@ const mcpDashboardFilterBaseShape = { '"missing required filters" message instead. By default, tiles that ' + 'reference this filter by its variable or receive a broadcasted value ' + 'from this filter will be blocked. isGlobalRequirement widens the block ' + - 'to all tiles.Only 0 and 1 are accepted; omit the field (or pass 0) for ' + - 'the normal optional behavior, which is usually what you want.', + 'to all tiles. Omit the field (or pass 0) for the normal optional ' + + 'behavior, which is usually what you want.', ), isGlobalRequirement: z .boolean() @@ -1381,14 +1506,14 @@ const mcpQueryExpressionFilterSchema = z 'collapses its dropdown to the values already picked.', ), whereLanguage: SearchConditionTrimmedLanguageSchema.describe( - 'Filter language for `where` ("lucene" or "sql"). Optional, but set it explicitly.', + 'Query language of `where`. Set it explicitly.', ), appliesToSourceIds: z .array(objectIdSchema) .optional() .describe( - 'Optional list of source IDs that this filter is applied to. ' + - 'Omit (or pass `undefined`) to apply the filter to ALL tiles regardless of source ' + + 'Source IDs (from clickstack_list_sources) that this filter is applied to. ' + + 'Omit to apply the filter to ALL tiles regardless of source ' + '— this is the recommended default. ' + 'A non-empty array restricts the filter to only tiles whose source ID is in the list; ' + 'tiles on other sources are not affected by the dropdown value at all. ' + @@ -1442,8 +1567,7 @@ const mcpStaticListFilterSchema = z 'Filter type discriminator for a filter whose dropdown offers a fixed hand-authored list; no source query.', ), options: StaticListDashboardFilterSchema.shape.options.describe( - 'The values the dropdown offers, in display order. ' + - `1-${DASHBOARD_STATIC_FILTER_MAX_OPTIONS} unique, non-empty strings.`, + 'The values the dropdown offers, in display order, without duplicates.', ), }) .describe( @@ -1532,15 +1656,17 @@ export const mcpFiltersParam = z ); export const mcpPatchDashboardSchema = z.object({ - dashboardId: objectIdSchema.describe('Dashboard ID.'), + dashboardId: objectIdSchema.describe( + 'ID of the dashboard to patch, from clickstack_get_dashboard (no id lists ' + + 'dashboards) or clickstack_search_dashboards.', + ), name: z .string() .min(1) .optional() .describe('New dashboard name. Omit to keep the current name.'), tags: tagsSchema.describe( - `New tags array (replaces all existing tags). Omit to keep the current tags. ` + - `Up to ${MAX_TAGS} tags, each at most ${MAX_TAG_LENGTH} characters.`, + 'New tag list; replaces all existing tags. Omit to keep the current tags.', ), tileId: z .string() @@ -1554,7 +1680,8 @@ export const mcpPatchDashboardSchema = z.object({ .describe( 'The full replacement tile definition. Replaces the tile matched by tileId. ' + 'Layout fields (x, y, w, h), name, and containerId/tabId default to the ' + - "existing tile's values when omitted, so you only need to specify what changed.", + "existing tile's values when omitted. `config` is not merged: send the " + + 'complete config, since omitted config fields are not carried over.', ), }); @@ -1564,12 +1691,14 @@ export const mcpSearchDashboardsSchema = z.object({ .max(200) .optional() .describe( - 'Search term to match against dashboard names (case-insensitive substring match).', + 'Text matched against dashboard names as a case-insensitive substring.', ), tags: z .array(z.string().min(1)) .optional() - .describe('Filter to dashboards that have ALL of these tags.'), + .describe( + 'Return only dashboards that carry every one of these tags (exact match).', + ), }); export const mcpContainersParam = z @@ -1585,10 +1714,6 @@ export const mcpContainersParam = z '- A tile.containerId must reference a container id in this array.\n' + '- A tile.tabId must reference a tab id on the same container.\n' + '- tile.tabId requires tile.containerId.\n\n' + - 'Container shape: { id, title, collapsed, collapsible?, bordered?, tabs? }. ' + - '`collapsed` is required. `collapsible` and `bordered` are optional and ' + - 'persisted absent when omitted; the renderer treats absence as true. ' + - 'Two or more tabs render as a tab bar; zero or one tab renders as a plain group header.\n\n' + 'Example:\n' + '[\n' + ' { "id": "service-health", "title": "Service Health", "collapsed": false,\n' + diff --git a/packages/api/src/mcp/tools/query/emergingSignals.ts b/packages/api/src/mcp/tools/query/emergingSignals.ts index 9850cbc7cc..ca776f7d24 100644 --- a/packages/api/src/mcp/tools/query/emergingSignals.ts +++ b/packages/api/src/mcp/tools/query/emergingSignals.ts @@ -83,7 +83,7 @@ const emergingSignalsSchema = z.object({ currentEndTime: z .string() .describe( - 'End of the CURRENT / report window (ISO 8601). Required — pass the ' + + 'End of the CURRENT / report window (ISO 8601). Pass the ' + 'current timestamp for a window ending now.', ), baselineStartTime: z @@ -104,7 +104,7 @@ const emergingSignalsSchema = z.object({ .max(25_000) .optional() .default(10_000) - .describe('Rows sampled per window for pattern mining. Default 10000.'), + .describe('Rows sampled from each window for pattern mining.'), topN: z .number() .min(1) @@ -112,7 +112,7 @@ const emergingSignalsSchema = z.object({ .optional() .default(20) .describe( - 'Max emerging + disappeared patterns to return each. Default 20.', + 'Maximum patterns returned in each list (emerging and disappeared).', ), minShareRatio: z .number() @@ -122,8 +122,8 @@ const emergingSignalsSchema = z.object({ .describe( 'How many times more frequent (by share of window) a pattern must be in ' + 'the current window vs baseline to count as EMERGING (and vice-versa ' + - 'for DISAPPEARED). Default 3× — a pattern must have tripled its share to ' + - 'qualify as a shift, not just noise.', + 'for DISAPPEARED). At 3, a pattern must have tripled its share to ' + + 'qualify as a shift rather than noise.', ), }); diff --git a/packages/api/src/mcp/tools/query/eventDeltas.ts b/packages/api/src/mcp/tools/query/eventDeltas.ts index 61145cdc75..5c4d51d7f0 100644 --- a/packages/api/src/mcp/tools/query/eventDeltas.ts +++ b/packages/api/src/mcp/tools/query/eventDeltas.ts @@ -24,37 +24,53 @@ import { clickHouseErrorResult, parseTimeRange } from './helpers'; // ─── Schema ────────────────────────────────────────────────────────────────── -const groupSchema = z.object({ - startTime: z.string().describe('Start of the group window as ISO 8601.'), - endTime: z.string().describe('End of the group window as ISO 8601.'), - where: z - .string() - .optional() - .default('') - .describe( - 'Optional row filter (Lucene by default, SQL via whereLanguage). ' + - 'Combined with the time window via AND. Useful for restricting the ' + - 'group to a service, endpoint, or other dimension.', - ), - whereLanguage: z - .enum(['lucene', 'sql']) - .optional() - .default('lucene') - .describe('Query language for where. Default: lucene.'), -}); +const makeGroupSchema = (text: { + startTime: string; + endTime: string; + where: string; +}) => + z.object({ + startTime: z.string().describe(text.startTime), + endTime: z.string().describe(text.endTime), + where: z.string().optional().default('').describe(text.where), + whereLanguage: z + .enum(['lucene', 'sql']) + .optional() + .default('lucene') + .describe( + "Language of where. Lucene uses Column:value; SQL uses Column = 'value'.", + ), + }); const deltasSchema = z.object({ sourceId: z .string() .describe( - 'Source ID. Works for trace and log sources. ' + + 'Trace or log source to sample. ' + 'Call clickstack_list_sources for available sources.', ), - target: groupSchema.describe( + target: makeGroupSchema({ + startTime: 'Start of the target window as ISO 8601.', + endTime: 'End of the target window as ISO 8601.', + where: + 'Row filter selecting the target rows, ANDed with the target window. ' + + 'Keep it narrow: only the outlier rows. For slow-vs-fast comparisons, ' + + 'include the same operation filter used in baseline.', + }).describe( 'Target ("outlier") group — the rows you suspect are different (e.g. the ' + 'recent slow window, the failing requests, the affected segment).', ), - baseline: groupSchema.describe( + baseline: makeGroupSchema({ + startTime: + 'Start of the baseline window as ISO 8601. Use an earlier healthy ' + + 'period for before/after comparisons, or the same window as target ' + + 'when the groups differ only by where.', + endTime: 'End of the baseline window as ISO 8601.', + where: + 'Row filter selecting the baseline rows, ANDed with the baseline ' + + 'window. Leave empty to use every row in the window. If where and ' + + 'whereLanguage match target, the windows must differ.', + }).describe( 'Baseline ("inlier") group — the rows considered normal (e.g. an earlier ' + 'healthy window, the successful requests, the unaffected segment).', ), @@ -65,8 +81,8 @@ const deltasSchema = z.object({ .optional() .default(500) .describe( - 'Rows to sample from each group. Default: 500. Larger samples give ' + - 'more stable rankings at the cost of latency.', + 'Rows to sample from each group. Larger samples give more stable ' + + 'rankings at the cost of latency.', ), topN: z .number() @@ -75,15 +91,17 @@ const deltasSchema = z.object({ .optional() .default(20) .describe( - 'Number of top-ranked properties to return in `properties`. Default: 20.', + 'Number of top-ranked properties to return in `properties` (and in ' + + '`hidden` when includeHidden is set).', ), includeHidden: z .boolean() .optional() .default(false) .describe( - 'When true, include denylisted/high-cardinality properties in a separate ' + - '`hidden` array. Default: false (mirrors UI behavior — these are noisy).', + 'Also return denylisted ID, timestamp, and high-cardinality properties ' + + 'in a separate `hidden` array. Off by default, like the UI, because ' + + 'these are noisy.', ), topValuesPerProperty: z .number() @@ -92,7 +110,8 @@ const deltasSchema = z.object({ .optional() .default(6) .describe( - 'How many top values per property to include in the response. Default: 6.', + 'Number of values per property in `topDeltas`, ordered by largest ' + + 'share shift.', ), }); @@ -146,58 +165,35 @@ export function registerEventDeltas({ context, registerTool }: ToolRegistrar) { title: 'Compare Events: Target vs Baseline', annotations: { readOnlyHint: true }, description: - 'Rank the properties of two row groups (logs or trace spans) by ' + - 'how much their value distributions differ. Same algorithm as the ' + - 'in-app Event Deltas view (DBDeltaChart). High-cardinality fields ' + - '(IDs, request IDs, timestamps) are filtered out by default so the ' + - 'ranking surfaces the categorical attributes that actually separate ' + - 'the two groups. Score is computed after normalizing each group to ' + - "100% so it's robust to different group sizes.\n\n" + - 'USE THIS INSTEAD OF MANUAL PIVOTS. When two row sets visibly differ ' + - "and you don't know which attribute(s) separate them, the standard " + - 'agentic move is to run a GROUP BY for each candidate attribute and ' + - 'compare. event_deltas does this for ALL attributes in one call, ' + - 'ranked by signal strength — usually 1 call instead of 5–20.\n\n' + - 'NARROW the target to the specific outlier rows. A broad target ' + - 'mostly contains healthy rows, so the ranking comes back noisy. ' + - 'The narrower target — the sharper the ranking.\n\n' + - 'TYPICAL USES (any source — logs or traces):\n' + - ' - Slow vs fast spans (MOST COMMON for latency triage):\n' + - ' target = {where: AND Duration > },\n' + - ' baseline = {where: AND Duration <= }\n' + - ' Scope BOTH to the same operation/endpoint via ``; ' + - 'the ranked attribute(s) are then what discriminates the slow ' + - 'invocations of THAT operation from the fast ones. Skipping the ' + - 'op-filter gives a noisy "which operation is slow" answer instead ' + - 'of "which sub-set of one operation is slow".\n' + - ' - Before vs after a deploy / incident onset:\n' + - ' target = {window: after onset}, baseline = {window: before onset}\n' + - ' - Failing vs succeeding rows:\n' + - ' target = {where: }, baseline = {where: }\n' + - ' - One service / endpoint vs the rest:\n' + - ' target = {where: ServiceName=X}, baseline = {where: ServiceName != X}\n' + - ' Any pair of row sets over the same source works — the tool just ' + - ' asks "what is statistically different about target vs baseline".\n\n' + - 'WHEN NOT TO USE: when the question is already known to be about a ' + - 'specific attribute (use clickstack_table groupBy), when you want raw ' + - 'rows (use clickstack_search), or when you need a time-series shape ' + - '(use clickstack_timeseries).\n\n' + + 'Rank every attribute of two row groups (logs or trace spans) by how ' + + 'much its value distribution differs between a target and a baseline ' + + '(the in-app Event Deltas algorithm). One call replaces running a ' + + 'GROUP BY per candidate attribute.\n\n' + + 'NARROW the target to the outlier rows. A broad target is mostly ' + + 'healthy rows and gives a noisy ranking. target and baseline must ' + + 'differ in where or in time window.\n\n' + + 'TYPICAL PAIRS:\n' + + ' - Slow vs fast (latency triage): target where = AND ' + + 'Duration > X, baseline where = AND Duration <= X. Scope ' + + 'BOTH to the same operation, or you learn which operation is slow ' + + 'instead of why it is slow.\n' + + ' - After vs before an incident or deploy: same where, different windows.\n' + + ' - Failing vs succeeding rows, or one service vs the rest.\n\n' + + 'WHEN NOT TO USE: the attribute is already known (clickstack_table ' + + 'groupBy), you want raw rows (clickstack_search) or a trend ' + + '(clickstack_timeseries), or you want patterns that are new or gone ' + + '(clickstack_emerging_signals).\n\n' + PREFER_BUILDER_OVER_SQL_NUDGE + '\n\n' + - 'OUTPUT SHAPE: an array of properties, each with rank, key, score, ' + - 'semanticBoost (true for well-known OTel attrs like service.name / ' + - 'http.method / error.type / status), targetCount and baselineCount ' + - '(sample sizes), and topDeltas — the values whose share shifted ' + - 'most, each with `value`, `targetPct`, `baselinePct`, and `diffPct`. ' + - 'topDeltas already contains the full per-value comparison for that ' + - 'attribute, so there is no separate target/baseline distribution to ' + - 'consult.\n\n' + - 'IMPORTANT — DO NOT STOP AT RANK 1. The top ~5 ranked properties ' + - 'are often INDEPENDENT axes that together explain the population ' + - 'shift (e.g. a regression localized on the intersection of two ' + - 'attributes). Scan down the list until the score visibly drops to ' + - 'noise level; any property well above that floor is a candidate axis ' + - 'to combine with the others.', + 'OUTPUT: properties ranked by score, the largest %-share difference of ' + + 'any value after normalizing each group to 100%, plus a 0.1 tie-breaking ' + + 'boost for well-known attributes. Each has key, score, ' + + 'semanticBoost (well-known OTel attribute), targetCount/baselineCount, ' + + 'and topDeltas (value, targetPct, baselinePct, diffPct): the ' + + 'topValuesPerProperty values whose share shifted most. ID and high-cardinality fields are hidden ' + + 'unless includeHidden is set.\n\n' + + 'DO NOT STOP AT RANK 1. The top ~5 are often independent axes that ' + + 'together explain the shift. Read down until scores drop to noise.', inputSchema: deltasSchema, }, async (input: DeltasInput) => { diff --git a/packages/api/src/mcp/tools/query/eventPatterns.ts b/packages/api/src/mcp/tools/query/eventPatterns.ts index 5be52c6dd6..43dea0a7a4 100644 --- a/packages/api/src/mcp/tools/query/eventPatterns.ts +++ b/packages/api/src/mcp/tools/query/eventPatterns.ts @@ -28,8 +28,8 @@ const eventPatternsSchema = z.object({ .optional() .default(10_000) .describe( - 'Number of random rows to sample for pattern mining. ' + - 'Default: 10000. Higher values produce more accurate patterns but take longer.', + 'Random rows to sample for pattern mining. ' + + 'Higher values produce more accurate patterns but take longer.', ), bodyExpression: z .string() @@ -45,7 +45,7 @@ const eventPatternsSchema = z.object({ .max(100) .optional() .default(20) - .describe('Number of top patterns to return (1-100). Default: 20.'), + .describe('Number of most frequent patterns to return.'), trendBuckets: z .number() .min(0) @@ -53,7 +53,7 @@ const eventPatternsSchema = z.object({ .optional() .default(24) .describe( - 'Number of time buckets for per-pattern trend sparklines (0-60). Default: 24. ' + + 'Number of time buckets for per-pattern trend sparklines. ' + 'Compare bucket counts at start vs end to spot patterns that started or stopped mid-window. ' + 'Set to 0 to disable trend computation (smaller response).', ), diff --git a/packages/api/src/mcp/tools/query/schemas.ts b/packages/api/src/mcp/tools/query/schemas.ts index f274f7e893..e3e70664b7 100644 --- a/packages/api/src/mcp/tools/query/schemas.ts +++ b/packages/api/src/mcp/tools/query/schemas.ts @@ -9,7 +9,7 @@ import { mcpUserError } from '@/mcp/utils/errors'; const WHERE_DESCRIPTION = 'Row filter.\n\n' + 'FIRST: pick a language (whereLanguage):\n' + - ' Lucene (default): Column:value e.g. level:error\n' + + ' Lucene: Column:value e.g. level:error\n' + ' Lucene map attrs: Column.key:value e.g. SpanAttributes.http.method:GET\n' + " SQL: Column = 'value' e.g. StatusCode = 500\n" + " SQL map attrs: SpanAttributes['key'] = 'value'\n\n" + @@ -23,17 +23,16 @@ const WHERE_DESCRIPTION = " For exact match, use SQL: SpanKind = 'Server'"; const WHERE_LANGUAGE_DESCRIPTION = - 'Query language for the "where" filter. Default: lucene.\n' + - 'IMPORTANT: the syntax in "where" MUST match "whereLanguage".\n' + - ' Lucene (default): Column:value, Column.mapKey:value, Column:>100\n' + - " SQL: Column = 'value', SpanAttributes['key'] = 'value'\n\n" + + 'Language of the "where" filter. The syntax in "where" MUST match this setting.\n' + + ' Lucene: Column:value, Column.mapKey:value, Column:>100\n' + + " SQL: Column = 'value', SpanAttributes['key'] = 'value'\n\n" + 'Lucene supports comparisons (>= > < <=), wildcards (field:val*), ranges ([1 TO 5]), ' + 'and map attributes via dot notation. Use "sql" for IN(...) lists, complex expressions, or function calls.\n' + 'IMPORTANT: Lucene field:value is a SUBSTRING match (ilike), not exact equality. ' + 'field:val* is prefix-within-substring, not a true prefix match. ' + "For exact matching or reliable wildcards, use SQL: WHERE field = 'value' or WHERE field LIKE 'val%'.\n\n" + 'Common mistake: writing Column:value (Lucene) but setting whereLanguage to "sql". ' + - 'If your filter uses colon syntax, leave whereLanguage as "lucene" (the default).'; + 'If your filter uses colon syntax, use "lucene".'; // ─── Shared Zod schemas ────────────────────────────────────────────────────── @@ -61,7 +60,7 @@ export const MCP_AGG_FN_OPTIONS = [ const mcpAggFnSchema = z .enum(MCP_AGG_FN_OPTIONS) .describe( - 'Aggregation function:\n' + + 'How rows are aggregated into this series:\n' + ' count – count matching rows (no valueExpression needed)\n' + ' sum / avg / min / max – aggregate a numeric column (valueExpression required)\n' + ' count_distinct – unique value count (valueExpression required)\n' + @@ -278,29 +277,27 @@ export const mcpSelectItemSchema = z.object({ .default('lucene') .describe( 'Query language for the per-item conditional filter. ' + - 'Use "sql" when comparing to literal timestamps or arbitrary attribute expressions. ' + - 'Default: lucene', + 'Use "sql" when comparing to literal timestamps or arbitrary attribute expressions.', ), alias: z .string() .optional() .describe( - 'Display label for this series — used in chart legends, table column headers, CSV exports, and onClick templates. ' + - 'Always set a short, human-readable alias (e.g. "Requests", "P95 Latency", "Error Rate"). ' + - 'Without an alias the UI shows the raw ClickHouse expression (e.g. count(), quantile(0.95)(Duration)) which is hard to read.', + 'Display label for this series, used in chart legends, table column headers, CSV exports, and onClick templates. ' + + 'Always set a short, readable label (e.g. "Requests", "P95 Latency", "Error Rate"); ' + + 'without one the UI shows the raw expression, e.g. quantile(0.95)(Duration).', ), level: mcpQuantileLevelSchema .optional() .describe( - 'Percentile level. Required when aggFn is "quantile" on a histogram or exponential histogram metric, ' + - 'optional otherwise. ' + - 'Allowed values: 0.5, 0.9, 0.95, 0.99', + 'Percentile for aggFn:"quantile" (0.95 = p95). Only valid with quantile; ' + + 'required when using quantile on a histogram or exponential histogram metric.', ), metricType: mcpMetricTypeSchema .optional() .describe( - 'METRIC SOURCES ONLY. OTel metric kind: gauge, sum, histogram, or exponential histogram. ' + - 'Required (with metricName) when sourceId is a metric source. ' + + 'METRIC SOURCES ONLY. OTel metric kind of metricName. ' + + 'Set together with metricName on every item when sourceId is a metric source. ' + 'Discover via clickstack_describe_source (sample) or clickstack_describe_metric.', ), metricName: z @@ -308,7 +305,7 @@ export const mcpSelectItemSchema = z.object({ .optional() .describe( 'METRIC SOURCES ONLY. OTel metric name (e.g. "system.cpu.utilization", ' + - '"http.server.request.duration"). Required when metricType is set. ' + + '"http.server.request.duration"). Set together with metricType. ' + 'Discover via clickstack_list_metrics or clickstack_describe_source.', ), isDelta: z @@ -317,7 +314,7 @@ export const mcpSelectItemSchema = z.object({ .describe( 'METRIC SOURCES ONLY (gauge metrics). When true, computes the Prometheus-style ' + 'delta over each bucket: (argMax(Value) - argMin(Value)) * bucketSecs / timeDiff. ' + - 'Use for cumulative gauges where you want to chart growth per bucket. Default false.', + 'Use for cumulative gauges where you want to chart growth per bucket.', ), }); // NOTE: cross-field validation (metric rules + level + valueExpression) is @@ -400,7 +397,7 @@ export const endTimeSchema = z export const sourceIdSchema = z .string() .describe( - 'Source ID (required). Call clickstack_list_sources to find available sources.', + 'Source to query. Call clickstack_list_sources to find source IDs.', ); export const whereSchema = z @@ -419,12 +416,10 @@ export const groupBySchema = z .string() .optional() .describe( - 'Column(s) or ClickHouse expression(s) to group/split by. ' + - 'Accepts a SINGLE entry or MULTIPLE entries as a comma-delimited list — ' + - 'multi-column groupBy expresses multi-dimensional breakdowns in one ' + - 'query (e.g. "ServiceName, SpanName, StatusMessage") instead of running ' + - 'one query per dimension. For "table" displayType, the result has one row ' + - 'per distinct combination of group values. ' + + 'Column(s) or ClickHouse expression(s) to group/split by, as one entry or a ' + + 'comma-delimited list. Multiple entries give a multi-dimensional breakdown ' + + 'in one query (e.g. "ServiceName, SpanName, StatusMessage") instead of one ' + + 'query per dimension; a table gets one row per distinct combination. ' + 'Top-level columns use PascalCase ("SpanName", "StatusCode"). ' + "Map attributes: SpanAttributes['key'], ResourceAttributes['key'].\n\n" + 'Arbitrary ClickHouse expressions are also allowed in groupBy — useful when ' + diff --git a/packages/api/src/mcp/tools/query/search.ts b/packages/api/src/mcp/tools/query/search.ts index 13ea2269f0..036c33b67e 100644 --- a/packages/api/src/mcp/tools/query/search.ts +++ b/packages/api/src/mcp/tools/query/search.ts @@ -37,8 +37,7 @@ const searchSchema = z.object({ .optional() .default(50) .describe( - 'Maximum number of rows to return (1-200). Default: 50. ' + - 'Use smaller values to reduce response size.', + 'Maximum rows to return. Use smaller values to reduce response size.', ), denoise: z .boolean() diff --git a/packages/api/src/mcp/tools/query/sql.ts b/packages/api/src/mcp/tools/query/sql.ts index 74e965e904..1ddcc32d68 100644 --- a/packages/api/src/mcp/tools/query/sql.ts +++ b/packages/api/src/mcp/tools/query/sql.ts @@ -16,14 +16,14 @@ const sqlSchema = z.object({ connectionId: z .string() .describe( - 'Connection ID (required). This is the only split tool that needs a connectionId ' + + 'Connection to query. This is the only query tool that takes a connectionId ' + 'instead of sourceId. Call clickstack_list_sources to find available connections.', ), sourceId: z .string() .optional() .describe( - 'Source ID. Optional. Set it when the query reads a table backed by a source, so ' + + 'Source ID. Set it when the query reads a table backed by a source, so ' + "`$__sourceTable` expands to that source's database.table. The source's " + 'connection must match connectionId. Call clickstack_list_sources to find source IDs.', ), diff --git a/packages/api/src/mcp/tools/query/table.ts b/packages/api/src/mcp/tools/query/table.ts index 5bdd83254b..687dd7370d 100644 --- a/packages/api/src/mcp/tools/query/table.ts +++ b/packages/api/src/mcp/tools/query/table.ts @@ -44,9 +44,8 @@ const tableSchema = z.object({ .optional() .default('table') .describe( - 'Output shape: "table" (grouped rows, default), "number" (single scalar), ' + - '"pie" (pie chart), or "bar" (categorical bar chart). ' + - 'If "number", "pie", or "bar" is set with select.length > 1, it is auto-upgraded to "table". ' + + 'Output shape: "table" is grouped rows, "number" a single scalar, "pie" a pie chart, "bar" a categorical bar chart. ' + + '"number", "pie", and "bar" are auto-upgraded to "table" when select has more than one item. ' + 'groupBy is ignored when shape is "number".', ), where: whereSchema.describe( @@ -209,31 +208,22 @@ 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.\n\n' + + 'or proportional breakdowns. For trends over time use clickstack_timeseries.\n\n' + PREFER_BUILDER_OVER_SQL_NUDGE + '\n\n' + 'Requires sourceId — call clickstack_list_sources then clickstack_describe_source first.\n\n' + - 'Use the top-level "where" to scope the entire query (e.g. filter by service). ' + - 'Each select item can also have its own "where" for per-metric cohort ' + - 'comparisons (compiles to If(...)). Both can be used together.\n\n' + - 'Column naming: top-level columns are PascalCase (Duration, StatusCode). ' + - "Map attributes use bracket syntax: SpanAttributes['http.method']. " + - 'Map attributes work in groupBy and valueExpression, including ' + - "toFloat64OrZero(SpanAttributes['key']).\n\n" + - 'Shape auto-upgrade: if shape is "number", "pie", or "bar" but select has >1 item, ' + - 'it is transparently upgraded to "table".\n\n' + - '── METRIC SOURCES ──\n' + - 'When sourceId is a metric source, each select item MUST set ' + - 'metricType ("gauge"|"sum"|"histogram"|"exponential histogram") and metricName (the OTel metric name). ' + - 'valueExpression defaults to "Value" — set it explicitly only to transform the value.\n' + - 'Discovery: clickstack_describe_source returns a per-kind metric-name sample; ' + - 'clickstack_list_metrics paginates the full catalog; clickstack_describe_metric ' + - 'returns attribute keys + sampled values for a single metric.\n' + - 'Per kind: gauge uses last_value/avg/min/max; sum uses aggFn:"increase" for counter increase ' + - '(top-N capped at 20 groups when combined with groupBy), or sum/avg on the rate; ' + - 'histogram and exponential histogram use aggFn:"quantile" + level for percentiles, or aggFn:"count" for total bucket count.\n' + - 'summary metrics are not supported by the query renderer — query them with ' + - "clickstack_sql against the table in the source's metricTables.summary.", + 'The top-level "where" scopes the whole query. Each select item can add its own ' + + '"where" (compiles to 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" + + 'METRIC SOURCES: every select item MUST set metricType and metricName; ' + + 'valueExpression defaults to "Value". Discover metrics with clickstack_describe_source ' + + '(sample), clickstack_list_metrics (full catalog), and clickstack_describe_metric ' + + '(attributes of one metric). Per kind: gauge uses last_value/avg/min/max; sum uses ' + + 'aggFn:"increase" (capped at the top 20 groups with groupBy) or sum/avg on the rate; ' + + 'histogram and exponential histogram use aggFn:"quantile" + level, or aggFn:"count". ' + + "summary metrics are unsupported — use clickstack_sql on the source's metricTables.summary table.", inputSchema: tableSchema, }, async input => { diff --git a/packages/api/src/mcp/tools/query/timeseries.ts b/packages/api/src/mcp/tools/query/timeseries.ts index f0b46b26fa..a81cdfe1b4 100644 --- a/packages/api/src/mcp/tools/query/timeseries.ts +++ b/packages/api/src/mcp/tools/query/timeseries.ts @@ -44,9 +44,7 @@ const timeseriesSchema = z.object({ .enum(['line', 'stacked_bar', 'stacked_line']) .optional() .default('line') - .describe( - 'Chart shape. "line" for line chart (default), "stacked_bar" for stacked bar chart, "stacked_line" for stacked line (area) chart.', - ), + .describe('Chart type. "stacked_line" is a stacked area chart.'), where: whereSchema.describe( 'Row filter applied to ALL select items. ' + 'Scopes the entire query — use to restrict by service, severity, etc. ' + diff --git a/packages/api/src/mcp/tools/savedSearches/saveSavedSearch.ts b/packages/api/src/mcp/tools/savedSearches/saveSavedSearch.ts index ba45d25cd4..5522954597 100644 --- a/packages/api/src/mcp/tools/savedSearches/saveSavedSearch.ts +++ b/packages/api/src/mcp/tools/savedSearches/saveSavedSearch.ts @@ -28,8 +28,15 @@ export function registerSaveSavedSearch({ annotations: { destructiveHint: true }, description: 'Create a new saved search (omit id) or update an existing one (provide id). ' + - 'A saved search stores a reusable query against a data source. ' + - 'Use clickstack_list_sources to find the sourceId.', + 'A saved search stores a reusable query (select, where, orderBy, filters) ' + + 'against a data source. Use clickstack_list_sources to find the sourceId.\n\n' + + 'UPDATES REPLACE FIELDS, they do not merge: name, sourceId, select, where, and ' + + 'tags are overwritten, and omitted select/where/tags are reset to empty. ' + + 'Omitted whereLanguage, orderBy, and filters keep their stored values. To ' + + 'change one field, read the saved search with clickstack_get_saved_search ' + + 'and resend everything you want to keep.\n\n' + + 'Alerts can be attached to a saved search and evaluate its current query, ' + + 'so changing where, select, or sourceId changes what those alerts check.', inputSchema: mcpSaveSavedSearchSchema, }, async input => { diff --git a/packages/api/src/mcp/tools/savedSearches/schemas.ts b/packages/api/src/mcp/tools/savedSearches/schemas.ts index 4dbf10be66..92e8d3ca80 100644 --- a/packages/api/src/mcp/tools/savedSearches/schemas.ts +++ b/packages/api/src/mcp/tools/savedSearches/schemas.ts @@ -1,11 +1,6 @@ import { z } from 'zod'; -import { - MAX_TAG_LENGTH, - MAX_TAGS, - objectIdSchema, - tagsSchema, -} from '@/utils/zod'; +import { objectIdSchema, tagsSchema } from '@/utils/zod'; // --------------------------------------------------------------------------- // MCP-compatible Zod schemas for saved search tools. @@ -14,34 +9,50 @@ import { const mcpFilterSchema = z .union([ z.object({ - type: z - .enum(['lucene', 'sql']) - .describe('Filter language: lucene or sql.'), - condition: z.string().describe('Filter condition string.'), + type: z.enum(['lucene', 'sql']).describe('Language of condition.'), + condition: z + .string() + .describe( + "Filter condition in the chosen language, e.g. level:error or StatusCode = 'Error'.", + ), }), z.object({ - type: z.literal('sql_ast').describe('Structured SQL AST filter.'), + type: z + .literal('sql_ast') + .describe('Structured comparison, rendered as `left operator right`.'), operator: z .enum(['=', '<', '>', '!=', '<=', '>=']) - .describe('Comparison operator.'), - left: z.string().describe('Left operand (column or expression).'), - right: z.string().describe('Right operand (value or expression).'), + .describe('Comparison between left and right.'), + left: z + .string() + .describe('Column or SQL expression to compare. Inserted as raw SQL.'), + right: z + .string() + .describe( + 'Value or SQL expression that left is compared against. Inserted ' + + 'verbatim as raw SQL, so quote string literals ("\'ok\'") and leave ' + + 'numbers bare ("100").', + ), }), ]) - .describe('Filter applied to the saved search.'); + .describe( + 'Extra filter ANDed with where: either a lucene/sql condition string or a ' + + 'structured sql_ast comparison.', + ); export const mcpSaveSavedSearchSchema = z.object({ id: z .string() .optional() .describe( - 'Saved search ID. Omit to create a new saved search, provide to update an existing one.', + 'Saved search ID, from clickstack_get_saved_search. Omit to create a new ' + + 'saved search, provide to update an existing one.', ), name: z .string() .min(1) .max(512) - .describe('Human-friendly name for the saved search.'), + .describe('Name shown for the saved search in the app.'), select: z .string() .optional() @@ -59,7 +70,10 @@ export const mcpSaveSavedSearchSchema = z.object({ whereLanguage: z .enum(['sql', 'lucene']) .optional() - .describe('Language for the where filter. Default: lucene.'), + .describe( + 'Language for the where filter. Defaults to lucene on create; on update, ' + + 'omitting it keeps the stored value, so resend it whenever you change where.', + ), orderBy: z .string() .optional() @@ -68,7 +82,7 @@ export const mcpSaveSavedSearchSchema = z.object({ 'Source ID — call clickstack_list_sources to find available sources.', ), tags: tagsSchema.describe( - `Tags for organizing saved searches. Up to ${MAX_TAGS} tags, each at most ${MAX_TAG_LENGTH} characters.`, + 'Tags for organizing saved searches. On update, omitting tags clears them.', ), filters: z .array(mcpFilterSchema) diff --git a/packages/api/src/mcp/tools/sources/deleteSource.ts b/packages/api/src/mcp/tools/sources/deleteSource.ts index 2f91831be3..3518a96912 100644 --- a/packages/api/src/mcp/tools/sources/deleteSource.ts +++ b/packages/api/src/mcp/tools/sources/deleteSource.ts @@ -22,7 +22,9 @@ export function registerDeleteSource({ 'left dangling, so check dependencies first. Use clickstack_list_sources ' + 'to find available source IDs.', inputSchema: z.object({ - id: objectIdSchema.describe('Source ID to delete.'), + id: objectIdSchema.describe( + 'ID of the source to delete. Get it from clickstack_list_sources.', + ), }), }, async ({ id: sourceId }) => { diff --git a/packages/api/src/mcp/tools/sources/describeMetric.ts b/packages/api/src/mcp/tools/sources/describeMetric.ts index 5547f40dde..8131235605 100644 --- a/packages/api/src/mcp/tools/sources/describeMetric.ts +++ b/packages/api/src/mcp/tools/sources/describeMetric.ts @@ -88,7 +88,7 @@ const describeMetricSchema = z.object({ kind: z .enum(DISCOVERABLE_METRIC_KINDS) .describe( - 'Metric kind: "gauge" | "sum" | "histogram" | "exponential histogram" | "summary". Required. ' + + 'OTel metric kind of metricName, which selects the metric table to read. ' + 'Discover via clickstack_list_metrics (which returns name + kind per entry) ' + 'or clickstack_describe_source (which groups metric-name samples by kind). ' + 'A metric name can legitimately live in more than one kind (e.g. ' + @@ -110,7 +110,7 @@ const describeMetricSchema = z.object({ .optional() .default(true) .describe( - 'When true (default), sample up to ' + + 'Sample up to ' + `${MAX_ATTR_VALUES} distinct values per attribute key for the top ${MAX_ATTR_KEYS_TO_SAMPLE} attributes. ` + 'Set false to skip value sampling for faster responses on high-cardinality metrics.', ), diff --git a/packages/api/src/mcp/tools/sources/listMetricsSchema.ts b/packages/api/src/mcp/tools/sources/listMetricsSchema.ts index f10ae9880c..a5bd1179b1 100644 --- a/packages/api/src/mcp/tools/sources/listMetricsSchema.ts +++ b/packages/api/src/mcp/tools/sources/listMetricsSchema.ts @@ -38,8 +38,8 @@ export const listMetricsSchema = z.object({ .enum(DISCOVERABLE_METRIC_KINDS) .optional() .describe( - 'Optional metric kind filter. Omit to scan every populated kind on the source ' + - '(gauge, sum, histogram, exponential histogram, summary). Set to narrow results to one kind. ' + + 'Restrict results to one metric kind. Omit to scan every kind that has ' + + 'a table on the source. ' + 'NOTE: summary metrics are discovery-only — they cannot be passed to ' + 'clickstack_timeseries / clickstack_table; query them with clickstack_sql.', ), @@ -47,7 +47,7 @@ export const listMetricsSchema = z.object({ .string() .optional() .describe( - 'Optional ClickHouse ILIKE pattern applied to MetricName server-side. ' + + 'ClickHouse ILIKE pattern (case-insensitive) matched against MetricName. ' + 'Use % as the wildcard. Examples: "system.cpu.%", "%duration%", "http.server.%".', ), startTime: z @@ -69,7 +69,7 @@ export const listMetricsSchema = z.object({ .optional() .default(DEFAULT_LIMIT) .describe( - `Max metrics returned per page. Default ${DEFAULT_LIMIT}, max ${MAX_LIMIT}.`, + 'Maximum metrics returned per page. Use cursor to fetch further pages.', ), cursor: z .string() diff --git a/packages/api/src/mcp/tools/sources/saveSource.ts b/packages/api/src/mcp/tools/sources/saveSource.ts index 74ba4c9df3..93622651bb 100644 --- a/packages/api/src/mcp/tools/sources/saveSource.ts +++ b/packages/api/src/mcp/tools/sources/saveSource.ts @@ -29,7 +29,9 @@ export function registerSaveSource({ description: 'Create a new data source (omit id) or update an existing one ' + '(provide id) so shipped telemetry becomes queryable. Update is a ' + - 'full replace of the source definition. Required for all kinds: kind, ' + + 'full replace of the source definition: start from the `config` ' + + 'returned by clickstack_describe_source and change only what you need. ' + + 'Required for all kinds: kind, ' + 'name, connection, databaseName, tableName, timestampValueExpression. ' + 'Kind-specific requirements: log & trace need ' + 'defaultTableSelectExpression; trace also needs durationExpression, ' + diff --git a/packages/api/src/mcp/tools/sources/schemas.ts b/packages/api/src/mcp/tools/sources/schemas.ts index bda19d0464..0b52a6fb57 100644 --- a/packages/api/src/mcp/tools/sources/schemas.ts +++ b/packages/api/src/mcp/tools/sources/schemas.ts @@ -24,47 +24,130 @@ void _assertSourceKindsMatchEnum; // Granularity fields use the internal " " form (e.g. "5 minute"). const highlightedAttributeExpressionsSchema = z.array( z.object({ - sqlExpression: z.string(), - luceneExpression: z.string().optional(), - alias: z.string().optional(), + sqlExpression: z + .string() + .describe( + "ClickHouse SQL expression for the attribute, e.g. ResourceAttributes['http.host'].", + ), + luceneExpression: z + .string() + .optional() + .describe( + 'Lucene version of sqlExpression, e.g. ResourceAttributes.http.host. ' + + 'When set, it is used when searching for this attribute value.', + ), + alias: z + .string() + .optional() + .describe('Display name for the attribute (rendered as AS ).'), }), ); const aggregatedColumnSchema = z.object({ - sourceColumn: z.string().optional(), - aggFn: z.string(), - mvColumn: z.string(), + sourceColumn: z + .string() + .optional() + .describe( + 'Column in the source table that the view aggregates. Required unless aggFn is "count".', + ), + aggFn: z + .string() + .describe( + 'Aggregate function the view applies to sourceColumn, e.g. count, sum, avg, min, max, quantile, histogram.', + ), + mvColumn: z + .string() + .describe( + 'Column in the materialized view that holds the aggregated value.', + ), }); const materializedViewsSchema = z.array( z.object({ - databaseName: z.string(), - tableName: z.string(), - dimensionColumns: z.string(), - minGranularity: z.string(), - minDate: z.string().nullish(), - timestampColumn: z.string(), - aggregatedColumns: z.array(aggregatedColumnSchema), + databaseName: z + .string() + .describe('ClickHouse database containing the materialized view table.'), + tableName: z + .string() + .describe('ClickHouse table the materialized view writes to.'), + dimensionColumns: z + .string() + .describe( + 'Comma-separated columns that are not pre-aggregated and can be used ' + + 'for filtering and grouping, e.g. "ServiceName, StatusCode".', + ), + minGranularity: z + .string() + .describe( + 'Time bucket size of the view\'s timestamp column, as " " ' + + 'with unit second, minute, hour, or day, e.g. "1 minute".', + ), + minDate: z + .string() + .nullish() + .describe( + 'ISO 8601 datetime of the earliest data in the view. Omit or null to ' + + 'assume the view covers every date the source table has data for.', + ), + timestampColumn: z + .string() + .describe('Timestamp column in the materialized view table.'), + aggregatedColumns: z + .array(aggregatedColumnSchema) + .describe( + 'Columns the view pre-aggregates. At least one entry is required.', + ), }), ); const metadataMaterializedViewsSchema = z.object({ - keyRollupTable: z.string().nullish(), - kvRollupTable: z.string(), - granularity: z.string(), + keyRollupTable: z + .string() + .nullish() + .describe( + 'Deprecated. Key rollup table used for field discovery; kvRollupTable is used when unset.', + ), + kvRollupTable: z + .string() + .describe( + "Key-value rollup table in the source's database, used for field discovery " + + 'and value autocomplete, e.g. "otel_logs_kv_rollup_15m".', + ), + granularity: z + .string() + .describe( + 'Time bucket size of the rollup tables, as " " with unit ' + + 'second, minute, hour, or day, e.g. "15 minute".', + ), }); const metricTablesSchema = z .object({ - gauge: z.string().optional(), - histogram: z.string().optional(), - sum: z.string().optional(), - summary: z.string().optional(), - 'exponential histogram': z.string().optional(), + gauge: z + .string() + .optional() + .describe('Table containing gauge metrics data.'), + histogram: z + .string() + .optional() + .describe('Table containing histogram metrics data.'), + sum: z.string().optional().describe('Table containing sum metrics data.'), + summary: z + .string() + .optional() + .describe( + 'Table containing summary metrics data. Summary metrics cannot be ' + + 'queried with clickstack_timeseries / clickstack_table; use clickstack_sql.', + ), + 'exponential histogram': z + .string() + .optional() + .describe('Table containing exponential histogram metrics data.'), }) .describe( - 'Metric source only. Map of OTel metric kind -> ClickHouse table name. ' + - 'At least one entry is required for metric sources.', + 'Metric source only. Map of OTel metric kind to the ClickHouse table (in ' + + 'databaseName) holding that kind. At least one entry is required for ' + + 'metric sources.', ); export const mcpSaveSourceSchema = z.object({ @@ -73,14 +156,17 @@ export const mcpSaveSourceSchema = z.object({ .string() .optional() .describe( - 'Source ID. Omit to create a new source, provide to update an existing one.', + 'ID of the source to update, from clickstack_list_sources. Omit to create a new source.', ), // ── Always required (base) ── kind: z .enum(SOURCE_KINDS) - .describe('Source kind. Determines which fields are required.'), - name: z.string().min(1).describe('Human-friendly source name.'), + .describe( + 'Type of telemetry the table holds. Determines which other fields are ' + + 'required; see the tool description.', + ), + name: z.string().min(1).describe('Display name shown in source selectors.'), connection: z .string() .min(1) @@ -90,7 +176,10 @@ export const mcpSaveSourceSchema = z.object({ databaseName: z .string() .min(1) - .describe('ClickHouse database name (maps to from.databaseName).'), + .describe( + 'ClickHouse database containing the table (stored as from.databaseName). ' + + 'For promql sources, use a placeholder such as "prometheus".', + ), tableName: z .string() .describe( @@ -100,73 +189,250 @@ export const mcpSaveSourceSchema = z.object({ timestampValueExpression: z .string() .min(1) - .describe('Expression/column used as the primary timestamp.'), + .describe( + 'DateTime column or expression used for time filtering, ideally part of ' + + "the table's primary key (e.g. Timestamp; TimeUnix for OTel metrics). " + + 'For trace sources it marks the start of the span.', + ), // ── Common optional ── - section: z.string().optional().describe('Optional grouping section label.'), - displayedTimestampValueExpression: z.string().optional(), - serviceNameExpression: z.string().optional(), + section: z + .string() + .optional() + .describe( + 'Grouping label for source selectors; sources with the same section are ' + + 'listed together, e.g. "Billing".', + ), + displayedTimestampValueExpression: z + .string() + .optional() + .describe( + 'Log and trace sources. DateTime column used to display and order search results.', + ), + serviceNameExpression: z + .string() + .optional() + .describe( + 'Log, trace, and metric sources. Expression for the service name, e.g. ServiceName.', + ), resourceAttributesExpression: z .string() .optional() - .describe('Required for metric sources; optional for others.'), - eventAttributesExpression: z.string().optional(), - implicitColumnExpression: z.string().optional(), - knownColumnsListExpression: z.string().optional(), - orderByExpression: z.string().optional(), + .describe( + 'Map column or expression holding resource attributes, e.g. ' + + 'ResourceAttributes. Required for metric sources.', + ), + eventAttributesExpression: z + .string() + .optional() + .describe( + 'Log and trace sources. Map column holding event-level attributes, e.g. ' + + 'LogAttributes for logs or SpanAttributes for traces.', + ), + implicitColumnExpression: z + .string() + .optional() + .describe( + 'Log and trace sources. Column searched by full-text Lucene terms that ' + + 'name no field, typically the log body (Body) or SpanName.', + ), + knownColumnsListExpression: z + .string() + .optional() + .describe( + 'Log and trace sources. For Distributed tables whose target tables have ' + + 'different column sets: comma-separated column names present in all ' + + 'targets, used instead of SELECT * when fetching full rows. Column ' + + 'names only, no expressions or aliases. Omit to select all columns.', + ), + orderByExpression: z + .string() + .optional() + .describe( + 'Log and trace sources. ORDER BY expression overriding the default ' + + 'search ordering, e.g. "Timestamp DESC". Omit to use the auto-detected default.', + ), useTextIndexForImplicitColumn: z .enum(['auto', 'enabled', 'disabled']) .optional() - .describe('Whether to use the text index for the implicit column.'), + .describe( + 'Log and trace sources. Whether Lucene searches on the implicit column ' + + 'use hasAllTokens(). "auto" (used when unset) detects a covering text ' + + 'index at query time; "enabled" always uses hasAllTokens(), useful for ' + + 'Merge engine tables; "disabled" falls back to hasToken().', + ), // ── Log / Trace ── defaultTableSelectExpression: z .string() .optional() - .describe('Default columns to select. Required for log and trace sources.'), - bodyExpression: z.string().optional().describe('Log body expression.'), - severityTextExpression: z.string().optional(), + .describe( + 'Comma-separated columns shown in search results by default, e.g. ' + + '"Timestamp, ServiceName, Body". Required for log and trace sources.', + ), + bodyExpression: z + .string() + .optional() + .describe('Log sources. Expression for the log message body, e.g. Body.'), + severityTextExpression: z + .string() + .optional() + .describe( + 'Log sources. Expression for the log level / severity text, e.g. SeverityText.', + ), // ── Trace (required for trace kind) ── - durationExpression: z.string().optional(), + durationExpression: z + .string() + .optional() + .describe( + 'Trace sources (required). Expression for span duration, e.g. Duration. ' + + 'Its unit is set by durationPrecision.', + ), durationPrecision: z .number() .min(0) .max(9) .optional() - .describe('Trace duration precision (0-9). Defaults to 3.'), - traceIdExpression: z.string().optional(), - spanIdExpression: z.string().optional(), - parentSpanIdExpression: z.string().optional(), - spanNameExpression: z.string().optional(), - spanKindExpression: z.string().optional(), - statusCodeExpression: z.string().optional(), - statusMessageExpression: z.string().optional(), - sampleRateExpression: z.string().optional(), - spanEventsValueExpression: z.string().optional(), + .describe( + 'Trace sources. Number of decimal digits of a second in durationExpression ' + + 'values: 0 seconds, 3 milliseconds, 6 microseconds, 9 nanoseconds ' + + '(OTel Duration is nanoseconds). Defaults to 3 when omitted.', + ), + traceIdExpression: z + .string() + .optional() + .describe( + 'Expression for the trace ID, e.g. TraceId. Required for trace sources; ' + + 'on log sources it correlates logs with traces.', + ), + spanIdExpression: z + .string() + .optional() + .describe( + 'Expression for the span ID, e.g. SpanId. Required for trace sources; ' + + 'on log sources it correlates logs with spans.', + ), + parentSpanIdExpression: z + .string() + .optional() + .describe( + 'Trace sources (required). Expression for the parent span ID, e.g. ParentSpanId.', + ), + spanNameExpression: z + .string() + .optional() + .describe( + 'Trace sources (required). Expression for the span name, e.g. SpanName.', + ), + spanKindExpression: z + .string() + .optional() + .describe( + 'Trace sources (required). Expression for the span kind (client, server, internal, ...), e.g. SpanKind.', + ), + statusCodeExpression: z + .string() + .optional() + .describe( + 'Trace sources. Expression for the span status code, e.g. StatusCode.', + ), + statusMessageExpression: z + .string() + .optional() + .describe( + 'Trace sources. Expression for the span status message, e.g. StatusMessage.', + ), + sampleRateExpression: z + .string() + .optional() + .describe( + 'Trace sources. Column or expression for the upstream sampling weight ' + + '(1/N). When set, count, avg, sum, and quantile aggregations are ' + + 'corrected for sampling (percentiles become approximate). Omit if spans ' + + 'are not sampled.', + ), + spanEventsValueExpression: z + .string() + .optional() + .describe( + 'Trace sources. Expression for span events, e.g. Events. Expected type: ' + + 'Nested(Timestamp DateTime64(9), Name LowCardinality(String), ' + + 'Attributes Map(LowCardinality(String), String)).', + ), // ── Highlighted attribute expressions (advanced) ── - highlightedTraceAttributeExpressions: - highlightedAttributeExpressionsSchema.optional(), - highlightedRowAttributeExpressions: - highlightedAttributeExpressionsSchema.optional(), + highlightedTraceAttributeExpressions: highlightedAttributeExpressionsSchema + .optional() + .describe( + 'Log and trace sources. Trace-level attributes displayed in the trace ' + + 'view for the selected trace.', + ), + highlightedRowAttributeExpressions: highlightedAttributeExpressionsSchema + .optional() + .describe( + 'Log and trace sources. Row-level attributes displayed in the row side ' + + 'panel for the selected row.', + ), // ── Correlated source IDs ── - logSourceId: z.string().optional(), + logSourceId: z + .string() + .optional() + .describe( + 'Trace and metric sources. ID of the log source holding logs related to ' + + 'this data. Get IDs from clickstack_list_sources.', + ), traceSourceId: z .string() .optional() - .describe('Correlated trace source ID. Required for session sources.'), - metricSourceId: z.string().optional(), - sessionSourceId: z.string().optional(), + .describe( + 'ID of the trace source holding traces related to this data, used to ' + + 'link rows to their traces. Required for session sources; optional ' + + 'for log sources. Get IDs from clickstack_list_sources.', + ), + metricSourceId: z + .string() + .optional() + .describe( + 'Log and trace sources. ID of the metric source holding related ' + + 'metrics. Get IDs from clickstack_list_sources.', + ), + sessionSourceId: z + .string() + .optional() + .describe( + 'Trace sources. ID of the session source holding related session ' + + 'replays. Get IDs from clickstack_list_sources.', + ), // ── Metric ── metricTables: metricTablesSchema.optional(), - minAutoGranularity: z.string().optional(), + minAutoGranularity: z + .string() + .optional() + .describe( + 'Metric and promql sources. Floor for auto granularity on charts, as ' + + '" " with unit second, minute, hour, or day, e.g. "1 minute". ' + + 'Set it to the scrape/report interval to avoid sparse charts on short ' + + 'time ranges; explicit chart granularities are unaffected. PromQL ' + + 'sources also use it as the scrape interval for $__rate_interval. Omit ' + + 'for no minimum.', + ), // ── Materialized views (advanced; granularities use " " form) ── - materializedViews: materializedViewsSchema.optional(), - metadataMaterializedViews: metadataMaterializedViewsSchema.optional(), + materializedViews: materializedViewsSchema + .optional() + .describe( + 'Log and trace sources. Pre-aggregated materialized views used to speed ' + + 'up aggregation queries.', + ), + metadataMaterializedViews: metadataMaterializedViewsSchema + .optional() + .describe( + 'Log and trace sources. Rollup tables used for fast field discovery and ' + + 'value autocomplete in filters and search suggestions.', + ), }); export type McpSaveSourceInput = z.infer; diff --git a/packages/api/src/mcp/tools/trace/breakdownSchema.ts b/packages/api/src/mcp/tools/trace/breakdownSchema.ts index 097608422c..efe353fc91 100644 --- a/packages/api/src/mcp/tools/trace/breakdownSchema.ts +++ b/packages/api/src/mcp/tools/trace/breakdownSchema.ts @@ -11,10 +11,10 @@ export const traceBreakdownSchema = z.object({ .string() .max(4096) .describe( - 'SQL WHERE clause that selects the PARENT spans you want to break ' + - 'down. The tool finds the distinct TraceIds matching this filter, ' + - 'then aggregates all spans within those traces. ' + - 'Use SQL syntax (not Lucene). Example: ' + + 'SQL WHERE clause selecting the PARENT spans to break down. The tool ' + + 'finds the distinct TraceIds with a matching span in the window, then ' + + 'aggregates every other span in those traces; spans matching this ' + + 'filter are excluded from the result. SQL syntax only, not Lucene. Example: ' + "\"ServiceName = '' AND SpanName = ''\".\n\n" + 'SCOPE TO A SPECIFIC OPERATION, not just a service. A service-only ' + 'filter mixes every endpoint together and returns whatever has the ' + @@ -22,22 +22,23 @@ export const traceBreakdownSchema = z.object({ 'you want. Always include a SpanName (or another operation-level ' + 'discriminator). To compare two slow operations, call this tool ' + 'once per operation and diff the results — two operations with ' + - "similar p99 don't necessarily share a slow child.", + "similar p99 don't necessarily share a slow child. Do not combine " + + 'several operations in one filter.', ), startTime: z .string() - .describe('Start of the parent-filter time window as ISO 8601. REQUIRED.'), + .describe('Start of the parent-filter time window as ISO 8601.'), endTime: z .string() - .describe('End of the parent-filter time window as ISO 8601. REQUIRED.'), + .describe('End of the parent-filter time window as ISO 8601.'), minParentDurationMs: z .number() .min(0) .optional() .describe( - 'When set, only break down parent spans whose Duration ≥ this value. ' + - 'Use to focus the breakdown on slow parents (e.g. 1000 to only look ' + - 'at parents that took ≥ 1 second).', + 'Only break down parent spans whose duration is ≥ this many ms. Set it ' + + 'to the threshold above which a parent counts as slow (e.g. 1000 for ' + + 'parents that took ≥ 1 second).', ), topN: z .number() @@ -45,9 +46,7 @@ export const traceBreakdownSchema = z.object({ .max(100) .optional() .default(20) - .describe( - 'Number of top operations to return, ranked by total_time_ms DESC. Default 20.', - ), + .describe('Number of child operations to return, ranked by totalTimeMs.'), maxParentTraces: z .number() .min(100) @@ -56,55 +55,34 @@ export const traceBreakdownSchema = z.object({ .default(100_000) .describe( 'Safety cap on the number of distinct parent TraceIds considered. ' + - 'A breakdown over more than this many parent traces gets ' + - 'truncated to the first N. Default 100000.', + 'When more traces match, only this many are used.', ), }); export type TraceBreakdownInput = z.infer; export const TRACE_BREAKDOWN_DESCRIPTION = - 'Given a parent-span filter and a time window, return the child ' + - 'operations contributing the most cumulative time across all traces ' + - 'matching the parent filter. Same algorithm as the in-app ' + - '"Top Most Time Consuming Operations" chart on the service dashboard.\n\n' + - 'WHAT IT DOES (two-stage, runs as one SQL):\n' + - ' 1. Pick distinct TraceIds where the parent span matches ' + - '`parentFilter` in the window. Optionally restrict to ' + - '`minParentDurationMs` to focus on slow parents.\n' + - ' 2. Aggregate ALL spans across those traces (excluding the ' + - 'matching root span itself) by (ServiceName, SpanName), ranked by ' + - '`total_time_ms` DESC.\n\n' + - 'USE WHEN: investigating "where is the time going" for a slow ' + - 'operation. Filter to a specific (ServiceName, SpanName) pair and ' + - 'set `minParentDurationMs` to the threshold above which a parent ' + - 'span counts as "slow" for your investigation.\n\n' + - 'MULTIPLE OPERATIONS SLOW: when more than one operation shows ' + - 'elevated latency, call this tool ONCE PER (service, operation) ' + - 'and compare the top child rows across the result sets. Operations ' + - 'with the same top child likely share a cause; operations with ' + - 'different top children are independent regressions that happen ' + - 'to co-occur. DO NOT merge multiple operations into a single ' + - 'parentFilter — the cumulative rank then conflates independent ' + - 'investigations into one noisy answer.\n\n' + - 'RANKING METRIC: `total_time_ms = sum(Duration)` across all matching ' + - 'child spans. This captures the true contribution to elapsed time — ' + - 'a fast-but-frequent child can dominate the latency even if its p99 ' + - 'is unremarkable.\n\n' + - 'RETURNS: array of rows, each with `service`, `operation`, ' + - '`total_time_ms`, `calls`, `in_parents` (how many parent traces ' + - 'contained at least one such span), `p50_ms`, `p99_ms`. Plus a ' + - '`summary` block with the matched-parent count.\n\n' + - 'NEXT STEP after this tool: once a dominant slow child operation is ' + - 'identified, the canonical follow-up is clickstack_event_deltas with ' + - 'slow-vs-fast spans of THAT child operation as target/baseline ' + - "(target = {where: SpanName='' AND Duration > X}, " + - "baseline = {where: SpanName='' AND Duration <= Y}). " + - 'The ranked attributes surface what distinguishes slow invocations ' + - 'of the child operation from fast ones.\n\n' + - 'CROSS-SERVICE BREAKDOWN: this tool does NOT scope children to the ' + - "parent's service. Slow cross-service calls (database, cache, " + - 'upstream HTTP) surface naturally — useful for triage.\n\n' + - 'PAIR TOOL: clickstack_trace_waterfall returns ONE concrete trace as a ' + - "parent/child tree. Use it for an example after this tool's " + - 'aggregate breakdown has pointed you at the slow downstream operation.'; + 'Given a parent-span filter and a time window, rank the child operations ' + + '(ServiceName, SpanName) by cumulative time across all traces whose parent ' + + 'span matches. Same algorithm as the in-app "Top Most Time Consuming ' + + 'Operations" chart.\n\n' + + 'USE WHEN: asking "where is the time going" for a slow operation. Filter to ' + + 'one (ServiceName, SpanName) pair and set minParentDurationMs to the slow ' + + 'threshold.\n\n' + + 'MULTIPLE SLOW OPERATIONS: call this tool ONCE PER (service, operation) and ' + + 'compare the top children. A shared top child suggests a shared cause; ' + + 'different top children are independent regressions. DO NOT merge ' + + 'operations into one parentFilter — the ranking then conflates them.\n\n' + + 'RANKING: totalTimeMs = sum(Duration) of matching child spans, so a fast ' + + 'but frequent child can dominate even with an unremarkable p99. Children are ' + + "not scoped to the parent's service, so slow cross-service calls (database, " + + 'cache, upstream HTTP) show up.\n\n' + + 'RETURNS: operations[] with service, operation, totalTimeMs, calls, ' + + 'inParents (parent traces containing that operation), p50Ms, p99Ms, and ' + + 'shareOfTotalTime, plus a summary with operationsReturned, topN, and ' + + 'grandTotalTimeMs.\n\n' + + 'NEXT STEP: once a dominant slow child is found, run clickstack_event_deltas ' + + "on that child: target = {where: SpanName='' AND Duration > X}, " + + "baseline = {where: SpanName='' AND Duration <= X}.\n\n" + + 'PAIR TOOL: clickstack_trace_waterfall shows ONE concrete trace as a ' + + 'parent/child tree, for an example after this breakdown.'; diff --git a/packages/api/src/mcp/tools/trace/waterfall.ts b/packages/api/src/mcp/tools/trace/waterfall.ts index f59cb1eb18..234e3bc3f6 100644 --- a/packages/api/src/mcp/tools/trace/waterfall.ts +++ b/packages/api/src/mcp/tools/trace/waterfall.ts @@ -63,13 +63,13 @@ const traceSchema = z.object({ .enum(['lucene', 'sql']) .optional() .default('lucene') - .describe('Query language for pickFilter. Default: lucene'), + .describe('Language of pickFilter.'), pickBy: z .enum(['slowest', 'first_error', 'most_recent']) .optional() .default('slowest') .describe( - 'How to choose which trace to return when traceId is not provided.\n' + + 'How to choose the trace when traceId is not provided:\n' + ' slowest – trace with the longest single span (use for latency investigations)\n' + ' first_error – earliest trace containing a span with STATUS_CODE_ERROR\n' + ' most_recent – the most recent trace matching pickFilter', @@ -94,8 +94,8 @@ const traceSchema = z.object({ .optional() .default(500) .describe( - 'Cap on spans returned in the tree (1–2000). Default 500. ' + - 'A trace with more spans than this will be truncated; the response notes the truncation.', + 'Cap on spans returned in the tree. ' + + 'A larger trace is truncated and the response notes the truncation.', ), includeLogs: z .boolean() @@ -115,8 +115,8 @@ const traceSchema = z.object({ .optional() .default(100) .describe( - 'Cap on correlated log rows returned (1–1000). Default 100. Has no ' + - 'effect when includeLogs is false or the trace source has no logSourceId.', + 'Cap on correlated log rows returned. Has no effect when includeLogs ' + + 'is false or the trace source has no logSourceId.', ), }); @@ -312,37 +312,26 @@ export function registerTraceWaterfall({ title: 'Trace Waterfall (single trace)', annotations: { readOnlyHint: true }, description: - 'Fetch all spans in ONE trace and return them as a parent/child waterfall, ' + - 'pre-ordered for human-readable display. Use this for "show me a concrete ' + - 'example trace" or "what happened in trace X" investigations — the tool walks ' + - 'the cascade for you instead of forcing the model to write self-JOINs in raw SQL.\n\n' + - 'NOT THE RIGHT TOOL when the question is "where does the time go across MANY ' + - 'slow traces of operation X" — that is the aggregate question, and the answer ' + - 'is clickstack_trace_top_time_consuming_operations (called per affected ' + - '(service, operation) with `minParentDurationMs`). Use this tool only when you ' + - 'want a single concrete example to inspect, or after the aggregate breakdown ' + - 'has already identified a suspicious operation.\n\n' + + 'Fetch every span in ONE trace as a parent/child waterfall, pre-ordered for ' + + 'reading. Use it for "show me an example trace" or "what happened in trace X" ' + + "instead of writing TraceId self-JOINs in raw SQL; it uses the source's " + + 'configured trace, span, and parent-span ID expressions.\n\n' + + 'NOT FOR AGGREGATE QUESTIONS. "Where does the time go across many slow traces ' + + 'of operation X" is clickstack_trace_top_time_consuming_operations, called ' + + 'once per (service, operation) with minParentDurationMs. Use this tool for a ' + + 'single concrete example, typically after that breakdown has pointed at a ' + + 'suspicious operation.\n\n' + 'Two modes:\n' + - ' 1. Specific trace: pass `traceId`. Returns every span in that trace.\n' + - ' 2. Auto-pick: pass `pickFilter` + `pickBy`. The tool finds one matching trace ' + - '(slowest / first_error / most_recent) and returns its full tree.\n\n' + - 'Each returned span has: depth (root=0), spanId, parentSpanId, serviceName, ' + - 'spanName, spanKind, durationMs, statusCode, statusMessage, timestamp, and ' + - 'spanAttributes. Spans are pre-order DFS — child spans follow their parent in ' + - 'execution order. The tool also surfaces a `summary` section with the picked ' + - 'TraceId, total span count, and root span info.\n\n' + - 'When the trace source has a linked logSourceId (the standard config), the ' + - 'response also includes a `logs[]` array of correlated log rows that share ' + - 'the same TraceId — sorted by timestamp, each carrying its `spanId` so the ' + - 'agent can attribute messages to specific spans. Disable with `includeLogs:false`.\n\n' + - "Prefer this over running raw SQL with JOINs on TraceId — it uses the source's " + - 'configured traceIdExpression / parentSpanIdExpression / spanIdExpression so ' + - 'attribute extraction stays consistent with the rest of the platform.\n\n' + - 'PAIR TOOL: clickstack_trace_top_time_consuming_operations is the aggregate ' + - 'counterpart — given a parent-span filter, it ranks child operations by total ' + - 'time across MANY matching traces. Use that when the question is "where does ' + - 'time go in slow X" (aggregate), and use THIS tool when the question is "show ' + - 'me one example of a slow X" (single trace).', + ' 1. Specific trace: pass traceId.\n' + + ' 2. Auto-pick: omit traceId and pass pickFilter + pickBy; the tool picks one ' + + 'matching trace and returns its full tree.\n\n' + + 'Returns traceId, spanCount, totalDurationMs, rootSpan, and spans in ' + + 'pre-order DFS, children after their parent in execution order. Each span has ' + + 'depth (root=0), spanId, parentSpanId, serviceName, spanName, spanKind, ' + + 'durationMs, statusCode, statusMessage, timestamp, and spanAttributes.\n\n' + + 'If the trace source has a linked logSourceId, the response also has `logs[]`: ' + + 'log rows sharing the TraceId, sorted by timestamp, each with its spanId. ' + + 'Disable with includeLogs:false.', inputSchema: traceSchema, }, async (rawInput: TraceInput) => { diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index 0ead1cf350..7deb2e9d15 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -11,8 +11,6 @@ import { ChartPaletteTokenSchema, DASHBOARD_CONTAINER_ID_MAX, DASHBOARD_MAX_TILES, - MAX_TAG_LENGTH, - MAX_TAGS, MetricFormulaSchema, MetricsDataType, NumberFormatSchema, @@ -161,7 +159,7 @@ const chartSeriesSchema = z.discriminatedUnion('type', [ // Re-exported from common-utils so existing `@/utils/zod` importers keep working // while the canonical definition lives in the shared package. -export { MAX_TAG_LENGTH, MAX_TAGS, tagsSchema }; +export { tagsSchema }; const externalQueryExpressionFilterShape = QueryExpressionDashboardFilterSchema.omit({ source: true }).extend({ diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index bf21cf98fb..de49bcf747 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -342,16 +342,36 @@ export const ChartPaletteTokenSchema = z.enum(CHART_PALETTE_TOKENS); * Lives in common-utils so both the app and a future external-API parity * PR can import it. */ +const colorConditionColor = ChartPaletteTokenSchema.describe( + 'Palette color applied when this rule matches.', +); +const colorConditionLabel = z + .string() + .max(40) + .optional() + .describe('Short label describing the rule.'); + // Numeric ordered operators (gt | gte | lt | lte). const numericOrderedColorCondition = z.object({ - operator: z.enum(['gt', 'gte', 'lt', 'lte']), - value: z.number().finite(), - color: ChartPaletteTokenSchema, - label: z.string().max(40).optional(), + operator: z + .enum(['gt', 'gte', 'lt', 'lte']) + .describe( + 'Compares the raw query value (before numberFormat is applied) against ' + + '`value`: greater than, greater ' + + 'than or equal, less than, or less than or equal.', + ), + value: z + .number() + .finite() + .describe('Numeric bound the raw value is compared against.'), + color: colorConditionColor, + label: colorConditionLabel, }); const betweenColorCondition = z.object({ - operator: z.literal('between'), + operator: z + .literal('between') + .describe('Matches when the raw value falls within the `value` range.'), // A fixed-length array rather than `z.tuple([...])`: the MCP dashboard tools // (clickstack_save_dashboard / clickstack_patch_dashboard) expose this schema // as a tool `input_schema`, and `zod-to-json-schema` renders a tuple in the @@ -360,17 +380,26 @@ const betweenColorCondition = z.object({ // invalid and any strict draft-2020-12 client (e.g. the Anthropic API) rejects // the tool list outright. The wire format — `[min, max]` — is identical either // way, and matches the published `BetweenColorCondition` external-API schema. - value: z.array(z.number().finite()).length(2), - color: ChartPaletteTokenSchema, - label: z.string().max(40).optional(), + value: z + .array(z.number().finite()) + .length(2) + .describe('Inclusive [min, max] range.'), + color: colorConditionColor, + label: colorConditionLabel, }); // Equality against a number or a string value. const equalityColorCondition = z.object({ - operator: z.enum(['eq', 'neq']), - value: z.union([z.number().finite(), z.string().max(200)]), - color: ChartPaletteTokenSchema, - label: z.string().max(40).optional(), + operator: z + .enum(['eq', 'neq']) + .describe( + 'Matches when the raw value equals (eq) or does not equal (neq) `value`.', + ), + value: z + .union([z.number().finite(), z.string().max(200)]) + .describe('Number or string to compare the raw value with.'), + color: colorConditionColor, + label: colorConditionLabel, }); // String-match operators, kept at the schema level only for a future @@ -1679,8 +1708,10 @@ export type NumberTileColorCondition = z.infer< * external-API parity PR can import it. */ export const BackgroundChartSchema = z.object({ - type: z.enum(['line', 'area']), - color: ChartPaletteTokenSchema.optional(), + type: z.enum(['line', 'area']).describe('Sparkline shape.'), + color: ChartPaletteTokenSchema.optional().describe( + "Palette color for the sparkline. Inherits the tile's color when unset.", + ), }); export type BackgroundChart = z.infer; @@ -2185,24 +2216,59 @@ export const DASHBOARD_MAX_CONTAINERS = 50; export const DASHBOARD_MAX_TILES = 500; export const DashboardContainerTabSchema = z.object({ - id: z.string().min(1).max(DASHBOARD_CONTAINER_ID_MAX), - title: z.string().min(1).max(DASHBOARD_CONTAINER_TITLE_MAX), + id: z + .string() + .min(1) + .max(DASHBOARD_CONTAINER_ID_MAX) + .describe( + 'Tab identifier that tiles reference via tile.tabId. Unique within its container.', + ), + title: z + .string() + .min(1) + .max(DASHBOARD_CONTAINER_TITLE_MAX) + .describe('Label shown on the tab.'), }); export const DashboardContainerSchema = z.object({ - id: z.string().min(1).max(DASHBOARD_CONTAINER_ID_MAX), - title: z.string().min(1).max(DASHBOARD_CONTAINER_TITLE_MAX), - collapsed: z.boolean(), - // Whether the group can be collapsed (default true) - collapsible: z.boolean().optional(), - // Whether to show a border around the group (default true) - bordered: z.boolean().optional(), - // Optional tabs: 2+ entries → tab bar renders, 0-1 → plain group header. - // Tiles reference a specific tab via tabId. + id: z + .string() + .min(1) + .max(DASHBOARD_CONTAINER_ID_MAX) + .describe( + 'Container identifier that tiles reference via tile.containerId. Unique on the dashboard.', + ), + title: z + .string() + .min(1) + .max(DASHBOARD_CONTAINER_TITLE_MAX) + .describe('Heading shown on the container.'), + collapsed: z + .boolean() + .describe( + 'Whether the container starts collapsed when the dashboard opens. ' + + 'Viewers can still expand it; ignored when collapsible is false.', + ), + collapsible: z + .boolean() + .optional() + .describe( + 'Whether viewers can collapse the container. Treated as true when omitted.', + ), + bordered: z + .boolean() + .optional() + .describe( + 'Whether to draw a border around the container. Treated as true when omitted.', + ), tabs: z .array(DashboardContainerTabSchema) .max(DASHBOARD_CONTAINER_MAX_TABS) - .optional(), + .optional() + .describe( + 'Tabs inside the container. Two or more render as a tab bar; zero or ' + + 'one renders as a plain group header.', + ), }); export type DashboardContainer = z.infer;