TL;DR

Don't treat Playwright MCP as the security boundary: the boundary is the runner's network and the account the agent signs in as. Use one pinned, isolated, origin-limited server config, plus a CI job where the agent reaches only the app under test, signed in as a test account.

  1. Pin an exact version of the scoped @playwright/mcp package as a dev dependency, install with npm ci, and launch the installed copy.
  2. Pass --isolated in CI so each session starts fresh, and seed it with --storage-state only when the task needs a login, and only with a test account's state.
  3. Drop the upload step: traces and state never go up as CI artifacts.
  4. Give the agent step one secret and a path: write the dotenv file for PLAYWRIGHT_MCP_SECRETS_FILE from one scoped CI secret that holds only the test account's credentials.
  5. Enforce egress at the runner with a firewall or proxy that allows only the test environment, give the job no route to production, and keep the origin list as the second layer.

When a Playwright MCP tool runs, it returns a structured snapshot of the page's elements, their roles and their text content to the model. The snapshot comes from the page's accessibility tree. The server's tools let the model navigate, click elements and type text. On your laptop, with the browser open in front of you, you see what it does. In a CI job, nobody does.

The setup in the Playwright MCP docs is built for that laptop. The Cursor instructions add the server with the unpinned npx @playwright/mcp@latest. The browser runs headed by default. In the default persistent mode, login state and cookies stay between sessions in a profile in the platform's cache directory.

Put that setup in a pipeline and the same agent runs next to job secrets, deploy tokens, trace files and a network route to whatever the runner can reach. Nothing in the docs' setup is wrong for a laptop. On a runner, though, we'd change each of those defaults.

The fix is one pinned, isolated, origin-limited server config, plus a CI job where the agent reaches only the app under test, signed in as a test account.

What the agent can reach

Indirect prompt injection doesn't need a bug in Playwright. It needs a page with text on it, because snapshots carry that text to the model and the model picks the next action. WebMCP widens the path: the page supplies the names, descriptions, schemas and results of WebMCP tools, so the docs say to treat them as untrusted input.

Three trust boundaries meet in one process. In the default persistent mode, login state and cookies are preserved between sessions. The pages the browser reads are untrusted. And the browser_run_code_unsafe tool runs arbitrary JavaScript in the Playwright server process, which the docs call RCE-equivalent. With that tool enabled, a page that steers the model can reach code execution on the machine that runs the server.

How far a hijacked agent gets depends on four things:

  • The server version, which decides which known bugs you carry.
  • The tools the server enables.
  • The origins the browser and the runner can reach.
  • The credentials and files the server's process can read.

The session is the prize. In the default persistent mode, login state and cookies are preserved between sessions in a profile per project, so the next session in the same project starts with the logins earlier sessions left. With --extension, the server connects to your existing browser tabs through the Playwright Extension, so the agent works in your real browser, signed in as you.

In GitHub Actions, artifacts persist data after a job has completed. A workflow can hand a secret to a step as an environment variable.

Pinning @playwright/mcp

When a client config launches a package that is not in the project's dependencies, npx installs it to a folder in the npm cache. The docs' Cursor setup adds the server in Cursor's MCP settings with the command npx @playwright/mcp@latest. npm audit reports known vulnerabilities in the dependencies configured in your project. Before you trust an inventory, search every MCP config file in the repo, each agent's included, for the servers it launches.

Anti-pattern

Latest tag in CI

The client config gets copied from the docs into the repo, and CI launches it as it is. With the latest tag, every job runs whatever was published last, with no lockfile check and no review of what changed:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"]
    }
  }
}

A bad publish reaches every job at once. In #42711, a user reported that version 0.0.80 of the MCP package, then npm's latest, was published without trusted-publisher provenance. The reporter said clients that enforce a no-downgrade trust policy cannot install 0.0.80 after having seen a trusted earlier version. A maintainer replied that provenance was restored in 0.0.81.

Fix

Pin an exact version of the scoped @playwright/mcp package, the name the docs use, as a dev dependency. Never install a lookalike package name. Install with npm ci, and launch the installed copy.

