# https://github.com/browserbase/mcp-server-browserbase Project Manual

Generated on: 2026-05-21 16:46:07 UTC

## Table of Contents

- [Introduction](#introduction)
- [Quick Start Guide](#quickstart)
- [System Architecture Overview](#architecture-overview)
- [Transport Layer](#transport-layer)
- [MCP Tools Reference](#mcp-tools)
- [Session Management](#session-management)
- [Configuration Options](#configuration-options)
- [Model Configuration](#model-configuration)
- [Deployment Methods](#deployment-methods)
- [Testing](#testing)

<a id='introduction'></a>

## Introduction

### Related Pages

Related topics: [System Architecture Overview](#architecture-overview), [Quick Start Guide](#quickstart)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)
- [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)
- [CHANGELOG.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/CHANGELOG.md)
- [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)
- [src/context.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)
- [src/sessionManager.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)
- [src/types/types.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/types/types.ts)
</details>

# Introduction

The **Browserbase MCP Server** (`@browserbasehq/mcp`) is an open-source Model Context Protocol (MCP) server that enables AI web browser automation through Browserbase's infrastructure and Stagehand's AI-powered browser control capabilities. Source: [README.md]()

## Project Overview

This MCP server bridges AI assistants with real web browser automation, allowing Large Language Models (LLMs) to interact with web pages through a standardized protocol. The server leverages Browserbase's cloud browser infrastructure for reliable, scalable web automation while using Stagehand for AI-driven element detection and action execution. Source: [README.md]()

| Attribute | Value |
|-----------|-------|
| **Package Name** | `@browserbasehq/mcp` |
| **Current Version** | `3.0.0` |
| **License** | Apache 2.0 |
| **Repository** | `browserbase/mcp-server-browserbase` |
| **Package Manager** | pnpm 10.12.4 |

Source: [package.json]()

## Architecture Overview

The MCP server follows a modular architecture with clear separation of concerns:

```mermaid
graph TD
    A[MCP Client] -->|MCP Protocol| B[MCP Server Entry]
    B --> C[Context Manager]
    C --> D[Session Manager]
    C --> E[Tools Registry]
    D --> F[Stagehand Instances]
    F --> G[Browserbase Cloud]
    E --> H[start]
    E --> I[navigate]
    E --> J[act]
    E --> K[observe]
    E --> L[extract]
    E --> M[end]
```

### Core Components

| Component | File Location | Purpose |
|-----------|---------------|---------|
| **Server Entry** | `src/index.ts` | MCP server initialization, tool registration, and request handling |
| **Context Manager** | `src/context.ts` | Executes tools and manages tool lifecycle |
| **Session Manager** | `src/sessionManager.ts` | Manages Stagehand browser sessions with lifecycle handling |
| **Tools Registry** | `src/tools/index.ts` | Defines available MCP tools |
| **Type Definitions** | `src/types/types.ts` | TypeScript interfaces for sessions, tools, and configurations |

Source: [src/index.ts](), [src/context.ts](), [src/sessionManager.ts](), [src/types/types.ts]()

## Available Tools

The MCP server exposes six primary tools for browser automation:

| Tool | Description | Parameters |
|------|-------------|------------|
| `start` | Create a new browser session | `{ apiKey?, projectId?, modelName?, modelApiKey?, browserbaseSessionID?, meta? }` |
| `navigate` | Navigate to a URL | `{ url: string }` |
| `act` | Perform an action on the page | `{ action: string }` |
| `observe` | Observe actionable elements on the page | `{ instruction: string }` |
| `extract` | Extract data from the page | `{ instruction?: string }` |
| `end` | Close the browser session | _(none)_ |

Source: [README.md](), [CHANGELOG.md]()

## Configuration Options

### Command-Line Flags

The server accepts the following configuration flags:

| Flag | Description | Default |
|------|-------------|---------|
| `--proxies` | Enable proxy support for sessions | `false` |
| `--viewportWidth` | Browser viewport width in pixels | `1280` |
| `--viewportHeight` | Browser viewport height in pixels | `768` |
| `--modelName` | Stagehand model identifier | `google/gemini-2.5-flash-lite` |
| `--modelApiKey` | API key for custom model provider | _(none)_ |
| `--experimental` | Enable experimental features | `false` |

Source: [README.md]()

### Configuration Schema

The server validates configuration using Zod with the following schema:

```typescript
export const configSchema = z.object({
  browserbaseApiKey: z.string().describe("The Browserbase API Key to use"),
  browserbaseProjectId: z.string().describe("The Browserbase Project ID to use"),
  proxies: z.boolean().optional().describe("Whether to use Browserbase proxies"),
  verified: z.boolean().optional().describe("Browserbase Verified Identity"),
  advancedStealth: z.boolean().optional().describe("Deprecated alias for verified"),
  keepAlive: z.boolean().optional().describe("Keep session alive"),
  context: z.object({
    contextId: z.string().optional().describe("Context ID")
  }).optional()
});
```

Source: [src/index.ts]()

### Required Environment Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `BROWSERBASE_API_KEY` | Your Browserbase API key | Yes |
| `BROWSERBASE_PROJECT_ID` | Your Browserbase Project ID | Yes |
| `GEMINI_API_KEY` | Gemini API key (for default model) | Yes |

Source: [README.md](), [server.json]()

## Transport Types

The MCP server supports two transport mechanisms for communication:

```mermaid
graph LR
    A[MCP Client] --> B[SHTTP Transport]
    A --> C[STDIO Transport]
    B -->|HTTP| D[Hosted Server<br/>mcp.browserbase.com]
    C -->|stdin/stdout| E[Local Server]
    E --> F[Direct Installation]
    E --> G[Docker Container]
```

### SHTTP (Hosted)

The hosted solution runs at `https://mcp.browserbase.com/mcp` and is the recommended approach for most users. Source: [README.md]()

```json
{
  "mcpServers": {
    "browserbase": {
      "type": "http",
      "url": "https://mcp.browserbase.com/mcp"
    }
  }
}
```

### STDIO (Self-Hosted)

Self-hosted deployment supports both direct npm installation and Docker containers. Source: [README.md]()

**Via NPM:**
```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["@browserbasehq/mcp"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

**Via Docker:**
```json
{
  "mcpServers": {
    "browserbase": {
      "command": "docker",
      "args": ["run", "--rm", "-i", "-e", "BROWSERBASE_API_KEY", "-e", "BROWSERBASE_PROJECT_ID", "-e", "GEMINI_API_KEY", "mcp-browserbase"]
    }
  }
}
```

## Session Management

The SessionManager handles browser session lifecycle with automatic validation and recreation:

```mermaid
stateDiagram-v2
    [*] --> Idle: No sessions
    Idle --> Creating: start tool called
    Creating --> Active: Session created
    Active --> Validating: Periodic check
    Validating --> Active: Session valid
    Validating --> Recreating: Session stale
    Recreating --> Creating: Retry
    Active --> Closing: end tool called
    Closing --> Idle: Cleanup complete
```

### Session Validation

Sessions are validated by checking if the Stagehand context has available pages. If validation fails, the session is marked as stale and recreated automatically. Source: [src/sessionManager.ts]()

## Model Configuration

Stagehand defaults to Google's Gemini 2.5 Flash Lite model, which has been shown to perform best in evaluations. However, the server supports custom models from various providers including Anthropic Claude and OpenAI GPT-4o. Source: [README.md]()

### Supported Models

The model must be supported by Stagehand. For a full list of supported models, see the [Stagehand documentation](https://docs.stagehand.dev/examples/custom_llms#supported-llms).

### Custom Model Setup

When using a custom model, provide both the model name and API key:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": [
        "@browserbasehq/mcp",
        "--modelName",
        "anthropic/claude-sonnet-4.5",
        "--modelApiKey",
        "your-anthropic-api-key"
      ]
    }
  }
}
```

Source: [README.md]()

## Version History

### v3.0.0 (Breaking Changes)

The latest major version introduced significant changes to align with the hosted MCP server:

- Tool names renamed (e.g., `browserbase_session_create` → `start`)
- Removed tools: `browserbase_screenshot`, `browserbase_stagehand_get_url`, `browserbase_stagehand_agent`
- Default model changed from `gemini-2.0-flash` to `google/gemini-2.5-flash-lite`
- Removed Smithery references and dependencies

Source: [CHANGELOG.md]()

## Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `@browserbasehq/sdk` | `^2.6.0` | Browserbase API client |
| `@browserbasehq/stagehand` | `^3.3.0` | AI browser automation |
| `@modelcontextprotocol/sdk` | `^1.13.1` | MCP protocol implementation |
| `zod` | `^3.25.67` | Schema validation |
| `commander` | `^14.0.0` | CLI argument parsing |

Source: [package.json]()

## Resources and Sampling

The server implements MCP's optional capabilities for completeness:

- **Resources**: Currently returns empty (no custom resources defined)
- **Sampling**: Capability declared but depends on client support

Source: [src/mcp/resources.ts](), [src/mcp/sampling.ts]()

## See Also

- [Browserbase MCP Documentation](https://docs.browserbase.com/integrations/mcp/introduction)
- [Model Context Protocol Specification](https://spec.modelcontextprotocol.io/)
- [Stagehand Documentation](https://docs.stagehand.dev/)
- [Stagehand Evals](https://www.stagehand.dev/evals)

---

<a id='quickstart'></a>

## Quick Start Guide

### Related Pages

Related topics: [Introduction](#introduction), [Deployment Methods](#deployment-methods)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)
- [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)
- [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)
- [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)
- [src/tools/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)
- [src/types/types.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/types/types.ts)
- [src/context.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)
- [CHANGELOG.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/CHANGELOG.md)
- [server.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/server.json)
</details>

# Quick Start Guide

The MCP Server for Browserbase is an implementation of the Model Context Protocol (MCP) that enables AI assistants to control web browsers through natural language commands. This guide covers all supported deployment methods, from the simplest hosted option to fully self-hosted deployments using Docker or direct Node.js execution.

## Overview

The server provides browser automation capabilities powered by Browserbase and Stagehand. It exposes MCP tools that allow LLMs to navigate websites, interact with page elements, extract data, and capture screenshots using natural language instructions.

### Key Capabilities

| Capability | Description |
|------------|-------------|
| **Browser Navigation** | Navigate to URLs and interact with web pages |
| **Element Interaction** | Click, type, and perform actions on page elements |
| **Data Extraction** | Extract structured data from web pages |
| **Session Management** | Create and manage persistent browser sessions |
| **Proxy Support** | Route traffic through Browserbase proxies |
| **Stealth Mode** | Use Browserbase Verified Identity for undetected automation |

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### Architecture

```mermaid
graph TD
    A[MCP Client] -->|HTTP or STDIO| B[MCP Server]
    B -->|Tool Calls| C[Context Handler]
    C -->|Session Mgmt| D[Stagehand Instance]
    D -->|Browser Automation| E[Browserbase Cloud]
    E -->|CDP| F[Remote Browser]
    
    G[BROWSERBASE_API_KEY] --> B
    H[BROWSERBASE_PROJECT_ID] --> B
    I[GEMINI_API_KEY] --> B
```

The server is built on the `@modelcontextprotocol/sdk` and registers capabilities for tools and resources. The `Context` class manages the lifecycle of Stagehand instances and routes tool requests to appropriate handlers.

Source: [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts:32-48)
Source: [src/context.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)

## Available Tools

The server exposes the following MCP tools that can be called by any compatible MCP client:

| Tool | Description | Parameters |
|------|-------------|------------|
| `start` | Create a new browser session | `{ apiKey?, projectId?, modelName?, modelApiKey? }` |
| `end` | Close an existing browser session | `{ sessionId: string }` |
| `navigate` | Navigate to a URL | `{ url: string }` |
| `act` | Perform an action on the page | `{ action: string }` |
| `observe` | Observe actionable elements on the page | `{ instruction: string }` |
| `extract` | Extract data from the page | `{ instruction?: string }` |

Source: [src/tools/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)
Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

## Deployment Methods

The server supports multiple transport mechanisms and deployment options depending on your requirements.

```mermaid
graph LR
    A[Deployment Options] --> B[SHTTP Hosted]
    A --> C[NPM Package]
    A --> D[Direct Installation]
    A --> E[Docker]
    
    B --> F[Easiest Setup]
    C --> G[Managed Runtime]
    D --> H[Full Control]
    E --> I[Containerized]
```

### Method 1: SHTTP (Hosted MCP)

The recommended approach uses the Browserbase hosted MCP server. This provides the simplest setup and includes LLM costs for Gemini, which is the best performing model in Stagehand according to their evaluations.

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md:42-44)

#### Configuration for SHTTP-Clients

If your MCP client supports HTTP transport:

```json
{
  "mcpServers": {
    "browserbase": {
      "type": "http",
      "url": "https://mcp.browserbase.com/mcp"
    }
  }
}
```

#### Configuration for Non-SHTTP Clients

If your client only supports STDIO but can invoke external processes:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["mcp-remote", "https://mcp.browserbase.com/mcp"]
    }
  }
}
```

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md:46-61)

### Method 2: NPM Package (Recommended for Self-Hosted)

This method runs the server locally while still using Browserbase's cloud infrastructure for browser sessions.

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["@browserbasehq/mcp"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

The package is published as `@browserbasehq/mcp` with version tracking available on npm.

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md:82-96)
Source: [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json:2-6)

### Method 3: Direct Installation

For full control over the runtime environment, clone and build the repository locally.

#### Prerequisites

- Node.js 18+ 
- npm or pnpm
- Git

#### Installation Steps

```bash
git clone https://github.com/browserbase/mcp-server-browserbase.git
cd mcp-server-browserbase
npm install && npm run build
```

The build script compiles TypeScript and sets executable permissions on the output files:

```bash
"build": "tsc && shx chmod +x dist/*.js"
```

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md:103-115)
Source: [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json:21)

#### Configuration

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "node",
      "args": ["/path/to/mcp-server-browserbase/cli.js"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

### Method 4: Docker

Containerized deployment provides isolation and consistency across environments.

#### Build the Image

```bash
git clone https://github.com/browserbase/mcp-server-browserbase.git
cd mcp-server-browserbase
docker build -t mcp-browserbase .
```

#### Configuration

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "-e",
        "BROWSERBASE_API_KEY",
        "-e",
        "BROWSERBASE_PROJECT_ID",
        "-e",
        "GEMINI_API_KEY",
        "mcp-browserbase"
      ],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md:116-143)

## Configuration Options

The server accepts configuration through environment variables and command-line arguments.

### Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `BROWSERBASE_API_KEY` | Yes | Your Browserbase API key for session management |
| `BROWSERBASE_PROJECT_ID` | Yes | Your Browserbase Project ID |
| `GEMINI_API_KEY` | Yes | Gemini API key for LLM inference (default model) |

Source: [server.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/server.json:17-34)

### Command-Line Flags

| Flag | Description |
|------|-------------|
| `--proxies` | Enable Browserbase proxy sessions |
| `--modelName` | Specify a different model to use (must be supported by Stagehand) |
| `--modelApiKey` | API key for the custom model |
| `--keepAlive` | Keep the browser session alive after tool execution |
| `--verified` | Use Browserbase Verified Identity (Scale Plan only) |

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md:78-80)
Source: [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts:15-35)

### Default Configuration

The server uses sensible defaults that can be overridden:

| Setting | Default Value |
|---------|---------------|
| Default Model | `google/gemini-2.5-flash-lite` |
| Browser Width | 1024px |
| Browser Height | 768px |
| Proxies | Disabled |
| Keep Alive | Disabled |

Source: [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts:37-48)

## Custom Model Configuration

To use a different LLM model, you must use a self-hosted deployment (not the hosted MCP server) and specify the model name:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["@browserbasehq/mcp", "--modelName", "anthropic/claude-sonnet-4-20250514"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "ANTHROPIC_API_KEY": ""
      }
    }
  }
}
```

The model must be supported in Stagehand. Check the supported models documentation at [docs.stagehand.dev](https://docs.stagehand.dev/examples/custom_llms#supported-llms).

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md:154-167)

## Session Workflow

Browser sessions follow a specific lifecycle managed by the MCP server:

```mermaid
sequenceDiagram
    participant Client
    participant Server
    participant Browserbase
    participant Browser
    
    Client->>Server: start session
    Server->>Browserbase: Create Browserbase Session
    Browserbase->>Browser: Launch Remote Browser
    Browser->>Server: Session Established
    Server->>Client: sessionId returned
    
    Client->>Server: navigate { url }
    Server->>Browser: Load URL
    Browser->>Server: Page Loaded
    Server->>Client: Navigation Complete
    
    Client->>Server: act { action }
    Server->>Browser: Execute Action
    Browser->>Server: Action Result
    Server->>Client: Action Complete
    
    Client->>Server: extract { instruction }
    Server->>Browser: Extract Data
    Browser->>Server: Extracted Data
    Server->>Client: Data Returned
    
    Client->>Server: end session
    Server->>Browserbase: Close Session
    Browserbase->>Browser: Terminate
    Server->>Client: Session Closed
```

### Session Creation Parameters

When starting a session, the following parameters are available:

```typescript
type CreateSessionParams = {
  apiKey?: string;                    // Override default API key
  projectId?: string;                // Override default project ID
  modelName?: string;                // Use custom model
  modelApiKey?: string;              // API key for custom model
  browserbaseSessionID?: string;     // Resume existing session
  browserbaseSessionCreateParams?: any;  // Browserbase-specific options
  meta?: Record<string, any>;        // Session metadata
};
```

Source: [src/types/types.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/types/types.ts:10-20)

## Verifying Installation

After configuring your MCP client, verify the connection by checking that the server responds to tool list requests. The server should advertise the following tools:

1. `start` - Session management
2. `end` - Session cleanup
3. `navigate` - URL navigation
4. `act` - Page interactions
5. `observe` - Element detection
6. `extract` - Data extraction

You can use the MCP inspector for debugging:

```bash
npx @modelcontextprotocol/inspector build/index.js
```

Source: [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json:24)

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| "browserbaseApiKey is required" | Set the `BROWSERBASE_API_KEY` environment variable |
| "browserbaseProjectId is required" | Set the `BROWSERBASE_PROJECT_ID` environment variable |
| Model not supported | Check [Stagehand supported models](https://docs.stagehand.dev/examples/custom_llms#supported-llms) |
| Docker connection issues | Ensure environment variables are passed with `-e` flags |

Source: [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts:8-14)

## Development

For local development and testing:

```bash
# Install dependencies
pnpm install

# Build the project
pnpm build

# Run tests
pnpm test

# Watch mode for development
pnpm watch

# Lint code
pnpm lint

# Format code
pnpm format
```

Source: [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json:21-31)

## Next Steps

- Review the [Browserbase MCP Documentation](https://docs.browserbase.com/integrations/mcp/introduction) for advanced usage
- Explore the [MCP Specification](https://spec.modelcontextprotocol.io/) for protocol details
- Check the [Stagehand Documentation](https://docs.stagehand.dev/) for browser automation capabilities
- Report issues at [GitHub Issues](https://github.com/browserbase/mcp-server-browserbase/issues)

---

<a id='architecture-overview'></a>

## System Architecture Overview

### Related Pages

Related topics: [Transport Layer](#transport-layer), [MCP Tools Reference](#mcp-tools), [Session Management](#session-management)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)
- [src/server.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/server.ts)
- [src/program.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/program.ts)
- [src/types/types.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/types/types.ts)
- [src/context.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)
- [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)
- [src/tools/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)
- [src/sessionManager.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)
- [config.d.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)
- [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)
</details>

# System Architecture Overview

The mcp-server-browserbase is an MCP (Model Context Protocol) server that enables AI web browser automation by integrating Browserbase's infrastructure with Stagehand's AI-powered browser control capabilities. The server acts as a bridge between MCP-compliant AI clients and browser automation, providing tools for session management, navigation, interaction, and data extraction.

## Architecture Layers

The system follows a layered architecture pattern that separates concerns between transport, protocol, execution, and browser automation.

```mermaid
graph TD
    subgraph "Transport Layer"
        STDIO[STDIO Transport]
        SHTTP[SHTTP Transport]
    end
    
    subgraph "MCP Protocol Layer"
        MCP_SDK[MCP SDK Server]
        Tools[MCP Tools]
        Resources[Resources]
        Sampling[Sampling]
    end
    
    subgraph "Application Layer"
        Context[Context Controller]
        Config[Configuration Resolver]
        SessionMgr[Session Manager]
    end
    
    subgraph "Browser Automation Layer"
        Stagehand[Stagehand Instance]
        Browserbase[Browserbase SDK]
    end
    
    STDIO --> MCP_SDK
    SHTTP --> MCP_SDK
    MCP_SDK --> Tools
    MCP_SDK --> Resources
    MCP_SDK --> Sampling
    Context --> SessionMgr
    SessionMgr --> Stagehand
    Stagehand --> Browserbase
```

**Source:** [src/index.ts:1-50](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts) | [src/context.ts:1-30](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)

## Core Components

### 1. Entry Point and CLI (program.ts)

The application entry point uses Commander.js to parse command-line arguments and initialize the server.

```mermaid
graph LR
    CLI[CLI Arguments] --> Program[program.ts]
    Program --> Config[resolveConfig]
    Config --> CreateServer[createServer]
    CreateServer --> Transport[Start Transport]
```

**Source:** [src/program.ts:1-80](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/program.ts)

**Command-line options supported:**

| Flag | Type | Description | Default |
|------|------|-------------|---------|
| `--browserbaseApiKey` | string | Browserbase API Key | env.BROWSERBASE_API_KEY |
| `--browserbaseProjectId` | string | Browserbase Project ID | env.BROWSERBASE_PROJECT_ID |
| `--proxies` | boolean | Enable Browserbase proxies | false |
| `--verified` | boolean | Use Verified Identity (Scale Plan) | false |
| `--advancedStealth` | boolean | Deprecated alias for verified | false |
| `--contextId` | string | Browserbase Context ID | undefined |
| `--persist` | boolean | Keep session alive | false |
| `--port` | number | SHTTP transport port | undefined (uses STDIO) |
| `--host` | string | SHTTP bind host | undefined |
| `--browserWidth` | number | Viewport width | 1024 |
| `--browserHeight` | number | Viewport height | 768 |
| `--modelName` | string | Stagehand model | google/gemini-2.5-flash-lite |
| `--modelApiKey` | string | Custom model API key | env.GEMINI_API_KEY |
| `--experimental` | boolean | Enable experimental features | false |

**Source:** [src/config.ts:15-28](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

### 2. Configuration System

The configuration system uses Zod for schema validation and implements a merge strategy: Defaults < File Config < CLI Options.

```mermaid
graph TD
    Default[Default Config] --> Merge[mergeConfig]
    File[File Config] --> Merge
    CLI[CLI Options] --> Merge
    Merge --> Normalize[normalizeVerifiedConfig]
    Normalize --> FinalConfig[Resolved Config]
    FinalConfig --> AddEnvVars[Add Env Vars]
    AddEnvVars --> Validate[Validation]
```

**Source:** [src/config.ts:50-75](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

**Configuration schema (Zod):**

```typescript
export const configSchema = z.object({
  browserbaseApiKey: z.string().describe("The Browserbase API Key to use"),
  browserbaseProjectId: z.string().describe("The Browserbase Project ID to use"),
  proxies: z.boolean().optional().describe("Whether to use Browserbase proxies"),
  verified: z.boolean().optional().describe("Use Browserbase Verified Identity"),
  keepAlive: z.boolean().optional().describe("Keep session alive"),
  context: z.object({
    contextId: z.string().optional()
  }).optional()
});
```

**Source:** [src/index.ts:30-50](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)

### 3. MCP Server (server.ts + index.ts)

The MCP server is built on the @modelcontextprotocol/sdk and handles tool registration, request routing, and protocol compliance.

**Source:** [src/server.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/server.ts) | [src/index.ts:80-130](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)

**MCP Server capabilities:**

| Capability | Implementation | Description |
|------------|----------------|-------------|
| Tools | TOOLS array | Browser automation operations |
| Resources | RESOURCE_TEMPLATES | URI-based resource access |
| Sampling | SAMPLING_CAPABILITY | Server-initiated LLM completions |

### 4. Context Controller (context.ts)

The Context class serves as the central orchestrator, maintaining references to the MCP server instance, configuration, and SessionManager.

```mermaid
classDiagram
    class Context {
        +Server server
        +Config config
        -SessionManager sessionManager
        +getServer() Server
        +getSessionManager() SessionManager
        +getStagehand(sessionId?) Promise~Stagehand~
        +run(tool, params) CallToolResult
    }
    
    class SessionManager {
        -Map sessions
        -string activeSessionId
        +createSession(config) Promise~Session~
        +getSession(id) Promise~Session~
        +closeSession(id) Promise~void~
        +getActiveSessionId() string
    }
    
    Context --> SessionManager
```

**Source:** [src/context.ts:15-50](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)

### 5. Session Manager (sessionManager.ts)

The SessionManager handles lifecycle management of browser sessions, creating and caching Stagehand instances per session.

**Source:** [src/sessionManager.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

**Session lifecycle:**

```mermaid
stateDiagram-v2
    [*] --> NoSession: Initial State
    NoSession --> Creating: start tool called
    Creating --> Active: Stagehand initialized
    Active --> Active: navigate/act/observe/extract
    Active --> Closing: end tool called
    Closing --> NoSession: Session closed
    Closing --> Active: Error, retry
```

### 6. Tool System

Tools are the primary interface for MCP clients to interact with browser automation capabilities.

**Source:** [src/tools/index.ts:1-25](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)

**Available tools:**

| Tool | Description | Input Schema |
|------|-------------|--------------|
| `start` | Create new browser session | `{ contextId?: string, proxies?: boolean, verified?: boolean }` |
| `end` | Close browser session | `{}` |
| `navigate` | Navigate to URL | `{ url: string }` |
| `act` | Perform action on page | `{ action: string }` |
| `observe` | Observe actionable elements | `{ instruction: string }` |
| `extract` | Extract data from page | `{ instruction?: string }` |

**Source:** [src/tools/index.ts:10-20](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)

**Tool registration flow:**

```mermaid
sequenceDiagram
    participant Client as MCP Client
    participant Server as MCP Server
    participant Context as Context
    participant SessionMgr as SessionManager
    participant Stagehand as Stagehand
    
    Client->>Server: Call Tool
    Server->>Context: run(tool, params)
    Context->>SessionMgr: getSession(id)
    SessionMgr->>Stagehand: Get/Create Instance
    Stagehand->>Stagehand: Execute operation
    Stagehand-->>Context: Result
    Context-->>Server: CallToolResult
    Server-->>Client: JSON-RPC Response
```

## Transport Layer

The server supports two transport mechanisms for MCP communication.

**Source:** [src/transport.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts)

| Transport | Use Case | Configuration |
|-----------|----------|---------------|
| STDIO | Local CLI tools, Claude Desktop | Default when no port specified |
| SHTTP | HTTP clients, Remote servers | `--port` flag required |

**STDIO Configuration (Docker):**

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "docker",
      "args": ["run", "--rm", "-i", "mcp-browserbase"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

**Source:** [README.md:1-50](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

## Data Flow

### Tool Execution Pipeline

```mermaid
graph TD
    Request[Tool Request] --> Validate[Zod Validation]
    Validate --> Authenticate[Auth Check]
    Authenticate --> GetSession[Get Session]
    GetSession --> GetStagehand[Get Stagehand]
    GetStagehand --> Execute[Execute Tool]
    Execute --> Transform[Transform Result]
    Transform --> Response[JSON-RPC Response]
    
    Execute -->|Error| ErrorHandler[Error Handler]
    ErrorHandler --> Response
```

**Source:** [src/index.ts:110-145](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)

### Configuration Merging Strategy

```mermaid
graph LR
    A[Defaults] -->|Low Priority| M[Merge Config]
    B[Environment Vars] -->|Medium Priority| M
    C[CLI Arguments] -->|High Priority| M
    M --> R[Resolved Config]
```

**Source:** [src/config.ts:40-65](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

## Type System

**Source:** [src/types/types.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/types/types.ts)

### Key Types

| Type | Definition | Usage |
|------|------------|-------|
| `MCPTool` | Tool definition with schema | Tool registration |
| `MCPToolsArray` | Array of MCPTool | Tool collection |
| `Config` | Server configuration interface | All config operations |
| `CLIOptions` | Command-line options | CLI parsing |

### Configuration Interface (config.d.ts)

```typescript
interface Config {
  browserbaseApiKey: string;
  browserbaseProjectId: string;
  proxies: boolean;
  verified?: boolean;
  modelName: string;
  modelApiKey?: string;
  keepAlive?: boolean;
  viewPort?: {
    browserWidth: number;
    browserHeight: number;
  };
  server?: {
    port?: number;
    host?: string;
  };
}
```

**Source:** [config.d.ts:1-50](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)

## Dependencies Architecture

**Source:** [package.json:20-45](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

```mermaid
graph BT
    MCP["@modelcontextprotocol/sdk"]
    Stagehand["@browserbasehq/stagehand"]
    BrowserbaseSDK["@browserbasehq/sdk"]
    Zod["zod"]
    Commander["commander"]
    
    mcp-server-browserbase --> MCP
    mcp-server-browserbase --> Stagehand
    mcp-server-browserbase --> BrowserbaseSDK
    mcp-server-browserbase --> Zod
    mcp-server-browserbase --> Commander
```

### Core Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | ^1.13.1 | MCP protocol implementation |
| `@browserbasehq/stagehand` | ^3.3.0 | AI browser automation |
| `@browserbasehq/sdk` | ^2.6.0 | Browserbase API client |
| `zod` | ^3.25.67 | Schema validation |
| `commander` | ^14.0.0 | CLI framework |

## Error Handling

The server implements structured error handling at multiple levels:

**Source:** [src/index.ts:125-140](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)

```mermaid
graph TD
    Error[Error Thrown] --> Log[Log to stderr]
    Log --> Format[Format error message]
    Format --> Throw[Throw MCP Error]
    Throw --> Response[JSON-RPC Error Response]
    
    Response --> Client[Client receives error]
```

**Error message format:**
```
[MCP Error] {ISO timestamp} Error running tool {tool_name}: {error_message}
```

## Module Structure Summary

```
mcp-server-browserbase/
├── src/
│   ├── index.ts          # Server factory, tool registration
│   ├── server.ts         # MCP server initialization
│   ├── program.ts        # CLI entry point
│   ├── context.ts        # Central controller
│   ├── config.ts         # Configuration resolver
│   ├── sessionManager.ts # Session lifecycle
│   ├── transport.ts      # STDIO/SHTTP transport
│   ├── types/
│   │   └── types.ts      # TypeScript definitions
│   ├── mcp/
│   │   ├── resources.ts # MCP resources
│   │   └── sampling.ts  # MCP sampling
│   └── tools/
│       ├── index.ts      # Tool exports
│       ├── session.ts    # start/end tools
│       ├── navigate.ts   # navigate tool
│       ├── act.ts        # act tool
│       ├── observe.ts   # observe tool
│       └── extract.ts   # extract tool
├── config.d.ts           # Config interface definition
├── package.json          # Dependencies and scripts
└── README.md             # Documentation
```

## Deployment Modes

### NPM Package (npx)

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["@browserbasehq/mcp"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

### Docker Container

```bash
docker build -t mcp-browserbase .
```

### Hosted MCP Server

```json
{
  "mcpServers": {
    "browserbase": {
      "type": "http",
      "url": "https://mcp.browserbase.com/mcp"
    }
  }
}
```

**Source:** [README.md:50-100](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

---

<a id='transport-layer'></a>

## Transport Layer

### Related Pages

Related topics: [System Architecture Overview](#architecture-overview), [Deployment Methods](#deployment-methods)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/transport.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts)
- [src/server.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/server.ts)
- [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)
- [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)
- [config.d.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)
- [server.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/server.json)
</details>

# Transport Layer

## Overview

The Transport Layer in the Browserbase MCP Server handles the communication between the MCP client and the server. It abstracts the underlying transport mechanism, allowing the server to support multiple transport protocols while maintaining a consistent interface for tool execution and resource management.

The transport layer is responsible for:

- Accepting incoming connections from MCP clients
- Managing server sessions for stateful communication
- Routing requests to appropriate handlers
- Handling the serialization and deserialization of MCP protocol messages

Source: [src/transport.ts:1-50](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts)

## Supported Transport Protocols

The MCP server supports two transport protocols:

| Transport Type | Description | Use Case |
|----------------|-------------|----------|
| **STDIO** | Standard Input/Output communication via process streams | Local development, CLI tools, direct execution |
| **SHTTP** | Streamable HTTP transport using the MCP HTTP extension | Hosted deployments, production environments, remote access |

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### STDIO Transport

The STDIO transport uses standard input and output streams for communication. This is the default transport when no server configuration is provided.

```mermaid
graph LR
    A[MCP Client] -->|stdin| B[MCP Server]
    B -->|stdout| A
```

The STDIO transport is initialized when both `port` and `host` are undefined in the server configuration. Source: [config.d.ts:45-55](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)

### SHTTP (Streamable HTTP) Transport

The SHTTP transport uses HTTP with session management for stateful communication. It supports multiple concurrent sessions through a session ID mechanism.

```mermaid
graph TD
    A[HTTP Request] --> B{Session ID Present?}
    B -->|Yes| C[Existing Session]
    B -->|No| D[Create New Session]
    C --> E[StreamableHTTPServerTransport]
    D --> F[Generate UUID Session ID]
    F --> E
    E --> G[Server Instance]
    G --> H[Tool Execution]
```

Source: [src/transport.ts:30-55](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts)

## Architecture

### Server Initialization Flow

```mermaid
sequenceDiagram
    participant Client
    participant Transport
    participant Server
    participant SessionManager
    participant Stagehand

    Client->>Transport: HTTP Request
    Transport->>Transport: Check Session ID
    alt No Session
        Transport->>Transport: Generate UUID
        Transport->>Server: Create Instance
        Server->>SessionManager: Initialize Session
        Server->>Stagehand: Create Browser Context
    else Has Session
        Transport->>Server: Route to Existing Session
    end
    Server->>Transport: Process Request
    Transport->>Client: Response
```

### Component Responsibilities

| Component | File | Responsibility |
|-----------|------|----------------|
| `startStdioTransport` | [src/transport.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts) | Initializes STDIO transport with the MCP SDK |
| `startHttpTransport` | [src/transport.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts) | Creates HTTP server with session management |
| `ServerList` | [src/server.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/server.ts) | Manages server instance lifecycle |
| `Context` | [src/context.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts) | Holds server state and session information |

## Session Management

The SHTTP transport implements a session-based model to maintain state across multiple requests.

### Session Lifecycle

```mermaid
stateDiagram-v2
    [*] --> NoSession: No Session ID Header
    NoSession --> Active: POST /mcp
    Active --> Active: Subsequent Requests
    Active --> Closed: Transport Close Event
    Closed --> [*]
```

### Session Storage

Sessions are stored in an in-memory `Map` structure:

```typescript
const streamableSessions = new Map<string, StreamableHTTPServerTransport>();
```

| Operation | Method | Description |
|-----------|--------|-------------|
| Create | POST without session ID | Generates new UUID, creates transport |
| Retrieve | Request with session ID | Looks up existing transport from Map |
| Delete | Transport close event | Removes session from Map on `onclose` |

Source: [src/transport.ts:20-45](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts)

## Configuration

### Server Transport Options

The transport layer is configured through the `server` configuration object:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `port` | `number` | `undefined` | Port for SHTTP transport. When `undefined`, uses STDIO |
| `host` | `string` | `"localhost"` | Host interface to bind. Use `"0.0.0.0"` for external access |

Source: [config.d.ts:40-55](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)

### Configuration Resolution

The configuration is resolved in order of precedence:

1. **Default values** - Built-in defaults for all options
2. **Environment variables** - `BROWSERBASE_API_KEY`, `BROWSERBASE_PROJECT_ID`, etc.
3. **CLI options** - Command-line arguments passed at runtime

```mermaid
graph LR
    A[CLI Options] --> B[mergeConfig]
    C[Default Config] --> B
    B --> D[normalizeVerifiedConfig]
    D --> E[Final Config]
```

Source: [src/config.ts:30-55](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

### Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `BROWSERBASE_API_KEY` | Yes | Browserbase authentication key |
| `BROWSERBASE_PROJECT_ID` | Yes | Browserbase project identifier |
| `GEMINI_API_KEY` | For default model | Google AI API key (falls back to `GOOGLE_API_KEY`) |

Source: [src/config.ts:55-60](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

## Request Handling

### HTTP Request Flow

```
┌─────────────────────────────────────────────────────────────┐
│                    Incoming HTTP Request                     │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    URL Validation                            │
│  Check: url.pathname.startsWith("/mcp")                     │
└─────────────────────────────────────────────────────────────┘
                              │
              ┌───────────────┴───────────────┐
              │                               │
              ▼                               ▼
        [Invalid URL]                    [Valid /mcp]
        Return 400                       Continue
              │                               │
              ▼                               ▼
        ┌─────────┐              ┌─────────────────────────┐
        │  End    │              │ Session Check           │
        └─────────┘              │ mcp-session-id header?  │
                                 └─────────────────────────┘
                                              │
                              ┌───────────────┴───────────────┐
                              │                               │
                              ▼                               ▼
                    [Session Found]                  [No Session]
                    Route to transport               Create new transport
                    from Map                         Generate UUID
                              │                               │
                              │                      ┌────────┴────────┐
                              │                      │ Create Server  │
                              │                      │ Connect        │
                              │                      └────────────────┘
                              ▼                               │
                    ┌─────────────────┐                       │
                    │ Handle Request  │◄──────────────────────┘
                    │ via Transport   │
                    └─────────────────┘
```

Source: [src/transport.ts:35-55](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts)

## Security Considerations

The transport layer implements several security measures:

| Aspect | Implementation | Notes |
|--------|---------------|-------|
| **Default Binding** | `localhost` | Only accepts local connections by default |
| **External Access** | Explicit `host: "0.0.0.0"` | Requires deliberate configuration |
| **Session Isolation** | Session ID validation | Requests without valid session ID rejected |
| **Session Cleanup** | `onclose` handler | Automatic removal of closed sessions |

Source: [config.d.ts:47-55](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)

### Security Recommendations

1. **Development**: Use default `localhost` binding
2. **Production**: If external access required:
   - Use firewall rules to restrict access
   - Consider VPN or reverse proxy
   - Implement authentication at the application layer
3. **Hosted Service**: Use Browserbase hosted MCP at `https://mcp.browserbase.com/mcp` for managed security

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

## Usage Examples

### STDIO Configuration (Self-Hosted)

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "node",
      "args": ["/path/to/mcp-server-browserbase/cli.js"],
      "env": {
        "BROWSERBASE_API_KEY": "your-api-key",
        "BROWSERBASE_PROJECT_ID": "your-project-id",
        "GEMINI_API_KEY": "your-gemini-key"
      }
    }
  }
}
```

### SHTTP Configuration (Hosted)

```json
{
  "mcpServers": {
    "browserbase": {
      "type": "http",
      "url": "https://mcp.browserbase.com/mcp"
    }
  }
}
```

### Docker with SHTTP

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "-e",
        "BROWSERBASE_API_KEY",
        "-e",
        "BROWSERBASE_PROJECT_ID",
        "-e",
        "GEMINI_API_KEY",
        "mcp-browserbase"
      ]
    }
  }
}
```

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

## CLI Options

The transport layer can be configured via command-line arguments:

| Flag | Description | Default |
|------|-------------|---------|
| `--browserbaseApiKey <key>` | Browserbase API Key | Environment variable |
| `--browserbaseProjectId <id>` | Browserbase Project ID | Environment variable |
| `--proxies` | Enable Browserbase proxies | `false` |
| `--verified` | Use Verified Identity | `false` |
| `--port <port>` | SHTTP server port | STDIO if unset |
| `--host <host>` | SHTTP bind address | `localhost` |
| `--browserWidth <px>` | Viewport width | `1024` |
| `--browserHeight <px>` | Viewport height | `768` |
| `--modelName <model>` | Stagehand model | `google/gemini-2.5-flash-lite` |
| `--modelApiKey <key>` | Custom model API key | Required for custom models |
| `--experimental` | Enable experimental features | `false` |

Source: [src/config.ts:15-30](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

## Error Handling

The transport layer implements robust error handling:

| Error Scenario | Handling | Response |
|----------------|----------|----------|
| Missing URL | Return 400 | `"Bad request: missing URL"` |
| Session not found | Return 404 | `"Session not found"` |
| Invalid request method | Return 400 | `"Invalid request"` |
| Tool execution failure | Log to stderr, throw MCP error | Formatted error message |

Source: [src/transport.ts:20-35](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts)

Error responses are logged with ISO timestamps for debugging:

```typescript
process.stderr.write(
  `[MCP Error] ${new Date().toISOString()} Error running tool ${tool.schema.name}: ${errorMessage}\n`,
);
```

Source: [src/index.ts:120-125](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)

## Dependencies

The transport layer relies on the following key dependencies:

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | `^1.13.1` | MCP protocol implementation, transport abstractions |
| `@browserbasehq/stagehand` | `^3.3.0` | Browser automation capabilities |
| `http` | Node.js built-in | HTTP server for SHTTP transport |
| `crypto` | Node.js built-in | UUID generation for session IDs |

Source: [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

---

<a id='mcp-tools'></a>

## MCP Tools Reference

### Related Pages

Related topics: [Session Management](#session-management), [System Architecture Overview](#architecture-overview)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/tools/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)
- [src/tools/navigate.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/navigate.ts)
- [src/tools/act.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/act.ts)
- [src/tools/observe.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/observe.ts)
- [src/tools/extract.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/extract.ts)
- [src/tools/session.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/session.ts)
- [src/tools/tool.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/tool.ts)
</details>

# MCP Tools Reference

This page documents all available MCP (Model Context Protocol) tools provided by the Browserbase MCP Server for AI-powered web browser automation.

## Overview

The Browserbase MCP Server exposes a set of tools that enable Large Language Models to interact with web pages through natural language commands. These tools wrap the Stagehand browser automation library and provide capabilities for session management, navigation, interaction, observation, and data extraction.

Source: [src/tools/index.ts:1-18](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)

## Architecture

The tools module follows a modular architecture where each tool is defined as an independent module with a consistent schema and handler structure.

```mermaid
graph TD
    A[MCP Server] --> B[TOOLS Array]
    B --> C[Session Tools]
    B --> D[navigateTool]
    B --> E[actTool]
    B --> F[observeTool]
    B --> G[extractTool]
    
    C --> H[start]
    C --> I[end]
    
    J[Context] --> K[SessionManager]
    K --> L[Stagehand Instances]
```

All tools are exported as a unified array that matches the hosted MCP server at `mcp.browserbase.com`. Source: [src/tools/index.ts:13-17](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)

## Tool Registration

Tools are registered with the MCP server using the SDK's `server.tool()` method. Each tool requires a schema defining its name, description, and input schema, along with an async handler function.

Source: [src/index.ts:42-63](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)

```mermaid
sequenceDiagram
    participant MCP as MCP Server
    participant Tool as Tool Handler
    participant Context as Context
    participant Stagehand as Stagehand
    
    MCP->>Tool: Execute Tool with params
    Tool->>Context: context.run(tool, params)
    Context->>Stagehand: Invoke Stagehand method
    Stagehand-->>Context: Return result
    Context-->>MCP: CallToolResult
```

## Tool Schema Structure

All tools implement a common interface defined in the `MCPTool` type. Each tool consists of a schema and a handler function.

Source: [src/tools/tool.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/tool.ts)

| Property | Type | Description |
|----------|------|-------------|
| `schema.name` | `string` | Unique identifier for the tool |
| `schema.description` | `string` | Human-readable description of tool functionality |
| `schema.inputSchema` | `ZodObject` | Validation schema for tool parameters |

## Available Tools

### Tool Categories

| Category | Tools | Purpose |
|----------|-------|---------|
| Session Management | `start`, `end` | Create and terminate browser sessions |
| Navigation | `navigate` | Navigate to URLs |
| Interaction | `act` | Perform actions on page elements |
| Observation | `observe` | Identify actionable elements |
| Extraction | `extract` | Extract data from pages |

### Complete Tool List

Source: [src/tools/index.ts:13-17](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)

```typescript
export const TOOLS = [
  ...sessionTools,    // start, end
  navigateTool,       // navigate
  actTool,            // act
  observeTool,        // observe
  extractTool,        // extract
];
```

## Session Management Tools

Session tools manage the lifecycle of Browserbase browser sessions. Each session maintains its own Stagehand instance for isolated browser automation.

Source: [src/tools/session.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/session.ts)

```mermaid
graph LR
    A[start] -->|Creates| B[SessionManager]
    B -->|Manages| C[Stagehand Instance]
    C --> D[Browser Tab]
    E[end] -->|Closes| B
```

### `start` Tool

Creates a new browser session and initializes a Stagehand instance. A session must be started before any other tools can be used.

**Renamed in v3.0.0** - Previously named `browserbase_session_create`.

Source: [src/tools/session.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/session.ts)

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `proxy` | `boolean` | No | Enable Browserbase proxies |
| `verified` | `boolean` | No | Use Browserbase Verified Identity (Scale Plan only) |
| `modelName` | `string` | No | Custom LLM model name |
| `modelApiKey` | `string` | No | API key for custom model |
| `keepAlive` | `boolean` | No | Keep session alive after operations |
| `contextId` | `string` | No | Optional context identifier |

### `end` Tool

Closes the current browser session and releases all associated resources.

**Renamed in v3.0.0** - Previously named `browserbase_session_close`.

Source: [src/tools/session.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/session.ts)

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| No parameters | - | - | Closes the active session |

## Navigation Tool

### `navigate` Tool

Navigates the browser to a specified URL. The tool uses Stagehand's navigation capabilities for reliable page loading.

**Renamed in v3.0.0** - Previously named `browserbase_stagehand_navigate`.

Source: [src/tools/navigate.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/navigate.ts)

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | `string` | Yes | The target URL to navigate to |

**Example usage:**

```json
{
  "name": "navigate",
  "arguments": {
    "url": "https://example.com"
  }
}
```

## Interaction Tool

### `act` Tool

Performs an action on the current page using AI-powered element identification. The model analyzes the page and determines the appropriate element and action to execute.

**Renamed in v3.0.0** - Previously named `browserbase_stagehand_act`.

**Breaking change in v3.0.0** - The `variables` parameter has been removed.

Source: [src/tools/act.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/act.ts)

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `action` | `string` | Yes | Natural language description of the action to perform |

**Supported action types:**

- Click on elements (buttons, links, etc.)
- Fill form fields (text inputs, textareas)
- Select dropdown options
- Check/uncheck checkboxes
- Submit forms

**Example usage:**

```json
{
  "name": "act",
  "arguments": {
    "action": "Click the 'Sign In' button"
  }
}
```

## Observation Tool

### `observe` Tool

Observes the current page and identifies all actionable elements. Returns a list of elements that can be interacted with, categorized by type.

**Renamed in v3.0.0** - Previously named `browserbase_stagehand_observe`.

Source: [src/tools/observe.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/observe.ts)

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `instruction` | `string` | Yes | Description of what elements to look for |

**Example usage:**

```json
{
  "name": "observe",
  "arguments": {
    "instruction": "Find all clickable buttons on the page"
  }
}
```

**Return value structure:**

The tool returns an array of observed elements with their properties:

```typescript
interface ObservedElement {
  type: "button" | "link" | "input" | "select" | ...;
  description: string;
  selector?: string;
  attributes?: Record<string, string>;
}
```

## Data Extraction Tool

### `extract` Tool

Extracts structured data from the current page based on natural language instructions. Uses AI to understand the page content and return relevant information.

**Renamed in v3.0.0** - Previously named `browserbase_stagehand_extract`.

**Breaking change in v3.0.0** - The `instruction` parameter is now optional.

Source: [src/tools/extract.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/extract.ts)

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `instruction` | `string` | No | Natural language description of what data to extract |

When `instruction` is omitted, the tool extracts all meaningful content from the page.

**Example usage:**

```json
{
  "name": "extract",
  "arguments": {
    "instruction": "Extract all product names and prices"
  }
}
```

## Tool Handler Implementation

Each tool follows a consistent implementation pattern using the tool factory function.

Source: [src/tools/tool.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/tool.ts)

```typescript
export interface MCPTool {
  schema: {
    name: string;
    description: string;
    inputSchema: z.ZodObject<any>;
  };
  handler: (params: any, context: Context) => Promise<CallToolResult>;
}
```

### Handler Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `params` | `object` | Validated input parameters matching the tool's inputSchema |
| `context` | `Context` | Server context providing access to SessionManager and Stagehand instances |

## Error Handling

All tool handlers are wrapped in try-catch blocks at the MCP server level. Errors are logged with timestamps and re-thrown with descriptive messages.

Source: [src/index.ts:47-59](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)

```typescript
try {
  const result = await context.run(tool, params);
  return result;
} catch (error) {
  const errorMessage = error instanceof Error ? error.message : String(error);
  process.stderr.write(
    `[MCP Error] ${new Date().toISOString()} Error running tool ${tool.schema.name}: ${errorMessage}\n`,
  );
  throw new Error(
    `Failed to run tool '${tool.schema.name}': ${errorMessage}`,
  );
}
```

## Session Management Integration

Tools interact with the SessionManager through the Context class, which provides synchronized access to session state.

Source: [src/context.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)

```mermaid
graph TD
    A[Tool Handler] --> B[Context.run]
    B --> C[currentSessionId getter]
    C --> D[SessionManager.getActiveSessionId]
    D --> E[Returns active session]
    B --> F[SessionManager.getSession]
    F --> G[Stagehand instance]
```

The `currentSessionId` property is a getter that delegates to SessionManager to ensure synchronization between Context and SessionManager session tracking.

Source: [src/context.ts:18-20](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)

## Configuration Options

The following configuration options affect tool behavior:

| Option | Tool Affected | Description |
|--------|---------------|-------------|
| `proxies` | `start` | Enable Browserbase proxies for the session |
| `verified` | `start` | Enable Verified Identity (Scale Plan) |
| `modelName` | `start` | Specify custom LLM model |
| `modelApiKey` | `start` | API key for custom model |
| `keepAlive` | `start` | Prevent session timeout |
| `browserWidth` | `start` | Browser viewport width (default: 1024) |
| `browserHeight` | `start` | Browser viewport height (default: 768) |

## Tool Execution Flow

```mermaid
sequenceDiagram
    participant Client as MCP Client
    participant Server as MCP Server
    participant Handler as Tool Handler
    participant Context as Context
    participant Session as SessionManager
    participant Stagehand as Stagehand
    
    Client->>Server: tool/CallRequest
    Server->>Handler: Execute with params
    Handler->>Context: context.run(tool, params)
    Context->>Session: getSession(currentSessionId)
    Session->>Stagehand: Get/initialize instance
    Stagehand-->>Context: Stagehand ready
    Context->>Stagehand: Execute operation
    Stagehand-->>Handler: Result
    Handler-->>Server: CallToolResult
    Server-->>Client: Response
```

## Changelog

### v3.0.0 Breaking Changes

Source: [CHANGELOG.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/CHANGELOG.md)

| Change | Previous | Current |
|--------|----------|---------|
| `browserbase_session_create` | `start` | Tool renamed |
| `browserbase_session_close` | `end` | Tool renamed |
| `browserbase_stagehand_navigate` | `navigate` | Tool renamed |
| `browserbase_stagehand_act` | `act` | Tool renamed |
| `browserbase_stagehand_observe` | `observe` | Tool renamed |
| `browserbase_stagehand_extract` | `extract` | Tool renamed |
| `act` parameters | `variables` accepted | Removed |
| `extract` parameters | `instruction` required | Now optional |
| Default model | `gemini-2.0-flash` | `google/gemini-2.5-flash-lite` |

### Removed Tools

The following tools were removed in v3.0.0:

- `browserbase_screenshot` - Screenshot functionality consolidated elsewhere
- `browserbase_stagehand_get_url` - URL accessible via session state
- `browserbase_stagehand_agent` - Agent capabilities restructured

## See Also

- [Browserbase MCP Documentation](https://docs.browserbase.com/integrations/mcp/introduction)
- [Stagehand Documentation](https://docs.stagehand.dev/)
- [MCP Specification](https://spec.modelcontextprotocol.io/)

---

<a id='session-management'></a>

## Session Management

### Related Pages

Related topics: [MCP Tools Reference](#mcp-tools), [Configuration Options](#configuration-options)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/sessionManager.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)
- [src/context.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)
- [src/tools/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)
- [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)
- [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)
</details>

# Session Management

## Overview

Session Management in the MCP Server for Browserbase is the core system responsible for creating, tracking, maintaining, and disposing of browser automation sessions. Each session represents an isolated browser instance powered by Stagehand, enabling AI-driven web automation operations.

The session management system serves as the backbone for all browser-based operations, providing:

- **Isolation**: Multiple concurrent browser sessions with independent state
- **Lifecycle Management**: Automated creation, validation, cleanup, and recovery
- **Concurrency Control**: Mutex patterns to prevent race conditions during session creation
- **Resource Optimization**: Session reuse and graceful cleanup to minimize resource consumption

Source: [src/sessionManager.ts:1-50](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

## Architecture

### High-Level Components

The session management architecture consists of three primary layers working in coordination:

```mermaid
graph TD
    subgraph "MCP Layer"
        MCP["MCP Server"]
        Tools["Session Tools<br/>(start, end)"]
    end
    
    subgraph "Context Layer"
        Context["Context<br/>(src/context.ts)"]
        SessionId["currentSessionId<br/>(getter)"]
    end
    
    subgraph "Session Management Layer"
        SM["SessionManager<br/>(src/sessionManager.ts)"]
        Browsers["Map&lt;string, BrowserSession&gt;"]
        Active["activeSessionId"]
        Default["defaultBrowserSession"]
        Mutex["defaultSessionCreationPromise"]
        Cleanup["cleaningUpSessions"]
    end
    
    subgraph "Stagehand Layer"
        Stagehand["Stagehand Instance"]
        Browser["Browser Context"]
        Page["Page"]
    end
    
    MCP --> Tools
    Tools --> Context
    Context --> SM
    SM --> Stagehand
    Stagehand --> Browser
    Browser --> Page
    
    Context -.-> SessionId
    SM -.-> Browsers
    SM -.-> Active
    SM -.-> Default
    SM -.-> Mutex
    SM -.-> Cleanup
```

### Class Hierarchy

| Layer | Class/Module | Responsibility |
|-------|--------------|----------------|
| MCP | `TOOLS` array | Exposes session tools via MCP protocol |
| Context | `Context` | Central controller, holds SessionManager reference |
| Session | `SessionManager` | Core session lifecycle management |
| Stagehand | `createStagehandInstance()` | Browser automation driver |

Source: [src/context.ts:1-30](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)

## Data Model

### BrowserSession Interface

```typescript
interface BrowserSession {
  page: Page;                    // Playwright Page instance
  sessionId: string;             // Browserbase session identifier
  stagehand: Stagehand;         // Stagehand automation instance
}
```

Source: [src/sessionManager.ts:120-125](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

### SessionManager State

The `SessionManager` class maintains the following internal state:

| Property | Type | Purpose |
|----------|------|---------|
| `browsers` | `Map<string, BrowserSession>` | Stores all active browser sessions |
| `defaultBrowserSession` | `BrowserSession \| null` | Reference to the default session |
| `defaultSessionId` | `string` | Unique identifier for the default session |
| `activeSessionId` | `string` | Currently active session ID |
| `defaultSessionCreationPromise` | `Promise<BrowserSession> \| null` | Mutex for concurrent creation attempts |
| `cleaningUpSessions` | `Set<string>` | Tracks sessions currently being cleaned |

Source: [src/sessionManager.ts:56-73](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

## Session Lifecycle

### Lifecycle States

```mermaid
stateDiagram-v2
    [*] --> Created: createNewBrowserSession()
    Created --> Active: setActiveSessionId()
    Active --> Validating: getSession()
    Validating --> Active: Session valid
    Validating --> Recreating: Session stale
    Recreating --> Active: Recreated successfully
    Recreating --> Error: Creation failed
    Active --> CleaningUp: cleanupSession()
    CleaningUp --> [*]: Cleanup complete
    Active --> [*]: closeAllSessions()
```

### Session Creation Flow

```mermaid
graph TD
    Start["Request Session"] --> CheckDefault{"Is Default<br/>Session?"}
    
    CheckDefault -->|Yes| CheckInProgress{"Creation<br/>In Progress?"}
    CheckDefault -->|No| GetFromMap["Get from<br/>browsers Map"]
    
    CheckInProgress -->|Yes| Wait["Wait for<br/>existing promise"]
    CheckInProgress -->|No| CheckExists{"Session<br/>Exists?"}
    
    Wait --> ReturnExisting["Return Promise"]
    CheckExists -->|No| Create["createNewBrowserSession()"]
    CheckExists -->|Yes| Validate["Validate<br/>Session"]
    
    Create --> Stagehand["Create Stagehand<br/>Instance"]
    Stagehand --> Extract["Extract Page &<br/>Session ID"]
    Extract --> Store["Store in Map"]
    Store --> SetActive["Set Active"]
    
    Validate -->|Valid| Return["Return Session"]
    Validate -->|Stale| Remove["Close & Remove"]
    Remove --> Create
```

Source: [src/sessionManager.ts:130-200](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

### Session Validation

Sessions are validated before use by checking page availability:

```typescript
try {
  const pages = sessionObj.stagehand.context.pages();
  if (!pages || pages.length === 0) {
    throw new Error("No pages available");
  }
} catch {
  needsReCreation = true;
}
```

Source: [src/sessionManager.ts:83-91](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

## Core Methods

### Creating Sessions

#### `createNewBrowserSession()`

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `newSessionId` | `string` | Yes | Internal tracking ID |
| `config` | `Config` | Yes | Browserbase configuration |
| `resumeSessionId` | `string` | No | Browserbase session to resume |

**Process:**

1. Validate API key and project ID exist in config
2. Create Stagehand instance with optional resume capability
3. Extract page and Browserbase session ID
4. Store session in browsers Map
5. Update active session ID

```typescript
const stagehand = await createStagehandInstance(
  config,
  {
    ...(resumeSessionId && { browserbaseSessionID: resumeSessionId }),
  },
  newSessionId,
);
```

Source: [src/sessionManager.ts:140-195](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

### Retrieving Sessions

#### `getSession()`

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `sessionId` | `string` | Required | Session identifier to retrieve |
| `config` | `Config` | Required | Configuration object |
| `createIfMissing` | `boolean` | `true` | Auto-create default session if missing |

**Returns:** `BrowserSession | null`

```typescript
async getSession(
  sessionId: string,
  config: Config,
  createIfMissing: boolean = true,
): Promise<BrowserSession | null>
```

Source: [src/sessionManager.ts:240-280](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

#### `ensureDefaultSessionInternal()`

Ensures the default session exists and is valid. Uses a mutex pattern to prevent race conditions when multiple concurrent requests attempt to create the default session simultaneously.

```typescript
if (this.defaultSessionCreationPromise) {
  process.stderr.write(
    `[SessionManager] Default session creation already in progress, waiting...\n`,
  );
  return await this.defaultSessionCreationPromise;
}
```

Source: [src/sessionManager.ts:200-220](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

### Cleanup Operations

#### `closeBrowserGracefully()`

Safely closes a single session with concurrent cleanup protection:

| Parameter | Type | Description |
|-----------|------|-------------|
| `session` | `BrowserSession \| undefined \| null` | Session to close |
| `sessionIdToLog` | `string` | ID for logging purposes |

**Features:**

- Tracks sessions being cleaned in `cleaningUpSessions` Set
- Prevents double-cleanup of the same session
- Always removes from cleanup tracking in `finally` block

```typescript
if (this.cleaningUpSessions.has(sessionIdToLog)) {
  process.stderr.write(
    `[SessionManager] Session ${sessionIdToLog} is already being cleaned up, skipping.\n`,
  );
  return;
}
this.cleaningUpSessions.add(sessionIdToLog);
```

Source: [src/sessionManager.ts:145-180](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

#### `cleanupSession()`

Removes a session and resets state:

```typescript
async cleanupSession(sessionId: string): Promise<void> {
  const session = this.browsers.get(sessionId);
  if (session) {
    await this.closeBrowserGracefully(session, sessionId);
  }
  this.browsers.delete(sessionId);
  
  if (sessionId === this.defaultSessionId) {
    this.defaultBrowserSession = null;
  }
  if (this.activeSessionId === sessionId) {
    this.setActiveSessionId(this.defaultSessionId);
  }
}
```

Source: [src/sessionManager.ts:110-145](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

#### `closeAllSessions()`

Closes all managed sessions in parallel:

```typescript
async closeAllSessions(): Promise<void> {
  const closePromises: Promise<void>[] = [];
  for (const [id, session] of this.browsers.entries()) {
    closePromises.push(this.closeBrowserGracefully(session, id));
  }
  await Promise.all(closePromises);
  this.browsers.clear();
  this.defaultBrowserSession = null;
  this.setActiveSessionId(this.defaultSessionId);
}
```

Source: [src/sessionManager.ts:155-175](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

## Session Tools (MCP Interface)

Session management is exposed to MCP clients through tools defined in `src/tools/session.ts` and registered in the TOOLS array:

| Tool | Description |
|------|-------------|
| `start` | Creates a new browser session |
| `end` | Closes an existing session |

Source: [src/tools/index.ts:1-20](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)

### Tool Exports

```typescript
export const TOOLS = [
  ...sessionTools,
  navigateTool,
  actTool,
  observeTool,
  extractTool,
];

export const sessionManagementTools = sessionTools;
```

Source: [src/tools/index.ts:16-18](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/tools/index.ts)

## Integration with Context

The `Context` class provides the bridge between MCP infrastructure and session management:

```typescript
export class Context {
  public readonly config: Config;
  private server: Server;
  private sessionManager: SessionManager;

  public get currentSessionId(): string {
    return this.sessionManager.getActiveSessionId();
  }

  public async getStagehand(
    sessionId: string = this.currentSessionId,
  ): Promise<Stagehand> {
    const session = await this.sessionManager.getSession(
      sessionId,
      this.config,
    );
    if (!session) {
      throw new Error("Session not found");
    }
    return session.stagehand;
  }
}
```

Source: [src/context.ts:15-45](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/context.ts)

## Concurrency Handling

### Mutex Pattern for Default Session

The default session creation uses a mutex pattern to prevent race conditions:

```mermaid
graph LR
    A["Request 1"] --> M{"In Progress?"}
    B["Request 2"] --> M
    C["Request 3"] --> M
    
    M -->|No| Create["Create Session"]
    M -->|Yes| Wait["Wait on Promise"]
    
    Create --> Store["Store Promise"]
    Store --> Return["Return to Request 1"]
    Wait --> Return
```

**Implementation:**

```typescript
private defaultSessionCreationPromise: Promise<BrowserSession> | null = null;

async ensureDefaultSessionInternal(config: Config): Promise<BrowserSession> {
  if (this.defaultSessionCreationPromise) {
    return await this.defaultSessionCreationPromise;
  }
  
  this.defaultSessionCreationPromise = (async () => {
    try {
      this.defaultBrowserSession = await this.createNewBrowserSession(...);
      return this.defaultBrowserSession;
    } finally {
      this.defaultSessionCreationPromise = null;
    }
  })();
  
  return await this.defaultSessionCreationPromise;
}
```

Source: [src/sessionManager.ts:200-240](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

### Cleanup Tracking

The `cleaningUpSessions` Set prevents concurrent cleanup operations:

```typescript
private cleaningUpSessions: Set<string> = new Set();

async closeBrowserGracefully(...): Promise<void> {
  if (this.cleaningUpSessions.has(sessionIdToLog)) {
    return; // Skip if already being cleaned
  }
  
  this.cleaningUpSessions.add(sessionIdToLog);
  try {
    // Perform cleanup
  } finally {
    this.cleaningUpSessions.delete(sessionIdToLog);
  }
}
```

Source: [src/sessionManager.ts:145-175](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

## Error Handling

### Session Creation Errors

Errors during session creation trigger automatic retry:

```typescript
try {
  this.defaultBrowserSession = await this.createNewBrowserSession(...);
  return this.defaultBrowserSession;
} catch (creationError) {
  process.stderr.write(`[SessionManager] Initial attempt failed...\n`);
  
  // Retry once
  try {
    this.defaultBrowserSession = await this.createNewBrowserSession(...);
    return this.defaultBrowserSession;
  } catch (retryError) {
    throw new Error(`Failed after initial error and retry: ${finalErrorMessage}`);
  }
} finally {
  this.defaultSessionCreationPromise = null;
}
```

Source: [src/sessionManager.ts:225-260](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

### Graceful Degradation

The system logs warnings and continues operation on non-fatal errors:

```typescript
} catch (closeError) {
  process.stderr.write(
    `[SessionManager] WARN - Error closing Stagehand for session ${sessionIdToLog}: ${
      closeError instanceof Error
        ? closeError.message
        : String(closeError)
    }\n`,
  );
}
```

Source: [src/sessionManager.ts:160-170](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

## Session Identification

### ID Generation

Default session IDs follow a structured format:

```typescript
const uniqueId = randomUUID();
this.defaultSessionId = `browserbase_session_${contextId || "default"}_${Date.now()}_${uniqueId}`;
```

Format: `browserbase_session_{contextId}_{timestamp}_{uuid}`

Example: `browserbase_session_default_1699123456789_a1b2c3d4-e5f6-7890-abcd-ef1234567890`

Source: [src/sessionManager.ts:66-70](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

### Active Session Management

The active session can be changed but only to existing sessions (or the default):

```typescript
setActiveSessionId(id: string): void {
  if (this.browsers.has(id)) {
    this.activeSessionId = id;
  } else if (id === this.defaultSessionId) {
    this.activeSessionId = id; // Allow even if not created yet
  } else {
    process.stderr.write(`[SessionManager] WARN - Set active session failed for non-existent ID: ${id}\n`);
  }
}
```

Source: [src/sessionManager.ts:75-90](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/sessionManager.ts)

## Summary

The Session Management system provides a robust foundation for browser automation within the MCP server:

- **Isolation**: Each session maintains independent browser state via Stagehand
- **Reliability**: Automatic validation, recreation, and retry mechanisms
- **Concurrency Safety**: Mutex patterns and cleanup tracking prevent race conditions
- **Resource Management**: Graceful cleanup ensures proper resource disposal
- **Integration**: Seamless connection through the Context layer to MCP tools

---

<a id='configuration-options'></a>

## Configuration Options

### Related Pages

Related topics: [Model Configuration](#model-configuration), [Quick Start Guide](#quickstart)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)
- [src/config.test.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.test.ts)
- [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)
- [src/program.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/program.ts)
- [config.d.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)
</details>

# Configuration Options

The MCP Server Browserbase provides a flexible configuration system that allows operators to customize server behavior through environment variables, command-line arguments, and programmatic configuration. This page documents all available configuration options, their types, default values, and how they are processed at runtime.

## Overview

The configuration system follows a hierarchical merge strategy where defaults are progressively overridden by file-based configuration and finally by CLI options. This approach ensures sensible defaults while maintaining maximum flexibility for different deployment scenarios.

The configuration system is built on three pillars:

- **Zod Schema Validation**: All configuration options are validated using Zod schemas defined in `src/index.ts`
- **Environment Variable Support**: Sensitive values and deployment-specific settings can be injected via environment variables
- **Command-Line Arguments**: Runtime behavior can be modified through CLI flags defined in `src/program.ts`

Source: [src/config.ts:1-15]()

## Configuration Schema

The root configuration interface `Config` defines the complete structure of valid configuration options. All options are type-safe and validated at server startup.

### Core Configuration Interface

```typescript
interface Config {
  browserbaseApiKey: string;
  browserbaseProjectId: string;
  proxies: boolean;
  server: {
    port?: number;
    host?: string;
  };
  viewPort: {
    browserWidth: number;
    browserHeight: number;
  };
  modelName: string;
  modelApiKey?: string;
  verified?: boolean;
  keepAlive?: boolean;
}
```

Source: [config.d.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)

### Zod Schema Definition

The configuration schema provides runtime validation and documentation for MCP clients:

```typescript
export const configSchema = z.object({
  browserbaseApiKey: z.string().describe("The Browserbase API Key to use"),
  browserbaseProjectId: z.string().describe("The Browserbase Project ID to use"),
  proxies: z.boolean().optional().describe("Whether or not to use Browserbase proxies"),
  verified: z.boolean().optional().describe("Use Browserbase Verified Identity"),
  advancedStealth: z.boolean().optional().describe("Deprecated alias for verified"),
  keepAlive: z.boolean().optional().describe("Whether or not to keep the Browserbase session alive"),
  // Additional fields...
});
```

Source: [src/index.ts:18-45]()

## Command-Line Options

The server accepts the following command-line flags when run directly via Node.js or the CLI entry point:

| Flag | Type | Description | Default |
|------|------|-------------|---------|
| `--browserbaseApiKey` | string | The Browserbase API Key to authenticate with the Browserbase service | _(none)_ |
| `--browserbaseProjectId` | string | The Browserbase Project ID for organizing sessions and billing | _(none)_ |
| `--proxies` | boolean | Enable Browserbase proxy rotation for requests | `false` |
| `--verified` | boolean | Use Browserbase Verified Identity (requires Scale Plan) | `false` |
| `--advancedStealth` | boolean | Deprecated alias for `--verified` | `false` |
| `--contextId` | string | Browserbase context identifier for session continuity | _(none)_ |
| `--persist` | boolean | Persist session data beyond server restart | `false` |
| `--port` | number | HTTP server port for streamable transport | _(none)_ |
| `--host` | string | HTTP server host binding address | _(none)_ |
| `--browserWidth` | number | Viewport width in pixels for browser sessions | `1024` |
| `--browserHeight` | number | Viewport height in pixels for browser sessions | `768` |
| `--modelName` | string | AI model identifier for Stagehand operations | `google/gemini-2.5-flash-lite` |
| `--modelApiKey` | string | API key for the configured AI model | _(none)_ |
| `--keepAlive` | boolean | Maintain browser session after request completion | `false` |
| `--experimental` | boolean | Enable experimental features | `false` |

Source: [src/program.ts:28-46]()

Source: [src/config.ts:7-22]()

## Environment Variables

The configuration system automatically loads values from environment variables when CLI options are not provided:

| Environment Variable | Config Property | Description |
|---------------------|-----------------|-------------|
| `BROWSERBASE_API_KEY` | `browserbaseApiKey` | Authentication token for Browserbase API |
| `BROWSERBASE_PROJECT_ID` | `browserbaseProjectId` | Project identifier for Browserbase resources |
| `GEMINI_API_KEY` | `modelApiKey` | API key for Gemini models (fallback) |
| `GOOGLE_API_KEY` | `modelApiKey` | Alternative API key for Google models |

Environment variables are loaded using the `dotenv` package at application startup:

```typescript
import * as dotenv from "dotenv";
dotenv.config();
```

Source: [src/index.ts:1-2]()

### Environment Variable Resolution Priority

When resolving the model API key, the system checks environment variables in the following order:

1. `process.env.GEMINI_API_KEY`
2. `process.env.GOOGLE_API_KEY`

```typescript
if (!mergedConfig.modelApiKey) {
  mergedConfig.modelApiKey =
    process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
}
```

Source: [src/config.ts:50-53]()

## Default Configuration Values

The server ships with sensible defaults for all optional parameters:

| Property | Default Value | Description |
|----------|---------------|-------------|
| `proxies` | `false` | Proxy rotation disabled by default |
| `server.port` | `undefined` | Auto-assigned by the operating system |
| `server.host` | `undefined` | Bind to all available interfaces |
| `viewPort.browserWidth` | `1024` | Standard desktop viewport width |
| `viewPort.browserHeight` | `768` | Standard desktop viewport height |
| `modelName` | `google/gemini-2.5-flash-lite` | Default model matches hosted MCP service |

Source: [src/config.ts:25-34]()

## Configuration Resolution Flow

The configuration passes through several transformation stages before being used by the server:

```mermaid
graph TD
    A[Default Config] --> B[CLI Options]
    B --> C[configFromCLIOptions]
    C --> D[mergeConfig]
    D --> E[normalizeVerifiedConfig]
    E --> F[normalizeVerifiedConfig with Env Vars]
    F --> G[Internal Config]
    G --> H[Server Initialization]
    
    I[process.env.GEMINI_API_KEY] -.-> F
    J[process.env.GOOGLE_API_KEY] -.-> F
```

### Configuration Processing Pipeline

The `resolveConfig` function orchestrates the complete configuration workflow:

```typescript
export async function resolveConfig(cliOptions: CLIOptions): Promise<Config> {
  const cliConfig = await configFromCLIOptions(cliOptions);
  // Order: Defaults < File Config < CLI Overrides
  const mergedConfig = normalizeVerifiedConfig(
    mergeConfig(defaultConfig, cliConfig),
  );

  // --- Add Browserbase Env Vars ---
  if (!mergedConfig.modelApiKey) {
    mergedConfig.modelApiKey =
      process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
  }
  // ...
}
```

Source: [src/config.ts:37-56]()

## Verified Identity Configuration

The `verified` option enables Browserbase Verified Identity features, which are only available to users on the Browserbase Scale Plan. The system also supports a legacy `advancedStealth` alias for backward compatibility.

### Legacy Alias Handling

```typescript
it("maps the legacy CLI advancedStealth alias to verified", async () => {
  const config = await configFromCLIOptions({ advancedStealth: true });
  expect(config.verified).toBe(true);
});

it("prefers verified when both verified and advancedStealth are set", () => {
  const config = normalizeVerifiedConfig({
    browserbaseApiKey: "test-key",
    browserbaseProjectId: "test-project",
    verified: false,
    advancedStealth: true,
  });
  expect(config.verified).toBe(false);
});
```

Source: [src/config.test.ts:7-22]()

## CLI Options Type Definition

The `CLIOptions` type represents all valid command-line input options:

```typescript
export type CLIOptions = {
  proxies?: boolean;
  verified?: boolean;
  advancedStealth?: boolean;
  contextId?: string;
  persist?: boolean;
  port?: number;
  host?: string;
  browserWidth?: number;
  browserHeight?: number;
  modelName?: string;
  modelApiKey?: string;
  keepAlive?: boolean;
  experimental?: boolean;
};
```

Source: [src/config.ts:7-22]()

## Required Configuration

Certain configuration values must be provided for the server to function:

### Mandatory Fields

| Field | Requirement | Error if Missing |
|-------|-------------|------------------|
| `browserbaseApiKey` | Required | `"browserbaseApiKey is required"` |
| `browserbaseProjectId` | Required | `"browserbaseProjectId is required"` |

The validation is performed in `src/index.ts` before the MCP server is initialized:

```typescript
if (!config.browserbaseApiKey) {
  throw new Error("browserbaseApiKey is required");
}
if (!config.browserbaseProjectId) {
  throw new Error("browserbaseProjectId is required");
}
```

Source: [src/index.ts:93-99]()

## Tool Capability Configuration

Configuration options can be tagged with capability levels for feature gating:

```typescript
export type ToolCapability = "core" | string;
```

This allows future extension of the configuration system to support optional tool sets based on subscription tier or feature flags.

Source: [src/config.ts:3-5]()

## Configuration in MCP Client Setup

When integrating with MCP clients, configuration is passed through the `env` property of the server definition:

### NPM Package Configuration

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["@browserbasehq/mcp"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

### Direct Node.js Installation

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "node",
      "args": ["/path/to/mcp-server-browserbase/cli.js"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

### Docker Container Configuration

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "-e",
        "BROWSERBASE_API_KEY",
        "-e",
        "BROWSERBASE_PROJECT_ID",
        "-e",
        "GEMINI_API_KEY",
        "mcp-browserbase"
      ],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

## Transport Configuration

The server supports multiple transport mechanisms, each with its own configuration requirements:

| Transport | Configuration Method | Notes |
|-----------|---------------------|-------|
| STDIO | Environment variables or CLI flags | Default for local installations |
| Streamable HTTP | Port/host CLI flags | Configured via `--port` and `--host` |
| SHTTP (Hosted) | URL configuration only | Uses hosted service at `mcp.browserbase.com` |

Source: [src/transport.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/transport.ts)

---

<a id='model-configuration'></a>

## Model Configuration

### Related Pages

Related topics: [Configuration Options](#configuration-options), [System Architecture Overview](#architecture-overview)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)
- [src/program.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/program.ts)
- [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)
- [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)
- [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)
</details>

# Model Configuration

The Model Configuration system in mcp-server-browserbase enables users to customize the AI model used for browser automation tasks powered by Stagehand. This flexibility allows integration with different LLM providers while maintaining a consistent interface for the MCP server.

## Overview

The MCP server leverages [Stagehand](https://www.stagehand.dev) for AI-powered web browser automation. Stagehand uses a default model of `google/gemini-2.5-flash-lite`, which provides optimal performance for web interaction tasks. The Model Configuration system allows users to override this default with supported alternative models from providers like Anthropic, OpenAI, or other compatible LLM services.

| Property | Type | Default Value | Description |
|----------|------|---------------|-------------|
| `modelName` | string | `google/gemini-2.5-flash-lite` | The model identifier for Stagehand |
| `modelApiKey` | string | Environment variable | API key for the custom model provider |

Source: [src/config.ts:26-27](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts#L26-L27)

## Configuration Architecture

### Configuration Resolution Order

The system employs a layered configuration strategy where settings are merged in a specific priority order:

```mermaid
graph TD
    A[Default Configuration] --> B[File Configuration]
    B --> C[CLI Options]
    C --> D[Environment Variables]
    D --> E[Final Merged Config]
    
    F[modelApiKey Override] --> |"if not set"| D
    G[GEMINI_API_KEY or GOOGLE_API_KEY] --> F
```

The resolution order from lowest to highest priority is:

1. **Default Configuration** - Hardcoded defaults in `src/config.ts`
2. **CLI Options** - Command-line arguments provided at runtime
3. **Environment Variables** - Used as fallback for `modelApiKey`

Source: [src/config.ts:29-43](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts#L29-L43)

### Configuration Schema

The server uses Zod for runtime validation of the configuration object:

```typescript
export const configSchema = z.object({
  browserbaseApiKey: z.string().describe("The Browserbase API Key to use"),
  browserbaseProjectId: z.string().describe("The Browserbase Project ID to use"),
  modelName: z.string().optional(),
  modelApiKey: z.string().optional(),
  // ... other options
});
```

Source: [src/index.ts:28-49](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts#L28-L49)

## CLI Options

### Available Flags

| Flag | Type | Description | Required |
|------|------|-------------|----------|
| `--modelName <model>` | string | Model identifier (e.g., `anthropic/claude-sonnet-4.5`) | No |
| `--modelApiKey <key>` | string | API key for the custom model provider | Conditional |

The `--modelName` and `--modelApiKey` flags are exposed through Commander.js:

```typescript
.option("--modelName <modelName>", "The model to use for Stagehand")
.option("--modelApiKey <modelApiKey>", "API key for the model provider")
```

Source: [src/program.ts:45-46](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/program.ts#L45-L46)

### CLI Options Type Definition

```typescript
export type CLIOptions = {
  modelName?: string;
  modelApiKey?: string;
  // ... other options
};
```

Source: [src/config.ts:13-24](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts#L13-L24)

## Environment Variable Handling

The `modelApiKey` can be automatically populated from environment variables when not explicitly provided:

```typescript
if (!mergedConfig.modelApiKey) {
  mergedConfig.modelApiKey =
    process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
}
```

This allows users to set credentials once in their environment rather than repeatedly on the command line.

Source: [src/config.ts:38-41](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts#L38-L41)

## Supported Models

The server uses Stagehand for browser automation, and the model must be supported by Stagehand. Refer to the [Stagehand documentation](https://docs.stagehand.dev/examples/custom_llms#supported-llms) for the complete list of supported models.

### Default Model

The default model is `google/gemini-2.5-flash-lite`, chosen for its performance in web interaction tasks:

```typescript
const defaultConfig: Config = {
  // ...
  modelName: "google/gemini-2.5-flash-lite", // Default Model — matches hosted MCP
};
```

Source: [src/config.ts:26](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts#L26)

### Popular Alternative Models

| Provider | Model Identifier | Use Case |
|----------|------------------|----------|
| Anthropic | `anthropic/claude-sonnet-4.5` | High-quality reasoning |
| Anthropic | `anthropic/claude-opus-4` | Maximum capability |
| OpenAI | `openai/gpt-4o` | Vision and speed |
| Google | `google/gemini-2.0-flash` | Balanced performance |

## Configuration Examples

### Using Default Model

When using the default Gemini model, provide the API key via environment variable:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "node",
      "args": ["/path/to/cli.js"],
      "env": {
        "BROWSERBASE_API_KEY": "your-api-key",
        "BROWSERBASE_PROJECT_ID": "your-project-id",
        "GEMINI_API_KEY": "your-gemini-key"
      }
    }
  }
}
```

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### Using Custom Model

To use a custom model like Claude:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": [
        "@browserbasehq/mcp",
        "--modelName",
        "anthropic/claude-sonnet-4.5",
        "--modelApiKey",
        "your-anthropic-api-key"
      ],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": ""
      }
    }
  }
}
```

Source: [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### NPM Installation with Custom Model

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": [
        "@browserbasehq/mcp",
        "--modelName",
        "anthropic/claude-sonnet-4.5",
        "--modelApiKey",
        "sk-ant-..."
      ],
      "env": {
        "BROWSERBASE_API_KEY": "bb-...",
        "BROWSERBASE_PROJECT_ID": "..."
      }
    }
  }
}
```

### Docker Configuration

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "-e",
        "BROWSERBASE_API_KEY",
        "-e",
        "BROWSERBASE_PROJECT_ID",
        "-e",
        "MODEL_NAME",
        "-e",
        "MODEL_API_KEY",
        "mcp-browserbase"
      ],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "MODEL_NAME": "anthropic/claude-sonnet-4.5",
        "MODEL_API_KEY": ""
      }
    }
  }
}
```

## Requirements for Custom Models

When using a custom model (non-default), you **must** provide your own API key for that model provider using the `--modelApiKey` flag. This ensures authentication with the external LLM service.

| Requirement | Reason |
|-------------|--------|
| Valid `--modelName` | Must be supported by Stagehand |
| Valid `--modelApiKey` | Required for authentication with external providers |
| Sufficient quota | Check your LLM provider's rate limits |

## Configuration Flow Diagram

```mermaid
sequenceDiagram
    participant User
    participant CLI as Command Line
    participant Config as Config Module
    participant Stagehand
    
    User->>CLI: Start server with options
    CLI->>Config: Parse CLI options
    Config->>Config: Load default config
    Config->>Config: Merge CLI options
    Config->>Config: Check env vars for modelApiKey
    Config->>Config: Return resolved config
    CLI->>Stagehand: Initialize with config
    Stagehand->>User: Server ready with model
```

## Related Dependencies

The model configuration system depends on the following key packages:

| Package | Version | Purpose |
|---------|---------|---------|
| `@browserbasehq/stagehand` | ^3.3.0 | Browser automation with AI |
| `@modelcontextprotocol/sdk` | ^1.13.1 | MCP server framework |
| `commander` | ^14.0.0 | CLI argument parsing |
| `zod` | ^3.25.67 | Schema validation |

Source: [package.json:40-45](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json#L40-L45)

## Best Practices

1. **Environment Variables for Secrets**: Store API keys in environment variables rather than command-line arguments to avoid exposing sensitive data in process listings.

2. **Model Selection**: Choose models based on your use case—`gemini-2.5-flash-lite` for cost efficiency, larger models like Claude Opus for complex reasoning tasks.

3. **Validation**: The Zod schema validates configuration at runtime, ensuring required fields are present before the server starts.

4. **Compatibility**: Always verify your chosen model is supported by Stagehand before configuration.

---

<a id='deployment-methods'></a>

## Deployment Methods

### Related Pages

Related topics: [Quick Start Guide](#quickstart), [Transport Layer](#transport-layer)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)
- [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)
- [src/program.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/program.ts)
- [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)
- [config.d.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)
- [src/index.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/index.ts)
</details>

# Deployment Methods

The Browserbase MCP Server supports multiple deployment approaches to accommodate different infrastructure requirements and use cases. This document covers all supported methods for deploying the MCP server, including local installations, containerized deployments, and hosted alternatives.

## Overview

The MCP server can be deployed in three primary ways:

1. **Direct Installation** - Clone the repository and run locally with Node.js
2. **Docker Container** - Run the server in an isolated container
3. **NPM Package** - Use the pre-built `@browserbasehq/mcp` package via npx

Additionally, the server supports two transport mechanisms for communication:

- **STDIO** - Standard input/output communication for local CLI integrations
- **SHTTP** - HTTP-based transport for networked or hosted deployments

Source: [README.md:1-50](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

## Deployment Architecture

```mermaid
graph TD
    A[Client MCP Config] --> B{Transport Type}
    B -->|STDIO| C[Direct Installation / NPM]
    B -->|SHTTP| D[Hosted Server / Self-Hosted HTTP]
    
    C --> E[Node.js Runtime]
    D --> F[mcp.browserbase.com]
    D --> G[Self-Hosted Docker/Node]
    
    E --> H[Browserbase Cloud]
    F --> H
    G --> H
    
    H --> I[Stagehand]
    I --> J[Browser Automation]
```

## Method 1: Direct Installation

Direct installation provides full control over the server and is suitable for development environments or custom deployments.

### Prerequisites

- Node.js 18+ (LTS recommended)
- npm or pnpm package manager
- Valid Browserbase API credentials

### Installation Steps

```bash
git clone https://github.com/browserbase/mcp-server-browserbase.git
cd mcp-server-browserbase
npm install && npm run build
```

Source: [README.md:1-10](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### Project Structure

The built artifacts are generated in the `dist/` directory with the following structure:

| File | Purpose |
|------|---------|
| `cli.js` | Main CLI entry point |
| `index.js` | Module entry point for programmatic use |
| `config.d.ts` | TypeScript type definitions |

Source: [package.json:11-17](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

### Available Build Scripts

| Script | Command | Description |
|--------|---------|-------------|
| `build` | `tsc && shx chmod +x dist/*.js` | Compiles TypeScript and sets executable permissions |
| `watch` | `tsc --watch` | Watch mode for development |
| `test` | `vitest run` | Run test suite |
| `inspector` | `npx @modelcontextprotocol/inspector` | MCP protocol inspector |

Source: [package.json:22-30](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

## Method 2: Docker Deployment

Docker deployment provides an isolated, reproducible environment that includes all dependencies.

### Building the Docker Image

```bash
git clone https://github.com/browserbase/mcp-server-browserbase.git
cd mcp-server-browserbase
docker build -t mcp-browserbase .
```

### Running the Container

The Docker image exposes the server with environment variable support for configuration:

```bash
docker run --rm -i \
  -e BROWSERBASE_API_KEY \
  -e BROWSERBASE_PROJECT_ID \
  -e GEMINI_API_KEY \
  mcp-browserbase
```

Source: [README.md:10-25](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### Docker Configuration Benefits

- **Isolation**: Runs independently of host system dependencies
- **Consistency**: Identical behavior across different environments
- **Security**: Sandboxed execution environment
- **Portability**: Easy to deploy to any container runtime

## Method 3: NPM Package (npx)

The pre-built package provides the fastest path to deployment without manual cloning or building.

### Quick Start

```bash
npx @browserbasehq/mcp
```

### Configuration in MCP Client

Add the following to your MCP configuration file:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["@browserbasehq/mcp"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

Source: [README.md:60-75](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### Package Metadata

| Property | Value |
|----------|-------|
| Package Name | `@browserbasehq/mcp` |
| Version | 3.0.0 |
| License | Apache-2.0 |
| Entry Point | `./cli.js` |
| Module Entry | `./src/index.ts` |

Source: [package.json:1-12](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

## Transport Methods

The MCP server supports two transport protocols for client communication.

### STDIO Transport

STDIO is the default transport when no HTTP configuration is specified. It uses standard input/output streams for communication.

```mermaid
graph LR
    A[MCP Client] -->|stdio| B[Browserbase MCP Server]
    B -->|stdout| A
```

#### Configuration

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["@browserbasehq/mcp"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

Source: [README.md:60-72](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### SHTTP Transport

SHTTP (Secure HTTP) enables networked deployments and is the recommended transport for hosted deployments.

#### Hosted Server (Recommended)

Use the Browserbase hosted MCP server for the simplest setup:

```json
{
  "mcpServers": {
    "browserbase": {
      "type": "http",
      "url": "https://mcp.browserbase.com/mcp"
    }
  }
}
```

#### Self-Hosted HTTP

For self-hosted HTTP transport, specify port and host in the CLI:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "node",
      "args": ["/path/to/mcp-server-browserbase/cli.js"],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": "",
        "GEMINI_API_KEY": ""
      }
    }
  }
}
```

Source: [README.md:30-55](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

#### Remote Access via mcp-remote

Clients without native SHTTP support can use the `mcp-remote` tool:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["mcp-remote", "https://mcp.browserbase.com/mcp"]
    }
  }
}
```

## Command-Line Options

The server accepts the following CLI flags for configuration:

| Flag | Description | Default |
|------|-------------|---------|
| `--proxies` | Enable Browserbase proxies for the session | `false` |
| `--verified` | Enable Browserbase Verified Identity (Scale Plan only) | `false` |
| `--advancedStealth` | Deprecated alias for `--verified` | `false` |
| `--keepAlive` | Enable Browserbase Keep Alive Session | `false` |
| `--contextId <id>` | Specify a Browserbase Context ID to use | _(none)_ |
| `--persist` | Whether to persist the Browserbase context | `true` |
| `--port <port>` | Port for HTTP/SHTTP transport | _(stdio)_ |
| `--host <host>` | Host to bind server to | `localhost` |
| `--browserWidth <width>` | Browser viewport width | `1024` |
| `--browserHeight <height>` | Browser viewport height | `768` |
| `--modelName <model>` | Stagehand model name | `google/gemini-2.5-flash-lite` |
| `--modelApiKey <key>` | API key for custom model provider | _(none)_ |
| `--experimental` | Enable experimental features | `false` |

Source: [README.md:85-100](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

### CLI Option Definitions

The CLI options are parsed using the `commander` package:

```typescript
program
  .option("--browserbaseApiKey <key>", "The Browserbase API Key to use")
  .option("--browserbaseProjectId <id>", "The Browserbase Project ID to use")
  .option("--proxies", "Use Browserbase proxies.")
  .option("--verified", "Use Browserbase Verified Identity. Only available to Browserbase Scale Plan users.")
  .option("--advancedStealth", "Deprecated alias for --verified.")
  .option("--contextId <contextId>", "Browserbase Context ID to use");
```

Source: [src/program.ts:30-40](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/program.ts)

## Environment Variables

### Required Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `BROWSERBASE_API_KEY` | Your Browserbase API key | Yes |
| `BROWSERBASE_PROJECT_ID` | Your Browserbase Project ID | Yes |
| `GEMINI_API_KEY` | Gemini API key for default model | Yes (unless using hosted) |

### Optional Variables

| Variable | Description | Auto-resolved From |
|----------|-------------|-------------------|
| `modelApiKey` | API key for custom models | `GEMINI_API_KEY` or `GOOGLE_API_KEY` |

### Configuration Resolution Order

The server resolves configuration using this precedence (highest to lowest):

1. CLI arguments
2. Environment variables
3. Default values

```mermaid
graph TD
    A[Config Resolution] --> B[Load Defaults]
    B --> C[Merge Env Variables]
    C --> D[Apply CLI Overrides]
    D --> E[Validate Configuration]
    E --> F[Start Server]
```

Source: [src/config.ts:40-60](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

## Configuration Type Definition

```typescript
interface Config {
  browserbaseApiKey: string;
  browserbaseProjectId: string;
  proxies?: boolean;
  verified?: boolean;
  advancedStealth?: boolean;
  keepAlive?: boolean;
  context?: {
    contextId?: string;
    persist?: boolean;
  };
  server?: {
    port?: number;
    host?: string;
  };
  viewPort?: {
    browserWidth?: number;
    browserHeight?: number;
  };
  modelName?: string;
  modelApiKey?: string;
  experimental?: boolean;
}
```

Source: [config.d.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)

## Model Configuration

The server defaults to Google's Gemini 2.5 Flash Lite model but supports custom models.

### Default Configuration

| Setting | Value |
|---------|-------|
| Default Model | `google/gemini-2.5-flash-lite` |
| API Key Source | `GEMINI_API_KEY` or `GOOGLE_API_KEY` env var |

### Custom Model Setup

To use a custom model, provide both `--modelName` and `--modelApiKey`:

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": [
        "@browserbasehq/mcp",
        "--modelName",
        "anthropic/claude-sonnet-4.5",
        "--modelApiKey",
        "your-anthropic-api-key"
      ],
      "env": {
        "BROWSERBASE_API_KEY": "",
        "BROWSERBASE_PROJECT_ID": ""
      }
    }
  }
}
```

> **Note**: The model must be supported by Stagehand. See [Stagehand Custom LLM docs](https://docs.stagehand.dev/examples/custom_llms#supported-llms).

Source: [README.md:110-130](https://github.com/browserbase/mcp-server-browserbase/blob/main/README.md)

## Deployment Decision Matrix

| Use Case | Recommended Method | Transport |
|----------|-------------------|-----------|
| Quick testing | NPM (npx) | STDIO |
| Development | Direct Installation | STDIO |
| Production (self-hosted) | Docker | SHTTP |
| Production (managed) | Hosted Server | SHTTP |
| CI/CD pipelines | Docker | STDIO |
| Claude Code integration | NPM | STDIO |

## Security Considerations

### Host Binding

| Host Value | Behavior | Security Level |
|------------|----------|----------------|
| `localhost` | Local connections only | High |
| `0.0.0.0` | All network interfaces | Low - requires firewall |

> **Warning**: Use `0.0.0.0` only when you need external access and have proper security measures in place.

### API Key Management

- Store credentials in environment variables, never in config files committed to version control
- Use secret management solutions in production environments
- Rotate API keys regularly

Source: [config.d.ts:25-35](https://github.com/browserbase/mcp-server-browserbase/blob/main/config.d.ts)

## Quick Reference

### Minimal STDIO Setup

```json
{
  "mcpServers": {
    "browserbase": {
      "command": "npx",
      "args": ["@browserbasehq/mcp"],
      "env": {
        "BROWSERBASE_API_KEY": "your-key",
        "BROWSERBASE_PROJECT_ID": "your-project",
        "GEMINI_API_KEY": "your-gemini-key"
      }
    }
  }
}
```

### Full-Featured Docker Setup

```bash
docker run --rm -i \
  -e BROWSERBASE_API_KEY \
  -e BROWSERBASE_PROJECT_ID \
  -e GEMINI_API_KEY \
  mcp-browserbase \
  --proxies \
  --verified \
  --browserWidth 1920 \
  --browserHeight 1080
```

## Related Documentation

- [Browserbase MCP Documentation](https://docs.browserbase.com/integrations/mcp/introduction)
- [MCP Specification](https://spec.modelcontextprotocol.io/)
- [Stagehand Documentation](https://docs.stagehand.dev/)

---

<a id='testing'></a>

## Testing

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [vitest.config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/vitest.config.ts)
- [src/config.test.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.test.ts)
- [package.json](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)
- [eslint.config.js](https://github.com/browserbase/mcp-server-browserbase/blob/main/eslint.config.js)
- [src/config.ts](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)
</details>

# Testing

## Overview

The mcp-server-browserbase project implements a comprehensive testing infrastructure using Vitest as the primary testing framework. The testing setup is designed to validate configuration handling, ensure type safety, and maintain code quality through integration with ESLint and Prettier. Testing focuses primarily on the configuration subsystem and verification compatibility, leveraging modern TypeScript testing practices with Zod schema validation testing.

## Testing Stack

### Core Testing Framework

The project uses **Vitest** (version 4.1.2), a Vite-native unit testing framework that provides fast test execution and excellent TypeScript support. Vitest is configured through `vitest.config.ts` to discover and run tests across the codebase.

### Supporting Tools

| Tool | Version | Purpose |
|------|---------|---------|
| `vitest` | ^4.1.2 | Primary testing framework |
| `mcpvals` | ^0.4.0 | MCP protocol validation |
| `tsx` | ^4.20.3 | TypeScript execution for evals |
| `typescript` | ^5.6.2 | TypeScript compiler and type checking |
| `eslint` | ^9.29.0 | Code linting |
| `prettier` | ^3.6.1 | Code formatting |

Source: [package.json:39-60](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

## Test Configuration

### Vitest Configuration

The Vitest configuration defines the scope and boundaries of test discovery within the project:

```typescript
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    include: ["src/**/*.test.ts", "tests/**/*.test.ts"],
    exclude: ["node_modules", "dist"],
  },
});
```

**Configuration Parameters:**

| Parameter | Value | Description |
|-----------|-------|-------------|
| `include` | `["src/**/*.test.ts", "tests/**/*.test.ts"]` | Glob patterns for test file discovery |
| `exclude` | `["node_modules", "dist"]` | Directories excluded from test discovery |

Source: [vitest.config.ts:1-9](https://github.com/browserbase/mcp-server-browserbase/blob/main/vitest.config.ts)

### Test Execution

Tests are executed through npm/pnpm scripts defined in package.json:

| Script | Command | Purpose |
|--------|---------|---------|
| `test` | `vitest run` | Run tests once without watch mode |
| `prepare` | `husky && pnpm build` | Git hook setup and build (runs on `npm install`) |
| `pre-commit` | `pnpm lint-staged` | Pre-commit hooks for linting and formatting |

Source: [package.json:32-34](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

## Test Structure

### Directory Organization

Tests follow a co-located pattern within the source directory:

```mermaid
graph TD
    A[Project Root] --> B[src/]
    A --> C[tests/]
    B --> D[config.test.ts]
    B --> E[index.ts]
    B --> F[config.ts]
    
    D -. tests .-> F
    D -. validates .-> E
```

### Configuration Tests

The `config.test.ts` file contains comprehensive tests for configuration handling, verifying the behavior of configuration normalization and schema validation:

#### Test Suite: Verified Config Compatibility

The test suite validates configuration alias handling and priority resolution between different configuration sources:

**Test 1: Legacy CLI AdvancedStealth Alias Mapping**

```typescript
it("maps the legacy CLI advancedStealth alias to verified", async () => {
  const config = await configFromCLIOptions({ advancedStealth: true });
  expect(config.verified).toBe(true);
});
```

This test verifies that the deprecated `advancedStealth` option correctly maps to the `verified` configuration property, maintaining backward compatibility.

Source: [src/config.test.ts:9-13](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.test.ts)

**Test 2: Verified/AdvancedStealth Priority Resolution**

```typescript
it("prefers verified when both verified and advancedStealth are set", () => {
  const config = normalizeVerifiedConfig({
    browserbaseApiKey: "test-key",
    browserbaseProjectId: "test-project",
    verified: false,
    advancedStealth: true,
  });
  expect(config.verified).toBe(false);
});
```

This test ensures that when both `verified` and `advancedStealth` are provided, the explicit `verified` value takes precedence, following the principle that explicit configuration overrides deprecated aliases.

Source: [src/config.test.ts:15-23](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.test.ts)

**Test 3: Smithery Config Schema Compatibility**

```typescript
it("accepts advancedStealth in the Smithery config schema", () => {
  const config = configSchema.parse({
    browserbaseApiKey: "test-key",
    browserbaseProjectId: "test-project",
    advancedStealth: true,
  });
  expect(config.advancedStealth).toBe(true);
});
```

This test validates compatibility with external configuration schemas like Smithery, ensuring the `advancedStealth` property is correctly parsed and preserved.

Source: [src/config.test.ts:25-32](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.test.ts)

## Code Quality Integration

### ESLint Configuration

The project uses ESLint with TypeScript support to maintain code quality across test files and source code:

```javascript
export default defineConfig([
  {
    files: ["**/*.{js,mjs,cjs,ts,mts,cts}"],
    plugins: { js },
    extends: ["js/recommended"],
    ignores: ["dist/**/*"],
  },
  {
    files: ["**/*.{js,mjs,cjs,ts,mts,cts}"],
    languageOptions: { globals: { ...globals.browser, ...globals.node } },
    ignores: ["dist/**/*"],
  },
  ...tseslint.configs.recommended,
  {
    files: ["src/types/**/*.ts", "src/mcp/**/*.ts"],
    rules: {
      "@typescript-eslint/no-explicit-any": "off",
      "@typescript-eslint/no-unused-vars": "off",
      "@typescript-eslint/ban-ts-comment": "off",
    },
  },
  {
    ignores: ["dist/**/*", "node_modules/**/*"],
  },
]);
```

**ESLint Rule Configuration:**

| Rule | Applied To | Setting | Rationale |
|------|------------|---------|-----------|
| `no-explicit-any` | `src/types/**`, `src/mcp/**` | Off | Type definitions may require explicit any |
| `no-unused-vars` | `src/types/**`, `src/mcp/**` | Off | Allow exported types with potential future use |
| `ban-ts-comment` | `src/types/**`, `src/mcp/**` | Off | Allow TypeScript directive comments |

Source: [eslint.config.js:1-34](https://github.com/browserbase/mcp-server-browserbase/blob/main/eslint.config.js)

### Lint-Staged Configuration

The project uses lint-staged to run automated linting and formatting on staged files before commits:

```json
"lint-staged": {
  "*.{js,jsx,ts,tsx,json,css,scss,md}": [
    "prettier --write .",
    "eslint --fix"
  ]
}
```

This configuration ensures all staged files are formatted with Prettier and fixed with ESLint before being committed, maintaining consistent code style.

Source: [package.json:26-31](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

## Configuration Resolution Flow

The testing infrastructure validates the configuration resolution process, which follows a cascading merge strategy:

```mermaid
graph LR
    A[Default Config] --> B[CLI Options]
    B --> C[mergeConfig]
    C --> D[normalizeVerifiedConfig]
    D --> E[Final Config]
    
    F[Env: GEMINI_API_KEY] -.-> E
    F -.-> G[modelApiKey]
    G --> E
```

**Configuration Priority Order (Lowest to Highest):**

1. Default configuration values
2. Environment variables
3. CLI options
4. Explicit verified flag (overrides deprecated advancedStealth)

Source: [src/config.ts:18-32](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

## Default Configuration Values

The test suite validates against the following default configuration structure:

| Property | Default Value | Source |
|----------|---------------|--------|
| `browserbaseApiKey` | `process.env.BROWSERBASE_API_KEY` | Environment |
| `browserbaseProjectId` | `process.env.BROWSERBASE_PROJECT_ID` | Environment |
| `proxies` | `false` | Hardcoded |
| `server.port` | `undefined` | None |
| `server.host` | `undefined` | None |
| `viewPort.browserWidth` | `1024` | Hardcoded |
| `viewPort.browserHeight` | `768` | Hardcoded |
| `modelName` | `google/gemini-2.5-flash-lite` | Hardcoded |

Source: [src/config.ts:18-28](https://github.com/browserbase/mcp-server-browserbase/blob/main/src/config.ts)

## Test Coverage Areas

### Currently Covered

| Area | File | Status |
|------|------|--------|
| Configuration alias mapping | `src/config.test.ts` | Implemented |
| Verified config priority | `src/config.test.ts` | Implemented |
| Schema validation | `src/config.test.ts` | Implemented |

### Evals System

The project includes an evaluation system for testing MCP server behavior:

```bash
"evals": "tsx evals/run-evals.ts run --config evals/mcp-eval-basic.config.json && tsx evals/run-evals.ts run --config evals/mcp-eval-minimal.config.json && tsx evals/run-evals.ts run --config evals/mcp-eval.config.json"
```

The evals system runs multiple evaluation configurations to validate the MCP server's functionality against expected behavior patterns.

Source: [package.json:30](https://github.com/browserbase/mcp-server-browserbase/blob/main/package.json)

## Running Tests

### Standard Test Execution

```bash
# Run all tests once
pnpm test

# Run tests in watch mode during development
npx vitest
```

### With Evals

```bash
# Run comprehensive evaluation suite
pnpm evals
```

### Code Quality Checks

```bash
# Run ESLint
pnpm lint

# Format code with Prettier
pnpm format

# Run all pre-commit checks
pnpm pre-commit
```

## Best Practices Demonstrated

The testing infrastructure demonstrates several best practices:

1. **Co-located tests**: Test files are placed alongside source files with `.test.ts` suffix
2. **Descriptive test names**: Tests use clear, descriptive names explaining the scenario being validated
3. **Configuration validation**: Zod schemas are tested for backward compatibility
4. **Code quality automation**: Pre-commit hooks ensure consistent formatting and linting
5. **Multiple test configurations**: The eval system provides tiered testing with basic, minimal, and full configurations

---

---

## Doramagic Pitfall Log

Project: browserbase/mcp-server-browserbase

Summary: Found 11 potential pitfall items; 1 are high/blocking. Highest priority: security_permissions - 来源证据：Browser Automation Platforms Comparison: Browserbase vs. Kernel vs. Alternatives.

## 1. security_permissions · 来源证据：Browser Automation Platforms Comparison: Browserbase vs. Kernel vs. Alternatives

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Browser Automation Platforms Comparison: Browserbase vs. Kernel vs. Alternatives
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_3f3713f7877146edb5a3e4a757649326 | https://github.com/browserbase/mcp-server-browserbase/issues/127 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。

## 2. identity · 仓库名和安装名不一致

- Severity: medium
- Evidence strength: runtime_trace
- Finding: 仓库名 `mcp-server-browserbase` 与安装入口 `@browserbasehq/mcp` 不完全一致。
- User impact: 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- Suggested check: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- Reproduction command: `npx @browserbasehq/mcp`
- Guardrail action: 页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- Evidence: identity.distribution | github_repo:899184149 | https://github.com/browserbase/mcp-server-browserbase | repo=mcp-server-browserbase; install=@browserbasehq/mcp

## 3. installation · 来源证据：Your MCP server is now indexed on Joy Trust Network

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Your MCP server is now indexed on Joy Trust Network
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_799b517ef2c24dc6af45a04e4fff4c42 | https://github.com/browserbase/mcp-server-browserbase/issues/174 | 来源类型 github_issue 暴露的待验证使用条件。

## 4. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | github_repo:899184149 | https://github.com/browserbase/mcp-server-browserbase | README/documentation is current enough for a first validation pass.

## 5. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | github_repo:899184149 | https://github.com/browserbase/mcp-server-browserbase | last_activity_observed missing

## 6. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | github_repo:899184149 | https://github.com/browserbase/mcp-server-browserbase | no_demo; severity=medium

## 7. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | github_repo:899184149 | https://github.com/browserbase/mcp-server-browserbase | no_demo; severity=medium

## 8. security_permissions · 来源证据：Add MCPpedia security badge to README

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add MCPpedia security badge to README
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_49127f0ff1d042b1bb4e2a0ed463a451 | https://github.com/browserbase/mcp-server-browserbase/issues/175 | 来源类型 github_issue 暴露的待验证使用条件。

## 9. security_permissions · 来源证据：Add policy enforcement for cloud browser sessions

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add policy enforcement for cloud browser sessions
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_7b66fd703d8643c4a3f9b0ffa3b61ce5 | https://github.com/browserbase/mcp-server-browserbase/issues/176 | 来源类型 github_issue 暴露的待验证使用条件。

## 10. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | github_repo:899184149 | https://github.com/browserbase/mcp-server-browserbase | issue_or_pr_quality=unknown

## 11. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | github_repo:899184149 | https://github.com/browserbase/mcp-server-browserbase | release_recency=unknown

<!-- canonical_name: browserbase/mcp-server-browserbase; human_manual_source: deepwiki_human_wiki -->
