New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

react-mcp-hook

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-mcp-hook

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

latest
Source
npmnpm
Version
0.5.0
Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

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)

OptionTypeDefaultDescription
urlstringrequiredBase MCP endpoint. May be upgraded automatically to an SSE session endpoint.
autoFetchbooleantrueFetch the tool list on mount and whenever url changes.
headersHeaderSource{}Static object or async factory returning headers (useful for auth tokens).
fetchTimeoutMsnumber10_000Timeout 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:

PropertyTypeDescription
loadingbooleanWhether the tool list request is in flight.
loadedbooleanIndicates if at least one successful tool fetch has completed.
toolsTool[]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()() => voidAbort 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:

OptionTypeDescription
signalAbortSignalCancel the in-flight MCP request. Useful for timeouts or component unmounts.
onEvent(message: RpcMessage, context: EventContext) => voidReceive 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

  • Clone the repository and install dependencies: npm install
  • Run npm run typecheck while editing to catch mistakes early.
  • 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

Keywords

react

FAQs

Package last updated on 24 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts