@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 ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Portions Copyright (c) Microsoft Corporation.
190
+ Portions Copyright 2017 Google Inc.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,237 @@
1
+ ## Playwright MCP
2
+
3
+ A Model Context Protocol (MCP) server that provides browser automation capabilities using [Playwright](https://playwright.dev). This server enables LLMs to interact with web pages through structured accessibility snapshots, bypassing the need for screenshots or visually-tuned models.
4
+
5
+ ### Key Features
6
+
7
+ - **Fast and lightweight**: Uses Playwright’s accessibility tree, not pixel-based input.
8
+ - **LLM-friendly**: No vision models needed, operates purely on structured data.
9
+ - **Deterministic tool application**: Avoids ambiguity common with screenshot-based approaches.
10
+
11
+ ### Use Cases
12
+
13
+ - Web navigation and form-filling
14
+ - Data extraction from structured content
15
+ - Automated testing driven by LLMs
16
+ - General-purpose browser interaction for agents
17
+
18
+ ### Example config
19
+
20
+ ```js
21
+ {
22
+ "mcpServers": {
23
+ "playwright": {
24
+ "command": "npx",
25
+ "args": [
26
+ "@playwright/mcp",
27
+ ]
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ ### Running headless browser (Browser without GUI).
34
+
35
+ This mode is useful for background or batch operations.
36
+
37
+ ```js
38
+ {
39
+ "mcpServers": {
40
+ "playwright": {
41
+ "command": "npx",
42
+ "args": [
43
+ "@playwright/mcp",
44
+ "--headless"
45
+ ]
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ ### Running headed browser on Linux w/o DISPLAY
52
+
53
+ When running headed browser on system w/o display or from worker processes of the IDEs,
54
+ you can run Playwright in a client-server manner. You'll run the Playwright server
55
+ from environment with the DISPLAY
56
+
57
+ ```sh
58
+ npx playwright run-server
59
+ ```
60
+
61
+ And then in MCP config, add following to the `env`:
62
+
63
+ ```js
64
+ {
65
+ "mcpServers": {
66
+ "playwright": {
67
+ "command": "npx",
68
+ "args": [
69
+ "@playwright/mcp"
70
+ ],
71
+ "env": {
72
+ // Use the endpoint from the output of the server above.
73
+ "PLAYWRIGHT_WS_ENDPOINT": "ws://localhost:<port>/"
74
+ }
75
+ }
76
+ }
77
+ }
78
+ ```
79
+
80
+ ### Tool Modes
81
+
82
+ The tools are available in two modes:
83
+
84
+ 1. **Snapshot Mode** (default): Uses accessibility snapshots for better performance and reliability
85
+ 2. **Vision Mode**: Uses screenshots for visual-based interactions
86
+
87
+ To use Vision Mode, add the `--vision` flag when starting the server:
88
+
89
+ ```js
90
+ {
91
+ "mcpServers": {
92
+ "playwright": {
93
+ "command": "npx",
94
+ "args": [
95
+ "@playwright/mcp",
96
+ "--vision"
97
+ ]
98
+ }
99
+ }
100
+ }
101
+ ```
102
+
103
+ Vision Mode works best with the computer use models that are able to interact with elements using
104
+ X Y coordinate space, based on the provided screenshot.
105
+
106
+ ### Snapshot Mode
107
+
108
+ The Playwright MCP provides a set of tools for browser automation. Here are all available tools:
109
+
110
+ - **browser_navigate**
111
+ - Description: Navigate to a URL
112
+ - Parameters:
113
+ - `url` (string): The URL to navigate to
114
+
115
+ - **browser_go_back**
116
+ - Description: Go back to the previous page
117
+ - Parameters: None
118
+
119
+ - **browser_go_forward**
120
+ - Description: Go forward to the next page
121
+ - Parameters: None
122
+
123
+ - **browser_click**
124
+ - Description: Perform click on a web page
125
+ - Parameters:
126
+ - `element` (string): Human-readable element description used to obtain permission to interact with the element
127
+ - `ref` (string): Exact target element reference from the page snapshot
128
+
129
+ - **browser_hover**
130
+ - Description: Hover over element on page
131
+ - Parameters:
132
+ - `element` (string): Human-readable element description used to obtain permission to interact with the element
133
+ - `ref` (string): Exact target element reference from the page snapshot
134
+
135
+ - **browser_drag**
136
+ - Description: Perform drag and drop between two elements
137
+ - Parameters:
138
+ - `startElement` (string): Human-readable source element description used to obtain permission to interact with the element
139
+ - `startRef` (string): Exact source element reference from the page snapshot
140
+ - `endElement` (string): Human-readable target element description used to obtain permission to interact with the element
141
+ - `endRef` (string): Exact target element reference from the page snapshot
142
+
143
+ - **browser_type**
144
+ - Description: Type text into editable element
145
+ - Parameters:
146
+ - `element` (string): Human-readable element description used to obtain permission to interact with the element
147
+ - `ref` (string): Exact target element reference from the page snapshot
148
+ - `text` (string): Text to type into the element
149
+ - `submit` (boolean): Whether to submit entered text (press Enter after)
150
+
151
+ - **browser_press_key**
152
+ - Description: Press a key on the keyboard
153
+ - Parameters:
154
+ - `key` (string): Name of the key to press or a character to generate, such as `ArrowLeft` or `a`
155
+
156
+ - **browser_snapshot**
157
+ - Description: Capture accessibility snapshot of the current page (better than screenshot)
158
+ - Parameters: None
159
+
160
+ - **browser_save_as_pdf**
161
+ - Description: Save page as PDF
162
+ - Parameters: None
163
+
164
+ - **browser_wait**
165
+ - Description: Wait for a specified time in seconds
166
+ - Parameters:
167
+ - `time` (number): The time to wait in seconds (capped at 10 seconds)
168
+
169
+ - **browser_close**
170
+ - Description: Close the page
171
+ - Parameters: None
172
+
173
+
174
+ ### Vision Mode
175
+
176
+ Vision Mode provides tools for visual-based interactions using screenshots. Here are all available tools:
177
+
178
+ - **browser_navigate**
179
+ - Description: Navigate to a URL
180
+ - Parameters:
181
+ - `url` (string): The URL to navigate to
182
+
183
+ - **browser_go_back**
184
+ - Description: Go back to the previous page
185
+ - Parameters: None
186
+
187
+ - **browser_go_forward**
188
+ - Description: Go forward to the next page
189
+ - Parameters: None
190
+
191
+ - **browser_screenshot**
192
+ - Description: Capture screenshot of the current page
193
+ - Parameters: None
194
+
195
+ - **browser_move_mouse**
196
+ - Description: Move mouse to specified coordinates
197
+ - Parameters:
198
+ - `x` (number): X coordinate
199
+ - `y` (number): Y coordinate
200
+
201
+ - **browser_click**
202
+ - Description: Click at specified coordinates
203
+ - Parameters:
204
+ - `x` (number): X coordinate to click at
205
+ - `y` (number): Y coordinate to click at
206
+
207
+ - **browser_drag**
208
+ - Description: Perform drag and drop operation
209
+ - Parameters:
210
+ - `startX` (number): Start X coordinate
211
+ - `startY` (number): Start Y coordinate
212
+ - `endX` (number): End X coordinate
213
+ - `endY` (number): End Y coordinate
214
+
215
+ - **browser_type**
216
+ - Description: Type text at specified coordinates
217
+ - Parameters:
218
+ - `text` (string): Text to type
219
+ - `submit` (boolean): Whether to submit entered text (press Enter after)
220
+
221
+ - **browser_press_key**
222
+ - Description: Press a key on the keyboard
223
+ - Parameters:
224
+ - `key` (string): Name of the key to press or a character to generate, such as `ArrowLeft` or `a`
225
+
226
+ - **browser_save_as_pdf**
227
+ - Description: Save page as PDF
228
+ - Parameters: None
229
+
230
+ - **browser_wait**
231
+ - Description: Wait for a specified time in seconds
232
+ - Parameters:
233
+ - `time` (number): The time to wait in seconds (capped at 10 seconds)
234
+
235
+ - **browser_close**
236
+ - Description: Close the page
237
+ - Parameters: None
package/cli.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ require('./lib/program');
package/lib/context.js ADDED
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
30
+ }) : function(o, v) {
31
+ o["default"] = v;
32
+ });
33
+ var __importStar = (this && this.__importStar) || (function () {
34
+ var ownKeys = function(o) {
35
+ ownKeys = Object.getOwnPropertyNames || function (o) {
36
+ var ar = [];
37
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
+ return ar;
39
+ };
40
+ return ownKeys(o);
41
+ };
42
+ return function (mod) {
43
+ if (mod && mod.__esModule) return mod;
44
+ var result = {};
45
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
+ __setModuleDefault(result, mod);
47
+ return result;
48
+ };
49
+ })();
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ exports.Context = void 0;
52
+ const playwright = __importStar(require("playwright"));
53
+ class Context {
54
+ _launchOptions;
55
+ _page;
56
+ _console = [];
57
+ _initializePromise;
58
+ constructor(launchOptions) {
59
+ this._launchOptions = launchOptions;
60
+ }
61
+ async ensurePage() {
62
+ await this._initialize();
63
+ return this._page;
64
+ }
65
+ async ensureConsole() {
66
+ await this._initialize();
67
+ return this._console;
68
+ }
69
+ async close() {
70
+ const page = await this.ensurePage();
71
+ await page.close();
72
+ this._initializePromise = undefined;
73
+ }
74
+ async _initialize() {
75
+ if (this._initializePromise)
76
+ return this._initializePromise;
77
+ this._initializePromise = (async () => {
78
+ const browser = await this._createBrowser();
79
+ this._page = await browser.newPage();
80
+ this._page.on('console', event => this._console.push(event));
81
+ this._page.on('framenavigated', frame => {
82
+ if (!frame.parentFrame())
83
+ this._console.length = 0;
84
+ });
85
+ })();
86
+ return this._initializePromise;
87
+ }
88
+ async _createBrowser() {
89
+ if (process.env.PLAYWRIGHT_WS_ENDPOINT) {
90
+ const url = new URL(process.env.PLAYWRIGHT_WS_ENDPOINT);
91
+ url.searchParams.set('launch-options', JSON.stringify(this._launchOptions));
92
+ return await playwright.chromium.connect(String(url));
93
+ }
94
+ return await playwright.chromium.launch({ channel: 'chrome', ...this._launchOptions });
95
+ }
96
+ }
97
+ exports.Context = Context;
package/lib/program.js ADDED
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
30
+ }) : function(o, v) {
31
+ o["default"] = v;
32
+ });
33
+ var __importStar = (this && this.__importStar) || (function () {
34
+ var ownKeys = function(o) {
35
+ ownKeys = Object.getOwnPropertyNames || function (o) {
36
+ var ar = [];
37
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
+ return ar;
39
+ };
40
+ return ownKeys(o);
41
+ };
42
+ return function (mod) {
43
+ if (mod && mod.__esModule) return mod;
44
+ var result = {};
45
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
+ __setModuleDefault(result, mod);
47
+ return result;
48
+ };
49
+ })();
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ const commander_1 = require("commander");
52
+ const server_1 = require("./server");
53
+ const snapshot = __importStar(require("./tools/snapshot"));
54
+ const common = __importStar(require("./tools/common"));
55
+ const screenshot = __importStar(require("./tools/screenshot"));
56
+ const console_1 = require("./resources/console");
57
+ const packageJSON = require('../package.json');
58
+ commander_1.program
59
+ .version('Version ' + packageJSON.version)
60
+ .name(packageJSON.name)
61
+ .option('--headless', 'Run browser in headless mode, headed by default')
62
+ .option('--vision', 'Run server that uses screenshots (Aria snapshots are used by default)')
63
+ .action(async (options) => {
64
+ const launchOptions = {
65
+ headless: !!options.headless,
66
+ };
67
+ const tools = options.vision ? screenshotTools : snapshotTools;
68
+ const server = new server_1.Server({
69
+ name: 'Playwright',
70
+ version: packageJSON.version,
71
+ tools,
72
+ resources,
73
+ }, launchOptions);
74
+ setupExitWatchdog(server);
75
+ await server.start();
76
+ });
77
+ function setupExitWatchdog(server) {
78
+ process.stdin.on('close', async () => {
79
+ setTimeout(() => process.exit(0), 15000);
80
+ await server?.stop();
81
+ process.exit(0);
82
+ });
83
+ }
84
+ const commonTools = [
85
+ common.pressKey,
86
+ common.wait,
87
+ common.pdf,
88
+ common.close,
89
+ ];
90
+ const snapshotTools = [
91
+ common.navigate(true),
92
+ common.goBack(true),
93
+ common.goForward(true),
94
+ snapshot.snapshot,
95
+ snapshot.click,
96
+ snapshot.hover,
97
+ snapshot.type,
98
+ ...commonTools,
99
+ ];
100
+ const screenshotTools = [
101
+ common.navigate(false),
102
+ common.goBack(false),
103
+ common.goForward(false),
104
+ screenshot.screenshot,
105
+ screenshot.moveMouse,
106
+ screenshot.click,
107
+ screenshot.drag,
108
+ screenshot.type,
109
+ ...commonTools,
110
+ ];
111
+ const resources = [
112
+ console_1.console,
113
+ ];
114
+ commander_1.program.parse(process.argv);
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.console = void 0;
19
+ exports.console = {
20
+ schema: {
21
+ uri: 'browser://console',
22
+ name: 'Page console',
23
+ mimeType: 'text/plain',
24
+ },
25
+ read: async (context, uri) => {
26
+ const result = [];
27
+ for (const message of await context.ensureConsole()) {
28
+ result.push({
29
+ uri,
30
+ mimeType: 'text/plain',
31
+ text: `[${message.type().toUpperCase()}] ${message.text()}`,
32
+ });
33
+ }
34
+ return result;
35
+ },
36
+ };
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/server.js ADDED
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.Server = void 0;
19
+ const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
20
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
21
+ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
22
+ const context_1 = require("./context");
23
+ class Server {
24
+ _server;
25
+ _tools;
26
+ _page;
27
+ _context;
28
+ constructor(options, launchOptions) {
29
+ const { name, version, tools, resources } = options;
30
+ this._context = new context_1.Context(launchOptions);
31
+ this._server = new index_js_1.Server({ name, version }, {
32
+ capabilities: {
33
+ tools: {},
34
+ resources: {},
35
+ }
36
+ });
37
+ this._tools = tools;
38
+ this._server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
39
+ return { tools: tools.map(tool => tool.schema) };
40
+ });
41
+ this._server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => {
42
+ return { resources: resources.map(resource => resource.schema) };
43
+ });
44
+ this._server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
45
+ const tool = this._tools.find(tool => tool.schema.name === request.params.name);
46
+ if (!tool) {
47
+ return {
48
+ content: [{ type: 'text', text: `Tool "${request.params.name}" not found` }],
49
+ isError: true,
50
+ };
51
+ }
52
+ try {
53
+ const result = await tool.handle(this._context, request.params.arguments);
54
+ return result;
55
+ }
56
+ catch (error) {
57
+ return {
58
+ content: [{ type: 'text', text: String(error) }],
59
+ isError: true,
60
+ };
61
+ }
62
+ });
63
+ this._server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
64
+ const resource = resources.find(resource => resource.schema.uri === request.params.uri);
65
+ if (!resource)
66
+ return { contents: [] };
67
+ const contents = await resource.read(this._context, request.params.uri);
68
+ return { contents };
69
+ });
70
+ }
71
+ async start() {
72
+ const transport = new stdio_js_1.StdioServerTransport();
73
+ await this._server.connect(transport);
74
+ }
75
+ async stop() {
76
+ await this._server.close();
77
+ await this._page?.context()?.browser()?.close();
78
+ }
79
+ }
80
+ exports.Server = Server;
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.close = exports.pdf = exports.pressKey = exports.wait = exports.goForward = exports.goBack = exports.navigate = void 0;
22
+ const os_1 = __importDefault(require("os"));
23
+ const path_1 = __importDefault(require("path"));
24
+ const zod_1 = require("zod");
25
+ const zod_to_json_schema_1 = require("zod-to-json-schema");
26
+ const utils_1 = require("./utils");
27
+ const navigateSchema = zod_1.z.object({
28
+ url: zod_1.z.string().describe('The URL to navigate to'),
29
+ });
30
+ const navigate = snapshot => ({
31
+ schema: {
32
+ name: 'browser_navigate',
33
+ description: 'Navigate to a URL',
34
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(navigateSchema),
35
+ },
36
+ handle: async (context, params) => {
37
+ const validatedParams = navigateSchema.parse(params);
38
+ const page = await context.ensurePage();
39
+ await page.goto(validatedParams.url, { waitUntil: 'domcontentloaded' });
40
+ // Cap load event to 5 seconds, the page is operational at this point.
41
+ await page.waitForLoadState('load', { timeout: 5000 }).catch(() => { });
42
+ if (snapshot)
43
+ return (0, utils_1.captureAriaSnapshot)(page);
44
+ return {
45
+ content: [{
46
+ type: 'text',
47
+ text: `Navigated to ${validatedParams.url}`,
48
+ }],
49
+ };
50
+ },
51
+ });
52
+ exports.navigate = navigate;
53
+ const goBackSchema = zod_1.z.object({});
54
+ const goBack = snapshot => ({
55
+ schema: {
56
+ name: 'browser_go_back',
57
+ description: 'Go back to the previous page',
58
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(goBackSchema),
59
+ },
60
+ handle: async (context) => {
61
+ return await (0, utils_1.runAndWait)(context, 'Navigated back', async () => {
62
+ const page = await context.ensurePage();
63
+ await page.goBack();
64
+ }, snapshot);
65
+ },
66
+ });
67
+ exports.goBack = goBack;
68
+ const goForwardSchema = zod_1.z.object({});
69
+ const goForward = snapshot => ({
70
+ schema: {
71
+ name: 'browser_go_forward',
72
+ description: 'Go forward to the next page',
73
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(goForwardSchema),
74
+ },
75
+ handle: async (context) => {
76
+ return await (0, utils_1.runAndWait)(context, 'Navigated forward', async () => {
77
+ const page = await context.ensurePage();
78
+ await page.goForward();
79
+ }, snapshot);
80
+ },
81
+ });
82
+ exports.goForward = goForward;
83
+ const waitSchema = zod_1.z.object({
84
+ time: zod_1.z.number().describe('The time to wait in seconds'),
85
+ });
86
+ exports.wait = {
87
+ schema: {
88
+ name: 'browser_wait',
89
+ description: 'Wait for a specified time in seconds',
90
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(waitSchema),
91
+ },
92
+ handle: async (context, params) => {
93
+ const validatedParams = waitSchema.parse(params);
94
+ const page = await context.ensurePage();
95
+ await page.waitForTimeout(Math.min(10000, validatedParams.time * 1000));
96
+ return {
97
+ content: [{
98
+ type: 'text',
99
+ text: `Waited for ${validatedParams.time} seconds`,
100
+ }],
101
+ };
102
+ },
103
+ };
104
+ const pressKeySchema = zod_1.z.object({
105
+ key: zod_1.z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),
106
+ });
107
+ exports.pressKey = {
108
+ schema: {
109
+ name: 'browser_press_key',
110
+ description: 'Press a key on the keyboard',
111
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(pressKeySchema),
112
+ },
113
+ handle: async (context, params) => {
114
+ const validatedParams = pressKeySchema.parse(params);
115
+ return await (0, utils_1.runAndWait)(context, `Pressed key ${validatedParams.key}`, async (page) => {
116
+ await page.keyboard.press(validatedParams.key);
117
+ });
118
+ },
119
+ };
120
+ const pdfSchema = zod_1.z.object({});
121
+ exports.pdf = {
122
+ schema: {
123
+ name: 'browser_save_as_pdf',
124
+ description: 'Save page as PDF',
125
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(pdfSchema),
126
+ },
127
+ handle: async (context) => {
128
+ const page = await context.ensurePage();
129
+ const fileName = path_1.default.join(os_1.default.tmpdir(), `/page-${new Date().toISOString()}.pdf`);
130
+ await page.pdf({ path: fileName });
131
+ return {
132
+ content: [{
133
+ type: 'text',
134
+ text: `Saved as ${fileName}`,
135
+ }],
136
+ };
137
+ },
138
+ };
139
+ const closeSchema = zod_1.z.object({});
140
+ exports.close = {
141
+ schema: {
142
+ name: 'browser_close',
143
+ description: 'Close the page',
144
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(closeSchema),
145
+ },
146
+ handle: async (context) => {
147
+ await context.close();
148
+ return {
149
+ content: [{
150
+ type: 'text',
151
+ text: `Page closed`,
152
+ }],
153
+ };
154
+ },
155
+ };
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.type = exports.drag = exports.click = exports.moveMouse = exports.screenshot = void 0;
19
+ const zod_1 = require("zod");
20
+ const zod_to_json_schema_1 = require("zod-to-json-schema");
21
+ const utils_1 = require("./utils");
22
+ exports.screenshot = {
23
+ schema: {
24
+ name: 'browser_screenshot',
25
+ description: 'Take a screenshot of the current page',
26
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(zod_1.z.object({})),
27
+ },
28
+ handle: async (context) => {
29
+ const page = await context.ensurePage();
30
+ const screenshot = await page.screenshot({ type: 'jpeg', quality: 50, scale: 'css' });
31
+ return {
32
+ content: [{ type: 'image', data: screenshot.toString('base64'), mimeType: 'image/jpeg' }],
33
+ };
34
+ },
35
+ };
36
+ const elementSchema = zod_1.z.object({
37
+ element: zod_1.z.string().describe('Human-readable element description used to obtain permission to interact with the element'),
38
+ });
39
+ const moveMouseSchema = elementSchema.extend({
40
+ x: zod_1.z.number().describe('X coordinate'),
41
+ y: zod_1.z.number().describe('Y coordinate'),
42
+ });
43
+ exports.moveMouse = {
44
+ schema: {
45
+ name: 'browser_move_mouse',
46
+ description: 'Move mouse to a given position',
47
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(moveMouseSchema),
48
+ },
49
+ handle: async (context, params) => {
50
+ const validatedParams = moveMouseSchema.parse(params);
51
+ const page = await context.ensurePage();
52
+ await page.mouse.move(validatedParams.x, validatedParams.y);
53
+ return {
54
+ content: [{ type: 'text', text: `Moved mouse to (${validatedParams.x}, ${validatedParams.y})` }],
55
+ };
56
+ },
57
+ };
58
+ const clickSchema = elementSchema.extend({
59
+ x: zod_1.z.number().describe('X coordinate'),
60
+ y: zod_1.z.number().describe('Y coordinate'),
61
+ });
62
+ exports.click = {
63
+ schema: {
64
+ name: 'browser_click',
65
+ description: 'Click left mouse button',
66
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(clickSchema),
67
+ },
68
+ handle: async (context, params) => {
69
+ return await (0, utils_1.runAndWait)(context, 'Clicked mouse', async (page) => {
70
+ const validatedParams = clickSchema.parse(params);
71
+ await page.mouse.move(validatedParams.x, validatedParams.y);
72
+ await page.mouse.down();
73
+ await page.mouse.up();
74
+ });
75
+ },
76
+ };
77
+ const dragSchema = elementSchema.extend({
78
+ startX: zod_1.z.number().describe('Start X coordinate'),
79
+ startY: zod_1.z.number().describe('Start Y coordinate'),
80
+ endX: zod_1.z.number().describe('End X coordinate'),
81
+ endY: zod_1.z.number().describe('End Y coordinate'),
82
+ });
83
+ exports.drag = {
84
+ schema: {
85
+ name: 'browser_drag',
86
+ description: 'Drag left mouse button',
87
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(dragSchema),
88
+ },
89
+ handle: async (context, params) => {
90
+ const validatedParams = dragSchema.parse(params);
91
+ return await (0, utils_1.runAndWait)(context, `Dragged mouse from (${validatedParams.startX}, ${validatedParams.startY}) to (${validatedParams.endX}, ${validatedParams.endY})`, async (page) => {
92
+ await page.mouse.move(validatedParams.startX, validatedParams.startY);
93
+ await page.mouse.down();
94
+ await page.mouse.move(validatedParams.endX, validatedParams.endY);
95
+ await page.mouse.up();
96
+ });
97
+ },
98
+ };
99
+ const typeSchema = zod_1.z.object({
100
+ text: zod_1.z.string().describe('Text to type into the element'),
101
+ submit: zod_1.z.boolean().describe('Whether to submit entered text (press Enter after)'),
102
+ });
103
+ exports.type = {
104
+ schema: {
105
+ name: 'browser_type',
106
+ description: 'Type text',
107
+ inputSchema: (0, zod_to_json_schema_1.zodToJsonSchema)(typeSchema),
108
+ },
109
+ handle: async (context, params) => {
110
+ const validatedParams = typeSchema.parse(params);
111
+ return await (0, utils_1.runAndWait)(context, `Typed text "${validatedParams.text}"`, async (page) => {
112
+ await page.keyboard.type(validatedParams.text);
113
+ if (validatedParams.submit)
114
+ await page.keyboard.press('Enter');
115
+ });
116
+ },
117
+ };
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.type = exports.hover = exports.drag = exports.click = exports.snapshot = void 0;
22
+ const zod_1 = require("zod");
23
+ const zod_to_json_schema_1 = __importDefault(require("zod-to-json-schema"));
24
+ const utils_1 = require("./utils");
25
+ exports.snapshot = {
26
+ schema: {
27
+ name: 'browser_snapshot',
28
+ description: 'Capture accessibility snapshot of the current page, this is better than screenshot',
29
+ inputSchema: (0, zod_to_json_schema_1.default)(zod_1.z.object({})),
30
+ },
31
+ handle: async (context) => {
32
+ return await (0, utils_1.captureAriaSnapshot)(await context.ensurePage());
33
+ },
34
+ };
35
+ const elementSchema = zod_1.z.object({
36
+ element: zod_1.z.string().describe('Human-readable element description used to obtain permission to interact with the element'),
37
+ ref: zod_1.z.string().describe('Exact target element reference from the page snapshot'),
38
+ });
39
+ exports.click = {
40
+ schema: {
41
+ name: 'browser_click',
42
+ description: 'Perform click on a web page',
43
+ inputSchema: (0, zod_to_json_schema_1.default)(elementSchema),
44
+ },
45
+ handle: async (context, params) => {
46
+ const validatedParams = elementSchema.parse(params);
47
+ return (0, utils_1.runAndWait)(context, `"${validatedParams.element}" clicked`, page => refLocator(page, validatedParams.ref).click(), true);
48
+ },
49
+ };
50
+ const dragSchema = zod_1.z.object({
51
+ startElement: zod_1.z.string().describe('Human-readable source element description used to obtain the permission to interact with the element'),
52
+ startRef: zod_1.z.string().describe('Exact source element reference from the page snapshot'),
53
+ endElement: zod_1.z.string().describe('Human-readable target element description used to obtain the permission to interact with the element'),
54
+ endRef: zod_1.z.string().describe('Exact target element reference from the page snapshot'),
55
+ });
56
+ exports.drag = {
57
+ schema: {
58
+ name: 'browser_drag',
59
+ description: 'Perform drag and drop between two elements',
60
+ inputSchema: (0, zod_to_json_schema_1.default)(dragSchema),
61
+ },
62
+ handle: async (context, params) => {
63
+ const validatedParams = dragSchema.parse(params);
64
+ return (0, utils_1.runAndWait)(context, `Dragged "${validatedParams.startElement}" to "${validatedParams.endElement}"`, async (page) => {
65
+ const startLocator = refLocator(page, validatedParams.startRef);
66
+ const endLocator = refLocator(page, validatedParams.endRef);
67
+ await startLocator.dragTo(endLocator);
68
+ }, true);
69
+ },
70
+ };
71
+ exports.hover = {
72
+ schema: {
73
+ name: 'browser_hover',
74
+ description: 'Hover over element on page',
75
+ inputSchema: (0, zod_to_json_schema_1.default)(elementSchema),
76
+ },
77
+ handle: async (context, params) => {
78
+ const validatedParams = elementSchema.parse(params);
79
+ return (0, utils_1.runAndWait)(context, `Hovered over "${validatedParams.element}"`, page => refLocator(page, validatedParams.ref).hover(), true);
80
+ },
81
+ };
82
+ const typeSchema = elementSchema.extend({
83
+ text: zod_1.z.string().describe('Text to type into the element'),
84
+ submit: zod_1.z.boolean().describe('Whether to submit entered text (press Enter after)'),
85
+ });
86
+ exports.type = {
87
+ schema: {
88
+ name: 'browser_type',
89
+ description: 'Type text into editable element',
90
+ inputSchema: (0, zod_to_json_schema_1.default)(typeSchema),
91
+ },
92
+ handle: async (context, params) => {
93
+ const validatedParams = typeSchema.parse(params);
94
+ return await (0, utils_1.runAndWait)(context, `Typed "${validatedParams.text}" into "${validatedParams.element}"`, async (page) => {
95
+ const locator = refLocator(page, validatedParams.ref);
96
+ await locator.fill(validatedParams.text);
97
+ if (validatedParams.submit)
98
+ await locator.press('Enter');
99
+ }, true);
100
+ },
101
+ };
102
+ function refLocator(page, ref) {
103
+ return page.locator(`aria-ref=${ref}`);
104
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.runAndWait = runAndWait;
19
+ exports.captureAriaSnapshot = captureAriaSnapshot;
20
+ async function waitForCompletion(page, callback) {
21
+ const requests = new Set();
22
+ let frameNavigated = false;
23
+ let waitCallback = () => { };
24
+ const waitBarrier = new Promise(f => { waitCallback = f; });
25
+ const requestListener = (request) => requests.add(request);
26
+ const requestFinishedListener = (request) => {
27
+ requests.delete(request);
28
+ if (!requests.size)
29
+ waitCallback();
30
+ };
31
+ const frameNavigateListener = (frame) => {
32
+ if (frame.parentFrame())
33
+ return;
34
+ frameNavigated = true;
35
+ dispose();
36
+ clearTimeout(timeout);
37
+ void frame.waitForLoadState('load').then(() => {
38
+ waitCallback();
39
+ });
40
+ };
41
+ const onTimeout = () => {
42
+ dispose();
43
+ waitCallback();
44
+ };
45
+ page.on('request', requestListener);
46
+ page.on('requestfinished', requestFinishedListener);
47
+ page.on('framenavigated', frameNavigateListener);
48
+ const timeout = setTimeout(onTimeout, 10000);
49
+ const dispose = () => {
50
+ page.off('request', requestListener);
51
+ page.off('requestfinished', requestFinishedListener);
52
+ page.off('framenavigated', frameNavigateListener);
53
+ clearTimeout(timeout);
54
+ };
55
+ try {
56
+ const result = await callback();
57
+ if (!requests.size && !frameNavigated)
58
+ waitCallback();
59
+ await waitBarrier;
60
+ await page.evaluate(() => new Promise(f => setTimeout(f, 1000)));
61
+ return result;
62
+ }
63
+ finally {
64
+ dispose();
65
+ }
66
+ }
67
+ async function runAndWait(context, status, callback, snapshot = false) {
68
+ const page = await context.ensurePage();
69
+ await waitForCompletion(page, () => callback(page));
70
+ return snapshot ? captureAriaSnapshot(page, status) : {
71
+ content: [{ type: 'text', text: status }],
72
+ };
73
+ }
74
+ async function captureAriaSnapshot(page, status = '') {
75
+ const snapshot = await page.locator('html').ariaSnapshot({ ref: true });
76
+ return {
77
+ content: [{ type: 'text', text: `${status ? `${status}\n` : ''}
78
+ - Page URL: ${page.url()}
79
+ - Page Title: ${await page.title()}
80
+ - Page Snapshot
81
+ \`\`\`yaml
82
+ ${snapshot}
83
+ \`\`\`
84
+ `
85
+ }],
86
+ };
87
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@playwright/mcp",
3
+ "version": "0.0.1",
4
+ "description": "Playwright Tools for MCP",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/microsoft/playwright-mcp.git"
8
+ },
9
+ "homepage": "https://playwright.dev",
10
+ "engines": {
11
+ "node": ">=18"
12
+ },
13
+ "author": {
14
+ "name": "Microsoft Corporation"
15
+ },
16
+ "license": "Apache-2.0",
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "lint": "eslint .",
20
+ "watch": "tsc --watch",
21
+ "test": "playwright test"
22
+ },
23
+ "exports": {
24
+ "./servers/server": "./lib/servers/server.js",
25
+ "./servers/screenshot": "./lib/servers/screenshot.js",
26
+ "./servers/snapshot": "./lib/servers/snapshot.js",
27
+ "./tools/common": "./lib/tools/common.js",
28
+ "./tools/screenshot": "./lib/tools/screenshot.js",
29
+ "./tools/snapshot": "./lib/tools/snapshot.js",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "dependencies": {
33
+ "@modelcontextprotocol/sdk": "^1.6.1",
34
+ "commander": "^13.1.0",
35
+ "playwright": "1.52.0-alpha-2025-03-21",
36
+ "zod-to-json-schema": "^3.24.4"
37
+ },
38
+ "devDependencies": {
39
+ "@eslint/eslintrc": "^3.2.0",
40
+ "@eslint/js": "^9.19.0",
41
+ "@playwright/test": "1.52.0-alpha-2025-03-21",
42
+ "@stylistic/eslint-plugin": "^3.0.1",
43
+ "@typescript-eslint/eslint-plugin": "^8.26.1",
44
+ "@typescript-eslint/parser": "^8.26.1",
45
+ "@typescript-eslint/utils": "^8.26.1",
46
+ "@types/node": "^22.13.10",
47
+ "eslint": "^9.19.0",
48
+ "eslint-plugin-import": "^2.31.0",
49
+ "eslint-plugin-notice": "^1.0.0",
50
+ "typescript": "^5.8.2"
51
+ },
52
+ "bin": {
53
+ "mcp": "cli.js"
54
+ }
55
+ }