Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export class BrowserServerBackend implements ServerBackend {
const parsedArguments = tool.schema.inputSchema.parse(rawArguments || {}) as any;
const cwd = rawArguments?._meta && typeof rawArguments?._meta === 'object' && (rawArguments._meta as any)?.cwd;
const context = this._context!;
const response = Response.create(context, name, parsedArguments, cwd);
const response = new Response(context, name, parsedArguments, cwd);
context.setRunningTool(name);
let responseObject: mcpServer.CallToolResult;
try {
Expand Down
27 changes: 18 additions & 9 deletions packages/playwright/src/mcp/browser/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { renderModalStates, shouldIncludeMessage } from './tab';
import { dateAsFileName } from './tools/utils';
import { scaleImageToFitMessage } from './tools/screenshot';

import type { TabHeader } from './tab';
import type { LogChunk, TabHeader } from './tab';
import type { CallToolResult, ImageContent, TextContent } from '@modelcontextprotocol/sdk/types.js';
import type { Context } from './context';

Expand Down Expand Up @@ -60,17 +60,13 @@ export class Response {
private _relativeTo: string | undefined;
private _imageResults: { data: Buffer, imageType: 'png' | 'jpeg' }[] = [];

private constructor(context: Context, toolName: string, toolArgs: Record<string, any>, relativeTo?: string) {
constructor(context: Context, toolName: string, toolArgs: Record<string, any>, relativeTo?: string) {
this._context = context;
this.toolName = toolName;
this.toolArgs = toolArgs;
this._relativeTo = relativeTo ?? context.firstRootPath();
}

static create(context: Context, toolName: string, toolArgs: Record<string, any>, relativeTo?: string) {
return new Response(context, toolName, toolArgs, relativeTo);
}

private _computRelativeTo(fileName: string): string {
if (this._relativeTo)
return path.relative(this._relativeTo, fileName);
Expand Down Expand Up @@ -219,10 +215,10 @@ export class Response {
}

// Handle tab log
const text: string[] = renderLogChunk(tabSnapshot?.logChunk, 'console', file => this._computRelativeTo(file));
if (tabSnapshot?.events.filter(event => event.type !== 'request').length) {
const text: string[] = [];
for (const event of tabSnapshot.events) {
if (event.type === 'console') {
if (event.type === 'console' && !tabSnapshot.logChunk) {
if (shouldIncludeMessage(this._context.config.console.level, event.message.type))
text.push(`- ${trimMiddle(event.message.toString(), 100)}`);
} else if (event.type === 'download-start') {
Expand All @@ -232,8 +228,8 @@ export class Response {
text.push(`- Downloaded file ${event.download.download.suggestedFilename()} to "${this._computRelativeTo(event.download.outputFile)}"`);
}
}
addSection('Events', text);
}
addSection('Events', text);
return sections;
}
}
Expand All @@ -258,6 +254,19 @@ export function renderTabsMarkdown(tabs: TabHeader[]): string[] {
return lines;
}

function renderLogChunk(logChunk: LogChunk | undefined, type: string, relativeTo: (fileName: string) => string): string[] {
if (!logChunk)
return [];
const lines: string[] = [];
const logFilePath = relativeTo(logChunk.file);
const entryWord = logChunk.entryCount === 1 ? 'entry' : 'entries';
const lineRange = logChunk.fromLine === logChunk.toLine
? `#L${logChunk.fromLine}`
: `#L${logChunk.fromLine}-L${logChunk.toLine}`;
lines.push(`- ${logChunk.entryCount} new ${type} ${entryWord} in "${logFilePath}${lineRange}"`);
return lines;
}

function trimMiddle(text: string, maxLength: number) {
if (text.length <= maxLength)
return text;
Expand Down
89 changes: 84 additions & 5 deletions packages/playwright/src/mcp/browser/tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
* limitations under the License.
*/

import fs from 'fs';
import { EventEmitter } from 'events';
import * as playwright from 'playwright-core';
import { asLocator, ManualPromise } from 'playwright-core/lib/utils';

import { callOnPageNoTrace, waitForCompletion, eventWaiter } from './tools/utils';
import { callOnPageNoTrace, waitForCompletion, eventWaiter, dateAsFileName } from './tools/utils';
import { logUnhandledError } from '../log';
import { ModalState } from './tools/tool';
import { handleDialog } from './tools/dialogs';
Expand Down Expand Up @@ -77,13 +78,81 @@ export type TabHeader = {
current: boolean;
};

export type LogChunk = {
file: string;
fromLine: number;
toLine: number;
entryCount: number;
};

export type TabSnapshot = {
ariaSnapshot: string;
ariaSnapshotDiff?: string;
modalStates: ModalState[];
events: EventEntry[];
logChunk?: LogChunk;
};

class LogFile {
private _startTime: number = Date.now();
private _context: Context;
private _filePrefix: string;
private _title: string;

private _file: string | undefined;
private _stopped: boolean = false;

private _line: number = 0;
private _entries: number = 0;
private _lastLine: number = 0;
private _lastEntries: number = 0;

private _writeChain: Promise<void> = Promise.resolve();

constructor(context: Context, filePrefix: string, title: string) {
this._context = context;
this._filePrefix = filePrefix;
this._title = title;
}

appendLine(wallTime: number, text: string) {
this._writeChain = this._writeChain.then(() => this._write(wallTime, text)).catch(logUnhandledError);
}

stop() {
this._stopped = true;
}

async take(): Promise<LogChunk | undefined> {
await this._writeChain;
if (!this._file || this._entries === this._lastEntries)
return undefined;
const chunk: LogChunk = {
file: this._file,
fromLine: this._lastLine + 1,
toLine: this._line,
entryCount: this._entries - this._lastEntries,
};
this._lastLine = this._line;
this._lastEntries = this._entries;
return chunk;
}

private async _write(wallTime: number, text: string) {
if (this._stopped)
return;
this._file ??= await this._context.outputFile(dateAsFileName(this._filePrefix, 'log', new Date(this._startTime)), { origin: 'code', title: this._title });
const relativeTime = wallTime - this._startTime;

const logLine = `[${String(relativeTime).padStart(8, ' ')}ms] ${text}\n`;
await fs.promises.appendFile(this._file, logLine);

const lineCount = logLine.split('\n').length - 1;
this._line += lineCount;
this._entries++;
}
}

export class Tab extends EventEmitter<TabEventsInterface> {
readonly context: Context;
readonly page: Page;
Expand All @@ -95,8 +164,8 @@ export class Tab extends EventEmitter<TabEventsInterface> {
private _modalStates: ModalState[] = [];
private _initializedPromise: Promise<void>;
private _needsFullSnapshot = false;
private _eventEntries: EventEntry[] = [];
private _recentEventEntries: EventEntry[] = [];
private _consoleLog: LogFile | undefined;

constructor(context: Context, page: playwright.Page, onPageClose: (tab: Tab) => void) {
super();
Expand All @@ -122,6 +191,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
page.setDefaultNavigationTimeout(this.context.config.timeouts.navigation);
page.setDefaultTimeout(this.context.config.timeouts.action);
(page as any)[tabSymbol] = this;
this._resetConsoleLogFile();
this._initializedPromise = this._initialize();
}

Expand Down Expand Up @@ -195,8 +265,15 @@ export class Tab extends EventEmitter<TabEventsInterface> {
this._consoleMessages.length = 0;
this._downloads.length = 0;
this._requests.clear();
this._eventEntries.length = 0;
this._recentEventEntries.length = 0;
this._resetConsoleLogFile();
}

private _resetConsoleLogFile() {
if (this.context.config.outputMode !== 'file')
return;
this._consoleLog?.stop();
this._consoleLog = new LogFile(this.context, 'console', 'Console');
}

private _handleRequest(request: playwright.Request) {
Expand All @@ -206,11 +283,12 @@ export class Tab extends EventEmitter<TabEventsInterface> {

private _handleConsoleMessage(message: ConsoleMessage) {
this._consoleMessages.push(message);
this._addLogEntry({ type: 'console', wallTime: Date.now(), message });
const wallTime = Date.now();
this._addLogEntry({ type: 'console', wallTime, message });
this._consoleLog?.appendLine(wallTime, message.toString());
}

private _addLogEntry(entry: EventEntry) {
this._eventEntries.push(entry);
this._recentEventEntries.push(entry);
}

Expand Down Expand Up @@ -302,6 +380,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
};
});
if (tabSnapshot) {
tabSnapshot.logChunk = await this._consoleLog?.take();
tabSnapshot.events = this._recentEventEntries;
this._recentEventEntries = [];
}
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright/src/mcp/browser/tools/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ export async function callOnPageNoTrace<T>(page: playwright.Page, callback: (pag
return await (page as any)._wrapApiCall(() => callback(page), { internal: true });
}

export function dateAsFileName(prefix: string, extension: string): string {
const date = new Date();
export function dateAsFileName(prefix: string, extension: string, date?: Date): string {
date = date ?? new Date();
return `${prefix}-${date.toISOString().replace(/[:.]/g, '-')}.${extension}`;
}

Expand Down
55 changes: 37 additions & 18 deletions packages/playwright/src/mcp/terminal/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* limitations under the License.
*/

import { z } from 'playwright-core/lib/mcpBundle';

import type zodType from 'zod';

export type Category = 'core' | 'navigation' | 'keyboard' | 'mouse' | 'export' | 'storage' | 'tabs' | 'devtools' | 'session' | 'config';
Expand All @@ -34,30 +36,47 @@ export function declareCommand<Args extends zodType.ZodTypeAny, Options extends
return command;
}

const kEmptyOptions = z.object({});
const kEmptyArgs = z.object({});

export function parseCommand(command: AnyCommandSchema, args: Record<string, string> & { _: string[] }): { toolName: string, toolParams: any } {
const shape = command.args ? (command.args as zodType.ZodObject<any>).shape : {};
const argv = args['_'];
const options = command.options?.parse({ ...args, _: undefined }) ?? {};
const argsObject: Record<string, string> = {};
let i = 0;
for (const name of Object.keys(shape))
argsObject[name] = argv[++i];
const optionsObject = { ...args } as Record<string, string>;
delete optionsObject['_'];
const optionsSchema = (command.options ?? kEmptyOptions).strict();
const options: Record<string, string> = zodParse(optionsSchema, optionsObject, 'option');

let parsedArgsObject: Record<string, string> = {};
try {
parsedArgsObject = command.args?.parse(argsObject) ?? {};
} catch (e) {
throw new Error(formatZodError(e as zodType.ZodError));
}
const argsSchema = (command.args ?? kEmptyArgs).strict();
const argNames = [...Object.keys(argsSchema.shape)];
const argv = args['_'].slice(1);
if (argv.length > argNames.length)
throw new Error(`error: too many arguments: expected ${argNames.length}, received ${argv.length}`);
const argsObject: Record<string, string> = {};
argNames.forEach((name, index) => argsObject[name] = argv[index]);
const parsedArgsObject: Record<string, string> = zodParse(argsSchema, argsObject, 'argument');

const toolName = typeof command.toolName === 'function' ? command.toolName({ ...parsedArgsObject, ...options }) : command.toolName;
const toolParams = command.toolParams({ ...parsedArgsObject, ...options });
return { toolName, toolParams };
}

function formatZodError(error: zodType.ZodError): string {
const issue = error.issues[0];
if (issue.code === 'invalid_type')
return `${issue.message} in <${issue.path.join('.')}>`;
return error.issues.map(i => i.message).join('\n');
function zodParse(schema: zodType.ZodAny, data: unknown, type: 'option' | 'argument'): any {
try {
return schema.parse(data);
} catch (e) {
throw new Error((e as zodType.ZodError).issues.map(issue => {
const keys: string[] = (issue as any).keys || [''];
const props = keys.map(key => [...issue.path, key].filter(Boolean).join('.'));
return props.map(prop => {
const label = type === 'option' ? `'--${prop}' option` : `'${prop}' argument`;
switch (issue.code) {
case 'invalid_type':
return 'error: ' + label + ': ' + issue.message.toLowerCase().replace(/invalid input:/, '').trim();
case 'unrecognized_keys':
return 'error: unknown ' + label;
default:
return 'error: ' + label + ': ' + issue.message.toLowerCase();
}
});
}).flat().join('\n'));
}
}
9 changes: 3 additions & 6 deletions packages/playwright/src/mcp/terminal/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,6 @@ const drag = declareCommand({
startRef: z.string().describe('Exact source element reference from the page snapshot'),
endRef: z.string().describe('Exact target element reference from the page snapshot'),
}),
options: z.object({
headed: z.boolean().default(false).describe('Run browser in headed mode'),
}),
toolName: 'browser_drag',
toolParams: ({ startRef, endRef }) => ({ startRef, endRef }),
});
Expand Down Expand Up @@ -536,10 +533,10 @@ const config = declareCommand({
description: 'Restart session with new config, defaults to `playwright-cli.json`',
category: 'config',
options: z.object({
browser: z.string().optional().describe('browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.'),
browser: z.string().optional().describe('Browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.'),
config: z.string().optional().describe('Path to the configuration file'),
isolated: z.boolean().optional().describe('keep the browser profile in memory, do not save it to disk.'),
headed: z.boolean().optional().describe('run browser in headed mode'),
isolated: z.boolean().optional().describe('Keep the browser profile in memory, do not save it to disk.'),
headed: z.boolean().optional().describe('Run browser in headed mode'),
}),
toolName: '',
toolParams: () => ({}),
Expand Down
2 changes: 2 additions & 0 deletions packages/playwright/src/mcp/terminal/helpGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,12 @@ export function generateHelp() {
}

lines.push('\nGlobal options:');
lines.push(formatWithGap(' --browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge'));
lines.push(formatWithGap(' --config <path>', 'create a session with custom config, defaults to `playwright-cli.json`'));
lines.push(formatWithGap(' --extension', 'connect to a running browser instance using Playwright MCP Bridge extension'));
lines.push(formatWithGap(' --headed', 'create a headed session'));
lines.push(formatWithGap(' --help [command]', 'print help'));
lines.push(formatWithGap(' --isolated', 'keep the browser profile in memory, do not save it to disk'));
lines.push(formatWithGap(' --session', 'run command in the scope of a specific session'));
lines.push(formatWithGap(' --version', 'print version'));

Expand Down
2 changes: 2 additions & 0 deletions packages/playwright/src/mcp/terminal/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,8 @@ class SessionManager {
this.sessions.set(sessionName, session);
}

for (const globalOption of ['browser', 'config', 'daemonVersion', 'extension', 'headed', 'help', 'isolated', 'session', 'version'])
delete args[globalOption];
const result = await session.run(args);
console.log(result.text);
session.close();
Expand Down
2 changes: 1 addition & 1 deletion tests/library/tracing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@ test('should not hang for clicks that open dialogs', async ({ context, page }) =
await context.tracing.start({ screenshots: true, snapshots: true });
const dialogPromise = page.waitForEvent('dialog');
await page.setContent(`<div onclick='window.alert(123)'>Click me</div>`);
await page.click('div', { timeout: 2000 }).catch(() => {});
await page.click('div', { timeout: 3500 }).catch(() => {});
const dialog = await dialogPromise;
await dialog.dismiss();
await context.tracing.stop();
Expand Down
Loading
Loading