AI › AI Tools

Implementing server tool approval with TanStack AI interrupts

Use TanStack AI v1.11.0 toolDefinition and AG-UI server-tool-approval interrupts to pause sensitive server tools until an operator approves or denies.

Implementing server tool approval with TanStack AI interrupts

Letting an LLM execute refund, deletion, or permission-change tools immediately means one bad argument can mutate production state. With TanStack AI v1.11.0’s toolDefinition({ needsApproval: true }) and AG-UI server-tool-approval interrupts, you can keep server handler execution at 0 calls until an operator explicitly approves.

All code and measurements below were verified on Node.js v22.23.3, Next.js 15.5.29, React 19.3.1, TypeScript 5.9.3, @tanstack/ai@1.11.0, @tanstack/ai-react@1.3.0, @tanstack/ai-ollama@1.1.1, and zod@4.6.7. I first confirmed native issue_order_refund tool calling and server-tool-approval interruption against a live local Ollama 0.40.18 instance (qwen2.5:1.5b). To hold tool-call arguments constant across the approval, denial, missing-resume, and page-reload matrix—and for the screenshots—I routed the exact same @tanstack/ai-ollama adapter to a local Ollama-compatible deterministic mock server (127.0.0.1:11439).

Why server tools need an approval boundary in TanStack AI 1.x

Read-only lookups and state-changing operations need different execution boundaries in an operations console. Fetching an order summary is safe to run automatically, but issuing a 45,000 KRW refund for order ORD-2026-4091 should pause so an operator can inspect the order ID, amount, and reason before the ledger updates.

In TanStack AI 0.x, approvals went through addToolApprovalResponse on the useChat return object. TanStack AI 1.x moved to the AG-UI interrupt protocol, and @tanstack/ai-react@1.3.0 removed addToolApprovalResponse from UseChatReturn. Instead, useChat exposes interrupts, interruptErrors, resuming, and resolveInterrupts, and each interrupt provides interrupt.resolveInterrupt(true) or interrupt.resolveInterrupt(false) to resume the run.

The server contract changed alongside it. Both chat() and useChat() now require threadId (replacing the removed conversationId), and the server Route Handler must pass parentRunId and resume from chatParamsFromRequest(request) back into chat() so the paused tool execution can continue.

flowchart TD
    A["Operator sends refund request"] --> B["Server chat() calls model"]
    B --> C["needsApproval tool pauses run"]
    C --> D["React renders server-tool-approval card"]
    D -->|"resolveInterrupt(true)"| E["parentRunId + resume runs .server() once"]
    D -->|"resolveInterrupt(false)"| F["Handler stays at 0 calls; denial sent to model"]

Pick the tool execution boundary based on where side effects happen:

Tool setupExecution locationInterrupt kindGood fit
.server() + needsApproval: trueServer Route Handlerserver-tool-approvalRefunds, account suspension, DB writes, payment API calls
.client() + needsApproval: trueBrowser (useChat({ tools }))tool-approvalTriggering local downloads, bulk client-side state updates
.server() (no needsApproval)Server Route HandlerNone (runs immediately)Read-only order lookups, log queries, idempotent calculations

Don’t add needsApproval: true to every tool. Putting human gates on read-only lookups or unattended batch jobs slows down every turn and trains operators to click approve without reading. Keep approval boundaries strictly on irreversible or sensitive writes.

Declaring the refund tool with toolDefinition and needsApproval

toolDefinition declares a tool’s name, description, Zod input/output schemas, and approval requirement in a shared module (src/lib/refund-tool.ts). When the server binds .server() to this definition, both the input arguments and return type stay type-checked end to end.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/lib/refund-tool.ts
import { toolDefinition } from '@tanstack/ai'
import { z } from 'zod'

export const issueOrderRefundDef = toolDefinition({
  name: 'issue_order_refund',
  description:
    'Issue a refund for an existing customer order after explicit operator approval.',
  inputSchema: z.object({
    orderId: z.string().describe('Order identifier such as ORD-2026-4091'),
    amount: z.number().int().positive().describe('Refund amount in KRW'),
    reason: z.string().min(2).describe('Reason for issuing the refund'),
  }),
  outputSchema: z.object({
    orderId: z.string(),
    status: z.enum(['REFUNDED']),
    refundedAmount: z.number().int(),
    processedAt: z.string(),
  }),
  needsApproval: true,
})

Setting needsApproval: true tells the @tanstack/ai runtime not to invoke the .server() callback when the model requests issue_order_refund. Instead, the runtime pauses the current runId and emits an AG-UI approval interrupt over the SSE stream.

