@mcptrail/webmcp-polyfill
v0.1.0
Published
A navigator.modelContext polyfill for WebMCP: installs a spec-faithful shim only when the browser lacks it, so tools register on any browser.
Maintainers
Readme
@mcptrail/webmcp-polyfill
A polyfill of navigator.modelContext for browsers and environments that lack it. It installs a spec-faithful shim only when the browser has no native modelContext, so your WebMCP tools register on any browser — and it never overwrites a real implementation.
It also exposes a small driver (tools() / invoke()) so dev tools and bridges can list and run the tools registered against the polyfill.
Install
npm install @mcptrail/webmcp-polyfillUsage
import { installModelContextPolyfill } from "@mcptrail/webmcp-polyfill";
// Installs a shim only if navigator.modelContext is missing.
const driver = installModelContextPolyfill();
// Your page (or SDK) registers tools the normal way:
navigator.modelContext.registerTool({
name: "book_hotel",
description: "Book a room",
execute: (args) => `Confirmation for ${JSON.stringify(args)}`,
});
driver.tools(); // ToolDescriptor[] (name, description, inputSchema, annotations, readOnly)
await driver.invoke("book_hotel", { hotelId: "h1" });
driver.uninstall(); // restore whatever was there beforeAPI
installModelContextPolyfill(options?): {
installed: boolean; // true only if we actually installed the shim
tools(): ToolDescriptor[]; // registry tools, sorted by name
invoke(name, args?): Promise<any>; // run the tool's execute(args), await, return
uninstall(): void; // restore the previous modelContext (and document's)
};
hasNativeModelContext(): boolean; // is a modelContext present right now?
modelContextTools(target?): ToolDescriptor[]; // tools, but only if THIS polyfill installed it; else []Options
| Option | Default | Notes |
|--------|---------|-------|
| force | false | Install even when a modelContext already exists (overwrites it) |
| target | navigator | Object to receive .modelContext (created on globalThis if absent) |
| alsoDocument | true | Also assign document.modelContext |
Behavior
- Never clobbers native. If
navigator.modelContextalready exists andforceis not set,installedisfalseand the native implementation is left untouched. You still get a driver with a stabletools()/invoke()API (operating over the polyfill's own registry). - Read-only safe. If assigning
.modelContextthrows (a read-only property), it falls back toObject.defineProperty. - No
navigator? Ifnavigatoris undefined, a minimal one is created onglobalThis. - Recognizable. The installed shim carries a non-enumerable marker so
modelContextTools()can tell a polyfill-installed context apart from a native one.
Development
npm install
npm run typecheck
npm test # Vitest + jsdom
npm run build # tsup → dist (ESM + CJS + d.ts)License
MIT © Zied Guetari
