Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

chore: refactor cli/daemon commands (#38889)

Pavel Feldman7e407f00b45e
diff --git a/packages/playwright/src/mcp/browser/context.ts b/packages/playwright/src/mcp/browser/context.ts
index 674ca1df08..c0e3e80b7c 100644
--- a/packages/playwright/src/mcp/browser/context.ts
+++ b/packages/playwright/src/mcp/browser/context.ts
@@ -79,7 +79,7 @@ export class Context {
currentTabOrDie(): Tab {
if (!this._currentTab)
- throw new Error('No open pages available. Use the "browser_navigate" tool to navigate to a page first.');
+ throw new Error('No open pages available.');
return this._currentTab;
}
diff --git a/packages/playwright/src/mcp/terminal/cli.ts b/packages/playwright/src/mcp/terminal/cli.ts
index a6c90195c4..a8a0343299 100644
--- a/packages/playwright/src/mcp/terminal/cli.ts
+++ b/packages/playwright/src/mcp/terminal/cli.ts
@@ -15,6 +15,7 @@
*/
/* eslint-disable no-console */
+/* eslint-disable no-restricted-properties */
import { spawn } from 'child_process';
import crypto from 'crypto';
@@ -24,7 +25,6 @@ import os from 'os';
import path from 'path';
import { debug } from 'playwright-core/lib/utilsBundle';
import { SocketConnection } from './socketConnection';
-import { aliases, globalHelp, helpMessage } from './commands';
import type * as mcp from '../sdk/exports';
@@ -32,9 +32,9 @@ const debugCli = debug('pw:cli');
const packageJSON = require('../../../package.json');
-async function runMcpCommand(argv: string[], options: { headless?: boolean } = {}) {
+async function runCliCommand(args: any, options: { headless?: boolean } = {}) {
const session = await connectToDaemon(options);
- const result = await session.runCliCommand(argv);
+ const result = await session.runCliCommand(args);
console.log(result);
session.dispose();
}
@@ -65,8 +65,8 @@ class SocketSession {
return this._send(name, args);
}
- async runCliCommand(argv: string[]): Promise<string> {
- return await this._send('runCliCommand', { argv });
+ async runCliCommand(args: any): Promise<string> {
+ return await this._send('runCliCommand', { args });
}
private async _send(method: string, params: any = {}): Promise<any> {
@@ -186,29 +186,31 @@ async function connectToSocket(socketPath: string): Promise<SocketSession> {
function main() {
const argv = process.argv.slice(2);
const args = require('minimist')(argv);
- const command = args._[0];
- if (args.help || args.h || !command) {
- // case of '--help navigate'
- const commandName = command ?? args.help ?? args.h;
- if (commandName && commandName in helpMessage)
- console.log(helpMessage[commandName]);
- else
- console.log(globalHelp);
- // eslint-disable-next-line no-restricted-properties
+ const help = require('./help.json');
+ const command = help.commands[args._[0]];
+ if (args.help || args.h) {
+ if (command) {
+ console.log(command);
+ } else {
+ console.log('playwright-cli - run playwright mcp commands from terminal\n');
+ console.log(help.global);
+ }
process.exit(0);
}
+ if (!command) {
+ console.error(`Unknown command: ${args._[0]}\n`);
+ console.log(help.global);
+ process.exit(1);
+ }
if (args.version || args.v) {
console.log(packageJSON.version);
- // eslint-disable-next-line no-restricted-properties
process.exit(0);
}
- const options: any = { };
- if (command === 'navigate' || aliases['navigate'].includes(command))
- options.headless = !args.headed;
- runMcpCommand(argv, options).catch(e => {
- console.error(e.message);
- // eslint-disable-next-line no-restricted-properties
+
+ runCliCommand(args).catch(e => {
+ console.error(e);
+
process.exit(1);
});
}
diff --git a/packages/playwright/src/mcp/terminal/command.ts b/packages/playwright/src/mcp/terminal/command.ts
new file mode 100644
index 0000000000..306114788a
--- /dev/null
+++ b/packages/playwright/src/mcp/terminal/command.ts
@@ -0,0 +1,46 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type zodType from 'zod';
+
+export type CommandSchema<Args extends zodType.ZodTypeAny, Options extends zodType.ZodTypeAny> = {
+ name: string;
+ description: string;
+ args?: Args;
+ options?: Options;
+ toolName: string | ((args: zodType.infer<Args>, options: zodType.infer<Options>) => string);
+ toolParams: (args: zodType.infer<Args>, options: zodType.infer<Options>) => any;
+};
+
+export type AnyCommandSchema = CommandSchema<any, any>;
+
+export function declareCommand<Args extends zodType.ZodTypeAny, Options extends zodType.ZodTypeAny>(command: CommandSchema<Args, Options>): CommandSchema<Args, Options> {
+ return command;
+}
+
+export function parseCommand(command: AnyCommandSchema, args: Record<string, string> & { _: string[] }): { toolName: string, toolParams: any } {
+ const shape = command.args ? (command.args as zodType.ZodObject<any>).shape : {};
+ const argv = args['_'];
+ const options = command.options?.parse({ ...args, _: undefined }) ?? {};
+ const argsObject: Record<string, string> = {};
+ let i = 0;
+ for (const name of Object.keys(shape))
+ argsObject[name] = argv[++i];
+ const parsedArgsObject = command.args?.parse(argsObject) ?? {};
+ const toolName = typeof command.toolName === 'function' ? command.toolName(parsedArgsObject, options) : command.toolName;
+ const toolParams = command.toolParams(parsedArgsObject, options);
+ return { toolName, toolParams };
+}
diff --git a/packages/playwright/src/mcp/terminal/commands.ts b/packages/playwright/src/mcp/terminal/commands.ts
index fb135f11bf..2b858bc2bf 100644
--- a/packages/playwright/src/mcp/terminal/commands.ts
+++ b/packages/playwright/src/mcp/terminal/commands.ts
@@ -14,429 +14,345 @@
* limitations under the License.
*/
-/* eslint-disable @stylistic/indent */
-// Commands generated by generate_cli_commands.js
-
-export const helpMessage: Record<string, string> = {};
-
-helpMessage['close'] =
-`playwright-cli close
-
-Close the page
-`;
-
-helpMessage['resize'] =
-`playwright-cli resize <width> <height>
-
-Resize the browser window
-
-Parameters:
- <width> Width of the browser window
- <height> Height of the browser window
-`;
-
-helpMessage['console_messages'] =
-`playwright-cli console_messages
-
-Returns all console messages
-
-Options:
- --level Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".
-`;
-
-helpMessage['handle_dialog'] =
-`playwright-cli handle_dialog <accept>
-
-Handle a dialog
-
-Parameters:
- <accept> Whether to accept the dialog.
-
-Options:
- --prompt-text The text of the prompt in case of a prompt dialog.
-`;
-
-helpMessage['evaluate'] =
-`playwright-cli evaluate <function>
-
-Evaluate JavaScript expression on page or element
-
-Parameters:
- <function> () => { /* code */ } or (element) => { /* code */ } when element is provided
-
-Options:
- --element Human-readable element description used to obtain permission to interact with the element
- --ref Exact target element reference from the page snapshot
-`;
-
-helpMessage['file_upload'] =
-`playwright-cli file_upload
-
-Upload one or multiple files
-
-Options:
- --paths The absolute paths to the files to upload. Can be single file or multiple files. If omitted, file chooser is cancelled.
-`;
-
-helpMessage['fill_form'] =
-`playwright-cli fill_form <fields>
-
-Fill multiple form fields
-
-Parameters:
- <fields> Fields to fill in
-`;
-
-helpMessage['install'] =
-`playwright-cli install
-
-Install the browser specified in the config. Call this if you get an error about the browser not being installed.
-`;
-
-helpMessage['press_key'] =
-`playwright-cli press_key <key>
-
-Press a key on the keyboard
-
-Parameters:
- <key> Name of the key to press or a character to generate, such as \`ArrowLeft\` or \`a\`
-`;
-
-helpMessage['type'] =
-`playwright-cli type <ref> <text>
-
-Type text into editable element
-
-Parameters:
- <ref> Exact target element reference from the page snapshot
- <text> Text to type into the element
-
-Options:
- --element Human-readable element description used to obtain permission to interact with the element
- --submit Whether to submit entered text (press Enter after)
- --slowly Whether to type one character at a time. Useful for triggering key handlers in the page. By default entire text is filled in at once.
-`;
-
-helpMessage['navigate'] =
-`playwright-cli navigate <url>
-
-Navigate to a URL
-
-Aliases: goto, open
-
-Parameters:
- <url> The URL to navigate to
-
-Options:
- --headed run browser in headed mode
-`;
-
-helpMessage['navigate_back'] =
-`playwright-cli navigate_back
-
-Go back to the previous page
-`;
-
-helpMessage['network_requests'] =
-`playwright-cli network_requests
-
-Returns all network requests since loading the page
-
-Options:
- --include-static Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.
-`;
-
-helpMessage['mouse_move_xy'] =
-`playwright-cli mouse_move_xy <element> <x> <y>
-
-Move mouse to a given position
-
-Parameters:
- <element> Human-readable element description used to obtain permission to interact with the element
- <x> X coordinate
- <y> Y coordinate
-`;
-
-helpMessage['mouse_click_xy'] =
-`playwright-cli mouse_click_xy <element> <x> <y>
-
-Click left mouse button at a given position
-
-Parameters:
- <element> Human-readable element description used to obtain permission to interact with the element
- <x> X coordinate
- <y> Y coordinate
-`;
-
-helpMessage['mouse_drag_xy'] =
-`playwright-cli mouse_drag_xy <element> <startX> <startY> <endX> <endY>
-
-Drag left mouse button to a given position
-
-Parameters:
- <element> Human-readable element description used to obtain permission to interact with the element
- <startX> Start X coordinate
- <startY> Start Y coordinate
- <endX> End X coordinate
- <endY> End Y coordinate
-`;
-
-helpMessage['pdf_save'] =
-`playwright-cli pdf_save
-
-Save page as PDF
-
-Options:
- --filename File name to save the pdf to. Defaults to \`page-{timestamp}.pdf\` if not specified. Prefer relative file names to stay within the output directory.
-`;
-
-helpMessage['run_code'] =
-`playwright-cli run_code <code>
-
-Run Playwright code snippet
-
-Parameters:
- <code> A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction. For example: \`async (page) => { await page.getByRole('button', { name: 'Submit' }).click(); return await page.title(); }\`
-`;
-
-helpMessage['take_screenshot'] =
-`playwright-cli take_screenshot
-
-Take a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.
-
-Aliases: screenshot
-
-Options:
- --type Image format for the screenshot. Default is png.
- --filename File name to save the screenshot to. Defaults to \`page-{timestamp}.{png|jpeg}\` if not specified. Prefer relative file names to stay within the output directory.
- --element Human-readable element description used to obtain permission to screenshot the element. If not provided, the screenshot will be taken of viewport. If element is provided, ref must be provided too.
- --ref Exact target element reference from the page snapshot. If not provided, the screenshot will be taken of viewport. If ref is provided, element must be provided too.
- --full-page When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Cannot be used with element screenshots.
-`;
-
-helpMessage['snapshot'] =
-`playwright-cli snapshot
-
-Capture accessibility snapshot of the current page, this is better than screenshot
-
-Options:
- --filename Save snapshot to markdown file instead of returning it in the response.
-`;
-
-helpMessage['click'] =
-`playwright-cli click <ref>
-
-Perform click on a web page
-
-Parameters:
- <ref> Exact target element reference from the page snapshot
-
-Options:
- --element Human-readable element description used to obtain permission to interact with the element
- --double-click Whether to perform a double click instead of a single click
- --button Button to click, defaults to left
- --modifiers Modifier keys to press
-`;
-
-helpMessage['drag'] =
-`playwright-cli drag <startElement> <startRef> <endElement> <endRef>
-
-Perform drag and drop between two elements
-
-Parameters:
- <startElement> Human-readable source element description used to obtain the permission to interact with the element
- <startRef> Exact source element reference from the page snapshot
- <endElement> Human-readable target element description used to obtain the permission to interact with the element
- <endRef> Exact target element reference from the page snapshot
-`;
-
-helpMessage['hover'] =
-`playwright-cli hover <ref>
-
-Hover over element on page
-
-Parameters:
- <ref> Exact target element reference from the page snapshot
-
-Options:
- --element Human-readable element description used to obtain permission to interact with the element
-`;
-
-helpMessage['select_option'] =
-`playwright-cli select_option <ref> <values>
-
-Select an option in a dropdown
-
-Parameters:
- <ref> Exact target element reference from the page snapshot
- <values> Array of values to select in the dropdown. This can be a single value or multiple values.
-
-Options:
- --element Human-readable element description used to obtain permission to interact with the element
-`;
-
-helpMessage['generate_locator'] =
-`playwright-cli generate_locator <ref>
-
-Generate locator for the given element to use in tests
-
-Parameters:
- <ref> Exact target element reference from the page snapshot
-
-Options:
- --element Human-readable element description used to obtain permission to interact with the element
-`;
-
-helpMessage['tabs'] =
-`playwright-cli tabs <action>
-
-List, create, close, or select a browser tab.
-
-Parameters:
- <action> Operation to perform
-
-Options:
- --index Tab index, used for close/select. If omitted for close, current tab is closed.
-`;
-
-helpMessage['start_tracing'] =
-`playwright-cli start_tracing
-
-Start trace recording
-`;
-
-helpMessage['stop_tracing'] =
-`playwright-cli stop_tracing
-
-Stop trace recording
-`;
-
-helpMessage['wait_for'] =
-`playwright-cli wait_for
-
-Wait for text to appear or disappear or a specified time to pass
-
-Options:
- --time The time to wait in seconds
- --text The text to wait for
- --text-gone The text to wait for to disappear
-`;
-
-helpMessage['verify_element_visible'] =
-`playwright-cli verify_element_visible <role> <accessibleName>
-
-Verify element is visible on the page
-
-Parameters:
- <role> ROLE of the element. Can be found in the snapshot like this: \`- {ROLE} "Accessible Name":\`
- <accessibleName> ACCESSIBLE_NAME of the element. Can be found in the snapshot like this: \`- role "{ACCESSIBLE_NAME}"\`
-`;
-
-helpMessage['verify_text_visible'] =
-`playwright-cli verify_text_visible <text>
-
-Verify text is visible on the page. Prefer browser_verify_element_visible if possible.
-
-Parameters:
- <text> TEXT to verify. Can be found in the snapshot like this: \`- role "Accessible Name": {TEXT}\` or like this: \`- text: {TEXT}\`
-`;
-
-helpMessage['verify_list_visible'] =
-`playwright-cli verify_list_visible <element> <ref> <items>
-
-Verify list is visible on the page
-
-Parameters:
- <element> Human-readable list description
- <ref> Exact target element reference that points to the list
- <items> Items to verify
-`;
-
-helpMessage['verify_value'] =
-`playwright-cli verify_value <type> <element> <ref> <value>
-
-Verify element value
-
-Parameters:
- <type> Type of the element
- <element> Human-readable element description
- <ref> Exact target element reference that points to the element
- <value> Value to verify. For checkbox, use "true" or "false".
-`;
-
-export const globalHelp: string =
-`playwright-cli - run playwright mcp commands from terminal
-
-Usage: playwright-cli <command> [options]
-
-Core:
- close close browser
- resize <width> <height> resize browser window
- console_messages get console messages
- handle_dialog <accept> handle a dialog
- evaluate <function> evaluate JavaScript
- file_upload upload files
- fill_form <fields> fill form
- press_key <key> press a key
- type <ref> <text> type text
- navigate <url> navigate to a URL
- navigate_back go back
- network_requests list network requests
- run_code <code> run Playwright code
- take_screenshot take a screenshot
- snapshot page snapshot
- click <ref> click
- drag <startElement> <startRef> <endElement> <endRef>
- drag mouse
- hover <ref> hover mouse
- select_option <ref> <values>select option
- wait_for wait for
-
-Tab management:
- tabs <action> manage tabs
-
-Browser installation:
- install install the browser specified in the config
-
-Coordinate-based:
- mouse_move_xy <element> <x> <y>
- move mouse
- mouse_click_xy <element> <x> <y>
- click
- mouse_drag_xy <element> <startX> <startY> <endX> <endY>
- drag mouse
-
-PDF generation:
- pdf_save save as PDF
-
-Tracing:
- start_tracing start tracing
- stop_tracing stop tracing
-
-Testing:
- generate_locator <ref> create locator for element
- verify_element_visible <role> <accessibleName>
- verify element visible
- verify_text_visible <text> verify text visible
- verify_list_visible <element> <ref> <items>
- verify list visible
- verify_value <type> <element> <ref> <value>
- verify value
-
-Options:
- --help show help for a specific command
- --version show version information
-
-Examples:
- playwright-cli navigate https://playwright.dev
- playwright-cli snapshot
- playwright-cli click e67
-`;
-
-export const aliases: Record<string, string[]> = {
- 'navigate': ['goto', 'open'],
- 'take_screenshot': ['screenshot'],
-};
-
-// End of commands generated section
+import { z } from 'playwright-core/lib/mcpBundle';
+import { declareCommand } from './command';
+
+import type { AnyCommandSchema } from './command';
+
+const click = declareCommand({
+ name: 'click',
+ description: 'Perform click on a web page',
+ args: z.object({
+ ref: z.string().describe('Exact target element reference from the page snapshot'),
+ }),
+ options: z.object({
+ button: z.string().optional().describe('Button to click, defaults to left'),
+ modifiers: z.array(z.string()).optional().describe('Modifier keys to press'),
+ }),
+ toolName: 'browser_click',
+ toolParams: ({ ref }, { button, modifiers }) => ({ ref, button, modifiers }),
+});
+
+const doubleClick = declareCommand({
+ name: 'dblclick',
+ description: 'Perform double click on a web page',
+ args: z.object({
+ ref: z.string().describe('Exact target element reference from the page snapshot'),
+ }),
+ options: z.object({
+ button: z.string().optional().describe('Button to click, defaults to left'),
+ modifiers: z.array(z.string()).optional().describe('Modifier keys to press'),
+ }),
+ toolName: 'browser_click',
+ toolParams: ({ ref }, { button, modifiers }) => ({ ref, button, modifiers, doubleClick: true }),
+});
+
+const close = declareCommand({
+ name: 'close',
+ description: 'Close the page',
+ args: z.object({}),
+ toolName: 'browser_close',
+ toolParams: () => ({}),
+});
+
+const consoleMessages = declareCommand({
+ name: 'console',
+ description: 'Returns all console messages',
+ args: z.object({
+ level: z.string().optional().describe('Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".'),
+ }),
+ toolName: 'browser_console_messages',
+ toolParams: ({ level }) => ({ level }),
+});
+
+const drag = declareCommand({
+ name: 'drag',
+ description: 'Perform drag and drop between two elements',
+ args: z.object({
+ startRef: z.string().describe('Exact source element reference from the page snapshot'),
+ endRef: z.string().describe('Exact target element reference from the page snapshot'),
+ }),
+ options: z.object({
+ headed: z.boolean().default(false).describe('Run browser in headed mode'),
+ }),
+ toolName: 'browser_drag',
+ toolParams: ({ startRef, endRef }) => ({ startRef, endRef }),
+});
+
+const evaluate = declareCommand({
+ name: 'evaluate',
+ description: 'Evaluate JavaScript expression on page or element',
+ args: z.object({
+ function: z.string().describe('() => { /* code */ } or (element) => { /* code */ } when element is provided'),
+ ref: z.string().optional().describe('Exact target element reference from the page snapshot'),
+ }),
+ toolName: 'browser_evaluate',
+ toolParams: ({ function: fn, ref }) => ({ function: fn, ref }),
+});
+
+const fileUpload = declareCommand({
+ name: 'upload-file',
+ description: 'Upload one or multiple files',
+ args: z.object({}),
+ options: z.object({
+ paths: z.array(z.string()).optional().describe('The absolute paths to the files to upload. Can be single file or multiple files. If omitted, file chooser is cancelled.'),
+ }),
+ toolName: 'browser_file_upload',
+ toolParams: (_, { paths }) => ({ paths }),
+});
+
+const handleDialog = declareCommand({
+ name: 'handle-dialog',
+ description: 'Handle a dialog',
+ args: z.object({
+ accept: z.boolean().describe('Whether to accept the dialog.'),
+ promptText: z.string().optional().describe('The text of the prompt in case of a prompt dialog.'),
+ }),
+ toolName: 'browser_handle_dialog',
+ toolParams: ({ accept, promptText }) => ({ accept, promptText }),
+});
+
+const hover = declareCommand({
+ name: 'hover',
+ description: 'Hover over element on page',
+ args: z.object({
+ ref: z.string().describe('Exact target element reference from the page snapshot'),
+ }),
+ toolName: 'browser_hover',
+ toolParams: ({ ref }) => ({ ref }),
+});
+
+const open = declareCommand({
+ name: 'open',
+ description: 'Open URL',
+ args: z.object({
+ url: z.string().describe('The URL to navigate to'),
+ }),
+ options: z.object({
+ headed: z.boolean().default(false).describe('Run browser in headed mode'),
+ }),
+ toolName: 'browser_navigate',
+ toolParams: ({ url }, { headed }) => ({ url, headed }),
+});
+
+const navigateBack = declareCommand({
+ name: 'go-back',
+ description: 'Go back to the previous page',
+ args: z.object({}),
+ toolName: 'browser_navigate_back',
+ toolParams: () => ({}),
+});
+
+const networkRequests = declareCommand({
+ name: 'network-requests',
+ description: 'Returns all network requests since loading the page',
+ args: z.object({}),
+ options: z.object({
+ includeStatic: z.boolean().optional().describe('Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.'),
+ }),
+ toolName: 'browser_network_requests',
+ toolParams: (_, { includeStatic }) => ({ includeStatic }),
+});
+
+const pressKey = declareCommand({
+ name: 'press-key',
+ description: 'Press a key on the keyboard',
+ args: z.object({
+ key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),
+ }),
+ toolName: 'browser_press_key',
+ toolParams: ({ key }) => ({ key }),
+});
+
+const resize = declareCommand({
+ name: 'resize',
+ description: 'Resize the browser window',
+ args: z.object({
+ width: z.number().describe('Width of the browser window'),
+ height: z.number().describe('Height of the browser window'),
+ }),
+ toolName: 'browser_resize',
+ toolParams: ({ width, height }) => ({ width, height }),
+});
+
+const runCode = declareCommand({
+ name: 'run-code',
+ description: 'Run Playwright code snippet',
+ args: z.object({
+ code: z.string().describe('A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction.'),
+ }),
+ toolName: 'browser_run_code',
+ toolParams: ({ code }) => ({ code }),
+});
+
+const selectOption = declareCommand({
+ name: 'select-option',
+ description: 'Select an option in a dropdown',
+ args: z.object({
+ ref: z.string().describe('Exact target element reference from the page snapshot'),
+ values: z.array(z.string()).describe('Array of values to select in the dropdown. This can be a single value or multiple values.'),
+ }),
+ toolName: 'browser_select_option',
+ toolParams: ({ ref, values }) => ({ ref, values }),
+});
+
+const snapshot = declareCommand({
+ name: 'snapshot',
+ description: 'Capture accessibility snapshot of the current page, this is better than screenshot',
+ args: z.object({}),
+ options: z.object({
+ filename: z.string().optional().describe('Save snapshot to markdown file instead of returning it in the response.'),
+ }),
+ toolName: 'browser_snapshot',
+ toolParams: (_, { filename }) => ({ filename }),
+});
+
+const screenshot = declareCommand({
+ name: 'screenshot',
+ description: 'Take a screenshot of the current page. You can\'t perform actions based on the screenshot, use browser_snapshot for actions.',
+ args: z.object({
+ ref: z.string().optional().describe('Exact target element reference from the page snapshot.'),
+ }),
+ options: z.object({
+ filename: z.string().optional().describe('File name to save the screenshot to. Defaults to `page-{timestamp}.{png|jpeg}` if not specified.'),
+ fullPage: z.boolean().optional().describe('When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport.'),
+ }),
+ toolName: 'browser_take_screenshot',
+ toolParams: ({ ref }, { filename, fullPage }) => ({ filename, ref, fullPage }),
+});
+
+const type = declareCommand({
+ name: 'type',
+ description: 'Type text into editable element',
+ args: z.object({
+ ref: z.string().describe('Exact target element reference from the page snapshot'),
+ text: z.string().describe('Text to type into the element'),
+ }),
+ options: z.object({
+ submit: z.boolean().optional().describe('Whether to submit entered text (press Enter after)'),
+ slowly: z.boolean().optional().describe('Whether to type one character at a time. Useful for triggering key handlers in the page.'),
+ }),
+ toolName: 'browser_type',
+ toolParams: ({ ref, text }, { submit, slowly }) => ({ ref, text, submit, slowly }),
+});
+
+const waitFor = declareCommand({
+ name: 'wait-for',
+ description: 'Wait for text to appear or disappear or a specified time to pass',
+ args: z.object({}),
+ options: z.object({
+ time: z.number().optional().describe('The time to wait in seconds'),
+ text: z.string().optional().describe('The text to wait for'),
+ textGone: z.string().optional().describe('The text to wait for to disappear'),
+ }),
+ toolName: 'browser_wait_for',
+ toolParams: (_, { time, text, textGone }) => ({ time, text, textGone }),
+});
+
+const tab = declareCommand({
+ name: 'tab',
+ description: 'Close a browser tab',
+ args: z.object({
+ action: z.string().describe(`Action to perform on tabs, 'list' | 'new' | 'close' | 'select'`),
+ index: z.number().optional().describe('Tab index. If omitted, current tab is closed.'),
+ }),
+ toolName: 'browser_tabs',
+ toolParams: ({ index }) => ({ action: 'close', index }),
+});
+
+const mouseClickXy = declareCommand({
+ name: 'mouse-click-xy',
+ description: 'Click left mouse button at a given position',
+ args: z.object({
+ x: z.number().describe('X coordinate'),
+ y: z.number().describe('Y coordinate'),
+ }),
+ toolName: 'browser_mouse_click_xy',
+ toolParams: ({ x, y }) => ({ x, y }),
+});
+
+const mouseDragXy = declareCommand({
+ name: 'mouse-drag-xy',
+ description: 'Drag left mouse button to a given position',
+ args: z.object({
+ startX: z.number().describe('Start X coordinate'),
+ startY: z.number().describe('Start Y coordinate'),
+ endX: z.number().describe('End X coordinate'),
+ endY: z.number().describe('End Y coordinate'),
+ }),
+ toolName: 'browser_mouse_drag_xy',
+ toolParams: ({ startX, startY, endX, endY }) => ({ startX, startY, endX, endY }),
+});
+
+const mouseMoveXy = declareCommand({
+ name: 'mouse-move-xy',
+ description: 'Move mouse to a given position',
+ args: z.object({
+ x: z.number().describe('X coordinate'),
+ y: z.number().describe('Y coordinate'),
+ }),
+ toolName: 'browser_mouse_move_xy',
+ toolParams: ({ x, y }) => ({ x, y }),
+});
+
+// PDF generation commands (opt-in via --caps=pdf)
+
+const pdfSave = declareCommand({
+ name: 'pdf-save',
+ description: 'Save page as PDF',
+ args: z.object({}),
+ options: z.object({
+ filename: z.string().optional().describe('File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified.'),
+ }),
+ toolName: 'browser_pdf_save',
+ toolParams: (_, { filename }) => ({ filename }),
+});
+
+const startTracing = declareCommand({
+ name: 'start-tracing',
+ description: 'Start trace recording',
+ args: z.object({}),
+ toolName: 'browser_start_tracing',
+ toolParams: () => ({}),
+});
+
+const stopTracing = declareCommand({
+ name: 'stop-tracing',
+ description: 'Stop trace recording',
+ args: z.object({}),
+ toolName: 'browser_stop_tracing',
+ toolParams: () => ({}),
+});
+
+const commandsArray: AnyCommandSchema[] = [
+ click,
+ close,
+ doubleClick,
+ consoleMessages,
+ drag,
+ evaluate,
+ fileUpload,
+ handleDialog,
+ hover,
+ open,
+ navigateBack,
+ networkRequests,
+ pressKey,
+ resize,
+ runCode,
+ selectOption,
+ snapshot,
+ screenshot,
+ type,
+ waitFor,
+ tab,
+ mouseClickXy,
+ mouseDragXy,
+ mouseMoveXy,
+ pdfSave,
+ startTracing,
+ stopTracing,
+];
+
+export const commands = Object.fromEntries(commandsArray.map(cmd => [cmd.name, cmd]));
diff --git a/packages/playwright/src/mcp/terminal/daemon.ts b/packages/playwright/src/mcp/terminal/daemon.ts
index dd6e507cb7..8a04d7bf9d 100644
--- a/packages/playwright/src/mcp/terminal/daemon.ts
+++ b/packages/playwright/src/mcp/terminal/daemon.ts
@@ -22,12 +22,11 @@ import url from 'url';
import { debug } from 'playwright-core/lib/utilsBundle';
import { SocketConnection } from './socketConnection';
-import { browserTools } from '../browser/tools';
-import { aliases } from './commands';
+import { commands } from './commands';
+import { parseCommand } from './command';
import type { ServerBackendFactory } from '../sdk/server';
import type * as mcp from '../sdk/exports';
-import type { z } from 'zod';
const daemonDebug = debug('pw:daemon');
@@ -84,9 +83,8 @@ export async function startMcpDaemonServer(
try {
daemonDebug('received command', method);
if (method === 'runCliCommand') {
- const { toolName, args } = parseCliCommand(params.argv);
- const adjustedArgs = adjustCommandParameters(toolName, args);
- const response = await backend.callTool(toolName, adjustedArgs, () => {});
+ const { toolName, toolParams } = parseCliCommand(params.args);
+ const response = await backend.callTool(toolName, toolParams, () => {});
await connection.send({ id, result: formatResult(response) });
} else {
throw new Error(`Unknown method: ${method}`);
@@ -122,65 +120,9 @@ function formatResult(result: mcp.CallToolResult) {
return lines.join('\n');
}
-function camelToKebabCase(camel: string): string {
- return camel.replace(/([A-Z])/g, letter => `-${letter.toLowerCase()}`);
-}
-
-function canonicalName(name: string): string {
- for (const [canonicalName, nameAliases] of Object.entries(aliases)) {
- if (nameAliases.includes(name))
- return canonicalName;
- }
- return name;
-}
-
-function parseCliCommand(argv: string[]): { toolName: string, args: mcp.CallToolRequest['params']['arguments'] } {
- const parsed = require('minimist')(argv);
-
- const commandAlias = parsed._[0];
- if (!commandAlias)
+function parseCliCommand(args: Record<string, string> & { _: string[] }): { toolName: string, toolParams: mcp.CallToolRequest['params']['arguments'] } {
+ const command = commands[args._[0]];
+ if (!command)
throw new Error('Command is required');
-
- const toolName = `browser_${canonicalName(commandAlias)}`;
- const tool = browserTools.find(tool => tool.schema.name === toolName);
- if (!tool)
- throw new Error(`Unknown command: ${commandAlias}.`);
-
- const args: mcp.CallToolRequest['params']['arguments'] = {};
-
- const inputSchema = tool.schema.inputSchema.toJSONSchema() as z.core.JSONSchema.BaseSchema;
-
- const requiredProperties = (inputSchema.required || []).filter(p => {
- const property = inputSchema.properties?.[p];
- return !(typeof property === 'object' && 'default' in property);
- });
-
- const freeArguments = parsed._.slice(1);
- if (requiredProperties.length && freeArguments.length < requiredProperties.length)
- throw new Error(`Missing required parameter(s): ${requiredProperties.slice(freeArguments.length).map(r => `${r}`).join(', ')}`);
-
- let index = 0;
- for (const requiredProperty of requiredProperties)
- args[requiredProperty] = freeArguments[index++];
-
- Object.entries(inputSchema.properties || {}).forEach(([propertyName, schema]) => {
- const optionName = camelToKebabCase(propertyName);
- if (optionName in parsed)
- args[propertyName] = parsed[optionName];
- else if (typeof schema === 'object' && schema.default !== undefined)
- args[propertyName] = schema.default;
- });
-
- return { toolName, args };
-}
-
-function adjustCommandParameters(toolName: string, args: mcp.CallToolRequest['params']['arguments']): mcp.CallToolRequest['params']['arguments'] {
- if (toolName === 'browser_snapshot') {
- args ??= {};
- if (!('filename' in args)) {
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
- args.filename = `snapshot-${timestamp}.md`;
- }
- }
- return args;
+ return parseCommand(command, args);
}
diff --git a/packages/playwright/src/mcp/terminal/help.json b/packages/playwright/src/mcp/terminal/help.json
new file mode 100644
index 0000000000..e064df95da
--- /dev/null
+++ b/packages/playwright/src/mcp/terminal/help.json
@@ -0,0 +1,32 @@
+{
+ "global": "Usage: playwright-cli <command> [options]\nCommands:\n click <ref> perform click on a web page\n close close the page\n dblclick <ref> perform double click on a web page\n console <level> returns all console messages\n drag <startRef> <endRef> perform drag and drop between two elements\n evaluate <function> <ref> evaluate javascript expression on page or element\n upload-file upload one or multiple files\n handle-dialog <accept> <promptText> handle a dialog\n hover <ref> hover over element on page\n open <url> open url\n go-back go back to the previous page\n network-requests returns all network requests since loading the page\n press-key <key> press a key on the keyboard\n resize <width> <height> resize the browser window\n run-code <code> run playwright code snippet\n select-option <ref> <values> select an option in a dropdown\n snapshot capture accessibility snapshot of the current page, this is better than screenshot\n screenshot <ref> take a screenshot of the current page. you can't perform actions based on the screenshot, use browser_snapshot for actions.\n type <ref> <text> type text into editable element\n wait-for wait for text to appear or disappear or a specified time to pass\n tab <action> <index> close a browser tab\n mouse-click-xy <x> <y> click left mouse button at a given position\n mouse-drag-xy <startX> <startY> <endX> <endY> drag left mouse button to a given position\n mouse-move-xy <x> <y> move mouse to a given position\n pdf-save save page as pdf\n start-tracing start trace recording\n stop-tracing stop trace recording",
+ "commands": {
+ "click": "playwright-cli click <ref>\n\nPerform click on a web page\n\nArguments:\n <ref>\tExact target element reference from the page snapshot\nOptions:\n --button\tbutton to click, defaults to left\n --modifiers\tmodifier keys to press",
+ "close": "playwright-cli close \n\nClose the page\n",
+ "dblclick": "playwright-cli dblclick <ref>\n\nPerform double click on a web page\n\nArguments:\n <ref>\tExact target element reference from the page snapshot\nOptions:\n --button\tbutton to click, defaults to left\n --modifiers\tmodifier keys to press",
+ "console": "playwright-cli console <level>\n\nReturns all console messages\n\nArguments:\n <level>\tLevel of the console messages to return. Each level includes the messages of more severe levels. Defaults to \"info\".",
+ "drag": "playwright-cli drag <startRef> <endRef>\n\nPerform drag and drop between two elements\n\nArguments:\n <startRef>\tExact source element reference from the page snapshot\n <endRef>\tExact target element reference from the page snapshot\nOptions:\n --headed\trun browser in headed mode",
+ "evaluate": "playwright-cli evaluate <function> <ref>\n\nEvaluate JavaScript expression on page or element\n\nArguments:\n <function>\t() => { /* code */ } or (element) => { /* code */ } when element is provided\n <ref>\tExact target element reference from the page snapshot",
+ "upload-file": "playwright-cli upload-file \n\nUpload one or multiple files\n\nOptions:\n --paths\tthe absolute paths to the files to upload. can be single file or multiple files. if omitted, file chooser is cancelled.",
+ "handle-dialog": "playwright-cli handle-dialog <accept> <promptText>\n\nHandle a dialog\n\nArguments:\n <accept>\tWhether to accept the dialog.\n <promptText>\tThe text of the prompt in case of a prompt dialog.",
+ "hover": "playwright-cli hover <ref>\n\nHover over element on page\n\nArguments:\n <ref>\tExact target element reference from the page snapshot",
+ "open": "playwright-cli open <url>\n\nOpen URL\n\nArguments:\n <url>\tThe URL to navigate to\nOptions:\n --headed\trun browser in headed mode",
+ "go-back": "playwright-cli go-back \n\nGo back to the previous page\n",
+ "network-requests": "playwright-cli network-requests \n\nReturns all network requests since loading the page\n\nOptions:\n --includeStatic\twhether to include successful static resources like images, fonts, scripts, etc. defaults to false.",
+ "press-key": "playwright-cli press-key <key>\n\nPress a key on the keyboard\n\nArguments:\n <key>\tName of the key to press or a character to generate, such as `ArrowLeft` or `a`",
+ "resize": "playwright-cli resize <width> <height>\n\nResize the browser window\n\nArguments:\n <width>\tWidth of the browser window\n <height>\tHeight of the browser window",
+ "run-code": "playwright-cli run-code <code>\n\nRun Playwright code snippet\n\nArguments:\n <code>\tA JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction.",
+ "select-option": "playwright-cli select-option <ref> <values>\n\nSelect an option in a dropdown\n\nArguments:\n <ref>\tExact target element reference from the page snapshot\n <values>\tArray of values to select in the dropdown. This can be a single value or multiple values.",
+ "snapshot": "playwright-cli snapshot \n\nCapture accessibility snapshot of the current page, this is better than screenshot\n\nOptions:\n --filename\tsave snapshot to markdown file instead of returning it in the response.",
+ "screenshot": "playwright-cli screenshot <ref>\n\nTake a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.\n\nArguments:\n <ref>\tExact target element reference from the page snapshot.\nOptions:\n --filename\tfile name to save the screenshot to. defaults to `page-{timestamp}.{png|jpeg}` if not specified.\n --fullPage\twhen true, takes a screenshot of the full scrollable page, instead of the currently visible viewport.",
+ "type": "playwright-cli type <ref> <text>\n\nType text into editable element\n\nArguments:\n <ref>\tExact target element reference from the page snapshot\n <text>\tText to type into the element\nOptions:\n --submit\twhether to submit entered text (press enter after)\n --slowly\twhether to type one character at a time. useful for triggering key handlers in the page.",
+ "wait-for": "playwright-cli wait-for \n\nWait for text to appear or disappear or a specified time to pass\n\nOptions:\n --time\tthe time to wait in seconds\n --text\tthe text to wait for\n --textGone\tthe text to wait for to disappear",
+ "tab": "playwright-cli tab <action> <index>\n\nClose a browser tab\n\nArguments:\n <action>\tAction to perform on tabs, 'list' | 'new' | 'close' | 'select'\n <index>\tTab index. If omitted, current tab is closed.",
+ "mouse-click-xy": "playwright-cli mouse-click-xy <x> <y>\n\nClick left mouse button at a given position\n\nArguments:\n <x>\tX coordinate\n <y>\tY coordinate",
+ "mouse-drag-xy": "playwright-cli mouse-drag-xy <startX> <startY> <endX> <endY>\n\nDrag left mouse button to a given position\n\nArguments:\n <startX>\tStart X coordinate\n <startY>\tStart Y coordinate\n <endX>\tEnd X coordinate\n <endY>\tEnd Y coordinate",
+ "mouse-move-xy": "playwright-cli mouse-move-xy <x> <y>\n\nMove mouse to a given position\n\nArguments:\n <x>\tX coordinate\n <y>\tY coordinate",
+ "pdf-save": "playwright-cli pdf-save \n\nSave page as PDF\n\nOptions:\n --filename\tfile name to save the pdf to. defaults to `page-{timestamp}.pdf` if not specified.",
+ "start-tracing": "playwright-cli start-tracing \n\nStart trace recording\n",
+ "stop-tracing": "playwright-cli stop-tracing \n\nStop trace recording\n"
+ }
+}
\ No newline at end of file
diff --git a/packages/playwright/src/mcp/terminal/helpGenerator.ts b/packages/playwright/src/mcp/terminal/helpGenerator.ts
new file mode 100644
index 0000000000..ccec783b4e
--- /dev/null
+++ b/packages/playwright/src/mcp/terminal/helpGenerator.ts
@@ -0,0 +1,97 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs';
+import path from 'path';
+import { commands } from './commands';
+
+import type zodType from 'zod';
+import type { AnyCommandSchema } from './command';
+
+function generateCommandHelp(command: AnyCommandSchema) {
+ const args: { name: string, description: string }[] = [];
+
+ const shape = command.args ? (command.args as zodType.ZodObject<any>).shape : {};
+ for (const [name, schema] of Object.entries(shape)) {
+ const zodSchema = schema as zodType.ZodTypeAny;
+ const description = zodSchema.description ?? '';
+ args.push({ name, description });
+ }
+
+ const lines: string[] = [
+ `playwright-cli ${command.name} ${Object.keys(shape).map(k => `<${k}>`).join(' ')}`,
+ '',
+ command.description,
+ '',
+ ];
+
+ if (args.length) {
+ lines.push('Arguments:');
+ lines.push(...args.map(({ name, description }) => ` <${name}>\t${description}`));
+ }
+
+ if (command.options) {
+ lines.push('Options:');
+ const optionsShape = (command.options as zodType.ZodObject<any>).shape;
+ for (const [name, schema] of Object.entries(optionsShape)) {
+ const zodSchema = schema as zodType.ZodTypeAny;
+ const description = (zodSchema.description ?? '').toLowerCase();
+ lines.push(` --${name}\t${description}`);
+ }
+ }
+
+ return lines.join('\n');
+}
+
+function generateHelp() {
+ const lines: string[] = [];
+ lines.push('Usage: playwright-cli <command> [options]');
+ lines.push('Commands:');
+ for (const command of Object.values(commands))
+ lines.push(' ' + generateHelpEntry(command));
+ return lines.join('\n');
+}
+
+function generateHelpEntry(command: AnyCommandSchema): string {
+ const args: { name: string, description: string }[] = [];
+
+ const shape = (command.args as zodType.ZodObject<any>).shape;
+ for (const [name, schema] of Object.entries(shape)) {
+ const zodSchema = schema as zodType.ZodTypeAny;
+ const description = zodSchema.description ?? '';
+ args.push({ name, description });
+ }
+
+ const prefix = `${command.name} ${Object.keys(shape).map(k => `<${k}>`).join(' ')}`;
+ const suffix = command.description.toLowerCase();
+ const padding = ' '.repeat(Math.max(1, 40 - prefix.length));
+ return prefix + padding + suffix;
+}
+
+async function main() {
+ const help = {
+ global: generateHelp(),
+ commands: Object.fromEntries(
+ Object.entries(commands).map(([name, command]) => [name, generateCommandHelp(command)])
+ ),
+ };
+ const fileName = path.resolve(__dirname, 'help.json').replace('lib', 'src');
+ // eslint-disable-next-line no-console
+ console.log('Writing ', path.relative(process.cwd(), fileName));
+ await fs.promises.writeFile(fileName, JSON.stringify(help, null, 2));
+}
+
+void main();
diff --git a/utils/build/build.js b/utils/build/build.js
index 252e7b6a5a..bcc5be5139 100644
--- a/utils/build/build.js
+++ b/utils/build/build.js
@@ -636,6 +636,12 @@ copyFiles.push({
to: 'packages/playwright/lib',
});
+copyFiles.push({
+ files: 'packages/playwright/src/mcp/terminal/*.json',
+ from: 'packages/playwright/src',
+ to: 'packages/playwright/lib',
+});
+
if (watchMode) {
// Run TypeScript for type checking.
steps.push(new ProgramStep({
diff --git a/utils/generate_cli_commands.js b/utils/generate_cli_commands.js
index c73ce10009..46da7c5aa3 100644
--- a/utils/generate_cli_commands.js
+++ b/utils/generate_cli_commands.js
@@ -19,228 +19,68 @@
const fs = require('fs')
const path = require('path')
-const { browserTools } = require('playwright/lib/mcp/browser/tools');
-
-const capabilityNames = {
- 'core': 'Core',
- 'core-tabs': 'Tab management',
- 'core-install': 'Browser installation',
- 'vision': 'Coordinate-based',
- 'pdf': 'PDF generation',
- 'tracing': 'Tracing',
- 'testing': 'Testing',
-};
-
-function camelToKebabCase(camel) {
- return camel.replace(/([A-Z])/g, (letter) => `-${letter.toLowerCase()}`);
-}
-
-/** @type {Record<string, string[]>} */
-const aliases = {
- 'navigate': ['goto', 'open'],
- 'take_screenshot': ['screenshot'],
-};
-
-/** @type {Record<string, Record<string, string>>} */
-const commandToExtraOptions = {
- 'navigate': {
- 'headed': 'run browser in headed mode'
- },
-};
-
-function commandNameForTool(toolName) {
- if (toolName.startsWith('browser_'))
- toolName = toolName.slice('browser_'.length);
- return toolName;
-}
-
-
-/**
- * @param {any} tool
- * @returns {string[]}
- */
-function requiredParamsForTool(tool) {
- const inputSchema = tool.inputSchema.toJSONSchema() ;
- return (inputSchema.required || []).filter(param => {
- const property = inputSchema.properties?.[param];
- return !(typeof property === 'object' && 'default' in property)
- });
-}
+const { commands } = require('../packages/playwright/lib/mcp/terminal/commands.js');
/**
- * @param {any} tool
- * @returns {string}
+ *
+ * @param {import('../packages/playwright/src/mcp/terminal/command').AnyCommandSchema} command
*/
-function formatHelpForCommand(tool) {
- const commandName = commandNameForTool(tool.name);
-
- const inputSchema = tool.inputSchema.toJSONSchema();
- const requiredParams = (inputSchema.required || []).filter(param => {
- const property = inputSchema.properties?.[param];
- return !(typeof property === 'object' && 'default' in property)
- });
-
- const lines = /** @type {string[]} */ ([]);
- lines.push(`playwright-cli ${commandName} ${requiredParams.map(param => `<${param}>`).join(' ')}`);
- lines.push(``);
- lines.push(tool.description);
-
- if (aliases[commandName]) {
- lines.push(``);
- lines.push(`Aliases: ${aliases[commandName].join(', ')}`);
+function generateCommandHelp(command: AnyCommandSchema) {
+ const args: { name: string, description: string }[] = [];
+
+ const shape = command.args ? (command.args as zodType.ZodObject<any>).shape : {};
+ for (const [name, schema] of Object.entries(shape)) {
+ const zodSchema = schema as zodType.ZodTypeAny;
+ const description = zodSchema.description ?? '';
+ args.push({ name, description})
}
- if (requiredParams.length) {
- lines.push(``);
- lines.push(`Parameters:`);
- for (const param of requiredParams) {
- const property = inputSchema.properties?.[param];
- lines.push(formatNameAndDescription(` <${param}>`, property.description, 20));
- }
- }
- if (inputSchema.properties && Object.keys(inputSchema.properties).length) {
- let printedHeader = false;
- function ensureHeader() {
- if (!printedHeader) {
- lines.push(``);
- lines.push(`Options:`);
- printedHeader = true;
- }
- }
- const extraOptions = commandToExtraOptions[commandName] || {};
- for (const [option, description] of Object.entries(extraOptions)) {
- ensureHeader();
- lines.push(formatNameAndDescription(` --${option}`, description));
- }
- Object.entries(inputSchema.properties).forEach(([name, param]) => {
- if (requiredParams.includes(name))
- return;
- ensureHeader();
- lines.push(formatNameAndDescription(` --${camelToKebabCase(name)}`, param.description, 20));
- });
- }
- lines.push('');
- return lines.join('\n');
-}
-
-function startWithLowerCase(string) {
- return string.charAt(0).toLowerCase() + string.slice(1);
-}
-
-/**
- * @param {string} name
- * @param {string} description
- * @returns {string}
- */
-function formatNameAndDescription(name, description, padding = 30) {
- if (name.length > padding)
- return `${name}\n${' '.repeat(padding)}${description}`;
- const paddedName = name.padEnd(padding);
- return `${paddedName}${description}`;
-}
-
-/**
- * @returns {string}
- */
-function formatGlobalHelp() {
- const lines = /** @type {string[]} */ ([]);
- lines.push(`playwright-cli - run playwright mcp commands from terminal`);
- lines.push('');
- lines.push(`Usage: playwright-cli <command> [options]`);
- lines.push('');
-
- // Group tools by capability
- /** @type {Record<string, Array<{name: string, title: string, requiredParams: string[]}>>} */
- const capabilityToTools = {};
+ const lines: string[] = [
+ `playwright-cli ${command.name} ${Object.keys(shape).map(k => `<${k}>`).join(' ')}`,
+ '',
+ command.description,
+ '',
+ ];
- for (const tool of browserTools) {
- const capability = tool.capability;
- if (!capabilityToTools[capability])
- capabilityToTools[capability] = [];
- capabilityToTools[capability].push({
- name: commandNameForTool(tool.schema.name),
- title: tool.schema.title,
- requiredParams: requiredParamsForTool(tool.schema),
- });
+ if (args.length) {
+ lines.push('Arguments:');
+ for (const arg of args)
+ lines.push(...args.map(({ name, description }) => ` <${name}>\t${description}`));
}
- const capabilityOrder = Object.keys(capabilityNames);
- for (const capability of Object.keys(capabilityToTools)) {
- if (!capabilityOrder.includes(capability))
- throw new Error(`Unknown capability: ${capability}`);
- }
- for (const capability of capabilityOrder) {
- if (!capabilityToTools[capability])
- throw new Error(`Unknown capability: ${capability}`);
- lines.push(`${capabilityNames[capability]}:`);
- for (const tool of capabilityToTools[capability]) {
- const params = tool.requiredParams.map(param => `<${param}>`).join(' ');
- const nameAndParams = ` ${tool.name}${params ? ` ${params}` : ''}`;
- lines.push(formatNameAndDescription(nameAndParams, startWithLowerCase(tool.title)));
+ if (command.options) {
+ lines.push('Options:');
+ const optionsShape = (command.options as zodType.ZodObject<any>).shape;
+ for (const [name, schema] of Object.entries(optionsShape)) {
+ const zodSchema = schema as zodType.ZodTypeAny;
+ const description = (zodSchema.description ?? '').toLowerCase();
+ lines.push(` --${name}\t${description}`);
}
- lines.push('');
}
- lines.push(`Options:`);
- lines.push(formatNameAndDescription(` --help`, `show help for a specific command`));
- lines.push(formatNameAndDescription(` --version`, `show version information`));
- lines.push('');
- lines.push(`Examples:`);
- lines.push(` playwright-cli navigate https://playwright.dev`);
- lines.push(` playwright-cli snapshot`);
- lines.push(` playwright-cli click e67`);
- lines.push('');
- return lines.join('\n');
+ console.log(lines.join('\n'));
}
-/**
- * @param {string} content
- * @param {string} startMarker
- * @param {string} endMarker
- * @param {string} generatedContent
- * @returns {Promise<string>}
- */
-async function updateSection(content, startMarker, endMarker, generatedContent) {
- const startMarkerIndex = content.indexOf(startMarker);
- const endMarkerIndex = content.indexOf(endMarker);
- if (startMarkerIndex === -1 || endMarkerIndex === -1)
- throw new Error('Markers for generated section not found');
-
- return [
- content.slice(0, startMarkerIndex + startMarker.length),
- '',
- generatedContent,
- '',
- content.slice(endMarkerIndex),
- ].join('\n');
+export function printHelp(commands: AnyCommandSchema[]) {
+ console.log('Usage: playwright-cli <command> [options]');
+ console.log('Commands:');
+ for (const command of commands)
+ console.log(' ' + commandHelpEntry(command));
}
-async function updateToolCommands() {
- const toolCommandsPath = path.join(__dirname, '../packages/playwright/src/mcp/terminal/commands.ts');
- const commands = browserTools.map(tool => {
- return `helpMessage['${commandNameForTool(tool.schema.name)}'] =\n\`${formatHelpForCommand(tool.schema).replace(/`/g, '\\`')}\`;`;
- });
+function commandHelpEntry(command: AnyCommandSchema): string {
+ const args: { name: string, description: string }[] = [];
- const aliasesContent = `export const aliases: Record<string, string[]> = {${Object.entries(aliases).map(([key, value]) => `\n '${key}': ['${value.join('\', \'')}'],`).join('')}
-};`;
+ const shape = (command.args as zodType.ZodObject<any>).shape;
+ for (const [name, schema] of Object.entries(shape)) {
+ const zodSchema = schema as zodType.ZodTypeAny;
+ const description = zodSchema.description ?? '';
+ args.push({ name, description})
+ }
- const lines = [
- `export const helpMessage: Record<string, string> = {};`,
- ...commands,
- `export const globalHelp: string =\n\`${formatGlobalHelp().replace(/`/g, '\\`')}\`;`,
- aliasesContent,
+ const lines: string[] = [
+ `${command.name} ${Object.keys(shape).map(k => `<${k}>`).join(' ')}`,
+ command.description.toLowerCase(),
];
-
- const startMarker = `// Commands generated by ${path.basename(__filename)}`;
- const endMarker = `// End of commands generated section\n`;
-
- const content = await fs.promises.readFile(toolCommandsPath, 'utf-8');
- const newContent = await updateSection(content, startMarker, endMarker, lines.join('\n\n'));
- await fs.promises.writeFile(toolCommandsPath, newContent, 'utf-8');
- console.log('Tool commands updated successfully');
+ return lines.join('\t');
}
-
-updateToolCommands().catch(err => {
- console.error('Error updating tool commands:', err);
- process.exit(1);
-});