safari-background-mcp
by AlexZai007
README.md
<p align="center">
<img src="https://raw.githubusercontent.com/AlexZai007/safari-background-mcp/main/docs/media/banner.png" alt="safari-background-mcp — AI agents drive your real Safari in the background" width="100%">
</p>
<p align="center">
<a href="https://github.com/AlexZai007/safari-background-mcp/actions/workflows/test.yml"><img src="https://github.com/AlexZai007/safari-background-mcp/actions/workflows/test.yml/badge.svg" alt="tests"></a>
<img src="https://img.shields.io/badge/macOS-Safari-0A84FF?logo=safari&logoColor=white" alt="macOS Safari">
<a href="https://www.npmjs.com/package/safari-background-mcp"><img src="https://img.shields.io/npm/v/safari-background-mcp?color=CB3837&logo=npm" alt="npm"></a>
<img src="https://img.shields.io/badge/node-%E2%89%A520-339933?logo=node.js&logoColor=white" alt="Node 20+">
<img src="https://img.shields.io/badge/MCP-server-7C3AED" alt="MCP server">
<img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license">
</p>
<p align="center">
<a href="#see-it-work">See it work</a> ·
<a href="#install">Install</a> ·
<a href="#tools">Tools</a> ·
<a href="#how-it-works">How it works</a> ·
<a href="#limitations">Limitations</a>
</p>
An [MCP](https://modelcontextprotocol.io) server that lets AI agents (Claude Code, Claude Desktop, Cursor, …) drive **your real Safari** — with your logins, cookies and extensions — **entirely in the background**.
- 🫥 **Never steals focus, never switches your Space.** Agent tabs open as *unselected background tabs* in an existing Safari window — no window is created (creating one makes macOS jump to another desktop when you work in a full-screen app), and nothing you see changes. All actions are DOM events inside the page; Safari is never activated. A focus guard hands focus back if macOS ever brings Safari forward.
- 🔒 **Never touches your tabs** unless you explicitly address one: without an agent tab, actions refuse to run instead of falling back to your active tab. Pinned tabs (which Safari mirrors into every window) are protected from closing.
- ⚡ **Fast.** One persistent `osascript` bridge instead of a process per call: ~15 ms per Safari round-trip, 70–200 ms for a typical snapshot or read.
- 🪶 **Context-frugal.** 26 tools in ~5k tokens of definitions (~3.4k with `SAFARI_MCP_TOOLS=core`). Compact snapshots with stable refs, change reports after actions instead of full page dumps, text search inside pages, small cropped screenshots.
- 🧩 **No extension, no WebDriver, no Xcode.** Just Node and a Safari setting.
## See it work
An agent signs up on a web page. On the left — what happens inside the agent's background tab (real Safari screenshots taken by `safari_screenshot`). On the right — the exact tool calls and what the agent gets back. The whole time Safari stayed behind the terminal; a watchdog checks the frontmost app on every call.
<table>
<tr>
<td width="40%" valign="top"><img src="https://raw.githubusercontent.com/AlexZai007/safari-background-mcp/main/docs/media/safari-demo.gif" alt="Safari: the agent fills the form in a background tab and submits it"></td>
<td width="60%" valign="top"><img src="https://raw.githubusercontent.com/AlexZai007/safari-background-mcp/main/docs/media/terminal-demo.gif" alt="Terminal: the tool calls and their compact responses"></td>
</tr>
<tr>
<td align="center"><sub>inside the background tab</sub></td>
<td align="center"><sub>what the agent sends and sees · <code>node docs/demo/demo.mjs</code></sub></td>
</tr>
</table>
Seven calls, about 3.5 s of Safari work. Notice what the agent does **not** get: page dumps. After each action it gets a short diff — `~ [e5] radio "Starter Free" [ ]`, `+ ## You're on the list!` — so a long session stays cheap.
## How it compares
| | this server | WebDriver-based (safaridriver, Playwright WebKit) | Extension-based Safari MCPs | Chrome DevTools / Playwright MCP |
|---|---|---|---|---|
| Your real profile & logins | ✅ | ❌ separate automation session | ✅ | ❌ by default |
| Works without stealing focus | ✅ by design | — | partially (restores focus afterwards) | ❌ on macOS |
| Install | `npx` | built-in, but isolated | build/enable an extension | separate browser |
| Tool definitions | ~5k tokens | — | up to 90+ tools | ~14–19k tokens |
| Actions report what changed | ✅ diff | ❌ | snapshot diff on request | full snapshot |
## Requirements
- macOS with Safari, Node.js 20+
- Safari → Settings → Advanced → **Show features for web developers**, then **Develop → Allow JavaScript from Apple Events**
- On first use macOS asks to allow your terminal / Claude app to control **Safari** (Automation). Screenshots additionally need **Screen Recording**. `press_key` with `real: true` needs **Accessibility**.
## Install
Claude Code:
```bash
claude mcp add safari -- npx -y safari-background-mcp
```
Claude Desktop / Cursor / any MCP client (`mcpServers` config):
```json
{
"mcpServers": {
"safari": { "command": "npx", "args": ["-y", "safari-background-mcp"] }
}
}
```
From source:
```bash
git clone https://github.com/AlexZai007/safari-background-mcp.git
cd safari-background-mcp && npm install
claude mcp add safari -- node "$PWD/server.mjs"
```
Then ask your agent something like *“open my GitHub notifications in Safari and summarize them”* — it will use your existing login, in a background tab.
## Tools
| Tool | What it does |
|---|---|
| `safari_new_tab` | Open a URL in an unselected background tab and wait for load |
| `safari_navigate` | Go to a URL, or back / forward / reload; waits for load |
| `safari_list_tabs` | Windows and tabs, marking the agent window and the current tab |
| `safari_switch_tab` | Target another tab (optionally show/activate it) |
| `safari_close_tab` | Close a tab or the whole agent window; pinned tabs are protected |
| `safari_snapshot` | Interactive elements with stable refs (`[e12]`), headings, viewport markers; `diff`, `within`, `text`, paging |
| `safari_find` | Find elements by text / label / role / selector → refs (cheaper than a snapshot) |
| `safari_get_text` | Page content as compact markdown or text; `query` returns only matching snippets; `main` skips nav/footer |
| `safari_get_html` | Cleaned HTML (no scripts/styles/svg) of the page or an element |
| `safari_click` | Click (also double/right/modifiers); waits for navigation; reports new tabs and DOM changes |
| `safari_hover` | Hover (JS events) to open menus/tooltips |
| `safari_type` | Type into inputs/textareas/contenteditable (React-safe); `submit`, per-key events |
| `safari_fill` | Fill many fields (text, selects, checkboxes) in one call |
| `safari_select` | Native or custom (ARIA) dropdowns, checkboxes, radios, switches |
| `safari_press_key` | Keys with emulated default actions (Enter submits, Tab moves focus, …) |
| `safari_scroll` | Scroll the page or the SPA's inner scroll container, or to an element |
| `safari_drag` | Drag and drop between elements |
| `safari_upload` | Attach local files to a file input / drop zone without the system dialog |
| `safari_evaluate` | Run JS (expression, function or body with `await`) and get JSON back |
| `safari_wait_for` | Wait for text / selector / URL / network idle (or disappearance) |
| `safari_screenshot` | Viewport or element screenshot, captured without bringing Safari forward |
| `safari_console` | New console messages, JS errors, failed resources, CSP violations |
| `safari_network` | fetch/XHR log with status and timing; optional response bodies |
| `safari_dialog` | `alert/confirm/prompt` are auto-answered (never block); configure answers, see history |
| `safari_storage` | localStorage / sessionStorage / cookies |
| `safari_batch` | Several tool calls in one round-trip |
Elements can be addressed by `ref` (from snapshot/find), CSS `selector` (pierces open shadow DOM and same-origin iframes), visible `text` (+ `role`), or form `label`; `index` picks the N-th match. Tabs are addressed by `window_id` + `tab_index`; when omitted, the tab used last is targeted.
<details>
<summary><b>Example: what an agent sees</b> (plain text)</summary>
```text
> safari_snapshot
Form fixture — http://127.0.0.1:58077/form.html
scroll 0/0px
# Sign up
[e1] textbox "Full name"
[e2] textbox "Email address"
[e3] password "Password"
[e4] textbox "Bio"
[e5] combobox "Country" ="Choose…" {Choose…|United States|Canada|Germany}
[e6] checkbox "I accept the terms" [ ]
[e7] radio "Free" [x]
[e8] radio "Pro" [ ]
[e9] editable "Notes"
[e10] button "Create account"
> safari_fill {"fields":[{"label":"Full name","value":"Ada"},{"label":"Country","value":"Canada"},{"ref":"e6","value":true}]}
✓ textbox "Full name" ="Ada"
✓ combobox "Country" ="Canada"
✓ checkbox "I accept the terms" [x]
no changes in interactive elements
> safari_click {"text":"Add item"} (on another page)
clicked button "Add item"
changes since last snapshot:
+ [e31] button "Item 1"
```
</details>
## Configuration
| Env var | Default | Meaning |
|---|---|---|
| `SAFARI_MCP_TOOLS` | `all` | `core` for a smaller tool set, or a comma list like `snapshot,click,type` |
| `SAFARI_MCP_AGENT_WINDOW` | `0` | `1` keeps agent tabs in a separate Safari window (tidier, but creating that window can switch you to another Space) |
| `SAFARI_MCP_STATE` | `$TMPDIR/safari-background-mcp.json` | Where the agent window id is remembered, so restarts and parallel sessions reuse one window |
## How it works
<p align="center"><img src="https://raw.githubusercontent.com/AlexZai007/safari-background-mcp/main/docs/media/architecture.png" alt="MCP client → stdio → Node server → NDJSON → JXA bridge → Apple Events → Safari" width="100%"></p>
- `src/jxa/bridge.js` — JXA side: window/tab addressing, background tabs, optional agent window, focus guard; newline-delimited JSON over stdin/stdout.
- `src/bridge.mjs` — Node side: request queue, per-call timeouts, automatic restart of a hung bridge.
- `src/page/runtime.js` — injected once per document: element refs, snapshot/diff, actions, readers, console/network/dialog capture.
- `src/safari.mjs` — tab targeting (agent tabs vs. user tabs), navigation and load detection, settle-after-action logic.
- `src/tools/*` — tool definitions; `src/server.mjs` — registry, profiles, `safari_batch`.
## Limitations
These come from automating Safari without an extension or WebDriver:
- Events are synthetic (`isTrusted = false`). Sites that require trusted input or CSS `:hover` may not react; `press_key {real: true}` sends real keystrokes but briefly brings Safari forward.
- Popups opened from synthetic clicks are blocked by Safari; the server opens `target=_blank` links and blocked `window.open` URLs in a background tab itself.
- Closed shadow roots and cross-origin iframes are not reachable. HttpOnly cookies are invisible.
- Console/network capture starts when the server first touches a page; earlier messages are missed (`safari_network {resources: true}` lists earlier resources).
- Screenshots need the window to be on the current Space (macOS does not render windows of inactive Spaces). A background tab is shown in its window for ~0.3 s during the capture and then switched back.
- Background tabs are throttled by Safari (timers, `requestAnimationFrame`), so some animations run slower there.
- Safari internal pages (favorites, settings) and PDFs cannot run scripts.
## Development
```bash
npm test # unit tests (no Safari needed; bridge tests need macOS)
npm run test:e2e # end-to-end tests in your real Safari, in a background window
STRICT_FOCUS=1 npm run test:e2e # also fail if Safari became frontmost during a call (run hands-off)
node test/client.mjs new_tab '{"url":"https://example.com"}' snapshot '{}' # poke the server manually
```
The README media is reproducible: `node docs/demo/demo.mjs --frames <dir>` saves the Safari frames and `docs/demo/make-safari-gif.sh <dir> docs/media/safari-demo.gif` turns them into the GIF, `vhs docs/demo/terminal.tape` records the terminal (needs [vhs](https://github.com/charmbracelet/vhs)); the banner and diagram are SVG sources in `docs/media/src`.
The e2e suite runs in a separate agent window (plus one test of the default background-tab mode), serves local fixture pages (forms, dialogs, shadow DOM, iframes, drag-and-drop, uploads, SPA routing, slow pages) and runs every tool against them while a watchdog records which app is frontmost.
## License
MIT
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessOutdated data