playwright-mcp-phantomx 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 +688 -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 +205 -0
- package/lib/browserServerBackend.js +121 -0
- package/lib/config.js +246 -0
- package/lib/context.js +226 -0
- package/lib/extension/cdpRelay.js +346 -0
- package/lib/extension/extensionContextFactory.js +56 -0
- package/lib/extension/main.js +26 -0
- package/lib/fileUtils.js +32 -0
- package/lib/httpServer.js +39 -0
- package/lib/index.js +39 -0
- package/lib/javascript.js +49 -0
- package/lib/log.js +21 -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 +66 -0
- package/lib/loopTools/main.js +49 -0
- package/lib/loopTools/perform.js +32 -0
- package/lib/loopTools/snapshot.js +29 -0
- package/lib/loopTools/tool.js +18 -0
- package/lib/manualPromise.js +111 -0
- package/lib/mcp/inProcessTransport.js +72 -0
- package/lib/mcp/server.js +93 -0
- package/lib/mcp/transport.js +140 -0
- package/lib/package.js +20 -0
- package/lib/program.js +103 -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/screenshot.js +77 -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 +56 -0
- package/lib/tools.js +50 -0
- package/lib/utils.js +26 -0
- package/package.json +73 -0
|
@@ -0,0 +1,72 @@
|
|
|
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 InProcessTransport {
|
|
17
|
+
_server;
|
|
18
|
+
_serverTransport;
|
|
19
|
+
_connected = false;
|
|
20
|
+
constructor(server) {
|
|
21
|
+
this._server = server;
|
|
22
|
+
this._serverTransport = new InProcessServerTransport(this);
|
|
23
|
+
}
|
|
24
|
+
async start() {
|
|
25
|
+
if (this._connected)
|
|
26
|
+
throw new Error('InprocessTransport already started!');
|
|
27
|
+
await this._server.connect(this._serverTransport);
|
|
28
|
+
this._connected = true;
|
|
29
|
+
}
|
|
30
|
+
async send(message, options) {
|
|
31
|
+
if (!this._connected)
|
|
32
|
+
throw new Error('Transport not connected');
|
|
33
|
+
this._serverTransport._receiveFromClient(message);
|
|
34
|
+
}
|
|
35
|
+
async close() {
|
|
36
|
+
if (this._connected) {
|
|
37
|
+
this._connected = false;
|
|
38
|
+
this.onclose?.();
|
|
39
|
+
this._serverTransport.onclose?.();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
onclose;
|
|
43
|
+
onerror;
|
|
44
|
+
onmessage;
|
|
45
|
+
sessionId;
|
|
46
|
+
setProtocolVersion;
|
|
47
|
+
_receiveFromServer(message, extra) {
|
|
48
|
+
this.onmessage?.(message, extra);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
class InProcessServerTransport {
|
|
52
|
+
_clientTransport;
|
|
53
|
+
constructor(clientTransport) {
|
|
54
|
+
this._clientTransport = clientTransport;
|
|
55
|
+
}
|
|
56
|
+
async start() {
|
|
57
|
+
}
|
|
58
|
+
async send(message, options) {
|
|
59
|
+
this._clientTransport._receiveFromServer(message);
|
|
60
|
+
}
|
|
61
|
+
async close() {
|
|
62
|
+
this.onclose?.();
|
|
63
|
+
}
|
|
64
|
+
onclose;
|
|
65
|
+
onerror;
|
|
66
|
+
onmessage;
|
|
67
|
+
sessionId;
|
|
68
|
+
setProtocolVersion;
|
|
69
|
+
_receiveFromClient(message) {
|
|
70
|
+
this.onmessage?.(message);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
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 { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
17
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
18
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
19
|
+
import { ManualPromise } from '../manualPromise.js';
|
|
20
|
+
import { logUnhandledError } from '../log.js';
|
|
21
|
+
export async function connect(serverBackendFactory, transport, runHeartbeat) {
|
|
22
|
+
const backend = serverBackendFactory();
|
|
23
|
+
const server = createServer(backend, runHeartbeat);
|
|
24
|
+
await server.connect(transport);
|
|
25
|
+
}
|
|
26
|
+
export function createServer(backend, runHeartbeat) {
|
|
27
|
+
const initializedPromise = new ManualPromise();
|
|
28
|
+
const server = new Server({ name: backend.name, version: backend.version }, {
|
|
29
|
+
capabilities: {
|
|
30
|
+
tools: {},
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
const tools = backend.tools();
|
|
34
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
35
|
+
return { tools: tools.map(tool => ({
|
|
36
|
+
name: tool.name,
|
|
37
|
+
description: tool.description,
|
|
38
|
+
inputSchema: zodToJsonSchema(tool.inputSchema),
|
|
39
|
+
annotations: {
|
|
40
|
+
title: tool.title,
|
|
41
|
+
readOnlyHint: tool.type === 'readOnly',
|
|
42
|
+
destructiveHint: tool.type === 'destructive',
|
|
43
|
+
openWorldHint: true,
|
|
44
|
+
},
|
|
45
|
+
})) };
|
|
46
|
+
});
|
|
47
|
+
let heartbeatRunning = false;
|
|
48
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
49
|
+
await initializedPromise;
|
|
50
|
+
if (runHeartbeat && !heartbeatRunning) {
|
|
51
|
+
heartbeatRunning = true;
|
|
52
|
+
startHeartbeat(server);
|
|
53
|
+
}
|
|
54
|
+
const errorResult = (...messages) => ({
|
|
55
|
+
content: [{ type: 'text', text: '### Result\n' + messages.join('\n') }],
|
|
56
|
+
isError: true,
|
|
57
|
+
});
|
|
58
|
+
const tool = tools.find(tool => tool.name === request.params.name);
|
|
59
|
+
if (!tool)
|
|
60
|
+
return errorResult(`Error: Tool "${request.params.name}" not found`);
|
|
61
|
+
try {
|
|
62
|
+
return await backend.callTool(tool, tool.inputSchema.parse(request.params.arguments || {}));
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
return errorResult(String(error));
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
addServerListener(server, 'initialized', () => {
|
|
69
|
+
backend.initialize?.(server).then(() => initializedPromise.resolve()).catch(logUnhandledError);
|
|
70
|
+
});
|
|
71
|
+
addServerListener(server, 'close', () => backend.serverClosed?.());
|
|
72
|
+
return server;
|
|
73
|
+
}
|
|
74
|
+
const startHeartbeat = (server) => {
|
|
75
|
+
const beat = () => {
|
|
76
|
+
Promise.race([
|
|
77
|
+
server.ping(),
|
|
78
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('ping timeout')), 5000)),
|
|
79
|
+
]).then(() => {
|
|
80
|
+
setTimeout(beat, 3000);
|
|
81
|
+
}).catch(() => {
|
|
82
|
+
void server.close();
|
|
83
|
+
});
|
|
84
|
+
};
|
|
85
|
+
beat();
|
|
86
|
+
};
|
|
87
|
+
function addServerListener(server, event, listener) {
|
|
88
|
+
const oldListener = server[`on${event}`];
|
|
89
|
+
server[`on${event}`] = () => {
|
|
90
|
+
oldListener?.();
|
|
91
|
+
listener();
|
|
92
|
+
};
|
|
93
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
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
|
+
import debug from 'debug';
|
|
18
|
+
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
|
|
19
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
20
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
21
|
+
import { httpAddressToString, startHttpServer } from '../httpServer.js';
|
|
22
|
+
import * as mcpServer from './server.js';
|
|
23
|
+
export async function start(serverBackendFactory, options) {
|
|
24
|
+
if (options.port !== undefined) {
|
|
25
|
+
const httpServer = await startHttpServer(options);
|
|
26
|
+
startHttpTransport(httpServer, serverBackendFactory);
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
await startStdioTransport(serverBackendFactory);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function startStdioTransport(serverBackendFactory) {
|
|
33
|
+
await mcpServer.connect(serverBackendFactory, new StdioServerTransport(), false);
|
|
34
|
+
}
|
|
35
|
+
const testDebug = debug('pw:mcp:test');
|
|
36
|
+
function handleHealthCheck(req, res) {
|
|
37
|
+
if (req.method !== 'GET') {
|
|
38
|
+
res.statusCode = 405;
|
|
39
|
+
res.setHeader('Content-Type', 'application/json');
|
|
40
|
+
return res.end(JSON.stringify({ error: 'Method not allowed' }));
|
|
41
|
+
}
|
|
42
|
+
res.statusCode = 200;
|
|
43
|
+
res.setHeader('Content-Type', 'application/json');
|
|
44
|
+
res.end(JSON.stringify({
|
|
45
|
+
status: 'ok',
|
|
46
|
+
service: 'playwright-mcp',
|
|
47
|
+
timestamp: new Date().toISOString()
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
async function handleSSE(serverBackendFactory, req, res, url, sessions) {
|
|
51
|
+
if (req.method === 'POST') {
|
|
52
|
+
const sessionId = url.searchParams.get('sessionId');
|
|
53
|
+
if (!sessionId) {
|
|
54
|
+
res.statusCode = 400;
|
|
55
|
+
return res.end('Missing sessionId');
|
|
56
|
+
}
|
|
57
|
+
const transport = sessions.get(sessionId);
|
|
58
|
+
if (!transport) {
|
|
59
|
+
res.statusCode = 404;
|
|
60
|
+
return res.end('Session not found');
|
|
61
|
+
}
|
|
62
|
+
return await transport.handlePostMessage(req, res);
|
|
63
|
+
}
|
|
64
|
+
else if (req.method === 'GET') {
|
|
65
|
+
const transport = new SSEServerTransport('/sse', res);
|
|
66
|
+
sessions.set(transport.sessionId, transport);
|
|
67
|
+
testDebug(`create SSE session: ${transport.sessionId}`);
|
|
68
|
+
await mcpServer.connect(serverBackendFactory, transport, false);
|
|
69
|
+
res.on('close', () => {
|
|
70
|
+
testDebug(`delete SSE session: ${transport.sessionId}`);
|
|
71
|
+
sessions.delete(transport.sessionId);
|
|
72
|
+
});
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
res.statusCode = 405;
|
|
76
|
+
res.end('Method not allowed');
|
|
77
|
+
}
|
|
78
|
+
async function handleStreamable(serverBackendFactory, req, res, sessions) {
|
|
79
|
+
const sessionId = req.headers['mcp-session-id'];
|
|
80
|
+
if (sessionId) {
|
|
81
|
+
const transport = sessions.get(sessionId);
|
|
82
|
+
if (!transport) {
|
|
83
|
+
res.statusCode = 404;
|
|
84
|
+
res.end('Session not found');
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
return await transport.handleRequest(req, res);
|
|
88
|
+
}
|
|
89
|
+
if (req.method === 'POST') {
|
|
90
|
+
const transport = new StreamableHTTPServerTransport({
|
|
91
|
+
sessionIdGenerator: () => crypto.randomUUID(),
|
|
92
|
+
onsessioninitialized: async (sessionId) => {
|
|
93
|
+
testDebug(`create http session: ${transport.sessionId}`);
|
|
94
|
+
await mcpServer.connect(serverBackendFactory, transport, true);
|
|
95
|
+
sessions.set(sessionId, transport);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
transport.onclose = () => {
|
|
99
|
+
if (!transport.sessionId)
|
|
100
|
+
return;
|
|
101
|
+
sessions.delete(transport.sessionId);
|
|
102
|
+
testDebug(`delete http session: ${transport.sessionId}`);
|
|
103
|
+
};
|
|
104
|
+
await transport.handleRequest(req, res);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
res.statusCode = 400;
|
|
108
|
+
res.end('Invalid request');
|
|
109
|
+
}
|
|
110
|
+
function startHttpTransport(httpServer, serverBackendFactory) {
|
|
111
|
+
const sseSessions = new Map();
|
|
112
|
+
const streamableSessions = new Map();
|
|
113
|
+
httpServer.on('request', async (req, res) => {
|
|
114
|
+
const url = new URL(`http://localhost${req.url}`);
|
|
115
|
+
if (url.pathname === '/health' || url.pathname === '/health/') {
|
|
116
|
+
handleHealthCheck(req, res);
|
|
117
|
+
}
|
|
118
|
+
else if (url.pathname.startsWith('/sse')) {
|
|
119
|
+
await handleSSE(serverBackendFactory, req, res, url, sseSessions);
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
await handleStreamable(serverBackendFactory, req, res, streamableSessions);
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
const url = httpAddressToString(httpServer.address());
|
|
126
|
+
const message = [
|
|
127
|
+
`Listening on ${url}`,
|
|
128
|
+
'Put this in your client config:',
|
|
129
|
+
JSON.stringify({
|
|
130
|
+
'mcpServers': {
|
|
131
|
+
'playwright': {
|
|
132
|
+
'url': `${url}/mcp`
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}, undefined, 2),
|
|
136
|
+
'For legacy SSE transport support, you can use the /sse endpoint instead.',
|
|
137
|
+
].join('\n');
|
|
138
|
+
// eslint-disable-next-line no-console
|
|
139
|
+
console.error(message);
|
|
140
|
+
}
|
package/lib/package.js
ADDED
|
@@ -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'));
|
package/lib/program.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
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 { program, Option } from 'commander';
|
|
17
|
+
// @ts-ignore
|
|
18
|
+
import { startTraceViewerServer } from 'playwright-core/lib/server';
|
|
19
|
+
import * as mcpTransport from './mcp/transport.js';
|
|
20
|
+
import { commaSeparatedList, resolveCLIConfig, semicolonSeparatedList } from './config.js';
|
|
21
|
+
import { packageJSON } from './package.js';
|
|
22
|
+
import { createExtensionContextFactory, runWithExtension } from './extension/main.js';
|
|
23
|
+
import { BrowserServerBackend } from './browserServerBackend.js';
|
|
24
|
+
import { Context } from './context.js';
|
|
25
|
+
import { contextFactory } from './browserContextFactory.js';
|
|
26
|
+
import { runLoopTools } from './loopTools/main.js';
|
|
27
|
+
program
|
|
28
|
+
.version('Version ' + packageJSON.version)
|
|
29
|
+
.name(packageJSON.name)
|
|
30
|
+
.option('--allowed-origins <origins>', 'semicolon-separated list of origins to allow the browser to request. Default is to allow all.', semicolonSeparatedList)
|
|
31
|
+
.option('--blocked-origins <origins>', 'semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.', semicolonSeparatedList)
|
|
32
|
+
.option('--block-service-workers', 'block service workers')
|
|
33
|
+
.option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')
|
|
34
|
+
.option('--caps <caps>', 'comma-separated list of additional capabilities to enable, possible values: vision, pdf.', commaSeparatedList)
|
|
35
|
+
.option('--cdp-endpoint <endpoint>', 'CDP endpoint to connect to.')
|
|
36
|
+
.option('--config <path>', 'path to the configuration file.')
|
|
37
|
+
.option('--device <device>', 'device to emulate, for example: "iPhone 15"')
|
|
38
|
+
.option('--executable-path <path>', 'path to the browser executable.')
|
|
39
|
+
.option('--headless', 'run browser in headless mode, headed by default')
|
|
40
|
+
.option('--host <host>', 'host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.')
|
|
41
|
+
.option('--ignore-https-errors', 'ignore https errors')
|
|
42
|
+
.option('--isolated', 'keep the browser profile in memory, do not save it to disk.')
|
|
43
|
+
.option('--image-responses <mode>', 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".')
|
|
44
|
+
.option('--no-sandbox', 'disable the sandbox for all process types that are normally sandboxed.')
|
|
45
|
+
.option('--output-dir <path>', 'path to the directory for output files.')
|
|
46
|
+
.option('--port <port>', 'port to listen on for SSE transport.')
|
|
47
|
+
.option('--proxy-bypass <bypass>', 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"')
|
|
48
|
+
.option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"')
|
|
49
|
+
.option('--save-session', 'Whether to save the Playwright MCP session into the output directory.')
|
|
50
|
+
.option('--save-trace', 'Whether to save the Playwright Trace of the session into the output directory.')
|
|
51
|
+
.option('--storage-state <path>', 'path to the storage state file for isolated sessions.')
|
|
52
|
+
.option('--user-agent <ua string>', 'specify user agent string')
|
|
53
|
+
.option('--user-data-dir <path>', 'path to the user data directory. If not specified, a temporary directory will be created.')
|
|
54
|
+
.option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"')
|
|
55
|
+
.addOption(new Option('--extension', 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.').hideHelp())
|
|
56
|
+
.addOption(new Option('--connect-tool', 'Allow to switch between different browser connection methods.').hideHelp())
|
|
57
|
+
.addOption(new Option('--loop-tools', 'Run loop tools').hideHelp())
|
|
58
|
+
.addOption(new Option('--vision', 'Legacy option, use --caps=vision instead').hideHelp())
|
|
59
|
+
.action(async (options) => {
|
|
60
|
+
setupExitWatchdog();
|
|
61
|
+
if (options.vision) {
|
|
62
|
+
// eslint-disable-next-line no-console
|
|
63
|
+
console.error('The --vision option is deprecated, use --caps=vision instead');
|
|
64
|
+
options.caps = 'vision';
|
|
65
|
+
}
|
|
66
|
+
const config = await resolveCLIConfig(options);
|
|
67
|
+
if (options.extension) {
|
|
68
|
+
await runWithExtension(config);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (options.loopTools) {
|
|
72
|
+
await runLoopTools(config);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const browserContextFactory = contextFactory(config);
|
|
76
|
+
const factories = [browserContextFactory];
|
|
77
|
+
if (options.connectTool)
|
|
78
|
+
factories.push(createExtensionContextFactory(config));
|
|
79
|
+
const serverBackendFactory = () => new BrowserServerBackend(config, factories);
|
|
80
|
+
await mcpTransport.start(serverBackendFactory, config.server);
|
|
81
|
+
if (config.saveTrace) {
|
|
82
|
+
const server = await startTraceViewerServer();
|
|
83
|
+
const urlPrefix = server.urlPrefix('human-readable');
|
|
84
|
+
const url = urlPrefix + '/trace/index.html?trace=' + config.browser.launchOptions.tracesDir + '/trace.json';
|
|
85
|
+
// eslint-disable-next-line no-console
|
|
86
|
+
console.error('\nTrace viewer listening on ' + url);
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
function setupExitWatchdog() {
|
|
90
|
+
let isExiting = false;
|
|
91
|
+
const handleExit = async () => {
|
|
92
|
+
if (isExiting)
|
|
93
|
+
return;
|
|
94
|
+
isExiting = true;
|
|
95
|
+
setTimeout(() => process.exit(0), 15000);
|
|
96
|
+
await Context.disposeAll();
|
|
97
|
+
process.exit(0);
|
|
98
|
+
};
|
|
99
|
+
process.stdin.on('close', handleExit);
|
|
100
|
+
process.on('SIGINT', handleExit);
|
|
101
|
+
process.on('SIGTERM', handleExit);
|
|
102
|
+
}
|
|
103
|
+
void program.parseAsync(process.argv);
|
package/lib/response.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
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 { renderModalStates } from './tab.js';
|
|
17
|
+
export class Response {
|
|
18
|
+
_result = [];
|
|
19
|
+
_code = [];
|
|
20
|
+
_images = [];
|
|
21
|
+
_context;
|
|
22
|
+
_includeSnapshot = false;
|
|
23
|
+
_includeTabs = false;
|
|
24
|
+
_tabSnapshot;
|
|
25
|
+
toolName;
|
|
26
|
+
toolArgs;
|
|
27
|
+
_isError;
|
|
28
|
+
constructor(context, toolName, toolArgs) {
|
|
29
|
+
this._context = context;
|
|
30
|
+
this.toolName = toolName;
|
|
31
|
+
this.toolArgs = toolArgs;
|
|
32
|
+
}
|
|
33
|
+
addResult(result) {
|
|
34
|
+
this._result.push(result);
|
|
35
|
+
}
|
|
36
|
+
addError(error) {
|
|
37
|
+
this._result.push(error);
|
|
38
|
+
this._isError = true;
|
|
39
|
+
}
|
|
40
|
+
isError() {
|
|
41
|
+
return this._isError;
|
|
42
|
+
}
|
|
43
|
+
result() {
|
|
44
|
+
return this._result.join('\n');
|
|
45
|
+
}
|
|
46
|
+
addCode(code) {
|
|
47
|
+
this._code.push(code);
|
|
48
|
+
}
|
|
49
|
+
code() {
|
|
50
|
+
return this._code.join('\n');
|
|
51
|
+
}
|
|
52
|
+
addImage(image) {
|
|
53
|
+
this._images.push(image);
|
|
54
|
+
}
|
|
55
|
+
images() {
|
|
56
|
+
return this._images;
|
|
57
|
+
}
|
|
58
|
+
setIncludeSnapshot() {
|
|
59
|
+
this._includeSnapshot = true;
|
|
60
|
+
}
|
|
61
|
+
setIncludeTabs() {
|
|
62
|
+
this._includeTabs = true;
|
|
63
|
+
}
|
|
64
|
+
async finish() {
|
|
65
|
+
// All the async snapshotting post-action is happening here.
|
|
66
|
+
// Everything below should race against modal states.
|
|
67
|
+
if (this._includeSnapshot && this._context.currentTab())
|
|
68
|
+
this._tabSnapshot = await this._context.currentTabOrDie().captureSnapshot();
|
|
69
|
+
for (const tab of this._context.tabs())
|
|
70
|
+
await tab.updateTitle();
|
|
71
|
+
}
|
|
72
|
+
tabSnapshot() {
|
|
73
|
+
return this._tabSnapshot;
|
|
74
|
+
}
|
|
75
|
+
serialize() {
|
|
76
|
+
const response = [];
|
|
77
|
+
// Start with command result.
|
|
78
|
+
if (this._result.length) {
|
|
79
|
+
response.push('### Result');
|
|
80
|
+
response.push(this._result.join('\n'));
|
|
81
|
+
response.push('');
|
|
82
|
+
}
|
|
83
|
+
// Add code if it exists.
|
|
84
|
+
if (this._code.length) {
|
|
85
|
+
response.push(`### Ran Playwright code
|
|
86
|
+
\`\`\`js
|
|
87
|
+
${this._code.join('\n')}
|
|
88
|
+
\`\`\``);
|
|
89
|
+
response.push('');
|
|
90
|
+
}
|
|
91
|
+
// List browser tabs.
|
|
92
|
+
if (this._includeSnapshot || this._includeTabs)
|
|
93
|
+
response.push(...renderTabsMarkdown(this._context.tabs(), this._includeTabs));
|
|
94
|
+
// Add snapshot if provided.
|
|
95
|
+
if (this._tabSnapshot?.modalStates.length) {
|
|
96
|
+
response.push(...renderModalStates(this._context, this._tabSnapshot.modalStates));
|
|
97
|
+
response.push('');
|
|
98
|
+
}
|
|
99
|
+
else if (this._tabSnapshot) {
|
|
100
|
+
response.push(renderTabSnapshot(this._tabSnapshot));
|
|
101
|
+
response.push('');
|
|
102
|
+
}
|
|
103
|
+
// Main response part
|
|
104
|
+
const content = [
|
|
105
|
+
{ type: 'text', text: response.join('\n') },
|
|
106
|
+
];
|
|
107
|
+
// Image attachments.
|
|
108
|
+
if (this._context.config.imageResponses !== 'omit') {
|
|
109
|
+
for (const image of this._images)
|
|
110
|
+
content.push({ type: 'image', data: image.data.toString('base64'), mimeType: image.contentType });
|
|
111
|
+
}
|
|
112
|
+
return { content, isError: this._isError };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function renderTabSnapshot(tabSnapshot) {
|
|
116
|
+
const lines = [];
|
|
117
|
+
if (tabSnapshot.consoleMessages.length) {
|
|
118
|
+
lines.push(`### New console messages`);
|
|
119
|
+
for (const message of tabSnapshot.consoleMessages)
|
|
120
|
+
lines.push(`- ${trim(message.toString(), 100)}`);
|
|
121
|
+
lines.push('');
|
|
122
|
+
}
|
|
123
|
+
if (tabSnapshot.downloads.length) {
|
|
124
|
+
lines.push(`### Downloads`);
|
|
125
|
+
for (const entry of tabSnapshot.downloads) {
|
|
126
|
+
if (entry.finished)
|
|
127
|
+
lines.push(`- Downloaded file ${entry.download.suggestedFilename()} to ${entry.outputFile}`);
|
|
128
|
+
else
|
|
129
|
+
lines.push(`- Downloading file ${entry.download.suggestedFilename()} ...`);
|
|
130
|
+
}
|
|
131
|
+
lines.push('');
|
|
132
|
+
}
|
|
133
|
+
lines.push(`### Page state`);
|
|
134
|
+
lines.push(`- Page URL: ${tabSnapshot.url}`);
|
|
135
|
+
lines.push(`- Page Title: ${tabSnapshot.title}`);
|
|
136
|
+
lines.push(`- Page Snapshot:`);
|
|
137
|
+
lines.push('```yaml');
|
|
138
|
+
lines.push(tabSnapshot.ariaSnapshot);
|
|
139
|
+
lines.push('```');
|
|
140
|
+
return lines.join('\n');
|
|
141
|
+
}
|
|
142
|
+
function renderTabsMarkdown(tabs, force = false) {
|
|
143
|
+
if (tabs.length === 1 && !force)
|
|
144
|
+
return [];
|
|
145
|
+
if (!tabs.length) {
|
|
146
|
+
return [
|
|
147
|
+
'### Open tabs',
|
|
148
|
+
'No open tabs. Use the "browser_navigate" tool to navigate to a page first.',
|
|
149
|
+
'',
|
|
150
|
+
];
|
|
151
|
+
}
|
|
152
|
+
const lines = ['### Open tabs'];
|
|
153
|
+
for (let i = 0; i < tabs.length; i++) {
|
|
154
|
+
const tab = tabs[i];
|
|
155
|
+
const current = tab.isCurrentTab() ? ' (current)' : '';
|
|
156
|
+
lines.push(`- ${i}:${current} [${tab.lastTitle()}] (${tab.page.url()})`);
|
|
157
|
+
}
|
|
158
|
+
lines.push('');
|
|
159
|
+
return lines;
|
|
160
|
+
}
|
|
161
|
+
function trim(text, maxLength) {
|
|
162
|
+
if (text.length <= maxLength)
|
|
163
|
+
return text;
|
|
164
|
+
return text.slice(0, maxLength) + '...';
|
|
165
|
+
}
|