@illuma-ai/agents 1.1.20 → 1.1.22

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 (246) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +85 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/llm/bedrock/index.cjs +14 -0
  6. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  7. package/dist/cjs/run.cjs +20 -9
  8. package/dist/cjs/run.cjs.map +1 -1
  9. package/dist/esm/graphs/Graph.mjs +12 -1
  10. package/dist/esm/graphs/Graph.mjs.map +1 -1
  11. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  12. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  13. package/dist/esm/llm/bedrock/index.mjs +14 -0
  14. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  15. package/dist/esm/run.mjs +20 -9
  16. package/dist/esm/run.mjs.map +1 -1
  17. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  18. package/package.json +1 -1
  19. package/src/graphs/Graph.ts +12 -1
  20. package/src/graphs/MultiAgentGraph.ts +105 -1
  21. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  22. package/src/llm/bedrock/index.ts +17 -0
  23. package/src/run.ts +20 -11
  24. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  25. package/src/agents/AgentContext.js +0 -782
  26. package/src/agents/AgentContext.test.js +0 -421
  27. package/src/agents/__tests__/AgentContext.test.js +0 -678
  28. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  29. package/src/common/enum.js +0 -192
  30. package/src/common/index.js +0 -3
  31. package/src/events.js +0 -166
  32. package/src/graphs/Graph.js +0 -1857
  33. package/src/graphs/MultiAgentGraph.js +0 -1092
  34. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  35. package/src/graphs/__tests__/structured-output.test.js +0 -144
  36. package/src/graphs/contextManagement.e2e.test.js +0 -718
  37. package/src/graphs/contextManagement.test.js +0 -485
  38. package/src/graphs/handoffValidation.test.js +0 -276
  39. package/src/graphs/index.js +0 -3
  40. package/src/index.js +0 -28
  41. package/src/instrumentation.js +0 -21
  42. package/src/llm/anthropic/index.js +0 -319
  43. package/src/llm/anthropic/types.js +0 -46
  44. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  45. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  46. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  47. package/src/llm/anthropic/utils/tools.js +0 -25
  48. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  49. package/src/llm/bedrock/index.js +0 -303
  50. package/src/llm/bedrock/types.js +0 -2
  51. package/src/llm/bedrock/utils/index.js +0 -6
  52. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  53. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  54. package/src/llm/fake.js +0 -92
  55. package/src/llm/google/index.js +0 -215
  56. package/src/llm/google/types.js +0 -12
  57. package/src/llm/google/utils/common.js +0 -670
  58. package/src/llm/google/utils/tools.js +0 -111
  59. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  60. package/src/llm/openai/index.js +0 -1033
  61. package/src/llm/openai/types.js +0 -2
  62. package/src/llm/openai/utils/index.js +0 -756
  63. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  64. package/src/llm/openrouter/index.js +0 -261
  65. package/src/llm/openrouter/reasoning.test.js +0 -181
  66. package/src/llm/providers.js +0 -36
  67. package/src/llm/text.js +0 -65
  68. package/src/llm/vertexai/index.js +0 -402
  69. package/src/messages/__tests__/tools.test.js +0 -392
  70. package/src/messages/cache.js +0 -404
  71. package/src/messages/cache.test.js +0 -1167
  72. package/src/messages/content.js +0 -48
  73. package/src/messages/content.test.js +0 -314
  74. package/src/messages/core.js +0 -359
  75. package/src/messages/ensureThinkingBlock.test.js +0 -997
  76. package/src/messages/format.js +0 -973
  77. package/src/messages/formatAgentMessages.test.js +0 -2278
  78. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  79. package/src/messages/formatMessage.test.js +0 -608
  80. package/src/messages/ids.js +0 -18
  81. package/src/messages/index.js +0 -9
  82. package/src/messages/labelContentByAgent.test.js +0 -725
  83. package/src/messages/prune.js +0 -438
  84. package/src/messages/reducer.js +0 -60
  85. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  86. package/src/messages/summarize.js +0 -146
  87. package/src/messages/summarize.test.js +0 -332
  88. package/src/messages/tools.js +0 -90
  89. package/src/mockStream.js +0 -81
  90. package/src/prompts/collab.js +0 -7
  91. package/src/prompts/index.js +0 -3
  92. package/src/prompts/taskmanager.js +0 -58
  93. package/src/run.js +0 -427
  94. package/src/schemas/index.js +0 -3
  95. package/src/schemas/schema-preparation.test.js +0 -370
  96. package/src/schemas/validate.js +0 -314
  97. package/src/schemas/validate.test.js +0 -264
  98. package/src/scripts/abort.js +0 -127
  99. package/src/scripts/ant_web_search.js +0 -130
  100. package/src/scripts/ant_web_search_edge_case.js +0 -133
  101. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  102. package/src/scripts/args.js +0 -41
  103. package/src/scripts/bedrock-cache-debug.js +0 -186
  104. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  105. package/src/scripts/bedrock-merge-test.js +0 -80
  106. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  107. package/src/scripts/caching.js +0 -106
  108. package/src/scripts/cli.js +0 -152
  109. package/src/scripts/cli2.js +0 -119
  110. package/src/scripts/cli3.js +0 -163
  111. package/src/scripts/cli4.js +0 -165
  112. package/src/scripts/cli5.js +0 -165
  113. package/src/scripts/code_exec.js +0 -171
  114. package/src/scripts/code_exec_files.js +0 -180
  115. package/src/scripts/code_exec_multi_session.js +0 -185
  116. package/src/scripts/code_exec_ptc.js +0 -265
  117. package/src/scripts/code_exec_session.js +0 -217
  118. package/src/scripts/code_exec_simple.js +0 -120
  119. package/src/scripts/content.js +0 -111
  120. package/src/scripts/empty_input.js +0 -125
  121. package/src/scripts/handoff-test.js +0 -96
  122. package/src/scripts/image.js +0 -138
  123. package/src/scripts/memory.js +0 -83
  124. package/src/scripts/multi-agent-chain.js +0 -271
  125. package/src/scripts/multi-agent-conditional.js +0 -185
  126. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  127. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  128. package/src/scripts/multi-agent-parallel-start.js +0 -214
  129. package/src/scripts/multi-agent-parallel.js +0 -346
  130. package/src/scripts/multi-agent-sequence.js +0 -184
  131. package/src/scripts/multi-agent-supervisor.js +0 -324
  132. package/src/scripts/multi-agent-test.js +0 -147
  133. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  134. package/src/scripts/parallel-full-metadata-test.js +0 -176
  135. package/src/scripts/parallel-tools-test.js +0 -256
  136. package/src/scripts/programmatic_exec.js +0 -277
  137. package/src/scripts/programmatic_exec_agent.js +0 -168
  138. package/src/scripts/search.js +0 -118
  139. package/src/scripts/sequential-full-metadata-test.js +0 -143
  140. package/src/scripts/simple.js +0 -174
  141. package/src/scripts/single-agent-metadata-test.js +0 -152
  142. package/src/scripts/stream.js +0 -113
  143. package/src/scripts/test-custom-prompt-key.js +0 -132
  144. package/src/scripts/test-handoff-input.js +0 -143
  145. package/src/scripts/test-handoff-preamble.js +0 -227
  146. package/src/scripts/test-handoff-steering.js +0 -353
  147. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  148. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  149. package/src/scripts/test-parallel-handoffs.js +0 -229
  150. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  151. package/src/scripts/test-thinking-handoff.js +0 -132
  152. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  153. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  154. package/src/scripts/test-tools-before-handoff.js +0 -187
  155. package/src/scripts/test_code_api.js +0 -263
  156. package/src/scripts/thinking-bedrock.js +0 -128
  157. package/src/scripts/thinking-vertexai.js +0 -130
  158. package/src/scripts/thinking.js +0 -134
  159. package/src/scripts/tool_search.js +0 -114
  160. package/src/scripts/tools.js +0 -125
  161. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  162. package/src/specs/agent-handoffs.test.js +0 -924
  163. package/src/specs/anthropic.simple.test.js +0 -287
  164. package/src/specs/azure.simple.test.js +0 -381
  165. package/src/specs/cache.simple.test.js +0 -282
  166. package/src/specs/custom-event-await.test.js +0 -148
  167. package/src/specs/deepseek.simple.test.js +0 -189
  168. package/src/specs/emergency-prune.test.js +0 -308
  169. package/src/specs/moonshot.simple.test.js +0 -237
  170. package/src/specs/observability.integration.test.js +0 -1337
  171. package/src/specs/openai.simple.test.js +0 -233
  172. package/src/specs/openrouter.simple.test.js +0 -202
  173. package/src/specs/prune.test.js +0 -733
  174. package/src/specs/reasoning.test.js +0 -144
  175. package/src/specs/spec.utils.js +0 -4
  176. package/src/specs/thinking-handoff.test.js +0 -486
  177. package/src/specs/thinking-prune.test.js +0 -600
  178. package/src/specs/token-distribution-edge-case.test.js +0 -246
  179. package/src/specs/token-memoization.test.js +0 -32
  180. package/src/specs/tokens.test.js +0 -49
  181. package/src/specs/tool-error.test.js +0 -139
  182. package/src/splitStream.js +0 -204
  183. package/src/splitStream.test.js +0 -504
  184. package/src/stream.js +0 -650
  185. package/src/stream.test.js +0 -225
  186. package/src/test/mockTools.js +0 -340
  187. package/src/tools/BrowserTools.js +0 -245
  188. package/src/tools/Calculator.js +0 -38
  189. package/src/tools/Calculator.test.js +0 -225
  190. package/src/tools/CodeExecutor.js +0 -233
  191. package/src/tools/ProgrammaticToolCalling.js +0 -602
  192. package/src/tools/StreamingToolCallBuffer.js +0 -179
  193. package/src/tools/ToolNode.js +0 -930
  194. package/src/tools/ToolSearch.js +0 -904
  195. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  196. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  197. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  198. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  199. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  200. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  201. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  202. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  203. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  204. package/src/tools/__tests__/handlers.test.js +0 -799
  205. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  206. package/src/tools/handlers.js +0 -306
  207. package/src/tools/schema.js +0 -25
  208. package/src/tools/search/anthropic.js +0 -34
  209. package/src/tools/search/content.js +0 -116
  210. package/src/tools/search/content.test.js +0 -133
  211. package/src/tools/search/firecrawl.js +0 -173
  212. package/src/tools/search/format.js +0 -198
  213. package/src/tools/search/highlights.js +0 -241
  214. package/src/tools/search/index.js +0 -3
  215. package/src/tools/search/jina-reranker.test.js +0 -106
  216. package/src/tools/search/rerankers.js +0 -165
  217. package/src/tools/search/schema.js +0 -102
  218. package/src/tools/search/search.js +0 -561
  219. package/src/tools/search/serper-scraper.js +0 -126
  220. package/src/tools/search/test.js +0 -129
  221. package/src/tools/search/tool.js +0 -453
  222. package/src/tools/search/types.js +0 -2
  223. package/src/tools/search/utils.js +0 -59
  224. package/src/types/graph.js +0 -24
  225. package/src/types/graph.test.js +0 -192
  226. package/src/types/index.js +0 -7
  227. package/src/types/llm.js +0 -2
  228. package/src/types/messages.js +0 -2
  229. package/src/types/run.js +0 -2
  230. package/src/types/stream.js +0 -2
  231. package/src/types/tools.js +0 -2
  232. package/src/utils/contextAnalytics.js +0 -79
  233. package/src/utils/contextAnalytics.test.js +0 -166
  234. package/src/utils/events.js +0 -26
  235. package/src/utils/graph.js +0 -11
  236. package/src/utils/handlers.js +0 -65
  237. package/src/utils/index.js +0 -10
  238. package/src/utils/llm.js +0 -21
  239. package/src/utils/llmConfig.js +0 -205
  240. package/src/utils/logging.js +0 -37
  241. package/src/utils/misc.js +0 -51
  242. package/src/utils/run.js +0 -69
  243. package/src/utils/schema.js +0 -21
  244. package/src/utils/title.js +0 -119
  245. package/src/utils/tokens.js +0 -92
  246. package/src/utils/toonFormat.js +0 -379
