Playwright Model Context Protocol (MCP) Server

repository·main·Indexed 12 days ago

https://github.com/microsoft/playwright-mcp

A Model Context Protocol server that enables LLMs to perform browser automation using Playwright. It utilizes structured accessibility snapshots instead of visual screenshots to provide a token-efficient and deterministic interface for agents. Features include core automation tools, tab management, network mocking, storage management for cookies and localStorage, and DevTools debugging capabilities. Supports installation via npx, Docker, and programmatic integration using the @playwright/mcp package.

Tokens
4.3K
Snippets
12
Records
23
Agent score
99%

What's inside Playwright MCP

  1. Overview of Playwright MCP

    main
    Playwright MCP is a Model Context Protocol (MCP) server that provides browser automation capabilities using Playwright. It enables LLMs to interact with web pages through structured accessibility snapshots, which is more token-efficient and deterministic than using screenshots or vision models. It is particularly useful for exploratory automation, self-healing tests, or long-running autonomous workflows that require persistent state and rich page introspection.
  2. Run Playwright MCP via Docker

    main

    You can run Playwright MCP using Docker in two ways:

    1. As an MCP server spawned by a client: Use the following configuration in your MCP client settings to have it manage the container lifecycle.

    2. As a long-lived service: Run the container in detached mode. The server will listen on host port 8931 and can be reached by any MCP client.

    Note: The Docker implementation currently only supports headless Chromium.

    {
      "mcpServers": {
        "playwright": {
          "command": "docker",
          "args": ["run", "-i", "--rm", "--init", "--pull=always", "mcr.microsoft.com/playwright/mcp"]
        }
      }
    }
    docker run -d -i --rm --init --pull=always \
      --entrypoint node \
      --name playwright \
      -p 8931:8931 \
      mcr.microsoft.com/playwright/mcp \
      /app/cli.js --headless --browser chromium --no-sandbox --port 8931 --host 0.0.0.0
  3. Initialize browser state with scripts

    main

    You can provide initial state to the browser context or page using TypeScript or JavaScript files:

    Using --init-page (TypeScript)

    Evaluates a TypeScript file on the Playwright page object. Useful for setting permissions or viewport.

    // 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 });
    };

    Using --init-script (JavaScript)

    Adds a JavaScript file as an initialization script that runs in every page before other scripts. Useful for overriding browser APIs.

    // init-script.js
    window.isPlaywrightMCP = true;
  4. Install Playwright MCP via standard config

    main

    Most MCP clients (like Claude Desktop or Gemini CLI) can be configured using a standard JSON configuration. This uses npx to run the latest version of the server.

    {
      "mcpServers": {
        "playwright": {
          "command": "npx",
          "args": [
            "@playwright/mcp@latest"
          ]
        }
      }
    }
  5. Run Playwright MCP as a standalone server with HTTP transport

    main

    If you are running a headed browser on a system without a display (or from an IDE worker process), you can run the MCP server with a specific port to enable HTTP transport.

    1. Start the server:
    npx @playwright/mcp@latest --port 8931
    1. Configure your MCP client to use the URL:
    {
      "mcpServers": {
        "playwright": {
          "url": "http://localhost:8931/mcp"
        }
      }
    }
  6. Install Playwright MCP in VS Code

    main

    You can install the Playwright MCP server in VS Code using the built-in MCP installation command via the CLI:

    code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'

    Alternatively, you can follow the standard VS Code MCP installation guide and use the standard JSON configuration.

    # For VS Code
    code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'
  7. Playwright MCP Configuration File Schema

    main

    You can use a JSON configuration file instead of CLI arguments by specifying it with the --config <path> flag. The schema supports the following main sections:

    • browser: Configuration for the browser instance (e.g., browserName, isolated, userDataDir, launchOptions, contextOptions, cdpEndpoint, initPage, initScript).
    • server: Server-side settings (e.g., port, host, allowedHosts).
    • capabilities: List of enabled tool capabilities (core, pdf, vision, devtools).
    • timeouts: Default timeouts for action, navigation, expect, and settle.
    • network: Origin control (allowedOrigins, blockedOrigins).
    • snapshot: Snapshot settings (mode, boxes).
  8. Implement Playwright MCP programmatically

    main

    You can create a headless Playwright MCP server using the @playwright/mcp package and an SSE (Server-Sent Events) transport. This is useful when integrating the server into an existing Node.js HTTP server.

    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);
    });
  9. Manage browser tabs

    main

    Use the browser_tabs tool to manage multiple tabs within a session.

    Parameters:

    • action (string): The operation to perform (e.g., list, create, close, select).
    • index (number, optional): Tab index for close or select operations.
    • url (string, optional): URL to navigate to when using the new action.
  10. Configure Playwright MCP projects and Docker mode

    main

    The Playwright configuration for this project supports a specialized chromium-docker project when the MCP_IN_DOCKER environment variable is set. This project is configured to only run tests matching the grep pattern /browser_navigate|browser_click/ and uses specific use options to enable Docker-based browser execution.

    Key configuration options for the Docker project:

    • mcpBrowser: Set to 'chromium' to specify the browser type.
    • mcpMode: Set to 'docker' to enable Docker mode.

    Note: The chromium-docker project is only included in the projects array if process.env.MCP_IN_DOCKER is truthy.

    // Example of the configuration applied when MCP_IN_DOCKER is set
    projects: [
      { name: 'chrome' },
      {
        name: 'chromium-docker',
        grep: /browser_navigate|browser_click/,
        use: {
          mcpBrowser: 'chromium',
          mcpMode: 'docker' as const
        }
      }
    ]