From 31f97df002a76a073baf9e5280dccf5e75fbeff1 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:00:04 +0000 Subject: [PATCH] feat(api): SLO preview, save and delete MCP tools Adds three MCP tools, registered only when SLOs are enabled. clickstack_preview_slo dry runs a definition over its window without saving it: good, bad and excluded events, SLI, budget left, the number of groups for a grouped SLO, and the counts SQL. clickstack_save_slo creates or updates 1 to 20 SLOs, validating and saving each on its own so one failing item does not block the others, and reports an error per failed item. clickstack_delete_slo deletes an SLO with its burn alerts. They go through the same checks and team scoping as the SLO API. Co-Authored-By: Claude Opus 5.5 --- .changeset/slo-mcp.md | 15 ++ MCP.md | 3 + .../api/src/mcp/__tests__/slos.int.test.ts | 222 ++++++++++++++++++ packages/api/src/mcp/__tests__/slos.test.ts | 161 ++++++++++++- packages/api/src/mcp/tools/slos/deleteSlo.ts | 43 ++++ packages/api/src/mcp/tools/slos/index.ts | 6 + packages/api/src/mcp/tools/slos/previewSlo.ts | 129 ++++++++++ packages/api/src/mcp/tools/slos/saveSlo.ts | 128 ++++++++++ packages/api/src/mcp/tools/slos/schemas.ts | 59 +++++ packages/api/src/mcp/utils/errors.ts | 3 +- 10 files changed, 766 insertions(+), 3 deletions(-) create mode 100644 .changeset/slo-mcp.md create mode 100644 packages/api/src/mcp/__tests__/slos.int.test.ts create mode 100644 packages/api/src/mcp/tools/slos/deleteSlo.ts create mode 100644 packages/api/src/mcp/tools/slos/previewSlo.ts create mode 100644 packages/api/src/mcp/tools/slos/saveSlo.ts create mode 100644 packages/api/src/mcp/tools/slos/schemas.ts diff --git a/.changeset/slo-mcp.md b/.changeset/slo-mcp.md new file mode 100644 index 000000000..db4c50526 --- /dev/null +++ b/.changeset/slo-mcp.md @@ -0,0 +1,15 @@ +--- +'@hyperdx/api': patch +--- + +feat: SLO tools for MCP, registered when SLOs are enabled + +Lists SLOs as a summary from their stored status, optionally by state, or +returns one SLO with its definition, its status computed when asked (per +group for a grouped SLO), its alerts' states and a SQL where clause that +selects its bad events for `clickstack_search`, for one group when asked. +`clickstack_preview_slo` dry runs a definition (good, bad and excluded +events, SLI, budget left, group count and the counts SQL), +`clickstack_save_slo` creates or updates 1 to 20 SLOs with an error per +failed item, and `clickstack_delete_slo` deletes an SLO with its alerts. They +use the same checks and team scoping as the SLO pages. diff --git a/MCP.md b/MCP.md index b2f7a715d..f9f3f82fe 100644 --- a/MCP.md +++ b/MCP.md @@ -162,6 +162,9 @@ with: | `clickstack_get_alert` | List alerts (summary) or get full detail with evaluation history; filter by state | | `clickstack_save_alert` | Create a new alert or update an existing one | | `clickstack_get_slo` | List SLOs (summary) or get one with its status, per group for a grouped SLO, and a SQL where clause for its bad events. Only registered when SLOs are enabled | +| `clickstack_preview_slo` | Dry run an SLO definition: good, bad and excluded events, SLI, budget left, group count and the counts SQL. Only registered when SLOs are enabled | +| `clickstack_save_slo` | Create or update 1 to 20 SLOs, each validated and saved on its own, with an error per failed item. Only registered when SLOs are enabled | +| `clickstack_delete_slo` | Permanently delete an SLO and its burn alerts. Only registered when SLOs are enabled | | `clickstack_trace_waterfall` | Fetch all spans in a single trace as a parent/child waterfall tree with optional correlated logs | | `clickstack_trace_top_time_consuming_ops` | Aggregate breakdown of child operations by cumulative time across matching parent traces | | `clickstack_get_webhook` | List available webhook destinations for use as alert notification channels | diff --git a/packages/api/src/mcp/__tests__/slos.int.test.ts b/packages/api/src/mcp/__tests__/slos.int.test.ts new file mode 100644 index 000000000..7b1bf4d43 --- /dev/null +++ b/packages/api/src/mcp/__tests__/slos.int.test.ts @@ -0,0 +1,222 @@ +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import mongoose from 'mongoose'; + +import * as config from '@/config'; +import { + bulkInsertData, + DEFAULT_DATABASE, + DEFAULT_TRACES_TABLE, + getLoggedInAgent, + getServer, +} from '@/fixtures'; +import type { McpContext } from '@/mcp/tools/types'; +import Alert, { AlertSource } from '@/models/alert'; +import Connection from '@/models/connection'; +import Slo from '@/models/slo'; +import { Source } from '@/models/source'; +import Webhook from '@/models/webhook'; + +import { callTool, createTestClient, getFirstText } from './mcpTestUtils'; + +// ClickHouse is shared across tests and files, so scope the spans to this run. +const SERVICE = `mcp-slo-${Date.now()}`; + +describe('MCP SLO write tools', () => { + const server = getServer(); + let client: Client; + let teamId: string; + let sourceId: string; + let webhookId: string; + let slosEnabled: jest.ReplaceProperty; + + const definition = (overrides: Record = {}) => ({ + name: 'Checkout availability', + source: sourceId, + indicator: { + template: 'availability', + eligible: { + where: `startsWith(ServiceName, '${SERVICE}-')`, + whereLanguage: 'sql', + }, + good: "StatusCode != 'Error'", + }, + target: 99, + window: '7d', + ...overrides, + }); + + const call = async (name: string, args: Record) => { + const result = await callTool(client, name, args); + return { isError: result.isError, text: getFirstText(result) }; + }; + + beforeAll(async () => { + await server.start(); + const now = Date.now(); + // One service with every span good, one with a fifth of them bad. + await bulkInsertData( + `${DEFAULT_DATABASE}.${DEFAULT_TRACES_TABLE}`, + [`${SERVICE}-a`, `${SERVICE}-b`].flatMap((service, s) => + Array.from({ length: 50 }, (_, i) => ({ + Timestamp: new Date(now - (i + 1) * 60_000), + TraceId: `${service}-trace-${i}`, + SpanId: `${service}-span-${i}`, + ParentSpanId: '', + SpanName: 'POST /checkout', + SpanKind: 'Server', + ServiceName: service, + Duration: 100 * 1e6, + StatusCode: s === 1 && i < 10 ? 'Error' : 'Ok', + StatusMessage: '', + SpanAttributes: {}, + ResourceAttributes: {}, + })), + ), + ); + }); + + beforeEach(async () => { + slosEnabled = jest.replaceProperty(config, 'IS_SLOS_ENABLED', true); + const { team, user } = await getLoggedInAgent(server); + teamId = team._id.toString(); + const connection = await Connection.create({ + team: team._id, + name: 'Default', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + const source = await Source.create({ + kind: SourceKind.Trace, + team: team._id, + from: { databaseName: DEFAULT_DATABASE, tableName: DEFAULT_TRACES_TABLE }, + timestampValueExpression: 'Timestamp', + connection: connection._id, + name: 'Traces', + traceIdExpression: 'TraceId', + spanIdExpression: 'SpanId', + parentSpanIdExpression: 'ParentSpanId', + spanNameExpression: 'SpanName', + spanKindExpression: 'SpanKind', + durationExpression: 'Duration', + durationPrecision: 9, + statusCodeExpression: 'StatusCode', + }); + sourceId = source._id.toString(); + const webhook = await Webhook.create({ + name: 'On call', + service: 'generic', + url: 'https://example.com/hook', + team: team._id, + }); + webhookId = webhook._id.toString(); + const context: McpContext = { teamId, userId: user._id.toString() }; + client = await createTestClient(context); + }); + + afterEach(async () => { + await client?.close(); + slosEnabled.restore(); + await server.clearDBs(); + }); + + afterAll(async () => { + await server.stop(); + }); + + it('previews a grouped definition from the source', async () => { + const { isError, text } = await call('clickstack_preview_slo', { + definition: definition({ name: undefined, groupBy: 'ServiceName' }), + }); + expect(isError).toBeFalsy(); + expect(JSON.parse(text)).toMatchObject({ + eligible: 100, + good: 90, + bad: 10, + sli: 0.9, + groupCount: 2, + trackedGroups: 2, + sql: expect.stringContaining('countIf'), + }); + expect(await Slo.countDocuments()).toBe(0); + }); + + it('saves a batch with the checks of the SLO pages, then updates and deletes', async () => { + const saved = JSON.parse( + ( + await call('clickstack_save_slo', { + slos: [ + definition({ + groupBy: 'ServiceName', + alerts: { + fastBurn: { channels: [{ type: 'webhook', webhookId }] }, + }, + }), + // ClickHouse rejects the condition, so this one is not saved. + definition({ + name: 'Typo', + indicator: { + ...definition().indicator, + good: "StatusCod != 'Error'", + }, + }), + ], + }) + ).text, + ); + expect(saved).toMatchObject({ saved: 1, failed: 1 }); + expect(saved.results[1]).toMatchObject({ + index: 1, + ok: false, + error: expect.stringContaining('StatusCod'), + }); + const id = saved.results[0].id; + const slo = await Slo.findById(id).lean(); + expect(slo).toMatchObject({ + name: 'Checkout availability', + groupBy: 'ServiceName', + }); + expect(slo?.team.toString()).toBe(teamId); + expect( + await Alert.countDocuments({ slo: id, source: AlertSource.SLO }), + ).toBe(1); + + // An update replaces the definition: without alerts, the alert goes. + const updated = JSON.parse( + ( + await call('clickstack_save_slo', { + slos: [definition({ id, name: 'Checkout success' })], + }) + ).text, + ); + expect(updated.results[0]).toMatchObject({ ok: true, id }); + expect((await Slo.findById(id).lean())?.name).toBe('Checkout success'); + expect(await Alert.countDocuments({ slo: id })).toBe(0); + + expect( + JSON.parse((await call('clickstack_delete_slo', { id })).text), + ).toEqual({ deleted: true, id }); + expect(await Slo.exists({ _id: id })).toBeNull(); + }); + + it("leaves another team's SLO alone", async () => { + const other = await Slo.create({ + ...definition(), + source: new mongoose.Types.ObjectId(), + team: new mongoose.Types.ObjectId(), + }); + const id = other._id.toString(); + const deleted = await call('clickstack_delete_slo', { id }); + expect(deleted.isError).toBe(true); + expect(deleted.text).toContain('SLO not found'); + const updated = JSON.parse( + (await call('clickstack_save_slo', { slos: [definition({ id })] })).text, + ); + expect(updated.results[0]).toMatchObject({ + ok: false, + error: 'SLO not found', + }); + expect(await Slo.exists({ _id: id })).toBeTruthy(); + }); +}); diff --git a/packages/api/src/mcp/__tests__/slos.test.ts b/packages/api/src/mcp/__tests__/slos.test.ts index e3fd15744..7c14f469f 100644 --- a/packages/api/src/mcp/__tests__/slos.test.ts +++ b/packages/api/src/mcp/__tests__/slos.test.ts @@ -1,10 +1,19 @@ import { Types } from 'mongoose'; import * as config from '@/config'; -import { getSlo, getSloQueryContext, listSlos } from '@/controllers/slo'; +import { + createSlo, + deleteSlo, + getSlo, + getSloQueryContext, + listSlos, + runSloQuery, + updateSlo, +} from '@/controllers/slo'; import { getSloAlerts } from '@/controllers/sloAlert'; import { computeSloStatusNow } from '@/controllers/sloStatus'; import { AlertState } from '@/models/alert'; +import { Api400Error } from '@/utils/errors'; import { callTool, createTestClient, getFirstText } from './mcpTestUtils'; @@ -13,6 +22,10 @@ jest.mock('@/controllers/slo', () => ({ listSlos: jest.fn(), getSlo: jest.fn(), getSloQueryContext: jest.fn(), + runSloQuery: jest.fn(), + createSlo: jest.fn(), + updateSlo: jest.fn(), + deleteSlo: jest.fn(), })); jest.mock('@/controllers/sloAlert', () => ({ getSloAlerts: jest.fn() })); jest.mock('@/controllers/sloStatus', () => ({ @@ -91,7 +104,12 @@ describe('MCP SLO tool', () => { afterEach(() => slosEnabled.restore()); it('is only registered while SLOs are enabled', async () => { - const slosTools = ['clickstack_get_slo']; + const slosTools = [ + 'clickstack_get_slo', + 'clickstack_preview_slo', + 'clickstack_save_slo', + 'clickstack_delete_slo', + ]; expect(await toolNames()).toEqual(expect.arrayContaining(slosTools)); slosEnabled.replaceValue(false); const names = await toolNames(); @@ -225,4 +243,143 @@ describe('MCP SLO tool', () => { expect(unknown.isError).toBe(true); expect(getFirstText(unknown)).toContain('SLO not found'); }); + + describe('write tools', () => { + // Call counts start from zero; the stubs set up above stay. + beforeEach(() => jest.clearAllMocks()); + + const definition = { + name: 'Checkout availability', + source: new Types.ObjectId().toString(), + indicator: { + template: 'availability', + eligible: { where: "SpanKind = 'Server'", whereLanguage: 'sql' }, + good: "StatusCode != 'Error'", + }, + target: 99.5, + window: '30d', + }; + + it('saves each SLO of a batch on its own and says which failed', async () => { + const created = new Types.ObjectId(); + jest + .mocked(createSlo) + .mockResolvedValueOnce({ ...slo, _id: created }) + .mockRejectedValueOnce( + new Api400Error("The SLO's query failed: Unknown identifier"), + ); + jest.mocked(updateSlo).mockResolvedValueOnce(null); + const result = await callTool(await connect(), 'clickstack_save_slo', { + slos: [ + definition, + { + ...definition, + target: 100, + indicator: { ...definition.indicator, good: '' }, + }, + { ...definition, name: 'Broken query' }, + { ...definition, id: new Types.ObjectId().toString() }, + { ...definition, id: 'nope' }, + ], + }); + const body = JSON.parse(getFirstText(result)); + expect(body).toMatchObject({ saved: 1, failed: 4 }); + expect(body.results).toEqual([ + expect.objectContaining({ index: 0, ok: true, id: created.toString() }), + { + index: 1, + ok: false, + error: 'Invalid SLO definition', + issues: expect.arrayContaining([ + { + path: 'indicator.good', + message: 'A good-event condition is required', + }, + { path: 'target', message: 'Target must be below 100%' }, + ]), + }, + { + index: 2, + ok: false, + error: "The SLO's query failed: Unknown identifier", + }, + { index: 3, ok: false, error: 'SLO not found' }, + { index: 4, ok: false, error: 'Invalid SLO ID' }, + ]); + // For the calling team and user, with the schema's defaults. + expect(createSlo).toHaveBeenCalledWith( + slo.team.toString(), + 'user-id', + expect.objectContaining({ version: 1, tags: [], target: 99.5 }), + ); + }); + + it('deletes an SLO of the calling team', async () => { + const id = sloId.toString(); + jest + .mocked(deleteSlo) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(false); + const client = await connect(); + const deleted = await callTool(client, 'clickstack_delete_slo', { id }); + expect(JSON.parse(getFirstText(deleted))).toEqual({ deleted: true, id }); + expect(deleteSlo).toHaveBeenCalledWith(slo.team.toString(), id); + const missing = await callTool(client, 'clickstack_delete_slo', { id }); + expect(missing.isError).toBe(true); + expect(getFirstText(missing)).toContain('SLO not found'); + }); + + it('previews a definition over its window without saving it', async () => { + // Enough metadata to render the counts query's SQL. + const metadata = { + getColumns: jest.fn().mockResolvedValue([]), + getMaterializedColumnsLookupTable: jest.fn().mockResolvedValue(null), + getColumn: jest.fn().mockResolvedValue(undefined), + getTableMetadata: jest + .fn() + .mockResolvedValue({ primary_key: 'Timestamp' }), + getSkipIndices: jest.fn().mockResolvedValue([]), + getSetting: jest.fn().mockResolvedValue(undefined), + isClickHouseCloud: jest.fn().mockResolvedValue(false), + }; + jest + .mocked(getSloQueryContext) + .mockResolvedValue({ ...queryContext, metadata }); + jest.mocked(runSloQuery).mockImplementation(async (_ctx, config) => { + const aliases = JSON.stringify(config.select); + const rows = aliases.includes('slo_group_count') + ? [{ slo_group_count: '120' }] + : aliases.includes('slo_eligible') + ? [{ slo_eligible: '1000', slo_good: '990' }] + : [{ slo_total: '1500' }]; + return { rows, rowsRead: 0, durationMs: 0 }; + }); + const client = await connect(); + const { name: _name, ...unnamed } = definition; + const result = await callTool(client, 'clickstack_preview_slo', { + definition: { ...unnamed, groupBy: 'ServiceName' }, + }); + expect(JSON.parse(getFirstText(result))).toEqual( + expect.objectContaining({ + eligible: 1000, + good: 990, + bad: 10, + excluded: 500, + sli: 0.99, + // 10 bad events against a budget of 5. + budgetRemaining: expect.closeTo(-1), + groupCount: 120, + trackedGroups: 100, + sql: expect.stringContaining("StatusCode != 'Error'"), + }), + ); + expect(createSlo).not.toHaveBeenCalled(); + + const invalid = await callTool(client, 'clickstack_preview_slo', { + definition: { ...definition, window: '90d' }, + }); + expect(invalid.isError).toBe(true); + expect(getFirstText(invalid)).toContain('window'); + }); + }); }); diff --git a/packages/api/src/mcp/tools/slos/deleteSlo.ts b/packages/api/src/mcp/tools/slos/deleteSlo.ts new file mode 100644 index 000000000..850aa71eb --- /dev/null +++ b/packages/api/src/mcp/tools/slos/deleteSlo.ts @@ -0,0 +1,43 @@ +import { z } from 'zod/v3'; + +import { deleteSlo } from '@/controllers/slo'; +import { IDEMPOTENT_DESTRUCTIVE_TOOL } from '@/mcp/tools/annotations'; +import type { ToolRegistrar } from '@/mcp/tools/types'; +import { mcpUserError } from '@/mcp/utils/errors'; +import { objectIdSchema } from '@/utils/zod'; + +export function registerDeleteSlo({ + context, + registerTool, +}: ToolRegistrar): void { + const { teamId } = context; + + registerTool( + 'clickstack_delete_slo', + { + title: 'Delete SLO', + annotations: IDEMPOTENT_DESTRUCTIVE_TOOL, + description: + 'Permanently delete an SLO by ID, together with its burn alerts. ' + + 'Use clickstack_get_slo (without an ID) to list SLO IDs.', + inputSchema: z.object({ + id: objectIdSchema.describe( + 'ID of the SLO to delete, from clickstack_get_slo.', + ), + }), + }, + async ({ id }) => { + if (!(await deleteSlo(teamId, id))) { + return mcpUserError('SLO not found'); + } + return { + content: [ + { + type: 'text' as const, + text: JSON.stringify({ deleted: true, id }, null, 2), + }, + ], + }; + }, + ); +} diff --git a/packages/api/src/mcp/tools/slos/index.ts b/packages/api/src/mcp/tools/slos/index.ts index f5736cc68..8a1e1dcf2 100644 --- a/packages/api/src/mcp/tools/slos/index.ts +++ b/packages/api/src/mcp/tools/slos/index.ts @@ -1,9 +1,15 @@ import type { ToolDefinition, ToolRegistrar } from '@/mcp/tools/types'; +import { registerDeleteSlo } from './deleteSlo'; import { registerGetSlo } from './getSlo'; +import { registerPreviewSlo } from './previewSlo'; +import { registerSaveSlo } from './saveSlo'; const slosTools: ToolDefinition = (registrar: ToolRegistrar) => { registerGetSlo(registrar); + registerPreviewSlo(registrar); + registerSaveSlo(registrar); + registerDeleteSlo(registrar); }; export default slosTools; diff --git a/packages/api/src/mcp/tools/slos/previewSlo.ts b/packages/api/src/mcp/tools/slos/previewSlo.ts new file mode 100644 index 000000000..d41342323 --- /dev/null +++ b/packages/api/src/mcp/tools/slos/previewSlo.ts @@ -0,0 +1,129 @@ +import { parameterizedQueryToSql } from '@hyperdx/common-utils/dist/clickhouse'; +import { renderChartConfig } from '@hyperdx/common-utils/dist/core/renderChartConfig'; +import { + buildSloCountsChartConfig, + buildSloGroupCountChartConfig, + buildSloSourceTotalChartConfig, + getSloGroupBy, + getSloWindowRange, + parseSloCountsRow, + parseSloGroupCountRow, + parseSloTotalRow, +} from '@hyperdx/common-utils/dist/core/slo'; +import { computeSloStats } from '@hyperdx/common-utils/dist/core/sloStats'; +import { SLO_MAX_GROUPS } from '@hyperdx/common-utils/dist/slo'; +import mongoose from 'mongoose'; + +import { getSloQueryContext, runSloQuery } from '@/controllers/slo'; +import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; +import type { ToolRegistrar } from '@/mcp/tools/types'; +import { formatZodIssues, mcpUserError } from '@/mcp/utils/errors'; +import { getClickHouseErrorType } from '@/utils/clickhouseErrors'; +import { BaseError } from '@/utils/errors'; + +import { mcpPreviewSloSchema, SloPreviewDefinitionSchema } from './schemas'; + +/** Bounds each preview query, as for one SLO's detail. */ +const SLO_PREVIEW_TIMEOUT_MS = 30_000; + +export function registerPreviewSlo({ + context, + registerTool, +}: ToolRegistrar): void { + const { teamId } = context; + + registerTool( + 'clickstack_preview_slo', + { + title: 'Preview SLO', + annotations: READ_ONLY_TOOL, + description: + 'Dry run an SLO definition over its window without saving it, like ' + + 'the preview in the SLO builder: eligible, good and bad events, ' + + 'excluded events (in the source but not eligible), the SLI, the ' + + 'error budget left, the number of groups for a group-by, and the SQL ' + + 'of the counts query. Use it before clickstack_save_slo to check ' + + 'that the conditions select the events you expect.', + inputSchema: mcpPreviewSloSchema, + }, + async ({ definition }) => { + const parsed = SloPreviewDefinitionSchema.safeParse(definition); + if (!parsed.success) { + return mcpUserError( + `Invalid SLO definition:\n${formatZodIssues(parsed.error)}`, + ); + } + const slo = parsed.data; + if (!mongoose.Types.ObjectId.isValid(slo.source)) { + return mcpUserError('Invalid source ID'); + } + try { + const ctx = await getSloQueryContext( + teamId, + slo.source, + SLO_PREVIEW_TIMEOUT_MS, + ); + const { source } = ctx; + const dateRange = getSloWindowRange(slo.window, new Date()); + const groupBy = getSloGroupBy(slo); + const counts = buildSloCountsChartConfig({ slo, source, dateRange }); + const run = (config: Parameters[1]) => + runSloQuery(ctx, config, SLO_PREVIEW_TIMEOUT_MS); + const [countRows, totalRows, groupRows, sql] = await Promise.all([ + run(counts), + run(buildSloSourceTotalChartConfig({ source, dateRange })), + groupBy != null + ? run( + buildSloGroupCountChartConfig({ + slo: { ...slo, groupBy }, + source, + dateRange, + }), + ) + : undefined, + renderChartConfig(counts, ctx.metadata, source.querySettings), + ]); + const stats = computeSloStats( + parseSloCountsRow(countRows.rows), + [], + slo.target, + ); + const groupCount = + groupRows != null ? parseSloGroupCountRow(groupRows.rows) : null; + const result = { + windowStart: dateRange[0].toISOString(), + windowEnd: dateRange[1].toISOString(), + eligible: stats.eligible, + good: stats.good, + bad: stats.bad, + excluded: Math.max( + 0, + parseSloTotalRow(totalRows.rows) - stats.eligible, + ), + sli: stats.sli, + budgetRemaining: stats.budgetRemaining, + ...(groupCount != null + ? { + groupCount, + trackedGroups: Math.min(groupCount, SLO_MAX_GROUPS), + } + : {}), + sql: parameterizedQueryToSql(sql), + }; + return { + content: [ + { type: 'text' as const, text: JSON.stringify(result, null, 2) }, + ], + }; + } catch (e) { + // A missing source or connection, or a condition ClickHouse rejects, + // is the caller's to fix. + if (e instanceof BaseError) return mcpUserError(e.name); + if (getClickHouseErrorType(e) != null && e instanceof Error) { + return mcpUserError(`The SLO's query failed: ${e.message}`); + } + throw e; + } + }, + ); +} diff --git a/packages/api/src/mcp/tools/slos/saveSlo.ts b/packages/api/src/mcp/tools/slos/saveSlo.ts new file mode 100644 index 000000000..031e4a3c7 --- /dev/null +++ b/packages/api/src/mcp/tools/slos/saveSlo.ts @@ -0,0 +1,128 @@ +import { SloInputSchema } from '@hyperdx/common-utils/dist/slo'; +import mongoose from 'mongoose'; + +import * as config from '@/config'; +import { createSlo, updateSlo } from '@/controllers/slo'; +import { OPEN_WORLD_UPSERT_TOOL } from '@/mcp/tools/annotations'; +import type { ToolRegistrar } from '@/mcp/tools/types'; +import { formatZodPath } from '@/mcp/utils/errors'; +import { BaseError } from '@/utils/errors'; +import logger from '@/utils/logger'; + +import { mcpSaveSloSchema } from './schemas'; + +type SaveResult = + | { index: number; ok: true; id: string; url?: string } + | { + index: number; + ok: false; + error: string; + issues?: { path: string; message: string }[]; + }; + +export function registerSaveSlo({ + context, + registerTool, +}: ToolRegistrar): void { + const { teamId, userId } = context; + const frontendUrl = config.FRONTEND_URL; + + /** Validates and saves one SLO; never throws, so the batch goes on. */ + const saveOne = async ( + index: number, + item: Record, + ): Promise => { + const { id, ...definition } = item; + if ( + id != null && + (typeof id !== 'string' || !mongoose.Types.ObjectId.isValid(id)) + ) { + return { index, ok: false, error: 'Invalid SLO ID' }; + } + const parsed = SloInputSchema.safeParse(definition); + if (!parsed.success) { + return { + index, + ok: false, + error: 'Invalid SLO definition', + issues: parsed.error.errors.map(issue => ({ + path: formatZodPath(issue.path), + message: issue.message, + })), + }; + } + if (!mongoose.Types.ObjectId.isValid(parsed.data.source)) { + return { + index, + ok: false, + error: 'Invalid SLO definition', + issues: [{ path: 'source', message: 'Invalid source ID' }], + }; + } + try { + const saved = + typeof id === 'string' + ? await updateSlo(teamId, id, userId, parsed.data) + : await createSlo(teamId, userId, parsed.data); + if (!saved) return { index, ok: false, error: 'SLO not found' }; + const savedId = saved._id.toString(); + return { + index, + ok: true, + id: savedId, + ...(frontendUrl ? { url: `${frontendUrl}/slos/${savedId}` } : {}), + }; + } catch (e) { + // Api400Error and the other BaseErrors keep their message in `name`. + if (e instanceof BaseError) return { index, ok: false, error: e.name }; + // Reported on the item rather than thrown: earlier items are saved, + // and a failed call would make the caller create them again. + logger.error({ error: e, teamId }, 'Failed to save an SLO from MCP'); + return { + index, + ok: false, + error: e instanceof Error ? e.message : String(e), + }; + } + }; + + registerTool( + 'clickstack_save_slo', + { + title: 'Create or Update SLOs', + annotations: OPEN_WORLD_UPSERT_TOOL, + description: + 'Create or update service level objectives, 1 to 20 per call. An ' + + 'item with "id" replaces the definition of that SLO (send every ' + + 'field you want to keep; read it with clickstack_get_slo first); an item ' + + 'without "id" creates an SLO. Each item is validated and saved on ' + + 'its own, with the same checks as the SLO builder: the query must ' + + 'run on the source and alert channels must exist. The result lists ' + + '{ index, ok, id, url } or { index, ok: false, error, issues } per ' + + 'item, where issues name the fields at fault, so fix and retry only ' + + 'the failed items. Check new definitions with clickstack_preview_slo ' + + 'first.', + inputSchema: mcpSaveSloSchema, + }, + async ({ slos }) => { + const results: SaveResult[] = []; + // One at a time, so the team's SLO limit counts the earlier items. + for (const [index, item] of slos.entries()) { + results.push(await saveOne(index, item)); + } + const failed = results.filter(r => !r.ok).length; + return { + content: [ + { + type: 'text' as const, + text: JSON.stringify( + { saved: results.length - failed, failed, results }, + null, + 2, + ), + }, + ], + }; + }, + ); +} diff --git a/packages/api/src/mcp/tools/slos/schemas.ts b/packages/api/src/mcp/tools/slos/schemas.ts new file mode 100644 index 000000000..3852ab407 --- /dev/null +++ b/packages/api/src/mcp/tools/slos/schemas.ts @@ -0,0 +1,59 @@ +import { SloInputSchema } from '@hyperdx/common-utils/dist/slo'; +import { z } from 'zod/v3'; + +/** How an SLO is written, for the save and preview tool descriptions. */ +const SLO_DEFINITION_GUIDE = + 'Fields: name; description; tags (strings); source (ID of a log or trace ' + + 'source, from clickstack_list_sources); indicator { template: ' + + '"availability" | "latency"; eligible { where, whereLanguage: "sql" | ' + + '"lucene" } (the events that count; an empty where counts every event ' + + 'in the source); good (availability only: the SQL condition a good event ' + + "matches, e.g. StatusCode != 'Error'; NULL counts as bad); latency " + + '(latency only: { expression (the duration column or expression, e.g. ' + + 'Duration), unit: "ns" | "us" | "ms" | "s", thresholdMs (events at or ' + + 'under it are good), numeric (true for a numeric duration column; ' + + 'otherwise the value is cast), requireDuration (default true: events ' + + 'without a duration are left out; false counts them as bad) }) }; ' + + 'target (percentage of good events, e.g. 99.9); window ("7d" or "30d", ' + + 'rolling); groupBy (optional SQL expression such as ServiceName: each ' + + 'value gets its own SLI, error budget and alerts, and the 100 values with ' + + 'the most events are tracked); alerts (optional { fastBurn, slowBurn }, ' + + 'each null for off or { channels: [{ type: "webhook", webhookId }] } ' + + 'with webhook IDs from clickstack_get_webhook: fastBurn notifies when 2% ' + + 'of the error budget is spent within 1 hour, slowBurn when 5% is spent ' + + 'within 6 hours; each notifies once when it starts and once when it ' + + 'resolves).'; + +// Items stay loose: the MCP SDK validates the whole call before the handler +// runs, so a strict schema would reject the batch instead of saying which +// items failed. The handlers parse each definition with SloInputSchema. +const definitionSchema = z.record(z.string(), z.unknown()); + +export const mcpSaveSloSchema = z.object({ + slos: z + .array( + definitionSchema.describe( + 'One SLO. Include "id" to update that SLO (the definition is ' + + 'replaced, not merged), omit it to create one. ' + + SLO_DEFINITION_GUIDE, + ), + ) + .min(1) + .max(20) + .describe( + 'Between 1 and 20 SLOs, each validated and saved on its own, so one ' + + 'failing item does not block the others.', + ), +}); + +export const mcpPreviewSloSchema = z.object({ + definition: definitionSchema.describe( + 'The SLO to preview, as for clickstack_save_slo; name and alerts are ' + + `not needed. ${SLO_DEFINITION_GUIDE}`, + ), +}); + +/** A definition to preview: no name needed, and the alerts play no part. */ +export const SloPreviewDefinitionSchema = SloInputSchema.omit({ + alerts: true, +}).extend({ name: z.string().max(256).optional() }); diff --git a/packages/api/src/mcp/utils/errors.ts b/packages/api/src/mcp/utils/errors.ts index 0c43543b9..b11d8ad0c 100644 --- a/packages/api/src/mcp/utils/errors.ts +++ b/packages/api/src/mcp/utils/errors.ts @@ -84,7 +84,8 @@ export function sanitizeFetchError(e: unknown): string { return message.replace(/\s+/g, ' ').trim().slice(0, 200); } -function formatZodPath(path: (string | number)[]): string { +/** A Zod issue path as one string, e.g. `indicator.latency.unit`. */ +export function formatZodPath(path: (string | number)[]): string { return path .map((segment, index) => typeof segment === 'number'