@yawlabs/mcp 1.1.7 → 1.1.8

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
@@ -127,7 +127,7 @@ import {
127
127
  userConfigDir,
128
128
  withFileLock,
129
129
  yawModeOverlay
130
- } from "./chunk-TI26KSBV.js";
130
+ } from "./chunk-7C5YSE4J.js";
131
131
 
132
132
  // src/audit-cmd.ts
133
133
  import { homedir as homedir6 } from "os";
@@ -3364,7 +3364,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
3364
3364
  if (downstreamCaps?.sampling) capabilities.sampling = downstreamCaps.sampling;
3365
3365
  if (downstreamCaps?.roots) capabilities.roots = {};
3366
3366
  const client = new Client(
3367
- { name: "yaw-mcp", version: true ? "1.1.7" : "dev" },
3367
+ { name: "yaw-mcp", version: true ? "1.1.8" : "dev" },
3368
3368
  { capabilities }
3369
3369
  );
3370
3370
  if (bridge && capabilities.elicitation) {
@@ -4708,15 +4708,15 @@ function renderList(print) {
4708
4708
  print("");
4709
4709
  const byCategory = /* @__PURE__ */ new Map();
4710
4710
  for (const b of CURATED_BUNDLES) {
4711
- const list = byCategory.get(b.category) ?? [];
4712
- list.push(b);
4713
- byCategory.set(b.category, list);
4711
+ const list2 = byCategory.get(b.category) ?? [];
4712
+ list2.push(b);
4713
+ byCategory.set(b.category, list2);
4714
4714
  }
4715
4715
  const categories = [...byCategory.keys()].sort();
4716
4716
  for (const cat of categories) {
4717
- const list = (byCategory.get(cat) ?? []).slice().sort((a, b) => a.id.localeCompare(b.id));
4717
+ const list2 = (byCategory.get(cat) ?? []).slice().sort((a, b) => a.id.localeCompare(b.id));
4718
4718
  print(` [${cat}]`);
4719
- for (const b of list) {
4719
+ for (const b of list2) {
4720
4720
  print(` ${b.id.padEnd(18)} ${b.name}`);
4721
4721
  print(` ${b.description}`);
4722
4722
  print(` -> ${bundleActivateHint(b)}`);
@@ -6594,9 +6594,9 @@ function cliToNamespaces() {
6594
6594
  const map = /* @__PURE__ */ new Map();
6595
6595
  for (const [namespace, shadows] of Object.entries(NAMESPACE_REGISTRY)) {
6596
6596
  for (const s of shadows) {
6597
- const list = map.get(s.cli) ?? [];
6598
- list.push(namespace);
6599
- map.set(s.cli, list);
6597
+ const list2 = map.get(s.cli) ?? [];
6598
+ list2.push(namespace);
6599
+ map.set(s.cli, list2);
6600
6600
  }
6601
6601
  }
6602
6602
  reverseIndexCache = map;
@@ -10784,7 +10784,7 @@ function foldBundleWarnings(warnings, probe) {
10784
10784
  const prefix = `${probe.path}:`;
10785
10785
  return warnings.filter((w) => !w.startsWith(prefix));
10786
10786
  }
10787
- var VERSION = true ? "1.1.7" : "dev";
10787
+ var VERSION = true ? "1.1.8" : "dev";
10788
10788
  var DOCTOR_USAGE = `Usage: yaw-mcp doctor [--json]
10789
10789
 
10790
10790
  Print a diagnostic of your yaw-mcp setup.
@@ -12582,6 +12582,92 @@ var SUB_FLOOR_STOPWORDS = /* @__PURE__ */ new Set([
12582
12582
  function tokenizeQuery(text) {
12583
12583
  return tokenizeIdent(text).filter((t) => t.length >= MIN_TOKEN_LEN || !SUB_FLOOR_STOPWORDS.has(t));
12584
12584
  }
12585
+ var ABBREVIATIONS = {
12586
+ pr: ["pull", "request"],
12587
+ prs: ["pull", "request"],
12588
+ k8s: ["kubernetes"],
12589
+ repo: ["repository"],
12590
+ repos: ["repository"],
12591
+ db: ["database"],
12592
+ dbs: ["database"],
12593
+ gh: ["github"],
12594
+ pkg: ["package"],
12595
+ pkgs: ["package"],
12596
+ dep: ["dependency"],
12597
+ deps: ["dependency"],
12598
+ dir: ["directory"],
12599
+ dirs: ["directory"],
12600
+ doc: ["documentation"],
12601
+ docs: ["documentation"],
12602
+ config: ["configuration"],
12603
+ configs: ["configuration"],
12604
+ cfg: ["configuration"],
12605
+ auth: ["authentication"],
12606
+ env: ["environment"],
12607
+ envs: ["environment"],
12608
+ cred: ["credential"],
12609
+ creds: ["credential"],
12610
+ cert: ["certificate"],
12611
+ certs: ["certificate"],
12612
+ msg: ["message"],
12613
+ msgs: ["message"],
12614
+ img: ["image"],
12615
+ imgs: ["image"],
12616
+ param: ["parameter"],
12617
+ params: ["parameter"],
12618
+ arg: ["argument"],
12619
+ args: ["argument"],
12620
+ info: ["information"],
12621
+ perf: ["performance"],
12622
+ stats: ["statistic"],
12623
+ prod: ["production"],
12624
+ mgmt: ["management"],
12625
+ txn: ["transaction"],
12626
+ js: ["javascript"],
12627
+ ts: ["typescript"],
12628
+ py: ["python"]
12629
+ };
12630
+ var STEM_EXCEPTIONS = /* @__PURE__ */ new Set(["news", "series", "species", "always", "perhaps"]);
12631
+ var VOWEL = /[aeiouy]/;
12632
+ function undouble(s) {
12633
+ const n = s.length;
12634
+ return n >= 4 && s[n - 1] === s[n - 2] && !/[aeiouylsz]/.test(s[n - 1]) ? s.slice(0, -1) : s;
12635
+ }
12636
+ function isShortCvc(s) {
12637
+ return s.length === 3 && !VOWEL.test(s[0]) && VOWEL.test(s[1]) && !VOWEL.test(s[2]);
12638
+ }
12639
+ function restoreE(stem) {
12640
+ const u = undouble(stem);
12641
+ if (u !== stem) return u;
12642
+ return isShortCvc(stem) && !/[wxy]$/.test(stem) ? `${stem}e` : stem;
12643
+ }
12644
+ function normalizeTerm(token) {
12645
+ if (token.length <= 3 || /\d/.test(token) || STEM_EXCEPTIONS.has(token)) return token;
12646
+ let s = token;
12647
+ if (s.endsWith("ies") && s.length > 4) s = `${s.slice(0, -3)}y`;
12648
+ else if (s.endsWith("sses")) s = s.slice(0, -2);
12649
+ else if (/(?:x|z|ch|sh)es$/.test(s)) s = s.slice(0, -2);
12650
+ else if (s.endsWith("s") && !/(?:ss|us|is)$/.test(s)) s = s.slice(0, -1);
12651
+ if (s.endsWith("ied") && s.length > 4) s = `${s.slice(0, -3)}y`;
12652
+ else if (s.endsWith("ing") && s.length >= 6 && VOWEL.test(s.slice(0, -3))) s = restoreE(s.slice(0, -3));
12653
+ else if (s.endsWith("ed") && !s.endsWith("eed") && s.length >= 5 && VOWEL.test(s.slice(0, -2))) {
12654
+ const stem = s.slice(0, -2);
12655
+ if (stem.length > 3 || isShortCvc(stem)) s = restoreE(stem);
12656
+ }
12657
+ if (s.endsWith("ability") && s.length >= 9) s = s.slice(0, -7);
12658
+ else if (s.endsWith("able") && s.length >= 7) s = s.slice(0, -4);
12659
+ if (s.endsWith("e") && s.length >= 5) s = s.slice(0, -1);
12660
+ return s.length >= 3 ? s : token;
12661
+ }
12662
+ function normalizeTokens(tokens) {
12663
+ const out = [];
12664
+ for (const t of tokens) {
12665
+ const expanded = ABBREVIATIONS[t];
12666
+ if (expanded) for (const e of expanded) out.push(normalizeTerm(e));
12667
+ else out.push(normalizeTerm(t));
12668
+ }
12669
+ return out;
12670
+ }
12585
12671
  function emptyField() {
12586
12672
  return { len: 0, counts: /* @__PURE__ */ new Map() };
12587
12673
  }
@@ -12592,19 +12678,28 @@ function addTokens(field, tokens) {
12592
12678
  field.len += tokens.length;
12593
12679
  return field;
12594
12680
  }
12595
- function buildDocFields(server) {
12681
+ function buildDoc(server) {
12596
12682
  const toolName = emptyField();
12597
12683
  const toolDescription = emptyField();
12684
+ const tools = [];
12598
12685
  for (const tool of server.tools) {
12599
- addTokens(toolName, tokenizeIdent(tool.name));
12600
- addTokens(toolDescription, tokenize(tool.description));
12686
+ const nameList = normalizeTokens(tokenizeIdent(tool.name));
12687
+ const descList = normalizeTokens(tokenize(tool.description));
12688
+ addTokens(toolName, nameList);
12689
+ addTokens(toolDescription, descList);
12690
+ tools.push({ name: new Set(nameList), nameList, desc: new Set(descList) });
12601
12691
  }
12692
+ const namespaceTerms = normalizeTokens(tokenizeIdent(server.namespace));
12602
12693
  return {
12603
- namespace: addTokens(emptyField(), tokenizeIdent(server.namespace)),
12604
- name: addTokens(emptyField(), tokenizeIdent(server.name)),
12605
- description: addTokens(emptyField(), tokenize(server.description)),
12606
- toolName,
12607
- toolDescription
12694
+ fields: {
12695
+ namespace: addTokens(emptyField(), namespaceTerms),
12696
+ name: addTokens(emptyField(), normalizeTokens(tokenizeIdent(server.name))),
12697
+ description: addTokens(emptyField(), normalizeTokens(tokenize(server.description))),
12698
+ toolName,
12699
+ toolDescription
12700
+ },
12701
+ tools,
12702
+ namespaceTerms
12608
12703
  };
12609
12704
  }
12610
12705
  function bm25Score(queryTerms, fields, avgFieldLen, idfValues) {
@@ -12664,20 +12759,114 @@ function serverSignature(server) {
12664
12759
  function indexKeyFor(docKeys) {
12665
12760
  return digest(docKeys.join(""));
12666
12761
  }
12667
- function docFieldsFor(docKey, server) {
12762
+ function docFor(docKey, server) {
12668
12763
  const cached = docCache.get(docKey);
12669
12764
  if (cached) {
12670
12765
  touch(docCache, docKey, cached);
12671
12766
  return cached;
12672
12767
  }
12673
12768
  docBuilds++;
12674
- const fields = buildDocFields(server);
12675
- putBounded(docCache, docKey, fields, MAX_CACHED_DOCS);
12676
- return fields;
12769
+ const doc = buildDoc(server);
12770
+ putBounded(docCache, docKey, doc, MAX_CACHED_DOCS);
12771
+ return doc;
12772
+ }
12773
+ var ACTION_VERBS = /* @__PURE__ */ new Set([
12774
+ "get",
12775
+ "set",
12776
+ "list",
12777
+ "create",
12778
+ "delete",
12779
+ "update",
12780
+ "add",
12781
+ "remove",
12782
+ "read",
12783
+ "write",
12784
+ "run",
12785
+ "fetch",
12786
+ "search",
12787
+ "find",
12788
+ "check",
12789
+ "show",
12790
+ "open",
12791
+ "close",
12792
+ "start",
12793
+ "stop",
12794
+ "put",
12795
+ "post",
12796
+ "patch",
12797
+ "send",
12798
+ "describe",
12799
+ "query",
12800
+ "execute",
12801
+ "exec",
12802
+ "upload",
12803
+ "download",
12804
+ "install",
12805
+ "enable",
12806
+ "disable"
12807
+ ]);
12808
+ var GENERIC_PRODUCT_WORDS = /* @__PURE__ */ new Set(["mcp", "server", "tool", "api", "client", "plugin", "service", "sdk", "app"]);
12809
+ var MIN_NUMERONYM_WORD = 8;
12810
+ function deriveAliases(servers, idf) {
12811
+ const phrases = /* @__PURE__ */ new Map();
12812
+ const fromName = /* @__PURE__ */ new Map();
12813
+ const note = (tokens, nameOf) => {
12814
+ for (let len = 2; len <= 3; len++) {
12815
+ for (let i = 0; i + len <= tokens.length; i++) {
12816
+ const words = tokens.slice(i, i + len);
12817
+ if (!words.every((w) => /^[a-z]{3,}$/.test(w) && !ACTION_VERBS.has(w) && !GENERIC_PRODUCT_WORDS.has(w)))
12818
+ continue;
12819
+ const acronym = words.map((w) => w[0]).join("");
12820
+ const key = normalizeTokens(words).join(" ");
12821
+ let byPhrase = phrases.get(acronym);
12822
+ if (!byPhrase) {
12823
+ byPhrase = /* @__PURE__ */ new Map();
12824
+ phrases.set(acronym, byPhrase);
12825
+ }
12826
+ byPhrase.set(key, (byPhrase.get(key) ?? 0) + (nameOf === void 0 ? 1 : 0));
12827
+ if (nameOf !== void 0) {
12828
+ let owners = fromName.get(key);
12829
+ if (!owners) {
12830
+ owners = /* @__PURE__ */ new Set();
12831
+ fromName.set(key, owners);
12832
+ }
12833
+ owners.add(nameOf);
12834
+ }
12835
+ }
12836
+ }
12837
+ };
12838
+ const aliases = /* @__PURE__ */ new Map();
12839
+ const offer = (alias, terms) => {
12840
+ if (idf.has(alias) || ABBREVIATIONS[alias] || SUB_FLOOR_STOPWORDS.has(alias)) return;
12841
+ aliases.set(alias, terms);
12842
+ };
12843
+ for (const server of servers) {
12844
+ const nsTokens = tokenizeIdent(server.namespace);
12845
+ const nameTokens = tokenizeIdent(server.name);
12846
+ note(nsTokens, server.namespace);
12847
+ note(nameTokens, server.namespace);
12848
+ const own = /* @__PURE__ */ new Set([...nsTokens, ...nameTokens]);
12849
+ for (const tool of server.tools)
12850
+ note(
12851
+ tokenizeIdent(tool.name).map((w) => own.has(w) ? "" : w),
12852
+ void 0
12853
+ );
12854
+ for (const word of [...nsTokens, ...nameTokens]) {
12855
+ if (word.length >= MIN_NUMERONYM_WORD && /^[a-z]+$/.test(word)) {
12856
+ offer(`${word[0]}${word.length - 2}${word[word.length - 1]}`, normalizeTokens([word]));
12857
+ }
12858
+ }
12859
+ }
12860
+ for (const [acronym, byPhrase] of phrases) {
12861
+ if (byPhrase.size !== 1) continue;
12862
+ const [[key, count]] = [...byPhrase];
12863
+ if (count >= 2 || fromName.get(key)?.size === 1) offer(acronym, key.split(" "));
12864
+ }
12865
+ return aliases;
12677
12866
  }
12678
12867
  function buildIndex(servers, docKeys) {
12679
12868
  indexBuilds++;
12680
- const docs = servers.map((s, i) => ({ namespace: s.namespace, fields: docFieldsFor(docKeys[i], s) }));
12869
+ const docs = servers.map((s, i) => ({ namespace: s.namespace, ...docFor(docKeys[i], s) }));
12681
12870
  const N = docs.length;
12682
12871
  const df = /* @__PURE__ */ new Map();
12683
12872
  for (const { fields } of docs) {
@@ -12713,7 +12902,38 @@ function buildIndex(servers, docKeys) {
12713
12902
  toolName: totalLen.toolName / denom,
12714
12903
  toolDescription: totalLen.toolDescription / denom
12715
12904
  };
12716
- return { docs, idf, avgFieldLen };
12905
+ return { docs, idf, avgFieldLen, aliases: deriveAliases(servers, idf) };
12906
+ }
12907
+ function indexFor(servers) {
12908
+ const docKeys = servers.map((s) => digest(serverSignature(s)));
12909
+ const indexKey = indexKeyFor(docKeys);
12910
+ let index = indexCache.get(indexKey);
12911
+ if (index === void 0) {
12912
+ index = buildIndex(servers, docKeys);
12913
+ putBounded(indexCache, indexKey, index, MAX_CACHED_INDEXES);
12914
+ } else {
12915
+ touch(indexCache, indexKey, index);
12916
+ }
12917
+ return index;
12918
+ }
12919
+ var QUERY_FUNCTION_WORDS = new Set(
12920
+ "the and for are that this with what which how does did was were have has had our your their its from into about can could would should will just any all some when where who why whether then than there here also very much many not but via you they them these those been being please thanks thank let lets since until while between among use using".split(" ")
12921
+ );
12922
+ function queryTermsFor(text, index, drop) {
12923
+ const out = [];
12924
+ for (const t of tokenizeQuery(text)) {
12925
+ if (drop?.has(t)) continue;
12926
+ const expanded = ABBREVIATIONS[t];
12927
+ if (expanded) {
12928
+ for (const e of expanded) out.push(normalizeTerm(e));
12929
+ continue;
12930
+ }
12931
+ const folded = normalizeTerm(t);
12932
+ const alias = index.idf.has(folded) ? void 0 : index.aliases.get(t);
12933
+ if (alias) out.push(...alias);
12934
+ else out.push(folded);
12935
+ }
12936
+ return out;
12717
12937
  }
12718
12938
  function scoreAgainstIndex(queryTerms, index) {
12719
12939
  const results = [];
@@ -12726,45 +12946,76 @@ function scoreAgainstIndex(queryTerms, index) {
12726
12946
  results.sort((a, b) => b.score - a.score || a.namespace.localeCompare(b.namespace));
12727
12947
  return results;
12728
12948
  }
12729
- function queryNamesNamespace(queryTerms, namespace) {
12730
- if (queryTerms.has(namespace.toLowerCase())) return true;
12731
- const parts = tokenizeIdent(namespace);
12732
- return parts.length > 0 && parts.every((p) => queryTerms.has(p));
12949
+ function queryNamesNamespace(queryTerms, namespaceTerms) {
12950
+ return namespaceTerms.length > 0 && namespaceTerms.every((p) => queryTerms.has(p));
12733
12951
  }
12734
12952
  function rankTools(query, servers) {
12735
- const queryTerms = new Set(tokenizeQuery(query));
12736
- if (queryTerms.size === 0 || servers.length === 0) return [];
12953
+ if (tokenizeQuery(query).length === 0 || servers.length === 0) return [];
12954
+ const index = indexFor(servers);
12955
+ const termList = queryTermsFor(query, index, QUERY_FUNCTION_WORDS);
12956
+ const queryTerms = new Set(termList);
12957
+ if (queryTerms.size === 0) return [];
12958
+ const serverScore = new Map(scoreAgainstIndex(termList, index).map((r) => [r.namespace, r.score]));
12737
12959
  const out = [];
12738
- for (const server of servers) {
12739
- for (const tool of server.tools) {
12740
- const nameTerms = new Set(tokenizeIdent(tool.name));
12741
- const descTerms = new Set(tokenize(tool.description));
12960
+ servers.forEach((server, i) => {
12961
+ const doc = index.docs[i];
12962
+ const namedNamespace = queryNamesNamespace(queryTerms, doc.namespaceTerms);
12963
+ server.tools.forEach((tool, j) => {
12964
+ const terms = doc.tools[j];
12742
12965
  let score = 0;
12966
+ let nameHits = 0;
12743
12967
  for (const term of queryTerms) {
12744
- if (nameTerms.has(term)) score += FIELD_WEIGHTS.toolName;
12745
- else if (descTerms.has(term)) score += FIELD_WEIGHTS.toolDescription;
12746
- }
12747
- if (score > 0 && queryNamesNamespace(queryTerms, server.namespace)) score += 0.5;
12748
- if (score > 0) out.push({ namespace: server.namespace, name: tool.name, description: tool.description, score });
12749
- }
12750
- }
12751
- return out.sort(
12752
- (a, b) => b.score - a.score || a.namespace.localeCompare(b.namespace) || a.name.localeCompare(b.name)
12968
+ if (terms.name.has(term)) {
12969
+ score += FIELD_WEIGHTS.toolName;
12970
+ nameHits++;
12971
+ } else if (terms.desc.has(term)) score += FIELD_WEIGHTS.toolDescription;
12972
+ }
12973
+ if (score === 0) return;
12974
+ if (namedNamespace) score += 0.5;
12975
+ const nameMisses = terms.nameList.filter((t) => !queryTerms.has(t)).length;
12976
+ out.push({
12977
+ namespace: server.namespace,
12978
+ name: tool.name,
12979
+ description: tool.description,
12980
+ score,
12981
+ serverScore: serverScore.get(server.namespace) ?? 0,
12982
+ nameHits,
12983
+ nameMisses,
12984
+ serverTools: server.tools.length
12985
+ });
12986
+ });
12987
+ });
12988
+ out.sort(
12989
+ (a, b) => b.score - a.score || b.serverScore - a.serverScore || b.nameHits - a.nameHits || a.nameMisses - b.nameMisses || a.serverTools - b.serverTools || a.namespace.localeCompare(b.namespace) || a.name.localeCompare(b.name)
12753
12990
  );
12991
+ return out.map(({ namespace, name, description, score }) => ({ namespace, name, description, score }));
12754
12992
  }
12755
12993
  function rankServers(context, servers) {
12756
- const queryTerms = tokenizeQuery(context);
12757
- if (queryTerms.length === 0 || servers.length === 0) return [];
12758
- const docKeys = servers.map((s) => digest(serverSignature(s)));
12759
- const indexKey = indexKeyFor(docKeys);
12760
- let index = indexCache.get(indexKey);
12761
- if (index === void 0) {
12762
- index = buildIndex(servers, docKeys);
12763
- putBounded(indexCache, indexKey, index, MAX_CACHED_INDEXES);
12764
- } else {
12765
- touch(indexCache, indexKey, index);
12766
- }
12767
- return scoreAgainstIndex(queryTerms, index);
12994
+ if (tokenizeQuery(context).length === 0 || servers.length === 0) return [];
12995
+ const index = indexFor(servers);
12996
+ return scoreAgainstIndex(queryTermsFor(context, index, QUERY_FUNCTION_WORDS), index);
12997
+ }
12998
+ function queryCoverage(query, servers) {
12999
+ if (servers.length === 0) return [];
13000
+ const index = indexFor(servers);
13001
+ const terms = [
13002
+ ...new Set(queryTermsFor(query, index, QUERY_FUNCTION_WORDS).filter((t) => t.length >= 2 && !/^[0-9]+$/.test(t)))
13003
+ ];
13004
+ const N = index.docs.length;
13005
+ const unseenIdf = Math.log((N + 0.5) / 0.5 + 1);
13006
+ const idfOf = (t) => index.idf.get(t) ?? unseenIdf;
13007
+ const total = terms.reduce((sum, t) => sum + idfOf(t), 0);
13008
+ return index.docs.map(({ namespace, fields }) => {
13009
+ let mass = 0;
13010
+ let matched = 0;
13011
+ for (const t of terms) {
13012
+ if (Object.keys(FIELD_WEIGHTS).some((f) => fields[f].counts.has(t))) {
13013
+ mass += idfOf(t);
13014
+ matched++;
13015
+ }
13016
+ }
13017
+ return { namespace, coverage: total > 0 ? mass / total : 0, matched, contentTerms: terms.length };
13018
+ });
12768
13019
  }
12769
13020
 
12770
13021
  // src/foundry.ts
@@ -15603,10 +15854,10 @@ function secretConsumersNotice(io, name, consumers, replacing, isFresh, referenc
15603
15854
  }
15604
15855
  const where2 = consumers.path ?? "bundles.json";
15605
15856
  if (consumers.namespaces.length > 0) {
15606
- const list = consumers.namespaces.join(", ");
15857
+ const list2 = consumers.namespaces.join(", ");
15607
15858
  if (replacing) {
15608
15859
  io.err(
15609
- `yaw-mcp secrets: ${ref} is referenced by: ${list} (${where2}).
15860
+ `yaw-mcp secrets: ${ref} is referenced by: ${list2} (${where2}).
15610
15861
  A running yaw-mcp keeps the OLD value in any of these it has already started, until it
15611
15862
  restarts. Unload each one (mcp_connect_deactivate <namespace>; the next call starts it
15612
15863
  with the new value), or reconnect yaw-mcp in your MCP client.
@@ -15614,7 +15865,7 @@ function secretConsumersNotice(io, name, consumers, replacing, isFresh, referenc
15614
15865
  );
15615
15866
  } else {
15616
15867
  io.err(
15617
- `yaw-mcp secrets: ${ref} is referenced by: ${list} (${where2}).
15868
+ `yaw-mcp secrets: ${ref} is referenced by: ${list2} (${where2}).
15618
15869
  yaw-mcp reads the vault at each server start, so they pick it up the next time they start.
15619
15870
  One a running yaw-mcp started before an earlier \`secrets remove\` of this name still holds
15620
15871
  the value it started with: unload it (mcp_connect_deactivate <namespace>) or reconnect yaw-mcp.
@@ -17881,6 +18132,147 @@ function validateExecRefs(steps) {
17881
18132
  return { ok: true };
17882
18133
  }
17883
18134
 
18135
+ // src/fallback-tools.ts
18136
+ var list = (rows) => rows.map(([name, description]) => ({ name, description }));
18137
+ var GITHUB = list([
18138
+ ["get_me", "Get details of the authenticated GitHub user"],
18139
+ ["get_team_members", "Get member usernames of a specific team in an organization"],
18140
+ ["get_teams", "Get details of the teams the user is a member of"],
18141
+ ["add_issue_comment", "Add a comment and/or reaction to a specific issue or issue comment in a GitHub repository"],
18142
+ ["get_label", "Get a specific label from a repository"],
18143
+ ["issue_read", "Get information about a specific issue in a GitHub repository"],
18144
+ ["issue_write", "Create a new or update an existing issue in a GitHub repository"],
18145
+ ["list_issue_fields", "List issue fields for a repository or organization"],
18146
+ ["list_issue_types", "List supported issue types for a repository or its owner organization"],
18147
+ ["list_issues", "List issues in a GitHub repository"],
18148
+ ["search_issues", "Search issues using natural-language semantic matching"],
18149
+ ["sub_issue_write", "Add a sub-issue to a parent issue in a GitHub repository"],
18150
+ ["update_issue_comment", "Update the body of an existing issue or pull request conversation comment"],
18151
+ ["add_comment_to_pending_review", "Add review comment to the requester's latest pending pull request review"],
18152
+ ["add_reply_to_pull_request_comment", "Add a reply and/or reaction to an existing pull request comment"],
18153
+ ["create_pull_request", "Create a new pull request in a GitHub repository"],
18154
+ ["list_pull_requests", "List pull requests in a GitHub repository"],
18155
+ ["merge_pull_request", "Merge a pull request in a GitHub repository"],
18156
+ ["pull_request_read", "Get information on a specific pull request in GitHub repository"],
18157
+ ["pull_request_review_write", "Create and/or submit, delete review of a pull request"],
18158
+ [
18159
+ "search_pull_requests",
18160
+ "Search for pull requests in GitHub repositories using issues search syntax already scoped to is:pr"
18161
+ ],
18162
+ ["update_pull_request", "Update an existing pull request in a GitHub repository"],
18163
+ ["update_pull_request_branch", "Update the branch of a pull request with the latest changes from the base branch"],
18164
+ ["create_branch", "Create a new branch in a GitHub repository"],
18165
+ ["create_or_update_file", "Create or update a single file in a GitHub repository"],
18166
+ ["create_repository", "Create a new GitHub repository in your account or specified organization"],
18167
+ ["delete_file", "Delete a file from a GitHub repository"],
18168
+ ["delete_repository", "Delete a GitHub repository after the user confirms the exact owner/repository name"],
18169
+ ["fork_repository", "Fork a GitHub repository to your account or specified organization"],
18170
+ ["get_commit", "Get details for a commit from a GitHub repository"],
18171
+ ["get_file_contents", "Get the contents of a file or directory from a GitHub repository"],
18172
+ ["get_latest_release", "Get the latest release in a GitHub repository"],
18173
+ ["get_release_by_tag", "Get a specific release by its tag name in a GitHub repository"],
18174
+ ["get_tag", "Get details about a specific git tag in a GitHub repository"],
18175
+ ["list_branches", "List branches in a GitHub repository"],
18176
+ ["list_commits", "Get list of commits of a branch in a GitHub repository"],
18177
+ ["list_releases", "List releases in a GitHub repository"],
18178
+ ["list_repository_collaborators", "List collaborators of a GitHub repository"],
18179
+ ["list_tags", "List git tags in a GitHub repository"],
18180
+ ["push_files", "Push multiple files to a GitHub repository in a single commit"],
18181
+ ["search_code", "Fast and precise code search across ALL GitHub repositories using GitHub's native search engine"],
18182
+ ["search_commits", "Search for commits across GitHub repositories using GitHub's commit search syntax"],
18183
+ ["search_repositories", "Find GitHub repositories by name, description, readme, topics, or other metadata"],
18184
+ ["search_users", "Find GitHub users by username, real name, or other profile information"]
18185
+ ]);
18186
+ var TERRAFORM = list([
18187
+ ["get_latest_module_version", "Fetches the latest version of a Terraform module from the public registry"],
18188
+ ["get_latest_provider_version", "Fetches the latest version of a Terraform provider from the public registry"],
18189
+ ["get_module_details", "Fetches up-to-date documentation on how to use a Terraform module"],
18190
+ ["get_policy_details", "Fetches up-to-date documentation for a specific policy from the Terraform registry"],
18191
+ [
18192
+ "get_provider_capabilities",
18193
+ "Get the capabilities of a Terraform provider including the types of resources, data sources, functions, guides, and other features it supports"
18194
+ ],
18195
+ ["get_provider_details", "Fetches up-to-date documentation for a specific service from a Terraform provider"],
18196
+ [
18197
+ "search_modules",
18198
+ "Resolves a Terraform module name to obtain a compatible module_id for the get_module_details tool and returns a list of matching Terraform modules"
18199
+ ],
18200
+ ["search_policies", "Searches for Terraform policies based on a query string"],
18201
+ [
18202
+ "search_provider_docs",
18203
+ "This tool retrieves a list of potential documents based on the 'service_slug' and 'provider_document_type' provided"
18204
+ ]
18205
+ ]);
18206
+ var VAULT = list([
18207
+ ["list_mounts", "List the available mounted secrets engines on a Vault Server"],
18208
+ ["create_mount", "Mount a new secrets engine on a specific path in Vault"],
18209
+ ["delete_mount", "Delete a mounted secret engine in Vault"],
18210
+ ["list_secrets", "List secrets in a KV mount under a specific path in Vault"],
18211
+ ["read_secret", "Read a secret from a KV mount in at a specific path in Vault"],
18212
+ ["write_secret", "Writes a secret value to a KV store in Vault using the specified path and mount"],
18213
+ ["delete_secret", "Delete a secret from a KV mount in Vault using the specified path and mount"],
18214
+ [
18215
+ "enable_pki",
18216
+ "Enable the PKI (Public Key Infrastructure) secrets engine in Vault, allowing for the issuance and management of SSL/TLS certificates"
18217
+ ],
18218
+ ["create_pki_issuer", "Create a new PKI SSL certificate issuer in Vault"],
18219
+ [
18220
+ "list_pki_issuers",
18221
+ "Get a list of PKI issuers on a specific pki mount in Vault, allowing you to see all the configured issuers for that mount"
18222
+ ],
18223
+ [
18224
+ "read_pki_issuer",
18225
+ "Read a PKI issuer details from a specific mount in Vault, allowing you to retrieve information about a specific PKI issuer"
18226
+ ],
18227
+ [
18228
+ "list_pki_roles",
18229
+ "Get a list of PKI roles which are able to issue certificates, allowing you to see all the configured roles for a specific PKI mount in Vault"
18230
+ ],
18231
+ ["read_pki_role", "Read a PKI role details from a specific mount in Vault"],
18232
+ ["create_pki_role", "Create a new PKI SSL certificate role in Vault"],
18233
+ ["delete_pki_role", "Delete a PKI SSL role in Vault"],
18234
+ [
18235
+ "issue_pki_certificate",
18236
+ "Create a new PKI SSL certificate issuer in Vault, allowing for the issuance of SSL/TLS certificates"
18237
+ ]
18238
+ ]);
18239
+ var ENTRIES = [
18240
+ { images: ["ghcr.io/github/github-mcp-server"], binaries: ["github-mcp-server"], tools: GITHUB },
18241
+ {
18242
+ images: ["hashicorp/terraform-mcp-server", "docker.io/hashicorp/terraform-mcp-server"],
18243
+ binaries: ["terraform-mcp-server"],
18244
+ tools: TERRAFORM
18245
+ },
18246
+ {
18247
+ images: ["hashicorp/vault-mcp-server", "docker.io/hashicorp/vault-mcp-server"],
18248
+ binaries: ["vault-mcp-server"],
18249
+ tools: VAULT
18250
+ }
18251
+ ];
18252
+ function imageRepository(arg) {
18253
+ const noDigest = arg.split("@")[0];
18254
+ const slash = noDigest.lastIndexOf("/");
18255
+ const colon = noDigest.lastIndexOf(":");
18256
+ return (colon > slash ? noDigest.slice(0, colon) : noDigest).toLowerCase();
18257
+ }
18258
+ function binaryName(command) {
18259
+ const base = command.split(/[\\/]/).pop() ?? command;
18260
+ return base.replace(/\.exe$/i, "").toLowerCase();
18261
+ }
18262
+ function fallbackToolsFor(server) {
18263
+ if (!server.command) return void 0;
18264
+ const bin = binaryName(server.command);
18265
+ const args = server.args ?? [];
18266
+ const containerRuntime = bin === "docker" || bin === "podman";
18267
+ for (const entry of ENTRIES) {
18268
+ if (entry.binaries.includes(bin)) return entry.tools;
18269
+ if (containerRuntime && args.some((a) => !a.startsWith("-") && entry.images.includes(imageRepository(a)))) {
18270
+ return entry.tools;
18271
+ }
18272
+ }
18273
+ return void 0;
18274
+ }
18275
+
17884
18276
  // src/idle-ttl.ts
17885
18277
  var ADAPTIVE_WINDOW_MS = 5 * 60 * 1e3;
17886
18278
  var ADAPTIVE_LOOKBACK = 20;
@@ -17999,7 +18391,8 @@ var PENALTY_RATE_PCT = Math.round(PENALTY_RATE_THRESHOLD * 100);
17999
18391
  var FIND_TOOL_MAX_LIMIT = 50;
18000
18392
  var SERVER_INSTRUCTIONS = [
18001
18393
  "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.",
18002
- "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).",
18394
+ "Concrete task: mcp_connect_dispatch loads the best server in one call; its description (find_tool's when dispatch is unlisted) names the installed servers. Browsing: mcp_connect_discover. Known 2-4 step chain: mcp_connect_exec (calls a cached server's tool by name, no load needed).",
18395
+ "Answer general-knowledge questions directly, without routing. If mcp_connect_find_tool finds nothing, retry with mcp_connect_dispatch in the user's own words. A just-loaded tool reported missing: call it through mcp_connect_exec.",
18003
18396
  "Prefer a server over the CLI it shadows. Read yaw-mcp://guide first when listed: this project's routing rules."
18004
18397
  ].join(" ");
18005
18398
  var META_TOOLS = {
@@ -18126,7 +18519,7 @@ var META_TOOLS = {
18126
18519
  routeEffort: {
18127
18520
  type: "string",
18128
18521
  enum: ["off", "auto", "aggressive"],
18129
- 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.'
18522
+ 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. No effect without client MCP sampling. Falls back to YAW_MCP_ROUTE_EFFORT. Budget 1 only.'
18130
18523
  }
18131
18524
  },
18132
18525
  required: ["intent"]
@@ -18332,314 +18725,122 @@ function computeSecretsReport(servers, vaultKeys) {
18332
18725
  }
18333
18726
  var META_TOOL_NAMES = new Set(Object.values(META_TOOLS).map((m) => m.name));
18334
18727
 
18335
- // src/pack-detect.ts
18336
- var DEFAULT_MAX_HISTORY = 100;
18337
- var DEFAULT_MAX_GAP_MS = 12e4;
18338
- var MIN_NAMESPACES = 2;
18339
- var MAX_NAMESPACES = 3;
18340
- var MIN_RECURRENCES = 2;
18341
- var BURST_SPAN_FACTOR = 5;
18342
- function packIdFromNamespaces(namespaces) {
18343
- return Array.from(new Set(namespaces)).sort().join("|");
18728
+ // src/proxy.ts
18729
+ var DEFERRED_INPUT_SCHEMA = {
18730
+ type: "object",
18731
+ properties: {},
18732
+ additionalProperties: true
18733
+ };
18734
+ function deferredDescription(server, cachedDesc) {
18735
+ const base = cachedDesc?.trim();
18736
+ const suffix = `[yaw-mcp: server "${server.namespace}" not yet connected \u2014 first call activates it]`;
18737
+ return base ? `${base}
18738
+
18739
+ ${suffix}` : suffix;
18344
18740
  }
18345
- var PackDetector = class {
18346
- maxHistory;
18347
- maxGapMs;
18348
- history = [];
18349
- constructor(options = {}) {
18350
- this.maxHistory = options.maxHistory ?? DEFAULT_MAX_HISTORY;
18351
- this.maxGapMs = options.maxGapMs ?? DEFAULT_MAX_GAP_MS;
18741
+ function compareNamespaces(a, b) {
18742
+ return a < b ? -1 : a > b ? 1 : 0;
18743
+ }
18744
+ function connectionsInOrder(activeConnections) {
18745
+ return [...activeConnections.values()].sort((a, b) => compareNamespaces(a.config.namespace, b.config.namespace));
18746
+ }
18747
+ function serversInOrder(servers) {
18748
+ return [...servers].sort((a, b) => compareNamespaces(a.namespace, b.namespace));
18749
+ }
18750
+ function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, exposure = "full", exposedNamespaces, isDenied) {
18751
+ const tools = [];
18752
+ const seen = /* @__PURE__ */ new Set();
18753
+ for (const meta of Object.values(META_TOOLS)) {
18754
+ if (exposure === "lite" && !LITE_META_TOOL_NAMES.has(meta.name)) continue;
18755
+ tools.push({
18756
+ name: meta.name,
18757
+ description: meta.description,
18758
+ inputSchema: meta.inputSchema,
18759
+ annotations: meta.annotations
18760
+ });
18761
+ seen.add(meta.name);
18352
18762
  }
18353
- recordCall(namespace, toolName, at) {
18354
- if (!namespace || !toolName) return;
18355
- if (typeof at !== "number" || !Number.isFinite(at)) return;
18356
- this.history.push({ namespace, toolName, at });
18357
- if (this.history.length > this.maxHistory) {
18358
- const overflow = this.history.length - this.maxHistory;
18359
- this.history = this.history.slice(overflow);
18763
+ for (const conn of connectionsInOrder(activeConnections)) {
18764
+ if (exposure !== "full" && !exposedNamespaces?.has(conn.config.namespace)) continue;
18765
+ const filter = toolFilters?.get(conn.config.namespace);
18766
+ for (const tool of conn.tools) {
18767
+ if (filter && !filter.has(tool.name)) continue;
18768
+ if (isDenied?.(tool.namespacedName)) continue;
18769
+ if (seen.has(tool.namespacedName)) continue;
18770
+ tools.push({
18771
+ name: tool.namespacedName,
18772
+ title: tool.title,
18773
+ description: tool.description,
18774
+ inputSchema: tool.inputSchema,
18775
+ outputSchema: tool.outputSchema,
18776
+ annotations: tool.annotations,
18777
+ _meta: tool._meta
18778
+ });
18779
+ seen.add(tool.namespacedName);
18360
18780
  }
18361
18781
  }
18362
- // Walk the history, segmenting it into "bursts" (see segmentBursts for
18363
- // the three boundaries). Each burst with ≥2 distinct namespaces is a
18364
- // candidate pack. A pack is returned when the same namespace set
18365
- // appears in ≥MIN_RECURRENCES bursts.
18366
- detectChains() {
18367
- if (this.history.length < 2) return [];
18368
- const bursts = this.segmentBursts();
18369
- const packCounts = /* @__PURE__ */ new Map();
18370
- for (const burst of bursts) {
18371
- if (burst.namespaces.length < MIN_NAMESPACES) continue;
18372
- if (burst.namespaces.length > MAX_NAMESPACES) continue;
18373
- const id = packIdFromNamespaces(burst.namespaces);
18374
- const prev = packCounts.get(id);
18375
- if (prev) {
18376
- prev.frequency += 1;
18377
- if (burst.lastAt > prev.lastSeenAt) prev.lastSeenAt = burst.lastAt;
18378
- } else {
18379
- packCounts.set(id, {
18380
- namespaces: [...burst.namespaces],
18381
- frequency: 1,
18382
- lastSeenAt: burst.lastAt
18383
- });
18782
+ for (const server of serversInOrder(inactiveWithCache)) {
18783
+ if (activeConnections.has(server.namespace)) continue;
18784
+ if (!server.toolCache || server.toolCache.length === 0) continue;
18785
+ if (exposure !== "full") continue;
18786
+ const filter = toolFilters?.get(server.namespace);
18787
+ for (const cached of server.toolCache) {
18788
+ if (filter && !filter.has(cached.name)) continue;
18789
+ const namespacedName = `${server.namespace}_${cached.name}`;
18790
+ if (isDenied?.(namespacedName)) continue;
18791
+ if (seen.has(namespacedName)) continue;
18792
+ tools.push({
18793
+ name: namespacedName,
18794
+ description: deferredDescription(server, cached.description),
18795
+ inputSchema: DEFERRED_INPUT_SCHEMA
18796
+ });
18797
+ seen.add(namespacedName);
18798
+ }
18799
+ }
18800
+ return tools;
18801
+ }
18802
+ function buildToolRoutes(activeConnections, inactiveWithCache = [], quiet = false) {
18803
+ const routes = /* @__PURE__ */ new Map();
18804
+ for (const conn of connectionsInOrder(activeConnections)) {
18805
+ for (const tool of conn.tools) {
18806
+ const existing = routes.get(tool.namespacedName);
18807
+ if (existing && existing.namespace !== conn.config.namespace) {
18808
+ if (!quiet) {
18809
+ log("warn", "Tool route collision; keeping the first upstream, ignoring the later one", {
18810
+ tool: tool.namespacedName,
18811
+ keptNamespace: existing.namespace,
18812
+ ignoredNamespace: conn.config.namespace
18813
+ });
18814
+ }
18815
+ continue;
18384
18816
  }
18817
+ routes.set(tool.namespacedName, {
18818
+ namespace: conn.config.namespace,
18819
+ originalName: tool.name
18820
+ });
18385
18821
  }
18386
- const packs = [];
18387
- for (const entry of packCounts.values()) {
18388
- if (entry.frequency >= MIN_RECURRENCES) {
18389
- packs.push({
18390
- namespaces: entry.namespaces,
18391
- frequency: entry.frequency,
18392
- lastSeenAt: entry.lastSeenAt
18393
- });
18822
+ }
18823
+ for (const server of serversInOrder(inactiveWithCache)) {
18824
+ if (activeConnections.has(server.namespace)) continue;
18825
+ if (!server.toolCache || server.toolCache.length === 0) continue;
18826
+ for (const cached of server.toolCache) {
18827
+ const namespacedName = `${server.namespace}_${cached.name}`;
18828
+ const existing = routes.get(namespacedName);
18829
+ if (existing) {
18830
+ if (!quiet && existing.deferred && existing.namespace !== server.namespace) {
18831
+ log("warn", "Deferred tool route collision; earlier cached server wins", {
18832
+ tool: namespacedName,
18833
+ winningNamespace: existing.namespace,
18834
+ shadowedNamespace: server.namespace
18835
+ });
18836
+ }
18837
+ continue;
18394
18838
  }
18395
- }
18396
- return packs;
18397
- }
18398
- // Segment the call history into bursts. A new burst starts whenever:
18399
- // 1. the gap to the previous call exceeds maxGapMs (idle boundary);
18400
- // 2. the burst has already spanned maxGapMs * BURST_SPAN_FACTOR
18401
- // (span boundary -- see the constant for why a continuous session
18402
- // must be sliced for recurrence to be countable); or
18403
- // 3. the call would add a namespace past MAX_NAMESPACES (overflow
18404
- // boundary). detectChains drops an over-wide burst entirely, so
18405
- // without this cut a single visit to a 4th namespace poisoned the
18406
- // whole burst and the recurring trio inside it was never counted.
18407
- // Cutting at the overflow keeps each burst representable as a
18408
- // pack; a wider rotation surfaces as its recurring 3-subsets, the
18409
- // best answer the MAX_NAMESPACES pack-size cap can express. SLOWLY,
18410
- // though: the cuts walk the rotation, so each 3-subset recurs only
18411
- // once per full pass over it. A strict a,b,c,d loop segments as
18412
- // [a,b,c] [d,a,b] [c,d,a] [b,c,d] [a,b,c] ..., and {a,b,c} reaches
18413
- // MIN_RECURRENCES at the 15th call -- all of which must land inside
18414
- // one span window and one maxGapMs cadence.
18415
- // Within a burst, each namespace is recorded only once
18416
- // (order-of-first-appearance); the "last seen" timestamp tracks the
18417
- // most recent call in the burst so recency ranking is truthful even
18418
- // when the burst has many calls.
18419
- segmentBursts() {
18420
- const bursts = [];
18421
- const maxBurstSpanMs = this.maxGapMs * BURST_SPAN_FACTOR;
18422
- let current = null;
18423
- let prevAt = 0;
18424
- for (const call of this.history) {
18425
- const gapExceeded = call.at - prevAt > this.maxGapMs;
18426
- const spanExceeded = current !== null && call.at - current.startAt > maxBurstSpanMs;
18427
- const wentBackwards = current !== null && call.at < prevAt;
18428
- const wouldOverflow = current !== null && current.namespaces.length >= MAX_NAMESPACES && !current.namespaces.includes(call.namespace);
18429
- if (!current || gapExceeded || spanExceeded || wentBackwards || wouldOverflow) {
18430
- current = { namespaces: [call.namespace], startAt: call.at, lastAt: call.at };
18431
- bursts.push(current);
18432
- } else {
18433
- if (!current.namespaces.includes(call.namespace)) {
18434
- current.namespaces.push(call.namespace);
18435
- }
18436
- current.lastAt = call.at;
18437
- }
18438
- prevAt = call.at;
18439
- }
18440
- return bursts;
18441
- }
18442
- // Exposed for tests.
18443
- getHistory() {
18444
- return this.history;
18445
- }
18446
- reset() {
18447
- this.history = [];
18448
- }
18449
- // Return a defensive copy of history for persistence. Each entry is a
18450
- // fresh object, safe to JSON.stringify without worrying about later
18451
- // mutations to the detector's internal array.
18452
- exportSnapshot() {
18453
- return this.history.map((c) => ({ namespace: c.namespace, toolName: c.toolName, at: c.at }));
18454
- }
18455
- // Replace in-memory history with the given snapshot. Respects the
18456
- // configured maxHistory cap — if the snapshot exceeds it, the oldest
18457
- // entries are dropped, matching the cap behavior of recordCall.
18458
- //
18459
- // Entries are SORTED by `at` after cleaning. segmentBursts reads the history
18460
- // as a time-ordered stream (see the boundary comparisons there), and the
18461
- // snapshot comes off disk where a hand-edited, merged or torn file can carry
18462
- // entries out of order; an out-of-order run would otherwise be segmented as
18463
- // one welded burst plus spurious boundaries. Sorting is stable, so equal
18464
- // timestamps keep their recorded order.
18465
- //
18466
- // `at` is validated as a finite number, not just present: the snapshot
18467
- // comes off disk (persistence.ts) where a hand-edited or torn file can
18468
- // carry null / "12345" / NaN. segmentBursts compares `call.at - prevAt >
18469
- // maxGapMs`, and every comparison against NaN is false, so a single NaN
18470
- // timestamp silently welds the whole history into one giant burst and
18471
- // manufactures packs that never happened.
18472
- loadSnapshot(snapshot) {
18473
- const clean = [];
18474
- for (const c of snapshot) {
18475
- if (!c?.namespace || !c.toolName) continue;
18476
- if (typeof c.at !== "number" || !Number.isFinite(c.at)) continue;
18477
- clean.push({ namespace: c.namespace, toolName: c.toolName, at: c.at });
18478
- }
18479
- clean.sort((a, b) => a.at - b.at);
18480
- if (clean.length > this.maxHistory) {
18481
- this.history = clean.slice(clean.length - this.maxHistory);
18482
- } else {
18483
- this.history = clean;
18484
- }
18485
- }
18486
- };
18487
-
18488
- // src/progress.ts
18489
- function isProgressRequested(ctx) {
18490
- const token = ctx?.mcpReq?._meta?.progressToken;
18491
- return token !== void 0 && token !== null && typeof ctx?.mcpReq?.notify === "function";
18492
- }
18493
- function createProgressReporter(ctx) {
18494
- if (!isProgressRequested(ctx)) {
18495
- return () => {
18496
- };
18497
- }
18498
- const token = ctx?.mcpReq?._meta?.progressToken;
18499
- const send = ctx?.mcpReq?.notify;
18500
- const EPSILON = 1e-3;
18501
- let lastEmitted = -EPSILON;
18502
- return (message, progress, total) => {
18503
- let emitted;
18504
- let emittedTotal;
18505
- if (progress !== void 0) {
18506
- emitted = progress > lastEmitted ? progress : lastEmitted + EPSILON;
18507
- emittedTotal = total !== void 0 && emitted <= total ? total : void 0;
18508
- } else {
18509
- emitted = lastEmitted + EPSILON;
18510
- emittedTotal = void 0;
18511
- }
18512
- const params = {
18513
- progressToken: token,
18514
- progress: emitted,
18515
- message
18516
- };
18517
- if (emittedTotal !== void 0) params.total = emittedTotal;
18518
- lastEmitted = emitted;
18519
- send({ method: "notifications/progress", params }).catch((err) => {
18520
- log("warn", "Progress notification send failed", {
18521
- error: err instanceof Error ? err.message : String(err)
18522
- });
18523
- });
18524
- };
18525
- }
18526
-
18527
- // src/proxy.ts
18528
- var DEFERRED_INPUT_SCHEMA = {
18529
- type: "object",
18530
- properties: {},
18531
- additionalProperties: true
18532
- };
18533
- function deferredDescription(server, cachedDesc) {
18534
- const base = cachedDesc?.trim();
18535
- const suffix = `[yaw-mcp: server "${server.namespace}" not yet connected \u2014 first call activates it]`;
18536
- return base ? `${base}
18537
-
18538
- ${suffix}` : suffix;
18539
- }
18540
- function compareNamespaces(a, b) {
18541
- return a < b ? -1 : a > b ? 1 : 0;
18542
- }
18543
- function connectionsInOrder(activeConnections) {
18544
- return [...activeConnections.values()].sort((a, b) => compareNamespaces(a.config.namespace, b.config.namespace));
18545
- }
18546
- function serversInOrder(servers) {
18547
- return [...servers].sort((a, b) => compareNamespaces(a.namespace, b.namespace));
18548
- }
18549
- function buildToolList(activeConnections, inactiveWithCache = [], toolFilters, exposure = "full", exposedNamespaces, isDenied) {
18550
- const tools = [];
18551
- const seen = /* @__PURE__ */ new Set();
18552
- for (const meta of Object.values(META_TOOLS)) {
18553
- if (exposure === "lite" && !LITE_META_TOOL_NAMES.has(meta.name)) continue;
18554
- tools.push({
18555
- name: meta.name,
18556
- description: meta.description,
18557
- inputSchema: meta.inputSchema,
18558
- annotations: meta.annotations
18559
- });
18560
- seen.add(meta.name);
18561
- }
18562
- for (const conn of connectionsInOrder(activeConnections)) {
18563
- if (exposure !== "full" && !exposedNamespaces?.has(conn.config.namespace)) continue;
18564
- const filter = toolFilters?.get(conn.config.namespace);
18565
- for (const tool of conn.tools) {
18566
- if (filter && !filter.has(tool.name)) continue;
18567
- if (isDenied?.(tool.namespacedName)) continue;
18568
- if (seen.has(tool.namespacedName)) continue;
18569
- tools.push({
18570
- name: tool.namespacedName,
18571
- title: tool.title,
18572
- description: tool.description,
18573
- inputSchema: tool.inputSchema,
18574
- outputSchema: tool.outputSchema,
18575
- annotations: tool.annotations,
18576
- _meta: tool._meta
18577
- });
18578
- seen.add(tool.namespacedName);
18579
- }
18580
- }
18581
- for (const server of serversInOrder(inactiveWithCache)) {
18582
- if (activeConnections.has(server.namespace)) continue;
18583
- if (!server.toolCache || server.toolCache.length === 0) continue;
18584
- if (exposure !== "full") continue;
18585
- const filter = toolFilters?.get(server.namespace);
18586
- for (const cached of server.toolCache) {
18587
- if (filter && !filter.has(cached.name)) continue;
18588
- const namespacedName = `${server.namespace}_${cached.name}`;
18589
- if (isDenied?.(namespacedName)) continue;
18590
- if (seen.has(namespacedName)) continue;
18591
- tools.push({
18592
- name: namespacedName,
18593
- description: deferredDescription(server, cached.description),
18594
- inputSchema: DEFERRED_INPUT_SCHEMA
18595
- });
18596
- seen.add(namespacedName);
18597
- }
18598
- }
18599
- return tools;
18600
- }
18601
- function buildToolRoutes(activeConnections, inactiveWithCache = [], quiet = false) {
18602
- const routes = /* @__PURE__ */ new Map();
18603
- for (const conn of connectionsInOrder(activeConnections)) {
18604
- for (const tool of conn.tools) {
18605
- const existing = routes.get(tool.namespacedName);
18606
- if (existing && existing.namespace !== conn.config.namespace) {
18607
- if (!quiet) {
18608
- log("warn", "Tool route collision; keeping the first upstream, ignoring the later one", {
18609
- tool: tool.namespacedName,
18610
- keptNamespace: existing.namespace,
18611
- ignoredNamespace: conn.config.namespace
18612
- });
18613
- }
18614
- continue;
18615
- }
18616
- routes.set(tool.namespacedName, {
18617
- namespace: conn.config.namespace,
18618
- originalName: tool.name
18619
- });
18620
- }
18621
- }
18622
- for (const server of serversInOrder(inactiveWithCache)) {
18623
- if (activeConnections.has(server.namespace)) continue;
18624
- if (!server.toolCache || server.toolCache.length === 0) continue;
18625
- for (const cached of server.toolCache) {
18626
- const namespacedName = `${server.namespace}_${cached.name}`;
18627
- const existing = routes.get(namespacedName);
18628
- if (existing) {
18629
- if (!quiet && existing.deferred && existing.namespace !== server.namespace) {
18630
- log("warn", "Deferred tool route collision; earlier cached server wins", {
18631
- tool: namespacedName,
18632
- winningNamespace: existing.namespace,
18633
- shadowedNamespace: server.namespace
18634
- });
18635
- }
18636
- continue;
18637
- }
18638
- routes.set(namespacedName, {
18639
- namespace: server.namespace,
18640
- originalName: cached.name,
18641
- deferred: true
18642
- });
18839
+ routes.set(namespacedName, {
18840
+ namespace: server.namespace,
18841
+ originalName: cached.name,
18842
+ deferred: true
18843
+ });
18643
18844
  }
18644
18845
  }
18645
18846
  return routes;
@@ -18737,138 +18938,389 @@ async function routeResourceRead(uri, resourceRoutes, activeConnections, builtin
18737
18938
  return { contents: [{ uri, text: `Error: ${message}` }] };
18738
18939
  }
18739
18940
  }
18740
- const route = resourceRoutes.get(uri);
18741
- if (!route) {
18742
- return { contents: [{ uri, text: `Unknown resource: ${uri}` }] };
18743
- }
18744
- const connection = activeConnections.get(route.namespace);
18745
- if (connection?.status !== "connected") {
18746
- return { contents: [{ uri, text: `Server "${route.namespace}" is not connected.` }] };
18747
- }
18748
- try {
18749
- const result = await connection.client.readResource({ uri: route.originalUri });
18750
- return {
18751
- ...result,
18752
- contents: (result.contents ?? []).map((c) => ({ ...c, uri: `connect://${route.namespace}/${c.uri}` }))
18753
- };
18754
- } catch (err) {
18755
- const message = err instanceof Error ? err.message : String(err);
18756
- log("error", "Resource read failed", { uri, namespace: route.namespace, error: scrubForWarning(message) });
18757
- return { contents: [{ uri, text: `Error: ${message}` }] };
18758
- }
18941
+ const route = resourceRoutes.get(uri);
18942
+ if (!route) {
18943
+ return { contents: [{ uri, text: `Unknown resource: ${uri}` }] };
18944
+ }
18945
+ const connection = activeConnections.get(route.namespace);
18946
+ if (connection?.status !== "connected") {
18947
+ return { contents: [{ uri, text: `Server "${route.namespace}" is not connected.` }] };
18948
+ }
18949
+ try {
18950
+ const result = await connection.client.readResource({ uri: route.originalUri });
18951
+ return {
18952
+ ...result,
18953
+ contents: (result.contents ?? []).map((c) => ({ ...c, uri: `connect://${route.namespace}/${c.uri}` }))
18954
+ };
18955
+ } catch (err) {
18956
+ const message = err instanceof Error ? err.message : String(err);
18957
+ log("error", "Resource read failed", { uri, namespace: route.namespace, error: scrubForWarning(message) });
18958
+ return { contents: [{ uri, text: `Error: ${message}` }] };
18959
+ }
18960
+ }
18961
+ async function routePromptGet(name, args, promptRoutes, activeConnections) {
18962
+ const route = promptRoutes.get(name);
18963
+ if (!route) {
18964
+ return { messages: [{ role: "user", content: { type: "text", text: `Unknown prompt: ${name}` } }] };
18965
+ }
18966
+ const connection = activeConnections.get(route.namespace);
18967
+ if (connection?.status !== "connected") {
18968
+ return {
18969
+ messages: [{ role: "user", content: { type: "text", text: `Server "${route.namespace}" is not connected.` } }]
18970
+ };
18971
+ }
18972
+ try {
18973
+ const result = await connection.client.getPrompt({ name: route.originalName, arguments: args });
18974
+ return result;
18975
+ } catch (err) {
18976
+ const message = err instanceof Error ? err.message : String(err);
18977
+ log("error", "Prompt get failed", { name, namespace: route.namespace, error: scrubForWarning(message) });
18978
+ return { messages: [{ role: "user", content: { type: "text", text: `Error: ${message}` } }] };
18979
+ }
18980
+ }
18981
+ var ROUTING_FAULT_BRAND = /* @__PURE__ */ Symbol("yaw-mcp:routing-fault");
18982
+ function brandRoutingFault(result) {
18983
+ Object.defineProperty(result, ROUTING_FAULT_BRAND, { value: true, enumerable: false });
18984
+ return result;
18985
+ }
18986
+ var CANCELLED_BRAND = /* @__PURE__ */ Symbol("yaw-mcp:cancelled");
18987
+ function brandCancelled(result) {
18988
+ Object.defineProperty(result, CANCELLED_BRAND, { value: true, enumerable: false });
18989
+ return result;
18990
+ }
18991
+ function isCancelledResult(result) {
18992
+ return typeof result === "object" && result !== null && result[CANCELLED_BRAND] === true;
18993
+ }
18994
+ function isRoutingFaultResult(result) {
18995
+ return typeof result === "object" && result !== null && result[ROUTING_FAULT_BRAND] === true;
18996
+ }
18997
+ var callTimeoutMs;
18998
+ function callTimeout() {
18999
+ callTimeoutMs ??= resolveTimeoutEnv("MCP_CALL_TIMEOUT", 6e4);
19000
+ return callTimeoutMs;
19001
+ }
19002
+ async function routeToolCall(toolName, args, toolRoutes, activeConnections, options) {
19003
+ const route = toolRoutes.get(toolName);
19004
+ if (!route) {
19005
+ return brandRoutingFault({
19006
+ content: [
19007
+ {
19008
+ type: "text",
19009
+ text: `Unknown tool: ${toolName}. Use mcp_connect_discover to see available servers, then mcp_connect_activate to load tools.`
19010
+ }
19011
+ ],
19012
+ isError: true
19013
+ });
19014
+ }
19015
+ const connection = activeConnections.get(route.namespace);
19016
+ if (connection?.status !== "connected") {
19017
+ return brandRoutingFault({
19018
+ content: [
19019
+ {
19020
+ type: "text",
19021
+ text: `Server "${route.namespace}" is no longer connected. Use mcp_connect_activate with server "${route.namespace}" to reconnect.`
19022
+ }
19023
+ ],
19024
+ isError: true
19025
+ });
19026
+ }
19027
+ try {
19028
+ const result = await connection.client.callTool(
19029
+ {
19030
+ name: route.originalName,
19031
+ arguments: args
19032
+ },
19033
+ // The second argument is the RESULT SCHEMA, not the options: passing the
19034
+ // options object there would silently replace CallToolResultSchema and
19035
+ // take the SDK's structured-output validation with it. `undefined` keeps
19036
+ // the SDK default; the request options belong in the third slot.
19037
+ void 0,
19038
+ // `signal` and `onprogress` are passed straight through, undefined and
19039
+ // all: the SDK guards both (`options?.signal?.throwIfAborted()`, and
19040
+ // `if (options?.onprogress)` before it registers a token), so an absent
19041
+ // one is inert and needs no conditional spread here.
19042
+ //
19043
+ // `resetTimeoutOnProgress` is deliberately NOT set. It would let a
19044
+ // progress-reporting upstream push past CALL_TIMEOUT indefinitely,
19045
+ // which is a change to how long a call may run -- a separate decision
19046
+ // from restoring the two signals the client already sent, and one that
19047
+ // wants its own bound (maxTotalTimeout) rather than riding in here.
19048
+ { timeout: callTimeout(), signal: options?.signal, onprogress: options?.onprogress }
19049
+ );
19050
+ return result;
19051
+ } catch (err) {
19052
+ const message = err instanceof Error ? err.message : String(err);
19053
+ const code = err && typeof err === "object" && "code" in err && typeof err.code === "number" ? err.code : void 0;
19054
+ if (options?.signal?.aborted) {
19055
+ log("info", "Tool call cancelled by the client", { tool: toolName, namespace: route.namespace });
19056
+ return brandCancelled({
19057
+ content: [{ type: "text", text: `Call to ${toolName} was cancelled by the client.` }],
19058
+ isError: true
19059
+ });
19060
+ }
19061
+ log("error", "Tool call failed", {
19062
+ tool: toolName,
19063
+ namespace: route.namespace,
19064
+ error: scrubForWarning(message),
19065
+ code
19066
+ });
19067
+ const codeTag = code !== void 0 ? ` [code=${code}]` : "";
19068
+ return {
19069
+ content: [{ type: "text", text: `Error calling ${toolName}${codeTag}: ${message}` }],
19070
+ isError: true
19071
+ };
19072
+ }
19073
+ }
19074
+
19075
+ // src/installed-summary.ts
19076
+ var INSTALLED_LINE_MAX_CHARS = 800;
19077
+ var TIERS = [
19078
+ { words: 4, shadow: true },
19079
+ { words: 3, shadow: true },
19080
+ { words: 2, shadow: true },
19081
+ { words: 1, shadow: true },
19082
+ { words: 0, shadow: true },
19083
+ { words: 0, shadow: false }
19084
+ ];
19085
+ var FILLER = new Set(
19086
+ "the and for are that this with what which how does from into about can any all some when where you your our its their them they via using use through over also just only more most other get list create update delete search set add remove read write run find fetch query info new edit covering manage management configure execute talk directly provide provides access tool tools server servers mcp assistant assistants model models intelligence development data date demand pulled up-to-date".split(" ")
19087
+ );
19088
+ var CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/g;
19089
+ function serverKeywords(server) {
19090
+ const ns = server.namespace.toLowerCase();
19091
+ const source = server.description ? server.description : [server.name ?? "", ...(server.toolCache ?? []).map((t) => t.name)].join(" ");
19092
+ const out = [];
19093
+ for (const raw of source.replace(CONTROL_CHARS, " ").toLowerCase().split(/[^a-z0-9]+/)) {
19094
+ if (raw.length < 3 || /^[0-9]+$/.test(raw) || FILLER.has(raw) || raw === ns) continue;
19095
+ const singular = raw.endsWith("s") ? raw.slice(0, -1) : raw;
19096
+ if (out.includes(raw) || out.includes(singular) || out.includes(`${raw}s`)) continue;
19097
+ out.push(raw);
19098
+ }
19099
+ return out;
19100
+ }
19101
+ function formatInstalledEntry(server, words = TIERS[0].words, shadow = true) {
19102
+ const keywords = words > 0 ? serverKeywords(server).slice(0, words) : [];
19103
+ const clis = shadow ? resolveShadowedClis(server).map((s) => `\`${s.cli}\``) : [];
19104
+ const parts = [keywords.join(", "), clis.length > 0 ? `over ${clis.join(", ")}` : ""].filter(Boolean);
19105
+ return parts.length > 0 ? `${server.namespace} (${parts.join("; ")})` : server.namespace;
19106
+ }
19107
+ function formatInstalledServers(servers, maxChars = INSTALLED_LINE_MAX_CHARS) {
19108
+ if (servers.length === 0) return null;
19109
+ const sorted = [...servers].sort((a, b) => compareNamespaces(a.namespace, b.namespace));
19110
+ const head = "Installed servers: ";
19111
+ for (const tier of TIERS) {
19112
+ const line2 = `${head}${sorted.map((s) => formatInstalledEntry(s, tier.words, tier.shadow)).join(", ")}.`;
19113
+ if (line2.length <= maxChars) return line2;
19114
+ }
19115
+ const more = (n) => ` +${n} more (mcp_connect_discover lists all).`;
19116
+ let line = head;
19117
+ let shown = 0;
19118
+ for (const server of sorted) {
19119
+ const sep2 = shown === 0 ? "" : ", ";
19120
+ const reserve = more(sorted.length - shown - 1).length;
19121
+ if (line.length + sep2.length + server.namespace.length + reserve > maxChars) break;
19122
+ line += sep2 + server.namespace;
19123
+ shown++;
19124
+ }
19125
+ if (shown === 0) return `${head}${sorted.length} (mcp_connect_discover lists them).`;
19126
+ return line + more(sorted.length - shown);
19127
+ }
19128
+ function withInstalledServers(tools, line, exposure) {
19129
+ if (!line) return tools;
19130
+ const target = exposure === "lite" ? META_TOOLS.findTool.name : META_TOOLS.dispatch.name;
19131
+ return tools.map((t) => t.name === target ? { ...t, description: `${t.description ?? ""} ${line}`.trim() } : t);
19132
+ }
19133
+
19134
+ // src/pack-detect.ts
19135
+ var DEFAULT_MAX_HISTORY = 100;
19136
+ var DEFAULT_MAX_GAP_MS = 12e4;
19137
+ var MIN_NAMESPACES = 2;
19138
+ var MAX_NAMESPACES = 3;
19139
+ var MIN_RECURRENCES = 2;
19140
+ var BURST_SPAN_FACTOR = 5;
19141
+ function packIdFromNamespaces(namespaces) {
19142
+ return Array.from(new Set(namespaces)).sort().join("|");
19143
+ }
19144
+ var PackDetector = class {
19145
+ maxHistory;
19146
+ maxGapMs;
19147
+ history = [];
19148
+ constructor(options = {}) {
19149
+ this.maxHistory = options.maxHistory ?? DEFAULT_MAX_HISTORY;
19150
+ this.maxGapMs = options.maxGapMs ?? DEFAULT_MAX_GAP_MS;
19151
+ }
19152
+ recordCall(namespace, toolName, at) {
19153
+ if (!namespace || !toolName) return;
19154
+ if (typeof at !== "number" || !Number.isFinite(at)) return;
19155
+ this.history.push({ namespace, toolName, at });
19156
+ if (this.history.length > this.maxHistory) {
19157
+ const overflow = this.history.length - this.maxHistory;
19158
+ this.history = this.history.slice(overflow);
19159
+ }
19160
+ }
19161
+ // Walk the history, segmenting it into "bursts" (see segmentBursts for
19162
+ // the three boundaries). Each burst with ≥2 distinct namespaces is a
19163
+ // candidate pack. A pack is returned when the same namespace set
19164
+ // appears in ≥MIN_RECURRENCES bursts.
19165
+ detectChains() {
19166
+ if (this.history.length < 2) return [];
19167
+ const bursts = this.segmentBursts();
19168
+ const packCounts = /* @__PURE__ */ new Map();
19169
+ for (const burst of bursts) {
19170
+ if (burst.namespaces.length < MIN_NAMESPACES) continue;
19171
+ if (burst.namespaces.length > MAX_NAMESPACES) continue;
19172
+ const id = packIdFromNamespaces(burst.namespaces);
19173
+ const prev = packCounts.get(id);
19174
+ if (prev) {
19175
+ prev.frequency += 1;
19176
+ if (burst.lastAt > prev.lastSeenAt) prev.lastSeenAt = burst.lastAt;
19177
+ } else {
19178
+ packCounts.set(id, {
19179
+ namespaces: [...burst.namespaces],
19180
+ frequency: 1,
19181
+ lastSeenAt: burst.lastAt
19182
+ });
19183
+ }
19184
+ }
19185
+ const packs = [];
19186
+ for (const entry of packCounts.values()) {
19187
+ if (entry.frequency >= MIN_RECURRENCES) {
19188
+ packs.push({
19189
+ namespaces: entry.namespaces,
19190
+ frequency: entry.frequency,
19191
+ lastSeenAt: entry.lastSeenAt
19192
+ });
19193
+ }
19194
+ }
19195
+ return packs;
19196
+ }
19197
+ // Segment the call history into bursts. A new burst starts whenever:
19198
+ // 1. the gap to the previous call exceeds maxGapMs (idle boundary);
19199
+ // 2. the burst has already spanned maxGapMs * BURST_SPAN_FACTOR
19200
+ // (span boundary -- see the constant for why a continuous session
19201
+ // must be sliced for recurrence to be countable); or
19202
+ // 3. the call would add a namespace past MAX_NAMESPACES (overflow
19203
+ // boundary). detectChains drops an over-wide burst entirely, so
19204
+ // without this cut a single visit to a 4th namespace poisoned the
19205
+ // whole burst and the recurring trio inside it was never counted.
19206
+ // Cutting at the overflow keeps each burst representable as a
19207
+ // pack; a wider rotation surfaces as its recurring 3-subsets, the
19208
+ // best answer the MAX_NAMESPACES pack-size cap can express. SLOWLY,
19209
+ // though: the cuts walk the rotation, so each 3-subset recurs only
19210
+ // once per full pass over it. A strict a,b,c,d loop segments as
19211
+ // [a,b,c] [d,a,b] [c,d,a] [b,c,d] [a,b,c] ..., and {a,b,c} reaches
19212
+ // MIN_RECURRENCES at the 15th call -- all of which must land inside
19213
+ // one span window and one maxGapMs cadence.
19214
+ // Within a burst, each namespace is recorded only once
19215
+ // (order-of-first-appearance); the "last seen" timestamp tracks the
19216
+ // most recent call in the burst so recency ranking is truthful even
19217
+ // when the burst has many calls.
19218
+ segmentBursts() {
19219
+ const bursts = [];
19220
+ const maxBurstSpanMs = this.maxGapMs * BURST_SPAN_FACTOR;
19221
+ let current = null;
19222
+ let prevAt = 0;
19223
+ for (const call of this.history) {
19224
+ const gapExceeded = call.at - prevAt > this.maxGapMs;
19225
+ const spanExceeded = current !== null && call.at - current.startAt > maxBurstSpanMs;
19226
+ const wentBackwards = current !== null && call.at < prevAt;
19227
+ const wouldOverflow = current !== null && current.namespaces.length >= MAX_NAMESPACES && !current.namespaces.includes(call.namespace);
19228
+ if (!current || gapExceeded || spanExceeded || wentBackwards || wouldOverflow) {
19229
+ current = { namespaces: [call.namespace], startAt: call.at, lastAt: call.at };
19230
+ bursts.push(current);
19231
+ } else {
19232
+ if (!current.namespaces.includes(call.namespace)) {
19233
+ current.namespaces.push(call.namespace);
19234
+ }
19235
+ current.lastAt = call.at;
19236
+ }
19237
+ prevAt = call.at;
19238
+ }
19239
+ return bursts;
19240
+ }
19241
+ // Exposed for tests.
19242
+ getHistory() {
19243
+ return this.history;
19244
+ }
19245
+ reset() {
19246
+ this.history = [];
19247
+ }
19248
+ // Return a defensive copy of history for persistence. Each entry is a
19249
+ // fresh object, safe to JSON.stringify without worrying about later
19250
+ // mutations to the detector's internal array.
19251
+ exportSnapshot() {
19252
+ return this.history.map((c) => ({ namespace: c.namespace, toolName: c.toolName, at: c.at }));
19253
+ }
19254
+ // Replace in-memory history with the given snapshot. Respects the
19255
+ // configured maxHistory cap — if the snapshot exceeds it, the oldest
19256
+ // entries are dropped, matching the cap behavior of recordCall.
19257
+ //
19258
+ // Entries are SORTED by `at` after cleaning. segmentBursts reads the history
19259
+ // as a time-ordered stream (see the boundary comparisons there), and the
19260
+ // snapshot comes off disk where a hand-edited, merged or torn file can carry
19261
+ // entries out of order; an out-of-order run would otherwise be segmented as
19262
+ // one welded burst plus spurious boundaries. Sorting is stable, so equal
19263
+ // timestamps keep their recorded order.
19264
+ //
19265
+ // `at` is validated as a finite number, not just present: the snapshot
19266
+ // comes off disk (persistence.ts) where a hand-edited or torn file can
19267
+ // carry null / "12345" / NaN. segmentBursts compares `call.at - prevAt >
19268
+ // maxGapMs`, and every comparison against NaN is false, so a single NaN
19269
+ // timestamp silently welds the whole history into one giant burst and
19270
+ // manufactures packs that never happened.
19271
+ loadSnapshot(snapshot) {
19272
+ const clean = [];
19273
+ for (const c of snapshot) {
19274
+ if (!c?.namespace || !c.toolName) continue;
19275
+ if (typeof c.at !== "number" || !Number.isFinite(c.at)) continue;
19276
+ clean.push({ namespace: c.namespace, toolName: c.toolName, at: c.at });
19277
+ }
19278
+ clean.sort((a, b) => a.at - b.at);
19279
+ if (clean.length > this.maxHistory) {
19280
+ this.history = clean.slice(clean.length - this.maxHistory);
19281
+ } else {
19282
+ this.history = clean;
19283
+ }
19284
+ }
19285
+ };
19286
+
19287
+ // src/progress.ts
19288
+ function isProgressRequested(ctx) {
19289
+ const token = ctx?.mcpReq?._meta?.progressToken;
19290
+ return token !== void 0 && token !== null && typeof ctx?.mcpReq?.notify === "function";
18759
19291
  }
18760
- async function routePromptGet(name, args, promptRoutes, activeConnections) {
18761
- const route = promptRoutes.get(name);
18762
- if (!route) {
18763
- return { messages: [{ role: "user", content: { type: "text", text: `Unknown prompt: ${name}` } }] };
18764
- }
18765
- const connection = activeConnections.get(route.namespace);
18766
- if (connection?.status !== "connected") {
18767
- return {
18768
- messages: [{ role: "user", content: { type: "text", text: `Server "${route.namespace}" is not connected.` } }]
19292
+ function createProgressReporter(ctx) {
19293
+ if (!isProgressRequested(ctx)) {
19294
+ return () => {
18769
19295
  };
18770
19296
  }
18771
- try {
18772
- const result = await connection.client.getPrompt({ name: route.originalName, arguments: args });
18773
- return result;
18774
- } catch (err) {
18775
- const message = err instanceof Error ? err.message : String(err);
18776
- log("error", "Prompt get failed", { name, namespace: route.namespace, error: scrubForWarning(message) });
18777
- return { messages: [{ role: "user", content: { type: "text", text: `Error: ${message}` } }] };
18778
- }
18779
- }
18780
- var ROUTING_FAULT_BRAND = /* @__PURE__ */ Symbol("yaw-mcp:routing-fault");
18781
- function brandRoutingFault(result) {
18782
- Object.defineProperty(result, ROUTING_FAULT_BRAND, { value: true, enumerable: false });
18783
- return result;
18784
- }
18785
- var CANCELLED_BRAND = /* @__PURE__ */ Symbol("yaw-mcp:cancelled");
18786
- function brandCancelled(result) {
18787
- Object.defineProperty(result, CANCELLED_BRAND, { value: true, enumerable: false });
18788
- return result;
18789
- }
18790
- function isCancelledResult(result) {
18791
- return typeof result === "object" && result !== null && result[CANCELLED_BRAND] === true;
18792
- }
18793
- function isRoutingFaultResult(result) {
18794
- return typeof result === "object" && result !== null && result[ROUTING_FAULT_BRAND] === true;
18795
- }
18796
- var callTimeoutMs;
18797
- function callTimeout() {
18798
- callTimeoutMs ??= resolveTimeoutEnv("MCP_CALL_TIMEOUT", 6e4);
18799
- return callTimeoutMs;
18800
- }
18801
- async function routeToolCall(toolName, args, toolRoutes, activeConnections, options) {
18802
- const route = toolRoutes.get(toolName);
18803
- if (!route) {
18804
- return brandRoutingFault({
18805
- content: [
18806
- {
18807
- type: "text",
18808
- text: `Unknown tool: ${toolName}. Use mcp_connect_discover to see available servers, then mcp_connect_activate to load tools.`
18809
- }
18810
- ],
18811
- isError: true
18812
- });
18813
- }
18814
- const connection = activeConnections.get(route.namespace);
18815
- if (connection?.status !== "connected") {
18816
- return brandRoutingFault({
18817
- content: [
18818
- {
18819
- type: "text",
18820
- text: `Server "${route.namespace}" is no longer connected. Use mcp_connect_activate with server "${route.namespace}" to reconnect.`
18821
- }
18822
- ],
18823
- isError: true
18824
- });
18825
- }
18826
- try {
18827
- const result = await connection.client.callTool(
18828
- {
18829
- name: route.originalName,
18830
- arguments: args
18831
- },
18832
- // The second argument is the RESULT SCHEMA, not the options: passing the
18833
- // options object there would silently replace CallToolResultSchema and
18834
- // take the SDK's structured-output validation with it. `undefined` keeps
18835
- // the SDK default; the request options belong in the third slot.
18836
- void 0,
18837
- // `signal` and `onprogress` are passed straight through, undefined and
18838
- // all: the SDK guards both (`options?.signal?.throwIfAborted()`, and
18839
- // `if (options?.onprogress)` before it registers a token), so an absent
18840
- // one is inert and needs no conditional spread here.
18841
- //
18842
- // `resetTimeoutOnProgress` is deliberately NOT set. It would let a
18843
- // progress-reporting upstream push past CALL_TIMEOUT indefinitely,
18844
- // which is a change to how long a call may run -- a separate decision
18845
- // from restoring the two signals the client already sent, and one that
18846
- // wants its own bound (maxTotalTimeout) rather than riding in here.
18847
- { timeout: callTimeout(), signal: options?.signal, onprogress: options?.onprogress }
18848
- );
18849
- return result;
18850
- } catch (err) {
18851
- const message = err instanceof Error ? err.message : String(err);
18852
- const code = err && typeof err === "object" && "code" in err && typeof err.code === "number" ? err.code : void 0;
18853
- if (options?.signal?.aborted) {
18854
- log("info", "Tool call cancelled by the client", { tool: toolName, namespace: route.namespace });
18855
- return brandCancelled({
18856
- content: [{ type: "text", text: `Call to ${toolName} was cancelled by the client.` }],
18857
- isError: true
18858
- });
19297
+ const token = ctx?.mcpReq?._meta?.progressToken;
19298
+ const send = ctx?.mcpReq?.notify;
19299
+ const EPSILON = 1e-3;
19300
+ let lastEmitted = -EPSILON;
19301
+ return (message, progress, total) => {
19302
+ let emitted;
19303
+ let emittedTotal;
19304
+ if (progress !== void 0) {
19305
+ emitted = progress > lastEmitted ? progress : lastEmitted + EPSILON;
19306
+ emittedTotal = total !== void 0 && emitted <= total ? total : void 0;
19307
+ } else {
19308
+ emitted = lastEmitted + EPSILON;
19309
+ emittedTotal = void 0;
18859
19310
  }
18860
- log("error", "Tool call failed", {
18861
- tool: toolName,
18862
- namespace: route.namespace,
18863
- error: scrubForWarning(message),
18864
- code
18865
- });
18866
- const codeTag = code !== void 0 ? ` [code=${code}]` : "";
18867
- return {
18868
- content: [{ type: "text", text: `Error calling ${toolName}${codeTag}: ${message}` }],
18869
- isError: true
19311
+ const params = {
19312
+ progressToken: token,
19313
+ progress: emitted,
19314
+ message
18870
19315
  };
18871
- }
19316
+ if (emittedTotal !== void 0) params.total = emittedTotal;
19317
+ lastEmitted = emitted;
19318
+ send({ method: "notifications/progress", params }).catch((err) => {
19319
+ log("warn", "Progress notification send failed", {
19320
+ error: err instanceof Error ? err.message : String(err)
19321
+ });
19322
+ });
19323
+ };
18872
19324
  }
18873
19325
 
18874
19326
  // src/prune.ts
@@ -19826,10 +20278,10 @@ function evaluateServerCap(namespace, loaded, cap, context = {}) {
19826
20278
  if (b.idleCount !== a.idleCount) return b.idleCount - a.idleCount;
19827
20279
  return a.namespace.localeCompare(b.namespace);
19828
20280
  });
19829
- const list = sorted.map(describeSlot).join(", ");
20281
+ const list2 = sorted.map(describeSlot).join(", ");
19830
20282
  return {
19831
20283
  allow: false,
19832
- message: `Cannot load "${namespace}" \u2014 already at the ${cap}-server concurrent cap. Loaded: ${list}. Free a slot with mcp_connect_deactivate, or use mcp_connect_read_tool to inspect one tool without loading its server. Ops can change the limit via YAW_MCP_SERVER_CAP.`
20284
+ message: `Cannot load "${namespace}" \u2014 already at the ${cap}-server concurrent cap. Loaded: ${list2}. Free a slot with mcp_connect_deactivate, or use mcp_connect_read_tool to inspect one tool without loading its server. Ops can change the limit via YAW_MCP_SERVER_CAP.`
19833
20285
  };
19834
20286
  }
19835
20287
  function describeSlot(s) {
@@ -19845,9 +20297,9 @@ function tokenRefusal(namespace, loaded, candidateTokens, loadedTokens, tokenCap
19845
20297
  if (bt !== at) return bt - at;
19846
20298
  return a.namespace.localeCompare(b.namespace);
19847
20299
  });
19848
- const list = sorted.map(describeSlot).join(", ");
20300
+ const list2 = sorted.map(describeSlot).join(", ");
19849
20301
  const over = loadedTokens + candidateTokens - tokenCap;
19850
- return `Cannot load "${namespace}" \u2014 its ~${candidateTokens} tokens of tools would put the loaded surface at ~${loadedTokens + candidateTokens}, over the ~${tokenCap}-token ceiling by ~${over}. Loaded, most expensive first: ${list}. Free the budget with mcp_connect_deactivate, or use mcp_connect_read_tool to inspect one tool without loading its server. Ops can change the limit via YAW_MCP_TOOL_TOKEN_CAP.`;
20302
+ return `Cannot load "${namespace}" \u2014 its ~${candidateTokens} tokens of tools would put the loaded surface at ~${loadedTokens + candidateTokens}, over the ~${tokenCap}-token ceiling by ~${over}. Loaded, most expensive first: ${list2}. Free the budget with mcp_connect_deactivate, or use mcp_connect_read_tool to inspect one tool without loading its server. Ops can change the limit via YAW_MCP_TOOL_TOKEN_CAP.`;
19851
20303
  }
19852
20304
 
19853
20305
  // src/server.ts
@@ -19943,6 +20395,116 @@ function resolveIdleThreshold() {
19943
20395
  function isAutoActivateEnabled() {
19944
20396
  return !isFeatureDisabled("YAW_MCP_AUTO_ACTIVATE");
19945
20397
  }
20398
+ var AUTO_ACTIVATE_MIN_SCORE_BM25 = 1;
20399
+ var AUTO_ACTIVATE_MARGIN_BM25 = 1.3;
20400
+ var AUTO_ACTIVATE_MIN_COVERAGE = 0.38;
20401
+ var AUTO_ACTIVATE_COVERAGE_MIN_SERVERS = 5;
20402
+ function pickAutoWarmWinner(ranked) {
20403
+ const top = ranked[0];
20404
+ const second = ranked[1];
20405
+ const topWinsDecisively = top !== void 0 && top.score >= AUTO_ACTIVATE_MIN_SCORE_BM25 && (top.coverage === void 0 || top.coverage >= AUTO_ACTIVATE_MIN_COVERAGE) && (second === void 0 || top.score / (second.score || 1e-6) >= AUTO_ACTIVATE_MARGIN_BM25);
20406
+ return topWinsDecisively ? top : void 0;
20407
+ }
20408
+ var DISPATCH_MAX_FALLBACKS = 2;
20409
+ function runnerUpCanReplace(failed, next) {
20410
+ if (next.score * AUTO_ACTIVATE_MARGIN_BM25 < failed.score) return false;
20411
+ return !coverageIsLow(failed, failed.score / (next.score || 1e-6));
20412
+ }
20413
+ var CONFIDENCE_NOTE_RUNNERS_UP = 2;
20414
+ var DISPATCH_LOW_COVERAGE_MARGIN = 2;
20415
+ function coverageIsLow(pick, lead) {
20416
+ return pick.coverage !== void 0 && pick.coverage < AUTO_ACTIVATE_MIN_COVERAGE && ((pick.matched ?? 0) <= 1 || lead < DISPATCH_LOW_COVERAGE_MARGIN);
20417
+ }
20418
+ function dispatchConfidenceNote(ranked, loaded, loadedSet, opts) {
20419
+ const pick = ranked.find((r) => r.namespace === loaded);
20420
+ if (!pick) return void 0;
20421
+ const others = ranked.filter((r) => !loadedSet.has(r.namespace) && r.score > 0);
20422
+ const best = others[0];
20423
+ const reasons = [];
20424
+ const lead = best === void 0 ? Number.POSITIVE_INFINITY : pick.score / (best.score || 1e-6);
20425
+ if (!opts.sampled && lead < AUTO_ACTIVATE_MARGIN_BM25) {
20426
+ reasons.push(
20427
+ `close call (${best.namespace} scored ${best.score.toFixed(2)} vs ${pick.score.toFixed(2)}${opts.noSampling ? "; this client cannot be asked to break the tie" : ""})`
20428
+ );
20429
+ }
20430
+ if (coverageIsLow(pick, lead)) {
20431
+ reasons.push(
20432
+ pick.contentTerms !== void 0 && pick.contentTerms > 0 ? `${loaded} matches ${pick.matched} of the request's ${pick.contentTerms} content words` : `the request has no content words to match`
20433
+ );
20434
+ }
20435
+ if (reasons.length === 0) return void 0;
20436
+ const runners = others.slice(0, CONFIDENCE_NOTE_RUNNERS_UP).map((r) => `${r.namespace} (${r.score.toFixed(2)})`).join(", ");
20437
+ return `Low confidence: ${reasons.join("; ")}.${runners ? ` Runners-up: ${runners}.` : ""} If ${loaded} does not fit, mcp_connect_activate a runner-up or dispatch a more specific intent; if the request needs no tool, answer it directly.`;
20438
+ }
20439
+ var DISPATCH_TOOL_HINTS = 3;
20440
+ var SIGNATURE_MAX_ARGS = 8;
20441
+ function isPlainObject2(v) {
20442
+ return v !== null && typeof v === "object" && !Array.isArray(v);
20443
+ }
20444
+ function schemaTypeLabel(prop) {
20445
+ if (!isPlainObject2(prop)) return "any";
20446
+ const t = prop.type;
20447
+ if (typeof t === "string") {
20448
+ if (t === "array" && isPlainObject2(prop.items) && typeof prop.items.type === "string")
20449
+ return `${prop.items.type}[]`;
20450
+ return t;
20451
+ }
20452
+ if (Array.isArray(t)) {
20453
+ const types = t.filter((x) => typeof x === "string" && x !== "null");
20454
+ if (types.length > 0) return types.join("|");
20455
+ }
20456
+ const union = Array.isArray(prop.anyOf) ? prop.anyOf : Array.isArray(prop.oneOf) ? prop.oneOf : void 0;
20457
+ if (union) {
20458
+ const labels = [...new Set(union.map(schemaTypeLabel).filter((l) => l !== "null"))];
20459
+ if (labels.length > 0) return labels.join("|");
20460
+ }
20461
+ if (Array.isArray(prop.enum)) return "enum";
20462
+ return "any";
20463
+ }
20464
+ function formatToolSignature(name, inputSchema, maxArgs = SIGNATURE_MAX_ARGS) {
20465
+ const schema = isPlainObject2(inputSchema) ? inputSchema : {};
20466
+ const props = isPlainObject2(schema.properties) ? schema.properties : {};
20467
+ const required = Array.isArray(schema.required) ? [...new Set(schema.required.filter((k) => typeof k === "string"))] : [];
20468
+ const optional = Object.keys(props).filter((k) => !required.includes(k));
20469
+ const args = [
20470
+ ...required.map((k) => `${k}: ${schemaTypeLabel(props[k])}`),
20471
+ ...optional.map((k) => `${k}?: ${schemaTypeLabel(props[k])}`)
20472
+ ];
20473
+ const shown = args.slice(0, maxArgs);
20474
+ if (args.length > shown.length) shown.push(`+${args.length - shown.length} more`);
20475
+ return `${name}(${shown.join(", ")})`;
20476
+ }
20477
+ var SCHEMA_COMPOSITION_KEYS = [
20478
+ "allOf",
20479
+ "anyOf",
20480
+ "oneOf",
20481
+ "$ref",
20482
+ "if",
20483
+ "dependencies",
20484
+ "dependentSchemas",
20485
+ "patternProperties",
20486
+ "unevaluatedProperties"
20487
+ ];
20488
+ function checkToolArgs(inputSchema, args) {
20489
+ if (!isPlainObject2(inputSchema)) return null;
20490
+ const props = isPlainObject2(inputSchema.properties) ? inputSchema.properties : void 0;
20491
+ const required = Array.isArray(inputSchema.required) ? inputSchema.required.filter((k) => typeof k === "string") : [];
20492
+ const has = (k) => Object.hasOwn(args, k);
20493
+ const missing = required.filter((k) => !has(k));
20494
+ const additional = inputSchema.additionalProperties;
20495
+ const listsKeys = props !== void 0 && Object.keys(props).length > 0 && (additional === void 0 || additional === false) && !SCHEMA_COMPOSITION_KEYS.some((k) => k in inputSchema);
20496
+ const unknownKeys = listsKeys ? Object.keys(args).filter((k) => !Object.hasOwn(props, k)) : [];
20497
+ if (missing.length === 0 && (additional !== false || unknownKeys.length === 0)) return null;
20498
+ const unsupplied = Object.keys(props ?? {}).filter((k) => !has(k));
20499
+ const squash = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
20500
+ const unknown = unknownKeys.map((key) => {
20501
+ const sameWord = unsupplied.find((p) => squash(p) === squash(key));
20502
+ const onlyPair = missing.length === 1 && unknownKeys.length === 1 ? missing[0] : void 0;
20503
+ const suggestion = sameWord ?? onlyPair ?? closestNames(key, unsupplied, 1)[0];
20504
+ return suggestion === void 0 ? { key } : { key, suggestion };
20505
+ });
20506
+ return { missing, unknown };
20507
+ }
19946
20508
  var ROUTING_FAULT_TOOL_GONE = "no longer available";
19947
20509
  var ROUTING_FAULT_RECONNECT_FAILED = "auto-reconnect failed";
19948
20510
  var ROUTING_FAULT_LOAD_FAILED = "could not be loaded on first call";
@@ -20427,7 +20989,7 @@ var ConnectServer = class _ConnectServer {
20427
20989
  * initialize handshake completes; see beginSession for why it waits. */
20428
20990
  buildServer(era, supportedProtocolVersions) {
20429
20991
  const s = new Server(
20430
- { name: "yaw-mcp", version: true ? "1.1.7" : "dev" },
20992
+ { name: "yaw-mcp", version: true ? "1.1.8" : "dev" },
20431
20993
  {
20432
20994
  capabilities: {
20433
20995
  tools: { listChanged: true },
@@ -20692,20 +21254,21 @@ var ConnectServer = class _ConnectServer {
20692
21254
  };
20693
21255
  handle("tools/list", async () => {
20694
21256
  await this.ready;
20695
- return {
20696
- tools: buildToolList(
20697
- this.connections,
20698
- this.getDeferredServers(),
20699
- this.toolFilters,
20700
- this.currentExposure(),
20701
- this.sessionActivated,
20702
- // Hidden here, refused at the gate, but still ROUTED: dropping the
20703
- // route instead would make a call by name return `Unknown tool`,
20704
- // which reads as a typo and sends the model hunting for a name that
20705
- // is right there.
20706
- (wireName) => this.isToolDenied(wireName)
20707
- )
20708
- };
21257
+ const exposure = this.currentExposure();
21258
+ const tools = buildToolList(
21259
+ this.connections,
21260
+ this.getDeferredServers(),
21261
+ this.toolFilters,
21262
+ exposure,
21263
+ this.sessionActivated,
21264
+ // Hidden here, refused at the gate, but still ROUTED: dropping the
21265
+ // route instead would make a call by name return `Unknown tool`,
21266
+ // which reads as a typo and sends the model hunting for a name that
21267
+ // is right there.
21268
+ (wireName) => this.isToolDenied(wireName)
21269
+ );
21270
+ const installed = formatInstalledServers(this.getProfiledActiveServers());
21271
+ return { tools: withInstalledServers(tools, installed, exposure) };
20709
21272
  });
20710
21273
  handle("tools/call", async (request2, ctx) => {
20711
21274
  await this.ready;
@@ -20904,21 +21467,42 @@ var ConnectServer = class _ConnectServer {
20904
21467
  * where the server has one, a tool that needs no arguments (read-only
20905
21468
  * first), so `args: {}` runs as written. When every tool needs arguments
20906
21469
  * the line says to fill them in rather than show a call that would fail. */
20907
- execHintForNonRelistingClient(loaded) {
21470
+ execHintForNonRelistingClient(loaded, preferred) {
20908
21471
  if (clientRelistsTools(this.clientSession().clientInfo)) return null;
21472
+ const example = this.execExample(loaded, preferred);
21473
+ if (example === null) return null;
21474
+ return `This client keeps the tool list it read at startup, so the tools just loaded are not in it and a direct call to one fails. Call them through mcp_connect_exec instead, e.g. ${example.call}${example.fill}`;
21475
+ }
21476
+ /** A ready-made exec call for a load reply: `preferred` (a namespaced
21477
+ * name) when it is a served tool of a loaded namespace, else a served --
21478
+ * not shadowed -- tool of the first namespace that loaded, preferring one
21479
+ * that needs no arguments (read-only first), so `args: {}` runs as
21480
+ * written. When the example needs arguments, `fill` says to supply them
21481
+ * rather than show a call that would fail. */
21482
+ execExample(loaded, preferred) {
20909
21483
  const needsNoArgs = (t) => {
20910
21484
  const required = t.inputSchema?.required;
20911
21485
  return !Array.isArray(required) || required.length === 0;
20912
21486
  };
21487
+ const render2 = (example) => ({
21488
+ call: JSON.stringify({ steps: [{ tool: example.namespacedName, args: {} }] }),
21489
+ fill: needsNoArgs(example) ? "" : ` (with the tool's own arguments in "args"; mcp_connect_read_tool shows a tool's arguments)`
21490
+ });
21491
+ if (preferred !== void 0) {
21492
+ for (const ns of loaded) {
21493
+ const conn = this.connections.get(ns);
21494
+ if (!conn) continue;
21495
+ const hit = this.splitShadowedTools(ns, conn.tools).served.find((t) => t.namespacedName === preferred);
21496
+ if (hit) return render2(hit);
21497
+ }
21498
+ }
20913
21499
  for (const ns of loaded) {
20914
21500
  const conn = this.connections.get(ns);
20915
21501
  if (!conn) continue;
20916
21502
  const served = this.splitShadowedTools(ns, conn.tools).served;
20917
21503
  const example = served.find((t) => needsNoArgs(t) && t.annotations?.readOnlyHint === true) ?? served.find(needsNoArgs) ?? served[0];
20918
21504
  if (example === void 0) continue;
20919
- const call = JSON.stringify({ steps: [{ tool: example.namespacedName, args: {} }] });
20920
- const fill = needsNoArgs(example) ? "" : ` (with the tool's own arguments in "args"; mcp_connect_read_tool shows a tool's arguments)`;
20921
- return `This client keeps the tool list it read at startup, so the tools just loaded are not in it and a direct call to one fails. Call them through mcp_connect_exec instead, e.g. ${call}${fill}`;
21505
+ return render2(example);
20922
21506
  }
20923
21507
  return null;
20924
21508
  }
@@ -22117,28 +22701,85 @@ var ConnectServer = class _ConnectServer {
22117
22701
  // same server. mergeToolCache is idempotent, so callers that already pass a
22118
22702
  // merged server (every current one does) pay one small clone and nothing
22119
22703
  // else.
22704
+ //
22705
+ // Only when there is no real list at all -- no connection, no learned
22706
+ // entry (an EMPTY learned list counts: the server was spawned and offered
22707
+ // nothing), no non-empty curated list -- does it fall back to the bundled
22708
+ // list fallback-tools.ts keeps for a few well-known servers, matched by
22709
+ // the image or binary the entry launches. That fallback lives here and
22710
+ // nowhere else: it feeds ranking (dispatch, discover, find_tool) but never
22711
+ // hasKnownTools, getDeferredServers or a route, so pre-warm keeps trying to
22712
+ // learn the real list and no call is ever built from the bundled one.
22120
22713
  rankableFor(server) {
22121
- const connection = this.connections.get(server.namespace);
22122
- const liveTools = connection?.tools.map((t) => ({ name: t.name, description: t.description }));
22123
22714
  return {
22124
22715
  namespace: server.namespace,
22125
22716
  name: server.name,
22126
22717
  description: server.description,
22127
- tools: liveTools ?? this.mergeToolCache(server).toolCache ?? []
22718
+ tools: this.rankableTools(server).tools
22128
22719
  };
22129
22720
  }
22721
+ // The tool list rankableFor ranks a server on, and where it came from:
22722
+ // "live" (connected), "known" (learned or curated -- possibly an empty
22723
+ // learned list), "bundled" (fallback-tools.ts, never confirmed on this
22724
+ // machine) or "none" (nothing at all; the server ranks on its name and
22725
+ // description only, and find_tool cannot see it).
22726
+ rankableTools(server) {
22727
+ const connection = this.connections.get(server.namespace);
22728
+ if (connection) {
22729
+ return { tools: connection.tools.map((t) => ({ name: t.name, description: t.description })), source: "live" };
22730
+ }
22731
+ const merged = this.mergeToolCache(server).toolCache;
22732
+ if (merged && merged.length > 0 || this.toolCache.has(server.namespace)) {
22733
+ return { tools: merged ?? [], source: "known" };
22734
+ }
22735
+ const bundled = fallbackToolsFor(server);
22736
+ if (bundled) return { tools: [...bundled], source: "bundled" };
22737
+ return { tools: merged ?? [], source: "none" };
22738
+ }
22130
22739
  // BM25 shortlist cap — wider than the budget so downstream re-sorts
22131
22740
  // (health penalty, learning boost, sampling tiebreak) have room to
22132
22741
  // promote a server BM25 ranked below the head of the list.
22133
22742
  static BM25_TOP_K = 25;
22134
- // Local BM25 ranking over the profiled active servers. Shared by
22135
- // discover's auto-warm gate and dispatch so both pick the same winner
22136
- // for the same intent.
22743
+ // Local BM25 ranking over the profiled active servers, each entry carrying
22744
+ // its queryCoverage for the same query (same RankableServer views, so the
22745
+ // same cached index) once there are AUTO_ACTIVATE_COVERAGE_MIN_SERVERS of
22746
+ // them. Raw: routingCandidates applies the health and
22747
+ // learning multipliers on top.
22137
22748
  async rankIntentCandidates(context, servers) {
22138
22749
  const bm25Input = servers.map((s) => this.rankableFor(s));
22139
22750
  const bm25 = rankServers(context, bm25Input);
22140
22751
  if (bm25.length === 0) return [];
22141
- return bm25.slice(0, _ConnectServer.BM25_TOP_K);
22752
+ const top = bm25.slice(0, _ConnectServer.BM25_TOP_K);
22753
+ if (bm25Input.length < AUTO_ACTIVATE_COVERAGE_MIN_SERVERS) {
22754
+ return top.map((r) => ({ namespace: r.namespace, score: r.score }));
22755
+ }
22756
+ const coverage = new Map(queryCoverage(context, bm25Input).map((c) => [c.namespace, c]));
22757
+ return top.map((r) => {
22758
+ const c = coverage.get(r.namespace);
22759
+ return {
22760
+ namespace: r.namespace,
22761
+ score: r.score,
22762
+ coverage: c?.coverage ?? 0,
22763
+ matched: c?.matched ?? 0,
22764
+ contentTerms: c?.contentTerms ?? 0
22765
+ };
22766
+ });
22767
+ }
22768
+ // The ranking both routing DECISIONS use -- dispatch's pick and discover's
22769
+ // auto-warm -- so the two choose the same server for the same intent:
22770
+ // rankIntentCandidates' BM25 score times the health penalty (recent
22771
+ // activation failures and high error rates shrink it, so routing prefers
22772
+ // servers that work when several match; healthFactor never exceeds 1) times
22773
+ // the learning boost, re-sorted. Coverage is passed through untouched.
22774
+ // discover's rendered listing and its `(relevance: X)` numbers stay raw
22775
+ // BM25 (buildDiscoverOutput): that body is memoized under a key that does
22776
+ // not cover health or learning state.
22777
+ async routingCandidates(context, servers) {
22778
+ const raw = await this.rankIntentCandidates(context, servers);
22779
+ return raw.map((r) => ({
22780
+ ...r,
22781
+ score: r.score * healthFactor(this.connections.get(r.namespace)?.health, this.activationFailures.get(r.namespace)) * this.learning.boostFactor(r.namespace)
22782
+ })).sort((a, b) => b.score - a.score);
22142
22783
  }
22143
22784
  // Auto-warm confidence gate — applied to discover(context) so a single
22144
22785
  // clearly-winning server gets activated without the LLM needing to
@@ -22146,13 +22787,9 @@ var ConnectServer = class _ConnectServer {
22146
22787
  // YAW_MCP_AUTO_ACTIVATE=0 if it causes surprise. The env read lives in
22147
22788
  // the module-level isAutoActivateEnabled() (re-read per call) rather
22148
22789
  // than a static initializer, which would latch the value at import.
22149
- //
22150
- // Top score must clear this floor AND the gap over the runner-up must
22151
- // be convincing before we auto-activate. BM25 scores are unbounded
22152
- // positive numbers. Tuned by intuition; revisit when we have real
22153
- // usage data.
22154
- static AUTO_ACTIVATE_MIN_SCORE_BM25 = 1;
22155
- static AUTO_ACTIVATE_MARGIN_BM25 = 1.3;
22790
+ // The score floor, coverage floor and runner-up margin live in the
22791
+ // module-level pickAutoWarmWinner (AUTO_ACTIVATE_MIN_SCORE_BM25 /
22792
+ // _MIN_COVERAGE / _MARGIN_BM25).
22156
22793
  // Below this installed-server count, discover() appends a one-line
22157
22794
  // marketplace pointer so sparse-config users see where to add more.
22158
22795
  // At or above the threshold we stay silent — power users already know
@@ -22227,14 +22864,10 @@ var ConnectServer = class _ConnectServer {
22227
22864
  if (!context || !isAutoActivateEnabled()) return this.handleDiscover(context, focusNamespace);
22228
22865
  const activeServers = this.getProfiledActiveServers();
22229
22866
  if (activeServers.length === 0) return this.handleDiscover(context, focusNamespace);
22230
- const ranked = await this.rankIntentCandidates(context, activeServers);
22867
+ const ranked = await this.routingCandidates(context, activeServers);
22231
22868
  if (ranked.length === 0) return this.handleDiscover(context, focusNamespace);
22232
- const top = ranked[0];
22233
- const second = ranked[1];
22234
- const minScore = _ConnectServer.AUTO_ACTIVATE_MIN_SCORE_BM25;
22235
- const margin = _ConnectServer.AUTO_ACTIVATE_MARGIN_BM25;
22236
- const topWinsDecisively = top !== void 0 && top.score >= minScore && (second === void 0 || top.score / (second.score || 1e-6) >= margin);
22237
- if (!topWinsDecisively || !top) return this.handleDiscover(context, focusNamespace);
22869
+ const top = pickAutoWarmWinner(ranked);
22870
+ if (!top) return this.handleDiscover(context, focusNamespace);
22238
22871
  const existing = this.connections.get(top.namespace);
22239
22872
  if (existing && existing.status === "connected") {
22240
22873
  this.prewarmNamespaces.delete(top.namespace);
@@ -22332,7 +22965,7 @@ var ConnectServer = class _ConnectServer {
22332
22965
  const blocked = profile ? servers.filter((s) => s.isActive && !profileAllows(profile, s.namespace)) : [];
22333
22966
  const parts = ["No servers enabled."];
22334
22967
  if (profile && blocked.length > 0) {
22335
- const quote = (list) => list.map((s) => `"${s.namespace}"`).join(", ");
22968
+ const quote = (list2) => list2.map((s) => `"${s.namespace}"`).join(", ");
22336
22969
  const denied = blocked.filter((s) => profile.blocked?.includes(s.namespace));
22337
22970
  const unlisted = blocked.filter((s) => !profile.blocked?.includes(s.namespace));
22338
22971
  const edits = [];
@@ -23887,11 +24520,7 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
23887
24520
  };
23888
24521
  }
23889
24522
  progress?.(`Ranking ${activeServers.length} ${activeServers.length === 1 ? "server" : "servers"}\u2026`);
23890
- const rankedRaw = await this.rankIntentCandidates(trimmed, activeServers);
23891
- const ranked = rankedRaw.map((r) => ({
23892
- namespace: r.namespace,
23893
- score: r.score * healthFactor(this.connections.get(r.namespace)?.health, this.activationFailures.get(r.namespace)) * this.learning.boostFactor(r.namespace)
23894
- })).sort((a, b) => b.score - a.score);
24523
+ const ranked = await this.routingCandidates(trimmed, activeServers);
23895
24524
  if (ranked.length === 0) {
23896
24525
  return {
23897
24526
  content: [
@@ -23909,6 +24538,7 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
23909
24538
  const clientCanSample = era === "legacy" && this.pushCapabilities()?.sampling !== void 0;
23910
24539
  const wantsTiebreak = safeBudget === 1 && shouldSample(ranked, effort);
23911
24540
  if (wantsTiebreak && !clientCanSample) noteNoSamplingCapability2(era);
24541
+ let sampledPick = false;
23912
24542
  if (wantsTiebreak && clientCanSample) {
23913
24543
  progress?.("Top candidates close \u2014 asking LLM to pick\u2026");
23914
24544
  const serversByNamespace = new Map(activeServers.map((s) => [s.namespace, s]));
@@ -23922,6 +24552,7 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
23922
24552
  const rest = ranked.filter((r) => r.namespace !== picked);
23923
24553
  ranked.length = 0;
23924
24554
  ranked.push(winner, ...rest);
24555
+ sampledPick = true;
23925
24556
  progress?.(`LLM chose ${picked}`);
23926
24557
  }
23927
24558
  }
@@ -23951,25 +24582,111 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
23951
24582
  const results = [];
23952
24583
  const tally = newExplicitLoadTally();
23953
24584
  const dispatchedOk = [];
24585
+ const attempted = new Set(winners.map((w) => w.namespace));
24586
+ const fallbackPool = ranked.slice(safeBudget).filter((r) => r.score > 0);
24587
+ let fallbacksLeft = DISPATCH_MAX_FALLBACKS;
24588
+ const rescues = [];
23954
24589
  let i = 0;
23955
24590
  for (const winner of winners) {
23956
24591
  i += 1;
23957
24592
  progress?.(`Loading ${winner.namespace} (${i}/${winners.length})`, i - 1, winners.length);
23958
24593
  const r = await this.activateOne(winner.namespace, progress);
23959
24594
  results.push(`${winner.namespace} (score ${winner.score.toFixed(2)}): ${r.message}`);
23960
- this.recordExplicitLoad(tally, winner.namespace, r);
23961
- if (r.ok) dispatchedOk.push(winner.namespace);
24595
+ const head = fallbackPool[0];
24596
+ if (r.ok || r.capped || fallbacksLeft === 0 || head === void 0 || !runnerUpCanReplace(winner, head)) {
24597
+ this.recordExplicitLoad(tally, winner.namespace, r);
24598
+ if (r.ok) dispatchedOk.push(winner.namespace);
24599
+ continue;
24600
+ }
24601
+ const failed = [{ namespace: winner.namespace, r }];
24602
+ let rescued = false;
24603
+ while (fallbacksLeft > 0 && fallbackPool.length > 0 && runnerUpCanReplace(winner, fallbackPool[0])) {
24604
+ const next = fallbackPool.shift();
24605
+ fallbacksLeft -= 1;
24606
+ attempted.add(next.namespace);
24607
+ progress?.(`${winner.namespace} failed to load; trying runner-up ${next.namespace}`);
24608
+ const fr = await this.activateOne(next.namespace, progress);
24609
+ results.push(
24610
+ `${next.namespace} (score ${next.score.toFixed(2)}, runner-up tried because ${winner.namespace} failed to load): ${fr.message}`
24611
+ );
24612
+ if (fr.ok) {
24613
+ this.recordExplicitLoad(tally, next.namespace, fr);
24614
+ dispatchedOk.push(next.namespace);
24615
+ this.lastIntentByNamespace.set(next.namespace, trimmed);
24616
+ rescues.push(`${winner.namespace} failed to load; loaded runner-up ${next.namespace} instead.`);
24617
+ rescued = true;
24618
+ break;
24619
+ }
24620
+ if (fr.capped) {
24621
+ this.recordExplicitLoad(tally, next.namespace, fr);
24622
+ break;
24623
+ }
24624
+ failed.push({ namespace: next.namespace, r: fr });
24625
+ }
24626
+ if (rescued) {
24627
+ if (failed.some((f) => f.r.isChanged)) tally.anyChanged = true;
24628
+ } else {
24629
+ for (const f of failed) this.recordExplicitLoad(tally, f.namespace, f.r);
24630
+ }
23962
24631
  }
23963
24632
  await this.announceExplicitLoads(tally);
23964
- const execHint = this.execHintForNonRelistingClient(dispatchedOk);
24633
+ const toolHints = this.dispatchToolHints(trimmed, dispatchedOk);
24634
+ if (toolHints.lines.length > 0) {
24635
+ results.push("Best tools for this request (arguments: required first, optional marked ?):", ...toolHints.lines);
24636
+ }
24637
+ const loadedPrimary = dispatchedOk[0];
24638
+ if (loadedPrimary) {
24639
+ const note = dispatchConfidenceNote(ranked, loadedPrimary, /* @__PURE__ */ new Set([...attempted, ...dispatchedOk]), {
24640
+ sampled: sampledPick && loadedPrimary === winners[0]?.namespace,
24641
+ noSampling: !clientCanSample && effort !== "off"
24642
+ });
24643
+ if (note) results.push(note);
24644
+ }
24645
+ const execHint = this.execHintForNonRelistingClient(dispatchedOk, toolHints.top);
23965
24646
  if (execHint) results.push(execHint);
23966
- const header = `Dispatched "${trimmed}" \u2014 loaded top ${winners.length} of ${ranked.length} matching server${ranked.length === 1 ? "" : "s"}.
24647
+ const runnersUpTried = attempted.size - winners.length;
24648
+ const tried = runnersUpTried > 0 ? `${attempted.size} (the top ${winners.length}, then ${runnersUpTried} ${runnersUpTried === 1 ? "runner-up" : "runners-up"})` : `the top ${winners.length}`;
24649
+ const header = `Dispatched "${trimmed}" \u2014 tried ${tried} of the ${ranked.length} server${ranked.length === 1 ? "" : "s"} ranked for it.${rescues.length > 0 ? ` ${rescues.join(" ")}` : ""}
23967
24650
  `;
23968
24651
  return {
23969
24652
  content: [{ type: "text", text: header + results.join("\n") }],
23970
24653
  isError: explicitLoadIsError(tally)
23971
24654
  };
23972
24655
  }
24656
+ /** For a dispatch reply: the DISPATCH_TOOL_HINTS tools of the namespaces
24657
+ * in `loaded` that rankTools ranks highest for `intent`, each as a
24658
+ * formatToolSignature line from its live inputSchema. Only served tools
24659
+ * (not shadowed by another namespace's wire name) that the profile does
24660
+ * not block. `top` is the first one's namespaced name, for the exec
24661
+ * example. Empty when no loaded tool shares a word with the intent --
24662
+ * the server then matched on its name or description, and naming three
24663
+ * arbitrary tools would be a guess. */
24664
+ dispatchToolHints(intent, loaded) {
24665
+ const views = [];
24666
+ const byKey = /* @__PURE__ */ new Map();
24667
+ for (const ns of loaded) {
24668
+ const conn = this.connections.get(ns);
24669
+ if (!conn) continue;
24670
+ const tools = this.splitShadowedTools(ns, conn.tools).served.filter((t) => !this.isToolDenied(t.namespacedName));
24671
+ for (const t of tools) byKey.set(`${ns}\0${t.name}`, t);
24672
+ views.push({
24673
+ namespace: ns,
24674
+ name: conn.config.name,
24675
+ description: conn.config.description,
24676
+ tools: tools.map((t) => ({ name: t.name, description: t.description }))
24677
+ });
24678
+ }
24679
+ if (views.length === 0) return { lines: [] };
24680
+ const lines = [];
24681
+ let top;
24682
+ for (const hit of rankTools(intent, views).slice(0, DISPATCH_TOOL_HINTS)) {
24683
+ const tool = byKey.get(`${hit.namespace}\0${hit.name}`);
24684
+ if (!tool) continue;
24685
+ top ??= tool.namespacedName;
24686
+ lines.push(` ${formatToolSignature(tool.namespacedName, tool.inputSchema)}`);
24687
+ }
24688
+ return { lines, top };
24689
+ }
23973
24690
  // Drop every per-namespace bit of session state after its connection has
23974
24691
  // been closed. Called by all four teardown sites -- explicit deactivate,
23975
24692
  // the idle reaper, reconcileConfig's unload of a server a bundles.json
@@ -24409,7 +25126,18 @@ Cross-session reliability (dormant, <${flakyPct}% success):`);
24409
25126
  this.getProfiledActiveServers().map((s) => this.rankableFor(s))
24410
25127
  );
24411
25128
  }
25129
+ const unseen = this.unseenToolListMatches(query);
24412
25130
  if (ranked.length === 0) {
25131
+ if (unseen.none.length > 0) {
25132
+ return {
25133
+ content: [
25134
+ {
25135
+ type: "text",
25136
+ text: `No known tool matches "${query}". ${this.unseenToolListLine(query, unseen.none)}`
25137
+ }
25138
+ ]
25139
+ };
25140
+ }
24413
25141
  return {
24414
25142
  content: [
24415
25143
  {
@@ -24428,7 +25156,8 @@ Cross-session reliability (dormant, <${flakyPct}% success):`);
24428
25156
  for (const hit of usable) {
24429
25157
  const connection = this.connections.get(hit.namespace);
24430
25158
  const live = connection?.status === "connected" ? connection.tools.find((t) => t.name === hit.name) : void 0;
24431
- lines.push(` ${hit.namespace}_${hit.name}${live ? " [loaded]" : ""}`);
25159
+ const bundled = unseen.bundled.includes(hit.namespace);
25160
+ lines.push(` ${hit.namespace}_${hit.name}${live ? " [loaded]" : bundled ? " [bundled list]" : ""}`);
24432
25161
  if (hit.description) lines.push(` ${hit.description}`);
24433
25162
  if (live) {
24434
25163
  lines.push(` input schema: ${JSON.stringify(live.inputSchema)}`);
@@ -24456,8 +25185,40 @@ Cross-session reliability (dormant, <${flakyPct}% success):`);
24456
25185
  "",
24457
25186
  primary === void 0 ? `Every match shown is blocked by the profile's "blockedTools" list.` : alsoTry.length > 0 ? `To use one: mcp_connect_activate with server "${primary}" (or ${alsoTry.join(", ")}).` : `To use one: mcp_connect_activate with server "${primary}".`
24458
25187
  );
25188
+ const bundledShown = [...new Set(usable.map((h) => h.namespace).filter((ns) => unseen.bundled.includes(ns)))];
25189
+ if (bundledShown.length > 0) {
25190
+ lines.push(
25191
+ `[bundled list]: ${bundledShown.join(", ")} has never loaded on this machine, so its tools above come from yaw-mcp's bundled copy of the upstream list and are unconfirmed; loading it replaces them with what it really serves.`
25192
+ );
25193
+ }
25194
+ if (unseen.none.length > 0) lines.push(this.unseenToolListLine(query, unseen.none));
24459
25195
  return { content: [{ type: "text", text: lines.join("\n") }] };
24460
25196
  }
25197
+ // How many of the query's best-ranked servers find_tool checks for an
25198
+ // unknown tool list. Wider would name servers that share one weak word
25199
+ // with the query; the point is the plausible ones.
25200
+ static FIND_TOOL_UNSEEN_TOP = 5;
25201
+ /** For find_tool: among the servers rankServers puts in its top
25202
+ * FIND_TOOL_UNSEEN_TOP for `query`, the ones whose tool list is unknown
25203
+ * (`none`, in ranking order); and every server ranked on the bundled list
25204
+ * (`bundled`), so its hits can be labelled. */
25205
+ unseenToolListMatches(query) {
25206
+ const servers = this.getProfiledActiveServers();
25207
+ const sources = new Map(servers.map((s) => [s.namespace, this.rankableTools(s).source]));
25208
+ const top = rankServers(
25209
+ query,
25210
+ servers.map((s) => this.rankableFor(s))
25211
+ ).slice(0, _ConnectServer.FIND_TOOL_UNSEEN_TOP);
25212
+ return {
25213
+ none: top.filter((r) => sources.get(r.namespace) === "none").map((r) => r.namespace),
25214
+ bundled: servers.filter((s) => sources.get(s.namespace) === "bundled").map((s) => s.namespace)
25215
+ };
25216
+ }
25217
+ unseenToolListLine(query, namespaces) {
25218
+ const plural = namespaces.length > 1;
25219
+ const call = JSON.stringify({ intent: query });
25220
+ return `Not searched: ${namespaces.join(", ")} match${plural ? "" : "es"} this request by name or description, but ${plural ? "their tool lists are" : "its tool list is"} unknown until ${plural ? "they have" : "it has"} loaded once. mcp_connect_dispatch ${call} loads the best match and lists its tools.`;
25221
+ }
24461
25222
  // Pack suggestion. Surfaces recurring multi-server tool-call sequences from
24462
25223
  // the pack history, which persists across restarts (see persistence.ts).
24463
25224
  // Observation only — never activates anything. Ranked by frequency
@@ -24679,6 +25440,33 @@ Cross-session reliability (dormant, <${flakyPct}% success):`);
24679
25440
  isError: true
24680
25441
  };
24681
25442
  }
25443
+ for (let i = 0; i < steps.length; i++) {
25444
+ const step = steps[i];
25445
+ const route = this.toolRoutes.get(step.tool);
25446
+ if (!route || route.deferred || isRefNode(step.args)) continue;
25447
+ const tool = this.connections.get(route.namespace)?.tools.find((t) => t.name === route.originalName);
25448
+ if (!tool) continue;
25449
+ const mismatch = checkToolArgs(tool.inputSchema, step.args);
25450
+ if (!mismatch) continue;
25451
+ const key = stepBindingKey(step, i);
25452
+ const parts = [];
25453
+ if (mismatch.missing.length > 0) parts.push(`Missing required: ${mismatch.missing.join(", ")}.`);
25454
+ if (mismatch.unknown.length > 0) {
25455
+ const listed = mismatch.unknown.map(
25456
+ (u) => u.suggestion ? `${u.key} (did you mean "${u.suggestion}"?)` : u.key
25457
+ );
25458
+ parts.push(`Not in the schema: ${listed.join(", ")}.`);
25459
+ }
25460
+ return {
25461
+ content: [
25462
+ {
25463
+ type: "text",
25464
+ text: `exec: step "${key}": the arguments do not fit "${step.tool}"; no step ran. ${parts.join(" ")} Expected: ${formatToolSignature(step.tool, tool.inputSchema, Number.POSITIVE_INFINITY)}`
25465
+ }
25466
+ ],
25467
+ isError: true
25468
+ };
25469
+ }
24682
25470
  const bindings = {};
24683
25471
  const echoed = {};
24684
25472
  const stepKeys = [];
@@ -24944,7 +25732,7 @@ function registerShutdownTriggers(shutdown, targets) {
24944
25732
  // src/status-cmd.ts
24945
25733
  import { existsSync as existsSync10 } from "fs";
24946
25734
  import { homedir as homedir23 } from "os";
24947
- var VERSION2 = true ? "1.1.7" : "dev";
25735
+ var VERSION2 = true ? "1.1.8" : "dev";
24948
25736
  var STATUS_SCHEMA_VERSION = 1;
24949
25737
  var STATUS_USAGE = `Usage: yaw-mcp status [--json]
24950
25738
 
@@ -25562,7 +26350,9 @@ if (subcommand === "compliance") {
25562
26350
  with the client LLM: \`off\` | \`auto\` |
25563
26351
  \`aggressive\` (default auto). The dispatch
25564
26352
  tool's \`routeEffort\` argument overrides this
25565
- per call.
26353
+ per call. Needs a client that supports MCP
26354
+ sampling (2025 protocol); without one it has
26355
+ no effect.
25566
26356
  YAW_MCP_REWARD_GRADER Set to \`1\` to OPT IN to the LLM reward
25567
26357
  grader: uncertain dispatch outcomes get a
25568
26358
  second opinion via client sampling. It spends
@@ -25788,7 +26578,7 @@ if (subcommand === "compliance") {
25788
26578
  `);
25789
26579
  process.exitCode = 0;
25790
26580
  } else if (subcommand === "--version" || subcommand === "-V") {
25791
- process.stdout.write(`yaw-mcp ${true ? "1.1.7" : "dev"}
26581
+ process.stdout.write(`yaw-mcp ${true ? "1.1.8" : "dev"}
25792
26582
  `);
25793
26583
  process.exitCode = 0;
25794
26584
  } else if (subcommand !== void 0 && !subcommand.startsWith("-")) {