use-mcp

repository·main·Indexed 21 days ago

https://github.com/modelcontextprotocol/use-mcp

A lightweight React integration for the Model Context Protocol (MCP) version 0.0.21. It provides the useMcp hook to connect to MCP servers via SSE, manage connection states, handle OAuth authentication, and interact with server-provided tools, resources, and prompts within React applications.

Tokens
10.4K
Snippets
36
Records
50
Agent score
75%

What's inside use-mcp

  1. Supported MCP features in the inspector

    main

    The MCP Inspector supports the following Model Context Protocol features, though functionality depends on the specific capabilities implemented by the target MCP server:

    • Tools: Execute server-provided tools with custom arguments and view results.
    • Resources: Browse available resources and read their contents (supporting both text and binary formats).
    • Resource Templates: View dynamic resource templates defined by URI patterns.
    • Prompts: Interact with server prompts, provide necessary arguments, and view the resulting generated messages.
  2. Understand the Model Selector features

    main

    The model selector system provides several ways to manage and find models:

    • Model Selection: View all available models (currently 39 models across Anthropic, Groq, and OpenRouter) which display provider logos, names, and capabilities.
    • Favorites System: Star models to save them to local storage. You can then use the "Favorites" filter to view only your starred models.
    • Search & Filtering:
      • Use the search box to find models by name or provider.
      • Use the "Tools Only" filter to show only models that support tool calling (this filter appears when MCP tools are available).
      • Use the "Favorites" filter to show only starred models.
    • Authentication:
      • Anthropic & Groq: Requires manual API key entry.
      • OpenRouter: Supports OAuth PKCE flow for one-click authentication.
  3. Set up OAuth callback for use-mcp

    main

    To handle the OAuth authentication flow, you must implement a callback endpoint in your application that calls onMcpAuthorization() from the use-mcp package. This function processes the authorization and closes the flow.

    React Router Implementation

    Create a component that calls onMcpAuthorization inside a useEffect and map it to a route like /oauth/callback.

    Next.js Pages Router Implementation

    Create a page at pages/oauth/callback.tsx that calls onMcpAuthorization inside a useEffect.

    // React Router Example
    import { useEffect } from 'react'
    import { onMcpAuthorization } from 'use-mcp'
    
    function OAuthCallback() {
      useEffect(() => {
        onMcpAuthorization()
      }, [])
    
      return <div>Authenticating...</div>
    }
  4. Quick Start with the useMcp hook

    main

    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>
      )
    }
  5. Run the AI Chat with MCP example application

    main

    The ai-chat-template is a React-based AI chat application that demonstrates how to integrate the Model Context Protocol (MCP) using the use-mcp library. It supports connecting to MCP servers (including OAuth), multiple AI providers (Anthropic and Groq), and local conversation storage via IndexedDB.

    To run the application locally for development, use pnpm to install dependencies and start the dev server.

    pnpm install
    pnpm dev
  6. Configure OpenRouter OAuth

    main

    To enable one-click OAuth authentication for OpenRouter, you must register an OAuth app in your OpenRouter dashboard and configure the redirect URI and environment variables.

    1. Create an OpenRouter account at https://openrouter.ai.
    2. Create an OAuth app in your dashboard.
    3. Set the redirect URI to: http://localhost:5002/oauth/openrouter/callback.
    4. Add your client ID to your .env file using the VITE_OPENROUTER_CLIENT_ID key.
    VITE_OPENROUTER_CLIENT_ID=your_client_id_here