diff --git a/README.md b/README.md index e67a6d7..c7f31e3 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,20 @@ 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). +### Code Report y CVEs (solo lectura) + +| Tool | API | Descripción | +| ---------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| `list_services` | `GET /api/code-report/services` | Servicios de un proyecto (`project`) con riesgo, severidades y política (`limit?`, `cursor?`) | +| `get_code_report` | `GET /api/code-report/services/[id]` | Último análisis de un servicio (`service`): riesgo, severidades, política y reglas incumplidas, monitores | +| `list_service_cves` | `GET /api/code-report/services/[id]/vulnerabilities` | CVEs de un servicio (`service`, `severity?[]`, `fixable?`, `limit?`, `cursor?`) | +| `list_technology_cves` | `GET /api/cves/feed` | Feed de CVEs por tecnología (`organization`, `technology?`, `severity?` mínima, `kev?`, `affects_me?`, ...) | +| `get_cve` | `GET /api/cves/[cve]` | Detalle de un CVE (`id`, `organization`) y servicios afectados | +| `get_cve_watchlist` | `GET /api/cves/watchlist` | Tecnologías vigiladas por la organización (`organization`) | + +`score` es un **riesgo** (más alto = peor). Los servicios se identifican como `org/proyecto/servicio` o por id. Con el feed de CVEs desactivado, las tools de CVEs lo indican sin error. Ejemplos: "¿cómo está el code report de acme/billing/api?", "¿qué CVEs críticos afectan a acme/billing?", "¿qué CVEs de la lista KEV me afectan en acme?". + +Pendientes: Monitoring (#130). ## Licencia diff --git a/src/tools/code-report.ts b/src/tools/code-report.ts index 7da3cb3..4382c7b 100644 --- a/src/tools/code-report.ts +++ b/src/tools/code-report.ts @@ -1,7 +1,15 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import * as z from 'zod'; -import type { Page, ApiProject } from '../api/types.js'; -import { projectLabel, resolveOrganization } from '../resolve.js'; +import type { + ApiProject, + ApiServiceReport, + ApiServiceSummary, + ApiVulnerability, + Page, + Severity, + SeverityCounts, +} from '../api/types.js'; +import { projectLabel, resolveOrganization, resolveProject, resolveService } from '../resolve.js'; import { runTool, type ToolContext } from './context.js'; import { toolResult } from './result.js'; @@ -13,6 +21,67 @@ const projectSchema = z.object({ modules: z.array(z.string()), }); +const SEVERITIES = ['critical', 'high', 'medium', 'low', 'unknown'] as const; +const SEVERITY_ES: Record = { + critical: ['crítica', 'críticas'], + high: ['alta', 'altas'], + medium: ['media', 'medias'], + low: ['baja', 'bajas'], + unknown: ['desconocida', 'desconocidas'], +}; + +const severityCountsSchema = z.object({ + critical: z.number(), + high: z.number(), + medium: z.number(), + low: z.number(), + unknown: z.number(), +}); + +const serviceSummarySchema = z.object({ + id: z.string(), + name: z.string(), + slug: z.string().nullable(), + lastAnalysisAt: z.string().nullable(), + score: z.number().nullable(), + severityCounts: severityCountsSchema.nullable(), + policyCompliant: z.boolean().nullable(), +}); + +const failedRuleSchema = z.object({ + policy: z.string(), + enforcement: z.string(), + rule: z.string(), + actual: z.unknown(), + limit: z.unknown(), + message: z.string(), +}); + +const vulnerabilitySchema = z.object({ + id: z.string(), + package: z.string(), + installedVersion: z.string(), + fixedVersion: z.string().nullable(), + severity: z.string(), + kev: z.boolean(), + title: z.string(), +}); + +/** "2 críticas, 5 altas" (only the non-zero ones, in severity order). */ +export function describeCounts(counts: Partial | null | undefined): string { + if (!counts) return ''; + return SEVERITIES.filter((s) => (counts[s] ?? 0) > 0) + .map((s) => `${counts[s]} ${SEVERITY_ES[s][counts[s] === 1 ? 0 : 1]}`) + .join(', '); +} + +const policyText = (compliant: boolean | null, failed: number | null): string => + compliant === null + ? 'sin política evaluada' + : compliant + ? 'política CUMPLIDA' + : `política INCUMPLIDA${failed ? ` (${failed} ${failed === 1 ? 'regla' : 'reglas'})` : ''}`; + export function registerCodeReportTools(server: McpServer, ctx: ToolContext): void { server.registerTool( 'list_projects', @@ -49,5 +118,177 @@ export function registerCodeReportTools(server: McpServer, ctx: ToolContext): vo }), ); - // TODO(#129): list_services, get_service_report, list_service_vulnerabilities + server.registerTool( + 'list_services', + { + title: 'List services of a project', + description: + 'Lists the services (code repositories) of a project with the summary of their last Code Report analysis: ' + + 'risk score, vulnerability counts by severity and whether the security policy is met. ' + + 'The score is a RISK: higher is worse. Services never analysed have null analysis fields. ' + + 'Use it to see which services of a project are in the worst shape or to discover service slugs ' + + '(services are referred to as org/project/service).', + inputSchema: { + project: z.string().describe('Project as "org/project", "project" (if unique) or its 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: { + project: z.string(), + services: z.array(serviceSummarySchema), + nextCursor: z.string().nullable(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ project, limit, cursor }) => + runTool(ctx, 'list_services', async () => { + const proj = await resolveProject(ctx.client, project); + const label = projectLabel(proj); + const page = await ctx.client.get>('/api/code-report/services', { + projectId: proj.id, + limit, + cursor, + }); + const lines = page.items.map((s) => { + const name = s.slug ?? s.name; + if (s.score === null) return `${name}: sin análisis`; + const counts = describeCounts(s.severityCounts); + return `${name}: riesgo ${s.score}${counts ? `, ${counts}` : ''} · ${policyText(s.policyCompliant, null)}`; + }); + const summary = page.items.length + ? `${label}: ${page.items.length} ${page.items.length === 1 ? 'servicio' : 'servicios'} (riesgo: más alto = peor).\n` + + lines.join('\n') + + (page.nextCursor ? '\n(hay más: usa cursor)' : '') + : `${label} no tiene servicios.`; + return toolResult(summary, { + project: label, + services: page.items, + nextCursor: page.nextCursor, + }); + }), + ); + + server.registerTool( + 'get_code_report', + { + title: 'Get the Code Report of a service', + description: + 'Returns the latest Code Report analysis of one service: date, commit and branch, risk score, ' + + 'vulnerabilities by severity, security policy compliance (with the failed rules) and, when ' + + 'monitoring is enabled, the monitors linked to the service. ' + + 'IMPORTANT: score is a RISK (higher is worse), not a quality grade. ' + + 'Use it to answer "how is the code report of X?". For the list of CVEs use list_service_cves.', + inputSchema: { + service: z + .string() + .describe('Service as "org/project/service" (slugs or names) or its id.'), + }, + outputSchema: { + service: z.string(), + report: serviceSummarySchema.extend({ + projectId: z.string(), + commit: z.string().nullable(), + branch: z.string().nullable(), + securityPolicy: z + .object({ + status: z.string().nullable(), + compliant: z.boolean().nullable(), + failedRules: z.array(failedRuleSchema), + }) + .nullable(), + monitors: z + .array(z.object({ id: z.string(), name: z.string(), status: z.string() })) + .optional(), + }), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ service }) => + runTool(ctx, 'get_code_report', async () => { + const svc = await resolveService(ctx.client, service); + const report = await ctx.client.get( + `/api/code-report/services/${encodeURIComponent(svc.id)}`, + ); + const label = svc.project + ? `${projectLabel(svc.project)}/${svc.slug ?? svc.name}` + : (report.slug ?? report.name); + let summary: string; + if (report.score === null) { + summary = `${label}: sin análisis de Code Report todavía.`; + } else { + const counts = describeCounts(report.severityCounts); + const failed = report.securityPolicy?.failedRules.length ?? 0; + summary = + `${label}: riesgo ${report.score} (más alto = peor)` + + (counts ? `, ${counts}` : ', sin vulnerabilidades') + + ` · ${policyText(report.policyCompliant, failed)}`; + if (report.lastAnalysisAt) summary += `\nÚltimo análisis: ${report.lastAnalysisAt}`; + if (report.branch || report.commit) { + summary += ` (${[report.branch, report.commit?.slice(0, 7)].filter(Boolean).join('@')})`; + } + const down = (report.monitors ?? []).filter((m) => m.status === 'down'); + if (down.length) summary += `\nMonitores caídos: ${down.map((m) => m.name).join(', ')}.`; + } + return toolResult(summary, { service: label, report }); + }), + ); + + server.registerTool( + 'list_service_cves', + { + title: 'List the CVEs of a service', + description: + 'Lists the vulnerabilities (CVEs) found in the latest Code Report analysis of a service, worst first ' + + '(severity, then KEV): package, installed and fixed version, severity and title. ' + + 'kev=true means the CVE is actively exploited, but it is only flagged when the CVE is in the ' + + 'CVE feed of the organization (otherwise it shows false). ' + + 'Use it for "what critical CVEs affect X?". For CVEs of a technology across the organization use list_technology_cves.', + inputSchema: { + service: z + .string() + .describe('Service as "org/project/service" (slugs or names) or its id.'), + severity: z + .array(z.enum(SEVERITIES)) + .min(1) + .optional() + .describe('Only these severities, e.g. ["critical","high"]. Omit for all.'), + fixable: z + .boolean() + .optional() + .describe('true: only CVEs with a fixed version available; false: only those without.'), + 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: { + service: z.string(), + vulnerabilities: z.array(vulnerabilitySchema), + nextCursor: z.string().nullable(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ service, severity, fixable, limit, cursor }) => + runTool(ctx, 'list_service_cves', async () => { + const svc = await resolveService(ctx.client, service); + const label = svc.project ? `${projectLabel(svc.project)}/${svc.slug ?? svc.name}` : svc.id; + const page = await ctx.client.get>( + `/api/code-report/services/${encodeURIComponent(svc.id)}/vulnerabilities`, + { severity: severity?.join(','), fixable, limit, cursor }, + ); + const counts: Partial = {}; + for (const v of page.items) { + counts[v.severity as Severity] = (counts[v.severity as Severity] ?? 0) + 1; + } + const kev = page.items.filter((v) => v.kev).length; + const summary = page.items.length + ? `${label}: ${page.items.length} ${page.items.length === 1 ? 'CVE' : 'CVEs'}` + + ` (${[describeCounts(counts), kev ? `${kev} en KEV` : ''].filter(Boolean).join(', ')})` + + (page.nextCursor ? ' · hay más: usa cursor' : '') + : `${label}: ninguna vulnerabilidad con esos filtros (o sin análisis todavía).`; + return toolResult(summary, { + service: label, + vulnerabilities: page.items, + nextCursor: page.nextCursor, + }); + }), + ); } diff --git a/src/tools/cves.ts b/src/tools/cves.ts index 6cde488..3548190 100644 --- a/src/tools/cves.ts +++ b/src/tools/cves.ts @@ -1,6 +1,223 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import type { ToolContext } from './context.js'; +import * as z from 'zod'; +import type { ApiCveDetail, ApiCveFeed, ApiCveWatchlist } from '../api/types.js'; +import { resolveOrganization } from '../resolve.js'; +import { runTool, type ToolContext } from './context.js'; +import { toolResult } from './result.js'; -export function registerCveTools(_server: McpServer, _ctx: ToolContext): void { - // TODO(#129): get_cve_watchlist, list_cve_feed, get_cve +const FEED_DISABLED = 'El feed de CVEs por tecnología está desactivado en esta instancia.'; +const SEVERITIES = ['low', 'medium', 'high', 'critical'] as const; +const MAX_REFERENCES = 10; +const MAX_DETAILS = 1000; + +const cveItemSchema = z.object({ + id: z.string(), + aliases: z.array(z.string()), + severity: z.string(), + cvss: z.number().nullable(), + epss: z.number().nullable(), + kev: z.boolean(), + technologies: z.array(z.string()), + summary: z.string(), + publishedAt: z.string().nullable(), + modifiedAt: z.string().nullable(), + affectsMe: z.boolean().optional(), +}); + +const orgField = z.string().describe('Organization slug or id.'); + +export function registerCveTools(server: McpServer, ctx: ToolContext): void { + server.registerTool( + 'list_technology_cves', + { + title: 'List CVEs of the technologies an organization watches', + description: + 'Lists the CVEs of the organization CVE feed (the technologies it watches, e.g. Node.js, PostgreSQL), ' + + 'newest/most relevant first, with severity, CVSS, EPSS, KEV (actively exploited) and a short summary. ' + + 'Use affects_me=true to keep only the CVEs that affect services scanned in the organization projects ' + + '(needs permission to read the organization projects, otherwise it fails with a permission error). ' + + 'The severity filter is a MINIMUM: "high" returns high and critical. ' + + 'If the feed is disabled on this instance it says so, without error. ' + + 'To see the CVEs of one service use list_service_cves; for one CVE in detail use get_cve.', + inputSchema: { + organization: orgField, + technology: z + .string() + .optional() + .describe('Technology id from the watchlist (see get_cve_watchlist), e.g. "nodejs".'), + severity: z.enum(SEVERITIES).optional().describe('Minimum severity.'), + kev: z + .boolean() + .optional() + .describe('true: only CVEs in the CISA KEV catalog (known exploited).'), + affects_me: z + .boolean() + .optional() + .describe('true: only CVEs that affect your scanned services.'), + 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: { + feedEnabled: z.boolean(), + cves: z.array(cveItemSchema), + total: z.number(), + nextCursor: z.string().nullable(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ organization, technology, severity, kev, affects_me, limit, cursor }) => + runTool(ctx, 'list_technology_cves', async () => { + const org = await resolveOrganization(ctx.client, organization); + const feed = await ctx.client.get('/api/cves/feed', { + organizationId: org.id, + technology, + severity, + kev, + affectsMe: affects_me, + limit, + cursor, + }); + if (!feed.feedEnabled) { + return toolResult(FEED_DISABLED, { + feedEnabled: false, + cves: [], + total: 0, + nextCursor: null, + }); + } + const items = feed.items; + const critical = items.filter((c) => c.severity === 'critical').length; + const inKev = items.filter((c) => c.kev).length; + const mine = items.filter((c) => c.affectsMe).length; + const details = [ + critical ? `${critical} ${critical === 1 ? 'crítica' : 'críticas'}` : '', + inKev ? `${inKev} en KEV` : '', + mine ? `${mine} te ${mine === 1 ? 'afecta' : 'afectan'}` : '', + ].filter(Boolean); + const summary = + `${feed.total} ${feed.total === 1 ? 'CVE' : 'CVEs'} en ${org.slug}` + + (items.length && details.length ? ` (${details.join(', ')} en esta página)` : '') + + (feed.nextCursor ? ' · hay más: usa cursor' : ''); + return toolResult(summary, { + feedEnabled: true, + cves: items, + total: feed.total, + nextCursor: feed.nextCursor, + }); + }), + ); + + server.registerTool( + 'get_cve', + { + title: 'Get a CVE in detail', + description: + 'Returns one CVE from the organization CVE feed: severity, CVSS (with vector), EPSS, KEV, CWE, ' + + 'affected packages, fixed versions, references and, when you can read the projects, which of ' + + 'your services are affected (as org/project/service). ' + + 'Use it after list_technology_cves or list_service_cves to answer "what is CVE-X and does it affect me?". ' + + 'The CVE must be in the feed of the organization (404 otherwise).', + inputSchema: { + id: z.string().describe('CVE id, e.g. "CVE-2026-12345" (or an alias such as a GHSA id).'), + organization: orgField, + }, + outputSchema: { + feedEnabled: z.boolean(), + cve: z + .object({ + id: z.string(), + title: z.string(), + aliases: z.array(z.string()), + severity: z.string(), + cvss: z.number().nullable(), + cvssVector: z.string().nullable(), + epss: z.number().nullable(), + epssPercentile: z.number().nullable(), + kev: z.boolean(), + kevAddedAt: z.string().nullable(), + cwe: z.array(z.string()), + technologies: z.array(z.string()), + summary: z.string(), + details: z.string(), + fixedVersions: z.array(z.string()), + affected: z.array(z.unknown()), + references: z.array(z.unknown()), + publishedAt: z.string().nullable(), + modifiedAt: z.string().nullable(), + affectsMe: z.boolean().optional(), + affectedServices: z.array(z.object({ service: z.string(), id: z.string() })).optional(), + }) + .nullable(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ id, organization }) => + runTool(ctx, 'get_cve', async () => { + const org = await resolveOrganization(ctx.client, organization); + const detail = await ctx.client.get( + `/api/cves/${encodeURIComponent(id.trim())}`, + { organizationId: org.id }, + ); + if (!detail.feedEnabled) { + return toolResult(FEED_DISABLED, { feedEnabled: false, cve: null }); + } + const { feedEnabled: _enabled, affectedServices, references, details, ...rest } = detail; + const services = affectedServices?.map((s) => ({ + service: `${org.slug}/${s.projectSlug}/${s.serviceSlug}`, + id: s.serviceId, + })); + const cve = { + ...rest, + details: details.length > MAX_DETAILS ? `${details.slice(0, MAX_DETAILS - 1)}…` : details, + references: references.slice(0, MAX_REFERENCES), + ...(services ? { affectedServices: services } : {}), + }; + const parts = [ + `${detail.id}: severidad ${detail.severity}`, + detail.cvss !== null ? `CVSS ${detail.cvss}` : '', + detail.kev ? 'en KEV (explotada activamente)' : '', + detail.fixedVersions.length ? `arreglada en ${detail.fixedVersions.join(', ')}` : '', + ].filter(Boolean); + let summary = `${parts.join(' · ')}\n${detail.title}`; + if (services) { + summary += services.length + ? `\nAfecta a: ${services.map((s) => s.service).join(', ')}.` + : '\nNo afecta a ningún servicio escaneado.'; + } + return toolResult(summary, { feedEnabled: true, cve }); + }), + ); + + server.registerTool( + 'get_cve_watchlist', + { + title: 'Get the CVE watchlist of an organization', + description: + 'Returns which technologies the organization watches for CVEs (and the minimum severity / KEV settings). ' + + 'Use it to know the technology ids accepted by list_technology_cves.', + inputSchema: { organization: orgField }, + outputSchema: { + feedEnabled: z.boolean(), + technologies: z.array(z.object({ id: z.string(), name: z.string() }).passthrough()), + minSeverity: z.string().nullable(), + includeKev: z.boolean(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ organization }) => + runTool(ctx, 'get_cve_watchlist', async () => { + const org = await resolveOrganization(ctx.client, organization); + const list = await ctx.client.get('/api/cves/watchlist', { + organizationId: org.id, + }); + const names = list.technologies.map((t) => `${t.name} (${t.id})`); + const summary = + (names.length + ? `${org.slug} vigila ${names.length} ${names.length === 1 ? 'tecnología' : 'tecnologías'}: ${names.join(', ')}.` + : `${org.slug} no vigila ninguna tecnología.`) + + (list.minSeverity ? ` Severidad mínima: ${list.minSeverity}.` : '') + + (list.feedEnabled ? '' : ` ${FEED_DISABLED}`); + return toolResult(summary, list); + }), + ); } diff --git a/test/code-report-cves.test.ts b/test/code-report-cves.test.ts new file mode 100644 index 0000000..205c8c8 --- /dev/null +++ b/test/code-report-cves.test.ts @@ -0,0 +1,312 @@ +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'; + +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()); + +const call = async (name: string, args: Record) => { + const result = await client.callTool({ name, arguments: args }); + return { + isError: Boolean(result.isError), + text: (result.content as { text: string }[])[0]!.text, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data: result.structuredContent as Record | undefined, + }; +}; +const apiPaths = () => + api.requests.map((r) => r.path).filter((p) => !p.startsWith('/api/projects')); + +describe('Code Report and CVE tools', () => { + it('are listed as read-only', async () => { + const { tools } = await client.listTools(); + for (const name of [ + 'list_projects', + 'list_services', + 'get_code_report', + 'list_service_cves', + 'list_technology_cves', + 'get_cve', + 'get_cve_watchlist', + ]) { + const tool = tools.find((t) => t.name === name); + expect(tool, name).toBeDefined(); + expect(tool!.annotations?.readOnlyHint, name).toBe(true); + expect(tool!.annotations?.openWorldHint, name).toBe(false); + expect(tool!.title, name).toBeTruthy(); + } + }); + + describe('list_services', () => { + it('resolves org/project and summarises risk', async () => { + const r = await call('list_services', { project: 'acme/billing' }); + expect(r.isError).toBe(false); + expect(r.text).toContain('acme/billing: 2 servicios'); + expect(r.text).toContain('billing-api: riesgo 72, 2 críticas, 3 altas, 5 medias, 1 baja'); + expect(r.text).toContain('billing-worker: sin análisis'); + expect(apiPaths()).toEqual([`/api/code-report/services?projectId=${IDS.acmeBilling}`]); + }); + + it('accepts an id, paginates and passes limit/cursor', async () => { + const first = await call('list_services', { project: IDS.acmeBilling, limit: 1 }); + expect(first.data!.services).toHaveLength(1); + expect(first.data!.nextCursor).toBeTruthy(); + expect(first.text).toContain('hay más: usa cursor'); + const second = await call('list_services', { + project: IDS.acmeBilling, + limit: 1, + cursor: first.data!.nextCursor, + }); + expect(second.data!.services[0].name).toBe('billing-worker'); + expect(second.data!.nextCursor).toBeNull(); + expect(api.requests.at(-1)!.path).toContain('limit=1&cursor='); + }); + + it('reports an ambiguous slug and an unknown project', async () => { + const ambiguous = await call('list_services', { project: 'billing' }); + expect(ambiguous.isError).toBe(true); + expect(ambiguous.text).toMatch(/ambiguous/); + expect(ambiguous.text).toContain('acme/billing'); + const unknown = await call('list_services', { project: 'acme/nope' }); + expect(unknown.isError).toBe(true); + expect(unknown.text).toMatch(/not found/); + }); + }); + + describe('get_code_report', () => { + it('summarises score, severities, policy and monitors by slug', async () => { + const r = await call('get_code_report', { service: 'acme/billing/billing-api' }); + expect(r.isError).toBe(false); + expect(r.text).toContain( + 'acme/billing/billing-api: riesgo 72 (más alto = peor), 2 críticas, 3 altas, 5 medias, 1 baja · política INCUMPLIDA (1 regla)', + ); + expect(r.text).toContain('main@abc1234'); + expect(r.text).toContain('Monitores caídos: billing-api'); + expect(r.data!.report.securityPolicy.failedRules[0].rule).toBe('critical'); + expect(apiPaths()).toEqual([ + `/api/code-report/services?projectId=${IDS.acmeBilling}&limit=100`, + `/api/code-report/services/${IDS.svcBillingApi}`, + ]); + }); + + it('accepts an id without resolving', async () => { + const r = await call('get_code_report', { service: IDS.svcWebFront }); + expect(r.text).toContain('web-front: riesgo 95'); + expect(r.text).toContain('política CUMPLIDA'); + expect(apiPaths()).toEqual([`/api/code-report/services/${IDS.svcWebFront}`]); + }); + + it('handles a service never analysed', async () => { + const r = await call('get_code_report', { service: 'acme/billing/billing-worker' }); + expect(r.isError).toBe(false); + expect(r.text).toContain('sin análisis'); + }); + + it('errors: unknown service, 403, 404, 429', async () => { + const unknown = await call('get_code_report', { service: 'acme/billing/nope' }); + expect(unknown.isError).toBe(true); + expect(unknown.text).toContain('billing-api'); + const bad = await call('get_code_report', { service: 'billing-api' }); + expect(bad.isError).toBe(true); + expect(bad.text).toMatch(/org\/project\/service/); + + api.failNext({ status: 403, code: 'forbidden', error: 'Forbidden' }); + expect((await call('get_code_report', { service: IDS.svcWebFront })).text).toMatch( + /^Sin permiso/, + ); + const notFound = await call('get_code_report', { service: IDS.acmeBilling }); + expect(notFound.isError).toBe(true); + expect(notFound.text).toMatch(/No encontrado o sin acceso/); + api.failNext({ status: 429, code: 'rate_limited', headers: { 'Retry-After': '3' } }); + expect((await call('get_code_report', { service: IDS.svcWebFront })).text).toMatch( + /reintenta en 3 s/, + ); + }); + }); + + describe('list_service_cves', () => { + it('sends severity and fixable as query and summarises', async () => { + const r = await call('list_service_cves', { + service: 'acme/billing/billing-api', + severity: ['critical', 'high'], + fixable: true, + }); + expect(r.isError).toBe(false); + const req = api.requests.at(-1)!; + expect(req.path).toBe( + `/api/code-report/services/${IDS.svcBillingApi}/vulnerabilities?severity=critical%2Chigh&fixable=true`, + ); + expect(r.data!.vulnerabilities.map((v: { id: string }) => v.id)).toEqual(['CVE-2026-0001']); + expect(r.text).toContain('1 CVE (1 crítica, 1 en KEV)'); + }); + + it('paginates', async () => { + const first = await call('list_service_cves', { service: IDS.svcBillingApi, limit: 1 }); + expect(first.data!.nextCursor).toBeTruthy(); + expect(first.text).toContain('hay más: usa cursor'); + const second = await call('list_service_cves', { + service: IDS.svcBillingApi, + limit: 1, + cursor: first.data!.nextCursor, + }); + expect(second.data!.vulnerabilities[0].id).toBe('CVE-2026-0003'); + }); + + it('empty result and invalid severity', async () => { + const empty = await call('list_service_cves', { service: IDS.svcWebFront }); + expect(empty.text).toContain('ninguna vulnerabilidad'); + const invalid = await client.callTool({ + name: 'list_service_cves', + arguments: { service: IDS.svcWebFront, severity: ['nope'] }, + }); + expect(invalid.isError).toBe(true); + }); + }); + + describe('list_technology_cves', () => { + it('resolves the organization and sends the filters', async () => { + const r = await call('list_technology_cves', { + organization: 'acme', + technology: 'nodejs', + severity: 'high', + kev: true, + affects_me: true, + limit: 5, + }); + expect(r.isError).toBe(false); + expect(api.requests.at(-1)!.path).toBe( + `/api/cves/feed?organizationId=${IDS.orgAcme}&technology=nodejs&severity=high&kev=true&affectsMe=true&limit=5`, + ); + expect(r.text).toContain('1 CVE en acme (1 crítica, 1 en KEV, 1 te afecta en esta página)'); + expect(r.data!.cves[0].id).toBe('CVE-2026-0001'); + }); + + it('paginates with total', async () => { + const first = await call('list_technology_cves', { organization: IDS.orgAcme, limit: 1 }); + expect(first.text).toContain('2 CVEs en acme'); + expect(first.text).toContain('hay más: usa cursor'); + const second = await call('list_technology_cves', { + organization: 'acme', + limit: 1, + cursor: first.data!.nextCursor, + }); + expect(second.data!.cves[0].id).toBe('CVE-2026-0002'); + expect(second.data!.nextCursor).toBeNull(); + }); + + it('feed disabled is not an error', async () => { + api.route('GET', /^\/api\/cves\/feed$/, () => ({ + body: { feedEnabled: false, items: [], nextCursor: null, total: 0 }, + })); + const r = await call('list_technology_cves', { organization: 'acme' }); + expect(r.isError).toBe(false); + expect(r.text).toContain('El feed de CVEs por tecnología está desactivado en esta instancia'); + expect(r.data!.feedEnabled).toBe(false); + }); + + it('affects_me without permission gives a useful 403', async () => { + api.route('GET', /^\/api\/cves\/feed$/, () => ({ + status: 403, + body: { + error: 'affectsMe requires organization:projects:read', + code: 'forbidden', + }, + })); + const r = await call('list_technology_cves', { organization: 'acme', affects_me: true }); + expect(r.isError).toBe(true); + expect(r.text).toBe('Sin permiso: affectsMe requires organization:projects:read'); + }); + + it('unknown organization and 429', async () => { + const unknown = await call('list_technology_cves', { organization: 'nope' }); + expect(unknown.isError).toBe(true); + expect(unknown.text).toContain('Known organizations: acme, globex'); + api.failNext({ status: 429, code: 'rate_limited' }); + const limited = await call('list_technology_cves', { organization: 'acme' }); + expect(limited.text).toMatch(/Límite de peticiones/); + }); + }); + + describe('get_cve', () => { + it('returns the detail', async () => { + const r = await call('get_cve', { id: 'CVE-2026-0001', organization: 'acme' }); + expect(r.isError).toBe(false); + expect(api.requests.at(-1)!.path).toBe( + `/api/cves/CVE-2026-0001?organizationId=${IDS.orgAcme}`, + ); + expect(r.text).toContain('CVE-2026-0001: severidad critical · CVSS 9.8 · en KEV'); + expect(r.data!.cve.id).toBe('CVE-2026-0001'); + }); + + it('lists affected services as org/project/service and trims references', async () => { + const base = api.db.cves[0]!; + api.db.cveDetails['CVE-2026-0001'] = { + feedEnabled: true, + ...base, + title: 'Prototype pollution', + cvssVector: null, + epssPercentile: null, + kevAddedAt: null, + cwe: [], + fixedVersions: ['4.17.21'], + affected: [], + references: Array.from({ length: 30 }, (_, i) => ({ url: `https://x/${i}` })), + details: 'x'.repeat(5000), + affectedServices: [ + { + projectId: IDS.acmeBilling, + projectSlug: 'billing', + projectName: 'Billing', + serviceId: IDS.svcBillingApi, + serviceSlug: 'billing-api', + serviceName: 'billing-api', + }, + ], + }; + const r = await call('get_cve', { id: 'CVE-2026-0001', organization: 'acme' }); + expect(r.text).toContain('Afecta a: acme/billing/billing-api'); + expect(r.text).toContain('arreglada en 4.17.21'); + expect(r.data!.cve.references).toHaveLength(10); + expect(r.data!.cve.details.length).toBeLessThanOrEqual(1000); + }); + + it('404 and feed disabled', async () => { + const missing = await call('get_cve', { id: 'CVE-1999-0', organization: 'acme' }); + expect(missing.isError).toBe(true); + expect(missing.text).toMatch(/No encontrado/); + api.route('GET', /^\/api\/cves\/([^/]+)$/, () => ({ + body: { feedEnabled: false, cve: null }, + })); + const off = await call('get_cve', { id: 'CVE-2026-0001', organization: 'acme' }); + expect(off.isError).toBe(false); + expect(off.text).toContain('desactivado'); + }); + }); + + describe('get_cve_watchlist', () => { + it('lists watched technologies', async () => { + const r = await call('get_cve_watchlist', { organization: 'acme' }); + expect(r.text).toContain('acme vigila 1 tecnología: Node.js (nodejs)'); + expect(api.requests.at(-1)!.path).toBe(`/api/cves/watchlist?organizationId=${IDS.orgAcme}`); + }); + }); +});