@roxybrowser/playwright-mcp 0.0.1
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 +202 -0
- package/README.md +742 -0
- package/cli.js +18 -0
- package/config.d.ts +119 -0
- package/index.d.ts +23 -0
- package/index.js +19 -0
- package/lib/browserContextFactory.js +264 -0
- package/lib/browserServerBackend.js +77 -0
- package/lib/config.js +246 -0
- package/lib/context.js +242 -0
- package/lib/extension/cdpRelay.js +355 -0
- package/lib/extension/extensionContextFactory.js +54 -0
- package/lib/index.js +40 -0
- package/lib/loop/loop.js +69 -0
- package/lib/loop/loopClaude.js +152 -0
- package/lib/loop/loopOpenAI.js +141 -0
- package/lib/loop/main.js +60 -0
- package/lib/loopTools/context.js +67 -0
- package/lib/loopTools/main.js +54 -0
- package/lib/loopTools/perform.js +32 -0
- package/lib/loopTools/snapshot.js +29 -0
- package/lib/loopTools/tool.js +18 -0
- package/lib/mcp/http.js +120 -0
- package/lib/mcp/inProcessTransport.js +72 -0
- package/lib/mcp/proxyBackend.js +104 -0
- package/lib/mcp/server.js +123 -0
- package/lib/mcp/tool.js +29 -0
- package/lib/program.js +145 -0
- package/lib/response.js +165 -0
- package/lib/sessionLog.js +121 -0
- package/lib/tab.js +249 -0
- package/lib/tools/common.js +55 -0
- package/lib/tools/console.js +33 -0
- package/lib/tools/dialogs.js +47 -0
- package/lib/tools/evaluate.js +53 -0
- package/lib/tools/files.js +44 -0
- package/lib/tools/install.js +53 -0
- package/lib/tools/keyboard.js +78 -0
- package/lib/tools/mouse.js +99 -0
- package/lib/tools/navigate.js +70 -0
- package/lib/tools/network.js +41 -0
- package/lib/tools/pdf.js +40 -0
- package/lib/tools/roxy.js +50 -0
- package/lib/tools/screenshot.js +79 -0
- package/lib/tools/snapshot.js +139 -0
- package/lib/tools/tabs.js +87 -0
- package/lib/tools/tool.js +33 -0
- package/lib/tools/utils.js +74 -0
- package/lib/tools/wait.js +55 -0
- package/lib/tools.js +52 -0
- package/lib/utils/codegen.js +49 -0
- package/lib/utils/fileUtils.js +36 -0
- package/lib/utils/guid.js +22 -0
- package/lib/utils/log.js +21 -0
- package/lib/utils/manualPromise.js +111 -0
- package/lib/utils/package.js +20 -0
- package/lib/vscode/host.js +128 -0
- package/lib/vscode/main.js +62 -0
- package/package.json +79 -0
|
@@ -0,0 +1,74 @@
|
|
|
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
|
+
// @ts-ignore
|
|
17
|
+
import { asLocator } from 'playwright-core/lib/utils';
|
|
18
|
+
export async function waitForCompletion(tab, callback) {
|
|
19
|
+
const requests = new Set();
|
|
20
|
+
let frameNavigated = false;
|
|
21
|
+
let waitCallback = () => { };
|
|
22
|
+
const waitBarrier = new Promise(f => { waitCallback = f; });
|
|
23
|
+
const requestListener = (request) => requests.add(request);
|
|
24
|
+
const requestFinishedListener = (request) => {
|
|
25
|
+
requests.delete(request);
|
|
26
|
+
if (!requests.size)
|
|
27
|
+
waitCallback();
|
|
28
|
+
};
|
|
29
|
+
const frameNavigateListener = (frame) => {
|
|
30
|
+
if (frame.parentFrame())
|
|
31
|
+
return;
|
|
32
|
+
frameNavigated = true;
|
|
33
|
+
dispose();
|
|
34
|
+
clearTimeout(timeout);
|
|
35
|
+
void tab.waitForLoadState('load').then(waitCallback);
|
|
36
|
+
};
|
|
37
|
+
const onTimeout = () => {
|
|
38
|
+
dispose();
|
|
39
|
+
waitCallback();
|
|
40
|
+
};
|
|
41
|
+
tab.page.on('request', requestListener);
|
|
42
|
+
tab.page.on('requestfinished', requestFinishedListener);
|
|
43
|
+
tab.page.on('framenavigated', frameNavigateListener);
|
|
44
|
+
const timeout = setTimeout(onTimeout, 10000);
|
|
45
|
+
const dispose = () => {
|
|
46
|
+
tab.page.off('request', requestListener);
|
|
47
|
+
tab.page.off('requestfinished', requestFinishedListener);
|
|
48
|
+
tab.page.off('framenavigated', frameNavigateListener);
|
|
49
|
+
clearTimeout(timeout);
|
|
50
|
+
};
|
|
51
|
+
try {
|
|
52
|
+
const result = await callback();
|
|
53
|
+
if (!requests.size && !frameNavigated)
|
|
54
|
+
waitCallback();
|
|
55
|
+
await waitBarrier;
|
|
56
|
+
await tab.waitForTimeout(1000);
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
dispose();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export async function generateLocator(locator) {
|
|
64
|
+
try {
|
|
65
|
+
const { resolvedSelector } = await locator._resolveSelector();
|
|
66
|
+
return asLocator('javascript', resolvedSelector);
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
throw new Error('Ref not found, likely because element was removed. Use browser_snapshot to see what elements are currently on the page.');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export async function callOnPageNoTrace(page, callback) {
|
|
73
|
+
return await page._wrapApiCall(() => callback(page), { internal: true });
|
|
74
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
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 { z } from 'zod';
|
|
17
|
+
import { defineTool } from './tool.js';
|
|
18
|
+
const wait = defineTool({
|
|
19
|
+
capability: 'core',
|
|
20
|
+
schema: {
|
|
21
|
+
name: 'browser_wait_for',
|
|
22
|
+
title: 'Wait for',
|
|
23
|
+
description: 'Wait for text to appear or disappear or a specified time to pass',
|
|
24
|
+
inputSchema: z.object({
|
|
25
|
+
time: z.number().optional().describe('The time to wait in seconds'),
|
|
26
|
+
text: z.string().optional().describe('The text to wait for'),
|
|
27
|
+
textGone: z.string().optional().describe('The text to wait for to disappear'),
|
|
28
|
+
}),
|
|
29
|
+
type: 'readOnly',
|
|
30
|
+
},
|
|
31
|
+
handle: async (context, params, response) => {
|
|
32
|
+
if (!params.text && !params.textGone && !params.time)
|
|
33
|
+
throw new Error('Either time, text or textGone must be provided');
|
|
34
|
+
if (params.time) {
|
|
35
|
+
response.addCode(`await new Promise(f => setTimeout(f, ${params.time} * 1000));`);
|
|
36
|
+
await new Promise(f => setTimeout(f, Math.min(30000, params.time * 1000)));
|
|
37
|
+
}
|
|
38
|
+
const tab = context.currentTabOrDie();
|
|
39
|
+
const locator = params.text ? tab.page.getByText(params.text).first() : undefined;
|
|
40
|
+
const goneLocator = params.textGone ? tab.page.getByText(params.textGone).first() : undefined;
|
|
41
|
+
if (goneLocator) {
|
|
42
|
+
response.addCode(`await page.getByText(${JSON.stringify(params.textGone)}).first().waitFor({ state: 'hidden' });`);
|
|
43
|
+
await goneLocator.waitFor({ state: 'hidden' });
|
|
44
|
+
}
|
|
45
|
+
if (locator) {
|
|
46
|
+
response.addCode(`await page.getByText(${JSON.stringify(params.text)}).first().waitFor({ state: 'visible' });`);
|
|
47
|
+
await locator.waitFor({ state: 'visible' });
|
|
48
|
+
}
|
|
49
|
+
response.addResult(`Waited for ${params.text || params.textGone || params.time}`);
|
|
50
|
+
response.setIncludeSnapshot();
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
export default [
|
|
54
|
+
wait,
|
|
55
|
+
];
|
package/lib/tools.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
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 common from './tools/common.js';
|
|
17
|
+
import console from './tools/console.js';
|
|
18
|
+
import dialogs from './tools/dialogs.js';
|
|
19
|
+
import evaluate from './tools/evaluate.js';
|
|
20
|
+
import files from './tools/files.js';
|
|
21
|
+
import install from './tools/install.js';
|
|
22
|
+
import keyboard from './tools/keyboard.js';
|
|
23
|
+
import navigate from './tools/navigate.js';
|
|
24
|
+
import network from './tools/network.js';
|
|
25
|
+
import pdf from './tools/pdf.js';
|
|
26
|
+
import snapshot from './tools/snapshot.js';
|
|
27
|
+
import tabs from './tools/tabs.js';
|
|
28
|
+
import screenshot from './tools/screenshot.js';
|
|
29
|
+
import wait from './tools/wait.js';
|
|
30
|
+
import mouse from './tools/mouse.js';
|
|
31
|
+
import roxy from './tools/roxy.js';
|
|
32
|
+
export const allTools = [
|
|
33
|
+
...common,
|
|
34
|
+
...console,
|
|
35
|
+
...dialogs,
|
|
36
|
+
...evaluate,
|
|
37
|
+
...files,
|
|
38
|
+
...install,
|
|
39
|
+
...keyboard,
|
|
40
|
+
...navigate,
|
|
41
|
+
...network,
|
|
42
|
+
...mouse,
|
|
43
|
+
...pdf,
|
|
44
|
+
...roxy,
|
|
45
|
+
...screenshot,
|
|
46
|
+
...snapshot,
|
|
47
|
+
...tabs,
|
|
48
|
+
...wait,
|
|
49
|
+
];
|
|
50
|
+
export function filteredTools(config) {
|
|
51
|
+
return allTools.filter(tool => tool.capability.startsWith('core') || config.capabilities?.includes(tool.capability));
|
|
52
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
// adapted from:
|
|
17
|
+
// - https://github.com/microsoft/playwright/blob/76ee48dc9d4034536e3ec5b2c7ce8be3b79418a8/packages/playwright-core/src/utils/isomorphic/stringUtils.ts
|
|
18
|
+
// - https://github.com/microsoft/playwright/blob/76ee48dc9d4034536e3ec5b2c7ce8be3b79418a8/packages/playwright-core/src/server/codegen/javascript.ts
|
|
19
|
+
// NOTE: this function should not be used to escape any selectors.
|
|
20
|
+
export function escapeWithQuotes(text, char = '\'') {
|
|
21
|
+
const stringified = JSON.stringify(text);
|
|
22
|
+
const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"');
|
|
23
|
+
if (char === '\'')
|
|
24
|
+
return char + escapedText.replace(/[']/g, '\\\'') + char;
|
|
25
|
+
if (char === '"')
|
|
26
|
+
return char + escapedText.replace(/["]/g, '\\"') + char;
|
|
27
|
+
if (char === '`')
|
|
28
|
+
return char + escapedText.replace(/[`]/g, '\\`') + char;
|
|
29
|
+
throw new Error('Invalid escape char');
|
|
30
|
+
}
|
|
31
|
+
export function quote(text) {
|
|
32
|
+
return escapeWithQuotes(text, '\'');
|
|
33
|
+
}
|
|
34
|
+
export function formatObject(value, indent = ' ') {
|
|
35
|
+
if (typeof value === 'string')
|
|
36
|
+
return quote(value);
|
|
37
|
+
if (Array.isArray(value))
|
|
38
|
+
return `[${value.map(o => formatObject(o)).join(', ')}]`;
|
|
39
|
+
if (typeof value === 'object') {
|
|
40
|
+
const keys = Object.keys(value).filter(key => value[key] !== undefined).sort();
|
|
41
|
+
if (!keys.length)
|
|
42
|
+
return '{}';
|
|
43
|
+
const tokens = [];
|
|
44
|
+
for (const key of keys)
|
|
45
|
+
tokens.push(`${key}: ${formatObject(value[key])}`);
|
|
46
|
+
return `{\n${indent}${tokens.join(`,\n${indent}`)}\n}`;
|
|
47
|
+
}
|
|
48
|
+
return String(value);
|
|
49
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
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 os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
export function cacheDir() {
|
|
19
|
+
let cacheDirectory;
|
|
20
|
+
if (process.platform === 'linux')
|
|
21
|
+
cacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');
|
|
22
|
+
else if (process.platform === 'darwin')
|
|
23
|
+
cacheDirectory = path.join(os.homedir(), 'Library', 'Caches');
|
|
24
|
+
else if (process.platform === 'win32')
|
|
25
|
+
cacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
|
26
|
+
else
|
|
27
|
+
throw new Error('Unsupported platform: ' + process.platform);
|
|
28
|
+
return path.join(cacheDirectory, 'ms-playwright');
|
|
29
|
+
}
|
|
30
|
+
export function sanitizeForFilePath(s) {
|
|
31
|
+
const sanitize = (s) => s.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, '-');
|
|
32
|
+
const separator = s.lastIndexOf('.');
|
|
33
|
+
if (separator === -1)
|
|
34
|
+
return sanitize(s);
|
|
35
|
+
return sanitize(s.substring(0, separator)) + '.' + sanitize(s.substring(separator + 1));
|
|
36
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
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 crypto from 'crypto';
|
|
17
|
+
export function createGuid() {
|
|
18
|
+
return crypto.randomBytes(16).toString('hex');
|
|
19
|
+
}
|
|
20
|
+
export function createHash(data) {
|
|
21
|
+
return crypto.createHash('sha256').update(data).digest('hex').slice(0, 7);
|
|
22
|
+
}
|
package/lib/utils/log.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
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
|
+
const errorsDebug = debug('pw:mcp:errors');
|
|
18
|
+
export function logUnhandledError(error) {
|
|
19
|
+
errorsDebug(error);
|
|
20
|
+
}
|
|
21
|
+
export const testDebug = debug('pw:mcp:test');
|
|
@@ -0,0 +1,111 @@
|
|
|
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
|
+
export class ManualPromise extends Promise {
|
|
17
|
+
_resolve;
|
|
18
|
+
_reject;
|
|
19
|
+
_isDone;
|
|
20
|
+
constructor() {
|
|
21
|
+
let resolve;
|
|
22
|
+
let reject;
|
|
23
|
+
super((f, r) => {
|
|
24
|
+
resolve = f;
|
|
25
|
+
reject = r;
|
|
26
|
+
});
|
|
27
|
+
this._isDone = false;
|
|
28
|
+
this._resolve = resolve;
|
|
29
|
+
this._reject = reject;
|
|
30
|
+
}
|
|
31
|
+
isDone() {
|
|
32
|
+
return this._isDone;
|
|
33
|
+
}
|
|
34
|
+
resolve(t) {
|
|
35
|
+
this._isDone = true;
|
|
36
|
+
this._resolve(t);
|
|
37
|
+
}
|
|
38
|
+
reject(e) {
|
|
39
|
+
this._isDone = true;
|
|
40
|
+
this._reject(e);
|
|
41
|
+
}
|
|
42
|
+
static get [Symbol.species]() {
|
|
43
|
+
return Promise;
|
|
44
|
+
}
|
|
45
|
+
get [Symbol.toStringTag]() {
|
|
46
|
+
return 'ManualPromise';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export class LongStandingScope {
|
|
50
|
+
_terminateError;
|
|
51
|
+
_closeError;
|
|
52
|
+
_terminatePromises = new Map();
|
|
53
|
+
_isClosed = false;
|
|
54
|
+
reject(error) {
|
|
55
|
+
this._isClosed = true;
|
|
56
|
+
this._terminateError = error;
|
|
57
|
+
for (const p of this._terminatePromises.keys())
|
|
58
|
+
p.resolve(error);
|
|
59
|
+
}
|
|
60
|
+
close(error) {
|
|
61
|
+
this._isClosed = true;
|
|
62
|
+
this._closeError = error;
|
|
63
|
+
for (const [p, frames] of this._terminatePromises)
|
|
64
|
+
p.resolve(cloneError(error, frames));
|
|
65
|
+
}
|
|
66
|
+
isClosed() {
|
|
67
|
+
return this._isClosed;
|
|
68
|
+
}
|
|
69
|
+
static async raceMultiple(scopes, promise) {
|
|
70
|
+
return Promise.race(scopes.map(s => s.race(promise)));
|
|
71
|
+
}
|
|
72
|
+
async race(promise) {
|
|
73
|
+
return this._race(Array.isArray(promise) ? promise : [promise], false);
|
|
74
|
+
}
|
|
75
|
+
async safeRace(promise, defaultValue) {
|
|
76
|
+
return this._race([promise], true, defaultValue);
|
|
77
|
+
}
|
|
78
|
+
async _race(promises, safe, defaultValue) {
|
|
79
|
+
const terminatePromise = new ManualPromise();
|
|
80
|
+
const frames = captureRawStack();
|
|
81
|
+
if (this._terminateError)
|
|
82
|
+
terminatePromise.resolve(this._terminateError);
|
|
83
|
+
if (this._closeError)
|
|
84
|
+
terminatePromise.resolve(cloneError(this._closeError, frames));
|
|
85
|
+
this._terminatePromises.set(terminatePromise, frames);
|
|
86
|
+
try {
|
|
87
|
+
return await Promise.race([
|
|
88
|
+
terminatePromise.then(e => safe ? defaultValue : Promise.reject(e)),
|
|
89
|
+
...promises
|
|
90
|
+
]);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
this._terminatePromises.delete(terminatePromise);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function cloneError(error, frames) {
|
|
98
|
+
const clone = new Error();
|
|
99
|
+
clone.name = error.name;
|
|
100
|
+
clone.message = error.message;
|
|
101
|
+
clone.stack = [error.name + ':' + error.message, ...frames].join('\n');
|
|
102
|
+
return clone;
|
|
103
|
+
}
|
|
104
|
+
function captureRawStack() {
|
|
105
|
+
const stackTraceLimit = Error.stackTraceLimit;
|
|
106
|
+
Error.stackTraceLimit = 50;
|
|
107
|
+
const error = new Error();
|
|
108
|
+
const stack = error.stack || '';
|
|
109
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
110
|
+
return stack.split('\n');
|
|
111
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
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 fs from 'fs';
|
|
17
|
+
import path from 'path';
|
|
18
|
+
import url from 'url';
|
|
19
|
+
const __filename = url.fileURLToPath(import.meta.url);
|
|
20
|
+
export const packageJSON = JSON.parse(fs.readFileSync(path.join(path.dirname(__filename), '..', '..', 'package.json'), 'utf8'));
|
|
@@ -0,0 +1,128 @@
|
|
|
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 { fileURLToPath } from 'url';
|
|
17
|
+
import path from 'path';
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
20
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
21
|
+
import { ListRootsRequestSchema, PingRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
22
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
23
|
+
import * as mcpServer from '../mcp/server.js';
|
|
24
|
+
import { logUnhandledError } from '../utils/log.js';
|
|
25
|
+
import { packageJSON } from '../utils/package.js';
|
|
26
|
+
import { BrowserServerBackend } from '../browserServerBackend.js';
|
|
27
|
+
import { contextFactory } from '../browserContextFactory.js';
|
|
28
|
+
const contextSwitchOptions = z.object({
|
|
29
|
+
connectionString: z.string().optional().describe('The connection string to use to connect to the browser'),
|
|
30
|
+
lib: z.string().optional().describe('The library to use for the connection'),
|
|
31
|
+
});
|
|
32
|
+
class VSCodeProxyBackend {
|
|
33
|
+
_config;
|
|
34
|
+
_defaultTransportFactory;
|
|
35
|
+
name = 'Playwright MCP Client Switcher';
|
|
36
|
+
version = packageJSON.version;
|
|
37
|
+
_currentClient;
|
|
38
|
+
_contextSwitchTool;
|
|
39
|
+
_roots = [];
|
|
40
|
+
_clientVersion;
|
|
41
|
+
constructor(_config, _defaultTransportFactory) {
|
|
42
|
+
this._config = _config;
|
|
43
|
+
this._defaultTransportFactory = _defaultTransportFactory;
|
|
44
|
+
this._contextSwitchTool = this._defineContextSwitchTool();
|
|
45
|
+
}
|
|
46
|
+
async initialize(clientVersion, roots) {
|
|
47
|
+
this._clientVersion = clientVersion;
|
|
48
|
+
this._roots = roots;
|
|
49
|
+
const transport = await this._defaultTransportFactory();
|
|
50
|
+
await this._setCurrentClient(transport);
|
|
51
|
+
}
|
|
52
|
+
async listTools() {
|
|
53
|
+
const response = await this._currentClient.listTools();
|
|
54
|
+
return [
|
|
55
|
+
...response.tools,
|
|
56
|
+
this._contextSwitchTool,
|
|
57
|
+
];
|
|
58
|
+
}
|
|
59
|
+
async callTool(name, args) {
|
|
60
|
+
if (name === this._contextSwitchTool.name)
|
|
61
|
+
return this._callContextSwitchTool(args);
|
|
62
|
+
return await this._currentClient.callTool({
|
|
63
|
+
name,
|
|
64
|
+
arguments: args,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
serverClosed() {
|
|
68
|
+
void this._currentClient?.close().catch(logUnhandledError);
|
|
69
|
+
}
|
|
70
|
+
async _callContextSwitchTool(params) {
|
|
71
|
+
if (!params.connectionString || !params.lib) {
|
|
72
|
+
const transport = await this._defaultTransportFactory();
|
|
73
|
+
await this._setCurrentClient(transport);
|
|
74
|
+
return {
|
|
75
|
+
content: [{ type: 'text', text: '### Result\nSuccessfully disconnected.\n' }],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
await this._setCurrentClient(new StdioClientTransport({
|
|
79
|
+
command: process.execPath,
|
|
80
|
+
cwd: process.cwd(),
|
|
81
|
+
args: [
|
|
82
|
+
path.join(fileURLToPath(import.meta.url), '..', 'main.js'),
|
|
83
|
+
JSON.stringify(this._config),
|
|
84
|
+
params.connectionString,
|
|
85
|
+
params.lib,
|
|
86
|
+
],
|
|
87
|
+
}));
|
|
88
|
+
return {
|
|
89
|
+
content: [{ type: 'text', text: '### Result\nSuccessfully connected.\n' }],
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
_defineContextSwitchTool() {
|
|
93
|
+
return {
|
|
94
|
+
name: 'browser_connect',
|
|
95
|
+
description: 'Do not call, this tool is used in the integration with the Playwright VS Code Extension and meant for programmatic usage only.',
|
|
96
|
+
inputSchema: zodToJsonSchema(contextSwitchOptions, { strictUnions: true }),
|
|
97
|
+
annotations: {
|
|
98
|
+
title: 'Connect to a browser running in VS Code.',
|
|
99
|
+
readOnlyHint: true,
|
|
100
|
+
openWorldHint: false,
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
async _setCurrentClient(transport) {
|
|
105
|
+
await this._currentClient?.close();
|
|
106
|
+
this._currentClient = undefined;
|
|
107
|
+
const client = new Client(this._clientVersion);
|
|
108
|
+
client.registerCapabilities({
|
|
109
|
+
roots: {
|
|
110
|
+
listRoots: true,
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
client.setRequestHandler(ListRootsRequestSchema, () => ({ roots: this._roots }));
|
|
114
|
+
client.setRequestHandler(PingRequestSchema, () => ({}));
|
|
115
|
+
await client.connect(transport);
|
|
116
|
+
this._currentClient = client;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export async function runVSCodeTools(config) {
|
|
120
|
+
const serverBackendFactory = {
|
|
121
|
+
name: 'Playwright w/ vscode',
|
|
122
|
+
nameInConfig: 'playwright-vscode',
|
|
123
|
+
version: packageJSON.version,
|
|
124
|
+
create: () => new VSCodeProxyBackend(config, () => mcpServer.wrapInProcess(new BrowserServerBackend(config, contextFactory(config))))
|
|
125
|
+
};
|
|
126
|
+
await mcpServer.start(serverBackendFactory, config.server);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
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 { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
17
|
+
import * as mcpServer from '../mcp/server.js';
|
|
18
|
+
import { BrowserServerBackend } from '../browserServerBackend.js';
|
|
19
|
+
class VSCodeBrowserContextFactory {
|
|
20
|
+
_config;
|
|
21
|
+
_playwright;
|
|
22
|
+
_connectionString;
|
|
23
|
+
name = 'vscode';
|
|
24
|
+
description = 'Connect to a browser running in the Playwright VS Code extension';
|
|
25
|
+
constructor(_config, _playwright, _connectionString) {
|
|
26
|
+
this._config = _config;
|
|
27
|
+
this._playwright = _playwright;
|
|
28
|
+
this._connectionString = _connectionString;
|
|
29
|
+
}
|
|
30
|
+
async createContext(clientInfo, abortSignal) {
|
|
31
|
+
let launchOptions = this._config.browser.launchOptions;
|
|
32
|
+
if (this._config.browser.userDataDir) {
|
|
33
|
+
launchOptions = {
|
|
34
|
+
...launchOptions,
|
|
35
|
+
...this._config.browser.contextOptions,
|
|
36
|
+
userDataDir: this._config.browser.userDataDir,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const connectionString = new URL(this._connectionString);
|
|
40
|
+
connectionString.searchParams.set('launch-options', JSON.stringify(launchOptions));
|
|
41
|
+
const browserType = this._playwright.chromium; // it could also be firefox or webkit, we just need some browser type to call `connect` on
|
|
42
|
+
const browser = await browserType.connect(connectionString.toString());
|
|
43
|
+
const context = browser.contexts()[0] ?? await browser.newContext(this._config.browser.contextOptions);
|
|
44
|
+
return {
|
|
45
|
+
browserContext: context,
|
|
46
|
+
close: async () => {
|
|
47
|
+
await browser.close();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function main(config, connectionString, lib) {
|
|
53
|
+
const playwright = await import(lib).then(mod => mod.default ?? mod);
|
|
54
|
+
const factory = new VSCodeBrowserContextFactory(config, playwright, connectionString);
|
|
55
|
+
await mcpServer.connect({
|
|
56
|
+
name: 'Playwright MCP',
|
|
57
|
+
nameInConfig: 'playwright-vscode',
|
|
58
|
+
create: () => new BrowserServerBackend(config, factory),
|
|
59
|
+
version: 'unused'
|
|
60
|
+
}, new StdioServerTransport(), false);
|
|
61
|
+
}
|
|
62
|
+
await main(JSON.parse(process.argv[2]), process.argv[3], process.argv[4]);
|