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

tools-test-tools.ts

472 lines12.0 KB

1import { toolDefinition } from '@tanstack/ai'
2import { z } from 'zod'
3​
4export type TestRuntimeContext = {
5 userId: string
6 tenantId: string
7 source: string
8}
9​
10export const STOP_CLIENT_TOOL_MESSAGE = 'Wait until Stop'
11​
12/**
13 * Server-side tool definitions (for tools that execute on the server)
14 */
15export const serverTools = {
16 read_server_context: toolDefinition({
17 name: 'read_server_context',
18 description: 'Read the typed runtime context provided by the server',
19 inputSchema: z.object({}),
20 outputSchema: z.object({
21 userId: z.string(),
22 tenantId: z.string(),
23 source: z.string(),
24 }),
25 }).server<TestRuntimeContext>(async (_args, context) => {
26 return {
27 userId: context.context.userId,
28 tenantId: context.context.tenantId,
29 source: context.context.source,
30 }
31 }),
32​
33 check_status: toolDefinition({
34 name: 'check_status',
35 description: 'Check system status (no required input)',
36 inputSchema: z.object({
37 component: z.string().optional(),
38 }),
39 }).server(async (args) => {
40 return JSON.stringify({
41 status: 'ok',
42 component: args.component || 'all',
43 timestamp: Date.now(),
44 })
45 }),
46​
47 get_weather: toolDefinition({
48 name: 'get_weather',
49 description: 'Get weather for a city',
50 inputSchema: z.object({
51 city: z.string(),
52 }),
53 }).server(async (args) => {
54 return JSON.stringify({
55 city: args.city,
56 temperature: 72,
57 condition: 'sunny',
58 })
59 }),
60​
61 fetch_data: toolDefinition({
62 name: 'fetch_data',
63 description: 'Fetch data from a source',
64 inputSchema: z.object({
65 source: z.string(),
66 }),
67 }).server(async (args) => {
68 return JSON.stringify({
69 source: args.source,
70 data: [1, 2, 3, 4, 5],
71 })
72 }),
73​
74 get_time: toolDefinition({
75 name: 'get_time',
76 description: 'Get current time in timezone',
77 inputSchema: z.object({
78 timezone: z.string(),
79 }),
80 }).server(async (args) => {
81 return JSON.stringify({
82 timezone: args.timezone,
83 time: '14:30:00',
84 })
85 }),
86​
87 get_screenshot: toolDefinition({
88 name: 'get_screenshot',
89 description: 'Get a screenshot of the layout',
90 inputSchema: z.object({}),
91 }).server(async () => [
92 { type: 'text' as const, content: 'Layout screenshot' },
93 {
94 type: 'image' as const,
95 source: {
96 type: 'data' as const,
97 // 1x1 transparent PNG
98 value:
99 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/1eYAAAAAElFTkSuQmCC',
100 mimeType: 'image/png',
101 },
102 },
103 ]),
104​
105 delete_file: toolDefinition({
106 name: 'delete_file',
107 description: 'Delete a file (requires approval)',
108 inputSchema: z.object({
109 path: z.string(),
110 }),
111 needsApproval: true,
112 }).server(async (args) => {
113 return JSON.stringify({
114 deleted: true,
115 path: args.path,
116 })
117 }),
119​
120/** A server tool that waits 300 ms and returns when it started and ended. */
121function timedServerTool(name: string) {
122 return toolDefinition({
123 name,
124 description: `Timed ${name}`,
125 inputSchema: z.object({}).passthrough(),
126 }).server(async () => {
127 const startedAt = Date.now()
128 await new Promise((resolve) => setTimeout(resolve, 300))
129 return JSON.stringify({ startedAt, endedAt: Date.now() })
130 })
132​
133/** The calls of the `parallel-tools` fixture, as slow tools that report their timing. */
134export const timedServerTools = {
135 get_weather: timedServerTool('get_weather'),
136 get_time: timedServerTool('get_time'),
138​
139/**
140 * Client-side tool definitions (tools that execute on the client)
141 * These use .client() without an execute function - execution happens on client side
142 */
143export const clientToolDefinitions = {
144 read_client_context: toolDefinition({
145 name: 'read_client_context',
146 description: 'Read the typed runtime context provided by the client',
147 inputSchema: z.object({}),
148 outputSchema: z.object({
149 userId: z.string(),
150 tenantId: z.string(),
151 source: z.string(),
152 }),
153 }).client(),
154​
155 show_notification: toolDefinition({
156 name: 'show_notification',
157 description: 'Show a notification to the user',
158 inputSchema: z.object({
159 message: z.string(),
160 type: z.enum(['info', 'warning', 'error']),
161 }),
162 }).client(),
163​
164 display_chart: toolDefinition({
165 name: 'display_chart',
166 description: 'Display a chart on the screen',
167 inputSchema: z.object({
168 type: z.enum(['bar', 'line', 'pie']),
169 data: z.array(z.number()),
170 }),
171 }).client(),
172​
173 fail_client_tool: toolDefinition({
174 name: 'fail_client_tool',
175 description: 'Fail while executing in the client',
176 inputSchema: z.object({}),
177 outputSchema: z.object({ completed: z.boolean() }),
178 }).client(),
180​
181export const searchInventory = toolDefinition({
182 name: 'search_inventory',
183 description: 'Search the guitar inventory by keyword',
184 inputSchema: z.object({
185 query: z.string(),
186 }),
187 lazy: true,
188}).server(async (args) => {
189 return JSON.stringify({
190 query: args.query,
191 results: [{ id: 1, name: 'Fender Stratocaster', match: 'name' }],
192 })
193})
194​
195export const failingTool = toolDefinition({
196 name: 'failing_tool',
197 description: 'A tool that always throws an error',
198 inputSchema: z.object({
199 message: z.string(),
200 }),
201}).server(async (args) => {
202 throw new Error(`Tool execution failed: ${args.message}`)
203})
204​
205export const processOrder = toolDefinition({
206 name: 'process_order',
207 description: 'Process a guitar order with progress updates',
208 inputSchema: z.object({
209 guitarId: z.number(),
210 quantity: z.number(),
211 }),
212}).server(async (args, context) => {
213 context?.emitCustomEvent('order:progress', {
214 step: 'validating',
215 message: `Validating order for guitar ${args.guitarId}`,
216 })
217​
218 context?.emitCustomEvent('order:progress', {
219 step: 'processing',
220 message: `Processing ${args.quantity} items`,
221 })
222​
223 return JSON.stringify({
224 orderId: 'ORD-123',
225 guitarId: args.guitarId,
226 quantity: args.quantity,
227 status: 'completed',
228 })
229})
230​
231// Available test scenarios (UI list with id/label/category)
232export const SCENARIO_LIST = [
233 { id: 'text-only', label: 'Text Only (No Tools)', category: 'basic' },
234 { id: 'server-tool-single', label: 'Single Server Tool', category: 'basic' },
235 { id: 'client-tool-single', label: 'Single Client Tool', category: 'basic' },
236 {
237 id: 'client-tool-reasoning',
238 label: 'Client Tool with Reasoning',
239 category: 'basic',
240 },
241 {
242 id: 'client-tool-stop',
243 label: 'Stop Pending Client Tool',
244 category: 'race',
245 },
246 { id: 'approval-tool', label: 'Approval Required Tool', category: 'basic' },
247 {
248 id: 'sequence-server-client',
249 label: 'Server \u2192 Client Sequence',
250 category: 'basic',
251 },
252 {
253 id: 'multimodal-server-tool',
254 label: 'Multimodal Server Tool Result (Regression #1283)',
255 category: 'basic',
256 },
257 { id: 'parallel-tools', label: 'Parallel Tools', category: 'basic' },
258 {
259 id: 'parallel-server-timing',
260 label: 'Parallel Server Tool Timing',
261 category: 'basic',
262 },
263 {
264 id: 'lazy-tool-discovery',
265 label: 'Lazy Tool Discovery',
266 category: 'basic',
267 },
268 { id: 'custom-events', label: 'Custom Event Emitting', category: 'basic' },
269 {
270 id: 'server-context',
271 label: 'Server Runtime Context',
272 category: 'basic',
273 },
274 {
275 id: 'client-context',
276 label: 'Client Runtime Context',
277 category: 'basic',
278 },
279 {
280 id: 'client-server-context',
281 label: 'Forwarded Props to Server Context',
282 category: 'basic',
283 },
284 { id: 'error', label: 'Error Response', category: 'basic' },
285 {
286 id: 'tool-error',
287 label: 'Tool Throws Error',
288 category: 'basic',
289 },
290 {
291 id: 'client-tool-error',
292 label: 'Client Tool Throws Error',
293 category: 'basic',
294 },
295 {
296 id: 'null-tool-input',
297 label: 'Null Tool Input (Regression #265)',
298 category: 'basic',
299 },
300 {
301 id: 'malformed-tool-arguments',
302 label: 'Malformed Tool Arguments (Regression #1131)',
303 category: 'basic',
304 },
305 {
306 id: 'provider-rejected-tool-call',
307 label: 'Provider-Rejected Tool Call',
308 category: 'basic',
309 },
310 {
311 id: 'client-tool-input-error',
312 label: 'Client Tool Input Error',
313 category: 'basic',
314 },
315 {
316 id: 'invalid-client-tool-retry',
317 label: 'Invalid Client Tool Retry (Regression #1192)',
318 category: 'race',
319 },
320 // Race condition / event flow scenarios
321 {
322 id: 'sequential-client-tools',
323 label: 'Sequential Client Tools (2)',
324 category: 'race',
325 },
326 {
327 id: 'parallel-client-tools',
328 label: 'Parallel Client Tools',
329 category: 'race',
330 },
331 {
332 id: 'sequential-approvals',
333 label: 'Sequential Approvals (2)',
334 category: 'race',
335 },
336 { id: 'parallel-approvals', label: 'Parallel Approvals', category: 'race' },
337 {
338 id: 'client-then-approval',
339 label: 'Client \u2192 Approval',
340 category: 'race',
341 },
342 {
343 id: 'approval-then-client',
344 label: 'Approval \u2192 Client',
345 category: 'race',
346 },
347 {
348 id: 'server-then-two-clients',
349 label: 'Server \u2192 2 Clients',
350 category: 'race',
351 },
352 {
353 id: 'triple-client-sequence',
354 label: 'Triple Client Sequence',
355 category: 'race',
356 },
357 {
358 id: 'interleaved-args',
359 label: 'Text Interleaved in Tool Args (Regression #1017)',
360 category: 'race',
361 },
362 {
363 id: 'canonical-tool-input',
364 label: 'TOOL_CALL_END Input Replaces Streamed Args',
365 category: 'race',
366 },
368​
369/**
370 * Get the tools needed for a specific scenario
371 */
372export function getToolsForScenario(scenario: string) {
373 switch (scenario) {
374 case 'text-only':
375 return []
376​
377 case 'server-tool-single':
378 return [serverTools.get_weather]
379​
380 case 'client-tool-single':
381 case 'client-tool-reasoning':
382 case 'client-tool-stop':
383 case 'client-tool-input-error':
384 case 'invalid-client-tool-retry':
385 return [clientToolDefinitions.show_notification]
386​
387 case 'client-tool-error':
388 return [clientToolDefinitions.fail_client_tool]
389​
390 case 'server-context':
391 return [serverTools.read_server_context]
392​
393 case 'client-context':
394 return [clientToolDefinitions.read_client_context]
395​
396 case 'client-server-context':
397 return [serverTools.read_server_context]
398​
399 case 'approval-tool':
400 return [serverTools.delete_file]
401​
402 case 'sequence-server-client':
403 return [serverTools.fetch_data, clientToolDefinitions.display_chart]
404​
405 case 'multimodal-server-tool':
406 return [serverTools.get_screenshot]
407​
408 case 'parallel-tools':
409 return [serverTools.get_weather, serverTools.get_time]
410​
411 case 'parallel-server-timing':
412 return [timedServerTools.get_weather, timedServerTools.get_time]
413​
414 // Race condition / event flow scenarios
415 case 'sequential-client-tools':
416 return [clientToolDefinitions.show_notification]
417​
418 case 'parallel-client-tools':
419 return [
420 clientToolDefinitions.show_notification,
421 clientToolDefinitions.display_chart,
422 ]
423​
424 case 'sequential-approvals':
425 return [serverTools.delete_file]
426​
427 case 'parallel-approvals':
428 return [serverTools.delete_file]
429​
430 case 'client-then-approval':
431 return [clientToolDefinitions.show_notification, serverTools.delete_file]
432​
433 case 'approval-then-client':
434 return [serverTools.delete_file, clientToolDefinitions.show_notification]
435​
436 case 'server-then-two-clients':
437 return [
438 serverTools.fetch_data,
439 clientToolDefinitions.show_notification,
440 clientToolDefinitions.display_chart,
441 ]
442​
443 case 'triple-client-sequence':
444 return [
445 clientToolDefinitions.show_notification,
446 clientToolDefinitions.display_chart,
447 ]
448​
449 case 'interleaved-args':
450 return [serverTools.get_weather]
451​
452 case 'lazy-tool-discovery':
453 return [serverTools.get_weather, searchInventory]
454​
455 case 'custom-events':
456 return [processOrder]
457​
458 case 'tool-error':
459 return [failingTool]
460​
461 case 'null-tool-input':
462 return [serverTools.check_status]
463​
464 case 'malformed-tool-arguments':
465 case 'provider-rejected-tool-call':
466 case 'canonical-tool-input':
467 return [serverTools.check_status]
468​
469 default:
470 return []
471 }