Files
broswer-automation/docs/MULTI_USER_SESSION_MANAGEMENT.md

223 lines
6.0 KiB
Markdown

# Multi-User Session Management
This document explains how the Chrome MCP extension and LiveKit agent handle multiple users with session-based isolation.
## Overview
The system now supports multiple users connecting simultaneously to the same MCP server with proper session isolation. Each connection gets a unique session ID and user ID, ensuring that commands from different users don't interfere with each other.
## Key Features
### 1. Automatic Session ID Generation
- **No Authentication Required**: Users don't need to authenticate
- **Random Session IDs**: Each connection gets a unique session ID
- **User Isolation**: Each user's commands are routed to their specific Chrome extension
### 2. Session Management Components
#### SessionManager (`app/remote-server/src/server/session-manager.ts`)
- Tracks all active connections and sessions
- Manages user-to-session mappings
- Handles session cleanup and expiration
- Provides session statistics
#### ConnectionRouter (`app/remote-server/src/server/connection-router.ts`)
- Routes messages to the correct Chrome extension based on session ID
- Implements load balancing for general requests
- Supports different routing strategies (newest, oldest, most active)
#### ChromeTools (Enhanced)
- Integrates with SessionManager and ConnectionRouter
- Provides session-aware tool calling
- Supports multi-user command routing
## How It Works
### 1. Connection Flow
```
1. Chrome Extension connects to ws://localhost:3001/chrome
2. Server generates random user ID: user_{timestamp}_{random}
3. Server creates session with unique session ID
4. Extension sends connection_info message
5. Server responds with session_info containing:
- userId
- sessionId
- connectionId
6. Extension stores session info for future requests
```
### 2. Message Routing
```
1. MCP client sends tool request to server
2. Server determines target session (by session ID, user ID, or load balancing)
3. ConnectionRouter finds appropriate Chrome extension connection
4. Message is sent to specific extension instance
5. Response is routed back through the same session
```
### 3. Session Isolation
Each user session is completely isolated:
- **Separate Chrome Extension Instance**: Each user connects their own extension
- **Independent Command Queues**: Commands don't interfere between users
- **Session-Specific State**: Each session maintains its own state
- **Resource Isolation**: No shared resources between sessions
## Configuration
### Chrome Extension
No configuration needed - sessions are created automatically on connection.
### Remote Server
The server automatically handles multi-user sessions with these defaults:
- Session cleanup interval: 60 seconds
- Stale connection threshold: 5 minutes
- Maximum inactive time: 1 hour
### LiveKit Agent
Enhanced with multi-user support:
```yaml
# agent-livekit/livekit_config.yaml
livekit:
room:
user_room_prefix: 'mcp-chrome-user-'
agent:
session:
max_inactive_time: 3600 # seconds
cleanup_interval: 300 # seconds
max_concurrent_sessions: 50
```
## Usage Examples
### 1. Multiple Users with Chrome Extensions
Each user installs the Chrome extension and connects:
```javascript
// User 1's extension connects
// Gets: userId: "user_1703123456_abc123", sessionId: "session_user_1703123456_abc123"
// User 2's extension connects
// Gets: userId: "user_1703123457_def456", sessionId: "session_user_1703123457_def456"
```
### 2. Cherry Studio Configuration
Each user configures Cherry Studio with the same server URL:
```json
{
"mcpServers": {
"chrome-mcp-remote-server": {
"type": "streamableHttp",
"url": "http://localhost:3001/mcp",
"description": "Remote Chrome MCP Server - Multi-User Support"
}
}
}
```
### 3. LiveKit Agent Sessions
Each user gets their own LiveKit room:
```python
# User 1 joins room: "mcp-chrome-user-user_1703123456_abc123"
# User 2 joins room: "mcp-chrome-user-user_1703123457_def456"
```
## Testing
Run the multi-user test script:
```bash
cd app/remote-server
node test-multi-user.js
```
This test:
1. Creates multiple simulated connections
2. Verifies unique session IDs
3. Tests message routing
4. Validates session isolation
## Monitoring
### Session Statistics
Get current session stats via the server API:
```javascript
// In ChromeTools
const stats = chromeTools.getSessionStats();
console.log(stats);
// Output:
// {
// totalUsers: 3,
// totalSessions: 3,
// totalConnections: 3,
// activeConnections: 3,
// pendingRequests: 0
// }
```
### Routing Statistics
```javascript
const routingStats = chromeTools.getRoutingStats();
console.log(routingStats);
```
### Connection Monitoring
The server logs all connection events:
- New connections with session info
- Message routing decisions
- Session cleanup events
- Connection state changes
## Troubleshooting
### Common Issues
1. **Sessions Not Isolated**
- Check that each Chrome extension instance is running in a separate browser profile
- Verify unique session IDs in server logs
2. **Commands Going to Wrong User**
- Check session ID routing in ConnectionRouter
- Verify message contains correct session context
3. **Session Cleanup Issues**
- Monitor session cleanup logs
- Adjust cleanup intervals if needed
### Debug Logging
Enable detailed logging in the remote server:
```javascript
// In server logs, look for:
// "🟢 [Chrome Extension] Connection registered"
// "📤 [Chrome Tools] Routed to connection"
// "🔧 [Chrome Tools] Calling tool with routing context"
```
## Architecture Benefits
1. **Scalability**: Supports many concurrent users
2. **Isolation**: Complete separation between user sessions
3. **Reliability**: Automatic cleanup and error recovery
4. **Simplicity**: No authentication complexity
5. **Flexibility**: Multiple routing strategies available
## Future Enhancements
- Persistent sessions across reconnections
- User preference storage
- Advanced load balancing algorithms
- Session sharing capabilities
- Performance metrics and analytics