@vantageos/mcp-doctor 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/doctor.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/doctor.ts
4
4
  import { readFileSync as readFileSync16, realpathSync } from "fs";
5
- import { dirname as dirname17, join as join27, resolve as resolve3 } from "path";
5
+ import { dirname as dirname17, join as join28, resolve as resolve3 } from "path";
6
6
  import { fileURLToPath as fileURLToPath2 } from "url";
7
7
 
8
8
  // src/scan.ts
@@ -106,6 +106,9 @@ var SubjectUnreadableError = class extends Error {
106
106
  this.form = form;
107
107
  }
108
108
  };
109
+ function loadSourceFile(path, root) {
110
+ return loadFile(path, root);
111
+ }
109
112
  function loadFile(path, root) {
110
113
  const raw = readFileSync(path, "utf8");
111
114
  const lines2 = raw.split("\n").map((r, i) => ({ n: i + 1, raw: r, comment: isCommentLine(r) }));
@@ -2772,6 +2775,7 @@ function outboundCalls(tree) {
2772
2775
  line: site.line.n,
2773
2776
  anchor: site.anchor,
2774
2777
  callee: site.match[0].replace(/\s*\($/, ""),
2778
+ col: site.col,
2775
2779
  args: splitTopLevel(inner),
2776
2780
  block: b ? b.text : site.line.raw.slice(open),
2777
2781
  unclosed: b === null
@@ -7733,6 +7737,11 @@ var c18StructureManifest = guardUnreadablePackageJson(
7733
7737
  { authoritative: false }
7734
7738
  );
7735
7739
 
7740
+ // src/runtime/sourceRoot.ts
7741
+ function runtimeSourceRoot(runtime) {
7742
+ return runtime.remote ? runtime.sourceRoot : runtime.root;
7743
+ }
7744
+
7736
7745
  // src/detectors/c19-served-descriptions.ts
7737
7746
  var PIN6 = STANDARD_PIN;
7738
7747
  var TOOL_DESC_INLINE_RE = /\b(?:s\.tool|\.tool|registerTool)\s*\(\s*(?:["'`][^"'`]+["'`]|[A-Za-z_$][\w$]*)\s*,\s*["'`]([^"'`]+)["'`]/;
@@ -7888,7 +7897,8 @@ var c19ServedDescriptions = {
7888
7897
  verdict: "server serves no tools over tools/list; served-descriptions check n/a (C-19)"
7889
7898
  };
7890
7899
  }
7891
- const ceiling = findCeiling(loadTree(runtime.root));
7900
+ const sourceRoot = runtimeSourceRoot(runtime);
7901
+ const ceiling = sourceRoot ? findCeiling(loadTree(sourceRoot)) : void 0;
7892
7902
  for (const t of runtime.tools) {
7893
7903
  if (!t.description) {
7894
7904
  return {
@@ -7926,6 +7936,16 @@ var c19ServedDescriptions = {
7926
7936
  };
7927
7937
  }
7928
7938
  }
7939
+ if (!sourceRoot) {
7940
+ const reason = `the ${runtime.tools.length} served description(s) are bilingual and carry their trigger phrase, but the declared per-tool ceiling lives in the source tree and none was given (--source DIR) \u2014 the budget half of C-19 is unmeasured, so the rule is not judged present`;
7941
+ return {
7942
+ id: this.id,
7943
+ anchor: runtime.root,
7944
+ state: "could-not-judge",
7945
+ reason,
7946
+ verdict: `could not judge: ${reason}`
7947
+ };
7948
+ }
7929
7949
  return {
7930
7950
  id: this.id,
7931
7951
  anchor: runtime.tools[0].name,
@@ -8071,7 +8091,18 @@ var c21ProgressiveDisclosure = {
8071
8091
  verdict: `could not judge: ${reason}`
8072
8092
  };
8073
8093
  }
8074
- const ceiling = findCeiling(loadTree(runtime.root));
8094
+ const sourceRoot = runtimeSourceRoot(runtime);
8095
+ if (!sourceRoot) {
8096
+ const reason = "the C-13 context ceiling is declared in the server's source tree and none was given (--source DIR) \u2014 C-21 has nothing to measure the served payload against";
8097
+ return {
8098
+ id: this.id,
8099
+ anchor: runtime.root,
8100
+ state: "could-not-judge",
8101
+ reason,
8102
+ verdict: `could not judge: ${reason}`
8103
+ };
8104
+ }
8105
+ const ceiling = findCeiling(loadTree(sourceRoot));
8075
8106
  if (!ceiling) {
8076
8107
  const reason = "no (global, perTool) context ceiling declared anywhere in the tree (C-13) \u2014 C-21 has nothing to measure against";
8077
8108
  return {
@@ -10148,6 +10179,75 @@ var d2 = {
10148
10179
  }
10149
10180
  };
10150
10181
 
10182
+ // src/detectors/servedFacts.ts
10183
+ function servedOrCouldNotJudge(id, rule, runtime) {
10184
+ const anchor = `${runtime.root} (served)`;
10185
+ if (runtime.launchError) {
10186
+ return {
10187
+ cnj: couldNotJudge(
10188
+ id,
10189
+ anchor,
10190
+ `the server could not be started/introspected, so nothing it serves was read: ${runtime.launchError} (${rule})`
10191
+ )
10192
+ };
10193
+ }
10194
+ if (!runtime.served) {
10195
+ return {
10196
+ cnj: couldNotJudge(
10197
+ id,
10198
+ anchor,
10199
+ `the introspector recorded no served facts for this run (list responses, capabilities, header probe, authorization-server metadata are unread) (${rule})`
10200
+ )
10201
+ };
10202
+ }
10203
+ return { served: runtime.served };
10204
+ }
10205
+ function declaredListMethods(caps) {
10206
+ const m = ["tools/list"];
10207
+ if (caps.resources) m.push("resources/list", "resources/templates/list");
10208
+ if (caps.prompts) m.push("prompts/list");
10209
+ return m;
10210
+ }
10211
+ function capabilityKeyPaths(caps, prefix = "") {
10212
+ if (typeof caps !== "object" || caps === null || Array.isArray(caps)) return [];
10213
+ const out = [];
10214
+ for (const [k, v] of Object.entries(caps)) {
10215
+ if (v === false) continue;
10216
+ const path = prefix ? `${prefix}.${k}` : k;
10217
+ out.push(path);
10218
+ out.push(...capabilityKeyPaths(v, path));
10219
+ }
10220
+ return out;
10221
+ }
10222
+ function listProblems(lists, methods) {
10223
+ const problems = [];
10224
+ for (const m of methods) {
10225
+ const l = lists.find((x) => x.method === m);
10226
+ if (!l) problems.push(`${m}: no record of it in this run`);
10227
+ else if (l.outcome === "refused")
10228
+ problems.push(`${m}: refused by the server (${l.detail ?? "no detail"})`);
10229
+ else if (l.outcome === "no-answer")
10230
+ problems.push(`${m}: no answer (${l.detail ?? "no detail"})`);
10231
+ }
10232
+ return problems;
10233
+ }
10234
+ function undeclaredProbeNote(caps) {
10235
+ const skills = capabilityKeyPaths(caps).filter((p) => /skill/i.test(p));
10236
+ return skills.length > 0 ? `${skills.join(", ")} declared: skills/list is not asked by this run` : void 0;
10237
+ }
10238
+ var RESULT_FIELDS_REVISION = "2026-07-28";
10239
+ function revisionCarriesResultFields(version) {
10240
+ if (version === void 0 || !/^\d{4}-\d{2}-\d{2}$/.test(version)) return void 0;
10241
+ return version >= RESULT_FIELDS_REVISION;
10242
+ }
10243
+ function absentBelowRevision(id, anchor, rule, fields, negotiated, where) {
10244
+ return couldNotJudge(
10245
+ id,
10246
+ anchor,
10247
+ `${where.join("; ")} lack ${fields}, but the session negotiated ${negotiated ?? "no named protocol revision"} and ${fields} are wire vocabulary of revision ${RESULT_FIELDS_REVISION}: the doctor could not obtain a ${RESULT_FIELDS_REVISION} session (initialize answers the highest revision the server supports), so what a ${RESULT_FIELDS_REVISION} client receives is unread (${rule})`
10248
+ );
10249
+ }
10250
+
10151
10251
  // src/detectors/d3.ts
10152
10252
  var RESULT_TYPE_RE = /\bresultType\b/;
10153
10253
  var KIT_RESULT_CALL_RE = /\b(buildToolsListResult|buildListResult|buildToolCallResult)\s*\(/;
@@ -10209,6 +10309,75 @@ var d3 = {
10209
10309
  state: "absent",
10210
10310
  verdict: "list/read builder returns {content} without resultType (grep resultType=0) -> add via protocol-kit"
10211
10311
  };
10312
+ },
10313
+ /**
10314
+ * SERVED half (S-2): the `resultType` the running server puts on each protocol list response it
10315
+ * serves. A server whose result shaping is the SDK's is judged here on the wire, not guessed from the
10316
+ * tree. A tool-call response is NOT exercised: the doctor invents no call, and says so.
10317
+ */
10318
+ runServed(runtime) {
10319
+ const got = servedOrCouldNotJudge(this.id, "S-2", runtime);
10320
+ if ("cnj" in got) return got.cnj;
10321
+ const { served } = got;
10322
+ const anchor = `${runtime.root} (served list responses)`;
10323
+ const methods = declaredListMethods(served.capabilities);
10324
+ const answered = [...served.lists, ...served.calls].filter((l) => l.outcome === "answered");
10325
+ const red = [];
10326
+ const absentOnly = /* @__PURE__ */ new Set();
10327
+ const ok = [];
10328
+ for (const l of answered) {
10329
+ if (typeof l.resultType === "string" && l.resultType.length > 0) {
10330
+ ok.push(`${l.method} resultType "${l.resultType}"`);
10331
+ } else if (l.resultType === void 0) {
10332
+ const t = `${l.method} is served with no resultType (result keys: ${(l.resultKeys ?? []).join(", ") || "none"})`;
10333
+ red.push(t);
10334
+ absentOnly.add(t);
10335
+ } else {
10336
+ red.push(
10337
+ `${l.method} is served with a resultType that is not a non-empty string (${JSON.stringify(l.resultType)})`
10338
+ );
10339
+ }
10340
+ }
10341
+ if (red.length > 0) {
10342
+ const carries = revisionCarriesResultFields(served.protocolVersion);
10343
+ if (carries !== true && red.every((r) => absentOnly.has(r))) {
10344
+ return absentBelowRevision(
10345
+ this.id,
10346
+ anchor,
10347
+ "S-2",
10348
+ "resultType",
10349
+ served.protocolVersion,
10350
+ red
10351
+ );
10352
+ }
10353
+ return {
10354
+ id: this.id,
10355
+ anchor,
10356
+ state: "non-conforming",
10357
+ verdict: `${red.join("; ")} -> every served response carries resultType (S-2, read on the served response)`
10358
+ };
10359
+ }
10360
+ const problems = [
10361
+ ...listProblems(served.lists, methods),
10362
+ ...served.calls.filter((c) => c.outcome !== "answered").map((c) => `${c.method}: ${c.outcome} (${c.detail ?? "no detail"})`),
10363
+ ...served.calls.length === 0 ? [
10364
+ "no tool-call response: no tool is declared read-only (readOnlyHint) with no required argument, and the doctor invents no call"
10365
+ ] : []
10366
+ ];
10367
+ const note = undeclaredProbeNote(served.capabilities);
10368
+ if (problems.length > 0 || note || ok.length === 0) {
10369
+ return couldNotJudge(
10370
+ this.id,
10371
+ anchor,
10372
+ `served resultType read on ${ok.length > 0 ? ok.join(", ") : "no list response"}; unread: ${[...problems, ...note ? [note] : []].join("; ") || "no list response answered"} (S-2)`
10373
+ );
10374
+ }
10375
+ return {
10376
+ id: this.id,
10377
+ anchor,
10378
+ state: "present",
10379
+ verdict: `resultType served on ${ok.join(", ")} (read on the wire, tool-call response included) (S-2)`
10380
+ };
10212
10381
  }
10213
10382
  };
10214
10383
 
@@ -10279,6 +10448,69 @@ var d4 = {
10279
10448
  state: "absent",
10280
10449
  verdict: "list/read builders lack ttlMs/cacheScope (grep=0) -> add CacheableResult"
10281
10450
  };
10451
+ },
10452
+ /**
10453
+ * SERVED half (S-3): `ttlMs` AND `cacheScope` on every list response the running server serves.
10454
+ * Both are required on each (the standard: "les deux presents sur toutes"); one missing is named.
10455
+ */
10456
+ runServed(runtime) {
10457
+ const got = servedOrCouldNotJudge(this.id, "S-3", runtime);
10458
+ if ("cnj" in got) return got.cnj;
10459
+ const { served } = got;
10460
+ const anchor = `${runtime.root} (served list responses)`;
10461
+ const methods = declaredListMethods(served.capabilities);
10462
+ const answered = served.lists.filter((l) => l.outcome === "answered");
10463
+ const red = [];
10464
+ const absentOnly = /* @__PURE__ */ new Set();
10465
+ const ok = [];
10466
+ for (const l of answered) {
10467
+ const bad = [];
10468
+ if (l.ttlMs === void 0) bad.push("ttlMs absent");
10469
+ else if (typeof l.ttlMs !== "number" || !Number.isFinite(l.ttlMs) || l.ttlMs < 0)
10470
+ bad.push(`ttlMs is not a non-negative number (${JSON.stringify(l.ttlMs)})`);
10471
+ if (l.cacheScope === void 0) bad.push("cacheScope absent");
10472
+ else if (typeof l.cacheScope !== "string" || l.cacheScope.length === 0)
10473
+ bad.push(`cacheScope is not a non-empty string (${JSON.stringify(l.cacheScope)})`);
10474
+ if (bad.length > 0) {
10475
+ const t = `${l.method}: ${bad.join(", ")}`;
10476
+ red.push(t);
10477
+ if (bad.every((b) => b.endsWith(" absent"))) absentOnly.add(t);
10478
+ } else ok.push(`${l.method} ttlMs ${String(l.ttlMs)} cacheScope "${String(l.cacheScope)}"`);
10479
+ }
10480
+ if (red.length > 0) {
10481
+ const carries = revisionCarriesResultFields(served.protocolVersion);
10482
+ if (carries !== true && red.every((r) => absentOnly.has(r))) {
10483
+ return absentBelowRevision(
10484
+ this.id,
10485
+ anchor,
10486
+ "S-3",
10487
+ "ttlMs/cacheScope",
10488
+ served.protocolVersion,
10489
+ red
10490
+ );
10491
+ }
10492
+ return {
10493
+ id: this.id,
10494
+ anchor,
10495
+ state: "non-conforming",
10496
+ verdict: `${red.join("; ")} -> every served list/read response carries ttlMs and cacheScope (S-3, read on the served response)`
10497
+ };
10498
+ }
10499
+ const problems = listProblems(served.lists, methods);
10500
+ const note = undeclaredProbeNote(served.capabilities);
10501
+ if (problems.length > 0 || note || ok.length === 0) {
10502
+ return couldNotJudge(
10503
+ this.id,
10504
+ anchor,
10505
+ `served ttlMs/cacheScope read on ${ok.length > 0 ? ok.join(", ") : "no list response"}; unread: ${[...problems, ...note ? [note] : []].join("; ") || "no list response answered"} (S-3)`
10506
+ );
10507
+ }
10508
+ return {
10509
+ id: this.id,
10510
+ anchor,
10511
+ state: "present",
10512
+ verdict: `ttlMs and cacheScope served on ${ok.join(", ")} (read on the wire) (S-3)`
10513
+ };
10282
10514
  }
10283
10515
  };
10284
10516
 
@@ -11649,9 +11881,10 @@ var d16 = {
11649
11881
  verdict: "[dynamic] the running server serves NO version on the pre-auth initialize handshake -> expose a version sourced from package.json (Server Rule 16)"
11650
11882
  };
11651
11883
  }
11652
- const pkgVersion = readPackageVersion(runtime.root);
11884
+ const sourceRoot = runtimeSourceRoot(runtime);
11885
+ const pkgVersion = sourceRoot ? readPackageVersion(sourceRoot) : null;
11653
11886
  if (!pkgVersion) {
11654
- const reason = `[dynamic] the server serves version "${served}" but its package.json version could not be read to compare against \u2014 canonical version unestablished (Server Rule 16)`;
11887
+ const reason = `[dynamic] the server serves version "${served}" but its package.json version could not be read to compare against \u2014 canonical version unestablished${sourceRoot ? "" : " (no source tree was given: --source DIR)"} (Server Rule 16)`;
11655
11888
  return {
11656
11889
  id: this.id,
11657
11890
  anchor,
@@ -13646,9 +13879,9 @@ function dServer6PositiveControls() {
13646
13879
  }
13647
13880
  };
13648
13881
  }
13649
- function referencedIdentifiers(argText) {
13650
- const interps = [...argText.matchAll(/\$\{([^}]*)\}/g)].map((m) => m[1]).join(" ");
13651
- const noStrings = argText.replace(/`(?:[^`\\]|\\.)*`/g, " ").replace(/'(?:[^'\\]|\\.)*'/g, " ").replace(/"(?:[^"\\]|\\.)*"/g, " ");
13882
+ function referencedIdentifiers(argText2) {
13883
+ const interps = [...argText2.matchAll(/\$\{([^}]*)\}/g)].map((m) => m[1]).join(" ");
13884
+ const noStrings = argText2.replace(/`(?:[^`\\]|\\.)*`/g, " ").replace(/'(?:[^'\\]|\\.)*'/g, " ").replace(/"(?:[^"\\]|\\.)*"/g, " ");
13652
13885
  return `${noStrings} ${interps}`;
13653
13886
  }
13654
13887
  function collectLogCalls(file) {
@@ -13661,7 +13894,7 @@ function collectLogCalls(file) {
13661
13894
  if (!m) continue;
13662
13895
  const openIdx = line.raw.indexOf("(", m.index ?? 0);
13663
13896
  let depth = 0;
13664
- let argText = "";
13897
+ let argText2 = "";
13665
13898
  let closed = false;
13666
13899
  for (let j = i; j < code.length && !closed; j++) {
13667
13900
  const raw = j === i ? line.raw.slice(openIdx) : code[j].raw;
@@ -13676,14 +13909,14 @@ function collectLogCalls(file) {
13676
13909
  break;
13677
13910
  }
13678
13911
  }
13679
- if (depth >= 1) argText += ch;
13912
+ if (depth >= 1) argText2 += ch;
13680
13913
  }
13681
- if (!closed) argText += " ";
13914
+ if (!closed) argText2 += " ";
13682
13915
  }
13683
13916
  if (!closed) {
13684
13917
  unbalanced.push(`${file.rel}:${line.n}`);
13685
13918
  } else {
13686
- calls.push({ argText, anchor: `${file.rel}:${line.n}`, line: line.n });
13919
+ calls.push({ argText: argText2, anchor: `${file.rel}:${line.n}`, line: line.n });
13687
13920
  }
13688
13921
  }
13689
13922
  return { calls, unbalanced };
@@ -15083,6 +15316,122 @@ var e12HostCapabilityPlacement = {
15083
15316
  }
15084
15317
  };
15085
15318
 
15319
+ // src/detectors/installedAs.ts
15320
+ import { readdirSync as readdirSync12, statSync as statSync19 } from "fs";
15321
+ import { join as join25 } from "path";
15322
+ var KEY = (k) => `(?:["']${k}["']|\\b${k}\\b)`;
15323
+ function flagTrueRe(key) {
15324
+ return new RegExp(`${KEY(key)}\\s*:\\s*true\\b`);
15325
+ }
15326
+ function authMethodsRe() {
15327
+ return {
15328
+ key: new RegExp(`${KEY("token_endpoint_auth_methods_supported")}\\s*:`),
15329
+ literal: new RegExp(`${KEY("token_endpoint_auth_methods_supported")}\\s*:\\s*\\[`),
15330
+ none: new RegExp(
15331
+ `${KEY("token_endpoint_auth_methods_supported")}\\s*:\\s*\\[[^\\]]*["'\`]none["'\`]`
15332
+ )
15333
+ };
15334
+ }
15335
+ var ROUTE_RE = /["'`]\/?\.well-known\/oauth-authorization-server["'`]/;
15336
+ var MAX_BYTES = 1e6;
15337
+ var MAX_FILES_PER_PACKAGE = 3e3;
15338
+ var SOURCE_EXT = /\.(?:js|mjs|cjs|json)$/;
15339
+ function declaredDependencies(tree) {
15340
+ const json = tree.packageJson?.json;
15341
+ const deps = json && typeof json.dependencies === "object" ? json.dependencies : null;
15342
+ return deps && !Array.isArray(deps) ? Object.keys(deps).sort() : [];
15343
+ }
15344
+ function readInstalledAs(tree) {
15345
+ const out = { installed: false, missing: [], publishers: [], unread: [] };
15346
+ const nm = join25(baseOf(tree), "node_modules");
15347
+ try {
15348
+ out.installed = statSync19(nm).isDirectory();
15349
+ } catch {
15350
+ out.installed = false;
15351
+ }
15352
+ if (!out.installed) return out;
15353
+ const methods = authMethodsRe();
15354
+ for (const dep of declaredDependencies(tree)) {
15355
+ const dir = join25(nm, dep);
15356
+ try {
15357
+ if (!statSync19(dir).isDirectory()) throw new Error("not a directory");
15358
+ } catch {
15359
+ out.missing.push(dep);
15360
+ continue;
15361
+ }
15362
+ const files = [];
15363
+ const walk2 = (d) => {
15364
+ let names;
15365
+ try {
15366
+ names = readdirSync12(d).sort();
15367
+ } catch (e) {
15368
+ out.unread.push(
15369
+ `${d.slice(nm.length + 1)} (directory not listed: ${e.message})`
15370
+ );
15371
+ return;
15372
+ }
15373
+ for (const n of names) {
15374
+ if (files.length >= MAX_FILES_PER_PACKAGE) return;
15375
+ if (n === "node_modules") continue;
15376
+ const full = join25(d, n);
15377
+ let st;
15378
+ try {
15379
+ st = statSync19(full);
15380
+ } catch (e) {
15381
+ out.unread.push(`${full.slice(nm.length + 1)} (not stat'ed: ${e.message})`);
15382
+ continue;
15383
+ }
15384
+ if (st.isDirectory()) walk2(full);
15385
+ else if (st.isFile() && SOURCE_EXT.test(n) && !n.endsWith(".d.ts")) files.push(full);
15386
+ }
15387
+ };
15388
+ walk2(dir);
15389
+ if (files.length >= MAX_FILES_PER_PACKAGE) {
15390
+ out.unread.push(`${dep} (more than ${MAX_FILES_PER_PACKAGE} files: the rest were not read)`);
15391
+ }
15392
+ const read = [];
15393
+ for (const f of files) {
15394
+ const rel = f.slice(nm.length + 1);
15395
+ try {
15396
+ if (statSync19(f).size > MAX_BYTES) {
15397
+ out.unread.push(`${rel} (larger than ${MAX_BYTES} bytes: not read)`);
15398
+ continue;
15399
+ }
15400
+ read.push({ rel, rows: uncommentedLines(loadSourceFile(f, nm)) });
15401
+ } catch (e) {
15402
+ out.unread.push(`${rel} (not read: ${e.message})`);
15403
+ }
15404
+ }
15405
+ if (!read.some((r) => r.rows.some((row) => ROUTE_RE.test(row)))) continue;
15406
+ out.publishers.push(dep);
15407
+ const find = (re) => {
15408
+ for (const r of read) {
15409
+ const i = r.rows.findIndex((row) => re.test(row));
15410
+ if (i >= 0) return { anchor: `node_modules/${r.rel}:${i + 1}` };
15411
+ }
15412
+ return void 0;
15413
+ };
15414
+ out.cimd ??= find(flagTrueRe("client_id_metadata_document_supported"));
15415
+ out.iss ??= find(flagTrueRe("authorization_response_iss_parameter_supported"));
15416
+ for (const r of read) {
15417
+ const joined = r.rows.join("\n");
15418
+ const m = methods.none.exec(joined);
15419
+ if (m && !out.none) {
15420
+ out.none = {
15421
+ anchor: `node_modules/${r.rel}:${joined.slice(0, m.index).split("\n").length}`
15422
+ };
15423
+ }
15424
+ const k = methods.key.exec(joined);
15425
+ if (k && !out.authMethodsKeyWithoutNone) {
15426
+ out.authMethodsKeyWithoutNone = {
15427
+ anchor: `node_modules/${r.rel}:${joined.slice(0, k.index).split("\n").length}`
15428
+ };
15429
+ }
15430
+ }
15431
+ }
15432
+ return out;
15433
+ }
15434
+
15086
15435
  // src/detectors/s5-authz-elements.ts
15087
15436
  var SUBJECT_RE = /WWW-Authenticate|verifyMcpAccessToken|unauthorizedChallenge|oauth-protected-resource/i;
15088
15437
  var BARE_BASE_RE = /^(?:issuer|baseUrl|origin|publicBaseUrl|BASE_URL|[\w$]+\.baseUrl|[\w$]+\.issuer|[\w$]+\.origin)$/;
@@ -15090,11 +15439,69 @@ var SESSION_RE2 = /\b(?:session\w*|__session|getAuth|verifyClerk\w*|requireUser|
15090
15439
  var ISSUE_RE = /createAuthorizationCode|authorization_code|issueCode|codeStore\.(?:create|put|set)|randomOpaqueToken|searchParams\.set\(\s*["'`]code["'`]/;
15091
15440
  var DELEGATE_RE = /\b(?:startAuthorize|handleAuthorize|completeAuthorize)\s*\(/;
15092
15441
  function quotedKeyTrue(key) {
15093
- return new RegExp(`(?:["']${key}["']|\\b${key}\\b)\\s*:\\s*true\\b`);
15442
+ return flagTrueRe(key);
15094
15443
  }
15095
15444
  function texts(tree) {
15096
15445
  return tree.files.map((file) => ({ file, text: uncommentedLines(file).join("\n") }));
15097
15446
  }
15447
+ var DOCUMENT_KEY_RE = new RegExp(
15448
+ `(?:["'](?:${[
15449
+ "authorization_endpoint",
15450
+ "token_endpoint",
15451
+ "response_types_supported",
15452
+ "grant_types_supported",
15453
+ "token_endpoint_auth_methods_supported",
15454
+ "jwks_uri",
15455
+ "registration_endpoint"
15456
+ ].join("|")})["']|\\b(?:${[
15457
+ "authorization_endpoint",
15458
+ "token_endpoint",
15459
+ "response_types_supported",
15460
+ "grant_types_supported",
15461
+ "token_endpoint_auth_methods_supported",
15462
+ "jwks_uri",
15463
+ "registration_endpoint"
15464
+ ].join("|")})\\b)\\s*:`
15465
+ );
15466
+ function delegatedAsElements(tree, fallbackAnchor) {
15467
+ const inst = readInstalledAs(tree);
15468
+ const owed = (what) => [
15469
+ { status: "owed", text: what, anchor: fallbackAnchor }
15470
+ ];
15471
+ const unread = inst.unread.length > 0 ? ` (not read: ${inst.unread.slice(0, 3).join("; ")})` : "";
15472
+ if (!inst.installed) {
15473
+ const r = owed(
15474
+ "the AS metadata document is written by a dependency, not by this tree, and node_modules is absent: install with the lockfile's manager and re-run, or read the served metadata (--url)"
15475
+ );
15476
+ return { g: r, l: r };
15477
+ }
15478
+ if (inst.publishers.length === 0) {
15479
+ const r = owed(
15480
+ `the AS metadata document is not written by this tree and no installed declared dependency serves ${"`/.well-known/oauth-authorization-server`"}${inst.missing.length > 0 ? ` (declared but not installed: ${inst.missing.slice(0, 5).join(", ")})` : ""}${unread}: read the served metadata (--url)`
15481
+ );
15482
+ return { g: r, l: r };
15483
+ }
15484
+ const pk = inst.publishers.join(", ");
15485
+ const g = inst.cimd && inst.none ? [
15486
+ {
15487
+ status: "ok",
15488
+ text: `CIMD announced (${inst.cimd.anchor}) and "none" listed (${inst.none.anchor}) by the installed ${pk}`,
15489
+ anchor: inst.cimd.anchor
15490
+ }
15491
+ ] : owed(
15492
+ `the installed ${pk} serves the AS metadata but its code does not state ${[inst.cimd ? "" : "client_id_metadata_document_supported: true", inst.none ? "" : '"none" in token_endpoint_auth_methods_supported'].filter(Boolean).join(" nor ")}${unread}: an installed library can prove an element, never its absence; read the served metadata (--url)`
15493
+ );
15494
+ const l = inst.iss ? [
15495
+ {
15496
+ status: "owed",
15497
+ text: `the installed ${pk} announces authorization_response_iss_parameter_supported: true (${inst.iss.anchor}); owed (probe): \`iss\` is returned on every authorization response, error responses included`,
15498
+ anchor: inst.iss.anchor
15499
+ }
15500
+ ] : owed(
15501
+ `the installed ${pk} serves the AS metadata but its code does not state authorization_response_iss_parameter_supported: true${unread}: read the served metadata (--url)`
15502
+ );
15503
+ return { g, l };
15504
+ }
15098
15505
  function s5PositiveControls() {
15099
15506
  return {
15100
15507
  bare: BARE_BASE_RE.test("issuer") && !BARE_BASE_RE.test("`${issuer}/mcp`"),
@@ -15206,26 +15613,41 @@ var s5AuthzElements = {
15206
15613
  );
15207
15614
  }
15208
15615
  } else {
15209
- const cimd = lineHits(tree, quotedKeyTrue("client_id_metadata_document_supported"));
15210
- if (cimd.length === 0) {
15211
- add(
15212
- "g",
15213
- "red",
15214
- "the AS metadata does not announce client_id_metadata_document_supported: true (Claude requires the CIMD pair)"
15215
- );
15216
- }
15217
- const none = all.some(
15218
- ({ text }) => /token_endpoint_auth_methods_supported\s*:\s*\[[^\]]*["'`]none["'`]/.test(text)
15219
- );
15220
- if (!none) {
15221
- add(
15222
- "g",
15223
- "red",
15224
- 'the AS metadata does not list "none" in token_endpoint_auth_methods_supported (public clients cannot authenticate)'
15225
- );
15616
+ const ownsDocument = lineHits(tree, DOCUMENT_KEY_RE).length > 0;
15617
+ const delegated = ownsDocument ? null : delegatedAsElements(tree, subject[0].anchor);
15618
+ if (delegated) {
15619
+ for (const e of delegated.g) add("g", e.status, e.text, e.anchor);
15620
+ } else {
15621
+ const cimd = lineHits(tree, quotedKeyTrue("client_id_metadata_document_supported"));
15622
+ if (cimd.length === 0) {
15623
+ add(
15624
+ "g",
15625
+ "red",
15626
+ "the AS metadata does not announce client_id_metadata_document_supported: true (Claude requires the CIMD pair)"
15627
+ );
15628
+ }
15629
+ const methods = authMethodsRe();
15630
+ const none = all.some(({ text }) => methods.none.test(text));
15631
+ if (!none) {
15632
+ const keyDefined = all.some(({ text }) => methods.key.test(text));
15633
+ const literal = all.some(({ text }) => methods.literal.test(text));
15634
+ if (keyDefined && !literal) {
15635
+ add(
15636
+ "g",
15637
+ "owed",
15638
+ 'token_endpoint_auth_methods_supported is written with a value that is not an array literal (a constant or an expression): whether it lists "none" is read from the served metadata'
15639
+ );
15640
+ } else {
15641
+ add(
15642
+ "g",
15643
+ "red",
15644
+ 'the AS metadata does not list "none" in token_endpoint_auth_methods_supported (public clients cannot authenticate)'
15645
+ );
15646
+ }
15647
+ }
15648
+ if (cimd.length > 0 && none)
15649
+ add("g", "ok", 'CIMD announced and "none" listed', cimd[0].anchor);
15226
15650
  }
15227
- if (cimd.length > 0 && none)
15228
- add("g", "ok", 'CIMD announced and "none" listed', cimd[0].anchor);
15229
15651
  const claude = lineHits(tree, /claude\.ai\/api\/mcp\/auth_callback/);
15230
15652
  add(
15231
15653
  "h",
@@ -15329,20 +15751,24 @@ var s5AuthzElements = {
15329
15751
  "no OIDC discovery published; it is owed only to a server aimed at a host that binds enterprise accounts, which no source states"
15330
15752
  );
15331
15753
  }
15332
- const iss = lineHits(tree, quotedKeyTrue("authorization_response_iss_parameter_supported"));
15333
- if (iss.length === 0) {
15334
- add(
15335
- "l",
15336
- "red",
15337
- "the AS metadata does not announce authorization_response_iss_parameter_supported: true (RFC 9207)"
15338
- );
15754
+ if (delegated) {
15755
+ for (const e of delegated.l) add("l", e.status, e.text, e.anchor);
15339
15756
  } else {
15340
- add(
15341
- "l",
15342
- "owed",
15343
- "the flag is announced; owed (probe): `iss` is returned on every authorization response, error responses included",
15344
- iss[0].anchor
15345
- );
15757
+ const iss = lineHits(tree, quotedKeyTrue("authorization_response_iss_parameter_supported"));
15758
+ if (iss.length === 0) {
15759
+ add(
15760
+ "l",
15761
+ "red",
15762
+ "the AS metadata does not announce authorization_response_iss_parameter_supported: true (RFC 9207)"
15763
+ );
15764
+ } else {
15765
+ add(
15766
+ "l",
15767
+ "owed",
15768
+ "the flag is announced; owed (probe): `iss` is returned on every authorization response, error responses included",
15769
+ iss[0].anchor
15770
+ );
15771
+ }
15346
15772
  }
15347
15773
  }
15348
15774
  const reds = els.filter((e) => e.status === "red");
@@ -15357,7 +15783,9 @@ var s5AuthzElements = {
15357
15783
  const exposed = els.filter((e) => e.status === "exposed");
15358
15784
  const owed = els.filter((e) => e.status === "owed");
15359
15785
  const uns = els.filter((e) => e.status === "unestablished");
15786
+ const established = els.filter((e) => e.status === "ok");
15360
15787
  const parts = [
15788
+ established.length > 0 ? `established: ${established.map((e) => e.text).join("; ")}` : "",
15361
15789
  exposed.length > 0 ? `sites exposed for a human verdict: ${exposed.map((e) => e.text).join("; ")}` : "",
15362
15790
  owed.length > 0 ? `owed (dynamic/probe): ${owed.map((e) => e.text).join("; ")}` : "",
15363
15791
  uns.length > 0 ? `unestablished condition: ${uns.map((e) => e.text).join("; ")}` : "",
@@ -15377,6 +15805,73 @@ var s5AuthzElements = {
15377
15805
  }))
15378
15806
  } : void 0
15379
15807
  );
15808
+ },
15809
+ /**
15810
+ * SERVED half (S-5 (g)(l)): the authorization-server metadata the PRM names, read on the wire.
15811
+ * (g): `client_id_metadata_document_supported` is the boolean true AND `token_endpoint_auth_methods_supported`
15812
+ * is an array listing "none". (l): `authorization_response_iss_parameter_supported` is the boolean true.
15813
+ * The other elements, and `iss` on every authorization response, are not readable from a metadata
15814
+ * document: the result says so and stays could-not-judge unless an element is contradicted.
15815
+ */
15816
+ runServed(runtime) {
15817
+ const got = servedOrCouldNotJudge(this.id, "S-5", runtime);
15818
+ if ("cnj" in got) return got.cnj;
15819
+ const as = got.served.authServer;
15820
+ const anchor = `${runtime.root} (served authorization-server metadata)`;
15821
+ if (as.kind !== "document") {
15822
+ return couldNotJudge(
15823
+ this.id,
15824
+ anchor,
15825
+ `the authorization-server metadata was not read: ${as.kind === "not-run" ? as.reason : `${as.url}: ${as.reason}`} (S-5 (g)(l))`
15826
+ );
15827
+ }
15828
+ const doc = as.document;
15829
+ const at = `served at ${as.url}`;
15830
+ const reds = [];
15831
+ const oks = [];
15832
+ const unreadable = [];
15833
+ const cimd = doc.client_id_metadata_document_supported;
15834
+ if (cimd === true) oks.push("client_id_metadata_document_supported true");
15835
+ else
15836
+ reds.push(
15837
+ `(g) the served AS metadata ${cimd === void 0 ? "does not announce" : `announces ${JSON.stringify(cimd)} for`} client_id_metadata_document_supported: true`
15838
+ );
15839
+ const methods = doc.token_endpoint_auth_methods_supported;
15840
+ if (Array.isArray(methods)) {
15841
+ if (methods.includes("none"))
15842
+ oks.push(`"none" in token_endpoint_auth_methods_supported ${JSON.stringify(methods)}`);
15843
+ else
15844
+ reds.push(
15845
+ `(g) the served AS metadata lists ${JSON.stringify(methods)} in token_endpoint_auth_methods_supported, without "none"`
15846
+ );
15847
+ } else if (methods === void 0) {
15848
+ reds.push(
15849
+ '(g) the served AS metadata has no token_endpoint_auth_methods_supported (so no "none")'
15850
+ );
15851
+ } else {
15852
+ unreadable.push(
15853
+ `token_endpoint_auth_methods_supported is served as ${JSON.stringify(methods)}, not an array`
15854
+ );
15855
+ }
15856
+ const iss = doc.authorization_response_iss_parameter_supported;
15857
+ if (iss === true) oks.push("authorization_response_iss_parameter_supported true");
15858
+ else
15859
+ reds.push(
15860
+ `(l) the served AS metadata ${iss === void 0 ? "does not announce" : `announces ${JSON.stringify(iss)} for`} authorization_response_iss_parameter_supported: true (RFC 9207)`
15861
+ );
15862
+ if (reds.length > 0) {
15863
+ return {
15864
+ id: this.id,
15865
+ anchor,
15866
+ state: "non-conforming",
15867
+ verdict: `${reds.join("; ")} (${at}) (S-5 (g)(l), read on the wire)`
15868
+ };
15869
+ }
15870
+ return couldNotJudge(
15871
+ this.id,
15872
+ anchor,
15873
+ `(g) and (l) hold on the served metadata (${at}): ${oks.join("; ")}${unreadable.length > 0 ? `; unreadable: ${unreadable.join("; ")}` : ""}. Not read over this surface: (f) PRM binding, (h) redirects, (i) /authorize sign-in, (j) jwt-bearer, (k) OIDC/UserInfo, and \`iss\` on every authorization response (probes or human verdicts) (S-5 (f)..(l))`
15874
+ );
15380
15875
  }
15381
15876
  };
15382
15877
 
@@ -15615,6 +16110,7 @@ ${rows[i + 1] ?? ""}`))) {
15615
16110
  };
15616
16111
 
15617
16112
  // src/detectors/s10-ssrf-guard.ts
16113
+ var SUBSCRIPTION_KEY_RE = /subscri|event|callback|webhook/i;
15618
16114
  var CALLER_MEMBER = /\b(?:(?:req|request)\.(?:body|query|params)|args|input|params|payload|delivery|subscription|opts|options|data)(?:\??\.[\w$]+)*\??\.(?:url|uri|href|callbackUrl|callback_url|webhookUrl|webhook_url|targetUrl|target_url|endpoint)\b/;
15619
16115
  var URL_PROP_NAMES = /* @__PURE__ */ new Set([
15620
16116
  "url",
@@ -15764,6 +16260,34 @@ var s10SsrfGuard = {
15764
16260
  dynamic[0]?.anchor ?? `${blocklistFiles[0]}:1`,
15765
16261
  `${[calls3, statedBlocklist].filter(Boolean).join(" and ")}, no caller-supplied full URL, no hand-written validation, no followed redirect and no incomplete blocklist; owed (dynamic): a subscription whose callback resolves to 127.0.0.1 is refused with -32602 or -32015, and a 302 to a second receiver reaches nothing (S-10)`
15766
16262
  );
16263
+ },
16264
+ /**
16265
+ * SERVED half (S-10): the dynamic probe is a SUBSCRIPTION whose callback resolves to loopback. A
16266
+ * server that declares no subscription or events surface has nothing to subscribe to: the dynamic
16267
+ * half is not applicable, and that is stated with the capability keys it was read from. A server
16268
+ * that declares one is could-not-judge: the probe needs a receiver the doctor does not stand up.
16269
+ * The static half (the outbound-fetch sites) is a source-tree read the served value does not cover:
16270
+ * this half NEVER returns absent or present, only could-not-judge naming both halves.
16271
+ */
16272
+ runServed(runtime, staticResult) {
16273
+ const got = servedOrCouldNotJudge(this.id, "S-10", runtime);
16274
+ if ("cnj" in got) return got.cnj;
16275
+ const anchor = `${runtime.root} (served capabilities)`;
16276
+ const keys = capabilityKeyPaths(got.served.capabilities);
16277
+ const surface = keys.filter((k) => SUBSCRIPTION_KEY_RE.test(k));
16278
+ if (surface.length > 0) {
16279
+ return couldNotJudge(
16280
+ this.id,
16281
+ anchor,
16282
+ `the server declares ${surface.join(", ")}: the S-10 subscription probe (a callback resolving to 127.0.0.1, then a 302 to a second receiver) needs a receiver the doctor does not stand up (S-10)`
16283
+ );
16284
+ }
16285
+ const fetchHalf = staticResult ? `the outbound-fetch half stays undecided (${(staticResult.reason ?? staticResult.verdict).slice(0, 200)})` : "the outbound-fetch half is a source-tree read and was NOT run over this surface";
16286
+ return couldNotJudge(
16287
+ this.id,
16288
+ anchor,
16289
+ `subscription half: not applicable, the server declares no subscription or events capability (capability keys served: ${keys.join(", ") || "none"}); ${fetchHalf}; the served value does not cover the outbound-fetch half, so S-10 is not settled (S-10)`
16290
+ );
15767
16291
  }
15768
16292
  };
15769
16293
 
@@ -15918,22 +16442,419 @@ var s12ListPagination = {
15918
16442
  state: "present",
15919
16443
  verdict: `${handled} hand-written list handler(s) emit nextCursor and no code decodes it (positive-control OK)${unserved.length > 0 ? `; ${unserved.join(", ")} are served by the SDK \u2014 dynamic page probe owed` : ""} (S-12)`
15920
16444
  };
15921
- }
15922
- };
15923
-
15924
- // src/detectors/s13-progress-cancel.ts
15925
- var TIMEOUT_RE = /\bsignal\b|\btimeout\b|AbortSignal|AbortController/i;
15926
- var LITERAL_ID = String.raw`(?:["'\`][^"'\`$]+["'\`]|\d+)`;
15927
- var STALE_CANCEL_RE = new RegExp(String.raw`requestId\s*:\s*${LITERAL_ID}`);
15928
- var STALE_PROGRESS_RE = new RegExp(String.raw`progressToken\s*:\s*${LITERAL_ID}`);
15929
- var CANCEL_HANDLER_RE = /CancelledNotificationSchema|["'`]notifications\/cancelled["'`]/;
15930
- var RESPOND_RE = /\brespond\s*\(|\bsendResponse\s*\(|\bres\.(?:json|send|end)\s*\(|\bsendResult\s*\(|\bsendError\s*\(|\btransport\.send\s*\(/;
15931
- function s13Controls() {
15932
- return {
15933
- sees: !TIMEOUT_RE.test("fetch(u, { method: 'POST' })") && STALE_CANCEL_RE.test("params: { requestId: 42 }") && STALE_PROGRESS_RE.test("params: { progressToken: 'tok' }") && RESPOND_RE.test("respond(id, {})"),
15934
- spares: TIMEOUT_RE.test("fetch(u, { signal: AbortSignal.timeout(1000) })") && !STALE_CANCEL_RE.test("params: { requestId: id }") && !RESPOND_RE.test("controllers.get(id)?.abort()")
15935
- };
15936
- }
16445
+ },
16446
+ /**
16447
+ * SERVED half (S-12): `nextCursor` on each protocol list method the running server serves. A served
16448
+ * cursor must be an opaque non-empty string and must be accepted when presented back untouched. A
16449
+ * page that carries no `nextCursor` is the terminal page: the server answered its WHOLE list, and
16450
+ * that is what is stated (growth past a page is not exercised: the doctor invents no entries).
16451
+ */
16452
+ runServed(runtime) {
16453
+ const got = servedOrCouldNotJudge(this.id, "S-12", runtime);
16454
+ if ("cnj" in got) return got.cnj;
16455
+ const { served } = got;
16456
+ const anchor = `${runtime.root} (served list responses)`;
16457
+ const methods = declaredListMethods(served.capabilities);
16458
+ const red = [];
16459
+ const unread = [];
16460
+ const ok = [];
16461
+ for (const m of methods) {
16462
+ const l = served.lists.find((x) => x.method === m);
16463
+ if (!l) {
16464
+ unread.push(`${m}: no record of it in this run`);
16465
+ } else if (l.outcome !== "answered") {
16466
+ unread.push(
16467
+ `${m}: ${l.outcome === "refused" ? "refused" : "no answer"} (${l.detail ?? "no detail"})`
16468
+ );
16469
+ } else if (l.nextCursor === void 0) {
16470
+ ok.push(
16471
+ `${m} served ${l.entries ?? "its"} entries in one page with no nextCursor (terminal page)`
16472
+ );
16473
+ } else if (typeof l.nextCursor !== "string" || l.nextCursor.length === 0) {
16474
+ red.push(
16475
+ `${m} serves a nextCursor that is not a non-empty string (${JSON.stringify(l.nextCursor)})`
16476
+ );
16477
+ } else if (!l.followUp || l.followUp.outcome === "no-answer") {
16478
+ unread.push(
16479
+ `${m}: the served cursor was not presented back (${l.followUp?.detail ?? "no follow-up recorded"})`
16480
+ );
16481
+ } else if (l.followUp.outcome === "refused") {
16482
+ red.push(
16483
+ `${m} refuses its own nextCursor presented back untouched (${l.followUp.detail ?? "no detail"})`
16484
+ );
16485
+ } else {
16486
+ ok.push(`${m} serves a nextCursor and answers the next page`);
16487
+ }
16488
+ }
16489
+ if (red.length > 0) {
16490
+ return {
16491
+ id: this.id,
16492
+ anchor,
16493
+ state: "non-conforming",
16494
+ verdict: `${red.join("; ")} -> a list method that paginates serves an opaque nextCursor that the next request accepts untouched (S-12, read on the served response)`
16495
+ };
16496
+ }
16497
+ const note = undeclaredProbeNote(served.capabilities);
16498
+ if (unread.length > 0 || note) {
16499
+ return couldNotJudge(
16500
+ this.id,
16501
+ anchor,
16502
+ `served pagination read on ${ok.length > 0 ? ok.join("; ") : "no list method"}; unread: ${[...unread, ...note ? [note] : []].join("; ")} (S-12)`
16503
+ );
16504
+ }
16505
+ return {
16506
+ id: this.id,
16507
+ anchor,
16508
+ state: "present",
16509
+ verdict: `${ok.join("; ")} (read on the wire; pagination under growth is not exercised: the doctor invents no entries) (S-12)`
16510
+ };
16511
+ }
16512
+ };
16513
+
16514
+ // src/detectors/s13OutboundSites.ts
16515
+ var TIMEOUT_RE = /\bsignal\b|\btimeout\b|AbortSignal|AbortController/i;
16516
+ var SCANNED_FORMS = "global fetch, axios / got / ky, http(s) / undici requests, injected fetchImpl / fetchWithToken, local wrappers (one level), SDK clients given a fetch option, imported-under-another-name HTTP clients";
16517
+ var INJECTED_CALLEE = /^(?:(?:[\w$]+(?:\?\.|\.))*(?:fetchImpl|fetchWithToken))$/;
16518
+ var TYPED_FETCH = /([A-Za-z_$][\w$]*)\s*\??\s*:\s*(?:typeof\s+(?:globalThis\s*\.\s*)?fetch|FetchLike)(?![\w$])/g;
16519
+ var ANY_CALLEE = /^(?:[\w$]+(?:\?\.|\.))*[\w$]+$/;
16520
+ var BARE_IDENT = /^[A-Za-z_$][\w$]*$/;
16521
+ var argText = (c) => c.src.shape.slice(c.open + 1, c.close);
16522
+ var isDeclaration = (c) => {
16523
+ const a = c.args[0];
16524
+ return a !== void 0 && /^\s*[A-Za-z_$][\w$]*\??\s*:\s*\S/.test(c.src.shape.slice(a[0], a[1]));
16525
+ };
16526
+ function typedFetchNames(s) {
16527
+ const names = /* @__PURE__ */ new Set();
16528
+ for (const h of s.shape.matchAll(TYPED_FETCH)) names.add(h[1]);
16529
+ return names;
16530
+ }
16531
+ function outboundSites(tree) {
16532
+ const sites = /* @__PURE__ */ new Map();
16533
+ const unreadable = [];
16534
+ const add = (s) => {
16535
+ const key = `${s.anchor}|${s.callee}`;
16536
+ const had = sites.get(key);
16537
+ if (!had || had.verdict === "timeout" && s.verdict === "none") sites.set(key, s);
16538
+ };
16539
+ const axiosDefault = productHits(tree, /axios\.defaults\.timeout/).length > 0;
16540
+ const step1Read = /* @__PURE__ */ new Set();
16541
+ for (const c of outboundCalls(tree)) {
16542
+ step1Read.add(`${c.anchor}:${c.col}`);
16543
+ if (c.unclosed) {
16544
+ unreadable.push({
16545
+ anchor: c.anchor,
16546
+ reason: `${c.anchor} (${c.callee}) is an outbound call that never closes its parentheses and was not read: whether it carries a timeout is unknown`
16547
+ });
16548
+ continue;
16549
+ }
16550
+ const covered = axiosDefault && /^axios/.test(c.callee) || TIMEOUT_RE.test(c.block);
16551
+ add({
16552
+ anchor: c.anchor,
16553
+ form: "direct call",
16554
+ callee: c.callee,
16555
+ verdict: covered ? "timeout" : "none",
16556
+ detail: `${c.anchor} (${c.callee}) is an outbound request with no timeout (no signal / timeout option)`
16557
+ });
16558
+ }
16559
+ const typed = new Map(srcs(tree).map((s) => [s, typedFetchNames(s)]));
16560
+ const fetchCalls = [];
16561
+ for (const c of callsMatching(tree, ANY_CALLEE)) {
16562
+ if (isDeclaration(c)) continue;
16563
+ const injected = INJECTED_CALLEE.test(c.callee) || (typed.get(c.src)?.has(c.callee) ?? false);
16564
+ if (injected) {
16565
+ fetchCalls.push(c);
16566
+ add({
16567
+ anchor: c.anchor,
16568
+ form: "injected fetch",
16569
+ callee: c.callee,
16570
+ verdict: TIMEOUT_RE.test(argText(c)) ? "timeout" : "none",
16571
+ detail: `${c.anchor} (${c.callee}) is an injected fetch called with no timeout (no signal / timeout option)`
16572
+ });
16573
+ } else if (c.callee === "fetch") fetchCalls.push(c);
16574
+ }
16575
+ const wrappers = /* @__PURE__ */ new Map();
16576
+ for (const c of fetchCalls) {
16577
+ const first = c.args[0] ? c.src.shape.slice(c.args[0][0], c.args[0][1]).trim() : "";
16578
+ if (!BARE_IDENT.test(first)) continue;
16579
+ const fns = enclosingFns(c.src, c.start);
16580
+ const inner = fns[fns.length - 1];
16581
+ if (!inner || !new RegExp(String.raw`(?<![\w$.])${esc(first)}(?![\w$])`).test(inner.header))
16582
+ continue;
16583
+ const named = [...fns].reverse().find((f) => f.name !== void 0);
16584
+ if (!named?.name) continue;
16585
+ const w = wrappers.get(named.name) ?? {
16586
+ name: named.name,
16587
+ defs: /* @__PURE__ */ new Set(),
16588
+ bodies: [],
16589
+ anchor: anchorAt(c.src, named.open)
16590
+ };
16591
+ w.defs.add(c.src);
16592
+ const carries = TIMEOUT_RE.test(argText(c));
16593
+ const body = w.bodies.find((b) => b.src === c.src && b.open === named.open);
16594
+ if (body) body.timeout = body.timeout && carries;
16595
+ else
16596
+ w.bodies.push({
16597
+ src: c.src,
16598
+ open: named.open,
16599
+ close: named.close,
16600
+ timeout: carries
16601
+ });
16602
+ wrappers.set(named.name, w);
16603
+ }
16604
+ const wrapperNames = new Set(wrappers.keys());
16605
+ const wrapperCalls = [];
16606
+ for (const w of wrappers.values()) {
16607
+ const applies = w.bodies.every((b) => b.timeout);
16608
+ for (const c of callsMatching(
16609
+ tree,
16610
+ new RegExp(String.raw`^(?:[\w$]+(?:\?\.|\.))*${esc(w.name)}$`)
16611
+ )) {
16612
+ if (isDeclaration(c) || !callReaches(c.src, c.callee, w.name, w.defs)) continue;
16613
+ if (w.bodies.some((b) => b.src === c.src && c.start > b.open && c.start < b.close)) continue;
16614
+ wrapperCalls.push(c);
16615
+ const fns = enclosingFns(c.src, c.start);
16616
+ const host = fns[fns.length - 1];
16617
+ const first = c.args[0] ? c.src.shape.slice(c.args[0][0], c.args[0][1]).trim() : "";
16618
+ const returned = /(?:\breturn\s+|=>\s*)$/.test(
16619
+ c.src.shape.slice(Math.max(0, c.start - 12), c.start)
16620
+ );
16621
+ if (host?.name && returned && BARE_IDENT.test(first) && new RegExp(String.raw`(?<![\w$.])${esc(first)}(?![\w$])`).test(host.header) && !wrapperNames.has(host.name)) {
16622
+ unreadable.push({
16623
+ anchor: c.anchor,
16624
+ reason: `${c.anchor} \`${c.callee}(...)\` is a wrapper (${w.name}, ${w.anchor}) called through a second wrapper (${host.name}): two levels of indirection, the timeout of its call sites is not followed`
16625
+ });
16626
+ continue;
16627
+ }
16628
+ const own = TIMEOUT_RE.test(argText(c));
16629
+ add({
16630
+ anchor: c.anchor,
16631
+ form: "wrapper call",
16632
+ callee: c.callee,
16633
+ verdict: applies || own ? "timeout" : "none",
16634
+ detail: `${c.anchor} (${c.callee}) is a call through the wrapper ${w.name} (${w.anchor}), which applies no timeout, and passes none`
16635
+ });
16636
+ }
16637
+ }
16638
+ const optionRanges = [];
16639
+ for (const c of callsMatching(tree, /^[A-Z][\w$]*(?:\.[\w$]+)*$/)) {
16640
+ if (!/\bnew\s+$/.test(c.src.shape.slice(Math.max(0, c.start - 8), c.start))) continue;
16641
+ for (const [a] of c.args) {
16642
+ const open = objectOpenAt(c.src, a);
16643
+ if (open < 0) continue;
16644
+ for (const p of objectProps(c.src, open) ?? []) {
16645
+ if (p.spread || p.key !== "fetch" && p.key !== "fetchImpl") continue;
16646
+ optionRanges.push({ src: c.src, from: p.from, to: p.to });
16647
+ const at = p.from + (/^\s*/.exec(c.src.shape.slice(p.from, p.to))?.[0].length ?? 0);
16648
+ const anchor = anchorAt(c.src, at);
16649
+ const v = p.value.trim();
16650
+ const call = /^([A-Za-z_$][\w$.]*)\s*\(/.exec(v);
16651
+ if (call && wrapperNames.has(call[1].split(".").pop() ?? "") && wrapperCalls.some((w) => w.src === c.src && w.start >= p.from && w.start < p.to))
16652
+ continue;
16653
+ if (/^(?:(?:globalThis|window|self|global)\s*\.\s*)?fetch$/.test(v)) {
16654
+ add({
16655
+ anchor,
16656
+ form: "SDK fetch option",
16657
+ callee: `new ${c.callee}`,
16658
+ verdict: "none",
16659
+ detail: `${anchor} (new ${c.callee}) is handed the global fetch as its fetch option: no timeout`
16660
+ });
16661
+ } else if (TIMEOUT_RE.test(v)) {
16662
+ add({
16663
+ anchor,
16664
+ form: "SDK fetch option",
16665
+ callee: `new ${c.callee}`,
16666
+ verdict: "timeout",
16667
+ detail: ""
16668
+ });
16669
+ } else {
16670
+ unreadable.push({
16671
+ anchor,
16672
+ reason: `${anchor} (new ${c.callee}) is handed a fetch option the scan does not follow (\`${v.replace(/\s+/g, " ").slice(0, 60)}\`): whether it carries a timeout is unknown`
16673
+ });
16674
+ }
16675
+ }
16676
+ }
16677
+ }
16678
+ for (const u of unresolvedOutbound(tree)) unreadable.push(u);
16679
+ for (const u of globalFetchReads(tree, typed, wrapperCalls, optionRanges, step1Read, add))
16680
+ unreadable.push(u);
16681
+ return {
16682
+ sites: [...sites.values()].sort(
16683
+ (x, y) => x.anchor.localeCompare(y.anchor, "en", { numeric: true })
16684
+ ),
16685
+ unreadable
16686
+ };
16687
+ }
16688
+ var ROOT = String.raw`(?:globalThis|window|self|global)`;
16689
+ var INJECTED_NAME = /^(?:fetchImpl|fetchWithToken)$/;
16690
+ function globalFetchReads(tree, typed, wrapperCalls, optionRanges, step1Read, addSite) {
16691
+ const out = [];
16692
+ const seen = /* @__PURE__ */ new Set();
16693
+ for (const s of srcs(tree)) {
16694
+ const sh = s.shape;
16695
+ const judgedRoot = /* @__PURE__ */ new Set();
16696
+ const recognised = (start, end) => {
16697
+ if (/\btypeof\s+$/.test(sh.slice(Math.max(0, start - 12), start))) return true;
16698
+ if (optionRanges.some((r) => r.src === s && start >= r.from && end <= r.to)) return true;
16699
+ if (wrapperCalls.some((c) => c.src === s && start > c.open && end <= c.close)) return true;
16700
+ const before = /(?:(fetchImpl|fetchWithToken)\s*:\s*)?([\w$]+)\s*(?::\s*[^=,;(){}]+?)?=\s*$/.exec(
16701
+ sh.slice(Math.max(0, start - 120), start)
16702
+ );
16703
+ return before !== null && (before[1] !== void 0 || INJECTED_NAME.test(before[2]) || (typed.get(s)?.has(before[2]) ?? false));
16704
+ };
16705
+ const report = (start, end, form) => {
16706
+ const anchor = anchorAt(s, start);
16707
+ const key = `${anchor}|${form}`;
16708
+ if (seen.has(key)) return;
16709
+ seen.add(key);
16710
+ out.push({
16711
+ anchor,
16712
+ reason: `${anchor} reads the global fetch as ${form}, a form the scan does not follow: whether the request it emits carries a timeout is unknown`
16713
+ });
16714
+ void end;
16715
+ };
16716
+ const nextIsCall = (end) => /^\s*(?:\?\.\s*)?(?:<[^<>()]*>\s*)?\(/.test(sh.slice(end, end + 40));
16717
+ const shadowed = /\b(?:const|let|var|function|class)\s+fetch(?![\w$])/.test(sh) || /\bimport\s*\{[^}]*(?<![\w$])fetch(?![\w$])[^}]*\}/.test(sh);
16718
+ if (!shadowed) {
16719
+ for (const h of sh.matchAll(/(?<![\w$.])fetch(?![\w$])/g)) {
16720
+ const i = h.index ?? 0;
16721
+ const e = i + 5;
16722
+ const prev = sh.slice(Math.max(0, i - 12), i);
16723
+ if (/\btypeof\s+$/.test(prev)) continue;
16724
+ const after = sh.slice(e, e + 40);
16725
+ if (/^\s*\??:/.test(after) && !/\?\s*$/.test(prev)) continue;
16726
+ if (/^\s*=(?![=>])/.test(after)) continue;
16727
+ if (/^\s*(?:<[^<>()]*>\s*)?\(/.test(after)) {
16728
+ const line = sh.slice(0, i).split("\n").length;
16729
+ const col = i - (sh.lastIndexOf("\n", i - 1) + 1);
16730
+ if (step1Read.has(`${s.rel}:${line}:${col}`)) continue;
16731
+ const open = sh.indexOf("(", e);
16732
+ const close = matchClose(sh, open);
16733
+ if (close < 0) {
16734
+ report(
16735
+ i,
16736
+ e,
16737
+ "a `fetch(` call whose parentheses never close (not read by the direct-call reader)"
16738
+ );
16739
+ continue;
16740
+ }
16741
+ const inner = sh.slice(open + 1, close);
16742
+ if (/^\s*[A-Za-z_$][\w$]*\??\s*:\s*\S/.test(inner)) continue;
16743
+ const anchor = anchorAt(s, i);
16744
+ addSite({
16745
+ anchor,
16746
+ form: "direct call",
16747
+ callee: "fetch",
16748
+ verdict: TIMEOUT_RE.test(s.code.slice(open, close + 1)) ? "timeout" : "none",
16749
+ detail: `${anchor} (fetch) is an outbound request with no timeout (no signal / timeout option)`
16750
+ });
16751
+ continue;
16752
+ }
16753
+ if (recognised(i, e)) continue;
16754
+ const call = /^\s*(?:\?\.\s*)?\(/.test(after);
16755
+ report(
16756
+ i,
16757
+ e,
16758
+ call ? "`fetch?.(...)`" : /^\s*\./.test(after) ? "`fetch` with a member read (`fetch.call` / `.apply` / `.bind`)" : "a value (`fetch` not called: aliased, passed, applied, stored or sequence-expressioned)"
16759
+ );
16760
+ }
16761
+ }
16762
+ for (const h of sh.matchAll(
16763
+ new RegExp(String.raw`(?<![\w$.])${ROOT}\s*\??\.\s*fetch(?![\w$])`, "g")
16764
+ )) {
16765
+ const i = h.index ?? 0;
16766
+ const e = i + h[0].length;
16767
+ if (recognised(i, e)) continue;
16768
+ report(
16769
+ i,
16770
+ e,
16771
+ nextIsCall(e) ? `\`${h[0].replace(/\s+/g, "")}(...)\`` : `a value (\`${h[0].replace(/\s+/g, "")}\` not called)`
16772
+ );
16773
+ }
16774
+ for (const h of sh.matchAll(new RegExp(String.raw`(?<![\w$.])${ROOT}\s*(?:\?\.\s*)?\[`, "g"))) {
16775
+ const i = h.index ?? 0;
16776
+ const open = i + h[0].length - 1;
16777
+ const close = matchClose(sh, open);
16778
+ const keyText = close < 0 ? "" : s.code.slice(open + 1, close);
16779
+ const lit = close < 0 ? null : stringLiteral(keyText);
16780
+ if (lit !== null && lit !== "fetch") continue;
16781
+ const e = close < 0 ? open + 1 : close + 1;
16782
+ if (lit === "fetch" && recognised(i, e)) continue;
16783
+ const root = /^[\w$]+/.exec(h[0])?.[0] ?? "global";
16784
+ report(
16785
+ i,
16786
+ e,
16787
+ lit === "fetch" ? `\`${root}["fetch"]\`${nextIsCall(e) ? " called" : " as a value"}` : `a computed member of \`${root}\` whose key the scan cannot read (it may be "fetch")`
16788
+ );
16789
+ }
16790
+ for (const h of sh.matchAll(
16791
+ new RegExp(String.raw`Reflect\s*\.\s*get\s*\(\s*${ROOT}\s*,`, "g")
16792
+ )) {
16793
+ const i = h.index ?? 0;
16794
+ const open = sh.indexOf("(", i);
16795
+ const close = matchClose(sh, open);
16796
+ const parts = close < 0 ? [] : splitTop(sh, open + 1, close);
16797
+ const keyText = parts[1] ? s.code.slice(parts[1][0], parts[1][1]) : "";
16798
+ const lit = stringLiteral(keyText);
16799
+ judgedRoot.add(i + h[0].search(new RegExp(`${ROOT}\\s*,$`)));
16800
+ if (lit !== null && lit !== "fetch") continue;
16801
+ report(
16802
+ i,
16803
+ i + h[0].length,
16804
+ '`Reflect.get(<global>, ...)` with the key "fetch" or one the scan cannot read'
16805
+ );
16806
+ }
16807
+ for (const h of sh.matchAll(new RegExp(String.raw`\{([^{}]*)\}\s*=\s*${ROOT}(?![\w$])`, "g"))) {
16808
+ const i = h.index ?? 0;
16809
+ judgedRoot.add(i + h[0].search(new RegExp(`${ROOT}(?![\\w$])$`)));
16810
+ if (!/(?<![\w$])fetch(?![\w$])/.test(h[1])) continue;
16811
+ report(i, i + h[0].length, "a destructuring of the global object that takes `fetch`");
16812
+ }
16813
+ for (const h of sh.matchAll(/(?<![\w$.])globalThis(?![\w$])(?!\s*(?:\?\.|\.|\[))/g)) {
16814
+ const i = h.index ?? 0;
16815
+ const e = i + h[0].length;
16816
+ const prev = sh.slice(Math.max(0, i - 24), i);
16817
+ if (/\b(?:typeof|in)\s+$/.test(prev)) continue;
16818
+ if (judgedRoot.has(i)) continue;
16819
+ report(i, e, "the bare `globalThis` used as a value (the holder escapes the scan)");
16820
+ }
16821
+ }
16822
+ return out;
16823
+ }
16824
+ function outboundSitesControl() {
16825
+ const wrap = (body) => `export function w(fetchImpl: typeof fetch) {
16826
+ return (input: string, init?: RequestInit) => {
16827
+ return fetchImpl(input, ${body});
16828
+ };
16829
+ }`;
16830
+ const use = 'import { w } from "./w.js";\nexport const f = w(fetch);';
16831
+ const green = outboundSites(
16832
+ controlTree({
16833
+ "src/w.ts": wrap("{ ...init, signal: AbortSignal.timeout(1) }"),
16834
+ "src/u.ts": use
16835
+ })
16836
+ );
16837
+ const red = outboundSites(controlTree({ "src/w.ts": wrap("{ ...init }"), "src/u.ts": use }));
16838
+ const out = [];
16839
+ if (!green.sites.some((s) => s.form === "wrapper call" && s.verdict === "timeout"))
16840
+ out.push("a wrapper that applies a timeout was not read as a conforming wrapper call");
16841
+ if (!red.sites.some((s) => s.form === "wrapper call" && s.verdict === "none"))
16842
+ out.push("a wrapper that applies no timeout was not read as a non-conforming wrapper call");
16843
+ return out;
16844
+ }
16845
+
16846
+ // src/detectors/s13-progress-cancel.ts
16847
+ var LITERAL_ID = String.raw`(?:["'\`][^"'\`$]+["'\`]|\d+)`;
16848
+ var STALE_CANCEL_RE = new RegExp(String.raw`requestId\s*:\s*${LITERAL_ID}`);
16849
+ var STALE_PROGRESS_RE = new RegExp(String.raw`progressToken\s*:\s*${LITERAL_ID}`);
16850
+ var CANCEL_HANDLER_RE = /CancelledNotificationSchema|["'`]notifications\/cancelled["'`]/;
16851
+ var RESPOND_RE = /\brespond\s*\(|\bsendResponse\s*\(|\bres\.(?:json|send|end)\s*\(|\bsendResult\s*\(|\bsendError\s*\(|\btransport\.send\s*\(/;
16852
+ function s13Controls() {
16853
+ return {
16854
+ sees: !TIMEOUT_RE.test("fetch(u, { method: 'POST' })") && STALE_CANCEL_RE.test("params: { requestId: 42 }") && STALE_PROGRESS_RE.test("params: { progressToken: 'tok' }") && RESPOND_RE.test("respond(id, {})"),
16855
+ spares: TIMEOUT_RE.test("fetch(u, { signal: AbortSignal.timeout(1000) })") && !STALE_CANCEL_RE.test("params: { requestId: id }") && !RESPOND_RE.test("controllers.get(id)?.abort()")
16856
+ };
16857
+ }
15937
16858
  var s13ProgressCancel = {
15938
16859
  id: "S13 progress-cancel",
15939
16860
  rule: "S-13",
@@ -15946,10 +16867,16 @@ var s13ProgressCancel = {
15946
16867
  );
15947
16868
  }
15948
16869
  const tools = productTools(tree);
15949
- const calls = outboundCalls(tree);
16870
+ const sitesCtl = outboundSitesControl();
16871
+ if (sitesCtl.length > 0) {
16872
+ throw new Error(
16873
+ `S13 positive control FAILED: ${sitesCtl.join("; ")} \u2014 the outbound-site reader cannot tell a bounded wrapper from an unbounded one, verdict untrustworthy`
16874
+ );
16875
+ }
16876
+ const { sites, unreadable } = outboundSites(tree);
15950
16877
  const cancelSites = productSites(tree, CANCEL_HANDLER_RE);
15951
16878
  const notifySites = productHits(tree, /notifications\/(?:cancelled|progress)/);
15952
- if (tools.length === 0 && calls.length === 0 && cancelSites.length === 0 && notifySites.length === 0) {
16879
+ if (tools.length === 0 && sites.length === 0 && unreadable.length === 0 && cancelSites.length === 0 && notifySites.length === 0) {
15953
16880
  return absentResult(
15954
16881
  this.id,
15955
16882
  "-",
@@ -15957,17 +16884,12 @@ var s13ProgressCancel = {
15957
16884
  );
15958
16885
  }
15959
16886
  const reds = [];
15960
- const axiosDefault = productHits(tree, /axios\.defaults\.timeout/).length > 0;
15961
- const unclosed = calls.filter((c) => c.unclosed);
15962
- for (const c of calls) {
15963
- if (c.unclosed) continue;
15964
- if (axiosDefault && /^axios/.test(c.callee)) continue;
15965
- if (!TIMEOUT_RE.test(c.block)) {
16887
+ for (const site of sites) {
16888
+ if (site.verdict === "none")
15966
16889
  reds.push({
15967
- anchor: c.anchor,
15968
- text: `${c.anchor} (${c.callee}) is an outbound request with no timeout (no signal / timeout option): every request the server emits carries a configured timeout, whatever the progress flow`
16890
+ anchor: site.anchor,
16891
+ text: `${site.detail}: every request the server emits carries a configured timeout, whatever the progress flow`
15969
16892
  });
15970
- }
15971
16893
  }
15972
16894
  for (const file of new Set(
15973
16895
  productHits(tree, /notifications\/(?:cancelled|progress)/).map((h) => h.file)
@@ -16005,24 +16927,26 @@ var s13ProgressCancel = {
16005
16927
  });
16006
16928
  }
16007
16929
  }
16008
- if (reds.length === 0 && unclosed.length > 0) {
16009
- return couldNotJudge(
16010
- this.id,
16011
- unclosed[0].anchor,
16012
- `${unclosed.length} outbound call(s): the call never closes its parentheses and was not read (${unclosed.map((c) => c.anchor).join(", ")}): whether they carry a timeout is unknown (S-13)`
16013
- );
16014
- }
16015
16930
  if (reds.length > 0) {
16016
- return redResult(
16931
+ return settle(
16017
16932
  this.id,
16018
- reds[0].anchor,
16019
- `${reds.map((r) => r.text).join("; ")} (S-13, positive-control OK)`
16933
+ redResult(
16934
+ this.id,
16935
+ reds[0].anchor,
16936
+ `${reds.map((r) => r.text).join("; ")} (S-13, positive-control OK)`
16937
+ ),
16938
+ unreadable
16020
16939
  );
16021
16940
  }
16022
- return presentResult(
16941
+ const siteList = sites.map((x) => `${x.anchor} (${x.form})`).join(", ");
16942
+ return settle(
16023
16943
  this.id,
16024
- tools[0]?.anchor ?? calls[0]?.anchor ?? cancelSites[0]?.anchor ?? "-",
16025
- `static half: ${calls.length === 0 ? "no outbound request is emitted, so there is no outbound timeout to omit" : `${calls.length} outbound call(s), each with a timeout`}, no stale id in an emitted notification, no cancellation handler that answers; NOT read by this run: progress is monotone and stops after completion, a late notifications/cancelled returns nothing, initialize cannot be cancelled (S-13)`
16944
+ presentResult(
16945
+ this.id,
16946
+ tools[0]?.anchor ?? sites[0]?.anchor ?? cancelSites[0]?.anchor ?? "-",
16947
+ `static half: ${sites.length === 0 ? unreadable.length > 0 ? `no readable outbound site (${unreadable.length} read(s) of an outbound form were not followed, named above)` : `no outbound request is emitted (every form scanned and found zero: ${SCANNED_FORMS}), so there is no outbound timeout to omit` : `${sites.length} outbound site(s), each with a timeout: ${siteList}`}, no stale id in an emitted notification, no cancellation handler that answers; NOT read by this run: progress is monotone and stops after completion, a late notifications/cancelled returns nothing, initialize cannot be cancelled (S-13)`
16948
+ ),
16949
+ unreadable
16026
16950
  );
16027
16951
  }
16028
16952
  };
@@ -17014,6 +17938,51 @@ var s23ProtocolVersionHeader = {
17014
17938
  transport[0].anchor,
17015
17939
  `a hand-rolled HTTP route is served (${transport[0].anchor}) and the tree never reads the MCP-Protocol-Version header: an unsupported version is processed silently -> read the header on every post-initialization request and answer 400 (S-23)`
17016
17940
  );
17941
+ },
17942
+ /**
17943
+ * SERVED half (S-23): two requests after initialization, one carrying the version the server
17944
+ * negotiated (the control) and one carrying an unsupported version. Present only when the control is
17945
+ * accepted (2xx) AND the unsupported one is answered 400; an unsupported version answered 2xx is red;
17946
+ * any other pair is could-not-judge naming both statuses (a control that is refused proves nothing).
17947
+ */
17948
+ runServed(runtime) {
17949
+ const got = servedOrCouldNotJudge(this.id, "S-23", runtime);
17950
+ if ("cnj" in got) return got.cnj;
17951
+ const probe = got.served.versionProbe;
17952
+ const anchor = `${runtime.root} (served header probe)`;
17953
+ if (probe.kind === "not-run") {
17954
+ return couldNotJudge(this.id, anchor, `the header probe was not run: ${probe.reason} (S-23)`);
17955
+ }
17956
+ const ctl = `control MCP-Protocol-Version ${probe.supportedVersion} -> HTTP ${probe.supported}; MCP-Protocol-Version 1999-01-01 -> HTTP ${probe.unsupported}`;
17957
+ const accepted = probe.supported >= 200 && probe.supported < 300;
17958
+ if (!accepted) {
17959
+ return couldNotJudge(
17960
+ this.id,
17961
+ anchor,
17962
+ `${ctl}: the control request was not accepted, so a refusal of the unsupported version proves nothing (S-23)`
17963
+ );
17964
+ }
17965
+ if (probe.unsupported === 400) {
17966
+ return {
17967
+ id: this.id,
17968
+ anchor,
17969
+ state: "present",
17970
+ verdict: `${ctl}: an unsupported version is refused with 400 and the negotiated one is accepted (read on the wire) (S-23)`
17971
+ };
17972
+ }
17973
+ if (probe.unsupported >= 200 && probe.unsupported < 300) {
17974
+ return {
17975
+ id: this.id,
17976
+ anchor,
17977
+ state: "non-conforming",
17978
+ verdict: `${ctl}: an unsupported MCP-Protocol-Version is processed (2xx) instead of refused with 400 Bad Request -> read the header on every post-initialization request (S-23)`
17979
+ };
17980
+ }
17981
+ return couldNotJudge(
17982
+ this.id,
17983
+ anchor,
17984
+ `${ctl}: the unsupported version was refused with a status other than 400 (S-23 requires an explicit 400)`
17985
+ );
17017
17986
  }
17018
17987
  };
17019
17988
 
@@ -17328,8 +18297,8 @@ var s27ElicitationFloor = {
17328
18297
  };
17329
18298
 
17330
18299
  // src/detectors/s28-claim-forwarded.ts
17331
- import { existsSync as existsSync21, readFileSync as readFileSync14, readdirSync as readdirSync12, statSync as statSync19 } from "fs";
17332
- import { dirname as dirname15, join as join25, relative as relative13 } from "path";
18300
+ import { existsSync as existsSync21, readFileSync as readFileSync14, readdirSync as readdirSync13, statSync as statSync20 } from "fs";
18301
+ import { dirname as dirname15, join as join26, relative as relative13 } from "path";
17333
18302
  var PIN11 = STANDARD_PIN;
17334
18303
  var CLAIM_TOKEN = /\bverified(?:Org|Person)\b/;
17335
18304
  var ANY_CLAIM = /\bverified(?:Actor|Org|Person)\b/g;
@@ -17390,17 +18359,17 @@ function splitTop2(m, from, to) {
17390
18359
  function listTs(dir, unread, out = []) {
17391
18360
  let names;
17392
18361
  try {
17393
- names = readdirSync12(dir);
18362
+ names = readdirSync13(dir);
17394
18363
  } catch (err) {
17395
18364
  unread.push(`${dir} could not be listed (${fsErrorCode(err)})`);
17396
18365
  return out;
17397
18366
  }
17398
18367
  for (const n of names) {
17399
18368
  if (n === "node_modules" || n === "_generated" || n === "__tests__") continue;
17400
- const p = join25(dir, n);
18369
+ const p = join26(dir, n);
17401
18370
  let st;
17402
18371
  try {
17403
- st = statSync19(p);
18372
+ st = statSync20(p);
17404
18373
  } catch (err) {
17405
18374
  unread.push(`${p} could not be read (${fsErrorCode(err)})`);
17406
18375
  continue;
@@ -17416,13 +18385,13 @@ function listTs(dir, unread, out = []) {
17416
18385
  function discoverBackend(root) {
17417
18386
  let dir = root;
17418
18387
  try {
17419
- if (!statSync19(root).isDirectory()) dir = dirname15(root);
18388
+ if (!statSync20(root).isDirectory()) dir = dirname15(root);
17420
18389
  } catch {
17421
18390
  return void 0;
17422
18391
  }
17423
18392
  for (let up = 0; up < 5; up++) {
17424
- const cand = join25(dir, "convex");
17425
- if (existsSync21(join25(cand, "schema.ts"))) return cand;
18393
+ const cand = join26(dir, "convex");
18394
+ if (existsSync21(join26(cand, "schema.ts"))) return cand;
17426
18395
  const parent = dirname15(dir);
17427
18396
  if (parent === dir) break;
17428
18397
  dir = parent;
@@ -17601,14 +18570,14 @@ function scanS28(tree) {
17601
18570
  );
17602
18571
  continue;
17603
18572
  }
17604
- const argText = parts[1] ? m.slice(parts[1][0], parts[1][1]) : "";
18573
+ const argText2 = parts[1] ? m.slice(parts[1][0], parts[1][1]) : "";
17605
18574
  const region = m.slice(tool.start, hit.index);
17606
18575
  const regionRaw = text.slice(tool.start, hit.index);
17607
18576
  const guard = GUARD_RE.test(region) || GUARD_RE.test(regionRaw);
17608
- let direct = CLAIM_TOKEN.test(argText);
18577
+ let direct = CLAIM_TOKEN.test(argText2);
17609
18578
  let viaHelper;
17610
- let virtual = argText;
17611
- const bare = /^\s*([A-Za-z_$][\w$]*)\s*$/.exec(argText);
18579
+ let virtual = argText2;
18580
+ const bare = /^\s*([A-Za-z_$][\w$]*)\s*$/.exec(argText2);
17612
18581
  if (bare && !direct) {
17613
18582
  const v = bare[1].replace(/\$/g, "\\$");
17614
18583
  const pieces = [];
@@ -18305,8 +19274,8 @@ function scanS35(tree) {
18305
19274
  });
18306
19275
  continue;
18307
19276
  }
18308
- const argText = parts.slice(1).map(([a, b]) => m.slice(a, b)).join(",");
18309
- const carried = CARRY_WORD.test(argText);
19277
+ const argText2 = parts.slice(1).map(([a, b]) => m.slice(a, b)).join(",");
19278
+ const carried = CARRY_WORD.test(argText2);
18310
19279
  const names = boundNames(m, start);
18311
19280
  const end = blockEnd(m, start);
18312
19281
  const inline = inlineNarrowing(m, start, close, end);
@@ -18328,7 +19297,7 @@ function scanS35(tree) {
18328
19297
  });
18329
19298
  continue;
18330
19299
  }
18331
- const spread = /\.\.\.\s*[A-Za-z_$]/.test(argText);
19300
+ const spread = /\.\.\.\s*[A-Za-z_$]/.test(argText2);
18332
19301
  const n = narrowings[0];
18333
19302
  const at = `${file.rel}:${lineAt3(m, n.offset)}`;
18334
19303
  if (spread) {
@@ -20705,17 +21674,17 @@ var detectors = registered.map(
20705
21674
 
20706
21675
  // src/runtime/launch.ts
20707
21676
  import { spawnSync as spawnSync2 } from "child_process";
20708
- import { existsSync as existsSync22, readFileSync as readFileSync15, statSync as statSync20 } from "fs";
20709
- import { dirname as dirname16, isAbsolute, join as join26, resolve as resolve2 } from "path";
21677
+ import { existsSync as existsSync22, readFileSync as readFileSync15, statSync as statSync21 } from "fs";
21678
+ import { dirname as dirname16, isAbsolute, join as join27, resolve as resolve2 } from "path";
20710
21679
  function findPackageDir(target) {
20711
21680
  let dir;
20712
21681
  try {
20713
- dir = statSync20(target).isDirectory() ? target : dirname16(target);
21682
+ dir = statSync21(target).isDirectory() ? target : dirname16(target);
20714
21683
  } catch {
20715
21684
  return null;
20716
21685
  }
20717
21686
  for (let depth = 0; depth < 8; depth++) {
20718
- if (existsSync22(join26(dir, "package.json"))) return dir;
21687
+ if (existsSync22(join27(dir, "package.json"))) return dir;
20719
21688
  const parent = dirname16(dir);
20720
21689
  if (parent === dir) break;
20721
21690
  dir = parent;
@@ -20740,13 +21709,13 @@ function deriveLaunchPlan(target) {
20740
21709
  }
20741
21710
  let pkg;
20742
21711
  try {
20743
- if (!statSync20(join26(pkgDir, "package.json")).isFile()) {
20744
- return { error: `${join26(pkgDir, "package.json")} is not a regular file \u2014 not read` };
21712
+ if (!statSync21(join27(pkgDir, "package.json")).isFile()) {
21713
+ return { error: `${join27(pkgDir, "package.json")} is not a regular file \u2014 not read` };
20745
21714
  }
20746
- pkg = JSON.parse(readFileSync15(join26(pkgDir, "package.json"), "utf8"));
21715
+ pkg = JSON.parse(readFileSync15(join27(pkgDir, "package.json"), "utf8"));
20747
21716
  } catch (err) {
20748
21717
  return {
20749
- error: `could not parse ${join26(pkgDir, "package.json")}: ${err instanceof Error ? err.message : String(err)}`
21718
+ error: `could not parse ${join27(pkgDir, "package.json")}: ${err instanceof Error ? err.message : String(err)}`
20750
21719
  };
20751
21720
  }
20752
21721
  const bin = firstBinEntry(pkg.bin);
@@ -20779,117 +21748,402 @@ import { spawn } from "node:child_process";
20779
21748
  const plan = JSON.parse(process.env.MCP_DOCTOR_PLAN);
20780
21749
  const INVALID_CURSOR = "mcp-doctor:invalid-cursor:%%%";
20781
21750
  const done = (o) => { process.stdout.write(JSON.stringify(o)); process.exit(0); };
20782
- let child;
20783
- try {
20784
- child = spawn(plan.command, plan.args, { cwd: plan.cwd, stdio: ["pipe", "pipe", "pipe"] });
20785
- } catch (e) {
20786
- done({ launchError: "spawn failed: " + (e && e.message ? e.message : String(e)) });
20787
- }
20788
21751
  let settled = false;
20789
21752
  let serverInfo;
20790
21753
  let capabilities = {};
21754
+ let negotiated;
20791
21755
  let tools;
20792
21756
  const probes = [];
20793
21757
  const pending = new Map();
21758
+ // The served list responses (S-3 / S-12): one record per protocol list method, read from the wire.
21759
+ const lists = [];
21760
+ // The one served tool-call response (S-2): a tool declared read-only that needs no argument.
21761
+ const calls = [];
21762
+ const listPending = new Map();
20794
21763
  let nextId = 10;
20795
21764
  let probeTimer;
20796
- const fail = (msg) => { if (settled) return; settled = true; try { child.kill(); } catch {} done({ launchError: msg }); };
21765
+ let transport;
21766
+ const fail = (msg) => { if (settled) return; settled = true; Promise.resolve(transport && transport.close()).finally(() => done({ launchError: msg })); };
21767
+ const outstanding = () => pending.size + listPending.size;
20797
21768
  const finish = (why) => {
20798
21769
  if (settled) return; settled = true; clearTimeout(to); clearTimeout(probeTimer);
20799
21770
  for (const idx of pending.values()) probes[idx].outcome = { kind: "no-answer", reason: why };
20800
- try { child.kill(); } catch {}
20801
- done({ tools, serverInfo, cursorProbes: probes });
21771
+ for (const rec of listPending.values()) {
21772
+ if (rec.followUpOf) rec.followUpOf.followUp = { outcome: "no-answer", detail: why };
21773
+ else { rec.outcome = "no-answer"; rec.detail = why; }
21774
+ }
21775
+ const served = { capabilities, protocolVersion: negotiated, lists, calls, versionProbe: { kind: "not-run", reason: "not run" }, authServer: { kind: "not-run", reason: "not run" } };
21776
+ Promise.resolve(extras(served))
21777
+ .catch((e) => { served.versionProbe = { kind: "not-run", reason: "the probe threw: " + (e && e.message ? e.message : String(e)) }; })
21778
+ .then(() => transport && transport.close())
21779
+ .finally(() => done({ tools, serverInfo, cursorProbes: probes, served }));
20802
21780
  };
20803
21781
  const to = setTimeout(() => {
20804
21782
  if (tools) finish("no answer before the introspection deadline");
20805
21783
  else fail("timeout: server did not answer initialize+tools/list within the deadline");
20806
21784
  }, 12000);
20807
- child.on("error", (e) => fail("spawn error: " + (e && e.message ? e.message : String(e))));
20808
- child.on("exit", (code) => {
20809
- if (tools) finish("the server exited (code " + code + ") before answering");
20810
- else fail("server exited (code " + code + ") before completing the MCP handshake");
20811
- });
20812
- const send = (o) => { try { child.stdin.write(JSON.stringify(o) + "\n"); } catch (e) { fail("write failed: " + e.message); } };
21785
+ // A transport failure with a NAMED cause: before tools/list answered it is a launch failure; after,
21786
+ // the pending probes are recorded as no-answer naming it. Never a silent pass.
21787
+ const onFailure = (cause) => { if (tools) finish(cause); else fail(cause); };
21788
+ // The transport is the ONLY thing that differs between a local launch and a remote URL. It delivers
21789
+ // every JSON-RPC message the server sends to onMessage; the probe sequence below is ONE code path.
21790
+ // stdio: newline-delimited JSON-RPC on the child's stdin/stdout. http: streamable HTTP (a POST per
21791
+ // message; the answer is a JSON body or an SSE stream), failures named through onFailure.
21792
+ const makeStdioTransport = () => {
21793
+ let child;
21794
+ try {
21795
+ child = spawn(plan.command, plan.args, { cwd: plan.cwd, stdio: ["pipe", "pipe", "pipe"] });
21796
+ } catch (e) {
21797
+ done({ launchError: "spawn failed: " + (e && e.message ? e.message : String(e)) });
21798
+ }
21799
+ child.on("error", (e) => fail("spawn error: " + (e && e.message ? e.message : String(e))));
21800
+ child.on("exit", (code) => {
21801
+ if (tools) finish("the server exited (code " + code + ") before answering");
21802
+ else fail("server exited (code " + code + ") before completing the MCP handshake");
21803
+ });
21804
+ const send = (o) => { try { child.stdin.write(JSON.stringify(o) + "\n"); } catch (e) { fail("write failed: " + e.message); } };
21805
+ let buf = "";
21806
+ child.stdout.on("data", (d) => {
21807
+ buf += d.toString();
21808
+ let i;
21809
+ while ((i = buf.indexOf("\n")) >= 0) {
21810
+ const line = buf.slice(0, i); buf = buf.slice(i + 1);
21811
+ if (!line.trim()) continue;
21812
+ // (a) Not a filesystem read: an in-memory parse of one stdout line. A non-JSON line is legitimately not a JSON-RPC answer (a server may log to stdout); the answers it never gave surface as no-answer outcomes / the 5 s probe deadline, never as a silent pass.
21813
+ let msg; try { msg = JSON.parse(line); } catch { continue; }
21814
+ onMessage(msg);
21815
+ }
21816
+ });
21817
+ return { send, close: () => { try { child.kill(); } catch {} } };
21818
+ };
21819
+ const makeHttpTransport = () => {
21820
+ let sessionId;
21821
+ let protocolVersion;
21822
+ const ctl = new AbortController();
21823
+ const TLS = /CERT|TLS|SSL|EPROTO|SELF_SIGNED|UNABLE_TO_VERIFY|HOSTNAME_MISMATCH/i;
21824
+ const classify = (e) => {
21825
+ const c = e && e.cause ? e.cause : e;
21826
+ const code = c && c.code ? String(c.code) : "";
21827
+ const msg = c && c.message ? String(c.message) : String(e);
21828
+ if (TLS.test(code) || TLS.test(msg)) return "TLS error (" + (code || msg) + ")";
21829
+ return "unreachable: " + (code ? code + " " : "") + msg;
21830
+ };
21831
+ const nonMcp = (what) => onFailure("non-MCP response: " + what);
21832
+ // A JSON-RPC message is an object carrying jsonrpc "2.0"; anything else is not an MCP answer.
21833
+ const isRpc = (m) => Boolean(m) && typeof m === "object" && !Array.isArray(m) && m.jsonrpc === "2.0";
21834
+ const deliver = (m) => {
21835
+ if (m.id === 1 && m.result && typeof m.result.protocolVersion === "string") protocolVersion = m.result.protocolVersion;
21836
+ onMessage(m);
21837
+ };
21838
+ const readSse = async (res, wantId) => {
21839
+ const reader = res.body.getReader();
21840
+ const dec = new TextDecoder();
21841
+ let buf = "";
21842
+ let answered = false;
21843
+ for (;;) {
21844
+ const { value, done: end } = await reader.read();
21845
+ if (value) buf += dec.decode(value, { stream: true });
21846
+ if (end) buf += "\n\n";
21847
+ let i;
21848
+ while ((i = buf.search(/\r?\n\r?\n/)) >= 0) {
21849
+ const ev = buf.slice(0, i); buf = buf.slice(i).replace(/^\r?\n\r?\n/, "");
21850
+ const data = ev.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
21851
+ if (!data) continue;
21852
+ let m; try { m = JSON.parse(data); } catch { nonMcp("an SSE event whose data is not JSON"); try { await reader.cancel(); } catch {} return; }
21853
+ if (!isRpc(m)) { nonMcp("an SSE event that is not a JSON-RPC message"); try { await reader.cancel(); } catch {} return; }
21854
+ deliver(m);
21855
+ if (m.id === wantId) answered = true;
21856
+ }
21857
+ if (answered) { try { await reader.cancel(); } catch {} return; }
21858
+ if (end) break;
21859
+ }
21860
+ onFailure("the SSE stream ended without answering request " + wantId);
21861
+ };
21862
+ const send = (o) => {
21863
+ const headers = Object.assign({}, plan.headers, { "content-type": "application/json", accept: "application/json, text/event-stream" });
21864
+ if (sessionId) headers["mcp-session-id"] = sessionId;
21865
+ if (protocolVersion) headers["mcp-protocol-version"] = protocolVersion;
21866
+ (async () => {
21867
+ let res;
21868
+ try {
21869
+ res = await fetch(plan.url, { method: "POST", headers, body: JSON.stringify(o), signal: ctl.signal, redirect: "manual" });
21870
+ } catch (e) { onFailure(classify(e)); return; }
21871
+ try {
21872
+ const st = res.status;
21873
+ const sid = res.headers.get("mcp-session-id");
21874
+ if (sid && !sessionId) sessionId = sid;
21875
+ if (st === 401 || st === 403) { onFailure("authentication refused: HTTP " + st + " (the server did not accept the credential supplied)"); return; }
21876
+ if (st >= 300 && st < 400) { onFailure("redirect not followed: HTTP " + st + " (a credential is never sent to a redirect target)"); return; }
21877
+ const ct = (res.headers.get("content-type") || "").toLowerCase();
21878
+ if (o.id === undefined) {
21879
+ if (st >= 200 && st < 300) { try { await res.body.cancel(); } catch {} return; }
21880
+ onFailure("HTTP " + st + " answering " + o.method); return;
21881
+ }
21882
+ if (ct.includes("text/event-stream") && st >= 200 && st < 300) { await readSse(res, o.id); return; }
21883
+ const text = await res.text();
21884
+ let list = [];
21885
+ if (ct.includes("json")) {
21886
+ try { const p = JSON.parse(text); list = Array.isArray(p) ? p : [p]; } catch { list = []; }
21887
+ }
21888
+ if (list.length > 0 && list.every(isRpc)) { for (const m of list) deliver(m); return; }
21889
+ if (st < 200 || st >= 300) { onFailure("HTTP " + st + " answering " + o.method); return; }
21890
+ nonMcp(ct ? "content-type " + ct.split(";")[0] + " that is not a JSON-RPC answer" : "no content-type and no JSON-RPC answer");
21891
+ } catch (e) { onFailure(classify(e)); }
21892
+ })();
21893
+ };
21894
+ const close = async () => {
21895
+ ctl.abort();
21896
+ if (!sessionId) return;
21897
+ try {
21898
+ const headers = Object.assign({}, plan.headers, { "mcp-session-id": sessionId });
21899
+ if (protocolVersion) headers["mcp-protocol-version"] = protocolVersion;
21900
+ await fetch(plan.url, { method: "DELETE", headers, redirect: "manual", signal: AbortSignal.timeout(1500) });
21901
+ } catch {}
21902
+ };
21903
+ // A request carrying a given MCP-Protocol-Version header, answered with its HTTP status (S-23).
21904
+ const statusFor = async (version) => {
21905
+ const headers = Object.assign({}, plan.headers, { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": version });
21906
+ if (sessionId) headers["mcp-session-id"] = sessionId;
21907
+ const res = await fetch(plan.url, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", id: 900, method: "tools/list", params: {} }), redirect: "manual", signal: AbortSignal.timeout(4000) });
21908
+ try { await res.body.cancel(); } catch {}
21909
+ return res.status;
21910
+ };
21911
+ return { send, close, statusFor, negotiatedVersion: () => protocolVersion };
21912
+ };
21913
+ const send = (o) => transport.send(o);
20813
21914
  const probe = (target, surface, method, params) => {
20814
21915
  const id = nextId++;
20815
21916
  pending.set(id, probes.length);
20816
21917
  probes.push({ target, surface });
20817
21918
  send({ jsonrpc: "2.0", id, method, params });
20818
21919
  };
20819
- let buf = "";
20820
- child.stdout.on("data", (d) => {
20821
- buf += d.toString();
20822
- let i;
20823
- while ((i = buf.indexOf("\n")) >= 0) {
20824
- const line = buf.slice(0, i); buf = buf.slice(i + 1);
20825
- if (!line.trim()) continue;
20826
- // (a) Not a filesystem read: an in-memory parse of one stdout line. A non-JSON line is legitimately not a JSON-RPC answer (a server may log to stdout); the answers it never gave surface as no-answer outcomes / the 5 s probe deadline, never as a silent pass.
20827
- let msg; try { msg = JSON.parse(line); } catch { continue; }
20828
- // A request or notification FROM the server carries a method: it is not an answer.
20829
- if (msg.method !== undefined) continue;
20830
- if (msg.id === 1) {
20831
- // The initialize response's serverInfo is the SAME non-authenticated
20832
- // discovery surface a client reads version from (S-7); captured here
20833
- // so C-25's dynamic half can read a served build-identity field
20834
- // alongside it, additively -- every existing consumer of the
20835
- // tools-only introspector output is unaffected.
20836
- serverInfo = msg.result && msg.result.serverInfo;
20837
- capabilities = (msg.result && msg.result.capabilities) || {};
20838
- send({ jsonrpc: "2.0", method: "notifications/initialized" });
20839
- send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} });
20840
- } else if (msg.id === 2) {
20841
- if (settled) return;
20842
- const served = msg.result && Array.isArray(msg.result.tools) ? msg.result.tools : [];
20843
- const schemaOf = (t) => (t && t.inputSchema && typeof t.inputSchema === "object" ? t.inputSchema : {});
20844
- const takesCursor = (t) => {
20845
- const props = schemaOf(t).properties;
20846
- return Boolean(props && typeof props === "object" && Object.prototype.hasOwnProperty.call(props, "cursor"));
20847
- };
20848
- tools = served.map((t) => ({ name: String(t && t.name), description: t && typeof t.description === "string" ? t.description : undefined, cursorArgument: takesCursor(t) }));
20849
- const lists = ["tools/list"];
20850
- if (capabilities.resources) lists.push("resources/list", "resources/templates/list");
20851
- if (capabilities.prompts) lists.push("prompts/list");
20852
- for (const m of lists) probe(m, "list-method", m, { cursor: INVALID_CURSOR });
20853
- for (const t of served) {
20854
- if (!takesCursor(t)) continue;
20855
- const name = String(t && t.name);
20856
- const required = Array.isArray(schemaOf(t).required) ? schemaOf(t).required.filter((r) => r !== "cursor") : [];
20857
- if (required.length > 0) {
20858
- probes.push({ target: name, surface: "tool-argument", outcome: { kind: "not-sent", reason: "the tool requires " + required.join(", ") + " beside the cursor; the probe never invents a value for them" } });
20859
- continue;
20860
- }
20861
- probe(name, "tool-argument", "tools/call", { name, arguments: { cursor: INVALID_CURSOR } });
20862
- }
20863
- if (pending.size === 0) { finish("no probe pending"); return; }
20864
- probeTimer = setTimeout(() => finish("no answer within the 5 s probe deadline"), 5000);
20865
- } else if (pending.has(msg.id)) {
20866
- const idx = pending.get(msg.id); pending.delete(msg.id);
20867
- if (msg.error && typeof msg.error === "object") {
20868
- probes[idx].outcome = { kind: "error", code: msg.error.code, message: typeof msg.error.message === "string" ? msg.error.message : undefined };
20869
- } else if (msg.result && typeof msg.result === "object") {
20870
- const sc = msg.result.structuredContent;
20871
- const err = sc && typeof sc === "object" ? sc.error : undefined;
20872
- probes[idx].outcome = { kind: "result", isError: msg.result.isError === true, errorCode: err && typeof err === "object" ? err.code : undefined };
20873
- } else {
20874
- probes[idx].outcome = { kind: "no-answer", reason: "an answer with neither result nor error" };
21920
+
21921
+ // A public metadata GET: NO credential is ever attached to it (the headers of the plan stay out).
21922
+ const getPublicJson = async (url) => {
21923
+ let res;
21924
+ try { res = await fetch(url, { method: "GET", headers: { accept: "application/json" }, redirect: "manual", signal: AbortSignal.timeout(4000) }); }
21925
+ catch (e) { return { ok: false, reason: "unreachable: " + (e && e.message ? e.message : String(e)) }; }
21926
+ if (res.status !== 200) { try { await res.body.cancel(); } catch {} return { ok: false, status: res.status, reason: "HTTP " + res.status }; }
21927
+ let doc; try { doc = JSON.parse(await res.text()); } catch { return { ok: false, status: res.status, reason: "the body is not JSON" }; }
21928
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) return { ok: false, status: res.status, reason: "the body is not a JSON object" };
21929
+ return { ok: true, status: res.status, doc };
21930
+ };
21931
+ // The authorization server the PRM names (RFC 9728), then its metadata (RFC 8414). The doctor fetches
21932
+ // ONLY a URL on the endpoint's own origin (so the scheme the caller already vetted): a server that names another origin never makes the
21933
+ // doctor request it (no SSRF from the audit tool); that case is reported as unavailable, naming it.
21934
+ const readAuthServer = async () => {
21935
+ const ep = new URL(plan.url);
21936
+ const prmUrls = [ep.origin + "/.well-known/oauth-protected-resource" + (ep.pathname === "/" ? "" : ep.pathname), ep.origin + "/.well-known/oauth-protected-resource"];
21937
+ let issuer;
21938
+ for (const u of prmUrls) {
21939
+ const r = await getPublicJson(u);
21940
+ const names = r.ok && Array.isArray(r.doc.authorization_servers) ? r.doc.authorization_servers.filter((x) => typeof x === "string") : [];
21941
+ if (names.length > 0) { issuer = names[0]; break; }
21942
+ }
21943
+ if (!issuer) return { kind: "unavailable", url: prmUrls[0], reason: "the protected-resource metadata names no authorization server (read at the suffixed and the bare path)" };
21944
+ let iu; try { iu = new URL(issuer); } catch { return { kind: "unavailable", url: prmUrls[0], reason: "the protected-resource metadata names an authorization server that is not a URL" }; }
21945
+ if (iu.origin !== ep.origin) return { kind: "unavailable", url: iu.origin, reason: "the authorization server is on another origin (" + iu.host + "): not fetched from here, only a same-origin authorization server is read" };
21946
+ const url = iu.origin + "/.well-known/oauth-authorization-server" + (iu.pathname === "/" ? "" : iu.pathname);
21947
+ const r = await getPublicJson(url);
21948
+ if (!r.ok) return { kind: "unavailable", url, reason: r.reason };
21949
+ return { kind: "document", url, status: r.status, document: r.doc };
21950
+ };
21951
+ const extras = async (served) => {
21952
+ if (plan.kind !== "http") {
21953
+ served.versionProbe = { kind: "not-run", reason: "stdio transport: the MCP-Protocol-Version header exists on HTTP only" };
21954
+ served.authServer = { kind: "not-run", reason: "stdio transport: no authorization-server metadata is served" };
21955
+ return;
21956
+ }
21957
+ const [vp, as] = await Promise.all([
21958
+ (async () => {
21959
+ const v = transport.negotiatedVersion();
21960
+ if (!v) return { kind: "not-run", reason: "no protocol version was negotiated, so no supported-version control request can be sent" };
21961
+ try {
21962
+ const supported = await transport.statusFor(v);
21963
+ const unsupported = await transport.statusFor("1999-01-01");
21964
+ return { kind: "statuses", supportedVersion: v, supported, unsupported };
21965
+ } catch (e) { return { kind: "not-run", reason: "the header probe failed: " + (e && e.message ? e.message : String(e)) }; }
21966
+ })(),
21967
+ readAuthServer().catch((e) => ({ kind: "unavailable", url: plan.url, reason: "the read failed: " + (e && e.message ? e.message : String(e)) })),
21968
+ ]);
21969
+ served.versionProbe = vp;
21970
+ served.authServer = as;
21971
+ };
21972
+ // One served list answer, read from the wire into a record: its keys, the S-2/S-3 fields, nextCursor.
21973
+ const listRecord = (method, msg) => {
21974
+ if (msg.error && typeof msg.error === "object") return { method, outcome: "refused", detail: "JSON-RPC error " + msg.error.code + (typeof msg.error.message === "string" ? " " + msg.error.message : "") };
21975
+ const r = msg.result;
21976
+ if (!r || typeof r !== "object" || Array.isArray(r)) return { method, outcome: "no-answer", detail: "an answer with no result object" };
21977
+ const arrays = Object.keys(r).filter((k) => Array.isArray(r[k]));
21978
+ return { method, outcome: "answered", resultKeys: Object.keys(r), resultType: r.resultType, ttlMs: r.ttlMs, cacheScope: r.cacheScope, nextCursor: r.nextCursor, entries: arrays.length === 1 ? r[arrays[0]].length : undefined };
21979
+ };
21980
+ // A cursor the server served is presented back UNTOUCHED (opaque, S-12): the next page must answer.
21981
+ const followCursor = (rec) => {
21982
+ const fid = nextId++;
21983
+ listPending.set(fid, { method: rec.method, followUpOf: rec });
21984
+ send({ jsonrpc: "2.0", id: fid, method: rec.method, params: { cursor: rec.nextCursor } });
21985
+ };
21986
+ const onMessage = (msg) => {
21987
+ // A request or notification FROM the server carries a method: it is not an answer.
21988
+ if (msg.method !== undefined) return;
21989
+ // An initialize or tools/list that the server ANSWERED WITH AN ERROR is a refusal, named: it is never read
21990
+ // as an empty tool list (which would judge "no tools" over a server that refused to say).
21991
+ if ((msg.id === 1 || msg.id === 2) && msg.error && typeof msg.error === "object") {
21992
+ fail((msg.id === 1 ? "initialize" : "tools/list") + " refused by the server: JSON-RPC error " + msg.error.code + (typeof msg.error.message === "string" ? " " + msg.error.message : ""));
21993
+ return;
21994
+ }
21995
+ if (msg.id === 1) {
21996
+ // The initialize response's serverInfo is the SAME non-authenticated
21997
+ // discovery surface a client reads version from (S-7); captured here
21998
+ // so C-25's dynamic half can read a served build-identity field
21999
+ // alongside it, additively -- every existing consumer of the
22000
+ // tools-only introspector output is unaffected.
22001
+ serverInfo = msg.result && msg.result.serverInfo;
22002
+ capabilities = (msg.result && msg.result.capabilities) || {};
22003
+ negotiated = msg.result && typeof msg.result.protocolVersion === "string" ? msg.result.protocolVersion : undefined;
22004
+ send({ jsonrpc: "2.0", method: "notifications/initialized" });
22005
+ send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} });
22006
+ } else if (msg.id === 2) {
22007
+ if (settled) return;
22008
+ const served = msg.result && Array.isArray(msg.result.tools) ? msg.result.tools : [];
22009
+ const schemaOf = (t) => (t && t.inputSchema && typeof t.inputSchema === "object" ? t.inputSchema : {});
22010
+ const takesCursor = (t) => {
22011
+ const props = schemaOf(t).properties;
22012
+ return Boolean(props && typeof props === "object" && Object.prototype.hasOwnProperty.call(props, "cursor"));
22013
+ };
22014
+ tools = served.map((t) => ({ name: String(t && t.name), description: t && typeof t.description === "string" ? t.description : undefined, cursorArgument: takesCursor(t) }));
22015
+ const methods = ["tools/list"];
22016
+ if (capabilities.resources) methods.push("resources/list", "resources/templates/list");
22017
+ if (capabilities.prompts) methods.push("prompts/list");
22018
+ const first = listRecord("tools/list", msg);
22019
+ lists.push(first);
22020
+ if (first.outcome === "answered" && typeof first.nextCursor === "string" && first.nextCursor) followCursor(first);
22021
+ // The other declared list methods, asked for their first page: S-3 / S-12 read what they serve.
22022
+ for (const m of methods.slice(1)) {
22023
+ const lid = nextId++;
22024
+ const rec = { method: m };
22025
+ lists.push(rec);
22026
+ listPending.set(lid, rec);
22027
+ send({ jsonrpc: "2.0", id: lid, method: m, params: {} });
22028
+ }
22029
+ // S-2 is verified "on the response returned" to a tool call: ONE tool the server itself declares
22030
+ // read-only (annotations.readOnlyHint === true) that requires no argument is called with {}; only
22031
+ // the KEYS of its result are recorded, never its content. No such tool: no call is invented.
22032
+ const safe = served.find((t) => t && t.annotations && t.annotations.readOnlyHint === true && (!Array.isArray(schemaOf(t).required) || schemaOf(t).required.length === 0));
22033
+ if (safe) {
22034
+ const cid = nextId++;
22035
+ const rec = { method: "tools/call " + String(safe.name) };
22036
+ calls.push(rec);
22037
+ listPending.set(cid, rec);
22038
+ send({ jsonrpc: "2.0", id: cid, method: "tools/call", params: { name: safe.name, arguments: {} } });
22039
+ }
22040
+ for (const m of methods) probe(m, "list-method", m, { cursor: INVALID_CURSOR });
22041
+ for (const t of served) {
22042
+ if (!takesCursor(t)) continue;
22043
+ const name = String(t && t.name);
22044
+ const required = Array.isArray(schemaOf(t).required) ? schemaOf(t).required.filter((r) => r !== "cursor") : [];
22045
+ if (required.length > 0) {
22046
+ probes.push({ target: name, surface: "tool-argument", outcome: { kind: "not-sent", reason: "the tool requires " + required.join(", ") + " beside the cursor; the probe never invents a value for them" } });
22047
+ continue;
20875
22048
  }
20876
- if (pending.size === 0) finish("no probe pending");
22049
+ probe(name, "tool-argument", "tools/call", { name, arguments: { cursor: INVALID_CURSOR } });
20877
22050
  }
22051
+ if (outstanding() === 0) { finish("no probe pending"); return; }
22052
+ probeTimer = setTimeout(() => finish("no answer within the 5 s probe deadline"), 5000);
22053
+ } else if (listPending.has(msg.id)) {
22054
+ const rec = listPending.get(msg.id); listPending.delete(msg.id);
22055
+ if (rec.followUpOf) {
22056
+ const got = listRecord(rec.method, msg);
22057
+ rec.followUpOf.followUp = { outcome: got.outcome, detail: got.detail, entries: got.entries };
22058
+ } else {
22059
+ Object.assign(rec, listRecord(rec.method, msg));
22060
+ if (rec.outcome === "answered" && typeof rec.nextCursor === "string" && rec.nextCursor) followCursor(rec);
22061
+ }
22062
+ if (outstanding() === 0) finish("no probe pending");
22063
+ } else if (pending.has(msg.id)) {
22064
+ const idx = pending.get(msg.id); pending.delete(msg.id);
22065
+ if (msg.error && typeof msg.error === "object") {
22066
+ probes[idx].outcome = { kind: "error", code: msg.error.code, message: typeof msg.error.message === "string" ? msg.error.message : undefined };
22067
+ } else if (msg.result && typeof msg.result === "object") {
22068
+ const sc = msg.result.structuredContent;
22069
+ const err = sc && typeof sc === "object" ? sc.error : undefined;
22070
+ probes[idx].outcome = { kind: "result", isError: msg.result.isError === true, errorCode: err && typeof err === "object" ? err.code : undefined };
22071
+ } else {
22072
+ probes[idx].outcome = { kind: "no-answer", reason: "an answer with neither result nor error" };
22073
+ }
22074
+ if (outstanding() === 0) finish("no probe pending");
20878
22075
  }
20879
- });
22076
+ };
22077
+ transport = plan.kind === "http" ? makeHttpTransport() : makeStdioTransport();
20880
22078
  send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "mcp-doctor", version: "0" } } });
20881
22079
  `;
22080
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
22081
+ var outcomeOf = (v) => v === "answered" || v === "refused" ? v : "no-answer";
22082
+ function readServed(raw) {
22083
+ if (!isObj(raw)) return void 0;
22084
+ const readList = (l) => {
22085
+ const r = isObj(l) ? l : {};
22086
+ const method = typeof r.method === "string" ? r.method : "<unnamed list>";
22087
+ const fu = isObj(r.followUp) ? r.followUp : void 0;
22088
+ return {
22089
+ method,
22090
+ outcome: isObj(l) ? outcomeOf(r.outcome) : "no-answer",
22091
+ ...typeof r.detail === "string" ? { detail: r.detail } : {},
22092
+ ...Array.isArray(r.resultKeys) ? { resultKeys: r.resultKeys.map(String) } : {},
22093
+ ...r.resultType !== void 0 ? { resultType: r.resultType } : {},
22094
+ ...r.ttlMs !== void 0 ? { ttlMs: r.ttlMs } : {},
22095
+ ...r.cacheScope !== void 0 ? { cacheScope: r.cacheScope } : {},
22096
+ ...r.nextCursor !== void 0 ? { nextCursor: r.nextCursor } : {},
22097
+ ...typeof r.entries === "number" ? { entries: r.entries } : {},
22098
+ ...fu ? {
22099
+ followUp: {
22100
+ outcome: outcomeOf(fu.outcome),
22101
+ ...typeof fu.detail === "string" ? { detail: fu.detail } : {},
22102
+ ...typeof fu.entries === "number" ? { entries: fu.entries } : {}
22103
+ }
22104
+ } : {}
22105
+ };
22106
+ };
22107
+ const lists = (Array.isArray(raw.lists) ? raw.lists : []).map(readList);
22108
+ const vp = raw.versionProbe;
22109
+ const versionProbe = isObj(vp) && vp.kind === "statuses" && typeof vp.supportedVersion === "string" && typeof vp.supported === "number" && typeof vp.unsupported === "number" ? {
22110
+ kind: "statuses",
22111
+ supportedVersion: vp.supportedVersion,
22112
+ supported: vp.supported,
22113
+ unsupported: vp.unsupported
22114
+ } : {
22115
+ kind: "not-run",
22116
+ reason: isObj(vp) && vp.kind === "not-run" && typeof vp.reason === "string" ? vp.reason : "unreadable version-probe record"
22117
+ };
22118
+ const as = raw.authServer;
22119
+ const authServer = isObj(as) && as.kind === "document" && typeof as.url === "string" && typeof as.status === "number" && isObj(as.document) ? { kind: "document", url: as.url, status: as.status, document: as.document } : isObj(as) && as.kind === "unavailable" && typeof as.url === "string" ? {
22120
+ kind: "unavailable",
22121
+ url: as.url,
22122
+ reason: typeof as.reason === "string" ? as.reason : "no reason given"
22123
+ } : {
22124
+ kind: "not-run",
22125
+ reason: isObj(as) && as.kind === "not-run" && typeof as.reason === "string" ? as.reason : "unreadable authorization-server record"
22126
+ };
22127
+ return {
22128
+ capabilities: isObj(raw.capabilities) ? raw.capabilities : {},
22129
+ ...typeof raw.protocolVersion === "string" ? { protocolVersion: raw.protocolVersion } : {},
22130
+ lists,
22131
+ calls: (Array.isArray(raw.calls) ? raw.calls : []).map(readList),
22132
+ versionProbe,
22133
+ authServer
22134
+ };
22135
+ }
20882
22136
  function readEvalCounts(target) {
20883
22137
  const counts = /* @__PURE__ */ new Map();
20884
22138
  const pkgDir = findPackageDir(target) ?? (statSyncSafe(target) ? target : null);
20885
22139
  if (!pkgDir) return { counts };
20886
22140
  let dir = pkgDir;
20887
22141
  for (let depth = 0; depth < 8; depth++) {
20888
- const candidate = join26(dir, "evals", "evals.json");
22142
+ const candidate = join27(dir, "evals", "evals.json");
20889
22143
  if (existsSync22(candidate)) {
20890
22144
  let text;
20891
22145
  try {
20892
- if (!statSync20(candidate).isFile()) {
22146
+ if (!statSync21(candidate).isFile()) {
20893
22147
  return { counts, unreadable: `${candidate} is not a regular file \u2014 not read` };
20894
22148
  }
20895
22149
  text = readFileSync15(candidate, "utf8");
@@ -20916,7 +22170,7 @@ function readEvalCounts(target) {
20916
22170
  }
20917
22171
  function statSyncSafe(p) {
20918
22172
  try {
20919
- return statSync20(p).isDirectory();
22173
+ return statSync21(p).isDirectory();
20920
22174
  } catch {
20921
22175
  return false;
20922
22176
  }
@@ -20984,31 +22238,62 @@ function readCursorProbe(raw) {
20984
22238
  return unreadable(`outcome kind ${JSON.stringify(o.kind)}`);
20985
22239
  }
20986
22240
  }
20987
- function launchAndIntrospect(target) {
20988
- const plan = deriveLaunchPlan(target);
20989
- if ("error" in plan) {
20990
- return { root: target, tools: [], launchError: plan.error };
22241
+ function endpointSecrets(ep) {
22242
+ const out = /* @__PURE__ */ new Set();
22243
+ const add = (v) => {
22244
+ if (v && v.length >= 6) out.add(v);
22245
+ };
22246
+ for (const v of Object.values(ep.headers)) {
22247
+ add(v);
22248
+ const m = /^\s*\S+\s+(\S.*)$/.exec(v);
22249
+ if (m) add(m[1]);
22250
+ }
22251
+ try {
22252
+ const u = new URL(ep.url);
22253
+ add(decodeURIComponent(u.username));
22254
+ add(decodeURIComponent(u.password));
22255
+ for (const [, v] of u.searchParams) add(v);
22256
+ } catch {
22257
+ }
22258
+ return [...out].sort((a, b) => b.length - a.length);
22259
+ }
22260
+ function redactSecrets(text, secrets) {
22261
+ let out = text;
22262
+ for (const s of secrets) out = out.split(s).join("[redacted]");
22263
+ return out;
22264
+ }
22265
+ function displayUrl(url) {
22266
+ try {
22267
+ const u = new URL(url);
22268
+ return `${u.protocol}//${u.host}${u.pathname}`;
22269
+ } catch {
22270
+ return "<unparsable url>";
20991
22271
  }
22272
+ }
22273
+ function introspect(plan, root, evalSource, expectedCommit, evalsNote, secrets) {
20992
22274
  const proc = spawnSync2(process.execPath, ["--input-type=module", "-e", INTROSPECTOR], {
20993
22275
  env: { ...process.env, MCP_DOCTOR_PLAN: JSON.stringify(plan) },
20994
22276
  encoding: "utf8",
20995
22277
  timeout: 2e4,
20996
22278
  maxBuffer: 8 * 1024 * 1024
20997
22279
  });
22280
+ const scrub = (t) => redactSecrets(t, secrets);
20998
22281
  if (proc.error) {
20999
22282
  return {
21000
- root: target,
22283
+ root,
21001
22284
  tools: [],
21002
- launchError: `introspector failed to run: ${proc.error.message}`
22285
+ launchError: scrub(`introspector failed to run: ${proc.error.message}`)
21003
22286
  };
21004
22287
  }
21005
22288
  const out = (proc.stdout ?? "").trim();
21006
22289
  if (!out) {
21007
22290
  const stderr = (proc.stderr ?? "").trim();
21008
22291
  return {
21009
- root: target,
22292
+ root,
21010
22293
  tools: [],
21011
- launchError: `introspector produced no result${stderr ? ` (stderr: ${stderr.slice(0, 300)})` : ""}`
22294
+ launchError: scrub(
22295
+ `introspector produced no result${stderr ? ` (stderr: ${stderr.slice(0, 300)})` : ""}`
22296
+ )
21012
22297
  };
21013
22298
  }
21014
22299
  let parsed;
@@ -21016,38 +22301,185 @@ function launchAndIntrospect(target) {
21016
22301
  parsed = JSON.parse(out);
21017
22302
  } catch {
21018
22303
  return {
21019
- root: target,
22304
+ root,
21020
22305
  tools: [],
21021
- launchError: `introspector emitted non-JSON output: ${out.slice(0, 300)}`
22306
+ launchError: scrub(`introspector emitted non-JSON output: ${out.slice(0, 300)}`)
21022
22307
  };
21023
22308
  }
21024
22309
  if (parsed.launchError) {
21025
- return { root: target, tools: [], launchError: parsed.launchError };
22310
+ return { root, tools: [], launchError: scrub(parsed.launchError) };
21026
22311
  }
21027
- const { counts: evalCounts, unreadable: evalsUnreadable } = readEvalCounts(target);
22312
+ const evals = evalSource ? readEvalCounts(evalSource) : { counts: /* @__PURE__ */ new Map() };
22313
+ const evalsUnreadable = evalsNote ?? evals.unreadable;
21028
22314
  const tools = (parsed.tools ?? []).map((t) => {
21029
22315
  const name = t.name;
21030
- const count = evalCounts.get(name);
22316
+ const count = evals.counts.get(name);
21031
22317
  const base = t.description ? { name, description: t.description } : { name };
21032
22318
  const withCursor = t.cursorArgument === true ? { ...base, cursorArgument: true } : base;
21033
22319
  return count === void 0 ? withCursor : { ...withCursor, evalCaseCount: count };
21034
22320
  });
21035
- const expectedCommit = deriveExpectedCommit(plan.cwd);
21036
22321
  return {
21037
- root: target,
22322
+ root,
21038
22323
  tools,
21039
22324
  ...parsed.serverInfo ? { serverInfo: parsed.serverInfo } : {},
21040
22325
  ...expectedCommit ? { expectedCommit } : {},
21041
22326
  ...evalsUnreadable ? { evalsUnreadable } : {},
21042
- ...Array.isArray(parsed.cursorProbes) ? { cursorProbes: parsed.cursorProbes.map(readCursorProbe) } : {}
22327
+ ...Array.isArray(parsed.cursorProbes) ? { cursorProbes: parsed.cursorProbes.map(readCursorProbe) } : {},
22328
+ ...readServed(parsed.served) ? { served: readServed(parsed.served) } : {}
21043
22329
  };
21044
22330
  }
22331
+ function launchAndIntrospect(target) {
22332
+ const plan = deriveLaunchPlan(target);
22333
+ if ("error" in plan) {
22334
+ return { root: target, tools: [], launchError: plan.error };
22335
+ }
22336
+ return introspect(
22337
+ { kind: "stdio", ...plan },
22338
+ target,
22339
+ target,
22340
+ deriveExpectedCommit(plan.cwd),
22341
+ void 0,
22342
+ []
22343
+ );
22344
+ }
22345
+ function introspectEndpoint(ep) {
22346
+ const expected = ep.expectedCommit ?? (ep.source ? deriveExpectedCommit(ep.source) : void 0);
22347
+ const rt = introspect(
22348
+ { kind: "http", url: ep.url, headers: ep.headers },
22349
+ displayUrl(ep.url),
22350
+ ep.source,
22351
+ expected,
22352
+ ep.source ? void 0 : "no --source tree was given: the server's evals/evals.json is not reachable over HTTP, so per-tool eval coverage is unknown, never zero",
22353
+ endpointSecrets(ep)
22354
+ );
22355
+ return { ...rt, remote: true, ...ep.source ? { sourceRoot: ep.source } : {} };
22356
+ }
21045
22357
 
21046
22358
  // src/types.ts
21047
22359
  function isLiveDetector(d) {
21048
22360
  return typeof d.runLive === "function";
21049
22361
  }
21050
22362
 
22363
+ // src/urlArgs.ts
22364
+ import { statSync as statSync22 } from "fs";
22365
+ var VALUE_OPTIONS = [
22366
+ "--url",
22367
+ "--header",
22368
+ "--bearer-env",
22369
+ "--source",
22370
+ "--expected-commit"
22371
+ ];
22372
+ var MANAGED_HEADERS = /* @__PURE__ */ new Set([
22373
+ "content-type",
22374
+ "accept",
22375
+ "mcp-session-id",
22376
+ "mcp-protocol-version"
22377
+ ]);
22378
+ var LOOPBACK2 = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
22379
+ function parseUrlArgs(args, env) {
22380
+ const values = {
22381
+ "--url": [],
22382
+ "--header": [],
22383
+ "--bearer-env": [],
22384
+ "--source": [],
22385
+ "--expected-commit": []
22386
+ };
22387
+ const remaining = [];
22388
+ for (let i = 0; i < args.length; i++) {
22389
+ const a = args[i];
22390
+ const opt = VALUE_OPTIONS.find((o) => a === o || a.startsWith(`${o}=`));
22391
+ if (!opt) {
22392
+ remaining.push(a);
22393
+ continue;
22394
+ }
22395
+ if (a.startsWith(`${opt}=`)) {
22396
+ values[opt].push(a.slice(opt.length + 1));
22397
+ } else {
22398
+ const next = args[i + 1];
22399
+ if (next === void 0) return { kind: "error", message: `${opt} needs a value` };
22400
+ values[opt].push(next);
22401
+ i++;
22402
+ }
22403
+ }
22404
+ const used = VALUE_OPTIONS.filter((o) => values[o].length > 0);
22405
+ if (values["--url"].length === 0) {
22406
+ if (used.length === 0) return { kind: "none", remaining };
22407
+ return { kind: "error", message: `${used[0]} is only meaningful with --url <https url>` };
22408
+ }
22409
+ if (values["--url"].length > 1) return { kind: "error", message: "--url may be given once" };
22410
+ const raw = values["--url"][0];
22411
+ let url;
22412
+ try {
22413
+ url = new URL(raw);
22414
+ } catch {
22415
+ return { kind: "error", message: "--url is not a valid URL" };
22416
+ }
22417
+ const loopback = LOOPBACK2.has(url.hostname);
22418
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
22419
+ return {
22420
+ kind: "error",
22421
+ message: "--url must be an https URL (cleartext http is accepted for a loopback host only: a credential never travels in clear)"
22422
+ };
22423
+ }
22424
+ url.hash = "";
22425
+ const headers = {};
22426
+ const setHeader = (name, value) => {
22427
+ const key = name.toLowerCase();
22428
+ if (MANAGED_HEADERS.has(key)) {
22429
+ return `header "${name}" is set by the doctor itself and cannot be supplied`;
22430
+ }
22431
+ if (key in headers) return `header "${name}" is given twice`;
22432
+ headers[key] = value;
22433
+ return null;
22434
+ };
22435
+ for (const h of values["--header"]) {
22436
+ const m = /^([A-Za-z0-9!#$%&'*+.^_`|~-]+)\s*:\s*(.*)$/.exec(h);
22437
+ if (!m) return { kind: "error", message: '--header must be "Name: value"' };
22438
+ const err = setHeader(m[1], m[2]);
22439
+ if (err) return { kind: "error", message: `--header: ${err}` };
22440
+ }
22441
+ if (values["--bearer-env"].length > 1) {
22442
+ return { kind: "error", message: "--bearer-env may be given once" };
22443
+ }
22444
+ if (values["--bearer-env"].length === 1) {
22445
+ const name = values["--bearer-env"][0];
22446
+ const token = env[name];
22447
+ if (token === void 0 || token === "") {
22448
+ return {
22449
+ kind: "error",
22450
+ message: `--bearer-env ${name}: that environment variable is unset or empty`
22451
+ };
22452
+ }
22453
+ const err = setHeader("Authorization", `Bearer ${token}`);
22454
+ if (err) return { kind: "error", message: `--bearer-env: ${err}` };
22455
+ }
22456
+ const endpoint = { url: url.toString(), headers };
22457
+ if (values["--source"].length > 1)
22458
+ return { kind: "error", message: "--source may be given once" };
22459
+ if (values["--source"].length === 1) {
22460
+ const src = values["--source"][0];
22461
+ let isDir2 = false;
22462
+ try {
22463
+ isDir2 = statSync22(src).isDirectory();
22464
+ } catch {
22465
+ isDir2 = false;
22466
+ }
22467
+ if (!isDir2) return { kind: "error", message: `--source ${src}: not a readable directory` };
22468
+ endpoint.source = src;
22469
+ }
22470
+ if (values["--expected-commit"].length > 1) {
22471
+ return { kind: "error", message: "--expected-commit may be given once" };
22472
+ }
22473
+ if (values["--expected-commit"].length === 1) {
22474
+ const sha = values["--expected-commit"][0].trim().toLowerCase();
22475
+ if (!/^[0-9a-f]{40}$/.test(sha)) {
22476
+ return { kind: "error", message: "--expected-commit must be a full 40-hex commit id" };
22477
+ }
22478
+ endpoint.expectedCommit = sha;
22479
+ }
22480
+ return { kind: "endpoint", endpoint, remaining };
22481
+ }
22482
+
21051
22483
  // src/doctor.ts
21052
22484
  function pad(s, w) {
21053
22485
  return s.length >= w ? s : s + " ".repeat(w - s.length);
@@ -21096,6 +22528,11 @@ function mergedOwed(a, b) {
21096
22528
  owedVerdict: { kind: "human", rule: (a.owedVerdict ?? b.owedVerdict)?.rule ?? "C-23", sites }
21097
22529
  };
21098
22530
  }
22531
+ function mergeServed(staticR, servedR) {
22532
+ if (servedR.state !== "could-not-judge") return servedR;
22533
+ const reason = `${staticR.reason ?? staticR.verdict} | served: ${servedR.reason ?? servedR.verdict}`;
22534
+ return { ...staticR, reason, verdict: `could not judge: ${reason}` };
22535
+ }
21099
22536
  function reconcile(id, staticR, dynamicR) {
21100
22537
  const reason = `static and dynamic verdicts DISAGREE for "${id}": static=${staticR.state} @ ${staticR.anchor} ("${staticR.verdict}") vs dynamic=${dynamicR.state} @ ${dynamicR.anchor} ("${dynamicR.verdict}"). The modes must never disagree silently \u2014 resolve which surface is authoritative for this rule.`;
21101
22538
  return {
@@ -21113,13 +22550,44 @@ function runDoctor(target, detectorList = detectors, opts = {}) {
21113
22550
  return runDoctorReport(target, detectorList, opts).results;
21114
22551
  }
21115
22552
  function runDoctorReport(target, detectorList = detectors, opts = {}) {
22553
+ if (opts.endpoint) {
22554
+ const rt = introspectEndpoint(opts.endpoint);
22555
+ const results2 = detectorList.filter((d) => typeof d.runDynamic === "function" || typeof d.runServed === "function").map(
22556
+ (d) => typeof d.runDynamic === "function" ? invokeChecked(
22557
+ d.id,
22558
+ "dynamic",
22559
+ () => d.runDynamic(rt)
22560
+ ) : invokeChecked(
22561
+ d.id,
22562
+ "dynamic",
22563
+ () => d.runServed(rt)
22564
+ )
22565
+ );
22566
+ return { results: results2, skipped: [] };
22567
+ }
21116
22568
  const mode = opts.mode ?? "static";
21117
22569
  const tree = loadTree(target, opts.backend);
21118
- const needsRuntime = mode !== "static" && detectorList.some((d) => typeof d.runDynamic === "function");
22570
+ const needsRuntime = mode !== "static" && detectorList.some(
22571
+ (d) => typeof d.runDynamic === "function" || typeof d.runServed === "function"
22572
+ );
21119
22573
  const runtime = needsRuntime ? launchAndIntrospect(target) : null;
21120
22574
  const results = [];
21121
22575
  for (const d of detectorList) {
21122
22576
  const hasDynamic = typeof d.runDynamic === "function";
22577
+ if (!hasDynamic && typeof d.runServed === "function" && mode !== "static") {
22578
+ const staticR2 = invokeChecked(d.id, "static", () => d.run(tree));
22579
+ if (staticR2.state !== "could-not-judge") {
22580
+ results.push(staticR2);
22581
+ continue;
22582
+ }
22583
+ const servedR = invokeChecked(
22584
+ d.id,
22585
+ "dynamic",
22586
+ () => d.runServed(runtime, staticR2)
22587
+ );
22588
+ results.push(mergeServed(staticR2, servedR));
22589
+ continue;
22590
+ }
21123
22591
  if (mode === "static" || !hasDynamic) {
21124
22592
  results.push(invokeChecked(d.id, "static", () => d.run(tree)));
21125
22593
  continue;
@@ -21278,6 +22746,7 @@ function computeExitCode(results) {
21278
22746
  }
21279
22747
  var USAGE = [
21280
22748
  "usage: mcp-doctor <source-tree-path> [--mode=static|dynamic|both] [--backend=<convex-dir>] [--json]",
22749
+ ' mcp-doctor --url <https url> [--bearer-env VAR] [--header "Name: value"]... [--source DIR] [--expected-commit SHA] [--json]',
21281
22750
  "",
21282
22751
  " --mode=static read the tree only (default)",
21283
22752
  " --mode=dynamic launch the server and judge what it serves",
@@ -21287,6 +22756,15 @@ var USAGE = [
21287
22756
  " fails (default 0)",
21288
22757
  " --backend=DIR the backend source (a convex/ dir) whose door list S-28 reads;",
21289
22758
  " default: the nearest convex/ above the tree",
22759
+ " --url URL judge a REMOTE streamable-HTTP server the way a customer reaches it (implies",
22760
+ " dynamic; no launch target; https, or http on loopback only). Only the rules that",
22761
+ " judge what a running server serves run; source-tree rules are not run",
22762
+ " --bearer-env VAR send the token held in environment variable VAR as 'Authorization: Bearer'",
22763
+ " (the token never appears on a command line or in output)",
22764
+ ' --header "Name: value" an extra request header (repeatable); values are never printed',
22765
+ " --source DIR with --url: the server's source tree, for D8 eval counts and the C-25 expected",
22766
+ " commit (git rev-parse HEAD there)",
22767
+ " --expected-commit SHA with --url: the full commit id the server must serve (C-25)",
21290
22768
  " --json print the report as JSON (results, owedHumanVerdicts, exitCode)",
21291
22769
  " --version print the version and exit",
21292
22770
  " --help print this and exit",
@@ -21297,12 +22775,40 @@ var USAGE = [
21297
22775
  function readVersion() {
21298
22776
  try {
21299
22777
  const here = dirname17(fileURLToPath2(import.meta.url));
21300
- const manifest = JSON.parse(readFileSync16(join27(here, "..", "package.json"), "utf8"));
22778
+ const manifest = JSON.parse(readFileSync16(join28(here, "..", "package.json"), "utf8"));
21301
22779
  return manifest.version ?? null;
21302
22780
  } catch {
21303
22781
  return null;
21304
22782
  }
21305
22783
  }
22784
+ function runUrlMode(endpoint, rest) {
22785
+ const target = rest.find((a) => !a.startsWith("--"));
22786
+ if (target) {
22787
+ console.error(
22788
+ "mcp-doctor: --url is incompatible with a launch target (the server is already running: nothing is launched or read from a path). Use --source DIR to give its source tree for the eval counts and the expected commit."
22789
+ );
22790
+ process.exit(1);
22791
+ }
22792
+ const modeArg = rest.find((a) => a.startsWith("--mode="));
22793
+ if (modeArg && modeArg !== "--mode=dynamic") {
22794
+ console.error(
22795
+ `mcp-doctor: --url implies --mode=dynamic; ${modeArg} contradicts it (a remote server has no source tree to scan statically).`
22796
+ );
22797
+ process.exit(1);
22798
+ }
22799
+ const secrets = endpointSecrets(endpoint);
22800
+ const surface = displayUrl(endpoint.url);
22801
+ const { results, skipped } = runDoctorReport(surface, detectors, { endpoint });
22802
+ const out = rest.includes("--json") ? renderJson(surface, results, skipped) : renderTable(surface, results, skipped);
22803
+ console.log(redactSecrets(out, secrets));
22804
+ const notRun = detectors.filter(
22805
+ (d) => typeof d.runDynamic !== "function" && typeof d.runServed !== "function"
22806
+ ).length;
22807
+ console.error(
22808
+ `mcp-doctor: --url judged the ${results.length} rules that read what a running server serves; ${notRun} source-tree rules were NOT run (no tree over HTTP) \u2014 this report says nothing about them.`
22809
+ );
22810
+ process.exitCode = computeExitCode(results);
22811
+ }
21306
22812
  function main() {
21307
22813
  const args = process.argv.slice(2);
21308
22814
  if (args.includes("--version") || args.includes("-V")) {
@@ -21318,6 +22824,15 @@ function main() {
21318
22824
  console.log(USAGE);
21319
22825
  return;
21320
22826
  }
22827
+ const urlArgs = parseUrlArgs(args, process.env);
22828
+ if (urlArgs.kind === "error") {
22829
+ console.error(`mcp-doctor: ${urlArgs.message}`);
22830
+ process.exit(1);
22831
+ }
22832
+ if (urlArgs.kind === "endpoint") {
22833
+ runUrlMode(urlArgs.endpoint, urlArgs.remaining);
22834
+ return;
22835
+ }
21321
22836
  const modeArg = args.find((a) => a.startsWith("--mode="));
21322
22837
  const backendArg = args.find((a) => a.startsWith("--backend="));
21323
22838
  const target = args.find((a) => !a.startsWith("--"));
@@ -21390,7 +22905,10 @@ export {
21390
22905
  SubjectUnreadableError,
21391
22906
  computeExitCode,
21392
22907
  countOwedHumanVerdicts,
22908
+ endpointSecrets,
22909
+ introspectEndpoint,
21393
22910
  isLiveDetector,
22911
+ redactSecrets,
21394
22912
  renderJson,
21395
22913
  renderOwedVerdicts,
21396
22914
  renderSkipped,