Edit

Expose site actions to AI agents with WebMCP

Use WebMCP to expose a webpage's actions as tools that AI agents can use to complete tasks for end users. For example, a flight booking site can expose a tool to search for flights. An agent can then call that tool, instead of finding and operating the site's search controls.

Detailed contents:

Introduction

WebMCP is a web API, but it doesn't run an AI model for the site. Instead, WebMCP connects the site's existing functionality to agents that interact with the site through the browser. This is different from AI web APIs for sites, which run AI models from the site's JavaScript code. See AI for the web.

WebMCP is a proposed web standard in the W3C Web Machine Learning Community Group. The API is experimental, and its design and implementation might change.

Benefits of WebMCP

Without WebMCP, an agent might need to analyze screenshots or HTML and CSS code to find the controls that complete a task. Changes to the page's layout can make those interactions less reliable.

WebMCP provides the following benefits:

  • Reuse existing code: Exposes existing client-side functions or HTML forms as tools.
  • Describe actions explicitly: Gives each tool a description and structured input parameters, so that the agent doesn't need to infer the action from the page's layout.
  • Share the page's context: Tools run in the current webpage and can use the same client-side state as the rest of the page, including the end user's signed-in state.
  • Keep actions visible: Tools can update the page, so that the end user and the agent work in the same interface.

WebMCP defines the tools that the site exposes. WebMCP doesn't prevent an agent from interacting with the site's other controls.

How WebMCP connects a site and an agent

WebMCP runs in the browser and connects the following parts:

  • The webpage: WebMCP registers tools by using JavaScript or by adding attributes to HTML forms.
  • Microsoft Edge: WebMCP tracks the registered tools, makes them available to agents, and runs a tool on the page when an agent calls it.
  • The agent: WebMCP selects a tool and provides input parameters to complete a task for the end user.

An in-browser AI agent communicates with the webpage's HTML UI and JavaScript tools through the browser's WebMCP runtime, as follows:

Diagram: Communicating through the WebMCP runtime

An agent can be built into the browser, provided by a browser extension, or hosted in a webpage, such as a chat widget. By default, an in-page agent can access tools from its own origin, but can't access tools from other origins.

Registering tools doesn't install or configure an agent. To test the tools with an agent, use WebMCP Explorer; see WebMCP Explorer, below.

Scope and lifetime of tools

WebMCP tools belong to the webpage that registers them.

  • Tools are scoped to the registering document, so each new page must register its own tools.
  • A page can update its registered tools when its application state changes. For example, a single-page application can register and unregister tools when the displayed content changes.
  • Tools have the same access as the page's other client-side code. Tools don't bypass the site's authentication or authorization checks.
  • WebMCP requires a secure context, such as HTTPS or localhost.
  • By default, cross-origin iframes can't register tools. To delegate the tools Permissions Policy feature to an iframe, add allow="tools" to that iframe.

Only delegate access to trusted embedded content. The iframe permission doesn't, by itself, expose all tools across origins.

Availability of WebMCP

WebMCP is available for testing in Microsoft Edge version 159 or later.

  • For local development, enable the WebMCP for testing flag on the development device.
  • For a live site, register for the WebMCP origin trial and add its token to the site.

The origin trial runs for a limited time. For its current expiration date, see WebMCP at the Microsoft Edge Origin Trials website.

Keep the site's normal controls available, so that the site works without WebMCP or an agent.

Enable WebMCP locally

To enable WebMCP on a development device:

  1. Make sure you're using Microsoft Edge version 159 or later.

  2. In Microsoft Edge, open a new tab or window, and then go to edge://flags.

  3. In the search box, at the top of the page, enter webmcp.

    The page is filtered to show the matching flag.

  4. Next to WebMCP for testing, select Enabled:

    The edge://flags page with "WebMCP for testing" set to Enabled and the Restart button available.

    In the lower right, the Restart button appears.

  5. Click the Restart button.

    Microsoft Edge restarts.

The WebMCP for testing flag enables WebMCP only on the device on which the flag is set. To enable WebMCP for end users of a live site, see Enable WebMCP on your live site by registering for the WebMCP origin trial, below.

