Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
247 changes: 244 additions & 3 deletions src/tools/code-report.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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<Severity, [string, string]> = {
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<SeverityCounts> | 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',
Expand Down Expand Up @@ -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<Page<ApiServiceSummary>>('/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<ApiServiceReport>(
`/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<Page<ApiVulnerability>>(
`/api/code-report/services/${encodeURIComponent(svc.id)}/vulnerabilities`,
{ severity: severity?.join(','), fixable, limit, cursor },
);
const counts: Partial<SeverityCounts> = {};
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,
});
}),
);
}
Loading
Loading