### Project Setup and Development Commands Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/servers/hono-mcp/README.md Standard npm commands for managing the project lifecycle. 'npm install' installs dependencies, 'npm run dev' starts the development server, and 'npm run deploy' handles deployment. ```bash npm install npm run dev npm run deploy ``` -------------------------------- ### Install Dependencies and Start Development Server Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/README.md Installs project dependencies using pnpm and starts the local development server for building and testing the application. ```shell pnpm install pnpm dev ``` -------------------------------- ### Run Development Environment Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/README.md Commands to start the development environment, including the Inspector, Chat UI, and example MCP servers. ```bash pnpm dev ``` -------------------------------- ### Development Commands Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/AGENT.md Common commands for managing the development server, building the project, linting, deploying, and running tests using pnpm. ```bash pnpm dev # Starts the development server. ``` ```bash pnpm build # Runs TypeScript compilation then Vite build. ``` ```bash pnpm lint # Runs ESLint for code linting. ``` ```bash pnpm deploy # Builds and deploys the project using Wrangler. ``` ```bash pnpm test # Executes Playwright End-to-End tests. ``` ```bash pnpm test:ui # Runs Playwright test runner with a UI. ``` ```bash pnpm test:headed # Runs tests in a visible browser. ``` -------------------------------- ### Start Development Server Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/README.md Starts the development server, allowing for live reloading and iteration on the project. ```bash pnpm dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/README.md Installs all necessary project dependencies using the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Hono App with Cloudflare Bindings Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/servers/hono-mcp/README.md TypeScript example showing how to instantiate the Hono framework with Cloudflare Bindings. This provides type safety for Cloudflare-specific environment variables and services within your application. ```typescript // src/index.ts const app = new Hono<{ Bindings: CloudflareBindings }>() ``` -------------------------------- ### Build Project with pnpm Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/AGENT.md Command to compile TypeScript and build the project for production, using Vite for bundling and optimization. ```Shell pnpm build ``` -------------------------------- ### Project Commands Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Common commands for managing the development server, building, linting, deploying, and testing the project. These are typically executed via pnpm. ```shell pnpm dev # Starts the development server. pnpm build # Runs TypeScript compilation then Vite build. pnpm lint # Runs ESLint for code linting. pnpm deploy # Builds and deploys the project using Wrangler. pnpm test # Executes Playwright End-to-End tests. pnpm test:ui # Launches the Playwright test runner with a UI. pnpm test:headed # Runs Playwright tests in a visible browser. ``` -------------------------------- ### Install Test Dependencies Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/test/README.md Installs the necessary Node.js dependencies for running the integration tests using pnpm. ```bash cd test pnpm install ``` -------------------------------- ### Deploy Project with pnpm Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/AGENT.md Command to build and deploy the project, typically utilizing Wrangler for deployment to Cloudflare Workers. ```Shell pnpm deploy ``` -------------------------------- ### Project Build, Lint, and Test Commands Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/AGENT.md Commands for running development builds, production builds, and code quality checks using pnpm. Includes starting various servers and UI components. ```shell pnpm dev # Run development build with watch mode and start all examples/servers # Chat UI: http://localhost:5002 # Inspector: http://localhost:5001 # Hono MCP Server: http://localhost:5101 # CF Agents MCP Server: http://localhost:5102 ``` ```shell pnpm build # Build the project ``` ```shell pnpm check # Run prettier checks and TypeScript type checking ``` -------------------------------- ### Install use-mcp Package Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/README.md Demonstrates how to install the use-mcp React hook using different package managers like npm, pnpm, and yarn. ```bash npm install use-mcp # or pnpm add use-mcp # or yarn add use-mcp ``` -------------------------------- ### Development Commands Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/README.md Common commands for development, including starting the dev server, building the project, linting code, and running end-to-end tests. ```shell pnpm dev pnpm build pnpm lint pnpm test ``` -------------------------------- ### Install use-mcp Package Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/src/react/README.md Installs the `use-mcp` package along with its core dependencies, `@modelcontextprotocol/sdk`, `react`, and `react-dom`. Supports npm, yarn, and pnpm package managers. ```bash npm install use-mcp @modelcontextprotocol/sdk react react-dom ``` ```bash yarn add use-mcp @modelcontextprotocol/sdk react react-dom ``` ```bash pnpm add use-mcp @modelcontextprotocol/sdk react react-dom ``` -------------------------------- ### Run ESLint Linting with pnpm Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/AGENT.md Command to execute ESLint for static code analysis, ensuring adherence to defined code style and identifying potential issues. ```Shell pnpm lint ``` -------------------------------- ### React Component Example using use-mcp Hook Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/src/react/README.md Demonstrates how to use the use-mcp hook within a React component to manage connection state, display available prompts, and interact with the MCP server by fetching prompt data. It shows conditional rendering based on the hook's state and how to handle asynchronous operations like getting a prompt. ```javascript import React from 'react'; import useMcp from './useMcp'; // Assuming useMcp is in the same directory function MyChatComponent() { const mcp = useMcp({ url: "/sse", // Required: The /sse URL of your MCP server // Other options can be configured here, e.g.: // clientName: "MyChatApp", // debug: true }); return (

