Blog · · 10 min read
Add WebMCP to an existing web application safely

A WebMCP integration can make an existing web application easier for browser agents to operate, but a thin registerTool() wrapper does not create a production boundary. The tool can expose stale page state, trust agent-supplied identity, bypass the authorization used by the visible interface, or submit a consequential action without a current user decision. Start with one real user journey, keep server-side authorization authoritative, bind tool availability to live page state, separate preparation from commitment, and preserve the ordinary UI as both evidence and fallback.
Understand the boundary before adding code
WebMCP exposes structured tools from the live web page to agents running in the browser. Chrome's WebMCP overview describes two ways to do that: declarative tools based on HTML forms and imperative tools registered through JavaScript. The proposal is tab-bound and aware of the current page rather than a persistent remote service.
That boundary differs from the alternatives:
- Server-side MCP exposes persistent backend capabilities that do not depend on a specific open page.
- A direct API gives an integration a stable machine endpoint without a browser tool-discovery layer.
- Computer use asks a model to infer controls from screenshots, coordinates, or page structure.
- WebMCP exposes explicit tools from the current document and can react to its state.
Chrome's WebMCP and MCP comparison treats them as complementary. Use backend MCP for durable, cross-client capabilities. Use WebMCP when the open page, current user session, visible selection, or immediate UI reaction matters. A product may use both, provided both paths call the same implementation of each business rule.
The WebMCP specification repository tracks the standard, and Chrome exposes the feature through an origin trial. Treat capability detection, version changes, and unsupported browsers as normal operating conditions rather than launch surprises.
Start with one workflow inventory
Do not begin by converting every button into a tool. Pick one user journey that is valuable, bounded, and observable. Good first candidates let the agent read or prepare work while leaving the user in control of the final effect. Examples include filtering an order list, preparing a support reply, or drafting changes to a project record.
For the selected journey, record:
- The user's goal and the visible starting page.
- The product entities the workflow may read or change.
- Required permissions, tenant boundaries, and feature flags.
- Page state the tool needs, such as a selected project or active filter.
- Each step's effect class: read, prepare, reversible write, or consequential write.
- The authoritative success signal shown by the server and UI.
- Recovery behavior for invalid input, stale state, cancellation, and partial failure.
- The path for browsers or agents that do not support WebMCP.
Chrome's guide to building effective WebMCP tools recommends defining the user goal, initial application state, agent context, and system constraints, then role-playing the whole conversation. This catches missing prerequisites before they become vague tool errors. It also stops the team from exposing unrelated capabilities simply because they already exist in the page code.
Choose declarative or imperative tools deliberately
Use the declarative API for a form that already represents the whole operation accurately. The form should have stable fields, normal browser validation, a clear submit path, and the same server checks whether a person or an agent submits it. This is a strong fit for search, filtering, and simple create operations that are already safe as one visible form transaction.
Use the imperative API when the tool needs dynamic application state, several backend calls, a structured result, custom recovery, or component-level lifecycle management. The official imperative API documentation defines registration through document.modelContext.registerTool(), JSON Schema input, an asynchronous execute function, annotations, cancellation signals, tool discovery, and cross-origin controls.
Avoid a second hidden implementation. Both the WebMCP handler and visible UI should call one product service that owns validation, authorization, mutation, and receipts. The page adapter translates between tool arguments and that service. It does not become a new source of business truth.
Put authorization inside the business operation
Tool discovery grants no authority. A tool name visible to an agent says that a capability is available in the current document. The server must still prove that the current user may perform the requested action on the named record.
Resolve identity from the authenticated browser request, not from tool input. Resolve tenant membership and object scope on the server. Recheck current permissions at execution time, including after a long conversation or a user role change. Reject any request that supplies a tenant, principal, price, policy version, or approval identity that the server can derive itself.
A useful handler contract includes:
- A server-derived user and tenant.
- A stable operation ID for deduplication and audit.
- An entity version or precondition for writes.
- A narrow command object after schema validation.
- A typed outcome such as
prepared,committed,rejected,stale, orunknown. - A receipt or current-state URL the visible page can render.
WebMCP's security guidance says tools are same-origin by default and supports explicit secure-origin exposure through exposedTo. It also warns that read-only tools can reveal private user information. Follow the official WebMCP tool-security guidance, but treat origin exposure as one layer. Same-origin JavaScript can still be compromised, and a trusted origin is not a substitute for object-level authorization.
Register tools with page lifecycle and cancellation
The following example keeps the browser adapter small. It registers a read-only project summary only while the relevant project route is mounted, derives the project ID from trusted route state, passes cancellation to the request, and leaves authentication to the existing cookie-backed server session.
type ProjectSummary = {
projectId: string;
name: string;
openTasks: number;
version: string;
};
export function registerProjectSummaryTool(projectId: string): () => void {
if (!("modelContext" in document)) return () => {};
const lifecycle = new AbortController();
void document.modelContext.registerTool(
{
name: "get_project_summary",
description:
"Get the current project's name, open task count, and version.",
inputSchema: {
type: "object",
properties: {},
additionalProperties: false,
},
annotations: {
readOnlyHint: true,
untrustedContentHint: true,
},
execute: async (_input, { signal }): Promise<string> => {
const response = await fetch(
`/api/projects/${encodeURIComponent(projectId)}/summary`,
{
method: "GET",
credentials: "same-origin",
headers: { Accept: "application/json" },
signal,
},
);
if (response.status === 401) {
return "Authentication expired. Ask the user to sign in again.";
}
if (response.status === 403) {
return "The current user cannot read this project.";
}
if (response.status === 404) {
return "This project no longer exists or is no longer visible.";
}
if (!response.ok) {
return "Project summary is temporarily unavailable. Try again later.";
}
const summary = (await response.json()) as ProjectSummary;
return JSON.stringify(summary);
},
},
{ signal: lifecycle.signal },
);
return () => lifecycle.abort();
}
Call the returned cleanup function when the route or component unmounts. Register a new tool when the selected project changes instead of allowing a closure to keep an obsolete ID. The imperative API also passes an AbortSignal to execute; forward it to fetches and other cancellable operations. Cancellation should stop unnecessary work, but it must not erase evidence if a write may already have reached the server.
The annotations only give the agent hints. readOnlyHint describes whether the tool changes state, while untrustedContentHint flags externally sourced or user-generated data. The server decides what the request can read and whether an effect is allowed.
Separate preparation from consequential action
A single send_invoice or delete_project tool hides the moment when the user should inspect the final target and effect. Split high-impact workflows into preparation and commitment:
- A prepare tool validates inputs and current authority, loads current server state, and creates an expiring proposal.
- The page renders the exact target, material fields, warnings, reversibility, and expiry.
- The user confirms through a trusted interaction bound to that proposal version.
- A commit endpoint rechecks authorization, entity version, proposal expiry, and prior execution.
- The page displays the authoritative receipt or current state.
A read-only versus write split is too coarse for confirmation, because drafting and sending are both writes with different consequences, and a read-only tool can still reveal private user information. The WebMCP consequential-action discussion uses drafting versus sending as the kind of difference a confirmation policy needs to express. Until the standard supplies every policy primitive your product needs, enforce this boundary in product code and UI.
Do not accept approved: true from tool arguments. Approval must come from a trusted user interaction or a previously issued product policy grant, then be consumed against the exact proposal. For idempotent commit behavior, give the proposal a stable operation ID and return the existing receipt when the same commit is retried.
Keep visible state and results honest
A successful handler should update the page or cause it to refresh the same authoritative state used by the ordinary UI. If an operation creates a support reply draft, show that draft. If it changes a record, show the new version and receipt. If the backend accepted the request but the final state is uncertain, return unknown and give the user a reconciliation path. Never convert a network timeout into a confident success message.
Errors should tell the agent what can safely happen next. Chrome's workflow guidance recommends context-aware recovery rather than raw API messages or silent failure. Useful errors include:
Authentication expired. Ask the user to sign in again.Project version changed. Refresh the project before preparing another update.This operation requires user confirmation in the visible page.The request may have committed. Check operation receipt op_123 before retrying.
Keep outputs bounded. The security guide recommends concise names, descriptions, parameters, and tool results. Return the minimum data needed for the next decision, along with stable references for explicit follow-up reads. Do not dump a whole page, private account record, or long user-generated document into one result.
Protect registration from page-level interference
WebMCP runs in the page environment, so review third-party scripts, tag managers, extensions, and same-origin bundles that can alter it. A specification issue reports that one registration can overwrite another tool with the same name, which could let page code proxy or observe interactions. Treat that report as a regression case, not as a claim that every implementation is exploitable.
Use unique, stable tool names and maintain an expected registry for each route. In development and test environments, call document.modelContext.getTools() and compare the discovered names, origins, schemas, and annotations with the expected manifest. Fail release checks on unexpected duplicates or replacements. Reduce third-party script authority through ordinary supply-chain controls, Content Security Policy, dependency review, and removal of unnecessary page code.
Cross-origin exposure deserves a separate test. Default to same-origin. If an embedded partner genuinely needs a tool, allow only named secure origins, verify both embedding directions described by the API, and test that every other origin receives no capability. Keep the same server authorization checks even for an allowed partner.
Roll out without breaking the existing product
Use capability detection and retain the normal UI path. An unsupported browser should still let a person complete the workflow. A supporting browser with WebMCP disabled should behave the same way. The agent path adds an interface to current product behavior while forms, accessibility, and documented APIs remain available.
Roll out in steps:
- Enable read-only tools for internal accounts.
- Compare tool results with the visible page and direct API response.
- Add malformed-input, stale-session, cancellation, and navigation tests.
- Add prepare-only tools for reversible work.
- Introduce consequential commits only after confirmation and receipt tests pass.
- Expand by tenant or feature flag, with a quick disable path.
- Track discovery, execution, rejection, cancellation, unknown outcome, confirmation, and fallback rates.
Independent implementation guides from Scalekit and Ivan Turkovic show how WebMCP fits existing dashboards, forms, React components, Rails applications, and products that also expose MCP. Those examples help with mechanics. Your rollout still needs product-specific authority, lifecycle, and failure tests.
Verify the retrofit with negative tests
Before enabling writes, prove all of these cases:
- An unauthenticated or expired session cannot use a registered tool.
- A user cannot read or change another tenant's record by altering arguments.
- A route change removes tools tied to the previous entity and state.
- Two components cannot silently replace each other's tool registration.
- Unexpected same-origin scripts cannot add an approved-looking tool without detection.
- Cross-origin documents see only explicitly exposed tools from named secure origins.
- Malformed, missing, oversized, and additional arguments receive bounded errors.
- Read-only tools do not mutate authoritative state.
- A prepare tool cannot commit, and a commit cannot proceed without a current bound decision.
- Duplicate commit requests return one effect and one authoritative receipt.
- Cancellation before dispatch stops work; cancellation during an uncertain write triggers reconciliation.
- Authentication expiry and permission changes are rechecked at execution time.
- Tool output containing user-generated text is marked untrusted and cannot widen authority.
- The visible page shows the same final state as the server receipt.
- Unsupported browsers and disabled WebMCP keep the normal interface usable.
- Disabling the feature flag removes tools without removing the ordinary workflow.
Use the WebMCP inspector for discovery and execution checks, then add browser-level tests around the product boundary. A passing happy-path invocation proves only that the adapter can run. The negative matrix proves that the existing application remains in control.
Take the next step
Choose one read-heavy workflow on an authenticated page. Write its user goal, initial state, authorization source, effect classes, expected tool registry, visible result, recovery messages, and unsupported-browser fallback. Implement one thin adapter over the existing product service, then run the sixteen negative tests above. Add a write tool only after the product proves that discovery grants no authority, stale page tools disappear, consequential effects require a current decision, and every outcome is visible and reconcilable.