Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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` |
Expand Down
14 changes: 9 additions & 5 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,16 +170,20 @@ 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
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
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
Expand Down
15 changes: 9 additions & 6 deletions apps/extension/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,15 +167,18 @@ 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
tokens from `api.auth` sources, performs the same-origin fetch, checks
`errorPath`, applies the `returns` JMESPath projection. `destructiveHint`
`api-executor.ts` binds `{{param}}` templates, acquires auth
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`.
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`).
Expand Down
11 changes: 7 additions & 4 deletions apps/extension/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)<br/>(validate input first, same-origin fetch,<br/>auth tokens, JMESPath projection,<br/>destructiveHint confirm)"]
CB --> DOM["dom-executor (packages/engine)<br/>(bounded top-level semantic reads)"]
API --> RESULT["mcp-result (packages/engine)<br/>(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

Expand Down
1 change: 1 addition & 0 deletions apps/extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions apps/extension/src/entrypoints/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export default defineContentScript({
const deps: RegistrationDeps = {
loadPackages: getPackagesForUrl,
getModelContext: getContentModelContext,
getDocument: () => document,
siteDeclaredToolNames,
reportStatus,
};
Expand Down
38 changes: 26 additions & 12 deletions apps/extension/src/lib/register-tools.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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<string>;
/** Surfaces the pass outcome on the action badge + popup. */
Expand Down Expand Up @@ -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, execution }, 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)) {
Expand Down
4 changes: 2 additions & 2 deletions apps/extension/test/install-bridge.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -154,7 +154,7 @@ describe("handleBridgeRequest", () => {
expect(response).toEqual({
ok: true,
protocol: 1,
engine: 1,
engine: ENGINE_VERSION,
extensionVersion: "0.0.1",
storageReadable: true,
});
Expand Down
73 changes: 73 additions & 0 deletions apps/extension/test/register-tools.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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(
"<!doctype html><html><body><h1>Coffee</h1></body></html>",
);
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<string, unknown>) => Promise<unknown>) | 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" });
Expand Down Expand Up @@ -148,6 +220,7 @@ describe("runRegistrationPass", () => {
return { packages: [pkg("wiki_summary")] };
},
getModelContext: () => mc,
getDocument: () => document,
siteDeclaredToolNames: () => new Set(),
reportStatus: (status) => statuses.push(status),
};
Expand Down
22 changes: 12 additions & 10 deletions apps/web/app/(registry)/docs/package-format/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ export default function PackageFormatPage() {
<h1 className="mt-3 font-display text-4xl tracking-tight">The package format</h1>
<p className="mt-4 text-sm leading-relaxed text-muted-foreground">
A package is one JSON document. It names the site it targets, the tools it registers there,
and the site&apos;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&apos;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&apos;re ready,{" "}
<Link href="/submit" className="text-foreground underline underline-offset-4">
paste it into the form
</Link>
Expand Down Expand Up @@ -65,13 +66,13 @@ export default function PackageFormatPage() {
The tools registered on a matching page. Names must be unique within the package.
</Field>
<Field name="api" type="ApiBlock · required">
The site&apos;s HTTP surface, with at least one endpoint. Execution is api-mode only, so
every tool binds to an endpoint declared here.
The site&apos;s HTTP surface. API tools bind to endpoints declared here. DOM-only
packages retain an inert same-site block with <Code>endpoints: &#123;&#125;</Code>.
</Field>
<Field name="minEngine" type="integer ≥ 1 · required">
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{" "}
<Code>1</Code>.
<Code>2</Code>. DOM observations require level 2.
</Field>
<Field name="changelog" type="string, ≤2000 · optional">
What changed in this version. Shown to installed users deciding whether to move their
Expand Down Expand Up @@ -112,9 +113,10 @@ export default function PackageFormatPage() {
<Code>destructiveHint</Code>. No unknown keys, and a tool can&apos;t claim both{" "}
<Code>readOnlyHint</Code> and <Code>destructiveHint</Code>. Mark writes honestly.
</Field>
<Field name="execution" type='{ mode: "api", endpoint } · required'>
Binds the tool to a key in <Code>api.endpoints</Code>. <Code>mode</Code> is{" "}
<Code>&quot;api&quot;</Code>, the only mode there is.
<Field name="execution" type="API or DOM descriptor · required">
API mode binds the tool to a key in <Code>api.endpoints</Code>. 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 <Code>minEngine: 2</Code>.
</Field>
</div>
</Section>
Expand All @@ -134,7 +136,7 @@ export default function PackageFormatPage() {
Hacker News&apos;s Firebase read API.
</Field>
<Field name="endpoints" type="Record<string, ApiEndpoint> · required">
Named requests. Tools bind to these keys.
Named requests. API tools bind to these keys; DOM-only packages use an empty record.
</Field>
<Field name="auth" type="Record<string, ApiAuthSource> · optional">
Named token flows: fetch a page or endpoint, pull a token out of the response, resend it
Expand Down
Loading