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

database-tools.ts

531 lines11.3 KB

1/* eslint-disable @typescript-eslint/require-await -- toolDefinition .server uses async handlers */
2import { z } from 'zod'
3import { toolDefinition } from '@tanstack/ai'
4​
5// ─── In-memory database ────────────────────────────────────────────────────
6​
7interface Customer {
8 id: number
9 name: string
10 email: string
11 city: string
12 joined: string
14​
15interface Product {
16 id: number
17 name: string
18 category: string
19 price: number
20 stock: number
22​
23interface Purchase {
24 id: number
25 customer_id: number
26 product_id: number
27 quantity: number
28 total: number
29 purchased_at: string
31​
32const CUSTOMERS: Array<Customer> = [
33 {
34 id: 1,
35 name: 'Alice Johnson',
36 email: 'alice@example.com',
37 city: 'New York',
38 joined: '2024-01-15',
39 },
40 {
41 id: 2,
42 name: 'Bob Smith',
43 email: 'bob@example.com',
44 city: 'San Francisco',
45 joined: '2024-02-20',
46 },
47 {
48 id: 3,
49 name: 'Carol Williams',
50 email: 'carol@example.com',
51 city: 'Chicago',
52 joined: '2024-03-10',
53 },
54 {
55 id: 4,
56 name: 'David Brown',
57 email: 'david@example.com',
58 city: 'Austin',
59 joined: '2024-04-05',
60 },
61 {
62 id: 5,
63 name: 'Eva Martinez',
64 email: 'eva@example.com',
65 city: 'Seattle',
66 joined: '2024-05-18',
67 },
68 {
69 id: 6,
70 name: 'Frank Lee',
71 email: 'frank@example.com',
72 city: 'New York',
73 joined: '2024-06-01',
74 },
75 {
76 id: 7,
77 name: 'Grace Kim',
78 email: 'grace@example.com',
79 city: 'San Francisco',
80 joined: '2024-07-22',
81 },
82 {
83 id: 8,
84 name: 'Henry Davis',
85 email: 'henry@example.com',
86 city: 'Chicago',
87 joined: '2024-08-14',
88 },
89 {
90 id: 9,
91 name: 'Ivy Chen',
92 email: 'ivy@example.com',
93 city: 'Austin',
94 joined: '2024-09-30',
95 },
96 {
97 id: 10,
98 name: 'Jack Wilson',
99 email: 'jack@example.com',
100 city: 'Seattle',
101 joined: '2024-10-12',
102 },
104​
105const PRODUCTS: Array<Product> = [
106 {
107 id: 1,
108 name: 'Wireless Mouse',
109 category: 'Electronics',
110 price: 29.99,
111 stock: 150,
112 },
113 {
114 id: 2,
115 name: 'Mechanical Keyboard',
116 category: 'Electronics',
117 price: 89.99,
118 stock: 75,
119 },
120 {
121 id: 3,
122 name: 'USB-C Hub',
123 category: 'Electronics',
124 price: 49.99,
125 stock: 200,
126 },
127 {
128 id: 4,
129 name: 'Standing Desk',
130 category: 'Furniture',
131 price: 399.99,
132 stock: 30,
133 },
134 {
135 id: 5,
136 name: 'Ergonomic Chair',
137 category: 'Furniture',
138 price: 299.99,
139 stock: 45,
140 },
141 {
142 id: 6,
143 name: 'Monitor Light Bar',
144 category: 'Electronics',
145 price: 59.99,
146 stock: 120,
147 },
148 {
149 id: 7,
150 name: 'Desk Organizer',
151 category: 'Office',
152 price: 24.99,
153 stock: 300,
154 },
155 { id: 8, name: 'Notebook Set', category: 'Office', price: 14.99, stock: 500 },
156 {
157 id: 9,
158 name: 'Webcam HD',
159 category: 'Electronics',
160 price: 69.99,
161 stock: 90,
162 },
163 {
164 id: 10,
165 name: 'Desk Lamp',
166 category: 'Furniture',
167 price: 44.99,
168 stock: 180,
169 },
171​
172const PURCHASES: Array<Purchase> = [
173 {
174 id: 1,
175 customer_id: 1,
176 product_id: 2,
177 quantity: 1,
178 total: 89.99,
179 purchased_at: '2024-03-01',
180 },
181 {
182 id: 2,
183 customer_id: 1,
184 product_id: 3,
185 quantity: 2,
186 total: 99.98,
187 purchased_at: '2024-03-15',
188 },
189 {
190 id: 3,
191 customer_id: 2,
192 product_id: 1,
193 quantity: 3,
194 total: 89.97,
195 purchased_at: '2024-04-02',
196 },
197 {
198 id: 4,
199 customer_id: 2,
200 product_id: 5,
201 quantity: 1,
202 total: 299.99,
203 purchased_at: '2024-04-10',
204 },
205 {
206 id: 5,
207 customer_id: 3,
208 product_id: 4,
209 quantity: 1,
210 total: 399.99,
211 purchased_at: '2024-05-01',
212 },
213 {
214 id: 6,
215 customer_id: 3,
216 product_id: 7,
217 quantity: 4,
218 total: 99.96,
219 purchased_at: '2024-05-20',
220 },
221 {
222 id: 7,
223 customer_id: 4,
224 product_id: 6,
225 quantity: 2,
226 total: 119.98,
227 purchased_at: '2024-06-05',
228 },
229 {
230 id: 8,
231 customer_id: 4,
232 product_id: 8,
233 quantity: 5,
234 total: 74.95,
235 purchased_at: '2024-06-18',
236 },
237 {
238 id: 9,
239 customer_id: 5,
240 product_id: 9,
241 quantity: 1,
242 total: 69.99,
243 purchased_at: '2024-07-01',
244 },
245 {
246 id: 10,
247 customer_id: 5,
248 product_id: 10,
249 quantity: 1,
250 total: 44.99,
251 purchased_at: '2024-07-15',
252 },
253 {
254 id: 11,
255 customer_id: 6,
256 product_id: 2,
257 quantity: 2,
258 total: 179.98,
259 purchased_at: '2024-08-01',
260 },
261 {
262 id: 12,
263 customer_id: 6,
264 product_id: 1,
265 quantity: 1,
266 total: 29.99,
267 purchased_at: '2024-08-20',
268 },
269 {
270 id: 13,
271 customer_id: 7,
272 product_id: 4,
273 quantity: 1,
274 total: 399.99,
275 purchased_at: '2024-09-05',
276 },
277 {
278 id: 14,
279 customer_id: 7,
280 product_id: 3,
281 quantity: 1,
282 total: 49.99,
283 purchased_at: '2024-09-15',
284 },
285 {
286 id: 15,
287 customer_id: 8,
288 product_id: 5,
289 quantity: 1,
290 total: 299.99,
291 purchased_at: '2024-10-01',
292 },
293 {
294 id: 16,
295 customer_id: 8,
296 product_id: 6,
297 quantity: 3,
298 total: 179.97,
299 purchased_at: '2024-10-10',
300 },
301 {
302 id: 17,
303 customer_id: 9,
304 product_id: 7,
305 quantity: 2,
306 total: 49.98,
307 purchased_at: '2024-10-20',
308 },
309 {
310 id: 18,
311 customer_id: 9,
312 product_id: 9,
313 quantity: 1,
314 total: 69.99,
315 purchased_at: '2024-11-01',
316 },
317 {
318 id: 19,
319 customer_id: 10,
320 product_id: 10,
321 quantity: 2,
322 total: 89.98,
323 purchased_at: '2024-11-10',
324 },
325 {
326 id: 20,
327 customer_id: 10,
328 product_id: 2,
329 quantity: 1,
330 total: 89.99,
331 purchased_at: '2024-11-25',
332 },
333 {
334 id: 21,
335 customer_id: 1,
336 product_id: 6,
337 quantity: 1,
338 total: 59.99,
339 purchased_at: '2024-12-01',
340 },
341 {
342 id: 22,
343 customer_id: 3,
344 product_id: 9,
345 quantity: 2,
346 total: 139.98,
347 purchased_at: '2024-12-10',
348 },
349 {
350 id: 23,
351 customer_id: 5,
352 product_id: 4,
353 quantity: 1,
354 total: 399.99,
355 purchased_at: '2024-12-15',
356 },
357 {
358 id: 24,
359 customer_id: 2,
360 product_id: 8,
361 quantity: 10,
362 total: 149.9,
363 purchased_at: '2024-12-20',
364 },
365 {
366 id: 25,
367 customer_id: 4,
368 product_id: 3,
369 quantity: 3,
370 total: 149.97,
371 purchased_at: '2024-12-28',
372 },
374​
375// ─── Simple query engine ───────────────────────────────────────────────────
376​
377type Table = 'customers' | 'products' | 'purchases'
378​
379const TABLES: Record<Table, Array<Record<string, unknown>>> = {
380 customers: CUSTOMERS as unknown as Array<Record<string, unknown>>,
381 products: PRODUCTS as unknown as Array<Record<string, unknown>>,
382 purchases: PURCHASES as unknown as Array<Record<string, unknown>>,
384​
385function getTableSchema(table: Table): Record<string, string> {
386 const schemas: Record<Table, Record<string, string>> = {
387 customers: {
388 id: 'number',
389 name: 'string',
390 email: 'string',
391 city: 'string',
392 joined: 'string (date)',
393 },
394 products: {
395 id: 'number',
396 name: 'string',
397 category: 'string',
398 price: 'number',
399 stock: 'number',
400 },
401 purchases: {
402 id: 'number',
403 customer_id: 'number',
404 product_id: 'number',
405 quantity: 'number',
406 total: 'number',
407 purchased_at: 'string (date)',
408 },
409 }
410 return schemas[table]
412​
413function evaluateCondition(
414 row: Record<string, unknown>,
415 where: Record<string, unknown>,
416): boolean {
417 for (const [key, value] of Object.entries(where)) {
418 if (row[key] !== value) return false
419 }
420 return true
422​
423// ─── Tool definitions ──────────────────────────────────────────────────────
424​
425export const queryTableTool = toolDefinition({
426 name: 'queryTable',
427 description:
428 'Query an in-memory database table. Supports filtering rows by exact-match conditions on columns, selecting specific columns, ordering by a column, and limiting results. Available tables: customers (id, name, email, city, joined), products (id, name, category, price, stock), purchases (id, customer_id, product_id, quantity, total, purchased_at).',
429 inputSchema: z.object({
430 table: z
431 .enum(['customers', 'products', 'purchases'])
432 .describe('The table to query'),
433 columns: z
434 .array(z.string())
435 .optional()
436 .describe('Columns to return. If omitted, all columns are returned.'),
437 where: z
438 .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
439 .optional()
440 .describe(
441 'Filter conditions as key-value pairs (exact match). Example: { "city": "New York" }',
442 ),
443 orderBy: z.string().optional().describe('Column name to sort results by'),
444 orderDirection: z
445 .enum(['asc', 'desc'])
446 .optional()
447 .describe('Sort direction, defaults to asc'),
448 limit: z.number().optional().describe('Maximum number of rows to return'),
449 }),
450 outputSchema: z.object({
451 rows: z.array(z.record(z.string(), z.any())),
452 totalMatchingRows: z.number(),
453 }),
454}).server(async ({ table, columns, where, orderBy, orderDirection, limit }) => {
455 if (!(table in TABLES)) {
456 throw new Error(
457 `Invalid table "${String(table)}". Use "customers", "products", or "purchases". ` +
458 `Call external_queryTable({ table: "purchases" }) with an object — not SQL strings.`,
459 )
460 }
461 const tableData = TABLES[table]
462 let rows = [...tableData]
463​
464 // Filter
465 if (where && Object.keys(where).length > 0) {
466 rows = rows.filter((row) => evaluateCondition(row, where))
467 }
468​
469 const totalMatchingRows = rows.length
470​
471 // Order
472 if (orderBy) {
473 const dir = orderDirection === 'desc' ? -1 : 1
474 rows.sort((a, b) => {
475 const aVal = a[orderBy]
476 const bVal = b[orderBy]
477 if (typeof aVal === 'number' && typeof bVal === 'number')
478 return (aVal - bVal) * dir
479 return String(aVal).localeCompare(String(bVal)) * dir
480 })
481 }
482​
483 // Limit
484 if (limit !== undefined) {
485 rows = rows.slice(0, limit)
486 }
487​
488 // Select columns
489 if (columns && columns.length > 0) {
490 rows = rows.map((row) => {
491 const selected: Record<string, unknown> = {}
492 for (const col of columns) {
493 if (col in row) selected[col] = row[col]
494 }
495 return selected
496 })
497 }
498​
499 return { rows, totalMatchingRows }
500})
501​
502export const getSchemaInfoTool = toolDefinition({
503 name: 'getSchemaInfo',
504 description:
505 'Get schema information for one or all database tables. Returns column names and types. Use this to understand what data is available before querying.',
506 inputSchema: z.object({
507 table: z
508 .enum(['customers', 'products', 'purchases'])
509 .optional()
510 .describe(
511 'Specific table to get schema for. If omitted, returns all table schemas.',
512 ),
513 }),
514 outputSchema: z.object({
515 schemas: z.record(z.string(), z.record(z.string(), z.string())),
516 rowCounts: z.record(z.string(), z.number()),
517 }),
518}).server(async ({ table }) => {
519 const tables: Array<Table> = table
520 ? [table]
521 : ['customers', 'products', 'purchases']
522 const schemas: Record<string, Record<string, string>> = {}
523 const rowCounts: Record<string, number> = {}
524 for (const t of tables) {
525 schemas[t] = getTableSchema(t)
526 rowCounts[t] = TABLES[t].length
527 }
528 return { schemas, rowCounts }
529})
530​
531export const databaseTools = [queryTableTool, getSchemaInfoTool]