Ver en Español
Your Web App Already Has Tools: Exposing Functions and Forms with WebMCP in Chrome
Nov 29, 2026
Updated: Nov 29, 2026

Your Web App Already Has Tools: Exposing Functions and Forms with WebMCP in Chrome

Your web app already knows how to search a catalog, filter items, build a reading list, or stage an order. That logic lives behind your buttons and forms today, inside an authenticated browser session the user already opened.

Friction starts the moment that user asks an AI agent to run one of those actions. Most assistants operate outside your tab: they call a separate server-side MCP (with separate auth and zero visibility into your open screen), or they launch a headless browser to guess clicks from screenshots and DOM snapshots.

Rename one CSS class or move a button and a DOM scraper breaks. Worse, it burns tokens parsing entire accessibility trees just to trigger a JavaScript function your page already owns.

WebMCP is Chrome's experimental proposal to close that gap. Your page exposes JavaScript functions and HTML forms as typed JSON Schema contracts on document.modelContext. The user and the agent share the same active tab, cookies, localStorage, and live DOM.

webmcp-external-gap.gif

The Honest Architecture: Two Pieces, One Contract

One boundary deserves clarity upfront: a standalone assistant running outside the browser (such as a CLI or desktop chat app) cannot reach into your open tab on its own, and a standard webpage exposes no actions by default.

