Skip to content

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

chore(mcp): make cwd a fallback to the roots at all times (#39498)

Pavel Feldman21368bb2e512
diff --git a/packages/playwright-core/src/mcp/browser/browserContextFactory.ts b/packages/playwright-core/src/mcp/browser/browserContextFactory.ts
index ecfa5d4cb3..c3c9bc6ea8 100644
--- a/packages/playwright-core/src/mcp/browser/browserContextFactory.ts
+++ b/packages/playwright-core/src/mcp/browser/browserContextFactory.ts
@@ -216,9 +216,8 @@ class PersistentContextFactory extends BaseContextFactory {
const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? registryDirectory;
const browserToken = this.config.browser.launchOptions?.channel ?? this.config.browser?.browserName;
// Hesitant putting hundreds of files into the user's workspace, so using it for hashing instead.
- const rootPath = firstRootPath(clientInfo);
- const rootPathToken = rootPath ? `-${createHash(rootPath)}` : '';
- const result = path.join(dir, `mcp-${browserToken}${rootPathToken}`);
+ const rootPathToken = createHash(firstRootPath(clientInfo));
+ const result = path.join(dir, `mcp-${browserToken}-${rootPathToken}`);
await fs.promises.mkdir(result, { recursive: true });
return result;
}
diff --git a/packages/playwright-core/src/mcp/browser/config.ts b/packages/playwright-core/src/mcp/browser/config.ts
index 2ecbf7acbd..17a5803d8e 100644
--- a/packages/playwright-core/src/mcp/browser/config.ts
+++ b/packages/playwright-core/src/mcp/browser/config.ts
@@ -379,7 +379,7 @@ export async function loadConfig(configFile: string | undefined): Promise<Config
// These methods should return resolved absolute file names.
export function workspaceDir(clientInfo: ClientInfo): string {
- return path.resolve(firstRootPath(clientInfo) ?? process.cwd());
+ return path.resolve(firstRootPath(clientInfo));
}
export async function workspaceFile(config: FullConfig, clientInfo: ClientInfo, fileName: string, perCallWorkspaceDir?: string): Promise<string> {
@@ -392,11 +392,7 @@ export async function workspaceFile(config: FullConfig, clientInfo: ClientInfo,
export function outputDir(config: FullConfig, clientInfo: ClientInfo): string {
if (config.outputDir)
return path.resolve(config.outputDir);
- const rootPath = firstRootPath(clientInfo);
- if (rootPath)
- return path.resolve(rootPath, config.skillMode ? '.playwright-cli' : '.playwright-mcp');
- const tmpDir = process.env.PW_TMPDIR_FOR_TEST ?? os.tmpdir();
- return path.resolve(tmpDir, 'playwright-mcp-output', String(clientInfo.timestamp));
+ return path.resolve(firstRootPath(clientInfo), config.skillMode ? '.playwright-cli' : '.playwright-mcp');
}
export async function outputFile(config: FullConfig, clientInfo: ClientInfo, fileName: string, options: { origin: 'code' | 'llm' }): Promise<string> {
diff --git a/packages/playwright-core/src/mcp/browser/context.ts b/packages/playwright-core/src/mcp/browser/context.ts
index f8e42a55af..2490841d2e 100644
--- a/packages/playwright-core/src/mcp/browser/context.ts
+++ b/packages/playwright-core/src/mcp/browser/context.ts
@@ -14,9 +14,7 @@
* limitations under the License.
*/
-import os from 'os';
import path from 'path';
-import { fileURLToPath } from 'url';
import { eventsHelper } from '../../client/eventEmitter';
import { debug } from '../../utilsBundle';
@@ -25,14 +23,15 @@ import { selectors } from '../../..';
import { Tab } from './tab';
import { outputFile, workspaceFile } from './config';
+import { allRootPaths, firstRootPath } from '../sdk/server';
import type * as playwright from '../../..';
import type { FullConfig } from './config';
import type { SessionLog } from './sessionLog';
import type { Tracing } from '../../client/tracing';
import type { Disposable } from '../../client/eventEmitter';
-import type { ClientInfo } from '../sdk/server';
import type { BrowserContext } from '../../client/browserContext';
+import type { ClientInfo } from '../sdk/server';
const testDebug = debug('pw:mcp:test');
@@ -280,9 +279,9 @@ export class Context {
},
});
}
- const rootPath = this.firstRootPath();
+ const rootPath = firstRootPath(this._clientInfo);
for (const initScript of this.config.browser.initScript || [])
- await browserContext.addInitScript({ path: rootPath ? path.resolve(rootPath, initScript) : initScript });
+ await browserContext.addInitScript({ path: path.resolve(rootPath, initScript) });
return browserContext;
}
@@ -294,34 +293,8 @@ export class Context {
code: `process.env['${secretName}']`,
};
}
-
- firstRootPath(): string | undefined {
- return allRootPaths(this._clientInfo)[0];
- }
}
-function allRootPaths(clientInfo: ClientInfo): string[] {
- const paths: string[] = [];
- for (const root of clientInfo.roots) {
- const url = new URL(root.uri);
- let rootPath;
- try {
- rootPath = fileURLToPath(url);
- } catch (e) {
- // Support WSL paths on Windows.
- if (e.code === 'ERR_INVALID_FILE_URL_PATH' && os.platform() === 'win32')
- rootPath = decodeURIComponent(url.pathname);
- }
- if (!rootPath)
- continue;
- paths.push(rootPath);
- }
- if (paths.length === 0)
- paths.push(process.cwd());
- return paths;
-}
-
-
function originOrHostGlob(originOrHost: string) {
// Support wildcard port patterns like "http://localhost:*" or "https://example.com:*"
const wildcardPortMatch = originOrHost.match(/^(https?:\/\/[^/:]+):\*$/);
diff --git a/packages/playwright-core/src/mcp/browser/response.ts b/packages/playwright-core/src/mcp/browser/response.ts
index 4082e40534..aef1215924 100644
--- a/packages/playwright-core/src/mcp/browser/response.ts
+++ b/packages/playwright-core/src/mcp/browser/response.ts
@@ -20,6 +20,7 @@ import path from 'path';
import { debug } from '../../utilsBundle';
import { renderModalStates, shouldIncludeMessage } from './tab';
import { scaleImageToFitMessage } from './tools/screenshot';
+import { firstRootPath } from '../sdk/server';
import type { TabHeader } from './tab';
import type { CallToolResult, ImageContent, TextContent } from '@modelcontextprotocol/sdk/types.js';
@@ -51,20 +52,18 @@ export class Response {
readonly toolName: string;
readonly toolArgs: Record<string, any>;
- private _clientWorkspace: string | undefined;
+ private _clientWorkspace: string;
private _imageResults: { data: Buffer, imageType: 'png' | 'jpeg' }[] = [];
constructor(context: Context, toolName: string, toolArgs: Record<string, any>, relativeTo?: string) {
this._context = context;
this.toolName = toolName;
this.toolArgs = toolArgs;
- this._clientWorkspace = relativeTo ?? context.firstRootPath();
+ this._clientWorkspace = relativeTo ?? firstRootPath(context.options.clientInfo);
}
private _computRelativeTo(fileName: string): string {
- if (this._clientWorkspace)
- return path.relative(this._clientWorkspace, fileName);
- return fileName;
+ return path.relative(this._clientWorkspace, fileName);
}
async resolveClientFile(template: FilenameTemplate, title: string): Promise<ResolvedFile> {
diff --git a/packages/playwright-core/src/mcp/sdk/server.ts b/packages/playwright-core/src/mcp/sdk/server.ts
index d176d29fa0..b15b66c8a7 100644
--- a/packages/playwright-core/src/mcp/sdk/server.ts
+++ b/packages/playwright-core/src/mcp/sdk/server.ts
@@ -217,31 +217,28 @@ export async function start(serverBackendFactory: ServerBackendFactory, options:
console.error(message);
}
-export function firstRootPath(clientInfo: ClientInfo): string | undefined {
- if (clientInfo.roots.length === 0)
- return undefined;
- const firstRootUri = clientInfo.roots[0]?.uri;
- const url = firstRootUri ? new URL(firstRootUri) : undefined;
- try {
- return url ? fileURLToPath(url) : undefined;
- } catch (error) {
- serverDebug(error);
- return undefined;
- }
+export function firstRootPath(clientInfo: ClientInfo): string {
+ return allRootPaths(clientInfo)[0];
}
export function allRootPaths(clientInfo: ClientInfo): string[] {
const paths: string[] = [];
for (const root of clientInfo.roots) {
+ const url = new URL(root.uri);
+ let rootPath;
try {
- const url = new URL(root.uri);
- const path = fileURLToPath(url);
- if (path)
- paths.push(path);
- } catch (error) {
- serverDebug(error);
+ rootPath = fileURLToPath(url);
+ } catch (e) {
+ // Support WSL paths on Windows.
+ if (e.code === 'ERR_INVALID_FILE_URL_PATH' && process.platform === 'win32')
+ rootPath = decodeURIComponent(url.pathname);
}
+ if (!rootPath)
+ continue;
+ paths.push(rootPath);
}
+ if (paths.length === 0)
+ paths.push(process.cwd());
return paths;
}
diff --git a/tests/mcp/tracing.spec.ts b/tests/mcp/tracing.spec.ts
index 20e7e5e03e..c693fd59ea 100644
--- a/tests/mcp/tracing.spec.ts
+++ b/tests/mcp/tracing.spec.ts
@@ -108,7 +108,6 @@ test('check that trace is saved with browser_start_tracing (no output dir)', asy
args: ['--caps=tracing'],
});
- const tmpDir = testInfo.outputPath('tmp');
expect(await client.callTool({
name: 'browser_start_tracing',
})).toHaveResponse({
@@ -128,10 +127,7 @@ test('check that trace is saved with browser_start_tracing (no output dir)', asy
result: expect.stringMatching(/trace-\d+.trace/)
});
- const folders = await fs.promises.readdir(path.join(tmpDir, 'playwright-mcp-output'));
- expect(folders.length).toBe(1);
- expect(folders[0]).toMatch(/\d+/);
- const files = await fs.promises.readdir(path.join(tmpDir, 'playwright-mcp-output', folders[0], 'traces'));
+ const files = await fs.promises.readdir(testInfo.outputPath('.playwright-mcp', 'traces'));
expect(files).toEqual([
'resources',
expect.stringMatching(/trace-\d+\.network/),