-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplaywright-edge-mcp.js
More file actions
280 lines (250 loc) · 8.84 KB
/
playwright-edge-mcp.js
File metadata and controls
280 lines (250 loc) · 8.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const { initTracing, runInSpan, recordException, shutdownTracing } = require('./tracing');
const defaultRuntimeRoot = process.env.LOCALAPPDATA
? path.join(process.env.LOCALAPPDATA, 'PlaywrightMCP')
: path.join(process.cwd(), '.playwright-mcp');
const userDataDir =
process.env.PLAYWRIGHT_MCP_USER_DATA_DIR || path.join(defaultRuntimeRoot, 'edge-profile');
const outputDir = process.env.PLAYWRIGHT_MCP_OUTPUT_DIR || path.join(defaultRuntimeRoot, 'output');
const initPageScript = path.join(process.cwd(), 'scripts', 'mcp-init-page.js');
const ownerFilePath =
process.env.PLAYWRIGHT_MCP_OWNER_FILE || path.join(defaultRuntimeRoot, 'active-owner.txt');
const owner = (() => {
const envOwner = normalizeOwner(process.env.PLAYWRIGHT_MCP_OWNER || '');
if (envOwner) return envOwner;
try {
if (fs.existsSync(ownerFilePath)) {
const fileOwner = normalizeOwner(fs.readFileSync(ownerFilePath, 'utf8'));
if (fileOwner) return fileOwner;
}
} catch (_) {
// best effort
}
return 'vscode';
})();
const explicitActiveOwner = String(process.env.PLAYWRIGHT_MCP_ACTIVE_OWNER || '').trim().toLowerCase();
const lockFilePath = path.join(userDataDir, '.mcp-owner-lock.json');
const extraArgs = process.argv.slice(2);
let child = null;
initTracing('agent-live-web-vscode-mcp').catch(() => {
// best effort; never block MCP startup
});
function toBool(value, fallback) {
if (value === undefined || value === null || value === '') return fallback;
const normalized = String(value).trim().toLowerCase();
return normalized === '1' || normalized === 'true' || normalized === 'yes' || normalized === 'on';
}
function normalizeOwner(value) {
return String(value || '').trim().toLowerCase();
}
function info(message) {
process.stderr.write(`${message}\n`);
}
function tryReadJson(filePath) {
try {
const raw = fs.readFileSync(filePath, 'utf8');
return JSON.parse(raw);
} catch (_) {
return null;
}
}
function isProcessAlive(pid) {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (_) {
return false;
}
}
function getActiveOwner() {
if (explicitActiveOwner) return explicitActiveOwner;
try {
if (!fs.existsSync(ownerFilePath)) return '';
return normalizeOwner(fs.readFileSync(ownerFilePath, 'utf8'));
} catch (_) {
return '';
}
}
function releaseOwnerLock() {
const lock = tryReadJson(lockFilePath);
if (!lock || lock.pid !== process.pid) return;
try {
fs.unlinkSync(lockFilePath);
} catch (_) {
// best effort
}
}
function acquireOwnerLock() {
const existing = tryReadJson(lockFilePath);
if (existing && isProcessAlive(existing.pid)) {
return {
ok: false,
reason: `Profile is locked by owner='${existing.owner || 'unknown'}' pid=${existing.pid}. Stop that session first.`
};
}
const lockPayload = {
owner,
pid: process.pid,
startedAt: new Date().toISOString(),
profile: userDataDir,
workspace: process.cwd()
};
try {
fs.writeFileSync(lockFilePath, JSON.stringify(lockPayload, null, 2), 'utf8');
return { ok: true, lock: lockPayload };
} catch (error) {
return { ok: false, reason: `Failed to write owner lock: ${error.message}` };
}
}
const persistProfile = toBool(process.env.PLAYWRIGHT_MCP_PERSIST_PROFILE, true);
const saveSession = toBool(process.env.PLAYWRIGHT_MCP_SAVE_SESSION, false);
const saveTrace = toBool(process.env.PLAYWRIGHT_MCP_SAVE_TRACE, false);
const forceOwner = toBool(process.env.PLAYWRIGHT_MCP_FORCE_OWNER, true);
const outputMode = process.env.PLAYWRIGHT_MCP_OUTPUT_MODE || 'stdout';
const snapshotMode = process.env.PLAYWRIGHT_MCP_SNAPSHOT_MODE || 'incremental';
const consoleLevel = process.env.PLAYWRIGHT_MCP_CONSOLE_LEVEL || 'error';
const timeoutActionMs = String(process.env.PLAYWRIGHT_MCP_TIMEOUT_ACTION_MS || '18000').trim();
const timeoutNavigationMs = String(process.env.PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION_MS || '90000').trim();
const sharedBrowserContext = toBool(process.env.PLAYWRIGHT_MCP_SHARED_BROWSER_CONTEXT, true);
const allowedHosts = process.env.PLAYWRIGHT_MCP_ALLOWED_HOSTS || '';
const allowedOrigins = process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS || '';
const blockedOrigins = process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS || '';
const blockServiceWorkers = toBool(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS, false);
const cdpEndpoint = String(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT || '').trim();
fs.mkdirSync(outputDir, { recursive: true });
if (persistProfile && !cdpEndpoint) {
fs.mkdirSync(userDataDir, { recursive: true });
}
fs.mkdirSync(path.dirname(ownerFilePath), { recursive: true });
const activeOwner = getActiveOwner();
if (activeOwner && owner && owner !== activeOwner) {
if (!forceOwner) {
info(`[MCP] Owner blocked. Active owner is '${activeOwner}', current owner is '${owner}'. Exiting.`);
process.exit(2);
}
info(`[MCP] Owner override: active owner '${activeOwner}' will be replaced with '${owner}' if lock is available.`);
}
const lockState = acquireOwnerLock();
if (!lockState.ok) {
info(`[MCP] ${lockState.reason}`);
process.exit(3);
}
try {
if (owner) {
fs.writeFileSync(ownerFilePath, `${owner}\n`, 'utf8');
}
} catch (_) {
// best effort
}
const baseArgs = [
'playwright',
'run-mcp-server',
'--browser',
'msedge',
'--output-dir',
outputDir,
'--output-mode',
outputMode,
'--console-level',
consoleLevel,
'--snapshot-mode',
snapshotMode,
'--timeout-action',
timeoutActionMs,
'--timeout-navigation',
timeoutNavigationMs,
'--caps',
'vision,pdf'
];
if (sharedBrowserContext) {
baseArgs.push('--shared-browser-context');
}
if (cdpEndpoint) {
baseArgs.push('--cdp-endpoint', cdpEndpoint);
} else if (persistProfile) {
baseArgs.push('--user-data-dir', userDataDir);
} else {
baseArgs.push('--isolated');
}
if (saveSession) baseArgs.push('--save-session');
if (saveTrace) baseArgs.push('--save-trace');
if (allowedHosts.trim()) baseArgs.push('--allowed-hosts', allowedHosts.trim());
if (allowedOrigins.trim()) baseArgs.push('--allowed-origins', allowedOrigins.trim());
if (blockedOrigins.trim()) baseArgs.push('--blocked-origins', blockedOrigins.trim());
if (blockServiceWorkers) baseArgs.push('--block-service-workers');
if (fs.existsSync(initPageScript)) {
baseArgs.push('--init-page', initPageScript);
}
const isWindows = process.platform === 'win32';
const command = isWindows ? (process.env.ComSpec || 'cmd.exe') : 'npx';
const commandArgs = isWindows
? ['/d', '/s', '/c', 'npx', ...baseArgs, ...extraArgs]
: [...baseArgs, ...extraArgs];
info(
persistProfile
? `[MCP] Starting Playwright MCP server (playwright-edge) with local Edge profile: ${userDataDir}`
: '[MCP] Starting Playwright MCP server (playwright-edge) in isolated profile mode'
);
info(`[MCP] Profile mode: ${persistProfile ? 'persistent' : 'isolated'}`);
info(`[MCP] Artifact mode: saveSession=${saveSession}, saveTrace=${saveTrace}, outputDir=${outputDir}`);
info(`[MCP] Runtime mode: outputMode=${outputMode}, snapshotMode=${snapshotMode}, consoleLevel=${consoleLevel}`);
info(`[MCP] Timeouts: action=${timeoutActionMs}ms, navigation=${timeoutNavigationMs}ms`);
info(`[MCP] Shared browser context: ${sharedBrowserContext}`);
if (cdpEndpoint) info(`[MCP] CDP endpoint: ${cdpEndpoint}`);
info(`[MCP] Owner: ${owner} | Active owner: ${activeOwner || '(unset)'}`);
info(`[MCP] Owner lock: ${lockFilePath}`);
if (allowedHosts.trim()) info(`[MCP] Network allow hosts: ${allowedHosts.trim()}`);
if (allowedOrigins.trim()) info(`[MCP] Network allow origins: ${allowedOrigins.trim()}`);
if (blockedOrigins.trim()) info(`[MCP] Network block origins: ${blockedOrigins.trim()}`);
if (blockServiceWorkers) info('[MCP] Network: service workers blocked');
info(`[MCP] Init page script: ${initPageScript}`);
info('[MCP] Press Ctrl+C to stop.');
child = spawn(command, commandArgs, {
stdio: 'inherit',
shell: false
});
runInSpan(
'mcp.server.launch',
{
'app.mcp.owner': owner || 'unknown',
'app.mcp.profile_persistent': persistProfile,
'app.mcp.shared_context': sharedBrowserContext
},
async (span) => {
span.addEvent('mcp_child_spawned', { pid: child.pid || 0 });
}
).catch(() => {
// best effort
});
child.on('error', (error) => {
runInSpan('mcp.server.error', {}, async (span) => {
recordException(span, error);
}).catch(() => {
// best effort
});
releaseOwnerLock();
console.error(`[MCP] Failed to start server: ${error.message}`);
process.exit(1);
});
child.on('exit', (code) => {
releaseOwnerLock();
shutdownTracing().catch(() => {
// best effort
});
process.exit(code === null ? 1 : code);
});
process.on('SIGINT', () => {
releaseOwnerLock();
});
process.on('SIGTERM', () => {
releaseOwnerLock();
});
process.on('exit', () => {
releaseOwnerLock();
shutdownTracing().catch(() => {
// best effort
});
});