# MCP Accessibility Scanner πŸ” Accessibility checks inside your coding agent: axe scans, keyboard-focus checks and repeatable reports. ![Scanner-generated screenshot of the Weekend Workshop demo, with red boxes and rule labels marking missing image alt text, low-contrast text, an unlabeled email input and an unnamed arrow button.](https://raw.githubusercontent.com/JustasMonkev/mcp-accessibility-scanner/c908465da60c59cd3668d72186d26962806e343b/docs/assets/accessibility-demo-annotated.png) *An intentionally flawed [local demo page](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/c908465da60c59cd3668d72186d26962806e343b/docs/assets/accessibility-demo.html), checked with automated tools. These annotations were generated by `scan_page` with `annotateScreenshot: true`, not added by hand.* This MCP server lets your coding agent inspect a page, run axe checks, exercise keyboard focus and save findings for review. Automated checks don't certify WCAG compliance; manual accessibility testing is still needed. `audit_screen_reader` inspects the browser's accessibility tree, accessible names and element geometry. It does not test with an actual screen reader. ## Quickstart: connect your coding agent Install [Google Chrome](https://www.google.com/chrome/) before the first audit. The configuration below uses system Chrome; installing the npm package does not install a browser. See [browser configuration](#configuration-options) for alternatives. Install the scanner: ```bash npm install -g mcp-accessibility-scanner --allow-scripts=re2 ``` The flag allows the native `re2` dependency to install on [npm 12](https://docs.npmjs.com/cli/v12/using-npm/config/#allow-scripts). If a prebuilt binary is unavailable, its installer needs a native build toolchain; see [re2's installation notes](https://www.npmjs.com/package/re2). Add this stdio server to your coding agent's MCP configuration, then restart or reconnect the client: ```json { "mcpServers": { "accessibility-scanner": { "command": "mcp-accessibility-scanner", "args": ["--headless", "--isolated", "--output-dir", "./a11y-output"] } } } ``` The client must be able to find the installed command on its `PATH`. `--isolated` uses a fresh browser profile, not your personal Chrome session. Output paths are relative to the server's working directory; use an absolute `--output-dir` if your client starts it elsewhere. Client-specific setup and other installation methods are in the [reference below](#installation). ### Your first audit Start your app locally, then ask your connected coding agent to run these tools in order, replacing the URL with your app's address: ```text browser_navigate {"url":"http://localhost:3000"} scan_page {"annotateScreenshot":true} audit_keyboard {"maxTabs":30} audit_screen_reader {} audit_text_spacing {} ``` These are MCP tool calls, not shell subcommands. For terminal use, see [interactive mode](#interactive-repl-interactive-subcommand). `scan_page` returns text findings with JSON node details and remediation links. With `annotateScreenshot: true`, it also saves a full-page annotated PNG and returns a file resource link. It does **not** save a JSON report. `audit_keyboard`, `audit_keyboard_operation`, `audit_form_validation`, `audit_screen_reader` and `audit_text_spacing` save JSON reports and return summaries and report links; `audit_site` and `scan_page_matrix` also save JSON reports. There is no generated HTML report dashboard. Review incomplete checks, coverage warnings and the page states you haven't tested. To reproduce the screenshot, serve the demo from this repository with `python3 -m http.server 8765 --bind 127.0.0.1 --directory docs/assets`, navigate to `http://127.0.0.1:8765/accessibility-demo.html`, then run `scan_page` with `annotateScreenshot: true`. The screenshot used a 1000Γ—720 viewport (`--viewport-size 1000,720`). ## Badges [![MCP Toplist](https://mcptoplist.com/badge/io.github.JustasMonkev%2Fmcp-accessibility-scanner.svg)](https://mcptoplist.com/server/io.github.JustasMonkev%2Fmcp-accessibility-scanner) [![MseeP.ai Security Assessment Badge](https://mseep.net/pr/justasmonkev-mcp-accessibility-scanner-badge.png)](https://mseep.ai/app/justasmonkev-mcp-accessibility-scanner) ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=justasmonkev%2Fmcp-accessibility-scanner&type=Date)](https://api.star-history.com/svg?repos=justasmonkev%2Fmcp-accessibility-scanner&type=Date) ## Features ### Accessibility Scanning βœ… Automated checks for WCAG 2.0/2.1/2.2 criteria (A, AA, AAA levels)\ πŸ“„ Saved JSON audit reports and scan findings with remediation guidance\ 🎯 Support for specific violation categories (color contrast, ARIA, forms, keyboard navigation, etc.) ### Browser Automation πŸ–±οΈ Click, hover, and drag elements using accessibility snapshots ⌨️ Type text and handle keyboard inputs πŸ” Capture page snapshots to discover all interactive elements πŸ“Έ Take screenshots and save PDFs 🎯 Support for both element-based and coordinate-based interactions ### Advanced Features πŸ“‘ Tab management for multi-page workflows 🌐 Monitor console messages and network requests ⏱️ Wait for dynamic content to load πŸ“ Handle file uploads and browser dialogs πŸ”„ Navigate through browser history ## Installation You can install the package using any of these methods: Using npm: ```bash npm install -g mcp-accessibility-scanner --allow-scripts=re2 ``` npm 12 does not run dependency install scripts unless you allow them. The scanner depends on [`re2`](https://www.npmjs.com/package/re2), a native module whose install script downloads or builds `re2.node`; without it the server fails to start with `Cannot find module './build/Release/re2.node'`. Pass `--allow-scripts=re2` to `npm install -g` and `npx` (older npm versions accept and ignore the flag). For a project dependency on npm 12 or later, run `npm install-scripts approve re2` followed by `npm rebuild re2` (approving does not run the script that was already skipped). On npm 11 and earlier, install scripts run by default; use `npm rebuild re2` to restore a missing binary, provided scripts have not been explicitly disabled. To allow it for every global install on npm 12, run `npm config set allow-scripts=re2 --location=user`. ### Installation with Docker A pre-built image is available on Docker Hub. The image includes Chromium and is pre-configured for containerized use β€” no extra flags needed. **Pull from Docker Hub:** ```bash docker pull justasmonkev/mcp-accessibility-scanner ``` #### Claude Code ```bash claude mcp add mcp-accessibility-scanner -s user -- docker run -i --rm justasmonkev/mcp-accessibility-scanner ``` To persist screenshots and reports on your host, add a volume mount: ```bash claude mcp add mcp-accessibility-scanner -s user \ -- docker run -i --rm -v /tmp/mcp-output:/app/output justasmonkev/mcp-accessibility-scanner ``` Without the `-v` mount, output files only exist inside the container and are lost when it exits. #### Docker Compose ```bash docker compose up -d ``` The Compose configuration publishes the unauthenticated MCP HTTP transport on `127.0.0.1:8931` only. Do not expose this port to untrusted networks. The Compose service defines a Docker healthcheck that sends a JSON-RPC `ping` to `/mcp` and expects HTTP 200. The image itself declares no `HEALTHCHECK`, because its default stdio mode opens no HTTP listener; add the Compose healthcheck to your own HTTP deployments if you need one. #### Build from source ```bash docker build -t mcp-accessibility-scanner . ``` Images built from this Dockerfile include `tini` as an init process; Docker's `--init` flag is optional. #### Docker smoke test ```bash npm run test:docker ``` ### Installation in VS Code Install the Accessibility Scanner in VS Code using the VS Code CLI: For VS Code: ```bash code --add-mcp '{"name":"accessibility-scanner","command":"npx","args":["--allow-scripts=re2","mcp-accessibility-scanner"]}' ``` For VS Code Insiders: ```bash code-insiders --add-mcp '{"name":"accessibility-scanner","command":"npx","args":["--allow-scripts=re2","mcp-accessibility-scanner"]}' ``` ## CLI Modes The scanner can run in two modes depending on how you use it. ### MCP server (default, no subcommand) When launched without a subcommand, the process starts an MCP server that communicates over stdio. This is the mode used by MCP clients such as Claude Desktop, VS Code, and Claude Code -- you should never need to run it by hand. ```bash npx --allow-scripts=re2 mcp-accessibility-scanner # starts the MCP server (stdio) ``` All of the MCP client configuration examples in this README already use this default mode. On POSIX systems, stdin closure, SIGINT, SIGTERM and SIGHUP trigger the same graceful server cleanup. Locally owned browser processes and temporary browser directories are released; caller-supplied persistent-profile directories are retained. ### Interactive REPL (`interactive` subcommand) For manual terminal use, the `interactive` subcommand starts a readline REPL where you can call any tool directly: ```bash $ npx --allow-scripts=re2 mcp-accessibility-scanner interactive Interactive mode. Type " " to call a tool. Ctrl+D to exit. > browser_navigate {"url": "https://example.com"} > scan_page {"violationsTag": ["wcag21aa"]} > audit_keyboard {"maxTabs": 30} > audit_screen_reader {} ``` Each line is ` `. Omit the JSON to pass `{}`. When input ends (Ctrl+D or the end of piped input), calls still running finish and are printed and saved before shutdown begins. Ctrl+C, SIGINT, SIGTERM and SIGHUP start shutdown right away without waiting for running calls. Either way, closing the browser and saving the session are bounded by a 15-second shutdown limit that starts only when shutdown begins. Global browser connection flags still apply here, for example `npx --allow-scripts=re2 mcp-accessibility-scanner --headless interactive`. Use `--mobile` or `PLAYWRIGHT_MCP_MOBILE=1` to emulate a generic mobile device (`Pixel 10` for Chromium, `iPhone 17` for WebKit). It cannot be combined with `--device`, CDP attach/launch modes, remote browser endpoints, or `--extension`. Device names supplied through `--device` or `PLAYWRIGHT_MCP_DEVICE` must match a Playwright device descriptor; unknown names fail at startup. An explicit `--device` overrides `PLAYWRIGHT_MCP_DEVICE`. ### Browser extension mode Use `--extension` to connect through the current [Playwright Extension](https://github.com/microsoft/playwright/blob/main/packages/extension/README.md), which must support extension protocol v2. ```bash npx --allow-scripts=re2 mcp-accessibility-scanner --extension ``` Controlled tabs are grouped by default. Pass `--no-tab-group` with `--extension`, set `PLAYWRIGHT_MCP_NO_TAB_GROUP=1`, or use `"tabGroup": false` in the config file to leave controlled tabs in their existing groups. This also applies when selecting the extension browser provider through `--connect-tool`; it has no effect on other browser providers. Connection approval and single-client tab ownership are unchanged. The environment accepts `1`/`true` to disable grouping and `0`/`false` to enable it, overriding the config file; `--no-tab-group` takes precedence over both. This requires an extension build containing [upstream change #43814](https://github.com/microsoft/playwright/pull/43814) (commit `deb7e86`, October 31, 2026). As of November 1, the [Chrome Web Store](https://chromewebstore.google.com/detail/playwright-extension/mmlmfjhmonkocbjadbfplnigmagldckm) still lists version **0.4.0**, updated September 1, which predates this change and ignores the setting. No supporting released version is confirmed yet; use a build containing that commit until one is available. The upstream manifest is also still 0.4.0, so the version number alone does not establish support. Set `PLAYWRIGHT_MCP_EXTENSION_TOKEN` to the token shown by the extension to bypass the connection approval dialog. The relay's CDP WebSocket endpoint always requires a separate random token, generated per relay and appended automatically for the server's own connection. This CDP token is never passed in Chrome's launch arguments or extension URL; the extension approval token cannot authenticate a CDP client. Token-bypass connections are not background-safe: Chrome focuses the connection tab and window, and client-created tabs remain open after disconnect ([upstream limitation](https://github.com/microsoft/playwright/issues/42343)). With a token, the extension must connect and finish setup within 30 seconds after the connection page opens. Failed attempts release the relay so the next tool call can retry. Without a token, manual approval waits up to 5 minutes; if you miss it, the call fails, the relay is released, and the next tool call opens the connect page again. When `--user-data-dir` contains multiple Chrome profiles, the profile with the extension installed is selected automatically, preferring Chrome's last-used profile. Pass `--profile-dir-name` (or set `PLAYWRIGHT_MCP_PROFILE_DIR_NAME`) to select a profile explicitly; it requires `--user-data-dir` and accepts a Chrome profile directory name such as `Default` or `Profile 1` (see "Profile Path" at `chrome://version`). The `PLAYWRIGHT_MCP_EXTENSION_TOKEN` approval token is specific to the profile, so when selecting a profile explicitly, use the token shown in that profile. Packed extensions require an enabled record in the profile's preferences; a leftover extension directory alone does not count as installed. Profiles whose preferences mark the extension disabled or uninstalled are excluded from automatic selection and rejected for explicit selection. Explicit selection with a custom executable skips local installation checks. A whitespace-only `PLAYWRIGHT_MCP_PROFILE_DIR_NAME` is treated as unset; other string environment variables retain their existing blank-value handling. ### Discovering available tools (`list-tools` subcommand) To print the built-in tool names and descriptions (page-registered WebMCP tools require a live MCP `tools/list` request): ```bash npx --allow-scripts=re2 mcp-accessibility-scanner list-tools ``` > **Note:** Tool names like `browser_navigate` and `scan_page` are MCP tool identifiers (and REPL commands in interactive mode). They are not shell subcommands -- you cannot run `npx mcp-accessibility-scanner browser_navigate`. ## Programmatic API `createConnection` returns an MCP `Server` directly, not a wrapper with a `server` property. Its type is the SDK's `Server` from `@modelcontextprotocol/server`. Connect it with `server.connect(transport)` and release it with `await server.close()`. Passing a custom context getter transfers that context's lifecycle to the server: `browser_close` or client disconnection closes the supplied context. Its parent browser and sibling contexts remain open. Supply a dedicated context, not one whose tabs or storage must survive the MCP connection. Multiple sessions cannot use a custom getter to obtain independent contexts. ```ts import { createConnection } from 'mcp-accessibility-scanner'; import { StdioServerTransport } from '@modelcontextprotocol/server/stdio'; const server = await createConnection({ browser: { isolated: true } }); await server.connect(new StdioServerTransport()); ``` ## Configuration Here's the Claude Desktop configuration: ```json { "mcpServers": { "accessibility-scanner": { "command": "npx", "args": ["-y", "--allow-scripts=re2", "mcp-accessibility-scanner"] } } } ``` ### Advanced Configuration Set `PLAYWRIGHT_MCP_CONFIG` or pass `--config ` to load a JSON configuration file. If both are set, `--config` selects the file: ```json { "mcpServers": { "accessibility-scanner": { "command": "npx", "args": ["-y", "--allow-scripts=re2", "mcp-accessibility-scanner", "--config", "/path/to/config.json"] } } } ``` #### Exact-name tool selection ```bash npx --allow-scripts=re2 mcp-accessibility-scanner --allowed-tools browser_pdf_save --blocked-tools browser_evaluate,browser_file_upload ``` | CLI | Environment | JSON config | | --- | --- | --- | | `--allowed-tools` | `PLAYWRIGHT_MCP_ALLOWED_TOOLS` | `allowedTools` | | `--blocked-tools` | `PLAYWRIGHT_MCP_BLOCKED_TOOLS` | `blockedTools` | CLI/environment values are comma-separated exact, case-sensitive names; JSON values are arrays of strings. `allowedTools` **adds** named tools to core and enabled capabilities; it is **not a restrictive whitelist**. For example, allowing `browser_pdf_save` does not disable navigation or accessibility audits, and allowing `browser_install` explicitly enables browser downloads without `--caps install`. Omitted lists preserve existing exposure defaults. `blockedTools` wins over core tools, capabilities and `allowedTools`. Blocked tools are absent from `tools/list` and rejected on `tools/call`, even without prior listing and even when a request names a browser session. The server instructions sent at initialization stop recommending blocked tools, so clients are not directed to calls that would be rejected. If the blocked tool is the one that clears an open modal (`browser_handle_dialog` or `browser_file_upload`), the modal-state guidance names it and says it is blocked instead of offering it as the way forward; other tools keep refusing while the modal is open. The policy applies to standalone, CDP, extension, provider-switching and VS Code backends, over stdio and HTTP. `browser_session_open`, `browser_session_close`, accessibility tools and the proxy-owned `browser_connect` are not exempt. Allowing a tool does not bypass a provider's limitations or enable a connection mode; `browser_connect` still requires a mode that supplies it. Precedence is **CLI > environment > config file**, independently for each list. A higher-precedence list replaces the lower one; lists are not merged. `[]` in JSON, `--blocked-tools=`, or an empty environment value explicitly clears that list (likewise for `allowedTools`). Empty lists add/block nothing; duplicates are harmless. Blank entries inside nonempty lists, non-array JSON values, unknown names (including generated `webmcp_*` page-tool names) and wildcards fail at startup. Page-provided WebMCP tools remain discoverable by default and are **outside this policy**. Their generated `webmcp__` names hash an identity minted for each server run, document and registration, so a name copied from `tools/list` never matches after a restart or navigation. Instead of accepting a value that could never take effect, startup rejects `webmcp_*` names in both lists like any other unknown name. Page tools keep their existing scope and staleness checks; a persistent page-action policy would need a stable registration key and is not part of this feature. This controls dispatch by tool name, not equivalent actions through other tools: for example, blocking `browser_click` does not prevent a page click through `browser_evaluate`. See the [adoption decision](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/decisions/002-tool-filtering.md). ##### Compact audit-focused MCP setup Use the [compact audit configuration](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/configs/compact-audit.json) for directly navigable pages on a stateful connection. Save that JSON locally and pass its absolute path to the server: ```sh mcp-accessibility-scanner --headless --isolated --config /path/to/compact-audit.json ``` With no extra capabilities, the profile keeps ten tools: navigation, snapshot and screenshot; Axe and retained findings; site and matrix scans; keyboard, screen-reader and text-spacing audits. It uses `blockedTools` because `allowedTools` adds to the defaults rather than replacing them. Use the default configuration for sign-in, clicks, typing, dialogs, uploads, scripted keyboard or form scenarios, tab/viewport management, console/network inspection, or session tools over stateless HTTP. This profile is not a security boundary: page-provided WebMCP tools may still appear after navigation. | Built-in catalog | Tools | Serialized `tools/list` result | | --- | ---: | ---: | | Default | 37 | 54,049 bytes | | Compact | 10 | 24,747 bytes | Measured over stdio with scanner 5.0.1, before navigation, with no extra `--caps`: UTF-8 bytes of `JSON.stringify(await client.listTools())`. The 54.2% cut is in discovery bytes, not per-turn tokens. Reproduce it with `npm run build && node bench/tool-surface-bench.mjs`. #### Configuration Options Relative filesystem paths in a JSON config file resolve from the directory containing that file, not the server's working directory. This applies only to these fields: | Config field | Paths resolved from the config directory | | --- | --- | | Top level | `outputDir` | | `browser` | `userDataDir`, each `allowedUploadDirs` entry, `cdpLaunch.cwd` | | `browser.launchOptions` | `executablePath`, `downloadsPath`, `tracesDir`, `artifactsDir` | | `browser.contextOptions` | String `storageState`, `recordHar.path`, `recordVideo.dir`, each `clientCertificates` entry's `certPath`, `keyPath`, `pfxPath` | For example, `/project/config/scanner.json` with `"outputDir": "./reports"` writes to `/project/config/reports`, regardless of where the server starts. Session logs and server-managed traces also use `outputDir`. Upload roots must still exist and are canonicalized after merging. Absolute paths and `storageState` objects are unchanged. Commands such as `browser.cdpLaunch.command`, launch arguments, profile names, URLs and URL filters are not rewritten. Relative CLI and environment paths still use the server's working directory, as do programmatic `Config` paths. Precedence remains **CLI > environment > config file**, so an override is never rebased against the config directory. The `--config` filename itself is still relative to the server's working directory. **Migration:** Earlier versions resolved file-configured relative paths from the server's working directory. If your config relied on that behavior, adjust those paths relative to the config file's directory or use absolute paths. CLI and environment values need no migration. Create a `config.json` file with the following options: ```json { "browser": { "browserName": "chromium", "launchOptions": { "headless": true, "channel": "chrome" }, "cdpLaunch": { "command": "open", "args": ["-a", "Slack", "--args", "--remote-debugging-port={port}"], "startupTimeoutMs": 30000 } }, "timeouts": { "navigationTimeout": 60000, "defaultTimeout": 5000, "settle": 500, "idle": 0 }, "network": { "allowedOrigins": ["example.com", "trusted-site.com"], "blockedOrigins": ["ads.example.com"] }, "snapshot": { "boxes": true } } ``` **Available Options:** - `browser.browserName`: Browser to use (`chromium`, `firefox`, `webkit`) An open `
` nested inside a closed `
` stays hidden from `browser_snapshot`, `browser_find`, `browser_verify_element_visible` and `browser_verify_text_visible` until the outer `
` is opened, in Chromium, Firefox and WebKit on the pinned Playwright 1.65.0. With WebKit on Playwright 1.63.0 its contents counted as visible ([upstream fix](https://github.com/microsoft/playwright/pull/42951)); `tests/details-visibility.integration.test.ts` checks each engine. See the [verification notes](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/issue-verification-2026-09.md#webkit-nested-details-visibility-246). - `browser.allowedUploadDirs`: Restrict files sent by `browser_file_upload` and `browser_drop` to regular files inside these directories, including resolved symlink targets. Restricted uploads and drops use a checked file handle and accept up to 50 MiB total per call. Unset allows any path; `[]` denies all file uploads and drops (text-only drops still work). Blank list entries are rejected. CLI: `--allowed-upload-dirs` (semicolon-separated; `""` denies all), env: `PLAYWRIGHT_MCP_ALLOWED_UPLOAD_DIRS` (empty string denies all). The list must be an array, not `null`. Roots must exist at startup: their canonical paths are resolved once and retained for the server's lifetime, so retargeting a configured symlink does not grant access to a new tree. Non-empty upload allowlists require macOS or Linux with `/proc/self/fd` available. macOS blocks ancestor symlinks during the file open; Linux checks the opened descriptor's path. Other platforms reject restricted file uploads and drops rather than rely on race-prone pathname checks. Unrestricted uploads, deny-all lists, and text-only drops keep working on all platforms. - `browser.launchOptions.headless`: Run browser in headless mode (default: `true` on Linux without display, `false` otherwise) - `browser.launchOptions.channel`: Browser channel (`chrome`, `chrome-beta`, `msedge`, etc.) - `browser.contextOptions.clientCertificates`: With client certificates, a configured launch proxy is also applied to fresh contexts unless `browser.contextOptions.proxy` explicitly overrides it. With certificates, Playwright routes every request through its certificate interceptor, which matches `proxy.bypass` entries only as domain suffixes: `example.com` and `.example.com` both bypass `example.com` and its subdomains, and IP addresses match exactly. Entries using browser-specific syntax (wildcards such as `*.example.com`, ports, IP ranges, ``) would be ignored there, so they are rejected before launch. Playwright 1.63.0 ignored every bypass entry in the interceptor; `tests/client-certificate-proxy-probe.mjs` checks bypassed and proxied routes on the pinned version. For a fresh context on a remote browser, configure its proxy explicitly; a proxy inherited only from that browser cannot be inspected. Existing attached contexts retain their current settings. Local persistent Firefox cannot combine client certificates with a configured proxy on Playwright 1.65.0: it sends requests without the configured certificate. This combination is rejected before launch. Explicitly use isolated Firefox or Chromium if suitable for your workflow; the server does not change browser, proxy or persistence mode automatically. Firefox without certificates or without a proxy remains supported. - `browser.launchOptions.proxy`: Browser proxy (CLI: `--proxy-server`, `--proxy-bypass`; env: `PLAYWRIGHT_MCP_PROXY_SERVER`, `PLAYWRIGHT_MCP_PROXY_BYPASS`). Credentials in a CLI or environment proxy URL, such as `http://user:password@myproxy:3128`, are moved into `proxy.username` and `proxy.password` so the browser can answer `407 Proxy Authentication Required`; percent-encode reserved characters such as `@`, `:` or `/` in them. A proxy set in the config file keeps its explicit `username` and `password` fields. **Proxy credentials and website authentication:** Playwright 1.65.0 sends proxy credentials only in answer to a proxy `407` challenge, never to a website's `401` challenge ([upstream fix](https://github.com/microsoft/playwright/pull/43482)); Playwright 1.63.0 leaked them, and the server's former startup warning was removed with the upgrade. Use `browser.contextOptions.httpCredentials` for website authentication. Without it, full Chromium fails a website's `401` with `net::ERR_INVALID_AUTH_CREDENTIALS`, with or without a proxy, while Firefox and WebKit show the `401` page. `tests/proxy-credentials.integration.test.ts` checks the credentials reach only the proxy. - `browser.launchOptions.chromiumSandbox`: Defaults to `false` for downloaded Chromium builds on Linux because they lack the setuid sandbox helper, and `true` otherwise. Remote and VS Code endpoints choose on the remote host. An explicit config or `PLAYWRIGHT_MCP_SANDBOX` value wins; `--no-sandbox` always disables it. - `browser.cdpEndpoint`: Attach to an already-running Chromium-family app with CDP enabled - `browser.cdpHeaders`: Map of HTTP headers to send with the CDP connect request, e.g. `{ "Authorization": "Bearer " }`, for endpoints that require header-based authentication - `browser.cdpTimeout`: Maximum time in milliseconds to wait when connecting to the CDP endpoint (default: `30000`) - `browser.cdpLaunch`: Launch a Chromium-family desktop app with CDP enabled, wait for the endpoint, and manage the child process lifecycle. `startupTimeoutMs` (default `30000`) bounds the whole wait, attach attempts included; each attempt also stops at `browser.cdpTimeout`. If the command cannot be started (for example a missing application) or exits with a nonzero code or a signal before the endpoint answers, the tool call fails right away with that error and the server keeps running; a clean exit (code `0`, as with `open -a `) is treated as a hand-off and the wait continues. - Numeric settings must be integers in range, whether they come from the CLI, the environment, or the config file: `cdpLaunch.startupTimeoutMs` from 1 and `cdpTimeout`, `timeouts.navigationTimeout`, `timeouts.defaultTimeout` and `timeouts.settle` from 0 (`cdpTimeout: 0` still disables the connect timeout), all up to `2147483647` ms; `cdpLaunch.port` from 1 and `server.port` from 0, up to `65535`. A mistyped value such as `PLAYWRIGHT_MCP_CDP_LAUNCH_STARTUP_TIMEOUT=30s` stops startup with an error instead of being ignored or disabling a timeout. A JSON `null` is rejected the same way rather than treated as omitted; leave the key out to use its default. - CDP attach modes preserve the target browser's existing default-context settings instead of applying Playwright's defaults. - `browser.contextOptions.storageState`: Start a fresh context from a recorded Playwright storage state. Imports into existing CDP or VS Code contexts are rejected; use `--isolated` for CDP or sign in interactively. If the browser exposes no context, the server creates one with the state. CDP sessions joining that same server-created context inherit its live state without resetting it. In the default persistent mode, pages the profile has open are replaced with blank tabs before the state lands and reopened afterwards; if new pages keep opening for 30 seconds, context creation fails with an error instead of waiting indefinitely. - `browser.profileDirName`: Chrome profile directory name used in extension mode, for example `Default` or `Profile 1` (CLI: `--profile-dir-name`, env: `PLAYWRIGHT_MCP_PROFILE_DIR_NAME`). Requires `--user-data-dir` and extension mode (`--extension` or `--connect-tool`); defaults to the last-used profile that has the extension installed. - `timeouts.navigationTimeout`: Maximum time for page navigation in milliseconds (default: `60000`) - `timeouts.defaultTimeout`: Default timeout for Playwright operations in milliseconds (default: `5000`) - `timeouts.settle`: How long to wait after every action for triggered work to settle before responding (default: `500`). With a positive settle delay, an action that finishes quietly is first watched for up to 100ms (or the settle delay, whichever is shorter) so scheduled network work can still be awaited before the settle delay. - `timeouts.idle`: Release the default browser context after this many idle milliseconds (default: `0`, disabled). Accepts integers from `0` to `2147483647`. - `network.allowedOrigins`: List of host patterns to allow (blocks other HTTP(S) requests and page WebSockets when nonempty), for example `example.com` or `*.example.com`. An entry without a port allows only the scheme's default port, so include the port for nondefault ports. - `network.blockedOrigins`: List of host patterns to block; blocklist matches take precedence over the allowlist. An entry without a port blocks that host on every port (`ads.example.com` also blocks `ads.example.com:8080`); an entry with a port, such as `ads.example.com:8080`, blocks only that port. - Port and trailing-dot matching for both lists: host patterns, including wildcards, match only the request's hostname, never its port (`example.*` in the allowlist does not allow `example.com:8080`). An entry with a port matches requests whose effective port is that port, including a scheme's default port (`example.com:443` matches `https://example.com/`, but not `http://example.com/`). Ports are compared by numeric value, so `example.com:0443` is the same as `example.com:443`. An entry whose port is not a number, such as `example.com:*`, is matched as a glob against the whole request URL. A host written with one trailing dot (`ads.example.com.`), whether in a request or an entry, names the same host as `ads.example.com`. Spellings with several trailing dots (`ads.example.com..`) are not equivalent: an allowlist entry written that way matches only that literal host, while blocklist matching strips every trailing dot. - `snapshot.boxes`: Include each element's viewport-relative bounding box as `[box=x,y,width,height]` in snapshots (default: `false`; CLI: `--snapshot-boxes`, env: `PLAYWRIGHT_MCP_SNAPSHOT_BOXES=1`) - `imageResponses`: `allow` (default) returns text and images; `omit` excludes images; `only` omits text from successful responses containing images. Errors, browser lifecycle notices, and responses without images (including full-page screenshots) keep their text. Structured results and resource links are always preserved. In `only` mode, screenshot save-path text, generated code and any accompanying text-only findings are omitted; use `allow` if you need them. Interactive mode rejects `only` because its REPL prints text only; use `allow` or `omit` there. `auto` remains a legacy alias for `allow`. CLI: `--image-responses only`; env: `PLAYWRIGHT_MCP_IMAGE_RESPONSES=only`. Precedence: CLI, then environment, then config file. - `server.authToken`: When set, Streamable HTTP requests (`--port`) require `Authorization: Bearer ` or return `401` (env: `PLAYWRIGHT_MCP_AUTH_TOKEN`). Blank or malformed tokens fail at startup. The scheme is case-insensitive; the token is exact. Bearer auth does not encrypt traffic: authenticated listeners must bind to loopback, such as `--host 127.0.0.1`; use a TLS reverse proxy for remote access. The printed client config includes a header placeholder to replace locally, without logging the secret. Unset keeps unauthenticated access. - `filePaths`: Optional `relative` or `absolute` rendering for output paths in screenshot/PDF results and generated code, report metadata, annotated/keyboard screenshots, and download summaries. Relative paths are based on the **server working directory**, not the client workspace or output directory. File writes, stored report contents, and absolute `file://` resource URIs are unchanged. Omitted preserves legacy rendering: configured relative output directories produce relative paths, while default temp output paths are absolute (unlike upstream Playwright’s relative default). CLI: `--file-paths absolute`; env: `PLAYWRIGHT_MCP_FILE_PATHS=absolute`. Precedence: CLI, then environment, then config file. - `outputDir`: Directory for output files β€” reports, screenshots, traces, and session logs (CLI: `--output-dir`, env: `PLAYWRIGHT_MCP_OUTPUT_DIR`). Defaults to a fresh directory under the system temp folder, resolved once per server run so all of a run's artifacts land together. The output location is always server configuration; the deprecated MCP roots capability (client workspace folders) is no longer consulted. - `redactUrlParams`: Optional array of URL query/fragment parameter names whose nonempty values are rendered as `REDACTED` (CLI: `--redact-url-params code,access_token`; env: `PLAYWRIGHT_MCP_REDACT_URL_PARAMS=code,access_token`). Defaults to no URL-parameter redaction. Names match literally and case-insensitively, without decoding keys; repeated matches, relative links and hash-route query parameters are included. Empty values and unselected parameters are preserved. CLI overrides environment, which overrides the config file; lists replace rather than merge. `[]` in JSON or an empty CLI/environment value clears a lower-precedence list. Non-array config values, non-string entries and blank names fail before browser startup. See [URL redaction coverage](#url-redaction-coverage) before sharing output or artifacts. Origin restrictions require locally launched Chromium (isolated or persistent). Firefox/WebKit and CDP, remote, extension, VS Code or custom-context connections reject restrictions instead of silently applying a partial policy or affecting unrelated browser contexts. Without origin restrictions those modes are unchanged. Enforcement begins when the browser context is acquired and the policy is installed; it does not retroactively filter startup traffic or existing connections (for example, during persistent-profile restoration). HTTP(S) filtering then covers each redirect hop, including subresources, frames and popups, while preserving browser redirect URLs, methods and cookies. Page WebSockets are checked before connecting to a server. **Worker-created WebSockets are not filtered by Playwright's page WebSocket routing.** These options are not a complete network security sandbox; use external network isolation when worker sockets or other browser traffic must be restricted. CDP launch settings combine across layers as follows: the application (`command`, `args`, `cwd`, and the config file's `env`) comes as a unit from the highest-precedence layer (CLI > environment > config file) that sets a command, because arguments written for one application are unsafe to pass to another. `port` and `startupTimeoutMs` merge field by field with the same precedence, so `--cdp-launch-command app` with `PLAYWRIGHT_MCP_CDP_LAUNCH_STARTUP_TIMEOUT=45000` uses that timeout (and a mistyped one fails startup), and a config file may set only `port` or `startupTimeoutMs`. Setting `args` or `cwd` in a layer without a command while another layer sets the command fails startup instead of being ignored, as does any CDP launch setting (from the config file, the environment or the CLI, such as `--cdp-launch-port` alone) when no layer sets a command. CLI equivalents are also available: `--cdp-launch-command`, `--cdp-launch-args`, `--cdp-launch-cwd`, `--cdp-launch-port`, `--cdp-launch-startup-timeout`, `--cdp-endpoint`, `--cdp-header` (repeat for multiple headers, e.g. `--cdp-header "Authorization: Bearer "`), and `--cdp-timeout`. The CDP headers and timeout can also be set via the `PLAYWRIGHT_MCP_CDP_HEADERS` (one `Name: Value` entry per line) and `PLAYWRIGHT_MCP_CDP_TIMEOUT` environment variables. If CDP attachment times out after the WebSocket connects, an existing tab may be blocking Playwright initialization ([upstream report](https://github.com/microsoft/playwright/issues/42730)). The pinned Playwright 1.65.0 fixes the crashed-renderer attach hang and omits crashed tabs, as `tests/cdp-attach.integration.test.ts` verifies. A genuine native proactive-discarded tab is different: attachment completes and healthy tabs remain usable, but the discarded tab is still exposed. The strict headed gate in `tests/cdp-discard.integration.test.ts` records that unresolved omission requirement without reloading the tab or changing its native discard state. For `--cdp-endpoint`, use an explicit positive `--cdp-timeout` to bound initialization; `0` disables it and attachment can wait forever. `--cdp-launch-startup-timeout` bounds the whole launched-application attempt, with each attachment also bounded by `--cdp-timeout`. On failure, launch mode stops only its own application. `noDefaults` and `--isolated` do not skip initialization of existing tabs. If a tab blocks attachment, reload or close it yourself, or attach to a separate disposable browser; the server does not close or reload browser-owned tabs to repair attachment. See the [verification notes](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/issue-verification-2026-09.md#cdp-attach-and-numpad-keys-244). Playwright does not support back/forward-cache (BFCache) restoration: an attached browser with BFCache enabled can return unusable references and omit iframe contents after back navigation. This was reproduced with full Chromium, Chrome, and Edge on Playwright 1.63.0, and again with full Chromium 158 on the pinned Playwright 1.65.0 (`MCP_TEST_ENABLE_BFCACHE=1`). For a browser you launch yourself, include `--disable-back-forward-cache` before attaching, or use the server's normal browser launch mode, which retains Playwright's default flag. The server does not change an attached browser's flags or replace back navigation with a reload. See the [upstream maintainer's explanation](https://github.com/microsoft/playwright/issues/42777#issuecomment-5739095543), [Playwright's BFCache limitation](https://playwright.dev/docs/navigations#backforward-cache-bfcache), and the [verification and reproduction command](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/issue-verification-2026-09.md#history-references-231). CDP attachment excludes unsupported `shared_worker` targets from Playwright's browser-level auto-attach. Chromium 158 can otherwise crash when another inspector retains a terminated shared worker. Application shared workers keep running; `tests/cdp-worker.integration.test.ts` checks live-worker messages, healthy-tab state and follow-up browsing in both bundled headless shell and full Chromium. A nonce-protected loopback relay retains Playwright's standard URL-based remote file-upload behavior. Channel lookup, HTTP discovery and the upstream WebSocket transport reuse exported internals from the pinned Playwright version, so dependency updates must revalidate these contracts. HTTP listeners accept `Host` headers for loopback aliases, the bound non-wildcard address, and the configured hostname (`--host`, `server.host`, or `PLAYWRIGHT_MCP_HOST`). A named host must resolve to an address on the server to bind; other hostnames remain forbidden. Wildcard binds (`--host 0.0.0.0` or `--host ::`) do not allow arbitrary hostnames or the wildcard address itself: use a loopback hostname or bind a specific hostname/address. Missing or invalid `Host` returns `400`; disallowed hosts return `403`. When present, `Origin` must use HTTP and exactly match the normalized `Host` hostname and port; HTTPS or a different authority returns `403`. These checks also apply with bearer authentication, which still requires a loopback listener. For remote HTTP access, configure the TLS reverse proxy explicitly. For example, with the MCP server bound using `--host 127.0.0.1 --port 8931` and `PLAYWRIGHT_MCP_AUTH_TOKEN` set: - Accept only your configured public hostname over HTTPS and forward `/mcp` to `http://127.0.0.1:8931/mcp`. - Set the upstream `Host` header to `127.0.0.1:8931`, not the public hostname. Forward the client's `Authorization` header unchanged; do not inject a shared token for unauthenticated clients. - Before removing `Origin`, reject any non-empty value outside your explicit trusted HTTPS origin list (for example, `https://mcp.example.com`). Allow absent `Origin` for non-browser clients. Then remove `Origin` upstream, or rewrite it to `http://127.0.0.1:8931`. Never strip arbitrary origins without checking them first. - Disable response buffering for SSE streams. Browser clients on a different origin also need a narrowly scoped CORS policy at the proxy. The server does not trust `Forwarded` or `X-Forwarded-*` to bypass its checks. Preserving the public `Host` or HTTPS `Origin` upstream returns `403`, even with a valid bearer token. Unexpected HTTP request setup failures, including stateful initialization, return a generic error with HTTP status `500`. Parsed legacy JSON-RPC requests retain their IDs, batch errors omit notifications, and notification-only failures have an empty response body. Failed or rejected initialization disposes its unregistered backend. If the request body is still unread or the response has already started, the connection is closed instead of remaining available for reuse. Caller-supplied screenshot, PDF, find-result, scan-page-matrix, and audit report filenames use a no-clobber policy: an existing file causes the tool call to fail instead of being overwritten. Windows-reserved basenames and names ending in a dot or space are rejected on every platform so configured names behave consistently across hosts. Failed download saves are reported as tool errors in the current or next response, including after the tab closes; failed entries do not advertise a saved file or an ongoing download. The server retains up to 20 bounded error messages between responses and reports any omitted count. Full Chromium-family browsers on Playwright 1.63.0 had [verified native crashes after persistent-profile relaunch](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/issue-verification-2026-09.md#persistent-profile-downloads-230). On the pinned Playwright 1.65.0, bundled Chromium 158 relaunched and saved downloads on Linux; Chrome for Testing 153.0.8010.12, a build already on that crash list, still crashed. Branded Chrome and Edge are checked by the Windows CI matrix. Error reporting does not fix a native crash. The explicit `--isolated` control passed, but does not preserve a profile between launches; use recorded storage state when needed for authentication. Existing profiles and browser defaults are preserved. Use `--timeout-settle` or `PLAYWRIGHT_MCP_TIMEOUT_SETTLE` to override the post-action settle delay. CLI values take precedence over environment and file configuration, including `0`. Empty or whitespace-only numeric timeout environment variables are ignored, preserving file configuration or defaults. The default remains `500` ms. Zero skips the settle delay and briefly allows pending browser events to arrive. The server still waits for observed requests and main-frame navigations, but can return before delayed page updates. Use `--timeout-idle 300000`, `timeouts.idle`, or `PLAYWRIGHT_MCP_TIMEOUT_IDLE` to release the default browser after five idle minutes. Shared contexts stay open while any client is working; the idle window starts after the last tool call or download finishes. Explicit recordings prevent idle release until `browser_stop_recording` finishes; passive `--save-session` capture does not. Cleanup finalizes traces. The next browser tool call reopens the connection and includes a note to navigate again and refresh element references. Attached CDP, extension, and VS Code browsers are disconnected; their external pages remain open. Close and session-management tools and `get_scan_findings` do not relaunch an idle browser. Explicit `browser_session_open` handles keep their separate `PLAYWRIGHT_MCP_BROWSER_SESSION_TTL_MS` behavior. Zero disables this feature; blank environment values leave the existing configuration unchanged. The VS Code `browser_connect` tool accepts only `playwright` or `playwright-core` libraries and loopback WebSocket URLs. `connectionString` and `lib` are optional strings: send both, non-blank, to switch providers, or omit both to disconnect. Supplying only one of them, a blank value, `null`, or only unrecognized fields is rejected and keeps the current provider. Set `PLAYWRIGHT_MCP_VSCODE_ALLOW_REMOTE=1` to allow remote endpoints, which must use `wss:`. URL userinfo credentials are rejected. #### HTTP Heartbeat When the server runs with `--port`, it sends MCP heartbeat pings after a Streamable HTTP client opens the optional event stream. POST-only clients stay connected without heartbeat because server-initiated requests cannot reach them. Set `PLAYWRIGHT_MCP_PING_TIMEOUT_MS` to override the default `5000` ms timeout, or to `0` or any negative value to disable heartbeat pings. A client that answers `ping` with a JSON-RPC "method not found" error is treated as alive: the server stops heartbeating that session instead of closing it. Only an unanswered ping (timeout) or a transport failure closes the session. Independently of the heartbeat, an `Mcp-Session-Id` session with no request in flight and no open event stream expires after 30 idle minutes, so a client that disappears without sending `DELETE` does not hold its browser forever; every request restarts that window, and a client whose session expired gets `404 Session not found` and must initialize again. #### Clients without the initialize handshake Clients on the MCP 2026-07-28 revision no longer send the `initialize` handshake. With `--port`, requests carrying the revision's per-request `_meta` envelope are served natively on the 2026-07-28 protocol: `server/discover` is answered (so clients negotiating with `versionNegotiation: 'auto'` or a `2026-07-28` pin connect directly), results carry `resultType` and the SEP-2549 cache fields β€” dynamic browser tool lists use the conservative `ttlMs: 0` default instead of a one-hour cache β€” and the SEP-2243 standard headers (`MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`) are validated against the request body. Older handshake-free clients (2025-era requests without the envelope) are served statelessly as before. In both cases requests receive no heartbeat pings, and in the modes where the server creates browser contexts itself each request runs against a fresh default browser session: with the default persistent profile the per-request default context runs in its own disposable profile (like an explicit browser session), so parallel handshake-free requests do not contend for the stable profile β€” and the stable profile's sign-in state is not visible to them β€” while `--isolated`, remote endpoints and isolated CDP modes mint a fresh context per request anyway. Modes that reuse one live browser context are the exception: `--extension` (and a `browser_connect` or VS Code session switched to a connected-browser provider) and CDP attach without `--isolated` serve every handshake-free request from the same shared context, so its tabs, cookies and storage persist across requests β€” the same sharing that makes these modes refuse `browser_session_open` (in `--vscode` serving the session tools are the exception: they are host-scoped and keep running against the default provider even while switched β€” see [Browser Session Tools](#browser-session-tools)). With a pinned `--cdp-launch-port`, only one launched application can be served at a time, so a second handshake-free request arriving while another request's browser context is still live is rejected with a clear error instead of silently attaching to the first request's application. With `--user-data-dir`, each handshake-free request launches a browser in the one configured profile: the profile's state persists across requests, and parallel requests contend for its browser lock and can fail with "Browser is already in use". Elsewhere, browser state that must persist across handshake-free requests belongs in an explicit browser session β€” a `browserSessionId` handle minted by `browser_session_open` in one request resolves in later ones (see [Browser Session Tools](#browser-session-tools)). Clients that do send `initialize` keep the classic `Mcp-Session-Id` session behavior unchanged. When several such stateful clients are connected at once in the default persistent-profile mode, the first client's default context holds the stable profile β€” concurrent clients' default contexts run in their own disposable profiles (without the stable profile's sign-in state) until it is freed, instead of failing with "Browser is already in use". ## Auditing pages behind a login Most real audits target pages that only exist for a signed-in user. There are two ways to get there. ### Interactive route (no setup) Keep every step in the same browser session. Within that session, `audit_site` crawls in a temporary tab of the same browser context, so cookies and local storage created while you drive the browser are available to the crawl: ```text 1. browser_navigate to the login page 2. browser_fill_form / browser_click to sign in 3. browser_navigate to the first page you want audited 4. audit_site β€” the crawl inherits the session you just created ``` The interactive CLI, stdio MCP and initialized stateful HTTP connections can use their default session for this sequence. **Handshake-free HTTP clients must call `browser_session_open` first and pass the returned `browserSessionId` to every navigation, interaction and scan call** when using a mode that creates contexts per request. Otherwise the next request starts a new default context and loses the login and page state. Shared-context modes such as `--extension` and non-isolated CDP attach reject `browser_session_open`; use their shared context or a stateful connection instead. See [Browser Session Tools](#browser-session-tools) for mode-specific behavior. With the default persistent profile, sign-in state also survives across server restarts, so you usually only sign in once. The default profile is keyed to the server's working directory, so each workspace's server keeps its own sign-in state β€” servers launched for different workspaces neither share cookies nor contend for the same profile. ### When a login form does not advance `browser_fill_form` stops when a field opens a native dialog or file chooser, returns the modal-handling guidance, and reports how many later fields were not attempted. After handling the modal, submit those remaining fields again; the form does not resume filling them in the background. - Take a fresh `browser_snapshot` after a rerender and use its current field references. Wait for an application-specific ready message with `browser_wait_for` before entering data. - `browser_fill_form` and ordinary `browser_type` use Playwright's `fill`. If the application requires individual key events, clear the field with `browser_type` and `text: ""`, then use `browser_type` with `slowly: true`. Slow typing appends characters; it does not clear an existing value. - Verify an authenticated page or account-specific element before scanning. A filled field or successful click is not proof of a successful login. Inspect `browser_console_messages` and `browser_network_requests` if submission fails; avoid sharing passwords, tokens or private response bodies in bug reports. - In Docker, the browser runs inside the container: `localhost` names the container, not your host's development server. Use a host address reachable from that container and configure the development server to accept that specific address. Check its bind address, allowed hosts and authentication origin/redirect settings; do not disable host checks or widen CORS as a blanket fix. Direct DOM value assignments can bypass application event handlers, and synthetic setters are not a general fix for controlled inputs. Report the scanner version, browser mode, exact tool arguments (with secrets removed) and a minimal local reproduction if the standard interactions still fail. ### Storage state route (repeatable, CI-friendly) Record a session once with Playwright's codegen, then hand the file to the server: ```bash npx playwright@1.65.1 codegen --save-storage=auth.json https://example.com/login ``` Sign in in the opened browser, then close it β€” `auth.json` now holds the cookies and local storage. Pass it to the server with the CLI flag, the environment variable, or the config file: ```bash npx --allow-scripts=re2 mcp-accessibility-scanner --isolated --storage-state ./auth.json ``` ```bash PLAYWRIGHT_MCP_ISOLATED=true PLAYWRIGHT_MCP_STORAGE_STATE=./auth.json npx --allow-scripts=re2 mcp-accessibility-scanner ``` ```json { "browser": { "isolated": true, "contextOptions": { "storageState": "./auth.json" } } } ``` > **Every supported mode handles the state β€” by applying it or refusing it.** > > **Existing-context safety restriction:** importing into an existing context is rejected before taking a rollback snapshot or resetting any storage. On Playwright 1.63.0, snapshot capture could execute service-worker-served scripts for a previously visited origin whose tab was no longer open ([upstream fix](https://github.com/microsoft/playwright/pull/42664)). The restriction is kept on the pinned Playwright 1.65.0 until that path is revalidated. Use a fresh context, or omit `--storage-state` and sign in interactively. Service workers are not disabled. Lifting it also requires passing the recorder/shared-client checks in [#218](https://github.com/JustasMonkev/mcp-accessibility-scanner/issues/218) and IndexedDB checks in [#224](https://github.com/JustasMonkev/mcp-accessibility-scanner/issues/224). > > **IndexedDB `Map` and `Set` records:** Playwright 1.63.0 lost `Map` and `Set` contents in `storageState({ indexedDB: true })`, restoring them as empty plain objects ([upstream fix](https://github.com/microsoft/playwright/pull/42707)). On the pinned Playwright 1.65.0, both `newContext({ storageState })` and `setStorageState()` preserved `Map` and `Set` types and entries with Chromium 158.0.8127.18, Firefox 159.0 and WebKit 27.2 on Linux. The real-browser regression in `tests/browser-failures.integration.test.ts` checks that rejecting an import leaves the original Map/Set records intact and that isolated JSON IndexedDB imports still work. > > - **Fresh-context modes** (`--isolated`, the remote-endpoint mode, or either CDP mode combined with `--isolated`): the context is created with the storage state directly. > - **Default persistent-profile mode with `--storage-state`**: the session runs in a fresh, disposable profile β€” unique to that session and removed when it closes β€” built from the state, so the recorded state is provably the only session data (without `--storage-state` the regular persistent profile is used and survives restarts, as before). Any page the launch opened (for example from a URL in `browser.launchOptions.args`) is parked on a blank replacement before the state lands, then the replacement is navigated to the same URL, so a still-running anonymous page cannot overwrite the recorded identity and a scan never reads its DOM. This also means `--storage-state` cannot be combined with `--user-data-dir` (a user-supplied profile carries its own session and will not be wiped; the server refuses the combination). > - **CDP modes without `--isolated` and the VS Code provider**: `--storage-state` is rejected when the browser already has a context. Add `--isolated` in CDP mode to create a fresh context; otherwise omit the state and sign in interactively. If the browser exposes no context, the server creates one with the state. CDP sessions joining that same server-created context inherit its live state without resetting it. > - **`--extension`** (with or without `--isolated`) refuses storage imports entirely: it works through the browser you are already running, where wiping cookies to install a recorded state is not an acceptable side effect, so the server refuses to start rather than doing that silently. There, sign in interactively instead β€” the persistent profile also keeps the session across restarts. ### Keep the crawl from destroying its own session `audit_site` excludes `logout|signout` by default, which is not enough for most applications. Add anything else that ends or changes the session before you start the crawl: ```json { "excludePathPatterns": ["logout|signout", "account/(close|delete)", "sessions/revoke", "/switch-(locale|account|org)"] } ``` Note that `excludePathPatterns` replaces the default rather than extending it, so repeat `logout|signout` in your list. If a session cookie disappears anyway, `audit_site` says so instead of reporting a confident, wrong audit: the result starts with a `WARNING: cookie(s) … disappeared while loading ` line, and both the JSON report and the structured content carry a `sessionLosses` list naming, for each lost cookie, the page that dropped it β€” the page reached after any redirect, and reported even when that page failed to finish loading. When pages are audited concurrently, any page loading at the same time may have been the one, so those pages are listed in the entry's `concurrentUrls` and in the warning; re-run with `concurrency: 1` to pin the loss on one page. If one of the lost cookies was the session, every page scanned after that point was audited as a signed-out user β€” exclude the offending URL, sign in again, and re-run. The check compares which cookies the crawled URLs carry, not their values, so a rotating CSRF token never reads as a lost session. A cookie the browser deleted at its own stated expiry is ignored for the same reason β€” Cloudflare's `__cf_bm` lives 30 minutes and would otherwise warn on any longer crawl. Beyond that no attempt is made to tell an authentication cookie from any other: nothing in a cookie marks it as one, so any cookie the crawl started with and later lost is reported. Monitoring does not stop at the first loss β€” each cookie is reported once, at the URL where it vanished, so an analytics cookie expiring early cannot mask the session cookie being dropped later. URLs discovered mid-crawl join the cookie tracking before they are visited, so a session cookie scoped to a path below the start URL (say `/app`) is watched too. ## Skills over MCP The server also publishes [Agent Skills](https://agentskills.io/specification) alongside its tools, using the MCP skills extension (`io.modelcontextprotocol/skills`, SEP-2640). A client that supports skills, such as Claude or Claude Code, loads a skill only when the task needs it. The skill teaches the client the audit workflow, so you don't have to spell it out in every prompt. | Skill | What it covers | |-------|----------------| | `accessibility-audit` | How to scope, run and report a WCAG audit with this server's tools: single pages, interactive flows and whole sites. Bundles a copyable Markdown evidence report template (`references/evidence-report-template.md`), a worked local-demo example with real JSON and annotated screenshot artifacts (`references/worked-example/evidence-report.md`), and a reference list of the success criteria automation cannot check (`references/manual-checks.md`). | The skills are served in every server mode (stdio and HTTP, standalone, `--extension`, `--connect-tool` and `--vscode`) and by `createConnection`. The server declares the extension, with `directoryRead`, next to `tools` and `resources`, and answers: - `skills/list` and `skills/get`, with a SHA-256 digest of every file; - `resources/read` for `skill://accessibility-audit/SKILL.md` and its supporting files; - `resources/directory/read` to browse a skill's folder. `SKILL.md` also appears in `resources/list`, so clients without skills support can still read it as an ordinary resource. The skill sources are in the [`skills/`](skills/) folder of the package. The root `SKILL.md` is different: it is a separate skill for driving the CLI's `interactive` REPL, and it is not served over MCP. ## Available Tools ### Page-registered WebMCP tools When the current page exposes a supported WebMCP API, MCP `tools/list` includes its tools as `webmcp__` alongside built-in tools. In `--extension` mode without `PLAYWRIGHT_MCP_EXTENSION_TOKEN`, listing never starts the extension connection, since that waits for your approval: page tools are listed once a browser tool call has connected it, and stateless (handshake-free) requests need the token to list them at all. Use the exact returned name: names are scoped to the browser session, frame/document and registration, and stale names are rejected rather than redirected to another action. Because of that, [`--allowed-tools` / `--blocked-tools`](#exact-name-tool-selection) cannot select them. No browser flags or polyfills are installed automatically. To discover or invoke tools in an explicit browser session, put its handle in **request metadata** (`params._meta.browserSessionId`) on both `tools/list` and `tools/call`. This is separate from `params.arguments`: page-defined `browserSessionId` and `_meta` arguments are preserved unchanged. Without routing metadata, discovery and invocation use the default session. Session handles are never enumerated by discovery. Listing holds its session against closure or expiry until discovery completes or the request is cancelled. Names, descriptions, schemas, results and page errors are untrusted. Every page tool retains conservative action annotations even if the page claims it is read-only. Calls are bounded and cancellable, but a timed-out or cancelled page action may still be running; do not retry it blindly. Stateful connections receive deduplicated list-change notifications for their last listed scope; stateless clients should re-list rather than cache the result. Native Chromium WebMCP invocation supports the JSON-string contract in Chromium 153 and the object-input contract verified in Chromium 156, including external CDP connections. The bridge selects the contract from the native method's signature before invocation; page-provided JavaScript shims keep JSON-string inputs. An invocation error never triggers an automatic retry. Stateful proxies buffer catalog changes until pending tool listings return, including changes arriving just as a listing finishes, so refresh notifications follow the returned catalog. See [WebMCP usage, limits and tests](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/webmcp.md) for request examples, discovery limits and validation commands. Page descriptors must pass the MCP SDK’s tool-schema validation, and their input schemas must compile with the validator that later checks call arguments, before publication. Schemas that define `pattern` or `patternProperties` subschemas, or declare a root type other than `object`, are omitted; `format` keywords are advertised but left for the page to enforce, and argument validation is interrupted after 500 ms. An empty listing is not proof that the page has no tools: unsupported, invalid or timed-out registrations are omitted. ### Built-in tools The MCP server provides comprehensive browser automation and accessibility scanning tools: ### Core Accessibility Tools #### `scan_page` Performs a comprehensive accessibility scan on the current page using Axe-core. **Parameters:** - `violationsTag`: Array of WCAG/violation tags to check - `includeIncomplete` (default `true`): also report Axe "incomplete" results - `retainFindings` (default `false`): keep all deduplicated findings in memory; the inline sample stays capped. To retrieve those findings later, `get_scan_findings` must also be enabled for the client - `maxNodesPerViolation` (1–50, default `10`): cap on node details reported per rule; occurrence totals use all deduplicated findings, not the capped sample - `includeSelectors` / `excludeSelectors`: CSS selectors that scope the scan - `withRules` / `disableRules`: Axe rule ids that narrow which rules run - `annotateScreenshot` (default `false`): capture an annotated screenshot of the violations **Annotated screenshots:** When `annotateScreenshot` is `true`, each violating element is outlined and labelled with the rule ids it failed, a full-page PNG is written to the MCP output directory (`scan-page-annotated-{timestamp}-{token}.png`) and returned as a resource link, and the markers are then removed so the page is left exactly as it was. The markers are drawn in an out-of-flow overlay clipped to each element's own box, so they never reflow the page. The overlay uses a fresh id per scan, is placed in the browser's top layer so it stays visible over an open dialog, popover or fullscreen element, and compensates for a CSS `zoom` or a scaled ancestor so markers line up with what is rendered. An element that fails several rules gets one box listing every rule id, and elements inside open shadow roots are marked by walking the shadow path Axe reports. Running animations are frozen at their current time before the elements are measured and resumed after the capture, so a moving target keeps its marker. The markers themselves live in a shadow root under an overlay whose own styles are `!important`, so page CSS cannot restyle or hide what the report counts, and each rule label sits outside the clipped box so it stays readable on an element smaller than its own label. At most 50 elements are annotated per scan. The result text always reports how many nodes were marked out of the total, plus how many were left out because they exceeded the limit, were hidden, zero-size or off-canvas (a full-page screenshot is clipped to the document box), or were inside an iframe (cross-frame selectors cannot be resolved from the top document). **Supported Violation Tags:** - WCAG standards (in the default set): `wcag2a`, `wcag2aa`, `wcag2aaa`, `wcag21a`, `wcag21aa`, `wcag21aaa`, `wcag22a`, `wcag22aa`, `wcag22aaa` - Section 508 (in the default set): `section508` - Categories (opt-in): `cat.aria`, `cat.color`, `cat.forms`, `cat.keyboard`, `cat.language`, `cat.name-role-value`, `cat.parsing`, `cat.semantics`, `cat.sensory-and-visual-cues`, `cat.structure`, `cat.tables`, `cat.text-alternatives`, `cat.time-and-media` - Non-conformance tags (opt-in): `best-practice`, `experimental` (see the caveat below -- a few experimental rules also carry a WCAG tag and run by default) The default set is the WCAG and Section 508 tags only, so a default report means "this fails a conformance criterion". Category tags are opt-in for that reason: Axe matches requested tags with OR, so asking for `cat.keyboard` also pulls in best-practice rules such as `region` and `skip-link` that carry both tags. No live conformance rule is lost by leaving them out: the only rules reachable *only* through a `cat.*` tag are `duplicate-id` and `duplicate-id-active`, which Axe marks deprecated because WCAG removed SC 4.1.1. Add `best-practice` (landmark structure, heading order, `tabindex` hygiene) or a `cat.*` tag when you want that broader review. The same OR semantics apply to `experimental`, with one deliberate exception: four experimental rules -- `css-orientation-lock` (SC 1.3.4), `p-as-heading`, `table-fake-caption` and `td-has-header` (SC 1.3.1) -- also carry a `wcag*` tag and so run in the default set. In Axe, `experimental` describes how settled the heuristic is, not whether the criterion is real, so these are kept rather than filtered out. Adding the `experimental` tag pulls in the remaining experimental rules, which have no conformance tag of their own. Axe 4.14 no longer marks `label-content-name-mismatch` (SC 2.5.3) as experimental; it still runs by default. **Scan scoping:** `scan_page`, `audit_site`, and `scan_page_matrix` accept `includeSelectors` and `excludeSelectors` to limit what Axe looks at. Use `includeSelectors` to audit one component (`["#checkout-form"]`) and `excludeSelectors` to drop third-party noise that pollutes every report (`["#cookie-banner", "iframe.intercom-frame"]`). Exclusions are applied after inclusions, so you can carve a widget out of an included subtree. Selectors are resolved before the scan runs: - Syntactically invalid CSS fails the scan, naming the selector. - An `includeSelectors` entry that matches nothing fails the scan. Axe on its own would accept a partly-matching include set and quietly scan less than you asked for, so the scanner refuses rather than returning a clean-looking report with half the scope missing. - An `excludeSelectors` entry that matches nothing is a no-op, not an error -- a crawl legitimately visits pages that lack the excluded widget. In `audit_site`, selectors apply to every crawled page, so an `includeSelectors` value that is absent from a given page marks *that page* as errored in the report while the crawl continues. Link discovery runs before the scan, so pages reachable only through an errored page are still crawled. **Rule-level control:** `scan_page`, `audit_site`, and `scan_page_matrix` accept `withRules` and `disableRules` to pick individual Axe rules instead of whole tag sets. Use `withRules` to re-check one rule after a fix (`["color-contrast"]`) and `disableRules` to mute a rule you have already triaged (`["region"]`). Rule ids are the ones Axe reports (`image-alt`, `color-contrast`, ...); see the [Deque rule reference](https://dequeuniversity.com/rules/axe/). - **`withRules` overrides `violationsTag`.** Axe can run either a rule list or a tag list, never both, so when `withRules` is set the tags are ignored entirely -- `withRules: ["image-alt"]` runs exactly that one rule regardless of `violationsTag`. Rule ids are the more specific request, so they win. - **`disableRules` subtracts from whatever is selected.** It applies to `violationsTag` and `withRules` alike. (Axe itself ignores disabled rules once you give it an explicit rule list; the scanner subtracts them up front so the two options mean the same thing together as apart.) Disabling every rule in `withRules` is an error rather than an empty scan. - **An explicitly empty `withRules` is an error too.** `withRules: []` selects no rules, and silently falling back to the tag set would run a different scan than the one requested β€” omit the option to scan by tags instead. Clients that build the list dynamically should drop the key when the list comes out empty. - **Unknown rule ids fail the scan, naming the id.** Both options are checked against Axe's rule catalogue before the browser is touched, so a typo is reported as `Unknown Axe rule id(s) in withRules: image-altt` rather than surfacing later as an `frame.evaluate` failure from inside the page. Rule ids apply to a whole run, so `audit_site` and `scan_page_matrix` check them once before they touch the page -- a bad id fails the call outright instead of crawling every URL, or reloading and re-emulating the page, before rejecting the argument. `audit_site` and `scan_page_matrix` record both values in their JSON report metadata, so a stored report can be told apart from a full scan. **Incomplete ("needs review") results:** Axe returns `incomplete` for checks it cannot decide on its own -- contrast over a background image or gradient, ambiguous labels, elements it could not fully evaluate. `scan_page`, `audit_site`, and `scan_page_matrix` report these in a section separate from violations so you can resolve them by inspecting the page (screenshot, snapshot, `browser_evaluate`). Set `includeIncomplete: false` to suppress their detailed findings. In matrix scans, this does not disable the comparison-validity checks described below. **Frames that could not be scanned:** Axe is installed into every frame of the page before the scan runs. A frame that navigates mid-injection, or whose renderer does not answer within a second, is left out -- and its contents then contribute no findings. Rather than let that pass as a clean result, all three scan tools print a `WARNING: Axe could not be installed in N frame(s)` block listing the frame URLs, and `audit_site` and `scan_page_matrix` also record them per page and per variant in their JSON reports (`unscannedFrames`) and in `structuredContent`. A frame that was still loading usually succeeds on a re-run; one that fails consistently has to be audited on its own. A nested frame is reported when any frame above it went unscanned, even if its own injection succeeded: Axe reaches a nested document only by relaying through the frames above it, so an outer frame without Axe takes everything below it out of the scan. A frame you scoped out yourself is not reported: with `excludeSelectors: ["iframe.intercom-frame"]` that widget failing to load is the outcome you asked for, not a gap. Scope is resolved through the whole frame chain and across shadow boundaries, so an `includeSelectors` entry naming an ancestor still covers frames nested several levels below it or inside a shadow root, and excluding an outer frame or a shadow host silences everything inside it. Anything the check cannot resolve is reported rather than hidden. #### `get_scan_findings` Use this read-only tool to page through the evidence from **one observation**, even after navigating away. It reads memory, not the current page. Start with: ```text scan_page {"withRules":["image-alt"],"maxNodesPerViolation":2,"retainFindings":true} get_scan_findings {"scanId":"","ruleId":"image-alt","outcome":"violation","offset":0,"limit":25} ``` An opted-in scan returns an opaque `scanId` in text and in MCP `structuredContent`, alongside a structured `rules` index of `{ruleId, outcome, count}`. Counts are deduplicated nodes before the inline cap. Outcomes are `violation` and `incomplete`; with `includeIncomplete: false`, incomplete entries are neither indexed nor retained. Passes and inapplicable rules have no retained nodes. Lookup returns the original Axe `target`, `html`, and `failureSummary` for each node in scan order, subject to configured URL-parameter redaction. Use `nextOffset` for the next request; `null` means finished. The zero-based `offset` defaults to 0 and must not exceed `total`. The integer `limit` defaults to 10 and must be 1–50. Only the latest **successfully retained** scan in the same browser session is available. A new retained scan replaces it; navigation, ordinary scans, and failed or cancelled scans do not. Closing or expiring the session, or restarting the server, loses the evidence. Pass the same `browserSessionId` if one was used for the scan; stateless HTTP requires an explicit session. Unknown, replaced and foreign scan IDs all return the same unavailable error. No scan report file is written. As with other tools, `--save-session` logs the returned text when enabled, but replaces scan IDs with redacted labels. If the rule index and node records exceed 1 MiB of UTF-8 JSON, the scan still returns its inline results and counts, but `scanId` is `null` with a reason. No partial evidence is retained and any previous retained scan remains available. ### Audit Tools #### `audit_site` Crawls and scans multiple internal pages, then aggregates violations across the site. - Default strategy: link-based BFS from the current URL - Audits up to `concurrency` pages at once (default `4`, max `8`), each in its own temporary tab, so page loads, settle waits and Axe runs overlap. This makes a crawl about 2-2.4x faster on a 4-core machine (benchmark crawl caps of 6 and 12 pages). Links each page discovers are queued in the order pages were visited, not the order they finished, so the pages scanned, their order, depth and `discoveredFrom`, and the aggregated findings are the same as with `concurrency: 1`. Use `concurrency: 1` when pages depend on `sessionStorage` written by earlier crawled pages, since each tab has its own, or when you want a lost session cookie pinned on exactly one page. - Supports `links`, `nav`, `sitemap`, and `provided` URL strategies. Trailing slashes are preserved; sitemap locations decode XML entities while preserving literal CDATA content. - The `sitemap` strategy accepts a flat `urlset` or a `sitemapindex`. It expands nested indexes breadth-first in listed order and fetches each distinct manifest URL once. Only page entries from the URL sets participate in `maxPages` and `pageSelection`; child manifests and extension locations (such as images) do not. Each selected page’s `discoveredFrom` identifies the first URL set that listed it, after manifest redirects. - The root sitemap, every child, and every redirect must pass the server network policy, crawl origin and path exclusions. Fetches run on the MCP host over HTTP(S) without browser cookies or auth headers. Expansion shares a 15-second timeout, 64 HTTP requests (including redirects), and 10 MiB of XML across all manifests, with at most 20 redirects per chain. An unreadable manifest or exceeded limit fails the audit before any page is scanned; no partial report is written. Browser proxy settings, `browser.remoteEndpoint`, `browser.cdpEndpoint` (including loopback endpoints, which may tunnel to remote browsers), `--extension`, switched `browser_connect` providers, and custom contexts from `createConnection(config, contextGetter)` are rejected for this strategy; use `provided` URLs in these modes. Sitemap TLS certificates must be valid even when browser HTTPS errors are ignored. - Always writes a JSON report (default filename: `audit-site-{timestamp}-{token}.json`). Per-page `summary.totalNodes`, `byImpact`, and `byRuleId` count all deduplicated violation nodes; `maxNodesPerViolation` only limits the saved node details. - In each saved page and in structured `topPages`, `url` is the queued address and `auditedUrl` is the document URL Axe measured. These can differ after a redirect. A skipped or failed page has no measurement (`auditedUrl: null`). - `pageSelection` decides which listed URLs fill `maxPages` when a `sitemap` or `provided` list is longer than the budget. `discovery` (default) takes them in listed order. `representative` builds a tree of the listed URLs by host, path segment, and then query parameter. Numeric, UUID, and long hex segments and values are masked, so `/products/1` and `/products/2` (or `?id=1` and `?id=2`) share a template, while `?page=home` and `?page=checkout` do not. Repeated and trailing slashes are significant: `/items/1`, `/items//1`, and `/items/1/` are separate templates. A literal `:id` is distinct from a masked ID, and an encoded `=` in a query key does not merge it with a different key/value pair. URLs that share a template are treated as interchangeable. Fragment routing and client-side state cannot be told apart. - **Coverage rule:** when the pages allotted to a group of URLs (a host, a path prefix, or a query level) are at least the number of its branches, every branch gets a page. With `maxPages` at least the number of top-level sections, every section is scanned. - **k-median for the rest:** remaining pages minimize the summed tree distance from every listed URL to its nearest scanned one, and the selection is solved exactly under both rules. Below the coverage threshold, k-median weighs groups by how many URLs they hold, so a populous section can take pages that a small one does not get. This optimizes URL coverage, not accessibility coverage: pages with the same template can still differ in content. - The selected URLs are queued and reported in listed order; concurrent requests can reach the server in a different order. The rest count as `skippedUrls`. The result says how many listed URLs the selection chose from, and the JSON report and structured content carry `representativeSelection: { candidates, selected, complete }` (`null` in discovery order). Selection work is bounded: when a very long or deeply nested list would exceed that budget, the first `maxPages` URLs are queued in listed order instead, `complete` is `false`, and the result starts the selection line with `WARNING:`. It is rejected for the `links` and `nav` strategies, which only learn their URLs while crawling. - To review at least one page for every observed violation rule, use `summary.violationWitnessPages` in the JSON report (or `violationWitnessPages` in structured content). Each step selects the scanned page that adds the most as-yet-unrepresented rule IDs; ties use report page order. Its `newRuleIds` name those rules. This is not necessarily the smallest possible set, does not include incomplete checks, and does not predict findings on unscanned pages. With no observed violations the list is empty. - For each rule, `uniqueOccurrences` counts distinct whitespace-normalized HTML across all scanned pages, before node details are capped. - Each aggregated violation also reports `similarPatterns`: its unique occurrences grouped by near-identical markup. This is a markup heuristic, not a count of root causes: similar markup often means a shared template, but it does not prove one fix covers every node. - **What counts as one pattern:** two nodes can share a pattern only when their root element, its `type` (inputs default to `text`), and its `role` match. Embedded separators in attribute values or text cannot bypass the semantic or token comparisons. Within that, they share one when their HTML differs in under about 30% of its tokens (tag names, attribute names and values, text words). Only the first 48 tokens of each node are compared, so differences past them are not seen. - **Order independence:** similarity is not transitive, so each rule's unique occurrences are grouped in a canonical sort order. The count depends only on which occurrences were found, not on crawl order. - **Limits:** at most 500 unique occurrences (the first in that order) and 50 patterns are grouped per rule. When either limit cuts in, `similarPatternsCapped` is `true`, the count covers only part of the occurrences, and the top-violations line reads `N patterns (partial)` instead of `N patterns`. - Up to three `sampleNodes` per rule show different patterns where there are several. - After browser navigation settles, the reached URL is checked again against HTTP(S), `sameOriginOnly`, `includeSubdomains`, and `excludePathPatterns`. A destination outside that scope is recorded as a page error naming the requested and reached URLs; it is not scanned or used for link discovery, and the crawl continues. This is a post-navigation check, not a network-request blocker: redirect destinations may already have been contacted and changed session state. - A URL that starts a file download instead of loading a document (for example a CSV served as an attachment) is recorded with `status: "skipped"` and a `skipReason`, counted in `skippedUrls`, and neither scanned nor used for link discovery. The crawl tab still shows the previous document after a download, so it is never audited under the download's URL. Redirects that end on an in-scope document are still audited. - A page that opens an `alert`, `confirm` or `prompt` while it is being audited is reported as an errored page as soon as the dialog opens, with the dialog named in its `error`. This includes terminal HTTP 3xx pages (for example, `300` or `302` without a `Location`) that commit a document instead of redirecting. The crawl never answers a dialog: it closes that page's tab and continues with the next URL in a fresh one, so one such page does not fail or hang the pages after it. A dialog the previous page raises while the crawl is already navigating away is not blamed on the next page, which is audited again in the fresh tab. Same-document history updates, even ones that keep the exact URL unchanged, do not count as the next page loading. A fresh tab starts without the old tab's `sessionStorage`, so the result then starts with a `WARNING: … continued in a fresh tab from ` line and both the JSON report and the structured content carry a `crawlTabRestarts` list; if the site keeps its session in `sessionStorage`, pages from that URL on may have been audited in a different session. The tab the tool was called from is not touched. - Warns and records `sessionLosses` if the crawl loses cookies it started with β€” see [Auditing pages behind a login](#auditing-pages-behind-a-login). If navigation fails on a browser-internal error page, the warning names the requested URL instead. **Example flow:** ```text 1. Navigate to your site homepage with browser_navigate 2. Run audit_site with maxPages: 25 and maxDepth: 2 3. Review the report path returned by the tool (written to the MCP output directory) ``` #### `scan_page_matrix` Viewport variants require a configured viewport (for example `--viewport-size=1280,720`). On native-sized browser tabs, use variants without viewport changes; the tool rejects viewport changes rather than permanently converting the tab to a fixed viewport. Cancellation waits for an active Axe scan or page mutation to finish, then stops subsequent variants and restores viewport, media and zoom. Site-audit cancellation stops the crawl and closes its owned tabs. Canceled runs do not write a completed report. Runs Axe scans on the same page across viewport/media/zoom variants and compares deltas against baseline. - Default variants: baseline, mobile, desktop, forced-colors, reduced-motion, zoom-200 - Supports custom variants and optional reload between variants - Runs exclusively in its browser context, like the interaction audits: while a matrix scan runs, overlapping MCP tool calls routed to the same context (including another matrix scan) are rejected with a busy error, and a matrix scan started while another tool is active is rejected too. Each scan therefore measures only its own variants and restores the viewport, media and zoom it captured. Calls routed to other browser sessions proceed independently. A matrix scan also claims the page itself: while it holds the page, tool calls from another client attached to the same shared browser context (for example a non-isolated `--cdp-endpoint` connection) are rejected as busy when the page they would act on is that page, including page changes such as `browser_emulate_media`, other matrix scans, a first `browser_navigate` that attaches to it, `browser_tabs` selecting or closing it by index, and all-tab timeout updates (`browser_default_timeout`, `browser_navigation_timeout`) when any affected tab is claimed (leaving other tabs unmodified). Only `browser_handle_dialog` is admitted on the claimed page. This page claim is what limits other clients, so their teardown (`browser_close`, `browser_session_close`) and their calls on other tabs are unaffected; calls routed to the scanning client's own browser context, other than `browser_handle_dialog`, are still rejected as busy whichever tab they target, as above. In turn, a matrix scan is rejected as busy before it reads or changes anything while another tool call, from any client, is still running on its page. - If the page opens a dialog during a variant (for example `alert()` on resize) or before the scan returns, the scan stops and returns an error naming the variant and the dialog; it does not answer the dialog or write a report. The paused page accepts no commands, so answer the dialog with `browser_handle_dialog` (admitted even while an exclusive audit runs); the server then attempts to restore the original viewport, media and zoom. A restore step that fails after the dialog closes is only logged, so verify the viewport, media and zoom before continuing. Until that restore finishes, the page stays claimed and other tool calls to the same browser context are rejected as busy, so they cannot change the page only to have the restore overwrite them. `browser_close` is still admitted: it cancels the pending restore and closes the context. For a browser session, `browser_session_close` likewise cancels the restore and closes the session. If `browser_handle_dialog` is in `blockedTools`, the error's modal-state guidance says it is blocked instead of recommending it. A dialog opened while the scan reads the original state stops the scan the same way, but nothing was changed, so no restore is pending. - Always writes a JSON report (default filename: `scan-matrix-{timestamp}-{token}.json`) - JSON report and structured result schema `v2` set baseline deltas to `null` when the variant was scanned at a different URL, when either scan left frames unscanned, or when a rule recorded as a violation on either side also has incomplete results on either side. An undecidable result is not evidence that a violation was fixed, introduced, or changed in count. - The report’s `metadata.url` and the structured result’s `page.url` identify the baseline Axe actually scanned. If a resize or reload routed the tab elsewhere, the variant records the observed URL in `differentPageUrl` (otherwise `null`). Its findings are still available, but the table says `n/a (page URL differs from baseline)` rather than crediting the new page with a fix. Comparison uses the full URL, including the query and fragment; matching URLs do not guarantee matching application state. - Each variant includes `comparisonIncompleteRuleIds` in JSON and structured output: the sorted rule IDs making its comparison uncertain, or `[]` when none do. The text table distinguishes missing-frame coverage from incomplete checks. These safeguards still apply with `includeIncomplete: false`; that option hides detailed findings, not comparison validity. - Unrelated incomplete-only rules do not suppress comparisons of confirmed violations. The baseline self-comparison is also unavailable if the same rule has both violating and incomplete nodes. - Summary totals and baseline count deltas use all deduplicated violation nodes, while saved node details remain capped by `maxNodesPerViolation`. Changing that cap does not change occurrence totals. - A rule can have the same count but different failing locations. The text table counts rules with changed target paths; `changedTargetRuleIds` in structured output names them. In the JSON report, each variant’s `targetChangesFromBaseline` maps those rule IDs to `added` (observed only in this variant) and `removed` (observed only in the baseline). Each has an exact distinct-path `count` and up to `maxNodesPerViolation` example paths in `samples`. The map is `{}` if no paths changed and `null` if the scans cannot be compared. - Paths are the selector arrays Axe observed, including frame and shadow boundaries. The path comparison ignores HTML and node order. Selectors do not establish element identity across renders, and a removed path does not establish that a violation was fixed. **Example flow:** ```text 1. Navigate to a page state you want to validate 2. Run scan_page_matrix with defaults (or provide custom variants) 3. Review per-variant deltas and open the generated JSON report path ``` #### `audit_keyboard` Audits real keyboard focus behavior by pressing Tab (and optional Shift+Tab) with practical heuristics. - Checks skip links, focus visibility, focus jumps, and possible focus traps (repeated focus cycles reported as `Possible focus trap (heuristic focus cycle)`; verify Escape or other keyboard exits and assistive-technology behavior manually) - Tabbing past the last control can return focus to the document. The report keeps that stop in the trace but does not flag a missing ring when no element has focus. This also applies to XHTML and standalone SVG. An explicitly focused `` or `` still gets checked. - On pages with synchronous focus changes, pass `settleAfterKeyMs: 0` to sample each stop immediately after the keypress and observed page activity. The default uses the server settle timeout (500 ms). Keep it for focus handlers, timers or animations that update the UI after a keypress. - Focus stops distinguish individual DOM elements, including controls in open shadow roots. Alternating Tab/Shift+Tab does not count an intentional return as a cycle; a keypress that cannot move focus can still indicate a trap. - Restores the original URL after cross-document skip-link navigation. It uses Back for a single observed history-entry increase, verifies the restored URL, and otherwise replaces the current entry with the original URL. Fragment jumps, same-document history changes, and same-URL reloads do not consume an earlier history entry. When forward history was truncated or an entry was replaced, restoration can reload the audited page rather than recover its previous document state. - Checks target size against WCAG 2.2 SC 2.5.8 (`checkTargetSize`, default on) - Checks that focus is not entirely obscured, WCAG 2.2 SC 2.4.11 (`checkFocusObscured`, default on), including painted covering hosts and focused hosts’ own content across open shadow roots. - Optional issue screenshots (`screenshotOnIssue`) - Always writes a JSON report (default filename: `audit-keyboard-{timestamp}-{token}.json`) **Limits of the WCAG 2.2 checks** β€” these are heuristics, not a conformance verdict: - Target size only inspects elements the tab order actually reaches, so pointer-only targets are never measured. - Of the SC 2.5.8 exceptions, only *spacing* (a 24px-diameter circle centered on the target must reach neither another target's box nor another undersized target's circle) and *inline* (an inline-level target β€” `inline`, `inline-block`, `inline-flex`, … β€” inside surrounding sentence text, found by walking out through inline wrappers such as `` to the containing block) are evaluated. The *user agent control*, *essential*, and *equivalent* exceptions cannot be detected from the DOM, so a target relying on one of them is still reported and needs manual triage. - Spacing neighbours use the same pointer-target rule as the focused element: a target must accept pointer input, so rendered `:disabled`, `visibility: hidden`/`collapse`, `pointer-events: none` and `inert` controls (including those inside an inert or hidden shadow host) are not counted on either side. Transparent (`opacity: 0`) controls still take clicks and are counted. `contenteditable` regions are counted as targets on both sides. A hidden or `pointer-events: none` control that has a descendant restoring `visibility`/`pointer-events` (open shadow roots and slotted content included) still activates when that descendant is clicked, so it is counted with the union box of those descendants as its target (`targetBox` in the JSON report). Each descendant is first cut to the `overflow` and `contain: paint` clips of the control and the elements between them (a positioned descendant only to the clips that contain its containing block). Those walks count against the 50,000-element limit below. A control whose descendants could not be walked within it, or with such a descendant under a clip the walk cannot place (`clip-path`, `clip`, a scaled or rotated clipping box, an `` nested in another), is inconclusive. - The spacing search checks each candidate as it goes and stops at the first crowding neighbour, so DOM order does not change the result. Neighbours inside open shadow roots, nested ones included, are searched too (closed ones cannot be). Per focus stop it examines at most 2,000 candidates and shadow roots and walks at most 50,000 elements (ordinary elements included); an undersized target with no crowding neighbour found before either limit is reported as inconclusive (`targetSizeInconclusive` in the JSON report, `targetSizeInconclusiveCount` in the structured summary), not as a pass. - Target size uses the element's bounding box, so an inline target wrapped over several lines is measured as one union box rather than per line, and a target whose visible area is cut down by an `overflow` or `clip-path` ancestor is measured at its full unclipped size. - SC 2.4.11 is the Minimum (AA) level: a focused element is only reported when *every* sampled point of its box is covered by other content. Partially covered focus passes here, and the stricter SC 2.4.12 (AAA) is not checked. It applies to every focus stop with a rendered box, including elements that are not pointer targets such as iframes. - Coverage is measured by hit-testing sample points and then checking that the element hit actually paints (visible, non-zero opacity all the way up to the first wrapper shared with the focused element, non-transparent background or background image). A transparent click-catching overlay therefore does *not* count as obscuration, but a covering layer with `pointer-events: none` is never returned by hit testing and is missed. Semi-transparent overlays that still leave content legible are reported. **Example flow:** ```text 1. Navigate to the target page and let it fully load 2. Run audit_keyboard with maxTabs: 50 3. Review focus findings and open the generated JSON report path ``` #### `audit_keyboard_operation` Exercises a caller-defined keyboard scenario and checks the outcome after each key. Unlike `audit_keyboard`, this tests operation: opening a menu, selecting an option, dismissing a dialog, or returning focus. It does not discover tasks or decide which outcome your application should produce. Start from a known page state. Supply `steps`, each with exactly one of `key` or `text` and a nonempty `expect` array. Expectations use stable selectors so they can address elements that appear or rerender during the scenario. Actions use real keyboard input, never programmatic focus, clicks, or fills. Use `Tab` steps to reach the control instead of bypassing keyboard reachability. ```json { "steps": [ { "key": "Tab", "expect": [{ "selector": "#open-menu", "focused": true }] }, { "key": "Enter", "expect": [{ "selector": "#open-menu", "expanded": true }, { "selector": "#menu", "visible": true }] }, { "key": "Escape", "expect": [{ "selector": "#menu", "visible": false }, { "selector": "#open-menu", "focused": true }] } ] } ``` **Parameters and bounds:** `steps` accepts 1–20 steps, with 1–10 expectations each. Keys are `Tab`, `Shift+Tab`, `Enter`, `Space`, the four arrow keys, `Escape`, `Home`, `End`, `Backspace`, `Delete` and `ControlOrMeta+A`. A `text` step enters 1–500 characters sequentially into the currently focused editable element. The audit checks that the same element remains focused and editable before and after each character; focus theft, removal or replacement makes the scenario incomplete instead of sending the remaining text elsewhere. Each expectation requires a CSS `selector` and at least one of `focused`, `visible`, `text`, `value`, `expanded`, `checked`, `selected`, `pressed` or `disabled`. Boolean states are exact; `checked` and `pressed` also accept `"mixed"`. Text compares trimmed `textContent`; values compare native form values or `aria-valuenow`. Text/value contents are omitted from reports. Selectors address the main frame and open shadow roots, not iframe contents. The audit compares selector matches before and after the outcome sample. If those matches differ, the step is incomplete. A match that changes and reverts between those checks can be missed. An ambiguous selector or unsupported state is incomplete, not a pass. `visible` checks rendering (content inside a closed `
` or `hidden=until-found` is not visible), layout boxes and computed visibility, not opacity or visual occlusion; use `audit_keyboard` separately for focus visibility/obscuration heuristics. `timeoutMs` is the per-step observation window (0–1000 ms, default 300). All outcomes for a step are measured together at the end of that window so a brief focus match before a delayed trap is not accepted immediately; zero samples once without waiting. Changes after the window are not covered. The overall scenario budget is 30 seconds. This is a **state-changing** tool: a key can submit a form or navigate. It does not undo actions. Use controlled test data and reset the page before repeating a scenario. An assertion mismatch stops the scenario; subsequent steps are not run. An interrupted action or unavailable measurement is not a passing check. JSON reports and structured results distinguish tested outcomes from incomplete work. This supports investigation of WCAG 2.1.1, 2.1.2 and 2.4.3, not certification of keyboard access across the site. #### `audit_form_validation` Exercises one caller-defined invalid-input case: reaches the named text inputs/textarea fields through keyboard navigation, replaces their contents through keyboard input, activates the supplied submit control, and inspects the expected error/status feedback. It does not discover forms, choose invalid values, or submit other forms automatically. ```json { "fields": [{ "selector": "#email", "value": "invalid-email" }], "submitSelector": "#submit", "expectedFeedback": [{ "selector": "#email-error", "kind": "error" }] } ``` `interactionMode` defaults to `"keyboard"`: starting from the current focus, it presses Tab to reach each field (up to 50 presses per target), selects existing text with `ControlOrMeta+A`, clears it with Backspace, and enters the supplied value character by character. It then reaches the submit control through Tab and presses Enter. It never calls focus, fill or click in this mode. A target that cannot be reached, focus that moves elsewhere during entry, or a field that does not retain the supplied value makes the scenario incomplete and prevents later submission. Keyboard mode rejects CR/LF in single-line input values before mutation; textarea newlines are supported. Use `interactionMode: "direct"` for the previous fill-and-click behavior; direct mode does not prove keyboard reachability. Both modes verify the supplied field values before activating submit and stop as incomplete on a mismatch. Reports identify the mode used. Text input follows browser key/input event sequences without randomized timing. It does not reproduce human cadence, an operating-system keyboard layout, IME composition, or a screen reader. Some Unicode characters are inserted by the browser without physical-key-equivalent events. Supply selectors for the fields and feedback in the main document; expected feedback may appear after validation. The audit examines native/ARIA invalid state, same-root error associations, feedback visibility, focus and changes to live-region content. Unfocused status feedback needs a change within the same live region, with polite or assertive semantics in both the pre-submit and post-submit samples. The JSON report records the current region’s pre-submit value as `baselineLive` when the region was exposed. A message inserted into a pre-existing, exposed live region counts when that same container survives submission. Changes between samples can still be missed. It reports DOM/live-region and programmatic feedback signals, **not actual NVDA/VoiceOver announcements**. An associated error does not also have to be a live region; native browser validation and focus-managed feedback must be considered. Human review is still needed to judge whether an error explains the problem and suggests an appropriate correction (WCAG 3.3.1/3.3.3), and whether status feedback is announced usefully (4.1.3). **Parameters and bounds:** `fields` and `expectedFeedback` each accept 1–20 entries. Field `value` is a string (up to 10,000 characters); supported fields are editable text/email/url/tel/password/search inputs and textareas. CSS selectors are limited to 500 characters and must be unambiguous. Feedback `kind` is `error` or `status`. `timeoutMs` sets the post-activation observation window (100–10,000 ms, default 3000); feedback is read once at its end. Keyboard actions have a 30-second budget; very long inputs may be incomplete. Direct mode retains its observation window plus 5-second overall budget and 1-second individual action bounds. Feedback text follows rendered descendants through open shadow roots and slots, excludes hidden or collapsed disclosure content and slot fallback replaced by assigned content, and retains visually clipped screen-reader-only text. Each target is bounded to 10,000 visited nodes and 10,000 exposed characters; exceeding either limit sets `textTruncated` and makes the audit incomplete. Native validation is reported as a possible browser-managed feedback route, not a verified announcement. Findings describe observed gaps; `completed` means the scenario was measured, not that the form conforms to WCAG. Other frames, transient feedback and message quality need separate review. This is a **state-changing** tool: supplied values are entered and the submit control is activated. An unexpectedly accepted value can submit the form. Use a test environment and reset its state between cases; the audit cannot undo submissions. Reports omit submitted values and feedback text. Both new interaction audits accept `reportFile` for a JSON report, use the normal MCP output directory and never overwrite an existing explicitly named report. While either interaction audit runs, overlapping MCP tool calls routed to the same browser context are rejected with a busy error before their actions start. Starting an interaction audit while another tool is active is also rejected; calls are not queued for later mutation. `browser_handle_dialog` is the one exception: a dialog pauses the page, so it is admitted to answer one. Calls routed to other browser sessions can proceed independently. This coordinates MCP calls, not page scripts, manual browser use, or independently connected clients. #### `audit_screen_reader` Inspects the browser's accessibility tree (`page.ariaSnapshot`), accessible names and element geometry for potential accessibility issues. No actual screen reader is installed or driven, and its announcements and interactions are not tested. **Checks (`checkNames`)** - `missing-accessible-name`: controls and images exposed with no accessible name (WCAG 4.1.2) - `uninformative-accessible-name`: names such as "click here", "read more", "image" that mean nothing out of context (WCAG 2.4.4) - `filename-as-accessible-name`: image alt text that is a file name, e.g. `IMG_1234.jpg`, `DSC00123` (WCAG 1.1.1). Only images are checked: a link or button legitimately named after the file it downloads (`logo.png`) is not a defect. - `label-in-name-mismatch`: the browser accessibility-tree name does not contain the visible label, which can prevent voice-control activation by the visible label (WCAG 2.5.3). The visible label of `
Docs`, a button whose label sits in a ``), so the audit installs its own copy of axe-core in the element's current frame when it needs a name the snapshot does not supply. When both checks are on, those names also label reading-order findings, including headings. The page's own `window.axe`, if any, is left as it was. Installing is bounded (10 s for the main frame, 1 s per child frame). A frame that refuses the copy (a blocking CSP, a page that removes it) is measured without names. The result says so: a `WARNING: accessible names could not be measured for N of these` line, `elementsWithoutMeasuredName` in the structured summary, and `elements.unmeasuredNames` in the JSON report. In those frames the snapshot's own names stand, including literal slash-delimited names such as `/` and `/docs/`, A control there with no snapshot name is not counted as `missing-accessible-name`, because a name carried by its children cannot be ruled out: it is listed as inconclusive instead (a `Missing name inconclusive` line and `inconclusiveNames` with the full `count` and up to `maxFindingsPerCheck` refs in the structured result and JSON report). Treat the name findings of a run with a non-zero count as partial and check those refs by hand. A frame that times out or stops answering is not evaluated by any check: its elements are counted as `unresolved` (with their own warning), and if that leaves nothing evaluated the audit fails rather than report a clean page. Every read of a frame is bounded by the same budgets (10 s main frame, 1 s child frame; the lookup that tells which frame owns an element gets the larger one), so a frame that stops answering cannot hold the audit open. Each ref lookup gets 1 s. Missing refs are not retried. Overlapping audits share two per-page limits: 200 ref lookups and four frame operations. A timed-out operation still occupies its slot until it settles. If timed-out work fills either pool and prevents new work from starting, the result says where measurement stopped. **Bounds:** `maxElements` (default 400) caps how many *screen-reader-reachable* accessibility tree elements are analyzed. The snapshot also refs `aria-hidden` subtrees, which no check reports, so measuring continues past them until the budget is filled with reachable elements (up to a hard ceiling of twice `maxElements` measured, so a page built mostly of hidden refs stays bounded). `maxFindingsPerCheck` (default 20) caps the findings listed per check. Both truncations are stated in the summary and the JSON report, and the full counts are always reported. Every summary states that results are browser accessibility-tree heuristics, not real screen-reader output. Always writes a JSON report (default filename: `audit-screen-reader-{timestamp}-{token}.json`). **Example flow:** ```text 1. Navigate to the target page and let it fully load 2. Run audit_screen_reader (optionally raise maxElements for a large page) 3. Review the accessibility findings and open the generated JSON report path ``` #### `audit_text_spacing` Stress-tests the current page against WCAG 1.4.12 Text Spacing (AA). It applies the four user overrides the criterion requires content to survive, compares text geometry before and after, and reports text that ends up hidden or colliding. It then removes the overrides, so the page is left as it was. Tools like ARC Toolkit and the text-spacing bookmarklet inject the same CSS and leave the judgement to a person. This tool measures the result instead. **Overrides applied** (the values of the common text-spacing bookmarklet): `line-height: 1.5`, `letter-spacing: 0.12em`, `word-spacing: 0.16em` on every element, and `margin-bottom: 2em` on paragraphs. **Checks** - `text-clipped`: text that the overrides newly hide behind an `overflow: hidden`/`clip` or paint-containment box (including `content-visibility: auto`; overflow on plain inline boxes, which does not clip, is ignored), such as a fixed-height card, a fixed-width button or a one-line `text-overflow: ellipsis` label. Each finding names the element, how much of its text is hidden before and after (`hiddenPercentBefore`, `hiddenPercentAfter`), and the box that cuts it off (`clippedBy`) with the styles responsible: `overflow`, `height`/`max-height`, `width`/`max-width`, `white-space`, `text-overflow` and `-webkit-line-clamp`. The fix text points at that box. - `text-overlap`: text of two different elements that overlaps after the overrides but did not before, typically absolutely positioned labels or text in fixed-height rows spilling into the next one. **Parameters:** - `maxElements` (default `1000`, max `5000`): visible text elements measured per frame. Hidden elements (`display: none`, `visibility: hidden`, `opacity: 0`) never count toward it. Elements past the cap are reported as truncated. Paragraph spacing is verified on at most this many paragraphs per frame; the rest are counted in a warning and in `paragraphsTruncated`. - `maxFindingsPerCheck` (default `20`): findings listed per check; the full counts are always reported. - `screenshot` (default `false`): also save a full-page PNG taken while the overrides are applied, returned as a resource link. - `reportFile`: JSON report file name (default `audit-text-spacing-{timestamp}-{token}.json`). **How it measures:** the visible text of each element (including text of `display: contents` elements, which renders in its parent's box) is measured as text line boxes (DOM `Range` rects) and intersected with every clipping ancestor, before and after the overrides, in a single pass inside the page. Clipping ancestors follow the containing-block chain: an absolutely positioned box is clipped only by `overflow` on its containing block and that block's own clipping ancestors, not by an `overflow: hidden` wrapper it escapes, and a fixed box only by ancestors that contain it (a transform, filter, layout/paint containment or `content-visibility`). Every line is checked for clipping. Overlap is compared on the first 200 painted lines of each element; an element with more than that before or after the overrides is counted once in a warning and in `elementsOverlapLinesTruncated`. Only text the overrides *newly* hide is reported: a finding needs at least 2 percentage points more of the element's text hidden, and at least a quarter of a glyph's area. Visually hidden text (a 1px `sr-only` box) and text that was already overlapping are therefore not reported. Text that was already partly truncated is reported only when the overrides hide noticeably more of it; `hiddenPercentBefore` shows how much was cut off already. Wrapping, taller boxes and a new scrollbar are not failures: `overflow: auto`/`scroll` boxes keep their content reachable, so they are not treated as clipping. Lines scrolled out of such a box are not painted outside it either, so they are not compared for overlap with the content around it. This holds for paint-contained boxes too (`contain: paint`, `content-visibility: auto`): with `overflow: auto`/`scroll` their content stays reachable, so only a non-scrolling paint-contained box counts as clipping. The overrides are applied as a constructed stylesheet (`adoptedStyleSheets`) in a uniquely named cascade layer, adopted by the document and every open shadow root. This means: - A page Content-Security-Policy that blocks inline `