search-index.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import type { ToolDefinition } from '@mavis/agent-core/tools';
  2. import { tokenize } from './tokenize.js';
  3. import type { McpToolEntry, McpToolIndex, McpSearchHit } from './types.js';
  4. const BM25_K1 = 1.5;
  5. const BM25_B = 0.75;
  6. function flattenSchema(schema: unknown, max: number): string {
  7. const parts: string[] = [];
  8. const walk = (node: unknown): void => {
  9. if (!node || typeof node !== 'object') return;
  10. const o = node as Record<string, unknown>;
  11. if (typeof o.description === 'string') parts.push(o.description);
  12. if (Array.isArray(o.enum)) parts.push(o.enum.map(String).join(' '));
  13. if (Array.isArray(o.required)) parts.push(o.required.map(String).join(' '));
  14. if (o.properties && typeof o.properties === 'object') {
  15. for (const [k, v] of Object.entries(o.properties as Record<string, unknown>)) {
  16. parts.push(k);
  17. walk(v);
  18. }
  19. }
  20. if (o.items) walk(o.items);
  21. };
  22. walk(schema);
  23. return parts.join(' ').slice(0, max);
  24. }
  25. function fnv1a(s: string): string {
  26. let h = 0x811c9dc5;
  27. for (let i = 0; i < s.length; i++) {
  28. h ^= s.charCodeAt(i);
  29. h = Math.imul(h, 0x01000193);
  30. }
  31. return (h >>> 0).toString(16);
  32. }
  33. interface Doc {
  34. name: string;
  35. description: string;
  36. input_schema: unknown;
  37. raw: string;
  38. tokens: string[];
  39. len: number;
  40. tf: Map<string, number>;
  41. }
  42. /**
  43. * Pure, stable content signature for a candidate set. Hashes the sorted
  44. * `name:fnv1a(schema):fnv1a(description)` triples — it intentionally does NOT
  45. * depend on `maxSchemaTextLen`, so two indexes built from the same candidates
  46. * (regardless of schema-text truncation) share a signature. `buildIndex` and
  47. * `buildOrReuseIndex` both route through this so their signatures always agree.
  48. */
  49. export function computeIndexSignature(candidates: readonly McpToolEntry[]): string {
  50. return fnv1a(
  51. [...candidates]
  52. .map(
  53. (e) =>
  54. `${e.tool.def.name}:${fnv1a(JSON.stringify(e.tool.def.schema ?? {}))}:${fnv1a(e.tool.def.description ?? '')}`,
  55. )
  56. .sort()
  57. .join('|'),
  58. );
  59. }
  60. export function buildIndex(
  61. candidates: readonly McpToolEntry[],
  62. opts: { maxSchemaTextLen: number },
  63. ): McpToolIndex {
  64. const docs: Doc[] = candidates.map((e) => {
  65. const def: ToolDefinition = e.tool.def;
  66. const schemaText = flattenSchema(def.schema, opts.maxSchemaTextLen);
  67. const raw = `${def.name} ${def.description ?? ''} ${schemaText}`;
  68. const tokens = tokenize(raw);
  69. const tf = new Map<string, number>();
  70. for (const t of tokens) tf.set(t, (tf.get(t) ?? 0) + 1);
  71. return {
  72. name: def.name,
  73. description: def.description ?? '',
  74. input_schema: def.schema,
  75. raw,
  76. tokens,
  77. len: tokens.length,
  78. tf,
  79. };
  80. });
  81. const N = docs.length;
  82. const df = new Map<string, number>();
  83. for (const d of docs) for (const t of new Set(d.tokens)) df.set(t, (df.get(t) ?? 0) + 1);
  84. const avgdl = N === 0 ? 0 : docs.reduce((s, d) => s + d.len, 0) / N;
  85. const idf = (t: string): number => {
  86. const n = df.get(t) ?? 0;
  87. return Math.log(1 + (N - n + 0.5) / (n + 0.5));
  88. };
  89. const signature = computeIndexSignature(candidates);
  90. function bm25(queryTokens: string[], d: Doc): number {
  91. let score = 0;
  92. for (const qt of new Set(queryTokens)) {
  93. const f = d.tf.get(qt) ?? 0;
  94. if (f === 0) continue;
  95. const denom = f + BM25_K1 * (1 - BM25_B + (BM25_B * d.len) / (avgdl || 1));
  96. score += idf(qt) * ((f * (BM25_K1 + 1)) / denom);
  97. }
  98. return score;
  99. }
  100. function search(input: { query?: string; regex?: string; topK: number }): McpSearchHit[] {
  101. let pool = docs;
  102. if (input.regex) {
  103. const re = new RegExp(input.regex, 'i');
  104. pool = pool.filter((d) => re.test(d.raw));
  105. }
  106. let scored: { d: Doc; score: number }[];
  107. if (input.query && input.query.trim()) {
  108. const qt = tokenize(input.query);
  109. scored = pool.map((d) => ({ d, score: bm25(qt, d) })).filter((x) => x.score > 0);
  110. // `regex` is a hard filter; `query` only ranks within it. When the query
  111. // adds no BM25 signal but a regex narrowed the pool, still return that pool
  112. // (flat score) so a narrowing regex never silently yields nothing. With no
  113. // regex in play, a zero-hit query means no match. Either way `topK` bounds
  114. // the result, so the fallback cannot flood the context.
  115. if (scored.length === 0) {
  116. if (!input.regex) return [];
  117. scored = pool.map((d) => ({ d, score: 1 }));
  118. }
  119. } else {
  120. scored = pool.map((d) => ({ d, score: 1 }));
  121. }
  122. scored.sort((a, b) => b.score - a.score || a.d.name.localeCompare(b.d.name));
  123. return scored.slice(0, Math.max(0, input.topK)).map(({ d, score }) => ({
  124. name: d.name,
  125. description: d.description,
  126. input_schema: d.input_schema,
  127. score,
  128. }));
  129. }
  130. return { search, size: N, signature };
  131. }
  132. /**
  133. * Module-level bounded LRU of built indexes keyed by content signature. The
  134. * planner rebuilds candidates every deferred turn; caching by signature avoids
  135. * redundant per-turn BM25 index construction when the configured MCP tool set is
  136. * unchanged. Insertion-ordered `Map` doubles as the recency list.
  137. */
  138. const CACHE_MAX = 16;
  139. const indexCache = new Map<string, McpToolIndex>();
  140. export function buildOrReuseIndex(
  141. candidates: readonly McpToolEntry[],
  142. opts: { maxSchemaTextLen: number },
  143. ): McpToolIndex {
  144. const sig = computeIndexSignature(candidates);
  145. const hit = indexCache.get(sig);
  146. if (hit !== undefined) {
  147. // Move to most-recent: delete + re-set so iteration order tracks recency.
  148. indexCache.delete(sig);
  149. indexCache.set(sig, hit);
  150. return hit;
  151. }
  152. const idx = buildIndex(candidates, opts);
  153. if (indexCache.size >= CACHE_MAX) {
  154. const oldest = indexCache.keys().next().value;
  155. if (oldest !== undefined) indexCache.delete(oldest);
  156. }
  157. indexCache.set(sig, idx);
  158. return idx;
  159. }
  160. /** Test-only: clear the module-level index cache for deterministic tests. */
  161. export function __resetMcpIndexCacheForTest(): void {
  162. indexCache.clear();
  163. }