In-tab execution requires two pieces:

  1. An agent connected to the browser. That can be an integrated model (Gemini in Chrome or the on-device Prompt API behind chrome://flags/#prompt-api-tool-use) or, during this experimental phase, a bridge like GoogleChromeLabs/webmcp-extension or chrome-devtools-mcp.
  2. A standard contract inside your web app. Your code registers tools on document.modelContext without coupling to any specific extension or model vendor.

Chrome acts as the broker in the middle: getTools() lists your JavaScript and HTML tools, ontoolchange announces updates, arguments validate against your JSON Schema, and Permissions-Policy: tools controls access. Swap the agent later and your page code stays intact.

dom-scraping-vs-webmcp.jpg

Design Around User Tasks, Not One Tool per Button

A common mistake when teams first expose page tools is mirroring the UI button by button. Twelve buttons become twelve tiny tools, which forces the model to chain trivial calls and raises selection errors.

Chrome's WebMCP documentation frames tool design around the user's task (Critical User Journey). If the job is locating a customer, one findClient tool is enough. When the workflow has clear stages, chain purposeful actions (record transcript, summarize notes, draft email).

cuj-single-tool-flow.jpg

cuj-multi-step-flow.jpg

Before writing code, rehearse the user-agent dialogue turn by turn. That quickly shows what state your page already holds, which parameters are missing, and where the user takes back control in the UI.

webmcp-agent-sequence.png

A shopping cart illustrates this well: forcing the agent to add items one by one, open the cart, and then move to checkout adds friction for someone who just wants to buy a single item right away. Collapsing that path into one "buy now" tool produces a much smoother flow.

Two Paths on One Page: Imperative API and Declarative API

In the interactive demo built for the talk (Demo 01 · Reading List), both WebMCP APIs operate on a single source of truth: a four-article catalog and an in-memory reading list.

demo-reading-route-sync.gif

1. Imperative API: document.modelContext.registerTool()

When an action lives in JavaScript and depends on in-memory state, register it directly with registerTool():

// articles already lives in your app state: [{ id: "models", ... }, ...]
await document.modelContext.registerTool({
  name: "add_to_route",
  description: "Add a blog article to the user reading list. Valid IDs: models, browserdj, patterns, ownership.",
  inputSchema: {
    type: "object",
    properties: {
      articleId: {
        type: "string",
        enum: articles.map(a => a.id),
        description: 'Article ID: "models", "browserdj", "patterns", or "ownership".'
      }
    },
    required: ["articleId"],
    additionalProperties: false
  },
  annotations: {
    readOnlyHint: false,
    consequentialHint: false,
    untrustedContentHint: false
  },
  execute: args => add(args, "tool")
}, { signal: controller.signal });

Three choices carry the weight here:

  • Live catalog data feeds the enum. When the valid set is small and known, mapping articles.map(a => a.id) prevents the agent from inventing IDs. (Part 3 covers dynamic catalogs where an enum does not fit.)
  • execute calls the exact same handler as your buttons. In reading-route.html, clicking "+ Add to list" runs add({ articleId }, "ui") and the agent runs add(args, "tool"). No parallel backend or duplicated state exists: once the agent adds the small-models article, you can remove it with the card button a second later.
  • An AbortSignal owns the tool lifecycle. When the route changes or the page unloads (pagehide), controller.abort() unregisters the batch so agents never see stale tools.

The same demo registers remove_from_route (write) and list_reading_route tagged with readOnlyHint: true for pure reads.

2. Declarative API: Turn an Existing <form> into a Tool

Not every page action needs JavaScript boilerplate. If your UI already renders an HTML form for searching or filtering, the Declarative API turns it into a WebMCP tool with four attributes:

<form
  id="declarative-filter-form"
  toolname="filter_catalog"
  tooldescription="Filter blog articles by keyword query and optional maximum reading time in minutes."
  toolautosubmit
>
  <input
    name="query"
    type="search"
    toolparamdescription="Keyword to match article title or tags (e.g. models, browserdj, patterns, ownership)."
  >
  <select
    name="maxMinutes"
    toolparamdescription="Maximum reading time in minutes (all, 8, 10, or 15)."
  >
    <option value="all">All durations</option>
    <option value="8">≤ 8 min</option>
    <option value="10">≤ 10 min</option>
    <option value="15">≤ 15 min</option>
  </select>
  <button type="submit">Filter</button>
</form>

Each attribute handles one job:

  • toolname and tooldescription register the <form> and tell the agent when to use it.
  • toolparamdescription adds semantic context to each <input> and <select> so Chrome builds the JSON Schema automatically.
  • toolautosubmit submits the form as soon as the agent populates the fields. Without it, the agent fills the controls and waits for manual submission.
  • While the agent interacts with the form, Chrome applies :tool-form-active and :tool-submit-active CSS pseudo-classes for live visual feedback.

Inside your submit handler, check e.agentInvoked to return structured data without a page reload:

form.addEventListener("submit", e => {
  e.preventDefault();
  const payload = syncFilter(e.agentInvoked ? "form" : "ui");
  if (e.agentInvoked && typeof e.respondWith === "function") {
    e.respondWith(Promise.resolve(payload));
  }
});

Open the WebMCP extension panel on the page and both the imperative JavaScript tools and the declarative HTML form show up in one list.

extension-available-tools.png

Progressive Enhancement and Framework Support

WebMCP is still experimental (Origin Trial). Treating it as a hard dependency would break your app for nearly every user today.

Use progressive enhancement: ship working buttons and HTML forms first, feature-detect document.modelContext?.registerTool at runtime, and wrap registration in try/catch with an AbortController:

async function registerPageTools(tools, signal) {
  if (!document.modelContext?.registerTool) return false;
  try {
    for (const tool of tools) {
      await document.modelContext.registerTool(tool, { signal });
    }
    return true;
  } catch (err) {
    console.warn("WebMCP registration skipped:", err.message);
    return false;
  }
}

If you build with a framework, the official docs already point to experimental integrations for React (use-webmcp-tool), Angular (Signal Forms), and Vue (@vueuse/core). The architectural rule stays the same: bind tools to the state layer your components already share.

Trying It in Your Own Tab Today (Extension or CLI)

To test locally in Chrome 155+ (or 149+ for the Origin Trial API):

  1. Enable chrome://flags/#enable-webmcp-testing and relaunch Chrome.
  2. Serve your app over HTTPS or http://localhost:8080 (npm run serve or python3 scripts/serve.py). Avoid file://, which Chrome extensions block by default.
  3. For an in-browser chat interface, load GoogleChromeLabs/webmcp-extension. For on-device execution without an API key, also enable chrome://flags/#prompt-api-tool-use.

You can also invoke the exact same page contract from your terminal (Antigravity, Claude Code, or Gemini CLI). That setup is for local development, not end users, yet it exercises your exact page contract. Enable remote debugging at chrome://inspect/#remote-debugging and configure chrome-devtools-mcp:

{
  "chrome-devtools": {
    "command": "npx",
    "args": [
      "chrome-devtools-mcp@latest",
      "--autoConnect",
      "--categoryExperimentalWebmcp"
    ]
  }
}

Without --autoConnect, the server opens an isolated empty Chrome profile; with --autoConnect, it attaches to your running browser with existing tabs and cookies. --categoryExperimentalWebmcp enables list_webmcp_tools and execute_webmcp_tool, letting your CLI agent call your tools directly without scraping the DOM.

What is still missing to move past demos is the usual story on the web: becoming an open standard adopted across more browsers, and collecting real developer feedback so the spec matures. Because WebMCP is still experimental, early testing and feedback are exactly what push adoption forward.

Auditing Your Site Without Hand-Writing the Boilerplate

Whenever I show these snippets live, the same question comes up: if AI writes most of the code now, why learn how to wire these tools by hand?

An LLM can draft your initial schemas and registrations quickly, but engineering judgment stays yours: choosing which user journeys deserve a tool and keeping destructive mutations behind explicit human confirmation. To speed up that first audit on your codebase, I published the WebMCP Auditor Prompt on GitHub Gist. It inspects your site and proposes registerTool() candidates for you to review and approve.

Part 2 tackles the hardest part of running agents inside an authenticated tab: permission fatigue, Indirect Prompt Injection, Spotlighting, and human confirmation gates in code.

Live Lab and References

Sebastian Gomez

Sebastian Gomez

Creador de contenido principalmente acerca de tecnología.

Leave a Reply

0 Comments

Advertisements

Related Posts

Categorías