React Hook Implementation Analysis

Overview

The React module provides the useMcp hook for integrating Model Context Protocol (MCP) servers into React applications. It handles connection management, authentication flows, and provides a clean API for interacting with MCP tools, resources, and prompts.

File Structure

src/react/index.ts - Entry Point

Purpose: Main export file for React integration
Line-by-Line Analysis:

  • Lines 1-4: File documentation
  • Line 6: Exports the main useMcp hook from ./useMcp.js
  • Line 7: Exports TypeScript types UseMcpOptions and UseMcpResult
  • Lines 9-10: Re-exports core MCP SDK types for convenience

src/react/types.ts - Type Definitions

UseMcpOptions Interface (Lines 3-33)

Configuration options for the useMcp hook:

Core Options:

  • url (Line 5): Required SSE URL of the MCP server
  • clientName (Line 7): OAuth client name for dynamic registration
  • clientUri (Line 9): OAuth client URI for registration
  • callbackUrl (Line 11): Custom OAuth callback URL (defaults to /oauth/callback)
  • storageKeyPrefix (Line 13): Prefix for localStorage keys (defaults to "mcp:auth")

Client Configuration:

  • clientConfig (Lines 14-18): Custom MCP client identity (name and version)
  • customHeaders (Line 20): Headers for bypassing authentication

Debug & Connection Options:

  • debug (Line 22): Enable verbose logging
  • autoRetry (Line 24): Auto-retry failed connections with delay
  • autoReconnect (Line 26): Auto-reconnect on connection loss (default: 3000ms)
  • popupFeatures (Line 28): OAuth popup window configuration
  • transportType (Line 30): Transport preference ('auto', 'http', 'sse')
  • preventAutoAuth (Line 32): Prevent automatic authentication popup

UseMcpResult Interface (Lines 35-115)

Return value from the useMcp hook:

State Properties:

  • tools (Line 37): Available tools from the server
  • resources (Line 39): Available resources
  • resourceTemplates (Line 41): Available resource templates
  • prompts (Line 43): Available prompts
  • state (Line 54): Connection state machine
  • error (Line 56): Error message when state is 'failed'
  • authUrl (Line 61): Manual authentication URL
  • log (Line 63): Debug log messages

Connection States (Lines 45-53):

  1. 'discovering' - Checking server capabilities
  2. 'pending_auth' - Authentication required, user action needed
  3. 'authenticating' - Authentication process initiated
  4. 'connecting' - Establishing connection
  5. 'loading' - Loading tools/resources
  6. 'ready' - Connected and ready
  7. 'failed' - Connection/authentication failed

API Functions:

  • callTool (Lines 71): Execute tools on the server
  • listResources (Lines 77): Refresh resource list
  • readResource (Lines 84): Read resource contents
  • listPrompts (Lines 90): Refresh prompt list
  • getPrompt (Lines 98): Get specific prompt with arguments
  • retry (Line 103): Manual reconnection
  • disconnect (Line 105): Disconnect from server
  • authenticate (Line 112): Manual authentication trigger
  • clearStorage (Line 114): Clear stored auth data

src/react/useMcp.ts - Main Hook Implementation

Dependencies and Constants (Lines 1-33)

  • Lines 2-14: MCP SDK imports for types and schemas
  • Line 15: React hooks (useCallback, useEffect, useRef, useState)
  • Lines 17-19: Transport implementations (SSE and HTTP)
  • Lines 20-25: Client, auth, and utility imports
  • Lines 27-29: Configuration constants

Hook Structure and State Management (Lines 34-75)

Configuration Processing (Lines 35-50):

  • Destructures options with sensible defaults
  • Sanitizes callback URL to prevent XSS
  • Sets up storage prefixes and client configuration

State Variables (Lines 52-59):

  • Connection state machine
  • Collections for tools, resources, and prompts
  • Error handling and logging
  • Authentication URL for manual auth

Refs for Internal State (Lines 61-74):

  • Client and transport references
  • Auth provider reference
  • Connection state tracking
  • Mount status tracking
  • Attempt counters and timeouts