MCP Chat Interface

Connection State: {mcp.state}

{mcp.state === 'failed' && mcp.error && (

Error: {mcp.error}

)} {mcp.state === 'ready' && mcp.tools.length > 0 && (

Available Tools:

)} {/* Example: Working with Prompts */} {mcp.state === 'ready' && mcp.prompts.length > 0 && (

Available Prompts:

{mcp.prompts.map((prompt) => (
{prompt.name}
))}
)}
); } export default MyChatComponent; ``` -------------------------------- ### Local Storage Keys Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/MODEL_SELECTOR_GUIDE.md Demonstrates the keys used for storing user preferences and authentication tokens in local storage. These keys manage favorites, tokens, and the selected model. ```javascript const FAVORITES_KEY = "aiChatTemplate_favorites_v1"; const TOKEN_KEY_PREFIX = "aiChatTemplate_token_"; // Appended with provider name const SELECTED_MODEL_KEY = "aiChatTemplate_selectedModel"; ``` -------------------------------- ### Run Playwright Test Runner UI with pnpm Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/AGENT.md Command to launch the Playwright test runner with a graphical user interface, providing an interactive way to run and debug tests. ```Shell pnpm test:ui ``` -------------------------------- ### UI Indicators and Layout Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Guidelines for implementing user interface indicators and layout balance. This includes using emoji-based indicators for models and servers, formatting counts, and positioning UI elements for visual equilibrium. ```javascript import React from 'react'; interface ServerStatusProps { enabledServers: number; totalServers: number; enabledTools: number; totalTools: number; } const ServerStatusIndicator: React.FC = ({ enabledServers, totalServers, enabledTools, totalTools, }) => { return (
🧠 {enabledTools}/{totalTools} 🔌 {enabledServers}/{totalServers} servers
); }; // Example Usage: // // Layout suggestion: // Model selector on the left, MCP servers on the right. // Show 'none' for empty states instead of red symbols. export default ServerStatusIndicator; ``` -------------------------------- ### Run Playwright E2E Tests with pnpm Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/AGENT.md Command to execute end-to-end tests using Playwright, verifying the application's functionality across different browsers. ```Shell pnpm test ``` -------------------------------- ### Configure New MCP Servers Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/test/README.md Example TypeScript code for adding new MCP server configurations to the test suite, specifying server URL and expected tools. ```typescript const MCP_SERVERS = [ { name: 'hono-mcp', url: 'http://localhost:9901/mcp', expectedTools: 1, }, { name: 'new-server', url: 'http://localhost:9902/mcp', expectedTools: 2, }, ] ``` -------------------------------- ### Run Playwright Tests in Headed Browser with pnpm Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/AGENT.md Command to execute Playwright tests in a visible browser window, useful for debugging and observing test execution. ```Shell pnpm test:headed ``` -------------------------------- ### State Persistence with localStorage and sessionStorage Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Guidelines for managing application state persistence. localStorage is recommended for user preferences like model selection and server configurations, while sessionStorage is suggested for temporary state, such as a single server URL in legacy components. ```javascript // Storing user preferences in localStorage function saveUserPreferences(prefs) { localStorage.setItem('userPreferences', JSON.stringify(prefs)); } // Retrieving user preferences from localStorage function getUserPreferences() { const prefs = localStorage.getItem('userPreferences'); return prefs ? JSON.parse(prefs) : null; } // Storing temporary state in sessionStorage function saveTemporaryState(key, value) { sessionStorage.setItem(key, JSON.stringify(value)); } // Retrieving temporary state from sessionStorage function getTemporaryState(key) { const value = sessionStorage.getItem(key); return value ? JSON.parse(value) : null; } // Example: Storing multiple MCP servers // localStorage.setItem('mcpServers', JSON.stringify([{ id: 'server1', name: 'Dev Server' }])); // localStorage.setItem('mcpServerToolCounts', JSON.stringify({ server1: 5 })); // Clearing related data when removing servers function removeServerData(serverId) { // localStorage.removeItem(`server_${serverId}_config`); // localStorage.removeItem(`server_${serverId}_tools`); console.log(`Removing data for server: ${serverId}`); } ``` -------------------------------- ### CSS Styling and Animation Guidelines Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Recommendations for CSS styling, including Tailwind CSS usage, responsive design, and specific techniques for background animations using CSS filters and pseudo-elements. It also covers modal backdrop styling and interaction. ```css /* Background Animation using hue-rotate filter */ .animated-background { /* Using CSS custom properties for delay */ animation: hueRotate 5s infinite linear; animation-delay: calc(var(--hue-delay, 0) * 1s); } .animated-background::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100vh; background-size: 100% 100vh; background-repeat: repeat-y; z-index: -1; filter: hue-rotate(0deg); animation: hueRotate 5s infinite linear; } @keyframes hueRotate { from { filter: hue-rotate(0deg); } to { filter: hue-rotate(360deg); } } /* Modal Backdrop */ .modal-backdrop { background-color: rgba(0, 0, 0, 0.8); cursor: pointer; } /* Clickable element styling */ .clickable-element { cursor: pointer; } /* Preventing background scroll when modal is open */ body.modal-open { overflow: hidden; } ``` -------------------------------- ### Update Model Data Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/MODEL_SELECTOR_GUIDE.md Command to refresh the list of available AI models from the models.dev API. This ensures the UI displays the latest model information. ```bash pnpm update-models ``` -------------------------------- ### Cloudflare Type Generation Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/servers/hono-mcp/README.md Command to generate types based on your Worker configuration for Cloudflare integration. This ensures type safety when interacting with Cloudflare services. ```bash npm run cf-typegen ``` -------------------------------- ### Routing for OAuth Callback Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Guidelines for handling OAuth callback routes using React Router. The callback route, such as '/oauth/callback', should match the main application's styling and include loading indicators during the process. ```javascript import React from 'react'; import { Routes, Route } from 'react-router-dom'; import OAuthCallbackPage from './pages/OAuthCallbackPage'; // Assume this component exists import LoadingSpinner from './components/LoadingSpinner'; // Assume this component exists function AppRoutes() { return ( {/* Other routes */} } /> {/* ... */} ); } // In OAuthCallbackPage.tsx: // const OAuthCallbackPage = () => { // // Logic to handle OAuth callback, redirect, etc. // // Show loading indicator while processing // return ( //
//

Processing OAuth Callback...

// //
// ); // }; export default AppRoutes; ``` -------------------------------- ### IndexedDB Usage Pattern Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Guidelines for interacting with IndexedDB, emphasizing the use of typed interfaces and the async/await pattern for asynchronous operations. This ensures type safety and cleaner code for database interactions. ```typescript // Example of typed interface for IndexedDB data interface UserData { id: string; name: string; email: string; } // Example of async/await pattern for database operations async function getUser(userId: string): Promise { // Assume 'db' is an initialized IndexedDB database instance // const transaction = db.transaction(['users'], 'readonly'); // const store = transaction.objectStore('users'); // const request = store.get(userId); // return new Promise((resolve, reject) => { // request.onsuccess = () => resolve(request.result); // request.onerror = () => reject(request.error); // }); console.log(`Fetching user with ID: ${userId}`); // Placeholder for actual IndexedDB logic return Promise.resolve({ id: userId, name: 'Example User', email: 'user@example.com' }); } async function saveUser(userData: UserData): Promise { // Assume 'db' is an initialized IndexedDB database instance // const transaction = db.transaction(['users'], 'readwrite'); // const store = transaction.objectStore('users'); // store.put(userData); console.log('Saving user data:', userData); await Promise.resolve(); } ``` -------------------------------- ### Performance: Transform and Filter Animations Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Performance recommendations for animations. Avoid animating gradients directly as it causes repainting. Instead, leverage CSS `transform` and `filter` properties, which are hardware-accelerated and generally more performant. ```css /* Avoid this (can cause repainting) */ /* .gradient-animation { background: linear-gradient(to right, red, blue); animation: moveGradient 2s infinite alternate; } @keyframes moveGradient { from { background-position: 0% 50%; } to { background-position: 100% 50%; } } */ /* Prefer this (hardware accelerated) */ .transform-animation { animation: scaleUp 2s infinite ease-in-out; } @keyframes scaleUp { from { transform: scale(1); } to { transform: scale(1.1); } } .filter-animation { animation: hueRotate 5s infinite linear; } @keyframes hueRotate { from { filter: hue-rotate(0deg); } to { filter: hue-rotate(360deg); } } ``` -------------------------------- ### React Component and Hook Conventions Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Guidelines for structuring React components and custom hooks. Components should be React Function Components (FC) with explicit typing and PascalCase names. Custom hooks must start with 'use' and follow camelCase naming. ```typescript // Component Convention (PascalCase) import React from 'react'; interface MyComponentProps { message: string; } const MyComponent: React.FC = ({ message }) => { return
{message}
; }; export default MyComponent; // Hook Convention (camelCase, starts with 'use') import { useState, useEffect } from 'react'; function useFetchData(url: string): { data: T | null, loading: boolean, error: Error | null } { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const result = await response.json(); setData(result); } catch (err) { setError(err as Error); } finally { setLoading(false); } }; fetchData(); }, [url]); return { data, loading, error }; } export default useFetchData; ``` -------------------------------- ### Build and Deploy Application Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/README.md Builds the static assets for the application and deploys them to a hosting service like Cloudflare Pages. ```shell pnpm build pnpm run deploy ``` -------------------------------- ### Build use-mcp Library Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/inspector/README.md Navigate to the parent directory, build the `use-mcp` library, and return to the current directory. This is a prerequisite for running the demo. ```bash cd ../.. && pnpm build && cd - ``` -------------------------------- ### Configure OpenRouter OAuth Client ID Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/MODEL_SELECTOR_GUIDE.md Sets the OpenRouter client ID required for OAuth authentication. This environment variable should be added to your project's .env file. ```env VITE_OPENROUTER_CLIENT_ID=your_client_id_here ``` -------------------------------- ### Run All Integration Tests Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/test/README.md Executes all integration tests, displaying the browser window during execution. ```bash cd test pnpm test ``` -------------------------------- ### Integration Test Commands Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/AGENT.md Commands to execute integration tests located in the /test directory. Supports various modes including headless, headed, watch, and interactive UI. ```shell cd test && pnpm test # Run integration tests headlessly (default) ``` ```shell cd test && pnpm test:headed # Run integration tests with visible browser ``` ```shell cd test && pnpm test:headless # Run integration tests headlessly ``` ```shell cd test && pnpm test:watch # Run integration tests in watch mode ``` ```shell cd test && pnpm test:ui # Run integration tests with interactive UI ``` -------------------------------- ### Run Tests with Interactive UI Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/test/README.md Executes integration tests and provides an interactive user interface for managing test runs. ```bash cd test pnpm test:ui ``` -------------------------------- ### Run Integration Tests Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/README.md Commands for running integration tests in various modes: headlessly, headed, watch mode, and with an interactive UI. ```bash cd test && pnpm test # Run tests headlessly (default) cd test && pnpm test:headed # Run tests with visible browser cd test && pnpm test:watch # Run tests in watch mode cd test && pnpm test:ui # Run tests with interactive UI ``` -------------------------------- ### React Hook Usage: useMcp Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/README.md Example of using the `useMcp` React hook to connect to an MCP server, manage state, and interact with tools, resources, and prompts. It handles connection states, authentication, and provides functions for calling tools and reading resources. ```tsx import { useMcp } from 'use-mcp/react' function MyAIComponent() { const { state, tools, resources, prompts, error, callTool, readResource, getPrompt, retry, authenticate, clearStorage, } = useMcp({ url: 'https://your-mcp-server.com', clientName: 'My App', autoReconnect: true, }) if (state === 'failed') { return (

