Skip to content
Merged
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
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
- `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`)
- `tools/`: one file per tool group (`navigate`, `interact`, `inspect`, `bidi`, `evaluate`, and the `--caps` groups
`vision`, `pdf`, `storage`)
- 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 Down
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Any other MCP client: run `npx @selenium/mcp@latest` as a stdio server.
| `--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). |
| `--allow-evaluate` | Offer `browser_evaluate`, which runs JavaScript the agent writes in the page. |
| `--caps <list>` | Comma-separated optional tool groups: `vision`, `pdf`, `storage`. See [Optional tools](#optional-tools). |
| `--log-level <level>` | Log to stderr: `severe`, `warning` (default), `info`, `fine`, `all`. `all` includes raw WebDriver traffic, so typed text such as passwords. |

Flag names match `@playwright/mcp` wherever they mean the same thing.
Expand Down Expand Up @@ -86,6 +87,16 @@ over.

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

### Optional tools

Each group is listed only when `--caps` names it, since every agent pays for every listed tool on every turn.

| Group | Tools |
| --------- | --------------------------------------------------------------------------------------------------- |
| `vision` | `browser_mouse_move_xy`, `browser_mouse_click_xy`, `browser_mouse_drag_xy`, `browser_mouse_down`, `browser_mouse_up`, `browser_mouse_wheel`: the mouse by viewport coordinates, as read from a screenshot. |
| `pdf` | `browser_pdf_save`: save the page as a PDF. Without a file name it goes to a new file in the temp directory; a name must be inside the working directory unless `--allow-unrestricted-file-access` is given. |
| `storage` | `browser_cookie_*`, `browser_localstorage_*` and `browser_sessionstorage_*`, each with `list`, `get`, `set`, `delete` and `clear`, for the current page. |

### Snapshots and refs

```
Expand All @@ -107,9 +118,9 @@ Every action returns the page's URL, title and a fresh snapshot, so the agent ra

## What it covers

Chrome, headless, stdio, and the tools above. Not yet: Firefox and Edge under test, the opt-in tool groups behind
`--caps` (request interception, storage, coordinates, PDF), HTTP transport, more than one session, and the
`selenium_*` tools (Grid status, `selenium_doctor`). Those come in later releases.
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.

## Security

Expand All @@ -121,6 +132,7 @@ Chrome, headless, stdio, and the tools above. Not yet: Firefox and Edge under te
- `--allowed-origins` and `--blocked-origins` restrict where `browser_navigate` can go. They do not stop links,
redirects or scripts on a page from going elsewhere, so they are not a browser-wide security boundary.
- Snapshots, screenshots, console messages and request URLs and statuses are the only page data returned by default.
`--caps storage` also returns cookie and Web Storage values, which can include session tokens.

## Development

Expand Down
23 changes: 20 additions & 3 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
const { parseArgs } = require('node:util')

const BROWSERS = ['chrome', 'edge', 'firefox']
/** Optional tool groups, named as @playwright/mcp names them. */
const CAPS = ['vision', 'pdf', 'storage']
/** Groups other MCP servers have that this one does not support yet, with why. */
const CAPS_NOT_YET = {
network: 'request routing is planned for a later version',
}
// The bindings read any other name as ALL, which logs request bodies, typed
// text included, so an unknown level is refused rather than passed on.
const LOG_LEVELS = ['severe', 'warning', 'info', 'fine', 'all']
Expand All @@ -39,6 +45,8 @@ Options:
allow browser_navigate to open file:// URLs, and
browser_file_upload to upload files outside the working directory
--allow-evaluate offer browser_evaluate, which runs JavaScript the agent writes in the page
--caps <list> comma-separated optional tool groups to offer: vision (mouse by
coordinates), pdf (save the page as PDF), storage (cookies and Web Storage)
--isolated accepted for compatibility; every session already uses a fresh profile
--log-level <level> log to stderr at this level: severe, warning (default), info, fine,
all (all includes raw WebDriver traffic, so typed text such as passwords)
Expand All @@ -48,7 +56,6 @@ Options:
/** Flags other MCP servers have that v0 does not support yet, with why. */
const NOT_YET = {
port: 'HTTP transport is planned for a later version; v0 serves stdio only',
caps: 'optional tool groups are planned for a later version',
}

/**
Expand All @@ -58,7 +65,7 @@ const NOT_YET = {
* @return {{help: boolean, version: boolean, browser: string, headless: boolean,
* grid: (string|undefined), allowedOrigins: !Array<string>,
* blockedOrigins: !Array<string>, allowFileAccess: boolean, allowEvaluate: boolean,
* logLevel: string}}
* caps: !Array<string>, logLevel: string}}
* @throws {Error} on an unknown or invalid option
*/
function parseCommandLine(argv) {
Expand All @@ -78,6 +85,7 @@ function parseCommandLine(argv) {
isolated: { type: 'boolean' },
'allow-unrestricted-file-access': { type: 'boolean' },
'allow-evaluate': { type: 'boolean' },
caps: { type: 'string' },
'log-level': { type: 'string', default: 'warning' },
help: { type: 'boolean', short: 'h' },
version: { type: 'boolean', short: 'v' },
Expand All @@ -94,6 +102,14 @@ function parseCommandLine(argv) {
if (!LOG_LEVELS.includes(logLevel)) {
throw new Error(`--log-level must be one of ${LOG_LEVELS.join(', ')}; got ${values['log-level']}`)
}
const caps = (values.caps || '')
.split(',')
.map((c) => c.trim().toLowerCase())
.filter(Boolean)
for (const cap of caps) {
if (CAPS_NOT_YET[cap]) throw new Error(`--caps ${cap} is not supported yet: ${CAPS_NOT_YET[cap]}.`)
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 {
Expand All @@ -113,6 +129,7 @@ function parseCommandLine(argv) {
blockedOrigins: splitList(values['blocked-origins']),
allowFileAccess: !!values['allow-unrestricted-file-access'],
allowEvaluate: !!values['allow-evaluate'],
caps,
logLevel,
}
}
Expand All @@ -124,4 +141,4 @@ function splitList(value) {
.filter(Boolean)
}

module.exports = { BROWSERS, LOG_LEVELS, USAGE, parseCommandLine }
module.exports = { BROWSERS, CAPS, LOG_LEVELS, USAGE, parseCommandLine }
9 changes: 8 additions & 1 deletion lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ const TOOL_GROUPS = [
require('./tools/interact').tools,
require('./tools/bidi').tools,
require('./tools/evaluate').tools,
require('./tools/vision').tools,
require('./tools/pdf').tools,
require('./tools/storage').tools,
]

/**
Expand All @@ -43,7 +46,11 @@ const TOOL_GROUPS = [
*/
function allTools(config) {
const tools = TOOL_GROUPS.flat()
return config ? tools.filter((t) => !t.enabled || t.enabled(config)) : tools
if (!config) return tools
// Optional groups stay out of the list unless asked for: every agent pays
// for each listed tool on every turn.
const caps = config.caps || []
return tools.filter((t) => (!t.cap || caps.includes(t.cap)) && (!t.enabled || t.enabled(config)))
}

/**
Expand Down
97 changes: 97 additions & 0 deletions lib/tools/pdf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// 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 fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')

const { error } = require('selenium-webdriver')

const { ToolError, textResult } = require('./common')

/**
* Where to write a PDF: a name the agent gave, resolved against the working
* directory and kept inside it unless file access is unrestricted, or a fresh
* file in the temp directory so nothing lands in the project unasked.
*
* @param {(string|undefined)} filename
* @param {{allowFileAccess: (boolean|undefined)}} config
* @param {string=} root
* @return {string} an absolute path
* @throws {ToolError}
*/
function pdfPath(filename, config, root = process.cwd()) {
if (!filename) {
const dir = path.join(os.tmpdir(), 'selenium-mcp')
fs.mkdirSync(dir, { recursive: true })
return path.join(dir, `page-${new Date().toISOString().replace(/[:.]/g, '-')}.pdf`)
}
const target = path.resolve(root, filename)
// The directory must exist to be checked, and realpath sees through symlinks.
let dir
try {
dir = fs.realpathSync(path.dirname(target))
} catch {
throw new ToolError(`No such directory: ${path.dirname(target)}`)
}
const realRoot = fs.realpathSync(root)
const inside = dir === realRoot || dir.startsWith(realRoot + path.sep)
if (!inside && !config.allowFileAccess) {
throw new ToolError(
`${target} is outside the working directory (${realRoot}). ` +
'Start the server with --allow-unrestricted-file-access to write files anywhere.',
)
}
return path.join(dir, path.basename(target))
}

const tools = [
{
name: 'browser_pdf_save',
cap: 'pdf',
description: 'Save the page as a PDF file',
inputSchema: {
type: 'object',
properties: {
filename: {
type: 'string',
description:
'File to save to, relative to the working directory. Defaults to a new file in the temp directory',
},
},
},
async run(ctx, { filename }) {
const file = pdfPath(filename, ctx.config)
const driver = await ctx.session.driver()
await driver.switchTo().defaultContent()
let data
try {
data = await driver.printPage()
} catch (e) {
if (e instanceof error.UnsupportedOperationError || e instanceof error.UnknownCommandError) {
throw new ToolError(`${ctx.config.browser} cannot print this page to PDF here: ${e.message.split('\n')[0]}`)
}
throw e
}
fs.writeFileSync(file, Buffer.from(data, 'base64'))
return textResult(`Saved the page as ${file}`)
},
},
]

module.exports = { tools, pdfPath }
Loading
Loading