From ffeb524909346a5b9f0079057e731a187def7cbb Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 15:50:33 +0100 Subject: [PATCH] feat: Monitoring tools (#130) Co-Authored-By: Claude Opus 5.5 --- README.md | 23 +- src/tools/context.ts | 5 +- src/tools/monitoring.ts | 586 +++++++++++++++++++++++++++++++++++++++- src/tools/result.ts | 16 +- test/fake-api.ts | 28 +- test/monitoring.test.ts | 336 +++++++++++++++++++++++ 6 files changed, 984 insertions(+), 10 deletions(-) create mode 100644 test/monitoring.test.ts diff --git a/README.md b/README.md index e67a6d7..e2a1f56 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,28 @@ Todas devuelven primero un resumen corto y después JSON compacto (sin nulls). L | --------------- | ------------------- | --------------------------------------------------------------------- | | `list_projects` | `GET /api/projects` | Proyectos visibles (`organization?` por slug/id, `limit?`, `cursor?`) | -Pendientes: Code Report y CVEs (#129), Monitoring (#130). +Pendientes: Code Report y CVEs (#129). + +## Monitoring + +| Tool | API | Descripción | +| ----------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | +| `get_monitoring_status` | `GET /api/monitoring/status`, `GET /api/monitoring/monitors` | "¿Está todo bien?": `project` **o** `service` (exactamente uno) | +| `list_monitors` | `GET /api/monitoring/monitors` | `project`, `service?`, `limit?`, `cursor?` | +| `get_monitor` | `GET /api/monitoring/monitors/[id]` | Uptime 24h/7d/30d, incidente abierto y últimos incidentes | +| `create_monitor` | `POST /api/monitoring/monitors` | `project`, `url`, `name?`, `method?`, `interval?` (30-3600 s), `timeout?` (1-30 s), `expected_status?`, `service?` | +| `test_monitor` | `POST /api/monitoring/monitors/[id]/test` | Un chequeo inmediato; no se guarda en el historial | + +Ejemplos: + +- "¿Está todo bien en acme/billing?" → `acme/billing: 5 up, 1 down (api-health desde hace 12 min: timeout) · 0 degradados` +- "Crea un monitor para https://api.acme.com/health en el proyecto acme/billing" → `Monitor creado: api.acme.com/health (GET https://api.acme.com/health cada 60 s) en acme/billing. Empezará a chequearse en breve.` + +Notas: + +- `create_monitor` **no admite cabeceras ni body** en v1 (el schema no los acepta y la API los rechaza para claves MCP). Las respuestas solo incluyen nombres de cabeceras y si hay body, nunca sus valores. +- Los errores de validación de la API se traducen al nombre de cada input (`intervalSeconds` → `interval`, `timeoutMs` → `timeout`…) con una explicación para que el agente pueda corregirlo. Si Monitoring no está activado en el proyecto, el error lo indica. +- `create_monitor` y `test_monitor` no son de solo lectura: el cliente suele pedir confirmación. ## Licencia diff --git a/src/tools/context.ts b/src/tools/context.ts index e1044b8..7c6fdb8 100644 --- a/src/tools/context.ts +++ b/src/tools/context.ts @@ -1,7 +1,7 @@ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { GitOpsApiError, type GitOpsApiClient } from '../api/client.js'; import type { Logger } from '../log.js'; -import { toolError } from './result.js'; +import { ToolMessageError, toolError } from './result.js'; /** What every tool gets. One per MCP request; `client` already carries the caller's token. */ export interface ToolContext { @@ -26,10 +26,11 @@ export async function runTool( ctx.log.info('tool ok', { ...base, durationMs: Date.now() - started }); return result; } catch (err) { + const api = err instanceof ToolMessageError ? err.api : err; ctx.log.warn('tool error', { ...base, durationMs: Date.now() - started, - ...(err instanceof GitOpsApiError ? { apiStatus: err.status, code: err.code } : {}), + ...(api instanceof GitOpsApiError ? { apiStatus: api.status, code: api.code } : {}), }); return toolError(err); } diff --git a/src/tools/monitoring.ts b/src/tools/monitoring.ts index 302edd6..b282f00 100644 --- a/src/tools/monitoring.ts +++ b/src/tools/monitoring.ts @@ -1,6 +1,586 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import type { ToolContext } from './context.js'; +import * as z from 'zod'; +import { fetchAll, GitOpsApiError } from '../api/client.js'; +import type { + ApiIncident, + ApiMonitorDetail, + ApiMonitoringStatus, + ApiMonitorSummary, + ApiMonitorTestResult, + ApiOpenIncident, + CreateMonitorBody, + Page, +} from '../api/types.js'; +import { + projectLabel, + ResolveError, + resolveProject, + resolveService, + type ResolvedService, +} from '../resolve.js'; +import { runTool, type ToolContext } from './context.js'; +import { ToolMessageError, toolResult } from './result.js'; -export function registerMonitoringTools(_server: McpServer, _ctx: ToolContext): void { - // TODO(#130): get_monitoring_status, list_monitors, get_monitor, create_monitor, test_monitor +// ---- Error translation ------------------------------------------------------------------------- + +/** API field name -> name of the tool input the agent has to fix. */ +const FIELD_TO_INPUT: Record = { + projectId: 'project', + serviceId: 'service', + intervalSeconds: 'interval', + timeoutMs: 'timeout', + expectedStatus: 'expected_status', + name: 'name', + url: 'url', + method: 'method', +}; + +const NO_SECRETS = + 'En v1 el MCP no admite cabeceras ni body en los monitores; créalo desde la UI de GitOps ' + + 'o con una clave de API normal.'; + +/** Explanation (Spanish) of each `monitoring.errors.*` code, with the tool input in context. */ +function explainCode(code: string, input: string): string { + switch (code) { + case 'required': + return 'es obligatorio'; + case 'too_long': + return input === 'name' + ? 'es demasiado largo (máximo 120 caracteres)' + : 'es demasiado largo (máximo 2048 caracteres)'; + case 'invalid_url': + return 'debe ser una URL http o https válida (p. ej. https://api.acme.com/health)'; + case 'private_target': + return 'no puede apuntar a direcciones privadas, locales o internas (localhost, 10.x, 192.168.x…)'; + case 'invalid_method': + return 'método HTTP no válido; usa GET, HEAD, POST, PUT, PATCH, DELETE u OPTIONS'; + case 'out_of_range': + if (input === 'interval') return 'fuera de rango; el intervalo va de 30 a 3600 segundos'; + if (input === 'timeout') return 'fuera de rango; el timeout va de 1 a 30 segundos'; + return 'valor fuera del rango permitido'; + case 'invalid_expected_status': + return 'usa códigos HTTP 100-599 o rangos separados por comas, p. ej. "200", "200-299,301"'; + case 'service_not_found': + return 'el servicio no existe en este proyecto'; + case 'too_many_headers': + case 'invalid_header': + case 'duplicate_header': + return NO_SECRETS; + default: + return `no válido (${code})`; + } +} + +const stripPrefix = (code: string) => code.replace(/^monitoring\.errors\./, ''); + +/** Turns the API's per-field validation failure into one message the agent can act on. */ +export function describeValidation(errors: Record): string { + const lines: string[] = []; + const seen = new Set(); + for (const [field, raw] of Object.entries(errors)) { + const secret = field === 'headers' || field.startsWith('headers.') || field === 'body'; + const input = secret ? field : (FIELD_TO_INPUT[field] ?? field); + const text = secret ? NO_SECRETS : explainCode(stripPrefix(raw), input); + const line = secret ? text : `${input}: ${text}`; + if (!seen.has(line)) lines.push(line); + seen.add(line); + } + return `Monitor no válido. Corrige: ${lines.join('; ')}.`; +} + +/** Runs an API call, translating the monitoring-specific failures into agent-friendly messages. */ +async function api(call: () => Promise): Promise { + try { + return await call(); + } catch (err) { + if (err instanceof GitOpsApiError) { + if (err.code === 'module_disabled') { + throw new ToolMessageError( + 'Monitoring no está activado en este proyecto; actívalo en Ajustes del proyecto.', + err, + ); + } + if (err.code === 'mcp_monitor_secrets_not_allowed') { + throw new ToolMessageError(NO_SECRETS, err); + } + if (err.code === 'validation_failed' && err.fieldErrors) { + throw new ToolMessageError(describeValidation(err.fieldErrors), err); + } + } + throw err; + } +} + +// ---- Formatting helpers -------------------------------------------------------------------------- + +function ago(since: string, now = Date.now()): string { + const minutes = Math.max(0, Math.round((now - Date.parse(since)) / 60_000)); + if (Number.isNaN(minutes)) return 'hace un tiempo'; + if (minutes < 1) return 'hace menos de 1 min'; + if (minutes < 60) return `hace ${minutes} min`; + const hours = Math.round(minutes / 60); + if (hours < 48) return `hace ${hours} h`; + return `hace ${Math.round(hours / 24)} días`; +} + +/** The API sends uptime as a 0..1 ratio. */ +function percent(ratio: number | null | undefined): string { + if (ratio == null) return 'n/d'; + return `${(Math.round(ratio * 10_000) / 100).toString()}%`; +} + +const short = (text: string | null | undefined, max = 120) => + !text ? '' : text.length > max ? `${text.slice(0, max - 1)}…` : text; + +function incidentNote(i: ApiOpenIncident): string { + const cause = short(i.cause, 80); + return `${i.name} desde ${ago(i.since)}${cause ? `: ${cause}` : ''}`; +} + +/** "acme/billing: 5 up, 1 down (api-health desde hace 12 min: timeout) · 0 degradados" */ +function statusSummary(label: string, s: ApiMonitoringStatus): string { + if (s.total === 0) return `${label}: no hay monitores configurados.`; + const notes = (status: string) => { + const list = s.openIncidents.filter((i) => i.status === status).map(incidentNote); + return list.length ? ` (${list.join('; ')})` : ''; + }; + const extras = [ + s.paused ? `${s.paused} en pausa` : '', + s.pending ? `${s.pending} pendientes de primer chequeo` : '', + ].filter(Boolean); + return ( + `${label}: ${s.up} up, ${s.down} down${notes('down')} · ${s.degraded} degradados${notes('degraded')}` + + (extras.length ? ` · ${extras.join(', ')}` : '') + ); +} + +/** Same derivation the API does for a whole project, but over an already-filtered list. */ +function countStatuses(monitors: ApiMonitorSummary[]) { + const counts = { up: 0, degraded: 0, down: 0, paused: 0, pending: 0 }; + for (const m of monitors) counts[m.status]++; + return { ...counts, total: monitors.length }; +} + +const intervalText = (seconds: number) => `${seconds} s`; + +// ---- Output schemas ------------------------------------------------------------------------------ + +const statusEnum = z.enum(['up', 'degraded', 'down', 'paused', 'pending']); + +const incidentSchema = z.object({ + id: z.string(), + status: z.string(), + cause: z.string().nullable(), + httpStatus: z.number().nullable(), + error: z.string().nullable(), + startedAt: z.string(), + endedAt: z.string().nullable(), + failedChecks: z.number(), +}); + +const monitorSummarySchema = z.object({ + id: z.string(), + name: z.string(), + method: z.string(), + url: z.string(), + serviceId: z.string().nullable(), + enabled: z.boolean(), + status: statusEnum, + uptime24h: z.number().nullable(), + hasHeaders: z.boolean(), + hasBody: z.boolean(), +}); + +const monitorDetailSchema = monitorSummarySchema.extend({ + headerNames: z.array(z.string()), + intervalSeconds: z.number(), + timeoutMs: z.number(), + expectedStatus: z.union([z.string(), z.number()]), + uptime: z.object({ + h24: z.number().nullable(), + d7: z.number().nullable(), + d30: z.number().nullable(), + }), + openIncident: incidentSchema.nullable(), + incidents: z.array(incidentSchema), +}); + +/** Only the fields we know are safe: never header values or the body. */ +function pickSummary(m: ApiMonitorSummary): ApiMonitorSummary { + return { + id: m.id, + name: m.name, + method: m.method, + url: m.url, + serviceId: m.serviceId, + enabled: m.enabled, + status: m.status, + uptime24h: m.uptime24h, + hasHeaders: m.hasHeaders, + hasBody: m.hasBody, + }; +} + +const pickIncident = (i: ApiIncident): ApiIncident => ({ + id: i.id, + status: i.status, + cause: i.cause ? short(i.cause, 200) : null, + httpStatus: i.httpStatus, + error: i.error ? short(i.error, 200) : null, + startedAt: i.startedAt, + endedAt: i.endedAt, + failedChecks: i.failedChecks, +}); + +function pickDetail(m: ApiMonitorDetail): ApiMonitorDetail { + return { + ...pickSummary(m), + headerNames: m.headerNames ?? [], + intervalSeconds: m.intervalSeconds, + timeoutMs: m.timeoutMs, + expectedStatus: m.expectedStatus, + uptime: { h24: m.uptime?.h24 ?? null, d7: m.uptime?.d7 ?? null, d30: m.uptime?.d30 ?? null }, + openIncident: m.openIncident ? pickIncident(m.openIncident) : null, + incidents: (m.incidents ?? []).slice(0, 10).map(pickIncident), + }; +} + +// ---- Create helpers ----------------------------------------------------------------------------- + +/** Name derived from host + path: `https://api.acme.com/health` -> `api.acme.com/health`. */ +export function deriveMonitorName(url: string): string { + try { + const parsed = new URL(url); + const path = parsed.pathname.replace(/\/+$/, ''); + return `${parsed.host}${path}`.slice(0, 120); + } catch { + return url.slice(0, 120); + } +} + +async function projectOfService(ctx: ToolContext, service: ResolvedService, project?: string) { + if (service.project) { + if (project) { + const given = await resolveProject(ctx.client, project); + if (given.id !== service.project.id) { + throw new ResolveError( + `El servicio ${service.name} pertenece a ${projectLabel(service.project)}, no a ${projectLabel(given)}.`, + ); + } + } + return service.project; + } + if (project) return resolveProject(ctx.client, project); + throw new ResolveError( + 'Con un id de servicio no puedo saber su proyecto. Usa org/proyecto/servicio o indica también el proyecto.', + ); +} + +// ---- Tools --------------------------------------------------------------------------------------- + +export function registerMonitoringTools(server: McpServer, ctx: ToolContext): void { + server.registerTool( + 'get_monitoring_status', + { + title: 'Monitoring status', + description: + 'Answers "is everything OK?": how many monitors are up, degraded, down, paused or pending, and ' + + 'which ones have an open incident (since when and why). Pass exactly one of `project` ' + + '("org/project" or id) for a whole project, or `service` ("org/project/service" or id) to ' + + 'look only at the monitors linked to that service.', + inputSchema: { + project: z.string().optional().describe('Project as "org/project" or id.'), + service: z + .string() + .optional() + .describe('Service as "org/project/service" or id. Alternative to `project`.'), + }, + outputSchema: { + scope: z.string(), + up: z.number(), + degraded: z.number(), + down: z.number(), + paused: z.number(), + pending: z.number(), + total: z.number(), + openIncidents: z.array( + z.object({ + monitorId: z.string(), + name: z.string(), + status: z.string(), + since: z.string(), + cause: z.string().nullable(), + }), + ), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ project, service }) => + runTool(ctx, 'get_monitoring_status', async () => { + if (!project && !service) { + throw new ResolveError('Indica `project` o `service` (exactamente uno de los dos).'); + } + if (project && service) { + throw new ResolveError( + 'Indica solo uno: `project` (todo el proyecto) o `service` (solo ese servicio), no ambos.', + ); + } + if (project) { + const p = await resolveProject(ctx.client, project); + const status = await api(() => + ctx.client.get('/api/monitoring/status', { projectId: p.id }), + ); + const label = projectLabel(p); + return toolResult(statusSummary(label, status), { scope: label, ...status }); + } + + const svc = await resolveService(ctx.client, service!); + const p = await projectOfService(ctx, svc); + const label = `${projectLabel(p)}/${svc.slug ?? svc.name}`; + const monitors = await api(() => + fetchAll(ctx.client, '/api/monitoring/monitors', { + projectId: p.id, + serviceId: svc.id, + }), + ); + // The list has no incident info: fetch the detail of the (few) failing monitors. + const failing = monitors.filter((m) => m.status === 'down' || m.status === 'degraded'); + const details = await Promise.all( + failing + .slice(0, 10) + .map((m) => ctx.client.get(`/api/monitoring/monitors/${m.id}`)), + ); + const openIncidents: ApiOpenIncident[] = details.flatMap((d) => + d.openIncident + ? [ + { + monitorId: d.id, + name: d.name, + status: d.openIncident.status, + since: d.openIncident.startedAt, + cause: d.openIncident.cause, + }, + ] + : [], + ); + const status: ApiMonitoringStatus = { ...countStatuses(monitors), openIncidents }; + return toolResult(statusSummary(label, status), { scope: label, ...status }); + }), + ); + + server.registerTool( + 'list_monitors', + { + title: 'List monitors', + description: + 'Lists the uptime monitors of a project (optionally only those linked to a service) with ' + + 'status and 24h uptime. Use get_monitor for uptime 7d/30d and incidents.', + inputSchema: { + project: z.string().describe('Project as "org/project" or id.'), + service: z + .string() + .optional() + .describe('Only monitors linked to this service ("org/project/service" or id).'), + limit: z.number().int().min(1).max(100).optional().describe('Page size (default 25).'), + cursor: z.string().optional().describe('nextCursor from a previous call.'), + }, + outputSchema: { monitors: z.array(monitorSummarySchema), nextCursor: z.string().nullable() }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ project, service, limit, cursor }) => + runTool(ctx, 'list_monitors', async () => { + const p = await resolveProject(ctx.client, project); + let serviceId: string | undefined; + if (service) { + const svc = await resolveService(ctx.client, service); + if (svc.project && svc.project.id !== p.id) { + throw new ResolveError( + `El servicio ${svc.name} pertenece a ${projectLabel(svc.project)}, no a ${projectLabel(p)}.`, + ); + } + serviceId = svc.id; + } + const page = await api(() => + ctx.client.get>('/api/monitoring/monitors', { + projectId: p.id, + serviceId, + limit, + cursor, + }), + ); + const monitors = page.items.map(pickSummary); + const label = projectLabel(p); + const summary = monitors.length + ? `${monitors.length} ${monitors.length === 1 ? 'monitor' : 'monitores'} en ${label}: ` + + monitors + .map((m) => `${m.name} (${m.status}, uptime 24h ${percent(m.uptime24h)})`) + .join(', ') + + (page.nextCursor ? ' (hay más, usa cursor)' : '') + : `No hay monitores en ${label}.`; + return toolResult(summary, { monitors, nextCursor: page.nextCursor }); + }), + ); + + server.registerTool( + 'get_monitor', + { + title: 'Get monitor', + description: + 'Details of one monitor: configuration, uptime 24h/7d/30d (as percentages in the summary), ' + + 'the open incident if any and the latest incidents. Header values and body are never ' + + 'returned, only header names and whether a body exists.', + inputSchema: { id: z.string().describe('Monitor id (from list_monitors).') }, + outputSchema: monitorDetailSchema.shape, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ id }) => + runTool(ctx, 'get_monitor', async () => { + const raw = await api(() => + ctx.client.get(`/api/monitoring/monitors/${encodeURIComponent(id)}`), + ); + const m = pickDetail(raw); + const parts = [ + `${m.name}: ${m.status}`, + `${m.method} ${m.url} cada ${intervalText(m.intervalSeconds)}`, + `uptime 24h ${percent(m.uptime.h24)} · 7d ${percent(m.uptime.d7)} · 30d ${percent(m.uptime.d30)}`, + ]; + if (m.openIncident) { + const cause = short(m.openIncident.cause ?? m.openIncident.error, 80); + parts.push( + `incidente abierto (${m.openIncident.status}) desde ${ago(m.openIncident.startedAt)}${cause ? `: ${cause}` : ''}`, + ); + } else { + parts.push('sin incidente abierto'); + } + parts.push(`${m.incidents.length} incidentes recientes`); + if (m.hasHeaders) parts.push(`cabeceras: ${m.headerNames.join(', ')} (valores ocultos)`); + if (m.hasBody) parts.push('con body (oculto)'); + return toolResult(parts.join(' · '), m); + }), + ); + + server.registerTool( + 'create_monitor', + { + title: 'Create monitor', + description: + 'Creates an HTTP uptime monitor for a URL in a project. It does NOT support request headers ' + + 'or body (not allowed through MCP in v1). Defaults: GET, every 60 s, timeout 10 s, expects ' + + 'a 2xx status. Private/internal addresses are rejected. Monitoring must be enabled in the ' + + 'project. This writes data: confirm the details with the user first.', + inputSchema: { + project: z.string().describe('Project as "org/project" or id.'), + url: z.string().describe('Public http(s) URL to check, e.g. https://api.acme.com/health.'), + name: z + .string() + .optional() + .describe('Monitor name (max 120). Defaults to host + path of the URL.'), + method: z + .string() + .optional() + .describe('HTTP method: GET (default), HEAD, POST, PUT, PATCH, DELETE or OPTIONS.'), + interval: z + .number() + .int() + .optional() + .describe('Seconds between checks, 30 to 3600 (default 60).'), + timeout: z + .number() + .int() + .optional() + .describe('Seconds to wait for a response, 1 to 30 (default 10).'), + expected_status: z + .union([z.string(), z.number()]) + .optional() + .describe('Expected HTTP status: a code or ranges, e.g. 200 or "200-299,301".'), + service: z + .string() + .optional() + .describe('Link the monitor to this service ("org/project/service" or id).'), + }, + outputSchema: monitorDetailSchema.shape, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, + }, + ({ project, url, name, method, interval, timeout, expected_status, service }) => + runTool(ctx, 'create_monitor', async () => { + const p = await resolveProject(ctx.client, project); + let serviceId: string | undefined; + if (service) { + const svc = await resolveService(ctx.client, service); + if (svc.project && svc.project.id !== p.id) { + throw new ResolveError( + `El servicio ${svc.name} pertenece a ${projectLabel(svc.project)}, no a ${projectLabel(p)}.`, + ); + } + serviceId = svc.id; + } + // Explicit allowlist: nothing else (headers, body…) can ever reach the API from here. + const body: CreateMonitorBody = { + projectId: p.id, + name: name?.trim() || deriveMonitorName(url.trim()), + url: url.trim(), + ...(method ? { method } : {}), + ...(serviceId ? { serviceId } : {}), + ...(interval !== undefined ? { intervalSeconds: interval } : {}), + ...(timeout !== undefined ? { timeoutMs: timeout * 1000 } : {}), + ...(expected_status !== undefined ? { expectedStatus: expected_status } : {}), + }; + const raw = await api(() => + ctx.client.post('/api/monitoring/monitors', body), + ); + const m = pickDetail(raw); + return toolResult( + `Monitor creado: ${m.name} (${m.method} ${m.url} cada ${intervalText(m.intervalSeconds)}) en ${projectLabel(p)}. ` + + `Empezará a chequearse en breve. Id: ${m.id}`, + m, + ); + }), + ); + + server.registerTool( + 'test_monitor', + { + title: 'Test monitor', + description: + 'Runs one check of an existing monitor right now and returns the outcome (status, HTTP ' + + 'status, latency, error). Nothing is saved to its history.', + inputSchema: { id: z.string().describe('Monitor id (from list_monitors).') }, + outputSchema: { + status: z.string(), + httpStatus: z.number().nullable(), + latencyMs: z.number().nullable(), + error: z.string().nullable(), + }, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: true, + openWorldHint: true, + }, + }, + ({ id }) => + runTool(ctx, 'test_monitor', async () => { + const r = await api(() => + ctx.client.post( + `/api/monitoring/monitors/${encodeURIComponent(id)}/test`, + ), + ); + const result = { + status: r.status, + httpStatus: r.httpStatus, + latencyMs: r.latencyMs, + error: r.error ? short(r.error, 200) : null, + }; + const parts = [`Chequeo de prueba: ${result.status}`]; + if (result.httpStatus != null) parts.push(`HTTP ${result.httpStatus}`); + if (result.latencyMs != null) parts.push(`${result.latencyMs} ms`); + if (result.error) parts.push(`error: ${result.error}`); + return toolResult(parts.join(' · '), result); + }), + ); } diff --git a/src/tools/result.ts b/src/tools/result.ts index 39d9705..f3a6fc6 100644 --- a/src/tools/result.ts +++ b/src/tools/result.ts @@ -23,6 +23,20 @@ export function toolResult(summary: string, data: object): CallToolResult { }; } +/** + * A failure whose message is already written for the agent (e.g. translated API validation + * errors). `api` keeps the original API error so `runTool` can still log its status and code. + */ +export class ToolMessageError extends Error { + constructor( + message: string, + readonly api?: GitOpsApiError, + ) { + super(message); + this.name = 'ToolMessageError'; + } +} + function describe(err: GitOpsApiError): string { switch (err.status) { case 401: @@ -58,7 +72,7 @@ function describe(err: GitOpsApiError): string { export function toolError(err: unknown): CallToolResult { let text: string; if (err instanceof GitOpsApiError) text = describe(err); - else if (err instanceof ResolveError) text = err.message; + else if (err instanceof ResolveError || err instanceof ToolMessageError) text = err.message; else text = 'Error interno del servidor MCP.'; return { isError: true, content: [{ type: 'text', text }] }; } diff --git a/test/fake-api.ts b/test/fake-api.ts index b5e4cb0..381b7b1 100644 --- a/test/fake-api.ts +++ b/test/fake-api.ts @@ -87,14 +87,14 @@ export function seed(): FakeDb { serviceId, enabled: true, status, - uptime24h: status === 'down' ? 91.5 : 100, + uptime24h: status === 'down' ? 0.915 : 1, hasHeaders: false, hasBody: false, headerNames: [], intervalSeconds: 60, timeoutMs: 10000, expectedStatus: 200, - uptime: { h24: status === 'down' ? 91.5 : 100, d7: 99.9, d30: 99.95 }, + uptime: { h24: status === 'down' ? 0.915 : 1, d7: 0.999, d30: 0.9995 }, openIncident: status === 'down' ? { @@ -407,7 +407,10 @@ export function defaultRoutes(): Route[] { handler: ({ url, db }) => { const projectId = url.searchParams.get('projectId'); if (!projectId) return err(400, 'invalid_request', 'projectId is required'); - if (!db.projects.some((p) => p.id === projectId)) return notFound('Project'); + const statusProject = db.projects.find((p) => p.id === projectId); + if (!statusProject) return notFound('Project'); + if (!statusProject.modules.includes('monitoring')) + return err(409, 'module_disabled', 'Monitoring is not enabled in this project'); const rows = db.monitors.filter((m) => m.projectId === projectId); const status: ApiMonitoringStatus = { up: 0, @@ -446,10 +449,29 @@ export function defaultRoutes(): Route[] { ); const project = db.projects.find((p) => p.id === b.projectId); if (!project) return notFound('Project'); + if (!project.modules.includes('monitoring')) + return err(409, 'module_disabled', 'Monitoring is not enabled in this project'); const errors: Record = {}; if (typeof b.name !== 'string' || !b.name) errors.name = 'monitoring.errors.required'; if (typeof b.url !== 'string' || !/^https?:\/\//.test(b.url)) errors.url = 'monitoring.errors.invalid_url'; + const interval = b.intervalSeconds; + if ( + interval !== undefined && + (typeof interval !== 'number' || interval < 30 || interval > 3600) + ) + errors.intervalSeconds = 'monitoring.errors.out_of_range'; + const timeoutMs = b.timeoutMs; + if ( + timeoutMs !== undefined && + (typeof timeoutMs !== 'number' || timeoutMs < 1000 || timeoutMs > 30000) + ) + errors.timeoutMs = 'monitoring.errors.out_of_range'; + if ( + typeof b.method === 'string' && + !/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/i.test(b.method) + ) + errors.method = 'monitoring.errors.invalid_method'; if (Object.keys(errors).length) return err(400, 'validation_failed', 'Invalid monitor', errors); const created = { diff --git a/test/monitoring.test.ts b/test/monitoring.test.ts new file mode 100644 index 0000000..54c79b0 --- /dev/null +++ b/test/monitoring.test.ts @@ -0,0 +1,336 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { IDS, startFakeApi, VALID_TOKEN, type FakeApi } from './fake-api.js'; +import { startMcp, type TestMcp } from './helpers.js'; +import { deriveMonitorName } from '../src/tools/monitoring.js'; + +let api: FakeApi; +let mcp: TestMcp; +let client: Client; +beforeAll(async () => { + api = await startFakeApi(); + mcp = await startMcp(api); + client = new Client({ name: 'test', version: '1' }); + await client.connect( + new StreamableHTTPClientTransport(new URL(`${mcp.url}/mcp`), { + requestInit: { headers: { Authorization: `Bearer ${VALID_TOKEN}` } }, + }), + ); +}); +afterAll(async () => { + await client.close(); + await mcp.close(); + await api.close(); +}); +beforeEach(() => { + api.reset(); +}); + +type Data = Record; // eslint-disable-line @typescript-eslint/no-explicit-any + +const call = async (name: string, args: Record) => { + const r = await client.callTool({ name, arguments: args }); + return { + isError: Boolean(r.isError), + text: (r.content as { text: string }[])[0]!.text, + data: r.structuredContent as Data | undefined, + }; +}; +const failOnCreate = (f: { status: number; code: string; errors?: Record }) => + api.route('POST', /^\/api\/monitoring\/monitors$/, () => ({ + status: f.status, + body: { error: 'x', code: f.code, ...(f.errors ? { errors: f.errors } : {}) }, + })); +const posts = () => api.requests.filter((r) => r.method === 'POST'); + +describe('monitoring tools: listing', () => { + it('has the right annotations', async () => { + const { tools } = await client.listTools(); + const by = (n: string) => tools.find((t) => t.name === n)!; + for (const n of ['get_monitoring_status', 'list_monitors', 'get_monitor']) { + expect(by(n).annotations?.readOnlyHint).toBe(true); + } + expect(by('create_monitor').annotations).toMatchObject({ + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }); + expect(by('test_monitor').annotations).toMatchObject({ + readOnlyHint: false, + destructiveHint: false, + idempotentHint: true, + }); + const props = Object.keys( + (by('create_monitor').inputSchema as { properties: Record }).properties, + ); + expect(props).toEqual( + expect.arrayContaining([ + 'project', + 'url', + 'name', + 'method', + 'interval', + 'timeout', + 'expected_status', + 'service', + ]), + ); + expect(props).not.toContain('headers'); + expect(props).not.toContain('body'); + }); +}); + +describe('get_monitoring_status', () => { + it('summarises a project', async () => { + const r = await call('get_monitoring_status', { project: 'acme/billing' }); + expect(r.isError).toBe(false); + expect(r.text).toMatch( + /^acme\/billing: 0 up, 1 down \(billing-api desde hace .+: HTTP 503\) · 0 degradados/, + ); + expect(r.data).toMatchObject({ down: 1, total: 1 }); + expect( + api.requests.some((q) => + q.path.startsWith(`/api/monitoring/status?projectId=${IDS.acmeBilling}`), + ), + ).toBe(true); + }); + + it('summarises a service by filtering the monitors', async () => { + const r = await call('get_monitoring_status', { service: 'acme/billing/billing-api' }); + expect(r.isError).toBe(false); + expect(r.text).toContain('acme/billing/billing-api: 0 up, 1 down (billing-api desde hace'); + expect( + api.requests.some( + (q) => + q.path.includes(`/api/monitoring/monitors?`) && + q.path.includes(`serviceId=${IDS.svcBillingApi}`), + ), + ).toBe(true); + }); + + it('service without monitors', async () => { + const r = await call('get_monitoring_status', { service: 'acme/billing/billing-worker' }); + expect(r.text).toContain('no hay monitores'); + }); + + it('requires exactly one of project or service', async () => { + const none = await call('get_monitoring_status', {}); + expect(none.isError).toBe(true); + expect(none.text).toMatch(/project.*service/); + const both = await call('get_monitoring_status', { + project: 'acme/billing', + service: 'acme/billing/billing-api', + }); + expect(both.isError).toBe(true); + expect(both.text).toMatch(/solo uno/); + expect(api.requests.filter((q) => q.path.includes('/monitoring/'))).toHaveLength(0); + }); + + it('module_disabled gives an actionable message', async () => { + const r = await call('get_monitoring_status', { project: 'globex/billing' }); + expect(r.isError).toBe(true); + expect(r.text).toBe( + 'Monitoring no está activado en este proyecto; actívalo en Ajustes del proyecto.', + ); + }); +}); + +describe('list_monitors / get_monitor', () => { + it('lists the monitors of a project', async () => { + const r = await call('list_monitors', { project: 'acme/web' }); + expect(r.text).toContain('1 monitor en acme/web: web (up, uptime 24h 100%)'); + expect(r.data?.monitors).toHaveLength(1); + expect(r.data?.nextCursor).toBeNull(); + }); + + it('filters by service', async () => { + const r = await call('list_monitors', { + project: 'acme/billing', + service: 'acme/billing/billing-api', + }); + expect(r.data?.monitors).toHaveLength(1); + const none = await call('list_monitors', { + project: 'acme/billing', + service: 'acme/billing/billing-worker', + }); + expect(none.text).toContain('No hay monitores'); + const wrong = await call('list_monitors', { + project: 'acme/web', + service: 'acme/billing/billing-api', + }); + expect(wrong.isError).toBe(true); + }); + + it('gets a monitor with uptime percentages and the open incident', async () => { + const r = await call('get_monitor', { id: IDS.monBillingApi }); + expect(r.isError).toBe(false); + expect(r.text).toContain('uptime 24h 91.5% · 7d 99.9% · 30d 99.95%'); + expect(r.text).toContain('incidente abierto (down) desde hace'); + expect(r.data?.openIncident?.cause).toBe('HTTP 503'); + }); + + it('never exposes header values or body, only names/flags', async () => { + const m = api.db.monitors[1]!; + Object.assign(m, { hasHeaders: true, headerNames: ['Authorization'], hasBody: true }); + Object.assign(m, { + headers: [{ name: 'Authorization', value: 'SECRET-VALUE' }], + body: 'SECRET-BODY', + }); + const r = await call('get_monitor', { id: m.id }); + expect(r.text).toContain('cabeceras: Authorization (valores ocultos)'); + expect(r.text).not.toContain('SECRET'); + expect(JSON.stringify(r.data)).not.toContain('SECRET'); + Object.assign(m, { hasHeaders: false, headerNames: [], hasBody: false }); + }); + + it('404 is readable', async () => { + const r = await call('get_monitor', { id: 'nope' }); + expect(r.isError).toBe(true); + expect(r.text).toMatch(/No encontrado/); + }); +}); + +describe('create_monitor', () => { + it('maps inputs to the API field names', async () => { + const r = await call('create_monitor', { + project: 'acme/billing', + url: 'https://api.acme.com/health/', + method: 'HEAD', + interval: 120, + timeout: 5, + expected_status: '200-299', + service: 'acme/billing/billing-worker', + }); + expect(r.isError).toBe(false); + expect(r.text).toContain( + 'Monitor creado: api.acme.com/health (HEAD https://api.acme.com/health/ cada 120 s) en acme/billing.', + ); + expect(r.text).toContain('Empezará a chequearse en breve'); + expect(r.text).toContain(r.data!.id); + expect(posts()).toHaveLength(1); + expect(posts()[0]!.body).toEqual({ + projectId: IDS.acmeBilling, + name: 'api.acme.com/health', + url: 'https://api.acme.com/health/', + method: 'HEAD', + serviceId: IDS.svcBillingWorker, + intervalSeconds: 120, + timeoutMs: 5000, + expectedStatus: '200-299', + }); + }); + + it('uses the given name and omits unset optionals', async () => { + await call('create_monitor', { + project: 'acme/web', + url: 'https://web.acme.com', + name: 'home', + }); + expect(posts()[0]!.body).toEqual({ + projectId: IDS.acmeWeb, + name: 'home', + url: 'https://web.acme.com', + }); + }); + + it('never forwards headers or body, even if the client sends them', async () => { + const r = await call('create_monitor', { + project: 'acme/web', + url: 'https://web.acme.com/x', + headers: [{ name: 'Authorization', value: 'SECRET' }], + body: 'SECRET', + }); + if (!r.isError) { + expect(posts()).toHaveLength(1); + expect(Object.keys(posts()[0]!.body as object)).not.toEqual( + expect.arrayContaining(['headers']), + ); + } + for (const p of posts()) { + expect(JSON.stringify(p.body)).not.toContain('SECRET'); + expect(p.body).not.toHaveProperty('headers'); + expect(p.body).not.toHaveProperty('body'); + } + }); + + it('translates per-field validation errors to input names', async () => { + const r = await call('create_monitor', { + project: 'acme/billing', + url: 'ftp://nope', + interval: 5, + timeout: 99, + method: 'FETCH', + }); + expect(r.isError).toBe(true); + expect(r.text).toContain('url: debe ser una URL http o https válida'); + expect(r.text).toContain('interval: fuera de rango; el intervalo va de 30 a 3600 segundos'); + expect(r.text).toContain('timeout: fuera de rango; el timeout va de 1 a 30 segundos'); + expect(r.text).toContain('method: método HTTP no válido'); + expect(r.text).not.toContain('intervalSeconds'); + expect(r.text).not.toContain('monitoring.errors'); + }); + + it('explains other known codes and unknown ones', async () => { + failOnCreate({ + status: 400, + code: 'validation_failed', + errors: { + expectedStatus: 'monitoring.errors.invalid_expected_status', + serviceId: 'monitoring.errors.service_not_found', + name: 'monitoring.errors.weird_code', + }, + }); + const r = await call('create_monitor', { project: 'acme/web', url: 'https://web.acme.com' }); + expect(r.text).toContain('expected_status: usa códigos HTTP 100-599'); + expect(r.text).toContain('service: el servicio no existe en este proyecto'); + expect(r.text).toContain('name: no válido (weird_code)'); + }); + + it('module_disabled', async () => { + const r = await call('create_monitor', { + project: 'globex/billing', + url: 'https://x.example.com', + }); + expect(r.isError).toBe(true); + expect(r.text).toContain('Monitoring no está activado en este proyecto'); + }); + + it('mcp_monitor_secrets_not_allowed explains v1', async () => { + failOnCreate({ status: 400, code: 'mcp_monitor_secrets_not_allowed' }); + const r = await call('create_monitor', { project: 'acme/web', url: 'https://web.acme.com' }); + expect(r.isError).toBe(true); + expect(r.text).toMatch(/no admite cabeceras ni body/); + }); +}); + +describe('test_monitor', () => { + it('runs the check and sends a JSON body', async () => { + const r = await call('test_monitor', { id: IDS.monWeb }); + expect(r.isError).toBe(false); + expect(r.text).toContain('Chequeo de prueba: up · HTTP 200 · 42 ms'); + expect(r.data).toMatchObject({ status: 'up', httpStatus: 200, latencyMs: 42 }); + expect(posts()[0]).toMatchObject({ + path: `/api/monitoring/monitors/${IDS.monWeb}/test`, + contentType: expect.stringContaining('application/json'), + body: {}, + }); + }); + + it('down result and 404', async () => { + expect((await call('test_monitor', { id: IDS.monBillingApi })).text).toContain( + 'down · HTTP 503', + ); + const r = await call('test_monitor', { id: 'nope' }); + expect(r.isError).toBe(true); + }); +}); + +describe('deriveMonitorName', () => { + it('uses host and path', () => { + expect(deriveMonitorName('https://api.acme.com/v1/health')).toBe('api.acme.com/v1/health'); + expect(deriveMonitorName('https://acme.com/')).toBe('acme.com'); + expect(deriveMonitorName('nonsense')).toBe('nonsense'); + }); +});