By
The Imperative API: Registering Tools from JavaScript
The imperative API is the core of WebMCP. Everything the declarative API does can be expressed with it, and it is what you will use for most real tools. This part builds the grocery store’s search_products, add_to_cart and get_cart tools.
The Shape of the API
Everything lives on document.modelContext, which is only available in secure contexts (HTTPS or localhost):
interface ModelContext extends EventTarget {
registerTool(tool: ModelContextTool, options?: { signal?: AbortSignal; exposedTo?: string[] }): Promise<void>
getTools(options?: { fromOrigins?: string[] }): Promise<RegisteredTool[]>
executeTool(tool: RegisteredTool, input?: object, options?: { signal?: AbortSignal }): Promise<string>
}
interface ModelContextTool {
name: string // 1–128 chars: A–Z a–z 0–9 _ - .
title?: string // human-readable label
description: string // what the agent reads to decide when to call it
inputSchema?: object // JSON Schema for the input
outputSchema?: object // JSON Schema for the result
annotations?: ToolAnnotations
execute(input: object, options: { signal: AbortSignal }): Promise<any>
}As a site, you mostly need registerTool(). getTools() and executeTool() are the consumer side — used by agents, and handy in tests (Part 4).
Your First Tool
await document.modelContext.registerTool({
name: 'search_products',
title: 'Search products',
description:
'Search the store catalogue by keyword. Returns up to 10 matching products ' +
'with their IDs, names, prices and stock status. Use the returned ID with add_to_cart.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'Search keywords, e.g. "oat milk"' },
maxPrice: { type: 'number', description: 'Optional upper price limit in EUR' },
},
required: ['query'],
},
annotations: { readOnlyHint: true },
async execute({ query, maxPrice }) {
const results = await api.searchProducts({ query, maxPrice, limit: 10 })
return results.map(({ id, name, price, inStock }) => ({ id, name, price, inStock }))
},
})A few things are worth noting.
The description is the interface. The agent never sees your code; it decides whether and how to call the tool purely from name, description and inputSchema. Say what the tool does, what it returns, and how it relates to other tools (“use the returned ID with add_to_cart”).
The schema is a hint, not a guarantee. Agents usually respect it, but execute can still receive missing fields, wrong types or out-of-range values. Validate inside execute as you would for any external input.
Return something compact. The result goes back to the model as text (objects are serialized). Return only what the agent needs to take its next step — IDs, names, prices, status — not entire API responses.
Writing Results and Errors
If execute throws or its promise rejects, the agent receives an error. Make error messages actionable, because the model reads them and decides what to do next:
async execute({ productId, quantity = 1 }) {
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 20) {
throw new Error('quantity must be an integer between 1 and 20')
}
const product = await api.getProduct(productId)
if (!product) {
throw new Error(`No product with ID "${productId}". Call search_products to find valid IDs.`)
}
if (!product.inStock) {
return { added: false, reason: 'out_of_stock', name: product.name }
}
const cart = await cartStore.add(product.id, quantity)
return { added: true, name: product.name, quantity, cartTotal: cart.total, itemCount: cart.count }
}Use a thrown error for “you called this wrong” and a normal result for “this worked, but the answer is no”. The out-of-stock case is a valid outcome, not a failure.
Annotations
Annotations tell the agent about a tool’s effects. All default to false.
| Annotation | Meaning | Example |
|---|---|---|
readOnlyHint |
Does not change any state | search_products, get_cart |
consequentialHint |
Has effects that matter and may be hard to undo | place_order, delete_account |
untrustedContentHint |
Output may include content the site does not control | Product reviews, user comments |
debugging |
Intended for development, not for normal agent use | dump_state |
An agent can use these to decide when to ask the user for confirmation, or to treat a tool’s output with more suspicion. They are hints the site declares about itself, so agents cannot rely on them blindly — but set them honestly; agents that trust your site will behave better.
Tool Lifetime and AbortSignal
There is no unregisterTool(). A tool stays registered until the page goes away or until the AbortSignal you passed at registration is aborted:
const controller = new AbortController()
await document.modelContext.registerTool(addToCartTool, { signal: controller.signal })
// Later, e.g. when the user logs out:
controller.abort()This is the same pattern as addEventListener(..., { signal }), and it pairs well with component lifecycles. One controller can own several tools, so you can drop a whole group at once.
Registering a second tool with a name that is already registered fails, so always clean up before registering again.
Cancellation inside execute
execute receives its own signal in the second argument. It is aborted if the agent or user cancels the call. Pass it to anything that supports cancellation:
async execute({ query }, { signal }) {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal })
return summarize(await res.json())
}Since Chrome 153, unregistering a tool no longer kills a call that is already running. If your tool must stop when it is unregistered, check the registration signal too.
Registering Tools by Page State
Tools should reflect what is possible now. A checkout tool on an empty cart, or a cancel_order tool for a logged-out user, invites the agent to make calls that can only fail.
Register and unregister as state changes:
let checkoutController = null
cartStore.subscribe(async (cart) => {
const shouldExist = cart.count > 0
if (shouldExist && !checkoutController) {
checkoutController = new AbortController()
await document.modelContext.registerTool(checkoutTool, { signal: checkoutController.signal })
} else if (!shouldExist && checkoutController) {
checkoutController.abort()
checkoutController = null
}
})Agents can listen for the toolchange event on document.modelContext to learn that the tool list changed.
Integrating with React
A small hook covers most cases. It registers on mount, unregisters on unmount, and always calls the latest execute so you don’t re-register on every render:
import { useEffect, useRef } from 'react'
type Tool = Parameters<ModelContext['registerTool']>[0]
export function useWebMCPTool(tool: Tool, enabled = true) {
const executeRef = useRef(tool.execute)
executeRef.current = tool.execute
useEffect(() => {
const mc = document.modelContext
if (!mc || !enabled) return
const controller = new AbortController()
mc.registerTool(
{ ...tool, execute: (input, opts) => executeRef.current(input, opts) },
{ signal: controller.signal },
).catch((err) => {
if (!controller.signal.aborted) console.error(`WebMCP: ${tool.name}`, err)
})
return () => controller.abort()
// Re-register only when the tool's public shape changes
}, [tool.name, tool.description, JSON.stringify(tool.inputSchema), enabled])
}Usage:
function CartPanel() {
const cart = useCart()
useWebMCPTool({
name: 'get_cart',
description: 'Get the current cart contents: items, quantities and total in EUR.',
annotations: { readOnlyHint: true },
inputSchema: { type: 'object', properties: {} },
async execute() {
return { items: cart.items.map(({ id, name, qty }) => ({ id, name, qty })), total: cart.total }
},
})
useWebMCPTool(checkoutTool, cart.count > 0)
return <CartView cart={cart} />
}The abort-on-cleanup pattern also makes this safe under React Strict Mode, which mounts effects twice in development.
TypeScript Types
document.modelContext is not in lib.dom.d.ts yet. A minimal declaration file:
// webmcp.d.ts
interface ToolAnnotations {
readOnlyHint?: boolean
consequentialHint?: boolean
untrustedContentHint?: boolean
debugging?: boolean
}
interface ModelContextTool {
name: string
title?: string
description: string
inputSchema?: object
outputSchema?: object
annotations?: ToolAnnotations
execute(input: any, options: { signal: AbortSignal }): Promise<unknown>
}
interface RegisteredTool extends Omit<ModelContextTool, 'execute'> {
window: Window
origin: string
}
interface ModelContext extends EventTarget {
registerTool(tool: ModelContextTool, options?: { signal?: AbortSignal; exposedTo?: string[] }): Promise<void>
getTools(options?: { fromOrigins?: string[] }): Promise<RegisteredTool[]>
executeTool(tool: RegisteredTool, input?: object, options?: { signal?: AbortSignal }): Promise<string>
}
interface Document {
readonly modelContext?: ModelContext
}Marking it optional forces a feature check everywhere, which you need anyway.
Summary
document.modelContext.registerTool()takes a name, description, input schema andexecutefunction.- The description and schema are all the agent sees — write them for a reader who has never seen your UI.
- Validate input, return compact results, and throw errors that tell the agent how to recover.
- Use annotations to declare read-only and consequential tools.
- Tool lifetime is controlled by
AbortSignal; register tools only when they can succeed.
Next, Part 3 covers the declarative API — getting tools from plain HTML forms.
— 2 —