核心用法(2/3)
Log into websites using real browser profiles, saved storage state, and 2FA codes for authenticated automation.
Browser-Use supports multiple authentication strategies depending on your use case:
| Approach | Best For | Setup Effort |
|---|---|---|
| Real Browser | Personal automation, existing logins | Low |
| Storage State | Production, CI/CD, headless | Medium |
| TOTP 2FA | Sites with authenticator apps | Low |
| Email and SMS 2FA | Sites with email/SMS verification | Medium |
Real Browser Profiles
Connect to your existing Chrome browser to reuse your authenticated sessions. No need to handle logins, cookies, or 2FA - if you are logged in on Chrome, the agent is, too.
See Real Browser for more details and platform paths.
You may need to close Chrome completely before running. Browser-Use launches Chrome in debug mode, which can conflict with existing Chrome processes.
from browser_use import Agent, Browser, ChatBrowserUse
# Auto-detect Chrome and profile (cross-platform)
browser = Browser.from_system_chrome()
agent = Agent(
task='Check my Gmail inbox',
browser=browser,
llm=ChatBrowserUse(),
)
await agent.run()
Storage State Persistence
Export cookies and localStorage from an authenticated browser, then load them in headless mode. Useful for production/CI where you cannot use a real browser profile.
See Browser Parameters for all storage options.
Export from Real Browser
from browser_use import Browser
browser = Browser.from_system_chrome()
await browser.start()
await browser.export_storage_state('auth.json')
await browser.stop()
Load in Headless Mode
from browser_use import Agent, Browser, ChatBrowserUse
browser = Browser(storage_state='auth.json')
agent = Agent(
task='Check my notifications',
browser=browser,
llm=ChatBrowserUse(),
)
await agent.run()
Auto-Save and Load
When you provide a storage_state path, Browser-Use automatically:
- Loads cookies from the file on startup (if it exists)
- Saves cookies to the file periodically and on shutdown
browser = Browser(storage_state='session.json')
The file is created if it does not exist, and new cookies are merged with existing ones on each save.
Storage State Format
The JSON file follows Playwright's format:
{
"cookies": [
{
"name": "session_id",
"value": "abc123",
"domain": ".example.com",
"path": "/",
"expires": 1704067200,
"httpOnly": true,
"secure": true,
"sameSite": "Lax"
}
],
"origins": [
{
"origin": "https://example.com",
"localStorage": [
{"name": "auth_token", "value": "xyz789"}
]
}
]
}
TOTP 2FA
For sites using authenticator apps (Google Authenticator, 1Password, etc.), Browser-Use can generate TOTP codes automatically.
See Sensitive Data for more on credential handling.
How It Works
- Get the TOTP secret key when setting up 2FA (usually shown as "manual entry" or "cannot scan QR code")
- Pass the secret with
bu_2fa_codesuffix insensitive_data - When the agent inputs
bu_2fa_code, it generates a fresh 6-digit code
from browser_use import Agent, ChatBrowserUse
# TOTP secret from your authenticator setup
# (NOT the 6-digit code - the secret key itself)
totp_secret = 'JBSWY3DPEHPK3PXP'
agent = Agent(
task='''
1. Go to https://example.com/login
2. Enter username x_user and password x_pass
3. When prompted for 2FA, enter bu_2fa_code
''',
sensitive_data={
'x_user': 'myusername',
'x_pass': 'mypassword',
'bu_2fa_code': totp_secret, # suffix must be bu_2fa_code
},
llm=ChatBrowserUse(),
)
await agent.run()
The placeholder name must end with bu_2fa_code. You can use any prefix: google_bu_2fa_code, github_bu_2fa_code, etc.
Where to Find TOTP Secrets
- 1Password: Edit item → One-Time Password → Show secret
- Google Authenticator: During setup, click "Can't scan it?" to see the key
- Authy: Export via desktop app settings
- Most sites: Look for "manual entry" or "setup key" during 2FA enrollment
Email and SMS 2FA
For sites that send verification codes via email or SMS, use follow-up tasks to retrieve the code.
With AgentMail
AgentMail provides disposable inboxes for email verification:
from agentmail import AsyncAgentMail
from browser_use import Agent, ChatBrowserUse, Tools, ActionResult
email_client = AsyncAgentMail()
inbox = await email_client.inboxes.create()
tools = Tools()
@tools.registry.action('Get email address for signup')
async def get_email_address():
return ActionResult(extracted_content=inbox.inbox_id)
@tools.registry.action('Get verification code from email')
async def get_verification_code():
emails = await email_client.inboxes.messages.list(inbox_id=inbox.inbox_id)
if emails.messages:
return ActionResult(extracted_content=emails.messages[0].text)
return ActionResult(error='No emails found')
agent = Agent(
task='Sign up at example.com, get verification code from email',
tools=tools,
llm=ChatBrowserUse(),
)
await agent.run()
See examples/integrations/agentmail/ for a more complete implementation with email waiting and parsing.
With 1Password SDK
Retrieve codes from your password manager:
import os
from onepassword.client import Client
from browser_use import Agent, Tools, ActionResult, ChatBrowserUse
tools = Tools()
@tools.registry.action('Get 2FA code from 1Password', domains=['*.google.com'])
async def get_1password_2fa():
client = await Client.authenticate(
auth=os.environ['OP_SERVICE_ACCOUNT_TOKEN'],
integration_name='Browser-Use',
integration_version='v1.0.0',
)
code = await client.secrets.resolve('op://Private/Google/One-time passcode')
return ActionResult(extracted_content=code)
agent = Agent(
task='Login to Google and check email',
tools=tools,
llm=ChatBrowserUse(),
)
await agent.run()
See examples/custom-functions/onepassword_2fa.py for the full example.
With Gmail API
Built-in Gmail integration for reading 2FA codes from your inbox:
from browser_use import Agent, ChatBrowserUse, Tools
from browser_use.integrations.gmail import GmailService, register_gmail_actions
gmail_service = GmailService()
tools = Tools()
register_gmail_actions(tools, gmail_service=gmail_service)
agent = Agent(
task='Login to example.com, then get the verification code from Gmail',
tools=tools,
llm=ChatBrowserUse(),
)
await agent.run()
Requires Gmail API setup:
- Enable Gmail API in Google Cloud Console
- Create OAuth 2.0 credentials (Desktop app)
- Save credentials to
~/.config/browseruse/gmail_credentials.json
See examples/integrations/gmail_2fa_integration.py for setup with automatic credential validation.
Security Best Practices
See Secure Setup for enterprise security with Azure OpenAI.
Restrict Domains
Limit where the browser can navigate to prevent credential leaks:
browser = Browser(
allowed_domains=['*.example.com', 'auth.example.com'],
)
Disable Vision for Sensitive Pages
Prevent screenshots from being sent to the LLM:
agent = Agent(
task='Login and check balance',
use_vision=False, # No screenshots sent to LLM
sensitive_data={'password': 'secret123'},
llm=ChatBrowserUse(),
)
Domain-Specific Credentials
Route credentials to specific domains only:
sensitive_data = {
'https://*.work.com': {
'work_user': 'alice@work.com',
'work_pass': 'work_password',
},
'https://personal.com': {
'personal_user': 'alice@gmail.com',
'personal_pass': 'personal_password',
},
}
Cloud Browser Profiles
For production deployments, consider Browser Use Cloud, which provides:
- Persistent browser profiles in the cloud
- Pre-authenticated sessions
- No local Chrome installation required
- Built-in proxy and fingerprint management
from browser_use import Agent, Browser, ChatBrowserUse
browser = Browser(cdp_url='wss://cloud.browser-use.com/...')
agent = Agent(
task='Check my orders',
browser=browser,
llm=ChatBrowserUse(),
)
await agent.run()
Complete reference for all browser configuration options — launch args, proxy, viewport, user data, and CDP settings.
The Browser instance also provides all Actor methods for direct browser control (page management, element interactions, etc.).
Core Settings
cdp_url: CDP URL for connecting to existing browser instance (e.g.,"http://localhost:9222")
Display & Appearance
headless(default:None): Run browser without UI. Auto-detects based on display availability (True/False/None)window_size: Browser window size for headful mode. Use dict{'width': 1920, 'height': 1080}orViewportSizeobjectwindow_position(default:{'width': 0, 'height': 0}): Window position from top-left corner in pixelsviewport: Content area size, same format aswindow_size. Use{'width': 1280, 'height': 720}orViewportSizeobjectno_viewport(default:None): Disable viewport emulation, content fits to window sizedevice_scale_factor: Device scale factor (DPI). Set to2.0or3.0for high-resolution screenshots
Browser Behavior
keep_alive(default:None): Keep browser running after agent completesallowed_domains: Restrict navigation to specific domains. Domain pattern formats:'example.com'- Matches onlyhttps://example.com/*'*.example.com'- Matcheshttps://example.com/*and any subdomainhttps://*.example.com/*'http*://example.com'- Matches bothhttp://andhttps://protocols'chrome-extension://*'- Matches any Chrome extension URL- Security: Wildcards in TLD (e.g.,
example.*) are not allowed for security - Use list like
['*.google.com', 'https://example.com', 'chrome-extension://*'] - Performance: Lists with 100+ domains are automatically optimized to sets for O(1) lookup. Pattern matching is disabled for optimized lists. Both
www.example.comandexample.comvariants are checked automatically. prohibited_domains: Block navigation to specific domains. Uses same pattern formats asallowed_domains. When bothallowed_domainsandprohibited_domainsare set,allowed_domainstakes precedence. Examples:['pornhub.com', '*.gambling-site.net']- Block specific sites and all subdomains['https://explicit-content.org']- Block specific protocol/domain combination- Performance: Lists with 100+ domains are automatically optimized to sets for O(1) lookup (same as
allowed_domains) enable_default_extensions(default:True): Load automation extensions (uBlock Origin, cookie handlers, ClearURLs)cross_origin_iframes(default:False): Enable cross-origin iframe support (may cause complexity)is_local(default:True): Whether this is a local browser instance. Set toFalsefor remote browsers. If we have aexecutable_pathset, it will be automatically set toTrue. This can affect your download behavior.
User Data & Profiles
user_data_dir(default: auto-generated temp): Directory for browser profile data. UseNonefor incognito modeprofile_directory(default:'Default'): Chrome profile subdirectory name ('Profile 1','Work Profile', etc.)storage_state: Browser storage state (cookies, localStorage). Can be file path string or dict object
Network & Security
-
proxy: Proxy configuration usingProxySettings(server='http://host:8080', bypass='localhost,127.0.0.1', username='user', password='pass') -
permissions(default:['clipboardReadWrite', 'notifications']): Browser permissions to grant. Use list like['camera', 'microphone', 'geolocation'] -
headers: Additional HTTP headers for connect requests (remote browsers only)
Browser Launch
executable_path: Path to browser executable for custom installations. Platform examples:- macOS:
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' - Windows:
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe' - Linux:
'/usr/bin/google-chrome' channel: Browser channel ('chromium','chrome','chrome-beta','msedge', etc.)args: Additional command-line arguments for the browser. Use list format:['--disable-gpu', '--custom-flag=value', '--another-flag']env: Environment variables for browser process. Use dict like{'DISPLAY': ':0', 'LANG': 'en_US.UTF-8', 'CUSTOM_VAR': 'test'}chromium_sandbox(default:Trueexcept in Docker): Enable Chromium sandboxing for securitydevtools(default:False): Open DevTools panel automatically (requiresheadless=False)ignore_default_args: List of default args to disable, orTrueto disable all. Use list like['--enable-automation', '--disable-extensions']
Timing & Performance
minimum_wait_page_load_time(default:0.25): Minimum time to wait before capturing page state in secondswait_for_network_idle_page_load_time(default:0.5): Time to wait for network activity to cease in secondswait_between_actions(default:0.1): Time to wait between agent actions in seconds
AI Integration
highlight_elements(default:True): Highlight interactive elements for AI visionpaint_order_filtering(default:True): Enable paint order filtering to optimize DOM tree by removing elements hidden behind others. Slightly experimental
Downloads & Files
accept_downloads(default:True): Automatically accept all downloadsdownloads_path: Directory for downloaded files. Use string like'./downloads'orPathobjectauto_download_pdfs(default:True): Automatically download PDFs instead of viewing in browser
Device Emulation
user_agent: Custom user agent string. Example:'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)'screen: Screen size information, same format aswindow_size
Recording & Debugging
Video recording requires additional optional dependencies. If these are not installed, no video will be saved and no error will be raised.
Install with:
pip install "browser-use[video]"
or:
pip install "imageio[ffmpeg]" numpy
record_video_dir: Directory to save video recordings as.mp4filesrecord_video_size(default:ViewportSize): The frame size (width, height) of the video recording.record_video_framerate(default:30): The framerate to use for the video recording.record_har_path: Path to save network trace files as.harformattraces_dir: Directory to save complete trace files for debuggingrecord_har_content(default:'embed'): HAR content mode ('omit','embed','attach')record_har_mode(default:'full'): HAR recording mode ('full','minimal')
Advanced Options
disable_security(default:False): ⚠️ NOT RECOMMENDED - Disables all browser security featuresdeterministic_rendering(default:False): ⚠️ NOT RECOMMENDED - Forces consistent rendering but reduces performance
Outdated BrowserProfile
For backward compatibility, you can pass all the parameters from above to the BrowserProfile and then to the Browser.
from browser_use import BrowserProfile
profile = BrowserProfile(headless=False)
browser = Browser(browser_profile=profile)
Browser vs BrowserSession
Browser is an alias for BrowserSession - they are exactly the same class:
Use Browser for cleaner, more intuitive code.
Class Methods
Browser.from_system_chrome()
Creates a Browser instance using your system's Chrome installation and profile. Automatically detects Chrome executable and user data directory for your platform.
from browser_use import Browser
# Auto-select first available profile
browser = Browser.from_system_chrome()
# Or specify a profile
browser = Browser.from_system_chrome(profile_directory='Profile 1')
Parameters:
profile_directory(default:None): Chrome profile to use ('Default','Profile 1', etc.). IfNone, auto-selects the first available profile.**kwargs: Additional arguments passed toBrowser()constructor (e.g.,headless=False)
Returns: Browser instance configured to use your system Chrome
Raises: RuntimeError if Chrome is not found on your system
Note: You may need to fully close Chrome before using this, so Chrome profiles aren't used by multiple instances simultaneously.
Browser.list_chrome_profiles()
Lists available Chrome profiles on the system.
from browser_use import Browser
profiles = Browser.list_chrome_profiles()
for p in profiles:
print(f"{p['directory']}: {p['name']}")
# Output:
# Profile 1: Work
# Profile 5: Personal
Returns: List of dicts with 'directory' and 'name' keys
Example return value:
[
{'directory': 'Default', 'name': 'Person 1'},
{'directory': 'Profile 1', 'name': 'Work'},
{'directory': 'Profile 5', 'name': 'Personal'}
]
Complete reference for all agent configuration options — LLM settings, prompts, tools, output format, and callbacks.
Available Parameters
Core Settings
tools: Registry of ../tools/available the agent can call. ../tools/basicsskills(orskill_ids): List of skill IDs to load (e.g.,['skill-uuid']or['*']for all). RequiresBROWSER_USE_API_KEY. ../skills/basicsbrowser: Browser object where you can specify the browser settings.output_model_schema: Pydantic model class for structured output validation. Example
Vision & Processing
use_vision(default:True): Vision mode -"auto"includes screenshot tool but only uses vision when requested,Truealways includes screenshots,Falsenever includes screenshots and excludes screenshot toolvision_detail_level(default:'auto'): Screenshot detail level -'low','high', or'auto'page_extraction_llm: Separate LLM model for page content extraction. You can choose a small & fast model because it only needs to extract text from the page (default: same asllm)
Fallback & Resilience
fallback_llm: Backup LLM to use when the primary LLM fails. The primary LLM will first exhaust its own retry logic (typically 5 attempts with exponential backoff), and only then switch to the fallback. Triggers on rate limits (429), authentication errors (401), payment/credit errors (402), or server errors (500, 502, 503, 504). Once switched, the fallback is used for the rest of the run. Example
Actions & Behavior
initial_actions: List of actions to run before the main task without LLM. Examplemax_actions_per_step(default:5): Maximum actions per step, e.g. for form filling the agent can output 4 fields at once. We execute the actions until the page changes.max_failures(default:5): Maximum retries for steps with errorsfinal_response_after_failure(default:True): If True, attempt to force one final model call with intermediate output after max_failures is reacheduse_thinking(default:True): Controls whether the agent uses its internal "thinking" field for explicit reasoning steps.flash_mode(default:False): Fast mode that skips evaluation, next goal and thinking and only uses memory. Ifflash_modeis enabled, it overridesuse_thinkingand disables the thinking process entirely. Example
System Messages
override_system_message: Completely replace the default system prompt.extend_system_message: Add additional instructions to the default system prompt. Example
File & Data Management
save_conversation_path: Path to save complete conversation historysave_conversation_path_encoding(default:'utf-8'): Encoding for saved conversationsavailable_file_paths: List of file paths the agent can accesssensitive_data: Dictionary of sensitive data to handle carefully. Example
Visual Output
generate_gif(default:False): Generate GIF of agent actions. Set toTrueor string pathinclude_attributes: List of HTML attributes to include in page analysis
Performance & Limits
max_history_items: Maximum number of last steps to keep in the LLM memory. IfNone, we keep all steps.llm_timeout(default:None): Timeout in seconds for LLM calls. When omitted, the agent selects a model-dependent timeout of 30, 75, or 90 secondsstep_timeout(default:180): Timeout in seconds for each stepdirectly_open_url(default:True): If we detect a url in the task, we directly open it.
Advanced Options
calculate_cost(default:False): Calculate and track API costsdisplay_files_in_done_text(default:True): Show file information in completion messages
Backwards Compatibility
controller: Alias fortoolsfor backwards compatibility.browser_session: Alias forbrowserfor backwards compatibility.
Environment Variables
These environment variables can be used to tune agent and browser behavior without code changes. They are particularly useful for debugging, slow networks, or deployment-level tuning.
Agent Timeouts
| Variable | Default | Description |
|---|---|---|
TIMEOUT_AgentEventBusStop |
3.0 |
Timeout in seconds for the agent's event bus to finish processing pending events during shutdown. |
Browser Action Timeouts
| Variable | Default | Description |
|---|---|---|
TIMEOUT_NavigateToUrlEvent |
30.0 |
Timeout for page navigation |
TIMEOUT_ClickElementEvent |
15.0 |
Timeout for clicking elements |
TIMEOUT_ClickCoordinateEvent |
15.0 |
Timeout for clicking at coordinates |
TIMEOUT_TypeTextEvent |
60.0 |
Timeout for typing text (longer for large inputs) |
TIMEOUT_ScrollEvent |
8.0 |
Timeout for scrolling |
TIMEOUT_ScrollToTextEvent |
15.0 |
Timeout for scrolling to find text |
TIMEOUT_SendKeysEvent |
60.0 |
Timeout for sending keyboard shortcuts |
TIMEOUT_UploadFileEvent |
30.0 |
Timeout for file uploads |
TIMEOUT_GetDropdownOptionsEvent |
15.0 |
Timeout for fetching dropdown options |
TIMEOUT_SelectDropdownOptionEvent |
8.0 |
Timeout for selecting dropdown option |
TIMEOUT_GoBackEvent |
15.0 |
Timeout for browser back navigation |
TIMEOUT_GoForwardEvent |
15.0 |
Timeout for browser forward navigation |
TIMEOUT_RefreshEvent |
15.0 |
Timeout for page refresh |
TIMEOUT_WaitEvent |
60.0 |
Timeout for explicit wait actions |
TIMEOUT_ScreenshotEvent |
15.0 |
Timeout for taking screenshots |
TIMEOUT_BrowserStateRequestEvent |
30.0 |
Timeout for fetching browser state/DOM |
Browser Lifecycle Timeouts
| Variable | Default | Description |
|---|---|---|
TIMEOUT_BrowserStartEvent |
30.0 |
Timeout for starting browser session |
TIMEOUT_BrowserStopEvent |
45.0 |
Timeout for stopping browser session |
TIMEOUT_BrowserLaunchEvent |
30.0 |
Timeout for launching browser process |
TIMEOUT_BrowserKillEvent |
30.0 |
Timeout for killing browser process |
TIMEOUT_BrowserConnectedEvent |
30.0 |
Timeout for CDP connection |
TIMEOUT_BrowserStoppedEvent |
30.0 |
Timeout for browser stopped confirmation |
TIMEOUT_BrowserErrorEvent |
30.0 |
Timeout for browser error events |
Tab Management Timeouts
| Variable | Default | Description |
|---|---|---|
TIMEOUT_SwitchTabEvent |
10.0 |
Timeout for switching tabs |
TIMEOUT_CloseTabEvent |
10.0 |
Timeout for closing tabs |
TIMEOUT_TabCreatedEvent |
30.0 |
Timeout for tab creation events |
TIMEOUT_TabClosedEvent |
10.0 |
Timeout for tab closed events |
TIMEOUT_AgentFocusChangedEvent |
10.0 |
Timeout for focus change events |
TIMEOUT_TargetCrashedEvent |
10.0 |
Timeout for crash events |
Navigation Event Timeouts
| Variable | Default | Description |
|---|---|---|
TIMEOUT_NavigationStartedEvent |
30.0 |
Timeout for navigation started events |
TIMEOUT_NavigationCompleteEvent |
30.0 |
Timeout for navigation complete events |
Storage & Download Timeouts
| Variable | Default | Description |
|---|---|---|
TIMEOUT_SaveStorageStateEvent |
45.0 |
Timeout for saving cookies/localStorage |
TIMEOUT_StorageStateSavedEvent |
30.0 |
Timeout for storage save confirmation |
TIMEOUT_LoadStorageStateEvent |
45.0 |
Timeout for loading storage state |
TIMEOUT_StorageStateLoadedEvent |
30.0 |
Timeout for storage load confirmation |
TIMEOUT_FileDownloadedEvent |
30.0 |
Timeout for file download events |
Example Usage
# Increase timeouts for slow network or complex pages
export TIMEOUT_NavigateToUrlEvent=30.0
export TIMEOUT_TypeTextEvent=120.0
export TIMEOUT_BrowserStateRequestEvent=60.0
# Increase agent shutdown timeout
export TIMEOUT_AgentEventBusStop=10.0
Run browser-use as a local Model Context Protocol server. Connect AI models to browser automation through the MCP standard.
Browser Use can run as a local Model Context Protocol (MCP) server on your machine via stdio. This is the free, open-source option that gives you direct, low-level control over browser automation but requires your own LLM API keys.
Looking for a hosted solution? Use the Cloud MCP Server instead — no setup required, just an API key.
Quick Start
uvx --from 'browser-use[cli]' browser-use --mcp
The server will start in stdio mode, ready to accept MCP connections.
Client Setup
claude mcp add browser-use -- uvx --from 'browser-use[cli]' browser-use --mcp
Add to your Claude Desktop config file:
**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
{
"mcpServers": {
"browser-use": {
"command": "/Users/your-username/.local/bin/uvx",
"args": ["--from", "browser-use[cli]", "browser-use", "--mcp"],
"env": {
"OPENAI_API_KEY": "your-openai-api-key-here"
}
}
}
}
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
{
"mcpServers": {
"browser-use": {
"command": "uvx",
"args": ["--from", "browser-use[cli]", "browser-use", "--mcp"],
"env": {
"OPENAI_API_KEY": "your-openai-api-key-here"
}
}
}
}
Restart Claude Desktop after saving.
**macOS/Linux PATH Issue:** Claude Desktop may not find `uvx` in your PATH. Use the full path to `uvx` instead:
* Run `which uvx` in your terminal to find the location (usually `/Users/username/.local/bin/uvx` or `~/.local/bin/uvx`)
* Replace `"command": "uvx"` with the full path, e.g., `"command": "/Users/your-username/.local/bin/uvx"`
* Replace `your-username` with your actual username
**CLI Extras Required:** The `--from browser-use[cli]` flag installs the CLI extras needed for MCP server support.
Add to `~/.cursor/mcp.json`:
{
"mcpServers": {
"browser-use": {
"command": "uvx",
"args": ["--from", "browser-use[cli]", "browser-use", "--mcp"],
"env": {
"OPENAI_API_KEY": "your-openai-api-key-here"
}
}
}
}
Add to `~/.codeium/windsurf/mcp_config.json`:
{
"mcpServers": {
"browser-use": {
"command": "uvx",
"args": ["--from", "browser-use[cli]", "browser-use", "--mcp"],
"env": {
"OPENAI_API_KEY": "your-openai-api-key-here"
}
}
}
}
Environment Variables
OPENAI_API_KEY- Your OpenAI API key (required)ANTHROPIC_API_KEY- Your Anthropic API key (alternative to OpenAI)BROWSER_USE_HEADLESS- Set tofalseto show browser windowBROWSER_USE_DISABLE_SECURITY- Set totrueto disable browser security features
Available Tools
The local MCP server exposes these low-level browser automation tools for direct control:
Autonomous Agent Tools
retry_with_browser_use_agent- Run a complete browser automation task with an AI agent (use as last resort when direct control fails)
Direct Browser Control
browser_navigate- Navigate to a URLbrowser_click- Click on an element by indexbrowser_type- Type text into an elementbrowser_get_state- Get current page state and interactive elementsbrowser_scroll- Scroll the pagebrowser_go_back- Go back in browser history
Tab Management
browser_list_tabs- List all open browser tabsbrowser_switch_tab- Switch to a specific tabbrowser_close_tab- Close a tab
Content Extraction
browser_extract_content- Extract structured content from the current pagebrowser_get_html- Return the full page HTML or one CSS-selected elementbrowser_screenshot- Capture the viewport or the full scrollable page
Session Management
browser_list_sessions- List all active browser sessions with detailsbrowser_close_session- Close a specific browser session by IDbrowser_close_all- Close all active browser sessions
Example Usage
Once configured, you can ask your AI to perform browser automation tasks:
"Please navigate to example.com and take a screenshot"
"Search for 'browser automation' on Google and summarize the first 3 results"
"Go to GitHub, find the browser-use repository, and tell me about the latest release"
Programmatic Usage
You can also connect to the MCP server programmatically:
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def use_browser_mcp():
# Connect to browser-use MCP server
server_params = StdioServerParameters(
command="uvx",
args=["--from", "browser-use[cli]", "browser-use", "--mcp"]
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# Navigate to a website
result = await session.call_tool(
"browser_navigate",
arguments={"url": "https://example.com"}
)
print(result.content[0].text)
# Get page state
result = await session.call_tool(
"browser_get_state",
arguments={"include_screenshot": True}
)
print("Page state retrieved!")
asyncio.run(use_browser_mcp())
Troubleshooting
"CLI addon is not installed" Error
Make sure you are using --from 'browser-use[cli]' in your uvx command:
uvx --from 'browser-use[cli]' browser-use --mcp
"spawn uvx ENOENT" Error (macOS/Linux)
Claude Desktop cannot find uvx in its PATH. Use the full path in your config:
- Run
which uvxin terminal to find the location - Update your config to use the full path (e.g.,
/Users/your-username/.local/bin/uvx)
Browser doesn't start
- Check that you have Chrome/Chromium installed
- Try setting
BROWSER_USE_HEADLESS=falseto see browser window - Ensure no other browser instances are using the same profile
API Key Issues
- Verify your
OPENAI_API_KEYis set correctly - Check API key permissions and billing status
- Try using
ANTHROPIC_API_KEYas an alternative
Connection Issues in Claude Desktop
- Restart Claude Desktop after config changes
- Check the config file syntax is valid JSON
- Verify the file path is correct for your OS
- Check logs at
~/Library/Logs/Claude/(macOS) or%APPDATA%\Claude\Logs\(Windows)
Debug Mode
Enable debug logging by setting:
export BROWSER_USE_LOGGING_LEVEL=DEBUG
uvx --from 'browser-use[cli]' browser-use --mcp
Security Considerations
- The MCP server has access to your browser and file system
- Only connect trusted MCP clients
- Be cautious with sensitive websites and data
- Consider running in a sandboxed environment for untrusted automation
Next Steps
- Explore the examples directory for more usage patterns
- Check out MCP documentation to learn more about the protocol
- Join our Discord for support and discussions
