@yawlabs/mcp 1.0.9 → 1.0.11

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-7MK2GPCC.js";
104
+ } from "./chunk-FIEXTOHT.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;
@@ -3203,7 +3205,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
3203
3205
  if (downstreamCaps?.sampling) capabilities.sampling = downstreamCaps.sampling;
3204
3206
  if (downstreamCaps?.roots) capabilities.roots = {};
3205
3207
  const client = new Client(
3206
- { name: "yaw-mcp", version: true ? "1.0.9" : "dev" },
3208
+ { name: "yaw-mcp", version: true ? "1.0.11" : "dev" },
3207
3209
  { capabilities }
3208
3210
  );
3209
3211
  if (bridge && capabilities.elicitation) {
@@ -5155,13 +5157,13 @@ async function resolvePassphrase(opts, io, confirm = false) {
5155
5157
  if (confirm) {
5156
5158
  for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
5157
5159
  const first = await readLineFromTTY(stdin, stdout, "Vault passphrase: ");
5158
- if (first === CANCELLED) return CANCELLED;
5160
+ if (first === CANCELLED || first === NO_ECHO) return first;
5159
5161
  if (first.length === 0) {
5160
5162
  stdout.write("Passphrase cannot be empty.\n");
5161
5163
  continue;
5162
5164
  }
5163
5165
  const second = await readLineFromTTY(stdin, stdout, "Confirm passphrase: ");
5164
- if (second === CANCELLED) return CANCELLED;
5166
+ if (second === CANCELLED || second === NO_ECHO) return second;
5165
5167
  if (first === second) {
5166
5168
  warnIfShortPassphrase(io, first, "the passphrase you chose");
5167
5169
  return first;
@@ -5172,7 +5174,7 @@ async function resolvePassphrase(opts, io, confirm = false) {
5172
5174
  }
5173
5175
  for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
5174
5176
  const entered = await readLineFromTTY(stdin, stdout);
5175
- if (entered === CANCELLED) return CANCELLED;
5177
+ if (entered === CANCELLED || entered === NO_ECHO) return entered;
5176
5178
  if (entered.length > 0) {
5177
5179
  warnIfShortPassphrase(
5178
5180
  io,
@@ -5198,13 +5200,13 @@ async function resolveNewPassphrase(opts, io) {
5198
5200
  if (!isInteractiveTTY(opts)) return null;
5199
5201
  for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
5200
5202
  const first = await readLineFromTTY(stdin, stdout, "New vault passphrase: ");
5201
- if (first === CANCELLED) return CANCELLED;
5203
+ if (first === CANCELLED || first === NO_ECHO) return first;
5202
5204
  if (first.length === 0) {
5203
5205
  stdout.write("Passphrase cannot be empty.\n");
5204
5206
  continue;
5205
5207
  }
5206
5208
  const second = await readLineFromTTY(stdin, stdout, "Confirm new passphrase: ");
5207
- if (second === CANCELLED) return CANCELLED;
5209
+ if (second === CANCELLED || second === NO_ECHO) return second;
5208
5210
  if (first === second) {
5209
5211
  warnIfShortPassphrase(io, first, "the new passphrase");
5210
5212
  return first;
@@ -5219,15 +5221,27 @@ var CTRL_C = "";
5219
5221
  var CTRL_D = "";
5220
5222
  var DEL = "\x7F";
5221
5223
  var ESC = "\x1B";
5224
+ var NO_ECHO = /* @__PURE__ */ Symbol("yaw-mcp:no-echo-unavailable");
5225
+ function noEchoRefusal(required, remedy) {
5226
+ return `${required} Refusing to prompt: this terminal would not turn echo off, so what you type would be shown on screen. ${remedy}`;
5227
+ }
5222
5228
  function readLineFromTTY(stdin, stdout, prompt = "Vault passphrase: ", echo = false) {
5223
- stdout.write(prompt);
5224
5229
  return new Promise((resolve8) => {
5225
5230
  const chunks = [];
5226
5231
  const wasRaw = stdin.isRaw === true;
5232
+ let raw = false;
5227
5233
  try {
5228
- stdin.setRawMode?.(true);
5234
+ if (typeof stdin.setRawMode === "function") {
5235
+ stdin.setRawMode(true);
5236
+ raw = true;
5237
+ }
5229
5238
  } catch {
5230
5239
  }
5240
+ if (!raw && !echo) {
5241
+ resolve8(NO_ECHO);
5242
+ return;
5243
+ }
5244
+ stdout.write(prompt);
5231
5245
  stdin.resume();
5232
5246
  stdin.setEncoding("utf8");
5233
5247
  const finish = (value) => {
@@ -5406,6 +5420,14 @@ async function runSecrets(opts, io = {
5406
5420
  const creatingVault = opts.action === "set" && !vault.check && Object.keys(vault.entries).length === 0;
5407
5421
  const passphrase = await resolvePassphrase(opts, io, creatingVault);
5408
5422
  if (passphrase === CANCELLED) return cancelledResult(io, opts.json);
5423
+ if (passphrase === NO_ECHO) {
5424
+ const msg = noEchoRefusal("Passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead.");
5425
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5426
+ `);
5427
+ else io.err(`yaw-mcp secrets: ${msg}
5428
+ `);
5429
+ return { exitCode: 1 };
5430
+ }
5409
5431
  if (passphrase === null) {
5410
5432
  const msg = promptUnavailableMessage(opts, "Passphrase required.", "YAW_MCP_VAULT_PASSPHRASE");
5411
5433
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
@@ -5432,6 +5454,14 @@ async function runSecrets(opts, io = {
5432
5454
  else {
5433
5455
  const entered = await readStdinValue(opts.io, opts.fromStdin);
5434
5456
  if (entered === CANCELLED) return cancelledResult(io, opts.json);
5457
+ if (entered === NO_ECHO) {
5458
+ const msg = noEchoRefusal("Secret value required.", "Pipe the value in with --stdin instead.");
5459
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5460
+ `);
5461
+ else io.err(`yaw-mcp secrets set: ${msg}
5462
+ `);
5463
+ return { exitCode: 1 };
5464
+ }
5435
5465
  if (entered === PROMPT_IMPOSSIBLE) {
5436
5466
  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
5467
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
@@ -5533,6 +5563,14 @@ async function runSecretsRotate(opts, io) {
5533
5563
  }
5534
5564
  const currentPassphrase = await resolvePassphrase(opts, io);
5535
5565
  if (currentPassphrase === CANCELLED) return cancelledResult(io, opts.json);
5566
+ if (currentPassphrase === NO_ECHO) {
5567
+ const msg = noEchoRefusal("Current passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead.");
5568
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5569
+ `);
5570
+ else io.err(`yaw-mcp secrets rotate: ${msg}
5571
+ `);
5572
+ return { exitCode: 1 };
5573
+ }
5536
5574
  if (currentPassphrase === null) {
5537
5575
  const msg = promptUnavailableMessage(opts, "Current passphrase required.", "YAW_MCP_VAULT_PASSPHRASE");
5538
5576
  if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
@@ -5554,6 +5592,14 @@ async function runSecretsRotate(opts, io) {
5554
5592
  }
5555
5593
  const newPassphrase = await resolveNewPassphrase(opts, io);
5556
5594
  if (newPassphrase === CANCELLED) return cancelledResult(io, opts.json);
5595
+ if (newPassphrase === NO_ECHO) {
5596
+ const msg = noEchoRefusal("New passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE_NEW instead.");
5597
+ if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5598
+ `);
5599
+ else io.err(`yaw-mcp secrets rotate: ${msg}
5600
+ `);
5601
+ return { exitCode: 1 };
5602
+ }
5557
5603
  if (newPassphrase === null) {
5558
5604
  const msg = promptUnavailableMessage(
5559
5605
  opts,
@@ -7624,7 +7670,7 @@ async function runSidecarsInstall(opts = {}) {
7624
7670
  print(` note: ${k.namespace} launches ${k.spec}, not a registry package; it keeps using npx`);
7625
7671
  }
7626
7672
  for (const k of ranges) {
7627
- print(` note: ${k.namespace} launches ${k.spec}, a version range oam cannot resolve; it keeps using npx`);
7673
+ print(` note: ${k.namespace} launches ${k.spec}, a version range yaw-mcp does not evaluate; it keeps using npx`);
7628
7674
  }
7629
7675
  };
7630
7676
  if (specs.length === 0) {
@@ -7947,8 +7993,7 @@ function defaultInstalledVersion(pkg, home) {
7947
7993
  return installedVersion(pkg, home);
7948
7994
  }
7949
7995
  function isSidecarRefreshDisabled(env = process.env) {
7950
- const raw = env.YAW_MCP_SIDECAR_REFRESH;
7951
- return raw === "0" || raw?.toLowerCase() === "false";
7996
+ return isFeatureDisabled("YAW_MCP_SIDECAR_REFRESH", env);
7952
7997
  }
7953
7998
  async function maybeRefreshSidecars(deps = {}) {
7954
7999
  try {
@@ -8231,14 +8276,24 @@ async function resolveCatalogSlug(slug, opts = {}) {
8231
8276
  if (!command) {
8232
8277
  throw new Error(`catalog entry "${slug}" install command was empty.`);
8233
8278
  }
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)) : [];
8279
+ const requiredEnvKeys = [];
8280
+ const optionalEnvKeys = [];
8281
+ if (Array.isArray(entry.requiredEnv)) {
8282
+ for (const e of entry.requiredEnv) {
8283
+ const key = e && typeof e === "object" ? e.key : void 0;
8284
+ if (typeof key !== "string" || !ENV_KEY_RE.test(key)) continue;
8285
+ (e.optional === true ? optionalEnvKeys : requiredEnvKeys).push(key);
8286
+ }
8287
+ }
8288
+ const optionalOnly = optionalEnvKeys.filter((k) => !requiredEnvKeys.includes(k));
8235
8289
  const source = typeof entry.repo === "string" ? entry.repo : typeof entry.homepage === "string" ? entry.homepage : void 0;
8236
8290
  return {
8237
8291
  slug,
8238
8292
  name: typeof entry.name === "string" && entry.name.trim() ? entry.name.trim() : slug,
8239
8293
  command,
8240
8294
  args,
8241
- requiredEnvKeys: requiredEnvKeys2,
8295
+ requiredEnvKeys,
8296
+ optionalEnvKeys: optionalOnly,
8242
8297
  description: typeof entry.description === "string" ? entry.description : void 0,
8243
8298
  source,
8244
8299
  docUrl: source,
@@ -8582,7 +8637,7 @@ ${USAGE}`);
8582
8637
  );
8583
8638
  } else if (oamProbeResult.belowMin) {
8584
8639
  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)`
8640
+ `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
8641
  );
8587
8642
  } else if (oamProbeResult.failure) {
8588
8643
  runtimeLines.push(
@@ -10294,6 +10349,7 @@ async function defaultFetchExplore(slug, catalogUrl) {
10294
10349
  args: resolved.args,
10295
10350
  requiredEnvVars: resolved.requiredEnvKeys
10296
10351
  };
10352
+ if (resolved.optionalEnvKeys.length > 0) out.optionalEnvVars = resolved.optionalEnvKeys;
10297
10353
  if (resolved.docUrl) out.docUrl = resolved.docUrl;
10298
10354
  return out;
10299
10355
  }
@@ -10391,6 +10447,9 @@ async function runTry(opts) {
10391
10447
  if (missing.length > 0) {
10392
10448
  printErr(`yaw-mcp try: ${server.name} needs the following env var(s) before it can run:`);
10393
10449
  for (const k of missing) printErr(` - ${k}`);
10450
+ if ((server.optionalEnvVars ?? []).length > 0) {
10451
+ printErr(`Optional, not needed to run: ${(server.optionalEnvVars ?? []).join(", ")}`);
10452
+ }
10394
10453
  printErr("");
10395
10454
  printErr("Set them via --env KEY=value (repeatable) or your shell, then re-run:");
10396
10455
  const example = missing.map((k) => `--env ${k}=...`).join(" ");
@@ -10398,8 +10457,9 @@ async function runTry(opts) {
10398
10457
  if (server.docUrl) printErr(`Docs: ${server.docUrl}`);
10399
10458
  return { exitCode: 1, written: [] };
10400
10459
  }
10460
+ const declaredEnvVars = [...server.requiredEnvVars ?? [], ...server.optionalEnvVars ?? []];
10401
10461
  const trialEnv = {};
10402
- for (const k of server.requiredEnvVars ?? []) {
10462
+ for (const k of declaredEnvVars) {
10403
10463
  const v = (lookup(k) ?? "").trim();
10404
10464
  if (v) trialEnv[k] = v;
10405
10465
  }
@@ -10409,9 +10469,11 @@ async function runTry(opts) {
10409
10469
  if (trimmed) trialEnv[k] = trimmed;
10410
10470
  }
10411
10471
  const overrides = opts.envOverrides ?? {};
10412
- const ambientOnlyRequired = (server.requiredEnvVars ?? []).filter(
10413
- (k) => !overrides[k] && (lookup(k) ?? "").trim() !== ""
10414
- );
10472
+ const ambientOnly = (k) => !overrides[k] && (lookup(k) ?? "").trim() !== "";
10473
+ const ambientOnlyRequired = [
10474
+ ...(server.requiredEnvVars ?? []).filter(ambientOnly),
10475
+ ...(server.optionalEnvVars ?? []).filter(ambientOnly).map((k) => `${k} (optional)`)
10476
+ ];
10415
10477
  const entry = buildLaunchEntry({
10416
10478
  os,
10417
10479
  upstream: {
@@ -10505,7 +10567,12 @@ async function runTry(opts) {
10505
10567
  print(`yaw-mcp try (dry-run): would write ${resolved.absolute}`);
10506
10568
  print(` entry name: ${entryName}`);
10507
10569
  print(` command: ${entry.command} ${entry.args.join(" ")}`);
10508
- if (entry.env) print(` env keys: ${Object.keys(entry.env).join(", ")}`);
10570
+ if (entry.env) {
10571
+ const optional = server.optionalEnvVars ?? [];
10572
+ print(
10573
+ ` env keys: ${Object.keys(entry.env).map((k) => optional.includes(k) ? `${k} (optional)` : k).join(", ")}`
10574
+ );
10575
+ }
10509
10576
  print(` expires: ${new Date(expiresAt).toISOString()}`);
10510
10577
  print(` marker: ${trialMarkerPath(slug, home)}`);
10511
10578
  if (replacesEntryInPlace) {
@@ -11074,7 +11141,7 @@ function foldBundleWarnings(warnings, probe) {
11074
11141
  const prefix = `${probe.path}:`;
11075
11142
  return warnings.filter((w) => !w.startsWith(prefix));
11076
11143
  }
11077
- var VERSION = true ? "1.0.9" : "dev";
11144
+ var VERSION = true ? "1.0.11" : "dev";
11078
11145
  var DOCTOR_USAGE = `Usage: yaw-mcp doctor [--json]
11079
11146
 
11080
11147
  Print a diagnostic of your yaw-mcp setup.
@@ -11521,7 +11588,7 @@ var DOCTOR_ENV_VARS = [
11521
11588
  { name: "YAW_MCP_PRUNE_RESPONSES", defaultHint: "pruning active" },
11522
11589
  { name: "YAW_MCP_MAX_RESULT_BYTES", defaultHint: "default 100000" },
11523
11590
  { name: "YAW_MCP_DEFAULT_RUNTIME", defaultHint: "oam when installed" },
11524
- { name: "YAW_MCP_TOOL_EXPOSURE", defaultHint: "gateway" },
11591
+ { name: "YAW_MCP_TOOL_EXPOSURE", defaultHint: "gateway; lite for typed-cli" },
11525
11592
  { name: "YAW_MCP_AUTO_UPGRADE", defaultHint: "default on" },
11526
11593
  { name: "YAW_MCP_AUTO_HEAL", defaultHint: "default on" },
11527
11594
  { name: "YAW_MCP_SIDECAR_REFRESH", defaultHint: "default on" },
@@ -11726,6 +11793,7 @@ function renderOamRuntimeSection(opts) {
11726
11793
  if (probe.belowMin) {
11727
11794
  print(` binary: installed (v${probe.version}) -- below min ${MIN_OAM_VERSION}; IGNORED, servers run on node`);
11728
11795
  print(" fix: oam self-update");
11796
+ print(" then: restart yaw-mcp -- a running broker keeps its oam probe for its lifetime");
11729
11797
  } else if (probe.failure !== null) {
11730
11798
  print(` binary: installed but UNUSABLE (${oamFailureLabel(probe.failure)}); servers run on node`);
11731
11799
  if (probe.failureDetail !== null) print(` detail: ${probe.failureDetail}`);
@@ -13105,83 +13173,92 @@ async function healStaleBrokerEntries(opts = {}) {
13105
13173
  replacement = { oamBinPath, oamEntry: oamBinPath === null ? null : resolveEntry("@yawlabs/mcp") };
13106
13174
  return replacement;
13107
13175
  };
13176
+ const clientEnv2 = readClientEnv(env);
13177
+ const appData = resolveAppDataDir({ appData: opts.appData, home: opts.home, env });
13178
+ const claudeConfigDir = opts.claudeConfigDir ?? clientEnv2.claudeConfigDir;
13108
13179
  const seen = /* @__PURE__ */ new Set();
13180
+ const healSite = async (target, scope, site) => {
13181
+ try {
13182
+ const view = await readClientConfigFile(site, { transform: target.entry });
13183
+ if (view.read.kind !== "ok") {
13184
+ if (view.read.kind !== "absent") {
13185
+ unhealable.push({
13186
+ clientId: target.clientId,
13187
+ scope,
13188
+ path: site.resolved.absolute,
13189
+ reason: view.read.kind
13190
+ });
13191
+ }
13192
+ return;
13193
+ }
13194
+ const stored = view.read.entries.find((e) => e.key === ENTRY_NAME);
13195
+ if (stored === void 0) return;
13196
+ const launch = stored.launch ?? launchOf(stored.value);
13197
+ if (launch === null) return;
13198
+ const entryPath = oamRunEntryPath(launch.command, launch.args);
13199
+ if (entryPath === null || !isOwnBrokerEntry(entryPath)) return;
13200
+ if (isForeignEntry(launch.command, entryPath, platform)) return;
13201
+ if (isLaunchableFile(entryPath)) return;
13202
+ const { oamBinPath, oamEntry } = await replacementFor();
13203
+ const base = buildLaunchEntry({
13204
+ os,
13205
+ oamBinPath,
13206
+ oamEntry,
13207
+ windowsWrap: target.entry?.windowsLaunch?.broker !== "bare"
13208
+ });
13209
+ const next = composeEntry({
13210
+ base,
13211
+ transform: target.entry,
13212
+ os,
13213
+ purpose: "broker",
13214
+ env: carryableEnvOf(stored.value),
13215
+ carried: carriedFieldsOf(stored.value, target.entry)
13216
+ });
13217
+ const nextLaunch = launchOf(next);
13218
+ const nextEntry = nextLaunch === null ? null : oamRunEntryPath(nextLaunch.command, nextLaunch.args);
13219
+ if (nextEntry !== null && norm(nextEntry, platform) === norm(entryPath, platform)) return;
13220
+ if (opts.dryRun !== true) {
13221
+ const text = applyClientConfigEdits(view, [{ op: "upsert", key: ENTRY_NAME, entry: next }], site);
13222
+ await atomicWriteFile(site.resolved.absolute, text);
13223
+ }
13224
+ healed.push({
13225
+ clientId: target.clientId,
13226
+ scope,
13227
+ path: site.resolved.absolute,
13228
+ from: entryPath,
13229
+ to: nextEntry ?? "npx"
13230
+ });
13231
+ } catch (err) {
13232
+ log("warn", "Could not heal a stale yaw-mcp entry", {
13233
+ path: site.resolved.absolute,
13234
+ error: err instanceof Error ? err.message : String(err)
13235
+ });
13236
+ }
13237
+ };
13109
13238
  for (const target of INSTALL_TARGETS) {
13110
13239
  for (const scope of target.scopes) {
13111
- let site;
13240
+ let sites;
13112
13241
  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];
13242
+ sites = selectSites(
13243
+ resolveInstallSites({
13244
+ clientId: target.clientId,
13245
+ scope: scope.scope,
13246
+ os,
13247
+ home: opts.home,
13248
+ appData,
13249
+ projectDir: scope.requiresProjectDir ? opts.cwd ?? process.cwd() : void 0,
13250
+ claudeConfigDir,
13251
+ clientEnv: clientEnv2
13252
+ })
13253
+ );
13122
13254
  } catch {
13123
13255
  continue;
13124
13256
  }
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
- });
13257
+ for (const site of sites) {
13258
+ const key = `${norm(site.resolved.absolute, platform)}::${addressOf(site).containerPath.join(".")}`;
13259
+ if (seen.has(key)) continue;
13260
+ seen.add(key);
13261
+ await healSite(target, scope.scope, site);
13185
13262
  }
13186
13263
  }
13187
13264
  }
@@ -13195,7 +13272,7 @@ async function healStaleBrokerEntries(opts = {}) {
13195
13272
  }
13196
13273
  async function maybeHealStaleBrokerEntries(opts = {}) {
13197
13274
  const env = opts.env ?? process.env;
13198
- if (env.YAW_MCP_AUTO_HEAL === "0") return { healed: [], unhealable: [] };
13275
+ if (isFeatureDisabled("YAW_MCP_AUTO_HEAL", env)) return { healed: [], unhealable: [] };
13199
13276
  try {
13200
13277
  return await healStaleBrokerEntries(opts);
13201
13278
  } catch (err) {
@@ -14093,9 +14170,16 @@ function jsonEntry(entry) {
14093
14170
  if (headerNames.length > 0) out.headerNames = headerNames;
14094
14171
  return out;
14095
14172
  }
14096
- function ambientOnlyRequiredKeys(requiredKeys, entry, env) {
14173
+ function ambientOnlyKeys(keys, entry, env) {
14097
14174
  const stored = entry.env ?? {};
14098
- return requiredKeys.filter((k) => (stored[k] ?? "").trim() === "" && (env[k] ?? "").trim() !== "");
14175
+ return keys.filter((k) => (stored[k] ?? "").trim() === "" && (env[k] ?? "").trim() !== "");
14176
+ }
14177
+ function unsetOptionalKeys(keys, entry, env) {
14178
+ const stored = entry.env ?? {};
14179
+ return keys.filter((k) => (stored[k] ?? "").trim() === "" && (env[k] ?? "").trim() === "");
14180
+ }
14181
+ function renderEnvKeys(env, optionalKeys) {
14182
+ return Object.keys(env).map((k) => optionalKeys.includes(k) ? `${k} (optional)` : k).join(", ");
14099
14183
  }
14100
14184
  async function danglingSecretRefs(entry, home) {
14101
14185
  const refSource = isRemoteEntry(entry) ? entry.headers : entry.env;
@@ -14132,6 +14216,22 @@ async function printPostWriteNotes(printErr, opts) {
14132
14216
  `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
14217
  );
14134
14218
  }
14219
+ const optAmbient = opts.optional.ambient;
14220
+ if (optAmbient.length > 0) {
14221
+ const one = optAmbient.length === 1;
14222
+ const verb = dryRun ? "would be" : one ? "was" : "were";
14223
+ printErr(
14224
+ `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.`
14225
+ );
14226
+ }
14227
+ const optUnset = opts.optional.unset;
14228
+ if (optUnset.length > 0) {
14229
+ const one = optUnset.length === 1;
14230
+ const verb = one ? "is" : "are";
14231
+ printErr(
14232
+ `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]}=...\`.`
14233
+ );
14234
+ }
14135
14235
  const shadow = await findShadowingProjectBundles(opts.cwd, opts.home, opts.env).catch(() => null);
14136
14236
  if (shadow) {
14137
14237
  printErr(
@@ -14240,6 +14340,7 @@ async function runAdd(opts) {
14240
14340
  // Nothing declares a requirement for a hand-defined server, so there is
14241
14341
  // no required-env gate to fail: whatever --env carries is all there is.
14242
14342
  requiredEnvKeys: [],
14343
+ optionalEnvKeys: [],
14243
14344
  description: opts.description
14244
14345
  };
14245
14346
  } else {
@@ -14263,6 +14364,9 @@ async function runAdd(opts) {
14263
14364
  if (missing.length > 0) {
14264
14365
  printErr(`yaw-mcp add: ${server.name} needs the following env var(s) before it can run:`);
14265
14366
  for (const k of missing) printErr(` - ${k}`);
14367
+ if (server.optionalEnvKeys.length > 0) {
14368
+ printErr(`Optional, not needed to run: ${server.optionalEnvKeys.join(", ")}`);
14369
+ }
14266
14370
  printErr("");
14267
14371
  printErr("Provide them with --env KEY=value (repeatable) or your shell, then re-run:");
14268
14372
  printErr(` yaw-mcp add ${slug} ${missing.map((k) => `--env ${k}=...`).join(" ")}`);
@@ -14270,7 +14374,7 @@ async function runAdd(opts) {
14270
14374
  return { exitCode: 1, written: [] };
14271
14375
  }
14272
14376
  const entryEnv = {};
14273
- for (const k of server.requiredEnvKeys) entryEnv[k] = "";
14377
+ for (const k of [...server.requiredEnvKeys, ...server.optionalEnvKeys]) entryEnv[k] = "";
14274
14378
  for (const [k, v] of Object.entries(opts.envOverrides ?? {})) {
14275
14379
  const trimmed = v.trim();
14276
14380
  if (trimmed === "") continue;
@@ -14295,7 +14399,16 @@ async function runAdd(opts) {
14295
14399
  transport: "stdio",
14296
14400
  command: server.command,
14297
14401
  args: server.args,
14298
- env: Object.keys(entryEnv).length > 0 ? entryEnv : void 0
14402
+ env: Object.keys(entryEnv).length > 0 ? entryEnv : void 0,
14403
+ // Which of the blank seeds above are optional. The entry env alone
14404
+ // cannot say -- a required key and an optional one are both "" until
14405
+ // filled -- and the Yaw app reads nothing but bundles.json when it
14406
+ // decides whether a server "needs key". The app writes the same
14407
+ // marker for the entries it adds; without ours, a server added here
14408
+ // showed "needs key" in the panel until re-added from the app.
14409
+ // Always an array so a re-add can CLEAR a stale marker (the merge
14410
+ // drops an empty one); an explicit-command add carries none.
14411
+ optionalEnvKeys: server.optionalEnvKeys
14299
14412
  },
14300
14413
  isActive: true,
14301
14414
  description: server.description,
@@ -14355,7 +14468,7 @@ If the existing entry is a different server you meant to keep, remove/re-add via
14355
14468
  const nsNote = previewNamespace === namespace ? `as namespace "${previewNamespace}"` : `keeping existing namespace "${previewNamespace}"`;
14356
14469
  print(`yaw-mcp add (dry-run): would ${preview.replaced ? "update" : "write"} ${server.name} ${nsNote}`);
14357
14470
  print(` launch: ${renderLaunch3(previewEntry)}`);
14358
- if (previewEntry.env) print(` env keys: ${Object.keys(previewEntry.env).join(", ")}`);
14471
+ if (previewEntry.env) print(` env keys: ${renderEnvKeys(previewEntry.env, server.optionalEnvKeys)}`);
14359
14472
  if (previewEntry.headers) print(` header names: ${Object.keys(previewEntry.headers).join(", ")}`);
14360
14473
  if (previewEntry.isActive === false) {
14361
14474
  print(
@@ -14364,7 +14477,12 @@ If the existing entry is a different server you meant to keep, remove/re-add via
14364
14477
  }
14365
14478
  }
14366
14479
  await printPostWriteNotes(printErr, {
14367
- ambientOnly: ambientOnlyRequiredKeys(server.requiredEnvKeys, previewEntry, env),
14480
+ ambientOnly: ambientOnlyKeys(server.requiredEnvKeys, previewEntry, env),
14481
+ optional: {
14482
+ ambient: ambientOnlyKeys(server.optionalEnvKeys, previewEntry, env),
14483
+ unset: unsetOptionalKeys(server.optionalEnvKeys, previewEntry, env),
14484
+ namespace: previewNamespace
14485
+ },
14368
14486
  // Previewed from the entry the run WOULD write, so --dry-run reports the
14369
14487
  // same dangling refs the real run would.
14370
14488
  dangling: await danglingSecretRefs(previewEntry, home),
@@ -14415,7 +14533,12 @@ If the previous entry was a different server you meant to keep, restore it from
14415
14533
  }
14416
14534
  }
14417
14535
  await printPostWriteNotes(printErr, {
14418
- ambientOnly: ambientOnlyRequiredKeys(server.requiredEnvKeys, written, env),
14536
+ ambientOnly: ambientOnlyKeys(server.requiredEnvKeys, written, env),
14537
+ optional: {
14538
+ ambient: ambientOnlyKeys(server.optionalEnvKeys, written, env),
14539
+ unset: unsetOptionalKeys(server.optionalEnvKeys, written, env),
14540
+ namespace: finalNamespace
14541
+ },
14419
14542
  // From the entry as WRITTEN, not from the flags: a re-add merges with what
14420
14543
  // was already on disk, so the stored refs are what will actually resolve.
14421
14544
  dangling: await danglingSecretRefs(written, home),
@@ -15410,10 +15533,22 @@ ${SEARCH_USAGE}` };
15410
15533
  opts.query = words.join(" ");
15411
15534
  return { ok: true, options: opts };
15412
15535
  }
15413
- function requiredEnvKeys(entry) {
15536
+ function catalogEnvKeys(entry) {
15414
15537
  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 !== "");
15538
+ const required = [];
15539
+ const optional = [];
15540
+ if (!Array.isArray(raw)) return { required, optional };
15541
+ for (const r of raw) {
15542
+ const key = typeof r === "string" ? r : r?.key;
15543
+ if (typeof key !== "string" || key === "") continue;
15544
+ const flagged = typeof r === "object" && r !== null && r.optional === true;
15545
+ (flagged ? optional : required).push(key);
15546
+ }
15547
+ return { required, optional };
15548
+ }
15549
+ function catalogEnvKeysJson(entry) {
15550
+ const { required, optional } = catalogEnvKeys(entry);
15551
+ return { requiredEnvKeys: required, optionalEnvKeys: optional };
15417
15552
  }
15418
15553
  function truncate(text, cap) {
15419
15554
  if (text.length <= cap) return text;
@@ -15426,11 +15561,12 @@ function metaLine(entry) {
15426
15561
  const parts = [`runtime ${typeof install.runtime === "string" ? install.runtime : "unknown"}`];
15427
15562
  const toolCount = entry.toolCount;
15428
15563
  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(", ")}`);
15564
+ const { required, optional } = catalogEnvKeys(entry);
15565
+ if (required.length > 0) parts.push(`needs ${required.join(", ")}`);
15431
15566
  else if (entry.requiresSetup === true)
15432
- parts.push("needs setup (no env keys listed)");
15567
+ parts.push(optional.length > 0 ? "needs setup" : "needs setup (no env keys listed)");
15433
15568
  else parts.push("no credentials");
15569
+ if (optional.length > 0) parts.push(`optional ${optional.join(", ")}`);
15434
15570
  const runtime = typeof install.runtime === "string" ? install.runtime.toLowerCase() : "";
15435
15571
  if (install.url || install.type === "remote" || /^(remote|https?|sse|url)$/.test(runtime)) {
15436
15572
  parts.push("remote -- add by hand");
@@ -15455,7 +15591,10 @@ function renderJson(opts, catalogUrl, matches, shown, suggested) {
15455
15591
  tags: entry.tags,
15456
15592
  runtime: entry.install?.runtime,
15457
15593
  command: entry.install?.command,
15458
- requiredEnvKeys: requiredEnvKeys(entry),
15594
+ // `requiredEnvKeys` keeps its pre-flag meaning (what `add` refuses
15595
+ // without) so a script gating on it does not start refusing servers
15596
+ // it used to accept; the optional keys ride in their own field.
15597
+ ...catalogEnvKeysJson(entry),
15459
15598
  toolCount: entry.toolCount,
15460
15599
  estimatedTokens: entry.estimatedTokens,
15461
15600
  repo: entry.repo
@@ -15552,6 +15691,7 @@ function decideServeMode(stdin, env) {
15552
15691
 
15553
15692
  // src/server.ts
15554
15693
  import { homedir as homedir22 } from "os";
15694
+ import { getSupportedElicitationModes } from "@modelcontextprotocol/sdk/client/index.js";
15555
15695
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
15556
15696
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15557
15697
  import {
@@ -15564,138 +15704,6 @@ import {
15564
15704
  ReadResourceRequestSchema
15565
15705
  } from "@modelcontextprotocol/sdk/types.js";
15566
15706
 
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
15707
  // src/cost-estimate.ts
15700
15708
  var BYTES_PER_TOKEN = 4;
15701
15709
  var CACHED_TOOL_SCHEMA_PAD_BYTES = 200;
@@ -16217,20 +16225,25 @@ function recordNudges(clis, home, now = Date.now) {
16217
16225
 
16218
16226
  // src/meta-tools.ts
16219
16227
  var PENALTY_RATE_PCT = Math.round(PENALTY_RATE_THRESHOLD * 100);
16228
+ var SERVER_INSTRUCTIONS = [
16229
+ "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.",
16230
+ "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).",
16231
+ "Prefer a server over the CLI it shadows. Read yaw-mcp://guide first when listed: this project's routing rules."
16232
+ ].join(" ");
16220
16233
  var META_TOOLS = {
16221
16234
  discover: {
16222
16235
  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.',
16236
+ 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
16237
  inputSchema: {
16225
16238
  type: "object",
16226
16239
  properties: {
16227
16240
  context: {
16228
16241
  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."
16242
+ description: "Optional: the current task. Servers are sorted by relevance to it."
16230
16243
  },
16231
16244
  server: {
16232
16245
  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."
16246
+ description: "Optional: one namespace to report on in full -- just that server's card, with its complete tool list."
16234
16247
  }
16235
16248
  }
16236
16249
  },
@@ -16244,7 +16257,7 @@ var META_TOOLS = {
16244
16257
  },
16245
16258
  activate: {
16246
16259
  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.',
16260
+ 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
16261
  inputSchema: {
16249
16262
  type: "object",
16250
16263
  properties: {
@@ -16260,7 +16273,7 @@ var META_TOOLS = {
16260
16273
  tools: {
16261
16274
  type: "array",
16262
16275
  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."
16276
+ 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
16277
  }
16265
16278
  }
16266
16279
  },
@@ -16274,7 +16287,7 @@ var META_TOOLS = {
16274
16287
  },
16275
16288
  deactivate: {
16276
16289
  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.',
16290
+ 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
16291
  inputSchema: {
16279
16292
  type: "object",
16280
16293
  properties: {
@@ -16299,7 +16312,7 @@ var META_TOOLS = {
16299
16312
  },
16300
16313
  health: {
16301
16314
  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.`,
16315
+ 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
16316
  inputSchema: {
16304
16317
  type: "object",
16305
16318
  properties: {}
@@ -16314,7 +16327,7 @@ var META_TOOLS = {
16314
16327
  },
16315
16328
  dispatch: {
16316
16329
  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").',
16330
+ 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
16331
  inputSchema: {
16319
16332
  type: "object",
16320
16333
  properties: {
@@ -16332,12 +16345,12 @@ var META_TOOLS = {
16332
16345
  minimum: 1,
16333
16346
  maximum: 10,
16334
16347
  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."
16348
+ description: "How many top-ranked servers to load. Default 1, cap 10."
16336
16349
  },
16337
16350
  routeEffort: {
16338
16351
  type: "string",
16339
16352
  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.'
16353
+ 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
16354
  }
16342
16355
  },
16343
16356
  required: ["intent"]
@@ -16352,7 +16365,7 @@ var META_TOOLS = {
16352
16365
  },
16353
16366
  read_tool: {
16354
16367
  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).",
16368
+ 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
16369
  inputSchema: {
16357
16370
  type: "object",
16358
16371
  properties: {
@@ -16362,7 +16375,7 @@ var META_TOOLS = {
16362
16375
  },
16363
16376
  tool: {
16364
16377
  type: "string",
16365
- description: 'Tool name. The namespace prefix is optional \u2014 both "create_issue" and "gh_create_issue" are accepted.'
16378
+ description: 'Tool name; the namespace prefix is optional ("create_issue" and "gh_create_issue" both work).'
16366
16379
  }
16367
16380
  },
16368
16381
  required: ["server", "tool"]
@@ -16377,13 +16390,13 @@ var META_TOOLS = {
16377
16390
  },
16378
16391
  findTool: {
16379
16392
  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.',
16393
+ 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
16394
  inputSchema: {
16382
16395
  type: "object",
16383
16396
  properties: {
16384
16397
  query: {
16385
16398
  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.'
16399
+ description: 'What the tool should DO, in plain words -- "create a github issue", "query postgres", "resize an image".'
16387
16400
  },
16388
16401
  limit: {
16389
16402
  type: "number",
@@ -16402,7 +16415,7 @@ var META_TOOLS = {
16402
16415
  },
16403
16416
  suggest: {
16404
16417
  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.",
16418
+ 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
16419
  inputSchema: {
16407
16420
  type: "object",
16408
16421
  properties: {}
@@ -16417,14 +16430,14 @@ var META_TOOLS = {
16417
16430
  },
16418
16431
  bundles: {
16419
16432
  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.',
16433
+ 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
16434
  inputSchema: {
16422
16435
  type: "object",
16423
16436
  properties: {
16424
16437
  action: {
16425
16438
  type: "string",
16426
16439
  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).'
16440
+ description: '"list" (default): the full curated catalog. "match": partition against installed servers.'
16428
16441
  }
16429
16442
  }
16430
16443
  },
@@ -16438,13 +16451,13 @@ var META_TOOLS = {
16438
16451
  },
16439
16452
  secrets: {
16440
16453
  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).",
16454
+ 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
16455
  inputSchema: {
16443
16456
  type: "object",
16444
16457
  properties: {
16445
16458
  server: {
16446
16459
  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.'
16460
+ description: 'Optional: one server namespace (e.g. "gh"). Omit for every server that references a vault secret.'
16448
16461
  }
16449
16462
  }
16450
16463
  },
@@ -16461,30 +16474,30 @@ var META_TOOLS = {
16461
16474
  // Joined rather than one literal so the step cap can be interpolated from
16462
16475
  // MAX_EXEC_STEPS -- the constant validateExecRequest actually enforces.
16463
16476
  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.",
16477
+ "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
16478
  `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."
16479
+ "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
16480
  ].join(" "),
16468
16481
  inputSchema: {
16469
16482
  type: "object",
16470
16483
  properties: {
16471
16484
  steps: {
16472
16485
  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.',
16486
+ description: 'Ordered tool calls, each `{ id?: string, tool: string, args?: object }`. `args` values may be `{"$ref": "<stepId>.path"}`.',
16474
16487
  items: {
16475
16488
  type: "object",
16476
16489
  properties: {
16477
16490
  id: {
16478
16491
  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."
16492
+ description: "Optional name for this step's output, used by later `$ref`s. Defaults to the positional index as a string."
16480
16493
  },
16481
16494
  tool: {
16482
16495
  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.'
16496
+ 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
16497
  },
16485
16498
  args: {
16486
16499
  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.',
16500
+ description: 'Arguments for the tool call. Any value, however nested, may be `{"$ref": "<stepId>[.path]"}` to substitute a prior step\'s output.',
16488
16501
  additionalProperties: true
16489
16502
  }
16490
16503
  },
@@ -16500,7 +16513,7 @@ var META_TOOLS = {
16500
16513
  },
16501
16514
  return: {
16502
16515
  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."
16516
+ 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
16517
  }
16505
16518
  },
16506
16519
  required: ["steps"]
@@ -16514,6 +16527,11 @@ var META_TOOLS = {
16514
16527
  }
16515
16528
  }
16516
16529
  };
16530
+ var LITE_META_TOOL_NAMES = /* @__PURE__ */ new Set([
16531
+ META_TOOLS.exec.name,
16532
+ META_TOOLS.findTool.name,
16533
+ META_TOOLS.read_tool.name
16534
+ ]);
16517
16535
  function computeSecretsReport(servers, vaultKeys) {
16518
16536
  const rows = [];
16519
16537
  for (const server of servers) {
@@ -16741,6 +16759,7 @@ function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, e
16741
16759
  const tools = [];
16742
16760
  const seen = /* @__PURE__ */ new Set();
16743
16761
  for (const meta of Object.values(META_TOOLS)) {
16762
+ if (exposure === "lite" && !LITE_META_TOOL_NAMES.has(meta.name)) continue;
16744
16763
  tools.push({
16745
16764
  name: meta.name,
16746
16765
  description: meta.description,
@@ -16750,7 +16769,7 @@ function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, e
16750
16769
  seen.add(meta.name);
16751
16770
  }
16752
16771
  for (const conn of activeConnections.values()) {
16753
- if (exposure === "gateway" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16772
+ if (exposure !== "full" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16754
16773
  const filter = toolFilters?.get(conn.config.namespace);
16755
16774
  for (const tool of conn.tools) {
16756
16775
  if (filter && !filter.has(tool.name)) continue;
@@ -16771,7 +16790,7 @@ function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, e
16771
16790
  for (const server of inactiveWithCache) {
16772
16791
  if (activeConnections.has(server.namespace)) continue;
16773
16792
  if (!server.toolCache || server.toolCache.length === 0) continue;
16774
- if (exposure === "gateway") continue;
16793
+ if (exposure !== "full") continue;
16775
16794
  const filter = toolFilters?.get(server.namespace);
16776
16795
  for (const cached of server.toolCache) {
16777
16796
  if (filter && !filter.has(cached.name)) continue;
@@ -16843,7 +16862,7 @@ function buildResourceList(activeConnections, builtins = [], exposure = "full",
16843
16862
  seen.add(b.uri);
16844
16863
  }
16845
16864
  for (const conn of activeConnections.values()) {
16846
- if (exposure === "gateway" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16865
+ if (exposure !== "full" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16847
16866
  for (const r of conn.resources) {
16848
16867
  if (seen.has(r.namespacedUri)) continue;
16849
16868
  resources.push({
@@ -16883,7 +16902,7 @@ function buildPromptList(activeConnections, exposure = "full", exposedNamespaces
16883
16902
  const prompts = [];
16884
16903
  const seen = /* @__PURE__ */ new Set();
16885
16904
  for (const conn of activeConnections.values()) {
16886
- if (exposure === "gateway" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16905
+ if (exposure !== "full" && !exposedNamespaces?.has(conn.config.namespace)) continue;
16887
16906
  for (const p of conn.prompts) {
16888
16907
  if (seen.has(p.namespacedName)) continue;
16889
16908
  prompts.push({
@@ -17702,6 +17721,287 @@ async function bestOfNViaSampling(server, intent, candidates, n) {
17702
17721
  }
17703
17722
  }
17704
17723
 
17724
+ // src/secret-entry-page.ts
17725
+ import { spawn as spawn4 } from "child_process";
17726
+ import { randomBytes as randomBytes3, randomUUID, timingSafeEqual as timingSafeEqual2 } from "crypto";
17727
+ import { createServer } from "http";
17728
+ import { win32 as win322 } from "path";
17729
+ var SECRET_ENTRY_PAGE_TTL_MS = 3 * 6e4;
17730
+ var MAX_BODY_BYTES = 16 * 1024;
17731
+ var REPLY_DRAIN_MS = 2e3;
17732
+ var LOOPBACK_HOST = "127.0.0.1";
17733
+ var SECURITY_HEADERS = {
17734
+ "Cache-Control": "no-store",
17735
+ Pragma: "no-cache",
17736
+ "X-Content-Type-Options": "nosniff",
17737
+ "X-Frame-Options": "DENY",
17738
+ "Referrer-Policy": "same-origin",
17739
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
17740
+ Connection: "close"
17741
+ };
17742
+ function escapeHtml(s) {
17743
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
17744
+ }
17745
+ function describeTtl(ms) {
17746
+ if (ms >= 6e4 && ms % 6e4 === 0) {
17747
+ const m = ms / 6e4;
17748
+ return `${m} ${m === 1 ? "minute" : "minutes"}`;
17749
+ }
17750
+ const s = Math.max(1, Math.ceil(ms / 1e3));
17751
+ return `${s} ${s === 1 ? "second" : "seconds"}`;
17752
+ }
17753
+ function htmlDocument(title, body) {
17754
+ return `<!doctype html>
17755
+ <html lang="en">
17756
+ <head>
17757
+ <meta charset="utf-8">
17758
+ <meta name="viewport" content="width=device-width, initial-scale=1">
17759
+ <title>${escapeHtml(title)}</title>
17760
+ <style>
17761
+ :root { color-scheme: light dark; }
17762
+ body { font: 16px/1.5 system-ui, sans-serif; margin: 0; padding: 2rem 1rem; }
17763
+ main { max-width: 32rem; margin: 0 auto; }
17764
+ h1 { font-size: 1.3rem; margin: 0 0 1rem; }
17765
+ label { display: block; font-weight: 600; margin: 1rem 0 .25rem; }
17766
+ input { box-sizing: border-box; width: 100%; font: inherit; padding: .5rem; }
17767
+ button { margin-top: 1.25rem; font: inherit; padding: .5rem 1.25rem; }
17768
+ .err { color: #b00020; font-weight: 600; }
17769
+ .fine { font-size: .9rem; opacity: .75; }
17770
+ </style>
17771
+ </head>
17772
+ <body><main>
17773
+ ${body}
17774
+ </main></body>
17775
+ </html>
17776
+ `;
17777
+ }
17778
+ function browserCommand(url, platform = process.platform, env = process.env) {
17779
+ if (platform === "win32") {
17780
+ const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? env.windir ?? env.WINDIR ?? "C:\\Windows";
17781
+ return { command: win322.join(systemRoot, "System32", "rundll32.exe"), args: ["url.dll,FileProtocolHandler", url] };
17782
+ }
17783
+ if (platform === "darwin") return { command: "/usr/bin/open", args: [url] };
17784
+ if (!env.DISPLAY && !env.WAYLAND_DISPLAY) return null;
17785
+ return { command: "xdg-open", args: [url] };
17786
+ }
17787
+ function openInSystemBrowser(url, spawnLauncher = spawn4) {
17788
+ const launch = browserCommand(url);
17789
+ if (!launch) {
17790
+ log("info", "No graphical session to open the secret entry page in");
17791
+ return Promise.resolve(false);
17792
+ }
17793
+ return new Promise((resolve8) => {
17794
+ let child;
17795
+ try {
17796
+ child = spawnLauncher(launch.command, launch.args, {
17797
+ stdio: "ignore",
17798
+ detached: true,
17799
+ windowsHide: true,
17800
+ env: stripInternalSecretsFromEnv(process.env)
17801
+ });
17802
+ } catch (err) {
17803
+ log("warn", "Could not launch a browser for the secret entry page", {
17804
+ command: launch.command,
17805
+ error: err instanceof Error ? err.message : String(err)
17806
+ });
17807
+ resolve8(false);
17808
+ return;
17809
+ }
17810
+ child.once("spawn", () => {
17811
+ child.unref();
17812
+ resolve8(true);
17813
+ });
17814
+ child.once("error", (err) => {
17815
+ log("warn", "Could not launch a browser for the secret entry page", {
17816
+ command: launch.command,
17817
+ error: err.message
17818
+ });
17819
+ resolve8(false);
17820
+ });
17821
+ });
17822
+ }
17823
+ function openSecretEntryPage(opts) {
17824
+ if (opts.fields.length === 0) return Promise.reject(new Error("a secret entry page needs at least one field"));
17825
+ const ttlMs = opts.ttlMs ?? SECRET_ENTRY_PAGE_TTL_MS;
17826
+ const token = randomBytes3(32).toString("hex");
17827
+ const expectedPath = Buffer.from(`/${token}`, "utf8");
17828
+ const elicitationId = randomUUID();
17829
+ let port = 0;
17830
+ let state = "open";
17831
+ let replying = false;
17832
+ let listenerClosed = false;
17833
+ let expiry;
17834
+ let settle = () => {
17835
+ };
17836
+ const result = new Promise((resolve8) => {
17837
+ settle = resolve8;
17838
+ });
17839
+ const server = createServer((req, res) => handle(req, res));
17840
+ const closeListener = (hard) => {
17841
+ if (!listenerClosed) {
17842
+ listenerClosed = true;
17843
+ server.close();
17844
+ }
17845
+ if (hard) server.closeAllConnections?.();
17846
+ else server.closeIdleConnections?.();
17847
+ };
17848
+ const end = (outcome) => {
17849
+ if (state === "done") return;
17850
+ state = "done";
17851
+ if (expiry) clearTimeout(expiry);
17852
+ closeListener(true);
17853
+ settle(outcome);
17854
+ };
17855
+ const send = (res, status, body, extra = {}, type = "text/html; charset=utf-8") => {
17856
+ res.writeHead(status, { ...SECURITY_HEADERS, "Content-Type": type, ...extra });
17857
+ res.end(body);
17858
+ };
17859
+ const formPage = (error) => {
17860
+ const fields = opts.fields.map(
17861
+ (f, i) => `<label for="f${i}">${escapeHtml(f.label)}</label>
17862
+ <input id="f${i}" name="${escapeHtml(f.name)}" type="password" autocomplete="off" autocapitalize="off" spellcheck="false" required${i === 0 ? " autofocus" : ""}>`
17863
+ ).join("\n");
17864
+ return htmlDocument(
17865
+ opts.title,
17866
+ `<h1>${escapeHtml(opts.title)}</h1>
17867
+ <p>${escapeHtml(opts.intro)}</p>
17868
+ ${error ? `<p class="err">${escapeHtml(error)}</p>
17869
+ ` : ""}<form method="post" autocomplete="off">
17870
+ ${fields}
17871
+ <button type="submit">Submit</button>
17872
+ </form>
17873
+ <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>`
17874
+ );
17875
+ };
17876
+ const gonePage = () => htmlDocument(
17877
+ opts.title,
17878
+ `<h1>This page has expired</h1>
17879
+ <p>It already took a submission, or its time ran out. Return to your MCP client.</p>`
17880
+ );
17881
+ const pathMatches = (path5) => {
17882
+ const got = Buffer.from(path5, "utf8");
17883
+ return got.length === expectedPath.length && timingSafeEqual2(got, expectedPath);
17884
+ };
17885
+ const accept = (values, res) => {
17886
+ state = "done";
17887
+ replying = true;
17888
+ if (expiry) clearTimeout(expiry);
17889
+ closeListener(false);
17890
+ let drained = false;
17891
+ const drain = () => {
17892
+ if (drained) return;
17893
+ drained = true;
17894
+ closeListener(true);
17895
+ };
17896
+ res.once("finish", drain);
17897
+ res.once("close", drain);
17898
+ setTimeout(drain, REPLY_DRAIN_MS).unref?.();
17899
+ send(res, 200, htmlDocument(opts.title, `<h1>Received</h1>
17900
+ <p>${escapeHtml(opts.doneMessage)}</p>`));
17901
+ settle({ kind: "submitted", values });
17902
+ };
17903
+ function handle(req, res) {
17904
+ const host = (req.headers.host ?? "").toLowerCase();
17905
+ if (host !== `${LOOPBACK_HOST}:${port}`) {
17906
+ send(res, 403, "Forbidden\n", {}, "text/plain; charset=utf-8");
17907
+ return;
17908
+ }
17909
+ const rawUrl = req.url ?? "";
17910
+ const q = rawUrl.indexOf("?");
17911
+ if (!pathMatches(q === -1 ? rawUrl : rawUrl.slice(0, q))) {
17912
+ send(res, 404, "Not found\n", {}, "text/plain; charset=utf-8");
17913
+ return;
17914
+ }
17915
+ if (state !== "open") {
17916
+ send(res, 410, gonePage());
17917
+ return;
17918
+ }
17919
+ if (req.method === "GET") {
17920
+ send(res, 200, formPage());
17921
+ return;
17922
+ }
17923
+ if (req.method !== "POST") {
17924
+ send(res, 405, "Method not allowed\n", { Allow: "GET, POST" }, "text/plain; charset=utf-8");
17925
+ return;
17926
+ }
17927
+ const origin = req.headers.origin;
17928
+ if (origin !== void 0 && origin !== `http://${LOOPBACK_HOST}:${port}`) {
17929
+ send(res, 403, "Forbidden\n", {}, "text/plain; charset=utf-8");
17930
+ return;
17931
+ }
17932
+ const contentType = (req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
17933
+ if (contentType !== "application/x-www-form-urlencoded") {
17934
+ send(res, 415, "Unsupported media type\n", {}, "text/plain; charset=utf-8");
17935
+ return;
17936
+ }
17937
+ const chunks = [];
17938
+ let size = 0;
17939
+ let tooLarge = false;
17940
+ req.on("data", (chunk) => {
17941
+ if (tooLarge) return;
17942
+ size += chunk.length;
17943
+ if (size > MAX_BODY_BYTES) {
17944
+ tooLarge = true;
17945
+ chunks.length = 0;
17946
+ return;
17947
+ }
17948
+ chunks.push(chunk);
17949
+ });
17950
+ req.on("error", () => {
17951
+ });
17952
+ req.on("end", () => {
17953
+ if (tooLarge) {
17954
+ send(res, 413, "Payload too large\n", {}, "text/plain; charset=utf-8");
17955
+ return;
17956
+ }
17957
+ if (state !== "open") {
17958
+ chunks.length = 0;
17959
+ send(res, 410, gonePage());
17960
+ return;
17961
+ }
17962
+ const params = new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
17963
+ chunks.length = 0;
17964
+ const values = {};
17965
+ for (const field of opts.fields) {
17966
+ const value = params.get(field.name);
17967
+ if (value === null || value.length === 0) {
17968
+ send(res, 400, formPage("Every field is required."));
17969
+ return;
17970
+ }
17971
+ values[field.name] = value;
17972
+ }
17973
+ accept(values, res);
17974
+ });
17975
+ }
17976
+ const close = () => {
17977
+ if (state === "open") {
17978
+ end({ kind: "closed" });
17979
+ return;
17980
+ }
17981
+ if (!replying) closeListener(true);
17982
+ };
17983
+ return new Promise((resolve8, reject) => {
17984
+ const onListenError = (err) => {
17985
+ state = "done";
17986
+ reject(err);
17987
+ };
17988
+ server.once("error", onListenError);
17989
+ server.listen({ host: LOOPBACK_HOST, port: 0 }, () => {
17990
+ server.removeListener("error", onListenError);
17991
+ server.on("error", (err) => {
17992
+ log("warn", "Secret entry page listener failed; closing it", { port, error: err.message });
17993
+ end({ kind: "closed" });
17994
+ });
17995
+ port = server.address().port;
17996
+ server.unref?.();
17997
+ expiry = setTimeout(() => end({ kind: "expired" }), ttlMs);
17998
+ expiry.unref?.();
17999
+ log("info", "Secret entry page listening", { port, ttlMs });
18000
+ resolve8({ url: `http://${LOOPBACK_HOST}:${port}/${token}`, elicitationId, result, close });
18001
+ });
18002
+ });
18003
+ }
18004
+
17705
18005
  // src/server-cap.ts
17706
18006
  var DEFAULT_SERVER_CAP = 6;
17707
18007
  function resolveServerCap(env = process.env) {
@@ -17773,22 +18073,26 @@ function isAutoLoadEnabled() {
17773
18073
  return raw === "1" || raw.toLowerCase() === "true";
17774
18074
  }
17775
18075
  function isPrewarmEnabled() {
17776
- const raw = process.env.YAW_MCP_PREWARM?.trim().toLowerCase();
17777
- return !(raw === "0" || raw === "false");
18076
+ return !isFeatureDisabled("YAW_MCP_PREWARM");
17778
18077
  }
17779
18078
  var exposureWarnedFor = null;
17780
- function resolveToolExposure() {
18079
+ var LITE_BY_DEFAULT_CLIENTS = /* @__PURE__ */ new Set(["typed-cli"]);
18080
+ function resolveToolExposure(clientInfo) {
18081
+ const fallback = clientInfo?.name !== void 0 && LITE_BY_DEFAULT_CLIENTS.has(clientInfo.name) ? "lite" : "gateway";
17781
18082
  const raw = process.env.YAW_MCP_TOOL_EXPOSURE?.trim().toLowerCase();
17782
18083
  if (raw === "full") return "full";
17783
- if (raw === void 0 || raw === "" || raw === "gateway") return "gateway";
18084
+ if (raw === "lite") return "lite";
18085
+ if (raw === "gateway") return "gateway";
18086
+ if (raw === void 0 || raw === "") return fallback;
17784
18087
  if (exposureWarnedFor !== raw) {
17785
18088
  exposureWarnedFor = raw;
17786
- log("warn", `unrecognized YAW_MCP_TOOL_EXPOSURE "${raw}"; using "gateway"`, { raw });
18089
+ log("warn", `unrecognized YAW_MCP_TOOL_EXPOSURE "${raw}"; using "${fallback}"`, { raw });
17787
18090
  }
17788
- return "gateway";
18091
+ return fallback;
17789
18092
  }
17790
18093
  var DEFAULT_IDLE_CALL_THRESHOLD = 10;
17791
18094
  var MAX_VAULT_PASSPHRASE_PROMPTS = 2;
18095
+ var VAULT_PAGE_FIELD = "passphrase";
17792
18096
  var MAX_CREDENTIAL_PROMPTS = 2;
17793
18097
  var EXEC_ECHO_BUDGET_BYTES = 4096;
17794
18098
  var idleThresholdClampWarnedFor = null;
@@ -18045,6 +18349,17 @@ var ConnectServer = class _ConnectServer {
18045
18349
  // MAX_VAULT_PASSPHRASE_PROMPTS budget in a single round. Followers await
18046
18350
  // this instead of prompting. Cleared when the prompt settles.
18047
18351
  vaultElicitInflight = null;
18352
+ // Masked-entry pages currently listening (see collectSecretOnLoopbackPage).
18353
+ // Tracked so shutdown() can close them: a listener keeps the process alive
18354
+ // under oam, whose http.Server has no unref().
18355
+ secretEntryPages = /* @__PURE__ */ new Set();
18356
+ // The page opener, the browser launcher and the page TTL. Instance fields
18357
+ // (not direct calls) purely so tests can substitute a fake page and a fake
18358
+ // browser, the same reason activationRetryDelayMs is one; production never
18359
+ // changes them.
18360
+ openSecretPage = openSecretEntryPage;
18361
+ openBrowser = openInSystemBrowser;
18362
+ secretEntryPageTtlMs = SECRET_ENTRY_PAGE_TTL_MS;
18048
18363
  // How many times we have asked for a given NAMESPACE's missing child
18049
18364
  // credentials. Per-namespace (unlike the vault counter) because these are
18050
18365
  // the child's own secrets. Bounds the re-ask that replaced the old
@@ -18159,13 +18474,19 @@ var ConnectServer = class _ConnectServer {
18159
18474
  static SHUTDOWN_DRAIN_MS = 2e3;
18160
18475
  constructor() {
18161
18476
  this.server = new Server(
18162
- { name: "yaw-mcp", version: true ? "1.0.9" : "dev" },
18477
+ { name: "yaw-mcp", version: true ? "1.0.11" : "dev" },
18163
18478
  {
18164
18479
  capabilities: {
18165
18480
  tools: { listChanged: true },
18166
18481
  resources: { listChanged: true },
18167
18482
  prompts: { listChanged: true }
18168
- }
18483
+ },
18484
+ // Returned once, in the initialize result, and injected by Claude
18485
+ // Code into the system prompt as a "# MCP Server Instructions"
18486
+ // block. This is where the routing prose the meta-tool descriptions
18487
+ // used to repeat now lives -- a description is paid on every
18488
+ // tools/list, this is paid once. See SERVER_INSTRUCTIONS.
18489
+ instructions: SERVER_INSTRUCTIONS
18169
18490
  }
18170
18491
  );
18171
18492
  this.clientBridge = {
@@ -18203,13 +18524,23 @@ var ConnectServer = class _ConnectServer {
18203
18524
  for (const b of this.getBuiltinResources()) map.set(b.uri, b);
18204
18525
  return map;
18205
18526
  }
18527
+ /** The exposure THIS session's lists are served at: the env when set,
18528
+ * else the default for the connected client (lite for typed-cli, gateway
18529
+ * otherwise -- see resolveToolExposure). The one place the client's
18530
+ * identity is read, so the three list handlers and discover's "in
18531
+ * context" summary cannot disagree about which surface they describe.
18532
+ * getClientVersion() is the SDK's copy of the initialize request's
18533
+ * clientInfo and is undefined before the handshake. */
18534
+ currentExposure() {
18535
+ return resolveToolExposure(this.server.getClientVersion());
18536
+ }
18206
18537
  setupHandlers() {
18207
18538
  this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
18208
18539
  tools: buildToolList(
18209
18540
  this.connections,
18210
18541
  this.getDeferredServers(),
18211
18542
  this.toolFilters,
18212
- resolveToolExposure(),
18543
+ this.currentExposure(),
18213
18544
  this.sessionActivated,
18214
18545
  // Hidden here, refused at the gate, but still ROUTED: dropping the
18215
18546
  // route instead would make a call by name return `Unknown tool`,
@@ -18226,7 +18557,7 @@ var ConnectServer = class _ConnectServer {
18226
18557
  resources: buildResourceList(
18227
18558
  this.connections,
18228
18559
  this.getBuiltinResources(),
18229
- resolveToolExposure(),
18560
+ this.currentExposure(),
18230
18561
  this.sessionActivated
18231
18562
  )
18232
18563
  }));
@@ -18237,7 +18568,7 @@ var ConnectServer = class _ConnectServer {
18237
18568
  return routeResourceRead(request2.params.uri, this.resourceRoutes, this.connections, this.getBuiltinResourceMap());
18238
18569
  });
18239
18570
  this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
18240
- prompts: buildPromptList(this.connections, resolveToolExposure(), this.sessionActivated)
18571
+ prompts: buildPromptList(this.connections, this.currentExposure(), this.sessionActivated)
18241
18572
  }));
18242
18573
  this.server.setRequestHandler(GetPromptRequestSchema, async (request2) => {
18243
18574
  return routePromptGet(
@@ -18525,8 +18856,7 @@ var ConnectServer = class _ConnectServer {
18525
18856
  * running config exactly as it was -- someone saving a broken JSON must not
18526
18857
  * cost them the servers they already have loaded. */
18527
18858
  async maybeReloadBundles() {
18528
- const reloadOptOut = process.env.YAW_MCP_CONFIG_RELOAD;
18529
- if (reloadOptOut === "0" || reloadOptOut?.toLowerCase() === "false") return;
18859
+ if (isFeatureDisabled("YAW_MCP_CONFIG_RELOAD")) return;
18530
18860
  if (this.shuttingDown) return;
18531
18861
  if (this.bundlesConsultedPaths.length === 0) return;
18532
18862
  const fingerprint = bundlesSignature(this.bundlesConsultedPaths);
@@ -18772,7 +19102,6 @@ var ConnectServer = class _ConnectServer {
18772
19102
  await this.server.connect(transport);
18773
19103
  maybeAutoUpgrade().catch((err) => log("warn", "Auto-upgrade check failed", { error: err?.message }));
18774
19104
  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
19105
  maybeHealStaleBrokerEntries().catch(
18777
19106
  (err) => log("warn", "Stale-entry heal failed", { error: err?.message })
18778
19107
  );
@@ -19609,7 +19938,7 @@ var ConnectServer = class _ConnectServer {
19609
19938
  }
19610
19939
  lines.push("");
19611
19940
  }
19612
- const exposure = resolveToolExposure();
19941
+ const exposure = this.currentExposure();
19613
19942
  const isAdvertised = (namespace) => exposure === "full" || this.sessionActivated.has(namespace);
19614
19943
  let omittedToolNames = false;
19615
19944
  let totalContextTokens = 0;
@@ -20300,8 +20629,15 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20300
20629
  // the retry hinges on a process-wide session value instead of a per-server
20301
20630
  // override.
20302
20631
  //
20632
+ // WHERE the passphrase is typed: never into the client's own dialog. A
20633
+ // form-mode elicitation field is an ordinary visible text input -- the
20634
+ // passphrase used to sit on screen, in plain text, while it was typed --
20635
+ // and the spec forbids form mode for secrets anyway. It is typed into a
20636
+ // masked field on a one-shot page this process serves on 127.0.0.1; see
20637
+ // collectSecretOnLoopbackPage for how the user gets there.
20638
+ //
20303
20639
  // 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
20640
+ // is typed by a human into a masked field: a single transposed character
20305
20641
  // otherwise cost the entire session. Each entry is VERIFIED against the
20306
20642
  // vault before it is stored (see verifyVaultPassphrase), so a wrong one is
20307
20643
  // rejected without ever becoming the session passphrase, and the user gets
@@ -20317,15 +20653,21 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20317
20653
  const joined = this.vaultElicitInflight;
20318
20654
  if (joined) {
20319
20655
  progress?.("Waiting for the vault passphrase prompt already in flight");
20320
- const outcome2 = await joined;
20321
- if (outcome2 === "unlocked") return this.runActivateOne(
20656
+ const outcome2 = await withHeartbeat(
20657
+ progress,
20658
+ (elapsed) => `Still waiting on the vault passphrase prompt already in flight -- ${elapsed}s so far`,
20659
+ () => joined
20660
+ );
20661
+ if (this.shuttingDown) return this.shuttingDownRefusal(namespace);
20662
+ if (outcome2.kind === "unlocked") return this.runActivateOne(
20322
20663
  namespace,
20323
20664
  progress,
20324
20665
  fromPrewarm,
20325
20666
  /* skipCap */
20326
20667
  true
20327
20668
  );
20328
- if (outcome2 === "rejected") return this.vaultPassphraseRejected(namespace, lastError);
20669
+ if (outcome2.kind === "rejected") return this.vaultPassphraseRejected(namespace, lastError);
20670
+ if (outcome2.kind === "unreachable") return this.vaultPassphraseUnreachable(namespace, lastError, outcome2.reason);
20329
20671
  return null;
20330
20672
  }
20331
20673
  if (this.vaultPassphraseElicited) return null;
@@ -20346,7 +20688,8 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20346
20688
  } finally {
20347
20689
  if (this.vaultElicitInflight === prompt) this.vaultElicitInflight = null;
20348
20690
  }
20349
- if (outcome === "unlocked") {
20691
+ if (this.shuttingDown) return this.shuttingDownRefusal(namespace);
20692
+ if (outcome.kind === "unlocked") {
20350
20693
  progress?.("Got the passphrase -- retrying load");
20351
20694
  return this.runActivateOne(
20352
20695
  namespace,
@@ -20356,7 +20699,8 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20356
20699
  true
20357
20700
  );
20358
20701
  }
20359
- if (outcome === "rejected") return this.vaultPassphraseRejected(namespace, lastError);
20702
+ if (outcome.kind === "rejected") return this.vaultPassphraseRejected(namespace, lastError);
20703
+ if (outcome.kind === "unreachable") return this.vaultPassphraseUnreachable(namespace, lastError, outcome.reason);
20360
20704
  return null;
20361
20705
  }
20362
20706
  // The result for a vault passphrase the user typed that did not verify.
@@ -20375,59 +20719,174 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20375
20719
  message: `Could not load "${namespace}": the passphrase entered does not unlock your local secret vault, which its env (${lastError.refKeys.join(", ")}) references.${retryHint}`
20376
20720
  };
20377
20721
  }
20722
+ // The result for a prompt whose masked-entry page never took a passphrase.
20723
+ // Shared by the winner and its followers, like vaultPassphraseRejected, and
20724
+ // for the same reason it skips runActivateOne's give-up path: nothing is
20725
+ // wrong with the server, and the original "vault locked" text would not
20726
+ // tell a user who said yes to the prompt that there was then nowhere to
20727
+ // type. The retry hint reads the latch, which promptForVaultPassphrase sets
20728
+ // for the two failures another prompt cannot fix (no page, no browser).
20729
+ vaultPassphraseUnreachable(namespace, lastError, reason) {
20730
+ 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";
20731
+ 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.`;
20732
+ return {
20733
+ ok: false,
20734
+ isChanged: false,
20735
+ message: `Could not load "${namespace}": ${what}, so your local secret vault, which its env (${lastError.refKeys.join(", ")}) references, is still locked.${retryHint}`
20736
+ };
20737
+ }
20738
+ // Collect secret values WITHOUT them ever being typed into the client's
20739
+ // own dialog. They are typed into masked fields on a one-shot page this
20740
+ // process serves on 127.0.0.1 (secret-entry-page.ts, which carries the
20741
+ // page's hardening), and the client is only told how to get the user
20742
+ // there:
20743
+ //
20744
+ // * URL mode, when the client declares it (capabilities.elicitation.url).
20745
+ // It is what the spec (2025-11-25) requires for secrets: servers MUST
20746
+ // NOT use form mode for passwords or tokens, and MUST use URL mode. The
20747
+ // client shows the link, asks, and opens it. Its "accept" means the
20748
+ // user consented, NOT that anything was submitted, so the page's own
20749
+ // result is what this waits on.
20750
+ // * Form mode, when that is all the client has. Claude Code (2.1.278, the
20751
+ // build checked) declares `elicitation: {}`, which the spec and the SDK
20752
+ // read as form only -- and its own client refuses a url-mode request
20753
+ // against that declaration, so url mode cannot be tried on it. The form
20754
+ // carries NO field -- it is a yes/no consent, which that build renders
20755
+ // with Accept focused -- and on a yes this process opens the page in
20756
+ // the system browser itself. A visible field is never the fallback:
20757
+ // that is exactly the exposure this replaces.
20758
+ //
20759
+ // Nothing here is vault-specific. The missing-credential prompt
20760
+ // (maybeElicitAndRetry, which still asks in a visible form field) can move
20761
+ // onto it by supplying its own words and fields.
20762
+ async collectSecretOnLoopbackPage(request2) {
20763
+ const { namespace, why, secretNoun, progress } = request2;
20764
+ const modes = getSupportedElicitationModes(this.server.getClientCapabilities()?.elicitation);
20765
+ if (!modes.supportsUrlMode && !modes.supportsFormMode) return { kind: "failed" };
20766
+ const mode = modes.supportsUrlMode ? "url" : "form";
20767
+ let page;
20768
+ try {
20769
+ page = await this.openSecretPage({ ...request2.page, ttlMs: this.secretEntryPageTtlMs });
20770
+ } catch (err) {
20771
+ log("warn", "Could not start the secret entry page", {
20772
+ namespace,
20773
+ error: err instanceof Error ? err.message : String(err)
20774
+ });
20775
+ return { kind: "unreachable", reason: "no-page" };
20776
+ }
20777
+ const openedAt = Date.now();
20778
+ this.secretEntryPages.add(page);
20779
+ try {
20780
+ if (this.shuttingDown) return { kind: "failed" };
20781
+ let result;
20782
+ try {
20783
+ result = mode === "url" ? await this.server.elicitInput({
20784
+ mode: "url",
20785
+ 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.`,
20786
+ elicitationId: page.elicitationId,
20787
+ url: page.url
20788
+ }) : await this.server.elicitInput({
20789
+ 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.`,
20790
+ requestedSchema: { type: "object", properties: {} }
20791
+ });
20792
+ } catch (err) {
20793
+ log("warn", "Secret entry elicitation failed", {
20794
+ namespace,
20795
+ mode,
20796
+ error: err instanceof Error ? err.message : String(err)
20797
+ });
20798
+ return { kind: "failed" };
20799
+ }
20800
+ if (result.action !== "accept") {
20801
+ log("info", "User declined the secret entry prompt", { namespace, mode, action: result.action });
20802
+ return { kind: "declined" };
20803
+ }
20804
+ if (this.shuttingDown) return { kind: "failed" };
20805
+ if (mode === "form" && !await this.openBrowser(page.url)) return { kind: "unreachable", reason: "no-browser" };
20806
+ progress?.("Waiting for the masked entry page in your browser");
20807
+ const outcome = await withHeartbeat(
20808
+ progress,
20809
+ (elapsed) => {
20810
+ const left = Math.max(0, Math.round((openedAt + this.secretEntryPageTtlMs - Date.now()) / 1e3));
20811
+ return `Still waiting for the masked entry page -- ${elapsed}s so far, ${left}s before it expires`;
20812
+ },
20813
+ () => page.result
20814
+ );
20815
+ if (mode === "url" && outcome.kind !== "closed") this.notifyElicitationComplete(page.elicitationId, namespace);
20816
+ if (outcome.kind === "submitted") return { kind: "submitted", values: outcome.values };
20817
+ if (outcome.kind === "expired") return { kind: "unreachable", reason: "expired" };
20818
+ return { kind: "failed" };
20819
+ } finally {
20820
+ page.close();
20821
+ this.secretEntryPages.delete(page);
20822
+ }
20823
+ }
20824
+ // notifications/elicitation/complete for a URL-mode elicitation. Best
20825
+ // effort and never awaited: the notification is a courtesy the spec lets a
20826
+ // server skip (MAY), so a client that errors on it must not fail the unlock.
20827
+ notifyElicitationComplete(elicitationId, namespace) {
20828
+ const onError = (err) => {
20829
+ log("debug", "Could not send the elicitation completion notification", {
20830
+ namespace,
20831
+ error: err instanceof Error ? err.message : String(err)
20832
+ });
20833
+ };
20834
+ try {
20835
+ this.server.createElicitationCompletionNotifier(elicitationId)().catch(onError);
20836
+ } catch (err) {
20837
+ onError(err);
20838
+ }
20839
+ }
20378
20840
  // The prompt half of the vault path, split out so concurrent callers can
20379
20841
  // await ONE of them (see vaultElicitInflight). Owns the ask budget, the
20380
20842
  // 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.
20843
+ // which of these happened, because they need different words:
20844
+ // unlocked -- verified and stored; retry the activation.
20845
+ // rejected -- the user typed a passphrase and it did not verify.
20846
+ // unavailable -- declined, empty, or the elicitation request failed.
20847
+ // unreachable -- the masked-entry page never took a passphrase.
20385
20848
  async promptForVaultPassphrase(namespace, lastError, progress) {
20386
20849
  this.vaultPassphrasePrompts++;
20387
20850
  if (this.vaultPassphrasePrompts >= MAX_VAULT_PASSPHRASE_PROMPTS) this.vaultPassphraseElicited = true;
20388
20851
  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) {
20852
+ const invalid = lastError.reason === "invalid";
20853
+ const keys = lastError.refKeys.join(", ");
20854
+ 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.`;
20855
+ 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.";
20856
+ const entry = await this.collectSecretOnLoopbackPage({
20857
+ namespace,
20858
+ why,
20859
+ secretNoun: invalid ? "the correct vault passphrase" : "your vault passphrase",
20860
+ page: {
20861
+ title: "Unlock your yaw-mcp secret vault",
20862
+ 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}`,
20863
+ fields: [{ name: VAULT_PAGE_FIELD, label: "Vault passphrase" }],
20864
+ doneMessage: "Received. You can close this tab and return to your MCP client."
20865
+ },
20866
+ progress
20867
+ });
20868
+ if (entry.kind === "failed") return { kind: "unavailable" };
20869
+ if (entry.kind === "declined") {
20414
20870
  this.vaultPassphraseElicited = true;
20415
- log("info", "User declined vault passphrase elicitation", { namespace, action: result.action });
20416
- return "unavailable";
20871
+ return { kind: "unavailable" };
20872
+ }
20873
+ if (entry.kind === "unreachable") {
20874
+ if (entry.reason !== "expired") this.vaultPassphraseElicited = true;
20875
+ return { kind: "unreachable", reason: entry.reason };
20417
20876
  }
20418
- const value = result.content.YAW_MCP_VAULT_PASSPHRASE;
20419
- if (typeof value !== "string" || value.length === 0) return "unavailable";
20877
+ const value = entry.values[VAULT_PAGE_FIELD];
20878
+ if (typeof value !== "string" || value.length === 0) return { kind: "unavailable" };
20420
20879
  if (!await verifyVaultPassphrase(value)) {
20421
20880
  log("info", "Elicited vault passphrase did not unlock the vault", {
20422
20881
  namespace,
20423
20882
  attempt: this.vaultPassphrasePrompts
20424
20883
  });
20425
20884
  progress?.("That passphrase did not unlock the vault");
20426
- return "rejected";
20885
+ return { kind: "rejected" };
20427
20886
  }
20428
20887
  setSessionVaultPassphrase(value);
20429
20888
  this.vaultPassphraseElicited = true;
20430
- return "unlocked";
20889
+ return { kind: "unlocked" };
20431
20890
  }
20432
20891
  async handleActivate(namespaces, progress, toolsFilter) {
20433
20892
  if (namespaces.length === 0) {
@@ -21492,6 +21951,7 @@ To load the top pack in one step, call \`mcp_connect_activate\` with namespaces=
21492
21951
  async shutdown() {
21493
21952
  log("info", "Shutting down yaw-mcp");
21494
21953
  this.shuttingDown = true;
21954
+ for (const page of this.secretEntryPages) page.close();
21495
21955
  if (this.stateSaveTimer) {
21496
21956
  clearTimeout(this.stateSaveTimer);
21497
21957
  this.stateSaveTimer = null;
@@ -21566,7 +22026,7 @@ function registerShutdownTriggers(shutdown, targets) {
21566
22026
  // src/status-cmd.ts
21567
22027
  import { existsSync as existsSync10 } from "fs";
21568
22028
  import { homedir as homedir23 } from "os";
21569
- var VERSION2 = true ? "1.0.9" : "dev";
22029
+ var VERSION2 = true ? "1.0.11" : "dev";
21570
22030
  var STATUS_SCHEMA_VERSION = 1;
21571
22031
  var STATUS_USAGE = `Usage: yaw-mcp status [--json]
21572
22032
 
@@ -22133,10 +22593,14 @@ if (subcommand === "compliance") {
22133
22593
  \`0\` disables).
22134
22594
  YAW_MCP_TOOL_EXPOSURE How much of the catalog tools/list advertises.
22135
22595
  \`gateway\` (default) exposes the meta-tools
22136
- plus loaded servers only; \`full\` restores the
22596
+ plus loaded servers only; \`lite\` (the default
22597
+ when the client is typed-cli) exposes only
22598
+ mcp_connect_exec / find_tool / read_tool plus
22599
+ loaded servers; \`full\` restores the
22137
22600
  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.
22601
+ catalog. Set, it wins over the client default.
22602
+ Re-read per call -- a change lands on the next
22603
+ tools/list without a restart.
22140
22604
  YAW_MCP_ROUTE_EFFORT How hard dispatch tries to break ranking ties
22141
22605
  with the client LLM: \`off\` | \`auto\` |
22142
22606
  \`aggressive\` (default auto). The dispatch
@@ -22226,10 +22690,11 @@ if (subcommand === "compliance") {
22226
22690
  (\`oam.exe\` on Windows).
22227
22691
  OAM_MAX_HEAP_MB Read by oam, not by yaw-mcp: raises the V8
22228
22692
  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"\`.
22693
+ by default; can be lower inside a memory-limited
22694
+ Linux container). Set it in that server's \`env\`
22695
+ in bundles.json when a hosted sidecar dies with a
22696
+ heap out-of-memory error, or give that server
22697
+ \`"runtime": "node"\`.
22233
22698
  MCP_CONNECT_TIMEOUT Milliseconds to wait for a server's MCP
22234
22699
  handshake (default 15000). This is the FALLBACK
22235
22700
  only -- a server's own \`connectTimeoutMs\` in
@@ -22340,7 +22805,7 @@ if (subcommand === "compliance") {
22340
22805
  `);
22341
22806
  process.exitCode = 0;
22342
22807
  } else if (subcommand === "--version" || subcommand === "-V") {
22343
- process.stdout.write(`yaw-mcp ${true ? "1.0.9" : "dev"}
22808
+ process.stdout.write(`yaw-mcp ${true ? "1.0.11" : "dev"}
22344
22809
  `);
22345
22810
  process.exitCode = 0;
22346
22811
  } else if (subcommand !== void 0 && !subcommand.startsWith("-")) {