What you'll learn: By the end of this lesson you will be able to describe what a tool call is and who runs it, design a typed registry that maps tool names to schemas and UI components, model one call as a small state machine (streaming, approval, running, done, failed, denied), decide which calls must wait for a human, validate both the model's input and the tool's output before drawing anything, and say what goes back to the model when a call fails or is refused.
Think of a hotel concierge with a desk of printed forms. A guest says "book me a taxi for 7". The concierge does not drive the taxi: they pick the right form, fill in the fields and hand it to the person who can act on it. If there is no form for the request, they say so. A tool call is that form, filled in by a language model. Your front end is the desk that decides which forms exist, checks they are filled in properly, and shows the guest what happened.
The running example is the order assistant of a grocery marketplace (the front end of the ShopStream marketplace used in this course). In a chat panel a shopper asks "where is order A-1001?" and sees an order card. They ask "cancel it" and see a confirmation before anything changes. This lesson builds the logic behind those two moments. The lab uses no real model: the stream is a list of events written by hand.
The core idea
- The model proposes, your application disposes. A tool call is a name plus JSON arguments. The model does not run anything, and its output is data you did not write.
- The registry is the allow-list. Only tools you registered can be rendered or run, each with an input schema, an output schema, an effect (read or write) and a component key.
- A call is a state machine, not a boolean. It streams, may wait for approval, runs, then succeeds, fails or is denied. The UI is a pure function of that state, and every state also decides what the model is told next.
What a tool call is
Anthropic's documentation says tool use "lets Claude call functions that you define", and that Claude "returns a structured call that your application runs (client tools) or that Anthropic runs (server tools)". For a client tool the response has stop_reason: "tool_use" and one or more tool_use blocks with an id, a name and an input that conforms to the tool's input_schema. Your code runs the operation and answers with a tool_result block. OpenAI's function calling has the same shape under other names: each function call has a call_id, a name and JSON-encoded arguments, and the result goes back as a function_call_output.
Illustration 1: the minimal example
The shape of one round trip, with illustrative values. The model's block, then the application's answer:
{ "type": "tool_use", "id": "toolu_example", "name": "get_order_status", "input": { "orderId": "A-1001" } }
{ "type": "tool_result", "tool_use_id": "toolu_example", "content": "{\"orderId\":\"A-1001\",\"status\":\"packed\"}" }
The id is how the result finds its call. The same Anthropic page says each tool_use block needs one tool_result block "even if the tool failed", and that the result blocks must come first in the user message that follows. The front end sits between these two blocks: it receives the first, decides what the shopper sees, and produces the second.
Figure 1. The front end between the model and the tool
How to read this: the accent boxes are decisions your code makes. Nothing the model emits reaches the UI component or the tool without passing the registry and the state machine.
The registry
A registry entry says what the application is willing to do for one tool name. In the lab (examples/frontend/labs/tool-call-registry) each entry has a name, an input schema, an output schema, an effect of read or write, the key of a component, and a function that writes the approval sentence from validated input. Two entries exist: get_order_status (read) and cancel_order (write).
Two details matter. Look names up in a Map, not a plain object: a model-chosen name such as constructor must not find something on a prototype (the lab's tests check constructor, __proto__ and toString). Reject fields the schema does not name: an extra field suggests the model misunderstood the tool.
Why validate when the provider offers strict mode
Anthropic's strict tool use page says that without strict mode "Claude might return incompatible types ("2" instead of 2) or omit required fields", and that strict: true constrains the model's sampling so tool inputs match your schema. OpenAI says setting strict to true makes calls "reliably adhere to the function schema, instead of being best effort". Strict mode is a good default where it exists, but it does not replace your own check: a range such as "at most 600 minutes" is a business rule, the tool's output comes from your own backend and can drift, and a stream can end before the JSON is complete. MCP's specification says servers must validate all tool inputs and that clients should validate structured results against an output schema when one exists.
One call as a state machine
The AI SDK documents typed tool parts with these states: input-streaming, input-available, output-available, output-error, and for approval approval-requested and output-denied. Its guide tells you to handle every state in your render code. The lab uses the same names; the transitions are its own.
Figure 2. The life of one tool part
How to read this: input_available means "validated, and the tool is running". Every path to output_error from input_streaming happens before any tool ran; the path from input_available happens after, which is why the two kinds of failure get different messages.
Argument text arrives in pieces, so the lab never parses before input-complete: a half-finished JSON string is not a value yet.
Illustration 2: the realistic example
The order assistant cancelling an order. The shopper has asked for it, the model has called cancel_order, and the lab runs the call through the machine. Scenario B of the demo, with each line a state after one event:
Expected output, captured from a real run (scenario B of the lab demo, examples/frontend/golden/tool-call-registry.txt):
=== B. a write tool, approved
start input-streaming
delta "{\"orderId\":\"A-1001\",\"reason\":\"changed_mind\"}" input-streaming
input-complete approval-requested
approve input-available
output {"orderId":"A-1001","cancelled":true,"refundCents":1250} output-available
screen: component CancelReceipt {"orderId":"A-1001","cancelled":true,"refundCents":1250}
to the model: {"type":"tool_result","tool_use_id":"call_b","content":"{\"orderId\":\"A-1001\",\"cancelled\":true,\"refundCents\":1250}"}
The write stops at approval-requested. Nothing runs until the shopper presses Approve, and the screen shows a sentence built from validated input only ("Cancel order A-1001 (reason: changed_mind)"). The last line is what goes back to the model, in the documented tool_result shape. The amounts are lab data.
Showing the result: generative UI
The AI SDK defines generative UI as "connecting the results of a tool call to a React component": the tool returns data, and the data becomes the component's props. The decision "which component" is a lookup in your registry, not something the model chooses. In the lab, viewOf turns a part into one of four views, and a thin React component draws it.
| State | View | What the shopper sees |
|---|---|---|
input-streaming, input-available |
progress | A short status line |
approval-requested |
confirm | A sentence and two buttons |
output-available |
component | The order card or the receipt |
output-error, output-denied |
notice | A plain message, and whether the action may have run |
Figure 3. Approving a write
How to read this: two checks, one on each side of the tool, and a human decision between them. The model hears about the outcome only through the final tool_result.
The MCP specification says there "SHOULD always be a human in the loop with the ability to deny tool invocations", that applications should make clear which tools are exposed, show a clear indicator when a tool is invoked, and present confirmation prompts. The AI SDK's tool approval "lets you require user confirmation before a server-side tool runs". Which tools need approval is a product decision. The lab uses a simple rule: every write tool asks, every read tool does not.
Draw model text as text
The fields of a result are strings that may have started life in a webpage or an email. React's documentation says that with dangerouslySetInnerHTML, if the HTML "isn't trusted... you risk introducing an XSS vulnerability", and to use it "only with trusted and sanitized data". The lab's components render every field as a text child, and a test passes <b>x</b> as an order id: the shopper sees that string, and no b element exists. Anthropic's documentation also warns that tool results often carry content from outside your control that may try to redirect the model (indirect prompt injection); that belongs to Prompt Injection and Output Safety in the UI, named here as plain text.
When the call is wrong
Illustration 3: a failure, from the lab
Scenario G: the shopper approved a cancellation, the backend replied, but the reply is missing a required field.
Expected output, captured from a real run (scenario G of the lab demo):
=== G. approved, then the result does not match its schema
start input-streaming
delta "{\"orderId\":\"A-1001\",\"reason\":\"arrives_late\"}" input-streaming
input-complete approval-requested
approve input-available
output {"orderId":"A-1001"} output-error
screen: notice(error, mayHaveRun=true) "The action may have gone through, but its result could not be shown. Check before trying again."
to the model: {"type":"tool_result","tool_use_id":"call_g","content":"invalid output: cancelled: required","is_error":true}
The state is output-error, but the message differs from the one for an unknown tool or bad JSON: here the write may have happened, so telling the shopper "nothing was changed" would be a lie. The lab's viewOf sets mayHaveRun only for a write tool whose call failed or whose output was invalid. The other failure scenarios in the run (unknown tool, input cut off, wrong shape) end in output-error with mayHaveRun=false, because no tool ran.
On the wire, Anthropic's page says to send is_error: true when a tool fails or a call is invalid, and warns that Claude "might then call the tool again with a new tool_use block, so limit how many retries your loop allows". Write error text that tells the model what to fix ("invalid input: orderId: expected string, got number"), not just "failed". The AI SDK's page adds a caution for the other direction: by default the client receives the same error text as the model, so decide what the shopper may see.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Registry with schemas for every tool | Safe, testable, predictable UI | A schema and a component per tool |
| Provider strict mode only | Less code | No check on outputs or business ranges |
| Approval for every write | Human stays in control | Friction; users may click through |
| Model picks the component | Flexible | Anything the model names could be rendered |
| Unknown tool becomes an error part | The screen never breaks | The model must be told, and retries limited |
Build it
The lab is examples/frontend/labs/tool-call-registry. Core: src/registry.ts (about 280 lines, pure TypeScript). React: src/components.tsx (thin). The demo prints seven scenarios.
cd examples/frontend/labs/tool-call-registry
pnpm test # 31 tests: 23 on the core, 8 in jsdom
pnpm typecheck
node src/demo.ts # the trace quoted above
Verified. The 31 tests passed with Node 26.13.1 and Vitest 5.1.0, and the trace above is a verbatim excerpt of the captured golden file. Tests cover validation, the Map lookup, every transition, the approve and deny paths, unknown tools, truncated JSON, invalid output after approval, markup shown as text, and a missing component. jsdom is a JavaScript model of the DOM, not a browser: no layout, focus movement or screen-reader announcement was observed, and no real model or provider SDK was used.
In practice: the order assistant
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The marketplace ships a chat assistant that can look up and cancel orders. The chat component parses the model's reply, calls the API directly when it sees a tool name, and prints the JSON it gets back.
Starting architecture
Figure 4. Parse, call, print
How to read this: the warning box does three jobs with no check between them, so a mistaken or hostile call reaches the API directly and raw output reaches the screen.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Registry plus state machine | Every call checked, every state drawn | A schema and component per tool | Schemas drift from the API |
| Registry plus approval for writes | Human decides on changes | A confirm step | Click-through fatigue |
The decision
| Field | Decision record |
|---|---|
| Context | Free-form calls and raw output; a write can run without the shopper deciding. |
| Decision | A registry with input and output schemas; a tool-part state machine; approval for every write tool; components looked up by key; model text drawn as text. |
| Consequences, good | Bad calls become notices; writes need a click; each state is a unit test. |
| Consequences, bad | Each tool needs a schema and a component; schema drift now fails visibly. |
| Revisit when | Tools multiply, calls run in parallel, or approval fatigue shows up in the data. |
Rollout and verification
- Register read tools first and ship the card for each.
- Add the write tool behind approval, and test the deny path before the approve path.
- Force each failure by hand: an unknown tool, cut-off JSON, a wrong enum value, a missing output field.
- Check with a keyboard that Approve and Deny are reachable.
The 2 a.m. failure
The orders API adds a required field to its cancel response. Receipts stop rendering and shoppers see "The action may have gone through". Support reports cancellations that did happen.
First three checks: (1) look at the invalid-output error text for the missing field name; (2) compare the output schema with the API's current response; (3) confirm the cancellation state through a read tool. Mitigation: update the schema and roll out; do not retry the write. Follow-up: a contract test between the output schema and the API, as in the contract-testing lesson linked below.
Architect's notes
- Treat the registry as an allow-list. The model can ask for anything; the application renders and runs only what it registered.
- Validate both sides of the tool. Strict mode helps with input; only you know what your API returns.
- Say what may have run. A failed write and a failed read need different words.
- Keep the machine pure. The lab's React components make no decisions, so 23 of the 31 tests need no DOM.
Common mistakes
- Looking tools up in a plain object, so
constructorfinds something. - Parsing partial JSON while the stream is still arriving.
- Letting the model choose the component instead of the registry.
- Telling the shopper "nothing changed" after a write that may have run.
- Rendering model text as HTML.
- Retrying without a limit when errors go back to the model.
Key takeaways
- A tool call is a name plus JSON arguments; your application runs the tool and answers with a result.
- The registry is an allow-list with schemas for input and output, an effect and a component key.
- Model each call as a state machine and draw the UI as a pure function of its state.
- Writes wait for a human; reads need not.
- Validate output as well as input, and tell the model what went wrong with
is_error. - Strict mode and your own validation do different jobs.
Practice exercises
Exercise 1: Starter (30 min). Predict what scenario D prints for to the model, then run the demo and check.
Exercise 2: Intermediate (2 hours). Add a search_products read tool with an output that includes a list. Extend the schema language with arrays and add tests for a list with a wrong element.
Exercise 3: Advanced (half day). Add two parallel tool parts in one assistant message, one approved and one denied, and test that each gets its own tool_result.
Related reading
In this course:
- Request Cancellation, Retries and Timeouts: bounding the work a tool call starts.
- Error, Loading and Empty States: the same state-first thinking for remote data.
- Accessible Forms and Dynamic Content: status messages and focus when content appears.
- Contract Testing for Front Ends: catching schema drift before users do.
- XSS Defenses: why model text is drawn as text.
Planned in this module, named as plain text: Chat Interface State and Message Model, Streaming LLM Responses in the Browser, Prompt Injection and Output Safety in the UI.
Official documentation
- Anthropic: Tool use overview, Handle tool calls and Strict tool use: the round trip,
tool_result,is_error, schema conformance. - OpenAI: Function calling: the same flow under other names, and strict mode.
- AI SDK: Generative user interfaces and Chatbot tool usage: tool parts, their states, approval.
- Model Context Protocol: Tools: definitions, error mechanisms, human in the loop.
- React: Common components, dangerouslySetInnerHTML: why untrusted markup is not inserted.