{
  "name": "checkout-web",
  "private": true,
  "devDependencies": {
    "@playwright/mcp": "0.0.81"
  }
}

The version has no caret, so package.json and the lockfile agree on one release. Replace 0.0.81 with the release you've reviewed. The client config then drops the tag:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp"]
    }
  }
}

Given a package name without a version, npx matches it with whatever version exists in the local project.

Keeping the pin current

A pin nobody bumps falls behind on known security fixes. Bump it on a schedule (quarterly works) and whenever a security advisory lands for @playwright/mcp or playwright. Read the package's published advisories before you pick a version, and pin one they list as fixed.

If a node_modules is already present, npm ci removes it before it begins its install. Add npm ls @playwright/mcp to the job: npm ls prints the installed versions of the packages you name, so the job log shows which version of @playwright/mcp is installed.

The pin covers one layer. Track the browser binaries the job installs and the Docker image it runs in as separate versions, and bump them with the same routine.

Isolated sessions

A persistent profile on a reused runner hands one job's login to the next agent.

Anti-pattern

Persistent profile on a shared runner

The server runs in its default mode on a self-hosted runner that keeps its cache directory between jobs. Persistent mode stores the profile in ms-playwright/mcp-{channel}-{workspace-hash} in the platform's cache directory, one profile per project, and keeps login state and cookies between sessions. On that runner, the next job for the same project opens the same profile, signed in as whoever the last job signed in as.

Fix

Pass --isolated in CI so each session starts fresh. Seed it with --storage-state only when the task needs a login, and only with a test account's state.

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp",
        "--isolated",
        "--storage-state",
        "test-results/setup/agent-state.json"
      ]
    }
  }
}

The state file comes from a setup project that signs in the test account, shown in the next section.

Idle closes

A headless browser launched by the server closes after an hour without tool calls. With --isolated, cookies and storage held in memory are lost on that close, and --storage-state is what keeps them. Re-seed from the state file. Don't switch back to a persistent profile to survive an idle close.

Extension mode

--extension connects the server to your existing tabs, and browsers attached that way or over --cdp-endpoint are never closed automatically. An attached browser that never closes is fine at a desk, where you can see its tabs. Keep extension mode on the laptop and out of CI.

Storage state and traces

A storage state file is a login you can copy. The file holds cookies plus the localStorage of every origin the browser visited, and the docs say never to commit these files because they carry live authentication tokens. The authentication guide states the risk directly: the cookies and headers in a state file could be used to impersonate you or your test account.

Traces carry the same secrets in another form. Trace Viewer shows the request headers, response headers, request body and response body of each recorded request, and a playwright-cli trace includes a network file with every request and response, headers and bodies included. A trace of an authenticated session is a credential file.

Keep the session down to the test account. Playwright MCP can list, get, set, and delete individual cookies. A reported bug said the MCP cookie-listing tool matched domains by substring and could return cookies from unrelated domains to the agent (#43308). The issue was closed as completed on 2026-10-13.

Anti-pattern

Credential files as artifacts

Someone turns tracing on and adds an upload step for debugging, uses the include-hidden-files input to upload hidden files, and it sweeps up the whole results folder and the auth folder. The artifact now holds live session tokens and full request bodies. People who are signed into GitHub and have read access to a repository can download workflow artifacts.

# Anti-pattern: uploads storage state and traces, live tokens and request bodies included
name: agent-run
on: workflow_dispatch
jobs:
  agent:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test --project=setup --trace on
      - run: node scripts/run-agent.mjs
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: agent-debug
          include-hidden-files: true
          path: |
            test-results/
            playwright/.auth/

Fix

Write the state under testProject.outputDir, which Playwright cleans up automatically before every test run, so no state file carries over from an earlier run. The setup test signs in the test account and writes its state there:

// tests/agent-auth.setup.ts
import { test as setup } from '@playwright/test';
import path from 'path';

setup('sign in the agent test account', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.AGENT_TEST_EMAIL!);
  await page.getByLabel('Password').fill(process.env.AGENT_TEST_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.waitForURL('/dashboard');

  const stateFile = path.join(setup.info().project.outputDir, 'agent-state.json');
  await page.context().storageState({ path: stateFile });
});

