> ## 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.

# @mcp-b/react-webmcp reference

> Reference for the full React integration: useWebMCP, prompt and resource hooks, client providers, and schema support.

`@mcp-b/react-webmcp` is the full React surface for MCP-B. It supports tool registration, prompt and resource hooks, and client/provider hooks for consuming MCP servers.

## Minimal example

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

import '@mcp-b/global';
import { useWebMCP } from '@mcp-b/react-webmcp';
import { z } from 'zod';

export function CalculatorTool() {
  const tool = useWebMCP({
    name: 'add_numbers',
    description: 'Add two numbers',
    inputSchema: z.object({ left: z.number(), right: z.number() }),
    outputSchema: {
      type: 'object',
      properties: { total: { type: 'number' } },
      required: ['total'],
    },
    annotations: { readOnlyHint: true, idempotentHint: true },
    execute: ({ left, right }) => ({ total: left + right }),
  });

  return <output>Last total: {tool.state.lastResult?.total ?? 'Not called yet'}</output>;
}
```

## Installation

```bash title="Install provider hooks" theme={null}
pnpm add @mcp-b/global @mcp-b/react-webmcp zod@^4.2
```

Zod is used by the example; any supported schema implementation or plain JSON Schema can be used instead.
Tool and context hooks work with native WebMCP, an initialized polyfill, or the MCP-B runtime.
Prompt and resource hooks require the MCP-B extensions installed by `@mcp-b/global`. Client hooks
only require their supplied client and transport. Native WebMCP and the standalone polyfill do not
advertise MCP `outputSchema` metadata.

For client functionality:

```bash title="Install client dependencies" theme={null}
pnpm add @mcp-b/transports @modelcontextprotocol/client
```

## Declarative form attributes

Importing this package adds React JSX declarations for `toolname`, `tooltitle`,
`tooldescription`, `toolautosubmit`, and `toolparamdescription`.

```tsx title="Declare a form tool in React" theme={null}
import '@mcp-b/global';
import type {} from '@mcp-b/react-webmcp';

