Home/Tools/WebMCP Generator
Google Chrome WebMCP Standard (document.modelContext · Chromium 146+ Early Preview)

WebMCP Schema & Code Generator

Turn your SaaS actions and forms into native AI agent tools in under 60 seconds. Generate declarative HTML (<form toolname="...">) or spec-compliant imperative TypeScript registration snippets (inputSchema + annotations + AbortSignal).

100% Free Client-Side·Zero Backend Overhead·Chromium 146.0.7672.0+ Spec·HTML Form Auto-Parser
Current Browser WebMCP Status: Not active in this browser tab. Enable flag: chrome://flags/#enable-webmcp-testing
Chromium 146+ Early PreviewW3C Explainer
Instant load or paste your existing HTML form

Tool Configuration

#1
#2
#3
#4
#5
|
useWebMCPTool.ts (TypeScript)
"use client";

import { useEffect, useState } from "react";

/**
 * Chrome WebMCP Tool Registration Hook (React 18/19 StrictMode Safe)
 * Standard: document.modelContext (Chromium 146.0.7672.0+ Early Preview)
 * Lifecycle: AbortController + AbortSignal teardown prevents InvalidStateError
 * Generated by AIIndieKit WebMCP Schema Generator
 */
export function useGenerateAiVideoTool() {
  const [isRegistered, setIsRegistered] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;

    const controller = new AbortController();

    // 1. Feature detection: inspect document.modelContext (legacy navigator.modelContext fallback)
    const win = window as any;
    const mc = win.document?.modelContext || win.navigator?.modelContext;

    if (!mc || typeof mc.registerTool !== "function") {
      console.debug(
        "[WebMCP] document.modelContext is not supported. Requires Chromium 146.0.7672.0+ with chrome://flags/#enable-webmcp-testing"
      );
      return;
    }

    // 2. Define standard JSON Schema inputSchema
    const inputSchema = {
      type: "object",
      properties: {
      "image_a_url": {
              "type": "string",
              "description": "Starting keyframe image URL (PNG, JPG, WebP)"
      },
      "image_b_url": {
              "type": "string",
              "description": "Ending keyframe image URL for video morphing or interpolation"
      },
      "duration_seconds": {
              "type": "number",
              "description": "Target video duration in seconds (5 or 10)"
      },
      "aspect_ratio": {
              "type": "string",
              "description": "Output video aspect ratio (16:9, 9:16, or 1:1)"
      },
      "motion_prompt": {
              "type": "string",
              "description": "Optional description of camera movement or subject dynamics"
      }
},
      required: ["image_a_url","duration_seconds"],
      additionalProperties: false,
    };

    // 3. Register tool asynchronously with AbortSignal for StrictMode / HMR safety
    (async () => {
      try {
        await mc.registerTool(
          {
            name: "generate_ai_video",
            description: "Generate an animated video transition and camera motion between two uploaded keyframe images.",
            inputSchema,
            annotations: {
              readOnlyHint: false,
              consequentialHint: false,
              untrustedContentHint: true,
            },
            execute: async (args: Record<string, unknown>) => {
              console.log("[WebMCP Execute] Calling 'generate_ai_video' with:", args);

              // Dispatch request to your backend handler
              const response = await fetch("/api/generate-video", {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify(args),
              });

              if (!response.ok) {
                throw new Error(`Tool execution failed with status ${response.status}`);
              }

              const result = await response.json();
              return {
                content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
              };
            },
          },
          { signal: controller.signal }
        );

        if (!controller.signal.aborted) {
          setIsRegistered(true);
          console.log("[WebMCP] Tool 'generate_ai_video' registered successfully.");
        }
      } catch (err) {
        if (!controller.signal.aborted) {
          console.error("[WebMCP] Registration error:", err);
        }
      }
    })();

    // 4. Teardown via AbortSignal (and legacy unregisterTool fallback) on unmount
    return () => {
      controller.abort();
      if (typeof mc.unregisterTool === "function") {
        try {
          mc.unregisterTool("generate_ai_video");
        } catch (_) {}
      }
    };
  }, []);

  return { isRegistered };
}
Standard Implementation Protocol (inputSchema + annotations + AbortSignal)

This snippet uses the standardized inputSchema, annotations, and AbortSignal lifecycle teardown so React 18/19 StrictMode double-mounts never throw InvalidStateError.

AIIndieKit Community Compatibility Badge (Independent Directory Tag)

Show developers your SaaS exposes WebMCP / Agent-Ready Actions

Add the AIIndieKit community "WebMCP Ready" compatibility badge to your GitHub README or footer. Note: "WebMCP Ready" is an independent community directory classification maintained by AIIndieKit (not an official Google or W3C certification).

Community compatibility tag · Free to use

Everything You Need to Know About Chrome WebMCP

An engineering deep dive for indie founders and software architects.

1. What is WebMCP?

WebMCP (Web Model Context Protocol) is Chrome's standardized bridge connecting browser-side AI agents (such as Google Gemini, Chrome built-in AI, or autonomous assistants) directly with web application workflows. Instead of relying on fragile DOM scraping or vision-based click models, WebMCP lets you register clean, structured tools via document.modelContext.registerTool.

2. Declarative vs Imperative

