@playwright/mcp 0.0.34 → 0.0.35-alpha-2025-08-28

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.
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { z } from 'zod';
17
+ import { defineTabTool } from './tool.js';
18
+ import * as javascript from '../utils/codegen.js';
19
+ import { generateLocator } from './utils.js';
20
+ const verifyElement = defineTabTool({
21
+ capability: 'verify',
22
+ schema: {
23
+ name: 'browser_verify_element_visible',
24
+ title: 'Verify element visible',
25
+ description: 'Verify element is visible on the page',
26
+ inputSchema: z.object({
27
+ role: z.string().describe('ROLE of the element. Can be found in the snapshot like this: \`- {ROLE} "Accessible Name":\`'),
28
+ accessibleName: z.string().describe('ACCESSIBLE_NAME of the element. Can be found in the snapshot like this: \`- role "{ACCESSIBLE_NAME}"\`'),
29
+ }),
30
+ type: 'readOnly',
31
+ },
32
+ handle: async (tab, params, response) => {
33
+ const locator = tab.page.getByRole(params.role, { name: params.accessibleName });
34
+ if (await locator.count() === 0) {
35
+ response.addError(`Element with role "${params.role}" and accessible name "${params.accessibleName}" not found`);
36
+ return;
37
+ }
38
+ response.addCode(`await expect(page.getByRole(${javascript.escapeWithQuotes(params.role)}, { name: ${javascript.escapeWithQuotes(params.accessibleName)} })).toBeVisible();`);
39
+ response.addResult('Done');
40
+ },
41
+ });
42
+ const verifyText = defineTabTool({
43
+ capability: 'verify',
44
+ schema: {
45
+ name: 'browser_verify_text_visible',
46
+ title: 'Verify text visible',
47
+ description: `Verify text is visible on the page. Prefer ${verifyElement.schema.name} if possible.`,
48
+ inputSchema: z.object({
49
+ text: z.string().describe('TEXT to verify. Can be found in the snapshot like this: \`- role "Accessible Name": {TEXT}\` or like this: \`- text: {TEXT}\`'),
50
+ }),
51
+ type: 'readOnly',
52
+ },
53
+ handle: async (tab, params, response) => {
54
+ const locator = tab.page.getByText(params.text).filter({ visible: true });
55
+ if (await locator.count() === 0) {
56
+ response.addError('Text not found');
57
+ return;
58
+ }
59
+ response.addCode(`await expect(page.getByText(${javascript.escapeWithQuotes(params.text)})).toBeVisible();`);
60
+ response.addResult('Done');
61
+ },
62
+ });
63
+ const verifyList = defineTabTool({
64
+ capability: 'verify',
65
+ schema: {
66
+ name: 'browser_verify_list_visible',
67
+ title: 'Verify list visible',
68
+ description: 'Verify list is visible on the page',
69
+ inputSchema: z.object({
70
+ element: z.string().describe('Human-readable list description'),
71
+ ref: z.string().describe('Exact target element reference that points to the list'),
72
+ items: z.array(z.string()).describe('Items to verify'),
73
+ }),
74
+ type: 'readOnly',
75
+ },
76
+ handle: async (tab, params, response) => {
77
+ const locator = await tab.refLocator({ ref: params.ref, element: params.element });
78
+ const itemTexts = [];
79
+ for (const item of params.items) {
80
+ const itemLocator = locator.getByText(item);
81
+ if (await itemLocator.count() === 0) {
82
+ response.addError(`Item "${item}" not found`);
83
+ return;
84
+ }
85
+ itemTexts.push((await itemLocator.textContent()));
86
+ }
87
+ const ariaSnapshot = `\`
88
+ - list:
89
+ ${itemTexts.map(t => ` - text: ${javascript.escapeWithQuotes(t, '"')}`).join('\n')}
90
+ \``;
91
+ response.addCode(`await expect(page.locator('body')).toMatchAriaSnapshot(${ariaSnapshot});`);
92
+ response.addResult('Done');
93
+ },
94
+ });
95
+ const verifyValue = defineTabTool({
96
+ capability: 'verify',
97
+ schema: {
98
+ name: 'browser_verify_value',
99
+ title: 'Verify value',
100
+ description: 'Verify element value',
101
+ inputSchema: z.object({
102
+ type: z.enum(['textbox', 'checkbox', 'radio', 'combobox', 'slider']).describe('Type of the element'),
103
+ element: z.string().describe('Human-readable element description'),
104
+ ref: z.string().describe('Exact target element reference that points to the element'),
105
+ value: z.string().describe('Value to verify. For checkbox, use "true" or "false".'),
106
+ }),
107
+ type: 'readOnly',
108
+ },
109
+ handle: async (tab, params, response) => {
110
+ const locator = await tab.refLocator({ ref: params.ref, element: params.element });
111
+ const locatorSource = `page.${await generateLocator(locator)}`;
112
+ if (params.type === 'textbox' || params.type === 'slider' || params.type === 'combobox') {
113
+ const value = await locator.inputValue();
114
+ if (value !== params.value) {
115
+ response.addError(`Expected value "${params.value}", but got "${value}"`);
116
+ return;
117
+ }
118
+ response.addCode(`await expect(${locatorSource}).toHaveValue(${javascript.quote(params.value)});`);
119
+ }
120
+ else if (params.type === 'checkbox' || params.type === 'radio') {
121
+ const value = await locator.isChecked();
122
+ if (value !== (params.value === 'true')) {
123
+ response.addError(`Expected value "${params.value}", but got "${value}"`);
124
+ return;
125
+ }
126
+ const matcher = value ? 'toBeChecked' : 'not.toBeChecked';
127
+ response.addCode(`await expect(${locatorSource}).${matcher}();`);
128
+ }
129
+ response.addResult('Done');
130
+ },
131
+ });
132
+ export default [
133
+ verifyElement,
134
+ verifyText,
135
+ verifyList,
136
+ verifyValue,
137
+ ];
package/lib/tools.js CHANGED
@@ -18,8 +18,10 @@ import console from './tools/console.js';
18
18
  import dialogs from './tools/dialogs.js';
