(options: CreateCodeToolOptions)
| 231 | * ``` |
| 232 | */ |
| 233 | export function createCodeTool(options: CreateCodeToolOptions): ServerTool { |
| 234 | const providers = normalizeProviders(options.tools); |
| 235 | |
| 236 | const typeBlocks: string[] = []; |
| 237 | const resolvedProviders: ResolvedProvider[] = []; |
| 238 | |
| 239 | for (const provider of providers) { |
| 240 | const providerName = provider.name ?? "codemode"; |
| 241 | const filtered = filterTools(provider.tools); |
| 242 | |
| 243 | const types = |
| 244 | provider.types ?? generateTypesFromRecord(filtered, providerName); |
| 245 | typeBlocks.push(types); |
| 246 | |
| 247 | const resolved: ResolvedProvider = { |
| 248 | name: providerName, |
| 249 | fns: extractFns(filtered) |
| 250 | }; |
| 251 | if (provider.positionalArgs) resolved.positionalArgs = true; |
| 252 | resolvedProviders.push(resolved); |
| 253 | } |
| 254 | |
| 255 | const typeBlock = typeBlocks.filter(Boolean).join("\n\n"); |
| 256 | const executor = options.executor; |
| 257 | |
| 258 | const description = (options.description ?? DEFAULT_DESCRIPTION).replace( |
| 259 | "{{types}}", |
| 260 | typeBlock |
| 261 | ); |
| 262 | |
| 263 | const def = toolDefinition({ |
| 264 | name: "codemode_execute" as const, |
| 265 | description, |
| 266 | inputSchema: codeSchema |
| 267 | }); |
| 268 | |
| 269 | return def.server(async ({ code }) => { |
| 270 | const normalizedCode = normalizeCode(code); |
| 271 | |
| 272 | const executeResult = await executor.execute( |
| 273 | normalizedCode, |
| 274 | resolvedProviders |
| 275 | ); |
| 276 | |
| 277 | if (executeResult.error) { |
| 278 | const logCtx = executeResult.logs?.length |
| 279 | ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` |
| 280 | : ""; |
| 281 | throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`); |
| 282 | } |
| 283 | |
| 284 | const output: CodeOutput = { code, result: executeResult.result }; |
| 285 | if (executeResult.logs) output.logs = executeResult.logs; |
| 286 | return output; |
| 287 | }); |
| 288 | } |
| 289 | |
| 290 | /** |
no test coverage detected