DEV Community

Lukas Kopischke
Lukas Kopischke

Posted on Edited on Originally published at lukiluki.me Fully Autonomous

Web MCP – Tools for AI Agents in the Browser

Originally published with interactive examples at lukiluki.me.

An AI agent tries to use your website through screen scraping and simulated mouse clicks. A CSS selector breaks or the layout changes, and the action fails. How can the application expose its capabilities directly, without making the agent reconstruct every interaction from the page layout?

WebMCP lets web applications expose structured tools to browser and extension agents through annotated HTML forms or JavaScript's document.modelContext. This gives agents named operations and defined inputs instead of relying entirely on simulated clicks. The API is evolving through an experimental browser implementation and specification work. Tool annotations describe intent and risk; reliable authorization, validation and business rules still belong in the application.

Merksatz (Key takeaway):
WebMCP provides semantic tool interfaces for browser agents. Treat those interfaces as application entry points with explicit permissions, validation and observable results.

What do you need, and how can you verify it?

Start with a browser participating in the WebMCP experiment and check the current trial requirements. For local testing, check availability of chrome://flags/#enable-webmcp-testing. Feature-detect modelContext before registration. Browser versions and individual API features can differ; the presence of the interface alone does not validate a complete integration.

Use type definitions that match the implementation you target. For React, Chrome's documentation points to experimental framework support; choose a wrapper only after checking its version and lifecycle behavior. Cross-origin frames additionally require explicit permission delegation.

To inspect the integration:

  • Check 'modelContext' in document in the console, then inspect await document.modelContext.getTools() in a supported browser.
  • Use the Model Context Tool Inspector linked from the browser documentation for manual invocations.
  • Listen for toolchange on document.modelContext and verify that tools appear and disappear with application state.
  • Test valid input, invalid input, cancellation and denied access against a test backend before using a consequential action.

Typical applications include mapping conversational input to form fields, exposing a diagnostic or filter operation, and supporting a booking workflow. Structured inputs can reduce ambiguity, but do not guarantee correct intent recognition or successful execution. Purchases, bookings and deletions need an explicit confirmation and authorization design.

Eight implementation criteria

These criteria combine the imperative API documentation with Chrome's tool security guidance. They are implementation guidance; recommended text budgets are not hard limits imposed by the specification.

Criterion Implementation decision What to check
Declarative or imperative API Use toolname and tooldescription for suitable HTML forms; use registerTool() for application logic. The chosen route fits the existing form and state model.
Annotation hints Describe read-only operations, consequential actions and untrusted output accurately. Client handling and application controls agree with the annotations.
Concise descriptions Start with recommended budgets: 30 characters for names, 150 for parameter descriptions, 500 for tool descriptions and 1,500 for output. Text remains informative; adjust to the agent and task rather than silently truncating essential data.
Recoverable errors Explain which input or condition failed and what can be corrected. Failure is distinguishable from success and exposes no sensitive internals.
Understandable input Prefer meaningful choices and accept raw input where practical. The model does not need to guess identifiers or perform unnecessary conversion.
Lifecycle and cancellation Remove obsolete tools and pass the execution signal to asynchronous work. Cancellation reaches requests; completed server actions are handled separately.
Origin boundaries Delegate frame permissions and expose tools only to explicitly trusted origins. Unauthorized origins cannot discover or execute them.
Validation in code Use the schema for input structure and application code for business constraints. Backend authorization and validation also reject direct invalid requests.

Annotation hints (Metadata describing a tool's side effects, output trust and intended handling; the fields do not replace application authorization or validation.) help agents interpret a tool. readOnlyHint describes operations that do not change state; consequentialHint signals significant actions so a client can request confirmation; untrustedContentHint labels externally sourced or user-generated output. A hint does not eliminate prompt injection.

Origin controls and cancellation

Cross-origin registration requires delegation through allow="tools". The registering document must also expose its tool to the intended secure origins using exposedTo. A caller discovering cross-origin tools lists the requested origins in getTools({ fromOrigins: [...] }). Review all three parts rather than assuming that frame permission alone grants access.

An AbortSignal (A signal that tells cooperating asynchronous operations to stop when their caller cancels the work.) passed during registration controls the registration lifecycle. The signal received by execute concerns an invocation. Forwarding it to fetch() can cancel client-side work; it cannot undo a booking that a server has already committed.

Implementation patterns

The snippets illustrate integration points. They require a compatible browser, matching types and working application endpoints. The booking endpoint must independently validate inputs, check authorization and enforce the intended confirmation workflow. The example does not provide a complete booking service.

Pattern 1: Imperative API with hints and cancellation

This client-side example uses Zod for input validation. Register it within your application's lifecycle and call controller.abort() when leaving the state in which the tool is available. The cast is an illustration for projects without matching browser types, rather than a replacement for checking the API contract.

import { z } from "zod";

const FlightBookingSchema = z.object({
  flightId: z.string().min(1, "A flight ID is required"),
  passengers: z.number().int().positive("At least one passenger is required"),
});

if (typeof document !== "undefined" && "modelContext" in document) {
  const controller = new AbortController();

  await (document as any).modelContext.registerTool(
    {
      name: "book_flight",
      description: "Book a selected flight after the travel details are confirmed.",
      inputSchema: {
        type: "object",
        properties: {
          flightId: { type: "string", description: "ID of the selected flight" },
          passengers: { type: "number", description: "Number of tickets" },
        },
        required: ["flightId", "passengers"],
      },
      annotations: {
        readOnlyHint: false,
        consequentialHint: true,
        untrustedContentHint: false,
      },
      execute: async (rawArgs: unknown, { signal }: { signal: AbortSignal }) => {
        const parsed = FlightBookingSchema.safeParse(rawArgs);
        if (!parsed.success) {
          return "Invalid input: supply a flight ID and a positive whole passenger count.";
        }

        try {
          const response = await fetch("/api/bookings", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(parsed.data),
            signal,
          });

          if (!response.ok) {
            return "Booking was not confirmed. Check availability and permissions before retrying.";
          }

          return "Booking confirmed by the server.";
        } catch {
          return signal.aborted
            ? "Request cancelled locally. Check booking status before retrying."
            : "No confirmation received. Check booking status before retrying.";
        }
      },
    },
    { signal: controller.signal }
  );

  // In your route or component cleanup: controller.abort();
}
Enter fullscreen mode Exit fullscreen mode

