Skip to content

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

simplify mcp client docs

Nick Sweetingd729732b2273
diff --git a/docs/cli.mdx b/docs/cli.mdx
index a62726265..cfd58b145 100644
--- a/docs/cli.mdx
+++ b/docs/cli.mdx
@@ -1,3 +1,9 @@
+---
+title: "CLI"
+description: "Start using the Browser Use CLI"
+icon: "terminal"
+---
+
# CLI Usage
The `browser-use` command-line interface provides multiple modes of operation for browser automation.
diff --git a/docs/customize/mcp-client.mdx b/docs/customize/mcp-client.mdx
index b564706bc..9e0bd5f98 100644
--- a/docs/customize/mcp-client.mdx
+++ b/docs/customize/mcp-client.mdx
@@ -4,30 +4,16 @@ description: "Connect external MCP servers to extend browser-use with additional
icon: "plug"
---
-The MCP (Model Context Protocol) client allows browser-use agents to connect to external MCP servers, automatically exposing their tools as actions. This enables integrations with databases, APIs, file systems, and other services without writing custom action code.
+The MCP (Model Context Protocol) client allows browser-use agents to connect to external MCP servers, automatically exposing their tools as actions.
<Note>
MCP is an open protocol for integrating LLMs with external data sources and tools. Learn more at [modelcontextprotocol.io](https://modelcontextprotocol.io).
</Note>
<Info>
- Looking to expose browser-use as an MCP server instead? See [MCP Server](/customize/mcp-server) to let AI assistants like Claude Desktop control browsers.
+ Looking to expose browser-use as an MCP server instead? See [MCP Server](/customize/mcp-server).
</Info>
-## Overview
-
-The MCP client acts as a bridge between external MCP servers and browser-use's action system:
-
-```mermaid
-graph LR
- A[Browser-use Agent] --> B[Controller]
- B --> C[MCP Client]
- C -->|MCP Protocol| D[External MCP Server]
- D --> E[Tools/Services]
-
- style C fill:#f9f,stroke:#333,stroke-width:2px
-```
-
## Installation
```bash
@@ -44,45 +30,32 @@ from browser_use.mcp.client import MCPClient
# Create controller
controller = Controller()
-# Connect to multiple MCP servers
-filesystem_client = MCPClient(
+# Connect to MCP server
+mcp_client = MCPClient(
server_name="filesystem",
command="npx",
args=["@modelcontextprotocol/server-filesystem", "/path/to/files"]
)
-github_client = MCPClient(
- server_name="github",
- command="npx",
- args=["@modelcontextprotocol/server-github"],
- env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")}
-)
-
-# Connect and register both servers
-await filesystem_client.connect()
-await filesystem_client.register_to_controller(controller, prefix="fs_")
-
-await github_client.connect()
-await github_client.register_to_controller(controller, prefix="gh_")
+# Connect and register
+await mcp_client.connect()
+await mcp_client.register_to_controller(controller)
-# Agent can now use both filesystem and GitHub tools
+# Agent can now use filesystem tools
agent = Agent(
- task="Read the README.md file and create a GitHub issue with a summary of its contents",
+ task="Read the README.md file",
controller=controller
)
await agent.run()
# Clean up
-await filesystem_client.disconnect()
-await github_client.disconnect()
+await mcp_client.disconnect()
```
## API Reference
### MCPClient
-The main class for connecting to MCP servers.
-
```python
class MCPClient:
def __init__(
@@ -94,208 +67,66 @@ class MCPClient:
) -> None
```
-#### Parameters
-
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `server_name` | `str` | Name of the MCP server (for logging and identification) |
-| `command` | `str` | Command to start the MCP server (e.g., `"npx"`, `"python"`) |
-| `args` | `list[str] \| None` | Arguments for the command (e.g., `["@modelcontextprotocol/server-filesystem", "."]`) |
-| `env` | `dict[str, str] \| None` | Environment variables for the server process |
-
-#### Methods
-
-##### `async def connect() -> None`
+**Parameters:**
+- `server_name`: Name of the MCP server (for logging)
+- `command`: Command to start the server (e.g., `"npx"`)
+- `args`: Arguments for the command
+- `env`: Environment variables for the server
-Establishes connection to the MCP server and discovers available tools.
+**Key Methods:**
```python
+# Connect to server
await mcp_client.connect()
-```
-
-**Raises:**
-- `ImportError`: If MCP SDK is not installed
-- `RuntimeError`: If connection fails after timeout (3 seconds)
-##### `async def disconnect() -> None`
-
-Disconnects from the MCP server and cleans up resources.
-
-```python
-await mcp_client.disconnect()
-```
-
-##### `async def register_to_controller(controller: Controller, tool_filter: list[str] | None = None, prefix: str | None = None) -> None`
-
-Registers MCP tools as browser-use actions.
-
-```python
+# Register tools to controller
await mcp_client.register_to_controller(
controller,
- tool_filter=['read_file', 'write_file'], # Optional: only specific tools
- prefix='fs_' # Optional: prefix for action names
+ tool_filter=['read_file', 'write_file'], # Optional
+ prefix='fs_' # Optional prefix
)
-```
-**Parameters:**
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `controller` | `Controller` | Browser-use controller instance |
-| `tool_filter` | `list[str] \| None` | List of tool names to register (None = all tools) |
-| `prefix` | `str \| None` | Prefix to add to action names to avoid conflicts |
-
-#### Properties
-
-| Property | Type | Description |
-|----------|------|-------------|
-| `session` | `ClientSession \| None` | Active MCP session (None if disconnected) |
-| `server_name` | `str` | Name of the MCP server |
-| `command` | `str` | Command used to start the server |
-| `args` | `list[str]` | Arguments passed to the command |
-| `env` | `dict[str, str] \| None` | Environment variables for the server |
+# Disconnect
+await mcp_client.disconnect()
+```
### Context Manager Usage
-MCPClient supports async context manager protocol for multiple servers:
-
```python
-controller = Controller()
-
-# Use multiple MCP servers with context managers
async with MCPClient(
server_name="github",
command="npx",
args=["@modelcontextprotocol/server-github"],
env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")}
-) as github_client:
- async with MCPClient(
- server_name="postgres",
- command="npx",
- args=["@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
- ) as db_client:
- # Register both servers
- await github_client.register_to_controller(controller, prefix="gh_")
- await db_client.register_to_controller(controller, prefix="db_")
-
- # Use agent with both GitHub and database tools
- agent = Agent(
- task="Query the user table and create a GitHub issue listing users who haven't logged in for 30 days",
- controller=controller
- )
- await agent.run()
-# Both automatically disconnected
-```
-
-### Convenience Functions
-
-#### `create_playwright_mcp_client`
-
-Helper function to create a Playwright MCP client:
-
-```python
-async def create_playwright_mcp_client(
- controller: Controller,
- headless: bool = True,
- browser: str = "chromium",
- viewport_size: str = "1280,720",
- vision: bool = False,
- **kwargs
-) -> MCPClient
-```
-
-**Parameters:**
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `controller` | `Controller` | - | Browser-use controller to register actions to |
-| `headless` | `bool` | `True` | Whether to run browser in headless mode |
-| `browser` | `str` | `"chromium"` | Browser to use (chromium, firefox, webkit) |
-| `viewport_size` | `str` | `"1280,720"` | Browser viewport size |
-| `vision` | `bool` | `False` | Whether to use vision mode (screenshots) |
-| `**kwargs` | `Any` | - | Additional arguments passed to Playwright MCP |
-
-## Concepts
-
-### Tool Discovery
-
-When connecting to an MCP server, the client automatically:
-1. Starts the server process using the specified command
-2. Establishes stdio communication
-3. Calls `list_tools()` to discover available tools
-4. Parses tool schemas to understand parameters
-
-### Tool Registration
-
-Each MCP tool is converted to a browser-use action:
-1. **Parameter Mapping**: JSON Schema → Pydantic model via `create_model()`
-2. **Type Conversion**: JSON types → Python types
-3. **Validation**: Automatic parameter validation
-4. **Error Handling**: Graceful failure with `ActionResult(success=False, error=...)`
-
-### Action Execution Flow
-
-```mermaid
-sequenceDiagram
- participant Agent
- participant Action
- participant MCPClient
- participant MCPServer
-
- Agent->>Action: Call MCP action
- Action->>MCPClient: Execute with params
- MCPClient->>MCPServer: session.call_tool(name, args)
- MCPServer->>MCPClient: Tool result
- MCPClient->>Action: ActionResult
- Action->>Agent: Result
+) as client:
+ await client.register_to_controller(controller)
+ await agent.run()
+# Automatically disconnected
```
-### Type Conversion
-
-The client converts JSON Schema types to Python types:
-
-| JSON Schema Type | Python Type |
-|------------------|-------------|
-| `"string"` | `str` |
-| `"number"` | `float` |
-| `"integer"` | `int` |
-| `"boolean"` | `bool` |
-| `"array"` | `list` |
-| `"object"` | `dict` |
-| `"null"` | `type(None)` |
-
-Nullable types are converted to unions: `type | None`
-
## Common MCP Servers
-### Filesystem Server
-
-Read and write local files:
-
+### Filesystem
```python
-mcp_client = MCPClient(
+MCPClient(
server_name="filesystem",
command="npx",
- args=["@modelcontextprotocol/server-filesystem", "/Users/me/documents"]
+ args=["@modelcontextprotocol/server-filesystem", "/path"]
)
```
-### PostgreSQL Server
-
-Database operations:
-
+### PostgreSQL
```python
-mcp_client = MCPClient(
+MCPClient(
server_name="postgres",
command="npx",
- args=["@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/db"]
+ args=["@modelcontextprotocol/server-postgres", "postgresql://localhost/db"]
)
```
-### GitHub Server
-
-Repository management:
-
+### GitHub
```python
-mcp_client = MCPClient(
+MCPClient(
server_name="github",
command="npx",
args=["@modelcontextprotocol/server-github"],
@@ -303,120 +134,62 @@ mcp_client = MCPClient(
)
```
-### Gmail Server
-
-Email operations:
-
-```python
-mcp_client = MCPClient(
- server_name="gmail",
- command="npx",
- args=["gmail-mcp-server"],
- env={
- "GMAIL_CLIENT_ID": os.getenv("GMAIL_CLIENT_ID"),
- "GMAIL_CLIENT_SECRET": os.getenv("GMAIL_CLIENT_SECRET"),
- "GMAIL_REFRESH_TOKEN": os.getenv("GMAIL_REFRESH_TOKEN")
- }
-)
-```
-
-## Advanced Usage
+## Multiple Servers
-### Multiple MCP Servers
-
-Connect multiple servers with different capabilities for complex multi-service tasks:
+Connect multiple servers with prefixes to avoid conflicts:
```python
-controller = Controller()
-
-# 1. Filesystem access for local files
+# Filesystem server
fs_client = MCPClient(
server_name="filesystem",
command="npx",
- args=["@modelcontextprotocol/server-filesystem", "./project"]
-)
-
-# 2. Database for data storage
-db_client = MCPClient(
- server_name="postgres",
- command="npx",
- args=["@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
+ args=["@modelcontextprotocol/server-filesystem", "."]
)
+await fs_client.connect()
+await fs_client.register_to_controller(controller, prefix="fs_")
-# 3. GitHub for repository management
-github_client = MCPClient(
+# GitHub server
+gh_client = MCPClient(
server_name="github",
command="npx",
args=["@modelcontextprotocol/server-github"],
env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")}
)
+await gh_client.connect()
+await gh_client.register_to_controller(controller, prefix="gh_")
-# 4. Gmail for notifications
-gmail_client = MCPClient(
- server_name="gmail",
- command="npx",
- args=["gmail-mcp-server"],
- env={
- "GMAIL_CLIENT_ID": os.getenv("GMAIL_CLIENT_ID"),
- "GMAIL_CLIENT_SECRET": os.getenv("GMAIL_CLIENT_SECRET"),
- "GMAIL_REFRESH_TOKEN": os.getenv("GMAIL_REFRESH_TOKEN")
- }
-)
-
-# Connect and register all servers with prefixes to avoid conflicts
-await fs_client.connect()
-await fs_client.register_to_controller(controller, prefix="fs_")
-
-await db_client.connect()
-await db_client.register_to_controller(controller, prefix="db_")
-
-await github_client.connect()
-await github_client.register_to_controller(controller, prefix="gh_")
-
-await gmail_client.connect()
-await gmail_client.register_to_controller(controller, prefix="email_")
-
-# Agent has access to all tools from all servers
+# Agent can use both
agent = Agent(
- task="""
- 1. Read all .json config files in the project directory
- 2. Validate the database schema matches the configs
- 3. Create a GitHub issue if there are mismatches
- 4. Send an email summary of the validation results
- """,
+ task="Read README.md and create a GitHub issue",
controller=controller
)
await agent.run()
-# Clean up all connections
+# Clean up
await fs_client.disconnect()
-await db_client.disconnect()
-await github_client.disconnect()
-await gmail_client.disconnect()
+await gh_client.disconnect()
```
-### Tool Filtering
+## Tool Filtering
Register only specific tools:
```python
-# Only register read operations
await mcp_client.register_to_controller(
controller,
- tool_filter=['read_file', 'list_directory', 'get_file_info']
+ tool_filter=['read_file', 'list_directory']
)
```
-### Custom MCP Server
+## Custom MCP Server
Create your own MCP server:
```python
-# my_mcp_server.py
+# my_server.py
import mcp.server.stdio
import mcp.types as types
from mcp.server import Server
-from mcp.server.models import InitializationOptions
server = Server("custom-tools")
@@ -429,10 +202,7 @@ async def handle_list_tools() -> list[types.Tool]:
inputSchema={
"type": "object",
"properties": {
- "expression": {
- "type": "string",
- "description": "Math expression"
- }
+ "expression": {"type": "string"}
},
"required": ["expression"]
}
@@ -442,311 +212,59 @@ async def handle_list_tools() -> list[types.Tool]:
@server.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name == "calculate":
- expr = arguments.get("expression", "")
- try:
- result = eval(expr) # Caution: example only
- return [types.TextContent(type="text", text=str(result))]
- except Exception as e:
- return [types.TextContent(type="text", text=f"Error: {e}")]
- return [types.TextContent(type="text", text="Unknown tool")]
+ result = eval(arguments["expression"])
+ return [types.TextContent(type="text", text=str(result))]
+ return []
# Run server
async def main():
async with mcp.server.stdio.stdio_server() as (read, write):
- await server.run(read, write, InitializationOptions(
- server_name="custom-tools",
- server_version="1.0.0",
- capabilities=server.get_capabilities()
- ))
+ await server.run(read, write, ...)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
```
-Connect custom server alongside standard servers:
+Connect custom server:
```python
-controller = Controller()
-
-# Custom calculation server
custom_client = MCPClient(
server_name="custom",
command="python",
- args=["my_mcp_server.py"]
-)
-
-# Standard filesystem server
-fs_client = MCPClient(
- server_name="filesystem",
- command="npx",
- args=["@modelcontextprotocol/server-filesystem", "."]
-)
-
-# Connect and register both
-await custom_client.connect()
-await custom_client.register_to_controller(controller, prefix="calc_")
-
-await fs_client.connect()
-await fs_client.register_to_controller(controller, prefix="fs_")
-
-# Agent can use both custom calculations and file operations
-agent = Agent(
- task="Read numbers from data.txt, calculate their sum using the custom calculator, and save the result",
- controller=controller
+ args=["my_server.py"]
)
-await agent.run()
-
-await custom_client.disconnect()
-await fs_client.disconnect()
```
## Error Handling
-The MCP client handles errors gracefully:
-
```python
-# Connection errors
try:
await mcp_client.connect()
except RuntimeError as e:
print(f"Failed to connect: {e}")
-
-# Tool execution errors return ActionResult with error
-# When using registered actions, errors are handled automatically
-# The ActionResult will have success=False and an error message
```
## Best Practices
-### 1. Resource Management
-
-Always disconnect all clients when done:
-
-```python
-# Manual management for multiple clients
-clients = []
-try:
- # Connect filesystem client
- fs_client = MCPClient(
- server_name="filesystem",
- command="npx",
- args=["@modelcontextprotocol/server-filesystem", "."]
- )
- await fs_client.connect()
- await fs_client.register_to_controller(controller, prefix="fs_")
- clients.append(fs_client)
-
- # Connect database client
- db_client = MCPClient(
- server_name="postgres",
- command="npx",
- args=["@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
- )
- await db_client.connect()
- await db_client.register_to_controller(controller, prefix="db_")
- clients.append(db_client)
-
- # Run agent with both clients
- await agent.run()
-finally:
- # Ensure all clients are disconnected
- for client in clients:
- await client.disconnect()
-```
-
-Or use nested context managers for automatic cleanup:
-
-```python
-async with MCPClient(
- server_name="filesystem",
- command="npx",
- args=["@modelcontextprotocol/server-filesystem", "."]
-) as fs_client:
- async with MCPClient(
- server_name="github",
- command="npx",
- args=["@modelcontextprotocol/server-github"],
- env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")}
- ) as gh_client:
- await fs_client.register_to_controller(controller, prefix="fs_")
- await gh_client.register_to_controller(controller, prefix="gh_")
- await agent.run()
-```
-
-### 2. Naming Conflicts
-
-Use prefixes when connecting multiple servers:
-
-```python
-# Without prefix: potential conflicts
-await server1.register_to_controller(controller) # Registers: read_file, write_file
-await server2.register_to_controller(controller) # May conflict if same tool names
-
-# With prefix: no conflicts
-await server1.register_to_controller(controller, prefix="local_") # local_read_file
-await server2.register_to_controller(controller, prefix="remote_") # remote_read_file
-```
-
-### 3. Security
-
-- Only connect to trusted MCP servers
-- Use tool filtering to limit capabilities
-- Review tool permissions before registration
-- Set appropriate environment variables securely
+1. **Always disconnect** when done
+2. **Use prefixes** when connecting multiple servers
+3. **Filter tools** to limit capabilities
+4. **Use context managers** for automatic cleanup
## Troubleshooting
-### Import Error
-
-```
-ImportError: MCP SDK not installed. Install with: pip install mcp
-```
-
-**Solution:**
+**Import Error:**
```bash
pip install mcp
# or
pip install "browser-use[mcp]"
```
-### Connection Timeout
-
-```
-RuntimeError: Failed to connect to MCP server 'name' after 3 seconds
-```
-
-**Solutions:**
-1. Verify the command works: `npx @modelcontextprotocol/server-filesystem /path`
-2. Check server logs for errors
-3. Ensure all dependencies are installed
-4. Try running the server command manually to see errors
-
-### Tool Discovery
-
-Check discovered tools:
-
-```python
-await mcp_client.connect()
-print(f"Found tools: {list(mcp_client._tools.keys())}")
-for name, tool in mcp_client._tools.items():
- print(f"- {name}: {tool.description}")
-```
-
-## Implementation Details
-
-### Action Wrapper Functions
-
-The MCP client creates wrapper functions for each tool:
-- Tools with parameters: `async def wrapper(params: ParamModel) -> ActionResult`
-- Tools without parameters: `async def wrapper() -> ActionResult`
-
-### Result Formatting
-
-MCP results are converted to strings:
-- If result has `.content` attribute, it's extracted
-- List results are joined with newlines
-- Text content items extract the `.text` attribute
-
-### Browser Tool Detection
-
-Tools starting with `"browser_"` or containing `"page"` in the name are marked as browser-specific and have a page filter applied.
-
-## Examples
-
-### Complete Multi-Service Integration
-
-Here's a comprehensive example showing multiple MCP servers working together:
-
-```python
-import os
-from browser_use import Agent, Controller
-from browser_use.mcp.client import MCPClient
-
-async def analyze_and_report():
- """Analyze project files, query database, and report findings via GitHub and email."""
- controller = Controller()
-
- # Setup all MCP clients
- clients = {
- 'fs': MCPClient(
- server_name="filesystem",
- command="npx",
- args=["@modelcontextprotocol/server-filesystem", "./src"]
- ),
- 'db': MCPClient(
- server_name="postgres",
- command="npx",
- args=["@modelcontextprotocol/server-postgres", os.getenv("DATABASE_URL")]
- ),
- 'gh': MCPClient(
- server_name="github",
- command="npx",
- args=["@modelcontextprotocol/server-github"],
- env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")}
- ),
- 'email': MCPClient(
- server_name="gmail",
- command="npx",
- args=["gmail-mcp-server"],
- env={
- "GMAIL_CLIENT_ID": os.getenv("GMAIL_CLIENT_ID"),
- "GMAIL_CLIENT_SECRET": os.getenv("GMAIL_CLIENT_SECRET"),
- "GMAIL_REFRESH_TOKEN": os.getenv("GMAIL_REFRESH_TOKEN")
- }
- )
- }
-
- try:
- # Connect all clients
- for name, client in clients.items():
- await client.connect()
- await client.register_to_controller(controller, prefix=f"{name}_")
-
- # Create agent with complex multi-service task
- agent = Agent(
- task="""
- Perform a comprehensive code analysis:
-
- 1. Use filesystem tools to:
- - List all Python files in the src directory
- - Read each Python file and count the number of functions
- - Identify files with more than 10 functions
-
- 2. Use database tools to:
- - Query the code_metrics table for historical function counts
- - Compare current counts with historical data
-
- 3. Use GitHub tools to:
- - Check if there's already an issue about large files
- - If not, create a new issue listing files that grew by >50%
- - Add labels: 'refactoring', 'code-quality'
-
- 4. Use email tools to:
- - Send a summary email to the team lead
- - Include the list of files needing refactoring
- - CC the development team
- """,
- controller=controller
- )
-
- # Run the analysis
- await agent.run()
-
- finally:
- # Cleanup all connections
- for client in clients.values():
- await client.disconnect()
-
-# Run the example
-import asyncio
-asyncio.run(analyze_and_report())
-```
-
-### Repository Links
-
-- [Simple MCP client](https://github.com/browser-use/browser-use/tree/main/examples/mcp/simple_client.py)
-- [Gmail integration](https://github.com/browser-use/browser-use/tree/main/examples/mcp/advanced_client.py)
+**Connection Timeout:**
+- Verify command works manually
+- Check server logs
+- Ensure dependencies installed
## See Also