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

tool-approval.md

268 lines8.6 KB

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