# mcp-playwright — AI agent instructions (Docker deployment)

> Paste this section into the consuming project's `AGENTS.md` / `CLAUDE.md` / system
> prompt when the agent will use mcp-playwright running **in Docker** (local container
> or remote pod). It explains the bridged architecture and session model that agents
> otherwise get wrong. Maintained by hand in `mcp-playwright/AGENT-INIT.md`
> (the generated capability card is `docs/agents/mcp-playwright.md`). For the full
> security/networking analysis of the reverse tunnel referenced below, see the
> repo-level case study [`docs/reverse-tunnel/`](../docs/reverse-tunnel/reverse-tunnel-localhost-case-study.html)
> — it proves the tunnel reaches exactly one pinned host:port on the developer machine.

---

## Playwright browser automation (mcp-playwright)

You are connected to a **Playwright MCP server running inside a Docker container**.
It exposes Microsoft's `@playwright/mcp` browser tools (`browser_navigate`,
`browser_click`, `browser_type`, `browser_snapshot`, `browser_take_screenshot`, …)
plus two extra tools added by the wrapper: `list_artifacts` and `download_artifact`.

### If `browser_navigate` isn't in your tool list

The browser tools live on this MCP server, which may not be attached to the
session you're in. If you can't see `browser_navigate`, don't conclude the server
is down — **delegate the browser work to a sub-agent that has the server
attached** (a general-purpose agent), and have it report back the result or the
screenshot. Check `tools/list` before assuming either way.

### Over stdio instead? (your client launched `docker run -i … -e MCP_TRANSPORT=stdio`)

Then the container is on the user's own machine, started for this session only.
With `--network host` (Linux) the browser shares the user's `localhost` —
navigate to `http://localhost:<port>` directly. The user's working directory is
mounted at `/work`: `browser_file_upload` takes `/work/...` paths, and saved files
land in `./.playwright-mcp` on their disk. There is no `/rpc`, tunnel or
`share_artifact` over stdio. The rest of this section describes the HTTP setup.

### Mental model — read this before using any tool

```
you (agent) ──HTTP /mcp──▶ facade (container :7184) ──stdio──▶ headless Chromium
                                                               (same container)
```

The browser is **not on your machine**. It runs inside the container, next to the
facade you're talking to. Everything that confuses agents follows from this:

1. **The browser's `localhost` is the container's loopback, not yours.**
   `browser_navigate("http://localhost:5173")` targets the *container's* port 5173
   and gets connection-refused. See "Reaching a dev server" below for the correct URL.
2. **Files the browser saves live inside the container**, in a per-session artifact
   directory. You cannot `Read` them from your filesystem — retrieve them over MCP
   with `list_artifacts()` / `download_artifact(name)`.
3. **Your MCP session owns a dedicated browser.** Nothing you do is visible to other
   sessions, and you cannot see their pages or files.

### Sessions — how state and isolation work

- On `initialize` the server assigns you an `mcp-session-id` (HTTP header; MCP SDK
  clients handle it automatically). That id maps to **your own Chromium child and
  your own artifact directory**. Concurrent agents never share browser state or files.
- **Transient disconnects do not kill your browser.** Reconnecting with the same
  `mcp-session-id` within the idle TTL (default **10 min**, `PW_SESSION_TTL_MS`)
  reattaches to the same live pages and artifacts. Don't restart your task after a
  dropped connection — reconnect and carry on.
- After the TTL of inactivity (or an explicit `DELETE /mcp`), the session's browser
  **and its artifacts are reaped**. Download any file you need *before* ending a
  session or going idle.
- Concurrent sessions are capped (default **8**, `PW_MAX_SESSIONS`). If `initialize`
  returns **503**, the server is full — don't retry in a tight loop; another
  session must end or idle out first. Free your own browser when done via a clean
  session close (`DELETE /mcp`) rather than just abandoning it.
- **Session hygiene matters more than it looks.** Your session holds an entire
  Chromium (~500 MiB for a real page) for the full idle TTL after you walk away, and
  on a memory-limited deployment that is enough to OOM the pod. Two rules follow:
  close the session when you're done, and **reconnect with your existing
  `mcp-session-id` instead of re-initializing** — every stray `initialize` spawns
  another browser while the abandoned one lingers.
- One session = one browser, but multiple **tabs** are fine (`browser_tabs`).
  Don't open a second MCP session to get a second page.

### Reaching a dev server (the #1 mistake)

Never navigate to `http://localhost:<port>` expecting *your* machine. Pick by
where the container runs relative to the dev server:

| Container runs… | Dev server prep | Navigate to |
|---|---|---|
| Same host, `--network host` (Linux) | none | `http://localhost:<port>` works |
| Same host, port-published (`-p 127.0.0.1:7184:7184`) | bind dev server to `0.0.0.0` (`vite --host`, `ng serve --host 0.0.0.0`, …) | `http://host.docker.internal:<port>` (Docker Desktop / with `--add-host=host.docker.internal:host-gateway`) or `http://172.17.0.1:<port>` (Linux bridge gateway) |
| Remote pod / another machine (k8s) | run `tools/tunnel-client.mjs` on the dev machine (reverse tunnel, control port 17184) | the printed `http://127.0.0.1:20XXX/` URL — that loopback address is *the pod's*, where the tunnel lands |

