WebMCP lets a web page register structured tools directly in the user’s browser through document.modelContext. When someone already has your application open alongside a browser-integrated assistant, the assistant invokes those tools under the active same-origin browser session without copying cookies, minting separate API keys, or scraping the DOM.
WebMCP is a progressive enhancement behind browser feature flags (such as Chrome’s WebMCP flag). Keep your standard HTML and HTTP interface functional when document.modelContext is absent, and expose the same operations over /mcp for remote assistants running outside the browser.
Register read-only and mutating browser tools
Feature-detect document.modelContext (falling back to navigator.modelContext for early implementations), pass an AbortSignal tied to the lifetime of the view or signed-in session, and call your application’s existing HTTP routes inside execute:
const modelContext = document.modelContext ?? navigator.modelContext
export function registerCatalogTools({ csrfToken }) {
if (!modelContext?.registerTool) return () => {}
const controller = new AbortController()
const { signal } = controller
modelContext.registerTool({
name: "list_classes",
title: "List classes",
description: "List upcoming classes with seat counts and times.",
inputSchema: {
type: "object",
properties: { day: { type: "string" } },
additionalProperties: false,
},
outputSchema: {
type: "object",
properties: {
classes: { type: "array", items: { type: "object" } },
},
required: ["classes"],
},
annotations: { readOnlyHint: true, untrustedContentHint: true },
execute: async ({ day }) => {
const qs = day ? `?day=${encodeURIComponent(day)}` : ""
const res = await fetch(`/api/classes${qs}`, { credentials: "same-origin" })
if (!res.ok) throw new Error(`list_classes failed: ${res.status}`)
return res.json()
},
}, { signal })
modelContext.registerTool({
name: "book_class",
title: "Book a class",
description: "Reserve one seat in the selected class for the signed-in member.",
inputSchema: {
type: "object",
properties: {
classId: { type: "string", minLength: 1 },
idempotencyKey: { type: "string", minLength: 8 },
},
required: ["classId", "idempotencyKey"],
additionalProperties: false,
},
annotations: { readOnlyHint: false, consequentialHint: true },
execute: async ({ classId, idempotencyKey }) => {
const res = await fetch("/api/bookings", {
method: "POST",
credentials: "same-origin",
headers: {
"content-type": "application/json",
"x-csrf-token": csrfToken,
"idempotency-key": idempotencyKey,
},
body: JSON.stringify({ classId }),
})
if (!res.ok) throw new Error(`book_class failed: ${res.status}`)
return res.json()
},
}, { signal })
window.addEventListener("pagehide", () => controller.abort(), { once: true })
return () => controller.abort()
}
In a single-page application (such as an Alloy React app), call the returned cleanup function when the route unmounts or when the active user or account changes. In a multi-page application (such as an Rsx app), bind controller.abort() to pagehide so stale handlers never outlive navigation.
Keep one operation schema across browser and remote MCP
agent-ready generates your OpenAPI catalogue and /mcp server from your Rust Surface, while WebMCP runs in client-side JavaScript. Reuse the exact operation names, input JSON schemas, and HTTP endpoints from your Surface when registering WebMCP tools so an assistant sees identical contracts whether it calls your app from inside a browser tab or over remote /mcp.
Ferrite uses this pattern on its own properties:
- The Ferrite documentation site registers
search_ferrite_docsandread_ferrite_docondocument.modelContext. - The Ferrite Dashboard registers
inspect_application_graphas a read-only WebMCP tool scoped to the currently selected account; see Dashboard WebMCP.
Security and failure rules
- Session cookies stay
HttpOnly. Same-originfetchattaches the browser’sHttpOnlysession cookie automatically. Never place a session token, API key, or bearer credential inlocalStorage, tool descriptions, tool arguments, tool results, or the URL. - Mutating tools enforce CSRF and idempotency. Mark writes with
readOnlyHint: falseandconsequentialHint: true, require your normal CSRF token, and accept anidempotency-keyheader so retries do not duplicate effects. - Scope tools to the active user and account. If a user signs out or switches accounts, abort the current
AbortControllerand re-register only the tools valid for the new context. Fail closed with a clear error code when the active account does not match the request. - Mark external or user-authored data. Set
untrustedContentHint: trueon tools that return customer-submitted or third-party text so the host treats the output as data rather than instructions.
Verify WebMCP registration
In a browser with WebMCP enabled, open DevTools on your running app (ferrite dev) and check that document.modelContext registered your tools, that invalid inputs fail schema validation, and that navigating away aborts the registration. You can also run agent-score or agent-scan against your deployed origin to verify WebMCP declaration checks; see Verify agent readiness.
Next steps
- Inspect a signed-in production WebMCP tool in Dashboard WebMCP.
- Expose the same operations over remote HTTP with OpenAPI and structured errors and MCP Servers.
- Embed interactive UI inside an external assistant conversation with MCP Apps.