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