19
19
  import evaluate from './tools/evaluate.js';
20
20
  import files from './tools/files.js';
21
+ import form from './tools/form.js';
21
22
  import install from './tools/install.js';
22
23
  import keyboard from './tools/keyboard.js';
24
+ import mouse from './tools/mouse.js';
23
25
  import navigate from './tools/navigate.js';
24
26
  import network from './tools/network.js';
25
27
  import pdf from './tools/pdf.js';
@@ -27,13 +29,14 @@ import snapshot from './tools/snapshot.js';
27
29
  import tabs from './tools/tabs.js';
28
30
  import screenshot from './tools/screenshot.js';
29
31
  import wait from './tools/wait.js';
30
- import mouse from './tools/mouse.js';
32
+ import verify from './tools/verify.js';
31
33
  export const allTools = [
32
34
  ...common,
33
35
  ...console,
34
36
  ...dialogs,
35
37
  ...evaluate,
36
38
  ...files,
39
+ ...form,
37
40
  ...install,
38
41
  ...keyboard,
39
42
  ...navigate,
@@ -44,6 +47,7 @@ export const allTools = [
44
47
  ...snapshot,
45
48
  ...tabs,
46
49
  ...wait,
50
+ ...verify,
47
51
  ];
48
52
  export function filteredTools(config) {
49
53
  return allTools.filter(tool => tool.capability.startsWith('core') || config.capabilities?.includes(tool.capability));
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { fileURLToPath } from 'url';
17
+ import path from 'path';
18
+ import { z } from 'zod';
19
+ import { zodToJsonSchema } from 'zod-to-json-schema';
20
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
21
+ import { ListRootsRequestSchema, PingRequestSchema } from '@modelcontextprotocol/sdk/types.js';
22
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
23
+ import * as mcpServer from '../mcp/server.js';
24
+ import { logUnhandledError } from '../utils/log.js';
25
+ import { packageJSON } from '../utils/package.js';
26
+ import { BrowserServerBackend } from '../browserServerBackend.js';
27
+ import { contextFactory } from '../browserContextFactory.js';
28
+ const contextSwitchOptions = z.object({
29
+ connectionString: z.string().optional().describe('The connection string to use to connect to the browser'),
30
+ lib: z.string().optional().describe('The library to use for the connection'),
31
+ });
32
+ class VSCodeProxyBackend {
33
+ _config;
34
+ _defaultTransportFactory;
35
+ name = 'Playwright MCP Client Switcher';
36
+ version = packageJSON.version;
37
+ _currentClient;
38
+ _contextSwitchTool;
39
+ _roots = [];
40
+ _clientVersion;
41
+ constructor(_config, _defaultTransportFactory) {
42
+ this._config = _config;
43
+ this._defaultTransportFactory = _defaultTransportFactory;
44
+ this._contextSwitchTool = this._defineContextSwitchTool();
45
+ }
46
+ async initialize(server, clientVersion, roots) {
47
+ this._clientVersion = clientVersion;
48
+ this._roots = roots;
49
+ const transport = await this._defaultTransportFactory();
50
+ await this._setCurrentClient(transport);
51
+ }
52
+ async listTools() {
53
+ const response = await this._currentClient.listTools();
54
+ return [
55
+ ...response.tools,
56
+ this._contextSwitchTool,
57
+ ];
58
+ }
59
+ async callTool(name, args) {
60
+ if (name === this._contextSwitchTool.name)
61
+ return this._callContextSwitchTool(args);
62
+ return await this._currentClient.callTool({
63
+ name,
64
+ arguments: args,
65
+ });
66
+ }
67
+ serverClosed(server) {
68
+ void this._currentClient?.close().catch(logUnhandledError);
69
+ }
70
+ async _callContextSwitchTool(params) {
71
+ if (!params.connectionString || !params.lib) {
72
+ const transport = await this._defaultTransportFactory();
73
+ await this._setCurrentClient(transport);
74
+ return {
75
+ content: [{ type: 'text', text: '### Result\nSuccessfully disconnected.\n' }],
76
+ };
77
+ }
78
+ await this._setCurrentClient(new StdioClientTransport({
79
+ command: process.execPath,
80
+ cwd: process.cwd(),
81
+ args: [
82
+ path.join(fileURLToPath(import.meta.url), '..', 'main.js'),
83
+ JSON.stringify(this._config),
84
+ params.connectionString,
85
+ params.lib,
86
+ ],
87
+ }));
88
+ return {
89
+ content: [{ type: 'text', text: '### Result\nSuccessfully connected.\n' }],
90
+ };
91
+ }
92
+ _defineContextSwitchTool() {
93
+ return {
94
+ name: 'browser_connect',
95
+ description: 'Do not call, this tool is used in the integration with the Playwright VS Code Extension and meant for programmatic usage only.',
96
+ inputSchema: zodToJsonSchema(contextSwitchOptions, { strictUnions: true }),
97
+ annotations: {
98
+ title: 'Connect to a browser running in VS Code.',
99
+ readOnlyHint: true,
100
+ openWorldHint: false,
101
+ },
102
+ };
103
+ }
104
+ async _setCurrentClient(transport) {
105
+ await this._currentClient?.close();
106
+ this._currentClient = undefined;
107
+ const client = new Client(this._clientVersion);
108
+ client.registerCapabilities({
109
+ roots: {
110
+ listRoots: true,
111
+ },
112
+ });
113
+ client.setRequestHandler(ListRootsRequestSchema, () => ({ roots: this._roots }));
114
+ client.setRequestHandler(PingRequestSchema, () => ({}));
115
+ await client.connect(transport);
116
+ this._currentClient = client;
117
+ }
118
+ }
119
+ export async function runVSCodeTools(config) {
120
+ const serverBackendFactory = {
121
+ name: 'Playwright w/ vscode',
122
+ nameInConfig: 'playwright-vscode',
123
+ version: packageJSON.version,
124
+ create: () => new VSCodeProxyBackend(config, () => mcpServer.wrapInProcess(new BrowserServerBackend(config, contextFactory(config))))
125
+ };
126
+ await mcpServer.start(serverBackendFactory, config.server);
127
+ return;
128
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
17
+ import * as mcpServer from '../mcp/server.js';
18
+ import { BrowserServerBackend } from '../browserServerBackend.js';
19
+ class VSCodeBrowserContextFactory {
20
+ _config;
21
+ _playwright;
22
+ _connectionString;
23
+ name = 'vscode';
24
+ description = 'Connect to a browser running in the Playwright VS Code extension';
25
+ constructor(_config, _playwright, _connectionString) {
26
+ this._config = _config;
27
+ this._playwright = _playwright;
28
+ this._connectionString = _connectionString;
29
+ }
30
+ async createContext(clientInfo, abortSignal) {
31
+ let launchOptions = this._config.browser.launchOptions;
32
+ if (this._config.browser.userDataDir) {
33
+ launchOptions = {
34
+ ...launchOptions,
35
+ ...this._config.browser.contextOptions,
36
+ userDataDir: this._config.browser.userDataDir,
37
+ };
38
+ }
39
+ const connectionString = new URL(this._connectionString);
40
+ connectionString.searchParams.set('launch-options', JSON.stringify(launchOptions));
41
+ const browserType = this._playwright.chromium; // it could also be firefox or webkit, we just need some browser type to call `connect` on
42
+ const browser = await browserType.connect(connectionString.toString());
43
+ const context = browser.contexts()[0] ?? await browser.newContext(this._config.browser.contextOptions);
44
+ return {
45
+ browserContext: context,
46
+ close: async () => {
47
+ await browser.close();
48
+ }
49
+ };
50
+ }
51
+ }
52
+ async function main(config, connectionString, lib) {
53
+ const playwright = await import(lib).then(mod => mod.default ?? mod);
54
+ const factory = new VSCodeBrowserContextFactory(config, playwright, connectionString);
55
+ await mcpServer.connect({
56
+ name: 'Playwright MCP',
57
+ nameInConfig: 'playwright-vscode',
58
+ create: () => new BrowserServerBackend(config, factory),
59
+ version: 'unused'
60
+ }, new StdioServerTransport(), false);
61
+ }
62
+ await main(JSON.parse(process.argv[2]), process.argv[3], process.argv[4]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@playwright/mcp",
3
- "version": "0.0.34",
3
+ "version": "0.0.35-alpha-2025-08-28",
4
4
  "description": "Playwright Tools for MCP",
5
5
  "type": "module",
6
6
  "repository": {
@@ -1,39 +0,0 @@
1
- /**
2
- * Copyright (c) Microsoft Corporation.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- import assert from 'assert';
17
- import http from 'http';
18
- export async function startHttpServer(config) {
19
- const { host, port } = config;
20
- const httpServer = http.createServer();
21
- await new Promise((resolve, reject) => {
22
- httpServer.on('error', reject);
23
- httpServer.listen(port, host, () => {
24
- resolve();
25
- httpServer.removeListener('error', reject);
26
- });
27
- });
28
- return httpServer;
29
- }
30
- export function httpAddressToString(address) {
31
- assert(address, 'Could not bind server socket');
32
- if (typeof address === 'string')
33
- return address;
34
- const resolvedPort = address.port;
35
- let resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`;
36
- if (resolvedHost === '0.0.0.0' || resolvedHost === '[::]')
37
- resolvedHost = 'localhost';
38
- return `http://${resolvedHost}:${resolvedPort}`;
39
- }
File without changes