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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ npx mcp-accessibility-scanner --extension
```

Set `PLAYWRIGHT_MCP_EXTENSION_TOKEN` to the token shown by the extension to bypass the connection approval dialog.
When `--user-data-dir` contains multiple Chrome profiles, the profile with the extension installed is selected automatically, preferring Chrome's last-used profile.

### Discovering available tools (`list-tools` subcommand)

Expand Down
68 changes: 57 additions & 11 deletions src/extension/cdpRelay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
*/

import { spawn } from 'node:child_process';
import fs from 'node:fs/promises';
import http from 'node:http';
import path from 'node:path';
import debug from 'debug';
import { WebSocket, WebSocketServer } from 'ws';
import { httpAddressToString } from '../mcp/http.js';
Expand Down Expand Up @@ -96,19 +98,28 @@ export class CDPRelayServer {
debugLogger('Ensuring extension connection for MCP context');
if (abortSignal.aborted)
throw abortSignal.reason;
// Protocol v2 requires explicit tab selection; the legacy newTab hint hides its only approval controls.
if (!this._extensionConnection)
this._connectBrowser(clientInfo);
debugLogger('Waiting for incoming extension connection');
// Manual approval is intentionally unbounded; callers cancel it through the abort signal.
await Promise.race([
Promise.all([this._extensionConnectionPromise, this._handler.ready()]),
new Promise((_, reject) => abortSignal.addEventListener('abort', reject))
]);
let abortListener = () => {};
const abortPromise = new Promise<never>((_, reject) => {
abortListener = () => reject(abortSignal.reason);
abortSignal.addEventListener('abort', abortListener, { once: true });
});
try {
// Protocol v2 requires explicit tab selection; the legacy newTab hint hides its only approval controls.
if (!this._extensionConnection)
await Promise.race([this._connectBrowser(clientInfo, abortSignal), abortPromise]);
debugLogger('Waiting for incoming extension connection');
// Manual approval is intentionally unbounded; callers cancel it through the abort signal.
await Promise.race([
Promise.all([this._extensionConnectionPromise, this._handler.ready()]),
abortPromise,
]);
} finally {
abortSignal.removeEventListener('abort', abortListener);
}
debugLogger('Extension connection established');
}

private _connectBrowser(clientInfo: ClientInfo) {
private async _connectBrowser(clientInfo: ClientInfo, abortSignal: AbortSignal) {
// Need to specify "key" in the manifest.json to make the id stable when loading from file.
const url = new URL(this._connectPagePrefix);
const client = {
Expand All @@ -133,8 +144,13 @@ export class CDPRelayServer {
}

const args: string[] = [];
if (this._userDataDir)
if (this._userDataDir) {
args.push(`--user-data-dir=${this._userDataDir}`);
const profileDirectory = await findPlaywrightExtensionProfile(this._userDataDir);
Comment thread
JustasMonkev marked this conversation as resolved.
Resolved
if (profileDirectory)
args.push(`--profile-directory=${profileDirectory}`);
}
abortSignal.throwIfAborted();
args.push(href);

spawn(executablePath, args, {
Expand Down Expand Up @@ -288,6 +304,36 @@ export class CDPRelayServer {
}
}

async function findPlaywrightExtensionProfile(userDataDir: string): Promise<string | undefined> {
let profiles: string[];
try {
profiles = (await fs.readdir(userDataDir, { withFileTypes: true }))
.filter(entry => entry.isDirectory() && (entry.name === 'Default' || /^Profile \d+$/.test(entry.name)))
.map(entry => entry.name)
.sort((a, b) => a === 'Default' ? -1 : b === 'Default' ? 1 : parseInt(a.slice(8), 10) - parseInt(b.slice(8), 10));
} catch {
return;
}

try {
const localState = JSON.parse(await fs.readFile(path.join(userDataDir, 'Local State'), 'utf8'));
const lastUsed = localState?.profile?.last_used;
if (typeof lastUsed === 'string' && profiles.includes(lastUsed))
profiles = [lastUsed, ...profiles.filter(profile => profile !== lastUsed)];
} catch {
// Fall back to the deterministic profile order when Local State is unavailable.
}

for (const profile of profiles) {
try {
await fs.access(path.join(userDataDir, profile, 'Extensions', protocol.EXTENSION_ID));
return profile;
} catch {
continue;
}
}
}

type ExtensionResponse = {
id?: number;
method?: string;
Expand Down
37 changes: 18 additions & 19 deletions src/tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,26 +180,25 @@ export class Tab extends EventEmitter<TabEventsInterface> {
async navigate(url: string) {
this._clearCollectedArtifacts();

const downloadEvent = callOnPageNoTrace(this.page, page => page.waitForEvent('download').catch(logUnhandledError));
const downloadEvent = new ManualPromise<playwright.Download>();
const downloadListener = (download: playwright.Download) => downloadEvent.resolve(download);
this.page.once('download', downloadListener);
try {
await this.page.goto(url, { waitUntil: 'domcontentloaded' });
} catch (_e: unknown) {
const e = _e as Error;
const mightBeDownload =
e.message.includes('net::ERR_ABORTED') // chromium
|| e.message.includes('Download is starting'); // firefox + webkit
if (!mightBeDownload)
throw e;
// on chromium, the download event is fired *after* page.goto rejects, so we wait a lil bit
const download = await Promise.race([
downloadEvent,
new Promise(resolve => setTimeout(resolve, 3000)),
]);
if (!download)
throw e;
// Make sure other "download" listeners are notified first.
await new Promise(resolve => setTimeout(resolve, 500));
return;
try {
await this.page.goto(url, { waitUntil: 'domcontentloaded' });
} catch (_e: unknown) {
const e = _e as Error;
if (!e.message.includes('Download is starting'))
throw e;
const download = await this._withPageStateTimeout(downloadEvent, 'waiting for download').catch(() => undefined);
if (!download)
throw e;
// Make sure other "download" listeners are notified first.
await new Promise(resolve => setTimeout(resolve, 500));
return;
}
} finally {
this.page.off('download', downloadListener);
}

// Cap load event to 5 seconds, the page is operational at this point.
Expand Down
73 changes: 73 additions & 0 deletions tests/extension-protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@

import { spawn } from 'node:child_process';
import { once } from 'node:events';
import fs from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { WebSocket } from 'ws';
import { describe, expect, it, vi } from 'vitest';
import { CDPRelayServer } from '../src/extension/cdpRelay.js';
Expand Down Expand Up @@ -268,4 +271,74 @@ describe('extension protocol v2', () => {
vi.unstubAllEnvs();
}
});

it('launches the profile containing the extension', async () => {
vi.mocked(spawn).mockClear();
const userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-extension-profile-'));
await fs.mkdir(path.join(userDataDir, 'Default', 'Extensions', EXTENSION_ID), { recursive: true });
await fs.mkdir(path.join(userDataDir, 'Profile 1', 'Extensions', EXTENSION_ID), { recursive: true });
await fs.writeFile(path.join(userDataDir, 'Local State'), JSON.stringify({ profile: { last_used: 'Profile 1' } }));
const server = http.createServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const relay = new CDPRelayServer(server, 'chrome', userDataDir, '/tmp/chrome');
let extension: WebSocket | undefined;
try {
const connecting = relay.ensureExtensionConnectionForMCPContext(
{ name: 'test-client', version: '1.0.0' },
new AbortController().signal,
undefined,
);
await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
expect(vi.mocked(spawn).mock.calls[0][1]).toContain('--profile-directory=Profile 1');

extension = new WebSocket(relay.extensionEndpoint());
await once(extension, 'open');
extension.send(JSON.stringify({ method: 'extension.initialized', params: [] }));
await expect(connecting).resolves.toBeUndefined();
} finally {
extension?.close();
relay.stop();
await new Promise<void>(resolve => server.close(() => resolve()));
await fs.rm(userDataDir, { recursive: true });
}
});

it('does not launch Chrome when cancelled during profile discovery', async () => {
vi.mocked(spawn).mockClear();
let finishScan!: () => void;
const scan = new Promise<void>(resolve => finishScan = resolve);
const readdir = vi.spyOn(fs, 'readdir').mockImplementationOnce(async () => {
await scan;
return [] as any;
});
const server = http.createServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const relay = new CDPRelayServer(server, 'chrome', '/tmp/profile', '/tmp/chrome');
try {
const controller = new AbortController();
const connecting = relay.ensureExtensionConnectionForMCPContext(
{ name: 'test-client', version: '1.0.0' },
controller.signal,
undefined,
);
await vi.waitFor(() => expect(readdir).toHaveBeenCalled());
controller.abort(new Error('cancelled during profile discovery'));

await expect(connecting).rejects.toThrow('cancelled during profile discovery');
expect(spawn).not.toHaveBeenCalled();
finishScan();
await Promise.resolve();
expect(spawn).not.toHaveBeenCalled();
} finally {
readdir.mockRestore();
relay.stop();
await new Promise<void>(resolve => server.close(() => resolve()));
}
});
});
38 changes: 38 additions & 0 deletions tests/tab.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ describe('Tab', () => {
},
},
currentTab: vi.fn(),
outputFile: vi.fn().mockResolvedValue('/tmp/download'),
tools: [],
} as any;

Expand Down Expand Up @@ -202,6 +203,43 @@ describe('Tab', () => {
});
});

describe('navigate', () => {
it('does not wait for a download after an unrelated aborted navigation', async () => {
mockPage.goto = vi.fn().mockRejectedValue(new Error('page.goto: net::ERR_ABORTED'));
mockPage.waitForEvent = vi.fn().mockReturnValue(new Promise(() => {}));
const tab = new Tab(mockContext, mockPage as any, onPageClose);

await expect(tab.navigate('chrome://crash')).rejects.toThrow('net::ERR_ABORTED');
});

it('waits for an explicitly reported download', async () => {
const download = {
suggestedFilename: vi.fn().mockReturnValue('download.txt'),
saveAs: vi.fn().mockResolvedValue(undefined),
};
mockPage.goto = vi.fn(async () => {
mockPage.emit('download', download);
throw new Error('Download is starting');
});
const tab = new Tab(mockContext, mockPage as any, onPageClose);

await expect(tab.navigate('https://example.com/download')).resolves.toBeUndefined();
expect(download.saveAs).toHaveBeenCalledWith('/tmp/download');
expect(mockPage.listenerCount('download')).toBe(1);
});

it('rethrows when an explicitly reported download never arrives', async () => {
vi.useFakeTimers();
mockPage.goto = vi.fn().mockRejectedValue(new Error('Download is starting'));
const tab = new Tab(mockContext, mockPage as any, onPageClose);

const result = expect(tab.navigate('https://example.com/download')).rejects.toThrow('Download is starting');
await vi.advanceTimersByTimeAsync(6000);
await result;
expect(mockPage.listenerCount('download')).toBe(1);
});
});

describe('captureSnapshot', () => {
it('should capture page snapshot', async () => {
const tab = new Tab(mockContext, mockPage as any, onPageClose);
Expand Down