Skip to content

feat(core): add WebMCPToolset for Chrome WebMCP (document.modelContext) tools - #914

Merged
ScottMansfield merged 3 commits into
mainfrom
feat/webmcp-toolset
Sep 22, 2026
Merged

ScottMansfield merged 3 commits into
mainfrom
feat/webmcp-toolset

Conversation

@ScottMansfield

Copy link
Copy Markdown
Member

Fixes #913

Adds WebMCPToolset / WebMCPTool under core/src/tools/webmcp/, so an in-browser ADK agent can use the tools a page registers with Chrome's WebMCP.

What this enables

A page declares typed tools on document.modelContext; the agent then drives the page through those handlers rather than scraping the DOM. Each tool's execute runs in the page, so the UI updates as a side effect.

import {LlmAgent} from '@google/adk';
import {WebMCPToolset} from '@google/adk/tools/webmcp';

const agent = new LlmAgent({
  name: 'page_agent',
  model: 'gemini-3.8-live',
  tools: [new WebMCPToolset()],
});

Unlike MCPToolset nothing is transported anywhere — discovery and execution are same-document browser calls, so there is no session manager and no new dependency.

Shape

Deliberately parallel to tools/mcp/:

  • WebMCPToolset extends BaseToolset — getTools() from document.modelContext.getTools(), with the usual toolFilter and prefix; plus fromOrigins for cross-origin iframes and onToolChange() for the toolchange event. close() detaches listeners.
  • WebMCPTool extends BaseTool — reuses the existing toGeminiSchema() for the declaration and delegates to executeTool.
  • annotations.consequentialHint maps onto checkRequireConfirmation(), so consequential page actions route through ADK's existing tool-confirmation path rather than firing unprompted.
  • Exported from the barrel and as a ./tools/webmcp subpath, matching ./tools/mcp.

Two browser quirks encoded

Both were found building against Chrome, and both otherwise fail silently — the model gets an unusable error or no arguments, and there is nothing in the logs to explain it.

executeTool argument encoding. Chrome took a JSON string originally and an object from 155, deprecating the string form. An object handed to an older build is parsed as "[object Object]" and returns {"error": "Failed to parse input arguments"} without running the tool. The encoding is probed once and reused; a parse failure means nothing executed, so the retry cannot double-apply a side effect, and unrelated tool errors propagate untouched.

inputSchema shape. Specified as an object, but one arriving as a JSON string converts to {type: "TYPE_UNSPECIFIED"} with no properties — the model then calls the tool with {} because it has no parameter names to fill in. Both shapes are now accepted, and a schema that yields no parameters warns.

Safe outside the browser

isWebMCPSupported() is false when document.modelContext is absent and getTools() returns [] rather than throwing, so importing from Node is harmless. The module reaches the global through globalThis and needs no DOM lib, matching how ChromeBuiltInLlm handles globalThis.LanguageModel.

Verified against the built output:

isWebMCPSupported() in node: false
getTools() in node: []

Tests

23 new tests across webmcp_tool_test.ts and webmcp_toolset_test.ts: schema conversion for both shapes, the consequential-hint mapping, the encoding probe and its reuse, abort-signal forwarding, unrelated errors propagating, filtering and prefixing, fromOrigins forwarding, toolchange subscribe/unsubscribe, and listener cleanup on close().

Test Files  259 passed | 1 skipped (260)
     Tests  3928 passed | 3 skipped (3931)

