playwright 1.56.0-alpha-2025-09-03 → 1.56.0-alpha-1756945786000

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.
Files changed (59) hide show
  1. package/README.md +2 -2
  2. package/ThirdPartyNotices.txt +3 -3
  3. package/lib/index.js +2 -2
  4. package/lib/matchers/toBeTruthy.js +3 -3
  5. package/lib/matchers/toEqual.js +3 -3
  6. package/lib/matchers/toMatchText.js +3 -3
  7. package/lib/mcp/browser/actions.d.js +16 -0
  8. package/lib/mcp/browser/browserContextFactory.js +227 -0
  9. package/lib/mcp/browser/browserServerBackend.js +82 -0
  10. package/lib/mcp/browser/codegen.js +64 -0
  11. package/lib/mcp/browser/config.js +279 -0
  12. package/lib/mcp/browser/context.js +229 -0
  13. package/lib/mcp/browser/response.js +163 -0
  14. package/lib/mcp/browser/sessionLog.js +160 -0
  15. package/lib/mcp/browser/tab.js +256 -0
  16. package/lib/mcp/browser/tools/common.js +63 -0
  17. package/lib/mcp/browser/tools/console.js +41 -0
  18. package/lib/mcp/browser/tools/dialogs.js +55 -0
  19. package/lib/mcp/browser/tools/evaluate.js +70 -0
  20. package/lib/mcp/browser/tools/files.js +52 -0
  21. package/lib/mcp/browser/tools/form.js +73 -0
  22. package/lib/mcp/browser/tools/install.js +69 -0
  23. package/lib/mcp/browser/tools/keyboard.js +95 -0
  24. package/lib/mcp/browser/tools/mouse.js +107 -0
  25. package/lib/mcp/browser/tools/navigate.js +62 -0
  26. package/lib/mcp/browser/tools/network.js +49 -0
  27. package/lib/mcp/{sdk/call.js → browser/tools/pdf.js} +27 -18
  28. package/lib/mcp/browser/tools/screenshot.js +94 -0
  29. package/lib/mcp/browser/tools/snapshot.js +162 -0
  30. package/lib/mcp/browser/tools/tabs.js +67 -0
  31. package/lib/mcp/browser/tools/tool.js +49 -0
  32. package/lib/mcp/browser/tools/utils.js +90 -0
  33. package/lib/mcp/browser/tools/verify.js +154 -0
  34. package/lib/mcp/browser/tools/wait.js +63 -0
  35. package/lib/mcp/browser/tools.js +42 -83
  36. package/lib/mcp/config.d.js +16 -0
  37. package/lib/mcp/extension/cdpRelay.js +348 -0
  38. package/lib/mcp/extension/extensionContextFactory.js +75 -0
  39. package/lib/mcp/{browser/tool.js → extension/protocol.js} +6 -8
  40. package/lib/mcp/index.js +61 -0
  41. package/lib/mcp/log.js +35 -0
  42. package/lib/mcp/program.js +96 -0
  43. package/lib/mcp/sdk/bundle.js +11 -1
  44. package/lib/mcp/sdk/exports.js +2 -2
  45. package/lib/mcp/sdk/http.js +21 -6
  46. package/lib/mcp/sdk/mdb.js +16 -15
  47. package/lib/mcp/sdk/proxyBackend.js +7 -6
  48. package/lib/mcp/sdk/server.js +6 -6
  49. package/lib/mcp/sdk/tool.js +1 -1
  50. package/lib/mcp/{browser/backend.js → test/browserBackend.js} +7 -9
  51. package/lib/mcp/test/browserTool.js +30 -0
  52. package/lib/mcp/test/browserTools.js +120 -0
  53. package/lib/mcp/test/{backend.js → testBackend.js} +12 -12
  54. package/lib/mcp/test/{context.js → testContext.js} +6 -6
  55. package/lib/mcp/test/{tool.js → testTool.js} +6 -6
  56. package/lib/mcp/test/{tools.js → testTools.js} +7 -7
  57. package/lib/mcpBundleImpl.js +11 -11
  58. package/lib/program.js +4 -4
  59. package/package.json +6 -3
