Overview
Let AI agents and WebMCP browsers read and drive your Bits UI components directly through component state.
Most browser agents scrape the DOM or click pixel coordinates. That breaks the moment you move a button, wrap a select in a portal, or hide settings behind a closed tab.
bits-ui/experimental/agent skips the DOM guessing. Every interactive Bits UI component already owns its state, accessible label, options, and disabled state. When you create an agent bridge, your app exposes those live controls through three small tools: snapshot, act, and query.
Experimental
Exported from bits-ui/experimental/agent while the API and WebMCP spec settle. Expect minor breaking changes before it moves to a stable subpath.
Why three tools instead of one per widget
Registering a separate tool for every input, switch, and dropdown on a page floods the model's tool list and breaks every time the DOM updates. bits-ui/experimental/agent keeps the tool surface fixed at three calls regardless of page size:
snapshot()returns the visible interactive controls in document order, with stable session refs (c1,c2), labels, current values, and callable actions.act({ steps })runs a batch of steps in order. A model can fill a form, switch a tab, select an option by its visible label, assert the result, and submit in a single turn.query(options)filters large pages by text or kind, paginates long option lists withwithin, or peeks inside closedTabs,Collapsible, andAccordionpanels withclosed: truebefore restoring the UI.
Tree-shaken bridge
The bridge lives in a dedicated "bits-ui/experimental/agent" subpath export:
- If your app never imports
bits-ui/experimental/agent, the scanner, action runner, and WebMCP glue are tree-shaken out completely. - Components register through a lightweight
WeakRefhook that no-ops during SSR and installs no DOM observers or event listeners untilcreateAgent()runs. - Standard HTML
<input>,<textarea>,<select>,<button>, and<a>elements are picked up automatically alongside Bits UI primitives (includeNative: trueby default).
Connect to WebMCP
In browsers that implement WebMCP (navigator.modelContext or document.modelContext), call registerTools() inside a client $effect. Returns a no-op cleanup in browsers without WebMCP.
<script lang="ts">
import { AlertDialog } from "bits-ui";
import { createAgent, registerTools, type AgentAction } from "bits-ui/experimental/agent";
let { children } = $props();
let pending = $state<{ step: AgentAction; resolve: (ok: boolean) => void } | null>(null);
function requestApproval(step: AgentAction, { signal }: { signal: AbortSignal }) {
// Auto-approve normal controls; pause for human approval on data-agent-confirm
if (!step.confirm) return true;
return new Promise<boolean>((resolve) => {
const onAbort = () => {
pending = null;
resolve(false);
};
signal.addEventListener("abort", onAbort, { once: true });
pending = {
step,
resolve: (approved) => {
signal.removeEventListener("abort", onAbort);
pending = null;
resolve(approved);
},
};
});
}
$effect(() => {
const agent = createAgent();
const unregister = registerTools(agent, { allow: requestApproval });
return () => unregister();
});
</script>
{@render children()}
<!-- Mark your approval UI data-agent-hidden so the agent cannot see or click Approve -->
<AlertDialog.Root open={pending !== null}>
<AlertDialog.Portal>
<AlertDialog.Overlay />
<AlertDialog.Content data-agent-hidden>
<AlertDialog.Title>Approve agent action?</AlertDialog.Title>
<AlertDialog.Description>
{pending?.step.confirm}
</AlertDialog.Description>
<div>
<AlertDialog.Cancel onclick={() => pending?.resolve(false)}>Deny</AlertDialog.Cancel>
<AlertDialog.Action onclick={() => pending?.resolve(true)}>Approve</AlertDialog.Action>
</div>
</AlertDialog.Content>
</AlertDialog.Portal>
</AlertDialog.Root>
See Safety & Attributes for how allow, data-agent-confirm, and secret redaction protect your app from untrusted prompts.
Use with your own LLM tool loop
Without WebMCP, pass agent.tools (JSON Schema definitions for snapshot, query, and act) directly to any LLM tool loop:
import { createAgent } from "bits-ui/experimental/agent";
const agent = createAgent({
allow: (step) => !step.confirm,
});
// Send `agent.tools` to your model, then dispatch tool calls:
async function handleToolCall(name: string, args: unknown) {
if (name === "snapshot") return agent.snapshot();
if (name === "query") return agent.query(args as Parameters<typeof agent.query>[0]);
if (name === "act") return agent.act(args as Parameters<typeof agent.act>[0]);
}
How targeting works
Steps in act() don't need brittle CSS selectors. Pass whichever identifier is clearest:
await agent.act({
steps: [
// 1. Direct label (resolves visible option label "EU Central" -> value "eu-central")
{ ref: "Deployment region", action: "setValue", args: ["EU Central"] },
// 2. Section path (automatically opens inactive "Billing" tab + nested collapsibles)
{ ref: "Billing > Tax details > Tax ID", action: "setValue", args: ["EU-123"] },
// 3. Table row context (from data-agent-row on <tr>)
{ ref: "Jane Doe", action: "press", args: ["Promote to Admin"] },
// 4. Built-in assertion before submitting
{ ref: "Deployment region", action: "expect", args: ["eu-central"] },
// 5. Session ref from snapshot()
{ ref: "c12", action: "press" },
],
});
Invalid step shapes fail the batch before step 1 runs. Ambiguous labels fail with the matching Section > Label (ref) candidates.
Try the full workbench
Open the WebMCP Workbench to test playbooks against dialogs, menus, nested accordions, secret fields, and a live WebMCP simulator.
Inspect and test your agent surface
In DevTools
Expose the bridge on window in development so you can run snapshot() and act() directly from the browser console:
$effect(() => {
const agent = createAgent();
if (import.meta.env.DEV) {
(window as Record<string, unknown>).__agent = agent;
}
});
__agent.snapshot();
await __agent.act({
steps: [{ ref: "Deployment region", action: "setValue", args: ["EU Central"] }],
});
In Vitest or Playwright
Scope createAgent({ root: container }) to a rendered component and assert that labels are clear, secrets serialize as "[redacted]", and risky controls fail closed:
const agent = createAgent({
root: container,
allow: (step) => !step.confirm,
});
// Verify destructive action is gated
const res = await agent.act({
steps: [{ ref: "Delete project", action: "press" }],
});
expect(res.ok).toBe(false);
Supported components
All 24 components below register automatically and have a dedicated Agent Support section on their docs page:
- Form inputs: Input, Textarea, PIN Input, Checkbox, Switch, Slider, Rating Group
- Selection: Select, Combobox, Radio Group, Toggle, Toggle Group, Command
- Overlays & menus: Dialog, Alert Dialog, Popover, Dropdown Menu, Context Menu, Menubar
- Disclosures & navigation: Tabs, Accordion, Collapsible, Pagination, Button
Building a custom widget? Wire it into the same registry with registerAgentControl().
Prior art & shared conventions
The agent bridge design in bits-ui/experimental/agent is directly inspired by Vercel's UI SDK (vercel-labs/ui), which pioneered the three-tool (snapshot, act, query) model, registerTools(), and the data-agent-* attribute conventions for WebMCP.
We deliberately adopted the same tool names, permission semantics, and HTML attributes rather than inventing a separate Bits UI dialect. Shared conventions make it easier for agents to work across libraries, reduce lock-in for app authors, and let Bits UI and UI SDK coexist cleanly on the same page. See Using with UI SDK for colocation patterns.