Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tool-to-binding.ts

150 lines4.3 KB

1import {
2 convertSchemaToJsonSchema,
3 isStandardSchema,
4 parseWithStandardSchema,
5} from '@tanstack/ai'
6import type { ToolExecutionContext } from '@tanstack/ai'
7import type { CodeModeTool, ToolBinding } from '../types'
8​
9/**
10 * Convert an array of TanStack AI tools to a Record of ToolBindings
11 *
12 * @param tools - Array of tools to convert
13 * @param prefix - Optional prefix to add to binding names (e.g., 'external_')
14 */
15export function toolsToBindings(
16 tools: Array<CodeModeTool>,
17 prefix: string = '',
18): Record<string, ToolBinding> {
19 const bindings: Record<string, ToolBinding> = {}
20​
21 for (const tool of tools) {
22 const bindingName = `${prefix}${tool.name}`
23 bindings[bindingName] = toolToBinding(tool, prefix)
24 }
25​
26 return bindings
28​
29/**
30 * Convert a single TanStack AI tool to a ToolBinding
31 *
32 * @param tool - Tool to convert
33 * @param prefix - Optional prefix to add to binding name (e.g., 'external_')
34 * @throws Error if the tool doesn't have an execute function
35 */
36export 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,
94 execute,
95 }
97​
98/**
99 * Create event-aware bindings that emit custom events for each external function call.
100 * Wraps each binding's execute function to emit events before and after execution.
101 *
102 * @param bindings - Original tool bindings
103 * @param emitCustomEvent - Callback to emit custom events to the stream
104 */
105export function createEventAwareBindings(
106 bindings: Record<string, ToolBinding>,
107 emitCustomEvent: ToolExecutionContext['emitCustomEvent'],
108): Record<string, ToolBinding> {
109 const wrapped: Record<string, ToolBinding> = {}
110​
111 for (const [name, binding] of Object.entries(bindings)) {
112 wrapped[name] = {
113 ...binding,
114 execute: async (args: unknown) => {
115 // Emit call event
116 emitCustomEvent('code_mode:external_call', {
117 function: name,
118 args,
119 timestamp: Date.now(),
120 })
121​
122 const startTime = Date.now()
123 try {
124 // Create context for the underlying tool so it can also emit events
125 const toolContext: ToolExecutionContext = { emitCustomEvent }
126 const result = await binding.execute(args, toolContext)
127​
128 // Emit result event
129 emitCustomEvent('code_mode:external_result', {
130 function: name,
131 result,
132 duration: Date.now() - startTime,
133 })
134​
135 return result
136 } catch (error) {
137 // Emit error event
138 emitCustomEvent('code_mode:external_error', {
139 function: name,
140 error: error instanceof Error ? error.message : String(error),
141 duration: Date.now() - startTime,
142 })
143 throw error
144 }
145 },
146 }
147 }
148​
149 return wrapped