Skip to content

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

chore: use zod for mcp tools schemas (#35245)

Pavel Feldman7ce4f88a5bc9
diff --git a/package-lock.json b/package-lock.json
index 8e8d5248b2..c4c550e47a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10066,7 +10066,9 @@
"version": "1.52.0-next",
"license": "Apache-2.0",
"dependencies": {
- "playwright": "1.52.0-next"
+ "commander": "^13.1.0",
+ "playwright": "1.52.0-next",
+ "zod-to-json-schema": "^3.24.4"
},
"bin": {
"mcp": "cli.js"
@@ -10078,6 +10080,34 @@
"node": ">=18"
}
},
+ "packages/playwright-mcp/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"
+ }
+ },
+ "packages/playwright-mcp/node_modules/zod": {
+ "version": "3.24.2",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz",
+ "integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==",
+ "license": "MIT",
+ "peer": true,
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
+ "packages/playwright-mcp/node_modules/zod-to-json-schema": {
+ "version": "3.24.4",
+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.4.tgz",
+ "integrity": "sha512-0uNlcvgabyrni9Ag8Vghj21drk7+7tp7VTwwR7KxxXXc/3pbXz2PHlDgj3cICahgF1kHm4dExBFj7BXrZJXzig==",
+ "license": "ISC",
+ "peerDependencies": {
+ "zod": "^3.24.1"
+ }
+ },
"packages/playwright-test": {
"name": "@playwright/test",
"version": "1.52.0-next",
diff --git a/packages/playwright-mcp/README.md b/packages/playwright-mcp/README.md
index 7f6648cc98..be13bed892 100644
--- a/packages/playwright-mcp/README.md
+++ b/packages/playwright-mcp/README.md
@@ -5,6 +5,47 @@ It is a subject to change and will not respect semver versioning.
### Example config
+```js
+{
+ "mcpServers": {
+ "playwright": {
+ "command": "npx",
+ "args": [
+ "@playwright/mcp",
+ "--headless"
+ ]
+ }
+ }
+}
+```
+
+### Running headed browser (Browser with GUI).
+
+```js
+{
+ "mcpServers": {
+ "playwright": {
+ "command": "npx",
+ "args": [
+ "@playwright/mcp"
+ ]
+ }
+ }
+}
+```
+
+### Running headed browser on Linux
+
+When running headed browser on system w/o display or from worker processes of the IDEs,
+you can run Playwright in a client-server manner. You'll run the Playwright server
+from environment with the DISPLAY
+
+```sh
+npx playwright run-server
+```
+
+And then in MCP config, add following to the `env`:
+
```js
{
"mcpServers": {
@@ -14,18 +55,8 @@ It is a subject to change and will not respect semver versioning.
"@playwright/mcp"
],
"env": {
- /**
- * If you run this server in a headless environment
- * (Cline on Linux, etc), either set HEADLESS to 1.
- */
- "PLAYWRIGHT_HEADLESS": "1",
-
- /**
- * ...or use Playwright Client/Server mode via
- * running the Playwright Server
- * npx playwright run-server
- */
- "PLAYWRIGHT_WS_ENDPOINT": "ws://localhost:41541/"
+ // Use the endpoint from the output of the server above.
+ "PLAYWRIGHT_WS_ENDPOINT": "ws://localhost:<port>/"
}
}
}
diff --git a/packages/playwright-mcp/cli.js b/packages/playwright-mcp/cli.js
index 968fa3b4a2..95d4dbd3b0 100755
--- a/packages/playwright-mcp/cli.js
+++ b/packages/playwright-mcp/cli.js
@@ -15,4 +15,4 @@
* limitations under the License.
*/
-require('./lib/servers/snapshot');
+require('./lib/program');
diff --git a/packages/playwright-mcp/package.json b/packages/playwright-mcp/package.json
index b426c44c9f..0b9e055e0f 100644
--- a/packages/playwright-mcp/package.json
+++ b/packages/playwright-mcp/package.json
@@ -24,7 +24,9 @@
"./package.json": "./package.json"
},
"dependencies": {
- "playwright": "1.52.0-next"
+ "commander": "^13.1.0",
+ "playwright": "1.52.0-next",
+ "zod-to-json-schema": "^3.24.4"
},
"devDependencies": {
"@modelcontextprotocol/sdk": "^1.6.1"
diff --git a/packages/playwright-mcp/src/program.ts b/packages/playwright-mcp/src/program.ts
new file mode 100644
index 0000000000..fecd43c1c8
--- /dev/null
+++ b/packages/playwright-mcp/src/program.ts
@@ -0,0 +1,94 @@
+/**
+ * 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 { program } from 'commander';
+
+import { Server } from './server';
+import * as snapshot from './tools/snapshot';
+import * as common from './tools/common';
+import * as screenshot from './tools/screenshot';
+import * as allResources from './resources/resources';
+
+import type { LaunchOptions } from './server';
+import type { Tool } from './tools/tool';
+import type { Resource } from './resources/resource';
+
+const packageJSON = require('../package.json');
+
+program
+ .version('Version ' + packageJSON.version)
+ .name(packageJSON.name)
+ .option('--headless', 'Run browser in headless mode, headed by default')
+ .option('--vision', 'Run server that uses screenshots (Aria snapshots are used by default)')
+ .action(async options => {
+ const launchOptions: LaunchOptions = {
+ headless: !!options.headless,
+ };
+ const tools = options.vision ? screenshotTools : snapshotTools;
+ const server = new Server({
+ name: 'Playwright',
+ version: packageJSON.version,
+ tools,
+ resources,
+ }, launchOptions);
+ setupExitWatchdog(server);
+ await server.start();
+ });
+
+function setupExitWatchdog(server: Server) {
+ process.stdin.on('close', async () => {
+ // eslint-disable-next-line no-restricted-properties
+ setTimeout(() => process.exit(0), 15000);
+
+ await server?.stop();
+ // eslint-disable-next-line no-restricted-properties
+ process.exit(0);
+ });
+}
+
+const commonTools: Tool[] = [
+ common.pressKey,
+ common.wait,
+];
+
+const snapshotTools: Tool[] = [
+ common.navigate(true),
+ common.goBack(true),
+ common.goForward(true),
+ snapshot.snapshot,
+ snapshot.click,
+ snapshot.hover,
+ snapshot.type,
+ ...commonTools,
+];
+
+const screenshotTools: Tool[] = [
+ common.navigate(false),
+ common.goBack(false),
+ common.goForward(false),
+ screenshot.screenshot,
+ screenshot.moveMouse,
+ screenshot.click,
+ screenshot.drag,
+ screenshot.type,
+ ...commonTools,
+];
+
+const resources: Resource[] = [
+ allResources.pdf,
+];
+
+program.parse(process.argv);
diff --git a/packages/playwright-mcp/src/servers/snapshot.ts b/packages/playwright-mcp/src/resources/resource.ts
similarity index 57%
rename from packages/playwright-mcp/src/servers/snapshot.ts
rename to packages/playwright-mcp/src/resources/resource.ts
index 71b6b478b9..2f45c4dc0b 100644
--- a/packages/playwright-mcp/src/servers/snapshot.ts
+++ b/packages/playwright-mcp/src/resources/resource.ts
@@ -14,21 +14,27 @@
* limitations under the License.
*/
-import { Server } from './server';
-import { wait, pressKey } from '../tools/common';
-import { navigate, snapshot, click, hover, type } from '../tools/snapshot';
+import type * as playwright from 'playwright';
-const server = new Server({
- name: 'Playwright snapshot-based browser server',
- version: '0.0.1',
- tools: [
- navigate,
- snapshot,
- click,
- hover,
- type,
- pressKey,
- wait,
- ]
-});
-server.start();
+export type ResourceContext = {
+ page: playwright.Page;
+};
+
+export type ResourceSchema = {
+ uri: string;
+ name: string;
+ description?: string;
+ mimeType?: string;
+};
+
+export type ResourceResult = {
+ uri: string;
+ mimeType?: string;
+ text?: string;
+ blob?: string;
+};
+
+export type Resource = {
+ schema: ResourceSchema;
+ read: (context: ResourceContext, uri: string) => Promise<ResourceResult>;
+};
diff --git a/packages/playwright-mcp/src/servers/screenshot.ts b/packages/playwright-mcp/src/resources/resources.ts
similarity index 58%
rename from packages/playwright-mcp/src/servers/screenshot.ts
rename to packages/playwright-mcp/src/resources/resources.ts
index 2f9eefae74..88edad2dc3 100644
--- a/packages/playwright-mcp/src/servers/screenshot.ts
+++ b/packages/playwright-mcp/src/resources/resources.ts
@@ -14,22 +14,22 @@
* limitations under the License.
*/
-import { Server } from './server';
-import { navigate, wait, pressKey } from '../tools/common';
-import { screenshot, moveMouse, click, drag, type } from '../tools/screenshot';
+import type { Resource } from './resource';
-const server = new Server({
- name: 'Playwright screenshot-based browser server',
- version: '0.0.1',
- tools: [
- navigate,
- screenshot,
- moveMouse,
- click,
- drag,
- type,
- pressKey,
- wait,
- ]
-});
-server.start();
+export const pdf: Resource = {
+ schema: {
+ uri: 'file:///playwright/page.pdf',
+ name: 'Page as PDF',
+ description: 'Save current page as PDF',
+ mimeType: 'application/pdf',
+ },
+
+ read: async (context, uri) => {
+ const pdf = await context.page.pdf();
+ return {
+ uri,
+ mimeType: 'application/pdf',
+ blob: pdf.toString('base64'),
+ };
+ },
+};
diff --git a/packages/playwright-mcp/src/servers/server.ts b/packages/playwright-mcp/src/server.ts
similarity index 60%
rename from packages/playwright-mcp/src/servers/server.ts
rename to packages/playwright-mcp/src/server.ts
index 0ac38796c2..42e4888e20 100644
--- a/packages/playwright-mcp/src/servers/server.ts
+++ b/packages/playwright-mcp/src/server.ts
@@ -16,25 +16,41 @@
import { Server as MCPServer } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
-import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
+import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import * as playwright from 'playwright';
-import type { Tool } from '../tools/common';
+import type { Tool } from './tools/tool';
+import type { Resource } from './resources/resource';
+
+export type LaunchOptions = {
+ headless?: boolean;
+};
export class Server {
private _server: MCPServer;
private _tools: Tool[];
private _page: playwright.Page | undefined;
+ private _launchOptions: LaunchOptions;
- constructor(options: { name: string, version: string, tools: Tool[] }) {
- const { name, version, tools } = options;
- this._server = new MCPServer({ name, version }, { capabilities: { tools: {} } });
+ constructor(options: { name: string, version: string, tools: Tool[], resources: Resource[] }, launchOptions: LaunchOptions) {
+ const { name, version, tools, resources } = options;
+ this._launchOptions = launchOptions;
+ this._server = new MCPServer({ name, version }, {
+ capabilities: {
+ tools: {},
+ resources: {},
+ }
+ });
this._tools = tools;
this._server.setRequestHandler(ListToolsRequestSchema, async () => {
return { tools: tools.map(tool => tool.schema) };
});
+ this._server.setRequestHandler(ListResourcesRequestSchema, async () => {
+ return { resources: resources.map(resource => resource.schema) };
+ });
+
this._server.setRequestHandler(CallToolRequestSchema, async request => {
const page = await this._openPage();
@@ -57,22 +73,37 @@ export class Server {
}
});
- this._setupExitWatchdog();
+ this._server.setRequestHandler(ReadResourceRequestSchema, async request => {
+ const resource = resources.find(resource => resource.schema.uri === request.params.uri);
+ if (!resource) {
+ return {
+ content: [{ type: 'text', text: `Resource "${request.params.uri}" not found` }],
+ isError: true,
+ };
+ }
+
+ const result = await resource.read({ page: await this._openPage() }, request.params.uri);
+ return result;
+ });
}
- start() {
+ async start() {
const transport = new StdioServerTransport();
- void this._server.connect(transport);
+ await this._server.connect(transport);
+ }
+
+ async stop() {
+ await this._server.close();
+ await this._page?.context()?.browser()?.close();
}
private async _createBrowser(): Promise<playwright.Browser> {
- const headless = process.env.PLAYWRIGHT_HEADLESS === '1' || process.env.PLAYWRIGHT_HEADLESS === 'true';
if (process.env.PLAYWRIGHT_WS_ENDPOINT) {
const url = new URL(process.env.PLAYWRIGHT_WS_ENDPOINT);
- url.searchParams.set('launch-options', JSON.stringify({ headless }));
+ url.searchParams.set('launch-options', JSON.stringify(this._launchOptions));
return await playwright.chromium.connect(String(url));
}
- return await playwright.chromium.launch({ headless });
+ return await playwright.chromium.launch(this._launchOptions);
}
private async _openPage(): Promise<playwright.Page> {
@@ -83,15 +114,4 @@ export class Server {
}
return this._page;
}
-
- private _setupExitWatchdog() {
- process.stdin.on('close', async () => {
- this._server.close();
- // eslint-disable-next-line no-restricted-properties
- setTimeout(() => process.exit(0), 15000);
- await this._page?.context()?.browser()?.close();
- // eslint-disable-next-line no-restricted-properties
- process.exit(0);
- });
- }
}
diff --git a/packages/playwright-mcp/src/tools/common.ts b/packages/playwright-mcp/src/tools/common.ts
index 214b2e997e..ff2323656b 100644
--- a/packages/playwright-mcp/src/tools/common.ts
+++ b/packages/playwright-mcp/src/tools/common.ts
@@ -14,111 +14,121 @@
* limitations under the License.
*/
-import { waitForCompletion } from '../utils';
+import { z } from 'zod';
+import { zodToJsonSchema } from 'zod-to-json-schema';
-import type * as playwright from 'playwright';
-import type { ImageContent, TextContent } from '@modelcontextprotocol/sdk/types';
+import { runAndWait } from './utils';
-export type ToolContext = {
- page: playwright.Page;
-};
+import type { ToolFactory, Tool } from './tool';
-export type ToolSchema = {
- name: string;
- description: string;
- inputSchema: Record<string, any>;
-};
+const navigateSchema = z.object({
+ url: z.string().describe('The URL to navigate to'),
+});
-export type ToolResult = {
- content: (ImageContent | TextContent)[];
- isError?: boolean;
-};
-
-export type Tool = {
- schema: ToolSchema;
- handle: (context: ToolContext, params?: Record<string, any>) => Promise<ToolResult>;
-};
-
-export const navigate: Tool = {
+export const navigate: ToolFactory = snapshot => ({
schema: {
name: 'navigate',
description: 'Navigate to a URL',
- inputSchema: {
- type: 'object',
- properties: {
- url: {
- type: 'string',
- description: 'URL to navigate to',
- },
- },
- }
+ inputSchema: zodToJsonSchema(navigateSchema),
},
-
handle: async (context, params) => {
- await waitForCompletion(context.page, async () => {
- await context.page.goto(params!.url as string);
- });
- return {
- content: [{
- type: 'text',
- text: `Navigated to ${params!.url}`,
- }],
- };
- }
-};
+ const validatedParams = navigateSchema.parse(params);
+ return await runAndWait(context, async () => {
+ await context.page.goto(validatedParams.url);
+ return {
+ content: [{
+ type: 'text',
+ text: `Navigated to ${validatedParams.url}`,
+ }],
+ };
+ }, snapshot);
+ },
+});
+
+const goBackSchema = z.object({});
+
+export const goBack: ToolFactory = snapshot => ({
+ schema: {
+ name: 'goBack',
+ description: 'Go back to the previous page',
+ inputSchema: zodToJsonSchema(goBackSchema),
+ },
+ handle: async context => {
+ return await runAndWait(context, async () => {
+ await context.page.goBack();
+ return {
+ content: [{
+ type: 'text',
+ text: `Navigated back`,
+ }],
+ };
+ }, snapshot);
+ },
+});
+
+const goForwardSchema = z.object({});
+
+export const goForward: ToolFactory = snapshot => ({
+ schema: {
+ name: 'goForward',
+ description: 'Go forward to the next page',
+ inputSchema: zodToJsonSchema(goForwardSchema),
+ },
+ handle: async context => {
+ return await runAndWait(context, async () => {
+ await context.page.goForward();
+ return {
+ content: [{
+ type: 'text',
+ text: `Navigated forward`,
+ }],
+ };
+ }, snapshot);
+ },
+});
+
+const waitSchema = z.object({
+ time: z.number().describe('The time to wait in seconds'),
+});
export const wait: Tool = {
schema: {
name: 'wait',
- description: `Wait for given amount of time to see if the page updates. Use it after action if you think page is not ready yet`,
- inputSchema: {
- type: 'object',
- properties: {
- time: {
- type: 'integer',
- description: 'Time to wait in seconds',
- },
- },
- required: ['time'],
- }
+ description: 'Wait for a specified time in seconds',
+ inputSchema: zodToJsonSchema(waitSchema),
},
-
handle: async (context, params) => {
- await context.page.waitForTimeout(Math.min(10000, params!.time as number * 1000));
+ const validatedParams = waitSchema.parse(params);
+ await context.page.waitForTimeout(Math.min(10000, validatedParams.time * 1000));
return {
content: [{
type: 'text',
- text: `Waited for ${params!.time} seconds`,
+ text: `Waited for ${validatedParams.time} seconds`,
}],
};
- }
+ },
};
+const pressKeySchema = z.object({
+ key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),
+});
+
export const pressKey: Tool = {
schema: {
- name: 'press_key',
- description: 'Press a key',
- inputSchema: {
- type: 'object',
- properties: {
- key: {
- type: 'string',
- description: 'Name of the key to press or a character to generate, such as `ArrowLeft` or `a`',
- },
- },
- required: ['key'],
- }
+ name: 'press',
+ description: 'Press a key on the keyboard',
+ inputSchema: zodToJsonSchema(pressKeySchema),
},
-
handle: async (context, params) => {
- await waitForCompletion(context.page, async () => {
- await context.page.keyboard.press(params!.key as string);
+ const validatedParams = pressKeySchema.parse(params);
+ return await runAndWait(context, async () => {
+ await context.page.keyboard.press(validatedParams.key);
+ return {
+ content: [{
+ type: 'text',
+ text: `Pressed key ${validatedParams.key}`,
+ }],
+ };
});
- return {
- content: [{
- type: 'text',
- text: `Pressed key ${params!.key}`,
- }],
- };
- }
+ },
};
diff --git a/packages/playwright-mcp/src/tools/screenshot.ts b/packages/playwright-mcp/src/tools/screenshot.ts
index ff8a188fd0..8dff613900 100644
--- a/packages/playwright-mcp/src/tools/screenshot.ts
+++ b/packages/playwright-mcp/src/tools/screenshot.ts
@@ -14,24 +14,18 @@
* limitations under the License.
*/
-import { Tool } from './common';
-import { waitForCompletion } from '../utils';
-
-const elementProperties = {
- element: {
- type: 'string',
- description: 'Element label, description or any other text to describe the element',
- }
-};
+import { z } from 'zod';
+import { zodToJsonSchema } from 'zod-to-json-schema';
+
+import { runAndWait } from './utils';
+
+import type { Tool } from './tool';
export const screenshot: Tool = {
schema: {
name: 'screenshot',
description: 'Take a screenshot of the current page',
- inputSchema: {
- type: 'object',
- properties: {},
- }
+ inputSchema: zodToJsonSchema(z.object({})),
},
handle: async context => {
@@ -39,117 +33,95 @@ export const screenshot: Tool = {
return {
content: [{ type: 'image', data: screenshot.toString('base64'), mimeType: 'image/jpeg' }],
};
- }
+ },
};
+const elementSchema = z.object({
+ element: z.string().describe('Element label, description or any other text to describe the element'),
+});
+
+const moveMouseSchema = elementSchema.extend({
+ x: z.number().describe('X coordinate'),
+ y: z.number().describe('Y coordinate'),
+});
+
export const moveMouse: Tool = {
schema: {
name: 'move_mouse',
description: 'Move mouse to a given position',
- inputSchema: {
- type: 'object',
- properties: {
- x: {
- type: 'number',
- description: 'X coordinate',
- },
- y: {
- type: 'number',
- description: 'Y coordinate',
- },
- ...elementProperties,
- },
- required: ['x', 'y', 'element'],
- }
+ inputSchema: zodToJsonSchema(moveMouseSchema),
},
handle: async (context, params) => {
- await context.page.mouse.move(params!.x as number, params!.y as number);
+ const validatedParams = moveMouseSchema.parse(params);
+ await context.page.mouse.move(validatedParams.x, validatedParams.y);
return {
- content: [{ type: 'text', text: `Moved mouse to (${params!.x}, ${params!.y})` }],
+ content: [{ type: 'text', text: `Moved mouse to (${validatedParams.x}, ${validatedParams.y})` }],
};
- }
+ },
};
export const click: Tool = {
schema: {
name: 'click',
description: 'Click left mouse button',
- inputSchema: {
- type: 'object',
- properties: {
- ...elementProperties,
- },
- required: ['element'],
- }
+ inputSchema: zodToJsonSchema(elementSchema),
},
handle: async context => {
- await waitForCompletion(context.page, async () => {
+ await runAndWait(context, async () => {
await context.page.mouse.down();
await context.page.mouse.up();
});
return {
content: [{ type: 'text', text: 'Clicked mouse' }],
};
- }
+ },
};
+const dragSchema = elementSchema.extend({
+ x: z.number().describe('X coordinate'),
+ y: z.number().describe('Y coordinate'),
+});
+
export const drag: Tool = {
schema: {
name: 'drag',
description: 'Drag left mouse button',
- inputSchema: {
- type: 'object',
- properties: {
- x: {
- type: 'number',
- description: 'X coordinate',
- },
- y: {
- type: 'number',
- description: 'Y coordinate',
- },
- },
- ...elementProperties,
- required: ['x', 'y', 'element'],
- }
+ inputSchema: zodToJsonSchema(dragSchema),
},
handle: async (context, params) => {
- await waitForCompletion(context.page, async () => {
+ const validatedParams = dragSchema.parse(params);
+ await runAndWait(context, async () => {
await context.page.mouse.down();
- await context.page.mouse.move(params!.x as number, params!.y as number);
+ await context.page.mouse.move(validatedParams.x, validatedParams.y);
await context.page.mouse.up();
});
return {
- content: [{ type: 'text', text: `Dragged mouse to (${params!.x}, ${params!.y})` }],
+ content: [{ type: 'text', text: `Dragged mouse to (${validatedParams.x}, ${validatedParams.y})` }],
};
- }
+ },
};
+const typeSchema = z.object({
+ text: z.string().describe('Text to type'),
+});
+
export const type: Tool = {
schema: {
name: 'type',
description: 'Type text',
- inputSchema: {
- type: 'object',
- properties: {
- text: {
- type: 'string',
- description: 'Text to type',
- },
- },
- required: ['text'],
- }
+ inputSchema: zodToJsonSchema(typeSchema),
},
handle: async (context, params) => {
- await waitForCompletion(context.page, async () => {
- await context.page.keyboard.type(params!.text as string);
+ const validatedParams = typeSchema.parse(params);
+ await runAndWait(context, async () => {
+ await context.page.keyboard.type(validatedParams.text);
});
return {
- content: [{ type: 'text', text: `Typed text "${params!.text}"` }],
+ content: [{ type: 'text', text: `Typed text "${validatedParams.text}"` }],
};
- }
+ },
};
diff --git a/packages/playwright-mcp/src/tools/snapshot.ts b/packages/playwright-mcp/src/tools/snapshot.ts
index 19d4611def..301a4db366 100644
--- a/packages/playwright-mcp/src/tools/snapshot.ts
+++ b/packages/playwright-mcp/src/tools/snapshot.ts
@@ -14,139 +14,82 @@
* limitations under the License.
*/
-import { waitForCompletion } from '../utils';
+import { z } from 'zod';
+import zodToJsonSchema from 'zod-to-json-schema';
-import type * as playwright from 'playwright';
-import type { Tool, ToolContext, ToolResult } from './common';
+import { captureAriaSnapshot, runAndWait } from './utils';
-const elementProperties = {
- element: {
- type: 'string',
- description: 'Element label, description of any other text to describe the element',
- },
- ref: {
- type: 'string',
- description: 'Target element reference',
- }
-};
+import type * as playwright from 'playwright';
+import type { Tool } from './tool';
export const snapshot: Tool = {
schema: {
name: 'snapshot',
description: 'Capture accessibility snapshot of the current page, this is better than screenshot',
- inputSchema: {
- type: 'object',
- properties: {},
- }
+ inputSchema: zodToJsonSchema(z.object({})),
},
handle: async context => {
return await captureAriaSnapshot(context.page);
- }
-};
-
-export const navigate: Tool = {
- schema: {
- name: 'navigate',
- description: 'Navigate to a URL',
- inputSchema: {
- type: 'object',
- properties: {
- url: {
- type: 'string',
- description: 'URL to navigate to',
- },
- },
- }
},
-
- handle: async (context, params) => {
- return runAndCaptureSnapshot(context, () => context.page.goto(params!.url));
- }
};
+const elementSchema = z.object({
+ element: z.string().describe('Element label, description of any other text to describe the element'),
+ ref: z.string().describe('Target element reference'),
+});
+
export const click: Tool = {
schema: {
name: 'click',
description: 'Perform click on a web page',
- inputSchema: {
- type: 'object',
- properties: {
- ...elementProperties,
- },
- required: ['ref', 'element'],
- }
+ inputSchema: zodToJsonSchema(elementSchema),
},
handle: async (context, params) => {
- const locator = refLocator(context.page, params!);
- return runAndCaptureSnapshot(context, () => locator.click());
- }
+ const validatedParams = elementSchema.parse(params);
+ const locator = refLocator(context.page, validatedParams);
+ return runAndWait(context, () => locator.click(), true);
+ },
};
export const hover: Tool = {
schema: {
name: 'hover',
description: 'Hover over element on page',
- inputSchema: {
- type: 'object',
- properties: {
- ...elementProperties,
- },
- required: ['ref', 'element'],
- }
+ inputSchema: zodToJsonSchema(elementSchema),
},
handle: async (context, params) => {
- const locator = refLocator(context.page, params!);
- return runAndCaptureSnapshot(context, () => locator.hover());
- }
+ const validatedParams = elementSchema.parse(params);
+ const locator = refLocator(context.page, validatedParams);
+ return runAndWait(context, () => locator.hover(), true);
+ },
};
+const typeSchema = elementSchema.extend({
+ text: z.string().describe('Text to type into the element'),
+ submit: z.boolean().describe('Whether to submit entered text (press Enter after)'),
+});
+
export const type: Tool = {
schema: {
name: 'type',
description: 'Type text into editable element',
- inputSchema: {
- type: 'object',
- properties: {
- ...elementProperties,
- text: {
- type: 'string',
- description: 'Text to enter',
- },
- submit: {
- type: 'boolean',
- description: 'Whether to submit entered text (press Enter after)'
- }
- },
- required: ['ref', 'element', 'text'],
- }
+ inputSchema: zodToJsonSchema(typeSchema),
},
handle: async (context, params) => {
- const locator = refLocator(context.page, params!);
- return await runAndCaptureSnapshot(context, async () => {
- locator.fill(params!.text as string);
- if (params!.submit)
+ const validatedParams = typeSchema.parse(params);
+ const locator = refLocator(context.page, validatedParams);
+ return await runAndWait(context, async () => {
+ await locator.fill(validatedParams.text);
+ if (validatedParams.submit)
await locator.press('Enter');
- });
- }
+ }, true);
+ },
};
-function refLocator(page: playwright.Page, params: Record<string, string>): playwright.Locator {
+function refLocator(page: playwright.Page, params: z.infer<typeof elementSchema>): playwright.Locator {
return page.locator(`aria-ref=${params.ref}`);
}
-
-async function runAndCaptureSnapshot(context: ToolContext, callback: () => Promise<any>): Promise<ToolResult> {
- const page = context.page;
- await waitForCompletion(page, () => callback());
- return captureAriaSnapshot(page);
-}
-
-async function captureAriaSnapshot(page: playwright.Page): Promise<ToolResult> {
- const snapshot = await page.locator('html').ariaSnapshot({ ref: true });
- return {
- content: [{ type: 'text', text: `# Current page snapshot\n${snapshot}` }],
- };
-}
diff --git a/packages/playwright-mcp/src/tools/tool.ts b/packages/playwright-mcp/src/tools/tool.ts
new file mode 100644
index 0000000000..f85702c448
--- /dev/null
+++ b/packages/playwright-mcp/src/tools/tool.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 type * as playwright from 'playwright';
+import type { ImageContent, TextContent } from '@modelcontextprotocol/sdk/types';
+import type { JsonSchema7Type } from 'zod-to-json-schema';
+
+export type ToolContext = {
+ page: playwright.Page;
+};
+
+export type ToolSchema = {
+ name: string;
+ description: string;
+ inputSchema: JsonSchema7Type;
+};
+
+export type ToolResult = {
+ content: (ImageContent | TextContent)[];
+ isError?: boolean;
+};
+
+export type Tool = {
+ schema: ToolSchema;
+ handle: (context: ToolContext, params?: Record<string, any>) => Promise<ToolResult>;
+};
+
+export type ToolFactory = (snapshot: boolean) => Tool;
diff --git a/packages/playwright-mcp/src/utils.ts b/packages/playwright-mcp/src/tools/utils.ts
similarity index 72%
rename from packages/playwright-mcp/src/utils.ts
rename to packages/playwright-mcp/src/tools/utils.ts
index 4a89d7466e..5ff7a5e37d 100644
--- a/packages/playwright-mcp/src/utils.ts
+++ b/packages/playwright-mcp/src/tools/utils.ts
@@ -15,8 +15,9 @@
*/
import type * as playwright from 'playwright';
+import type { ToolContext, ToolResult } from './tool';
-export async function waitForCompletion<R>(page: playwright.Page, callback: () => Promise<R>): Promise<R> {
+async function waitForCompletion<R>(page: playwright.Page, callback: () => Promise<R>): Promise<R> {
const requests = new Set<playwright.Request>();
let frameNavigated = false;
let waitCallback: () => void = () => {};
@@ -68,3 +69,21 @@ export async function waitForCompletion<R>(page: playwright.Page, callback: () =
dispose();
}
}
+
+export async function runAndWait(context: ToolContext, callback: () => Promise<any>, snapshot: boolean = false): Promise<ToolResult> {
+ const page = context.page;
+ const result = await waitForCompletion(page, () => callback());
+ return snapshot ? captureAriaSnapshot(page) : result;
+}
+
+export async function captureAriaSnapshot(page: playwright.Page): Promise<ToolResult> {
+ const snapshot = await page.locator('html').ariaSnapshot({ ref: true });
+ return {
+ content: [{ type: 'text', text: `
+ # Page URL: ${page.url()}
+ # Page Title: ${page.title()}
+ # Page Snapshot
+ ${snapshot}`
+ }],
+ };
+}