mcp-playwright-proxy 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kucharskill
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,76 @@
1
- # Temporary Holding Version
1
+ # Playwright MCP Proxy
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
+ One MCP endpoint for independently configured Playwright browser executors. Each browser tool takes an `instanceId`; the proxy routes it to the official Playwright MCP without that extra argument.
4
+
5
+ ## Requirements and startup
6
+
7
+ Node.js 22+, npm/npx, registry connectivity when resolving current packages, and a supported browser. Edge is the default launch channel; no browser binaries are bundled. Install the Playwright Extension in a Chromium browser for extension mode.
8
+
9
+ ```json
10
+ {
11
+ "mcpServers": {
12
+ "playwright": {
13
+ "command": "npx",
14
+ "args": ["-y", "--prefer-online", "mcp-playwright-proxy@latest"]
15
+ }
16
+ }
17
+ }
18
+ ```
19
+
20
+ The stdio adapter stays connected. It resolves the current worker through npx on demand. The worker resolves `@playwright/mcp@latest` when creating each executor. Package resolution finishes before the executor starts. Existing executors keep their version and browser state until closed. Updating the adapter itself still requires reconnecting the MCP client. An open executor intentionally delays worker updates.
21
+
22
+ ## Instances
23
+
24
+ ```js
25
+ browser_instance_start({ mode: "launch", browser: "msedge", headless: false, isolated: true })
26
+ // Read instanceId from the result, then reuse it:
27
+ browser_navigate({ instanceId: "returned-id", url: "https://example.com" })
28
+ browser_tabs({ instanceId: "returned-id", action: "list" })
29
+ browser_instance_list({})
30
+ browser_instance_stop({ instanceId: "returned-id" })
31
+ ```
32
+
33
+ Start options:
34
+
35
+ | Option | Meaning |
36
+ | --- | --- |
37
+ | `mode` | `launch` (default) or `extension` |
38
+ | `browser` | `msedge`, `chrome`, `firefox`, `webkit`; launch defaults to Edge, extension follows upstream defaults |
39
+ | `headless`, `isolated` | Launch-only settings; upstream defaults apply when omitted |
40
+ | `executablePath` | Custom browser executable, including portable Chromium browsers |
41
+ | `userDataDir` | Browser data directory; incompatible with `isolated: true` |
42
+ | `profileDirName` | Extension-only profile directory name |
43
+ | `allowUnrestrictedFileAccess` | Explicit upstream file-access relaxation; default false |
44
+ | `idleTimeoutMs` | Inactivity after completed work; default 1800000 (30 minutes), 0 disables |
45
+
46
+ For extension mode, omit `headless` and `isolated`. Supply credentials such as `PLAYWRIGHT_MCP_EXTENSION_TOKEN` through the MCP process environment, never tool arguments. The proxy contains no machine-specific browser paths or tokens.
47
+
48
+ Tabs retain upstream numeric indexes and contexts retain upstream names. Operations in one executor run serially; different executors run concurrently. A sequence of selecting a tab and then clicking is not an atomic transaction: clients sharing an executor must coordinate such sequences.
49
+
50
+ The proxy forwards upstream tool schemas and results, adding required `instanceId`. The deliberate exception is `browser_close`: it stops the executor, so extension mode never forwards a browser-wide close command. Devtools, vision and PDF capabilities are enabled. Page-provided experimental WebMCP tools are disabled to keep discovery consistent across instances. Unsafe server-side JavaScript is upstream functionality, not a sandbox. Workspace restrictions are guardrails, not a security boundary.
51
+
52
+ ## Lifecycle and updates
53
+
54
+ - Discovery is cached in the adapter for five minutes. Cache hits do not start or retain a worker.
55
+ - Without live instances or active requests the worker exits after one minute. A future request starts a current worker.
56
+ - Each executor has one queue and one inactivity timer. Running and queued operations prevent idle shutdown.
57
+ - Closed IDs never silently recreate browser state. Start a new instance after expiry.
58
+ - Client response timeout does not prove execution ended. The proxy does not replay operations.
59
+ - Disconnecting the client closes owned executors. Windows launch executors use parent-owned, kill-on-close Job Objects and a startup gate. Extension executors are deliberately outside those Jobs to preserve the user's browser; the owned Node executor is stopped directly.
60
+ - Graceful shutdown is bounded by the stdio transport's termination sequence. Browser work can be interrupted on client disconnect or process failure. Idle and explicit stop normally drain queued work.
61
+ - Tool-list change notifications invalidate discovery. Cache is refreshed from the real upstream; no hardcoded browser tool catalog is shipped. Client support for live tool-list changes varies.
62
+
63
+ ## Development
64
+
65
+ ```sh
66
+ npm ci
67
+ node src/cli.js
68
+ npm run check
69
+ npm run release:prepare
70
+ ```
71
+
72
+ Direct source execution uses the local worker. npx execution from the npm cache uses the current published worker. Set `PW_PROXY_RUNNER=local` or `latest` explicitly to override. No source edit affects an already running worker; reconnect or let it expire first.
73
+
74
+ Environment: `PW_PROXY_DIAGNOSTICS=1` enables stderr lifecycle logs without tool arguments or credentials. `PW_PROXY_STARTUP_MS` and `PW_PROXY_REQUEST_MS` default to 180000; the latter applies to discovery, not the lifetime of running browser work. `PW_PROXY_DISCOVERY_CACHE_MS` defaults to 300000. `PW_PROXY_WORKER_IDLE_MS` defaults to 60000; 0 disables. Browser output defaults to `.tmp/playwright/` under the working directory. Explicit upstream file names follow upstream workspace rules.
75
+
76
+ MIT licensed. Uses the official [Playwright MCP](https://github.com/microsoft/playwright-mcp).
package/package.json CHANGED
@@ -1,6 +1 @@
1
- {
2
- "name": "mcp-playwright-proxy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {"name":"mcp-playwright-proxy","version":"0.1.0","description":"On-demand multi-instance Playwright MCP proxy with current workers and idle cleanup.","type":"module","license":"MIT","engines":{"node":">=22"},"bin":{"mcp-playwright-proxy":"src/cli.js"},"files":["src/","README.md","LICENSE"],"repository":{"type":"git","url":"git+https://github.com/kucharskill/mcp-playwright-proxy.git"},"homepage":"https://github.com/kucharskill/mcp-playwright-proxy#readme","bugs":{"url":"https://github.com/kucharskill/mcp-playwright-proxy/issues"},"scripts":{"test":"node --test test/*.test.js","check":"node scripts/check.mjs","release:prepare":"npm run check && node scripts/pack.mjs"},"publishConfig":{"access":"public"},"dependencies":{"@modelcontextprotocol/sdk":"1.32.2","cross-spawn":"7.0.6","koffi":"3.3.8","zod":"4.6.7"}}
package/src/adapter.js ADDED
@@ -0,0 +1,58 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { serve } from './server.js';
3
+ import { connect } from './connection.js';
4
+ import { resolveLatest } from './resolve.js';
5
+ import { metadata, milliseconds, log } from './meta.js';
6
+
7
+ export function runnerMode(env = process.env) {
8
+ const explicit = env.PW_PROXY_RUNNER;
9
+ if (explicit && !['local', 'latest'].includes(explicit)) throw new Error('PW_PROXY_RUNNER must be local or latest');
10
+ if (explicit) return explicit;
11
+ return /[\\/]_npx[\\/]/.test(fileURLToPath(import.meta.url)) && env.npm_command === 'exec' ? 'latest' : 'local';
12
+ }
13
+ export async function startAdapter() {
14
+ const mode = runnerMode();
15
+ let handle;
16
+ let current;
17
+ let starting;
18
+ let cached;
19
+ let loading;
20
+ let closed = false;
21
+ const invalidate = () => { cached = undefined; void handle?.server.sendToolListChanged().catch(() => {}); };
22
+ async function worker() {
23
+ if (closed) throw new Error('Adapter is closing');
24
+ if (current) return current;
25
+ if (!starting) starting = (async () => {
26
+ const resolved = mode === 'latest' ? await resolveLatest(metadata.name) : { entry: fileURLToPath(new URL('./cli.js', import.meta.url)), version: metadata.version };
27
+ if (closed) throw new Error('Adapter is closing');
28
+ let connection;
29
+ connection = await connect([resolved.entry, '--worker'], {
30
+ protect: false, // A worker may attach to a user-owned browser. Its launch executors own Jobs.
31
+ roots: () => handle.server.getClientCapabilities()?.roots ? handle.server.listRoots() : { roots: [] },
32
+ changed: invalidate,
33
+ disconnected: () => { if (current === connection) current = undefined; },
34
+ });
35
+ if (closed) { await connection.close(); throw new Error('Adapter is closing'); }
36
+ current = connection;
37
+ if (cached && cached.version !== resolved.version) invalidate();
38
+ log({ event: 'worker-started', mode, version: resolved.version });
39
+ return connection;
40
+ })().finally(() => { starting = undefined; });
41
+ return starting;
42
+ }
43
+ handle = await serve({
44
+ list: async () => {
45
+ if (cached && Date.now() < cached.expires) return cached.value;
46
+ loading ??= (async () => {
47
+ const connection = await worker();
48
+ const value = await connection.list();
49
+ cached = { value, version: connection.client.getServerVersion().version, expires: Date.now() + milliseconds('PW_PROXY_DISCOVERY_CACHE_MS', 300000) };
50
+ return value;
51
+ })().finally(() => { loading = undefined; });
52
+ return loading;
53
+ },
54
+ call: async params => (await worker()).call(params),
55
+ close: async () => { closed = true; await current?.close(); await starting?.catch(() => {}); },
56
+ rootsChanged: () => { void current?.client.sendRootsListChanged().catch(() => {}); },
57
+ });
58
+ }
package/src/cli.js ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { metadata } from './meta.js';
3
+ const args = process.argv.slice(2);
4
+ try {
5
+ if (args.length === 1 && ['--version', '-v'].includes(args[0])) console.log(metadata.version);
6
+ else if (args.length === 1 && ['--help', '-h'].includes(args[0])) console.log(`Usage: ${metadata.name} [mcp | --worker | --version | --help]\n\nMulti-instance Playwright MCP over stdio. Node.js 22+ and npm/npx are required.\nPW_PROXY_RUNNER=local|latest overrides worker selection.\nPW_PROXY_DIAGNOSTICS=1 enables metadata-only stderr logs.\nPLAYWRIGHT_MCP_EXTENSION_TOKEN is forwarded from the environment.\nSee README.md for instance options and lifecycle limits.`);
7
+ else if (args.length === 1 && args[0] === '--worker') await (await import('./worker.js')).startWorker();
8
+ else if (!args.length || (args.length === 1 && args[0] === 'mcp')) await (await import('./adapter.js')).startAdapter();
9
+ else throw new Error('Unknown arguments. Use --help.');
10
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
@@ -0,0 +1,43 @@
1
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
3
+ import { ListRootsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { createJob } from './job.js';
6
+ import { info, milliseconds } from './meta.js';
7
+
8
+ class OwnedTransport extends StdioClientTransport {
9
+ async start() {
10
+ this.job = this.protect ? await createJob() : undefined;
11
+ try {
12
+ await super.start();
13
+ this.job?.assign(this.pid);
14
+ await this.send({ jsonrpc: '2.0', method: 'proxy/gate' });
15
+ } catch (error) { await this.close(); throw error; }
16
+ }
17
+ async close() {
18
+ try { await super.close(); } finally { this.job?.close(); }
19
+ }
20
+ }
21
+
22
+ export async function connect(args, { cwd = process.cwd(), protect = true, roots, changed, disconnected, env = process.env } = {}) {
23
+ const transport = new OwnedTransport({
24
+ command: process.execPath, args: [fileURLToPath(new URL('./host.js', import.meta.url))],
25
+ cwd, env: { ...env, PW_PROXY_HOST: JSON.stringify({ args, cwd, protect }) }, stderr: 'inherit',
26
+ });
27
+ transport.protect = protect;
28
+ const client = new Client(info, { capabilities: { roots: { listChanged: true } } });
29
+ client.setRequestHandler(ListRootsRequestSchema, () => roots?.() ?? { roots: [] });
30
+ // Notifications are registered below using their protocol schemas.
31
+ const { ToolListChangedNotificationSchema } = await import('@modelcontextprotocol/sdk/types.js');
32
+ client.setNotificationHandler(ToolListChangedNotificationSchema, () => changed?.());
33
+ client.onclose = () => disconnected?.();
34
+ try { await client.connect(transport, { timeout: milliseconds('PW_PROXY_STARTUP_MS', 180000) }); }
35
+ catch (error) { await transport.close(); throw error; }
36
+ return {
37
+ client, pid: transport.pid,
38
+ list: () => client.listTools({}, { timeout: milliseconds('PW_PROXY_REQUEST_MS', 180000) }),
39
+ // No protocol timeout here: a client timeout must not release active execution.
40
+ call: params => client.callTool(params, undefined, { timeout: 2147483647, maxTotalTimeout: 2147483647 }),
41
+ close: () => client.close(),
42
+ };
43
+ }
package/src/host.js ADDED
@@ -0,0 +1,39 @@
1
+ // Only fixed Node entry points reach this host. Arguments never pass through a shell.
2
+ import spawn from 'cross-spawn';
3
+ const launch = JSON.parse(process.env.PW_PROXY_HOST);
4
+ delete process.env.PW_PROXY_HOST;
5
+ let buffer = Buffer.alloc(0);
6
+ let child;
7
+ let ending = false;
8
+ let timer;
9
+ function end() {
10
+ ending = true;
11
+ if (!child) return process.exit(0);
12
+ child.stdin.end();
13
+ timer ??= setTimeout(() => {
14
+ if (launch.protect && process.platform !== 'win32') { try { process.kill(-child.pid, 'SIGKILL'); } catch {} }
15
+ else child.kill('SIGKILL');
16
+ }, 3000);
17
+ }
18
+ process.stdin.on('data', chunk => {
19
+ if (child) { if (!ending) child.stdin.write(chunk); return; }
20
+ buffer = Buffer.concat([buffer, chunk]);
21
+ const newline = buffer.indexOf(10);
22
+ if (newline < 0) return;
23
+ const gate = JSON.parse(buffer.subarray(0, newline).toString());
24
+ if (gate.method !== 'proxy/gate') throw new Error('Missing process gate');
25
+ child = spawn(launch.command ?? process.execPath, launch.args, {
26
+ cwd: launch.cwd, env: process.env, stdio: ['pipe', 'pipe', 'inherit'], windowsHide: true,
27
+ detached: Boolean(launch.protect && process.platform !== 'win32'),
28
+ });
29
+ child.stdin.on('error', () => {});
30
+ child.stdout.pipe(process.stdout);
31
+ child.once('error', () => { console.error('Failed to start owned process'); process.exit(1); });
32
+ child.once('exit', code => { clearTimeout(timer); process.exit(code ?? 1); });
33
+ const rest = buffer.subarray(newline + 1);
34
+ buffer = null;
35
+ if (rest.length) child.stdin.write(rest);
36
+ });
37
+ process.stdin.once('end', end);
38
+ process.once('SIGTERM', end);
39
+ process.once('SIGINT', end);
@@ -0,0 +1,109 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { optionsSchema, upstreamArgs, withInstance, controls } from './options.js';
3
+ import { connect } from './connection.js';
4
+ import { resolveLatest } from './resolve.js';
5
+ import { log } from './meta.js';
6
+
7
+ export class Instances {
8
+ constructor({ resolve = () => resolveLatest('@playwright/mcp'), open = connect, cwd = process.cwd(), roots, changed, stateChanged = () => {} } = {}) {
9
+ Object.assign(this, { resolve, open, cwd, roots, changed, stateChanged });
10
+ this.items = new Map();
11
+ this.closed = false;
12
+ this.pending = 0;
13
+ }
14
+ async connection(options, disconnected) {
15
+ const resolved = await this.resolve();
16
+ if (this.closed) throw new Error('Worker is closing');
17
+ const connection = await this.open([resolved.entry, ...upstreamArgs(options, this.cwd)], { cwd: this.cwd, protect: options.mode !== 'extension', roots: this.roots, changed: this.changed, disconnected });
18
+ return { connection, version: resolved.version };
19
+ }
20
+ async manifest() {
21
+ const { connection, version } = await this.connection({ mode: 'launch', headless: true, isolated: true });
22
+ try {
23
+ const result = await connection.list();
24
+ this.catalogVersion = version;
25
+ return { tools: [...controls, ...result.tools.map(withInstance)] };
26
+ } finally { await connection.close(); }
27
+ }
28
+ async start(input) {
29
+ if (this.closed) throw new Error('Worker is closing');
30
+ const options = optionsSchema.parse(input);
31
+ const item = { instanceId: randomUUID(), state: 'starting', options, queue: Promise.resolve(), pending: 0 };
32
+ this.items.set(item.instanceId, item);
33
+ this.stateChanged();
34
+ try {
35
+ const { connection, version } = await this.connection(options, () => { if (item.state === 'open') void this.stop(item.instanceId, 'disconnected'); });
36
+ item.connection = connection;
37
+ item.version = version;
38
+ if (this.catalogVersion && this.catalogVersion !== version) this.changed?.();
39
+ if (this.closed || item.state !== 'starting') { await connection.close(); throw new Error('Instance closed during startup'); }
40
+ item.state = 'open';
41
+ this.arm(item);
42
+ log({ event: 'instance-started', instanceId: item.instanceId, mode: options.mode, version });
43
+ return this.describe(item);
44
+ } catch (error) {
45
+ item.state = 'closed'; item.reason = 'startup-failed'; this.stateChanged(); throw error;
46
+ }
47
+ }
48
+ describe(item) {
49
+ return { instanceId: item.instanceId, state: item.state, mode: item.options.mode, browser: item.options.browser ?? (item.options.executablePath ? 'custom' : item.options.mode === 'launch' ? 'msedge' : 'chrome'), version: item.version, pending: item.pending, expiresAt: item.expiresAt ?? null, reason: item.reason };
50
+ }
51
+ list() { return [...this.items.values()].map(item => this.describe(item)); }
52
+ hasLive() { return [...this.items.values()].some(item => item.state !== 'closed'); }
53
+ arm(item) {
54
+ clearTimeout(item.timer);
55
+ item.expiresAt = null;
56
+ if (item.state !== 'open' || item.pending || !item.options.idleTimeoutMs) return;
57
+ item.expiresAt = Date.now() + item.options.idleTimeoutMs;
58
+ item.timer = setTimeout(() => { void this.stop(item.instanceId, 'idle-expired'); }, item.options.idleTimeoutMs);
59
+ item.timer.unref();
60
+ }
61
+ call(name, args) {
62
+ const { instanceId, ...arguments_ } = args;
63
+ const item = this.items.get(instanceId);
64
+ if (!item || item.state !== 'open') throw new Error(`Instance is unavailable (${item?.reason ?? item?.state ?? 'unknown'}). Start a new instance.`);
65
+ item.pending++;
66
+ if (name === 'browser_close') item.state = 'closing';
67
+ this.arm(item);
68
+ const execution = item.queue.then(async () => {
69
+ // browser_close is interpreted as executor shutdown, including safe extension detach.
70
+ if (name === 'browser_close') return { content: [{ type: 'text', text: 'Instance closed.' }] };
71
+ return item.connection.call({ name, arguments: arguments_ });
72
+ });
73
+ item.queue = execution.catch(() => {});
74
+ return execution.finally(() => {
75
+ item.pending--;
76
+ if (name === 'browser_close') queueMicrotask(() => { void this.stop(instanceId, 'browser-close'); });
77
+ else this.arm(item);
78
+ });
79
+ }
80
+ stop(id, reason = 'explicit-stop') {
81
+ const item = this.items.get(id);
82
+ if (!item) throw new Error('Unknown instanceId');
83
+ if (item.stopPromise) return item.stopPromise;
84
+ if (item.state === 'closed') return Promise.resolve(this.describe(item));
85
+ item.state = 'closing'; clearTimeout(item.timer); item.expiresAt = null;
86
+ item.stopPromise = (async () => {
87
+ await item.queue;
88
+ try { await item.connection?.close(); }
89
+ finally {
90
+ item.state = 'closed'; item.reason = reason;
91
+ log({ event: 'instance-closed', instanceId: id, reason });
92
+ // Bound tombstones. IDs are never reused.
93
+ const dead = [...this.items.values()].filter(x => x.state === 'closed');
94
+ for (const old of dead.slice(0, Math.max(0, dead.length - 100))) this.items.delete(old.instanceId);
95
+ this.stateChanged();
96
+ }
97
+ return this.describe(item);
98
+ })();
99
+ return item.stopPromise;
100
+ }
101
+ async close() {
102
+ this.closed = true;
103
+ // On transport loss do not wait indefinitely for queued browser work.
104
+ await Promise.allSettled([...this.items.values()].map(async item => {
105
+ clearTimeout(item.timer); item.state = 'closing';
106
+ await item.connection?.close(); item.state = 'closed';
107
+ }));
108
+ }
109
+ }
package/src/job.js ADDED
@@ -0,0 +1,27 @@
1
+ // A parent-owned, non-inheritable handle protects a gated child before it can spawn.
2
+ export async function createJob() {
3
+ if (process.platform !== 'win32') return { assign() {}, close() {} };
4
+ const { default: koffi } = await import('koffi');
5
+ const kernel = koffi.load('kernel32.dll');
6
+ const create = kernel.func('void * __stdcall CreateJobObjectW(void *, const char16_t *)');
7
+ const set = kernel.func('bool __stdcall SetInformationJobObject(void *, int, void *, uint32_t)');
8
+ const open = kernel.func('void * __stdcall OpenProcess(uint32_t, bool, uint32_t)');
9
+ const assign = kernel.func('bool __stdcall AssignProcessToJobObject(void *, void *)');
10
+ const close = kernel.func('bool __stdcall CloseHandle(void *)');
11
+ const handle = create(null, null);
12
+ if (!handle) throw new Error('Cannot create Windows Job Object');
13
+ // JOBOBJECT_EXTENDED_LIMIT_INFORMATION, Windows x64/arm64 layout.
14
+ const limits = Buffer.alloc(process.arch === 'ia32' ? 112 : 144);
15
+ limits.writeUInt32LE(0x2000, 16); // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
16
+ if (!set(handle, 9, limits, limits.length)) { close(handle); throw new Error('Cannot configure Windows Job Object'); }
17
+ let closed = false;
18
+ return {
19
+ assign(pid) {
20
+ const processHandle = open(0x101, false, pid); // SET_QUOTA | TERMINATE
21
+ if (!processHandle) throw new Error('Cannot open owned child process');
22
+ try { if (!assign(handle, processHandle)) throw new Error('Cannot assign owned child to Windows Job Object'); }
23
+ finally { close(processHandle); }
24
+ },
25
+ close() { if (!closed) { closed = true; close(handle); } },
26
+ };
27
+ }
package/src/meta.js ADDED
@@ -0,0 +1,11 @@
1
+ import { readFileSync } from 'node:fs';
2
+ export const metadata = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
3
+ export const info = { name: metadata.name, version: metadata.version };
4
+ export function log(event) {
5
+ if (process.env.PW_PROXY_DIAGNOSTICS === '1') console.error(JSON.stringify(event));
6
+ }
7
+ export function milliseconds(name, fallback) {
8
+ const value = Number(process.env[name] ?? fallback);
9
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${name} must be a nonnegative integer`);
10
+ return value;
11
+ }
package/src/options.js ADDED
@@ -0,0 +1,39 @@
1
+ import { z } from 'zod';
2
+ export const optionsSchema = z.object({
3
+ mode: z.enum(['launch', 'extension']).default('launch'),
4
+ browser: z.enum(['msedge', 'chrome', 'firefox', 'webkit']).optional(),
5
+ headless: z.boolean().optional(),
6
+ isolated: z.boolean().optional(),
7
+ executablePath: z.string().min(1).optional(),
8
+ userDataDir: z.string().min(1).optional(),
9
+ profileDirName: z.string().min(1).optional(),
10
+ allowUnrestrictedFileAccess: z.boolean().default(false),
11
+ idleTimeoutMs: z.number().int().min(0).max(2147483647).default(1800000),
12
+ }).strict().superRefine((o, ctx) => {
13
+ if (o.mode === 'extension' && (o.headless !== undefined || o.isolated !== undefined)) ctx.addIssue({ code: 'custom', message: 'headless and isolated apply only to launch mode' });
14
+ if (o.mode === 'extension' && o.browser && !['chrome', 'msedge'].includes(o.browser)) ctx.addIssue({ code: 'custom', message: 'Extension requires a Chromium browser' });
15
+ if (o.isolated && o.userDataDir) ctx.addIssue({ code: 'custom', message: 'isolated and userDataDir are mutually exclusive' });
16
+ if (o.mode === 'launch' && o.profileDirName) ctx.addIssue({ code: 'custom', message: 'profileDirName applies only to extension mode' });
17
+ });
18
+ export function upstreamArgs(input, cwd) {
19
+ const o = optionsSchema.parse(input);
20
+ const args = ['--caps', 'devtools,vision,pdf', '--idle-timeout', '0', '--no-webmcp', '--output-dir', `${cwd}/.tmp/playwright`];
21
+ if (o.browser) args.push('--browser', o.browser);
22
+ else if (o.mode === 'launch' && !o.executablePath) args.push('--browser', 'msedge');
23
+ if (o.mode === 'extension') args.push('--extension');
24
+ if (o.headless) args.push('--headless');
25
+ if (o.isolated) args.push('--isolated');
26
+ for (const [key, flag] of [['executablePath', '--executable-path'], ['userDataDir', '--user-data-dir'], ['profileDirName', '--profile-dir-name']]) if (o[key]) args.push(flag, o[key]);
27
+ if (o.allowUnrestrictedFileAccess) args.push('--allow-unrestricted-file-access');
28
+ return args;
29
+ }
30
+ export const controls = [
31
+ { name: 'browser_instance_start', description: 'Start an independently configured Playwright MCP executor. Returns instanceId. Reuse that ID for browser operations. Extension mode attaches to an existing user browser.', inputSchema: z.toJSONSchema(optionsSchema, { unrepresentable: 'any', io: 'input' }) },
32
+ { name: 'browser_instance_list', description: 'List live and recently closed browser instances without extending their lifetime.', inputSchema: { type: 'object', properties: {}, additionalProperties: false } },
33
+ { name: 'browser_instance_stop', description: 'Close an instance after queued operations finish. Extension mode disconnects without closing the user browser.', inputSchema: { type: 'object', properties: { instanceId: { type: 'string' } }, required: ['instanceId'], additionalProperties: false } },
34
+ ];
35
+ export function withInstance(tool) {
36
+ const schema = tool.inputSchema;
37
+ if (schema.type !== 'object' || schema.properties?.instanceId) throw new Error(`Unsupported upstream schema: ${tool.name}`);
38
+ return { ...tool, inputSchema: { ...schema, properties: { ...schema.properties, instanceId: { type: 'string', description: 'ID returned by browser_instance_start.' } }, required: [...new Set([...(schema.required ?? []), 'instanceId'])] } };
39
+ }
@@ -0,0 +1,17 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { delimiter, dirname, join, resolve } from 'node:path';
3
+ const name = process.argv[2];
4
+ if (!['@playwright/mcp', 'mcp-playwright-proxy'].includes(name)) throw new Error('Unsupported package');
5
+ for (const bin of (process.env.PATH ?? process.env.Path ?? '').split(delimiter)) {
6
+ if (!bin || !/[\\/]node_modules[\\/]\.bin[\\/]?$/.test(bin)) continue;
7
+ const root = resolve(dirname(bin), name);
8
+ const file = join(root, 'package.json');
9
+ if (!existsSync(file)) continue;
10
+ const pkg = JSON.parse(readFileSync(file, 'utf8'));
11
+ if (pkg.name !== name) continue;
12
+ const entry = typeof pkg.bin === 'string' ? pkg.bin : Object.values(pkg.bin ?? {})[0];
13
+ if (!entry) continue;
14
+ console.log(JSON.stringify({ entry: resolve(root, entry), version: pkg.version }));
15
+ process.exit(0);
16
+ }
17
+ throw new Error('npm did not expose the requested package entry point');
package/src/resolve.js ADDED
@@ -0,0 +1,31 @@
1
+ import spawn from 'cross-spawn';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { createJob } from './job.js';
4
+ import { milliseconds } from './meta.js';
5
+ export async function resolveLatest(name) {
6
+ const job = await createJob();
7
+ return new Promise((resolve, reject) => {
8
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^npm_config_(package|call)$/i.test(key)));
9
+ const launch = { command: 'npx', protect: true, args: ['-y', '--prefer-online', `--package=${name}@latest`, '--', 'node', fileURLToPath(new URL('./resolve-entry.js', import.meta.url)), name] };
10
+ const child = spawn(process.execPath, [fileURLToPath(new URL('./host.js', import.meta.url))], { env: { ...env, PW_PROXY_HOST: JSON.stringify(launch) }, windowsHide: true, stdio: ['pipe', 'pipe', 'inherit'] });
11
+ let output = '';
12
+ let settled = false;
13
+ const finish = (error, value) => {
14
+ if (settled) return;
15
+ settled = true;
16
+ clearTimeout(timer);
17
+ job.close();
18
+ error ? reject(error) : resolve(value);
19
+ };
20
+ const timer = setTimeout(() => { child.kill('SIGKILL'); finish(new Error(`Timed out resolving ${name}`)); }, milliseconds('PW_PROXY_STARTUP_MS', 180000));
21
+ child.stdin.on('error', error => finish(error));
22
+ child.once('spawn', () => { try { job.assign(child.pid); child.stdin.write(JSON.stringify({ method: 'proxy/gate' }) + '\n'); } catch (error) { child.kill(); finish(error); } });
23
+ child.once('error', error => finish(error));
24
+ child.stdout.on('data', chunk => { output += chunk; if (output.length > 65536) { child.kill(); finish(new Error('Resolver output too large')); } });
25
+ child.once('close', code => {
26
+ if (code !== 0) return finish(new Error(`npm could not resolve ${name} (exit ${code})`));
27
+ try { const value = JSON.parse(output); if (!value.entry || !value.version) throw new Error('Invalid resolver output'); finish(null, value); }
28
+ catch (error) { finish(error); }
29
+ });
30
+ });
31
+ }
package/src/server.js ADDED
@@ -0,0 +1,25 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
+ import { info } from './meta.js';
5
+ export const textResult = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }] });
6
+ export async function serve({ list, call, close, rootsChanged }) {
7
+ const server = new Server(info, { capabilities: { tools: { listChanged: true } } });
8
+ server.setRequestHandler(ListToolsRequestSchema, list);
9
+ server.setRequestHandler(CallToolRequestSchema, async request => {
10
+ try { return await call(request.params); }
11
+ catch (error) { return { isError: true, content: [{ type: 'text', text: error.message }] }; }
12
+ });
13
+ if (rootsChanged) {
14
+ const { RootsListChangedNotificationSchema } = await import('@modelcontextprotocol/sdk/types.js');
15
+ server.setNotificationHandler(RootsListChangedNotificationSchema, rootsChanged);
16
+ }
17
+ let closing;
18
+ const shutdown = () => closing ??= (async () => { await close(); await server.close(); })();
19
+ const transport = new StdioServerTransport();
20
+ transport.onclose = () => { void shutdown(); };
21
+ process.stdin.once('end', () => { void shutdown(); });
22
+ for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { void shutdown(); });
23
+ await server.connect(transport);
24
+ return { server, shutdown };
25
+ }
package/src/worker.js ADDED
@@ -0,0 +1,55 @@
1
+ import { Instances } from './instances.js';
2
+ import { serve, textResult } from './server.js';
3
+ import { milliseconds, log } from './meta.js';
4
+ import { pathToFileURL } from 'node:url';
5
+ export async function startWorker() {
6
+ let handle;
7
+ let manifest;
8
+ let loading;
9
+ let timer;
10
+ let active = 0;
11
+ let closing = false;
12
+ const retention = milliseconds('PW_PROXY_WORKER_IDLE_MS', 60000);
13
+ const arm = () => {
14
+ clearTimeout(timer);
15
+ if (!closing && !active && !instances.hasLive() && retention) timer = setTimeout(() => {
16
+ log({ event: 'worker-idle-expired' });
17
+ void handle.shutdown();
18
+ }, retention);
19
+ };
20
+ const changed = () => {
21
+ manifest = undefined;
22
+ void handle?.server.sendToolListChanged().catch(() => {});
23
+ };
24
+ const roots = async () => {
25
+ if (!handle.server.getClientCapabilities()?.roots) return { roots: [{ uri: pathToFileURL(process.cwd()).href, name: 'workspace' }] };
26
+ return handle.server.listRoots();
27
+ };
28
+ const instances = new Instances({ roots, changed, stateChanged: arm });
29
+ const during = async operation => {
30
+ active++; clearTimeout(timer);
31
+ try { return await operation(); }
32
+ finally { active--; arm(); }
33
+ };
34
+ handle = await serve({
35
+ list: () => during(async () => {
36
+ if (manifest) return manifest;
37
+ loading ??= instances.manifest().then(value => manifest = value).finally(() => loading = undefined);
38
+ return loading;
39
+ }),
40
+ call: params => during(async () => {
41
+ const args = params.arguments ?? {};
42
+ switch (params.name) {
43
+ case 'browser_instance_start': return textResult(await instances.start(args));
44
+ case 'browser_instance_list': return textResult(instances.list());
45
+ case 'browser_instance_stop': return textResult(await instances.stop(args.instanceId));
46
+ default: return instances.call(params.name, args);
47
+ }
48
+ }),
49
+ close: async () => { closing = true; clearTimeout(timer); await instances.close(); },
50
+ rootsChanged: () => {
51
+ for (const item of instances.items.values()) void item.connection?.client.sendRootsListChanged().catch(() => {});
52
+ },
53
+ });
54
+ arm();
55
+ }