npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-mcp-hook

v0.5.0

Published

A React hook for interacting with Model Context Protocol (MCP) servers.

Readme

react-mcp-hook

A React hook for speaking Model Context Protocol (MCP) from the browser. useMcp discovers an MCP session, streams notifications, and exposes a convenient API for listing and calling MCP tools from React components.

Demo

Features

  • Zero-boilerplate MCP client — initialize a connection, fetch tools, and invoke MCP methods from React.
  • Framework-agnostic core client — import McpClient from react-mcp-hook/client for vanilla TypeScript or Node apps.
  • Plugin architecture — extend with custom transport layers (HTTP, stdio, WebSocket, etc.) via transport plugins.
  • Automatic session handling — retries between regular HTTP, SSE, and legacy endpoints with session stickiness.
  • Prompt discovery — page through server-defined prompts while handling unsupported servers gracefully.
  • Prompt retrieval — request fully rendered prompt messages (with arguments) directly from MCP servers.
  • Tool execution helpers — capture intermediate SSE events and final results from long-running tool calls.
  • Typed API surface — ships TypeScript definitions for options, return types, events, and tool payloads.

Installation

Use your package manager of choice. React ≥18 is required as a peer dependency.

npm install react-mcp-hook

(Optional) If you prefer Yarn or pnpm:

yarn add react-mcp-hook
# or
pnpm add react-mcp-hook

Quick start

import { useEffect } from 'react'
import { useMcp } from 'react-mcp-hook'

const McpToolList = () => {
  const {
    tools,
    loading,
    error,
    callTool,
    refetch,
    lastEvent
  } = useMcp({
    url: 'https://your-mcp-server.example.com/mcp',
    headers: async () => ({
      Authorization: `Bearer ${await getAccessToken()}`
    })
  })

  useEffect(() => {
    if (lastEvent) {
      console.debug('Received MCP notification:', lastEvent.message)
    }
  }, [lastEvent])

  if (loading) return <p>Loading tools…</p>
  if (error) return <p>Failed to fetch tools: {error.message}</p>

  return (
    <ul>
      {tools.map((tool) => (
        <li key={tool.name}>
          {tool.name}
          <button
            onClick={() => {
              void callTool(tool.name, { prompt: 'Hello MCP!' }, {
                onEvent: (message) => console.log('Tool progress', message)
              }).then(({ result }) => console.log('Tool result', result))
            }}
          >
            Run
          </button>
        </li>
      ))}
      <li>
        <button onClick={() => refetch()}>Refresh tools</button>
      </li>
    </ul>
  )
}

API reference

useMcp(options: UseMcpOptions | null): UseMcpApi

Initialize the hook with connection details. Pass null to temporarily disable the connection while retaining previous state.

Options (UseMcpOptions)

| Option | Type | Default | Description | | --- | --- | --- | --- | | url | string | required | Base MCP endpoint. May be upgraded automatically to an SSE session endpoint. | | autoFetch | boolean | true | Fetch the tool list on mount and whenever url changes. | | headers | HeaderSource | {} | Static object or async factory returning headers (useful for auth tokens). | | fetchTimeoutMs | number | 10_000 | Timeout for network requests and long-running tool calls. |

HeaderSource can be:

  • A plain record { Authorization: 'Bearer …' }
  • A function returning a record synchronously or asynchronously (e.g. refreshing tokens).

Return value (UseMcpApi)

The hook returns the reactive state plus helper functions:

| Property | Type | Description | | --- | --- | --- | | loading | boolean | Whether the tool list request is in flight. | | loaded | boolean | Indicates if at least one successful tool fetch has completed. | | tools | Tool[] | Latest tool list from the server. | | error | <code>Error &#124; undefined</code> | Last load error (cleared on the next successful fetch). | | serverInfo | <code>ServerInfo &#124; undefined</code> | Metadata returned from the MCP server initialize call. | | protocolVersion | <code>string &#124; undefined</code> | Negotiated protocol version. | | capabilities | <code>ServerCapabilities &#124; undefined</code> | Dynamic capability map from the server. | | lastEvent | <code>RpcNotificationRecord &#124; undefined</code> | Last SSE notification (useful for UI badges/logging). | | fetchTools() | () => Promise<void> | Manually refetch the tool list (auto-cancels previous fetch). | | refetch() | () => Promise<void> | Alias that resets loaded state before fetching. | | abort() | () => void | Abort the active fetch or tool call (invokes AbortController). | | callTool(name, arguments?, options?) | (name: string, arguments?: Record<string, unknown>, options?: CallToolOptions) => Promise<ToolCallOutcome> | Invoke a server tool and collect streamed events. | | listPrompts(options?) | (options?: ListPromptsOptions) => Promise<ListPromptsResult> | Request prompt definitions with optional pagination and per-call abort handling. | | getPrompt(name, arguments?, options?) | (name: string, arguments?: Record<string, unknown>, options?: GetPromptOptions) => Promise<GetPromptResult> | Fetch a render-ready prompt instance, including message content and metadata. |

Listing prompts (listPrompts)

Use listPrompts to discover prompt definitions exposed by the MCP server. The helper returns a ListPromptsResult containing an array of prompts, the next pagination cursor (if provided by the server), and an optional error when the server lacks prompt support or returns a failure.

const { listPrompts } = useMcp({ url: 'https://your-mcp-server.example.com/mcp' })

