← 返回
AI智能 中文

WebMCP

WebMCP - Enable AI agents to interact with your web applications through structured tools. Implements the WebMCP standard for Next.js/React apps with tool re...
WebMCP - 赋予AI代理通过结构化工具与Web应用交互的能力。为Next.js/React应用实现WebMCP标准,支持工具复用。
slemo54
AI智能 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 1,387
下载
💾 26
安装
1
版本
#latest

概述

WebMCP

Enable AI agents to interact with your web applications through structured tools. WebMCP provides a clean, self-documenting interface between AI agents and your web app.

What is WebMCP?

WebMCP is a web standard that gives AI agents an explicit, structured contract for interacting with websites. Instead of screen-scraping or brittle DOM selectors, a WebMCP-enabled page exposes tools — each with:

  • A name
  • A JSON Schema describing inputs and outputs
  • An executable function
  • Optional annotations (read-only hints, etc.)

Quick Start

# Initialize WebMCP in your Next.js project
webmcp init

# Add a new tool
webmcp add-tool searchProducts

# Generate TypeScript types
webmcp generate-types

Core Concepts

1. Tool Definition

const searchTool = {
  name: "searchProducts",
  description: "Search for products by query",
  inputSchema: {
    type: "object",
    properties: {
      query: { type: "string", description: "Search query" }
    },
    required: ["query"]
  },
  outputSchema: { type: "string" },
  execute: async (params) => {
    // Implementation
  },
  annotations: {
    readOnlyHint: "true"
  }
};

2. Contextual Tool Loading

Tools are registered when components mount and unregistered when they unmount:

useEffect(() => {
  registerSearchTools();  // Tools appear to agent
  return () => {
    unregisterSearchTools();  // Tools disappear
  };
}, []);

3. Event Bridge Pattern

Tools communicate with React through CustomEvents:

Agent → execute() → dispatch CustomEvent → React updates → signal completion → Agent receives result

Architecture

┌─────────────────────────────────────────┐
│  Browser (navigator.modelContext)       │
│                                         │
│  ┌───────────┐    registers/     ┌────┐ │
│  │ AI Agent  │◄──unregisters────│web │ │
│  │ (Claude)  │    tools         │mcp│ │
│  │           │                  │.ts│ │
│  │ calls─────┼─────────────────►│    │ │
│  └───────────┘                  └──┬─┘ │
│                                    │    │
│                         CustomEvent│    │
│                         dispatch   │    │
│                                    ▼    │
│  ┌──────────────────────────────────┐   │
│  │ React Component Tree             │   │
│  │                                  │   │
│  │ ┌──────────┐   ┌──────────┐     │   │
│  │ │/products │   │  /cart   │     │   │
│  │ │useEffect:│   │useEffect:│     │   │
│  │ │ register │   │ register │     │   │
│  │ │ search   │   │  cart    │     │   │
│  │ │  tools   │   │  tools   │     │   │
│  │ └──────────┘   └──────────┘     │   │
│  └──────────────────────────────────┘   │
└─────────────────────────────────────────┘

Installation

# In your Next.js project
npx webmcp init

# Or install globally
npm install -g @webmcp/cli
webmcp init

Usage

1. Initialize WebMCP

webmcp init

This creates:

  • lib/webmcp.ts - Core implementation
  • hooks/useWebMCP.ts - React hook
  • components/WebMCPProvider.tsx - Provider component

2. Define Tools

// lib/webmcp.ts
export const searchProductsTool = {
  name: "searchProducts",
  description: "Search for products",
  execute: async (params) => {
    return dispatchAndWait("searchProducts", params, "Search completed");
  },
  inputSchema: {
    type: "object",
    properties: {
      query: { type: "string" }
    },
    required: ["query"]
  },
  annotations: { readOnlyHint: "true" }
};

3. Register in Components

// app/products/page.tsx
"use client";

import { useEffect, useState } from "react";
import { registerProductTools, unregisterProductTools } from "@/lib/webmcp";

