illuma-agents 1.0.36 → 1.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +69 -14
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +3 -1
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +50 -8
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +277 -11
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/index.cjs +128 -61
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  11. package/dist/cjs/main.cjs +16 -7
  12. package/dist/cjs/main.cjs.map +1 -1
  13. package/dist/cjs/messages/cache.cjs +1 -0
  14. package/dist/cjs/messages/cache.cjs.map +1 -1
  15. package/dist/cjs/messages/core.cjs +1 -1
  16. package/dist/cjs/messages/core.cjs.map +1 -1
  17. package/dist/cjs/messages/tools.cjs +2 -2
  18. package/dist/cjs/messages/tools.cjs.map +1 -1
  19. package/dist/cjs/stream.cjs +4 -2
  20. package/dist/cjs/stream.cjs.map +1 -1
  21. package/dist/cjs/tools/BrowserTools.cjs +27 -3
  22. package/dist/cjs/tools/BrowserTools.cjs.map +1 -1
  23. package/dist/cjs/tools/CodeExecutor.cjs +22 -21
  24. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  25. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
  26. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  27. package/dist/cjs/tools/ToolNode.cjs +101 -2
  28. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  29. package/dist/cjs/tools/ToolSearch.cjs +862 -0
  30. package/dist/cjs/tools/ToolSearch.cjs.map +1 -0
  31. package/dist/esm/agents/AgentContext.mjs +69 -14
  32. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  33. package/dist/esm/common/enum.mjs +3 -1
  34. package/dist/esm/common/enum.mjs.map +1 -1
  35. package/dist/esm/graphs/Graph.mjs +51 -9
  36. package/dist/esm/graphs/Graph.mjs.map +1 -1
  37. package/dist/esm/graphs/MultiAgentGraph.mjs +278 -12
  38. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  39. package/dist/esm/llm/bedrock/index.mjs +127 -60
  40. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  41. package/dist/esm/main.mjs +1 -1
  42. package/dist/esm/messages/cache.mjs +1 -0
  43. package/dist/esm/messages/cache.mjs.map +1 -1
  44. package/dist/esm/messages/core.mjs +1 -1
  45. package/dist/esm/messages/core.mjs.map +1 -1
  46. package/dist/esm/messages/tools.mjs +2 -2
  47. package/dist/esm/messages/tools.mjs.map +1 -1
  48. package/dist/esm/stream.mjs +4 -2
  49. package/dist/esm/stream.mjs.map +1 -1
  50. package/dist/esm/tools/BrowserTools.mjs +27 -3
  51. package/dist/esm/tools/BrowserTools.mjs.map +1 -1
  52. package/dist/esm/tools/CodeExecutor.mjs +22 -21
  53. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  54. package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
  55. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  56. package/dist/esm/tools/ToolNode.mjs +102 -3
  57. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  58. package/dist/esm/tools/ToolSearch.mjs +827 -0
  59. package/dist/esm/tools/ToolSearch.mjs.map +1 -0
  60. package/dist/types/agents/AgentContext.d.ts +33 -1
  61. package/dist/types/common/enum.d.ts +4 -2
  62. package/dist/types/graphs/Graph.d.ts +6 -0
  63. package/dist/types/graphs/MultiAgentGraph.d.ts +16 -0
  64. package/dist/types/index.d.ts +1 -1
  65. package/dist/types/llm/bedrock/index.d.ts +89 -11
  66. package/dist/types/llm/bedrock/types.d.ts +27 -0
  67. package/dist/types/llm/bedrock/utils/index.d.ts +5 -0
  68. package/dist/types/llm/bedrock/utils/message_inputs.d.ts +31 -0
  69. package/dist/types/llm/bedrock/utils/message_outputs.d.ts +33 -0
  70. package/dist/types/tools/BrowserTools.d.ts +2 -0
  71. package/dist/types/tools/CodeExecutor.d.ts +0 -3
  72. package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
  73. package/dist/types/tools/ToolNode.d.ts +3 -1
  74. package/dist/types/tools/ToolSearch.d.ts +148 -0
  75. package/dist/types/types/graph.d.ts +2 -0
  76. package/dist/types/types/llm.d.ts +3 -1
  77. package/dist/types/types/tools.d.ts +42 -2
  78. package/package.json +12 -5
  79. package/src/agents/AgentContext.ts +88 -16
  80. package/src/common/enum.ts +3 -1
  81. package/src/graphs/Graph.ts +64 -13
  82. package/src/graphs/MultiAgentGraph.ts +350 -13
  83. package/src/index.ts +1 -1
  84. package/src/llm/bedrock/index.ts +221 -99
  85. package/src/llm/bedrock/llm.spec.ts +616 -0
  86. package/src/llm/bedrock/types.ts +51 -0
  87. package/src/llm/bedrock/utils/index.ts +18 -0
  88. package/src/llm/bedrock/utils/message_inputs.ts +563 -0
  89. package/src/llm/bedrock/utils/message_outputs.ts +310 -0
  90. package/src/messages/__tests__/tools.test.ts +21 -21
  91. package/src/messages/cache.test.ts +259 -0
  92. package/src/messages/cache.ts +104 -1
  93. package/src/messages/core.ts +1 -1
  94. package/src/messages/tools.ts +2 -2
  95. package/src/scripts/caching.ts +27 -19
  96. package/src/scripts/code_exec_files.ts +58 -15
  97. package/src/scripts/code_exec_multi_session.ts +241 -0
  98. package/src/scripts/code_exec_session.ts +282 -0
  99. package/src/scripts/multi-agent-conditional.ts +1 -0
  100. package/src/scripts/multi-agent-supervisor.ts +1 -0
  101. package/src/scripts/programmatic_exec_agent.ts +4 -4
  102. package/src/scripts/test-handoff-preamble.ts +277 -0
  103. package/src/scripts/test-parallel-handoffs.ts +291 -0
  104. package/src/scripts/test-tools-before-handoff.ts +8 -4
  105. package/src/scripts/test_code_api.ts +361 -0
  106. package/src/scripts/thinking-bedrock.ts +159 -0
  107. package/src/scripts/thinking.ts +39 -18
  108. package/src/scripts/{tool_search_regex.ts → tool_search.ts} +5 -5
  109. package/src/scripts/tools.ts +7 -3
  110. package/src/stream.ts +4 -2
  111. package/src/tools/BrowserTools.ts +68 -14
  112. package/src/tools/CodeExecutor.ts +26 -23
  113. package/src/tools/ProgrammaticToolCalling.ts +18 -14
  114. package/src/tools/ToolNode.ts +114 -1
  115. package/src/tools/ToolSearch.ts +1041 -0
  116. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
  117. package/src/tools/__tests__/{ToolSearchRegex.integration.test.ts → ToolSearch.integration.test.ts} +6 -6
  118. package/src/tools/__tests__/ToolSearch.test.ts +1003 -0
  119. package/src/types/graph.ts +2 -0
  120. package/src/types/llm.ts +3 -1
  121. package/src/types/tools.ts +51 -2
  122. package/dist/cjs/tools/ToolSearchRegex.cjs +0 -455
  123. package/dist/cjs/tools/ToolSearchRegex.cjs.map +0 -1
  124. package/dist/esm/tools/ToolSearchRegex.mjs +0 -448
  125. package/dist/esm/tools/ToolSearchRegex.mjs.map +0 -1
  126. package/dist/types/tools/ToolSearchRegex.d.ts +0 -80
  127. package/src/tools/ToolSearchRegex.ts +0 -535
  128. package/src/tools/__tests__/ToolSearchRegex.test.ts +0 -232
