> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mcp-b.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# usewebmcp reference

> Reference for upstream WebMCP React hooks, JSON Schema inference, registration lifecycle, and cancellation.

`usewebmcp` registers React-owned tools with `document.modelContext`. Its browser contracts and JSON Schema input inference come from the Community Group's [`webmcp-types`](https://github.com/webmachinelearning/webmcp-types).

The runtime comes from the browser, [`@mcp-b/webmcp-polyfill`](/packages/webmcp-polyfill/overview), or [`@mcp-b/global`](/packages/global/overview). The hook does not install a runtime or MCP SDK. For MCP output metadata, prompts, resources, and clients, use [`@mcp-b/react-webmcp`](/packages/react-webmcp/reference).

## Minimal example

```tsx title="Counter.tsx" theme={null}
'use client';

import { useState } from 'react';
import { useWebMCP } from 'usewebmcp';

export function Counter() {
  const [count, setCount] = useState(0);

  useWebMCP({
    name: 'get_count',
    description: 'Get the current counter value',
    annotations: { readOnlyHint: true },
    execute: () => ({ count }),
  });

  return (
    <button type="button" onClick={() => setCount((value) => value + 1)}>
      Count: {count}
    </button>
  );
}
```

## Installation

```bash title="Install packages" theme={null}
pnpm add usewebmcp react
```

React 18 and 19 are supported. The published entry point preserves `'use client'`, including production builds. Importing and server rendering do not access browser globals or register tools. Renderers without a `document` report `isSupported: false`. Framework integration is covered in the [framework guide](/how-to/frameworks).

## Hook

### `useWebMCP(config, deps?)`

`deps` is an optional React dependency list for explicitly refreshing registration.

| Returned field | Type | Description |
| - | - | - |
| `state` | `ToolExecutionState<TResult>` | Execution state |
| `execute(input, options?)` | `Promise<TResult>` | Local execution with optional `{ signal }` |
| `reset()` | `void` | Clears observed execution state without cancelling work |
| `isSupported` | `boolean` | A registration API is available |
| `registrationError` | `Error \| null` | Invalid input schema or rejected registration |

`registrationError` describes setup failures separately from `state.error`. A null error does not confirm registration; use the runtime’s `getTools()` for discovery.
When the browser rejects a registration, for example because another tool already uses the name, the hook also logs one `console.warn` naming the tool. The tool stays unregistered until its registration refreshes.

## Config fields

| Field | Type | Required | Description |
| - | - | - | - |
| `name` | `string` | Yes | Tool identifier |
| `title` | `string` | No | Human-readable label |
| `description` | `string` | Yes | Tool description |
| `inputSchema` | WebMCP JSON Schema | No | Input metadata and type inference |
| `annotations` | `WebMCP.ToolAnnotations` | No | Upstream behavior hints |
| `execute(input, options)` | `(input, { signal }) => TResult \| Promise<TResult>` | Yes | Tool implementation |
| `enabled` | `boolean` | No | Defaults to true; controls registration |
| `exposedTo` | `string[]` | No | Forwarded to the browser's registration options |

`enabled: false` unregisters the tool while leaving local execution available. The browser enforces origin exposure; see the [Community Group draft](https://webmachinelearning.github.io/webmcp/#dictdef-modelcontextregistertooloptions).

## Execution state

| Field | Type | Description |
| - | - | - |
| `isExecuting` | `boolean` | At least one execution is pending |
| `lastResult` | `TResult \| null` | Most recent successful result |
| `error` | `Error \| null` | Most recent execution error |
| `executionCount` | `number` | Successful executions since the last reset |

The handler receives the upstream execution `AbortSignal`. Local calls can provide their own signal or use a fresh one. Cancellation rejects the call and clears its pending state. Work that ignores cancellation cannot replace state when it finishes later.

## JSON Schema and inference

Inline WebMCP JSON Schema literals infer caller and handler inputs through upstream types. Reusable schemas retain literals with `as const`. `TResult` is inferred from the handler's return value. The schema is registered as metadata; the hook passes runtime input to the handler without validation or transformation.

`ToolInputSchema` excludes Standard Schema values. Passing Zod or another Standard Schema validator is a type error, and at runtime a schema with a `~standard` property sets `registrationError` without registering the tool.

For Standard Schema conversion and runtime validation, use [`@mcp-b/react-webmcp`](/packages/react-webmcp/reference). For direct registration, the [schema guide](/how-to/use-schemas-and-structured-output) covers callback validation and the [SDK schema adapter](/packages/webmcp-ts-sdk/reference#schema-boundary) covers metadata conversion.

## Re-registration triggers

Registration refreshes when serialized tool metadata, `enabled`, `exposedTo`, or explicit `deps` change. Equivalent metadata does not re-register a tool. The latest committed callback applies without callback-reference-driven registration changes.

Treat input schemas as immutable. Serialization is memoized by `inputSchema` identity; replace the object when its contents change. A new object with equivalent serialized contents keeps the existing registration.

Committed callbacks are published with a layout effect in the browser and a passive effect on the server. Suspended or abandoned renders do not replace the active implementation. Cleanup aborts the component's registration signal.

The hook reads `document.modelContext` when it registers and does not wait for a runtime installed later, so install the runtime before mounting tools. It does not fall back to `navigator.modelContext`. A registration that resolves or rejects after cleanup cannot change the replacement registration's state.

When the API is available, the hook commits once after mount to set `isSupported`. Later successful registrations add no commits.

## Results

Local execution resolves with the handler's raw result, which is also stored in `state.lastResult`. Thrown or returned `Error` objects reject. The hook does not wrap agent results in MCP `CallToolResult` values.

Agent calls receive `null` when the handler returns `undefined`. Any other agent result must be JSON-serializable. A BigInt, function, or circular result fails the agent call, and `state.error` records the reason. For output schemas, MCP annotations, or automatic response formatting, use [`@mcp-b/react-webmcp`](/packages/react-webmcp/reference#usewebmcpconfig-deps).

## Exported types

| Type | Description |
| - | - |
| `WebMCP` | Upstream namespace from `webmcp-types` |
| `WebMCPConfig<TInputSchema, TResult>` | Configuration with the result type inferred from the handler |
| `WebMCPReturn<TInputSchema, TResult>` | Execution state, API availability, registration errors, and controls |
| `ToolExecutionState<TResult>` | Execution state |
| `ToolExecuteFunction<TInputSchema, TResult>` | Handler signature |
| `ToolInputSchema` | Accepted WebMCP JSON Schema type, excluding Standard Schema values |
| `InferToolInput<TInputSchema>` | Input type inferred from the WebMCP JSON Schema |

The second generic parameter of core configuration and return types is the result type. MCP output-schema helpers and schema-validated input types are available from `@mcp-b/react-webmcp`.

## Internal entry point

`usewebmcp/internal` exports `useWebMCPWithAdapter` and `WebMCPAdapter` for [`@mcp-b/react-webmcp`](/packages/react-webmcp/reference). It is not a stable API and can change in any release.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.