const loadPrompts = async (cursor?: string) => {
  const { prompts, nextCursor, error } = await listPrompts({ cursor })

  if (error) {
    console.warn('Prompt discovery failed:', error.message)
    return
  }

  setPromptList((existing) => [...existing, ...prompts])

  if (nextCursor) {
    setNextCursor(nextCursor)
  }
}

ListPromptsOptions accepts the same signal and onEvent fields as other RPC helpers, plus an optional cursor to continue pagination. When error is present in the result, the prompts array is empty and nextCursor is undefined, making it safe to surface a user-facing message without throwing.

CallToolOptions.onEvent fires for each streamed message (notifications and responses) with the original RpcMessage and metadata including the requestId and whether it is the final event.

Fetching prompts (getPrompt)

Use getPrompt when you want the server to produce a concrete prompt instance (messages, description, etc.) for a specific definition. Pass any arguments required by the prompt as a plain JSON object; omit the second parameter or pass {} when the prompt does not accept arguments.

const { getPrompt } = useMcp({ url: 'https://your-mcp-server.example.com/mcp' })

const previewPrompt = async () => {
  const { prompt, error } = await getPrompt('code_review', {
    code: `def hello():\n    print('world')`
  })

  if (error) {
    console.error('Prompt fetch failed:', error.message)
    return
  }

  if (!prompt) {
    console.warn('Server returned no prompt data')
    return
  }

  console.table(
    (prompt.messages ?? []).map((message) => ({
      role: message.role,
      content: typeof message.content === 'string'
        ? message.content
        : JSON.stringify(message.content)
    }))
  )
}

GetPromptResult mirrors the shape returned by the MCP server. When the server reports an error (for example, missing method support or invalid arguments), the helper resolves with error and leaves prompt undefined so callers can display a friendly message without handling exceptions.

Call options (CallToolOptions, ListPromptsOptions, GetPromptOptions)

All helper methods accept a shared options object with the following fields:

| Option | Type | Description | | --- | --- | --- | | signal | AbortSignal | Cancel the in-flight MCP request. Useful for timeouts or component unmounts. | | onEvent | (message: RpcMessage, context: EventContext) => void | Receive streaming SSE notifications while the request is active. |

Using the standalone client

Prefer a framework-free API or want to integrate MCP into server-side code? Import the core client directly:

import { McpClient } from 'react-mcp-hook/client'

const client = new McpClient({
  url: 'https://your-mcp-server.example.com/mcp',
  headers: async () => ({
    Authorization: `Bearer ${await getAccessToken()}`
  })
})

await client.initialize()

const tools = await client.listTools()
const promptResult = await client.getPrompt('code_review', { filePath: 'src/App.tsx' })

const toolRun = await client.callTool('code_review', { filePath: 'src/App.tsx' }, {
  signal: AbortSignal.timeout(10_000),
  onEvent: (message) => console.log('Event:', message)
})

console.log('Final result:', toolRun.result)

The standalone client exposes the same helper methods as the hook (listTools, listPrompts, getPrompt, callTool) and automatically handles session negotiation, SSE fallbacks, and error normalisation. You can swap headers, timeouts, or URLs at runtime via client.setOptions(newOptions) without recreating the client instance.

Transport plugins

The library supports a plugin architecture for custom transport layers. While the React hook uses HTTP/SSE by default, the standalone client can use any transport plugin:

import { McpClient } from 'react-mcp-hook/client'
import { StdioTransportPlugin } from './my-stdio-plugin'

// Use stdio transport for Node.js child processes  
const client = new McpClient({
  transport: {
    plugin: new StdioTransportPlugin(),
    options: {
      command: 'python',
      args: ['mcp_server.py'],
      timeoutMs: 30000
    }
  }
  // Note: no 'url' field needed when using transport plugins
})

// The plugin is automatically initialized when you use the client
await client.initialize()
const tools = await client.listTools()

Important: When using transport plugins, do not specify a url field in the client options. The plugin handles all communication and the URL would cause conflicts.

See PLUGIN_ARCHITECTURE.md for detailed documentation on creating custom transport plugins, including a complete stdio transport example for Node.js applications.

Error handling

  • Network or protocol failures reject the returned promises with descriptive Error objects.
  • Aborting a request raises new Error('MCP request was aborted'), allowing callers to treat cancellations separately from real failures.
  • Streaming tool calls surface intermediate RpcMessage payloads via onEvent, so validate context.isFinal before assuming the call has completed.

Tool execution tips

  • Use the events array from callTool results to render progress analytics or audit logs.
  • If your MCP server supports session reuse, you can call abort() before unmounting to free server resources.
  • For manual refresh flows, call refetch() to reset the "loaded" state and show skeleton UIs while data reloads.

Building the library

The project ships with TypeScript build tooling:

npm run build

This compiles everything under src/ and writes ESM output with type declarations to dist/. Publish only the dist directory (already listed in package.json#files).

To check types without emitting files:

npm run typecheck

Local development

  1. Clone the repository and install dependencies: npm install
  2. Run npm run typecheck while editing to catch mistakes early.
  3. The demo/ folder contains a sandbox app; start it with your preferred dev server to experiment with useMcp in context.

Testing

This project uses Vitest. Run the full suite with:

npm test

License

MIT © Ben Goodman