@dornick/webmcp
v0.1.0
Published
Zero-dependency, spec-conformant polyfill and TypeScript types for the W3C WebMCP API (document.modelContext). Standalone — no Dornick required.
Maintainers
Readme
@dornick/webmcp
Zero-dependency, spec-conformant polyfill and TypeScript types for the
W3C WebMCP API
(document.modelContext).
Standalone — it does not depend on Dornick, or on anything else.
npm install @dornick/webmcpimport { installWebMcpPolyfill } from "@dornick/webmcp";
const result = installWebMcpPolyfill();
console.info(result.reason); // e.g. "document.modelContext is implemented natively; nothing was installed"
await document.modelContext.registerTool({
name: "search-products",
description: "Search the catalog by keyword",
inputSchema: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"],
},
async execute({ query }) {
const hits = await search(query);
return { content: [{ type: "text", text: `${hits.length} results` }] };
},
});Or, as a side-effect import: import "@dornick/webmcp/auto";
What this polyfill cannot do
Read this before you promise anything to anyone.
- It cannot reach a browser-level agent. Native
document.modelContextis a browser IPC surface. This is ordinary page JavaScript, visible only to page script and to drivers that evaluate JS in the page — extension content scripts, CDP/Playwright, the MCP-B relay. Chrome's built-in agent will not see polyfilled tools. For that you need the real thing: an origin trial token (Chrome 149–156) orchrome://flags/#enable-webmcp-testing. - It cannot enforce the
toolsPermissions Policy.allow="tools"is unreadable from script.permissionsPolicyCheckis advisory only. - It cannot reach frames that have not loaded it. Native mediates the whole
frame tree; the
postMessagebridge only reaches opted-in peers that also configureallowedOrigins. - It cannot provide
:tool-form-active/:tool-submit-active. There is no extension point for CSS pseudo-classes. See Styling. - It cannot set
agentInvokedon submits it did not initiate. - It cannot stop page script forging tools or results. Page script owns the registry by construction.
- It does not survive
document.open(). bfcache and normal reloads are fine. - Its
toolchangetiming is not Chrome's. We dispatch synchronously; Chrome may coalesce.
Never clobbers
installWebMcpPolyfill() stands down for a native implementation and for any
other vendor's polyfill, returning theirs rather than replacing it:
const { status, installed, provider, modelContext } = installWebMcpPolyfill();
// status: "installed" | "already-installed" | "native-present"
// | "foreign-polyfill-present" | "insecure-context" | "no-document"Because of that, installing unconditionally is safe.
Options
| Option | Default | Notes |
|---|---|---|
| allowInsecureContext | false | The API is [SecureContext]. We refuse on http:// rather than being more permissive than the spec — code that works on http://staging would otherwise break on https://prod. localhost is already a secure context. |
| installNavigatorAlias | true | navigator.modelContext, deprecated in Chrome 150, warns once on first read. |
| installTesting | true | navigator.modelContextTesting — getTools, provideContext, clearContext, executeTool. |
| aggregateSameOriginFrames | true | Merges same-origin child frames' tools, matching native. |
| crossOrigin | off | { allowedOrigins: [...] } enables the postMessage bridge. "*" throws. |
| validateInput | "off" | "shallow" opts into required-key and primitive-type checks. Off by default because being stricter than native breaks working code. |
| permissionsPolicyCheck | probe | Advisory; see limitation 2. |
Declarative tools
@dornick/webmcp/declarative turns <form toolname> into a registered tool —
and it works against a native document.modelContext with no polyfill
loaded at all.
<form toolname="search-cars"
tooldescription="Search by make and model"
toolautosubmit>
<input name="make" toolparamdescription="The vehicle's make" required>
<input name="model" toolparamdescription="The vehicle's model">
<button type="submit">Search</button>
</form>import { installDeclarativeTools } from "@dornick/webmcp/declarative";
installDeclarativeTools(); // scans, and watches for forms added laterform.addEventListener("submit", (e) => {
e.preventDefault();
if (e.agentInvoked) e.respondWith(doSearch(new FormData(e.target)));
});Submission goes through the real form.requestSubmit(), not a synthesized
event, so constraint validation, :invalid, the invalid event, and submitter
association all behave normally.
Password and file inputs are omitted from generated schemas — the first for
safety (includePasswordFields to opt in), the second because it cannot be set
programmatically.
Styling
The CSS pseudo-classes are not polyfillable, so the declarative layer also sets
data-tool-form-active and data-tool-submit-active. Style both with a
forgiving :is():
form:is([data-tool-form-active], :tool-form-active) { outline: 2px solid #6c5ce7; }:is() drops a branch it does not understand and keeps the rule. A plain comma
list — form[data-tool-form-active], form:tool-form-active { … } — invalidates
the entire selector on browsers without the pseudo-class.
Types only
Targeting native Chrome and want no runtime at all?
import type { ModelContext, ModelContextTool } from "@dornick/webmcp/types";This subpath is pure types plus the declare global augmentation of Document,
Navigator, and SubmitEvent.
Test coverage
166 conformance assertions run under happy-dom. The cross-origin bridge is
covered at the protocol level over a fake message fabric — neither jsdom nor
happy-dom provides real cross-origin frames, so browser-level bridge behaviour
needs a Playwright test we have not written yet.
MIT.
