@yawlabs/mcp 0.75.4 → 0.76.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,32 +1,63 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ CLAUDE_CODE_ALLOW_PATTERN,
3
4
  CONFIG_DIRNAME,
5
+ CURRENT_OS,
6
+ ENTRY_NAME,
7
+ INSTALL_TARGETS,
8
+ LEGACY_ENTRY_NAMES,
4
9
  MIN_OAM_VERSION,
10
+ buildLaunchEntry,
5
11
  cacheDir,
6
12
  compareVersions,
13
+ findLegacyEntry,
7
14
  findProjectConfigDir,
8
15
  guidePath,
9
16
  isOamCommand,
10
17
  isOamLaunch,
18
+ isProjectLocalEntry,
11
19
  isRegistrySpec,
12
- log,
20
+ isUnderHome,
13
21
  nodeLaunchKind,
14
22
  npxSpec,
15
23
  npxSpecIndex,
16
24
  oamFailureLabel,
25
+ oamHeapOomHint,
26
+ oamInstallAdvice,
17
27
  oamInstallCommand,
28
+ oamNoBinaryReason,
29
+ oamPublishesBinaryForThisMachine,
18
30
  packageName,
19
31
  probeOam,
32
+ resolveClaudeCodeSettingsPath,
33
+ resolveInstallPath,
20
34
  resolveOamSpawn,
21
35
  resolveStableNpmEntry,
22
36
  sidecarsNodeModules,
23
37
  sidecarsRoot,
24
38
  specConstraint,
25
39
  userConfigDir
26
- } from "./chunk-VHPGG3GN.js";
40
+ } from "./chunk-CNEMSMQD.js";
41
+ import {
42
+ BINARY_DOWNLOAD_URL,
43
+ buildUpgradePlan,
44
+ detectInstallMethod,
45
+ detectSea,
46
+ fetchLatestVersion,
47
+ maybeAutoUpgrade,
48
+ parseUpgradeArgs,
49
+ refineInstallMethod,
50
+ runUpgrade
51
+ } from "./chunk-U3KC5QAD.js";
52
+ import {
53
+ log
54
+ } from "./chunk-C3AQHLOR.js";
27
55
 
28
56
  // src/audit-cmd.ts
57
+ import { readFile as readFile4 } from "fs/promises";
29
58
  import { homedir as homedir4 } from "os";
59
+ import { dirname, join as join4 } from "path";
60
+ import { fileURLToPath } from "url";
30
61
 
31
62
  // src/grades-cache.ts
32
63
  import { readFile } from "fs/promises";
@@ -36,6 +67,26 @@ import { join } from "path";
36
67
  // src/atomic-write.ts
37
68
  import { chmod, mkdir, rename, stat, unlink, writeFile } from "fs/promises";
38
69
  import path from "path";
70
+ import { setTimeout as delay } from "timers/promises";
71
+ var RENAME_RETRY_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
72
+ var RENAME_RETRY_DELAYS_MS = [10, 50, 100];
73
+ async function renameWithRetry(tmp, target) {
74
+ if (process.platform !== "win32") {
75
+ await rename(tmp, target);
76
+ return;
77
+ }
78
+ for (const ms of RENAME_RETRY_DELAYS_MS) {
79
+ try {
80
+ await rename(tmp, target);
81
+ return;
82
+ } catch (err) {
83
+ const code = err.code;
84
+ if (code === void 0 || !RENAME_RETRY_CODES.has(code)) throw err;
85
+ await delay(ms);
86
+ }
87
+ }
88
+ await rename(tmp, target);
89
+ }
39
90
  var tmpSeq = 0;
40
91
  async function atomicWriteFile(filePath, contents, encoding = "utf8", mode, dirMode) {
41
92
  const dir = path.dirname(filePath);
@@ -57,7 +108,7 @@ async function atomicWriteFile(filePath, contents, encoding = "utf8", mode, dirM
57
108
  } catch {
58
109
  }
59
110
  }