@@ -0,0 +1,1003 @@
1
+ // src/tools/__tests__/ToolSearch.test.ts
2
+ /**
3
+ * Unit tests for Tool Search.
4
+ * Tests helper functions and sanitization logic without hitting the API.
5
+ */
6
+ import { describe, it, expect } from '@jest/globals';
7
+ import {
8
+ sanitizeRegex,
9
+ escapeRegexSpecialChars,
10
+ isDangerousPattern,
11
+ countNestedGroups,
12
+ hasNestedQuantifiers,
13
+ performLocalSearch,
14
+ extractMcpServerName,
15
+ isFromMcpServer,
16
+ isFromAnyMcpServer,
17
+ normalizeServerFilter,
18
+ getAvailableMcpServers,
19
+ getDeferredToolsListing,
20
+ getBaseToolName,
21
+ formatServerListing,
22
+ } from '../ToolSearch';
23
+ import type { ToolMetadata, LCToolRegistry } from '@/types';
24
+
25
+ describe('ToolSearch', () => {
26
+ describe('escapeRegexSpecialChars', () => {
27
+ it('escapes special regex characters', () => {
28
+ expect(escapeRegexSpecialChars('hello.world')).toBe('hello\\.world');
29
+ expect(escapeRegexSpecialChars('test*pattern')).toBe('test\\*pattern');
30
+ expect(escapeRegexSpecialChars('query+result')).toBe('query\\+result');
31
+ expect(escapeRegexSpecialChars('a?b')).toBe('a\\?b');
32
+ expect(escapeRegexSpecialChars('(group)')).toBe('\\(group\\)');
33
+ expect(escapeRegexSpecialChars('[abc]')).toBe('\\[abc\\]');
34
+ expect(escapeRegexSpecialChars('a|b')).toBe('a\\|b');
35
+ expect(escapeRegexSpecialChars('a^b$c')).toBe('a\\^b\\$c');
36
+ expect(escapeRegexSpecialChars('a{2,3}')).toBe('a\\{2,3\\}');
37
+ });
38
+
39
+ it('handles empty string', () => {
40
+ expect(escapeRegexSpecialChars('')).toBe('');
41
+ });
42
+
43
+ it('handles string with no special chars', () => {
44
+ expect(escapeRegexSpecialChars('hello_world')).toBe('hello_world');
45
+ expect(escapeRegexSpecialChars('test123')).toBe('test123');
46
+ });
47
+
48
+ it('handles multiple consecutive special chars', () => {
49
+ expect(escapeRegexSpecialChars('...')).toBe('\\.\\.\\.');
50
+ expect(escapeRegexSpecialChars('***')).toBe('\\*\\*\\*');
51
+ });
52
+ });
53
+
54
+ describe('countNestedGroups', () => {
55
+ it('counts simple nesting', () => {
56
+ expect(countNestedGroups('(a)')).toBe(1);
57
+ expect(countNestedGroups('((a))')).toBe(2);
58
+ expect(countNestedGroups('(((a)))')).toBe(3);
59
+ });
60
+
61
+ it('counts maximum depth with multiple groups', () => {
62
+ expect(countNestedGroups('(a)(b)(c)')).toBe(1);
63
+ expect(countNestedGroups('(a(b)c)')).toBe(2);
64
+ expect(countNestedGroups('(a(b(c)))')).toBe(3);
65
+ });
66
+
67
+ it('handles mixed nesting levels', () => {
68
+ expect(countNestedGroups('(a)((b)(c))')).toBe(2);
69
+ expect(countNestedGroups('((a)(b))((c))')).toBe(2);
70
+ });
71
+
72
+ it('ignores escaped parentheses', () => {
73
+ expect(countNestedGroups('\\(not a group\\)')).toBe(0);
74
+ expect(countNestedGroups('(a\\(b\\)c)')).toBe(1);
75
+ });
76
+
77
+ it('handles no groups', () => {
78
+ expect(countNestedGroups('abc')).toBe(0);
79
+ expect(countNestedGroups('test.*pattern')).toBe(0);
80
+ });
81
+
82
+ it('handles unbalanced groups', () => {
83
+ expect(countNestedGroups('((a)')).toBe(2);
84
+ expect(countNestedGroups('(a))')).toBe(1);
85
+ });
86
+ });
87
+
88
+ describe('hasNestedQuantifiers', () => {
89
+ it('detects nested quantifiers', () => {
90
+ expect(hasNestedQuantifiers('(a+)+')).toBe(true);
91
+ expect(hasNestedQuantifiers('(a*)*')).toBe(true);
92
+ expect(hasNestedQuantifiers('(a+)*')).toBe(true);
93
+ expect(hasNestedQuantifiers('(a*)?')).toBe(true);
94
+ });
95
+
96
+ it('allows safe quantifiers', () => {
97
+ expect(hasNestedQuantifiers('a+')).toBe(false);
98
+ expect(hasNestedQuantifiers('(abc)+')).toBe(false);
99
+ expect(hasNestedQuantifiers('a+b*c?')).toBe(false);
100
+ });
101
+
102
+ it('handles complex patterns', () => {
103
+ expect(hasNestedQuantifiers('(a|b)+')).toBe(false);
104
+ // Note: This pattern might not be detected by the simple regex check
105
+ const complexPattern = '((a|b)+)+';
106
+ const result = hasNestedQuantifiers(complexPattern);
107
+ // Just verify it doesn't crash - detection may vary
108
+ expect(typeof result).toBe('boolean');
109
+ });
110
+ });
111
+
112
+ describe('isDangerousPattern', () => {
113
+ it('detects nested quantifiers', () => {
114
+ expect(isDangerousPattern('(a+)+')).toBe(true);
115
+ expect(isDangerousPattern('(a*)*')).toBe(true);
116
+ expect(isDangerousPattern('(.+)+')).toBe(true);
117
+ expect(isDangerousPattern('(.*)*')).toBe(true);
118
+ });
119
+
120
+ it('detects excessive nesting', () => {
121
+ expect(isDangerousPattern('((((((a))))))')).toBe(true); // Depth > 5
122
+ });
123
+
124
+ it('detects excessive wildcards', () => {
125
+ const pattern = '.{1000,}';
126
+ expect(isDangerousPattern(pattern)).toBe(true);
127
+ });
128
+
129
+ it('allows safe patterns', () => {
130
+ expect(isDangerousPattern('weather')).toBe(false);
131
+ expect(isDangerousPattern('get_.*_data')).toBe(false);
132
+ expect(isDangerousPattern('(a|b|c)')).toBe(false);
133
+ expect(isDangerousPattern('test\\d+')).toBe(false);
134
+ });
135
+
136
+ it('detects various dangerous patterns', () => {
137
+ expect(isDangerousPattern('(.*)+')).toBe(true);
138
+ expect(isDangerousPattern('(.+)*')).toBe(true);
139
+ });
140
+ });
141
+
142
+ describe('sanitizeRegex', () => {
143
+ it('returns safe pattern unchanged', () => {
144
+ const result = sanitizeRegex('weather');
145
+ expect(result.safe).toBe('weather');
146
+ expect(result.wasEscaped).toBe(false);
147
+ });
148
+
149
+ it('escapes dangerous patterns', () => {
150
+ const result = sanitizeRegex('(a+)+');
151
+ expect(result.safe).toBe('\\(a\\+\\)\\+');
152
+ expect(result.wasEscaped).toBe(true);
153
+ });
154
+
155
+ it('escapes invalid regex', () => {
156
+ const result = sanitizeRegex('(unclosed');
157
+ expect(result.wasEscaped).toBe(true);
158
+ expect(result.safe).toContain('\\(');
159
+ });
160
+
161
+ it('allows complex but safe patterns', () => {
162
+ const result = sanitizeRegex('get_[a-z]+_data');
163
+ expect(result.safe).toBe('get_[a-z]+_data');
164
+ expect(result.wasEscaped).toBe(false);
165
+ });
166
+
167
+ it('handles alternation patterns', () => {
168
+ const result = sanitizeRegex('weather|forecast');
169
+ expect(result.safe).toBe('weather|forecast');
170
+ expect(result.wasEscaped).toBe(false);
171
+ });
172
+ });
173
+
174
+ describe('Pattern Validation Edge Cases', () => {
175
+ it('handles empty pattern', () => {
176
+ expect(countNestedGroups('')).toBe(0);
177
+ expect(hasNestedQuantifiers('')).toBe(false);
178
+ expect(isDangerousPattern('')).toBe(false);
179
+ });
180
+
181
+ it('handles pattern with only quantifiers', () => {
182
+ expect(hasNestedQuantifiers('+++')).toBe(false);
183
+ expect(hasNestedQuantifiers('***')).toBe(false);
184
+ });
185
+
186
+ it('handles escaped special sequences', () => {
187
+ const result = sanitizeRegex('\\d+\\w*\\s?');
188
+ expect(result.wasEscaped).toBe(false);
189
+ });
190
+
191
+ it('sanitizes exponential backtracking patterns', () => {
192
+ // These can cause catastrophic backtracking
193
+ expect(isDangerousPattern('(a+)+')).toBe(true);
194
+ expect(isDangerousPattern('(a*)*')).toBe(true);
195
+ expect(isDangerousPattern('(.*)*')).toBe(true);
196
+ });
197
+ });
198
+
199
+ describe('Real-World Pattern Examples', () => {
200
+ it('handles common search patterns safely', () => {
201
+ const safePatterns = [
202
+ 'expense',
203
+ 'weather|forecast',
204
+ 'data.*query',
205
+ '_tool$',
206
+ ];
207
+
208
+ for (const pattern of safePatterns) {
209
+ const result = sanitizeRegex(pattern);
210
+ expect(result.wasEscaped).toBe(false);
211
+ }
212
+ });
213
+
214
+ it('escapes clearly dangerous patterns', () => {
215
+ const dangerousPatterns = ['(a+)+', '(.*)+', '(.+)*'];
216
+
217
+ for (const pattern of dangerousPatterns) {
218
+ const result = sanitizeRegex(pattern);
219
+ expect(result.wasEscaped).toBe(true);
220
+ }
221
+ });
222
+
223
+ it('handles patterns that may or may not be escaped', () => {
224
+ // These patterns might be escaped depending on validation logic
225
+ const edgeCasePatterns = [
226
+ '(?i)email',
227
+ '^create_',
228
+ 'get_[a-z]+_info',
229
+ 'get_.*',
230
+ '((((((a))))))',
231
+ '(a|a)*',
232
+ ];
233
+
234
+ for (const pattern of edgeCasePatterns) {
235
+ const result = sanitizeRegex(pattern);
236
+ // Just verify it returns a result without crashing
237
+ expect(typeof result.safe).toBe('string');
238
+ expect(typeof result.wasEscaped).toBe('boolean');
239
+ }
240
+ });
241
+ });
242
+
243
+ describe('performLocalSearch', () => {
244
+ const mockTools: ToolMetadata[] = [
245
+ {
246
+ name: 'get_weather',
247
+ description: 'Get current weather data',
248
+ parameters: undefined,
249
+ },
250
+ {
251
+ name: 'get_forecast',
252
+ description: 'Get weather forecast for multiple days',
253
+ parameters: undefined,
254
+ },
255
+ {
256
+ name: 'send_email',
257
+ description: 'Send an email message',
258
+ parameters: undefined,
259
+ },
260
+ {
261
+ name: 'get_expenses',
262
+ description: 'Retrieve expense reports',
263
+ parameters: undefined,
264
+ },
265
+ {
266
+ name: 'calculate_expense_totals',
267
+ description: 'Sum up expenses by category',
268
+ parameters: undefined,
269
+ },
270
+ {
271
+ name: 'run_database_query',
272
+ description: 'Execute a database query',
273
+ parameters: {
274
+ type: 'object',
275
+ properties: {
276
+ query: { type: 'string' },
277
+ timeout: { type: 'number' },
278
+ },
279
+ },
280
+ },
281
+ ];
282
+
283
+ it('finds tools by exact name match', () => {
284
+ // BM25 tokenizes "get weather" from "get_weather"
285
+ const result = performLocalSearch(mockTools, 'get weather', ['name'], 10);
286
+
287
+ expect(result.tool_references.length).toBeGreaterThan(0);
288
+ expect(result.tool_references[0].tool_name).toBe('get_weather');
289
+ expect(result.tool_references[0].match_score).toBeGreaterThan(0.5);
290
+ expect(result.tool_references[0].matched_field).toBe('name');
291
+ });
292
+
293
+ it('finds tools by partial name match', () => {
294
+ // BM25 finds tools containing "get" token
295
+ const result = performLocalSearch(mockTools, 'get', ['name'], 10);
296
+
297
+ expect(result.tool_references.length).toBe(3);
298
+ expect(result.tool_references[0].match_score).toBeGreaterThan(0);
299
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
300
+ 'get_weather'
301
+ );
302
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
303
+ 'get_forecast'
304
+ );
305
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
306
+ 'get_expenses'
307
+ );
308
+ });
309
+
310
+ it('finds tools by substring match in name', () => {
311
+ const result = performLocalSearch(mockTools, 'expense', ['name'], 10);
312
+
313
+ expect(result.tool_references.length).toBe(2);
314
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
315
+ 'get_expenses'
316
+ );
317
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
318
+ 'calculate_expense_totals'
319
+ );
320
+ expect(result.tool_references[0].match_score).toBeGreaterThan(0);
321
+ });
322
+
323
+ it('performs case-insensitive search', () => {
324
+ const result = performLocalSearch(
325
+ mockTools,
326
+ 'WEATHER',
327
+ ['name', 'description'],
328
+ 10
329
+ );
330
+
331
+ expect(result.tool_references.length).toBe(2);
332
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
333
+ 'get_weather'
334
+ );
335
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
336
+ 'get_forecast'
337
+ );
338
+ });
339
+
340
+ it('searches in description field', () => {
341
+ const result = performLocalSearch(
342
+ mockTools,
343
+ 'email',
344
+ ['description'],
345
+ 10
346
+ );
347
+
348
+ expect(result.tool_references.length).toBe(1);
349
+ expect(result.tool_references[0].tool_name).toBe('send_email');
350
+ expect(result.tool_references[0].matched_field).toBe('description');
351
+ expect(result.tool_references[0].match_score).toBeGreaterThan(0);
352
+ });
353
+
354
+ it('searches in parameter names', () => {
355
+ const result = performLocalSearch(mockTools, 'query', ['parameters'], 10);
356
+
357
+ expect(result.tool_references.length).toBeGreaterThan(0);
358
+ expect(result.tool_references[0].tool_name).toBe('run_database_query');
359
+ expect(result.tool_references[0].matched_field).toBe('parameters');
360
+ expect(result.tool_references[0].match_score).toBeGreaterThan(0);
361
+ });
362
+
363
+ it('prioritizes name matches over description matches', () => {
364
+ const result = performLocalSearch(
365
+ mockTools,
366
+ 'weather',
367
+ ['name', 'description'],
368
+ 10
369
+ );
370
+
371
+ const weatherTool = result.tool_references.find(
372
+ (r) => r.tool_name === 'get_weather'
373
+ );
374
+ const forecastTool = result.tool_references.find(
375
+ (r) => r.tool_name === 'get_forecast'
376
+ );
377
+
378
+ expect(weatherTool?.matched_field).toBe('name');
379
+ expect(forecastTool?.matched_field).toBe('description');
380
+ expect(weatherTool!.match_score).toBeGreaterThan(
381
+ forecastTool!.match_score
382
+ );
383
+ });
384
+
385
+ it('limits results to max_results', () => {
386
+ const result = performLocalSearch(mockTools, 'get', ['name'], 2);
387
+
388
+ expect(result.tool_references.length).toBe(2);
389
+ expect(result.total_tools_searched).toBe(mockTools.length);
390
+ });
391
+
392
+ it('returns empty array when no matches found', () => {
393
+ const result = performLocalSearch(
394
+ mockTools,
395
+ 'nonexistent_xyz_123',
396
+ ['name', 'description'],
397
+ 10
398
+ );
399
+
400
+ expect(result.tool_references.length).toBe(0);
401
+ expect(result.total_tools_searched).toBe(mockTools.length);
402
+ });
403
+
404
+ it('sorts results by score descending', () => {
405
+ const result = performLocalSearch(
406
+ mockTools,
407
+ 'expense',
408
+ ['name', 'description'],
409
+ 10
410
+ );
411
+
412
+ for (let i = 1; i < result.tool_references.length; i++) {
413
+ expect(
414
+ result.tool_references[i - 1].match_score
415
+ ).toBeGreaterThanOrEqual(result.tool_references[i].match_score);
416
+ }
417
+ });
418
+
419
+ it('handles empty tools array', () => {
420
+ const result = performLocalSearch([], 'test', ['name'], 10);
421
+
422
+ expect(result.tool_references.length).toBe(0);
423
+ expect(result.total_tools_searched).toBe(0);
424
+ });
425
+
426
+ it('handles empty query gracefully', () => {
427
+ const result = performLocalSearch(mockTools, '', ['name'], 10);
428
+
429
+ // BM25 correctly returns no results for empty queries (no terms to match)
430
+ expect(result.tool_references.length).toBe(0);
431
+ expect(result.total_tools_searched).toBe(mockTools.length);
432
+ });
433
+
434
+ it('includes correct metadata in response', () => {
435
+ const result = performLocalSearch(mockTools, 'weather', ['name'], 10);
436
+
437
+ expect(result.total_tools_searched).toBe(mockTools.length);
438
+ expect(result.pattern_used).toBe('weather');
439
+ });
440
+
441
+ it('provides snippet in results', () => {
442
+ const result = performLocalSearch(
443
+ mockTools,
444
+ 'database',
445
+ ['description'],
446
+ 10
447
+ );
448
+
449
+ expect(result.tool_references[0].snippet).toBeTruthy();
450
+ expect(result.tool_references[0].snippet.length).toBeGreaterThan(0);
451
+ });
452
+ });
453
+
454
+ describe('extractMcpServerName', () => {
455
+ it('extracts server name from MCP tool name', () => {
456
+ expect(extractMcpServerName('get_weather_mcp_weather-server')).toBe(
457
+ 'weather-server'
458
+ );
459
+ expect(extractMcpServerName('send_email_mcp_gmail')).toBe('gmail');
460
+ expect(extractMcpServerName('query_database_mcp_postgres-mcp')).toBe(
461
+ 'postgres-mcp'
462
+ );
463
+ });
464
+
465
+ it('returns undefined for non-MCP tools', () => {
466
+ expect(extractMcpServerName('get_weather')).toBeUndefined();
467
+ expect(extractMcpServerName('send_email')).toBeUndefined();
468
+ expect(extractMcpServerName('regular_tool_name')).toBeUndefined();
469
+ });
470
+
471
+ it('handles edge cases', () => {
472
+ expect(extractMcpServerName('_mcp_server')).toBe('server');
473
+ expect(extractMcpServerName('tool_mcp_')).toBe('');
474
+ });
475
+ });
476
+
477
+ describe('getBaseToolName', () => {
478
+ it('extracts base name from MCP tool name', () => {
479
+ expect(getBaseToolName('get_weather_mcp_weather-server')).toBe(
480
+ 'get_weather'
481
+ );
482
+ expect(getBaseToolName('send_email_mcp_gmail')).toBe('send_email');
483
+ });
484
+
485
+ it('returns full name for non-MCP tools', () => {
486
+ expect(getBaseToolName('get_weather')).toBe('get_weather');
487
+ expect(getBaseToolName('regular_tool')).toBe('regular_tool');
488
+ });
489
+ });
490
+
491
+ describe('isFromMcpServer', () => {
492
+ it('returns true for matching MCP server', () => {
493
+ expect(
494
+ isFromMcpServer('get_weather_mcp_weather-server', 'weather-server')
495
+ ).toBe(true);
496
+ expect(isFromMcpServer('send_email_mcp_gmail', 'gmail')).toBe(true);
497
+ });
498
+
499
+ it('returns false for non-matching MCP server', () => {
500
+ expect(
501
+ isFromMcpServer('get_weather_mcp_weather-server', 'other-server')
502
+ ).toBe(false);
503
+ expect(isFromMcpServer('send_email_mcp_gmail', 'outlook')).toBe(false);
504
+ });
505
+
506
+ it('returns false for non-MCP tools', () => {
507
+ expect(isFromMcpServer('get_weather', 'weather-server')).toBe(false);
508
+ expect(isFromMcpServer('regular_tool', 'any-server')).toBe(false);
509
+ });
510
+ });
511
+
512
+ describe('isFromAnyMcpServer', () => {
513
+ it('returns true if tool is from any of the specified servers', () => {
514
+ expect(
515
+ isFromAnyMcpServer('get_weather_mcp_weather-api', [
516
+ 'weather-api',
517
+ 'gmail',
518
+ ])
519
+ ).toBe(true);
520
+ expect(
521
+ isFromAnyMcpServer('send_email_mcp_gmail', ['weather-api', 'gmail'])
522
+ ).toBe(true);
523
+ });
524
+
525
+ it('returns false if tool is not from any specified server', () => {
526
+ expect(
527
+ isFromAnyMcpServer('get_weather_mcp_weather-api', ['gmail', 'slack'])
528
+ ).toBe(false);
529
+ });
530
+
531
+ it('returns false for non-MCP tools', () => {
532
+ expect(isFromAnyMcpServer('regular_tool', ['weather-api', 'gmail'])).toBe(
533
+ false
534
+ );
535
+ });
536
+
537
+ it('returns false for empty server list', () => {
538
+ expect(isFromAnyMcpServer('get_weather_mcp_weather-api', [])).toBe(false);
539
+ });
540
+ });
541
+
542
+ describe('normalizeServerFilter', () => {
543
+ it('converts string to single-element array', () => {
544
+ expect(normalizeServerFilter('gmail')).toEqual(['gmail']);
545
+ });
546
+
547
+ it('passes through arrays unchanged', () => {
548
+ expect(normalizeServerFilter(['gmail', 'slack'])).toEqual([
549
+ 'gmail',
550
+ 'slack',
551
+ ]);
552
+ });
553
+
554
+ it('returns empty array for undefined', () => {
555
+ expect(normalizeServerFilter(undefined)).toEqual([]);
556
+ });
557
+
558
+ it('returns empty array for empty string', () => {
559
+ expect(normalizeServerFilter('')).toEqual([]);
560
+ });
561
+
562
+ it('filters out empty strings from arrays', () => {
563
+ expect(normalizeServerFilter(['gmail', '', 'slack'])).toEqual([
564
+ 'gmail',
565
+ 'slack',
566
+ ]);
567
+ });
568
+ });
569
+
570
+ describe('getAvailableMcpServers', () => {
571
+ const createRegistry = (): LCToolRegistry => {
572
+ const registry: LCToolRegistry = new Map();
573
+ registry.set('get_weather_mcp_weather-api', {
574
+ name: 'get_weather_mcp_weather-api',
575
+ description: 'Get weather',
576
+ defer_loading: true,
577
+ });
578
+ registry.set('get_forecast_mcp_weather-api', {
579
+ name: 'get_forecast_mcp_weather-api',
580
+ description: 'Get forecast',
581
+ defer_loading: true,
582
+ });
583
+ registry.set('send_email_mcp_gmail', {
584
+ name: 'send_email_mcp_gmail',
585
+ description: 'Send email',
586
+ defer_loading: true,
587
+ });
588
+ registry.set('read_inbox_mcp_gmail', {
589
+ name: 'read_inbox_mcp_gmail',
590
+ description: 'Read inbox',
591
+ defer_loading: true,
592
+ });
593
+ registry.set('post_message_mcp_slack', {
594
+ name: 'post_message_mcp_slack',
595
+ description: 'Post to Slack',
596
+ defer_loading: true,
597
+ });
598
+ registry.set('regular_tool', {
599
+ name: 'regular_tool',
600
+ description: 'Not an MCP tool',
601
+ defer_loading: true,
602
+ });
603
+ registry.set('non_deferred_mcp_special', {
604
+ name: 'non_deferred_mcp_special',
605
+ description: 'Not deferred',
606
+ defer_loading: false,
607
+ });
608
+ return registry;
609
+ };
610
+
611
+ it('extracts unique server names from registry', () => {
612
+ const registry = createRegistry();
613
+ const servers = getAvailableMcpServers(registry, true);
614
+
615
+ expect(servers).toEqual(['gmail', 'slack', 'weather-api']);
616
+ });
617
+
618
+ it('returns servers sorted alphabetically', () => {
619
+ const registry = createRegistry();
620
+ const servers = getAvailableMcpServers(registry, true);
621
+
622
+ expect(servers).toEqual([...servers].sort());
623
+ });
624
+
625
+ it('excludes non-MCP tools', () => {
626
+ const registry = createRegistry();
627
+ const servers = getAvailableMcpServers(registry, true);
628
+
629
+ expect(servers).not.toContain('regular_tool');
630
+ });
631
+
632
+ it('respects onlyDeferred flag', () => {
633
+ const registry = createRegistry();
634
+
635
+ const deferredOnly = getAvailableMcpServers(registry, true);
636
+ expect(deferredOnly).not.toContain('special');
637
+
638
+ const allTools = getAvailableMcpServers(registry, false);
639
+ expect(allTools).toContain('special');
640
+ });
641
+
642
+ it('returns empty array for undefined registry', () => {
643
+ expect(getAvailableMcpServers(undefined, true)).toEqual([]);
644
+ });
645
+
646
+ it('returns empty array for registry with no MCP tools', () => {
647
+ const registry: LCToolRegistry = new Map();
648
+ registry.set('tool1', {
649
+ name: 'tool1',
650
+ description: 'Regular tool',
651
+ defer_loading: true,
652
+ });
653
+
654
+ expect(getAvailableMcpServers(registry, true)).toEqual([]);
655
+ });
656
+ });
657
+
658
+ describe('getDeferredToolsListing', () => {
659
+ const createRegistry = (): LCToolRegistry => {
660
+ const registry: LCToolRegistry = new Map();
661
+ registry.set('get_weather_mcp_weather-api', {
662
+ name: 'get_weather_mcp_weather-api',
663
+ description: 'Get weather',
664
+ defer_loading: true,
665
+ });
666
+ registry.set('get_forecast_mcp_weather-api', {
667
+ name: 'get_forecast_mcp_weather-api',
668
+ description: 'Get forecast',
669
+ defer_loading: true,
670
+ });
671
+ registry.set('send_email_mcp_gmail', {
672
+ name: 'send_email_mcp_gmail',
673
+ description: 'Send email',
674
+ defer_loading: true,
675
+ });
676
+ registry.set('execute_code', {
677
+ name: 'execute_code',
678
+ description: 'Execute code',
679
+ defer_loading: true,
680
+ });
681
+ registry.set('read_file', {
682
+ name: 'read_file',
683
+ description: 'Read file',
684
+ defer_loading: false,
685
+ });
686
+ return registry;
687
+ };
688
+
689
+ it('groups tools by server with format D', () => {
690
+ const registry = createRegistry();
691
+ const listing = getDeferredToolsListing(registry, true);
692
+
693
+ expect(listing).toContain('gmail: send_email');
694
+ expect(listing).toContain('weather-api: get_weather, get_forecast');
695
+ expect(listing).toContain('other: execute_code');
696
+ });
697
+
698
+ it('sorts servers alphabetically with other last', () => {
699
+ const registry = createRegistry();
700
+ const listing = getDeferredToolsListing(registry, true);
701
+ const lines = listing.split('\n');
702
+
703
+ expect(lines[0]).toMatch(/^gmail:/);
704
+ expect(lines[1]).toMatch(/^weather-api:/);
705
+ expect(lines[2]).toMatch(/^other:/);
706
+ });
707
+
708
+ it('uses base tool names without MCP suffix', () => {
709
+ const registry = createRegistry();
710
+ const listing = getDeferredToolsListing(registry, true);
711
+
712
+ expect(listing).toContain('get_weather');
713
+ expect(listing).not.toContain('get_weather_mcp_weather-api');
714
+ });
715
+
716
+ it('respects onlyDeferred flag', () => {
717
+ const registry = createRegistry();
718
+
719
+ const deferredOnly = getDeferredToolsListing(registry, true);
720
+ expect(deferredOnly).not.toContain('read_file');
721
+
722
+ const allTools = getDeferredToolsListing(registry, false);
723
+ expect(allTools).toContain('read_file');
724
+ });
725
+
726
+ it('returns empty string for undefined registry', () => {
727
+ expect(getDeferredToolsListing(undefined, true)).toBe('');
728
+ });
729
+
730
+ it('returns empty string for registry with no matching tools', () => {
731
+ const registry: LCToolRegistry = new Map();
732
+ registry.set('read_file', {
733
+ name: 'read_file',
734
+ description: 'Read file',
735
+ defer_loading: false,
736
+ });
737
+
738
+ expect(getDeferredToolsListing(registry, true)).toBe('');
739
+ });
740
+ });
741
+
742
+ describe('performLocalSearch with MCP tools', () => {
743
+ const mcpTools: ToolMetadata[] = [
744
+ {
745
+ name: 'get_weather_mcp_weather-server',
746
+ description: 'Get weather from MCP server',
747
+ parameters: undefined,
748
+ },
749
+ {
750
+ name: 'get_forecast_mcp_weather-server',
751
+ description: 'Get forecast from MCP server',
752
+ parameters: undefined,
753
+ },
754
+ {
755
+ name: 'send_email_mcp_gmail',
756
+ description: 'Send email via Gmail MCP',
757
+ parameters: undefined,
758
+ },
759
+ {
760
+ name: 'read_inbox_mcp_gmail',
761
+ description: 'Read inbox via Gmail MCP',
762
+ parameters: undefined,
763
+ },
764
+ {
765
+ name: 'get_weather',
766
+ description: 'Regular weather tool (not MCP)',
767
+ parameters: undefined,
768
+ },
769
+ ];
770
+
771
+ it('searches across all tools including MCP tools', () => {
772
+ const result = performLocalSearch(
773
+ mcpTools,
774
+ 'weather',
775
+ ['name', 'description'],
776
+ 10
777
+ );
778
+
779
+ expect(result.tool_references.length).toBe(3);
780
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
781
+ 'get_weather_mcp_weather-server'
782
+ );
783
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
784
+ 'get_weather'
785
+ );
786
+ });
787
+
788
+ it('finds MCP tools by searching the full name including server suffix', () => {
789
+ const result = performLocalSearch(mcpTools, 'gmail', ['name'], 10);
790
+
791
+ expect(result.tool_references.length).toBe(2);
792
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
793
+ 'send_email_mcp_gmail'
794
+ );
795
+ expect(result.tool_references.map((r) => r.tool_name)).toContain(
796
+ 'read_inbox_mcp_gmail'
797
+ );
798
+ });
799
+
800
+ it('can search for tools by MCP keyword', () => {
801
+ // BM25 tokenizes queries, so search for "mcp" to find MCP tools
802
+ const result = performLocalSearch(mcpTools, 'mcp', ['name'], 10);
803
+
804
+ expect(result.tool_references.length).toBe(4);
805
+ expect(result.tool_references.map((r) => r.tool_name)).not.toContain(
806
+ 'get_weather'
807
+ );
808
+ });
809
+
810
+ it('finds tools when query contains underscores', () => {
811
+ // Underscores in query should be tokenized the same as in tool names
812
+ const tools: ToolMetadata[] = [
813
+ {
814
+ name: 'convert_time_mcp_time',
815
+ description: 'Convert time between timezones',
816
+ parameters: undefined,
817
+ },
818
+ ];
819
+
820
+ const result = performLocalSearch(tools, 'convert_time', ['name'], 10);
821
+
822
+ expect(result.tool_references.length).toBe(1);
823
+ expect(result.tool_references[0].tool_name).toBe('convert_time_mcp_time');
824
+ expect(result.tool_references[0].match_score).toBeGreaterThan(0.5);
825
+ });
826
+
827
+ it('finds tools with partial underscore query', () => {
828
+ const tools: ToolMetadata[] = [
829
+ {
830
+ name: 'get_current_time_mcp_time',
831
+ description: 'Get current time',
832
+ parameters: undefined,
833
+ },
834
+ {
835
+ name: 'convert_time_mcp_time',
836
+ description: 'Convert time between timezones',
837
+ parameters: undefined,
838
+ },
839
+ ];
840
+
841
+ // "current_time" should match "get_current_time_mcp_time"
842
+ const result = performLocalSearch(tools, 'current_time', ['name'], 10);
843
+
844
+ expect(result.tool_references.length).toBeGreaterThan(0);
845
+ expect(result.tool_references[0].tool_name).toBe(
846
+ 'get_current_time_mcp_time'
847
+ );
848
+ });
849
+
850
+ it('gives exact base name match a perfect score', () => {
851
+ const tools: ToolMetadata[] = [
852
+ {
853
+ name: 'convert_time_mcp_time',
854
+ description: 'Convert time between timezones',
855
+ parameters: undefined,
856
+ },
857
+ {
858
+ name: 'get_current_time_mcp_time',
859
+ description: 'Get current time',
860
+ parameters: undefined,
861
+ },
862
+ ];
863
+
864
+ // Exact match on base name should get score of 1.0
865
+ const result = performLocalSearch(tools, 'convert_time', ['name'], 10);
866
+
867
+ expect(result.tool_references[0].tool_name).toBe('convert_time_mcp_time');
868
+ expect(result.tool_references[0].match_score).toBe(1.0);
869
+ });
870
+
871
+ it('boosts starts-with matches on base name', () => {
872
+ const tools: ToolMetadata[] = [
873
+ {
874
+ name: 'send_email_mcp_gmail',
875
+ description: 'Send email',
876
+ parameters: undefined,
877
+ },
878
+ {
879
+ name: 'read_email_mcp_gmail',
880
+ description: 'Read email',
881
+ parameters: undefined,
882
+ },
883
+ ];
884
+
885
+ // "send" starts-with "send_email", should get boosted score
886
+ const result = performLocalSearch(tools, 'send', ['name'], 10);
887
+
888
+ expect(result.tool_references[0].tool_name).toBe('send_email_mcp_gmail');
889
+ expect(result.tool_references[0].match_score).toBeGreaterThanOrEqual(
890
+ 0.95
891
+ );
892
+ });
893
+ });
894
+
895
+ describe('formatServerListing', () => {
896
+ const serverTools: ToolMetadata[] = [
897
+ {
898
+ name: 'get_weather_mcp_weather-api',
899
+ description: 'Get current weather conditions for a location',
900
+ parameters: undefined,
901
+ },
902
+ {
903
+ name: 'get_forecast_mcp_weather-api',
904
+ description: 'Get weather forecast for the next 7 days',
905
+ parameters: undefined,
906
+ },
907
+ ];
908
+
909
+ it('returns valid JSON with tool listing', () => {
910
+ const result = formatServerListing(serverTools, 'weather-api');
911
+ const parsed = JSON.parse(result);
912
+
913
+ expect(parsed.listing_mode).toBe(true);
914
+ expect(parsed.servers).toEqual(['weather-api']);
915
+ expect(parsed.total_tools).toBe(2);
916
+ expect(parsed.tools_by_server['weather-api']).toHaveLength(2);
917
+ });
918
+
919
+ it('includes hint to search for specific tool to load it', () => {
920
+ const result = formatServerListing(serverTools, 'weather-api');
921
+ const parsed = JSON.parse(result);
922
+
923
+ expect(parsed.hint).toContain('To use a tool, search for it by name');
924
+ });
925
+
926
+ it('uses base tool name (without MCP suffix) in display', () => {
927
+ const result = formatServerListing(serverTools, 'weather-api');
928
+ const parsed = JSON.parse(result);
929
+
930
+ const toolNames = parsed.tools_by_server['weather-api'].map(
931
+ (t: { name: string }) => t.name
932
+ );
933
+ expect(toolNames).toContain('get_weather');
934
+ expect(toolNames).not.toContain('get_weather_mcp_weather-api');
935
+ });
936
+
937
+ it('handles empty tools array', () => {
938
+ const result = formatServerListing([], 'empty-server');
939
+ const parsed = JSON.parse(result);
940
+
941
+ expect(parsed.total_tools).toBe(0);
942
+ expect(parsed.servers).toContain('empty-server');
943
+ expect(parsed.hint).toContain('No tools found');
944
+ });
945
+
946
+ it('truncates long descriptions', () => {
947
+ const toolsWithLongDesc: ToolMetadata[] = [
948
+ {
949
+ name: 'long_tool_mcp_server',
950
+ description:
951
+ 'This is a very long description that exceeds 100 characters and should be truncated to keep the listing compact and readable for the LLM.',
952
+ parameters: undefined,
953
+ },
954
+ ];
955
+
956
+ const result = formatServerListing(toolsWithLongDesc, 'server');
957
+ const parsed = JSON.parse(result);
958
+
959
+ const toolDesc = parsed.tools_by_server['server'][0].description;
960
+ expect(toolDesc).toContain('...');
961
+ expect(toolDesc.length).toBeLessThanOrEqual(100);
962
+ });
963
+
964
+ it('handles multiple servers with grouped output', () => {
965
+ const multiServerTools: ToolMetadata[] = [
966
+ {
967
+ name: 'get_weather_mcp_weather-api',
968
+ description: 'Get weather',
969
+ parameters: undefined,
970
+ },
971
+ {
972
+ name: 'send_email_mcp_gmail',
973
+ description: 'Send email',
974
+ parameters: undefined,
975
+ },
976
+ {
977
+ name: 'read_inbox_mcp_gmail',
978
+ description: 'Read inbox',
979
+ parameters: undefined,
980
+ },
981
+ ];
982
+
983
+ const result = formatServerListing(multiServerTools, [
984
+ 'weather-api',
985
+ 'gmail',
986
+ ]);
987
+ const parsed = JSON.parse(result);
988
+
989
+ expect(parsed.servers).toEqual(['weather-api', 'gmail']);
990
+ expect(parsed.total_tools).toBe(3);
991
+ expect(parsed.tools_by_server['weather-api']).toHaveLength(1);
992
+ expect(parsed.tools_by_server['gmail']).toHaveLength(2);
993
+ });
994
+
995
+ it('accepts single server as array', () => {
996
+ const result = formatServerListing(serverTools, ['weather-api']);
997
+ const parsed = JSON.parse(result);
998
+
999
+ expect(parsed.servers).toEqual(['weather-api']);
1000
+ expect(parsed.tools_by_server['weather-api']).toBeDefined();
1001
+ });
1002
+ });
1003
+ });