Skip to content

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

chore: experimental test mcp (#37117)

Pavel Feldmane0adf78b3651
diff --git a/package-lock.json b/package-lock.json
index 4d1c0cbc0c..39fa270d43 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1402,10 +1402,6 @@
"resolved": "packages/playwright-test",
"link": true
},
- "node_modules/@playwright/test-runner-mcp": {
- "resolved": "packages/playwright-test-mcp",
- "link": true
- },
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.40.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.40.1.tgz",
@@ -3057,15 +3053,6 @@
"node": ">=0.1.90"
}
},
- "node_modules/commander": {
- "version": "13.1.0",
- "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz",
- "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==",
- "license": "MIT",
- "engines": {
- "node": ">=18"
- }
- },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -8892,6 +8879,7 @@
"packages/playwright-test-mcp": {
"name": "@playwright/test-runner-mcp",
"version": "0.0.1",
+ "extraneous": true,
"license": "Apache-2.0",
"dependencies": {
"commander": "^13.1.0",
diff --git a/packages/playwright-test-mcp/README.md b/packages/playwright-test-mcp/README.md
deleted file mode 100644
index a3c65d33b8..0000000000
--- a/packages/playwright-test-mcp/README.md
+++ /dev/null
@@ -1 +0,0 @@
-# 🎭 Experimental
diff --git a/packages/playwright-test-mcp/cli.js b/packages/playwright-test-mcp/cli.js
deleted file mode 100755
index 8a49330f8f..0000000000
--- a/packages/playwright-test-mcp/cli.js
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/env node
-/**
- * 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.
- */
-
-const { program } = require('./lib/program');
-program.parse(process.argv);
-
diff --git a/packages/playwright-test-mcp/package.json b/packages/playwright-test-mcp/package.json
deleted file mode 100644
index b87d2b60c1..0000000000
--- a/packages/playwright-test-mcp/package.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "name": "@playwright/test-runner-mcp",
- "version": "0.0.1",
- "private": true,
- "description": "Experimental MCP server for Playwright Test",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/microsoft/playwright.git"
- },
- "homepage": "https://playwright.dev",
- "engines": {
- "node": ">=18"
- },
- "author": {
- "name": "Microsoft Corporation"
- },
- "license": "Apache-2.0",
- "exports": {
- ".": {
- "types": "./index.d.ts",
- "import": "./index.mjs",
- "require": "./index.js",
- "default": "./index.js"
- },
- "./cli": "./cli.js",
- "./package.json": "./package.json",
- "./reporter": "./reporter.js"
- },
- "bin": {
- "mcp-server-playwright-test": "cli.js"
- },
- "scripts": {},
- "dependencies": {
- "commander": "^13.1.0",
- "playwright": "1.56.0-next",
- "playwright-core": "1.56.0-next"
- }
-}
diff --git a/packages/playwright/bundles/mcp/src/mcpBundleImpl.ts b/packages/playwright/bundles/mcp/src/mcpBundleImpl.ts
index 782b3ac8b8..1df3787d47 100644
--- a/packages/playwright/bundles/mcp/src/mcpBundleImpl.ts
+++ b/packages/playwright/bundles/mcp/src/mcpBundleImpl.ts
@@ -19,6 +19,7 @@ export { Server } from '@modelcontextprotocol/sdk/server/index.js';
export { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
export { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
export { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
+export { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
export { CallToolRequestSchema, ListRootsRequestSchema, ListToolsRequestSchema, PingRequestSchema } from '@modelcontextprotocol/sdk/types.js';
export { z } from 'zod';
export { zodToJsonSchema } from 'zod-to-json-schema';
diff --git a/packages/playwright/package.json b/packages/playwright/package.json
index d4379d66e4..6e2183c72b 100644
--- a/packages/playwright/package.json
+++ b/packages/playwright/package.json
@@ -21,7 +21,7 @@
"./package.json": "./package.json",
"./lib/common/configLoader": "./lib/common/configLoader.js",
"./lib/fsWatcher": "./lib/fsWatcher.js",
- "./lib/mcp": "./lib/mcp/exports.js",
+ "./lib/mcp/sdk/exports": "./lib/mcp/sdk/exports.js",
"./lib/program": "./lib/program.js",
"./lib/reporters/base": "./lib/reporters/base.js",
"./lib/reporters/list": "./lib/reporters/list.js",
diff --git a/packages/playwright/src/DEPS.list b/packages/playwright/src/DEPS.list
index e9b4b2f493..b667396ff3 100644
--- a/packages/playwright/src/DEPS.list
+++ b/packages/playwright/src/DEPS.list
@@ -10,6 +10,9 @@ common/
@testIsomorphic/**
./prompt.ts
./worker/testTracing.ts
+./mcp/browser/
+./mcp/sdk/
+./transform/babelBundle.ts
[internalsForTest.ts]
**
diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.ts
index 9277f03632..ef94853fc0 100644
--- a/packages/playwright/src/index.ts
+++ b/packages/playwright/src/index.ts
@@ -22,8 +22,12 @@ import { setBoxedStackPrefixes, createGuid, currentZone, debugMode, jsonStringif
import { currentTestInfo } from './common/globals';
import { rootTestType } from './common/testType';
+import { BrowserBackend } from './mcp/browser/backend';
+import { runOnPauseBackendLoop } from './mcp/sdk/mdb';
+import { codeFrameColumns } from './transform/babelBundle';
+import { stripAnsiEscapes } from './util';
-import type { Fixtures, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, ScreenshotMode, TestInfo, TestType, VideoMode } from '../types/test';
+import type { Fixtures, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, ScreenshotMode, TestInfo, TestType, VideoMode, Location } from '../types/test';
import type { ContextReuseMode } from './common/config';
import type { TestInfoImpl, TestStepInternal } from './worker/testInfo';
import type { ClientInstrumentationListener } from '../../playwright-core/src/client/clientInstrumentation';
@@ -236,7 +240,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
(testInfo as TestInfoImpl)._setDebugMode();
playwright._defaultContextOptions = _combinedContextOptions;
- playwright._defaultContextTimeout = actionTimeout || 0;
+ playwright._defaultContextTimeout = process.env.PLAYWRIGHT_TEST_DEBUGGER_MCP ? 5000 : actionTimeout || 0;
playwright._defaultContextNavigationTimeout = navigationTimeout || 0;
await use();
playwright._defaultContextOptions = undefined;
@@ -287,9 +291,21 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
tracingGroupSteps.push(step);
},
onApiCallRecovery: (data, error, recoveryHandlers) => {
- const step = data.userData as TestStepInternal;
- if (step)
- recoveryHandlers.push(() => step.recoverFromStepError(error));
+ if (!process.env.PLAYWRIGHT_TEST_DEBUGGER_MCP)
+ return;
+
+ const step = data.userData;
+ if (!step)
+ return;
+
+ const code = createErrorCodeframe(error.message, step.location);
+
+ recoveryHandlers.push(async () => {
+ const [context] = playwright._allContexts();
+ const introMessage = `Paused on error:\n\n${stripAnsiEscapes(code)}\n\nTry recovering from the error prior to continuing.`;
+ await runOnPauseBackendLoop(process.env.PLAYWRIGHT_TEST_DEBUGGER_MCP!, new BrowserBackend(context), introMessage);
+ return { status: 'recovered' };
+ });
},
onApiCallEnd: data => {
// "tracing.group" step will end later, when "tracing.groupEnd" finishes.
@@ -785,3 +801,29 @@ export const test = _baseTest.extend<TestFixtures, WorkerFixtures>(playwrightFix
export { defineConfig } from './common/configLoader';
export { mergeTests } from './common/testType';
export { mergeExpects } from './matchers/expect';
+
+
+function createErrorCodeframe(message: string, location: Location) {
+ let source: string;
+ try {
+ source = fs.readFileSync(location.file, 'utf-8') + '\n//';
+ } catch (e) {
+ return '';
+ }
+
+ return codeFrameColumns(
+ source,
+ {
+ start: {
+ line: location.line,
+ column: location.column,
+ },
+ },
+ {
+ highlightCode: true,
+ linesAbove: 5,
+ linesBelow: 5,
+ message: message.split('\n')[0] || undefined,
+ }
+ );
+}
diff --git a/packages/playwright/src/mcp/browser/DEPS.list b/packages/playwright/src/mcp/browser/DEPS.list
new file mode 100644
index 0000000000..a9266a844f
--- /dev/null
+++ b/packages/playwright/src/mcp/browser/DEPS.list
@@ -0,0 +1,2 @@
+[*]
+../sdk/
diff --git a/packages/playwright/src/mcp/browser/backend.ts b/packages/playwright/src/mcp/browser/backend.ts
new file mode 100644
index 0000000000..5fe672cec2
--- /dev/null
+++ b/packages/playwright/src/mcp/browser/backend.ts
@@ -0,0 +1,65 @@
+/**
+ * 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 mcp from '../sdk/exports';
+import * as mcpBundle from '../sdk/bundle';
+import { snapshot, pickLocator, evaluate } from './tools';
+import { defineToolSchema } from '../sdk/exports';
+
+import type { Tool } from './tool';
+import type * as playwright from '../../../index';
+import type { ServerBackendOnPause } from '../sdk/mdb';
+
+export class BrowserBackend implements ServerBackendOnPause {
+ readonly name = 'Playwright';
+ readonly version = '0.0.1';
+ private _tools: Tool<any>[] = [snapshot, pickLocator, evaluate];
+ private _context: playwright.BrowserContext;
+
+ constructor(context: playwright.BrowserContext) {
+ this._context = context;
+ }
+
+ async initialize() {
+ }
+
+ async listTools(): Promise<mcp.Tool[]> {
+ return [...this._tools.map(tool => mcp.toMcpTool(tool.schema)), mcp.toMcpTool(doneToolSchema)];
+ }
+
+ async callTool(name: string, args: mcp.CallToolRequest['params']['arguments']): Promise<mcp.CallToolResult> {
+ if (name === 'done') {
+ (this as ServerBackendOnPause).requestSelfDestruct?.();
+ return {
+ content: [{ type: 'text', text: 'Done' }],
+ };
+ }
+
+ const tool = this._tools.find(tool => tool.schema.name === name);
+ if (!tool)
+ throw new Error(`Tool not found: ${name}. Available tools: ${this._tools.map(tool => tool.schema.name).join(', ')}`);
+ const parsedArguments = tool.schema.inputSchema.parse(args || {});
+ return await tool.handle(this._context, parsedArguments);
+ }
+}
+
+const doneToolSchema = defineToolSchema({
+ name: 'done',
+ title: 'Done',
+ description: 'Done',
+ inputSchema: mcpBundle.z.object({}),
+ type: 'destructive',
+});
diff --git a/packages/playwright-test-mcp/src/context.ts b/packages/playwright/src/mcp/browser/tool.ts
similarity index 59%
rename from packages/playwright-test-mcp/src/context.ts
rename to packages/playwright/src/mcp/browser/tool.ts
index aa20aac081..1291ddc97c 100644
--- a/packages/playwright-test-mcp/src/context.ts
+++ b/packages/playwright/src/mcp/browser/tool.ts
@@ -14,17 +14,15 @@
* limitations under the License.
*/
-import { TestRunner } from 'playwright/lib/runner/testRunner';
+import type { z } from 'zod';
+import type * as mcp from '../sdk/exports';
+import type * as playwright from '../../../index';
-import type { ConfigLocation } from 'playwright/lib/common/config';
+export type Tool<Input extends z.Schema = z.Schema> = {
+ schema: mcp.ToolSchema<Input>;
+ handle: (context: playwright.BrowserContext, params: z.output<Input>) => Promise<mcp.CallToolResult>;
+};
-export class Context {
- readonly testRunner: TestRunner;
-
- constructor(configLocation: ConfigLocation) {
- this.testRunner = new TestRunner(configLocation, {});
- }
-
- async close() {
- }
+export function defineTool<Input extends z.Schema>(tool: Tool<Input>): Tool<Input> {
+ return tool;
}
diff --git a/packages/playwright/src/mcp/browser/tools.ts b/packages/playwright/src/mcp/browser/tools.ts
new file mode 100644
index 0000000000..65a6f377a1
--- /dev/null
+++ b/packages/playwright/src/mcp/browser/tools.ts
@@ -0,0 +1,137 @@
+/**
+ * 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 { asLocator } from 'playwright-core/lib/utils';
+
+import { defineTool } from './tool.js';
+import * as mcp from '../sdk/bundle';
+
+import type * as playwright from '../../../index';
+import type z from 'zod';
+
+type PageEx = playwright.Page & {
+ _snapshotForAI: () => Promise<string>;
+};
+
+export const snapshot = defineTool({
+ schema: {
+ name: 'browser_snapshot',
+ title: 'Page snapshot',
+ description: 'Capture accessibility snapshot of the current page, this is better than screenshot',
+ inputSchema: mcp.z.object({}),
+ type: 'readOnly',
+ },
+
+ handle: async (context, params) => {
+ const [page] = context.pages();
+ if (!page)
+ throw new Error('No open pages available');
+
+ const snapshot = await (page as PageEx)._snapshotForAI();
+ return {
+ content: [
+ {
+ type: 'text',
+ text: snapshot,
+ },
+ ],
+ };
+ },
+});
+
+export const elementSchema = mcp.z.object({
+ element: mcp.z.string().describe('Human-readable element description used to obtain permission to interact with the element'),
+ ref: mcp.z.string().describe('Exact target element reference from the page snapshot'),
+});
+
+export const pickLocator = defineTool({
+ schema: {
+ name: 'browser_pick_locator',
+ title: 'Pick locator',
+ description: 'Pick a locator for the given element',
+ inputSchema: elementSchema,
+ type: 'readOnly',
+ },
+
+ handle: async (context, params) => {
+ const [page] = context.pages();
+ if (!page)
+ throw new Error('No open pages available');
+
+ const locator = await refLocator(page, params);
+ const locatorString = await generateLocator(locator);
+ return {
+ content: [
+ {
+ type: 'text',
+ text: locatorString,
+ },
+ ],
+ };
+ },
+});
+
+
+const evaluateSchema = mcp.z.object({
+ function: mcp.z.string().describe('() => { /* code */ } or (element) => { /* code */ } when element is provided'),
+ element: mcp.z.string().optional().describe('Human-readable element description used to obtain permission to interact with the element'),
+ ref: mcp.z.string().optional().describe('Exact target element reference from the page snapshot'),
+});
+
+export const evaluate = defineTool({
+ schema: {
+ name: 'browser_evaluate',
+ title: 'Evaluate JavaScript',
+ description: 'Evaluate JavaScript expression on page or element',
+ inputSchema: evaluateSchema,
+ type: 'destructive',
+ },
+
+ handle: async (context, params) => {
+ const [page] = context.pages();
+ if (!page)
+ throw new Error('No open pages available');
+
+ if (params.ref && params.element) {
+ const locator = await refLocator(page, { ref: params.ref, element: params.element });
+ const result = await locator.evaluate(params.function);
+ return {
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) || 'undefined' }],
+ };
+ }
+
+ const result = await page.evaluate(params.function);
+ return {
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) || 'undefined' }],
+ };
+ },
+});
+
+async function refLocator(page: playwright.Page, elementRef: z.output<typeof elementSchema>): Promise<playwright.Locator> {
+ const snapshot = await (page as PageEx)._snapshotForAI();
+ if (!snapshot.includes(`[ref=${elementRef.ref}]`))
+ throw new Error(`Ref ${elementRef.ref} not found in the current page snapshot. Try capturing new snapshot.`);
+ return page.locator(`aria-ref=${elementRef.ref}`).describe(elementRef.element);
+}
+
+async function generateLocator(locator: playwright.Locator): Promise<string> {
+ try {
+ const { resolvedSelector } = await (locator as any)._resolveSelector();
+ return asLocator('javascript', resolvedSelector);
+ } catch (e) {
+ throw new Error('Ref not found, likely because element was removed. Use browser_snapshot to see what elements are currently on the page.');
+ }
+}
diff --git a/packages/playwright/src/mcp/sdk/DEPS.list b/packages/playwright/src/mcp/sdk/DEPS.list
new file mode 100644
index 0000000000..e43dcb5d9f
--- /dev/null
+++ b/packages/playwright/src/mcp/sdk/DEPS.list
@@ -0,0 +1 @@
+[*]
diff --git a/packages/playwright/src/mcp/bundle.ts b/packages/playwright/src/mcp/sdk/bundle.ts
similarity index 88%
rename from packages/playwright/src/mcp/bundle.ts
rename to packages/playwright/src/mcp/sdk/bundle.ts
index 3c594f11b8..3836bc2cab 100644
--- a/packages/playwright/src/mcp/bundle.ts
+++ b/packages/playwright/src/mcp/sdk/bundle.ts
@@ -14,13 +14,14 @@
* limitations under the License.
*/
-const bundle = require('./mcpBundleImpl');
-const zodToJsonSchema: typeof import('zod-to-json-schema').zodToJsonSchema = require('./mcpBundleImpl').zodToJsonSchema;
+const bundle = require('../../mcpBundleImpl');
+const zodToJsonSchema: typeof import('zod-to-json-schema').zodToJsonSchema = bundle.zodToJsonSchema;
const Client: typeof import('@modelcontextprotocol/sdk/client/index.js').Client = bundle.Client;
const Server: typeof import('@modelcontextprotocol/sdk/server/index.js').Server = bundle.Server;
const SSEServerTransport: typeof import('@modelcontextprotocol/sdk/server/sse.js').SSEServerTransport = bundle.SSEServerTransport;
const StdioServerTransport: typeof import('@modelcontextprotocol/sdk/server/stdio.js').StdioServerTransport = bundle.StdioServerTransport;
const StreamableHTTPServerTransport: typeof import('@modelcontextprotocol/sdk/server/streamableHttp.js').StreamableHTTPServerTransport = bundle.StreamableHTTPServerTransport;
+const StreamableHTTPClientTransport: typeof import('@modelcontextprotocol/sdk/client/streamableHttp.js').StreamableHTTPClientTransport = bundle.StreamableHTTPClientTransport;
const CallToolRequestSchema: typeof import('@modelcontextprotocol/sdk/types.js').CallToolRequestSchema = bundle.CallToolRequestSchema;
const ListRootsRequestSchema: typeof import('@modelcontextprotocol/sdk/types.js').ListRootsRequestSchema = bundle.ListRootsRequestSchema;
const ListToolsRequestSchema: typeof import('@modelcontextprotocol/sdk/types.js').ListToolsRequestSchema = bundle.ListToolsRequestSchema;
@@ -35,6 +36,7 @@ export {
Server,
SSEServerTransport,
StdioServerTransport,
+ StreamableHTTPClientTransport,
StreamableHTTPServerTransport,
CallToolRequestSchema,
ListRootsRequestSchema,
diff --git a/packages/playwright/src/mcp/sdk/call.ts b/packages/playwright/src/mcp/sdk/call.ts
new file mode 100644
index 0000000000..2818867f80
--- /dev/null
+++ b/packages/playwright/src/mcp/sdk/call.ts
@@ -0,0 +1,31 @@
+/**
+ * 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 './bundle.js';
+
+import type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/sdk/types';
+
+export async function callTool(mcpUrl: string, name: string, params: CallToolRequest['params']['arguments']): Promise<CallToolResult> {
+ const transport = new mcpBundle.StreamableHTTPClientTransport(new URL(mcpUrl));
+ const client = new mcpBundle.Client({ name: 'Internal', version: '0.0.0' });
+ await client.connect(transport);
+ try {
+ return await client.callTool({ name, arguments: params }) as CallToolResult;
+ } finally {
+ await transport.terminateSession();
+ await client.close();
+ }
+}
diff --git a/packages/playwright/src/mcp/exports.ts b/packages/playwright/src/mcp/sdk/exports.ts
similarity index 78%
rename from packages/playwright/src/mcp/exports.ts
rename to packages/playwright/src/mcp/sdk/exports.ts
index 9ca581762f..12a1cb87da 100644
--- a/packages/playwright/src/mcp/exports.ts
+++ b/packages/playwright/src/mcp/sdk/exports.ts
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-export * from './inProcessTransport.js';
-export * from './proxyBackend.js';
-export * from './server.js';
-export * from './tool.js';
-export * from './transport.js';
+export * from './inProcessTransport';
+export * from './proxyBackend';
+export * from './server';
+export * from './tool';
+export * from './http';
+export * from './call';
diff --git a/packages/playwright/src/mcp/transport.ts b/packages/playwright/src/mcp/sdk/http.ts
similarity index 71%
rename from packages/playwright/src/mcp/transport.ts
rename to packages/playwright/src/mcp/sdk/http.ts
index b4161b692c..93b64bdefd 100644
--- a/packages/playwright/src/mcp/transport.ts
+++ b/packages/playwright/src/mcp/sdk/http.ts
@@ -15,32 +15,59 @@
*/
import assert from 'assert';
-import http from 'http';
import net from 'net';
+import http from 'http';
import crypto from 'crypto';
import { debug } from 'playwright-core/lib/utilsBundle';
-import * as mcpBundle from './bundle';
-import * as mcpServer from './server';
+import * as mcp from './bundle';
+import { connect } from './server';
-import type { ServerBackendFactory } from './server.js';
import type { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
import type { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
+import type { ServerBackendFactory } from './server';
-export async function start(serverBackendFactory: ServerBackendFactory, options: { host?: string; port?: number }) {
- if (options.port !== undefined) {
- const httpServer = await startHttpServer(options);
- startHttpTransport(httpServer, serverBackendFactory);
- } else {
- await startStdioTransport(serverBackendFactory);
- }
+const testDebug = debug('pw:mcp:test');
+
+export async function startHttpServer(config: { host?: string, port?: number }, abortSignal?: AbortSignal): Promise<http.Server> {
+ const { host, port } = config;
+ const httpServer = http.createServer();
+ await new Promise<void>((resolve, reject) => {
+ httpServer.on('error', reject);
+ abortSignal?.addEventListener('abort', () => {
+ httpServer.close();
+ reject(new Error('Aborted'));
+ });
+ httpServer.listen(port, host, () => {
+ resolve();
+ httpServer.removeListener('error', reject);
+ });
+ });
+ return httpServer;
}
-async function startStdioTransport(serverBackendFactory: ServerBackendFactory) {
- await mcpServer.connect(serverBackendFactory, new mcpBundle.StdioServerTransport(), false);
+export function httpAddressToString(address: string | net.AddressInfo | null): string {
+ assert(address, 'Could not bind server socket');
+ if (typeof address === 'string')
+ return address;
+ const resolvedPort = address.port;
+ let resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`;
+ if (resolvedHost === '0.0.0.0' || resolvedHost === '[::]')
+ resolvedHost = 'localhost';
+ return `http://${resolvedHost}:${resolvedPort}`;
}
-const testDebug = debug('pw:mcp:test');
+export async function installHttpTransport(httpServer: http.Server, serverBackendFactory: ServerBackendFactory) {
+ const sseSessions = new Map();
+ const streamableSessions = new Map();
+ httpServer.on('request', async (req, res) => {
+ const url = new URL(`http://localhost${req.url}`);
+ if (url.pathname.startsWith('/sse'))
+ await handleSSE(serverBackendFactory, req, res, url, sseSessions);
+ else
+ await handleStreamable(serverBackendFactory, req, res, streamableSessions);
+ });
+}
async function handleSSE(serverBackendFactory: ServerBackendFactory, req: http.IncomingMessage, res: http.ServerResponse, url: URL, sessions: Map<string, SSEServerTransport>) {
if (req.method === 'POST') {
@@ -58,10 +85,10 @@ async function handleSSE(serverBackendFactory: ServerBackendFactory, req: http.I
return await transport.handlePostMessage(req, res);
} else if (req.method === 'GET') {
- const transport = new mcpBundle.SSEServerTransport('/sse', res);
+ const transport = new mcp.SSEServerTransport('/sse', res);
sessions.set(transport.sessionId, transport);
testDebug(`create SSE session: ${transport.sessionId}`);
- await mcpServer.connect(serverBackendFactory, transport, false);
+ await connect(serverBackendFactory, transport, false);
res.on('close', () => {
testDebug(`delete SSE session: ${transport.sessionId}`);
sessions.delete(transport.sessionId);
@@ -86,11 +113,11 @@ async function handleStreamable(serverBackendFactory: ServerBackendFactory, req:
}
if (req.method === 'POST') {
- const transport = new mcpBundle.StreamableHTTPServerTransport({
+ const transport = new mcp.StreamableHTTPServerTransport({
sessionIdGenerator: () => crypto.randomUUID(),
onsessioninitialized: async sessionId => {
testDebug(`create http session: ${transport.sessionId}`);
- await mcpServer.connect(serverBackendFactory, transport, true);
+ await connect(serverBackendFactory, transport, true);
sessions.set(sessionId, transport);
}
});
@@ -109,54 +136,3 @@ async function handleStreamable(serverBackendFactory: ServerBackendFactory, req:
res.statusCode = 400;
res.end('Invalid request');
}
-
-function startHttpTransport(httpServer: http.Server, serverBackendFactory: ServerBackendFactory) {
- const sseSessions = new Map();
- const streamableSessions = new Map();
- httpServer.on('request', async (req, res) => {
- const url = new URL(`http://localhost${req.url}`);
- if (url.pathname.startsWith('/sse'))
- await handleSSE(serverBackendFactory, req, res, url, sseSessions);
- else
- await handleStreamable(serverBackendFactory, req, res, streamableSessions);
- });
- const url = httpAddressToString(httpServer.address());
- const message = [
- `Listening on ${url}`,
- 'Put this in your client config:',
- JSON.stringify({
- 'mcpServers': {
- 'playwright': {
- 'url': `${url}/mcp`
- }
- }
- }, undefined, 2),
- 'For legacy SSE transport support, you can use the /sse endpoint instead.',
- ].join('\n');
- // eslint-disable-next-line no-console
- console.error(message);
-}
-
-async function startHttpServer(config: { host?: string, port?: number }): Promise<http.Server> {
- const { host, port } = config;
- const httpServer = http.createServer();
- await new Promise<void>((resolve, reject) => {
- httpServer.on('error', reject);
- httpServer.listen(port, host, () => {
- resolve();
- httpServer.removeListener('error', reject);
- });
- });
- return httpServer;
-}
-
-function httpAddressToString(address: string | net.AddressInfo | null): string {
- assert(address, 'Could not bind server socket');
- if (typeof address === 'string')
- return address;
- const resolvedPort = address.port;
- let resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`;
- if (resolvedHost === '0.0.0.0' || resolvedHost === '[::]')
- resolvedHost = 'localhost';
- return `http://${resolvedHost}:${resolvedPort}`;
-}
diff --git a/packages/playwright/src/mcp/inProcessTransport.ts b/packages/playwright/src/mcp/sdk/inProcessTransport.ts
similarity index 100%
rename from packages/playwright/src/mcp/inProcessTransport.ts
rename to packages/playwright/src/mcp/sdk/inProcessTransport.ts
diff --git a/packages/playwright/src/mcp/sdk/mdb.ts b/packages/playwright/src/mcp/sdk/mdb.ts
new file mode 100644
index 0000000000..3216e4366b
--- /dev/null
+++ b/packages/playwright/src/mcp/sdk/mdb.ts
@@ -0,0 +1,215 @@
+/**
+ * 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 { debug } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from 'playwright-core/lib/utils';
+
+import { PingRequestSchema, z } from './bundle.js';
+import { StreamableHTTPClientTransport } from './bundle.js';
+import * as mcpBundle from './bundle.js';
+
+import { defineToolSchema } from './tool.js';
+import * as mcpServer from './server.js';
+import * as mcpHttp from './http.js';
+import { callTool } from './call.js';
+
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+
+const errorsDebug = debug('pw:mcp:errors');
+
+export class MDBBackend implements mcpServer.ServerBackend {
+ private _stack: { client: Client, toolNames: string[], resultPromise: ManualPromise<mcpServer.CallToolResult> | undefined }[] = [];
+ private _interruptPromise: ManualPromise<mcpServer.CallToolResult> | undefined;
+ private _server!: mcpServer.Server;
+
+ async initialize(server: mcpServer.Server): Promise<void> {
+ this._server = server;
+ }
+
+ async listTools(): Promise<mcpServer.Tool[]> {
+ const response = await this._client().listTools();
+ return response.tools;
+ }
+
+ async callTool(name: string, args: mcpServer.CallToolRequest['params']['arguments']): Promise<mcpServer.CallToolResult> {
+ if (name === pushToolsSchema.name)
+ return await this._pushTools(pushToolsSchema.inputSchema.parse(args || {}));
+
+ this._interruptPromise = new ManualPromise<mcpServer.CallToolResult>();
+ let [entry] = this._stack;
+
+ // Pop the client while the tool is not found.
+ while (entry && !entry.toolNames.includes(name)) {
+ this._stack.shift();
+ await entry.client.close();
+ entry = this._stack[0];
+ }
+
+ const resultPromise = new ManualPromise<mcpServer.CallToolResult>();
+ entry.resultPromise = resultPromise;
+
+ this._client().callTool({
+ name,
+ arguments: args,
+ }).then(result => {
+ resultPromise.resolve(result as mcpServer.CallToolResult);
+ }).catch(e => {
+ if (this._stack.length < 2)
+ throw e;
+ this._stack.shift();
+ const prevEntry = this._stack[0];
+ void prevEntry.resultPromise!.then(result => resultPromise.resolve(result));
+ });
+ return await Promise.race([this._interruptPromise, resultPromise]);
+ }
+
+ private _client(): Client {
+ const [entry] = this._stack;
+ if (!entry)
+ throw new Error('No debugging backend available');
+ return entry.client;
+ }
+
+ private async _pushTools(params: { mcpUrl: string, introMessage?: string }): Promise<mcpServer.CallToolResult> {
+ const client = new mcpBundle.Client({ name: 'Internal client', version: '0.0.0' });
+ client.setRequestHandler(PingRequestSchema, () => ({}));
+ const transport = new StreamableHTTPClientTransport(new URL(params.mcpUrl));
+ await client.connect(transport);
+
+ this._interruptPromise?.resolve({
+ content: [{
+ type: 'text',
+ text: params.introMessage || '',
+ }],
+ });
+ this._interruptPromise = undefined;
+
+ const { tools } = await client.listTools();
+ this._stack.unshift({ client, toolNames: tools.map(tool => tool.name), resultPromise: undefined });
+ await this._server.notification({
+ method: 'notifications/tools/list_changed',
+ });
+ return { content: [{ type: 'text', text: 'Tools pushed' }] };
+ }
+}
+
+const pushToolsSchema = defineToolSchema({
+ name: 'mdb_push_tools',
+ title: 'Push MCP tools to the tools stack',
+ description: 'Push MCP tools to the tools stack',
+ inputSchema: z.object({
+ mcpUrl: z.string(),
+ introMessage: z.string().optional(),
+ }),
+ type: 'readOnly',
+});
+
+export type ServerBackendOnPause = mcpServer.ServerBackend & {
+ requestSelfDestruct?: () => void;
+};
+
+export async function runToolsBackend(backendFactories: mcpServer.ServerBackendFactory[], options: { port: number }): Promise<string> {
+ const mdbBackend = new MDBBackend();
+ const mdbBackendFactory = {
+ name: 'Playwright MDB',
+ nameInConfig: 'playwright-mdb',
+ version: '0.0.0',
+ create: () => mdbBackend
+ };
+
+ const mdbUrl = await startAsHttp(mdbBackendFactory, options);
+
+ for (const backendFactory of backendFactories) {
+ const backendUrl = await startAsHttp(backendFactory, { port: 0 });
+ const result = await callTool(mdbUrl, pushToolsSchema.name, { mcpUrl: backendUrl });
+ if (result.isError)
+ errorsDebug('Failed to push tools', result.content);
+ }
+ return mdbUrl;
+}
+
+export async function runOnPauseBackendLoop(mdbUrl: string, backend: ServerBackendOnPause, introMessage: string) {
+ const wrappedBackend = new OnceTimeServerBackendWrapper(backend);
+
+ const factory = {
+ name: 'on-pause-backend',
+ nameInConfig: 'on-pause-backend',
+ version: '0.0.0',
+ create: () => wrappedBackend,
+ };
+
+ const httpServer = await mcpHttp.startHttpServer({ port: 0 });
+ await mcpHttp.installHttpTransport(httpServer, factory);
+ const url = mcpHttp.httpAddressToString(httpServer.address());
+
+ const client = new mcpBundle.Client({ name: 'Internal client', version: '0.0.0' });
+ client.setRequestHandler(PingRequestSchema, () => ({}));
+ const transport = new StreamableHTTPClientTransport(new URL(mdbUrl));
+ await client.connect(transport);
+
+ const pushToolsResult = await client.callTool({
+ name: pushToolsSchema.name,
+ arguments: {
+ mcpUrl: url,
+ introMessage,
+ },
+ });
+ if (pushToolsResult.isError)
+ errorsDebug('Failed to push tools', pushToolsResult.content);
+ await transport.terminateSession();
+ await client.close();
+
+ await wrappedBackend.waitForClosed();
+ httpServer.close();
+}
+
+async function startAsHttp(backendFactory: mcpServer.ServerBackendFactory, options: { port: number }) {
+ const httpServer = await mcpHttp.startHttpServer(options);
+ await mcpHttp.installHttpTransport(httpServer, backendFactory);
+ return mcpHttp.httpAddressToString(httpServer.address());
+}
+
+
+class OnceTimeServerBackendWrapper implements mcpServer.ServerBackend {
+ private _backend: ServerBackendOnPause;
+ private _selfDestructPromise = new ManualPromise<void>();
+
+ constructor(backend: ServerBackendOnPause) {
+ this._backend = backend;
+ this._backend.requestSelfDestruct = () => this._selfDestructPromise.resolve();
+ }
+
+ async initialize(server: mcpServer.Server, clientVersion: mcpServer.ClientVersion, roots: mcpServer.Root[]): Promise<void> {
+ await this._backend.initialize?.(server, clientVersion, roots);
+ }
+
+ async listTools(): Promise<mcpServer.Tool[]> {
+ return this._backend.listTools();
+ }
+
+ async callTool(name: string, args: mcpServer.CallToolRequest['params']['arguments']): Promise<mcpServer.CallToolResult> {
+ return this._backend.callTool(name, args);
+ }
+
+ serverClosed() {
+ this._backend.serverClosed?.();
+ this._selfDestructPromise.resolve();
+ }
+
+ async waitForClosed() {
+ await this._selfDestructPromise;
+ }
+}
diff --git a/packages/playwright/src/mcp/proxyBackend.ts b/packages/playwright/src/mcp/sdk/proxyBackend.ts
similarity index 80%
rename from packages/playwright/src/mcp/proxyBackend.ts
rename to packages/playwright/src/mcp/sdk/proxyBackend.ts
index 529b3bc8e4..2f7530ebcf 100644
--- a/packages/playwright/src/mcp/proxyBackend.ts
+++ b/packages/playwright/src/mcp/sdk/proxyBackend.ts
@@ -15,39 +15,33 @@
*/
import { debug } from 'playwright-core/lib/utilsBundle';
+import * as mcp from './bundle';
-import * as mcpBundle from './bundle';
-
-import type { ServerBackend, ClientVersion, Root } from './server.js';
+import type { ServerBackend, ClientVersion, Root, Server } from './server.js';
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import type { Tool, CallToolResult, CallToolRequest } from '@modelcontextprotocol/sdk/types.js';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
-const errorsDebug = debug('pw:mcp:errors');
-
export type MCPProvider = {
name: string;
description: string;
connect(): Promise<Transport>;
};
-export class ProxyBackend implements ServerBackend {
- readonly name: string;
- readonly version: string;
+const errorsDebug = debug('pw:mcp:errors');
+export class ProxyBackend implements ServerBackend {
private _mcpProviders: MCPProvider[];
private _currentClient: Client | undefined;
private _contextSwitchTool: Tool;
private _roots: Root[] = [];
- constructor(name: string, version: string, mcpProviders: MCPProvider[]) {
- this.name = name;
- this.version = version;
+ constructor(mcpProviders: MCPProvider[]) {
this._mcpProviders = mcpProviders;
this._contextSwitchTool = this._defineContextSwitchTool();
}
- async initialize(clientVersion: ClientVersion, roots: Root[]): Promise<void> {
+ async initialize(server: Server, clientVersion: ClientVersion, roots: Root[]): Promise<void> {
this._roots = roots;
await this._setCurrentClient(this._mcpProviders[0]);
}
@@ -100,8 +94,8 @@ export class ProxyBackend implements ServerBackend {
'Connect to a browser using one of the available methods:',
...this._mcpProviders.map(factory => `- "${factory.name}": ${factory.description}`),
].join('\n'),
- inputSchema: mcpBundle.zodToJsonSchema(mcpBundle.z.object({
- name: mcpBundle.z.enum(this._mcpProviders.map(factory => factory.name) as [string, ...string[]]).default(this._mcpProviders[0].name).describe('The method to use to connect to the browser'),
+ inputSchema: mcp.zodToJsonSchema(mcp.z.object({
+ name: mcp.z.enum(this._mcpProviders.map(factory => factory.name) as [string, ...string[]]).default(this._mcpProviders[0].name).describe('The method to use to connect to the browser'),
}), { strictUnions: true }) as Tool['inputSchema'],
annotations: {
title: 'Connect to a browser context',
@@ -115,14 +109,14 @@ export class ProxyBackend implements ServerBackend {
await this._currentClient?.close();
this._currentClient = undefined;
- const client = new mcpBundle.Client({ name: this.name, version: this.version });
+ const client = new mcp.Client({ name: 'Playwright MCP Proxy', version: '0.0.0' });
client.registerCapabilities({
roots: {
listRoots: true,
},
});
- client.setRequestHandler(mcpBundle.ListRootsRequestSchema, () => ({ roots: this._roots }));
- client.setRequestHandler(mcpBundle.PingRequestSchema, () => ({}));
+ client.setRequestHandler(mcp.ListRootsRequestSchema, () => ({ roots: this._roots }));
+ client.setRequestHandler(mcp.PingRequestSchema, () => ({}));
const transport = await factory.connect();
await client.connect(transport);
diff --git a/packages/playwright/src/mcp/server.ts b/packages/playwright/src/mcp/sdk/server.ts
similarity index 61%
rename from packages/playwright/src/mcp/server.ts
rename to packages/playwright/src/mcp/sdk/server.ts
index 24a3ce17e2..b6982a0fc4 100644
--- a/packages/playwright/src/mcp/server.ts
+++ b/packages/playwright/src/mcp/sdk/server.ts
@@ -15,7 +15,10 @@
*/
import { debug } from 'playwright-core/lib/utilsBundle';
-import * as mcpBundle from './bundle';
+
+import * as mcp from './bundle';
+import { InProcessTransport } from './inProcessTransport';
+import { httpAddressToString, installHttpTransport, startHttpServer } from './http';
import type { Tool, CallToolResult, CallToolRequest, Root } from '@modelcontextprotocol/sdk/types.js';
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
@@ -28,32 +31,39 @@ const errorsDebug = debug('pw:mcp:errors');
export type ClientVersion = { name: string, version: string };
export interface ServerBackend {
- name: string;
- version: string;
- initialize?(clientVersion: ClientVersion, roots: Root[]): Promise<void>;
+ initialize?(server: Server, clientVersion: ClientVersion, roots: Root[]): Promise<void>;
listTools(): Promise<Tool[]>;
callTool(name: string, args: CallToolRequest['params']['arguments']): Promise<CallToolResult>;
serverClosed?(): void;
}
-export type ServerBackendFactory = () => ServerBackend;
+export type ServerBackendFactory = {
+ name: string;
+ nameInConfig: string;
+ version: string;
+ create: () => ServerBackend;
+};
-export async function connect(serverBackendFactory: ServerBackendFactory, transport: Transport, runHeartbeat: boolean) {
- const backend = serverBackendFactory();
- const server = createServer(backend, runHeartbeat);
+export async function connect(factory: ServerBackendFactory, transport: Transport, runHeartbeat: boolean) {
+ const server = createServer(factory.name, factory.version, factory.create(), runHeartbeat);
await server.connect(transport);
}
-export function createServer(backend: ServerBackend, runHeartbeat: boolean): Server {
- let initializedCallback = () => {};
- const initializedPromise = new Promise<void>(resolve => initializedCallback = resolve);
- const server = new mcpBundle.Server({ name: backend.name, version: backend.version }, {
+export async function wrapInProcess(backend: ServerBackend): Promise<Transport> {
+ const server = createServer('Internal', '0.0.0', backend, false);
+ return new InProcessTransport(server);
+}
+
+export function createServer(name: string, version: string, backend: ServerBackend, runHeartbeat: boolean): Server {
+ let initializedPromiseResolve = () => {};
+ const initializedPromise = new Promise<void>(resolve => initializedPromiseResolve = resolve);
+ const server = new mcp.Server({ name, version }, {
capabilities: {
tools: {},
}
});
- server.setRequestHandler(mcpBundle.ListToolsRequestSchema, async () => {
+ server.setRequestHandler(mcp.ListToolsRequestSchema, async () => {
serverDebug('listTools');
await initializedPromise;
const tools = await backend.listTools();
@@ -61,7 +71,7 @@ export function createServer(backend: ServerBackend, runHeartbeat: boolean): Ser
});
let heartbeatRunning = false;
- server.setRequestHandler(mcpBundle.CallToolRequestSchema, async request => {
+ server.setRequestHandler(mcp.CallToolRequestSchema, async request => {
serverDebug('callTool', request);
await initializedPromise;
@@ -88,8 +98,8 @@ export function createServer(backend: ServerBackend, runHeartbeat: boolean): Ser
clientRoots = roots;
}
const clientVersion = server.getClientVersion() ?? { name: 'unknown', version: 'unknown' };
- await backend.initialize?.(clientVersion, clientRoots);
- initializedCallback();
+ await backend.initialize?.(server, clientVersion, clientRoots);
+ initializedPromiseResolve();
} catch (e) {
errorsDebug(e);
}
@@ -120,3 +130,27 @@ function addServerListener(server: Server, event: 'close' | 'initialized', liste
listener();
};
}
+
+export async function start(serverBackendFactory: ServerBackendFactory, options: { host?: string; port?: number }) {
+ if (options.port === undefined) {
+ await connect(serverBackendFactory, new mcp.StdioServerTransport(), false);
+ return;
+ }
+
+ const httpServer = await startHttpServer(options);
+ await installHttpTransport(httpServer, serverBackendFactory);
+ const url = httpAddressToString(httpServer.address());
+
+ const mcpConfig: any = { mcpServers: { } };
+ mcpConfig.mcpServers[serverBackendFactory.nameInConfig] = {
+ url: `${url}/mcp`
+ };
+ const message = [
+ `Listening on ${url}`,
+ 'Put this in your client config:',
+ JSON.stringify(mcpConfig, undefined, 2),
+ 'For legacy SSE transport support, you can use the /sse endpoint instead.',
+ ].join('\n');
+ // eslint-disable-next-line no-console
+ console.error(message);
+}
diff --git a/packages/playwright/src/mcp/tool.ts b/packages/playwright/src/mcp/sdk/tool.ts
similarity index 85%
rename from packages/playwright/src/mcp/tool.ts
rename to packages/playwright/src/mcp/sdk/tool.ts
index 78e39a9a30..450170bab3 100644
--- a/packages/playwright/src/mcp/tool.ts
+++ b/packages/playwright/src/mcp/sdk/tool.ts
@@ -14,17 +14,17 @@
* limitations under the License.
*/
-import { zodToJsonSchema } from './bundle';
+import { zodToJsonSchema } from './bundle.js';
import type { z } from 'zod';
-import type * as mcpServer from './server';
+import type * as mcpServer from './server.js';
export type ToolSchema<Input extends z.Schema> = {
name: string;
title: string;
description: string;
- type: 'readOnly' | 'destructive';
inputSchema: Input;
+ type: 'readOnly' | 'destructive';
};
export function toMcpTool(tool: ToolSchema<any>): mcpServer.Tool {
@@ -40,3 +40,7 @@ export function toMcpTool(tool: ToolSchema<any>): mcpServer.Tool {
},
};
}
+
+export function defineToolSchema<Input extends z.Schema>(tool: ToolSchema<Input>): ToolSchema<Input> {
+ return tool;
+}
diff --git a/packages/playwright/src/mcp/test/DEPS.list b/packages/playwright/src/mcp/test/DEPS.list
new file mode 100644
index 0000000000..a24a81a08e
--- /dev/null
+++ b/packages/playwright/src/mcp/test/DEPS.list
@@ -0,0 +1,12 @@
+[*]
+../sdk/
+../../reporters
+../../runner
+../../transform
+../../util
+../../common
+../../util.ts
+
+
+[backend.ts]
+../browser/tools.ts
diff --git a/packages/playwright-test-mcp/src/testServerBackend.ts b/packages/playwright/src/mcp/test/backend.ts
similarity index 70%
rename from packages/playwright-test-mcp/src/testServerBackend.ts
rename to packages/playwright/src/mcp/test/backend.ts
index c3a8c5fe16..3efa3f0274 100644
--- a/packages/playwright-test-mcp/src/testServerBackend.ts
+++ b/packages/playwright/src/mcp/test/backend.ts
@@ -14,14 +14,16 @@
* limitations under the License.
*/
-import * as mcp from 'playwright/src/mcp/exports';
+import * as mcp from '../sdk/exports.js';
import { Context } from './context';
-import { listTests } from './tools/listTests';
-import { runTests } from './tools/runTests';
+import { listTests } from './listTests';
+import { runTests } from './runTests';
+import { snapshot, pickLocator, evaluate } from '../browser/tools';
-import type { ConfigLocation } from 'playwright/lib/common/config';
+import type { ConfigLocation } from '../../common/config';
import type { Tool } from './tool';
+
export class TestServerBackend implements mcp.ServerBackend {
readonly name = 'Playwright';
readonly version = '0.0.1';
@@ -32,15 +34,19 @@ export class TestServerBackend implements mcp.ServerBackend {
this._context = new Context(resolvedLocation);
}
- async initialize() {
- }
-
async listTools(): Promise<mcp.Tool[]> {
- return this._tools.map(tool => mcp.toMcpTool(tool.schema));
+ return [
+ ...this._tools.map(tool => mcp.toMcpTool(tool.schema)),
+ mcp.toMcpTool(snapshot.schema),
+ mcp.toMcpTool(pickLocator.schema),
+ mcp.toMcpTool(evaluate.schema),
+ ];
}
async callTool(name: string, args: mcp.CallToolRequest['params']['arguments']): Promise<mcp.CallToolResult> {
- const tool = this._tools.find(tool => tool.schema.name === name)!;
+ const tool = this._tools.find(tool => tool.schema.name === name);
+ if (!tool)
+ throw new Error(`Tool not found: ${name}. Available tools: ${this._tools.map(tool => tool.schema.name).join(', ')}`);
const parsedArguments = tool.schema.inputSchema.parse(args || {});
return await tool.handle(this._context!, parsedArguments);
}
diff --git a/packages/playwright/src/mcp/test/context.ts b/packages/playwright/src/mcp/test/context.ts
new file mode 100644
index 0000000000..fada1fb68d
--- /dev/null
+++ b/packages/playwright/src/mcp/test/context.ts
@@ -0,0 +1,40 @@
+/**
+ * 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 { TestRunner } from '../../runner/testRunner';
+
+import type { ConfigLocation } from '../../common/config';
+
+export class Context {
+ private _testRunner: TestRunner | undefined;
+ readonly configLocation: ConfigLocation;
+
+ constructor(configLocation: ConfigLocation) {
+ this.configLocation = configLocation;
+ }
+
+ async createTestRunner(): Promise<TestRunner> {
+ if (this._testRunner)
+ await this._testRunner.stopTests();
+ const testRunner = new TestRunner(this.configLocation, {});
+ await testRunner.initialize({});
+ this._testRunner = testRunner;
+ return testRunner;
+ }
+
+ async close() {
+ }
+}
diff --git a/packages/playwright-test-mcp/src/tools/listTests.ts b/packages/playwright/src/mcp/test/listTests.ts
similarity index 92%
rename from packages/playwright-test-mcp/src/tools/listTests.ts
rename to packages/playwright/src/mcp/test/listTests.ts
index 1ebe85de60..ab204ea914 100644
--- a/packages/playwright-test-mcp/src/tools/listTests.ts
+++ b/packages/playwright/src/mcp/test/listTests.ts
@@ -15,8 +15,9 @@
*/
import path from 'path';
-import { z } from 'zod';
-import { defineTool } from '../tool.js';
+
+import { z } from '../sdk/bundle';
+import { defineTool } from './tool.js';
import type * as reporterTypes from 'playwright/types/testReporter';
@@ -31,7 +32,8 @@ export const listTests = defineTool({
handle: async (context, params) => {
const reporter = new ListModeReporter();
- await context.testRunner.listTests(reporter, {});
+ const testRunner = await context.createTestRunner();
+ await testRunner.listTests(reporter, {});
if (reporter.hasErrors())
throw new Error(reporter.content());
diff --git a/packages/playwright-test-mcp/src/program.ts b/packages/playwright/src/mcp/test/program.ts
similarity index 65%
rename from packages/playwright-test-mcp/src/program.ts
rename to packages/playwright/src/mcp/test/program.ts
index 763eb5aa24..0d5d0ea48f 100644
--- a/packages/playwright-test-mcp/src/program.ts
+++ b/packages/playwright/src/mcp/test/program.ts
@@ -15,11 +15,11 @@
*/
import path from 'path';
-import { program } from 'commander';
-import { resolveConfigLocation } from 'playwright/lib/common/configLoader';
+import { program } from 'playwright-core/lib/utilsBundle';
-import * as mcp from 'playwright/src/mcp/exports.js';
-import { TestServerBackend } from './testServerBackend.js';
+import { resolveConfigLocation } from '../../common/configLoader';
+import { TestServerBackend } from './backend.js';
+import { runToolsBackend } from '../sdk/mdb';
program
.version('Version 0.0.1')
@@ -31,8 +31,16 @@ program
const resolvedLocation = resolveConfigLocation(options.config);
// eslint-disable-next-line no-console
console.error('Test config: ', path.relative(process.cwd(), resolvedLocation.resolvedConfigFile ?? resolvedLocation.configDir));
- const serverBackendFactory = () => new TestServerBackend(resolvedLocation);
- await mcp.start(serverBackendFactory, options);
+ const backendFactory = {
+ name: 'Playwright Test',
+ nameInConfig: 'playwright-test-mcp',
+ version: '0.0.0',
+ create: () => new TestServerBackend(resolvedLocation),
+ };
+ const mdbUrl = await runToolsBackend([backendFactory], { port: 9224 });
+ process.env.PLAYWRIGHT_TEST_DEBUGGER_MCP = mdbUrl;
+ // eslint-disable-next-line no-console
+ console.error('MCP Listening on: ', mdbUrl);
});
-export { program };
+void program.parseAsync(process.argv);
diff --git a/packages/playwright-test-mcp/src/tools/runTests.ts b/packages/playwright/src/mcp/test/runTests.ts
similarity index 79%
rename from packages/playwright-test-mcp/src/tools/runTests.ts
rename to packages/playwright/src/mcp/test/runTests.ts
index 40fcf860c0..4d75c0bc6d 100644
--- a/packages/playwright-test-mcp/src/tools/runTests.ts
+++ b/packages/playwright/src/mcp/test/runTests.ts
@@ -14,13 +14,14 @@
* limitations under the License.
*/
-import { z } from 'zod';
import { noColors } from 'playwright-core/lib/utils';
-import { terminalScreen } from 'playwright/lib/reporters/base';
-import ListReporter from 'playwright/lib/reporters/list';
-import { defineTool } from '../tool';
-import { StringWriteStream } from '../streams';
+import { z } from '../sdk/bundle';
+import { terminalScreen } from '../../reporters/base';
+import ListReporter from '../../reporters/list';
+
+import { defineTool } from './tool';
+import { StringWriteStream } from './streams';
export const runTests = defineTool({
schema: {
@@ -45,13 +46,16 @@ export const runTests = defineTool({
stdout: stream as unknown as NodeJS.WriteStream,
stderr: stream as unknown as NodeJS.WriteStream,
};
- const configDir = context.testRunner.configLocation.configDir;
+ const configDir = context.configLocation.configDir;
const reporter = new ListReporter({ configDir, screen });
- const result = await context.testRunner.runTests(reporter, {
+ const testRunner = await context.createTestRunner();
+ const result = await testRunner.runTests(reporter, {
testIds: params.tests?.map(test => test.id),
+ // For automatic recovery
+ timeout: 0,
});
- const text = stream.content();
+ const text = stream.content();
return {
content: [
{ type: 'text', text },
diff --git a/packages/playwright-test-mcp/src/streams.ts b/packages/playwright/src/mcp/test/streams.ts
similarity index 100%
rename from packages/playwright-test-mcp/src/streams.ts
rename to packages/playwright/src/mcp/test/streams.ts
diff --git a/packages/playwright-test-mcp/src/tool.ts b/packages/playwright/src/mcp/test/tool.ts
similarity index 94%
rename from packages/playwright-test-mcp/src/tool.ts
rename to packages/playwright/src/mcp/test/tool.ts
index 28b05159d4..165c840b02 100644
--- a/packages/playwright-test-mcp/src/tool.ts
+++ b/packages/playwright/src/mcp/test/tool.ts
@@ -16,7 +16,7 @@
import type { z } from 'zod';
import type { Context } from './context.js';
-import type * as mcp from 'playwright/src/mcp/exports.js';
+import type * as mcp from '../sdk/exports.js';
export type Tool<Input extends z.Schema = z.Schema> = {
schema: mcp.ToolSchema<Input>;
diff --git a/packages/playwright/src/runner/testRunner.ts b/packages/playwright/src/runner/testRunner.ts
index a2c1774263..c678043b2b 100644
--- a/packages/playwright/src/runner/testRunner.ts
+++ b/packages/playwright/src/runner/testRunner.ts
@@ -64,6 +64,7 @@ export type ListTestsParams = {
};
export type RunTestsParams = {
+ timeout?: number;
locations?: string[];
grep?: string;
grepInvert?: string;
@@ -301,6 +302,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
...this._configCLIOverrides,
repeatEach: 1,
retries: 0,
+ timeout: params.timeout,
preserveOutputDir: true,
reporter: params.reporters ? params.reporters.map(r => [r]) : undefined,
use: {
diff --git a/utils/workspace.js b/utils/workspace.js
index a03b62f52f..5331dc3335 100755
--- a/utils/workspace.js
+++ b/utils/workspace.js
@@ -219,11 +219,6 @@ const workspace = new Workspace(ROOT_PATH, [
path: path.join(ROOT_PATH, 'packages', 'playwright-ct-vue'),
files: ['LICENSE'],
}),
- new PWPackage({
- name: '@playwright/test-runner-mcp',
- path: path.join(ROOT_PATH, 'packages', 'playwright-test-mcp'),
- files: ['LICENSE'],
- }),
]);
if (require.main === module) {