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

toolDefinition.md

91 lines2.5 KB

1---
2id: toolDefinition
3title: toolDefinition
4---
5​
6# Function: toolDefinition()
7​
8```ts
9function toolDefinition<TInput, TOutput, TName>(config): ToolDefinition<TInput, TOutput, TName>;
10```
11​
12Defined in: [packages/typescript/ai/src/activities/chat/tools/tool-definition.ts:192](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/activities/chat/tools/tool-definition.ts#L192)
13​
14Create an isomorphic tool definition that can be used directly or instantiated for server/client
15​
16The definition contains all tool metadata (name, description, schemas) and can be:
171. Used directly in chat() on the server (as a tool definition without execute)
182. Instantiated as a server tool with .server()
193. Instantiated as a client tool with .client()
20​
21Supports any Standard JSON Schema compliant library (Zod v4+, ArkType, Valibot, etc.)
22or plain JSON Schema objects.
23​
24## Type Parameters
25​
26### TInput
27​
28`TInput` *extends* [`SchemaInput`](../type-aliases/SchemaInput.md) = [`SchemaInput`](../type-aliases/SchemaInput.md)
29​
30### TOutput
31​
32`TOutput` *extends* [`SchemaInput`](../type-aliases/SchemaInput.md) = [`SchemaInput`](../type-aliases/SchemaInput.md)
33​
34### TName
35​
36`TName` *extends* `string` = `string`
37​
38## Parameters
39​
40### config
41​
42[`ToolDefinitionConfig`](../interfaces/ToolDefinitionConfig.md)\<`TInput`, `TOutput`, `TName`\>
43​
44## Returns
45​
46[`ToolDefinition`](../interfaces/ToolDefinition.md)\<`TInput`, `TOutput`, `TName`\>
47​
48## Example
49​
50```typescript
51import { toolDefinition } from '@tanstack/ai';
52import { z } from 'zod';
53​
54// Using Zod (natively supports Standard JSON Schema)
55const addToCartTool = toolDefinition({
56 name: 'addToCart',
57 description: 'Add a guitar to the shopping cart (requires approval)',
58 needsApproval: true,
59 inputSchema: z.object({
60 guitarId: z.string(),
61 quantity: z.number(),
62 }),
63 outputSchema: z.object({
64 success: z.boolean(),
65 cartId: z.string(),
66 totalItems: z.number(),
67 }),
68});
69​
70// Use directly in chat (server-side, no execute function)
71chat({
72 tools: [addToCartTool],
73 // ...
74});
75​
76// Or create server-side implementation
77const addToCartServer = addToCartTool.server(async (args) => {
78 // args is typed as { guitarId: string; quantity: number }
79 return {
80 success: true,
81 cartId: 'CART_' + Date.now(),
82 totalItems: args.quantity,
83 };
84});
85​
86// Or create client-side implementation
87const addToCartClient = addToCartTool.client(async (args) => {
88 // Client-specific logic (e.g., localStorage)
89 return { success: true, cartId: 'local', totalItems: 1 };
90});
91```