Repository navigation
feat(core): add WebMCPToolset for Chrome WebMCP (document.modelContext) tools - #914
Conversation
…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
left a comment
There was a problem hiding this comment.
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.
| /** | ||
| * A tool registered by the page on `document.modelContext`. | ||
| * | ||
| * Converts the tool's JSON Schema into a Gemini {@link FunctionDeclaration} and |
There was a problem hiding this comment.
Not a nit. Remove the {@link} here.
* Converts the tool's JSON Schema into a Gemini {@link FunctionDeclaration} andFunctionDeclaration 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` andThere was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| return firstResult; | ||
| } | ||
| negotiatedArgEncoding = 'json-string'; | ||
| logger.info( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Done in d2073bc — logger.debug. Agreed, it is a one-line operational detail about which wire format a browser wanted, not an application event.
| let negotiatedArgEncoding: ArgEncoding | undefined; | ||
|
|
||
| /** Clears the negotiated encoding. Exported for tests. */ | ||
| export function resetWebMCPArgEncoding(): void { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, andresetWebMCPArgEncoding 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
fromOriginscan 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
left a comment
There was a problem hiding this comment.
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.
|
Thanks for the review — all four addressed in d2073bc, replies inline on each thread.
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 Verified locally on Also rebuilt and re-checked the public surface: the subpath exports exactly |
AmaadMartin
left a comment
There was a problem hiding this comment.
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 nevercasts are gone; the tests build a realContext(webmcp_tool_test.ts:39). logger.infois nowlogger.debug(webmcp_tool.ts:188).resetWebMCPArgEncodingis removed; the encoding is now aWeakMapkeyed 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
left a comment
There was a problem hiding this comment.
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 nevercasts are gone; tests build a realContextthroughtoolContextWith(webmcp_tool_test.ts:39), soargsis 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
WeakMapkeyed 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.
| constructor( | ||
| readonly webmcpTool: WebMCPRegisteredTool, | ||
| name?: string, | ||
| doc?: WebMCPDocument, | ||
| ) { |
There was a problem hiding this comment.
can you make it as a params?
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
…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.
Fixes #913
Adds
WebMCPToolset/WebMCPToolundercore/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'sexecuteruns in the page, so the UI updates as a side effect.Unlike
MCPToolsetnothing 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()fromdocument.modelContext.getTools(), with the usualtoolFilterandprefix; plusfromOriginsfor cross-origin iframes andonToolChange()for thetoolchangeevent.close()detaches listeners.WebMCPTool extends BaseTool— reuses the existingtoGeminiSchema()for the declaration and delegates toexecuteTool.annotations.consequentialHintmaps ontocheckRequireConfirmation(), so consequential page actions route through ADK's existing tool-confirmation path rather than firing unprompted../tools/webmcpsubpath, 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.
executeToolargument 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.inputSchemashape. Specified as an object, but one arriving as a JSON string converts to{type: "TYPE_UNSPECIFIED"}with noproperties— 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 whendocument.modelContextis absent andgetTools()returns[]rather than throwing, so importing from Node is harmless. The module reaches the global throughglobalThisand needs no DOM lib, matching howChromeBuiltInLlmhandlesglobalThis.LanguageModel.Verified against the built output:
Tests
23 new tests across
webmcp_tool_test.tsandwebmcp_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,fromOriginsforwarding,toolchangesubscribe/unsubscribe, and listener cleanup onclose().package_install_weight_test.tspins the public subpath list, so./tools/webmcpis added there too.eslintandprettierare clean.tsc --noEmitreports only the 4 pre-existingtests/integration/**errors that reproduce unchanged onmain.npm run buildwas run and the subpath checked end to end:dist/{types,esm,cjs}/tools/webmcp/index.*are emitted, the subpath and barrel both resolve, andWebMCPToolsetis present indist/web/index_web.js.Field testing
Driven against the real Live API: an in-browser
LlmAgentongemini-3.8-liverunning a two-turn voice conversation against a page exposing five WebMCP tools — spoken input transcribed,search_flightscalled with{destination: "Tokyo"}, thenselect_flightwith{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 onwebmcp-types: nothing in core has to move if the shape shifts.