Title: WebMCP
Shortname: webmcp
Level: None
Status: CG-DRAFT
Group: webml
Repository: webmachinelearning/webmcp
URL: https://webmachinelearning.github.io/webmcp
Editor: Brandon Walderman, Microsoft https://www.microsoft.com, brwalder@microsoft.com, w3cid 115877
Editor: Khushal Sagar, Google https://www.google.com, khushalsagar@google.com, w3cid 122787
Editor: Dominic Farolino, Google https://www.google.com, domfarolino@google.com, w3cid 102763
Abstract: The WebMCP API enables web applications to provide JavaScript-based tools to AI agents.
Markup Shorthands: markdown yes, css no
Complain About: accidental-2119 yes, missing-example-ids yes
Assume Explicit For: yes
Default Biblio Status: current
Boilerplate: omit conformance
Indent: 2
Die On: warning
spec: html; type: dfn; urlPrefix: https://html.spec.whatwg.org/C
  text: create and initialize a Document object; url: initialise-the-document-object
  # Because `text` and `url` are the same (modulo slashes), we should be able to
  # exclude `url`. But the colon breaks the URL in `text`, forcing us to include
  # `url`.
  text:is initial about:blank; url: is-initial-about:blank
  text: associated Navigator
spec: SECURE-CONTEXTS; urlPrefix: https://w3c.github.io/webappsec-secure-contexts/
  type: abstract-op
    text: is origin potentially trustworthy?; url: is-origin-trustworthy

Introduction