@@ -1,904 +0,0 @@
1
- // src/tools/ToolSearch.ts
2
- import * as okapibm25Module from 'okapibm25';
3
- import { config } from 'dotenv';
4
- function getBM25Function() {
5
- const mod = okapibm25Module;
6
- if (typeof mod === 'function')
7
- return mod;
8
- if (typeof mod.default === 'function')
9
- return mod.default;
10
- if (mod.default != null && typeof mod.default.default === 'function')
11
- return mod.default.default;
12
- throw new Error('Could not resolve BM25 function from okapibm25 module');
13
- }
14
- const BM25 = getBM25Function();
15
- import fetch from 'node-fetch';
16
- import { HttpsProxyAgent } from 'https-proxy-agent';
17
- import { getEnvironmentVariable } from '@langchain/core/utils/env';
18
- import { tool } from '@langchain/core/tools';
19
- import { getCodeBaseURL } from './CodeExecutor';
20
- import { EnvVar, Constants } from '@/common';
21
- config();
22
- /** Maximum allowed regex pattern length */
23
- const MAX_PATTERN_LENGTH = 200;
24
- export const ToolSearchToolName = Constants.TOOL_SEARCH;
25
- export const ToolSearchToolDescription = 'Searches deferred tools using BM25 ranking. Multi-word queries supported. Use mcp_server param to filter by server.';
26
- const QUERY_DESCRIPTION_LOCAL = 'Search term to find in tool names and descriptions. Case-insensitive substring matching. Optional if mcp_server is provided.';
27
- const QUERY_DESCRIPTION_REGEX = 'Regex pattern to search tool names and descriptions. Optional if mcp_server is provided.';
28
- const FIELDS_DESCRIPTION = 'Which fields to search. Default: name and description';
29
- const MAX_RESULTS_DESCRIPTION = 'Maximum number of matching tools to return';
30
- const DEFAULT_MAX_RESULTS = 5;
31
- const MCP_SERVER_DESCRIPTION = 'Filter to tools from specific MCP server(s). Can be a single server name or array of names. If provided without a query, lists all tools from those servers.';
32
- export const ToolSearchToolSchema = {
33
- type: 'object',
34
- properties: {
35
- query: {
36
- type: 'string',
37
- maxLength: MAX_PATTERN_LENGTH,
38
- default: '',
39
- description: QUERY_DESCRIPTION_LOCAL,
40
- },
41
- fields: {
42
- type: 'array',
43
- items: { type: 'string', enum: ['name', 'description', 'parameters'] },
44
- default: ['name', 'description'],
45
- description: FIELDS_DESCRIPTION,
46
- },
47
- max_results: {
48
- type: 'integer',
49
- minimum: 1,
50
- maximum: 50,
51
- default: DEFAULT_MAX_RESULTS,
52
- description: MAX_RESULTS_DESCRIPTION,
53
- },
54
- mcp_server: {
55
- oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],
56
- description: MCP_SERVER_DESCRIPTION,
57
- },
58
- },
59
- required: [],
60
- };
61
- export const ToolSearchToolDefinition = {
62
- name: ToolSearchToolName,
63
- description: ToolSearchToolDescription,
64
- schema: ToolSearchToolSchema,
65
- };
66
- /** Maximum allowed regex nesting depth */
67
- const MAX_REGEX_COMPLEXITY = 5;
68
- /** Default search timeout in milliseconds */
69
- const SEARCH_TIMEOUT = 5000;
70
- /**
71
- * Creates the JSON schema with dynamic query description based on mode.
72
- * @param mode - The search mode determining query interpretation
73
- * @returns JSON schema for tool search parameters
74
- */
75
- function createToolSearchSchema(mode) {
76
- const queryDescription = mode === 'local' ? QUERY_DESCRIPTION_LOCAL : QUERY_DESCRIPTION_REGEX;
77
- return {
78
- type: 'object',
79
- properties: {
80
- query: {
81
- type: 'string',
82
- maxLength: MAX_PATTERN_LENGTH,
83
- default: '',
84
- description: queryDescription,
85
- },
86
- fields: {
87
- type: 'array',
88
- items: { type: 'string', enum: ['name', 'description', 'parameters'] },
89
- default: ['name', 'description'],
90
- description: FIELDS_DESCRIPTION,
91
- },
92
- max_results: {
93
- type: 'integer',
94
- minimum: 1,
95
- maximum: 50,
96
- default: DEFAULT_MAX_RESULTS,
97
- description: MAX_RESULTS_DESCRIPTION,
98
- },
99
- mcp_server: {
100
- oneOf: [
101
- { type: 'string' },
102
- { type: 'array', items: { type: 'string' } },
103
- ],
104
- description: MCP_SERVER_DESCRIPTION,
105
- },
106
- },
107
- required: [],
108
- };
109
- }
110
- /**
111
- * Extracts the MCP server name from a tool name.
112
- * MCP tools follow the pattern: toolName_mcp_serverName
113
- * @param toolName - The full tool name
114
- * @returns The server name if it's an MCP tool, undefined otherwise
115
- */
116
- function extractMcpServerName(toolName) {
117
- const delimiterIndex = toolName.indexOf(Constants.MCP_DELIMITER);
118
- if (delimiterIndex === -1) {
119
- return undefined;
120
- }
121
- return toolName.substring(delimiterIndex + Constants.MCP_DELIMITER.length);
122
- }
123
- /**
124
- * Checks if a tool belongs to a specific MCP server.
125
- * @param toolName - The full tool name
126
- * @param serverName - The server name to match
127
- * @returns True if the tool belongs to the specified server
128
- */
129
- function isFromMcpServer(toolName, serverName) {
130
- const toolServer = extractMcpServerName(toolName);
131
- return toolServer === serverName;
132
- }
133
- /**
134
- * Checks if a tool belongs to any of the specified MCP servers.
135
- * @param toolName - The full tool name
136
- * @param serverNames - Array of server names to match
137
- * @returns True if the tool belongs to any of the specified servers
138
- */
139
- function isFromAnyMcpServer(toolName, serverNames) {
140
- const toolServer = extractMcpServerName(toolName);
141
- if (toolServer === undefined) {
142
- return false;
143
- }
144
- return serverNames.includes(toolServer);
145
- }
146
- /**
147
- * Normalizes server filter input to always be an array.
148
- * @param serverFilter - String, array of strings, or undefined
149
- * @returns Array of server names (empty if none specified)
150
- */
151
- function normalizeServerFilter(serverFilter) {
152
- if (serverFilter === undefined) {
153
- return [];
154
- }
155
- if (typeof serverFilter === 'string') {
156
- return serverFilter === '' ? [] : [serverFilter];
157
- }
158
- return serverFilter.filter((s) => s !== '');
159
- }
160
- /**
161
- * Extracts all unique MCP server names from a tool registry.
162
- * @param toolRegistry - The tool registry to scan
163
- * @param onlyDeferred - If true, only considers deferred tools
164
- * @returns Array of unique server names, sorted alphabetically
165
- */
166
- function getAvailableMcpServers(toolRegistry, onlyDeferred = true) {
167
- if (!toolRegistry) {
168
- return [];
169
- }
170
- const servers = new Set();
171
- for (const [, toolDef] of toolRegistry) {
172
- if (onlyDeferred && toolDef.defer_loading !== true) {
173
- continue;
174
- }
175
- const server = extractMcpServerName(toolDef.name);
176
- if (server !== undefined && server !== '') {
177
- servers.add(server);
178
- }
179
- }
180
- return Array.from(servers).sort();
181
- }
182
- /**
183
- * Escapes special regex characters in a string to use as a literal pattern.
184
- * @param pattern - The string to escape
185
- * @returns The escaped string safe for use in a RegExp
186
- */
187
- function escapeRegexSpecialChars(pattern) {
188
- return pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
189
- }
190
- /**
191
- * Counts the maximum nesting depth of groups in a regex pattern.
192
- * @param pattern - The regex pattern to analyze
193
- * @returns The maximum nesting depth
194
- */
195
- function countNestedGroups(pattern) {
196
- let maxDepth = 0;
197
- let currentDepth = 0;
198
- for (let i = 0; i < pattern.length; i++) {
199
- if (pattern[i] === '(' && (i === 0 || pattern[i - 1] !== '\\')) {
200
- currentDepth++;
201
- maxDepth = Math.max(maxDepth, currentDepth);
202
- }
203
- else if (pattern[i] === ')' && (i === 0 || pattern[i - 1] !== '\\')) {
204
- currentDepth = Math.max(0, currentDepth - 1);
205
- }
206
- }
207
- return maxDepth;
208
- }
209
- /**
210
- * Detects nested quantifiers that can cause catastrophic backtracking.
211
- * Patterns like (a+)+, (a*)*, (a+)*, etc.
212
- * @param pattern - The regex pattern to check
213
- * @returns True if nested quantifiers are detected
214
- */
215
- function hasNestedQuantifiers(pattern) {
216
- const nestedQuantifierPattern = /\([^)]*[+*][^)]*\)[+*?]/;
217
- return nestedQuantifierPattern.test(pattern);
218
- }
219
- /**
220
- * Checks if a regex pattern contains potentially dangerous constructs.
221
- * @param pattern - The regex pattern to validate
222
- * @returns True if the pattern is dangerous
223
- */
224
- function isDangerousPattern(pattern) {
225
- if (hasNestedQuantifiers(pattern)) {
226
- return true;
227
- }
228
- if (countNestedGroups(pattern) > MAX_REGEX_COMPLEXITY) {
229
- return true;
230
- }
231
- const dangerousPatterns = [
232
- /\.\{1000,\}/, // Excessive wildcards
233
- /\(\?=\.\{100,\}\)/, // Runaway lookaheads
234
- /\([^)]*\|\s*\){20,}/, // Excessive alternation (rough check)
235
- /\(\.\*\)\+/, // (.*)+
236
- /\(\.\+\)\+/, // (.+)+
237
- /\(\.\*\)\*/, // (.*)*
238
- /\(\.\+\)\*/, // (.+)*
239
- ];
240
- for (const dangerous of dangerousPatterns) {
241
- if (dangerous.test(pattern)) {
242
- return true;
243
- }
244
- }
245
- return false;
246
- }
247
- /**
248
- * Sanitizes a regex pattern for safe execution.
249
- * If the pattern is dangerous, it will be escaped to a literal string search.
250
- * @param pattern - The regex pattern to sanitize
251
- * @returns Object containing the safe pattern and whether it was escaped
252
- */
253
- function sanitizeRegex(pattern) {
254
- if (isDangerousPattern(pattern)) {
255
- return {
256
- safe: escapeRegexSpecialChars(pattern),
257
- wasEscaped: true,
258
- };
259
- }
260
- try {
261
- new RegExp(pattern);
262
- return { safe: pattern, wasEscaped: false };
263
- }
264
- catch {
265
- return {
266
- safe: escapeRegexSpecialChars(pattern),
267
- wasEscaped: true,
268
- };
269
- }
270
- }
271
- /**
272
- * Simplifies tool parameters for search purposes.
273
- * Extracts only the essential structure needed for parameter name searching.
274
- * @param parameters - The tool's JSON schema parameters
275
- * @returns Simplified parameters object
276
- */
277
- function simplifyParametersForSearch(parameters) {
278
- if (!parameters) {
279
- return undefined;
280
- }
281
- if (parameters.properties) {
282
- return {
283
- type: parameters.type,
284
- properties: Object.fromEntries(Object.entries(parameters.properties).map(([key, value]) => [
285
- key,
286
- { type: value.type },
287
- ])),
288
- };
289
- }
290
- return { type: parameters.type };
291
- }
292
- /**
293
- * Tokenizes a string into lowercase words for BM25.
294
- * Splits on underscores and non-alphanumeric characters for consistent matching.
295
- * @param text - The text to tokenize
296
- * @returns Array of lowercase tokens
297
- */
298
- function tokenize(text) {
299
- return text
300
- .toLowerCase()
301
- .replace(/[^a-z0-9]/g, ' ')
302
- .split(/\s+/)
303
- .filter((token) => token.length > 0);
304
- }
305
- /**
306
- * Creates a searchable document string from tool metadata.
307
- * @param tool - The tool metadata
308
- * @param fields - Which fields to include
309
- * @returns Combined document string for BM25
310
- */
311
- function createToolDocument(tool, fields) {
312
- const parts = [];
313
- if (fields.includes('name')) {
314
- const baseName = tool.name.replace(/_/g, ' ');
315
- parts.push(baseName, baseName);
316
- }
317
- if (fields.includes('description') && tool.description) {
318
- parts.push(tool.description);
319
- }
320
- if (fields.includes('parameters') && tool.parameters?.properties) {
321
- const paramNames = Object.keys(tool.parameters.properties).join(' ');
322
- parts.push(paramNames);
323
- }
324
- return parts.join(' ');
325
- }
326
- /**
327
- * Determines which field had the best match for a query.
328
- * @param tool - The tool to check
329
- * @param queryTokens - Tokenized query
330
- * @param fields - Fields to check
331
- * @returns The matched field and a snippet
332
- */
333
- function findMatchedField(tool, queryTokens, fields) {
334
- if (fields.includes('name')) {
335
- const nameLower = tool.name.toLowerCase();
336
- for (const token of queryTokens) {
337
- if (nameLower.includes(token)) {
338
- return { field: 'name', snippet: tool.name };
339
- }
340
- }
341
- }
342
- if (fields.includes('description') && tool.description) {
343
- const descLower = tool.description.toLowerCase();
344
- for (const token of queryTokens) {
345
- if (descLower.includes(token)) {
346
- return {
347
- field: 'description',
348
- snippet: tool.description.substring(0, 100),
349
- };
350
- }
351
- }
352
- }
353
- if (fields.includes('parameters') && tool.parameters?.properties) {
354
- const paramNames = Object.keys(tool.parameters.properties);
355
- const paramLower = paramNames.join(' ').toLowerCase();
356
- for (const token of queryTokens) {
357
- if (paramLower.includes(token)) {
358
- return { field: 'parameters', snippet: paramNames.join(', ') };
359
- }
360
- }
361
- }
362
- const fallbackSnippet = tool.description
363
- ? tool.description.substring(0, 100)
364
- : tool.name;
365
- return { field: 'unknown', snippet: fallbackSnippet };
366
- }
367
- /**
368
- * Performs BM25-based search for better relevance ranking.
369
- * Uses Okapi BM25 algorithm for term frequency and document length normalization.
370
- * If query is empty, returns all tools (up to maxResults) sorted alphabetically.
371
- * @param tools - Array of tool metadata to search
372
- * @param query - The search query (empty returns all tools)
373
- * @param fields - Which fields to search
374
- * @param maxResults - Maximum results to return
375
- * @returns Search response with matching tools ranked by BM25 score
376
- */
377
- function performLocalSearch(tools, query, fields, maxResults) {
378
- if (tools.length === 0) {
379
- return {
380
- tool_references: [],
381
- total_tools_searched: 0,
382
- pattern_used: query,
383
- };
384
- }
385
- const queryTokens = tokenize(query);
386
- if (queryTokens.length === 0) {
387
- const allTools = tools
388
- .slice()
389
- .sort((a, b) => a.name.localeCompare(b.name))
390
- .slice(0, maxResults)
391
- .map((tool) => ({
392
- tool_name: tool.name,
393
- match_score: 1.0,
394
- matched_field: 'name',
395
- snippet: tool.description.substring(0, 100) || tool.name,
396
- }));
397
- return {
398
- tool_references: allTools,
399
- total_tools_searched: tools.length,
400
- pattern_used: query,
401
- };
402
- }
403
- const documents = tools.map((tool) => createToolDocument(tool, fields));
404
- const scores = BM25(documents, queryTokens, { k1: 1.5, b: 0.75 });
405
- const maxScore = Math.max(...scores.filter((s) => s > 0), 1);
406
- const queryLower = query.toLowerCase().trim();
407
- const results = [];
408
- for (let i = 0; i < tools.length; i++) {
409
- if (scores[i] > 0) {
410
- const { field, snippet } = findMatchedField(tools[i], queryTokens, fields);
411
- let normalizedScore = Math.min(scores[i] / maxScore, 1.0);
412
- const baseName = getBaseToolName(tools[i].name).toLowerCase();
413
- if (baseName === queryLower) {
414
- normalizedScore = 1.0;
415
- }
416
- else if (baseName.startsWith(queryLower)) {
417
- normalizedScore = Math.max(normalizedScore, 0.95);
418
- }
419
- results.push({
420
- tool_name: tools[i].name,
421
- match_score: normalizedScore,
422
- matched_field: field,
423
- snippet,
424
- });
425
- }
426
- }
427
- results.sort((a, b) => b.match_score - a.match_score);
428
- const topResults = results.slice(0, maxResults);
429
- return {
430
- tool_references: topResults,
431
- total_tools_searched: tools.length,
432
- pattern_used: query,
433
- };
434
- }
435
- /**
436
- * Generates the JavaScript search script to be executed in the sandbox.
437
- * Uses plain JavaScript for maximum compatibility with the Code API.
438
- * @param deferredTools - Array of tool metadata to search through
439
- * @param fields - Which fields to search
440
- * @param maxResults - Maximum number of results to return
441
- * @param sanitizedPattern - The sanitized regex pattern
442
- * @returns The JavaScript code string
443
- */
444
- function generateSearchScript(deferredTools, fields, maxResults, sanitizedPattern) {
445
- const lines = [
446
- '// Tool definitions (injected)',
447
- 'var tools = ' + JSON.stringify(deferredTools) + ';',
448
- 'var searchFields = ' + JSON.stringify(fields) + ';',
449
- 'var maxResults = ' + maxResults + ';',
450
- 'var pattern = ' + JSON.stringify(sanitizedPattern) + ';',
451
- '',
452
- '// Compile regex (pattern is sanitized client-side)',
453
- 'var regex;',
454
- 'try {',
455
- ' regex = new RegExp(pattern, \'i\');',
456
- '} catch (e) {',
457
- ' regex = new RegExp(pattern.replace(/[.*+?^${}()[\\]\\\\|]/g, "\\\\$&"), "i");',
458
- '}',
459
- '',
460
- '// Search logic',
461
- 'var results = [];',
462
- '',
463
- 'for (var j = 0; j < tools.length; j++) {',
464
- ' var tool = tools[j];',
465
- ' var bestScore = 0;',
466
- ' var matchedField = \'\';',
467
- ' var snippet = \'\';',
468
- '',
469
- ' // Search name (highest priority)',
470
- ' if (searchFields.indexOf(\'name\') >= 0 && regex.test(tool.name)) {',
471
- ' bestScore = 0.95;',
472
- ' matchedField = \'name\';',
473
- ' snippet = tool.name;',
474
- ' }',
475
- '',
476
- ' // Search description (medium priority)',
477
- ' if (searchFields.indexOf(\'description\') >= 0 && tool.description && regex.test(tool.description)) {',
478
- ' if (bestScore === 0) {',
479
- ' bestScore = 0.75;',
480
- ' matchedField = \'description\';',
481
- ' snippet = tool.description.substring(0, 100);',
482
- ' }',
483
- ' }',
484
- '',
485
- ' // Search parameter names (lower priority)',
486
- ' if (searchFields.indexOf(\'parameters\') >= 0 && tool.parameters && tool.parameters.properties) {',
487
- ' var paramNames = Object.keys(tool.parameters.properties).join(\' \');',
488
- ' if (regex.test(paramNames)) {',
489
- ' if (bestScore === 0) {',
490
- ' bestScore = 0.60;',
491
- ' matchedField = \'parameters\';',
492
- ' snippet = paramNames;',
493
- ' }',
494
- ' }',
495
- ' }',
496
- '',
497
- ' if (bestScore > 0) {',
498
- ' results.push({',
499
- ' tool_name: tool.name,',
500
- ' match_score: bestScore,',
501
- ' matched_field: matchedField,',
502
- ' snippet: snippet',
503
- ' });',
504
- ' }',
505
- '}',
506
- '',
507
- '// Sort by score (descending) and limit results',
508
- 'results.sort(function(a, b) { return b.match_score - a.match_score; });',
509
- 'var topResults = results.slice(0, maxResults);',
510
- '',
511
- '// Output as JSON',
512
- 'console.log(JSON.stringify({',
513
- ' tool_references: topResults.map(function(r) {',
514
- ' return {',
515
- ' tool_name: r.tool_name,',
516
- ' match_score: r.match_score,',
517
- ' matched_field: r.matched_field,',
518
- ' snippet: r.snippet',
519
- ' };',
520
- ' }),',
521
- ' total_tools_searched: tools.length,',
522
- ' pattern_used: pattern',
523
- '}));',
524
- ];
525
- return lines.join('\n');
526
- }
527
- /**
528
- * Parses the search results from stdout JSON.
529
- * @param stdout - The stdout string containing JSON results
530
- * @returns Parsed search response
531
- */
532
- function parseSearchResults(stdout) {
533
- const jsonMatch = stdout.trim();
534
- const parsed = JSON.parse(jsonMatch);
535
- return parsed;
536
- }
537
- /**
538
- * Formats search results as structured JSON for efficient parsing.
539
- * @param searchResponse - The parsed search response
540
- * @param nameFormat - Whether to show 'full' names (tool_mcp_server) or 'base' names (tool only)
541
- * @returns JSON string with search results
542
- */
543
- function formatSearchResults(searchResponse, nameFormat = 'full') {
544
- const { tool_references, total_tools_searched, pattern_used } = searchResponse;
545
- const useFullName = nameFormat === 'full';
546
- const output = {
547
- found: tool_references.length,
548
- tools: tool_references.map((ref) => ({
549
- name: useFullName ? ref.tool_name : getBaseToolName(ref.tool_name),
550
- score: Number(ref.match_score.toFixed(2)),
551
- matched_in: ref.matched_field,
552
- snippet: ref.snippet,
553
- })),
554
- total_searched: total_tools_searched,
555
- query: pattern_used,
556
- };
557
- return JSON.stringify(output, null, 2);
558
- }
559
- /**
560
- * Extracts the base tool name (without MCP server suffix) from a full tool name.
561
- * @param toolName - The full tool name
562
- * @returns The base tool name without server suffix
563
- */
564
- function getBaseToolName(toolName) {
565
- const delimiterIndex = toolName.indexOf(Constants.MCP_DELIMITER);
566
- if (delimiterIndex === -1) {
567
- return toolName;
568
- }
569
- return toolName.substring(0, delimiterIndex);
570
- }
571
- /**
572
- * Checks whether a tool has any defined parameters in its JSON schema.
573
- * @param parameters - The tool's JSON schema parameters
574
- * @returns true if the tool has at least one parameter property
575
- */
576
- function hasParams(parameters) {
577
- return (parameters?.properties != null &&
578
- Object.keys(parameters.properties).length > 0);
579
- }
580
- /**
581
- * Generates a compact listing of deferred tools grouped by server.
582
- * Format: "server: tool1, tool2(\u2026), tool3"
583
- * Tools with parameters are annotated with (\u2026) to signal
584
- * that the LLM should discover the schema via tool_search before calling.
585
- * Non-MCP tools are grouped under "other".
586
- * @param toolRegistry - The tool registry
587
- * @param onlyDeferred - Whether to only include deferred tools
588
- * @returns Formatted string with tools grouped by server
589
- */
590
- function getDeferredToolsListing(toolRegistry, onlyDeferred) {
591
- if (!toolRegistry) {
592
- return '';
593
- }
594
- const toolsByServer = {};
595
- for (const lcTool of toolRegistry.values()) {
596
- if (onlyDeferred && lcTool.defer_loading !== true) {
597
- continue;
598
- }
599
- const toolName = lcTool.name;
600
- const serverName = extractMcpServerName(toolName) ?? 'other';
601
- const baseName = getBaseToolName(toolName);
602
- const displayName = hasParams(lcTool.parameters)
603
- ? `${baseName}(\u2026)`
604
- : baseName;
605
- if (!(serverName in toolsByServer)) {
606
- toolsByServer[serverName] = [];
607
- }
608
- toolsByServer[serverName].push(displayName);
609
- }
610
- const serverNames = Object.keys(toolsByServer).sort((a, b) => {
611
- if (a === 'other')
612
- return 1;
613
- if (b === 'other')
614
- return -1;
615
- return a.localeCompare(b);
616
- });
617
- if (serverNames.length === 0) {
618
- return '';
619
- }
620
- const lines = serverNames.map((server) => `${server}: ${toolsByServer[server].join(', ')}`);
621
- return lines.join('\n');
622
- }
623
- /**
624
- * Formats a server listing response as structured JSON.
625
- * NOTE: This is a PREVIEW only - tools are NOT discovered/loaded.
626
- * @param tools - Array of tool metadata from the server(s)
627
- * @param serverNames - The MCP server name(s)
628
- * @param nameFormat - Whether to show 'full' names (tool_mcp_server) or 'base' names (tool only)
629
- * @returns JSON string showing all tools grouped by server
630
- */
631
- function formatServerListing(tools, serverNames, nameFormat = 'full') {
632
- const servers = Array.isArray(serverNames) ? serverNames : [serverNames];
633
- const useFullName = nameFormat === 'full';
634
- if (tools.length === 0) {
635
- return JSON.stringify({
636
- listing_mode: true,
637
- servers,
638
- total_tools: 0,
639
- tools_by_server: {},
640
- hint: 'No tools found from the specified MCP server(s).',
641
- }, null, 2);
642
- }
643
- const toolsByServer = {};
644
- for (const tool of tools) {
645
- const server = extractMcpServerName(tool.name) ?? 'unknown';
646
- if (!(server in toolsByServer)) {
647
- toolsByServer[server] = [];
648
- }
649
- toolsByServer[server].push({
650
- name: useFullName ? tool.name : getBaseToolName(tool.name),
651
- description: tool.description.length > 100
652
- ? tool.description.substring(0, 97) + '...'
653
- : tool.description,
654
- });
655
- }
656
- const exampleToolName = useFullName
657
- ? (tools[0]?.name ?? 'tool_name')
658
- : getBaseToolName(tools[0]?.name ?? 'tool_name');
659
- const output = {
660
- listing_mode: true,
661
- servers,
662
- total_tools: tools.length,
663
- tools_by_server: toolsByServer,
664
- hint: `To use a tool, search for it by name (e.g., query: "${exampleToolName}") to load it.`,
665
- };
666
- return JSON.stringify(output, null, 2);
667
- }
668
- /**
669
- * Creates a Tool Search tool for discovering tools from a large registry.
670
- *
671
- * This tool enables AI agents to dynamically discover tools from a large library
672
- * without loading all tool definitions into the LLM context window. The agent
673
- * can search for relevant tools on-demand.
674
- *
675
- * **Modes:**
676
- * - `code_interpreter` (default): Uses external sandbox for regex search. Safer for complex patterns.
677
- * - `local`: Uses safe substring matching locally. No network call, faster, completely safe from ReDoS.
678
- *
679
- * The tool registry can be provided either:
680
- * 1. At initialization time via params.toolRegistry
681
- * 2. At runtime via config.configurable.toolRegistry when invoking
682
- *
683
- * @param params - Configuration parameters for the tool (toolRegistry is optional)
684
- * @returns A LangChain DynamicStructuredTool for tool searching
685
- *
686
- * @example
687
- * // Option 1: Code interpreter mode (regex via sandbox)
688
- * const tool = createToolSearch({ apiKey, toolRegistry });
689
- * await tool.invoke({ query: 'expense.*report' });
690
- *
691
- * @example
692
- * // Option 2: Local mode (safe substring search, no API key needed)
693
- * const tool = createToolSearch({ mode: 'local', toolRegistry });
694
- * await tool.invoke({ query: 'expense' });
695
- */
696
- function createToolSearch(initParams = {}) {
697
- const mode = initParams.mode ?? 'code_interpreter';
698
- const defaultOnlyDeferred = initParams.onlyDeferred ?? true;
699
- const mcpNameFormat = initParams.mcpNameFormat ?? 'full';
700
- const schema = createToolSearchSchema(mode);
701
- const apiKey = mode === 'code_interpreter'
702
- ? (initParams[EnvVar.CODE_API_KEY] ??
703
- initParams.apiKey ??
704
- getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
705
- '')
706
- : '';
707
- if (mode === 'code_interpreter' && !apiKey) {
708
- throw new Error('No API key provided for tool search in code_interpreter mode. Use mode: "local" to search without an API key.');
709
- }
710
- const baseEndpoint = initParams.baseUrl ?? getCodeBaseURL();
711
- const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
712
- const deferredToolsListing = getDeferredToolsListing(initParams.toolRegistry, defaultOnlyDeferred);
713
- const toolsListSection = deferredToolsListing.length > 0
714
- ? `
715
-
716
- Deferred tools (search to load; \u2026 = has params, search first):
717
- ${deferredToolsListing}`
718
- : '';
719
- const mcpNote = deferredToolsListing.includes(Constants.MCP_DELIMITER) ||
720
- deferredToolsListing.split('\n').some((line) => !line.startsWith('other:'))
721
- ? `
722
- - MCP tools use format: toolName${Constants.MCP_DELIMITER}serverName
723
- - Use mcp_server param to filter by server`
724
- : '';
725
- const description = mode === 'local'
726
- ? `
727
- Searches deferred tools using BM25 ranking. Multi-word queries supported.
728
- ${mcpNote}${toolsListSection}
729
- `.trim()
730
- : `
731
- Searches deferred tools by regex pattern.
732
- ${mcpNote}${toolsListSection}
733
- `.trim();
734
- return tool(async (rawParams, config) => {
735
- const params = rawParams;
736
- const { query = '', fields = ['name', 'description'], max_results = DEFAULT_MAX_RESULTS, mcp_server, } = params;
737
- const { toolRegistry: paramToolRegistry, onlyDeferred: paramOnlyDeferred, mcpServer: paramMcpServer, } = config.toolCall ?? {};
738
- const toolRegistry = paramToolRegistry ?? initParams.toolRegistry;
739
- const onlyDeferred = paramOnlyDeferred !== undefined
740
- ? paramOnlyDeferred
741
- : defaultOnlyDeferred;
742
- const rawServerFilter = mcp_server ?? paramMcpServer ?? initParams.mcpServer;
743
- const serverFilters = normalizeServerFilter(rawServerFilter);
744
- const hasServerFilter = serverFilters.length > 0;
745
- if (toolRegistry == null) {
746
- return [
747
- 'Error: No tool registry provided. Configure toolRegistry at agent level or initialization.',
748
- {
749
- tool_references: [],
750
- metadata: {
751
- total_searched: 0,
752
- pattern: query,
753
- error: 'No tool registry provided',
754
- },
755
- },
756
- ];
757
- }
758
- const toolsArray = Array.from(toolRegistry.values());
759
- const deferredTools = toolsArray
760
- .filter((lcTool) => {
761
- if (onlyDeferred === true && lcTool.defer_loading !== true) {
762
- return false;
763
- }
764
- if (hasServerFilter &&
765
- !isFromAnyMcpServer(lcTool.name, serverFilters)) {
766
- return false;
767
- }
768
- return true;
769
- })
770
- .map((lcTool) => ({
771
- name: lcTool.name,
772
- description: lcTool.description ?? '',
773
- parameters: simplifyParametersForSearch(lcTool.parameters),
774
- }));
775
- if (deferredTools.length === 0) {
776
- const serverMsg = hasServerFilter
777
- ? ` from MCP server(s): ${serverFilters.join(', ')}`
778
- : '';
779
- return [
780
- `No tools available to search${serverMsg}. The tool registry is empty or no matching deferred tools are registered.`,
781
- {
782
- tool_references: [],
783
- metadata: {
784
- total_searched: 0,
785
- pattern: query,
786
- mcp_server: serverFilters,
787
- },
788
- },
789
- ];
790
- }
791
- const isServerListing = hasServerFilter && query === '';
792
- if (isServerListing) {
793
- const formattedOutput = formatServerListing(deferredTools, serverFilters, mcpNameFormat);
794
- return [
795
- formattedOutput,
796
- {
797
- tool_references: [],
798
- metadata: {
799
- total_available: deferredTools.length,
800
- mcp_server: serverFilters,
801
- listing_mode: true,
802
- },
803
- },
804
- ];
805
- }
806
- if (mode === 'local') {
807
- const searchResponse = performLocalSearch(deferredTools, query, fields, max_results);
808
- const formattedOutput = formatSearchResults(searchResponse, mcpNameFormat);
809
- return [
810
- formattedOutput,
811
- {
812
- tool_references: searchResponse.tool_references,
813
- metadata: {
814
- total_searched: searchResponse.total_tools_searched,
815
- pattern: searchResponse.pattern_used,
816
- mcp_server: serverFilters.length > 0 ? serverFilters : undefined,
817
- },
818
- },
819
- ];
820
- }
821
- const { safe: sanitizedPattern, wasEscaped } = sanitizeRegex(query);
822
- let warningMessage = '';
823
- if (wasEscaped) {
824
- warningMessage =
825
- 'Note: The provided pattern was converted to a literal search for safety.\n\n';
826
- }
827
- const searchScript = generateSearchScript(deferredTools, fields, max_results, sanitizedPattern);
828
- const postData = {
829
- lang: 'js',
830
- code: searchScript,
831
- timeout: SEARCH_TIMEOUT,
832
- };
833
- try {
834
- const fetchOptions = {
835
- method: 'POST',
836
- headers: {
837
- 'Content-Type': 'application/json',
838
- 'User-Agent': 'Illuma/1.0',
839
- 'X-API-Key': apiKey,
840
- },
841
- body: JSON.stringify(postData),
842
- };
843
- if (process.env.PROXY != null && process.env.PROXY !== '') {
844
- fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
845
- }
846
- const response = await fetch(EXEC_ENDPOINT, fetchOptions);
847
- if (!response.ok) {
848
- throw new Error(`HTTP error! status: ${response.status}`);
849
- }
850
- const result = await response.json();
851
- if (result.stderr && result.stderr.trim()) {
852
- // eslint-disable-next-line no-console
853
- console.warn('[ToolSearch] stderr:', result.stderr);
854
- }
855
- if (!result.stdout || !result.stdout.trim()) {
856
- return [
857
- `${warningMessage}No tools matched the pattern "${sanitizedPattern}".\nTotal tools searched: ${deferredTools.length}`,
858
- {
859
- tool_references: [],
860
- metadata: {
861
- total_searched: deferredTools.length,
862
- pattern: sanitizedPattern,
863
- },
864
- },
865
- ];
866
- }
867
- const searchResponse = parseSearchResults(result.stdout);
868
- const formattedOutput = `${warningMessage}${formatSearchResults(searchResponse, mcpNameFormat)}`;
869
- return [
870
- formattedOutput,
871
- {
872
- tool_references: searchResponse.tool_references,
873
- metadata: {
874
- total_searched: searchResponse.total_tools_searched,
875
- pattern: searchResponse.pattern_used,
876
- },
877
- },
878
- ];
879
- }
880
- catch (error) {
881
- // eslint-disable-next-line no-console
882
- console.error('[ToolSearch] Error:', error);
883
- const errorMessage = error instanceof Error ? error.message : String(error);
884
- return [
885
- `Tool search failed: ${errorMessage}\n\nSuggestion: Try a simpler search pattern or search for specific tool names.`,
886
- {
887
- tool_references: [],
888
- metadata: {
889
- total_searched: 0,
890
- pattern: sanitizedPattern,
891
- error: errorMessage,
892
- },
893
- },
894
- ];
895
- }
896
- }, {
897
- name: Constants.TOOL_SEARCH,
898
- description,
899
- schema,
900
- responseFormat: Constants.CONTENT_AND_ARTIFACT,
901
- });
902
- }
903
- export { createToolSearch, performLocalSearch, extractMcpServerName, isFromMcpServer, isFromAnyMcpServer, normalizeServerFilter, getAvailableMcpServers, getDeferredToolsListing, getBaseToolName, formatServerListing, sanitizeRegex, escapeRegexSpecialChars, isDangerousPattern, countNestedGroups, hasNestedQuantifiers, };
904
- //# sourceMappingURL=ToolSearch.js.map