The config gives the setup project its own output folder and sets tracing explicitly:

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  use: {
    baseURL: process.env.STAGING_URL,
    // Already the default; set here so turning it on shows up in review
    trace: 'off',
  },
  projects: [
    {
      name: 'setup',
      testMatch: /agent-auth\.setup\.ts/,
      outputDir: 'test-results/setup',
    },
  ],
});

The trace option sets whether to record a trace for each test and defaults to 'off'. Drop the upload step: traces and state never go up as CI artifacts.

Allowed origins

An origin list narrows where the browser goes. It doesn't decide where the job can go.

The PLAYWRIGHT_MCP_ALLOWED_ORIGINS environment variable sets the origins the browser may request, separated by semicolons. Set it to the app under test and localhost:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp", "--isolated"],
      "env": {
        "PLAYWRIGHT_MCP_ALLOWED_ORIGINS": "https://staging.example.com;http://localhost:*"
      }
    }
  }
}

If you keep settings in the MCP config file instead, the same list goes in its allowedOrigins field. That file also takes browser options, context options, network rules and timeouts, and the docs point to the Playwright MCP repository for the full schema.

Anti-pattern

Origin list as egress control

The origin list goes in, and the runner stays as it was: free to reach production, internal services and the open internet. The variable is a browser setting. It lists the origins the browser may request.

Browser filters can fail too. A user reported in #43630 that a routing call through the MCP server that set only headers bypassed both the blocked and the allowed origin lists. The issue was closed as completed on 2026-10-25.

Fix

Don't treat Playwright MCP as the security boundary. The boundary is the runner's network and the account the agent signs in as. Enforce egress at the runner with a firewall or proxy that allows only the test environment, give the job no route to production, and keep the origin list as the second layer.

Secrets and file access

Treat anything the agent's process can read as something the agent can read. Playwright MCP gives the agent tools to click elements, type text and fill forms.

PLAYWRIGHT_MCP_SECRETS_FILE points the server at a secrets file in dotenv format. Write that file inside the job from one scoped CI secret that holds only the test account's credentials. Deploy tokens, cloud keys and reporting keys stay out of the file and out of the agent step's environment.

PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS allows file access outside the workspace. Leave it unset in CI.

Anti-pattern

Every secret in the agent step

The agent step gets the job's whole secret list as environment variables, because mapping all of them was quicker than sorting them. Or a file error stops the agent, and someone sets PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS to make the error go away. Either way, the agent's process can now read credentials the task never needed.

Fix

Give the agent step one secret and a path. This job writes the dotenv file from a single test-account secret into the runner's temp directory and passes only its path to the agent step:

name: agent-task
on: workflow_dispatch
permissions:
  contents: read
jobs:
  agent:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - name: Write the test-account secrets file
        env:
          AGENT_TEST_ACCOUNT: ${{ secrets.AGENT_TEST_ACCOUNT }}
        run: printf '%s\n' "$AGENT_TEST_ACCOUNT" > "$RUNNER_TEMP/agent.env"
      - name: Run the agent
        env:
          PLAYWRIGHT_MCP_SECRETS_FILE: ${{ runner.temp }}/agent.env
        run: node scripts/run-agent.mjs

The AGENT_TEST_ACCOUNT secret holds the dotenv lines themselves, such as AGENT_EMAIL and AGENT_PASSWORD. scripts/run-agent.mjs stands for your agent client, which launches the server from the MCP config with this environment. The top-level permissions block applies to all jobs in the workflow, and any permission it does not list is set to none.

Capabilities and tool surface

Every enabled tool is one more thing a steered model can call. MCP gates its tools by capability. The CLI doesn't: every playwright-cli command is always available. If you're moving an agent from MCP to the CLI to cut token use, count the lost gating in the trade.

Enable only the capabilities a job's task needs. browser_run_code_unsafe is a core tool, and core tools are always available and cannot be disabled, so let only trusted MCP clients reach the server. The docs say to enable that tool only for trusted MCP clients. A client that reads untrusted pages isn't a trusted client.

Anti-pattern

Every capability on

One task once needed network mocking, so every capability went into the shared config and stayed there. From then on, every agent job carries tool groups it never uses, on top of browser_run_code_unsafe, a core tool that runs arbitrary JavaScript in the Playwright server process and is RCE-equivalent.

Fix

Keep the capability list per job, sized to that job's task, and review a change to it like a permission change. If the agent also connects to the Currents MCP server, each of its tools needs one permission. The local server lists every tool, and the API key refuses what it does not allow. Give the agent a key scoped to the read tools it uses.

Docker and the Chromium sandbox

The official image is a test image, and the Docker docs say so: it is meant for testing and development only, and the docs don't recommend it for visiting untrusted websites. By default it also runs the browsers as root, which disables the Chromium sandbox.

Anti-pattern

Root test image for browsing

The image that runs the test suite gets reused for an agent that browses pages outside your app. A renderer exploit on one of those pages then lands in a browser whose sandbox is already off.

Fix

Run the agent container as a separate non-root user together with the seccomp profile from the Docker docs, which they say is needed to run Chromium with sandbox. Testing your own app and letting an agent browse pages you don't control are different threat models. An agent that browses outside your app belongs on a throwaway VM or runner with no real credentials and a fresh profile, never in the image your test suite uses.

The CI agent job

Playwright MCP runs the browser headed by default, and on Linux agents headed execution requires Xvfb to be installed. For a headed browser on a system without a display, the docs start the MCP server separately with HTTP transport. Don't take that route in CI: an HTTP server is one more listener on the runner. Use the docs' headless setup, which adds --headless to the server's args.

Anti-pattern

Agent in the deploy job

The agent becomes one more step in the job that deploys staging, since that job already knows the URL. The step can read the deploy job's job-level environment variables, which are available to all steps in the job. Like every step, it runs in the runner environment and has access to the workspace and filesystem the deploy steps used.

Fix

Give the agent a job of its own. Its MCP config runs the pinned server headless and isolated, seeded from the test account's state:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp",
        "--headless",
        "--isolated",
        "--storage-state",
        "test-results/setup/agent-state.json"
      ]
    }
  }
}

The workflow signs in the test account in a setup step, writes the secrets file and starts the agent with the origin list:

name: staging-agent
on: workflow_dispatch
permissions:
  contents: read
  id-token: write # OIDC token, so recording needs no stored key
jobs:
  agent:
    # Ephemeral runners whose firewall allows only staging
    runs-on: [self-hosted, agent-staging]
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npm ls @playwright/mcp
      - run: npx playwright install --with-deps chromium chrome
      - name: Sign in the test account
        env:
          STAGING_URL: https://staging.example.com
          AGENT_TEST_EMAIL: ${{ secrets.AGENT_TEST_EMAIL }}
          AGENT_TEST_PASSWORD: ${{ secrets.AGENT_TEST_PASSWORD }}
        run: npx playwright test --project=setup
      - name: Write the test-account secrets file
        env:
          AGENT_TEST_ACCOUNT: ${{ secrets.AGENT_TEST_ACCOUNT }}
        run: printf '%s\n' "$AGENT_TEST_ACCOUNT" > "$RUNNER_TEMP/agent.env"
      - name: Run the agent against staging
        env:
          PLAYWRIGHT_MCP_ALLOWED_ORIGINS: "https://staging.example.com;http://localhost:*"
          PLAYWRIGHT_MCP_SECRETS_FILE: ${{ runner.temp }}/agent.env
        run: node scripts/run-agent.mjs

All three secrets hold only the test account's credentials. The egress rule lives on the runner, not in the YAML: the agent-staging label stands for a runner pool you've locked to staging. The job uploads nothing.

Timeouts and recording

Set timeout-minutes to match the task instead of leaning on the server's idle close. Make the pool's runners ephemeral, so GitHub assigns each runner only one job, and wipe each runner after it is de-registered.

