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
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.2.0",
"version": "0.2.1",
"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
25 changes: 22 additions & 3 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
// 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.2.0';
export const VERSION = '0.2.1';

const NAME_RE = /^[A-Za-z0-9_.-]{1,64}$/;
// Symbol.for, not Symbol(): every copy of this module must find the same key.
const REGISTRY = Symbol.for('@profullstack/webmcp.registered');

/** The page's ModelContext, or null when the browser has no WebMCP. */
export function getModelContext(doc = globalThis.document, nav = globalThis.navigator) {
Expand Down Expand Up @@ -115,16 +117,31 @@ export async function registerTool(tool, options = {}) {
if (!mc) return () => {};
if (options.signal?.aborted) return () => {};

// One registration per tool name per ModelContext, page-wide. The registry
// lives on the context itself, so two copies of this library (a site tag and
// the crawlproof stats.js plugin, or @0 and a pinned version) share it and the
// second copy skips instead of registering a duplicate.
const names = (mc[REGISTRY] ??= new Set());
if (names.has(def.name)) return () => {};
names.add(def.name);

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, options.onCall) }, regOptions);
let registered;
try {
registered = await mc.registerTool({ ...def, execute: wrapExecute(def, options.onError, options.onCall) }, regOptions);
} catch (err) {
names.delete(def.name);
throw err;
}

let done = false;
const unregister = () => {
if (done) return;
done = true;
names.delete(def.name);
controller.abort();
// Pre-signal builds: an object with unregister(), or unregisterTool(name).
try {
Expand All @@ -134,7 +151,9 @@ export async function registerTool(tool, options = {}) {
// Already gone.
}
};
options.signal?.addEventListener('abort', unregister, { once: true });
// Aborted while registerTool was pending (React StrictMode mount/unmount).
if (options.signal?.aborted) unregister();
else options.signal?.addEventListener('abort', unregister, { once: true });
return unregister;
}

Expand Down
36 changes: 34 additions & 2 deletions test/webmcp.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ test('no WebMCP: registerTool is a no-op', async () => {
assert.equal(typeof off, 'function');
});

test('registerTools skips a duplicate and keeps the rest', async () => {
test('registerTools skips a duplicate name and keeps the rest', async () => {
const mc = fakeContext();
const errors = [];
const off = await registerTools(
Expand All @@ -118,11 +118,43 @@ test('registerTools skips a duplicate and keeps the rest', async () => {
{ context: mc, onError: (e) => errors.push(e) },
);
assert.deepEqual([...mc.tools.keys()], ['a', 'b']);
assert.equal(errors.length, 1);
assert.equal(mc.tools.get('a').description, 'd');
assert.equal(errors.length, 0);
off();
assert.equal(mc.tools.size, 0);
});

test('a second copy of the library (separate module instance) never double-registers', async () => {
const mc = fakeContext();
const copy = await import('../src/core.js?copy=2'); // a distinct module instance
await registerTool({ name: 'site_info', description: 'first', execute: () => 1 }, { context: mc });
const off2 = await copy.registerTool({ name: 'site_info', description: 'second', execute: () => 2 }, { context: mc });
assert.equal(mc.tools.size, 1);
assert.equal(mc.tools.get('site_info').description, 'first');
off2(); // the skipped copy's unregister must not remove the first copy's tool
assert.equal(mc.tools.size, 1);
});

test('unregister frees the name for re-registration; abort during a pending register cleans up', async () => {
const mc = fakeContext();
const off = await registerTool({ name: 'x', description: 'd', execute: () => 1 }, { context: mc });
off();
await registerTool({ name: 'x', description: 'again', execute: () => 1 }, { context: mc });
assert.equal(mc.tools.get('x').description, 'again');

const slow = { ...fakeContext() };
const inner = fakeContext();
slow.tools = inner.tools;
slow.registerTool = async (t, o) => { await new Promise((r) => setTimeout(r, 10)); return inner.registerTool(t, o); };
const ac = new AbortController();
const p = registerTool({ name: 'y', description: 'd', execute: () => 1 }, { context: slow, signal: ac.signal });
ac.abort();
await p;
assert.equal(inner.tools.size, 0);
await registerTool({ name: 'y', description: 'd', execute: () => 1 }, { context: slow });
assert.equal(inner.tools.size, 1);
});

test('mapAnnotations: unknown tools are consequential, read-only ones are not', () => {
assert.deepEqual(mapAnnotations({}), { readOnlyHint: false, consequentialHint: true, untrustedContentHint: false });
assert.deepEqual(mapAnnotations({ readOnlyHint: true, openWorldHint: true }), {
Expand Down
Loading