Skip to main content
Glama
playwright-grid-mcp

playwright-grid-mcp

by Nishan277
README.md
# playwright-grid-mcp

A general-purpose **Spatial Web & Document Viewer MCP Server** built in strict TypeScript on top of Playwright and the Model Context Protocol (`@modelcontextprotocol/sdk`).

Designed for multimodal AI agents that need to read, ground, and interact with **canvas applications, SVG/PDF document viewers, and authenticated SPAs** where traditional DOM-only scrapers break down.

---

## Why This Exists

Standard browser automation tools assume every interactive target is a semantic `<input>` or `<button>` in the light DOM. Real-world web applications frequently break that assumption:

- **Canvas & SVG Document Viewers:** PDF viewers, whiteboards, CAD/diagram editors, and interactive worksheets render content into `<canvas>`, inline `<svg>`, or embedded `<object type="image/svg+xml">` layers with zero semantic form fields.
- **Pixel-Drift & Vision Hallucination:** Asking a vision model to guess raw pixel coordinates on a `1920x1080` screenshot leads to misclicks, while sending uncompressed full-resolution PNGs burns thousands of tokens per turn.
- **Cold-Start Overhead & Auth Friction:** Relaunching Chromium and re-authenticating behind SSO/MFA on every tool call slows multi-step workflows by 5x–10x.

`playwright-grid-mcp` solves all three with a **persistent Playwright session**, **DOM + SVG text extraction**, **token-efficient JPEG screenshots overlaid with a 10%-interval spatial coordinate grid**, and **batch coordinate interactions with `Range`-based glyph centering**.

---

## Architecture

```text
MCP Client (LLM / Agent)
  │  stdio (JSON-RPC 2.0 — logs isolated to stderr)
  ▼
src/index.ts            Strict Zod schemas + MCP tool registration
  │
  ▼
src/engine.ts           SpatialBrowserEngine
  ├─ DOM + SVG Extractor     Scrapes light DOM, inline <svg>, and same-origin <object *.svg> frames
  ├─ Form Inspector          Resolves unique CSS selectors, ARIA labels & 0–100% bounding boxes
  ├─ Canvas Grid Renderer    Downscales to ≤1100px JPEG (q=75) + draws 10% X/Y (0–100) grid & pills
  └─ Spatial Actor           Batch click/double-click/type + Range-based glyph centering
  │
  ▼
src/browser.ts          BrowserManager
  └─ Mutex-serialized persistent Playwright Chromium context + reusable active Page (./.browser-session)
```

### Key Engineering Choices
- **Persistent Live Browser Context:** Keeps one Playwright `BrowserContext` and active `Page` alive across tool calls (supporting seamless headless ↔ headed transitions without tearing down tabs or losing session cookies).
- **Zero-Dependency Offscreen `<canvas>` Grid Overlay:** Renders crisp red vertical (`X: 0–100`) and blue horizontal (`Y: 0–100`) 10% major lines, subtle 5% minor dashed guides, and high-contrast axis pills inside Chromium's native `<canvas>` encoder—compressing screenshots to `image/jpeg` (`quality: 75`, `maxWidth: 1100px`) for ~5x–8x smaller payloads.
- **Range-Based Glyph Centering:** On positioned overlay text boxes (e.g., PDF/SVG markup tools), CSS `min-width` and padding often skew left-aligned short text when centering by container width. Measuring the rendered glyph bounds via `document.createRange().selectNodeContents(...)` centers the actual ink directly on `(x_percent, y_percent)`.
- **Strict TypeScript:** Compiled with `strict`, `noImplicitAny`, `noUncheckedIndexedAccess`, `noImplicitOverride`, and zero `any` types across the entire codebase.

---

## MCP Tools

| Tool | Purpose |
| :--- | :--- |
| **`browser_login`** | Opens a visible Chromium window to any `url` so a human can complete SSO/MFA and persist cookies/storage into `./.browser-session`. |
| **`read_page_grid`** | Navigates to a `url` (or jumps via `anchor` in the active tab), extracts visible DOM + SVG text, inspects interactive form elements with relative bounding boxes, and returns a compressed JPEG with a 10%-interval coordinate grid (`X: 0–100`, `Y: 0–100`). |
| **`fill_form_fields`** | Fills standard HTML inputs, selects, checkboxes, radios, and `contenteditable` fields across frames by CSS selector or accessible label, dispatching `input`/`change`/`blur` events. |
| **`click_or_type_at_coordinates`** | Executes batch `click`, `double_click`, or `type` actions at `(x_percent, y_percent)` grid coordinates relative to the viewport or a `container_selector`, with optional `align: "center"` glyph centering. |

---

## Quick Start

### 1. Install & Build

```bash
npm install
npx playwright install chromium
npm run typecheck
npm run build
```

### 2. Configure in Your MCP Client

Add the server to your MCP client configuration (e.g., Claude Desktop, Cursor, or Antigravity CLI):

```json
{
  "mcpServers": {
    "playwright-grid": {
      "command": "node",
      "args": ["/absolute/path/to/playwright-grid-mcp/dist/index.js"],
      "env": {
        "PLAYWRIGHT_GRID_SESSION_DIR": "/absolute/path/to/playwright-grid-mcp/.browser-session"
      }
    }
  }
}
```

### 3. Environment Variables (Optional)

| Variable | Default | Description |
| :--- | :--- | :--- |
| `PLAYWRIGHT_GRID_SESSION_DIR` | `./.browser-session` | Directory for persistent Chromium cookies and storage. |
| `PLAYWRIGHT_GRID_CHROMIUM_PATH` | Playwright bundled | Custom Chromium/Chrome executable path. |
| `PLAYWRIGHT_GRID_LOCALE` | `en-US` | Browser locale passed to Playwright. |
| `PLAYWRIGHT_GRID_TIMEZONE` | System default | Optional IANA timezone ID (e.g., `Europe/Vienna`, `America/New_York`). |

---

## Typical Spatial Grounding Workflow

1. **Authenticate (if needed):** Call `browser_login` with `{ "url": "https://app.example.com/login", "success_url_pattern": "/workspace" }`.
2. **Ground visually:** Call `read_page_grid` with `{ "url": "https://app.example.com/workspace/doc/1", "container_selector": "#document-canvas", "show_grid": true }`.
3. **Read coordinates:** Inspect the returned JPEG's red `X (0–100)` and blue `Y (0–100)` grid lines to locate exact target boxes or buttons.
4. **Act in a single batch:** Call `click_or_type_at_coordinates` with `{ "container_selector": "#document-canvas", "items": [{ "x_percent": 38.5, "y_percent": 22.0, "text": "A", "align": "center" }], "visible": true }` and verify placement in the returned JPEG.

---

## Security Notes

- Session profiles (`.browser-session/`) and `.env*` files are excluded via `.gitignore`. Never commit browser session directories.
- All logging is routed strictly to `stderr` so the MCP `stdio` JSON-RPC channel stays clean.

## License

MIT — see [LICENSE](./LICENSE).