Cloudflare Playwright Model Context Protocol (MCP) Server

repository·main·Indexed 42 days ago

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

A Model Context Protocol (MCP) server that enables LLMs to interact with a web browser via Playwright, hosted on Cloudflare Workers using Browser Rendering. It supports two interaction modes: Snapshot Mode for accessibility-based page structure and Vision Mode for coordinate-based visual interaction. Includes tools for navigation, resource extraction, and browser management, and can be integrated with Claude Desktop, VS Code, and Cursor.

Tokens
10.4K
Snippets
37
Records
51
Agent score
54%

What's inside Cloudflare Playwright MCP

  1. Understand Tool Modes: Snapshot vs Vision

    main

    The Playwright MCP tools operate in two distinct modes:

    1. Snapshot Mode (default): Uses accessibility snapshots. This is optimized for performance and reliability when an LLM needs to understand page structure.
    2. Vision Mode: Uses screenshots. This is best suited for 'computer use' models that interact with elements using X/Y coordinates based on visual input.

    When using Vision Mode, specific tools prefixed with browser_screen_ (e.g., browser_screen_click, browser_screen_move_mouse) are used to interact with the page visually.

  2. Enable inline screenshots in Cursor

    main

    By default, when imageResponses is set to "auto", the server disables inline image responses for Cursor clients. To enable inline screenshots in Cursor, you must override this behavior when creating the MCP agent in your Cloudflare Worker code:

    export const PlaywrightMCP = createMcpAgent(env.BROWSER, {
      imageResponses: 'allow',
    } as any);
  3. Use with Claude Desktop

    main

    Since Claude Desktop only supports local MCP servers, use mcp-remote to proxy your remote Cloudflare Worker.

    1. Open your Claude Desktop configuration file.
    2. Add the following JSON under the mcpServers section:
    {
      "mcpServers": {
        "cloudflare-playwright-mcp": {
          "command": "npx",
          "args": [
            "mcp-remote",
            "https://[my-mcp-url].workers.dev/sse"
          ]
        }
      }
    }
    1. Restart Claude Desktop to apply the changes.
  4. Configure in VS Code and VS Code Insiders

    main

    Install the Playwright MCP server via the VS Code CLI to use it with your GitHub Copilot agent.

    For VS Code:

    code --add-mcp '{"name":"cloudflare-playwright","type":"sse","url":"https://[my-mcp-url].workers.dev/sse"}'

    For VS Code Insiders:

    code-insiders --add-mcp '{"name":"cloudflare-playwright","type":"sse","url":"https://[my-mcp-url].workers.dev/sse"}'
  5. Build and Deploy Cloudflare Playwright MCP

    main

    To set up and deploy the project to Cloudflare Workers, follow these steps:

    1. Install dependencies in the root directory:
      npm ci
    2. Build the Cloudflare project:
      cd cloudflare
      npm run build
    3. Deploy the example worker:
      cd cloudflare/example
      npm ci
      npx wrangler deploy
    npm ci
    cd cloudflare
    npm run build
    cd cloudflare/example
    npm ci
    npx wrangler deploy
  6. Use with Cloudflare AI Playground

    main

    You can test the MCP server using Cloudflare playground AI.

    1. Navigate to the playground.
    2. Set the model to llama-3.3-70b-instruct-fp8-fast.
    3. In the MCP Servers section, set the URL to your deployed worker's SSE endpoint: https://[my-mcp-url].workers.dev/sse.
    4. Click Connect. The status should update to Connected and list 14 available tools.

    Tip: For best results, provide simple, single-action instructions like "Take a screenshot" or "Go to cloudflare site".

  7. Use persistent browser contexts

    main

    By default, if no specific connection type (Remote, CDP, etc.) is specified, the system uses PersistentContextFactory. This mode uses a userDataDir to maintain state across sessions.

    • If userDataDir is provided in the config, it uses that directory.
    • If not provided, it automatically creates a directory in the system's cache folder (e.g., ~/.cache/ms-playwright/... on Linux, Library/Caches on macOS, or AppData/Local on Windows).
    • Note: If the user data directory is already in use by another process, the factory will retry several times before throwing an error. To avoid this, use the isolated: true configuration to run multiple instances without shared state.
  8. Configure browser connection modes

    main

    The contextFactory selects an implementation based on the following configuration properties in your browser config object:

    • Remote: If remoteEndpoint is provided, uses RemoteContextFactory to connect via a URL.
    • CDP: If cdpEndpoint is provided, uses CdpContextFactory to connect via Chrome DevTools Protocol.
    • Isolated: If isolated: true is provided, uses IsolatedContextFactory to launch a fresh, non-persistent browser instance.
    • Browser Agent: If browserAgent is provided, uses BrowserServerContextFactory to request a browser launch from a remote agent.
    • Persistent (Default): If none of the above are provided, uses PersistentContextFactory to launch a browser with a persistent user data directory.
  9. Understand tool availability and modal state constraints

    main

    Tools in this MCP implementation are subject to state-based constraints involving 'modal states'.

    1. Tool Selection: Tools are filtered by config.capabilities. If a tool's capability is not 'core' and is not included in your config.capabilities array, it will not be available.
    2. Modal State Enforcement:
      • If a tool is marked with clearsModalState, it can only be executed if a matching modal state is currently present in the context.
      • If a tool is not marked with clearsModalState, it cannot be executed if any modal states are currently active (as the tool does not handle them).

    If these conditions are not met, the tool call will return an error message describing the current modal states.

  10. Configure network and capabilities via CLI

    main

    Control network access and tool capabilities through these options:

    • --allowed-origins: Array of allowed origins.
    • --blocked-origins: Array of blocked origins.
    • --block-service-workers: Boolean to block service workers.
    • --ignore-https-errors: Boolean to ignore HTTPS errors.
    • --caps: A comma-separated list of ToolCapability strings to enable specific tool features.
  11. Configure browser via CLI options

    main

    You can specify the browser and its behavior using several CLI flags:

    • --browser: Supports chrome, chrome-beta, chrome-canary, chrome-dev, chromium, msedge, msedge-beta, msedge-canary, msedge-dev, firefox, or webkit.
    • --headless: Boolean to toggle headless mode.
    • --executable-path: Path to a specific browser executable.
    • --sandbox: Boolean (defaults to true). If set to false, chromiumSandbox is disabled.
    • --device: Use Playwright device emulation (e.g., passing a device name from Playwright).
    • --viewport-size: Set dimensions using the format "width,height" (e.g., --viewport-size="800,600").
    • --storage-state: Path to a storage state file for session persistence.
    • --user-agent: Custom User Agent string.
    • --proxy-server and --proxy-bypass: Configure proxy settings.
  12. Generate Playwright tests for a specific scenario

    main

    You can use the Playwright MCP tools to generate automated tests by providing a natural language description of a user scenario. This is useful for converting manual checklists or navigation steps into executable Playwright test scripts.

    To generate a test, describe the sequence of actions a user or bot should take, such as navigating to a specific repository, clicking tabs, and expanding specific UI elements.

    ## GitHub PR Checks Navigation Checklist
    
    1. Open the [Microsoft Playwright GitHub repository](https://github.com/microsoft/playwright).
    2. Click on the **Pull requests** tab.
    3. Find and open the pull request titled **"chore: make noWaitAfter a default"**.
    4. Switch to the **Checks** tab for that pull request.
    5. Expand the **infra** check suite to view its jobs.
    6. Click on the **docs & lint** job to view its details.