TS

use-mcp

by modelcontextprotocol/use-mcp

0 views

No description available

typescriptjavascriptAPI Integration

๐Ÿฆ‘ use-mcp ๐Ÿฆ‘

GitHub last commitย  npm GitHub License

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

Try it out: MCP Inspector | Cloudflare Workers AI Playground

Installation

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

Features

  • ๐Ÿ”„ Automatic connection management with reconnection and retries
  • ๐Ÿ” OAuth authentication flow handling with popup and fallback support
  • ๐Ÿ“ฆ Simple React hook interface for MCP integration
  • ๐Ÿงฐ TypeScript types for editor assistance and type checking
  • ๐Ÿ“ Comprehensive logging for debugging
  • ๐ŸŒ Works with both HTTP and SSE (Server-Sent Events) transports

Quick Start

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>
  )
}

Setting Up OAuth Callback

To handle the OAuth authentication flow, you need to set up a callback endpoint in your app.

With React Router

// 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>
  )
}

With Next.js Pages Router

// 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

Options

OptionTypeDescription
urlstringRequired. URL of your MCP server
clientNamestringName of your client for OAuth registration
clientUristringURI of your client for OAuth registration
callbackUrlstringCustom callback URL for OAuth redirect (defaults to /oauth/callback on the current origin)
storageKeyPrefixstringStorage key prefix for OAuth data in localStorage (defaults to "mcp:auth")
clientConfigobjectCustom configuration for the MCP client identity
debugbooleanWhether to enable verbose debug logging
autoRetryboolean | numberAuto retry connection if initial connection fails, with delay in ms
autoReconnectboolean | numberAuto reconnect if an established connection is lost, with delay in ms (default: 3000)
transportType'auto' | 'http' | 'sse'Transport type preference: 'auto' (HTTP with SSE fallback), 'http' (HTTP only), 'sse' (SSE only) (default: 'auto')

Return Value

PropertyTypeDescription
statestringCurrent connection state: 'discovering', 'authenticating', 'connecting', 'loading', 'ready', 'failed'
toolsTool[]Available tools from the MCP server
errorstring | undefinedError message if connection failed
authUrlstring | undefinedManual authentication URL if popup is blocked
log{ level: 'debug' | 'info' | 'warn' | 'error'; message: string; timestamp: number }[]Array of log messages
callTool(name: string, args?: Record<string, unknown>) => Promise<any>Function to call a tool on the MCP server
retry() => voidManually attempt to reconnect
disconnect() => voidDisconnect from the MCP server
authenticate() => voidManually trigger authentication
clearStorage() => voidClear all stored authentication data

License

MIT

Install

No configuration available
For more configuration details, refer to the content on the left

Related

Related projects feature coming soon

Will recommend related projects based on sub-categories