multiple agents

This commit is contained in:
Josh at WLTechBlog committed 2026-07-12 18:51:47 -07:00
1 parent ec391bd7ed
commit a399e1f365
6 files changed
+499 -658

No files matched your search

+111 -262
View File
@@ -1,278 +1,127 @@
# Cremote MCP Multi-Client Support
# Multi-Client / Multi-Agent 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.
This document describes how multiple AI agents (or CLI users) safely share a
single `cremotedaemon` + Chrome instance.
## Architecture Overview
## Architecture
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ 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) │
└───────────────────────────┘
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Agent 1 │ │ Agent 2 │ │ Agent N │
│ (LLM/CLI) │ │ (LLM/CLI) │ │ (LLM/CLI) │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ stdio │ stdio │ stdio (or HTTP CLI)
┌──────┴───────┐ ┌──────┴───────┐ ┌──────┴───────┐
│ cremote-mcp │ │ cremote-mcp │ │ cremote-mcp │ ← one MCP process
│ (process) │ │ (process) │ │ (process) │ per agent; each
│ currentTab, │ │ currentTab, │ │ currentTab, │ holds its OWN
│ iframeMode │ │ iframeMode │ │ iframeMode │ session state
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ HTTP (always sends an explicit tab id)
└──────────────────┼──────────────────┘
│
┌─────────────┴─────────────┐
│ cremotedaemon │ ← ONE shared daemon
│ (stateless re: current │ (no current tab, no history)
│ tab; per-tab maps keyed │
│ by Chrome TargetID) │
└─────────────┬─────────────┘
│ CDP / WebSocket
┌─────────────┴─────────────┐
│ Chrome / Chromium │
│ (all tabs accessible) │
└───────────────────────────┘
```
## Transport Modes
### How isolation is achieved
### 1. stdio Transport (Single Client - Legacy)
There is **no session layer** and **no daemon-side "current tab"**. Instead,
isolation comes from two properties:
**Default mode** - Maintains backward compatibility with existing clients.
1. **One `cremote-mcp` process per agent.** Each agent's MCP server is a
separate process with its own in-memory `currentTab`, `tabHistory`, and
`iframeMode`. There is no shared process state between agents. (The MCP
server is served over **stdio**; it does not run an HTTP listener.)
2. **The daemon requires an explicit tab id on every call** and keys all
per-tab state (cached page, iframe context, console logs) by the
globally-unique Chrome `TargetID`. Because each agent opens its own tabs
and always passes the tab id it received, two agents never address the same
map entry.
### What was removed and why
Earlier revisions of this guide described an HTTP transport with
`Mcp-Session-Id` headers and a daemon-tracked "current tab" / tab history.
Neither existed in the code: the MCP server only ever spoke stdio, and a
process-global `currentTab` is **not safe to share** across concurrent clients
(two agents that omit the tab id would silently operate on whichever tab was
touched last). The current-tab fallback was therefore removed entirely.
Concretely, in `daemon/daemon.go`:
- `Daemon.currentTab` and `Daemon.tabHistory` fields: **removed**.
- `getTabID()` (empty → current tab fallback) and `updateTabHistory()`:
**removed**.
- Every operation (`getTab`, `closeTab`, `switchToIframe`, `switchToMain`,
`getConsoleLogs`, and all 20+ command handlers) now returns
`tab id is required` when the tab id is empty.
- The single mutex was split into `stateMu`, which guards **only** the
`tabs` / `iframePages` / `consoleLogs` maps. Long Chrome DevTools Protocol
calls (notably `switchToIframe`'s element/frame waits, and `openTab`'s page
creation) now run **lock-free**, so one agent switching iframes no longer
blocks another agent clicking on a different tab.
## Implications for callers
### MCP clients
No change required. Each agent's MCP process already tracked its own
`currentTab` and always sent an explicit tab id to the daemon, so the
multi-agent workflow continues to work. If an agent's MCP process has not yet
opened/navigated a tab, tools that need a tab will now return
`tab id is required`; call `web_manage_tabs` (`open` or `switch`) first.
### CLI clients
You must now pass `--tab` on every command that operates on a tab. The
convenience of omitting `--tab` is gone. Capture the id from `open-tab`:
```bash
# Default mode (stdio)
./cremote-mcp
# Or explicitly set
CREMOTE_TRANSPORT=stdio ./cremote-mcp
TAB=$(cremote open-tab)
cremote load-url --tab="$TAB" --url="https://example.com"
cremote click-element --tab="$TAB" --selector="a.button"
cremote close-tab --tab="$TAB"
```
- **Clients**: 1 concurrent client
- **Communication**: stdin/stdout JSON-RPC
- **Session Management**: Single global state
- **Use Case**: Existing integrations, single-agent scenarios
### `list-tabs`
The `*` "current tab" marker and history-based ordering are gone. Tabs are
listed by id. `/status` no longer returns `current_tab` or `tab_history`;
clients that read those keys get empty values (graceful).
### 2. HTTP Transport (Multiple Clients - New)
## Remaining concurrency notes / future hardening
**Multi-client mode** - Supports concurrent clients with session isolation.
- **No tab ownership enforcement.** Any client can address any tab by id. This
is fine for trusted agents but means a fat-fingered id could touch another
agent's tab. Optional `tabOwners` tracking + a `--strict-ownership` flag is a
straightforward follow-up.
- **No per-tab lock.** Two concurrent operations against the *same* tab are the
caller's responsibility (each MCP process is request/response, so this does
not arise naturally). A per-tab mutex keyed by TargetID can be added if
needed.
- **Tab lifecycle.** Tabs opened by an MCP process are not auto-closed when
that process exits; agents should close their tabs. A `release-session`
cleanup hook is a future improvement.
```bash
# Enable HTTP transport
CREMOTE_TRANSPORT=http ./cremote-mcp
```
## Verification
- **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
- `daemon/daemon_test.go` covers the tab-required contract and concurrent
`consoleLogs` access; run with `go test -race ./daemon/...`.
- `TestMultiAgentIsolation` is a Chrome-backed integration test (several agents
open distinct tabs in parallel and assert no cross-agent content leak). Run
it with:
```bash
CREMOTE_INTEGRATION=1 go test -race -run TestMultiAgentIsolation ./daemon/...
```
It requires Chrome reachable on port 9222 via `http://localhost:9222/json/version`
(note: some environments resolve `localhost` to IPv6 `::1` while Chrome
listens on IPv4 `127.0.0.1`; ensure `localhost` resolves to IPv4 for the
discovery check to pass).