For verification, I backed the handler with an in-memory server ledger (src/lib/order-ledger.ts) initialized with order ORD-2026-4091 (45,000 KRW, status: 'PAID', refundedAmount: 0, handlerCalls: 0). Each executeRefund() call increments handlerCalls by 1 and flips status to 'REFUNDED', making it easy to verify whether the handler actually ran.

Resuming paused runs with parentRunId and resume on the server

In the Next.js App Router handler (src/app/api/refund/route.ts), bind issueOrderRefundDef.server(...) and parse the incoming AG-UI payload with chatParamsFromRequest(request). If a client sends malformed JSON or missing fields, chatParamsFromRequest throws a Response instance that you can return directly as HTTP 400.

The critical wiring step is forwarding threadId, runId, parentRunId, and resume into chat():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// src/app/api/refund/route.ts
import {
  chat,
  chatParamsFromRequest,
  toServerSentEventsResponse,
} from '@tanstack/ai'
import { createOllamaChat } from '@tanstack/ai-ollama'
import { issueOrderRefundDef } from '@/lib/refund-tool'
import { executeRefund } from '@/lib/order-ledger'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

const issueOrderRefundServer = issueOrderRefundDef.server(async (input) => {
  return executeRefund(input)
})

export async function POST(request: Request) {
  let params: Awaited<ReturnType<typeof chatParamsFromRequest>>
  try {
    params = await chatParamsFromRequest(request)
  } catch (err) {
    if (err instanceof Response) {
      return err
    }
    throw err
  }

  const stream = chat({
    adapter: createOllamaChat('qwen2.5:1.5b', 'http://127.0.0.1:11434'),
    messages: params.messages,
    threadId: params.threadId,
    runId: params.runId,
    parentRunId: params.parentRunId,
    resume: params.resume,
    tools: [issueOrderRefundServer],
    systemPrompts: [
      'You are an internal order operations assistant.',
      'When the operator asks to refund an order, you MUST call the issue_order_refund tool with the exact orderId, integer amount, and reason.',
      'After the tool either succeeds or is denied by the operator, reply concisely in English summarizing the outcome.',
    ],
    stream: true,
  })

  return toServerSentEventsResponse(stream, {
    headers: { 'X-Accel-Buffering': 'no' },
  })
}

