> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anchorbrowser.io/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Anchor Browser is cloud browser infrastructure for AI agents and automation: browser sessions you control over CDP or REST, natural-language web tasks, versioned automation tasks, managed authentication into third-party web apps (identities with MFA), persistent volumes and profiles, recordings, live view, batch sessions, webhooks, and network options including residential proxies, extra stealth, and captcha solving for sites that block standard browsers. The for-agents page (https://docs.anchorbrowser.io/for-agents) covers authentication and the first API calls. API keys are created at https://app.anchorbrowser.io/api-keys. Append .md to any page URL for its Markdown version. The SDKs read the API key from ANCHORBROWSER_API_KEY, and REST calls send it in the anchor-api-key header. End every session you create with DELETE /v1/sessions/{id}, because a session is billed until it ends. Location targeting, captcha solving and managed authentication need the Starter plan, and extra stealth needs the Growth plan; on the Free plan, create a session with an empty body. Plans and limits are at https://docs.anchorbrowser.io/pricing. The hosted MCP server is https://api.anchorbrowser.io/v1/mcp.

# Boat

> Run agent code in a Boat sandbox and drive an Anchor cloud browser from it, with the sandbox locked to Anchor's hosts.

[Boat](https://boat.dev) gives an agent a full Ubuntu machine in the cloud: root, Docker, SSH and coding agents already installed, billed per second. This guide runs agent code in a Boat sandbox and gives it a real browser on Anchor.

Every sample is in Python and TypeScript. Tested with the Boat SDKs 1.15.0 (`boat-sdk` and `@boatdev/sdk`), the Anchor Python SDK 1.0.1 and the Anchor TypeScript SDK 1.0.0.

## What you're integrating

**Anchor SDK in a Boat sandbox → Anchor Cloud.** The sandbox runs your agent and its code. Chromium runs as a managed Anchor cloud session, reached over HTTPS and CDP.

* Boat stays the code runtime: the agent edits files, installs packages and runs commands there.
* Anchor stays the remote browser: stealth, proxies, live view and session lifecycle.
* The sandbox can be locked so its only way out is Anchor.

A Boat sandbox also ships Chrome and a desktop of its own. That browser runs inside the sandbox, on the sandbox's address, and needs the sandbox's network open to every site it visits. With Anchor the browser is outside the sandbox: it gets past bot detection, you watch it through Anchor's live view, and the sandbox itself only needs to reach two Anchor hosts.

## Before you start

Sign up at [boat.dev](https://boat.dev) and create an API key in the [dashboard](https://boat.dev/dashboard?tab=api-keys). Keep it in your shell:

```bash theme={null}
export BOAT_API_KEY=boat_...
```

Install the Boat SDK for your language:

```bash Python theme={null}
python -m pip install boat-sdk
```

```bash TypeScript theme={null}
npm install @boatdev/sdk tsx
```

The TypeScript samples use top-level `await`, so set `"type": "module"` in your `package.json`.

## Store your Anchor key in Boat

Create an Anchor key at [API Keys](https://app.anchorbrowser.io/api-keys). Save it as a variable of your default Boat environment, so every new sandbox starts with it and it never sits in your code. With the key in `ANCHORBROWSER_API_KEY` in your shell:

```bash theme={null}
ENV_ID=$(curl -sS "https://boat.dev/api/v1/environments" \
  -H "Authorization: Bearer $BOAT_API_KEY" \
  | jq -r '.environments[] | select(.isDefault) | .id')

jq -n --arg v "$ANCHORBROWSER_API_KEY" '{value: $v}' \
  | curl -sS -X PUT "https://boat.dev/api/v1/environments/$ENV_ID/vars/ANCHORBROWSER_API_KEY" \
      -H "Authorization: Bearer $BOAT_API_KEY" \
      -H "Content-Type: application/json" \
      --data-binary @- | jq -c '{ok, type}'
```

```json theme={null}
{"ok":true,"type":"environment.updated"}
```

The value goes in the request body, read from standard input, so it does not appear in the process list. Keep the name `ANCHORBROWSER_API_KEY`: the Anchor Python SDK reads it on its own, and the TypeScript samples pass it to the SDK.

> [!WARNING]
>
> Boat puts the real key inside the sandbox as an environment variable, and anything that runs there can read it. Use a dedicated Anchor key for sandboxes, and [lock the sandbox](#lock-the-sandbox-to-anchor) so the key has nowhere else to go.

## Run a web task from the sandbox

Describe the goal in plain English and let Anchor's agent drive the browser. The script creates a sandbox, installs the Anchor SDK, runs the task and deletes the sandbox.

```python run_task.py theme={null}
import os

from boat_sdk import ApiClient, Configuration, exec_command, wait_until_ready, write_text
from boat_sdk.api.boat_api import BoatApi
from boat_sdk.models import CreateSandboxRequest

TASK = '''
from anchorbrowser import Anchorbrowser

client = Anchorbrowser()
session = client.sessions.create_session()
try:
    result = client.agent.task(
        "Go to books.toscrape.com and return the title and price of the first three books",
        session_id=session.data.id,
    )
    print(result.data.result)
finally:
    client.sessions.delete_session(session.data.id)
    print("anchor session ended")
'''

INSTALL = "python3 -m venv anchor-env && anchor-env/bin/pip install -q 'anchorbrowser>=1.0' playwright"

config = Configuration(host="https://boat.dev/api/v1", access_token=os.environ["BOAT_API_KEY"])

with ApiClient(config) as client:
    boat = BoatApi(client)
    created = boat.create(create_sandbox_request=CreateSandboxRequest(type="small", ttl_seconds=1800))
    sandbox_id = created.sandbox.id
    try:
        wait_until_ready(boat, sandbox_id)
        exec_command(boat, sandbox_id, INSTALL, timeout_seconds=300)
        write_text(boat, sandbox_id, "task.py", TASK)
        out = exec_command(boat, sandbox_id, "anchor-env/bin/python task.py", timeout_seconds=300).actual_instance
        print(out.stdout)
        if out.stderr:
            print("stderr:", out.stderr)
        print("exit code:", out.exit_code)
    finally:
        boat.delete_sandbox(sandbox_id=sandbox_id, x_ascii_confirm_delete=sandbox_id)
        print("boat sandbox deleted")
```

```typescript run_task.ts theme={null}
import { BoatApi, Configuration, execCommand, waitUntilReady, writeText } from "@boatdev/sdk";
import type { CommandResponse } from "@boatdev/sdk";

const TASK = `
import { client, agentTask, Sessions } from "anchorbrowser";

client.setConfig({ auth: () => process.env.ANCHORBROWSER_API_KEY });

const session = await Sessions.createSession();
try {
  const result = await agentTask(
    "Go to books.toscrape.com and return the title and price of the first three books",
    { sessionId: session.data.id }
  );
  console.log(result.data.result);
} finally {
  await Sessions.deleteSession({ path: { session_id: session.data.id } });
  console.log("anchor session ended");
}
`;

const INSTALL = "mkdir -p anchor && cd anchor && npm init -y >/dev/null && npm install anchorbrowser@^1 playwright-core";

const boat = new BoatApi(new Configuration({
  basePath: "https://boat.dev/api/v1",
  accessToken: process.env.BOAT_API_KEY!,
}));

const created = await boat.create({ type: "small", ttlSeconds: 1800 });
const sandboxId = created.sandbox.id;
try {
  await waitUntilReady(boat, sandboxId);
  await execCommand(boat, sandboxId, INSTALL, undefined, 300);
  await writeText(boat, sandboxId, "anchor/task.mjs", TASK);
  const out = (await execCommand(boat, sandboxId, "node task.mjs", "anchor", 300)) as CommandResponse;
  console.log(out.stdout);
  if (out.stderr) console.log("stderr:", out.stderr);
  console.log("exit code:", out.exitCode);
} finally {
  await boat.deleteSandbox({ sandboxId, xAsciiConfirmDelete: sandboxId });
  console.log("boat sandbox deleted");
}
```

```bash Python theme={null}
python run_task.py
```

```bash TypeScript theme={null}
npx tsx run_task.ts
```

Both print:

```text theme={null}
1. A Light in the Attic — £51.77
2. Tipping the Velvet — £53.74
3. Soumission — £50.10
anchor session ended

exit code: 0
boat sandbox deleted
```

What the script relies on:

* **The sandbox is ready in seconds.** In testing a `small` sandbox was ready 2.6 seconds after the create call, and the Python script ran end to end in 33 seconds, install included.
* **The install is small.** `playwright` (Python) and `playwright-core` (Node.js) are only the client library that speaks CDP. You do not run `playwright install`, because the browser lives on Anchor. Python needs a virtual environment: Ubuntu's system `pip` refuses to install packages outside one.
* **Paths are relative to `/home/user`.** `write_text` and `exec_command` both start there. The TypeScript version runs in the `anchor` folder, where `npm` installed the packages.
* **The session is created first.** The task runs on a session the script created, so `finally` can always end it, also when the task fails.

## Drive the browser yourself with Playwright

For step-by-step control, create an Anchor session and connect Playwright to it over CDP from inside the sandbox.

```python run_playwright.py theme={null}
import os

from boat_sdk import ApiClient, Configuration, exec_command, wait_until_ready, write_text
from boat_sdk.api.boat_api import BoatApi
from boat_sdk.models import CreateSandboxRequest

SCRIPT = '''
from anchorbrowser import Anchorbrowser
from playwright.sync_api import sync_playwright

client = Anchorbrowser()
session = client.sessions.create_session(
    session={"timeout": {"max_duration": 10, "idle_timeout": 3}}
)
print("live view:", session.data.live_view_url)

try:
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp(session.data.cdp_url)
        context = browser.contexts[0]
        page = context.pages[0] if context.pages else context.new_page()
        page.goto("https://books.toscrape.com")
        print("title:", page.title())
        print("first book:", page.get_attribute("article.product_pod h3 a", "title"))
        browser.close()
finally:
    client.sessions.delete_session(session.data.id)
    print("anchor session ended")
'''

INSTALL = "python3 -m venv anchor-env && anchor-env/bin/pip install -q 'anchorbrowser>=1.0' playwright"

config = Configuration(host="https://boat.dev/api/v1", access_token=os.environ["BOAT_API_KEY"])

with ApiClient(config) as client:
    boat = BoatApi(client)
    created = boat.create(create_sandbox_request=CreateSandboxRequest(type="small", ttl_seconds=1800))
    sandbox_id = created.sandbox.id
    try:
        wait_until_ready(boat, sandbox_id)
        exec_command(boat, sandbox_id, INSTALL, timeout_seconds=300)
        write_text(boat, sandbox_id, "browse.py", SCRIPT)
        out = exec_command(boat, sandbox_id, "anchor-env/bin/python browse.py", timeout_seconds=300).actual_instance
        print(out.stdout)
        if out.stderr:
            print("stderr:", out.stderr)
        print("exit code:", out.exit_code)
    finally:
        boat.delete_sandbox(sandbox_id=sandbox_id, x_ascii_confirm_delete=sandbox_id)
        print("boat sandbox deleted")
```

```typescript run_playwright.ts theme={null}
import { BoatApi, Configuration, execCommand, waitUntilReady, writeText } from "@boatdev/sdk";
import type { CommandResponse } from "@boatdev/sdk";

const SCRIPT = `
import { client, Sessions } from "anchorbrowser";
import { chromium } from "playwright-core";

client.setConfig({ auth: () => process.env.ANCHORBROWSER_API_KEY });

const session = await Sessions.createSession({
  body: { session: { timeout: { max_duration: 10, idle_timeout: 3 } } },
});
console.log("live view:", session.data.live_view_url);

try {
  const browser = await chromium.connectOverCDP(session.data.cdp_url);
  const context = browser.contexts()[0];
  const page = context.pages()[0] ?? (await context.newPage());
  await page.goto("https://books.toscrape.com");
  console.log("title:", await page.title());
  console.log(
    "first book:",
    await page.getAttribute("article.product_pod h3 a", "title")
  );
  await browser.close();
} finally {
  await Sessions.deleteSession({ path: { session_id: session.data.id } });
  console.log("anchor session ended");
}
`;

const INSTALL = "mkdir -p anchor && cd anchor && npm init -y >/dev/null && npm install anchorbrowser@^1 playwright-core";

const boat = new BoatApi(new Configuration({
  basePath: "https://boat.dev/api/v1",
  accessToken: process.env.BOAT_API_KEY!,
}));

const created = await boat.create({ type: "small", ttlSeconds: 1800 });
const sandboxId = created.sandbox.id;
try {
  await waitUntilReady(boat, sandboxId);
  await execCommand(boat, sandboxId, INSTALL, undefined, 300);
  await writeText(boat, sandboxId, "anchor/browse.mjs", SCRIPT);
  const out = (await execCommand(boat, sandboxId, "node browse.mjs", "anchor", 300)) as CommandResponse;
  console.log(out.stdout);
  if (out.stderr) console.log("stderr:", out.stderr);
  console.log("exit code:", out.exitCode);
} finally {
  await boat.deleteSandbox({ sandboxId, xAsciiConfirmDelete: sandboxId });
  console.log("boat sandbox deleted");
}
```

Both print:

```text theme={null}
live view: https://live.anchorbrowser.io/inspector.html?sessionId=<session-id>&rt=<token>
title: All products | Books to Scrape - Sandbox
first book: A Light in the Attic
anchor session ended

exit code: 0
boat sandbox deleted
```

> [!WARNING]
>
> `session.data.cdp_url` and the live view URL carry a session token (`rt`). Anyone who has one of them can reach that browser until the session ends. Do not write them to logs you share.

### Watch the browser

Open the `live view` URL in your own browser while the script runs, or open the session in the [Anchor dashboard](https://app.anchorbrowser.io). This is the Anchor session streaming directly, so the sandbox needs no desktop, tunnel or public port for it.

![Anchor dashboard showing a running session with the live browser on Books to Scrape, opened by a script inside a Boat sandbox](https://mintcdn.com/anchor-b3ec2715/QsD0HZwjHIuuq647/images/integrations/boat/anchor-session.png?fit=max\&auto=format\&n=QsD0HZwjHIuuq647\&q=85\&s=f0ad709e5ed90ca7f579687f8f34e30c)

The Boat dashboard shows the other half: the sandbox that runs your script.

![Boat dashboard listing one running small sandbox with 2 vCPU and 4 GB](https://mintcdn.com/anchor-b3ec2715/QsD0HZwjHIuuq647/images/integrations/boat/sandboxes.png?fit=max\&auto=format\&n=QsD0HZwjHIuuq647\&q=85\&s=d9e1c6fd6bd4a8dd8cc60ef73cb57668)

Its metrics list the Playwright driver from `anchor-env` as a process using about 109 MB. No browser runs in the sandbox for this work, because the browser is on Anchor.

![Boat sandbox metrics with CPU, RAM, disk and IO, and the Playwright driver from anchor-env in the process list](https://mintcdn.com/anchor-b3ec2715/QsD0HZwjHIuuq647/images/integrations/boat/metrics.png?fit=max\&auto=format\&n=QsD0HZwjHIuuq647\&q=85\&s=933161855698a362721b78087c7e0ddc)

## Lock the sandbox to Anchor

By default a Boat sandbox can reach any public address. When the code inside is untrusted, limit it to the two hosts the Anchor SDK needs with a Boat [network policy](https://docs.boat.dev/network-policy). Install the packages first, then set the policy and wait until Boat reports it as enforced:

```python Python theme={null}
import time

from boat_sdk.models.network_policy_request import NetworkPolicyRequest

exec_command(boat, sandbox_id, INSTALL, timeout_seconds=300)

boat.set_network_policy(sandbox_id, NetworkPolicyRequest(
    mode="allow",
    allow=["api.anchorbrowser.io", "connect.anchorbrowser.io"],
))
deadline = time.monotonic() + 60
while boat.get_network_policy(sandbox_id).network.status != "enforced":
    if time.monotonic() > deadline:
        raise TimeoutError("network policy not enforced after 60 seconds")
    time.sleep(1)
```

```typescript TypeScript theme={null}
await execCommand(boat, sandboxId, INSTALL, undefined, 300);

await boat.setNetworkPolicy({
  sandboxId,
  mode: "allow",
  allow: ["api.anchorbrowser.io", "connect.anchorbrowser.io"],
});
const deadline = Date.now() + 60_000;
while ((await boat.getNetworkPolicy({ sandboxId })).network?.status !== "enforced") {
  if (Date.now() > deadline) throw new Error("network policy not enforced after 60 seconds");
  await new Promise((resolve) => setTimeout(resolve, 1000));
}
```

In testing the policy was enforced within 20 seconds. The loop stops with an error after 60, so a policy that never applies does not hang the script.

The Playwright script still works in that sandbox, and requests to other sites fail:

```text theme={null}
title: All products | Books to Scrape - Sandbox
first book: A Light in the Attic
anchor session ended

exit code: 0
example.org: blocked
pypi.org: blocked
```

The code can still browse any site, because the page loads happen in Anchor's browser, not in the sandbox. It just cannot open its own connections anywhere else. This is the main reason to pair the two: the agent's code is boxed in, and all web access goes through one browser you can watch and record.

| Host | Used for |
| - | - |
| `api.anchorbrowser.io` | Creating and ending sessions, running tasks, the hosted MCP servers |
| `connect.anchorbrowser.io` | The CDP websocket Playwright connects to |

`live.anchorbrowser.io` is opened by the person watching, not by the sandbox, so it does not need to be on the list. Boat's own `exec` and file calls keep working under any policy.

## Give the coding agents in the sandbox Anchor's MCP server

Every Boat sandbox has Claude Code, Codex and other coding agents installed. Register Anchor's hosted MCP server once and the agent can run web tasks by itself:

```bash theme={null}
claude mcp add --scope user --transport http anchor https://api.anchorbrowser.io/v1/mcp \
  --header "anchor-api-key: $ANCHORBROWSER_API_KEY"
```

Run it inside the sandbox, for example with `exec_command`. `claude mcp list` then shows Anchor next to the `computer` server Boat registers itself:

```text theme={null}
computer: /usr/bin/python3 /home/user/.config/ascii/computer-mcp.py ... - ✔ Connected
anchor: https://api.anchorbrowser.io/v1/mcp (HTTP) - ✔ Connected
```

A locked sandbox also blocks the agent's own model provider. With only the two Anchor hosts allowed, `api.anthropic.com` is blocked, so Claude Code cannot reach its model. If you run a coding agent inside a locked sandbox, add the hosts that agent needs to `allow`. For Claude Code that includes `api.anthropic.com`: with it on the list, the sandbox reaches it and `example.org` stays blocked.

The registration is stored in `/home/user/.claude.json`, with the key in it. See the [MCP server](https://docs.anchorbrowser.io/advanced/mcp.md) page for the tools it offers.

## Clean up two lifecycles

There are two things to end, and ending one does not end the other.

* **The Anchor session.** End it in a `finally` block inside the sandbox script. Deleting the sandbox does not end a cloud browser; it keeps running and billing until its own timeout.
* **The Boat sandbox.** Delete it in a `finally` block. `ttl_seconds` (Python) or `ttlSeconds` (TypeScript) stops the sandbox if your script dies before that.
* Set Anchor's `timeout.max_duration` and `timeout.idle_timeout`, in minutes, as a safety net for a sandbox that dies mid-run. See [Session Timeout](https://docs.anchorbrowser.io/advanced/session-timeout.md).
* Reuse one Anchor session for a whole agent run instead of creating one per page.

To confirm nothing is left running:

```bash theme={null}
curl https://api.anchorbrowser.io/v1/sessions/all/status \
  -H "anchor-api-key: $ANCHORBROWSER_API_KEY"

curl -sS "https://boat.dev/api/v1/sandboxes" -H "Authorization: Bearer $BOAT_API_KEY" | jq '.sandboxes | length'
```

Each test run on this page used a `small` sandbox for 8 to 20 seconds. Boat reported `$0.0001` to `$0.0002` per run.

## API key

Each customer brings their own Anchor key as a variable of their Boat environment. Anchor bills them directly for browser usage; Boat bills for the sandbox.

## Troubleshooting

* **`402 billing_required` when you create a sandbox:** the Boat account has no plan yet. Start one in the Boat dashboard under Billing.
* **`401` from Anchor inside the sandbox:** the variable is missing or has another name. Check that your default environment holds `ANCHORBROWSER_API_KEY`.
* **`error: externally-managed-environment` from `pip`:** Ubuntu's system Python refuses installs outside a virtual environment. Create one with `python3 -m venv anchor-env`, as the samples do.
* **`403 trial_saved_snapshots_not_allowed`:** Boat's free trial cannot save a sandbox as a saved snapshot, so the samples install the SDK at the start of each run. The install takes about 14 seconds.
* **`400 trial_auto_stop_required`:** during Boat's free trial a sandbox needs an auto-stop of at most 2 hours. Pass `ttl_seconds` of 7200 or less.
* **A request fails right after you set a network policy:** the policy can report `pending` for a moment. Wait until its status is `enforced`, as the sample does.
* **The command stops after 30 seconds:** that is Boat's default command timeout. Pass `timeout_seconds` (up to 600), as the samples do. A web task can take a few minutes.

See the [Sandboxes overview](https://docs.anchorbrowser.io/integrations/sandboxes) and [Create a Session](https://docs.anchorbrowser.io/quickstart/create-session.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.