Логотип @mcp-fe/react-tools

@mcp-fe/react-tools

Организация
mcp-fe

Give AI agents eyes and hands inside your live React app — no browser extension required

Издательmcp-fe
Репозиторийmcp-fe
ЯзыкTypeScript
Форки
2
Звёзды
15
Доступные инструменты
0
Тип транспортаstdio
Категории
ЛицензияApache-2.0
Ссылки
  • Подключайте инструменты к рабочим процессам с ИИ

    @mcp-fe/react-tools предоставляет возможности MCP, доступные совместимым ИИ-клиентам и агентам.

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

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

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

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

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

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

MCP-FE — Frontend Edge for AI Agents

npm License WebMCP Status

Give AI agents eyes and hands inside your live React app.

MCP-FE turns your browser into an active MCP node — letting agents like Claude or Cursor query live state, read user context, and trigger actions directly inside your frontend. No browser extension required.

tsx
// One hook. Claude can now see and control this component.
useMCPTool({
  name: 'get_cart_items',
  description: 'Returns current items in the shopping cart',
  inputSchema: { type: 'object', properties: {} },
  handler: async () => ({
    content: [{ type: 'text', text: JSON.stringify(cartItems) }],
  }),
});
// ✅ Available to remote agents via MCP proxy
// ✅ Available to browser's agent via navigator.modelContext (if supported)

🌐 Try the Live Demo — no setup required  ·  🎬 Watch demo  ·  🌍 mcp-fe.ai  ·  📦 pnpm add @mcp-fe/mcp-worker


Why MCP-FE?

AI agents are often runtime-blind: they can read your code, but they can't see the current DOM, the state of a Redux/Zustand store, or the exact interaction sequence that led to an error.

MCP-FE exposes the browser runtime as a first-class MCP Server so that context is retrievable on demand via tool calls.

What this enables

  • In-app AI copilot — give users an AI assistant that truly understands your application. Because tools return structured component data rather than pixels or DOM nodes, the agent works reliably even as your UI evolves. "Book the cheapest Tuesday flight" or "fill the form with my usual details" — the agent reads live state and triggers actions directly, no browser extension required.

  • Support with full context — when a user opens a support chat, the agent immediately queries get_form_state or get_validation_errors instead of asking for screenshots. It sees exactly what the user sees — active errors, current field values, where they are in a flow — and resolves issues in seconds rather than back-and-forth exchanges.

  • Guided complex workflows — in tax forms, insurance claims, or ERP systems, users often get lost in deep menus and multi-step flows. The agent knows exactly which step they're on, what's already filled, and what's missing — and can navigate or configure the UI on their behalf instead of pointing them to documentation.

  • Ready for the browser AI era — as AI browser extensions and built-in browser agents become mainstream, apps with MCP-FE are already compatible. Via the WebMCP adapter, the browser's native agent gets structured semantic tools through navigator.modelContext instead of scraping the DOM. One registerTool() call covers both today's remote agents and tomorrow's browser-native ones.


Table of Contents


Quick Start (Local Live Demo)

This monorepo includes a small demo frontend app and the MCP proxy. Run the commands below to start a local live demo on your machine.

  1. Install dependencies
bash
pnpm install
  1. Start the demo app + MCP Proxy
bash
pnpm start
  1. Open the demo frontend

Navigate to http://localhost:4200 (or the port shown in your terminal). The browser worker will automatically register and connect.

  1. Connect an AI agent

Point your MCP-compatible agent to:

  • MCP endpoint (HTTP): http://localhost:3001/mcp

