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 Tools section, to a Query the Renderer runs;
  • read the four arguments of Query and say when a query fetches, re-fetches, and keeps its last value;
  • follow a Mutation through idle, loading, success and error, and explain why a failure stops the rest of the action;
  • wire a toolProvider as 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

ToolSpec registry get_weather(city, units?) System prompt ## Available Tools Model writes text, calls nothing w = Query( "get_weather", {city: $city}, …) Renderer stream ended: run queries toolProvider function map or MCP client Your API validate, run, validate result replaces the defaults; every prop that reads w re-evaluates no model call, no new turn
  1. Your server describes each tool as a ToolSpec: a name, a description, and JSON Schemas for input and output.
  2. You pass the specs to library.prompt({ tools }). They become the ## Available Tools section, plus the Query, Mutation and Data Workflow sections that teach the model how to use them.
  3. 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.
  4. The stream ends. The Renderer evaluates the arguments (here $city is "Pune") and starts the call. Until the answer arrives, everything that reads w shows the Query's default value.
  5. 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.
  6. Your API validates the arguments, runs the tool and returns JSON. The result replaces the default, and every expression that reads w re-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 + "°")])
ArgumentWhat it isWhat 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

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

idle nothing ran yet @Run loading a second click is ignored success data = result next steps run @Run(todos), @Reset error error = message plan halts onError: tool-error
  1. After the stream ends, addResult = Mutation("add_todo", {title: $title}) is registered with status idle. Nothing is sent on page load.
  2. A click runs @Run(addResult). The arguments are evaluated now, so they carry the current $title. Status becomes loading, and another @Run of the same mutation is rejected until it settles, which stops double submits.
  3. The tool returns. Status becomes success with the result in data, and the action moves on to its next step.
  4. The tool throws. Status becomes error with the message in error, the rest of the action is skipped, and onError receives a tool-error (tool-not-found for a name the function map lacks, mcp-error for 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 getsWhat a Query doesWhat a Mutation does
A map that has the toolFetches; a throw becomes tool-errorRuns on @Run; a throw becomes tool-error and status error
A map without the tooltool-not-found, with a hint listing the available toolstool-not-found, status error
null or no propNever fetches: keeps its defaults, reports nothingNever 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

Break it

Predict each outcome before you try it.

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?

  • The app sends the new city to the model, which writes a new program
  • The card resets to {temp: 0} until the user reloads
  • The Renderer calls get_weather with {city: "Tokyo"}, showing the Pune result until Tokyo arrives
$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?

  • All three steps run, and save.status is "error"
  • save.status is "error", list is not re-fetched, and $title keeps its value
  • list re-fetches automatically because a mutation ran
A failed @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?

  • The tool name is misspelled in the Query
  • The model forgot the third argument
  • The Renderer has no toolProvider
A misspelled name with a function map gives a loud tool-not-found error. A missing provider is silent: the query manager skips every fetch and the defaults stay on screen.

Recap