Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
# Java runs the Selenium Grid that the selenium_grid_* tools are tested against.
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
- name: Download Selenium Grid
run: |
curl -sSLf -o "$RUNNER_TEMP/selenium-server.jar" \
"https://github.com/SeleniumHQ/selenium/releases/download/selenium-${SELENIUM_GRID_VERSION}/selenium-server-${SELENIUM_GRID_VERSION}.jar"
env:
SELENIUM_GRID_VERSION: 4.52.0
- name: Install
run: npm install --no-audit --no-fund
env:
Expand All @@ -37,5 +48,8 @@ jobs:
run: npm run lint
- name: Unit tests
run: npm run test:unit
- name: Browser tests (Chrome)
- name: Browser tests (Chrome, and Selenium Grid)
run: npm run test:e2e
env:
SELENIUM_MCP_TEST_SERVER_JAR: ${{ runner.temp }}/selenium-server.jar
SELENIUM_MCP_TEST_NODE_ARGS: --selenium-manager true
10 changes: 7 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
- `server.js`: MCP server and tool registration
- `session.js`: browser lifecycle, options, Grid URL, console capture over BiDi
- `snapshot.js`: the in-page accessibility walk and the ref table
- `tools/`: one file per tool group (`navigate`, `interact`, `inspect`, `bidi`, `evaluate`, and the `--caps` groups
`vision`, `pdf`, `storage`)
- `tools/`: one file per tool group (`navigate`, `interact`, `inspect`, `bidi`, `evaluate`, `grid`, and the `--caps`
groups `vision`, `pdf`, `storage`)
- `grids.js`: saved Grids and the config file; `grid_api.js`: reads a Grid over `/status`, GraphQL and the queue
- CLI: `bin/selenium-mcp.js`, flags parsed in `lib/cli.js`
- Tests: `test/unit/` (no browser) and `test/e2e/` (real browser, in-memory MCP client). `test/fixtures/common/`
holds copies of pages from the Selenium bindings' shared test pages.
Expand All @@ -16,7 +17,8 @@

- Install: `NODE_AUTH_TOKEN=<token with read:packages> npm install` (see `.npmrc`)
- Unit tests: `npm run test:unit`
- Browser tests: `npm run test:e2e` (needs Chrome)
- Browser tests: `npm run test:e2e` (needs Chrome). The Grid tests also need Java and
`SELENIUM_MCP_TEST_SERVER_JAR=<selenium-server jar>`; they are skipped without it.
- Lint: `npm run lint`; fix formatting with `npm run format`

## Rules for tools
Expand All @@ -29,6 +31,8 @@
("Call browser_snapshot to get fresh refs").
- Actions return `actionResult(...)` so the agent gets a fresh snapshot without another call.
- Never write to stdout outside the MCP transport; logs go to stderr.
- `selenium_grid_*` tools only read a Grid. Destructive tasks (ending sessions, draining or removing nodes, clearing
the queue) are left to the person, and tools never guess which node, session or request is meant.

## Code conventions

