API Reference
Complete API reference for bits-ui/experimental/agent, composeAgents, WebMCP registration, and custom components.
Everything is exported from "bits-ui/experimental/agent":
import {
createAgent,
composeAgents,
registerTools,
isWebMCPSupported,
agentTools,
registerAgentControl,
} from "bits-ui/experimental/agent";
createAgent(options?)
Creates an agent bridge scoped to the document or a specific subtree.
const agent = createAgent({
root: () => containerEl,
includeNative: true,
snapshotLimit: 100,
allow: (step, { signal }) => !step.confirm,
timeout: 300_000,
});
| Property | Details |
|---|---|
root | |
includeNative | |
snapshotLimit | |
allow | |
timeout | |
reveal | |
attributes | |
transformSnapshot | |
onAction |
Customization recipes
const agent = createAgent({
// Use your own data-* attribute names instead of data-agent-*
attributes: {
confirm: "data-ai-confirm",
hidden: "data-ai-hidden",
},
// Disable automatic opening of closed Tabs/Accordions/Collapsibles during act()
reveal: false,
// Audit log or visually highlight each control as the agent drives it
onAction: ({ phase, action, element }) => {
if (phase === "before") element?.setAttribute("data-agent-active", "");
else element?.removeAttribute("data-agent-active");
console.debug(`[agent:${phase}]`, action.ref, action.action);
},
});
// Expose a read-only snapshot tool (no `allow` callback required) with custom naming
const unregister = registerTools(agent, {
tools: ["snapshot"],
names: { snapshot: "read_workspace_ui" },
descriptions: { snapshot: "List visible controls in the current workspace." },
});
agent.snapshot()
Returns AgentComponent[] in document order for all currently visible, non-hidden controls:
interface AgentComponent {
ref: string; // session ref ("c1", "c2", ...)
component: string; // "input", "select", "dialog", "switch", ...
label?: string; // accessible name
section?: string; // enclosing landmark or data-agent-section path
row?: string; // enclosing data-agent-row text
disabled?: boolean;
secret?: boolean;
reveals?: boolean;
confirm?: string; // message from data-agent-confirm
actions: string[]; // currently callable actions (empty when disabled)
items?: AgentItem[]; // inline option list when <= 10 items
more?: number; // count of omitted items when > 10
buttons?: string[]; // clickable labels inside an open overlay
text?: string[]; // title and description lines inside an open dialog
[state: string]: unknown; // value, checked, pressed, open, query, search, min, max, step, page, pageCount
}
agent.act(input, options?)
Executes an ordered batch of steps in a serialized turn queue so concurrent calls never interleave:
const result = await agent.act(
{
steps: [
{ ref: "Project name", action: "setValue", args: ["Atlas"] },
{ ref: "Deployment region", action: "setValue", args: ["EU Central"] },
{ ref: "Project name", action: "expect", args: ["Atlas"] },
],
},
{ signal: abortController.signal }
);
Target resolution order (ref)
- Exact ref:
"c4" - Section path:
"Billing > Auto renew"or"Billing > Tax details > Tax ID" - Exact label or row match:
"Project name","Jane Doe" - Component kind fallback:
"dialog"when only one dialog is present - Whole-word match: case- and accent-folded whole-word match across accessible names (open dialogs match both their trigger text and
Dialog.Title) - Closed container reveal: if nothing visible matches, peeks inside non-confirmed
Tabs,Collapsible, andAccordioncontainers up to 3 levels deep
Ambiguous matches fail with the matching Section > Label (ref) candidates rather than guessing. Every step's shape (ref, action, optional args array) is validated before step 1 runs.
Built-in expect action
Every non-secret component supports { ref, action: "expect", args: [expected] }. It compares expected against the component's primary state (value, checked, pressed, open, or page) and halts the batch on mismatch. Calling expect on a secret component is always refused.
Return value (AgentActResult)
interface AgentActResult {
ok: boolean;
results: AgentStepResult[];
error?: string;
state: Record<string, unknown>; // compact post-batch state summary (secrets redacted)
}
agent.query(input?)
Searches or inspects components without leaving visible UI state mutated:
| Property | Details |
|---|---|
text | |
kind | |
within | |
closed | |
from |
When within targets a closed Select rendered without the items prop, result.within.note explains that options only mount while the dropdown is open.
composeAgents(agents, options?)
Merges multiple bridges (bits-ui/experimental/agent, @ui-sdk/*, or custom { snapshot, act, query? } adapters) into one BitsAgent with namespaced refs (bits:c1, ui:c1), cross-bridge act() routing, and a single registerTools() surface. See Using with UI SDK.
const agent = composeAgents(
{
bits: createAgent({ includeNative: false }),
ui: createUiSdkAgent(),
},
{
allow: (step, { signal }) => !step.confirm,
timeout: 300_000,
}
);
| Property | Details |
|---|---|
allow | |
timeout |
WebMCP Registration
registerTools(agent, options)
Registers snapshot, act, and query with navigator.modelContext.registerTool (or document.modelContext.registerTool / options.modelContext) and returns an unregister cleanup function backed by an internal AbortController.
const unregister = registerTools(agent, {
allow: (step, { signal }) => confirmWithUser(step, signal),
prefix: "bits_",
tools: ["snapshot", "query", "act"],
});
| Property | Details |
|---|---|
allow | |
prefix | |
tools | |
names | |
descriptions | |
modelContext | |
document |
- Throws if
actorqueryis included andoptions.allowis missing. Read-onlytools: ["snapshot"]does not requireallow. - Returns a no-op cleanup when no
modelContextis available.
isWebMCPSupported(doc?)
Returns true when navigator.modelContext.registerTool or document.modelContext.registerTool is present.
agentTools
Read-only JSON Schema definitions for snapshot, query, and act with WebMCP annotations:
| Property | Details |
|---|---|
snapshot | |
query | |
act |
Why query is not marked readOnlyHint: true
query({ closed: true }) temporarily opens closed Tabs, Collapsible, or Accordion panels to discover hidden controls before restoring the previous state, so it is annotated with readOnlyHint: false.
Custom Components (registerAgentControl)
Register custom Svelte 5 components with the same bridge using registerAgentControl(target, descriptor). Inside a Svelte component or $effect, unregistration runs automatically on destroy (and the returned cleanup function can also be called manually).
<script lang="ts">
import { registerAgentControl } from "bits-ui/experimental/agent";
let { value = $bindable("#3b82f6"), disabled = false } = $props();
let rootEl = $state<HTMLDivElement | null>(null);
const owner = {};
registerAgentControl(owner, {
component: "color-picker",
getElements: () => [rootEl],
isDisabled: () => disabled,
getState: () => ({ value }),
actions: {
setValue: (next) => {
if (disabled) return;
const hex = String(next ?? "").trim();
if (!/^#[0-9a-f]{6}$/i.test(hex)) {
throw new Error(`Expected 6-digit hex color, got "${hex}".`);
}
value = hex;
},
},
});
</script>
<div bind:this={rootEl} role="group" aria-label="Brand color">
<!-- custom color picker UI -->
</div>
BitAgentDescriptor
| Property | Details |
|---|---|
component | |
getElements | |
getState | |
actions | |
isDisabled | |
secret | |
closed | |
getItems | |
pressTarget | |
getButtons | |
getText | |
actionNames | |
isShown | |
reveals | |
reveal |