Enable WebMCP on your live site by registering for the WebMCP origin trial

An origin trial enables WebMCP on registered sites, without requiring end users to set the WebMCP for testing flag.

To register a site for the WebMCP origin trial:

  1. Go to Microsoft Edge Origin Trials, in a new tab or window.

  2. Select the WebMCP trial.

  3. Click the I Accept the Terms of Use button.

  4. If prompted, sign in to GitHub, and then authorize the Microsoft Edge Origin Trials page to use the account sign-in.

    The New Origin Trial Registration form opens.

  5. In the Domain text box, enter a domain URL, such as https://example.com, or a subdomain URL, such as https://beta.example.com. Don't include a path or query parameters.

  6. Set the Enable token for subdomains? toggle.

    • To include the domain's subdomains, turn on the toggle.
    • To register only the specified domain or subdomain, turn off the toggle.
  7. Click the Submit button.

    The generated token appears in the Registrations section.

  8. Click the Copy button.

    The token is copied into the copy/paste buffer.

  9. Add the following tag to the <head> of each page that uses WebMCP, replacing EXAMPLE_TOKEN with the token:

    <meta http-equiv="origin-trial" content="EXAMPLE_TOKEN">
    

    Alternatively, send the token in an HTTP response header:

    Origin-Trial: EXAMPLE_TOKEN
    

When a supported version of Microsoft Edge finds a valid token, Microsoft Edge enables WebMCP for that page.

These registration steps follow Registering for an origin trial. For token configuration, expiration, and renewal, see Test experimental APIs and features by using origin trials.

Inspect and debug tools in DevTools

You can inspect, debug, and manually run WebMCP tools directly in Microsoft Edge DevTools, without installing an extension or configuring an LLM provider.

To inspect and debug tools in DevTools:

  1. Open a webpage that uses WebMCP, such as Idea Board - Imperative WebMCP API Playground, in a new tab or window.

  2. Right-click the page, and then select Inspect.

    Or, press any of the following keys:

    • F12
    • Ctrl+Shift+I (Windows, Linux)
    • Command+Option+I (macOS)

    DevTools opens.

  3. In DevTools, on the Activity Bar, select the Application icon Application tab. If that tab isn't visible, click the More tools (More tools icon) button, and then click Application.

    The Application tool is displayed.

  4. In the outline on the left, select Application > WebMCP.

    The Application > WebMCP page is displayed, including the following sections:

    • Tool activity - Lists the tools that have been invoked.
    • Available tools - Lists the tools that are currently registered on the page, including both declarative and imperative tools.

    The Application > WebMCP page

  5. In the Available tools section, select a tool, such as add-sticky.

    Next to the tool name, the Details pane is displayed, showing details about the tool.

  6. To run the selected tool: In the Run tool section of the Details pane, enter the required input parameters, and then click the Run tool button.

    The webpage runs the tool, such as the add-sticky tool. In this example, a new sticky note appears in the demo page, containing the text that you entered in the input parameters.

    In the Application > WebMCP page, in the Tool activity section at the top, the list of calls is displayed and updated to show the latest tool call (in this example, add-sticky). The WebMCP page shows the details of the add-sticky tool:

    Details of the add-sticky tool

Test end-to-end agent interactions with WebMCP Explorer

To test how an LLM actually discovers, selects, and chains your tools in an end-to-end agentic loop, use WebMCP Explorer. WebMCP Explorer is a browser extension that provides an agent that's powered by your configured large language model (LLM) provider, along with a view for inspecting and running tools.

Use WebMCP Explorer only on sites that you own, control, or trust. The extension sends the page's tool descriptions and results to the configured model as-is. A page could use that content to manipulate the model. Don't use sensitive data in test prompts or tool results.

