Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(tools): list and call the tools a site registers through WebMCP

Shahriarb46af9157b06
diff --git a/README.md b/README.md
index dcb584d..504f31b 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@ Hand your real, logged-in browser to the AI agent you already run. Browsentic is
- **Your Real Browser, Not a Headless One**: Drives the tab in front of you, in your own profile, with your own logins and sessions
- **Bring Your Own Agent**: Runs on the agent CLI you already pay for and are already signed in to — switch between Claude Code, Codex and Antigravity with one click, and pick the model each one runs
-- **49 Page Capabilities**: Reading, clicking, typing, dragging, on-site search, form submission, navigation, screenshots, file upload and download, captchas, theming and accessibility, console and network diagnostics, background progress monitoring, scheduled and repeating jobs, and pointing at an element
+- **51 Page Capabilities**: Reading, clicking, typing, dragging, on-site search, form submission, navigation, screenshots, file upload and download, captchas, theming and accessibility, console and network diagnostics, background progress monitoring, scheduled and repeating jobs, pointing at an element, and calling the tools a WebMCP site registers for agents
- **Live Tools, Off By Default**: For work that repeats twenty times or needs something no tool covers, flip the **Live tool** switch and the agent may write a small script for the page — you read the code in the panel and approve it before a line of it runs
- **Keep What It Wrote**: A script that worked can be kept as a tool of your own, named after the site it belongs to (`youtube.com:watch:darken-page-except-video-player`) and run later by typing `/`. The code stays in the browser; no MCP client can reach it
- **Voice, Text, or Demonstration**: Dictate in the side panel, type anywhere, or record yourself doing a job once and later say "do it like last time"
@@ -67,7 +67,7 @@ The extension dials out to the daemon, because a Manifest V3 service worker cann
- 📚 [Documentation](docs/)
- 🚀 [Install and Pair](docs/guide/install.md)
- ✨ [Features](docs/guide/features/)
-- 🧰 [All 49 Page Tools](docs/reference/tools.md)
+- 🧰 [All 51 Page Tools](docs/reference/tools.md)
- 🔌 [Use It From Claude Code, Cursor or Zed](docs/guide/mcp-clients.md)
- 🛡️ [Approvals and Guardrails](docs/guide/approvals.md)
- 🏗️ [Architecture](docs/internals/)
diff --git a/docs/guide/approvals.md b/docs/guide/approvals.md
index b698f25..650e392 100644
--- a/docs/guide/approvals.md
+++ b/docs/guide/approvals.md
@@ -48,6 +48,7 @@ depend on declaration order.
| `off-scope-navigation` | Navigating off the sites this run is about | confirm |
| `url-payload` | A navigation whose query string or fragment exceeds `urlPayloadBytes` (512 by default) | confirm |
| `form-submission` | Anything that commits a form, however spelled | confirm |
+| `site-tool-call` | `page_callSiteTool` — running a tool the site registered through WebMCP | confirm |
| `file-upload` | `page_attachFile` — putting one of your files into a page | confirm |
| `file-download` | `page_captureDownload` — letting a page write a file to your disk | confirm |
| `leaves-pinned-tab` | Moving to a tab the run was not pointed at | confirm |
diff --git a/docs/reference/tools.md b/docs/reference/tools.md
index 7b9833d..79404b9 100644
--- a/docs/reference/tools.md
+++ b/docs/reference/tools.md
@@ -24,6 +24,7 @@ The surface, at a glance:
| [Reading](#reading) | `page_getPageInfo`, `page_extractText`, `page_waitForElement`, `page_findProgress`, `page_findSearch`, `page_screenshot` |
| [Acting](#acting) | `page_clickElement`, `page_trustedClick`, `page_findCaptcha`, `page_solveCaptcha`, `page_hoverElement`, `page_dragElement`, `page_focusInput`, `page_fillInput`, `page_typeText`, `page_selectOption`, `page_selectText`, `page_pressKey`, `page_submitForm`, `page_highlightElement` |
| [Scripting](#scripting) | `page_injectCode`, `page_runCode` |
+| [Site tools (WebMCP)](#site-tools-webmcp) | `page_listSiteTools`, `page_callSiteTool` |
| [Moving](#moving) | `page_searchSite`, `page_navigate`, `page_scrollTo`, `page_openTab`, `page_switchTab`, `page_closeTab` |
| [Theming](#theming) | `page_readTheme`, `page_auditContrast`, `page_applyTheme` |
| [Diagnostics](#diagnostics) | `page_startDiagnostics`, `page_readConsole`, `page_readNetwork`, `page_stopDiagnostics` |
@@ -540,6 +541,48 @@ with it).
---
+## Site tools (WebMCP)
+
+Some sites now publish their own tools for agents through
+[WebMCP](https://github.com/webmachinelearning/webmcp) — `document.modelContext`, shipping natively
+in Chrome and polyfilled elsewhere. A registered site tool is the site saying "call this instead of
+clicking": one structured call with a schema, handled by the site's own code, replacing a whole
+click-and-fill sequence that selectors could miss. These two tools are how Browsentic finds and
+calls them; `page_getPageInfo` already carries a `siteTools` list whenever a page registers any, so
+a run learns a site is agent-ready without asking.
+
+Both read the page's main world through Chrome's scripting API — no debugger bar, no approval to
+install anything, and they work whether the site's implementation is the browser's own or a library.
+
+### page_listSiteTools
+
+List the tools the current site registers: `name`, `description`, `inputSchema` and any
+`annotations`, plus `api` — which of `document.modelContext` or the older `navigator.modelContext`
+the page exposes. No parameters.
+
+Fails with `NO_SITE_TOOLS` on the many sites that register none, which is the signal to work with
+the ordinary page tools instead.
+
+### page_callSiteTool
+
+Call one registered tool by name. Gated by the [`site-tool-call`](../guide/approvals.md) rule the
+same way a form submit is: the site decides what the call does, and that can include acting on the
+signed-in account.
+
+| Parameter | Type | Default | Purpose |
+| --- | --- | --- | --- |
+| `tool` | string | required | Name exactly as `page_listSiteTools` reported it |
+| `args` | object | `{}` | Arguments matching the tool's input schema. JSON values only |
+| `timeoutMs` | integer | `15000` | How long the tool may run before the call is abandoned |
+
+Returns `{ tool, returned }`, where `returned` is whatever the site's tool produced, as JSON.
+
+Three refusals are worth reading rather than retrying: `NO_SITE_TOOLS` (the site registers nothing —
+use the ordinary tools), `SITE_TOOL_NOT_FOUND` (the error lists what the site does register), and
+`SITE_TOOL_FAILED` (the site's own error message comes back with it).
+
+---
+
## Moving
### page_searchSite
diff --git a/src/daemon/agent/mapping.ts b/src/daemon/agent/mapping.ts
index 7f9d91c..c7bf5d2 100644
--- a/src/daemon/agent/mapping.ts
+++ b/src/daemon/agent/mapping.ts
@@ -30,6 +30,7 @@ const READ_ONLY_ACTIONS = new Set([
'page.findProgress',
'page.findSearch',
'page.findCaptcha',
+ 'page.listSiteTools',
'page.monitorStatus',
'page.timerStatus',
'page.readTheme',
diff --git a/src/daemon/guardrails/policy.ts b/src/daemon/guardrails/policy.ts
index 9587f2e..daef4c5 100644
--- a/src/daemon/guardrails/policy.ts
+++ b/src/daemon/guardrails/policy.ts
@@ -36,6 +36,7 @@ export const CAPTCHA_ACTION = 'page.solveCaptcha';
export const NETWORK_ACTION = 'page.readNetwork';
export const INJECT_ACTION = 'page.injectCode';
export const RUN_CODE_ACTION = 'page.runCode';
+export const SITE_TOOL_ACTION = 'page.callSiteTool';
/** One definition, shared with the settings screen that renders it. */
export type Effect = RuleEffect;
@@ -103,6 +104,9 @@ export const CONDITIONS = {
/** Acting on another site's human-verification control. */
answersCaptcha: (request) => request.action === CAPTCHA_ACTION,
+ /** Running a tool the site registered through WebMCP — the site decides what it does. */
+ callsSiteTool: (request) => request.action === SITE_TOOL_ACTION,
+
/**
* Installing agent-written JavaScript into the page. The code is the whole of what is
* being authorised — `page.runCode` only ever calls back into what this approved.
@@ -211,6 +215,13 @@ export const DEFAULT_RULES: readonly Rule[] = [
title: 'Submits a form',
reason: 'Submitting a form is a consequential action.',
},
+ {
+ id: 'site-tool-call',
+ when: 'callsSiteTool',
+ effect: 'confirm',
+ title: 'Calls a tool the site provides',
+ reason: 'A WebMCP site tool runs the site’s own code and can act on the user’s account in one call.',
+ },
{
id: 'file-upload',
when: 'uploadsFile',
diff --git a/src/daemon/skills/browser-control.md b/src/daemon/skills/browser-control.md
index 78d1f4e..e8edcdc 100644
--- a/src/daemon/skills/browser-control.md
+++ b/src/daemon/skills/browser-control.md
@@ -15,6 +15,8 @@ Each entry also carries its `role`, its `state` and the `region` it lives in. Ch
`page_getPageInfo { maxPerKind: 30 }` is the useful default. Drop to `maxPerKind: 1` when you only need the layout diagram and the URL.
+When the snapshot carries a `siteTools` list, this site registers its own tools for agents through WebMCP — a structured alternative to its UI, offered by the site itself. Call `page_listSiteTools` for their schemas and prefer `page_callSiteTool` over a click-and-fill sequence wherever a listed tool covers the step: the site's own code handles the call, so there is no selector to break and no intermediate state to wait through. A call is gated like a form submit, because the site decides what it does. No `siteTools` in the snapshot means the site registers none, which is the common case — work with the ordinary tools and do not go looking.
+
## 2. Target by what the user can see
```
diff --git a/src/lib/actions/page/call-site-tool.ts b/src/lib/actions/page/call-site-tool.ts
new file mode 100644
index 0000000..c3464e5
--- /dev/null
+++ b/src/lib/actions/page/call-site-tool.ts
@@ -0,0 +1,25 @@
+import { z } from 'zod';
+import { ActionError, defineAction } from '../core';
+
+export const callSiteTool = defineAction({
+ name: 'page.callSiteTool',
+ description:
+ 'Call one of the tools this site offers through WebMCP (document.modelContext), with arguments matching the schema page.listSiteTools reported. The site’s own code handles the call, which makes it the reliable path wherever a listed tool covers the step — no selectors to break, no intermediate states to wait through. The return value is whatever the site’s tool produced, as JSON. Treat a call like a form submit: the site decides what it does, and that can include acting on the user’s account, so it passes the same approval gate.',
+ input: z.object({
+ tool: z.string().min(1).describe('Name of a tool exactly as page.listSiteTools reported it.'),
+ args: z
+ .record(z.string(), z.unknown())
+ .default({})
+ .describe('Arguments for the tool, matching its input schema. JSON values only.'),
+ timeoutMs: z
+ .number()
+ .int()
+ .min(100)
+ .max(120_000)
+ .default(15_000)
+ .describe('How long the tool may run before the call is abandoned. Raise it for tools that wait on the site’s backend.'),
+ }),
+ execute() {
+ throw new ActionError('page.callSiteTool is resolved by the Browsentic extension, not in the page', 'UNSUPPORTED');
+ },
+});
diff --git a/src/lib/actions/page/get-page-info.ts b/src/lib/actions/page/get-page-info.ts
index 3eb4de0..8c68563 100644
--- a/src/lib/actions/page/get-page-info.ts
+++ b/src/lib/actions/page/get-page-info.ts
@@ -43,7 +43,7 @@ const LANDMARK_ROLES = new Set([
export const getPageInfo = defineAction({
name: 'page.getPageInfo',
description:
- 'Snapshot the current page: document metadata, viewport and scroll state, a semantic layout tree with a text diagram, the heading outline, and an inventory of interactive elements — each carrying its ARIA role, its live state (disabled, checked, expanded, filled, aria-current) and the landmark region it sits in.',
+ 'Snapshot the current page: document metadata, viewport and scroll state, a semantic layout tree with a text diagram, the heading outline, and an inventory of interactive elements — each carrying its ARIA role, its live state (disabled, checked, expanded, filled, aria-current) and the landmark region it sits in. When the site registers WebMCP tools, the result also carries a siteTools list — prefer page.callSiteTool over clicking wherever a listed tool covers the step.',
input: z.object({
maxPerKind: z
.number()
diff --git a/src/lib/actions/page/list-site-tools.ts b/src/lib/actions/page/list-site-tools.ts
new file mode 100644
index 0000000..4684f5d
--- /dev/null
+++ b/src/lib/actions/page/list-site-tools.ts
@@ -0,0 +1,12 @@
+import { z } from 'zod';
+import { ActionError, defineAction } from '../core';
+
+export const listSiteTools = defineAction({
+ name: 'page.listSiteTools',
+ description:
+ 'List the tools this site itself offers to agents through WebMCP (document.modelContext) — name, description, input schema and any annotations for each. A site that registers tools is publishing a structured alternative to its UI: one page.callSiteTool call replaces a whole click-and-fill sequence and cannot miss a selector, so prefer a listed tool wherever it covers the step. page.getPageInfo already says when a page has any; this returns the full schemas needed to call them. Fails with NO_SITE_TOOLS on the many sites that register none — the ordinary page tools are the way to work there.',
+ input: z.object({}),
+ execute() {
+ throw new ActionError('page.listSiteTools is resolved by the Browsentic extension, not in the page', 'UNSUPPORTED');
+ },
+});
diff --git a/src/lib/actions/registry.ts b/src/lib/actions/registry.ts
index 9a81c62..6c80156 100644
--- a/src/lib/actions/registry.ts
+++ b/src/lib/actions/registry.ts
@@ -5,6 +5,7 @@ import { applyTheme } from './page/apply-theme';
import { attachFile } from './page/attach-file';
import { auditContrast } from './page/audit-contrast';
import { awaitMonitor } from './page/await-monitor';
+import { callSiteTool } from './page/call-site-tool';
import { captureDownload } from './page/capture-download';
import { clickElement } from './page/click-element';
import { closeTab } from './page/close-tab';
@@ -22,6 +23,7 @@ import { injectCode } from './page/inject-code';
import { listDownloads } from './page/list-downloads';
import { listFiles } from './page/list-files';
import { listRecordings } from './page/list-recordings';
+import { listSiteTools } from './page/list-site-tools';
import { monitorStatus } from './page/monitor-status';
import { navigate } from './page/navigate';
import { openTab } from './page/open-tab';
@@ -74,6 +76,8 @@ export const actions: ReadonlyMap<string, AnyAction> = new Map(
waitForElement,
injectCode,
runCode,
+ listSiteTools,
+ callSiteTool,
findProgress,
findSearch,
readTheme,
diff --git a/src/lib/bridge/invoke.ts b/src/lib/bridge/invoke.ts
index 332a487..45bfbc0 100644
--- a/src/lib/bridge/invoke.ts
+++ b/src/lib/bridge/invoke.ts
@@ -4,13 +4,16 @@ import { invokeInTab } from '@/lib/actions/client';
import { ActionError } from '@/lib/actions/core';
import { attachFile } from '@/lib/actions/page/attach-file';
import { awaitMonitor } from '@/lib/actions/page/await-monitor';
+import { callSiteTool } from '@/lib/actions/page/call-site-tool';
import { captureDownload } from '@/lib/actions/page/capture-download';
import { closeTab } from '@/lib/actions/page/close-tab';
import { dragElement } from '@/lib/actions/page/drag-element';
import { findCaptcha } from '@/lib/actions/page/find-captcha';
+import { getPageInfo } from '@/lib/actions/page/get-page-info';
import { injectCode } from '@/lib/actions/page/inject-code';
import { listFiles } from '@/lib/actions/page/list-files';
import { listRecordings } from '@/lib/actions/page/list-recordings';
+import { listSiteTools } from '@/lib/actions/page/list-site-tools';
import { monitorStatus } from '@/lib/actions/page/monitor-status';
import { navigate, resolveNavigation, type NavigateInput } from '@/lib/actions/page/navigate';
import { openTab } from '@/lib/actions/page/open-tab';
@@ -36,6 +39,7 @@ import { EXPIRED_MESSAGE, REFUSED_MESSAGE } from '@/lib/secrets';
import { releaseForAction, sealForPage } from '@/lib/bridge/secret-vault';
import { findCaptchaInTab, solveCaptchaInTab } from '@/lib/bridge/captcha';
import { installToolkit, runToolkit } from '@/lib/bridge/code-toolkit';
+import { callSiteToolInTab, listSiteToolsInTab, pageInfoWithSiteTools } from '@/lib/bridge/site-tools';
import { captureFromPage } from '@/lib/bridge/downloads';
import { listMeta, readBytes } from '@/lib/bridge/file-store';
import {
@@ -133,6 +137,9 @@ async function dispatch(
if (action === captureDownload.name) return captureFromPage(tab.id, input);
if (action === injectCode.name) return installToolkit(tab.id, tab.url, input);
if (action === runCode.name) return runToolkit(tab.id, tab.url, input);
+ if (action === getPageInfo.name) return pageInfoWithSiteTools(tab.id, input);
+ if (action === listSiteTools.name) return listSiteToolsInTab(tab.id, tab.url);
+ if (action === callSiteTool.name) return callSiteToolInTab(tab.id, tab.url, input);
if (action === trustedClick.name) return trustedClickInTab(tab.id, input);
if (action === dragElement.name && isTrustedDrag(input)) return dragInTab(tab.id, input);
if (action === findCaptcha.name) return findCaptchaInTab(tab.id);
diff --git a/src/lib/bridge/site-tools.ts b/src/lib/bridge/site-tools.ts
new file mode 100644
index 0000000..489a77f
--- /dev/null
+++ b/src/lib/bridge/site-tools.ts
@@ -0,0 +1,196 @@
+/**
+ * Reading and calling the tools a site registers through WebMCP.
+ *
+ * `document.modelContext` (and its older `navigator.modelContext` alias) lives in the
+ * page's main world — a native implementation is visible from the isolated world, but a
+ * polyfilled one is not, so both paths go through `scripting.executeScript` with
+ * `world: 'MAIN'`. The injected functions are serialized, which is why each one is
+ * self-contained, never throws, and hands back plain JSON either way.
+ */
+
+import { browser } from 'wxt/browser';
+import { z } from 'zod';
+import { invokeInTab } from '@/lib/actions/client';
+import { callSiteTool } from '@/lib/actions/page/call-site-tool';
+import { getPageInfo } from '@/lib/actions/page/get-page-info';
+import { failure, success, type ActionResult } from '@/lib/actions/protocol';
+import { originOf } from './code-toolkit';
+
+const TIMEOUT_MARKER = '⟪browsentic:site-tool-timeout⟫';
+
+interface SiteToolDescriptor {
+ name: string;
+ description?: string;
+ inputSchema?: unknown;
+ annotations?: unknown;
+}
+
+type ReadReply =
+ | { ok: true; api: string | null; tools: SiteToolDescriptor[] }
+ | { ok: false; error: string };
+
+type CallReply =
+ | { ok: true; value: unknown }
+ | { ok: false; code: string; error: string; tools?: string[] };
+
+async function readRegisteredTools(withSchemas: boolean): Promise<ReadReply> {
+ try {
+ const fromDocument = (document as { modelContext?: Record<string, unknown> }).modelContext;
+ const fromNavigator = (navigator as { modelContext?: Record<string, unknown> }).modelContext;
+ const host = fromDocument ?? fromNavigator;
+ if (!host) return { ok: true, api: null, tools: [] };
+
+ const api = fromDocument ? 'document.modelContext' : 'navigator.modelContext';
+ const enumerate = host.getTools ?? host.listTools;
+ if (typeof enumerate !== 'function') return { ok: true, api, tools: [] };
+
+ const raw = await Promise.resolve((enumerate as () => unknown).call(host));
+ const list = Array.isArray(raw)
+ ? raw
+ : Array.isArray((raw as { tools?: unknown } | null)?.tools)
+ ? ((raw as { tools: unknown[] }).tools)
+ : [];
+
+ const safe = (value: unknown) => {
+ try {
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
+ } catch {
+ return undefined;
+ }
+ };
+
+ const tools = list
+ .filter((tool): tool is Record<string, unknown> => !!tool && typeof (tool as { name?: unknown }).name === 'string')
+ .map((tool) => ({
+ name: String(tool.name),
+ description:
+ typeof tool.description === 'string' ? tool.description.slice(0, withSchemas ? 500 : 140) : undefined,
+ ...(withSchemas
+ ? {
+ inputSchema: safe(tool.inputSchema ?? tool.input_schema ?? tool.parameters),
+ annotations: safe(tool.annotations),
+ }
+ : {}),
+ }));
+ return { ok: true, api, tools };
+ } catch (error) {
+ return { ok: false, error: String((error as { message?: unknown } | null)?.message ?? error) };
+ }
+}
+
+async function callRegisteredTool(
+ name: string,
+ args: Record<string, unknown>,
+ timeoutMs: number,
+ timeoutMarker: string,
+): Promise<CallReply> {
+ try {
+ const fromDocument = (document as { modelContext?: Record<string, unknown> }).modelContext;
+ const fromNavigator = (navigator as { modelContext?: Record<string, unknown> }).modelContext;
+ const host = fromDocument ?? fromNavigator;
+ if (!host) return { ok: false, code: 'NO_SITE_TOOLS', error: 'This site registers no WebMCP tools.' };
+
+ const enumerate = host.getTools ?? host.listTools;
+ if (typeof enumerate === 'function') {
+ const raw = await Promise.resolve((enumerate as () => unknown).call(host));
+ const list = Array.isArray(raw)
+ ? raw
+ : Array.isArray((raw as { tools?: unknown } | null)?.tools)
+ ? ((raw as { tools: unknown[] }).tools)
+ : [];
+ const names = list
+ .map((tool) => (tool as { name?: unknown } | null)?.name)
+ .filter((candidate): candidate is string => typeof candidate === 'string');
+ if (names.length && !names.includes(name)) {
+ return {
+ ok: false,
+ code: 'SITE_TOOL_NOT_FOUND',
+ error: `This site registers no tool named “${name}”.`,
+ tools: names,
+ };
+ }
+ }
+
+ const invoke = host.executeTool ?? host.callTool;
+ if (typeof invoke !== 'function') {
+ return { ok: false, code: 'NO_SITE_TOOLS', error: 'This site’s model context offers no way to execute a tool.' };
+ }
+
+ const outcome = await Promise.race([
+ Promise.resolve((invoke as (tool: string, input: unknown) => unknown).call(host, name, args)),
+ new Promise((resolve) => setTimeout(() => resolve(timeoutMarker), timeoutMs)),
+ ]);
+ if (outcome === timeoutMarker) {
+ return { ok: false, code: 'TIMEOUT', error: `“${name}” did not finish within ${timeoutMs}ms.` };
+ }
+
+ try {
+ return { ok: true, value: outcome === undefined ? null : JSON.parse(JSON.stringify(outcome)) };
+ } catch {
+ return { ok: false, code: 'SITE_TOOL_FAILED', error: 'The tool returned something that is not JSON.' };
+ }
+ } catch (error) {
+ return {
+ ok: false,
+ code: 'SITE_TOOL_FAILED',
+ error: String((error as { message?: unknown } | null)?.message ?? error),
+ };
+ }
+}
+
+async function inMainWorld<T>(tabId: number, func: (...args: never[]) => Promise<T>, args: unknown[]): Promise<T | null> {
+ try {
+ const results = await browser.scripting.executeScript({
+ target: { tabId },
+ world: 'MAIN',
+ func: func as () => Promise<T>,
+ args: args as [],
+ });
+ return (results[0]?.result as T | undefined) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export async function probeSiteTools(tabId: number) {
+ const read = await inMainWorld<ReadReply>(tabId, readRegisteredTools, [false]);
+ if (!read?.ok || !read.tools.length) return null;
+ return { api: read.api, count: read.tools.length, tools: read.tools };
+}
+
+export async function pageInfoWithSiteTools(tabId: number, input: unknown): Promise<ActionResult> {
+ const [info, siteTools] = await Promise.all([invokeInTab(tabId, getPageInfo.name, input), probeSiteTools(tabId)]);
+ if (!info.ok || !siteTools) return info;
+ return success({ ...(info.data as object), siteTools });
+}
+
+export async function listSiteToolsInTab(tabId: number, url: string | undefined): Promise<ActionResult> {
+ if (!originOf(url)) return failure('UNSUPPORTED', 'Site tools can only be read on an http(s) page.');
+
+ const read = await inMainWorld<ReadReply>(tabId, readRegisteredTools, [true]);
+ if (!read) {
+ return failure('UNSUPPORTED', 'Reading site tools needs main-world scripting, which this browser does not allow here.');
+ }
+ if (!read.ok) return failure('ACTION_FAILED', `The site’s model context failed while listing its tools: ${read.error}`);
+ if (!read.tools.length) {
+ return failure('NO_SITE_TOOLS', 'This site registers no WebMCP tools — the ordinary page tools are the way to work here.');
+ }
+ return success({ api: read.api, count: read.tools.length, tools: read.tools });
+}
+
+export async function callSiteToolInTab(tabId: number, url: string | undefined, input: unknown): Promise<ActionResult> {
+ const parsed = callSiteTool.input.safeParse(input ?? {});
+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
+ if (!originOf(url)) return failure('UNSUPPORTED', 'Site tools can only be called on an http(s) page.');
+
+ const { tool, args, timeoutMs } = parsed.data;
+ const called = await inMainWorld<CallReply>(tabId, callRegisteredTool, [tool, args, timeoutMs, TIMEOUT_MARKER]);
+ if (!called) {
+ return failure('UNSUPPORTED', 'Calling site tools needs main-world scripting, which this browser does not allow here.');
+ }
+ if (!called.ok) {
+ const listed = called.tools?.length ? ` It defines: ${called.tools.join(', ')}.` : '';
+ return failure(called.code, `${called.error}${listed}`);
+ }
+ return success({ tool, returned: called.value });
+}