Chat UI Example Application Analysis
Overview
The chat-ui example is a comprehensive React-based chat application that demonstrates integration with multiple AI providers and MCP (Model Context Protocol) servers. It showcases how to use the use-mcp library in a real-world application with features like model selection, conversation management, and MCP tool integration.
Application Architecture
Project Structure
- React 19 with TypeScript
- Vite for build tooling
- Tailwind CSS for styling
- React Router for navigation
- IndexedDB for local data storage
- AI SDK for LLM integrations
- use-mcp for MCP server connections
Dependencies Analysis
Core Dependencies (package.json Lines 18-35)
- AI SDK Providers: Anthropic, Groq, OpenAI integrations
ai: Vercel AI SDK for streaming responsesuse-mcp: Local link to parent libraryidb: IndexedDB wrapper for data persistencereact-router-dom: Client-side routingreact-markdown: Markdown rendering with syntax highlightinghono: Server framework (likely for API routes)workers-ai-provider: Cloudflare Workers AI integration
Main Application Components
App.tsx - Application Router
Purpose: Defines the main routing structure for the application
Route Configuration (Lines 9-14):
/oauth/groq/callback: PKCE callback for Groq provider/oauth/openrouter/callback: PKCE callback for OpenRouter provider/oauth/callback: MCP OAuth callback (usesuse-mcplibrary)/: Main chat interface
Integration Points:
- Uses
use-mcp'sOAuthCallbackcomponent for MCP authentication - Supports multiple OAuth providers with different callback patterns
- Clean separation between MCP and AI provider authentication flows
components/OAuthCallback.tsx - MCP Authentication Handler
Purpose: Handles OAuth callbacks for MCP server authentication
Implementation (Lines 4-22):
- Line 6: Calls
onMcpAuthorization()fromuse-mcplibrary - Lines 10-21: Provides user-friendly loading interface
- Auto-close: Window closes automatically after authentication
UI Features:
- Loading spinner and status messages
- Responsive design with Tailwind CSS
- Clean user experience during auth flow
components/ChatApp.tsx - Main Application Component
State Management (Lines 17-27):
- Conversations: Array of chat conversations stored in IndexedDB
- Model Selection: Currently selected AI model with persistence
- MCP Tools: Tools available from connected MCP servers
- Sidebar: Responsive sidebar visibility
- API Keys: Trigger for API key updates
OAuth Integration (Lines 33-135):
- Message Handling (Lines 34-45): Listens for OAuth success messages from popups
- Token Polling (Lines 47-135): Fallback mechanism for detecting OAuth token changes
- Polls localStorage every 500ms for new tokens
- Supports Groq and OpenRouter providers
- Automatic cleanup when tokens are detected
Conversation Management (Lines 155-199):
- IndexedDB Integration: Persistent storage for conversations
- CRUD Operations: Create, read, update, delete conversations
- Cleanup Logic: Removes conversations with no messages
- Unique IDs: Timestamp-based conversation identification
components/McpServers.tsx - MCP Integration Component
Connection Management (Lines 6-23):
McpConnectionComponent: Wrapper foruseMcphook- Configuration: Debug mode, retry settings, popup configuration
- Auto-auth Prevention: Requires manual authentication trigger
State Management (Lines 25-50):
- Server URL: Persisted in sessionStorage
- Connection State: Tracks MCP connection status
- Tools Integration: Forwards MCP tools to parent components
- Settings UI: Toggle for connection configuration
Key Features:
- Manual Authentication: Uses
preventAutoAuth: truefor controlled auth flow - Debug Logging: Detailed connection and authentication logs
- Tool Forwarding: Makes MCP tools available to chat system
components/ConversationThread.tsx - Chat Interface
Props Interface (Lines 21-38):
- Conversation Data: Current conversations and state management
- Model Integration: Selected model and change handlers
- MCP Integration: Tools and update callbacks
- Database: IndexedDB instance for persistence
- Model Management: Favorites and model selection
Integration Points:
- Uses
useStreamResponsehook for AI responses - Integrates MCP tools with AI SDK
- Manages conversation persistence
- Handles model selection and API key management
Custom Hooks
hooks/useStreamResponse.ts - AI Response Streaming
Purpose: Manages streaming responses from AI providers with MCP tool integration
Configuration (Lines 18-34):
- Provider Integration: Supports multiple AI providers (Groq, Anthropic, OpenAI)
- MCP Tools: Converts MCP tools to AI SDK format
- Stream Management: Handles streaming text responses
- Error Handling: API key validation and error recovery
Tool Integration (Lines 46-50):
- Tool Conversion: Transforms MCP tool schemas to AI SDK format
- Schema Mapping: Maps MCP input schemas to AI tool parameters
- Tool Execution: Handles tool calls during AI responses
hooks/useModels.ts - Model Management
- Model Catalog: Manages available AI models
- Favorites: User-preferred models
- Provider Integration: Maps models to AI providers
hooks/useIndexedDB.ts - Data Persistence
- IndexedDB Wrapper: Simplified database operations
- Conversation Storage: Persistent chat history
- Migration Support: Database schema updates
hooks/useAutoscroll.ts - UI Behavior
- Auto-scroll: Keeps chat scrolled to bottom
- User Override: Respects manual scrolling
- Performance: Optimized scroll behavior
Authentication & OAuth Integration
Multiple OAuth Flows
- MCP Servers: Uses
use-mcplibrary's OAuth implementation - AI Providers: Custom PKCE flows for Groq and OpenRouter
- Fallback Mechanisms: Polling for token detection when popups fail
Token Management
- localStorage: Stores OAuth tokens with provider-specific keys
- Format:
aiChatTemplate_token_{providerId} - Validation: Checks for
access_tokenpresence - Cleanup: Automatic removal of invalid tokens
Security Considerations
- Origin Validation: postMessage communication validates origins
- Token Expiry: Handles token refresh and expiration
- Error Handling: Graceful degradation when auth fails
AI Provider Integration
Supported Providers
- Anthropic: Claude models via AI SDK
- Groq: Fast inference models
- OpenAI: GPT models and compatible providers
- OpenRouter: Multiple provider access
- Cloudflare Workers AI: Edge computing models
Model Selection
- Dynamic Catalog: Updates from provider APIs
- Favorites System: User-preferred models
- Persistence: Remembers selected model
- Capability Mapping: Tool support per model
MCP Integration Patterns
Tool Integration
- Schema Conversion: MCP tool schemas → AI SDK tool format
- Tool Execution: AI models can call MCP tools during responses
- Result Integration: Tool results incorporated into conversation
- Error Handling: Graceful failure when tools are unavailable
Connection Management
- Manual Control: User initiates MCP connections
- State Tracking: Visual feedback for connection status
- Debug Logging: Detailed connection and authentication logs
- Tool Discovery: Automatic detection of available tools
Data Architecture
IndexedDB Schema
- Conversations: Chat history with metadata
- Messages: Individual chat messages with types
- Settings: User preferences and configurations
State Management
- React State: Component-level state for UI
- Local Storage: API keys and OAuth tokens
- Session Storage: Temporary connection settings
- IndexedDB: Persistent conversation data
Deployment & Production
Build Configuration
- Vite: Modern build tooling with HMR
- TypeScript: Type safety and development experience
- Cloudflare Pages: Static site deployment
- Wrangler: Cloudflare deployment tooling
Performance Optimizations
- Code Splitting: Route-based chunks
- Lazy Loading: Dynamic imports for heavy components
- Caching: Service worker for offline support
- Compression: Build-time asset optimization
Key Learnings
1. Multi-Provider Architecture
The application successfully demonstrates how to integrate multiple AI providers and MCP servers in a single interface, providing users with flexibility and choice.
2. Authentication Complexity
Managing multiple OAuth flows (MCP + AI providers) requires careful state management and fallback mechanisms for various failure scenarios.
3. Tool Integration
The seamless integration of MCP tools with AI responses showcases the power of the Model Context Protocol for extending AI capabilities.
4. User Experience
The application prioritizes user experience with features like conversation persistence, model favorites, and graceful error handling.
5. Development Patterns
The codebase demonstrates modern React patterns with hooks, TypeScript, and clean component architecture that makes the use-mcp integration straightforward and maintainable.
This example serves as a comprehensive reference implementation for building production-ready chat applications with MCP integration, showcasing both the capabilities of the use-mcp library and best practices for real-world deployment.