The snippet above targets the local Ollama default (http://127.0.0.1:11434, qwen2.5:1.5b). The test harness adds query parameters (host, model, omitResume) to the same route to switch between live Ollama, the deterministic mock server, and the missing-resume failure test.

If you omit parentRunId and resume in chat(), clicking Approve won’t run the server handler. In my omitResume=1 test, no error banner appeared; handlerCalls stayed at 0, the ledger stayed PAID, and the model emitted the same tool call again, looping the approval card.

Rendering approval cards with useChat interrupts in React

On the client (src/app/refund-console/page.tsx), connect fetchServerSentEvents('/api/refund') to useChat and read interrupts and resuming.

One TypeScript gotcha shows up immediately here. When you register a .server() tool on the backend without passing client tools to useChat, the interrupt’s kind is 'server-tool-approval' (ServerToolApprovalInterrupt), not 'tool-approval'. Checking item.kind === 'tool-approval' without client tools fails compilation with TS2367 because 'tool-approval' only applies to tools registered on the client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// src/app/refund-console/page.tsx (core excerpt)
'use client'

import { useMemo } from 'react'
import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'

export function RefundApprovalPanel() {
  const connection = useMemo(() => fetchServerSentEvents('/api/refund'), [])

  const { interrupts, resuming } = useChat({
    threadId: 'refund-console-thread',
    connection,
  })

  // Server-only approval tools emit kind === 'server-tool-approval'.
  const approvalInterrupts = interrupts.filter(
    (item) => item.kind === 'server-tool-approval',
  )

  return (
    <div>
      {approvalInterrupts.map((interrupt) => (
        <div key={interrupt.id}>
          <strong>Approval Required: {interrupt.toolName}</strong>
          <pre>{JSON.stringify(interrupt.originalArgs ?? {}, null, 2)}</pre>
          <button
            type="button"
            disabled={!interrupt.canResolve || resuming}
            onClick={() => interrupt.resolveInterrupt(true)}
          >
            Approve Refund
          </button>
          <button
            type="button"
            disabled={!interrupt.canResolve || resuming}
            onClick={() => interrupt.resolveInterrupt(false)}
          >
            Deny Refund
          </button>
        </div>
      ))}
    </div>
  )
}

In @tanstack/ai-react@1.3.0, interrupt.resolveInterrupt(true) and interrupt.resolveInterrupt(false) compile cleanly with a single boolean argument (npx tsc --noEmit passes). Gating the buttons with !interrupt.canResolve || resuming prevents duplicate resume requests while the first decision is in flight.

Verifying pending, approved, denied, and reload transitions

I first sent "Process a 45000 KRW refund for order ORD-2026-4091 due to shipping delay." to live local Ollama 0.40.18 (qwen2.5:1.5b). The model natively called issue_order_refund with {"amount": 45000, "orderId": "ORD-2026-4091", "reason": "shipping delay"}, the UI displayed a kind: server-tool-approval card, and the server ledger stayed at PAID with handlerCalls: 0.

Next, I ran the full five-case matrix through the same @tanstack/ai-ollama createOllamaChat adapter against the local Ollama-compatible deterministic mock server (127.0.0.1:11439) so every branch started from identical tool arguments:

ScenarioClient actionLedger statushandlerCallsRefunded amountObserved result
Pending approvalSubmit refund promptPAID00 KRWkind: server-tool-approval card shown; execution paused
ApprovedresolveInterrupt(true)REFUNDED145,000 KRWparentRunId + resume sent; .server() ran once; summary streamed
DeniedresolveInterrupt(false)PAID00 KRWHandler never ran; denial returned to model; denial summary streamed
Missing resumeOmit parentRunId/resume on serverPAID00 KRWNo error banner; handler stayed 0; approval card reappeared (1 card)
Reload while pendingRefresh browser before decisionPAID00 KRWApproval card disappeared (1 -> 0) without persistence; ledger stayed PAID

While paused, the right panel shows Approval Required: issue_order_refund with kind: server-tool-approval, while the server ledger on the left stays at PAID and Server Handler Calls: 0.

Order Refund Approval Console paused at a TanStack AI server-tool-approval interrupt for order ORD-2026-4091 Figure 1. Pending approval state verified via @tanstack/ai-ollama against the local deterministic mock server (interrupts: 1, kind: server-tool-approval, ledger PAID, Server Handler Calls: 0).

Clicking Approve Refund sends the following resume payload to /api/refund:

1
2
3
4
5
6
7
8
9
10
11
12
{
  "parentRunId": "run-1796220193338-0m54e1",
  "resume": [
    {
      "interruptId": "approval_issue_order_refund-1796220193372-06ie1n1cs93o",
      "payload": {
        "approved": true
      },
      "status": "resolved"
    }
  ]
}

Once the server forwards parentRunId and resume into chat(), the .server() handler runs exactly once, updating ORD-2026-4091 to REFUNDED (45,000 KRW), and the model streams a confirmation summary.

Order Refund Approval Console after approving refund with Server Handler Calls at 1 and Ledger Status REFUNDED Figure 2. State after calling resolveInterrupt(true): Server Handler Calls: 1, Ledger Status: REFUNDED, and Refunded Amount: 45,000 KRW.

Clicking Deny Refund sends payload: { "approved": false }. The server handler stays at 0 calls, the order stays PAID with 0 KRW refunded, and the model receives the denial so it can explain that no refund was executed.

Order Refund Approval Console after denying refund with Server Handler Calls at 0 and Ledger Status PAID Figure 3. State after calling resolveInterrupt(false): Server Handler Calls: 0, Ledger Status: PAID, and Refunded Amount: 0 KRW.

Production caveats and checklist

Client-side approval cards stop accidental execution, not malicious requests. Before shipping a server-tool approval flow to an internal console, check four items:

  • Re-validate permissions and state inside .server(): A client can forge an approved: true resume payload. Always re-check the caller’s session role, refund limit, and whether the order is still PAID inside the server handler.
  • Guard side effects with an idempotency key: Protect downstream payment or ledger mutations with a unique constraint on orderId or interruptId so retried resume requests cannot trigger a double refund.
  • Add chat persistence if pending approvals must survive reloads: Without persistence, refreshing the page drops the pending card (1 -> 0). The server ledger fails closed (PAID, 0 calls), but operators lose visibility into pending decisions unless you store thread state with TanStack AI Chat Persistence.
  • Disable proxy buffering and match the exact interrupt kind: Keep X-Accel-Buffering: no on SSE responses behind reverse proxies, and filter on 'server-tool-approval' for server-only tools versus 'tool-approval' for client-registered tools.

References

Make a tool wait for a yes from the user before it runs. Mark it with needsApproval, then show Approve and Deny buttons in your chat.
Move approval and resume code from the 0.x custom events and raw resume APIs to typed AG-UI interrupts in 1.0.
withPersistence writes the transcript and a waiting approval outside the request. A process restart then keeps both. withPersistence is a chat middleware. You choose the store, and the server keeps...
This post is licensed under CC BY 4.0 by the author.