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

tool-approval.md

281 lines8.4 KB

1---
2title: Tool Approval
3id: interrupts-tool-approval
4order: 2
5description: "Stop a tool call until a person says yes or no, show the question in the chat, and continue the run with the decision."
6keywords:
7 - tanstack ai
8 - tool approval
9 - needsApproval
10 - approvalSchema
11 - resolveInterrupt
12---
13​
14Set `needsApproval: true` on a tool. The model can plan the call. The tool runs after a person approves it.
15​
16The chat shows an approve or reject prompt, and the run continues with the decision.
17​
18## Quick setup
19​
20### 1. Define the tool
21​
22Put the tool in a file that the server and the browser both import, so both
23sides get the same types:
24​
25```ts
26// tools/transfer.ts
27import { toolDefinition } from '@tanstack/ai'
28import { z } from 'zod'
29​
30export const transferTool = toolDefinition({
31 name: 'transfer',
32 description: 'Transfer funds to a recipient',
33 needsApproval: true,
34 inputSchema: z.object({
35 amount: z.number().positive(),
36 recipient: z.string().min(1),
37 }),
38 outputSchema: z.object({ receiptId: z.string() }),
39})
40```
41​
42### 2. Serve it
43​
44The server runs the tool only after the user approves. Forward `parentRunId`
45and `resume` into `chat()`. The browser sends back the message history and the
46decision, so `chat()` can rebuild the paused call with no database:
47​
48```ts
49// app/api/chat/route.ts
50import {
51 chat,
52 chatParamsFromRequest,
53 toServerSentEventsResponse,
54} from '@tanstack/ai'
55import { openaiText } from '@tanstack/ai-openai'
56import { transferTool } from '../../../tools/transfer'
57​
58const transfer = transferTool.server(
59 async (input: { amount: number; recipient: string }) => ({
60 receiptId: `${input.recipient}-${input.amount}-${crypto.randomUUID()}`,
61 }),
63​
64export async function POST(request: Request) {
65 const params = await chatParamsFromRequest(request)
66 const stream = chat({
67 adapter: openaiText('gpt-6.1-sol'),
68 messages: params.messages,
69 threadId: params.threadId,
70 runId: params.runId,
71 parentRunId: params.parentRunId,
72 ...(params.resume ? { resume: params.resume } : {}),
73 tools: [transfer],
74 })
75 return toServerSentEventsResponse(stream)
77```
78​
79### 3. Render it in the chat
80​
81Pass the shared tool to `useChat`, so `toolName` and `originalArgs` are typed.
82When the run pauses, the approval shows up in `interrupts`. Resolve it on the
83item with `interrupt.resolveInterrupt(...)`:
84​
85```tsx
86// app/transfer-chat.tsx
87import { useState } from 'react'
88import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
89import { transferTool } from '../tools/transfer'
90​
91export function TransferChat() {
92 const { messages, sendMessage, interrupts, resuming } = useChat({
93 threadId: 'account-42',
94 connection: fetchServerSentEvents('/api/chat'),
95 tools: [transferTool] as const,
96 })
97 const [input, setInput] = useState('')
98​
99 return (
100 <div>
101 {messages.map((message) => (
102 <div key={message.id}>
103 <strong>{message.role}: </strong>
104 {message.parts.map((part, i) =>
105 part.type === 'text' ? <span key={i}>{part.content}</span> : null,
106 )}
107 </div>
108 ))}
109​
110 {interrupts.map((interrupt) => {
111 if (
112 interrupt.kind !== 'tool-approval' ||
113 interrupt.toolName !== 'transfer'
114 ) {
115 return null
116 }
117 return (
118 <div key={interrupt.id} className="approval">
119 <p>
120 Send {interrupt.originalArgs.amount} to{' '}
121 {interrupt.originalArgs.recipient}?
122 </p>
123 <button
124 disabled={!interrupt.canResolve || resuming}
125 onClick={() => interrupt.resolveInterrupt(true)}
126 >
127 Approve
128 </button>
129 <button
130 disabled={!interrupt.canResolve || resuming}
131 onClick={() => interrupt.resolveInterrupt(false)}
132 >
133 Reject
134 </button>
135 </div>
136 )
137 })}
138​
139 <form
140 onSubmit={(event) => {
141 event.preventDefault()
142 void sendMessage(input)
143 setInput('')
144 }}
145 >
146 <input value={input} onChange={(event) => setInput(event.target.value)} />
147 <button type="submit">Send</button>
148 </form>
149 </div>
150 )
152```
153​
154### 4. Try it
155​
156Ask the model to send 20 to Ada. The chat stops and asks "Send 20 to Ada?".
157Click Approve. The tool runs, and the model replies with the receipt.
158​
159## How it works
160​
161With one pending decision, `resolveInterrupt` submits at once. There is no
162extra step. To answer several decisions together, see
163[Multiple Interrupts](./multiple).
164​
165Approval works the same for server tools and client tools. Only the place where
166the tool runs after the yes is different:
167​
168- A **server tool** (`.server()`) runs on the server.
169- A **client tool** (`.client()`) runs in the browser.
170​
171The approval interrupt is the same in both cases, so the UI above does not
172change. A client tool without `needsApproval` runs on its own and never pauses.
173See [Client Tools](../tools/client-tools).
174​
175Reject and cancel are two different answers:
176​
177- `interrupt.resolveInterrupt(false)` is a no. The run continues, and the model
178 sees the rejection, so it can respond to it.
179- `interrupt.cancel()` drops the pause with no answer. It has no payload and
180 does not use the reject branch.
181​
182If the user answered no, use reject. If the user leaves the workflow without an
183answer, use cancel.
184​
185## Add data to the decision
186​
187Sometimes the decision needs data: a review note, or the reason for a no. Add
188an `approvalSchema` to the tool definition. Use one schema for both branches,
189or an `{ approve, reject }` map for a different payload per branch:
190​
191```ts
192// tools/transfer.ts
193import { toolDefinition } from '@tanstack/ai'
194import { z } from 'zod'
195​
196export const transferTool = toolDefinition({
197 name: 'transfer',
198 description: 'Transfer funds to a recipient',
199 needsApproval: true,
200 inputSchema: z.object({
201 amount: z.number().positive(),
202 recipient: z.string().min(1),
203 }),
204 outputSchema: z.object({ receiptId: z.string() }),
205 approvalSchema: {
206 approve: z.object({ note: z.string().min(1) }),
207 reject: z.object({ reason: z.string().min(1) }),
208 },
209})
210```
211​
212Now each decision carries a payload. On approval, you can also replace the
213arguments:
214​
215```ts ignore
216// Approve with the approve-branch payload.
217interrupt.resolveInterrupt(true, { payload: { note: 'Reviewed' } })
218​
219// Approve, but replace the arguments first.
220interrupt.resolveInterrupt(true, {
221 editedArgs: { amount: 12, recipient: 'Ada' },
222 payload: { note: 'Capped to policy' },
223})
224​
225// Reject with the reject-branch payload.
226interrupt.resolveInterrupt(false, { payload: { reason: 'Too large' } })
227```
228​
229Without an `approvalSchema`, `resolveInterrupt(true)` and
230`resolveInterrupt(false)` are all you need.
231​
232## Advanced
233​
234### Rules for `editedArgs`
235​
236- Only approval accepts `editedArgs`. Reject does not.
237- `editedArgs` is a full replacement of the arguments, not a merge.
238- The tool `inputSchema` validates `editedArgs`.
239- The server validates the full decision again before it runs the tool.
240​
241### Where `editedArgs` and `payload` go on the server
242​
243`editedArgs` become the arguments that the tool runs with. You wire up nothing:
244`execute` always gets the final input, edited or not, already validated against
245`inputSchema`:
246​
247```ts
248// server/transfer-tool.ts
249import { toolDefinition } from '@tanstack/ai'
250import { z } from 'zod'
251​
252const transferTool = toolDefinition({
253 name: 'transfer',
254 description: 'Move money between accounts',
255 needsApproval: true,
256 inputSchema: z.object({
257 recipient: z.string(),
258 amount: z.number(),
259 }),
260 outputSchema: z.object({ receiptId: z.string() }),
261})
262​
263export const transfer = transferTool.server(async (input) => {
264 // input holds the model's arguments, or the approver's editedArgs when
265 // they changed them. The code is the same in both cases.
266 return {
267 receiptId: `${input.recipient}-${input.amount}-${crypto.randomUUID()}`,
268 }
269})
270```
271​
272The `payload` is decision data, not tool input. Each branch uses it in a
273different way:
274​
275- **Reject payload.** It goes back to the model as the failed result of
276 the call. Then the model can read why the call was refused.
277 `resolveInterrupt(false, { payload: { reason: 'Too large' } })` gives
278 `{ reason: 'Too large' }` to the model as the result of that call.
279- **Approve payload.** It is validated decision data for your app: an audit
280 log, a "reviewed by" record, an analytics event. `execute` does not get it.
281 If the tool needs a value from the approver, put that value in `editedArgs`.