Skip to content
Back to search

use-mcp

A lightweight React hook for connecting to Model Context Protocol (MCP) servers. Simplifies authentication and tool calling for AI systems implementing the MCP standard.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/modelcontextprotocol--use-mcp/badge.svg)](/listings/modelcontextprotocol--use-mcp)

HTML

<a href="/listings/modelcontextprotocol--use-mcp"><img src="/api/listings/modelcontextprotocol--use-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npm install use-mcp
# or
pnpm add use-mcp
# or
yarn add use-mcp

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 256 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <div class="oranda-hide">
  2. # 🦑 use-mcp 🦑
  3. </div>
  4. [![GitHub last commit](https://img.shields.io/github/last-commit/modelcontextprotocol/use-mcp?logo=github&style=flat&label=​)](https://github.com/modelcontextprotocol/use-mcp)&nbsp; [![npm](https://img.shields.io/npm/v/use-mcp?label=​&logo=npm)](https://www.npmjs.com/package/use-mcp) ![GitHub License](https://img.shields.io/github/license/modelcontextprotocol/use-mcp)
  5. A lightweight React hook for connecting to [Model Context Protocol (MCP)](https://github.com/modelcontextprotocol) servers. Simplifies authentication and tool calling for AI systems implementing the MCP standard.
  6. Try it out: [Chat Demo](https://chat.use-mcp.dev) | [MCP Inspector](https://inspector.use-mcp.dev) | [Cloudflare Workers AI Playground](https://playground.ai.cloudflare.com/)
  7. ## Installation
  8. ```bash
  9. npm install use-mcp
  10. # or
  11. pnpm add use-mcp
  12. # or
  13. yarn add use-mcp
  14. ```
  15. ## Development
  16. To run the development environment with all examples and servers:
  17. ```bash
  18. pnpm dev
  19. ```
  20. This starts:
  21. - **Inspector**: http://localhost:5001 - MCP server debugging tool
  22. - **Chat UI**: http://localhost:5002 - Example chat interface
  23. - **Hono MCP Server**: http://localhost:5101 - Example MCP server
  24. - **CF Agents MCP Server**: http://localhost:5102 - Cloudflare Workers AI MCP server
  25. ### Testing
  26. Integration tests are located in the `test/` directory and run headlessly by default:
  27. ```bash
  28. cd test && pnpm test # Run tests headlessly (default)
  29. cd test && pnpm test:headed # Run tests with visible browser
  30. cd test && pnpm test:watch # Run tests in watch mode
  31. cd test && pnpm test:ui # Run tests with interactive UI
  32. ```
  33. ## Features
  34. - 🔄 Automatic connection management with reconnection and retries
  35. - 🔐 OAuth authentication flow handling with popup and fallback support
  36. - 📦 Simple React hook interface for MCP integration
  37. - 🧰 Full support for MCP tools, resources, and prompts
  38. - 📄 Access server resources and read their contents
  39. - 💬 Use server-provided prompt templates
  40. - 🧰 TypeScript types for editor assistance and type checking
  41. - 📝 Comprehensive logging for debugging
  42. - 🌐 Works with both HTTP and SSE (Server-Sent Events) transports
  43. ## Quick Start
  44. ```tsx
  45. import { useMcp } from 'use-mcp/react'
  46. function MyAIComponent() {
  47. const {
  48. state, // Connection state: 'discovering' | 'pending_auth' | 'authenticating' | 'connecting' | 'loading' | 'ready' | 'failed'
  49. tools, // Available tools from MCP server
  50. resources, // Available resources from MCP server
  51. prompts, // Available prompts from MCP server
  52. error, // Error message if connection failed
  53. callTool, // Function to call tools on the MCP server
  54. readResource, // Function to read resource contents
  55. getPrompt, // Function to get prompt messages
  56. retry, // Retry connection manually
  57. authenticate, // Manually trigger authentication
  58. clearStorage, // Clear stored tokens and credentials
  59. } = useMcp({
  60. url: 'https://your-mcp-server.com',
  61. clientName: 'My App',
  62. autoReconnect: true,
  63. })
  64. // Handle different states
  65. if (state === 'failed') {
  66. return (
  67. <div>
  68. <p>Connection failed: {error}</p>
  69. <button onClick={retry}>Retry</button>
  70. <button onClick={authenticate}>Authenticate Manually</button>
  71. </div>
  72. )
  73. }
  74. if (state !== 'ready') {
  75. return <div>Connecting to AI service...</div>
  76. }
  77. // Use available tools
  78. const handleSearch = async () => {
  79. try {
  80. const result = await callTool('search', { query: 'example search' })
  81. console.log('Search results:', result)
  82. } catch (err) {
  83. console.error('Tool call failed:', err)
  84. }
  85. }
  86. return (
  87. <div>
  88. <h2>Available Tools: {tools.length}</h2>
  89. <ul>
  90. {tools.map(tool => (
  91. <li key={tool.name}>{tool.name}</li>
  92. ))}
  93. </ul>
  94. <button onClick={handleSearch}>Search</button>
  95. {/* Example: Display and read resources */}
  96. {resources.length > 0 && (
  97. <div>
  98. <h3>Resources: {resources.length}</h3>
  99. <button onClick={async () => {
  100. const content = await readResource(resources[0].uri)
  101. console.log('Resource content:', content)
  102. }}>
  103. Read First Resource
  104. </button>
  105. </div>
  106. )}
  107. {/* Example: Use prompts */}
  108. {prompts.length > 0 && (
  109. <div>
  110. <h3>Prompts: {prompts.length}</h3>
  111. <button onClick={async () => {
  112. const result = await getPrompt(prompts[0].name)
  113. console.log('Prompt messages:', result.messages)
  114. }}>
  115. Get First Prompt
  116. </button>
  117. </div>
  118. )}
  119. </div>
  120. )
  121. }
  122. ```
  123. ## Setting Up OAuth Callback
  124. To handle the OAuth authentication flow, you need to set up a callback endpoint in your app.
  125. ### With React Router
  126. ```tsx
  127. // App.tsx with React Router
  128. import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
  129. import { useEffect } from 'react'
  130. import { onMcpAuthorization } from 'use-mcp'
  131. function OAuthCallback() {
  132. useEffect(() => {
  133. onMcpAuthorization()
  134. }, [])
  135. return (
  136. <div>
  137. <h1>Authenticating...</h1>
  138. <p>This window should close automatically.</p>
  139. </div>
  140. )
  141. }
  142. function App() {
  143. return (
  144. <Router>
  145. <Routes>
  146. <Route path="/oauth/callback" element={<OAuthCallback />} />
  147. <Route path="/" element={<YourMainComponent />} />
  148. </Routes>
  149. </Router>
  150. )
  151. }
  152. ```
  153. ### With Next.js Pages Router
  154. ```tsx
  155. // pages/oauth/callback.tsx
  156. import { useEffect } from 'react'
  157. import { onMcpAuthorization } from 'use-mcp'
  158. export default function OAuthCallbackPage() {
  159. useEffect(() => {
  160. onMcpAuthorization()
  161. }, [])
  162. return (
  163. <div>
  164. <h1>Authenticating...</h1>
  165. <p>This window should close automatically.</p>
  166. </div>
  167. )
  168. }
  169. ```
  170. ## API Reference
  171. ### `useMcp` Hook
  172. ```ts
  173. function useMcp(options: UseMcpOptions): UseMcpResult
  174. ```
  175. #### Options
  176. | Option | Type | Description |
  177. |--------|------|-------------|
  178. | `url` | `string` | **Required**. URL of your MCP server |
  179. | `clientName` | `string` | Name of your client for OAuth registration |
  180. | `clientUri` | `string` | URI of your client for OAuth registration |
  181. | `callbackUrl` | `string` | Custom callback URL for OAuth redirect (defaults to `/oauth/callback` on the current origin) |
  182. | `storageKeyPrefix` | `string` | Storage key prefix for OAuth data in localStorage (defaults to "mcp:auth") |
  183. | `clientConfig` | `object` | Custom configuration for the MCP client identity |
  184. | `debug` | `boolean` | Whether to enable verbose debug logging |
  185. | `autoRetry` | `boolean \| number` | Auto retry connection if initial connection fails, with delay in ms |
  186. | `autoReconnect` | `boolean \| number` | Auto reconnect if an established connection is lost, with delay in ms (default: 3000) |
  187. | `transportType` | `'auto' \| 'http' \| 'sse'` | Transport type preference: 'auto' (HTTP with SSE fallback), 'http' (HTTP only), 'sse' (SSE only) (default: 'auto') |
  188. | `preventAutoAuth` | `boolean` | Prevent automatic authentication popup on initial connection (default: false) |
  189. | `onPopupWindow` | `(url: string, features: string, window: Window \| null) => void` | Callback invoked just after the authentication popup window is opened |
  190. #### Return Value
  191. | Property | Type | Description |
  192. |----------|------|-------------|
  193. | `state` | `string` | Current connection state: 'discovering', 'pending_auth', 'authenticating', 'connecting', 'loading', 'ready', 'failed' |
  194. | `tools` | `Tool[]` | Available tools from the MCP server |
  195. | `resources` | `Resource[]` | Available resources from the MCP server |
  196. | `resourceTemplates` | `ResourceTemplate[]` | Available resource templates from the MCP server |
  197. | `prompts` | `Prompt[]` | Available prompts from the MCP server |
  198. | `error` | `string \| undefined` | Error message if connection failed |
  199. | `authUrl` | `string \| undefined` | Manual authentication URL if popup is blocked |
  200. | `log` | `{ level: 'debug' \| 'info' \| 'warn' \| 'error'; message: string; timestamp: number }[]` | Array of log messages |
  201. | `callTool` | `(name: string, args?: Record<string, unknown>) => Promise<any>` | Function to call a tool on the MCP server |
  202. | `listResources` | `() => Promise<void>` | Refresh the list of available resources |
  203. | `readResource` | `(uri: string) => Promise<{ contents: Array<...> }>` | Read the contents of a specific resource |
  204. | `listPrompts` | `() => Promise<void>` | Refresh the list of available prompts |
  205. | `getPrompt` | `(name: string, args?: Record<string, string>) => Promise<{ messages: Array<...> }>` | Get a specific prompt with optional arguments |
  206. | `retry` | `() => void` | Manually attempt to reconnect |
  207. | `disconnect` | `() => void` | Disconnect from the MCP server |
  208. | `authenticate` | `() => void` | Manually trigger authentication |
  209. | `clearStorage` | `() => void` | Clear all stored authentication data |
  210. ## License
  211. MIT

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.