@efraindrummer/ghostdeps 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/) y [SemVer](https://semver.org/lang/es/).
4
4
 
5
+ ## [0.3.0] - 2026-11-25
6
+
7
+ ### Añadido
8
+ - **Asesor de Ciberseguridad con IA (`--ai`)**: Integración nativa sin dependencias pesadas con **Google Gemini**, **Anthropic Claude** y **OpenAI ChatGPT**. Detecta automáticamente claves de API (`GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`) y genera recomendaciones concretas de migración, alternativas seguras y plan de mitigación priorizado.
9
+ - **Servidor MCP (Model Context Protocol) (`--mcp`)**: Permite a agentes de IA (Claude Desktop, Cursor, Gemini CLI, etc.) invocar a GhostDeps como una herramienta (`ghostdeps_audit`) mediante stdio (JSON-RPC 2.0).
10
+ - Flags `--ai-provider <gemini|anthropic|openai>` y `--ai-model <model>`.
11
+
5
12
  ## [0.2.0] - 2026-11-24
6
13
 
7
14
  ### Añadido
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  Los escáneres de vulnerabilidades te avisan cuando ya existe un CVE. GhostDeps intenta avisarte **antes**: cuando una dependencia lleva años sin commits, depende de una sola persona, está archivada/deprecated o cambió de manos de forma sospechosa (el patrón de `event-stream`, `ua-parser-js` o `xz`).
10
10
 
11
11
  ```
12
- 👻 GhostDeps v0.2.0 · mi-app
12
+ 👻 GhostDeps v0.3.0 · mi-app
13
13
  ┌─────────────────────────────┬───────┬──────────────────┬───────────────┬──────────────────────────────────────────────┐
14
14
  │ Paquete │ Score │ Días últ. commit │ Mant. activos │ Alerta principal │
15
15
  ├─────────────────────────────┼───────┼──────────────────┼───────────────┼──────────────────────────────────────────────┤
@@ -126,6 +126,10 @@ ghostdeps --version
126
126
  | `--fail-under <score>` | Exit code `1` si algún paquete **evaluado** tiene score menor | — |
127
127
  | `-c, --concurrency <n>` | Paquetes analizados en paralelo (1–32) | `4` |
128
128
  | `--explain` | Desglose de penalizaciones de cada paquete | `false` |
129
+ | `--ai` | Asesor de ciberseguridad con IA (reemplazos y plan de mitigación) | `false` |
130
+ | `--ai-provider <prov>` | Proveedor de IA: `gemini`, `anthropic` u `openai` | autodetección |
131
+ | `--ai-model <model>` | Modelo específico de IA a consultar | por defecto del proveedor |
132
+ | `--mcp` | Inicia el servidor MCP (Model Context Protocol) sobre stdio | `false` |
129
133
  | `--no-cache` | No lee ni escribe la caché en disco | caché activa |
130
134
  | `--cache-ttl <horas>` | TTL de la caché | `24` |
131
135
  | `--timeout <ms>` | Timeout por petición | `15000` |
@@ -272,6 +276,55 @@ La validación es estricta: una clave mal escrita o un valor fuera de rango abor
272
276
 
273
277
  Con la propiedad `$schema`, VS Code y otros editores ofrecen **autocompletado y validación** mientras editas. Hay un ejemplo completo en [`examples/.ghostdepsrc.json`](examples/.ghostdepsrc.json) y el esquema en [`schema/ghostdepsrc.schema.json`](schema/ghostdepsrc.schema.json).
274
278
 
279
+ ### Asesor de Ciberseguridad con IA (`--ai`)
280
+
281
+ GhostDeps integra conexión nativa (sin SDKs pesados) con **Google Gemini**, **Anthropic Claude** y **OpenAI ChatGPT**.
282
+
283
+ Al activar `--ai`, el motor analiza las dependencias con puntuación baja o en riesgo y consulta al modelo de IA para generar:
284
+ 1. **Diagnóstico ejecutivo:** Evaluación del nivel de exposición ante ataques a la cadena de suministro.
285
+ 2. **Reemplazos concretos:** Alternativas activas, mantenidas y seguras (o APIs nativas de Node.js como `fetch`, `crypto`, etc.).
286
+ 3. **Plan de mitigación:** Instrucciones paso a paso (ej. `overrides` en `package.json` para transitivas, o refactorización).
287
+
288
+ ```bash
289
+ # Exporta tu clave favorita (autodetección inteligente)
290
+ export GEMINI_API_KEY="AIzaSy..." # Gemini (por defecto: gemini-1.5-flash)
291
+ # o bien:
292
+ export ANTHROPIC_API_KEY="sk-ant-..." # Claude (por defecto: claude-3-5-haiku)
293
+ # o bien:
294
+ export OPENAI_API_KEY="sk-proj-..." # OpenAI (por defecto: gpt-4o-mini)
295
+
296
+ # Ejecutar auditoría con asesoría de IA
297
+ ghostdeps --ai
298
+
299
+ # Elegir proveedor o modelo específico
300
+ ghostdeps --ai --ai-provider anthropic --ai-model claude-3-5-sonnet-20241022
301
+ ghostdeps --ai --format markdown -o informe-con-ia.md
302
+ ```
303
+
304
+ ### Servidor MCP para Agentes de IA (`--mcp`)
305
+
306
+ GhostDeps implementa el estándar abierto **Model Context Protocol (MCP)** sobre `stdio` (JSON-RPC 2.0). Esto permite que agentes como **Claude Desktop**, **Cursor**, **Gemini CLI** o cualquier cliente MCP invoquen a GhostDeps directamente como una herramienta (`ghostdeps_audit`).
307
+
308
+ #### Configuración en Claude Desktop o Cursor
309
+ En tu archivo de configuración MCP (ej. `claude_desktop_config.json` o `.cursor/mcp.json`):
310
+
311
+ ```json
312
+ {
313
+ "mcpServers": {
314
+ "ghostdeps": {
315
+ "command": "npx",
316
+ "args": ["-y", "@efraindrummer/ghostdeps", "--mcp"],
317
+ "env": {
318
+ "GITHUB_TOKEN": "ghp_..."
319
+ }
320
+ }
321
+ }
322
+ }
323
+ ```
324
+
325
+ Una vez configurado, tu agente de IA puede auditar proyectos automáticamente cuando se lo pidas en lenguaje natural:
326
+ > *"Revisa las dependencias de este repositorio con GhostDeps y dime cuáles tienen riesgo de abandono o bus factor bajo."*
327
+
275
328
  ### Formatos de salida
276
329
 
277
330
  | Formato | Uso | Ejemplo |
@@ -0,0 +1,162 @@
1
+ export function detectAiConfig(options = {}) {
2
+ const env = process.env;
3
+ const geminiKey = options.apiKey || env.GEMINI_API_KEY || env.GOOGLE_API_KEY;
4
+ const anthropicKey = options.apiKey || env.ANTHROPIC_API_KEY;
5
+ const openaiKey = options.apiKey || env.OPENAI_API_KEY;
6
+ if (options.provider === 'gemini') {
7
+ if (!geminiKey)
8
+ return null;
9
+ return { provider: 'gemini', apiKey: geminiKey, model: options.model || 'gemini-1.5-flash' };
10
+ }
11
+ if (options.provider === 'anthropic') {
12
+ if (!anthropicKey)
13
+ return null;
14
+ return { provider: 'anthropic', apiKey: anthropicKey, model: options.model || 'claude-3-5-haiku-20241022' };
15
+ }
16
+ if (options.provider === 'openai') {
17
+ if (!openaiKey)
18
+ return null;
19
+ return { provider: 'openai', apiKey: openaiKey, model: options.model || 'gpt-4o-mini' };
20
+ }
21
+ // Auto-detección por variables de entorno disponibles
22
+ if (geminiKey) {
23
+ return { provider: 'gemini', apiKey: geminiKey, model: options.model || 'gemini-1.5-flash' };
24
+ }
25
+ if (anthropicKey) {
26
+ return { provider: 'anthropic', apiKey: anthropicKey, model: options.model || 'claude-3-5-haiku-20241022' };
27
+ }
28
+ if (openaiKey) {
29
+ return { provider: 'openai', apiKey: openaiKey, model: options.model || 'gpt-4o-mini' };
30
+ }
31
+ return null;
32
+ }
33
+ export function buildAiPrompt(reports, summary) {
34
+ const problematic = reports.filter((r) => r.status === 'evaluated' && r.result && r.result.score < 70);
35
+ const payload = problematic.map((r) => ({
36
+ name: r.name,
37
+ version: r.spec,
38
+ kind: r.kind,
39
+ via: r.via,
40
+ score: r.result?.score,
41
+ category: r.result?.category,
42
+ mainAlert: r.result?.mainAlert?.message,
43
+ penalties: r.result?.penalties.map((p) => p.message),
44
+ daysSinceLastCommit: r.signals?.daysSinceLastCommit,
45
+ activeMaintainers: r.signals?.activeMaintainers,
46
+ archived: r.signals?.archived,
47
+ deprecated: r.signals?.deprecated,
48
+ }));
49
+ return `Actúa como un Ingeniero Principal de Ciberseguridad y Supply Chain Security experto en el ecosistema Node.js / JavaScript.
50
+
51
+ Se ha ejecutado la herramienta GhostDeps sobre un proyecto y se han detectado ${problematic.length} dependencias en riesgo (de un total de ${summary.total}):
52
+ - Críticas/Fantasma: ${summary.critical}
53
+ - Precaución: ${summary.caution}
54
+
55
+ A continuación tienes el detalle de las dependencias problemáticas:
56
+ \`\`\`json
57
+ ${JSON.stringify(payload, null, 2)}
58
+ \`\`\`
59
+
60
+ Por favor, proporciona una respuesta en Markdown clara, profesional y concisa (en español):
61
+ 1. **Diagnóstico Ejecutivo de Ciberseguridad**: Resumen rápido del nivel de exposición del proyecto.
62
+ 2. **Alternativas y Reemplazos Recomendados**: Para cada dependencia crítica o con bajo score, sugiere un reemplazo moderno, activo y seguro del ecosistema npm (o APIs nativas de Node.js como \`fetch\`, \`crypto\`, etc., si aplica).
63
+ 3. **Plan de Remediación Priorizado**: Qué acciones inmediatas debe tomar el equipo (ej. overrides en package.json para transitivas, vendorización, o actualización de paquetes directos).
64
+
65
+ Mantén la respuesta práctica y orientada a código.`;
66
+ }
67
+ export async function queryGemini(apiKey, model, prompt, timeoutMs = 25000) {
68
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`;
69
+ const res = await fetch(url, {
70
+ method: 'POST',
71
+ headers: { 'content-type': 'application/json' },
72
+ body: JSON.stringify({
73
+ contents: [{ parts: [{ text: prompt }] }],
74
+ generationConfig: { temperature: 0.2, maxOutputTokens: 2000 },
75
+ }),
76
+ signal: AbortSignal.timeout(timeoutMs),
77
+ });
78
+ if (!res.ok) {
79
+ const errorText = await res.text().catch(() => '');
80
+ throw new Error(`Error en API de Gemini (HTTP ${res.status}): ${errorText.slice(0, 200)}`);
81
+ }
82
+ const json = (await res.json());
83
+ const text = json.candidates?.[0]?.content?.parts?.[0]?.text;
84
+ if (!text)
85
+ throw new Error('Respuesta vacía o inesperada de la API de Gemini.');
86
+ return text;
87
+ }
88
+ export async function queryAnthropic(apiKey, model, prompt, timeoutMs = 25000) {
89
+ const url = 'https://api.anthropic.com/v1/messages';
90
+ const res = await fetch(url, {
91
+ method: 'POST',
92
+ headers: {
93
+ 'content-type': 'application/json',
94
+ 'x-api-key': apiKey,
95
+ 'anthropic-version': '2023-06-01',
96
+ },
97
+ body: JSON.stringify({
98
+ model,
99
+ max_tokens: 2000,
100
+ temperature: 0.2,
101
+ messages: [{ role: 'user', content: prompt }],
102
+ }),
103
+ signal: AbortSignal.timeout(timeoutMs),
104
+ });
105
+ if (!res.ok) {
106
+ const errorText = await res.text().catch(() => '');
107
+ throw new Error(`Error en API de Anthropic (HTTP ${res.status}): ${errorText.slice(0, 200)}`);
108
+ }
109
+ const json = (await res.json());
110
+ const text = json.content?.find((c) => c.type === 'text')?.text;
111
+ if (!text)
112
+ throw new Error('Respuesta vacía o inesperada de la API de Anthropic.');
113
+ return text;
114
+ }
115
+ export async function queryOpenAI(apiKey, model, prompt, timeoutMs = 25000) {
116
+ const url = 'https://api.openai.com/v1/chat/completions';
117
+ const res = await fetch(url, {
118
+ method: 'POST',
119
+ headers: {
120
+ 'content-type': 'application/json',
121
+ authorization: `Bearer ${apiKey}`,
122
+ },
123
+ body: JSON.stringify({
124
+ model,
125
+ temperature: 0.2,
126
+ max_tokens: 2000,
127
+ messages: [{ role: 'user', content: prompt }],
128
+ }),
129
+ signal: AbortSignal.timeout(timeoutMs),
130
+ });
131
+ if (!res.ok) {
132
+ const errorText = await res.text().catch(() => '');
133
+ throw new Error(`Error en API de OpenAI (HTTP ${res.status}): ${errorText.slice(0, 200)}`);
134
+ }
135
+ const json = (await res.json());
136
+ const text = json.choices?.[0]?.message?.content;
137
+ if (!text)
138
+ throw new Error('Respuesta vacía o inesperada de la API de OpenAI.');
139
+ return text;
140
+ }
141
+ export async function analyzeWithAi(reports, summary, options = {}) {
142
+ const config = detectAiConfig(options);
143
+ if (!config)
144
+ return null;
145
+ const prompt = buildAiPrompt(reports, summary);
146
+ const timeoutMs = options.timeoutMs ?? 30000;
147
+ let analysis;
148
+ if (config.provider === 'gemini') {
149
+ analysis = await queryGemini(config.apiKey, config.model, prompt, timeoutMs);
150
+ }
151
+ else if (config.provider === 'anthropic') {
152
+ analysis = await queryAnthropic(config.apiKey, config.model, prompt, timeoutMs);
153
+ }
154
+ else {
155
+ analysis = await queryOpenAI(config.apiKey, config.model, prompt, timeoutMs);
156
+ }
157
+ return {
158
+ provider: config.provider,
159
+ model: config.model,
160
+ analysis,
161
+ };
162
+ }
package/dist/cli.js CHANGED
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import { stripVTControlCharacters } from 'node:util';
6
6
  import chalk from 'chalk';
7
7
  import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
8
+ import { analyzeWithAi, detectAiConfig } from './ai/advisor.js';
8
9
  import { analyzeAll, sortReports, summarize } from './analyzer.js';
9
10
  import { DiskCache, defaultCacheDir } from './clients/cache.js';
10
11
  import { GitHubClient } from './clients/github.js';
@@ -12,6 +13,7 @@ import { RateLimitGate } from './clients/http.js';
12
13
  import { NpmClient } from './clients/npm.js';
13
14
  import { createIgnoreMatcher, loadConfig } from './config.js';
14
15
  import { GhostDepsError, errorMessage } from './errors.js';
16
+ import { startMcpServer } from './mcp/server.js';
15
17
  import { readLockfile, resolveTransitive } from './parser/lockfile.js';
16
18
  import { readManifest } from './parser/manifest.js';
17
19
  import { renderMarkdown } from './render/markdown.js';
@@ -49,6 +51,10 @@ function collectList(value, previous = []) {
49
51
  }
50
52
  const log = (msg) => process.stderr.write(`${msg}\n`);
51
53
  async function run(opts, command, version) {
54
+ if (opts.mcp) {
55
+ startMcpServer(version);
56
+ return new Promise(() => { }); // Escuchar indefinidamente sobre stdio
57
+ }
52
58
  const fromCli = (key) => command.getOptionValueSource(key) === 'cli';
53
59
  const format = opts.json ? 'json' : opts.format;
54
60
  const quiet = format !== 'table'; // en json/markdown, stderr solo para avisos importantes
@@ -116,6 +122,30 @@ async function run(opts, command, version) {
116
122
  const failing = failUnder === undefined
117
123
  ? []
118
124
  : sorted.filter((r) => r.status === 'evaluated' && r.result && r.result.score < failUnder).map((r) => r.name);
125
+ // --- Asesor de Ciberseguridad IA ---
126
+ let aiResult = null;
127
+ if (opts.ai) {
128
+ const hasRisks = sorted.some((r) => r.status === 'evaluated' && r.result && r.result.score < 70);
129
+ const aiConfig = detectAiConfig({ provider: opts.aiProvider, model: opts.aiModel });
130
+ if (!aiConfig) {
131
+ log(chalk.yellow('\n⚠ Modo --ai activado pero no se detectó ninguna clave de API.\n' +
132
+ ' Exporta GEMINI_API_KEY, ANTHROPIC_API_KEY u OPENAI_API_KEY en tu entorno.'));
133
+ }
134
+ else if (!hasRisks) {
135
+ if (!quiet)
136
+ log(chalk.green('\n🤖 IA: Todas las dependencias están saludables (score ≥ 70). No se requieren reemplazos.'));
137
+ }
138
+ else {
139
+ if (!quiet)
140
+ log(chalk.cyan(`\n🤖 Consultando a ${aiConfig.provider} (${aiConfig.model}) para análisis de mitigación y reemplazos...`));
141
+ try {
142
+ aiResult = await analyzeWithAi(sorted, summary, { provider: opts.aiProvider, model: opts.aiModel });
143
+ }
144
+ catch (err) {
145
+ log(chalk.red(`\n✖ Error consultando a la IA: ${err.message}`));
146
+ }
147
+ }
148
+ }
119
149
  // --- Salida ---
120
150
  let rendered;
121
151
  if (format === 'json') {
@@ -125,11 +155,12 @@ async function run(opts, command, version) {
125
155
  generatedAt: now.toISOString(),
126
156
  manifest: manifest.manifestPath,
127
157
  config: config.source,
128
- options: { dev, transitive, depth: depth ?? null, failUnder: failUnder ?? null, authenticated: Boolean(token) },
158
+ options: { dev, transitive, depth: depth ?? null, failUnder: failUnder ?? null, authenticated: Boolean(token), ai: opts.ai },
129
159
  thresholds: config.thresholds,
130
160
  summary,
131
161
  ignored,
132
162
  failUnder: failUnder === undefined ? null : { threshold: failUnder, failing },
163
+ aiAnalysis: aiResult,
133
164
  packages: sorted,
134
165
  }, null, 2);
135
166
  }
@@ -142,6 +173,9 @@ async function run(opts, command, version) {
142
173
  failing,
143
174
  ignored,
144
175
  });
176
+ if (aiResult) {
177
+ rendered += `\n\n### 🤖 Recomendaciones de Ciberseguridad (${aiResult.provider} / ${aiResult.model})\n\n${aiResult.analysis}\n`;
178
+ }
145
179
  }