package_install_weight_test.ts pins the public subpath list, so ./tools/webmcp is added there too. eslint and prettier are clean. tsc --noEmit reports only the 4 pre-existing tests/integration/** errors that reproduce unchanged on main.

npm run build was run and the subpath checked end to end: dist/{types,esm,cjs}/tools/webmcp/index.* are emitted, the subpath and barrel both resolve, and WebMCPToolset is present in dist/web/index_web.js.

Field testing

Driven against the real Live API: an in-browser LlmAgent on gemini-3.8-live running a two-turn voice conversation against a page exposing five WebMCP tools — spoken input transcribed, search_flights called with {destination: "Tokyo"}, then select_flight with {flightId: "SB-103"}, both actuating the page.

Caveat

WebMCP is experimental — Chrome flag chrome://flags/#enable-webmcp-testing, origin trial from Chrome 149 — and the API may still change. That is the reason the types here are a few local structural declarations rather than a dependency on webmcp-types: nothing in core has to move if the shape shifts.

…t) tools

Chrome's WebMCP lets a page register typed, callable tools on
document.modelContext. This exposes them to an in-browser agent, so it drives
the page through the handlers the page published instead of scraping the DOM.
Nothing is transported anywhere: discovery and execution are same-document
browser calls, and each tool's own execute runs in the page.

WebMCPToolset mirrors MCPToolset - toolFilter, prefix, close() - and adds
fromOrigins for cross-origin iframes plus onToolChange() for the toolchange
event. WebMCPTool reuses toGeminiSchema for the declaration and maps
annotations.consequentialHint onto checkRequireConfirmation(), so consequential
page actions route through the existing tool-confirmation path.

Two browser quirks are handled, both of which otherwise fail silently:

- executeTool arguments were a JSON string before Chrome 155 and are an object
  after. Passing an object to an older build makes it parse "[object Object]"
  and return a parse error without running the tool. The encoding is probed
  once and reused; a parse failure means nothing executed, so the retry cannot
  double-apply a side effect.
- inputSchema is specified as an object, but one arriving as a JSON string
  would convert to a parameterless declaration, leaving the model no argument
  names and making it call the tool with {}. Both shapes are accepted.

Browser-only and inert elsewhere: isWebMCPSupported() is false without the API
and getTools() returns [], so importing from Node is harmless. Reached through
globalThis so the module needs no DOM lib, matching ChromeBuiltInLlm.

Fixes #913

@AmaadMartin AmaadMartin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at head 7f2b11a. The toolset and tool logic read well, the browser-quirk handling is clear, and index.ts re-exports every new type. Two items in the diff block approval: a docs build break and type suppressions in the tool test. CI note: run-tests (ubuntu) failed only at the documentation build step, which is the first comment below, not a flake.

Comment thread core/src/tools/webmcp/webmcp_tool.ts Outdated
/**
* A tool registered by the page on `document.modelContext`.
*
* Converts the tool's JSON Schema into a Gemini {@link FunctionDeclaration} and

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a nit. Remove the {@link} here.

 * Converts the tool's JSON Schema into a Gemini {@link FunctionDeclaration} and

FunctionDeclaration comes from @google/genai. typedoc runs with excludeExternals: true, so it cannot resolve the link and docs:check fails with exit 4. This is the ubuntu run-tests failure. No other file in core/src links an external genai type. Use plain code font:

 * Converts the tool's JSON Schema into a Gemini `FunctionDeclaration` and

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d2073bc — now plain code font.

Reproduced it locally first to be sure it was the cause rather than a coincidence:

$ npm run docs:check
[warning] The comment for WebMCPTool links to "FunctionDeclaration" which was resolved
          but is not included in the documentation.
[warning] Found 0 errors and 1 warnings
exit=4

and after the change docs:check exits 0. Thanks — I had not run that target before opening the PR, which is how it got through.

Worth noting for anyone reading the CI: all three platforms showed red, but only ubuntu had a genuinely failed step (Run documentation build check); macos and windows were fail-fast cancellations of the same matrix.


const result = await tool.runAsync({
args: {flightId: 'SB-101'},
} as never);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a nit. Replace as never with a real toolContext.

      } as never);

as never turns off type checking for the whole request, including args. The sibling test builds a context instead (core/test/tools/mcp/mcp_tool_test.ts:45):

const toolContext = new Context({invocationContext});
await tool.runAsync({args: {...}, toolContext});

The same cast repeats at lines 140, 155, 158, 169, 187, and 196. Fix all seven.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d2073bc — all seven are gone, grep -c "as never" is now 0 in that file.

Followed the pattern you pointed at. Since several tests needed one, it is a small helper rather than repeated inline:

/** A real Context, so request typing is checked rather than suppressed. */
function toolContextWith(abortSignal?: AbortSignal): Context {
  const invocationContext = {
    abortSignal,
    session: {state: {}},
  } as unknown as InvocationContext;
  return new Context({invocationContext});
}

Call sites now read await tool.runAsync({args: {...}, toolContext: toolContextWith()}), and the abort-signal test passes the signal through it.

