coldpin 0.0.0-stage → 1.5.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.
Files changed (102) hide show
  1. package/ACCESSIBILITY.md +17 -0
  2. package/CHANGELOG.md +89 -0
  3. package/CONTRIBUTING.md +36 -0
  4. package/LICENSE +98 -0
  5. package/MAINTENANCE.md +33 -0
  6. package/README.md +142 -2
  7. package/SECURITY.md +34 -0
  8. package/TESTING.md +26 -0
  9. package/agents/coldpin-auditor.md +47 -0
  10. package/agents/coldpin-compliance.md +38 -0
  11. package/agents/coldpin-confusion-auditor.md +38 -0
  12. package/agents/coldpin-discoverer.md +37 -0
  13. package/agents/coldpin-forensics.md +38 -0
  14. package/agents/coldpin-inspector.md +37 -0
  15. package/agents/coldpin-manifest-auditor.md +38 -0
  16. package/assets/icon.svg +7 -0
  17. package/catalog/mcp-schema-pin.json +14 -0
  18. package/catalog/plugin.oms.sig +19 -0
  19. package/catalog/sigma/npx-suspicious-child-process-linux.yml +54 -0
  20. package/catalog/sigma/npx-suspicious-child-process.yml +49 -0
  21. package/catalog/triage-rules.json +104 -0
  22. package/docs/assets/readme-header.svg +21 -0
  23. package/docs/designs/SITEMAP.md +14 -0
  24. package/docs/designs/coldpin.md +68 -0
  25. package/docs/fact-ledger.md +35 -0
  26. package/docs/faq.md +31 -0
  27. package/docs/getting_started.md +62 -0
  28. package/docs/harnesses.md +45 -0
  29. package/docs/privacy.md +27 -0
  30. package/docs/verification/skill-inspector-self-audit.md +33 -0
  31. package/examples/.coldpin.policy.example.json +27 -0
  32. package/examples/.npmrc.example +8 -0
  33. package/examples/mcp_config.private-registry.example.json +42 -0
  34. package/hooks.json +47 -0
  35. package/lib/analysis/parity-and-bisect.mjs +1371 -0
  36. package/lib/analysis/static-triage.mjs +4572 -0
  37. package/lib/cache/sqlite-store.mjs +251 -0
  38. package/lib/cli.mjs +427 -0
  39. package/lib/compliance/audit-log.mjs +357 -0
  40. package/lib/config/policy.mjs +780 -0
  41. package/lib/core/path-confinement.mjs +289 -0
  42. package/lib/core/workflows.mjs +1205 -0
  43. package/lib/discovery/slopsquat-guard.mjs +289 -0
  44. package/lib/hook.mjs +1038 -0
  45. package/lib/intel/registry-osv.mjs +1681 -0
  46. package/lib/mcp/report-store.mjs +175 -0
  47. package/lib/mcp/server.mjs +1387 -0
  48. package/lib/mcp/stdio-transport.mjs +289 -0
  49. package/lib/mcp/tool-catalog.mjs +273 -0
  50. package/lib/mcp/types.mjs +95 -0
  51. package/lib/mcp.mjs +19 -0
  52. package/lib/quarantine/safe-unpack.mjs +568 -0
  53. package/lib/types.mjs +383 -0
  54. package/lib/verdict/engine-and-formatters.mjs +895 -0
  55. package/mcp_config.json +21 -0
  56. package/package.json +71 -3
  57. package/plugin.json +54 -0
  58. package/rules/AGENTS.md +18 -0
  59. package/rules/coldpin-incident-checklist.md +18 -0
  60. package/rules/coldpin-manifest-guard.md +14 -0
  61. package/server.json +38 -0
  62. package/skills/coldpin/BENCHMARK.md +166 -0
  63. package/skills/coldpin/SKILL.md +110 -0
  64. package/skills/coldpin/TEST.md +13 -0
  65. package/skills/coldpin/agents/openai.yaml +6 -0
  66. package/skills/coldpin/assets/icon.svg +7 -0
  67. package/skills/coldpin/assets/runtime-contract.yaml +105 -0
  68. package/skills/coldpin/evals/evals.json +60 -0
  69. package/skills/coldpin/references/aspect-compliance-audit.md +27 -0
  70. package/skills/coldpin/references/aspect-discovery.md +26 -0
  71. package/skills/coldpin/references/aspect-forensics-rea.md +26 -0
  72. package/skills/coldpin/references/aspect-inspection.md +26 -0
  73. package/skills/coldpin/references/aspect-manifest-confusion.md +26 -0
  74. package/skills/coldpin/references/enterprise-policy-schema.md +65 -0
  75. package/skills/coldpin/references/evidence-card-spec.md +27 -0
  76. package/skills/coldpin/references/rea-integration-playbook.md +34 -0
  77. package/skills/coldpin/references/threat-taxonomy.md +35 -0
  78. package/skills/coldpin/skill-card.md +62 -0
  79. package/skills/coldpin/skill.oms.sig +19 -0
  80. package/skills/coldpin/test_scenarios.yaml +61 -0
  81. package/skills/coldpin-audit/SKILL.md +39 -0
  82. package/skills/coldpin-incident/SKILL.md +37 -0
  83. package/src/analysis/parity-and-bisect.ts +1368 -0
  84. package/src/analysis/static-triage.ts +4569 -0
  85. package/src/cache/sqlite-store.ts +248 -0
  86. package/src/cli.ts +424 -0
  87. package/src/compliance/audit-log.ts +354 -0
  88. package/src/config/policy.ts +777 -0
  89. package/src/core/path-confinement.ts +286 -0
  90. package/src/core/workflows.ts +1202 -0
  91. package/src/discovery/slopsquat-guard.ts +286 -0
  92. package/src/hook.ts +1035 -0
  93. package/src/intel/registry-osv.ts +1678 -0
  94. package/src/mcp/report-store.ts +172 -0
  95. package/src/mcp/server.ts +1384 -0
  96. package/src/mcp/stdio-transport.ts +286 -0
  97. package/src/mcp/tool-catalog.ts +270 -0
  98. package/src/mcp/types.ts +92 -0
  99. package/src/mcp.ts +16 -0
  100. package/src/quarantine/safe-unpack.ts +565 -0
  101. package/src/types.ts +380 -0
  102. package/src/verdict/engine-and-formatters.ts +892 -0