export default function ProductsPage() {
  const [results, setResults] = useState([]);
  const [completedRequestId, setCompletedRequestId] = useState(null);

  // Signal completion after render
  useEffect(() => {
    if (completedRequestId) {
      window.dispatchEvent(
        new CustomEvent(`tool-completion-${completedRequestId}`)
      );
      setCompletedRequestId(null);
    }
  }, [completedRequestId]);

  // Register tools + listen for events
  useEffect(() => {
    const handleSearch = (event: CustomEvent) => {
      const { requestId, query } = event.detail;
      // Perform search
      setResults(searchProducts(query));
      if (requestId) setCompletedRequestId(requestId);
    };

    window.addEventListener("searchProducts", handleSearch);
    registerProductTools();

    return () => {
      window.removeEventListener("searchProducts", handleSearch);
      unregisterProductTools();
    };
  }, []);

  return <div>{/* Product UI */}</div>;
}

CLI Commands

CommandDescription
----------------------
webmcp initInitialize WebMCP in project
webmcp add-tool Add new tool definition
webmcp generate-typesGenerate TypeScript types
webmcp example Create example project

Tool Types

Read-Only Tools

{
  name: "viewCart",
  description: "View cart contents",
  annotations: { readOnlyHint: "true" }
}

Mutating Tools

{
  name: "addToCart",
  description: "Add item to cart",
  annotations: { readOnlyHint: "false" }
}

Tools with Parameters

{
  name: "setFilters",
  inputSchema: {
    type: "object",
    properties: {
      category: { type: "string", enum: ["electronics", "clothing"] },
      maxPrice: { type: "number" }
    }
  }
}

Examples

E-Commerce

webmcp example e-commerce

Features:

  • Product search
  • Cart management
  • Checkout flow
  • Order tracking

Dashboard

webmcp example dashboard

Features:

  • Widget interactions
  • Data filtering
  • Export functionality
  • Real-time updates

Blog

webmcp example blog

Features:

  • Article search
  • Comment posting
  • Category filtering
  • Related articles

Best Practices

1. Tool Naming

Use camelCase verbs that describe the action:

  • searchProducts
  • addToCart
  • updateProfile
  • product_search
  • handleCart

2. Descriptions

Write clear, specific descriptions:

  • ✅ "Search for products by name or category"
  • ❌ "Search stuff"

3. Schema Completeness

Always include descriptions for parameters:

properties: {
  query: {
    type: "string",
    description: "The search query to find products by name or category"
  }
}

4. Contextual Loading

Register tools only when relevant:

// Product page
useEffect(() => {
  registerProductTools();
  return () => unregisterProductTools();
}, []);

// Cart page  
useEffect(() => {
  registerCartTools();
  return () => unregisterCartTools();
}, []);

5. Error Handling

Always handle timeouts and errors:

async function execute(params) {
  try {
    return await dispatchAndWait("action", params, "Success", 5000);
  } catch (error) {
    return `Error: ${error.message}`;
  }
}

Browser Support

WebMCP requires browsers that support:

  • CustomEvent API
  • navigator.modelContext (proposed standard)

For development, use the WebMCP polyfill:

import "@webmcp/polyfill";

Resources

Integration with Other Skills

  • ai-labs-builder: Use WebMCP to make AI apps agent-accessible
  • mcp-workflow: Combine with workflow automation
  • gcc-context: Version control your tool definitions

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-03-29 07:16 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

ai-intelligence

self-improving agent

pskoett
捕获经验教训、错误和纠正,以实现持续改进。使用时机:(1)命令或操作意外失败;(2)用户纠正……
★ 4,055 📥 795,905
ai-intelligence

Self-Improving + Proactive Agent

ivangdavila
自我反思+自我批评+自我学习+自组织记忆。智能体评估自身工作、发现错误并持续改进。
★ 1,349 📥 317,697
productivity

MCP Workflow

slemo54
基于Jason Zhou启发的MCP(模型上下文协议)模式实现工作流自动化
★ 1 📥 1,512