If the job's test steps report to Currents, record with OIDC: the reporter exchanges the job's OIDC token for a short-lived record key, so there is no record key in CI secrets for the agent to read and none to rotate. A short maximum token age in the trust policy limits how long a token that leaks from a job log stays useful. Set it close to the job's timeout.

If your agent client logs its tool calls, keep that log. Scrub it the way you would a trace before it leaves the job.

Before it goes live

Check six things before the job runs for real:

  1. The pin: package.json holds an exact @playwright/mcp version, and npm ls @playwright/mcp in the job log shows it.
  2. Isolation: the server args include --isolated, and --storage-state points at a test account's state in the setup project's output folder.
  3. Origins: PLAYWRIGHT_MCP_ALLOWED_ORIGINS lists staging and localhost and nothing else.
  4. The secrets file: it holds test-account credentials only, and PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS is unset.
  5. The tools: the capability list matches the task, and the agent client's tool permissions block browser_run_code_unsafe, a core tool the server always exposes.
  6. Egress: from the runner, staging answers and production doesn't.

Where these controls stop

Playwright MCP's help text says --allowed-origins does not serve as a security boundary and does not affect redirects. The help text for --blocked-origins says the same: it does not serve as a security boundary and does not affect redirects. The boundary is the runner's network, the test account and the job's credentials. Playwright MCP's config schema calls the file-access restriction not a secure boundary, and it calls secrets a convenience and not a security feature.

Some tasks don't fit this setup at all. When a task needs production access, real user accounts or the open web, don't run the agent in CI. Run it on an isolated machine with throwaway credentials, or don't automate the task.

Decide where each agent runs before you configure it. Exploration belongs on your laptop, in extension mode, where you can see the tabs. Staging work belongs in a CI job built like the one above. Production gets no agent at all.

Owning these controls has a running cost: bumping pins, keeping egress rules current and maintaining test accounts. Budget for that work, or keep the agent's scope small enough that a stale control can't reach anything that matters.

Frequently asked questions

Is Playwright MCP safe to run in CI?

For staging work, yes, in a CI job built with these controls, and production gets no agent at all. When a task needs production access, real user accounts or the open web, don't run the agent in CI. Run it on an isolated machine with throwaway credentials, or don't automate the task, as Where these controls stop explains.

Is allowed-origins a security boundary in Playwright MCP?

No. Playwright MCP's help text says --allowed-origins does not serve as a security boundary and does not affect redirects. The boundary is the runner's network, the test account and the job's credentials, as Where these controls stop covers.

Why use --isolated with Playwright MCP in CI?

Pass --isolated in CI so each session starts fresh. Persistent mode stores the profile in ms-playwright/mcp-{channel}-{workspace-hash} in the platform's cache directory, one profile per project, and keeps login state and cookies between sessions. On a runner that keeps its cache directory, the next job for the same project opens the same profile, as the persistent profile anti-pattern shows.

How do I pin the Playwright MCP version?

Pin an exact version of the scoped @playwright/mcp package as a dev dependency, install with npm ci, and launch the installed copy. The version has no caret, so package.json and the lockfile agree on one release, as the latest tag anti-pattern shows.

Should I upload Playwright traces and storageState as CI artifacts?

No. The cookies and headers in a state file could be used to impersonate you or your test account. Drop the upload step so traces and state never go up as CI artifacts, as Storage state and traces explains.

How do I pass secrets to Playwright MCP in CI?

Point PLAYWRIGHT_MCP_SECRETS_FILE at a dotenv file you write inside the job from one scoped CI secret that holds only the test account's credentials. Deploy tokens, cloud keys and reporting keys stay out of the file and out of the agent step's environment. Leave PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS unset in CI, as Secrets and file access covers.

Can Playwright MCP run headless in CI?

Yes: use the docs' headless setup, which adds --headless to the server's args.

Is the official Playwright Docker image safe for an MCP agent?

Not for browsing pages you don't control. The Docker docs say the image is meant for testing and development only and don't recommend it for visiting untrusted websites. By default it also runs the browsers as root, which disables the Chromium sandbox, as Docker and the Chromium sandbox covers.