Note: the example app connects the worker to the proxy via WebSocket (e.g., ws://localhost:3001).


How It Works

Runtime flow — how a tool call travels from agent to browser and back.

Traditional MCP integrations are backend-centric. Frontends usually push events continuously, whether anyone needs them or not.

MCP-FE inverts the flow:

  • Pull, not push: the frontend does not stream context by default.
  • Worker-based edge: a browser SharedWorker (preferred) or ServiceWorker stores event history (IndexedDB) and coordinates tool calls.
  • Proxy for remote agents: a Node.js proxy maintains a WebSocket connection to the worker and exposes MCP tools to agents.
  • Dynamic tools: register tools from application code; handlers run in the main thread with controlled access to state/DOM/imports.

Key Concepts

MCP Workers: SharedWorker vs ServiceWorker

  • SharedWorker (preferred):

    • One shared instance available to all same-origin windows/iframes.
    • Good for multi-tab apps and when you want a single MCP edge connection per browser.
  • ServiceWorker (fallback):

    • Runs in background, lifecycle managed by the browser.
    • Useful when SharedWorker is not supported.

WorkerClient prefers SharedWorker and automatically falls back to ServiceWorker. It also supports passing an explicit ServiceWorkerRegistration to use a previously registered service worker.

Worker as an MCP Edge Server

The Shared/Service Worker acts as a lightweight edge node that enables you to:

  • Collect UI-level event history (navigation, interactions, errors)
  • Store events in IndexedDB for later retrieval
  • Expose data and actions via MCP tools
  • Maintain a persistent WebSocket connection to the proxy
  • Register custom tools dynamically with handlers running in the main thread (full browser API access)

Server-Driven Pull Model (Tool Calls)

The MCP worker never sends context proactively to the backend. Context is shared only when an AI agent explicitly requests it by calling a tool.


WebMCP — Native Browser Integration

MCP-FE includes built-in support for the WebMCP specification (navigator.modelContext), an emerging W3C standard that allows web pages to register MCP tools directly with the browser. This means your tools are discoverable not only by remote AI agents (via the proxy), but also by browser-native agents, extensions, and assistive technologies.

How it fits together

Your App ──→ workerClient.registerTool('my-tool', ...)
                │
                ├── ① Worker transport ──→ Proxy ──→ Remote AI agents (Claude, Cursor, ...)
                │
                └── ② WebMCP adapter ──→ navigator.modelContext.registerTool()
                                              └──→ Browser's built-in agent / extensions

One registerTool() call → two delivery channels. Your tool handlers are written once and automatically served to both remote agents (via WebSocket + MCP proxy) and the browser's native agent system (via navigator.modelContext).

Enabled by default

WebMCP is auto-detected — if the browser supports navigator.modelContext, tools are registered there automatically. No configuration needed:

ts
// This single call registers the tool in BOTH systems:
await workerClient.registerTool(
  'get_cart_items',
  'Returns the current shopping cart contents',
  { type: 'object', properties: {} },
  async () => ({
    content: [{ type: 'text', text: JSON.stringify(getCart()) }],
  }),
);
// ✅ Available to remote agents via MCP proxy
// ✅ Available to browser's agent via navigator.modelContext (if supported)

To explicitly disable WebMCP:

ts
await workerClient.init({
  backendWsUrl: 'ws://localhost:3001',
  enableWebMcp: false,  // opt-out
});

Delivery channels

ChannelAgent typeTransportRequires proxy?
Worker + ProxyRemote AI agents (Claude, Cursor, etc.)WebSocket → HTTP/SSEYes
WebMCPBrowser's built-in agent, extensions, assistive technavigator.modelContext (in-process)No

With WebMCP support, your frontend tools work even without a running proxy — the browser agent can invoke them directly. And when the proxy is running, remote agents get access too. Both channels coexist seamlessly.

📖 For implementation details, see libs/mcp-worker/docs/native-webmcp.md


🛡️ Security by Design

Unlike traditional analytics or logging tools that stream data to third-party servers, MCP-FE is passive and restrictive:

  • Explicit Exposure Only: The AI agent has zero "magic" access to your app. It can only see data or trigger actions that you explicitly expose via registerTool or useMCPTool.
  • Zero-Stream Policy: No data is ever pushed automatically. Context transfer only happens when an AI agent triggers a specific tool call.
  • Local Execution: Tool handlers run in your application's context, allowing you to implement custom authorization, filtering, or scrubbing before returning data to the agent.
  • Privacy First: Sensitive fields (PII, passwords, tokens) never leave the client unless the developer intentionally includes them in a tool's return payload.

🏗️ Architecture

Component overview — the three layers that make up MCP-FE.

The MCP-FE architecture is built on three core layers designed to keep the main application thread responsive while providing a persistent link to AI agents.

1. The Proxy Server (Node.js)

The Proxy acts as the gateway. It speaks the standard MCP Protocol towards the AI agent (via HTTP/SSE) and maintains a persistent WebSocket connection to the browser.

  • Role: Bridges the gap between the internet and the user's local browser session.
  • Security: Handles Bearer token authentication to ensure only authorized agents can talk to the worker.

2. The MCP Worker (SharedWorker / ServiceWorker)

This is the "Brain" on the Frontend Edge. It runs in its own thread, meaning it doesn't slow down your UI.

  • Event Logging: Automatically captures interactions and errors into IndexedDB.
  • Routing: When a tool call comes from the Agent, the Worker routes it to the correct tab or the Main Thread.
  • Resilience: Implements a Ping-Pong mechanism to keep the WebSocket alive even when the user isn't actively interacting with the page.

3. The Main Thread (Your App)

This is where your React/Vue/JS code lives.

  • Dynamic Tools: Using hooks like useMCPTool, your components register handlers that have direct access to the live DOM, State, and LocalStorage.
  • Zero-Push: It only executes logic and sends data when the Worker explicitly asks for it (the Pull Model).

Packages

MCP-FE is delivered as a set of packages in this monorepo and can be consumed directly from your applications. For install instructions, APIs, and framework-specific examples, use the package READMEs:

PackageWhat it's forDocs
@mcp-fe/mcp-workerCore: worker client + worker scripts + transport + dynamic tool registration./libs/mcp-worker/README.md
@mcp-fe/event-trackerCore (optional): framework-agnostic event tracking (navigation/interactions/errors)./libs/event-tracker/README.md
@mcp-fe/react-event-trackerReact (optional): drop-in hooks for automatic navigation/click/input tracking./libs/react-event-tracker/README.md
@mcp-fe/react-toolsReact (optional): hooks for registering tools with component lifecycle management./libs/react-tools/README.md
mcp-server (Docker image)Proxy: Node.js MCP server that bridges remote agents ↔ browser worker./apps/mcp-server/README.md

Using MCP-FE in Your App

You can adopt MCP-FE incrementally. The smallest useful setup is:

  1. Run the proxy (mcp-server) somewhere reachable by your users' browsers.
  2. Initialize the worker client in your app and point it at the proxy.
  3. Optionally add event tracking and/or custom tools.

Minimal frontend setup:

bash
pnpm add @mcp-fe/mcp-worker
ts
import { workerClient } from '@mcp-fe/mcp-worker';

await workerClient.init({
  backendWsUrl: 'ws://YOUR_PROXY_HOST:3001',
  // Optional: custom paths for worker scripts (useful for cache-busting)
  sharedWorkerUrl: '/mcp-shared-worker.js',
  serviceWorkerUrl: '/mcp-service-worker.js',
});

Typical Integration Paths

  • Minimal (custom tools only): @mcp-fe/mcp-worker + your own registerTool(...) handlers.
  • Observability (events + queries): add @mcp-fe/event-tracker or @mcp-fe/react-event-tracker.
  • React-first: @mcp-fe/mcp-worker + @mcp-fe/react-tools + @mcp-fe/react-event-tracker.

Minimal Example (Worker + Tool)

ts
import { workerClient } from '@mcp-fe/mcp-worker';

await workerClient.init({
  backendWsUrl: 'ws://localhost:3001',
});

await workerClient.registerTool(
  'get_user_data',
  'Get current user information',
  { type: 'object', properties: {} },
  async () => ({
    content: [{ type: 'text', text: JSON.stringify(getCurrentUser()) }],
  })
);

Structured Output (outputSchema)

Tools can optionally declare an outputSchema — a JSON Schema describing the shape of the returned data. When provided, the agent receives strongly-typed, structured output instead of raw text, which makes it easier to consume tool results programmatically.

ts
await workerClient.registerTool(
  'get_cart_summary',
  'Get current cart contents with totals',
  { type: 'object', properties: {} },
  async () => ({
    content: [{ type: 'text', text: JSON.stringify(getCartSummary()) }],
  }),
  {
    outputSchema: {
      type: 'object',
      properties: {
        items: { type: 'array' },
        total: { type: 'number' },
        currency: { type: 'string' },
      },
      required: ['items', 'total'],
    },
  }
);

With useMCPTool (React):

tsx
useMCPTool({
  name: 'get_cart_summary',
  description: 'Get current cart contents with totals',
  inputSchema: { type: 'object', properties: {} },
  outputSchema: {
    type: 'object',
    properties: {
      items: { type: 'array' },
      total: { type: 'number' },
      currency: { type: 'string' },
    },
    required: ['items', 'total'],
  },
  handler: async () => ({
    content: [{ type: 'text', text: JSON.stringify(getCartSummary()) }],
  }),
});

🚧 Security Roadmap & Known Limitations

We are actively working on hardening the proxy and worker. Contributions and PRs are highly welcome!

Resolved ✅

  • Strict JWT Verification: The Node proxy used a "mock" decoded JWT without verifying the signature. → Implemented jwtVerify() with HS256 (local mode) and JWKS-based RS256 validation (Keycloak mode).

  • Secure Token Transport: WebSockets initiated using ?token=... in the URL query string. → Migrated to an initial payload handshake: client sends { type: "AUTH", token } as the first WebSocket message.

Open

  • Privacy-First Event Tracking: Default trackInput() hook captures raw input values. Roadmap: track length/hashes only, ignore type="password", introduce opt-in allowlist.

  • WebSocket Origin Validation: Stricter origin allowlist enforcement beyond the current CORS_ORIGIN configuration.

  • Data Retention Limits (client-side): SESSION_TTL_MINUTES is configurable on the server, but the local IndexedDB has no automatic TTL yet.


⚠️ Project Status: Experimental (PoC)

This project is currently a Proof of Concept. While the architecture is stable and demonstrates the power of MCP-FE, it is not yet intended for high-stakes production environments.

Current focus:

  • Finalizing the SharedWorker/ServiceWorker fallback logic.
  • Refining the React hook lifecycle (auto-deregistration of tools).
  • Hardening the Proxy-to-Worker authentication flow.

Contributing

Contributions, issues, and architectural discussions are welcome!

  • Bug reports & feature requests: open an issue on GitHub
  • Pull requests: feel free to submit fixes or improvements — please open an issue first for larger changes so we can align on the approach
  • Discussions: architecture questions and ideas belong in GitHub Discussions

License

Licensed under the Apache License, Version 2.0. See LICENSE for details.


👨‍💻 Author

Michal Kopecký — Frontend engineer & creator of MCP-FE

I built MCP-FE to solve the "runtime-blindness" of current AI agents. By treating the browser as an active edge-node, we can provide agents with deep, real-time context without sacrificing user privacy or network performance.

GitHub · LinkedIn · mcp-fe.ai

Используйте MCP @mcp-fe/react-tools с разными ИИ-моделями

TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому после подключения @mcp-fe/react-tools вы можете использовать их с разными моделями ИИ в 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

Добавьте @mcp-fe/react-tools как сервер

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

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

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

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

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

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

Для чего используется сервер MCP @mcp-fe/react-tools?

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

Можно ли использовать сервер MCP @mcp-fe/react-tools с несколькими ИИ-моделями в TypingMind?

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

Зачем использовать MCP @mcp-fe/react-tools с TypingMind?

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

Как подключить сервер MCP @mcp-fe/react-tools к TypingMind?

@mcp-fe/react-tools работает через локальный коннектор MCP TypingMind. Этот вариант лучше всего подходит, когда серверу MCP нужен доступ к локальным файлам, настольным приложениям, инструментам командной строки или закрытым ресурсам на вашем компьютере.

Какие инструменты предоставляет сервер MCP @mcp-fe/react-tools в TypingMind?

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

Нужно ли передавать TypingMind свои ключи API для использования сервера MCP @mcp-fe/react-tools?

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

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

Все

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

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