Connection failed: {error}

) } if (state !== 'ready') { return
Connecting to AI service...
} 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 (

Available Tools: {tools.length}

    {tools.map(tool => (
  • {tool.name}
  • ))}
{resources.length > 0 && (

Resources: {resources.length}

)} {prompts.length > 0 && (

Prompts: {prompts.length}

)}
) } ``` -------------------------------- ### Run Tests Headlessly Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/test/README.md Executes all integration tests without opening a browser window, suitable for CI environments. ```bash cd test pnpm test:headless ``` -------------------------------- ### use-mcp Hook API Reference Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/src/react/README.md Provides detailed documentation for the use-mcp hook, including all configurable options with their types, defaults, and descriptions, as well as a comprehensive list of returned values, methods, and their functionalities for interacting with an MCP server. ```APIDOC useMcp(options) Initializes and manages a connection to an MCP server using a React hook. Parameters: options (UseMcpOptions): An object containing configuration settings for the hook. Hook Options (UseMcpOptions): url (string, required): The /sse URL of your MCP server. clientName (string, optional): Name used for OAuth dynamic client registration. Defaults to "MCP React Client". clientUri (string, optional): Client URI used for OAuth registration. Defaults to window.location.origin. callbackUrl (string, optional): The absolute URL of your OAuth callback page. Must match the redirect URI registered with your OAuth server. Defaults to /oauth/callback on the current origin. storageKeyPrefix (string, optional): Prefix for keys used in localStorage (e.g., tokens, client info). Defaults to "mcp:auth". Useful to avoid conflicts. clientConfig (object, optional): Information about the client application sent during the MCP handshake. Includes: name (string, optional): Defaults to "mcp-react-client". version (string, optional): Defaults to "0.1.0". debug (boolean, optional): Enable verbose logging to the console and the log state array. Defaults to false. autoRetry (boolean | number, optional): If true or a number (milliseconds), automatically tries to reconnect if the initial connection fails. Defaults to false. Uses a 5000ms delay if set to true. autoReconnect (boolean | number, optional): If true or a number (milliseconds), automatically tries to reconnect if an established connection is lost. Defaults to 3000 (3 seconds). Set to false to disable. popupFeatures (string, optional): The features string passed to window.open for the OAuth popup. Defaults to "width=600,height=700,resizable=yes,scrollbars=yes,status=yes". Hook Return Value (UseMcpResult): tools (Array, optional): An array of Tool objects provided by the server. Empty until state is 'ready'. resources (Array, optional): An array of Resource objects representing data available from the server. resourceTemplates (Array, optional): An array of ResourceTemplate objects representing dynamic resources available from the server. prompts (Array, optional): An array of Prompt objects representing reusable prompt templates from the server. state (string): The current connection state. Possible values: 'discovering', 'authenticating', 'connecting', 'loading', 'ready', 'failed'. Use this to conditionally render UI or enable/disable features. error (string, optional): An error message if state is 'failed'. authUrl (string, optional): If authentication is required and the popup was potentially blocked, this URL string can be used to let the user manually open the auth page (e.g., ...). log (Array<{level: string, message: string, timestamp: Date}>, optional): An array of log messages. Useful for debugging when debug option is true. callTool(name: string, args?: object): async function to execute a tool on the MCP server. Throws an error if the client isn't ready or the call fails. listResources(): async function to refresh the list of available resources. Returns void. readResource(uri: string): async function to read the contents of a specific resource. Returns an object with a 'contents' array containing the resource data. listPrompts(): async function to refresh the list of available prompts. Returns void. getPrompt(name: string, args?: object): async function to get a specific prompt with optional arguments. Returns an object with a 'messages' array containing the prompt messages. retry(): Manually triggers a reconnection attempt if the state is 'failed'. disconnect(): Disconnects the client from the server. authenticate(): Manually attempts to start the authentication flow. Useful for triggering the popup via a user click if it was initially blocked. clearStorage(): Removes all authentication-related data (tokens, client info, code verifier, state) for the configured server URL from localStorage. Automatically disconnects the client. Setting up the OAuth Callback Route: Ensure a callback route (e.g., /oauth/callback) is created and configured in `callbackUrl`. This route must execute the `onMcpAuthorization` function exported from the main use-mcp package. Refer to the root README for an example. ``` -------------------------------- ### Component Visibility and Conditional Rendering Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/examples/chat-ui/AGENT.md Strategy for managing component visibility, particularly for disabled components. The recommendation is to keep disabled components within the React tree but hide them using CSS, rather than completely removing them via conditional rendering. This prevents MCP connections from being destroyed when modals close. ```javascript import React from 'react'; interface DisabledComponentWrapperProps { isDisabled: boolean; children: React.ReactNode; } const DisabledComponentWrapper: React.FC = ({ isDisabled, children, }) => { // Keep component in React tree but hide with CSS if disabled // This prevents MCP connections from being destroyed when modals close return (
{children}
); }; // Example Usage: // const isServerDisabled = true; // // // // Conditional rendering sparingly: // { !isServerDisabled && } export default DisabledComponentWrapper; ``` -------------------------------- ### API Reference for useMcp Hook Source: https://github.com/modelcontextprotocol/use-mcp/blob/main/README.md Detailed documentation for the `useMcp` React hook, outlining its configuration options and the properties and functions returned for managing MCP connections and interactions. ```APIDOC function useMcp(options: UseMcpOptions): UseMcpResult Options: - `url`: `string` (Required). URL of your MCP server - `clientName`: `string`. Name of your client for OAuth registration - `clientUri`: `string`. URI of your client for OAuth registration - `callbackUrl`: `string`. Custom callback URL for OAuth redirect (defaults to `/oauth/callback` on the current origin) - `storageKeyPrefix`: `string`. Storage key prefix for OAuth data in localStorage (defaults to "mcp:auth") - `clientConfig`: `object`. Custom configuration for the MCP client identity - `debug`: `boolean`. Whether to enable verbose debug logging - `autoRetry`: `boolean | number`. Auto retry connection if initial connection fails, with delay in ms - `autoReconnect`: `boolean | number`. Auto 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') - `preventAutoAuth`: `boolean`. Prevent automatic authentication popup on initial connection (default: false) Return Value: - `state`: `string`. Current connection state: 'discovering', 'pending_auth', 'authenticating', 'connecting', 'loading', 'ready', 'failed' - `tools`: `Tool[]`. Available tools from the MCP server - `resources`: `Resource[]`. Available resources from the MCP server - `resourceTemplates`: `ResourceTemplate[]`. Available resource templates from the MCP server - `prompts`: `Prompt[]`. Available prompts from the MCP server - `error`: `string | undefined`. Error message if connection failed - `authUrl`: `string | undefined`. Manual 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) => Promise`. Function to call a tool on the MCP server - `listResources`: `() => Promise`. Refresh the list of available resources - `readResource`: `(uri: string) => Promise<{ contents: Array }>`. Read the contents of a specific resource - `listPrompts`: `() => Promise`. Refresh the list of available prompts - `getPrompt`: `(name: string, args?: Record) => Promise<{ messages: Array }>`. Get a specific prompt with optional arguments - `retry`: `() => void`. Manually attempt to reconnect - `disconnect`: `() => void`. Disconnect from the MCP server - `authenticate`: `() => void`. Manually trigger authentication - `clearStorage`: `() => void`. Clear all stored authentication data ```