From 71ee1f1ab311f50a5492bcb7a20f4e4f4fc13fd7 Mon Sep 17 00:00:00 2001 From: robertn702 <8119609+robertn702@users.noreply.github.com> Date: Wed, 2 Sep 2026 18:32:25 +0000 Subject: [PATCH 1/2] feat(engine): add read-only DOM execution --- AGENTS.md | 15 +- ARCHITECTURE.md | 8 +- apps/extension/AGENTS.md | 9 +- apps/extension/ARCHITECTURE.md | 11 +- apps/extension/package.json | 1 + apps/extension/src/entrypoints/content.ts | 1 + apps/extension/src/lib/register-tools.ts | 38 +- apps/extension/test/install-bridge.test.ts | 4 +- apps/extension/test/register-tools.test.ts | 73 +++ .../(registry)/docs/package-format/page.tsx | 15 +- apps/web/test/package-format-example.test.ts | 4 +- bun.lock | 2 + docs/DECISIONS.md | 19 +- docs/api-execution-model.md | 9 +- packages/db/src/package-schema.ts | 2 +- packages/engine/package.json | 3 +- packages/engine/src/api-executor.ts | 9 +- packages/engine/src/dom-executor.ts | 457 ++++++++++++++++++ packages/engine/src/index.ts | 2 + packages/engine/test/dom-executor.test.ts | 424 ++++++++++++++++ packages/schema/README.md | 4 +- packages/schema/src/api.ts | 6 +- packages/schema/src/budgets.ts | 8 +- packages/schema/src/execution.ts | 94 +++- packages/schema/src/package.ts | 29 +- packages/schema/src/registry.ts | 13 +- packages/schema/src/tool.ts | 45 +- packages/schema/test/api-validation.test.ts | 6 +- packages/schema/test/dom-validation.test.ts | 145 ++++++ 29 files changed, 1357 insertions(+), 99 deletions(-) create mode 100644 packages/engine/src/dom-executor.ts create mode 100644 packages/engine/test/dom-executor.test.ts create mode 100644 packages/schema/test/dom-validation.test.ts diff --git a/AGENTS.md b/AGENTS.md index edf947f..a884f3b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,14 +90,15 @@ Next route handlers + zod (no tRPC), Neon Postgres + Drizzle, better-auth (GitHu - `version`: author-declared positive integer (not semver) — `1` on create, exactly `max(version)+1` on publish, or the API 409s with `expectedVersion` (docs/DECISIONS.md 2026-07-29). -- Tool `execution` is `api`-mode only: the tool binds to an entry in the - package-level `api.endpoints` block by name. (DOM execution was cut - before the initial release — `docs/DECISIONS.md` 2026-07-28.) +- Tool `execution` is discriminated: API tools bind to `api.endpoints`; DOM tools + declare bounded, read-only semantic observations and require `minEngine: 2`. + `api` remains required; DOM-only packages carry an inert same-site + `api.endpoints: {}` block. Publish schema first, then the engine minor release, + before publishing packages that require DOM mode. - `minEngine`: positive-integer capability level (not semver), version-scoped. - Extension must skip + warn on tool-name collision with site-registered tools. -- `ENGINE_VERSION` remains `1` for the initial package format. Bump the capability - level only for an incompatible format change; compatible format changes do not - require a bump (`packages/schema/src/budgets.ts` says why). +- `ENGINE_VERSION` is `2`, which adds the DOM observation executor. Bump the capability + level only for an incompatible format change (`packages/schema/src/budgets.ts` says why). - Tier-1 `api` block: `returns` is a JMESPath expression; `errorPath` and auth-source `extract` are locator arrays (`["json","errors"]`); an auth source declares exactly one of `extract` (JSON locator) or `pattern` (regex over the raw response text, @@ -168,7 +169,7 @@ a correction, and prune entries whose reasoning has since migrated into code or | Extension notes | `apps/extension/AGENTS.md` | | Extension internal map | `apps/extension/ARCHITECTURE.md` | | Data model ERD | `docs/erd.md` | -| Execution model (API-only) | `docs/api-execution-model.md` | +| Execution model | `docs/api-execution-model.md` | | Platform risk register | `docs/platform-risks.md` | | Why non-obvious calls were made | `docs/DECISIONS.md` | | Open follow-ups (prune as done) | `docs/BACKLOG.md` | diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 5c140ea..6c13682 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -170,16 +170,18 @@ sequenceDiagram EX-->>A: tool output (uncapped in v1) ``` -One execution mode, selected per tool by binding to an `api.endpoints` entry: +Two execution modes are selected per tool: - **API mode (tier 1)** — the package declares the site's own HTTP API as data (`api.endpoints`, `auth` token sources, `returns` projections); the executor derives and performs the call. Ships zero code. The load-bearing invariant: **`api.baseUrl` must use the package domain or a subdomain, and every derived request is pinned to that exact origin after interpolation**. `urlPatterns` select pages for tool - registration; they do not constrain `api.baseUrl` or need to cover it. (DOM execution was cut pre-launch — `docs/DECISIONS.md` - 2026-07-28.) Tiers 2–3 (scoped script slots, full `evaluate`) are designed + registration; they do not constrain `api.baseUrl` or need to cover it. Tiers 2–3 (scoped script slots, full `evaluate`) are designed but not shipped — see `docs/api-execution-model.md`. +- **DOM mode (level 2)** — reads only a bounded, top-level light-DOM set of exact + semantic role/name observations. It cannot mutate, inspect values/HTML/URLs, or + traverse frames or shadow roots. DOM-only packages retain an inert same-site API block. - **Validate before any side effect.** The executor re-validates input against the tool's `inputSchema` (primitive-only profile) and a 64 KiB serialized-input cap before the `destructiveHint` confirm prompt or any network access — an invalid call diff --git a/apps/extension/AGENTS.md b/apps/extension/AGENTS.md index 89b36ab..e6dcecd 100644 --- a/apps/extension/AGENTS.md +++ b/apps/extension/AGENTS.md @@ -167,15 +167,16 @@ package(s) matched this URL` → bridge `list_webmcp_tools` shows the tools. - `src/entrypoints/popup/` + the action badge — per-tab status, the install list (with uninstall), and the paused/recovery states. Never inject UI into the page. -- The executor lives in `packages/engine` (`@webmcp-today/engine`, MIT) — +- The executors live in `packages/engine` (`@webmcp-today/engine`, MIT) — extracted from `src/lib/` for license separation (docs/DECISIONS.md 2026-07-30): - `api-executor.ts` is the only executor (DOM mode was cut pre-launch, - `docs/DECISIONS.md` 2026-07-28): binds `{{param}}` templates, acquires auth + `api-executor.ts` binds `{{param}}` templates, acquires auth tokens from `api.auth` sources, performs the same-origin fetch, checks `errorPath`, applies the `returns` JMESPath projection. `destructiveHint` tools gate on a blocking `window.confirm`. The fetch MUST run in the content-script (page) context — the SameSite-cookie rationale is the header - comment in `packages/engine/src/api-executor.ts`. + comment in `packages/engine/src/api-executor.ts`. `dom-executor.ts` is a separate + level-2, read-only semantic observer; registration passes it the live document, URL, + and abort signal so navigation and frames fail closed. - The bundled fallback is gone: the `@webmcp-today/curated-packages` dependency was removed in step 5b (U7). The package remains the seed source for the registry (`apps/web/scripts/seed.ts`). diff --git a/apps/extension/ARCHITECTURE.md b/apps/extension/ARCHITECTURE.md index 14589fb..06f38de 100644 --- a/apps/extension/ARCHITECTURE.md +++ b/apps/extension/ARCHITECTURE.md @@ -147,17 +147,20 @@ _What happens when the in-page LLM invokes a registered tool._ ```mermaid flowchart TB CB["registerTool execute callback"] --> API["api-executor (packages/engine)
(validate input first, same-origin fetch,
auth tokens, JMESPath projection,
destructiveHint confirm)"] + CB --> DOM["dom-executor (packages/engine)
(bounded top-level semantic reads)"] API --> RESULT["mcp-result (packages/engine)
(text → WebMCP result shape)"] + DOM --> RESULT ``` `api-executor` (in `packages/engine/src/api-executor.ts`, MIT — extracted from -`src/lib/` for license separation, `docs/DECISIONS.md` 2026-07-30) is the only -executor — DOM mode was cut pre-launch -(`docs/DECISIONS.md` 2026-07-28). It re-validates input against `inputSchema` and a +`src/lib/` for license separation, `docs/DECISIONS.md` 2026-07-30) re-validates input against `inputSchema` and a 64 KiB serialized-input cap **before** the `destructiveHint` confirm prompt or any network access, then binds `{{param}}` templates from that validated input, acquires tokens from the package's `api.auth` sources, performs the same-origin fetch, checks -`errorPath`, and applies the `returns` projection. +`errorPath`, and applies the `returns` projection. `dom-executor` is the separate level-2 +path: it receives the live document, registration URL, and pass abort signal; it returns +only bounded top-level semantic observations and fails closed after navigation, in frames, +or on ambiguity. ### ④ Local bridge flow — MCP → selected tab's live tools diff --git a/apps/extension/package.json b/apps/extension/package.json index dfa31e0..75032ef 100644 --- a/apps/extension/package.json +++ b/apps/extension/package.json @@ -18,6 +18,7 @@ "zod": "^4.0.0" }, "devDependencies": { + "linkedom": "0.18.13", "typescript": "^5.9.2", "vitest": "^3.2.4", "wxt": "^0.20.6" diff --git a/apps/extension/src/entrypoints/content.ts b/apps/extension/src/entrypoints/content.ts index ad487b8..0d912e4 100644 --- a/apps/extension/src/entrypoints/content.ts +++ b/apps/extension/src/entrypoints/content.ts @@ -61,6 +61,7 @@ export default defineContentScript({ const deps: RegistrationDeps = { loadPackages: getPackagesForUrl, getModelContext: getContentModelContext, + getDocument: () => document, siteDeclaredToolNames, reportStatus, }; diff --git a/apps/extension/src/lib/register-tools.ts b/apps/extension/src/lib/register-tools.ts index 8aebcd7..c89c287 100644 --- a/apps/extension/src/lib/register-tools.ts +++ b/apps/extension/src/lib/register-tools.ts @@ -1,4 +1,9 @@ -import { executeApiTool, requiredEngineLevel, supportsPackageEngine } from "@webmcp-today/engine"; +import { + executeApiTool, + executeDomTool, + requiredEngineLevel, + supportsPackageEngine, +} from "@webmcp-today/engine"; import { ENGINE_VERSION } from "@webmcp-today/schema"; import type { PageLoadPackages } from "./local-lookup.js"; import type { McpResult, ModelContextLike } from "./model-context.js"; @@ -13,6 +18,8 @@ export interface RegistrationDeps { /** The WebMCP context to register into — the content script always supplies * one (native API or the built-in fallback), so this is never absent. */ getModelContext: () => ModelContextLike; + /** The live page document; DOM tools must never receive a detached snapshot. */ + getDocument: () => Document; /** Tool names the site declared itself (`form[toolname]`) — ours yield to them. */ siteDeclaredToolNames: () => Set; /** Surfaces the pass outcome on the action badge + popup. */ @@ -76,18 +83,25 @@ export async function runRegistrationPass( const execution = tool.execution; if (!execution) continue; - // v1 has one execution mode: api. The endpoint must resolve against the - // package's api block (install-time zod validation makes this a - // should-never-happen guard). - const api = pkg.api; - const endpoint = api?.endpoints[execution.endpoint]; - if (!api || !endpoint) { - console.warn( - `[webmcp-today] Skipping tool "${tool.name}" — api endpoint "${execution.endpoint}" is missing from the package's api block.`, - ); - continue; + let execute: ToolExecute; + if (execution.mode === "api") { + const api = pkg.api; + const endpoint = api?.endpoints[execution.endpoint]; + if (!api || !endpoint) { + console.warn( + `[webmcp-today] Skipping tool "${tool.name}" — api endpoint "${execution.endpoint}" is missing from the package's api block.`, + ); + continue; + } + execute = (params) => executeApiTool({ ...tool, execution }, api, params); + } else { + execute = (params) => + executeDomTool(tool, params, { + document: deps.getDocument(), + registrationUrl: url, + signal, + }); } - const execute: ToolExecute = (params) => executeApiTool(tool, api, params); if (seen.has(tool.name)) continue; if (declarativeNames.has(tool.name)) { diff --git a/apps/extension/test/install-bridge.test.ts b/apps/extension/test/install-bridge.test.ts index b1670c1..124d1c4 100644 --- a/apps/extension/test/install-bridge.test.ts +++ b/apps/extension/test/install-bridge.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import type { RevocationEntry } from "@webmcp-today/schema"; +import { ENGINE_VERSION, type RevocationEntry } from "@webmcp-today/schema"; import { handleBridgeRequest, type BridgeDeps } from "../src/lib/install-bridge.js"; import { createInstallsStore, type ReadySchemaState } from "../src/lib/installs-store.js"; import { INDEX_KEY, REVOKED_KEY, pkgKey, type RevokedDoc } from "../src/lib/store-schema.js"; @@ -154,7 +154,7 @@ describe("handleBridgeRequest", () => { expect(response).toEqual({ ok: true, protocol: 1, - engine: 1, + engine: ENGINE_VERSION, extensionVersion: "0.0.1", storageReadable: true, }); diff --git a/apps/extension/test/register-tools.test.ts b/apps/extension/test/register-tools.test.ts index ffd5ee7..07024ec 100644 --- a/apps/extension/test/register-tools.test.ts +++ b/apps/extension/test/register-tools.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { parseHTML } from "linkedom"; import { webMcpPackageSchema, type WebMcpPackage } from "@webmcp-today/schema"; import type { PageLoadPackages } from "../src/lib/local-lookup.js"; import type { ModelContextLike } from "../src/lib/model-context.js"; @@ -35,6 +36,35 @@ function pkg(...toolNames: string[]): WebMcpPackage { }); } +function domPkg(): WebMcpPackage { + return webMcpPackageSchema.parse({ + id: "pkg-dom", + versionId: "ver-dom", + version: 1, + contributor: "robert", + createdAt: "2026-09-02T00:00:00.000Z", + updatedAt: "2026-09-02T00:00:00.000Z", + domain: "en.wikipedia.org", + urlPatterns: ["*://en.wikipedia.org/wiki/*"], + title: "DOM fixture", + description: "Read-only DOM fixture package", + minEngine: 2, + tools: [ + { + name: "wiki_dom_status", + description: "Read page heading status.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true, untrustedContentHint: true }, + execution: { + mode: "dom", + observations: { heading: { role: "heading", name: "Coffee", read: "exists" } }, + }, + }, + ], + api: { baseUrl: "https://en.wikipedia.org", endpoints: {} }, + }); +} + /** Records what was registered; `reject` names make registerTool fail. */ function recordingContext(reject: string[] = []): { mc: ModelContextLike; @@ -64,6 +94,7 @@ function harness( const deps: RegistrationDeps = { loadPackages: vi.fn(async () => result), getModelContext, + getDocument: () => document, siteDeclaredToolNames: () => new Set(declared), reportStatus: (status) => { statuses.push(status); @@ -106,6 +137,47 @@ describe("runRegistrationPass", () => { expect(statuses).toEqual([{ kind: "registered", toolNames: ["wiki_summary", "wiki_search"] }]); }); + it("dispatches DOM tools against the live document and fails stale or aborted calls", async () => { + const { document: liveDocument, window } = parseHTML( + "

Coffee

", + ); + Object.defineProperty(window, "location", { configurable: true, value: { href: PAGE_URL } }); + Object.defineProperty(window, "top", { configurable: true, value: window }); + Object.defineProperty(window, "parent", { configurable: true, value: window }); + vi.stubGlobal("document", liveDocument); + vi.stubGlobal("Element", window.Element); + vi.stubGlobal("HTMLInputElement", window.HTMLInputElement); + vi.stubGlobal("HTMLTextAreaElement", window.HTMLTextAreaElement); + let execute: ((params: Record) => Promise) | undefined; + const mc: ModelContextLike = { + registerTool: async (descriptor) => { + execute = descriptor.execute; + }, + }; + const { deps, statuses } = harness([domPkg()], mc); + deps.getDocument = () => liveDocument; + const controller = new AbortController(); + + await runRegistrationPass(PAGE_URL, controller.signal, deps); + + expect(statuses).toEqual([{ kind: "registered", toolNames: ["wiki_dom_status"] }]); + if (execute === undefined) throw new Error("DOM fixture was not registered"); + await expect(execute({})).resolves.toEqual({ + content: [{ type: "text", text: '{"heading":{"matched":true}}' }], + }); + Object.defineProperty(window, "location", { + configurable: true, + value: { href: "https://en.wikipedia.org/wiki/Tea" }, + }); + await expect(execute({})).resolves.toEqual({ + content: [{ type: "text", text: "DOM tool execution failed." }], + }); + controller.abort(); + await expect(execute({})).resolves.toEqual({ + content: [{ type: "text", text: "DOM tool execution failed." }], + }); + }); + it("registers tools through the in-memory fallback", async () => { vi.stubGlobal("document", {}); vi.stubGlobal("location", { origin: "https://en.wikipedia.org" }); @@ -148,6 +220,7 @@ describe("runRegistrationPass", () => { return { packages: [pkg("wiki_summary")] }; }, getModelContext: () => mc, + getDocument: () => document, siteDeclaredToolNames: () => new Set(), reportStatus: (status) => statuses.push(status), }; diff --git a/apps/web/app/(registry)/docs/package-format/page.tsx b/apps/web/app/(registry)/docs/package-format/page.tsx index cf86011..0806dd7 100644 --- a/apps/web/app/(registry)/docs/package-format/page.tsx +++ b/apps/web/app/(registry)/docs/package-format/page.tsx @@ -65,13 +65,13 @@ export default function PackageFormatPage() { The tools registered on a matching page. Names must be unique within the package. - The site's HTTP surface, with at least one endpoint. Execution is api-mode only, so - every tool binds to an endpoint declared here. + The site's HTTP surface. API tools bind to endpoints declared here. DOM-only + packages retain an inert same-site block with endpoints: {}. The capability floor this version needs, like an Android API level. An extension whose own level is lower skips the package instead of half-running it. Current level is{" "} - 1. + 2. DOM observations require level 2. What changed in this version. Shown to installed users deciding whether to move their @@ -112,9 +112,10 @@ export default function PackageFormatPage() { destructiveHint. No unknown keys, and a tool can't claim both{" "} readOnlyHint and destructiveHint. Mark writes honestly. - - Binds the tool to a key in api.endpoints. mode is{" "} - "api", the only mode there is. + + API mode binds the tool to a key in api.endpoints. DOM mode declares 1–16 + exact semantic role/name observations and can return only presence or allowed boolean + states; it has empty input, read-only/untrusted hints, and minEngine: 2. @@ -134,7 +135,7 @@ export default function PackageFormatPage() { Hacker News's Firebase read API. - Named requests. Tools bind to these keys. + Named requests. API tools bind to these keys; DOM-only packages use an empty record. Named token flows: fetch a page or endpoint, pull a token out of the response, resend it diff --git a/apps/web/test/package-format-example.test.ts b/apps/web/test/package-format-example.test.ts index 3be7cdc..663150a 100644 --- a/apps/web/test/package-format-example.test.ts +++ b/apps/web/test/package-format-example.test.ts @@ -33,12 +33,12 @@ describe("docs package-format example", () => { }); // The page cites these budgets by number (tool name ≤30, tool description - // ≤500, engine level 1). If any of them move, /docs/package-format needs a + // ≤500, engine level 2). If any of them move, /docs/package-format needs a // matching edit — this assertion is what forces that instead of silent rot. it("cites the budget constants the page states", () => { expect(TOOL_NAME_MAX).toBe(30); expect(TOOL_DESCRIPTION_MAX).toBe(500); - expect(ENGINE_VERSION).toBe(1); + expect(ENGINE_VERSION).toBe(2); }); // The page's "The shape" section documents every top-level field by name. diff --git a/bun.lock b/bun.lock index b2af37c..3433026 100644 --- a/bun.lock +++ b/bun.lock @@ -30,6 +30,7 @@ "zod": "^4.0.0", }, "devDependencies": { + "linkedom": "0.18.13", "typescript": "^5.9.2", "vitest": "^3.2.4", "wxt": "^0.20.6", @@ -113,6 +114,7 @@ "@webmcp-today/schema": "0.3.0", }, "devDependencies": { + "linkedom": "0.18.13", "typescript": "^5.9.2", "vitest": "^3.2.4", }, diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 0453f72..e957127 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -23,17 +23,14 @@ lives in code or another doc, and **code + `AGENTS.md` win on disagreement**. and OS-level AppleScript focus — outside the extension trust model and permission-fragile. -- 2026-07-28 — **DOM execution mode was removed entirely; `api` is the only execution - mode.** The pre-launch curated set was 5/6 DOM packages, but they were read-only - page-extraction demos nobody needed, while the Reddit API package was the actual - product thesis ("act as me on a site I live in"). Keeping DOM meant maintaining two - executors, two validation paths, and two doc stories for a fallback whose expected - failure (selector rot) is silent — the exact opposite of the API model's loud 4xx. - Rejected: keeping read-only DOM extraction — it survives breakage better, but the - format/docs surface was the cost being cut, and unauthenticated content APIs (or the - site's own WebMCP, eventually) cover that need. If a site with no usable API ever - matters, the `mode` literal in `packages/schema/src/execution.ts` turns back into a - discriminated union; the deleted executor is in git history. +- 2026-07-28 — **DOM mode is a narrow read-only observation capability, not browser + automation.** Some sites have no usable API for non-sensitive structure, so level 2 + admits exact semantic role/name observations only. It rejects selectors, values, raw + HTML, frames, shadow roots, and mutations; bounded traversal/name work and ambiguous + matches fail closed. Rejected: restoring click/type/form choreography or generic DOM + extraction — both reintroduce silent selector rot and sensitive-data exposure. API + execution remains the preferred general mode; DOM-only packages retain an inert API + block to avoid persistence migration scope. - 2026-07-23 — **Registry lookups are fetched in the extension's background worker, not the content script.** A background fetch goes to the registry's own origin and is not diff --git a/docs/api-execution-model.md b/docs/api-execution-model.md index 68bc356..f92df39 100644 --- a/docs/api-execution-model.md +++ b/docs/api-execution-model.md @@ -28,9 +28,7 @@ Flagship target: a **read + write Reddit package** backed by its JSON API — re threads, plus posting comments — controllable from a terminal LLM through WebMCP. That requires authenticated writes, which forces the token-acquisition design below. -DOM execution was cut pre-launch (2026-07-28 — `docs/DECISIONS.md`): this API model -is the only execution mode. The selector-rot argument above won, and dropping the DOM -fallback shrank the schema, executor, and docs surface to one model. +API execution remains the general execution model. Engine level 2 also supports a deliberately narrow DOM read mode: exact semantic role/name observations with only `exists`, `disabled`, `checked`, or `required` boolean output. It cannot use selectors, values, HTML, frames, shadow roots, or mutation operations. DOM-only packages currently carry an inert same-site `api` block with `endpoints: {}`; publishing this format requires schema and engine minor releases and `minEngine: 2`. ## Tiered execution model @@ -420,9 +418,8 @@ data — so it is buildable today and is not blocked on the spike. tier-1 calls against live sites; what runs it, and how do auth'd writes get canaried safely (a write canary posts real comments)? - **`minEngine` bump policy — resolved.** Packages set `minEngine` to the engine level - whose format they rely on. `ENGINE_VERSION` remains `1` for the initial format. - Bump the capability level only for an incompatible format change; compatible - additions and changes do not require a bump (`packages/schema/src/budgets.ts`). The + whose format they rely on. `ENGINE_VERSION` is `2`: level 2 adds the DOM observation + executor. The extension refuses a too-new package _whole_ rather than registering tools it cannot run — `supportsPackageEngine` (`packages/engine/src/engine-gate.ts`), applied per package in `register-tools.ts`. diff --git a/packages/db/src/package-schema.ts b/packages/db/src/package-schema.ts index e64e809..6163d5f 100644 --- a/packages/db/src/package-schema.ts +++ b/packages/db/src/package-schema.ts @@ -55,7 +55,7 @@ export const packageVersions = pgTable( version: integer("version").notNull(), urlPatterns: jsonb("url_patterns").$type().notNull(), tools: jsonb("tools").$type().notNull(), - /** Tier-1 API execution surface for this version's API-mode tools (see docs/api-execution-model.md). Required — execution is api-mode only. */ + /** Required API execution surface for API-mode tools; DOM-only versions retain an inert block. */ api: jsonb("api").$type().notNull(), /** Capability floor this version's content requires (see engineLevelSchema in packages/schema). Required. */ minEngine: integer("min_engine").notNull(), diff --git a/packages/engine/package.json b/packages/engine/package.json index 5d3d596..6927ce8 100644 --- a/packages/engine/package.json +++ b/packages/engine/package.json @@ -1,7 +1,7 @@ { "name": "@webmcp-today/engine", "version": "0.1.0", - "description": "Execution engine for WebMCP Today — runs a package's declarative api block as HTTP requests", + "description": "Execution engine for WebMCP Today — runs declarative API calls and bounded read-only DOM observations", "type": "module", "license": "MIT", "publishConfig": { @@ -33,6 +33,7 @@ "@webmcp-today/schema": "0.3.0" }, "devDependencies": { + "linkedom": "0.18.13", "typescript": "^5.9.2", "vitest": "^3.2.4" } diff --git a/packages/engine/src/api-executor.ts b/packages/engine/src/api-executor.ts index fd1edcc..0b8d609 100644 --- a/packages/engine/src/api-executor.ts +++ b/packages/engine/src/api-executor.ts @@ -3,6 +3,7 @@ import { validateToolInput, type ApiAuthSource, type ApiBlock, + type ApiExecution, type ApiEndpoint, type ToolDescriptor, } from "@webmcp-today/schema"; @@ -474,10 +475,10 @@ export function handleResponse(endpoint: ApiEndpoint, outcome: FetchOutcome): Mc * destructiveHint confirm gate, and `execution` for the endpoint binding. * The engine never touches `description` (that's UI/registration-only), so * callers (and tests) don't have to fabricate one just to execute a tool. */ -export type ApiToolDescriptor = Pick< - ToolDescriptor, - "name" | "inputSchema" | "annotations" | "execution" ->; +export type ApiToolDescriptor = Omit< + Pick, + "execution" +> & { execution: ApiExecution }; export async function executeApiTool( tool: ApiToolDescriptor, diff --git a/packages/engine/src/dom-executor.ts b/packages/engine/src/dom-executor.ts new file mode 100644 index 0000000..4f1516b --- /dev/null +++ b/packages/engine/src/dom-executor.ts @@ -0,0 +1,457 @@ +import { + toolDescriptorSchema, + validateToolInput, + type DomObservation, + type ToolDescriptor, +} from "@webmcp-today/schema"; +import { mcpResult } from "./mcp-result.js"; +import type { McpResult } from "./result.js"; + +const MAX_ELEMENTS = 10_000; +const MAX_CANDIDATES = 2_000; +const MAX_NAME_WORK = 4_000; +const MAX_INDEX_WORK = 10_000; +const MAX_NAME_NODES = 256; +const MAX_NAME_BYTES = 512; +const MAX_ID_BYTES = 512; +const MAX_OUTPUT_BYTES = 4096; +const PRUNED_TAGS = new Set([ + "SELECT", + "OPTION", + "IFRAME", + "OBJECT", + "EMBED", + "SCRIPT", + "STYLE", + "TEMPLATE", + "NOSCRIPT", +]); +const TEXT_EXCLUDED_TAGS = new Set(["INPUT", "TEXTAREA", ...PRUNED_TAGS]); + +export type DomToolDescriptor = ToolDescriptor; + +export interface DomExecutionContext { + document: Document; + registrationUrl: string; + signal: AbortSignal; +} + +type DomOutput = Record; +type IdEntry = { element: Element; eligible: boolean }; +type IdIndex = Map; + +interface NameBudget { + work: number; +} + +function utf8LengthAtMost(value: string, limit: number): number { + let bytes = 0; + for (let index = 0; index < value.length; index += 1) { + const code = value.charCodeAt(index); + if (code < 0x80) bytes += 1; + else if (code < 0x800) bytes += 2; + else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) { + const next = value.charCodeAt(index + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + bytes += 4; + index += 1; + } else { + bytes += 3; + } + } else bytes += 3; + if (bytes > limit) return limit + 1; + } + return bytes; +} + +function normalizeText(value: string): string { + return value.normalize("NFC").replace(/\s+/gu, " ").trim(); +} + +function boundedNameString(value: string, budget: NameBudget): string { + addNameWork(budget); + if (value.length > MAX_NAME_BYTES || utf8LengthAtMost(value, MAX_NAME_BYTES) > MAX_NAME_BYTES) { + throw new Error("DOM name-byte limit"); + } + return normalizeText(value); +} + +function isPrunedSelf(element: Element): boolean { + if (PRUNED_TAGS.has(element.tagName)) return true; + if (element.hasAttribute("hidden") || element.hasAttribute("inert")) return true; + if (element.getAttribute("contenteditable") !== null) return true; + if (element.getAttribute("aria-hidden")?.trim().toLowerCase() === "true") return true; + if (element.tagName !== "INPUT") return false; + const type = element.getAttribute("type")?.trim().toLowerCase() ?? "text"; + return ["button", "submit", "reset", "image", "password", "hidden"].includes(type); +} + +function addNameWork(budget: NameBudget): void { + budget.work += 1; + if (budget.work > MAX_NAME_WORK) throw new Error("DOM name-work limit"); +} + +/** Text-only, light-DOM extraction. It never reads a container's textContent. */ +function safeText(element: Element, eligible: Map, budget: NameBudget): string { + if (eligible.get(element) !== true || TEXT_EXCLUDED_TAGS.has(element.tagName)) return ""; + let nodes = 0; + let bytes = 0; + let text = ""; + let node: Node | null = element.firstChild; + + while (node !== null) { + nodes += 1; + addNameWork(budget); + if (nodes > MAX_NAME_NODES) throw new Error("DOM name-node limit"); + if (node.nodeType === 3) { + const value = node.nodeValue ?? ""; + if (value.length > MAX_NAME_BYTES) throw new Error("DOM name-byte limit"); + bytes += utf8LengthAtMost(value, MAX_NAME_BYTES - bytes); + if (bytes > MAX_NAME_BYTES) throw new Error("DOM name-byte limit"); + text += value; + } + + const child = + node instanceof Element && + eligible.get(node) === true && + !TEXT_EXCLUDED_TAGS.has(node.tagName) + ? node.firstChild + : null; + if (child !== null) { + node = child; + continue; + } + while (node !== null && node !== element && node.nextSibling === null) node = node.parentNode; + if (node === null || node === element) break; + node = node.nextSibling; + } + return normalizeText(text); +} + +function isNameSourceEligible(element: Element, eligible: Map): boolean { + return eligible.get(element) === true && !TEXT_EXCLUDED_TAGS.has(element.tagName); +} + +function ariaName( + element: Element, + idIndex: IdIndex, + eligible: Map, + budget: NameBudget, +): string | null { + const labelledBy = element.getAttribute("aria-labelledby"); + if (labelledBy !== null) { + const normalizedReferences = boundedNameString(labelledBy, budget); + const references = normalizedReferences.split(/\s+/u).filter(Boolean); + if (references.length === 0 || new Set(references).size !== references.length) { + throw new Error("invalid aria-labelledby"); + } + let name = ""; + for (const reference of references) { + const entry = idIndex.get(reference); + if ( + entry === undefined || + entry === null || + !entry.eligible || + !isNameSourceEligible(entry.element, eligible) + ) { + throw new Error("invalid aria-labelledby"); + } + const part = safeText(entry.element, eligible, budget); + if (name.length + part.length > MAX_NAME_BYTES) throw new Error("DOM name-byte limit"); + name += name === "" ? part : ` ${part}`; + } + return boundedNameString(name, budget); + } + const label = element.getAttribute("aria-label"); + return label === null ? null : boundedNameString(label, budget); +} + +function labelName( + element: Element, + idIndex: IdIndex, + eligible: Map, + budget: NameBudget, +): string | null { + if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) { + const id = element.getAttribute("id"); + if (id !== null && id !== "") { + const entry = idIndex.get(id); + if (entry === null || entry?.element !== element) throw new Error("ambiguous label target"); + } + const labels = element.labels; + if (labels !== null && labels !== undefined) { + if (labels.length > 1) throw new Error("ambiguous control labels"); + if (labels.length === 0) return null; + addNameWork(budget); + const label = labels.item(0); + if (label !== null && eligible.get(label) === true) return safeText(label, eligible, budget); + return null; + } + } + let parent = element.parentElement; + while (parent !== null) { + addNameWork(budget); + if (parent.tagName === "LABEL") { + return eligible.get(parent) === true ? safeText(parent, eligible, budget) : null; + } + parent = parent.parentElement; + } + return null; +} + +function fieldsetName( + element: Element, + eligible: Map, + budget: NameBudget, +): string | null { + let child = element.firstElementChild; + while (child !== null) { + addNameWork(budget); + if (child.tagName === "LEGEND") return safeText(child, eligible, budget); + child = child.nextElementSibling; + } + return null; +} + +function nativeInputRole(element: Element): DomObservation["role"] | null { + const type = element.getAttribute("type")?.toLowerCase() ?? "text"; + if (type === "checkbox") return "checkbox"; + if (element.hasAttribute("list")) return null; + return ["text", "email", "tel", "url"].includes(type) ? "textbox" : null; +} + +function roleFor(element: Element): DomObservation["role"] | null { + const explicitRole = element.getAttribute("role"); + if (element.tagName === "INPUT") { + const nativeRole = nativeInputRole(element); + if (nativeRole === null) return null; + return explicitRole === null || explicitRole === nativeRole ? nativeRole : null; + } + if (element.tagName === "TEXTAREA") + return explicitRole === null || explicitRole === "textbox" ? "textbox" : null; + if (explicitRole !== null) { + if (explicitRole === "button") return "button"; + if (explicitRole === "checkbox") return "checkbox"; + if (explicitRole === "group") return "group"; + if (explicitRole === "heading") return "heading"; + if (explicitRole === "link") return "link"; + if (explicitRole === "textbox") return "textbox"; + return null; + } + if (element.tagName === "BUTTON") return "button"; + if (element.tagName === "A" && element.hasAttribute("href")) return "link"; + if (/^H[1-6]$/u.test(element.tagName)) return "heading"; + return element.tagName === "FIELDSET" ? "group" : null; +} + +function accessibleName( + element: Element, + role: DomObservation["role"], + idIndex: IdIndex, + eligible: Map, + budget: NameBudget, +): string | null { + const aria = ariaName(element, idIndex, eligible, budget); + if (aria !== null) return aria; + if (role === "checkbox" || role === "textbox") + return labelName(element, idIndex, eligible, budget); + if (role === "group" && element.tagName === "FIELDSET") + return fieldsetName(element, eligible, budget); + return role === "button" || role === "link" || role === "heading" + ? safeText(element, eligible, budget) + : null; +} + +function ariaBoolean(element: Element, attribute: string): boolean | undefined { + const value = element.getAttribute(attribute); + if (value === null) return undefined; + if (value === "true") return true; + if (value === "false") return false; + throw new Error("invalid ARIA boolean state"); +} + +function isFirstLegendDescendant(element: Element, fieldset: Element, budget: NameBudget): boolean { + let child = fieldset.firstElementChild; + while (child !== null) { + addNameWork(budget); + if (child.tagName === "LEGEND") { + let parent: Element | null = element; + while (parent !== null && parent !== fieldset) { + addNameWork(budget); + if (parent === child) return true; + parent = parent.parentElement; + } + return false; + } + child = child.nextElementSibling; + } + return false; +} + +function nativeDisabled(element: Element, budget: NameBudget): boolean | undefined { + if (!["BUTTON", "INPUT", "TEXTAREA"].includes(element.tagName)) return undefined; + const direct = Reflect.get(element, "disabled"); + if (typeof direct !== "boolean") throw new Error("undetermined native disabled state"); + if (direct) return true; + let parent = element.parentElement; + while (parent !== null) { + addNameWork(budget); + if (parent.tagName === "FIELDSET") { + const disabled = Reflect.get(parent, "disabled"); + if (typeof disabled !== "boolean") throw new Error("undetermined inherited disabled state"); + if (disabled && !isFirstLegendDescendant(element, parent, budget)) return true; + } + parent = parent.parentElement; + } + return false; +} + +function nativeBoolean( + element: Element, + read: DomObservation["read"], + budget: NameBudget, +): boolean | undefined { + if ( + read === "checked" && + element.tagName === "INPUT" && + nativeInputRole(element) === "checkbox" + ) { + if (Reflect.get(element, "indeterminate") === true) throw new Error("indeterminate checkbox"); + const checked = Reflect.get(element, "checked"); + if (typeof checked !== "boolean") throw new Error("undetermined native checked state"); + return checked; + } + if (read === "required" && (element.tagName === "INPUT" || element.tagName === "TEXTAREA")) { + const required = Reflect.get(element, "required"); + if (typeof required !== "boolean") throw new Error("undetermined native required state"); + return required; + } + return read === "disabled" ? nativeDisabled(element, budget) : undefined; +} + +function readState(element: Element, read: DomObservation["read"], budget: NameBudget): boolean { + const attribute = read === "checked" ? "aria-checked" : `aria-${read}`; + const aria = ariaBoolean(element, attribute); + const native = nativeBoolean(element, read, budget); + if (aria !== undefined && native !== undefined) throw new Error("mixed native and ARIA state"); + if (aria !== undefined) return aria; + if (native !== undefined) return native; + throw new Error("unsupported DOM state"); +} + +function assertLiveTopLevelDocument(context: DomExecutionContext): void { + if (context.signal.aborted) throw new Error("aborted"); + const registration = new URL(context.registrationUrl); + if (registration.protocol !== "http:" && registration.protocol !== "https:") { + throw new Error("registration URL is not http(s)"); + } + const view = context.document.defaultView; + if (view === null) throw new Error("missing browsing context"); + if (view.top !== view || view.parent !== view) throw new Error("frame context"); + const current = new URL(view.location.href); + if (current.href !== registration.href || current.origin !== registration.origin) { + throw new Error("stale registration"); + } +} + +function collectLightDom(document: Document): { + elements: Element[]; + eligible: Map; + idIndex: IdIndex; +} { + const root = document.documentElement; + if (root === null) throw new Error("missing document root"); + const elements: Element[] = []; + const eligible = new Map(); + const idIndex: IdIndex = new Map(); + let current: Element | null = root; + let visited = 0; + let indexWork = 0; + + while (current !== null) { + visited += 1; + indexWork += 1; + if (visited > MAX_ELEMENTS || indexWork > MAX_INDEX_WORK) + throw new Error("DOM traversal limit"); + const parent = current.parentElement; + const parentEligible = parent === null || eligible.get(parent) === true; + const currentEligible = parentEligible && !isPrunedSelf(current); + eligible.set(current, currentEligible); + elements.push(current); + const id = current.getAttribute("id"); + if (id !== null && id !== "") { + if (id.length > MAX_ID_BYTES || utf8LengthAtMost(id, MAX_ID_BYTES) > MAX_ID_BYTES) { + throw new Error("DOM id-byte limit"); + } + idIndex.set(id, idIndex.has(id) ? null : { element: current, eligible: currentEligible }); + } + + if (current.firstElementChild !== null) { + current = current.firstElementChild; + continue; + } + while (current !== null && current !== root && current.nextElementSibling === null) + current = current.parentElement; + if (current === null || current === root) break; + current = current.nextElementSibling; + } + return { elements, eligible, idIndex }; +} + +/** Executes one declarative DOM tool against only the live top-level light DOM. */ +export async function executeDomTool( + tool: DomToolDescriptor, + input: unknown, + context: DomExecutionContext, +): Promise { + try { + const parsedTool = toolDescriptorSchema.safeParse(tool); + if (!parsedTool.success || parsedTool.data.execution.mode !== "dom") + throw new Error("invalid DOM descriptor"); + if (!validateToolInput(parsedTool.data.inputSchema, input).success) + throw new Error("invalid DOM input"); + assertLiveTopLevelDocument(context); + + const { elements, eligible, idIndex } = collectLightDom(context.document); + const observationsByRole = new Map>(); + const matches = new Map(); + for (const [key, observation] of Object.entries(parsedTool.data.execution.observations)) { + const roleObservations = observationsByRole.get(observation.role) ?? []; + roleObservations.push([key, observation]); + observationsByRole.set(observation.role, roleObservations); + } + + let candidates = 0; + const nameBudget: NameBudget = { work: 0 }; + for (const element of elements) { + if (eligible.get(element) !== true) continue; + const role = roleFor(element); + if (role === null) continue; + const observations = observationsByRole.get(role); + if (observations === undefined) continue; + candidates += 1; + if (candidates > MAX_CANDIDATES) throw new Error("DOM candidate limit"); + const name = accessibleName(element, role, idIndex, eligible, nameBudget); + for (const [key, observation] of observations) { + if (name !== observation.name) continue; + if (matches.has(key)) throw new Error("ambiguous DOM match"); + matches.set(key, element); + } + } + + const output: DomOutput = {}; + for (const [key, observation] of Object.entries(parsedTool.data.execution.observations)) { + const element = matches.get(key); + if (element === undefined) output[key] = { matched: false }; + else if (observation.read === "exists") output[key] = { matched: true }; + else output[key] = { matched: true, value: readState(element, observation.read, nameBudget) }; + } + + const text = JSON.stringify(output); + if (utf8LengthAtMost(text, MAX_OUTPUT_BYTES) > MAX_OUTPUT_BYTES) + throw new Error("DOM output limit"); + return mcpResult(text); + } catch { + return mcpResult("DOM tool execution failed."); + } +} diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index 93cdc5b..d2f146c 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -5,5 +5,7 @@ export { buildRequest, executeApiTool, handleResponse } from "./api-executor.js"; export type { ApiToolDescriptor, DerivedRequest, FetchOutcome } from "./api-executor.js"; +export { executeDomTool } from "./dom-executor.js"; +export type { DomExecutionContext, DomToolDescriptor } from "./dom-executor.js"; export { requiredEngineLevel, supportsPackageEngine } from "./engine-gate.js"; export type { McpResult, McpTextContent } from "./result.js"; diff --git a/packages/engine/test/dom-executor.test.ts b/packages/engine/test/dom-executor.test.ts new file mode 100644 index 0000000..d813558 --- /dev/null +++ b/packages/engine/test/dom-executor.test.ts @@ -0,0 +1,424 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { parseHTML } from "linkedom"; +import { toolDescriptorSchema } from "@webmcp-today/schema"; +import { executeDomTool } from "../src/dom-executor.js"; + +const URL = "https://example.com/checkout"; + +function tool(observations: Record) { + return toolDescriptorSchema.parse({ + name: "checkout_status", + description: "Read checkout status.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true, untrustedContentHint: true }, + execution: { mode: "dom", observations }, + }); +} + +function page(html: string, url = URL) { + const { document, window } = parseHTML(`${html}`); + Object.defineProperty(window, "location", { configurable: true, value: { href: url } }); + Object.defineProperty(window, "top", { configurable: true, value: window }); + Object.defineProperty(window, "parent", { configurable: true, value: window }); + for (const input of Array.from(document.querySelectorAll("input[checked]"))) { + Reflect.set(input, "checked", true); + } + for (const input of Array.from(document.querySelectorAll("input[required]"))) { + Reflect.set(input, "required", true); + } + for (const input of Array.from(document.querySelectorAll("input"))) { + Reflect.set(input, "indeterminate", false); + } + for (const button of Array.from(document.querySelectorAll("button[disabled]"))) { + Reflect.set(button, "disabled", true); + } + for (const fieldset of Array.from(document.querySelectorAll("fieldset[disabled]"))) { + Reflect.set(fieldset, "disabled", true); + } + vi.stubGlobal("Element", window.Element); + vi.stubGlobal("HTMLInputElement", window.HTMLInputElement); + vi.stubGlobal("HTMLTextAreaElement", window.HTMLTextAreaElement); + vi.stubGlobal("HTMLButtonElement", window.HTMLButtonElement); + vi.stubGlobal("HTMLFieldSetElement", window.HTMLFieldSetElement); + return { document, window }; +} + +async function execute( + html: string, + observations: Record, + options?: { url?: string; signal?: AbortSignal }, +) { + const { document } = page(html, options?.url ?? URL); + return executeDomTool( + tool(observations), + {}, + { + document, + registrationUrl: URL, + signal: options?.signal ?? new AbortController().signal, + }, + ); +} + +afterEach(() => vi.unstubAllGlobals()); + +describe("executeDomTool", () => { + it("returns only allowed boolean states for semantic controls", async () => { + const result = await execute( + ` + +
Delivery
`, + { + pay: { role: "button", name: "Pay now", read: "disabled" }, + terms: { role: "checkbox", name: "Accept terms", read: "checked" }, + terms_required: { role: "checkbox", name: "Accept terms", read: "required" }, + delivery: { role: "group", name: "Delivery", read: "exists" }, + }, + ); + expect(result.content[0]?.text).toBe( + '{"pay":{"matched":true,"value":true},"terms":{"matched":true,"value":true},"terms_required":{"matched":true,"value":true},"delivery":{"matched":true}}', + ); + }); + + it("returns matched false for zero matches and fails closed for ambiguous matches", async () => { + const absent = await execute("
", { + help: { role: "link", name: "Help", read: "exists" }, + }); + expect(absent.content[0]?.text).toBe('{"help":{"matched":false}}'); + + const ambiguous = await execute("", { + continue: { role: "button", name: "Continue", read: "exists" }, + }); + expect(ambiguous.content[0]?.text).toBe("DOM tool execution failed."); + }); + + it("rejects stale URLs, frames, and aborted calls", async () => { + const stale = await execute( + "", + { + continue: { role: "button", name: "Continue", read: "exists" }, + }, + { url: "https://example.com/other" }, + ); + expect(stale.content[0]?.text).toBe("DOM tool execution failed."); + + const frame = page(""); + Object.defineProperty(frame.window, "top", { configurable: true, value: {} }); + const framed = await executeDomTool( + tool({ continue: { role: "button", name: "Continue", read: "exists" } }), + {}, + { + document: frame.document, + registrationUrl: URL, + signal: new AbortController().signal, + }, + ); + expect(framed.content[0]?.text).toBe("DOM tool execution failed."); + + const controller = new AbortController(); + controller.abort(); + const aborted = await execute( + "", + { + continue: { role: "button", name: "Continue", read: "exists" }, + }, + { signal: controller.signal }, + ); + expect(aborted.content[0]?.text).toBe("DOM tool execution failed."); + }); + + it("never derives names from sensitive fields or ignored frame/shadow content", async () => { + const { document } = page( + '
', + ); + const host = document.getElementById("host"); + if (host === null) throw new Error("fixture missing host"); + host.attachShadow({ mode: "open" }).innerHTML = '
Pay now
'; + const result = await executeDomTool( + tool({ + pay: { role: "button", name: "Pay now", read: "exists" }, + sensitive: { role: "textbox", name: "Sensitive value", read: "exists" }, + }), + {}, + { document, registrationUrl: URL, signal: new AbortController().signal }, + ); + expect(result.content[0]?.text).toBe('{"pay":{"matched":false},"sensitive":{"matched":false}}'); + }); + + it("prunes forbidden subtrees before explicit-role candidate matching", async () => { + const result = await execute( + ` + + +
Inert button
+ +
Editable button
+ `, + { + password: { role: "checkbox", name: "Private", read: "checked" }, + hidden: { role: "textbox", name: "Private", read: "exists" }, + hidden_button: { role: "button", name: "Hidden button", read: "exists" }, + inert_button: { role: "button", name: "Inert button", read: "exists" }, + aria_hidden: { role: "button", name: "ARIA hidden button", read: "exists" }, + editable: { role: "button", name: "Editable button", read: "exists" }, + }, + ); + expect(result.content[0]?.text).toBe( + '{"password":{"matched":false},"hidden":{"matched":false},"hidden_button":{"matched":false},"inert_button":{"matched":false},"aria_hidden":{"matched":false},"editable":{"matched":false}}', + ); + }); + + it("keeps value-bearing hosts in their narrow native role set and rejects unsafe name sources", async () => { + const textareaRole = await execute( + '', + { + pay: { role: "button", name: "Pay", read: "exists" }, + }, + ); + expect(textareaRole.content[0]?.text).toBe('{"pay":{"matched":false}}'); + + const textareaLabel = await execute( + '', + { + pay: { role: "button", name: "Pay", read: "exists" }, + }, + ); + expect(textareaLabel.content[0]?.text).toBe("DOM tool execution failed."); + + const hiddenLabel = await execute( + '', + { terms: { role: "checkbox", name: "Accept terms", read: "exists" } }, + ); + expect(hiddenLabel.content[0]?.text).toBe('{"terms":{"matched":false}}'); + + const inertLabel = await execute( + '', + { terms: { role: "checkbox", name: "Accept terms", read: "exists" } }, + ); + expect(inertLabel.content[0]?.text).toBe('{"terms":{"matched":false}}'); + + const combobox = await execute('', { + search: { role: "textbox", name: "Search", read: "exists" }, + }); + expect(combobox.content[0]?.text).toBe('{"search":{"matched":false}}'); + }); + + it("fails closed for multiple native labels and duplicate label targets", async () => { + const multiple = page( + '', + ); + const input = multiple.document.getElementById("email"); + const first = multiple.document.getElementById("first"); + const second = multiple.document.getElementById("second"); + if (input === null || first === null || second === null) + throw new Error("fixture missing label"); + Object.defineProperty(input, "labels", { + configurable: true, + value: { + length: 2, + item(index: number) { + if (index === 0) return first; + return index === 1 ? second : null; + }, + }, + }); + const multipleResult = await executeDomTool( + tool({ email: { role: "textbox", name: "Primary", read: "exists" } }), + {}, + { + document: multiple.document, + registrationUrl: URL, + signal: new AbortController().signal, + }, + ); + expect(multipleResult.content[0]?.text).toBe("DOM tool execution failed."); + + const duplicateTarget = await execute( + '', + { email: { role: "textbox", name: "Email", read: "exists" } }, + ); + expect(duplicateTarget.content[0]?.text).toBe("DOM tool execution failed."); + }); + + it("uses the narrow native/ARIA boolean state matrix", async () => { + const result = await execute( + `
+
+
`, + { + terms: { role: "checkbox", name: "Terms", read: "checked" }, + pay: { role: "button", name: "Pay", read: "disabled" }, + email: { role: "textbox", name: "Email", read: "required" }, + }, + ); + expect(result.content[0]?.text).toBe( + '{"terms":{"matched":true,"value":true},"pay":{"matched":true,"value":false},"email":{"matched":true,"value":true}}', + ); + + const invalid = await execute( + '
', + { + terms: { role: "checkbox", name: "Terms", read: "checked" }, + }, + ); + expect(invalid.content[0]?.text).toBe("DOM tool execution failed."); + + const mixed = await execute('', { + terms: { role: "checkbox", name: "Terms", read: "checked" }, + }); + expect(mixed.content[0]?.text).toBe("DOM tool execution failed."); + + const indeterminate = page(''); + const input = indeterminate.document.querySelector("input"); + if (input === null) throw new Error("fixture missing checkbox"); + Reflect.set(input, "indeterminate", true); + const indeterminateResult = await executeDomTool( + tool({ terms: { role: "checkbox", name: "Terms", read: "checked" } }), + {}, + { + document: indeterminate.document, + registrationUrl: URL, + signal: new AbortController().signal, + }, + ); + expect(indeterminateResult.content[0]?.text).toBe("DOM tool execution failed."); + }); + + it("handles disabled fieldset inheritance and the first legend exception", async () => { + const result = await execute( + '
', + { + legend: { role: "button", name: "Legend action", read: "disabled" }, + blocked: { role: "button", name: "Blocked action", read: "disabled" }, + }, + ); + expect(result.content[0]?.text).toBe( + '{"legend":{"matched":true,"value":false},"blocked":{"matched":true,"value":true}}', + ); + }); + + it("does not fall back from unsupported explicit roles or unsafe implicit roles", async () => { + const result = await execute( + ` + Help`, + { + continue: { role: "button", name: "Continue", read: "exists" }, + help: { role: "link", name: "Help", read: "exists" }, + search: { role: "textbox", name: "Search", read: "exists" }, + pay: { role: "button", name: "Pay", read: "exists" }, + }, + ); + expect(result.content[0]?.text).toBe( + '{"continue":{"matched":false},"help":{"matched":false},"search":{"matched":false},"pay":{"matched":false}}', + ); + }); + + it("fails closed for duplicate aria-labelledby ids and bounded name work", async () => { + const duplicate = await execute( + 'ContinueOther', + { continue: { role: "button", name: "Continue", read: "exists" } }, + ); + expect(duplicate.content[0]?.text).toBe("DOM tool execution failed."); + + const duplicateToken = await execute( + 'Continue', + { + continue: { role: "button", name: "Continue", read: "exists" }, + }, + ); + expect(duplicateToken.content[0]?.text).toBe("DOM tool execution failed."); + + const hiddenTarget = await execute( + '', + { + continue: { role: "button", name: "Continue", read: "exists" }, + }, + ); + expect(hiddenTarget.content[0]?.text).toBe("DOM tool execution failed."); + + const missingTarget = await execute('', { + continue: { role: "button", name: "Continue", read: "exists" }, + }); + expect(missingTarget.content[0]?.text).toBe("DOM tool execution failed."); + + const prunedDuplicate = await execute( + 'Continue', + { continue: { role: "button", name: "Continue", read: "exists" } }, + ); + expect(prunedDuplicate.content[0]?.text).toBe("DOM tool execution failed."); + + const perName = await execute(``, { + button: { role: "button", name: "X", read: "exists" }, + }); + expect(perName.content[0]?.text).toBe("DOM tool execution failed."); + + const totalWork = await execute( + "
" + "".repeat(2000) + "
", + { + button: { role: "button", name: "No match", read: "exists" }, + }, + ); + expect(totalWork.content[0]?.text).toBe("DOM tool execution failed."); + + const hugeText = await execute(``, { + button: { role: "button", name: "x", read: "exists" }, + }); + expect(hugeText.content[0]?.text).toBe("DOM tool execution failed."); + + const hugeId = await execute( + `Continue`, + { + button: { role: "button", name: "Continue", read: "exists" }, + }, + ); + expect(hugeId.content[0]?.text).toBe("DOM tool execution failed."); + + const deepLabel = await execute( + "", + { + terms: { role: "checkbox", name: "Terms", read: "exists" }, + }, + ); + expect(deepLabel.content[0]?.text).toBe("DOM tool execution failed."); + + const hugeFieldset = await execute( + `
${"".repeat(4001)}Group
`, + { + group: { role: "group", name: "Group", read: "exists" }, + }, + ); + expect(hugeFieldset.content[0]?.text).toBe("DOM tool execution failed."); + }); + + it("fails on traversal and serialized-output bounds without truncating", async () => { + const traversal = await execute("
" + "
".repeat(10_000) + "
", { + missing: { role: "heading", name: "Nothing", read: "exists" }, + }); + expect(traversal.content[0]?.text).toBe("DOM tool execution failed."); + + const candidates = await execute("
" + "".repeat(2001) + "
", { + button: { role: "button", name: "No match", read: "exists" }, + }); + expect(candidates.content[0]?.text).toBe("DOM tool execution failed."); + + vi.spyOn(JSON, "stringify").mockReturnValue("x".repeat(4097)); + const output = await execute("

Status

", { + status: { role: "heading", name: "Status", read: "exists" }, + }); + expect(output.content[0]?.text).toBe("DOM tool execution failed."); + }); + + it("rejects non-empty runtime input and malformed mutation descriptors", async () => { + const { document } = page(""); + const input = await executeDomTool( + tool({ continue: { role: "button", name: "Continue", read: "exists" } }), + { action: "click" }, + { document, registrationUrl: URL, signal: new AbortController().signal }, + ); + expect(input.content[0]?.text).toBe("DOM tool execution failed."); + }); +}); diff --git a/packages/schema/README.md b/packages/schema/README.md index 231c985..57c6c4d 100644 --- a/packages/schema/README.md +++ b/packages/schema/README.md @@ -67,11 +67,13 @@ if (!result.success) { All public values are exported from the package root. - **Package schemas and types:** `createPackageSchema`, `createPackageObjectSchema`, `updatePackageMetaSchema`, `publishVersionSchema`, `publishVersionSchemaForDomain`, `CreatePackageInput`, `UpdatePackageMetaInput`, and `PublishVersionInput`. -- **Tool and input schemas:** `toolDescriptorSchema`, `inputSchemaSchema`, `executionDescriptorSchema`, `apiExecutionSchema`, plus their inferred types. Tool execution currently supports `execution: { mode: "api", endpoint }`. +- **Tool and input schemas:** `toolDescriptorSchema`, `inputSchemaSchema`, `executionDescriptorSchema`, `apiExecutionSchema`, `domExecutionSchema`, and their inferred types. DOM tools declare 1–16 exact semantic role/name observations and return only presence or allowed boolean states. They require an empty input schema, read-only and untrusted-content hints, and `minEngine: 2`. - **API format:** `apiBlockSchema`, `apiEndpointSchema`, `apiAuthSourceSchema`, `apiGraphqlSchema`, `collectApiIssues`, and the `ApiBlock`/`ApiEndpoint` types. Endpoints can declare a method, path, query, one request-body form (`body`, `form`, or `graphql`), optional JMESPath `returns`, error locators, and named auth sources. - **Registry and bridge wire schemas:** `webMcpPackageSchema`, response schemas such as `packageLookupResponseSchema`, `bridgeRequestSchema`, and local-bridge request/response schemas. - **Utilities and constants:** URL-pattern parsing/matching helpers including `matchUrlPattern` and `rankPackagesByUrl`; `unknownPlaceholders`; `canonicalizeApiBlock` and `apiContentHash`; and limits such as `TOOL_NAME_MAX`, `TOOL_DESCRIPTION_MAX`, and `ENGINE_VERSION`. +The `api` block remains required. A DOM-only package currently carries an inert same-site block with `endpoints: {}`; API tools still require their referenced endpoint. Publishing this public format change requires a schema minor release followed by an engine minor release; publish the schema first so the engine can depend on it. + For exact field constraints and all exports, see the [source](https://github.com/robertn702/webmcp-today/tree/main/packages/schema/src) and the [API-backed package-format documentation](https://github.com/robertn702/webmcp-today/blob/main/docs/api-execution-model.md). ## License diff --git a/packages/schema/src/api.ts b/packages/schema/src/api.ts index 345f048..2d65cac 100644 --- a/packages/schema/src/api.ts +++ b/packages/schema/src/api.ts @@ -320,9 +320,9 @@ export const apiEndpointSchema = z export const apiBlockSchema = z.strictObject({ baseUrl: httpsUrlSchema, auth: z.record(z.string(), apiAuthSourceSchema).optional(), - endpoints: z - .record(z.string(), apiEndpointSchema) - .refine((endpoints) => Object.keys(endpoints).length > 0, "api.endpoints must not be empty"), + // DOM-only packages retain the required api block for now. Package-level + // cross-validation still rejects every API tool whose endpoint is absent. + endpoints: z.record(z.string(), apiEndpointSchema), // Opaque named static GraphQL documents, referenced as "@documents/name". // NEVER template-scanned. documents: z.record(z.string(), z.string().min(1).max(DOCUMENT_MAX)).optional(), diff --git a/packages/schema/src/budgets.ts b/packages/schema/src/budgets.ts index 50fea9a..f424117 100644 --- a/packages/schema/src/budgets.ts +++ b/packages/schema/src/budgets.ts @@ -11,8 +11,6 @@ export const PARAM_DESCRIPTION_MAX = 150; /** Current package format engine version — a capability level compared with * plain `>=` against a version's `minEngine` (docs/DECISIONS.md 2026-07-24). * - * Keep level 1 valid for the initial package format. Bump the capability level - * only when a format change is incompatible with an older engine; compatible - * additions and changes do not require a bump. The extension refuses packages - * whose minEngine exceeds its supported level. */ -export const ENGINE_VERSION = 1; + * Level 2 adds read-only DOM observations. The extension refuses packages whose + * minEngine exceeds its supported level. */ +export const ENGINE_VERSION = 2; diff --git a/packages/schema/src/execution.ts b/packages/schema/src/execution.ts index 1603407..8643256 100644 --- a/packages/schema/src/execution.ts +++ b/packages/schema/src/execution.ts @@ -1,19 +1,97 @@ import { z } from "zod"; -// Execution descriptor — v1 supports exactly one mode: -// - "api": binds the tool to an api.endpoints entry by name. -// Reference integrity + {{param}} checks are package-level (they need the -// sibling `api` block) — see collectApiIssues in api.ts. -// `mode` stays an explicit literal (rather than dropping the field) so a -// future execution mode can turn this back into a discriminated union -// without migrating published package data. +const DOM_NAME_BYTES_MAX = 512; + +function utf8LengthAtMost(value: string, limit: number): number { + let bytes = 0; + for (let index = 0; index < value.length; index += 1) { + const code = value.charCodeAt(index); + if (code < 0x80) bytes += 1; + else if (code < 0x800) bytes += 2; + else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) { + const next = value.charCodeAt(index + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + bytes += 4; + index += 1; + } else bytes += 3; + } else bytes += 3; + if (bytes > limit) return limit + 1; + } + return bytes; +} + +// Execution descriptors bind a tool either to an API endpoint or to a tightly +// constrained read-only DOM observation set. API reference integrity remains +// package-level because it needs the sibling `api` block. export const apiExecutionSchema = z.strictObject({ mode: z.literal("api"), endpoint: z.string().min(1).max(64), }); -export const executionDescriptorSchema = apiExecutionSchema; +const normalizedName = z + .string() + .min(1) + .max(200) + .refine((value) => value === value.normalize("NFC").replace(/\s+/gu, " ").trim(), { + message: "must use NFC normalization with collapsed whitespace", + }) + .refine((value) => utf8LengthAtMost(value, DOM_NAME_BYTES_MAX) <= DOM_NAME_BYTES_MAX, { + message: "must not exceed 512 UTF-8 bytes", + }); + +const domRoleSchema = z.enum(["button", "checkbox", "group", "heading", "link", "textbox"]); +const domReadSchema = z.enum(["exists", "disabled", "checked", "required"]); + +export const domObservationSchema = z + .strictObject({ + role: domRoleSchema, + name: normalizedName, + read: domReadSchema, + }) + .superRefine((observation, ctx) => { + const valid = + observation.read === "exists" || + (observation.read === "checked" && observation.role === "checkbox") || + (observation.read === "required" && ["checkbox", "textbox"].includes(observation.role)) || + (observation.read === "disabled" && + ["button", "checkbox", "textbox"].includes(observation.role)); + if (!valid) { + ctx.addIssue({ + code: "custom", + message: `read "${observation.read}" is not supported for role "${observation.role}"`, + path: ["read"], + }); + } + }); + +export const domExecutionSchema = z.strictObject({ + mode: z.literal("dom"), + observations: z + .record( + z + .string() + .min(1) + .max(32) + .regex(/^[A-Za-z][A-Za-z0-9_-]*$/, "must be an identifier-shaped key"), + domObservationSchema, + ) + .refine( + (observations) => Object.keys(observations).length >= 1, + "must declare at least one observation", + ) + .refine( + (observations) => Object.keys(observations).length <= 16, + "may declare at most 16 observations", + ), +}); + +export const executionDescriptorSchema = z.discriminatedUnion("mode", [ + apiExecutionSchema, + domExecutionSchema, +]); export type ApiExecution = z.infer; +export type DomExecution = z.infer; +export type DomObservation = z.infer; export type ExecutionDescriptor = z.infer; diff --git a/packages/schema/src/package.ts b/packages/schema/src/package.ts index e3abb75..95dea80 100644 --- a/packages/schema/src/package.ts +++ b/packages/schema/src/package.ts @@ -124,10 +124,25 @@ export function applyDomainCrossValidation( } } +/** DOM observations require the level-2 executor in every package envelope. */ +export function applyDomEngineValidation( + pkg: { tools: z.infer; minEngine: number }, + ctx: z.RefinementCtx, +): void { + if (pkg.tools.some((tool) => tool.execution.mode === "dom") && pkg.minEngine < 2) { + ctx.addIssue({ + code: "custom", + message: "DOM tools require minEngine 2 or newer", + path: ["minEngine"], + }); + } +} + /** What contributors submit (contributor identity comes from auth, not the body). */ -export const createPackageSchema = createPackageObjectSchema.superRefine( - applyDomainCrossValidation, -); +export const createPackageSchema = createPackageObjectSchema.superRefine((pkg, ctx) => { + applyDomainCrossValidation(pkg, ctx); + applyDomEngineValidation(pkg, ctx); +}); /** * Metadata-only edits (packages row) — title and description. `domain` is the @@ -156,6 +171,7 @@ export const publishVersionSchema = createPackageObjectSchema for (const issue of collectApiIssues(pkg)) { ctx.addIssue({ code: "custom", message: issue.message, path: issue.path }); } + applyDomEngineValidation(pkg, ctx); }); /** @@ -173,9 +189,10 @@ export function publishVersionSchemaForDomain(domain: string) { changelog: true, minEngine: true, }) - .superRefine((pkg, ctx) => - applyDomainCrossValidation({ ...pkg, domain }, ctx, ["urlPatterns"]), - ); + .superRefine((pkg, ctx) => { + applyDomainCrossValidation({ ...pkg, domain }, ctx, ["urlPatterns"]); + applyDomEngineValidation(pkg, ctx); + }); } export type CreatePackageInput = z.infer; diff --git a/packages/schema/src/registry.ts b/packages/schema/src/registry.ts index 831167f..af4dbc5 100644 --- a/packages/schema/src/registry.ts +++ b/packages/schema/src/registry.ts @@ -1,5 +1,9 @@ import { z } from "zod"; -import { applyDomainCrossValidation, createPackageObjectSchema } from "./package.js"; +import { + applyDomEngineValidation, + applyDomainCrossValidation, + createPackageObjectSchema, +} from "./package.js"; // Shapes served by the registry API (superset of the submission format). @@ -39,9 +43,10 @@ const webMcpPackageObjectSchema = createPackageObjectSchema.extend({ * checks existed fails closed instead of being served as-is — see * `apps/web/lib/packages-repo.ts`'s `hydrate`. */ -export const webMcpPackageSchema = webMcpPackageObjectSchema - .loose() - .superRefine((pkg, ctx) => applyDomainCrossValidation(pkg, ctx)); +export const webMcpPackageSchema = webMcpPackageObjectSchema.loose().superRefine((pkg, ctx) => { + applyDomainCrossValidation(pkg, ctx); + applyDomEngineValidation(pkg, ctx); +}); export const packageListResponseSchema = z.object({ packages: z.array(webMcpPackageSchema), diff --git a/packages/schema/src/tool.ts b/packages/schema/src/tool.ts index c8d05a7..71a4c45 100644 --- a/packages/schema/src/tool.ts +++ b/packages/schema/src/tool.ts @@ -3,7 +3,7 @@ import { TOOL_DESCRIPTION_MAX, TOOL_NAME_MAX } from "./budgets.js"; import { executionDescriptorSchema } from "./execution.js"; import { inputSchemaSchema } from "./input-schema.js"; -// Tool descriptor — one WebMCP tool: metadata + its API execution binding. +// Tool descriptor — one WebMCP tool: metadata + its execution binding. export const toolAnnotationsSchema = z .strictObject({ @@ -21,7 +21,7 @@ export const toolAnnotationsSchema = z } }); -export const toolDescriptorSchema = z.strictObject({ +const toolDescriptorObjectSchema = z.strictObject({ name: z .string() .min(1) @@ -30,11 +30,46 @@ export const toolDescriptorSchema = z.strictObject({ description: z.string().min(1).max(TOOL_DESCRIPTION_MAX), inputSchema: inputSchemaSchema, annotations: toolAnnotationsSchema.optional(), - // How the tool executes: v1 is "api" only. API-endpoint reference + - // placeholder checks are package-level (they need the sibling `api` - // block) — see collectApiIssues in api.ts. + // API references are package-level (they need the sibling `api` block) — + // see collectApiIssues in api.ts. DOM tools are constrained below. execution: executionDescriptorSchema, }); +export const toolDescriptorSchema = toolDescriptorObjectSchema.superRefine((tool, ctx) => { + if (tool.execution.mode !== "dom") return; + + if ( + Object.keys(tool.inputSchema.properties).length > 0 || + (tool.inputSchema.required?.length ?? 0) > 0 + ) { + ctx.addIssue({ + code: "custom", + message: "DOM tools must use an empty input schema", + path: ["inputSchema"], + }); + } + if (tool.annotations?.readOnlyHint !== true) { + ctx.addIssue({ + code: "custom", + message: "DOM tools must set annotations.readOnlyHint to true", + path: ["annotations", "readOnlyHint"], + }); + } + if (tool.annotations?.untrustedContentHint !== true) { + ctx.addIssue({ + code: "custom", + message: "DOM tools must set annotations.untrustedContentHint to true", + path: ["annotations", "untrustedContentHint"], + }); + } + if (tool.annotations?.destructiveHint === true) { + ctx.addIssue({ + code: "custom", + message: "DOM tools cannot be destructive", + path: ["annotations", "destructiveHint"], + }); + } +}); + export type ToolAnnotations = z.infer; export type ToolDescriptor = z.infer; diff --git a/packages/schema/test/api-validation.test.ts b/packages/schema/test/api-validation.test.ts index 98164f7..f766ac1 100644 --- a/packages/schema/test/api-validation.test.ts +++ b/packages/schema/test/api-validation.test.ts @@ -565,13 +565,13 @@ describe("apiAuthSourceSchema pattern validation", () => { }); }); -describe("apiBlockSchema endpoints requirement", () => { - it("rejects an empty endpoints object", () => { +describe("apiBlockSchema endpoints", () => { + it("allows an empty endpoints object for DOM-only packages", () => { const result = apiBlockSchema.safeParse({ baseUrl: "https://acme.com", endpoints: {}, }); - expect(result.success).toBe(false); + expect(result.success).toBe(true); }); it("accepts a single endpoint", () => { diff --git a/packages/schema/test/dom-validation.test.ts b/packages/schema/test/dom-validation.test.ts new file mode 100644 index 0000000..5d53461 --- /dev/null +++ b/packages/schema/test/dom-validation.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from "vitest"; +import { + createPackageSchema, + executionDescriptorSchema, + publishVersionSchema, + publishVersionSchemaForDomain, + webMcpPackageSchema, +} from "../src/index.js"; + +const domTool = { + name: "checkout_status", + description: "Check whether checkout is ready.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true, untrustedContentHint: true }, + execution: { + mode: "dom", + observations: { + pay_button: { role: "button", name: "Pay now", read: "disabled" }, + terms: { role: "checkbox", name: "Accept terms", read: "checked" }, + }, + }, +}; + +function domPackage() { + return { + version: 1, + domain: "en.wikipedia.org", + urlPatterns: ["*://en.wikipedia.org/*"], + title: "Checkout status", + description: "Read-only checkout structure.", + minEngine: 2, + tools: [structuredClone(domTool)], + api: { baseUrl: "https://en.wikipedia.org", endpoints: {} }, + }; +} + +describe("DOM execution descriptor", () => { + it("accepts bounded semantic observations and an inert api block", () => { + expect(executionDescriptorSchema.safeParse(domTool.execution).success).toBe(true); + expect(createPackageSchema.safeParse(domPackage()).success).toBe(true); + }); + + it("requires normalized exact names and valid role/read combinations", () => { + const decomposed = structuredClone(domTool.execution); + decomposed.observations.pay_button.name = "Pay now"; + expect(executionDescriptorSchema.safeParse(decomposed).success).toBe(false); + + const invalidRead = structuredClone(domTool.execution); + invalidRead.observations.pay_button.read = "checked"; + expect(executionDescriptorSchema.safeParse(invalidRead).success).toBe(false); + + const overBytes = structuredClone(domTool.execution); + overBytes.observations.pay_button.name = "界".repeat(200); + expect(executionDescriptorSchema.safeParse(overBytes).success).toBe(false); + + const withinBytes = structuredClone(domTool.execution); + withinBytes.observations.pay_button.name = "é".repeat(200); + expect(executionDescriptorSchema.safeParse(withinBytes).success).toBe(true); + }); + + it("rejects mutation vocabulary and selectors in strict descriptors", () => { + expect( + executionDescriptorSchema.safeParse({ ...domTool.execution, action: "click" }).success, + ).toBe(false); + expect( + executionDescriptorSchema.safeParse({ ...domTool.execution, selector: "button" }).success, + ).toBe(false); + expect( + executionDescriptorSchema.safeParse({ ...domTool.execution, value: "secret" }).success, + ).toBe(false); + expect( + executionDescriptorSchema.safeParse({ ...domTool.execution, submit: true }).success, + ).toBe(false); + }); + + it("requires empty read-only, untrusted DOM tool inputs and engine level 2", () => { + const nonEmptyInput = { + ...domPackage(), + tools: [ + { + ...structuredClone(domTool), + inputSchema: { + type: "object", + properties: { submit: { type: "string" } }, + additionalProperties: false, + }, + }, + ], + }; + expect(createPackageSchema.safeParse(nonEmptyInput).success).toBe(false); + + const destructive = { + ...domPackage(), + tools: [ + { + ...structuredClone(domTool), + annotations: { ...domTool.annotations, destructiveHint: true }, + }, + ], + }; + expect(createPackageSchema.safeParse(destructive).success).toBe(false); + + const oldEngine = domPackage(); + oldEngine.minEngine = 1; + expect(createPackageSchema.safeParse(oldEngine).success).toBe(false); + }); + + it("continues to reject API tools with a missing endpoint", () => { + const invalid = { + ...domPackage(), + tools: [ + { + ...structuredClone(domTool), + execution: { mode: "api", endpoint: "missing" }, + }, + ], + }; + expect(createPackageSchema.safeParse(invalid).success).toBe(false); + }); + + it("enforces the DOM engine floor across every package envelope", () => { + const body = domPackage(); + body.minEngine = 1; + expect(createPackageSchema.safeParse(body).success).toBe(false); + const version = { + version: body.version, + urlPatterns: body.urlPatterns, + tools: body.tools, + api: body.api, + minEngine: body.minEngine, + }; + expect(publishVersionSchema.safeParse(version).success).toBe(false); + expect(publishVersionSchemaForDomain(body.domain).safeParse(version).success).toBe(false); + expect( + webMcpPackageSchema.safeParse({ + ...body, + id: "pkg-dom", + versionId: "ver-dom", + contributor: "fixture", + createdAt: "2026-09-02T00:00:00.000Z", + updatedAt: "2026-09-02T00:00:00.000Z", + }).success, + ).toBe(false); + }); +}); From 5c466a3b33cfcbb6adf7c2373cbb74fa833ed32b Mon Sep 17 00:00:00 2001 From: robertn702 <8119609+robertn702@users.noreply.github.com> Date: Wed, 2 Sep 2026 22:25:48 +0000 Subject: [PATCH 2/2] fix(engine): repair DOM package contract --- ARCHITECTURE.md | 6 +- apps/extension/AGENTS.md | 6 +- apps/extension/src/lib/register-tools.ts | 2 +- .../(registry)/docs/package-format/page.tsx | 7 +- bun.lock | 14 ++-- docs/api-execution-model.md | 2 +- docs/release-security.md | 33 +++++---- packages/engine/package.json | 4 +- packages/engine/src/dom-executor.ts | 3 +- packages/engine/test/dom-executor.test.ts | 8 ++- packages/schema/package.json | 2 +- scripts/check-engine-package.mjs | 72 +++++++++++++++---- 12 files changed, 108 insertions(+), 51 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6c13682..69a102a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -175,8 +175,10 @@ Two execution modes are selected per tool: - **API mode (tier 1)** — the package declares the site's own HTTP API as data (`api.endpoints`, `auth` token sources, `returns` projections); the executor derives and performs the call. Ships zero code. The load-bearing invariant: **`api.baseUrl` - must use the package domain or a subdomain, and every derived request is pinned to - that exact origin after interpolation**. `urlPatterns` select pages for tool + must normally use the package domain or a subdomain, and every derived request is + pinned to that exact origin after interpolation**. The sole cross-origin exception is + anonymous `GET` reads from `https://hacker-news.firebaseio.com`, with no auth, + omitted cookies, and rejected redirects. `urlPatterns` select pages for tool registration; they do not constrain `api.baseUrl` or need to cover it. Tiers 2–3 (scoped script slots, full `evaluate`) are designed but not shipped — see `docs/api-execution-model.md`. - **DOM mode (level 2)** — reads only a bounded, top-level light-DOM set of exact diff --git a/apps/extension/AGENTS.md b/apps/extension/AGENTS.md index e6dcecd..79df277 100644 --- a/apps/extension/AGENTS.md +++ b/apps/extension/AGENTS.md @@ -170,8 +170,10 @@ package(s) matched this URL` → bridge `list_webmcp_tools` shows the tools. - The executors live in `packages/engine` (`@webmcp-today/engine`, MIT) — extracted from `src/lib/` for license separation (docs/DECISIONS.md 2026-07-30): `api-executor.ts` binds `{{param}}` templates, acquires auth - tokens from `api.auth` sources, performs the same-origin fetch, checks - `errorPath`, applies the `returns` JMESPath projection. `destructiveHint` + tokens from `api.auth` sources, performs the origin-pinned fetch, checks + `errorPath`, applies the `returns` JMESPath projection. The sole cross-origin + exception is anonymous `GET` reads from `https://hacker-news.firebaseio.com`, + with no auth, omitted cookies, and rejected redirects. `destructiveHint` tools gate on a blocking `window.confirm`. The fetch MUST run in the content-script (page) context — the SameSite-cookie rationale is the header comment in `packages/engine/src/api-executor.ts`. `dom-executor.ts` is a separate diff --git a/apps/extension/src/lib/register-tools.ts b/apps/extension/src/lib/register-tools.ts index c89c287..43d7397 100644 --- a/apps/extension/src/lib/register-tools.ts +++ b/apps/extension/src/lib/register-tools.ts @@ -96,7 +96,7 @@ export async function runRegistrationPass( execute = (params) => executeApiTool({ ...tool, execution }, api, params); } else { execute = (params) => - executeDomTool(tool, params, { + executeDomTool({ ...tool, execution }, params, { document: deps.getDocument(), registrationUrl: url, signal, diff --git a/apps/web/app/(registry)/docs/package-format/page.tsx b/apps/web/app/(registry)/docs/package-format/page.tsx index 0806dd7..4a0678c 100644 --- a/apps/web/app/(registry)/docs/package-format/page.tsx +++ b/apps/web/app/(registry)/docs/package-format/page.tsx @@ -21,9 +21,10 @@ export default function PackageFormatPage() {

The package format

A package is one JSON document. It names the site it targets, the tools it registers there, - and the site's own HTTP endpoints those tools call. Nothing in it can run arbitrary - code in the page: a tool is a declared request, not a script. This page covers every field. - When you're ready,{" "} + and the API metadata they use, which is an inert same-site block for DOM-only packages. Each + tool declares either an HTTP request or a bounded read-only DOM observation. Nothing in it + can run arbitrary code in the page: tools are declarations, not scripts. This page covers + every field. When you're ready,{" "} paste it into the form diff --git a/bun.lock b/bun.lock index 3433026..24de3e1 100644 --- a/bun.lock +++ b/bun.lock @@ -108,10 +108,10 @@ }, "packages/engine": { "name": "@webmcp-today/engine", - "version": "0.1.0", + "version": "0.2.0", "dependencies": { "@jmespath-community/jmespath": "1.3.0", - "@webmcp-today/schema": "0.3.0", + "@webmcp-today/schema": "0.4.0", }, "devDependencies": { "linkedom": "0.18.13", @@ -121,13 +121,13 @@ }, "packages/mcp": { "name": "@webmcp-today/mcp-bridge", - "version": "0.3.0", + "version": "0.3.1", "bin": { - "webmcp-today-mcp": "./dist/index.js", + "webmcp-today-mcp": "dist/index.js", }, "dependencies": { "@modelcontextprotocol/sdk": "^1.17.0", - "@webmcp-today/schema": "workspace:*", + "@webmcp-today/schema": "0.3.0", "zod": "^4.0.0", }, "devDependencies": { @@ -139,7 +139,7 @@ }, "packages/schema": { "name": "@webmcp-today/schema", - "version": "0.3.0", + "version": "0.4.0", "dependencies": { "@jmespath-community/jmespath": "1.3.0", "tldts": "7.4.10", @@ -2366,6 +2366,8 @@ "@typescript-eslint/visitor-keys/eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="], + "@webmcp-today/mcp-bridge/@webmcp-today/schema": ["@webmcp-today/schema@0.3.0", "", { "dependencies": { "@jmespath-community/jmespath": "1.3.0", "tldts": "7.4.10", "zod": "^4.0.0" } }, "sha512-nGC0WmeV7QjLpT3hh79y+T3MFy34Ab1wX9PvjzUzVL2hY/hB8qVUHC6rBaJf/PEFZP49aPUe6FHSy3d/15rEOw=="], + "@wxt-dev/storage/@wxt-dev/browser": ["@wxt-dev/browser@0.1.43", "", { "dependencies": { "@types/filesystem": "*", "@types/har-format": "*" } }, "sha512-RMB0zgfe7uuiTp18s9taLeKXoOCLBV418797dnEggiMWmM1JDJekiLtlvrNc6QeZg+amDBy2/KKYuQB2kh/K9A=="], "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], diff --git a/docs/api-execution-model.md b/docs/api-execution-model.md index f92df39..c406b0a 100644 --- a/docs/api-execution-model.md +++ b/docs/api-execution-model.md @@ -28,7 +28,7 @@ Flagship target: a **read + write Reddit package** backed by its JSON API — re threads, plus posting comments — controllable from a terminal LLM through WebMCP. That requires authenticated writes, which forces the token-acquisition design below. -API execution remains the general execution model. Engine level 2 also supports a deliberately narrow DOM read mode: exact semantic role/name observations with only `exists`, `disabled`, `checked`, or `required` boolean output. It cannot use selectors, values, HTML, frames, shadow roots, or mutation operations. DOM-only packages currently carry an inert same-site `api` block with `endpoints: {}`; publishing this format requires schema and engine minor releases and `minEngine: 2`. +API execution remains the general execution model. Engine level 2 also supports a deliberately narrow DOM read mode: exact semantic role/name observations with `matched` and only `disabled`, `checked`, or `required` boolean output. It cannot use selectors, values, HTML, frames, shadow roots, or mutation operations. DOM-only packages currently carry an inert same-site `api` block with `endpoints: {}`; publishing this format requires schema and engine minor releases and `minEngine: 2`. ## Tiered execution model diff --git a/docs/release-security.md b/docs/release-security.md index a43b908..7f771a5 100644 --- a/docs/release-security.md +++ b/docs/release-security.md @@ -16,10 +16,10 @@ exists anywhere in the repository or environment, and npm records publish provenance automatically. The publish job holds only `contents: read` and `id-token: write`, and every action is pinned to a full commit SHA. -The first `@webmcp-today/engine` publication is a one-time human-run bootstrap -using the maintainer's npm credentials and the reviewed commands below. It does -not use the OIDC workflow, so the publisher must verify the exact checkout and -tarball contents before approving the command. +`@webmcp-today/engine` releases are human-run using the maintainer's npm +credentials and the reviewed commands below. They do not use the OIDC workflow, +so the publisher must verify the exact checkout and tarball contents before +approving the command. ## Checksum scope @@ -78,21 +78,27 @@ environment, and the required reviewer is the last line of defense for a legitimate tag run. Review the exact workflow file being executed before approving any run. -## First engine publication +## Engine publication -The proposed first version is `@webmcp-today/engine@0.1.0`. This first bootstrap -is a human-run npm publication; do not add the engine to the automated OIDC -workflow until a later, separately reviewed release process requires it. +Engine releases remain human-run npm publications; do not add the engine to the +automated OIDC workflow until a later, separately reviewed release process +requires it. -Before publishing, confirm that `@webmcp-today/schema@0.3.0` is public (the -engine's exact runtime dependency), the reviewed commit is checked out, and the -package gate passes: +For the DOM execution release, publish `@webmcp-today/schema@0.4.0` first, then +confirm it is public before publishing `@webmcp-today/engine@0.2.0` (which pins +that exact runtime dependency). The reviewed commit must be checked out and the +package gate must pass: ```bash -bun run check:engine-package +bun run check:engine-package --published-schema (cd packages/engine && npm publish --dry-run --access public) ``` +CI runs the same gate without `--published-schema`, installing locally packed +schema and engine tarballs so an unpublished release pair can be reviewed. The +release-mode flag installs only the engine tarball and requires npm to supply +the pinned schema version that was published first. + The human publisher must be authenticated to npm with permission to publish the `@webmcp-today` scope and must inspect the dry-run tarball before running this exact command from `packages/engine`: @@ -101,9 +107,6 @@ exact command from `packages/engine`: npm publish --access public ``` -ROB-216 prepares this command only. It does not publish, release, merge, or -deploy `@webmcp-today/engine`. - ### One-time npm Trusted Publisher configuration Configure a Trusted Publisher per package on npmjs.com (the `npm trust` flow if diff --git a/packages/engine/package.json b/packages/engine/package.json index 6927ce8..3853b82 100644 --- a/packages/engine/package.json +++ b/packages/engine/package.json @@ -1,6 +1,6 @@ { "name": "@webmcp-today/engine", - "version": "0.1.0", + "version": "0.2.0", "description": "Execution engine for WebMCP Today — runs declarative API calls and bounded read-only DOM observations", "type": "module", "license": "MIT", @@ -30,7 +30,7 @@ }, "dependencies": { "@jmespath-community/jmespath": "1.3.0", - "@webmcp-today/schema": "0.3.0" + "@webmcp-today/schema": "0.4.0" }, "devDependencies": { "linkedom": "0.18.13", diff --git a/packages/engine/src/dom-executor.ts b/packages/engine/src/dom-executor.ts index 4f1516b..bccd678 100644 --- a/packages/engine/src/dom-executor.ts +++ b/packages/engine/src/dom-executor.ts @@ -1,6 +1,7 @@ import { toolDescriptorSchema, validateToolInput, + type DomExecution, type DomObservation, type ToolDescriptor, } from "@webmcp-today/schema"; @@ -28,7 +29,7 @@ const PRUNED_TAGS = new Set([ ]); const TEXT_EXCLUDED_TAGS = new Set(["INPUT", "TEXTAREA", ...PRUNED_TAGS]); -export type DomToolDescriptor = ToolDescriptor; +export type DomToolDescriptor = Omit & { execution: DomExecution }; export interface DomExecutionContext { document: Document; diff --git a/packages/engine/test/dom-executor.test.ts b/packages/engine/test/dom-executor.test.ts index d813558..b4c06d5 100644 --- a/packages/engine/test/dom-executor.test.ts +++ b/packages/engine/test/dom-executor.test.ts @@ -1,18 +1,20 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { parseHTML } from "linkedom"; import { toolDescriptorSchema } from "@webmcp-today/schema"; -import { executeDomTool } from "../src/dom-executor.js"; +import { executeDomTool, type DomToolDescriptor } from "../src/dom-executor.js"; const URL = "https://example.com/checkout"; -function tool(observations: Record) { - return toolDescriptorSchema.parse({ +function tool(observations: Record): DomToolDescriptor { + const parsed = toolDescriptorSchema.parse({ name: "checkout_status", description: "Read checkout status.", inputSchema: { type: "object", properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true, untrustedContentHint: true }, execution: { mode: "dom", observations }, }); + if (parsed.execution.mode !== "dom") throw new Error("expected DOM tool descriptor"); + return { ...parsed, execution: parsed.execution }; } function page(html: string, url = URL) { diff --git a/packages/schema/package.json b/packages/schema/package.json index 5db435a..2a637c0 100644 --- a/packages/schema/package.json +++ b/packages/schema/package.json @@ -1,6 +1,6 @@ { "name": "@webmcp-today/schema", - "version": "0.3.0", + "version": "0.4.0", "description": "Config format for WebMCP Today — zod schemas for community WebMCP tool configs", "type": "module", "license": "MIT", diff --git a/scripts/check-engine-package.mjs b/scripts/check-engine-package.mjs index bbaedd6..3ad287a 100644 --- a/scripts/check-engine-package.mjs +++ b/scripts/check-engine-package.mjs @@ -1,12 +1,18 @@ #!/usr/bin/env bun -/* global console */ +/* global console, process */ import { spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; const repoRoot = resolve(import.meta.dirname, ".."); const engineDir = join(repoRoot, "packages/engine"); +const schemaDir = join(repoRoot, "packages/schema"); const scratchDir = join(repoRoot, ".scratch"); +const usePublishedSchema = process.argv.includes("--published-schema"); + +if (process.argv.slice(2).some((argument) => argument !== "--published-schema")) { + throw new Error("usage: bun scripts/check-engine-package.mjs [--published-schema]"); +} function fail(message) { throw new Error(message); @@ -21,6 +27,15 @@ function run(command, args, cwd) { return result.stdout; } +function packPackage(packageDir, packDir) { + const output = run("npm", ["pack", "--json", "--pack-destination", packDir], packageDir); + const jsonStart = output.lastIndexOf("\n["); + const [packed] = JSON.parse(output.slice(jsonStart === -1 ? 0 : jsonStart)); + if (!packed?.filename || !Array.isArray(packed.files)) + fail(`npm pack did not report a tarball file list for ${packageDir}`); + return packed; +} + let tempDir; try { @@ -29,14 +44,13 @@ try { const packDir = join(tempDir, "pack"); mkdirSync(packDir); - const packOutput = run("npm", ["pack", "--json", "--pack-destination", packDir], engineDir); - const packJsonStart = packOutput.lastIndexOf("\n["); - const [packed] = JSON.parse(packOutput.slice(packJsonStart === -1 ? 0 : packJsonStart)); - if (!packed?.filename || !Array.isArray(packed.files)) - fail("npm pack did not report a tarball file list"); + const schemaPackage = JSON.parse(readFileSync(join(schemaDir, "package.json"), "utf8")); + if (typeof schemaPackage.version !== "string") fail("schema package has no version"); + const packedSchema = usePublishedSchema ? null : packPackage(schemaDir, packDir); + const packed = packPackage(engineDir, packDir); const packedFiles = new Set(packed.files.map((file) => file.path)); - const modules = ["index", "api-executor", "engine-gate", "mcp-result", "result"]; + const modules = ["index", "api-executor", "dom-executor", "engine-gate", "mcp-result", "result"]; const requiredFiles = [ "package.json", "LICENSE", @@ -53,24 +67,37 @@ try { const consumerDir = join(tempDir, "consumer"); mkdirSync(consumerDir); writeFileSync(join(consumerDir, "package.json"), '{"private":true,"type":"module"}\n'); - const tarball = join(packDir, packed.filename); - run("npm", ["install", "--ignore-scripts", "--no-audit", "--no-fund", tarball], consumerDir); + const engineTarball = join(packDir, packed.filename); + const installTargets = [engineTarball]; + if (packedSchema !== null) installTargets.unshift(join(packDir, packedSchema.filename)); + run( + "npm", + ["install", "--ignore-scripts", "--no-audit", "--no-fund", ...installTargets], + consumerDir, + ); const installedPackage = JSON.parse( readFileSync(join(consumerDir, "node_modules/@webmcp-today/engine/package.json"), "utf8"), ); - if (installedPackage.dependencies?.["@webmcp-today/schema"] !== "0.3.0") { - fail("packed engine must pin @webmcp-today/schema to 0.3.0"); + const installedSchema = JSON.parse( + readFileSync(join(consumerDir, "node_modules/@webmcp-today/schema/package.json"), "utf8"), + ); + if (installedPackage.dependencies?.["@webmcp-today/schema"] !== schemaPackage.version) { + fail(`packed engine must pin @webmcp-today/schema to ${schemaPackage.version}`); + } + if (installedSchema.version !== schemaPackage.version) { + fail(`consumer installed schema ${installedSchema.version}, expected ${schemaPackage.version}`); } const testFile = join(consumerDir, "engine.test.mjs"); writeFileSync( testFile, `import { expect, test } from "bun:test"; -import { buildRequest, executeApiTool, handleResponse } from "@webmcp-today/engine"; +import { buildRequest, executeApiTool, executeDomTool, handleResponse } from "@webmcp-today/engine"; test("exposes the engine package API", () => { expect(typeof executeApiTool).toBe("function"); + expect(typeof executeDomTool).toBe("function"); expect(typeof buildRequest).toBe("function"); expect(typeof handleResponse).toBe("function"); }); @@ -85,9 +112,12 @@ test("exposes the engine package API", () => { `import { buildRequest, executeApiTool, + executeDomTool, handleResponse, type ApiToolDescriptor, type DerivedRequest, + type DomExecutionContext, + type DomToolDescriptor, type FetchOutcome, type McpResult, type McpTextContent, @@ -95,10 +125,24 @@ test("exposes the engine package API", () => { declare const tool: ApiToolDescriptor; declare const request: DerivedRequest; +declare const domContext: DomExecutionContext; +declare const domTool: DomToolDescriptor; declare const outcome: FetchOutcome; declare const result: McpResult; declare const content: McpTextContent; -void [buildRequest, executeApiTool, handleResponse, tool, request, outcome, result, content]; +void [ + buildRequest, + executeApiTool, + executeDomTool, + handleResponse, + tool, + request, + domContext, + domTool, + outcome, + result, + content, +]; `, ); writeFileSync( @@ -126,7 +170,7 @@ void [buildRequest, executeApiTool, handleResponse, tool, request, outcome, resu const metafile = join(consumerDir, "meta.json"); writeFileSync( entryPoint, - 'import { executeApiTool } from "@webmcp-today/engine";\nexport { executeApiTool };\n', + 'import { executeApiTool, executeDomTool } from "@webmcp-today/engine";\nexport { executeApiTool, executeDomTool };\n', ); run( "bun",