Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { toolDefinition } from '@tanstack/ai'
4import {
5 createEventAwareBindings,
6 toolToBinding,
7 toolsToBindings,
8} from '../src/bindings/tool-to-binding'
9import type {
10 CodeModeCallHook,
11 ToolBinding,
12 ToolExecutionContext,
13} from '../src/types'
14
15function createMockServerTool<TName extends string>(
16 name: TName,
17 description = 'A test tool',
18) {
19 const def = toolDefinition({
20 name,
21 description,
22 inputSchema: z.object({ query: z.string() }),
23 outputSchema: z.object({ result: z.string() }),
24 })
25 return def.server(async (input) => ({
26 result: `response to ${input.query}`,
27 }))
28}
29
30describe('toolToBinding', () => {
31 it('converts ServerTool to ToolBinding with correct fields', () => {
32 const tool = createMockServerTool('fetchData')
33 const binding = toolToBinding(tool)
34
35 expect(binding.name).toBe('fetchData')
36 expect(binding.description).toBe('A test tool')
37 expect(binding.inputSchema).toBeDefined()
38 expect(binding.execute).toBeTypeOf('function')
39 })
40
41 it('applies prefix to binding name', () => {
42 const tool = createMockServerTool('fetchData')
43 const binding = toolToBinding(tool, 'external_')
44
45 expect(binding.name).toBe('external_fetchData')
46 })
47
48 it('throws for ToolDefinition without execute', () => {
49 const def = toolDefinition({
50 name: 'noExec',
51 description: 'No execute',
52 inputSchema: z.object({ x: z.string() }),
53 })
54
55 // @ts-expect-error - bare definitions are rejected by the Code Mode API.
56 expect(() => toolToBinding(def)).toThrow('server tools')
57 })
58
59 it('execute function calls through to the tool', async () => {
60 const tool = createMockServerTool('fetchData')
61 const binding = toolToBinding(tool)
62
63 const result = await binding.execute({ query: 'test' })
64 expect(result).toEqual({ result: 'response to test' })
65 })
66
67 it('validates input against the tool schema and throws an agent-readable error', async () => {
68 const tool = createMockServerTool('fetchData')
69 const binding = toolToBinding(tool)
70
71 await expect(binding.execute({ query: 123 })).rejects.toThrow(
72 /Input validation failed for tool fetchData/,
73 )
74 })
75
76 it('coerces/defaults input via the schema before calling execute', async () => {
77 const def = toolDefinition({
78 name: 'withDefault',
79 description: 'has a defaulted field',
80 inputSchema: z.object({ n: z.number().default(7) }),
81 outputSchema: z.object({ n: z.number() }),
82 })
83 const execute = vi.fn(async (input: { n?: number }) => ({ n: input.n! }))
84 const binding = toolToBinding(def.server(execute))
85
86 const result = await binding.execute({})
87 expect(execute).toHaveBeenCalledWith({ n: 7 }, undefined)
88 expect(result).toEqual({ n: 7 })
89 })
90
91 it('validates output against the tool schema', async () => {
92 const def = toolDefinition({
93 name: 'badOutput',
94 description: 'returns the wrong shape',
95 inputSchema: z.object({}),
96 outputSchema: z.object({ result: z.string() }),
97 })
98 // @ts-expect-error - deliberately returns a non-conforming value
99 const binding = toolToBinding(def.server(async () => ({ result: 123 })))
100
101 await expect(binding.execute({})).rejects.toThrow(
102 /Output validation failed for tool badOutput/,
103 )
104 })
105})
106
107describe('toolsToBindings', () => {
108 it('converts multiple tools, keyed by prefixed name', () => {
109 const tool1 = createMockServerTool('fetchWeather')
110 const tool2 = createMockServerTool('dbQuery')
111
112 const bindings = toolsToBindings([tool1, tool2], 'external_')
113
114 expect(Object.keys(bindings)).toEqual([
115 'external_fetchWeather',
116 'external_dbQuery',
117 ])
118 expect(bindings['external_fetchWeather']!.name).toBe(
119 'external_fetchWeather',
120 )
121 expect(bindings['external_dbQuery']!.name).toBe('external_dbQuery')
122 })
123
124 it('returns empty object for empty array', () => {
125 const bindings = toolsToBindings([])
126 expect(bindings).toEqual({})
127 })
128})
129
130describe('createEventAwareBindings', () => {
131 /** Wraps one `external_fetch` binding whose `execute` resolves 'ok'. */
132 function wrapBinding(
133 options: {
134 parentContext?: ToolExecutionContext
135 hook?: CodeModeCallHook
136 } = {},
137 ) {
138 const emitCustomEvent = vi.fn<ToolExecutionContext['emitCustomEvent']>()
139 const execute = vi.fn<ToolBinding['execute']>().mockResolvedValue('ok')
140 const bindings = {
141 external_fetch: {
142 name: 'external_fetch',
143 description: 'test',
144 inputSchema: {},
145 execute,
146 },
147 }
148 const wrapped = createEventAwareBindings(
149 bindings,
150 emitCustomEvent,
151 options.parentContext,
152 options.hook,
153 )
154 return { emitCustomEvent, execute, wrapped: wrapped['external_fetch']! }
155 }
156
157 it('emits code_mode:external_call before execution', async () => {
158 const { emitCustomEvent, wrapped } = wrapBinding()
159
160 await wrapped.execute({ q: 'test' })
161
162 expect(emitCustomEvent).toHaveBeenCalledWith(
163 'code_mode:external_call',
164 expect.objectContaining({
165 function: 'external_fetch',
166 args: { q: 'test' },
167 timestamp: expect.any(Number),
168 }),
169 )
170 })
171
172 it('emits code_mode:external_result after success with duration', async () => {
173 const { emitCustomEvent, wrapped } = wrapBinding()
174
175 await wrapped.execute({})
176
177 expect(emitCustomEvent).toHaveBeenCalledWith(
178 'code_mode:external_result',
179 expect.objectContaining({
180 function: 'external_fetch',
181 result: 'ok',
182 duration: expect.any(Number),
183 }),
184 )
185 })
186
187 it('emits code_mode:external_error on failure and re-throws', async () => {
188 const { emitCustomEvent, execute, wrapped } = wrapBinding()
189 execute.mockRejectedValue(new Error('network fail'))
190
191 await expect(wrapped.execute({})).rejects.toThrow('network fail')
192
193 expect(emitCustomEvent).toHaveBeenCalledWith(
194 'code_mode:external_error',
195 expect.objectContaining({
196 function: 'external_fetch',
197 error: 'network fail',
198 duration: expect.any(Number),
199 }),
200 )
201 })
202
203 it('passes the parent abortSignal, threadId, and context, not its toolCallId or inputResponse', async () => {
204 const controller = new AbortController()
205 const { emitCustomEvent, execute, wrapped } = wrapBinding({
206 parentContext: {
207 toolCallId: 'parent-call',
208 threadId: 'thread-1',
209 abortSignal: controller.signal,
210 context: { userId: 'u1' },
211 inputResponse: { status: 'cancelled' },
212 emitCustomEvent: vi.fn(),
213 },
214 })
215
216 await wrapped.execute({})
217
218 const ctx = execute.mock.calls[0]![1]
219 expect(ctx?.abortSignal).toBe(controller.signal)
220 expect(ctx?.context).toEqual({ userId: 'u1' })
221 expect(ctx?.threadId).toBe('thread-1')
222 expect(ctx?.toolCallId).toBeUndefined()
223 expect(ctx?.inputResponse).toBeUndefined()
224 // The wrapper's emitCustomEvent is the one the binding gets.
225 expect(ctx?.emitCustomEvent).toBe(emitCustomEvent)
226 })
227
228 it('builds a context with no threadId when there is no parent context', async () => {
229 const { emitCustomEvent, execute, wrapped } = wrapBinding()
230
231 await wrapped.execute({})
232
233 const ctx = execute.mock.calls[0]![1]
234 expect(ctx?.emitCustomEvent).toBe(emitCustomEvent)
235 expect(ctx?.threadId).toBeUndefined()
236 })
237
238 it('does not run the binding when the parent signal is already aborted', async () => {
239 const controller = new AbortController()
240 controller.abort()
241 const { emitCustomEvent, execute, wrapped } = wrapBinding({
242 parentContext: {
243 threadId: 'thread-1',
244 abortSignal: controller.signal,
245 emitCustomEvent: vi.fn(),
246 },
247 })
248
249 await expect(wrapped.execute({})).rejects.toMatchObject({
250 name: 'AbortError',
251 })
252 expect(execute).not.toHaveBeenCalled()
253 expect(emitCustomEvent).toHaveBeenCalledWith(
254 'code_mode:external_error',
255 expect.objectContaining({ function: 'external_fetch' }),
256 )
257 })
258
259 it('event data includes function name, args, and timestamps', async () => {
260 const { emitCustomEvent, wrapped } = wrapBinding()
261
262 await wrapped.execute({ term: 'hello' })
263
264 const callEvent = emitCustomEvent.mock.calls[0]!
265 expect(callEvent[0]).toBe('code_mode:external_call')
266 expect(callEvent[1].function).toBe('external_fetch')
267 expect(callEvent[1].args).toEqual({ term: 'hello' })
268 expect(typeof callEvent[1].timestamp).toBe('number')
269 })
270
271 it('runs each call through the hook with the tool name and the args', async () => {
272 const calls: Array<{ name: string; args: unknown }> = []
273 const { emitCustomEvent, execute, wrapped } = wrapBinding({
274 hook: (call, run) => {
275 calls.push(call)
276 return run()
277 },
278 })
279
280 await expect(wrapped.execute({ q: 'test' })).resolves.toBe('ok')
281
282 expect(calls).toEqual([{ name: 'fetch', args: { q: 'test' } }])
283 expect(execute).toHaveBeenCalledWith(
284 { q: 'test' },
285 expect.objectContaining({ emitCustomEvent }),
286 )
287 })
288
289 it('fails the call and emits code_mode:external_error when the hook refuses it', async () => {
290 const { emitCustomEvent, execute, wrapped } = wrapBinding({
291 hook: async () => {
292 throw new Error('denied by a rule')
293 },
294 })
295
296 await expect(wrapped.execute({})).rejects.toThrow('denied by a rule')
297
298 expect(execute).not.toHaveBeenCalled()
299 expect(emitCustomEvent).toHaveBeenCalledWith(
300 'code_mode:external_error',
301 expect.objectContaining({
302 function: 'external_fetch',
303 error: 'denied by a rule',
304 }),
305 )
306 })
307
308 it('returns the result of the hook in place of the binding result', async () => {
309 const { emitCustomEvent, execute, wrapped } = wrapBinding({
310 hook: async () => 'stored result',
311 })
312
313 await expect(wrapped.execute({})).resolves.toBe('stored result')
314
315 expect(execute).not.toHaveBeenCalled()
316 expect(emitCustomEvent).toHaveBeenCalledWith(
317 'code_mode:external_result',
318 expect.objectContaining({
319 function: 'external_fetch',
320 result: 'stored result',
321 }),
322 )
323 })
324})