Skip to content

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

feat(mcp): allow saving trace as a command (#37323)

Pavel Feldman033d36e66510
diff --git a/packages/playwright-core/src/server/har/harTracer.ts b/packages/playwright-core/src/server/har/harTracer.ts
index dc70ad2079..601f1821e5 100644
--- a/packages/playwright-core/src/server/har/harTracer.ts
+++ b/packages/playwright-core/src/server/har/harTracer.ts
@@ -193,7 +193,7 @@ export class HarTracer {
private _onAPIRequest(event: APIRequestEvent) {
if (!this._shouldIncludeEntryWithUrl(event.url.toString()))
return;
- const harEntry = createHarEntry(event.method, event.url, undefined, this._options);
+ const harEntry = createHarEntry(undefined, event.method, event.url, undefined, this._options);
harEntry._apiRequest = true;
if (!this._options.omitCookies)
harEntry.request.cookies = event.cookies;
@@ -265,9 +265,7 @@ export class HarTracer {
return;
const pageEntry = this._createPageEntryIfNeeded(page);
- const harEntry = createHarEntry(request.method(), url, request.frame()?.guid, this._options);
- if (pageEntry)
- harEntry.pageref = pageEntry.id;
+ const harEntry = createHarEntry(pageEntry?.id, request.method(), url, request.frame()?.guid, this._options);
this._recordRequestHeadersAndCookies(harEntry, request.headers());
harEntry.request.postData = this._postDataForRequest(request, this._options.content);
if (!this._options.omitSizes)
@@ -608,10 +606,9 @@ export class HarTracer {
}
-function createHarEntry(method: string, url: URL, frameref: string | undefined, options: HarTracerOptions): har.Entry {
+function createHarEntry(pageRef: string | undefined, method: string, url: URL, frameref: string | undefined, options: HarTracerOptions): har.Entry {
const harEntry: har.Entry = {
- _frameref: options.includeTraceInfo ? frameref : undefined,
- _monotonicTime: options.includeTraceInfo ? monotonicTime() : undefined,
+ pageref: pageRef,
startedDateTime: new Date().toISOString(),
time: -1,
request: {
@@ -645,6 +642,8 @@ function createHarEntry(method: string, url: URL, frameref: string | undefined,
wait: -1,
receive: -1
},
+ _frameref: options.includeTraceInfo ? frameref : undefined,
+ _monotonicTime: options.includeTraceInfo ? monotonicTime() : undefined,
};
return harEntry;
}
diff --git a/packages/playwright/src/mcp/browser/browserContextFactory.ts b/packages/playwright/src/mcp/browser/browserContextFactory.ts
index e4320b3a1a..813e56e3ad 100644
--- a/packages/playwright/src/mcp/browser/browserContextFactory.ts
+++ b/packages/playwright/src/mcp/browser/browserContextFactory.ts
@@ -103,8 +103,11 @@ class IsolatedContextFactory extends BaseContextFactory {
protected override async _doObtainBrowser(clientInfo: ClientInfo): Promise<playwright.Browser> {
await injectCdpPort(this.config.browser);
const browserType = playwright[this.config.browser.browserName];
+ const tracesDir = await outputFile(this.config, clientInfo.rootPath, `traces`);
+ if (this.config.saveTrace)
+ await startTraceServer(this.config, tracesDir);
return browserType.launch({
- tracesDir: await startTraceServer(this.config, clientInfo.rootPath),
+ tracesDir,
...this.config.browser.launchOptions,
handleSIGINT: false,
handleSIGTERM: false,
@@ -167,7 +170,9 @@ class PersistentContextFactory implements BrowserContextFactory {
await injectCdpPort(this.config.browser);
testDebug('create browser context (persistent)');
const userDataDir = this.config.browser.userDataDir ?? await this._createUserDataDir(clientInfo.rootPath);
- const tracesDir = await startTraceServer(this.config, clientInfo.rootPath);
+ const tracesDir = await outputFile(this.config, clientInfo.rootPath, `traces`);
+ if (this.config.saveTrace)
+ await startTraceServer(this.config, tracesDir);
this._userDataDirs.add(userDataDir);
testDebug('lock user data dir', userDataDir);
@@ -233,17 +238,15 @@ async function findFreePort(): Promise<number> {
});
}
-async function startTraceServer(config: FullConfig, rootPath: string | undefined): Promise<string | undefined> {
+async function startTraceServer(config: FullConfig, tracesDir: string): Promise<string | undefined> {
if (!config.saveTrace)
- return undefined;
+ return;
- const tracesDir = await outputFile(config, rootPath, `traces-${Date.now()}`);
const server = await startTraceViewerServer();
const urlPrefix = server.urlPrefix('human-readable');
const url = urlPrefix + '/trace/index.html?trace=' + tracesDir + '/trace.json';
// eslint-disable-next-line no-console
console.error('\nTrace viewer listening on ' + url);
- return tracesDir;
}
function createHash(data: string): string {
diff --git a/packages/playwright/src/mcp/browser/context.ts b/packages/playwright/src/mcp/browser/context.ts
index a4bd590887..18b13d5682 100644
--- a/packages/playwright/src/mcp/browser/context.ts
+++ b/packages/playwright/src/mcp/browser/context.ts
@@ -27,6 +27,7 @@ import type { Tool } from './tools/tool';
import type { BrowserContextFactory, ClientInfo } from './browserContextFactory';
import type * as actions from './actions';
import type { SessionLog } from './sessionLog';
+import type { Tracing } from '../../../../playwright-core/src/client/tracing';
const testDebug = debug('pw:mcp:test');
@@ -189,6 +190,11 @@ export class Context {
}
}
+ async ensureBrowserContext(): Promise<playwright.BrowserContext> {
+ const { browserContext } = await this._ensureBrowserContext();
+ return browserContext;
+ }
+
private _ensureBrowserContext() {
if (!this._browserContextPromise) {
this._browserContextPromise = this._setupBrowserContext();
@@ -212,11 +218,11 @@ export class Context {
this._onPageCreated(page);
browserContext.on('page', page => this._onPageCreated(page));
if (this.config.saveTrace) {
- await browserContext.tracing.start({
- name: 'trace',
- screenshots: false,
+ await (browserContext.tracing as Tracing).start({
+ name: 'trace-' + Date.now(),
+ screenshots: true,
snapshots: true,
- sources: false,
+ _live: true,
});
}
return result;
diff --git a/packages/playwright/src/mcp/browser/tools.ts b/packages/playwright/src/mcp/browser/tools.ts
index b1e8059f91..408058ab99 100644
--- a/packages/playwright/src/mcp/browser/tools.ts
+++ b/packages/playwright/src/mcp/browser/tools.ts
@@ -27,8 +27,9 @@ import navigate from './tools/navigate';
import network from './tools/network';
import pdf from './tools/pdf';
import snapshot from './tools/snapshot';
-import tabs from './tools/tabs';
import screenshot from './tools/screenshot';
+import tabs from './tools/tabs';
+import tracing from './tools/tracing';
import wait from './tools/wait';
import verify from './tools/verify';
@@ -51,6 +52,7 @@ export const allTools: Tool<any>[] = [
...screenshot,
...snapshot,
...tabs,
+ ...tracing,
...wait,
...verify,
];
diff --git a/packages/playwright/src/mcp/browser/tools/tracing.ts b/packages/playwright/src/mcp/browser/tools/tracing.ts
new file mode 100644
index 0000000000..828386c40d
--- /dev/null
+++ b/packages/playwright/src/mcp/browser/tools/tracing.ts
@@ -0,0 +1,76 @@
+/**
+ * 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 '../../sdk/bundle';
+import { defineTool } from './tool';
+
+import type { Tracing } from '../../../../../playwright-core/src/client/tracing';
+
+const tracingStart = defineTool({
+ capability: 'tracing',
+
+ schema: {
+ name: 'browser_start_tracing',
+ title: 'Start tracing',
+ description: 'Start trace recording',
+ inputSchema: z.object({}),
+ type: 'readOnly',
+ },
+
+ handle: async (context, params, response) => {
+ const browserContext = await context.ensureBrowserContext();
+ const tracesDir = await context.outputFile(`traces`);
+ const name = 'trace-' + Date.now();
+ await (browserContext.tracing as Tracing).start({
+ name,
+ screenshots: true,
+ snapshots: true,
+ _live: true,
+ });
+ const traceLegend = `- Action log: ${tracesDir}/${name}.trace
+- Network log: ${tracesDir}/${name}.network
+- Resources with content by sha1: ${tracesDir}/resources`;
+
+ response.addResult(`Tracing started, saving to ${tracesDir}.\n${traceLegend}`);
+ (browserContext.tracing as any)[traceLegendSymbol] = traceLegend;
+ },
+});
+
+const tracingStop = defineTool({
+ capability: 'tracing',
+
+ schema: {
+ name: 'browser_stop_tracing',
+ title: 'Stop tracing',
+ description: 'Stop trace recording',
+ inputSchema: z.object({}),
+ type: 'readOnly',
+ },
+
+ handle: async (context, params, response) => {
+ const browserContext = await context.ensureBrowserContext();
+ await browserContext.tracing.stop();
+ const traceLegend = (browserContext.tracing as any)[traceLegendSymbol];
+ response.addResult(`Tracing stopped.\n${traceLegend}`);
+ },
+});
+
+export default [
+ tracingStart,
+ tracingStop,
+];
+
+const traceLegendSymbol = Symbol('tracesDir');
diff --git a/packages/playwright/src/mcp/config.d.ts b/packages/playwright/src/mcp/config.d.ts
index 09a999d88c..fd42445a6e 100644
--- a/packages/playwright/src/mcp/config.d.ts
+++ b/packages/playwright/src/mcp/config.d.ts
@@ -16,7 +16,7 @@
import type * as playwright from 'playwright-core';
-export type ToolCapability = 'core' | 'core-tabs' | 'core-install' | 'vision' | 'pdf' | 'verify';
+export type ToolCapability = 'core' | 'core-tabs' | 'core-install' | 'vision' | 'pdf' | 'verify' | 'tracing';
export type Config = {
/**
diff --git a/tests/mcp/trace.spec.ts b/tests/mcp/trace.spec.ts
deleted file mode 100644
index 927f23a798..0000000000
--- a/tests/mcp/trace.spec.ts
+++ /dev/null
@@ -1,37 +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 fs from 'fs';
-
-import { test, expect } from './fixtures';
-
-test('check that trace is saved', async ({ startClient, server, mcpMode }, testInfo) => {
- const outputDir = testInfo.outputPath('output');
-
- const { client } = await startClient({
- args: ['--save-trace', `--output-dir=${outputDir}`],
- });
-
- expect(await client.callTool({
- name: 'browser_navigate',
- arguments: { url: server.HELLO_WORLD },
- })).toHaveResponse({
- code: expect.stringContaining(`page.goto('http://localhost`),
- });
-
- const [file] = await fs.promises.readdir(outputDir);
- expect(file).toContain('traces');
-});
diff --git a/tests/mcp/tracing.spec.ts b/tests/mcp/tracing.spec.ts
new file mode 100644
index 0000000000..23bc94fee5
--- /dev/null
+++ b/tests/mcp/tracing.spec.ts
@@ -0,0 +1,69 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs';
+import path from 'path';
+import { test, expect } from './fixtures';
+
+test('check that trace is saved with --save-trace', async ({ startClient, server, mcpMode }, testInfo) => {
+ const outputDir = testInfo.outputPath('output');
+
+ const { client } = await startClient({
+ args: ['--save-trace', `--output-dir=${outputDir}`],
+ });
+
+ expect(await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.HELLO_WORLD },
+ })).toHaveResponse({
+ code: expect.stringContaining(`page.goto('http://localhost`),
+ });
+
+ const [file] = await fs.promises.readdir(outputDir);
+ expect(file).toContain('traces');
+});
+
+test('check that trace is saved with browser_start_tracing', async ({ startClient, server, mcpMode }, testInfo) => {
+ const outputDir = testInfo.outputPath('output');
+
+ const { client } = await startClient({ args: [`--output-dir=${outputDir}`, '--caps=tracing'] });
+
+ expect(await client.callTool({
+ name: 'browser_start_tracing',
+ })).toHaveResponse({
+ result: expect.stringContaining(`Tracing started, saving to ${outputDir}`),
+ });
+
+ expect(await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.HELLO_WORLD },
+ })).toHaveResponse({
+ code: expect.stringContaining(`page.goto('http://localhost`),
+ });
+
+ expect(await client.callTool({
+ name: 'browser_stop_tracing',
+ })).toHaveResponse({
+ result: expect.stringMatching(/trace-\d+.trace/)
+ });
+
+ const files = await fs.promises.readdir(path.join(outputDir, 'traces'));
+ expect(files).toEqual([
+ 'resources',
+ expect.stringMatching(/trace-\d+\.network/),
+ expect.stringMatching(/trace-\d+\.trace/),
+ ]);
+});