Skip to content

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

chore(mcp): generate cli command help (#38872)

Yury Semikhatsky5f8364e35428
diff --git a/package-lock.json b/package-lock.json
index d38efafaaf..f236396171 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -25,6 +25,7 @@
"@types/codemirror": "^5.60.7",
"@types/formidable": "^2.0.4",
"@types/mdast": "^4.0.4",
+ "@types/minimist": "^1.2.5",
"@types/node": "18.19.76",
"@types/react": "^19.2.1",
"@types/react-dom": "^19.2.1",
@@ -1874,6 +1875,13 @@
"@types/unist": "*"
}
},
+ "node_modules/@types/minimist": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.5.tgz",
+ "integrity": "sha512-hov8bUuiLiyFPGyFPE1lwWhmzYbirOXQNNo40+y3zow8aFVTeyn3VWL0VFFfdNddA8S4Vf0Tc062rzyNr7Paag==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "18.19.76",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.76.tgz",
diff --git a/package.json b/package.json
index 0cc666aecc..3771b7e399 100644
--- a/package.json
+++ b/package.json
@@ -62,6 +62,7 @@
"@types/codemirror": "^5.60.7",
"@types/formidable": "^2.0.4",
"@types/mdast": "^4.0.4",
+ "@types/minimist": "^1.2.5",
"@types/node": "18.19.76",
"@types/react": "^19.2.1",
"@types/react-dom": "^19.2.1",
diff --git a/packages/playwright/src/mcp/terminal/DEPS.list b/packages/playwright/src/mcp/terminal/DEPS.list
new file mode 100644
index 0000000000..bdc43d74d9
--- /dev/null
+++ b/packages/playwright/src/mcp/terminal/DEPS.list
@@ -0,0 +1,2 @@
+[daemon.ts]
+../browser/tools
diff --git a/packages/playwright/src/mcp/terminal/cli.ts b/packages/playwright/src/mcp/terminal/cli.ts
index 21989507ec..5a8627da3d 100644
--- a/packages/playwright/src/mcp/terminal/cli.ts
+++ b/packages/playwright/src/mcp/terminal/cli.ts
@@ -22,8 +22,9 @@ import fs from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
-import { program, debug } from 'playwright-core/lib/utilsBundle';
+import { debug } from 'playwright-core/lib/utilsBundle';
import { SocketConnection } from './socketConnection';
+import { aliases, globalHelp, helpMessage } from './commands';
import type * as mcp from '../sdk/exports';
@@ -31,138 +32,13 @@ const debugCli = debug('pw:cli');
const packageJSON = require('../../../package.json');
-program
- .version('Version ' + (process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version))
- .name('playwright-command');
-
-function addCommand(name: string, description: string, action: (...args: any[]) => Promise<void>) {
- program
- .command(name)
- .description(description)
- .action(action);
-}
-
-program
- .command('navigate <url>')
- .aliases(['open', 'goto'])
- .description('open url in the browser')
- .option('--headed', 'run browser in headed mode')
- .action(async (url, options) => {
- await runMcpCommand('browser_navigate', { url }, { headless: !options.headed });
- });
-
-addCommand('close', 'close the browser', async () => {
- await runMcpCommand('browser_close', {});
-});
-
-// snapshot.ts
-addCommand('click <ref>', 'click an element using a ref from a snapshot, e.g. e67', async ref => {
- await runMcpCommand('browser_click', { ref });
-});
-
-addCommand('snapshot', 'get accessible snapshot of the current page', async () => {
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
- await runMcpCommand('browser_snapshot', { filename: `snapshot-${timestamp}.md` });
-});
-
-addCommand('drag <startRef> <endRef>', 'drag from one element to another', async (startRef, endRef) => {
- await runMcpCommand('browser_drag', { startRef, endRef });
-});
-
-addCommand('hover <ref>', 'hover over an element', async ref => {
- await runMcpCommand('browser_hover', { ref });
-});
-
-addCommand('select <ref> <values...>', 'select option(s) in a dropdown', async (ref, values) => {
- await runMcpCommand('browser_select_option', { ref, values });
-});
-
-// TODO: remove?
-addCommand('locator <ref>', 'generate a locator for an element', async ref => {
- await runMcpCommand('browser_generate_locator', { ref });
-});
-
-// keyboard.ts
-addCommand('press <key>', 'press a key on the keyboard', async key => {
- await runMcpCommand('browser_press_key', { key });
-});
-
-addCommand('type <ref> <text>', 'type text into an element', async (ref, text) => {
- await runMcpCommand('browser_type', { ref, text });
-});
-
-// navigate.ts
-addCommand('back', 'go back to the previous page', async () => {
- await runMcpCommand('browser_navigate_back', {});
-});
-
-// wait.ts
-addCommand('wait <time>', 'wait for a specified time in seconds', async time => {
- await runMcpCommand('browser_wait_for', { time: parseFloat(time) });
-});
-
-addCommand('wait-for-text <text>', 'wait for text to appear', async text => {
- await runMcpCommand('browser_wait_for', { text });
-});
-
-// dialogs.ts
-addCommand('dialog-accept [promptText]', 'accept a dialog', async promptText => {
- await runMcpCommand('browser_handle_dialog', { accept: true, promptText });
-});
-
-addCommand('dialog-dismiss', 'dismiss a dialog', async () => {
- await runMcpCommand('browser_handle_dialog', { accept: false });
-});
-
-// screenshot.ts
-addCommand('screenshot [filename]', 'take a screenshot of the current page', async filename => {
- await runMcpCommand('browser_take_screenshot', { filename });
-});
-
-// common.ts (resize)
-addCommand('resize <width> <height>', 'resize the browser window', async (width, height) => {
- await runMcpCommand('browser_resize', { width: parseInt(width, 10), height: parseInt(height, 10) });
-});
-
-// files.ts
-addCommand('upload <paths...>', 'upload files', async paths => {
- await runMcpCommand('browser_file_upload', { paths });
-});
-
-// tabs.ts
-addCommand('tabs', 'list all browser tabs', async () => {
- await runMcpCommand('browser_tabs', { action: 'list' });
-});
-
-addCommand('tab-new', 'create a new browser tab', async () => {
- await runMcpCommand('browser_tabs', { action: 'new' });
-});
-
-addCommand('tab-close [index]', 'close a browser tab', async index => {
- await runMcpCommand('browser_tabs', { action: 'close', index: index !== undefined ? parseInt(index, 10) : undefined });
-});
-
-addCommand('tab-select <index>', 'select a browser tab', async index => {
- await runMcpCommand('browser_tabs', { action: 'select', index: parseInt(index, 10) });
-});
-
-
-async function runMcpCommand(name: string, args: mcp.CallToolRequest['params']['arguments'], options: { headless?: boolean } = {}) {
+async function runMcpCommand(argv: string[], options: { headless?: boolean } = {}) {
const session = await connectToDaemon(options);
- const result = await session.callTool(name, args);
- printResult(result);
+ const result = await session.runCliCommand(argv);
+ console.log(result);
session.dispose();
}
-function printResult(result: mcp.CallToolResult) {
- for (const content of result.content) {
- if (content.type === 'text')
- console.log(content.text);
- else
- console.log(`<${content.type} content>`);
- }
-}
-
async function socketExists(socketPath: string): Promise<boolean> {
try {
const stat = await fs.promises.stat(socketPath);
@@ -189,6 +65,10 @@ class SocketSession {
return this._send(name, args);
}
+ async runCliCommand(argv: string[]): Promise<string> {
+ return await this._send('runCliCommand', { argv });
+ }
+
private async _send(method: string, params: any = {}): Promise<any> {
const messageId = this._nextMessageId++;
const message = {
@@ -302,4 +182,34 @@ async function connectToSocket(socketPath: string): Promise<SocketSession> {
return new SocketSession(new SocketConnection(socket));
}
-void program.parseAsync(process.argv);
+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
+ process.exit(0);
+ }
+
+ 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
+ process.exit(1);
+ });
+}
+
+main();
diff --git a/packages/playwright/src/mcp/terminal/commands.ts b/packages/playwright/src/mcp/terminal/commands.ts
new file mode 100644
index 0000000000..fb135f11bf
--- /dev/null
+++ b/packages/playwright/src/mcp/terminal/commands.ts
@@ -0,0 +1,442 @@
+/**
+ * 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.
+ */
+
+/* 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
diff --git a/packages/playwright/src/mcp/terminal/daemon.ts b/packages/playwright/src/mcp/terminal/daemon.ts
index 022937c384..c16cde81a8 100644
--- a/packages/playwright/src/mcp/terminal/daemon.ts
+++ b/packages/playwright/src/mcp/terminal/daemon.ts
@@ -22,8 +22,11 @@ import url from 'url';
import { debug } from 'playwright-core/lib/utilsBundle';
import { SocketConnection } from './socketConnection';
+import { browserTools } from '../browser/tools';
import type { ServerBackendFactory } from '../sdk/server';
+import type * as mcp from '../sdk/exports';
+import type { z } from 'zod';
const daemonDebug = debug('pw:daemon');
@@ -79,14 +82,17 @@ export async function startMcpDaemonServer(
const { id, method, params } = message;
try {
daemonDebug('received command', method);
- const response = await backend.callTool(method, params, () => {});
- daemonDebug('sending response', !!response);
- if (response)
- await connection.send({ id, result: response });
+ if (method === 'runCliCommand') {
+ const { toolName, args } = parseCliCommand(params.argv);
+ const adjustedArgs = adjustCommandParameters(toolName, args);
+ const response = await backend.callTool(toolName, adjustedArgs, () => {});
+ await connection.send({ id, result: formatResult(response) });
+ } else {
+ throw new Error(`Unknown method: ${method}`);
+ }
} catch (e) {
daemonDebug('command failed', e);
await connection.send({ id, error: (e as Error).message });
- daemonDebug('error handling message', e);
}
};
});
@@ -103,3 +109,89 @@ export async function startMcpDaemonServer(
});
});
}
+
+function formatResult(result: mcp.CallToolResult) {
+ const lines = [];
+ for (const content of result.content) {
+ if (content.type === 'text')
+ lines.push(content.text);
+ else
+ lines.push(`<${content.type} content>`);
+ }
+ return lines.join('\n');
+}
+
+function camelToKebabCase(camel: string): string {
+ return camel.replace(/([A-Z])/g, letter => `-${letter.toLowerCase()}`);
+}
+
+export const aliases: Record<string, string[]> = {
+ 'navigate': ['goto', 'open'],
+ 'take_screenshot': ['screenshot'],
+};
+
+function canonicalName(name: string): string {
+ switch (name) {
+ case 'goto':
+ case 'navigate':
+ case 'open':
+ return 'navigate';
+ case 'screenshot':
+ case 'take_screenshot':
+ return 'take_screenshot';
+ default:
+ return name;
+ }
+}
+
+function parseCliCommand(argv: string[]): { toolName: string, args: mcp.CallToolRequest['params']['arguments'] } {
+ const parsed = require('minimist')(argv);
+
+ const commandAlias = parsed._[0];
+ if (!commandAlias)
+ throw new Error('Command is required');
+
+ const toolName = `browser_${canonicalName(commandAlias)}`;
+ // TODO: support aliases
+ 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;
+}
diff --git a/utils/generate_cli_commands.js b/utils/generate_cli_commands.js
new file mode 100644
index 0000000000..c73ce10009
--- /dev/null
+++ b/utils/generate_cli_commands.js
@@ -0,0 +1,246 @@
+#!/usr/bin/env node
+/**
+ * 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.
+ */
+// @ts-check
+
+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)
+ });
+}
+
+/**
+ * @param {any} tool
+ * @returns {string}
+ */
+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(', ')}`);
+ }
+
+ 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 = {};
+
+ 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),
+ });
+ }
+
+ 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)));
+ }
+ 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');
+}
+
+/**
+ * @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');
+}
+
+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, '\\`')}\`;`;
+ });
+
+ const aliasesContent = `export const aliases: Record<string, string[]> = {${Object.entries(aliases).map(([key, value]) => `\n '${key}': ['${value.join('\', \'')}'],`).join('')}
+};`;
+
+ const lines = [
+ `export const helpMessage: Record<string, string> = {};`,
+ ...commands,
+ `export const globalHelp: string =\n\`${formatGlobalHelp().replace(/`/g, '\\`')}\`;`,
+ aliasesContent,
+ ];
+
+ 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');
+}
+
+updateToolCommands().catch(err => {
+ console.error('Error updating tool commands:', err);
+ process.exit(1);
+});