Getting started

Actions

Forms

Layout

Navigation

Overlays

Feedback

Data display

Controllers

Helpers

Recipes

Agent tools

A cart that the person and a browser agent both add to, through the same method, with the agent's tool present exactly while the cart is on the page.

Experimental. WebMCP is an origin trial and may change, and the helpers here follow it.

Goal

A page that lets an agent do what a person does: add a product to the cart, close a dialog, filter a list. The agent calls a tool the page registered, instead of finding and clicking the DOM. The tool belongs to the component that owns the state, so it appears when the component connects and goes when it is removed, and the form and the tool call the same method.

Primitives

  • @agentTool turns a method into a tool. The method stays an ordinary method, so the form submit calls addItem with a typed argument and the agent calls the same method. The schema guards only the agent's path, since the form passes a typed value straight in, so the field carries required.
  • registerAgentTool, from @ecopages/radiant/helpers/register-agent-tool, registers a tool without a host and returns the function that removes it. The plain form uses it.
  • createAgentTool(host, config), from @ecopages/radiant/helpers/create-agent-tool, ties a tool to an element's connect and disconnect. The decorator is built from it.
  • Static JSON Schema describes the input. inputSchema is a plain object the browser shows the agent, so no schema library loads on the page. Here it is addItemSchema in agent-tools.data.ts, kept in step with a Zod schema by a test. An app with a build step writes it with z.toJSONSchema, and validates on the server the tool calls.

Left to the recipe: the schema, what the method does, and what it returns. The tool name is unique on the page, so a component that can appear twice builds the name from an instance value such as its id. Type the host parameter, because the decorator is written before TypeScript knows the class:

@agentTool({
	name: (host: AgentToolsElement) => `add_to_cart_${host.id}`,
	description: 'Adds a product to the cart by its SKU.',
})
addItem(item: { sku: string }) {}

Example

Add a product with the form, or call the tool from the inspector below the example, which stands in for an agent. The inspector lists the page's tools and calls one with the JSON in its box. A call that fails parse is rejected before the method runs, so the cart does not change and the agent receives an error. This page uses a small stand-in for document.modelContext where the browser has none, and reads the tools back from the browser's WebMCP testing surface where it has its own and offers one; the recipe code never touches either.

Pick an authoring pattern below; they behave the same, and the one you pick is remembered on the other recipes.

The same behavior as a RadiantElement. The markup is authored inside the element, and @agentTool on addItem registers the tool when the element connects and removes it when the element disconnects.

0 in cart

    import { RadiantElement, customElement, onEvent, query } from '@ecopages/radiant';
    import { agentTool } from '@ecopages/radiant/decorators/agent-tool';
    import { addItemSchema, parseAddItem, type AddItem } from './agent-tools.data';
    
    @customElement('agent-tools-element')
    export class AgentToolsElement extends RadiantElement {
    	@query('input') private input!: HTMLInputElement;
    	@query('ul') private list!: HTMLElement;
    	@query('[data-status]') private status!: HTMLElement;
    
    	@onEvent({ selector: 'form', type: 'submit' })
    	submit(event: SubmitEvent): void {
    		event.preventDefault();
    		this.addItem({ sku: this.input.value });
    	}
    
    	@agentTool({
    		name: 'add_to_cart',
    		description: 'Adds a product to the cart by its SKU.',
    		annotations: { consequentialHint: false },
    		inputSchema: addItemSchema,
    		parse: parseAddItem,
    	})
    	addItem({ sku }: AddItem) {
    		const item = document.createElement('li');
    		item.textContent = sku;
    		this.list.append(item);
    		const count = this.list.children.length;
    		this.status.textContent = `${count} in cart`;
    		return { count };
    	}
    }

    Remove the element and the tool is gone, move it and the tool is registered again, and a client-side navigation that adds a copy starts it without any call. addItemSchema is the inputSchema the agent reads, parseAddItem runs on the agent's input before addItem, and AddItem types the method's argument for the form too. The recipe has no server, so a small hand-written parse does the checking in the browser; with a server, the endpoint validates and parse goes.

      Styles

      The stylesheet is the agent-tools.css tab in the files above, and styles the element and the plain div alike, each as the one root its frame holds. The inspector is docs-only and is not part of the recipe.

      What to watch for

      • Unique names. A second registration with the same name is rejected by the browser, and Radiant reports it with the tool and the element. Two UIs that do the same thing use two names, or one owner registers the tool once.
      • Validate in code. inputSchema is advisory, so an agent can send anything. Check the input where the tool executes: on the server when there is one, or in parse when the browser must reject a call before the method runs. A method with neither receives the input as sent.
      • Return when the page is true. Update the UI before the method returns, and return a value that says what happened, because the agent reads it.
      • Embedded pages. A tool registered inside a cross-origin iframe needs allow="tools" on the frame.
      • Server-rendered elements. An element whose children come from its parent's view registers its tool only after it hydrates, and never when the parent does not render on the client.

      Keeping data safe

      A tool runs page code for an agent, and what it returns can leave the device. Radiant has no tool that reads the page, so a tool exposes only what you return from it. The full list is in the package README; the ones this recipe shows:

      • Say what it changes. The tool sets annotations: { consequentialHint: false }: adding to a cart is easy to undo. An action that is hard to undo sets consequentialHint: true, and one that changes nothing sets readOnlyHint: true. In development a tool with neither hint logs a warning.
      • Return the least. { count } is all the agent needs. Never return tokens, secrets or the contents of password, card or one-time-code fields, and set untrustedContentHint: true on output that carries text a user or another site wrote, because an agent may treat tool output as trusted.
      • Ask for the least. The schema asks for a SKU and nothing about the person.
      • Confirm in your own UI. The current WebMCP spec has no confirmation API. A consequential tool awaits the app's own dialog inside execute and closes it when the signal aborts.
      • Authorize on the server. The agent can skip the checks the UI does, so a real cart checks permission on the server and binds a consequential call to an id or version, such as a cart revision that the server rejects when it is out of date.
      • Keep it on this origin. Tools are visible only to the page's own origin. exposedTo lets other origins call them with arguments you cannot trust, and logs a warning in development.