use-mcp - A Lightweight React Hook for Integrating with MCP Servers
Along with LLM Playground, Cloudflare has open sourced use-mcp - a lightweight React hook for connecting with remote MCP servers.
This will be useful if you’re building a playground for remote MCP servers.
It takes care of lot of things out of box:
- Automatic connection management with reconnection and retries
- OAuth auth support
- Logging for debugging
- Support for HTTP & SSE transports
Installation
npm install use-mcp
# or
pnpm add use-mcp
# or
yarn add use-mcp
Example snippet
import { useMcp } from 'use-mcp/react'
function MyAIComponent() {
const {
state, // Connection state: 'discovering' | 'authenticating' | 'connecting' | 'loading' | 'ready' | 'failed'
tools, // Available tools from MCP server
error, // Error message if connection failed
callTool, // Function to call tools on the MCP server
retry, // Retry connection manually
authenticate, // Manually trigger authentication
clearStorage, // Clear stored tokens and credentials
} = useMcp({
url: 'https://your-mcp-server.com',
clientName: 'My App',
autoReconnect: true,
})
// Handle different states
if (state === 'failed') {
return (
<div>
<p>Connection failed: {error}</p>
<button onClick={retry}>Retry</button>
<button onClick={authenticate}>Authenticate Manually</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 call failed:', err)
}
}
return (
<div>
<h2>Available Tools: {tools.length}</h2>
<ul>
{tools.map(tool => (
<li key={tool.name}>{tool.name}</li>
))}
</ul>
<button onClick={handleSearch}>Search</button>
</div>
)
}
Here is an example of showcasing the capabilities of use-mcp 👇
Source Code
References
Happy building apps!