> ## 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.

# Fly.io Sprites

> Run agent code in a Fly.io Sprite and give it an Anchor cloud browser, with the Anchor key held by a Sprites Connector and the network locked down.

[Sprites](https://fly.io/sprites) are Fly.io's Linux computers for agents: a Sprite starts in under a second, keeps its disk, and sleeps when idle. This guide runs your agent's code in a Sprite and gives it an Anchor cloud browser. The Sprite never holds your Anchor API key, and it can be locked so that it reaches Anchor and nothing else.

Tested with `fly` 0.5.26, `sprites-py` 0.7.2, `@fly/sprites` 0.2.5, the Anchor Python SDK 1.0.1 and the Anchor TypeScript SDK 1.0.0.

## What you're integrating

* **The Sprite** runs your code. It is an Ubuntu machine with Python, Node.js, Claude Code and Codex already installed.
* **Anchor** runs the browser. Your code creates a session over the API and drives it with a task or with Playwright over CDP. No browser runs in the Sprite.
* **A Sprites Connector** holds the Anchor API key. Code in the Sprite calls a gateway URL, and Sprites adds the key outside the Sprite. A leaked environment or a prompt-injected agent has no key to give away.
* **A network policy** limits what the Sprite can reach. With the policy on this page, the only path to Anchor's API is the connector.

## Before you start

You need an [Anchor API key](https://app.anchorbrowser.io/api-keys) and a Fly.io account.

Install the Fly CLI ([instructions](https://fly.io/docs/flyctl/install/)), version 0.5.20 or later, and sign in:

```bash theme={null}
fly version
fly auth login
```

The scripts on this page that use the Sprites SDKs also need a Sprites token. Create one in the Fly.io dashboard under your organization, **Sprites**, **Tokens**, and keep it in your shell:

```bash theme={null}
export SPRITES_TOKEN=...
```

Install the Sprites SDK for your language on your own machine:

```bash Python theme={null}
pip install sprites-py
```

```bash TypeScript theme={null}
npm install @fly/sprites tsx
npm pkg set type=module
```

## Save your Anchor key as a Connector

Create a custom API connector that points at Anchor's API and sends the key in the `anchor-api-key` header. Only Sprites with the label `anchor` may use it:

```bash theme={null}
jq -n --arg key "$ANCHORBROWSER_API_KEY" '{
  name: "anchorbrowser",
  base_api_url: "https://api.anchorbrowser.io",
  access_token: $key,
  auth_method: "custom_header",
  auth_custom_header_name: "anchor-api-key",
  test_url: "https://api.anchorbrowser.io/v1/sessions/all/status",
  access_policy: { sprite_labels: ["anchor"] }
}' | fly sprites api /v1/oauth/connections/custom_api -sS \
    -X POST -H "Content-Type: application/json" --data-binary @- \
  | jq -r '.connection.id'
```

It prints the connection ID. Keep it and build the gateway URL from it:

```bash theme={null}
export ANCHOR_CONNECTION_ID=<connection-id>
export GATEWAY="https://api.sprites.dev/v1/gateway/custom_api/$ANCHOR_CONNECTION_ID"
```

`jq` reads the key from your environment and the request body goes over standard input, so the key does not appear in your shell history. The connector shows up in the dashboard under **Connectors**:

![Fly.io dashboard listing a custom connector named anchorbrowser for api.anchorbrowser.io, limited to Sprites with the label anchor](https://mintcdn.com/anchor-b3ec2715/3D_flZyR5GhRb8C1/images/integrations/fly-sprites/connectors.png?fit=max\&auto=format\&n=3D_flZyR5GhRb8C1\&q=85\&s=eb8b7e49fdf33f5be2cd929a250af3e8)

> [!NOTE]
>
> A connector with no access policy refuses every Sprite. The `sprite_labels` rule above is what lets a Sprite in. Running the command again with the same `name` updates the connector in place, which is how you rotate the key.

## Create a Sprite and install the SDK

Create a Sprite with the `anchor` label and make it the default for this folder:

```bash theme={null}
fly sprites create --skip-console --label anchor anchor-demo
fly sprites use anchor-demo
```

```text theme={null}
Creating sprite anchor-demo in organization <your-org>...
✓ Created sprite anchor-demo in 0.5s
```

Install the Anchor SDK and the Playwright client in it:

```bash Python theme={null}
fly sprites exec -- bash -c "pip install -q 'anchorbrowser>=1.0' playwright"
```

```bash TypeScript theme={null}
fly sprites exec -- bash -c "mkdir -p ~/anchor && cd ~/anchor && npm init -y >/dev/null && npm install anchorbrowser@^1 playwright-core"
```

![Fly.io dashboard page for the Sprite anchor-demo, shown as Running with the label anchor](https://mintcdn.com/anchor-b3ec2715/3D_flZyR5GhRb8C1/images/integrations/fly-sprites/sprite.png?fit=max\&auto=format\&n=3D_flZyR5GhRb8C1\&q=85\&s=d1dc96502a946cda0cef029de758700d)

What to expect:

* **The Sprite is ready at once.** In testing the create call took 0.5 seconds. The Python install took 9 seconds and the Node.js install 4.
* **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.
* **The install stays.** A Sprite keeps its disk when it sleeps, so you install once.
* **Run commands through `bash -c`.** A Sprite has two Pythons. Through `bash`, `python3` is the Sprite's managed Python 3.13, where `pip` installed the SDK. Started directly, `python3` is the system Python 3.14, and the import fails.

## Run a web task

The script in the Sprite uses the Anchor SDK as usual, with two environment variables: `ANCHORBROWSER_BASE_URL` points the SDK at the gateway, and `ANCHORBROWSER_API_KEY` is a placeholder, because the SDK wants a value. The connector replaces it with the real key.

Each host script below writes the task script into the Sprite and runs it.

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

from sprites import SpritesClient

GATEWAY = "https://api.sprites.dev/v1/gateway/custom_api/" + os.environ["ANCHOR_CONNECTION_ID"]

SCRIPT = '''
from anchorbrowser import Anchorbrowser

client = Anchorbrowser()
session = client.sessions.create_session()
try:
    result = client.tools.perform_web_task(
        session_id=session.data.id,
        prompt="Return the title and price of the first three books",
        url="https://books.toscrape.com",
    )
    print(result.data.result)
finally:
    client.sessions.delete_session(session.data.id)
    print("anchor session ended")
'''

sprite = SpritesClient(os.environ["SPRITES_TOKEN"]).sprite("anchor-demo")
(sprite.filesystem("/home/sprite") / "task.py").write_text(SCRIPT)

out = sprite.run(
    "bash", "-c", "python3 task.py",
    cwd="/home/sprite",
    env={
        "ANCHORBROWSER_BASE_URL": GATEWAY,
        "ANCHORBROWSER_API_KEY": "held-by-the-connector",
    },
    capture_output=True,
    timeout=300,
)
print(out.stdout.decode())
if out.stderr:
    print("stderr:", out.stderr.decode())
print("exit code:", out.returncode)
```

```typescript run_task.ts theme={null}
import { SpritesClient } from "@fly/sprites";

const GATEWAY = `https://api.sprites.dev/v1/gateway/custom_api/${process.env.ANCHOR_CONNECTION_ID}`;

const SCRIPT = `
import { client, Sessions, Tools } from "anchorbrowser";

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

const session = await Sessions.createSession({});
try {
  const result = await Tools.performWebTask({
    query: { sessionId: session.data.id },
    body: {
      prompt: "Return the title and price of the first three books",
      url: "https://books.toscrape.com",
    },
  });
  console.log(result.data.result);
} finally {
  await Sessions.deleteSession({ path: { session_id: session.data.id } });
  console.log("anchor session ended");
}
`;

const sprite = new SpritesClient(process.env.SPRITES_TOKEN!).sprite("anchor-demo");
await sprite.filesystem("/home/sprite/anchor").writeFile("task.mjs", SCRIPT);

const out = await sprite.execFile("bash", ["-c", "node task.mjs"], {
  cwd: "/home/sprite/anchor",
  env: {
    ANCHORBROWSER_BASE_URL: GATEWAY,
    ANCHORBROWSER_API_KEY: "held-by-the-connector",
  },
  timeout: 300_000,
});
console.log(out.stdout);
if (out.stderr) console.log("stderr:", out.stderr);
console.log("exit code:", out.exitCode);
```

Run it with `python run_task.py` or `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
```

The Python script ran end to end in 15 seconds.

> [!WARNING]
>
> Use `perform_web_task` (Python) and `Tools.performWebTask` (TypeScript) with a connector, not `agent.task` and `agentTask`. Those two helpers build their own CDP address from the SDK's base URL. With the gateway as the base URL they try to reach `connect.sprites.dev`, which does not exist, and fail with `getaddrinfo ENOTFOUND connect.sprites.dev`.

## 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 Sprite. The session is created through the connector. The CDP connection goes straight to `connect.anchorbrowser.io` with the session's own token, so it needs no API key.

```python browse.py theme={null}
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")
```

```javascript browse.mjs theme={null}
import { client, Sessions } from "anchorbrowser";
import { chromium } from "playwright-core";

client.setConfig({
  baseUrl: process.env.ANCHORBROWSER_BASE_URL,
  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");
}
```

Save the file on your machine. `fly sprites exec` uploads it and runs it in one command:

```bash Python theme={null}
fly sprites exec \
  --file browse.py:/home/sprite/browse.py \
  --env "ANCHORBROWSER_BASE_URL=$GATEWAY,ANCHORBROWSER_API_KEY=held-by-the-connector" \
  -- bash -c "python3 browse.py"
```

```bash Node.js theme={null}
fly sprites exec \
  --file browse.mjs:/home/sprite/anchor/browse.mjs \
  --dir /home/sprite/anchor \
  --env "ANCHORBROWSER_BASE_URL=$GATEWAY,ANCHORBROWSER_API_KEY=held-by-the-connector" \
  -- bash -c "node browse.mjs"
```

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
```

> [!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 Sprite needs no desktop, tunnel or public URL for it.

![Anchor dashboard showing a running session with the live browser on Books to Scrape and its network requests](https://mintcdn.com/anchor-b3ec2715/eYinnaSf6G30CyB8/images/integrations/instabox/anchor-session.png?fit=max\&auto=format\&n=eYinnaSf6G30CyB8\&q=85\&s=30793ee5f6efb3f34eb091f0154eebc8)

## Lock the Sprite to Anchor

By default a Sprite can reach any public address. When the code inside is untrusted, set a network policy that allows two hosts only. Install the packages first, because the policy also blocks PyPI and npm.

```bash CLI theme={null}
fly sprites api /policy/network -sS -X POST -H "Content-Type: application/json" -d '{
  "rules": [
    { "domain": "api.sprites.dev", "action": "allow" },
    { "domain": "connect.anchorbrowser.io", "action": "allow" }
  ]
}'
sleep 5
```

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

from sprites import NetworkPolicy, PolicyRule, SpritesClient

sprite = SpritesClient(os.environ["SPRITES_TOKEN"]).sprite("anchor-demo")
sprite.update_network_policy(NetworkPolicy(rules=[
    PolicyRule(domain="api.sprites.dev", action="allow"),
    PolicyRule(domain="connect.anchorbrowser.io", action="allow"),
]))
time.sleep(5)
```

```typescript TypeScript theme={null}
import { SpritesClient } from "@fly/sprites";

const sprite = new SpritesClient(process.env.SPRITES_TOKEN!).sprite("anchor-demo");
await sprite.updateNetworkPolicy({
  rules: [
    { domain: "api.sprites.dev", action: "allow" },
    { domain: "connect.anchorbrowser.io", action: "allow" },
  ],
});
await new Promise((resolve) => setTimeout(resolve, 5000));
```

> [!WARNING]
>
> Wait a few seconds after every policy change before you start work. A policy applies at once, but in testing a request that started within about a second of the change, and took longer than a second to answer, was cut off and hung until its timeout. After a 3 second wait the same request passed every time. Session creation takes about 2 seconds, so it is exactly the kind of request this hits.

The task and Playwright scripts still pass in the locked Sprite. Everything else is refused at the DNS level, so it fails fast:

```bash theme={null}
fly sprites exec -- bash -c 'for h in example.org pypi.org api.anchorbrowser.io; do curl -s -m 8 -o /dev/null https://$h; echo "$h: curl exit $?"; done'
```

```text theme={null}
example.org: curl exit 6
pypi.org: curl exit 6
api.anchorbrowser.io: curl exit 6
```

`api.anchorbrowser.io` is blocked too. The Sprite cannot call Anchor's API directly, even if someone gave it a key. Its only route is the connector, which you can restrict and revoke.

| Host | Used for |
| - | - |
| `api.sprites.dev` | The connector gateway. Every Anchor API call from the Sprite goes through it |
| `connect.anchorbrowser.io` | The CDP websocket Playwright connects to |

The code can still browse any site, because the page loads happen in Anchor's browser, not in the Sprite. `live.anchorbrowser.io` is opened by the person watching, so it does not need to be on the list. `fly sprites exec` and the Sprites SDKs keep working under any policy.

To open the Sprite again, for example to install another package, post an empty rule list and wait before the next request:

```bash theme={null}
fly sprites api /policy/network -sS -X POST -H "Content-Type: application/json" -d '{"rules":[]}'
```

### Limit what the connector may call

The connector's access policy can also list the Anchor paths a Sprite may use. This one allows the session and tool endpoints and the MCP server, and nothing else:

```bash theme={null}
fly sprites api "/v1/oauth/connections/$ANCHOR_CONNECTION_ID" -sS \
  -X PUT -H "Content-Type: application/json" -d '{
  "access_policy": {
    "sprite_labels": ["anchor"],
    "allowed_endpoints": ["/v1/sessions", "/v1/sessions/*", "/v1/tools/*", "/v1/mcp"]
  }
}'
```

A call to a path that is not on the list gets `403` with `endpoint is not in allowed list`. The `*` matches the rest of the path, so `/v1/sessions/*` also covers the `/v1/sessions/all/status` check in the cleanup section.

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

Every Sprite has Claude Code and Codex installed. Register Anchor's hosted MCP server through the connector, and the agent can run web tasks without ever holding the key:

```bash theme={null}
fly sprites exec -- bash -c "claude mcp add --scope user --transport http anchor $GATEWAY/v1/mcp --header 'anchor-api-key: held-by-the-connector'"
fly sprites exec -- bash -c "claude mcp list"
```

```text theme={null}
anchor: https://api.sprites.dev/v1/gateway/custom_api/<connection-id>/v1/mcp (HTTP) - ✔ Connected
```

The registration in `/home/sprite/.claude.json` holds only the placeholder. This also works in the locked Sprite, because the MCP calls go through `api.sprites.dev`.

A locked Sprite also blocks the agent's own model provider. If you run a coding agent inside a locked Sprite, add the hosts that agent needs to the policy. For Claude Code that includes `api.anthropic.com`. See the [MCP server](https://docs.anchorbrowser.io/advanced/mcp.md) page for the tools Anchor's server 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 script that runs in the Sprite. A Sprite that goes to sleep or is destroyed does not end a cloud browser; it keeps running and billing until its own timeout.
* **The Sprite.** It sleeps by itself when idle and bills no compute while asleep, so you can keep it. Destroy it with `fly sprites destroy --yes -s anchor-demo` when you no longer need it.
* Set Anchor's `timeout.max_duration` and `timeout.idle_timeout`, in minutes, as a safety net for a script that stops 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 no browser is left running, ask Anchor from the Sprite:

```bash theme={null}
fly sprites exec -- bash -c "curl -s $GATEWAY/v1/sessions/all/status"
```

```text theme={null}
{"data":{"count":0,"items":[]}}
```

To remove the key from Fly.io, delete the connector. Every Sprite loses access at once:

```bash theme={null}
fly sprites api "/v1/oauth/connections/$ANCHOR_CONNECTION_ID" -sS -X DELETE
```

## API key

Create and manage Anchor API keys in the [Anchor dashboard](https://app.anchorbrowser.io/api-keys). To rotate the key, run the connector command again with the new key and the same `name`.

## Troubleshooting

| What you see | Cause and fix |
| - | - |
| `ModuleNotFoundError: No module named 'anchorbrowser'` | The command ran the system Python. Run it through `bash -c "python3 ..."` so the Sprite's managed Python is used |
| `getaddrinfo ENOTFOUND connect.sprites.dev` | `agent.task` or `agentTask` was used with the gateway as base URL. Use `perform_web_task` or `Tools.performWebTask` |
| `403` `sprite is missing required labels: anchor` | The Sprite does not have the label the connector asks for. Add it with `fly sprites config update --label anchor` |
| `403` `no access policy configured — connection denies all sprites by default` | The connector has no access policy. Set one, as in the create command above |
| `403` `endpoint is not in allowed list` | The path is not in the connector's `allowed_endpoints` |
| `404` from the gateway on your own machine | The gateway only answers calls that come from inside a Sprite |
| The first request after a policy change hangs | Wait a few seconds after changing the policy. If requests keep hanging, restart the Sprite from the dashboard |
| `curl` exits with code 6, or `dig` shows `status: REFUSED` | The host is not allowed by the network policy |
| `Sprites API token minted for this run could not be revoked` | The CLI creates a short-lived Sprites token per command. To stop that, give the CLI your Sprites token in `SPRITE_TOKEN`. The CLI reads that name, without the second S; `SPRITES_TOKEN` on this page is only the name the SDK scripts use |


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