**Tunnel URLs outlive your MCP session.** Tunnels are keyed by the developer's
token, not by `mcp-session-id` — the forward port is derived from the token, so a
tunnel URL you already know stays valid across MCP session drops, re-initializations,
and even pod restarts. Don't discard it after a reconnect. If connections to it are
refused, the helper on the dev machine is detached — restart `tunnel-client.mjs`
(same token reattaches to the same port).

#### Starting the tunnel client — run it as a background sub-agent

`tools/tunnel-client.mjs` is a **long-running foreground process**. It prints its
status and then stays attached, auto-reconnecting for as long as the tunnel is
needed. Running it inline blocks your session forever — the call never returns.

Do this instead:

1. **Ask the user once** for permission to install/start the tunnel client. Ask only
   that — do not follow up with further confirmation prompts about ports, tokens, or
   restarts; pick sane defaults (`openssl rand -hex 16` for the token, the dev
   server's port for `--target`) and proceed.
2. **Dispatch it to a sub-agent that runs it in the background**, silently — not in
   the main session. The command is:
   ```sh
   node tools/tunnel-client.mjs --server <gateway-host>:17184 \
     --token "$(openssl rand -hex 16)" --target <your-dev-port>
   ```
3. The sub-agent **waits for the readiness line** and captures the URL from it:
   ```
   [tunnel] READY — the pod-side browser can now reach … http://127.0.0.1:20XXX/
   ```
   (`RE-ATTACHED` instead of `READY` means it reconnected to an existing tunnel —
   equally good.)
4. The sub-agent then **reports back to the main session** with that
   `http://127.0.0.1:20XXX/` URL, and nothing else. Navigate to it and carry on.

**There is no TLS on the control port, and no `TUNNEL_TLS` setting.** The protocol
is newline-delimited JSON straight over TCP. If a connection there fails, the
helper now names the cause itself — an HTTP response means an HTTP proxy or
ingress is in front of a port that must be raw TCP, and a TLS handshake means
you're pointed at an HTTPS listener rather than the gateway. Read that message
rather than inventing a transport setting; setting `TUNNEL_TLS` does nothing.

Constraints worth knowing before you start it: the token must be **≥16 characters**
(it is a bearer capability for the exposed port, so generate it randomly, never reuse
a guessable string), the target must be **loopback** unless `--allow-remote-target`
is passed explicitly, and the tunnel reaches **exactly one host:port** — you cannot
ask it for a second service later without starting another tunnel.

If a navigation is refused, diagnose topology first (is the target reachable *from
the container*?) before assuming the app is down. `curl http://127.0.0.1:7184/health`
shows server config (sessions, blocked origins, timeouts) if you have shell access.

### Screenshots and files

- **`browser_take_screenshot` returns the PNG inline either way** — with or without
  `filename`. You never need a second call just to see the image. Passing
  `filename` *additionally* saves it server-side; omitting it is simply inline-only.
- Page **downloads** and traces are a different case: those are saved in the
  container and are not returned automatically. List them with `list_artifacts()`
  and fetch bytes with `download_artifact(name)` (basename only; size-capped,
  default 32 MB). Essential when the server is remote — there is no shared disk.
- For *reading* a page, prefer `browser_snapshot` (accessibility tree, cheap text)
  over screenshots; screenshot only when pixels matter.

### When a navigation hangs or times out

If the page bounces to an SSO/identity host (Keycloak etc.) the *container* cannot
reach, the navigation stalls until the navigation timeout — that's an unreachable
IdP, not a server bug. Options, in order of preference:

1. Disable the app's dev auth gate for the run (env flag in the app under test),
   screenshot, revert.
2. Have the operator set `PW_BLOCKED_ORIGINS` (glob list, instant abort) and/or
   `PW_TIMEOUT_NAVIGATION` (catch-all bound, ms) on the server.

Blocking only stops the hang; it does not log you in.

### Quick rules

- ✅ Reconnect with the same session id after a drop — your browser is still there.
- ✅ Download needed artifacts before finishing; they die with the session.
- ✅ Use inline screenshots unless you need a saved file.
- ❌ Don't navigate to `localhost` for a host-side dev server from a container.
- ❌ Don't read artifact files from your local filesystem — they're in the container.
- ❌ Don't open extra MCP sessions for extra pages — use tabs; sessions are capped.
- ❌ Writing your own Playwright script inside the container? Don't run `npx playwright
  install` when it says `chromium_headless_shell-… doesn't exist`. Launch with
  `chromium.launch({ channel: "chromium" })` instead. The image has the full Chromium only.
