@mirsella/browser-mcp 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "browser-mcp",
3
+ "plugins": [
4
+ {
5
+ "name": "browser",
6
+ "source": {
7
+ "source": "local",
8
+ "path": "."
9
+ },
10
+ "policy": {
11
+ "installation": "AVAILABLE",
12
+ "authentication": "ON_INSTALL"
13
+ },
14
+ "category": "Developer Tools"
15
+ }
16
+ ]
17
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "browser",
3
+ "version": "2.0.0",
4
+ "description": "Shared Chromium profile with isolated conversation tabs for Codex and OpenCode.",
5
+ "author": {
6
+ "name": "mirsella"
7
+ },
8
+ "repository": "https://github.com/mirsella/browser-mcp",
9
+ "license": "MIT",
10
+ "skills": "./skills/",
11
+ "hooks": "./hooks/hooks.json"
12
+ }
package/.mcp.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "mcpServers": {
3
+ "browser": {
4
+ "command": "./vendor/browser-mcp",
5
+ "cwd": ".",
6
+ "env_vars": [
7
+ "DBUS_SESSION_BUS_ADDRESS",
8
+ "DESKTOP_SESSION",
9
+ "DISPLAY",
10
+ "GDK_BACKEND",
11
+ "OZONE_PLATFORM",
12
+ "WAYLAND_DISPLAY",
13
+ "XAUTHORITY",
14
+ "XDG_CURRENT_DESKTOP",
15
+ "XDG_RUNTIME_DIR",
16
+ "XDG_SESSION_TYPE",
17
+ "XDG_CONFIG_HOME",
18
+ "XDG_CACHE_HOME",
19
+ "OPENCODE_BROWSER_PROFILE",
20
+ "OPENCODE_BROWSER_SESSION_LAYOUT",
21
+ "OPENCODE_BROWSER_EXECUTABLE",
22
+ "OPENCODE_BROWSER_HEADLESS",
23
+ "OPENCODE_BROWSER_DISABLE_CRASH_REPORTER",
24
+ "OPENCODE_BROWSER_CDP_HOST",
25
+ "OPENCODE_BROWSER_CDP_PORT",
26
+ "OPENCODE_BROWSER_IDLE_MINUTES",
27
+ "OPENCODE_BROWSER_MAX_PAGES",
28
+ "OPENCODE_BROWSER_STARTUP_SECONDS",
29
+ "OPENCODE_BROWSER_OPERATION_SECONDS",
30
+ "OPENCODE_BROWSER_DOWNSTREAM_COMMAND"
31
+ ],
32
+ "startup_timeout_sec": 40,
33
+ "tool_timeout_sec": 540
34
+ }
35
+ }
36
+ }
@@ -0,0 +1,96 @@
1
+ # Contributing
2
+
3
+ Contributions should preserve the ownership model rather than working around
4
+ it in an adapter or response filter.
5
+
6
+ ## Requirements
7
+
8
+ - Rust 1.89 or newer
9
+ - Bun
10
+ - Node.js 20.19+, 22.12+, or 23+ for npm packaging
11
+ - A compatible headed Chromium-family browser for the E2E test
12
+ - A display server or Xvfb for headed browser tests
13
+ - `x86_64-unknown-linux-musl` for the published native binary
14
+
15
+ ## Checks
16
+
17
+ Run the normal checks before opening a pull request:
18
+
19
+ ```sh
20
+ cargo fmt --check
21
+ cargo test --all-targets
22
+ cargo clippy --all-targets -- -D warnings
23
+ bun test tests/plugin.test.ts
24
+ ```
25
+
26
+ Run the real-browser test for changes to routing, ownership, browser startup,
27
+ cleanup, persistence, profile locking, or process shutdown:
28
+
29
+ ```sh
30
+ cargo test --release --test e2e -- --ignored --nocapture --test-threads=1
31
+ ```
32
+
33
+ The real-browser cases share Bunx's installation cache and run serially. Adapter
34
+ and tool-call concurrency is exercised within each case.
35
+
36
+ The E2E test starts adapters with temporary profiles, private sockets, and CDP
37
+ ports. It verifies automatic race-safe broker startup, shared cookies, tab
38
+ isolation, compact dispatch, concurrent calls, release during an active call,
39
+ reconnecting adapters, unowned-tab preservation, lazy Chromium activation,
40
+ per-session window placement, and automatic browser shutdown. The regular
41
+ integration suite verifies that one adapter disconnect cannot stop a broker
42
+ still used by another adapter.
43
+
44
+ Check the npm artifact when changing package files or the native binary:
45
+
46
+ ```sh
47
+ rustup target add x86_64-unknown-linux-musl
48
+ npm pack --dry-run
49
+ ```
50
+
51
+ ## Design rules
52
+
53
+ - Stable browser-level CDP tab target IDs are the ownership authority.
54
+ - Worker-local numeric page IDs are disposable routes and must not reach models.
55
+ - A tab can have only one browser session owner.
56
+ - Existing or unowned tabs must not be claimed by inference.
57
+ - Cleanup closes only exact targets owned by the retiring session.
58
+ - Browser generation changes invalidate ownership instead of guessing.
59
+ - Ownership conflicts and malformed downstream responses fail closed.
60
+ - One auto-managed broker owns the browser configuration, profile lease, socket
61
+ lease, workers, and browser lifecycle.
62
+ - The first adapter starts the broker. Concurrent startup must converge on the
63
+ lease winner rather than clone a browser or profile.
64
+ - Independent adapters may share one broker and profile. Their tab ownership
65
+ remains isolated while browser profile data is shared deliberately.
66
+ - A second broker must fail clearly rather than share or clone an active profile
67
+ or socket.
68
+ - Compact OpenCode tools disclose one current action schema at a time without
69
+ duplicating upstream definitions.
70
+ - Per-action OpenCode permission or tool rules force direct mode rather than
71
+ silently broadening access through the compact dispatcher.
72
+ - Tool discovery and compact help must not activate the browser runtime.
73
+ - The broker exits only after every adapter disconnects and the reconnect grace
74
+ expires.
75
+ - Broker shutdown must reject new calls and give active calls up to five seconds
76
+ to finish before closing workers and the browser.
77
+ - Window layout is best-effort presentation. Stable target ownership remains
78
+ authoritative, and layout repair must not move, claim, or close tabs.
79
+
80
+ ## Releases
81
+
82
+ Push the versioned source commit to `main` for 2.x, or to
83
+ `release/opencode-v1` for 1.x, and wait for CI. Dispatch `release.yml` from
84
+ `main` with the full source `commit` SHA. It verifies the pinned workflow and
85
+ source branch, then reuses the checksummed `npm-package` artifact.
86
+
87
+ Use `npm_mode=stage` to submit a release for approval on npm's Staged Packages
88
+ page. For a new npm name, a temporary staging-only `NPM_STAGE_TOKEN` can
89
+ bootstrap the first release; remove that secret and revoke the token after
90
+ approval. Configure npm's trusted publisher as this repository's `release.yml`
91
+ without an environment, then use `npm_mode=publish` for OIDC publication.
92
+ Versions 1.x use `opencode1`; 2.x use `latest`. GitHub releases attach the same
93
+ tested tarball and `SHA256SUMS`. Keep npm, Cargo and Codex versions synchronized.
94
+
95
+ CI runs headed tests against Chrome for Testing 155.0.8059.39. Update the pin
96
+ when validating a new browser version.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mirsella
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,281 @@
1
- # Temporary Holding Version
1
+ # Browser MCP
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@mirsella/browser-mcp)](https://www.npmjs.com/package/@mirsella/browser-mcp)
4
+ [![CI](https://github.com/mirsella/browser-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/mirsella/browser-mcp/actions/workflows/ci.yml)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ One shared browser profile with separate tab ownership for OpenCode sessions
8
+ and Codex conversations. The plugin wraps
9
+ [`chrome-devtools-mcp`](https://github.com/ChromeDevTools/chrome-devtools-mcp)
10
+ and routes each conversation through its own browser tabs while sharing cookies,
11
+ logins, local storage, cache, and extensions.
12
+
13
+ Package 2.x targets OpenCode v2 (2.0.27 or newer). Package 1.x retains the
14
+ OpenCode v1 adapter (1.18 or newer, below 2). Codex uses the same Rust MCP
15
+ server and manifests in both releases. The native v2 adapter uses
16
+ `@opencode/plugin`; local directories also expose a physical `server` entrypoint.
17
+
18
+ Install `@mirsella/browser-mcp` for OpenCode v2, or `@mirsella/browser-mcp@opencode1`
19
+ for OpenCode v1. Existing Nix-managed and local-directory installations can keep
20
+ their configured paths.
21
+
22
+ ## Requirements
23
+
24
+ - OpenCode 2.0.27 or newer, or Codex with plugin and hook support
25
+ - Linux x64
26
+ - Bun
27
+ - A local Chromium-family browser
28
+ - A graphical session, unless `OPENCODE_BROWSER_HEADLESS=true`
29
+
30
+ ## OpenCode setup
31
+
32
+ Add the plugin to `opencode.json`. It enables the browser server and makes
33
+ the browser automation skill available by default:
34
+
35
+ ```json
36
+ {
37
+ "$schema": "https://opencode.ai/v2/config.json",
38
+ "plugins": ["@mirsella/browser-mcp"]
39
+ }
40
+ ```
41
+
42
+ Restart OpenCode after changing its configuration. That is the complete setup.
43
+ You do not need a separate installation, broker command, or background service.
44
+
45
+ The first adapter starts the packaged native broker automatically.
46
+ Concurrent Codex and OpenCode instances converge on the same private socket and browser
47
+ profile. The broker remains available while at least one adapter is connected,
48
+ then closes the browser and exits shortly after the final adapter disconnects.
49
+
50
+ OpenCode loads the JavaScript `./server` package export. Codex uses the
51
+ plugin and MCP manifests plus the session hooks. Both integrations launch
52
+ the same packaged Rust executable.
53
+
54
+ ## Codex setup
55
+
56
+ The release tarball contains the executable, both integrations, and a local
57
+ Codex marketplace. Download it from [GitHub Releases](https://github.com/mirsella/browser-mcp/releases),
58
+ extract it to a permanent directory, then register that directory:
59
+
60
+ ```sh
61
+ codex plugin marketplace add /path/to/browser-mcp
62
+ codex plugin add browser@browser-mcp
63
+ ```
64
+
65
+ The npm package is now `@mirsella/browser-mcp`; it replaces `@mirsella/opencode-browser-mcp`.
66
+ To use a GitHub release in OpenCode, set the plugin entry to the `file:///absolute/path`
67
+ of its unpacked directory instead of the npm name.
68
+
69
+ For a source checkout, build and stage the binary first (`bun run build:native`
70
+ and `bun run stage:native`). Use a packaged directory for installation so
71
+ compiler outputs are not copied into Codex's plugin cache.
72
+
73
+ The installed plugin is enabled by default. Open `/hooks` in Codex to review
74
+ and trust its two hooks, then restart Codex. They inject the conversation ID
75
+ before browser calls and release owned tabs at `SessionEnd`. Browser calls
76
+ without an injected identity fail closed. The plugin exposes compact `help`
77
+ and `dispatch` tools and loads the same browser automation skill as OpenCode.
78
+
79
+ Codex and OpenCode use separate ownership namespaces while sharing the existing
80
+ broker, profile, cookies and logins. Codex's hook API identifies subagents with
81
+ their parent conversation ID, so subagents share that conversation's tabs.
82
+ Use separate pages when they work concurrently.
83
+
84
+ Codex runs `SessionEnd` on normal shutdown, on archive/delete of an open
85
+ conversation, or after 30 minutes idle with no client connected. Its hook has
86
+ a three-second deadline: the broker acknowledges cleanup promptly, then waits
87
+ for active calls before closing only that conversation's owned tabs. Cleanup
88
+ does not start a broker when none is running. Crashes still use normal broker
89
+ shutdown and idle cleanup.
90
+
91
+ The Codex MCP entry uses a 540-second tool timeout. Add `--direct-tools` to its
92
+ arguments when configuring per-action Codex tool approval rules; compact
93
+ dispatch has one approval rule for all actions.
94
+
95
+ ## Plugin behavior
96
+
97
+ The plugin:
98
+
99
+ - registers and enables the packaged browser MCP adapter;
100
+ - injects the active OpenCode session ID after model argument generation;
101
+ - exposes compact browser tools unless existing permissions require direct tools;
102
+ - releases owned tabs when an OpenCode session is deleted;
103
+ - registers the bundled browser automation skill when the server is enabled.
104
+
105
+ OpenCode sees two compact tools by default:
106
+
107
+ - `browser_dispatch` executes one browser action.
108
+ - `browser_help` lists actions or loads one action schema.
109
+
110
+ If the plugin detects per-action `browser_*` permission or tool rules, it uses
111
+ direct tools so those policies continue to work.
112
+
113
+ Settings:
114
+
115
+ - `enabled` (default `true`): start the server and load the skill. Set it to
116
+ `false` to disable both. An explicit `mcp.servers.browser` entry takes precedence.
117
+ - `compactTools` (default `true`): keep `browser_dispatch` and `browser_help`
118
+ instead of the direct tools. Set it to `false` to always use direct tools:
119
+
120
+ ```json
121
+ {
122
+ "$schema": "https://opencode.ai/v2/config.json",
123
+ "plugins": [
124
+ { "package": "@mirsella/browser-mcp", "options": { "compactTools": false } }
125
+ ]
126
+ }
127
+ ```
128
+
129
+ ## Architecture
130
+
131
+ ```mermaid
132
+ flowchart LR
133
+ O1[OpenCode instance A] --> A1[packaged stdio adapter]
134
+ O2[OpenCode instance B] --> A2[packaged stdio adapter]
135
+ A1 -->|private Unix socket| R[auto-managed broker]
136
+ A2 -->|private Unix socket| R
137
+ R --> T[CDP target tracker]
138
+ R --> W[session worker pool]
139
+ W --> C[chrome-devtools-mcp]
140
+ T --> B[managed browser]
141
+ C --> B
142
+ B --> P[shared locked profile]
143
+ ```
144
+
145
+ The adapter starts the broker on demand but does not own it. This lets adapters
146
+ from separate OpenCode processes share one browser without tying its lifetime to
147
+ whichever process connected first. Socket and profile locks make simultaneous
148
+ startup race-safe and prevent two browsers from opening the same profile.
149
+
150
+ Each routed session leases its own `chrome-devtools-mcp` worker. Stable
151
+ browser-level CDP target IDs remain the ownership authority; worker-local page
152
+ numbers are removed from model-visible schemas and responses.
153
+
154
+ ## Ownership guarantees
155
+
156
+ - A tab has at most one owner.
157
+ - Routed sessions execute concurrently through separate workers.
158
+ - Popups inherit the owner of their opener tab.
159
+ - A session cannot select, inspect, or close another session's tabs through the broker.
160
+ - Manual and otherwise unowned tabs are not claimed during cleanup.
161
+ - Ownership conflicts, stale browser generations, and malformed responses fail closed.
162
+
163
+ These are routing guarantees, not an operating-system security boundary. Any
164
+ process running as the same Unix user can connect directly to the browser's
165
+ loopback CDP port.
166
+
167
+ ## Browser and profile
168
+
169
+ The plugin detects Chromium, Google Chrome, Helium, Brave, and Microsoft Edge.
170
+ Chromium is preferred by default; `OPENCODE_BROWSER_EXECUTABLE` overrides
171
+ automatic detection.
172
+ Google Chrome 136 and newer ignore remote-debugging flags for its default data
173
+ directory, so Chrome uses a dedicated directory under
174
+ `~/.config/opencode-browser-mcp` by default. Other detected browsers retain their
175
+ existing profile defaults.
176
+
177
+ The broker starts Chromium lazily on the first browser action. For a headed
178
+ browser it passes only a fixed allowlist of display and desktop variables. The
179
+ current process environment stays authoritative; missing values are recovered
180
+ from the current user session when available.
181
+
182
+ Configuration variables inherited from either host (the existing names are
183
+ shared by both integrations):
184
+
185
+ | Variable | Default | Purpose |
186
+ | --- | --- | --- |
187
+ | `OPENCODE_BROWSER_EXECUTABLE` | auto-detected | Chromium-family executable |
188
+ | `OPENCODE_BROWSER_PROFILE` | browser-dependent | Shared browser data directory |
189
+ | `OPENCODE_BROWSER_HEADLESS` | `false` | Run without a visible window |
190
+ | `OPENCODE_BROWSER_SESSION_LAYOUT` | `shared-window` | `shared-window` or `window-per-session` |
191
+ | `OPENCODE_BROWSER_CDP_PORT` | `9222` | Loopback CDP port |
192
+ | `OPENCODE_BROWSER_IDLE_MINUTES` | `30` | Fallback cleanup for routed sessions |
193
+ | `OPENCODE_BROWSER_MAX_PAGES` | `5` | Max owned tabs per agent session |
194
+ | `OPENCODE_BROWSER_STARTUP_SECONDS` | `20` | Browser startup deadline |
195
+ | `OPENCODE_BROWSER_OPERATION_SECONDS` | `540` | Browser operation deadline |
196
+ | `OPENCODE_BROWSER_DOWNSTREAM_COMMAND` | `bunx` | DevTools MCP launcher |
197
+
198
+ ## Lifecycle
199
+
200
+ | Event | Behavior |
201
+ | --- | --- |
202
+ | First adapter connects | One internal broker acquires the socket and profile leases |
203
+ | Tools are listed | Chromium remains stopped |
204
+ | First browser action | Chromium and the ownership tracker start |
205
+ | OpenCode turn becomes idle | Owned tabs remain available for the next turn |
206
+ | OpenCode session is deleted | Only that session's owned tabs close |
207
+ | Each session owns at most 5 pages | `new_page` beyond the cap fails; reuse a page with `navigate_page` or free one with `close_page` |
208
+ | Routed session reaches the configured inactivity timeout | Fallback cleanup closes that session's owned tabs; defaults to 30 minutes and `0` disables it |
209
+ | Another OpenCode instance connects | It shares the broker and profile with isolated tab ownership |
210
+ | Final adapter disconnects | The broker waits briefly, closes Chromium, and exits |
211
+ | Browser exits, segfaults, or is killed | The next browser action starts Chromium again; ownership from the old browser generation is discarded |
212
+ | DevTools worker exits or loses its transport | The next call replaces the worker and restores routing to surviving owned tabs |
213
+ | Broker exits unexpectedly | Connected adapters stay available and start one replacement on the next call; surviving tabs are restored only when the exact browser generation matches |
214
+ | MCP adapter exits unexpectedly | The OpenCode plugin reconnects it automatically, with retries up to 30 seconds apart |
215
+
216
+ Calls interrupted after dispatch can have taken effect. They return an error and
217
+ are never replayed automatically. Inspect the browser state before retrying an
218
+ action. Explicitly disabled or disconnected MCP entries stay disabled.
219
+
220
+ ## Troubleshooting
221
+
222
+ - A headed startup error mentioning `DISPLAY` or `WAYLAND_DISPLAY` means no graphical session could be found. Set `OPENCODE_BROWSER_HEADLESS=true` when running without one.
223
+ - A profile or socket lease error means another live package process owns it or a stale process is still running. Do not bypass the locks.
224
+ - A process on the configured CDP port must belong to the exact managed browser generation. Stop it or choose another port.
225
+ - If downstream startup fails, verify that `bunx` is available to OpenCode.
226
+ - The plugin refuses to replace an unrelated `mcp.servers.browser` entry.
227
+
228
+ ## Security
229
+
230
+ All sessions deliberately share cookies, authentication, storage, extensions,
231
+ permissions, history, and downloads. Browser content remains untrusted and may
232
+ contain prompt injection. The private same-UID socket prevents access by other
233
+ local users, but it does not isolate processes already running as your Unix user.
234
+
235
+ File exports can use the conversation's workspace and `/tmp/opencode`.
236
+ Chrome DevTools also permits its OS temporary directory. `/tmp/opencode`
237
+ is a shared scratch directory for small, temporary snapshots,
238
+ screenshots, and network responses. Clean up exported files when finished;
239
+ store larger or lasting artifacts in the workspace.
240
+
241
+ Read [`SECURITY.md`](SECURITY.md) before using a profile with sensitive data.
242
+
243
+ ## Development
244
+
245
+ ```sh
246
+ cargo fmt --check
247
+ cargo test --all-targets
248
+ cargo clippy --all-targets -- -D warnings
249
+ bun test tests/plugin.test.ts
250
+ cargo test --release --test e2e -- --ignored --nocapture --test-threads=1
251
+ ```
252
+
253
+ The headed E2E starts adapters against temporary profiles, sockets, and CDP
254
+ ports. It checks automatic startup, startup races, cookie sharing, tab isolation,
255
+ concurrent calls, active-call cleanup, reconnect grace, compact
256
+ dispatch, both window layouts, and automatic browser shutdown.
257
+
258
+ | Path | Responsibility |
259
+ | --- | --- |
260
+ | `plugin/` | OpenCode registration, session routing, and cleanup controls |
261
+ | `vendor/` | packaged native binary used directly by the OpenCode plugin |
262
+ | `src/broker.rs` | adapter bridge, managed broker lifecycle, routing, and leases |
263
+ | `src/cdp.rs` | stable CDP target tracking and ownership |
264
+ | `src/main.rs` | browser supervision, workers, and response filtering |
265
+ | `src/persistence.rs` | atomic generation-scoped ownership state |
266
+ | `tests/e2e.rs` | startup, shared-profile, isolation, routing, and shutdown coverage |
267
+
268
+ See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the development and release workflow.
269
+
270
+ ## Releases
271
+
272
+ CI builds and tests the distributable tarball on every push. Run the `release`
273
+ workflow from `main` with the full tested source commit: `main` for 2.x, or
274
+ `release/opencode-v1` for 1.x. The workflow verifies that commit and downloads
275
+ its checksummed CI artifact instead of rebuilding it. Use `stage` for npm
276
+ browser approval, or `publish` after configuring `release.yml` as an npm
277
+ trusted publisher. The channels are `latest` for 2.x and `opencode1` for 1.x.
278
+
279
+ ## License
280
+
281
+ [MIT](LICENSE)
package/SECURITY.md ADDED
@@ -0,0 +1,64 @@
1
+ # Security policy
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Please use [GitHub private vulnerability reporting](https://github.com/mirsella/browser-mcp/security/advisories/new).
6
+ Do not open a public issue for a vulnerability that exposes browser data,
7
+ credentials, local files, or cross-session tabs.
8
+
9
+ Include the package version, browser and version, MCP host, reproduction steps,
10
+ and whether the issue also reproduces with `chrome-devtools-mcp@1.6.0` directly.
11
+
12
+ ## Security boundary
13
+
14
+ This project isolates tab ownership between cooperating MCP sessions. It is not
15
+ a sandbox for mutually untrusted local users or processes.
16
+
17
+ The broker keeps its Unix socket, profile lock, and ownership state private to
18
+ the current Unix user, but the managed browser exposes an unauthenticated CDP
19
+ endpoint on loopback. Any process running as the same user can connect to that
20
+ port and control the browser without going through the ownership broker.
21
+
22
+ Only one broker may open a given browser profile. The profile and socket locks
23
+ prevent accidental concurrent use and profile corruption; they are not a
24
+ security boundary against another process running as the same user. Multiple MCP
25
+ adapters are expected to connect to that broker and share its browser profile.
26
+
27
+ The broker socket accepts only peers with the broker's Unix UID and is created
28
+ with mode `0600` in a private directory. This protects against other local users,
29
+ not against another process already running as the same user.
30
+
31
+ All browser sessions share one user-data directory. This includes cookies,
32
+ authentication, local storage, cache, extensions, permissions, history, and
33
+ downloads. A session cannot inspect another session's tabs through the broker,
34
+ but websites can still communicate through shared browser data and origins.
35
+ The optional per-session window layout is visual organization only and does not
36
+ create another security boundary.
37
+
38
+ Browser content is untrusted input. Pages can include text designed to alter an
39
+ agent's behavior. The broker preserves structured output where upstream tools
40
+ provide it, but it cannot prevent prompt injection.
41
+
42
+ ## Operational guidance
43
+
44
+ - Use a dedicated browser user-data directory for sensitive automation.
45
+ - Do not bypass or remove the profile or socket locks to run another broker.
46
+ - Let the packaged adapters share the auto-managed broker through its private
47
+ socket. Do not start another browser against the same profile.
48
+ - Do not expose the CDP port beyond loopback.
49
+ - Do not run untrusted local processes while a sensitive profile is open.
50
+ - Use OS, container, or VM isolation when local users or workloads do not trust each other.
51
+ - Keep OpenCode, the browser, this package, and `chrome-devtools-mcp` updated.
52
+ - Review browser downloads and file writes before opening or executing them.
53
+ - Treat screenshots, DOM text, console messages, and network responses as untrusted data.
54
+
55
+ The downstream worker runs with usage statistics and CrUX requests disabled.
56
+ It also disables update checks and redacts headers that upstream classifies as
57
+ sensitive. URLs, bodies, and other headers can still appear in tool output.
58
+ These settings do not disable browser telemetry or prevent websites from
59
+ making network requests.
60
+
61
+ ## Supported versions
62
+
63
+ Security fixes are provided for the latest published release. Reports against
64
+ older versions should first be reproduced on the latest version when possible.
@@ -0,0 +1,19 @@
1
+ {
2
+ "hooks": {
3
+ "PreToolUse": [{
4
+ "matcher": "^mcp__(browser|plugin_browser_browser)__.*$",
5
+ "hooks": [{
6
+ "type": "command",
7
+ "command": "cd \"$PLUGIN_ROOT\" && \"$PLUGIN_ROOT/vendor/browser-mcp\" codex-hook",
8
+ "timeout": 5
9
+ }]
10
+ }],
11
+ "SessionEnd": [{
12
+ "hooks": [{
13
+ "type": "command",
14
+ "command": "cd \"$PLUGIN_ROOT\" && \"$PLUGIN_ROOT/vendor/browser-mcp\" codex-hook",
15
+ "timeout": 3
16
+ }]
17
+ }]
18
+ }
19
+ }
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "@mirsella/browser-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.0",
4
+ "description": "Session-isolated browser automation over MCP and Chrome DevTools Protocol",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./server.ts",
8
+ "./server": "./server.ts"
9
+ },
10
+ "bin": {
11
+ "browser-mcp": "vendor/browser-mcp"
12
+ },
13
+ "files": [
14
+ "plugin/",
15
+ "skills/",
16
+ "vendor/",
17
+ ".codex-plugin/plugin.json",
18
+ ".mcp.json",
19
+ "hooks/",
20
+ ".agents/plugins/marketplace.json",
21
+ "README.md",
22
+ "SECURITY.md",
23
+ "CONTRIBUTING.md",
24
+ "LICENSE",
25
+ "server.ts"
26
+ ],
27
+ "keywords": [
28
+ "opencode",
29
+ "mcp",
30
+ "browser",
31
+ "browser-automation",
32
+ "cdp",
33
+ "session-isolation",
34
+ "chrome-devtools",
35
+ "chromium",
36
+ "codex"
37
+ ],
38
+ "homepage": "https://github.com/mirsella/browser-mcp#readme",
39
+ "bugs": "https://github.com/mirsella/browser-mcp/issues",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/mirsella/browser-mcp.git"
43
+ },
44
+ "license": "MIT",
45
+ "author": "mirsella",
46
+ "os": [
47
+ "linux"
48
+ ],
49
+ "cpu": [
50
+ "x64"
51
+ ],
52
+ "engines": {
53
+ "opencode": ">=2.0.27 <3"
54
+ },
55
+ "devDependencies": {
56
+ "@opencode/plugin": "2.0.28",
57
+ "@types/node": "24.0.0",
58
+ "typescript": "5.9.3"
59
+ },
60
+ "publishConfig": {
61
+ "access": "public",
62
+ "tag": "latest"
63
+ },
64
+ "peerDependencies": {
65
+ "@opencode/plugin": ">=2.0.27 <3"
66
+ },
67
+ "dependencies": {
68
+ "yaml": "2.8.1"
69
+ },
70
+ "main": "./server.ts",
71
+ "scripts": {
72
+ "build:native": "cargo build --release --target x86_64-unknown-linux-musl",
73
+ "stage:native": "node scripts/stage-native.mjs",
74
+ "test": "cargo test --all-targets && bun test tests/plugin.test.ts"
75
+ }
6
76
  }
@@ -0,0 +1,143 @@
1
+ import { Plugin, Skill } from "@opencode/plugin";
2
+ import { execFile } from "node:child_process";
3
+ import { readdir, readFile } from "node:fs/promises";
4
+ import { fileURLToPath } from "node:url";
5
+ import { promisify } from "node:util";
6
+ import { parse } from "yaml";
7
+
8
+ const execute = promisify(execFile);
9
+ const binary = fileURLToPath(new URL("../vendor/browser-mcp", import.meta.url));
10
+ const skills = fileURLToPath(new URL("../skills/", import.meta.url));
11
+ const directTools = `click close_page drag emulate evaluate_script fill fill_form get_console_message
12
+ get_network_request handle_dialog hover lighthouse_audit list_console_messages list_network_requests
13
+ list_pages navigate_page new_page performance_analyze_insight performance_start_trace performance_stop_trace
14
+ press_key resize_page take_heapsnapshot take_screenshot take_snapshot type_text upload_file wait_for`
15
+ .split(/\s+/).map(name => `browser_${name}`);
16
+
17
+ function partialPolicy(agents: Array<{ permissions: readonly { action: string }[] }>) {
18
+ return agents.some(agent => agent.permissions.some(({ action }) => {
19
+ const regex = new RegExp(`^${action.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*").replaceAll("?", ".")}$`);
20
+ return directTools.some(tool => regex.test(tool))
21
+ && !(regex.test("browser_dispatch") && directTools.every(tool => regex.test(tool)));
22
+ }));
23
+ }
24
+
25
+ export default Plugin.define({
26
+ id: "@mirsella/browser-mcp",
27
+ async setup(ctx) {
28
+ const { enabled = true, compactTools = true } = ctx.options;
29
+ if (typeof enabled !== "boolean") throw new Error("enabled must be a boolean");
30
+ if (typeof compactTools !== "boolean") throw new Error("compactTools must be a boolean");
31
+ let compact = compactTools;
32
+ let reconnectGeneration = 0;
33
+ let active = enabled;
34
+ await ctx.mcp.transform(editor => {
35
+ const existing = editor.get("browser");
36
+ if (existing?.type === "remote" || (existing && existing.command[0] !== binary)) {
37
+ throw new Error("Browser MCP cannot replace an incompatible mcp.servers.browser configuration");
38
+ }
39
+ active = !(existing?.disabled ?? !enabled);
40
+ editor.set("browser", {
41
+ ...existing,
42
+ type: "local", command: compact ? [binary] : [binary, "--direct-tools"],
43
+ disabled: !active, codemode: false,
44
+ environment: { ...existing?.environment, BROWSER_MCP_RECONNECT_GENERATION: String(reconnectGeneration) },
45
+ timeout: { startup: 30_000, catalog: 30_000, execution: 600_000, ...existing?.timeout },
46
+ });
47
+ });
48
+ if (active) {
49
+ const entries = await readdir(skills, { withFileTypes: true });
50
+ const registered = await Promise.all(entries.filter(entry => entry.isDirectory()).map(async entry => {
51
+ const path = `${skills}${entry.name}/SKILL.md`;
52
+ const text = await readFile(path, "utf8");
53
+ const frontmatter = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
54
+ if (!frontmatter) throw new Error(`Missing skill frontmatter: ${path}`);
55
+ const meta = parse(frontmatter[1]);
56
+ if (!meta || typeof meta.name !== "string" || typeof meta.description !== "string") throw new Error(`Invalid skill metadata: ${path}`);
57
+ return Skill.Info.make({ id: Skill.ID.make(meta.name), name: Skill.Name.make(meta.name),
58
+ description: meta.description, path: Skill.Info.fields.path.make(path), content: text.slice(frontmatter[0].length) });
59
+ }));
60
+ await ctx.skill.transform(editor => { for (const skill of registered) editor.add(skill); });
61
+ }
62
+ await ctx.tool.hook("execute.before", input => {
63
+ if (!input.tool.startsWith("browser_")) return;
64
+ if (!input.sessionID) throw new Error("Browser tool call has no OpenCode session ID");
65
+ if (!input.input || typeof input.input !== "object" || Array.isArray(input.input)) throw new Error("Browser tool call has invalid arguments");
66
+ input.input = { ...input.input, __opencode_session_id: input.sessionID };
67
+ });
68
+ const controller = new AbortController();
69
+ let timer: ReturnType<typeof setTimeout> | undefined;
70
+ let recovering: Promise<void> | undefined;
71
+ let failures = 0;
72
+ // Runners that never list the server cannot be fixed by reloading;
73
+ // stay quiet until it has been seen at least once.
74
+ let seen = false;
75
+ const schedule = () => {
76
+ if (controller.signal.aborted) return;
77
+ timer = setTimeout(() => void recover(), failures ? Math.min(30_000, 1_000 * 2 ** Math.min(failures - 1, 5)) : 5_000);
78
+ timer.unref();
79
+ };
80
+ const recover = (): Promise<void> => {
81
+ if (controller.signal.aborted) return Promise.resolve();
82
+ if (recovering) return recovering;
83
+ if (timer) clearTimeout(timer);
84
+ recovering = (async () => {
85
+ try {
86
+ const server = (await ctx.mcp.list()).data.find(server => server.name === "browser");
87
+ if (!server) throw new Error("Browser MCP status is missing");
88
+ seen = true;
89
+ // A disabled connection is an explicit user choice; only recover failures.
90
+ if (server.status.status === "failed" && !controller.signal.aborted) {
91
+ console.warn("Browser MCP adapter failed; reloading its registration");
92
+ reconnectGeneration++;
93
+ await ctx.mcp.reload();
94
+ const restored = (await ctx.mcp.list()).data.find(server => server.name === "browser");
95
+ if (restored?.status.status !== "connected") throw new Error(`Browser MCP recovery failed: ${JSON.stringify(restored?.status)}`);
96
+ }
97
+ failures = 0;
98
+ } catch (error) {
99
+ if (!controller.signal.aborted) { failures++; if (seen) console.error("Browser MCP recovery failed; will retry", error); }
100
+ } finally { recovering = undefined; schedule(); }
101
+ })();
102
+ return recovering;
103
+ };
104
+ // Recovery must never stall a prompt: a wedged adapter keeps retrying in
105
+ // the background while chat continues within a short deadline.
106
+ const recoverSoon = async () => {
107
+ let deadline: ReturnType<typeof setTimeout> | undefined;
108
+ try {
109
+ await Promise.race([
110
+ recover(),
111
+ new Promise<void>(resolve => { deadline = setTimeout(resolve, 5_000); deadline.unref(); }),
112
+ ]);
113
+ } finally {
114
+ if (deadline) clearTimeout(deadline);
115
+ }
116
+ };
117
+ // Catalog reads wait for plugin bootstrap. Do not await them inside setup.
118
+ const checkPolicy = async () => {
119
+ if (!compactTools || controller.signal.aborted) return;
120
+ const next = !partialPolicy((await ctx.agent.list()).data);
121
+ if (controller.signal.aborted || next === compact) return;
122
+ compact = next;
123
+ if (!compact) console.warn("Browser MCP uses direct tools to preserve per-action permissions");
124
+ await ctx.mcp.reload();
125
+ };
126
+ const policyReady = Promise.resolve().then(checkPolicy);
127
+ void policyReady.catch(error => console.error("Browser MCP permission initialization failed", error));
128
+ await ctx.session.hook("prompt", async () => { await policyReady; await checkPolicy(); await recoverSoon(); });
129
+ const events = async () => {
130
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
131
+ if (controller.signal.aborted) break;
132
+ if (event.type === "agent.updated") void checkPolicy().catch(error => console.error("Browser MCP permission update failed", error));
133
+ if ((event.type === "mcp.status.changed") && event.data.server === "browser") void recover();
134
+ if (event.type !== "session.deleted") continue;
135
+ try { await execute(binary, ["release-session", event.data.sessionID], { signal: controller.signal }); }
136
+ catch (error) { if (!controller.signal.aborted) console.error(`Failed to release browser session ${event.data.sessionID}`, error); }
137
+ }
138
+ };
139
+ void events().catch(error => { if (!controller.signal.aborted) console.error("Browser MCP event subscription failed", error); });
140
+ schedule();
141
+ return () => { controller.abort(); if (timer) clearTimeout(timer); };
142
+ },
143
+ });
package/server.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./plugin/browser-routing.ts";
@@ -0,0 +1,45 @@
1
+ ---
2
+ name: browser-automation
3
+ description: Use browser automation to inspect or interact with websites, test rendered interfaces, capture screenshots, and diagnose console or network behavior.
4
+ ---
5
+
6
+ # Browser Automation
7
+
8
+ Use the browser tools when the task requires rendered state, authentication,
9
+ client-side behavior, layout, accessibility, console output, or network traffic.
10
+
11
+ OpenCode and Codex expose two compact tools: `help` and `dispatch`. OpenCode
12
+ names them `browser_help` and `browser_dispatch`; Codex namespaces them under
13
+ this plugin's browser MCP server.
14
+
15
+ - `browser_help` lists action names or loads the current schema for one action.
16
+ - `browser_dispatch` executes an action with `{ action, arguments }`.
17
+
18
+ For compact `browser_dispatch`, put every action-specific field inside `arguments`,
19
+ not beside it. For example, use `{ "action": "navigate_page", "arguments": { "url": "https://example.com" } }`.
20
+
21
+ Common actions include `navigate_page`, `take_snapshot`, `click`, `fill_form`,
22
+ `take_screenshot`, `evaluate_script`, `list_console_messages`, and
23
+ `list_network_requests`. Call `browser_help` for an action before using it when
24
+ its exact arguments are not already clear. Do not guess argument shapes.
25
+
26
+ Direct `browser_*` action tools may appear when compact tools are disabled. Use
27
+ them directly with the same workflow.
28
+
29
+ The host injects conversation identity automatically. Never add hidden routing
30
+ fields. Browser tabs belong to the conversation; Codex subagents share their
31
+ parent conversation's tabs, so coordinate concurrent work using separate pages.
32
+
33
+ ## Workflow
34
+
35
+ 1. Reuse the current page by default. Use `navigate_page` to change URLs or reload after code or deployment changes. Use `new_page` only when simultaneous pages are necessary (max 5 owned pages per session; extra `new_page` calls fail, so `close_page` a finished page first), and close temporary pages when finished.
36
+ 2. Navigate, then inspect the page before interacting.
37
+ 3. Use the latest snapshot to identify elements and references. Refresh it after navigation or meaningful DOM changes.
38
+ 4. Perform the smallest interaction needed, then inspect the result.
39
+ 5. Verify consequential actions from visible state or relevant diagnostics.
40
+
41
+ Use screenshots when visual appearance, responsive layout, rendering, or image output matters. Prefer snapshots for locating elements and understanding page structure.
42
+
43
+ Inspect console messages for client-side exceptions and warnings. Inspect network requests when diagnosing API failures, redirects, authentication, caching, or unexpected response data.
44
+
45
+ Do not claim an interaction succeeded solely because a tool call returned without an error; verify its observable result.
Binary file