### Installation and Setup Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Instructions for installing and configuring the MCP Browser Use server, including Claude Code Plugin installation, manual installation with uv, and Claude Desktop configuration. ```APIDOC ## Installation ### Installing with Claude Code Plugin Install as a Claude Code plugin for automatic setup and daemon management. ```bash # Install the plugin /plugin install browser-use/mcp-browser-use # Set your API key (required for the browser agent's LLM) export GEMINI_API_KEY=your-key-here # Or configure via CLI mcp-server-browser-use config set -k llm.api_key -v your-key-here ``` ### Manual Installation with uv Clone the repository and install dependencies using uv package manager. ```bash # Clone and install git clone https://github.com/Saik0s/mcp-browser-use.git cd mcp-server-browser-use uv sync # Install Chromium browser for Playwright uv run playwright install chromium # Start the HTTP server daemon uv run mcp-server-browser-use server # Or run in foreground for debugging uv run mcp-server-browser-use server -f ``` ### Claude Desktop Configuration Configure Claude Desktop to connect to the MCP server via HTTP transport. ```json { "mcpServers": { "browser-use": { "type": "streamable-http", "url": "http://localhost:8383/mcp" } } } ``` For MCP clients that don't support HTTP transport, use mcp-remote as a proxy: ```json { "mcpServers": { "browser-use": { "command": "npx", "args": ["mcp-remote", "http://localhost:8383/mcp"] } } } ``` ``` -------------------------------- ### Install mcp-browser-use Service (Linux/macOS) Source: https://github.com/saik0s/mcp-browser-use/blob/main/plans/feat-background-service-installation.md Installs the mcp-browser-use service using systemd on Linux or launchd on macOS. It finds the executable, generates the appropriate service configuration file, and enables the service to start automatically. Requires the 'mcp-server-browser-use' executable to be in the system's PATH. ```python import platform import shutil import subprocess import sys from pathlib import Path SERVICE_NAME = "mcp-browser-use" SYSTEMD_TEMPLATE = """[Unit] Description=MCP Browser Use Server After=network-online.target Wants=network-online.target [Service] Type=simple ExecStart={exe} Environment="MCP_SERVER_TRANSPORT=streamable-http" Environment="MCP_SERVER_HOST={host}" Environment="MCP_SERVER_PORT={port}" Restart=on-failure RestartSec=10 StartLimitIntervalSec=300 StartLimitBurst=5 KillMode=mixed TimeoutStopSec=30 [Install] WantedBy=default.target """ LAUNCHD_TEMPLATE = """ Label com.mcp.browser-use ProgramArguments {exe} EnvironmentVariables MCP_SERVER_TRANSPORT streamable-http MCP_SERVER_HOST {host} MCP_SERVER_PORT {port} RunAtLoad KeepAlive ThrottleInterval 10 StandardOutPath {home}/Library/Logs/mcp-browser-use.log StandardErrorPath {home}/Library/Logs/mcp-browser-use-error.log """ def get_executable() -> str: """Find mcp-server-browser-use executable.""" exe = shutil.which("mcp-server-browser-use") if not exe: raise FileNotFoundError( "mcp-server-browser-use not found. " "Install with: uv tool install mcp-server-browser-use" ) return exe def install(host: str = "127.0.0.1", port: int = 8000) -> None: """Install service for current platform.""" exe = get_executable() system = platform.system() if system == "Linux": _install_systemd(exe, host, port) elif system == "Darwin": _install_launchd(exe, host, port) else: raise RuntimeError("Windows not supported. Use WSL.") def _install_systemd(exe: str, host: str, port: int) -> None: service_dir = Path.home() / ".config/systemd/user" service_dir.mkdir(parents=True, exist_ok=True) service_file = service_dir / f"{SERVICE_NAME}.service" content = SYSTEMD_TEMPLATE.format(exe=exe, host=host, port=port) service_file.write_text(content) subprocess.run(["systemctl", "--user", "daemon-reload"], check=True) subprocess.run(["systemctl", "--user", "enable", SERVICE_NAME], check=True) print(f"Service installed: {service_file}") print(f"Start with: mcp-browser-cli service start") def _install_launchd(exe: str, host: str, port: int) -> None: home = Path.home() plist_dir = home / "Library/LaunchAgents" plist_dir.mkdir(parents=True, exist_ok=True) plist_file = plist_dir / "com.mcp.browser-use.plist" log_dir = home / "Library/Logs" log_dir.mkdir(parents=True, exist_ok=True) content = LAUNCHD_TEMPLATE.format(exe=exe, host=host, port=str(port), home=home) plist_file.write_text(content) subprocess.run(["launchctl", "load", str(plist_file)], check=True) print(f"Service installed: {plist_file}") print(f"Service will start automatically on login.") ``` -------------------------------- ### Manual Installation with uv Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Manually installs the project by cloning the repository and using the uv package manager for dependency synchronization. It also includes steps to install the Chromium browser for Playwright and start the HTTP server daemon. ```bash # Clone and install git clone https://github.com/Saik0s/mcp-browser-use.git cd mcp-server-browser-use uv sync # Install Chromium browser for Playwright uv run playwright install chromium # Start the HTTP server daemon uv run mcp-server-browser-use server # Or run in foreground for debugging uv run mcp-server-browser-use server -f ``` -------------------------------- ### Install MCP Browser Use Plugin Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Installs the browser-use/mcp-browser-use plugin for automatic setup and daemon management. Requires setting an API key for the browser agent's LLM, either via environment variables or the CLI. ```bash # Install the plugin /plugin install browser-use/mcp-browser-use # Set your API key (required for the browser agent's LLM) export GEMINI_API_KEY=your-key-here # Or configure via CLI mcp-server-browser-use config set -k llm.api_key -v your-key-here ``` -------------------------------- ### Install Dependencies and Playwright Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Commands to install project dependencies using `uv` and install Playwright browsers, essential for the browser-use functionality. ```bash uv sync --dev uv run playwright install ``` -------------------------------- ### Start mcp-browser-use Service (Linux/macOS) Source: https://github.com/saik0s/mcp-browser-use/blob/main/plans/feat-background-service-installation.md Starts the mcp-browser-use service. It uses 'systemctl' on Linux and 'launchctl' on macOS to initiate the service process. ```python def start() -> None: """Start the service.""" system = platform.system() if system == "Linux": subprocess.run(["systemctl", "--user", "start", SERVICE_NAME], check=True) elif system == "Darwin": subprocess.run(["launchctl", "start", "com.mcp.browser-use"], check=True) print("Service started.") ``` -------------------------------- ### Start Learning Session (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md Initiates a learning session to capture a new skill. This POST request to /api/learn requires a JSON body specifying the task description and the skill name. It also starts a background task and returns a task ID and status URL. ```bash curl -X POST http://localhost:8383/api/learn \ -H "Content-Type: application/json" \ -d '{ "task": "Search for TypeScript packages on npmjs.com", "skill_name": "npm-search" }' ``` -------------------------------- ### Run MCP Browser CLI Commands Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Provides examples of using the MCP browser CLI to execute browser agent tasks and deep research operations. It shows how to specify an environment file and the commands to run. ```bash uv run mcp-browser-cli -e .env run-browser-agent "Go to example.com" uv run mcp-browser-cli -e .env run-deep-research "Research topic" ``` -------------------------------- ### Correct FastMCP Test Client Setup (Python) Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Shows the recommended way to set up an in-memory test client for a FastMCP application using pytest. It includes setting environment variables, creating the app instance, and using `Client(app)` within an async context manager. ```python import pytest from fastmcp import Client @pytest.fixture async def client(monkeypatch): monkeypatch.setenv("MCP_LLM_PROVIDER", "openai") monkeypatch.setenv("OPENAI_API_KEY", "test-key") from mcp_server_browser_use.server import serve app = serve() async with Client(app) as client: yield client ``` -------------------------------- ### Install and Check Dependencies (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/AGENTS.md Commands to install dependencies, format code, perform lint checks, type checking, and run tests. These are critical before committing and are enforced by pre-commit hooks. ```bash uv sync uv run ruff format . uv run ruff check . uv run pyright uv run pytest ``` -------------------------------- ### Troubleshoot Server Start Issues (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/AGENTS.md This snippet provides bash commands to troubleshoot issues with the mcp-browser-use server not starting. It includes checking the server status, reviewing logs, and forcefully terminating any running processes. These steps help resolve common startup failures. ```bash # Server Won't Start 1. Check if already running: `mcp-server-browser-use status` 2. Check logs: `mcp-server-browser-use logs` 3. Kill orphan processes: `pkill -f mcp-server-browser-use` ``` -------------------------------- ### Start MCP Browser-Use Server Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Configures and starts the MCP browser-use server based on the transport setting. Supports 'stdio', 'streamable-http', and 'sse' transports. Raises a ValueError for unknown transports. ```python import logging # Assuming settings, logger, and server_instance are defined elsewhere # from . import settings, logger, server_instance transport = settings.server.transport logger.info( f"Starting MCP browser-use server (provider: {settings.llm.provider}, transport: {transport})" ) if transport == "stdio": server_instance.run() elif transport in ("streamable-http", "sse"): logger.info(f"HTTP server at http://{settings.server.host}:{settings.server.port}/mcp") server_instance.run(transport=transport, host=settings.server.host, port=settings.server.port) else: raise ValueError(f"Unknown transport: {transport}") if __name__ == "__main__": main() ``` -------------------------------- ### Troubleshoot Server Startup (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/CLAUDE.md Provides commands to diagnose and resolve issues when the mcp-browser-use server fails to start. Includes checking status, logs, and killing orphaned processes. ```bash # Check if already running: mcp-server-browser-use status # Check logs: mcp-server-browser-use logs # Kill orphan processes: pkill -f mcp-server-browser-use ``` -------------------------------- ### Test Systemd Service Installation (Linux) Source: https://github.com/saik0s/mcp-browser-use/blob/main/plans/feat-background-service-installation.md This Python test verifies the installation of a systemd user service file on Linux. It mocks the platform to return 'Linux', patches subprocess.run, and sets a temporary home directory. It asserts that the service file is created with the correct content. ```python def test_install_linux(tmp_path): with patch("platform.system", return_value="Linux"): with patch("subprocess.run") as mock_run: with patch("pathlib.Path.home", return_value=tmp_path): from mcp_server_browser_use.service import _install_systemd _install_systemd("/usr/bin/test", "127.0.0.1", 8000) service_file = tmp_path / ".config/systemd/user/mcp-browser-use.service" assert service_file.exists() content = service_file.read_text() assert "ExecStart=/usr/bin/test" in content ``` -------------------------------- ### Skill File Parameterization Example (YAML) Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md This YAML snippet demonstrates how to define parameters within a skill's request URL and body template. Placeholders like {query} and {limit} in the URL, and {category} in the body, are substituted at execution time using `skill_params`. ```yaml request: url: "https://api.example.com/search?q={query}&limit={limit}" body_template: '{"filters": {"category": "{category}"}}' ``` -------------------------------- ### Start MCP Server and Access Web UI Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Starts the MCP server and provides commands to access the web UI, including the task viewer and the full dashboard. The server runs on localhost, typically on port 8383. ```bash # Start the server mcp-server-browser-use server # Access the task viewer open http://localhost:8383 # Access the full dashboard open http://localhost:8383/dashboard ``` -------------------------------- ### CLI Service Management Commands (Python) Source: https://github.com/saik0s/mcp-browser-use/blob/main/plans/feat-background-service-installation.md This Python code defines a Typer CLI application for managing the MCP Browser Use service. It includes commands for installing, uninstalling, starting, stopping, and checking the status of the service, with options for host and port during installation. ```python service_app = typer.Typer(help="Manage background service") app.add_typer(service_app, name="service") @service_app.command("install") def cmd_service_install( port: int = typer.Option(8000, help="HTTP port"), host: str = typer.Option("127.0.0.1", help="Bind address"), ): """Install MCP server as a background service.""" from .service import install try: install(host=host, port=port) except (FileNotFoundError, RuntimeError) as e: typer.echo(str(e), err=True) raise typer.Exit(1) @service_app.command("uninstall") def cmd_service_uninstall(): """Remove the background service.""" from .service import uninstall if typer.confirm("Remove the service?"): uninstall() @service_app.command("start") def cmd_service_start(): """Start the background service.""" from .service import start start() @service_app.command("stop") def cmd_service_stop(): """Stop the background service.""" from .service import stop stop() @service_app.command("status") def cmd_service_status(): """Show service status.""" from .service import status status() ``` -------------------------------- ### Setup FastMCP In-Memory Client for Testing Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md This fixture sets up an in-memory FastMCP client for testing. It configures necessary environment variables for the LLM provider, model name, API key, and browser headless mode. The fixture then imports and serves the application, yielding a client instance for use in tests. ```python import pytest from fastmcp import Client from collections.abc import AsyncGenerator @pytest.fixture def anyio_backend(): """Use asyncio backend for pytest-asyncio.""" return "asyncio" @pytest.fixture async def client(monkeypatch) -> AsyncGenerator[Client, None]: """Create an in-memory FastMCP client for testing.""" # Set environment variables for testing monkeypatch.setenv("MCP_LLM_PROVIDER", "openai") monkeypatch.setenv("MCP_LLM_MODEL_NAME", "gpt-4") monkeypatch.setenv("OPENAI_API_KEY", "test-key") monkeypatch.setenv("MCP_BROWSER_HEADLESS", "true") # Import server after setting env vars to ensure config picks them up from mcp_server_browser_use.server import serve app = serve() # ✓ Use FastMCP's Client class for in-memory testing async with Client(app) as client: yield client ``` -------------------------------- ### Start MCP Server Daemon (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/CLAUDE.md Starts the mcp-browser-use server daemon in the background. Use the -f flag to run in the foreground for debugging purposes. ```bash mcp-server-browser-use server # Start daemon mcp-server-browser-use server -f # Foreground (debug) ``` -------------------------------- ### Initialize and Configure FastMCP Server Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Creates and configures a FastMCP server instance. It includes helper functions to initialize LLM and browser profiles, and defines tools for running browser agents and deep research tasks. ```python from fastmcp import FastMCP, TaskConfig, Context, CurrentContext, Progress from mcp_browser_use.settings import settings from mcp_browser_use.llm import get_llm, LLMProviderError from mcp_browser_use.browser import BrowserProfile, ProxySettings from mcp_browser_use.agent import Agent, BrowserError from mcp_browser_use.research import ResearchMachine from typing import Optional def serve() -> FastMCP: """Create and configure MCP server with background task support.""" server = FastMCP("mcp_server_browser_use") def _get_llm_and_profile(): """Helper to get LLM instance and browser profile.""" llm = get_llm( provider=settings.llm.provider, model=settings.llm.model_name, api_key=settings.llm.get_api_key_for_provider(), base_url=settings.llm.base_url, azure_endpoint=settings.llm.azure_endpoint, azure_api_version=settings.llm.azure_api_version, aws_region=settings.llm.aws_region, ) proxy = None if settings.browser.proxy_server: proxy = ProxySettings( server=settings.browser.proxy_server, bypass=settings.browser.proxy_bypass, ) profile = BrowserProfile(headless=settings.browser.headless, proxy=proxy) return llm, profile @server.tool(task=TaskConfig(mode="optional")) async def run_browser_agent( task: str, max_steps: Optional[int] = None, ctx: Context = CurrentContext(), # ✓ Use CurrentContext() marker progress: Progress = Progress(), # ✓ Use Progress() default ) -> str: """ Execute a browser automation task using AI. Supports background execution with progress tracking when client requests it. Args: task: Natural language description of what to do in the browser max_steps: Maximum number of agent steps (default from settings) Returns: Result of the browser automation task """ logger.info(f"Starting browser agent task: {task[:100]}...") try: llm, profile = _get_llm_and_profile() except LLMProviderError as e: logger.error(f"LLM initialization failed: {e}") return f"Error: {e}" steps = max_steps if max_steps is not None else settings.agent.max_steps if progress: await progress.set_total(steps) await progress.set_message("Starting browser agent...") try: agent = Agent( task=task, llm=llm, browser_profile=profile, max_steps=steps, ) result = await agent.run() # Mark as complete if progress: await progress.set_total(1) await progress.increment() final = result.final_result() or "Task completed without explicit result." logger.info(f"Agent completed: {final[:100]}...") return final except Exception as e: logger.error(f"Browser agent failed: {e}") raise BrowserError(f"Browser automation failed: {e}") from e @server.tool(task=TaskConfig(mode="optional")) async def run_deep_research( topic: str, max_searches: Optional[int] = None, save_to_file: Optional[str] = None, ctx: Context = CurrentContext(), # ✓ Use CurrentContext() marker progress: Progress = Progress(), # ✓ Use Progress() default ) -> str: """ Execute deep research on a topic with progress tracking. Runs as a background task if client requests it, otherwise synchronous. Progress updates are streamed via the MCP task protocol. Args: topic: The research topic or question to investigate max_searches: Maximum number of web searches (default from settings) save_to_file: Optional file path to save the report Returns: The research report as markdown """ logger.info(f"Starting deep research on: {topic}") try: llm, profile = _get_llm_and_profile() except LLMProviderError as e: logger.error(f"LLM initialization failed: {e}") return f"Error: {e}" searches = ( max_searches if max_searches is not None else settings.research.max_searches ) save_path = save_to_file or ( f"{settings.research.save_directory}/{topic[:50].replace(' ', '_')}.md" if settings.research.save_directory else None ) # Execute research with progress tracking machine = ResearchMachine( topic=topic, max_searches=searches, save_path=save_path, llm=llm, browser_profile=profile, progress=progress, # ← Pass Progress to research machine ) report = await machine.run() return report return server server_instance = serve() def main() -> None: pass ``` -------------------------------- ### List All Skills (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md Retrieves a list of all available skills from the API. This is a simple GET request to the /api/skills endpoint. The response includes skill details, count, and the directory where skills are stored. ```bash curl http://localhost:8383/api/skills ``` -------------------------------- ### Install Package with uv (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/CLAUDE.md Command to add a new package to the project's dependencies using the 'uv' package manager. Use '--dev' for development-only dependencies. ```bash uv add package uv add --dev package ``` -------------------------------- ### Run MCP Server with Different Transports Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Demonstrates how to run the MCP server using various transport mechanisms: stdio (default), streamable-http, and SSE. It also shows how to configure the server port and access the HTTP endpoint. ```bash # Run MCP server (stdio - default) uv run mcp-server-browser-use # Run MCP server (HTTP - stateful) MCP_SERVER_TRANSPORT=streamable-http MCP_SERVER_PORT=8000 uv run mcp-server-browser-use # Server runs at http://localhost:8000/mcp # Run MCP server (SSE transport) MCP_SERVER_TRANSPORT=sse MCP_SERVER_PORT=8000 uv run mcp-server-browser-use ``` -------------------------------- ### Define an MCP Tool (Python) Source: https://github.com/saik0s/mcp-browser-use/blob/main/AGENTS.md Example of defining a new MCP tool using the `@server.tool()` decorator. Includes type hints for parameters and return values, and a docstring for LLM client visibility. ```python @server.tool() async def my_tool(param: str) -> str: """Tool description shown to LLM clients.""" return result ``` -------------------------------- ### Dependency Injection Flow in FastMCP Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Illustrates the dependency injection process within the FastMCP framework. It shows how user calls are handled, dependencies like Context and Progress are injected based on task mode, and the tool function execution. ```text User calls tool via MCP client ↓ FastMCP receives request ↓ FastMCP inspects tool function signature ↓ For ctx: Context = CurrentContext(): ✓ Inject current request Context For progress: Progress = Progress(): ✓ If task mode: inject real Progress tracker ✓ Otherwise: inject no-op Progress ↓ Tool function executes with injected dependencies ↓ Tool returns result to client ``` -------------------------------- ### Initialize Theme and Health Check Source: https://github.com/saik0s/mcp-browser-use/blob/main/src/mcp_server_browser_use/ui/dashboard.html Sets up event listeners for theme toggling and initializes the theme. It also starts a periodic health check for the browser agent, with a specified interval. A cleanup function is registered for the 'beforeunload' event to clear the interval. ```javascript // Initialize document.getElementById('themeToggle').addEventListener('click', toggleTheme); initTheme(); checkHealth(); healthCheckInterval = setInterval(checkHealth, 5000); // Cleanup window.addEventListener('beforeunload', () => { if (healthCheckInterval) { clearInterval(healthCheckInterval); } }); ``` -------------------------------- ### Use a Pre-learned Skill with MCP Browser Use Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md This command executes a previously learned skill using its name and any necessary parameters. The skill will perform its defined task, such as searching for packages on npmjs.com with a specified query. Dependencies include the mcp-server-browser-use tool and a pre-existing skill file. ```bash mcp-server-browser-use call run_browser_agent \ skill_name="npm-search" \ skill_params='{"query": "vue"}' ``` -------------------------------- ### FastMCP Client In-Memory Test (Python) Source: https://github.com/saik0s/mcp-browser-use/blob/main/AGENTS.md Example of testing a FastMCP server using its in-memory transport. This allows for efficient testing without starting a full server process. ```python from fastmcp import Client from mcp_server_browser_use.server import create_server async def test_tool(): server = create_server() async with Client(server) as client: result = await client.call_tool("health_check", {{}}) assert result.data["status"] == "ok" ``` -------------------------------- ### Skill File Format Example (YAML) Source: https://context7.com/saik0s/mcp-browser-use/llms.txt This YAML structure defines a skill, including its name, description, version, request details (URL, method, headers, response type, extraction path), execution hints, authentication recovery, and parameters. It also includes usage statistics. ```yaml name: npm-search description: Search for packages on npmjs.com version: "1.0" # Direct execution configuration (fast path ~2 seconds) request: url: "https://www.npmjs.com/search?q={query}" method: GET headers: Accept: application/json response_type: json extract_path: "objects[*].package" # Hint-based execution fallback (~60-120 seconds) hints: navigation: - step: "Go to npmjs.com" url: "https://www.npmjs.com" money_request: url_pattern: "/search" method: GET # Auth recovery configuration auth_recovery: trigger_on_status: [401, 403] recovery_page: "https://www.npmjs.com/login" max_retries: 2 # Parameters with defaults parameters: - name: query type: string required: true description: "Search term for npm packages" # Usage statistics success_count: 12 failure_count: 1 last_used: "2024-01-15T10:30:00Z" ``` -------------------------------- ### Using a Skill Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md This section explains how to execute a previously learned skill by providing its name and any necessary parameters. ```APIDOC ## Using a Skill ### Description Execute a pre-learned skill by specifying its name and any required parameters. ### Method CLI Command ### Endpoint N/A (CLI command) ### Parameters #### CLI Arguments - **skill_name** (string) - Required - The name of the skill to execute (e.g., "npm-search"). - **skill_params** (JSON string) - Optional - Parameters for the skill, formatted as a JSON string (e.g., '{"query": "vue"}'). ### Request Example ```bash mcp-server-browser-use call run_browser_agent \ skill_name="npm-search" \ skill_params='{"query": "vue"}' ``` ### Response #### Success Response - Data returned by the skill's execution. #### Response Example (Depends on the skill; for npm-search, it would be a JSON array of package objects) ``` -------------------------------- ### Get Skill Definition (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md Fetches the full JSON definition of a specific skill by its name. This operation uses a GET request to the /api/skills/{name} endpoint. ```bash curl http://localhost:8383/api/skills/npm-search ``` -------------------------------- ### Learn a Skill with MCP Browser Use Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md This command initiates the process of learning a new skill by running a browser agent. It captures network traffic, identifies the 'money request', extracts URL patterns and parsing rules, and saves the skill as a YAML file. Dependencies include the mcp-server-browser-use tool. ```bash mcp-server-browser-use call run_browser_agent \ task="Find React packages on npmjs.com" \ learn=true \ save_skill_as="npm-search" ``` -------------------------------- ### POST /api/learn Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Initiates a learning session to capture and save a new skill based on a given task and skill name. ```APIDOC ## POST /api/learn ### Description Initiates a learning session to capture and save a new skill based on a given task and skill name. This allows for the creation of reusable automation sequences. ### Method POST ### Endpoint `/api/learn` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **task** (string) - Required - The natural language description of the task to learn. - **skill_name** (string) - Required - The name to assign to the learned skill. ### Request Example ```json { "task": "Search for TypeScript packages on npmjs.com", "skill_name": "npm-search" } ``` ### Response #### Success Response (200) (No specific success response body is detailed in the provided text, but typically would indicate the learning session has started or been initiated.) #### Response Example (No specific response example is provided in the source text.) ``` -------------------------------- ### Skill File Format Example (YAML) Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md This YAML structure defines a browser skill, including its name, description, request details for direct execution, hints for fallback execution, and authentication recovery settings. It also tracks usage statistics. This format is used to store learned skills. ```yaml name: npm-search description: Search for packages on npmjs.com version: "1.0" # For direct execution (fast path) request: url: "https://www.npmjs.com/search?q={query}" method: GET headers: Accept: application/json response_type: json extract_path: "objects[*].package" # For hint-based execution (fallback) hints: navigation: - step: "Go to npmjs.com" url: "https://www.npmjs.com" money_request: url_pattern: "/search" method: GET # Auth recovery (if API returns 401/403) auth_recovery: trigger_on_status: [401, 403] recovery_page: "https://www.npmjs.com/login" # Usage stats success_count: 12 failure_count: 1 last_used: "2024-01-15T10:30:00Z" ``` -------------------------------- ### Start MCP Server Daemon Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Starts the HTTP MCP server as a background daemon process for handling browser automation requests. Options include running in foreground mode for debugging, specifying custom host and port, and using SSE transport. ```bash # Start as background daemon (default) mcp-server-browser-use server # Start in foreground mode for debugging mcp-server-browser-use server -f # Specify custom host and port mcp-server-browser-use server --host 0.0.0.0 --port 9000 # Use SSE transport instead of streamable-http mcp-server-browser-use server --transport sse ``` -------------------------------- ### CLI Configuration: View and Set Settings Source: https://context7.com/saik0s/mcp-browser-use/llms.txt These bash commands demonstrate how to manage the mcp-browser-use server configuration using the command-line interface. You can view all settings, show the config file path, and set specific configuration keys for LLM, browser, agent, and research options. ```bash # View all current settings mcp-server-browser-use config view # Show config file path mcp-server-browser-use config path # Set LLM provider and model mcp-server-browser-use config set -k llm.provider -v openai mcp-server-browser-use config set -k llm.model_name -v gpt-4o # Set browser options mcp-server-browser-use config set -k browser.headless -v false mcp-server-browser-use config set -k browser.user_data_dir -v ~/.chrome-browser-use # Set agent behavior mcp-server-browser-use config set -k agent.max_steps -v 30 mcp-server-browser-use config set -k agent.use_vision -v true # Set research options mcp-server-browser-use config set -k research.max_searches -v 7 # Save current config to file mcp-server-browser-use config save ``` -------------------------------- ### Manage MCP Server Daemon Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md Commands to manage the mcp-server-browser-use background daemon, including starting, checking status, stopping, and viewing logs. ```bash mcp-server-browser-use server # Start as background daemon mcp-server-browser-use server -f # Start in foreground (for debugging) mcp-server-browser-use status # Check if running mcp-server-browser-use stop # Stop the daemon mcp-server-browser-use logs -f # Tail server logs ``` -------------------------------- ### Run Skill with Parameters (Bash) Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md Executes a skill with provided parameters. This initiates a background task and requires a POST request to /api/skills/{name}/run with a JSON payload containing the parameters. The response includes a task ID and a URL to check the task status. ```bash curl -X POST http://localhost:8383/api/skills/npm-search/run \ -H "Content-Type: application/json" \ -d '{"params": {"query": "react"}}' ``` -------------------------------- ### Get Skill Details Source: https://github.com/saik0s/mcp-browser-use/blob/main/skills/browser-use/SKILL.md Retrieves details about a specific learned skill, useful for verifying its parameters. ```shell skill_get skill_name: my_skill ``` -------------------------------- ### Execute MCP Browser Agent and Research Tools Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md Demonstrates how to call MCP tools to perform browser automation tasks and conduct deep research on specified topics. ```bash mcp-server-browser-use call run_browser_agent task="Go to google.com" mcp-server-browser-use call run_deep_research topic="quantum computing" ``` -------------------------------- ### Log Browser Agent Start, Page Changes, and Completion with Context Source: https://github.com/saik0s/mcp-browser-use/blob/main/plans/feat-context-logging-progress.md This Python code snippet demonstrates how to integrate client-visible status updates into a browser automation agent. It logs the start of the task, significant page transitions (based on URL changes), and the final completion status using `ctx.info()`. It also includes standard Python logging for server-side debugging and progress tracking. ```python # src/mcp_server_browser_use/server.py @server.tool(task=TaskConfig(mode="optional")) async def run_browser_agent( task: str, max_steps: Optional[int] = None, ctx: Context = CurrentContext(), progress: Progress = Progress(), ) -> str: """Execute a browser automation task using AI.""" await ctx.info(f"Starting: {task}") logger.info(f"Starting browser agent task: {task[:100]}...") try: llm, profile = _get_llm_and_profile() except LLMProviderError as e: logger.error(f"LLM initialization failed: {e}") return f"Error: {e}" steps = max_steps if max_steps is not None else settings.agent.max_steps await progress.set_total(steps) # Track page changes only (not every step) last_url: str | None = None async def step_callback( state: BrowserStateSummary, output: AgentOutput, step_num: int, ) -> None: nonlocal last_url if state.url != last_url: await ctx.info(f"→ {state.title or state.url}") last_url = state.url await progress.increment() try: agent = Agent( task=task, llm=llm, browser_profile=profile, max_steps=steps, register_new_step_callback=step_callback, ) result = await agent.run() final = result.final_result() if result else "No result" await ctx.info(f"Completed: {final[:100]}") logger.info(f"Agent completed: {final[:100]}...") return final except Exception as e: logger.error(f"Browser agent failed: {e}") raise BrowserError(f"Browser automation failed: {e}") from e ``` -------------------------------- ### Get Specific Task Details Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md Fetches detailed information about a specific task using its ID. This is useful for debugging and monitoring individual task executions. ```bash mcp-server-browser-use task a1b2c3d4 ``` -------------------------------- ### Task Tracking with Task Store (Python) Source: https://github.com/saik0s/mcp-browser-use/blob/main/AGENTS.md Illustrates how to use the task store for tracking the progress of asynchronous operations. It shows retrieving the store and creating a new task entry with relevant details. ```python from mcp_server_browser_use.observability import get_task_store task_store = get_task_store() await task_store.create_task(task_id, "tool_name", {"args": "here"}) ``` -------------------------------- ### Server Management Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Commands for managing the MCP Browser Use server daemon, including starting, checking status, and stopping the server. ```APIDOC ## Server Management ### Starting the Server Daemon Start the HTTP MCP server as a background daemon process that handles browser automation requests. ```bash # Start as background daemon (default) mcp-server-browser-use server # Start in foreground mode for debugging mcp-server-browser-use server -f # Specify custom host and port mcp-server-browser-use server --host 0.0.0.0 --port 9000 # Use SSE transport instead of streamable-http mcp-server-browser-use server --transport sse ``` ### Checking Server Status Check if the daemon is running and view connection information. ```bash # Check server status mcp-server-browser-use status # Example output: # Server running (PID 12345) # URL: http://127.0.0.1:8383/mcp # Transport: streamable-http # Log: ~/.local/state/mcp-server-browser-use/server.log ``` ### Stopping the Server Gracefully stop the running server daemon. ```bash # Stop the daemon mcp-server-browser-use stop # View server logs mcp-server-browser-use logs -f # Follow mode mcp-server-browser-use logs -n 100 # Last 100 lines ``` ``` -------------------------------- ### Configuration via Environment Variables Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Lists environment variables that can be used to configure the server's behavior, including LLM, browser, server, research, and skills settings. ```APIDOC ## Environment Variables Configuration ### Description Configure various aspects of the MCP server using environment variables prefixed with `MCP_`. ### Environment Variables #### LLM Configuration - `GEMINI_API_KEY`: API key for Google Gemini. - `OPENAI_API_KEY`: API key for OpenAI. - `ANTHROPIC_API_KEY`: API key for Anthropic Claude. - `MCP_LLM_PROVIDER`: Override the default LLM provider (e.g., `google`). - `MCP_LLM_MODEL_NAME`: Specify the LLM model name (e.g., `gemini-3-flash-preview`). #### Browser Configuration - `MCP_BROWSER_HEADLESS`: Set to `true` to run the browser in headless mode. - `MCP_BROWSER_CDP_URL`: The URL for the Chrome DevTools Protocol (CDP) connection. - `MCP_BROWSER_USER_DATA_DIR`: Path to the user data directory for the browser profile. #### Server Configuration - `MCP_SERVER_HOST`: The host address for the server. - `MCP_SERVER_PORT`: The port number for the server. - `MCP_SERVER_RESULTS_DIR`: Directory to store server results. #### Research Configuration - `MCP_RESEARCH_MAX_SEARCHES`: Maximum number of searches allowed during research. - `MCP_RESEARCH_SAVE_DIRECTORY`: Directory to save research data. #### Skills Configuration - `MCP_SKILLS_ENABLED`: Set to `true` to enable skills. - `MCP_SKILLS_DIRECTORY`: Directory where skill files are stored. ### Example Usage ```bash # Set Google Gemini API key export GEMINI_API_KEY=your-key-here # Set OpenAI API key export OPENAI_API_KEY=sk-... # Set Anthropic API key export ANTHROPIC_API_KEY=sk-ant-... # Override LLM provider to Google export MCP_LLM_PROVIDER=google # Specify LLM model name export MCP_LLM_MODEL_NAME=gemini-3-flash-preview # Run browser in headless mode export MCP_BROWSER_HEADLESS=true # Set Chrome DevTools Protocol URL export MCP_BROWSER_CDP_URL=http://localhost:9222 # Set user data directory for Chrome profile export MCP_BROWSER_USER_DATA_DIR=~/.chrome-profile # Set server host export MCP_SERVER_HOST=127.0.0.1 # Set server port export MCP_SERVER_PORT=8383 # Set directory for server results export MCP_SERVER_RESULTS_DIR=~/Documents/browser-results # Set maximum research searches export MCP_RESEARCH_MAX_SEARCHES=5 # Set directory for saving research data export MCP_RESEARCH_SAVE_DIRECTORY=~/Documents/research # Enable skills export MCP_SKILLS_ENABLED=true # Set directory for skill files export MCP_SKILLS_DIRECTORY=~/.config/browser-skills ``` ``` -------------------------------- ### Get Task Details Source: https://github.com/saik0s/mcp-browser-use/blob/main/skills/browser-use/SKILL.md Retrieves detailed information about a specific task, including its input, output, and progress. Requires a task ID. ```shell task_get task_id: a1b2c3d4 ``` -------------------------------- ### Initialize and Toggle Theme Management (JavaScript) Source: https://github.com/saik0s/mcp-browser-use/blob/main/src/mcp_server_browser_use/ui/dashboard.html Manages the application's theme (light/dark) by reading from local storage or system preferences. It updates the UI and the theme toggle button accordingly. Dependencies include `localStorage` and `window.matchMedia`. ```javascript const API_BASE = 'http://localhost:8383/api'; let healthCheckInterval = null; // Theme management function function initTheme() { const saved = localStorage.getItem('theme'); const theme = saved || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); document.documentElement.setAttribute('data-theme', theme); updateThemeButton(theme); } function toggleTheme() { const current = document.documentElement.getAttribute('data-theme'); const next = current === 'dark' ? 'light' : 'dark'; document.documentElement.setAttribute('data-theme', next); localStorage.setItem('theme', next); updateThemeButton(next); } function updateThemeButton(theme) { const btn = document.getElementById('themeToggle'); btn.textContent = theme === 'dark' ? '☀️ Light' : '🌙 Dark'; } ``` -------------------------------- ### Server Implementation: Imports Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Imports necessary modules for the MCP server implementation, including `FastMCP`, dependency injection helpers like `CurrentContext` and `Progress`, and context-related classes. ```python """MCP server exposing browser-use as tools with native background task support.""" import logging from typing import Optional from browser_use import Agent, BrowserProfile from browser_use.browser.profile import ProxySettings from fastmcp import FastMCP, TaskConfig from fastmcp.dependencies import CurrentContext, Progress # ← Key imports from fastmcp.server.context import Context # ← Correct import from .config import settings from .exceptions import BrowserError, LLMProviderError from .providers import get_llm from .research.machine import ResearchMachine ``` -------------------------------- ### Update Dependencies: pyproject.toml Source: https://github.com/saik0s/mcp-browser-use/blob/main/docs/fastmcp-migration-solution.md Specifies the dependencies required for the FastMCP migration, including `browser-use`, `fastmcp` from jlowin's repository, and development dependencies like `pytest` and `pyright`. ```toml [tool.poetry] name = "mcp-browser-use" version = "0.1.0" description = "" authors = ["Saik0s "] readme = "README.md" packages = [{include = "mcp_server_browser_use"}] [tool.poetry.dependencies] python = "^3.12" browser-use=">=0.10.1" fastmcp = {git = "https://github.com/jlowin/fastmcp.git", branch = "main"} # Use jlowin's repo pydantic-settings=">=2.0.0" typer=">=0.12.0" uvicorn=">=0.30.0" starlette=">=0.38.0" [tool.poetry.group.dev.dependencies] pyright=">=1.1.378" pytest=">=8.3.3" pytest-asyncio=">=0.24.0" # For async test support ruff=">=0.6.9" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" ``` -------------------------------- ### Run a Skill Source: https://context7.com/saik0s/mcp-browser-use/llms.txt Executes a skill with specified parameters. This can be a direct execution or a hint-based fallback. ```APIDOC ## POST /api/skills/{skill_id}/run ### Description Executes a skill with optional parameters. The execution can be a fast path or a slower hint-based fallback. ### Method POST ### Endpoint /api/skills/{skill_id}/run ### Parameters #### Path Parameters - **skill_id** (string) - Required - The identifier of the skill to run. #### Request Body - **params** (object) - Optional - A key-value map of parameters to pass to the skill. - **query** (string) - Example parameter for the 'npm-search' skill. ### Request Example ```bash curl -X POST http://localhost:8383/api/skills/npm-search/run \ -H "Content-Type: application/json" \ -d '{"params": {"query": "vue"}}' ``` ### Response #### Success Response (200) Returns the result of the skill execution. #### Response Example ```json { "result": [ { "name": "vue", "version": "3.4.1", "description": "The Progressive JavaScript Framework." } ] } ``` ``` -------------------------------- ### Get Specific Task Details (REST API) Source: https://github.com/saik0s/mcp-browser-use/blob/main/README.md This curl command fetches detailed information about a specific task identified by its unique `task_id`. The task ID is appended to the /api/tasks/ endpoint. The response is in JSON format. ```bash curl http://localhost:8383/api/tasks/abc123 ```