To install WebMCP Explorer:

  1. Enable WebMCP locally, as described above.

  2. Open a terminal window, go to the directory where you want to clone the repo, and then enter:

    git clone https://github.com/MicrosoftEdge/webmcp-labs.git
    
  3. In Microsoft Edge, go to edge://extensions, in a new tab or window.

  4. In the sidebar, turn on Developer mode.

  5. Click the Load unpacked button.

  6. In the file explorer, go to the cloned repo, select the webmcp-labs\webmcp-explorer\dist directory, and then click the Select Folder button.

    In the edge://extensions page, the WebMCP Explorer extension is displayed in the list of installed extensions:

    The WebMCP Explorer extension, listed as installed

  7. Click the WebMCP Explorer extension icon. If the icon isn't visible in the toolbar, click Extensions, and then click WebMCP Explorer.

    WebMCP Explorer appears in the Microsoft Edge sidebar.

To configure the model provider and run the demo:

  1. In WebMCP Explorer, click the Config tab.

  2. Under Provider, select an LLM provider, and then enter the required connection details.

    The model must support tool calling. For provider-specific instructions, see Provider setup in WebMCP Explorer.

  3. Click the Save button, and then click the Test Connection button:

    The Config tab in WebMCP Explorer, showing the provider settings, the Save button, and the Test Connection button

    The message "Connection successful!" appears below the Test Connection button.

  4. In a new tab, go to the Contoso Pizza demo.

  5. In WebMCP Explorer, click the Agent tab.

  6. In the Goal text box, enter Order pepperoni pizza for a party of 10, deliver to 123 main road, and then press Enter.

    The extension uses the configured model and the page's WebMCP tools to complete the goal:

    The Contoso Pizza demo site, with the WebMCP Explorer sidebar open. The Agent tab is selected, and WebMCP is using tools on the site.

To inspect a site's tools without running a complete agent task, use the Tools tab. The Tools tab lists the tools that are registered on the current page, and lets you run a tool with custom JSON input. For example, at the Contoso Pizza demo page, with the WebMCP Explorer extension displayed in the Microsoft Edge sidebar, select the Tools tab to display the currently registered browse and create-order tools:

The WebMCP Explorer sidebar

To update the extension, pull the latest changes in the cloned repo, and then reload the extension at edge://extensions.

Generate tool definitions by using your AI coding tool

If you use an AI coding tool to build your site, Modern Web Guidance can help that tool define WebMCP tools for you. Modern Web Guidance is a set of skills that provides current web platform guidance and browser compatibility information to AI coding tools.

WebMCP is currently in origin trial. By default, Modern Web Guidance doesn't provide guidance for origin-trial features, so installing the skills isn't enough to access its WebMCP guides.

To install Modern Web Guidance and enable its WebMCP guidance:

  1. If not done already, install an up-to-date version of Node.js from Node.js. Modern Web Guidance requires Node.js version 22 or later.

  2. In a terminal, run the following command, and then follow the installation prompts:

    npx modern-web-guidance@latest install
    

    For other installation methods, see Installation in Get started with Modern Web Guidance.

  3. From the site's project root directory, enable guidance for origin-trial features:

    npx modern-web-guidance@latest set-allow-origin-trials
    

    Run this command in a terminal rather than through your AI coding tool, because agents can't enable guidance for origin-trial features on their own.

This opt-in enables guidance for the AI coding tool only. This opt-in doesn't enable WebMCP in Microsoft Edge or register the site for the origin trial.

See also:

Define WebMCP tools by using the JavaScript API

If your site uses JavaScript functions to handle actions that you want to expose as WebMCP tools, you can define those tools by using the JavaScript API.

Register a JavaScript tool

Use document.modelContext.registerTool() to expose an existing JavaScript function as a tool. The method returns a promise. Registration can fail, for example, if the tool name isn't valid, the description is empty, or another tool with the same name is already registered.

Before registering tools, check whether WebMCP is available:

if ("modelContext" in document) {
  // Register the page's WebMCP tools.
}

For example, a flight booking site might already have an asynchronous getAndDisplayFlights() function. This function accepts search criteria, fetches flights, displays them on the page, and returns results that can be serialized as JSON.

The following example code exposes the getAndDisplayFlights() function as a tool:

if ("modelContext" in document) {
  await document.modelContext.registerTool({
    name: "search-flights",
    title: "Search flights",
    description: "Searches for one-way or round-trip flights.",
    inputSchema: {
      type: "object",
      properties: {
        origin: {
          type: "string",
          description: "Departure airport or city"
        },
        destination: {
          type: "string",
          description: "Arrival airport or city"
        },
        departureDate: {
          type: "string",
          format: "date",
          description: "Departure date"
        },
        returnDate: {
          type: "string",
          format: "date",
          description: "Return date, for round-trip flights"
        }
      },
      required: ["origin", "destination", "departureDate"]
    },
    annotations: { readOnlyHint: true },
    async execute(input, { signal }) {
      return await getAndDisplayFlights({ ...input, signal });
    }
  });
}

This example assumes that getAndDisplayFlights() validates the search criteria and passes the signal to its network requests. Before registering the tool, define the function in the site's code. Use this code snippet within a JavaScript module or within an asynchronous function, because the snippet uses await.

The tool definition includes the following properties:

Property Required Description
name Yes A unique tool name, from 1 to 128 characters. Use ASCII letters, digits, underscores (_), hyphens (-), or dots (.).
title No A short label that the browser can display in its UI. Localize the label for the end user's language.
description Yes A description of what the tool does.
inputSchema No A JSON Schema object that describes the input parameters. If the tool doesn't take any input, omit this property.
outputSchema No A JSON Schema object that describes the structure of the tool's return value. Use this for tools that return structured data or IDs for follow-up calls. For simple actions, to conserve context tokens, omit this.
execute Yes A synchronous or asynchronous function that runs the action. The function receives the input parameters and receives an execution options object that contains a signal. The result is serialized as JSON and returned to the agent.
annotations No Hints about the tool's behavior. See Describe tool behavior with annotations, below.

Treat tool input as untrusted. A schema describes the input, but doesn't replace validation in the tool or on the server. See Security best practices for WebMCP tools, below.

For the current API definition, see WebMCP.

Describe tool behavior with annotations

Use the tool's annotations property to give agents hints about the tool's behavior.

Annotation When to set the annotation to true
readOnlyHint The tool only reads data but doesn't modify data.
untrustedContentHint The tool returns content that the site doesn't control, such as end-user reviews.
consequentialHint The tool has significant real-world or irreversible effects, such as booking a flight, sending money, or deleting data.
debugging The tool is intended for debugging or developer tooling, rather than for end users.

These hints default to false. An agent can use these hints to decide whether to request confirmation or handle the output with extra care. These hints aren't security controls, and they don't replace permission checks or confirmation in the site.

Unregister a JavaScript tool

To unregister a tool, pass an AbortSignal in the second argument to registerTool(), and then call the corresponding controller's abort() method:

const registrationController = new AbortController();

await document.modelContext.registerTool({
  name: "search-flights",
  // ...description, inputSchema, and execute
}, {
  signal: registrationController.signal
});

// When the action is no longer available on this page:
registrationController.abort();

Before registering another tool that has the same name, unregister the previous tool.

Unregistering a tool doesn't cancel an execution that's already running.

Handle cancellation of a tool call

The browser passes an execution options object to the tool's execute function. When an agent cancels a tool call, the browser aborts the object's signal.

Pass this signal to long-running work, such as fetch() calls. The above flight search example passes the signal to getAndDisplayFlights(), so that the function can cancel its network requests.

WebMCP uses signals for two different purposes:

  • Registration signal: The site creates this signal and then passes the signal to registerTool(). Aborting this signal unregisters the tool.
  • Execution signal: The browser creates this signal and then passes the signal to execute(). Aborting this signal cancels a tool call, not the tool's registration.

After cancellation, the agent doesn't receive the tool's return value. Cancellation doesn't undo work that's already completed. For a payment, booking, or other irreversible action, check signal.aborted before committing the action, and keep the site's normal confirmation and server-side checks.

Share, discover, and execute tools across origins

By default, tools are only visible to same-origin documents. To expose a tool to a trusted cross-origin document (such as a parent page or embedded iframe), pass secure origins in the exposedTo option of registerTool():