Pattern 2: Declarative HTML form API

A supported browser can derive a tool from annotated form controls. Existing server-side form handling remains responsible for processing and validating the request.

<form
  toolname="supportRequest"
  tooldescription="Create a customer support request."
  action="/api/support"
  method="POST"
>
  <label for="fullName">Full name</label>
  <input type="text" id="fullName" name="fullName" required />

  <label for="category">Topic</label>
  <select
    id="category"
    name="category"
    toolparamdescription="Route the request to the relevant support team."
    required
  >
    <option value="returns">Returns and return shipping</option>
    <option value="shipping">Delivery status and tracking</option>
    <option value="billing">Billing and payment</option>
  </select>

  <label for="description">Problem description</label>
  <textarea id="description" name="description" required></textarea>

  <button type="submit">Submit request</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Architectural practices and limits

Keep tools distinct and narrowly scoped. Meaningful parameters such as a shipping choice are easier to interpret than unexplained numeric IDs. Remove a tool when its action is no longer valid, rather than leaving obsolete operations available after navigation.

Hints are part of a security design
Label consequential actions and untrusted output, but also verify permissions,
confirmation and data handling in the application. A read-only tool can still
expose private information. Model behavior and annotation metadata alone do
not establish a security boundary.

Keep errors actionable and avoid returning raw internal exceptions. Test repeated calls and interrupted requests, especially where retrying could duplicate a purchase. The browser interface structures the call; the application still owns transaction correctness and recovery.

Agent system prompts

Copy these prompts into a coding agent such as Cursor, Claude Code or Antigravity after identifying the target browser and test environment. They ask the agent to follow the project's existing architecture and verify the current API rather than assume fixed file paths.

🤖 WebMCP Implementation and Integration (Ziel: Cursor / Claude Code / Antigravity)

You are an experienced frontend architect. Implement WebMCP in this web application.

First inspect the framework, routing, forms and state management. Read the current primary WebMCP documentation for the target browser. Choose a small integration that fits the existing application.

1. Choose declarative form attributes for suitable standard forms or document.modelContext.registerTool() for dynamic application logic.
2. Set accurate readOnlyHint, consequentialHint and untrustedContentHint annotations. Verify confirmation and authorization separately.
3. Keep names and descriptions concise. Start with the documented recommended character budgets and preserve essential result information.
4. Validate inputs and business rules, and return actionable errors without leaking internals.
5. Forward execution cancellation to asynchronous requests. Remove tools when their application state ends and account for already committed server actions.
6. Prefer meaningful inputs and enums. Restrict cross-origin access explicitly if it is required.

Present the registered tools, schemas and annotations. Test success, invalid input, denied access and cancellation in a safe test environment, and report any behavior you could not verify.
Enter fullscreen mode Exit fullscreen mode

🤖 WebMCP Security and Evaluation Audit (Ziel: Cursor / Claude Code / Antigravity)

Review this project's WebMCP tools against the current primary documentation and application security requirements.

1. Are read-only and consequential operations labeled accurately, and are sensitive actions protected by a verified confirmation workflow?
2. Is untrusted output identified and handled as data rather than instructions? Are unsafe DOM writes or data disclosures possible?
3. Are tool descriptions and outputs concise without silently omitting essential information?
4. Do frame delegation, exposedTo and discovery origins grant only the intended access?
5. Does cancellation reach long-running requests, and are uncertain transaction outcomes handled without unsafe retries?
6. Can tests distinguish success, validation failures, denied access and cancellation? Are backend checks independent of the tool schema?

Return a prioritized report with concrete code references, reproducible checks and explicitly unverified behavior.
Enter fullscreen mode Exit fullscreen mode

WebMCP implementation checklist

  • [ ] Choose the API: Use forms for appropriate declarative input and document.modelContext for application logic; verify target browser support.
  • [ ] Describe and enforce intent: Set accurate annotations and verify authorization, confirmation and input validation independently.
  • [ ] Keep results useful: Use concise descriptions and explicit success or failure responses; test invalid and ambiguous inputs.
  • [ ] Handle lifecycle: Remove obsolete tools, forward cancellation and check uncertain server outcomes before retrying.
  • [ ] Restrict exposure: Test allowed and denied origins, including frame delegation, exposedTo and discovery options.

Sources and next steps

The API is experimental and subject to change. Primary API and security guidance checked for this translation on October 19, 2026; the snippets are integration examples, not measured browser test results.

Testing explains how to verify application behavior around tool calls. Enterprise Architecture puts data access and authority to act in the wider context of AI system design.


Read the original guide & explore the interactive playground on *lukiluki.me*.

Top comments (0)