nulladrift 0.2.0 → 0.3.1

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/index.js CHANGED
@@ -26,6 +26,7 @@ var CHANGE_KINDS = [
26
26
  "tool.behavior.escalated",
27
27
  "tool.behavior.relaxed",
28
28
  "tool.header_params.changed",
29
+ "tool.capability.gained",
29
30
  "tool.changed",
30
31
  "resource.added",
31
32
  "resource.removed",
@@ -58,6 +59,12 @@ var SEVERITY = {
58
59
  "tool.behavior.escalated": "high",
59
60
  "tool.behavior.relaxed": "low",
60
61
  "tool.header_params.changed": "high",
62
+ /*
63
+ * Severity is set per change rather than read from here: what a tool gained decides it. A
64
+ * `command` argument is not the same finding as a `url` one, and flattening both to one number
65
+ * is how "accepts input it did not before" came to describe arbitrary command execution.
66
+ */
67
+ "tool.capability.gained": "high",
61
68
  "tool.changed": "medium",
62
69
  "resource.added": "medium",
63
70
  "resource.removed": "low",
@@ -316,6 +323,125 @@ function sanitizeUrl(raw) {
316
323
  }
317
324
  }
318
325
 
326
+ // ../core/src/risk/untrusted.ts
327
+ function objectsIn(value) {
328
+ if (!Array.isArray(value)) return [];
329
+ return value.filter((member) => typeof member === "object" && member !== null);
330
+ }
331
+ function objectOr(value) {
332
+ return typeof value === "object" && value !== null ? value : {};
333
+ }
334
+ function stringOr(value) {
335
+ return typeof value === "string" ? value : void 0;
336
+ }
337
+
338
+ // ../core/src/risk/capability.ts
339
+ var CAPABILITY_SEVERITIES = ["critical", "high", "medium", "low"];
340
+ var CAPABILITY_KINDS = [
341
+ "process-exec",
342
+ "code-eval",
343
+ "credential-access",
344
+ "file-write",
345
+ "network-egress",
346
+ "database",
347
+ "privilege",
348
+ "agent-control",
349
+ "env-access",
350
+ "file-read"
351
+ ];
352
+ var RULES = [
353
+ { kind: "process-exec", severity: "critical", name: /(^|_)(exec|execute|spawn|shell|bash|sh|cmd|command|run_command|terminal|subprocess)(_|$)/, arg: /(^|_)(command|cmd|argv|shell|exec|script)(_|$)/ },
354
+ // `source` is deliberately absent: in `copy_file(source, destination)` it is a path, and
355
+ // labelling a file copy as arbitrary code execution at CRITICAL is the false positive that
356
+ // teaches people to stop reading the line. `code` has to be the whole argument name for the
357
+ // same reason -- a crawl of 468 published tools flagged `location_code` as arbitrary code
358
+ // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.
359
+ { kind: "code-eval", severity: "critical", name: /(^|_)(eval|evaluate|run_code|exec_code|interpret|compile)(_|$)/, arg: /^code$|(^|_)(source_code|code_to_run|js_code|python_code|expression|program|snippet)(_|$)/ },
360
+ { kind: "credential-access", severity: "critical", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },
361
+ { kind: "file-write", severity: "high", name: /(^|_)(write|create_file|put_file|save|delete|remove|unlink|rename|move|copy|chmod|mkdir|rmdir|edit)(_|$)/, arg: /(^|_)(contents|content|data|destination|dest_path|target_path)(_|$)/ },
362
+ { kind: "network-egress", severity: "high", name: /(^|_)(fetch|request|http|curl|download|upload|post|webhook|navigate|browse|send)(_|$)/, arg: /(^|_)(url|uri|endpoint|host|hostname|webhook|callback)(_|$)/ },
363
+ // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their
364
+ // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,
365
+ // none of which is a database.
366
+ { kind: "database", severity: "high", name: /(^|_)(sql|execute_sql|run_sql|query_db|db_query|migrate)(_|$)/, arg: /(^|_)(sql|statement|dsn|connection_string)(_|$)/ },
367
+ { kind: "privilege", severity: "high", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },
368
+ { kind: "agent-control", severity: "high", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },
369
+ { kind: "env-access", severity: "medium", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },
370
+ { kind: "file-read", severity: "low", name: /(^|_)(read|read_file|cat|open|load|list_directory|ls|glob|search_files)(_|$)/, arg: /(^|_)(path|file|filename|filepath|directory|dir)(_|$)/ }
371
+ ];
372
+ var CONFUSABLES = {
373
+ "\u0430": "a",
374
+ "\u0435": "e",
375
+ "\u043E": "o",
376
+ "\u0441": "c",
377
+ "\u0440": "p",
378
+ "\u0445": "x",
379
+ "\u0443": "y",
380
+ "\u0456": "i",
381
+ "\u0458": "j",
382
+ "\u04BB": "h",
383
+ "\u0501": "d",
384
+ "\u051B": "q",
385
+ "\u03BF": "o",
386
+ "\u03B1": "a",
387
+ "\u03B5": "e",
388
+ "\u03BD": "v",
389
+ "\u03C1": "p",
390
+ "\u03C5": "u",
391
+ "\u0131": "i",
392
+ "\u1E9E": "s"
393
+ };
394
+ var CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLES).join("")}]`, "g");
395
+ function normalize(identifier) {
396
+ return identifier.toLowerCase().replace(CONFUSABLE_PATTERN, (character) => CONFUSABLES[character] ?? character).replace(/[-.\s/]+/g, "_");
397
+ }
398
+ function argumentNames(inputSchema, depth = 0) {
399
+ if (depth > 6 || typeof inputSchema !== "object" || inputSchema === null) return [];
400
+ const node = inputSchema;
401
+ const names = [];
402
+ const properties = node.properties;
403
+ if (typeof properties === "object" && properties !== null) {
404
+ for (const [name, child] of Object.entries(properties)) {
405
+ names.push(name);
406
+ names.push(...argumentNames(child, depth + 1));
407
+ }
408
+ }
409
+ if (node.items !== void 0) names.push(...argumentNames(node.items, depth + 1));
410
+ return names;
411
+ }
412
+ function toolCapabilities(tool2) {
413
+ const subject = objectOr(tool2);
414
+ const name = normalize(stringOr(subject.name) ?? "");
415
+ const args = argumentNames(subject.inputSchema).map((argument) => [argument, normalize(argument)]);
416
+ const found = /* @__PURE__ */ new Map();
417
+ for (const rule of RULES) {
418
+ if (found.has(rule.kind)) continue;
419
+ if (rule.name?.test(name)) {
420
+ found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: "name" });
421
+ continue;
422
+ }
423
+ const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : void 0;
424
+ if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });
425
+ }
426
+ return [...found.values()].sort(
427
+ (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
428
+ );
429
+ }
430
+ function surfaceCapabilities(tools) {
431
+ const byKind = /* @__PURE__ */ new Map();
432
+ for (const tool2 of objectsIn(tools)) {
433
+ const label = stringOr(tool2.name) ?? "?";
434
+ for (const capability of toolCapabilities(tool2)) {
435
+ const existing = byKind.get(capability.kind);
436
+ if (existing) existing.tools.push(label);
437
+ else byKind.set(capability.kind, { ...capability, tools: [label] });
438
+ }
439
+ }
440
+ return [...byKind.values()].sort(
441
+ (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
442
+ );
443
+ }
444
+
319
445
  // ../core/src/diff/schema.ts
320
446
  function numberAt(node, key) {
321
447
  const value = node[key];
@@ -460,6 +586,32 @@ function compareCapabilities(before, after, name) {
460
586
  }
461
587
  return [change("server.capabilities.changed", name, "declared capabilities changed", { before: before.capabilities, after: after.capabilities })];
462
588
  }
589
+ var CAPABILITY_SEVERITY = {
590
+ critical: "high",
591
+ high: "high",
592
+ medium: "medium",
593
+ low: "low"
594
+ };
595
+ function compareToolCapabilities(server2, before, after) {
596
+ const previous = indexBy(before, (tool2) => tool2.name);
597
+ const changes = [];
598
+ for (const tool2 of after ?? []) {
599
+ const existing = previous.get(tool2.name);
600
+ if (!existing) continue;
601
+ const had = new Set(toolCapabilities(existing).map((capability) => capability.kind));
602
+ for (const capability of toolCapabilities(tool2)) {
603
+ if (had.has(capability.kind)) continue;
604
+ changes.push(
605
+ change("tool.capability.gained", server2, `can now ${capability.kind} (${capability.evidence})`, {
606
+ member: tool2.name,
607
+ severity: CAPABILITY_SEVERITY[capability.severity],
608
+ after: { kind: capability.kind, severity: capability.severity, evidence: capability.evidence }
609
+ })
610
+ );
611
+ }
612
+ }
613
+ return changes;
614
+ }
463
615
  function compareTool(name, before, after) {
464
616
  if (before.digest === after.digest) return [];
465
617
  const changes = [];
@@ -517,7 +669,10 @@ function compareMembers(name, before, after, spec, deep) {
517
669
  for (const [key, member] of next) {
518
670
  const existing = previous.get(key);
519
671
  if (!existing) {
520
- changes.push(change(spec.added, name, `new ${spec.noun} ${spec.label(member)}`, { member: spec.label(member), after: member }));
672
+ const extra = spec.arriving?.(member);
673
+ changes.push(
674
+ change(spec.added, name, `new ${spec.noun} ${spec.label(member)}${extra ? ` \xB7 ${extra}` : ""}`, { member: spec.label(member), after: member })
675
+ );
521
676
  continue;
522
677
  }
523
678
  if (existing.digest === member.digest) continue;
@@ -561,10 +716,22 @@ function compareServer(name, before, after) {
561
716
  name,
562
717
  before.tools,
563
718
  after.tools,
564
- { key: (t) => t.name, label: (t) => t.name, added: "tool.added", removed: "tool.removed", changed: "tool.changed", noun: "tool" },
719
+ {
720
+ key: (t) => t.name,
721
+ label: (t) => t.name,
722
+ added: "tool.added",
723
+ removed: "tool.removed",
724
+ changed: "tool.changed",
725
+ noun: "tool",
726
+ arriving: (t) => {
727
+ const can = toolCapabilities(t);
728
+ return can.length > 0 ? `can ${can.map((capability) => capability.kind).join(", ")}` : "";
729
+ }
730
+ },
565
731
  (_key, a, b) => compareTool(name, a, b)
566
732
  )
567
733
  );
734
+ changes.push(...compareToolCapabilities(name, before.tools, after.tools));
568
735
  changes.push(
569
736
  ...compareMembers(name, before.resources, after.resources, {
570
737
  key: (r) => r.uri,
@@ -644,99 +811,6 @@ function diffLockfiles(before, after) {
644
811
  return sortChanges(changes);
645
812
  }
646
813
 
647
- // ../core/src/risk/capability.ts
648
- var CAPABILITY_SEVERITIES = ["critical", "high", "medium", "low"];
649
- var RULES = [
650
- { kind: "process-exec", severity: "critical", name: /(^|_)(exec|execute|spawn|shell|bash|sh|cmd|command|run_command|terminal|subprocess)(_|$)/, arg: /(^|_)(command|cmd|argv|shell|exec|script)(_|$)/ },
651
- // `source` is deliberately absent: in `copy_file(source, destination)` it is a path, and
652
- // labelling a file copy as arbitrary code execution at CRITICAL is the false positive that
653
- // teaches people to stop reading the line. `code` has to be the whole argument name for the
654
- // same reason -- a crawl of 468 published tools flagged `location_code` as arbitrary code
655
- // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.
656
- { kind: "code-eval", severity: "critical", name: /(^|_)(eval|evaluate|run_code|exec_code|interpret|compile)(_|$)/, arg: /^code$|(^|_)(source_code|code_to_run|js_code|python_code|expression|program|snippet)(_|$)/ },
657
- { kind: "credential-access", severity: "critical", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },
658
- { kind: "file-write", severity: "high", name: /(^|_)(write|create_file|put_file|save|delete|remove|unlink|rename|move|copy|chmod|mkdir|rmdir|edit)(_|$)/, arg: /(^|_)(contents|content|data|destination|dest_path|target_path)(_|$)/ },
659
- { kind: "network-egress", severity: "high", name: /(^|_)(fetch|request|http|curl|download|upload|post|webhook|navigate|browse|send)(_|$)/, arg: /(^|_)(url|uri|endpoint|host|hostname|webhook|callback)(_|$)/ },
660
- // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their
661
- // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,
662
- // none of which is a database.
663
- { kind: "database", severity: "high", name: /(^|_)(sql|execute_sql|run_sql|query_db|db_query|migrate)(_|$)/, arg: /(^|_)(sql|statement|dsn|connection_string)(_|$)/ },
664
- { kind: "privilege", severity: "high", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },
665
- { kind: "agent-control", severity: "high", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },
666
- { kind: "env-access", severity: "medium", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },
667
- { kind: "file-read", severity: "low", name: /(^|_)(read|read_file|cat|open|load|list_directory|ls|glob|search_files)(_|$)/, arg: /(^|_)(path|file|filename|filepath|directory|dir)(_|$)/ }
668
- ];
669
- var CONFUSABLES = {
670
- "\u0430": "a",
671
- "\u0435": "e",
672
- "\u043E": "o",
673
- "\u0441": "c",
674
- "\u0440": "p",
675
- "\u0445": "x",
676
- "\u0443": "y",
677
- "\u0456": "i",
678
- "\u0458": "j",
679
- "\u04BB": "h",
680
- "\u0501": "d",
681
- "\u051B": "q",
682
- "\u03BF": "o",
683
- "\u03B1": "a",
684
- "\u03B5": "e",
685
- "\u03BD": "v",
686
- "\u03C1": "p",
687
- "\u03C5": "u",
688
- "\u0131": "i",
689
- "\u1E9E": "s"
690
- };
691
- var CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLES).join("")}]`, "g");
692
- function normalize(identifier) {
693
- return identifier.toLowerCase().replace(CONFUSABLE_PATTERN, (character) => CONFUSABLES[character] ?? character).replace(/[-.\s/]+/g, "_");
694
- }
695
- function argumentNames(inputSchema, depth = 0) {
696
- if (depth > 6 || typeof inputSchema !== "object" || inputSchema === null) return [];
697
- const node = inputSchema;
698
- const names = [];
699
- const properties = node.properties;
700
- if (typeof properties === "object" && properties !== null) {
701
- for (const [name, child] of Object.entries(properties)) {
702
- names.push(name);
703
- names.push(...argumentNames(child, depth + 1));
704
- }
705
- }
706
- if (node.items !== void 0) names.push(...argumentNames(node.items, depth + 1));
707
- return names;
708
- }
709
- function toolCapabilities(tool2) {
710
- const name = normalize(tool2.name ?? "");
711
- const args = argumentNames(tool2.inputSchema).map((argument) => [argument, normalize(argument)]);
712
- const found = /* @__PURE__ */ new Map();
713
- for (const rule of RULES) {
714
- if (found.has(rule.kind)) continue;
715
- if (rule.name?.test(name)) {
716
- found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: "name" });
717
- continue;
718
- }
719
- const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : void 0;
720
- if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });
721
- }
722
- return [...found.values()].sort(
723
- (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
724
- );
725
- }
726
- function surfaceCapabilities(tools) {
727
- const byKind = /* @__PURE__ */ new Map();
728
- for (const tool2 of tools) {
729
- for (const capability of toolCapabilities(tool2)) {
730
- const existing = byKind.get(capability.kind);
731
- if (existing) existing.tools.push(tool2.name ?? "?");
732
- else byKind.set(capability.kind, { ...capability, tools: [tool2.name ?? "?"] });
733
- }
734
- }
735
- return [...byKind.values()].sort(
736
- (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
737
- );
738
- }
739
-
740
814
  // ../core/src/risk/steering.ts
741
815
  var PATTERNS = [
742
816
  // Imperatives aimed at the reader of the prompt, not at a person reading documentation.
@@ -790,6 +864,22 @@ function steeringSignals(text, field) {
790
864
  return found;
791
865
  }
792
866
 
867
+ // ../core/src/risk/policy.ts
868
+ function capabilityViolations(lock, denied) {
869
+ if (!denied || denied.length === 0) return [];
870
+ const forbidden = new Set(denied);
871
+ const found = [];
872
+ for (const [server2, subject] of Object.entries(lock?.subjects ?? {})) {
873
+ for (const tool2 of objectsIn(objectOr(subject).tools)) {
874
+ for (const capability of toolCapabilities(tool2)) {
875
+ if (!forbidden.has(capability.kind)) continue;
876
+ found.push({ server: server2, tool: stringOr(tool2.name) ?? "?", kind: capability.kind, severity: capability.severity, evidence: capability.evidence });
877
+ }
878
+ }
879
+ }
880
+ return found.sort((a, b) => a.server.localeCompare(b.server) || a.tool.localeCompare(b.tool) || a.kind.localeCompare(b.kind));
881
+ }
882
+
793
883
  // ../core/src/risk/surface-text.ts
794
884
  var MAX_NODES = 2e4;
795
885
  function schemaText(root, rootPath, out) {
@@ -818,29 +908,29 @@ function surfaceText(subject) {
818
908
  const push = (field, text) => {
819
909
  if (typeof text === "string" && text.length > 0) out.push({ field, text });
820
910
  };
821
- push("instructions", subject.instructions);
822
- for (const tool2 of subject.tools ?? []) {
823
- const where = tool2.name ?? "?";
911
+ push("instructions", subject?.instructions);
912
+ for (const tool2 of objectsIn(subject?.tools)) {
913
+ const where = stringOr(tool2.name) ?? "?";
824
914
  push(`${where}.title`, tool2.title);
825
915
  push(`${where}.description`, tool2.description);
826
916
  schemaText(tool2.inputSchema, `${where}.inputSchema`, out);
827
917
  schemaText(tool2.outputSchema, `${where}.outputSchema`, out);
828
918
  }
829
- for (const prompt2 of subject.prompts ?? []) {
830
- const where = prompt2.name ?? "?";
919
+ for (const prompt2 of objectsIn(subject?.prompts)) {
920
+ const where = stringOr(prompt2.name) ?? "?";
831
921
  push(`prompt:${where}.title`, prompt2.title);
832
922
  push(`prompt:${where}.description`, prompt2.description);
833
- for (const argument of prompt2.arguments ?? []) {
834
- push(`prompt:${where}.${argument.name ?? "?"}`, argument.description);
923
+ for (const argument of objectsIn(prompt2.arguments)) {
924
+ push(`prompt:${where}.${stringOr(argument.name) ?? "?"}`, argument.description);
835
925
  }
836
926
  }
837
- for (const resource2 of subject.resources ?? []) {
838
- const where = resource2.name ?? resource2.uri ?? "?";
927
+ for (const resource2 of objectsIn(subject?.resources)) {
928
+ const where = stringOr(resource2.name) ?? stringOr(resource2.uri) ?? "?";
839
929
  push(`resource:${where}.title`, resource2.title);
840
930
  push(`resource:${where}.description`, resource2.description);
841
931
  }
842
- for (const template of subject.resourceTemplates ?? []) {
843
- const where = template.name ?? template.uriTemplate ?? "?";
932
+ for (const template of objectsIn(subject?.resourceTemplates)) {
933
+ const where = stringOr(template.name) ?? stringOr(template.uriTemplate) ?? "?";
844
934
  push(`template:${where}.title`, template.title);
845
935
  push(`template:${where}.description`, template.description);
846
936
  }
@@ -1355,7 +1445,7 @@ import { dirname, join as join2 } from "path";
1355
1445
  import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
1356
1446
 
1357
1447
  // src/lib/version.ts
1358
- var VERSION = "0.2.0";
1448
+ var VERSION = "0.3.1";
1359
1449
  var USER_AGENT = `nulladrift/${VERSION}`;
1360
1450
 
1361
1451
  // src/mcp/oauth.ts
@@ -1886,7 +1976,13 @@ var lockfileSchema = z2.object({
1886
1976
  generatedBy: z2.string().optional(),
1887
1977
  policy: z2.object({
1888
1978
  ignoreMetaPrefixes: z2.array(z2.string()).optional(),
1889
- allowUnreachable: z2.boolean().optional()
1979
+ allowUnreachable: z2.boolean().optional(),
1980
+ /*
1981
+ * Validated against the real list rather than accepted as free strings: a policy with
1982
+ * `process_exec` in it would otherwise parse, forbid nothing, and read in the diff of
1983
+ * whoever added it as though the rule were in force.
1984
+ */
1985
+ deniedCapabilities: z2.array(z2.enum(CAPABILITY_KINDS)).optional()
1890
1986
  }).optional(),
1891
1987
  /*
1892
1988
  * One map for everything pinned, each entry saying what it is. `z.discriminatedUnion` on a
@@ -1900,7 +1996,7 @@ var lockfileSchema = z2.object({
1900
1996
  var DEFAULT_LOCK_FILENAME = "mcp.lock";
1901
1997
  var KEY_ORDER = {
1902
1998
  root: ["lockfileVersion", "generatedBy", "policy", "subjects"],
1903
- policy: ["ignoreMetaPrefixes", "allowUnreachable"],
1999
+ policy: ["ignoreMetaPrefixes", "allowUnreachable", "deniedCapabilities"],
1904
2000
  server: ["kind", "source", "transport", "protocol", "serverInfo", "capabilities", "instructions", "tools", "resources", "resourceTemplates", "prompts", "digest"],
1905
2001
  source: ["client", "file", "scope"],
1906
2002
  transport: ["type", "command", "args", "envKeys", "cwd", "url", "headerKeys"],
@@ -2116,8 +2212,27 @@ function renderSteering(report) {
2116
2212
  lines.push("", dim("This did not change the verdict. Read the passages and decide; a server documenting"), dim('"before using this tool, call authenticate first" has the same shape as an attack.'), "");
2117
2213
  return lines;
2118
2214
  }
2215
+ function renderViolations(report) {
2216
+ const found = report.violations ?? [];
2217
+ if (found.length === 0) return [];
2218
+ const lines = ["", bold(red(`${found.length} capability(ies) this project does not permit:`)), ""];
2219
+ for (const violation of found) {
2220
+ lines.push(
2221
+ ` ${red("denied")} ${bold(`${violation.server} \u203A ${violation.tool}`)} ${dim(violation.kind)}`,
2222
+ ` ${violation.severity} \xB7 ${violation.evidence}`
2223
+ );
2224
+ }
2225
+ lines.push(
2226
+ "",
2227
+ dim("Set by `policy.deniedCapabilities` in the lockfile. Accepting the change does not clear"),
2228
+ dim("this; remove the capability, or change the policy deliberately."),
2229
+ ""
2230
+ );
2231
+ return lines;
2232
+ }
2119
2233
  function renderHumanReport(report) {
2120
2234
  const lines = [];
2235
+ lines.push(...renderViolations(report));
2121
2236
  if (report.changes.length > 0) {
2122
2237
  const drifted = new Set(report.changes.map((change2) => change2.server)).size;
2123
2238
  const heading = drifted > report.serversChecked ? `Drift in ${drifted} server(s); ${report.serversChecked} still configured:` : `Drift in ${drifted} of ${report.serversChecked} server(s):`;
@@ -2140,7 +2255,7 @@ function renderHumanReport(report) {
2140
2255
  }
2141
2256
  }
2142
2257
  lines.push(...renderSteering(report));
2143
- if (report.changes.length === 0 && report.unreachable.length === 0) {
2258
+ if (report.changes.length === 0 && report.unreachable.length === 0 && (report.violations ?? []).length === 0) {
2144
2259
  lines.push(green(`\u2713 ${report.serversChecked} server(s) match ${report.lockPath}`));
2145
2260
  return `${lines.join("\n")}
2146
2261
  `;
@@ -2190,7 +2305,9 @@ function renderJsonReport(report, exitCode) {
2190
2305
  * Counted separately from `changes` because it is not part of the verdict. A consumer
2191
2306
  * that gates on this field is gating on a regex, which is the thing this must never be.
2192
2307
  */
2193
- steering: (report.steering ?? []).reduce((sum, server2) => sum + server2.signals.length, 0)
2308
+ steering: (report.steering ?? []).reduce((sum, server2) => sum + server2.signals.length, 0),
2309
+ /** Unlike steering, these DO decide the exit code. */
2310
+ violations: (report.violations ?? []).length
2194
2311
  },
2195
2312
  changes: report.changes.map((change2) => ({
2196
2313
  kind: change2.kind,
@@ -2203,7 +2320,8 @@ function renderJsonReport(report, exitCode) {
2203
2320
  })),
2204
2321
  unreachable: report.unreachable,
2205
2322
  /** Text that began addressing the model since the lock was approved. Reported, never gated. */
2206
- steering: report.steering ?? []
2323
+ steering: report.steering ?? [],
2324
+ violations: report.violations ?? []
2207
2325
  },
2208
2326
  null,
2209
2327
  2
@@ -2237,7 +2355,10 @@ var LEVEL = {
2237
2355
  medium: "warning",
2238
2356
  low: "note"
2239
2357
  };
2358
+ var DENIED_RULE = "policy.capability.denied";
2359
+ var STEERING_RULE = "steering.passage.arrived";
2240
2360
  var RULE_HELP = {
2361
+ "tool.capability.gained": "A tool gained a capability it did not declare before, derived from its name, its argument names and the shape of its schema. The severity is the capability's, not the schema change's: gaining a `command` argument is not the same finding as gaining an optional string.",
2241
2362
  "tool.description.changed": "A tool description is injected into the model's context. A change here can carry instructions to the agent and should be read in full, not skimmed.",
2242
2363
  "server.instructions.changed": "The server's instructions string is placed in the model's system prompt by the client. Treat a change the way you would treat a change to prompt source.",
2243
2364
  "tool.behavior.escalated": "The tool now claims a power it did not claim when it was pinned. Annotation defaults are not neutral: removing readOnlyHint is an escalation.",
@@ -2255,8 +2376,32 @@ function sarifUri(report) {
2255
2376
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) return report.lockPath;
2256
2377
  return rel.split(sep2).join("/");
2257
2378
  }
2258
- function renderSarifReport(report) {
2379
+ function renderSarifReport(report, options = {}) {
2259
2380
  const used = [...new Set(report.changes.map((change2) => change2.kind))].sort();
2381
+ const violations = report.violations ?? [];
2382
+ const steering = options.steering ? report.steering ?? [] : [];
2383
+ const at = (name, qualified) => [
2384
+ {
2385
+ physicalLocation: { artifactLocation: { uri: sarifUri(report), uriBaseId: "%SRCROOT%" } },
2386
+ logicalLocations: [{ name, fullyQualifiedName: qualified, kind: "member" }]
2387
+ }
2388
+ ];
2389
+ const extraRules = [
2390
+ ...violations.length > 0 ? [{
2391
+ id: DENIED_RULE,
2392
+ name: "PolicyCapabilityDenied",
2393
+ shortDescription: { text: "A capability this project does not permit" },
2394
+ fullDescription: { text: "A pinned tool has a capability listed in policy.deniedCapabilities. Derived from the shape of the declaration, and not cleared by accepting the change." },
2395
+ defaultConfiguration: { level: "error" }
2396
+ }] : [],
2397
+ ...steering.length > 0 ? [{
2398
+ id: STEERING_RULE,
2399
+ name: "SteeringPassageArrived",
2400
+ shortDescription: { text: "Text that began addressing the model" },
2401
+ fullDescription: { text: "A passage a model is shown started reading as an instruction since this lock was approved. A signal to read, not a verdict: legitimate servers trip the same shape. It does not affect the exit code." },
2402
+ defaultConfiguration: { level: "note" }
2403
+ }] : []
2404
+ ];
2260
2405
  const document = {
2261
2406
  $schema: "https://json.schemastore.org/sarif-2.1.0.json",
2262
2407
  version: "2.1.0",
@@ -2267,28 +2412,44 @@ function renderSarifReport(report) {
2267
2412
  name: "nulladrift",
2268
2413
  version: VERSION,
2269
2414
  ...publishedDocsUrl() === void 0 ? {} : { informationUri: publishedDocsUrl() },
2270
- rules: (used.length > 0 ? used : CHANGE_KINDS.slice(0, 0)).map((kind) => ({
2271
- id: kind,
2272
- name: kind.split(/[._]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""),
2273
- shortDescription: { text: `MCP capability drift: ${kind}` },
2274
- fullDescription: { text: RULE_HELP[kind] ?? "The pinned MCP capability surface no longer matches what the server reports." },
2275
- defaultConfiguration: { level: LEVEL[SEVERITY[kind]] },
2276
- ...helpUriFor("6-change-taxonomy") === void 0 ? {} : { helpUri: helpUriFor("6-change-taxonomy") }
2277
- }))
2415
+ rules: [
2416
+ ...(used.length > 0 ? used : CHANGE_KINDS.slice(0, 0)).map((kind) => ({
2417
+ id: kind,
2418
+ name: kind.split(/[._]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""),
2419
+ shortDescription: { text: `MCP capability drift: ${kind}` },
2420
+ fullDescription: { text: RULE_HELP[kind] ?? "The pinned MCP capability surface no longer matches what the server reports." },
2421
+ defaultConfiguration: { level: LEVEL[SEVERITY[kind]] },
2422
+ ...helpUriFor("6-change-taxonomy") === void 0 ? {} : { helpUri: helpUriFor("6-change-taxonomy") }
2423
+ })),
2424
+ ...extraRules
2425
+ ]
2278
2426
  }
2279
2427
  },
2280
- results: report.changes.map((change2) => ({
2281
- ruleId: change2.kind,
2282
- level: LEVEL[change2.severity],
2283
- message: { text: change2.member ? `${change2.server} \u203A ${change2.member}: ${change2.summary}` : `${change2.server}: ${change2.summary}` },
2284
- locations: [
2285
- {
2286
- physicalLocation: { artifactLocation: { uri: sarifUri(report), uriBaseId: "%SRCROOT%" } },
2287
- logicalLocations: [{ name: change2.member ?? change2.server, fullyQualifiedName: change2.member ? `${change2.server}/${change2.member}` : change2.server, kind: "member" }]
2288
- }
2289
- ],
2290
- partialFingerprints: { "mcpAuditChange/v1": fingerprint(change2) }
2291
- }))
2428
+ results: [
2429
+ ...report.changes.map((change2) => ({
2430
+ ruleId: change2.kind,
2431
+ level: LEVEL[change2.severity],
2432
+ message: { text: change2.member ? `${change2.server} \u203A ${change2.member}: ${change2.summary}` : `${change2.server}: ${change2.summary}` },
2433
+ locations: at(change2.member ?? change2.server, change2.member ? `${change2.server}/${change2.member}` : change2.server),
2434
+ partialFingerprints: { "mcpAuditChange/v1": fingerprint(change2) }
2435
+ })),
2436
+ ...violations.map((violation) => ({
2437
+ ruleId: DENIED_RULE,
2438
+ level: "error",
2439
+ message: { text: `${violation.server} \u203A ${violation.tool}: ${violation.kind} is not permitted here (${violation.evidence})` },
2440
+ locations: at(violation.tool, `${violation.server}/${violation.tool}`),
2441
+ partialFingerprints: { "mcpAuditChange/v1": `${violation.server}/${violation.tool}/${violation.kind}` }
2442
+ })),
2443
+ ...steering.flatMap(
2444
+ ({ server: server2, signals }) => signals.map((signal) => ({
2445
+ ruleId: STEERING_RULE,
2446
+ level: "note",
2447
+ message: { text: `${server2} \u203A ${signal.field}: ${signal.quote}` },
2448
+ locations: at(signal.field, `${server2}/${signal.field}`),
2449
+ partialFingerprints: { "mcpAuditChange/v1": `${server2}/${signal.field}/${signal.kind}` }
2450
+ }))
2451
+ )
2452
+ ]
2292
2453
  }
2293
2454
  ]
2294
2455
  };
@@ -2530,6 +2691,11 @@ async function buildReport(options) {
2530
2691
  * first" must not be able to fail somebody's build.
2531
2692
  */
2532
2693
  steering: newSteering(committed, result.lock),
2694
+ /*
2695
+ * Against the freshly read surface, not the diff. A rule saying nothing here may execute
2696
+ * processes has to fail on the day it is added, not on the next day a server happens to move.
2697
+ */
2698
+ violations: capabilityViolations(result.lock, committed.policy?.deniedCapabilities),
2533
2699
  unreachable: result.unreachable,
2534
2700
  serversChecked: Object.keys(result.lock.subjects).length,
2535
2701
  lockPath: options.lockPath,
@@ -2538,7 +2704,12 @@ async function buildReport(options) {
2538
2704
  return {
2539
2705
  report,
2540
2706
  exitCode: resolveExitCode({
2541
- driftCount: changes.length,
2707
+ /*
2708
+ * A forbidden capability fails the build like drift does. It is not drift -- nothing moved
2709
+ * -- but the surface is not one the project permits, and `review --accept-all` must not be
2710
+ * able to make it pass: policy is the thing acceptance cannot overrule.
2711
+ */
2712
+ driftCount: changes.length + (report.violations?.length ?? 0),
2542
2713
  incompleteCount: allowUnreachable ? 0 : result.unreachable.length
2543
2714
  })
2544
2715
  };
@@ -2546,7 +2717,7 @@ async function buildReport(options) {
2546
2717
  async function runCheck(options) {
2547
2718
  const { report, exitCode } = await buildReport(options);
2548
2719
  if (options.format === "json") process.stdout.write(renderJsonReport(report, exitCode));
2549
- else if (options.format === "sarif") process.stdout.write(renderSarifReport(report));
2720
+ else if (options.format === "sarif") process.stdout.write(renderSarifReport(report, { steering: options.sarifSteering }));
2550
2721
  else process.stdout.write(renderHumanReport(report));
2551
2722
  await reportIfChanged(report, report.changes);
2552
2723
  if (options.comment) await comment(report);
@@ -3039,6 +3210,30 @@ ${dim(`Looked in: ${looked}`)}
3039
3210
 
3040
3211
  // src/commands/review.ts
3041
3212
  import { createInterface as createInterface2 } from "readline/promises";
3213
+ function describeSurface(subject, previous) {
3214
+ if (typeof subject !== "object" || subject === null) return [];
3215
+ const entry = subject;
3216
+ const lines = [];
3217
+ const capabilities = surfaceCapabilities(entry.tools);
3218
+ if (capabilities.length > 0) {
3219
+ const worst = capabilities.some((c) => c.severity === "critical" || c.severity === "high");
3220
+ const text = ` after accepting, this server can: ${capabilities.map((c) => c.kind).join(", ")}`;
3221
+ lines.push(worst ? yellow(text) : dim(text));
3222
+ }
3223
+ const had = new Set(
3224
+ (typeof previous === "object" && previous !== null ? surfaceText(previous).flatMap((piece) => steeringSignals(piece.text, piece.field)) : []).map((signal) => `${signal.field}\0${signal.kind}\0${signal.quote}`)
3225
+ );
3226
+ const steering = surfaceText(entry).flatMap((piece) => steeringSignals(piece.text, piece.field)).filter((signal) => !had.has(`${signal.field}\0${signal.kind}\0${signal.quote}`));
3227
+ if (steering.length > 0) {
3228
+ lines.push(yellow(` ${steering.length} new passage(s) here read as instructions to the model:`));
3229
+ const byField = /* @__PURE__ */ new Map();
3230
+ for (const signal of steering) if (!byField.has(signal.field)) byField.set(signal.field, signal.quote);
3231
+ for (const [field, quote] of [...byField].slice(0, 3)) {
3232
+ lines.push(dim(` ${elideMiddle(field, 52)}: ${truncate(quote, 72)}`));
3233
+ }
3234
+ }
3235
+ return lines;
3236
+ }
3042
3237
  function describe(change2) {
3043
3238
  const head = ` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${change2.member ? `${bold(change2.member)}: ` : ""}${change2.summary} ${dim(change2.kind)}`;
3044
3239
  if (change2.kind !== "tool.description.changed" && change2.kind !== "server.instructions.changed") return head;
@@ -3082,10 +3277,14 @@ async function runReview(options) {
3082
3277
  let declined = 0;
3083
3278
  try {
3084
3279
  for (const [serverName, serverChanges] of grouped) {
3085
- process.stdout.write(`
3280
+ const context = describeSurface(result.lock.subjects[serverName], committed.subjects[serverName]);
3281
+ process.stdout.write(
3282
+ `
3086
3283
  ${bold(serverName)}
3087
3284
  ${serverChanges.map(describe).join("\n")}
3088
- `);
3285
+ ${context.length > 0 ? `${context.join("\n")}
3286
+ ` : ""}`
3287
+ );
3089
3288
  let take = options.acceptAll;
3090
3289
  if (readline) {
3091
3290
  const answer = (await readline.question(`
@@ -3139,6 +3338,7 @@ ${bold("Options")}
3139
3338
  --allow-unreachable a server that cannot be reached warns instead of failing
3140
3339
  --json machine-readable output (check)
3141
3340
  --sarif SARIF 2.1.0 output (check)
3341
+ --sarif-steering also emit steering passages as SARIF notes (off: an alert is a gate)
3142
3342
  --accept-all accept every change without prompting (review)
3143
3343
  --force re-pin over an existing lockfile, discarding it (init)
3144
3344
  --api <url> control plane to push to (push; or NULLADRIFT_API_URL)
@@ -3167,6 +3367,7 @@ async function main() {
3167
3367
  "allow-unreachable": { type: "boolean", default: false },
3168
3368
  json: { type: "boolean", default: false },
3169
3369
  sarif: { type: "boolean", default: false },
3370
+ "sarif-steering": { type: "boolean", default: false },
3170
3371
  "accept-all": { type: "boolean", default: false },
3171
3372
  force: { type: "boolean", default: false },
3172
3373
  api: { type: "string" },
@@ -3208,6 +3409,7 @@ async function main() {
3208
3409
  timeoutMs,
3209
3410
  allowUnreachable: values["allow-unreachable"],
3210
3411
  format: values.sarif ? "sarif" : values.json ? "json" : "human",
3412
+ sarifSteering: values["sarif-steering"] === true,
3211
3413
  comment: values.comment
3212
3414
  };
3213
3415
  switch (command) {