> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch24-browser-control/24.4-browser-server.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 24.4 Browser Server

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~190k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In the previous three sections, we analyzed the three layers of browser control in sequence: architecture overview, CDP low-level layer, and Playwright high-level layer. This section analyzes the outermost layer—the **browser HTTP server**, which encapsulates all capabilities as RESTful APIs for Gateway and Agent tool layers to call.

***

## 24.4.1 Browser HTTP Server

### Server Startup

```typescript
// src/browser/server.ts — startBrowserControlServerFromConfig
export async function startBrowserControlServerFromConfig() {
  const cfg = loadConfig();
  const resolved = resolveBrowserConfig(cfg.browser, cfg);
  if (!resolved.enabled) return null;

  const app = express();
  app.use(express.json({ limit: "1mb" }));

  // Register routes
  const ctx = createBrowserRouteContext({ getState: () => state });
  registerBrowserRoutes(app, ctx);

  // Bind to 127.0.0.1 (local access only)
  const server = await app.listen(resolved.controlPort, "127.0.0.1");

  state = {
    server,
    port: resolved.controlPort,
    resolved,
    profiles: new Map(),
  };

  // Pre-start Relay server for extension-mode profiles
  for (const name of Object.keys(resolved.profiles)) {
    const profile = resolveProfile(resolved, name);
    if (profile?.driver === "extension") {
      await ensureChromeExtensionRelayServer({ cdpUrl: profile.cdpUrl });
    }
  }

  return state;
}
```

Key design points:

* **Bind to `127.0.0.1`**—browser control service is local-only, not exposed to network
* **JSON request limit 1MB**—prevent malicious large requests
* **profiles Map**—runtime state for each profile (browser process, last active tab, etc.)
* **Extension Relay pre-start**—if a profile uses Chrome extension mode, start Relay at server startup, don't wait for first operation

### Graceful Shutdown

```typescript
export async function stopBrowserControlServer() {
  // 1. Stop browsers for all profiles
  for (const name of Object.keys(current.resolved.profiles)) {
    await ctx.forProfile(name).stopRunningBrowser();
  }
  
  // 2. Close HTTP server
  await new Promise(resolve => current.server?.close(resolve));
  
  // 3. Close Playwright connection
  const mod = await import("./pw-ai.js");
  await mod.closePlaywrightBrowserConnection();
}
```

***

## 24.4.2 Server Context and Tab Management

### Profile Context

`createBrowserRouteContext()` creates a **profile-scoped** operation context for each route request:

```typescript
// src/browser/server-context.ts — ProfileContext interface (inferred)
interface ProfileContext {
  listTabs(): Promise<BrowserTab[]>;
  openTab(url: string): Promise<BrowserTab>;
  closeTab(targetId: string): Promise<void>;
  focusTab(targetId: string): Promise<void>;
  ensureBrowserRunning(): Promise<void>;
  stopRunningBrowser(): Promise<void>;
  getStatus(): ProfileStatus;
  getLastTargetId(): string | null;
  setLastTargetId(id: string): void;
}
```

```typescript
// src/browser/server-context.types.ts — BrowserTab type
type BrowserTab = {
  targetId: string;
  title?: string;
  url?: string;
  type?: string;
  wsUrl?: string;        // CDP WebSocket URL
};
```

### Profile Runtime State

```typescript
type ProfileRuntimeState = {
  profile: ResolvedBrowserProfile;
  running: RunningChrome | null;  // Currently running Chrome process (if any)
  lastTargetId: string | null;    // Last operated tab
};
```

The design purpose of `lastTargetId`: when an Agent doesn't specify `targetId`, it defaults to the last operated tab. This aligns with human browsing habits—"continue operating on the current tab".

### Tab Operations

Tab opening supports two methods:

```typescript
// Local browser: create via CDP
const { targetId } = await createTargetViaCdp({
  cdpUrl: profile.cdpUrl,
  url: targetUrl,
});

// Remote browser: create via Playwright
const page = await createPageViaPlaywright({
  cdpUrl: profile.cdpUrl,
  url: targetUrl,
});
```

Tab closing is similar—local via CDP `/json/close/${targetId}`, remote via Playwright.

***

## 24.4.3 Client Actions Layer

`client-actions.ts` is an aggregation of four submodules:

```typescript
// src/browser/client-actions.ts
export * from "./client-actions-core.js";    // Core operations
export * from "./client-actions-observe.js"; // Observation operations
export * from "./client-actions-state.js";   // State operations
export * from "./client-actions-types.js";   // Type definitions
```

The client actions layer sits between browser server routes and Playwright tools core—it converts HTTP request parameters to Playwright function calls and formats responses.

### Core Actions (core)

```
click     → clickViaPlaywright
hover     → hoverViaPlaywright
type      → typeViaPlaywright
fill_form → fillFormViaPlaywright
select    → selectOptionViaPlaywright
press_key → pressKeyViaPlaywright
drag      → dragViaPlaywright
```

### Observation Actions (observe)

