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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,24 @@ 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.

Every agent call fires `webmcp:call` on `document` with `{ name, ok, ms, error? }`
(never the input or the result), so analytics can count which tools agents use.
In code, pass `onCall` to `registerTool`/`registerTools`/`bridgeMcpServer`.

### Via crawlproof stats.js

Sites already on [crawlproof](https://crawlproof.com) stats can skip the separate tag:

```html
<script data-site="<project_id>" src="https://crawlproof.com/stats.js"
data-webmcp data-webmcp-mcp="/mcp" data-webmcp-search="/search?q={query}"></script>
```

stats.js loads this embed only in browsers that have WebMCP, and records each
agent tool call as a `webmcp_tool` event. `data-webmcp-*` takes the same keys as
the embed's `data-*` attributes (`-mcp`, `-mcp-prefix`, `-mcp-exclude`, `-search`,
`-search-api`, `-pages`, `-name`, `-description`).

## Forms

Use the declarative attributes from the WebMCP proposal. Browsers that support them
Expand Down
2 changes: 2 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export interface RegisterOptions {
signal?: AbortSignal;
exposedTo?: string[];
onError?: (error: unknown, tool: WebMCPTool) => void;
/** After each agent call: tool name, outcome, duration. Never the input or result. */
onCall?: (detail: { name: string; ok: boolean; ms: number; error?: 'error' | 'aborted' }) => void;
context?: unknown;
}

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@profullstack/webmcp",
"version": "0.1.0",
"version": "0.2.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"],
Expand Down
24 changes: 20 additions & 4 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// 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';
export const VERSION = '0.2.0';

const NAME_RE = /^[A-Za-z0-9_.-]{1,64}$/;

Expand Down Expand Up @@ -71,13 +71,28 @@ export function defineTool(tool) {
// 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) {
//
// onCall({ name, ok, ms, error? }) fires once per agent call, after it settles.
// It never sees the input or the result: analytics get what was used, not what
// the person typed.
function wrapExecute(tool, onError, onCall) {
const report = (detail) => {
try {
onCall?.(detail);
} catch {
// A broken listener must not break the tool.
}
};
return async (input, options) => {
const started = Date.now();
try {
const result = await tool.execute(input ?? {}, options ?? {});
report({ name: tool.name, ok: true, ms: Date.now() - started });
return result === undefined ? { ok: true } : result;
} catch (err) {
if (options?.signal?.aborted) throw err;
const aborted = Boolean(options?.signal?.aborted);
report({ name: tool.name, ok: false, ms: Date.now() - started, error: aborted ? 'aborted' : 'error' });
if (aborted) throw err;
onError?.(err, tool);
return { error: String(err?.message ?? err) };
}
Expand All @@ -91,6 +106,7 @@ function wrapExecute(tool, onError) {
* 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.onCall called with { name, ok, ms, error? } after each agent call
* options.context a ModelContext to use (tests, iframes)
*/
export async function registerTool(tool, options = {}) {
Expand All @@ -103,7 +119,7 @@ export async function registerTool(tool, options = {}) {
const regOptions = { signal: controller.signal };
if (options.exposedTo) regOptions.exposedTo = options.exposedTo;

const registered = await mc.registerTool({ ...def, execute: wrapExecute(def, options.onError) }, regOptions);
const registered = await mc.registerTool({ ...def, execute: wrapExecute(def, options.onError, options.onCall) }, regOptions);

let done = false;
const unregister = () => {
Expand Down
22 changes: 19 additions & 3 deletions src/embed.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,23 @@ function findConfig() {
};
}

// Every agent call is announced on document as `webmcp:call` with
// { name, ok, ms, error? } (never the input or result), so analytics such as
// crawlproof stats.js can count which tools agents use.
function onCall(detail) {
document.dispatchEvent(new CustomEvent('webmcp:call', { detail }));
}

async function main() {
const api = { VERSION, supported: false, tools: [], registerTool, registerTools };
if (globalThis.ProfullstackWebMCP) return; // loaded twice (site tag + stats.js plugin)
const withCall = (opts = {}) => ({ onCall, ...opts });
const api = {
VERSION,
supported: false,
tools: [],
registerTool: (tool, opts) => registerTool(tool, withCall(opts)),
registerTools: (tools, opts) => registerTools(tools, withCall(opts)),
};
globalThis.ProfullstackWebMCP = api;
if (!getModelContext()) return;
api.supported = true;
Expand All @@ -58,16 +73,17 @@ async function main() {

const offs = [];
const own = siteTools(cfg);
offs.push(await registerTools(own, { onError }));
offs.push(await registerTools(own, { onError, onCall }));
api.tools.push(...own.map((t) => t.name));

if (cfg.forms) offs.push(await registerForms(document, { onError }));
if (cfg.forms) offs.push(await registerForms(document, { onError, onCall }));

if (cfg.mcp) {
const res = await bridgeMcpServer(new URL(cfg.mcp, location.href).href, {
prefix: cfg.mcpPrefix,
exclude: cfg.mcpExclude,
onError,
onCall,
});
if (res.error) console.info('[webmcp] MCP bridge skipped:', res.error);
offs.push(res.unregister);
Expand Down
23 changes: 23 additions & 0 deletions test/webmcp.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,29 @@ test('registerTool registers, wraps errors as results, and unregisters', async (
off(); // idempotent
});

test('onCall reports name/ok/ms per call, never input, and a throwing listener is harmless', async () => {
const mc = fakeContext();
const calls = [];
await registerTools(
[
{ name: 'good', description: 'd', execute: () => ({ secret: 1 }) },
{ name: 'bad', description: 'd', execute: () => { throw new Error('x'); } },
],
{ context: mc, onCall: (d) => calls.push(d) },
);
await mc.tools.get('good').execute({ password: 'p' }, {});
await mc.tools.get('bad').execute({}, {});
assert.deepEqual(calls.map(({ name, ok, error }) => ({ name, ok, error })), [
{ name: 'good', ok: true, error: undefined },
{ name: 'bad', ok: false, error: 'error' },
]);
assert.ok(calls.every((c) => typeof c.ms === 'number' && !('input' in c) && !('result' in c)));

const mc2 = fakeContext();
await registerTool({ name: 't', description: 'd', execute: () => 7 }, { context: mc2, onCall: () => { throw new Error('listener'); } });
assert.equal(await mc2.tools.get('t').execute({}, {}), 7);
});

test('caller signal unregisters', async () => {
const mc = fakeContext();
const ac = new AbortController();
Expand Down
Loading