@yawlabs/mcp 0.72.0 → 0.73.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.
Files changed (3) hide show
  1. package/README.md +147 -413
  2. package/dist/index.js +357 -137
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -523,7 +523,7 @@ async function doUpsertUserBundle(entry, opts) {
523
523
  else file.servers.push(entry);
524
524
  file.version = file.version ?? CURRENT_BUNDLES_SCHEMA_VERSION;
525
525
  await atomicWriteFile(path7, `${JSON.stringify(file, null, 2)}
526
- `, "utf8", 384);
526
+ `, "utf8", 384, 448);
527
527
  if (process.platform !== "win32") {
528
528
  try {
529
529
  await chmod2(path7, 384);
@@ -550,7 +550,7 @@ async function doRemoveUserBundle(namespace, opts) {
550
550
  if (file.servers.length === before) return { path: path7, removed: false };
551
551
  file.version = file.version ?? CURRENT_BUNDLES_SCHEMA_VERSION;
552
552
  await atomicWriteFile(path7, `${JSON.stringify(file, null, 2)}
553
- `, "utf8", 384);
553
+ `, "utf8", 384, 448);
554
554
  if (process.platform !== "win32") {
555
555
  try {
556
556
  await chmod2(path7, 384);
@@ -940,6 +940,18 @@ var CONFIG_FILENAME = "config.json";
940
940
  var LOCAL_CONFIG_FILENAME = "config.local.json";
941
941
  var CURRENT_SCHEMA_VERSION = 1;
942
942
  var DEFAULT_API_BASE = "https://yaw.sh/mcp";
943
+ function filterStringArray(raw, field, path7, warnings) {
944
+ if (!Array.isArray(raw)) return void 0;
945
+ const strings = raw.filter((v) => typeof v === "string");
946
+ const dropped = raw.length - strings.length;
947
+ if (dropped > 0) {
948
+ warnings.push(
949
+ `${path7}: '${field}' dropped ${dropped} non-string ${dropped === 1 ? "entry" : "entries"} -- only string namespaces are honored.`
950
+ );
951
+ }
952
+ if (strings.length === 0 && raw.length > 0) return void 0;
953
+ return strings;
954
+ }
943
955
  async function readConfigAt(path7, scope, warnings) {
944
956
  let raw;
945
957
  try {
@@ -979,16 +991,17 @@ async function readConfigAt(path7, scope, warnings) {
979
991
  apiBase = void 0;
980
992
  }
981
993
  }
982
- const servers = Array.isArray(obj.servers) ? obj.servers.filter((v) => typeof v === "string") : void 0;
983
- const blocked = Array.isArray(obj.blocked) ? obj.blocked.filter((v) => typeof v === "string") : void 0;
994
+ const servers = filterStringArray(obj.servers, "servers", path7, warnings);
995
+ const blocked = filterStringArray(obj.blocked, "blocked", path7, warnings);
984
996
  const installNudge = typeof obj.installNudge === "boolean" ? obj.installNudge : void 0;
985
997
  if (token5) {
986
998
  if (scope === "project") {
987
999
  warnings.push(
988
1000
  `${path7}: 'token' found in a project-shared config file is IGNORED -- yaw-mcp never reads a token from this scope to avoid committing credentials. Move it to ${CONFIG_DIRNAME}/${LOCAL_CONFIG_FILENAME} (machine-local, gitignore by convention) or ~/${CONFIG_DIRNAME}/${CONFIG_FILENAME} (user-global).`
989
1001
  );
1002
+ } else {
1003
+ await checkPermissions(path7, warnings);
990
1004
  }
991
- await checkPermissions(path7, warnings);
992
1005
  }
993
1006
  return { path: path7, scope, version, token: token5, apiBase, servers, blocked, installNudge };
994
1007
  }
@@ -1524,10 +1537,15 @@ var SUBCOMMAND_SPEC = [
1524
1537
  name: "secrets",
1525
1538
  description: "Manage stored secrets",
1526
1539
  positional: [["set", "get", "list", "remove", "lock", "rotate", "audit"], ["<name>"]],
1527
- flags: ["--value", "--stdin", "--secret", "--server", "--json", "--help"]
1540
+ flags: ["--value", "--stdin", "--force", "--secret", "--server", "--json", "--help"]
1528
1541
  },
1529
1542
  // Other.
1530
- { name: "audit", description: "Run a full-pass audit of loaded servers", flags: ["--json", "--help"] },
1543
+ {
1544
+ name: "audit",
1545
+ description: "Grade a stdio server against the compliance suite",
1546
+ positional: [["<namespace>"]],
1547
+ flags: ["--json", "--help"]
1548
+ },
1531
1549
  { name: "compliance", description: "Run the compliance suite against a server", flags: ["--publish", "--help"] },
1532
1550
  {
1533
1551
  name: "foundry",
@@ -1713,7 +1731,7 @@ function renderPowershell() {
1713
1731
  const caseBranches = SUBCOMMAND_SPEC.map((spec) => {
1714
1732
  const flags = spec.flags.map((f) => `'${f}'`).join(", ");
1715
1733
  const positionalLines = realPositionals(spec).map(
1716
- ({ candidates, index }) => ` if ($tokens.Count -eq ${index + 2}) { $completions += @(${candidates.map((c) => `'${c}'`).join(", ")}) }`
1734
+ ({ candidates, index }) => ` if ($argIndex -eq ${index}) { $completions += @(${candidates.map((c) => `'${c}'`).join(", ")}) }`
1717
1735
  ).join("\n");
1718
1736
  const positionalBlock = positionalLines ? `${positionalLines}
1719
1737
  ` : "";
@@ -1725,9 +1743,17 @@ ${positionalBlock} $completions += @(${flags})
1725
1743
  # Install: append this script to your profile ($PROFILE) and reload.
1726
1744
  Register-ArgumentCompleter -CommandName yaw-mcp -ScriptBlock {
1727
1745
  param($wordToComplete, $commandAst, $cursorPosition)
1728
- $tokens = $commandAst.CommandElements | ForEach-Object { $_.ToString() }
1746
+ $tokens = @($commandAst.CommandElements | ForEach-Object { $_.ToString() })
1729
1747
  $completions = @()
1730
- if ($tokens.Count -le 2) {
1748
+ # $argIndex is the normalized index of the positional being completed: 0 is
1749
+ # the first argument AFTER the subcommand. $tokens[0] is "yaw-mcp" and
1750
+ # $tokens[1] is the subcommand, hence -2. A partially typed word is already
1751
+ # one of $tokens, so back off one more when $wordToComplete is non-empty --
1752
+ # that keeps "install <TAB>" and "install cl<TAB>" both on slot 0. Negative
1753
+ # means the user is still on the subcommand itself.
1754
+ $argIndex = $tokens.Count - 2
1755
+ if ($wordToComplete -ne '') { $argIndex-- }
1756
+ if ($argIndex -lt 0) {
1731
1757
  $completions = @(${subcommandNames}, '--help', '-h', '--version', '-V')
1732
1758
  } else {
1733
1759
  switch ($tokens[1]) {
@@ -1809,6 +1835,20 @@ function quoteForShell(arg, platform) {
1809
1835
  if (arg.includes("'")) return null;
1810
1836
  return `'${arg}'`;
1811
1837
  }
1838
+ function unquotableCharsFor(platform) {
1839
+ return platform === "win32" ? "double quotes, percent signs, newlines or NUL bytes" : "single quotes, newlines or NUL bytes";
1840
+ }
1841
+ function formatLaunchFailure(npxArgs, platform = process.platform) {
1842
+ const offender = npxArgs.find((a) => quoteForShell(a, platform) === null);
1843
+ const detail = offender === void 0 ? "and the target arguments cannot be safely quoted for a shell fallback.\n" : (
1844
+ // JSON.stringify so a newline / NUL in the argument is shown escaped
1845
+ // instead of mangling the diagnostic it appears in.
1846
+ `and this argument cannot be safely quoted for a shell fallback: ${JSON.stringify(offender)}
1847
+ `
1848
+ );
1849
+ return "\nFailed to launch mcp-compliance: npm's npx-cli.js was not found next to this node binary,\n" + detail + `Install npm, or pass a target without ${unquotableCharsFor(platform)}.
1850
+ `;
1851
+ }
1812
1852
  function resolveNpxLaunch(npxArgs, opts = {}) {
1813
1853
  const execPath = opts.execPath ?? process.execPath;
1814
1854
  const platform = opts.platform ?? process.platform;
@@ -1868,9 +1908,7 @@ function runTest(args, err) {
1868
1908
  const npxArgs = ["-y", "@yawlabs/mcp-compliance", "test", "--format", "json", ...args];
1869
1909
  const launch = resolveNpxLaunch(npxArgs);
1870
1910
  if (!launch) {
1871
- fail(
1872
- "\nFailed to launch mcp-compliance: npm's npx-cli.js was not found next to this node binary,\nand the target arguments cannot be safely quoted for a shell fallback. Install npm, or pass\na target without quotes / newlines.\n"
1873
- );
1911
+ fail(formatLaunchFailure(npxArgs));
1874
1912
  return;
1875
1913
  }
1876
1914
  let child;
@@ -2228,6 +2266,7 @@ async function shutdownAnalytics() {
2228
2266
  for (let i = 0; i < 3 && dispatchBuffer.length > 0; i++) {
2229
2267
  await flushDispatch();
2230
2268
  }
2269
+ droppedEvents += buffer.length + dispatchBuffer.length;
2231
2270
  buffer.length = 0;
2232
2271
  dispatchBuffer.length = 0;
2233
2272
  }
@@ -2458,6 +2497,7 @@ function rewriteForOam(command, args, deps) {
2458
2497
  if (command === "node") {
2459
2498
  const [entry, ...rest] = args;
2460
2499
  if (!entry) return { command, args };
2500
+ if (entry.startsWith("-")) return { command, args };
2461
2501
  return toOam(entry, rest);
2462
2502
  }
2463
2503
  if (command === "npx") {
@@ -3196,20 +3236,22 @@ ${USAGE}`);
3196
3236
  const writeYawMcpConfig = !opts.skipYawMcpConfig && token5 !== null;
3197
3237
  const home = opts.home ?? homedir7();
3198
3238
  const yawMcpConfigPath = join8(home, CONFIG_DIRNAME, CONFIG_FILENAME);
3199
- const yawMcpConfigComposed = writeYawMcpConfig ? await composeYawMcpConfig(yawMcpConfigPath, token5) : { json: "" };
3239
+ const yawMcpConfigComposed = writeYawMcpConfig ? await composeYawMcpConfig(yawMcpConfigPath, token5, opts.dryRun ?? false) : { json: "" };
3200
3240
  if ("backupPath" in yawMcpConfigComposed && yawMcpConfigComposed.backupPath) {
3201
3241
  const reason = yawMcpConfigComposed.backupReason;
3242
+ const backedUp = opts.dryRun ? "would be backed up" : "backed up";
3243
+ const preserved = opts.dryRun ? "would be preserved" : "preserved";
3202
3244
  if (reason === "malformed") {
3203
3245
  log2(
3204
- `yaw-mcp install: existing ${yawMcpConfigPath} was malformed; backed up to ${yawMcpConfigComposed.backupPath} before overwriting (original bytes preserved for recovery).`
3246
+ `yaw-mcp install: existing ${yawMcpConfigPath} was malformed; ${backedUp} to ${yawMcpConfigComposed.backupPath} before overwriting (original bytes ${preserved} for recovery).`
3205
3247
  );
3206
3248
  } else if (reason === "token-rotation") {
3207
3249
  log2(
3208
- `yaw-mcp install: existing ${yawMcpConfigPath} backed up before token rotation to ${yawMcpConfigComposed.backupPath} (previous token preserved for recovery).`
3250
+ `yaw-mcp install: existing ${yawMcpConfigPath} ${backedUp} before token rotation to ${yawMcpConfigComposed.backupPath} (previous token ${preserved} for recovery).`
3209
3251
  );
3210
3252
  } else {
3211
3253
  log2(
3212
- `yaw-mcp install: existing ${yawMcpConfigPath} was not a JSON object; backed up to ${yawMcpConfigComposed.backupPath} before overwriting (original bytes preserved for recovery).`
3254
+ `yaw-mcp install: existing ${yawMcpConfigPath} was not a JSON object; ${backedUp} to ${yawMcpConfigComposed.backupPath} before overwriting (original bytes ${preserved} for recovery).`
3213
3255
  );
3214
3256
  }
3215
3257
  }
@@ -3221,6 +3263,11 @@ ${USAGE}`);
3221
3263
  os,
3222
3264
  claudeConfigDir: opts.claudeConfigDir
3223
3265
  }) : null;
3266
+ if (settingsPatch?.malformed) {
3267
+ err(
3268
+ `yaw-mcp install: warning \u2014 could not patch ${settingsPatch.path} (${settingsPatch.malformedReason}); left unchanged. Add "${CLAUDE_CODE_ALLOW_PATTERN}" to permissions.allow by hand, or you may be re-prompted for each yaw-mcp tool call.`
3269
+ );
3270
+ }
3224
3271
  if (opts.dryRun) {
3225
3272
  log2("\n--- dry run: would write the following ---");
3226
3273
  if (writeYawMcpConfig) log2(`# ${yawMcpConfigPath}
@@ -3304,11 +3351,11 @@ async function prepareClaudeCodeSettingsPatch(opts) {
3304
3351
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3305
3352
  existing = parsed;
3306
3353
  } else {
3307
- return { path: path7, nextJson: "", changed: false };
3354
+ return { path: path7, nextJson: "", changed: false, malformed: true, malformedReason: "not a JSON object" };
3308
3355
  }
3309
3356
  }
3310
- } catch {
3311
- return { path: path7, nextJson: "", changed: false };
3357
+ } catch (e) {
3358
+ return { path: path7, nextJson: "", changed: false, malformed: true, malformedReason: e.message };
3312
3359
  }
3313
3360
  }
3314
3361
  const merged = mergePermissionsAllow(existing, [CLAUDE_CODE_ALLOW_PATTERN]);
@@ -3376,8 +3423,9 @@ function mergeClientConfig(existing, containerPath, entry, entryName = ENTRY_NAM
3376
3423
  parent[leafKey] = container;
3377
3424
  return out;
3378
3425
  }
3379
- async function writeBackup(path7, raw) {
3426
+ async function writeBackup(path7, raw, dryRun = false) {
3380
3427
  const candidate = `${path7}.bak-${Date.now()}`;
3428
+ if (dryRun) return candidate;
3381
3429
  try {
3382
3430
  await atomicWriteFile(candidate, raw, "utf8", 384);
3383
3431
  if (process.platform !== "win32") {
@@ -3391,7 +3439,7 @@ async function writeBackup(path7, raw) {
3391
3439
  return void 0;
3392
3440
  }
3393
3441
  }
3394
- async function composeYawMcpConfig(path7, token5) {
3442
+ async function composeYawMcpConfig(path7, token5, dryRun = false) {
3395
3443
  let existing = {};
3396
3444
  let backupPath;
3397
3445
  let backupReason;
@@ -3409,15 +3457,15 @@ async function composeYawMcpConfig(path7, token5) {
3409
3457
  existing = parsed;
3410
3458
  const existingToken = existing.token;
3411
3459
  if (typeof existingToken === "string" && existingToken.length > 0 && existingToken !== token5) {
3412
- backupPath = await writeBackup(path7, raw);
3460
+ backupPath = await writeBackup(path7, raw, dryRun);
3413
3461
  if (backupPath) backupReason = "token-rotation";
3414
3462
  }
3415
3463
  } else {
3416
- backupPath = await writeBackup(path7, raw);
3464
+ backupPath = await writeBackup(path7, raw, dryRun);
3417
3465
  if (backupPath) backupReason = "non-object";
3418
3466
  }
3419
3467
  } catch {
3420
- backupPath = await writeBackup(path7, raw);
3468
+ backupPath = await writeBackup(path7, raw, dryRun);
3421
3469
  if (backupPath) backupReason = "malformed";
3422
3470
  }
3423
3471
  }
@@ -3455,13 +3503,13 @@ function parseInstallArgs(argv) {
3455
3503
  }
3456
3504
  case "--token": {
3457
3505
  const v = next();
3458
- if (!v) return { ok: false, error: "--token requires a value" };
3506
+ if (!v || v.startsWith("--")) return { ok: false, error: "--token requires a value" };
3459
3507
  opts.token = v;
3460
3508
  break;
3461
3509
  }
3462
3510
  case "--project-dir": {
3463
3511
  const v = next();
3464
- if (!v) return { ok: false, error: "--project-dir requires a value" };
3512
+ if (!v || v.startsWith("--")) return { ok: false, error: "--project-dir requires a value" };
3465
3513
  opts.projectDir = v;
3466
3514
  break;
3467
3515
  }
@@ -3709,8 +3757,11 @@ function parseTryArgs(argv) {
3709
3757
  switch (a) {
3710
3758
  case "--client": {
3711
3759
  const v = next();
3712
- if (!v || !["claude-code", "claude-desktop", "cursor", "vscode"].includes(v)) {
3713
- return { ok: false, error: "--client requires claude-code|claude-desktop|cursor|vscode" };
3760
+ if (!v || !INSTALL_TARGETS.some((t) => t.clientId === v)) {
3761
+ return {
3762
+ ok: false,
3763
+ error: `--client requires ${INSTALL_TARGETS.map((t) => t.clientId).join("|")}`
3764
+ };
3714
3765
  }
3715
3766
  opts.clientId = v;
3716
3767
  break;
@@ -3882,7 +3933,7 @@ async function autoDetectClient(opts) {
3882
3933
  for (const p of probes) {
3883
3934
  if (!p.unavailable) return p.clientId;
3884
3935
  }
3885
- return "claude-code";
3936
+ throw new Error("autoDetectClient: no available install client for this OS");
3886
3937
  }
3887
3938
  async function runTry(opts) {
3888
3939
  const out = opts.out ?? ((s) => process.stdout.write(s));
@@ -4035,10 +4086,12 @@ async function runTry(opts) {
4035
4086
  printErr(`yaw-mcp try: failed to write trial marker: ${e.message}`);
4036
4087
  return { exitCode: 1, written: [] };
4037
4088
  }
4089
+ const entryHasSecrets = entry.env !== void 0 && Object.keys(entry.env).length > 0;
4090
+ const tightenPerms = entryHasSecrets && process.platform !== "win32";
4038
4091
  try {
4039
- await atomicWriteFile(resolved.absolute, clientJson);
4092
+ await atomicWriteFile(resolved.absolute, clientJson, "utf8", tightenPerms ? 384 : void 0);
4040
4093
  written.push(resolved.absolute);
4041
- if (!clientPreExisted && entry.env && Object.keys(entry.env).length > 0 && process.platform !== "win32") {
4094
+ if (tightenPerms) {
4042
4095
  try {
4043
4096
  await chmod4(resolved.absolute, 384);
4044
4097
  } catch {
@@ -4179,7 +4232,7 @@ async function gcExpiredTrials(opts) {
4179
4232
  const env = opts.env ?? process.env;
4180
4233
  const baseUrl = opts.baseUrl ?? env.YAW_MCP_BASE_URL ?? DEFAULT_BASE_URL;
4181
4234
  const postEvent = opts.postEvent ?? defaultPostEvent;
4182
- const scan = await scanTrials({ home, now: opts.now });
4235
+ const scan = opts.scan ?? await scanTrials({ home, now: opts.now });
4183
4236
  if (scan.expired.length === 0) return { cleared: 0, failed: 0 };
4184
4237
  const anonId = await loadOrCreateAnonId(home);
4185
4238
  let cleared = 0;
@@ -4530,7 +4583,7 @@ async function runUpgrade(opts = {}) {
4530
4583
  return { exitCode: 3, lines };
4531
4584
  }
4532
4585
  function readCurrentVersion() {
4533
- return true ? "0.72.0" : "dev";
4586
+ return true ? "0.73.1" : "dev";
4534
4587
  }
4535
4588
 
4536
4589
  // src/learning.ts
@@ -4557,7 +4610,7 @@ var LearningStore = class {
4557
4610
  recordSuccess(namespace) {
4558
4611
  const prev = this.usage.get(namespace);
4559
4612
  this.usage.set(namespace, {
4560
- dispatched: prev?.dispatched ?? 1,
4613
+ dispatched: prev?.dispatched ?? 0,
4561
4614
  succeeded: (prev?.succeeded ?? 0) + 1,
4562
4615
  lastUsedAt: Date.now()
4563
4616
  });
@@ -4732,7 +4785,7 @@ function selectFlakyNamespaces(entries, limit) {
4732
4785
  }
4733
4786
 
4734
4787
  // src/doctor-cmd.ts
4735
- var VERSION = true ? "0.72.0" : "dev";
4788
+ var VERSION = true ? "0.73.1" : "dev";
4736
4789
  function isPersistenceDisabled(env) {
4737
4790
  const raw = env.YAW_MCP_DISABLE_PERSISTENCE;
4738
4791
  return raw !== void 0 && raw !== "" && (raw === "1" || raw.toLowerCase() === "true");
@@ -4951,11 +5004,14 @@ async function runDoctorJson(opts) {
4951
5004
  }
4952
5005
  }
4953
5006
  const shellShadows = scanShellHistoryForShadows({ home, env });
4954
- const trialGc = await gcExpiredTrials({ home, env, postEvent: opts.postTryEvent, now: opts.now }).catch(() => ({
4955
- cleared: 0,
4956
- failed: 0
4957
- }));
4958
5007
  const trialScan = await scanTrials({ home, now: opts.now });
5008
+ const trialGc = await gcExpiredTrials({
5009
+ home,
5010
+ env,
5011
+ postEvent: opts.postTryEvent,
5012
+ now: opts.now,
5013
+ scan: trialScan
5014
+ }).catch(() => ({ cleared: 0, failed: 0 }));
4959
5015
  const trials = {
4960
5016
  cleared: trialGc.cleared,
4961
5017
  live: trialScan.live.map(({ marker, msUntilExpiry }) => ({
@@ -5176,8 +5232,8 @@ function renderReliabilitySection(opts) {
5176
5232
  }
5177
5233
  async function renderTrialsSection(opts) {
5178
5234
  const { home, env, print, postEvent, now } = opts;
5179
- const gc = await gcExpiredTrials({ home, env, postEvent, now }).catch(() => ({ cleared: 0, failed: 0 }));
5180
5235
  const scan = await scanTrials({ home, now });
5236
+ const gc = await gcExpiredTrials({ home, env, postEvent, now, scan }).catch(() => ({ cleared: 0, failed: 0 }));
5181
5237
  if (scan.live.length === 0 && gc.cleared === 0 && scan.malformed.length === 0) return;
5182
5238
  print("TRIALS (yaw-mcp try)");
5183
5239
  if (gc.cleared > 0) {
@@ -6278,7 +6334,7 @@ import { homedir as homedir16 } from "os";
6278
6334
 
6279
6335
  // src/secrets-audit.ts
6280
6336
  import { existsSync as existsSync7 } from "fs";
6281
- import { appendFile as appendFile2, chmod as chmod5, readFile as readFile9, stat as stat5, writeFile as writeFile2 } from "fs/promises";
6337
+ import { appendFile as appendFile2, chmod as chmod5, readFile as readFile9, stat as stat5 } from "fs/promises";
6282
6338
  import { homedir as homedir14 } from "os";
6283
6339
  import { join as join12 } from "path";
6284
6340
  var SECRETS_AUDIT_FILENAME = "secrets-audit.log";
@@ -6298,7 +6354,7 @@ async function appendAuditEvent(input, home = homedir14()) {
6298
6354
  const line = `${JSON.stringify(event)}
6299
6355
  `;
6300
6356
  if (!existsSync7(path7)) {
6301
- await atomicWriteFile(path7, line);
6357
+ await atomicWriteFile(path7, line, "utf8", 384, 448);
6302
6358
  } else {
6303
6359
  await appendFile2(path7, line, "utf8");
6304
6360
  }
@@ -6317,8 +6373,8 @@ async function trimToTailCap(path7) {
6317
6373
  const lines = raw.split("\n").filter((l) => l.length > 0);
6318
6374
  if (lines.length <= AUDIT_TAIL_CAP) return;
6319
6375
  const kept = lines.slice(lines.length - AUDIT_TAIL_CAP);
6320
- await writeFile2(path7, `${kept.join("\n")}
6321
- `, "utf8");
6376
+ await atomicWriteFile(path7, `${kept.join("\n")}
6377
+ `, "utf8", 384);
6322
6378
  }
6323
6379
  async function readAuditLog(filter = {}, home = homedir14()) {
6324
6380
  const path7 = auditLogPath(home);
@@ -6446,6 +6502,14 @@ async function loadVault(path7) {
6446
6502
  if (typeof obj.salt !== "string" || !obj.entries || typeof obj.entries !== "object") {
6447
6503
  throw new Error(`vault at ${path7} is corrupt: missing or invalid salt/entries`);
6448
6504
  }
6505
+ if (Buffer.from(obj.salt, "base64").length !== SALT_LEN) {
6506
+ throw new Error(`vault at ${path7} is corrupt: salt (expected ${SALT_LEN} bytes)`);
6507
+ }
6508
+ if (typeof obj.version === "number" && obj.version > SECRETS_SCHEMA_VERSION) {
6509
+ throw new Error(
6510
+ `vault at ${path7} was written by a newer yaw-mcp (schema version ${obj.version} > ${SECRETS_SCHEMA_VERSION}); upgrade yaw-mcp to read it`
6511
+ );
6512
+ }
6449
6513
  const entries = obj.entries;
6450
6514
  for (const [name, entry] of Object.entries(entries)) {
6451
6515
  if (!isEncryptedEntry(entry)) {
@@ -6641,14 +6705,19 @@ var SECRETS_USAGE = `Usage: yaw-mcp secrets <action> [args]
6641
6705
  Actions:
6642
6706
  set <name> Store a secret. Reads value from stdin (one
6643
6707
  line, no echo). Override with --value <v> or
6644
- --stdin (raw, multi-line) for scripting.
6708
+ --stdin (raw, multi-line) for scripting. Setting
6709
+ a name that already exists REPLACES it (confirmed
6710
+ first on a TTY; scripted runs proceed and say
6711
+ "Replaced" instead of "Stored").
6645
6712
  get <name> Decrypt and print one secret value to stdout.
6646
6713
  NOTE: this prints the secret in CLEARTEXT (with
6647
6714
  or without --json). Redirect to a file or pipe
6648
6715
  to a consumer; avoid running it interactively so
6649
6716
  the value does not land in terminal scrollback.
6650
6717
  list Show vault entry names (values stay encrypted).
6651
- remove <name> Delete an entry.
6718
+ remove <name> Delete an entry. Unrecoverable, so it asks you
6719
+ to confirm on a TTY (bare Enter = no) and refuses
6720
+ without --force when there is no TTY to ask on.
6652
6721
  lock Forget the passphrase cached in THIS process's
6653
6722
  memory. The cache never outlives the process, so
6654
6723
  for a one-shot CLI run this is close to a no-op --
@@ -6673,6 +6742,11 @@ Flags:
6673
6742
  --value <v> Inline secret value (set only). Beware shell
6674
6743
  history -- prefer the default stdin prompt.
6675
6744
  --stdin Read the secret from raw stdin (set only).
6745
+ --force Skip the destructive-action confirmation
6746
+ (remove, and a set that overwrites an existing
6747
+ name). Required for remove when stdin or stdout
6748
+ is not a TTY (both ends are needed to ask). NEVER
6749
+ skips the passphrase.
6676
6750
  --secret <name> (audit only) Filter to one secret name.
6677
6751
  --server <ns> (audit only) Filter to one server namespace.
6678
6752
 
@@ -6696,6 +6770,10 @@ function parseSecretsArgs(argv) {
6696
6770
  opts.fromStdin = true;
6697
6771
  continue;
6698
6772
  }
6773
+ if (a === "--force") {
6774
+ opts.force = true;
6775
+ continue;
6776
+ }
6699
6777
  if (a === "--value") {
6700
6778
  const v = argv[++i];
6701
6779
  if (v === void 0 || v.startsWith("-")) {
@@ -6757,6 +6835,14 @@ ${SECRETS_USAGE}` };
6757
6835
 
6758
6836
  ${SECRETS_USAGE}` };
6759
6837
  }
6838
+ if (opts.action === "set" && opts.name !== void 0 && !SECRET_NAME_RE.test(opts.name)) {
6839
+ return {
6840
+ ok: false,
6841
+ error: `yaw-mcp secrets set: invalid secret name "${opts.name}" -- use letters, digits, "_", "." or "-" only; other characters can never be referenced as \${secret:NAME}
6842
+
6843
+ ${SECRETS_USAGE}`
6844
+ };
6845
+ }
6760
6846
  return { ok: true, options: opts };
6761
6847
  }
6762
6848
  async function safeLoadVault(path7, io, json, action) {
@@ -6783,7 +6869,40 @@ function cancelledResult(io, json) {
6783
6869
  `);
6784
6870
  return { exitCode: 130 };
6785
6871
  }
6786
- async function resolvePassphrase(opts) {
6872
+ function abortedResult(io, json, action) {
6873
+ const msg = "Aborted.";
6874
+ if (json) io.err(`${JSON.stringify({ ok: false, error: msg, aborted: true })}
6875
+ `);
6876
+ else io.err(`yaw-mcp secrets ${action}: ${msg}
6877
+ `);
6878
+ return { exitCode: 1 };
6879
+ }
6880
+ function ttyEnds(opts) {
6881
+ const stdin = opts.io?.stdin ?? process.stdin;
6882
+ const stdout = opts.io?.stdout ?? process.stdout;
6883
+ return {
6884
+ stdin: stdin.isTTY === true,
6885
+ stdout: stdout.isTTY === true
6886
+ };
6887
+ }
6888
+ function isInteractiveTTY(opts) {
6889
+ const ends = ttyEnds(opts);
6890
+ return ends.stdin && ends.stdout;
6891
+ }
6892
+ function nonTTYEnds(opts) {
6893
+ const ends = ttyEnds(opts);
6894
+ if (!ends.stdin && !ends.stdout) return "neither stdin nor stdout is a TTY";
6895
+ return ends.stdin ? "stdout is not a TTY" : "stdin is not a TTY";
6896
+ }
6897
+ async function promptYesNo(opts, question) {
6898
+ const stdin = opts.io?.stdin ?? process.stdin;
6899
+ const stdout = opts.io?.stdout ?? process.stdout;
6900
+ const answer = await readLineFromTTY(stdin, stdout, `${question} [y/N] `, true);
6901
+ if (answer === CANCELLED) return CANCELLED;
6902
+ const a = answer.trim().toLowerCase();
6903
+ return a === "y" || a === "yes";
6904
+ }
6905
+ async function resolvePassphrase(opts, confirm = false) {
6787
6906
  if (opts.passphrase !== void 0) return opts.passphrase.length > 0 ? opts.passphrase : null;
6788
6907
  const fromEnv = process.env.YAW_MCP_VAULT_PASSPHRASE;
6789
6908
  if (typeof fromEnv === "string" && fromEnv.length > 0) {
@@ -6798,10 +6917,24 @@ async function resolvePassphrase(opts) {
6798
6917
  }
6799
6918
  const stdin = opts.io?.stdin ?? process.stdin;
6800
6919
  const stdout = opts.io?.stdout ?? process.stdout;
6801
- const isTTY = stdin.isTTY === true && stdout.isTTY === true;
6802
- if (!isTTY) return null;
6920
+ if (!isInteractiveTTY(opts)) return null;
6921
+ if (confirm) {
6922
+ for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
6923
+ const first = await readLineFromTTY(stdin, stdout, "Vault passphrase: ");
6924
+ if (first === CANCELLED) return CANCELLED;
6925
+ if (first.length === 0) {
6926
+ stdout.write("Passphrase cannot be empty.\n");
6927
+ continue;
6928
+ }
6929
+ const second = await readLineFromTTY(stdin, stdout, "Confirm passphrase: ");
6930
+ if (second === CANCELLED) return CANCELLED;
6931
+ if (first === second) return first;
6932
+ stdout.write("Passphrases did not match. Try again.\n");
6933
+ }
6934
+ return null;
6935
+ }
6803
6936
  for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
6804
- const entered = await readPassphraseFromTTY(stdin, stdout);
6937
+ const entered = await readLineFromTTY(stdin, stdout);
6805
6938
  if (entered === CANCELLED) return CANCELLED;
6806
6939
  if (entered.length > 0) return entered;
6807
6940
  stdout.write("Passphrase cannot be empty.\n");
@@ -6823,16 +6956,15 @@ async function resolveNewPassphrase(opts) {
6823
6956
  }
6824
6957
  const stdin = opts.io?.stdin ?? process.stdin;
6825
6958
  const stdout = opts.io?.stdout ?? process.stdout;
6826
- const isTTY = stdin.isTTY === true && stdout.isTTY === true;
6827
- if (!isTTY) return null;
6959
+ if (!isInteractiveTTY(opts)) return null;
6828
6960
  for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
6829
- const first = await readPassphraseFromTTY(stdin, stdout, "New vault passphrase: ");
6961
+ const first = await readLineFromTTY(stdin, stdout, "New vault passphrase: ");
6830
6962
  if (first === CANCELLED) return CANCELLED;
6831
6963
  if (first.length === 0) {
6832
6964
  stdout.write("Passphrase cannot be empty.\n");
6833
6965
  continue;
6834
6966
  }
6835
- const second = await readPassphraseFromTTY(stdin, stdout, "Confirm new passphrase: ");
6967
+ const second = await readLineFromTTY(stdin, stdout, "Confirm new passphrase: ");
6836
6968
  if (second === CANCELLED) return CANCELLED;
6837
6969
  if (first === second) return first;
6838
6970
  stdout.write("Passphrases did not match. Try again.\n");
@@ -6844,7 +6976,7 @@ var MIN_PASSPHRASE_WARN_LEN = 12;
6844
6976
  var CTRL_C = "";
6845
6977
  var CTRL_D = "";
6846
6978
  var DEL = "\x7F";
6847
- function readPassphraseFromTTY(stdin, stdout, prompt = "Vault passphrase: ") {
6979
+ function readLineFromTTY(stdin, stdout, prompt = "Vault passphrase: ", echo = false) {
6848
6980
  stdout.write(prompt);
6849
6981
  return new Promise((resolve7) => {
6850
6982
  const chunks = [];
@@ -6880,10 +7012,15 @@ function readPassphraseFromTTY(stdin, stdout, prompt = "Vault passphrase: ") {
6880
7012
  return;
6881
7013
  }
6882
7014
  if (ch === "\b" || ch === DEL) {
6883
- if (chunks.length > 0) chunks.pop();
7015
+ if (chunks.length > 0) {
7016
+ chunks.pop();
7017
+ if (echo) stdout.write("\b \b");
7018
+ }
6884
7019
  continue;
6885
7020
  }
7021
+ if (ch < " ") continue;
6886
7022
  chunks.push(ch);
7023
+ if (echo) stdout.write(ch);
6887
7024
  }
6888
7025
  }
6889
7026
  stdin.on("data", onData);
@@ -6894,8 +7031,7 @@ async function readStdinValue(io, forceRaw) {
6894
7031
  const stdout = io?.stdout ?? process.stdout;
6895
7032
  const isTTY = stdin.isTTY === true;
6896
7033
  if (isTTY && !forceRaw) {
6897
- stdout.write("Secret value: ");
6898
- return readPassphraseFromTTY(stdin, stdout);
7034
+ return readLineFromTTY(stdin, stdout, "Secret value: ");
6899
7035
  }
6900
7036
  const chunks = [];
6901
7037
  stdin.setEncoding("utf8");
@@ -6953,9 +7089,35 @@ async function runSecrets(opts, io = {
6953
7089
  return { exitCode: 1 };
6954
7090
  }
6955
7091
  }
7092
+ const replacing = opts.action === "set" && loaded.vault !== null && Object.hasOwn(loaded.vault.entries, opts.name);
7093
+ if (opts.action === "remove" && !opts.force) {
7094
+ if (isInteractiveTTY(opts)) {
7095
+ const confirmed = await promptYesNo(opts, `Permanently delete secret "${opts.name}"? This cannot be undone.`);
7096
+ if (confirmed === CANCELLED) return cancelledResult(io, opts.json);
7097
+ if (!confirmed) return abortedResult(io, opts.json, "remove");
7098
+ } else {
7099
+ const msg = `refusing to delete "${opts.name}" without confirmation and ${nonTTYEnds(opts)}.`;
7100
+ const hint = "Re-run with --force to delete it. This cannot be undone.";
7101
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: `${msg} ${hint}` })}
7102
+ `);
7103
+ else io.err(`yaw-mcp secrets remove: ${msg}
7104
+ ${hint}
7105
+ `);
7106
+ return { exitCode: 2 };
7107
+ }
7108
+ }
7109
+ if (replacing && !opts.force && isInteractiveTTY(opts)) {
7110
+ const confirmed = await promptYesNo(
7111
+ opts,
7112
+ `Secret "${opts.name}" already exists. Replace it? The stored value is overwritten.`
7113
+ );
7114
+ if (confirmed === CANCELLED) return cancelledResult(io, opts.json);
7115
+ if (!confirmed) return abortedResult(io, opts.json, "set");
7116
+ }
6956
7117
  let vault = loaded.vault ?? newVault();
6957
7118
  const isFresh = !existsSync8(path7);
6958
- const passphrase = await resolvePassphrase(opts);
7119
+ const creatingVault = opts.action === "set" && !vault.check && Object.keys(vault.entries).length === 0;
7120
+ const passphrase = await resolvePassphrase(opts, creatingVault);
6959
7121
  if (passphrase === CANCELLED) return cancelledResult(io, opts.json);
6960
7122
  if (passphrase === null) {
6961
7123
  const msg = "Passphrase required. Set YAW_MCP_VAULT_PASSPHRASE or run from a TTY so we can prompt.";
@@ -7004,7 +7166,9 @@ async function runSecrets(opts, io = {
7004
7166
  return { exitCode: 1 };
7005
7167
  }
7006
7168
  await saveVault(path7, vault);
7007
- if (opts.json) io.out(`${JSON.stringify({ ok: true, name, fresh_vault: isFresh })}
7169
+ if (opts.json) io.out(`${JSON.stringify({ ok: true, name, fresh_vault: isFresh, replaced: replacing })}
7170
+ `);
7171
+ else if (replacing) io.out(`Replaced secret "${name}".
7008
7172
  `);
7009
7173
  else io.out(`${isFresh ? "Created vault and " : ""}Stored secret "${name}".
7010
7174
  `);
@@ -7293,7 +7457,7 @@ function defaultSpawn2(cmd, args) {
7293
7457
  async function maybeAutoUpgrade(deps = {}) {
7294
7458
  const optOut = process.env.YAW_MCP_AUTO_UPGRADE;
7295
7459
  if (optOut === "0" || optOut?.toLowerCase() === "false") return;
7296
- const current = deps.currentVersion ?? (true ? "0.72.0" : "dev");
7460
+ const current = deps.currentVersion ?? (true ? "0.73.1" : "dev");
7297
7461
  if (current === "dev") return;
7298
7462
  const method = (deps.isSeaImpl ? await deps.isSeaImpl() : await detectSea()) ? "binary" : detectInstallMethod(deps.argvPath ?? process.argv[1]);
7299
7463
  const latest = await (deps.fetchLatestImpl ?? fetchLatestVersion2)();
@@ -7523,7 +7687,7 @@ function classifyError(text) {
7523
7687
  if (RX_HTTP_429.test(t) || t.includes("rate limit") || t.includes("too many requests")) {
7524
7688
  return "rate_limited";
7525
7689
  }
7526
- if (RX_HTTP_401.test(t) || RX_HTTP_403.test(t) || t.includes("unauthorized") || t.includes("forbidden") || t.includes("permission denied") || RX_NO_TOKEN.test(text)) {
7690
+ if (RX_HTTP_401.test(t) || RX_HTTP_403.test(t) || t.includes("unauthorized") || t.includes("forbidden") || t.includes("permission denied") || RX_NO_TOKEN.test(t)) {
7527
7691
  return "unauthorized";
7528
7692
  }
7529
7693
  if (RX_HTTP_404.test(t) || t.includes("not found")) {
@@ -7881,6 +8045,7 @@ function renderActiveServersSection(activeServers) {
7881
8045
  var ACTIVATION_FAILURE_TTL_MS = 5 * 60 * 1e3;
7882
8046
  var OBSERVATION_FLOOR = 3;
7883
8047
  var MIN_FACTOR = 0.5;
8048
+ var WARN_RATE_FLOOR = 0.1;
7884
8049
  function errorRateFactor(health) {
7885
8050
  if (!health) return 1;
7886
8051
  if (health.totalCalls < OBSERVATION_FLOOR) return 1;
@@ -7904,7 +8069,7 @@ function formatHealthWarning(health, activationFailure, now = Date.now()) {
7904
8069
  }
7905
8070
  if (health && health.totalCalls >= OBSERVATION_FLOOR) {
7906
8071
  const rate = health.errorCount / health.totalCalls;
7907
- if (rate >= 0.3) {
8072
+ if (rate >= WARN_RATE_FLOOR) {
7908
8073
  const lastErr = health.lastErrorMessage ? `: ${truncateForWarning(health.lastErrorMessage)}` : "";
7909
8074
  return `warn: ${health.errorCount} of last ${health.totalCalls} calls failed${lastErr}`;
7910
8075
  }
@@ -9804,8 +9969,10 @@ async function extractArchive(archivePath, destDir) {
9804
9969
  ["archivePath", archivePath],
9805
9970
  ["destDir", destDir]
9806
9971
  ]) {
9807
- if (/['\r\n]/.test(p)) {
9808
- throw new Error(`Refusing to extract uv archive: ${label} contains a quote or newline (${JSON.stringify(p)})`);
9972
+ if (/[\r\n‘’‚‛]/.test(p)) {
9973
+ throw new Error(
9974
+ `Refusing to extract uv archive: ${label} contains a newline or smart quote (${JSON.stringify(p)})`
9975
+ );
9809
9976
  }
9810
9977
  }
9811
9978
  await runCommand("powershell.exe", [
@@ -9954,14 +10121,14 @@ async function resolveServerEnv(env, namespace) {
9954
10121
  return resolved;
9955
10122
  }
9956
10123
  async function recordResolveAudit(namespace, env, missing) {
9957
- const missingSet = new Set(missing);
9958
- const referenced = collectSecretNames(env);
9959
- for (const name of referenced) {
9960
- if (missingSet.has(name)) continue;
9961
- await appendAuditEvent({ server: namespace, secret: name, event: "injected" });
10124
+ if (missing.length > 0) {
10125
+ for (const name of new Set(missing)) {
10126
+ await appendAuditEvent({ server: namespace, secret: name, event: "missing" });
10127
+ }
10128
+ return;
9962
10129
  }
9963
- for (const name of missingSet) {
9964
- await appendAuditEvent({ server: namespace, secret: name, event: "missing" });
10130
+ for (const name of collectSecretNames(env)) {
10131
+ await appendAuditEvent({ server: namespace, secret: name, event: "injected" });
9965
10132
  }
9966
10133
  }
9967
10134
  function collectSecretNames(env) {
@@ -10003,7 +10170,10 @@ var ActivationError = class extends Error {
10003
10170
  };
10004
10171
  function redactSecretsInOutput(text, env) {
10005
10172
  let out = text;
10006
- for (const [k, v] of Object.entries(env)) {
10173
+ const entries = Object.entries(env).sort(
10174
+ ([, a], [, b]) => (typeof b === "string" ? b.length : 0) - (typeof a === "string" ? a.length : 0)
10175
+ );
10176
+ for (const [k, v] of entries) {
10007
10177
  if (typeof v !== "string" || v.length < 8) continue;
10008
10178
  if (v.startsWith("${secret:") && v.endsWith("}")) continue;
10009
10179
  const escaped = v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -10037,7 +10207,7 @@ async function connectToUpstream(config, onDisconnect, onListChanged) {
10037
10207
  }
10038
10208
  async function connectToUpstreamOnce(config, onDisconnect, onListChanged, attempt, disableOamRewrite) {
10039
10209
  const client = new Client(
10040
- { name: "yaw-mcp", version: true ? "0.72.0" : "dev" },
10210
+ { name: "yaw-mcp", version: true ? "0.73.1" : "dev" },
10041
10211
  { capabilities: {} }
10042
10212
  );
10043
10213
  let transport;
@@ -10142,17 +10312,23 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, attemp
10142
10312
  });
10143
10313
  try {
10144
10314
  const connection = { status: "disconnected" };
10315
+ let closedBeforeReady = false;
10145
10316
  client.onclose = () => {
10146
10317
  if (connection.status === "connected") {
10147
10318
  connection.status = "error";
10148
10319
  connection.error = "Upstream disconnected unexpectedly";
10149
10320
  log("warn", "Upstream disconnected unexpectedly", { namespace: config.namespace });
10150
10321
  if (onDisconnect) onDisconnect(config.namespace);
10322
+ } else {
10323
+ closedBeforeReady = true;
10151
10324
  }
10152
10325
  };
10153
10326
  const tools = await fetchToolsFromUpstream(client, config.namespace);
10154
10327
  const resources = await fetchResourcesFromUpstream(client, config.namespace);
10155
10328
  const prompts = await fetchPromptsFromUpstream(client, config.namespace);
10329
+ if (closedBeforeReady) {
10330
+ throw new ActivationError(`Server "${config.namespace}" disconnected during initialization`, "protocol_error");
10331
+ }
10156
10332
  Object.assign(connection, {
10157
10333
  config,
10158
10334
  client,
@@ -10321,6 +10497,13 @@ function isPersistenceDisabled2() {
10321
10497
  function resolveMinCompliance() {
10322
10498
  return parseMinCompliance(process.env.YAW_MCP_MIN_COMPLIANCE);
10323
10499
  }
10500
+ function complianceRefusalReason(grade, min) {
10501
+ const c = classifyGrade(grade);
10502
+ if (c.kind === "unrecognized") {
10503
+ return `unrecognized compliance grade "${c.raw}" (not A-F); failing closed under YAW_MCP_MIN_COMPLIANCE=${min}`;
10504
+ }
10505
+ return `compliance grade ${grade ?? "unknown"} is below YAW_MCP_MIN_COMPLIANCE=${min}`;
10506
+ }
10324
10507
  function isAutoLoadEnabled() {
10325
10508
  const raw = process.env.YAW_MCP_AUTO_LOAD;
10326
10509
  if (raw === void 0 || raw === "") return false;
@@ -10345,8 +10528,9 @@ function isRoutingFaultText(text) {
10345
10528
  return ROUTING_FAULT_MARKERS.some((marker) => text.includes(marker));
10346
10529
  }
10347
10530
  function resolveNamespaces(args) {
10348
- if (Array.isArray(args.servers) && args.servers.length > 0) {
10349
- return args.servers;
10531
+ if (Array.isArray(args.servers)) {
10532
+ const filtered = args.servers.filter((s) => typeof s === "string" && s.length > 0);
10533
+ if (filtered.length > 0) return filtered;
10350
10534
  }
10351
10535
  if (typeof args.server === "string" && args.server) {
10352
10536
  return [args.server];
@@ -10405,7 +10589,7 @@ var ConnectServer = class _ConnectServer {
10405
10589
  this.apiUrl = apiUrl5;
10406
10590
  this.token = token5;
10407
10591
  this.server = new Server(
10408
- { name: "yaw-mcp", version: true ? "0.72.0" : "dev" },
10592
+ { name: "yaw-mcp", version: true ? "0.73.1" : "dev" },
10409
10593
  {
10410
10594
  capabilities: {
10411
10595
  tools: { listChanged: true },
@@ -10504,6 +10688,15 @@ var ConnectServer = class _ConnectServer {
10504
10688
  // With this set: prewarm only disconnects when the namespace was NOT
10505
10689
  // claimed by an explicit activate while P1 was in flight.
10506
10690
  prewarmNamespaces = /* @__PURE__ */ new Set();
10691
+ // Slot reservations for the concurrent-server cap. A namespace is added
10692
+ // here synchronously (before the first `await connectToUpstream`) once it
10693
+ // clears the cap check, and removed when its activation settles. Counting
10694
+ // these pending reservations alongside connected servers closes a TOCTOU
10695
+ // gap: two DISTINCT namespaces activating concurrently would otherwise
10696
+ // both pass the cap check against the same connected set and overshoot
10697
+ // YAW_MCP_SERVER_CAP. Distinct from activationInflight (which dedupes
10698
+ // repeat activations of the SAME namespace) — this bounds the TOTAL count.
10699
+ pendingActivations = /* @__PURE__ */ new Set();
10507
10700
  // Usage learning — nudges dispatch toward namespaces that have been
10508
10701
  // genuinely useful. Counts persist across yaw-mcp restarts via state.json
10509
10702
  // (see persistence.ts). YAW_MCP_DISABLE_PERSISTENCE=1 makes it session
@@ -11020,14 +11213,15 @@ var ConnectServer = class _ConnectServer {
11020
11213
  let routes = this.toolRoutes;
11021
11214
  let route = routes.get(name);
11022
11215
  if (route?.deferred) {
11023
- progress?.(`Loading "${route.namespace}" on first tools/call\u2026`);
11024
- const activation = await this.activateOne(route.namespace, progress);
11216
+ const deferredNs = route.namespace;
11217
+ progress?.(`Loading "${deferredNs}" on first tools/call\u2026`);
11218
+ const activation = await this.activateOne(deferredNs, progress);
11025
11219
  if (!activation.ok) {
11026
11220
  return {
11027
11221
  content: [
11028
11222
  {
11029
11223
  type: "text",
11030
- text: `Server "${route.namespace}" could not be loaded on first call: ${activation.message}`
11224
+ text: `Server "${deferredNs}" could not be loaded on first call: ${activation.message}`
11031
11225
  }
11032
11226
  ],
11033
11227
  isError: true
@@ -11044,7 +11238,7 @@ var ConnectServer = class _ConnectServer {
11044
11238
  content: [
11045
11239
  {
11046
11240
  type: "text",
11047
- text: `Tool "${name}" is ${ROUTING_FAULT_TOOL_GONE} after loading "${activation.serverId ? activation.serverId : name}" \u2014 the upstream's tool set changed. Call mcp_connect_discover to list the current tools for that namespace.`
11241
+ text: `Tool "${name}" is ${ROUTING_FAULT_TOOL_GONE} after loading "${deferredNs}" \u2014 the upstream's tool set changed. Call mcp_connect_discover to list the current tools for that namespace.`
11048
11242
  }
11049
11243
  ],
11050
11244
  isError: true
@@ -11445,7 +11639,8 @@ var ConnectServer = class _ConnectServer {
11445
11639
  let complianceLabel = "";
11446
11640
  if (server.complianceGrade) {
11447
11641
  if (minCompliance !== null && !passesMinCompliance(server.complianceGrade, minCompliance)) {
11448
- complianceLabel = ` (grade ${server.complianceGrade} \u2014 below YAW_MCP_MIN_COMPLIANCE=${minCompliance}, won't auto-activate)`;
11642
+ const label = classifyGrade(server.complianceGrade).kind === "unrecognized" ? `unrecognized, won't auto-activate` : `below YAW_MCP_MIN_COMPLIANCE=${minCompliance}, won't auto-activate`;
11643
+ complianceLabel = ` (grade ${server.complianceGrade} \u2014 ${label})`;
11449
11644
  } else {
11450
11645
  complianceLabel = ` [${server.complianceGrade}]`;
11451
11646
  }
@@ -11634,10 +11829,26 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
11634
11829
  message: `"${namespace}" is not allowed by the project profile at ${this.profile?.path}.`
11635
11830
  };
11636
11831
  }
11832
+ const minCompliance = resolveMinCompliance();
11833
+ if (minCompliance !== null && !passesMinCompliance(serverConfig.complianceGrade, minCompliance)) {
11834
+ return {
11835
+ ok: false,
11836
+ isChanged: false,
11837
+ message: `Refused to load "${namespace}": ${complianceRefusalReason(serverConfig.complianceGrade, minCompliance)}. Unset YAW_MCP_MIN_COMPLIANCE (or lower it) to override.`
11838
+ };
11839
+ }
11637
11840
  const loadedSlots = [];
11841
+ const counted = /* @__PURE__ */ new Set();
11638
11842
  for (const [ns, conn] of this.connections) {
11639
11843
  if (conn.status === "connected") {
11640
11844
  loadedSlots.push({ namespace: ns, idleCount: this.idleCallCounts.get(ns) ?? 0 });
11845
+ counted.add(ns);
11846
+ }
11847
+ }
11848
+ for (const ns of this.pendingActivations) {
11849
+ if (ns !== namespace && !counted.has(ns)) {
11850
+ loadedSlots.push({ namespace: ns, idleCount: this.idleCallCounts.get(ns) ?? 0 });
11851
+ counted.add(ns);
11641
11852
  }
11642
11853
  }
11643
11854
  const capDecision = evaluateServerCap(namespace, loadedSlots, this.serverCap);
@@ -11649,58 +11860,63 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
11649
11860
  message: capDecision.message ?? "Concurrent server cap reached."
11650
11861
  };
11651
11862
  }
11652
- const elicited = this.elicitedEnv.get(namespace);
11653
- const effectiveConfig = elicited ? { ...serverConfig, env: { ...serverConfig.env, ...elicited } } : serverConfig;
11654
- let lastError = null;
11655
- for (let attempt = 0; attempt < 2; attempt++) {
11656
- try {
11657
- progress?.(
11658
- attempt === 0 ? `Spawning "${namespace}" upstream\u2026` : `Retrying "${namespace}" (attempt ${attempt + 1})\u2026`
11659
- );
11660
- const connection = await connectToUpstream(
11661
- effectiveConfig,
11662
- this.onUpstreamDisconnect,
11663
- this.onUpstreamListChanged
11664
- );
11665
- progress?.(`"${namespace}" loaded ${connection.tools.length} tools`);
11666
- this.connections.set(namespace, connection);
11667
- this.idleCallCounts.set(namespace, 0);
11668
- const toolMeta = connection.tools.map((t) => ({ name: t.name, description: t.description }));
11669
- this.toolCache.set(namespace, toolMeta);
11670
- if (toolMeta.length > 0) {
11671
- reportTools(serverConfig.id, toolMeta).catch(
11672
- (err) => log("warn", "reportTools failed", { namespace, error: err?.message })
11863
+ this.pendingActivations.add(namespace);
11864
+ try {
11865
+ const elicited = this.elicitedEnv.get(namespace);
11866
+ const effectiveConfig = elicited ? { ...serverConfig, env: { ...serverConfig.env, ...elicited } } : serverConfig;
11867
+ let lastError = null;
11868
+ for (let attempt = 0; attempt < 2; attempt++) {
11869
+ try {
11870
+ progress?.(
11871
+ attempt === 0 ? `Spawning "${namespace}" upstream\u2026` : `Retrying "${namespace}" (attempt ${attempt + 1})\u2026`
11673
11872
  );
11674
- }
11675
- const toolNames = connection.tools.map((t) => t.namespacedName).join(", ");
11676
- this.activationFailures.delete(namespace);
11677
- return {
11678
- ok: true,
11679
- isChanged: true,
11680
- serverId: serverConfig.id,
11681
- message: `Loaded "${namespace}" \u2014 ${connection.tools.length} tools: ${toolNames}`
11682
- };
11683
- } catch (err) {
11684
- lastError = err;
11685
- if (attempt === 0) {
11686
- const msg = err instanceof Error ? err.message : String(err);
11687
- log("warn", "Activation attempt failed, retrying", { namespace, error: msg });
11688
- await new Promise((r) => setTimeout(r, 1e3 * 2 ** attempt));
11873
+ const connection = await connectToUpstream(
11874
+ effectiveConfig,
11875
+ this.onUpstreamDisconnect,
11876
+ this.onUpstreamListChanged
11877
+ );
11878
+ progress?.(`"${namespace}" loaded ${connection.tools.length} tools`);
11879
+ this.connections.set(namespace, connection);
11880
+ this.idleCallCounts.set(namespace, 0);
11881
+ const toolMeta = connection.tools.map((t) => ({ name: t.name, description: t.description }));
11882
+ this.toolCache.set(namespace, toolMeta);
11883
+ if (toolMeta.length > 0) {
11884
+ reportTools(serverConfig.id, toolMeta).catch(
11885
+ (err) => log("warn", "reportTools failed", { namespace, error: err?.message })
11886
+ );
11887
+ }
11888
+ const toolNames = connection.tools.map((t) => t.namespacedName).join(", ");
11889
+ this.activationFailures.delete(namespace);
11890
+ return {
11891
+ ok: true,
11892
+ isChanged: true,
11893
+ serverId: serverConfig.id,
11894
+ message: `Loaded "${namespace}" \u2014 ${connection.tools.length} tools: ${toolNames}`
11895
+ };
11896
+ } catch (err) {
11897
+ lastError = err;
11898
+ if (attempt === 0) {
11899
+ const msg = err instanceof Error ? err.message : String(err);
11900
+ log("warn", "Activation attempt failed, retrying", { namespace, error: msg });
11901
+ await new Promise((r) => setTimeout(r, 1e3 * 2 ** attempt));
11902
+ }
11689
11903
  }
11690
11904
  }
11905
+ const elicitedRetry = await this.maybeElicitAndRetry(namespace, lastError, progress);
11906
+ if (elicitedRetry) return elicitedRetry;
11907
+ log("error", "Failed to activate upstream", {
11908
+ namespace,
11909
+ error: lastError instanceof Error ? lastError.message : String(lastError)
11910
+ });
11911
+ this.activationFailures.set(namespace, {
11912
+ at: Date.now(),
11913
+ message: lastError instanceof Error ? lastError.message : String(lastError)
11914
+ });
11915
+ const message = lastError instanceof ActivationError ? `Failed to load "${namespace}": ${lastError.message}` : `Failed to load "${namespace}": ${lastError instanceof Error ? lastError.message : String(lastError)}`;
11916
+ return { ok: false, isChanged: false, message };
11917
+ } finally {
11918
+ this.pendingActivations.delete(namespace);
11691
11919
  }
11692
- const elicitedRetry = await this.maybeElicitAndRetry(namespace, lastError, progress);
11693
- if (elicitedRetry) return elicitedRetry;
11694
- log("error", "Failed to activate upstream", {
11695
- namespace,
11696
- error: lastError instanceof Error ? lastError.message : String(lastError)
11697
- });
11698
- this.activationFailures.set(namespace, {
11699
- at: Date.now(),
11700
- message: lastError instanceof Error ? lastError.message : String(lastError)
11701
- });
11702
- const message = lastError instanceof ActivationError ? `Failed to load "${namespace}": ${lastError.message}` : `Failed to load "${namespace}": ${lastError instanceof Error ? lastError.message : String(lastError)}`;
11703
- return { ok: false, isChanged: false, message };
11704
11920
  }
11705
11921
  // If the activation error names a missing credential (e.g. "GITHUB_TOKEN
11706
11922
  // is required") AND the client supports elicitation, ask the user for
@@ -11806,8 +12022,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
11806
12022
  if (minCompliance !== null) {
11807
12023
  const cfg = this.config?.servers.find((s) => s.namespace === namespace);
11808
12024
  if (cfg && !passesMinCompliance(cfg.complianceGrade, minCompliance)) {
11809
- const grade = cfg.complianceGrade ?? "unknown";
11810
- const message = `Refused to load "${namespace}": compliance grade ${grade} is below YAW_MCP_MIN_COMPLIANCE=${minCompliance}. Unset YAW_MCP_MIN_COMPLIANCE (or lower it) to override.`;
12025
+ const message = `Refused to load "${namespace}": ${complianceRefusalReason(cfg.complianceGrade, minCompliance)}. Unset YAW_MCP_MIN_COMPLIANCE (or lower it) to override.`;
11811
12026
  results.push(message);
11812
12027
  anyError = true;
11813
12028
  continue;
@@ -12795,7 +13010,7 @@ To load the top pack in one step, call \`mcp_connect_activate\` with namespaces=
12795
13010
  this.learning.recordOutcome(stepNs, 0.5);
12796
13011
  for (const dep of deps) {
12797
13012
  const depNs = stepNamespaces.get(dep);
12798
- if (depNs) this.learning.recordOutcome(depNs, 0.5);
13013
+ if (depNs) this.learning.adjustSucceeded(depNs, -0.5);
12799
13014
  }
12800
13015
  } else {
12801
13016
  this.learning.recordOutcome(stepNs, 0);
@@ -13082,7 +13297,7 @@ function suggestFlag(input, limit = 2) {
13082
13297
  const q = input.toLowerCase();
13083
13298
  const hits = [];
13084
13299
  for (const alias of FLAG_ALIASES) {
13085
- if (alias.toLowerCase() === q) continue;
13300
+ if (alias === input) continue;
13086
13301
  const d = levenshtein(q, alias.toLowerCase());
13087
13302
  if (d <= 2) hits.push({ name: alias, d });
13088
13303
  }
@@ -13422,7 +13637,7 @@ if (subcommand === "compliance") {
13422
13637
  `);
13423
13638
  process.exitCode = 0;
13424
13639
  } else if (subcommand === "--version" || subcommand === "-V") {
13425
- process.stdout.write(`yaw-mcp ${true ? "0.72.0" : "dev"}
13640
+ process.stdout.write(`yaw-mcp ${true ? "0.73.1" : "dev"}
13426
13641
  `);
13427
13642
  process.exitCode = 0;
13428
13643
  } else if (subcommand && !subcommand.startsWith("-")) {
@@ -13438,7 +13653,12 @@ if (subcommand === "compliance") {
13438
13653
  `);
13439
13654
  process.exit(2);
13440
13655
  } else {
13441
- runServer();
13656
+ runServer().catch((err) => {
13657
+ const msg = err instanceof Error ? err.message : String(err);
13658
+ process.stderr.write(`yaw-mcp: ${msg}
13659
+ `);
13660
+ process.exitCode = 1;
13661
+ });
13442
13662
  }
13443
13663
  }
13444
13664
  async function runServer() {