@mirsella/browser-mcp 0.0.0-stage → 1.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": "1.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,276 @@
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 1.x is the OpenCode v1 release line (1.18 or newer, below 2).
14
+ Use package 2.x for the native OpenCode v2 adapter. Codex uses the same
15
+ standalone Rust server in both release lines.
16
+
17
+ ## Requirements
18
+
19
+ - OpenCode 1.18 or newer, or Codex with plugin and hook support
20
+ - Linux x64
21
+ - Bun
22
+ - A local Chromium-family browser
23
+ - A graphical session, unless `OPENCODE_BROWSER_HEADLESS=true`
24
+
25
+ ## OpenCode setup
26
+
27
+ Add the plugin to `opencode.json`. It enables the browser server and makes
28
+ the browser automation skill available by default:
29
+
30
+ ```json
31
+ {
32
+ "$schema": "https://opencode.ai/config.json",
33
+ "plugin": ["@mirsella/browser-mcp@opencode1"]
34
+ }
35
+ ```
36
+
37
+ Restart OpenCode after changing its configuration. That is the complete setup.
38
+ You do not need a separate installation, broker command, or background service.
39
+
40
+ The first adapter starts the packaged native broker automatically.
41
+ Concurrent Codex and OpenCode instances converge on the same private socket and browser
42
+ profile. The broker remains available while at least one adapter is connected,
43
+ then closes the browser and exits shortly after the final adapter disconnects.
44
+
45
+ OpenCode loads the JavaScript `./server` package export. Codex uses the
46
+ plugin and MCP manifests plus the session hooks. Both integrations launch
47
+ the same packaged Rust executable.
48
+
49
+ ## Codex setup
50
+
51
+ The release tarball contains the executable, both integrations, and a local
52
+ Codex marketplace. Download it from [GitHub Releases](https://github.com/mirsella/browser-mcp/releases),
53
+ extract it to a permanent directory, then register that directory:
54
+
55
+ ```sh
56
+ codex plugin marketplace add /path/to/browser-mcp
57
+ codex plugin add browser@browser-mcp
58
+ ```
59
+
60
+ The npm package is now `@mirsella/browser-mcp`; it replaces `@mirsella/opencode-browser-mcp`.
61
+ To use a GitHub release in OpenCode, set the plugin entry to the `file:///absolute/path`
62
+ of its unpacked directory instead of the npm name.
63
+
64
+ For a source checkout, build and stage the binary first (`bun run build:native`
65
+ and `bun run stage:native`). Use a packaged directory for installation so
66
+ compiler outputs are not copied into Codex's plugin cache.
67
+
68
+ The installed plugin is enabled by default. Open `/hooks` in Codex to review
69
+ and trust its two hooks, then restart Codex. They inject the conversation ID
70
+ before browser calls and release owned tabs at `SessionEnd`. Browser calls
71
+ without an injected identity fail closed. The plugin exposes compact `help`
72
+ and `dispatch` tools and loads the same browser automation skill as OpenCode.
73
+
74
+ Codex and OpenCode use separate ownership namespaces while sharing the existing
75
+ broker, profile, cookies and logins. Codex's hook API identifies subagents with
76
+ their parent conversation ID, so subagents share that conversation's tabs.
77
+ Use separate pages when they work concurrently.
78
+
79
+ Codex runs `SessionEnd` on normal shutdown, on archive/delete of an open
80
+ conversation, or after 30 minutes idle with no client connected. Its hook has
81
+ a three-second deadline: the broker acknowledges cleanup promptly, then waits
82
+ for active calls before closing only that conversation's owned tabs. Cleanup
83
+ does not start a broker when none is running. Crashes still use normal broker
84
+ shutdown and idle cleanup.
85
+
86
+ The Codex MCP entry uses a 540-second tool timeout. Add `--direct-tools` to its
87
+ arguments when configuring per-action Codex tool approval rules; compact
88
+ dispatch has one approval rule for all actions.
89
+
90
+ ## Plugin behavior
91
+
92
+ The plugin:
93
+
94
+ - registers and enables the packaged browser MCP adapter;
95
+ - injects the active OpenCode session ID after model argument generation;
96
+ - exposes compact browser tools unless existing permissions require direct tools;
97
+ - releases owned tabs when an OpenCode session is deleted;
98
+ - registers the bundled browser automation skill when the server is enabled.
99
+
100
+ OpenCode sees two compact tools by default:
101
+
102
+ - `browser_dispatch` executes one browser action.
103
+ - `browser_help` lists actions or loads one action schema.
104
+
105
+ If the plugin detects per-action `browser_*` permission or tool rules, it uses
106
+ direct tools so those policies continue to work.
107
+
108
+ Settings:
109
+
110
+ - `enabled` (default `true`): start the server and load the skill. Set it to
111
+ `false` to disable both. An explicit `mcp.browser` entry takes precedence.
112
+ - `compactTools` (default `true`): keep `browser_dispatch` and `browser_help`
113
+ instead of the direct tools. Set it to `false` to always use direct tools:
114
+
115
+ ```json
116
+ {
117
+ "$schema": "https://opencode.ai/config.json",
118
+ "plugin": [
119
+ ["@mirsella/browser-mcp@opencode1", { "compactTools": false }]
120
+ ]
121
+ }
122
+ ```
123
+
124
+ ## Architecture
125
+
126
+ ```mermaid
127
+ flowchart LR
128
+ O1[OpenCode instance A] --> A1[packaged stdio adapter]
129
+ O2[OpenCode instance B] --> A2[packaged stdio adapter]
130
+ A1 -->|private Unix socket| R[auto-managed broker]
131
+ A2 -->|private Unix socket| R
132
+ R --> T[CDP target tracker]
133
+ R --> W[session worker pool]
134
+ W --> C[chrome-devtools-mcp]
135
+ T --> B[managed browser]
136
+ C --> B
137
+ B --> P[shared locked profile]
138
+ ```
139
+
140
+ The adapter starts the broker on demand but does not own it. This lets adapters
141
+ from separate OpenCode processes share one browser without tying its lifetime to
142
+ whichever process connected first. Socket and profile locks make simultaneous
143
+ startup race-safe and prevent two browsers from opening the same profile.
144
+
145
+ Each routed session leases its own `chrome-devtools-mcp` worker. Stable
146
+ browser-level CDP target IDs remain the ownership authority; worker-local page
147
+ numbers are removed from model-visible schemas and responses.
148
+
149
+ ## Ownership guarantees
150
+
151
+ - A tab has at most one owner.
152
+ - Routed sessions execute concurrently through separate workers.
153
+ - Popups inherit the owner of their opener tab.
154
+ - A session cannot select, inspect, or close another session's tabs through the broker.
155
+ - Manual and otherwise unowned tabs are not claimed during cleanup.
156
+ - Ownership conflicts, stale browser generations, and malformed responses fail closed.
157
+
158
+ These are routing guarantees, not an operating-system security boundary. Any
159
+ process running as the same Unix user can connect directly to the browser's
160
+ loopback CDP port.
161
+
162
+ ## Browser and profile
163
+
164
+ The plugin detects Chromium, Google Chrome, Helium, Brave, and Microsoft Edge.
165
+ Chromium is preferred by default; `OPENCODE_BROWSER_EXECUTABLE` overrides
166
+ automatic detection.
167
+ Google Chrome 136 and newer ignore remote-debugging flags for its default data
168
+ directory, so Chrome uses a dedicated directory under
169
+ `~/.config/opencode-browser-mcp` by default. Other detected browsers retain their
170
+ existing profile defaults.
171
+
172
+ The broker starts Chromium lazily on the first browser action. For a headed
173
+ browser it passes only a fixed allowlist of display and desktop variables. The
174
+ current process environment stays authoritative; missing values are recovered
175
+ from the current user session when available.
176
+
177
+ Configuration variables inherited from either host (the existing names are
178
+ shared by both integrations):
179
+
180
+ | Variable | Default | Purpose |
181
+ | --- | --- | --- |
182
+ | `OPENCODE_BROWSER_EXECUTABLE` | auto-detected | Chromium-family executable |
183
+ | `OPENCODE_BROWSER_PROFILE` | browser-dependent | Shared browser data directory |
184
+ | `OPENCODE_BROWSER_HEADLESS` | `false` | Run without a visible window |
185
+ | `OPENCODE_BROWSER_SESSION_LAYOUT` | `shared-window` | `shared-window` or `window-per-session` |
186
+ | `OPENCODE_BROWSER_CDP_PORT` | `9222` | Loopback CDP port |
187
+ | `OPENCODE_BROWSER_IDLE_MINUTES` | `30` | Fallback cleanup for routed sessions |
188
+ | `OPENCODE_BROWSER_MAX_PAGES` | `5` | Max owned tabs per agent session |
189
+ | `OPENCODE_BROWSER_STARTUP_SECONDS` | `20` | Browser startup deadline |
190
+ | `OPENCODE_BROWSER_OPERATION_SECONDS` | `540` | Browser operation deadline |
191
+ | `OPENCODE_BROWSER_DOWNSTREAM_COMMAND` | `bunx` | DevTools MCP launcher |
192
+
193
+ ## Lifecycle
194
+
195
+ | Event | Behavior |
196
+ | --- | --- |
197
+ | First adapter connects | One internal broker acquires the socket and profile leases |
198
+ | Tools are listed | Chromium remains stopped |
199
+ | First browser action | Chromium and the ownership tracker start |
200
+ | OpenCode turn becomes idle | Owned tabs remain available for the next turn |
201
+ | OpenCode session is deleted | Only that session's owned tabs close |
202
+ | 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` |
203
+ | Routed session reaches the configured inactivity timeout | Fallback cleanup closes that session's owned tabs; defaults to 30 minutes and `0` disables it |
204
+ | Another OpenCode instance connects | It shares the broker and profile with isolated tab ownership |
205
+ | Final adapter disconnects | The broker waits briefly, closes Chromium, and exits |
206
+ | Browser exits, segfaults, or is killed | The next browser action starts Chromium again; ownership from the old browser generation is discarded |
207
+ | DevTools worker exits or loses its transport | The next call replaces the worker and restores routing to surviving owned tabs |
208
+ | 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 |
209
+ | MCP adapter exits unexpectedly | The OpenCode plugin reconnects it automatically, with retries up to 30 seconds apart |
210
+
211
+ Calls interrupted after dispatch can have taken effect. They return an error and
212
+ are never replayed automatically. Inspect the browser state before retrying an
213
+ action. Explicitly disabled or disconnected MCP entries stay disabled.
214
+
215
+ ## Troubleshooting
216
+
217
+ - 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.
218
+ - 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.
219
+ - A process on the configured CDP port must belong to the exact managed browser generation. Stop it or choose another port.
220
+ - If downstream startup fails, verify that `bunx` is available to OpenCode.
221
+ - The plugin refuses to replace an unrelated `mcp.browser` entry.
222
+
223
+ ## Security
224
+
225
+ All sessions deliberately share cookies, authentication, storage, extensions,
226
+ permissions, history, and downloads. Browser content remains untrusted and may
227
+ contain prompt injection. The private same-UID socket prevents access by other
228
+ local users, but it does not isolate processes already running as your Unix user.
229
+
230
+ File exports can use the conversation's workspace and `/tmp/opencode`.
231
+ Chrome DevTools also permits its OS temporary directory. `/tmp/opencode`
232
+ is a shared scratch directory for small, temporary snapshots,
233
+ screenshots, and network responses. Clean up exported files when finished;
234
+ store larger or lasting artifacts in the workspace.
235
+
236
+ Read [`SECURITY.md`](SECURITY.md) before using a profile with sensitive data.
237
+
238
+ ## Development
239
+
240
+ ```sh
241
+ cargo fmt --check
242
+ cargo test --all-targets
243
+ cargo clippy --all-targets -- -D warnings
244
+ bun test tests/plugin.test.ts
245
+ cargo test --release --test e2e -- --ignored --nocapture --test-threads=1
246
+ ```
247
+
248
+ The headed E2E starts adapters against temporary profiles, sockets, and CDP
249
+ ports. It checks automatic startup, startup races, cookie sharing, tab isolation,
250
+ concurrent calls, active-call cleanup, reconnect grace, compact
251
+ dispatch, both window layouts, and automatic browser shutdown.
252
+
253
+ | Path | Responsibility |
254
+ | --- | --- |
255
+ | `plugin/` | OpenCode registration, session routing, and cleanup controls |
256
+ | `vendor/` | packaged native binary used directly by the OpenCode plugin |
257
+ | `src/broker.rs` | adapter bridge, managed broker lifecycle, routing, and leases |
258
+ | `src/cdp.rs` | stable CDP target tracking and ownership |
259
+ | `src/main.rs` | browser supervision, workers, and response filtering |
260
+ | `src/persistence.rs` | atomic generation-scoped ownership state |
261
+ | `tests/e2e.rs` | startup, shared-profile, isolation, routing, and shutdown coverage |
262
+
263
+ See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the development and release workflow.
264
+
265
+ ## Releases
266
+
267
+ CI builds and tests the distributable tarball on every push. Run the `release`
268
+ workflow from `main` with the full tested source commit: `main` for 2.x, or
269
+ `release/opencode-v1` for 1.x. The workflow verifies that commit and downloads
270
+ its checksummed CI artifact instead of rebuilding it. Use `stage` for npm
271
+ browser approval, or `publish` after configuring `release.yml` as an npm
272
+ trusted publisher. The channels are `latest` for 2.x and `opencode1` for 1.x.
273
+
274
+ ## License
275
+
276
+ [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,68 @@
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": "1.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": ">=1.18.0 <2"
54
+ },
55
+ "devDependencies": {
56
+ "@opencode-ai/plugin": "1.18.11"
57
+ },
58
+ "publishConfig": {
59
+ "access": "public",
60
+ "tag": "opencode1"
61
+ },
62
+ "main": "./server.ts",
63
+ "scripts": {
64
+ "build:native": "cargo build --release --target x86_64-unknown-linux-musl",
65
+ "stage:native": "node scripts/stage-native.mjs",
66
+ "test": "cargo test --all-targets && bun test tests/plugin.test.ts"
67
+ }
6
68
  }
@@ -0,0 +1,174 @@
1
+ import type { Plugin, PluginModule } from "@opencode-ai/plugin";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ const SESSION_KEY = "__opencode_session_id";
5
+ const SKILLS_PATH = fileURLToPath(new URL("../skills", import.meta.url));
6
+ const MCP_CLI = fileURLToPath(new URL("../vendor/browser-mcp", import.meta.url));
7
+ const DISPATCH_TOOL = "browser_dispatch";
8
+ const DIRECT_TOOLS = `
9
+ browser_click browser_close_page browser_drag browser_emulate browser_evaluate_script browser_fill browser_fill_form
10
+ browser_get_console_message browser_get_network_request browser_handle_dialog browser_hover browser_lighthouse_audit
11
+ browser_list_console_messages browser_list_network_requests browser_list_pages browser_navigate_page browser_new_page
12
+ browser_performance_analyze_insight browser_performance_start_trace browser_performance_stop_trace browser_press_key
13
+ browser_resize_page browser_take_heapsnapshot browser_take_screenshot browser_take_snapshot browser_type_text
14
+ browser_upload_file browser_wait_for
15
+ `
16
+ .trim()
17
+ .split(/\s+/);
18
+
19
+ type ConfigWithPolicies = {
20
+ agent?: Record<string, { permission?: unknown; tools?: unknown }>;
21
+ permission?: unknown;
22
+ skills?: { paths?: string[] };
23
+ tools?: unknown;
24
+ };
25
+
26
+ type BrowserRoutingOptions = {
27
+ enabled?: boolean;
28
+ compactTools?: boolean;
29
+ };
30
+
31
+ function hasPartialBrowserPolicy(value: unknown): boolean {
32
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
33
+ return Object.keys(value).some((pattern) => {
34
+ const expression = pattern
35
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
36
+ .replaceAll("*", ".*")
37
+ .replaceAll("?", ".");
38
+ const regex = new RegExp(`^${expression}$`);
39
+ const matches = (tool: string) => regex.test(tool);
40
+ return DIRECT_TOOLS.some(matches) && !(matches(DISPATCH_TOOL) && DIRECT_TOOLS.every(matches));
41
+ });
42
+ }
43
+
44
+ function requiresDirectTools(config: ConfigWithPolicies): boolean {
45
+ if (hasPartialBrowserPolicy(config.permission) || hasPartialBrowserPolicy(config.tools)) {
46
+ return true;
47
+ }
48
+ return Object.values(config.agent ?? {}).some(
49
+ (agent) => hasPartialBrowserPolicy(agent.permission) || hasPartialBrowserPolicy(agent.tools),
50
+ );
51
+ }
52
+
53
+ const server: Plugin = async ({ $, client, directory }, options) => {
54
+ const { enabled = true, compactTools = true } = (options ?? {}) as BrowserRoutingOptions;
55
+ if (typeof enabled !== "boolean") throw new Error("enabled must be a boolean");
56
+ if (typeof compactTools !== "boolean") throw new Error("compactTools must be a boolean");
57
+ let configured = false;
58
+ let disposed = false;
59
+ let failures = 0;
60
+ let timer: ReturnType<typeof setTimeout> | undefined;
61
+ let recovering: Promise<void> | undefined;
62
+ const scheduleRecovery = (delay: number) => {
63
+ if (timer) clearTimeout(timer);
64
+ if (disposed || !configured) return;
65
+ timer = setTimeout(() => void recover(), delay);
66
+ timer.unref();
67
+ };
68
+ const recover = (): Promise<void> => {
69
+ if (disposed || !configured) return Promise.resolve();
70
+ if (recovering) return recovering;
71
+ recovering = (async () => {
72
+ try {
73
+ const status = await client.mcp.status({ query: { directory }, throwOnError: true });
74
+ if (disposed) return;
75
+ if (!status.data?.browser) throw new Error("Browser MCP status is missing");
76
+ // Respect explicit runtime disconnects in the OpenCode UI.
77
+ if (status.data?.browser?.status === "failed") {
78
+ console.warn("Browser MCP adapter failed; reconnecting");
79
+ await client.mcp.connect({ path: { name: "browser" }, query: { directory }, throwOnError: true });
80
+ const restored = await client.mcp.status({ query: { directory }, throwOnError: true });
81
+ if (restored.data?.browser?.status !== "connected") {
82
+ throw new Error(`Browser MCP adapter recovery failed: ${JSON.stringify(restored.data?.browser)}`);
83
+ }
84
+ console.warn("Browser MCP adapter reconnected");
85
+ }
86
+ failures = 0;
87
+ } catch (error) {
88
+ failures++;
89
+ console.error("Failed to recover browser MCP adapter; will retry", error);
90
+ } finally {
91
+ recovering = undefined;
92
+ scheduleRecovery(failures ? Math.min(30_000, 1_000 * 2 ** Math.min(failures - 1, 5)) : 5_000);
93
+ }
94
+ })();
95
+ return recovering;
96
+ };
97
+
98
+ return {
99
+ config: async (config) => {
100
+ const extended = config as typeof config & ConfigWithPolicies;
101
+ const compact = compactTools && !requiresDirectTools(extended);
102
+
103
+ config.mcp ??= {};
104
+ const existing = config.mcp.browser;
105
+ if (
106
+ existing &&
107
+ ((existing.type !== undefined && existing.type !== "local") ||
108
+ (existing.command?.[0] !== undefined && existing.command[0] !== MCP_CLI))
109
+ ) {
110
+ throw new Error(
111
+ "@mirsella/browser-mcp cannot replace the existing mcp.browser configuration",
112
+ );
113
+ }
114
+ const requestedEnabled = existing?.enabled ?? enabled;
115
+ config.mcp.browser = {
116
+ type: "local",
117
+ command: compact ? [MCP_CLI] : [MCP_CLI, "--direct-tools"],
118
+ enabled: requestedEnabled,
119
+ timeout: 600_000,
120
+ };
121
+ configured = true;
122
+ scheduleRecovery(1_000);
123
+ if (!requestedEnabled) return;
124
+ if (compactTools && !compact) {
125
+ console.warn(
126
+ "@mirsella/browser-mcp uses direct tools to preserve per-action browser permissions",
127
+ );
128
+ }
129
+
130
+ extended.skills ??= {};
131
+ extended.skills.paths ??= [];
132
+ if (!extended.skills.paths.includes(SKILLS_PATH)) extended.skills.paths.push(SKILLS_PATH);
133
+ },
134
+ "tool.execute.before": async (input, output) => {
135
+ if (!input.tool.startsWith("browser_")) return;
136
+ if (!input.sessionID) throw new Error("browser tool call has no OpenCode session ID");
137
+ if (!output.args || typeof output.args !== "object" || Array.isArray(output.args)) {
138
+ throw new Error("browser tool call has invalid arguments");
139
+ }
140
+ (output.args as Record<string, unknown>)[SESSION_KEY] = input.sessionID;
141
+ },
142
+ "chat.message": async () => {
143
+ await recover();
144
+ },
145
+ event: async ({ event }) => {
146
+ if (event.type === "server.instance.disposed") {
147
+ disposed = true;
148
+ if (timer) clearTimeout(timer);
149
+ return;
150
+ }
151
+ const change = event as { type: string; properties: { server?: string } };
152
+ if (change.type === "mcp.tools.changed" && change.properties.server === "browser") {
153
+ // Do not await a callback that can be published by the connect request itself.
154
+ void recover();
155
+ return;
156
+ }
157
+ if (event.type !== "session.deleted") return;
158
+ const sessionID = event.properties.info.id;
159
+ try {
160
+ const result = await $`${[MCP_CLI, "release-session", sessionID]}`.quiet().nothrow();
161
+ if (result.exitCode !== 0) {
162
+ const stderr = String(result.stderr).trim();
163
+ console.error(
164
+ `Failed to release browser session ${sessionID} with exit code ${result.exitCode}${stderr ? `: ${stderr}` : ""}`,
165
+ );
166
+ }
167
+ } catch (error) {
168
+ console.error(`Failed to release browser session ${sessionID}`, error);
169
+ }
170
+ },
171
+ };
172
+ };
173
+
174
+ export default { id: "@mirsella/browser-mcp", server } satisfies PluginModule;
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