WebMCP for Next.js & React
Implement WebMCP in a Next.js or React app: polyfill setup, lifecycle-safe tool registration with hooks, client-side routing gotchas, and Chrome origin-trial configuration.
Updated 2026-08-28 · webmcp-ai.dev research desk
React apps have a WebMCP-specific problem the CMS guides don't: lifecycle. Tools
should exist only while the UI that backs them exists — register a checkout tool globally and an
agent may call it from a page where it can't work. The @mcp-b packages solve this
with hooks that register on mount and clean up on unmount.
Step 1 — Install
npm install @mcp-b/webmcp-polyfill @mcp-b/react-webmcp
Step 2 — Initialize the polyfill
In a client component mounted once (e.g. in your root layout):
'use client';
import { useEffect } from 'react';
export function WebMCPProvider({ children }) {
useEffect(() => {
import('@mcp-b/webmcp-polyfill').then((m) => m.initialize?.());
}, []);
return children;
}
On browsers in the Chrome origin trial, native document.modelContext is used; the
polyfill covers everyone else via extension-based agents.
Step 3 — Register tools with component lifecycle
'use client';
import { useWebMCP } from '@mcp-b/react-webmcp';
export function ProductSearch() {
useWebMCP({
name: 'search_products',
description: "Search the product catalog. Returns names, prices and URLs.",
inputSchema: {
type: 'object',
properties: { query: { type: 'string' } },
required: ['query']
},
annotations: { readOnlyHint: true },
async execute({ query }) {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
return res.json();
}
});
return <SearchUI />;
}
The hook unregisters the tool when the component unmounts — which also solves the client-side
routing gotcha: on soft navigations the page never reloads, so manually-registered tools from a
previous route would otherwise leak into the next one. If you register imperatively instead,
listen for route changes and clean up, and use the toolchange event to verify what's
currently exposed.
Step 4 — Origin trial + verification
Serve the token as a header from next.config.js:
module.exports = {
async headers() {
return [{ source: '/(.*)',
headers: [{ key: 'Origin-Trial', value: process.env.WEBMCP_OT_TOKEN }] }];
}
};
- Check
document.modelContextexists in the DevTools console on Chrome 149+. - Verify tools with Google's Model Context Tool Inspector extension.
- Remember WebMCP requires a secure context and same-origin execution — it will not work on plain HTTP, and
document.domaintricks disable it.
Server components and the bigger picture
WebMCP is a client API, but agent readiness is mostly a server concern: RSC/SSR output that's readable without JavaScript, JSON-LD in the HTML, llms.txt, and sane AI-crawler rules. A React SPA that renders client-side only scores near zero on content accessibility no matter how good its tools are. Check where you stand with the free scan, or get the full per-page picture in the deep audit.