Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

fix: keep browser references stable across cloud sessions

Gregor Žunič4ddd18d54927
diff --git a/browser_use/integrations/anthropic/browser_use.py b/browser_use/integrations/anthropic/browser_use.py
index 617c7861a..408fff67d 100644
--- a/browser_use/integrations/anthropic/browser_use.py
+++ b/browser_use/integrations/anthropic/browser_use.py
@@ -45,7 +45,7 @@ from .tab_state import PinnedTabSnapshot, consume_pinned_tabs, converged_active_
@dataclass(frozen=True)
class Reference:
tab: str
- document: int
+ document: str
backend: int
@@ -87,7 +87,7 @@ class BrowserUse(BetaAsyncAbstractBrowserToolset20260801):
self._refs: dict[str, Reference] = {}
self._ref_names: dict[Reference, str] = {}
self._next_ref = 1
- self._documents: dict[str, int] = {}
+ self._documents: dict[str, str] = {}
self._reported_tabs: set[str] = set()
self._last_tabs: list[dict] = []
self._observer: CDPClient | None = None
@@ -412,15 +412,26 @@ class BrowserUse(BetaAsyncAbstractBrowserToolset20260801):
self._documents.pop(tab, None)
async def _document(self, page):
- result = await self._cdp.send.DOM.getDocument(params={'depth': 0}, session_id=await page.session_id)
- document = result['root']['backendNodeId']
+ # Backend node IDs for the document root can differ across attached CDP
+ # sessions even when the page has not navigated. Cloud browsers may rotate
+ # those sessions between calls, so use the main frame and loader as the
+ # stable document identity. The loader changes on navigation; detached
+ # elements inside one document are still rejected by _resolve.
+ session_id = await page.session_id
+ result, _ = await asyncio.gather(
+ self._cdp.send.Page.getFrameTree(session_id=session_id),
+ # Prime the DOM domain for resolveNode on a newly attached session.
+ self._cdp.send.DOM.getDocument(params={'depth': 0}, session_id=session_id),
+ )
+ frame = result['frameTree']['frame']
+ document = f'{frame["id"]}:{frame.get("loaderId", "")}'
tab = page._target_id
if self._documents.get(tab) != document:
self._invalidate_refs(tab)
self._documents[tab] = document
return document
- def _reference(self, page, document, backend):
+ def _reference(self, page, document: str, backend: int):
reference = Reference(page._target_id, document, backend)
if reference not in self._ref_names:
name = f'ref_{self._next_ref}'
diff --git a/examples/integrations/anthropic/README.md b/examples/integrations/anthropic/README.md
index 23b135a84..28ea30b94 100644
--- a/examples/integrations/anthropic/README.md
+++ b/examples/integrations/anthropic/README.md
@@ -101,6 +101,8 @@ Set `BROWSER_USE_API_KEY`, then change one line:
driver = BrowserUse(use_cloud=True)
```
+Create a key at
+[cloud.browser-use.com/new-api-key](https://cloud.browser-use.com/new-api-key).
The driver creates a Browser Use Cloud browser, connects to it over CDP, and
stops it when the context exits.
@@ -166,24 +168,33 @@ The working directory is a boundary for generated files, not an operating
system sandbox. Run the SDK process inside your normal container or sandbox
when tasks may contain untrusted instructions.
-## Approvals and high-risk actions
+## Optional actions and approvals
-Anthropic's SDK calls `confirm` for actions that require approval. Keep
-`javascript_exec` and `file_upload` disabled unless your application needs
-them:
+Anthropic leaves `javascript_exec`, `file_upload`, `read_console`, and
+`read_network` disabled by default. Enabling JavaScript or file upload
+requires a `confirm` callback. When a callback is present, the SDK calls it
+before every browser action, so approve routine actions in code and prompt a
+person only for the actions your application treats as sensitive:
```python
async def confirm(context):
- return await app.approve(
- action=context.member,
- tab_id=context.tab_id,
+ if context.member not in {'javascript_exec', 'file_upload'}:
+ return True
+ return await app.approve(
+ action=context.member,
+ tab_id=context.tab_id,
tab_url=context.tab_url,
)
driver = BrowserUse(
- confirm=confirm,
- configs={'javascript_exec': {'enabled': True}},
+ confirm=confirm,
+ configs={
+ 'javascript_exec': {'enabled': True},
+ 'file_upload': {'enabled': True},
+ 'read_console': {'enabled': True},
+ 'read_network': {'enabled': True},
+ },
)
```
diff --git a/examples/integrations/anthropic/quickstart.py b/examples/integrations/anthropic/quickstart.py
index 528222fc6..23a2d8ec0 100644
--- a/examples/integrations/anthropic/quickstart.py
+++ b/examples/integrations/anthropic/quickstart.py
@@ -11,28 +11,28 @@ from browser_use.integrations.anthropic import Bash, BrowserUse
async def main() -> None:
driver = BrowserUse()
+ # driver = BrowserUse(use_cloud=True) # Requires BROWSER_USE_API_KEY
bash = Bash(output_dir=Path('outputs'))
- async with driver:
- async with AsyncAnthropic() as client:
- runner = client.beta.messages.tool_runner(
- model=os.environ['ANTHROPIC_MODEL'],
- max_tokens=32_768,
- max_iterations=1_000,
- tools=[driver, bash],
- system=(
- 'Complete the task autonomously. Use Browser Use for browser actions. '
- 'Use Bash for local computation and files in outputs/.'
- ),
- messages=[
- {
- 'role': 'user',
- 'content': 'Open example.com and save its page title to title.txt.',
- }
- ],
- )
- final = await runner.until_done()
- print('\n'.join(block.text for block in final.content if block.type == 'text'))
+ async with driver, AsyncAnthropic() as client:
+ runner = client.beta.messages.tool_runner(
+ model=os.environ['ANTHROPIC_MODEL'],
+ max_tokens=32_768,
+ max_iterations=1_000,
+ tools=[driver, bash],
+ system=(
+ 'Complete the task autonomously. Use Browser Use for browser actions. '
+ 'Use Bash for local computation and files in outputs/.'
+ ),
+ messages=[
+ {
+ 'role': 'user',
+ 'content': 'Open example.com and save its page title to title.txt.',
+ }
+ ],
+ )
+ final = await runner.until_done()
+ print('\n'.join(block.text for block in final.content if block.type == 'text'))
if __name__ == '__main__':
diff --git a/skills/open-source/SKILL.md b/skills/open-source/SKILL.md
index 1a32db147..70ca76ee3 100644
--- a/skills/open-source/SKILL.md
+++ b/skills/open-source/SKILL.md
@@ -27,7 +27,7 @@ Read the relevant file based on what the user needs.
| Browser params, auth, real browser, remote/cloud | `references/browser.md` |
| Custom tools, built-in tools, ActionResult | `references/tools.md` |
| Actor API: Page/Element/Mouse (legacy) | `references/actor.md` |
-| MCP server, skills, docs-mcp | `references/integrations.md` |
+| Anthropic browser toolset, MCP server, skills, docs-mcp | `references/integrations.md` |
| Laminar, OpenLIT, cost tracking, telemetry | `references/monitoring.md` |
| Fast agent, parallel, playwright, sensitive data | `references/examples.md` |
diff --git a/skills/open-source/references/integrations.md b/skills/open-source/references/integrations.md
index 4bb789238..71b27909f 100644
--- a/skills/open-source/references/integrations.md
+++ b/skills/open-source/references/integrations.md
@@ -1,6 +1,7 @@
-# Integrations (MCP, Skills, Docs)
+# Integrations
## Table of Contents
+- [Anthropic browser toolset](#anthropic-browser-toolset)
- [MCP Server (Cloud)](#mcp-server-cloud)
- [MCP Server (Local)](#mcp-server-local)
- [Skills](#skills)
@@ -8,6 +9,123 @@
---
+## Anthropic browser toolset
+
+Browser Use and Anthropic collaborated so Claude can use Browser Use as the
+driver behind Anthropic's browser toolset. Anthropic's SDK owns the model loop
+and tool runner. Browser Use implements the 31 browser actions and connects
+them to local Chromium, Browser Use Cloud, or an existing browser over CDP.
+
+Requirements:
+
+- Python 3.11 or newer
+- An Anthropic SDK release with `anthropic.tools.browser` and
+ `client.beta.messages.tool_runner`
+- `ANTHROPIC_API_KEY` and the model ID Anthropic documents for the browser
+ toolset
+- `BROWSER_USE_API_KEY` only when using Browser Use Cloud. Create one at
+ [cloud.browser-use.com/new-api-key](https://cloud.browser-use.com/new-api-key).
+
+Install the packages and local Chromium:
+
+```bash
+uv init --python 3.12
+uv add browser-use anthropic
+uvx browser-use install
+```
+
+Create `run_browser.py`:
+
+```python
+import asyncio
+import os
+from pathlib import Path
+
+from anthropic import AsyncAnthropic
+
+from browser_use.integrations.anthropic import Bash, BrowserUse
+
+
+async def main() -> None:
+ task = 'Open example.com and save its page title to title.txt.'
+ driver = BrowserUse()
+ # driver = BrowserUse(use_cloud=True) # Requires BROWSER_USE_API_KEY
+ bash = Bash(output_dir=Path('outputs'))
+
+ async with driver, AsyncAnthropic() as client:
+ runner = client.beta.messages.tool_runner(
+ model=os.environ['ANTHROPIC_MODEL'],
+ max_tokens=32_768,
+ max_iterations=1_000,
+ tools=[driver, bash],
+ messages=[{'role': 'user', 'content': task}],
+ )
+ final = await runner.until_done()
+
+ print('\n'.join(block.text for block in final.content if block.type == 'text'))
+
+
+asyncio.run(main())
+```
+
+Set the Anthropic variables and run it:
+
+```bash
+export ANTHROPIC_API_KEY=your-key
+export ANTHROPIC_MODEL=your-model
+# Optional SDK request and tool-runner logs
+export ANTHROPIC_LOG=info
+
+uv run run_browser.py
+```
+
+The `async with driver` block starts and closes a driver-owned local or Cloud
+browser. When passing an already-started `BrowserSession`, the application
+starts and closes that session instead.
+
+`BrowserUse` implements all 31 actions. Anthropic leaves
+`javascript_exec`, `file_upload`, `read_console`, and `read_network`
+disabled by default. Enable only the capabilities the application needs:
+
+```python
+async def confirm(context):
+ if context.member not in {'javascript_exec', 'file_upload'}:
+ return True
+ return await app.approve(context.member, context.tab_url)
+
+
+driver = BrowserUse(
+ confirm=confirm,
+ configs={
+ 'javascript_exec': {'enabled': True},
+ 'file_upload': {'enabled': True},
+ 'read_console': {'enabled': True},
+ 'read_network': {'enabled': True},
+ },
+)
+```
+
+`Bash` is a separate bounded tool for local computation and deliverables:
+
+```python
+bash = Bash(output_dir='outputs', timeout_seconds=120, max_output_bytes=50_000)
+```
+
+Bash strips ambient credentials from child commands and limits execution time
+and returned output. Its working directory is a file boundary, not an operating
+system sandbox. Run the SDK process in your normal container or sandbox for
+untrusted tasks.
+
+For a remote browser, upload paths must already exist on the browser host.
+Local files created by Bash are not copied to that host automatically. Use the
+SDK's file policy and a `document_resolver` that maps approved document IDs to
+browser-host paths.
+
+See the complete
+[quickstart, runtime examples, action list, and file guidance](../../../examples/integrations/anthropic/README.md).
+
+---
+
## MCP Server (Cloud)
HTTP-based MCP server at `https://api.browser-use.com/mcp`
diff --git a/tests/ci/integrations/test_anthropic_browser_use.py b/tests/ci/integrations/test_anthropic_browser_use.py
index c52131abc..6e3298c7e 100644
--- a/tests/ci/integrations/test_anthropic_browser_use.py
+++ b/tests/ci/integrations/test_anthropic_browser_use.py
@@ -8,6 +8,7 @@ import os
import subprocess
import sys
from pathlib import Path
+from types import SimpleNamespace
import pytest
@@ -118,6 +119,46 @@ def test_browser_use_rejects_a_borrowed_browser_with_cloud_selection() -> None:
BrowserUse(BrowserSession(), use_cloud=True)
+async def test_reference_document_identity_survives_cdp_session_rotation() -> None:
+ pytest.importorskip('anthropic.tools.browser')
+ from browser_use.integrations.anthropic import BrowserUse
+
+ class FakeCDP:
+ def __init__(self):
+ self.loader_id = 'loader-a'
+ self.send = SimpleNamespace(
+ Page=SimpleNamespace(getFrameTree=self.get_frame_tree),
+ DOM=SimpleNamespace(getDocument=self.get_document),
+ )
+
+ async def get_frame_tree(self, **kwargs):
+ return {'frameTree': {'frame': {'id': 'frame-a', 'loaderId': self.loader_id}}}
+
+ async def get_document(self, **kwargs):
+ return {'root': {'backendNodeId': 999}}
+
+ class FakePage:
+ _target_id = 'tab-a'
+
+ @property
+ async def session_id(self):
+ return 'rotating-session'
+
+ driver = BrowserUse()
+ driver.browser = SimpleNamespace(cdp_client=FakeCDP())
+ page = FakePage()
+ document = await driver._document(page)
+ ref = driver._reference(page, document, 42)
+ assert ref in driver._refs
+
+ assert await driver._document(page) == document
+ assert ref in driver._refs
+
+ driver.browser.cdp_client.loader_id = 'loader-b'
+ assert await driver._document(page) != document
+ assert ref not in driver._refs
+
+
def _tabs(active: str) -> list[dict]:
return [
{'tab_id': 'tab-a', 'url': 'https://a.example', 'title': 'A', 'active': active == 'tab-a'},