@craswitch/mcp-server 0.0.0-stage → 2.0.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/dist/server.js ADDED
@@ -0,0 +1,1075 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+ import { ENISA_SRP_PORTAL_URL, LEGAL_DISCLAIMER, SCAN_LIMITS } from './core/types.js';
17
+ import {
18
+ deriveRepoStatusLevel,
19
+ detectLockfileKind as coreDetectLockfileKind,
20
+ generateCycloneDxSbom as coreGenerateCycloneDxSbom,
21
+ generateEnisaWorksheetStandalone,
22
+ matchExploits as coreMatchExploits,
23
+ parseCraVexConfig,
24
+ parseLockfile as coreParseLockfile,
25
+ parseSbomPayload,
26
+ resolveAlertTriageState,
27
+ verifyOpenVex as coreVerifyOpenVex,
28
+ } from './core/index.js';
29
+ import { verifyEd25519VexDocument } from './crypto.js';
30
+
31
+ import {
32
+ checkVendorCraStatus,
33
+ fetchVexDocument,
34
+ scanLockfileRemote,
35
+ validateRepoSegment,
36
+ } from './http-client.js';
37
+ import { BUNDLED_KEV_FEED } from './kev-baseline.js';
38
+
39
+ export { verifyEd25519VexDocument } from './crypto.js';
40
+
41
+ export const MCP_PROTOCOL_VERSION = '2024-11-05' ;
42
+
43
+ export const MCP_SERVER_INFO = {
44
+ name: '@craswitch/mcp-server',
45
+ version: '2.0.0',
46
+ } ;
47
+
48
+ const VALID_VEX_JUSTIFICATIONS = new Set ([
49
+ 'component_not_present',
50
+ 'vulnerable_code_not_present',
51
+ 'vulnerable_code_not_in_execute_path',
52
+ 'vulnerable_code_cannot_be_controlled_by_adversary',
53
+ 'inline_mitigations_already_exist',
54
+ ]);
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+ export const MCP_TOOLS = [
120
+ {
121
+ name: 'craswitch_scan_lockfile',
122
+ description:
123
+ 'Scan a dependency lockfile or SBOM via POST /api/v1/scan (when baseUrl is provided) or local @cra-switch/core fallback. Returns CycloneDX PURL count, matched KEV/EUVD advisories, and 4-state triage status (triage_required on raw matches — never starts 24h statutory clock automatically — or clean).',
124
+ inputSchema: {
125
+ type: 'object',
126
+ properties: {
127
+ kind: {
128
+ type: 'string',
129
+ description:
130
+ 'Lockfile/SBOM kind or filename (e.g. "package-lock.json", "pnpm-lock.yaml", "Cargo.lock", "go.sum", "requirements.txt", "poetry.lock", "pom.xml", "cyclonedx.json", "spdx.json").',
131
+ },
132
+ content: {
133
+ type: 'string',
134
+ description: 'Raw UTF-8 text content of the lockfile or SBOM.',
135
+ },
136
+ repo: {
137
+ type: 'string',
138
+ description: 'Optional repository slug (e.g. "acme-eu/payments-sdk").',
139
+ },
140
+ baseUrl: {
141
+ type: 'string',
142
+ description: 'Optional CRA-Switch API base URL for remote POST /api/v1/scan.',
143
+ },
144
+ },
145
+ required: ['kind', 'content'],
146
+ additionalProperties: false,
147
+ },
148
+ },
149
+ {
150
+ name: 'craswitch_init_vex',
151
+ description:
152
+ 'Scaffold a valid .cra-vex.json v2 configuration file (with empty suppressions and triageEvents arrays) for EU CRA Article 14 compliance.',
153
+ inputSchema: {
154
+ type: 'object',
155
+ properties: {
156
+ repo: {
157
+ type: 'string',
158
+ description: 'Repository identifier (e.g. "acme-eu/payments-sdk").',
159
+ },
160
+ securityEmail: {
161
+ type: 'string',
162
+ description: 'Security contact email for internal triage alerts (e.g. "security@example.eu").',
163
+ },
164
+ coordinatorCsirt: {
165
+ type: 'string',
166
+ description: 'Optional coordinator CSIRT (e.g. "BSI (DE)", "ANSSI (FR)").',
167
+ },
168
+ euMemberStates: {
169
+ type: 'array',
170
+ items: { type: 'string' },
171
+ description: 'Optional list of ISO-3166 EU Member State codes where the product is distributed (e.g. ["DE", "FR", "NL"]).',
172
+ },
173
+ },
174
+ required: ['repo', 'securityEmail'],
175
+ additionalProperties: false,
176
+ },
177
+ },
178
+ {
179
+ name: 'craswitch_add_suppression',
180
+ description:
181
+ 'Append a spec-compliant OpenVEX not_affected suppression AND an auditable triageEvents timestamp entry to .cra-vex.json v2.',
182
+ inputSchema: {
183
+ type: 'object',
184
+ properties: {
185
+ cveId: {
186
+ type: 'string',
187
+ description: 'Vulnerability identifier (e.g. "CVE-2021-23337" or "EUVD-2025-55182").',
188
+ },
189
+ purl: {
190
+ type: 'string',
191
+ description: 'Affected component PURL (e.g. "pkg:npm/lodash@4.17.20").',
192
+ },
193
+ justification: {
194
+ type: 'string',
195
+ enum: [
196
+ 'component_not_present',
197
+ 'vulnerable_code_not_present',
198
+ 'vulnerable_code_not_in_execute_path',
199
+ 'vulnerable_code_cannot_be_controlled_by_adversary',
200
+ 'inline_mitigations_already_exist',
201
+ ],
202
+ description: 'Standard OpenVEX v0.2.0 not_affected justification label.',
203
+ },
204
+ impactStatement: {
205
+ type: 'string',
206
+ description: 'Human-readable engineering rationale explaining why the product is not affected.',
207
+ },
208
+ existingVexJson: {
209
+ type: 'string',
210
+ description: 'Optional existing .cra-vex.json file text to update in place.',
211
+ },
212
+ triagedBy: {
213
+ type: 'string',
214
+ description: 'Optional identifier of the engineer/security reviewer performing triage.',
215
+ },
216
+ detectedAt: {
217
+ type: 'string',
218
+ description: 'Optional ISO-8601 timestamp when the vulnerability was first detected.',
219
+ },
220
+ expiresAt: {
221
+ type: 'string',
222
+ description: 'Optional ISO-8601 expiry timestamp for the suppression.',
223
+ },
224
+ },
225
+ required: ['cveId', 'purl', 'justification', 'impactStatement'],
226
+ additionalProperties: false,
227
+ },
228
+ },
229
+ {
230
+ name: 'craswitch_draft_enisa_srp',
231
+ description:
232
+ 'Generate a 1:1 ENISA SRP manual web-form copy-paste worksheet AND parallel EU CRA Article 14(8) customer notification advisory draft. Never auto-submits to ENISA.',
233
+ inputSchema: {
234
+ type: 'object',
235
+ properties: {
236
+ cveId: {
237
+ type: 'string',
238
+ description: 'Confirmed vulnerability identifier (e.g. "CVE-2025-55182").',
239
+ },
240
+ confirmedAt: {
241
+ type: 'string',
242
+ description: 'ISO-8601 timestamp when vendor explicitly confirmed active exploitation (starts 24h/72h/14d statutory clock).',
243
+ },
244
+ memberStates: {
245
+ type: 'array',
246
+ items: { type: 'string' },
247
+ description: 'EU Member States where the affected product is distributed (e.g. ["DE", "FR"]).',
248
+ },
249
+ productName: {
250
+ type: 'string',
251
+ description: 'Optional product/repository identifier (e.g. "acme-eu/legacy-gateway").',
252
+ },
253
+ releaseVersion: {
254
+ type: 'string',
255
+ description: 'Optional affected release tag/version (e.g. "v1.9.3").',
256
+ },
257
+ coordinatorCsirt: {
258
+ type: 'string',
259
+ description: 'Optional designated Coordinator CSIRT (e.g. "BSI (DE)").',
260
+ },
261
+ affectedPurls: {
262
+ type: 'array',
263
+ items: { type: 'string' },
264
+ description: 'Optional list of affected production PURLs.',
265
+ },
266
+ detectedAt: {
267
+ type: 'string',
268
+ description: 'Optional ISO-8601 timestamp when dependency match was initially detected.',
269
+ },
270
+ mitigationStatus: {
271
+ type: 'string',
272
+ description: 'Optional current mitigation/patch status description.',
273
+ },
274
+ stage: {
275
+ type: 'string',
276
+ enum: ['early_warning_24h', 'detailed_notification_72h', 'final_report_14d'],
277
+ description: 'Optional Article 14 notification stage (defaults to early_warning_24h).',
278
+ },
279
+ },
280
+ required: ['cveId', 'confirmedAt', 'memberStates'],
281
+ additionalProperties: false,
282
+ },
283
+ },
284
+ {
285
+ name: 'check_vendor_cra_status',
286
+ description:
287
+ 'Query a vendor repository EU CRA Article 14 attestation via HTTP x402 (/api/v1/x402/attest/:org/:repo). Returns structured payment-required challenge details on HTTP 402 or the signed CRA posture on HTTP 200.',
288
+ inputSchema: {
289
+ type: 'object',
290
+ properties: {
291
+ org: {
292
+ type: 'string',
293
+ description: 'GitHub/GitLab organization or owner slug (e.g. "acme-eu").',
294
+ },
295
+ repo: {
296
+ type: 'string',
297
+ description: 'Repository name (e.g. "payments-sdk").',
298
+ },
299
+ baseUrl: {
300
+ type: 'string',
301
+ description: 'Optional CRA-Switch API base URL (defaults to CRA_SWITCH_URL).',
302
+ },
303
+ paymentProof: {
304
+ type: 'string',
305
+ description: 'Optional x402 payment proof sent in X-Payment-Proof header.',
306
+ },
307
+ },
308
+ required: ['org', 'repo'],
309
+ additionalProperties: false,
310
+ },
311
+ },
312
+ {
313
+ name: 'verify_vex_signature',
314
+ description:
315
+ 'Fetch /.well-known/vex.json?repo=<org>/<repo> and cryptographically verify its Ed25519 signature via WebCrypto.',
316
+ inputSchema: {
317
+ type: 'object',
318
+ properties: {
319
+ org: {
320
+ type: 'string',
321
+ description: 'Repository owner or organization slug.',
322
+ },
323
+ repo: {
324
+ type: 'string',
325
+ description: 'Repository name.',
326
+ },
327
+ baseUrl: {
328
+ type: 'string',
329
+ description: 'Optional CRA-Switch API base URL.',
330
+ },
331
+ publicKey: {
332
+ type: 'string',
333
+ description:
334
+ 'Optional Ed25519 public key (base64 SPKI, ed25519:<base64url>, PEM, or JWK JSON). Auto-discovered from document or response headers if omitted.',
335
+ },
336
+ },
337
+ required: ['org', 'repo'],
338
+ additionalProperties: false,
339
+ },
340
+ },
341
+ {
342
+ name: 'scan_lockfile_kev',
343
+ description:
344
+ 'Legacy alias: parse a dependency lockfile and check active CISA KEV / ENISA EUVD exploit status locally via @cra-switch/core (or remotely via POST /api/v1/scan when baseUrl is provided).',
345
+ inputSchema: {
346
+ type: 'object',
347
+ properties: {
348
+ filename: {
349
+ type: 'string',
350
+ description:
351
+ 'Lockfile filename or path (e.g. "package-lock.json", "Cargo.lock", "requirements.txt", "go.sum", "pom.xml", "pnpm-lock.yaml", "poetry.lock").',
352
+ },
353
+ content: {
354
+ type: 'string',
355
+ description: 'Raw text content of the lockfile.',
356
+ },
357
+ baseUrl: {
358
+ type: 'string',
359
+ description: 'Optional CRA-Switch API base URL for remote /api/v1/scan execution.',
360
+ },
361
+ },
362
+ required: ['filename', 'content'],
363
+ additionalProperties: false,
364
+ },
365
+ },
366
+ ];
367
+
368
+ const DEFAULT_CORE_ADAPTER = {
369
+ detectLockfileKind: coreDetectLockfileKind,
370
+ parseLockfile: coreParseLockfile,
371
+ generateCycloneDxSbom: coreGenerateCycloneDxSbom,
372
+ matchExploits: coreMatchExploits,
373
+ verifyOpenVex: coreVerifyOpenVex,
374
+ };
375
+
376
+ function resolveCoreAdapter(opts ) {
377
+ return opts?.coreAdapter ?? DEFAULT_CORE_ADAPTER;
378
+ }
379
+
380
+ function makeRpcError(
381
+ id ,
382
+ code ,
383
+ message ,
384
+ data ,
385
+ ) {
386
+ const err = { code, message };
387
+ if (data !== undefined) err.data = data;
388
+ return { jsonrpc: '2.0', id, error: err };
389
+ }
390
+
391
+ function makeToolResult(
392
+ payload ,
393
+ isError = false,
394
+ ) {
395
+ return {
396
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
397
+ structuredContent: payload,
398
+ ...(isError ? { isError: true } : {}),
399
+ };
400
+ }
401
+
402
+ function asObject(value ) {
403
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
404
+ return value ;
405
+ }
406
+ return null;
407
+ }
408
+
409
+ function asStringArray(value ) {
410
+ if (!Array.isArray(value)) return [];
411
+ return value
412
+ .filter((v) => typeof v === 'string' && v.trim().length > 0)
413
+ .map((v) => v.trim());
414
+ }
415
+
416
+ async function runLockfileOrSbomScan(
417
+ params
418
+
419
+
420
+
421
+
422
+
423
+ ,
424
+ opts ,
425
+ ) {
426
+ const filename = params.filename.trim();
427
+ const content = params.content;
428
+ if (!filename) {
429
+ throw new Error('Missing required lockfile "kind" / "filename".');
430
+ }
431
+ if (!content) {
432
+ throw new Error('Missing required argument "content".');
433
+ }
434
+
435
+ const byteLen = new TextEncoder().encode(content).byteLength;
436
+ if (byteLen > SCAN_LIMITS.maxLockfileBytes) {
437
+ throw new Error(
438
+ `Lockfile "${filename}" exceeds maximum allowed size (${byteLen} > ${SCAN_LIMITS.maxLockfileBytes} bytes).`,
439
+ );
440
+ }
441
+
442
+ const repoFullName = params.repo?.trim() || `local/${filename}`;
443
+ const remoteBaseUrl = params.baseUrl?.trim() || undefined;
444
+ let remoteError ;
445
+
446
+ if (remoteBaseUrl) {
447
+ try {
448
+ const remote = await scanLockfileRemote(
449
+ { filename, content, baseUrl: remoteBaseUrl },
450
+ opts.fetchImpl ?? fetch,
451
+ opts.timeoutMs,
452
+ );
453
+ if (params.legacyShape) {
454
+ return makeToolResult({
455
+ mode: 'remote',
456
+ filename,
457
+ endpoint: remote.endpoint,
458
+ httpStatus: remote.httpStatus,
459
+ scan: remote.result,
460
+ legalDisclaimer: LEGAL_DISCLAIMER,
461
+ });
462
+ }
463
+ const remoteObj = asObject(remote.result) ?? {};
464
+ const remoteMatches = Array.isArray(remoteObj.activeMatches)
465
+ ? remoteObj.activeMatches
466
+ : Array.isArray(remoteObj.matches)
467
+ ? remoteObj.matches
468
+ : [];
469
+ const triageState = remoteMatches.length > 0 ? 'triage_required' : 'clean';
470
+ return makeToolResult({
471
+ mode: 'remote',
472
+ repo: repoFullName,
473
+ kind: filename,
474
+ endpoint: remote.endpoint,
475
+ httpStatus: remote.httpStatus,
476
+ status: triageState,
477
+ triageState,
478
+ statutoryClockStarted: false,
479
+ componentCount: Number(remoteObj.componentCount ?? 0),
480
+ matchedCount: remoteMatches.length,
481
+ triageRequiredCount: remoteMatches.length,
482
+ matches: remoteMatches,
483
+ scan: remote.result,
484
+ legalDisclaimer: LEGAL_DISCLAIMER,
485
+ });
486
+ } catch (err) {
487
+ if (params.legacyShape) throw err;
488
+ remoteError = err instanceof Error ? err.message : String(err);
489
+ }
490
+ }
491
+
492
+ const core = resolveCoreAdapter(opts);
493
+ const kind = core.detectLockfileKind(filename);
494
+ if (!kind) {
495
+ throw new Error(
496
+ `Unsupported lockfile/SBOM "${filename}". Supported: package-lock.json, pnpm-lock.yaml, Cargo.lock, go.sum, requirements.txt, poetry.lock, pom.xml, cyclonedx.json, spdx.json.`,
497
+ );
498
+ }
499
+
500
+ let components ;
501
+ if (kind === 'spdx.json' || kind === 'cyclonedx.json') {
502
+ components = parseSbomPayload(content, undefined, filename).components;
503
+ } else {
504
+ components = core.parseLockfile({ path: filename, kind, content });
505
+ }
506
+
507
+ const nowIso = new Date().toISOString();
508
+ const sbom = core.generateCycloneDxSbom(repoFullName, 'unreleased', components);
509
+ const feedItems = [...(opts.feedItems ?? BUNDLED_KEV_FEED)];
510
+ const matches = core.matchExploits(components, feedItems);
511
+ const activeMatches = matches.filter((m) => !m.suppressed);
512
+
513
+ // CRITICAL GUARDRAIL: raw lockfile matches ALWAYS enter `triage_required` (never 24h statutory clock)
514
+ const triagedAlerts = activeMatches.map((match) => {
515
+ const resolved = resolveAlertTriageState(match, [], [], nowIso);
516
+ return {
517
+ vulnId: match.vulnId,
518
+ cveId: match.cveId ?? null,
519
+ euvdId: match.euvdId ?? null,
520
+ sources: match.sources,
521
+ matchedPurls: match.matchedComponents.map((c) => c.purl),
522
+ summary: match.summary,
523
+ triageState: resolved.triageState,
524
+ detectedAt: resolved.detectedAt,
525
+ triageSlaDueAt: resolved.triageSlaDueAt,
526
+ statutoryClockStarted: resolved.statutoryClockStarted,
527
+ };
528
+ });
529
+
530
+ const status = deriveRepoStatusLevel(
531
+ triagedAlerts.map((a) => ({ triageState: a.triageState, status: 'open' })),
532
+ 0,
533
+ true,
534
+ );
535
+
536
+ return makeToolResult({
537
+ mode: remoteError ? 'local_fallback' : 'local',
538
+ ...(remoteError ? { remoteFallbackReason: remoteError } : {}),
539
+ repo: repoFullName,
540
+ filename,
541
+ kind,
542
+ lockfileKind: kind,
543
+ status,
544
+ triageState: status,
545
+ statutoryClockStarted: false,
546
+ componentCount: sbom.components.length,
547
+ productionComponentCount: components.filter((c) => c.scope !== 'dev').length,
548
+ activeKevCount: activeMatches.length,
549
+ matchedCount: activeMatches.length,
550
+ triageRequiredCount: triagedAlerts.filter((a) => a.triageState === 'triage_required').length,
551
+ matches: activeMatches,
552
+ triagedAlerts,
553
+ sbomSummary: {
554
+ bomFormat: sbom.bomFormat,
555
+ specVersion: sbom.specVersion,
556
+ serialNumber: sbom.serialNumber,
557
+ },
558
+ legalDisclaimer: LEGAL_DISCLAIMER,
559
+ });
560
+ }
561
+
562
+ async function callInitVex(args ) {
563
+ const repo = typeof args.repo === 'string' ? args.repo.trim() : '';
564
+ const securityEmail = typeof args.securityEmail === 'string' ? args.securityEmail.trim() : '';
565
+ if (!repo) {
566
+ throw new Error('Missing required argument "repo".');
567
+ }
568
+ if (!securityEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(securityEmail)) {
569
+ throw new Error('Invalid "securityEmail": expected a valid email address.');
570
+ }
571
+
572
+ const coordinatorCsirt =
573
+ typeof args.coordinatorCsirt === 'string' && args.coordinatorCsirt.trim().length > 0
574
+ ? args.coordinatorCsirt.trim()
575
+ : undefined;
576
+ const euMemberStates = asStringArray(args.euMemberStates).map((s) => s.toUpperCase());
577
+
578
+ const config = {
579
+ version: '2',
580
+ securityContactEmail: securityEmail,
581
+ ...(coordinatorCsirt ? { coordinatorCsirt } : {}),
582
+ ...(euMemberStates.length > 0 ? { euMemberStatesDistributed: euMemberStates } : {}),
583
+ suppressions: [],
584
+ triageEvents: [],
585
+ };
586
+
587
+ const json = `${JSON.stringify(config, null, 2)}\n`;
588
+ // Validate with @cra-switch/core parser to guarantee schema conformance
589
+ const validated = parseCraVexConfig(json, '.cra-vex.json');
590
+
591
+ return makeToolResult({
592
+ path: '.cra-vex.json',
593
+ repo,
594
+ config: validated,
595
+ json,
596
+ legalDisclaimer: LEGAL_DISCLAIMER,
597
+ });
598
+ }
599
+
600
+ async function callAddSuppression(args ) {
601
+ const cveId = typeof args.cveId === 'string' ? args.cveId.trim().toUpperCase() : '';
602
+ const purl = typeof args.purl === 'string' ? args.purl.trim() : '';
603
+ const justification = typeof args.justification === 'string' ? args.justification.trim() : '';
604
+ const impactStatement = typeof args.impactStatement === 'string' ? args.impactStatement.trim() : '';
605
+
606
+ if (!cveId) throw new Error('Missing required argument "cveId".');
607
+ if (!purl || !purl.startsWith('pkg:')) {
608
+ throw new Error('Invalid "purl": expected a Package URL starting with "pkg:".');
609
+ }
610
+ if (!VALID_VEX_JUSTIFICATIONS.has(justification )) {
611
+ throw new Error(
612
+ `Invalid "justification": expected one of ${Array.from(VALID_VEX_JUSTIFICATIONS).join(', ')}.`,
613
+ );
614
+ }
615
+ if (!impactStatement) {
616
+ throw new Error('Missing required argument "impactStatement".');
617
+ }
618
+
619
+ let baseConfig = {
620
+ version: '2',
621
+ suppressions: [],
622
+ triageEvents: [],
623
+ };
624
+
625
+ if (typeof args.existingVexJson === 'string' && args.existingVexJson.trim().length > 0) {
626
+ const parsed = parseCraVexConfig(args.existingVexJson, '.cra-vex.json');
627
+ baseConfig = {
628
+ ...parsed,
629
+ version: '2',
630
+ suppressions: [...parsed.suppressions],
631
+ triageEvents: [...(parsed.triageEvents ?? [])],
632
+ };
633
+ }
634
+
635
+ const nowIso = new Date().toISOString();
636
+ const detectedAt =
637
+ typeof args.detectedAt === 'string' && !Number.isNaN(Date.parse(args.detectedAt))
638
+ ? new Date(Date.parse(args.detectedAt)).toISOString()
639
+ : nowIso;
640
+ const triagedBy =
641
+ typeof args.triagedBy === 'string' && args.triagedBy.trim().length > 0
642
+ ? args.triagedBy.trim()
643
+ : 'mcp-operator';
644
+ const expiresAt =
645
+ typeof args.expiresAt === 'string' && args.expiresAt.trim().length > 0
646
+ ? args.expiresAt.trim()
647
+ : undefined;
648
+
649
+ const newSuppression = {
650
+ vulnerabilityId: cveId,
651
+ purl,
652
+ status: 'not_affected',
653
+ justification: justification ,
654
+ impactStatement,
655
+ ...(expiresAt ? { expiresAt } : {}),
656
+ sourcePath: '.cra-vex.json',
657
+ };
658
+
659
+ // Replace existing suppression for the exact same (vulnerabilityId, purl) or append
660
+ const filteredSuppressions = baseConfig.suppressions.filter(
661
+ (s) =>
662
+ !(
663
+ s.vulnerabilityId.toUpperCase() === cveId &&
664
+ (s.purl ?? '').toLowerCase() === purl.toLowerCase()
665
+ ),
666
+ );
667
+ filteredSuppressions.push(newSuppression);
668
+
669
+ const newTriageEvent = {
670
+ vulnerabilityId: cveId,
671
+ purl,
672
+ detectedAt,
673
+ triagedAt: nowIso,
674
+ determination: 'not_affected',
675
+ triagedBy,
676
+ note: impactStatement,
677
+ };
678
+
679
+ const updatedConfig = {
680
+ ...baseConfig,
681
+ version: '2',
682
+ suppressions: filteredSuppressions,
683
+ triageEvents: [...(baseConfig.triageEvents ?? []), newTriageEvent],
684
+ };
685
+
686
+ const json = `${JSON.stringify(updatedConfig, null, 2)}\n`;
687
+ const validated = parseCraVexConfig(json, '.cra-vex.json');
688
+
689
+ return makeToolResult({
690
+ path: '.cra-vex.json',
691
+ config: validated,
692
+ json,
693
+ addedSuppression: newSuppression,
694
+ addedTriageEvent: newTriageEvent,
695
+ legalDisclaimer: LEGAL_DISCLAIMER,
696
+ });
697
+ }
698
+
699
+ async function callDraftEnisaSrp(args ) {
700
+ const cveId = typeof args.cveId === 'string' ? args.cveId.trim().toUpperCase() : '';
701
+ const confirmedAt = typeof args.confirmedAt === 'string' ? args.confirmedAt.trim() : '';
702
+ const memberStates = asStringArray(args.memberStates).map((s) => s.toUpperCase());
703
+
704
+ if (!cveId) throw new Error('Missing required argument "cveId".');
705
+ if (!confirmedAt || Number.isNaN(Date.parse(confirmedAt))) {
706
+ throw new Error('Invalid "confirmedAt": expected a valid ISO-8601 timestamp.');
707
+ }
708
+ if (memberStates.length === 0) {
709
+ throw new Error('Missing required argument "memberStates": provide at least one EU Member State code.');
710
+ }
711
+
712
+ const validStages = new Set ([
713
+ 'early_warning_24h',
714
+ 'detailed_notification_72h',
715
+ 'final_report_14d',
716
+ ]);
717
+ const stage =
718
+ typeof args.stage === 'string' && validStages.has(args.stage )
719
+ ? (args.stage )
720
+ : 'early_warning_24h';
721
+
722
+ const result = generateEnisaWorksheetStandalone({
723
+ cveId,
724
+ confirmedAt,
725
+ memberStates,
726
+ productName: typeof args.productName === 'string' ? args.productName : undefined,
727
+ releaseVersion: typeof args.releaseVersion === 'string' ? args.releaseVersion : undefined,
728
+ coordinatorCsirt: typeof args.coordinatorCsirt === 'string' ? args.coordinatorCsirt : undefined,
729
+ affectedPurls: asStringArray(args.affectedPurls),
730
+ detectedAt: typeof args.detectedAt === 'string' ? args.detectedAt : undefined,
731
+ mitigationStatus: typeof args.mitigationStatus === 'string' ? args.mitigationStatus : undefined,
732
+ stage,
733
+ });
734
+
735
+ return makeToolResult({
736
+ autoSubmitted: false,
737
+ stage: result.webFormWorksheet.stage ?? stage,
738
+ submissionUrl: ENISA_SRP_PORTAL_URL,
739
+ webFormWorksheet: {
740
+ ...result.webFormWorksheet,
741
+ stage: result.webFormWorksheet.stage ?? stage,
742
+ },
743
+ webFormWorksheetMarkdown: result.webFormWorksheetMarkdown,
744
+ article14_8Advisory: result.article14_8Advisory,
745
+ legalDisclaimer: result.legalDisclaimer,
746
+ });
747
+ }
748
+
749
+ async function callCheckVendorCraStatus(
750
+ args ,
751
+ opts ,
752
+ ) {
753
+ const defaultBaseUrl = opts.defaultBaseUrl ?? process.env.CRA_SWITCH_URL ?? 'https://craswitch.dev';
754
+ const result = await checkVendorCraStatus(
755
+ {
756
+ org: String(args.org ?? ''),
757
+ repo: String(args.repo ?? ''),
758
+ baseUrl: typeof args.baseUrl === 'string' ? args.baseUrl : undefined,
759
+ paymentProof: typeof args.paymentProof === 'string' ? args.paymentProof : undefined,
760
+ },
761
+ defaultBaseUrl,
762
+ opts.fetchImpl ?? fetch,
763
+ opts.timeoutMs,
764
+ );
765
+
766
+ return makeToolResult(
767
+ result ,
768
+ result.status === 'error',
769
+ );
770
+ }
771
+
772
+ async function callVerifyVexSignature(
773
+ args ,
774
+ opts ,
775
+ ) {
776
+ const defaultBaseUrl = opts.defaultBaseUrl ?? process.env.CRA_SWITCH_URL ?? 'https://craswitch.dev';
777
+ const org = validateRepoSegment(args.org, 'org');
778
+ const repo = validateRepoSegment(args.repo, 'repo');
779
+ const explicitKey = typeof args.publicKey === 'string' ? args.publicKey : undefined;
780
+
781
+ const fetched = await fetchVexDocument(
782
+ {
783
+ org,
784
+ repo,
785
+ baseUrl: typeof args.baseUrl === 'string' ? args.baseUrl : undefined,
786
+ },
787
+ defaultBaseUrl,
788
+ opts.fetchImpl ?? fetch,
789
+ opts.timeoutMs,
790
+ );
791
+
792
+ const keyCandidate = explicitKey ?? fetched.publicKeyHeader;
793
+ let verification = await verifyEd25519VexDocument(fetched.document, keyCandidate);
794
+
795
+ if (!verification.valid && verification.reason?.includes('No Ed25519 public key')) {
796
+ try {
797
+ const core = resolveCoreAdapter(opts);
798
+ if (core.verifyOpenVex) {
799
+ const coreOk = await core.verifyOpenVex(fetched.document, keyCandidate);
800
+ if (coreOk) {
801
+ verification = {
802
+ ...verification,
803
+ valid: true,
804
+ reason: undefined,
805
+ };
806
+ }
807
+ }
808
+ } catch {
809
+ // Keep standalone verification reason
810
+ }
811
+ }
812
+
813
+ return makeToolResult(
814
+ {
815
+ org,
816
+ repo,
817
+ url: fetched.url,
818
+ httpStatus: fetched.httpStatus,
819
+ valid: verification.valid,
820
+ reason: verification.reason ?? null,
821
+ algorithm: verification.algorithm ?? null,
822
+ keyId: verification.keyId ?? null,
823
+ signedAt: verification.signedAt ?? null,
824
+ statementCount: verification.statementCount,
825
+ documentId: fetched.document['@id'],
826
+ author: fetched.document.author,
827
+ statements: fetched.document.statements,
828
+ },
829
+ false,
830
+ );
831
+ }
832
+
833
+ /**
834
+ * Pure JSON-RPC 2.0 MCP request handler — exported for direct unit testing and stdio execution.
835
+ * Returns `null` for JSON-RPC notifications (e.g. `notifications/initialized`).
836
+ */
837
+ export async function handleMcpRequest(
838
+ rawReq ,
839
+ opts = {},
840
+ ) {
841
+ const reqObj = asObject(rawReq);
842
+ if (!reqObj || reqObj.jsonrpc !== '2.0' || typeof reqObj.method !== 'string') {
843
+ const id =
844
+ reqObj && (typeof reqObj.id === 'string' || typeof reqObj.id === 'number')
845
+ ? reqObj.id
846
+ : null;
847
+ return makeRpcError(id, -32600, 'Invalid Request: expected JSON-RPC 2.0 object with method.');
848
+ }
849
+
850
+ const method = reqObj.method;
851
+ const hasId = Object.prototype.hasOwnProperty.call(reqObj, 'id') && reqObj.id !== undefined;
852
+ const id =
853
+ typeof reqObj.id === 'string' || typeof reqObj.id === 'number' ? reqObj.id : null;
854
+
855
+ if (method === 'notifications/initialized' || (!hasId && method.startsWith('notifications/'))) {
856
+ return null;
857
+ }
858
+
859
+ if (method === 'initialize') {
860
+ return {
861
+ jsonrpc: '2.0',
862
+ id,
863
+ result: {
864
+ protocolVersion: MCP_PROTOCOL_VERSION,
865
+ capabilities: {
866
+ tools: {},
867
+ },
868
+ serverInfo: MCP_SERVER_INFO,
869
+ },
870
+ };
871
+ }
872
+
873
+ if (method === 'ping') {
874
+ return {
875
+ jsonrpc: '2.0',
876
+ id,
877
+ result: {},
878
+ };
879
+ }
880
+
881
+ if (method === 'tools/list') {
882
+ return {
883
+ jsonrpc: '2.0',
884
+ id,
885
+ result: {
886
+ tools: MCP_TOOLS,
887
+ },
888
+ };
889
+ }
890
+
891
+ if (method === 'tools/call') {
892
+ const params = asObject(reqObj.params);
893
+ if (!params || typeof params.name !== 'string') {
894
+ return makeRpcError(id, -32602, 'Invalid params: "name" string is required.');
895
+ }
896
+
897
+ const toolName = params.name;
898
+ const toolArgs = asObject(params.arguments) ?? {};
899
+
900
+ const knownTool = MCP_TOOLS.some((t) => t.name === toolName);
901
+ if (!knownTool) {
902
+ return makeRpcError(id, -32602, `Unknown tool: "${toolName}".`);
903
+ }
904
+
905
+ try {
906
+ let toolResult ;
907
+ if (toolName === 'craswitch_scan_lockfile') {
908
+ toolResult = await runLockfileOrSbomScan(
909
+ {
910
+ filename: String(toolArgs.kind ?? toolArgs.filename ?? ''),
911
+ content: String(toolArgs.content ?? ''),
912
+ repo: typeof toolArgs.repo === 'string' ? toolArgs.repo : undefined,
913
+ baseUrl: typeof toolArgs.baseUrl === 'string' ? toolArgs.baseUrl : undefined,
914
+ legacyShape: false,
915
+ },
916
+ opts,
917
+ );
918
+ } else if (toolName === 'craswitch_init_vex') {
919
+ toolResult = await callInitVex(toolArgs);
920
+ } else if (toolName === 'craswitch_add_suppression') {
921
+ toolResult = await callAddSuppression(toolArgs);
922
+ } else if (toolName === 'craswitch_draft_enisa_srp') {
923
+ toolResult = await callDraftEnisaSrp(toolArgs);
924
+ } else if (toolName === 'check_vendor_cra_status') {
925
+ toolResult = await callCheckVendorCraStatus(toolArgs, opts);
926
+ } else if (toolName === 'verify_vex_signature') {
927
+ toolResult = await callVerifyVexSignature(toolArgs, opts);
928
+ } else {
929
+ toolResult = await runLockfileOrSbomScan(
930
+ {
931
+ filename: String(toolArgs.filename ?? ''),
932
+ content: String(toolArgs.content ?? ''),
933
+ baseUrl: typeof toolArgs.baseUrl === 'string' ? toolArgs.baseUrl : undefined,
934
+ legacyShape: true,
935
+ },
936
+ opts,
937
+ );
938
+ }
939
+
940
+ return {
941
+ jsonrpc: '2.0',
942
+ id,
943
+ result: toolResult,
944
+ };
945
+ } catch (err) {
946
+ const message = err instanceof Error ? err.message : String(err);
947
+ return {
948
+ jsonrpc: '2.0',
949
+ id,
950
+ result: makeToolResult({ error: message }, true),
951
+ };
952
+ }
953
+ }
954
+
955
+ if (!hasId) {
956
+ return null;
957
+ }
958
+
959
+ return makeRpcError(id, -32601, `Method not found: "${method}".`);
960
+ }
961
+
962
+ const HEADER_LINE_RE = /^[A-Za-z][A-Za-z0-9-]*:\s*/;
963
+
964
+ /**
965
+ * Starts the JSON-RPC 2.0 MCP server over stdio (newline-delimited JSON, with
966
+ * multi-header Content-Length LSP/MCP framing compatibility).
967
+ */
968
+ export function startStdioServer(opts = {}) {
969
+ const input = opts.input ?? process.stdin;
970
+ const output = opts.output ?? process.stdout;
971
+ const stderr = opts.stderr ?? process.stderr;
972
+
973
+ let buffer = '';
974
+ let chain = Promise.resolve();
975
+
976
+ const safeWriteError = (err ) => {
977
+ try {
978
+ const msg = err instanceof Error ? err.message : String(err);
979
+ stderr.write(`[cra-switch-mcp] stdio transport error: ${msg}\n`);
980
+ } catch {
981
+ // Never propagate secondary stderr write failures
982
+ }
983
+ };
984
+
985
+ const processPayload = (rawJson ) => {
986
+ chain = chain
987
+ .then(async () => {
988
+ try {
989
+ let parsed ;
990
+ try {
991
+ parsed = JSON.parse(rawJson);
992
+ } catch (err) {
993
+ const parseErr = makeRpcError(
994
+ null,
995
+ -32700,
996
+ `Parse error: ${err instanceof Error ? err.message : String(err)}`,
997
+ );
998
+ output.write(`${JSON.stringify(parseErr)}\n`);
999
+ return;
1000
+ }
1001
+
1002
+ const response = await handleMcpRequest(parsed, opts);
1003
+ if (response !== null) {
1004
+ output.write(`${JSON.stringify(response)}\n`);
1005
+ }
1006
+ } catch (err) {
1007
+ safeWriteError(err);
1008
+ }
1009
+ })
1010
+ .catch((err) => {
1011
+ safeWriteError(err);
1012
+ });
1013
+ };
1014
+
1015
+ const drainBuffer = () => {
1016
+ while (buffer.length > 0) {
1017
+ const leadingWs = buffer.match(/^(?:\r?\n)+/);
1018
+ if (leadingWs) {
1019
+ buffer = buffer.slice(leadingWs[0].length);
1020
+ if (buffer.length === 0) return;
1021
+ }
1022
+
1023
+ if (HEADER_LINE_RE.test(buffer)) {
1024
+ const headerEnd = buffer.indexOf('\r\n\r\n');
1025
+ if (headerEnd === -1) return;
1026
+ const headerBlock = buffer.slice(0, headerEnd);
1027
+ const match = headerBlock.match(/(?:^|\r\n)content-length:\s*(\d+)/i);
1028
+ if (!match) {
1029
+ buffer = buffer.slice(headerEnd + 4);
1030
+ continue;
1031
+ }
1032
+ const expectedBytes = Number.parseInt(match[1] , 10);
1033
+ const remaining = buffer.slice(headerEnd + 4);
1034
+ const remainingBytes = Buffer.byteLength(remaining, 'utf8');
1035
+ if (remainingBytes < expectedBytes) return;
1036
+
1037
+ const payloadBuf = Buffer.from(remaining, 'utf8');
1038
+ const messageText = payloadBuf.subarray(0, expectedBytes).toString('utf8');
1039
+ buffer = payloadBuf.subarray(expectedBytes).toString('utf8');
1040
+ processPayload(messageText);
1041
+ continue;
1042
+ }
1043
+
1044
+ const nlIdx = buffer.indexOf('\n');
1045
+ if (nlIdx === -1) return;
1046
+ const line = buffer.slice(0, nlIdx).trim();
1047
+ buffer = buffer.slice(nlIdx + 1);
1048
+ if (!line) continue;
1049
+ processPayload(line);
1050
+ }
1051
+ };
1052
+
1053
+ const onData = (chunk ) => {
1054
+ buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
1055
+ drainBuffer();
1056
+ };
1057
+
1058
+ const onEnd = () => {
1059
+ const trailing = buffer.trim();
1060
+ buffer = '';
1061
+ if (trailing && !HEADER_LINE_RE.test(trailing)) {
1062
+ processPayload(trailing);
1063
+ }
1064
+ };
1065
+
1066
+ input.on('data', onData);
1067
+ input.on('end', onEnd);
1068
+
1069
+ return {
1070
+ close: () => {
1071
+ input.off('data', onData);
1072
+ input.off('end', onEnd);
1073
+ },
1074
+ };
1075
+ }