146
180
  else if (format === 'sarif') {
147
181
  rendered = renderSarif(sorted, {
@@ -152,12 +186,17 @@ async function run(opts, command, version) {
152
186
  }
153
187
  else {
154
188
  const title = manifest.projectName ? ` · ${manifest.projectName}` : '';
155
- rendered = [
189
+ const parts = [
156
190
  chalk.bold(`\n👻 GhostDeps v${version}${title}`),
157
191
  renderTable(sorted, now),
158
192
  renderSummary(summary, config.thresholds),
159
193
  ...(opts.explain ? [renderExplain(sorted)] : []),
160
- ].join('\n');
194
+ ];
195
+ if (aiResult) {
196
+ parts.push(chalk.bold.cyan(`\n🤖 Recomendaciones de Ciberseguridad (${aiResult.provider} / ${aiResult.model}):`));
197
+ parts.push(aiResult.analysis);
198
+ }
199
+ rendered = parts.join('\n');
161
200
  }
162
201
  if (opts.output) {
163
202
  const file = path.resolve(opts.output);
@@ -205,17 +244,26 @@ async function main() {
205
244
  .option('--timeout <ms>', 'timeout por request en milisegundos', positiveInt('--timeout'), 15_000)
206
245
  .option('--max-wait <seconds>', 'espera máxima ante rate limit antes de abortar', positiveInt('--max-wait'), 60)
207
246
  .option('--explain', 'mostrar el desglose de penalizaciones de cada paquete', false)
247
+ .option('--ai', 'analizar dependencias con IA para sugerir reemplazos y plan de mitigación', false)
248
+ .addOption(new Option('--ai-provider <provider>', 'proveedor de IA a utilizar').choices(['gemini', 'anthropic', 'openai']))
249
+ .option('--ai-model <model>', 'modelo específico de IA a consultar')
250
+ .option('--mcp', 'iniciar servidor MCP (Model Context Protocol) sobre stdio para agentes de IA', false)
208
251
  .addHelpText('after', [
209
252
  '',
210
253
  'Ejemplos:',
211
254
  ' ghostdeps --dev --explain',
212
255
  ' ghostdeps --transitive --depth 3 --ignore "@types/*"',
256
+ ' ghostdeps --ai',
257
+ ' ghostdeps --mcp',
213
258
  ' ghostdeps --format markdown -o ghostdeps.md',
214
259
  ' ghostdeps --fail-under 40',
215
260
  '',
216
261
  'Variables de entorno:',
217
- ' GITHUB_TOKEN / GH_TOKEN token de GitHub (recomendado; 5000 req/h)',
218
- ' GHOSTDEPS_CACHE_DIR directorio de caché personalizado',
262
+ ' GITHUB_TOKEN / GH_TOKEN token de GitHub (recomendado; 5000 req/h)',
263
+ ' GEMINI_API_KEY clave para modo --ai con Google Gemini',
264
+ ' ANTHROPIC_API_KEY clave para modo --ai con Anthropic Claude',
265
+ ' OPENAI_API_KEY clave para modo --ai con OpenAI ChatGPT',
266
+ ' GHOSTDEPS_CACHE_DIR directorio de caché personalizado',
219
267
  '',
220
268
  'Códigos de salida: 0 OK · 1 --fail-under incumplido · 2 error fatal',
221
269
  ].join('\n'))
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Servidor MCP (Model Context Protocol) para GhostDeps.
3
+ * Permite que agentes de IA como Claude Desktop, Cursor, Gemini CLI o ChatGPT
4
+ * llamen a GhostDeps como una herramienta (tool) a través de stdio (JSON-RPC 2.0).
5
+ */
6
+ import readline from 'node:readline';
7
+ import path from 'node:path';
8
+ import { analyzeAll, sortReports, summarize } from '../analyzer.js';
9
+ import { DiskCache, defaultCacheDir } from '../clients/cache.js';
10
+ import { GitHubClient } from '../clients/github.js';
11
+ import { RateLimitGate } from '../clients/http.js';
12
+ import { NpmClient } from '../clients/npm.js';
13
+ import { createIgnoreMatcher, loadConfig } from '../config.js';
14
+ import { readLockfile, resolveTransitive } from '../parser/lockfile.js';
15
+ import { readManifest } from '../parser/manifest.js';
16
+ import { renderMarkdown } from '../render/markdown.js';
17
+ export function createAuditToolDefinition() {
18
+ return {
19
+ name: 'ghostdeps_audit',
20
+ description: 'Audita la salud social, de mantenimiento y ciberseguridad de las dependencias de un proyecto Node.js / JavaScript. ' +
21
+ 'Detecta paquetes abandonados, bus factor crítico (0 o 1 mantenedor), repositorios archivados y posibles señales de secuestro (hijacking).',
22
+ inputSchema: {
23
+ type: 'object',
24
+ properties: {
25
+ path: {
26
+ type: 'string',
27
+ description: 'Ruta al directorio que contiene el package.json (por defecto el directorio actual).',
28
+ },
29
+ dev: {
30
+ type: 'boolean',
31
+ description: 'Incluir también devDependencies en el análisis.',
32
+ },
33
+ transitive: {
34
+ type: 'boolean',
35
+ description: 'Incluir dependencias transitivas leyendo package-lock.json o yarn.lock.',
36
+ },
37
+ depth: {
38
+ type: 'integer',
39
+ description: 'Profundidad máxima para dependencias transitivas (1 = solo directas).',
40
+ },
41
+ failUnder: {
42
+ type: 'number',
43
+ description: 'Umbral mínimo de Health Score (0 a 100).',
44
+ },
45
+ ignore: {
46
+ type: 'array',
47
+ items: { type: 'string' },
48
+ description: 'Lista de nombres o patrones comodín a ignorar (ej: ["@types/*"]).',
49
+ },
50
+ },
51
+ },
52
+ };
53
+ }
54
+ export async function executeMcpAudit(args = {}, version) {
55
+ const targetDir = typeof args.path === 'string' && args.path ? path.resolve(args.path) : process.cwd();
56
+ const includeDev = Boolean(args.dev);
57
+ const includeTransitive = Boolean(args.transitive);
58
+ const depth = typeof args.depth === 'number' ? args.depth : undefined;
59
+ const failUnder = typeof args.failUnder === 'number' ? args.failUnder : undefined;
60
+ const ignoreList = Array.isArray(args.ignore) ? args.ignore.filter((i) => typeof i === 'string') : [];
61
+ const config = await loadConfig(targetDir);
62
+ const isIgnored = createIgnoreMatcher([...config.ignore, ...ignoreList]);
63
+ const manifest = await readManifest(targetDir, { includeDev: includeDev || (config.dev ?? false) });
64
+ let all = manifest.dependencies;
65
+ if (includeTransitive || config.transitive) {
66
+ try {
67
+ const { lock } = await readLockfile(targetDir);
68
+ const trans = resolveTransitive(lock, manifest.dependencies, {
69
+ maxDepth: depth ?? config.depth ?? Number.POSITIVE_INFINITY,
70
+ });
71
+ all = [...manifest.dependencies, ...trans];
72
+ }
73
+ catch (err) {
74
+ process.stderr.write(`[GhostDeps MCP] Advertencia al leer lockfile: ${err.message}\n`);
75
+ }
76
+ }
77
+ const ignored = all.filter((d) => isIgnored(d.name) || isIgnored(d.registryName)).map((d) => d.name);
78
+ const toAnalyze = all.filter((d) => !ignored.includes(d.name));
79
+ const token = process.env.GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || undefined;
80
+ const userAgent = `ghostdeps/${version} (+https://github.com/ghostdeps/ghostdeps)`;
81
+ const cache = new DiskCache(defaultCacheDir(), 24 * 3_600_000, true);
82
+ const gate = new RateLimitGate();
83
+ const now = new Date();
84
+ const npm = new NpmClient({ cache, timeoutMs: 15_000, retries: 3, userAgent });
85
+ const github = new GitHubClient({
86
+ cache,
87
+ token,
88
+ timeoutMs: 15_000,
89
+ retries: 3,
90
+ userAgent,
91
+ gate,
92
+ maxRateLimitWaitMs: 30_000,
93
+ now: () => now,
94
+ });
95
+ const reports = await analyzeAll(toAnalyze, { npm, github, now, weights: config.weights, thresholds: config.thresholds }, config.concurrency ?? 4);
96
+ const sorted = sortReports(reports);
97
+ const summary = summarize(sorted);
98
+ const failing = failUnder === undefined
99
+ ? []
100
+ : sorted.filter((r) => r.status === 'evaluated' && r.result && r.result.score < failUnder).map((r) => r.name);
101
+ return renderMarkdown(sorted, summary, now, {
102
+ version,
103
+ projectName: manifest.projectName,
104
+ thresholds: config.thresholds,
105
+ failUnder,
106
+ failing,
107
+ ignored,
108
+ });
109
+ }
110
+ export function startMcpServer(version) {
111
+ const rl = readline.createInterface({
112
+ input: process.stdin,
113
+ output: process.stdout,
114
+ terminal: false,
115
+ });
116
+ const sendResponse = (id, result) => {
117
+ if (id === undefined)
118
+ return;
119
+ const msg = JSON.stringify({ jsonrpc: '2.0', id, result });
120
+ process.stdout.write(`${msg}\n`);
121
+ };
122
+ const sendError = (id, code, message) => {
123
+ if (id === undefined)
124
+ return;
125
+ const msg = JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
126
+ process.stdout.write(`${msg}\n`);
127
+ };
128
+ process.stderr.write(`[GhostDeps MCP Server] Iniciado sobre stdio (v${version})\n`);
129
+ rl.on('line', async (line) => {
130
+ const trimmed = line.trim();
131
+ if (!trimmed)
132
+ return;
133
+ let req;
134
+ try {
135
+ req = JSON.parse(trimmed);
136
+ }
137
+ catch {
138
+ sendError(undefined, -32700, 'Parse error: invalid JSON');
139
+ return;
140
+ }
141
+ const { id, method, params } = req;
142
+ try {
143
+ if (method === 'initialize') {
144
+ sendResponse(id, {
145
+ protocolVersion: '2024-11-05',
146
+ capabilities: { tools: {} },
147
+ serverInfo: {
148
+ name: '@efraindrummer/ghostdeps',
149
+ version,
150
+ },
151
+ });
152
+ return;
153
+ }
154
+ if (method === 'notifications/initialized') {
155
+ // Notificación del cliente, no requiere respuesta
156
+ return;
157
+ }
158
+ if (method === 'ping') {
159
+ sendResponse(id, {});
160
+ return;
161
+ }
162
+ if (method === 'tools/list') {
163
+ sendResponse(id, {
164
+ tools: [createAuditToolDefinition()],
165
+ });
166
+ return;
167
+ }
168
+ if (method === 'tools/call') {
169
+ const toolName = params?.name;
170
+ if (toolName !== 'ghostdeps_audit') {
171
+ sendError(id, -32601, `Herramienta desconocida: ${toolName}`);
172
+ return;
173
+ }
174
+ const args = params?.arguments ?? {};
175
+ const markdown = await executeMcpAudit(args, version);
176
+ sendResponse(id, {
177
+ content: [
178
+ {
179
+ type: 'text',
180
+ text: markdown,
181
+ },
182
+ ],
183
+ isError: false,
184
+ });
185
+ return;
186
+ }
187
+ // Método no implementado
188
+ sendError(id, -32601, `Método no soportado: ${method}`);
189
+ }
190
+ catch (err) {
191
+ sendError(id, -32603, `Error interno ejecutando ${method}: ${err.message}`);
192
+ }
193
+ });
194
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@efraindrummer/ghostdeps",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Detecta dependencias fantasma (abandonadas, bus factor bajo o con señales de secuestro) evaluando la salud social y de mantenimiento del repositorio origen.",
5
5
  "keywords": [
6
6
  "supply-chain",