
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
react-mcp-hook
Advanced tools
A React hook for interacting with Model Context Protocol (MCP) servers.
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.
McpClient from react-mcp-hook/client for vanilla TypeScript or Node apps.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
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>
)
}
useMcp(options: UseMcpOptions | null): UseMcpApiInitialize the hook with connection details. Pass null to temporarily disable the connection while retaining previous state.
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:
{ Authorization: 'Bearer …' }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 | undefined</code> | Last load error (cleared on the next successful fetch). |
serverInfo | <code>ServerInfo | undefined</code> | Metadata returned from the MCP server initialize call. |
protocolVersion | <code>string | undefined</code> | Negotiated protocol version. |
capabilities | <code>ServerCapabilities | undefined</code> | Dynamic capability map from the server. |
lastEvent | <code>RpcNotificationRecord | 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. |
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.
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.
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. |
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.
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 objects.new Error('MCP request was aborted'), allowing callers to treat cancellations separately from real failures.RpcMessage payloads via onEvent, so validate context.isFinal before assuming the call has completed.events array from callTool results to render progress analytics or audit logs.abort() before unmounting to free server resources.refetch() to reset the "loaded" state and show skeleton UIs while data reloads.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
npm installnpm run typecheck while editing to catch mistakes early.demo/ folder contains a sandbox app; start it with your preferred dev server to experiment with useMcp in context.This project uses Vitest. Run the full suite with:
npm test
MIT © Ben Goodman
FAQs
A React hook for interacting with Model Context Protocol (MCP) servers.
The npm package react-mcp-hook receives a total of 0 weekly downloads. As such, react-mcp-hook popularity was classified as not popular.
We found that react-mcp-hook demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

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.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.