( tool: CodeModeTool, prefix: string = '', )
| 34 | * @throws Error if the tool doesn't have an execute function |
| 35 | */ |
| 36 | export function toolToBinding( |
| 37 | tool: CodeModeTool, |
| 38 | prefix: string = '', |
| 39 | ): ToolBinding { |
| 40 | // Convert schemas (Zod or Standard Schema) to JSON Schema |
| 41 | const inputSchema = convertSchemaToJsonSchema(tool.inputSchema) || { |
| 42 | type: 'object', |
| 43 | properties: {}, |
| 44 | } |
| 45 | |
| 46 | const outputSchema = tool.outputSchema |
| 47 | ? convertSchemaToJsonSchema(tool.outputSchema) |
| 48 | : undefined |
| 49 | |
| 50 | if (typeof tool.execute !== 'function') { |
| 51 | throw new Error( |
| 52 | `Tool "${tool.name}" does not have an execute function. ` + |
| 53 | `Code Mode requires server tools with implementations.`, |
| 54 | ) |
| 55 | } |
| 56 | |
| 57 | const toolExecute = tool.execute |
| 58 | const execute = async (args: unknown, context?: ToolExecutionContext) => { |
| 59 | let input = args |
| 60 | if (tool.inputSchema && isStandardSchema(tool.inputSchema)) { |
| 61 | try { |
| 62 | input = parseWithStandardSchema(tool.inputSchema, args) |
| 63 | } catch (error) { |
| 64 | const message = |
| 65 | error instanceof Error ? error.message : 'Validation failed' |
| 66 | throw new Error( |
| 67 | `Input validation failed for tool ${tool.name}: ${message}`, |
| 68 | ) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | let result = await Promise.resolve(toolExecute(input, context)) |
| 73 | |
| 74 | if (tool.outputSchema && isStandardSchema(tool.outputSchema)) { |
| 75 | try { |
| 76 | result = parseWithStandardSchema(tool.outputSchema, result) |
| 77 | } catch (error) { |
| 78 | const message = |
| 79 | error instanceof Error ? error.message : 'Validation failed' |
| 80 | throw new Error( |
| 81 | `Output validation failed for tool ${tool.name}: ${message}`, |
| 82 | ) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | return result |
| 87 | } |
| 88 | |
| 89 | return { |
| 90 | name: `${prefix}${tool.name}`, |
| 91 | description: tool.description, |
| 92 | inputSchema, |
| 93 | outputSchema, |
no test coverage detected