Query and Mutation
The model writes a tool call once, as a line of OpenUI Lang. The browser makes the call, shows a default until the answer arrives, fetches again when an input changes, and runs writes when a button asks for them. None of that goes back to the model.
By the end of this lesson you can
- trace a tool from its
ToolSpec, through the prompt's## Available Toolssection, to aQuerytheRendererruns; - read the four arguments of
Queryand say when a query fetches, re-fetches, and keeps its last value; - follow a
Mutationthroughidle,loading,successanderror, and explain why a failure stops the rest of the action; - wire a
toolProvideras a function map or an MCP client, and predict what a missing tool or a missing provider does.
One tool, end to end
A Query is the model's way of saying "this part of the screen comes from a tool". The model never calls the tool itself. It learns the tool exists from the system prompt, writes the call into the program, and the Renderer in the browser runs it after the stream ends. Step through the whole loop.
From ToolSpec to live data
- Your server describes each tool as a ToolSpec: a name, a description, and JSON Schemas for input and output.
- You pass the specs to
library.prompt({ tools }). They become the## Available Toolssection, plus the Query, Mutation and Data Workflow sections that teach the model how to use them. - The model writes
w = Query("get_weather", {city: $city}, …). That is plain text in the stream. The model cannot call the tool while writing, and does not need to. - The stream ends. The
Rendererevaluates the arguments (here$cityis"Pune") and starts the call. Until the answer arrives, everything that readswshows the Query's default value. - The Renderer calls its toolProvider, which forwards the call to your API. That code runs in the browser, so it calls your server, which keeps keys and rate limits out of the page.
- Your API validates the arguments, runs the tool and returns JSON. The result replaces the default, and every expression that reads
wre-evaluates. The model is not involved.
Generation and execution are separate
The model pays for one line of text per tool call. After that, every fetch, re-fetch and write happens between the browser and your API at network speed. Ask the model again only when the program must change, not when the data does.
The four arguments of Query
$city = "Pune"
w = Query("get_weather", {city: $city}, {city: "", current: {temp: 0, sky: ""}})
card = Card([CardHeader(w.city), TextContent("" + w.current.temp + "°")])
| Argument | What it is | What the runtime does with it |
|---|---|---|
"get_weather" | The tool name, exactly as in ## Available Tools. | Looks it up in the toolProvider. With a function map, a missing name is a tool-not-found error. With an MCP client, an unknown tool comes back as mcp-error or tool-error. With no toolProvider, nothing runs and the defaults stay, with no error. |
{city: $city} | The arguments object. It may read $variables. | The parser records deps: ["$city"]. When $city changes, the arguments change and the Query fetches again. |
{city: "", …} | The default data, in the shape of the tool's output. | Shown immediately, before the first result arrives, so the layout renders with zeros instead of breaking. |
30 (optional) | A refresh interval in seconds. | Fetches again on a timer. The simulator on this site does not implement it. |
Two rules from the generated prompt keep this working. A query result is a plain identifier (w = Query(…), never $w = Query(…)), and its fields are read with dots: w.current.temp, or todos.rows.title to pluck title from every row.
OpenUI rule
The third argument is the default value, and the UI renders it until the tool responds. A Mutation does not run when the page loads. It runs only when an action runs it with @Run, and if it fails, the actions after it do not run.
Myth: the query fires as soon as its line streams in
The real Renderer does not evaluate any Query or register any Mutation while isStreaming is true. Queries wait for the whole program, so a half-written argument such as "Pu" never reaches your API. During the stream, the UI shows defaults.
Four flows, message by message
Pick a scenario and step through it. The lanes are the user, the model, the Renderer in the browser, and your API. The bottom panel shows what the Renderer holds for each query and mutation at that moment.
Things to look for
- The model appears only in the first scenario. Re-fetches and writes never involve it.
- After a
$citychange, the old result stays on screen while the new one loads. The defaults do not flash back. - After a successful write, the list updates only because the action says
@Run(todos). Nothing re-fetches a query on its own after a mutation. - After a failed write,
@Run(todos)and@Reset($title)are skipped, so the user's typed title survives for a retry.
A Mutation's status
A Mutation is registered when the stream ends and then waits. Its value is not data but a status object, {status, data?, error?}, that the program can read like any other reference.
idle, loading, success or error
- After the stream ends,
addResult = Mutation("add_todo", {title: $title})is registered with statusidle. Nothing is sent on page load. - A click runs
@Run(addResult). The arguments are evaluated now, so they carry the current$title. Status becomesloading, and another@Runof the same mutation is rejected until it settles, which stops double submits. - The tool returns. Status becomes
successwith the result indata, and the action moves on to its next step. - The tool throws. Status becomes
errorwith the message inerror, the rest of the action is skipped, andonErrorreceives atool-error(tool-not-foundfor a name the function map lacks,mcp-errorfor an MCP failure).
The model shows feedback by reading the status, assigning each check to a statement and placing it in the layout:
addResult = Mutation("add_todo", {title: $title})
addBtn = Button("Add", Action([@Run(addResult), @Run(todos), @Reset($title)]), "primary")
addError = addResult.status == "error" ? Callout("error", "Could not add", addResult.error) : null
@Run on a Query re-fetches it and never fails the action. That is why the usual write pattern is "mutate, then re-fetch": @Run(addResult), then @Run(todos).
What the model sees: Available Tools
The ## Available Tools section is the only place the model learns which tools exist. This is the real section that lab 02 prints for one get_weather spec:
## Available Tools
Use these with Query() for read operations or Mutation() for write operations. The LLM decides which is appropriate based on the tool's purpose.
- get_weather(city: string, units?: "celsius" | "fahrenheit") → {city: string, current: {temp: number, sky: string}}
Current weather for a city
### Default values for Query results
Use these shapes as minimal Query defaults:
- get_weather: `{"city":"","current":{"temp":0,"sky":""}}`
Each line is built from four fields of the spec: name, the input schema's properties (a ? marks the ones not in required), the output schema, and description. The defaults line is derived from the output schema, which is where the third argument of a well-written Query comes from.
The annotations field (readOnlyHint, destructiveHint) is not printed, so nothing in the section says which tools write. The model decides from the description. The registry in this repo makes that unmissable by prefixing every write tool's description:
Run it
cd openui && node 02-library/prompt.mjs prints the prompt with and without tools: about 706 tokens without, about 3,124 with, because tools switch on the Built-in Functions, Query, Mutation, Interactive Filters, Forms and Data Workflow sections as well.
toolProvider: two shapes
The Renderer takes the provider as a prop and accepts two shapes. It tells them apart by looking for a callTool function.
With an MCP client, the Renderer calls callTool({name, arguments}) and unwraps the result itself: structuredContent first, otherwise the text content parsed as JSON, and isError: true becomes an mcp-error. The provider is passed to the Renderer like this:
| What the Renderer gets | What a Query does | What a Mutation does |
|---|---|---|
| A map that has the tool | Fetches; a throw becomes tool-error | Runs on @Run; a throw becomes tool-error and status error |
| A map without the tool | tool-not-found, with a hint listing the available tools | tool-not-found, status error |
null or no prop | Never fetches: keeps its defaults, reports nothing | Never runs: stays idle, and the action stops at that step without an error |
Myth: no toolProvider means a loud error
A missing provider is silent. The query manager simply skips every fetch, so the screen shows defaults (zeros and empty tables) and buttons that run a mutation do nothing. If live data looks suspiciously empty and onError is quiet, check that the Renderer got a toolProvider at all.
These calls come from the browser
Any user can open the console and call your tool endpoints with any arguments. Validate input and output on the server, authorize every call, and keep secrets and third-party keys there, as runTool in the registry does.
A todo list against fake tools
This is a recorded model response: one Query and three Mutations. Let it stream, then add, toggle and delete todos. The inspector shows every tool call the Renderer made and every error onError would receive. Use the Tools menu to make a tool fail, or take the provider away.
Simulated: no model is called and the tools are in-page functions with a short delay. The parser and runtime are a teaching subset of @openuidev/react-lang 1.0.1; the simulator does not implement refreshInterval or share a cache between Renderers, and its toolProvider is a function map only (no MCP client callTool).
Things to look for
- The Tool calls tab stays empty while the stream plays, then
list_todosappears once it ends. - Adding a todo makes two calls,
add_todothenlist_todos. Toggling makes the same pair withtoggle_todo. - The header line
"" + todos.open + " open of " + todos.totalupdates from the re-fetched data, not from anything the model wrote.
Break it
Predict each outcome before you try it.
- Choose "add_todo fails", type a title and click Add.
What should happen
One call,
add_todo, marked as an error. Nolist_todoscall follows and the title stays in the field, because the failed@Run(addResult)stopped the action. The red "Could not add" callout appears, sinceaddResult.statusis now"error", and the Errors tab showstool-error:Mutation "add_todo" failed: Database is read-only. Switch back to "All tools succeed" and click Add again: the same title goes through. - Choose "Every tool fails", then press Restart on the player.
What should happen
The table stays empty and the header reads "0 open of 0": those are the Query's defaults, which stay on screen when the first fetch fails. The Errors tab shows a
tool-errorwith sourcequery. The program is fine; only the data source failed, which is why a real app should offer a retry instead of asking the model to rewrite the UI. - Choose "toolProvider = null" and click Add after the stream ends.
What should happen
Nothing at all. No tool calls, no errors, an empty table, and a button that does nothing. Without a provider, queries keep their defaults and mutations never leave
idle. This is the silent failure from the myth above.
Quick check
The model wrote w = Query("get_weather", {city: $city}, {temp: 0}), and the user changes the city input from Pune to Tokyo. What happens?
$city is a dependency of the Query, recorded at parse time. A new value means new arguments, which means a new fetch through the toolProvider. While it loads, the last settled result stays visible. The model is not involved.A button runs Action([@Run(save), @Run(list), @Reset($title)]) and the save tool throws. What happens?
@Run on a mutation halts the remaining steps. Nothing re-fetches a query by itself after a write; only an explicit @Run(list) does, and here it never runs.Your weather card shows 0° forever and onError never fires. What is the most likely cause?
tool-not-found error. A missing provider is silent: the query manager skips every fetch and the defaults stay on screen.Recap
- The model learns tools only from
## Available Tools, built from eachToolSpec's name, schemas and description. Annotations are not printed, so mark writes in the description. Query(tool, args, defaults, refreshInterval?): defaults render first, the fetch starts after the stream ends, and a$variablein the args re-fetches on change with the last result kept on screen.Mutation(tool, args)runs only on@Run, moves fromidletoloadingtosuccessorerror, and a failure halts the rest of the action.toolProvideris a function map or an MCP client. A missing tool istool-not-found; a missing provider is silent.