Логотип Webmcp React

Webmcp React

Организация
agentcathq

React hooks for exposing your app's functionality as WebMCP tools - transport-agnostic, SSR-safe, Strict Mode safe, W3C spec-aligned

Издательagentcathq
Репозиторийwebmcp-react
ЯзыкTypeScript
Форки
9
Звёзды
75
Доступные инструменты
0
Тип транспортаstdio
ЛицензияMIT
Ссылки
  • Подключайте инструменты к рабочим процессам с ИИ

    Webmcp React предоставляет возможности MCP, доступные совместимым ИИ-клиентам и агентам.

  • Доступные инструменты: 0

    Ниже представлены доступные для вызова действия с названиями и описаниями, если сервер их предоставляет.

  • Готовая конфигурация для копирования

    Используйте примеры конфигурации, чтобы настроить этот сервер в предпочитаемом MCP-клиенте.

  • Показатели интереса к открытому проекту

    Звёзды: 75, форки: 9 — в связанном репозитории.

webmcp-react

React hooks for exposing typed tools on document.modelContext, aligned with the current WebMCP specification.

npm version npm downloads license CI TypeScript

  • Zod-first. Define inputs with Zod and get full type inference in handlers
  • JSON Schema support. Pass raw JSON Schema when you do not use Zod
  • Built-in polyfill. Installs a lightweight polyfill when native WebMCP is unavailable
  • SSR-safe. Works with Next.js, Remix, and other server-rendering frameworks
  • StrictMode-safe. Prevents duplicate registrations and orphaned tools
  • Spec-aligned. Tracks the WebMCP specification and native Chrome behavior release by release

Requirements

  • React 18 or later
  • Zod 3.25 or later, or Zod 4, as a peer dependency. Tools can also be defined with JSON Schema.

Install

bash
npm install webmcp-react zod

Quick start

Wrap your app in <WebMCPProvider> and register tools with useMcpTool:

tsx
import { WebMCPProvider, useMcpTool } from "webmcp-react";
import { z } from "zod";

function SearchTool() {
  useMcpTool({
    name: "search",
    description: "Search the catalog",
    input: z.object({ query: z.string() }),
    handler: async ({ query }) => ({
      content: [{ type: "text", text: `Results for: ${query}` }],
    }),
  });
  return null;
}

export default function App() {
  return (
    <WebMCPProvider name="my-app" version="1.0">
      <SearchTool />
    </WebMCPProvider>
  );
}

The tool is now registered on document.modelContext and any WebMCP-compatible agent can call it.

Agent skills

This repository ships agent skills that install webmcp-react and scaffold tools for you. Install them with the skills CLI:

bash
npx skills add agentcathq/webmcp-react

The skills work with Cursor, Claude Code, GitHub Copilot, Cline, and 18+ other agents.

Playground

Try it live: WebMCP Wordle Demo

The playground is a fully playable Wordle clone built on webmcp-react hooks. Tools register and unregister as the game moves through its phases (idle, playing, won, lost). You can make guesses with the keyboard or through an AI agent. A DevPanel shows the current tool state, and an easy-mode toggle enables a hint tool.

To play with an AI agent:

  • Codex. Open the demo in Codex and ask it to play. Codex discovers and calls the page's WebMCP tools directly.
  • Claude, Cursor, and other MCP clients. Install the WebMCP Bridge extension, open the demo in Chrome, and activate the extension for the page.

How it works

WebMCP is a proposed web standard from the W3C Web Machine Learning Community Group. It adds document.modelContext to the browser, an API that lets any page expose typed, callable tools to AI agents. Chrome ships the API in Early Preview.

This library provides the React bindings for that API. <WebMCPProvider> installs a polyfill when native support is absent, and each useMcpTool call registers a tool that agents can discover and execute.

How webmcp-react works

Connect to AI clients

Agents with built-in WebMCP browser support, such as Codex, discover and call tools directly from the page. Clients that cannot access document.modelContext directly, such as Claude Code and Cursor, connect through the WebMCP Bridge extension, which exposes your registered tools to any MCP client.

  1. Install the extension from the Chrome Web Store.
  2. Configure your MCP client. See the extension setup guide for details.

The extension will be deprecated when Chrome provides native bridging to desktop clients.

Usage

Execution state

useMcpTool returns reactive state you can use to build UI around tool execution:

tsx
function TranslateTool() {
  const { state, execute } = useMcpTool({
    name: "translate",
    description: "Translate text to Spanish",
    input: z.object({ text: z.string() }),
    handler: async ({ text }) => {
      const result = await translate(text, "es");
      return { content: [{ type: "text", text: result }] };
    },
  });

  return (
    <div>
      <button onClick={() => execute({ text: "Hello" })} disabled={state.isExecuting}>
        {state.isExecuting ? "Translating..." : "Translate"}
      </button>
      {state.lastResult && <p>{state.lastResult.content[0].text}</p>}
      {state.error && <p className="error">{state.error.message}</p>}
    </div>
  );
}

Cancellation

Each execution receives its own AbortSignal. Pass it to fetch and other cancellable work. Chrome 153+ aborts the signal when the agent cancels the call. On older browsers the library substitutes a never-aborting signal, so the second argument is always safe to use:

tsx
useMcpTool({
  name: "fetch_report",
  description: "Fetch a report by ID",
  input: z.object({ id: z.string() }),
  handler: async ({ id }, { signal }) => {
    const res = await fetch(`/api/reports/${id}`, { signal });
    return { content: [{ type: "text", text: await res.text() }] };
  },
});

Title and annotations

Give a tool a human-friendly display title, and describe its behavior to agents with annotations. The current WebMCP specification defines two annotations: readOnlyHint and untrustedContentHint.

tsx
useMcpTool({
  name: "search_users",
  title: "Search users",
  description: "Find users by name or email",
  input: z.object({ query: z.string() }),
  annotations: {
    readOnlyHint: true,
  },
  handler: async ({ query }) => { /* ... */ },
});

Dynamic tools

Tools register on mount and unregister on unmount. Render them conditionally like any React component:

tsx
function App({ user }) {
  return (
    <WebMCPProvider name="app" version="1.0">
      <PublicTools />
      {user.isAdmin && <AdminTools />}
    </WebMCPProvider>
  );
}

Callbacks

Run side effects on success or failure:

tsx
useMcpTool({
  name: "checkout",
  description: "Complete a purchase",
  input: z.object({ cartId: z.string() }),
  handler: async ({ cartId }) => { /* ... */ },
  onSuccess: (result) => analytics.track("checkout_complete"),
  onError: (error) => toast.error(error.message),
});

JSON Schema

Pass inputSchema directly to define a tool without Zod:

tsx
useMcpTool({
  name: "calculate",
  description: "Basic arithmetic",
  inputSchema: {
    type: "object",
    properties: {
      a: { type: "number" },
      b: { type: "number" },
      op: { type: "string", enum: ["add", "subtract", "multiply", "divide"] },
    },
    required: ["a", "b", "op"],
  },
  handler: async (args) => {
    const { a, b, op } = args as { a: number; b: number; op: string };
    const result = { add: a + b, subtract: a - b, multiply: a * b, divide: a / b }[op];
    return { content: [{ type: "text", text: String(result) }] };
  },
});

SSR

The library works with Next.js, Remix, and any server-rendering framework. The build includes a "use client" banner, so no extra configuration is needed.

Browser support

EnvironmentBehavior
Chrome with native document.modelContextThe library uses the native API. The polyfill is not installed.
All other browsersThe library installs its polyfill, which implements the registration and consumer APIs.

The polyfill follows native Chrome behavior. See the polyfill section of the API reference for the exact Chrome versions each behavior tracks.

Versioning and stability

webmcp-react follows Semantic Versioning. Breaking changes to the public API bump the major version. Every release is documented in the changelog, including the WebMCP specification and Chrome changes it tracks.

outputSchema and structuredContent are documented library extensions to the WebMCP specification. They are part of the public API and follow the same versioning policy.

API

See the full API reference.

Contributing

Bug reports, feature requests, and pull requests are welcome. Read the contributing guide before you open a pull request. This project follows the Contributor Covenant Code of Conduct.

License

MIT

Используйте MCP Webmcp React с разными ИИ-моделями

TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому после подключения Webmcp React вы можете использовать их с разными моделями ИИ в TypingMind, не настраивая подключение отдельно для каждой модели. Эта интеграция MCP работает локально на вашем устройстве через коннектор MCP TypingMind.

Руководство по настройке локального коннектора

Выберите этот способ, если серверу MCP нужен доступ к локальным файлам, приложениям или закрытым ресурсам на вашем компьютере.

1

Откройте настройки MCP

