installWebMCPPolyfill
Installs a document.modelContext polyfill unless the browser already has one, and returns whichever ModelContext is active.
Installs a document.modelContext polyfill unless the browser already has one, and returns whichever ModelContext is active. <WebAgentsProvider> and createWebAgents call it for you, through loadWebMCPPolyfill; call it yourself only on a page that registers tools without them.
Import
import { installWebMCPPolyfill } from "@webmcp-agents/core/polyfill";
Example
Call it before any tool registers. Here it also lists the registered tools whenever they change.
import { installWebMCPPolyfill } from "@webmcp-agents/core/polyfill";
// For a page that registers tools without createWebAgents or the
// provider (they load it themselves). Does nothing where the browser
// already has document.modelContext, and returns the native one.
const modelContext = installWebMCPPolyfill();
modelContext?.addEventListener("toolchange", async () => {
const tools = await modelContext.getTools();
console.log(tools.map((tool) => tool.name));
});
When you do not need the return value, import @webmcp-agents/core/polyfill/auto instead.
Options
None. The function takes no arguments.
Returns
ModelContext | undefined:
- The native
document.modelContextwhen the browser has one. Nothing is installed. - Otherwise a new
PolyfillModelContext, defined ondocumentasmodelContext(configurable). undefinedon the server (nodocument).
When it installs, it also starts declarative <form toolname> tools (found on install and with a MutationObserver on document.documentElement, including toolautosubmit and the confirmation pause) and logs [web-agents] document.modelContext polyfilled: this browser has no native WebMCP once.
Notes
- Safe to call more than once: later calls return the installed instance.
- It steps aside when the browser has the real API. In a WebMCP-enabled Chrome you get Chrome’s behaviour, including its event order and its cancelling of calls whose tool changes.
- Installed by hand, it must come before tools register: outside
createWebAgentsand the provider,registerWebToolwithoutdocument.modelContextwarns once and registers nothing. Tools thatcreateWebAgentsor the provider manage wait for the polyfill instead. - Imported statically, it is in your main bundle;
loadWebMCPPolyfillkeeps it in a chunk that only browsers without WebMCP download. - The declarative-form observer is never disconnected.
@webmcp-agents/polyfill(deprecated) re-exports it, soimport { installWebMCPPolyfill } from "@webmcp-agents/polyfill"keeps working.