Permet aux développeurs React d'exposer les fonctionnalités typées d'une application sous forme d'outils WebMCP que les agents IA peuvent découvrir et appeler.
Aussi connu sous agentcathq/webmcp-react
- Étoiles
- 92
- Outils
- —
- Téléchargements, 30 jours
- —
- Dernière version
- —
- Dernier commit
- 27 oct. 2026
- Licence
- MIT
Qu'est-ce que webmcp-react MCP ?
webmcp-react est un serveur MCP. Permet aux développeurs React d'exposer les fonctionnalités typées d'une application sous forme d'outils WebMCP que les agents IA peuvent découvrir et appeler.
Résumé généré à partir du README du projet
À propos du MCP server webmcp-react
webmcp-react permet d'exposer des parties d'une application React en tant qu'outils appelables par des agents IA, grâce à des hooks qui enregistrent chaque outil sur document.modelContext. Les développeurs React enveloppent leur application dans un WebMCPProvider et déclarent des outils avec useMcpTool, en attribuant à chacun un nom, une description, des entrées et un gestionnaire asynchrone. Les entrées sont définies avec Zod pour l'inférence de type dans les gestionnaires, ou via un JSON Schema brut via inputSchema lorsque Zod n'est pas utilisé. React 18 ou une version ultérieure est requis, et Zod 3.25 ou une version ultérieure, ou Zod 4, est une peer dependency lorsque Zod est utilisé.
La bibliothèque installe un polyfill léger lorsque le navigateur ne dispose pas du support WebMCP natif, sinon elle utilise l'API native. Elle est compatible SSR et inclut une directive "use client", de sorte que Next.js et Remix ne nécessitent aucune configuration supplémentaire, et elle protège contre les enregistrements en double sous StrictMode. Les outils s'enregistrent au montage et se désenregistrent au démontage, le rendu conditionnel contrôlant ainsi ce que les agents peuvent voir. useMcpTool renvoie l'état d'exécution (isExecuting, lastResult, error), chaque appel reçoit son propre AbortSignal, et les rappels onSuccess et onError exécutent des effets de bord. Quatre annotations (readOnlyHint, untrustedContentHint, consequentialHint, debugging) décrivent le comportement aux agents.
Les agents disposant du support WebMCP natif comme Codex appellent les outils directement depuis la page ; Claude Code, Cursor et d'autres clients MCP se connectent via une extension de navigateur Bridge. Un terrain de jeu Wordle et des Agent Skills installés avec la CLI skills permettent de démontrer et de générer des outils.
Ce que vous pouvez faire avec
- 1Outil de recherche de catalogue pour les agentsEnregistrez un outil de recherche qui prend une chaîne de requête et renvoie les résultats correspondants du catalogue pour qu'un client IA puisse l'appeler.
- 2Récupération de rapports annulablePermettez à un agent de récupérer un rapport par ID tout en connectant l'AbortSignal fourni au fetch, afin qu'un appel annulé interrompe la requête.
- 3Confirmation pour les commandesMarquez un outil de paiement avec une annotation pour que les agents sachent qu'ils doivent vérifier auprès de l'utilisateur avant d'exécuter une action difficile à annuler.
- 4Outils d'administration via rendu conditionnelExposez les outils réservés aux administrateurs uniquement lorsque l'utilisateur actuel est un administrateur, en laissant le montage et le démontage gérer l'enregistrement.
- 5État d'exécution de l'outil dans l'interface utilisateurPilotez l'état désactivé et le message d'un bouton à partir de l'état d'exécution renvoyé par un hook d'outil de traduction.
Extrait du README du projet. Chaque cas d'utilisation est vérifié par rapport à une citation du document.
Comment installer webmcp-react MCP
Formats vérifiés le 10 nov. 2026Ajouter à CursorAjouter à GooseInstaller webmcp-react MCP dans Claude Code
$ claude mcp add webmcp-react -- npx -y webmcp-reactInstaller webmcp-react MCP dans Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"webmcp-react": {
"command": "npx",
"args": [
"-y",
"webmcp-react"
]
}
}
}Installer webmcp-react MCP dans VS Code
.vscode/mcp.json
{
"servers": {
"webmcp-react": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"webmcp-react"
]
}
}
}Installer webmcp-react MCP dans VS Code CLI
$ code --add-mcp '{"name":"webmcp-react","type":"stdio","command":"npx","args":["-y","webmcp-react"]}'Installer webmcp-react MCP dans Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"webmcp-react": {
"command": "npx",
"args": [
"-y",
"webmcp-react"
]
}
}
}Installer webmcp-react MCP dans Codex
$ codex mcp add webmcp-react -- npx -y webmcp-reactInstaller webmcp-react MCP dans Codex config.toml
~/.codex/config.toml
[mcp_servers.webmcp-react] command = "npx" args = ["-y", "webmcp-react"]
Installer webmcp-react MCP dans Gemini CLI
$ gemini mcp add -s user webmcp-react npx -- -y webmcp-reactInstaller webmcp-react MCP dans Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"webmcp-react": {
"command": "npx",
"args": [
"-y",
"webmcp-react"
]
}
}
}Vérifications automatisées
Exécuté le 13 nov. 2026Rapport complet →A passé nos vérifications automatisées. Il ne s'agit pas d'un audit de sécurité : lisez le code et donnez au serveur l'accès le plus restreint dont il a besoin. Fonctionnement des vérifications
- Dépôt source lié et accessibleRéussi
- Licence open source (OSI)Réussi
- Commit ou version publiée au cours de l'année écouléeRéussi
- Nom du package non proche d'un package populaireRéussi
- L'endpoint distant utilise HTTPSNon vérifié
- Les outils destructifs sont étiquetésNon vérifié
- Aucune instruction cachée destinée au modèleRéussi
- Aucun avis critique dans le package ou ses dépendancesNon vérifié
README
Voir sur GitHubwebmcp-react
React hooks for exposing typed tools on document.modelContext, aligned with the current WebMCP specification.
- 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
npm install webmcp-react zod
Quick start
Wrap your app in <WebMCPProvider> and register tools with useMcpTool:
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:
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.
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.
- Install the extension from the Chrome Web Store.
- Configure your MCP client. See the extension setup guide for details.
The extension will be deprecated when Chrome provides native bridging to desktop clients.
Testing in Chrome
Google's WebMCP extension lists a page's tools and runs an agent against them from a side panel, which is handy while building tools. It only sees tools registered through Chrome's native API, so on a page running the polyfill it finds nothing. Turn on chrome://flags/#enable-webmcp-testing (the extension needs Chrome 155 or newer) and <WebMCPProvider> will use the native API instead of the polyfill.
Usage
Execution state
useMcpTool returns reactive state you can use to build UI around tool execution:
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:
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 four annotations: readOnlyHint, untrustedContentHint, consequentialHint and debugging. Set consequentialHint on tools that do something hard to undo, like placing an order, so agents know to check with the user first.
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:
function App({ user }) {
return (
<WebMCPProvider name="app" version="1.0">
<PublicTools />
{user.isAdmin && <AdminTools />}
</WebMCPProvider>
);
}
Callbacks
Run side effects on success or failure:
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),
});
onError fires when the handler throws. A handler that returns { isError: true } on its own still counts as a success, so onSuccess fires for it.
JSON Schema
Pass inputSchema directly to define a tool without Zod:
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) }] };
},
});
TypeScript
webmcp-react already types document.modelContext, so theres no need to add Google's webmcp-types as well. The two packages declare the same global differently and clash if you install both, see TypeScript and webmcp-types for details and a workaround.
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
| Environment | Behavior |
|---|---|
Chrome with native document.modelContext |
The library uses the native API. The polyfill is not installed. |
| All other browsers | The 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
Questions sur webmcp-react MCP
Comment ajouter webmcp-react MCP à Claude Code ?
Exécutez claude mcp add webmcp-react -- npx -y webmcp-react dans votre terminal. Ajoutez --scope user pour le rendre disponible dans tous les projets.
Comment ajouter webmcp-react MCP à Cursor ?
Ouvrez ~/.cursor/mcp.json et ajoutez le serveur sous mcpServers, avec la configuration Cursor indiquée dans la section d'installation ci-dessus.
À quoi sert webmcp-react ?
Il fournit des hooks React pour enregistrer des outils typés sur document.modelContext, permettant ainsi aux agents IA d'appeler les fonctionnalités de votre application web.
webmcp-react fonctionne-t-il sans support WebMCP natif dans le navigateur ?
Oui. Il installe un polyfill léger lorsque le support WebMCP natif est indisponible, et utilise l'API native lorsqu'elle est présente.
Puis-je définir des outils avec JSON Schema au lieu de Zod ?
Oui, passez directement l'inputSchema pour définir un outil sans utiliser Zod.
webmcp-react est-il compatible avec le SSR ?
Oui, il fonctionne avec Next.js, Remix et d'autres frameworks de rendu côté serveur, et le build inclut une directive "use client".
Comment les outils sont-ils désenregistrés ?
Les outils s'enregistrent au montage et se désenregistrent au démontage, ce qui vous permet de les afficher conditionnellement comme n'importe quel composant React.