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

toolDefinition.md

87 lines2.2 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: [activities/chat/tools/tool-definition.ts:179](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/activities/chat/tools/tool-definition.ts#L179)
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​
21## Type Parameters
22​
23### TInput
24​
25`TInput` *extends* [`SchemaInput`](../type-aliases/SchemaInput.md) = `ZodAny`
26​
27### TOutput
28​
29`TOutput` *extends* [`SchemaInput`](../type-aliases/SchemaInput.md) = `ZodAny`
30​
31### TName
32​
33`TName` *extends* `string` = `string`
34​
35## Parameters
36​
37### config
38​
39[`ToolDefinitionConfig`](../interfaces/ToolDefinitionConfig.md)\<`TInput`, `TOutput`, `TName`\>
40​
41## Returns
42​
43[`ToolDefinition`](../interfaces/ToolDefinition.md)\<`TInput`, `TOutput`, `TName`\>
44​
45## Example
46​
47```typescript
48import { toolDefinition } from '@tanstack/ai';
49import { z } from 'zod';
50​
51const addToCartTool = toolDefinition({
52 name: 'addToCart',
53 description: 'Add a guitar to the shopping cart (requires approval)',
54 needsApproval: true,
55 inputSchema: z.object({
56 guitarId: z.string(),
57 quantity: z.number(),
58 }),
59 outputSchema: z.object({
60 success: z.boolean(),
61 cartId: z.string(),
62 totalItems: z.number(),
63 }),
64});
65​
66// Use directly in chat (server-side, no execute function)
67chat({
68 tools: [addToCartTool],
69 // ...
70});
71​
72// Or create server-side implementation
73const addToCartServer = addToCartTool.server(async (args) => {
74 // args is typed as { guitarId: string; quantity: number }
75 return {
76 success: true,
77 cartId: 'CART_' + Date.now(),
78 totalItems: args.quantity,
79 };
80});
81​
82// Or create client-side implementation
83const addToCartClient = addToCartTool.client(async (args) => {
84 // Client-specific logic (e.g., localStorage)
85 return { success: true, cartId: 'local', totalItems: 1 };
86});
87```