Expand Down
46 changes: 43 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ Any other MCP client: run `npx @selenium/mcp@latest` as a stdio server.
| -------------------------- | ----------------------------------------------------------------------- |
| `--browser <name>` | `chrome` (default). `edge` and `firefox` start but are not yet tested. |
| `--headless` / `--headed` | Run headless (the default) or show the window. |
| `--grid <url>` | Run the browser on a Selenium Grid instead of locally. |
| `--grid <url\|name>` | Run the browser on a Selenium Grid instead of locally: a URL, or a Grid saved in the config file. |
| `--config <path>` | Config file of saved Grids (see [Selenium Grid](#selenium-grid)). |
| `--allowed-origins <list>` | Semicolon-separated origins or hosts (`*.example.com`) the browser may navigate to. |
| `--blocked-origins <list>` | Semicolon-separated origins or hosts it may not navigate to. |
| `--allow-unrestricted-file-access` | Let `browser_navigate` open `file://` URLs, and `browser_file_upload` send files from outside the working directory (both blocked by default). |
Expand Down Expand Up @@ -87,6 +88,16 @@ over.

Every action returns the page's URL, title and a fresh snapshot, so the agent rarely needs to ask for one.

These read a Selenium Grid (see [Selenium Grid](#selenium-grid)):

| Tool | What it does |
| -------------------------- | -------------------------------------------------------------------- |
| `selenium_grid_use` | Save a Grid by URL, or pick a saved one, as the default. |
| `selenium_grid_status` | Readiness, nodes and free slots per browser; one node in detail. |
| `selenium_grid_sessions` | Running sessions, longest first, with links to them in the Grid UI. |
| `selenium_grid_queue` | Waiting session requests, with a hint at why each waits. |
| `selenium_grid_bug_report` | A summary to paste into an issue, without URLs or ids. |

### Optional tools

Each group is listed only when `--caps` names it, since every agent pays for every listed tool on every turn.
Expand Down Expand Up @@ -116,11 +127,40 @@ Each group is listed only when `--caps` names it, since every agent pays for eve
- Content inside an iframe gets refs prefixed with the frame's own ref (`f5e1`), and tools act on them directly.
- Password values are never shown.

## Selenium Grid

The server can run its browser on a [Selenium Grid](https://www.selenium.dev/documentation/grid/) and tell an agent
what a Grid is doing. When the person names a Grid, the agent calls `selenium_grid_use`, which checks the Grid answers
and saves it as the default, so nobody is asked again. Browsers then start on that Grid, and the `selenium_grid_*`
tools read it. `--grid` on the command line still decides where browsers start for that run.

Saved Grids live in the first of these that applies, and are saved back to it:

1. `--config <path>`
2. the `SELENIUM_MCP_CONFIG` environment variable
3. `.selenium-mcp.json` in the working directory, if it exists
4. `~/.config/selenium-mcp/config.json` (or under `$XDG_CONFIG_HOME`)

```json
{
"defaultGrid": "staging",
"grids": {
"local": { "url": "http://localhost:4444" },
"staging": { "url": "https://grid.staging.example.com" }
}
}
```

The Grid tools only read. Ending sessions, draining or removing nodes and clearing the queue are left to the person,
on their Grid; `selenium_grid_sessions` gives each session's link in the Grid UI. The server assumes a Grid is
protected by its own network or auth: it saves no credentials, and refuses a URL with a user name or password in it
(one given to `--grid` is used for that run only). Browsers it starts on a Grid are named `selenium-mcp` (`se:name`),
so people can tell them apart in the Grid UI.

## What it covers

Chrome, headless, stdio, and the tools above. Not yet: Firefox and Edge under test, request interception
(`--caps network`), HTTP transport, more than one session, and the `selenium_*` tools (Grid status,
`selenium_doctor`). Those come in later releases.
(`--caps network`), HTTP transport, more than one session, and `selenium_doctor`. Those come in later releases.

## Security

Expand Down
9 changes: 8 additions & 1 deletion bin/selenium-mcp.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,14 @@ async function main() {
}

logToStderr(config.logLevel)
const { server, session } = createServer(config)
let created
try {
created = createServer(config)
} catch (e) {
process.stderr.write(`${e.message}\n`)
process.exit(2)
}
const { server, session } = created

let closing = false
const shutdown = async () => {
Expand Down
24 changes: 17 additions & 7 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

const { parseArgs } = require('node:util')

const { isGridName } = require('./grids')

const BROWSERS = ['chrome', 'edge', 'firefox']
/** Optional tool groups, named as @playwright/mcp names them. */
const CAPS = ['vision', 'pdf', 'storage']
Expand All @@ -38,7 +40,9 @@ Options:
--browser <name> chrome (default), edge or firefox
--headless run the browser headless (the default)
--headed show the browser window
--grid <url> run the browser on a Selenium Grid at this URL
--grid <url|name> run the browser on a Selenium Grid: a URL, or a Grid saved in the config file
--config <path> config file of saved Grids (default: $SELENIUM_MCP_CONFIG, then
./.selenium-mcp.json, then ~/.config/selenium-mcp/config.json)
--allowed-origins <list> semicolon-separated origins the browser may navigate to
--blocked-origins <list> semicolon-separated origins the browser may not navigate to
--allow-unrestricted-file-access
Expand All @@ -63,7 +67,7 @@ const NOT_YET = {
*
* @param {!Array<string>} argv arguments after the script name
* @return {{help: boolean, version: boolean, browser: string, headless: boolean,
* grid: (string|undefined), allowedOrigins: !Array<string>,
* grid: (string|undefined), configPath: (string|undefined), allowedOrigins: !Array<string>,
* blockedOrigins: !Array<string>, allowFileAccess: boolean, allowEvaluate: boolean,
* caps: !Array<string>, logLevel: string}}
* @throws {Error} on an unknown or invalid option
Expand All @@ -80,6 +84,7 @@ function parseCommandLine(argv) {
headless: { type: 'boolean' },
headed: { type: 'boolean' },
grid: { type: 'string' },
config: { type: 'string' },
'allowed-origins': { type: 'string' },
'blocked-origins': { type: 'string' },
isolated: { type: 'boolean' },
Expand Down Expand Up @@ -111,11 +116,15 @@ function parseCommandLine(argv) {
if (!CAPS.includes(cap)) throw new Error(`--caps takes ${CAPS.join(', ')}; got ${cap}`)
}
if (values.headless && values.headed) throw new Error('--headless and --headed cannot both be given')
if (values.grid) {
try {
new URL(values.grid)
} catch {
throw new Error(`--grid must be a URL; got ${values.grid}`)
if (values.grid !== undefined) {
if (/^https?:\/\//i.test(values.grid)) {
try {
new URL(values.grid)
} catch {
throw new Error(`--grid must be a URL or a saved Grid's name; got ${values.grid}`)
}
} else if (!isGridName(values.grid)) {
throw new Error(`--grid must be a URL or a saved Grid's name; got ${values.grid}`)
}
}

Expand All @@ -125,6 +134,7 @@ function parseCommandLine(argv) {
browser,
headless: !values.headed,
grid: values.grid,
configPath: values.config,
allowedOrigins: splitList(values['allowed-origins']),
blockedOrigins: splitList(values['blocked-origins']),
allowFileAccess: !!values['allow-unrestricted-file-access'],
Expand Down
145 changes: 145 additions & 0 deletions lib/grid_api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

'use strict'

const logging = require('selenium-webdriver/lib/logging')

const { ToolError } = require('./tools/common')
const { redact } = require('./grids')

const log_ = logging.getLogger('selenium.mcp.grid')

const TIMEOUT_MS = 10000

/** What the Grid tools read over GraphQL, in one request. */
const GRID_QUERY = `{
grid { version sessionCount sessionQueueSize }
sessionsInfo {
sessions { id capabilities startTime nodeId sessionDurationMillis }
}
}`

/**
* Reads a Selenium Grid's state over its HTTP API: /status, /graphql and the
* session queue. It only reads; nothing here changes the Grid.
*/
class GridApi {
/**
* @param {{name: string, url: string}} grid
* @param {{fetch: (function|undefined), timeoutMs: (number|undefined)}=} options
*/
constructor(grid, options = {}) {
this.name = grid.name
const url = new URL(grid.url)
this.headers_ = {}
if (url.username || url.password) {
const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`
this.headers_.authorization = `Basic ${Buffer.from(credentials).toString('base64')}`
url.username = ''
url.password = ''
}
/** The Grid's URL as given, without credentials and trailing slash. */
this.url = url.href.replace(/\/+$/, '')
this.fetch_ = options.fetch || globalThis.fetch
this.timeoutMs_ = options.timeoutMs || TIMEOUT_MS
}

/** @return {!Promise<!Object>} the `value` of GET /status */
async status() {
return (await this.request_('GET', '/status')).value
}

/** @return {!Promise<!Array<{requestId: string, capabilities: !Array<!Object>}>>} waiting requests */
async queue() {
return (await this.request_('GET', '/se/grid/newsessionqueue/queue')).value || []
}

/** @return {!Promise<!Object>} the `data` of GRID_QUERY */
async gridData() {
const body = await this.request_('POST', '/graphql', { query: GRID_QUERY })
if (body.errors && body.errors.length) {
throw new ToolError(`The Grid "${this.name}" rejected the query: ${body.errors[0].message}`)
}
return body.data
}

/**
* @param {string} id
* @return {string} where a person can watch, or end, the session in the Grid UI
*/
sessionLink(id) {
return `${this.url}/ui/#/session/${id}`
}

async request_(method, path, body) {
const where = `${this.url}${path}`
log_.fine(`${method} ${where}`)
let response
try {
response = await this.fetch_(where, {
method,
headers: {
...this.headers_,
accept: 'application/json',
// The Grid refuses a JSON body unless the charset is spelled out.
...(body ? { 'content-type': 'application/json; charset=utf-8' } : {}),
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(this.timeoutMs_),
})
} catch (e) {
const reason = e.name === 'TimeoutError' ? `no answer within ${this.timeoutMs_ / 1000}s` : causeOf(e)
log_.warning(`${method} ${redact(where)} failed: ${reason}`)
throw new ToolError(
`Could not reach the Grid "${this.name}" at ${this.url}: ${reason}. ` +
'Check the URL with the person; selenium_grid_use saves a corrected one.',
)
}
if (response.status === 401 || response.status === 403) {
throw new ToolError(
`The Grid "${this.name}" at ${this.url} refused the request (HTTP ${response.status}); it needs credentials ` +
'this server does not have.',
)
}
const text = await response.text()
let json
try {
json = JSON.parse(text)
} catch {
throw new ToolError(
`${this.url}${path} answered HTTP ${response.status} without JSON. Is ${this.url} a Selenium Grid?`,
)
}
if (!response.ok && !json.data) {
const message = (json.value && json.value.message) || `HTTP ${response.status}`
throw new ToolError(`The Grid "${this.name}" answered ${path} with an error: ${firstLine(message)}`)
}
return json
}
}

function causeOf(e) {
const cause = e.cause || e
return cause.code || cause.message || String(cause)
}

function firstLine(message) {
return String(message).split('\n')[0]
}

module.exports = { GRID_QUERY, GridApi }
Loading
Loading