@@ -0,0 +1,1384 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { delimiter } from "node:path";
3
+ import type { Readable, Writable } from "node:stream";
4
+ import { cleanupActiveGitTempDirs } from "../analysis/parity-and-bisect.ts";
5
+ import { defaultCacheDbPath, SplitPlaneCache } from "../cache/sqlite-store.ts";
6
+ import {
7
+ hasSecretLikeDiscoveryToken,
8
+ loadMcpPolicy,
9
+ loadNpmrc,
10
+ probeHostCapabilitiesAsync,
11
+ sanitizeOperatorEnvValue,
12
+ } from "../config/policy.ts";
13
+ import {
14
+ canonicalizeAuthorizedRoots,
15
+ intersectAuthorizedRoots,
16
+ parseFileUriToPath,
17
+ } from "../core/path-confinement.ts";
18
+ import {
19
+ runAuditManifestBatch,
20
+ runAuditVerify,
21
+ runDiscover,
22
+ runInspect,
23
+ runResolveAnchor,
24
+ runVerifyConfusion,
25
+ type OperatorRuntimeConfig,
26
+ type WorkflowContext,
27
+ } from "../core/workflows.ts";
28
+ import {
29
+ ENGINE_VERSION,
30
+ type DiscoveryCardList,
31
+ type HostCapabilities,
32
+ type ManifestBatchReport,
33
+ type PackageInspectionReport,
34
+ type SafeAnchorDecision,
35
+ } from "../types.ts";
36
+ import {
37
+ formatCycloneDxSbom,
38
+ formatInspectionMarkdownCard,
39
+ formatSarif210,
40
+ } from "../verdict/engine-and-formatters.ts";
41
+ import { BoundedReportStore, REPORT_TEXT_CHUNK_MAX_BYTES, sliceUtf8Safe } from "./report-store.ts";
42
+ import { StdioJsonRpcTransport } from "./stdio-transport.ts";
43
+ import { MCP_PROMPTS, MCP_RESOURCES, MCP_RESOURCE_TEMPLATES, MCP_TOOLS } from "./tool-catalog.ts";
44
+ import {
45
+ JSONRPC_ERRORS,
46
+ SUPPORTED_PROTOCOL_VERSIONS,
47
+ type JsonRpcId,
48
+ type JsonRpcRequest,
49
+ type McpLifecycleState,
50
+ type McpToolCallResult,
51
+ type SupportedProtocolVersion,
52
+ } from "./types.ts";
53
+
54
+ const SUMMARY_MAX_BYTES = 6144;
55
+ const BATCH_SUMMARY_MAX_BYTES = 2000;
56
+ const FULL_PAYLOAD_HARD_CAP_BYTES = 48 * 1024;
57
+ const DEFAULT_MAX_CONCURRENT = 4;
58
+ const DEFAULT_MAX_QUEUE = 16;
59
+
60
+ function isTruthyEnv(val: string | undefined): boolean {
61
+ if (!val) return false;
62
+ const v = val.trim().toLowerCase();
63
+ return v === "1" || v === "true" || v === "yes";
64
+ }
65
+
66
+ export function loadOperatorConfigFromEnv(env: NodeJS.ProcessEnv = process.env): OperatorRuntimeConfig {
67
+ const rawRoots = env["COLDPIN_ALLOWED_ROOTS"] ?? "";
68
+ const allowedRoots = rawRoots
69
+ .split(delimiter)
70
+ .map((s) => sanitizeOperatorEnvValue(s))
71
+ .filter((s): s is string => Boolean(s));
72
+ return {
73
+ policyPath: sanitizeOperatorEnvValue(env["COLDPIN_POLICY_PATH"]),
74
+ trustWorkspacePolicy: isTruthyEnv(env["COLDPIN_TRUST_WORKSPACE_POLICY"]),
75
+ auditLogPath: sanitizeOperatorEnvValue(env["COLDPIN_AUDIT_LOG"]),
76
+ cacheDir: sanitizeOperatorEnvValue(env["COLDPIN_CACHE_DIR"]),
77
+ allowedRoots,
78
+ forceOffline: isTruthyEnv(env["COLDPIN_OFFLINE"]),
79
+ verbose: isTruthyEnv(env["COLDPIN_VERBOSE"]),
80
+ allowPublicConfusionProbe: isTruthyEnv(env["COLDPIN_ALLOW_PUBLIC_CONFUSION_PROBE"]),
81
+ };
82
+ }
83
+
84
+ class BoundedSemaphore {
85
+ private active = 0;
86
+ private readonly queue: Array<{
87
+ resolve: () => void;
88
+ reject: (err: Error) => void;
89
+ signal?: AbortSignal;
90
+ onAbort?: () => void;
91
+ }> = [];
92
+ private readonly maxConcurrent: number;
93
+ private readonly maxQueue: number;
94
+
95
+ constructor(maxConcurrent = DEFAULT_MAX_CONCURRENT, maxQueue = DEFAULT_MAX_QUEUE) {
96
+ this.maxConcurrent = maxConcurrent;
97
+ this.maxQueue = maxQueue;
98
+ }
99
+
100
+ get activeSlots(): number {
101
+ return this.active;
102
+ }
103
+
104
+ acquire(signal?: AbortSignal): Promise<() => void> {
105
+ if (signal?.aborted) {
106
+ return Promise.reject(new Error("Operation aborted"));
107
+ }
108
+ if (this.active < this.maxConcurrent) {
109
+ this.active++;
110
+ return Promise.resolve(() => this.release());
111
+ }
112
+ if (this.queue.length >= this.maxQueue) {
113
+ return Promise.reject(new Error("SERVER_BUSY"));
114
+ }
115
+ return new Promise<() => void>((resolveAcquire, rejectAcquire) => {
116
+ const item: {
117
+ resolve: () => void;
118
+ reject: (err: Error) => void;
119
+ signal?: AbortSignal;
120
+ onAbort?: () => void;
121
+ } = {
122
+ resolve: () => resolveAcquire(() => this.release()),
123
+ reject: rejectAcquire,
124
+ signal,
125
+ };
126
+ if (signal) {
127
+ const onAbort = () => {
128
+ const idx = this.queue.indexOf(item);
129
+ if (idx >= 0) {
130
+ this.queue.splice(idx, 1);
131
+ rejectAcquire(new Error("Operation aborted"));
132
+ }
133
+ };
134
+ item.onAbort = onAbort;
135
+ signal.addEventListener("abort", onAbort, { once: true });
136
+ }
137
+ this.queue.push(item);
138
+ });
139
+ }
140
+
141
+ private release(): void {
142
+ this.active = Math.max(0, this.active - 1);
143
+ while (this.queue.length > 0 && this.active < this.maxConcurrent) {
144
+ const next = this.queue.shift()!;
145
+ if (next.signal && next.onAbort) {
146
+ next.signal.removeEventListener("abort", next.onAbort);
147
+ }
148
+ if (next.signal?.aborted) continue;
149
+ this.active++;
150
+ next.resolve();
151
+ return;
152
+ }
153
+ }
154
+ }
155
+
156
+ class ParamValidationError extends Error {
157
+ constructor(message: string) {
158
+ super(message);
159
+ this.name = "ParamValidationError";
160
+ }
161
+ }
162
+
163
+ function assertAllowedKeys(obj: Record<string, unknown>, allowed: readonly string[], toolName: string): void {
164
+ const allowedSet = new Set(allowed);
165
+ for (const key of Object.keys(obj)) {
166
+ if (!allowedSet.has(key)) {
167
+ throw new ParamValidationError(`Unexpected parameter '${key}' for tool '${toolName}'.`);
168
+ }
169
+ }
170
+ }
171
+
172
+ function readOptionalString(
173
+ obj: Record<string, unknown>,
174
+ key: string,
175
+ maxLen: number,
176
+ minLen = 0,
177
+ ): string | undefined {
178
+ const val = obj[key];
179
+ if (val === undefined) return undefined;
180
+ if (typeof val !== "string") throw new ParamValidationError(`Parameter '${key}' must be a string.`);
181
+ if (val.length < minLen || val.length > maxLen) {
182
+ throw new ParamValidationError(`Parameter '${key}' length must be between ${minLen} and ${maxLen}.`);
183
+ }
184
+ return val;
185
+ }
186
+
187
+ function readRequiredString(obj: Record<string, unknown>, key: string, minLen: number, maxLen: number): string {
188
+ const val = readOptionalString(obj, key, maxLen, minLen);
189
+ if (val === undefined) throw new ParamValidationError(`Missing required string parameter '${key}'.`);
190
+ return val;
191
+ }
192
+
193
+ function readOptionalInt(
194
+ obj: Record<string, unknown>,
195
+ key: string,
196
+ min: number,
197
+ max: number,
198
+ ): number | undefined {
199
+ const val = obj[key];
200
+ if (val === undefined) return undefined;
201
+ if (typeof val !== "number" || !Number.isInteger(val) || val < min || val > max) {
202
+ throw new ParamValidationError(`Parameter '${key}' must be an integer between ${min} and ${max}.`);
203
+ }
204
+ return val;
205
+ }
206
+
207
+ function readOptionalBool(obj: Record<string, unknown>, key: string): boolean | undefined {
208
+ const val = obj[key];
209
+ if (val === undefined) return undefined;
210
+ if (typeof val !== "boolean") throw new ParamValidationError(`Parameter '${key}' must be a boolean.`);
211
+ return val;
212
+ }
213
+
214
+ function readOptionalEnum<T extends string>(
215
+ obj: Record<string, unknown>,
216
+ key: string,
217
+ allowed: readonly T[],
218
+ fallback: T,
219
+ ): T {
220
+ const val = obj[key];
221
+ if (val === undefined) return fallback;
222
+ if (typeof val !== "string" || !allowed.includes(val as T)) {
223
+ throw new ParamValidationError(`Parameter '${key}' must be one of: ${allowed.join(", ")}.`);
224
+ }
225
+ return val as T;
226
+ }
227
+
228
+ function truncateText(s: string, maxChars: number): string {
229
+ return s.length <= maxChars ? s : `${s.slice(0, Math.max(0, maxChars - 1))}…`;
230
+ }
231
+
232
+ function fitJsonSummaryWithinBudget(
233
+ buildPayload: (obsLimit: number, unkLimit: number, detailChars: number) => Record<string, unknown>,
234
+ maxBytes = SUMMARY_MAX_BYTES,
235
+ ): { obj: Record<string, unknown>; text: string } {
236
+ const attempts: Array<[number, number, number]> = [
237
+ [10, 8, 140],
238
+ [6, 5, 110],
239
+ [3, 3, 90],
240
+ [1, 2, 72],
241
+ [0, 1, 60],
242
+ ];
243
+ for (const [oLim, uLim, dChars] of attempts) {
244
+ const obj = buildPayload(oLim, uLim, dChars);
245
+ const text = JSON.stringify(obj);
246
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) {
247
+ return { obj, text };
248
+ }
249
+ }
250
+ const minimal = buildPayload(0, 0, 40);
251
+ return { obj: minimal, text: JSON.stringify(minimal) };
252
+ }
253
+
254
+ function buildInspectSummary(report: PackageInspectionReport, reportId: string): {
255
+ obj: Record<string, unknown>;
256
+ text: string;
257
+ } {
258
+ const allObs = report.evidence.flatMap((e) => e.observations);
259
+ const allUnknowns = report.evidence.flatMap((e) => e.unknowns);
260
+ return fitJsonSummaryWithinBudget((obsLim, unkLim, detailChars) => ({
261
+ schema_version: "1",
262
+ report_id: reportId,
263
+ package_name: report.title.package_name,
264
+ version: report.title.version,
265
+ verdict: report.verdict,
266
+ recommended_action: report.recommended_action,
267
+ parity_tier: report.info.parity_tier,
268
+ pinned_execution: {
269
+ command: report.pinned_execution.command,
270
+ exact_version: report.pinned_execution.exact_version,
271
+ tarball_sha512: report.pinned_execution.tarball_sha512,
272
+ caveat: truncateText(report.pinned_execution.caveat, 160),
273
+ },
274
+ top_observations: allObs.slice(0, obsLim).map((o) => ({
275
+ code: o.code,
276
+ severity: o.severity,
277
+ path: truncateText(o.path, 80),
278
+ ...(o.line !== undefined ? { line: o.line } : {}),
279
+ detail: truncateText(o.detail, detailChars),
280
+ })),
281
+ unknowns: allUnknowns.slice(0, unkLim).map((u) => truncateText(u, detailChars)),
282
+ ...(report.local_workspace_compromised
283
+ ? {
284
+ local_workspace_compromised: {
285
+ lockfile_kind: report.local_workspace_compromised.lockfile_kind,
286
+ matched_version: report.local_workspace_compromised.matched_version,
287
+ containment_steps_count: report.local_workspace_compromised.containment_steps.length,
288
+ },
289
+ }
290
+ : {}),
291
+ ...(report.rea_escalation_plan
292
+ ? {
293
+ rea_escalation_plan: {
294
+ required: report.rea_escalation_plan.required,
295
+ rea_available_on_host: report.rea_escalation_plan.rea_available_on_host,
296
+ steps_count: report.rea_escalation_plan.steps.length,
297
+ },
298
+ }
299
+ : {}),
300
+ counts: {
301
+ observations: allObs.length,
302
+ iocs: report.iocs.length,
303
+ unknowns: allUnknowns.length,
304
+ evidence: report.evidence.length,
305
+ },
306
+ }));
307
+ }
308
+
309
+ function buildDiscoverSummary(report: DiscoveryCardList, reportId: string): {
310
+ obj: Record<string, unknown>;
311
+ text: string;
312
+ } {
313
+ return fitJsonSummaryWithinBudget((candLim, blkLim, detailChars) => ({
314
+ schema_version: "1",
315
+ report_id: reportId,
316
+ query: truncateText(report.query, 96),
317
+ registry_route: report.registry_route,
318
+ candidates: report.candidates.slice(0, Math.max(candLim, 1)).map((c) => ({
319
+ package_name: c.package_name,
320
+ version: c.version,
321
+ license: c.license,
322
+ verdict_preview: c.verdict_preview,
323
+ squat_warning_count: c.squat_warnings.length,
324
+ summary: truncateText(c.summary, detailChars),
325
+ })),
326
+ blocked_candidates: report.blocked_candidates.slice(0, Math.max(blkLim, 1)).map((b) => ({
327
+ package_name: truncateText(b.package_name, 80),
328
+ reason: truncateText(b.reason, detailChars),
329
+ })),
330
+ unknowns: report.unknowns.slice(0, 4).map((u) => truncateText(u, detailChars)),
331
+ counts: {
332
+ candidates: report.candidates.length,
333
+ blocked: report.blocked_candidates.length,
334
+ unknowns: report.unknowns.length,
335
+ },
336
+ }));
337
+ }
338
+
339
+ function buildAnchorSummary(decision: SafeAnchorDecision, reportId: string): {
340
+ obj: Record<string, unknown>;
341
+ text: string;
342
+ } {
343
+ return fitJsonSummaryWithinBudget((altLim, unkLim, detailChars) => ({
344
+ schema_version: "1",
345
+ report_id: reportId,
346
+ package_name: decision.package_name,
347
+ recommended_action: decision.recommended_action,
348
+ compromised_latest: {
349
+ ...(decision.compromised_latest.version ? { version: decision.compromised_latest.version } : {}),
350
+ ...(decision.compromised_latest.patient_zero_sha
351
+ ? { patient_zero_sha: decision.compromised_latest.patient_zero_sha }
352
+ : {}),
353
+ reason: truncateText(decision.compromised_latest.reason, 180),
354
+ },
355
+ ...(decision.safe_anchor
356
+ ? {
357
+ safe_anchor: {
358
+ commit_sha: decision.safe_anchor.commit_sha,
359
+ version: decision.safe_anchor.version,
360
+ pinned_command: decision.safe_anchor.pinned_execution.command,
361
+ residual_advisories_count: decision.safe_anchor.residual_advisories.length,
362
+ },
363
+ }
364
+ : {}),
365
+ alternatives: decision.alternatives.slice(0, Math.max(altLim, 1)).map((a) => ({
366
+ package_name: a.package_name,
367
+ version: a.version,
368
+ verdict: a.verdict,
369
+ reason: truncateText(a.reason, detailChars),
370
+ })),
371
+ unknowns: decision.unknowns.slice(0, unkLim).map((u) => truncateText(u, detailChars)),
372
+ counts: {
373
+ inspected_commits: decision.inspected_commits.length,
374
+ alternatives: decision.alternatives.length,
375
+ evidence: decision.evidence.length,
376
+ unknowns: decision.unknowns.length,
377
+ },
378
+ }));
379
+ }
380
+
381
+ function buildBatchSummary(report: ManifestBatchReport, reportId: string): {
382
+ obj: Record<string, unknown>;
383
+ text: string;
384
+ } {
385
+ return fitJsonSummaryWithinBudget(
386
+ (flagLim, unkLim, detailChars) => ({
387
+ schema_version: "1",
388
+ report_id: reportId,
389
+ manifest_path: truncateText(report.manifest_path, 120),
390
+ total_declared: report.total_declared,
391
+ evaluated_count: report.evaluated_count,
392
+ truncated_at_cap: report.truncated_at_cap,
393
+ offline_mode: report.offline_mode,
394
+ summary_counts: report.summary_counts,
395
+ top_flagged: report.flagged.slice(0, flagLim).map((f) => ({
396
+ package_name: truncateText(f.package_name, 72),
397
+ status: f.status,
398
+ route: f.route,
399
+ reason: truncateText(f.reasons[0] ?? "", Math.min(detailChars, 90)),
400
+ ...(f.advisory_ids.length > 0 ? { advisory_ids: f.advisory_ids.slice(0, 3) } : {}),
401
+ })),
402
+ unknowns: report.unknowns.slice(0, Math.min(unkLim, 4)).map((u) => truncateText(u, Math.min(detailChars, 100))),
403
+ counts: {
404
+ flagged: report.flagged.length,
405
+ unknowns: report.unknowns.length,
406
+ },
407
+ }),
408
+ BATCH_SUMMARY_MAX_BYTES,
409
+ );
410
+ }
411
+
412
+ function buildResourceConstraintResult(reportId: string, section: string, totalBytes: number): McpToolCallResult {
413
+ const payload = {
414
+ schema_version: "1",
415
+ resource_constraint: true,
416
+ report_id: reportId,
417
+ section,
418
+ total_bytes: totalBytes,
419
+ max_inline_bytes: FULL_PAYLOAD_HARD_CAP_BYTES,
420
+ next_call: {
421
+ tool: "get_artifact_report",
422
+ arguments: { report_id: reportId, section, offset: 0 },
423
+ },
424
+ message: `Payload (${totalBytes} bytes) exceeds 48 KiB inline cap; page via get_artifact_report.`,
425
+ };
426
+ return {
427
+ content: [{ type: "text", text: JSON.stringify(payload) }],
428
+ structuredContent: payload,
429
+ isError: false,
430
+ };
431
+ }
432
+
433
+ export interface ColdpinMcpServerOptions {
434
+ operatorConfig?: OperatorRuntimeConfig;
435
+ input?: Readable;
436
+ output?: Writable;
437
+ errorOutput?: Writable;
438
+ hijackProcessStdio?: boolean;
439
+ maxConcurrent?: number;
440
+ maxQueue?: number;
441
+ reportStore?: BoundedReportStore;
442
+ hostCapabilities?: HostCapabilities;
443
+ }
444
+
445
+ export class ColdpinMcpServer {
446
+ private readonly operatorConfig: OperatorRuntimeConfig;
447
+ private readonly transport: StdioJsonRpcTransport;
448
+ private readonly cache: SplitPlaneCache;
449
+ private readonly reportStore: BoundedReportStore;
450
+ private readonly semaphore: BoundedSemaphore;
451
+
452
+ private state: McpLifecycleState = "UNINITIALIZED";
453
+ private negotiatedProtocol: SupportedProtocolVersion = SUPPORTED_PROTOCOL_VERSIONS[0];
454
+ private clientSupportsRoots = false;
455
+ private clientName: string | undefined;
456
+ private clientRoots: string[] = [];
457
+ private effectiveRoots: string[];
458
+ private hostCapabilitiesPromise: Promise<HostCapabilities> | null = null;
459
+ private readonly inFlightControllers = new Map<string, AbortController>();
460
+ private shutdownComplete = false;
461
+
462
+ constructor(opts: ColdpinMcpServerOptions = {}) {
463
+ this.operatorConfig = opts.operatorConfig ?? loadOperatorConfigFromEnv();
464
+ this.effectiveRoots = canonicalizeAuthorizedRoots(this.operatorConfig.allowedRoots);
465
+ this.cache = new SplitPlaneCache(
466
+ this.operatorConfig.cacheDir ? defaultCacheDbPath(this.operatorConfig.cacheDir) : defaultCacheDbPath(),
467
+ );
468
+ this.reportStore = opts.reportStore ?? new BoundedReportStore();
469
+ this.semaphore = new BoundedSemaphore(opts.maxConcurrent, opts.maxQueue);
470
+
471
+ if (opts.hostCapabilities) {
472
+ this.hostCapabilitiesPromise = Promise.resolve(opts.hostCapabilities);
473
+ }
474
+
475
+ this.transport = new StdioJsonRpcTransport({
476
+ input: opts.input,
477
+ output: opts.output,
478
+ errorOutput: opts.errorOutput,
479
+ hijackProcessStdio: opts.hijackProcessStdio ?? false,
480
+ onMessage: (raw) => this.handleIncomingMessage(raw),
481
+ onParseError: (msg) => {
482
+ if (this.operatorConfig.verbose) {
483
+ this.transport.writeStderrLog({ stage: "parse_error", message: msg });
484
+ }
485
+ },
486
+ onClose: () => {
487
+ void this.shutdown();
488
+ },
489
+ });
490
+ }
491
+
492
+ start(): void {
493
+ // Warm host capability probe asynchronously at startup (never blocks event loop)
494
+ if (!this.hostCapabilitiesPromise) {
495
+ this.hostCapabilitiesPromise = probeHostCapabilitiesAsync();
496
+ }
497
+ this.transport.start();
498
+ }
499
+
500
+ async shutdown(): Promise<void> {
501
+ if (this.shutdownComplete) return;
502
+ this.shutdownComplete = true;
503
+ this.state = "SHUTTING_DOWN";
504
+ for (const ctrl of this.inFlightControllers.values()) {
505
+ ctrl.abort();
506
+ }
507
+ this.inFlightControllers.clear();
508
+ cleanupActiveGitTempDirs();
509
+ try {
510
+ await this.transport.flush();
511
+ } catch {
512
+ // Ignore flush error during shutdown
513
+ }
514
+ try {
515
+ this.cache.close();
516
+ } catch {
517
+ // Ignore already-closed cache
518
+ }
519
+ }
520
+
521
+ private recomputeEffectiveRoots(): void {
522
+ const opRoots = canonicalizeAuthorizedRoots(this.operatorConfig.allowedRoots);
523
+ if (opRoots.length > 0) {
524
+ this.effectiveRoots =
525
+ this.clientRoots.length > 0 ? intersectAuthorizedRoots(this.clientRoots, opRoots) : opRoots;
526
+ } else if (this.clientRoots.length > 0) {
527
+ this.effectiveRoots = canonicalizeAuthorizedRoots(this.clientRoots);
528
+ } else {
529
+ this.effectiveRoots = [];
530
+ }
531
+ }
532
+
533
+ private async syncClientRoots(): Promise<void> {
534
+ if (!this.clientSupportsRoots || this.state === "SHUTTING_DOWN") return;
535
+ try {
536
+ const res = (await this.transport.sendClientRequest("roots/list", {}, 3000)) as {
537
+ roots?: Array<{ uri?: string }>;
538
+ } | null;
539
+ const parsedPaths: string[] = [];
540
+ for (const r of res?.roots ?? []) {
541
+ if (typeof r?.uri === "string") {
542
+ const fsPath = parseFileUriToPath(r.uri);
543
+ if (fsPath) parsedPaths.push(fsPath);
544
+ }
545
+ }
546
+ this.clientRoots = parsedPaths;
547
+ this.recomputeEffectiveRoots();
548
+ } catch (err) {
549
+ if (this.operatorConfig.verbose) {
550
+ this.transport.writeStderrLog({
551
+ stage: "roots_sync_fallback",
552
+ error: err instanceof Error ? err.message : String(err),
553
+ });
554
+ }
555
+ }
556
+ }
557
+
558
+ private async buildWorkflowContext(requestId: string, signal?: AbortSignal): Promise<WorkflowContext> {
559
+ const hostCaps = await (this.hostCapabilitiesPromise ?? probeHostCapabilitiesAsync());
560
+ const primaryRoot = this.effectiveRoots[0];
561
+ const { policy, policy_sha256 } = loadMcpPolicy({
562
+ explicitPolicyPath: this.operatorConfig.policyPath,
563
+ workspaceRoot: primaryRoot,
564
+ trustWorkspacePolicy: this.operatorConfig.trustWorkspacePolicy,
565
+ forceOffline: this.operatorConfig.forceOffline,
566
+ });
567
+ const npmrc = loadNpmrc(primaryRoot ?? process.cwd(), {
568
+ includeWorkspaceRegistries: this.operatorConfig.trustWorkspacePolicy,
569
+ });
570
+ return {
571
+ cwd: primaryRoot,
572
+ workspaceRoots: this.effectiveRoots,
573
+ enforceRootConfinement: true,
574
+ policy,
575
+ policy_sha256,
576
+ npmrc,
577
+ host_capabilities: hostCaps,
578
+ cache: this.cache,
579
+ auditLogPath: this.operatorConfig.auditLogPath,
580
+ invokerSurface: "mcp",
581
+ mcpClientName: this.clientName,
582
+ requestId,
583
+ signal,
584
+ onTelemetry: this.operatorConfig.verbose
585
+ ? (ev) => this.transport.writeStderrLog({ ...ev, active_slots: this.semaphore.activeSlots })
586
+ : undefined,
587
+ };
588
+ }
589
+
590
+ private async handleIncomingMessage(raw: unknown): Promise<void> {
591
+ // Reject JSON-RPC batch arrays on MCP 2025-06-18 / 2025-11-25 (and pre-init)
592
+ if (Array.isArray(raw)) {
593
+ await this.transport.sendError(
594
+ null,
595
+ JSONRPC_ERRORS.INVALID_REQUEST,
596
+ `JSON-RPC batch requests are not supported under MCP ${this.negotiatedProtocol}.`,
597
+ );
598
+ return;
599
+ }
600
+
601
+ if (raw === null || typeof raw !== "object") {
602
+ await this.transport.sendError(null, JSONRPC_ERRORS.INVALID_REQUEST, "Invalid JSON-RPC request object.");
603
+ return;
604
+ }
605
+
606
+ const msg = raw as Partial<JsonRpcRequest>;
607
+ const hasId = Object.prototype.hasOwnProperty.call(msg, "id");
608
+ const id: JsonRpcId = hasId ? (msg.id as JsonRpcId) : null;
609
+
610
+ if (msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || msg.method.length === 0) {
611
+ if (hasId) {
612
+ await this.transport.sendError(id, JSONRPC_ERRORS.INVALID_REQUEST, "Invalid JSON-RPC 2.0 envelope.");
613
+ }
614
+ return;
615
+ }
616
+
617
+ const method = msg.method;
618
+ const params = msg.params && typeof msg.params === "object" && !Array.isArray(msg.params) ? msg.params : {};
619
+
620
+ // Notifications (no id)
621
+ if (!hasId) {
622
+ await this.handleNotification(method, params);
623
+ return;
624
+ }
625
+
626
+ // Requests (have id)
627
+ if (method === "ping") {
628
+ await this.transport.sendResult(id, {});
629
+ return;
630
+ }
631
+
632
+ if (method === "initialize") {
633
+ await this.handleInitialize(id, params);
634
+ return;
635
+ }
636
+
637
+ if (this.state === "UNINITIALIZED") {
638
+ await this.transport.sendError(
639
+ id,
640
+ JSONRPC_ERRORS.NOT_INITIALIZED,
641
+ "Server not initialized; send 'initialize' first.",
642
+ );
643
+ return;
644
+ }
645
+
646
+ // Legacy client compatibility: transition INITIALIZING -> ACTIVE without blocking on roots/list
647
+ if (this.state === "INITIALIZING") {
648
+ this.state = "ACTIVE";
649
+ }
650
+
651
+ if (this.state === "SHUTTING_DOWN") {
652
+ await this.transport.sendError(id, JSONRPC_ERRORS.SERVER_BUSY, "Server is shutting down.");
653
+ return;
654
+ }
655
+
656
+ if (method === "tools/list") {
657
+ await this.transport.sendResult(id, { tools: MCP_TOOLS });
658
+ return;
659
+ }
660
+
661
+ if (method === "resources/list") {
662
+ await this.transport.sendResult(id, { resources: MCP_RESOURCES });
663
+ return;
664
+ }
665
+
666
+ if (method === "resources/templates/list") {
667
+ await this.transport.sendResult(id, { resourceTemplates: MCP_RESOURCE_TEMPLATES });
668
+ return;
669
+ }
670
+
671
+ if (method === "resources/read") {
672
+ await this.handleResourceRead(id, params);
673
+ return;
674
+ }
675
+
676
+ if (method === "prompts/list") {
677
+ await this.transport.sendResult(id, { prompts: MCP_PROMPTS });
678
+ return;
679
+ }
680
+
681
+ if (method === "prompts/get") {
682
+ await this.handlePromptGet(id, params);
683
+ return;
684
+ }
685
+
686
+ if (method === "tools/call") {
687
+ await this.handleToolCall(id, params);
688
+ return;
689
+ }
690
+
691
+ await this.transport.sendError(id, JSONRPC_ERRORS.METHOD_NOT_FOUND, `Method not found: ${method}`);
692
+ }
693
+
694
+ private async handleNotification(method: string, params: Record<string, unknown>): Promise<void> {
695
+ if (method === "notifications/initialized") {
696
+ if (this.state === "INITIALIZING") {
697
+ this.state = "ROOTS_SYNCING";
698
+ await this.syncClientRoots();
699
+ if (this.state === "ROOTS_SYNCING") this.state = "ACTIVE";
700
+ }
701
+ return;
702
+ }
703
+ if (method === "notifications/roots/list_changed") {
704
+ if (this.state === "ACTIVE") {
705
+ await this.syncClientRoots();
706
+ }
707
+ return;
708
+ }
709
+ if (method === "notifications/cancelled") {
710
+ const targetId = params["requestId"];
711
+ if (targetId !== undefined && targetId !== null) {
712
+ const ctrl = this.inFlightControllers.get(String(targetId));
713
+ if (ctrl) ctrl.abort();
714
+ }
715
+ }
716
+ }
717
+
718
+ private async handleInitialize(id: JsonRpcId, params: Record<string, unknown>): Promise<void> {
719
+ const requested = typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : "";
720
+ const matched = SUPPORTED_PROTOCOL_VERSIONS.find((v) => v === requested);
721
+ this.negotiatedProtocol = matched ?? SUPPORTED_PROTOCOL_VERSIONS[0];
722
+
723
+ const clientCaps =
724
+ params["capabilities"] && typeof params["capabilities"] === "object"
725
+ ? (params["capabilities"] as Record<string, unknown>)
726
+ : {};
727
+ this.clientSupportsRoots = Boolean(clientCaps["roots"]);
728
+
729
+ const clientInfo =
730
+ params["clientInfo"] && typeof params["clientInfo"] === "object"
731
+ ? (params["clientInfo"] as Record<string, unknown>)
732
+ : {};
733
+ if (typeof clientInfo["name"] === "string" && clientInfo["name"].trim().length > 0) {
734
+ this.clientName = clientInfo["name"].trim().slice(0, 64);
735
+ }
736
+
737
+ this.state = "INITIALIZING";
738
+ await this.transport.sendResult(id, {
739
+ protocolVersion: this.negotiatedProtocol,
740
+ capabilities: {
741
+ tools: { listChanged: false },
742
+ resources: { subscribe: false, listChanged: false },
743
+ prompts: { listChanged: false },
744
+ },
745
+ serverInfo: {
746
+ name: "coldpin",
747
+ version: ENGINE_VERSION,
748
+ },
749
+ });
750
+ }
751
+
752
+ private async handleResourceRead(id: JsonRpcId, params: Record<string, unknown>): Promise<void> {
753
+ const uri = typeof params["uri"] === "string" ? params["uri"] : "";
754
+ if (!uri) {
755
+ await this.transport.sendError(id, JSONRPC_ERRORS.INVALID_PARAMS, "Missing required resource 'uri'.");
756
+ return;
757
+ }
758
+
759
+ if (uri === "coldpin://policy/active") {
760
+ const ctx = await this.buildWorkflowContext(`res_${randomUUID().slice(0, 12)}`);
761
+ const sanitized = {
762
+ schema_version: "1",
763
+ engine_version: ENGINE_VERSION,
764
+ policy_sha256: ctx.policy_sha256,
765
+ allowed_roots_count: this.effectiveRoots.length,
766
+ trust_workspace_policy: this.operatorConfig.trustWorkspacePolicy,
767
+ allow_public_confusion_probe: this.operatorConfig.allowPublicConfusionProbe,
768
+ audit_logging_enabled: Boolean(this.operatorConfig.auditLogPath),
769
+ host_capabilities: ctx.host_capabilities,
770
+ policy: {
771
+ private_scopes: ctx.policy.private_scopes,
772
+ private_prefixes: ctx.policy.private_prefixes,
773
+ private_registry_scopes: Object.keys(ctx.policy.private_registries),
774
+ default_registry: ctx.policy.default_registry,
775
+ osv_api_url: ctx.policy.osv_api_url,
776
+ allow_public_fallback: ctx.policy.allow_public_fallback,
777
+ allowed_orgs: ctx.policy.allowed_orgs,
778
+ denied_orgs: ctx.policy.denied_orgs,
779
+ blocked_licenses: ctx.policy.blocked_licenses,
780
+ cooldown_hours: ctx.policy.cooldown_hours,
781
+ max_compressed_bytes: ctx.policy.max_compressed_bytes,
782
+ max_uncompressed_bytes: ctx.policy.max_uncompressed_bytes,
783
+ max_files: ctx.policy.max_files,
784
+ max_single_file_bytes: ctx.policy.max_single_file_bytes,
785
+ block_on_kev: ctx.policy.block_on_kev,
786
+ block_on_critical_cve: ctx.policy.block_on_critical_cve,
787
+ block_on_high_cve: ctx.policy.block_on_high_cve,
788
+ require_provenance: ctx.policy.require_provenance,
789
+ require_source_link: ctx.policy.require_source_link,
790
+ bisect_max_commits: ctx.policy.bisect_max_commits,
791
+ bisect_max_days: ctx.policy.bisect_max_days,
792
+ offline_mode: ctx.policy.offline_mode,
793
+ },
794
+ };
795
+ await this.transport.sendResult(id, {
796
+ contents: [
797
+ {
798
+ uri,
799
+ mimeType: "application/json",
800
+ text: JSON.stringify(sanitized, null, 2),
801
+ },
802
+ ],
803
+ });
804
+ return;
805
+ }
806
+
807
+ const rptMatch = /^coldpin:\/\/reports\/(rpt_[a-f0-9-]{4,48})$/.exec(uri);
808
+ if (rptMatch?.[1]) {
809
+ const reportId = rptMatch[1];
810
+ const stored = this.reportStore.get(reportId);
811
+ if (!stored) {
812
+ await this.transport.sendError(
813
+ id,
814
+ JSONRPC_ERRORS.INVALID_PARAMS,
815
+ `Session report '${reportId}' not found or expired.`,
816
+ );
817
+ return;
818
+ }
819
+ const summary =
820
+ stored.kind === "inspect"
821
+ ? buildInspectSummary(stored.report, reportId).text
822
+ : stored.kind === "discover"
823
+ ? buildDiscoverSummary(stored.report, reportId).text
824
+ : stored.kind === "batch"
825
+ ? buildBatchSummary(stored.report, reportId).text
826
+ : buildAnchorSummary(stored.decision, reportId).text;
827
+ await this.transport.sendResult(id, {
828
+ contents: [{ uri, mimeType: "application/json", text: summary }],
829
+ });
830
+ return;
831
+ }
832
+
833
+ await this.transport.sendError(id, JSONRPC_ERRORS.INVALID_PARAMS, `Unknown resource URI: ${uri}`);
834
+ }
835
+
836
+ private async handlePromptGet(id: JsonRpcId, params: Record<string, unknown>): Promise<void> {
837
+ const name = typeof params["name"] === "string" ? params["name"] : "";
838
+ const args =
839
+ params["arguments"] && typeof params["arguments"] === "object" && !Array.isArray(params["arguments"])
840
+ ? (params["arguments"] as Record<string, unknown>)
841
+ : {};
842
+
843
+ if (name === "vet_before_npx") {
844
+ const pkgSpec = typeof args["package_spec"] === "string" ? args["package_spec"].trim() : "";
845
+ if (!pkgSpec || pkgSpec.length > 256) {
846
+ await this.transport.sendError(id, JSONRPC_ERRORS.INVALID_PARAMS, "Prompt 'vet_before_npx' requires 'package_spec'.");
847
+ return;
848
+ }
849
+ const gitDir = typeof args["git_dir"] === "string" ? args["git_dir"].trim() : "";
850
+ const text = gitDir
851
+ ? `Run Coldpin tool 'inspect_package_artifact' with package_spec="${pkgSpec}" and git_dir="${gitDir}" (detail="summary"). Present the deterministic verdict, parity tier, unknowns, and only propose the pinned npx command if verdict is VERIFIED_CLEAN_WITHIN_SCOPE and the human explicitly approves execution.`
852
+ : `Run Coldpin tool 'inspect_package_artifact' with package_spec="${pkgSpec}" (detail="summary"). Present the deterministic verdict, parity tier, unknowns, and only propose the pinned npx command if verdict is VERIFIED_CLEAN_WITHIN_SCOPE and the human explicitly approves execution.`;
853
+ await this.transport.sendResult(id, {
854
+ description: "Vet an npm package cold before running npx.",
855
+ messages: [{ role: "user", content: { type: "text", text } }],
856
+ });
857
+ return;
858
+ }
859
+
860
+ if (name === "investigate_compromised_org") {
861
+ const pkgName = typeof args["package_name"] === "string" ? args["package_name"].trim() : "";
862
+ if (!pkgName || pkgName.length > 214) {
863
+ await this.transport.sendError(
864
+ id,
865
+ JSONRPC_ERRORS.INVALID_PARAMS,
866
+ "Prompt 'investigate_compromised_org' requires 'package_name'.",
867
+ );
868
+ return;
869
+ }
870
+ const repoUrl = typeof args["repo_url"] === "string" ? args["repo_url"].trim() : "";
871
+ const text = repoUrl
872
+ ? `Run Coldpin tool 'resolve_safe_anchor' with package_name="${pkgName}" and repo_url="${repoUrl}" (detail="summary"). Report patient-zero commit SHA, safe pre-compromise version or vetted alternatives, and any residual advisories or unknowns.`
873
+ : `Run Coldpin tool 'resolve_safe_anchor' with package_name="${pkgName}" (detail="summary"). Report patient-zero commit SHA, safe pre-compromise version or vetted alternatives, and any residual advisories or unknowns.`;
874
+ await this.transport.sendResult(id, {
875
+ description: "Locate patient-zero commit and safe rollback anchor or vetted alternative.",
876
+ messages: [{ role: "user", content: { type: "text", text } }],
877
+ });
878
+ return;
879
+ }
880
+
881
+ await this.transport.sendError(id, JSONRPC_ERRORS.INVALID_PARAMS, `Unknown prompt: ${name}`);
882
+ }
883
+
884
+ private async handleToolCall(id: JsonRpcId, params: Record<string, unknown>): Promise<void> {
885
+ const toolName = typeof params["name"] === "string" ? params["name"] : "";
886
+ const rawArgs = params["arguments"] ?? {};
887
+ if (!toolName || rawArgs === null || typeof rawArgs !== "object" || Array.isArray(rawArgs)) {
888
+ await this.transport.sendError(id, JSONRPC_ERRORS.INVALID_PARAMS, "Invalid tools/call parameters.");
889
+ return;
890
+ }
891
+ const args = rawArgs as Record<string, unknown>;
892
+ const knownTool = MCP_TOOLS.some((t) => t.name === toolName);
893
+ if (!knownTool) {
894
+ await this.transport.sendError(id, JSONRPC_ERRORS.INVALID_PARAMS, `Unknown tool: ${toolName}`);
895
+ return;
896
+ }
897
+
898
+ // Validate parameters synchronously BEFORE acquiring semaphore slot so bad schemas never consume slots
899
+ try {
900
+ this.validateToolArguments(toolName, args);
901
+ } catch (err) {
902
+ const msg = err instanceof Error ? err.message : "Invalid tool arguments";
903
+ await this.transport.sendError(id, JSONRPC_ERRORS.INVALID_PARAMS, msg);
904
+ return;
905
+ }
906
+
907
+ const startMs = Date.now();
908
+ const rpcKey = String(id);
909
+ const controller = new AbortController();
910
+ this.inFlightControllers.set(rpcKey, controller);
911
+
912
+ let release: (() => void) | null = null;
913
+ try {
914
+ release = await this.semaphore.acquire(controller.signal);
915
+ } catch (err) {
916
+ this.inFlightControllers.delete(rpcKey);
917
+ const errMsg = err instanceof Error ? err.message : String(err);
918
+ if (errMsg === "SERVER_BUSY") {
919
+ await this.transport.sendError(
920
+ id,
921
+ JSONRPC_ERRORS.SERVER_BUSY,
922
+ "Coldpin MCP server concurrency queue saturated; retry shortly.",
923
+ );
924
+ } else {
925
+ await this.transport.sendResult(id, {
926
+ content: [{ type: "text", text: "Request cancelled before execution." }],
927
+ isError: true,
928
+ });
929
+ }
930
+ return;
931
+ }
932
+
933
+ const requestId = `mcp_${randomUUID().slice(0, 12)}`;
934
+ try {
935
+ const result = await this.executeTool(toolName, args, requestId, controller.signal);
936
+ if (this.operatorConfig.verbose) {
937
+ this.transport.writeStderrLog({
938
+ request_id: requestId,
939
+ rpc_id: id,
940
+ tool: toolName,
941
+ duration_ms: Date.now() - startMs,
942
+ active_slots: this.semaphore.activeSlots,
943
+ is_error: result.isError,
944
+ });
945
+ }
946
+ await this.transport.sendResult(id, result);
947
+ } catch (err) {
948
+ const msg = err instanceof Error ? err.message : String(err);
949
+ if (this.operatorConfig.verbose) {
950
+ this.transport.writeStderrLog({
951
+ request_id: requestId,
952
+ rpc_id: id,
953
+ tool: toolName,
954
+ duration_ms: Date.now() - startMs,
955
+ active_slots: this.semaphore.activeSlots,
956
+ error_code: "TOOL_EXEC_ERROR",
957
+ });
958
+ }
959
+ await this.transport.sendResult(id, {
960
+ content: [{ type: "text", text: `Operational error executing '${toolName}': ${msg}` }],
961
+ isError: true,
962
+ });
963
+ } finally {
964
+ this.inFlightControllers.delete(rpcKey);
965
+ if (release) release();
966
+ }
967
+ }
968
+
969
+ private validateToolArguments(toolName: string, args: Record<string, unknown>): void {
970
+ if (toolName === "discover_packages") {
971
+ assertAllowedKeys(args, ["query", "org", "creator", "category", "limit", "detail"], toolName);
972
+ const query = readRequiredString(args, "query", 1, 128);
973
+ const org = readOptionalString(args, "org", 64);
974
+ const creator = readOptionalString(args, "creator", 64);
975
+ const category = readOptionalString(args, "category", 64);
976
+ readOptionalInt(args, "limit", 1, 25);
977
+ readOptionalEnum(args, "detail", ["summary", "full"] as const, "summary");
978
+ // Security [MCP-04]: reject credential/secret-like strings across all 4 discovery arguments with -32602
979
+ for (const [k, v] of [
980
+ ["query", query],
981
+ ["org", org],
982
+ ["creator", creator],
983
+ ["category", category],
984
+ ] as const) {
985
+ if (v && hasSecretLikeDiscoveryToken(v)) {
986
+ throw new ParamValidationError(`Parameter '${k}' contains credential-shaped or secret-like material.`);
987
+ }
988
+ }
989
+ return;
990
+ }
991
+
992
+ if (toolName === "inspect_package_artifact") {
993
+ assertAllowedKeys(
994
+ args,
995
+ ["package_spec", "tarball_path", "git_dir", "subdir", "offline", "detail", "format"],
996
+ toolName,
997
+ );
998
+ const pkgSpec = readOptionalString(args, "package_spec", 256, 1);
999
+ const tarballPath = readOptionalString(args, "tarball_path", 1024, 1);
1000
+ if (Boolean(pkgSpec) === Boolean(tarballPath)) {
1001
+ throw new ParamValidationError("Specify exactly one of 'package_spec' or 'tarball_path' (XOR).");
1002
+ }
1003
+ readOptionalString(args, "git_dir", 1024, 1);
1004
+ readOptionalString(args, "subdir", 256);
1005
+ readOptionalBool(args, "offline");
1006
+ readOptionalEnum(args, "detail", ["summary", "card", "full"] as const, "summary");
1007
+ readOptionalEnum(args, "format", ["json", "card", "sarif", "sbom"] as const, "json");
1008
+ return;
1009
+ }
1010
+
1011
+ if (toolName === "resolve_safe_anchor") {
1012
+ assertAllowedKeys(args, ["package_name", "git_dir", "repo_url", "subdir", "window", "detail"], toolName);
1013
+ readRequiredString(args, "package_name", 1, 214);
1014
+ readOptionalString(args, "git_dir", 1024, 1);
1015
+ readOptionalString(args, "repo_url", 256, 1);
1016
+ readOptionalString(args, "subdir", 256);
1017
+ readOptionalInt(args, "window", 1, 200);
1018
+ readOptionalEnum(args, "detail", ["summary", "full"] as const, "summary");
1019
+ return;
1020
+ }
1021
+
1022
+ if (toolName === "verify_confusion") {
1023
+ assertAllowedKeys(args, ["manifest_path", "check_public"], toolName);
1024
+ readOptionalString(args, "manifest_path", 1024, 1);
1025
+ readOptionalBool(args, "check_public");
1026
+ return;
1027
+ }
1028
+
1029
+ if (toolName === "audit_verify") {
1030
+ assertAllowedKeys(args, ["audit_log_path"], toolName);
1031
+ readRequiredString(args, "audit_log_path", 1, 1024);
1032
+ return;
1033
+ }
1034
+
1035
+ if (toolName === "audit_manifest_batch") {
1036
+ assertAllowedKeys(args, ["manifest_path", "include_dev", "max_deps", "offline", "detail"], toolName);
1037
+ readOptionalString(args, "manifest_path", 1024, 1);
1038
+ readOptionalBool(args, "include_dev");
1039
+ readOptionalInt(args, "max_deps", 1, 50);
1040
+ readOptionalBool(args, "offline");
1041
+ readOptionalEnum(args, "detail", ["summary", "full"] as const, "summary");
1042
+ return;
1043
+ }
1044
+
1045
+ if (toolName === "get_artifact_report") {
1046
+ assertAllowedKeys(args, ["report_id", "section", "offset", "limit"], toolName);
1047
+ readRequiredString(args, "report_id", 4, 64);
1048
+ readOptionalEnum(
1049
+ args,
1050
+ "section",
1051
+ ["observations", "iocs", "unknowns", "commits", "card", "sarif", "sbom"] as const,
1052
+ "observations",
1053
+ );
1054
+ if (args["section"] === undefined) {
1055
+ throw new ParamValidationError("Missing required parameter 'section'.");
1056
+ }
1057
+ readOptionalInt(args, "offset", 0, 10_000_000);
1058
+ readOptionalInt(args, "limit", 1, 50);
1059
+ }
1060
+ }
1061
+
1062
+ private async executeTool(
1063
+ toolName: string,
1064
+ args: Record<string, unknown>,
1065
+ requestId: string,
1066
+ signal: AbortSignal,
1067
+ ): Promise<McpToolCallResult> {
1068
+ if (toolName === "get_artifact_report") {
1069
+ return this.executeGetArtifactReport(args);
1070
+ }
1071
+
1072
+ const ctx = await this.buildWorkflowContext(requestId, signal);
1073
+
1074
+ if (toolName === "discover_packages") {
1075
+ const detail = readOptionalEnum(args, "detail", ["summary", "full"] as const, "summary");
1076
+ const res = await runDiscover(ctx, {
1077
+ query: args["query"] as string,
1078
+ org: args["org"] as string | undefined,
1079
+ creator: args["creator"] as string | undefined,
1080
+ category: args["category"] as string | undefined,
1081
+ limit: (args["limit"] as number | undefined) ?? 10,
1082
+ });
1083
+ const reportId = this.reportStore.put({ kind: "discover", report: res.report });
1084
+ if (detail === "summary") {
1085
+ const { obj, text } = buildDiscoverSummary(res.report, reportId);
1086
+ return { content: [{ type: "text", text }], structuredContent: obj, isError: false };
1087
+ }
1088
+ const fullObj = { ...res.report, report_id: reportId };
1089
+ const fullText = JSON.stringify(fullObj);
1090
+ if (Buffer.byteLength(fullText, "utf8") > FULL_PAYLOAD_HARD_CAP_BYTES) {
1091
+ return buildResourceConstraintResult(reportId, "unknowns", Buffer.byteLength(fullText, "utf8"));
1092
+ }
1093
+ return { content: [{ type: "text", text: fullText }], structuredContent: fullObj, isError: false };
1094
+ }
1095
+
1096
+ if (toolName === "inspect_package_artifact") {
1097
+ const detail = readOptionalEnum(args, "detail", ["summary", "card", "full"] as const, "summary");
1098
+ const format = readOptionalEnum(args, "format", ["json", "card", "sarif", "sbom"] as const, "json");
1099
+ const res = await runInspect(ctx, {
1100
+ packageSpec: args["package_spec"] as string | undefined,
1101
+ tarballPath: args["tarball_path"] as string | undefined,
1102
+ localGitDir: args["git_dir"] as string | undefined,
1103
+ subdir: args["subdir"] as string | undefined,
1104
+ offline: args["offline"] as boolean | undefined,
1105
+ });
1106
+ if (!res.ok) {
1107
+ if (!res.isOperationalError) {
1108
+ const blockedPayload = {
1109
+ schema_version: "1",
1110
+ verdict: "MALICIOUS_INDICATORS_FOUND",
1111
+ recommended_action: "BLOCK_NO_SAFE_PATH",
1112
+ reason: res.error,
1113
+ };
1114
+ return {
1115
+ content: [{ type: "text", text: JSON.stringify(blockedPayload) }],
1116
+ structuredContent: blockedPayload,
1117
+ isError: false,
1118
+ };
1119
+ }
1120
+ return { content: [{ type: "text", text: res.error }], isError: true };
1121
+ }
1122
+
1123
+ const reportId = this.reportStore.put({
1124
+ kind: "inspect",
1125
+ report: res.report,
1126
+ dependencies: res.dependencies,
1127
+ });
1128
+
1129
+ if (format === "card" || detail === "card") {
1130
+ const card = formatInspectionMarkdownCard(res.report);
1131
+ const bytes = Buffer.byteLength(card, "utf8");
1132
+ if (bytes > FULL_PAYLOAD_HARD_CAP_BYTES) {
1133
+ return buildResourceConstraintResult(reportId, "card", bytes);
1134
+ }
1135
+ return {
1136
+ content: [{ type: "text", text: card }],
1137
+ structuredContent: {
1138
+ report_id: reportId,
1139
+ verdict: res.report.verdict,
1140
+ recommended_action: res.report.recommended_action,
1141
+ format: "card",
1142
+ },
1143
+ isError: false,
1144
+ };
1145
+ }
1146
+
1147
+ if (format === "sarif") {
1148
+ const sarifText = JSON.stringify(formatSarif210(res.report));
1149
+ const bytes = Buffer.byteLength(sarifText, "utf8");
1150
+ if (bytes > FULL_PAYLOAD_HARD_CAP_BYTES) {
1151
+ return buildResourceConstraintResult(reportId, "sarif", bytes);
1152
+ }
1153
+ return {
1154
+ content: [{ type: "text", text: sarifText }],
1155
+ structuredContent: { report_id: reportId, format: "sarif", bytes },
1156
+ isError: false,
1157
+ };
1158
+ }
1159
+
1160
+ if (format === "sbom") {
1161
+ const sbomText = JSON.stringify(formatCycloneDxSbom(res.report, res.dependencies));
1162
+ const bytes = Buffer.byteLength(sbomText, "utf8");
1163
+ if (bytes > FULL_PAYLOAD_HARD_CAP_BYTES) {
1164
+ return buildResourceConstraintResult(reportId, "sbom", bytes);
1165
+ }
1166
+ return {
1167
+ content: [{ type: "text", text: sbomText }],
1168
+ structuredContent: { report_id: reportId, format: "sbom", bytes },
1169
+ isError: false,
1170
+ };
1171
+ }
1172
+
1173
+ if (detail === "full") {
1174
+ const fullObj = { ...res.report, report_id: reportId };
1175
+ const fullText = JSON.stringify(fullObj);
1176
+ const bytes = Buffer.byteLength(fullText, "utf8");
1177
+ if (bytes > FULL_PAYLOAD_HARD_CAP_BYTES) {
1178
+ return buildResourceConstraintResult(reportId, "observations", bytes);
1179
+ }
1180
+ return { content: [{ type: "text", text: fullText }], structuredContent: fullObj, isError: false };
1181
+ }
1182
+
1183
+ const { obj, text } = buildInspectSummary(res.report, reportId);
1184
+ return { content: [{ type: "text", text }], structuredContent: obj, isError: false };
1185
+ }
1186
+
1187
+ if (toolName === "resolve_safe_anchor") {
1188
+ const detail = readOptionalEnum(args, "detail", ["summary", "full"] as const, "summary");
1189
+ const res = await runResolveAnchor(ctx, {
1190
+ packageName: args["package_name"] as string,
1191
+ localGitDir: args["git_dir"] as string | undefined,
1192
+ repoUrl: args["repo_url"] as string | undefined,
1193
+ subdir: args["subdir"] as string | undefined,
1194
+ window: args["window"] as number | undefined,
1195
+ });
1196
+ if (!res.ok) {
1197
+ if (!res.isOperationalError) {
1198
+ const blockedPayload = {
1199
+ schema_version: "1",
1200
+ recommended_action: "BLOCK_NO_SAFE_PATH",
1201
+ reason: res.error,
1202
+ };
1203
+ return {
1204
+ content: [{ type: "text", text: JSON.stringify(blockedPayload) }],
1205
+ structuredContent: blockedPayload,
1206
+ isError: false,
1207
+ };
1208
+ }
1209
+ return { content: [{ type: "text", text: res.error }], isError: true };
1210
+ }
1211
+
1212
+ const reportId = this.reportStore.put({ kind: "anchor", decision: res.decision });
1213
+ if (detail === "full") {
1214
+ const fullObj = { ...res.decision, report_id: reportId };
1215
+ const fullText = JSON.stringify(fullObj);
1216
+ const bytes = Buffer.byteLength(fullText, "utf8");
1217
+ if (bytes > FULL_PAYLOAD_HARD_CAP_BYTES) {
1218
+ return buildResourceConstraintResult(reportId, "commits", bytes);
1219
+ }
1220
+ return { content: [{ type: "text", text: fullText }], structuredContent: fullObj, isError: false };
1221
+ }
1222
+
1223
+ const { obj, text } = buildAnchorSummary(res.decision, reportId);
1224
+ return { content: [{ type: "text", text }], structuredContent: obj, isError: false };
1225
+ }
1226
+
1227
+ if (toolName === "verify_confusion") {
1228
+ const res = await runVerifyConfusion(ctx, {
1229
+ manifestPath: args["manifest_path"] as string | undefined,
1230
+ checkPublic: args["check_public"] as boolean | undefined,
1231
+ allowPublicProbe: this.operatorConfig.allowPublicConfusionProbe,
1232
+ });
1233
+ if (!res.ok) {
1234
+ return { content: [{ type: "text", text: res.error }], isError: true };
1235
+ }
1236
+ const payload = res.report as unknown as Record<string, unknown>;
1237
+ return {
1238
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1239
+ structuredContent: payload,
1240
+ isError: false,
1241
+ };
1242
+ }
1243
+
1244
+ if (toolName === "audit_verify") {
1245
+ const res = await runAuditVerify(ctx, {
1246
+ auditLogPath: args["audit_log_path"] as string,
1247
+ });
1248
+ if (!res.ok) {
1249
+ return { content: [{ type: "text", text: res.error }], isError: true };
1250
+ }
1251
+ // Valid OR tampered audit chains are deterministic security verdicts (isError: false)
1252
+ const payload = res.result as unknown as Record<string, unknown>;
1253
+ return {
1254
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1255
+ structuredContent: payload,
1256
+ isError: false,
1257
+ };
1258
+ }
1259
+
1260
+ if (toolName === "audit_manifest_batch") {
1261
+ const detail = readOptionalEnum(args, "detail", ["summary", "full"] as const, "summary");
1262
+ const res = await runAuditManifestBatch(ctx, {
1263
+ manifestPath: args["manifest_path"] as string | undefined,
1264
+ includeDev: args["include_dev"] as boolean | undefined,
1265
+ maxDeps: args["max_deps"] as number | undefined,
1266
+ offline: args["offline"] as boolean | undefined,
1267
+ });
1268
+ if (!res.ok) {
1269
+ return { content: [{ type: "text", text: res.error }], isError: true };
1270
+ }
1271
+ const reportId = this.reportStore.put({ kind: "batch", report: res.report });
1272
+ if (detail === "full") {
1273
+ const fullObj = { ...res.report, report_id: reportId };
1274
+ const fullText = JSON.stringify(fullObj);
1275
+ const bytes = Buffer.byteLength(fullText, "utf8");
1276
+ if (bytes > FULL_PAYLOAD_HARD_CAP_BYTES) {
1277
+ return buildResourceConstraintResult(reportId, "observations", bytes);
1278
+ }
1279
+ return { content: [{ type: "text", text: fullText }], structuredContent: fullObj, isError: false };
1280
+ }
1281
+ const { obj, text } = buildBatchSummary(res.report, reportId);
1282
+ return { content: [{ type: "text", text }], structuredContent: obj, isError: false };
1283
+ }
1284
+
1285
+ return { content: [{ type: "text", text: `Unhandled tool: ${toolName}` }], isError: true };
1286
+ }
1287
+
1288
+ private executeGetArtifactReport(args: Record<string, unknown>): McpToolCallResult {
1289
+ const reportId = args["report_id"] as string;
1290
+ const section = args["section"] as "observations" | "iocs" | "unknowns" | "commits" | "card" | "sarif" | "sbom";
1291
+ const offset = (args["offset"] as number | undefined) ?? 0;
1292
+ const limit = (args["limit"] as number | undefined) ?? 20;
1293
+
1294
+ const stored = this.reportStore.get(reportId);
1295
+ if (!stored) {
1296
+ return {
1297
+ content: [{ type: "text", text: `Report '${reportId}' not found or expired in session store.` }],
1298
+ isError: true,
1299
+ };
1300
+ }
1301
+
1302
+ if (section === "card" || section === "sarif" || section === "sbom") {
1303
+ if (stored.kind !== "inspect") {
1304
+ return {
1305
+ content: [{ type: "text", text: `Section '${section}' is only available for inspection reports.` }],
1306
+ isError: true,
1307
+ };
1308
+ }
1309
+ const fullText =
1310
+ section === "card"
1311
+ ? formatInspectionMarkdownCard(stored.report)
1312
+ : section === "sarif"
1313
+ ? JSON.stringify(formatSarif210(stored.report))
1314
+ : JSON.stringify(formatCycloneDxSbom(stored.report, stored.dependencies));
1315
+ const sliced = sliceUtf8Safe(fullText, offset, REPORT_TEXT_CHUNK_MAX_BYTES);
1316
+ const payload = { report_id: reportId, section, ...sliced };
1317
+ return {
1318
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1319
+ structuredContent: payload,
1320
+ isError: false,
1321
+ };
1322
+ }
1323
+
1324
+ let items: unknown[] = [];
1325
+ if (section === "observations") {
1326
+ if (stored.kind === "inspect") items = stored.report.evidence.flatMap((e) => e.observations);
1327
+ else if (stored.kind === "discover") items = stored.report.candidates;
1328
+ else if (stored.kind === "batch") items = stored.report.flagged;
1329
+ else items = stored.decision.evidence;
1330
+ } else if (section === "iocs") {
1331
+ items = stored.kind === "inspect" ? stored.report.iocs : [];
1332
+ } else if (section === "unknowns") {
1333
+ if (stored.kind === "inspect") items = stored.report.evidence.flatMap((e) => e.unknowns);
1334
+ else if (stored.kind === "discover") items = stored.report.unknowns;
1335
+ else if (stored.kind === "batch") items = stored.report.unknowns;
1336
+ else items = stored.decision.unknowns;
1337
+ } else if (section === "commits") {
1338
+ items = stored.kind === "anchor" ? stored.decision.inspected_commits : [];
1339
+ }
1340
+
1341
+ const slice = items.slice(offset, offset + limit);
1342
+ const nextOffset = offset + slice.length < items.length ? offset + slice.length : null;
1343
+ const payload = {
1344
+ report_id: reportId,
1345
+ section,
1346
+ offset,
1347
+ limit,
1348
+ total: items.length,
1349
+ next_offset: nextOffset,
1350
+ items: slice,
1351
+ };
1352
+ return {
1353
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1354
+ structuredContent: payload,
1355
+ isError: false,
1356
+ };
1357
+ }
1358
+ }
1359
+
1360
+ export async function startMcpServerFromEnv(env: NodeJS.ProcessEnv = process.env): Promise<number> {
1361
+ const server = new ColdpinMcpServer({
1362
+ operatorConfig: loadOperatorConfigFromEnv(env),
1363
+ hijackProcessStdio: true,
1364
+ });
1365
+
1366
+ const onSignal = (): void => {
1367
+ void server.shutdown().finally(() => {
1368
+ process.exit(0);
1369
+ });
1370
+ };
1371
+ process.once("SIGINT", onSignal);
1372
+ process.once("SIGTERM", onSignal);
1373
+
1374
+ return new Promise<number>((resolveExit) => {
1375
+ process.stdin.once("close", () => {
1376
+ void server.shutdown().finally(() => {
1377
+ process.off("SIGINT", onSignal);
1378
+ process.off("SIGTERM", onSignal);
1379
+ resolveExit(0);
1380
+ });
1381
+ });
1382
+ server.start();
1383
+ });
1384
+ }