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