Open History to see the last commit
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 }),
118}
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 })
131}
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'),
137}
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 // Must match the browser tool's outputSchema. A different schema makes
163 // the client treat the pause as a generic interrupt, not a client tool.
164 outputSchema: z.object({
165 displayed: z.boolean(),
166 timestamp: z.number(),
167 }),
168 }).client(),
169
170 display_chart: toolDefinition({
171 name: 'display_chart',
172 description: 'Display a chart on the screen',
173 inputSchema: z.object({
174 type: z.enum(['bar', 'line', 'pie']),
175 data: z.array(z.number()),
176 }),
177 outputSchema: z.object({
178 rendered: z.boolean(),
179 chartId: z.string(),
180 }),
181 }).client(),
182
183 fail_client_tool: toolDefinition({
184 name: 'fail_client_tool',
185 description: 'Fail while executing in the client',
186 inputSchema: z.object({}),
187 outputSchema: z.object({ completed: z.boolean() }),
188 }).client(),
189}
190
191export const searchInventory = toolDefinition({
192 name: 'search_inventory',
193 description: 'Search the guitar inventory by keyword',
194 inputSchema: z.object({
195 query: z.string(),
196 }),
197 lazy: true,
198}).server(async (args) => {
199 return JSON.stringify({
200 query: args.query,
201 results: [{ id: 1, name: 'Fender Stratocaster', match: 'name' }],
202 })
203})
204
205export const failingTool = toolDefinition({
206 name: 'failing_tool',
207 description: 'A tool that always throws an error',
208 inputSchema: z.object({
209 message: z.string(),
210 }),
211}).server(async (args) => {
212 throw new Error(`Tool execution failed: ${args.message}`)
213})
214
215export const processOrder = toolDefinition({
216 name: 'process_order',
217 description: 'Process a guitar order with progress updates',
218 inputSchema: z.object({
219 guitarId: z.number(),
220 quantity: z.number(),
221 }),
222}).server(async (args, context) => {
223 context?.emitCustomEvent('order:progress', {
224 step: 'validating',
225 message: `Validating order for guitar ${args.guitarId}`,
226 })
227
228 context?.emitCustomEvent('order:progress', {
229 step: 'processing',
230 message: `Processing ${args.quantity} items`,
231 })
232
233 return JSON.stringify({
234 orderId: 'ORD-123',
235 guitarId: args.guitarId,
236 quantity: args.quantity,
237 status: 'completed',
238 })
239})
240
241// Available test scenarios (UI list with id/label/category)
242export const SCENARIO_LIST = [
243 { id: 'text-only', label: 'Text Only (No Tools)', category: 'basic' },
244 { id: 'server-tool-single', label: 'Single Server Tool', category: 'basic' },
245 { id: 'client-tool-single', label: 'Single Client Tool', category: 'basic' },
246 {
247 id: 'client-tool-reasoning',
248 label: 'Client Tool with Reasoning',
249 category: 'basic',
250 },
251 {
252 id: 'client-tool-stop',
253 label: 'Stop Pending Client Tool',
254 category: 'race',
255 },
256 { id: 'approval-tool', label: 'Approval Required Tool', category: 'basic' },
257 {
258 id: 'sequence-server-client',
259 label: 'Server \u2192 Client Sequence',
260 category: 'basic',
261 },
262 {
263 id: 'multimodal-server-tool',
264 label: 'Multimodal Server Tool Result (Regression #1283)',
265 category: 'basic',
266 },
267 { id: 'parallel-tools', label: 'Parallel Tools', category: 'basic' },
268 {
269 id: 'parallel-server-timing',
270 label: 'Parallel Server Tool Timing',
271 category: 'basic',
272 },
273 {
274 id: 'lazy-tool-discovery',
275 label: 'Lazy Tool Discovery',
276 category: 'basic',
277 },
278 { id: 'custom-events', label: 'Custom Event Emitting', category: 'basic' },
279 {
280 id: 'server-context',
281 label: 'Server Runtime Context',
282 category: 'basic',
283 },
284 {
285 id: 'client-context',
286 label: 'Client Runtime Context',
287 category: 'basic',
288 },
289 {
290 id: 'client-server-context',
291 label: 'Forwarded Props to Server Context',
292 category: 'basic',
293 },
294 { id: 'error', label: 'Error Response', category: 'basic' },
295 {
296 id: 'tool-error',
297 label: 'Tool Throws Error',
298 category: 'basic',
299 },
300 {
301 id: 'client-tool-error',
302 label: 'Client Tool Throws Error',
303 category: 'basic',
304 },
305 {
306 id: 'null-tool-input',
307 label: 'Null Tool Input (Regression #265)',
308 category: 'basic',
309 },
310 {
311 id: 'malformed-tool-arguments',
312 label: 'Malformed Tool Arguments (Regression #1131)',
313 category: 'basic',
314 },
315 {
316 id: 'provider-rejected-tool-call',
317 label: 'Provider-Rejected Tool Call',
318 category: 'basic',
319 },
320 {
321 id: 'client-tool-input-error',
322 label: 'Client Tool Input Error',
323 category: 'basic',
324 },
325 {
326 id: 'invalid-client-tool-retry',
327 label: 'Invalid Client Tool Retry (Regression #1192)',
328 category: 'race',
329 },
330 // Race condition / event flow scenarios
331 {
332 id: 'sequential-client-tools',
333 label: 'Sequential Client Tools (2)',
334 category: 'race',
335 },
336 {
337 id: 'parallel-client-tools',
338 label: 'Parallel Client Tools',
339 category: 'race',
340 },
341 {
342 id: 'sequential-approvals',
343 label: 'Sequential Approvals (2)',
344 category: 'race',
345 },
346 { id: 'parallel-approvals', label: 'Parallel Approvals', category: 'race' },
347 {
348 id: 'client-then-approval',
349 label: 'Client \u2192 Approval',
350 category: 'race',
351 },
352 {
353 id: 'approval-then-client',
354 label: 'Approval \u2192 Client',
355 category: 'race',
356 },
357 {
358 id: 'server-then-two-clients',
359 label: 'Server \u2192 2 Clients',
360 category: 'race',
361 },
362 {
363 id: 'triple-client-sequence',
364 label: 'Triple Client Sequence',
365 category: 'race',
366 },
367 {
368 id: 'interleaved-args',
369 label: 'Text Interleaved in Tool Args (Regression #1017)',
370 category: 'race',
371 },
372 {
373 id: 'canonical-tool-input',
374 label: 'TOOL_CALL_END Input Replaces Streamed Args',
375 category: 'race',
376 },
377]
378
379/**
380 * Get the tools needed for a specific scenario
381 */
382export function getToolsForScenario(scenario: string) {
383 switch (scenario) {
384 case 'text-only':
385 return []
386
387 case 'server-tool-single':
388 return [serverTools.get_weather]
389
390 case 'client-tool-single':
391 case 'client-tool-reasoning':
392 case 'client-tool-stop':
393 case 'client-tool-input-error':
394 case 'invalid-client-tool-retry':
395 return [clientToolDefinitions.show_notification]
396
397 case 'client-tool-error':
398 return [clientToolDefinitions.fail_client_tool]
399
400 case 'server-context':
401 return [serverTools.read_server_context]
402
403 case 'client-context':
404 return [clientToolDefinitions.read_client_context]
405
406 case 'client-server-context':
407 return [serverTools.read_server_context]
408
409 case 'approval-tool':
410 return [serverTools.delete_file]
411
412 case 'sequence-server-client':
413 return [serverTools.fetch_data, clientToolDefinitions.display_chart]
414
415 case 'multimodal-server-tool':
416 return [serverTools.get_screenshot]
417
418 case 'parallel-tools':
419 return [serverTools.get_weather, serverTools.get_time]
420
421 case 'parallel-server-timing':
422 return [timedServerTools.get_weather, timedServerTools.get_time]
423
424 // Race condition / event flow scenarios
425 case 'sequential-client-tools':
426 return [clientToolDefinitions.show_notification]
427
428 case 'parallel-client-tools':
429 return [
430 clientToolDefinitions.show_notification,
431 clientToolDefinitions.display_chart,
432 ]
433
434 case 'sequential-approvals':
435 return [serverTools.delete_file]
436
437 case 'parallel-approvals':
438 return [serverTools.delete_file]
439
440 case 'client-then-approval':
441 return [clientToolDefinitions.show_notification, serverTools.delete_file]
442
443 case 'approval-then-client':
444 return [serverTools.delete_file, clientToolDefinitions.show_notification]
445
446 case 'server-then-two-clients':
447 return [
448 serverTools.fetch_data,
449 clientToolDefinitions.show_notification,
450 clientToolDefinitions.display_chart,
451 ]
452
453 case 'triple-client-sequence':
454 return [
455 clientToolDefinitions.show_notification,
456 clientToolDefinitions.display_chart,
457 ]
458
459 case 'interleaved-args':
460 return [serverTools.get_weather]
461
462 case 'lazy-tool-discovery':
463 return [serverTools.get_weather, searchInventory]
464
465 case 'custom-events':
466 return [processOrder]
467
468 case 'tool-error':
469 return [failingTool]
470
471 case 'null-tool-input':
472 return [serverTools.check_status]
473
474 case 'malformed-tool-arguments':
475 case 'provider-rejected-tool-call':
476 case 'canonical-tool-input':
477 return [serverTools.check_status]
478
479 default:
480 return []
481 }
482}