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 `
` | 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 + + + +
+``` + +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
in browsers without +// declarative WebMCP. Silent no-op in browsers without WebMCP. +// +// Pages can add their own tools later through window.ProfullstackWebMCP, or set +// window.webmcpConfig (same keys, camelCase) before this script runs. + +import { getModelContext, registerTool, registerTools, VERSION } from './core.js'; +import { siteTools } from './site.js'; +import { bridgeMcpServer } from './mcp-bridge.js'; +import { registerForms } from './forms.js'; + +function findConfig() { + const here = import.meta.url; + const el = + [...document.querySelectorAll('script[src]')].find((s) => s.src === here) || + document.querySelector('script[data-webmcp]'); + const d = el?.dataset ?? {}; + let pages; + try { + pages = d.pages ? JSON.parse(d.pages) : undefined; + } catch { + console.warn('[webmcp] data-pages is not valid JSON'); + } + return { + name: d.name, + description: d.description, + mcp: d.mcp, + mcpPrefix: d.mcpPrefix, + mcpExclude: d.mcpExclude ? d.mcpExclude.split(',').map((s) => s.trim()) : undefined, + search: d.search, + searchApi: d.searchApi, + searchDescription: d.searchDescription, + pages, + llmsTxt: d.llmsTxt === 'false' ? false : d.llmsTxt, + forms: d.forms !== 'false', + ...(globalThis.webmcpConfig || {}), + }; +} + +async function main() { + const api = { VERSION, supported: false, tools: [], registerTool, registerTools }; + globalThis.ProfullstackWebMCP = api; + if (!getModelContext()) return; + api.supported = true; + const cfg = findConfig(); + const onError = (err, tool) => console.warn('[webmcp]', tool?.name ?? '', err?.message ?? err); + + const offs = []; + const own = siteTools(cfg); + offs.push(await registerTools(own, { onError })); + api.tools.push(...own.map((t) => t.name)); + + if (cfg.forms) offs.push(await registerForms(document, { onError })); + + if (cfg.mcp) { + const res = await bridgeMcpServer(new URL(cfg.mcp, location.href).href, { + prefix: cfg.mcpPrefix, + exclude: cfg.mcpExclude, + onError, + }); + if (res.error) console.info('[webmcp] MCP bridge skipped:', res.error); + offs.push(res.unregister); + api.tools.push(...res.tools); + } + api.unregisterAll = () => offs.forEach((off) => off()); + document.dispatchEvent(new CustomEvent('webmcp:ready', { detail: { tools: api.tools.slice() } })); +} + +main().catch((err) => console.warn('[webmcp]', err?.message ?? err)); diff --git a/src/forms.js b/src/forms.js new file mode 100644 index 0000000..55f8222 --- /dev/null +++ b/src/forms.js @@ -0,0 +1,135 @@ +// Forms as tools. +// +// The WebMCP declarative proposal makes +// a tool natively: each named control is a property, toolparamdescription its +// description, toolautosubmit lets the agent submit. Browsers that ship only the +// imperative API ignore those attributes, so registerForms() reads the same +// attributes and registers an equivalent imperative tool there. Write the +// attributes once; both kinds of browser get the tool. + +import { registerTools } from './core.js'; + +export function supportsDeclarativeForms(win = globalThis) { + const F = win.HTMLFormElement; + return Boolean(F && ('toolName' in F.prototype || 'toolname' in F.prototype)); +} + +const SKIP = new Set(['submit', 'button', 'reset', 'image', 'file', 'hidden', 'password']); + +function typeOf(el) { + return (el.getAttribute('type') || '').toLowerCase(); +} + +function describe(el) { + const label = el.id && el.ownerDocument?.querySelector?.(`label[for="${el.id}"]`)?.textContent?.trim(); + return ( + el.getAttribute('toolparamdescription') || el.getAttribute('aria-label') || label || el.getAttribute('placeholder') || undefined + ); +} + +function controlSchema(el) { + const tag = el.tagName.toLowerCase(); + const type = typeOf(el); + const s = {}; + if (tag === 'select') { + s.type = 'string'; + s.enum = [...el.options].map((o) => o.value).filter((v) => v !== ''); + } else if (type === 'checkbox') { + s.type = 'boolean'; + } else if (type === 'number' || type === 'range') { + s.type = 'number'; + if (el.getAttribute('min') != null) s.minimum = Number(el.getAttribute('min')); + if (el.getAttribute('max') != null) s.maximum = Number(el.getAttribute('max')); + } else { + s.type = 'string'; + if (type === 'email') s.format = 'email'; + if (type === 'url') s.format = 'uri'; + if (type === 'date') s.format = 'date'; + const max = Number(el.getAttribute('maxlength')); + if (max > 0) s.maxLength = max; + } + const d = describe(el); + if (d) s.description = d; + return s; +} + +/** JSON Schema for a form, synthesised from its named controls. */ +export function formSchema(form) { + const properties = {}; + const required = []; + const els = [...form.elements]; + for (const el of els) { + const name = el.name; + if (!name || el.disabled || properties[name]) continue; + const type = typeOf(el); + if (SKIP.has(type)) continue; + if (type === 'radio') { + properties[name] = { type: 'string', enum: els.filter((r) => r.name === name).map((r) => r.value) }; + const d = el.getAttribute('toolparamdescription'); + if (d) properties[name].description = d; + } else { + properties[name] = controlSchema(el); + } + if (el.required) required.push(name); + } + return required.length ? { type: 'object', properties, required } : { type: 'object', properties }; +} + +function setValue(form, name, value) { + for (const el of [...form.elements].filter((e) => e.name === name)) { + const type = typeOf(el); + if (SKIP.has(type)) continue; + if (type === 'checkbox') el.checked = Boolean(value); + else if (type === 'radio') el.checked = el.value === String(value); + else el.value = value == null ? '' : String(value); + // Frameworks (React, Svelte) listen for these, not for .value writes. + el.dispatchEvent(new Event('input', { bubbles: true })); + el.dispatchEvent(new Event('change', { bubbles: true })); + } +} + +function toolName(raw) { + return String(raw).trim().replace(/\s+/g, '_').replace(/[^A-Za-z0-9_.-]/g, '').slice(0, 64); +} + +/** + * An imperative tool for one form. Fills the named controls; submits when the + * form has toolautosubmit (or options.autosubmit), otherwise focuses the submit + * button so the person reviews and sends it. + */ +export function formTool(form, options = {}) { + const autosubmit = options.autosubmit ?? form.hasAttribute('toolautosubmit'); + const allowed = formSchema(form).properties; + return { + name: toolName(options.name ?? form.getAttribute('toolname')), + description: options.description ?? form.getAttribute('tooldescription'), + inputSchema: formSchema(form), + annotations: { consequentialHint: autosubmit, ...options.annotations }, + async execute(input) { + const fields = Object.keys(input ?? {}).filter((k) => k in allowed); + for (const k of fields) setValue(form, k, input[k]); + if (typeof form.checkValidity === 'function' && !form.checkValidity()) { + form.reportValidity?.(); + return { submitted: false, error: 'The form rejected these values', fields }; + } + if (autosubmit) { + if (typeof form.requestSubmit === 'function') form.requestSubmit(); + else form.submit(); + return { submitted: true }; + } + form.querySelector?.('[type=submit],button:not([type])')?.focus?.(); + return { submitted: false, note: 'Filled in. Ask the person to review the form and press submit.' }; + }, + }; +} + +/** + * Register every form[toolname][tooldescription] under root as an imperative + * tool, unless the browser already turns those forms into tools itself. + */ +export async function registerForms(root = globalThis.document, options = {}) { + if (!root?.querySelectorAll) return () => {}; + if (!options.force && supportsDeclarativeForms()) return () => {}; + const forms = [...root.querySelectorAll('form[toolname][tooldescription]')]; + return registerTools(forms.map((f) => formTool(f)), options); +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..32c1826 --- /dev/null +++ b/src/index.js @@ -0,0 +1,5 @@ +// @profullstack/webmcp. See core.js for the WebMCP background. +export { VERSION, getModelContext, isSupported, defineTool, registerTool, registerTools, listTools } from './core.js'; +export { bridgeMcpServer, mcpCall, mapAnnotations, unwrapResult } from './mcp-bridge.js'; +export { siteTools } from './site.js'; +export { formTool, formSchema, registerForms, supportsDeclarativeForms } from './forms.js'; diff --git a/src/mcp-bridge.js b/src/mcp-bridge.js new file mode 100644 index 0000000..c2155fa --- /dev/null +++ b/src/mcp-bridge.js @@ -0,0 +1,194 @@ +// Bridge a site's existing MCP server into WebMCP. +// +// House rule: anything an agent should operate ships an MCP server, and most of +// ours answer Streamable HTTP JSON-RPC at /mcp. bridgeMcpServer() lists those +// tools and registers each one as a WebMCP tool whose execute() is a tools/call +// to the same server, from the page, with the user's cookies. One line turns the +// server that an outside agent needs an API key for into tools a browser agent +// can use as the signed-in person. + +import { registerTools, VERSION } from './core.js'; + +const PROTOCOL = '2025-06-18'; + +async function readJsonRpc(res) { + const type = res.headers.get('content-type') || ''; + const text = await res.text(); + if (type.includes('text/event-stream')) { + // Take the last JSON-RPC response carried in a data: line. + let last = null; + for (const line of text.split(/\r?\n/)) { + if (!line.startsWith('data:')) continue; + try { + const msg = JSON.parse(line.slice(5).trim()); + if (msg && (msg.result !== undefined || msg.error !== undefined)) last = msg; + } catch { + // keep-alive or partial line + } + } + if (!last) throw new Error('webmcp: MCP server sent no JSON-RPC result'); + return last; + } + try { + return JSON.parse(text); + } catch { + throw new Error(`webmcp: MCP server answered ${res.status} with non-JSON`); + } +} + +/** A small MCP Streamable-HTTP client bound to one endpoint. */ +export function mcpCall(url, opts = {}) { + const fetchImpl = opts.fetch ?? globalThis.fetch; + const credentials = opts.credentials ?? 'same-origin'; + let sessionId = null; + let initialized = null; + let nextId = 1; + + async function headers() { + const h = { + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + 'mcp-protocol-version': PROTOCOL, + ...(typeof opts.headers === 'function' ? await opts.headers() : opts.headers), + }; + if (sessionId) h['mcp-session-id'] = sessionId; + return h; + } + + async function rpc(method, params, signal) { + const res = await fetchImpl(url, { + method: 'POST', + headers: await headers(), + credentials, + body: JSON.stringify({ jsonrpc: '2.0', id: nextId++, method, params }), + signal, + }); + const sid = res.headers.get('mcp-session-id'); + if (sid) sessionId = sid; + if (res.status === 401 || res.status === 403) { + throw new Error(`webmcp: MCP server refused (${res.status}); the person needs to sign in`); + } + const msg = await readJsonRpc(res); + if (msg.error) throw new Error(msg.error.message || `webmcp: MCP error ${msg.error.code}`); + return msg.result; + } + + function init() { + initialized ??= rpc('initialize', { + protocolVersion: PROTOCOL, + capabilities: {}, + clientInfo: { name: '@profullstack/webmcp', version: VERSION }, + }) + .then(async (result) => { + // A notification: no id, nothing to read back. + await fetchImpl(url, { + method: 'POST', + headers: await headers(), + credentials, + body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }), + }).catch(() => {}); + return result; + }) + .catch((err) => { + initialized = null; + throw err; + }); + return initialized; + } + + return { + async listTools(signal) { + await init(); + const tools = []; + let cursor; + do { + const r = await rpc('tools/list', cursor ? { cursor } : {}, signal); + tools.push(...(r?.tools ?? [])); + cursor = r?.nextCursor; + } while (cursor); + return tools; + }, + async callTool(name, args, signal) { + await init(); + return rpc('tools/call', { name, arguments: args ?? {} }, signal); + }, + }; +} + +// MCP annotations -> WebMCP annotations. A tool counts as consequential unless the +// server says it only reads or is explicitly non-destructive, so the browser asks +// the person before it runs. +export function mapAnnotations(a = {}) { + const readOnly = a.readOnlyHint === true; + return { + readOnlyHint: readOnly, + consequentialHint: !readOnly && a.destructiveHint !== false, + untrustedContentHint: a.openWorldHint === true, + }; +} + +// tools/call result -> what the agent gets back. +export function unwrapResult(r) { + if (!r) return { ok: true }; + const content = r.content ?? []; + if (r.isError) { + const msg = content.filter((c) => c.type === 'text').map((c) => c.text).join('\n'); + throw new Error(msg || 'tool failed'); + } + if (r.structuredContent !== undefined) return r.structuredContent; + if (content.length && content.every((c) => c.type === 'text')) { + const text = content.map((c) => c.text).join('\n'); + try { + return JSON.parse(text); + } catch { + return text; + } + } + return content; +} + +function keepFn(include, exclude) { + return (n) => { + if (typeof include === 'function' && !include(n)) return false; + if (Array.isArray(include) && !include.includes(n)) return false; + if (typeof exclude === 'function' && exclude(n)) return false; + if (Array.isArray(exclude) && exclude.includes(n)) return false; + return true; + }; +} + +/** + * Register every tool of the MCP server at `url` as a WebMCP tool. + * + * options.include / exclude tool names (array or predicate) to keep / drop + * options.prefix prepended to each name, e.g. 'rssamp_' + * options.headers object or async () => object, e.g. a bearer token + * options.signal aborting unregisters everything + * + * Resolves to { tools, unregister, error? }. Never rejects: a server that is down + * or needs auth resolves with tools: [] and the reason in `error`. + */ +export async function bridgeMcpServer(url, options = {}) { + const client = mcpCall(url, options); + let listed; + try { + listed = await client.listTools(options.signal); + } catch (err) { + return { tools: [], unregister: () => {}, error: String(err?.message ?? err) }; + } + const keep = keepFn(options.include, options.exclude); + const prefix = options.prefix ?? ''; + const tools = listed + .filter((t) => keep(t.name)) + .map((t) => ({ + name: (prefix + t.name).replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 64), + title: t.title ?? t.annotations?.title, + description: t.description || t.title || t.name, + inputSchema: t.inputSchema ?? { type: 'object', properties: {} }, + ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}), + annotations: mapAnnotations(t.annotations), + execute: async (input, { signal } = {}) => unwrapResult(await client.callTool(t.name, input, signal)), + })); + const unregister = await registerTools(tools, options); + return { tools: tools.map((t) => t.name), unregister }; +} diff --git a/src/react.js b/src/react.js new file mode 100644 index 0000000..850c3d3 --- /dev/null +++ b/src/react.js @@ -0,0 +1,38 @@ +// React binding: register a tool while a component is mounted. +// +// 'use client'; +// import { useWebMCPTool } from '@profullstack/webmcp/react'; +// useWebMCPTool({ name: 'add_to_cart', description: '...', inputSchema, execute }, [cart]); +// +// execute always sees the latest props/state; the registration itself only +// changes when deps change. + +import { useEffect, useRef } from 'react'; +import { registerTool, registerTools } from './core.js'; + +export function useWebMCPTool(tool, deps = []) { + const ref = useRef(tool); + ref.current = tool; + useEffect(() => { + const ac = new AbortController(); + registerTool({ ...ref.current, execute: (input, opts) => ref.current.execute(input, opts) }, { signal: ac.signal }).catch( + (err) => console.warn('[webmcp]', err?.message ?? err), + ); + return () => ac.abort(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ref.current.name, ...deps]); +} + +export function useWebMCPTools(tools, deps = []) { + const ref = useRef(tools); + ref.current = tools; + useEffect(() => { + const ac = new AbortController(); + registerTools( + ref.current.map((t, i) => ({ ...t, execute: (input, opts) => ref.current[i].execute(input, opts) })), + { signal: ac.signal }, + ).catch((err) => console.warn('[webmcp]', err?.message ?? err)); + return () => ac.abort(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, deps); +} diff --git a/src/site.js b/src/site.js new file mode 100644 index 0000000..1a5fd2f --- /dev/null +++ b/src/site.js @@ -0,0 +1,118 @@ +// The tools every Profullstack property can offer with no app code: +// site_info what this site is and what an agent can do here (llms.txt if present) +// search_site run the site's search (JSON API when given, else open the results page) +// open_page navigate to one of the site's own pages +// +// All three only read, and only touch this origin. + +const MAX_LLMS = 8000; + +function fill(template, values) { + return template.replace(/\{(\w+)\}/g, (_, k) => encodeURIComponent(values[k] ?? '')); +} + +function sameOriginUrl(path, loc) { + const u = new URL(String(path), loc.href); + if (u.origin !== loc.origin) throw new Error('only pages on this site can be opened'); + return u; +} + +/** + * options.name site name (default: document.title) + * options.description one line (default: meta description) + * options.search results page template, e.g. '/search?q={query}' + * options.searchApi JSON endpoint template, e.g. '/api/search?q={query}&limit={limit}' + * options.searchDescription what search_site searches, for the agent + * options.pages { label: '/path' } the agent may open (default: any same-origin path) + * options.llmsTxt path to llms.txt, or false to skip (default '/llms.txt') + * options.extraInfo object merged into site_info's answer + */ +export function siteTools(options = {}) { + const doc = options.document ?? globalThis.document; + const loc = options.location ?? globalThis.location; + const fetchImpl = options.fetch ?? globalThis.fetch; + const tools = []; + + const meta = (n) => + doc?.querySelector?.(`meta[name="${n}"],meta[property="og:${n}"]`)?.getAttribute('content') || undefined; + + tools.push({ + name: 'site_info', + title: 'About this site', + description: + 'Describe this website: what it is, what an agent can do here, its main pages, and its llms.txt guide when it has one. Call this first.', + inputSchema: { type: 'object', properties: {} }, + annotations: { readOnlyHint: true }, + async execute() { + const info = { + name: options.name ?? doc?.title, + description: options.description ?? meta('description'), + url: loc?.origin, + page: loc?.pathname, + ...(options.pages ? { pages: options.pages } : {}), + ...options.extraInfo, + }; + if (options.llmsTxt !== false && fetchImpl && loc) { + try { + const r = await fetchImpl(new URL(options.llmsTxt ?? '/llms.txt', loc.href).href, { credentials: 'same-origin' }); + const type = r.headers.get('content-type') || 'text/plain'; + if (r.ok && /text\/(plain|markdown)/.test(type)) info.llmsTxt = (await r.text()).slice(0, MAX_LLMS); + } catch { + // no llms.txt + } + } + return info; + }, + }); + + if (options.search || options.searchApi) { + tools.push({ + name: 'search_site', + title: 'Search this site', + description: options.searchDescription ?? `Search ${options.name ?? 'this site'} and return matching results.`, + inputSchema: { + type: 'object', + properties: { + query: { type: 'string', description: 'What to search for' }, + limit: { type: 'integer', minimum: 1, maximum: 50, description: 'Max results (API search only)' }, + }, + required: ['query'], + }, + annotations: { readOnlyHint: true, untrustedContentHint: true }, + async execute({ query, limit = 10 }, { signal } = {}) { + if (!query || !String(query).trim()) throw new Error('query is required'); + if (options.searchApi) { + const u = sameOriginUrl(fill(options.searchApi, { query, limit }), loc); + const r = await fetchImpl(u.href, { credentials: 'same-origin', headers: { accept: 'application/json' }, signal }); + if (!r.ok) throw new Error(`search failed (${r.status})`); + return r.json(); + } + const u = sameOriginUrl(fill(options.search, { query, limit }), loc); + loc.assign(u.href); + return { navigated: u.href, note: 'Opened the results page; read the results from the page.' }; + }, + }); + } + + const pages = options.pages; + tools.push({ + name: 'open_page', + title: 'Open a page', + description: pages + ? `Open one of this site's pages: ${Object.keys(pages).join(', ')}.` + : 'Open a page on this site by its path, e.g. /pricing.', + inputSchema: pages + ? { type: 'object', properties: { page: { type: 'string', enum: Object.keys(pages) } }, required: ['page'] } + : { type: 'object', properties: { path: { type: 'string', description: 'Path on this site' } }, required: ['path'] }, + annotations: { readOnlyHint: true }, + async execute(input) { + const target = pages ? pages[input.page] : input.path; + if (!target) throw new Error('unknown page'); + const u = sameOriginUrl(target, loc); + loc.assign(u.href); + return { navigated: u.href }; + }, + }); + + return tools; +} diff --git a/test/webmcp.test.js b/test/webmcp.test.js new file mode 100644 index 0000000..02d2d90 --- /dev/null +++ b/test/webmcp.test.js @@ -0,0 +1,207 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + getModelContext, + defineTool, + registerTool, + registerTools, + bridgeMcpServer, + mapAnnotations, + unwrapResult, + siteTools, +} from '../src/index.js'; + +// A ModelContext that follows the current draft: async registerTool, signal unregisters. +function fakeContext() { + const tools = new Map(); + return { + tools, + async registerTool(tool, { signal } = {}) { + if (tools.has(tool.name)) throw new DOMException(`duplicate ${tool.name}`, 'InvalidStateError'); + tools.set(tool.name, tool); + signal?.addEventListener('abort', () => tools.delete(tool.name), { once: true }); + }, + async getTools() { + return [...tools.values()]; + }, + }; +} + +test('getModelContext prefers document, falls back to navigator, null otherwise', () => { + const a = fakeContext(); + const b = fakeContext(); + assert.equal(getModelContext({ modelContext: a }, { modelContext: b }), a); + assert.equal(getModelContext({}, { modelContext: b }), b); + assert.equal(getModelContext({}, {}), null); + assert.equal(getModelContext(undefined, undefined), null); +}); + +test('defineTool rejects bad names, missing description, non-object schema', () => { + const ok = { name: 'a_b.c-1', description: 'x', execute() {} }; + assert.equal(defineTool(ok).name, 'a_b.c-1'); + assert.deepEqual(defineTool(ok).inputSchema, { type: 'object', properties: {} }); + assert.throws(() => defineTool({ ...ok, name: 'has space' }), TypeError); + assert.throws(() => defineTool({ ...ok, name: 'x'.repeat(65) }), TypeError); + assert.throws(() => defineTool({ ...ok, description: ' ' }), TypeError); + assert.throws(() => defineTool({ ...ok, inputSchema: [] }), TypeError); + assert.throws(() => defineTool({ ...ok, execute: 1 }), TypeError); +}); + +test('registerTool registers, wraps errors as results, and unregisters', async () => { + const mc = fakeContext(); + const off = await registerTool( + { name: 'boom', description: 'fails', execute: () => { throw new Error('nope'); } }, + { context: mc }, + ); + assert.ok(mc.tools.has('boom')); + assert.deepEqual(await mc.tools.get('boom').execute({}, {}), { error: 'nope' }); + off(); + assert.ok(!mc.tools.has('boom')); + off(); // idempotent +}); + +test('caller signal unregisters', async () => { + const mc = fakeContext(); + const ac = new AbortController(); + await registerTool({ name: 't', description: 'd', execute: () => 1 }, { context: mc, signal: ac.signal }); + assert.ok(mc.tools.has('t')); + ac.abort(); + assert.ok(!mc.tools.has('t')); +}); + +test('legacy context: sync registerTool + unregisterTool(name)', async () => { + const names = new Set(); + const mc = { registerTool: (t) => { names.add(t.name); }, unregisterTool: (n) => names.delete(n) }; + const off = await registerTool({ name: 'old', description: 'd', execute: () => 1 }, { context: mc }); + assert.ok(names.has('old')); + off(); + assert.ok(!names.has('old')); +}); + +test('no WebMCP: registerTool is a no-op', async () => { + const off = await registerTool({ name: 'x', description: 'd', execute: () => 1 }, { context: null }); + assert.equal(typeof off, 'function'); +}); + +test('registerTools skips a duplicate and keeps the rest', async () => { + const mc = fakeContext(); + const errors = []; + const off = await registerTools( + [ + { name: 'a', description: 'd', execute: () => 1 }, + { name: 'a', description: 'dup', execute: () => 2 }, + { name: 'b', description: 'd', execute: () => 3 }, + ], + { context: mc, onError: (e) => errors.push(e) }, + ); + assert.deepEqual([...mc.tools.keys()], ['a', 'b']); + assert.equal(errors.length, 1); + off(); + assert.equal(mc.tools.size, 0); +}); + +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 }), { + readOnlyHint: true, + consequentialHint: false, + untrustedContentHint: true, + }); + assert.equal(mapAnnotations({ destructiveHint: false }).consequentialHint, false); +}); + +test('unwrapResult: structured, JSON text, plain text, error', () => { + assert.deepEqual(unwrapResult({ structuredContent: { a: 1 }, content: [] }), { a: 1 }); + assert.deepEqual(unwrapResult({ content: [{ type: 'text', text: '{"n":2}' }] }), { n: 2 }); + assert.equal(unwrapResult({ content: [{ type: 'text', text: 'hi' }] }), 'hi'); + assert.throws(() => unwrapResult({ isError: true, content: [{ type: 'text', text: 'bad' }] }), /bad/); +}); + +// A Streamable-HTTP MCP server: JSON for initialize, SSE for tools/list and tools/call. +function fakeMcpFetch(log) { + return async (url, init) => { + const msg = JSON.parse(init.body); + log.push({ method: msg.method, session: init.headers['mcp-session-id'], credentials: init.credentials }); + const json = (body, extra = {}) => + new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json', ...extra } }); + const sse = (body) => + new Response(`event: message\ndata: ${JSON.stringify(body)}\n\n`, { headers: { 'content-type': 'text/event-stream' } }); + if (msg.method === 'initialize') return json({ jsonrpc: '2.0', id: msg.id, result: { protocolVersion: '2025-06-18' } }, { 'mcp-session-id': 's1' }); + if (msg.method === 'notifications/initialized') return new Response(null, { status: 202 }); + if (msg.method === 'tools/list') { + return sse({ + jsonrpc: '2.0', + id: msg.id, + result: { + tools: [ + { name: 'search', description: 'Search feeds', inputSchema: { type: 'object', properties: { q: { type: 'string' } } }, annotations: { readOnlyHint: true } }, + { name: 'delete-feed', description: 'Delete a feed', inputSchema: { type: 'object', properties: {} } }, + { name: 'admin_wipe', description: 'Wipe', inputSchema: { type: 'object', properties: {} } }, + ], + }, + }); + } + if (msg.method === 'tools/call') { + return sse({ jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: JSON.stringify({ got: msg.params }) }] } }); + } + return json({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'no' } }); + }; +} + +test('bridgeMcpServer registers server tools and proxies calls with the session', async () => { + const mc = fakeContext(); + const log = []; + const res = await bridgeMcpServer('https://x.test/mcp', { + context: mc, + fetch: fakeMcpFetch(log), + prefix: 'rs_', + exclude: ['admin_wipe'], + }); + assert.deepEqual(res.tools, ['rs_search', 'rs_delete-feed']); + assert.equal(mc.tools.get('rs_search').annotations.readOnlyHint, true); + assert.equal(mc.tools.get('rs_delete-feed').annotations.consequentialHint, true); + const out = await mc.tools.get('rs_search').execute({ q: 'rust' }, {}); + assert.deepEqual(out, { got: { name: 'search', arguments: { q: 'rust' } } }); + const call = log.find((l) => l.method === 'tools/call'); + assert.equal(call.session, 's1'); + assert.equal(call.credentials, 'same-origin'); + res.unregister(); + assert.equal(mc.tools.size, 0); +}); + +test('bridgeMcpServer resolves with an error instead of throwing when refused', async () => { + const res = await bridgeMcpServer('https://x.test/mcp', { + context: fakeContext(), + fetch: async () => new Response('no', { status: 401 }), + }); + assert.deepEqual(res.tools, []); + assert.match(res.error, /401/); +}); + +test('siteTools: site_info reads llms.txt, search_site uses the API, open_page stays same-origin', async () => { + const assigned = []; + const loc = { href: 'https://site.test/a', origin: 'https://site.test', pathname: '/a', assign: (u) => assigned.push(u) }; + const fetchImpl = async (u) => { + if (String(u).endsWith('/llms.txt')) return new Response('# Site\nDoes things', { headers: { 'content-type': 'text/plain' } }); + if (String(u).includes('/api/search')) return new Response(JSON.stringify({ results: [String(u)] }), { headers: { 'content-type': 'application/json' } }); + return new Response('', { status: 404 }); + }; + const tools = siteTools({ name: 'Site', searchApi: '/api/search?q={query}&limit={limit}', location: loc, fetch: fetchImpl, document: null }); + const by = Object.fromEntries(tools.map((t) => [t.name, t])); + assert.deepEqual(Object.keys(by), ['site_info', 'search_site', 'open_page']); + const info = await by.site_info.execute({}); + assert.equal(info.name, 'Site'); + assert.match(info.llmsTxt, /Does things/); + const s = await by.search_site.execute({ query: 'a b&c', limit: 3 }, {}); + assert.deepEqual(s, { results: ['https://site.test/api/search?q=a%20b%26c&limit=3'] }); + await by.open_page.execute({ path: '/pricing' }); + assert.deepEqual(assigned, ['https://site.test/pricing']); + await assert.rejects(by.open_page.execute({ path: 'https://evil.test/' }), /only pages on this site/); + await assert.rejects(by.open_page.execute({ path: '//evil.test/x' }), /only pages on this site/); +}); + +test('siteTools with a pages map uses an enum', () => { + const loc = { href: 'https://s.test/', origin: 'https://s.test', pathname: '/', assign() {} }; + const open = siteTools({ pages: { pricing: '/pricing' }, location: loc, document: null }).find((t) => t.name === 'open_page'); + assert.deepEqual(open.inputSchema.properties.page.enum, ['pricing']); +});