Skip to main content
Glama
GonzaloRando03

Selenium MCP Server

README.md
# 🎭 Selenium MCP Server

**Model Context Protocol server for browser automation using Selenium WebDriver.**

66 tools for navigation, interaction, screenshots, assertions, cookies, tabs, HTTP API, recording, batch execution, iframes, and raw WebDriver access β€” all with strict hexagonal architecture.

[![TypeScript](https://img.shields.io/badge/TypeScript-93.6%25-blue)](https://www.typescriptlang.org/)
[![License](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
[![Node](https://img.shields.io/badge/node-%3E%3D18-brightgreen)](https://nodejs.org/)

---

## Why this MCP?

Most Selenium MCPs expose basic WebDriver commands. This one adds the layers that make AI agents truly reliable:

| Feature                                                               | Status |
| --------------------------------------------------------------------- | ------ |
| Page snapshot with stable element refs (`capture_page` β†’ e1, e2, ...) | βœ…     |
| Persistent per-domain selector hints                                  | βœ…     |
| HTTP API tools (GET/POST/PUT/PATCH/DELETE)                            | βœ…     |
| Batch multi-step execution (up to 20 steps in 1 call)                 | βœ…     |
| Built-in test assertions                                              | βœ…     |
| Raw WebDriver API access (`run_selenium`)                             | βœ…     |
| Recording for test generation                                         | βœ…     |
| Dialog handling (alert/confirm/prompt)                                | βœ…     |
| Cookie management                                                     | βœ…     |
| Stealth mode                                                          | βœ…     |
| Session tracing (NDJSON)                                              | βœ…     |
| Selenium Manager auto-provisioning                                    | βœ…     |

---

## Quick Start

### One-click install

[![Install in VS Code](https://img.shields.io/badge/VS_Code-Install-blue?logo=visualstudiocode)](https://insiders.vscode.dev/redirect?url=vscode%3Amcp%2Finstall%3F%257B%2522name%2522%253A%2522selenium-mcp%2522%252C%2522command%2522%253A%2522npx%2522%252C%2522args%2522%253A%255B%2522mcp-selenium-webdriver%2522%255D%257D)

### From npm

```bash
npm install -g mcp-selenium-webdriver
```

Or run directly:

```bash
npx mcp-selenium-webdriver
```

### Prerequisites

- **Node.js 18+**
- **Chrome**, Firefox, or Edge installed
- Selenium Manager provisions the matching driver automatically β€” no manual setup needed.

```bash
# Verify everything is ready
npx mcp-selenium-webdriver doctor
```

### MCP Client Configuration

**VS Code Copilot** (`.vscode/mcp.json`):

```json
{
  "servers": {
    "selenium-mcp": {
      "command": "npx",
      "args": ["mcp-selenium-webdriver"],
      "type": "stdio"
    }
  }
}
```

**Claude Desktop**:

```json
{
  "mcpServers": {
    "selenium-mcp": {
      "command": "npx",
      "args": ["mcp-selenium-webdriver"]
    }
  }
}
```

**Cursor** (`.cursor/mcp.json`):

```json
{
  "mcpServers": {
    "selenium-mcp": {
      "command": "npx",
      "args": ["mcp-selenium-webdriver"]
    }
  }
}
```

---

## Environment Variables

| Variable                          | Default  | Description                          |
| --------------------------------- | -------- | ------------------------------------ |
| `SELENIUM_BROWSER`                | `chrome` | Browser: `chrome`, `firefox`, `edge` |
| `SELENIUM_HEADLESS`               | `false`  | Run browser in headless mode         |
| `SELENIUM_STEALTH`                | `false`  | Hide automation indicators           |
| `SELENIUM_GRID_URL`               | β€”        | Selenium Grid hub URL                |
| `SELENIUM_MCP_OUTPUT_MODE`        | `stdout` | Output: `stdout` or `file`           |
| `SELENIUM_MCP_OUTPUT_DIR`         | auto     | Custom output directory              |
| `SELENIUM_MCP_SAVE_TRACE`         | `false`  | Save session trace as NDJSON         |
| `SELENIUM_MCP_UNRESTRICTED_FILES` | `false`  | Bypass workspace sandbox             |
| `HTTPS_PROXY` / `HTTP_PROXY`      | β€”        | Corporate proxy                      |

Pass them in your MCP config:

```json
{
  "mcpServers": {
    "selenium-mcp": {
      "command": "npx",
      "args": ["mcp-selenium-webdriver"],
      "env": {
        "SELENIUM_HEADLESS": "true",
        "SELENIUM_STEALTH": "true"
      }
    }
  }
}
```

---

## CLI Flags

```bash
npx mcp-selenium-webdriver [flags]
npx mcp-selenium-webdriver doctor   # preflight diagnostics
```

| Flag                               | Description                                             |
| ---------------------------------- | ------------------------------------------------------- |
| `doctor`                           | Run diagnostics (Chrome, driver, proxy, cache) and exit |
| `--headless`                       | Run browser headless                                    |
| `--stealth`                        | Enable stealth mode                                     |
| `--save-trace`                     | Save session trace JSON                                 |
| `--output-mode=stdout\|file`       | Set output mode                                         |
| `--output-dir=<path>`              | Custom output directory                                 |
| `--grid-url=<url>`                 | Selenium Grid hub URL                                   |
| `--allow-unrestricted-file-access` | Bypass workspace sandbox                                |

---

## Tools (66)

### 🧭 Navigation (7)

| Tool              | Description                                      |
| ----------------- | ------------------------------------------------ |
| `navigate_to`     | Navigate to a URL. Starts browser automatically. |
| `go_back`         | Navigate back in history.                        |
| `go_forward`      | Navigate forward in history.                     |
| `refresh_page`    | Refresh the current page.                        |
| `scroll_page`     | Scroll the page or element into view.            |
| `get_current_url` | Get the current URL. Read-only.                  |
| `get_title`       | Get the page title. Read-only.                   |

### πŸ“Έ Page Analysis (5)

| Tool               | Description                                                               |
| ------------------ | ------------------------------------------------------------------------- |
| `capture_page`     | Capture page state as element list with stable refs (e1-e300). Read-only. |
| `get_page_source`  | Get the full HTML DOM. Read-only.                                         |
| `get_visible_text` | Get visible text, optionally scoped to a CSS selector. Read-only.         |
| `get_visible_html` | Get visible HTML (scripts removed by default). Read-only.                 |
| `take_screenshot`  | Take a screenshot (viewport, full-page, or element).                      |

### πŸ–±οΈ Elements (9)

| Tool             | Description                                        |
| ---------------- | -------------------------------------------------- |
| `click_element`  | Click an element by CSS selector or ref.           |
| `hover_element`  | Hover over an element.                             |
| `double_click`   | Double-click an element.                           |
| `right_click`    | Right-click (context menu) an element.             |
| `select_option`  | Select a dropdown option by value, text, or index. |
| `drag_drop`      | Drag one element to another.                       |
| `teach_selector` | Teach a preferred CSS selector for a domain.       |
| `iframe_click`   | Click an element inside an iframe.                 |
| `iframe_fill`    | Fill an input inside an iframe.                    |

### ⌨️ Input (3)

| Tool          | Description                                                               |
| ------------- | ------------------------------------------------------------------------- |
| `input_text`  | Type text into an input field.                                            |
| `key_press`   | Press a keyboard key, optionally with modifiers (ctrl, alt, shift, meta). |
| `file_upload` | Upload a file through a file input.                                       |

### πŸ–²οΈ Mouse (3)

| Tool          | Description                                 |
| ------------- | ------------------------------------------- |
| `mouse_move`  | Move mouse to coordinates.                  |
| `mouse_click` | Click at coordinates (left, right, middle). |
| `mouse_drag`  | Drag from one position to another.          |

### πŸ“‘ Tabs (4)

| Tool         | Description                    |
| ------------ | ------------------------------ |
| `tab_list`   | List all open tabs. Read-only. |
| `tab_select` | Switch to a specific tab.      |
| `tab_new`    | Open a new tab.                |
| `tab_close`  | Close a tab.                   |

### βœ… Verification (4)

| Tool                     | Description                                        |
| ------------------------ | -------------------------------------------------- |
| `verify_element_visible` | Verify an element is visible. Read-only.           |
| `verify_text_visible`    | Verify text is visible. Read-only.                 |
| `verify_value`           | Verify an input has the expected value. Read-only. |
| `verify_list_visible`    | Verify multiple texts are visible. Read-only.      |

### 🌐 Browser Control (7)

| Tool                 | Description                                            |
| -------------------- | ------------------------------------------------------ |
| `wait_for`           | Wait for a condition (element visible, URL, title...). |
| `execute_javascript` | Run JavaScript in the browser context.                 |
| `resize_window`      | Resize the browser window.                             |
| `dialog_handle`      | Handle dialogs (alert, confirm, prompt).               |
| `console_logs`       | Get browser console logs with filtering. Read-only.    |
| `network_monitor`    | Monitor network requests / toggle offline mode.        |
| `pdf_generate`       | Generate a PDF from the current page. Read-only.       |

### πŸ”„ Browser Lifecycle (5)

| Tool               | Description                                        |
| ------------------ | -------------------------------------------------- |
| `start_browser`    | Start the browser explicitly with options.         |
| `close_browser`    | Close the browser and end the session.             |
| `reset_session`    | Reset the session (close + restart).               |
| `set_stealth_mode` | Enable/disable stealth mode.                       |
| `browser_status`   | Get session status (URL, title, state). Read-only. |

### πŸͺ Cookies (3)

| Tool            | Description                 |
| --------------- | --------------------------- |
| `get_cookies`   | Get all cookies. Read-only. |
| `add_cookie`    | Add a cookie.               |
| `delete_cookie` | Delete a cookie by name.    |

### ⏺️ Recording (4)

| Tool               | Description                                  |
| ------------------ | -------------------------------------------- |
| `start_recording`  | Start recording actions for test generation. |
| `stop_recording`   | Stop recording and return the action log.    |
| `recording_status` | Check recording status. Read-only.           |
| `clear_recording`  | Clear all recorded actions.                  |

### πŸ’Ύ Selector Hints (4)

| Tool                   | Description                                 |
| ---------------------- | ------------------------------------------- |
| `selector_hint_save`   | Save a preferred CSS selector for a domain. |
| `selector_hint_get`    | Get saved hints for a domain. Read-only.    |
| `selector_hint_list`   | List domains with hints. Read-only.         |
| `selector_hint_delete` | Delete a hint.                              |

### 🌍 HTTP API (5)

| Tool          | Description                  |
| ------------- | ---------------------------- |
| `http_get`    | HTTP GET request. Read-only. |
| `http_post`   | HTTP POST request with body. |
| `http_put`    | HTTP PUT request.            |
| `http_patch`  | HTTP PATCH request.          |
| `http_delete` | HTTP DELETE request.         |

### ⚑ Power Tools (3)

| Tool                       | Description                                                                         |
| -------------------------- | ----------------------------------------------------------------------------------- |
| `batch_execute`            | Execute up to 20 tool steps in a single call.                                       |
| `run_selenium`             | Execute raw Selenium WebDriver API code (access to `driver`, `By`, `until`, `Key`). |
| `browser_generate_locator` | Generate a robust locator for an element by description. Read-only.                 |

---

## Architecture

Hexagonal architecture (Ports & Adapters):

```
src/
β”œβ”€β”€ domain/
β”‚   β”œβ”€β”€ models/          Pure types & value objects
β”‚   β”œβ”€β”€ ports/           18 interfaces (IBrowserPort, INavigationPort...)
β”‚   └── services/        16 use cases
β”œβ”€β”€ adapters/
β”‚   β”œβ”€β”€ selenium/        14 Selenium WebDriver implementations
β”‚   β”œβ”€β”€ mcp/             MCP SDK server & tool registry
β”‚   β”œβ”€β”€ persistence/     File system & selector hints storage
β”‚   └── logging/         Console & trace (NDJSON) loggers
β”œβ”€β”€ infrastructure/      DI container (tsyringe), bootstrap, config
β”œβ”€β”€ index.ts             Entry point
└── cli.ts               CLI (doctor, flags)
```

**Key design decisions:**

- **Dependency Injection** via `tsyringe` with `Symbol` tokens β€” every port is swappable
- **Zod** would be used for runtime validation (planned)
- **Selenium Manager** auto-provisions chromedriver matching your installed Chrome version
- **16-phase selector engine** for `capture_page` (ID β†’ testId β†’ role β†’ label β†’ ... β†’ positional index)
- **Stealth mode** injects scripts to hide `navigator.webdriver` and automation indicators

---

## Example Usage

Ask your AI agent:

> Navigate to https://example.com, capture the page, click the first link, take a screenshot, verify "Example Domain" is visible.

The agent chains the tools automatically:

```
navigate_to β†’ capture_page β†’ click_element β†’ take_screenshot β†’ verify_text_visible
```

Or use raw WebDriver API:

```
run_selenium with:
  const el = await driver.findElement(By.css('h1'));
  const text = await el.getText();
  return text;
```

Batch execution:

```
batch_execute with:
  steps: [
    { tool: "navigate_to", args: { url: "https://example.com" } },
    { tool: "take_screenshot", args: { name: "before" } },
    { tool: "click_element", args: { selector: "a" } },
    { tool: "take_screenshot", args: { name: "after" } }
  ]
```

---

## Development

```bash
git clone <this-repo>
cd mcp-selenium-webdriver
npm install
npm run build
npm run doctor
```

### Scripts

```bash
npm run build          # Compile TypeScript
npm run dev            # Run with tsx (hot reload)
npm run typecheck      # Type-check without emitting
npm test               # Run all tests
npm run test:coverage  # Run tests with coverage
```

---

## License

MIT