@@ -28,92 +28,51 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var tools_exports = {};
30
30
  __export(tools_exports, {
31
- elementSchema: () => elementSchema,
32
- evaluate: () => evaluate,
33
- pickLocator: () => pickLocator,
34
- snapshot: () => snapshot
31
+ allTools: () => allTools,
32
+ filteredTools: () => filteredTools
35
33
  });
36
34
  module.exports = __toCommonJS(tools_exports);
37
- var import_utils = require("playwright-core/lib/utils");
38
- var import_tool = require("./tool.js");
39
- var mcp = __toESM(require("../sdk/bundle"));
40
- const snapshot = (0, import_tool.defineTool)({
41
- schema: {
42
- name: "playwright_test_browser_snapshot",
43
- title: "Capture page snapshot",
44
- description: "Capture page snapshot for debugging",
45
- inputSchema: mcp.z.object({}),
46
- type: "readOnly"
47
- },
48
- handle: async (page, params) => {
49
- const snapshot2 = await page._snapshotForAI();
50
- return {
51
- content: [
52
- {
53
- type: "text",
54
- text: snapshot2
55
- }
56
- ]
57
- };
58
- }
59
- });
60
- const elementSchema = mcp.z.object({
61
- element: mcp.z.string().describe("Human-readable element description used to obtain permission to interact with the element"),
62
- ref: mcp.z.string().describe("Exact target element reference from the page snapshot")
63
- });
64
- const pickLocator = (0, import_tool.defineTool)({
65
- schema: {
66
- name: "playwright_test_generate_locator",
67
- title: "Create locator for element",
68
- description: "Generate locator for the given element to use in tests",
69
- inputSchema: elementSchema,
70
- type: "readOnly"
71
- },
72
- handle: async (page, params) => {
73
- const locator = await refLocator(page, params);
74
- try {
75
- const { resolvedSelector } = await locator._resolveSelector();
76
- const locatorString = (0, import_utils.asLocator)("javascript", resolvedSelector);
77
- return { content: [{ type: "text", text: locatorString }] };
78
- } catch (e) {
79
- throw new Error(`Ref not found, likely because element was removed. Use ${snapshot.schema.name} to see what elements are currently on the page.`);
80
- }
81
- }
82
- });
83
- const evaluateSchema = mcp.z.object({
84
- function: mcp.z.string().describe("() => { /* code */ } or (element) => { /* code */ } when element is provided"),
85
- element: mcp.z.string().optional().describe("Human-readable element description used to obtain permission to interact with the element"),
86
- ref: mcp.z.string().optional().describe("Exact target element reference from the page snapshot")
87
- });
88
- const evaluate = (0, import_tool.defineTool)({
89
- schema: {
90
- name: "playwright_test_evaluate_on_pause",
91
- title: "Evaluate in page",
92
- description: "Evaluate JavaScript expression on page or element",
93
- inputSchema: evaluateSchema,
94
- type: "destructive"
95
- },
96
- handle: async (page, params) => {
97
- let locator;
98
- if (params.ref && params.element)
99
- locator = await refLocator(page, { ref: params.ref, element: params.element });
100
- const receiver = locator ?? page;
101
- const result = await receiver._evaluateFunction(params.function);
102
- return {
103
- content: [{ type: "text", text: JSON.stringify(result, null, 2) || "undefined" }]
104
- };
105
- }
106
- });
107
- async function refLocator(page, elementRef) {
108
- const snapshot2 = await page._snapshotForAI();
109
- if (!snapshot2.includes(`[ref=${elementRef.ref}]`))
110
- throw new Error(`Ref ${elementRef.ref} not found in the current page snapshot. Try capturing new snapshot.`);
111
- return page.locator(`aria-ref=${elementRef.ref}`).describe(elementRef.element);
35
+ var import_common = __toESM(require("./tools/common"));
36
+ var import_console = __toESM(require("./tools/console"));
37
+ var import_dialogs = __toESM(require("./tools/dialogs"));
38
+ var import_evaluate = __toESM(require("./tools/evaluate"));
39
+ var import_files = __toESM(require("./tools/files"));
40
+ var import_form = __toESM(require("./tools/form"));
41
+ var import_install = __toESM(require("./tools/install"));
42
+ var import_keyboard = __toESM(require("./tools/keyboard"));
43
+ var import_mouse = __toESM(require("./tools/mouse"));
44
+ var import_navigate = __toESM(require("./tools/navigate"));
45
+ var import_network = __toESM(require("./tools/network"));
46
+ var import_pdf = __toESM(require("./tools/pdf"));
47
+ var import_snapshot = __toESM(require("./tools/snapshot"));
48
+ var import_tabs = __toESM(require("./tools/tabs"));
49
+ var import_screenshot = __toESM(require("./tools/screenshot"));
50
+ var import_wait = __toESM(require("./tools/wait"));
51
+ var import_verify = __toESM(require("./tools/verify"));
52
+ const allTools = [
53
+ ...import_common.default,
54
+ ...import_console.default,
55
+ ...import_dialogs.default,
56
+ ...import_evaluate.default,
57
+ ...import_files.default,
58
+ ...import_form.default,
59
+ ...import_install.default,
60
+ ...import_keyboard.default,
61
+ ...import_navigate.default,
62
+ ...import_network.default,
63
+ ...import_mouse.default,
64
+ ...import_pdf.default,
65
+ ...import_screenshot.default,
66
+ ...import_snapshot.default,
67
+ ...import_tabs.default,
68
+ ...import_wait.default,
69
+ ...import_verify.default
70
+ ];
71
+ function filteredTools(config) {
72
+ return allTools.filter((tool) => tool.capability.startsWith("core") || config.capabilities?.includes(tool.capability));
112
73
  }
113
74
  // Annotate the CommonJS export names for ESM import in node:
114
75
  0 && (module.exports = {
115
- elementSchema,
116
- evaluate,
117
- pickLocator,
118
- snapshot
76
+ allTools,
77
+ filteredTools
119
78
  });
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var config_d_exports = {};
16
+ module.exports = __toCommonJS(config_d_exports);
@@ -0,0 +1,348 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var cdpRelay_exports = {};
30
+ __export(cdpRelay_exports, {
31
+ CDPRelayServer: () => CDPRelayServer
32
+ });
33
+ module.exports = __toCommonJS(cdpRelay_exports);
34
+ var import_child_process = require("child_process");
35
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
36
+ var import_registry = require("playwright-core/lib/server/registry/index");
37
+ var import_utils = require("playwright-core/lib/utils");
38
+ var import_http2 = require("../sdk/http");
39
+ var import_log = require("../log");
40
+ var protocol = __toESM(require("./protocol"));
41
+ const debugLogger = (0, import_utilsBundle.debug)("pw:mcp:relay");
42
+ class CDPRelayServer {
43
+ constructor(server, browserChannel, userDataDir, executablePath) {
44
+ this._playwrightConnection = null;
45
+ this._extensionConnection = null;
46
+ this._nextSessionId = 1;
47
+ this._wsHost = (0, import_http2.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 import_utilsBundle.wsServer({ 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) : 5e3)),
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
+ const url = new URL("chrome-extension://jakfalbnbhgkpmoaakfflhflbfpkailf/connect.html");
82
+ url.searchParams.set("mcpRelayUrl", mcpRelayEndpoint);
83
+ const client = {
84
+ name: clientInfo.name,
85
+ version: clientInfo.version
86
+ };
87
+ url.searchParams.set("client", JSON.stringify(client));
88
+ url.searchParams.set("protocolVersion", process.env.PWMCP_TEST_PROTOCOL_VERSION ?? protocol.VERSION.toString());
89
+ if (toolName)
90
+ url.searchParams.set("newTab", String(toolName === "browser_navigate"));
91
+ const href = url.toString();
92
+ let executablePath = this._executablePath;
93
+ if (!executablePath) {
94
+ const executableInfo = import_registry.registry.findExecutable(this._browserChannel);
95
+ if (!executableInfo)
96
+ throw new Error(`Unsupported channel: "${this._browserChannel}"`);
97
+ executablePath = executableInfo.executablePath("javascript");
98
+ if (!executablePath)
99
+ throw new Error(`"${this._browserChannel}" executable not found. Make sure it is installed at a standard location.`);
100
+ }
101
+ const args = [];
102
+ if (this._userDataDir)
103
+ args.push(`--user-data-dir=${this._userDataDir}`);
104
+ args.push(href);
105
+ (0, import_child_process.spawn)(executablePath, args, {
106
+ windowsHide: true,
107
+ detached: true,
108
+ shell: false,
109
+ stdio: "ignore"
110
+ });
111
+ }
112
+ stop() {
113
+ this.closeConnections("Server stopped");
114
+ this._wss.close();
115
+ }
116
+ closeConnections(reason) {
117
+ this._closePlaywrightConnection(reason);
118
+ this._closeExtensionConnection(reason);
119
+ }
120
+ _onConnection(ws2, request) {
121
+ const url = new URL(`http://localhost${request.url}`);
122
+ debugLogger(`New connection to ${url.pathname}`);
123
+ if (url.pathname === this._cdpPath) {
124
+ this._handlePlaywrightConnection(ws2);
125
+ } else if (url.pathname === this._extensionPath) {
126
+ this._handleExtensionConnection(ws2);
127
+ } else {
128
+ debugLogger(`Invalid path: ${url.pathname}`);
129
+ ws2.close(4004, "Invalid path");
130
+ }
131
+ }
132
+ _handlePlaywrightConnection(ws2) {
133
+ if (this._playwrightConnection) {
134
+ debugLogger("Rejecting second Playwright connection");
135
+ ws2.close(1e3, "Another CDP client already connected");
136
+ return;
137
+ }
138
+ this._playwrightConnection = ws2;
139
+ ws2.on("message", async (data) => {
140
+ try {
141
+ const message = JSON.parse(data.toString());
142
+ await this._handlePlaywrightMessage(message);
143
+ } catch (error) {
144
+ debugLogger(`Error while handling Playwright message
145
+ ${data.toString()}
146
+ `, error);
147
+ }
148
+ });
149
+ ws2.on("close", () => {
150
+ if (this._playwrightConnection !== ws2)
151
+ return;
152
+ this._playwrightConnection = null;
153
+ this._closeExtensionConnection("Playwright client disconnected");
154
+ debugLogger("Playwright WebSocket closed");
155
+ });
156
+ ws2.on("error", (error) => {
157
+ debugLogger("Playwright WebSocket error:", error);
158
+ });
159
+ debugLogger("Playwright MCP connected");
160
+ }
161
+ _closeExtensionConnection(reason) {
162
+ this._extensionConnection?.close(reason);
163
+ this._extensionConnectionPromise.reject(new Error(reason));
164
+ this._resetExtensionConnection();
165
+ }
166
+ _resetExtensionConnection() {
167
+ this._connectedTabInfo = void 0;
168
+ this._extensionConnection = null;
169
+ this._extensionConnectionPromise = new import_utils.ManualPromise();
170
+ void this._extensionConnectionPromise.catch(import_log.logUnhandledError);
171
+ }
172
+ _closePlaywrightConnection(reason) {
173
+ if (this._playwrightConnection?.readyState === import_utilsBundle.ws.OPEN)
174
+ this._playwrightConnection.close(1e3, reason);
175
+ this._playwrightConnection = null;
176
+ }
177
+ _handleExtensionConnection(ws2) {
178
+ if (this._extensionConnection) {
179
+ ws2.close(1e3, "Another extension connection already established");
180
+ return;
181
+ }
182
+ this._extensionConnection = new ExtensionConnection(ws2);
183
+ this._extensionConnection.onclose = (c, reason) => {
184
+ debugLogger("Extension WebSocket closed:", reason, c === this._extensionConnection);
185
+ if (this._extensionConnection !== c)
186
+ return;
187
+ this._resetExtensionConnection();
188
+ this._closePlaywrightConnection(`Extension disconnected: ${reason}`);
189
+ };
190
+ this._extensionConnection.onmessage = this._handleExtensionMessage.bind(this);
191
+ this._extensionConnectionPromise.resolve();
192
+ }
193
+ _handleExtensionMessage(method, params) {
194
+ switch (method) {
195
+ case "forwardCDPEvent":
196
+ const sessionId = params.sessionId || this._connectedTabInfo?.sessionId;
197
+ this._sendToPlaywright({
198
+ sessionId,
199
+ method: params.method,
200
+ params: params.params
201
+ });
202
+ break;
203
+ }
204
+ }
205
+ async _handlePlaywrightMessage(message) {
206
+ debugLogger("\u2190 Playwright:", `${message.method} (id=${message.id})`);
207
+ const { id, sessionId, method, params } = message;
208
+ try {
209
+ const result = await this._handleCDPCommand(method, params, sessionId);
210
+ this._sendToPlaywright({ id, sessionId, result });
211
+ } catch (e) {
212
+ debugLogger("Error in the extension:", e);
213
+ this._sendToPlaywright({
214
+ id,
215
+ sessionId,
216
+ error: { message: e.message }
217
+ });
218
+ }
219
+ }
220
+ async _handleCDPCommand(method, params, sessionId) {
221
+ switch (method) {
222
+ case "Browser.getVersion": {
223
+ return {
224
+ protocolVersion: "1.3",
225
+ product: "Chrome/Extension-Bridge",
226
+ userAgent: "CDP-Bridge-Server/1.0.0"
227
+ };
228
+ }
229
+ case "Browser.setDownloadBehavior": {
230
+ return {};
231
+ }
232
+ case "Target.setAutoAttach": {
233
+ if (sessionId)
234
+ break;
235
+ const { targetInfo } = await this._extensionConnection.send("attachToTab", {});
236
+ this._connectedTabInfo = {
237
+ targetInfo,
238
+ sessionId: `pw-tab-${this._nextSessionId++}`
239
+ };
240
+ debugLogger("Simulating auto-attach");
241
+ this._sendToPlaywright({
242
+ method: "Target.attachedToTarget",
243
+ params: {
244
+ sessionId: this._connectedTabInfo.sessionId,
245
+ targetInfo: {
246
+ ...this._connectedTabInfo.targetInfo,
247
+ attached: true
248
+ },
249
+ waitingForDebugger: false
250
+ }
251
+ });
252
+ return {};
253
+ }
254
+ case "Target.getTargetInfo": {
255
+ return this._connectedTabInfo?.targetInfo;
256
+ }
257
+ }
258
+ return await this._forwardToExtension(method, params, sessionId);
259
+ }
260
+ async _forwardToExtension(method, params, sessionId) {
261
+ if (!this._extensionConnection)
262
+ throw new Error("Extension not connected");
263
+ if (this._connectedTabInfo?.sessionId === sessionId)
264
+ sessionId = void 0;
265
+ return await this._extensionConnection.send("forwardCDPCommand", { sessionId, method, params });
266
+ }
267
+ _sendToPlaywright(message) {
268
+ debugLogger("\u2192 Playwright:", `${message.method ?? `response(id=${message.id})`}`);
269
+ this._playwrightConnection?.send(JSON.stringify(message));
270
+ }
271
+ }
272
+ class ExtensionConnection {
273
+ constructor(ws2) {
274
+ this._callbacks = /* @__PURE__ */ new Map();
275
+ this._lastId = 0;
276
+ this._ws = ws2;
277
+ this._ws.on("message", this._onMessage.bind(this));
278
+ this._ws.on("close", this._onClose.bind(this));
279
+ this._ws.on("error", this._onError.bind(this));
280
+ }
281
+ async send(method, params) {
282
+ if (this._ws.readyState !== import_utilsBundle.ws.OPEN)
283
+ throw new Error(`Unexpected WebSocket state: ${this._ws.readyState}`);
284
+ const id = ++this._lastId;
285
+ this._ws.send(JSON.stringify({ id, method, params }));
286
+ const error = new Error(`Protocol error: ${method}`);
287
+ return new Promise((resolve, reject) => {
288
+ this._callbacks.set(id, { resolve, reject, error });
289
+ });
290
+ }
291
+ close(message) {
292
+ debugLogger("closing extension connection:", message);
293
+ if (this._ws.readyState === import_utilsBundle.ws.OPEN)
294
+ this._ws.close(1e3, message);
295
+ }
296
+ _onMessage(event) {
297
+ const eventData = event.toString();
298
+ let parsedJson;
299
+ try {
300
+ parsedJson = JSON.parse(eventData);
301
+ } catch (e) {
302
+ debugLogger(`<closing ws> Closing websocket due to malformed JSON. eventData=${eventData} e=${e?.message}`);
303
+ this._ws.close();
304
+ return;
305
+ }
306
+ try {
307
+ this._handleParsedMessage(parsedJson);
308
+ } catch (e) {
309
+ debugLogger(`<closing ws> Closing websocket due to failed onmessage callback. eventData=${eventData} e=${e?.message}`);
310
+ this._ws.close();
311
+ }
312
+ }
313
+ _handleParsedMessage(object) {
314
+ if (object.id && this._callbacks.has(object.id)) {
315
+ const callback = this._callbacks.get(object.id);
316
+ this._callbacks.delete(object.id);
317
+ if (object.error) {
318
+ const error = callback.error;
319
+ error.message = object.error;
320
+ callback.reject(error);
321
+ } else {
322
+ callback.resolve(object.result);
323
+ }
324
+ } else if (object.id) {
325
+ debugLogger("\u2190 Extension: unexpected response", object);
326
+ } else {
327
+ this.onmessage?.(object.method, object.params);
328
+ }
329
+ }
330
+ _onClose(event) {
331
+ debugLogger(`<ws closed> code=${event.code} reason=${event.reason}`);
332
+ this._dispose();
333
+ this.onclose?.(this, event.reason);
334
+ }
335
+ _onError(event) {
336
+ debugLogger(`<ws error> message=${event.message} type=${event.type} target=${event.target}`);
337
+ this._dispose();
338
+ }
339
+ _dispose() {
340
+ for (const callback of this._callbacks.values())
341
+ callback.reject(new Error("WebSocket closed"));
342
+ this._callbacks.clear();
343
+ }
344
+ }
345
+ // Annotate the CommonJS export names for ESM import in node:
346
+ 0 && (module.exports = {
347
+ CDPRelayServer
348
+ });
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var extensionContextFactory_exports = {};
30
+ __export(extensionContextFactory_exports, {
31
+ ExtensionContextFactory: () => ExtensionContextFactory
32
+ });
33
+ module.exports = __toCommonJS(extensionContextFactory_exports);
34
+ var playwright = __toESM(require("playwright-core"));
35
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
36
+ var import_http = require("../sdk/http");
37
+ var import_cdpRelay = require("./cdpRelay");
38
+ const debugLogger = (0, import_utilsBundle.debug)("pw:mcp:relay");
39
+ class ExtensionContextFactory {
40
+ constructor(browserChannel, userDataDir, executablePath) {
41
+ this._browserChannel = browserChannel;
42
+ this._userDataDir = userDataDir;
43
+ this._executablePath = executablePath;
44
+ }
45
+ async createContext(clientInfo, abortSignal, toolName) {
46
+ const browser = await this._obtainBrowser(clientInfo, abortSignal, toolName);
47
+ return {
48
+ browserContext: browser.contexts()[0],
49
+ close: async () => {
50
+ debugLogger("close() called for browser context");
51
+ await browser.close();
52
+ }
53
+ };
54
+ }
55
+ async _obtainBrowser(clientInfo, abortSignal, toolName) {
56
+ const relay = await this._startRelay(abortSignal);
57
+ await relay.ensureExtensionConnectionForMCPContext(clientInfo, abortSignal, toolName);
58
+ return await playwright.chromium.connectOverCDP(relay.cdpEndpoint());
59
+ }
60
+ async _startRelay(abortSignal) {
61
+ const httpServer = await (0, import_http.startHttpServer)({});
62
+ if (abortSignal.aborted) {
63
+ httpServer.close();
64
+ throw new Error(abortSignal.reason);
65
+ }
66
+ const cdpRelayServer = new import_cdpRelay.CDPRelayServer(httpServer, this._browserChannel, this._userDataDir, this._executablePath);
67
+ abortSignal.addEventListener("abort", () => cdpRelayServer.stop());
68
+ debugLogger(`CDP relay server started, extension endpoint: ${cdpRelayServer.extensionEndpoint()}.`);
69
+ return cdpRelayServer;
70
+ }
71
+ }
72
+ // Annotate the CommonJS export names for ESM import in node:
73
+ 0 && (module.exports = {
74
+ ExtensionContextFactory
75
+ });
@@ -16,15 +16,13 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var tool_exports = {};
20
- __export(tool_exports, {
21
- defineTool: () => defineTool
19
+ var protocol_exports = {};
20
+ __export(protocol_exports, {
21
+ VERSION: () => VERSION
22
22
  });
23
- module.exports = __toCommonJS(tool_exports);
24
- function defineTool(tool) {
25
- return tool;
26
- }
23
+ module.exports = __toCommonJS(protocol_exports);
24
+ const VERSION = 1;
27
25
  // Annotate the CommonJS export names for ESM import in node:
28
26
  0 && (module.exports = {
29
- defineTool
27
+ VERSION
30
28
  });
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var mcp_exports = {};
30
+ __export(mcp_exports, {
31
+ createConnection: () => createConnection
32
+ });
33
+ module.exports = __toCommonJS(mcp_exports);
34
+ var import_browserServerBackend = require("./browser/browserServerBackend");
35
+ var import_config = require("./browser/config");
36
+ var import_browserContextFactory = require("./browser/browserContextFactory");
37
+ var mcpServer = __toESM(require("./sdk/server"));
38
+ const packageJSON = require("../../package.json");
39
+ async function createConnection(userConfig = {}, contextGetter) {
40
+ const config = await (0, import_config.resolveConfig)(userConfig);
41
+ const factory = contextGetter ? new SimpleBrowserContextFactory(contextGetter) : (0, import_browserContextFactory.contextFactory)(config);
42
+ return mcpServer.createServer("Playwright", packageJSON.version, new import_browserServerBackend.BrowserServerBackend(config, factory), false);
43
+ }
44
+ class SimpleBrowserContextFactory {
45
+ constructor(contextGetter) {
46
+ this.name = "custom";
47
+ this.description = "Connect to a browser using a custom context getter";
48
+ this._contextGetter = contextGetter;
49
+ }
50
+ async createContext() {
51
+ const browserContext = await this._contextGetter();
52
+ return {
53
+ browserContext,
54
+ close: () => browserContext.close()
55
+ };
56
+ }
57
+ }
58
+ // Annotate the CommonJS export names for ESM import in node:
59
+ 0 && (module.exports = {
60
+ createConnection
61
+ });