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
+479 -638

No files matched your search

+5 -30
View File
@@ -86,11 +86,13 @@ func (c *Client) GetVersion() (string, error) {
type TabInfo struct {
ID string `json:"id"`
URL string `json:"url"`
IsCurrent bool `json:"is_current"`
HistoryIndex int `json:"history_index"` // Position in tab history (higher = more recent)
}
// ListTabs returns a list of all open tabs
// ListTabs returns a list of all open tabs.
//
// The daemon no longer tracks a "current tab" or tab history (those concepts
// are not safe to share across multiple concurrent clients), so the status
// endpoint only reports the set of open tabs and their URLs.
func (c *Client) ListTabs() ([]TabInfo, error) {
resp, err := http.Get(c.serverURL + "/status")
if err != nil {
@@ -124,24 +126,6 @@ func (c *Client) ListTabs() ([]TabInfo, error) {
return nil, fmt.Errorf("unexpected tabs format")
}
// Get the current tab
currentTab, _ := data["current_tab"].(string)
// Get the tab history
tabHistoryData, ok := data["tab_history"].([]interface{})
if !ok {
tabHistoryData = []interface{}{}
}
// Create a map of tab history indices
tabHistoryIndices := make(map[string]int)
for i, idInterface := range tabHistoryData {
id, ok := idInterface.(string)
if ok {
tabHistoryIndices[id] = i
}
}
// Convert to TabInfo
tabs := make([]TabInfo, 0, len(tabsData))
for id, urlInterface := range tabsData {
@@ -149,18 +133,9 @@ func (c *Client) ListTabs() ([]TabInfo, error) {
if !ok {
url = "<unknown>"
}
// Get the history index (default to -1 if not in history)
historyIndex, inHistory := tabHistoryIndices[id]
if !inHistory {
historyIndex = -1
}
tabs = append(tabs, TabInfo{
ID: id,
URL: url,
IsCurrent: id == currentTab,
HistoryIndex: historyIndex,
})
}
+164 -343
View File
@@ -25,16 +25,26 @@ import (
const Version = "2.2.1-contrast-detection-fix"
// Daemon is the main server that manages browser connections
// Daemon is the main server that manages browser connections.
//
// Concurrency model: the daemon is stateless with respect to "current tab".
// Every operation requires an explicit tab id, which makes it safe for multiple
// clients (e.g. one MCP server process per agent, or multiple CLI invocations)
// to share a single daemon without interfering with each other. Per-tab state
// (cached page, iframe context, console logs) is keyed by the globally-unique
// Chrome TargetID, so distinct tabs never collide.
//
// stateMu guards ONLY the maps below. It must never be held while performing
// Chrome DevTools Protocol calls that can block (navigation, element waits,
// iframe resolution, etc.) - those run lock-free so clients on different tabs
// do not serialize each other.
type Daemon struct {
browser *rod.Browser
tabs map[string]*rod.Page
iframePages map[string]*rod.Page // Maps tab ID to iframe page context
currentTab string // ID of the current/last used tab
tabHistory []string // Stack of tab IDs in order of activation (LIFO)
consoleLogs map[string][]ConsoleLog // Maps tab ID to console logs
debug bool // Enable debug logging
mu sync.Mutex
stateMu sync.Mutex // Guards tabs, iframePages, consoleLogs only
server *http.Server
}
@@ -125,7 +135,6 @@ func NewDaemon(host string, port int, debug bool) (*Daemon, error) {
browser: browser,
tabs: make(map[string]*rod.Page),
iframePages: make(map[string]*rod.Page),
tabHistory: make([]string, 0),
consoleLogs: make(map[string][]ConsoleLog),
debug: debug,
}
@@ -172,12 +181,9 @@ func (d *Daemon) handleStatus(w http.ResponseWriter, r *http.Request) {
return
}
d.mu.Lock()
d.stateMu.Lock()
tabCount := len(d.tabs)
tabs := make(map[string]string)
currentTab := d.currentTab
tabHistory := make([]string, len(d.tabHistory))
copy(tabHistory, d.tabHistory)
// Get info about each tab
for id, page := range d.tabs {
@@ -190,7 +196,7 @@ func (d *Daemon) handleStatus(w http.ResponseWriter, r *http.Request) {
}
tabs[id] = try()
}
d.mu.Unlock()
d.stateMu.Unlock()
response := Response{
Success: true,
@@ -198,8 +204,6 @@ func (d *Daemon) handleStatus(w http.ResponseWriter, r *http.Request) {
"status": "running",
"tab_count": tabCount,
"tabs": tabs,
"current_tab": currentTab,
"tab_history": tabHistory,
},
}
@@ -2311,113 +2315,66 @@ func (d *Daemon) handleCommand(w http.ResponseWriter, r *http.Request) {
// openTab opens a new tab and returns its ID
func (d *Daemon) openTab(timeout int) (string, error) {
d.debugLog("Opening new tab with timeout: %d", timeout)
d.mu.Lock()
defer d.mu.Unlock()
// Create a context with timeout if specified
// createPage performs the CDP round-trip to create a new tab. It runs
// lock-free so that concurrent openTab calls from different clients do not
// serialize on stateMu (and do not block other clients' getTab lookups).
createPage := func() (*rod.Page, string, error) {
page, err := d.browser.Page(proto.TargetCreateTarget{URL: "about:blank"})
if err != nil {
return nil, "", fmt.Errorf("failed to create new tab: %w", err)
}
return page, string(page.TargetID), nil
}
var page *rod.Page
var tabID string
var err error
if timeout > 0 {
d.debugLog("Using timeout context: %d seconds", timeout)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
// Create a channel to signal completion
done := make(chan struct {
page *rod.Page
tabID string
err error
}, 1)
// Execute the tab creation in a goroutine
go func() {
page, err := d.browser.Page(proto.TargetCreateTarget{URL: "about:blank"})
var tabID string
if err == nil {
tabID = string(page.TargetID)
}
p, id, e := createPage()
done <- struct {
page *rod.Page
tabID string
err error
}{page, tabID, err}
}{p, id, e}
}()
// Wait for either completion or timeout
select {
case res := <-done:
if res.err != nil {
return "", fmt.Errorf("failed to create new tab: %w", res.err)
}
// Store the tab and update history
d.tabs[res.tabID] = res.page
d.tabHistory = append(d.tabHistory, res.tabID)
d.currentTab = res.tabID
// Set up console logging for this tab
d.setupConsoleLogging(res.tabID, res.page)
return res.tabID, nil
page, tabID, err = res.page, res.tabID, res.err
case <-ctx.Done():
return "", fmt.Errorf("opening tab timed out after %d seconds", timeout)
}
} else {
// No timeout
page, err := d.browser.Page(proto.TargetCreateTarget{URL: "about:blank"})
page, tabID, err = createPage()
}
if err != nil {
return "", fmt.Errorf("failed to create new tab: %w", err)
return "", err
}
// Use the page ID as the tab ID
tabID := string(page.TargetID)
// Register the tab. setupConsoleLogging touches consoleLogs and must be
// called with stateMu held.
d.stateMu.Lock()
defer d.stateMu.Unlock()
d.tabs[tabID] = page
// Add to tab history stack and set as current tab
d.tabHistory = append(d.tabHistory, tabID)
d.currentTab = tabID
// Set up console logging for this tab
d.setupConsoleLogging(tabID, page)
return tabID, nil
}
}
// getTabID returns the tab ID to use, falling back to the current tab if none is provided
func (d *Daemon) getTabID(tabID string) (string, error) {
d.mu.Lock()
defer d.mu.Unlock()
// If no tab ID is provided, use the current tab
if tabID == "" {
if d.currentTab == "" {
return "", fmt.Errorf("no current tab available, please open a tab first")
}
return d.currentTab, nil
}
// Otherwise, use the provided tab ID
return tabID, nil
}
// updateTabHistory updates the tab history stack when a tab is activated
func (d *Daemon) updateTabHistory(tabID string) {
// Set as current tab
d.currentTab = tabID
// Remove the tab from history if it's already there
for i, id := range d.tabHistory {
if id == tabID {
// Remove this tab from history
d.tabHistory = append(d.tabHistory[:i], d.tabHistory[i+1:]...)
break
}
}
// Add the tab to the end of history (most recent)
d.tabHistory = append(d.tabHistory, tabID)
}
// findPageByID finds a page by its ID without updating the current tab or cache
// findPageByID finds a page by its ID without updating the cache
func (d *Daemon) findPageByID(tabID string) (*rod.Page, error) {
// If not in memory, try to get the page from the browser
pages, err := d.browser.Pages()
@@ -2456,134 +2413,105 @@ func (d *Daemon) findPageByID(tabID string) (*rod.Page, error) {
return nil, fmt.Errorf("tab not found: %s", tabID)
}
// getTab returns a tab by its ID, checking for iframe context first
// getTab returns the page for a tab, checking for an iframe context first.
// tabID is required; the daemon no longer tracks a "current tab" because that
// state cannot be shared safely across multiple concurrent clients.
func (d *Daemon) getTab(tabID string) (*rod.Page, error) {
// Get the tab ID to use (may be the current tab)
actualTabID, err := d.getTabID(tabID)
if tabID == "" {
return nil, fmt.Errorf("tab id is required")
}
// Fast path: serve from cached iframe context or main-page cache. Only the
// map lookups happen under stateMu, so this never blocks on Chrome.
d.stateMu.Lock()
if p, ok := d.iframePages[tabID]; ok {
d.stateMu.Unlock()
return p, nil
}
if p, ok := d.tabs[tabID]; ok {
d.stateMu.Unlock()
return p, nil
}
d.stateMu.Unlock()
// Slow path: the tab exists in Chrome but isn't cached yet (e.g. the daemon
// was restarted while the browser kept running, or the tab was opened
// outside the daemon). findPageByID does a CDP round-trip and runs lock-free
// so it does not block other clients.
page, err := d.findPageByID(tabID)
if err != nil {
return nil, err
}
d.mu.Lock()
defer d.mu.Unlock()
// First check if we have an iframe context for this tab
if iframePage, exists := d.iframePages[actualTabID]; exists {
// Update tab history and current tab
d.updateTabHistory(actualTabID)
return iframePage, nil
d.stateMu.Lock()
defer d.stateMu.Unlock()
// Another goroutine may have cached the same tab in the meantime.
if cached, ok := d.tabs[tabID]; ok {
return cached, nil
}
// Check in-memory cache for main page
page, exists := d.tabs[actualTabID]
if exists {
// Update tab history and current tab
d.updateTabHistory(actualTabID)
d.tabs[tabID] = page
d.setupConsoleLogging(tabID, page)
d.debugLog("Found and cached existing tab %s from browser", tabID)
return page, nil
}
// If not in memory, try to find it
// Note: This can happen if the daemon was restarted but the browser is still running,
// or if a tab was created outside of the daemon. Pages retrieved this way may have
// initialization issues (see findPageByID for details).
page, err = d.findPageByID(actualTabID)
if err != nil {
return nil, err
}
// If found, cache it for future use and set up console logging
if page != nil {
d.tabs[actualTabID] = page
// Set up console logging for this tab since it wasn't created through openTab
d.setupConsoleLogging(actualTabID, page)
// Update tab history and current tab
d.updateTabHistory(actualTabID)
d.debugLog("Found and cached existing tab %s from browser", actualTabID)
return page, nil
}
return nil, fmt.Errorf("tab not found: %s", actualTabID)
}
// closeTab closes a tab by its ID
// closeTab closes a tab by its ID. tabID is required.
func (d *Daemon) closeTab(tabID string, timeout int) error {
// Get the tab ID to use (may be the current tab)
actualTabID, err := d.getTabID(tabID)
if err != nil {
return err
if tabID == "" {
return fmt.Errorf("tab id is required")
}
// First remove from our internal map to avoid future references
d.mu.Lock()
page, exists := d.tabs[actualTabID]
delete(d.tabs, actualTabID)
// Remove from our internal maps first to avoid future references.
d.stateMu.Lock()
page, exists := d.tabs[tabID]
delete(d.tabs, tabID)
delete(d.iframePages, tabID)
delete(d.consoleLogs, tabID)
d.stateMu.Unlock()
// Remove the tab from history
for i, id := range d.tabHistory {
if id == actualTabID {
// Remove this tab from history
d.tabHistory = append(d.tabHistory[:i], d.tabHistory[i+1:]...)
break
}
}
// If we closed the current tab, set it to the previous tab in history
if d.currentTab == actualTabID {
if len(d.tabHistory) > 0 {
// Set current tab to the most recent tab in history
d.currentTab = d.tabHistory[len(d.tabHistory)-1]
} else {
// No tabs left in history, clear the current tab
d.currentTab = ""
}
}
d.mu.Unlock()
// If the page doesn't exist in our cache, try to find it
// If the page isn't in our cache, try to resolve it (it may still be open in
// the browser). This runs lock-free.
if !exists {
var err error
page, err = d.findPageByID(actualTabID)
page, err = d.findPageByID(tabID)
if err != nil {
// If we can't find the page, it might already be closed
// If we can't find the page, it might already be closed.
return nil
}
}
if page == nil {
return nil
}
if timeout > 0 {
// Use timeout for closing the tab
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
// Create a channel to signal completion
done := make(chan error, 1)
// Execute the close in a goroutine
go func() {
err := page.Close()
done <- err
done <- page.Close()
}()
// Wait for either completion or timeout
select {
case err := <-done:
if err != nil {
// Log the error but don't return it, as we've already removed it from our map
fmt.Printf("Warning: failed to close tab %s: %v\n", actualTabID, err)
fmt.Printf("Warning: failed to close tab %s: %v\n", tabID, err)
}
return nil
case <-ctx.Done():
return fmt.Errorf("closing tab timed out after %d seconds", timeout)
}
} else {
// No timeout - try to close the page, but don't fail if it's already closed
err = page.Close()
if err != nil {
// Log the error but don't return it, as we've already removed it from our map
fmt.Printf("Warning: failed to close tab %s: %v\n", actualTabID, err)
}
return nil
// No timeout - try to close the page, but don't fail if it's already closed
if err := page.Close(); err != nil {
fmt.Printf("Warning: failed to close tab %s: %v\n", tabID, err)
}
return nil
}
// loadURL loads a URL in a tab
@@ -3669,49 +3597,52 @@ func (d *Daemon) takeScreenshotEnhanced(tabID, outputPath string, fullPage bool,
func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
d.debugLog("Switching to iframe: selector=%s, tab=%s, timeout=%d", selector, tabID, timeout)
// Get the main page first (not iframe context)
actualTabID, err := d.getTabID(tabID)
if err != nil {
d.debugLog("Failed to get tab ID: %v", err)
return err
if tabID == "" {
return fmt.Errorf("tab id is required")
}
d.mu.Lock()
defer d.mu.Unlock()
// Resolve the MAIN page (bypassing any existing iframe context). Only the
// cache lookup is done under stateMu; the findPageByID fallback (a CDP
// round-trip) runs lock-free.
d.stateMu.Lock()
mainPage, exists := d.tabs[tabID]
d.stateMu.Unlock()
// Get the main page (bypass iframe context)
mainPage, exists := d.tabs[actualTabID]
if !exists {
d.debugLog("Tab %s not in cache, trying to find it", actualTabID)
// Try to find it
mainPage, err = d.findPageByID(actualTabID)
d.debugLog("Tab %s not in cache, trying to find it", tabID)
var err error
mainPage, err = d.findPageByID(tabID)
if err != nil {
d.debugLog("Failed to find tab %s: %v", actualTabID, err)
d.debugLog("Failed to find tab %s: %v", tabID, err)
return err
}
if mainPage == nil {
d.debugLog("Tab %s not found", actualTabID)
return fmt.Errorf("tab not found: %s", actualTabID)
d.debugLog("Tab %s not found", tabID)
return fmt.Errorf("tab not found: %s", tabID)
}
d.tabs[actualTabID] = mainPage
d.stateMu.Lock()
if _, ok := d.tabs[tabID]; !ok {
d.tabs[tabID] = mainPage
}
d.stateMu.Unlock()
}
d.debugLog("Found main page for tab %s, looking for iframe element", actualTabID)
d.debugLog("Found main page for tab %s, looking for iframe element", tabID)
// Find the iframe element with timeout
// Find the iframe element. This is a potentially long CDP operation and is
// performed WITHOUT holding stateMu so that clients operating on other tabs
// are not blocked while we wait.
var iframeElement *rod.Element
var err error
if timeout > 0 {
// Use timeout context for finding the iframe element
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
// Create a channel to signal completion
done := make(chan struct {
element *rod.Element
err error
}, 1)
// Execute the element search in a goroutine
go func() {
defer func() {
if r := recover(); r != nil {
@@ -3729,7 +3660,6 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
}{element, err}
}()
// Wait for either completion or timeout
select {
case result := <-done:
iframeElement = result.element
@@ -3739,7 +3669,6 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
return fmt.Errorf("failed to find iframe element (timeout after %ds): %s", timeout, selector)
}
} else {
// No timeout
iframeElement, err = mainPage.Element(selector)
}
@@ -3750,20 +3679,17 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
d.debugLog("Found iframe element, getting frame context")
// Get the iframe's page context with timeout
// Get the iframe's page context. Also a long CDP operation; runs lock-free.
var iframePage *rod.Page
if timeout > 0 {
// Use timeout context for getting the frame
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
// Create a channel to signal completion
done := make(chan struct {
page *rod.Page
err error
}, 1)
// Execute the frame access in a goroutine
go func() {
defer func() {
if r := recover(); r != nil {
@@ -3781,7 +3707,6 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
}{page, err}
}()
// Wait for either completion or timeout
select {
case result := <-done:
iframePage = result.page
@@ -3791,7 +3716,6 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
return fmt.Errorf("failed to get iframe context (timeout after %ds)", timeout)
}
} else {
// No timeout
iframePage, err = iframeElement.Frame()
}
@@ -3800,37 +3724,34 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
return fmt.Errorf("failed to get iframe context: %w", err)
}
// Store the iframe page context
d.iframePages[actualTabID] = iframePage
d.debugLog("Successfully switched to iframe context for tab %s", actualTabID)
// Store the iframe page context (brief critical section).
d.stateMu.Lock()
d.iframePages[tabID] = iframePage
d.stateMu.Unlock()
d.debugLog("Successfully switched to iframe context for tab %s", tabID)
return nil
}
// switchToMain switches back to the main page context
// switchToMain switches back to the main page context. tabID is required.
func (d *Daemon) switchToMain(tabID string) error {
d.debugLog("Switching back to main context: tab=%s", tabID)
// Get the tab ID to use (may be the current tab)
actualTabID, err := d.getTabID(tabID)
if err != nil {
d.debugLog("Failed to get tab ID: %v", err)
return err
if tabID == "" {
return fmt.Errorf("tab id is required")
}
d.mu.Lock()
defer d.mu.Unlock()
d.stateMu.Lock()
defer d.stateMu.Unlock()
// Check if there was an iframe context to remove
if _, exists := d.iframePages[actualTabID]; exists {
d.debugLog("Removing iframe context for tab %s", actualTabID)
// Remove the iframe context for this tab
delete(d.iframePages, actualTabID)
if _, exists := d.iframePages[tabID]; exists {
d.debugLog("Removing iframe context for tab %s", tabID)
delete(d.iframePages, tabID)
} else {
d.debugLog("No iframe context found for tab %s", actualTabID)
d.debugLog("No iframe context found for tab %s", tabID)
}
d.debugLog("Successfully switched back to main context for tab %s", actualTabID)
d.debugLog("Successfully switched back to main context for tab %s", tabID)
return nil
}
@@ -3943,8 +3864,8 @@ func (d *Daemon) setupConsoleLogging(tabID string, page *rod.Page) {
// Listen for console events
go page.EachEvent(func(e *proto.RuntimeConsoleAPICalled) {
d.mu.Lock()
defer d.mu.Unlock()
d.stateMu.Lock()
defer d.stateMu.Unlock()
// Convert console level
level := string(e.Type)
@@ -3985,16 +3906,11 @@ func (d *Daemon) setupConsoleLogging(tabID string, page *rod.Page) {
// getConsoleLogs retrieves console logs for a tab
func (d *Daemon) getConsoleLogs(tabID string, clear bool) ([]ConsoleLog, error) {
d.mu.Lock()
defer d.mu.Unlock()
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
d.stateMu.Lock()
defer d.stateMu.Unlock()
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
// Check if tab exists
@@ -4018,13 +3934,8 @@ func (d *Daemon) getConsoleLogs(tabID string, clear bool) ([]ConsoleLog, error)
// executeConsoleCommand executes a command in the browser console
func (d *Daemon) executeConsoleCommand(tabID, command string, timeout int) (string, error) {
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return "", fmt.Errorf("no tab specified and no current tab available")
return "", fmt.Errorf("tab id is required")
}
// Execute the command as JavaScript and return the result
@@ -4079,13 +3990,8 @@ type TextExtractionResult struct {
// checkElement checks various states of an element
func (d *Daemon) checkElement(tabID, selector, checkType string, timeout int) (*ElementCheckResult, error) {
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, exists := d.tabs[tabID]
@@ -4187,13 +4093,8 @@ func (d *Daemon) checkElement(tabID, selector, checkType string, timeout int) (*
// getElementAttributes gets attributes, properties, and computed styles of an element
func (d *Daemon) getElementAttributes(tabID, selector, attributes string, timeout int) (map[string]interface{}, error) {
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, exists := d.tabs[tabID]
@@ -4329,13 +4230,8 @@ func (d *Daemon) getElementAttributes(tabID, selector, attributes string, timeou
// countElements counts the number of elements matching a selector
func (d *Daemon) countElements(tabID, selector string, timeout int) (int, error) {
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return 0, fmt.Errorf("no tab specified and no current tab available")
return 0, fmt.Errorf("tab id is required")
}
page, exists := d.tabs[tabID]
@@ -4371,13 +4267,8 @@ func (d *Daemon) countElements(tabID, selector string, timeout int) (int, error)
// extractMultiple extracts data from multiple selectors in a single call
func (d *Daemon) extractMultiple(tabID, selectorsJSON string, timeout int) (*MultipleExtractionResult, error) {
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, exists := d.tabs[tabID]
@@ -4466,13 +4357,8 @@ func (d *Daemon) extractMultiple(tabID, selectorsJSON string, timeout int) (*Mul
// extractLinks extracts all links from the page with optional filtering
func (d *Daemon) extractLinks(tabID, containerSelector, hrefPattern, textPattern string, timeout int) (*LinksExtractionResult, error) {
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, exists := d.tabs[tabID]
@@ -4571,13 +4457,8 @@ func (d *Daemon) extractLinks(tabID, containerSelector, hrefPattern, textPattern
// extractTable extracts table data as structured JSON
func (d *Daemon) extractTable(tabID, selector string, includeHeaders bool, timeout int) (*TableExtractionResult, error) {
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, exists := d.tabs[tabID]
@@ -4684,13 +4565,8 @@ func (d *Daemon) extractTable(tabID, selector string, includeHeaders bool, timeo
// extractText extracts text content with optional pattern matching
func (d *Daemon) extractText(tabID, selector, pattern, extractType string, timeout int) (*TextExtractionResult, error) {
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, exists := d.tabs[tabID]
@@ -6416,13 +6292,8 @@ func (d *Daemon) getAccessibilityTree(tabID string, depth *int, timeout int) (*A
func (d *Daemon) getAccessibilityTreeWithContrast(tabID string, depth *int, includeContrast bool, timeout int) (*AccessibilityTreeResult, error) {
d.debugLog("Getting accessibility tree for tab: %s with depth: %v, includeContrast: %v, timeout: %d", tabID, depth, includeContrast, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -6596,13 +6467,8 @@ func (d *Daemon) convertProtoAXValue(protoValue *proto.AccessibilityAXValue) *AX
func (d *Daemon) getPartialAccessibilityTree(tabID, selector string, fetchRelatives bool, timeout int) (*AccessibilityTreeResult, error) {
d.debugLog("Getting partial accessibility tree for tab: %s, selector: %s, fetchRelatives: %v, timeout: %d", tabID, selector, fetchRelatives, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -6657,13 +6523,8 @@ func (d *Daemon) getPartialAccessibilityTree(tabID, selector string, fetchRelati
func (d *Daemon) queryAccessibilityTree(tabID, selector, accessibleName, role string, timeout int) (*AccessibilityQueryResult, error) {
d.debugLog("Querying accessibility tree for tab: %s, selector: %s, name: %s, role: %s, timeout: %d", tabID, selector, accessibleName, role, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return nil, fmt.Errorf("no tab specified and no current tab available")
return nil, fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -6731,13 +6592,8 @@ func (d *Daemon) queryAccessibilityTree(tabID, selector, accessibleName, role st
func (d *Daemon) setCacheDisabled(tabID string, disabled bool, timeout int) error {
d.debugLog("Setting cache disabled=%v for tab: %s with timeout: %d", disabled, tabID, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return fmt.Errorf("no tab specified and no current tab available")
return fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -6784,13 +6640,8 @@ func (d *Daemon) setCacheDisabled(tabID string, disabled bool, timeout int) erro
func (d *Daemon) clearBrowserCache(tabID string, timeout int) error {
d.debugLog("Clearing browser cache for tab: %s with timeout: %d", tabID, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return fmt.Errorf("no tab specified and no current tab available")
return fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -6837,13 +6688,8 @@ func (d *Daemon) clearBrowserCache(tabID string, timeout int) error {
func (d *Daemon) clearAllSiteData(tabID string, timeout int) error {
d.debugLog("Clearing all site data for tab: %s with timeout: %d", tabID, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return fmt.Errorf("no tab specified and no current tab available")
return fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -6897,13 +6743,8 @@ func (d *Daemon) clearAllSiteData(tabID string, timeout int) error {
func (d *Daemon) clearCookies(tabID string, timeout int) error {
d.debugLog("Clearing cookies for tab: %s with timeout: %d", tabID, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return fmt.Errorf("no tab specified and no current tab available")
return fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -6957,13 +6798,8 @@ func (d *Daemon) clearCookies(tabID string, timeout int) error {
func (d *Daemon) clearStorage(tabID string, timeout int) error {
d.debugLog("Clearing storage for tab: %s with timeout: %d", tabID, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return fmt.Errorf("no tab specified and no current tab available")
return fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -7017,13 +6853,8 @@ func (d *Daemon) clearStorage(tabID string, timeout int) error {
func (d *Daemon) dragAndDrop(tabID, sourceSelector, targetSelector string, timeout int) error {
d.debugLog("Performing drag and drop from %s to %s for tab: %s with timeout: %d", sourceSelector, targetSelector, tabID, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return fmt.Errorf("no tab specified and no current tab available")
return fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -7070,13 +6901,8 @@ func (d *Daemon) dragAndDrop(tabID, sourceSelector, targetSelector string, timeo
func (d *Daemon) dragAndDropToCoordinates(tabID, sourceSelector string, targetX, targetY, timeout int) error {
d.debugLog("Performing drag and drop from %s to coordinates (%d, %d) for tab: %s with timeout: %d", sourceSelector, targetX, targetY, tabID, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return fmt.Errorf("no tab specified and no current tab available")
return fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
@@ -7123,13 +6949,8 @@ func (d *Daemon) dragAndDropToCoordinates(tabID, sourceSelector string, targetX,
func (d *Daemon) dragAndDropByOffset(tabID, sourceSelector string, offsetX, offsetY, timeout int) error {
d.debugLog("Performing drag and drop from %s by offset (%d, %d) for tab: %s with timeout: %d", sourceSelector, offsetX, offsetY, tabID, timeout)
// Use current tab if not specified
if tabID == "" {
tabID = d.currentTab
}
if tabID == "" {
return fmt.Errorf("no tab specified and no current tab available")
return fmt.Errorf("tab id is required")
}
page, err := d.getTab(tabID)
+169
View File
@@ -0,0 +1,169 @@
package daemon
import (
"fmt"
"net"
"os"
"strings"
"sync"
"testing"
"github.com/go-rod/rod"
)
// newZeroDaemon builds a Daemon with only the in-memory maps initialized and no
// browser connection. It is sufficient to exercise the entry points that
// validate their tab id before any Chrome DevTools Protocol call.
func newZeroDaemon() *Daemon {
return &Daemon{
tabs: make(map[string]*rod.Page),
iframePages: make(map[string]*rod.Page),
consoleLogs: make(map[string][]ConsoleLog),
}
}
// TestTabRequired verifies the core multi-agent invariant: the daemon no longer
// keeps a "current tab", so every operation that takes a tab id must reject an
// empty one up front instead of silently falling back to shared state. Each of
// these returns before touching the browser, so they can be tested without
// Chrome.
func TestTabRequired(t *testing.T) {
d := newZeroDaemon()
tests := []struct {
name string
fn func() error
}{
{"getTab", func() error { _, err := d.getTab(""); return err }},
{"closeTab", func() error { return d.closeTab("", 0) }},
{"switchToMain", func() error { return d.switchToMain("") }},
{"switchToIframe", func() error { return d.switchToIframe("", "#i", 0) }},
{"getConsoleLogs", func() error { _, err := d.getConsoleLogs("", false); return err }},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := tc.fn()
if err == nil {
t.Fatalf("%s: expected an error for empty tab id, got nil", tc.name)
}
if !strings.Contains(strings.ToLower(err.Error()), "required") {
t.Fatalf("%s: error should mention 'required', got: %v", tc.name, err)
}
})
}
}
// TestConsoleLogsConcurrent hammers getConsoleLogs from many goroutines (some
// clearing, some reading) to confirm the per-tab log storage is race-free under
// the stateMu discipline. Run with -race to catch any unprotected access.
func TestConsoleLogsConcurrent(t *testing.T) {
d := newZeroDaemon()
const tabs = 8
for i := 0; i < tabs; i++ {
id := fmt.Sprintf("tab-%d", i)
// getConsoleLogs only checks tab existence via d.tabs, so a nil page
// entry is enough to let it reach the consoleLogs storage.
d.tabs[id] = nil
logs := make([]ConsoleLog, 0, 64)
for j := 0; j < 64; j++ {
logs = append(logs, ConsoleLog{Level: "info", Message: fmt.Sprintf("m-%d-%d", i, j)})
}
d.consoleLogs[id] = logs
}
const goroutines = 64
var wg sync.WaitGroup
wg.Add(goroutines)
for g := 0; g < goroutines; g++ {
go func(g int) {
defer wg.Done()
id := fmt.Sprintf("tab-%d", g%tabs)
_, err := d.getConsoleLogs(id, g%2 == 0) // every other call clears
if err != nil {
t.Errorf("getConsoleLogs(%q): %v", id, err)
}
}(g)
}
wg.Wait()
}
// TestMultiAgentIsolation is an integration test that requires a Chrome running
// with remote debugging on port 9222. It is gated behind CREMOTE_INTEGRATION=1
// so that `go test` does not open tabs in the host browser by default. When
// enabled, run with -race to verify concurrent multi-agent access is race-free
// and that each agent's tab content is isolated:
//
// CREMOTE_INTEGRATION=1 go test -race -run TestMultiAgentIsolation ./daemon/...
func TestMultiAgentIsolation(t *testing.T) {
if os.Getenv("CREMOTE_INTEGRATION") != "1" {
t.Skip("set CREMOTE_INTEGRATION=1 to run the Chrome-backed integration test")
}
if !checkChromeDevTools(9222) {
t.Skip("chrome remote debugging not available on :9222")
}
d, err := NewDaemon("127.0.0.1", freePort(t), false)
if err != nil {
t.Fatalf("NewDaemon: %v", err)
}
t.Cleanup(func() { _ = d.Stop() })
go func() { _ = d.Start() }()
const agents = 6
var wg sync.WaitGroup
errs := make([]error, agents)
tabs := make([]string, agents)
wg.Add(agents)
for a := 0; a < agents; a++ {
go func(agent int) {
defer wg.Done()
tab, err := d.openTab(30)
if err != nil {
errs[agent] = fmt.Errorf("openTab: %w", err)
return
}
tabs[agent] = tab
marker := fmt.Sprintf("AGENT-MARKER-%d", agent)
url := "data:text/html,<html><body><h1>" + marker + "</h1></body></html>"
if err := d.loadURL(tab, url, 30); err != nil {
errs[agent] = fmt.Errorf("loadURL: %w", err)
return
}
src, err := d.getPageSource(tab, 30)
if err != nil {
errs[agent] = fmt.Errorf("getPageSource: %w", err)
return
}
if !strings.Contains(src, marker) {
errs[agent] = fmt.Errorf("agent %d: page source missing %q (possible cross-agent leak)", agent, marker)
}
}(a)
}
wg.Wait()
// Clean up any tabs that were opened.
for _, tab := range tabs {
if tab != "" {
_ = d.closeTab(tab, 30)
}
}
for i, err := range errs {
if err != nil {
t.Errorf("agent %d failed: %v", i, err)
}
}
}
// freePort returns an available TCP port for the daemon HTTP listener.
func freePort(t *testing.T) int {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()
return port
}
+4 -8
View File
@@ -637,22 +637,18 @@ func main() {
os.Exit(1)
}
// Sort tabs by history index (most recent first)
// Sort tabs by ID for stable, deterministic output
sort.Slice(tabs, func(i, j int) bool {
return tabs[i].HistoryIndex > tabs[j].HistoryIndex
return tabs[i].ID < tabs[j].ID
})
// Print the tabs
if len(tabs) == 0 {
fmt.Println("No tabs open")
} else {
fmt.Println("Open tabs (in order of recent use):")
fmt.Println("Open tabs:")
for _, tab := range tabs {
currentMarker := " "
if tab.IsCurrent {
currentMarker = "*"
}
fmt.Printf("%s %s: %s\n", currentMarker, tab.ID, tab.URL)
fmt.Printf(" %s: %s\n", tab.ID, tab.URL)
}
}
+33 -2
View File
@@ -1,6 +1,26 @@
# Cremote MCP Tools - LLM Usage Guide
Cremote MCP server provides 67 web automation and accessibility testing tools. All tools accept optional `tab` (tab ID) and `timeout` (seconds, default varies) parameters unless otherwise noted.
Cremote MCP server provides 67 web automation and accessibility testing tools. Most tools accept an optional `tab` (tab ID) and `timeout` (seconds, default varies) parameter unless otherwise noted.
## Tab & Session Model (read this first)
- **Per-session current tab.** Each `cremote-mcp` process maintains its own
"current tab" in memory. When you omit `tab`, the tool targets that current
tab. There is **no shared daemon-side current tab** — that was removed because
it cannot be shared safely across multiple concurrent agents.
- **You must open/navigate a tab first.** Tools that act on a tab will error
with `no tab available - navigate to a page first` (or, for tools that wrap
the daemon directly, `tab id is required`) until you have opened a tab via
`web_navigate_cremotemcp`, `web_manage_tabs_cremotemcp` (`open`), or by
passing an explicit `url`/`tab` to a tool that accepts one.
- **Explicit `tab` always wins.** Pass `tab` when you want to operate on a
specific tab, e.g. when juggling multiple tabs via `web_manage_tabs_cremotemcp`.
- **Multi-agent safe.** Multiple agents may share one `cremotedaemon` + Chrome
instance. Each agent's MCP process holds isolated tab state and always sends
an explicit tab id to the daemon, so agents never collide. Per-tab state
(iframe context, console logs) is keyed by the globally-unique Chrome tab id.
- **Iframe context is per-tab.** `web_iframe_cremotemcp` (`enter`/`exit`)
affects only the current tab's iframe context for this session.
## 🚀 NEW: Optimized Workflows (Reduce Tool Calls by 50-70%)
@@ -273,6 +293,10 @@ Screenshot with metadata.
## Cache Control Tools
> All cache/site-data tools operate on the **current tab** (or an explicit `tab`
> if provided). A tab must already be open/navigated; otherwise they return
> `tab id is required`.
### web_disable_cache_cremotemcp
Disable browser cache for tab. No required parameters. Default timeout: 5s
@@ -669,13 +693,20 @@ Common errors:
- **Timeout**: Increase timeout parameter for slow-loading content
- **Navigation failed**: Check URL accessibility
- **File not found**: Verify file paths for upload/download operations
- **`no tab available - navigate to a page first` / `tab id is required`**: No
current tab is set in this session. Call `web_navigate_cremotemcp` (with a
`url`), `web_manage_tabs_cremotemcp` (`open`), or pass an explicit `tab`/`url`
on the tool that errored.
---
## Notes
- All tools return structured JSON responses
- Tab management is automatic if no tab ID specified
- The MCP server tracks a current tab per session; omit `tab` to use it. A tab
must be opened/navigated first (see *Tab & Session Model* above). There is no
daemon-side current tab, so omitting `tab` before any tab exists returns an
error rather than silently picking another agent's tab.
- File upload operations now auto-detect host paths and transfer to container
- Accessibility tools follow WCAG 2.1 Level AA/AAA standards
- Screenshot tools automatically copy files from container to host
+104 -255
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
│ │ │
└──────────────────────┼──────────────────────┘
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 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)
└──────────────────┼──────────────────┘
│
┌─────────────┴─────────────┐
│ Cremote MCP Server │
│ (Session Manager) │
│ cremotedaemon │ ← ONE shared daemon
│ (stateless re: current │ (no current tab, no history)
│ tab; per-tab maps keyed │
│ by Chrome TargetID) │
└─────────────┬─────────────┘
│
│ TCP
│
┌─────────────┴─────────────┐
│ Cremote Daemon │
│ (Shared Browser) │
└─────────────┬─────────────┘
│
│ DevTools Protocol
│
│ CDP / WebSocket
┌─────────────┴─────────────┐
│ Chrome / Chromium │
│ (All tabs accessible) │
│ (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.
## Verification
- `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
# Enable HTTP transport
CREMOTE_TRANSPORT=http ./cremote-mcp
CREMOTE_INTEGRATION=1 go test -race -run TestMultiAgentIsolation ./daemon/...
```
- **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
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).