The useMcp hook from use-mcp/react provides a complete interface for connecting to an MCP server, managing connection states, and interacting with tools, resources, and prompts.
Key features include:
- State Management: Track connection status via the
state property. - Tool Calling: Use
callTool(name, args) to execute server-side tools. - Resource Access: Use
readResource(uri) to fetch content from server resources. - Prompt Templates: Use
getPrompt(name) to retrieve server-provided prompt messages. - Auth & Recovery: Includes
authenticate(), retry(), and clearStorage() for managing OAuth and connection issues.
import { useMcp } from 'use-mcp/react'
function MyAIComponent() {
const {
state, // 'discovering' | 'pending_auth' | 'authenticating' | 'connecting' | 'loading' | 'ready' | 'failed'
tools, // Available tools
resources, // Available resources
prompts, // Available prompts
error, // Error message
callTool, // (name, args) => Promise<any>
readResource, // (uri) => Promise<{ contents: Array<...> }>
getPrompt, // (name, args) => Promise<{ messages: Array<...> }>
retry, // Reconnect manually
authenticate, // Trigger auth manually
clearStorage, // Clear tokens/credentials
} = useMcp({
url: 'https://your-mcp-server.com',
clientName: 'My App',
autoReconnect: true,
})
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>
}
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>
<button onClick={handleSearch}>Search</button>
{/* ... render tools, resources, or prompts ... */}
</div>
)
}