Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
141 changes: 141 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -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"
108 changes: 108 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
<script type="module" data-webmcp
src="https://cdn.jsdelivr.net/npm/@profullstack/webmcp@0/src/embed.js"
data-mcp="/mcp"
data-search-api="/api/search?q={query}&limit={limit}"
data-pages='{"pricing":"/pricing","docs":"/docs"}'></script>
```

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 `<form toolname tooldescription>` | browsers without declarative WebMCP | fills the form; submits only with `toolautosubmit` |

Other attributes: `data-mcp-prefix` (prefix bridged names), `data-mcp-exclude`
(comma list), `data-search` (results page template), `data-search-description`,
`data-name`, `data-description`, `data-llms-txt="false"`, `data-forms="false"`.
Or set `window.webmcpConfig = {...}` (camelCase) before the tag.

`@0` gets every 0.x release automatically; pin `@0.1.0` if you would rather not.
CSP: allow `https://cdn.jsdelivr.net` in `script-src`.

Pages can add tools later: `window.ProfullstackWebMCP.registerTool({...})`, and
`document` fires `webmcp:ready` with the registered names.

## Forms

Use the declarative attributes from the WebMCP proposal. Browsers that support them
make the tool natively; the embed registers the same tool imperatively everywhere else.

```html
<form toolname="subscribe" tooldescription="Subscribe an email to the newsletter" toolautosubmit>
<input name="email" type="email" required toolparamdescription="Subscriber email">
<select name="plan"><option>weekly</option><option>daily</option></select>
</form>
```

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.
79 changes: 79 additions & 0 deletions bin/webmcp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#!/usr/bin/env node
// webmcp: check a site's WebMCP setup and print the embed snippet.
//
// webmcp check <url> what an agent would find on this page
// webmcp snippet [options] print the <script> tag for a site
// webmcp mcp <url> list the tools of an MCP endpoint (what data-mcp would bridge)

import { mcpCall } from '../src/mcp-bridge.js';
import { VERSION } from '../src/core.js';

const UA =
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36';
const CDN = 'https://cdn.jsdelivr.net/npm/@profullstack/webmcp@0/src/embed.js';

function arg(name) {
const i = process.argv.indexOf(`--${name}`);
return i > 0 ? process.argv[i + 1] : undefined;
}

function attr(html, re) {
return [...html.matchAll(re)].map((m) => m[1]);
}

async function check(url) {
const res = await fetch(url, { headers: { 'user-agent': UA, accept: 'text/html' }, redirect: 'follow' });
const html = await res.text();
const embed = /@profullstack\/webmcp[^"']*embed\.js/.test(html);
const imperative = /modelContext/.test(html);
const forms = attr(html, /<form[^>]*\btoolname="([^"]+)"/g);
const out = { url: res.url, status: res.status, embed, imperativeInHtml: imperative, declarativeForms: forms };
const csp = res.headers.get('content-security-policy');
if (csp && embed && !/cdn\.jsdelivr\.net/.test(csp)) out.cspWarning = 'CSP does not allow cdn.jsdelivr.net in script-src';
const mcpPath = attr(html, /data-mcp="([^"]+)"/g)[0];
if (mcpPath) {
try {
const tools = await mcpCall(new URL(mcpPath, res.url).href, { credentials: 'omit' }).listTools();
out.mcp = { path: mcpPath, tools: tools.map((t) => t.name) };
} catch (err) {
out.mcp = { path: mcpPath, error: err.message };
}
}
out.ok = embed || imperative || forms.length > 0;
return out;
}

function snippet() {
const attrs = [['data-webmcp', null]];
for (const k of ['mcp', 'search', 'search-api', 'pages', 'name', 'mcp-prefix']) {
const v = arg(k);
if (v) attrs.push([`data-${k}`, v]);
}
const a = attrs.map(([k, v]) => (v == null ? k : `${k}='${v.replace(/'/g, '&#39;')}'`)).join(' ');
return `<script type="module" src="${CDN}" ${a}></script>`;
}

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 <url> 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 <url> list an MCP endpoint's tools`);
process.exit(cmd ? 1 : 0);
}
} catch (err) {
console.error(`webmcp: ${err.message}`);
process.exit(2);
}
Loading
Loading