use-mcp Project Detailed Introduction
Project Overview
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.
Project Features
๐ Automatic Connection Management
- Supports automatic reconnection and retry mechanisms
- Intelligently handles connection status and exceptions
๐ OAuth Authentication Flow
- Complete OAuth authentication flow handling
- Supports popup and fallback authentication methods
- Automatically handles authentication token storage
๐ฆ Concise React Hook Interface
- Provides an intuitive React Hook API
- Automated state management
- Easy to integrate into existing React applications
๐งฐ TypeScript Support
- Complete TypeScript type definitions
- Editor intelligent prompts and type checking
- Improves development efficiency and code quality
๐ Comprehensive Logging
- Detailed debugging log functionality
- Facilitates troubleshooting and development debugging
๐ Multi-Transport Protocol Support
- Supports HTTP transport
- Supports SSE (Server-Sent Events) transport
Installation
npm install use-mcp
# or
pnpm add use-mcp
# or
yarn add use-mcp
Basic Usage
Main Hook Usage
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>
)
}
OAuth Authentication Callback Setup
To handle the OAuth authentication flow, you need to set up a callback endpoint in your application.
React Router Configuration
// 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>
)
}
Next.js Configuration
// 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>
)
}
API Reference
useMcp Hook
function useMcp(options: UseMcpOptions): UseMcpResult
Configuration Options (UseMcpOptions)
| 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) |
Return Value (UseMcpResult)
| 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 |
Real-World Application Examples
Online Demos
- MCP Inspector - MCP Inspector Tool
- Cloudflare Workers AI Playground - Cloudflare Workers AI Playground
Summary
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.