60
- await rename(tmp, filePath);
111
+ await renameWithRetry(tmp, filePath);
61
112
  } catch (err) {
62
113
  await unlink(tmp).catch(() => void 0);
63
114
  throw err;
@@ -238,7 +289,8 @@ function validateEntry(entry) {
238
289
  if (score < MIN_SCORE || score > MAX_SCORE) return null;
239
290
  const gradedAt = typeof e.gradedAt === "string" && e.gradedAt.length > 0 ? e.gradedAt : "";
240
291
  if (!gradedAt) return null;
241
- return { grade, score, gradedAt };
292
+ const suiteVersion = typeof e.suiteVersion === "string" && e.suiteVersion.length > 0 ? e.suiteVersion : void 0;
293
+ return suiteVersion ? { grade, score, gradedAt, suiteVersion } : { grade, score, gradedAt };
242
294
  }
243
295
  async function readGradesCache(home = homedir()) {
244
296
  const path6 = gradesCachePath(home);
@@ -327,7 +379,8 @@ function trustStorePath(home = homedir2()) {
327
379
  }
328
380
  function normalizeTrustKey(p) {
329
381
  const resolved = resolve(p);
330
- return process.platform === "win32" ? resolved.toLowerCase() : resolved;
382
+ const caseInsensitiveFs = process.platform === "win32" || process.platform === "darwin";
383
+ return caseInsensitiveFs ? resolved.toLowerCase() : resolved;
331
384
  }
332
385
  function hashTrustContent(contents) {
333
386
  return createHash("sha256").update(contents).digest("hex");
@@ -395,7 +448,7 @@ async function readTrustStore(home = homedir2()) {
395
448
  log("warn", "Dropping trust entry with a missing or malformed sha256", { path: path6, key });
396
449
  continue;
397
450
  }
398
- setJsonKey(entries, key, {
451
+ setJsonKey(entries, normalizeTrustKey(key), {
399
452
  path: typeof v.path === "string" && v.path.length > 0 ? v.path : key,
400
453
  sha256: v.sha256,
401
454
  grantedAt: typeof v.grantedAt === "string" ? v.grantedAt : ""
@@ -488,7 +541,7 @@ function validateEntry2(entry, warnings) {
488
541
  const command = typeof e.command === "string" ? e.command : void 0;
489
542
  const args = Array.isArray(e.args) ? e.args.filter((a) => typeof a === "string") : void 0;
490
543
  const env = e.env && typeof e.env === "object" && !Array.isArray(e.env) ? Object.fromEntries(
491
- Object.entries(e.env).filter(([, v]) => typeof v === "string")
544
+ Object.entries(e.env).filter(([, v]) => typeof v === "string" && v.trim() !== "")
492
545
  ) : void 0;
493
546
  const url = typeof e.url === "string" ? e.url : void 0;
494
547
  const description = typeof e.description === "string" ? e.description : void 0;
@@ -939,15 +992,41 @@ ${AUDIT_USAGE}` };
939
992
  function findServer(servers, namespace) {
940
993
  return servers.find((s) => s.namespace === namespace);
941
994
  }
995
+ async function resolveComplianceSuiteVersion(fromUrl = import.meta.url) {
996
+ let here;
997
+ try {
998
+ here = fileURLToPath(fromUrl);
999
+ } catch {
1000
+ return void 0;
1001
+ }
1002
+ for (let dir = dirname(here); ; dir = dirname(dir)) {
1003
+ const pjPath = join4(dir, "node_modules", "@yawlabs", "mcp-compliance", "package.json");
1004
+ let raw;
1005
+ try {
1006
+ raw = await readFile4(pjPath, "utf8");
1007
+ } catch {
1008
+ if (dirname(dir) === dir) return void 0;
1009
+ continue;
1010
+ }
1011
+ try {
1012
+ const parsed = JSON.parse(raw);
1013
+ const version = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.version : void 0;
1014
+ return typeof version === "string" && version.length > 0 ? version : void 0;
1015
+ } catch {
1016
+ return void 0;
1017
+ }
1018
+ }
1019
+ }
942
1020
  async function defaultRunner(target) {
943
1021
  const { runComplianceSuite } = await import("@yawlabs/mcp-compliance");
1022
+ const suiteVersion = await resolveComplianceSuiteVersion();
944
1023
  const report = await runComplianceSuite({
945
1024
  type: "stdio",
946
1025
  command: target.command,
947
1026
  args: target.args,
948
1027
  env: target.env
949
1028
  });
950
- return { grade: report.grade, score: report.score };
1029
+ return suiteVersion ? { grade: report.grade, score: report.score, suiteVersion } : { grade: report.grade, score: report.score };
951
1030
  }
952
1031
  async function runAudit(opts = {}) {
953
1032
  const write = opts.out ?? ((s) => process.stdout.write(s));
@@ -969,7 +1048,8 @@ async function runAudit(opts = {}) {
969
1048
  return { exitCode: 2, lines };
970
1049
  }
971
1050
  const home = opts.home ?? homedir4();
972
- const { config, path: path6 } = await loadLocalBundles({ cwd: opts.cwd, home });
1051
+ const { config, path: path6, warnings } = await loadLocalBundles({ cwd: opts.cwd, home });
1052
+ for (const w of warnings) printErr(`warning: ${w}`);
973
1053
  const servers = config?.servers ?? [];
974
1054
  const server = findServer(servers, namespace);
975
1055
  if (!server) {
@@ -1012,7 +1092,11 @@ async function runAudit(opts = {}) {
1012
1092
  let cachePath = null;
1013
1093
  let cacheError = null;
1014
1094
  try {
1015
- cachePath = await writeGrade(namespace, { grade: report.grade, score: report.score, gradedAt }, home);
1095
+ cachePath = await writeGrade(
1096
+ namespace,
1097
+ report.suiteVersion ? { grade: report.grade, score: report.score, gradedAt, suiteVersion: report.suiteVersion } : { grade: report.grade, score: report.score, gradedAt },
1098
+ home
1099
+ );
1016
1100
  } catch (err) {
1017
1101
  cacheError = err instanceof Error ? err.message : String(err);
1018
1102
  log("error", "audit: grade cache write failed", { namespace, error: cacheError });
@@ -1060,7 +1144,10 @@ var CURATED_BUNDLES = [
1060
1144
  id: "growth-stack",
1061
1145
  name: "Growth Stack",
1062
1146
  description: "HubSpot + Slack + GA for lifecycle + funnel signals",
1063
- namespaces: ["hubspot", "slack", "ga"],
1147
+ // NOT "ga": the catalog slug is `ga`, but every install path derives the
1148
+ // namespace from the row's NAME ("Google Analytics"), so the installed
1149
+ // namespace is `googleanalytics` and the slug form can never match.
1150
+ namespaces: ["hubspot", "slack", "googleanalytics"],
1064
1151
  category: "growth"
1065
1152
  },
1066
1153
  {
@@ -1114,13 +1201,13 @@ function topPartialBundles(installedNamespaces, limit) {
1114
1201
  }
1115
1202
 
1116
1203
  // src/config-loader.ts
1117
- import { readFile as readFile4 } from "fs/promises";
1204
+ import { readFile as readFile5 } from "fs/promises";
1118
1205
  import { homedir as homedir5 } from "os";
1119
- import { join as join5, resolve as resolve3 } from "path";
1206
+ import { join as join6, resolve as resolve3 } from "path";
1120
1207
 
1121
1208
  // src/migrate.ts
1122
1209
  import { mkdir as mkdir2, rename as rename2, stat as stat2 } from "fs/promises";
1123
- import { dirname, isAbsolute, join as join4, relative, resolve as resolve2 } from "path";
1210
+ import { dirname as dirname2, join as join5, resolve as resolve2 } from "path";
1124
1211
  var LEGACY_GLOBAL_FILENAME = ".yaw-mcp.json";
1125
1212
  var LEGACY_PROJECT_FILENAME = ".yaw-mcp.json";
1126
1213
  var LEGACY_LOCAL_FILENAME = ".yaw-mcp.local.json";
@@ -1171,7 +1258,7 @@ async function migrateFile(legacy, target, scope) {
1171
1258
  return;
1172
1259
  }
1173
1260
  try {
1174
- await mkdir2(dirname(target), { recursive: true });
1261
+ await mkdir2(dirname2(target), { recursive: true });
1175
1262
  await rename2(legacy, target);
1176
1263
  log("info", "yaw-mcp config: migrated legacy file into .yaw-mcp/ directory", {
1177
1264
  scope,
@@ -1189,40 +1276,31 @@ async function migrateFile(legacy, target, scope) {
1189
1276
  }
1190
1277
  async function migrateLegacyConfigPaths(opts) {
1191
1278
  const { cwd, home } = opts;
1192
- const legacyGlobal = join4(home, LEGACY_GLOBAL_FILENAME);
1193
- const newGlobal = join4(userConfigDir(home), NEW_CONFIG_FILENAME);
1279
+ const legacyGlobal = join5(home, LEGACY_GLOBAL_FILENAME);
1280
+ const newGlobal = join5(userConfigDir(home), NEW_CONFIG_FILENAME);
1194
1281
  await migrateFile(legacyGlobal, newGlobal, "global");
1195
1282
  const legacyProjectRoot = await findLegacyProjectRoot(cwd, home);
1196
1283
  if (legacyProjectRoot) {
1197
- const newDir = join4(legacyProjectRoot, CONFIG_DIRNAME);
1198
- const legacyLocal = join4(legacyProjectRoot, LEGACY_LOCAL_FILENAME);
1199
- const newLocal = join4(newDir, NEW_LOCAL_FILENAME);
1284
+ const newDir = join5(legacyProjectRoot, CONFIG_DIRNAME);
1285
+ const legacyLocal = join5(legacyProjectRoot, LEGACY_LOCAL_FILENAME);
1286
+ const newLocal = join5(newDir, NEW_LOCAL_FILENAME);
1200
1287
  await migrateFile(legacyLocal, newLocal, "local");
1201
- const legacyProject = join4(legacyProjectRoot, LEGACY_PROJECT_FILENAME);
1202
- const newProject = join4(newDir, NEW_CONFIG_FILENAME);
1288
+ const legacyProject = join5(legacyProjectRoot, LEGACY_PROJECT_FILENAME);
1289
+ const newProject = join5(newDir, NEW_CONFIG_FILENAME);
1203
1290
  await migrateFile(legacyProject, newProject, "project");
1204
1291
  }
1205
1292
  }
1206
- function normalizeForCompare(p) {
1207
- return process.platform === "win32" ? p.toLowerCase() : p;
1208
- }
1209
- function isUnderHome(dir, homeResolved) {
1210
- if (normalizeForCompare(dir) === normalizeForCompare(homeResolved)) return false;
1211
- const rel = relative(homeResolved, dir);
1212
- const relNorm = normalizeForCompare(rel);
1213
- return relNorm !== "" && !relNorm.startsWith("..") && !isAbsolute(rel);
1214
- }
1215
1293
  async function findLegacyProjectRoot(cwd, home) {
1216
1294
  const homeResolved = resolve2(home);
1217
1295
  let dir = resolve2(cwd);
1218
1296
  let prev = "";
1219
1297
  while (dir !== prev) {
1220
1298
  if (!isUnderHome(dir, homeResolved)) return null;
1221
- const legacyProject = join4(dir, LEGACY_PROJECT_FILENAME);
1222
- const legacyLocal = join4(dir, LEGACY_LOCAL_FILENAME);
1299
+ const legacyProject = join5(dir, LEGACY_PROJECT_FILENAME);
1300
+ const legacyLocal = join5(dir, LEGACY_LOCAL_FILENAME);
1223
1301
  if (await exists(legacyProject) || await exists(legacyLocal)) return dir;
1224
1302
  prev = dir;
1225
- dir = dirname(dir);
1303
+ dir = dirname2(dir);
1226
1304
  }
1227
1305
  return null;
1228
1306
  }
@@ -1254,7 +1332,7 @@ function filterStringArray(raw, field, path6, warnings) {
1254
1332
  async function readConfigAt(path6, scope, warnings) {
1255
1333
  let raw;
1256
1334
  try {
1257
- raw = await readFile4(path6, "utf8");
1335
+ raw = await readFile5(path6, "utf8");
1258
1336
  } catch (err) {
1259
1337
  const code = err.code;
1260
1338
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -1345,9 +1423,9 @@ async function loadYawMcpConfig(opts = {}) {
1345
1423
  return null;
1346
1424
  });
1347
1425
  const globalDir = userConfigDir(home);
1348
- const localPath = projectConfigDir ? join5(projectConfigDir, LOCAL_CONFIG_FILENAME) : null;
1349
- const projectPath = projectConfigDir ? join5(projectConfigDir, CONFIG_FILENAME) : null;
1350
- const globalPath = join5(globalDir, CONFIG_FILENAME);
1426
+ const localPath = projectConfigDir ? join6(projectConfigDir, LOCAL_CONFIG_FILENAME) : null;
1427
+ const projectPath = projectConfigDir ? join6(projectConfigDir, CONFIG_FILENAME) : null;
1428
+ const globalPath = join6(globalDir, CONFIG_FILENAME);
1351
1429
  const local = localPath ? await readConfigAt(localPath, "local", warnings) : null;
1352
1430
  if (local) loadedFiles.push(local);
1353
1431
  const normalizeDir = (d) => {
@@ -1726,7 +1804,7 @@ function renderBash() {
1726
1804
  const topLevelFlags = "--help -h --version -V";
1727
1805
  const cases = SUBCOMMAND_SPEC.map((spec) => {
1728
1806
  const posClauses = realPositionals(spec).map(
1729
- ({ candidates, index }) => ` if [[ $cword -eq $((${index} + 2)) ]]; then
1807
+ ({ candidates, index }) => ` if [[ $cword -eq $((${index} + 2)) && $cur != -* ]]; then
1730
1808
  COMPREPLY=( $(compgen -W "${candidates.join(" ")}" -- "$cur") )
1731
1809
  return 0
1732
1810
  fi`
@@ -1984,13 +2062,13 @@ function killTree(child) {
1984
2062
  }
1985
2063
  }
1986
2064
  function runTest(args, err) {
1987
- return new Promise((resolve8) => {
2065
+ return new Promise((resolve7) => {
1988
2066
  let settled = false;
1989
2067
  const fail = (message) => {
1990
2068
  if (settled) return;
1991
2069
  settled = true;
1992
2070
  err(message);
1993
- resolve8(null);
2071
+ resolve7(null);
1994
2072
  };
1995
2073
  const npxArgs = ["-y", "@yawlabs/mcp-compliance", "test", "--format", "json", ...args];
1996
2074
  const launch = resolveNpxLaunch(npxArgs);
@@ -2022,7 +2100,7 @@ Failed to launch mcp-compliance: ${e instanceof Error ? e.message : String(e)}
2022
2100
  process.off("SIGINT", onInterrupt);
2023
2101
  process.off("SIGTERM", onInterrupt);
2024
2102
  };
2025
- let stdout = "";
2103
+ const stdoutChunks = [];
2026
2104
  let stdoutBytes = 0;
2027
2105
  const timer = setTimeout(() => {
2028
2106
  if (settled) return;
@@ -2032,7 +2110,7 @@ Failed to launch mcp-compliance: ${e instanceof Error ? e.message : String(e)}
2032
2110
  err(`
2033
2111
  mcp-compliance timed out after ${CHILD_TIMEOUT_MS / 1e3}s; killed.
2034
2112
  `);
2035
- resolve8(null);
2113
+ resolve7(null);
2036
2114
  }, CHILD_TIMEOUT_MS);
2037
2115
  timer.unref?.();
2038
2116
  child.stdout?.on("data", (chunk) => {
@@ -2046,10 +2124,10 @@ mcp-compliance timed out after ${CHILD_TIMEOUT_MS / 1e3}s; killed.
2046
2124
  err(`
2047
2125
  mcp-compliance produced more than ${MAX_STDOUT_BYTES / (1024 * 1024)} MB of output; killed.
2048
2126
  `);
2049
- resolve8(null);
2127
+ resolve7(null);
2050
2128
  return;
2051
2129
  }
2052
- stdout += chunk.toString();
2130
+ stdoutChunks.push(chunk);
2053
2131
  });
2054
2132
  child.on("error", (e) => {
2055
2133
  if (settled) return;
@@ -2064,21 +2142,22 @@ Failed to launch mcp-compliance: ${e.message}
2064
2142
  settled = true;
2065
2143
  clearTimeout(timer);
2066
2144
  releaseSignals();
2145
+ const stdout = Buffer.concat(stdoutChunks).toString("utf8");
2067
2146
  try {
2068
2147
  const parsed = JSON.parse(stdout);
2069
2148
  if (!isRenderableReport(parsed)) {
2070
2149
  err(`
2071
2150
  mcp-compliance returned unexpected JSON (exit ${code}).
2072
2151
  `);
2073
- resolve8(null);
2152
+ resolve7(null);
2074
2153
  return;
2075
2154
  }
2076
- resolve8({ report: parsed, code });
2155
+ resolve7({ report: parsed, code });
2077
2156
  } catch {
2078
2157
  err(`
2079
2158
  mcp-compliance exited ${code} without valid JSON output.
2080
2159
  `);
2081
- resolve8(null);
2160
+ resolve7(null);
2082
2161
  }
2083
2162
  });
2084
2163
  });
@@ -2095,9 +2174,9 @@ Target: ${url}
2095
2174
 
2096
2175
  // src/doctor-cmd.ts
2097
2176
  import { closeSync, existsSync as existsSync6, fstatSync, openSync, readFileSync as readFileSync2, readSync } from "fs";
2098
- import { readFile as readFile9 } from "fs/promises";
2099
- import { homedir as homedir10 } from "os";
2100
- import { isAbsolute as isAbsolute3, join as join9 } from "path";
2177
+ import { readFile as readFile10 } from "fs/promises";
2178
+ import { homedir as homedir9 } from "os";
2179
+ import { isAbsolute, join as join9 } from "path";
2101
2180
 
2102
2181
  // src/cli-shadows.ts
2103
2182
  var EMPTY = [];
@@ -2386,14 +2465,14 @@ function describeServerRuntime(server, configDefault, probe) {
2386
2465
  }
2387
2466
 
2388
2467
  // src/guide.ts
2389
- import { readFile as readFile5 } from "fs/promises";
2468
+ import { readFile as readFile6 } from "fs/promises";
2390
2469
  var GUIDE_READ_TIMEOUT_MS = 1e3;
2391
2470
  async function readGuide(path6, scope) {
2392
2471
  let raw;
2393
2472
  const ac = new AbortController();
2394
2473
  const timer = setTimeout(() => ac.abort(new Error("guide read timeout")), GUIDE_READ_TIMEOUT_MS);
2395
2474
  try {
2396
- raw = await readFile5(path6, { encoding: "utf8", signal: ac.signal });
2475
+ raw = await readFile6(path6, { encoding: "utf8", signal: ac.signal });
2397
2476
  } catch (err) {
2398
2477
  const isTimeout = err instanceof Error && err.code === "ABORT_ERR";
2399
2478
  if (isTimeout) {
@@ -2472,222 +2551,8 @@ function renderActiveServersSection(activeServers) {
2472
2551
  ].join("\n");
2473
2552
  }
2474
2553
 
2475
- // src/install-targets.ts
2476
- import { homedir as homedir6 } from "os";
2477
- import { isAbsolute as isAbsolute2, join as join6, resolve as resolve4 } from "path";
2478
- var CURRENT_OS = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : "linux";
2479
- var INSTALL_TARGETS = [
2480
- {
2481
- clientId: "claude-code",
2482
- label: "Claude Code",
2483
- jsonShape: "mcpServers",
2484
- availableOn: ["macos", "linux", "windows"],
2485
- scopes: [
2486
- {
2487
- scope: "user",
2488
- label: "User (global)",
2489
- description: "Private to this machine; applies to every project.",
2490
- requiresProjectDir: false
2491
- },
2492
- {
2493
- scope: "project",
2494
- label: "Project",
2495
- description: "Commit to share with your team.",
2496
- requiresProjectDir: true
2497
- },
2498
- {
2499
- scope: "local",
2500
- label: "Local",
2501
- description: "Per-project override; typically gitignored.",
2502
- requiresProjectDir: true
2503
- }
2504
- ]
2505
- },
2506
- {
2507
- clientId: "claude-desktop",
2508
- label: "Claude Desktop",
2509
- jsonShape: "mcpServers",
2510
- availableOn: ["macos", "windows"],
2511
- notes: "Claude Desktop reads one file per OS \u2014 no project scope. Restart the app after editing.",
2512
- scopes: [
2513
- {
2514
- scope: "user",
2515
- label: "User",
2516
- description: "The only config file Claude Desktop reads.",
2517
- requiresProjectDir: false
2518
- }
2519
- ]
2520
- },
2521
- {
2522
- clientId: "cursor",
2523
- label: "Cursor",
2524
- jsonShape: "mcpServers",
2525
- availableOn: ["macos", "linux", "windows"],
2526
- scopes: [
2527
- {
2528
- scope: "user",
2529
- label: "User (global)",
2530
- description: "Private to this machine; applies to every Cursor project.",
2531
- requiresProjectDir: false
2532
- },
2533
- {
2534
- scope: "project",
2535
- label: "Project",
2536
- description: "Commit to share with your team.",
2537
- requiresProjectDir: true
2538
- }
2539
- ]
2540
- },
2541
- {
2542
- clientId: "vscode",
2543
- label: "VS Code",
2544
- jsonShape: "servers",
2545
- availableOn: ["macos", "linux", "windows"],
2546
- notes: "VS Code uses `servers` (not `mcpServers`) as the top-level key in .vscode/mcp.json.",
2547
- scopes: [
2548
- {
2549
- scope: "project",
2550
- label: "Workspace",
2551
- description: "Per-project config; commit to share.",
2552
- requiresProjectDir: true
2553
- }
2554
- ]
2555
- }
2556
- ];
2557
- function resolveInstallPath(opts) {
2558
- const home = opts.home ?? homedir6();
2559
- const appData = opts.appData ?? process.env.APPDATA ?? join6(home, "AppData", "Roaming");
2560
- const { clientId, scope, os, projectDir, claudeConfigDir } = opts;
2561
- const target = INSTALL_TARGETS.find((t) => t.clientId === clientId);
2562
- if (!target) throw new Error(`Unknown client: ${clientId}`);
2563
- const scopeSpec = target.scopes.find((s) => s.scope === scope);
2564
- if (!scopeSpec) throw new Error(`Client ${clientId} does not support scope ${scope}`);
2565
- if (!target.availableOn.includes(os)) {
2566
- throw new Error(`${target.label} is not available on ${os}`);
2567
- }
2568
- if (scopeSpec.requiresProjectDir && !projectDir) {
2569
- throw new Error(`Scope ${scope} for ${clientId} requires a project directory`);
2570
- }
2571
- const absoluteProjectDir = projectDir && !isAbsolute2(projectDir) ? resolve4(projectDir) : projectDir;
2572
- const p = pathFor(clientId, scope, os, {
2573
- home,
2574
- appData,
2575
- projectDir: absoluteProjectDir ?? "",
2576
- claudeConfigDir: claudeConfigDir && claudeConfigDir.length > 0 ? claudeConfigDir : void 0
2577
- });
2578
- return p;
2579
- }
2580
- function pathFor(client, scope, os, base) {
2581
- const { home, appData, projectDir, claudeConfigDir } = base;
2582
- const sep2 = os === "windows" ? "\\" : "/";
2583
- const joinPath = (...parts) => parts.join(sep2);
2584
- if (client === "claude-code") {
2585
- if (scope === "user") {
2586
- if (claudeConfigDir) {
2587
- const absolute = join6(claudeConfigDir, ".claude.json");
2588
- return { absolute, display: absolute, containerPath: ["mcpServers"] };
2589
- }
2590
- const display = os === "windows" ? "%USERPROFILE%\\.claude.json" : "~/.claude.json";
2591
- return { absolute: join6(home, ".claude.json"), display, containerPath: ["mcpServers"] };
2592
- }
2593
- if (scope === "project") {
2594
- return {
2595
- absolute: join6(projectDir, ".mcp.json"),
2596
- display: joinPath("<project folder>", ".mcp.json"),
2597
- containerPath: ["mcpServers"]
2598
- };
2599
- }
2600
- if (claudeConfigDir) {
2601
- const absolute = join6(claudeConfigDir, ".claude.json");
2602
- return { absolute, display: absolute, containerPath: ["projects", projectDir, "mcpServers"] };
2603
- }
2604
- return {
2605
- absolute: join6(home, ".claude.json"),
2606
- display: os === "windows" ? "%USERPROFILE%\\.claude.json" : "~/.claude.json",
2607
- containerPath: ["projects", projectDir, "mcpServers"]
2608
- };
2609
- }
2610
- if (client === "claude-desktop") {
2611
- if (os === "macos") {
2612
- return {
2613
- absolute: join6(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"),
2614
- display: "~/Library/Application Support/Claude/claude_desktop_config.json",
2615
- containerPath: ["mcpServers"]
2616
- };
2617
- }
2618
- if (os === "windows") {
2619
- return {
2620
- absolute: join6(appData, "Claude", "claude_desktop_config.json"),
2621
- display: "%APPDATA%\\Claude\\claude_desktop_config.json",
2622
- containerPath: ["mcpServers"]
2623
- };
2624
- }
2625
- throw new Error("Claude Desktop is not available on Linux");
2626
- }
2627
- if (client === "cursor") {
2628
- if (scope === "user") {
2629
- const display = os === "windows" ? "%USERPROFILE%\\.cursor\\mcp.json" : "~/.cursor/mcp.json";
2630
- return { absolute: join6(home, ".cursor", "mcp.json"), display, containerPath: ["mcpServers"] };
2631
- }
2632
- return {
2633
- absolute: join6(projectDir, ".cursor", "mcp.json"),
2634
- display: joinPath("<project folder>", ".cursor", "mcp.json"),
2635
- containerPath: ["mcpServers"]
2636
- };
2637
- }
2638
- if (client === "vscode") {
2639
- return {
2640
- absolute: join6(projectDir, ".vscode", "mcp.json"),
2641
- display: joinPath("<project folder>", ".vscode", "mcp.json"),
2642
- containerPath: ["servers"]
2643
- };
2644
- }
2645
- throw new Error(`Unhandled client: ${client}`);
2646
- }
2647
- function buildLaunchEntry(opts) {
2648
- if (opts.upstream) {
2649
- const { command, args, env } = opts.upstream;
2650
- if (opts.os === "windows") {
2651
- const wrapped = { command: "cmd", args: ["/c", command, ...args] };
2652
- if (env && Object.keys(env).length > 0) wrapped.env = { ...env };
2653
- return wrapped;
2654
- }
2655
- const entry = { command, args: [...args] };
2656
- if (env && Object.keys(env).length > 0) entry.env = { ...env };
2657
- return entry;
2658
- }
2659
- const pkg = opts.pkg ?? "@yawlabs/mcp@latest";
2660
- if (opts.oamBinPath && isAbsolute2(opts.oamBinPath) && opts.oamEntry && !opts.pkg) {
2661
- return { command: opts.oamBinPath, args: ["run", "--no-check", opts.oamEntry] };
2662
- }
2663
- return opts.os === "windows" ? { command: "cmd", args: ["/c", "npx", "-y", pkg] } : { command: "npx", args: ["-y", pkg] };
2664
- }
2665
- function isProjectLocalEntry(entryPath, cwd) {
2666
- const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
2667
- const entry = norm(entryPath);
2668
- const here = norm(cwd);
2669
- const idx = entry.indexOf("/node_modules/");
2670
- if (idx <= 0) return false;
2671
- const root = entry.slice(0, idx);
2672
- return here === root || here.startsWith(`${root}/`);
2673
- }
2674
- var ENTRY_NAME = "mcp";
2675
- var LEGACY_ENTRY_NAMES = ["mcp.hosting", "mcph", "yaw-mcp"];
2676
- function findLegacyEntry(container) {
2677
- return LEGACY_ENTRY_NAMES.find((n) => n in container) ?? null;
2678
- }
2679
- var CLAUDE_CODE_ALLOW_PATTERN = "mcp__mcp__*";
2680
- function resolveClaudeCodeSettingsPath(scope, opts) {
2681
- const { home, projectDir, claudeConfigDir } = opts;
2682
- const cfgDir = claudeConfigDir && claudeConfigDir.length > 0 ? claudeConfigDir : null;
2683
- if (scope === "user") return cfgDir ? join6(cfgDir, "settings.json") : join6(home, ".claude", "settings.json");
2684
- if (scope === "project" && projectDir) return join6(projectDir, ".claude", "settings.json");
2685
- if (scope === "local" && projectDir) return join6(projectDir, ".claude", "settings.local.json");
2686
- return null;
2687
- }
2688
-
2689
2554
  // src/persistence.ts
2690
- import { readFile as readFile6 } from "fs/promises";
2555
+ import { readFile as readFile7 } from "fs/promises";
2691
2556
  import path2 from "path";
2692
2557
  var STATE_SCHEMA_VERSION = 2;
2693
2558
  var STATE_FILENAME = "state.json";
@@ -2713,8 +2578,8 @@ function emptyState() {
2713
2578
  }
2714
2579
  async function loadState(filePath = statePath()) {
2715
2580
  try {
2716
- const raw = await readFile6(filePath, "utf8");
2717
- const parsed = JSON.parse(raw);
2581
+ const raw = await readFile7(filePath, "utf8");
2582
+ const parsed = JSON.parse(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw);
2718
2583
  if (!parsed || typeof parsed !== "object") return emptyState();
2719
2584
  if (!isReadableStateVersion(parsed.version)) return emptyState();
2720
2585
  const p = parsed;
@@ -2822,12 +2687,12 @@ function errorMessage(err) {
2822
2687
  // src/sidecars-cmd.ts
2823
2688
  import { spawn as spawn2 } from "child_process";
2824
2689
  import { existsSync as existsSync3, mkdirSync, readFileSync } from "fs";
2825
- import { homedir as homedir7 } from "os";
2690
+ import { homedir as homedir6 } from "os";
2826
2691
  import { join as join7 } from "path";
2827
2692
  function collectSidecarSpecs(servers) {
2828
2693
  const byPkg = /* @__PURE__ */ new Map();
2829
2694
  for (const s of servers) {
2830
- if (s.type !== "local" || s.command !== "npx") continue;
2695
+ if (s.type !== "local" || s.command === void 0 || nodeLaunchKind(s.command) !== "npx") continue;
2831
2696
  const spec = npxSpec(s.args ?? []);
2832
2697
  if (spec === null) continue;
2833
2698
  if (!isRegistrySpec(spec)) continue;
@@ -2846,7 +2711,7 @@ function collectSidecarSpecs(servers) {
2846
2711
  function collectNonRegistrySpecs(servers) {
2847
2712
  const out = [];
2848
2713
  for (const s of servers) {
2849
- if (s.type !== "local" || s.command !== "npx") continue;
2714
+ if (s.type !== "local" || s.command === void 0 || nodeLaunchKind(s.command) !== "npx") continue;
2850
2715
  const spec = npxSpec(s.args ?? []);
2851
2716
  if (spec === null || isRegistrySpec(spec)) continue;
2852
2717
  out.push({ namespace: s.namespace ?? "(unnamed)", spec });
@@ -2872,7 +2737,21 @@ function sidecarsManifest(specs) {
2872
2737
  )}
2873
2738
  `;
2874
2739
  }
2875
- function installedVersion(pkg, home = homedir7()) {
2740
+ function sidecarsPlatformPath(home = homedir6()) {
2741
+ return join7(sidecarsRoot(home), "platform.json");
2742
+ }
2743
+ function installedPlatform(home = homedir6()) {
2744
+ try {
2745
+ const raw = JSON.parse(readFileSync(sidecarsPlatformPath(home), "utf8"));
2746
+ if (typeof raw?.platform === "string" && typeof raw?.arch === "string") {
2747
+ return { platform: raw.platform, arch: raw.arch };
2748
+ }
2749
+ return null;
2750
+ } catch {
2751
+ return null;
2752
+ }
2753
+ }
2754
+ function installedVersion(pkg, home = homedir6()) {
2876
2755
  const pj = join7(sidecarsNodeModules(home), ...pkg.split("/"), "package.json");
2877
2756
  try {
2878
2757
  const v = JSON.parse(readFileSync(pj, "utf8")).version;
@@ -2897,7 +2776,7 @@ function jsonDocument(root, over = {}) {
2897
2776
  `;
2898
2777
  }
2899
2778
  function defaultRunNpm(args, cwd) {
2900
- return new Promise((resolve8) => {
2779
+ return new Promise((resolve7) => {
2901
2780
  const isWindows = process.platform === "win32";
2902
2781
  let child;
2903
2782
  try {
@@ -2915,11 +2794,11 @@ function defaultRunNpm(args, cwd) {
2915
2794
  shell: isWindows
2916
2795
  });
2917
2796
  } catch {
2918
- resolve8(-1);
2797
+ resolve7(-1);
2919
2798
  return;
2920
2799
  }
2921
- child.on("error", () => resolve8(-1));
2922
- child.on("close", (code, signal) => resolve8(code ?? (signal ? -1 : 0)));
2800
+ child.on("error", () => resolve7(-1));
2801
+ child.on("close", (code, signal) => resolve7(code ?? (signal ? -1 : 0)));
2923
2802
  });
2924
2803
  }
2925
2804
  var SIDECARS_USAGE = `Usage: yaw-mcp sidecars install [--json]
@@ -2962,7 +2841,9 @@ ${SIDECARS_USAGE}` };
2962
2841
  return { ok: true, options: { json } };
2963
2842
  }
2964
2843
  async function unhostedReasons(servers, opts, home) {
2965
- const npx = servers.filter((s) => s.type === "local" && s.command === "npx");
2844
+ const npx = servers.filter(
2845
+ (s) => s.type === "local" && s.command !== void 0 && nodeLaunchKind(s.command) === "npx"
2846
+ );
2966
2847
  if (npx.length === 0) return [];
2967
2848
  const probe = await (opts.oamProbe ?? probeOam)();
2968
2849
  const { runtime: configDefault } = await describeDefaultRuntime({ cwd: opts.cwd, home });
@@ -2984,7 +2865,7 @@ async function unhostedReasons(servers, opts, home) {
2984
2865
  return [...new Set(verdicts.map((v) => v.reason))];
2985
2866
  }
2986
2867
  async function runSidecarsInstall(opts = {}) {
2987
- const home = opts.home ?? homedir7();
2868
+ const home = opts.home ?? homedir6();
2988
2869
  const write = opts.out ?? ((s) => process.stdout.write(s));
2989
2870
  const lines = [];
2990
2871
  const print = (s = "") => {
@@ -3060,6 +2941,11 @@ async function runSidecarsInstall(opts = {}) {
3060
2941
  if (opts.json) write(jsonDocument(root, { error: `npm exited ${code}`, conflicts, skipped }));
3061
2942
  return { exitCode: 1, installed: [], lines };
3062
2943
  }
2944
+ await atomicWriteFile(
2945
+ sidecarsPlatformPath(home),
2946
+ `${JSON.stringify({ platform: process.platform, arch: process.arch }, null, 2)}
2947
+ `
2948
+ );
3063
2949
  const updateCode = await runNpm(["update", "--no-audit", "--no-fund"], root);
3064
2950
  const updateError = updateCode === 0 ? null : `npm update exited ${updateCode}`;
3065
2951
  const installed = specs.map((s) => ({
@@ -3094,15 +2980,15 @@ async function runSidecarsInstall(opts = {}) {
3094
2980
  if (opts.json) write(jsonDocument(root, { installed, conflicts, skipped, error, updateError, unhosted }));
3095
2981
  return { exitCode: nothingLanded ? 1 : 0, installed, lines };
3096
2982
  }
3097
- function hasManagedSidecars(home = homedir7()) {
2983
+ function hasManagedSidecars(home = homedir6()) {
3098
2984
  return existsSync3(sidecarsNodeModules(home));
3099
2985
  }
3100
2986
 
3101
2987
  // src/try-cmd.ts
3102
2988
  import { existsSync as existsSync5 } from "fs";
3103
- import { chmod as chmod4, mkdir as mkdir3, readdir, readFile as readFile8, unlink as unlink2 } from "fs/promises";
3104
- import { homedir as homedir9 } from "os";
3105
- import { join as join8, resolve as resolve6 } from "path";
2989
+ import { chmod as chmod4, mkdir as mkdir3, readdir, readFile as readFile9, unlink as unlink2 } from "fs/promises";
2990
+ import { homedir as homedir8 } from "os";
2991
+ import { join as join8, resolve as resolve5 } from "path";
3106
2992
 
3107
2993
  // src/catalog.ts
3108
2994
  var DEFAULT_CATALOG_URL = "https://yaw.sh/data/mcp-catalog.json";
@@ -3138,7 +3024,21 @@ function tokenizeCommand(cmd) {
3138
3024
  if (has) out.push(cur);
3139
3025
  return out;
3140
3026
  }
3141
- async function defaultFetchCatalog(url = DEFAULT_CATALOG_URL) {
3027
+ var CATALOG_STALE_AFTER_DAYS = 90;
3028
+ function warnIfCatalogStale(body, opts) {
3029
+ const stamp = body?.generated_at;
3030
+ if (typeof stamp !== "string") return;
3031
+ const generated = Date.parse(stamp);
3032
+ if (Number.isNaN(generated)) return;
3033
+ const ageDays = Math.floor(((opts.now?.() ?? Date.now()) - generated) / 864e5);
3034
+ if (ageDays < CATALOG_STALE_AFTER_DAYS) return;
3035
+ const warn = opts.warn ?? ((line) => process.stderr.write(`${line}
3036
+ `));
3037
+ warn(
3038
+ `yaw-mcp: note: the Yaw MCP catalog was generated ${stamp.slice(0, 10)} (${ageDays} days ago); its entries may be out of date.`
3039
+ );
3040
+ }
3041
+ async function defaultFetchCatalog(url = DEFAULT_CATALOG_URL, deps = {}) {
3142
3042
  const ac = new AbortController();
3143
3043
  const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);
3144
3044
  let body;
@@ -3169,6 +3069,7 @@ async function defaultFetchCatalog(url = DEFAULT_CATALOG_URL) {
3169
3069
  if (!Array.isArray(servers)) {
3170
3070
  throw new Error(`the Yaw MCP catalog at ${url} was not in the expected shape.`);
3171
3071
  }
3072
+ warnIfCatalogStale(body, deps);
3172
3073
  return servers.filter(
3173
3074
  (s) => typeof s === "object" && s !== null && typeof s.slug === "string"
3174
3075
  );
@@ -3215,13 +3116,17 @@ async function resolveCatalogSlug(slug, opts = {}) {
3215
3116
 
3216
3117
  // src/install-cmd.ts
3217
3118
  import { existsSync as existsSync4 } from "fs";
3218
- import { readFile as readFile7 } from "fs/promises";
3219
- import { homedir as homedir8 } from "os";
3220
- import { resolve as resolve5 } from "path";
3119
+ import { readFile as readFile8 } from "fs/promises";
3120
+ import { homedir as homedir7 } from "os";
3121
+ import { resolve as resolve4 } from "path";
3221
3122
  import { createInterface } from "readline/promises";
3222
3123
  import { Writable } from "stream";
3223
3124
  function oamAbsentNote(os) {
3224
- return `Runtime: node (oam is not installed, which is fine -- node is the supported default. To host yaw-mcp on oam instead: \`${oamInstallCommand(os)}\`, then re-run install.)`;
3125
+ const head = "Runtime: node (oam is not installed, which is fine -- node is the supported default. ";
3126
+ if (os === CURRENT_OS && !oamPublishesBinaryForThisMachine()) {
3127
+ return `${head}oam is not an option on this machine: ${oamNoBinaryReason()}.)`;
3128
+ }
3129
+ return `${head}To host yaw-mcp on oam instead: \`${oamInstallCommand(os)}\`, then re-run install.)`;
3225
3130
  }
3226
3131
  function oamIsAbsent(probe) {
3227
3132
  return probe.bin === null && probe.binPath === null && !probe.belowMin && probe.failure === null;
@@ -3268,7 +3173,12 @@ ${USAGE}`);
3268
3173
  }
3269
3174
  const os = opts.os ?? CURRENT_OS;
3270
3175
  if (!target.availableOn.includes(os)) {
3271
- const fix = target.clientId === "claude-desktop" && os === "linux" ? "Anthropic ships Claude Desktop on macOS and Windows only. Install Claude Code or Cursor instead." : "Pick a different client or pass --os to override.";
3176
+ const fix = target.clientId === "claude-desktop" && os === "linux" ? "Anthropic ships Claude Desktop on macOS and Windows only. Install Claude Code or Cursor instead." : (
3177
+ // NOT "pass --os to override": install resolves paths against THIS
3178
+ // machine, so a cross-OS --os write is refused at the flag boundary
3179
+ // (see parseInstallArgs) — only the --dry-run preview is offered.
3180
+ "Pick a different client, or preview another OS's config with --os <os> --dry-run."
3181
+ );
3272
3182
  err(`yaw-mcp install: ${target.label} is not available on ${os}.
3273
3183
  ${fix}`);
3274
3184
  return { written: [], wouldWrite: [], messages, exitCode: 2 };
@@ -3281,7 +3191,7 @@ ${USAGE}`);
3281
3191
  );
3282
3192
  return { written: [], wouldWrite: [], messages, exitCode: 2 };
3283
3193
  }
3284
- const projectDir = scopeSpec.requiresProjectDir ? resolve5(opts.projectDir ?? opts.cwd ?? process.cwd()) : void 0;
3194
+ const projectDir = scopeSpec.requiresProjectDir ? resolve4(opts.projectDir ?? opts.cwd ?? process.cwd()) : void 0;
3285
3195
  let resolved;
3286
3196
  try {
3287
3197
  resolved = resolveInstallPath({
@@ -3341,7 +3251,7 @@ ${USAGE}`);
3341
3251
  if (existsSync4(resolved.absolute)) {
3342
3252
  let raw;
3343
3253
  try {
3344
- raw = await readFile7(resolved.absolute, "utf8");
3254
+ raw = await readFile8(resolved.absolute, "utf8");
3345
3255
  } catch (e) {
3346
3256
  err(`yaw-mcp install: cannot read ${resolved.absolute}: ${e.message}`);
3347
3257
  return { written: [], wouldWrite: [], messages, exitCode: 1 };
@@ -3448,7 +3358,7 @@ ${USAGE}`);
3448
3358
  clientJson = `${JSON.stringify(merged, null, 2)}
3449
3359
  `;
3450
3360
  }
3451
- const home = opts.home ?? homedir8();
3361
+ const home = opts.home ?? homedir7();
3452
3362
  const settingsPatch = opts.clientId === "claude-code" ? await prepareClaudeCodeSettingsPatch({
3453
3363
  scope,
3454
3364
  home,
@@ -3509,8 +3419,11 @@ ${settingsPatch.nextJson}`);
3509
3419
  `Note: legacy "${legacyEntry}" entry remains at ${resolved.absolute}. Remove it to avoid running yaw-mcp twice.`
3510
3420
  );
3511
3421
  }
3512
- log2(`
3513
- Done: ${target.label} is configured. Restart it to pick up the new MCP server.`);
3422
+ log2(
3423
+ target.clientId === "claude-code" && scope === "project" ? `
3424
+ Done: ${target.label} is configured. Restart it in this project and approve the .mcp.json server when prompted \u2014 Claude Code keeps project-scope (.mcp.json) servers disabled until you approve them.` : `
3425
+ Done: ${target.label} is configured. Restart it to pick up the new MCP server.`
3426
+ );
3514
3427
  return { written, wouldWrite: [], messages, exitCode: 0 };
3515
3428
  }
3516
3429
  async function prepareClaudeCodeSettingsPatch(opts) {
@@ -3525,7 +3438,7 @@ async function prepareClaudeCodeSettingsPatch(opts) {
3525
3438
  let rawSettings = null;
3526
3439
  if (existsSync4(path6)) {
3527
3440
  try {
3528
- const raw = await readFile7(path6, "utf8");
3441
+ const raw = await readFile8(path6, "utf8");
3529
3442
  if (raw.trim().length > 0) {
3530
3443
  const parsed = parseJsonc(raw);
3531
3444
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
@@ -3559,7 +3472,7 @@ async function prepareClaudeCodeSettingsPatch(opts) {
3559
3472
  function legacyAllowPatternFor(entryName) {
3560
3473
  return `mcp__${entryName.replace(/[^A-Za-z0-9]/g, "_")}__*`;
3561
3474
  }
3562
- var LEGACY_CLAUDE_CODE_ALLOW_PATTERNS = ["mcp__mcp_hosting__*", "mcp__yaw_mcp__*"];
3475
+ var LEGACY_CLAUDE_CODE_ALLOW_PATTERNS = LEGACY_ENTRY_NAMES.map(legacyAllowPatternFor);
3563
3476
  function mergePermissionsAllow(existing, patterns, retain = []) {
3564
3477
  const out = { ...existing };
3565
3478
  const prev = out.permissions;
@@ -3716,6 +3629,12 @@ ${USAGE}` };
3716
3629
  positional.push(a);
3717
3630
  }
3718
3631
  }
3632
+ if (opts.os && opts.os !== CURRENT_OS && !opts.dryRun && !opts.listOnly) {
3633
+ return {
3634
+ ok: false,
3635
+ error: `yaw-mcp install: --os ${opts.os} does not match this machine (${CURRENT_OS}), and install can only resolve config paths for the machine it runs on \u2014 a cross-OS write would create a ${CURRENT_OS}-shaped junk tree. Add --dry-run to preview, or run install on the ${opts.os} machine itself.`
3636
+ };
3637
+ }
3719
3638
  if (opts.listOnly || opts.all) {
3720
3639
  if (positional.length > 0) {
3721
3640
  return {
@@ -3740,7 +3659,7 @@ ${USAGE}` };
3740
3659
  return { ok: true, options: opts };
3741
3660
  }
3742
3661
  async function runInstallList(opts, log2, messages) {
3743
- const home = opts.home ?? homedir8();
3662
+ const home = opts.home ?? homedir7();
3744
3663
  const cwd = opts.cwd ?? process.cwd();
3745
3664
  const os = opts.os ?? CURRENT_OS;
3746
3665
  const probes = await probeClientsAsync({ home, os, cwd, claudeConfigDir: opts.claudeConfigDir });
@@ -4032,10 +3951,10 @@ function parseDurationMs(s) {
4032
3951
  const factor = unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
4033
3952
  return n * factor;
4034
3953
  }
4035
- function trialsDir(home = homedir9()) {
3954
+ function trialsDir(home = homedir8()) {
4036
3955
  return join8(home, CONFIG_DIRNAME, TRIALS_DIRNAME);
4037
3956
  }
4038
- function trialMarkerPath(slug, home = homedir9()) {
3957
+ function trialMarkerPath(slug, home = homedir8()) {
4039
3958
  return join8(trialsDir(home), `${slug}.json`);
4040
3959
  }
4041
3960
  function rejectUntrustedMarker(marker) {
@@ -4049,7 +3968,7 @@ function rejectUntrustedMarker(marker) {
4049
3968
  }
4050
3969
  async function readTrialMarker(markerPath) {
4051
3970
  try {
4052
- const parsed = JSON.parse(await readFile8(markerPath, "utf8"));
3971
+ const parsed = JSON.parse(await readFile9(markerPath, "utf8"));
4053
3972
  if (!parsed || typeof parsed !== "object") return null;
4054
3973
  if (typeof parsed.clientPath !== "string" || typeof parsed.entryName !== "string") return null;
4055
3974
  if (!Array.isArray(parsed.containerPath)) return null;
@@ -4062,7 +3981,7 @@ async function peelTrialEntry(marker) {
4062
3981
  if (rejectUntrustedMarker(marker) !== null) return "failed";
4063
3982
  if (!existsSync5(marker.clientPath)) return "absent";
4064
3983
  try {
4065
- const raw = await readFile8(marker.clientPath, "utf8");
3984
+ const raw = await readFile9(marker.clientPath, "utf8");
4066
3985
  if (raw.trim().length === 0) return "absent";
4067
3986
  const parsed = parseJsonc(raw);
4068
3987
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "failed";
@@ -4122,7 +4041,7 @@ async function runTry(opts) {
4122
4041
  return { exitCode: 2, written: [] };
4123
4042
  }
4124
4043
  const env = opts.env ?? process.env;
4125
- const home = opts.home ?? homedir9();
4044
+ const home = opts.home ?? homedir8();
4126
4045
  const cwd = opts.cwd ?? process.cwd();
4127
4046
  const os = opts.os ?? CURRENT_OS;
4128
4047
  const now = opts.now ? opts.now() : Date.now();
@@ -4147,7 +4066,7 @@ async function runTry(opts) {
4147
4066
  }
4148
4067
  const clientId = opts.clientId ?? await autoDetectClient({ home, os, cwd, claudeConfigDir });
4149
4068
  const scope = clientId === "vscode" ? "project" : "user";
4150
- const projectDir = scope === "project" ? resolve6(cwd) : void 0;
4069
+ const projectDir = scope === "project" ? resolve5(cwd) : void 0;
4151
4070
  let resolved;
4152
4071
  try {
4153
4072
  resolved = resolveInstallPath({ clientId, scope, os, home, projectDir, claudeConfigDir });
@@ -4205,7 +4124,7 @@ async function runTry(opts) {
4205
4124
  if (clientPreExisted) {
4206
4125
  let raw;
4207
4126
  try {
4208
- raw = await readFile8(resolved.absolute, "utf8");
4127
+ raw = await readFile9(resolved.absolute, "utf8");
4209
4128
  } catch (e) {
4210
4129
  const code = e.code;
4211
4130
  printErr(
@@ -4327,7 +4246,7 @@ async function runTryCleanup(opts) {
4327
4246
  return { exitCode: 2, written: [] };
4328
4247
  }
4329
4248
  const env = opts.env ?? process.env;
4330
- const home = opts.home ?? homedir9();
4249
+ const home = opts.home ?? homedir8();
4331
4250
  const baseUrl = opts.baseUrl ?? env.YAW_MCP_BASE_URL ?? DEFAULT_BASE_URL;
4332
4251
  const markerPath = trialMarkerPath(slug, home);
4333
4252
  if (!existsSync5(markerPath)) {
@@ -4336,7 +4255,7 @@ async function runTryCleanup(opts) {
4336
4255
  }
4337
4256
  let marker;
4338
4257
  try {
4339
- const raw = await readFile8(markerPath, "utf8");
4258
+ const raw = await readFile9(markerPath, "utf8");
4340
4259
  const parsed = JSON.parse(raw);
4341
4260
  if (!parsed || typeof parsed !== "object" || typeof parsed.entryName !== "string") {
4342
4261
  throw new Error("marker is missing required fields");
@@ -4355,7 +4274,7 @@ async function runTryCleanup(opts) {
4355
4274
  const written = [];
4356
4275
  if (existsSync5(marker.clientPath)) {
4357
4276
  try {
4358
- const raw = await readFile8(marker.clientPath, "utf8");
4277
+ const raw = await readFile9(marker.clientPath, "utf8");
4359
4278
  if (raw.trim().length > 0) {
4360
4279
  const parsed = parseJsonc(raw);
4361
4280
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
@@ -4394,7 +4313,7 @@ function formatTtl(ms) {
4394
4313
  return `${Math.round(clamped / 864e5)}d`;
4395
4314
  }
4396
4315
  async function scanTrials(opts = {}) {
4397
- const home = opts.home ?? homedir9();
4316
+ const home = opts.home ?? homedir8();
4398
4317
  const now = opts.now ? opts.now() : Date.now();
4399
4318
  const dir = trialsDir(home);
4400
4319
  const result = { live: [], expired: [], malformed: [] };
@@ -4409,7 +4328,7 @@ async function scanTrials(opts = {}) {
4409
4328
  if (!filename.endsWith(".json")) continue;
4410
4329
  const path6 = join8(dir, filename);
4411
4330
  try {
4412
- const raw = await readFile8(path6, "utf8");
4331
+ const raw = await readFile9(path6, "utf8");
4413
4332
  const parsed = JSON.parse(raw);
4414
4333
  if (!parsed || typeof parsed !== "object" || typeof parsed.slug !== "string" || typeof parsed.expiresAt !== "number" || typeof parsed.clientPath !== "string" || !Array.isArray(parsed.containerPath) || typeof parsed.entryName !== "string" || // Same trust check runTryCleanup applies: the GC deletes these three
4415
4334
  // fields' worth of state from a file named by the marker itself, so a
@@ -4432,7 +4351,7 @@ async function scanTrials(opts = {}) {
4432
4351
  return result;
4433
4352
  }
4434
4353
  async function gcExpiredTrials(opts) {
4435
- const home = opts.home ?? homedir9();
4354
+ const home = opts.home ?? homedir8();
4436
4355
  const env = opts.env ?? process.env;
4437
4356
  const baseUrl = opts.baseUrl ?? env.YAW_MCP_BASE_URL ?? DEFAULT_BASE_URL;
4438
4357
  const postEvent = opts.postEvent ?? defaultPostEvent;
@@ -4443,7 +4362,7 @@ async function gcExpiredTrials(opts) {
4443
4362
  for (const { marker, path: path6 } of scan.expired) {
4444
4363
  try {
4445
4364
  if (existsSync5(marker.clientPath)) {
4446
- const raw = await readFile8(marker.clientPath, "utf8");
4365
+ const raw = await readFile9(marker.clientPath, "utf8");
4447
4366
  if (raw.trim().length > 0) {
4448
4367
  const parsed = parseJsonc(raw);
4449
4368
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
@@ -4469,357 +4388,6 @@ async function gcExpiredTrials(opts) {
4469
4388
  return { cleared, failed };
4470
4389
  }
4471
4390
 
4472
- // src/upgrade-cmd.ts
4473
- import { spawn as spawn3 } from "child_process";
4474
- import { realpathSync } from "fs";
4475
- var BINARY_DOWNLOAD_URL = "https://github.com/YawLabs/mcp/releases/latest";
4476
- var POSIX_GLOBAL_LIB_PREFIX = /^(?:[A-Za-z]:)?(?:\/usr(?:\/local)?|\/opt\/[^/]+)\/lib\/node_modules\/@yawlabs\/mcp\//;
4477
- var MANAGED_NODE_LIB_PREFIX = /\/(?:\.local|\.nvm|\.fnm|fnm|\.asdf|\.volta|\.nodenv|\.nvs|n)\/(?:[^/]+\/)*lib\/node_modules\/@yawlabs\/mcp\//;
4478
- var UPGRADE_USAGE = `Usage: yaw-mcp upgrade [--run] [--json]
4479
-
4480
- Show (or execute) the command to upgrade @yawlabs/mcp to the latest version.
4481
-
4482
- --run Run the upgrade in place (global npm, pnpm, bun, and local npm
4483
- installs). No-op for npx installs -- they always fetch the latest.
4484
- --json Emit a machine-readable snapshot ({ current, latest, stale,
4485
- method, command }) instead of prose.
4486
- NOTE: --json is a report-only snapshot; it never spawns an upgrade
4487
- even when combined with --run. Use --run without --json to
4488
- actually perform the upgrade.`;
4489
- function parseUpgradeArgs(argv) {
4490
- const opts = {};
4491
- for (const a of argv) {
4492
- if (a === "--run") opts.run = true;
4493
- else if (a === "--json") opts.json = true;
4494
- else if (a === "--help" || a === "-h") return { ok: false, error: UPGRADE_USAGE, help: true };
4495
- else return { ok: false, error: `yaw-mcp upgrade: unknown argument "${a}"
4496
-
4497
- ${UPGRADE_USAGE}` };
4498
- }
4499
- return { ok: true, options: opts };
4500
- }
4501
- function detectInstallMethod(argvPath) {
4502
- if (!argvPath) return "unknown";
4503
- const normalized = argvPath.replace(/\\/g, "/");
4504
- if (/\/_npx\/[0-9a-f]+\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "npx";
4505
- if (/\/app\.asar\.unpacked\//.test(normalized)) return "bundled-app";
4506
- if (/\/npm\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
4507
- if (POSIX_GLOBAL_LIB_PREFIX.test(normalized)) return "global-npm";
4508
- if (MANAGED_NODE_LIB_PREFIX.test(normalized)) return "global-npm";
4509
- if (/\/AppData\/Roaming\/npm\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
4510
- if (/\/bin\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
4511
- if (/\/pnpm\/global\/\d+\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "pnpm-global";
4512
- if (/\/\.bun\/install\/global\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "bun-global";
4513
- if (/\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "local-node-modules";
4514
- if (/\/(yaw-mcp|mcph)\/(dist|src)\//.test(normalized)) return "dev-checkout";
4515
- return "unknown";
4516
- }
4517
- function localInstallRoot(argvPath) {
4518
- if (!argvPath) return null;
4519
- const idx = argvPath.replace(/\\/g, "/").indexOf("/node_modules/");
4520
- return idx > 0 ? argvPath.slice(0, idx) : null;
4521
- }
4522
- async function npmGlobalPrefix() {
4523
- if (process.env.VITEST) return null;
4524
- return new Promise((resolve8) => {
4525
- const child = spawn3("npm", ["prefix", "-g"], {
4526
- shell: process.platform === "win32",
4527
- stdio: ["ignore", "pipe", "ignore"]
4528
- });
4529
- let out = "";
4530
- const timer = setTimeout(() => {
4531
- child.kill();
4532
- resolve8(null);
4533
- }, 3e3);
4534
- child.stdout?.on("data", (d) => {
4535
- out += String(d);
4536
- });
4537
- child.on("close", (code) => {
4538
- clearTimeout(timer);
4539
- resolve8(code === 0 && out.trim() ? out.trim() : null);
4540
- });
4541
- child.on("error", () => {
4542
- clearTimeout(timer);
4543
- resolve8(null);
4544
- });
4545
- });
4546
- }
4547
- function comparablePath(p) {
4548
- let real = p;
4549
- try {
4550
- real = realpathSync(p);
4551
- } catch {
4552
- }
4553
- const normalized = real.replace(/\\/g, "/");
4554
- return process.platform === "win32" ? normalized.toLowerCase() : normalized;
4555
- }
4556
- async function refineInstallMethod(method, argvPath, npmPrefix = npmGlobalPrefix) {
4557
- if (method !== "local-node-modules" && method !== "unknown") return method;
4558
- if (!argvPath) return method;
4559
- const prefix = await npmPrefix();
4560
- if (!prefix) return method;
4561
- const entry = comparablePath(argvPath);
4562
- const pfx = comparablePath(prefix);
4563
- if (entry.startsWith(`${pfx}/node_modules/`) || entry.startsWith(`${pfx}/lib/node_modules/`)) {
4564
- return "global-npm";
4565
- }
4566
- return method;
4567
- }
4568
- function buildUpgradePlan(input) {
4569
- const { current, latest, method } = input;
4570
- const stale = latest !== null && current !== "dev" && compareSemverLocal(current, latest) < 0;
4571
- let command;
4572
- switch (method) {
4573
- case "global-npm":
4574
- command = "npm install -g @yawlabs/mcp@latest";
4575
- break;
4576
- case "pnpm-global":
4577
- command = "pnpm add -g @yawlabs/mcp@latest";
4578
- break;
4579
- case "bun-global":
4580
- command = "bun add -g @yawlabs/mcp@latest";
4581
- break;
4582
- case "npx":
4583
- command = null;
4584
- break;
4585
- case "bundled-app":
4586
- command = null;
4587
- break;
4588
- case "local-node-modules":
4589
- command = "npm install @yawlabs/mcp@latest";
4590
- break;
4591
- case "dev-checkout":
4592
- command = "git pull && npm run build";
4593
- break;
4594
- case "binary":
4595
- command = null;
4596
- break;
4597
- default:
4598
- command = "npm install -g @yawlabs/mcp@latest";
4599
- break;
4600
- }
4601
- return { current, latest, stale, method, command };
4602
- }
4603
- function compareSemverLocal(a, b) {
4604
- const parse = (s) => {
4605
- const cleaned = s.replace(/\+.*$/, "");
4606
- const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(cleaned);
4607
- if (!m) return null;
4608
- const release = [Number(m[1]), Number(m[2]), Number(m[3])];
4609
- const prerelease = m[4] ? m[4].split(".") : [];
4610
- return { release, prerelease };
4611
- };
4612
- const pa = parse(a);
4613
- const pb = parse(b);
4614
- if (!pa || !pb) return 0;
4615
- for (let i = 0; i < 3; i++) {
4616
- if (pa.release[i] < pb.release[i]) return -1;
4617
- if (pa.release[i] > pb.release[i]) return 1;
4618
- }
4619
- if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0;
4620
- if (pa.prerelease.length === 0) return 1;
4621
- if (pb.prerelease.length === 0) return -1;
4622
- const len = Math.min(pa.prerelease.length, pb.prerelease.length);
4623
- for (let i = 0; i < len; i++) {
4624
- const ai = pa.prerelease[i];
4625
- const bi = pb.prerelease[i];
4626
- const aNum = /^\d+$/.test(ai);
4627
- const bNum = /^\d+$/.test(bi);
4628
- if (aNum && bNum) {
4629
- const na = Number(ai);
4630
- const nb = Number(bi);
4631
- if (na < nb) return -1;
4632
- if (na > nb) return 1;
4633
- } else if (aNum !== bNum) {
4634
- return aNum ? -1 : 1;
4635
- } else {
4636
- if (ai < bi) return -1;
4637
- if (ai > bi) return 1;
4638
- }
4639
- }
4640
- if (pa.prerelease.length < pb.prerelease.length) return -1;
4641
- if (pa.prerelease.length > pb.prerelease.length) return 1;
4642
- return 0;
4643
- }
4644
- var REGISTRY_FETCH_TIMEOUT_MS = 3e3;
4645
- async function fetchLatestVersion(opts = {}) {
4646
- if (opts.override) {
4647
- try {
4648
- return await opts.override();
4649
- } catch {
4650
- return null;
4651
- }
4652
- }
4653
- const ac = new AbortController();
4654
- const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? REGISTRY_FETCH_TIMEOUT_MS);
4655
- try {
4656
- const res = await fetch("https://registry.npmjs.org/@yawlabs/mcp/latest", {
4657
- signal: ac.signal,
4658
- headers: { accept: "application/json" }
4659
- });
4660
- if (!res.ok) return null;
4661
- const body = await res.json();
4662
- return typeof body.version === "string" ? body.version : null;
4663
- } catch {
4664
- return null;
4665
- } finally {
4666
- clearTimeout(timer);
4667
- }
4668
- }
4669
- async function oamFloorLines(probe) {
4670
- if (!probe && process.env.VITEST) return [];
4671
- try {
4672
- const { MIN_OAM_VERSION: MIN_OAM_VERSION2, probeOam: probeOam2 } = await import("./oam-spawn-Z5CASEBY.js");
4673
- const oam = probe ? await probe() : await probeOam2();
4674
- if (!oam.belowMin) return [];
4675
- return [
4676
- "",
4677
- `oam: v${oam.version ?? "unknown"} is installed but below the v${MIN_OAM_VERSION2} floor yaw-mcp`,
4678
- " requires, so MCP sidecars run on node instead of oam. Update it:",
4679
- "",
4680
- " oam self-update"
4681
- ];
4682
- } catch {
4683
- return [];
4684
- }
4685
- }
4686
- async function defaultSpawn(cmd, args, cwd) {
4687
- return new Promise((resolve8) => {
4688
- const child = spawn3(cmd, args, { stdio: "inherit", shell: process.platform === "win32", cwd });
4689
- child.on("close", (code) => resolve8(typeof code === "number" ? code : 1));
4690
- child.on("error", () => resolve8(1));
4691
- });
4692
- }
4693
- async function detectSea() {
4694
- if (process.env.ELECTRON_RUN_AS_NODE) return false;
4695
- const exe = process.execPath.replace(/\\/g, "/").split("/").pop()?.toLowerCase() ?? "";
4696
- if (exe === "node" || exe === "node.exe") return false;
4697
- try {
4698
- const sea = await import("sea");
4699
- return typeof sea.isSea === "function" && sea.isSea() === true;
4700
- } catch {
4701
- return false;
4702
- }
4703
- }
4704
- async function runUpgrade(opts = {}) {
4705
- const write = opts.out ?? ((s) => process.stdout.write(s));
4706
- const writeErr = opts.err ?? ((s) => process.stderr.write(s));
4707
- const lines = [];
4708
- const print = (s = "") => {
4709
- lines.push(s);
4710
- write(`${s}
4711
- `);
4712
- };
4713
- const printErr = (s) => {
4714
- lines.push(s);
4715
- writeErr(`${s}
4716
- `);
4717
- };
4718
- const fetcher = opts.fetchLatest ?? fetchLatestVersion;
4719
- const current = opts.currentVersion ?? readCurrentVersion();
4720
- const argvPath = opts.argvPath ?? process.argv[1];
4721
- const sea = opts.isSea ? opts.isSea() : await detectSea();
4722
- const method = sea ? "binary" : await refineInstallMethod(detectInstallMethod(argvPath), argvPath, opts.npmPrefix);
4723
- let latest;
4724
- try {
4725
- latest = await fetcher();
4726
- } catch {
4727
- latest = null;
4728
- }
4729
- const plan = buildUpgradePlan({ current, latest, method });
4730
- if (opts.json) {
4731
- print(JSON.stringify(plan, null, 2));
4732
- return { exitCode: plan.stale && !opts.run ? 1 : 0, lines };
4733
- }
4734
- if (latest === null) {
4735
- print("yaw-mcp upgrade: couldn't reach the npm registry (offline? firewall?).");
4736
- if (plan.command) {
4737
- print("When you're back online, run:");
4738
- print("");
4739
- print(` ${plan.command}`);
4740
- } else if (method === "bundled-app") {
4741
- print("This copy of yaw-mcp ships inside Yaw Terminal and updates with the app \u2014 nothing to run.");
4742
- } else if (method === "binary") {
4743
- print("yaw-mcp is a standalone binary \u2014 download the latest build and replace");
4744
- print(`this executable: ${BINARY_DOWNLOAD_URL}`);
4745
- } else {
4746
- print("Your install uses `npx -y` \u2014 just restart the MCP client when you're back online.");
4747
- }
4748
- return { exitCode: 0, lines };
4749
- }
4750
- print(`Current: ${current}`);
4751
- print(`Latest: ${latest}`);
4752
- print(`Install: ${method}`);
4753
- for (const line of await oamFloorLines(opts.oamProbe)) print(line);
4754
- if (!plan.stale) {
4755
- print("");
4756
- print("OK: You're on the latest version -- nothing to do.");
4757
- return { exitCode: 0, lines };
4758
- }
4759
- print("");
4760
- if (method === "npx") {
4761
- print("Your install uses `npx -y` \u2014 restart the MCP client and it will fetch the new version.");
4762
- return { exitCode: 0, lines };
4763
- }
4764
- if (method === "bundled-app") {
4765
- print("This copy of yaw-mcp ships inside Yaw Terminal and updates with the app \u2014");
4766
- print("there is nothing to run here. Update Yaw Terminal to get the new version.");
4767
- return { exitCode: 0, lines };
4768
- }
4769
- if (method === "binary") {
4770
- print("yaw-mcp is running as a standalone binary \u2014 manual upgrade required.");
4771
- print("There's no package manager to upgrade it, and `--run` can't automate");
4772
- print("this: download the latest build and replace this executable:");
4773
- print("");
4774
- print(` ${BINARY_DOWNLOAD_URL}`);
4775
- return { exitCode: opts.run ? 2 : 1, lines };
4776
- }
4777
- const installRoot = method === "local-node-modules" ? localInstallRoot(argvPath) : null;
4778
- const runSpec = method === "global-npm" ? { cmd: "npm", args: ["install", "-g", "@yawlabs/mcp@latest"] } : method === "pnpm-global" ? { cmd: "pnpm", args: ["add", "-g", "@yawlabs/mcp@latest"] } : method === "bun-global" ? { cmd: "bun", args: ["add", "-g", "@yawlabs/mcp@latest"] } : method === "local-node-modules" && installRoot !== null ? { cmd: "npm", args: ["install", "@yawlabs/mcp@latest"], cwd: installRoot } : null;
4779
- if (!opts.run) {
4780
- if (runSpec) {
4781
- print("Run `yaw-mcp upgrade --run` to upgrade in place, or run it yourself:");
4782
- } else {
4783
- print("Manual upgrade required (--run can't safely automate this install method). Run it yourself:");
4784
- }
4785
- print("");
4786
- if (installRoot) {
4787
- print(`in ${installRoot}:`);
4788
- }
4789
- print(` ${plan.command}`);
4790
- return { exitCode: 1, lines };
4791
- }
4792
- if (!runSpec) {
4793
- printErr(
4794
- `yaw-mcp upgrade --run: a "${method}" install can't be upgraded automatically (manual upgrade required). Run it yourself:`
4795
- );
4796
- printErr("");
4797
- printErr(` ${plan.command}`);
4798
- return { exitCode: 2, lines };
4799
- }
4800
- const runner = opts.spawnImpl ?? defaultSpawn;
4801
- if (runSpec.cwd) {
4802
- print(`Running in ${runSpec.cwd}:`);
4803
- } else {
4804
- print("Running:");
4805
- }
4806
- print(` ${plan.command}`);
4807
- print("");
4808
- const code = await runner(runSpec.cmd, runSpec.args, runSpec.cwd);
4809
- if (code === 0) {
4810
- print("");
4811
- print(`OK: Upgraded @yawlabs/mcp to ${latest}`);
4812
- return { exitCode: 0, lines };
4813
- }
4814
- printErr(`yaw-mcp upgrade: ${runSpec.cmd} exited ${code}. Try running the command yourself:`);
4815
- printErr("");
4816
- printErr(` ${plan.command}`);
4817
- return { exitCode: 3, lines };
4818
- }
4819
- function readCurrentVersion() {
4820
- return true ? "0.75.4" : "dev";
4821
- }
4822
-
4823
4391
  // src/learning.ts
4824
4392
  var LEARNING_MIN_OBSERVATIONS = 3;
4825
4393
  var LEARNING_MAX_BOOST = 1.1;
@@ -5051,7 +4619,7 @@ function foldBundleWarnings(warnings, probe) {
5051
4619
  const prefix = `${probe.path}:`;
5052
4620
  return warnings.filter((w) => !w.startsWith(prefix));
5053
4621
  }
5054
- var VERSION = true ? "0.75.4" : "dev";
4622
+ var VERSION = true ? "0.76.1" : "dev";
5055
4623
  async function runDoctor(opts = {}) {
5056
4624
  if (opts.json) return runDoctorJson(opts);
5057
4625
  const lines = [];
@@ -5062,7 +4630,7 @@ async function runDoctor(opts = {}) {
5062
4630
  `);
5063
4631
  };
5064
4632
  const cwd = opts.cwd ?? process.cwd();
5065
- const home = opts.home ?? homedir10();
4633
+ const home = opts.home ?? homedir9();
5066
4634
  const os = opts.os ?? CURRENT_OS;
5067
4635
  const env = opts.env ?? process.env;
5068
4636
  print(`yaw-mcp doctor \u2014 ${(/* @__PURE__ */ new Date()).toISOString()}`);
@@ -5085,7 +4653,13 @@ async function runDoctor(opts = {}) {
5085
4653
  const projectGuide = await loadProjectGuide(cwd, home, env).catch(() => null);
5086
4654
  renderProjectGuideSection({ guide: projectGuide, print });
5087
4655
  renderEnvSection({ env, print });
5088
- const oamStatus = await collectOamRuntimeStatus({ env, cwd, home, probeFn: opts.oamProbe ?? probeOam });
4656
+ const oamStatus = await collectOamRuntimeStatus({
4657
+ env,
4658
+ cwd,
4659
+ home,
4660
+ probeFn: opts.oamProbe ?? probeOam,
4661
+ sidecarLatest: sidecarLatestFetcher(opts)
4662
+ });
5089
4663
  config.warnings = [...config.warnings, ...foldBundleWarnings(oamStatus.bundleWarnings, trustProbe)];
5090
4664
  renderOamRuntimeSection({ status: oamStatus, print, os });
5091
4665
  const persistenceDisabled = isPersistenceDisabled(env);
@@ -5180,7 +4754,7 @@ async function runDoctorJson(opts) {
5180
4754
  const lines = [];
5181
4755
  const write = opts.out ?? ((s) => process.stdout.write(s));
5182
4756
  const cwd = opts.cwd ?? process.cwd();
5183
- const home = opts.home ?? homedir10();
4757
+ const home = opts.home ?? homedir9();
5184
4758
  const os = opts.os ?? CURRENT_OS;
5185
4759
  const env = opts.env ?? process.env;
5186
4760
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
@@ -5281,7 +4855,13 @@ async function runDoctorJson(opts) {
5281
4855
  })),
5282
4856
  malformed: trialScan.malformed
5283
4857
  };
5284
- const oamStatus = await collectOamRuntimeStatus({ env, cwd, home, probeFn: opts.oamProbe ?? probeOam });
4858
+ const oamStatus = await collectOamRuntimeStatus({
4859
+ env,
4860
+ cwd,
4861
+ home,
4862
+ probeFn: opts.oamProbe ?? probeOam,
4863
+ sidecarLatest: sidecarLatestFetcher(opts)
4864
+ });
5285
4865
  config.warnings = [...config.warnings, ...foldBundleWarnings(oamStatus.bundleWarnings, trustProbe)];
5286
4866
  const oamRuntime = {
5287
4867
  binary: oamStatus.probe.bin,
@@ -5375,6 +4955,27 @@ function renderEnvSection(opts) {
5375
4955
  }
5376
4956
  print("");
5377
4957
  }
4958
+ async function fetchSidecarLatest(pkg) {
4959
+ const ac = new AbortController();
4960
+ const timer = setTimeout(() => ac.abort(), DOCTOR_REGISTRY_TIMEOUT_MS);
4961
+ try {
4962
+ const res = await fetch(`https://registry.npmjs.org/${pkg}/latest`, {
4963
+ signal: ac.signal,
4964
+ headers: { accept: "application/json" }
4965
+ });
4966
+ if (!res.ok) return null;
4967
+ const body = await res.json();
4968
+ return typeof body.version === "string" ? body.version : null;
4969
+ } catch {
4970
+ return null;
4971
+ } finally {
4972
+ clearTimeout(timer);
4973
+ }
4974
+ }
4975
+ function sidecarLatestFetcher(opts) {
4976
+ const skip = (opts.skipRegistryCheck === true || Boolean(process.env.VITEST)) && !opts.sidecarRegistryFetch;
4977
+ return skip ? null : opts.sidecarRegistryFetch ?? fetchSidecarLatest;
4978
+ }
5378
4979
  async function collectOamRuntimeStatus(opts) {
5379
4980
  const probe = await opts.probeFn();
5380
4981
  const bundles = await loadLocalBundles({ cwd: opts.cwd, home: opts.home, env: opts.env }).catch(() => null);
@@ -5386,9 +4987,20 @@ async function collectOamRuntimeStatus(opts) {
5386
4987
  }));
5387
4988
  const specs = collectSidecarSpecs(bundles?.config?.servers ?? []);
5388
4989
  const anyManaged = hasManagedSidecars(opts.home);
4990
+ const packages = await Promise.all(
4991
+ specs.map(async (s) => {
4992
+ const version = anyManaged ? installedVersion(s.pkg, opts.home) : null;
4993
+ const latest = version !== null && opts.sidecarLatest !== null ? await opts.sidecarLatest(s.pkg) : null;
4994
+ const stale = version !== null && latest !== null && compareSemver(version, latest) < 0;
4995
+ return { pkg: s.pkg, version, latest, stale };
4996
+ })
4997
+ );
4998
+ const installedFor = anyManaged ? installedPlatform(opts.home) : null;
5389
4999
  const managed = {
5390
5000
  root: sidecarsRoot(opts.home),
5391
- packages: specs.map((s) => ({ pkg: s.pkg, version: anyManaged ? installedVersion(s.pkg, opts.home) : null }))
5001
+ packages,
5002
+ installedFor,
5003
+ platformMismatch: installedFor !== null && (installedFor.platform !== process.platform || installedFor.arch !== process.arch)
5392
5004
  };
5393
5005
  return { probe, dflt, servers, managed, bundleWarnings: bundles?.warnings ?? [] };
5394
5006
  }
@@ -5405,7 +5017,7 @@ function renderOamRuntimeSection(opts) {
5405
5017
  print(" fix: run `oam --version` by hand; OAM_BIN overrides which binary is probed");
5406
5018
  } else if (probe.bin === null) {
5407
5019
  print(" binary: not installed \u2014 node/npx spawns are used directly");
5408
- print(` install: ${oamInstallCommand(opts.os)}`);
5020
+ print(` install: ${oamInstallAdvice(opts.os)}`);
5409
5021
  } else if (probe.version === null) {
5410
5022
  print(` binary: ${probe.bin} (version unparseable -- min ${MIN_OAM_VERSION} NOT verified, hosting anyway)`);
5411
5023
  } else {
@@ -5437,7 +5049,15 @@ function renderOamRuntimeSection(opts) {
5437
5049
  if (anyInstalled) {
5438
5050
  const widest = managed.packages.reduce((m, p) => Math.max(m, p.pkg.length), 0);
5439
5051
  for (const p of managed.packages) {
5440
- print(` ${p.pkg.padEnd(widest)} ${p.version ?? "not in the managed tree"}`);
5052
+ const staleNote = p.stale && p.latest !== null ? ` (latest ${p.latest} -- re-run \`yaw-mcp sidecars install\`)` : "";
5053
+ print(` ${p.pkg.padEnd(widest)} ${p.version ?? "not in the managed tree"}${staleNote}`);
5054
+ }
5055
+ if (managed.platformMismatch && managed.installedFor !== null) {
5056
+ print(
5057
+ ` ! installed on ${managed.installedFor.platform}/${managed.installedFor.arch}; this process is ${process.platform}/${process.arch}.`
5058
+ );
5059
+ print(" Native bindings resolve for the installing machine, so these packages can fail");
5060
+ print(" at spawn here -- re-run `yaw-mcp sidecars install` on this machine.");
5441
5061
  }
5442
5062
  }
5443
5063
  }
@@ -5489,7 +5109,7 @@ function renderStateSection(opts) {
5489
5109
  async function peekStateFile(filePath) {
5490
5110
  let raw;
5491
5111
  try {
5492
- raw = await readFile9(filePath, "utf8");
5112
+ raw = await readFile10(filePath, "utf8");
5493
5113
  } catch (err) {
5494
5114
  if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") {
5495
5115
  return { kind: "missing" };
@@ -5758,14 +5378,14 @@ function classifyProbeContent(raw, containerPath, exists3 = existsSync6) {
5758
5378
  if (typeof entry === "object" && entry !== null && !Array.isArray(entry)) {
5759
5379
  const command = entry.command;
5760
5380
  if (typeof command === "string") {
5761
- if (isAbsolute3(command) && !exists3(command)) launchCommandMissing = command;
5381
+ if (isAbsolute(command) && !exists3(command)) launchCommandMissing = command;
5762
5382
  const entryArgs = entry.args;
5763
5383
  const args = Array.isArray(entryArgs) ? entryArgs : [];
5764
5384
  launchRuntime = isOamLaunch(command, args) ? "oam" : "node";
5765
- if (isOamCommand(command) && !isAbsolute3(command)) launchOamNotAbsolute = command;
5385
+ if (isOamCommand(command) && !isAbsolute(command)) launchOamNotAbsolute = command;
5766
5386
  if (launchRuntime === "oam") {
5767
5387
  const entryPath = oamRunEntryPath(command, args);
5768
- if (entryPath !== null && isAbsolute3(entryPath) && !exists3(entryPath)) {
5388
+ if (entryPath !== null && isAbsolute(entryPath) && !exists3(entryPath)) {
5769
5389
  launchOamEntryMissing = entryPath;
5770
5390
  }
5771
5391
  }
@@ -5799,7 +5419,7 @@ async function probeClientsAsync(opts) {
5799
5419
  for (const { result, read } of enumerateProbeSlots(opts)) {
5800
5420
  if (read) {
5801
5421
  try {
5802
- Object.assign(result, classifyProbeContent(await readFile9(read.path, "utf8"), read.containerPath));
5422
+ Object.assign(result, classifyProbeContent(await readFile10(read.path, "utf8"), read.containerPath));
5803
5423
  } catch {
5804
5424
  Object.assign(result, MALFORMED);
5805
5425
  }
@@ -5914,12 +5534,12 @@ function compareSemver(a, b) {
5914
5534
 
5915
5535
  // src/foundry-cmd.ts
5916
5536
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync } from "fs";
5917
- import { homedir as homedir12 } from "os";
5537
+ import { homedir as homedir11 } from "os";
5918
5538
  import path4 from "path";
5919
5539
 
5920
5540
  // src/foundry.ts
5921
5541
  import { appendFile, mkdir as mkdir4, stat as stat3 } from "fs/promises";
5922
- import { homedir as homedir11 } from "os";
5542
+ import { homedir as homedir10 } from "os";
5923
5543
  import path3 from "path";
5924
5544
 
5925
5545
  // src/relevance.ts
@@ -6182,7 +5802,7 @@ function redactIntent(intent) {
6182
5802
  return " ";
6183
5803
  });
6184
5804
  }
6185
- const all = tokenize(scrubbed);
5805
+ const all = tokenizeQuery(scrubbed);
6186
5806
  const tokens = [];
6187
5807
  for (const token of all) {
6188
5808
  if (looksSensitive(token)) {
@@ -6202,7 +5822,7 @@ function isFoundryEnabled() {
6202
5822
  }
6203
5823
  var MAX_FOUNDRY_BYTES = 5 * 1024 * 1024;
6204
5824
  var FOUNDRY_FILENAME = "foundry.jsonl";
6205
- async function appendFoundryTrace(trace, home = homedir11()) {
5825
+ async function appendFoundryTrace(trace, home = homedir10()) {
6206
5826
  try {
6207
5827
  if (!isFoundryEnabled()) return;
6208
5828
  const dir = userConfigDir(home);
@@ -6386,7 +6006,7 @@ async function runFoundryExport(opts) {
6386
6006
  writeErr(`${s}
6387
6007
  `);
6388
6008
  };
6389
- const home = opts.home ?? homedir12();
6009
+ const home = opts.home ?? homedir11();
6390
6010
  const harvestPath = path4.join(userConfigDir(home), FOUNDRY_FILENAME);
6391
6011
  const blob = opts.readTraces ? opts.readTraces() : (() => {
6392
6012
  try {
@@ -6441,14 +6061,14 @@ async function runFoundryExport(opts) {
6441
6061
  }
6442
6062
 
6443
6063
  // src/local-add-cmd.ts
6444
- import { readFile as readFile11 } from "fs/promises";
6445
- import { homedir as homedir14 } from "os";
6064
+ import { readFile as readFile12 } from "fs/promises";
6065
+ import { homedir as homedir13 } from "os";
6446
6066
  import { createInterface as createInterface3 } from "readline/promises";
6447
6067
 
6448
6068
  // src/trust-cmd.ts
6449
- import { readFile as readFile10 } from "fs/promises";
6450
- import { homedir as homedir13 } from "os";
6451
- import { isAbsolute as isAbsolute4, resolve as resolve7 } from "path";
6069
+ import { readFile as readFile11 } from "fs/promises";
6070
+ import { homedir as homedir12 } from "os";
6071
+ import { isAbsolute as isAbsolute2, resolve as resolve6 } from "path";
6452
6072
  import { createInterface as createInterface2 } from "readline/promises";
6453
6073
  var TRUST_USAGE = `Usage: yaw-mcp trust [--yes]
6454
6074
  yaw-mcp trust --list [--json]
@@ -6548,7 +6168,7 @@ async function runTrustGrant(opts) {
6548
6168
  `);
6549
6169
  const printErr = (s) => err(`${s}
6550
6170
  `);
6551
- const home = opts.home ?? homedir13();
6171
+ const home = opts.home ?? homedir12();
6552
6172
  const cwd = opts.cwd ?? process.cwd();
6553
6173
  const env = opts.env ?? process.env;
6554
6174
  const probe = await probeProjectTrust({ cwd, home, env });
@@ -6586,6 +6206,11 @@ async function runTrustGrant(opts) {
6586
6206
  ` Status: ${probe.status === "changed" ? "CHANGED since you approved it" : probe.status === "store-unreadable" ? `trust store unreadable (${displaySafe(probe.storePath)})` : "never approved"}`
6587
6207
  );
6588
6208
  print(` Servers: ${serverCount}`);
6209
+ if (probe.bypassed) {
6210
+ print(
6211
+ ` ! ${TRUST_BYPASS_ENV} is set: this file (like every project bundles.json) loads WITHOUT approval right now. This approval takes effect once it is unset.`
6212
+ );
6213
+ }
6589
6214
  print("");
6590
6215
  if (serverCount === 0) {
6591
6216
  print(" This file defines no servers, so approving it spawns nothing. It");
@@ -6624,7 +6249,7 @@ async function runTrustGrant(opts) {
6624
6249
  }
6625
6250
  let confirmBytes;
6626
6251
  try {
6627
- confirmBytes = await readFile10(path6);
6252
+ confirmBytes = await readFile11(path6);
6628
6253
  } catch (e) {
6629
6254
  printErr(
6630
6255
  `yaw-mcp trust: ${displaySafe(path6)} could not be re-read before approving (${e.message}). Nothing approved.`
@@ -6671,7 +6296,13 @@ async function runTrustGrant(opts) {
6671
6296
  print(" NOT PINNED: the code those commands actually run. Files inside this repo and");
6672
6297
  print(" packages fetched at spawn time can change with no edit to bundles.json, and so");
6673
6298
  print(" with no new prompt. Approving is trusting the repo, not just this one file.");
6674
- print("Restart your MCP client (or yaw-mcp) to load it.");
6299
+ if (probe.bypassed) {
6300
+ print(
6301
+ `NOTE: ${TRUST_BYPASS_ENV} is set, so this file was ALREADY loading without approval. This approval takes effect once the variable is unset.`
6302
+ );
6303
+ } else {
6304
+ print("Restart your MCP client (or yaw-mcp) to load it.");
6305
+ }
6675
6306
  return { exitCode: 0 };
6676
6307
  }
6677
6308
  function renderLaunch(s) {
@@ -6695,7 +6326,7 @@ function displayArg(s) {
6695
6326
  var SCRIPT_EXT_RE = /\.(?:js|mjs|cjs|ts|mts|cts|py|rb|sh|bash|zsh|pl|php|lua|jar|bat|cmd|ps1|exe)$/i;
6696
6327
  function inRepoTokens(s) {
6697
6328
  const hits = [];
6698
- const isLocalish = (t) => t.length > 0 && !/\s/.test(t) && !isAbsolute4(t) && !t.includes("://") && !t.startsWith("-");
6329
+ const isLocalish = (t) => t.length > 0 && !/\s/.test(t) && !isAbsolute2(t) && !t.includes("://") && !t.startsWith("-");
6699
6330
  const command = s.command ?? "";
6700
6331
  if (isLocalish(command) && (/^\.{1,2}[\\/]/.test(command) || /[\\/]/.test(command))) hits.push(command);
6701
6332
  for (const a of s.args ?? []) {
@@ -6723,6 +6354,13 @@ var VALUELESS_RUNNER_FLAGS = /* @__PURE__ */ new Set([
6723
6354
  "--no-install",
6724
6355
  "--ignore-existing"
6725
6356
  ]);
6357
+ function stripVersionPrefixV(spec) {
6358
+ const start = spec.startsWith("@") ? 1 : 0;
6359
+ const at = spec.indexOf("@", start);
6360
+ if (at === -1) return spec;
6361
+ const suffix = spec.slice(at + 1);
6362
+ return /^v\d/.test(suffix) ? spec.slice(0, at + 1) + suffix.slice(1) : spec;
6363
+ }
6726
6364
  function unversionedRegistrySpec(s) {
6727
6365
  const base = (s.command ?? "").split(/[\\/]/).pop()?.replace(/\.(?:exe|cmd|bat)$/i, "") ?? "";
6728
6366
  const runner = REGISTRY_RUNNERS.find((r) => r.cmd === base);
@@ -6742,10 +6380,9 @@ function unversionedRegistrySpec(s) {
6742
6380
  break;
6743
6381
  }
6744
6382
  if (spec === null || spec.length === 0) return null;
6745
- if (spec.includes("://") || isAbsolute4(spec) || /^\.{1,2}[\\/]/.test(spec)) return null;
6746
- const body = spec.startsWith("@") ? spec.slice(1) : spec;
6747
- const afterScope = body.includes("/") ? body.slice(body.indexOf("/") + 1) : body;
6748
- if (afterScope.includes("@") || afterScope.includes("==")) return null;
6383
+ if (spec.includes("://") || isAbsolute2(spec) || /^\.{1,2}[\\/]/.test(spec)) return null;
6384
+ if (spec.includes("==")) return null;
6385
+ if (specConstraint(stripVersionPrefixV(spec)).kind === "exact") return null;
6749
6386
  return spec;
6750
6387
  }
6751
6388
  function pinGaps(s) {
@@ -6760,7 +6397,7 @@ function pinGaps(s) {
6760
6397
  const spec = unversionedRegistrySpec(s);
6761
6398
  if (spec !== null) {
6762
6399
  lines.push(
6763
- `NOT covered by the pin: ${displayArg(spec)} has no version -- it resolves to whatever the registry serves at spawn time.`
6400
+ `NOT covered by the pin: ${displayArg(spec)} is not pinned to an exact version -- it resolves to whatever the registry serves at spawn time.`
6764
6401
  );
6765
6402
  }
6766
6403
  return lines;
@@ -6770,14 +6407,22 @@ async function runTrustList(opts) {
6770
6407
  const err = opts.err ?? ((s) => process.stderr.write(s));
6771
6408
  const print = (s = "") => out(`${s}
6772
6409
  `);
6773
- const home = opts.home ?? homedir13();
6410
+ const home = opts.home ?? homedir12();
6411
+ const env = opts.env ?? process.env;
6412
+ const bypassed = isTrustBypassEnabled(env);
6413
+ if (bypassed && !opts.json) {
6414
+ err(
6415
+ `yaw-mcp trust: warning -- ${TRUST_BYPASS_ENV} is set, so EVERY project bundles.json loads WITHOUT approval right now, regardless of what is listed here. Unset it to restore the approval gate.
6416
+ `
6417
+ );
6418
+ }
6774
6419
  const store = await readTrustStore(home);
6775
6420
  if (store.malformed) {
6776
6421
  const fix = store.malformedKind === "io" ? "fix its permissions (do NOT delete it -- your approvals are still in there)" : store.malformedKind === "schema" ? "you upgrade with `npm i -g @yawlabs/mcp@latest` (do NOT delete it -- your approvals are still in there)" : "it is fixed or deleted";
6777
6422
  const msg = `trust store unusable: ${store.malformedReason ?? "unknown"} -- NOTHING is trusted until ${fix}`;
6778
6423
  if (opts.json) {
6779
6424
  out(
6780
- `${JSON.stringify({ storePath: trustStorePath(home), malformed: true, error: msg, trusted: [] }, null, 2)}
6425
+ `${JSON.stringify({ storePath: trustStorePath(home), malformed: true, bypassed, error: msg, trusted: [] }, null, 2)}
6781
6426
  `
6782
6427
  );
6783
6428
  } else {
@@ -6792,7 +6437,7 @@ async function runTrustList(opts) {
6792
6437
  rows.push({ ...r, status: await classifyRecord(r.path, r.sha256) });
6793
6438
  }
6794
6439
  if (opts.json) {
6795
- out(`${JSON.stringify({ storePath: trustStorePath(home), malformed: false, trusted: rows }, null, 2)}
6440
+ out(`${JSON.stringify({ storePath: trustStorePath(home), malformed: false, bypassed, trusted: rows }, null, 2)}
6796
6441
  `);
6797
6442
  return { exitCode: 0 };
6798
6443
  }
@@ -6825,7 +6470,7 @@ async function runTrustList(opts) {
6825
6470
  }
6826
6471
  async function classifyRecord(path6, sha256) {
6827
6472
  try {
6828
- const raw = await readFile10(path6);
6473
+ const raw = await readFile11(path6);
6829
6474
  return hashTrustContent(raw) === sha256 ? "ok" : "stale (content changed)";
6830
6475
  } catch (e) {
6831
6476
  const code = e.code;
@@ -6839,12 +6484,12 @@ async function runTrustRevoke(opts) {
6839
6484
  `);
6840
6485
  const printErr = (s) => err(`${s}
6841
6486
  `);
6842
- const home = opts.home ?? homedir13();
6487
+ const home = opts.home ?? homedir12();
6843
6488
  const cwd = opts.cwd ?? process.cwd();
6844
6489
  const env = opts.env ?? process.env;
6845
6490
  let target;
6846
6491
  if (opts.path) {
6847
- target = resolve7(cwd, opts.path);
6492
+ target = resolve6(cwd, opts.path);
6848
6493
  } else {
6849
6494
  const probe = await probeProjectTrust({ cwd, home, env });
6850
6495
  if (probe.path === null) {
@@ -6987,7 +6632,7 @@ async function runAdd(opts) {
6987
6632
  return { exitCode: 2, written: [] };
6988
6633
  }
6989
6634
  const env = opts.env ?? process.env;
6990
- const home = opts.home ?? homedir14();
6635
+ const home = opts.home ?? homedir13();
6991
6636
  const cwd = opts.cwd ?? process.cwd();
6992
6637
  let server;
6993
6638
  try {
@@ -7022,6 +6667,7 @@ async function runAdd(opts) {
7022
6667
  id: `local-${namespace}`,
7023
6668
  name: server.name,
7024
6669
  namespace,
6670
+ slug: server.slug,
7025
6671
  type: "local",
7026
6672
  transport: "stdio",
7027
6673
  command: server.command,
@@ -7121,7 +6767,7 @@ async function findRemovalTarget(candidates, home) {
7121
6767
  const path6 = localBundlesPath(userConfigDir(home));
7122
6768
  let raw;
7123
6769
  try {
7124
- raw = await readFile11(path6, "utf8");
6770
+ raw = await readFile12(path6, "utf8");
7125
6771
  } catch {
7126
6772
  return null;
7127
6773
  }
@@ -7143,6 +6789,30 @@ async function findRemovalTarget(candidates, home) {
7143
6789
  }
7144
6790
  return null;
7145
6791
  }
6792
+ async function namespacesForStoredSlug(target, home) {
6793
+ const path6 = localBundlesPath(userConfigDir(home));
6794
+ let raw;
6795
+ try {
6796
+ raw = await readFile12(path6, "utf8");
6797
+ } catch {
6798
+ return [];
6799
+ }
6800
+ let parsed;
6801
+ try {
6802
+ parsed = parseJsonc(raw);
6803
+ } catch {
6804
+ return [];
6805
+ }
6806
+ if (typeof parsed !== "object" || parsed === null) return [];
6807
+ const servers = parsed.servers;
6808
+ if (!Array.isArray(servers)) return [];
6809
+ const out = [];
6810
+ for (const s of servers) {
6811
+ const e = s;
6812
+ if (e?.slug === target && typeof e?.namespace === "string") out.push(e.namespace);
6813
+ }
6814
+ return out;
6815
+ }
7146
6816
  function renderLaunch2(entry) {
7147
6817
  const command = typeof entry.command === "string" ? entry.command : "";
7148
6818
  const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
@@ -7195,10 +6865,10 @@ async function runRemove(opts) {
7195
6865
  printErr(`yaw-mcp remove: "${opts.target}" isn't a valid slug or namespace.`);
7196
6866
  return { exitCode: 2, written: [] };
7197
6867
  }
7198
- const home = opts.home ?? homedir14();
6868
+ const home = opts.home ?? homedir13();
7199
6869
  const cwd = opts.cwd ?? process.cwd();
7200
- const derived = deriveNamespace(opts.target);
7201
- const candidates = derived === opts.target ? [opts.target] : [opts.target, derived];
6870
+ const bySlug = await namespacesForStoredSlug(opts.target, home);
6871
+ const candidates = [.../* @__PURE__ */ new Set([opts.target, ...bySlug, deriveNamespace(opts.target)])];
7202
6872
  if (!opts.force) {
7203
6873
  const doomed = await findRemovalTarget(candidates, home);
7204
6874
  if (doomed) {
@@ -7254,7 +6924,35 @@ var LIST_USAGE = `Usage: yaw-mcp list [--json]
7254
6924
 
7255
6925
  List the MCP servers yaw-mcp loads locally from bundles.json (the
7256
6926
  project-local file wins over user-global), with the compliance grade
7257
- \`yaw-mcp audit\` last cached for each. --json for machine output.`;
6927
+ \`yaw-mcp audit\` last cached for each. --json for machine output.
6928
+ Env vars appear as \`envKeys\` -- key NAMES only, never the stored
6929
+ values (same posture as \`add --json\`).`;
6930
+ async function rawEnvKeysByNamespace(path6) {
6931
+ const out = /* @__PURE__ */ new Map();
6932
+ if (!path6) return out;
6933
+ let raw;
6934
+ try {
6935
+ raw = await readFile12(path6, "utf8");
6936
+ } catch {
6937
+ return out;
6938
+ }
6939
+ let parsed;
6940
+ try {
6941
+ parsed = parseJsonc(raw);
6942
+ } catch {
6943
+ return out;
6944
+ }
6945
+ if (typeof parsed !== "object" || parsed === null) return out;
6946
+ const servers = parsed.servers;
6947
+ if (!Array.isArray(servers)) return out;
6948
+ for (const s of servers) {
6949
+ const e = s;
6950
+ if (!e || typeof e.namespace !== "string" || out.has(e.namespace)) continue;
6951
+ const env = e.env && typeof e.env === "object" && !Array.isArray(e.env) ? e.env : {};
6952
+ out.set(e.namespace, Object.keys(env));
6953
+ }
6954
+ return out;
6955
+ }
7258
6956
  function parseListArgs(argv) {
7259
6957
  const opts = {};
7260
6958
  for (const a of argv) {
@@ -7275,7 +6973,7 @@ async function runList(opts) {
7275
6973
  `);
7276
6974
  const printErr = (s) => err(`${s}
7277
6975
  `);
7278
- const home = opts.home ?? homedir14();
6976
+ const home = opts.home ?? homedir13();
7279
6977
  const cwd = opts.cwd ?? process.cwd();
7280
6978
  const loaded = await loadLocalBundles({ home, cwd });
7281
6979
  const servers = loaded.config?.servers ?? [];
@@ -7287,7 +6985,19 @@ async function runList(opts) {
7287
6985
  return cached ? { ...s, complianceGrade: cached.grade } : s;
7288
6986
  });
7289
6987
  if (opts.json) {
7290
- print(JSON.stringify({ path: loaded.path, servers: graded, warnings: loaded.warnings }, null, 2));
6988
+ const rawEnvKeys = await rawEnvKeysByNamespace(loaded.path);
6989
+ const jsonServers = graded.map((s) => {
6990
+ const entry = jsonEntry(s);
6991
+ const keys = rawEnvKeys.get(s.namespace);
6992
+ if (keys !== void 0 && keys.length > 0) entry.envKeys = keys;
6993
+ const cached = grades[s.namespace];
6994
+ if (cached) {
6995
+ entry.complianceGradedAt = cached.gradedAt;
6996
+ if (cached.suiteVersion) entry.complianceSuiteVersion = cached.suiteVersion;
6997
+ }
6998
+ return entry;
6999
+ });
7000
+ print(JSON.stringify({ path: loaded.path, servers: jsonServers, warnings: loaded.warnings }, null, 2));
7291
7001
  return { exitCode: 0, written: [] };
7292
7002
  }
7293
7003
  if (servers.length === 0) {
@@ -7316,8 +7026,8 @@ ${servers.length} server${servers.length === 1 ? "" : "s"} in ${loaded.path}`);
7316
7026
  }
7317
7027
 
7318
7028
  // src/reset-learning-cmd.ts
7319
- import { readFile as readFile12, unlink as unlink3 } from "fs/promises";
7320
- import { homedir as homedir15 } from "os";
7029
+ import { readFile as readFile13, unlink as unlink3 } from "fs/promises";
7030
+ import { homedir as homedir14 } from "os";
7321
7031
  import { join as join10 } from "path";
7322
7032
  var RESET_LEARNING_USAGE = `Usage: yaw-mcp reset-learning
7323
7033
 
@@ -7349,7 +7059,7 @@ ${RESET_LEARNING_USAGE}`
7349
7059
  };
7350
7060
  }
7351
7061
  async function runResetLearning(opts = {}) {
7352
- const home = opts.home ?? homedir15();
7062
+ const home = opts.home ?? homedir14();
7353
7063
  const env = opts.env ?? process.env;
7354
7064
  const write = opts.out ?? ((s) => process.stdout.write(s));
7355
7065
  const writeErr = opts.err ?? ((s) => process.stderr.write(s));
@@ -7401,7 +7111,7 @@ async function runResetLearning(opts = {}) {
7401
7111
  async function peekParsedCleanly(filePath) {
7402
7112
  let raw;
7403
7113
  try {
7404
- raw = await readFile12(filePath, "utf8");
7114
+ raw = await readFile13(filePath, "utf8");
7405
7115
  } catch (err) {
7406
7116
  if (isFileNotFound2(err)) return true;
7407
7117
  return false;
@@ -7420,19 +7130,19 @@ function isFileNotFound2(err) {
7420
7130
 
7421
7131
  // src/secrets-cmd.ts
7422
7132
  import { existsSync as existsSync8 } from "fs";
7423
- import { homedir as homedir18 } from "os";
7133
+ import { homedir as homedir17 } from "os";
7424
7134
 
7425
7135
  // src/secrets-audit.ts
7426
7136
  import { existsSync as existsSync7 } from "fs";
7427
- import { appendFile as appendFile2, chmod as chmod5, readFile as readFile13, stat as stat4 } from "fs/promises";
7428
- import { homedir as homedir16 } from "os";
7137
+ import { appendFile as appendFile2, chmod as chmod5, readFile as readFile14, stat as stat4 } from "fs/promises";
7138
+ import { homedir as homedir15 } from "os";
7429
7139
  import { join as join11 } from "path";
7430
7140
  var SECRETS_AUDIT_FILENAME = "secrets-audit.log";
7431
7141
  var AUDIT_TAIL_CAP = 5e3;
7432
- function auditLogPath(home = homedir16()) {
7142
+ function auditLogPath(home = homedir15()) {
7433
7143
  return join11(home, CONFIG_DIRNAME, SECRETS_AUDIT_FILENAME);
7434
7144
  }
7435
- async function appendAuditEvent(input, home = homedir16()) {
7145
+ async function appendAuditEvent(input, home = homedir15()) {
7436
7146
  try {
7437
7147
  const event = {
7438
7148
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -7459,19 +7169,19 @@ var MIN_AUDIT_LINE_BYTES = 64;
7459
7169
  async function trimToTailCap(path6) {
7460
7170
  const { size } = await stat4(path6);
7461
7171
  if (size < AUDIT_TAIL_CAP * MIN_AUDIT_LINE_BYTES) return;
7462
- const raw = await readFile13(path6, "utf8");
7172
+ const raw = await readFile14(path6, "utf8");
7463
7173
  const lines = raw.split("\n").filter((l) => l.length > 0);
7464
7174
  if (lines.length <= AUDIT_TAIL_CAP) return;
7465
7175
  const kept = lines.slice(lines.length - AUDIT_TAIL_CAP);
7466
7176
  await atomicWriteFile(path6, `${kept.join("\n")}
7467
7177
  `, "utf8", 384);
7468
7178
  }
7469
- async function readAuditLog(filter = {}, home = homedir16()) {
7179
+ async function readAuditLog(filter = {}, home = homedir15()) {
7470
7180
  const path6 = auditLogPath(home);
7471
7181
  if (!existsSync7(path6)) return [];
7472
7182
  let raw;
7473
7183
  try {
7474
- raw = await readFile13(path6, "utf8");
7184
+ raw = await readFile14(path6, "utf8");
7475
7185
  } catch {
7476
7186
  return [];
7477
7187
  }
@@ -7499,9 +7209,9 @@ function isAuditEvent(v) {
7499
7209
 
7500
7210
  // src/secrets-vault.ts
7501
7211
  import { createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
7502
- import { chmod as chmod6, mkdir as mkdir5, readFile as readFile14 } from "fs/promises";
7503
- import { homedir as homedir17 } from "os";
7504
- import { dirname as dirname2, join as join12 } from "path";
7212
+ import { chmod as chmod6, mkdir as mkdir5, readFile as readFile15 } from "fs/promises";
7213
+ import { homedir as homedir16 } from "os";
7214
+ import { dirname as dirname3, join as join12 } from "path";
7505
7215
 
7506
7216
  // src/secrets-crypto.ts
7507
7217
  import { createCipheriv, createDecipheriv, randomBytes, scrypt as scryptCb } from "crypto";
@@ -7519,13 +7229,13 @@ async function deriveKey(passphrase, salt) {
7519
7229
  return scryptCallWithMaxmem(passphrase, salt, KEY_LEN);
7520
7230
  }
7521
7231
  async function scryptCallWithMaxmem(password, salt, keylen) {
7522
- return new Promise((resolve8, reject) => {
7232
+ return new Promise((resolve7, reject) => {
7523
7233
  scryptCb(
7524
7234
  password,
7525
7235
  salt,
7526
7236
  keylen,
7527
7237
  { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P, maxmem: SCRYPT_MAXMEM },
7528
- (err, key) => err ? reject(err) : resolve8(key)
7238
+ (err, key) => err ? reject(err) : resolve7(key)
7529
7239
  );
7530
7240
  });
7531
7241
  }
@@ -7559,7 +7269,7 @@ var SECRETS_FILENAME = "secrets.json";
7559
7269
  var SECRETS_SCHEMA_VERSION = 1;
7560
7270
  var VAULT_CHECK_PLAINTEXT = "yaw-mcp-vault-v1";
7561
7271
  var VAULT_CHECK_CORRUPT_ERROR = 'vault verification token ("check") is corrupt -- the passphrase is correct, but the check marker does not decrypt';
7562
- function vaultPath(home = homedir17()) {
7272
+ function vaultPath(home = homedir16()) {
7563
7273
  return join12(home, CONFIG_DIRNAME, SECRETS_FILENAME);
7564
7274
  }
7565
7275
  function emptyVault() {
@@ -7572,7 +7282,7 @@ function emptyVault() {
7572
7282
  async function loadVault(path6) {
7573
7283
  let raw;
7574
7284
  try {
7575
- raw = await readFile14(path6, "utf8");
7285
+ raw = await readFile15(path6, "utf8");
7576
7286
  } catch (err) {
7577
7287
  const code = err.code;
7578
7288
  if (code === "ENOENT") return null;
@@ -7621,7 +7331,7 @@ function isEncryptedEntry(v) {
7621
7331
  return typeof e.iv === "string" && typeof e.ciphertext === "string" && typeof e.authTag === "string";
7622
7332
  }
7623
7333
  async function saveVault(path6, vault) {
7624
- const dir = dirname2(path6);
7334
+ const dir = dirname3(path6);
7625
7335
  await mkdir5(dir, { recursive: true });
7626
7336
  if (process.platform !== "win32") {
7627
7337
  try {
@@ -8034,6 +7744,12 @@ function nonTTYEnds(opts) {
8034
7744
  if (!ends.stdin && !ends.stdout) return "neither stdin nor stdout is a TTY";
8035
7745
  return ends.stdin ? "stdout is not a TTY" : "stdin is not a TTY";
8036
7746
  }
7747
+ function promptUnavailableMessage(opts, required, envVar) {
7748
+ if (!isInteractiveTTY(opts) && (process.env.MSYSTEM ?? "") !== "") {
7749
+ return `${required} Node cannot prompt under Git Bash/MSYS -- the terminal is emulated with pipes, not a TTY. Set ${envVar}, run under winpty (winpty yaw-mcp ...), or use PowerShell/cmd.`;
7750
+ }
7751
+ return `${required} Set ${envVar} or run from a TTY so we can prompt.`;
7752
+ }
8037
7753
  async function promptYesNo(opts, question) {
8038
7754
  const stdin = opts.io?.stdin ?? process.stdin;
8039
7755
  const stdout = opts.io?.stdout ?? process.stdout;
@@ -8128,7 +7844,7 @@ var CTRL_D = "";
8128
7844
  var DEL = "\x7F";
8129
7845
  function readLineFromTTY(stdin, stdout, prompt = "Vault passphrase: ", echo = false) {
8130
7846
  stdout.write(prompt);
8131
- return new Promise((resolve8) => {
7847
+ return new Promise((resolve7) => {
8132
7848
  const chunks = [];
8133
7849
  const wasRaw = stdin.isRaw === true;
8134
7850
  try {
@@ -8145,20 +7861,28 @@ function readLineFromTTY(stdin, stdout, prompt = "Vault passphrase: ", echo = fa
8145
7861
  } catch {
8146
7862
  }
8147
7863
  stdin.pause();
8148
- resolve8(value);
7864
+ resolve7(value);
8149
7865
  };
8150
7866
  function onData(chunk) {
7867
+ let consumed = 0;
7868
+ const finishAndRebuffer = (value) => {
7869
+ finish(value);
7870
+ const rest = chunk.slice(consumed);
7871
+ if (rest.length > 0) stdin.unshift?.(rest);
7872
+ };
8151
7873
  for (const ch of chunk) {
7874
+ consumed += ch.length;
8152
7875
  if (ch === "\n" || ch === "\r") {
8153
- finish(chunks.join(""));
7876
+ if (ch === "\r" && chunk[consumed] === "\n") consumed += 1;
7877
+ finishAndRebuffer(chunks.join(""));
8154
7878
  return;
8155
7879
  }
8156
7880
  if (ch === CTRL_D) {
8157
- finish("");
7881
+ finishAndRebuffer("");
8158
7882
  return;
8159
7883
  }
8160
7884
  if (ch === CTRL_C) {
8161
- finish(CANCELLED);
7885
+ finishAndRebuffer(CANCELLED);
8162
7886
  return;
8163
7887
  }
8164
7888
  if (ch === "\b" || ch === DEL) {
@@ -8192,7 +7916,7 @@ async function runSecrets(opts, io = {
8192
7916
  out: (s) => process.stdout.write(s),
8193
7917
  err: (s) => process.stderr.write(s)
8194
7918
  }) {
8195
- const home = opts.home ?? homedir18();
7919
+ const home = opts.home ?? homedir17();
8196
7920
  const path6 = vaultPath(home);
8197
7921
  if (opts.action === "lock") {
8198
7922
  lock();
@@ -8270,7 +7994,7 @@ async function runSecrets(opts, io = {
8270
7994
  const passphrase = await resolvePassphrase(opts, creatingVault);
8271
7995
  if (passphrase === CANCELLED) return cancelledResult(io, opts.json);
8272
7996
  if (passphrase === null) {
8273
- const msg = "Passphrase required. Set YAW_MCP_VAULT_PASSPHRASE or run from a TTY so we can prompt.";
7997
+ const msg = promptUnavailableMessage(opts, "Passphrase required.", "YAW_MCP_VAULT_PASSPHRASE");
8274
7998
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
8275
7999
  `);
8276
8000
  else io.err(`yaw-mcp secrets: ${msg}
@@ -8367,7 +8091,7 @@ async function runSecrets(opts, io = {
8367
8091
  return { exitCode: 2 };
8368
8092
  }
8369
8093
  async function runSecretsRotate(opts, io) {
8370
- const home = opts.home ?? homedir18();
8094
+ const home = opts.home ?? homedir17();
8371
8095
  const path6 = vaultPath(home);
8372
8096
  const loaded = await safeLoadVault(path6, io, opts.json, "rotate");
8373
8097
  if (!loaded.ok) return loaded.result;
@@ -8383,7 +8107,7 @@ async function runSecretsRotate(opts, io) {
8383
8107
  const currentPassphrase = await resolvePassphrase(opts);
8384
8108
  if (currentPassphrase === CANCELLED) return cancelledResult(io, opts.json);
8385
8109
  if (currentPassphrase === null) {
8386
- const msg = "Current passphrase required. Set YAW_MCP_VAULT_PASSPHRASE or run from a TTY so we can prompt.";
8110
+ const msg = promptUnavailableMessage(opts, "Current passphrase required.", "YAW_MCP_VAULT_PASSPHRASE");
8387
8111
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
8388
8112
  `);
8389
8113
  else io.err(`yaw-mcp secrets rotate: ${msg}
@@ -8404,7 +8128,11 @@ async function runSecretsRotate(opts, io) {
8404
8128
  const newPassphrase = await resolveNewPassphrase(opts);
8405
8129
  if (newPassphrase === CANCELLED) return cancelledResult(io, opts.json);
8406
8130
  if (newPassphrase === null) {
8407
- const msg = "New passphrase required (and must be confirmed). Set YAW_MCP_VAULT_PASSPHRASE_NEW or run from a TTY so we can prompt.";
8131
+ const msg = promptUnavailableMessage(
8132
+ opts,
8133
+ "New passphrase required (and must be confirmed).",
8134
+ "YAW_MCP_VAULT_PASSPHRASE_NEW"
8135
+ );
8408
8136
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
8409
8137
  `);
8410
8138
  else io.err(`yaw-mcp secrets rotate: ${msg}
@@ -8439,7 +8167,7 @@ async function runSecretsRotate(opts, io) {
8439
8167
  return { exitCode: 0 };
8440
8168
  }
8441
8169
  async function runSecretsAudit(opts, io) {
8442
- const home = opts.home ?? homedir18();
8170
+ const home = opts.home ?? homedir17();
8443
8171
  let events;
8444
8172
  try {
8445
8173
  events = await readAuditLog(
@@ -8474,7 +8202,7 @@ async function runSecretsAudit(opts, io) {
8474
8202
  }
8475
8203
 
8476
8204
  // src/server.ts
8477
- import { homedir as homedir19 } from "os";
8205
+ import { homedir as homedir18 } from "os";
8478
8206
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
8479
8207
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8480
8208
  import {
@@ -8482,162 +8210,11 @@ import {
8482
8210
  GetPromptRequestSchema,
8483
8211
  ListPromptsRequestSchema,
8484
8212
  ListResourcesRequestSchema,
8213
+ ListResourceTemplatesRequestSchema,
8485
8214
  ListToolsRequestSchema,
8486
8215
  ReadResourceRequestSchema
8487
8216
  } from "@modelcontextprotocol/sdk/types.js";
8488
8217
 
8489
- // src/auto-upgrade.ts
8490
- import { spawn as spawn4 } from "child_process";
8491
- import { realpathSync as realpathSync2 } from "fs";
8492
- import { dirname as dirname3, sep } from "path";
8493
- function quoteShellArgIfNeeded(arg, platform = process.platform) {
8494
- if (platform !== "win32") return arg;
8495
- if (/[\r\n\0"%]/.test(arg)) return null;
8496
- if (!/[\s&|<>^]/.test(arg)) return arg;
8497
- return `"${arg}"`;
8498
- }
8499
- function detectRunningInstallPrefix(argvPath) {
8500
- if (!argvPath) return null;
8501
- let resolved;
8502
- try {
8503
- resolved = realpathSync2(argvPath);
8504
- } catch {
8505
- return null;
8506
- }
8507
- let dir = dirname3(resolved);
8508
- let prev = "";
8509
- let safety = 24;
8510
- while (dir !== prev && safety-- > 0) {
8511
- const idx = dir.lastIndexOf(`${sep}node_modules${sep}`);
8512
- if (idx !== -1) {
8513
- const candidate = dir.slice(0, idx);
8514
- if (candidate.endsWith(`${sep}lib`)) return candidate.slice(0, -`${sep}lib`.length);
8515
- return candidate;
8516
- }
8517
- prev = dir;
8518
- dir = dirname3(dir);
8519
- }
8520
- return null;
8521
- }
8522
- function comparablePrefix(p) {
8523
- const trimmed = p.trim();
8524
- return process.platform === "win32" ? trimmed.toLowerCase() : trimmed;
8525
- }
8526
- async function compareWithNpmPrefix(detected, probe = npmGlobalPrefix) {
8527
- const npmPrefix = await probe();
8528
- if (!npmPrefix?.trim()) return;
8529
- if (comparablePrefix(npmPrefix) === comparablePrefix(detected)) return;
8530
- process.stderr.write(
8531
- `yaw-mcp self-upgrade: detected running prefix differs from \`npm prefix -g\`:
8532
- running: ${detected}
8533
- npm -g: ${npmPrefix}
8534
- Installing into the running prefix so the upgrade lands in the same tree the client spawned from.
8535
- `
8536
- );
8537
- }
8538
- function defaultSpawn2(cmd, args) {
8539
- let errorFired = false;
8540
- const correctiveCmd = cmd === "npm" ? "npm install -g @yawlabs/mcp@latest" : cmd === "pnpm" ? "pnpm add -g @yawlabs/mcp@latest" : "bun add -g @yawlabs/mcp@latest";
8541
- const child = spawn4(cmd, args, {
8542
- stdio: "ignore",
8543
- // Not detached, so the install shares yaw-mcp's process group and an MCP
8544
- // client that tears down the whole tree takes it with it. Two things this
8545
- // does NOT buy (the file header lists both as known gaps): on POSIX a
8546
- // plain parent exit does not kill it, and if it IS killed mid-install the
8547
- // result is not guaranteed intact -- npm reify removes the existing
8548
- // package dir before moving the new one in, and nothing here repairs a
8549
- // partial install on the next startup.
8550
- detached: false,
8551
- shell: process.platform === "win32"
8552
- });
8553
- child.on("close", (code) => {
8554
- if (errorFired) return;
8555
- if (code === 0) {
8556
- log("info", "yaw-mcp self-upgrade complete; the next client restart will run the new version");
8557
- } else {
8558
- const hint = cmd === "npm" ? " (often EACCES on a sudo-installed global -- run with the right permissions)" : "";
8559
- log(
8560
- "warn",
8561
- `yaw-mcp self-upgrade: ${cmd} exited non-zero${hint}. Run \`${correctiveCmd}\` manually, or set YAW_MCP_AUTO_UPGRADE=0 to silence this.`,
8562
- { code }
8563
- );
8564
- }
8565
- });
8566
- child.on("error", (err) => {
8567
- errorFired = true;
8568
- log("warn", `yaw-mcp self-upgrade: ${cmd} spawn failed`, { error: err?.message });
8569
- });
8570
- }
8571
- async function maybeAutoUpgrade(deps = {}) {
8572
- const optOut = process.env.YAW_MCP_AUTO_UPGRADE;
8573
- if (optOut === "0" || optOut?.toLowerCase() === "false") return;
8574
- const current = deps.currentVersion ?? (true ? "0.75.4" : "dev");
8575
- if (current === "dev") return;
8576
- const method = (deps.isSeaImpl ? await deps.isSeaImpl() : await detectSea()) ? "binary" : detectInstallMethod(deps.argvPath ?? process.argv[1]);
8577
- const latest = await (deps.fetchLatestImpl ?? fetchLatestVersion)();
8578
- if (latest === null) return;
8579
- const plan = buildUpgradePlan({ current, latest, method });
8580
- if (!plan.stale) return;
8581
- const rawPrefix = method === "global-npm" ? detectRunningInstallPrefix(deps.argvPath ?? process.argv[1]) : null;
8582
- const quotedPrefix = rawPrefix === null ? null : quoteShellArgIfNeeded(rawPrefix);
8583
- const globalSpec = method === "global-npm" ? {
8584
- cmd: "npm",
8585
- args: quotedPrefix ? ["install", "-g", "--prefix", quotedPrefix, "@yawlabs/mcp@latest"] : ["install", "-g", "@yawlabs/mcp@latest"]
8586
- } : method === "pnpm-global" ? { cmd: "pnpm", args: ["add", "-g", "@yawlabs/mcp@latest"] } : method === "bun-global" ? { cmd: "bun", args: ["add", "-g", "@yawlabs/mcp@latest"] } : null;
8587
- if (globalSpec) {
8588
- log("info", "yaw-mcp is out of date; upgrading the global install in the background", {
8589
- current,
8590
- latest,
8591
- tool: globalSpec.cmd,
8592
- // The RAW prefix, not the shell-quoted argv form -- a log field is read
8593
- // by a human, and stray quotes read as part of the path. Omitted when
8594
- // quoting failed, because then no `--prefix` was passed at all and npm
8595
- // resolves its own prefix.
8596
- prefix: quotedPrefix === null ? void 0 : rawPrefix ?? void 0
8597
- });
8598
- if (method === "global-npm" && rawPrefix !== null && quotedPrefix !== null) {
8599
- void compareWithNpmPrefix(rawPrefix, deps.npmPrefixImpl);
8600
- }
8601
- (deps.spawnImpl ?? defaultSpawn2)(globalSpec.cmd, globalSpec.args);
8602
- return;
8603
- }
8604
- if (method === "bundled-app") {
8605
- log("info", "yaw-mcp (bundled with Yaw Terminal) is behind npm; it updates with the app", { current, latest });
8606
- return;
8607
- }
8608
- if (method === "binary") {
8609
- log("info", "yaw-mcp (standalone binary) is behind npm; download the latest build to update", { current, latest });
8610
- return;
8611
- }
8612
- if (method === "npx") {
8613
- log("info", "yaw-mcp is out of date; restart your MCP client to pick up the latest version", {
8614
- current,
8615
- latest,
8616
- method
8617
- });
8618
- } else if (method === "local-node-modules") {
8619
- log(
8620
- "info",
8621
- "yaw-mcp is out of date; run `yaw-mcp upgrade --run` to update this install (a restart re-runs the version pinned in your project's node_modules)",
8622
- {
8623
- current,
8624
- latest,
8625
- method
8626
- }
8627
- );
8628
- } else {
8629
- log(
8630
- "info",
8631
- "yaw-mcp is out of date; run `yaw-mcp upgrade` for the command that updates this install (`--run` can't automate this install method)",
8632
- {
8633
- current,
8634
- latest,
8635
- method
8636
- }
8637
- );
8638
- }
8639
- }
8640
-
8641
8218
  // src/compliance.ts
8642
8219
  var GRADE_ORDER = {
8643
8220
  A: 4,
@@ -8999,6 +8576,9 @@ function validateExecRequest(req) {
8999
8576
  if (typeof s.id !== "string" || s.id.length === 0) {
9000
8577
  return { ok: false, message: `step ${i}: \`id\` must be a non-empty string` };
9001
8578
  }
8579
+ if (s.id === "__proto__") {
8580
+ return { ok: false, message: `step ${i}: \`id\` "__proto__" is reserved; use a different id` };
8581
+ }
9002
8582
  if (seenIds.has(s.id)) {
9003
8583
  return { ok: false, message: `step ${i}: duplicate id "${s.id}"` };
9004
8584
  }
@@ -9336,6 +8916,11 @@ var META_TOOLS = {
9336
8916
  type: "number",
9337
8917
  default: 1,
9338
8918
  description: "How many top-ranked servers to load into the session. Defaults to 1. Cap is 10. Raise only when one task genuinely spans multiple servers."
8919
+ },
8920
+ routeEffort: {
8921
+ type: "string",
8922
+ enum: ["off", "auto", "aggressive"],
8923
+ description: 'Per-call override of the routing-effort dial. "off" never asks the client LLM to break ranking ties; "auto" (the default) asks once only on genuine ambiguity; "aggressive" samples best-of-3 on milder ambiguity. Falls back to the YAW_MCP_ROUTE_EFFORT env var when omitted. Only meaningful at budget 1.'
9339
8924
  }
9340
8925
  },
9341
8926
  required: ["intent"]
@@ -9506,6 +9091,7 @@ var DEFAULT_MAX_GAP_MS = 12e4;
9506
9091
  var MIN_NAMESPACES = 2;
9507
9092
  var MAX_NAMESPACES = 3;
9508
9093
  var MIN_RECURRENCES = 2;
9094
+ var BURST_SPAN_FACTOR = 5;
9509
9095
  function packIdFromNamespaces(namespaces) {
9510
9096
  return Array.from(new Set(namespaces)).sort().join("|");
9511
9097
  }
@@ -9525,8 +9111,8 @@ var PackDetector = class {
9525
9111
  this.history = this.history.slice(overflow);
9526
9112
  }
9527
9113
  }
9528
- // Walk the history, segmenting it into "bursts" separated by gaps
9529
- // longer than maxGapMs. Each burst with ≥2 distinct namespaces is a
9114
+ // Walk the history, segmenting it into "bursts" (see segmentBursts for
9115
+ // the three boundaries). Each burst with ≥2 distinct namespaces is a
9530
9116
  // candidate pack. A pack is returned when the same namespace set
9531
9117
  // appears in ≥MIN_RECURRENCES bursts.
9532
9118
  detectChains() {
@@ -9561,18 +9147,33 @@ var PackDetector = class {
9561
9147
  }
9562
9148
  return packs;
9563
9149
  }
9564
- // Segment the call history into bursts. A new burst starts whenever
9565
- // the gap to the previous call exceeds maxGapMs. Within a burst, each
9566
- // namespace is recorded only once (order-of-first-appearance); the
9567
- // "last seen" timestamp tracks the most recent call in the burst so
9568
- // recency ranking is truthful even when the burst has many calls.
9150
+ // Segment the call history into bursts. A new burst starts whenever:
9151
+ // 1. the gap to the previous call exceeds maxGapMs (idle boundary);
9152
+ // 2. the burst has already spanned maxGapMs * BURST_SPAN_FACTOR
9153
+ // (span boundary -- see the constant for why a continuous session
9154
+ // must be sliced for recurrence to be countable); or
9155
+ // 3. the call would add a namespace past MAX_NAMESPACES (overflow
9156
+ // boundary). detectChains drops an over-wide burst entirely, so
9157
+ // without this cut a single visit to a 4th namespace poisoned the
9158
+ // whole burst and the recurring trio inside it was never counted.
9159
+ // Cutting at the overflow keeps each burst representable as a
9160
+ // pack; a wider rotation surfaces as its recurring 3-subsets, the
9161
+ // best answer the MAX_NAMESPACES pack-size cap can express.
9162
+ // Within a burst, each namespace is recorded only once
9163
+ // (order-of-first-appearance); the "last seen" timestamp tracks the
9164
+ // most recent call in the burst so recency ranking is truthful even
9165
+ // when the burst has many calls.
9569
9166
  segmentBursts() {
9570
9167
  const bursts = [];
9168
+ const maxBurstSpanMs = this.maxGapMs * BURST_SPAN_FACTOR;
9571
9169
  let current = null;
9572
9170
  let prevAt = 0;
9573
9171
  for (const call of this.history) {
9574
- if (!current || call.at - prevAt > this.maxGapMs) {
9575
- current = { namespaces: [call.namespace], lastAt: call.at };
9172
+ const gapExceeded = call.at - prevAt > this.maxGapMs;
9173
+ const spanExceeded = current !== null && call.at - current.startAt > maxBurstSpanMs;
9174
+ const wouldOverflow = current !== null && current.namespaces.length >= MAX_NAMESPACES && !current.namespaces.includes(call.namespace);
9175
+ if (!current || gapExceeded || spanExceeded || wouldOverflow) {
9176
+ current = { namespaces: [call.namespace], startAt: call.at, lastAt: call.at };
9576
9177
  bursts.push(current);
9577
9178
  } else {
9578
9179
  if (!current.namespaces.includes(call.namespace)) {
@@ -9630,18 +9231,24 @@ function createProgressReporter(extra) {
9630
9231
  return () => {
9631
9232
  };
9632
9233
  }
9633
- let step = 0;
9634
- let lastEmitted = -Number.POSITIVE_INFINITY;
9234
+ const EPSILON = 1e-3;
9235
+ let lastEmitted = -EPSILON;
9635
9236
  return (message, progress, total) => {
9636
- step += 1;
9637
- const candidate = progress ?? step;
9638
- const emitted = candidate > lastEmitted ? candidate : lastEmitted;
9237
+ let emitted;
9238
+ let emittedTotal;
9239
+ if (progress !== void 0) {
9240
+ emitted = progress > lastEmitted ? progress : lastEmitted + EPSILON;
9241
+ emittedTotal = total !== void 0 && emitted <= total ? total : void 0;
9242
+ } else {
9243
+ emitted = lastEmitted + EPSILON;
9244
+ emittedTotal = void 0;
9245
+ }
9639
9246
  const params = {
9640
9247
  progressToken: token,
9641
9248
  progress: emitted,
9642
9249
  message
9643
9250
  };
9644
- if (total !== void 0) params.total = total;
9251
+ if (emittedTotal !== void 0) params.total = emittedTotal;
9645
9252
  lastEmitted = emitted;
9646
9253
  send({ method: "notifications/progress", params }).catch((err) => {
9647
9254
  log("warn", "Progress notification send failed", {
@@ -9684,9 +9291,12 @@ function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, e
9684
9291
  if (seen.has(tool.namespacedName)) continue;
9685
9292
  tools.push({
9686
9293
  name: tool.namespacedName,
9294
+ title: tool.title,
9687
9295
  description: tool.description,
9688
9296
  inputSchema: tool.inputSchema,
9689
- annotations: tool.annotations
9297
+ outputSchema: tool.outputSchema,
9298
+ annotations: tool.annotations,
9299
+ _meta: tool._meta
9690
9300
  });
9691
9301
  seen.add(tool.namespacedName);
9692
9302
  }
@@ -9966,7 +9576,7 @@ function numberLiteralIsFaithful(literal) {
9966
9576
  return digits.replace(/0+$/, "").length <= MAX_FAITHFUL_MANTISSA_DIGITS;
9967
9577
  }
9968
9578
  function pruneWhitespace(text) {
9969
- return text.split("\n").map((line) => line.replace(/[ \t]+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n");
9579
+ return text.split("\n").map((line) => line.replace(/[ \t]+(?=\r?$)/, "")).join("\n").replace(/(?:\r?\n){3,}/g, (run2) => run2.includes("\r") ? "\r\n\r\n" : "\n\n");
9970
9580
  }
9971
9581
  function pruneJson(value) {
9972
9582
  if (value === null || value === void 0) return void 0;
@@ -10137,9 +9747,11 @@ function firstTextBlock(result) {
10137
9747
  return void 0;
10138
9748
  }
10139
9749
  function isEmptyBody(result) {
9750
+ if (result.structuredContent !== void 0) return false;
10140
9751
  const content = result.content;
10141
9752
  if (!content || content.length === 0) return true;
10142
9753
  for (const block of content) {
9754
+ if (block.type !== "text") return false;
10143
9755
  if (typeof block.text === "string" && block.text.trim().length > 0) {
10144
9756
  return false;
10145
9757
  }
@@ -10224,11 +9836,19 @@ async function gradeOutcomeViaSampling(server, ctx) {
10224
9836
  const prompt = buildGraderPrompt(ctx);
10225
9837
  try {
10226
9838
  const result = await withTimeout(
10227
- server.createMessage({
10228
- messages: [{ role: "user", content: { type: "text", text: prompt } }],
10229
- maxTokens: GRADER_MAX_TOKENS,
10230
- includeContext: "none"
10231
- }),
9839
+ server.createMessage(
9840
+ {
9841
+ messages: [{ role: "user", content: { type: "text", text: prompt } }],
9842
+ maxTokens: GRADER_MAX_TOKENS,
9843
+ includeContext: "none"
9844
+ },
9845
+ // Cancel the REQUEST at the deadline, not just our wait for it: the
9846
+ // SDK's request timeout sends notifications/cancelled to the client
9847
+ // and rejects here. Without it, abandoning the promise left the
9848
+ // sampling request (and the client's generation / token spend)
9849
+ // running until the SDK's 60s DEFAULT_REQUEST_TIMEOUT_MSEC.
9850
+ { timeout: GRADER_TIMEOUT_MS }
9851
+ ),
10232
9852
  GRADER_TIMEOUT_MS
10233
9853
  );
10234
9854
  if (!result || typeof result !== "object" || !("content" in result) || !result.content) return null;
@@ -10241,17 +9861,17 @@ async function gradeOutcomeViaSampling(server, ctx) {
10241
9861
  }
10242
9862
  }
10243
9863
  function withTimeout(p, ms) {
10244
- return new Promise((resolve8) => {
10245
- const timer = setTimeout(() => resolve8(null), ms);
9864
+ return new Promise((resolve7) => {
9865
+ const timer = setTimeout(() => resolve7(null), ms);
10246
9866
  if (typeof timer === "object" && timer && "unref" in timer) timer.unref();
10247
9867
  p.then(
10248
9868
  (v) => {
10249
9869
  clearTimeout(timer);
10250
- resolve8(v);
9870
+ resolve7(v);
10251
9871
  },
10252
9872
  () => {
10253
9873
  clearTimeout(timer);
10254
- resolve8(null);
9874
+ resolve7(null);
10255
9875
  }
10256
9876
  );
10257
9877
  });
@@ -10445,8 +10065,8 @@ async function bestOfNViaSampling(server, intent, candidates, n) {
10445
10065
  return winner;
10446
10066
  })();
10447
10067
  let timer;
10448
- const timeout = new Promise((resolve8) => {
10449
- timer = setTimeout(() => resolve8(null), SAMPLING_TIMEOUT_MS);
10068
+ const timeout = new Promise((resolve7) => {
10069
+ timer = setTimeout(() => resolve7(null), SAMPLING_TIMEOUT_MS);
10450
10070
  });
10451
10071
  try {
10452
10072
  return await Promise.race([aggregate, timeout]);
@@ -10460,8 +10080,10 @@ var DEFAULT_SERVER_CAP = 6;
10460
10080
  function resolveServerCap(env = process.env) {
10461
10081
  const raw = env.YAW_MCP_SERVER_CAP;
10462
10082
  if (raw === void 0 || raw === "") return DEFAULT_SERVER_CAP;
10463
- const n = Number.parseInt(raw, 10);
10464
- if (!Number.isFinite(n) || n < 0) return DEFAULT_SERVER_CAP;
10083
+ const trimmed = raw.trim();
10084
+ if (!/^\d+$/.test(trimmed)) return DEFAULT_SERVER_CAP;
10085
+ const n = Number.parseInt(trimmed, 10);
10086
+ if (!Number.isFinite(n)) return DEFAULT_SERVER_CAP;
10465
10087
  return n;
10466
10088
  }
10467
10089
  function evaluateServerCap(namespace, loaded, cap) {
@@ -10485,23 +10107,35 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
10485
10107
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
10486
10108
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
10487
10109
  import {
10110
+ CreateMessageRequestSchema,
10111
+ ElicitRequestSchema,
10112
+ ListRootsRequestSchema,
10488
10113
  PromptListChangedNotificationSchema,
10489
10114
  ResourceListChangedNotificationSchema,
10490
10115
  ToolListChangedNotificationSchema
10491
10116
  } from "@modelcontextprotocol/sdk/types.js";
10492
10117
 
10493
10118
  // src/uv-bootstrap.ts
10494
- import { spawn as spawn5 } from "child_process";
10119
+ import { spawn as spawn3 } from "child_process";
10495
10120
  import { createHash as createHash3 } from "crypto";
10496
10121
  import { createWriteStream } from "fs";
10497
10122
  import fs from "fs/promises";
10498
10123
  import path5 from "path";
10499
10124
  import { pipeline } from "stream/promises";
10500
10125
  import { request } from "undici";
10501
- var UV_VERSION = "0.11.7";
10126
+ var UV_VERSION = "0.12.5";
10502
10127
  var RELEASE_BASE = `https://github.com/astral-sh/uv/releases/download/${UV_VERSION}`;
10503
- function uvTarget() {
10504
- const { platform, arch } = process;
10128
+ function isMuslLibc() {
10129
+ try {
10130
+ const raw = process.report?.getReport();
10131
+ const report = typeof raw === "string" ? JSON.parse(raw) : raw;
10132
+ const header = report?.header;
10133
+ return typeof header?.glibcVersionRuntime !== "string";
10134
+ } catch {
10135
+ return false;
10136
+ }
10137
+ }
10138
+ function uvTarget(platform = process.platform, arch = process.arch, musl = platform === "linux" && isMuslLibc()) {
10505
10139
  if (platform === "win32") {
10506
10140
  if (arch === "x64") return "x86_64-pc-windows-msvc";
10507
10141
  if (arch === "arm64") return "aarch64-pc-windows-msvc";
@@ -10514,8 +10148,9 @@ function uvTarget() {
10514
10148
  return null;
10515
10149
  }
10516
10150
  if (platform === "linux") {
10517
- if (arch === "x64") return "x86_64-unknown-linux-gnu";
10518
- if (arch === "arm64") return "aarch64-unknown-linux-gnu";
10151
+ const libc = musl ? "musl" : "gnu";
10152
+ if (arch === "x64") return `x86_64-unknown-linux-${libc}`;
10153
+ if (arch === "arm64") return `aarch64-unknown-linux-${libc}`;
10519
10154
  return null;
10520
10155
  }
10521
10156
  return null;
@@ -10535,16 +10170,16 @@ async function exists2(p) {
10535
10170
  }
10536
10171
  }
10537
10172
  async function onPath(cmd) {
10538
- return new Promise((resolve8) => {
10173
+ return new Promise((resolve7) => {
10539
10174
  let settled = false;
10540
10175
  const settle = (v) => {
10541
10176
  if (settled) return;
10542
10177
  settled = true;
10543
- resolve8(v);
10178
+ resolve7(v);
10544
10179
  };
10545
10180
  let child;
10546
10181
  try {
10547
- child = spawn5(cmd, ["--version"], {
10182
+ child = spawn3(cmd, ["--version"], {
10548
10183
  stdio: "ignore",
10549
10184
  // Windows needs a shell for PATHEXT shim resolution (.cmd/.exe)
10550
10185
  // so `uv --version` finds uv.cmd without an ENOENT false-negative.
@@ -10558,7 +10193,11 @@ async function onPath(cmd) {
10558
10193
  }
10559
10194
  const timer = setTimeout(() => {
10560
10195
  try {
10561
- child.kill();
10196
+ child.kill("SIGKILL");
10197
+ } catch {
10198
+ }
10199
+ try {
10200
+ child.unref();
10562
10201
  } catch {
10563
10202
  }
10564
10203
  settle(false);
@@ -10641,7 +10280,7 @@ async function extractArchive(archivePath, destDir) {
10641
10280
  var UV_EXTRACT_TIMEOUT_MS = 12e4;
10642
10281
  var RUN_COMMAND_MAX_STDERR = 8 * 1024;
10643
10282
  function runCommand(cmd, args, timeoutMs = UV_EXTRACT_TIMEOUT_MS) {
10644
- return new Promise((resolve8, reject) => {
10283
+ return new Promise((resolve7, reject) => {
10645
10284
  let settled = false;
10646
10285
  let timer;
10647
10286
  const settle = (fn) => {
@@ -10652,7 +10291,7 @@ function runCommand(cmd, args, timeoutMs = UV_EXTRACT_TIMEOUT_MS) {
10652
10291
  };
10653
10292
  let child;
10654
10293
  try {
10655
- child = spawn5(cmd, args, {
10294
+ child = spawn3(cmd, args, {
10656
10295
  stdio: ["ignore", "ignore", "pipe"],
10657
10296
  shell: false,
10658
10297
  windowsHide: process.platform === "win32"
@@ -10672,7 +10311,7 @@ function runCommand(cmd, args, timeoutMs = UV_EXTRACT_TIMEOUT_MS) {
10672
10311
  child.on(
10673
10312
  "close",
10674
10313
  (code, signal) => settle(() => {
10675
- if (code === 0) resolve8();
10314
+ if (code === 0) resolve7();
10676
10315
  else reject(new Error(`${cmd} exited ${code ?? signal}: ${stderr.trim()}`));
10677
10316
  })
10678
10317
  );
@@ -10723,7 +10362,7 @@ async function resolveUv() {
10723
10362
  `No prebuilt uv binary for ${process.platform}/${process.arch}. Install uv manually: https://docs.astral.sh/uv/`
10724
10363
  );
10725
10364
  }
10726
- const installDir = path5.join(cacheDir(), "uv", UV_VERSION);
10365
+ const installDir = path5.join(cacheDir(), "uv", UV_VERSION, target);
10727
10366
  const finalBin = path5.join(installDir, binName());
10728
10367
  if (await exists2(finalBin)) return finalBin;
10729
10368
  await fs.mkdir(installDir, { recursive: true });
@@ -10768,10 +10407,19 @@ async function resolveUv() {
10768
10407
  log("info", "uv bootstrap complete", { bin: finalBin });
10769
10408
  return finalBin;
10770
10409
  }
10410
+ var UV_WIN_EXE_EXT = /\.(?:exe|cmd|bat)$/i;
10411
+ function uvLaunchKind(command) {
10412
+ if (/[\\/]/.test(command)) return null;
10413
+ const base = command.replace(UV_WIN_EXE_EXT, "").toLowerCase();
10414
+ if (base === "uv") return "uv";
10415
+ if (base === "uvx") return "uvx";
10416
+ return null;
10417
+ }
10771
10418
  async function resolveUvSpawn(command, args) {
10772
- if (command !== "uv" && command !== "uvx") return { command, args };
10419
+ const kind = uvLaunchKind(command);
10420
+ if (kind === null) return { command, args };
10773
10421
  const uvBin = await ensureUv();
10774
- if (command === "uvx") {
10422
+ if (kind === "uvx") {
10775
10423
  return { command: uvBin, args: ["tool", "run", ...args] };
10776
10424
  }
10777
10425
  return { command: uvBin, args };
@@ -10846,6 +10494,7 @@ var STDERR_RING_CAP = 8 * 1024;
10846
10494
  var MAX_TOOLS_PER_SERVER = 1e3;
10847
10495
  var MAX_RESOURCES_PER_SERVER = 1e3;
10848
10496
  var MAX_PROMPTS_PER_SERVER = 1e3;
10497
+ var MAX_LIST_PAGES = 50;
10849
10498
  var ActivationError = class extends Error {
10850
10499
  constructor(message, category, stderrTail, cause) {
10851
10500
  super(message);
@@ -10883,10 +10532,10 @@ function categorizeSpawnError(err) {
10883
10532
  return "unknown";
10884
10533
  }
10885
10534
  var oamDowngradedNamespaces = /* @__PURE__ */ new Set();
10886
- async function connectToUpstream(config, onDisconnect, onListChanged) {
10535
+ async function connectToUpstream(config, onDisconnect, onListChanged, bridge) {
10887
10536
  const attempt = { oamRewriteApplied: false, oamVersion: null };
10888
10537
  try {
10889
- return await connectToUpstreamOnce(config, onDisconnect, onListChanged, attempt, false);
10538
+ return await connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge, attempt, false);
10890
10539
  } catch (err) {
10891
10540
  if (!attempt.oamRewriteApplied || !(err instanceof ActivationError)) throw err;
10892
10541
  log("warn", "oam-hosted server failed to boot; downgrading to node for this session", {
@@ -10896,7 +10545,7 @@ async function connectToUpstream(config, onDisconnect, onListChanged) {
10896
10545
  error: err.message
10897
10546
  });
10898
10547
  try {
10899
- const connection = await connectToUpstreamOnce(config, onDisconnect, onListChanged, attempt, true);
10548
+ const connection = await connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge, attempt, true);
10900
10549
  oamDowngradedNamespaces.add(config.namespace);
10901
10550
  return connection;
10902
10551
  } catch (nodeErr) {
@@ -10913,11 +10562,43 @@ async function connectToUpstream(config, onDisconnect, onListChanged) {
10913
10562
  }
10914
10563
  }
10915
10564
  }
10916
- async function connectToUpstreamOnce(config, onDisconnect, onListChanged, attempt, disableOamRewrite) {
10565
+ var INTERNAL_SECRET_ENV_KEYS = /* @__PURE__ */ new Set(["YAW_MCP_TOKEN", "YAW_MCP_VAULT_PASSPHRASE", "YAW_MCP_VAULT_PASSPHRASE_NEW"]);
10566
+ function stripInternalSecretsFromEnv(env) {
10567
+ const out = {};
10568
+ for (const [key, value] of Object.entries(env)) {
10569
+ if (INTERNAL_SECRET_ENV_KEYS.has(key.toUpperCase())) continue;
10570
+ out[key] = value;
10571
+ }
10572
+ return out;
10573
+ }
10574
+ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge, attempt, disableOamRewrite) {
10575
+ const downstreamCaps = bridge?.getClientCapabilities();
10576
+ const capabilities = {};
10577
+ if (downstreamCaps?.elicitation) capabilities.elicitation = downstreamCaps.elicitation;
10578
+ if (downstreamCaps?.sampling) capabilities.sampling = downstreamCaps.sampling;
10579
+ if (downstreamCaps?.roots) capabilities.roots = {};
10917
10580
  const client = new Client(
10918
- { name: "yaw-mcp", version: true ? "0.75.4" : "dev" },
10919
- { capabilities: {} }
10581
+ { name: "yaw-mcp", version: true ? "0.76.1" : "dev" },
10582
+ { capabilities }
10920
10583
  );
10584
+ if (bridge && capabilities.elicitation) {
10585
+ client.setRequestHandler(
10586
+ ElicitRequestSchema,
10587
+ (request2, extra) => bridge.elicitInput(request2.params, { signal: extra.signal })
10588
+ );
10589
+ }
10590
+ if (bridge && capabilities.sampling) {
10591
+ client.setRequestHandler(
10592
+ CreateMessageRequestSchema,
10593
+ (request2, extra) => bridge.createMessage(request2.params, { signal: extra.signal })
10594
+ );
10595
+ }
10596
+ if (bridge && capabilities.roots) {
10597
+ client.setRequestHandler(
10598
+ ListRootsRequestSchema,
10599
+ (request2, extra) => bridge.listRoots(request2.params, { signal: extra.signal })
10600
+ );
10601
+ }
10921
10602
  let transport;
10922
10603
  let stderrRing = "";
10923
10604
  let resolvedServerEnv = {};
@@ -10925,11 +10606,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, attemp
10925
10606
  if (!config.command) {
10926
10607
  throw new Error("command is required for local servers");
10927
10608
  }
10928
- const {
10929
- YAW_MCP_TOKEN: _excludedToken,
10930
- YAW_MCP_VAULT_PASSPHRASE: _excludedVaultPassphrase,
10931
- ...parentEnv
10932
- } = process.env;
10609
+ const parentEnv = stripInternalSecretsFromEnv(process.env);
10933
10610
  let resolved;
10934
10611
  try {
10935
10612
  resolved = await resolveUvSpawn(config.command, config.args ?? []);
@@ -11010,7 +10687,8 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, attemp
11010
10687
  } else if (trimmedStderr.length > 0) {
11011
10688
  category = "install_failure";
11012
10689
  const safe = redactSecretsInOutput(trimmedStderr, resolvedServerEnv);
11013
- message = `Server "${config.namespace}" failed to start. stderr: ${safe.slice(-500)}`;
10690
+ const oomHint = oamHeapOomHint(trimmedStderr);
10691
+ message = oomHint ? `Server "${config.namespace}" ran out of memory. ${oomHint} stderr: ${safe.slice(-500)}` : `Server "${config.namespace}" failed to start. stderr: ${safe.slice(-500)}`;
11014
10692
  } else {
11015
10693
  category = categorizeSpawnError(err);
11016
10694
  if (category === "spawn_failure") {
@@ -11124,10 +10802,42 @@ async function disconnectFromUpstream(connection) {
11124
10802
  }
11125
10803
  log("info", "Disconnected from upstream", { namespace: connection.config.namespace });
11126
10804
  }
10805
+ async function fetchAllPages(fetchPage, cap, context) {
10806
+ const all = [];
10807
+ let cursor;
10808
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
10809
+ const { items, nextCursor } = await fetchPage(cursor);
10810
+ all.push(...items);
10811
+ if (nextCursor === void 0 || all.length > cap) return all;
10812
+ if (items.length === 0) {
10813
+ log("warn", "Upstream returned an empty page with a cursor; stopping pagination", {
10814
+ namespace: context.namespace,
10815
+ endpoint: context.endpoint,
10816
+ pagesFetched: page + 1,
10817
+ items: all.length
10818
+ });
10819
+ return all;
10820
+ }
10821
+ cursor = nextCursor;
10822
+ }
10823
+ log("warn", "Upstream pagination exceeded page cap; truncating", {
10824
+ namespace: context.namespace,
10825
+ endpoint: context.endpoint,
10826
+ pageCap: MAX_LIST_PAGES,
10827
+ items: all.length
10828
+ });
10829
+ return all;
10830
+ }
11127
10831
  async function fetchResourcesFromUpstream(client, namespace, opts = {}) {
11128
10832
  try {
11129
- const result = await client.listResources({}, { timeout: LIST_TIMEOUT });
11130
- const raw = result.resources ?? [];
10833
+ const raw = await fetchAllPages(
10834
+ async (cursor) => {
10835
+ const result = await client.listResources(cursor === void 0 ? {} : { cursor }, { timeout: LIST_TIMEOUT });
10836
+ return { items: result.resources ?? [], nextCursor: result.nextCursor };
10837
+ },
10838
+ MAX_RESOURCES_PER_SERVER,
10839
+ { namespace, endpoint: "resources/list" }
10840
+ );
11131
10841
  if (raw.length > MAX_RESOURCES_PER_SERVER) {
11132
10842
  log("warn", "Upstream returned more resources than cap; truncating", {
11133
10843
  namespace,
@@ -11150,8 +10860,14 @@ async function fetchResourcesFromUpstream(client, namespace, opts = {}) {
11150
10860
  }
11151
10861
  async function fetchPromptsFromUpstream(client, namespace, opts = {}) {
11152
10862
  try {
11153
- const result = await client.listPrompts({}, { timeout: LIST_TIMEOUT });
11154
- const raw = result.prompts ?? [];
10863
+ const raw = await fetchAllPages(
10864
+ async (cursor) => {
10865
+ const result = await client.listPrompts(cursor === void 0 ? {} : { cursor }, { timeout: LIST_TIMEOUT });
10866
+ return { items: result.prompts ?? [], nextCursor: result.nextCursor };
10867
+ },
10868
+ MAX_PROMPTS_PER_SERVER,
10869
+ { namespace, endpoint: "prompts/list" }
10870
+ );
11155
10871
  if (raw.length > MAX_PROMPTS_PER_SERVER) {
11156
10872
  log("warn", "Upstream returned more prompts than cap; truncating", {
11157
10873
  namespace,
@@ -11172,9 +10888,16 @@ async function fetchPromptsFromUpstream(client, namespace, opts = {}) {
11172
10888
  }
11173
10889
  }
11174
10890
  async function fetchToolsFromUpstream(client, namespace) {
11175
- let result;
10891
+ let all;
11176
10892
  try {
11177
- result = await client.listTools({}, { timeout: LIST_TIMEOUT });
10893
+ all = await fetchAllPages(
10894
+ async (cursor) => {
10895
+ const result = await client.listTools(cursor === void 0 ? {} : { cursor }, { timeout: LIST_TIMEOUT });
10896
+ return { items: result.tools ?? [], nextCursor: result.nextCursor };
10897
+ },
10898
+ MAX_TOOLS_PER_SERVER,
10899
+ { namespace, endpoint: "tools/list" }
10900
+ );
11178
10901
  } catch (err) {
11179
10902
  const message = err instanceof Error ? err.message : String(err);
11180
10903
  throw new ActivationError(
@@ -11184,7 +10907,13 @@ async function fetchToolsFromUpstream(client, namespace) {
11184
10907
  err
11185
10908
  );
11186
10909
  }
11187
- const raw = result.tools ?? [];
10910
+ const raw = all.filter((tool) => tool.execution?.taskSupport !== "required");
10911
+ if (raw.length < all.length) {
10912
+ log("warn", "Withholding tools that require task-based execution (unsupported through the proxy)", {
10913
+ namespace,
10914
+ tools: all.filter((tool) => tool.execution?.taskSupport === "required").map((tool) => tool.name)
10915
+ });
10916
+ }
11188
10917
  if (raw.length > MAX_TOOLS_PER_SERVER) {
11189
10918
  log("warn", "Upstream returned more tools than cap; truncating", {
11190
10919
  namespace,
@@ -11195,9 +10924,15 @@ async function fetchToolsFromUpstream(client, namespace) {
11195
10924
  return raw.slice(0, MAX_TOOLS_PER_SERVER).map((tool) => ({
11196
10925
  name: tool.name,
11197
10926
  namespacedName: `${namespace}_${tool.name}`,
10927
+ title: tool.title,
11198
10928
  description: tool.description,
11199
10929
  inputSchema: tool.inputSchema,
11200
- annotations: tool.annotations
10930
+ outputSchema: tool.outputSchema,
10931
+ annotations: tool.annotations,
10932
+ // `execution` is deliberately NOT carried: the proxy always calls
10933
+ // upstream in plain (non-task) mode, so advertising task support
10934
+ // downstream would be a false claim.
10935
+ _meta: tool._meta
11201
10936
  }));
11202
10937
  }
11203
10938
 
@@ -11213,7 +10948,7 @@ function complianceRefusalReason(grade, min) {
11213
10948
  return `compliance grade ${grade ?? "unknown"} is below YAW_MCP_MIN_COMPLIANCE=${min}`;
11214
10949
  }
11215
10950
  function isAutoLoadEnabled() {
11216
- const raw = process.env.YAW_MCP_AUTO_LOAD;
10951
+ const raw = process.env.YAW_MCP_AUTO_LOAD?.trim();
11217
10952
  if (raw === void 0 || raw === "") return false;
11218
10953
  return raw === "1" || raw.toLowerCase() === "true";
11219
10954
  }
@@ -11233,7 +10968,7 @@ function resolveIdleThreshold() {
11233
10968
  return Number.isFinite(n) && n >= 1 ? n : DEFAULT_IDLE_CALL_THRESHOLD;
11234
10969
  }
11235
10970
  function isAutoActivateEnabled() {
11236
- const raw = process.env.YAW_MCP_AUTO_ACTIVATE;
10971
+ const raw = process.env.YAW_MCP_AUTO_ACTIVATE?.trim();
11237
10972
  if (raw === void 0 || raw === "") return true;
11238
10973
  return raw === "1" || raw.toLowerCase() === "true";
11239
10974
  }
@@ -11275,12 +11010,12 @@ function argsEqual(a, b) {
11275
11010
  return a.every((v, i) => v === b[i]);
11276
11011
  }
11277
11012
  function settledWithin(p, ms) {
11278
- return new Promise((resolve8) => {
11279
- const timer = setTimeout(() => resolve8(false), ms);
11013
+ return new Promise((resolve7) => {
11014
+ const timer = setTimeout(() => resolve7(false), ms);
11280
11015
  if (typeof timer.unref === "function") timer.unref();
11281
11016
  const done = () => {
11282
11017
  clearTimeout(timer);
11283
- resolve8(true);
11018
+ resolve7(true);
11284
11019
  };
11285
11020
  p.then(done, done);
11286
11021
  });
@@ -11317,6 +11052,7 @@ function computeToolOverlaps(connections) {
11317
11052
  }
11318
11053
  var ConnectServer = class _ConnectServer {
11319
11054
  server;
11055
+ clientBridge;
11320
11056
  connections = /* @__PURE__ */ new Map();
11321
11057
  config = null;
11322
11058
  configVersion = null;
@@ -11370,7 +11106,7 @@ var ConnectServer = class _ConnectServer {
11370
11106
  // real process values; overridable so tests can point the scan at a
11371
11107
  // synthetic home + stubbed env without touching the developer's real
11372
11108
  // shell history or ~/.yaw-mcp/ state file.
11373
- nudgeHome = homedir19();
11109
+ nudgeHome = homedir18();
11374
11110
  nudgeEnv = process.env;
11375
11111
  // Loaded YAW-MCP.md guides (user-global + project-local). Null until
11376
11112
  // start() has run the loader; fail-open if either file is missing,
@@ -11484,7 +11220,7 @@ var ConnectServer = class _ConnectServer {
11484
11220
  static SHUTDOWN_DRAIN_MS = 2e3;
11485
11221
  constructor() {
11486
11222
  this.server = new Server(
11487
- { name: "yaw-mcp", version: true ? "0.75.4" : "dev" },
11223
+ { name: "yaw-mcp", version: true ? "0.76.1" : "dev" },
11488
11224
  {
11489
11225
  capabilities: {
11490
11226
  tools: { listChanged: true },
@@ -11493,6 +11229,12 @@ var ConnectServer = class _ConnectServer {
11493
11229
  }
11494
11230
  }
11495
11231
  );
11232
+ this.clientBridge = {
11233
+ getClientCapabilities: () => this.server.getClientCapabilities(),
11234
+ elicitInput: (params, options) => this.server.elicitInput(params, options),
11235
+ createMessage: (params, options) => this.server.createMessage(params, options),
11236
+ listRoots: (params, options) => this.server.listRoots(params, options)
11237
+ };
11496
11238
  this.setupHandlers();
11497
11239
  }
11498
11240
  // Builtin resources served directly by yaw-mcp (not proxied from an
@@ -11544,6 +11286,9 @@ var ConnectServer = class _ConnectServer {
11544
11286
  this.sessionActivated
11545
11287
  )
11546
11288
  }));
11289
+ this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
11290
+ resourceTemplates: []
11291
+ }));
11547
11292
  this.server.setRequestHandler(ReadResourceRequestSchema, async (request2) => {
11548
11293
  return routeResourceRead(request2.params.uri, this.resourceRoutes, this.connections, this.getBuiltinResourceMap());
11549
11294
  });
@@ -11651,6 +11396,30 @@ var ConnectServer = class _ConnectServer {
11651
11396
  const cached = this.toolCache.get(server.namespace);
11652
11397
  return cached !== void 0 && cached.length > 0;
11653
11398
  }
11399
+ // How long a LEARNED tool list stays trusted before the next pre-warm
11400
+ // re-spawns the server to refresh it. Installs resolve at @latest, so an
11401
+ // upstream that renames or removes a tool would otherwise keep discover's
11402
+ // "known tools:" line, the BM25 corpus, and the deferred routes pointing
11403
+ // at dead names for the full persistence TTL (TOOLCACHE_TTL_MS, 30 days)
11404
+ // -- the only recovery being the "no longer available after loading"
11405
+ // error on a live call. A weekly re-learn bounds that drift at one extra
11406
+ // spawn per server per week.
11407
+ static TOOLCACHE_REFRESH_MS = 7 * 24 * 60 * 60 * 1e3;
11408
+ // 7 days
11409
+ // True when the list hasKnownTools trusts came from a PREVIOUS session's
11410
+ // learning and is old enough to re-verify. Scoped to learned entries on
11411
+ // purpose: a toolCache shipped in bundles.json is curated, carries no
11412
+ // learnedAt, and is never refreshed here -- refreshing it every session
11413
+ // is exactly the per-session `npx -y <pkg>@latest` resolve pre-warm
11414
+ // exists to avoid. runActivateOne stamps a fresh learnedAt on every
11415
+ // activation, so a server in actual use never looks stale.
11416
+ isLearnedCacheStale(namespace) {
11417
+ const cached = this.toolCache.get(namespace);
11418
+ if (cached === void 0 || cached.length === 0) return false;
11419
+ const learnedAt = this.toolCacheLearnedAt.get(namespace);
11420
+ if (learnedAt === void 0) return false;
11421
+ return Date.now() - learnedAt > _ConnectServer.TOOLCACHE_REFRESH_MS;
11422
+ }
11654
11423
  // Seed the in-memory tool cache from the persisted snapshot. Runs before
11655
11424
  // reconcileConfig so the first tools/list of the session can already
11656
11425
  // include deferred servers' tools. Entries for namespaces no longer in
@@ -11689,7 +11458,7 @@ var ConnectServer = class _ConnectServer {
11689
11458
  //
11690
11459
  // `home` is a parameter rather than a field so tests can point it at a
11691
11460
  // synthetic ~/.yaw-mcp without running the whole of start().
11692
- async hydrateComplianceGrades(home = homedir19()) {
11461
+ async hydrateComplianceGrades(home = homedir18()) {
11693
11462
  if (!this.config) return;
11694
11463
  const grades = await readGradesCache(home).catch(() => ({}));
11695
11464
  if (Object.keys(grades).length === 0) return;
@@ -11772,16 +11541,18 @@ var ConnectServer = class _ConnectServer {
11772
11541
  });
11773
11542
  await this.hydrateComplianceGrades();
11774
11543
  await this.reconcileConfig(this.config);
11775
- if (this.config?.servers.some((s) => s.command === "uv" || s.command === "uvx")) {
11544
+ if (this.config?.servers.some((s) => s.command !== void 0 && uvLaunchKind(s.command) !== null)) {
11776
11545
  ensureUv().catch((err) => log("warn", "uv prewarm failed", { error: err?.message }));
11777
11546
  }
11778
11547
  const transport = new StdioServerTransport();
11548
+ this.server.oninitialized = () => {
11549
+ this.prewarmDormantServers().catch((err) => log("warn", "Pre-warm failed", { error: err?.message }));
11550
+ if (isAutoLoadEnabled() && this.persistenceReady) {
11551
+ this.autoLoadRecurringPack().catch((err) => log("warn", "Auto-load failed", { error: err?.message }));
11552
+ }
11553
+ };
11779
11554
  await this.server.connect(transport);
11780
- this.prewarmDormantServers().catch((err) => log("warn", "Pre-warm failed", { error: err?.message }));
11781
11555
  maybeAutoUpgrade().catch((err) => log("warn", "Auto-upgrade check failed", { error: err?.message }));
11782
- if (isAutoLoadEnabled() && this.persistenceReady) {
11783
- this.autoLoadRecurringPack().catch((err) => log("warn", "Auto-load failed", { error: err?.message }));
11784
- }
11785
11556
  log("info", "yaw-mcp started", {
11786
11557
  servers: this.config?.servers.length ?? 0
11787
11558
  });
@@ -11840,9 +11611,13 @@ var ConnectServer = class _ConnectServer {
11840
11611
  // the one hydrated from state.json — so this is a one-time cost per
11841
11612
  // server rather than a per-session `npx -y <pkg>@latest` resolve for
11842
11613
  // every active server (which is what it degenerated into while the
11843
- // learned cache had nowhere to persist).
11614
+ // learned cache had nowhere to persist). A learned list past
11615
+ // TOOLCACHE_REFRESH_MS counts as dormant again so @latest drift gets
11616
+ // re-learned weekly instead of only at the 30-day persistence expiry.
11844
11617
  async prewarmDormantServers() {
11845
- const dormant = this.getProfiledActiveServers().filter((s) => !this.hasKnownTools(s));
11618
+ const dormant = this.getProfiledActiveServers().filter(
11619
+ (s) => this.connections.get(s.namespace)?.status !== "connected" && (!this.hasKnownTools(s) || this.isLearnedCacheStale(s.namespace))
11620
+ );
11846
11621
  if (dormant.length === 0) return;
11847
11622
  log("info", "Pre-warming dormant servers", {
11848
11623
  count: dormant.length,
@@ -11862,6 +11637,10 @@ var ConnectServer = class _ConnectServer {
11862
11637
  true
11863
11638
  );
11864
11639
  if (!result.ok) return;
11640
+ if (!result.isChanged) {
11641
+ this.prewarmNamespaces.delete(server.namespace);
11642
+ return;
11643
+ }
11865
11644
  if (!this.prewarmNamespaces.has(server.namespace)) {
11866
11645
  log("info", "Pre-warm skipping disconnect \u2014 namespace claimed by explicit activate", {
11867
11646
  namespace: server.namespace
@@ -11905,17 +11684,8 @@ var ConnectServer = class _ConnectServer {
11905
11684
  if (!this.guides.user && !this.guides.project) return result;
11906
11685
  this.guideNudgeFired = true;
11907
11686
  const sources = [this.guides.user?.path, this.guides.project?.path].filter(Boolean).join(", ");
11908
- const text = `
11909
-
11910
- [yaw-mcp] Tip: read the \`yaw-mcp://guide\` resource for project-specific routing & credential guidance (from ${sources}). This hint appears once per session.`;
11911
- const content = [...result.content];
11912
- const last = content[content.length - 1];
11913
- if (last && last.type === "text") {
11914
- content[content.length - 1] = { ...last, text: `${last.text}${text}` };
11915
- } else {
11916
- content.push({ type: "text", text: text.trimStart() });
11917
- }
11918
- return { ...result, content };
11687
+ const text = `[yaw-mcp] Tip: read the \`yaw-mcp://guide\` resource for project-specific routing & credential guidance (from ${sources}). This hint appears once per session.`;
11688
+ return { ...result, content: [...result.content, { type: "text", text }] };
11919
11689
  }
11920
11690
  async handleToolCall(name, args, extra, opts) {
11921
11691
  const progress = createProgressReporter(extra);
@@ -12014,7 +11784,8 @@ var ConnectServer = class _ConnectServer {
12014
11784
  const newConn = await connectToUpstream(
12015
11785
  reconnectConfig,
12016
11786
  this.onUpstreamDisconnect,
12017
- this.onUpstreamListChanged
11787
+ this.onUpstreamListChanged,
11788
+ this.clientBridge
12018
11789
  );
12019
11790
  this.connections.set(ns, newConn);
12020
11791
  await this.refreshRoutesAndNotify();
@@ -12204,10 +11975,18 @@ var ConnectServer = class _ConnectServer {
12204
11975
  const topWinsDecisively = top !== void 0 && top.score >= minScore && (second === void 0 || top.score / (second.score || 1e-6) >= margin);
12205
11976
  if (!topWinsDecisively || !top) return this.handleDiscover(context);
12206
11977
  const existing = this.connections.get(top.namespace);
12207
- if (existing && existing.status === "connected") return this.handleDiscover(context);
11978
+ if (existing && existing.status === "connected") {
11979
+ const grew = !this.sessionActivated.has(top.namespace);
11980
+ this.sessionActivated.add(top.namespace);
11981
+ if (grew) {
11982
+ await this.notifyAllListsChanged();
11983
+ }
11984
+ return this.buildDiscoverOutput(context, top.namespace);
11985
+ }
12208
11986
  progress?.(`Auto-warming top candidate "${top.namespace}"`);
12209
11987
  const result = await this.activateOne(top.namespace, progress);
12210
11988
  if (result.ok) {
11989
+ this.sessionActivated.add(top.namespace);
12211
11990
  await this.refreshRoutesAndNotify();
12212
11991
  log("info", "Auto-warmed top-ranked server on discover", { namespace: top.namespace, score: top.score });
12213
11992
  }
@@ -12580,7 +12359,8 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
12580
12359
  const connection = await connectToUpstream(
12581
12360
  effectiveConfig,
12582
12361
  this.onUpstreamDisconnect,
12583
- this.onUpstreamListChanged
12362
+ this.onUpstreamListChanged,
12363
+ this.clientBridge
12584
12364
  );
12585
12365
  progress?.(`"${namespace}" loaded ${connection.tools.length} tools`);
12586
12366
  this.connections.set(namespace, connection);
@@ -12721,6 +12501,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
12721
12501
  let anyChanged = false;
12722
12502
  let anyError = false;
12723
12503
  let anyCapped = false;
12504
+ let advertisedGrew = false;
12724
12505
  const total = namespaces.length;
12725
12506
  let i = 0;
12726
12507
  for (const namespace of namespaces) {
@@ -12729,7 +12510,10 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
12729
12510
  const r = await this.activateOne(namespace, progress);
12730
12511
  results.push(r.message);
12731
12512
  if (r.isChanged) anyChanged = true;
12732
- if (r.ok) this.sessionActivated.add(namespace);
12513
+ if (r.ok) {
12514
+ if (!this.sessionActivated.has(namespace)) advertisedGrew = true;
12515
+ this.sessionActivated.add(namespace);
12516
+ }
12733
12517
  if (!r.ok) {
12734
12518
  if (r.capped) anyCapped = true;
12735
12519
  else anyError = true;
@@ -12743,7 +12527,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
12743
12527
  }
12744
12528
  if (anyChanged) {
12745
12529
  await this.refreshRoutesAndNotify();
12746
- } else if (filtersChanged) {
12530
+ } else if (filtersChanged || advertisedGrew) {
12747
12531
  await this.notifyAllListsChanged();
12748
12532
  }
12749
12533
  return {
@@ -12871,6 +12655,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
12871
12655
  let anyChanged = false;
12872
12656
  let anyError = false;
12873
12657
  let anyCapped = false;
12658
+ let advertisedGrew = false;
12874
12659
  let i = 0;
12875
12660
  for (const winner of winners) {
12876
12661
  i += 1;
@@ -12878,6 +12663,10 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
12878
12663
  const r = await this.activateOne(winner.namespace, progress);
12879
12664
  results.push(`${winner.namespace} (score ${winner.score.toFixed(2)}): ${r.message}`);
12880
12665
  if (r.isChanged) anyChanged = true;
12666
+ if (r.ok) {
12667
+ if (!this.sessionActivated.has(winner.namespace)) advertisedGrew = true;
12668
+ this.sessionActivated.add(winner.namespace);
12669
+ }
12881
12670
  if (!r.ok) {
12882
12671
  if (r.capped) anyCapped = true;
12883
12672
  else anyError = true;
@@ -12885,6 +12674,8 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
12885
12674
  }
12886
12675
  if (anyChanged) {
12887
12676
  await this.refreshRoutesAndNotify();
12677
+ } else if (advertisedGrew) {
12678
+ await this.notifyAllListsChanged();
12888
12679
  }
12889
12680
  const header = `Dispatched "${trimmed}" \u2014 loaded top ${winners.length} of ${ranked.length} matching server${ranked.length === 1 ? "" : "s"}.
12890
12681
  `;
@@ -13091,7 +12882,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13091
12882
  try {
13092
12883
  const elicitedForTransient = this.elicitedEnv.get(serverArg);
13093
12884
  const transientConfig = elicitedForTransient ? { ...serverConfig, env: { ...serverConfig.env, ...elicitedForTransient } } : serverConfig;
13094
- transient = await connectToUpstream(transientConfig);
12885
+ transient = await connectToUpstream(transientConfig, void 0, void 0, this.clientBridge);
13095
12886
  } catch (err) {
13096
12887
  const message = err instanceof ActivationError ? err.message : err instanceof Error ? err.message : String(err);
13097
12888
  return {
@@ -13849,6 +13640,22 @@ if (subcommand === "compliance") {
13849
13640
  stale global installs are upgraded in the
13850
13641
  background -- npm, pnpm, and bun globals alike).
13851
13642
  YAW_MCP_PRUNE_RESPONSES Set to \`0\` to disable response pruning.
13643
+ YAW_MCP_TOOL_EXPOSURE How much of the catalog tools/list advertises.
13644
+ \`gateway\` (default) exposes the meta-tools
13645
+ plus loaded servers only; \`full\` restores the
13646
+ pre-gateway behavior and inlines the whole
13647
+ catalog. Re-read per call -- a change lands on
13648
+ the next tools/list without a restart.
13649
+ YAW_MCP_ROUTE_EFFORT How hard dispatch tries to break ranking ties
13650
+ with the client LLM: \`off\` | \`auto\` |
13651
+ \`aggressive\` (default auto). The dispatch
13652
+ tool's \`routeEffort\` argument overrides this
13653
+ per call.
13654
+ YAW_MCP_REWARD_GRADER Set to \`1\` to OPT IN to the LLM reward
13655
+ grader: uncertain dispatch outcomes get a
13656
+ second opinion via client sampling. It spends
13657
+ the client's LLM budget and adds a round-trip,
13658
+ so it is off by default.
13852
13659
  YAW_MCP_IDLE_THRESHOLD Non-matching tool calls a loaded server
13853
13660
  tolerates before it is unloaded (default 10).
13854
13661
  Bursty servers earn more patience on top of
@@ -13897,6 +13704,9 @@ if (subcommand === "compliance") {
13897
13704
  only -- a server's own \`connectTimeoutMs\` in
13898
13705
  bundles.json always wins, so one slow server does
13899
13706
  not need the global ceiling raised.
13707
+ MCP_LIST_TIMEOUT Milliseconds to wait for a server's tool/
13708
+ resource/prompt inventory calls after the
13709
+ handshake (default 15000).
13900
13710
 
13901
13711
  Config resolution (highest precedence first) -- for the \`servers\` allow-list
13902
13712
  and \`blocked\` deny-list:
@@ -13918,7 +13728,7 @@ if (subcommand === "compliance") {
13918
13728
  `);
13919
13729
  process.exitCode = 0;
13920
13730
  } else if (subcommand === "--version" || subcommand === "-V") {
13921
- process.stdout.write(`yaw-mcp ${true ? "0.75.4" : "dev"}
13731
+ process.stdout.write(`yaw-mcp ${true ? "0.76.1" : "dev"}
13922
13732
  `);
13923
13733
  process.exitCode = 0;
13924
13734
  } else if (subcommand && !subcommand.startsWith("-")) {