export function SearchForm() {
  return (
    <form toolname="search_catalog" tooldescription="Search the product catalog" toolautosubmit="">
      <input name="query" toolparamdescription="Words to match" required />
      <button type="submit">Search</button>
    </form>
  );
}
```

Use `toolautosubmit=""`. React drops an unknown attribute whose value is the
boolean `true`, so JSX shorthand (`toolautosubmit`) does not reach the DOM.
See the [declarative API reference](/reference/webmcp/declarative-api) for the
runtime behavior.

## Provider hooks

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

```ts title="Import useWebMCP" theme={null}
import { useWebMCP } from '@mcp-b/react-webmcp';
```

This hook wraps [`usewebmcp`](/packages/usewebmcp/reference) with Standard Schema conversion and
validation, MCP annotations, output-schema inference, and automatic text/`structuredContent`
response formatting. Registration lifecycle, cancellation, `enabled`, `exposedTo`, and execution
state use the core hook.
The published entry point preserves `'use client'`; server rendering is tested on React 19.

| Field | Type | Required | Description |
| - | - | - | - |
| `name` | `string` | Yes | Unique tool identifier |
| `description` | `string` | Yes | Human-readable description |
| `inputSchema` | JSON Schema or Standard JSON Schema v1 | No | Input parameters |
| `outputSchema` | JSON Schema | No | MCP-B output helper metadata |
| `annotations` | `ToolAnnotations` | No | Metadata hints |
| `execute(input, options)` | `(input, { signal }) => T \| Promise<T>` | Yes | Tool implementation |
| `formatOutput` | `(result: T) => unknown` | No | Overrides MCP success formatting |
| `formatError` | `(error: Error) => unknown` | No | Overrides MCP error formatting |

**Returns:** `WebMCPReturn`, including `state`, `execute`, `reset`, `isSupported`, and `registrationError`.

Agent failures default to `{ content: [{ type: "text", text: error.message }], isError: true }`.
`formatError` overrides this response. A handler that returns `undefined` yields a success response
whose text is `undefined`; `formatOutput` overrides that. Both formatters may be async and are awaited. Local failures
and cancellation always reject. `state.error` retains execution failures separately
from `registrationError`. Core-hook behavior is in the [usewebmcp reference](/packages/usewebmcp/reference).

### `useWebMCPContext(name, description, getValue, options?)`

```ts title="Import useWebMCPContext" theme={null}
import { useWebMCPContext } from '@mcp-b/react-webmcp';
```

Convenience wrapper around `useWebMCP` for read-only context tools. It automatically sets `readOnlyHint: true`, `idempotentHint: true`, `destructiveHint: false`, and `openWorldHint: false`.

| Parameter | Type | Description |
| - | - | - |
| `name` | `string` | Tool identifier |
| `description` | `string` | Description for AI assistants |
| `getValue` | `() => T` | Function returning the current context value |
| `options` | `{ enabled?: boolean }` | Optional registration control; `enabled` defaults to `true` |

The `enabled` option has the same behavior as `useWebMCP`.

### `useWebMCPPrompt(config)`

```ts title="Import useWebMCPPrompt" theme={null}
import { useWebMCPPrompt } from '@mcp-b/react-webmcp';
```

Registers an MCP prompt through the `BrowserMcpServer` installed by `@mcp-b/global`. It does not register against a native tool-only context.

| Config field | Type | Required | Description |
| - | - | - | - |
| `name` | `string` | Yes | Prompt identifier |
| `description` | `string` | No | Human-readable description |
| `enabled` | `boolean` | No | Whether to register. Defaults to `true`. |
| `argsSchema` | JSON Schema or Standard JSON Schema v1 | No | Argument schema |
| `get(args)` | `(args) => { messages: PromptMessage[] }` | Yes | Message generator |

**Returns:** `WebMCPPromptReturn`, with `isRegistered: boolean` indicating whether the prompt's
registration is active.

### `useWebMCPResource(config)`

```ts title="Import useWebMCPResource" theme={null}
import { useWebMCPResource } from '@mcp-b/react-webmcp';
```

Registers an MCP resource through the `BrowserMcpServer` installed by `@mcp-b/global`. It does not register against a native tool-only context.

| Config field | Type | Required | Description |
| - | - | - | - |
| `uri` | `string` | Yes | Resource URI or URI template |
| `name` | `string` | Yes | Human-readable name |
| `description` | `string` | No | Resource description |
| `mimeType` | `string` | No | MIME type of the resource content |
| `enabled` | `boolean` | No | Whether to register. Defaults to `true`. |
| `read(uri, params?)` | `(uri: URL, params?) => Promise<{ contents: ResourceContents[] }>` | Yes | Read handler |

**Returns:** `WebMCPResourceReturn`, with `isRegistered: boolean` indicating whether the resource's
registration is active.

For prompts and resources, `enabled: false` skips or removes the registration and sets
`isRegistered` to `false`. Re-enabling registers the latest committed configuration. Call these
hooks unconditionally and pass the condition through `enabled`.

The prompt `get` and resource `read` handlers follow the same
[committed-ref lifecycle as `useWebMCP`](/packages/usewebmcp/reference#re-registration-triggers):
the latest committed handler is available without replacing its registration.

## Client hooks

### `McpClientProvider`

```ts title="browser-connection.ts" theme={null}
import { TabClientTransport } from '@mcp-b/transports';
import { Client } from '@modelcontextprotocol/client';

