@playwright/mcp 0.0.36 → 0.0.37-alpha-2025-09-09
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/README.md +82 -47
- package/cli.js +7 -1
- package/config.d.ts +24 -0
- package/index.d.ts +1 -1
- package/index.js +2 -2
- package/package.json +14 -40
- package/lib/browserContextFactory.js +0 -211
- package/lib/browserServerBackend.js +0 -77
- package/lib/config.js +0 -246
- package/lib/context.js +0 -226
- package/lib/extension/cdpRelay.js +0 -358
- package/lib/extension/extensionContextFactory.js +0 -56
- package/lib/extension/protocol.js +0 -18
- package/lib/index.js +0 -40
- package/lib/loop/loop.js +0 -69
- package/lib/loop/loopClaude.js +0 -152
- package/lib/loop/loopOpenAI.js +0 -141
- package/lib/loop/main.js +0 -60
- package/lib/loopTools/context.js +0 -67
- package/lib/loopTools/main.js +0 -54
- package/lib/loopTools/perform.js +0 -32
- package/lib/loopTools/snapshot.js +0 -29
- package/lib/loopTools/tool.js +0 -18
- package/lib/mcp/http.js +0 -135
- package/lib/mcp/inProcessTransport.js +0 -72
- package/lib/mcp/manualPromise.js +0 -111
- package/lib/mcp/mdb.js +0 -198
- package/lib/mcp/proxyBackend.js +0 -104
- package/lib/mcp/server.js +0 -123
- package/lib/mcp/tool.js +0 -32
- package/lib/program.js +0 -132
- package/lib/response.js +0 -165
- package/lib/sessionLog.js +0 -121
- package/lib/tab.js +0 -249
- package/lib/tools/common.js +0 -55
- package/lib/tools/console.js +0 -33
- package/lib/tools/dialogs.js +0 -47
- package/lib/tools/evaluate.js +0 -53
- package/lib/tools/files.js +0 -44
- package/lib/tools/form.js +0 -57
- package/lib/tools/install.js +0 -53
- package/lib/tools/keyboard.js +0 -78
- package/lib/tools/mouse.js +0 -99
- package/lib/tools/navigate.js +0 -54
- package/lib/tools/network.js +0 -41
- package/lib/tools/pdf.js +0 -40
- package/lib/tools/screenshot.js +0 -79
- package/lib/tools/snapshot.js +0 -139
- package/lib/tools/tabs.js +0 -59
- package/lib/tools/tool.js +0 -33
- package/lib/tools/utils.js +0 -74
- package/lib/tools/verify.js +0 -137
- package/lib/tools/wait.js +0 -55
- package/lib/tools.js +0 -54
- package/lib/utils/codegen.js +0 -49
- package/lib/utils/fileUtils.js +0 -36
- package/lib/utils/guid.js +0 -22
- package/lib/utils/log.js +0 -21
- package/lib/utils/package.js +0 -20
- package/lib/vscode/host.js +0 -128
- package/lib/vscode/main.js +0 -62
|
@@ -1,358 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Copyright (c) Microsoft Corporation.
|
|
3
|
-
*
|
|
4
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
* you may not use this file except in compliance with the License.
|
|
6
|
-
* You may obtain a copy of the License at
|
|
7
|
-
*
|
|
8
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
*
|
|
10
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
* See the License for the specific language governing permissions and
|
|
14
|
-
* limitations under the License.
|
|
15
|
-
*/
|
|
16
|
-
/**
|
|
17
|
-
* WebSocket server that bridges Playwright MCP and Chrome Extension
|
|
18
|
-
*
|
|
19
|
-
* Endpoints:
|
|
20
|
-
* - /cdp/guid - Full CDP interface for Playwright MCP
|
|
21
|
-
* - /extension/guid - Extension connection for chrome.debugger forwarding
|
|
22
|
-
*/
|
|
23
|
-
import { spawn } from 'child_process';
|
|
24
|
-
import debug from 'debug';
|
|
25
|
-
import { WebSocket, WebSocketServer } from 'ws';
|
|
26
|
-
import { httpAddressToString } from '../mcp/http.js';
|
|
27
|
-
import { logUnhandledError } from '../utils/log.js';
|
|
28
|
-
import { ManualPromise } from '../mcp/manualPromise.js';
|
|
29
|
-
import * as protocol from './protocol.js';
|
|
30
|
-
// @ts-ignore
|
|
31
|
-
const { registry } = await import('playwright-core/lib/server/registry/index');
|
|
32
|
-
const debugLogger = debug('pw:mcp:relay');
|
|
33
|
-
export class CDPRelayServer {
|
|
34
|
-
_wsHost;
|
|
35
|
-
_browserChannel;
|
|
36
|
-
_userDataDir;
|
|
37
|
-
_executablePath;
|
|
38
|
-
_cdpPath;
|
|
39
|
-
_extensionPath;
|
|
40
|
-
_wss;
|
|
41
|
-
_playwrightConnection = null;
|
|
42
|
-
_extensionConnection = null;
|
|
43
|
-
_connectedTabInfo;
|
|
44
|
-
_nextSessionId = 1;
|
|
45
|
-
_extensionConnectionPromise;
|
|
46
|
-
constructor(server, browserChannel, userDataDir, executablePath) {
|
|
47
|
-
this._wsHost = httpAddressToString(server.address()).replace(/^http/, 'ws');
|
|
48
|
-
this._browserChannel = browserChannel;
|
|
49
|
-
this._userDataDir = userDataDir;
|
|
50
|
-
this._executablePath = executablePath;
|
|
51
|
-
const uuid = crypto.randomUUID();
|
|
52
|
-
this._cdpPath = `/cdp/${uuid}`;
|
|
53
|
-
this._extensionPath = `/extension/${uuid}`;
|
|
54
|
-
this._resetExtensionConnection();
|
|
55
|
-
this._wss = new WebSocketServer({ server });
|
|
56
|
-
this._wss.on('connection', this._onConnection.bind(this));
|
|
57
|
-
}
|
|
58
|
-
cdpEndpoint() {
|
|
59
|
-
return `${this._wsHost}${this._cdpPath}`;
|
|
60
|
-
}
|
|
61
|
-
extensionEndpoint() {
|
|
62
|
-
return `${this._wsHost}${this._extensionPath}`;
|
|
63
|
-
}
|
|
64
|
-
async ensureExtensionConnectionForMCPContext(clientInfo, abortSignal, toolName) {
|
|
65
|
-
debugLogger('Ensuring extension connection for MCP context');
|
|
66
|
-
if (this._extensionConnection)
|
|
67
|
-
return;
|
|
68
|
-
this._connectBrowser(clientInfo, toolName);
|
|
69
|
-
debugLogger('Waiting for incoming extension connection');
|
|
70
|
-
await Promise.race([
|
|
71
|
-
this._extensionConnectionPromise,
|
|
72
|
-
new Promise((_, reject) => setTimeout(() => {
|
|
73
|
-
reject(new Error(`Extension connection timeout. Make sure the "Playwright MCP Bridge" extension is installed. See https://github.com/microsoft/playwright-mcp/blob/main/extension/README.md for installation instructions.`));
|
|
74
|
-
}, process.env.PWMCP_TEST_CONNECTION_TIMEOUT ? parseInt(process.env.PWMCP_TEST_CONNECTION_TIMEOUT, 10) : 5_000)),
|
|
75
|
-
new Promise((_, reject) => abortSignal.addEventListener('abort', reject))
|
|
76
|
-
]);
|
|
77
|
-
debugLogger('Extension connection established');
|
|
78
|
-
}
|
|
79
|
-
_connectBrowser(clientInfo, toolName) {
|
|
80
|
-
const mcpRelayEndpoint = `${this._wsHost}${this._extensionPath}`;
|
|
81
|
-
// Need to specify "key" in the manifest.json to make the id stable when loading from file.
|
|
82
|
-
const url = new URL('chrome-extension://jakfalbnbhgkpmoaakfflhflbfpkailf/connect.html');
|
|
83
|
-
url.searchParams.set('mcpRelayUrl', mcpRelayEndpoint);
|
|
84
|
-
const client = {
|
|
85
|
-
name: clientInfo.name,
|
|
86
|
-
version: clientInfo.version,
|
|
87
|
-
};
|
|
88
|
-
url.searchParams.set('client', JSON.stringify(client));
|
|
89
|
-
url.searchParams.set('protocolVersion', process.env.PWMCP_TEST_PROTOCOL_VERSION ?? protocol.VERSION.toString());
|
|
90
|
-
if (toolName)
|
|
91
|
-
url.searchParams.set('newTab', String(toolName === 'browser_navigate'));
|
|
92
|
-
const href = url.toString();
|
|
93
|
-
let executablePath = this._executablePath;
|
|
94
|
-
if (!executablePath) {
|
|
95
|
-
const executableInfo = registry.findExecutable(this._browserChannel);
|
|
96
|
-
if (!executableInfo)
|
|
97
|
-
throw new Error(`Unsupported channel: "${this._browserChannel}"`);
|
|
98
|
-
executablePath = executableInfo.executablePath();
|
|
99
|
-
if (!executablePath)
|
|
100
|
-
throw new Error(`"${this._browserChannel}" executable not found. Make sure it is installed at a standard location.`);
|
|
101
|
-
}
|
|
102
|
-
const args = [];
|
|
103
|
-
if (this._userDataDir)
|
|
104
|
-
args.push(`--user-data-dir=${this._userDataDir}`);
|
|
105
|
-
args.push(href);
|
|
106
|
-
spawn(executablePath, args, {
|
|
107
|
-
windowsHide: true,
|
|
108
|
-
detached: true,
|
|
109
|
-
shell: false,
|
|
110
|
-
stdio: 'ignore',
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
stop() {
|
|
114
|
-
this.closeConnections('Server stopped');
|
|
115
|
-
this._wss.close();
|
|
116
|
-
}
|
|
117
|
-
closeConnections(reason) {
|
|
118
|
-
this._closePlaywrightConnection(reason);
|
|
119
|
-
this._closeExtensionConnection(reason);
|
|
120
|
-
}
|
|
121
|
-
_onConnection(ws, request) {
|
|
122
|
-
const url = new URL(`http://localhost${request.url}`);
|
|
123
|
-
debugLogger(`New connection to ${url.pathname}`);
|
|
124
|
-
if (url.pathname === this._cdpPath) {
|
|
125
|
-
this._handlePlaywrightConnection(ws);
|
|
126
|
-
}
|
|
127
|
-
else if (url.pathname === this._extensionPath) {
|
|
128
|
-
this._handleExtensionConnection(ws);
|
|
129
|
-
}
|
|
130
|
-
else {
|
|
131
|
-
debugLogger(`Invalid path: ${url.pathname}`);
|
|
132
|
-
ws.close(4004, 'Invalid path');
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
_handlePlaywrightConnection(ws) {
|
|
136
|
-
if (this._playwrightConnection) {
|
|
137
|
-
debugLogger('Rejecting second Playwright connection');
|
|
138
|
-
ws.close(1000, 'Another CDP client already connected');
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
this._playwrightConnection = ws;
|
|
142
|
-
ws.on('message', async (data) => {
|
|
143
|
-
try {
|
|
144
|
-
const message = JSON.parse(data.toString());
|
|
145
|
-
await this._handlePlaywrightMessage(message);
|
|
146
|
-
}
|
|
147
|
-
catch (error) {
|
|
148
|
-
debugLogger(`Error while handling Playwright message\n${data.toString()}\n`, error);
|
|
149
|
-
}
|
|
150
|
-
});
|
|
151
|
-
ws.on('close', () => {
|
|
152
|
-
if (this._playwrightConnection !== ws)
|
|
153
|
-
return;
|
|
154
|
-
this._playwrightConnection = null;
|
|
155
|
-
this._closeExtensionConnection('Playwright client disconnected');
|
|
156
|
-
debugLogger('Playwright WebSocket closed');
|
|
157
|
-
});
|
|
158
|
-
ws.on('error', error => {
|
|
159
|
-
debugLogger('Playwright WebSocket error:', error);
|
|
160
|
-
});
|
|
161
|
-
debugLogger('Playwright MCP connected');
|
|
162
|
-
}
|
|
163
|
-
_closeExtensionConnection(reason) {
|
|
164
|
-
this._extensionConnection?.close(reason);
|
|
165
|
-
this._extensionConnectionPromise.reject(new Error(reason));
|
|
166
|
-
this._resetExtensionConnection();
|
|
167
|
-
}
|
|
168
|
-
_resetExtensionConnection() {
|
|
169
|
-
this._connectedTabInfo = undefined;
|
|
170
|
-
this._extensionConnection = null;
|
|
171
|
-
this._extensionConnectionPromise = new ManualPromise();
|
|
172
|
-
void this._extensionConnectionPromise.catch(logUnhandledError);
|
|
173
|
-
}
|
|
174
|
-
_closePlaywrightConnection(reason) {
|
|
175
|
-
if (this._playwrightConnection?.readyState === WebSocket.OPEN)
|
|
176
|
-
this._playwrightConnection.close(1000, reason);
|
|
177
|
-
this._playwrightConnection = null;
|
|
178
|
-
}
|
|
179
|
-
_handleExtensionConnection(ws) {
|
|
180
|
-
if (this._extensionConnection) {
|
|
181
|
-
ws.close(1000, 'Another extension connection already established');
|
|
182
|
-
return;
|
|
183
|
-
}
|
|
184
|
-
this._extensionConnection = new ExtensionConnection(ws);
|
|
185
|
-
this._extensionConnection.onclose = (c, reason) => {
|
|
186
|
-
debugLogger('Extension WebSocket closed:', reason, c === this._extensionConnection);
|
|
187
|
-
if (this._extensionConnection !== c)
|
|
188
|
-
return;
|
|
189
|
-
this._resetExtensionConnection();
|
|
190
|
-
this._closePlaywrightConnection(`Extension disconnected: ${reason}`);
|
|
191
|
-
};
|
|
192
|
-
this._extensionConnection.onmessage = this._handleExtensionMessage.bind(this);
|
|
193
|
-
this._extensionConnectionPromise.resolve();
|
|
194
|
-
}
|
|
195
|
-
_handleExtensionMessage(method, params) {
|
|
196
|
-
switch (method) {
|
|
197
|
-
case 'forwardCDPEvent':
|
|
198
|
-
const sessionId = params.sessionId || this._connectedTabInfo?.sessionId;
|
|
199
|
-
this._sendToPlaywright({
|
|
200
|
-
sessionId,
|
|
201
|
-
method: params.method,
|
|
202
|
-
params: params.params
|
|
203
|
-
});
|
|
204
|
-
break;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
async _handlePlaywrightMessage(message) {
|
|
208
|
-
debugLogger('← Playwright:', `${message.method} (id=${message.id})`);
|
|
209
|
-
const { id, sessionId, method, params } = message;
|
|
210
|
-
try {
|
|
211
|
-
const result = await this._handleCDPCommand(method, params, sessionId);
|
|
212
|
-
this._sendToPlaywright({ id, sessionId, result });
|
|
213
|
-
}
|
|
214
|
-
catch (e) {
|
|
215
|
-
debugLogger('Error in the extension:', e);
|
|
216
|
-
this._sendToPlaywright({
|
|
217
|
-
id,
|
|
218
|
-
sessionId,
|
|
219
|
-
error: { message: e.message }
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
async _handleCDPCommand(method, params, sessionId) {
|
|
224
|
-
switch (method) {
|
|
225
|
-
case 'Browser.getVersion': {
|
|
226
|
-
return {
|
|
227
|
-
protocolVersion: '1.3',
|
|
228
|
-
product: 'Chrome/Extension-Bridge',
|
|
229
|
-
userAgent: 'CDP-Bridge-Server/1.0.0',
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
case 'Browser.setDownloadBehavior': {
|
|
233
|
-
return {};
|
|
234
|
-
}
|
|
235
|
-
case 'Target.setAutoAttach': {
|
|
236
|
-
// Forward child session handling.
|
|
237
|
-
if (sessionId)
|
|
238
|
-
break;
|
|
239
|
-
// Simulate auto-attach behavior with real target info
|
|
240
|
-
const { targetInfo } = await this._extensionConnection.send('attachToTab', {});
|
|
241
|
-
this._connectedTabInfo = {
|
|
242
|
-
targetInfo,
|
|
243
|
-
sessionId: `pw-tab-${this._nextSessionId++}`,
|
|
244
|
-
};
|
|
245
|
-
debugLogger('Simulating auto-attach');
|
|
246
|
-
this._sendToPlaywright({
|
|
247
|
-
method: 'Target.attachedToTarget',
|
|
248
|
-
params: {
|
|
249
|
-
sessionId: this._connectedTabInfo.sessionId,
|
|
250
|
-
targetInfo: {
|
|
251
|
-
...this._connectedTabInfo.targetInfo,
|
|
252
|
-
attached: true,
|
|
253
|
-
},
|
|
254
|
-
waitingForDebugger: false
|
|
255
|
-
}
|
|
256
|
-
});
|
|
257
|
-
return {};
|
|
258
|
-
}
|
|
259
|
-
case 'Target.getTargetInfo': {
|
|
260
|
-
return this._connectedTabInfo?.targetInfo;
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
return await this._forwardToExtension(method, params, sessionId);
|
|
264
|
-
}
|
|
265
|
-
async _forwardToExtension(method, params, sessionId) {
|
|
266
|
-
if (!this._extensionConnection)
|
|
267
|
-
throw new Error('Extension not connected');
|
|
268
|
-
// Top level sessionId is only passed between the relay and the client.
|
|
269
|
-
if (this._connectedTabInfo?.sessionId === sessionId)
|
|
270
|
-
sessionId = undefined;
|
|
271
|
-
return await this._extensionConnection.send('forwardCDPCommand', { sessionId, method, params });
|
|
272
|
-
}
|
|
273
|
-
_sendToPlaywright(message) {
|
|
274
|
-
debugLogger('→ Playwright:', `${message.method ?? `response(id=${message.id})`}`);
|
|
275
|
-
this._playwrightConnection?.send(JSON.stringify(message));
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
class ExtensionConnection {
|
|
279
|
-
_ws;
|
|
280
|
-
_callbacks = new Map();
|
|
281
|
-
_lastId = 0;
|
|
282
|
-
onmessage;
|
|
283
|
-
onclose;
|
|
284
|
-
constructor(ws) {
|
|
285
|
-
this._ws = ws;
|
|
286
|
-
this._ws.on('message', this._onMessage.bind(this));
|
|
287
|
-
this._ws.on('close', this._onClose.bind(this));
|
|
288
|
-
this._ws.on('error', this._onError.bind(this));
|
|
289
|
-
}
|
|
290
|
-
async send(method, params) {
|
|
291
|
-
if (this._ws.readyState !== WebSocket.OPEN)
|
|
292
|
-
throw new Error(`Unexpected WebSocket state: ${this._ws.readyState}`);
|
|
293
|
-
const id = ++this._lastId;
|
|
294
|
-
this._ws.send(JSON.stringify({ id, method, params }));
|
|
295
|
-
const error = new Error(`Protocol error: ${method}`);
|
|
296
|
-
return new Promise((resolve, reject) => {
|
|
297
|
-
this._callbacks.set(id, { resolve, reject, error });
|
|
298
|
-
});
|
|
299
|
-
}
|
|
300
|
-
close(message) {
|
|
301
|
-
debugLogger('closing extension connection:', message);
|
|
302
|
-
if (this._ws.readyState === WebSocket.OPEN)
|
|
303
|
-
this._ws.close(1000, message);
|
|
304
|
-
}
|
|
305
|
-
_onMessage(event) {
|
|
306
|
-
const eventData = event.toString();
|
|
307
|
-
let parsedJson;
|
|
308
|
-
try {
|
|
309
|
-
parsedJson = JSON.parse(eventData);
|
|
310
|
-
}
|
|
311
|
-
catch (e) {
|
|
312
|
-
debugLogger(`<closing ws> Closing websocket due to malformed JSON. eventData=${eventData} e=${e?.message}`);
|
|
313
|
-
this._ws.close();
|
|
314
|
-
return;
|
|
315
|
-
}
|
|
316
|
-
try {
|
|
317
|
-
this._handleParsedMessage(parsedJson);
|
|
318
|
-
}
|
|
319
|
-
catch (e) {
|
|
320
|
-
debugLogger(`<closing ws> Closing websocket due to failed onmessage callback. eventData=${eventData} e=${e?.message}`);
|
|
321
|
-
this._ws.close();
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
_handleParsedMessage(object) {
|
|
325
|
-
if (object.id && this._callbacks.has(object.id)) {
|
|
326
|
-
const callback = this._callbacks.get(object.id);
|
|
327
|
-
this._callbacks.delete(object.id);
|
|
328
|
-
if (object.error) {
|
|
329
|
-
const error = callback.error;
|
|
330
|
-
error.message = object.error;
|
|
331
|
-
callback.reject(error);
|
|
332
|
-
}
|
|
333
|
-
else {
|
|
334
|
-
callback.resolve(object.result);
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
else if (object.id) {
|
|
338
|
-
debugLogger('← Extension: unexpected response', object);
|
|
339
|
-
}
|
|
340
|
-
else {
|
|
341
|
-
this.onmessage?.(object.method, object.params);
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
_onClose(event) {
|
|
345
|
-
debugLogger(`<ws closed> code=${event.code} reason=${event.reason}`);
|
|
346
|
-
this._dispose();
|
|
347
|
-
this.onclose?.(this, event.reason);
|
|
348
|
-
}
|
|
349
|
-
_onError(event) {
|
|
350
|
-
debugLogger(`<ws error> message=${event.message} type=${event.type} target=${event.target}`);
|
|
351
|
-
this._dispose();
|
|
352
|
-
}
|
|
353
|
-
_dispose() {
|
|
354
|
-
for (const callback of this._callbacks.values())
|
|
355
|
-
callback.reject(new Error('WebSocket closed'));
|
|
356
|
-
this._callbacks.clear();
|
|
357
|
-
}
|
|
358
|
-
}
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Copyright (c) Microsoft Corporation.
|
|
3
|
-
*
|
|
4
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
* you may not use this file except in compliance with the License.
|
|
6
|
-
* You may obtain a copy of the License at
|
|
7
|
-
*
|
|
8
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
*
|
|
10
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
* See the License for the specific language governing permissions and
|
|
14
|
-
* limitations under the License.
|
|
15
|
-
*/
|
|
16
|
-
import debug from 'debug';
|
|
17
|
-
import * as playwright from 'playwright';
|
|
18
|
-
import { startHttpServer } from '../mcp/http.js';
|
|
19
|
-
import { CDPRelayServer } from './cdpRelay.js';
|
|
20
|
-
const debugLogger = debug('pw:mcp:relay');
|
|
21
|
-
export class ExtensionContextFactory {
|
|
22
|
-
_browserChannel;
|
|
23
|
-
_userDataDir;
|
|
24
|
-
_executablePath;
|
|
25
|
-
constructor(browserChannel, userDataDir, executablePath) {
|
|
26
|
-
this._browserChannel = browserChannel;
|
|
27
|
-
this._userDataDir = userDataDir;
|
|
28
|
-
this._executablePath = executablePath;
|
|
29
|
-
}
|
|
30
|
-
async createContext(clientInfo, abortSignal, toolName) {
|
|
31
|
-
const browser = await this._obtainBrowser(clientInfo, abortSignal, toolName);
|
|
32
|
-
return {
|
|
33
|
-
browserContext: browser.contexts()[0],
|
|
34
|
-
close: async () => {
|
|
35
|
-
debugLogger('close() called for browser context');
|
|
36
|
-
await browser.close();
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
async _obtainBrowser(clientInfo, abortSignal, toolName) {
|
|
41
|
-
const relay = await this._startRelay(abortSignal);
|
|
42
|
-
await relay.ensureExtensionConnectionForMCPContext(clientInfo, abortSignal, toolName);
|
|
43
|
-
return await playwright.chromium.connectOverCDP(relay.cdpEndpoint());
|
|
44
|
-
}
|
|
45
|
-
async _startRelay(abortSignal) {
|
|
46
|
-
const httpServer = await startHttpServer({});
|
|
47
|
-
if (abortSignal.aborted) {
|
|
48
|
-
httpServer.close();
|
|
49
|
-
throw new Error(abortSignal.reason);
|
|
50
|
-
}
|
|
51
|
-
const cdpRelayServer = new CDPRelayServer(httpServer, this._browserChannel, this._userDataDir, this._executablePath);
|
|
52
|
-
abortSignal.addEventListener('abort', () => cdpRelayServer.stop());
|
|
53
|
-
debugLogger(`CDP relay server started, extension endpoint: ${cdpRelayServer.extensionEndpoint()}.`);
|
|
54
|
-
return cdpRelayServer;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Copyright (c) Microsoft Corporation.
|
|
3
|
-
*
|
|
4
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
* you may not use this file except in compliance with the License.
|
|
6
|
-
* You may obtain a copy of the License at
|
|
7
|
-
*
|
|
8
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
*
|
|
10
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
* See the License for the specific language governing permissions and
|
|
14
|
-
* limitations under the License.
|
|
15
|
-
*/
|
|
16
|
-
// Whenever the commands/events change, the version must be updated. The latest
|
|
17
|
-
// extension version should be compatible with the old MCP clients.
|
|
18
|
-
export const VERSION = 1;
|
package/lib/index.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Copyright (c) Microsoft Corporation.
|
|
3
|
-
*
|
|
4
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
* you may not use this file except in compliance with the License.
|
|
6
|
-
* You may obtain a copy of the License at
|
|
7
|
-
*
|
|
8
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
*
|
|
10
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
* See the License for the specific language governing permissions and
|
|
14
|
-
* limitations under the License.
|
|
15
|
-
*/
|
|
16
|
-
import { BrowserServerBackend } from './browserServerBackend.js';
|
|
17
|
-
import { resolveConfig } from './config.js';
|
|
18
|
-
import { contextFactory } from './browserContextFactory.js';
|
|
19
|
-
import * as mcpServer from './mcp/server.js';
|
|
20
|
-
import { packageJSON } from './utils/package.js';
|
|
21
|
-
export async function createConnection(userConfig = {}, contextGetter) {
|
|
22
|
-
const config = await resolveConfig(userConfig);
|
|
23
|
-
const factory = contextGetter ? new SimpleBrowserContextFactory(contextGetter) : contextFactory(config);
|
|
24
|
-
return mcpServer.createServer('Playwright', packageJSON.version, new BrowserServerBackend(config, factory), false);
|
|
25
|
-
}
|
|
26
|
-
class SimpleBrowserContextFactory {
|
|
27
|
-
name = 'custom';
|
|
28
|
-
description = 'Connect to a browser using a custom context getter';
|
|
29
|
-
_contextGetter;
|
|
30
|
-
constructor(contextGetter) {
|
|
31
|
-
this._contextGetter = contextGetter;
|
|
32
|
-
}
|
|
33
|
-
async createContext() {
|
|
34
|
-
const browserContext = await this._contextGetter();
|
|
35
|
-
return {
|
|
36
|
-
browserContext,
|
|
37
|
-
close: () => browserContext.close()
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
}
|
package/lib/loop/loop.js
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Copyright (c) Microsoft Corporation.
|
|
3
|
-
*
|
|
4
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
* you may not use this file except in compliance with the License.
|
|
6
|
-
* You may obtain a copy of the License at
|
|
7
|
-
*
|
|
8
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
*
|
|
10
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
* See the License for the specific language governing permissions and
|
|
14
|
-
* limitations under the License.
|
|
15
|
-
*/
|
|
16
|
-
import debug from 'debug';
|
|
17
|
-
export async function runTask(delegate, client, task, oneShot = false) {
|
|
18
|
-
const { tools } = await client.listTools();
|
|
19
|
-
const taskContent = oneShot ? `Perform following task: ${task}.` : `Perform following task: ${task}. Once the task is complete, call the "done" tool.`;
|
|
20
|
-
const conversation = delegate.createConversation(taskContent, tools, oneShot);
|
|
21
|
-
for (let iteration = 0; iteration < 5; ++iteration) {
|
|
22
|
-
debug('history')('Making API call for iteration', iteration);
|
|
23
|
-
const toolCalls = await delegate.makeApiCall(conversation);
|
|
24
|
-
if (toolCalls.length === 0)
|
|
25
|
-
throw new Error('Call the "done" tool when the task is complete.');
|
|
26
|
-
const toolResults = [];
|
|
27
|
-
for (const toolCall of toolCalls) {
|
|
28
|
-
const doneResult = delegate.checkDoneToolCall(toolCall);
|
|
29
|
-
if (doneResult !== null)
|
|
30
|
-
return conversation.messages;
|
|
31
|
-
const { name, arguments: args, id } = toolCall;
|
|
32
|
-
try {
|
|
33
|
-
debug('tool')(name, args);
|
|
34
|
-
const response = await client.callTool({
|
|
35
|
-
name,
|
|
36
|
-
arguments: args,
|
|
37
|
-
});
|
|
38
|
-
const responseContent = (response.content || []);
|
|
39
|
-
debug('tool')(responseContent);
|
|
40
|
-
const text = responseContent.filter(part => part.type === 'text').map(part => part.text).join('\n');
|
|
41
|
-
toolResults.push({
|
|
42
|
-
toolCallId: id,
|
|
43
|
-
content: text,
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
catch (error) {
|
|
47
|
-
debug('tool')(error);
|
|
48
|
-
toolResults.push({
|
|
49
|
-
toolCallId: id,
|
|
50
|
-
content: `Error while executing tool "${name}": ${error instanceof Error ? error.message : String(error)}\n\nPlease try to recover and complete the task.`,
|
|
51
|
-
isError: true,
|
|
52
|
-
});
|
|
53
|
-
// Skip remaining tool calls for this iteration
|
|
54
|
-
for (const remainingToolCall of toolCalls.slice(toolCalls.indexOf(toolCall) + 1)) {
|
|
55
|
-
toolResults.push({
|
|
56
|
-
toolCallId: remainingToolCall.id,
|
|
57
|
-
content: `This tool call is skipped due to previous error.`,
|
|
58
|
-
isError: true,
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
break;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
delegate.addToolResults(conversation, toolResults);
|
|
65
|
-
if (oneShot)
|
|
66
|
-
return conversation.messages;
|
|
67
|
-
}
|
|
68
|
-
throw new Error('Failed to perform step, max attempts reached');
|
|
69
|
-
}
|