Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: add more nav and input commands (#38910)
Pavel Feldman26a33fd6683d
diff --git a/packages/playwright/src/mcp/browser/browserServerBackend.ts b/packages/playwright/src/mcp/browser/browserServerBackend.tsindex 67dc800fe6..a9e576e043 100644--- a/packages/playwright/src/mcp/browser/browserServerBackend.ts+++ b/packages/playwright/src/mcp/browser/browserServerBackend.ts@@ -19,7 +19,7 @@ import { Context } from './context';import { logUnhandledError } from '../log';import { Response } from './response';import { SessionLog } from './sessionLog';-import { filteredTools } from './tools';+import { browserTools, filteredTools } from './tools';import { toMcpTool } from '../sdk/tool';import type { Tool } from './tools/tool';@@ -34,10 +34,10 @@ export class BrowserServerBackend implements ServerBackend {private _config: FullConfig;private _browserContextFactory: BrowserContextFactory;- constructor(config: FullConfig, factory: BrowserContextFactory) {+ constructor(config: FullConfig, factory: BrowserContextFactory, options: { allTools?: boolean } = {}) {this._config = config;this._browserContextFactory = factory;- this._tools = filteredTools(config);+ this._tools = options.allTools ? browserTools : filteredTools(config);}async initialize(clientInfo: mcpServer.ClientInfo): Promise<void> {diff --git a/packages/playwright/src/mcp/browser/tab.ts b/packages/playwright/src/mcp/browser/tab.tsindex a346e6f628..665240fffc 100644--- a/packages/playwright/src/mcp/browser/tab.ts+++ b/packages/playwright/src/mcp/browser/tab.ts@@ -273,11 +273,21 @@ export class Tab extends EventEmitter<TabEventsInterface> {return this._consoleMessages.filter(message => shouldIncludeMessage(level, message.type));}+ async clearConsoleMessages() {+ await this._initializedPromise;+ this._consoleMessages.length = 0;+ }+async requests(): Promise<Set<playwright.Request>> {await this._initializedPromise;return this._requests;}+ async clearRequests() {+ await this._initializedPromise;+ this._requests.clear();+ }+async captureSnapshot(): Promise<TabSnapshot> {await this._initializedPromise;let tabSnapshot: TabSnapshot | undefined;diff --git a/packages/playwright/src/mcp/browser/tools.ts b/packages/playwright/src/mcp/browser/tools.tsindex efc6a88649..1b00ffc826 100644--- a/packages/playwright/src/mcp/browser/tools.ts+++ b/packages/playwright/src/mcp/browser/tools.ts@@ -25,7 +25,6 @@ import keyboard from './tools/keyboard';import mouse from './tools/mouse';import navigate from './tools/navigate';import network from './tools/network';-import open from './tools/open';import pdf from './tools/pdf';import runCode from './tools/runCode';import snapshot from './tools/snapshot';@@ -50,7 +49,6 @@ export const browserTools: Tool<any>[] = [...mouse,...navigate,...network,- ...open,...pdf,...runCode,...screenshot,@@ -62,5 +60,5 @@ export const browserTools: Tool<any>[] = [];export function filteredTools(config: FullConfig) {- return browserTools.filter(tool => tool.capability.startsWith('core') || config.capabilities?.includes(tool.capability));+ return browserTools.filter(tool => tool.capability.startsWith('core') || config.capabilities?.includes(tool.capability)).filter(tool => !tool.skillOnly);}diff --git a/packages/playwright/src/mcp/browser/tools/console.ts b/packages/playwright/src/mcp/browser/tools/console.tsindex cc9fe13e6e..857fd072f5 100644--- a/packages/playwright/src/mcp/browser/tools/console.ts+++ b/packages/playwright/src/mcp/browser/tools/console.ts@@ -36,6 +36,22 @@ const console = defineTabTool({},});+const consoleClear = defineTabTool({+ capability: 'core',+ skillOnly: true,+ schema: {+ name: 'browser_console_clear',+ title: 'Clear console messages',+ description: 'Clear all console messages',+ inputSchema: z.object({}),+ type: 'readOnly',+ },+ handle: async tab => {+ await tab.clearConsoleMessages();+ },+});+export default [console,+ consoleClear,];diff --git a/packages/playwright/src/mcp/browser/tools/keyboard.ts b/packages/playwright/src/mcp/browser/tools/keyboard.tsindex cb2ba08dc0..d6b9bc712c 100644--- a/packages/playwright/src/mcp/browser/tools/keyboard.ts+++ b/packages/playwright/src/mcp/browser/tools/keyboard.ts@@ -18,8 +18,8 @@ import { z } from 'playwright-core/lib/mcpBundle';import { defineTabTool } from './tool';import { elementSchema } from './snapshot';-const pressKey = defineTabTool({- capability: 'core',+const press = defineTabTool({+ capability: 'core-input',schema: {name: 'browser_press_key',@@ -39,14 +39,15 @@ const pressKey = defineTabTool({});const pressSequentially = defineTabTool({- capability: 'internal',+ capability: 'core-input',+ skillOnly: true,schema: {name: 'browser_press_sequentially',- title: 'Press sequentially',- description: 'Press text sequentially on the keyboard',+ title: 'Type text key by key',+ description: 'Type text key by key on the keyboard',inputSchema: z.object({- text: z.string().describe('Text to press sequentially'),+ text: z.string().describe('Text to type'),submit: z.boolean().optional().describe('Whether to submit entered text (press Enter after)'),}),type: 'input',@@ -73,7 +74,7 @@ const typeSchema = elementSchema.extend({});const type = defineTabTool({- capability: 'core',+ capability: 'core-input',schema: {name: 'browser_type',title: 'Type text',@@ -105,8 +106,50 @@ const type = defineTabTool({},});+const keydown = defineTabTool({+ capability: 'core-input',+ skillOnly: true,++ schema: {+ name: 'browser_keydown',+ title: 'Press a key down',+ description: 'Press a key down on the keyboard',+ inputSchema: z.object({+ key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),+ }),+ type: 'input',+ },++ handle: async (tab, params, response) => {+ response.addCode(`await page.keyboard.down('${params.key}');`);+ await tab.page.keyboard.down(params.key);+ },+});++const keyup = defineTabTool({+ capability: 'core-input',+ skillOnly: true,++ schema: {+ name: 'browser_keyup',+ title: 'Press a key up',+ description: 'Press a key up on the keyboard',+ inputSchema: z.object({+ key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),+ }),+ type: 'input',+ },++ handle: async (tab, params, response) => {+ response.addCode(`await page.keyboard.up('${params.key}');`);+ await tab.page.keyboard.up(params.key);+ },+});+export default [- pressKey,+ press,type,pressSequentially,+ keydown,+ keyup,];diff --git a/packages/playwright/src/mcp/browser/tools/mouse.ts b/packages/playwright/src/mcp/browser/tools/mouse.tsindex b781fcaee3..9ed4441c20 100644--- a/packages/playwright/src/mcp/browser/tools/mouse.ts+++ b/packages/playwright/src/mcp/browser/tools/mouse.ts@@ -17,17 +17,13 @@import { z } from 'playwright-core/lib/mcpBundle';import { defineTabTool } from './tool';-const elementSchema = z.object({- element: z.string().describe('Human-readable element description used to obtain permission to interact with the element'),-});-const mouseMove = defineTabTool({capability: 'vision',schema: {name: 'browser_mouse_move_xy',title: 'Move mouse',description: 'Move mouse to a given position',- inputSchema: elementSchema.extend({+ inputSchema: z.object({x: z.number().describe('X coordinate'),y: z.number().describe('Y coordinate'),}),@@ -44,13 +40,73 @@ const mouseMove = defineTabTool({},});+const mouseDown = defineTabTool({+ capability: 'vision',++ schema: {+ name: 'browser_mouse_down',+ title: 'Press mouse down',+ description: 'Press mouse down',+ inputSchema: z.object({+ button: z.enum(['left', 'right', 'middle']).optional().describe('Button to press, defaults to left'),+ }),+ type: 'input',+ },++ handle: async (tab, params, response) => {+ response.addCode(`// Press mouse down`);+ response.addCode(`await page.mouse.down({ button: '${params.button}' });`);+ await tab.page.mouse.down({ button: params.button });+ },+});++const mouseUp = defineTabTool({+ capability: 'vision',++ schema: {+ name: 'browser_mouse_up',+ title: 'Press mouse up',+ description: 'Press mouse up',+ inputSchema: z.object({+ button: z.enum(['left', 'right', 'middle']).optional().describe('Button to press, defaults to left'),+ }),+ type: 'input',+ },++ handle: async (tab, params, response) => {+ response.addCode(`// Press mouse up`);+ response.addCode(`await page.mouse.up({ button: '${params.button}' });`);+ await tab.page.mouse.up({ button: params.button });+ },+});++const mouseWheel = defineTabTool({+ capability: 'vision',+ schema: {+ name: 'browser_mouse_wheel',+ title: 'Scroll mouse wheel',+ description: 'Scroll mouse wheel',+ inputSchema: z.object({+ deltaX: z.number().default(0).describe('X delta'),+ deltaY: z.number().default(0).describe('Y delta'),+ }),+ type: 'input',+ },++ handle: async (tab, params, response) => {+ response.addCode(`// Scroll mouse wheel`);+ response.addCode(`await page.mouse.wheel(${params.deltaX}, ${params.deltaY});`);+ await tab.page.mouse.wheel(params.deltaX, params.deltaY);+ },+});+const mouseClick = defineTabTool({capability: 'vision',schema: {name: 'browser_mouse_click_xy',title: 'Click',description: 'Click left mouse button at a given position',- inputSchema: elementSchema.extend({+ inputSchema: z.object({x: z.number().describe('X coordinate'),y: z.number().describe('Y coordinate'),}),@@ -79,7 +135,7 @@ const mouseDrag = defineTabTool({name: 'browser_mouse_drag_xy',title: 'Drag mouse',description: 'Drag left mouse button to a given position',- inputSchema: elementSchema.extend({+ inputSchema: z.object({startX: z.number().describe('Start X coordinate'),startY: z.number().describe('Start Y coordinate'),endX: z.number().describe('End X coordinate'),@@ -110,4 +166,7 @@ export default [mouseMove,mouseClick,mouseDrag,+ mouseDown,+ mouseUp,+ mouseWheel,];diff --git a/packages/playwright/src/mcp/browser/tools/navigate.ts b/packages/playwright/src/mcp/browser/tools/navigate.tsindex e68c65e6cf..233e8aeb8b 100644--- a/packages/playwright/src/mcp/browser/tools/navigate.ts+++ b/packages/playwright/src/mcp/browser/tools/navigate.ts@@ -18,7 +18,7 @@ import { z } from 'playwright-core/lib/mcpBundle';import { defineTool, defineTabTool } from './tool';const navigate = defineTool({- capability: 'core',+ capability: 'core-navigation',schema: {name: 'browser_navigate',@@ -49,12 +49,46 @@ const navigate = defineTool({},});+const open = defineTool({+ capability: 'core-navigation',+ skillOnly: true,+ schema: {+ name: 'browser_open',+ title: 'Open URL',+ description: 'Open a URL in the browser',+ inputSchema: z.object({+ url: z.string().describe('The URL to open'),+ headed: z.boolean().optional().describe('Run browser in headed mode'),+ }),+ type: 'action',+ },++ handle: async (context, params, response) => {+ const forceHeadless = params.headed ? 'headed' : 'headless';+ const tab = await context.ensureTab({ forceHeadless });+ let url = params.url;+ try {+ new URL(url);+ } catch (e) {+ if (url.startsWith('localhost'))+ url = 'http://' + url;+ else+ url = 'https://' + url;+ }++ await tab.navigate(url);++ response.setIncludeSnapshot();+ response.addCode(`await page.goto('${params.url}');`);+ },+});+const goBack = defineTabTool({- capability: 'core',+ capability: 'core-navigation',schema: {name: 'browser_navigate_back',title: 'Go back',- description: 'Go back to the previous page',+ description: 'Go back to the previous page in the history',inputSchema: z.object({}),type: 'action',},@@ -66,7 +100,46 @@ const goBack = defineTabTool({},});+const goForward = defineTabTool({+ capability: 'core-navigation',+ skillOnly: true,+ schema: {+ name: 'browser_navigate_forward',+ title: 'Go forward',+ description: 'Go forward to the next page in the history',+ inputSchema: z.object({}),+ type: 'action',+ },++ handle: async (tab, params, response) => {+ await tab.page.goForward();+ response.setIncludeSnapshot();+ response.addCode(`await page.goForward();`);+ },+});++const reload = defineTabTool({+ capability: 'core-navigation',+ skillOnly: true,+ schema: {+ name: 'browser_reload',+ title: 'Reload the page',+ description: 'Reload the current page',+ inputSchema: z.object({}),+ type: 'action',+ },++ handle: async (tab, params, response) => {+ await tab.page.reload();+ response.setIncludeSnapshot();+ response.addCode(`await page.reload();`);+ },+});+export default [navigate,+ open,goBack,+ goForward,+ reload,];diff --git a/packages/playwright/src/mcp/browser/tools/network.ts b/packages/playwright/src/mcp/browser/tools/network.tsindex cf6fb952fa..d8428d119c 100644--- a/packages/playwright/src/mcp/browser/tools/network.ts+++ b/packages/playwright/src/mcp/browser/tools/network.ts@@ -46,6 +46,21 @@ const requests = defineTabTool({},});+const networkClear = defineTabTool({+ capability: 'core',+ skillOnly: true,+ schema: {+ name: 'browser_network_clear',+ title: 'Clear network requests',+ description: 'Clear all network requests',+ inputSchema: z.object({}),+ type: 'readOnly',+ },+ handle: async (tab, params, response) => {+ await tab.clearRequests();+ },+});+async function renderRequest(request: playwright.Request, includeStatic: boolean): Promise<string | undefined> {const response = (request as Request)._hasResponse ? await request.response() : undefined;const isStaticRequest = ['document', 'stylesheet', 'image', 'media', 'font', 'script', 'manifest'].includes(request.resourceType());@@ -63,4 +78,5 @@ async function renderRequest(request: playwright.Request, includeStatic: booleanexport default [requests,+ networkClear,];diff --git a/packages/playwright/src/mcp/browser/tools/open.ts b/packages/playwright/src/mcp/browser/tools/open.tsdeleted file mode 100644index 245473b865..0000000000--- a/packages/playwright/src/mcp/browser/tools/open.ts+++ /dev/null@@ -1,56 +0,0 @@-/**- * 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 { z } from 'playwright-core/lib/mcpBundle';-import { defineTool } from './tool';--const open = defineTool({- capability: 'internal',-- schema: {- name: 'browser_open',- title: 'Open URL',- description: 'Open a URL in the browser',- inputSchema: z.object({- url: z.string().describe('The URL to open'),- headed: z.boolean().optional().describe('Run browser in headed mode'),- }),- type: 'action',- },-- handle: async (context, params, response) => {- const forceHeadless = params.headed ? 'headed' : 'headless';- const tab = await context.ensureTab({ forceHeadless });- let url = params.url;- try {- new URL(url);- } catch (e) {- if (url.startsWith('localhost'))- url = 'http://' + url;- else- url = 'https://' + url;- }-- await tab.navigate(url);-- response.setIncludeSnapshot();- response.addCode(`await page.goto('${params.url}');`);- },-});--export default [- open,-];diff --git a/packages/playwright/src/mcp/browser/tools/snapshot.ts b/packages/playwright/src/mcp/browser/tools/snapshot.tsindex 9aa57388bb..e8620e0a55 100644--- a/packages/playwright/src/mcp/browser/tools/snapshot.ts+++ b/packages/playwright/src/mcp/browser/tools/snapshot.ts@@ -178,6 +178,41 @@ const pickLocator = defineTabTool({},});+const check = defineTabTool({+ capability: 'core-input',+ skillOnly: true,++ schema: {+ name: 'browser_check',+ title: 'Check',+ description: 'Check a checkbox or radio button',+ inputSchema: elementSchema,+ type: 'input',+ },++ handle: async (tab, params, response) => {+ const { resolved } = await tab.refLocator(params);+ response.addCode(`await page.${resolved}.check();`);+ },+});++const uncheck = defineTabTool({+ capability: 'core-input',+ skillOnly: true,+ schema: {+ name: 'browser_uncheck',+ title: 'Uncheck',+ description: 'Uncheck a checkbox or radio button',+ inputSchema: elementSchema,+ type: 'input',+ },++ handle: async (tab, params, response) => {+ const { resolved } = await tab.refLocator(params);+ response.addCode(`await page.${resolved}.uncheck();`);+ },+});+export default [snapshot,click,@@ -185,4 +220,6 @@ export default [hover,selectOption,pickLocator,+ check,+ uncheck,];diff --git a/packages/playwright/src/mcp/browser/tools/tool.ts b/packages/playwright/src/mcp/browser/tools/tool.tsindex 306b711f2b..d4c4e80f66 100644--- a/packages/playwright/src/mcp/browser/tools/tool.ts+++ b/packages/playwright/src/mcp/browser/tools/tool.ts@@ -40,6 +40,7 @@ export type ModalState = FileUploadModalState | DialogModalState;export type Tool<Input extends z.Schema = z.Schema> = {capability: ToolCapability;+ skillOnly?: boolean;schema: ToolSchema<Input>;handle: (context: Context, params: z.output<Input>, response: Response) => Promise<void>;};@@ -50,6 +51,7 @@ export function defineTool<Input extends z.Schema>(tool: Tool<Input>): Tool<Inpuexport type TabTool<Input extends z.Schema = z.Schema> = {capability: ToolCapability;+ skillOnly?: boolean;schema: ToolSchema<Input>;clearsModalState?: ModalState['type'];handle: (tab: Tab, params: z.output<Input>, response: Response) => Promise<void>;diff --git a/packages/playwright/src/mcp/config.d.ts b/packages/playwright/src/mcp/config.d.tsindex 5f82604f13..c47cae41e2 100644--- a/packages/playwright/src/mcp/config.d.ts+++ b/packages/playwright/src/mcp/config.d.ts@@ -16,7 +16,17 @@import type * as playwright from 'playwright-core';-export type ToolCapability = 'core' | 'core-tabs' | 'core-install' | 'vision' | 'pdf' | 'testing' | 'tracing' | 'internal';+export type ToolCapability =+ 'core' |+ 'core-input' |+ 'core-navigation' |+ 'core-tabs' |+ 'core-install' |+ 'core-input' |+ 'vision' |+ 'pdf' |+ 'testing' |+ 'tracing';export type Config = {/**diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.tsindex d09ee22a64..d9653f0a58 100644--- a/packages/playwright/src/mcp/program.ts+++ b/packages/playwright/src/mcp/program.ts@@ -116,13 +116,12 @@ export function decorateCommand(command: Command, version: string) {config.outputMode = 'file';config.codegen = 'none';config.snapshot.mode = 'full';- config.capabilities = ['core', 'internal', 'tracing', 'pdf', 'vision'];const serverBackendFactory: mcpServer.ServerBackendFactory = {name: 'Playwright',nameInConfig: 'playwright-daemon',version,- create: () => new BrowserServerBackend(config, browserContextFactory)+ create: () => new BrowserServerBackend(config, browserContextFactory, { allTools: true })};const socketPath = await startMcpDaemonServer(options.daemon, serverBackendFactory);console.error(`Daemon server listening on ${socketPath}`);diff --git a/packages/playwright/src/mcp/terminal/command.ts b/packages/playwright/src/mcp/terminal/command.tsindex 9146504d97..32e6fdd05f 100644--- a/packages/playwright/src/mcp/terminal/command.ts+++ b/packages/playwright/src/mcp/terminal/command.ts@@ -17,13 +17,16 @@import type zodType from 'zod';+export type Category = 'core' | 'navigation' | 'keyboard' | 'mouse' | 'export' | 'storage' | 'tabs' | 'devtools';+export type CommandSchema<Args extends zodType.ZodTypeAny, Options extends zodType.ZodTypeAny> = {name: string;+ category: Category;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;+ toolParams: (args: zodType.infer<Args> & zodType.infer<Options>) => any;};export type AnyCommandSchema = CommandSchema<any, any>;@@ -49,7 +52,7 @@ export function parseCommand(command: AnyCommandSchema, args: Record<string, str}const toolName = typeof command.toolName === 'function' ? command.toolName(parsedArgsObject, options) : command.toolName;- const toolParams = command.toolParams(parsedArgsObject, options);+ 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.tsindex c41722f74b..861644c4ff 100644--- a/packages/playwright/src/mcp/terminal/commands.ts+++ b/packages/playwright/src/mcp/terminal/commands.ts@@ -20,337 +20,512 @@ 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 }),-});+// Navigation commands-const doubleClick = declareCommand({- name: 'dblclick',- description: 'Perform double click on a web page',+const open = declareCommand({+ name: 'open',+ description: 'Open URL',+ category: 'core',args: z.object({- ref: z.string().describe('Exact target element reference from the page snapshot'),+ url: z.string().describe('The URL to navigate to'),}),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'),+ headed: z.boolean().default(false).describe('Run browser in headed mode'),}),- toolName: 'browser_click',- toolParams: ({ ref }, { button, modifiers }) => ({ ref, button, modifiers, doubleClick: true }),+ toolName: 'browser_open',+ toolParams: ({ url, headed }) => ({ url, headed }),});const close = declareCommand({name: 'close',description: 'Close the page',+ category: 'core',args: z.object({}),toolName: 'browser_close',toolParams: () => ({}),});-const consoleMessages = declareCommand({- name: 'console',- description: 'Returns all console messages',+const goBack = declareCommand({+ name: 'go-back',+ description: 'Go back to the previous page',+ category: 'navigation',+ args: z.object({}),+ toolName: 'browser_navigate_back',+ toolParams: () => ({}),+});++const goForward = declareCommand({+ name: 'go-forward',+ description: 'Go forward to the next page',+ category: 'navigation',+ args: z.object({}),+ toolName: 'browser_navigate_forward',+ toolParams: () => ({}),+});++const reload = declareCommand({+ name: 'reload',+ description: 'Reload the current page',+ category: 'navigation',+ args: z.object({}),+ toolName: 'browser_reload',+ toolParams: () => ({}),+});++// Keyboard++const pressKey = declareCommand({+ name: 'key-press',+ description: 'Press a key on the keyboard, `a`, `ArrowLeft`',+ category: 'keyboard',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".'),+ key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),}),- toolName: 'browser_console_messages',- toolParams: ({ level }) => ({ level }),+ toolName: 'browser_press_key',+ toolParams: ({ key }) => ({ key }),});-const drag = declareCommand({- name: 'drag',- description: 'Perform drag and drop between two elements',+const type = declareCommand({+ name: 'type',+ description: 'Type text into editable element',+ category: 'core',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'),+ text: z.string().describe('Text to type into the element'),}),options: z.object({- headed: z.boolean().default(false).describe('Run browser in headed mode'),+ submit: z.boolean().optional().describe('Whether to submit entered text (press Enter after)'),}),- toolName: 'browser_drag',- toolParams: ({ startRef, endRef }) => ({ startRef, endRef }),+ toolName: 'browser_press_sequentially',+ toolParams: ({ text, submit }) => ({ text, submit }),});-const evaluate = declareCommand({- name: 'evaluate',- description: 'Evaluate JavaScript expression on page or element',+const keydown = declareCommand({+ name: 'key-down',+ description: 'Press a key down on the keyboard',+ category: 'keyboard',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'),+ key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),}),- toolName: 'browser_evaluate',- toolParams: ({ function: fn, ref }) => ({ function: fn, ref }),+ toolName: 'browser_keydown',+ toolParams: ({ key }) => ({ key }),});-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.'),+const keyup = declareCommand({+ name: 'key-up',+ description: 'Press a key up on the keyboard',+ category: '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_file_upload',- toolParams: (_, { paths }) => ({ paths }),+ toolName: 'browser_keyup',+ toolParams: ({ key }) => ({ key }),});-const handleDialog = declareCommand({- name: 'handle-dialog',- description: 'Handle a dialog',+// Mouse++const mouseMove = declareCommand({+ name: 'mouse-move',+ description: 'Move mouse to a given position',+ category: 'mouse',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.'),+ x: z.number().describe('X coordinate'),+ y: z.number().describe('Y coordinate'),}),- toolName: 'browser_handle_dialog',- toolParams: ({ accept, promptText }) => ({ accept, promptText }),+ toolName: 'browser_mouse_move_xy',+ toolParams: ({ x, y }) => ({ x, y }),});-const hover = declareCommand({- name: 'hover',- description: 'Hover over element on page',+const mouseDown = declareCommand({+ name: 'mouse-down',+ description: 'Press mouse down',+ category: 'mouse',args: z.object({- ref: z.string().describe('Exact target element reference from the page snapshot'),+ button: z.string().optional().describe('Button to press, defaults to left'),}),- toolName: 'browser_hover',- toolParams: ({ ref }) => ({ ref }),+ toolName: 'browser_mouse_down',+ toolParams: ({ button }) => ({ button }),});-const open = declareCommand({- name: 'open',- description: 'Open URL',+const mouseUp = declareCommand({+ name: 'mouse-up',+ description: 'Press mouse up',+ category: 'mouse',args: z.object({- url: z.string().describe('The URL to navigate to'),+ button: z.string().optional().describe('Button to press, defaults to left'),}),- options: z.object({- headed: z.boolean().default(false).describe('Run browser in headed mode'),+ toolName: 'browser_mouse_up',+ toolParams: ({ button }) => ({ button }),+});++const mouseWheel = declareCommand({+ name: 'mouse-wheel',+ description: 'Scroll mouse wheel',+ category: 'mouse',+ args: z.object({+ dx: z.number().describe('Y delta'),+ dy: z.number().describe('X delta'),}),- toolName: 'browser_open',- toolParams: ({ url }, { headed }) => ({ url, headed }),+ toolName: 'browser_mouse_wheel',+ toolParams: ({ dx: deltaY, dy: deltaX }) => ({ deltaY, deltaX }),});-const navigateBack = declareCommand({- name: 'go-back',- description: 'Go back to the previous page',- args: z.object({}),- toolName: 'browser_navigate_back',- toolParams: () => ({}),+// Core++const click = declareCommand({+ name: 'click',+ description: 'Perform click on a web page',+ category: 'core',+ args: z.object({+ ref: z.string().describe('Exact target element reference from the page snapshot'),+ button: z.string().optional().describe('Button to click, defaults to left'),+ }),+ options: z.object({+ modifiers: z.array(z.string()).optional().describe('Modifier keys to press'),+ }),+ toolName: 'browser_click',+ toolParams: ({ ref, button, modifiers }) => ({ ref, button, modifiers }),});-const networkRequests = declareCommand({- name: 'network-requests',- description: 'Returns all network requests since loading the page',- args: z.object({}),+const doubleClick = declareCommand({+ name: 'dblclick',+ description: 'Perform double click on a web page',+ category: 'core',+ args: z.object({+ ref: z.string().describe('Exact target element reference from the page snapshot'),+ button: z.string().optional().describe('Button to click, defaults to left'),+ }),options: z.object({- includeStatic: z.boolean().optional().describe('Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.'),+ modifiers: z.array(z.string()).optional().describe('Modifier keys to press'),}),- toolName: 'browser_network_requests',- toolParams: (_, { includeStatic }) => ({ includeStatic }),+ toolName: 'browser_click',+ toolParams: ({ ref, button, modifiers }) => ({ ref, button, modifiers, doubleClick: true }),});-const pressKey = declareCommand({- name: 'press',- description: 'Press a key on the keyboard',+const drag = declareCommand({+ name: 'drag',+ description: 'Perform drag and drop between two elements',+ category: 'core',args: z.object({- key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),+ startRef: z.string().describe('Exact source element reference from the page snapshot'),+ endRef: z.string().describe('Exact target element reference from the page snapshot'),}),- toolName: 'browser_press_key',- toolParams: ({ key }) => ({ key }),+ options: z.object({+ headed: z.boolean().default(false).describe('Run browser in headed mode'),+ }),+ toolName: 'browser_drag',+ toolParams: ({ startRef, endRef }) => ({ startRef, endRef }),});-const resize = declareCommand({- name: 'resize',- description: 'Resize the browser window',+const fill = declareCommand({+ name: 'fill',+ description: 'Fill text into editable element',+ category: 'core',args: z.object({- width: z.number().describe('Width of the browser window'),- height: z.number().describe('Height of the browser window'),+ ref: z.string().describe('Exact target element reference from the page snapshot'),+ text: z.string().describe('Text to fill into the element'),}),- toolName: 'browser_resize',- toolParams: ({ width, height }) => ({ width, height }),+ options: z.object({+ submit: z.boolean().optional().describe('Whether to submit entered text (press Enter after)'),+ }),+ toolName: 'browser_fill',+ toolParams: ({ ref, text, submit }) => ({ ref, text, submit }),});-const runCode = declareCommand({- name: 'run-code',- description: 'Run Playwright code snippet',+const hover = declareCommand({+ name: 'hover',+ description: 'Hover over element on page',+ category: 'core',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.'),+ ref: z.string().describe('Exact target element reference from the page snapshot'),}),- toolName: 'browser_run_code',- toolParams: ({ code }) => ({ code }),+ toolName: 'browser_hover',+ toolParams: ({ ref }) => ({ ref }),});const selectOption = declareCommand({- name: 'select-option',+ name: 'select',description: 'Select an option in a dropdown',+ category: 'core',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.'),+ vals: 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 }),+ toolParams: ({ ref, vals: values }) => ({ ref, values }),+});++const fileUpload = declareCommand({+ name: 'upload',+ description: 'Upload one or multiple files',+ category: 'core',+ args: z.object({+ file: z.string().describe('The absolute paths to the files to upload'),+ }),+ toolName: 'browser_file_upload',+ toolParams: ({ file }) => ({ paths: [file] }),+});++const check = declareCommand({+ name: 'check',+ description: 'Check a checkbox or radio button',+ category: 'core',+ args: z.object({+ ref: z.string().describe('Exact target element reference from the page snapshot'),+ }),+ toolName: 'browser_check',+ toolParams: ({ ref }) => ({ ref }),+});++const uncheck = declareCommand({+ name: 'uncheck',+ description: 'Uncheck a checkbox or radio button',+ category: 'core',+ args: z.object({+ ref: z.string().describe('Exact target element reference from the page snapshot'),+ }),+ toolName: 'browser_uncheck',+ toolParams: ({ ref }) => ({ ref }),});const snapshot = declareCommand({name: 'snapshot',- description: 'Capture accessibility snapshot of the current page, this is better than screenshot',+ description: 'Capture page snapshot to obtain element ref',+ category: 'core',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 }),+ 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.',+const evaluate = declareCommand({+ name: 'eval',+ description: 'Evaluate JavaScript expression on page or element',+ category: 'core',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.'),+ func: 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_take_screenshot',- toolParams: ({ ref }, { filename, fullPage }) => ({ filename, ref, fullPage }),+ toolName: 'browser_evaluate',+ toolParams: ({ func: fn, ref }) => ({ function: fn, ref }),});-const type = declareCommand({- name: 'type',- description: 'Type text into editable element',+const dialogAccept = declareCommand({+ name: 'dialog-accept',+ description: 'Accept a dialog',+ category: 'core',args: z.object({- 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)'),+ prompt: z.string().optional().describe('The text of the prompt in case of a prompt dialog.'),}),- toolName: 'browser_press_sequentially',- toolParams: ({ text }, { submit }) => ({ text, submit }),+ toolName: 'browser_handle_dialog',+ toolParams: ({ prompt: promptText }) => ({ accept: true, promptText }),});-const waitFor = declareCommand({- name: 'wait-for',- description: 'Wait for text to appear or disappear or a specified time to pass',+const dialogDismiss = declareCommand({+ name: 'dialog-dismiss',+ description: 'Dismiss a dialog',+ category: 'core',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 }),+ toolName: 'browser_handle_dialog',+ toolParams: () => ({ accept: false }),});-const tab = declareCommand({- name: 'tab',- description: 'Close a browser tab',+const resize = declareCommand({+ name: 'resize',+ description: 'Resize the browser window',+ category: 'core',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.'),+ w: z.number().describe('Width of the browser window'),+ h: z.number().describe('Height of the browser window'),}),+ toolName: 'browser_resize',+ toolParams: ({ w: width, h: height }) => ({ width, height }),+});++// Tabs++const tabList = declareCommand({+ name: 'tab-list',+ description: 'List all tabs',+ category: 'tabs',+ args: z.object({}),toolName: 'browser_tabs',- toolParams: ({ action, index }) => ({ action, index }),+ toolParams: () => ({ action: 'list' }),});-const mouseClickXy = declareCommand({- name: 'mouse-click-xy',- description: 'Click left mouse button at a given position',+const tabNew = declareCommand({+ name: 'tab-new',+ description: 'Create a new tab',+ category: 'tabs',args: z.object({- x: z.number().describe('X coordinate'),- y: z.number().describe('Y coordinate'),+ url: z.string().optional().describe('The URL to navigate to in the new tab. If omitted, the new tab will be blank.'),}),- toolName: 'browser_mouse_click_xy',- toolParams: ({ x, y }) => ({ x, y }),+ toolName: 'browser_tabs',+ toolParams: ({ url }) => ({ action: 'new', url }),});-const mouseDragXy = declareCommand({- name: 'mouse-drag-xy',- description: 'Drag left mouse button to a given position',+const tabClose = declareCommand({+ name: 'tab-close',+ description: 'Close a browser tab',+ category: 'tabs',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'),+ index: z.number().optional().describe('Tab index. If omitted, current tab is closed.'),}),- toolName: 'browser_mouse_drag_xy',- toolParams: ({ startX, startY, endX, endY }) => ({ startX, startY, endX, endY }),+ toolName: 'browser_tabs',+ toolParams: ({ index }) => ({ action: 'close', index }),});-const mouseMoveXy = declareCommand({- name: 'mouse-move-xy',- description: 'Move mouse to a given position',+const tabSelect = declareCommand({+ name: 'tab-select',+ description: 'Select a browser tab',+ category: 'tabs',args: z.object({- x: z.number().describe('X coordinate'),- y: z.number().describe('Y coordinate'),+ index: z.number().describe('Tab index'),}),- toolName: 'browser_mouse_move_xy',- toolParams: ({ x, y }) => ({ x, y }),+ toolName: 'browser_tabs',+ toolParams: ({ index }) => ({ action: 'select', index }),});-// PDF generation commands (opt-in via --caps=pdf)+// Export++const screenshot = declareCommand({+ name: 'screenshot',+ description: 'screenshot of the current page or element',+ category: 'export',+ 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 pdfSave = declareCommand({- name: 'pdf-save',+ name: 'pdf',description: 'Save page as PDF',+ category: 'export',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 }),+ toolParams: ({ filename }) => ({ filename }),+});++// DevTools++const consoleList = declareCommand({+ name: 'console',+ description: 'List console messages',+ category: 'devtools',+ args: z.object({+ ['min-level']: z.string().optional().describe('Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".'),+ }),+ options: z.object({+ clear: z.boolean().optional().describe('Whether to clear the console list'),+ }),+ toolName: 'browser_console_messages',+ toolParams: ({ ['min-level']: minLevel }) => ({ minLevel }),+});++const networkRequests = declareCommand({+ name: 'network',+ description: 'List all network requests since loading the page',+ category: 'devtools',+ args: z.object({}),+ options: z.object({+ static: z.boolean().optional().describe('Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.'),+ clear: z.boolean().optional().describe('Whether to clear the network list'),+ }),+ toolName: 'browser_network_requests',+ toolParams: ({ static: includeStatic }) => ({ includeStatic }),+});++const runCode = declareCommand({+ name: 'run-code',+ description: 'Run Playwright code snippet',+ category: 'devtools',+ 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 startTracing = declareCommand({- name: 'start-tracing',+const tracingStart = declareCommand({+ name: 'tracing-start',description: 'Start trace recording',+ category: 'devtools',args: z.object({}),toolName: 'browser_start_tracing',toolParams: () => ({}),});-const stopTracing = declareCommand({- name: 'stop-tracing',+const tracingStop = declareCommand({+ name: 'tracing-stop',description: 'Stop trace recording',+ category: 'devtools',args: z.object({}),toolName: 'browser_stop_tracing',toolParams: () => ({}),});const commandsArray: AnyCommandSchema[] = [- click,+ // core category+ open,close,+ type,+ click,doubleClick,- consoleMessages,+ fill,drag,- evaluate,- fileUpload,- handleDialog,hover,- open,- navigateBack,- networkRequests,- pressKey,- resize,- runCode,selectOption,+ fileUpload,+ check,+ uncheck,snapshot,+ evaluate,+ consoleList,+ dialogAccept,+ dialogDismiss,+ resize,++ // navigation category+ goBack,+ goForward,+ reload,++ // keyboard category+ pressKey,+ keydown,+ keyup,++ // mouse category+ mouseMove,+ mouseDown,+ mouseUp,+ mouseWheel,++ // export categoryscreenshot,- type,- waitFor,- tab,- mouseClickXy,- mouseDragXy,- mouseMoveXy,pdfSave,- startTracing,- stopTracing,++ // tabs category+ tabList,+ tabNew,+ tabClose,+ tabSelect,++ // devtools category+ networkRequests,+ runCode,+ tracingStart,+ tracingStop,];export const commands = Object.fromEntries(commandsArray.map(cmd => [cmd.name, cmd]));diff --git a/packages/playwright/src/mcp/terminal/help.json b/packages/playwright/src/mcp/terminal/help.jsonindex 3d1fb8c09f..441f9bac2a 100644--- a/packages/playwright/src/mcp/terminal/help.json+++ b/packages/playwright/src/mcp/terminal/help.json@@ -1,32 +1,43 @@{- "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> 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 <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",+ "global": "Usage: playwright-cli <command> [args] [options]\n\nCore:\n open <url> open url\n close close the page\n type <text> type text into editable element\n click <ref> [button] perform click on a web page\n dblclick <ref> [button] perform double click on a web page\n fill <ref> <text> fill text into editable element\n drag <startRef> <endRef> perform drag and drop between two elements\n hover <ref> hover over element on page\n select <ref> <vals> select an option in a dropdown\n upload <file> upload one or multiple files\n check <ref> check a checkbox or radio button\n uncheck <ref> uncheck a checkbox or radio button\n snapshot capture page snapshot to obtain element ref\n eval <func> [ref] evaluate javascript expression on page or element\n dialog-accept [prompt] accept a dialog\n dialog-dismiss dismiss a dialog\n resize <w> <h> resize the browser window\n\nNavigation:\n go-back go back to the previous page\n go-forward go forward to the next page\n reload reload the current page\n\nKeyboard:\n key-press <key> press a key on the keyboard, `a`, `arrowleft`\n key-down <key> press a key down on the keyboard\n key-up <key> press a key up on the keyboard\n\nMouse:\n mouse-move <x> <y> move mouse to a given position\n mouse-down [button] press mouse down\n mouse-up [button] press mouse up\n mouse-wheel <dx> <dy> scroll mouse wheel\n\nSave as:\n screenshot [ref] screenshot of the current page or element\n pdf save page as pdf\n\nTabs:\n tab-list list all tabs\n tab-new [url] create a new tab\n tab-close [index] close a browser tab\n tab-select <index> select a browser tab\n\nDevTools:\n console [min-level] list console messages\n network list all network requests since loading the page\n run-code <code> run playwright code snippet\n tracing-start start trace recording\n tracing-stop 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",+ "open": "playwright-cli open <url>\n\nOpen URL\n\nArguments:\n <url> the url to navigate to\nOptions:\n --headed run browser in headed mode","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",+ "type": "playwright-cli type <text>\n\nType text into editable element\n\nArguments:\n <text> text to type into the element\nOptions:\n --submit whether to submit entered text (press enter after)",+ "click": "playwright-cli click <ref> [button]\n\nPerform click on a web page\n\nArguments:\n <ref> exact target element reference from the page snapshot\n [button] button to click, defaults to left\nOptions:\n --modifiers modifier keys to press",+ "dblclick": "playwright-cli dblclick <ref> [button]\n\nPerform double click on a web page\n\nArguments:\n <ref> exact target element reference from the page snapshot\n [button] button to click, defaults to left\nOptions:\n --modifiers modifier keys to press",+ "fill": "playwright-cli fill <ref> <text>\n\nFill text into editable element\n\nArguments:\n <ref> exact target element reference from the page snapshot\n <text> text to fill into the element\nOptions:\n --submit whether to submit entered text (press enter after)",+ "drag": "playwright-cli drag <startRef> <endRef>\n\nPerform drag and drop between two elements\n\nArguments:\n <startRef> exact source element reference from the page snapshot\n <endRef> exact target element reference from the page snapshot\nOptions:\n --headed run browser in headed mode",+ "hover": "playwright-cli hover <ref>\n\nHover over element on page\n\nArguments:\n <ref> exact target element reference from the page snapshot",+ "select": "playwright-cli select <ref> <vals>\n\nSelect an option in a dropdown\n\nArguments:\n <ref> exact target element reference from the page snapshot\n <vals> array of values to select in the dropdown. this can be a single value or multiple values.",+ "upload": "playwright-cli upload <file>\n\nUpload one or multiple files\n\nArguments:\n <file> the absolute paths to the files to upload",+ "check": "playwright-cli check <ref>\n\nCheck a checkbox or radio button\n\nArguments:\n <ref> exact target element reference from the page snapshot",+ "uncheck": "playwright-cli uncheck <ref>\n\nUncheck a checkbox or radio button\n\nArguments:\n <ref> exact target element reference from the page snapshot",+ "snapshot": "playwright-cli snapshot \n\nCapture page snapshot to obtain element ref\n\nOptions:\n --filename save snapshot to markdown file instead of returning it in the response.",+ "eval": "playwright-cli eval <func> [ref]\n\nEvaluate JavaScript expression on page or element\n\nArguments:\n <func> () => { /* code */ } or (element) => { /* code */ } when element is provided\n [ref] exact target element reference from the page snapshot",+ "console": "playwright-cli console [min-level]\n\nList console messages\n\nArguments:\n [min-level] level of the console messages to return. each level includes the messages of more severe levels. defaults to \"info\".\nOptions:\n --clear whether to clear the console list",+ "dialog-accept": "playwright-cli dialog-accept [prompt]\n\nAccept a dialog\n\nArguments:\n [prompt] the text of the prompt in case of a prompt dialog.",+ "dialog-dismiss": "playwright-cli dialog-dismiss \n\nDismiss a dialog\n",+ "resize": "playwright-cli resize <w> <h>\n\nResize the browser window\n\nArguments:\n <w> width of the browser window\n <h> height of the browser window","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": "playwright-cli press <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 <text>\n\nType text into editable element\n\nArguments:\n <text>\tText to type into the element\nOptions:\n --submit\twhether to submit entered text (press enter after)",- "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"+ "go-forward": "playwright-cli go-forward \n\nGo forward to the next page\n",+ "reload": "playwright-cli reload \n\nReload the current page\n",+ "key-press": "playwright-cli key-press <key>\n\nPress a key on the keyboard, `a`, `ArrowLeft`\n\nArguments:\n <key> name of the key to press or a character to generate, such as `arrowleft` or `a`",+ "key-down": "playwright-cli key-down <key>\n\nPress a key down on the keyboard\n\nArguments:\n <key> name of the key to press or a character to generate, such as `arrowleft` or `a`",+ "key-up": "playwright-cli key-up <key>\n\nPress a key up on the keyboard\n\nArguments:\n <key> name of the key to press or a character to generate, such as `arrowleft` or `a`",+ "mouse-move": "playwright-cli mouse-move <x> <y>\n\nMove mouse to a given position\n\nArguments:\n <x> x coordinate\n <y> y coordinate",+ "mouse-down": "playwright-cli mouse-down [button]\n\nPress mouse down\n\nArguments:\n [button] button to press, defaults to left",+ "mouse-up": "playwright-cli mouse-up [button]\n\nPress mouse up\n\nArguments:\n [button] button to press, defaults to left",+ "mouse-wheel": "playwright-cli mouse-wheel <dx> <dy>\n\nScroll mouse wheel\n\nArguments:\n <dx> y delta\n <dy> x delta",+ "screenshot": "playwright-cli screenshot [ref]\n\nscreenshot of the current page or element\n\nArguments:\n [ref] exact target element reference from the page snapshot.\nOptions:\n --filename file name to save the screenshot to. defaults to `page-{timestamp}.{png|jpeg}` if not specified.\n --fullPage when true, takes a screenshot of the full scrollable page, instead of the currently visible viewport.",+ "pdf": "playwright-cli pdf \n\nSave page as PDF\n\nOptions:\n --filename file name to save the pdf to. defaults to `page-{timestamp}.pdf` if not specified.",+ "tab-list": "playwright-cli tab-list \n\nList all tabs\n",+ "tab-new": "playwright-cli tab-new [url]\n\nCreate a new tab\n\nArguments:\n [url] the url to navigate to in the new tab. if omitted, the new tab will be blank.",+ "tab-close": "playwright-cli tab-close [index]\n\nClose a browser tab\n\nArguments:\n [index] tab index. if omitted, current tab is closed.",+ "tab-select": "playwright-cli tab-select <index>\n\nSelect a browser tab\n\nArguments:\n <index> tab index",+ "network": "playwright-cli network \n\nList all network requests since loading the page\n\nOptions:\n --static whether to include successful static resources like images, fonts, scripts, etc. defaults to false.\n --clear whether to clear the network list",+ "run-code": "playwright-cli run-code <code>\n\nRun Playwright code snippet\n\nArguments:\n <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.",+ "tracing-start": "playwright-cli tracing-start \n\nStart trace recording\n",+ "tracing-stop": "playwright-cli tracing-stop \n\nStop trace recording\n"}}\ No newline at end of filediff --git a/packages/playwright/src/mcp/terminal/helpGenerator.ts b/packages/playwright/src/mcp/terminal/helpGenerator.tsindex ccec783b4e..f916b27f13 100644--- a/packages/playwright/src/mcp/terminal/helpGenerator.ts+++ b/packages/playwright/src/mcp/terminal/helpGenerator.ts@@ -19,20 +19,29 @@ import path from 'path';import { commands } from './commands';import type zodType from 'zod';-import type { AnyCommandSchema } from './command';+import type { AnyCommandSchema, Category } from './command';-function generateCommandHelp(command: AnyCommandSchema) {- const args: { name: string, description: string }[] = [];+type CommandArg = { name: string, description: string, optional: boolean };+function commandArgs(command: AnyCommandSchema): CommandArg[] {+ const args: CommandArg[] = [];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 });+ args.push({ name, description, optional: zodSchema.safeParse(undefined).success });}+ return args;+}+function commandArgsText(args: CommandArg[]) {+ return args.map(a => a.optional ? `[${a.name}]` : `<${a.name}>`).join(' ');+}++function generateCommandHelp(command: AnyCommandSchema) {+ const args = commandArgs(command);const lines: string[] = [- `playwright-cli ${command.name} ${Object.keys(shape).map(k => `<${k}>`).join(' ')}`,+ `playwright-cli ${command.name} ${commandArgsText(args)}`,'',command.description,'',@@ -40,7 +49,7 @@ function generateCommandHelp(command: AnyCommandSchema) {if (args.length) {lines.push('Arguments:');- lines.push(...args.map(({ name, description }) => ` <${name}>\t${description}`));+ lines.push(...args.map(a => formatWithGap(` ${a.optional ? `[${a.name}]` : `<${a.name}>`}`, a.description.toLowerCase())));}if (command.options) {@@ -49,36 +58,49 @@ function generateCommandHelp(command: AnyCommandSchema) {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(formatWithGap(` --${name}`, description));}}return lines.join('\n');}+const categories: { name: Category, title: string }[] = [+ { name: 'core', title: 'Core' },+ { name: 'navigation', title: 'Navigation' },+ { name: 'keyboard', title: 'Keyboard' },+ { name: 'mouse', title: 'Mouse' },+ { name: 'export', title: 'Save as' },+ { name: 'tabs', title: 'Tabs' },+ { name: 'storage', title: 'Storage' },+ { name: 'devtools', title: 'DevTools' },+] as const;+function generateHelp() {const lines: string[] = [];- lines.push('Usage: playwright-cli <command> [options]');- lines.push('Commands:');+ lines.push('Usage: playwright-cli <command> [args] [options]');+ const commandsByCategory = new Map<string, AnyCommandSchema[]>();+ for (const c of categories)+ commandsByCategory.set(c.name, []);for (const command of Object.values(commands))- lines.push(' ' + generateHelpEntry(command));+ commandsByCategory.get(command.category)!.push(command);++ for (const c of categories) {+ const cc = commandsByCategory.get(c.name)!;+ if (!cc.length)+ continue;+ lines.push(`\n${c.title}:`);+ for (const command of cc)+ 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 args = commandArgs(command);+ const prefix = ` ${command.name} ${commandArgsText(args)}`;const suffix = command.description.toLowerCase();- const padding = ' '.repeat(Math.max(1, 40 - prefix.length));- return prefix + padding + suffix;+ return formatWithGap(prefix, suffix);}async function main() {@@ -92,6 +114,13 @@ async function main() {// eslint-disable-next-line no-consoleconsole.log('Writing ', path.relative(process.cwd(), fileName));await fs.promises.writeFile(fileName, JSON.stringify(help, null, 2));+ // eslint-disable-next-line no-console+ console.log(help.global);+}++function formatWithGap(prefix: string, text: string) {+ const indent = Math.max(1, 30 - prefix.length);+ return prefix + ' '.repeat(indent) + text;}void main();diff --git a/tests/mcp/generator.spec.ts b/tests/mcp/generator.spec.tsindex b5769459ea..5504c00dd5 100644--- a/tests/mcp/generator.spec.ts+++ b/tests/mcp/generator.spec.ts@@ -30,35 +30,27 @@ test('generator tools intent', async ({ startClient }) => {}toolsWithIntent.sort();- expect(toolsWithIntent).toEqual([- 'browser_click',- 'browser_close',- 'browser_drag',- 'browser_evaluate',- 'browser_file_upload',- 'browser_fill_form',- 'browser_handle_dialog',- 'browser_hover',- 'browser_install',- 'browser_mouse_click_xy',- 'browser_mouse_drag_xy',- 'browser_mouse_move_xy',- 'browser_navigate',- 'browser_navigate_back',- 'browser_open',- 'browser_press_key',- 'browser_press_sequentially',- 'browser_resize',- 'browser_run_code',- 'browser_select_option',- 'browser_tabs',- 'browser_type',- 'browser_verify_element_visible',- 'browser_verify_list_visible',- 'browser_verify_text_visible',- 'browser_verify_value',- 'browser_wait_for',- ]);+ expect(toolsWithIntent).toContain('browser_click');+ expect(toolsWithIntent).toContain('browser_close');+ expect(toolsWithIntent).toContain('browser_drag');+ expect(toolsWithIntent).toContain('browser_evaluate');+ expect(toolsWithIntent).toContain('browser_file_upload');+ expect(toolsWithIntent).toContain('browser_fill_form');+ expect(toolsWithIntent).toContain('browser_handle_dialog');+ expect(toolsWithIntent).toContain('browser_hover');+ expect(toolsWithIntent).toContain('browser_install');+ expect(toolsWithIntent).toContain('browser_mouse_click_xy');+ expect(toolsWithIntent).toContain('browser_mouse_drag_xy');+ expect(toolsWithIntent).toContain('browser_mouse_move_xy');+ expect(toolsWithIntent).toContain('browser_navigate');+ expect(toolsWithIntent).toContain('browser_navigate_back');+ expect(toolsWithIntent).toContain('browser_open');+ expect(toolsWithIntent).toContain('browser_press_key');+ expect(toolsWithIntent).toContain('browser_press_sequentially');+ expect(toolsWithIntent).toContain('browser_resize');+ expect(toolsWithIntent).toContain('browser_run_code');+ expect(toolsWithIntent).toContain('browser_select_option');+ expect(toolsWithIntent).toContain('browser_tabs');});test('generator_setup_page', async ({ startClient }) => {