| 37 | export type InferMetadata<T extends Info> = T extends Info<any, infer M> ? M : never |
| 38 | |
| 39 | export function define<Parameters extends z.ZodType, Result extends Metadata>( |
| 40 | id: string, |
| 41 | init: Info<Parameters, Result>["init"] | Awaited<ReturnType<Info<Parameters, Result>["init"]>>, |
| 42 | ): Info<Parameters, Result> { |
| 43 | return { |
| 44 | id, |
| 45 | init: async () => { |
| 46 | const toolInfo = init instanceof Function ? await init() : init |
| 47 | const execute = toolInfo.execute |
| 48 | toolInfo.execute = (args, ctx) => { |
| 49 | try { |
| 50 | toolInfo.parameters.parse(args) |
| 51 | } catch (error) { |
| 52 | if (error instanceof z.ZodError && toolInfo.formatValidationError) { |
| 53 | throw new Error(toolInfo.formatValidationError(error), { cause: error }) |
| 54 | } |
| 55 | throw new Error( |
| 56 | `The ${id} tool was called with invalid arguments: ${error}.\nPlease rewrite the input so it satisfies the expected schema.`, |
| 57 | { cause: error }, |
| 58 | ) |
| 59 | } |
| 60 | return execute(args, ctx) |
| 61 | } |
| 62 | return toolInfo |
| 63 | }, |
| 64 | } |
| 65 | } |
| 66 | } |