diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..d252725
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,10 @@
+name: ci
+on: [push, pull_request]
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with: { node-version: 24 }
+ - run: node --test
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 0000000..ffd29d1
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,141 @@
+# Publish the release to npm.
+#
+# The release is the trigger, so there is no separate step to forget: a channel
+# that only updates when somebody remembers is a channel that silently serves an
+# old version forever. `workflow_dispatch` is for re-running one that failed on
+# something transient, and is safe because a version already on the registry is
+# skipped rather than attempted.
+#
+# Authenticates with an npm automation token in the repository secret
+# `NPM_TOKEN`. `registry-url` is what makes setup-node write the token into
+# .npmrc; it is required for token auth and fatal under trusted publishing.
+name: publish
+
+on:
+ release:
+ types: [published]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 35
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ registry-url: https://registry.npmjs.org
+
+ # No install step: this package has no dependencies.
+ - run: node --test
+ env:
+ CI: true
+
+ - name: Read the version being published
+ id: version
+ run: |
+ VERSION="$(node -p "require('./package.json').version")"
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+ echo "@profullstack/webmcp@$VERSION"
+
+ - name: Check the tag matches package.json
+ if: github.event_name == 'release'
+ env:
+ TAG: ${{ github.event.release.tag_name }}
+ VERSION: ${{ steps.version.outputs.version }}
+ run: |
+ if [ "$TAG" != "v$VERSION" ]; then
+ echo "::error::release tag $TAG does not match package.json version $VERSION"
+ exit 1
+ fi
+
+ - name: Skip if this version is already on npm
+ id: published
+ env:
+ VERSION: ${{ steps.version.outputs.version }}
+ run: |
+ if npm view "@profullstack/webmcp@$VERSION" version >/dev/null 2>&1; then
+ echo "already=true" >> "$GITHUB_OUTPUT"
+ echo "@profullstack/webmcp@$VERSION is already published — nothing to do"
+ else
+ echo "already=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Require an npm token
+ if: steps.published.outputs.already == 'false'
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+ run: |
+ if [ -z "$NPM_TOKEN" ]; then
+ echo "::error::NPM_TOKEN is not set — add an npm automation token as a repository secret named NPM_TOKEN"
+ exit 1
+ fi
+
+ - name: Publish
+ if: steps.published.outputs.already == 'false'
+ run: npm publish --access public --provenance
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+
+ # A brand-new scoped package 404s on every read path for minutes after a
+ # successful publish, so a short window here fails a release that worked.
+ # Wait longer, and never fail the run on the read alone: `npm publish`
+ # exiting 0 is the authority on whether it published.
+ - name: Confirm the registry has it
+ if: steps.published.outputs.already == 'false'
+ continue-on-error: true
+ env:
+ VERSION: ${{ steps.version.outputs.version }}
+ run: |
+ for _ in $(seq 1 30); do
+ if [ "$(npm view "@profullstack/webmcp@$VERSION" version 2>/dev/null)" = "$VERSION" ]; then
+ echo "@profullstack/webmcp@$VERSION is on the registry"
+ exit 0
+ fi
+ sleep 10
+ done
+ echo "::warning::published, but the registry does not report @profullstack/webmcp@$VERSION yet (first publishes can lag several minutes)"
+
+ # Sites load src/embed.js from jsDelivr @0. Its purge endpoint
+ # rate-limits this path; retry only after the reported cooldown, then
+ # poll until the CDN actually resolves the new package version.
+ - name: Purge jsDelivr @0 and verify the embed version
+ if: steps.published.outputs.already == 'false'
+ continue-on-error: true
+ env:
+ VERSION: ${{ steps.version.outputs.version }}
+ run: |
+ # embed.js imports its siblings relatively, so every module is served
+ # under @0; purge them all so no page mixes two versions.
+ for f in core.js site.js forms.js mcp-bridge.js index.js react.js; do
+ curl -sS -o /dev/null "https://purge.jsdelivr.net/npm/@profullstack/webmcp@0/src/$f" || true
+ done
+ PURGE_URL="https://purge.jsdelivr.net/npm/@profullstack/webmcp@0/src/embed.js"
+ CDN_URL="https://cdn.jsdelivr.net/npm/@profullstack/webmcp@0/src/embed.js"
+ get_reset() {
+ printf '%s' "$1" | node -e 'let s="";process.stdin.on("data",d=>s+=d);process.stdin.on("end",()=>{try{const p=JSON.parse(s).paths?.["/npm/@profullstack/webmcp@0/src/embed.js"];console.log(Number(p?.throttlingReset)||0)}catch{console.log(0)}})'
+ }
+ purge_response="$(curl -sS "$PURGE_URL" || true)"
+ reset="$(get_reset "$purge_response")"
+ if [ "$reset" -gt 0 ]; then
+ echo "jsDelivr rate-limited the purge; retrying after ${reset}s"
+ sleep "$((reset + 5))"
+ purge_response="$(curl -sS "$PURGE_URL" || true)"
+ reset="$(get_reset "$purge_response")"
+ if [ "$reset" -gt 0 ]; then
+ echo "::warning::jsDelivr still rate-limited the purge for ${reset}s"
+ fi
+ fi
+ for attempt in $(seq 1 60); do
+ got="$(curl -fsSI "$CDN_URL" | tr -d '\r' | awk -F': ' 'tolower($1)=="x-jsd-version"{print $2}')"
+ if [ "$got" = "$VERSION" ]; then echo "jsDelivr @0 serves $VERSION"; exit 0; fi
+ echo "jsDelivr @0 still on ${got:-?} (attempt $attempt/60)"
+ sleep 20
+ done
+ echo "::warning::jsDelivr @0 did not reach $VERSION in 20 minutes; verify and purge by hand"
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f7bd84e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,108 @@
+# @profullstack/webmcp
+
+WebMCP for every site. Register a page's own functions as tools for the AI agent
+in the visitor's browser, bridge the MCP server you already run, and turn plain
+forms into tools. One script tag or one import. Where the browser has no WebMCP
+it does nothing, so you can ship it now.
+
+[WebMCP](https://webmachinelearning.github.io/webmcp/) is the W3C Web Machine
+Learning CG draft (`document.modelContext.registerTool()`). It is in origin
+trial in Chrome 149+ and Edge 150+, and is used by Brave Leo, ChatGPT Desktop
+and Meta's glasses web apps. Instead of screenshotting and clicking, an agent calls
+`search_site({ query })` and gets JSON back, as the signed-in person.
+
+## One script tag
+
+```html
+
+```
+
+That registers:
+
+| tool | when | what |
+| --- | --- | --- |
+| `site_info` | always | name, description, pages, and your `/llms.txt` |
+| `open_page` | always | navigate within this origin (an enum when `data-pages` is set) |
+| `search_site` | `data-search` or `data-search-api` | JSON results, or opens the results page |
+| every tool of your MCP server | `data-mcp` | proxied `tools/call` with the visitor's cookies |
+| one per `
+```
+
+Without `toolautosubmit` the agent fills the form and the person presses submit.
+
+## In code
+
+```js
+import { registerTool, registerTools, bridgeMcpServer, siteTools } from '@profullstack/webmcp';
+
+const off = await registerTool({
+ name: 'add_to_cart',
+ description: 'Add a product to the cart by SKU',
+ inputSchema: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'integer', minimum: 1 } }, required: ['sku'] },
+ annotations: { consequentialHint: false },
+ execute: async ({ sku, qty = 1 }) => cart.add(sku, qty),
+});
+
+await bridgeMcpServer('/mcp', { exclude: ['admin_reset'] });
+await registerTools(siteTools({ searchApi: '/api/search?q={query}' }));
+```
+
+React (Next.js client components):
+
+```jsx
+'use client';
+import { useWebMCPTool } from '@profullstack/webmcp/react';
+
+useWebMCPTool({ name: 'play', description: 'Play a channel', inputSchema, execute: ({ id }) => player.play(id) }, [player]);
+```
+
+## Rules the module enforces
+
+- Names match `[A-Za-z0-9_.-]{1,64}`; every tool has a description; schemas are objects.
+- A throwing `execute` returns `{ error }` to the agent instead of crashing the call.
+- Bridged MCP tools are `consequentialHint: true` unless the server marks them
+ `readOnlyHint` or `destructiveHint: false`, so the browser asks before they run.
+- `search_site` and `open_page` never leave the page's origin.
+- Works with `document.modelContext` (current draft) and `navigator.modelContext`
+ (early previews), async or sync `registerTool`, and signal or `unregisterTool` removal.
+
+## CLI
+
+```sh
+npx @profullstack/webmcp check https://example.com # what an agent finds; exit 1 if nothing
+npx @profullstack/webmcp snippet --mcp /mcp --search '/search?q={query}'
+npx @profullstack/webmcp mcp https://example.com/mcp # tools data-mcp would bridge
+```
+
+## Testing in Chrome
+
+`chrome --enable-features=WebMCPTesting` (or `chrome://flags/#enable-webmcp-testing`),
+then in DevTools: `await document.modelContext.getTools()`.
+
+MIT, Profullstack, Inc.
diff --git a/bin/webmcp.js b/bin/webmcp.js
new file mode 100755
index 0000000..383d408
--- /dev/null
+++ b/bin/webmcp.js
@@ -0,0 +1,79 @@
+#!/usr/bin/env node
+// webmcp: check a site's WebMCP setup and print the embed snippet.
+//
+// webmcp check what an agent would find on this page
+// webmcp snippet [options] print the `;
+}
+
+const [cmd, target] = process.argv.slice(2);
+try {
+ if (cmd === 'check' && target) {
+ const r = await check(target);
+ console.log(JSON.stringify(r, null, 2));
+ process.exit(r.ok ? 0 : 1);
+ } else if (cmd === 'snippet') {
+ console.log(snippet());
+ } else if (cmd === 'mcp' && target) {
+ const tools = await mcpCall(target, { credentials: 'omit' }).listTools();
+ for (const t of tools) console.log(`${t.name}\t${(t.description || '').split('\n')[0]}`);
+ } else if (cmd === '--version' || cmd === '-v') {
+ console.log(VERSION);
+ } else {
+ console.log(`webmcp ${VERSION}
+ webmcp check report the page's WebMCP tools (embed, forms, MCP bridge); exit 1 if none
+ webmcp snippet [--mcp /mcp] [--search '/search?q={query}'] [--search-api ...] [--pages '{"a":"/a"}']
+ webmcp mcp list an MCP endpoint's tools`);
+ process.exit(cmd ? 1 : 0);
+ }
+} catch (err) {
+ console.error(`webmcp: ${err.message}`);
+ process.exit(2);
+}
diff --git a/index.d.ts b/index.d.ts
new file mode 100644
index 0000000..4d06a29
--- /dev/null
+++ b/index.d.ts
@@ -0,0 +1,86 @@
+export const VERSION: string;
+
+export interface ToolAnnotations {
+ readOnlyHint?: boolean;
+ untrustedContentHint?: boolean;
+ consequentialHint?: boolean;
+ debugging?: boolean;
+}
+
+export interface ToolExecuteOptions {
+ signal?: AbortSignal;
+}
+
+export interface WebMCPTool {
+ name: string;
+ title?: string;
+ description: string;
+ inputSchema?: object;
+ outputSchema?: object;
+ annotations?: ToolAnnotations;
+ execute(input: I, options: ToolExecuteOptions): O | Promise;
+}
+
+export interface RegisterOptions {
+ signal?: AbortSignal;
+ exposedTo?: string[];
+ onError?: (error: unknown, tool: WebMCPTool) => void;
+ context?: unknown;
+}
+
+export type Unregister = () => void;
+
+export function getModelContext(doc?: Document, nav?: Navigator): any | null;
+export function isSupported(doc?: Document, nav?: Navigator): boolean;
+export function defineTool(tool: T): T;
+export function registerTool(tool: WebMCPTool, options?: RegisterOptions): Promise;
+export function registerTools(tools: WebMCPTool[], options?: RegisterOptions): Promise;
+export function listTools(options?: { context?: unknown; fromOrigins?: string[] }): Promise;
+
+export interface McpClientOptions {
+ fetch?: typeof fetch;
+ credentials?: RequestCredentials;
+ headers?: Record | (() => Record | Promise>);
+}
+export function mcpCall(
+ url: string,
+ options?: McpClientOptions,
+): {
+ listTools(signal?: AbortSignal): Promise;
+ callTool(name: string, args?: object, signal?: AbortSignal): Promise;
+};
+export function mapAnnotations(a?: object): Required>;
+export function unwrapResult(result: any): any;
+
+export interface BridgeOptions extends McpClientOptions, RegisterOptions {
+ include?: string[] | ((name: string) => boolean);
+ exclude?: string[] | ((name: string) => boolean);
+ prefix?: string;
+}
+export function bridgeMcpServer(
+ url: string,
+ options?: BridgeOptions,
+): Promise<{ tools: string[]; unregister: Unregister; error?: string }>;
+
+export interface SiteToolsOptions {
+ name?: string;
+ description?: string;
+ search?: string;
+ searchApi?: string;
+ searchDescription?: string;
+ pages?: Record;
+ llmsTxt?: string | false;
+ extraInfo?: Record;
+ document?: Document;
+ location?: Location;
+ fetch?: typeof fetch;
+}
+export function siteTools(options?: SiteToolsOptions): WebMCPTool[];
+
+export function supportsDeclarativeForms(win?: any): boolean;
+export function formSchema(form: HTMLFormElement): object;
+export function formTool(
+ form: HTMLFormElement,
+ options?: { name?: string; description?: string; autosubmit?: boolean; annotations?: ToolAnnotations },
+): WebMCPTool;
+export function registerForms(root?: ParentNode, options?: RegisterOptions & { force?: boolean }): Promise;
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..90dc11f
--- /dev/null
+++ b/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "@profullstack/webmcp",
+ "version": "0.1.0",
+ "type": "module",
+ "description": "WebMCP for every site: register page tools for in-browser AI agents (document.modelContext), bridge an existing MCP server, and turn forms into tools. One script tag or one import; no-op where unsupported.",
+ "keywords": ["webmcp", "mcp", "model-context-protocol", "modelContext", "ai-agents", "agentic-web", "browser", "tools"],
+ "repository": { "type": "git", "url": "git+https://github.com/profullstack/webmcp.git" },
+ "homepage": "https://github.com/profullstack/webmcp#readme",
+ "bugs": { "url": "https://github.com/profullstack/webmcp/issues" },
+ "license": "MIT",
+ "author": "Profullstack, Inc.",
+ "exports": {
+ ".": { "types": "./index.d.ts", "import": "./src/index.js" },
+ "./react": { "types": "./react.d.ts", "import": "./src/react.js" },
+ "./embed": "./src/embed.js",
+ "./package.json": "./package.json"
+ },
+ "bin": { "webmcp": "bin/webmcp.js" },
+ "files": ["src", "bin", "index.d.ts", "react.d.ts", "README.md", "LICENSE"],
+ "sideEffects": ["./src/embed.js"],
+ "peerDependencies": { "react": ">=18" },
+ "peerDependenciesMeta": { "react": { "optional": true } },
+ "engines": { "node": ">=18" },
+ "scripts": {
+ "test": "node --test"
+ }
+}
diff --git a/react.d.ts b/react.d.ts
new file mode 100644
index 0000000..8ef2d11
--- /dev/null
+++ b/react.d.ts
@@ -0,0 +1,3 @@
+import type { WebMCPTool } from './index.js';
+export function useWebMCPTool(tool: WebMCPTool, deps?: unknown[]): void;
+export function useWebMCPTools(tools: WebMCPTool[], deps?: unknown[]): void;
diff --git a/src/core.js b/src/core.js
new file mode 100644
index 0000000..b7d9f6b
--- /dev/null
+++ b/src/core.js
@@ -0,0 +1,148 @@
+// @profullstack/webmcp: register a page's own functions as WebMCP tools.
+//
+// WebMCP (W3C Web Machine Learning CG draft, https://webmachinelearning.github.io/webmcp/)
+// lets an agent running in the browser call tools the page registers, with the
+// user's own session, instead of screen-scraping and clicking. The draft API is
+//
+// await document.modelContext.registerTool(tool, { signal, exposedTo })
+//
+// Chrome 149's origin trial and older previews expose it as navigator.modelContext,
+// and early builds returned synchronously or offered unregisterTool(name). This
+// module hides those differences, validates tool definitions, and is a silent no-op
+// where WebMCP does not exist, so a site can ship it unconditionally.
+
+export const VERSION = '0.1.0';
+
+const NAME_RE = /^[A-Za-z0-9_.-]{1,64}$/;
+
+/** The page's ModelContext, or null when the browser has no WebMCP. */
+export function getModelContext(doc = globalThis.document, nav = globalThis.navigator) {
+ try {
+ if (doc && doc.modelContext && typeof doc.modelContext.registerTool === 'function') return doc.modelContext;
+ if (nav && nav.modelContext && typeof nav.modelContext.registerTool === 'function') return nav.modelContext;
+ } catch {
+ // A SecureContext-only getter can throw on http: pages.
+ }
+ return null;
+}
+
+export function isSupported(doc, nav) {
+ return getModelContext(doc, nav) !== null;
+}
+
+/**
+ * Validate and normalise a tool definition. Returns a new object; throws TypeError
+ * on anything the browser would reject, so mistakes surface in tests and in
+ * browsers without WebMCP rather than only in Chrome.
+ */
+export function defineTool(tool) {
+ if (!tool || typeof tool !== 'object') throw new TypeError('webmcp: tool must be an object');
+ const { name, title, description, inputSchema, outputSchema, execute, annotations } = tool;
+ if (typeof name !== 'string' || !NAME_RE.test(name)) {
+ throw new TypeError(`webmcp: tool name ${JSON.stringify(name)} must match ${NAME_RE}`);
+ }
+ if (typeof description !== 'string' || !description.trim()) {
+ throw new TypeError(`webmcp: tool ${name} needs a description`);
+ }
+ if (typeof execute !== 'function') throw new TypeError(`webmcp: tool ${name} needs an execute function`);
+ for (const [key, schema] of [['inputSchema', inputSchema], ['outputSchema', outputSchema]]) {
+ if (schema !== undefined && (schema === null || typeof schema !== 'object' || Array.isArray(schema))) {
+ throw new TypeError(`webmcp: tool ${name} ${key} must be a JSON Schema object`);
+ }
+ }
+ const out = {
+ name,
+ description: description.trim(),
+ inputSchema: inputSchema ?? { type: 'object', properties: {} },
+ execute,
+ };
+ if (title) out.title = String(title);
+ if (outputSchema) out.outputSchema = outputSchema;
+ if (annotations) {
+ const a = {};
+ for (const k of ['readOnlyHint', 'untrustedContentHint', 'consequentialHint', 'debugging']) {
+ if (annotations[k] !== undefined) a[k] = Boolean(annotations[k]);
+ }
+ out.annotations = a;
+ }
+ return out;
+}
+
+// The agent receives whatever execute resolves to, serialised. Errors become a
+// plain { error } result rather than a rejected promise, which some agents report
+// as "the tool crashed" and never show the message from.
+function wrapExecute(tool, onError) {
+ return async (input, options) => {
+ try {
+ const result = await tool.execute(input ?? {}, options ?? {});
+ return result === undefined ? { ok: true } : result;
+ } catch (err) {
+ if (options?.signal?.aborted) throw err;
+ onError?.(err, tool);
+ return { error: String(err?.message ?? err) };
+ }
+ };
+}
+
+/**
+ * Register one tool. Resolves to a function that unregisters it.
+ * Resolves to a no-op when WebMCP is unavailable.
+ *
+ * options.signal aborting it unregisters the tool
+ * options.exposedTo origins (in this document's tree) the tool is exposed to
+ * options.onError called with (error, tool) when execute throws
+ * options.context a ModelContext to use (tests, iframes)
+ */
+export async function registerTool(tool, options = {}) {
+ const def = defineTool(tool);
+ const mc = options.context ?? getModelContext();
+ if (!mc) return () => {};
+ if (options.signal?.aborted) return () => {};
+
+ const controller = new AbortController();
+ const regOptions = { signal: controller.signal };
+ if (options.exposedTo) regOptions.exposedTo = options.exposedTo;
+
+ const registered = await mc.registerTool({ ...def, execute: wrapExecute(def, options.onError) }, regOptions);
+
+ let done = false;
+ const unregister = () => {
+ if (done) return;
+ done = true;
+ controller.abort();
+ // Pre-signal builds: an object with unregister(), or unregisterTool(name).
+ try {
+ if (registered && typeof registered.unregister === 'function') registered.unregister();
+ else if (typeof mc.unregisterTool === 'function') mc.unregisterTool(def.name);
+ } catch {
+ // Already gone.
+ }
+ };
+ options.signal?.addEventListener('abort', unregister, { once: true });
+ return unregister;
+}
+
+/**
+ * Register several tools. Resolves to one function that unregisters them all.
+ * A tool that fails to register (duplicate name, bad schema) is reported to
+ * options.onError and skipped; the rest still register.
+ */
+export async function registerTools(tools, options = {}) {
+ const offs = [];
+ for (const tool of tools) {
+ try {
+ offs.push(await registerTool(tool, options));
+ } catch (err) {
+ if (options.onError) options.onError(err, tool);
+ else console.warn('[webmcp]', err?.message ?? err);
+ }
+ }
+ return () => offs.forEach((off) => off());
+}
+
+/** List the tools visible to this page (draft getTools); [] without WebMCP. */
+export async function listTools(options = {}) {
+ const mc = options.context ?? getModelContext();
+ if (!mc || typeof mc.getTools !== 'function') return [];
+ return mc.getTools(options.fromOrigins ? { fromOrigins: options.fromOrigins } : {});
+}
diff --git a/src/embed.js b/src/embed.js
new file mode 100644
index 0000000..cc4d5ba
--- /dev/null
+++ b/src/embed.js
@@ -0,0 +1,80 @@
+// Drop-in WebMCP for any page, static or framework:
+//
+//
+//
+// Registers site_info + open_page always, search_site when a search template is
+// given, every tool of the site's MCP server when data-mcp is given, and an
+// imperative tool for every