saktum 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +49 -4
  2. package/package.json +1 -1
  3. package/saktum.mjs +1563 -586
package/saktum.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Saktum Check 0.1.4 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
2
+ // Saktum Check 0.3.0 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
3
3
  import { createRequire as __saktumCreateRequire } from "node:module";
4
4
  const require = __saktumCreateRequire(import.meta.url);
5
5
  var __create = Object.create;
@@ -14,6 +14,14 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
14
14
  if (typeof require !== "undefined") return require.apply(this, arguments);
15
15
  throw Error('Dynamic require of "' + x + '" is not supported');
16
16
  });
17
+ var __esm = (fn, res, err) => function __init() {
18
+ if (err) throw err[0];
19
+ try {
20
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
21
+ } catch (e) {
22
+ throw err = [e], e;
23
+ }
24
+ };
17
25
  var __commonJS = (cb, mod) => function __require2() {
18
26
  try {
19
27
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
@@ -3495,7 +3503,7 @@ var require_anchors = __commonJS({
3495
3503
  var require_applyReviver = __commonJS({
3496
3504
  "node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/dist/doc/applyReviver.js"(exports) {
3497
3505
  "use strict";
3498
- function applyReviver(reviver, obj, key, val) {
3506
+ function applyReviver(reviver, obj2, key, val) {
3499
3507
  if (val && typeof val === "object") {
3500
3508
  if (Array.isArray(val)) {
3501
3509
  for (let i = 0, len = val.length; i < len; ++i) {
@@ -3535,7 +3543,7 @@ var require_applyReviver = __commonJS({
3535
3543
  }
3536
3544
  }
3537
3545
  }
3538
- return reviver.call(obj, key, val);
3546
+ return reviver.call(obj2, key, val);
3539
3547
  }
3540
3548
  exports.applyReviver = applyReviver;
3541
3549
  }
@@ -4471,10 +4479,10 @@ var require_stringify = __commonJS({
4471
4479
  return match.find((t) => t.format === item.format) ?? match[0];
4472
4480
  }
4473
4481
  let tagObj = void 0;
4474
- let obj;
4482
+ let obj2;
4475
4483
  if (identity.isScalar(item)) {
4476
- obj = item.value;
4477
- let match = tags.filter((t) => t.identify?.(obj));
4484
+ obj2 = item.value;
4485
+ let match = tags.filter((t) => t.identify?.(obj2));
4478
4486
  if (match.length > 1) {
4479
4487
  const testMatch = match.filter((t) => t.test);
4480
4488
  if (testMatch.length > 0)
@@ -4482,11 +4490,11 @@ var require_stringify = __commonJS({
4482
4490
  }
4483
4491
  tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
4484
4492
  } else {
4485
- obj = item;
4486
- tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass);
4493
+ obj2 = item;
4494
+ tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass);
4487
4495
  }
4488
4496
  if (!tagObj) {
4489
- const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
4497
+ const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2);
4490
4498
  throw new Error(`Tag not resolved for ${name} value`);
4491
4499
  }
4492
4500
  return tagObj;
@@ -5042,23 +5050,23 @@ var require_YAMLMap = __commonJS({
5042
5050
  * A generic collection parsing method that can be extended
5043
5051
  * to other node classes that inherit from YAMLMap
5044
5052
  */
5045
- static from(schema, obj, ctx) {
5053
+ static from(schema, obj2, ctx) {
5046
5054
  const { keepUndefined, replacer } = ctx;
5047
5055
  const map = new this(schema);
5048
5056
  const add = (key, value) => {
5049
5057
  if (typeof replacer === "function")
5050
- value = replacer.call(obj, key, value);
5058
+ value = replacer.call(obj2, key, value);
5051
5059
  else if (Array.isArray(replacer) && !replacer.includes(key))
5052
5060
  return;
5053
5061
  if (value !== void 0 || keepUndefined)
5054
5062
  map.items.push(Pair.createPair(key, value, ctx));
5055
5063
  };
5056
- if (obj instanceof Map) {
5057
- for (const [key, value] of obj)
5064
+ if (obj2 instanceof Map) {
5065
+ for (const [key, value] of obj2)
5058
5066
  add(key, value);
5059
- } else if (obj && typeof obj === "object") {
5060
- for (const key of Object.keys(obj))
5061
- add(key, obj[key]);
5067
+ } else if (obj2 && typeof obj2 === "object") {
5068
+ for (const key of Object.keys(obj2))
5069
+ add(key, obj2[key]);
5062
5070
  }
5063
5071
  if (typeof schema.sortMapEntries === "function") {
5064
5072
  map.items.sort(schema.sortMapEntries);
@@ -5168,7 +5176,7 @@ var require_map = __commonJS({
5168
5176
  onError("Expected a mapping for this tag");
5169
5177
  return map2;
5170
5178
  },
5171
- createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
5179
+ createNode: (schema, obj2, ctx) => YAMLMap.YAMLMap.from(schema, obj2, ctx)
5172
5180
  };
5173
5181
  exports.map = map;
5174
5182
  }
@@ -5264,15 +5272,15 @@ var require_YAMLSeq = __commonJS({
5264
5272
  onComment
5265
5273
  });
5266
5274
  }
5267
- static from(schema, obj, ctx) {
5275
+ static from(schema, obj2, ctx) {
5268
5276
  const { replacer } = ctx;
5269
5277
  const seq = new this(schema);
5270
- if (obj && Symbol.iterator in Object(obj)) {
5278
+ if (obj2 && Symbol.iterator in Object(obj2)) {
5271
5279
  let i = 0;
5272
- for (let it of obj) {
5280
+ for (let it of obj2) {
5273
5281
  if (typeof replacer === "function") {
5274
- const key = obj instanceof Set ? it : String(i++);
5275
- it = replacer.call(obj, key, it);
5282
+ const key = obj2 instanceof Set ? it : String(i++);
5283
+ it = replacer.call(obj2, key, it);
5276
5284
  }
5277
5285
  seq.items.push(createNode.createNode(it, void 0, ctx));
5278
5286
  }
@@ -5306,7 +5314,7 @@ var require_seq = __commonJS({
5306
5314
  onError("Expected a sequence for this tag");
5307
5315
  return seq2;
5308
5316
  },
5309
- createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
5317
+ createNode: (schema, obj2, ctx) => YAMLSeq.YAMLSeq.from(schema, obj2, ctx)
5310
5318
  };
5311
5319
  exports.seq = seq;
5312
5320
  }
@@ -11201,12 +11209,12 @@ var require_codegen = __commonJS({
11201
11209
  }
11202
11210
  // `for-in` statement.
11203
11211
  // With option `ownProperties` replaced with a `for-of` loop for object keys
11204
- forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
11212
+ forIn(nameOrPrefix, obj2, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
11205
11213
  if (this.opts.ownProperties) {
11206
- return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
11214
+ return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj2})`, forBody);
11207
11215
  }
11208
11216
  const name = this._scope.toName(nameOrPrefix);
11209
- return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
11217
+ return this._for(new ForIter("in", varKind, name, obj2), () => forBody(name));
11210
11218
  }
11211
11219
  // end `for` loop
11212
11220
  endFor() {
@@ -11430,11 +11438,11 @@ var require_util = __commonJS({
11430
11438
  return false;
11431
11439
  }
11432
11440
  exports.schemaHasRules = schemaHasRules;
11433
- function schemaHasRulesButRef(schema, RULES) {
11441
+ function schemaHasRulesButRef(schema, RULES2) {
11434
11442
  if (typeof schema == "boolean")
11435
11443
  return !schema;
11436
11444
  for (const key in schema)
11437
- if (key !== "$ref" && RULES.all[key])
11445
+ if (key !== "$ref" && RULES2.all[key])
11438
11446
  return true;
11439
11447
  return false;
11440
11448
  }
@@ -12828,17 +12836,17 @@ var require_validate = __commonJS({
12828
12836
  }
12829
12837
  function schemaKeywords(it, types, typeErrors, errsCount) {
12830
12838
  const { gen, schema, data, allErrors, opts, self } = it;
12831
- const { RULES } = self;
12832
- if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
12833
- gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
12839
+ const { RULES: RULES2 } = self;
12840
+ if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES2))) {
12841
+ gen.block(() => keywordCode(it, "$ref", RULES2.all.$ref.definition));
12834
12842
  return;
12835
12843
  }
12836
12844
  if (!opts.jtd)
12837
12845
  checkStrictTypes(it, types);
12838
12846
  gen.block(() => {
12839
- for (const group of RULES.rules)
12847
+ for (const group of RULES2.rules)
12840
12848
  groupKeywords(group);
12841
- groupKeywords(RULES.post);
12849
+ groupKeywords(RULES2.post);
12842
12850
  });
12843
12851
  function groupKeywords(group) {
12844
12852
  if (!(0, applicability_1.shouldUseGroup)(schema, group))
@@ -13026,11 +13034,11 @@ var require_validate = __commonJS({
13026
13034
  if (!this.allErrors)
13027
13035
  this.gen.if(cond);
13028
13036
  }
13029
- setParams(obj, assign) {
13037
+ setParams(obj2, assign) {
13030
13038
  if (assign)
13031
- Object.assign(this.params, obj);
13039
+ Object.assign(this.params, obj2);
13032
13040
  else
13033
- this.params = obj;
13041
+ this.params = obj2;
13034
13042
  }
13035
13043
  block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
13036
13044
  this.gen.block(() => {
@@ -14993,10 +15001,10 @@ var require_core = __commonJS({
14993
15001
  }
14994
15002
  // Remove keyword
14995
15003
  removeKeyword(keyword) {
14996
- const { RULES } = this;
14997
- delete RULES.keywords[keyword];
14998
- delete RULES.all[keyword];
14999
- for (const group of RULES.rules) {
15004
+ const { RULES: RULES2 } = this;
15005
+ delete RULES2.keywords[keyword];
15006
+ delete RULES2.all[keyword];
15007
+ for (const group of RULES2.rules) {
15000
15008
  const i = group.rules.findIndex((rule) => rule.keyword === keyword);
15001
15009
  if (i >= 0)
15002
15010
  group.rules.splice(i, 1);
@@ -15164,9 +15172,9 @@ var require_core = __commonJS({
15164
15172
  }
15165
15173
  var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
15166
15174
  function checkKeyword(keyword, def) {
15167
- const { RULES } = this;
15175
+ const { RULES: RULES2 } = this;
15168
15176
  (0, util_1.eachItem)(keyword, (kwd) => {
15169
- if (RULES.keywords[kwd])
15177
+ if (RULES2.keywords[kwd])
15170
15178
  throw new Error(`Keyword ${kwd} is already defined`);
15171
15179
  if (!KEYWORD_NAME.test(kwd))
15172
15180
  throw new Error(`Keyword ${kwd} has invalid name`);
@@ -15182,13 +15190,13 @@ var require_core = __commonJS({
15182
15190
  const post = definition === null || definition === void 0 ? void 0 : definition.post;
15183
15191
  if (dataType && post)
15184
15192
  throw new Error('keyword with "post" flag cannot have "type"');
15185
- const { RULES } = this;
15186
- let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
15193
+ const { RULES: RULES2 } = this;
15194
+ let ruleGroup = post ? RULES2.post : RULES2.rules.find(({ type: t }) => t === dataType);
15187
15195
  if (!ruleGroup) {
15188
15196
  ruleGroup = { type: dataType, rules: [] };
15189
- RULES.rules.push(ruleGroup);
15197
+ RULES2.rules.push(ruleGroup);
15190
15198
  }
15191
- RULES.keywords[keyword] = true;
15199
+ RULES2.keywords[keyword] = true;
15192
15200
  if (!definition)
15193
15201
  return;
15194
15202
  const rule = {
@@ -15203,7 +15211,7 @@ var require_core = __commonJS({
15203
15211
  addBeforeRule.call(this, ruleGroup, rule, definition.before);
15204
15212
  else
15205
15213
  ruleGroup.rules.push(rule);
15206
- RULES.all[keyword] = rule;
15214
+ RULES2.all[keyword] = rule;
15207
15215
  (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd));
15208
15216
  }
15209
15217
  function addBeforeRule(ruleGroup, rule, before) {
@@ -18867,6 +18875,517 @@ var require_dist2 = __commonJS({
18867
18875
  }
18868
18876
  });
18869
18877
 
18878
+ // packages/testkit-core/dist/embedded.js
18879
+ var EMBEDDED_CONTRACTS, EMBEDDED_PACKS;
18880
+ var init_embedded = __esm({
18881
+ "packages/testkit-core/dist/embedded.js"() {
18882
+ "use strict";
18883
+ EMBEDDED_CONTRACTS = { "envelope.schema.json": `{
18884
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
18885
+ "$id": "https://saktum.dev/schemas/envelope/0.1.json",
18886
+ "title": "Saktum canonical call envelope",
18887
+ "description": "Protocol-neutral description of one call between an agent and a service. Trust Check records calls in this shape; the gateway (2027) uses the same contract.",
18888
+ "type": "object",
18889
+ "required": [
18890
+ "envelopeFormat",
18891
+ "id",
18892
+ "protocol",
18893
+ "operation",
18894
+ "target",
18895
+ "timestamp"
18896
+ ],
18897
+ "additionalProperties": false,
18898
+ "properties": {
18899
+ "envelopeFormat": {
18900
+ "const": "0.1"
18901
+ },
18902
+ "id": {
18903
+ "type": "string"
18904
+ },
18905
+ "protocol": {
18906
+ "enum": [
18907
+ "mcp",
18908
+ "a2a",
18909
+ "http"
18910
+ ]
18911
+ },
18912
+ "operation": {
18913
+ "type": "string",
18914
+ "description": "e.g. tools/call"
18915
+ },
18916
+ "tool": {
18917
+ "type": "string"
18918
+ },
18919
+ "caller": {
18920
+ "type": "object",
18921
+ "properties": {
18922
+ "agent": {
18923
+ "type": "string"
18924
+ },
18925
+ "onBehalfOf": {
18926
+ "type": "string"
18927
+ }
18928
+ }
18929
+ },
18930
+ "target": {
18931
+ "type": "object",
18932
+ "required": [
18933
+ "service"
18934
+ ],
18935
+ "properties": {
18936
+ "service": {
18937
+ "type": "string"
18938
+ },
18939
+ "version": {
18940
+ "type": "string"
18941
+ }
18942
+ }
18943
+ },
18944
+ "argumentsHash": {
18945
+ "type": "string",
18946
+ "pattern": "^sha256:[0-9a-f]{64}$"
18947
+ },
18948
+ "timestamp": {
18949
+ "type": "string",
18950
+ "format": "date-time"
18951
+ },
18952
+ "context": {
18953
+ "type": "object",
18954
+ "additionalProperties": false,
18955
+ "description": "Optional governance context (Baseline 7.0): which task and business-process step this call belongs to. Policies may reference it; receipts echo it.",
18956
+ "properties": {
18957
+ "task": {
18958
+ "type": "object",
18959
+ "additionalProperties": false,
18960
+ "properties": {
18961
+ "id": {
18962
+ "type": "string"
18963
+ },
18964
+ "purpose": {
18965
+ "type": "string"
18966
+ },
18967
+ "permissions": {
18968
+ "type": "array",
18969
+ "items": {
18970
+ "type": "string"
18971
+ }
18972
+ }
18973
+ }
18974
+ },
18975
+ "process": {
18976
+ "type": "object",
18977
+ "additionalProperties": false,
18978
+ "properties": {
18979
+ "id": {
18980
+ "type": "string"
18981
+ },
18982
+ "name": {
18983
+ "type": "string"
18984
+ },
18985
+ "step": {
18986
+ "type": "string"
18987
+ }
18988
+ }
18989
+ },
18990
+ "orchestrator": {
18991
+ "type": "string",
18992
+ "description": "e.g. camunda, temporal, n8n"
18993
+ },
18994
+ "rationale": {
18995
+ "type": "string",
18996
+ "maxLength": 280,
18997
+ "description": "Optional short reason the agent states for this call (Baseline 7.9); recorded on the receipt so reasoning is auditable without storing conversations."
18998
+ },
18999
+ "executor": {
19000
+ "type": "object",
19001
+ "additionalProperties": false,
19002
+ "description": "Optional (Baseline 8.4): the orchestrator that carried out the action on the agent's behalf, so receipts distinguish who decided, who executed and who authorised.",
19003
+ "properties": {
19004
+ "type": {
19005
+ "type": "string",
19006
+ "description": "e.g. orchestrator, rpa, gateway"
19007
+ },
19008
+ "id": {
19009
+ "type": "string"
19010
+ },
19011
+ "name": {
19012
+ "type": "string"
19013
+ },
19014
+ "instance": {
19015
+ "type": "string"
19016
+ }
19017
+ }
19018
+ }
19019
+ }
19020
+ }
19021
+ }
19022
+ }
19023
+ `, "pack.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/pack/0.1.json",\n "title": "Saktum Trust Check test pack",\n "description": "A versioned set of checks. Packs are data, never code: steps use a closed set of actions, and any logic lives in named, engine-versioned analysers.",\n "type": "object",\n "required": [\n "packFormat",\n "id",\n "version",\n "category",\n "checks"\n ],\n "additionalProperties": false,\n "properties": {\n "packFormat": {\n "const": "0.1"\n },\n "id": {\n "type": "string",\n "pattern": "^[a-z][a-z0-9-]*$"\n },\n "version": {\n "type": "string",\n "pattern": "^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$"\n },\n "category": {\n "enum": [\n "conformance",\n "auth",\n "security",\n "agent-experience",\n "performance",\n "functional"\n ]\n },\n "description": {\n "type": "string"\n },\n "checks": {\n "type": "array",\n "minItems": 1,\n "items": {\n "$ref": "#/$defs/check"\n }\n },\n "signature": {\n "type": "object",\n "required": [\n "alg",\n "kid",\n "jws"\n ],\n "additionalProperties": false,\n "properties": {\n "alg": {\n "const": "EdDSA"\n },\n "kid": {\n "type": "string",\n "pattern": "^did:key:z"\n },\n "jws": {\n "type": "string"\n }\n },\n "description": "Detached JWS over the canonical pack without this member. Required for packs from the feed (v0.2)."\n }\n },\n "$defs": {\n "check": {\n "type": "object",\n "required": [\n "id",\n "title",\n "severity",\n "safety",\n "steps",\n "fix"\n ],\n "additionalProperties": false,\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^[a-z]+(\\\\.[a-z0-9-]+)+$"\n },\n "title": {\n "type": "string"\n },\n "severity": {\n "enum": [\n "critical",\n "high",\n "medium",\n "low",\n "info"\n ]\n },\n "safety": {\n "enum": [\n "passive",\n "active"\n ]\n },\n "scored": {\n "type": "boolean",\n "default": true\n },\n "appliesTo": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "transports": {\n "type": "array",\n "items": {\n "enum": [\n "stdio",\n "streamable-http"\n ]\n }\n },\n "protocol": {\n "type": "string",\n "description": "Minimum protocol revision, e.g. >=2025-03-26"\n }\n }\n },\n "steps": {\n "type": "array",\n "minItems": 1,\n "items": {\n "$ref": "#/$defs/step"\n }\n },\n "fix": {\n "type": "string"\n },\n "references": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "normative": {\n "type": "array",\n "description": "Baseline 4.1: the normative statements this check verifies, for the public traceability matrix.",\n "items": {\n "type": "object",\n "required": [\n "source",\n "level"\n ],\n "additionalProperties": false,\n "properties": {\n "source": {\n "type": "string",\n "description": "e.g. MCP specification, RFC 9728, OWASP MCP Top 10"\n },\n "version": {\n "type": "string",\n "description": "specification revision or date"\n },\n "clause": {\n "type": "string",\n "description": "section or requirement identifier"\n },\n "level": {\n "enum": [\n "MUST",\n "SHOULD",\n "MAY",\n "best-practice"\n ]\n }\n }\n }\n }\n }\n },\n "step": {\n "type": "object",\n "required": [\n "action"\n ],\n "additionalProperties": false,\n "properties": {\n "action": {\n "enum": [\n "mcp.initialize",\n "mcp.listTools",\n "mcp.callTool",\n "analyse"\n ]\n },\n "tool": {\n "type": "string"\n },\n "arguments": {\n "type": "object"\n },\n "analyser": {\n "type": "string"\n },\n "expect": {\n "$ref": "#/$defs/expectation"\n }\n }\n },\n "expectation": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "exists": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "isError": {\n "type": "boolean"\n },\n "errorCodeIn": {\n "type": "array",\n "items": {\n "type": "integer"\n }\n },\n "failed": {\n "type": "boolean",\n "description": "The call must not succeed: either a protocol error or a tool result flagged as an error."\n },\n "anyOf": {\n "type": "array",\n "items": {\n "$ref": "#/$defs/expectation"\n }\n }\n }\n }\n }\n}\n', "receipt.schema.json": `{
19024
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
19025
+ "$id": "https://saktum.dev/schemas/receipt/0.1.json",
19026
+ "title": "Saktum receipt",
19027
+ "description": "A signed record of one call's outcome. Signatures use public-key cryptography so any third party can verify them without a shared secret.",
19028
+ "type": "object",
19029
+ "required": [
19030
+ "receiptFormat",
19031
+ "envelope",
19032
+ "outcome",
19033
+ "issuedAt",
19034
+ "signatures"
19035
+ ],
19036
+ "additionalProperties": false,
19037
+ "properties": {
19038
+ "receiptFormat": {
19039
+ "const": "0.1"
19040
+ },
19041
+ "envelope": {
19042
+ "$ref": "https://saktum.dev/schemas/envelope/0.1.json"
19043
+ },
19044
+ "outcome": {
19045
+ "enum": [
19046
+ "allow",
19047
+ "deny",
19048
+ "error"
19049
+ ]
19050
+ },
19051
+ "reason": {
19052
+ "type": "string"
19053
+ },
19054
+ "issuedAt": {
19055
+ "type": "string",
19056
+ "format": "date-time"
19057
+ },
19058
+ "signatures": {
19059
+ "type": "array",
19060
+ "minItems": 1,
19061
+ "items": {
19062
+ "type": "object",
19063
+ "required": [
19064
+ "alg",
19065
+ "kid",
19066
+ "jws"
19067
+ ],
19068
+ "properties": {
19069
+ "alg": {
19070
+ "const": "EdDSA"
19071
+ },
19072
+ "kid": {
19073
+ "type": "string"
19074
+ },
19075
+ "jws": {
19076
+ "type": "string"
19077
+ }
19078
+ }
19079
+ }
19080
+ },
19081
+ "explanation": {
19082
+ "type": "string",
19083
+ "maxLength": 500,
19084
+ "description": "One plain-language sentence: what happened, which rule applied, who could have stopped it."
19085
+ },
19086
+ "context": {
19087
+ "$ref": "https://saktum.dev/schemas/envelope/0.1.json#/properties/context"
19088
+ },
19089
+ "compensates": {
19090
+ "type": "string",
19091
+ "description": "Optional (Baseline 8.4): id of the original envelope or receipt that this call reverses (compensation transaction)."
19092
+ }
19093
+ }
19094
+ }
19095
+ `, "result.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/result/0.1.json",\n "title": "Saktum Trust Check result",\n "description": "The canonical result of one run. Every report format is rendered from this model. Evidence is a hash plus a short, sanitised excerpt; raw payloads never appear.",\n "type": "object",\n "required": [\n "resultFormat",\n "tool",\n "target",\n "packs",\n "findings",\n "scores",\n "metrics",\n "run"\n ],\n "additionalProperties": false,\n "properties": {\n "resultFormat": {\n "const": "0.1"\n },\n "tool": {\n "type": "object",\n "required": [\n "name",\n "version"\n ],\n "additionalProperties": false,\n "properties": {\n "name": {\n "const": "saktum-trust-check"\n },\n "version": {\n "type": "string"\n }\n }\n },\n "target": {\n "type": "object",\n "required": [\n "transport",\n "description"\n ],\n "additionalProperties": false,\n "properties": {\n "transport": {\n "enum": [\n "stdio",\n "streamable-http"\n ]\n },\n "description": {\n "type": "string"\n },\n "protocolVersion": {\n "type": "string"\n },\n "serverInfo": {\n "type": "object"\n },\n "toolsFingerprint": {\n "type": "string",\n "pattern": "^sha256:[0-9a-f]{64}$"\n },\n "toolCount": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "packs": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "id",\n "version",\n "hash"\n ],\n "additionalProperties": false,\n "properties": {\n "id": {\n "type": "string"\n },\n "version": {\n "type": "string"\n },\n "hash": {\n "type": "string",\n "pattern": "^sha256:[0-9a-f]{64}$"\n }\n }\n }\n },\n "findings": {\n "type": "array",\n "items": {\n "$ref": "#/$defs/finding"\n }\n },\n "scores": {\n "type": "object",\n "required": [\n "overall",\n "capped",\n "categories"\n ],\n "additionalProperties": false,\n "properties": {\n "overall": {\n "type": [\n "integer",\n "null"\n ],\n "minimum": 0,\n "maximum": 100\n },\n "capped": {\n "type": "boolean"\n },\n "categories": {\n "type": "object",\n "additionalProperties": {\n "type": [\n "integer",\n "null"\n ]\n }\n }\n }\n },\n "metrics": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "contextCostTokens": {\n "type": "integer",\n "minimum": 0\n },\n "largestTools": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "tool",\n "tokens"\n ],\n "properties": {\n "tool": {\n "type": "string"\n },\n "tokens": {\n "type": "integer"\n }\n }\n }\n },\n "contextCostPer1kTurnsUsd": {\n "type": "number",\n "minimum": 0,\n "description": "Estimated cost of loading the tool definitions on 1,000 agent turns at pricePerMTokUsd. Reported only."\n },\n "pricePerMTokUsd": {\n "type": "number",\n "minimum": 0\n },\n "performance": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "initMs": {\n "type": "integer",\n "minimum": 0\n },\n "listMs": {\n "type": "integer",\n "minimum": 0\n },\n "listBytes": {\n "type": "integer",\n "minimum": 0\n },\n "rssMb": {\n "type": "number",\n "minimum": 0\n },\n "cpuPct": {\n "type": "number",\n "minimum": 0\n },\n "burst": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "requests": {\n "type": "integer"\n },\n "ok": {\n "type": "integer"\n },\n "rateLimited": {\n "type": "integer"\n },\n "errors": {\n "type": "integer"\n },\n "p95Ms": {\n "type": "integer"\n }\n }\n }\n }\n }\n }\n },\n "run": {\n "type": "object",\n "required": [\n "startedAt",\n "durationMs",\n "mode",\n "runner",\n "sandbox"\n ],\n "additionalProperties": false,\n "properties": {\n "startedAt": {\n "type": "string",\n "format": "date-time"\n },\n "durationMs": {\n "type": "integer",\n "minimum": 0\n },\n "mode": {\n "enum": [\n "passive",\n "active"\n ]\n },\n "runner": {\n "enum": [\n "self",\n "hosted"\n ],\n "description": "self: run and signed by the user, proves integrity not independence. hosted: run and signed by Saktum (later)."\n },\n "sandbox": {\n "enum": [\n "none",\n "docker"\n ],\n "description": "Whether local servers ran inside a container sandbox."\n }\n }\n },\n "signature": {\n "type": "object",\n "required": [\n "alg",\n "kid",\n "jws"\n ],\n "additionalProperties": false,\n "properties": {\n "alg": {\n "const": "EdDSA"\n },\n "kid": {\n "type": "string",\n "pattern": "^did:key:z"\n },\n "jws": {\n "type": "string"\n }\n }\n },\n "grade": {\n "enum": [\n "A",\n "B",\n "C",\n "D",\n "F",\n null\n ],\n "description": "Letter grade from the trust score: A 90-100, B 80-89, C 70-79, D 50-69, F below 50 or any failed critical check."\n },\n "summary": {\n "type": "array",\n "maxItems": 5,\n "items": {\n "type": "string",\n "maxLength": 400\n },\n "description": "Plain-language summary sentences shown first in every report."\n },\n "assuranceLevel": {\n "enum": [\n "L1",\n "L2",\n "L3",\n "L4"\n ],\n "description": "L1 self-tested (Saktum Check); L2 independently tested; L3 certified; L4 continuously certified."\n },\n "readiness": {\n "description": "Agent readiness: a second grade beside trust (annotations, descriptions, context cost), never mixed into the trust score.",\n "oneOf": [\n {\n "type": "null"\n },\n {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "score",\n "grade",\n "toolsAnnotated",\n "toolsDescribed",\n "toolCount",\n "contextTokens"\n ],\n "properties": {\n "score": {\n "type": "integer",\n "minimum": 0,\n "maximum": 100\n },\n "grade": {\n "enum": [\n "A",\n "B",\n "C",\n "D",\n "F",\n null\n ]\n },\n "toolsAnnotated": {\n "type": "integer",\n "minimum": 0\n },\n "toolsDescribed": {\n "type": "integer",\n "minimum": 0\n },\n "toolCount": {\n "type": "integer",\n "minimum": 0\n },\n "contextTokens": {\n "type": "integer",\n "minimum": 0\n },\n "topImprovement": {\n "type": "string",\n "maxLength": 300\n }\n }\n }\n ]\n },\n "coverage": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "trustChecksRun": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "capabilities": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "capabilities",\n "lethalTrifecta",\n "note"\n ],\n "properties": {\n "capabilities": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "capability",\n "label",\n "tools",\n "basis"\n ],\n "properties": {\n "capability": {\n "type": "string"\n },\n "label": {\n "type": "string",\n "maxLength": 400\n },\n "tools": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n },\n "maxItems": 20\n },\n "basis": {\n "enum": [\n "declared",\n "inferred"\n ]\n }\n }\n }\n },\n "lethalTrifecta": {\n "type": "boolean"\n },\n "note": {\n "type": "string",\n "maxLength": 400\n }\n }\n },\n "functional": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "ran",\n "calledTools",\n "notCalled",\n "calls"\n ],\n "properties": {\n "ran": {\n "type": "boolean"\n },\n "reason": {\n "type": "string",\n "maxLength": 400\n },\n "calledTools": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n },\n "survived": {\n "type": "boolean"\n },\n "notCalled": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "tool",\n "why"\n ],\n "properties": {\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "why": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n },\n "calls": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "tool",\n "purpose",\n "outcome",\n "latencyMs",\n "problems"\n ],\n "properties": {\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "purpose": {\n "type": "string",\n "maxLength": 400\n },\n "outcome": {\n "type": "string",\n "maxLength": 400\n },\n "latencyMs": {\n "type": "integer",\n "minimum": 0\n },\n "problems": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n }\n }\n }\n },\n "load": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "operation",\n "latency",\n "levels",\n "verdicts"\n ],\n "properties": {\n "operation": {\n "type": "string",\n "maxLength": 400\n },\n "latency": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "p50": {\n "type": "number"\n },\n "p95": {\n "type": "number"\n },\n "samples": {\n "type": "integer"\n }\n }\n },\n "levels": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "concurrency",\n "requests",\n "ok",\n "rateLimited",\n "errors",\n "p95",\n "throughput"\n ],\n "properties": {\n "concurrency": {\n "type": "number",\n "minimum": 0\n },\n "requests": {\n "type": "number",\n "minimum": 0\n },\n "ok": {\n "type": "number",\n "minimum": 0\n },\n "rateLimited": {\n "type": "number",\n "minimum": 0\n },\n "errors": {\n "type": "number",\n "minimum": 0\n },\n "p95": {\n "type": "number",\n "minimum": 0\n },\n "throughput": {\n "type": "number",\n "minimum": 0\n }\n }\n }\n },\n "memoryGrowthMb": {\n "type": "number"\n },\n "verdicts": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n },\n "tests": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "id",\n "tool",\n "status",\n "problems"\n ],\n "properties": {\n "id": {\n "type": "string",\n "maxLength": 400\n },\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "status": {\n "enum": [\n "pass",\n "fail",\n "skipped"\n ]\n },\n "problems": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n },\n "latencyMs": {\n "type": "integer",\n "minimum": 0\n }\n }\n }\n },\n "suppressions": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "check",\n "reason"\n ],\n "properties": {\n "check": {\n "type": "string",\n "maxLength": 400\n },\n "reason": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n }\n },\n "$defs": {\n "finding": {\n "type": "object",\n "required": [\n "check",\n "pack",\n "status",\n "severity",\n "title"\n ],\n "additionalProperties": false,\n "properties": {\n "check": {\n "type": "string"\n },\n "pack": {\n "type": "string"\n },\n "status": {\n "enum": [\n "pass",\n "fail",\n "skipped",\n "inconclusive",\n "info"\n ]\n },\n "severity": {\n "enum": [\n "critical",\n "high",\n "medium",\n "low",\n "info"\n ]\n },\n "scored": {\n "type": "boolean"\n },\n "title": {\n "type": "string"\n },\n "subject": {\n "type": "string"\n },\n "message": {\n "type": "string"\n },\n "fix": {\n "type": "string"\n },\n "references": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "evidence": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "hash": {\n "type": "string"\n },\n "excerpt": {\n "type": "string",\n "maxLength": 240\n }\n }\n },\n "suppressed": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "reason"\n ],\n "properties": {\n "reason": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n }\n }\n }\n}\n', "test-cases.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/test-cases/0.1.json",\n "title": "Saktum Trust Check functional test cases (saktum.tests.yaml)",\n "type": "object",\n "required": ["testsFormat", "tests"],\n "additionalProperties": false,\n "properties": {\n "testsFormat": { "const": "0.1" },\n "tests": {\n "type": "array",\n "items": {\n "type": "object",\n "required": ["id", "tool", "input", "expect"],\n "additionalProperties": false,\n "properties": {\n "id": { "type": "string" },\n "tool": { "type": "string" },\n "input": { "type": "object" },\n "sideEffects": { "type": "boolean", "default": false, "description": "Tests with side effects run only against owned targets." },\n "expect": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "isError": { "type": "boolean" },\n "textContains": { "type": "string" },\n "structured": { "type": "object" },\n "outputSchema": { "type": "boolean" },\n "latencyMs": { "type": "object", "properties": { "lt": { "type": "integer" } }, "additionalProperties": false }\n }\n }\n }\n }\n }\n }\n}\n' };
19096
+ EMBEDDED_PACKS = { "agent-experience.yaml": 'packFormat: "0.1"\nid: agent-experience\nversion: 0.1.0\ncategory: agent-experience\ndescription: How easily and cheaply agents can use the server. Reported, never part of the trust score.\nchecks:\n - id: ax.context-cost\n title: Context cost of tool definitions\n severity: info\n safety: passive\n scored: false\n steps: [{ action: analyse, analyser: context-cost }]\n fix: Shorten long descriptions, split large servers, and drop tools agents rarely need.\n - id: ax.annotations\n title: Tools declare annotations\n severity: low\n safety: passive\n steps: [{ action: analyse, analyser: annotations-present }]\n fix: Set readOnlyHint, destructiveHint, idempotentHint and openWorldHint on every tool so clients can warn before risky actions.\n references: ["MCP specification: tool annotations", "OWASP MCP Top 10: MCP02 Privilege Escalation via Scope Creep (undeclared write and destructive tools)"]\n - id: ax.short-descriptions\n title: Tools have usable descriptions\n severity: low\n safety: passive\n steps: [{ action: analyse, analyser: short-descriptions }]\n fix: Describe what the tool does, when to use it and when not to, in at least a full sentence.\n - id: ax.client-compat\n title: Fits common client and model-provider constraints\n severity: info\n safety: passive\n scored: false\n steps: [{ action: analyse, analyser: client-compat }]\n fix: Use tool names of 1 to 64 letters, digits, underscores and hyphens, keep them short enough for a server prefix, and keep the tool count manageable.\n', "auth.yaml": `packFormat: "0.1"
19097
+ id: auth
19098
+ version: 0.1.0
19099
+ category: auth
19100
+ description: Sign-in for remote servers, checked from the outside without credentials. Follows the MCP authorization specification and the OAuth RFCs it builds on.
19101
+ checks:
19102
+ - id: auth.https
19103
+ title: Served over HTTPS
19104
+ severity: critical
19105
+ safety: passive
19106
+ appliesTo: { transports: [streamable-http] }
19107
+ steps: [{ action: analyse, analyser: auth-https }]
19108
+ fix: Serve the MCP endpoint over HTTPS (plain HTTP only on localhost during development).
19109
+ references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization", "CWE-319"]
19110
+ normative: [{ source: "MCP specification", version: "verify-latest", clause: "Authorization: communication security", level: MUST }, { source: "RFC 9700", clause: "OAuth security best current practice: TLS", level: MUST }]
19111
+ - id: auth.unauthenticated
19112
+ title: Whether sign-in is required
19113
+ severity: info
19114
+ safety: passive
19115
+ scored: false
19116
+ appliesTo: { transports: [streamable-http] }
19117
+ steps: [{ action: analyse, analyser: auth-unauthenticated }]
19118
+ fix: Require OAuth sign-in for any server that exposes user data or actions.
19119
+ references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]
19120
+ - id: auth.www-authenticate
19121
+ title: Refusals point clients to the resource metadata
19122
+ severity: high
19123
+ safety: passive
19124
+ appliesTo: { transports: [streamable-http] }
19125
+ steps: [{ action: analyse, analyser: auth-www-authenticate }]
19126
+ fix: Answer unauthenticated requests with 401 and a header such as WWW-Authenticate Bearer resource_metadata="https://your-server/.well-known/oauth-protected-resource".
19127
+ references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]
19128
+ normative: [{ source: "RFC 9728", clause: "Section 5.1, WWW-Authenticate response", level: MUST }, { source: "MCP specification", version: "verify-latest", clause: "Authorization: authorization server discovery", level: MUST }]
19129
+ - id: auth.resource-metadata
19130
+ title: Protected resource metadata is published and correct
19131
+ severity: high
19132
+ safety: passive
19133
+ appliesTo: { transports: [streamable-http] }
19134
+ steps: [{ action: analyse, analyser: auth-resource-metadata }]
19135
+ fix: Publish /.well-known/oauth-protected-resource with "resource" set to this server's URL and "authorization_servers" listing your HTTPS authorization server.
19136
+ references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]
19137
+ normative: [{ source: "RFC 9728", clause: "Sections 2 and 3, metadata and well-known URI", level: MUST }]
19138
+ - id: auth.server-metadata
19139
+ title: Authorization server metadata is complete, with PKCE
19140
+ severity: high
19141
+ safety: passive
19142
+ appliesTo: { transports: [streamable-http] }
19143
+ steps: [{ action: analyse, analyser: auth-server-metadata }]
19144
+ fix: Publish RFC 8414 metadata with issuer, HTTPS authorization and token endpoints, the code response type, and code_challenge_methods_supported including S256.
19145
+ references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]
19146
+ normative: [{ source: "RFC 8414", clause: "Sections 2 and 3", level: MUST }, { source: "RFC 7636", clause: "PKCE with S256", level: MUST }, { source: "MCP specification", version: "verify-latest", clause: "Authorization: PKCE required", level: MUST }]
19147
+ - id: auth.invalid-token
19148
+ title: Invalid tokens are rejected
19149
+ severity: critical
19150
+ safety: passive
19151
+ appliesTo: { transports: [streamable-http] }
19152
+ steps: [{ action: analyse, analyser: auth-invalid-token }]
19153
+ fix: Validate every bearer token (signature or introspection, expiry, audience) and answer invalid ones with 401 and error="invalid_token".
19154
+ references: ["OWASP MCP Top 10: MCP01 Token Mismanagement and Secret Exposure", "OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization", "CWE-287"]
19155
+ normative: [{ source: "RFC 6750", clause: "Section 3.1, invalid_token", level: MUST }]
19156
+ `, "conformance.yaml": `packFormat: "0.1"
19157
+ id: conformance
19158
+ version: 0.1.0
19159
+ category: conformance
19160
+ description: Does the server speak MCP correctly? Basis for every other check.
19161
+ checks:
19162
+ - id: conf.init.handshake
19163
+ title: Initialize returns server info and capabilities
19164
+ severity: high
19165
+ safety: passive
19166
+ steps: [{ action: analyse, analyser: handshake }]
19167
+ fix: Return serverInfo (name, version) and a capabilities object from initialize.
19168
+ normative: [{ source: "MCP specification", version: "verify-latest", clause: "Lifecycle: initialization (server returns capabilities and serverInfo)", level: MUST }]
19169
+ references: ["MCP specification: lifecycle"]
19170
+ - id: conf.tools.list
19171
+ title: Tool list is returned
19172
+ severity: high
19173
+ safety: passive
19174
+ steps: [{ action: mcp.listTools, expect: { exists: [tools] } }]
19175
+ fix: Implement tools/list and return a tools array (empty if you have none).
19176
+ normative: [{ source: "MCP specification", version: "verify-latest", clause: "Server features: tools, listing tools", level: MUST }]
19177
+ references: ["MCP specification: tools"]
19178
+ - id: conf.tools.schema-valid
19179
+ title: Every input schema is a valid JSON Schema object
19180
+ severity: high
19181
+ safety: passive
19182
+ steps: [{ action: analyse, analyser: tool-input-schemas }]
19183
+ fix: Give every tool an inputSchema of type "object" that compiles as JSON Schema.
19184
+ normative: [{ source: "MCP specification", version: "verify-latest", clause: "Tools: inputSchema is a JSON Schema object", level: MUST }]
19185
+ references: ["MCP specification: tools", "JSON Schema 2020-12", "OWASP MCP Top 10: MCP05 Command Injection and Execution (input validation)"]
19186
+ - id: conf.tools.names
19187
+ title: Tool names are unique and use allowed characters
19188
+ severity: medium
19189
+ safety: passive
19190
+ steps: [{ action: analyse, analyser: tool-names }]
19191
+ fix: Use unique names of 1 to 128 characters from A-Z, a-z, 0-9, underscore, dot and hyphen.
19192
+ references: ["MCP specification: tools"]
19193
+ - id: conf.tools.unknown-not-success
19194
+ title: Calling an unknown tool does not succeed
19195
+ severity: high
19196
+ safety: passive
19197
+ steps:
19198
+ - action: mcp.callTool
19199
+ tool: saktum_trust_check_no_such_tool
19200
+ arguments: {}
19201
+ expect: { failed: true }
19202
+ fix: Return an error for unknown tool names; never a successful result.
19203
+ references: ["MCP specification: tools, error handling", "OWASP MCP Top 10: MCP08 Lack of Audit and Telemetry (false success hides actions)"]
19204
+ - id: conf.tools.unknown-error-code
19205
+ title: Error code for unknown tools
19206
+ severity: info
19207
+ safety: passive
19208
+ scored: false
19209
+ steps: [{ action: analyse, analyser: unknown-tool-code }]
19210
+ fix: Answer an unknown tool name with a JSON-RPC error; the specification's example uses -32602 (invalid params).
19211
+ references: ["MCP specification: tools, error handling", "JSON-RPC 2.0"]
19212
+ `, "functional.yaml": `packFormat: "0.1"
19213
+ id: functional
19214
+ version: 0.1.0
19215
+ category: functional
19216
+ description: Do the tools actually work? Smoke calls with arguments generated from each tool's schema, output validation and robustness. Runs only with --active, and only on tools annotated read-only unless named with --call.
19217
+ checks:
19218
+ - id: func.tools.respond
19219
+ title: Tools respond to valid arguments
19220
+ severity: high
19221
+ safety: active
19222
+ steps: [{ action: analyse, analyser: func-respond }]
19223
+ fix: Accept every argument set that satisfies the tool's own input schema, and answer within the client's timeout.
19224
+ references: ["MCP specification: tools, calling tools"]
19225
+ normative: [{ source: "MCP specification", version: "verify-latest", clause: "Tools: calling tools", level: MUST }]
19226
+ - id: func.output.valid
19227
+ title: Results are well-formed and match the declared output schema
19228
+ severity: high
19229
+ safety: active
19230
+ steps: [{ action: analyse, analyser: func-output }]
19231
+ fix: Return content as an array of typed items, and when a tool declares an outputSchema, return structuredContent that conforms to it.
19232
+ references: ["MCP specification: tools, structured content and output schema"]
19233
+ normative: [{ source: "MCP specification", version: "verify-latest", clause: "Tools: output schema (servers MUST provide structured results that conform)", level: MUST }]
19234
+ - id: func.errors.graceful
19235
+ title: Invalid arguments are rejected gracefully
19236
+ severity: medium
19237
+ safety: active
19238
+ steps: [{ action: analyse, analyser: func-invalid }]
19239
+ fix: Validate arguments against the input schema and return an error result or JSON-RPC -32602 with a short, helpful message; never crash, hang or expose internals.
19240
+ references: ["MCP specification: tools, error handling", "CWE-20", "CWE-209", "OWASP MCP Top 10: MCP05 Command Injection and Execution (input validation)"]
19241
+ - id: func.server.survives
19242
+ title: The server keeps working after the functional calls
19243
+ severity: high
19244
+ safety: active
19245
+ steps: [{ action: analyse, analyser: func-survives }]
19246
+ fix: Catch errors per request so one bad call cannot stop the server.
19247
+ `, "performance.yaml": `packFormat: "0.1"
19248
+ id: performance
19249
+ version: 0.1.0
19250
+ category: performance
19251
+ description: Speed and resource use, reported as information and never part of the trust score. The burst test runs only with --active.
19252
+ checks:
19253
+ - id: perf.startup
19254
+ title: Start-up and handshake time
19255
+ severity: info
19256
+ safety: passive
19257
+ scored: false
19258
+ steps: [{ action: analyse, analyser: perf-startup }]
19259
+ fix: Defer heavy initialisation until the first call that needs it; agents and clients time out on slow starts.
19260
+ - id: perf.latency
19261
+ title: Tool-list latency and size
19262
+ severity: info
19263
+ safety: passive
19264
+ scored: false
19265
+ steps: [{ action: analyse, analyser: perf-latency }]
19266
+ fix: Keep tools/list fast and small; cache it and trim long descriptions.
19267
+ - id: perf.memory
19268
+ title: Memory and CPU of a local server
19269
+ severity: info
19270
+ safety: passive
19271
+ scored: false
19272
+ appliesTo: { transports: [stdio] }
19273
+ steps: [{ action: analyse, analyser: perf-memory }]
19274
+ fix: Reduce idle memory and CPU; local servers run beside the user's other tools.
19275
+ - id: perf.concurrency
19276
+ title: Latency percentiles and behaviour at 1, 5 and 20 concurrent callers
19277
+ severity: info
19278
+ safety: active
19279
+ scored: false
19280
+ steps: [{ action: analyse, analyser: perf-concurrency }]
19281
+ fix: Keep p95 latency low, answer overload with HTTP 429 and Retry-After instead of errors, and set limits per client.
19282
+ references: ["OWASP MCP Top 10: MCP02 Privilege Escalation via Scope Creep (resource abuse)", "CWE-770"]
19283
+ `, "security.yaml": 'packFormat: "0.1"\nid: security\nversion: 0.1.0\ncategory: security\ndescription: Passive security checks on what the server tells agents and users.\nchecks:\n - id: sec.description.hidden-instructions\n title: No instructions to the agent in tool descriptions or schemas\n severity: critical\n safety: passive\n steps: [{ action: analyse, analyser: hidden-instructions }]\n fix: Describe what each tool does; never instruct the agent (for example to read other data, send data elsewhere or hide actions from the user).\n normative: [{ source: "OWASP MCP Top 10", clause: "MCP03 Tool Poisoning", level: best-practice }]\n references: ["MCP security best practices", "CWE-1427", "OWASP MCP Top 10: MCP03 Tool Poisoning", "OWASP MCP Top 10: MCP06 Intent Flow Subversion"]\n - id: sec.description.invisible-text\n title: No invisible or bidirectional control characters\n severity: high\n safety: passive\n steps: [{ action: analyse, analyser: invisible-text }]\n fix: Remove zero-width and bidirectional control characters from names, descriptions and schemas.\n references: ["CWE-1007", "OWASP MCP Top 10: MCP03 Tool Poisoning"]\n - id: sec.description.control-characters\n title: No escape sequences or control characters\n severity: high\n safety: passive\n steps: [{ action: analyse, analyser: control-characters }]\n fix: Remove terminal escape sequences and control characters; clients may print tool text to a terminal.\n references: ["CWE-150", "OWASP MCP Top 10: MCP03 Tool Poisoning"]\n - id: sec.secrets.exposed\n title: No secrets in tool definitions or responses\n severity: critical\n safety: passive\n steps: [{ action: analyse, analyser: secrets }]\n fix: Remove keys, tokens and passwords from descriptions, schemas, defaults, examples and error messages; load them from a secret store at runtime.\n references: ["OWASP MCP Top 10: MCP01 Token Mismanagement and Secret Exposure", "CWE-798", "CWE-200"]\n normative: [{ source: "OWASP MCP Top 10", clause: "MCP01 Token Mismanagement and Secret Exposure", level: best-practice }]\n - id: sec.errors.leakage\n title: Errors do not expose internals\n severity: medium\n safety: passive\n steps: [{ action: analyse, analyser: error-leakage }]\n fix: Return short, actionable error messages; log stack traces, file paths and database errors on the server only.\n references: ["OWASP MCP Top 10: MCP08 Lack of Audit and Telemetry (errors leak internals)", "CWE-209"]\n normative: [{ source: "OWASP MCP Top 10", clause: "Information exposure through errors", level: best-practice }]\n - id: sec.http.origin\n title: Local HTTP servers refuse requests from foreign web origins\n severity: high\n safety: passive\n appliesTo: { transports: [streamable-http] }\n steps: [{ action: analyse, analyser: origin-validation }]\n fix: Validate the Origin header on every request and refuse origins you do not expect (HTTP 403); bind local servers to 127.0.0.1, not all interfaces.\n references: ["MCP specification: transports, security warning (DNS rebinding)", "CWE-346", "OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]\n normative: [{ source: "MCP specification", version: "verify-latest", clause: "Transports: Streamable HTTP security warning, validate the Origin header", level: MUST }]\n' };
19284
+ }
19285
+ });
19286
+
19287
+ // packages/testkit-core/dist/contracts.js
19288
+ var contracts_exports = {};
19289
+ __export(contracts_exports, {
19290
+ compileContract: () => compileContract,
19291
+ compileUntrustedSchema: () => compileUntrustedSchema,
19292
+ compileUntrustedSchemaValidator: () => compileUntrustedSchemaValidator,
19293
+ contractText: () => contractText,
19294
+ contractsDir: () => contractsDir,
19295
+ schemaDialect: () => schemaDialect
19296
+ });
19297
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
19298
+ import { fileURLToPath } from "node:url";
19299
+ function contractText(f) {
19300
+ if (existsSync2(contractsDir + f))
19301
+ return readFileSync2(contractsDir + f, "utf8");
19302
+ const t = EMBEDDED_CONTRACTS[f];
19303
+ if (!t)
19304
+ throw new Error(`contract ${f} not found`);
19305
+ return t;
19306
+ }
19307
+ function compileContract(file) {
19308
+ const v = ajv.getSchema(file);
19309
+ if (!v)
19310
+ throw new Error(`unknown contract ${file}`);
19311
+ return v;
19312
+ }
19313
+ function schemaDialect(schema) {
19314
+ const id = schema && typeof schema === "object" ? schema.$schema : void 0;
19315
+ if (id === void 0)
19316
+ return "2020-12";
19317
+ const s = String(id);
19318
+ if (/draft-04/.test(s))
19319
+ return "draft-04";
19320
+ if (/draft-06/.test(s))
19321
+ return "draft-06";
19322
+ if (/draft-07/.test(s))
19323
+ return "draft-07";
19324
+ if (/2019-09/.test(s))
19325
+ return "2019-09";
19326
+ if (/2020-12/.test(s))
19327
+ return "2020-12";
19328
+ return "unknown";
19329
+ }
19330
+ function compileUntrustedSchema(schema) {
19331
+ try {
19332
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
19333
+ return { ok: false, error: "the schema is not a JSON object" };
19334
+ const dialect = schemaDialect(schema);
19335
+ if (dialect === "unknown")
19336
+ return { ok: false, error: `unrecognised $schema dialect ${JSON.stringify(schema.$schema).slice(0, 80)}` };
19337
+ const { $schema: _ignored, ...body } = schema;
19338
+ const Ctor = dialect === "2020-12" ? Ajv2020 : dialect === "2019-09" ? Ajv2019 : AjvDraft7;
19339
+ new Ctor({ strict: false, allErrors: false, validateSchema: true, logger: false }).compile(body);
19340
+ return { ok: true };
19341
+ } catch (e) {
19342
+ return { ok: false, error: e.message };
19343
+ }
19344
+ }
19345
+ function compileUntrustedSchemaValidator(schema) {
19346
+ try {
19347
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
19348
+ return { ok: false, error: "the schema is not a JSON object" };
19349
+ const dialect = schemaDialect(schema);
19350
+ if (dialect === "unknown")
19351
+ return { ok: false, error: "unrecognised $schema dialect" };
19352
+ const { $schema: _ignored, ...body } = schema;
19353
+ const Ctor = dialect === "2020-12" ? Ajv2020 : dialect === "2019-09" ? Ajv2019 : AjvDraft7;
19354
+ const ajv2 = new Ctor({ strict: false, allErrors: false, validateSchema: true, logger: false });
19355
+ const fn = ajv2.compile(body);
19356
+ return { ok: true, validate: (d) => Boolean(fn(d)), errors: () => (fn.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message ?? ""}`).join("; ") };
19357
+ } catch (e) {
19358
+ return { ok: false, error: e.message };
19359
+ }
19360
+ }
19361
+ var Ajv2020Module, Ajv2019Module, AjvDraft7Module, addFormatsModule, pick, Ajv2020, Ajv2019, AjvDraft7, addFormats, contractsDir, ajv;
19362
+ var init_contracts = __esm({
19363
+ "packages/testkit-core/dist/contracts.js"() {
19364
+ "use strict";
19365
+ Ajv2020Module = __toESM(require__(), 1);
19366
+ Ajv2019Module = __toESM(require__2(), 1);
19367
+ AjvDraft7Module = __toESM(require_ajv(), 1);
19368
+ addFormatsModule = __toESM(require_dist2(), 1);
19369
+ init_embedded();
19370
+ pick = (m) => {
19371
+ let x = m;
19372
+ while (x && typeof x !== "function" && x.default)
19373
+ x = x.default;
19374
+ return x;
19375
+ };
19376
+ Ajv2020 = pick(Ajv2020Module);
19377
+ Ajv2019 = pick(Ajv2019Module);
19378
+ AjvDraft7 = pick(AjvDraft7Module);
19379
+ addFormats = pick(addFormatsModule);
19380
+ contractsDir = fileURLToPath(new URL("../../../contracts/", import.meta.url));
19381
+ ajv = new Ajv2020({ allErrors: true, strict: false });
19382
+ addFormats(ajv);
19383
+ for (const f of ["envelope.schema.json", "receipt.schema.json", "pack.schema.json", "result.schema.json", "test-cases.schema.json"]) {
19384
+ ajv.addSchema(JSON.parse(contractText(f)), f);
19385
+ }
19386
+ }
19387
+ });
19388
+
18870
19389
  // node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
18871
19390
  var require_windows = __commonJS({
18872
19391
  "node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
@@ -19381,12 +19900,12 @@ var require_content_type = __commonJS({
19381
19900
  var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
19382
19901
  exports.format = format;
19383
19902
  exports.parse = parse3;
19384
- function format(obj) {
19385
- if (!obj || typeof obj !== "object") {
19903
+ function format(obj2) {
19904
+ if (!obj2 || typeof obj2 !== "object") {
19386
19905
  throw new TypeError("argument obj is required");
19387
19906
  }
19388
- var parameters = obj.parameters;
19389
- var type = obj.type;
19907
+ var parameters = obj2.parameters;
19908
+ var type = obj2.type;
19390
19909
  if (!type || !TYPE_REGEXP.test(type)) {
19391
19910
  throw new TypeError("invalid type");
19392
19911
  }
@@ -19417,7 +19936,7 @@ var require_content_type = __commonJS({
19417
19936
  if (!TYPE_REGEXP.test(type)) {
19418
19937
  throw new TypeError("invalid media type");
19419
19938
  }
19420
- var obj = new ContentType(type.toLowerCase());
19939
+ var obj2 = new ContentType(type.toLowerCase());
19421
19940
  if (index !== -1) {
19422
19941
  var key;
19423
19942
  var match;
@@ -19436,20 +19955,20 @@ var require_content_type = __commonJS({
19436
19955
  value = value.replace(QESC_REGEXP, "$1");
19437
19956
  }
19438
19957
  }
19439
- obj.parameters[key] = value;
19958
+ obj2.parameters[key] = value;
19440
19959
  }
19441
19960
  if (index !== header.length) {
19442
19961
  throw new TypeError("invalid parameter format");
19443
19962
  }
19444
19963
  }
19445
- return obj;
19964
+ return obj2;
19446
19965
  }
19447
- function getcontenttype(obj) {
19966
+ function getcontenttype(obj2) {
19448
19967
  var header;
19449
- if (typeof obj.getHeader === "function") {
19450
- header = obj.getHeader("content-type");
19451
- } else if (typeof obj.headers === "object") {
19452
- header = obj.headers && obj.headers["content-type"];
19968
+ if (typeof obj2.getHeader === "function") {
19969
+ header = obj2.getHeader("content-type");
19970
+ } else if (typeof obj2.headers === "object") {
19971
+ header = obj2.headers && obj2.headers["content-type"];
19453
19972
  }
19454
19973
  if (typeof header !== "string") {
19455
19974
  throw new TypeError("content-type header is missing from object");
@@ -19532,9 +20051,9 @@ function canonicalize(value) {
19532
20051
  if (Array.isArray(value))
19533
20052
  return "[" + value.map((v) => v === void 0 ? "null" : canonicalize(v)).join(",") + "]";
19534
20053
  if (typeof value === "object") {
19535
- const obj = value;
19536
- const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
19537
- return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalize(obj[k])).join(",") + "}";
20054
+ const obj2 = value;
20055
+ const keys = Object.keys(obj2).filter((k) => obj2[k] !== void 0).sort();
20056
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalize(obj2[k])).join(",") + "}";
19538
20057
  }
19539
20058
  throw new Error(`canonicalize: unsupported type ${typeof value}`);
19540
20059
  }
@@ -19639,450 +20158,9 @@ function verifyDocument(doc) {
19639
20158
  return ok ? { valid: true, kid: s.kid } : { valid: false, kid: s.kid, reason: "signature does not match content" };
19640
20159
  }
19641
20160
 
19642
- // packages/testkit-core/dist/contracts.js
19643
- var Ajv2020Module = __toESM(require__(), 1);
19644
- var Ajv2019Module = __toESM(require__2(), 1);
19645
- var AjvDraft7Module = __toESM(require_ajv(), 1);
19646
- var addFormatsModule = __toESM(require_dist2(), 1);
19647
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
19648
- import { fileURLToPath } from "node:url";
19649
-
19650
- // packages/testkit-core/dist/embedded.js
19651
- var EMBEDDED_CONTRACTS = { "envelope.schema.json": `{
19652
- "$schema": "https://json-schema.org/draft/2020-12/schema",
19653
- "$id": "https://saktum.dev/schemas/envelope/0.1.json",
19654
- "title": "Saktum canonical call envelope",
19655
- "description": "Protocol-neutral description of one call between an agent and a service. Trust Check records calls in this shape; the gateway (2027) uses the same contract.",
19656
- "type": "object",
19657
- "required": [
19658
- "envelopeFormat",
19659
- "id",
19660
- "protocol",
19661
- "operation",
19662
- "target",
19663
- "timestamp"
19664
- ],
19665
- "additionalProperties": false,
19666
- "properties": {
19667
- "envelopeFormat": {
19668
- "const": "0.1"
19669
- },
19670
- "id": {
19671
- "type": "string"
19672
- },
19673
- "protocol": {
19674
- "enum": [
19675
- "mcp",
19676
- "a2a",
19677
- "http"
19678
- ]
19679
- },
19680
- "operation": {
19681
- "type": "string",
19682
- "description": "e.g. tools/call"
19683
- },
19684
- "tool": {
19685
- "type": "string"
19686
- },
19687
- "caller": {
19688
- "type": "object",
19689
- "properties": {
19690
- "agent": {
19691
- "type": "string"
19692
- },
19693
- "onBehalfOf": {
19694
- "type": "string"
19695
- }
19696
- }
19697
- },
19698
- "target": {
19699
- "type": "object",
19700
- "required": [
19701
- "service"
19702
- ],
19703
- "properties": {
19704
- "service": {
19705
- "type": "string"
19706
- },
19707
- "version": {
19708
- "type": "string"
19709
- }
19710
- }
19711
- },
19712
- "argumentsHash": {
19713
- "type": "string",
19714
- "pattern": "^sha256:[0-9a-f]{64}$"
19715
- },
19716
- "timestamp": {
19717
- "type": "string",
19718
- "format": "date-time"
19719
- },
19720
- "context": {
19721
- "type": "object",
19722
- "additionalProperties": false,
19723
- "description": "Optional governance context (Baseline 7.0): which task and business-process step this call belongs to. Policies may reference it; receipts echo it.",
19724
- "properties": {
19725
- "task": {
19726
- "type": "object",
19727
- "additionalProperties": false,
19728
- "properties": {
19729
- "id": {
19730
- "type": "string"
19731
- },
19732
- "purpose": {
19733
- "type": "string"
19734
- },
19735
- "permissions": {
19736
- "type": "array",
19737
- "items": {
19738
- "type": "string"
19739
- }
19740
- }
19741
- }
19742
- },
19743
- "process": {
19744
- "type": "object",
19745
- "additionalProperties": false,
19746
- "properties": {
19747
- "id": {
19748
- "type": "string"
19749
- },
19750
- "name": {
19751
- "type": "string"
19752
- },
19753
- "step": {
19754
- "type": "string"
19755
- }
19756
- }
19757
- },
19758
- "orchestrator": {
19759
- "type": "string",
19760
- "description": "e.g. camunda, temporal, n8n"
19761
- },
19762
- "rationale": {
19763
- "type": "string",
19764
- "maxLength": 280,
19765
- "description": "Optional short reason the agent states for this call (Baseline 7.9); recorded on the receipt so reasoning is auditable without storing conversations."
19766
- },
19767
- "executor": {
19768
- "type": "object",
19769
- "additionalProperties": false,
19770
- "description": "Optional (Baseline 8.4): the orchestrator that carried out the action on the agent's behalf, so receipts distinguish who decided, who executed and who authorised.",
19771
- "properties": {
19772
- "type": {
19773
- "type": "string",
19774
- "description": "e.g. orchestrator, rpa, gateway"
19775
- },
19776
- "id": {
19777
- "type": "string"
19778
- },
19779
- "name": {
19780
- "type": "string"
19781
- },
19782
- "instance": {
19783
- "type": "string"
19784
- }
19785
- }
19786
- }
19787
- }
19788
- }
19789
- }
19790
- }
19791
- `, "pack.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/pack/0.1.json",\n "title": "Saktum Trust Check test pack",\n "description": "A versioned set of checks. Packs are data, never code: steps use a closed set of actions, and any logic lives in named, engine-versioned analysers.",\n "type": "object",\n "required": [\n "packFormat",\n "id",\n "version",\n "category",\n "checks"\n ],\n "additionalProperties": false,\n "properties": {\n "packFormat": {\n "const": "0.1"\n },\n "id": {\n "type": "string",\n "pattern": "^[a-z][a-z0-9-]*$"\n },\n "version": {\n "type": "string",\n "pattern": "^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$"\n },\n "category": {\n "enum": [\n "conformance",\n "auth",\n "security",\n "agent-experience",\n "performance",\n "functional"\n ]\n },\n "description": {\n "type": "string"\n },\n "checks": {\n "type": "array",\n "minItems": 1,\n "items": {\n "$ref": "#/$defs/check"\n }\n },\n "signature": {\n "type": "object",\n "required": [\n "alg",\n "kid",\n "jws"\n ],\n "additionalProperties": false,\n "properties": {\n "alg": {\n "const": "EdDSA"\n },\n "kid": {\n "type": "string",\n "pattern": "^did:key:z"\n },\n "jws": {\n "type": "string"\n }\n },\n "description": "Detached JWS over the canonical pack without this member. Required for packs from the feed (v0.2)."\n }\n },\n "$defs": {\n "check": {\n "type": "object",\n "required": [\n "id",\n "title",\n "severity",\n "safety",\n "steps",\n "fix"\n ],\n "additionalProperties": false,\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^[a-z]+(\\\\.[a-z0-9-]+)+$"\n },\n "title": {\n "type": "string"\n },\n "severity": {\n "enum": [\n "critical",\n "high",\n "medium",\n "low",\n "info"\n ]\n },\n "safety": {\n "enum": [\n "passive",\n "active"\n ]\n },\n "scored": {\n "type": "boolean",\n "default": true\n },\n "appliesTo": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "transports": {\n "type": "array",\n "items": {\n "enum": [\n "stdio",\n "streamable-http"\n ]\n }\n },\n "protocol": {\n "type": "string",\n "description": "Minimum protocol revision, e.g. >=2025-03-26"\n }\n }\n },\n "steps": {\n "type": "array",\n "minItems": 1,\n "items": {\n "$ref": "#/$defs/step"\n }\n },\n "fix": {\n "type": "string"\n },\n "references": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "normative": {\n "type": "array",\n "description": "Baseline 4.1: the normative statements this check verifies, for the public traceability matrix.",\n "items": {\n "type": "object",\n "required": [\n "source",\n "level"\n ],\n "additionalProperties": false,\n "properties": {\n "source": {\n "type": "string",\n "description": "e.g. MCP specification, RFC 9728, OWASP MCP Top 10"\n },\n "version": {\n "type": "string",\n "description": "specification revision or date"\n },\n "clause": {\n "type": "string",\n "description": "section or requirement identifier"\n },\n "level": {\n "enum": [\n "MUST",\n "SHOULD",\n "MAY",\n "best-practice"\n ]\n }\n }\n }\n }\n }\n },\n "step": {\n "type": "object",\n "required": [\n "action"\n ],\n "additionalProperties": false,\n "properties": {\n "action": {\n "enum": [\n "mcp.initialize",\n "mcp.listTools",\n "mcp.callTool",\n "analyse"\n ]\n },\n "tool": {\n "type": "string"\n },\n "arguments": {\n "type": "object"\n },\n "analyser": {\n "type": "string"\n },\n "expect": {\n "$ref": "#/$defs/expectation"\n }\n }\n },\n "expectation": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "exists": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "isError": {\n "type": "boolean"\n },\n "errorCodeIn": {\n "type": "array",\n "items": {\n "type": "integer"\n }\n },\n "failed": {\n "type": "boolean",\n "description": "The call must not succeed: either a protocol error or a tool result flagged as an error."\n },\n "anyOf": {\n "type": "array",\n "items": {\n "$ref": "#/$defs/expectation"\n }\n }\n }\n }\n }\n}\n', "receipt.schema.json": `{
19792
- "$schema": "https://json-schema.org/draft/2020-12/schema",
19793
- "$id": "https://saktum.dev/schemas/receipt/0.1.json",
19794
- "title": "Saktum receipt",
19795
- "description": "A signed record of one call's outcome. Signatures use public-key cryptography so any third party can verify them without a shared secret.",
19796
- "type": "object",
19797
- "required": [
19798
- "receiptFormat",
19799
- "envelope",
19800
- "outcome",
19801
- "issuedAt",
19802
- "signatures"
19803
- ],
19804
- "additionalProperties": false,
19805
- "properties": {
19806
- "receiptFormat": {
19807
- "const": "0.1"
19808
- },
19809
- "envelope": {
19810
- "$ref": "https://saktum.dev/schemas/envelope/0.1.json"
19811
- },
19812
- "outcome": {
19813
- "enum": [
19814
- "allow",
19815
- "deny",
19816
- "error"
19817
- ]
19818
- },
19819
- "reason": {
19820
- "type": "string"
19821
- },
19822
- "issuedAt": {
19823
- "type": "string",
19824
- "format": "date-time"
19825
- },
19826
- "signatures": {
19827
- "type": "array",
19828
- "minItems": 1,
19829
- "items": {
19830
- "type": "object",
19831
- "required": [
19832
- "alg",
19833
- "kid",
19834
- "jws"
19835
- ],
19836
- "properties": {
19837
- "alg": {
19838
- "const": "EdDSA"
19839
- },
19840
- "kid": {
19841
- "type": "string"
19842
- },
19843
- "jws": {
19844
- "type": "string"
19845
- }
19846
- }
19847
- }
19848
- },
19849
- "explanation": {
19850
- "type": "string",
19851
- "maxLength": 500,
19852
- "description": "One plain-language sentence: what happened, which rule applied, who could have stopped it."
19853
- },
19854
- "context": {
19855
- "$ref": "https://saktum.dev/schemas/envelope/0.1.json#/properties/context"
19856
- },
19857
- "compensates": {
19858
- "type": "string",
19859
- "description": "Optional (Baseline 8.4): id of the original envelope or receipt that this call reverses (compensation transaction)."
19860
- }
19861
- }
19862
- }
19863
- `, "result.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/result/0.1.json",\n "title": "Saktum Trust Check result",\n "description": "The canonical result of one run. Every report format is rendered from this model. Evidence is a hash plus a short, sanitised excerpt; raw payloads never appear.",\n "type": "object",\n "required": [\n "resultFormat",\n "tool",\n "target",\n "packs",\n "findings",\n "scores",\n "metrics",\n "run"\n ],\n "additionalProperties": false,\n "properties": {\n "resultFormat": {\n "const": "0.1"\n },\n "tool": {\n "type": "object",\n "required": [\n "name",\n "version"\n ],\n "additionalProperties": false,\n "properties": {\n "name": {\n "const": "saktum-trust-check"\n },\n "version": {\n "type": "string"\n }\n }\n },\n "target": {\n "type": "object",\n "required": [\n "transport",\n "description"\n ],\n "additionalProperties": false,\n "properties": {\n "transport": {\n "enum": [\n "stdio",\n "streamable-http"\n ]\n },\n "description": {\n "type": "string"\n },\n "protocolVersion": {\n "type": "string"\n },\n "serverInfo": {\n "type": "object"\n },\n "toolsFingerprint": {\n "type": "string",\n "pattern": "^sha256:[0-9a-f]{64}$"\n },\n "toolCount": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "packs": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "id",\n "version",\n "hash"\n ],\n "additionalProperties": false,\n "properties": {\n "id": {\n "type": "string"\n },\n "version": {\n "type": "string"\n },\n "hash": {\n "type": "string",\n "pattern": "^sha256:[0-9a-f]{64}$"\n }\n }\n }\n },\n "findings": {\n "type": "array",\n "items": {\n "$ref": "#/$defs/finding"\n }\n },\n "scores": {\n "type": "object",\n "required": [\n "overall",\n "capped",\n "categories"\n ],\n "additionalProperties": false,\n "properties": {\n "overall": {\n "type": [\n "integer",\n "null"\n ],\n "minimum": 0,\n "maximum": 100\n },\n "capped": {\n "type": "boolean"\n },\n "categories": {\n "type": "object",\n "additionalProperties": {\n "type": [\n "integer",\n "null"\n ]\n }\n }\n }\n },\n "metrics": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "contextCostTokens": {\n "type": "integer",\n "minimum": 0\n },\n "largestTools": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "tool",\n "tokens"\n ],\n "properties": {\n "tool": {\n "type": "string"\n },\n "tokens": {\n "type": "integer"\n }\n }\n }\n },\n "contextCostPer1kTurnsUsd": {\n "type": "number",\n "minimum": 0,\n "description": "Estimated cost of loading the tool definitions on 1,000 agent turns at pricePerMTokUsd. Reported only."\n },\n "pricePerMTokUsd": {\n "type": "number",\n "minimum": 0\n },\n "performance": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "initMs": {\n "type": "integer",\n "minimum": 0\n },\n "listMs": {\n "type": "integer",\n "minimum": 0\n },\n "listBytes": {\n "type": "integer",\n "minimum": 0\n },\n "rssMb": {\n "type": "number",\n "minimum": 0\n },\n "cpuPct": {\n "type": "number",\n "minimum": 0\n },\n "burst": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "requests": {\n "type": "integer"\n },\n "ok": {\n "type": "integer"\n },\n "rateLimited": {\n "type": "integer"\n },\n "errors": {\n "type": "integer"\n },\n "p95Ms": {\n "type": "integer"\n }\n }\n }\n }\n }\n }\n },\n "run": {\n "type": "object",\n "required": [\n "startedAt",\n "durationMs",\n "mode",\n "runner",\n "sandbox"\n ],\n "additionalProperties": false,\n "properties": {\n "startedAt": {\n "type": "string",\n "format": "date-time"\n },\n "durationMs": {\n "type": "integer",\n "minimum": 0\n },\n "mode": {\n "enum": [\n "passive",\n "active"\n ]\n },\n "runner": {\n "enum": [\n "self",\n "hosted"\n ],\n "description": "self: run and signed by the user, proves integrity not independence. hosted: run and signed by Saktum (later)."\n },\n "sandbox": {\n "enum": [\n "none",\n "docker"\n ],\n "description": "Whether local servers ran inside a container sandbox."\n }\n }\n },\n "signature": {\n "type": "object",\n "required": [\n "alg",\n "kid",\n "jws"\n ],\n "additionalProperties": false,\n "properties": {\n "alg": {\n "const": "EdDSA"\n },\n "kid": {\n "type": "string",\n "pattern": "^did:key:z"\n },\n "jws": {\n "type": "string"\n }\n }\n },\n "grade": {\n "enum": [\n "A",\n "B",\n "C",\n "D",\n "F",\n null\n ],\n "description": "Letter grade from the trust score: A 90-100, B 80-89, C 70-79, D 50-69, F below 50 or any failed critical check."\n },\n "summary": {\n "type": "array",\n "maxItems": 5,\n "items": {\n "type": "string",\n "maxLength": 400\n },\n "description": "Plain-language summary sentences shown first in every report."\n },\n "assuranceLevel": {\n "enum": [\n "L1",\n "L2",\n "L3",\n "L4"\n ],\n "description": "L1 self-tested (Saktum Check); L2 independently tested; L3 certified; L4 continuously certified."\n },\n "readiness": {\n "description": "Agent readiness: a second grade beside trust (annotations, descriptions, context cost), never mixed into the trust score.",\n "oneOf": [\n {\n "type": "null"\n },\n {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "score",\n "grade",\n "toolsAnnotated",\n "toolsDescribed",\n "toolCount",\n "contextTokens"\n ],\n "properties": {\n "score": {\n "type": "integer",\n "minimum": 0,\n "maximum": 100\n },\n "grade": {\n "enum": [\n "A",\n "B",\n "C",\n "D",\n "F",\n null\n ]\n },\n "toolsAnnotated": {\n "type": "integer",\n "minimum": 0\n },\n "toolsDescribed": {\n "type": "integer",\n "minimum": 0\n },\n "toolCount": {\n "type": "integer",\n "minimum": 0\n },\n "contextTokens": {\n "type": "integer",\n "minimum": 0\n },\n "topImprovement": {\n "type": "string",\n "maxLength": 300\n }\n }\n }\n ]\n },\n "coverage": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "trustChecksRun": {\n "type": "integer",\n "minimum": 0\n }\n }\n }\n },\n "$defs": {\n "finding": {\n "type": "object",\n "required": [\n "check",\n "pack",\n "status",\n "severity",\n "title"\n ],\n "additionalProperties": false,\n "properties": {\n "check": {\n "type": "string"\n },\n "pack": {\n "type": "string"\n },\n "status": {\n "enum": [\n "pass",\n "fail",\n "skipped",\n "inconclusive",\n "info"\n ]\n },\n "severity": {\n "enum": [\n "critical",\n "high",\n "medium",\n "low",\n "info"\n ]\n },\n "scored": {\n "type": "boolean"\n },\n "title": {\n "type": "string"\n },\n "subject": {\n "type": "string"\n },\n "message": {\n "type": "string"\n },\n "fix": {\n "type": "string"\n },\n "references": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "evidence": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "hash": {\n "type": "string"\n },\n "excerpt": {\n "type": "string",\n "maxLength": 240\n }\n }\n }\n }\n }\n }\n}\n', "test-cases.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/test-cases/0.1.json",\n "title": "Saktum Trust Check functional test cases (saktum.tests.yaml)",\n "type": "object",\n "required": ["testsFormat", "tests"],\n "additionalProperties": false,\n "properties": {\n "testsFormat": { "const": "0.1" },\n "tests": {\n "type": "array",\n "items": {\n "type": "object",\n "required": ["id", "tool", "input", "expect"],\n "additionalProperties": false,\n "properties": {\n "id": { "type": "string" },\n "tool": { "type": "string" },\n "input": { "type": "object" },\n "sideEffects": { "type": "boolean", "default": false, "description": "Tests with side effects run only against owned targets." },\n "expect": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "isError": { "type": "boolean" },\n "textContains": { "type": "string" },\n "structured": { "type": "object" },\n "outputSchema": { "type": "boolean" },\n "latencyMs": { "type": "object", "properties": { "lt": { "type": "integer" } }, "additionalProperties": false }\n }\n }\n }\n }\n }\n }\n}\n' };
19864
- var EMBEDDED_PACKS = { "agent-experience.yaml": 'packFormat: "0.1"\nid: agent-experience\nversion: 0.1.0\ncategory: agent-experience\ndescription: How easily and cheaply agents can use the server. Reported, never part of the trust score.\nchecks:\n - id: ax.context-cost\n title: Context cost of tool definitions\n severity: info\n safety: passive\n scored: false\n steps: [{ action: analyse, analyser: context-cost }]\n fix: Shorten long descriptions, split large servers, and drop tools agents rarely need.\n - id: ax.annotations\n title: Tools declare annotations\n severity: low\n safety: passive\n steps: [{ action: analyse, analyser: annotations-present }]\n fix: Set readOnlyHint, destructiveHint, idempotentHint and openWorldHint on every tool so clients can warn before risky actions.\n references: ["MCP specification: tool annotations", "OWASP MCP Top 10: MCP02 Privilege Escalation via Scope Creep (undeclared write and destructive tools)"]\n - id: ax.short-descriptions\n title: Tools have usable descriptions\n severity: low\n safety: passive\n steps: [{ action: analyse, analyser: short-descriptions }]\n fix: Describe what the tool does, when to use it and when not to, in at least a full sentence.\n', "auth.yaml": `packFormat: "0.1"
19865
- id: auth
19866
- version: 0.1.0
19867
- category: auth
19868
- description: Sign-in for remote servers, checked from the outside without credentials. Follows the MCP authorization specification and the OAuth RFCs it builds on.
19869
- checks:
19870
- - id: auth.https
19871
- title: Served over HTTPS
19872
- severity: critical
19873
- safety: passive
19874
- appliesTo: { transports: [streamable-http] }
19875
- steps: [{ action: analyse, analyser: auth-https }]
19876
- fix: Serve the MCP endpoint over HTTPS (plain HTTP only on localhost during development).
19877
- references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization", "CWE-319"]
19878
- normative: [{ source: "MCP specification", version: "verify-latest", clause: "Authorization: communication security", level: MUST }, { source: "RFC 9700", clause: "OAuth security best current practice: TLS", level: MUST }]
19879
- - id: auth.unauthenticated
19880
- title: Whether sign-in is required
19881
- severity: info
19882
- safety: passive
19883
- scored: false
19884
- appliesTo: { transports: [streamable-http] }
19885
- steps: [{ action: analyse, analyser: auth-unauthenticated }]
19886
- fix: Require OAuth sign-in for any server that exposes user data or actions.
19887
- references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]
19888
- - id: auth.www-authenticate
19889
- title: Refusals point clients to the resource metadata
19890
- severity: high
19891
- safety: passive
19892
- appliesTo: { transports: [streamable-http] }
19893
- steps: [{ action: analyse, analyser: auth-www-authenticate }]
19894
- fix: Answer unauthenticated requests with 401 and a header such as WWW-Authenticate Bearer resource_metadata="https://your-server/.well-known/oauth-protected-resource".
19895
- references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]
19896
- normative: [{ source: "RFC 9728", clause: "Section 5.1, WWW-Authenticate response", level: MUST }, { source: "MCP specification", version: "verify-latest", clause: "Authorization: authorization server discovery", level: MUST }]
19897
- - id: auth.resource-metadata
19898
- title: Protected resource metadata is published and correct
19899
- severity: high
19900
- safety: passive
19901
- appliesTo: { transports: [streamable-http] }
19902
- steps: [{ action: analyse, analyser: auth-resource-metadata }]
19903
- fix: Publish /.well-known/oauth-protected-resource with "resource" set to this server's URL and "authorization_servers" listing your HTTPS authorization server.
19904
- references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]
19905
- normative: [{ source: "RFC 9728", clause: "Sections 2 and 3, metadata and well-known URI", level: MUST }]
19906
- - id: auth.server-metadata
19907
- title: Authorization server metadata is complete, with PKCE
19908
- severity: high
19909
- safety: passive
19910
- appliesTo: { transports: [streamable-http] }
19911
- steps: [{ action: analyse, analyser: auth-server-metadata }]
19912
- fix: Publish RFC 8414 metadata with issuer, HTTPS authorization and token endpoints, the code response type, and code_challenge_methods_supported including S256.
19913
- references: ["OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization"]
19914
- normative: [{ source: "RFC 8414", clause: "Sections 2 and 3", level: MUST }, { source: "RFC 7636", clause: "PKCE with S256", level: MUST }, { source: "MCP specification", version: "verify-latest", clause: "Authorization: PKCE required", level: MUST }]
19915
- - id: auth.invalid-token
19916
- title: Invalid tokens are rejected
19917
- severity: critical
19918
- safety: passive
19919
- appliesTo: { transports: [streamable-http] }
19920
- steps: [{ action: analyse, analyser: auth-invalid-token }]
19921
- fix: Validate every bearer token (signature or introspection, expiry, audience) and answer invalid ones with 401 and error="invalid_token".
19922
- references: ["OWASP MCP Top 10: MCP01 Token Mismanagement and Secret Exposure", "OWASP MCP Top 10: MCP07 Insufficient Authentication and Authorization", "CWE-287"]
19923
- normative: [{ source: "RFC 6750", clause: "Section 3.1, invalid_token", level: MUST }]
19924
- `, "conformance.yaml": `packFormat: "0.1"
19925
- id: conformance
19926
- version: 0.1.0
19927
- category: conformance
19928
- description: Does the server speak MCP correctly? Basis for every other check.
19929
- checks:
19930
- - id: conf.init.handshake
19931
- title: Initialize returns server info and capabilities
19932
- severity: high
19933
- safety: passive
19934
- steps: [{ action: analyse, analyser: handshake }]
19935
- fix: Return serverInfo (name, version) and a capabilities object from initialize.
19936
- normative: [{ source: "MCP specification", version: "verify-latest", clause: "Lifecycle: initialization (server returns capabilities and serverInfo)", level: MUST }]
19937
- references: ["MCP specification: lifecycle"]
19938
- - id: conf.tools.list
19939
- title: Tool list is returned
19940
- severity: high
19941
- safety: passive
19942
- steps: [{ action: mcp.listTools, expect: { exists: [tools] } }]
19943
- fix: Implement tools/list and return a tools array (empty if you have none).
19944
- normative: [{ source: "MCP specification", version: "verify-latest", clause: "Server features: tools, listing tools", level: MUST }]
19945
- references: ["MCP specification: tools"]
19946
- - id: conf.tools.schema-valid
19947
- title: Every input schema is a valid JSON Schema object
19948
- severity: high
19949
- safety: passive
19950
- steps: [{ action: analyse, analyser: tool-input-schemas }]
19951
- fix: Give every tool an inputSchema of type "object" that compiles as JSON Schema.
19952
- normative: [{ source: "MCP specification", version: "verify-latest", clause: "Tools: inputSchema is a JSON Schema object", level: MUST }]
19953
- references: ["MCP specification: tools", "JSON Schema 2020-12", "OWASP MCP Top 10: MCP05 Command Injection and Execution (input validation)"]
19954
- - id: conf.tools.names
19955
- title: Tool names are unique and use allowed characters
19956
- severity: medium
19957
- safety: passive
19958
- steps: [{ action: analyse, analyser: tool-names }]
19959
- fix: Use unique names of 1 to 128 characters from A-Z, a-z, 0-9, underscore, dot and hyphen.
19960
- references: ["MCP specification: tools"]
19961
- - id: conf.tools.unknown-not-success
19962
- title: Calling an unknown tool does not succeed
19963
- severity: high
19964
- safety: passive
19965
- steps:
19966
- - action: mcp.callTool
19967
- tool: saktum_trust_check_no_such_tool
19968
- arguments: {}
19969
- expect: { failed: true }
19970
- fix: Return an error for unknown tool names; never a successful result.
19971
- references: ["MCP specification: tools, error handling", "OWASP MCP Top 10: MCP08 Lack of Audit and Telemetry (false success hides actions)"]
19972
- - id: conf.tools.unknown-error-code
19973
- title: Unknown tools get the expected error
19974
- severity: low
19975
- safety: passive
19976
- steps:
19977
- - action: mcp.callTool
19978
- tool: saktum_trust_check_no_such_tool
19979
- arguments: {}
19980
- expect: { anyOf: [{ errorCodeIn: [-32602] }, { isError: true }] }
19981
- fix: Respond to an unknown tool name with JSON-RPC error -32602 (invalid params), as in the specification's example.
19982
- references: ["MCP specification: tools, error handling", "JSON-RPC 2.0"]
19983
- `, "performance.yaml": `packFormat: "0.1"
19984
- id: performance
19985
- version: 0.1.0
19986
- category: performance
19987
- description: Speed and resource use, reported as information and never part of the trust score. The burst test runs only with --active.
19988
- checks:
19989
- - id: perf.startup
19990
- title: Start-up and handshake time
19991
- severity: info
19992
- safety: passive
19993
- scored: false
19994
- steps: [{ action: analyse, analyser: perf-startup }]
19995
- fix: Defer heavy initialisation until the first call that needs it; agents and clients time out on slow starts.
19996
- - id: perf.latency
19997
- title: Tool-list latency and size
19998
- severity: info
19999
- safety: passive
20000
- scored: false
20001
- steps: [{ action: analyse, analyser: perf-latency }]
20002
- fix: Keep tools/list fast and small; cache it and trim long descriptions.
20003
- - id: perf.memory
20004
- title: Memory and CPU of a local server
20005
- severity: info
20006
- safety: passive
20007
- scored: false
20008
- appliesTo: { transports: [stdio] }
20009
- steps: [{ action: analyse, analyser: perf-memory }]
20010
- fix: Reduce idle memory and CPU; local servers run beside the user's other tools.
20011
- - id: perf.burst
20012
- title: Behaviour under a short burst (rate limiting)
20013
- severity: info
20014
- safety: active
20015
- scored: false
20016
- steps: [{ action: analyse, analyser: perf-burst }]
20017
- fix: Answer overload with HTTP 429 and Retry-After instead of errors, and set limits per client.
20018
- references: ["OWASP MCP Top 10: MCP02 Privilege Escalation via Scope Creep (resource abuse)", "CWE-770"]
20019
- `, "security.yaml": 'packFormat: "0.1"\nid: security\nversion: 0.1.0\ncategory: security\ndescription: Passive security checks on what the server tells agents and users.\nchecks:\n - id: sec.description.hidden-instructions\n title: No instructions to the agent in tool descriptions or schemas\n severity: critical\n safety: passive\n steps: [{ action: analyse, analyser: hidden-instructions }]\n fix: Describe what each tool does; never instruct the agent (for example to read other data, send data elsewhere or hide actions from the user).\n normative: [{ source: "OWASP MCP Top 10", clause: "MCP03 Tool Poisoning", level: best-practice }]\n references: ["MCP security best practices", "CWE-1427", "OWASP MCP Top 10: MCP03 Tool Poisoning", "OWASP MCP Top 10: MCP06 Intent Flow Subversion"]\n - id: sec.description.invisible-text\n title: No invisible or bidirectional control characters\n severity: high\n safety: passive\n steps: [{ action: analyse, analyser: invisible-text }]\n fix: Remove zero-width and bidirectional control characters from names, descriptions and schemas.\n references: ["CWE-1007", "OWASP MCP Top 10: MCP03 Tool Poisoning"]\n - id: sec.description.control-characters\n title: No escape sequences or control characters\n severity: high\n safety: passive\n steps: [{ action: analyse, analyser: control-characters }]\n fix: Remove terminal escape sequences and control characters; clients may print tool text to a terminal.\n references: ["CWE-150", "OWASP MCP Top 10: MCP03 Tool Poisoning"]\n - id: sec.secrets.exposed\n title: No secrets in tool definitions or responses\n severity: critical\n safety: passive\n steps: [{ action: analyse, analyser: secrets }]\n fix: Remove keys, tokens and passwords from descriptions, schemas, defaults, examples and error messages; load them from a secret store at runtime.\n references: ["OWASP MCP Top 10: MCP01 Token Mismanagement and Secret Exposure", "CWE-798", "CWE-200"]\n normative: [{ source: "OWASP MCP Top 10", clause: "MCP01 Token Mismanagement and Secret Exposure", level: best-practice }]\n - id: sec.errors.leakage\n title: Errors do not expose internals\n severity: medium\n safety: passive\n steps: [{ action: analyse, analyser: error-leakage }]\n fix: Return short, actionable error messages; log stack traces, file paths and database errors on the server only.\n references: ["OWASP MCP Top 10: MCP08 Lack of Audit and Telemetry (errors leak internals)", "CWE-209"]\n normative: [{ source: "OWASP MCP Top 10", clause: "Information exposure through errors", level: best-practice }]\n\n' };
20020
-
20021
- // packages/testkit-core/dist/contracts.js
20022
- var pick = (m) => {
20023
- let x = m;
20024
- while (x && typeof x !== "function" && x.default)
20025
- x = x.default;
20026
- return x;
20027
- };
20028
- var Ajv2020 = pick(Ajv2020Module);
20029
- var Ajv2019 = pick(Ajv2019Module);
20030
- var AjvDraft7 = pick(AjvDraft7Module);
20031
- var addFormats = pick(addFormatsModule);
20032
- var contractsDir = fileURLToPath(new URL("../../../contracts/", import.meta.url));
20033
- var ajv = new Ajv2020({ allErrors: true, strict: false });
20034
- addFormats(ajv);
20035
- function contractText(f) {
20036
- if (existsSync2(contractsDir + f))
20037
- return readFileSync2(contractsDir + f, "utf8");
20038
- const t = EMBEDDED_CONTRACTS[f];
20039
- if (!t)
20040
- throw new Error(`contract ${f} not found`);
20041
- return t;
20042
- }
20043
- for (const f of ["envelope.schema.json", "receipt.schema.json", "pack.schema.json", "result.schema.json", "test-cases.schema.json"]) {
20044
- ajv.addSchema(JSON.parse(contractText(f)), f);
20045
- }
20046
- function compileContract(file) {
20047
- const v = ajv.getSchema(file);
20048
- if (!v)
20049
- throw new Error(`unknown contract ${file}`);
20050
- return v;
20051
- }
20052
- function schemaDialect(schema) {
20053
- const id = schema && typeof schema === "object" ? schema.$schema : void 0;
20054
- if (id === void 0)
20055
- return "2020-12";
20056
- const s = String(id);
20057
- if (/draft-04/.test(s))
20058
- return "draft-04";
20059
- if (/draft-06/.test(s))
20060
- return "draft-06";
20061
- if (/draft-07/.test(s))
20062
- return "draft-07";
20063
- if (/2019-09/.test(s))
20064
- return "2019-09";
20065
- if (/2020-12/.test(s))
20066
- return "2020-12";
20067
- return "unknown";
20068
- }
20069
- function compileUntrustedSchema(schema) {
20070
- try {
20071
- if (!schema || typeof schema !== "object" || Array.isArray(schema))
20072
- return { ok: false, error: "the schema is not a JSON object" };
20073
- const dialect = schemaDialect(schema);
20074
- if (dialect === "unknown")
20075
- return { ok: false, error: `unrecognised $schema dialect ${JSON.stringify(schema.$schema).slice(0, 80)}` };
20076
- const { $schema: _ignored, ...body } = schema;
20077
- const Ctor = dialect === "2020-12" ? Ajv2020 : dialect === "2019-09" ? Ajv2019 : AjvDraft7;
20078
- new Ctor({ strict: false, allErrors: false, validateSchema: true, logger: false }).compile(body);
20079
- return { ok: true };
20080
- } catch (e) {
20081
- return { ok: false, error: e.message };
20082
- }
20083
- }
20084
-
20085
20161
  // packages/testkit-core/dist/packs.js
20162
+ init_contracts();
20163
+ init_embedded();
20086
20164
  var validatePack = compileContract("pack.schema.json");
20087
20165
  var PackError = class extends Error {
20088
20166
  };
@@ -20118,6 +20196,273 @@ function loadEmbeddedPacks(opts) {
20118
20196
  return Object.keys(EMBEDDED_PACKS).sort().map((f) => loadPackText(EMBEDDED_PACKS[f], `embedded:${f}`, opts));
20119
20197
  }
20120
20198
 
20199
+ // packages/testkit-core/dist/index.js
20200
+ init_contracts();
20201
+
20202
+ // packages/testkit-core/dist/analysers.js
20203
+ init_contracts();
20204
+
20205
+ // packages/testkit-core/dist/capabilities.js
20206
+ var CAPABILITY_LABELS = {
20207
+ "reads-private-data": "reads private or account data",
20208
+ "untrusted-content": "brings in untrusted content (web pages, emails, documents)",
20209
+ network: "reaches the network",
20210
+ "code-execution": "runs code or commands",
20211
+ filesystem: "reads or writes files",
20212
+ "writes-or-deletes": "changes or deletes data",
20213
+ "sends-messages": "sends messages or posts content",
20214
+ money: "moves money or makes purchases"
20215
+ };
20216
+ var RULES = [
20217
+ { cap: "code-execution", name: /(^|[_-])(exec|execute|eval|shell|bash|terminal|psql|run_command|run_code|run_script)([_-]|$)|exec_in_/i, text: /\b(execute|run)s? (a |an |the )?(shell|terminal|bash|command|script|code|program|sql|query)\b/i, strong: /\b(arbitrary (code|commands?)|shell commands?|(executes?|runs?) (shell|terminal|bash) commands?|runs? (javascript|python) code|starts? (a |an )?(new )?(terminal|shell) (process|session))\b/i, arg: /^(command|cmd|script|code|shell)$/i },
20218
+ { cap: "filesystem", name: /(^|[_-])(read_file|write_file|edit_file|move_file|list_directory|create_directory|directory_tree|filesystem|fs)([_-]|$)/i, text: /\b(local )?file ?system\b|\bon (the )?(local )?(disk|machine)\b|\b(files?|director(y|ies)) (on|in) the (user'?s )?(computer|machine|disk)\b/i, arg: /^(path|filepath|file_path|directory|dir)$/i },
20219
+ { cap: "network", name: /(^|[_-])(fetch|http|download|webhook|crawl|scrape|browse|navigate)([_-]|$)/i, text: /\b(fetch(es)? (a |the )?(url|web ?page|website)|http requests?|crawls?|scrapes?|web ?hooks?|downloads? .{0,20} from)\b/i, strong: /\b(http requests?|fetch(es)? (a |the |any )?(url|web ?page|website))\b/i, arg: /^(url|uri|endpoint|webhook|href)$/i },
20220
+ { cap: "untrusted-content", name: /(^|[_-])(fetch|crawl|scrape|browse|web_search|read_email|get_email|read_emails|read_message|read_messages)([_-]|$)/i, text: /\b(web ?pages?|websites?|internet|emails?|inbox|scrap(e|es|ing)|crawl(s|ing)?)\b/i, strong: /\b(search(es)? the (web|internet)|web search|scrap(e|es|ing) (web|pages|sites)|crawl(s|ing)? (a |the )?(web|site|website)|web ?pages?)\b/i },
20221
+ { cap: "reads-private-data", arg: /^(sql)$/i, name: /(^|[_-])(query|sql|customers?|contacts?|inbox|calendar|crm|database|db)([_-]|$)/i, text: /\b(reads?|retrieves?|gets?|lists?|search(es)?|quer(y|ies)|looks? up|fetch(es)?|returns?)\b.{0,40}\b(database|customers?|contacts?|account (data|details)|personal|private|inbox|calendar|crm)\b/i },
20222
+ { cap: "writes-or-deletes", name: /(^|[_-])(create|update|delete|remove|write|insert|upsert|drop|patch|edit|modify|move|rename|overwrite|reset|commit|push|purge)([_-]|$)/i, text: /\b(deletes?|removes?|overwrites?|modif(y|ies)|updates?|creates?|writes?) (a |an |the |one or more )?(new )?\w+/i },
20223
+ { cap: "sends-messages", name: /(^|[_-])(send|notify|reply|tweet|sms|send_message|send_email|post_message)([_-]|$)/i, text: /\bsends? (an? )?(new )?(email|message|sms|notification)|\bposts? (a |an )?(new )?(message|comment|tweet|reply)\b|\brepl(y|ies) to (a |the )?(specific )?(message|thread|email)/i, strong: /\bsends? (an? )?(email|sms|text message|slack message)s?\b|\bposts? (a |an )?(new )?message to (a |the )?(slack )?channel\b/i },
20224
+ { cap: "money", name: /(^|[_-])(pay|payment|payments|charge|refund|refunds|invoice|invoices|payout|purchase|billing)([_-]|$)/i, text: /\b(payments?|charges? (a |the )?(card|customer)|refunds?|invoices?|transfers? (funds|money)|purchases?)\b/i, strong: /\b(refunds? (a |the )?(payment|charge)|charges? (a |the )?(card|customer)|creates? (a |an )?(invoice|payment|payout))\b/i }
20225
+ ];
20226
+ function capabilityProfile(tools) {
20227
+ const found = /* @__PURE__ */ new Map();
20228
+ const add = (c, tool, declared = false) => {
20229
+ const e = found.get(c) ?? { tools: /* @__PURE__ */ new Set(), declared: false };
20230
+ e.tools.add(sanitizeText(tool, 60));
20231
+ e.declared ||= declared;
20232
+ found.set(c, e);
20233
+ };
20234
+ for (const t of tools) {
20235
+ const a = t.annotations ?? {};
20236
+ if (a.openWorldHint === true)
20237
+ add("network", t.name, true);
20238
+ if (a.destructiveHint === true || a.readOnlyHint === false)
20239
+ add("writes-or-deletes", t.name, true);
20240
+ const args = Object.keys((t.inputSchema ?? {}).properties ?? {});
20241
+ const desc = (t.description ?? "").trim().split(/(?<=[.!?])\s/)[0].slice(0, 280);
20242
+ for (const r of RULES) {
20243
+ if (r.cap === "writes-or-deletes" && a.readOnlyHint === true)
20244
+ continue;
20245
+ const signals = Number(r.name.test(t.name)) + Number(r.text.test(desc)) + Number(Boolean(r.arg && args.some((x) => r.arg.test(x))));
20246
+ if (signals >= 2 || r.strong && r.strong.test(desc))
20247
+ add(r.cap, t.name);
20248
+ }
20249
+ }
20250
+ const has2 = (c) => found.has(c);
20251
+ const lethalTrifecta = has2("reads-private-data") && has2("untrusted-content") && (has2("network") || has2("sends-messages"));
20252
+ const order = Object.keys(CAPABILITY_LABELS);
20253
+ return {
20254
+ capabilities: order.filter(has2).map((c) => ({ capability: c, label: CAPABILITY_LABELS[c], tools: [...found.get(c).tools].slice(0, 8), basis: found.get(c).declared ? "declared" : "inferred" })),
20255
+ lethalTrifecta,
20256
+ note: "Inferred from annotations, tool names, descriptions and argument names; it describes what the tools appear able to do, not a finding."
20257
+ };
20258
+ }
20259
+
20260
+ // packages/testkit-core/dist/provider.js
20261
+ var words = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
20262
+ var READ = /* @__PURE__ */ new Set(["get", "list", "read", "search", "find", "fetch", "query", "describe", "show", "view", "lookup", "count", "check", "status", "retrieve", "browse", "inspect", "resolve", "validate", "analyze", "analyse", "summarize", "summarise", "explain", "compare", "preview", "info", "stats", "download", "export", "diff", "log", "history", "whoami", "ping", "health", "extract", "crawl", "scrape", "research", "map", "summary", "lookup", "tail", "watch"]);
20263
+ var DESTROY = /* @__PURE__ */ new Set(["delete", "remove", "drop", "purge", "destroy", "reset", "revoke", "cancel", "terminate", "kill", "wipe", "truncate", "overwrite", "uninstall", "unpublish", "archive"]);
20264
+ var WRITE = /* @__PURE__ */ new Set(["create", "add", "insert", "update", "set", "put", "patch", "edit", "write", "save", "upload", "send", "post", "publish", "deploy", "run", "execute", "exec", "start", "stop", "restart", "move", "rename", "merge", "commit", "push", "install", "enable", "disable", "assign", "invite", "approve", "pay", "charge", "refund", "transfer", "book", "order", "replace", "import", "sync", "trigger", "schedule", "close", "open", "submit", "apply", "generate", "upsert"]);
20265
+ var IDEMPOTENT_WRITE = /* @__PURE__ */ new Set(["set", "put", "update", "upsert", "enable", "disable", "replace"]);
20266
+ function suggestAnnotations(tools) {
20267
+ const caps = capabilityProfile(tools).capabilities;
20268
+ const hasCap = (tool, c) => caps.some((x) => x.capability === c && x.tools.includes(sanitizeText(tool, 60)));
20269
+ return tools.map((t) => {
20270
+ const w = words(t.name);
20271
+ const verb = w.find((x) => READ.has(x) || DESTROY.has(x) || WRITE.has(x));
20272
+ const current = t.annotations && Object.keys(t.annotations).length ? t.annotations : void 0;
20273
+ const openWorld = hasCap(t.name, "network") || hasCap(t.name, "untrusted-content") || hasCap(t.name, "sends-messages") ? true : void 0;
20274
+ let suggested;
20275
+ let reason;
20276
+ if (verb && DESTROY.has(verb)) {
20277
+ suggested = { readOnlyHint: false, destructiveHint: true, idempotentHint: verb === "delete" || verb === "remove" ? true : void 0, openWorldHint: openWorld };
20278
+ reason = `"${verb}" usually deletes or overwrites data`;
20279
+ } else if (verb && WRITE.has(verb)) {
20280
+ suggested = { readOnlyHint: false, destructiveHint: false, idempotentHint: IDEMPOTENT_WRITE.has(verb) ? true : void 0, openWorldHint: openWorld };
20281
+ reason = `"${verb}" usually changes data without destroying it`;
20282
+ } else if (verb && READ.has(verb)) {
20283
+ suggested = { readOnlyHint: true, openWorldHint: openWorld };
20284
+ reason = `"${verb}" usually only reads`;
20285
+ } else {
20286
+ reason = "the name does not say whether it reads or changes data: decide and annotate it";
20287
+ }
20288
+ const clean = suggested ? Object.fromEntries(Object.entries(suggested).filter(([, v]) => v !== void 0)) : void 0;
20289
+ let conflict;
20290
+ if (current?.readOnlyHint === true && verb && (DESTROY.has(verb) || WRITE.has(verb)))
20291
+ conflict = `declared read-only, but "${verb}" suggests it changes data`;
20292
+ if (current?.destructiveHint === false && verb && DESTROY.has(verb))
20293
+ conflict = `declared non-destructive, but "${verb}" suggests it deletes or overwrites`;
20294
+ return { tool: t.name, current, suggested: clean, reason, confidence: verb ? "likely" : "review", conflict };
20295
+ });
20296
+ }
20297
+ var tsValue = (o) => `{ ${Object.entries(o).map(([k, v]) => `${k}: ${v}`).join(", ")} }`;
20298
+ var pyValue = (o) => `ToolAnnotations(${Object.entries(o).map(([k, v]) => `${k}=${v === true ? "True" : v === false ? "False" : v}`).join(", ")})`;
20299
+ function renderFix(tools, format = "ts") {
20300
+ const s = suggestAnnotations(tools);
20301
+ if (format === "json")
20302
+ return JSON.stringify(s, null, 2) + "\n";
20303
+ const todo = s.filter((x) => !x.current && x.suggested);
20304
+ const review = s.filter((x) => !x.current && !x.suggested);
20305
+ const conflicts = s.filter((x) => x.conflict);
20306
+ const lines = [];
20307
+ lines.push(`Saktum fix: annotation suggestions for ${tools.length} tools (review each before applying; Saktum suggests, you decide).`);
20308
+ lines.push(`${todo.length} to add, ${review.length} need your judgement, ${conflicts.length} possible conflicts, ${s.filter((x) => x.current && !x.conflict).length} already annotated.`);
20309
+ lines.push("");
20310
+ if (format === "py")
20311
+ lines.push("from mcp.types import ToolAnnotations", "");
20312
+ for (const x of todo) {
20313
+ lines.push(format === "py" ? `# ${sanitizeText(x.tool, 60)}: ${x.reason}
20314
+ @mcp.tool(annotations=${pyValue(x.suggested)})` : `// ${sanitizeText(x.tool, 60)}: ${x.reason}
20315
+ annotations: ${tsValue(x.suggested)},`);
20316
+ lines.push("");
20317
+ }
20318
+ if (review.length) {
20319
+ lines.push(format === "py" ? "# Decide for these tools:" : "// Decide for these tools:");
20320
+ for (const x of review)
20321
+ lines.push(`${format === "py" ? "#" : "//"} ${sanitizeText(x.tool, 60)}: ${x.reason}`);
20322
+ lines.push("");
20323
+ }
20324
+ if (conflicts.length) {
20325
+ lines.push(format === "py" ? "# Possible conflicts with your current annotations:" : "// Possible conflicts with your current annotations:");
20326
+ for (const x of conflicts)
20327
+ lines.push(`${format === "py" ? "#" : "//"} ${sanitizeText(x.tool, 60)}: ${x.conflict}`);
20328
+ lines.push("");
20329
+ }
20330
+ const short = tools.filter((t) => (t.description ?? "").trim().length < 20);
20331
+ if (short.length)
20332
+ lines.push(`${format === "py" ? "#" : "//"} Also write a one-sentence description (what it does, when to use it) for: ${short.map((t) => sanitizeText(t.name, 40)).join(", ")}`);
20333
+ const cost = contextCost(tools);
20334
+ if (cost.contextCostTokens > 1e4)
20335
+ lines.push(`${format === "py" ? "#" : "//"} Context cost is ${cost.contextCostTokens.toLocaleString("en-US")} tokens per turn; the largest tools are ${cost.largestTools.slice(0, 3).map((x) => `${x.tool} (${x.tokens})`).join(", ")}: shorten their descriptions and schemas first.`);
20336
+ return lines.join("\n").trimEnd() + "\n";
20337
+ }
20338
+ function toolsLock(tools, server) {
20339
+ const sorted = [...tools].sort((a, b) => a.name.localeCompare(b.name));
20340
+ return { lockFormat: "0.1", server, createdAt: (/* @__PURE__ */ new Date()).toISOString(), tools: sorted.map((t) => ({ ...t, hash: sha256Tag(canonicalize(t)) })) };
20341
+ }
20342
+ var typeOf = (s) => JSON.stringify(s?.type ?? null);
20343
+ function schemaChanges(tool, label, a, b, out, forInput) {
20344
+ if (!a && !b)
20345
+ return;
20346
+ if (a && !b) {
20347
+ out.push({ tool, kind: forInput ? "change" : "breaking", detail: `${label} schema removed` });
20348
+ return;
20349
+ }
20350
+ if (!a && b) {
20351
+ out.push({ tool, kind: "addition", detail: `${label} schema added` });
20352
+ return;
20353
+ }
20354
+ const pa = a.properties ?? {}, pb = b.properties ?? {};
20355
+ const ra = new Set(a.required ?? []), rb = new Set(b.required ?? []);
20356
+ for (const k of Object.keys(pa)) {
20357
+ if (!(k in pb)) {
20358
+ out.push({ tool, kind: "breaking", detail: `${label} field "${k}" removed` });
20359
+ continue;
20360
+ }
20361
+ if (typeOf(pa[k]) !== typeOf(pb[k]))
20362
+ out.push({ tool, kind: "breaking", detail: `${label} field "${k}" changed type from ${typeOf(pa[k])} to ${typeOf(pb[k])}` });
20363
+ const ea = pa[k].enum, eb = pb[k].enum;
20364
+ if (Array.isArray(ea) && Array.isArray(eb)) {
20365
+ const removed = ea.filter((v) => !eb.some((w) => JSON.stringify(w) === JSON.stringify(v)));
20366
+ const added = eb.filter((v) => !ea.some((w) => JSON.stringify(w) === JSON.stringify(v)));
20367
+ if (removed.length)
20368
+ out.push({ tool, kind: forInput ? "breaking" : "change", detail: `${label} field "${k}" no longer allows ${removed.map((v) => JSON.stringify(v)).join(", ")}` });
20369
+ if (added.length)
20370
+ out.push({ tool, kind: forInput ? "addition" : "breaking", detail: `${label} field "${k}" now allows ${added.map((v) => JSON.stringify(v)).join(", ")}` });
20371
+ }
20372
+ }
20373
+ for (const k of Object.keys(pb))
20374
+ if (!(k in pa))
20375
+ out.push({ tool, kind: forInput && rb.has(k) ? "breaking" : "addition", detail: `${label} field "${k}" added${forInput && rb.has(k) ? " as required" : ""}` });
20376
+ if (forInput) {
20377
+ for (const k of rb)
20378
+ if (!ra.has(k) && k in pa)
20379
+ out.push({ tool, kind: "breaking", detail: `input field "${k}" is now required` });
20380
+ }
20381
+ if (!forInput) {
20382
+ for (const k of ra)
20383
+ if (!rb.has(k) && k in pb)
20384
+ out.push({ tool, kind: "breaking", detail: `output field "${k}" is no longer guaranteed` });
20385
+ }
20386
+ if (forInput && a.additionalProperties !== false && b.additionalProperties === false)
20387
+ out.push({ tool, kind: "breaking", detail: "input no longer accepts extra fields" });
20388
+ }
20389
+ function diffLocks(a, b) {
20390
+ const out = [];
20391
+ const ma = new Map(a.tools.map((t) => [t.name, t])), mb = new Map(b.tools.map((t) => [t.name, t]));
20392
+ for (const [n2] of ma)
20393
+ if (!mb.has(n2))
20394
+ out.push({ tool: n2, kind: "breaking", detail: "tool removed" });
20395
+ for (const [n2] of mb)
20396
+ if (!ma.has(n2))
20397
+ out.push({ tool: n2, kind: "addition", detail: "tool added" });
20398
+ for (const [n2, ta] of ma) {
20399
+ const tb = mb.get(n2);
20400
+ if (!tb)
20401
+ continue;
20402
+ schemaChanges(n2, "input", ta.inputSchema, tb.inputSchema, out, true);
20403
+ schemaChanges(n2, "output", ta.outputSchema, tb.outputSchema, out, false);
20404
+ const aa = ta.annotations ?? {}, ab = tb.annotations ?? {};
20405
+ if (aa.readOnlyHint === true && ab.readOnlyHint !== true)
20406
+ out.push({ tool: n2, kind: "risky", detail: "no longer declared read-only: re-review before agents use it" });
20407
+ if (aa.destructiveHint !== true && ab.destructiveHint === true)
20408
+ out.push({ tool: n2, kind: "risky", detail: "now declared destructive" });
20409
+ if (aa.openWorldHint !== true && ab.openWorldHint === true)
20410
+ out.push({ tool: n2, kind: "risky", detail: "now reaches outside systems (openWorldHint)" });
20411
+ if ((ta.description ?? "") !== (tb.description ?? ""))
20412
+ out.push({ tool: n2, kind: "risky", detail: "description changed: review it for new instructions to agents (silent tool changes, OWASP MCP03)" });
20413
+ }
20414
+ const has2 = (k) => out.some((c) => c.kind === k);
20415
+ const semver = has2("breaking") ? "major" : has2("addition") ? "minor" : out.length ? "patch" : "none";
20416
+ const n = (k) => out.filter((c) => c.kind === k).length;
20417
+ return { changes: out, semver, summary: out.length ? `${n("breaking")} breaking, ${n("risky")} to review, ${n("addition")} additions, ${n("change")} other changes; suggested version bump: ${semver}.` : "No changes to tools." };
20418
+ }
20419
+ function docsFor(tools, name, launch) {
20420
+ const kind = (t) => {
20421
+ const a = t.annotations ?? {};
20422
+ return a.readOnlyHint === true ? "reads only" : a.destructiveHint === true ? "can delete or overwrite" : a.readOnlyHint === false ? "changes data" : "not declared";
20423
+ };
20424
+ const firstSentence = (d) => sanitizeText((d ?? "").trim().split(/(?<=[.!?])\s/)[0] ?? "", 160).replace(/\|/g, "/");
20425
+ const req = (t) => ((t.inputSchema ?? {}).required ?? []).join(", ") || "none";
20426
+ const id = name.replace(/[^a-zA-Z0-9_-]/g, "-").replace(/^-+|-+$/g, "") || "server";
20427
+ const local = launch.url ? void 0 : { command: launch.command, args: launch.args ?? [] };
20428
+ const lines = [
20429
+ `## Tools`,
20430
+ "",
20431
+ "| Tool | What it does | Effect | Required arguments |",
20432
+ "| --- | --- | --- | --- |",
20433
+ ...tools.map((t) => `| \`${sanitizeText(t.name, 60)}\` | ${firstSentence(t.description)} | ${kind(t)} | ${req(t)} |`),
20434
+ "",
20435
+ `## Use it`,
20436
+ "",
20437
+ "**Claude Desktop** (`claude_desktop_config.json`) and **Cursor** (`.cursor/mcp.json`):",
20438
+ "",
20439
+ "```json",
20440
+ JSON.stringify({ mcpServers: { [id]: local ?? { url: launch.url } } }, null, 2),
20441
+ "```",
20442
+ "",
20443
+ "**VS Code** (`.vscode/mcp.json`):",
20444
+ "",
20445
+ "```json",
20446
+ JSON.stringify({ servers: { [id]: local ? { type: "stdio", ...local } : { type: "http", url: launch.url } } }, null, 2),
20447
+ "```",
20448
+ "",
20449
+ `_Generated by Saktum Check. Check the exact configuration format in each client's documentation._`
20450
+ ];
20451
+ return lines.join("\n") + "\n";
20452
+ }
20453
+ function clientCompatibility(tools) {
20454
+ const issues = [];
20455
+ const bad = tools.filter((t) => !/^[a-zA-Z0-9_-]{1,64}$/.test(t.name));
20456
+ if (bad.length)
20457
+ issues.push(`${bad.length} tool name(s) use characters or a length that many model providers reject in function names (allowed: 1 to 64 letters, digits, underscores and hyphens): ${bad.slice(0, 5).map((t) => sanitizeText(t.name, 60)).join(", ")}`);
20458
+ const long = tools.filter((t) => t.name.length > 40 && t.name.length <= 64);
20459
+ if (long.length)
20460
+ issues.push(`${long.length} tool name(s) are over 40 characters; clients that prefix the server name may exceed the 64-character limit: ${long.slice(0, 3).map((t) => sanitizeText(t.name, 60)).join(", ")}`);
20461
+ if (tools.length > 40)
20462
+ issues.push(`${tools.length} tools: some clients limit how many tools they load or show; check your target clients and consider grouping or splitting the server`);
20463
+ return issues;
20464
+ }
20465
+
20121
20466
  // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
20122
20467
  var util_exports = {};
20123
20468
  __export(util_exports, {
@@ -20283,8 +20628,8 @@ function defineLazy(object3, key, getter) {
20283
20628
  configurable: true
20284
20629
  });
20285
20630
  }
20286
- function objectClone(obj) {
20287
- return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
20631
+ function objectClone(obj2) {
20632
+ return Object.create(Object.getPrototypeOf(obj2), Object.getOwnPropertyDescriptors(obj2));
20288
20633
  }
20289
20634
  function assignProp(target, prop, value) {
20290
20635
  Object.defineProperty(target, prop, {
@@ -20355,10 +20700,10 @@ function mergeDefs(...defs) {
20355
20700
  function cloneDef(schema) {
20356
20701
  return mergeDefs(schema._zod.def);
20357
20702
  }
20358
- function getElementAtPath(obj, path) {
20703
+ function getElementAtPath(obj2, path) {
20359
20704
  if (!path)
20360
- return obj;
20361
- return path.reduce((acc, key) => acc?.[key], obj);
20705
+ return obj2;
20706
+ return path.reduce((acc, key) => acc?.[key], obj2);
20362
20707
  }
20363
20708
  function promiseAllObject(promisesObj) {
20364
20709
  const keys = Object.keys(promisesObj);
@@ -20794,9 +21139,9 @@ function parsedType(data) {
20794
21139
  if (Array.isArray(data)) {
20795
21140
  return "array";
20796
21141
  }
20797
- const obj = data;
20798
- if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
20799
- return obj.constructor.name;
21142
+ const obj2 = data;
21143
+ if (obj2 && Object.getPrototypeOf(obj2) !== Object.prototype && "constructor" in obj2 && obj2.constructor) {
21144
+ return obj2.constructor.name;
20800
21145
  }
20801
21146
  }
20802
21147
  }
@@ -20814,8 +21159,8 @@ function issue(...args) {
20814
21159
  }
20815
21160
  return { ...iss };
20816
21161
  }
20817
- function cleanEnum(obj) {
20818
- return Object.entries(obj).filter(([k, _]) => {
21162
+ function cleanEnum(obj2) {
21163
+ return Object.entries(obj2).filter(([k, _]) => {
20819
21164
  return Number.isNaN(Number.parseInt(k, 10));
20820
21165
  }).map((el) => el[1]);
20821
21166
  }
@@ -21139,15 +21484,15 @@ var $ZodError = $constructor("$ZodError", initializer);
21139
21484
  var $ZodRealError = $constructor("$ZodError", initializer, void 0, {
21140
21485
  Parent: Error
21141
21486
  });
21142
- function node(obj, key, make) {
21143
- if (!Object.prototype.hasOwnProperty.call(obj, key)) {
21487
+ function node(obj2, key, make) {
21488
+ if (!Object.prototype.hasOwnProperty.call(obj2, key)) {
21144
21489
  if (key === "__proto__") {
21145
- Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });
21490
+ Object.defineProperty(obj2, key, { value: make(), writable: true, enumerable: true, configurable: true });
21146
21491
  } else {
21147
- obj[key] = make();
21492
+ obj2[key] = make();
21148
21493
  }
21149
21494
  }
21150
- return obj[key];
21495
+ return obj2[key];
21151
21496
  }
21152
21497
  function flattenError(error2, mapper = (issue2) => issue2.message) {
21153
21498
  const fieldErrors = {};
@@ -29590,15 +29935,15 @@ function applyElicitationDefaults(schema, data) {
29590
29935
  if (!schema || data === null || typeof data !== "object")
29591
29936
  return;
29592
29937
  if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
29593
- const obj = data;
29938
+ const obj2 = data;
29594
29939
  const props = schema.properties;
29595
29940
  for (const key of Object.keys(props)) {
29596
29941
  const propSchema = props[key];
29597
- if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
29598
- obj[key] = propSchema.default;
29942
+ if (obj2[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
29943
+ obj2[key] = propSchema.default;
29599
29944
  }
29600
- if (obj[key] !== void 0) {
29601
- applyElicitationDefaults(propSchema, obj[key]);
29945
+ if (obj2[key] !== void 0) {
29946
+ applyElicitationDefaults(propSchema, obj2[key]);
29602
29947
  }
29603
29948
  }
29604
29949
  }
@@ -31930,7 +32275,7 @@ var StreamableHTTPClientTransport = class {
31930
32275
  };
31931
32276
 
31932
32277
  // packages/transports/dist/index.js
31933
- var USER_AGENT = "saktum-check/0.1.4 (+https://saktum.dev/check)";
32278
+ var USER_AGENT = "saktum-check/0.3.0 (+https://saktum.dev/check)";
31934
32279
  var LIMITS = { requestTimeoutMs: 1e4, connectTimeoutMs: 6e4, maxResponseChars: 5e6 };
31935
32280
  var LimitError = class extends Error {
31936
32281
  };
@@ -32004,6 +32349,11 @@ function guardSize(value, what) {
32004
32349
  async function connect(target) {
32005
32350
  const client = new Client({ name: "saktum-trust-check", version: "0.0.1" }, { capabilities: {} });
32006
32351
  const transport = target.kind === "streamable-http" ? new StreamableHTTPClientTransport(new URL(target.url), { requestInit: { headers: { "User-Agent": USER_AGENT, ...target.headers ?? {} } } }) : new StdioClientTransport({ command: target.command, args: target.args, env: minimalEnv(target.env), cwd: target.cwd, stderr: "ignore" });
32352
+ const tAny = transport;
32353
+ if (!tAny.setProtocolVersion)
32354
+ tAny.setProtocolVersion = (v) => {
32355
+ tAny.protocolVersion = v;
32356
+ };
32007
32357
  const t0 = Date.now();
32008
32358
  await withTimeout(client.connect(transport), LIMITS.connectTimeoutMs, "connect");
32009
32359
  const initMs = Date.now() - t0;
@@ -32060,7 +32410,7 @@ var INIT_BODY = JSON.stringify({
32060
32410
  jsonrpc: "2.0",
32061
32411
  id: 1,
32062
32412
  method: "initialize",
32063
- params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.1.4" } }
32413
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.3.0" } }
32064
32414
  });
32065
32415
  async function httpRequest(url2, init = {}) {
32066
32416
  const t0 = Date.now();
@@ -32344,6 +32694,23 @@ var authAnalysers = {
32344
32694
  return { status: "fail", message: `Answered an invalid token with HTTP ${p.status} instead of 401 (RFC 6750); server errors on bad tokens can hide validation bugs.` };
32345
32695
  }
32346
32696
  };
32697
+ authAnalysers["origin-validation"] = (ctx) => {
32698
+ const u = serverUrl(ctx);
32699
+ if (!u)
32700
+ return skippedNotHttp;
32701
+ if (!isLocal(u))
32702
+ return { status: "skipped", message: "Applies to local HTTP servers, where DNS rebinding can expose them to web pages." };
32703
+ const p = ctx.http?.foreignOrigin;
32704
+ if (!p || p.status === null)
32705
+ return { status: "inconclusive", message: "No answer to a request from a foreign web origin." };
32706
+ if (p.status === 403 || p.status === 400)
32707
+ return { status: "pass", message: `Refuses requests from foreign web origins (HTTP ${p.status}).` };
32708
+ if (p.status === 401)
32709
+ return { status: "pass", message: "Requires sign-in, which also blocks requests from foreign web origins that carry no token." };
32710
+ if (p.status >= 200 && p.status < 300)
32711
+ return { status: "fail", message: "Accepted a request claiming to come from an unrelated web page (Origin: https://attacker.example). Through DNS rebinding, any website the user visits could call this local server." };
32712
+ return { status: "inconclusive", message: `Answered a foreign-origin request with HTTP ${p.status}.` };
32713
+ };
32347
32714
  var AUTH_NEEDS = Object.fromEntries(Object.keys(authAnalysers).map((k) => [k, "none"]));
32348
32715
 
32349
32716
  // packages/testkit-core/dist/leakage.js
@@ -32429,7 +32796,9 @@ var perfAnalysers = {
32429
32796
  const slow = perf.initMs > PERF_THRESHOLDS.startupMs;
32430
32797
  return { status: "info", message: `${what} in ${perf.initMs} ms.${slow ? " That is slow: agents and clients may time out." : ""}` };
32431
32798
  },
32432
- "perf-latency": ({ perf }) => {
32799
+ "perf-latency": ({ perf, load }) => {
32800
+ if (load)
32801
+ return { status: "info", message: `${load.verdicts[0]} (p50 ${load.latency.p50} ms over ${load.latency.samples} samples; tool list ${Math.round((perf?.listBytes ?? 0) / 1024)} KB).` };
32433
32802
  if (perf?.listMs === void 0)
32434
32803
  return { status: "inconclusive", message: "Tool-list latency was not measured." };
32435
32804
  const notes = [];
@@ -32449,19 +32818,58 @@ var perfAnalysers = {
32449
32818
  const heavy = perf.rssMb > PERF_THRESHOLDS.rssMb;
32450
32819
  return { status: "info", message: `Uses ${perf.rssMb} MB of memory (including any launcher such as npx); averaged ${perf.cpuPct}% CPU since start-up.${heavy ? " That is a lot of memory for a tool server." : ""}` };
32451
32820
  },
32452
- "perf-burst": ({ perf }) => {
32453
- const b = perf?.burst;
32454
- if (!b)
32455
- return { status: "inconclusive", message: "The burst test did not run." };
32456
- const parts = [`${b.ok} of ${b.requests} concurrent requests succeeded (p95 ${b.p95Ms} ms)`];
32457
- if (b.rateLimited)
32458
- parts.push(`${b.rateLimited} were rate-limited, which is healthy behaviour`);
32459
- if (b.errors)
32460
- parts.push(`${b.errors} failed with errors under light load`);
32461
- return { status: "info", message: `${parts.join("; ")}.` };
32821
+ "perf-concurrency": ({ load }) => {
32822
+ if (!load)
32823
+ return { status: "inconclusive", message: "The load measurement did not run." };
32824
+ const levels = load.levels.map((l) => `${l.concurrency} caller${l.concurrency === 1 ? "" : "s"}: ${l.ok}/${l.requests} ok, p95 ${l.p95} ms, ${l.throughput}/s`).join("; ");
32825
+ return { status: "info", message: `${load.verdicts.join(" ")} Measured by ${load.operation} (${levels}).${load.memoryGrowthMb !== void 0 ? ` Memory grew by ${load.memoryGrowthMb} MB during the run.` : ""}` };
32462
32826
  }
32463
32827
  };
32464
- var PERF_NEEDS = { "perf-startup": "session", "perf-latency": "session", "perf-memory": "session", "perf-burst": "session" };
32828
+ var PERF_NEEDS = { "perf-startup": "session", "perf-latency": "session", "perf-memory": "session", "perf-concurrency": "session" };
32829
+
32830
+ // packages/testkit-core/dist/functional-checks.js
32831
+ var notEligible = { status: "skipped", message: "No tools were eligible to call: annotate read-only tools (readOnlyHint), name tools with --call, or add test cases." };
32832
+ var describe2 = (xs) => xs.slice(0, 3).map((x) => `${sanitizeText(x.tool, 50)}: ${x.problems.join("; ")}`).join(" \xB7 ");
32833
+ var functionalAnalysers = {
32834
+ "func-respond": ({ functional }) => {
32835
+ if (!functional?.ran)
32836
+ return { status: "skipped", message: functional?.reason ?? "Functional calls did not run." };
32837
+ const smoke = functional.calls.filter((c) => c.purpose === "smoke");
32838
+ if (!smoke.length)
32839
+ return notEligible;
32840
+ const bad = smoke.filter((c) => c.outcome.kind === "timeout" || c.outcome.kind === "transport-error" || c.outcome.kind === "protocol-error" && c.outcome.code === -32602);
32841
+ if (bad.length)
32842
+ return { status: "fail", subject: "tools", message: `${bad.length} of ${smoke.length} tool(s) failed with valid arguments: ${describe2(bad.map((b) => ({ tool: b.tool, problems: b.problems.length ? b.problems : [b.outcome.kind] })))}.` };
32843
+ const errored = smoke.filter((c) => c.outcome.kind !== "result" || c.outcome.isError).length;
32844
+ return { status: "pass", message: `${smoke.length} tool(s) called with arguments generated from their schemas${errored ? ` (${errored} answered with an error result, for example because they need credentials or real data; that is not counted as a failure)` : ""}.` };
32845
+ },
32846
+ "func-output": ({ functional }) => {
32847
+ if (!functional?.ran)
32848
+ return { status: "skipped", message: functional?.reason ?? "Functional calls did not run." };
32849
+ const ok = functional.calls.filter((c) => c.purpose === "smoke" && c.outcome.kind === "result" && !c.outcome.isError);
32850
+ if (!ok.length)
32851
+ return { status: "skipped", message: "No call returned a successful result to validate (tools may need credentials or real data; add test cases with real inputs)." };
32852
+ const bad = ok.map((c) => ({ tool: c.tool, problems: c.problems })).filter((c) => c.problems.length);
32853
+ return bad.length ? { status: "fail", subject: "tools", message: `${bad.length} of ${ok.length} successful result(s) are malformed or break their declared output schema: ${describe2(bad)}.` } : { status: "pass", message: `${ok.length} successful result(s) are well-formed and match any declared output schema.` };
32854
+ },
32855
+ "func-invalid": ({ functional }) => {
32856
+ if (!functional?.ran)
32857
+ return { status: "skipped", message: functional?.reason ?? "Functional calls did not run." };
32858
+ const probes = functional.calls.filter((c) => c.purpose === "invalid-args");
32859
+ if (!probes.length)
32860
+ return notEligible;
32861
+ const bad = probes.filter((c) => c.problems.length);
32862
+ return bad.length ? { status: "fail", subject: "tools", message: `${bad.length} of ${probes.length} tool(s) handled invalid arguments badly: ${describe2(bad)}.` } : { status: "pass", message: `${probes.length} tool(s) rejected invalid arguments gracefully.` };
32863
+ },
32864
+ "func-survives": ({ functional }) => {
32865
+ if (!functional?.ran)
32866
+ return { status: "skipped", message: functional?.reason ?? "Functional calls did not run." };
32867
+ if (functional.survived === void 0)
32868
+ return notEligible;
32869
+ return functional.survived ? { status: "pass", message: "The server kept responding after all functional calls." } : { status: "fail", message: "The server stopped responding after the functional calls." };
32870
+ }
32871
+ };
32872
+ var FUNCTIONAL_NEEDS = { "func-respond": "session", "func-output": "session", "func-invalid": "session", "func-survives": "session" };
32465
32873
 
32466
32874
  // packages/testkit-core/dist/analysers.js
32467
32875
  var textOf = (t) => `${t.name ?? ""}
@@ -32475,13 +32883,35 @@ var evidenceFor = (tool, text) => tool ? { hash: sha256Tag(JSON.stringify(tool))
32475
32883
  var CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/;
32476
32884
  var HIDDEN_INSTRUCTION = [
32477
32885
  /ignore (all |any )?(previous|prior|above) (instructions|messages)/i,
32478
- /do not (tell|mention|inform|reveal to) the user/i,
32886
+ // Concealment, not guidance: honest advice such as "do not tell the user it is in their account" must not match.
32887
+ /\b(do not|don['’]t|never) tell the user\s*[.!]/i,
32888
+ /\bwithout (telling|informing|alerting|notifying) the user\b/i,
32889
+ /\b(do not|don['’]t|never) (mention|reveal|disclose) (this|these) (instructions?|steps?|tool|call)\b/i,
32890
+ /\bhide (this|it|the (action|request|call|upload)) from the user\b/i,
32479
32891
  /<\s*important\s*>/i,
32480
- /\b(system prompt|developer message)\b/i,
32892
+ // Manipulating the agent's instructions, not merely mentioning a system prompt (for example a parameter that appends to one).
32893
+ /\b(ignore|disregard|override|forget|replace) (the |your |all )?(system prompt|developer message|previous instructions)\b/i,
32894
+ /\b(reveal|print|output|leak|show) (the |your )?(system prompt|developer message)\b/i,
32481
32895
  /before using this tool,? (you must |first )?(read|send|call|fetch|upload)/i,
32482
32896
  /(send|upload|post|forward) (the |all |any )?(conversation|chat history|credentials|api keys?|secrets?|tokens?) to/i
32483
32897
  ];
32484
32898
  var coreAnalysers = {
32899
+ "client-compat": ({ tools }) => {
32900
+ const issues = clientCompatibility(tools);
32901
+ return issues.length ? { status: "info", message: issues.join(" ") } : { status: "pass", message: "Tool names and count fit the constraints common to model providers and clients." };
32902
+ },
32903
+ "unknown-tool-code": ({ probes }) => {
32904
+ const o = probes?.unknownTool;
32905
+ if (!o)
32906
+ return { status: "inconclusive", message: "The unknown-tool probe did not run." };
32907
+ if (o.kind === "protocol-error" && (o.code === -32602 || o.code === -32601))
32908
+ return { status: "pass", message: `Unknown tools get JSON-RPC error ${o.code} (${o.code === -32602 ? "invalid params, as in the specification's example" : "method not found, understood by most clients"}).` };
32909
+ if (o.kind === "result" && o.isError)
32910
+ return { status: "pass", message: "Unknown tools get an error result." };
32911
+ if (o.kind === "protocol-error")
32912
+ return { status: "info", message: `Unknown tools get JSON-RPC error ${o.code}. The MCP specification's example uses -32602 (invalid params); -32601 is also widely understood.` };
32913
+ return { status: "info", message: "See the unknown-tool success check for how this server answers unknown tools." };
32914
+ },
32485
32915
  handshake: ({ session }) => {
32486
32916
  if (!session)
32487
32917
  return { status: "inconclusive", message: "No MCP session (the server requires sign-in)." };
@@ -32553,7 +32983,7 @@ var coreAnalysers = {
32553
32983
  "context-cost": ({ tools, pricePerMTokUsd }) => {
32554
32984
  const { contextCostTokens, largestTools, contextCostPer1kTurnsUsd } = contextCost(tools, pricePerMTokUsd);
32555
32985
  const money = contextCostPer1kTurnsUsd !== void 0 ? ` (about $${contextCostPer1kTurnsUsd.toFixed(2)} per 1,000 agent turns at $${pricePerMTokUsd} per million input tokens)` : "";
32556
- return { status: "info", message: `Tool definitions cost about ${contextCostTokens} tokens of agent context per turn when loaded upfront${money}. Largest: ${largestTools.slice(0, 3).map((s) => `${s.tool} (${s.tokens})`).join(", ") || "none"}.` };
32986
+ return { status: "info", message: `Tool definitions cost about ${contextCostTokens.toLocaleString("en-US")} tokens of agent context per turn when loaded upfront${money}. Largest: ${largestTools.slice(0, 3).map((s) => `${s.tool} (${s.tokens})`).join(", ") || "none"}.` };
32557
32987
  }
32558
32988
  };
32559
32989
  function contextCost(tools, pricePerMTokUsd) {
@@ -32562,8 +32992,8 @@ function contextCost(tools, pricePerMTokUsd) {
32562
32992
  const per1k = pricePerMTokUsd !== void 0 && pricePerMTokUsd > 0 ? Math.round(contextCostTokens / 1e6 * pricePerMTokUsd * 1e3 * 100) / 100 : void 0;
32563
32993
  return { contextCostTokens, largestTools: sized.slice(0, 5), ...per1k !== void 0 ? { contextCostPer1kTurnsUsd: per1k } : {} };
32564
32994
  }
32565
- var analysers = { ...coreAnalysers, ...authAnalysers, ...leakageAnalysers, ...perfAnalysers };
32566
- var ANALYSER_NEEDS = { handshake: "session", ...AUTH_NEEDS, ...LEAKAGE_NEEDS, ...PERF_NEEDS };
32995
+ var analysers = { ...coreAnalysers, ...authAnalysers, ...leakageAnalysers, ...perfAnalysers, ...functionalAnalysers };
32996
+ var ANALYSER_NEEDS = { handshake: "session", "unknown-tool-code": "session", ...AUTH_NEEDS, ...LEAKAGE_NEEDS, ...PERF_NEEDS, ...FUNCTIONAL_NEEDS };
32567
32997
  var needsOf = (name) => ANALYSER_NEEDS[name] ?? "tools";
32568
32998
 
32569
32999
  // packages/testkit-core/dist/runner.js
@@ -32584,7 +33014,7 @@ function meets(value, e) {
32584
33014
  return false;
32585
33015
  return true;
32586
33016
  }
32587
- function describe2(value) {
33017
+ function describe3(value) {
32588
33018
  const c = value;
32589
33019
  if (c && typeof c === "object" && "kind" in c) {
32590
33020
  if (c.kind === "result")
@@ -32632,7 +33062,7 @@ async function runCheck(check, ctx) {
32632
33062
  }
32633
33063
  }
32634
33064
  if (step.expect && !meets(value, step.expect))
32635
- return { status: "fail", message: `Got ${describe2(value)}, which does not meet the expectation.` };
33065
+ return { status: "fail", message: `Got ${describe3(value)}, which does not meet the expectation.` };
32636
33066
  } catch (e) {
32637
33067
  if (e instanceof LimitError)
32638
33068
  return { status: "inconclusive", message: sanitizeText(e.message) };
@@ -32709,12 +33139,16 @@ function summarise(r, noGrade, isTrust = () => true) {
32709
33139
  lines.push(`Trust grade ${r.grade}: all ${passed} checks that apply passed.`);
32710
33140
  else
32711
33141
  lines.push(`Trust grade ${r.grade}: ${fails.length} problem${fails.length === 1 ? "" : "s"} found (${counts.map(([s, n]) => `${n} ${s}`).join(", ")}); ${passed} checks passed.`);
33142
+ const fnFails = r.findings.filter((f) => (f.pack === "functional" || f.pack === "tests") && f.status === "fail" && f.scored);
33143
+ const functionalLine = fnFails.length ? `Functional: ${fnFails.length} problem${fnFails.length === 1 ? "" : "s"}, first ${fnFails[0].title.charAt(0).toLowerCase()}${fnFails[0].title.slice(1)}: ${(fnFails[0].message ?? "").split(/(?<=\.)\s/)[0].replace(/\.$/, "")}.` : void 0;
32712
33144
  const rd = r.readiness;
32713
33145
  const readinessLine = rd && rd.grade && rd.topImprovement ? `Agent readiness ${rd.grade}: ${rd.topImprovement}.` : void 0;
32714
33146
  if (fails[0]) {
32715
33147
  const first = (fails[0].message ?? fails[0].title).split(/(?<=\.)\s/)[0].replace(/\.$/, "");
32716
33148
  lines.push(`Fix first (${fails[0].severity}): ${first.charAt(0).toLowerCase()}${first.slice(1)}.`);
32717
- } else if (readinessLine)
33149
+ } else if (functionalLine)
33150
+ lines.push(functionalLine);
33151
+ else if (readinessLine)
32718
33152
  lines.push(readinessLine);
32719
33153
  else
32720
33154
  lines.push("Nothing to fix in this run; keep running it in CI to catch regressions.");
@@ -32767,11 +33201,285 @@ function readinessFor(tools) {
32767
33201
  };
32768
33202
  }
32769
33203
 
33204
+ // packages/testkit-core/dist/functional.js
33205
+ init_contracts();
33206
+ var FUNCTIONAL_LIMITS = { maxSmokeTools: 8, perCallTimeoutMs: 15e3, survivalWaitMs: 500 };
33207
+ var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
33208
+ function exampleFor(schema, depth = 0) {
33209
+ const s = obj(schema);
33210
+ if (depth > 6)
33211
+ return null;
33212
+ if ("const" in s)
33213
+ return s.const;
33214
+ if (Array.isArray(s.examples) && s.examples.length)
33215
+ return s.examples[0];
33216
+ if ("default" in s)
33217
+ return s.default;
33218
+ if (Array.isArray(s.enum) && s.enum.length)
33219
+ return s.enum[0];
33220
+ for (const k of ["oneOf", "anyOf"])
33221
+ if (Array.isArray(s[k]) && s[k].length)
33222
+ return exampleFor(s[k][0], depth + 1);
33223
+ if (Array.isArray(s.allOf) && s.allOf.length)
33224
+ return exampleFor(Object.assign({}, ...s.allOf.map(obj)), depth + 1);
33225
+ const type = Array.isArray(s.type) ? s.type.find((t) => t !== "null") : s.type;
33226
+ switch (type ?? (s.properties ? "object" : void 0)) {
33227
+ case "object": {
33228
+ const out = {};
33229
+ const props = obj(s.properties);
33230
+ for (const key of Array.isArray(s.required) ? s.required : [])
33231
+ out[key] = exampleFor(props[key], depth + 1);
33232
+ return out;
33233
+ }
33234
+ case "array": {
33235
+ const n = typeof s.minItems === "number" ? Math.min(s.minItems, 3) : 0;
33236
+ return Array.from({ length: n }, () => exampleFor(s.items, depth + 1));
33237
+ }
33238
+ case "integer":
33239
+ case "number": {
33240
+ let v = typeof s.minimum === "number" ? s.minimum : typeof s.exclusiveMinimum === "number" ? s.exclusiveMinimum + 1 : 1;
33241
+ if (typeof s.maximum === "number" && v > s.maximum)
33242
+ v = s.maximum;
33243
+ return type === "integer" ? Math.ceil(v) : v;
33244
+ }
33245
+ case "boolean":
33246
+ return false;
33247
+ case "null":
33248
+ return null;
33249
+ case "string": {
33250
+ const fmt2 = { uri: "https://example.com", url: "https://example.com", email: "user@example.com", date: "2026-01-15", "date-time": "2026-01-15T09:00:00Z", uuid: "123e4567-e89b-42d3-a456-426614174000", hostname: "example.com", ipv4: "192.0.2.1" };
33251
+ let v = fmt2[String(s.format)] ?? "example";
33252
+ if (typeof s.minLength === "number" && v.length < s.minLength)
33253
+ v = v.padEnd(s.minLength, "x");
33254
+ if (typeof s.maxLength === "number" && v.length > s.maxLength)
33255
+ v = v.slice(0, Math.max(1, s.maxLength));
33256
+ return v;
33257
+ }
33258
+ default:
33259
+ return "example";
33260
+ }
33261
+ }
33262
+ function invalidArgsFor(schema) {
33263
+ const s = obj(schema);
33264
+ const required2 = Array.isArray(s.required) ? s.required : [];
33265
+ if (required2.length)
33266
+ return {};
33267
+ const first = Object.entries(obj(s.properties))[0];
33268
+ if (!first)
33269
+ return void 0;
33270
+ const t = obj(first[1]).type;
33271
+ return { [first[0]]: t === "string" ? 12345 : "not-the-right-type" };
33272
+ }
33273
+ var isReadOnly = (t) => t.annotations?.readOnlyHint === true;
33274
+ function resultProblems(tool, o) {
33275
+ if (o.kind !== "result" || o.isError)
33276
+ return [];
33277
+ const p = [];
33278
+ if (!Array.isArray(o.content))
33279
+ p.push("content is not an array");
33280
+ else
33281
+ for (const c of o.content) {
33282
+ const it = obj(c);
33283
+ if (typeof it.type !== "string") {
33284
+ p.push("a content item has no type");
33285
+ break;
33286
+ }
33287
+ if (it.type === "text" && typeof it.text !== "string") {
33288
+ p.push("a text content item has no text");
33289
+ break;
33290
+ }
33291
+ }
33292
+ const outSchema = tool.outputSchema;
33293
+ if (outSchema) {
33294
+ if (o.structuredContent === void 0)
33295
+ p.push("the tool declares an outputSchema but returned no structuredContent");
33296
+ else {
33297
+ const v = compileUntrustedSchemaValidator(outSchema);
33298
+ if (!v.ok)
33299
+ p.push(`its outputSchema is not valid JSON Schema (${v.error.slice(0, 80)})`);
33300
+ else if (!v.validate(o.structuredContent))
33301
+ p.push(`structuredContent does not match its outputSchema (${v.errors().slice(0, 120)})`);
33302
+ }
33303
+ }
33304
+ return p;
33305
+ }
33306
+ function invalidArgProblems(o) {
33307
+ const p = [];
33308
+ if (o.kind === "timeout")
33309
+ p.push("timed out instead of rejecting the invalid arguments");
33310
+ else if (o.kind === "transport-error")
33311
+ p.push("the connection failed (the server may have crashed)");
33312
+ else if (o.kind === "result" && !o.isError)
33313
+ p.push("accepted arguments that violate its input schema and reported success");
33314
+ const text = outcomeText(o);
33315
+ const leak = LEAK_PATTERNS.find((l) => l.re.test(text));
33316
+ if (leak)
33317
+ p.push(`its error exposes ${/^[aeiou]/i.test(leak.name) ? "an" : "a"} ${leak.name}`);
33318
+ return p;
33319
+ }
33320
+ async function runFunctional(session, tools, opts) {
33321
+ if (!opts.active)
33322
+ return { ran: false, reason: "Tools are called only with --active, against servers you own.", calledTools: [], notCalled: [], calls: [] };
33323
+ const allow = new Set(opts.allowTools ?? []);
33324
+ const notCalled = [];
33325
+ const eligible = [];
33326
+ for (const t of tools) {
33327
+ if (allow.has(t.name) || isReadOnly(t))
33328
+ eligible.push(t);
33329
+ else
33330
+ notCalled.push({ tool: t.name, why: t.annotations?.destructiveHint ? "destructive (never called automatically)" : "not annotated read-only (name it with --call to include it)" });
33331
+ }
33332
+ const chosen = eligible.slice(0, FUNCTIONAL_LIMITS.maxSmokeTools);
33333
+ for (const t of eligible.slice(FUNCTIONAL_LIMITS.maxSmokeTools))
33334
+ notCalled.push({ tool: t.name, why: `limit of ${FUNCTIONAL_LIMITS.maxSmokeTools} tools per run` });
33335
+ const calls = [];
33336
+ for (const t of chosen) {
33337
+ const args = exampleFor(t.inputSchema);
33338
+ const inCheck = compileUntrustedSchemaValidator(t.inputSchema);
33339
+ if (inCheck.ok && !inCheck.validate(args)) {
33340
+ notCalled.push({ tool: t.name, why: "could not generate arguments that satisfy its input schema (add a test case for it)" });
33341
+ continue;
33342
+ }
33343
+ const outcome = await session.callTool(t.name, args);
33344
+ const problems = outcome.kind === "result" ? resultProblems(t, outcome) : outcome.kind === "protocol-error" && outcome.code === -32602 ? ["rejected arguments that satisfy its own input schema"] : outcome.kind === "protocol-error" ? [] : [`${outcome.kind === "timeout" ? "timed out" : "the call failed"}`];
33345
+ calls.push({ tool: t.name, purpose: "smoke", args, outcome, problems });
33346
+ const bad = invalidArgsFor(t.inputSchema);
33347
+ if (bad) {
33348
+ const o2 = await session.callTool(t.name, bad);
33349
+ calls.push({ tool: t.name, purpose: "invalid-args", args: bad, outcome: o2, problems: invalidArgProblems(o2) });
33350
+ }
33351
+ }
33352
+ let survived;
33353
+ if (calls.length) {
33354
+ await new Promise((r) => setTimeout(r, FUNCTIONAL_LIMITS.survivalWaitMs));
33355
+ try {
33356
+ await session.listTools();
33357
+ survived = true;
33358
+ } catch {
33359
+ survived = false;
33360
+ }
33361
+ }
33362
+ return { ran: true, calledTools: [...new Set(calls.map((c) => c.tool))], notCalled, calls, survived };
33363
+ }
33364
+ function subsetMatch(expected, actual) {
33365
+ if (expected === null || typeof expected !== "object")
33366
+ return expected === actual;
33367
+ if (Array.isArray(expected))
33368
+ return Array.isArray(actual) && expected.length === actual.length && expected.every((e, i) => subsetMatch(e, actual[i]));
33369
+ if (!actual || typeof actual !== "object")
33370
+ return false;
33371
+ return Object.entries(expected).every(([k, v]) => subsetMatch(v, actual[k]));
33372
+ }
33373
+ async function runTestCases(session, tools, cases, opts) {
33374
+ const out = [];
33375
+ for (const tc of cases) {
33376
+ const tool = tools.find((t) => t.name === tc.tool);
33377
+ if (!tool) {
33378
+ out.push({ id: tc.id, tool: tc.tool, status: "fail", problems: [`the server does not list a tool named ${sanitizeText(tc.tool, 60)}`] });
33379
+ continue;
33380
+ }
33381
+ if (tc.sideEffects && !opts.active) {
33382
+ out.push({ id: tc.id, tool: tc.tool, status: "skipped", problems: ["has side effects: runs only with --active against a server you own"] });
33383
+ continue;
33384
+ }
33385
+ const o = await session.callTool(tc.tool, tc.input);
33386
+ const p = [];
33387
+ const e = tc.expect;
33388
+ const isError = o.kind === "result" ? o.isError : true;
33389
+ if (o.kind !== "result" && e.isError !== true)
33390
+ p.push(o.kind === "protocol-error" ? `protocol error ${o.code}: ${sanitizeText(o.message, 120)}` : o.kind === "timeout" ? "timed out" : "the call failed");
33391
+ if (e.isError !== void 0 && isError !== e.isError)
33392
+ p.push(e.isError ? "expected an error result but the call succeeded" : "expected success but got an error result");
33393
+ const text = outcomeText(o);
33394
+ if (e.textContains !== void 0 && !text.includes(e.textContains))
33395
+ p.push(`the result does not contain "${sanitizeText(e.textContains, 60)}"`);
33396
+ if (e.structured !== void 0 && !(o.kind === "result" && subsetMatch(e.structured, o.structuredContent)))
33397
+ p.push("structuredContent does not match the expected values");
33398
+ if (e.outputSchema)
33399
+ p.push(...resultProblems(tool, o).filter((x) => /outputSchema|structuredContent/.test(x)));
33400
+ if (e.latencyMs?.lt !== void 0 && o.latencyMs >= e.latencyMs.lt)
33401
+ p.push(`took ${o.latencyMs} ms (expected under ${e.latencyMs.lt} ms)`);
33402
+ out.push({ id: tc.id, tool: tc.tool, status: p.length ? "fail" : "pass", problems: p, latencyMs: o.latencyMs });
33403
+ }
33404
+ return out;
33405
+ }
33406
+ async function parseTestCases(text) {
33407
+ const { parse: parse3 } = await Promise.resolve().then(() => __toESM(require_dist(), 1));
33408
+ const { compileContract: compileContract2 } = await Promise.resolve().then(() => (init_contracts(), contracts_exports));
33409
+ const data = parse3(text);
33410
+ const validate2 = compileContract2("test-cases.schema.json");
33411
+ if (!validate2(data))
33412
+ throw new Error(`Invalid test cases: ${(validate2.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}`);
33413
+ return data.tests;
33414
+ }
33415
+
33416
+ // packages/testkit-core/dist/load.js
33417
+ var LOAD = { latencySamples: 10, levels: [1, 5, 20], perLevelRequests: 20 };
33418
+ function percentile(values, p) {
33419
+ if (!values.length)
33420
+ return 0;
33421
+ const s = [...values].sort((a, b) => a - b);
33422
+ return s[Math.min(s.length - 1, Math.max(0, Math.ceil(p / 100 * s.length) - 1))];
33423
+ }
33424
+ async function measureLoad(session, op) {
33425
+ const operation = op ? `calling ${op.tool}` : "listing tools";
33426
+ const once = async () => {
33427
+ const t = Date.now();
33428
+ try {
33429
+ if (op) {
33430
+ const o = await session.callTool(op.tool, op.args);
33431
+ const limited = o.kind === "protocol-error" && /429|rate.?limit/i.test(o.message);
33432
+ return { ms: Date.now() - t, ok: o.kind === "result" && !o.isError, limited };
33433
+ }
33434
+ await session.listTools();
33435
+ return { ms: Date.now() - t, ok: true, limited: false };
33436
+ } catch (e) {
33437
+ return { ms: Date.now() - t, ok: false, limited: /429|rate.?limit/i.test(String(e.message)) };
33438
+ }
33439
+ };
33440
+ const lat = [];
33441
+ for (let i = 0; i < LOAD.latencySamples; i++)
33442
+ lat.push((await once()).ms);
33443
+ const levels = [];
33444
+ for (const c of LOAD.levels) {
33445
+ const results = [];
33446
+ const t0 = Date.now();
33447
+ let next = 0;
33448
+ await Promise.all(Array.from({ length: c }, async () => {
33449
+ while (next < LOAD.perLevelRequests) {
33450
+ next++;
33451
+ results.push(await once());
33452
+ }
33453
+ }));
33454
+ const secs = Math.max(1e-3, (Date.now() - t0) / 1e3);
33455
+ levels.push({
33456
+ concurrency: c,
33457
+ requests: results.length,
33458
+ ok: results.filter((r) => r.ok).length,
33459
+ rateLimited: results.filter((r) => r.limited).length,
33460
+ errors: results.filter((r) => !r.ok && !r.limited).length,
33461
+ p95: percentile(results.map((r) => r.ms), 95),
33462
+ throughput: Math.round(results.length / secs * 10) / 10
33463
+ });
33464
+ }
33465
+ const p50 = percentile(lat, 50), p95 = percentile(lat, 95);
33466
+ const verdicts = [];
33467
+ verdicts.push(p95 < 300 ? `Fast: ${operation} takes ${p95} ms at p95, fine for interactive agents.` : p95 < 1e3 ? `Acceptable: ${p95} ms at p95 for ${operation}; agents will notice delays in long tool chains.` : `Slow: ${p95} ms at p95 for ${operation}; agents and clients may time out.`);
33468
+ const top = levels[levels.length - 1];
33469
+ const base = levels[0];
33470
+ if (top.errors > 0)
33471
+ verdicts.push(`Under ${top.concurrency} concurrent callers, ${top.errors} of ${top.requests} requests failed: check limits and connection handling.`);
33472
+ else if (top.rateLimited > 0)
33473
+ verdicts.push(`Under ${top.concurrency} concurrent callers it rate-limited ${top.rateLimited} requests, which is healthy behaviour.`);
33474
+ else
33475
+ verdicts.push(`Handled ${top.concurrency} concurrent callers with no errors (${top.throughput} requests per second; p95 ${top.p95} ms against ${base.p95} ms with one caller).`);
33476
+ return { operation, latency: { p50, p95, samples: lat.length }, levels, verdicts };
33477
+ }
33478
+
32770
33479
  // packages/testkit-core/dist/engine.js
32771
- var ENGINE_VERSION = "0.1.4";
33480
+ var ENGINE_VERSION = "0.3.0";
32772
33481
  var UNKNOWN_TOOL = "saktum_trust_check_no_such_tool";
32773
33482
  var INVALID_TOKEN = "saktum-check-deliberately-invalid-token";
32774
- var BURST_REQUESTS = 20;
32775
33483
  function isProtocolFailure(e) {
32776
33484
  const m = String(e?.message ?? e);
32777
33485
  return !/ENOENT|EACCES|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|fetch failed|timed out|spawn|Connection closed|socket hang up/i.test(m);
@@ -32786,8 +33494,9 @@ var baseOf = (pack, check) => ({
32786
33494
  references: check.references
32787
33495
  });
32788
33496
  var MIN_GRADED_CHECKS = 5;
32789
- function finish(target, opts, startedAt, findings, extra, metrics, sandbox, noGrade, readiness = null) {
32790
- const categoryOf = (id) => opts.packs.find((p) => p.pack.id === id)?.pack.category ?? "other";
33497
+ function finish(target, opts, startedAt, findings, extra, metrics, sandbox, noGrade, readiness = null, more = {}) {
33498
+ const categoryOf = (id) => id === "tests" ? "functional" : opts.packs.find((p) => p.pack.id === id)?.pack.category ?? "other";
33499
+ applySuppressions(findings, opts.ignore);
32791
33500
  const scores = score(findings, categoryOf);
32792
33501
  const ran = findings.filter((f) => f.scored && (f.status === "pass" || f.status === "fail") && categoryOf(f.pack) in TRUST_WEIGHTS).length;
32793
33502
  const reason = noGrade ?? (ran < MIN_GRADED_CHECKS ? { kind: "too-few" } : void 0);
@@ -32804,29 +33513,39 @@ function finish(target, opts, startedAt, findings, extra, metrics, sandbox, noGr
32804
33513
  metrics,
32805
33514
  readiness,
32806
33515
  coverage: { trustChecksRun: ran },
33516
+ ...more,
33517
+ ...opts.ignore?.length ? { suppressions: opts.ignore.map((i) => ({ check: i.check, reason: sanitizeText(i.reason, 200) })) } : {},
32807
33518
  run: { startedAt: startedAt.toISOString(), durationMs: Date.now() - startedAt.getTime(), mode: opts.mode ?? "passive", runner: "self", sandbox }
32808
33519
  };
32809
33520
  r.summary = summarise(r, reason, (f) => categoryOf(f.pack) in TRUST_WEIGHTS);
32810
33521
  return r;
32811
33522
  }
32812
- async function burst(session) {
32813
- const times = [];
32814
- let ok = 0, rateLimited = 0, errors = 0;
32815
- await Promise.all(Array.from({ length: BURST_REQUESTS }, async () => {
32816
- const t = Date.now();
32817
- try {
32818
- await session.listTools();
32819
- ok++;
32820
- } catch (e) {
32821
- if (/\b429\b|rate.?limit/i.test(String(e.message)))
32822
- rateLimited++;
32823
- else
32824
- errors++;
33523
+ function applySuppressions(findings, ignore) {
33524
+ if (!ignore?.length)
33525
+ return;
33526
+ for (const f of findings) {
33527
+ const rule = ignore.find((i) => i.check === f.check || i.check.endsWith("*") && f.check.startsWith(i.check.slice(0, -1)));
33528
+ if (rule) {
33529
+ f.suppressed = { reason: sanitizeText(rule.reason, 200) };
33530
+ f.scored = false;
32825
33531
  }
32826
- times.push(Date.now() - t);
32827
- }));
32828
- times.sort((a, b) => a - b);
32829
- return { requests: BURST_REQUESTS, ok, rateLimited, errors, p95Ms: times[Math.min(times.length - 1, Math.floor(times.length * 0.95))] ?? 0 };
33532
+ }
33533
+ }
33534
+ function summariseFunctional(f) {
33535
+ return {
33536
+ ran: f.ran,
33537
+ reason: f.reason,
33538
+ calledTools: f.calledTools,
33539
+ notCalled: f.notCalled,
33540
+ survived: f.survived,
33541
+ calls: f.calls.map((c) => ({
33542
+ tool: sanitizeText(c.tool, 60),
33543
+ purpose: c.purpose,
33544
+ outcome: c.outcome.kind === "result" ? c.outcome.isError ? "error result" : "success" : c.outcome.kind === "protocol-error" ? `protocol error ${c.outcome.code}` : c.outcome.kind,
33545
+ latencyMs: c.outcome.latencyMs,
33546
+ problems: c.problems.map((x) => sanitizeText(x, 200))
33547
+ }))
33548
+ };
32830
33549
  }
32831
33550
  async function runTrustCheck(target, opts) {
32832
33551
  const startedAt = /* @__PURE__ */ new Date();
@@ -32837,7 +33556,8 @@ async function runTrustCheck(target, opts) {
32837
33556
  const userSuppliedAuth = Object.keys(target.headers ?? {}).some((k) => k.toLowerCase() === "authorization");
32838
33557
  const unauthenticated = await probeInitialize(target.url);
32839
33558
  const invalidToken = await probeInitialize(target.url, { Authorization: `Bearer ${INVALID_TOKEN}` });
32840
- ctx.http = { unauthenticated, invalidToken, userSuppliedAuth };
33559
+ const foreignOrigin = await probeInitialize(target.url, { Origin: "https://attacker.example" });
33560
+ ctx.http = { unauthenticated, invalidToken, foreignOrigin, userSuppliedAuth };
32841
33561
  if (unauthenticated.status === null && !userSuppliedAuth)
32842
33562
  throw new Error(`Could not reach ${target.url}: ${unauthenticated.error}`);
32843
33563
  }
@@ -32862,6 +33582,7 @@ async function runTrustCheck(target, opts) {
32862
33582
  }
32863
33583
  ctx.session = session;
32864
33584
  try {
33585
+ let testResults;
32865
33586
  let listError;
32866
33587
  let listShape = false;
32867
33588
  if (session) {
@@ -32886,8 +33607,23 @@ async function runTrustCheck(target, opts) {
32886
33607
  ctx.perf.cpuPct = u.cpuPct;
32887
33608
  }
32888
33609
  }
32889
- if (mode === "active")
32890
- ctx.perf.burst = await burst(session);
33610
+ if (mode === "active" && !listError) {
33611
+ const rssBefore = ctx.perf.rssMb;
33612
+ ctx.functional = await runFunctional(session, ctx.tools, { active: true, allowTools: opts.callTools });
33613
+ const smokeOk = ctx.functional.calls.find((c) => c.purpose === "smoke" && c.outcome.kind === "result" && !c.outcome.isError && c.problems.length === 0);
33614
+ ctx.load = await measureLoad(session, smokeOk ? { tool: smokeOk.tool, args: smokeOk.args } : void 0);
33615
+ if (session.pid && rssBefore !== void 0) {
33616
+ const after = await processUsage(session.pid);
33617
+ if (after) {
33618
+ ctx.load.memoryGrowthMb = Math.round((after.rssMb - rssBefore) * 10) / 10;
33619
+ if (ctx.load.memoryGrowthMb > Math.max(50, rssBefore * 0.5))
33620
+ ctx.load.verdicts.push(`Memory grew by ${ctx.load.memoryGrowthMb} MB during the run: check for leaks.`);
33621
+ }
33622
+ }
33623
+ } else if (mode !== "active")
33624
+ ctx.functional = { ran: false, reason: "Tools are called only with --active, against servers you own.", calledTools: [], notCalled: [], calls: [] };
33625
+ if (opts.testCases?.length && !listError)
33626
+ testResults = await runTestCases(session, ctx.tools, opts.testCases, { active: mode === "active" });
32891
33627
  }
32892
33628
  const tools = ctx.tools;
32893
33629
  const fingerprint = sha256Tag(canonicalize([...tools].sort((a, b) => String(a.name).localeCompare(String(b.name)))));
@@ -32918,6 +33654,17 @@ async function runTrustCheck(target, opts) {
32918
33654
  findings.push({ ...base, status: v.status, message: v.message, subject: v.subject, evidence: v.evidence, ...v.status === "pass" || v.status === "skipped" || v.status === "info" ? { fix: void 0 } : {} });
32919
33655
  }
32920
33656
  }
33657
+ for (const t of testResults ?? [])
33658
+ findings.push({
33659
+ check: `test.${sanitizeText(t.id, 80)}`,
33660
+ pack: "tests",
33661
+ severity: "medium",
33662
+ scored: t.status !== "skipped",
33663
+ status: t.status,
33664
+ title: `Test case ${sanitizeText(t.id, 80)} (${sanitizeText(t.tool, 60)})`,
33665
+ message: t.status === "pass" ? `Passed${t.latencyMs !== void 0 ? ` in ${t.latencyMs} ms` : ""}.` : sanitizeText(t.problems.join("; "), 400),
33666
+ ...t.status === "fail" ? { fix: "Fix the tool, or update the test case if the expectation is wrong." } : {}
33667
+ });
32921
33668
  const cost = contextCost(tools, price);
32922
33669
  const metrics = { ...cost, pricePerMTokUsd: price, performance: { ...ctx.perf } };
32923
33670
  if (!session || listError) {
@@ -32926,19 +33673,27 @@ async function runTrustCheck(target, opts) {
32926
33673
  delete metrics.contextCostPer1kTurnsUsd;
32927
33674
  }
32928
33675
  const noGrade = signInRequired ? { kind: "sign-in" } : listError ? { kind: "list-failed", error: sanitizeText(listError, 160) } : tools.length === 0 ? { kind: "no-tools", toolsCapability: Boolean(session?.capabilities?.tools) } : void 0;
32929
- return finish(target, { ...opts, mode }, startedAt, findings, session ? { protocolVersion: session.protocolVersion, serverInfo: session.serverInfo, toolsFingerprint: fingerprint, toolCount: tools.length } : { toolCount: 0 }, metrics, session?.sandbox ?? "none", noGrade, session && !listError ? readinessFor(tools) : null);
33676
+ return finish(target, { ...opts, mode }, startedAt, findings, session ? { protocolVersion: session.protocolVersion, serverInfo: session.serverInfo, toolsFingerprint: fingerprint, toolCount: tools.length } : { toolCount: 0 }, metrics, session?.sandbox ?? "none", noGrade, session && !listError ? readinessFor(tools) : null, {
33677
+ ...session && !listError && tools.length ? { capabilities: capabilityProfile(tools) } : {},
33678
+ ...ctx.functional ? { functional: summariseFunctional(ctx.functional) } : {},
33679
+ ...ctx.load ? { load: ctx.load } : {},
33680
+ ...testResults ? { tests: testResults } : {}
33681
+ });
32930
33682
  } finally {
32931
33683
  if (session && !opts.session)
32932
33684
  await session.close();
32933
33685
  }
32934
33686
  }
32935
33687
 
33688
+ // packages/testkit-core/dist/index.js
33689
+ init_embedded();
33690
+
32936
33691
  // packages/report/dist/index.js
32937
33692
  var SEV_ORDER = ["critical", "high", "medium", "low", "info"];
32938
33693
  var rank = (s) => SEV_ORDER.indexOf(s);
32939
33694
  var SYMBOL = { fail: "\u2717 FAIL", inconclusive: "! INCONCLUSIVE", pass: "\u2713 PASS", skipped: "- SKIPPED", info: "i INFO" };
32940
33695
  var FEEDBACK_URL = "https://github.com/soodhere/saktum-check/discussions";
32941
- var COVERAGE_NOTE = "v0.1 tests conformance, sign-in basics and security hygiene; deeper sign-in, injection and supply-chain checks arrive in v0.2 to v0.6.";
33696
+ var COVERAGE_NOTE = "This version tests conformance, sign-in basics, security hygiene, functional behaviour (with --active or test cases), performance and agent readiness; deeper sign-in, injection and supply-chain checks arrive in later releases.";
32942
33697
  var DISCLAIMER = "Findings describe this server at the time of the run. They are not a guarantee of security or correctness.";
32943
33698
  var SELF_SIGNED_NOTE = "Assurance level L1 (self-tested): the signature proves this report was not changed after the run, not that it was run independently.";
32944
33699
  var OWASP_MCP = [
@@ -32966,7 +33721,7 @@ var PARTIAL = {
32966
33721
  MCP02: "danger annotations only; scope tests in v0.2 to v0.6",
32967
33722
  MCP05: "schema validity only; active injection tests in v0.2",
32968
33723
  MCP06: "hidden-instruction scanning only; adversarial agent tests in v0.6",
32969
- MCP08: "error handling only; audit trails need runtime receipts (Saktum gateway)"
33724
+ MCP08: "error handling only; audit trails need runtime receipts from the Saktum gateway"
32970
33725
  };
32971
33726
  function owaspCoverage(r) {
32972
33727
  return OWASP_MCP.map(([id, name]) => {
@@ -32983,6 +33738,59 @@ function owaspCoverage(r) {
32983
33738
  };
32984
33739
  });
32985
33740
  }
33741
+ var PACK_DIMENSION = { conformance: "Conformance", auth: "Sign-in", security: "Security", functional: "Functional", tests: "Functional", performance: "Performance", "agent-experience": "Agent readiness" };
33742
+ var dim = (f) => PACK_DIMENSION[f.pack] ?? "Other";
33743
+ function trustCard(r) {
33744
+ const rows = [];
33745
+ const counted = (d) => r.findings.filter((f) => dim(f) === d && f.scored && !f.suppressed && (f.status === "pass" || f.status === "fail"));
33746
+ for (const d of ["Security", "Conformance", "Sign-in"]) {
33747
+ const fs = counted(d);
33748
+ const fails = fs.filter((f) => f.status === "fail");
33749
+ if (!fs.length) {
33750
+ const skipped = r.findings.find((f) => dim(f) === d && f.status === "skipped");
33751
+ const inconclusive = r.findings.find((f) => dim(f) === d && f.status === "inconclusive");
33752
+ rows.push({ dimension: d, mark: "-", text: skipped ? `not applicable: ${(skipped.message ?? "").replace(/\.$/, "").toLowerCase()}` : inconclusive ? `not tested: ${(inconclusive.message ?? "").replace(/\.$/, "")}` : "not tested" });
33753
+ } else
33754
+ rows.push({ dimension: d, mark: fails.length ? "\u2717" : "\u2713", text: fails.length ? `${fails.length} of ${fs.length} checks failed (worst: ${fails.sort((a, b) => rank(a.severity) - rank(b.severity))[0].severity})` : `${fs.length} checks passed` });
33755
+ }
33756
+ const fn = counted("Functional");
33757
+ const fnFails = fn.filter((f) => f.status === "fail");
33758
+ const called = r.functional?.calledTools.length ?? 0;
33759
+ if (fn.length)
33760
+ rows.push({ dimension: "Functional", mark: fnFails.length ? "\u2717" : "\u2713", text: `${fn.length - fnFails.length} of ${fn.length} functional checks passed${called ? ` (${called} tool${called === 1 ? "" : "s"} called)` : ""}${r.tests?.length ? `, ${r.tests.filter((t) => t.status === "pass").length} of ${r.tests.length} test cases` : ""}` });
33761
+ else
33762
+ rows.push({ dimension: "Functional", mark: "-", text: r.functional && !r.functional.ran ? "not tested: run with --active (read-only tools only) or add test cases with --tests" : "not tested: no tools were eligible to call (annotate read-only tools, use --call, or add test cases)" });
33763
+ if (r.load)
33764
+ rows.push({ dimension: "Performance", mark: r.load.levels.some((l) => l.errors) ? "!" : "\u2713", text: r.load.verdicts.join(" ") });
33765
+ else
33766
+ rows.push({ dimension: "Performance", mark: "-", text: `start-up and tool-list latency only${r.metrics.performance?.listMs !== void 0 ? ` (${r.metrics.performance.listMs} ms)` : ""}; run with --active for latency percentiles and concurrency` });
33767
+ if (r.readiness)
33768
+ rows.push({ dimension: "Agent readiness", mark: r.readiness.grade ?? "-", text: r.readiness.topImprovement ? `${r.readiness.topImprovement}` : "annotations, descriptions and context cost all good" });
33769
+ if (r.capabilities) {
33770
+ const caps = r.capabilities.capabilities.map((c) => c.label);
33771
+ rows.push({ dimension: "Capabilities", mark: r.capabilities.lethalTrifecta ? "!" : "i", text: caps.length ? `${caps.join("; ")}${r.capabilities.lethalTrifecta ? ". Warning: private data + untrusted content + outbound channel (the lethal trifecta); limit what agents can combine" : ""}` : "no notable capabilities inferred" });
33772
+ }
33773
+ return rows;
33774
+ }
33775
+ function scopeOfRun(r) {
33776
+ const lines = [];
33777
+ const ran = r.findings.filter((f) => f.status !== "skipped").length;
33778
+ const skipped = r.findings.filter((f) => f.status === "skipped");
33779
+ const reasons = /* @__PURE__ */ new Map();
33780
+ for (const f of skipped) {
33781
+ const k = (f.message ?? "skipped").replace(/\.$/, "");
33782
+ reasons.set(k, (reasons.get(k) ?? 0) + 1);
33783
+ }
33784
+ lines.push(`Mode: ${r.run.mode}${r.run.mode === "passive" ? " (no tool was called; only listing, a call to a non-existent tool, and read-only probes)" : " (tools were called as listed above)"}.`);
33785
+ lines.push(`${ran} checks ran; ${skipped.length} did not apply to this run.`);
33786
+ for (const [why, n] of reasons)
33787
+ lines.push(` ${n} \xB7 ${why}`);
33788
+ const later = owaspCoverage(r).filter((c) => !c.tested && c.later && !c.later.startsWith("not applicable")).map((c) => `${c.id} (${c.later})`);
33789
+ if (later.length)
33790
+ lines.push(`Not yet tested by this version: ${later.join("; ")}.`);
33791
+ lines.push("Full list of checks, with the standard behind each: saktum checks.");
33792
+ return lines;
33793
+ }
32986
33794
  function renderTerminal(r) {
32987
33795
  const s = (x, n) => sanitizeText(x, n);
32988
33796
  const lines = [];
@@ -32997,12 +33805,15 @@ function renderTerminal(r) {
32997
33805
  const rd = r.readiness;
32998
33806
  lines.push(` AGENT READINESS ${rd.grade ?? "-"} (score ${rd.score} \xB7 annotations ${rd.toolsAnnotated}/${rd.toolCount} tools \xB7 ${rd.contextTokens.toLocaleString("en-US")} tokens per turn)`);
32999
33807
  }
33808
+ const fn = r.findings.filter((f) => (f.pack === "functional" || f.pack === "tests") && f.scored && !f.suppressed && (f.status === "pass" || f.status === "fail"));
33809
+ lines.push(` FUNCTIONAL ${fn.length ? `${fn.filter((f) => f.status === "pass").length} of ${fn.length} checks passed${r.functional?.calledTools.length ? ` \xB7 ${r.functional.calledTools.length} tool${r.functional.calledTools.length === 1 ? "" : "s"} called` : ""}${r.tests?.length ? ` \xB7 ${r.tests.length} test cases` : ""}` : "not tested (run with --active, or add test cases)"}`);
33000
33810
  lines.push(` ${COVERAGE_NOTE}`);
33001
33811
  for (const line of r.summary ?? [])
33002
33812
  lines.push(` ${s(line, 300)}`);
33003
33813
  lines.push("");
33004
- for (const [c, v] of Object.entries(r.scores.categories))
33005
- lines.push(` ${c.padEnd(18)} ${v === null ? "n/a" : String(v).padStart(3)}`);
33814
+ lines.push("TRUST CARD");
33815
+ for (const row of trustCard(r))
33816
+ lines.push(` ${row.dimension.padEnd(16)} ${row.mark.padEnd(2)} ${s(row.text, 400)}`);
33006
33817
  lines.push("");
33007
33818
  const shown = [...r.findings].filter((f) => f.status === "fail" || f.status === "inconclusive").sort((a, b) => rank(a.severity) - rank(b.severity));
33008
33819
  for (const f of shown) {
@@ -33014,15 +33825,50 @@ function renderTerminal(r) {
33014
33825
  if (f.fix && f.status === "fail")
33015
33826
  lines.push(` Fix: ${s(f.fix, 300)}`);
33016
33827
  }
33017
- const passed = r.findings.filter((f) => f.status === "pass").length;
33828
+ const passedF = r.findings.filter((f) => f.status === "pass");
33829
+ const byDim = /* @__PURE__ */ new Map();
33830
+ for (const f of passedF)
33831
+ byDim.set(dim(f), (byDim.get(dim(f)) ?? 0) + 1);
33018
33832
  const skipped = r.findings.filter((f) => f.status === "skipped").length;
33019
- lines.push(`${SYMBOL.pass} ${passed} checks passed${skipped ? ` \xB7 ${skipped} not applicable` : ""}`);
33833
+ lines.push(`${SYMBOL.pass} ${passedF.length} checks passed (${[...byDim].map(([d, n]) => `${n} ${d.toLowerCase()}`).join(", ")})${skipped ? ` \xB7 ${skipped} not applicable` : ""}`);
33020
33834
  const info = r.findings.filter((f) => f.status === "info");
33021
33835
  if (info.length) {
33022
33836
  lines.push("");
33023
33837
  for (const f of info)
33024
33838
  lines.push(`i ${s(f.title)}: ${s(f.message, 300)}`);
33025
33839
  }
33840
+ if (r.functional?.ran) {
33841
+ lines.push("");
33842
+ lines.push("TOOLS CALLED");
33843
+ for (const c of r.functional.calls)
33844
+ lines.push(` ${s(c.tool, 40).padEnd(30)} ${c.purpose.padEnd(13)} ${s(c.outcome, 40).padEnd(18)} ${String(c.latencyMs).padStart(5)} ms${c.problems.length ? ` \u2717 ${s(c.problems.join("; "), 200)}` : ""}`);
33845
+ for (const n of r.functional.notCalled)
33846
+ lines.push(` ${s(n.tool, 40).padEnd(30)} not called: ${s(n.why, 160)}`);
33847
+ }
33848
+ if (r.tests?.length) {
33849
+ lines.push("");
33850
+ lines.push("TEST CASES");
33851
+ for (const t of r.tests)
33852
+ lines.push(` ${t.status === "pass" ? "\u2713" : t.status === "fail" ? "\u2717" : "-"} ${s(t.id, 60).padEnd(30)} ${s(t.tool, 40).padEnd(24)} ${t.status === "pass" ? `${t.latencyMs ?? ""} ms` : s(t.problems.join("; "), 200)}`);
33853
+ }
33854
+ if (r.capabilities?.capabilities.length) {
33855
+ lines.push("");
33856
+ lines.push("CAPABILITIES (inferred from annotations, names and descriptions; informational)");
33857
+ for (const c of r.capabilities.capabilities)
33858
+ lines.push(` ${s(c.label, 80).padEnd(58)} ${c.basis === "declared" ? "declared" : "inferred"}: ${s(c.tools.join(", "), 160)}`);
33859
+ if (r.capabilities.lethalTrifecta)
33860
+ lines.push(" ! This server combines private data, untrusted content and an outbound channel (the lethal trifecta). Limit what an agent can do with it.");
33861
+ }
33862
+ if (r.suppressions?.length) {
33863
+ lines.push("");
33864
+ lines.push("IGNORED BY THE PROVIDER (not scored)");
33865
+ for (const x of r.suppressions)
33866
+ lines.push(` ${s(x.check, 60)}: ${s(x.reason, 200)}`);
33867
+ }
33868
+ lines.push("");
33869
+ lines.push("SCOPE OF THIS RUN");
33870
+ for (const l of scopeOfRun(r))
33871
+ lines.push(` ${s(l, 400)}`);
33026
33872
  lines.push("");
33027
33873
  lines.push("OWASP MCP Top 10 coverage in this run:");
33028
33874
  for (const c of owaspCoverage(r)) {
@@ -33050,10 +33896,66 @@ function renderHtml(r) {
33050
33896
  <p class="grade">Trust ${e(r.grade ?? "-")}${r.readiness ? ` &middot; Agent readiness ${e(r.readiness.grade ?? "-")}` : ""}</p>
33051
33897
  <p><small>${e(COVERAGE_NOTE)}</small></p>
33052
33898
  ${(r.summary ?? []).map((l) => `<p>${e(l)}</p>`).join("")}
33053
- <table>${rows}</table>
33899
+ <h2>Trust card</h2><table>${trustCard(r).map((x) => `<tr><td>${e(x.dimension)}</td><td>${e(x.mark)}</td><td>${e(x.text)}</td></tr>`).join("")}</table>
33900
+ <h2>Findings</h2><table>${rows}</table>
33901
+ <h2>Scope of this run</h2>${scopeOfRun(r).map((l) => `<p>${e(l)}</p>`).join("")}
33054
33902
  <h2>OWASP MCP Top 10 coverage</h2><table>${cov}</table>
33055
33903
  <p><small>${e(SELF_SIGNED_NOTE)} ${e(DISCLAIMER)}</small></p></body></html>`;
33056
33904
  }
33905
+ function badgeSvg(r) {
33906
+ const colour = (g) => ({ A: "#2e7d32", B: "#558b2f", C: "#f9a825", D: "#ef6c00", F: "#c62828" })[g ?? ""] ?? "#757575";
33907
+ const right = `trust ${r.grade ?? "-"} \xB7 readiness ${r.readiness?.grade ?? "-"}`;
33908
+ const lw = 52, rw = 7 * right.length + 14, w = lw + rw;
33909
+ const worst = [r.grade, r.readiness?.grade].filter(Boolean).sort().pop();
33910
+ const title = escapeHtml(`Saktum Check ${r.tool.version}: trust ${r.grade ?? "-"}, agent readiness ${r.readiness?.grade ?? "-"}; self-tested (L1) on ${r.run.startedAt.slice(0, 10)}`);
33911
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="20" role="img" aria-label="${title}"><title>${title}</title><rect width="${lw}" height="20" fill="#3b2e8c"/><rect x="${lw}" width="${rw}" height="20" fill="${colour(worst)}"/><g fill="#fff" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11"><text x="8" y="14">saktum</text><text x="${lw + 7}" y="14">${escapeHtml(right)}</text></g></svg>
33912
+ `;
33913
+ }
33914
+ function checksTable(packs, markdown = false) {
33915
+ const rows = packs.flatMap(({ pack }) => pack.checks.map((c) => ({
33916
+ id: c.id,
33917
+ title: c.title,
33918
+ area: PACK_DIMENSION[pack.id] ?? pack.category,
33919
+ severity: c.severity,
33920
+ scored: c.scored === false || c.severity === "info" ? "no" : "yes",
33921
+ when: `${c.safety === "active" ? "--active only" : "every run"}${c.appliesTo?.transports ? `, ${c.appliesTo.transports.join("/")} servers` : ""}`,
33922
+ basis: (c.normative ?? []).map((n) => `${n.source}${n.clause ? `: ${n.clause}` : ""} (${n.level})`).concat((c.references ?? []).filter((x) => /OWASP|CWE|RFC/.test(x))).slice(0, 3).join("; ")
33923
+ })));
33924
+ if (markdown)
33925
+ return [
33926
+ "| Check | What it tests | Area | Severity | Scored | When it runs | Standard |",
33927
+ "| --- | --- | --- | --- | --- | --- | --- |",
33928
+ ...rows.map((x) => `| \`${x.id}\` | ${x.title} | ${x.area} | ${x.severity} | ${x.scored} | ${x.when} | ${x.basis.replace(/\|/g, "/")} |`)
33929
+ ].join("\n") + "\n";
33930
+ return rows.map((x) => `${x.id.padEnd(34)} ${x.area.padEnd(16)} ${x.severity.padEnd(9)} ${x.when.padEnd(32)} ${x.title}`).join("\n") + "\n";
33931
+ }
33932
+ function renderPacket(r, signedBy) {
33933
+ const e = (x) => escapeHtml(sanitizeText(x, 2e3));
33934
+ const name = `${r.target.serverInfo?.["name"] ?? r.target.description} ${r.target.serverInfo?.["version"] ?? ""}`.trim();
33935
+ const card = trustCard(r).map((x) => `<tr><td><b>${e(x.dimension)}</b></td><td class="m">${e(x.mark)}</td><td>${e(x.text)}</td></tr>`).join("");
33936
+ const problems = r.findings.filter((f) => f.status === "fail" && !f.suppressed).map((f) => `<tr><td>${e(f.severity)}</td><td>${e(f.title)}</td><td>${e(f.message ?? "")}</td></tr>`).join("") || `<tr><td colspan="3">No failed checks in this run.</td></tr>`;
33937
+ const caps = (r.capabilities?.capabilities ?? []).map((c) => `<li>${e(c.label)} <small>(${e(c.basis)}: ${e(c.tools.join(", "))})</small></li>`).join("") || "<li>No notable capabilities inferred.</li>";
33938
+ const tests = (r.tests ?? []).map((t) => `<li>${t.status === "pass" ? "\u2713" : t.status === "fail" ? "\u2717" : "-"} ${e(t.id)} (${e(t.tool)})</li>`).join("");
33939
+ const declare = ["Data the server processes, and whether it includes personal data", "Where it is hosted, and data residency", "Logging and retention of requests and results", "Credentials it needs and how they are stored", "How to report a security issue, and response time", "Incident notification commitment"].map((q) => `<tr><td>${e(q)}</td><td class="blank">&nbsp;</td></tr>`).join("");
33940
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
33941
+ <title>Security packet: ${e(name)}</title>
33942
+ <style>body{font:14px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#16161d;max-width:860px;margin:32px auto;padding:0 20px}h1{font-size:26px;margin:0 0 4px}h2{font-size:18px;margin:28px 0 8px;border-bottom:2px solid #16161d;padding-bottom:4px}
33943
+ table{border-collapse:collapse;width:100%}td,th{border-top:1px solid #ddd;padding:7px 6px;vertical-align:top;text-align:left}.m{width:28px;text-align:center}.blank{width:55%;border-bottom:1px solid #999}.muted{color:#555}.grades{font-size:20px;font-weight:700}
33944
+ @media print{body{margin:0}h2{break-after:avoid}}</style></head><body>
33945
+ <h1>Security packet: ${e(name)}</h1>
33946
+ <p class="muted">Prepared with Saktum Check ${e(r.tool.version)} on ${e(r.run.startedAt.slice(0, 10))} (${e(r.run.mode)} run). Assurance level ${e(r.assuranceLevel ?? "L1")}: self-tested by the provider; the result is signed so it cannot be changed without detection.</p>
33947
+ <p class="grades">Trust ${e(r.grade ?? "-")} &middot; Agent readiness ${e(r.readiness?.grade ?? "-")}</p>
33948
+ ${(r.summary ?? []).map((l) => `<p>${e(l)}</p>`).join("")}
33949
+ <h2>1. Trust card</h2><table>${card}</table>
33950
+ <h2>2. Open findings</h2><table><tr><th>Severity</th><th>Check</th><th>Detail</th></tr>${problems}</table>
33951
+ <h2>3. What the tools can do</h2><ul>${caps}</ul>${r.capabilities?.lethalTrifecta ? "<p><b>Note:</b> the tools combine private data, untrusted content and an outbound channel; customers should limit what an agent can combine.</p>" : ""}
33952
+ ${tests ? `<h2>4. Provider test cases</h2><ul>${tests}</ul>` : ""}
33953
+ <h2>${tests ? 5 : 4}. Scope and limits</h2>${scopeOfRun(r).map((l) => `<p>${e(l)}</p>`).join("")}<p class="muted">${e(COVERAGE_NOTE)} ${e(DISCLAIMER)}</p>
33954
+ <h2>${tests ? 6 : 5}. Verify this evidence</h2><p>The full signed result accompanies this packet${signedBy ? ` (signed by <code>${e(signedBy)}</code>)` : ""}. Anyone can check it was not altered: <code>npx saktum verify saktum-report.json</code>.</p>
33955
+ <h2>${tests ? 7 : 6}. Provider statements (completed by the provider; not verified by Saktum)</h2><table>${declare}</table>
33956
+ </body></html>
33957
+ `;
33958
+ }
33057
33959
 
33058
33960
  // packages/cli/dist/doctor.js
33059
33961
  import { spawn as spawn2, spawnSync } from "node:child_process";
@@ -33207,13 +34109,26 @@ var parseEnv = (kvs) => Object.fromEntries(kvs.map((kv) => {
33207
34109
  }));
33208
34110
  async function main(argv = process.argv) {
33209
34111
  let exitCode = 0;
33210
- const program2 = new Command().name("saktum").version(ENGINE_VERSION).description("Saktum Check: test MCP servers for conformance, sign-in, security and agent experience.").exitOverride();
33211
- program2.command("check").description("Test an MCP server: a URL, or the command that starts a local server (after --)").argument("<target...>", "https://host/mcp or -- node server.js").option("--packs <dir>", "directory of packs (default: the built-in packs)").option("--out <file>", "signed JSON result", "saktum-report.json").option("--html <file>", "also write an HTML report").option("--fail-on <severity>", "exit 1 if any failure at or above this severity", "high").option("--active", "run active checks (only against servers you own)", false).option("--key <path>", "signing key file (created on first use)").option("--env <KEY=VALUE>", "environment variable for a local server (repeatable); your own environment is never passed", collect, []).option("--header <Name: value>", 'HTTP header for a remote server, e.g. "Authorization: Bearer <token>" (repeatable)', collect, []).option("--price-per-mtok <usd>", "your model's price per million input tokens, for the context-cost estimate", "3").action(async (targetParts, o) => {
34112
+ const program2 = new Command().name("saktum").version(ENGINE_VERSION).description("Saktum Check: test MCP servers for trust (conformance, sign-in, security), functional behaviour, performance and agent readiness.").exitOverride();
34113
+ const withCheckOptions = (c, testsDefault) => c.option("--packs <dir>", "directory of packs (default: the built-in packs)").option("--out <file>", "signed JSON result", "saktum-report.json").option("--html <file>", "also write an HTML report").option("--badge <file>", "also write a README badge (SVG) with the trust and agent-readiness grades").option("--fail-on <severity>", "exit 1 if any failure at or above this severity", "high").option("--active", "call tools and measure load (only against servers you own; read-only tools unless named with --call)", false).option("--call <tool>", "with --active: also call this tool even if it is not annotated read-only (repeatable)", collect, []).option("--tests <file>", "run your test cases (YAML or JSON, see docs/TESTS.md)", testsDefault).option("--ignore <check=reason>", "ignore a check, with a reason shown in the report; check IDs may end with * (repeatable)", collect, []).option("--key <path>", "signing key file (created on first use)").option("--env <KEY=VALUE>", "environment variable for a local server (repeatable); your own environment is never passed", collect, []).option("--header <Name: value>", 'HTTP header for a remote server, e.g. "Authorization: Bearer <token>" (repeatable)', collect, []).option("--price-per-mtok <usd>", "your model's price per million input tokens, for the context-cost estimate", "3");
34114
+ const runCheckCommand = async (targetParts, o) => {
33212
34115
  if (!SEV.includes(o.failOn))
33213
34116
  throw new Error(`--fail-on must be one of ${SEV.join(", ")}`);
33214
34117
  const price = Number(o.pricePerMtok);
33215
34118
  if (!Number.isFinite(price) || price < 0)
33216
34119
  throw new Error("--price-per-mtok must be a number of US dollars, e.g. 3");
34120
+ const ignore = o.ignore.map((x) => {
34121
+ const i = x.indexOf("=");
34122
+ if (i < 1 || !x.slice(i + 1).trim())
34123
+ throw new Error(`--ignore must look like check.id="reason" (a reason is required)`);
34124
+ return { check: x.slice(0, i).trim(), reason: x.slice(i + 1).trim() };
34125
+ });
34126
+ let testCases;
34127
+ if (o.tests) {
34128
+ if (!existsSync3(o.tests))
34129
+ throw new Error(`Test file not found: ${o.tests}. See docs/TESTS.md for the format.`);
34130
+ testCases = await parseTestCases(readFileSync4(o.tests, "utf8"));
34131
+ }
33217
34132
  const target = parseTarget(targetParts);
33218
34133
  if (target.kind === "stdio" && o.env.length)
33219
34134
  target.env = parseEnv(o.env);
@@ -33222,25 +34137,87 @@ async function main(argv = process.argv) {
33222
34137
  const packs = o.packs ? loadPackDir(o.packs) : existsSync3(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
33223
34138
  let result;
33224
34139
  try {
33225
- result = await runTrustCheck(target, { packs, mode: o.active ? "active" : "passive", pricePerMTokUsd: price });
34140
+ result = await runTrustCheck(target, { packs, mode: o.active ? "active" : "passive", pricePerMTokUsd: price, callTools: o.call, testCases, ignore });
33226
34141
  } catch (e) {
33227
34142
  process.stderr.write(`Could not connect to ${sanitizeText(targetParts.join(" "), 120)}: ${sanitizeText(e.message, 300)}
33228
34143
  `);
33229
34144
  process.stderr.write(`Hint: run saktum doctor ${targetParts[0]?.startsWith("http") ? "" : "-- "}${sanitizeText(targetParts.join(" "), 120)} to see why.
33230
34145
  `);
33231
- exitCode = 2;
33232
- return;
34146
+ return 2;
33233
34147
  }
33234
34148
  const signed = signDocument(result, loadOrCreateKey(o.key));
33235
34149
  writeFileSync2(o.out, JSON.stringify(signed, null, 2));
33236
34150
  if (o.html)
33237
34151
  writeFileSync2(o.html, renderHtml(signed));
34152
+ if (o.badge)
34153
+ writeFileSync2(o.badge, badgeSvg(signed));
33238
34154
  process.stdout.write(renderTerminal(signed) + "\n");
33239
34155
  process.stdout.write(`
33240
- Signed result: ${sanitizeText(o.out)} (verify with: saktum verify ${sanitizeText(o.out)})
34156
+ Signed result: ${sanitizeText(o.out)} (verify with: saktum verify ${sanitizeText(o.out)})${o.badge ? `
34157
+ Badge: ${sanitizeText(o.badge)}` : ""}
33241
34158
  `);
33242
34159
  const threshold = SEV.indexOf(o.failOn);
33243
- exitCode = signed.findings.some((f) => f.status === "fail" && SEV.indexOf(f.severity) <= threshold) ? 1 : 0;
34160
+ return signed.findings.some((f) => f.status === "fail" && !f.suppressed && SEV.indexOf(f.severity) <= threshold) ? 1 : 0;
34161
+ };
34162
+ withCheckOptions(program2.command("check").description("Test an MCP server: a URL, or the command that starts a local server (after --)").argument("<target...>", "https://host/mcp or -- node server.js")).action(async (targetParts, o) => {
34163
+ exitCode = await runCheckCommand(targetParts, o);
34164
+ });
34165
+ withCheckOptions(program2.command("test").description("Run your test cases (saktum.tests.yaml by default) plus every check, against a server").argument("<target...>", "https://host/mcp or -- node server.js"), "saktum.tests.yaml").action(async (targetParts, o) => {
34166
+ exitCode = await runCheckCommand(targetParts, o);
34167
+ });
34168
+ program2.command("checks").description("List every check: what it tests, the standard behind it, and when it runs").option("--markdown", "print a Markdown table (as in docs/CHECKS.md)", false).option("--packs <dir>", "directory of packs (default: the built-in packs)").action((o) => {
34169
+ const packs = o.packs ? loadPackDir(o.packs) : existsSync3(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
34170
+ process.stdout.write(checksTable(packs, o.markdown));
34171
+ });
34172
+ const listTarget = async (targetParts, env, header) => {
34173
+ const target = parseTarget(targetParts);
34174
+ if (target.kind === "stdio" && env.length)
34175
+ target.env = parseEnv(env);
34176
+ if (target.kind === "streamable-http" && header.length)
34177
+ target.headers = parseHeaders(header);
34178
+ const s = await connect(target);
34179
+ try {
34180
+ return { target, tools: await s.listTools(), server: s.serverInfo };
34181
+ } finally {
34182
+ await s.close();
34183
+ }
34184
+ };
34185
+ program2.command("fix").description("Suggest annotations (and other quick fixes) for every tool, as code to paste").argument("<target...>", "https://host/mcp or -- node server.js").option("--format <ts|py|json>", "code style: TypeScript SDK, Python SDK, or JSON", "ts").option("--env <KEY=VALUE>", "environment variable for a local server (repeatable)", collect, []).option("--header <Name: value>", "HTTP header for a remote server (repeatable)", collect, []).action(async (targetParts, o) => {
34186
+ const { tools } = await listTarget(targetParts, o.env, o.header);
34187
+ process.stdout.write(renderFix(tools, o.format));
34188
+ });
34189
+ program2.command("snapshot").description("Write a lock file of the server's tools, to detect breaking or silent changes later with saktum diff").argument("<target...>", "https://host/mcp or -- node server.js").option("--out <file>", "lock file", "saktum.lock.json").option("--env <KEY=VALUE>", "environment variable for a local server (repeatable)", collect, []).option("--header <Name: value>", "HTTP header for a remote server (repeatable)", collect, []).action(async (targetParts, o) => {
34190
+ const { tools, server } = await listTarget(targetParts, o.env, o.header);
34191
+ writeFileSync2(o.out, JSON.stringify(toolsLock(tools, server), null, 2) + "\n");
34192
+ process.stdout.write(`Wrote ${sanitizeText(o.out)} with ${tools.length} tools. Commit it; run saktum diff in CI to catch breaking or silent changes.
34193
+ `);
34194
+ });
34195
+ program2.command("diff").description("Compare tools with a lock file: breaking changes, risky changes (silent tool changes), additions, and the version bump they need").argument("<lock>", "the lock file written by saktum snapshot").argument("[target...]", "a second lock file, or the server to compare (after --)").option("--allow-breaking", "do not fail on breaking or risky changes", false).option("--env <KEY=VALUE>", "environment variable for a local server (repeatable)", collect, []).option("--header <Name: value>", "HTTP header for a remote server (repeatable)", collect, []).action(async (lock, rest, o) => {
34196
+ const before = JSON.parse(readFileSync4(lock, "utf8"));
34197
+ const after = rest.length === 1 && rest[0].endsWith(".json") ? JSON.parse(readFileSync4(rest[0], "utf8")) : { tools: (await listTarget(rest, o.env, o.header)).tools };
34198
+ const d = diffLocks(before, after);
34199
+ const mark2 = { breaking: "\u2717 BREAKING", risky: "! REVIEW ", addition: "+ ADDED ", change: "~ CHANGED " };
34200
+ for (const c of d.changes)
34201
+ process.stdout.write(`${mark2[c.kind]} ${sanitizeText(c.tool, 60)}: ${sanitizeText(c.detail, 200)}
34202
+ `);
34203
+ process.stdout.write(`
34204
+ ${d.summary}
34205
+ `);
34206
+ exitCode = !o.allowBreaking && d.changes.some((c) => c.kind === "breaking" || c.kind === "risky") ? 1 : 0;
34207
+ });
34208
+ program2.command("docs").description("Generate a Markdown tools table and ready-to-paste client configuration").argument("<target...>", "https://host/mcp or -- npx -y your-package").option("--name <name>", "server name in the client configuration").option("--env <KEY=VALUE>", "environment variable for a local server (repeatable)", collect, []).option("--header <Name: value>", "HTTP header for a remote server (repeatable)", collect, []).action(async (targetParts, o) => {
34209
+ const { target, tools, server } = await listTarget(targetParts, o.env, o.header);
34210
+ const name = o.name ?? String(server?.["name"] ?? "server");
34211
+ process.stdout.write(docsFor(tools, name, target.kind === "stdio" ? { command: target.command, args: target.args } : { url: target.url }));
34212
+ });
34213
+ program2.command("packet").description("Turn a signed result into a printable security packet for customers' security reviews").argument("<result>", "a signed result (saktum-report.json)").option("--out <file>", "HTML packet (print to PDF from a browser)", "saktum-security-packet.html").action((file, o) => {
34214
+ const doc = JSON.parse(readFileSync4(file, "utf8"));
34215
+ const v = verifyDocument(doc);
34216
+ if (!v.valid)
34217
+ throw new Error(`The result's signature is not valid (${v.reason}); a packet must be built from an unaltered signed result.`);
34218
+ writeFileSync2(o.out, renderPacket(doc, v.kid));
34219
+ process.stdout.write(`Wrote ${sanitizeText(o.out)}: open it in a browser and print to PDF. Send it with ${sanitizeText(file)} so customers can verify it.
34220
+ `);
33244
34221
  });
33245
34222
  program2.command("doctor").description("Check your environment, and why a server will not start or connect").argument("[target...]", "optional: the same target you would pass to check").option("--env <KEY=VALUE>", "environment variable for a local server (repeatable)", collect, []).option("--header <Name: value>", "HTTP header for a remote server (repeatable)", collect, []).action(async (targetParts, o) => {
33246
34223
  const r = await runDoctor(targetParts ?? [], o.env, o.header);