You were right that this was hiding something rather than just being noisy: with the casts removed, args is type-checked against RunAsyncToolRequest for the first time. 23 tests still pass.

Comment thread core/src/tools/webmcp/webmcp_tool.ts Outdated
return firstResult;
}
negotiatedArgEncoding = 'json-string';
logger.info(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. Use logger.debug here.

    logger.info(
      'This browser expects JSON-string WebMCP tool arguments; using that encoding.',
    );

This is an operational message. The repo reserves info for higher-level application events and uses debug for messages like this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in d2073bc — logger.debug. Agreed, it is a one-line operational detail about which wire format a browser wanted, not an application event.

Comment thread core/src/tools/webmcp/webmcp_tool.ts Outdated
let negotiatedArgEncoding: ArgEncoding | undefined;

/** Clears the negotiated encoding. Exported for tests. */
export function resetWebMCPArgEncoding(): void {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, optional. resetWebMCPArgEncoding is a test-only reset, but common.ts exports it into the public @google/adk barrel. A test seam then sits in the API surface. Consider keeping it out of the barrel.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken, and gone further than dropping it from the barrel — in d2073bc the function no longer exists.

Your comment prompted the right question: why was there a module-global to reset at all? The negotiated encoding is a property of the browser that owns the model context, not of the module. It is now a WeakMap keyed on the context:

const argEncodingByContext = new WeakMap<object, ArgEncoding>();

Three things fall out of that:

  • No test seam anywhere in the public surface. The subpath now exports exactly WebMCPTool, WebMCPToolset, getModelContext, isWebMCPSupported, and resetWebMCPArgEncoding in barrel: false.
  • Tests need no reset — each builds its own mock document, so it starts clean.
  • It is more correct. A cross-origin iframe reached through fromOrigins can be a different implementation than the top-level document, and previously the first one to probe would have decided the encoding for both.

The probe still happens once per page, since every tool from the same document shares one context object.

@AmaadMartin AmaadMartin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 7f2b11a; no commit was pushed since my last review, so both Not a nit. findings still stand. The {@link FunctionDeclaration} at webmcp_tool.ts:63 breaks docs:check — this is the failing ubuntu run-tests documentation build check. The seven as never casts in webmcp_tool_test.ts are type suppressions that stand in for a real fix. Both block approval; the two nits stay open but do not block.

…PTool

Addresses review on #914.

The {@link FunctionDeclaration} in the WebMCPTool doc comment pointed at an
external @google/genai type. typedoc runs with excludeExternals, so it could
not resolve the link and docs:check failed with exit 4 - the ubuntu run-tests
failure. Plain code font instead, matching how the rest of core/src refers to
genai types.

The seven `as never` casts in the tool test disabled checking for the whole
request object, args included. They now build a real Context, as
core/test/tools/mcp/mcp_tool_test.ts does.

resetWebMCPArgEncoding existed only so tests could clear a module-global, and
it sat in the public barrel. Removed: the negotiated encoding now lives in a
WeakMap keyed on the model context. That is also more correct, because the
answer is a property of the browser that owns the context - a cross-origin
iframe reached via fromOrigins may differ from the top-level document - while
still being shared by every tool from the same page, so the probe still
happens once.

Demotes the encoding-negotiation log from info to debug.
@ScottMansfield

Copy link
Copy Markdown
Member Author

Thanks for the review — all four addressed in d2073bc, replies inline on each thread.

finding resolution
{@link FunctionDeclaration} breaks docs:check plain code font; reproduced the exit 4 locally, now exits 0
seven as never casts replaced with a real Context; 0 casts remain
logger.info → logger.debug done
resetWebMCPArgEncoding in the public barrel function removed entirely; state is now a WeakMap keyed on the model context

The last one turned into a genuine fix rather than a cosmetic one. Asking why a module-global needed resetting at all exposed that the negotiated encoding was shared across every document in the process, so a cross-origin iframe reached via fromOrigins would have inherited whatever the top-level document probed first. Keyed on the context it is correct per document, still negotiated once per page, and needs no test seam.

Verified locally on d2073bc:

docs:check   exit 0   (was exit 4)
Test Files   259 passed | 1 skipped (260)
     Tests   3928 passed | 3 skipped (3931)
eslint       clean
prettier     clean
tsc          only the 4 pre-existing tests/integration errors, unchanged on main

Also rebuilt and re-checked the public surface: the subpath exports exactly WebMCPTool, WebMCPToolset, getModelContext, isWebMCPSupported, and the test seam is absent from both the subpath and the @google/adk barrel.

@AmaadMartin AmaadMartin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at d2073bc. All four earlier findings are resolved, verified against the source:

  • The {@link FunctionDeclaration} is now plain code font (webmcp_tool.ts:68).
  • The seven as never casts are gone; the tests build a real Context (webmcp_tool_test.ts:39).
  • logger.info is now logger.debug (webmcp_tool.ts:188).
  • resetWebMCPArgEncoding is removed; the encoding is now a WeakMap keyed on the model context (webmcp_tool.ts:49), so no test seam reaches the public barrel.

The WeakMap refactor is correct and scoped per context. {@link MCPToolset} resolves because MCPToolset is reachable from the docs entry point (index.ts). I found no suppressions, no instanceof, and no new public type missing from common.ts. CI is fully green. Approving.

@AmaadMartin AmaadMartin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at d2073bc. All four prior findings are fixed in the current source:

  • The {@link FunctionDeclaration} is now plain code font (webmcp_tool.ts:68).
  • The seven as never casts are gone; tests build a real Context through toolContextWith (webmcp_tool_test.ts:39), so args is type-checked.
  • The encoding log uses logger.debug (webmcp_tool.ts:188).
  • The test-only reset left the public barrel; the module-global became a WeakMap keyed on the model context (webmcp_tool.ts:49). This is also more correct for cross-origin iframes.

I found no new problems: no type suppressions, no instanceof, no console.log, and all public types are exported from common.ts. CI is green at this SHA. Approving.

Comment thread core/src/tools/webmcp/webmcp_tool.ts Outdated
Comment on lines +79 to +83
constructor(
readonly webmcpTool: WebMCPRegisteredTool,
name?: string,
doc?: WebMCPDocument,
) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you make it as a params?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — done in 6814c22.

// before
new WebMCPTool(tool, undefined, doc)
// after
new WebMCPTool({tool, document: doc})

You're right that it was out of step, and more so than I realised when I wrote it. BaseTool, FunctionTool, AgentTool, VertexAiSearchTool and LongRunningFunctionTool all take a single params/options object; MCPTool is the only positional one in the package, and it is what I modelled this on. WebMCPToolset in this same module already took WebMCPToolsetOptions, so the two halves disagreed with each other.

The two trailing optionals also made the awkward call unavoidable: passing a document meant supplying undefined for the name first, which is exactly what every construction site in the tests was doing. That undefined was the smell.

export interface WebMCPToolParams {
  /** The tool as reported by `document.modelContext.getTools()`. */
  tool: WebMCPRegisteredTool;
  /** Overrides the name exposed to the model; the toolset uses it for its prefix. */
  name?: string;
  /** Document to read `modelContext` from. Defaults to the global document. */
  document?: WebMCPDocument;
}

WebMCPToolParams is exported from common.ts next to WebMCPToolsetOptions. Callers in webmcp_toolset.ts and all 13 tool tests are updated; document rather than doc to match the toolset option name.

Verified on 6814c22: docs:check exit 0, 3928 tests pass, eslint and prettier clean, tsc shows only the four pre-existing tests/integration errors. Also rebuilt and constructed a tool from dist/esm with the new signature to confirm the shipped artifact behaves.

Addresses review on #914.

WebMCPTool took (tool, name?, doc?) positionally, copied from MCPTool. That is
the outlier in this package: BaseTool, FunctionTool, AgentTool,
VertexAiSearchTool and LongRunningFunctionTool all take a single params or
options object, and WebMCPToolset in this same module already takes
WebMCPToolsetOptions.

Two trailing optionals also made the awkward case unavoidable - supplying a
document meant passing `undefined` for the name first, which every call site
in the tests was doing:

  new WebMCPTool(tool, undefined, doc)
  new WebMCPTool({tool, document: doc})

WebMCPToolParams is exported from common.ts alongside WebMCPToolsetOptions.

@AmaadMartin AmaadMartin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 6814c22. All four earlier findings are fixed in the source: the {@link FunctionDeclaration} is now plain code font; the seven as never casts are gone, and the tests build a real Context through toolContextWith, so args is type-checked; logger.info is now logger.debug; and resetWebMCPArgEncoding no longer exists, replaced by a per-context WeakMap. The constructor now takes WebMCPToolParams, which is exported from common.ts. I found no new any, instanceof, or suppression, and every {@link} target resolves from the index.ts typedoc entry. CI is green at this SHA. Approving.

@ScottMansfield
ScottMansfield merged commit e4709c2 into main Sep 22, 2026
14 checks passed
@ScottMansfield
ScottMansfield deleted the feat/webmcp-toolset branch September 22, 2026 20:03
@kalenkevich kalenkevich mentioned this pull request Sep 22, 2026
prasanna8585 pushed a commit to prasanna8585/adk-js that referenced this pull request Nov 10, 2026
…t) tools (google#914)

* feat(core): add WebMCPToolset for Chrome WebMCP (document.modelContext) tools

Chrome's WebMCP lets a page register typed, callable tools on
document.modelContext. This exposes them to an in-browser agent, so it drives
the page through the handlers the page published instead of scraping the DOM.
Nothing is transported anywhere: discovery and execution are same-document
browser calls, and each tool's own execute runs in the page.

WebMCPToolset mirrors MCPToolset - toolFilter, prefix, close() - and adds
fromOrigins for cross-origin iframes plus onToolChange() for the toolchange
event. WebMCPTool reuses toGeminiSchema for the declaration and maps
annotations.consequentialHint onto checkRequireConfirmation(), so consequential
page actions route through the existing tool-confirmation path.

Two browser quirks are handled, both of which otherwise fail silently:

- executeTool arguments were a JSON string before Chrome 155 and are an object
  after. Passing an object to an older build makes it parse "[object Object]"
  and return a parse error without running the tool. The encoding is probed
  once and reused; a parse failure means nothing executed, so the retry cannot
  double-apply a side effect.
- inputSchema is specified as an object, but one arriving as a JSON string
  would convert to a parameterless declaration, leaving the model no argument
  names and making it call the tool with {}. Both shapes are accepted.

Browser-only and inert elsewhere: isWebMCPSupported() is false without the API
and getTools() returns [], so importing from Node is harmless. Reached through
globalThis so the module needs no DOM lib, matching ChromeBuiltInLlm.

Fixes google#913

* fix(core): unbreak the docs build and drop test-only seams from WebMCPTool

Addresses review on google#914.

The {@link FunctionDeclaration} in the WebMCPTool doc comment pointed at an
external @google/genai type. typedoc runs with excludeExternals, so it could
not resolve the link and docs:check failed with exit 4 - the ubuntu run-tests
failure. Plain code font instead, matching how the rest of core/src refers to
genai types.

The seven `as never` casts in the tool test disabled checking for the whole
request object, args included. They now build a real Context, as
core/test/tools/mcp/mcp_tool_test.ts does.

resetWebMCPArgEncoding existed only so tests could clear a module-global, and
it sat in the public barrel. Removed: the negotiated encoding now lives in a
WeakMap keyed on the model context. That is also more correct, because the
answer is a property of the browser that owns the context - a cross-origin
iframe reached via fromOrigins may differ from the top-level document - while
still being shared by every tool from the same page, so the probe still
happens once.

Demotes the encoding-negotiation log from info to debug.

* refactor(core): take WebMCPTool constructor arguments as a params object

Addresses review on google#914.

WebMCPTool took (tool, name?, doc?) positionally, copied from MCPTool. That is
the outlier in this package: BaseTool, FunctionTool, AgentTool,
VertexAiSearchTool and LongRunningFunctionTool all take a single params or
options object, and WebMCPToolset in this same module already takes
WebMCPToolsetOptions.

Two trailing optionals also made the awkward case unavoidable - supplying a
document meant passing `undefined` for the name first, which every call site
in the tests was doing:

  new WebMCPTool(tool, undefined, doc)
  new WebMCPTool({tool, document: doc})

WebMCPToolParams is exported from common.ts alongside WebMCPToolsetOptions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support Chrome WebMCP (document.modelContext) tools via a WebMCPToolset

4 participants