use-mcp is a lightweight React hook library specifically designed for connecting to Model Context Protocol (MCP) servers. This project simplifies the authentication and tool invocation process of the MCP standard in AI systems, providing developers with an easy-to-use front-end integration solution.
npm install use-mcp
# or
pnpm add use-mcp
# or
yarn add use-mcp
import { useMcp } from 'use-mcp/react'
function MyAIComponent() {
const {
state, // Connection state: 'discovering' | 'authenticating' | 'connecting' | 'loading' | 'ready' | 'failed'
tools, // Available tools provided by the MCP server
error, // Error information when the connection fails
callTool, // Function to call MCP server tools
retry, // Manually retry the connection
authenticate, // Manually trigger authentication
clearStorage, // Clear stored tokens and credentials
} = useMcp({
url: 'https://your-mcp-server.com',
clientName: 'My App',
autoReconnect: true,
})
// Handle different connection states
if (state === 'failed') {
return (
<div>
<p>Connection failed: {error}</p>
<button onClick={retry}>Retry</button>
<button onClick={authenticate}>Authenticate</button>
</div>
)
}
if (state !== 'ready') {
return <div>Connecting to AI service...</div>
}
// Use available tools
const handleSearch = async () => {
try {
const result = await callTool('search', { query: 'example search' })
console.log('Search results:', result)
} catch (err) {
console.error('Tool invocation failed:', err)
}
}
return (
<div>
<h2>Number of available tools: {tools.length}</h2>
<ul>
{tools.map(tool => (
<li key={tool.name}>{tool.name}</li>
))}
</ul>
<button onClick={handleSearch}>Search</button>
</div>
)
}
To handle the OAuth authentication flow, you need to set up a callback endpoint in your application.
// App.tsx with React Router
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import { useEffect } from 'react'
import { onMcpAuthorization } from 'use-mcp'
function OAuthCallback() {
useEffect(() => {
onMcpAuthorization()
}, [])
return (
<div>
<h1>Authenticating...</h1>
<p>This window should close automatically.</p>
</div>
)
}
function App() {
return (
<Router>
<Routes>
<Route path="/oauth/callback" element={<OAuthCallback />} />
<Route path="/" element={<YourMainComponent />} />
</Routes>
</Router>
)
}
// pages/oauth/callback.tsx
import { useEffect } from 'react'
import { onMcpAuthorization } from 'use-mcp'
export default function OAuthCallbackPage() {
useEffect(() => {
onMcpAuthorization()
}, [])
return (
<div>
<h1>Authenticating...</h1>
<p>This window should close automatically.</p>
</div>
)
}
function useMcp(options: UseMcpOptions): UseMcpResult
Option | Type | Description |
---|---|---|
url |
string |
Required. The URL of the MCP server |
clientName |
string |
The client name when registering with OAuth |
clientUri |
string |
The client URI when registering with OAuth |
callbackUrl |
string |
Custom callback URL for OAuth redirects (defaults to /oauth/callback on the current domain) |
storageKeyPrefix |
string |
Storage key prefix for OAuth data in localStorage (defaults to "mcp:auth" ) |
clientConfig |
object |
Custom configuration for the MCP client identity |
debug |
boolean |
Whether to enable detailed debugging logs |
autoRetry |
boolean | number |
Automatic retry on initial connection failure, can set the delay in milliseconds |
autoReconnect |
boolean | number |
Automatic reconnection when an established connection is lost, can set the delay in milliseconds (default: 3000) |
Property | Type | Description |
---|---|---|
state |
string |
Current connection state: 'discovering' , 'authenticating' , 'connecting' , 'loading' , 'ready' , 'failed' |
tools |
Tool[] |
Available tools provided by the MCP server |
error |
string | undefined |
Error information when the connection fails |
authUrl |
string | undefined |
Manual authentication URL when the popup is blocked |
log |
LogEntry[] |
Array of log messages |
callTool |
(name: string, args?: Record<string, unknown>) => Promise<any> |
Function to call MCP server tools |
retry |
() => void |
Manually attempt to reconnect |
disconnect |
() => void |
Disconnect from the MCP server |
authenticate |
() => void |
Manually trigger authentication |
clearStorage |
() => void |
Clear all stored authentication data |
use-mcp provides React developers with a powerful and concise solution for integrating Model Context Protocol servers. Through its intuitive Hook interface, complete authentication flow handling, and robust connection management features, developers can easily implement AI tool integration in React applications, greatly reducing the barrier to entry for using the MCP standard.