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

database-tools.ts

528 lines11.0 KB

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