Use Declarative HTML (<form toolname="...">) for static pages, WordPress, or traditional SSR forms with zero JavaScript. Use Imperative JavaScript (document.modelContext.registerTool) for interactive Next.js/React apps where client validation, custom headers, or async JSON dispatching is needed.

3. Safety Annotations (readOnlyHint & consequentialHint)

Autonomous agents evaluate the annotations object before taking action:
• annotations.readOnlyHint: true: Safe to call repeatedly during planning.
• annotations.consequentialHint: true: Triggers charges, deletes data, or modifies external state; agent halts and prompts the user for human authorization.

4. Why WebMCP Matters for Agent Interoperability

WebMCP schemas provide machine-readable action definitions so browser-side AI agents can understand and invoke website functions directly without brittle DOM scraping. Note: declaring WebMCP tools improves agent execution reliability, though it does not guarantee search engine ranking or AI citation boosts on its own.

How to Fix InvalidStateError Duplicate Tool Registration in Next.js (React 18/19 StrictMode)

When integrating document.modelContext.registerTool() inside a Next.js App Router Client Component, React 18/19 StrictMode and Fast Refresh (HMR) execute useEffect twice on mount. Calling registerTool a second time with an already-registered tool name throws DOMException: InvalidStateError: Failed to execute 'registerTool' on 'ModelContext': Tool already registered.

Verified Fix: Pass an AbortController signal ({ signal: controller.signal }) as the second argument to await mc.registerTool(toolDef, { signal: controller.signal }), nest schema fields inside inputSchema and safety hints inside annotations, and invoke controller.abort() inside your useEffect cleanup function.

Chrome WebMCP Exact Troubleshooting & Error Matrix

Symptom / Exact Console ErrorTechnical Root CauseVerified Resolution Step
DOMException: InvalidStateError: Failed to execute 'registerTool' on 'ModelContext'Duplicate tool name registered during React 18/19 StrictMode double-mount or Next.js HMR without aborting the previous registration.Pass { signal: controller.signal } to await mc.registerTool(def, { signal }) and call controller.abort() (plus optional mc.unregisterTool?.(name)) in useEffect cleanup.
TypeError: Cannot read properties of undefined (reading 'registerTool')Browser is below Chromium 146.0.7672.0+, WebMCP flag is disabled, or code executes during Next.js SSR where document is undefined.Wrap registration inside useEffect and guard with const mc = document.modelContext || navigator.modelContext. Enable chrome://flags/#enable-webmcp-testing in Chromium 146.0.7672.0+ (Canary/Dev).
TypeError / Schema Ignored: 'inputSchema' missing or top-level hints ignoredCode uses legacy parameters property or top-level readOnlyHint instead of the current W3C WebMCP specification structure.Rename parameters to inputSchema and wrap safety hints inside annotations: { readOnlyHint, consequentialHint, untrustedContentHint }.
navigator.modelContext is undefined in Chromium 146+ CanaryUpstream W3C explainer migrated the namespace from navigator.modelContext to document.modelContext to tie tool lifecycles to the active DOM document.Check document.modelContext first, falling back to navigator.modelContext only for older experimental builds.
Declarative <form toolname="..."> ignored by Agent InspectorForm inputs lack explicit name attributes or toolparamdescription metadata, preventing schema extraction.Ensure every <input> / <select> has both a name attribute and a descriptive toolparamdescription.
Agent halts before executing checkout or mutation toolExpected safety behavior when annotations.consequentialHint: true or toolconsequential="true" is set on state-mutating actions.Keep consequentialHint: true for billing/deletion routes so the browser prompts explicit human confirmation; set readOnlyHint: true only for idempotent queries.
AIIndieKit "WebMCP Ready" Directory Inclusion Criteria (Community Standard)Independent Classification

The WebMCP Ready tag in the AIIndieKit Tools Directory is an independent technical compatibility classification maintained by AIIndieKit—not an official certification or endorsement by Google Chrome or the W3C Web Machine Learning Community Group. To qualify for the tag, a listed developer tool must meet at least one of the following verifiable criteria:

  • Exposes browser-side tools via document.modelContext.registerTool() or declarative <form toolname="..."> attributes;
  • Provides first-class Model Context Protocol (MCP / WebMCP) tool definitions, schemas, or agent-ready webhook/API connectors;
  • Declares explicit safety annotations (readOnlyHint / consequentialHint) and structured JSON Schema inputs for autonomous agent execution.
Evidence, Sources & Verification Scope (4-Tier Policy)
Last Reviewed: 2026-10-31
1. Verified from Upstream Spec: API signatures (document.modelContext.registerTool, inputSchema, annotations, AbortSignal, and declarative form attributes) follow the W3C Draft Community Group Report & Google Chrome WebMCP Early Preview documentation (github.com/explainers-by-googlers/model-context).
2. Browser & Runtime Diagnostics: Local flag activation (chrome://flags/#enable-webmcp-testing) and live dogfooding registration on this page target Chromium 146.0.7672.0+ (Early Preview / Canary / Dev) builds.
3. Client-Side Privacy Guarantee: All schema generation and HTML <form> DOM parsing execute 100% in your local browser memory via native DOMParser; zero form payloads are transmitted to our servers.
4. Unverified Claims Policy: Because WebMCP is an evolving W3C/Chromium incubation standard, browser vendor flag names or method signatures may change across Canary releases. We do not claim guaranteed search ranking boosts from schema adoption alone.