```
snapshot    → snapshotAiViaPlaywright / snapshotRoleViaPlaywright
screenshot  → takeScreenshotViaPlaywright
console     → getConsoleMessagesViaPlaywright
network     → getNetworkRequestsViaPlaywright
errors      → getPageErrorsViaPlaywright
```

### State Actions (state)

```
navigate    → navigateViaPlaywright
evaluate    → evaluateViaPlaywright
cookies     → cookiesGetViaPlaywright / cookiesSetViaPlaywright
storage     → storageGetViaPlaywright / storageSetViaPlaywright
resize      → resizeViewportViaPlaywright
```

***

## 24.4.4 Chrome Extension Relay

### Why Extension Relay?

In `extension` driver mode, the user's Chrome is not launched by OpenClaw—it doesn't have the `--remote-debugging-port` parameter and can't connect directly via CDP. Chrome Extension Relay solves this problem:

```
┌──────────────────┐         ┌──────────────────┐
│   OpenClaw       │         │   User's Chrome   │
│   (CDP Client)   │ ──WS──▶ │                  │
│                  │         │  Extension Relay  │
│  Relay Server    │ ◀──WS── │  (Chrome Ext)     │
│  (Local HTTP+WS) │         │                  │
└──────────────────┘         └──────────────────┘
```

> **Sidebar**: Chrome Extensions run inside the browser with higher privileges than regular web pages—they can access the `chrome.debugger` API, which provides functionality equivalent to CDP. OpenClaw's relay architecture leverages this: the extension executes CDP commands inside the browser, then forwards results to OpenClaw's Relay Server via WebSocket.

### Relay Architecture

```typescript
// src/browser/extension-relay.ts — Message types
type ExtensionForwardCommandMessage = {
  id: number;
  method: "forwardCDPCommand";
  params: { method: string; params?: unknown; sessionId?: string };
};

type ExtensionResponseMessage = {
  id: number;
  result?: unknown;
  error?: string;
};

type ExtensionForwardEventMessage = {
  method: "forwardCDPEvent";
  params: { method: string; params?: unknown; sessionId?: string };
};
```

Communication flow:

1. OpenClaw connects to extension's WebSocket via local Relay Server
2. Send `forwardCDPCommand` message (containing CDP method and parameters)
3. Extension executes `chrome.debugger.sendCommand()` inside browser
4. Extension returns result via `ExtensionResponseMessage`
5. Browser events (like page load completion) are pushed via `forwardCDPEvent`

### Authentication

```typescript
const RELAY_AUTH_HEADER = "x-openclaw-relay-token";
```

Relay Server generates a random token at startup, stored in configuration. Extensions must provide this token when connecting. This prevents other programs from impersonating the extension connecting to Relay Server.

### Target Management

Relay internally maintains a **Connected Target** table:

```typescript
type ConnectedTarget = {
  sessionId: string;    // CDP session ID
  targetId: string;     // Tab ID
  targetInfo: TargetInfo; // Tab information
};
```

When the extension detects a `Target.attachedToTarget` event, it adds the new target to the table; when it detects `Target.detachedFromTarget`, it removes it. This way OpenClaw knows which tabs are operable.

***

## 24.4.5 Bridge Server

`bridge-server.ts` provides an additional HTTP service, acting as a **bridge** between the Agent tool layer and browser control service. It starts in the Agent's execution context (possibly inside a Docker container), forwarding requests to the browser control service on the host machine.

This is particularly important in sandbox mode:

```
┌────────────────────┐     ┌──────────────────────┐
│   Docker Container  │     │   Host Machine        │
│                    │     │                      │
│  Agent Tool Layer   │──▶  │  Bridge Server        │
│  (browser tool)    │     │  (port 18790)         │
│                    │     │        │              │
└────────────────────┘     │        ▼              │
                           │  Browser Control      │
                           │  (port 18791)         │
                           │        │              │
                           │        ▼              │
                           │  Chrome (CDP 18800)   │
                           └──────────────────────┘
```

***

## Summary of This Section

1. **Browser HTTP server** binds to `127.0.0.1` (local only), provides RESTful API via Express
2. **Profile context** provides isolated operation interface for each browser instance—tab list, open/close, start/stop browser
3. **`lastTargetId`** records the last operated tab, Agents default to it when not specified, aligning with human browsing habits
4. **Client actions layer** is an adapter between routes and Playwright—core/observation/state three categories cover all browser operations
5. **Chrome extension relay** solves the "user already has Chrome" problem—extension executes CDP commands inside browser, forwards via WebSocket to OpenClaw
6. **Bridge Server** acts as a forwarder between Docker container and host machine in sandbox mode
7. Complete server stack: Agent Tool → Bridge (sandbox) → Browser Control Server → CDP/Playwright → Chrome

***

> ### 🔬 Going Deeper: 24.5 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**24.5 Source Deep Dive: Four Browser Sources and Three Security Gates**](https://www.openclawbook.xyz/en/ch24-browser-control/24.5-source-deep-dive-four-sources-three-gates.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
