diff --git a/MCP.md b/MCP.md index d836b6a40..b2f7a715d 100644 --- a/MCP.md +++ b/MCP.md @@ -161,6 +161,7 @@ with: | `clickstack_save_saved_search` | Create or update a saved search (reusable query against a data source) | | `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_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/controllers/sloStatus.ts b/packages/api/src/controllers/sloStatus.ts index 58bb30556..e6e4a8f08 100644 --- a/packages/api/src/controllers/sloStatus.ts +++ b/packages/api/src/controllers/sloStatus.ts @@ -9,13 +9,14 @@ import { } from '@hyperdx/common-utils/dist/core/sloStats'; import type { SloStatus } from '@hyperdx/common-utils/dist/slo'; -import { getSloQueryContext } from '@/controllers/slo'; +import { getSloQueryContext, SloQueryContext } from '@/controllers/slo'; import { buildSloStatus, computeSloBurn, computeSloWindow, hasSloQueryTime, type SloBurnNumbers, + type SloDefinitionFields, SloQueryDeadlineError, type SloWindowNumbers, } from '@/controllers/sloStatusQueries'; @@ -54,6 +55,25 @@ const refreshCounter = getCounter('hyperdx.slo.refresh', { description: 'SLO status refreshes, by outcome', }); +/** + * The SLO's numbers as of now, for one SLO someone asked for. Not stored: + * the background refresh keeps the stored snapshot for lists. + */ +export async function computeSloStatusNow( + slo: SloDefinitionFields, + ctx: SloQueryContext, + now = new Date(), +): Promise { + const window = await computeSloWindow(slo, ctx, now); + const burn = await computeSloBurn( + slo, + ctx, + now, + window.groups?.map(g => g.value), + ); + return buildSloStatus(slo, window, burn, now.toISOString(), now); +} + /** * Stores the burn numbers an SLO's alert check computed, so the list shows * the alert's own verdict: for an ungrouped SLO its burn numbers, for a diff --git a/packages/api/src/controllers/sloStatusQueries.ts b/packages/api/src/controllers/sloStatusQueries.ts index cc22c0905..d90d3545f 100644 --- a/packages/api/src/controllers/sloStatusQueries.ts +++ b/packages/api/src/controllers/sloStatusQueries.ts @@ -34,7 +34,7 @@ import type { ISlo } from '@/models/slo'; const SLO_QUERY_TIMEOUT_MS = 30_000; const SLO_MIN_QUERY_MS = 5_000; -type SloDefinitionFields = Pick< +export type SloDefinitionFields = Pick< ISlo, 'indicator' | 'target' | 'window' | 'groupBy' >; diff --git a/packages/api/src/mcp/__tests__/slos.test.ts b/packages/api/src/mcp/__tests__/slos.test.ts new file mode 100644 index 000000000..e3fd15744 --- /dev/null +++ b/packages/api/src/mcp/__tests__/slos.test.ts @@ -0,0 +1,228 @@ +import { Types } from 'mongoose'; + +import * as config from '@/config'; +import { getSlo, getSloQueryContext, listSlos } from '@/controllers/slo'; +import { getSloAlerts } from '@/controllers/sloAlert'; +import { computeSloStatusNow } from '@/controllers/sloStatus'; +import { AlertState } from '@/models/alert'; + +import { callTool, createTestClient, getFirstText } from './mcpTestUtils'; + +jest.mock('@/controllers/slo', () => ({ + ...jest.requireActual('@/controllers/slo'), + listSlos: jest.fn(), + getSlo: jest.fn(), + getSloQueryContext: jest.fn(), +})); +jest.mock('@/controllers/sloAlert', () => ({ getSloAlerts: jest.fn() })); +jest.mock('@/controllers/sloStatus', () => ({ + computeSloStatusNow: jest.fn(), +})); + +const sloId = new Types.ObjectId(); +const slo: any = { + _id: sloId, + version: 1, + team: new Types.ObjectId(), + name: 'Checkout availability', + tags: ['checkout'], + source: new Types.ObjectId(), + indicator: { + template: 'availability', + eligible: { where: "SpanKind = 'Server'", whereLanguage: 'sql' }, + good: "StatusCode != 'Error'", + }, + target: 99.5, + window: '30d', + alerts: { fastBurn: { channels: [{ type: 'webhook', webhookId: 'w' }] } }, + status: { + state: 'burning', + sli: 0.99, + budgetRemaining: 0.4, + burn: [{ window: '1h', burnRate: 20 }], + }, + createdAt: new Date('2026-01-01T00:00:00Z'), + updatedAt: new Date('2026-01-02T00:00:00Z'), +}; + +// An SQL where clause and SQL filters render without reading metadata. +const queryContext: any = { + source: { + id: 'source-1', + kind: 'trace', + connection: 'connection-1', + from: { databaseName: 'otel', tableName: 'otel_traces' }, + timestampValueExpression: 'Timestamp', + }, + clickhouseClient: {}, + metadata: {}, +}; + +const connect = () => + createTestClient({ teamId: slo.team.toString(), userId: 'user-id' }); + +const toolNames = async () => + (await (await connect()).listTools()).tools.map(tool => tool.name); + +describe('MCP SLO tool', () => { + let slosEnabled: jest.ReplaceProperty; + + beforeEach(() => { + slosEnabled = jest.replaceProperty(config, 'IS_SLOS_ENABLED', true); + jest.mocked(listSlos).mockResolvedValue([slo]); + jest.mocked(getSlo).mockResolvedValue(slo); + jest.mocked(getSloQueryContext).mockResolvedValue(queryContext); + jest.mocked(getSloAlerts).mockResolvedValue( + new Map([ + [ + sloId.toString(), + { + fastBurn: { + id: 'alert-1', + state: AlertState.ALERT, + silencedUntil: null, + }, + }, + ], + ]), + ); + }); + + afterEach(() => slosEnabled.restore()); + + it('is only registered while SLOs are enabled', async () => { + const slosTools = ['clickstack_get_slo']; + expect(await toolNames()).toEqual(expect.arrayContaining(slosTools)); + slosEnabled.replaceValue(false); + const names = await toolNames(); + expect(slosTools.filter(name => names.includes(name))).toEqual([]); + }); + + it('lists SLOs as a summary, filtered by state', async () => { + const client = await connect(); + const all = JSON.parse( + getFirstText(await callTool(client, 'clickstack_get_slo')), + ); + expect(all).toEqual([ + { + id: sloId.toString(), + name: 'Checkout availability', + tags: ['checkout'], + target: 99.5, + window: '30d', + groupBy: null, + state: 'burning', + sli: 0.99, + budgetRemaining: 0.4, + burnRate: 20, + alertStates: { fastBurn: AlertState.ALERT, slowBurn: null }, + }, + ]); + const healthy = JSON.parse( + getFirstText( + await callTool(client, 'clickstack_get_slo', { state: 'healthy' }), + ), + ); + expect(healthy).toEqual([]); + }); + + it('returns one SLO with its status as of now and the query for its bad events', async () => { + const live = { + ...slo.status, + state: 'healthy', + burn: [{ window: '1h', burnRate: 1 }], + }; + jest.mocked(computeSloStatusNow).mockResolvedValue(live); + const result = await callTool(await connect(), 'clickstack_get_slo', { + id: sloId.toString(), + }); + const detail = JSON.parse(getFirstText(result)); + expect(detail).toEqual( + expect.objectContaining({ + id: sloId.toString(), + indicator: slo.indicator, + alerts: slo.alerts, + alertStates: { + fastBurn: { + id: 'alert-1', + state: AlertState.ALERT, + silencedUntil: null, + }, + }, + status: live, + statusSource: 'live', + // One where clause, which is all clickstack_search takes. + badEventsWhere: + "(SpanKind = 'Server') AND (NOT ifNull((StatusCode != 'Error'), 0))", + }), + ); + // Read for the calling team only. + expect(getSlo).toHaveBeenCalledWith(slo.team.toString(), sloId.toString()); + }); + + it('scopes the bad events of a grouped SLO to one group', async () => { + jest + .mocked(getSlo) + .mockResolvedValue({ ...slo, groupBy: "ResourceAttributes['k8s.ns']" }); + jest.mocked(computeSloStatusNow).mockResolvedValue(slo.status); + const url = jest.replaceProperty(config, 'FRONTEND_URL', 'http://app'); + try { + const result = await callTool(await connect(), 'clickstack_get_slo', { + id: sloId.toString(), + group: "o'brien", + }); + expect(JSON.parse(getFirstText(result))).toEqual( + expect.objectContaining({ + groupBy: "ResourceAttributes['k8s.ns']", + badEventsWhere: + "(SpanKind = 'Server') AND " + + "(toString(ResourceAttributes['k8s.ns']) = 'o''brien') AND " + + "(NOT ifNull((StatusCode != 'Error'), 0))", + url: `http://app/slos/${sloId}?group=o%27brien`, + }), + ); + } finally { + url.restore(); + } + }); + + it('refuses a group for an SLO that is not grouped', async () => { + const result = await callTool(await connect(), 'clickstack_get_slo', { + id: sloId.toString(), + group: 'checkout', + }); + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain('not grouped'); + }); + + it('falls back to the stored status when computing it fails', async () => { + jest + .mocked(computeSloStatusNow) + .mockRejectedValue(new Error('Timeout error')); + const result = await callTool(await connect(), 'clickstack_get_slo', { + id: sloId.toString(), + }); + expect(JSON.parse(getFirstText(result))).toEqual( + expect.objectContaining({ + status: slo.status, + statusSource: 'stored', + }), + ); + }); + + it('reports a malformed or unknown id', async () => { + const client = await connect(); + const malformed = await callTool(client, 'clickstack_get_slo', { + id: 'nope', + }); + expect(malformed.isError).toBe(true); + expect(getFirstText(malformed)).toContain('Invalid SLO ID'); + + jest.mocked(getSlo).mockResolvedValue(null); + const unknown = await callTool(client, 'clickstack_get_slo', { + id: new Types.ObjectId().toString(), + }); + expect(unknown.isError).toBe(true); + expect(getFirstText(unknown)).toContain('SLO not found'); + }); +}); diff --git a/packages/api/src/mcp/mcpServer.ts b/packages/api/src/mcp/mcpServer.ts index 1e4cd4a60..139aceb0f 100644 --- a/packages/api/src/mcp/mcpServer.ts +++ b/packages/api/src/mcp/mcpServer.ts @@ -1,7 +1,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import type { Implementation } from '@modelcontextprotocol/sdk/types.js'; -import { CODE_VERSION, FRONTEND_URL } from '@/config'; +import { CODE_VERSION, FRONTEND_URL, IS_SLOS_ENABLED } from '@/config'; import dashboardPrompts from './prompts/dashboards/index'; import alertsTools from './tools/alerts/index'; @@ -12,6 +12,7 @@ import { } from './tools/query/builderCatalog'; import queryTools from './tools/query/index'; import savedSearchesTools from './tools/savedSearches/index'; +import slosTools from './tools/slos/index'; import sourcesTools from './tools/sources/index'; import traceTools from './tools/trace/index'; import { McpContext } from './tools/types'; @@ -85,6 +86,7 @@ export function createServer(context: McpContext) { dashboardsTools(registrar); queryTools(registrar); savedSearchesTools(registrar); + if (IS_SLOS_ENABLED) slosTools(registrar); traceTools(registrar); dashboardPrompts(server, context); diff --git a/packages/api/src/mcp/tools/slos/getSlo.ts b/packages/api/src/mcp/tools/slos/getSlo.ts new file mode 100644 index 000000000..bbf389bb7 --- /dev/null +++ b/packages/api/src/mcp/tools/slos/getSlo.ts @@ -0,0 +1,193 @@ +import { + buildSloBadEventsSearch, + getSloGroupBy, +} from '@hyperdx/common-utils/dist/core/slo'; +import { describeFilter } from '@hyperdx/common-utils/dist/filters'; +import { SloStateSchema } from '@hyperdx/common-utils/dist/slo'; +import { isLogSource, isTraceSource } from '@hyperdx/common-utils/dist/types'; +import { z } from 'zod/v3'; + +import * as config from '@/config'; +import { + formatSlo, + getSlo, + getSloQueryContext, + listSlos, + SloQueryContext, +} from '@/controllers/slo'; +import { getSloAlerts } from '@/controllers/sloAlert'; +import { computeSloStatusNow } from '@/controllers/sloStatus'; +import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; +import { andSql, userWhereAsSql } from '@/mcp/tools/query/patternDrilldown'; +import type { ToolRegistrar } from '@/mcp/tools/types'; +import { mcpUserError, validateObjectId } from '@/mcp/utils/errors'; +import type { ISlo } from '@/models/slo'; +import { BaseError } from '@/utils/errors'; + +const json = (value: unknown) => ({ + content: [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }], +}); + +/** + * Bounds the status computed for one SLO and the metadata reads that render + * its bad-events where clause. + */ +const SLO_DETAIL_TIMEOUT_MS = 30_000; + +/** + * The SLO's bad events as one SQL where clause: the eligible where clause + * and filters, rendered to SQL where they are Lucene, and the bad condition. + * clickstack_search takes a single where clause, so this is what it can run. + */ +async function getBadEventsWhere( + slo: ISlo, + ctx: SloQueryContext, + group: string | undefined, +) { + const { source } = ctx; + const search = buildSloBadEventsSearch(slo, undefined, group); + const toSql = (where: string, whereLanguage: 'lucene' | 'sql') => + userWhereAsSql({ + where, + whereLanguage, + metadata: ctx.metadata, + databaseName: source.from.databaseName, + tableName: source.from.tableName, + connectionId: source.connection.toString(), + implicitColumnExpression: + isLogSource(source) || isTraceSource(source) + ? source.implicitColumnExpression + : undefined, + bodyExpression: isLogSource(source) ? source.bodyExpression : undefined, + }); + const parts = await Promise.all([ + toSql(search.where, search.whereLanguage), + ...search.filters.map(filter => + filter.type === 'lucene' + ? toSql(filter.condition, 'lucene') + : describeFilter(filter), + ), + ]); + return andSql(...parts); +} + +export function registerGetSlo({ context, registerTool }: ToolRegistrar): void { + const { teamId } = context; + const frontendUrl = config.FRONTEND_URL; + + registerTool( + 'clickstack_get_slo', + { + title: 'Get SLO(s)', + annotations: READ_ONLY_TOOL, + description: + 'Without an ID: list service level objectives as a summary (id, ' + + 'name, tags, target, window, group-by expression, state, SLI, ' + + 'error budget left, burn rate, alert states) from the status stored ' + + 'in the background (burn rate every few minutes, SLI and budget ' + + 'every 30 minutes; null until the first update). Optionally filter ' + + 'by state (e.g. state="burning"). With an ID: get the full ' + + 'definition, the status computed now (statusSource "live", or ' + + '"stored" if computing it failed), and badEventsWhere, a SQL where ' + + 'clause that selects the bad events: pass it to clickstack_search ' + + 'with whereLanguage "sql" and the source of the SLO. A grouped SLO ' + + '(groupBy set) has numbers for each of its busiest groups in ' + + 'status.groups, worst first, and takes the state of its worst ' + + 'group; status.groupCount counts all groups. Pass group to scope ' + + 'badEventsWhere to one group.', + inputSchema: z.object({ + id: z + .string() + .optional() + .describe( + 'SLO ID from a previous list call. Omit to list all SLOs, ' + + 'provide to get full detail.', + ), + state: SloStateSchema.optional().describe( + 'List only SLOs currently in this state; ignored when id is ' + + 'provided. Use breached or burning to find SLOs that need ' + + 'attention.', + ), + group: z + .string() + .optional() + .describe( + 'With an id of a grouped SLO: a value of its groupBy ' + + 'expression, as in status.groups[].value. Scopes ' + + 'badEventsWhere and the url to that group.', + ), + }), + }, + async ({ id, state, group }) => { + if (!id) { + const slos = await listSlos(teamId); + const alerts = await getSloAlerts( + teamId, + slos.map(slo => slo._id), + ); + return json( + slos + .map(slo => formatSlo(slo, alerts.get(slo._id.toString()))) + .filter(slo => !state || slo.status?.state === state) + .map(slo => ({ + id: slo.id, + name: slo.name, + tags: slo.tags, + target: slo.target, + window: slo.window, + // Null when the SLO is not grouped. + groupBy: slo.groupBy, + state: slo.status?.state ?? null, + sli: slo.status?.sli ?? null, + budgetRemaining: slo.status?.budgetRemaining ?? null, + burnRate: slo.status?.burn[0]?.burnRate ?? null, + // Each burn alert's state, or null when it is off. + alertStates: { + fastBurn: slo.alertStates.fastBurn?.state ?? null, + slowBurn: slo.alertStates.slowBurn?.state ?? null, + }, + })), + ); + } + + const idError = validateObjectId(id, 'SLO ID'); + if (idError) return idError; + const slo = await getSlo(teamId, id); + if (!slo) return mcpUserError('SLO not found'); + if (group != null && getSloGroupBy(slo) == null) { + return mcpUserError('This SLO is not grouped; omit group'); + } + const alert = (await getSloAlerts(teamId, [slo._id])).get(id); + let ctx: SloQueryContext; + try { + ctx = await getSloQueryContext( + teamId, + slo.source.toString(), + SLO_DETAIL_TIMEOUT_MS, + ); + } catch (e) { + // A deleted source or connection is the caller's to fix. + if (e instanceof BaseError) return mcpUserError(e.name); + throw e; + } + const formatted = formatSlo(slo, alert); + // The stored snapshot stands in when the query fails or times out. + const live = await computeSloStatusNow(slo, ctx).catch(() => null); + return json({ + ...formatted, + status: live ?? formatted.status, + statusSource: live ? 'live' : 'stored', + badEventsWhere: await getBadEventsWhere(slo, ctx, group), + ...(frontendUrl + ? { + url: + `${frontendUrl}/slos/${id}` + + (group != null + ? `?${new URLSearchParams({ group }).toString()}` + : ''), + } + : {}), + }); + }, + ); +} diff --git a/packages/api/src/mcp/tools/slos/index.ts b/packages/api/src/mcp/tools/slos/index.ts new file mode 100644 index 000000000..f5736cc68 --- /dev/null +++ b/packages/api/src/mcp/tools/slos/index.ts @@ -0,0 +1,9 @@ +import type { ToolDefinition, ToolRegistrar } from '@/mcp/tools/types'; + +import { registerGetSlo } from './getSlo'; + +const slosTools: ToolDefinition = (registrar: ToolRegistrar) => { + registerGetSlo(registrar); +}; + +export default slosTools;