Core Connection Logic (Lines 152-502)

Connection Orchestration (Lines 152-189):

  • Prevents concurrent connections
  • Initializes auth provider and client
  • Manages connection attempt counting
  • Sets up proper error handling

Transport Strategy Implementation (Lines 191-441):
The tryConnectWithTransport helper function:

  1. Transport Creation (Lines 201-242):

    • Creates HTTP or SSE transport instances
    • Configures authentication and headers
    • Sanitizes URLs for security
  2. Event Handler Setup (Lines 253-293):

    • onmessage: Forwards messages to client
    • onerror: Handles transport errors with fallback logic
    • onclose: Manages reconnection logic
  3. Connection Attempt (Lines 296-440):

    • Attempts client connection
    • Loads tools, resources, and prompts on success
    • Handles authentication errors with OAuth flow
    • Manages fallback between transport types

Transport Fallback Logic (Lines 443-486):

  • SSE-only mode: Direct SSE connection
  • HTTP-only mode: Direct HTTP connection
  • Auto mode: HTTP first, SSE fallback on specific errors (404, 405, CORS)

API Function Implementations (Lines 504-738)

Tool Calling (Lines 504-571):

  • Validates client readiness
  • Handles authentication errors with re-auth flow
  • Provides detailed error logging
  • Manages timeout handling

Resource Management (Lines 658-698):

  • Lists and refreshes available resources
  • Reads resource contents with proper error handling
  • Updates state atomically

Prompt Management (Lines 702-738):

  • Lists available prompts
  • Retrieves prompt messages with arguments
  • Handles server capabilities gracefully

Effects and Event Handling (Lines 740-821)

OAuth Callback Handler (Lines 743-767):

  • Listens for postMessage from OAuth popup
  • Validates message origin for security
  • Triggers reconnection on successful auth
  • Handles auth failures appropriately

Initial Connection Effect (Lines 770-801):

  • Sets up mount tracking
  • Initializes auth provider
  • Triggers initial connection
  • Cleanup on unmount

Auto-Retry Logic (Lines 804-821):

  • Monitors failed state
  • Implements configurable retry delays
  • Respects mount status and state changes

Key Design Patterns

1. Stable Callback Pattern

All callback functions use useCallback with carefully managed dependencies to prevent infinite re-renders while maintaining functionality.

2. Ref-Based State Management

Critical state is stored in refs (stateRef, autoReconnectRef) to allow access in callbacks without dependency cycles.

3. Transport Fallback Strategy

Automatic fallback from HTTP to SSE based on specific error conditions, with manual transport selection support.

4. Comprehensive Error Handling

  • Authentication errors trigger re-auth flows
  • Transport errors trigger fallback or reconnection
  • All errors are logged with detailed context
  • User-friendly error messages and manual recovery options

5. Security Considerations

  • URL sanitization to prevent XSS attacks
  • Origin validation for OAuth callbacks
  • Proper cleanup of timeouts and event listeners
  • Secure token storage with configurable prefixes

6. State Machine Architecture

Clear state transitions from discovering → authenticating → connecting → loading → ready, with proper error states and recovery paths.

Integration Points

1. Authentication System

  • Uses BrowserOAuthClientProvider for OAuth flows
  • Integrates with MCP SDK's auth function
  • Supports manual authentication triggers
  • Handles popup blocking gracefully

2. Transport Layer

  • Supports both SSE and HTTP transports
  • Automatic transport selection with fallback
  • Proper connection lifecycle management
  • Event-driven architecture

3. MCP Protocol Compliance

  • Full support for MCP tools, resources, and prompts
  • Proper JSON-RPC message handling
  • Schema validation using MCP SDK schemas
  • Capability discovery and negotiation

4. React Integration

  • Follows React hooks patterns
  • Proper cleanup and memory management
  • State updates respect component lifecycle
  • Debug logging for development

This implementation provides a robust, production-ready solution for integrating MCP servers into React applications with comprehensive error handling, authentication flows, and transport fallback mechanisms.