# ws-devtools

> Remote browser devtools over WebSocket — arm a tab with the MV3 extension and drive it from your terminal, an MCP agent, or a Node script.

`ws-devtools` is a two-part bridge:

- a **Node server** (CLI + file API + MCP server) that runs in your terminal, and
- an **MV3 browser extension** that injects a framework-agnostic client into the tab you arm, relaying commands through its service worker.

Once connected, your terminal can read the DOM, run JS, click/type/drag/upload, press keyboard chords, scroll, auto-answer native dialogs, seed cookies & storage, emulate geolocation, capture errors, log `fetch`/XHR/WebSocket calls, screenshot the page (or stream **live video** of it), and batch many commands into one round-trip — on a live page, with no framework dependency. For visual agents it can overlay numbered `@ref` badges (**Set-of-Mark**) and **fuse an action with a settled frame** so one call acts and hands back the result. Because the client rides the extension's service worker, the CDP-backed commands reach above the page sandbox (HttpOnly cookies, trusted input, full-page capture, live screencast), with a page-JS fallback everywhere CDP isn't available.

It started life as the debug bridge for a single web app and was extracted to stand on its own. The framework bits (React, Vue, Pinia, react-query, TanStack Router) now live behind an optional adapter seam, so the core runs anywhere.

> **📖 How to use it lives in one place:**
> **[docs/using-from-another-project.md](docs/using-from-another-project.md)** — every
> transport (MCP / file API / CLI / driver), arming a tab, the driving rules, visual
> driving, the full command reference, and troubleshooting. This README covers what it
> is, how to install it, and how it's built.

---

## ⚠️ Security — read this first

This tool gives a terminal **full control of the tab you arm**: it can run arbitrary JavaScript (`eval`), read cookies and `localStorage`, click and type, and exfiltrate anything the page can see.

- **Only arm tabs you own and trust**, for local development and debugging.
- **Never** arm a banking tab, a production app, or any page handling someone else's data.
- The server has **no authentication** — anything that can reach `ws://127.0.0.1:9999` can drive a connected page. Keep it on localhost.

There is intentionally no sandbox: remote `eval` is the whole point. Treat it like an open devtools session, because that's effectively what it is.

---

## Install

Published to npm — **no clone required**. Requires Node 20+.

```bash
# Zero-install: run the MCP server (or the CLI) straight from npm.
npx -y -p ws-devtools ws-devtools-mcp   # MCP server (for agents)
npx -y ws-devtools          # interactive CLI

# Or install once, globally:
npm i -g ws-devtools        # exposes `ws-devtools` + `ws-devtools-mcp` on PATH
```

**The extension ships inside the npm package** — no clone needed for it either:

```bash
npx -y ws-devtools extension          # → unpacks to ~/.ws-devtools/extension, prints the path
npx -y ws-devtools extension --out .  # …or anywhere you like
```

Then Chrome/Edge → `chrome://extensions` → enable **Developer mode** → **Load unpacked**
→ pick that folder. Then click the toolbar button and pick your project to **arm** the
current tab. Re-run the
command after upgrading to refresh the folder.

Stuck? `npx -y ws-devtools doctor` reports the resolved version, where the extension
landed, whether anything answers on the bridge port, and whether you're in a container
(where the **host** must forward that port) — then names the next step.

Building from a clone is only needed to develop ws-devtools itself:

```bash
npm install
npm run build      # → dist/mcp.mjs, dist/server.mjs, dist/driver.mjs, dist/adapters.mjs, dist/extension/
```

## Usage

All usage — registering the MCP server for an agent, the file API, the interactive
CLI, the Node driver, arming a tab, the driving rules, visual driving, the full
command reference, and troubleshooting — lives in the single guide:

**→ [docs/using-from-another-project.md](docs/using-from-another-project.md)**

The 30-second version:

```bash
# Claude Code (recommended): the plugin brings the MCP server + the driving runbook skill
claude plugin marketplace add rationalthinker1/ws-devtools
claude plugin install ws-devtools@ws-devtools
# Any other MCP client: the server self-starts the bridge (first free port in 9999–10030)
claude mcp add --scope user ws-devtools -- npx -y -p ws-devtools ws-devtools-mcp
# Or a plain terminal session:
npx -y ws-devtools        # then arm a tab and type at the dbg> prompt
```

Then **arm a tab** with the MV3 extension (toolbar button) and drive it. The same
command set works across every transport — see the guide for the command reference.

## For AI agents

If you are an agent reading this to get unstuck, follow this in order. Do not skip to
driving — most failures are setup, and each step below is only reachable once the one
above it holds.

1. **`doctor` first when nothing works.** It is answered inside the MCP server process,
   so it replies when `status` cannot: no bridge, no browser, no armed tab. It reports
   the version, the extension path, the bridge probe, and container state, and it names
   the next action. Use it before forming any theory.
2. **`status` next.** `doctor` covers the local install; `status` covers what the bridge
   sees. `browserAttached: false` means the tab is not armed. An error saying "This
   bridge (…) isn't bound to a tab" means several agents' bridges are live and the tab
   is bound to another one — the user picks this project from the extension icon.
   `proxied: true` means every bridge port was taken and yours forwards through the 9999
   owner — that is healthy, drive normally, do not kill anything.
3. **You cannot arm a tab.** Arming is a human clicking the extension's toolbar button on
   the page they want driven. There is no API, flag or eval for it. When `status` says
   `browserAttached: false`, stop and ask the user — retrying tools will not fix it.
