# Cremote MCP Multi-Client Support

The Cremote MCP server now supports multiple concurrent clients with isolated browser sessions. This allows multiple AI agents or applications to use the same cremote daemon simultaneously without interfering with each other's browser state.

## Architecture Overview

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Client A      │    │   Client B      │    │   Client N      │
│   (Agent 1)     │    │   (Agent 2)     │    │   (Agent N)     │
└─────────┬───────┘    └─────────┬───────┘    └─────────┬───────┘
          │                      │                      │
          │ HTTP/Session         │ HTTP/Session         │ HTTP/Session
          │                      │                      │
          └──────────────────────┼──────────────────────┘
                                 │
                    ┌─────────────┴─────────────┐
                    │   Cremote MCP Server      │
                    │   (Session Manager)       │
                    └─────────────┬─────────────┘
                                  │
                                  │ TCP
                                  │
                    ┌─────────────┴─────────────┐
                    │   Cremote Daemon          │
                    │   (Shared Browser)        │
                    └─────────────┬─────────────┘
                                  │
                                  │ DevTools Protocol
                                  │
                    ┌─────────────┴─────────────┐
                    │   Chrome/Chromium         │
                    │   (All tabs accessible)  │
                    └───────────────────────────┘
```

## Transport Modes

### 1. stdio Transport (Single Client - Legacy)

**Default mode** - Maintains backward compatibility with existing clients.

```bash
# Default mode (stdio)
./cremote-mcp

# Or explicitly set
CREMOTE_TRANSPORT=stdio ./cremote-mcp
```

- **Clients**: 1 concurrent client
- **Communication**: stdin/stdout JSON-RPC
- **Session Management**: Single global state
- **Use Case**: Existing integrations, single-agent scenarios

### 2. HTTP Transport (Multiple Clients - New)

**Multi-client mode** - Supports concurrent clients with session isolation.

```bash
# Enable HTTP transport
CREMOTE_TRANSPORT=http ./cremote-mcp
```

- **Clients**: Multiple concurrent clients
- **Communication**: HTTP POST/GET with JSON-RPC
- **Session Management**: Per-client isolated sessions
- **Use Case**: Multiple agents, concurrent automation

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `CREMOTE_TRANSPORT` | `stdio` | Transport mode: `stdio` or `http` |
| `CREMOTE_HOST` | `localhost` | Cremote daemon host |
| `CREMOTE_PORT` | `8989` | Cremote daemon port |
| `CREMOTE_HTTP_HOST` | `localhost` | HTTP server host (HTTP mode only) |
| `CREMOTE_HTTP_PORT` | `8990` | HTTP server port (HTTP mode only) |

### Example Configurations

#### Single Client (Legacy)
```bash
export CREMOTE_HOST=localhost
export CREMOTE_PORT=8989
export CREMOTE_TRANSPORT=stdio
./cremote-mcp
```

#### Multiple Clients
```bash
export CREMOTE_HOST=localhost
export CREMOTE_PORT=8989
export CREMOTE_TRANSPORT=http
export CREMOTE_HTTP_HOST=localhost
export CREMOTE_HTTP_PORT=8990
./cremote-mcp
```

## Session Management

### Session Lifecycle

1. **Initialization**: Client sends `initialize` request, receives `Mcp-Session-Id` header
2. **Operations**: All subsequent requests include the session ID header
3. **Isolation**: Each session maintains independent browser state
4. **Cleanup**: Sessions auto-expire after 30 minutes of inactivity
5. **Termination**: Clients can explicitly terminate sessions with DELETE request

### Session State

Each client session maintains isolated state:

- **Current Tab**: Independent active tab tracking
- **Tab History**: Per-client tab navigation history
- **Iframe Context**: Independent iframe mode state
- **Screenshots**: Per-client screenshot collection

### Session Headers

HTTP clients must include session headers:

```http
POST /mcp HTTP/1.1
Content-Type: application/json
Accept: application/json
Mcp-Session-Id: a1b2c3d4e5f6g7h8
MCP-Protocol-Version: 2025-06-18

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "web_navigate_cremotemcp",
    "arguments": {
      "url": "https://example.com"
    }
  }
}
```

## Testing Multi-Client Setup

### Prerequisites

1. **Start Cremote Daemon**:
   ```bash
   cremotedaemon
   ```

2. **Start Chrome with Remote Debugging**:
   ```bash
   chromium --remote-debugging-port=9222 --user-data-dir=/tmp/chromium-debug
   ```

### Run Multi-Client Test

```bash
cd mcp/
./test_multiclient.sh
```

This test:
- Starts the MCP server in HTTP mode
- Creates 3 concurrent test clients
- Verifies each gets a unique session ID
- Tests session isolation
- Cleans up all sessions

### Manual Testing

1. **Start HTTP Server**:
   ```bash
   CREMOTE_TRANSPORT=http ./cremote-mcp
   ```

2. **Test with curl**:
   ```bash
   # Initialize session
   curl -X POST http://localhost:8990/mcp \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}'
   
   # Use returned Mcp-Session-Id for subsequent requests
   ```

## Benefits

### For AI Agents
- **Concurrent Operations**: Multiple agents can browse simultaneously
- **State Isolation**: No interference between agent sessions
- **Resource Sharing**: Shared browser instance reduces memory usage
- **Session Recovery**: Automatic cleanup prevents resource leaks

### For Developers
- **Scalability**: Support multiple concurrent automations
- **Debugging**: Isolated sessions simplify troubleshooting
- **Flexibility**: Choose transport mode based on use case
- **Compatibility**: Backward compatible with existing stdio clients

## Limitations

### Current Implementation
- **Tool Coverage**: Not all 27 tools are session-aware yet (work in progress)
- **SSE Streaming**: Server-Sent Events not implemented yet
- **Advanced Features**: Some MCP protocol features pending

### Planned Improvements
- Complete tool migration to session-aware handlers
- SSE support for real-time notifications
- Enhanced session management features
- Performance optimizations

## Migration Guide

### From Single Client to Multi-Client

1. **Update Environment**:
   ```bash
   # Old
   ./cremote-mcp
   
   # New
   CREMOTE_TRANSPORT=http ./cremote-mcp
   ```

2. **Update Client Code**:
   - Switch from stdio to HTTP transport
   - Handle session ID headers
   - Implement proper session cleanup

3. **Test Thoroughly**:
   - Verify session isolation
   - Test concurrent operations
   - Monitor resource usage

### Backward Compatibility

Existing stdio clients continue to work unchanged:
- No code changes required
- Same tool interface
- Same behavior and performance

## Troubleshooting

### Common Issues

1. **Session Not Found (404)**:
   - Session expired (30min timeout)
   - Invalid session ID
   - Server restart cleared sessions

2. **Port Conflicts**:
   - Change `CREMOTE_HTTP_PORT` if 8990 is in use
   - Ensure cremote daemon port (8989) is available

3. **CORS Issues**:
   - Server includes CORS headers for web clients
   - Use proper Accept headers in requests

### Debug Mode

Enable debug logging:
```bash
CREMOTE_TRANSPORT=http ./cremote-mcp 2>&1 | tee mcp-debug.log
```

## Next Steps

1. **Complete Tool Migration**: Migrate remaining tools to session-aware handlers
2. **Add SSE Support**: Implement Server-Sent Events for streaming
3. **Enhanced Testing**: Add comprehensive integration tests
4. **Performance Tuning**: Optimize session management and cleanup
5. **Documentation**: Complete API documentation and examples
