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(mcp): add vscode tools (#37340)
Simon Knott5c64fb24c612
diff --git a/packages/playwright/src/mcp/DEPS.list b/packages/playwright/src/mcp/DEPS.listindex 37011f7172..7634f18222 100644--- a/packages/playwright/src/mcp/DEPS.list+++ b/packages/playwright/src/mcp/DEPS.list@@ -2,6 +2,7 @@./sdk/./browser/./extension/+./vscode/[index.ts]./sdk/diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.tsindex 25dcb12c40..7e3edcb9b3 100644--- a/packages/playwright/src/mcp/program.ts+++ b/packages/playwright/src/mcp/program.ts@@ -22,6 +22,7 @@ import { contextFactory } from './browser/browserContextFactory';import { ProxyBackend } from './sdk/proxyBackend';import { BrowserServerBackend } from './browser/browserServerBackend';import { ExtensionContextFactory } from './extension/extensionContextFactory';+import { runVSCodeTools } from './vscode/host';import type { Command } from 'playwright-core/lib/utilsBundle';import type { MCPProvider } from './sdk/proxyBackend';@@ -58,6 +59,7 @@ export function decorateCommand(command: Command, version: string) {.option('--user-data-dir <path>', 'path to the user data directory. If not specified, a temporary directory will be created.').option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"').addOption(new ProgramOption('--connect-tool', 'Allow to switch between different browser connection methods.').hideHelp())+ .addOption(new ProgramOption('--vscode', 'VS Code tools.').hideHelp()).addOption(new ProgramOption('--vision', 'Legacy option, use --caps=vision instead').hideHelp()).action(async options => {setupExitWatchdog();@@ -83,6 +85,11 @@ export function decorateCommand(command: Command, version: string) {return;}+ if (options.vscode) {+ await runVSCodeTools(config);+ return;+ }+if (options.connectTool) {const providers: MCPProvider[] = [{diff --git a/packages/playwright/src/mcp/vscode/DEPS.list b/packages/playwright/src/mcp/vscode/DEPS.listnew file mode 100644index 0000000000..6e7a1c9a22--- /dev/null+++ b/packages/playwright/src/mcp/vscode/DEPS.list@@ -0,0 +1,6 @@+[*]+../sdk/+../browser/config.ts+../browser/browserServerBackend.ts+../browser/browserContextFactory.ts+../log.tsdiff --git a/packages/playwright/src/mcp/vscode/host.ts b/packages/playwright/src/mcp/vscode/host.tsnew file mode 100644index 0000000000..15332a32c6--- /dev/null+++ b/packages/playwright/src/mcp/vscode/host.ts@@ -0,0 +1,205 @@+/**+ * 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 path from 'path';++import * as mcpBundle from '../sdk/bundle';+import * as mcpServer from '../sdk/server';+import { logUnhandledError } from '../log';++import { FullConfig } from '../browser/config';+import { BrowserServerBackend } from '../browser/browserServerBackend';+import { contextFactory } from '../browser/browserContextFactory';++import type { z as zod } from 'zod';+import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';+import type { ClientVersion, ServerBackend } from '../sdk/server';+import type { Root, Tool, CallToolResult, CallToolRequest } from '@modelcontextprotocol/sdk/types.js';+import type { Browser, BrowserContext, BrowserServer } from 'playwright';+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';++const packageJSON = require('../../../package.json');++const { z, zodToJsonSchema } = mcpBundle;++const contextSwitchOptions = z.object({+ connectionString: z.string().optional().describe('The connection string to use to connect to the browser'),+ lib: z.string().optional().describe('The library to use for the connection'),+ debugController: z.boolean().optional().describe('Enable the debug controller')+});++class VSCodeProxyBackend implements ServerBackend {+ name = 'Playwright MCP Client Switcher';+ version = packageJSON.version;++ private _currentClient: Client | undefined;+ private _contextSwitchTool: Tool;+ private _roots: Root[] = [];+ private _clientVersion?: ClientVersion;+ private _context?: BrowserContext;+ private _browser?: Browser;+ private _browserServer?: BrowserServer;++ constructor(private readonly _config: FullConfig, private readonly _defaultTransportFactory: (delegate: VSCodeProxyBackend) => Promise<Transport>) {+ this._contextSwitchTool = this._defineContextSwitchTool();+ }++ async initialize(server: mcpServer.Server, clientVersion: ClientVersion, roots: Root[]): Promise<void> {+ this._clientVersion = clientVersion;+ this._roots = roots;+ const transport = await this._defaultTransportFactory(this);+ await this._setCurrentClient(transport);+ }++ async listTools(): Promise<Tool[]> {+ const response = await this._currentClient!.listTools();+ return [+ ...response.tools,+ this._contextSwitchTool,+ ];+ }++ async callTool(name: string, args: CallToolRequest['params']['arguments']): Promise<CallToolResult> {+ if (name === this._contextSwitchTool.name)+ return this._callContextSwitchTool(args as any);+ return await this._currentClient!.callTool({+ name,+ arguments: args,+ }) as CallToolResult;+ }++ serverClosed?(server: mcpServer.Server): void {+ void this._currentClient?.close().catch(logUnhandledError);+ }++ onContext(context: BrowserContext) {+ this._context = context;+ context.on('close', () => {+ this._context = undefined;+ });+ }++ private async _getDebugControllerURL() {+ if (!this._context)+ return;++ const browser = this._context.browser() as any;+ if (!browser || !browser._launchServer)+ return;++ if (this._browser !== browser)+ this._browserServer = undefined;++ if (!this._browserServer)+ this._browserServer = await browser._launchServer({ _debugController: true }) as BrowserServer;++ const url = new URL(this._browserServer.wsEndpoint());+ url.searchParams.set('debug-controller', '1');+ return url.toString();+ }++ private async _callContextSwitchTool(params: zod.infer<typeof contextSwitchOptions>): Promise<CallToolResult> {+ if (params.debugController) {+ const url = await this._getDebugControllerURL();+ const lines = [`### Result`];+ if (url) {+ lines.push(`URL: ${url}`);+ lines.push(`Version: ${packageJSON.version}`);+ } else {+ lines.push(`No open browsers.`);+ }+ return { content: [{ type: 'text', text: lines.join('\n') }] };+ }++ if (!params.connectionString || !params.lib) {+ const transport = await this._defaultTransportFactory(this);+ await this._setCurrentClient(transport);+ return {+ content: [{ type: 'text', text: '### Result\nSuccessfully disconnected.\n' }],+ };+ }++ await this._setCurrentClient(+ new mcpBundle.StdioClientTransport({+ command: process.execPath,+ cwd: process.cwd(),+ args: [+ path.join(__dirname, 'main.js'),+ JSON.stringify(this._config),+ params.connectionString,+ params.lib,+ ],+ })+ );+ return {+ content: [{ type: 'text', text: '### Result\nSuccessfully connected.\n' }],+ };+ }++ private _defineContextSwitchTool(): Tool {+ return {+ name: 'browser_connect',+ description: 'Do not call, this tool is used in the integration with the Playwright VS Code Extension and meant for programmatic usage only.',+ inputSchema: zodToJsonSchema(contextSwitchOptions, { strictUnions: true }) as Tool['inputSchema'],+ annotations: {+ title: 'Connect to a browser running in VS Code.',+ readOnlyHint: true,+ openWorldHint: false,+ },+ };+ }++ private async _setCurrentClient(transport: Transport) {+ await this._currentClient?.close();+ this._currentClient = undefined;++ const client = new mcpBundle.Client(this._clientVersion!);+ client.registerCapabilities({+ roots: {+ listRoots: true,+ },+ });+ client.setRequestHandler(mcpBundle.ListRootsRequestSchema, () => ({ roots: this._roots }));+ client.setRequestHandler(mcpBundle.PingRequestSchema, () => ({}));++ await client.connect(transport);+ this._currentClient = client;+ }+}++export async function runVSCodeTools(config: FullConfig) {+ const serverBackendFactory: mcpServer.ServerBackendFactory = {+ name: 'Playwright w/ vscode',+ nameInConfig: 'playwright-vscode',+ version: packageJSON.version,+ create: () => new VSCodeProxyBackend(+ config,+ delegate => mcpServer.wrapInProcess(+ new BrowserServerBackend(config,+ {+ async createContext(clientInfo, abortSignal, toolName) {+ const context = await contextFactory(config).createContext(clientInfo, abortSignal, toolName);+ delegate.onContext(context.browserContext);+ return context;+ },+ }+ )+ )+ )+ };+ await mcpServer.start(serverBackendFactory, config.server);+ return;+}diff --git a/packages/playwright/src/mcp/vscode/main.ts b/packages/playwright/src/mcp/vscode/main.tsnew file mode 100644index 0000000000..5eb46569a3--- /dev/null+++ b/packages/playwright/src/mcp/vscode/main.ts@@ -0,0 +1,78 @@+/**+ * 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 * as mcpBundle from '../sdk/bundle';+import * as mcpServer from '../sdk/server';+import { BrowserServerBackend } from '../browser/browserServerBackend';+import { BrowserContextFactory, ClientInfo } from '../browser/browserContextFactory';++import type { FullConfig } from '../browser/config';+import type { BrowserContext } from 'playwright-core';++class VSCodeBrowserContextFactory implements BrowserContextFactory {+ name = 'vscode';+ description = 'Connect to a browser running in the Playwright VS Code extension';++ constructor(private _config: FullConfig, private _playwright: typeof import('playwright'), private _connectionString: string) {}++ async createContext(clientInfo: ClientInfo, abortSignal: AbortSignal): Promise<{ browserContext: BrowserContext; close: () => Promise<void>; }> {+ let launchOptions: any = this._config.browser.launchOptions;+ if (this._config.browser.userDataDir) {+ launchOptions = {+ ...launchOptions,+ ...this._config.browser.contextOptions,+ userDataDir: this._config.browser.userDataDir,+ };+ }+ const connectionString = new URL(this._connectionString);+ connectionString.searchParams.set('launch-options', JSON.stringify(launchOptions));++ const browserType = this._playwright.chromium; // it could also be firefox or webkit, we just need some browser type to call `connect` on+ const browser = await browserType.connect(connectionString.toString());++ const context = browser.contexts()[0] ?? await browser.newContext(this._config.browser.contextOptions);++ return {+ browserContext: context,+ close: async () => {+ await browser.close();+ }+ };+ }+}++async function main(config: FullConfig, connectionString: string, lib: string) {+ const playwright = await import(lib).then(mod => mod.default ?? mod);+ const factory = new VSCodeBrowserContextFactory(config, playwright, connectionString);+ await mcpServer.connect(+ {+ name: 'Playwright MCP',+ nameInConfig: 'playwright-vscode',+ create: () => new BrowserServerBackend(config, factory),+ version: 'unused'+ },+ new mcpBundle.StdioServerTransport(),+ false+ );+}++void (async () => {+ await main(+ JSON.parse(process.argv[2]),+ process.argv[3],+ process.argv[4]+ );+})();diff --git a/tests/mcp/vscode.spec.ts b/tests/mcp/vscode.spec.tsnew file mode 100644index 0000000000..fc0b8187e8--- /dev/null+++ b/tests/mcp/vscode.spec.ts@@ -0,0 +1,120 @@+/**+ * 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 { test, expect } from './fixtures';+import { pathToFileURL } from 'node:url';++test('browser_connect(vscode) works', async ({ startClient, playwright, browserName }) => {+ const { client } = await startClient({+ args: ['--vscode'],+ });++ const server = await playwright[browserName].launchServer();++ expect(await client.callTool({+ name: 'browser_connect',+ arguments: {+ connectionString: server.wsEndpoint(),+ lib: pathToFileURL(require.resolve('playwright')),+ }+ })).toHaveResponse({+ result: 'Successfully connected.'+ });++ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: {+ url: 'data:text/html,foo'+ }+ })).toHaveResponse({+ pageState: expect.stringContaining('foo'),+ });++ await server.close();++ expect(await client.callTool({+ name: 'browser_snapshot',+ arguments: {}+ }), 'it actually used the server').toHaveResponse({+ isError: true,+ result: expect.stringContaining('ECONNREFUSED')+ });+});++test('browser_connect(debugController) works', async ({ startClient }) => {+ test.skip(!globalThis.WebSocket, 'WebSocket is not supported in this environment');++ const { client } = await startClient({+ args: ['--vscode'],+ });++ expect(await client.callTool({+ name: 'browser_connect',+ arguments: {+ debugController: true,+ }+ })).toHaveResponse({+ result: 'No open browsers.'+ });++ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: {+ url: 'data:text/html,foo'+ }+ })).toHaveResponse({+ pageState: expect.stringContaining('foo'),+ });++ const response = await client.callTool({+ name: 'browser_connect',+ arguments: {+ debugController: true,+ }+ });+ expect(response.content?.[0].text).toMatch(/Version: \d+\.\d+\.\d+/);+ const url = new URL(response.content?.[0].text.match(/URL: (.*)/)?.[1]);+ const messages: unknown[] = [];+ const socket = new WebSocket(url);+ socket.onmessage = event => {+ messages.push(JSON.parse(event.data));+ };+ await new Promise((resolve, reject) => {+ socket.onopen = resolve;+ socket.onerror = reject;+ });++ socket.send(JSON.stringify({+ id: '1',+ guid: 'DebugController',+ method: 'setReportStateChanged',+ params: {+ enabled: true,+ },+ metadata: {},+ }));++ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: {+ url: 'data:text/html,bar'+ }+ })).toHaveResponse({+ pageState: expect.stringContaining('bar'),+ });++ await expect.poll(() => messages).toContainEqual(expect.objectContaining({ method: 'stateChanged' }));+});