await document.modelContext.registerTool(toolDefinition, {
  exposedTo: ["https://example.com"]
});

An in-page agent can discover available tools with document.modelContext.getTools(), execute a tool with executeTool(), and listen for changes with the toolchange event.

Cross-origin tools are included only when both sides opt in: the registering page lists the caller in exposedTo, and the caller requests that origin in fromOrigins.

// Retrieve same-origin tools and opted-in tools from a partner origin:
const tools = await document.modelContext.getTools({
  fromOrigins: ["https://partner.example"]
});

const flightTool = tools.find(tool => tool.name === "search-flights");
if (flightTool) {
  const result = await document.modelContext.executeTool(
    flightTool,
    { origin: "SEA", destination: "JFK", departureDate: "2026-06-15" }
  );
}

// Listen for tool registration or unregistration changes:
document.modelContext.addEventListener("toolchange", () => {
  // Refresh the agent's tool list.
});

Pass a Tool object that's returned by getTools() to executeTool(). If that registration is removed, executeTool() rejects the call with a NotFoundError, and you must call getTools() again.

Only expose tools to origins that you trust to read user data, or that you trust to take actions on behalf of the end user.

Define WebMCP tools by using the HTML form API

If your site uses HTML forms to handle actions that you want to expose as WebMCP tools, you can declare those forms as tools using the HTML form API.

Register an HTML form as a tool

Use the declarative API to expose an existing HTML form. Add toolname and tooldescription to the <form>, and describe its input parameters by using toolparamdescription:

<form toolname="search-flights"
      tooldescription="Searches for one-way or round-trip flights."
      action="/search"
      method="post">
  <label for="origin">Origin</label>
  <input id="origin" name="origin" required
         toolparamdescription="Departure airport or city">

  <label for="destination">Destination</label>
  <input id="destination" name="destination" required
         toolparamdescription="Arrival airport or city">

  <label for="departureDate">Departure date</label>
  <input type="date" id="departureDate" name="departureDate" required
         toolparamdescription="Departure date">

  <label for="returnDate">Return date</label>
  <input type="date" id="returnDate" name="returnDate"
         toolparamdescription="Return date, for round-trip flights">

  <button type="submit">Search</button>
</form>

The example assumes that the site handles flight searches at /search. Browsers that don't support WebMCP ignore the tool attributes, and use the form normally.

The declarative API supports these attributes:

Attribute Applies to Required Description
toolname <form> Yes A unique tool name, with the same character and length limits as a JavaScript tool name.
tooldescription <form> Yes A description of what the form does.
toolautosubmit <form> No Allows the browser to submit the form automatically when an agent invokes the tool.
toolparamdescription Form controls, such as <input>, <select>, and <textarea> No Describes a tool input parameter. If omitted, Microsoft Edge uses the control's label text or, if no label is available, its aria-description.

Keep the form's labels and other accessibility information. Tool descriptions don't replace labels for end users.

How form controls become tool parameters

Microsoft Edge generates a tool input schema from the form's controls:

  • A control's name provides the parameter name.
  • The required attribute identifies required parameters.
  • A <select> element's option values provide the allowed values.

To inspect how Microsoft Edge exposes the form, use either:

  • The Application > WebMCP page in DevTools.
  • The Tools tab in WebMCP Explorer.

To unregister a declarative tool, remove the toolname or tooldescription attribute from the <form> element.

Control form submission by an agent

When an agent invokes a declarative tool, Microsoft Edge fills the form with the agent's input values.

By default, Microsoft Edge puts focus on the form's submit button, so that the end user can review and submit the form. To submit the form automatically instead, add the boolean toolautosubmit attribute:

<form toolname="search-flights"
      tooldescription="Searches for one-way or round-trip flights."
      toolautosubmit
      action="/search"
      method="post">
  <!-- Keep the form's labeled controls and submit button here. -->
</form>

Don't use automatic submission as a replacement for confirmation of a purchase, payment, or other consequential action.

While the tool is active, its form matches the :tool-form-active CSS pseudo-class, and its submit button matches :tool-submit-active. Use these pseudo-classes to highlight the form, as follows:

form:tool-form-active {
  outline: 2px dashed blue;
}

button:tool-submit-active {
  outline: 2px dashed red;
}

The toolactivated and toolcancel events on document.modelContext also let the page respond to tool activity:

document.modelContext.addEventListener("toolactivated", ({ toolName }) => {
  console.log(`Tool activated: ${toolName}`);
});

document.modelContext.addEventListener("toolcancel", ({ toolName }) => {
  console.log(`Tool canceled: ${toolName}`);
});

Customize a form tool's return value

The declarative API adds two members to SubmitEvent:

Member Description
agentInvoked A boolean that indicates whether an agent triggered the form submission.
respondWith() A method that accepts a promise for the tool's return value. Before calling this method, first call preventDefault().

If the form already handles form submission via JavaScript, reuse that handler to return results to the agent. For example, the following handler uses the same getAndDisplayFlights() function as the JavaScript tool:

const form = document.querySelector('form[toolname="search-flights"]');

form.addEventListener("submit", event => {
  if (!event.agentInvoked) {
    return;
  }

  event.preventDefault();

  const input = Object.fromEntries(new FormData(form));
  event.respondWith(getAndDisplayFlights(input));
});

This example assumes that getAndDisplayFlights() validates the input, displays results or errors on the page, and returns a promise for a JSON-serializable result. For actionable errors such as invalid input or a failed search, resolve the promise with a structured error payload (for example, { error: "No flights found for those dates." }), rather than rejecting the promise, because a rejected promise would only return a generic failure, without forwarding the error details to the agent.

For an end-user submission, the handler leaves the form's normal submission behavior unchanged. For an agent submission, the handler prevents navigation, and returns the function's result to the agent.

The design of responses from forms that navigate to another page is still under discussion. See Getting the form response to the agent in WebMCP declarative API.

Security best practices for WebMCP tools

A tool runs using the page's client-side access, so an agent can trigger actions in the end user's signed-in session.

Treat every tool call as untrusted input, because an agent calling your tool could be influenced by prompt injection from another webpage or untrusted content.

Protect user actions and sessions

  • Don't register tools for actions that aren't available to the end user in the current page or in the current authentication state.
  • Validate all tool inputs in both client-side code and server-side handlers.
    • Keep all existing authentication and authorization checks.
  • Set consequentialHint: true on JavaScript tools that execute high-stakes or irreversible actions, so that the browser or agent can request user confirmation.
    • For the highest-risk actions, require server-side verification, because annotations are merely advisory hints.
  • Before committing irreversible work:
    • Enforce rate limits.
    • Make mutating tools idempotent or bound to fresh state tokens.
    • Check signal.aborted.

Help agents defend against prompt injection

The agent is responsible for defending against prompt injection. Your site can also reduce the attack surface, as follows:

  • Don't interpolate user-generated or untrusted content into tool names, descriptions (description or tooldescription), or parameter descriptions.
  • Return structured data that includes only the fields that are needed, rather than returning raw HTML or large freeform text blocks, which can carry hidden instructions or unrelated user-generated content.
  • When a tool returns user-generated or external content, set untrustedContentHint: true.

Control the data and origin boundaries

  • Request only the input parameters that the tool actually needs.
  • Return only the information that the agent needs. Tool results can be sent to the agent's model provider.
  • Only expose tools via exposedTo or delegate allow="tools" to origins that you trust to read that user data or act on the user's behalf. Browser extensions that have host permissions can still inspect and invoke a page's tools.
  • Don't expose debugging: true tools or sensitive internal actions in production, unless they are needed and are protected by suitable access controls.

For the community's current discussion, see Security and Privacy Considerations in the WebMCP repo.

Send feedback

For feedback about the WebMCP API design, use the Issues page in the WebMCP repo.

For issues with the Microsoft Edge origin trial, use the Feedback link on the WebMCP registration page.

For issues with WebMCP Explorer or the demos, use the Issues page in the WebMCP Labs repo.

See also

GitHub:

Packages and framework integrations: