### Install Dependencies and Build
Source: https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md
Installs project dependencies, starts the build in watch mode for continuous compilation, and installs Playwright's browser binaries.
```bash
npm ci
npm run watch
npx playwright install
```
--------------------------------
### Start Chrome with CDP Enabled
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Command-line examples for starting Chrome or Chromium with the remote debugging port enabled for CDP connections.
```bash
# Headless Chrome with CDP enabled
google-chrome --headless --remote-debugging-port=9222
# Headless Chromium
chromium --headless --remote-debugging-port=9222
```
--------------------------------
### TypeScript Import Example with Types
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/exports.md
Example showing how to import createConnection and the Config type in TypeScript.
```typescript
import { createConnection } from '@playwright/mcp';
import type { Config } from '@playwright/mcp';
const config: Config = { /* ... */ };
const server = await createConnection(config);
```
--------------------------------
### CLI Setup Snippet
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
Illustrates the initial setup for the command-line interface, importing necessary modules from playwright-core.
```javascript
const { program } = require('playwright-core/lib/utilsBundle');
const { tools, libCli } = require('playwright-core/lib/coreBundle');
// ... CLI setup
```
--------------------------------
### Custom Output Directory Example
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/advanced-configuration.md
Example demonstrating the use of both relative and absolute paths for the output directory.
```javascript
const config = {
outputDir: './output', // Relative path
// or
outputDir: '/absolute/path/output', // Absolute path
};
```
--------------------------------
### CommonJS Import Example
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/exports.md
Example demonstrating how to import the createConnection function using CommonJS module syntax.
```javascript
const { createConnection } = require('@playwright/mcp');
const server = await createConnection();
```
--------------------------------
### Playwright CLI Install Command
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/cli.md
Installs browser binaries for Chromium, Firefox, and WebKit. Use either 'install' or 'install-browser' as the command.
```bash
playwright-mcp install
# or
playwright-mcp install-browser
```
--------------------------------
### ESM Import Example
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/exports.md
Example demonstrating how to import the createConnection function using ECMAScript Module (ESM) syntax.
```javascript
import { createConnection } from '@playwright/mcp';
const server = await createConnection();
```
--------------------------------
### Install Playwright Browsers
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Use this command to install all necessary browser binaries for Playwright MCP.
```bash
npx playwright-mcp install
```
```bash
npx playwright install
```
--------------------------------
### Example Bug Report Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
An example of how to structure configuration details when reporting a bug. Remove sensitive information before submitting.
```javascript
{
timeouts: {
action: 5000,
},
capabilities: ['core'],
}
```
--------------------------------
### Basic Playwright MCP Setup with require
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/INDEX.md
Demonstrates the basic setup for Playwright MCP using `require` to import `createConnection`. This pattern is common in Node.js environments.
```javascript
const { createConnection } = require('@playwright/mcp');
async function main() {
const server = await createConnection();
}
```
--------------------------------
### Full Playwright MCP Server Setup
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
Use this snippet to start the Playwright MCP server with a comprehensive configuration. It includes browser, server, capabilities, output, timeouts, and network settings.
```javascript
const { createConnection } = require('@playwright/mcp');
async function main() {
const config = {
// Browser configuration
browser: {
browserName: 'chromium',
launchOptions: {
headless: true,
channel: 'chrome',
},
contextOptions: {
viewport: { width: 1920, height: 1080 },
},
},
// Server configuration
server: {
port: 8080,
host: 'localhost',
},
// Tool capabilities
capabilities: ['core', 'vision', 'pdf', 'network'],
// Output configuration
outputDir: './output',
// Timeouts
timeouts: {
action: 5000,
navigation: 30000,
expect: 5000,
},
// Network control
network: {
allowedOrigins: [
'https://example.com',
'http://localhost:*',
],
},
};
try {
const server = await createConnection(config);
console.log('✓ MCP server started');
console.log(' Port: 8080');
console.log(' Browser: Chromium');
console.log(' Capabilities: core, vision, pdf, network');
} catch (error) {
console.error('✗ Failed to start server:', error.message);
process.exit(1);
}
}
main();
```
--------------------------------
### Troubleshoot: Browsers Not Found
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
If browsers are not found, run the install command to download the necessary browser binaries.
```bash
# Solution: Install browsers
npx playwright-mcp install
```
--------------------------------
### Install Browsers
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
Install the necessary browser binaries (Chromium, Firefox, WebKit) required by Playwright MCP.
```bash
npx playwright-mcp install
```
--------------------------------
### Basic MCP Server Invocation
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/cli.md
Starts the MCP server with default configuration. This is the most basic way to launch the server.
```bash
playwright-mcp
```
--------------------------------
### CLI Server Start
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/README.md
Run the Playwright MCP server directly from the command line. This is useful for quick setup or when integrating with shell scripts.
```bash
playwright-mcp [command] [options]
npx @playwright/mcp@latest
```
--------------------------------
### Example Config with Capabilities
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/types.md
Demonstrates how to specify enabled tool capabilities within the `Config` object. If `capabilities` is omitted, all capabilities are enabled by default.
```typescript
const config: Config = {
capabilities: ['core', 'vision', 'pdf'],
// ... other config
};
```
--------------------------------
### Basic Server Creation
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/README.md
Demonstrates the simplest way to create an MCP server using default configurations. Ensure the '@playwright/mcp' package is installed.
```javascript
const { createConnection } = require('@playwright/mcp');
async function main() {
const server = await createConnection();
console.log('MCP server started');
}
main().catch(console.error);
```
--------------------------------
### Page-Level TypeScript Init Script Example
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Example content of a TypeScript initialization script. These scripts can define global functions and utilities available in the page context.
```typescript
// Global functions and utilities available in page context
window.myUtils = {
selectElement: (selector: string) => document.querySelector(selector),
getAllText: () => document.body.innerText,
};
```
--------------------------------
### Playwright MCP Configuration Example
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/configuration.md
A comprehensive example demonstrating how to configure various aspects of Playwright MCP, including browser settings, server details, capabilities, output directory, console logging, network origins, test ID attributes, timeouts, image responses, and secrets.
```typescript
const config: Config = {
browser: {
browserName: 'chromium',
headless: false,
launchOptions: {
channel: 'chrome',
},
contextOptions: {
viewport: { width: 1920, height: 1080 },
},
},
server: {
port: 8080,
host: '0.0.0.0',
allowedHosts: ['localhost', 'app.example.com'],
},
capabilities: ['core', 'vision', 'pdf', 'network'],
outputDir: '/tmp/playwright-output',
console: {
level: 'info',
},
network: {
allowedOrigins: ['https://example.com', 'http://localhost:*'],
},
testIdAttribute: 'data-test-id',
timeouts: {
action: 10000,
navigation: 30000,
expect: 5000,
},
imageResponses: 'allow',
secrets: {
'api-key-123': '***',
'token-secret': '***',
},
};
```
--------------------------------
### Test CDP Endpoint and Start Chrome
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Test CDP connectivity and start Chrome with CDP enabled if needed.
```bash
curl http://localhost:9222/json/version
```
```bash
google-chrome --headless --remote-debugging-port=9222
```
--------------------------------
### Start Playwright MCP Server via CLI
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
Start the Playwright MCP server directly from the command line using the default configuration.
```bash
playwright-mcp
# Starts MCP server with default config
```
--------------------------------
### Install Playwright Browsers
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/cli.md
Installs all browser binaries required by Playwright. This command ensures that Playwright has the necessary browsers to run tests.
```bash
playwright-mcp install
```
--------------------------------
### Install Playwright MCP CLI
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/cli.md
Install the playwright-mcp CLI globally using npm or use npx for direct execution.
```bash
npm install -g @playwright/mcp
# or use with npx
npx @playwright/mcp [command] [options]
```
--------------------------------
### Usage in TypeScript
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/exports.md
Example of how to import and use the createConnection function with a configuration object in a TypeScript project.
```typescript
import { createConnection } from '@playwright/mcp';
import type { Config } from '@playwright/mcp';
const config: Config = {
browser: { browserName: 'chromium' },
capabilities: ['core', 'vision'],
};
const server = await createConnection(config);
```
--------------------------------
### Example Semantic Commit Message
Source: https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md
An example demonstrating the Semantic Commit Message format for a new feature, including a description and references to GitHub issues.
```text
feat(trace viewer): network panel filtering
This patch adds a filtering toolbar to the network panel.
Fixes #123, references #234.
```
--------------------------------
### Install Playwright MCP
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
Install the Playwright MCP package using npm. You can install it locally for a project or globally for command-line access.
```bash
npm install @playwright/mcp
# or
npm install -g @playwright/mcp
```
--------------------------------
### browser_start_video
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Start video recording of the browser session. An optional filename and size can be provided.
```APIDOC
## browser_start_video
### Description
Start video recording.
### Method
Not specified (assumed to be a command/function call)
### Endpoint
Not applicable (SDK method)
### Parameters
#### Path Parameters
- **filename** (string, optional) - Filename to save the video.
- **size** (object, optional) - Video size, e.g. `{ width: 1280, height: 720 }`.
### Request Example
```
browser_start_video({ filename: 'session.mp4', size: { width: 1920, height: 1080 } })
```
### Response
No specific response details provided.
```
--------------------------------
### Development Setup for Visual Testing
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Configuration for a development environment, enabling visual testing with a non-headless browser and a larger viewport.
```javascript
const config = {
browser: {
browserName: 'chromium',
launchOptions: {
headless: false,
slowMo: 100,
},
contextOptions: {
viewport: { width: 1920, height: 1080 },
},
},
};
```
--------------------------------
### Cursor Manual Installation Command for Playwright MCP Server
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Manually install the Playwright MCP server in Cursor by using the specified command. This command should be entered in the Cursor settings for MCP servers.
```string
npx @playwright/mcp@latest
```
--------------------------------
### Install Playwright MCP Package
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Install the `@playwright/mcp` package using npm if it's not found. You can also try reinstalling `node_modules` or verifying the installation.
```bash
# Install package
npm install @playwright/mcp
# Or reinstall node_modules
rm -rf node_modules package-lock.json
npm install
# Verify installation
npm list @playwright/mcp
```
--------------------------------
### CI/CD Setup for Headless and Persistent Browsers
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Configuration optimized for CI/CD environments, using a headless browser and a persistent user data directory for state preservation.
```javascript
const config = {
browser: {
browserName: 'chromium',
userDataDir: '/tmp/ci-profile',
launchOptions: {
headless: true,
},
},
};
```
--------------------------------
### Playwright MCP Setup with Configuration Object
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/INDEX.md
Illustrates how to create a Playwright MCP connection using a configuration object. This allows specifying browser, capabilities, and output directory.
```javascript
const config = {
browser: { browserName: 'chromium' },
capabilities: ['core', 'vision'],
outputDir: './output',
};
const server = await createConnection(config);
```
--------------------------------
### Development Security Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/network-security.md
Example configuration for development environments, enabling full logging and unrestricted file access.
```javascript
const config = {
server: {
host: 'localhost',
port: 8080,
},
console: {
level: 'debug', // Full logging
},
imageResponses: 'allow',
allowUnrestrictedFileAccess: true,
};
```
--------------------------------
### Production Deployment Security Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/network-security.md
Example configuration for production deployment, focusing on security best practices like localhost binding, allowed hosts, and reduced logging.
```javascript
const config = {
server: {
host: '127.0.0.1', // Localhost only
port: 8080,
allowedHosts: ['localhost'],
},
network: {
allowedOrigins: [
'https://trusted-domain.com',
'https://api.trusted-domain.com',
],
blockedOrigins: [
'https://analytics.com',
'https://ads.com',
],
},
secrets: {
'prod-api-key': '[SECRET]',
'db-password': '[SECRET]',
},
allowUnrestrictedFileAccess: false,
console: {
level: 'warning', // Reduce noise
},
};
```
--------------------------------
### VS Code CLI MCP Server Installation
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Install the Playwright MCP server using the VS Code CLI by providing the name, command, and arguments.
```bash
# For VS Code
code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'
```
--------------------------------
### Programmatic Server Creation
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/README.md
Import and use the createConnection function to programmatically start an MCP server. This is the primary entry point for integrating the server into your application.
```javascript
const { createConnection } = require('@playwright/mcp');
const server = await createConnection(config);
```
--------------------------------
### Verify Playwright MCP Installation
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
Run a verification script to confirm that Playwright MCP is installed and functioning correctly.
```javascript
const { createConnection } = require('@playwright/mcp');
async function verify() {
try {
const server = await createConnection();
console.log('✓ Installation successful');
process.exit(0);
} catch (error) {
console.error('✗ Installation failed:', error.message);
process.exit(1);
}
}
verify();
```
--------------------------------
### Playwright MCP CLI Command Examples
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/INDEX.md
Shows how to invoke the Playwright MCP command-line interface. Includes direct invocation and execution via npx.
```bash
playwright-mcp [command]
npx @playwright/mcp@latest
```
--------------------------------
### Add Specific Capability Example
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Adds the PDF capability alongside the core capability for specific document generation needs.
```javascript
const config = {
capabilities: ['core', 'pdf'], // Core + PDF only
};
```
--------------------------------
### browser_start_tracing
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Start trace recording for debugging purposes. This operation is read-only.
```APIDOC
## browser_start_tracing
### Description
Start trace recording.
### Method
Not specified (assumed to be a command/function call)
### Endpoint
Not applicable (SDK method)
### Parameters
None
### Request Example
```
browser_start_tracing()
```
### Response
No specific response details provided.
```
--------------------------------
### Run Playwright MCP Server
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
Execute the Node.js script to start the Playwright MCP server.
```bash
node server.js
# MCP server ready
```
--------------------------------
### Commit Convention Example
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
Illustrates the conventional commit format used for commits, including labels like 'fix', 'feat', 'chore', etc., and their scopes.
```git
fix(config): handle missing userDataDir
feat(cli): add new command
```
--------------------------------
### createConnection API
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/README.md
Creates and returns a configured MCP Server instance. This function is the primary programmatic entry point for starting the MCP server.
```APIDOC
## createConnection(config?, contextGetter?)
### Description
Creates and returns a configured MCP Server instance. This function is the primary programmatic entry point for starting the MCP server.
### Method
`createConnection`
### Parameters
#### Parameters
- `config` (Config) - Optional - Object controlling browser and server behavior.
- `contextGetter` (Function) - Optional - Function returning a `BrowserContext` for custom context provision.
### Returns
- `Promise` - Promise resolving to an MCP Server instance.
### Examples
#### Basic Server Creation
```javascript
const { createConnection } = require('@playwright/mcp');
async function main() {
const server = await createConnection();
console.log('MCP server started');
}
main().catch(console.error);
```
#### With Custom Configuration
```javascript
const { createConnection } = require('@playwright/mcp');
const config = {
browser: { browserName: 'chromium' },
server: { port: 8080 },
capabilities: ['core', 'vision', 'pdf'],
outputDir: './output',
};
const server = await createConnection(config);
```
#### With Existing Browser Context
```javascript
const { createConnection } = require('@playwright/mcp');
const { chromium } = require('playwright');
const browser = await chromium.launch();
const context = await browser.newContext();
const server = await createConnection(
{ capabilities: ['core', 'vision'] },
async () => context
);
```
### See Also
- [API Reference](./api-reference.md) for complete documentation.
```
--------------------------------
### Cline Local Setup for Playwright MCP Server
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Configure the Playwright MCP server for local setup in Cline by adding this configuration to your `cline_mcp_settings.json` file. It specifies the server type, command, and arguments.
```json
{
"mcpServers": {
"playwright": {
"type": "stdio",
"command": "npx",
"timeout": 30,
"args": [
"-y",
"@playwright/mcp@latest"
],
"disabled": false
}
}
}
```
--------------------------------
### Start Standalone MCP Server
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Run the MCP server from an environment with the DISPLAY variable set. Use the --port flag to enable HTTP transport for headed browser instances or when running from IDE worker processes.
```bash
npx @playwright/mcp@latest --port 8931
```
--------------------------------
### Check Browser Executable Path
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Verify the installation path of the Chromium browser executable. This is useful for ensuring Playwright can locate the browser.
```bash
which chromium
which firefox
which webkit
```
--------------------------------
### Reinstall Playwright Browsers
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Reinstall browsers if they are missing or corrupt. This command also installs system dependencies on Linux.
```bash
npx playwright-mcp install
```
```bash
npx playwright install-deps
```
```bash
ps aux | grep chrome
```
```bash
rm -rf ~/.cache/ms-playwright
npx playwright-mcp install
```
--------------------------------
### Performance: Faster Startup Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Minimal capability configuration for faster tool initialization.
```javascript
// Faster startup
const config = {
capabilities: ['core'],
};
```
--------------------------------
### Environment-Based Configuration Example
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/advanced-configuration.md
Dynamically configure Playwright settings based on the Node.js environment variable `NODE_ENV`. Adjusts timeouts, logging, output, and session saving.
```javascript
const isDev = process.env.NODE_ENV === 'development';
const isProd = process.env.NODE_ENV === 'production';
const config = {
timeouts: {
action: isDev ? 10000 : 5000,
navigation: isProd ? 30000 : 60000,
expect: isDev ? 10000 : 5000,
},
console: {
level: isDev ? 'debug' : 'error',
},
imageResponses: isDev ? 'allow' : 'omit',
outputDir: process.env.OUTPUT_DIR || './output',
saveSession: !isProd,
allowUnrestrictedFileAccess: isDev,
};
```
--------------------------------
### Dockerfile for MCP Server
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
A basic Dockerfile setup for creating a containerized MCP server using a Node.js 18 slim image. It exposes port 8080 and sets the default command.
```dockerfile
FROM node:18-slim
# ... setup
EXPOSE 8080
CMD ["playwright-mcp"]
```
--------------------------------
### Initialize Playwright Page State
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Use `--init-page` to point to a TypeScript file that sets up the Playwright page object. This allows arbitrary code execution for page setup, such as granting permissions, setting geolocation, and configuring the viewport.
```typescript
// init-page.ts
export default async ({ page }) => {
await page.context().grantPermissions(['geolocation']);
await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
await page.setViewportSize({ width: 1280, height: 720 });
};
```
--------------------------------
### Programmatic Playwright MCP Server with SSE
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Create a headless Playwright MCP server programmatically using Node.js. This example demonstrates setting up an HTTP server and connecting it with an SSEServerTransport.
```js
import http from 'http';
import { createConnection } from '@playwright/mcp';
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
http.createServer(async (req, res) => {
// ...
// Creates a headless Playwright MCP server with SSE transport
const connection = await createConnection({ browser: { launchOptions: { headless: true } } });
const transport = new SSEServerTransport('/messages', res);
await connection.connect(transport);
// ...
});
```
--------------------------------
### Minimal Playwright MCP Connection
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/INDEX.md
Establishes a basic connection to Playwright MCP with default settings. This is the simplest way to get started.
```javascript
const server = await createConnection();
```
--------------------------------
### CLI Commands for Playwright MCP
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/README.md
Execute Playwright MCP commands via the command line interface. Use 'install' to download necessary browser binaries.
```bash
# Default server
playwright-mcp
# Install browsers
playwright-mcp install
# With npm
npx @playwright/mcp@latest
```
--------------------------------
### Connect to Playwright Server
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Configure Playwright to connect to a browser managed by a running Playwright server. Ensure the server is started with `npx playwright server`.
```javascript
const config = {
browser: {
remoteEndpoint: 'ws://localhost:3000',
},
};
// Start server: npx playwright server
```
--------------------------------
### Troubleshoot Docker Run Failures
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Run the Docker container with an interactive terminal (`-it`) to debug. Verify the browser installation or run with increased resources (`-m`, `--cpus`) if the container exits with an error.
```bash
# Run with interactive terminal
docker run -it playwright-mcp:latest /bin/bash
# Check browser installed
docker run playwright-mcp:latest playwright-mcp install
# Run with more resources
docker run -m 2g --cpus 2 playwright-mcp:latest
```
--------------------------------
### Launch Local Browser Instance
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Default configuration to launch a new local browser instance. Allows specifying browser name, launch options like headless mode, and context options like viewport size.
```javascript
const config = {
browser: {
browserName: 'chromium',
launchOptions: {
headless: false,
},
contextOptions: {
viewport: { width: 1920, height: 1080 },
},
},
};
```
--------------------------------
### Basic Launch Options Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Configure basic browser launch options, including headless mode, channel selection, and slowing down interactions.
```javascript
const config = {
browser: {
launchOptions: {
headless: true,
channel: 'chrome',
slowMo: 100,
},
},
};
```
--------------------------------
### Performance: Comprehensive Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Comprehensive capability configuration, resulting in the slowest startup time.
```javascript
// Comprehensive (slowest startup)
const config = {
capabilities: [
'config',
'core',
'core-navigation',
'core-tabs',
'core-input',
'core-install',
'network',
'pdf',
'storage',
'testing',
'vision',
'devtools',
],
};
```
--------------------------------
### Initialize Browser Environment with JavaScript
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Use `--init-script` to provide a JavaScript file that acts as an initialization script. This script is evaluated in every page before its own scripts, useful for overriding browser APIs or setting up the environment.
```javascript
// init-script.js
window.isPlaywrightMCP = true;
```
--------------------------------
### Server Creation with Custom Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/README.md
Configure the MCP server's browser, server port, capabilities, and output directory. This allows tailoring the server to specific project needs.
```javascript
const { createConnection } = require('@playwright/mcp');
const config = {
browser: { browserName: 'chromium' },
server: { port: 8080 },
capabilities: ['core', 'vision', 'pdf'],
outputDir: './output',
};
const server = await createConnection(config);
```
--------------------------------
### Enable Browser Installation Management
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Configure Playwright MCP to enable only browser installation and management features. This capability is useful for managing browser versions in CI/CD environments.
```javascript
const config = {
capabilities: ['core-install'],
};
```
--------------------------------
### browser_mouse_drag_xy
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Drags the left mouse button from a starting position to an ending position.
```APIDOC
## browser_mouse_drag_xy
### Description
Drag left mouse button to a given position
### Parameters
#### Path Parameters
- **startX** (number) - Required - Start X coordinate
- **startY** (number) - Required - Start Y coordinate
- **endX** (number) - Required - End X coordinate
- **endY** (number) - Required - End Y coordinate
```
--------------------------------
### Performance: Standard Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Standard capability configuration including core, vision, and PDF.
```javascript
// Standard
const config = {
capabilities: ['core', 'vision', 'pdf'],
};
```
--------------------------------
### Configure Server Host for All Interfaces
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/network-security.md
Set the server host to '0.0.0.0' to allow connections from any client. Use this setting with caution as it exposes the server to all network interfaces.
```javascript
const config = {
server: {
host: '0.0.0.0',
},
};
```
--------------------------------
### Lightweight (API) Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Minimal configuration for API-focused tasks, including core automation and server info.
```javascript
const config = {
capabilities: [
'core', // Just automation
'config', // Server info
],
};
```
--------------------------------
### Create MCP Connection - Basic Usage
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/api-reference.md
Use this snippet to create a basic MCP server instance. It initializes Playwright and registers MCP tools for browser automation.
```javascript
const { createConnection } = require('@playwright/mcp');
async function main() {
const server = await createConnection();
// Server is now ready to handle MCP client requests
}
main().catch(console.error);
```
--------------------------------
### Configure Shared Browser Context
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/advanced-configuration.md
Control whether to reuse the same browser context across all clients. By default, each client gets an isolated context.
```javascript
const config = {
sharedBrowserContext: false, // Default: one context per client
};
```
```javascript
const config = {
sharedBrowserContext: true,
};
```
--------------------------------
### Playwright MCP Configuration File Schema
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Example of a Playwright MCP configuration file in TypeScript, detailing various browser, server, and capability settings.
```typescript
{
/**
* The browser to use.
*/
browser?: {
/**
* The type of browser to use.
*/
browserName?: 'chromium' | 'firefox' | 'webkit';
/**
* Keep the browser profile in memory, do not save it to disk.
*/
isolated?: boolean;
/**
* Path to a user data directory for browser profile persistence.
* Temporary directory is created by default.
*/
userDataDir?: string;
/**
* Launch options passed to
* @see https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context
*
* This is useful for settings options like `channel`, `headless`, `executablePath`, etc.
*/
launchOptions?: playwright.LaunchOptions;
/**
* Context options for the browser context.
*
* This is useful for settings options like `viewport`.
*/
contextOptions?: playwright.BrowserContextOptions;
/**
* Chrome DevTools Protocol endpoint to connect to an existing browser instance in case of Chromium family browsers.
*/
cdpEndpoint?: string;
/**
* CDP headers to send with the connect request.
*/
cdpHeaders?: Record;
/**
* Timeout in milliseconds for connecting to CDP endpoint. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
*/
cdpTimeout?: number;
/**
* Remote endpoint to connect to an existing Playwright server. May be a
* WebSocket URL string, or a [ConnectOptions] object that mirrors the
* `connectOptions` shape used by the test runner. When passed as an object,
* `exposeNetwork`, `headers`, `slowMo`, and `timeout` are forwarded to the
* underlying connect call.
*/
remoteEndpoint?: string | playwright.ConnectOptions & { endpoint: string };
/**
* Paths to TypeScript files to add as initialization scripts for Playwright page.
*/
initPage?: string[];
/**
* Paths to JavaScript files to add as initialization scripts.
* The scripts will be evaluated in every page before any of the page's scripts.
*/
initScript?: string[];
},
/**
* Connect to a running browser instance (Edge/Chrome only). If specified, `browser`
* config is ignored.
* Requires the "Playwright Extension" to be installed.
*/
extension?: boolean;
server?: {
/**
* The port to listen on for SSE or MCP transport.
*/
port?: number;
/**
* The host to bind the server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.
*/
host?: string;
/**
* The hosts this server is allowed to serve from. Defaults to the host server is bound to.
* This is not for CORS, but rather for the DNS rebinding protection.
*/
allowedHosts?: string[];
},
/**
* List of enabled tool capabilities. Possible values:
* - 'core': Core browser automation features.
* - 'pdf': PDF generation and manipulation.
* - 'vision': Coordinate-based interactions.
* - 'devtools': Developer tools features.
*/
capabilities?: ToolCapability[];
/**
* Whether to save the Playwright session into the output directory.
*/
saveSession?: boolean;
/**
* Reuse the same browser context between all connected HTTP clients.
*/
sharedBrowserContext?: boolean;
}
```
--------------------------------
### Full Browser Simulation Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Comprehensive configuration for full browser simulation, enabling all major capabilities.
```javascript
const config = {
capabilities: [
'core',
'core-navigation',
'core-tabs',
'core-input',
'core-install',
'network',
'pdf',
'storage',
'testing',
'vision',
'devtools',
'config',
],
};
```
--------------------------------
### Configure Browser Launch Arguments
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Pass arguments to the browser executable during launch. Useful for disabling browser features or setting specific startup behaviors.
```javascript
const config = {
browser: {
launchOptions: {
args: [
'--disable-blink-features=AutomationControlled',
'--start-maximized',
'--user-data-dir=/tmp/profile',
],
},
},
};
```
--------------------------------
### Create MCP Connection - Custom Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/api-reference.md
Use this snippet to create an MCP server instance with custom browser, server, and capability configurations. This allows fine-tuning of the server's behavior and resource allocation.
```javascript
const { createConnection } = require('@playwright/mcp');
async function main() {
const config = {
browser: {
browserName: 'chromium',
headless: false,
},
server: {
port: 8080,
host: '0.0.0.0',
},
capabilities: ['core', 'vision', 'pdf'],
outputDir: '/tmp/playwright-output',
};
const server = await createConnection(config);
// Server is now running with custom configuration
}
main().catch(console.error);
```
--------------------------------
### Load JavaScript Initialization Scripts
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Specify paths to JavaScript files that should be executed in each page context. These scripts are useful for polyfills and test utilities.
```javascript
const config = {
browser: {
initScript: [
'/path/to/polyfill.js',
'/path/to/setup.js',
],
},
};
```
--------------------------------
### Run Docker Container with Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
Manual command to run the Docker container with environment variables and volume mounts. It sets OUTPUT_DIR and maps a local directory to /output.
```bash
docker run -it -e OUTPUT_DIR=/output -v /tmp:/output \
-p 8080:8080 playwright-mcp-dev:latest
```
--------------------------------
### Resolve TypeScript Type Errors
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Ensure correct imports for types like `Config` from `@playwright/mcp`. Install type definitions if necessary and force TypeScript to reload its cache.
```typescript
// Check import
import type { Config } from '@playwright/mcp';
// Or ensure @playwright/mcp is installed
// npm install --save-dev @types/@playwright/mcp
// Force TypeScript to reload
rm -rf node_modules/.typescript
npm i
```
--------------------------------
### Connect via Browser Extension
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Use this configuration to connect to an existing browser instance via the Playwright Extension. Requires Chrome or Edge with the extension installed and running.
```javascript
const config = {
extension: true,
// browser config is ignored when extension is true
};
```
--------------------------------
### Debug Connection Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Log the configuration object and attempt to create a connection using `createConnection`. This helps in debugging connection issues by showing the exact config and catching errors.
```javascript
const { createConnection } = require('@playwright/mcp');
async function debug() {
const config = {
browser: { browserName: 'chromium' },
// ... your config
};
console.log('Config:', JSON.stringify(config, null, 2));
try {
const server = await createConnection(config);
console.log('✓ Server created successfully');
} catch (error) {
console.error('✗ Failed:', error);
console.error('Stack:', error.stack);
}
}
debug();
```
--------------------------------
### Troubleshoot File Access Denied
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/network-security.md
Check the `allowUnrestrictedFileAccess` setting to resolve file access denied errors.
```javascript
const config = {
allowUnrestrictedFileAccess: true, // Allow if needed
};
```
--------------------------------
### Load TypeScript Initialization Scripts
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Specify paths to TypeScript files that should be executed in each page context. These scripts are loaded before any page scripts.
```javascript
const config = {
browser: {
initPage: [
'/path/to/setup.ts',
'/path/to/utils.ts',
],
},
};
```
--------------------------------
### Get Chromium Executable Path in Node.js
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Retrieve the file path of the Chromium executable using Playwright within a Node.js environment. This confirms Playwright's access to the browser.
```javascript
const { chromium } = require('playwright');
chromium.executablePath().then(path => {
console.log('Chromium at:', path);
});
```
--------------------------------
### Emulate Mobile Device Viewport and Properties
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Configure context options to emulate a specific mobile device, including viewport, device scale factor, and touch support.
```javascript
const config = {
browser: {
contextOptions: {
// Emulate iPhone 12
viewport: { width: 390, height: 844 },
deviceScaleFactor: 3,
isMobile: true,
hasTouch: true,
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)...',
},
},
};
```
--------------------------------
### High-Performance Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/advanced-configuration.md
Configuration optimized for minimal overhead and fast execution, featuring short timeouts, minimal output, reduced logging, and no code generation.
```javascript
const config = {
// Fast timeouts
timeouts: {
action: 3000,
navigation: 30000,
expect: 3000,
},
// Minimal output
imageResponses: 'omit',
snapshot: { mode: 'none' },
// Reduced logging
console: { level: 'warning' },
// No code generation
codegen: 'none',
// Core capabilities only
capabilities: ['core'],
};
```
--------------------------------
### Basic Web Automation Capabilities
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Combines core, navigation, and input capabilities for basic web automation.
```javascript
capabilities: ['core', 'core-navigation', 'core-input']
```
--------------------------------
### Create Playwright MCP Server (Node.js)
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
Create a basic Playwright MCP server instance using Node.js. This is the entry point for most automation tasks.
```javascript
const { createConnection } = require('@playwright/mcp');
async function main() {
const server = await createConnection();
console.log('✓ MCP server ready');
}
main().catch(console.error);
```
--------------------------------
### Config Capability Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Enable the config capability for server management and configuration tools.
```javascript
const config = {
capabilities: ['config'],
};
```
--------------------------------
### Headless Server Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/quickstart.md
Configure Playwright MCP to run in headless mode using Chromium.
```javascript
const { createConnection } = require('@playwright/mcp');
const config = {
browser: {
browserName: 'chromium',
launchOptions: { headless: true },
},
};
const server = await createConnection(config);
```
--------------------------------
### LLM-Optimized Capabilities
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Minimal overhead configuration for LLM-optimized scenarios, including core and vision.
```javascript
capabilities: ['core', 'vision']
```
--------------------------------
### Configure All Timeouts
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/advanced-configuration.md
Set specific timeouts for action, navigation, and expect operations simultaneously in a single configuration object.
```javascript
const config = {
timeouts: {
action: 5000, // Interaction timeout
navigation: 60000, // Page load timeout
expect: 5000, // Assertion timeout
},
};
```
--------------------------------
### Configure Proxy Settings
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Configure proxy settings for the browser launch, including the proxy server address and domains to bypass.
```javascript
const config = {
browser: {
launchOptions: {
proxy: {
server: 'http://proxy.example.com:8080',
bypass: '.example.com, 127.0.0.1',
},
},
},
};
```
--------------------------------
### Configure HTTP Credentials
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Set basic HTTP authentication credentials for the browser context. This will automatically handle authentication for protected resources.
```javascript
const config = {
browser: {
contextOptions: {
httpCredentials: {
username: 'user',
password: 'pass',
},
},
},
};
```
--------------------------------
### Configure Playwright MCP Server with JSON
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Configure the Playwright MCP server by specifying a JSON configuration file using the `--config` command line option.
```bash
npx @playwright/mcp@latest --config path/to/config.json
```
--------------------------------
### Publish to NPM Registry
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
Command to publish the package to the npm registry after linting and testing. Ensures documentation and tests are up-to-date.
```bash
npm run npm-publish
```
--------------------------------
### browser_video_chapter
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Adds a chapter marker to the video recording, displaying a full-screen chapter card.
```APIDOC
## browser_video_chapter
### Description
Add a chapter marker to the video recording. Shows a full-screen chapter card with blurred backdrop.
### Parameters
#### Path Parameters
- **title** (string) - Required - Chapter title
- **description** (string) - Optional - Chapter description
- **duration** (number) - Optional - Duration in milliseconds to show the chapter card
```
--------------------------------
### Check and Upgrade Node.js Version
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Verify your Node.js version using `node --version`. Upgrade to Node.js 18 or later if it's too old, using tools like `nvm` or by downloading from nodejs.org.
```bash
# Check Node version
node --version
# Upgrade Node.js
# Using nvm (Node Version Manager)
nvm install 18
nvm use 18
# Or download from nodejs.org
```
--------------------------------
### Add HTTP Credentials
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Configure HTTP credentials in the browser context options if required for authentication.
```javascript
// Add HTTP credentials if needed
const config = {
browser: {
contextOptions: {
httpCredentials: {
username: 'user',
password: 'pass',
},
},
},
};
```
--------------------------------
### Specify Browser Channel
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/browser-configuration.md
Configure the specific browser channel to use for launching, such as stable Chrome, beta, canary, or Edge channels.
```javascript
const config = {
browser: {
launchOptions: {
channel: 'chrome',
// or:
// channel: 'chrome-beta',
// channel: 'chrome-canary',
// channel: 'chromium',
// channel: 'msedge',
// channel: 'msedge-beta',
},
},
};
```
--------------------------------
### Run All Tests
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
Executes all test suites, including Chrome, Firefox, WebKit, and Docker modes. This is the primary command for verifying package integrity.
```bash
npm test
```
--------------------------------
### Build Playwright MCP Docker Image
Source: https://github.com/microsoft/playwright-mcp/blob/main/README.md
Build the Docker image for Playwright MCP locally. This command tags the image as 'mcr.microsoft.com/playwright/mcp'.
```bash
docker build -t mcr.microsoft.com/playwright/mcp .
```
--------------------------------
### Development Dependencies
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
Lists dependencies needed for development, including the MCP SDK, Playwright test framework, and Node.js type definitions.
```json
{
"@modelcontextprotocol/sdk": "^1.25.2",
"@playwright/test": "1.61.0-alpha-1778188671000",
"@types/node": "^24.3.0"
}
```
--------------------------------
### Development Configuration
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/advanced-configuration.md
Configuration for development environments, providing generous timeouts, full output, verbose logging, code generation, and all capabilities for comprehensive diagnostics.
```javascript
const config = {
// Generous timeouts
timeouts: {
action: 10000,
navigation: 120000,
expect: 10000,
},
// Full output
imageResponses: 'allow',
snapshot: { mode: 'full' },
// Verbose logging
console: { level: 'debug' },
// Enable code generation
codegen: 'typescript',
// All capabilities
capabilities: [
'core',
'core-navigation',
'core-tabs',
'core-input',
'vision',
'pdf',
'network',
'storage',
'testing',
'devtools',
],
// Diagnostic output
outputDir: './diagnostic-output',
saveSession: true,
};
```
--------------------------------
### Build Docker Image Manually
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
Manual command to build the Docker image using 'docker build'. It tags the image as 'playwright-mcp-dev:latest'.
```bash
docker build -t playwright-mcp-dev:latest .
```
--------------------------------
### createConnection Function
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/exports.md
The `createConnection` function is the primary way to create an MCP Server instance. It can optionally accept configuration and a browser context getter.
```APIDOC
## createConnection
### Description
Function that creates an MCP Server instance.
### Method
```typescript
function createConnection(
config?: Config,
contextGetter?: () => Promise
): Promise
```
### Parameters
#### Optional Parameters
- **config** (Config) - Configuration object for the MCP Server.
- **contextGetter** (() => Promise) - A function that returns a Promise resolving to a Playwright BrowserContext.
### Returns
- **Promise** - A Promise that resolves to the MCP Server instance.
### See
- [API Reference](./api-reference.md)
- [Configuration Guide](./configuration.md)
- [Playwright Documentation](https://playwright.dev/docs/api/class-browsercontext)
```
--------------------------------
### Web Testing Capabilities
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/capabilities-reference.md
Includes core, navigation, tabs, input, testing, and storage for comprehensive web testing.
```javascript
capabilities: [
'core',
'core-navigation',
'core-tabs',
'core-input',
'testing',
'storage',
]
```
--------------------------------
### Configure Server Host for Specific Interface
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/network-security.md
Bind the server to a specific IP address to listen only on that particular network interface. This provides more granular control over network accessibility.
```javascript
const config = {
server: {
host: '192.168.1.100', // Specific IP address
},
};
```
--------------------------------
### Troubleshoot Docker Build Failures
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/troubleshooting.md
Ensure Docker is running using `docker ps`. Rebuild the image with `--no-cache` for verbose output and check container logs if the Docker build fails.
```bash
# Check Docker is running
docker ps
# Rebuild with verbose output
docker build --no-cache -t playwright-mcp:latest .
# Check logs
docker logs
```
--------------------------------
### Build Docker Image
Source: https://github.com/microsoft/playwright-mcp/blob/main/_autodocs/architecture.md
Command to build the Docker image for the Playwright-MCP development environment. This creates a tagged image for subsequent use.
```bash
npm run docker-build
```