Description:
use-mcp is a lightweight React hook for connecting applications to Model Context Protocol (MCP) servers.
It simplifies the integration of AI systems that implement the MCP standard by managing authentication, connection states, and tool calls.
The main goal of use-mcp is to handle the entire lifecycle of the connection to an MCP server. This includes service discovery, authentication flows using OAuth, and persistent connections with automatic retries.
You can use it to call tools, read resources, and use prompts provided by the server, abstracting away the underlying communication complexities.
Features
- 🔄 Manages connections automatically, including reconnection and retry logic.
- 🔐 Handles the OAuth authentication flow with support for popups and fallbacks.
- 📦 Offers a simple React hook interface for integrating with MCP servers.
- 🧰 Supports MCP tools, resources, and prompts available on the server.
- 📄 Allows access to server resources and the ability to read their contents.
- 💬 Provides functionality to use prompt templates defined on the server.
- 🧰 Includes TypeScript types for improved editor assistance and type safety.
- 📝 Features comprehensive logging capabilities for debugging purposes.
- 🌐 Works with both HTTP and Server-Sent Events (SSE) transports for communication.
Use Cases
- Build a custom AI chat application that connects to a backend MCP server for processing user queries.
- Develop an internal developer tool that uses AI agents for tasks like code generation or searching technical documentation.
- Create a data analysis dashboard where users can input natural language queries that an AI model processes via MCP.
- Integrate a third-party AI service that exposes its features through the MCP standard into a React application.
- Construct a user interface for an automation workflow that calls different tools on an MCP server to perform a series of actions.
How to Use It
1. Install the package using your preferred package manager.
npm install use-mcp2. Import the useMcp hook into your React component. and initialize it with the URL of your MCP server and a client name. The hook returns the current connection state and other properties you can use to build your UI.
import { useMcp } from 'use-mcp/react';
function AiComponent() {
const { state, error } = useMcp({
url: 'https://your-mcp-server.com',
clientName: 'My AI Application',
});
if (state === 'failed') {
return <p>Connection failed: {error}</p>;
}
if (state !== 'ready') {
return <div>Initializing AI connection...</div>;
}
return <div>Connection Ready</div>;
}3. Once the connection state is ‘ready’, you can interact with the server’s capabilities. The hook provides tools, resources, and functions like callTool and readResource. You can list available tools and execute them with specific arguments.
import { useMcp } from 'use-mcp/react';
function ToolCaller() {
const { state, tools, callTool } = useMcp({
url: 'https://your-mcp-server.com',
clientName: 'My AI Application',
});
if (state !== 'ready') {
return <div>Waiting for connection...</div>;
}
const handleToolExecution = async () => {
try {
const searchTool = tools.find(tool => tool.name === 'search');
if (searchTool) {
const results = await callTool('search', { query: 'React hooks' });
console.log('Search Results:', results);
}
} catch (err) {
console.error('Failed to call tool:', err);
}
};
return (
<div>
<h2>Available Tools</h2>
<ul>
{tools.map(tool => (
<li key={tool.name}>{tool.name}</li>
))}
</ul>
<button onClick={handleToolExecution}>Run Search</button>
</div>
);
}4. Authentication requires a dedicated callback route in your application. For an application using React Router, you can create a component that calls onMcpAuthorization when it mounts. This handles the final step of the OAuth flow.
// In your main App component with routing
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { useEffect } from 'react';
import { onMcpAuthorization } from 'use-mcp';
function OAuthCallbackComponent() {
useEffect(() => {
onMcpAuthorization();
}, []);
return <h1>Authenticating, please wait...</h1>;
}
function App() {
return (
<Router>
<Routes>
<Route path="/oauth/callback" element={<OAuthCallbackComponent />} />
<Route path="/" element={<YourMainComponent />} />
</Routes>
</Router>
);
}5. You can customize the hook’s behavior by passing an options object.
onPopupWindow: A callback function invoked just after the authentication popup window opens.url: Required. The URL of your MCP server.clientName: The name of your client application for OAuth registration.clientUri: The URI of your client application for OAuth registration.callbackUrl: A custom callback URL for the OAuth redirect. It defaults to/oauth/callbackon the current origin.storageKeyPrefix: The prefix for OAuth data stored in localStorage. It defaults to “mcp:auth”.clientConfig: A custom configuration object for the MCP client identity.debug: A boolean to enable verbose debug logging.autoRetry: Automatically retries the connection if the initial attempt fails. You can set a delay in milliseconds.autoReconnect: Automatically reconnects if an established connection is lost. The default delay is 3000ms.transportType: Sets the transport preference. Options are ‘auto’, ‘http’, or ‘sse’. The default is ‘auto’.preventAutoAuth: A boolean that prevents the automatic authentication popup on the initial connection. The default is false.
function useMcp(options: UseMcpOptions): UseMcpResult
6. The useMcp hook returns an object with the following properties.
state: The current connection state, which can be ‘discovering’, ‘pending_auth’, ‘authenticating’, ‘connecting’, ‘loading’, ‘ready’, or ‘failed’.tools: An array of available tools from the MCP server.resources: An array of available resources from the MCP server.resourceTemplates: An array of available resource templates from the MCP server.prompts: An array of available prompts from the MCP server.error: An error message if the connection failed.authUrl: A manual authentication URL if the popup is blocked.log: An array of log messages for debugging.callTool: A function to call a tool on the MCP server by name with optional arguments.listResources: A function to refresh the list of available resources.readResource: A function to read the contents of a specific resource by its URI.listPrompts: A function to refresh the list of available prompts.getPrompt: A function to get a specific prompt by name with optional arguments.retry: A function to manually attempt to reconnect.disconnect: A function to disconnect from the MCP server.authenticate: A function to manually trigger the authentication process.clearStorage: A function to clear all stored authentication data from localStorage.
Related Resources
- Model Context Protocol (MCP): The official documentation and specification for MCP, providing the core concepts behind the protocol that use-mcp implements.
- Hono: A small, simple, and ultrafast web framework for any JavaScript runtime. It can be used to build MCP servers that
use-mcpcan connect to. - Cloudflare Workers AI: A platform that allows you to run AI models on Cloudflare’s network. You can build MCP servers on Cloudflare Workers to serve AI models that can be accessed with
use-mcp. - MCP Servers: A directory of curated & open-source Model Context Protocol servers.
FAQs
Q: What is the Model Context Protocol (MCP)?
A: MCP is an open standard that defines how AI applications can connect with external tools and data sources. It acts as a universal connector, allowing language models to interact with different services in a standardized way.
Q: How does use-mcp manage authentication?
A: The hook handles the OAuth authentication flow required by MCP servers. It can open a popup window for user authorization and requires a callback endpoint in your application to finalize the process.
Q: What is the difference between ‘tools’ and ‘resources’?
A: In MCP, ‘tools’ are functions that the AI can execute on the server, such as searching a database or sending an email. ‘Resources’ are data files or documents that the AI can read to gain context for its tasks.
Q: What should I do if the connection fails?
A: The hook provides a state property that will be set to ‘failed’ and an error property with details. It also returns a retry function that you can call to attempt a new connection manually.
Q: Can I customize the connection behavior?
A: Yes, the useMcp hook accepts several options to control its behavior, such as autoReconnect to manage reconnections on a lost link and transportType to specify a preference for HTTP or SSE communication.