@yawlabs/mcp 1.0.10 → 1.0.12

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
@@ -42,6 +42,7 @@ import {
42
42
  findProjectConfigDir,
43
43
  guidePath,
44
44
  importViewOf,
45
+ isFeatureDisabled,
45
46
  isOamCommand,
46
47
  isOamLaunch,
47
48
  isProjectLocalEntry,
@@ -100,7 +101,7 @@ import {
100
101
  unparseableConfigFix,
101
102
  userConfigDir,
102
103
  yawModeOverlay
103
- } from "./chunk-UTRRLFLD.js";
104
+ } from "./chunk-HRHGAT5G.js";
104
105
 
105
106
  // src/audit-cmd.ts
106
107
  import { homedir as homedir6 } from "os";
@@ -1419,6 +1420,7 @@ function mergeServerEntry(existing, incoming) {
1419
1420
  merged[k] = v;
1420
1421
  }
1421
1422
  if (base.isActive === false && incoming.isActive !== false) merged.isActive = false;
1423
+ if (Array.isArray(merged.optionalEnvKeys) && merged.optionalEnvKeys.length === 0) delete merged.optionalEnvKeys;
1422
1424
  const convertedToRemote = typeof incoming.url === "string" && incoming.command === void 0;
1423
1425
  if (convertedToRemote) {
1424
1426
  delete merged.command;
@@ -1686,6 +1688,7 @@ var LEGACY_SCHEMA_VERSION = 1;
1686
1688
  var VAULT_CHECK_AAD = "yaw-mcp:vault-check";
1687
1689
  var VAULT_CHECK_PLAINTEXT = "yaw-mcp-vault-v1";
1688
1690
  var VAULT_CHECK_CORRUPT_ERROR = 'vault verification token ("check") is corrupt -- the passphrase is correct, but the check marker does not decrypt';
1691
+ var VAULT_WRONG_PASSPHRASE_ERROR = "wrong passphrase for this vault (decryption failed)";
1689
1692
  function vaultPath(home = homedir4()) {
1690
1693
  return join5(home, CONFIG_DIRNAME, SECRETS_FILENAME);
1691
1694
  }
@@ -1846,11 +1849,11 @@ function verifyKey(vault, key) {
1846
1849
  if (vault.check) {
1847
1850
  if (checkMarkerMatches(vault, key)) return;
1848
1851
  if (someEntryDecrypts()) throw new Error(VAULT_CHECK_CORRUPT_ERROR);
1849
- throw new Error("wrong passphrase for this vault (decryption failed)");
1852
+ throw new Error(VAULT_WRONG_PASSPHRASE_ERROR);
1850
1853
  }
1851
1854
  if (entries.length === 0) return;
1852
1855
  if (someEntryDecrypts()) return;
1853
- throw new Error("wrong passphrase for this vault (decryption failed)");
1856
+ throw new Error(VAULT_WRONG_PASSPHRASE_ERROR);
1854
1857
  }
1855
1858
  function checkMarkerMatches(vault, key) {
1856
1859
  if (!vault.check) return false;
@@ -1864,6 +1867,30 @@ function ensureCheck(vault, key) {
1864
1867
  if (vault.check) return vault;
1865
1868
  return { ...vault, check: encryptEntry(VAULT_CHECK_PLAINTEXT, key, VAULT_CHECK_AAD) };
1866
1869
  }
1870
+ function vaultVerifiesPassphrases(vault) {
1871
+ return vault.check !== void 0 || Object.keys(vault.entries).length > 0;
1872
+ }
1873
+ async function checkVaultPassphrase(vault, passphrase) {
1874
+ if (passphrase.length === 0) return "wrong";
1875
+ try {
1876
+ (await unlock(vault, passphrase)).fill(0);
1877
+ return "opens";
1878
+ } catch (err) {
1879
+ return (err instanceof Error ? err.message : String(err)) === VAULT_CHECK_CORRUPT_ERROR ? "marker-corrupt" : "wrong";
1880
+ }
1881
+ }
1882
+ function vaultCheckCorruptHint(path5) {
1883
+ return `Your entries are intact: delete the "check" key from ${path5} by hand and re-run -- the next \`yaw-mcp secrets set\` re-stamps it.`;
1884
+ }
1885
+ async function createEmptyVault(passphrase) {
1886
+ const vault = emptyVault();
1887
+ const key = await deriveKey(passphrase, Buffer.from(vault.salt, "base64"), DEFAULT_KDF);
1888
+ try {
1889
+ return ensureCheck(vault, key);
1890
+ } finally {
1891
+ key.fill(0);
1892
+ }
1893
+ }
1867
1894
  async function rotateVault(vault, oldKey, newPassphrase) {
1868
1895
  if (vault.check && !checkMarkerMatches(vault, oldKey)) {
1869
1896
  throw new Error("rotate aborted: current passphrase is wrong (vault check failed to decrypt)");
@@ -3203,7 +3230,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
3203
3230
  if (downstreamCaps?.sampling) capabilities.sampling = downstreamCaps.sampling;
3204
3231
  if (downstreamCaps?.roots) capabilities.roots = {};
3205
3232
  const client = new Client(
3206
- { name: "yaw-mcp", version: true ? "1.0.10" : "dev" },
3233
+ { name: "yaw-mcp", version: true ? "1.0.12" : "dev" },
3207
3234
  { capabilities }
3208
3235
  );
3209
3236
  if (bridge && capabilities.elicitation) {
@@ -4785,7 +4812,7 @@ import { basename as basename2, isAbsolute, join as join9, resolve as resolve4 }
4785
4812
 
4786
4813
  // src/secrets-cmd.ts
4787
4814
  import { createHash as createHash4 } from "crypto";
4788
- import { readFile as readFile8 } from "fs/promises";
4815
+ import { chmod as chmod5, copyFile, constants as fsConstants, readFile as readFile8, unlink } from "fs/promises";
4789
4816
  import { homedir as homedir8 } from "os";
4790
4817
  var SECRETS_USAGE = `Usage: yaw-mcp secrets <action> [args]
4791
4818
 
@@ -4830,6 +4857,19 @@ Actions:
4830
4857
  entry name. (Every other command leaves the
4831
4858
  file's schema as it found it, and says so on
4832
4859
  stderr when it is behind.)
4860
+ reset Start the vault over when its passphrase is
4861
+ forgotten. Moves the existing file aside as
4862
+ secrets.json.reset-<timestamp>, next to it (it
4863
+ still opens under the old passphrase, should that
4864
+ turn up), prints the entry names it held (plaintext
4865
+ keys, so no passphrase is needed) so you know what
4866
+ to set again, and creates an empty vault under a
4867
+ NEW passphrase -- confirmed twice on a TTY, or
4868
+ YAW_MCP_VAULT_PASSPHRASE when it is set. Asks you
4869
+ to type RESET first, and refuses without --force
4870
+ when there is no TTY to ask on. Refuses when the
4871
+ passphrase it is given already opens the vault:
4872
+ that is \`rotate\`, not a reset.
4833
4873
  audit [--secret NAME] [--server NS]
4834
4874
  Show the local secret-resolution audit trail
4835
4875
  (~/.yaw-mcp/secrets-audit.log): which secret
@@ -4844,8 +4884,9 @@ Actions:
4844
4884
  Flags:
4845
4885
  --json Machine-readable output (where applicable). stdout
4846
4886
  carries the result envelope; stderr carries one
4847
- JSON object per line: {"warning":...} lines about
4848
- the FILE (schema-behind) and, on failure, the
4887
+ JSON object per line: {"warning":...} lines (a
4888
+ schema-behind file, a short passphrase, a vault
4889
+ just created or reset) and, on failure, the
4849
4890
  {"ok":false,"error":...} envelope last. Key on
4850
4891
  "warning" vs "ok", never on line position.
4851
4892
  --value <v> Inline secret value (set only). The value sits in
@@ -4859,10 +4900,10 @@ Flags:
4859
4900
  scripting-safe alternative to --value: the value
4860
4901
  never appears in argv.
4861
4902
  --force Skip the destructive-action confirmation
4862
- (remove, and a set that overwrites an existing
4863
- name). Required for remove when stdin or stdout
4864
- is not a TTY (both ends are needed to ask). NEVER
4865
- skips the passphrase.
4903
+ (remove, reset, and a set that overwrites an
4904
+ existing name). Required for remove and reset
4905
+ when stdin or stdout is not a TTY (both ends are
4906
+ needed to ask). NEVER skips the passphrase.
4866
4907
  --secret <name> (audit only) Filter to one secret name.
4867
4908
  --server <ns> (audit only) Filter to one server namespace.
4868
4909
 
@@ -4872,7 +4913,15 @@ Passphrase:
4872
4913
  scrypt and is cached in memory for the lifetime of this yaw-mcp
4873
4914
  process; the on-disk vault only ever holds ciphertext. For rotate, the
4874
4915
  NEW passphrase comes from YAW_MCP_VAULT_PASSPHRASE_NEW (or a TTY
4875
- confirm-twice prompt).`;
4916
+ confirm-twice prompt).
4917
+
4918
+ Forgot the passphrase?
4919
+ There is no recovery: the file holds only ciphertext under a key derived
4920
+ from the passphrase, and nothing else -- no server, no recovery key -- can
4921
+ open it. \`yaw-mcp secrets reset\` is the way back to a working vault: it
4922
+ moves the old file aside (kept, in case the passphrase turns up), lists
4923
+ the entry names you have to set again, and starts an empty vault under a
4924
+ new passphrase.`;
4876
4925
  function parseSecretsArgs(argv) {
4877
4926
  const opts = {};
4878
4927
  for (let i = 0; i < argv.length; i++) {
@@ -4920,7 +4969,7 @@ ${SECRETS_USAGE}` };
4920
4969
  ${SECRETS_USAGE}` };
4921
4970
  }
4922
4971
  if (!opts.action) {
4923
- if (a !== "set" && a !== "get" && a !== "list" && a !== "remove" && a !== "lock" && a !== "rotate" && a !== "audit") {
4972
+ if (a !== "set" && a !== "get" && a !== "list" && a !== "remove" && a !== "lock" && a !== "rotate" && a !== "reset" && a !== "audit") {
4924
4973
  return { ok: false, error: `yaw-mcp secrets: unknown action "${a}"
4925
4974
 
4926
4975
  ${SECRETS_USAGE}` };
@@ -4989,7 +5038,7 @@ async function safeLoadVault(path5, io, json, action) {
4989
5038
  } catch (err) {
4990
5039
  const raw = err instanceof Error ? err.message : String(err);
4991
5040
  const name = err instanceof VaultEntryCorruptError ? err.entryName : void 0;
4992
- const msg = name ? `secret entry ${name} is corrupt, and every secrets command fails until it is gone. Delete the "${name}" key from ${path5} by hand (or delete that file to start the vault over), then re-add it with \`yaw-mcp secrets set ${name}\`.` : raw;
5041
+ const msg = name ? `secret entry ${name} is corrupt, and every secrets command fails until it is gone. Delete the "${name}" key from ${path5} by hand (or run \`yaw-mcp secrets reset\` to start the vault over -- it keeps the old file), then re-add it with \`yaw-mcp secrets set ${name}\`.` : raw;
4993
5042
  if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
4994
5043
  `);
4995
5044
  else io.err(`yaw-mcp secrets${action ? ` ${action}` : ""}: ${msg}
@@ -5022,20 +5071,24 @@ function vaultUnreadableResult(io, json, action, path5, fp) {
5022
5071
  `);
5023
5072
  return { exitCode: 1 };
5024
5073
  }
5025
- async function saveVaultOrReport(path5, vault, io, json, action) {
5074
+ async function trySaveVault(path5, vault) {
5026
5075
  try {
5027
5076
  await saveVault(path5, vault);
5028
5077
  return null;
5029
5078
  } catch (err) {
5030
5079
  const e = err;
5031
- const cause = e.code ?? (err instanceof Error ? err.message : String(err));
5032
- const msg = `could not write the vault file at ${path5} (${cause}) -- nothing was saved.`;
5033
- if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5080
+ return e.code ?? (err instanceof Error ? err.message : String(err));
5081
+ }
5082
+ }
5083
+ async function saveVaultOrReport(path5, vault, io, json, action) {
5084
+ const cause = await trySaveVault(path5, vault);
5085
+ if (cause === null) return null;
5086
+ const msg = `could not write the vault file at ${path5} (${cause}) -- nothing was saved.`;
5087
+ if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5034
5088
  `);
5035
- else io.err(`yaw-mcp secrets${action ? ` ${action}` : ""}: ${msg}
5089
+ else io.err(`yaw-mcp secrets${action ? ` ${action}` : ""}: ${msg}
5036
5090
  `);
5037
- return { exitCode: 1 };
5038
- }
5091
+ return { exitCode: 1 };
5039
5092
  }
5040
5093
  function vaultChangedResult(io, json, action) {
5041
5094
  const msg = "the vault changed on disk while this command was waiting for input -- nothing was written. Re-run to work from the current vault.";
@@ -5047,8 +5100,13 @@ function vaultChangedResult(io, json, action) {
5047
5100
  }
5048
5101
  function unlockErrorMessage(err, path5) {
5049
5102
  const msg = err instanceof Error ? err.message : String(err);
5050
- if (msg !== VAULT_CHECK_CORRUPT_ERROR) return msg;
5051
- return `${msg}. Your entries are intact: delete the "check" key from ${path5} by hand and re-run -- the next \`yaw-mcp secrets set\` re-stamps it.`;
5103
+ if (msg === VAULT_CHECK_CORRUPT_ERROR) {
5104
+ return `${msg}. ${vaultCheckCorruptHint(path5)}`;
5105
+ }
5106
+ if (msg === VAULT_WRONG_PASSPHRASE_ERROR) {
5107
+ return `${msg}. If it is forgotten, \`yaw-mcp secrets reset\` moves this vault aside and starts a new one (the old file is kept).`;
5108
+ }
5109
+ return msg;
5052
5110
  }
5053
5111
  var CANCELLED = /* @__PURE__ */ Symbol("yaw-mcp:passphrase-cancelled");
5054
5112
  function cancelledResult(io, json) {
@@ -5098,15 +5156,39 @@ async function promptYesNo(opts, question) {
5098
5156
  const a = answer.trim().toLowerCase();
5099
5157
  return a === "y" || a === "yes";
5100
5158
  }
5101
- function warnIfShortPassphrase(io, passphrase, subject, hint) {
5159
+ function warnIfShortPassphrase(io, json, passphrase, subject, hint) {
5102
5160
  if (passphrase.length >= MIN_PASSPHRASE_WARN_LEN) return;
5161
+ if (json) {
5162
+ io.err(
5163
+ `${JSON.stringify({
5164
+ warning: "short-passphrase",
5165
+ subject,
5166
+ min_length: MIN_PASSPHRASE_WARN_LEN,
5167
+ ...hint ? { hint } : {}
5168
+ })}
5169
+ `
5170
+ );
5171
+ return;
5172
+ }
5103
5173
  io.err(
5104
5174
  `yaw-mcp secrets: warning -- ${subject} is shorter than ${MIN_PASSPHRASE_WARN_LEN} characters; consider a longer passphrase.${hint ? ` ${hint}` : ""}
5105
5175
  `
5106
5176
  );
5107
5177
  }
5108
- function freshVaultNudge(io, path5) {
5178
+ function freshVaultNudge(io, path5, json) {
5109
5179
  const envSet = (process.env.YAW_MCP_VAULT_PASSPHRASE ?? "").length > 0;
5180
+ if (json) {
5181
+ io.err(
5182
+ `${JSON.stringify({
5183
+ warning: "vault-created",
5184
+ path: path5,
5185
+ env_set_here: envSet,
5186
+ hint: envSet ? "YAW_MCP_VAULT_PASSPHRASE is set in this shell; the yaw-mcp your MCP client launches has its own environment -- set it there too. `yaw-mcp doctor` reports whether it is set." : "set YAW_MCP_VAULT_PASSPHRASE in the environment your MCP client launches yaw-mcp from; without it a server referencing ${secret:...} asks in-session or fails to start. `yaw-mcp doctor` reports whether it is set."
5187
+ })}
5188
+ `
5189
+ );
5190
+ return;
5191
+ }
5110
5192
  const lines = envSet ? [
5111
5193
  " YAW_MCP_VAULT_PASSPHRASE is set in THIS shell, but ${secret:NAME} refs are resolved",
5112
5194
  " by the yaw-mcp your MCP client launches, which has its own environment -- set it",
@@ -5142,40 +5224,54 @@ function schemaBehindNotice(io, vault, path5, json) {
5142
5224
  `
5143
5225
  );
5144
5226
  }
5145
- async function resolvePassphrase(opts, io, confirm = false) {
5227
+ var CREATE_VAULT_LABELS = {
5228
+ first: "Vault passphrase: ",
5229
+ confirm: "Confirm passphrase: ",
5230
+ subject: "the passphrase you chose"
5231
+ };
5232
+ var NEW_PASSPHRASE_LABELS = {
5233
+ first: "New vault passphrase: ",
5234
+ confirm: "Confirm new passphrase: ",
5235
+ subject: "the new passphrase"
5236
+ };
5237
+ async function promptPassphraseTwice(opts, io, labels) {
5238
+ const stdin = opts.io?.stdin ?? process.stdin;
5239
+ const stdout = opts.io?.stdout ?? process.stdout;
5240
+ for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
5241
+ const first = await readLineFromTTY(stdin, stdout, labels.first);
5242
+ if (first === CANCELLED || first === NO_ECHO) return first;
5243
+ if (first.length === 0) {
5244
+ stdout.write("Passphrase cannot be empty.\n");
5245
+ continue;
5246
+ }
5247
+ const second = await readLineFromTTY(stdin, stdout, labels.confirm);
5248
+ if (second === CANCELLED || second === NO_ECHO) return second;
5249
+ if (first === second) {
5250
+ warnIfShortPassphrase(io, opts.json, first, labels.subject);
5251
+ return first;
5252
+ }
5253
+ stdout.write("Passphrases did not match. Try again.\n");
5254
+ }
5255
+ return null;
5256
+ }
5257
+ async function resolvePassphrase(opts, io, confirm = false, labels = CREATE_VAULT_LABELS) {
5146
5258
  if (opts.passphrase !== void 0) return opts.passphrase.length > 0 ? opts.passphrase : null;
5147
5259
  const fromEnv = process.env.YAW_MCP_VAULT_PASSPHRASE;
5148
5260
  if (typeof fromEnv === "string" && fromEnv.length > 0) {
5149
- warnIfShortPassphrase(io, fromEnv, "YAW_MCP_VAULT_PASSPHRASE");
5261
+ warnIfShortPassphrase(io, opts.json, fromEnv, "YAW_MCP_VAULT_PASSPHRASE");
5150
5262
  return fromEnv;
5151
5263
  }
5152
5264
  const stdin = opts.io?.stdin ?? process.stdin;
5153
5265
  const stdout = opts.io?.stdout ?? process.stdout;
5154
5266
  if (!isInteractiveTTY(opts)) return null;
5155
- if (confirm) {
5156
- for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
5157
- const first = await readLineFromTTY(stdin, stdout, "Vault passphrase: ");
5158
- if (first === CANCELLED) return CANCELLED;
5159
- if (first.length === 0) {
5160
- stdout.write("Passphrase cannot be empty.\n");
5161
- continue;
5162
- }
5163
- const second = await readLineFromTTY(stdin, stdout, "Confirm passphrase: ");
5164
- if (second === CANCELLED) return CANCELLED;
5165
- if (first === second) {
5166
- warnIfShortPassphrase(io, first, "the passphrase you chose");
5167
- return first;
5168
- }
5169
- stdout.write("Passphrases did not match. Try again.\n");
5170
- }
5171
- return null;
5172
- }
5267
+ if (confirm) return promptPassphraseTwice(opts, io, labels);
5173
5268
  for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
5174
5269
  const entered = await readLineFromTTY(stdin, stdout);
5175
- if (entered === CANCELLED) return CANCELLED;
5270
+ if (entered === CANCELLED || entered === NO_ECHO) return entered;
5176
5271
  if (entered.length > 0) {
5177
5272
  warnIfShortPassphrase(
5178
5273
  io,
5274
+ opts.json,
5179
5275
  entered,
5180
5276
  "the passphrase you entered",
5181
5277
  "If it unlocks this vault, re-key it with `yaw-mcp secrets rotate`."
@@ -5190,28 +5286,11 @@ async function resolveNewPassphrase(opts, io) {
5190
5286
  if (opts.newPassphrase !== void 0) return opts.newPassphrase.length > 0 ? opts.newPassphrase : null;
5191
5287
  const fromEnv = process.env.YAW_MCP_VAULT_PASSPHRASE_NEW;
5192
5288
  if (typeof fromEnv === "string" && fromEnv.length > 0) {
5193
- warnIfShortPassphrase(io, fromEnv, "the new passphrase");
5289
+ warnIfShortPassphrase(io, opts.json, fromEnv, "the new passphrase");
5194
5290
  return fromEnv;
5195
5291
  }
5196
- const stdin = opts.io?.stdin ?? process.stdin;
5197
- const stdout = opts.io?.stdout ?? process.stdout;
5198
5292
  if (!isInteractiveTTY(opts)) return null;
5199
- for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
5200
- const first = await readLineFromTTY(stdin, stdout, "New vault passphrase: ");
5201
- if (first === CANCELLED) return CANCELLED;
5202
- if (first.length === 0) {
5203
- stdout.write("Passphrase cannot be empty.\n");
5204
- continue;
5205
- }
5206
- const second = await readLineFromTTY(stdin, stdout, "Confirm new passphrase: ");
5207
- if (second === CANCELLED) return CANCELLED;
5208
- if (first === second) {
5209
- warnIfShortPassphrase(io, first, "the new passphrase");
5210
- return first;
5211
- }
5212
- stdout.write("Passphrases did not match. Try again.\n");
5213
- }
5214
- return null;
5293
+ return promptPassphraseTwice(opts, io, NEW_PASSPHRASE_LABELS);
5215
5294
  }
5216
5295
  var MAX_PASSPHRASE_PROMPTS = 3;
5217
5296
  var MIN_PASSPHRASE_WARN_LEN = 12;
@@ -5219,15 +5298,27 @@ var CTRL_C = "";
5219
5298
  var CTRL_D = "";
5220
5299
  var DEL = "\x7F";
5221
5300
  var ESC = "\x1B";
5301
+ var NO_ECHO = /* @__PURE__ */ Symbol("yaw-mcp:no-echo-unavailable");
5302
+ function noEchoRefusal(required, remedy) {
5303
+ return `${required} Refusing to prompt: this terminal would not turn echo off, so what you type would be shown on screen. ${remedy}`;
5304
+ }
5222
5305
  function readLineFromTTY(stdin, stdout, prompt = "Vault passphrase: ", echo = false) {
5223
- stdout.write(prompt);
5224
5306
  return new Promise((resolve8) => {
5225
5307
  const chunks = [];
5226
5308
  const wasRaw = stdin.isRaw === true;
5309
+ let raw = false;
5227
5310
  try {
5228
- stdin.setRawMode?.(true);
5311
+ if (typeof stdin.setRawMode === "function") {
5312
+ stdin.setRawMode(true);
5313
+ raw = true;
5314
+ }
5229
5315
  } catch {
5230
5316
  }
5317
+ if (!raw && !echo) {
5318
+ resolve8(NO_ECHO);
5319
+ return;
5320
+ }
5321
+ stdout.write(prompt);
5231
5322
  stdin.resume();
5232
5323
  stdin.setEncoding("utf8");
5233
5324
  const finish = (value) => {
@@ -5337,6 +5428,9 @@ async function runSecrets(opts, io = {
5337
5428
  if (opts.action === "rotate") {
5338
5429
  return await runSecretsRotate(opts, io);
5339
5430
  }
5431
+ if (opts.action === "reset") {
5432
+ return await runSecretsReset(opts, io);
5433
+ }
5340
5434
  if (opts.action === "audit") {
5341
5435
  return await runSecretsAudit(opts, io);
5342
5436
  }
@@ -5406,6 +5500,14 @@ async function runSecrets(opts, io = {
5406
5500
  const creatingVault = opts.action === "set" && !vault.check && Object.keys(vault.entries).length === 0;
5407
5501
  const passphrase = await resolvePassphrase(opts, io, creatingVault);
5408
5502
  if (passphrase === CANCELLED) return cancelledResult(io, opts.json);
5503
+ if (passphrase === NO_ECHO) {
5504
+ const msg = noEchoRefusal("Passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead.");
5505
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5506
+ `);
5507
+ else io.err(`yaw-mcp secrets: ${msg}
5508
+ `);
5509
+ return { exitCode: 1 };
5510
+ }
5409
5511
  if (passphrase === null) {
5410
5512
  const msg = promptUnavailableMessage(opts, "Passphrase required.", "YAW_MCP_VAULT_PASSPHRASE");
5411
5513
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
@@ -5432,6 +5534,14 @@ async function runSecrets(opts, io = {
5432
5534
  else {
5433
5535
  const entered = await readStdinValue(opts.io, opts.fromStdin);
5434
5536
  if (entered === CANCELLED) return cancelledResult(io, opts.json);
5537
+ if (entered === NO_ECHO) {
5538
+ const msg = noEchoRefusal("Secret value required.", "Pipe the value in with --stdin instead.");
5539
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5540
+ `);
5541
+ else io.err(`yaw-mcp secrets set: ${msg}
5542
+ `);
5543
+ return { exitCode: 1 };
5544
+ }
5435
5545
  if (entered === PROMPT_IMPOSSIBLE) {
5436
5546
  const msg = "cannot prompt for the value: stdin is a TTY but stdout is not, so the prompt would be written into the redirect instead of shown. Pass --value <v>, or pipe the value in with --stdin.";
5437
5547
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
@@ -5469,7 +5579,7 @@ async function runSecrets(opts, io = {
5469
5579
  `);
5470
5580
  else io.out(`${isFresh ? "Created vault and " : ""}Stored secret "${name}".
5471
5581
  `);
5472
- if (isFresh) freshVaultNudge(io, path5);
5582
+ if (isFresh) freshVaultNudge(io, path5, opts.json);
5473
5583
  return { exitCode: 0 };
5474
5584
  }
5475
5585
  if (opts.action === "get") {
@@ -5533,6 +5643,14 @@ async function runSecretsRotate(opts, io) {
5533
5643
  }
5534
5644
  const currentPassphrase = await resolvePassphrase(opts, io);
5535
5645
  if (currentPassphrase === CANCELLED) return cancelledResult(io, opts.json);
5646
+ if (currentPassphrase === NO_ECHO) {
5647
+ const msg = noEchoRefusal("Current passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead.");
5648
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5649
+ `);
5650
+ else io.err(`yaw-mcp secrets rotate: ${msg}
5651
+ `);
5652
+ return { exitCode: 1 };
5653
+ }
5536
5654
  if (currentPassphrase === null) {
5537
5655
  const msg = promptUnavailableMessage(opts, "Current passphrase required.", "YAW_MCP_VAULT_PASSPHRASE");
5538
5656
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
@@ -5554,6 +5672,14 @@ async function runSecretsRotate(opts, io) {
5554
5672
  }
5555
5673
  const newPassphrase = await resolveNewPassphrase(opts, io);
5556
5674
  if (newPassphrase === CANCELLED) return cancelledResult(io, opts.json);
5675
+ if (newPassphrase === NO_ECHO) {
5676
+ const msg = noEchoRefusal("New passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE_NEW instead.");
5677
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5678
+ `);
5679
+ else io.err(`yaw-mcp secrets rotate: ${msg}
5680
+ `);
5681
+ return { exitCode: 1 };
5682
+ }
5557
5683
  if (newPassphrase === null) {
5558
5684
  const msg = promptUnavailableMessage(
5559
5685
  opts,
@@ -5601,6 +5727,221 @@ async function runSecretsRotate(opts, io) {
5601
5727
  }
5602
5728
  return { exitCode: 0 };
5603
5729
  }
5730
+ function resetBackupPath(path5, at, attempt = 1) {
5731
+ return `${path5}.reset-${at.toISOString().replace(/:/g, "-")}${attempt > 1 ? `-${attempt}` : ""}`;
5732
+ }
5733
+ async function readVaultEntryNames(path5) {
5734
+ let raw;
5735
+ try {
5736
+ raw = await readFile8(path5, "utf8");
5737
+ } catch (err) {
5738
+ const e = err;
5739
+ return { unreadable: e.code ?? (err instanceof Error ? err.message : String(err)) };
5740
+ }
5741
+ let parsed;
5742
+ try {
5743
+ parsed = JSON.parse(raw);
5744
+ } catch (err) {
5745
+ return { unreadable: `not valid JSON: ${err instanceof Error ? err.message : String(err)}` };
5746
+ }
5747
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
5748
+ return { unreadable: "root is not a JSON object" };
5749
+ }
5750
+ const entries = parsed.entries;
5751
+ if (!entries || typeof entries !== "object" || Array.isArray(entries)) {
5752
+ return { unreadable: '"entries" is missing or not an object' };
5753
+ }
5754
+ return { names: Object.keys(entries).sort() };
5755
+ }
5756
+ async function copyVaultAside(path5, at) {
5757
+ for (let attempt = 1; ; attempt++) {
5758
+ const target = resetBackupPath(path5, at, attempt);
5759
+ try {
5760
+ await copyFile(path5, target, fsConstants.COPYFILE_EXCL);
5761
+ } catch (err) {
5762
+ if (err.code === "EEXIST" && attempt < 100) continue;
5763
+ throw err;
5764
+ }
5765
+ if (process.platform !== "win32") await chmod5(target, 384).catch(() => void 0);
5766
+ return target;
5767
+ }
5768
+ }
5769
+ var RESET_ALTERNATIVES = "To change the passphrase of a vault that opens, use `yaw-mcp secrets rotate`; to drop an entry from it, `yaw-mcp secrets remove <name>`.";
5770
+ function alreadyOpensMessage(verdict, subject, path5) {
5771
+ if (verdict === "marker-corrupt") {
5772
+ return `${subject} is this vault's passphrase; it is the check marker in ${path5} that is corrupt -- nothing to reset, and the vault was not touched. ${vaultCheckCorruptHint(path5)}`;
5773
+ }
5774
+ return `${subject} already opens the vault at ${path5} -- nothing to reset, and the vault was not touched. ${RESET_ALTERNATIVES}`;
5775
+ }
5776
+ function resetPreamble(path5, backup, names, envKeyed) {
5777
+ const lines = [];
5778
+ if ("names" in names) {
5779
+ const n = names.names.length;
5780
+ lines.push(
5781
+ n === 0 ? `The vault at ${path5} has no entries.` : `The vault at ${path5} holds ${n} ${n === 1 ? "entry" : "entries"}: ${names.names.join(", ")}`
5782
+ );
5783
+ } else {
5784
+ lines.push(`The vault at ${path5} could not be read (${names.unreadable}).`);
5785
+ }
5786
+ lines.push(`It will be moved to ${backup} -- it still opens under its old passphrase, should that turn up --`);
5787
+ lines.push("and an empty vault will be started in its place. Every entry has to be set again.");
5788
+ lines.push(
5789
+ envKeyed ? "The new vault will be keyed under the passphrase in YAW_MCP_VAULT_PASSPHRASE (set in this shell)." : "You will be asked to choose the new vault's passphrase next."
5790
+ );
5791
+ return `${lines.join("\n")}
5792
+ `;
5793
+ }
5794
+ function resetVaultNudge(io, path5, json, envKeyed) {
5795
+ if (json) {
5796
+ io.err(
5797
+ `${JSON.stringify({
5798
+ warning: "vault-reset",
5799
+ path: path5,
5800
+ passphrase_source: envKeyed ? "env" : "prompt",
5801
+ hint: "A running yaw-mcp server keeps the passphrase it started with -- restart it (restart your MCP client) to use the new vault, and update YAW_MCP_VAULT_PASSPHRASE in any client config `env` block that carries the old value. `yaw-mcp doctor` reports whether the passphrase it sees unlocks the vault."
5802
+ })}
5803
+ `
5804
+ );
5805
+ return;
5806
+ }
5807
+ const lines = [
5808
+ " A yaw-mcp server that is already running keeps the passphrase it started with and will not",
5809
+ " open the new vault with it: restart it (restart your MCP client), or answer its in-session",
5810
+ " prompt with the new passphrase if it offers one.",
5811
+ envKeyed ? " The new vault is keyed under YAW_MCP_VAULT_PASSPHRASE as set in THIS shell; a client config" : " A YAW_MCP_VAULT_PASSPHRASE in the `env` block of a client config still holds the OLD",
5812
+ envKeyed ? " whose `env` block carries a different value still holds the OLD passphrase -- update it." : " passphrase -- update it to the new one.",
5813
+ " `yaw-mcp doctor` reports whether the passphrase it can see unlocks the vault."
5814
+ ];
5815
+ io.err(`yaw-mcp secrets: the vault at ${path5} was reset.
5816
+ ${lines.join("\n")}
5817
+ `);
5818
+ }
5819
+ async function runSecretsReset(opts, io) {
5820
+ const home = opts.home ?? homedir8();
5821
+ const path5 = vaultPath(home);
5822
+ const json = opts.json;
5823
+ const fail = (msg, exitCode = 1) => {
5824
+ if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5825
+ `);
5826
+ else io.err(`yaw-mcp secrets reset: ${msg}
5827
+ `);
5828
+ return { exitCode };
5829
+ };
5830
+ const baseline = await vaultFingerprint(path5);
5831
+ if (isVaultUnreadable(baseline)) return vaultUnreadableResult(io, json, "reset", path5, baseline);
5832
+ if (baseline === null) {
5833
+ return fail(`No vault at ${path5} to reset. Run \`yaw-mcp secrets set <name>\` to create one.`);
5834
+ }
5835
+ const names = await readVaultEntryNames(path5);
5836
+ let vault = null;
5837
+ if ("names" in names) {
5838
+ try {
5839
+ vault = await loadVault(path5);
5840
+ } catch {
5841
+ vault = null;
5842
+ }
5843
+ }
5844
+ const guardable = vault !== null && vaultVerifiesPassphrases(vault);
5845
+ const scripted = opts.passphrase ?? process.env.YAW_MCP_VAULT_PASSPHRASE ?? "";
5846
+ if (guardable && vault !== null && scripted.length > 0) {
5847
+ const verdict = await checkVaultPassphrase(vault, scripted);
5848
+ lock();
5849
+ if (verdict !== "wrong") return fail(alreadyOpensMessage(verdict, "YAW_MCP_VAULT_PASSPHRASE", path5));
5850
+ }
5851
+ const at = /* @__PURE__ */ new Date();
5852
+ const envKeyed = opts.passphrase === void 0 && (process.env.YAW_MCP_VAULT_PASSPHRASE ?? "").length > 0;
5853
+ if (!opts.force) {
5854
+ if (isInteractiveTTY(opts)) {
5855
+ const stdin = opts.io?.stdin ?? process.stdin;
5856
+ const stdout = opts.io?.stdout ?? process.stdout;
5857
+ stdout.write(resetPreamble(path5, resetBackupPath(path5, at), names, envKeyed));
5858
+ const answer = await readLineFromTTY(stdin, stdout, "Type RESET to continue: ", true);
5859
+ if (answer === CANCELLED) return cancelledResult(io, json);
5860
+ if (answer.trim().toLowerCase() !== "reset") return abortedResult(io, json, "reset");
5861
+ } else {
5862
+ const msg = `refusing to reset the vault without confirmation and ${nonTTYEnds(opts)}.`;
5863
+ const hint = "Re-run with --force to reset it. The old vault is moved aside, not deleted, and every entry has to be set again.";
5864
+ if (json) io.err(`${JSON.stringify({ ok: false, error: `${msg} ${hint}` })}
5865
+ `);
5866
+ else io.err(`yaw-mcp secrets reset: ${msg}
5867
+ ${hint}
5868
+ `);
5869
+ return { exitCode: 2 };
5870
+ }
5871
+ }
5872
+ const passphrase = await resolvePassphrase(opts, io, true, NEW_PASSPHRASE_LABELS);
5873
+ if (passphrase === CANCELLED) return cancelledResult(io, json);
5874
+ if (passphrase === NO_ECHO) {
5875
+ return fail(noEchoRefusal("New passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead."));
5876
+ }
5877
+ if (passphrase === null) {
5878
+ return fail(
5879
+ promptUnavailableMessage(opts, "New passphrase required (and must be confirmed).", "YAW_MCP_VAULT_PASSPHRASE")
5880
+ );
5881
+ }
5882
+ if (guardable && vault !== null && scripted.length === 0) {
5883
+ const verdict = await checkVaultPassphrase(vault, passphrase);
5884
+ lock();
5885
+ if (verdict !== "wrong") return fail(alreadyOpensMessage(verdict, "that passphrase", path5));
5886
+ }
5887
+ let fresh;
5888
+ try {
5889
+ fresh = await createEmptyVault(passphrase);
5890
+ } catch (err) {
5891
+ const msg = err instanceof Error ? err.message : String(err);
5892
+ return fail(`could not derive the new vault's key (${msg}) -- nothing was changed.`);
5893
+ }
5894
+ if (await vaultChangedSinceLoad(path5, baseline)) return vaultChangedResult(io, json, "reset");
5895
+ let movedTo;
5896
+ try {
5897
+ movedTo = await copyVaultAside(path5, at);
5898
+ } catch (err) {
5899
+ const e = err;
5900
+ const cause2 = e.code ?? (err instanceof Error ? err.message : String(err));
5901
+ return fail(`could not copy the vault aside next to ${path5} (${cause2}) -- nothing was changed.`);
5902
+ }
5903
+ const cause = await trySaveVault(path5, fresh);
5904
+ if (cause !== null) {
5905
+ const stray = await unlink(movedTo).then(
5906
+ () => "",
5907
+ () => ` A copy of it was left at ${movedTo}.`
5908
+ );
5909
+ return fail(`could not write the new vault at ${path5} (${cause}) -- the old vault is untouched.${stray}`);
5910
+ }
5911
+ if (json) {
5912
+ io.out(
5913
+ `${JSON.stringify({
5914
+ ok: true,
5915
+ path: path5,
5916
+ moved_to: movedTo,
5917
+ entries: "names" in names ? names.names : null,
5918
+ unreadable: "unreadable" in names ? names.unreadable : null
5919
+ })}
5920
+ `
5921
+ );
5922
+ } else {
5923
+ io.out(`Moved the old vault to ${movedTo}. It still opens under its old passphrase, should that turn up.
5924
+ `);
5925
+ io.out(
5926
+ `Created an empty vault at ${path5} under ${envKeyed ? "the passphrase in YAW_MCP_VAULT_PASSPHRASE" : "the new passphrase"}.
5927
+ `
5928
+ );
5929
+ if ("names" in names) {
5930
+ const n = names.names.length;
5931
+ if (n === 0) io.out("The old vault held no entries.\n");
5932
+ else {
5933
+ io.out(`Entries to set again (${n}): ${names.names.join(", ")}
5934
+ `);
5935
+ io.out(" yaw-mcp secrets set <name> for each\n");
5936
+ }
5937
+ } else {
5938
+ io.out(`Could not read the old vault's entry names (${names.unreadable}); the file is kept at ${movedTo}.
5939
+ `);
5940
+ }
5941
+ }
5942
+ resetVaultNudge(io, path5, json, envKeyed);
5943
+ return { exitCode: 0 };
5944
+ }
5604
5945
  async function runSecretsAudit(opts, io) {
5605
5946
  const home = opts.home ?? homedir8();
5606
5947
  let events;
@@ -6662,7 +7003,7 @@ var SUBCOMMAND_SPEC = [
6662
7003
  {
6663
7004
  name: "secrets",
6664
7005
  description: "Manage stored secrets",
6665
- positional: [["set", "get", "list", "remove", "lock", "rotate", "audit"], ["<name>"]],
7006
+ positional: [["set", "get", "list", "remove", "lock", "rotate", "reset", "audit"], ["<name>"]],
6666
7007
  flags: ["--value", "--stdin", "--force", "--secret", "--server", "--json", "--help"]
6667
7008
  },
6668
7009
  // Other.
@@ -7624,7 +7965,7 @@ async function runSidecarsInstall(opts = {}) {
7624
7965
  print(` note: ${k.namespace} launches ${k.spec}, not a registry package; it keeps using npx`);
7625
7966
  }
7626
7967
  for (const k of ranges) {
7627
- print(` note: ${k.namespace} launches ${k.spec}, a version range oam cannot resolve; it keeps using npx`);
7968
+ print(` note: ${k.namespace} launches ${k.spec}, a version range yaw-mcp does not evaluate; it keeps using npx`);
7628
7969
  }
7629
7970
  };
7630
7971
  if (specs.length === 0) {
@@ -7947,8 +8288,7 @@ function defaultInstalledVersion(pkg, home) {
7947
8288
  return installedVersion(pkg, home);
7948
8289
  }
7949
8290
  function isSidecarRefreshDisabled(env = process.env) {
7950
- const raw = env.YAW_MCP_SIDECAR_REFRESH;
7951
- return raw === "0" || raw?.toLowerCase() === "false";
8291
+ return isFeatureDisabled("YAW_MCP_SIDECAR_REFRESH", env);
7952
8292
  }
7953
8293
  async function maybeRefreshSidecars(deps = {}) {
7954
8294
  try {
@@ -8039,7 +8379,7 @@ async function maybeRefreshSidecars(deps = {}) {
8039
8379
  // src/try-cmd.ts
8040
8380
  import { createHash as createHash5 } from "crypto";
8041
8381
  import { existsSync as existsSync5 } from "fs";
8042
- import { chmod as chmod5, mkdir as mkdir4, readdir, readFile as readFile12, unlink } from "fs/promises";
8382
+ import { chmod as chmod6, mkdir as mkdir4, readdir, readFile as readFile12, unlink as unlink2 } from "fs/promises";
8043
8383
  import { homedir as homedir14 } from "os";
8044
8384
  import { join as join13, resolve as resolve6 } from "path";
8045
8385
  import { createInterface as createInterface2 } from "readline/promises";
@@ -8231,14 +8571,24 @@ async function resolveCatalogSlug(slug, opts = {}) {
8231
8571
  if (!command) {
8232
8572
  throw new Error(`catalog entry "${slug}" install command was empty.`);
8233
8573
  }
8234
- const requiredEnvKeys2 = Array.isArray(entry.requiredEnv) ? entry.requiredEnv.map((e) => e && typeof e === "object" ? e.key : void 0).filter((k) => typeof k === "string" && ENV_KEY_RE.test(k)) : [];
8574
+ const requiredEnvKeys = [];
8575
+ const optionalEnvKeys = [];
8576
+ if (Array.isArray(entry.requiredEnv)) {
8577
+ for (const e of entry.requiredEnv) {
8578
+ const key = e && typeof e === "object" ? e.key : void 0;
8579
+ if (typeof key !== "string" || !ENV_KEY_RE.test(key)) continue;
8580
+ (e.optional === true ? optionalEnvKeys : requiredEnvKeys).push(key);
8581
+ }
8582
+ }
8583
+ const optionalOnly = optionalEnvKeys.filter((k) => !requiredEnvKeys.includes(k));
8235
8584
  const source = typeof entry.repo === "string" ? entry.repo : typeof entry.homepage === "string" ? entry.homepage : void 0;
8236
8585
  return {
8237
8586
  slug,
8238
8587
  name: typeof entry.name === "string" && entry.name.trim() ? entry.name.trim() : slug,
8239
8588
  command,
8240
8589
  args,
8241
- requiredEnvKeys: requiredEnvKeys2,
8590
+ requiredEnvKeys,
8591
+ optionalEnvKeys: optionalOnly,
8242
8592
  description: typeof entry.description === "string" ? entry.description : void 0,
8243
8593
  source,
8244
8594
  docUrl: source,
@@ -8582,7 +8932,7 @@ ${USAGE}`);
8582
8932
  );
8583
8933
  } else if (oamProbeResult.belowMin) {
8584
8934
  runtimeLines.push(
8585
- `Runtime: node (oam${oamVersion} is below the ${MIN_OAM_VERSION} minimum -- upgrade oam and re-run install to host yaw-mcp on it)`
8935
+ `Runtime: node (oam${oamVersion} is below the ${MIN_OAM_VERSION} minimum -- run \`oam self-update\`, then re-run install to host yaw-mcp on it)`
8586
8936
  );
8587
8937
  } else if (oamProbeResult.failure) {
8588
8938
  runtimeLines.push(
@@ -10294,6 +10644,7 @@ async function defaultFetchExplore(slug, catalogUrl) {
10294
10644
  args: resolved.args,
10295
10645
  requiredEnvVars: resolved.requiredEnvKeys
10296
10646
  };
10647
+ if (resolved.optionalEnvKeys.length > 0) out.optionalEnvVars = resolved.optionalEnvKeys;
10297
10648
  if (resolved.docUrl) out.docUrl = resolved.docUrl;
10298
10649
  return out;
10299
10650
  }
@@ -10391,6 +10742,9 @@ async function runTry(opts) {
10391
10742
  if (missing.length > 0) {
10392
10743
  printErr(`yaw-mcp try: ${server.name} needs the following env var(s) before it can run:`);
10393
10744
  for (const k of missing) printErr(` - ${k}`);
10745
+ if ((server.optionalEnvVars ?? []).length > 0) {
10746
+ printErr(`Optional, not needed to run: ${(server.optionalEnvVars ?? []).join(", ")}`);
10747
+ }
10394
10748
  printErr("");
10395
10749
  printErr("Set them via --env KEY=value (repeatable) or your shell, then re-run:");
10396
10750
  const example = missing.map((k) => `--env ${k}=...`).join(" ");
@@ -10398,8 +10752,9 @@ async function runTry(opts) {
10398
10752
  if (server.docUrl) printErr(`Docs: ${server.docUrl}`);
10399
10753
  return { exitCode: 1, written: [] };
10400
10754
  }
10755
+ const declaredEnvVars = [...server.requiredEnvVars ?? [], ...server.optionalEnvVars ?? []];
10401
10756
  const trialEnv = {};
10402
- for (const k of server.requiredEnvVars ?? []) {
10757
+ for (const k of declaredEnvVars) {
10403
10758
  const v = (lookup(k) ?? "").trim();
10404
10759
  if (v) trialEnv[k] = v;
10405
10760
  }
@@ -10409,9 +10764,11 @@ async function runTry(opts) {
10409
10764
  if (trimmed) trialEnv[k] = trimmed;
10410
10765
  }
10411
10766
  const overrides = opts.envOverrides ?? {};
10412
- const ambientOnlyRequired = (server.requiredEnvVars ?? []).filter(
10413
- (k) => !overrides[k] && (lookup(k) ?? "").trim() !== ""
10414
- );
10767
+ const ambientOnly = (k) => !overrides[k] && (lookup(k) ?? "").trim() !== "";
10768
+ const ambientOnlyRequired = [
10769
+ ...(server.requiredEnvVars ?? []).filter(ambientOnly),
10770
+ ...(server.optionalEnvVars ?? []).filter(ambientOnly).map((k) => `${k} (optional)`)
10771
+ ];
10415
10772
  const entry = buildLaunchEntry({
10416
10773
  os,
10417
10774
  upstream: {
@@ -10505,7 +10862,12 @@ async function runTry(opts) {
10505
10862
  print(`yaw-mcp try (dry-run): would write ${resolved.absolute}`);
10506
10863
  print(` entry name: ${entryName}`);
10507
10864
  print(` command: ${entry.command} ${entry.args.join(" ")}`);
10508
- if (entry.env) print(` env keys: ${Object.keys(entry.env).join(", ")}`);
10865
+ if (entry.env) {
10866
+ const optional = server.optionalEnvVars ?? [];
10867
+ print(
10868
+ ` env keys: ${Object.keys(entry.env).map((k) => optional.includes(k) ? `${k} (optional)` : k).join(", ")}`
10869
+ );
10870
+ }
10509
10871
  print(` expires: ${new Date(expiresAt).toISOString()}`);
10510
10872
  print(` marker: ${trialMarkerPath(slug, home)}`);
10511
10873
  if (replacesEntryInPlace) {
@@ -10569,7 +10931,7 @@ async function runTry(opts) {
10569
10931
  written.push(resolved.absolute);
10570
10932
  if (tightenPerms) {
10571
10933
  try {
10572
- await chmod5(resolved.absolute, 384);
10934
+ await chmod6(resolved.absolute, 384);
10573
10935
  } catch {
10574
10936
  }
10575
10937
  }
@@ -10578,7 +10940,7 @@ async function runTry(opts) {
10578
10940
  if (previousRead !== null && (!peelsPrevious || previousPeelFailedWhileTrusted)) {
10579
10941
  await atomicWriteFile(trialMarkerPath(slug, home), previousRead.raw).catch(() => void 0);
10580
10942
  } else {
10581
- await unlink(trialMarkerPath(slug, home)).catch(() => void 0);
10943
+ await unlink2(trialMarkerPath(slug, home)).catch(() => void 0);
10582
10944
  }
10583
10945
  return { exitCode: 1, written: [] };
10584
10946
  }
@@ -10710,7 +11072,7 @@ async function runTryCleanup(opts) {
10710
11072
  );
10711
11073
  }
10712
11074
  try {
10713
- await unlink(markerPath);
11075
+ await unlink2(markerPath);
10714
11076
  } catch (e) {
10715
11077
  printErr(`yaw-mcp try-cleanup: couldn't delete marker ${markerPath} (${e.message}).`);
10716
11078
  return { exitCode: 1, written: [] };
@@ -10789,7 +11151,7 @@ async function gcExpiredTrials(opts) {
10789
11151
  stage = "replaced";
10790
11152
  let markerRemoved = true;
10791
11153
  try {
10792
- await unlink(path5);
11154
+ await unlink2(path5);
10793
11155
  } catch {
10794
11156
  markerRemoved = false;
10795
11157
  }
@@ -10809,7 +11171,7 @@ async function gcExpiredTrials(opts) {
10809
11171
  throw new Error(`${marker.clientPath} is not a JSON object`);
10810
11172
  }
10811
11173
  stage = "unlink";
10812
- await unlink(path5);
11174
+ await unlink2(path5);
10813
11175
  cleared++;
10814
11176
  } catch (e) {
10815
11177
  const error = e.message;
@@ -11074,7 +11436,7 @@ function foldBundleWarnings(warnings, probe) {
11074
11436
  const prefix = `${probe.path}:`;
11075
11437
  return warnings.filter((w) => !w.startsWith(prefix));
11076
11438
  }
11077
- var VERSION = true ? "1.0.10" : "dev";
11439
+ var VERSION = true ? "1.0.12" : "dev";
11078
11440
  var DOCTOR_USAGE = `Usage: yaw-mcp doctor [--json]
11079
11441
 
11080
11442
  Print a diagnostic of your yaw-mcp setup.
@@ -11521,7 +11883,7 @@ var DOCTOR_ENV_VARS = [
11521
11883
  { name: "YAW_MCP_PRUNE_RESPONSES", defaultHint: "pruning active" },
11522
11884
  { name: "YAW_MCP_MAX_RESULT_BYTES", defaultHint: "default 100000" },
11523
11885
  { name: "YAW_MCP_DEFAULT_RUNTIME", defaultHint: "oam when installed" },
11524
- { name: "YAW_MCP_TOOL_EXPOSURE", defaultHint: "gateway" },
11886
+ { name: "YAW_MCP_TOOL_EXPOSURE", defaultHint: "gateway; lite for typed-cli" },
11525
11887
  { name: "YAW_MCP_AUTO_UPGRADE", defaultHint: "default on" },
11526
11888
  { name: "YAW_MCP_AUTO_HEAL", defaultHint: "default on" },
11527
11889
  { name: "YAW_MCP_SIDECAR_REFRESH", defaultHint: "default on" },
@@ -11557,15 +11919,25 @@ async function collectVaultStatus(opts) {
11557
11919
  let entries = exists2 ? null : [];
11558
11920
  let unreadable = null;
11559
11921
  let schemaVersion = null;
11922
+ let vault = null;
11560
11923
  if (exists2) {
11561
11924
  try {
11562
- const vault = await loadVault(path5);
11925
+ vault = await loadVault(path5);
11563
11926
  entries = vault ? listKeys(vault) : [];
11564
11927
  schemaVersion = vault ? vault.version : null;
11565
11928
  } catch (err) {
11566
11929
  unreadable = err instanceof Error ? err.message : String(err);
11567
11930
  }
11568
11931
  }
11932
+ const passphrase = opts.env.YAW_MCP_VAULT_PASSPHRASE ?? "";
11933
+ let passphraseUnlocks = null;
11934
+ let checkMarkerCorrupt = false;
11935
+ if (passphrase !== "" && vault !== null && vaultVerifiesPassphrases(vault)) {
11936
+ const verdict = await checkVaultPassphrase(vault, passphrase);
11937
+ lock();
11938
+ passphraseUnlocks = verdict === "opens";
11939
+ checkMarkerCorrupt = verdict === "marker-corrupt";
11940
+ }
11569
11941
  const refs = [];
11570
11942
  const malformed = [];
11571
11943
  for (const s of opts.servers) {
@@ -11584,7 +11956,9 @@ async function collectVaultStatus(opts) {
11584
11956
  entries,
11585
11957
  unreadable,
11586
11958
  schemaVersion,
11587
- passphraseSet: (opts.env.YAW_MCP_VAULT_PASSPHRASE ?? "") !== "",
11959
+ passphraseSet: passphrase !== "",
11960
+ passphraseUnlocks,
11961
+ checkMarkerCorrupt,
11588
11962
  refs,
11589
11963
  malformed,
11590
11964
  missing
@@ -11609,7 +11983,24 @@ function renderVaultSection(opts) {
11609
11983
  print(` schema: v${status.schemaVersion}`);
11610
11984
  }
11611
11985
  }
11612
- print(` passphrase: ${status.passphraseSet ? "set in this environment" : "not set in this environment"}`);
11986
+ if (!status.passphraseSet) {
11987
+ print(" passphrase: not set in this environment");
11988
+ } else if (status.passphraseUnlocks === true) {
11989
+ print(" passphrase: set in this environment, and it unlocks the vault");
11990
+ } else if (status.checkMarkerCorrupt) {
11991
+ print(" passphrase: set in this environment, and it is the vault's -- but the vault's check");
11992
+ print(" marker is corrupt, so nothing opens until it is repaired.");
11993
+ print(` ${vaultCheckCorruptHint(status.path)}`);
11994
+ } else if (status.passphraseUnlocks === false) {
11995
+ print(" passphrase: set in this environment, but it does NOT unlock the vault");
11996
+ print(" a server whose env references the vault fails to start or connect with it.");
11997
+ print(" Check the value in the `env` block of your client config (doctor sees THIS");
11998
+ print(" shell's, which can differ). If the passphrase is forgotten,");
11999
+ print(" `yaw-mcp secrets reset` moves the vault aside, lists its entry names, and");
12000
+ print(" starts a new one under a passphrase you choose.");
12001
+ } else {
12002
+ print(" passphrase: set in this environment");
12003
+ }
11613
12004
  if (status.refs.length === 0) {
11614
12005
  print(" refs: no server references ${secret:NAME} on the channel it uses (env local, headers remote)");
11615
12006
  } else {
@@ -11726,6 +12117,7 @@ function renderOamRuntimeSection(opts) {
11726
12117
  if (probe.belowMin) {
11727
12118
  print(` binary: installed (v${probe.version}) -- below min ${MIN_OAM_VERSION}; IGNORED, servers run on node`);
11728
12119
  print(" fix: oam self-update");
12120
+ print(" then: restart yaw-mcp -- a running broker keeps its oam probe for its lifetime");
11729
12121
  } else if (probe.failure !== null) {
11730
12122
  print(` binary: installed but UNUSABLE (${oamFailureLabel(probe.failure)}); servers run on node`);
11731
12123
  if (probe.failureDetail !== null) print(` detail: ${probe.failureDetail}`);
@@ -13105,83 +13497,92 @@ async function healStaleBrokerEntries(opts = {}) {
13105
13497
  replacement = { oamBinPath, oamEntry: oamBinPath === null ? null : resolveEntry("@yawlabs/mcp") };
13106
13498
  return replacement;
13107
13499
  };
13500
+ const clientEnv2 = readClientEnv(env);
13501
+ const appData = resolveAppDataDir({ appData: opts.appData, home: opts.home, env });
13502
+ const claudeConfigDir = opts.claudeConfigDir ?? clientEnv2.claudeConfigDir;
13108
13503
  const seen = /* @__PURE__ */ new Set();
13504
+ const healSite = async (target, scope, site) => {
13505
+ try {
13506
+ const view = await readClientConfigFile(site, { transform: target.entry });
13507
+ if (view.read.kind !== "ok") {
13508
+ if (view.read.kind !== "absent") {
13509
+ unhealable.push({
13510
+ clientId: target.clientId,
13511
+ scope,
13512
+ path: site.resolved.absolute,
13513
+ reason: view.read.kind
13514
+ });
13515
+ }
13516
+ return;
13517
+ }
13518
+ const stored = view.read.entries.find((e) => e.key === ENTRY_NAME);
13519
+ if (stored === void 0) return;
13520
+ const launch = stored.launch ?? launchOf(stored.value);
13521
+ if (launch === null) return;
13522
+ const entryPath = oamRunEntryPath(launch.command, launch.args);
13523
+ if (entryPath === null || !isOwnBrokerEntry(entryPath)) return;
13524
+ if (isForeignEntry(launch.command, entryPath, platform)) return;
13525
+ if (isLaunchableFile(entryPath)) return;
13526
+ const { oamBinPath, oamEntry } = await replacementFor();
13527
+ const base = buildLaunchEntry({
13528
+ os,
13529
+ oamBinPath,
13530
+ oamEntry,
13531
+ windowsWrap: target.entry?.windowsLaunch?.broker !== "bare"
13532
+ });
13533
+ const next = composeEntry({
13534
+ base,
13535
+ transform: target.entry,
13536
+ os,
13537
+ purpose: "broker",
13538
+ env: carryableEnvOf(stored.value),
13539
+ carried: carriedFieldsOf(stored.value, target.entry)
13540
+ });
13541
+ const nextLaunch = launchOf(next);
13542
+ const nextEntry = nextLaunch === null ? null : oamRunEntryPath(nextLaunch.command, nextLaunch.args);
13543
+ if (nextEntry !== null && norm(nextEntry, platform) === norm(entryPath, platform)) return;
13544
+ if (opts.dryRun !== true) {
13545
+ const text = applyClientConfigEdits(view, [{ op: "upsert", key: ENTRY_NAME, entry: next }], site);
13546
+ await atomicWriteFile(site.resolved.absolute, text);
13547
+ }
13548
+ healed.push({
13549
+ clientId: target.clientId,
13550
+ scope,
13551
+ path: site.resolved.absolute,
13552
+ from: entryPath,
13553
+ to: nextEntry ?? "npx"
13554
+ });
13555
+ } catch (err) {
13556
+ log("warn", "Could not heal a stale yaw-mcp entry", {
13557
+ path: site.resolved.absolute,
13558
+ error: err instanceof Error ? err.message : String(err)
13559
+ });
13560
+ }
13561
+ };
13109
13562
  for (const target of INSTALL_TARGETS) {
13110
13563
  for (const scope of target.scopes) {
13111
- let site;
13564
+ let sites;
13112
13565
  try {
13113
- site = resolveInstallSites({
13114
- clientId: target.clientId,
13115
- scope: scope.scope,
13116
- os,
13117
- home: opts.home,
13118
- appData: opts.appData,
13119
- projectDir: scope.requiresProjectDir ? opts.cwd ?? process.cwd() : void 0,
13120
- claudeConfigDir: opts.claudeConfigDir
13121
- })[0];
13566
+ sites = selectSites(
13567
+ resolveInstallSites({
13568
+ clientId: target.clientId,
13569
+ scope: scope.scope,
13570
+ os,
13571
+ home: opts.home,
13572
+ appData,
13573
+ projectDir: scope.requiresProjectDir ? opts.cwd ?? process.cwd() : void 0,
13574
+ claudeConfigDir,
13575
+ clientEnv: clientEnv2
13576
+ })
13577
+ );
13122
13578
  } catch {
13123
13579
  continue;
13124
13580
  }
13125
- if (site === void 0) continue;
13126
- const resolvedSite = site;
13127
- const key = `${norm(resolvedSite.resolved.absolute, platform)}::${addressOf(resolvedSite).containerPath.join(".")}`;
13128
- if (seen.has(key)) continue;
13129
- seen.add(key);
13130
- try {
13131
- const view = await readClientConfigFile(resolvedSite, { transform: target.entry });
13132
- if (view.read.kind !== "ok") {
13133
- if (view.read.kind !== "absent") {
13134
- unhealable.push({
13135
- clientId: target.clientId,
13136
- scope: scope.scope,
13137
- path: resolvedSite.resolved.absolute,
13138
- reason: view.read.kind
13139
- });
13140
- }
13141
- continue;
13142
- }
13143
- const stored = view.read.entries.find((e) => e.key === ENTRY_NAME);
13144
- if (stored === void 0) continue;
13145
- const launch = stored.launch ?? launchOf(stored.value);
13146
- if (launch === null) continue;
13147
- const entryPath = oamRunEntryPath(launch.command, launch.args);
13148
- if (entryPath === null || !isOwnBrokerEntry(entryPath)) continue;
13149
- if (isForeignEntry(launch.command, entryPath, platform)) continue;
13150
- if (isLaunchableFile(entryPath)) continue;
13151
- const { oamBinPath, oamEntry } = await replacementFor();
13152
- const base = buildLaunchEntry({
13153
- os,
13154
- oamBinPath,
13155
- oamEntry,
13156
- windowsWrap: target.entry?.windowsLaunch?.broker !== "bare"
13157
- });
13158
- const next = composeEntry({
13159
- base,
13160
- transform: target.entry,
13161
- os,
13162
- purpose: "broker",
13163
- env: carryableEnvOf(stored.value),
13164
- carried: carriedFieldsOf(stored.value, target.entry)
13165
- });
13166
- const nextLaunch = launchOf(next);
13167
- const nextEntry = nextLaunch === null ? null : oamRunEntryPath(nextLaunch.command, nextLaunch.args);
13168
- if (nextEntry !== null && norm(nextEntry, platform) === norm(entryPath, platform)) continue;
13169
- if (opts.dryRun !== true) {
13170
- const text = applyClientConfigEdits(view, [{ op: "upsert", key: ENTRY_NAME, entry: next }], resolvedSite);
13171
- await atomicWriteFile(resolvedSite.resolved.absolute, text);
13172
- }
13173
- healed.push({
13174
- clientId: target.clientId,
13175
- scope: scope.scope,
13176
- path: resolvedSite.resolved.absolute,
13177
- from: entryPath,
13178
- to: nextEntry ?? "npx"
13179
- });
13180
- } catch (err) {
13181
- log("warn", "Could not heal a stale yaw-mcp entry", {
13182
- path: resolvedSite.resolved.absolute,
13183
- error: err instanceof Error ? err.message : String(err)
13184
- });
13581
+ for (const site of sites) {
13582
+ const key = `${norm(site.resolved.absolute, platform)}::${addressOf(site).containerPath.join(".")}`;
13583
+ if (seen.has(key)) continue;
13584
+ seen.add(key);
13585
+ await healSite(target, scope.scope, site);
13185
13586
  }
13186
13587
  }
13187
13588
  }
@@ -13195,7 +13596,7 @@ async function healStaleBrokerEntries(opts = {}) {
13195
13596
  }
13196
13597
  async function maybeHealStaleBrokerEntries(opts = {}) {
13197
13598
  const env = opts.env ?? process.env;
13198
- if (env.YAW_MCP_AUTO_HEAL === "0") return { healed: [], unhealable: [] };
13599
+ if (isFeatureDisabled("YAW_MCP_AUTO_HEAL", env)) return { healed: [], unhealable: [] };
13199
13600
  try {
13200
13601
  return await healStaleBrokerEntries(opts);
13201
13602
  } catch (err) {
@@ -14093,9 +14494,16 @@ function jsonEntry(entry) {
14093
14494
  if (headerNames.length > 0) out.headerNames = headerNames;
14094
14495
  return out;
14095
14496
  }
14096
- function ambientOnlyRequiredKeys(requiredKeys, entry, env) {
14497
+ function ambientOnlyKeys(keys, entry, env) {
14498
+ const stored = entry.env ?? {};
14499
+ return keys.filter((k) => (stored[k] ?? "").trim() === "" && (env[k] ?? "").trim() !== "");
14500
+ }
14501
+ function unsetOptionalKeys(keys, entry, env) {
14097
14502
  const stored = entry.env ?? {};
14098
- return requiredKeys.filter((k) => (stored[k] ?? "").trim() === "" && (env[k] ?? "").trim() !== "");
14503
+ return keys.filter((k) => (stored[k] ?? "").trim() === "" && (env[k] ?? "").trim() === "");
14504
+ }
14505
+ function renderEnvKeys(env, optionalKeys) {
14506
+ return Object.keys(env).map((k) => optionalKeys.includes(k) ? `${k} (optional)` : k).join(", ");
14099
14507
  }
14100
14508
  async function danglingSecretRefs(entry, home) {
14101
14509
  const refSource = isRemoteEntry(entry) ? entry.headers : entry.env;
@@ -14132,6 +14540,22 @@ async function printPostWriteNotes(printErr, opts) {
14132
14540
  `Note: ${ambientOnly.join(", ")} ${verb} read from your shell env and NOT persisted; the server depends on ${one ? "that var" : "those vars"} being present wherever yaw-mcp launches. Pass --env ${ambientOnly[0]}=... to persist a value.`
14133
14541
  );
14134
14542
  }
14543
+ const optAmbient = opts.optional.ambient;
14544
+ if (optAmbient.length > 0) {
14545
+ const one = optAmbient.length === 1;
14546
+ const verb = dryRun ? "would be" : one ? "was" : "were";
14547
+ printErr(
14548
+ `Note: ${optAmbient.join(", ")} (optional) ${verb} read from your shell env and NOT persisted; the server reads ${one ? "it" : "them"} only where your shell sets ${one ? "it" : "them"}. Pass --env ${optAmbient[0]}=... to persist a value.`
14549
+ );
14550
+ }
14551
+ const optUnset = opts.optional.unset;
14552
+ if (optUnset.length > 0) {
14553
+ const one = optUnset.length === 1;
14554
+ const verb = one ? "is" : "are";
14555
+ printErr(
14556
+ `Note: ${optUnset.join(", ")} ${verb} optional and not set; the server runs without ${one ? "it" : "them"}. Set ${one ? "it" : "each"} later with \`yaw-mcp set ${opts.optional.namespace} env.${optUnset[0]}=...\`.`
14557
+ );
14558
+ }
14135
14559
  const shadow = await findShadowingProjectBundles(opts.cwd, opts.home, opts.env).catch(() => null);
14136
14560
  if (shadow) {
14137
14561
  printErr(
@@ -14240,6 +14664,7 @@ async function runAdd(opts) {
14240
14664
  // Nothing declares a requirement for a hand-defined server, so there is
14241
14665
  // no required-env gate to fail: whatever --env carries is all there is.
14242
14666
  requiredEnvKeys: [],
14667
+ optionalEnvKeys: [],
14243
14668
  description: opts.description
14244
14669
  };
14245
14670
  } else {
@@ -14263,6 +14688,9 @@ async function runAdd(opts) {
14263
14688
  if (missing.length > 0) {
14264
14689
  printErr(`yaw-mcp add: ${server.name} needs the following env var(s) before it can run:`);
14265
14690
  for (const k of missing) printErr(` - ${k}`);
14691
+ if (server.optionalEnvKeys.length > 0) {
14692
+ printErr(`Optional, not needed to run: ${server.optionalEnvKeys.join(", ")}`);
14693
+ }
14266
14694
  printErr("");
14267
14695
  printErr("Provide them with --env KEY=value (repeatable) or your shell, then re-run:");
14268
14696
  printErr(` yaw-mcp add ${slug} ${missing.map((k) => `--env ${k}=...`).join(" ")}`);
@@ -14270,7 +14698,7 @@ async function runAdd(opts) {
14270
14698
  return { exitCode: 1, written: [] };
14271
14699
  }
14272
14700
  const entryEnv = {};
14273
- for (const k of server.requiredEnvKeys) entryEnv[k] = "";
14701
+ for (const k of [...server.requiredEnvKeys, ...server.optionalEnvKeys]) entryEnv[k] = "";
14274
14702
  for (const [k, v] of Object.entries(opts.envOverrides ?? {})) {
14275
14703
  const trimmed = v.trim();
14276
14704
  if (trimmed === "") continue;
@@ -14295,7 +14723,16 @@ async function runAdd(opts) {
14295
14723
  transport: "stdio",
14296
14724
  command: server.command,
14297
14725
  args: server.args,
14298
- env: Object.keys(entryEnv).length > 0 ? entryEnv : void 0
14726
+ env: Object.keys(entryEnv).length > 0 ? entryEnv : void 0,
14727
+ // Which of the blank seeds above are optional. The entry env alone
14728
+ // cannot say -- a required key and an optional one are both "" until
14729
+ // filled -- and the Yaw app reads nothing but bundles.json when it
14730
+ // decides whether a server "needs key". The app writes the same
14731
+ // marker for the entries it adds; without ours, a server added here
14732
+ // showed "needs key" in the panel until re-added from the app.
14733
+ // Always an array so a re-add can CLEAR a stale marker (the merge
14734
+ // drops an empty one); an explicit-command add carries none.
14735
+ optionalEnvKeys: server.optionalEnvKeys
14299
14736
  },
14300
14737
  isActive: true,
14301
14738
  description: server.description,
@@ -14355,7 +14792,7 @@ If the existing entry is a different server you meant to keep, remove/re-add via
14355
14792
  const nsNote = previewNamespace === namespace ? `as namespace "${previewNamespace}"` : `keeping existing namespace "${previewNamespace}"`;
14356
14793
  print(`yaw-mcp add (dry-run): would ${preview.replaced ? "update" : "write"} ${server.name} ${nsNote}`);
14357
14794
  print(` launch: ${renderLaunch3(previewEntry)}`);
14358
- if (previewEntry.env) print(` env keys: ${Object.keys(previewEntry.env).join(", ")}`);
14795
+ if (previewEntry.env) print(` env keys: ${renderEnvKeys(previewEntry.env, server.optionalEnvKeys)}`);
14359
14796
  if (previewEntry.headers) print(` header names: ${Object.keys(previewEntry.headers).join(", ")}`);
14360
14797
  if (previewEntry.isActive === false) {
14361
14798
  print(
@@ -14364,7 +14801,12 @@ If the existing entry is a different server you meant to keep, remove/re-add via
14364
14801
  }
14365
14802
  }
14366
14803
  await printPostWriteNotes(printErr, {
14367
- ambientOnly: ambientOnlyRequiredKeys(server.requiredEnvKeys, previewEntry, env),
14804
+ ambientOnly: ambientOnlyKeys(server.requiredEnvKeys, previewEntry, env),
14805
+ optional: {
14806
+ ambient: ambientOnlyKeys(server.optionalEnvKeys, previewEntry, env),
14807
+ unset: unsetOptionalKeys(server.optionalEnvKeys, previewEntry, env),
14808
+ namespace: previewNamespace
14809
+ },
14368
14810
  // Previewed from the entry the run WOULD write, so --dry-run reports the
14369
14811
  // same dangling refs the real run would.
14370
14812
  dangling: await danglingSecretRefs(previewEntry, home),
@@ -14415,7 +14857,12 @@ If the previous entry was a different server you meant to keep, restore it from
14415
14857
  }
14416
14858
  }
14417
14859
  await printPostWriteNotes(printErr, {
14418
- ambientOnly: ambientOnlyRequiredKeys(server.requiredEnvKeys, written, env),
14860
+ ambientOnly: ambientOnlyKeys(server.requiredEnvKeys, written, env),
14861
+ optional: {
14862
+ ambient: ambientOnlyKeys(server.optionalEnvKeys, written, env),
14863
+ unset: unsetOptionalKeys(server.optionalEnvKeys, written, env),
14864
+ namespace: finalNamespace
14865
+ },
14419
14866
  // From the entry as WRITTEN, not from the flags: a re-add merges with what
14420
14867
  // was already on disk, so the stored refs are what will actually resolve.
14421
14868
  dangling: await danglingSecretRefs(written, home),
@@ -15204,7 +15651,7 @@ async function runEnableDisable(opts) {
15204
15651
 
15205
15652
  // src/reset-learning-cmd.ts
15206
15653
  import { existsSync as existsSync8 } from "fs";
15207
- import { unlink as unlink2 } from "fs/promises";
15654
+ import { unlink as unlink3 } from "fs/promises";
15208
15655
  import { homedir as homedir21 } from "os";
15209
15656
  import { createInterface as createInterface6 } from "readline/promises";
15210
15657
  var RESET_LEARNING_USAGE = `Usage: yaw-mcp reset-learning
@@ -15318,7 +15765,7 @@ async function runResetLearning(opts = {}) {
15318
15765
  }
15319
15766
  }
15320
15767
  try {
15321
- await unlink2(filePath);
15768
+ await unlink3(filePath);
15322
15769
  } catch (err) {
15323
15770
  if (isFileNotFound(err)) {
15324
15771
  print("yaw-mcp reset-learning: no persisted state to reset.");
@@ -15410,10 +15857,22 @@ ${SEARCH_USAGE}` };
15410
15857
  opts.query = words.join(" ");
15411
15858
  return { ok: true, options: opts };
15412
15859
  }
15413
- function requiredEnvKeys(entry) {
15860
+ function catalogEnvKeys(entry) {
15414
15861
  const raw = entry.requiredEnv;
15415
- if (!Array.isArray(raw)) return [];
15416
- return raw.map((r) => typeof r === "string" ? r : r?.key).filter((k) => typeof k === "string" && k !== "");
15862
+ const required = [];
15863
+ const optional = [];
15864
+ if (!Array.isArray(raw)) return { required, optional };
15865
+ for (const r of raw) {
15866
+ const key = typeof r === "string" ? r : r?.key;
15867
+ if (typeof key !== "string" || key === "") continue;
15868
+ const flagged = typeof r === "object" && r !== null && r.optional === true;
15869
+ (flagged ? optional : required).push(key);
15870
+ }
15871
+ return { required, optional };
15872
+ }
15873
+ function catalogEnvKeysJson(entry) {
15874
+ const { required, optional } = catalogEnvKeys(entry);
15875
+ return { requiredEnvKeys: required, optionalEnvKeys: optional };
15417
15876
  }
15418
15877
  function truncate(text, cap) {
15419
15878
  if (text.length <= cap) return text;
@@ -15426,11 +15885,12 @@ function metaLine(entry) {
15426
15885
  const parts = [`runtime ${typeof install.runtime === "string" ? install.runtime : "unknown"}`];
15427
15886
  const toolCount = entry.toolCount;
15428
15887
  if (typeof toolCount === "number") parts.push(`${toolCount} ${toolCount === 1 ? "tool" : "tools"}`);
15429
- const keys = requiredEnvKeys(entry);
15430
- if (keys.length > 0) parts.push(`needs ${keys.join(", ")}`);
15888
+ const { required, optional } = catalogEnvKeys(entry);
15889
+ if (required.length > 0) parts.push(`needs ${required.join(", ")}`);
15431
15890
  else if (entry.requiresSetup === true)
15432
- parts.push("needs setup (no env keys listed)");
15891
+ parts.push(optional.length > 0 ? "needs setup" : "needs setup (no env keys listed)");
15433
15892
  else parts.push("no credentials");
15893
+ if (optional.length > 0) parts.push(`optional ${optional.join(", ")}`);
15434
15894
  const runtime = typeof install.runtime === "string" ? install.runtime.toLowerCase() : "";
15435
15895
  if (install.url || install.type === "remote" || /^(remote|https?|sse|url)$/.test(runtime)) {
15436
15896
  parts.push("remote -- add by hand");
@@ -15455,7 +15915,10 @@ function renderJson(opts, catalogUrl, matches, shown, suggested) {
15455
15915
  tags: entry.tags,
15456
15916
  runtime: entry.install?.runtime,
15457
15917
  command: entry.install?.command,
15458
- requiredEnvKeys: requiredEnvKeys(entry),
15918
+ // `requiredEnvKeys` keeps its pre-flag meaning (what `add` refuses
15919
+ // without) so a script gating on it does not start refusing servers
15920
+ // it used to accept; the optional keys ride in their own field.
15921
+ ...catalogEnvKeysJson(entry),
15459
15922
  toolCount: entry.toolCount,
15460
15923
  estimatedTokens: entry.estimatedTokens,
15461
15924
  repo: entry.repo
@@ -15552,6 +16015,7 @@ function decideServeMode(stdin, env) {
15552
16015
 
15553
16016
  // src/server.ts
15554
16017
  import { homedir as homedir22 } from "os";
16018
+ import { getSupportedElicitationModes } from "@modelcontextprotocol/sdk/client/index.js";
15555
16019
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
15556
16020
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15557
16021
  import {
@@ -15564,138 +16028,6 @@ import {
15564
16028
  ReadResourceRequestSchema
15565
16029
  } from "@modelcontextprotocol/sdk/types.js";
15566
16030
 
15567
- // src/auto-prewarm.ts
15568
- import { spawn as spawn4 } from "child_process";
15569
- var DEFAULT_MAX_AUTO_PREWARM = 20;
15570
- var DEFAULT_AUTO_PREWARM_TIMEOUT_MS = 3e4;
15571
- var AUTO_PREWARM_DISABLE_ENV = "YAW_MCP_AUTO_PREWARM";
15572
- var AUTO_PREWARM_MAX_ENV = "YAW_MCP_MAX_AUTO_PREWARM";
15573
- var AUTO_PREWARM_TIMEOUT_ENV = "YAW_MCP_AUTO_PREWARM_TIMEOUT";
15574
- var NPX_PACKAGE_PATTERN = /^@?[\w.-]+\/[\w.-]+@[\w.*+-]+$|^[\w.-]+@[\w.*+-]+$/;
15575
- function extractNpxPackages(servers) {
15576
- const seen = /* @__PURE__ */ new Set();
15577
- const out = [];
15578
- for (const server of servers) {
15579
- if (server.type !== "local") continue;
15580
- if (server.command !== "npx") continue;
15581
- const args = server.args ?? [];
15582
- if (args[0] !== "-y") continue;
15583
- for (const arg of args.slice(1)) {
15584
- if (typeof arg !== "string") continue;
15585
- if (!NPX_PACKAGE_PATTERN.test(arg)) continue;
15586
- if (seen.has(arg)) continue;
15587
- seen.add(arg);
15588
- out.push(arg);
15589
- break;
15590
- }
15591
- }
15592
- return out;
15593
- }
15594
- function isAutoPrewarmDisabled(env = process.env) {
15595
- const raw = env[AUTO_PREWARM_DISABLE_ENV];
15596
- if (raw === void 0) return false;
15597
- const trimmed = raw.trim();
15598
- if (trimmed === "") return false;
15599
- return trimmed === "0" || trimmed.toLowerCase() === "false";
15600
- }
15601
- function parseAutoPrewarmMax(env = process.env, fallback = DEFAULT_MAX_AUTO_PREWARM) {
15602
- const raw = env[AUTO_PREWARM_MAX_ENV];
15603
- if (raw === void 0 || raw === "") return fallback;
15604
- const n = Number.parseInt(raw, 10);
15605
- return Number.isFinite(n) && n > 0 ? n : fallback;
15606
- }
15607
- function parseAutoPrewarmTimeoutMs(env = process.env, fallback = DEFAULT_AUTO_PREWARM_TIMEOUT_MS) {
15608
- const raw = env[AUTO_PREWARM_TIMEOUT_ENV];
15609
- if (raw === void 0 || raw === "") return fallback;
15610
- const n = Number.parseInt(raw, 10);
15611
- return Number.isFinite(n) && n > 0 ? n : fallback;
15612
- }
15613
- function defaultAcquireLockImpl() {
15614
- if (process.env.VITEST) return () => {
15615
- };
15616
- return acquireSidecarsLock(sidecarsRoot());
15617
- }
15618
- function defaultSpawn(pkg, timeoutMs) {
15619
- let errorFired = false;
15620
- let done;
15621
- const donePromise = new Promise((resolve8) => {
15622
- done = resolve8;
15623
- });
15624
- const opts = {
15625
- stdio: "ignore",
15626
- // Mirror auto-upgrade.ts:736. npm runs every transitive pre/postinstall
15627
- // with this env; YAW_MCP_VAULT_PASSPHRASE in particular is in process.env
15628
- // only by operator choice and must not be forwarded to a download.
15629
- env: stripInternalSecretsFromEnv(process.env),
15630
- detached: false,
15631
- shell: process.platform === "win32"
15632
- };
15633
- const child = spawn4("npx", ["-y", pkg, "--version"], opts);
15634
- const finish = (reason, ok) => {
15635
- done({ reason, ok });
15636
- };
15637
- child.on("close", (code) => {
15638
- if (errorFired) return;
15639
- finish("exit", code === 0);
15640
- });
15641
- child.on("error", (err) => {
15642
- errorFired = true;
15643
- log("warn", "auto-prewarm: npx spawn failed", { package: pkg, error: err?.message });
15644
- finish("spawn-error", false);
15645
- });
15646
- const timer = setTimeout(() => {
15647
- log("warn", "auto-prewarm: npx prime exceeded timeout; aborting", { package: pkg, timeoutMs });
15648
- try {
15649
- child.kill("SIGTERM");
15650
- } catch {
15651
- }
15652
- finish("timeout", false);
15653
- }, timeoutMs);
15654
- timer.unref();
15655
- donePromise.finally(() => clearTimeout(timer));
15656
- return { package: pkg, child, done: donePromise };
15657
- }
15658
- async function maybeAutoPrewarmNpxCache(deps = {}) {
15659
- try {
15660
- if ((deps.isDisabled ?? (() => isAutoPrewarmDisabled()))()) return;
15661
- const listServers = deps.listActiveServers ?? (() => []);
15662
- const max = deps.maxPackages ?? (() => parseAutoPrewarmMax());
15663
- const timeoutMs = deps.perPackageTimeoutMs ?? (() => parseAutoPrewarmTimeoutMs());
15664
- const spawnOne = deps.spawnImpl ?? ((pkg) => defaultSpawn(pkg, timeoutMs()));
15665
- const acquire = deps.acquireLockImpl ?? defaultAcquireLockImpl;
15666
- const packages = extractNpxPackages(listServers());
15667
- if (packages.length === 0) return;
15668
- const capped = packages.length > max() ? packages.slice(0, max()) : packages;
15669
- if (packages.length > capped.length) {
15670
- log(
15671
- "info",
15672
- `auto-prewarm: capping at ${capped.length} of ${packages.length} npx packages (YAW_MCP_MAX_AUTO_PREWARM)`,
15673
- { capped: capped.length, total: packages.length }
15674
- );
15675
- }
15676
- const release = acquire();
15677
- if (release === null) {
15678
- log("info", "auto-prewarm: another process holds the sidecars lock; skipping this pass");
15679
- return;
15680
- }
15681
- const start = Date.now();
15682
- const results = await Promise.all(capped.map((pkg) => spawnOne(pkg).done));
15683
- release();
15684
- const okCount = results.filter((r) => r.ok).length;
15685
- const failed = capped.length - okCount;
15686
- const elapsedMs = Date.now() - start;
15687
- const level = failed === 0 ? "info" : "warn";
15688
- log(level, `auto-prewarmed ${okCount} of ${capped.length} npx packages in ${elapsedMs}ms (failed: ${failed})`, {
15689
- ok: okCount,
15690
- failed,
15691
- total: capped.length,
15692
- elapsedMs
15693
- });
15694
- } catch (err) {
15695
- log("warn", "auto-prewarm: unexpected failure", { error: err?.message });
15696
- }
15697
- }
15698
-
15699
16031
  // src/cost-estimate.ts
15700
16032
  var BYTES_PER_TOKEN = 4;
15701
16033
  var CACHED_TOOL_SCHEMA_PAD_BYTES = 200;
@@ -16217,20 +16549,25 @@ function recordNudges(clis, home, now = Date.now) {
16217
16549
 
16218
16550
  // src/meta-tools.ts
16219
16551
  var PENALTY_RATE_PCT = Math.round(PENALTY_RATE_THRESHOLD * 100);
16552
+ var SERVER_INSTRUCTIONS = [
16553
+ "yaw-mcp fronts every MCP server the user installed; tools/list shows the mcp_connect_* meta-tools plus servers loaded THIS session. Each load adds tools to your context: unload (mcp_connect_deactivate) when done.",
16554
+ "Concrete task: mcp_connect_dispatch loads the best server in one call. Browsing: mcp_connect_discover. Known 2-4 step chain: mcp_connect_exec (calls a cached server's tool by name, no load needed).",
16555
+ "Prefer a server over the CLI it shadows. Read yaw-mcp://guide first when listed: this project's routing rules."
16556
+ ].join(" ");
16220
16557
  var META_TOOLS = {
16221
16558
  discover: {
16222
16559
  name: "mcp_connect_discover",
16223
- description: 'List the MCP servers configured in the user\'s local ~/.yaw-mcp/bundles.json and ready to use. Call this when browsing what\'s available or when the task isn\'t specific yet. If the task is already clear ("file a github issue", "query postgres", "post to slack"), prefer `mcp_connect_dispatch` \u2014 it picks the right server and loads its tools in one call. Load only the servers the CURRENT task needs; each one adds tools to your context. Shows names, namespaces, tool counts, a token-cost estimate per server (e.g. "22 tools, ~2.8k tokens") so you can budget context before activating \u2014 tilde values are estimates based on cached tool metadata, unprefixed values reflect live tool schemas. Tool-name lists are truncated to the first few names per server; pass `server` to see the full list for one server. Scored servers carry an inline `[A]`\u2013`[F]` compliance grade from the Yaw MCP test suite \u2014 treat it as a trust signal and prefer higher-graded alternatives when otherwise equivalent (ungraded servers are unmarked, not penalized). Also surfaces whether each server is loaded, any local CLI it shadows (prefer the MCP tools over the CLI when a shadow is listed), and usage hints ("used Nx" or "often loaded with X") when the signals are present (counts persist across yaw-mcp restarts). Recurring packs that have been loaded together \u22652 times get their own block at the top with a ready-to-run `activate` call \u2014 skip the extra `mcp_connect_suggest` round-trip when the signal is already there. If a `yaw-mcp://guide` resource is listed, read it FIRST: it carries project/user-specific routing rules and credential conventions that override generic defaults.',
16560
+ description: "List the MCP servers installed in the user's ~/.yaw-mcp/bundles.json: name, namespace, tool count, an estimated token cost (a tilde marks an estimate from cached metadata), whether it is loaded, any local CLI it shadows, an inline `[A]`-`[F]` compliance grade when scored (ungraded is unmarked, not penalized), and usage hints. Tool-name lists are truncated; pass `server` for one server's full card. Recurring packs get a ready-to-run `mcp_connect_activate` call at the top.",
16224
16561
  inputSchema: {
16225
16562
  type: "object",
16226
16563
  properties: {
16227
16564
  context: {
16228
16565
  type: "string",
16229
- description: "Optional: describe the current task or conversation context. Servers will be sorted by relevance to help you pick the right one."
16566
+ description: "Optional: the current task. Servers are sorted by relevance to it."
16230
16567
  },
16231
16568
  server: {
16232
16569
  type: "string",
16233
- description: "Optional: one namespace to report on in full. Returns just that server's card with its complete tool list, and none of the cross-server blocks."
16570
+ description: "Optional: one namespace to report on in full -- just that server's card, with its complete tool list."
16234
16571
  }
16235
16572
  }
16236
16573
  },
@@ -16244,7 +16581,7 @@ var META_TOOLS = {
16244
16581
  },
16245
16582
  activate: {
16246
16583
  name: "mcp_connect_activate",
16247
- description: 'Load one or more installed MCP servers\' tools into the current session by namespace. Each server adds its tools to your context, so load only what the current task needs. When you move on, unload servers you\'re done with via `mcp_connect_deactivate` before loading new ones. Tools are prefixed by namespace (e.g., "gh_create_issue"). Pass "server" for one or "servers" for multiple. Optionally pass `tools: [...]` to expose only those tools by name \u2014 the rest stay proxyable via mcp_connect_dispatch. If `YAW_MCP_MIN_COMPLIANCE` is set, activation refuses servers whose reported grade is below the floor (ungraded servers always pass); the refusal message names the grade and the env var to unset.',
16584
+ description: "Load one or more installed servers' tools into this session by namespace; tools are prefixed by it (e.g. \"gh_create_issue\"). Pass `server` for one or `servers` for several. `tools: [...]` (single server only) advertises just those tools; the rest stay callable by name. Refused when YAW_MCP_MIN_COMPLIANCE is set and the server's grade is below it (ungraded always passes); the message names the grade and the variable.",
16248
16585
  inputSchema: {
16249
16586
  type: "object",
16250
16587
  properties: {
@@ -16260,7 +16597,7 @@ var META_TOOLS = {
16260
16597
  tools: {
16261
16598
  type: "array",
16262
16599
  items: { type: "string" },
16263
- description: "Optional per-server tool filter (bare tool names, not namespace-prefixed). When set, only the listed tools surface in tools/list \u2014 others stay reachable via mcp_connect_dispatch. Omit (or re-activate without it) to expose the full tool set. Only applied when activating a single server."
16600
+ description: "Optional per-server tool filter (bare names, not namespace-prefixed). Only the listed tools surface in tools/list; the rest stay callable by name. Omit, or re-activate without it, for the full set. Single-server activation only."
16264
16601
  }
16265
16602
  }
16266
16603
  },
@@ -16274,7 +16611,7 @@ var META_TOOLS = {
16274
16611
  },
16275
16612
  deactivate: {
16276
16613
  name: "mcp_connect_deactivate",
16277
- description: 'Unload one or more MCP servers\' tools from the current session to free context. The server stays configured in ~/.yaw-mcp/bundles.json and can be reloaded via `mcp_connect_activate` when needed again. Unload servers you\'re done with; yaw-mcp also auto-unloads a server after a stretch of tool calls to other servers (baseline set by YAW_MCP_IDLE_THRESHOLD, raised for a server used in bursts). Pass "server" for one or "servers" for multiple.',
16614
+ description: "Unload one or more loaded servers' tools from this session to free context. The server stays installed and can be reloaded with `mcp_connect_activate`. yaw-mcp also auto-unloads a server after a run of calls to other servers (baseline YAW_MCP_IDLE_THRESHOLD, raised for a server used in bursts).",
16278
16615
  inputSchema: {
16279
16616
  type: "object",
16280
16617
  properties: {
@@ -16299,7 +16636,7 @@ var META_TOOLS = {
16299
16636
  },
16300
16637
  health: {
16301
16638
  name: "mcp_connect_health",
16302
- description: `Show health stats for MCP servers loaded in the current session: total calls, error count, average latency, and last error. Per-call telemetry covers LOADED servers only; installed-but-unloaded servers with a poor persisted success rate (<${PENALTY_RATE_PCT}% across sessions) are listed in a separate cross-session reliability block \u2014 do NOT load a server just to see its history, loading it resets the in-session counters to zero.`,
16639
+ description: `Health stats for the servers loaded this session: total calls, error count, average latency, last error. Installed-but-unloaded servers with a poor persisted success rate (<${PENALTY_RATE_PCT}% across sessions) are listed in a separate block -- do NOT load a server just to see its history, loading resets its in-session counters.`,
16303
16640
  inputSchema: {
16304
16641
  type: "object",
16305
16642
  properties: {}
@@ -16314,7 +16651,7 @@ var META_TOOLS = {
16314
16651
  },
16315
16652
  dispatch: {
16316
16653
  name: "mcp_connect_dispatch",
16317
- description: 'PREFERRED entry point when the task is already concrete. Picks the best-matching installed MCP server(s) for a natural-language task and loads their tools in ONE call \u2014 no separate discover + load step. Describe what you want to do ("create a github issue for the login bug", "post a summary to slack", "query the prod postgres") and yaw-mcp will rank the user\'s installed servers with BM25, load the top match into the session, and expose its tools so you can call them. Use `mcp_connect_discover` only when browsing what\'s installed without a specific task. When an installed MCP server shadows a local CLI (e.g. npmjs shadows `npm`, tailscale shadows `tailscale`, github shadows `gh`), prefer dispatching to the server over running the CLI via Bash. Default budget is 1 to keep the tool list focused; raise it only if the task genuinely spans multiple servers. If `yaw-mcp://guide` is listed as a resource, read it first \u2014 the project may have explicit routing rules (e.g. "use `gh` not bash for GitHub").',
16654
+ description: 'Pick the best-matching installed server(s) for a natural-language task and load their tools in one call. Describe the task ("create a github issue for the login bug", "query the prod postgres"); yaw-mcp ranks the installed servers with BM25 and loads the top match. `budget` defaults to 1; raise it only when one task genuinely spans several servers.',
16318
16655
  inputSchema: {
16319
16656
  type: "object",
16320
16657
  properties: {
@@ -16332,12 +16669,12 @@ var META_TOOLS = {
16332
16669
  minimum: 1,
16333
16670
  maximum: 10,
16334
16671
  default: 1,
16335
- 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."
16672
+ description: "How many top-ranked servers to load. Default 1, cap 10."
16336
16673
  },
16337
16674
  routeEffort: {
16338
16675
  type: "string",
16339
16676
  enum: ["off", "auto", "aggressive"],
16340
- 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.'
16677
+ description: 'Per-call routing-effort dial: "off" never asks the client LLM to break a ranking tie, "auto" (default) asks once on genuine ambiguity, "aggressive" samples best-of-3 on milder ambiguity. Falls back to YAW_MCP_ROUTE_EFFORT. Budget 1 only.'
16341
16678
  }
16342
16679
  },
16343
16680
  required: ["intent"]
@@ -16352,7 +16689,7 @@ var META_TOOLS = {
16352
16689
  },
16353
16690
  read_tool: {
16354
16691
  name: "mcp_connect_read_tool",
16355
- description: "Return one tool's full input schema without loading its server into the session. Use this when you need to inspect an MCP tool's arguments before deciding whether to activate its server, or to compare schemas across two tools. For already-loaded servers this is free (schema is in memory). For not-loaded servers yaw-mcp spawns a transient upstream connection, reads the schema, and tears the connection down \u2014 no tools are added to your context, and `mcp_connect_health` will not show the server as loaded. When you're ready to actually call the tool, pass the server namespace to `mcp_connect_activate` (or use `mcp_connect_dispatch` with the task intent).",
16692
+ description: "Return one tool's full input schema without loading its server. Free for a loaded server; for an unloaded one yaw-mcp opens a transient connection, reads the schema and closes it -- nothing is added to the session. To call the tool, load its server with `mcp_connect_activate` or call it by name from `mcp_connect_exec`.",
16356
16693
  inputSchema: {
16357
16694
  type: "object",
16358
16695
  properties: {
@@ -16362,7 +16699,7 @@ var META_TOOLS = {
16362
16699
  },
16363
16700
  tool: {
16364
16701
  type: "string",
16365
- description: 'Tool name. The namespace prefix is optional \u2014 both "create_issue" and "gh_create_issue" are accepted.'
16702
+ description: 'Tool name; the namespace prefix is optional ("create_issue" and "gh_create_issue" both work).'
16366
16703
  }
16367
16704
  },
16368
16705
  required: ["server", "tool"]
@@ -16377,13 +16714,13 @@ var META_TOOLS = {
16377
16714
  },
16378
16715
  findTool: {
16379
16716
  name: "mcp_connect_find_tool",
16380
- description: 'Search for a TOOL across every configured server by what it DOES, when you do not know which server has it. Ranks tool names and descriptions from all servers -- loaded and not -- and returns the matches with the namespace to activate. Nothing is loaded and no server is contacted, so this costs no context beyond the reply. Use it when the capability is clear but its home is not ("something that can resize an image", "a way to list pull requests"); use `mcp_connect_dispatch` instead when you want the right server LOADED in one step, and `mcp_connect_read_tool` when you already know both the server and the tool and just want its schema. A match on a loaded server carries its full input schema; a match on a server that has never been loaded carries name and description only, from cache -- activate it, or call `mcp_connect_read_tool`, to see the arguments.',
16717
+ description: 'Search every installed server\'s tools by what they DO ("resize an image", "list pull requests") when you do not know which server has it. Ranks tool names and descriptions across loaded and unloaded servers from cache; nothing is loaded and no server is contacted. A match on a loaded server carries its full input schema; one on a never-loaded server carries name and description only -- `mcp_connect_read_tool` returns its arguments.',
16381
16718
  inputSchema: {
16382
16719
  type: "object",
16383
16720
  properties: {
16384
16721
  query: {
16385
16722
  type: "string",
16386
- description: 'What the tool should DO, in plain words -- "create a github issue", "query postgres", "resize an image". Matched against every configured server tool name and description.'
16723
+ description: 'What the tool should DO, in plain words -- "create a github issue", "query postgres", "resize an image".'
16387
16724
  },
16388
16725
  limit: {
16389
16726
  type: "number",
@@ -16402,7 +16739,7 @@ var META_TOOLS = {
16402
16739
  },
16403
16740
  suggest: {
16404
16741
  name: "mcp_connect_suggest",
16405
- description: "Surface recurring multi-server tool-call patterns as suggested 'packs' to activate in one step. Observation-only \u2014 this never loads or unloads anything. When the same 2-3 servers get used together in short bursts more than once, the pattern is surfaced here so the next workflow can call `mcp_connect_activate` once with the whole pack's namespaces instead of juggling discover + load for each server. Patterns persist across yaw-mcp restarts (via ~/.yaw-mcp/state.json) so a fresh process already knows what you usually use together. As a general rule: prefer loaded MCP servers over matching local CLIs (a loaded `npmjs` server replaces `npm audit`, `tailscale` replaces the `tailscale` CLI, etc.) \u2014 see `mcp_connect_discover` for which CLIs each installed server shadows. Returns a friendly 'no patterns yet' message when nothing has recurred.",
16742
+ description: "Surface recurring multi-server 'packs' -- servers used together in short bursts more than once -- each as a ready-to-run `mcp_connect_activate` call with all its namespaces. Observation-only: loads and unloads nothing. Patterns persist across yaw-mcp restarts. Returns a 'no patterns yet' message when nothing has recurred.",
16406
16743
  inputSchema: {
16407
16744
  type: "object",
16408
16745
  properties: {}
@@ -16417,14 +16754,14 @@ var META_TOOLS = {
16417
16754
  },
16418
16755
  bundles: {
16419
16756
  name: "mcp_connect_bundles",
16420
- description: 'List curated multi-server \'bundles\' \u2014 presets like `pr-review` (github + linear) or `devops-incident` (github + pagerduty + slack) that commonly ship together. Routing order is `mcp_connect_dispatch` > this > `mcp_connect_discover`: when the task is one concrete action ("file a github issue"), dispatch still comes first. Reach for bundles when the intent maps to a known multi-server WORKFLOW (on-call triage, PR review, data pipeline debugging) rather than a single call, and before `mcp_connect_discover` \u2014 it returns a ready-to-run `mcp_connect_activate namespaces=[...]` call per bundle. With `action="match"` (recommended after the user\'s installed list is known) the response partitions bundles into READY (every namespace already in the user\'s bundles.json \u2014 activate now) and PARTIAL (some present, some missing \u2014 names the missing namespaces so you can tell the user to run `yaw-mcp add <slug>`; the slug catalog is at https://yaw.sh/mcp/catalog/). With `action="list"` (default) it returns the full curated catalog. Bundles are static client-side data, not a network call.',
16757
+ description: 'List curated multi-server \'bundles\' (`pr-review` = github + linear, `devops-incident` = github + pagerduty + slack, ...) for a known multi-server WORKFLOW, each with a ready-to-run `mcp_connect_activate namespaces=[...]` call. `action="match"` partitions them against the installed servers into READY (activate now) and PARTIAL (names the missing namespaces; `yaw-mcp add <slug>` installs one, catalog at https://yaw.sh/mcp/catalog/). `action="list"` (default) returns the whole catalog. Static data, no network call.',
16421
16758
  inputSchema: {
16422
16759
  type: "object",
16423
16760
  properties: {
16424
16761
  action: {
16425
16762
  type: "string",
16426
16763
  enum: ["list", "match"],
16427
- description: 'Either "list" (return the full curated catalog; default) or "match" (partition bundles against installed servers into ready-to-activate vs partially-installed).'
16764
+ description: '"list" (default): the full curated catalog. "match": partition against installed servers.'
16428
16765
  }
16429
16766
  }
16430
16767
  },
@@ -16438,13 +16775,13 @@ var META_TOOLS = {
16438
16775
  },
16439
16776
  secrets: {
16440
16777
  name: "mcp_connect_secrets",
16441
- description: "List, per installed server, which local-vault secrets its `${secret:NAME}` env references resolve to \u2014 by NAME only, never a value. Use this to confirm a server will get the credentials it needs before activating it, or to spot a typo'd / un-set secret reference. `injectedSecrets` are the names the local vault HAS and the server references; `missing` are names the server references but the vault LACKS (set them via `yaw-mcp secrets set <name>`); `malformed` are `${secret:` references that do not PARSE (a space in the name, a missing `}`), quoted in bounded form behind a `<malformed ref>` marker -- yaw-mcp refuses to start the server over one exactly as over a missing name, so the fix is editing the reference in the server's env. This is a values-free preview: it reads the vault's KEY LIST and the server's env-reference NAMES, and never decrypts or returns any secret value. Servers with no `${secret:...}` references (well-formed or malformed) are omitted. Requires no passphrase (no decryption happens).",
16778
+ description: "Report, per installed server, which local-vault secrets its `${secret:NAME}` references resolve to -- NAMES only, never a value. `injectedSecrets`: names the vault has. `missing`: names it lacks (`yaw-mcp secrets set <name>`). `malformed`: references that do not parse (a space in the name, a missing `}`), quoted in bounded form behind a `<malformed ref>` marker. yaw-mcp refuses to start a server over a missing or malformed reference. Servers with no references are omitted. Decrypts nothing; needs no passphrase.",
16442
16779
  inputSchema: {
16443
16780
  type: "object",
16444
16781
  properties: {
16445
16782
  server: {
16446
16783
  type: "string",
16447
- description: 'Optional: restrict the report to a single server namespace (e.g. "gh"). Omit to report every installed server that references a vault secret.'
16784
+ description: 'Optional: one server namespace (e.g. "gh"). Omit for every server that references a vault secret.'
16448
16785
  }
16449
16786
  }
16450
16787
  },
@@ -16461,30 +16798,30 @@ var META_TOOLS = {
16461
16798
  // Joined rather than one literal so the step cap can be interpolated from
16462
16799
  // MAX_EXEC_STEPS -- the constant validateExecRequest actually enforces.
16463
16800
  description: [
16464
- "Run a short DECLARATIVE pipeline of upstream tool calls in a single round-trip. Use this when you already know the exact 2-4 tool calls to make and one call's output feeds another's args \u2014 e.g. `a = gh_list_prs(); b = gh_get_pr(a[0].number); return b`. NOT a code sandbox: there is no expression language, no loops, no branching, no arithmetic. The only control flow is sequential step execution; the only data-flow primitive is `{\"$ref\": \"<stepId>[.path.to.value]\"}` which substitutes a prior step's output (or a nested field of it) into the next step's args. Paths support dot keys and `[N]` / `.N` array indexing. Each step's `tool` is a namespaced upstream tool name: an already-loaded server is called directly, and a not-yet-loaded server whose tools are known from cache is loaded on first use exactly as a direct tools/call would be \u2014 that adds its tools to this session, and can still be refused. A POLICY refusal (server disabled, project profile, compliance floor) is decided before step 0 runs and refuses the whole pipeline with nothing done, so fixing it and re-running costs no repeated side effect; a server-cap refusal is only knowable when the step is reached and fails it there, with `partial` holding what already ran. A name that is neither loaded nor cached also fails the step.",
16801
+ "Run a short DECLARATIVE pipeline of upstream tool calls in one round-trip, when you already know the 2-4 calls and one step's output feeds another's args -- e.g. `a = gh_list_prs(); b = gh_get_pr(a[0].number); return b`. NOT a code sandbox: no expressions, loops, branching or arithmetic. Steps run in order; the only data flow is `{\"$ref\": \"<stepId>[.path.to.value]\"}` (dot keys, `[N]` / `.N` array indexing), which substitutes a prior step's output into a later step's args. Each `tool` is a namespaced upstream name: a loaded server is called directly; a not-yet-loaded server whose tools are cached is loaded on first use, as a direct tools/call would (its tools join this session; it can still be refused). A POLICY refusal (server disabled, project profile, compliance floor) is decided before step 0 runs and refuses the whole pipeline with nothing done, so fixing it and re-running costs no repeated side effect; a server-cap refusal is only knowable when the step is reached and fails it there, with `partial` holding what already ran. A name neither loaded nor cached fails its step.",
16465
16802
  `Max ${MAX_EXEC_STEPS} steps per exec.`,
16466
- "If any step fails, the whole pipeline fails and returns `{ ok: false, failedStep, error, partial: { ...completed outputs } }`. On success the shape depends on whether you named a `return`: WITH one you get `{ ok: true, result: <that step's output>, stepKeys: [...] }` \u2014 plus `steps` as well while the intermediate outputs stay small (about 4 KB), so a created issue's id survives while a long list you skipped is not replayed at you; WITHOUT one you get `{ ok: true, result: <last step's output>, steps: { ...all outputs } }`. Name a `return` whenever you only need one value: it is what stops a LARGE intermediate output (a long list you only wanted one element of) from being replayed back into your context. Prefer this over back-to-back tool calls when the chain is deterministic \u2014 it saves prompt-token replay and client round-trips."
16803
+ "Any failure returns `{ ok: false, failedStep, error, partial }`. Success returns `{ ok: true, result, steps }`; with a named `return`, `result` is that step's output, `stepKeys` is added, and `steps` is dropped once the intermediate outputs exceed about 4 KB. Name a `return` whenever one value is enough: it stops a large intermediate output being replayed into your context."
16467
16804
  ].join(" "),
16468
16805
  inputSchema: {
16469
16806
  type: "object",
16470
16807
  properties: {
16471
16808
  steps: {
16472
16809
  type: "array",
16473
- description: 'Ordered list of tool calls to run. Each step is `{ id?: string, tool: string, args?: object }`. `args` values may be `{"$ref": "<stepId>.path"}` to inject a prior step\'s output.',
16810
+ description: 'Ordered tool calls, each `{ id?: string, tool: string, args?: object }`. `args` values may be `{"$ref": "<stepId>.path"}`.',
16474
16811
  items: {
16475
16812
  type: "object",
16476
16813
  properties: {
16477
16814
  id: {
16478
16815
  type: "string",
16479
- description: "Optional binding name for this step's output. Later steps reference it via `$ref`. Defaults to the step's positional index as a string."
16816
+ description: "Optional name for this step's output, used by later `$ref`s. Defaults to the positional index as a string."
16480
16817
  },
16481
16818
  tool: {
16482
16819
  type: "string",
16483
- description: 'Namespaced tool name (e.g. "gh_list_prs"). Loaded servers are called directly; a not-yet-loaded server whose tools are known from cache is loaded on first use, adding its tools to the session. A name that is neither loaded nor cached fails the step. Meta-tools (mcp_connect_*) are not callable from exec.'
16820
+ description: 'Namespaced tool name (e.g. "gh_list_prs"); a cached-but-unloaded server is loaded on first use. Meta-tools (mcp_connect_*) are not callable from exec.'
16484
16821
  },
16485
16822
  args: {
16486
16823
  type: "object",
16487
- description: 'Arguments for the tool call. Any value (including deeply nested) may be `{"$ref": "<stepId>[.path]"}` to substitute a prior step\'s output at that position.',
16824
+ description: 'Arguments for the tool call. Any value, however nested, may be `{"$ref": "<stepId>[.path]"}` to substitute a prior step\'s output.',
16488
16825
  additionalProperties: true
16489
16826
  }
16490
16827
  },
@@ -16500,7 +16837,7 @@ var META_TOOLS = {
16500
16837
  },
16501
16838
  return: {
16502
16839
  type: "string",
16503
- description: "Optional: id of the step whose output should be surfaced as `result`. Defaults to the last step's id (or its positional index). Naming a step is NOT just a selection: it also adds `stepKeys`, and once the intermediate outputs exceed roughly 4 KB it drops `steps` from the response so a large payload you skipped is not replayed back to you. Below that they are all still returned."
16840
+ description: "Optional: id of the step whose output becomes `result` (default: the last step). Naming one adds `stepKeys` and drops `steps` once the intermediate outputs exceed about 4 KB, so a large payload you skipped is not replayed."
16504
16841
  }
16505
16842
  },
16506
16843
  required: ["steps"]
@@ -16514,6 +16851,11 @@ var META_TOOLS = {
16514
16851
  }
16515
16852
  }
16516
16853
  };
16854
+ var LITE_META_TOOL_NAMES = /* @__PURE__ */ new Set([
16855
+ META_TOOLS.exec.name,
16856
+ META_TOOLS.findTool.name,
16857
+ META_TOOLS.read_tool.name
16858
+ ]);
16517
16859
  function computeSecretsReport(servers, vaultKeys) {
16518
16860
  const rows = [];
16519
16861
  for (const server of servers) {
@@ -16741,6 +17083,7 @@ function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, e
16741
17083
  const tools = [];
16742
17084
  const seen = /* @__PURE__ */ new Set();
16743
17085
  for (const meta of Object.values(META_TOOLS)) {
17086
+ if (exposure === "lite" && !LITE_META_TOOL_NAMES.has(meta.name)) continue;
16744
17087
  tools.push({
16745
17088
  name: meta.name,
16746
17089
  description: meta.description,
@@ -16750,7 +17093,7 @@ function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, e
16750
17093
  seen.add(meta.name);
16751
17094
  }
16752
17095
  for (const conn of activeConnections.values()) {
16753
- if (exposure === "gateway" && !exposedNamespaces?.has(conn.config.namespace)) continue;
17096
+ if (exposure !== "full" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16754
17097
  const filter = toolFilters?.get(conn.config.namespace);
16755
17098
  for (const tool of conn.tools) {
16756
17099
  if (filter && !filter.has(tool.name)) continue;
@@ -16771,7 +17114,7 @@ function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, e
16771
17114
  for (const server of inactiveWithCache) {
16772
17115
  if (activeConnections.has(server.namespace)) continue;
16773
17116
  if (!server.toolCache || server.toolCache.length === 0) continue;
16774
- if (exposure === "gateway") continue;
17117
+ if (exposure !== "full") continue;
16775
17118
  const filter = toolFilters?.get(server.namespace);
16776
17119
  for (const cached of server.toolCache) {
16777
17120
  if (filter && !filter.has(cached.name)) continue;
@@ -16843,7 +17186,7 @@ function buildResourceList(activeConnections, builtins = [], exposure = "full",
16843
17186
  seen.add(b.uri);
16844
17187
  }
16845
17188
  for (const conn of activeConnections.values()) {
16846
- if (exposure === "gateway" && !exposedNamespaces?.has(conn.config.namespace)) continue;
17189
+ if (exposure !== "full" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16847
17190
  for (const r of conn.resources) {
16848
17191
  if (seen.has(r.namespacedUri)) continue;
16849
17192
  resources.push({
@@ -16883,7 +17226,7 @@ function buildPromptList(activeConnections, exposure = "full", exposedNamespaces
16883
17226
  const prompts = [];
16884
17227
  const seen = /* @__PURE__ */ new Set();
16885
17228
  for (const conn of activeConnections.values()) {
16886
- if (exposure === "gateway" && !exposedNamespaces?.has(conn.config.namespace)) continue;
17229
+ if (exposure !== "full" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16887
17230
  for (const p of conn.prompts) {
16888
17231
  if (seen.has(p.namespacedName)) continue;
16889
17232
  prompts.push({
@@ -17702,6 +18045,287 @@ async function bestOfNViaSampling(server, intent, candidates, n) {
17702
18045
  }
17703
18046
  }
17704
18047
 
18048
+ // src/secret-entry-page.ts
18049
+ import { spawn as spawn4 } from "child_process";
18050
+ import { randomBytes as randomBytes3, randomUUID, timingSafeEqual as timingSafeEqual2 } from "crypto";
18051
+ import { createServer } from "http";
18052
+ import { win32 as win322 } from "path";
18053
+ var SECRET_ENTRY_PAGE_TTL_MS = 3 * 6e4;
18054
+ var MAX_BODY_BYTES = 16 * 1024;
18055
+ var REPLY_DRAIN_MS = 2e3;
18056
+ var LOOPBACK_HOST = "127.0.0.1";
18057
+ var SECURITY_HEADERS = {
18058
+ "Cache-Control": "no-store",
18059
+ Pragma: "no-cache",
18060
+ "X-Content-Type-Options": "nosniff",
18061
+ "X-Frame-Options": "DENY",
18062
+ "Referrer-Policy": "same-origin",
18063
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
18064
+ Connection: "close"
18065
+ };
18066
+ function escapeHtml(s) {
18067
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
18068
+ }
18069
+ function describeTtl(ms) {
18070
+ if (ms >= 6e4 && ms % 6e4 === 0) {
18071
+ const m = ms / 6e4;
18072
+ return `${m} ${m === 1 ? "minute" : "minutes"}`;
18073
+ }
18074
+ const s = Math.max(1, Math.ceil(ms / 1e3));
18075
+ return `${s} ${s === 1 ? "second" : "seconds"}`;
18076
+ }
18077
+ function htmlDocument(title, body) {
18078
+ return `<!doctype html>
18079
+ <html lang="en">
18080
+ <head>
18081
+ <meta charset="utf-8">
18082
+ <meta name="viewport" content="width=device-width, initial-scale=1">
18083
+ <title>${escapeHtml(title)}</title>
18084
+ <style>
18085
+ :root { color-scheme: light dark; }
18086
+ body { font: 16px/1.5 system-ui, sans-serif; margin: 0; padding: 2rem 1rem; }
18087
+ main { max-width: 32rem; margin: 0 auto; }
18088
+ h1 { font-size: 1.3rem; margin: 0 0 1rem; }
18089
+ label { display: block; font-weight: 600; margin: 1rem 0 .25rem; }
18090
+ input { box-sizing: border-box; width: 100%; font: inherit; padding: .5rem; }
18091
+ button { margin-top: 1.25rem; font: inherit; padding: .5rem 1.25rem; }
18092
+ .err { color: #b00020; font-weight: 600; }
18093
+ .fine { font-size: .9rem; opacity: .75; }
18094
+ </style>
18095
+ </head>
18096
+ <body><main>
18097
+ ${body}
18098
+ </main></body>
18099
+ </html>
18100
+ `;
18101
+ }
18102
+ function browserCommand(url, platform = process.platform, env = process.env) {
18103
+ if (platform === "win32") {
18104
+ const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? env.windir ?? env.WINDIR ?? "C:\\Windows";
18105
+ return { command: win322.join(systemRoot, "System32", "rundll32.exe"), args: ["url.dll,FileProtocolHandler", url] };
18106
+ }
18107
+ if (platform === "darwin") return { command: "/usr/bin/open", args: [url] };
18108
+ if (!env.DISPLAY && !env.WAYLAND_DISPLAY) return null;
18109
+ return { command: "xdg-open", args: [url] };
18110
+ }
18111
+ function openInSystemBrowser(url, spawnLauncher = spawn4) {
18112
+ const launch = browserCommand(url);
18113
+ if (!launch) {
18114
+ log("info", "No graphical session to open the secret entry page in");
18115
+ return Promise.resolve(false);
18116
+ }
18117
+ return new Promise((resolve8) => {
18118
+ let child;
18119
+ try {
18120
+ child = spawnLauncher(launch.command, launch.args, {
18121
+ stdio: "ignore",
18122
+ detached: true,
18123
+ windowsHide: true,
18124
+ env: stripInternalSecretsFromEnv(process.env)
18125
+ });
18126
+ } catch (err) {
18127
+ log("warn", "Could not launch a browser for the secret entry page", {
18128
+ command: launch.command,
18129
+ error: err instanceof Error ? err.message : String(err)
18130
+ });
18131
+ resolve8(false);
18132
+ return;
18133
+ }
18134
+ child.once("spawn", () => {
18135
+ child.unref();
18136
+ resolve8(true);
18137
+ });
18138
+ child.once("error", (err) => {
18139
+ log("warn", "Could not launch a browser for the secret entry page", {
18140
+ command: launch.command,
18141
+ error: err.message
18142
+ });
18143
+ resolve8(false);
18144
+ });
18145
+ });
18146
+ }
18147
+ function openSecretEntryPage(opts) {
18148
+ if (opts.fields.length === 0) return Promise.reject(new Error("a secret entry page needs at least one field"));
18149
+ const ttlMs = opts.ttlMs ?? SECRET_ENTRY_PAGE_TTL_MS;
18150
+ const token = randomBytes3(32).toString("hex");
18151
+ const expectedPath = Buffer.from(`/${token}`, "utf8");
18152
+ const elicitationId = randomUUID();
18153
+ let port = 0;
18154
+ let state = "open";
18155
+ let replying = false;
18156
+ let listenerClosed = false;
18157
+ let expiry;
18158
+ let settle = () => {
18159
+ };
18160
+ const result = new Promise((resolve8) => {
18161
+ settle = resolve8;
18162
+ });
18163
+ const server = createServer((req, res) => handle(req, res));
18164
+ const closeListener = (hard) => {
18165
+ if (!listenerClosed) {
18166
+ listenerClosed = true;
18167
+ server.close();
18168
+ }
18169
+ if (hard) server.closeAllConnections?.();
18170
+ else server.closeIdleConnections?.();
18171
+ };
18172
+ const end = (outcome) => {
18173
+ if (state === "done") return;
18174
+ state = "done";
18175
+ if (expiry) clearTimeout(expiry);
18176
+ closeListener(true);
18177
+ settle(outcome);
18178
+ };
18179
+ const send = (res, status, body, extra = {}, type = "text/html; charset=utf-8") => {
18180
+ res.writeHead(status, { ...SECURITY_HEADERS, "Content-Type": type, ...extra });
18181
+ res.end(body);
18182
+ };
18183
+ const formPage = (error) => {
18184
+ const fields = opts.fields.map(
18185
+ (f, i) => `<label for="f${i}">${escapeHtml(f.label)}</label>
18186
+ <input id="f${i}" name="${escapeHtml(f.name)}" type="password" autocomplete="off" autocapitalize="off" spellcheck="false" required${i === 0 ? " autofocus" : ""}>`
18187
+ ).join("\n");
18188
+ return htmlDocument(
18189
+ opts.title,
18190
+ `<h1>${escapeHtml(opts.title)}</h1>
18191
+ <p>${escapeHtml(opts.intro)}</p>
18192
+ ${error ? `<p class="err">${escapeHtml(error)}</p>
18193
+ ` : ""}<form method="post" autocomplete="off">
18194
+ ${fields}
18195
+ <button type="submit">Submit</button>
18196
+ </form>
18197
+ <p class="fine">Served by yaw-mcp on this computer only (${LOOPBACK_HOST}). This page takes one submission, and stops working after ${describeTtl(ttlMs)}.</p>`
18198
+ );
18199
+ };
18200
+ const gonePage = () => htmlDocument(
18201
+ opts.title,
18202
+ `<h1>This page has expired</h1>
18203
+ <p>It already took a submission, or its time ran out. Return to your MCP client.</p>`
18204
+ );
18205
+ const pathMatches = (path5) => {
18206
+ const got = Buffer.from(path5, "utf8");
18207
+ return got.length === expectedPath.length && timingSafeEqual2(got, expectedPath);
18208
+ };
18209
+ const accept = (values, res) => {
18210
+ state = "done";
18211
+ replying = true;
18212
+ if (expiry) clearTimeout(expiry);
18213
+ closeListener(false);
18214
+ let drained = false;
18215
+ const drain = () => {
18216
+ if (drained) return;
18217
+ drained = true;
18218
+ closeListener(true);
18219
+ };
18220
+ res.once("finish", drain);
18221
+ res.once("close", drain);
18222
+ setTimeout(drain, REPLY_DRAIN_MS).unref?.();
18223
+ send(res, 200, htmlDocument(opts.title, `<h1>Received</h1>
18224
+ <p>${escapeHtml(opts.doneMessage)}</p>`));
18225
+ settle({ kind: "submitted", values });
18226
+ };
18227
+ function handle(req, res) {
18228
+ const host = (req.headers.host ?? "").toLowerCase();
18229
+ if (host !== `${LOOPBACK_HOST}:${port}`) {
18230
+ send(res, 403, "Forbidden\n", {}, "text/plain; charset=utf-8");
18231
+ return;
18232
+ }
18233
+ const rawUrl = req.url ?? "";
18234
+ const q = rawUrl.indexOf("?");
18235
+ if (!pathMatches(q === -1 ? rawUrl : rawUrl.slice(0, q))) {
18236
+ send(res, 404, "Not found\n", {}, "text/plain; charset=utf-8");
18237
+ return;
18238
+ }
18239
+ if (state !== "open") {
18240
+ send(res, 410, gonePage());
18241
+ return;
18242
+ }
18243
+ if (req.method === "GET") {
18244
+ send(res, 200, formPage());
18245
+ return;
18246
+ }
18247
+ if (req.method !== "POST") {
18248
+ send(res, 405, "Method not allowed\n", { Allow: "GET, POST" }, "text/plain; charset=utf-8");
18249
+ return;
18250
+ }
18251
+ const origin = req.headers.origin;
18252
+ if (origin !== void 0 && origin !== `http://${LOOPBACK_HOST}:${port}`) {
18253
+ send(res, 403, "Forbidden\n", {}, "text/plain; charset=utf-8");
18254
+ return;
18255
+ }
18256
+ const contentType = (req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
18257
+ if (contentType !== "application/x-www-form-urlencoded") {
18258
+ send(res, 415, "Unsupported media type\n", {}, "text/plain; charset=utf-8");
18259
+ return;
18260
+ }
18261
+ const chunks = [];
18262
+ let size = 0;
18263
+ let tooLarge = false;
18264
+ req.on("data", (chunk) => {
18265
+ if (tooLarge) return;
18266
+ size += chunk.length;
18267
+ if (size > MAX_BODY_BYTES) {
18268
+ tooLarge = true;
18269
+ chunks.length = 0;
18270
+ return;
18271
+ }
18272
+ chunks.push(chunk);
18273
+ });
18274
+ req.on("error", () => {
18275
+ });
18276
+ req.on("end", () => {
18277
+ if (tooLarge) {
18278
+ send(res, 413, "Payload too large\n", {}, "text/plain; charset=utf-8");
18279
+ return;
18280
+ }
18281
+ if (state !== "open") {
18282
+ chunks.length = 0;
18283
+ send(res, 410, gonePage());
18284
+ return;
18285
+ }
18286
+ const params = new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
18287
+ chunks.length = 0;
18288
+ const values = {};
18289
+ for (const field of opts.fields) {
18290
+ const value = params.get(field.name);
18291
+ if (value === null || value.length === 0) {
18292
+ send(res, 400, formPage("Every field is required."));
18293
+ return;
18294
+ }
18295
+ values[field.name] = value;
18296
+ }
18297
+ accept(values, res);
18298
+ });
18299
+ }
18300
+ const close = () => {
18301
+ if (state === "open") {
18302
+ end({ kind: "closed" });
18303
+ return;
18304
+ }
18305
+ if (!replying) closeListener(true);
18306
+ };
18307
+ return new Promise((resolve8, reject) => {
18308
+ const onListenError = (err) => {
18309
+ state = "done";
18310
+ reject(err);
18311
+ };
18312
+ server.once("error", onListenError);
18313
+ server.listen({ host: LOOPBACK_HOST, port: 0 }, () => {
18314
+ server.removeListener("error", onListenError);
18315
+ server.on("error", (err) => {
18316
+ log("warn", "Secret entry page listener failed; closing it", { port, error: err.message });
18317
+ end({ kind: "closed" });
18318
+ });
18319
+ port = server.address().port;
18320
+ server.unref?.();
18321
+ expiry = setTimeout(() => end({ kind: "expired" }), ttlMs);
18322
+ expiry.unref?.();
18323
+ log("info", "Secret entry page listening", { port, ttlMs });
18324
+ resolve8({ url: `http://${LOOPBACK_HOST}:${port}/${token}`, elicitationId, result, close });
18325
+ });
18326
+ });
18327
+ }
18328
+
17705
18329
  // src/server-cap.ts
17706
18330
  var DEFAULT_SERVER_CAP = 6;
17707
18331
  function resolveServerCap(env = process.env) {
@@ -17773,22 +18397,26 @@ function isAutoLoadEnabled() {
17773
18397
  return raw === "1" || raw.toLowerCase() === "true";
17774
18398
  }
17775
18399
  function isPrewarmEnabled() {
17776
- const raw = process.env.YAW_MCP_PREWARM?.trim().toLowerCase();
17777
- return !(raw === "0" || raw === "false");
18400
+ return !isFeatureDisabled("YAW_MCP_PREWARM");
17778
18401
  }
17779
18402
  var exposureWarnedFor = null;
17780
- function resolveToolExposure() {
18403
+ var LITE_BY_DEFAULT_CLIENTS = /* @__PURE__ */ new Set(["typed-cli"]);
18404
+ function resolveToolExposure(clientInfo) {
18405
+ const fallback = clientInfo?.name !== void 0 && LITE_BY_DEFAULT_CLIENTS.has(clientInfo.name) ? "lite" : "gateway";
17781
18406
  const raw = process.env.YAW_MCP_TOOL_EXPOSURE?.trim().toLowerCase();
17782
18407
  if (raw === "full") return "full";
17783
- if (raw === void 0 || raw === "" || raw === "gateway") return "gateway";
18408
+ if (raw === "lite") return "lite";
18409
+ if (raw === "gateway") return "gateway";
18410
+ if (raw === void 0 || raw === "") return fallback;
17784
18411
  if (exposureWarnedFor !== raw) {
17785
18412
  exposureWarnedFor = raw;
17786
- log("warn", `unrecognized YAW_MCP_TOOL_EXPOSURE "${raw}"; using "gateway"`, { raw });
18413
+ log("warn", `unrecognized YAW_MCP_TOOL_EXPOSURE "${raw}"; using "${fallback}"`, { raw });
17787
18414
  }
17788
- return "gateway";
18415
+ return fallback;
17789
18416
  }
17790
18417
  var DEFAULT_IDLE_CALL_THRESHOLD = 10;
17791
18418
  var MAX_VAULT_PASSPHRASE_PROMPTS = 2;
18419
+ var VAULT_PAGE_FIELD = "passphrase";
17792
18420
  var MAX_CREDENTIAL_PROMPTS = 2;
17793
18421
  var EXEC_ECHO_BUDGET_BYTES = 4096;
17794
18422
  var idleThresholdClampWarnedFor = null;
@@ -18045,6 +18673,17 @@ var ConnectServer = class _ConnectServer {
18045
18673
  // MAX_VAULT_PASSPHRASE_PROMPTS budget in a single round. Followers await
18046
18674
  // this instead of prompting. Cleared when the prompt settles.
18047
18675
  vaultElicitInflight = null;
18676
+ // Masked-entry pages currently listening (see collectSecretOnLoopbackPage).
18677
+ // Tracked so shutdown() can close them: a listener keeps the process alive
18678
+ // under oam, whose http.Server has no unref().
18679
+ secretEntryPages = /* @__PURE__ */ new Set();
18680
+ // The page opener, the browser launcher and the page TTL. Instance fields
18681
+ // (not direct calls) purely so tests can substitute a fake page and a fake
18682
+ // browser, the same reason activationRetryDelayMs is one; production never
18683
+ // changes them.
18684
+ openSecretPage = openSecretEntryPage;
18685
+ openBrowser = openInSystemBrowser;
18686
+ secretEntryPageTtlMs = SECRET_ENTRY_PAGE_TTL_MS;
18048
18687
  // How many times we have asked for a given NAMESPACE's missing child
18049
18688
  // credentials. Per-namespace (unlike the vault counter) because these are
18050
18689
  // the child's own secrets. Bounds the re-ask that replaced the old
@@ -18159,13 +18798,19 @@ var ConnectServer = class _ConnectServer {
18159
18798
  static SHUTDOWN_DRAIN_MS = 2e3;
18160
18799
  constructor() {
18161
18800
  this.server = new Server(
18162
- { name: "yaw-mcp", version: true ? "1.0.10" : "dev" },
18801
+ { name: "yaw-mcp", version: true ? "1.0.12" : "dev" },
18163
18802
  {
18164
18803
  capabilities: {
18165
18804
  tools: { listChanged: true },
18166
18805
  resources: { listChanged: true },
18167
18806
  prompts: { listChanged: true }
18168
- }
18807
+ },
18808
+ // Returned once, in the initialize result, and injected by Claude
18809
+ // Code into the system prompt as a "# MCP Server Instructions"
18810
+ // block. This is where the routing prose the meta-tool descriptions
18811
+ // used to repeat now lives -- a description is paid on every
18812
+ // tools/list, this is paid once. See SERVER_INSTRUCTIONS.
18813
+ instructions: SERVER_INSTRUCTIONS
18169
18814
  }
18170
18815
  );
18171
18816
  this.clientBridge = {
@@ -18203,13 +18848,23 @@ var ConnectServer = class _ConnectServer {
18203
18848
  for (const b of this.getBuiltinResources()) map.set(b.uri, b);
18204
18849
  return map;
18205
18850
  }
18851
+ /** The exposure THIS session's lists are served at: the env when set,
18852
+ * else the default for the connected client (lite for typed-cli, gateway
18853
+ * otherwise -- see resolveToolExposure). The one place the client's
18854
+ * identity is read, so the three list handlers and discover's "in
18855
+ * context" summary cannot disagree about which surface they describe.
18856
+ * getClientVersion() is the SDK's copy of the initialize request's
18857
+ * clientInfo and is undefined before the handshake. */
18858
+ currentExposure() {
18859
+ return resolveToolExposure(this.server.getClientVersion());
18860
+ }
18206
18861
  setupHandlers() {
18207
18862
  this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
18208
18863
  tools: buildToolList(
18209
18864
  this.connections,
18210
18865
  this.getDeferredServers(),
18211
18866
  this.toolFilters,
18212
- resolveToolExposure(),
18867
+ this.currentExposure(),
18213
18868
  this.sessionActivated,
18214
18869
  // Hidden here, refused at the gate, but still ROUTED: dropping the
18215
18870
  // route instead would make a call by name return `Unknown tool`,
@@ -18226,7 +18881,7 @@ var ConnectServer = class _ConnectServer {
18226
18881
  resources: buildResourceList(
18227
18882
  this.connections,
18228
18883
  this.getBuiltinResources(),
18229
- resolveToolExposure(),
18884
+ this.currentExposure(),
18230
18885
  this.sessionActivated
18231
18886
  )
18232
18887
  }));
@@ -18237,7 +18892,7 @@ var ConnectServer = class _ConnectServer {
18237
18892
  return routeResourceRead(request2.params.uri, this.resourceRoutes, this.connections, this.getBuiltinResourceMap());
18238
18893
  });
18239
18894
  this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
18240
- prompts: buildPromptList(this.connections, resolveToolExposure(), this.sessionActivated)
18895
+ prompts: buildPromptList(this.connections, this.currentExposure(), this.sessionActivated)
18241
18896
  }));
18242
18897
  this.server.setRequestHandler(GetPromptRequestSchema, async (request2) => {
18243
18898
  return routePromptGet(
@@ -18525,8 +19180,7 @@ var ConnectServer = class _ConnectServer {
18525
19180
  * running config exactly as it was -- someone saving a broken JSON must not
18526
19181
  * cost them the servers they already have loaded. */
18527
19182
  async maybeReloadBundles() {
18528
- const reloadOptOut = process.env.YAW_MCP_CONFIG_RELOAD;
18529
- if (reloadOptOut === "0" || reloadOptOut?.toLowerCase() === "false") return;
19183
+ if (isFeatureDisabled("YAW_MCP_CONFIG_RELOAD")) return;
18530
19184
  if (this.shuttingDown) return;
18531
19185
  if (this.bundlesConsultedPaths.length === 0) return;
18532
19186
  const fingerprint = bundlesSignature(this.bundlesConsultedPaths);
@@ -18772,7 +19426,6 @@ var ConnectServer = class _ConnectServer {
18772
19426
  await this.server.connect(transport);
18773
19427
  maybeAutoUpgrade().catch((err) => log("warn", "Auto-upgrade check failed", { error: err?.message }));
18774
19428
  maybeRefreshSidecars().catch((err) => log("warn", "Sidecar refresh check failed", { error: err?.message }));
18775
- maybeAutoPrewarmNpxCache().catch((err) => log("warn", "Auto-prewarm check failed", { error: err?.message }));
18776
19429
  maybeHealStaleBrokerEntries().catch(
18777
19430
  (err) => log("warn", "Stale-entry heal failed", { error: err?.message })
18778
19431
  );
@@ -19609,7 +20262,7 @@ var ConnectServer = class _ConnectServer {
19609
20262
  }
19610
20263
  lines.push("");
19611
20264
  }
19612
- const exposure = resolveToolExposure();
20265
+ const exposure = this.currentExposure();
19613
20266
  const isAdvertised = (namespace) => exposure === "full" || this.sessionActivated.has(namespace);
19614
20267
  let omittedToolNames = false;
19615
20268
  let totalContextTokens = 0;
@@ -20300,8 +20953,15 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20300
20953
  // the retry hinges on a process-wide session value instead of a per-server
20301
20954
  // override.
20302
20955
  //
20956
+ // WHERE the passphrase is typed: never into the client's own dialog. A
20957
+ // form-mode elicitation field is an ordinary visible text input -- the
20958
+ // passphrase used to sit on screen, in plain text, while it was typed --
20959
+ // and the spec forbids form mode for secrets anyway. It is typed into a
20960
+ // masked field on a one-shot page this process serves on 127.0.0.1; see
20961
+ // collectSecretOnLoopbackPage for how the user gets there.
20962
+ //
20303
20963
  // Bounded by attempts rather than latched after one ask, because the value
20304
- // is typed by a human into a no-echo field: a single transposed character
20964
+ // is typed by a human into a masked field: a single transposed character
20305
20965
  // otherwise cost the entire session. Each entry is VERIFIED against the
20306
20966
  // vault before it is stored (see verifyVaultPassphrase), so a wrong one is
20307
20967
  // rejected without ever becoming the session passphrase, and the user gets
@@ -20317,15 +20977,21 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20317
20977
  const joined = this.vaultElicitInflight;
20318
20978
  if (joined) {
20319
20979
  progress?.("Waiting for the vault passphrase prompt already in flight");
20320
- const outcome2 = await joined;
20321
- if (outcome2 === "unlocked") return this.runActivateOne(
20980
+ const outcome2 = await withHeartbeat(
20981
+ progress,
20982
+ (elapsed) => `Still waiting on the vault passphrase prompt already in flight -- ${elapsed}s so far`,
20983
+ () => joined
20984
+ );
20985
+ if (this.shuttingDown) return this.shuttingDownRefusal(namespace);
20986
+ if (outcome2.kind === "unlocked") return this.runActivateOne(
20322
20987
  namespace,
20323
20988
  progress,
20324
20989
  fromPrewarm,
20325
20990
  /* skipCap */
20326
20991
  true
20327
20992
  );
20328
- if (outcome2 === "rejected") return this.vaultPassphraseRejected(namespace, lastError);
20993
+ if (outcome2.kind === "rejected") return this.vaultPassphraseRejected(namespace, lastError);
20994
+ if (outcome2.kind === "unreachable") return this.vaultPassphraseUnreachable(namespace, lastError, outcome2.reason);
20329
20995
  return null;
20330
20996
  }
20331
20997
  if (this.vaultPassphraseElicited) return null;
@@ -20346,7 +21012,8 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20346
21012
  } finally {
20347
21013
  if (this.vaultElicitInflight === prompt) this.vaultElicitInflight = null;
20348
21014
  }
20349
- if (outcome === "unlocked") {
21015
+ if (this.shuttingDown) return this.shuttingDownRefusal(namespace);
21016
+ if (outcome.kind === "unlocked") {
20350
21017
  progress?.("Got the passphrase -- retrying load");
20351
21018
  return this.runActivateOne(
20352
21019
  namespace,
@@ -20356,7 +21023,8 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20356
21023
  true
20357
21024
  );
20358
21025
  }
20359
- if (outcome === "rejected") return this.vaultPassphraseRejected(namespace, lastError);
21026
+ if (outcome.kind === "rejected") return this.vaultPassphraseRejected(namespace, lastError);
21027
+ if (outcome.kind === "unreachable") return this.vaultPassphraseUnreachable(namespace, lastError, outcome.reason);
20360
21028
  return null;
20361
21029
  }
20362
21030
  // The result for a vault passphrase the user typed that did not verify.
@@ -20375,59 +21043,174 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20375
21043
  message: `Could not load "${namespace}": the passphrase entered does not unlock your local secret vault, which its env (${lastError.refKeys.join(", ")}) references.${retryHint}`
20376
21044
  };
20377
21045
  }
21046
+ // The result for a prompt whose masked-entry page never took a passphrase.
21047
+ // Shared by the winner and its followers, like vaultPassphraseRejected, and
21048
+ // for the same reason it skips runActivateOne's give-up path: nothing is
21049
+ // wrong with the server, and the original "vault locked" text would not
21050
+ // tell a user who said yes to the prompt that there was then nowhere to
21051
+ // type. The retry hint reads the latch, which promptForVaultPassphrase sets
21052
+ // for the two failures another prompt cannot fix (no page, no browser).
21053
+ vaultPassphraseUnreachable(namespace, lastError, reason) {
21054
+ const what = reason === "no-browser" ? "yaw-mcp could not open a browser on this machine for the page that takes the passphrase in a masked field" : reason === "no-page" ? "yaw-mcp could not start the local page that takes the passphrase in a masked field" : "the passphrase page expired with nothing submitted";
21055
+ const retryHint = this.vaultPassphraseElicited ? " No further prompts this session: set YAW_MCP_VAULT_PASSPHRASE in yaw-mcp's own env and restart this MCP client." : ` Activate "${namespace}" again for a new page, or set YAW_MCP_VAULT_PASSPHRASE in yaw-mcp's own env and restart this MCP client.`;
21056
+ return {
21057
+ ok: false,
21058
+ isChanged: false,
21059
+ message: `Could not load "${namespace}": ${what}, so your local secret vault, which its env (${lastError.refKeys.join(", ")}) references, is still locked.${retryHint}`
21060
+ };
21061
+ }
21062
+ // Collect secret values WITHOUT them ever being typed into the client's
21063
+ // own dialog. They are typed into masked fields on a one-shot page this
21064
+ // process serves on 127.0.0.1 (secret-entry-page.ts, which carries the
21065
+ // page's hardening), and the client is only told how to get the user
21066
+ // there:
21067
+ //
21068
+ // * URL mode, when the client declares it (capabilities.elicitation.url).
21069
+ // It is what the spec (2025-11-25) requires for secrets: servers MUST
21070
+ // NOT use form mode for passwords or tokens, and MUST use URL mode. The
21071
+ // client shows the link, asks, and opens it. Its "accept" means the
21072
+ // user consented, NOT that anything was submitted, so the page's own
21073
+ // result is what this waits on.
21074
+ // * Form mode, when that is all the client has. Claude Code (2.1.278, the
21075
+ // build checked) declares `elicitation: {}`, which the spec and the SDK
21076
+ // read as form only -- and its own client refuses a url-mode request
21077
+ // against that declaration, so url mode cannot be tried on it. The form
21078
+ // carries NO field -- it is a yes/no consent, which that build renders
21079
+ // with Accept focused -- and on a yes this process opens the page in
21080
+ // the system browser itself. A visible field is never the fallback:
21081
+ // that is exactly the exposure this replaces.
21082
+ //
21083
+ // Nothing here is vault-specific. The missing-credential prompt
21084
+ // (maybeElicitAndRetry, which still asks in a visible form field) can move
21085
+ // onto it by supplying its own words and fields.
21086
+ async collectSecretOnLoopbackPage(request2) {
21087
+ const { namespace, why, secretNoun, progress } = request2;
21088
+ const modes = getSupportedElicitationModes(this.server.getClientCapabilities()?.elicitation);
21089
+ if (!modes.supportsUrlMode && !modes.supportsFormMode) return { kind: "failed" };
21090
+ const mode = modes.supportsUrlMode ? "url" : "form";
21091
+ let page;
21092
+ try {
21093
+ page = await this.openSecretPage({ ...request2.page, ttlMs: this.secretEntryPageTtlMs });
21094
+ } catch (err) {
21095
+ log("warn", "Could not start the secret entry page", {
21096
+ namespace,
21097
+ error: err instanceof Error ? err.message : String(err)
21098
+ });
21099
+ return { kind: "unreachable", reason: "no-page" };
21100
+ }
21101
+ const openedAt = Date.now();
21102
+ this.secretEntryPages.add(page);
21103
+ try {
21104
+ if (this.shuttingDown) return { kind: "failed" };
21105
+ let result;
21106
+ try {
21107
+ result = mode === "url" ? await this.server.elicitInput({
21108
+ mode: "url",
21109
+ message: `${why} Open the link to type ${secretNoun} into a masked field on a page yaw-mcp serves on this computer -- it never passes through this client. Decline to cancel.`,
21110
+ elicitationId: page.elicitationId,
21111
+ url: page.url
21112
+ }) : await this.server.elicitInput({
21113
+ message: `${why} Accept to open a page yaw-mcp serves on this computer (127.0.0.1) in your browser, and type ${secretNoun} into its masked field there -- it is never typed into this dialog. Decline to cancel.`,
21114
+ requestedSchema: { type: "object", properties: {} }
21115
+ });
21116
+ } catch (err) {
21117
+ log("warn", "Secret entry elicitation failed", {
21118
+ namespace,
21119
+ mode,
21120
+ error: err instanceof Error ? err.message : String(err)
21121
+ });
21122
+ return { kind: "failed" };
21123
+ }
21124
+ if (result.action !== "accept") {
21125
+ log("info", "User declined the secret entry prompt", { namespace, mode, action: result.action });
21126
+ return { kind: "declined" };
21127
+ }
21128
+ if (this.shuttingDown) return { kind: "failed" };
21129
+ if (mode === "form" && !await this.openBrowser(page.url)) return { kind: "unreachable", reason: "no-browser" };
21130
+ progress?.("Waiting for the masked entry page in your browser");
21131
+ const outcome = await withHeartbeat(
21132
+ progress,
21133
+ (elapsed) => {
21134
+ const left = Math.max(0, Math.round((openedAt + this.secretEntryPageTtlMs - Date.now()) / 1e3));
21135
+ return `Still waiting for the masked entry page -- ${elapsed}s so far, ${left}s before it expires`;
21136
+ },
21137
+ () => page.result
21138
+ );
21139
+ if (mode === "url" && outcome.kind !== "closed") this.notifyElicitationComplete(page.elicitationId, namespace);
21140
+ if (outcome.kind === "submitted") return { kind: "submitted", values: outcome.values };
21141
+ if (outcome.kind === "expired") return { kind: "unreachable", reason: "expired" };
21142
+ return { kind: "failed" };
21143
+ } finally {
21144
+ page.close();
21145
+ this.secretEntryPages.delete(page);
21146
+ }
21147
+ }
21148
+ // notifications/elicitation/complete for a URL-mode elicitation. Best
21149
+ // effort and never awaited: the notification is a courtesy the spec lets a
21150
+ // server skip (MAY), so a client that errors on it must not fail the unlock.
21151
+ notifyElicitationComplete(elicitationId, namespace) {
21152
+ const onError = (err) => {
21153
+ log("debug", "Could not send the elicitation completion notification", {
21154
+ namespace,
21155
+ error: err instanceof Error ? err.message : String(err)
21156
+ });
21157
+ };
21158
+ try {
21159
+ this.server.createElicitationCompletionNotifier(elicitationId)().catch(onError);
21160
+ } catch (err) {
21161
+ onError(err);
21162
+ }
21163
+ }
20378
21164
  // The prompt half of the vault path, split out so concurrent callers can
20379
21165
  // await ONE of them (see vaultElicitInflight). Owns the ask budget, the
20380
21166
  // latch, verification, and storing the verified value; tells the caller
20381
- // which of the three things happened, because they need different words:
20382
- // "unlocked" -- verified and stored; retry the activation.
20383
- // "rejected" -- the user typed a passphrase and it did not verify.
20384
- // "unavailable" -- declined, empty, or the elicitation request failed.
21167
+ // which of these happened, because they need different words:
21168
+ // unlocked -- verified and stored; retry the activation.
21169
+ // rejected -- the user typed a passphrase and it did not verify.
21170
+ // unavailable -- declined, empty, or the elicitation request failed.
21171
+ // unreachable -- the masked-entry page never took a passphrase.
20385
21172
  async promptForVaultPassphrase(namespace, lastError, progress) {
20386
21173
  this.vaultPassphrasePrompts++;
20387
21174
  if (this.vaultPassphrasePrompts >= MAX_VAULT_PASSPHRASE_PROMPTS) this.vaultPassphraseElicited = true;
20388
21175
  progress?.("Vault is locked -- asking for the passphrase");
20389
- const why = lastError.reason === "invalid" ? `the vault passphrase yaw-mcp has does not unlock your local secret vault (${lastError.refKeys.join(", ")} reference it). Enter the correct passphrase to use for this session, or decline to cancel. The value in YAW_MCP_VAULT_PASSPHRASE is wrong or belongs to a different vault -- fix it there to stop this recurring.` : `its env (${lastError.refKeys.join(", ")}) references your local secret vault, which is locked. Enter your vault passphrase to unlock it for this session, or decline to cancel. Set YAW_MCP_VAULT_PASSPHRASE in yaw-mcp's own env to skip this prompt in future sessions.`;
20390
- let result;
20391
- try {
20392
- result = await this.server.elicitInput({
20393
- message: `"${namespace}" cannot start: ${why}`,
20394
- requestedSchema: {
20395
- type: "object",
20396
- properties: {
20397
- YAW_MCP_VAULT_PASSPHRASE: {
20398
- type: "string",
20399
- title: "Vault passphrase",
20400
- description: "Unlocks ~/.yaw-mcp/secrets.json. Kept in memory for this session only -- never written to disk, and never passed to the server being started."
20401
- }
20402
- },
20403
- required: ["YAW_MCP_VAULT_PASSPHRASE"]
20404
- }
20405
- });
20406
- } catch (err) {
20407
- log("warn", "Vault passphrase elicitation failed", {
20408
- namespace,
20409
- error: err instanceof Error ? err.message : String(err)
20410
- });
20411
- return "unavailable";
20412
- }
20413
- if (result.action !== "accept" || !result.content) {
21176
+ const invalid = lastError.reason === "invalid";
21177
+ const keys = lastError.refKeys.join(", ");
21178
+ const why = invalid ? `"${namespace}" cannot start: the vault passphrase yaw-mcp has does not unlock your local secret vault (${keys} reference it). The value in YAW_MCP_VAULT_PASSPHRASE is wrong or belongs to a different vault -- fix it there to stop this recurring.` : `"${namespace}" cannot start: its env (${keys}) references your local secret vault, which is locked. Set YAW_MCP_VAULT_PASSPHRASE in yaw-mcp's own env to skip this prompt in future sessions.`;
21179
+ const keep = "yaw-mcp keeps it in memory for this session only -- it is never written to disk, and never passed to the server being started.";
21180
+ const entry = await this.collectSecretOnLoopbackPage({
21181
+ namespace,
21182
+ why,
21183
+ secretNoun: invalid ? "the correct vault passphrase" : "your vault passphrase",
21184
+ page: {
21185
+ title: "Unlock your yaw-mcp secret vault",
21186
+ intro: invalid ? `The passphrase yaw-mcp was given does not unlock your local secret vault (~/.yaw-mcp/secrets.json), and "${namespace}" needs it. Type the correct passphrase below. ${keep}` : `"${namespace}" needs your local secret vault (~/.yaw-mcp/secrets.json) unlocked. Type its passphrase below. ${keep}`,
21187
+ fields: [{ name: VAULT_PAGE_FIELD, label: "Vault passphrase" }],
21188
+ doneMessage: "Received. You can close this tab and return to your MCP client."
21189
+ },
21190
+ progress
21191
+ });
21192
+ if (entry.kind === "failed") return { kind: "unavailable" };
21193
+ if (entry.kind === "declined") {
20414
21194
  this.vaultPassphraseElicited = true;
20415
- log("info", "User declined vault passphrase elicitation", { namespace, action: result.action });
20416
- return "unavailable";
21195
+ return { kind: "unavailable" };
21196
+ }
21197
+ if (entry.kind === "unreachable") {
21198
+ if (entry.reason !== "expired") this.vaultPassphraseElicited = true;
21199
+ return { kind: "unreachable", reason: entry.reason };
20417
21200
  }
20418
- const value = result.content.YAW_MCP_VAULT_PASSPHRASE;
20419
- if (typeof value !== "string" || value.length === 0) return "unavailable";
21201
+ const value = entry.values[VAULT_PAGE_FIELD];
21202
+ if (typeof value !== "string" || value.length === 0) return { kind: "unavailable" };
20420
21203
  if (!await verifyVaultPassphrase(value)) {
20421
21204
  log("info", "Elicited vault passphrase did not unlock the vault", {
20422
21205
  namespace,
20423
21206
  attempt: this.vaultPassphrasePrompts
20424
21207
  });
20425
21208
  progress?.("That passphrase did not unlock the vault");
20426
- return "rejected";
21209
+ return { kind: "rejected" };
20427
21210
  }
20428
21211
  setSessionVaultPassphrase(value);
20429
21212
  this.vaultPassphraseElicited = true;
20430
- return "unlocked";
21213
+ return { kind: "unlocked" };
20431
21214
  }
20432
21215
  async handleActivate(namespaces, progress, toolsFilter) {
20433
21216
  if (namespaces.length === 0) {
@@ -21492,6 +22275,7 @@ To load the top pack in one step, call \`mcp_connect_activate\` with namespaces=
21492
22275
  async shutdown() {
21493
22276
  log("info", "Shutting down yaw-mcp");
21494
22277
  this.shuttingDown = true;
22278
+ for (const page of this.secretEntryPages) page.close();
21495
22279
  if (this.stateSaveTimer) {
21496
22280
  clearTimeout(this.stateSaveTimer);
21497
22281
  this.stateSaveTimer = null;
@@ -21566,7 +22350,7 @@ function registerShutdownTriggers(shutdown, targets) {
21566
22350
  // src/status-cmd.ts
21567
22351
  import { existsSync as existsSync10 } from "fs";
21568
22352
  import { homedir as homedir23 } from "os";
21569
- var VERSION2 = true ? "1.0.10" : "dev";
22353
+ var VERSION2 = true ? "1.0.12" : "dev";
21570
22354
  var STATUS_SCHEMA_VERSION = 1;
21571
22355
  var STATUS_USAGE = `Usage: yaw-mcp status [--json]
21572
22356
 
@@ -22044,7 +22828,7 @@ if (subcommand === "compliance") {
22044
22828
 
22045
22829
  Secrets:
22046
22830
  secrets <action> Manage the local encrypted secret vault: set,
22047
- get, list, remove, lock, rotate, audit.
22831
+ get, list, remove, lock, rotate, reset, audit.
22048
22832
  Reference a stored value from any server's env
22049
22833
  as \${secret:NAME}.
22050
22834
 
@@ -22133,10 +22917,14 @@ if (subcommand === "compliance") {
22133
22917
  \`0\` disables).
22134
22918
  YAW_MCP_TOOL_EXPOSURE How much of the catalog tools/list advertises.
22135
22919
  \`gateway\` (default) exposes the meta-tools
22136
- plus loaded servers only; \`full\` restores the
22920
+ plus loaded servers only; \`lite\` (the default
22921
+ when the client is typed-cli) exposes only
22922
+ mcp_connect_exec / find_tool / read_tool plus
22923
+ loaded servers; \`full\` restores the
22137
22924
  pre-gateway behavior and inlines the whole
22138
- catalog. Re-read per call -- a change lands on
22139
- the next tools/list without a restart.
22925
+ catalog. Set, it wins over the client default.
22926
+ Re-read per call -- a change lands on the next
22927
+ tools/list without a restart.
22140
22928
  YAW_MCP_ROUTE_EFFORT How hard dispatch tries to break ranking ties
22141
22929
  with the client LLM: \`off\` | \`auto\` |
22142
22930
  \`aggressive\` (default auto). The dispatch
@@ -22176,7 +22964,8 @@ if (subcommand === "compliance") {
22176
22964
  from every child env. A client that supports
22177
22965
  MCP elicitation prompts for it instead, for
22178
22966
  that session only. Manage entries with
22179
- \`yaw-mcp secrets\`.
22967
+ \`yaw-mcp secrets\`; when it is set, \`secrets
22968
+ reset\` keys the fresh vault it creates under it.
22180
22969
  YAW_MCP_VAULT_PASSPHRASE_NEW The NEW passphrase for \`yaw-mcp secrets
22181
22970
  rotate\`, so a re-wrap can run without a TTY.
22182
22971
  Read only by \`rotate\`; without it (and
@@ -22226,10 +23015,11 @@ if (subcommand === "compliance") {
22226
23015
  (\`oam.exe\` on Windows).
22227
23016
  OAM_MAX_HEAP_MB Read by oam, not by yaw-mcp: raises the V8
22228
23017
  heap cap oam applies to a hosted server (4 GiB
22229
- by default since oam 0.9.2). Set it in that
22230
- server's \`env\` in bundles.json when a hosted
22231
- sidecar dies with a heap out-of-memory error,
22232
- or give that server \`"runtime": "node"\`.
23018
+ by default; can be lower inside a memory-limited
23019
+ Linux container). Set it in that server's \`env\`
23020
+ in bundles.json when a hosted sidecar dies with a
23021
+ heap out-of-memory error, or give that server
23022
+ \`"runtime": "node"\`.
22233
23023
  MCP_CONNECT_TIMEOUT Milliseconds to wait for a server's MCP
22234
23024
  handshake (default 15000). This is the FALLBACK
22235
23025
  only -- a server's own \`connectTimeoutMs\` in
@@ -22340,7 +23130,7 @@ if (subcommand === "compliance") {
22340
23130
  `);
22341
23131
  process.exitCode = 0;
22342
23132
  } else if (subcommand === "--version" || subcommand === "-V") {
22343
- process.stdout.write(`yaw-mcp ${true ? "1.0.10" : "dev"}
23133
+ process.stdout.write(`yaw-mcp ${true ? "1.0.12" : "dev"}
22344
23134
  `);
22345
23135
  process.exitCode = 0;
22346
23136
  } else if (subcommand !== void 0 && !subcommand.startsWith("-")) {