# Shared: Shiplight MCP — browser tools & connection

All browser-driven subcommands (`verify`, `review`, parts of `create-yaml-tests`
and `fix`) use the Shiplight MCP server. This module is the single description of
the toolset and the connection check.

## Connection check

The Shiplight MCP browser tools (e.g. `new_session`, `inspect_page`, `act`) must
be available. If they are not, the server is not connected — tell the user to
install/enable it (see the repo README, whose "Bun" section has the Bun form) and
reconnect (`/mcp`), then stop. In a Bun project (`package-manager.md`) the server
command is `bunx --bun --package @shiplightai/mcp@latest shiplight-mcp`; the
scaffolded `.mcp.json` already has it for Claude Code.

## Core browser tools

- `new_session({ starting_url, storage_state_path?, browser_options? })` — open a
  browser session. `browser_options` fixes the session's `viewport`
  (`{ width, height }`), `is_mobile`, `has_touch`, `color_scheme`, `locale` and
  more for its whole life. Set `browser_options.record_evidence: true` when you
  intend to produce an HTML report. Multiple concurrent sessions are supported.
- `inspect_page()` — returns the DOM tree (with element indices) and a screenshot.
  **Always read the DOM file first** — it carries the element indices needed for
  `act` and costs far fewer tokens. Only view the screenshot when you need visual
  information (layout, colors, images).
- `act(...)` — perform deterministic user actions by element index: click, type,
  press keys, select, scroll, navigate, switch tabs, wait, upload a file, save a
  variable. The act tool's description lists every action the connected server
  accepts, and `shiplight://schemas/action-entity` has their parameters. `act`
  never calls a model, so it has no `verify` action, and it rejects any unlisted
  action with "Unsupported act action(s)". `upload_file` paths are relative to
  the project root (the folder the MCP server runs in) or absolute. Each action's
  result has a `step_index`, and a `screenshot_path` of the active tab after that
  action when one could be taken.
- `get_browser_console_logs()` / `get_browser_network_logs()` — fetch what the
  page logged and requested, in every tab, from `new_session`'s first page load
  on. Each entry's `tab` is the index the tab had when the entry was logged, as
  `inspect_page` lists tabs ("Tab N") and `switch_tab` takes it; closing a tab
  shifts the later ones down; a service worker's entries have no `tab`. The
  console log also has uncaught exceptions and unhandled rejections, as `error`
  entries whose text starts with `Uncaught`. The network log lists a request
  when it starts (`timestamp`), so `since_timestamp` splits requests by when
  they started: `status` is absent until its response arrives, and `failure` says
  why one failed. WebSocket handshakes are entries with `resourceType:
  "websocket"` that never get a `status`: one without `failure` connected or
  is still connecting. A connection that was refused outright appears only in
  the console log, as "WebSocket connection to '<url>' failed".
  - **Each call lists the latest 100 matching entries**, and `log_count` says
    how many matched. When it is higher than the entries listed, narrow the
    call: with `log_types` (e.g. `["error"]`) or `status_filter` (`"errors"`:
    4xx, 5xx and failed requests; `"success"`) fewer entries match, so earlier
    ones of that kind are listed. `since_timestamp` only leaves out older
    entries, so it can't reach back to the ones a call left out. On a busy
    flow, call them after each step with `since_timestamp` set to when the step
    started. An entry is completed in place, so one that had neither `status`
    nor `failure` then ends later under its own start time: read from that
    earlier `since_timestamp` again to see how it ended. A page load or step
    with more than 100 entries of the kind you need takes the full capture
    (below).
  - **Reading `failure`:** `csp` and `mixed-content` mean the page's own policy
    stopped the request, so no visitor sends it. `net::ERR_CONNECTION_REFUSED`
    and `net::ERR_NAME_NOT_RESOLVED` mean the host didn't answer (see below).
    Other reasons can come after the server got the request: `net::ERR_ABORTED`
    (often a beacon the page dropped as it unloaded), `net::ERR_BLOCKED_BY_ORB`,
    `net::ERR_BLOCKED_BY_RESPONSE.*`, and `net::ERR_FAILED` for a CORS failure
    (when the preflight was refused, only the preflight got there, with the URL
    but no body).
  - **`new_session`'s load is a first visit** unless you give it state: the
    session starts with no cookies or storage beyond what `storage_state_path`
    restores, or what a reused `browser_options.user_data_dir` profile kept from
    earlier sessions (leave both out to see a fresh visit). `reload_page`
    is not one: it runs with the cookies and storage the page has set, so
    whatever fires only on a first visit (before consent, before a tracker's
    cookie exists) is missing. Use it only to see what an open page loads
    again, such as after a consent choice.

  **Before you trust a log**, check two things. Either one means it is
  incomplete:
  - `log_count` is higher than the entries listed: narrow the call (above) or
    use the full capture (below).
  - A request failed with `net::ERR_NAME_NOT_RESOLVED` or
    `net::ERR_CONNECTION_REFUSED`. If it is the app's own host (localhost, its
    API), that is a real failure: a server that isn't running or a wrong URL. A
    third-party host is often blocked by this machine's network (a DNS ad
    blocker, a sandbox) where real visitors reach it, and whatever a blocked
    script would have loaded never happens here, so rerun on an open network
    before trusting an inventory or passing a check that something doesn't
    fire.
