Skip to main content
In this tutorial, we will create a minimal React app that registers one WebMCP tool using the useWebMCP hook. The hook handles registration on mount and cleanup on unmount automatically. By the end, you will have a React component that exposes a tool to browser-side WebMCP consumers and shows execution state in the UI.

Prerequisites

  • Node.js 22.12 or later
  • pnpm
  • A text editor
  • Chrome or Edge 126+, Firefox 126+, or Safari 18+

What we will build

A React app with a single component that:
  1. Initializes the WebMCP polyfill
  2. Registers a say_hello tool via the useWebMCP hook
  3. Shows execution count and results in the page
  4. Allows you to call the tool from both the UI and the browser console
1

Scaffold the project

Create a new React project with Vite:
Create the React app
Install the WebMCP dependencies:
Install the hook and polyfill
@mcp-b/webmcp-polyfill provides the document.modelContext runtime. usewebmcp provides the React hook for tool registration.
2

Initialize the polyfill

Open src/main.tsx and add the polyfill initialization before createRoot:
src/main.tsx
Calling installWebMCP() once at the top level makes document.modelContext available before any component mounts.
3

Create the tool component

Replace the contents of src/App.tsx with:
src/App.tsx
The useWebMCP hook registers the tool when the component mounts and unregisters it when the component unmounts. The named schema also keeps the component easy to scan; inline schema objects do not cause re-registration by reference.
4

Start the development server

Start Vite
Open http://localhost:5173 in your browser. You should see:
Expected page
5

Call the tool from the UI

Click the Run Tool Locally button. Notice the page updates:
Expected result
Click the button a few more times. The execution count increases with each click.
6

Verify the tool from the console

Open the browser console (F12) and verify the tool is registered:
Find the registered tool
You should see an array containing your say_hello tool. Now call it with an input object:
Call the tool through the polyfill
The output should be an object containing the tool response:
Expected agent result
Notice that the execution count in the UI also incremented, because the same underlying execute function ran.

What you learned

  • installWebMCP() should be called once at app startup, before components mount
  • useWebMCP registers a tool on mount and unregisters on unmount
  • Metadata changes update registration automatically; equivalent inline schemas do not cause re-registration
  • The hook returns state (with executionCount, lastResult, error, isExecuting) and an execute function for local invocation
  • Tools registered via the hook are discoverable with document.modelContext.getTools() and callable with executeTool(tool, inputObject)

Next steps