export function createBrowserConnection() {
  return {
    client: new Client(
      { name: 'tool-browser', version: '1.0.0' },
      { versionNegotiation: { mode: 'auto' } }
    ),
    transport: new TabClientTransport({
      channelId: 'mcp',
      targetOrigin: window.location.origin,
    }),
  };
}
```

Call `createBrowserConnection()` in browser setup and pass its stable instances to the provider.
The [framework guide](/how-to/frameworks#handle-server-rendering) covers browser-global access during server rendering.

Provider component that manages an MCP client connection and shares tools, resources, capabilities, and connection state with descendant components.

| Prop | Type | Required | Description |
| - | - | - | - |
| `children` | `ReactNode` | Yes | Child components |
| `client` | `Client` | Yes | MCP client instance |
| `transport` | `Transport` | Yes | Transport instance |
| `opts` | `ConnectOptions` | No | Connection options, including a cached era verdict |

### `useMcpClient()`

```ts title="Import useMcpClient" theme={null}
import { useMcpClient } from '@mcp-b/react-webmcp';
```

Accesses the client context. It must be used inside `McpClientProvider`.

| Field | Type | Description |
| - | - | - |
| `client` | `Client` | MCP client instance |
| `tools` | `Tool[]` | Available tools from the server |
| `resources` | `Resource[]` | Available resources from the server |
| `isConnected` | `boolean` | Whether the MCP handshake is active |
| `isLoading` | `boolean` | Whether connection or inventory discovery is in progress |
| `error` | `Error \| null` | Connection or inventory error, if any |
| `capabilities` | `ServerCapabilities \| null` | Server-reported capabilities |
| `reconnect(transport?)` | `(transport?: Transport) => Promise<void>` | Retry inventory discovery or reconnect a disconnected client to the server |

Calling `reconnect()` while connected retries the complete tool and resource inventory. After a
one-shot transport closes, create a new transport instance and pass it to `reconnect(newTransport)`;
reusing a closed transport is not supported by every transport implementation.

## Schema compatibility

`@mcp-b/react-webmcp` no longer accepts raw Zod object maps. Use JSON Schema directly, or pass a
Standard JSON Schema object such as `z.object(...)` from Zod 4.2 or newer. `outputSchema` remains
JSON Schema-only. The tool hook runs a supplied `~standard.validate()` on local and agent calls,
awaits async validation, and passes transformed output to the handler. Callers supply the schema's input
type. JSON Schema metadata alone does not add validation.

Treat input schemas as immutable: conversion and serialization are cached by identity. Replace the
object to change its contents; equivalent serialized contents do not refresh registration.
The hook checks output JSON serializability; the official MCP server enforces the output schema
on MCP client calls. Local calls, direct browser execution, and native mirrors bypass that validation.

The tool hook registers plain JSON metadata and keeps the supplied vendor validator in its callback, so the MCP server checks the JSON Schema and the validator runs once, on every path. The [SDK schema adapter](/packages/webmcp-ts-sdk/reference#schema-boundary) converts metadata for direct MCP server registrations. The [schema guide](/how-to/use-schemas-and-structured-output) shows validation outside React.

## Exported types

| Type | Description |
| - | - |
| `InferOutput` | Infers a tool result from an output schema |
| `InferToolInput` | Caller input before validation |
| `InferValidatedToolInput` | Handler input after validation and transforms |
| `WebMCP` | Upstream browser type namespace |
| `ToolExecutionState` | State exposed by `useWebMCP` |
| `WebMCPConfig` | Configuration accepted by `useWebMCP` |
| `WebMCPReturn` | Return value from `useWebMCP` and `useWebMCPContext` |
| `ToolInputSchema` | Supported JSON Schema or Standard JSON Schema input type |
| `McpClientProviderProps` | Props accepted by `McpClientProvider` |
| `WebMCPPromptConfig` | Configuration accepted by `useWebMCPPrompt` |
| `WebMCPPromptReturn` | Registration state returned by `useWebMCPPrompt` |
| `WebMCPResourceConfig` | Configuration accepted by `useWebMCPResource` |
| `WebMCPResourceReturn` | Registration state returned by `useWebMCPResource` |

## Related pages

* [@mcp-b/react-webmcp overview](/packages/react-webmcp/overview)
* [usewebmcp reference](/packages/usewebmcp/reference)
* [Register prompts and resources](/how-to/register-prompts-and-resources)
* [Your first React tool](/tutorials/first-react-tool)
* [@mcp-b/global reference](/packages/global/reference)
* [@mcp-b/transports reference](/packages/transports/reference)


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