В TypingMind откройте «Настройки», затем «Расширенные настройки», перейдите в раздел «Протокол контекста модели» и выберите «Настроить коннектор».

  1. Откройте TypingMind в браузере.
  2. Нажмите значок настроек.
  3. Перейдите в «Расширенные настройки».
  4. Откройте раздел «Протокол контекста модели».
  5. Нажмите «Настроить коннектор» и выберите «Это устройство».
Экран настройки коннектора MCP в TypingMind с выбранным вариантом «Это устройство»
2

Выполните команду коннектора

Выберите «Это устройство», скопируйте команду из TypingMind и выполните её в терминале. Не останавливайте процесс, пока используете MCP.

  1. Скопируйте команду настройки, показанную в TypingMind.
  2. Откройте «Терминал» в macOS или Windows Terminal в Windows.
  3. Вставьте и выполните команду.
  4. Подтвердите установку пакета, если терминал запросит разрешение продолжить.
  5. Не закрывайте окно терминала и не останавливайте процесс, пока используете инструменты MCP.
3

Добавьте Webmcp React как сервер

Когда статус коннектора сменится на «Готов», нажмите «Изменить серверы» и вставьте конфигурацию сервера MCP.

  1. Дождитесь, пока статус коннектора сменится на «Готов».
  2. Нажмите «Изменить серверы».
  3. Вставьте конфигурацию сервера MCP для Webmcp React.
  4. Сохраните список серверов.
  5. Обновите статус, если хотите убедиться, что коннектор по-прежнему готов к работе.
Настройки MCP в TypingMind с активным сервером и кнопкой «Изменить серверы»
{
  "mcpServers": {
    "webmcp-react": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Используйте подключение с разными моделями

Сохраните список серверов, откройте раздел «Плагины», включите инструменты MCP для Webmcp React, затем выберите любую поддерживаемую модель ИИ в TypingMind и используйте инструменты в чате или назначьте их ИИ-агенту.

  1. Откройте страницу «Плагины» в TypingMind.
  2. Включите инструменты MCP для Webmcp React.
  3. Начните чат и выберите модель ИИ, которую хотите использовать.
  4. Используйте инструменты MCP в чате или назначьте их ИИ-агенту.
  5. При необходимости переключайтесь на другую модель ИИ без повторного подключения MCP.
Чат TypingMind с включёнными инструментами MCP и выбранной ИИ-моделью
Можете помочь мне с этой задачей с помощью Webmcp React?
Webmcp React
Конечно. Я всё прочитал.
Вот что я нашёл с помощью Webmcp React.

Часто задаваемые вопросы

Для чего используется сервер MCP Webmcp React?

Webmcp React — это сервер MCP, который позволяет совместимым ИИ-клиентам подключаться к внешним инструментам и получать контекст. В TypingMind достаточно один раз добавить этот сервер MCP, чтобы его инструменты стали доступны в вашем рабочем пространстве с ИИ.

Можно ли использовать сервер MCP Webmcp React с несколькими ИИ-моделями в TypingMind?

Да. TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому вы можете использовать Webmcp React с разными ИИ-моделями, например Claude, ChatGPT, Gemini или другими моделями, настроенными в TypingMind, без отдельной настройки сервера MCP для каждой модели.

Зачем использовать MCP Webmcp React с TypingMind?

TypingMind — один из лучших интерфейсов для чата с LLM: он объединяет разные ИИ-модели, промпты, плагины, ИИ-агентов, ключи API и инструменты MCP в одном рабочем пространстве. Подключив Webmcp React, вы сможете использовать его инструменты MCP с предпочитаемыми моделями, сохраняя удобную организацию работы с чатами в TypingMind.

Как подключить сервер MCP Webmcp React к TypingMind?

Webmcp React работает через локальный коннектор MCP TypingMind. Этот вариант лучше всего подходит, когда серверу MCP нужен доступ к локальным файлам, настольным приложениям, инструментам командной строки или закрытым ресурсам на вашем компьютере.

Какие инструменты предоставляет сервер MCP Webmcp React в TypingMind?

Webmcp React предоставляет возможности MCP, которые можно включить на странице «Плагины» в TypingMind и использовать в чате или назначить ИИ-агентам.

Нужно ли передавать TypingMind свои ключи API для использования сервера MCP Webmcp React?

Нет. TypingMind ориентирован прежде всего на локальную работу и позволяет вам контролировать выбор провайдеров моделей, ключи API, промпты и конфигурацию MCP. Если Webmcp React требует аутентификации, при создании подключения добавьте необходимые заголовки, настройки OAuth или локальную конфигурацию для этого сервера MCP.

Похожие серверы MCP

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