WebMCP API is a new JavaScript interface that allows web developers to expose their web application functionality as “tools” - JavaScript functions with natural language descriptions and structured schemas that can be invoked by [=agents=], [=browser's agents=], and [=assistive technologies=]. Web pages that use WebMCP can be thought of as Model Context Protocol [[!MCP]] servers that implement tools in client-side script instead of on the backend. WebMCP enables collaborative workflows where users and agents work together within the same web interface, leveraging existing application logic while maintaining shared context and user control.

Terminology

An agent is an autonomous assistant that can understand a user’s goals and take actions on the user’s behalf to achieve them. Today, these are typically implemented by large language model (LLM) based [=AI platforms=], interacting with users via text-based chat interfaces. A browser’s agent is an [=agent=] provided by or through the browser that could be built directly into the browser or hosted by it, for example, via an extension or plug-in. An AI platform is a provider of agentic assistants such as OpenAI’s ChatGPT, Anthropic’s Claude, or Google’s Gemini.

Supporting concepts

A model context is a [=struct=] with the following [=struct/items=]:
: tool map :: a [=map=] whose [=map/keys=] are [=strings=] and whose [=map/values=] are [=tool definition=] [=structs=].
A tool definition is a [=struct=] with the following [=struct/items=]:
: name :: a [=string=] uniquely identifying a tool registered within a [=model context=]'s [=model context/tool map=]; it is the same as the [=map/key=] identifying this object. The [=tool definition/name=]'s [=string/length=] must be between 1 and 128, inclusive, and only consist of [=ASCII alphanumeric=] [=code points=], U+005F LOW LINE (_), U+002D HYPHEN-MINUS (-), and U+002E FULL STOP (.). : title :: A [=string=]-or-null representing a human-readable title of the tool for use in user interfaces. Note: If {{ModelContextTool/title}} is not provided, the user agent is free to use a different value for display. : description :: a [=string=]. : input schema :: a [=string=]. Note: For tools registered by the imperative form of this API (i.e., {{ModelContext/registerTool()}}), this is the stringified representation of {{ModelContextTool/inputSchema}}. For tools registered [declaratively](https://github.com/webmachinelearning/webmcp/pull/76), this will be a stringified JSON Schema object created by the [=synthesize a declarative JSON Schema object algorithm=]. [[!JSON-SCHEMA]] : execute steps :: a set of steps to invoke the tool. Note: For tools registered imperatively, these steps will simply invoke the supplied {{ToolExecuteCallback}} callback. For tools registered [declaratively](https://github.com/webmachinelearning/webmcp/pull/76), this will be a set of "internal" steps that have not been defined yet, that describe how to fill out a <{form}> and its [=form-associated elements=]. : read-only hint :: a [=boolean=], initially false. : untrusted content hint :: a [=boolean=], initially false. : exposed origins :: a [=list=] or [=origins=], initially [=list/empty=].

To notify documents of a tool change given a {{Document}} |tool owner| and a [=list=] of [=origins=] |exposed origins|, run these steps: 1. [=Assert=]: these steps are running on |tool owner|'s [=relevant agent=]'s [=agent/event loop=]. 1. Let |navigablesToNotify| be |tool owner|'s [=node navigable=]'s [=navigable/traversable navigable=]'s [=Document/descendant navigables=]. 1. [=list/For each=] |navigable| of |navigablesToNotify|: 1. Let |targetDocument| be |navigable|'s [=navigable/active document=]. 1. If |targetDocument| is not [=allowed to use=] the "{{tools}}" feature, then [=iteration/continue=]. 1. If [=tool is visible to an origin=] given |tool owner|'s [=Document/origin=], |exposed origins|, and |targetDocument|'s [=Document/origin=], then [=queue a global task=] on the [=webmcp task source=] given |targetDocument|'s [=relevant global object=] to [=fire an event=] named {{ModelContext/toolchange}} at |targetDocument|'s [=relevant global object=]'s [=associated Navigator|associated Navigator=]'s [=Navigator/associated ModelContext|associated ModelContext=].

This algorithm's use of the [=webmcp task source=] means that the timing between firing the {{ModelContext/toolchange}} event, and other tasks queued after this algorithm, cannot be relied upon. For example:

navigator.modelContext.ontoolchange = e => console.log('Parent toolchange'); iframe.contentWindow.navigator.modelContext.ontoolchange = e => console.log('Child toolchange'); // Queues a task to fire `toolchange`, on the `webmcp task source`. navigator.modelContext.registerTool({ name: "tool_name", description: "tool_desc", execute: async () => {} }); // Queues a task on the `timer task source`. setTimeout(() => console.log('Post-register task')); // `Parent toolchange` will always log before `Child toolchange`. // But `Post-register task` can log before, in between, or after both.
To determine if a tool is visible to an origin given an [=origin=] |tool owner origin|, a [=list=] of [=origins=] |exposed origins|, and an [=origin=] |target origin|, run these steps: 1. If |tool owner origin| is [=same origin=] with |target origin|, then return true. 1. [=list/For each=] |origin| of |exposed origins|: 1. If |target origin| is [=same origin=] with |origin|, then return true. 1. Return false.
To unregister a tool given a {{ModelContext}} |modelContext| and a [=string=] |tool name|, run these steps: 1. [=Assert=]: these steps are running on |modelContext|'s [=relevant agent=]'s [=agent/event loop=]. 1. Let |tool map| be |modelContext|'s [=ModelContext/internal context=]'s [=model context/tool map=]. 1. [=Assert=] |tool map|[|tool name|] [=map/exists=]. 1. Let |exposed origins| be |tool map|[|tool name|]'s [=tool definition/exposed origins=]. 1. [=map/Remove=] |tool map|[|tool name|]. 1. Run [=notify documents of a tool change=] given |modelContext|'s [=relevant global object=]'s [=associated Document|associated Document=] and |exposed origins|.

API

Each {{Navigator}} object has an associated {{ModelContext}}, which is a {{ModelContext}} object. Upon creation of the {{Navigator}} object, its [=Navigator/associated ModelContext|associated ModelContext=] must be set to a [=new=] {{ModelContext}} object created in the {{Navigator}}'s [=relevant realm=]. It only ever changes from one `{{ModelContext}}` instance to another the first time the {{Navigator/modelContext}} getter is accessed after a navigation away from the [=is initial about:blank|initial about:blank=], Note: The reason a {{Navigator}}'s [=Navigator/associated ModelContext|associated ModelContext=] changes is as follows: {{ModelContext}} is a {{Document}}-scoped registry of tools, but because it is accessed from an object that is shared between two {{Document}} objects, it gets updated when the {{Navigator}}'s [=relevant global object=]'s [=associated Document|associated Document=] gets updated, to ensure that tools registered within the [=is initial about:blank|initial about:blank=] {{Document}} do not mix with tools in the subsequent [=same origin=] {{Document}} See step 6.1 in [=create and initialize a Document object|create and initialize a Document object=]. Each {{ModelContext}} object has a creation {{Document}}, which is its [=relevant global object=]s [=associated Document|associated Document=] at the time of creation.
partial interface Navigator { [SecureContext] readonly attribute ModelContext modelContext; };
The modelContext getter steps are: 1. If [=this=]'s [=Navigator/associated ModelContext|associated ModelContext=]'s [=ModelContext/creation Document| creation Document=] does not equal [=this=]'s [=relevant global object=]'s [=associated Document|associated Document=], then set [=this=]'s [=Navigator/associated ModelContext|associated ModelContext=] to a [=new=] {{ModelContext}} object. 1. Return [=this=]'s [=Navigator/associated ModelContext|associated ModelContext=] object.

ModelContext Interface

The {{ModelContext}} interface provides methods for web applications to register and manage tools that can be invoked by [=agents=]. [Exposed=Window, SecureContext] interface ModelContext : EventTarget { undefined registerTool(ModelContextTool tool, optional ModelContextRegisterToolOptions options = {}); attribute EventHandler ontoolchange; }; Each {{ModelContext}} object has an associated internal context, which is a [=model context=] [=struct=] created alongside the {{ModelContext}}.
navigator.{{Navigator/modelContext}}.{{ModelContext/registerTool(tool, options)}}

Registers a tool that [=agents=] can invoke. Throws an exception if a tool with the same name is already registered, if the given {{ModelContextTool/name}} or {{ModelContextTool/description}} are empty strings, or if the {{ModelContextTool/inputSchema}} is invalid.

The registerTool(tool, options) method steps are: 1. Let |tool owner| be [=this=]'s [=relevant global object=]'s [=associated Document|associated Document=]. 1. If |tool owner| is not [=Document/fully active=], then [=exception/throw=] an "{{InvalidStateError}}" {{DOMException}}. 1. If |tool owner| is not [=allowed to use=] the "{{tools}}" feature, then [=exception/throw=] a "{{NotAllowedError}}" {{DOMException}}. 1. Let |tool map| be [=this=]'s [=ModelContext/internal context=]'s [=model context/tool map=]. 1. Let |tool name| be |tool|'s {{ModelContextTool/name}}. 1. Let |tool title| be |tool|'s {{ModelContextTool/title}}. 1. If |tool map|[|tool name|] [=map/exists=], then [=exception/throw=] an {{InvalidStateError}} {{DOMException}}. 1. If |tool name| or {{ModelContextTool/description}} is an empty string, then [=exception/throw=] an {{InvalidStateError}} {{DOMException}}. 1. If either |tool name| is the empty string, or its [=string/length=] is greater than 128, or if |tool name| contains a [=code point=] that is not an [=ASCII alphanumeric=], U+005F (_), U+002D (-), or U+002E (.), then [=exception/throw=] an {{InvalidStateError}}. 1. Let |stringified input schema| be the empty string. 1. If |tool|'s {{ModelContextTool/inputSchema}} [=map/exists=], then set |stringified input schema| to the result of [=serializing a JavaScript value to a JSON string=], given |tool|'s {{ModelContextTool/inputSchema}}.

The serialization algorithm above throws exceptions in the following cases:

  1. Throws a new {{TypeError}} when the backing "JSON.stringify()" yields undefined, e.g., "inputSchema: { toJSON() {return HTMLDivElement;}}", or "inputSchema: { toJSON() {return undefined;}}".

  2. Re-throws exceptions thrown by "JSON.stringify()", e.g., when "inputSchema" is an object with a circular reference, etc.

1. Let |read-only hint| be true if |tool|'s {{ModelContextTool/annotations}} [=map/exists=] and its {{ToolAnnotations/readOnlyHint}} is true. Otherwise, let it be false. 1. Let |untrusted content hint| be true if |tool|'s {{ModelContextTool/annotations}} [=map/exists=] and its {{ToolAnnotations/untrustedContentHint}} is true. Otherwise, let it be false. 1. Let |signal| be |options|'s {{ModelContextRegisterToolOptions/signal}}. 1. If |signal| [=map/exists=], then: 1. If |signal| is [=AbortSignal/aborted=], then optionally [=report a warning to the console=] indicating that the tool was not registered because the {{AbortSignal}} was already [=AbortSignal/aborted=], and return. 1. [=AbortSignal/add|Add an abort algorithm=] to |signal| that [=model context/unregisters a tool=] given [=this=] and |tool name|. 1. Let |exposed origins| be an empty [=list=] of [=origins=]. 1. If |options|'s {{ModelContextRegisterToolOptions/exposedTo}} [=map/exists=], then: 1. [=list/For each=] |origin| of |options|'s {{ModelContextRegisterToolOptions/exposedTo}}: 1. Let |parsedURL| be the result of running the [=URL parser=] on |origin|. 1. If |parsedURL| is failure or its [=url/origin=] is not [$is origin potentially trustworthy?|potentially trustworthy$], then [=exception/throw=] an "{{SecurityError}}" {{DOMException}}. 1. [=list/Append=] |parsedURL|'s [=url/origin=] to |exposed origins|. 1. Let |tool definition| be a new [=tool definition=], with the following [=struct/items=]: : [=tool definition/name=] :: |tool name| : [=tool definition/title=] :: |tool title| : [=tool definition/description=] :: |tool|'s {{ModelContextTool/description}} : [=tool definition/input schema=] :: |stringified input schema| : [=tool definition/execute steps=] :: steps that invoke |tool|'s {{ModelContextTool/execute}} : [=tool definition/read-only hint=] :: |read-only hint| : [=tool definition/untrusted content hint=] :: |untrusted content hint| : [=tool definition/exposed origins=] :: |exposed origins| 1. Set [=this=]'s [=ModelContext/internal context=][|tool name|] to |tool definition|. 1. Run [=notify documents of a tool change=] given |tool owner| and |exposed origins|.

ModelContextTool Dictionary

The {{ModelContextTool}} dictionary describes a tool that can be invoked by [=agents=]. dictionary ModelContextTool { required DOMString name; // Because `title` is for display in possibly native UIs, this must be a `USVString`. // See https://w3ctag.github.io/design-principles/#idl-string-types. USVString title; required DOMString description; object inputSchema; required ToolExecuteCallback execute; ToolAnnotations annotations; }; dictionary ToolAnnotations { boolean readOnlyHint = false; boolean untrustedContentHint = false; }; callback ToolExecuteCallback = Promise<any> (object input, ModelContextClient client);
tool["{{ModelContextTool/name}}"]

A unique identifier for the tool. This is used by [=agents=] to reference the tool when making tool calls.

tool["{{ModelContextTool/title}}"]

A label for the tool. This is used by the user agent to reference the tool in the user interface.

It is recommended that this string be localized to the user's {{NavigatorLanguage/language}}.

tool["{{ModelContextTool/description}}"]

A natural language description of the tool's functionality. This helps [=agents=] understand when and how to use the tool.

tool["{{ModelContextTool/inputSchema}}"]

A JSON Schema [[!JSON-SCHEMA]] object describing the expected input parameters for the tool.

tool["{{ModelContextTool/execute}}"]

A callback function that is invoked when an [=agent=] calls the tool. The function receives the input parameters and a {{ModelContextClient}} object.

The function can be asynchronous and return a promise, in which case the [=agent=] will receive the result once the promise is resolved.

tool["{{ModelContextTool/annotations}}"]

Optional annotations providing additional metadata about the tool's behavior.

The {{ToolAnnotations}} dictionary provides optional metadata about a tool:
: readOnlyHint :: If true, indicates that the tool does not modify any state and only reads data. This hint can help [=agents=] make decisions about when it is safe to call the tool. : untrustedContentHint :: If true, indicates that the tool's output contains data that is untrusted, from the perspective of the author registering the tool.

ModelContextRegisterToolOptions Dictionary

The {{ModelContextRegisterToolOptions}} dictionary carries information pertaining to a tool's registration, in contrast with the {{ModelContextTool}} dictionary which carries the tool definition itself. dictionary ModelContextRegisterToolOptions { AbortSignal signal; sequence<USVString> exposedTo; };
tool["{{ModelContextRegisterToolOptions/signal}}"]

An {{AbortSignal}} that unregisters the tool when aborted.

exposedTo["{{ModelContextRegisterToolOptions/exposedTo}}"]

An array of origins that control which documents this tool is exposed to, in the current document's tree.

ModelContextClient Interface

The {{ModelContextClient}} interface represents an [=agent=] executing a tool provided by the site through the {{ModelContext}} API. [Exposed=Window, SecureContext] interface ModelContextClient { Promise<any> requestUserInteraction(UserInteractionCallback callback); }; callback UserInteractionCallback = Promise<any> ();
client.{{ModelContextClient/requestUserInteraction(callback)}}

Asynchronously requests user input during the execution of a tool.

The callback function is invoked to perform the user interaction (e.g., showing a confirmation dialog), and the promise resolves with the result of the callback.

The requestUserInteraction(callback) method steps are: 1. TODO: fill this out.

Declarative WebMCP

This section is entirely a TODO. For now, refer to the [explainer draft](https://github.com/webmachinelearning/webmcp/pull/76).
The synthesize a declarative JSON Schema object algorithm, given a <{form}> element |form|, runs the following steps. They return a [=map=] representing a JSON Schema object. [[!JSON-SCHEMA]] 1. TODO: Derive a conformant JSON Schema object from |form| and its [=form-associated elements=].
{
  "mcp": {
    "href": "https://modelcontextprotocol.io/specification/latest",
    "title": "Model Context Protocol (MCP) Specification",
    "publisher": "The Linux Foundation"
  },
  "json-schema": {
    "href": "https://json-schema.org/draft/2020-12/json-schema-core.html",
    "title": "JSON Schema: A Media Type for Describing JSON Documents",
    "publisher": "JSON Schema"
  }
}

Events

The following are the [=event handlers=] (and their corresponding [=event handler event types=]) that must be supported, as [=event handler IDL attributes=], by all {{ModelContext}} objects:
[=Event handler=] [=Event handler event type=]
ontoolchange toolchange

Permissions policy integration

Access to the APIs in this specification is gated behind the [=policy-controlled feature=] "tools", which has a [=policy-controlled feature/default allowlist=] of [=default allowlist/'self'=].

Interaction with agents

Event loop integration

A web site's functionality is exposed to [=agents=] as tools that live in a [=Document=]'s [=event loop=], that get registered with the APIs in this specification. The [=user agent=]'s [=browser agent=] runs [=in parallel=] to any [=event loops=] associated with a {{ModelContext}} [=relevant global object=]. Steps running on the [=browser agent=] get queued on its AI agent queue, which is the result of [=starting a new parallel queue=]. Conversely, steps queued *from* the [=browser agent=] onto the [=event loop=] of a given {{ModelContext}} object (i.e., the "main thread" where JavaScript runs) are queued on its [=relevant global object=]'s webmcp task source.

Page observations

This section is non-normative. It contains an example of infrastructure that a [=user agent=] might employ to expose a tab's tools to a [=browser agent=], and illustrates how that infrastructure interacts with the web platform, for the purposes of implementer guidance.
In-page [=agents=] implemented in JavaScript can "observe" the tools that a page offers by using the {{ModelContext}} APIs directly, and any other platform APIs to obtain necessary context about the page in order to actuate it appropriately. The [=browser agent=], on the other hand, does not run JavaScript on the page. Instead, it obtains a view of the page's tools and any other relevant context by getting an [=observation=]. An observation is an [=implementation-defined=] data structure containing at least a tool map, which is a [=map=] whose [=map/keys=] are [=Document/unique ID=]s, and whose [=map/values=] are [=lists=] of [=tool definition=] [=structs=]. Note: An [=observation=] is usually a "snapshot" distillation of a page being presented to the user, along with any other state the [=user agent=] believes is relevant for the [=browser agent=]; this often includes screenshots of the page, not just a DOM serialization. See [Annotated Page Content (APC)](https://chromium.googlesource.com/chromium/src.git/+/main/third_party/blink/renderer/modules/content_extraction/readme.md) in the Chromium project for an example of what might contribute to an observation.
To perform an observation given a [=top-level traversable=] |traversable|, run these steps: 1. [=Assert=]: This algorithm is running in the [=browser agent=]'s [=AI agent queue=]. 1. [=Assert=]: |traversable|'s [=navigable/active document=] is not [=Document/fully active=]. 1. Let |observation| be a new [=observation=]. 1. Let |flat descendants| be the [=Document/inclusive descendant navigables=] of |traversable|'s [=navigable/active document=]. 1. [=list/For each=] [=navigable=] |descendant| of |flat descendants|: 1. Let |document| be |descendant|'s [=navigable/active document=]'s. 1. Let |id| be |document|'s [=Document/unique ID=]. 1. Set |observation|'s [=observation/tool map=][|id|] = |document|'s [=relevant global object=]'s [=associated Navigator|associated Navigator=]'s [=Navigator/associated ModelContext|associated ModelContext=]'s [=ModelContext/internal context=]'s [=model context/tool map=]'s [=map/values=], which are [=tool definitions=]. 1. Perform any [=implementation-defined=] steps to add anything to |observation| that the [=user agent=] might deem useful or necessary, besides just populating the [=observation/tool map=]. This might include annotated screenshots of the page, parts of the accessibility tree, etc. 1. Perform any [=implementation-defined=] steps with |observation| and the [=browser agent=], to expose the |observation|'s [=observation/tool map=] to the [=browser agent=] in whatever way it accepts. Note: Despite the name of this API (i., Web*MCP*), this specification does not prescribe the format in which tools are exposed to the [=browser agent=]. Browsers are free to distill and expose tools via Model Context Protocol, other proprietary "function calling" methods, or any other way it deems appropriate. Advisement: Implementations are expected to convey to the [=browser agent=] any relevant security information associated with [=tool definitions=], such as the originating [=origin=], among other things, so that the backing model has an idea of the different parties at play, and can most safely carry out the end user's intent.
Each {{Document}} object has a unique ID, which is a [=unique internal value=]. The times at which a [=browser agent=] [=performs an observation=] are [=implementation-defined=]. A [=browser agent=] may [=parallel queue/enqueue steps=] to the [=AI agent queue=] to [=perform an observation=] given any [=top-level browsing context=] in the [=user agent=] [=browsing context group set=], at any time, although implementations typically reserve this operation for when the user is interacting with a [=browser agent=] while web content is in view.

Security and privacy considerations

Accessibility considerations

Acknowledgements

Thanks to Brandon Walderman, Leo Lee, Andrew Nolan, David Bokan, Khushal Sagar, Hannah Van Opstal, Sushanth Rajasankar for the initial explainer, proposals and discussions that established the foundation for this specification. Also many thanks to Alex Nahas and Jason McGhee for sharing early implementation experience. Finally, thanks to the participants of the Web Machine Learning Community Group for feedback and suggestions.