Skip to content

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

document multiple mcp servers connected to client

Nick Sweetingab36c9a301bc
diff --git a/README.md b/README.md
index 06c633148..31e7527b6 100644
--- a/README.md
+++ b/README.md
@@ -107,25 +107,54 @@ This gives Claude Desktop access to browser automation tools for web scraping, f
### Connect External MCP Servers to Browser-Use Agent
-Browser-use agents can connect to external MCP servers to extend their capabilities:
+Browser-use agents can connect to multiple external MCP servers to extend their capabilities:
```python
-from browser_use import Agent, MCPClient
+import asyncio
+from browser_use import Agent, Controller
+from browser_use.mcp.client import MCPClient
from browser_use.llm import ChatOpenAI
-# Connect to an external MCP server (e.g., filesystem, database, etc.)
-mcp_client = MCPClient(
- server_command=["npx", "-y", "@modelcontextprotocol/server-filesystem"],
- server_args=["/Users/me/documents"]
-)
-
-# Create agent with MCP tools
-agent = Agent(
- task="Find the latest report.pdf file and upload it to the website",
- llm=ChatOpenAI(model="gpt-4o"),
- mcp_client=mcp_client
-)
-await agent.run()
+async def main():
+ # Initialize controller
+ controller = Controller()
+
+ # Connect to multiple MCP servers
+ filesystem_client = MCPClient(
+ server_name="filesystem",
+ command="npx",
+ args=["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/documents"]
+ )
+
+ github_client = MCPClient(
+ server_name="github",
+ command="npx",
+ args=["-y", "@modelcontextprotocol/server-github"],
+ env={"GITHUB_TOKEN": "your-github-token"}
+ )
+
+ # Connect and register tools from both servers
+ await filesystem_client.connect()
+ await filesystem_client.register_to_controller(controller)
+
+ await github_client.connect()
+ await github_client.register_to_controller(controller)
+
+ # Create agent with MCP-enabled controller
+ agent = Agent(
+ task="Find the latest report.pdf in my documents and create a GitHub issue about it",
+ llm=ChatOpenAI(model="gpt-4o"),
+ controller=controller # Controller has tools from both MCP servers
+ )
+
+ # Run the agent
+ await agent.run()
+
+ # Cleanup
+ await filesystem_client.disconnect()
+ await github_client.disconnect()
+
+asyncio.run(main())
```
See the [MCP documentation](https://docs.browser-use.com/customize/mcp-server) for more details.
diff --git a/docs/customize/mcp-client.mdx b/docs/customize/mcp-client.mdx
index 9bae99b55..9fa46efa8 100644
--- a/docs/customize/mcp-client.mdx
+++ b/docs/customize/mcp-client.mdx
@@ -37,32 +37,44 @@ pip install "browser-use[mcp]"
## Quick Start
```python
+import os
from browser_use import Agent, Controller
from browser_use.mcp.client import MCPClient
# Create controller
controller = Controller()
-# Connect to an MCP server
-mcp_client = MCPClient(
+# Connect to multiple MCP servers
+filesystem_client = MCPClient(
server_name="filesystem",
command="npx",
args=["@modelcontextprotocol/server-filesystem", "/path/to/files"]
)
-# Connect and register tools
-await mcp_client.connect()
-await mcp_client.register_to_controller(controller)
+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_")
-# Agent can now use filesystem tools
+await github_client.connect()
+await github_client.register_to_controller(controller, prefix="gh_")
+
+# Agent can now use both filesystem and GitHub tools
agent = Agent(
- task="Read all .txt files and summarize their contents",
+ task="Read the README.md file and create a GitHub issue with a summary of its contents",
controller=controller
)
await agent.run()
# Clean up
-await mcp_client.disconnect()
+await filesystem_client.disconnect()
+await github_client.disconnect()
```
## API Reference
@@ -144,19 +156,34 @@ await mcp_client.register_to_controller(
### Context Manager Usage
-MCPClient supports async context manager protocol:
+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 mcp_client:
- await mcp_client.register_to_controller(controller)
- # Use agent with MCP tools
- await agent.run()
-# Automatically disconnected
+) 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
@@ -297,37 +324,75 @@ mcp_client = MCPClient(
### Multiple MCP Servers
-Connect multiple servers with different capabilities:
+Connect multiple servers with different capabilities for complex multi-service tasks:
```python
controller = Controller()
-# Filesystem access
+# 1. Filesystem access for local files
fs_client = MCPClient(
server_name="filesystem",
command="npx",
- args=["@modelcontextprotocol/server-filesystem", "."]
+ args=["@modelcontextprotocol/server-filesystem", "./project"]
)
-# Database access
+# 2. Database for data storage
db_client = MCPClient(
server_name="postgres",
command="npx",
args=["@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
)
-# Register both with prefixes
+# 3. GitHub for repository management
+github_client = MCPClient(
+ server_name="github",
+ command="npx",
+ args=["@modelcontextprotocol/server-github"],
+ env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")}
+)
+
+# 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_")
-# Agent has access to both fs_read_file() and db_query()
+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 = Agent(
- task="Read config.json and update the database based on its contents",
+ 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
+ """,
controller=controller
)
+await agent.run()
+
+# Clean up all connections
+await fs_client.disconnect()
+await db_client.disconnect()
+await github_client.disconnect()
+await gmail_client.disconnect()
```
### Tool Filtering
@@ -399,14 +464,41 @@ if __name__ == "__main__":
asyncio.run(main())
```
-Connect to custom server:
+Connect custom server alongside standard servers:
```python
-mcp_client = MCPClient(
+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
+)
+await agent.run()
+
+await custom_client.disconnect()
+await fs_client.disconnect()
```
## Error Handling
@@ -429,23 +521,57 @@ except RuntimeError as e:
### 1. Resource Management
-Always disconnect when done:
+Always disconnect all clients when done:
```python
+# Manual management for multiple clients
+clients = []
try:
- await mcp_client.connect()
- await mcp_client.register_to_controller(controller)
+ # 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:
- await mcp_client.disconnect()
+ # Ensure all clients are disconnected
+ for client in clients:
+ await client.disconnect()
```
-Or use context manager:
+Or use nested context managers for automatic cleanup:
```python
-async with MCPClient(...) as mcp_client:
- await mcp_client.register_to_controller(controller)
- await agent.run()
+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
@@ -528,6 +654,97 @@ Tools starting with `"browser_"` or containing `"page"` in the name are marked a
## 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)
diff --git a/examples/mcp/advanced_client.py b/examples/mcp/advanced_client.py
index fb49619d6..da220db31 100644
--- a/examples/mcp/advanced_client.py
+++ b/examples/mcp/advanced_client.py
@@ -1,11 +1,12 @@
"""
-Advanced example: Using Gmail MCP Server for automated account verification.
+Advanced example: Using multiple MCP servers together.
This example demonstrates how to:
-1. Connect Gmail MCP Server to browser-use
+1. Connect multiple MCP servers (Gmail + Filesystem) to browser-use
2. Sign up for a new account on a website
-3. Retrieve the verification link from Gmail
-4. Complete the verification process
+3. Save registration details to a file
+4. Retrieve the verification link from Gmail
+5. Complete the verification process
"""
import asyncio
@@ -17,14 +18,13 @@ from browser_use.mcp.client import MCPClient
async def main():
- """Sign up for Anthropic account and verify via Gmail."""
+ """Sign up for account, save details, and verify via Gmail."""
# Initialize controller
controller = Controller()
# Connect to Gmail MCP Server
# Requires Gmail API credentials - see: https://github.com/GongRzhe/Gmail-MCP-Server#setup
- # Get Gmail credentials from environment
gmail_env = {}
if client_id := os.getenv('GMAIL_CLIENT_ID'):
gmail_env['GMAIL_CLIENT_ID'] = client_id
@@ -35,29 +35,53 @@ async def main():
gmail_client = MCPClient(server_name='gmail', command='npx', args=['gmail-mcp-server'], env=gmail_env)
- # Connect and register Gmail tools
+ # Connect to Filesystem MCP Server for saving registration details
+ filesystem_client = MCPClient(
+ server_name='filesystem',
+ command='npx',
+ args=['-y', '@modelcontextprotocol/server-filesystem', os.path.expanduser('~/Desktop')],
+ )
+
+ # Connect and register tools from both servers
+ print('Connecting to Gmail MCP server...')
await gmail_client.connect()
await gmail_client.register_to_controller(controller)
- # Create agent with extended system prompt for Gmail integration
+ print('Connecting to Filesystem MCP server...')
+ await filesystem_client.connect()
+ await filesystem_client.register_to_controller(controller)
+
+ # Create agent with extended system prompt for using multiple MCP servers
agent = Agent(
- task='Sign up for a new Anthropic account using the email [email protected]',
+ task='Sign up for a new Anthropic account using the email [email protected], save the registration details to a file',
llm=ChatOpenAI(model='gpt-4o'),
controller=controller,
- system_prompt="""
-You are a browser automation agent with access to Gmail tools. When signing up for accounts:
+ extend_system_message="""
+You have access to both Gmail and Filesystem tools through MCP servers. When signing up for accounts:
1. Fill out registration forms with the provided email address
-2. After submitting the registration, use the Gmail MCP tools to check for verification emails
-3. Search for recent emails (within the last 5 minutes) from the service you're signing up for
-4. Look for verification links or codes in those emails
-5. Use any verification links or codes found to complete the account setup
-
-Available Gmail tools include:
+2. Use the filesystem tools to create a file called 'anthropic_registration.txt' on the Desktop containing:
+ - Email used for registration
+ - Timestamp of registration
+ - Any username or account details
+3. After submitting the registration, use the Gmail MCP tools to check for verification emails
+4. Search for recent emails (within the last 5 minutes) from the service you're signing up for
+5. Look for verification links or codes in those emails
+6. Append the verification details to the registration file
+7. Use any verification links or codes found to complete the account setup
+8. Update the file with the final account status
+
+Available tools include:
+Gmail tools:
- search_emails: Search for emails by query (e.g., "from:[email protected]")
- get_email: Get full email content by ID
- list_emails: List recent emails
+Filesystem tools:
+- read_file: Read content from a file
+- write_file: Write content to a file
+- list_directory: List files in a directory
+
Always wait a few seconds after submitting a form before checking Gmail to allow the email to arrive.
""",
)
@@ -68,13 +92,16 @@ Always wait a few seconds after submitting a form before checking Gmail to allow
print('\nTask completed!')
print(f'Result: {result}')
- # Disconnect Gmail client
+ # Disconnect both MCP clients
await gmail_client.disconnect()
+ await filesystem_client.disconnect()
if __name__ == '__main__':
# Prerequisites:
- # 1. Install Gmail MCP Server: npm install -g gmail-mcp-server
+ # 1. Install both MCP servers:
+ # npm install -g gmail-mcp-server
+ # npm install -g @modelcontextprotocol/server-filesystem
# 2. Set up Gmail API credentials following: https://github.com/GongRzhe/Gmail-MCP-Server#setup
# 3. Set these environment variables:
# export GMAIL_CLIENT_ID="your-client-id"
diff --git a/tests/ci/test_mcp_client.py b/tests/ci/test_mcp_client.py
index 5d38351fb..435573e0a 100644
--- a/tests/ci/test_mcp_client.py
+++ b/tests/ci/test_mcp_client.py
@@ -436,3 +436,103 @@ async def test_mcp_result_formatting(test_mcp_server_script):
finally:
await mcp_client.disconnect()
+
+
+async def test_agent_with_multiple_mcp_servers(test_mcp_server_script, httpserver: HTTPServer):
+ """Test agent using tools from multiple MCP servers in a single task."""
+ # Set up test webpage
+ httpserver.expect_request('/').respond_with_data(
+ """
+ <html>
+ <body>
+ <h1>Multi-MCP Test</h1>
+ <p>Use tools from both servers</p>
+ </body>
+ </html>
+ """,
+ content_type='text/html',
+ )
+
+ browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True, user_data_dir=None))
+ await browser_session.start()
+ controller = Controller()
+
+ # Connect two MCP servers with different prefixes
+ mcp_server1 = MCPClient(server_name='math-server', command=sys.executable, args=[test_mcp_server_script])
+ mcp_server2 = MCPClient(server_name='data-server', command=sys.executable, args=[test_mcp_server_script])
+
+ try:
+ # Connect and register both servers
+ await mcp_server1.connect()
+ await mcp_server1.register_to_controller(controller, prefix='math_', tool_filter=['count_to_n'])
+
+ await mcp_server2.connect()
+ await mcp_server2.register_to_controller(controller, prefix='data_', tool_filter=['echo_message', 'get_test_data'])
+
+ # Import create_mock_llm from conftest
+ from tests.ci.conftest import create_mock_llm
+
+ # Create mock LLM with actions using tools from both servers
+ actions = [
+ f'{{"thinking": null, "evaluation_previous_goal": "Starting", "memory": "Starting multi-MCP task", "next_goal": "Navigate to test page", "action": [{{"go_to_url": {{"url": "{httpserver.url_for("/")}"}}}}]}}',
+ '{"thinking": null, "evaluation_previous_goal": "Navigated", "memory": "On test page", "next_goal": "Use math server to count", "action": [{"math_count_to_n": {"n": 5}}]}',
+ '{"thinking": null, "evaluation_previous_goal": "Counted with math server", "memory": "Used math_count_to_n", "next_goal": "Use data server to echo", "action": [{"data_echo_message": {"message": "Counted successfully", "prefix": "Result:"}}]}',
+ '{"thinking": null, "evaluation_previous_goal": "Echoed with data server", "memory": "Used data_echo_message", "next_goal": "Get test data from data server", "action": [{"data_get_test_data": {}}]}',
+ '{"thinking": null, "evaluation_previous_goal": "Got test data", "memory": "Retrieved JSON data", "next_goal": "Complete", "action": [{"done": {"text": "Used tools from both MCP servers successfully", "success": true}}]}',
+ ]
+ mock_llm = create_mock_llm(actions=actions)
+
+ # Create agent with extended system message
+ agent = Agent(
+ task=f'Go to {httpserver.url_for("/")}, use math_count_to_n to count to 5, then use data_echo_message and data_get_test_data',
+ llm=mock_llm,
+ browser_session=browser_session,
+ controller=controller,
+ extend_system_message="""You have access to tools from two MCP servers:
+- math server: Provides math_count_to_n for counting
+- data server: Provides data_echo_message for echoing and data_get_test_data for JSON data
+
+Use tools from both servers to complete the task.""",
+ )
+
+ # Run agent
+ history = await agent.run(max_steps=10)
+
+ # Verify the agent used tools from both servers
+ action_names = []
+ for step in history.history:
+ if step.model_output and step.model_output.action:
+ for action in step.model_output.action:
+ action_dict = action.model_dump(exclude_unset=True)
+ action_names.extend(action_dict.keys())
+
+ # Should have used tools from both servers
+ assert 'math_count_to_n' in action_names
+ assert 'data_echo_message' in action_names
+ assert 'data_get_test_data' in action_names
+
+ # Check results contain outputs from both servers
+ results = []
+ memory_entries = []
+ for step in history.history:
+ if step.result:
+ for r in step.result:
+ if r.extracted_content:
+ results.append(r.extracted_content)
+ if r.long_term_memory:
+ memory_entries.append(r.long_term_memory)
+
+ # Verify outputs from both servers
+ assert any('Counted to 5: 1, 2, 3, 4, 5' in r for r in results)
+ assert any('Result: Counted successfully' in r for r in results)
+ assert any('"status": "success"' in r for r in results)
+
+ # Verify both server names appear in memory
+ all_memory = ' '.join(memory_entries)
+ assert 'math-server' in all_memory
+ assert 'data-server' in all_memory
+
+ finally:
+ await mcp_server1.disconnect()
+ await mcp_server2.disconnect()
+ await browser_session.stop()