WebMCP in React: Let an Agent Ask for the Action, Not Guess the Click
“Go to page seven” is a small request. Making an agent guess which button to click is a surprisingly indirect way to fulfil it.

“Go to page seven” is a small request. Making an agent guess which button to click is a surprisingly indirect way to fulfil it.
A page can instead describe a navigation operation with an explicit input. We'll expose that operation from a React component, keep its manual buttons, and then compare it with an annotated form. The interesting lifecycle question is what happens when the component disappears while a request is still running.
Availability is experimental
WebMCP exposes page functions to browser agents and in-page agents. It is not a remote MCP server, an MCP transport, or an inference engine. The current specification is a Community Group draft, not a W3C Recommendation.
Chrome documents an origin trial beginning with Chrome 149 and a local testing flag. That is not general stable-browser availability. Examples below target the reviewed draft and current Chrome documentation; older trial builds can differ. Use HTTPS, feature detection, and manual controls. Registering tools does not create an assistant or install an on-device model.
A bounded React tool
In an example React project, install Zod and the development typings package webmcp-types (reviewed: 0.1.10). The type-only import supplies declarations, not a polyfill. This component owns one document-unique tool and a fixed ten-page demonstration; it does not render a PDF.
"use client";
import type {} from "webmcp-types";
import { useEffect, useState } from "react";
import { z } from "zod";
const PAGE_COUNT = 10;
const pageInput = z.object({
pageNumber: z.number().int().min(1).max(PAGE_COUNT),
}).strict();
export function DocumentNavigator() {
const [page, setPage] = useState(1);
const [status, setStatus] = useState("Checking WebMCP support...");
useEffect(() => {
const context = document.modelContext;
if (!context) {
setStatus("WebMCP unavailable. Manual controls still work.");
return;
}
const lifetime = new AbortController();
void context.registerTool({
name: "navigate_document_page",
description: "Request a page in this ten-page demonstration viewer.",
inputSchema: {
type: "object",
properties: {
pageNumber: { type: "integer", minimum: 1, maximum: PAGE_COUNT },
},
required: ["pageNumber"],
additionalProperties: false,
},
execute: async (input, { signal }) => {
signal.throwIfAborted();
lifetime.signal.throwIfAborted();
const { pageNumber } = pageInput.parse(input);
setPage(pageNumber);
return { status: "scheduled", requestedPage: pageNumber };
},
}, { signal: lifetime.signal }).then(() => {
if (!lifetime.signal.aborted) setStatus("WebMCP tool registered.");
}).catch((error: unknown) => {
if (lifetime.signal.aborted) return;
console.error("WebMCP registration failed", error);
setStatus("WebMCP registration failed. Use the manual controls.");
});
return () => lifetime.abort();
}, []);
return (
<section aria-label="Demonstration document navigation">
<p role="status">{status}</p>
<p>Page {page} of {PAGE_COUNT}</p>
<button disabled={page === 1} onClick={() => setPage(p => p - 1)}>
Previous
</button>
<button disabled={page === PAGE_COUNT} onClick={() => setPage(p => p + 1)}>
Next
</button>
</section>
);
}The agent asks for a page number, not a DOM selector. The component validates that number and schedules the same state change its manual controls use. This keeps the operation understandable while leaving React responsible for when the updated page becomes visible.
Registration is asynchronous: handle its rejection, and abort registration on unmount. Current Chrome distinguishes registration lifetime from execution cancellation; unregistering alone need not cancel an in-flight call. The callback checks both signals. Runtime validation rejects fractions, out-of-range values, and extra fields; JSON Schema alone is not the application's validation boundary.
The callback schedules React state and says “scheduled,” not “the DOM has committed.” Workflows needing a committed observation require an explicit post-commit acknowledgement. This fixed-schema example avoids stale state closures; dynamic tools must update their registration when their schema or behavior changes.
Discovery returns descriptors, not callbacks
import type {} from "webmcp-types";
export async function requestPage(pageNumber: number, signal: AbortSignal) {
const context = document.modelContext;
if (!context) throw new Error("WebMCP is unavailable.");
const tools = await context.getTools();
const tool = tools.find(candidate =>
candidate.name === "navigate_document_page" &&
candidate.origin === location.origin &&
candidate.window === window
);
if (!tool) throw new Error("The current page has no navigation tool.");
return context.executeTool(tool, { pageNumber }, { signal });
}Use getTools(), then executeTool(descriptor, object, options). There is no listTools() here and no discovered tool.execute(). The example restricts selection to this window and origin. Tool lists can change; surface invocation failures rather than pretending an action succeeded. Tool results are serialized strings in the reviewed draft.
Declarative forms are a separate experimental surface
Chrome documents toolname and tooldescription on forms. Without toolautosubmit, the user must submit manually; with it, agent invocation can submit. This HTML and the following browser script demonstrate a local preview only. The illustrative /orders GET endpoint is not implemented here; provide it for useful navigation without JavaScript.
<form id="filter-preview" action="/orders" method="get"
toolname="preview_order_filter"
tooldescription="Preview a minimum order amount; do not place an order."
toolautosubmit>
<label for="minimum">Minimum amount</label>
<input id="minimum" name="minimum" type="number"
min="0" max="1000000" step="0.01" value="0" required>
<button type="submit">Preview filter</button>
<output id="filter-status" role="status"></output>
</form>const form = document.getElementById("filter-preview");
const output = document.getElementById("filter-status");
if (!(form instanceof HTMLFormElement) || !output) {
throw new Error("The preview form and status output are required.");
}
form.addEventListener("submit", event => {
event.preventDefault();
const result = (async () => {
if (!form.reportValidity()) throw new Error("Invalid filter input.");
const raw = new FormData(form).get("minimum");
if (typeof raw !== "string" || raw.trim() === "") {
throw new Error("A minimum amount is required.");
}
const minimum = Number(raw);
if (!Number.isFinite(minimum) || minimum < 0 || minimum > 1000000) {
throw new Error("Minimum amount is outside the permitted range.");
}
output.textContent = "Filter preview: minimum " + minimum;
return { minimum, status: "preview-only" };
})();
if (event.agentInvoked && typeof event.respondWith === "function") {
event.respondWith(result);
}
void result.catch(error => {
console.error("Filter preview failed", error);
output.textContent = "Filter preview failed. Check the amount.";
});
});Attach the script after the form exists. Call preventDefault() before respondWith(), and provide the result promise synchronously during an agent-invoked submit event. Ordinary human submission uses the same visible validation and preview. This is native event handling, not a claim that React form actions automatically supply WebMCP results.
Permission and trust boundaries
The tools Permissions Policy defaults to self. Cross-origin frames require policy delegation and explicit origin exposure/discovery rules. Read-only and consequential annotations are hints, not authorization or guaranteed user consent. Keep server-side authentication, authorization, input checks, and transaction rules; require real user confirmation for sensitive actions. Treat tool descriptions and results as untrusted data.
Neither local dispatch nor WebMCP proves local inference, zero latency, no network traffic, or regulatory compliance. Test lifecycle races, cancellation, rejected input, manual fallback, and the exact browser trial version before deployment.
The tool should be another way into the same application rules, not a privileged back door. Keep manual controls working, validate every request, and distinguish scheduling an update from observing it on screen. An explicit action is useful only when its result is equally clear.