4. **`url` before believing any page read.** Confirm which page you are on; a stale
   assumption about the current page invalidates everything after it.
5. **Prefer text over pixels.** `read`, `snapshot --lean`, `dom_text`, `role` — a
   screenshot costs 20–50× the tokens. Reach for `screencast_frame` when you need to see
   layout, `screenshot` only to confirm one.
6. **Re-`snapshot` before acting on an `@ref`.** Refs go stale as the page mutates.
7. **Read argument errors literally.** Tool args are validated against each tool's
   schema: a missing required arg or an unknown one (`expression` where `eval` wants
   `code`) returns an error naming what's accepted, so fix the name and retry. Older
   servers accepted the call and returned `"undefined"`. Against one of those, a
   suspiciously empty result is an argument-name typo until proven otherwise.
8. **A form you can't find may be inside an iframe.** `snapshot` and `eval` see only the
   top document. Pass `frame` (an `<iframe>` CSS selector, e.g.
   `iframe[src*="withpersona"]`) to `click`/`type`/`press`/`hover`/`drag`/`eval` to act
   inside it, cross-origin included.
9. **`eval` takes an expression, not statements.** Wrap statements in an IIFE:
   `(() => { foo(); return 'done'; })()`.
10. **Someone else's session is on the other end.** Reads and navigation are fine. Leave
    creates, deletes, submits and confirmations to the user unless they asked for that
    specific action.

In a devcontainer, the browser runs on the **host** and the extension scans ports
9999–10030, so the host must forward the bridge's port (usually 9999) to the container.
VS Code's auto-forward works even when it remaps to another port in that range. A probe from inside the container
cannot see the host's forward — `doctor` says so rather than letting you chase it.

## Extending it (adapters)

Framework / state inspectors are extra commands **bundled in the extension** and
registered automatically when you arm a tab: **React**, **React Query**, **TanStack
Router**, **TanStack Form**, **TanStack Table**, **Sonner**, **Auth** (any provider),
**Vue**, **Pinia**. `react`/`vue` need nothing (they walk the fiber / component
instance from the matched DOM node); the state inspectors read a dependency your app
exposes on a window global (dev only):

```ts
// in your app bootstrap (dev only) — the extension's adapters pick these up:
window.__WS_DEVTOOLS_QUERY_CLIENT__ = queryClient; // → `react-query [key]`
window.__WS_DEVTOOLS_ROUTER__ = router; //             → `tanstack-router`
window.__WS_DEVTOOLS_PINIA__ = pinia; //               → `pinia [store]`
window.__WS_DEVTOOLS_AUTH__ = authSnapshot; //         → `auth`
```

**Custom adapters** — add your own command by publishing an `Adapter`
(`{ name, commands }`) on `window.__WS_DEVTOOLS_ADAPTERS__` **before you arm the
tab**; the extension merges it into the command map. The `ws-devtools/adapters`
entry ships the types + helpers for authoring one (it's types + pure helpers — no
socket, not self-inject):

```ts
import type { Adapter } from 'ws-devtools/adapters';

const myAdapter: Adapter = {
  name: 'mything',
  commands: { mything: (parsed, respond) => respond({ data: { hello: parsed.selector } }) },
};
window.__WS_DEVTOOLS_ADAPTERS__ = [myAdapter]; // handlers reply { data } → JSON output
```

## Architecture

```
src/
  protocol.ts          shared wire format ({__cmd}/{__resp}/{__ack}, encode/decode/guards)
  server/
    commands.ts        pure CLI-line → action routing (unit-tested in isolation)
    index.ts           ws server + CLI + file API + startServer() programmatic API
    instance-lock.ts   per-bridge lockfile (${tmpdir}/ws-devtools-<port>.json) so the
                       driver discovers the file-API dir cross-platform (no /proc scan)
    mcp.ts             MCP stdio server — agents call commands as native tools
  client/              in-page client sources, bundled ONLY into the extension:
    core.ts            framework-agnostic command handlers (DOM/eval/net/snapshot/...)
    connect.ts         transport wiring, instrumentation, pure dispatcher
    adapters/          inspectors + authoring helpers → ws-devtools/adapters (react,
                       react-query, tanstack-router/form/table, sonner, auth, vue,
                       pinia; Adapter interface + mergeAdapters + readCustomAdapters)
  driver/              high-level Node file-API client → ws-devtools/driver
  extension/           MV3 extension: service worker + content script + MAIN-world client
                       (the only path the client reaches the page). The SW also serves
                       CDP commands (cookies-all/clear, cdp-click, screenshot-full,
                       geolocation, viewport-set, screencast-start/stop) via
                       chrome.debugger, with page fallback. Screencast frames are
                       fanned out as MJPEG on the screencast host (/live, /viewer)
tests/
  unit/                vitest — protocol, server routing, client core (happy-dom)
  e2e/                 playwright — fixtures for a future extension-loaded harness
```

## Development

```bash
npm run test:unit      # fast unit layer (no browser)
npm run test:watch     # red-green loop
npm run build          # bundle everything to dist/
npm run test:e2e       # real-browser E2E (runs against the build)
npm test               # unit → build → e2e
npm run typecheck      # tsc --noEmit
npm run lint           # eslint (lint:fix to autofix)
npm run format         # prettier --write (format:check to verify)
npm run check          # typecheck + lint + format:check
```

See [CLAUDE.md](./CLAUDE.md) for the internals — the test protocol, how to add a command, and the CDP/extension architecture.

## License

[MIT](./LICENSE)