- `close_session()` — closes the session; returns `local_video_path` and
  `local_trace_path` (used for reporting).
- `save_storage_state(...)` / `storage_state_path` — capture and reuse auth; see
  `_shared/auth.md`.
- `generate_html_report(...)` — see `_shared/evidence-and-report.md`.

## Checking UI state

You judge whether the UI is right: `act` has no assertion that every server
offers. Re-run `inspect_page` after the action, read the DOM file (text,
elements, which controls exist), view its screenshot for visual detail, and read
the console and network logs, checked as "Before you trust a log" says (above).

## What a live session can't do

- **Run JavaScript in the page** (computed styles, `document.cookie`, storage,
  the Performance API, `page.route()` to fake failures). No `act` action
  evaluates code. Put the script in a YAML test as a `description:` + `js:`
  statement (`await page.evaluate(() => ...)`; see
  `create-yaml-tests/test-implementation-guide.md`) and run it with
  `npx shiplight test tests/<file>.test.yaml`
  (`bun run --bun shiplight test tests/<file>.test.yaml` in a Bun project). The
  test runs in its own browser, not in your session, so it navigates and logs
  in itself (see `_shared/auth.md`), and at the project's viewport: call
  `await page.setViewportSize({ width, height })` first when size matters.
- **Change the viewport or emulation mid-session.** Open a new session with the
  `browser_options` you need, one per breakpoint or device.
- **Turn JavaScript off.** In a YAML `js:` statement, open a context without it
  (`const ctx = await page.context().browser().newContext({ javaScriptEnabled: false })`),
  load the page in `await ctx.newPage()` and check what renders. The raw HTML
  (`curl -sL <url>`) is a quicker but partial check: content in it can still be
  hidden until a script runs.

## Full capture

When a page load or step has more than 100 entries of the kind you need, or a
check should run again as a test, record it in a YAML test (run as in "What a
live session can't do"): every request of every tab, failed ones included,
every console message and every uncaught error or rejection, with no 100-entry
limit (`tab.on('websocket', …)` adds WebSocket connections). The listeners go on
a context before the page loads, `testContext` keeps what they collect, and a
later `js:` statement asserts on it with `expect`:

```yaml
goal: Record everything the page does on a first visit
statements:
  - description: Load the page as a first visit and record everything it does
    js: |
      const ctx = await page.context().browser().newContext({ storageState: { cookies: [], origins: [] } });
      const seen = { requests: [], failed: [], console: [], errors: [] };
      ctx.on('request', (r) => seen.requests.push(`${r.resourceType()} ${r.url()}`));
      ctx.on('requestfailed', (r) => seen.failed.push(`${r.failure()?.errorText} ${r.url()}`));
      ctx.on('console', (m) => seen.console.push(`${m.type()}: ${m.text()}`));
      ctx.on('weberror', (e) => seen.errors.push(String(e.error())));
      testContext.set('seen', seen);
      const tab = await ctx.newPage();
      await tab.goto('https://app.example.com/');
      await tab.waitForTimeout(5000); // late scripts and beacons; the checks cover only this window
  - description: No tracker loads before consent
    js: |
      const { requests } = testContext.get('seen');
      console.log(requests.join('\n')); // the inventory, in the run's output
      expect(requests.filter((r) => r.includes('tracker.example'))).toEqual([]);
```

- The empty `storageState` makes it a first visit. Without it, a context the
  test opens starts from the project's `storageState` too (`_shared/auth.md`),
  which may hold a login, a consent choice or tracker cookies. For a page behind
  the login, use the test's own context: `const ctx = page.context();`.
- Later ACTION, `URL:` and `VERIFY:` statements don't reliably drive `tab`, so
  do the rest of the flow in the same `js:` statement; `seen` keeps recording.
  For a consent check, note where consent starts before the click
  (`testContext.set('beforeConsent', seen.requests.length)`), then click and
  `await tab.waitForTimeout(5000)` so the page can save the choice, then
  `await tab.reload()` and wait again. The check before consent reads
  `requests.slice(0, testContext.get('beforeConsent'))`, and what fires after
  the choice is the rest. Requests are listed when they start.
- Every entry in `requests` is a request the page made; `failed` says what
  became of it in this run, read as "Reading `failure`" above says.

## Resources

Before generating any YAML, read the references:

- `npx shiplight spec yaml` (`bun run --bun shiplight spec yaml` in a Bun
  project) — the YAML language spec.
- `npx shiplight spec actions` (`bun run --bun shiplight spec actions` in a Bun
  project) — the actions a statement's `action:` field can
  name, with their YAML parameters (element-targeted actions take `locator:` /
  `xpath:`, never `element`).
- `shiplight://schemas/action-entity` — MCP resource: the actions `act` can
  perform in a live session and the `locator` / `xpath` / `frame_path` payload
  they return, which you embed into statements.

Local `.test.yaml` files are written, validated, and run with `npx shiplight`
commands (`bun run --bun shiplight` in a Bun project; see `package-manager.md`).
