跳到正文
DEV Community· Raghav Agarwal·· 5 小時前AI 評分56

WebMCP 實踐:以具型別的 document.modelContext 工具取代脆弱的 DOM 抓取

WebMCP in Practice: Replacing Brittle DOM Scraping With Typed document.modelContext Tools

AI 導讀

文章以實作方式説明,WebMCP 可讓網頁透過 document.modelContext 在瀏覽器內提供經結構描述驗證的工具,作為以截圖或 DOM 解析驅動智能體的替代方式。

正文

Most browser agents today still interact with web apps the hard way: capture a screenshot or parse a 15,000-node DOM, guess which <div> acts like a button, and hope a CSS refactor doesn't break the flow tomorrow.

The WebMCP (Web Model Context Protocol) Community Group draft explores a cleaner alternative: letting web pages expose explicit, schema-validated tools directly in the browser via document.modelContext.

Note on specification maturity: As reviewed against the WebMCP Community Group draft, WebMCP is experimental and not a W3C Standard. Chrome implementations and early trials may expose different surfaces, and native browser-agent interoperability across browsers is still evolving.

In this first part of the Building for the Agentic Web series, let's walk through concrete, zero-dependency JavaScript patterns for registering, discovering, validating, and tearing down WebMCP tools safely.

GitHub logo raghav453 / webmcp-action-examples

Runnable WebMCP JavaScript examples: search, availability and human-reviewed drafts. Validated handlers, cleanup and automated negative tests.

WebMCP JavaScript action examples

Four runnable examples with shared, validated handlers: catalogue search, documentation lookup, fictional availability and a human-reviewed local draft. No framework, account or backend required.

Try the live examples · Copy the handlers · Registration and cleanup · Verification

Runnable WebMCP JavaScript examples

Try a known result first

Example Live task Expected result
Catalogue Search lamp under 50 One item: lamp-01
Validation Load an invalid price Reject maxPrice: "50"
Documentation Search cancellation notes One registration/cleanup note
Availability Check the north fixture available: true; no booking
Local review Prepare and refuse a draft status: "canceled", sent: false

Manual controls work in ordinary browsers. Opt into the labelled polyfill 0.2.0 experiment to try actual discovery/execution in that library. Native browser-agent interoperability remains unverified.

Run locally

Requires Node.js 20+; no npm install or runtime network dependencies.

npm test
npm start

Open http://127.0.0.1:4173/?example=catalog. Other examples: ?example=docs, ?example=availability, ?example=request. Source handlers are in…


1. WebMCP vs. Server-Side MCP

A common misconception is conflating server-side MCP with WebMCP:

  • Server-side MCP connects an LLM host (desktop app, IDE, backend agent) to remote APIs, databases, or local tools over stdio/HTTP.
  • WebMCP exposes client-side actions inside an active browser page, scoped to the user's current origin, session, and UI state.

For a deeper conceptual comparison, see WebMCP vs. MCP.


2. Detecting the Draft Context & Managing Lifecycle With AbortSignal

Never assume document.modelContext is present, and never silently adapt unverified surfaces without checking the required methods (registerTool, getTools, executeTool).

Here is the explicit detection and AbortController teardown pattern used in registration.mjs:

export function registrationContext(doc = globalThis.document) {
  const context = doc?.modelContext;
  return context && typeof context.registerTool === "function" ? context : null;
}

export function draftContext(doc = globalThis.document) {
  const context = registrationContext(doc);
  return context &&
    typeof context.getTools === "function" &&
    typeof context.executeTool === "function"
    ? context
    : null;
}

export async function registerTools(context, tools) {
  const lifecycle = new AbortController();
  try {
    for (const tool of tools) {
      await context.registerTool(tool, { signal: lifecycle.signal });
    }
  } catch (error) {
    // Roll back partial registrations if any tool fails
    lifecycle.abort();
    throw error;
  }
  return lifecycle;
}

Why does AbortController matter? In single-page apps (SPAs), routes mount and unmount continuously. Calling lifecycle.abort() on route teardown or logout ensures obsolete tools don't stay registered after the UI context is gone.


3. Preserving Opaque Tool Identity During Invocation

When invoking a discovered tool, look it up from getTools() and verify its origin before calling executeTool—never reconstruct a mock object and pass it in:

export async function invoke(
  context,
  name,
  input,
  { signal, origin = globalThis.location?.origin } = {}
) {
  const found = (await context.getTools()).find(
    (tool) => tool.name === name && tool.origin === origin
  );
  if (!found) {
    throw new Error("Tool is not discovered in the expected origin: " + name);
  }
  const raw = await context.executeTool(found, input, { signal });
  return { raw, origin: found.origin, name: found.name };
}

4. Validate Inputs Inside Every Handler (Treat Schemas as Contracts, Not Firewalls)

Even when a tool declares an inputSchema with additionalProperties: false, always validate inside execute():

export function validate(input, allowed) {
  if (!input || typeof input !== "object" || Array.isArray(input)) {
    throw new TypeError("Input must be an object");
  }
  for (const key of Object.keys(input)) {
    if (!allowed.includes(key)) {
      throw new TypeError("Unknown input field: " + key);
    }
  }
}

export function checkAbort(signal) {
  if (signal?.aborted) {
    throw signal.reason || new DOMException("Canceled", "AbortError");
  }
}

And for any action that modifies state (a draft, order, or request), mark annotations: { consequentialHint: true } and gate execution behind an explicit human confirmation step—remembering that consequentialHint is a UX hint, not server-side security enforcement.


Try the Live Browser Examples

You can test these four handlers (catalogue search, documentation lookup, availability check, and a human-reviewed local draft) right in the browser with no backend or account required:

In Part 2 of this series, we'll break down the WebMCP Security Checklist: how to prevent prompt injection, enforce server-side authorization, and wire atomic idempotency for consequential actions.

來源:DEV Community · dev.to