DEV Community

Cover image for 🤖Setting Up MCP Agents with Playwright
Vignesh Ambalam Suresh
Vignesh Ambalam Suresh

Posted on

🤖Setting Up MCP Agents with Playwright

A Comprehensive Guide for Test Automation Engineers

What is the Model Context Protocol (MCP)?

MCP is an open protocol developed by Anthropic that enables seamless communication between AI assistants and external tools. It acts as a standardized bridge, allowing AI models like Claude to interact with various systems such as browsers, databases, file systems, and APIs through a unified interface.

Key Benefits of MCP + Playwright Integration

  • Natural Language Testing - Write tests in plain English without complex syntax

  • Intelligent Element Detection - AI understands context and finds elements smartly

  • Self-Healing Capabilities - Adapts to UI changes automatically

  • Reduced Maintenance - Less time spent updating brittle selectors

  • Faster Test Creation - Generate tests from user stories instantly

Understanding the architecture is crucial before diving into implementation. The MCP + Playwright integration consists of four main layers that work together to enable AI-powered browser automation

Architecture Overview

Understanding the architecture is crucial before diving into implementation. The MCP + Playwright integration consists of four main layers that work together to enable AI-powered browser automation

Architecture Components

  • Claude AI - Natural language processor that interprets test commands

  • MCP Client - Handles protocol communication with the server

  • MCP Server - Routes commands to appropriate tool handlers

  • Tool Handlers - Execute specific Playwright actions

  • Playwright - Cross-browser automation framework

  • Browsers - Chromium, Firefox, or WebKit instances

Architecture Flow

Step-by-Step Configuration

Step 1: Project Initialization

Begin by creating a new project directory and initializing it with npm. This establishes the foundation for your MCP + Playwright automation framework.

# Create project directory
mkdir playwright-mcp-automation
cd playwright-mcp-automation

# Initialize npm project
npm init -y

# Install required dependencies
npm install playwright @playwright/test typescript ts-node
npm install @modelcontextprotocol/sdk

# Install Playwright browsers
npx playwright install
Enter fullscreen mode Exit fullscreen mode

Step 2: TypeScript Configuration

Create a tsconfig.json file to configure TypeScript compilation settings. This ensures proper type checking and module resolution for the MCP server implementation.

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "declaration": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Project Structure Setup

Organize your project with a clean, maintainable folder structure. This structure follows industry best practices and separates concerns effectively.

playwright-mcp-automation/
├── src/
│   ├── mcp-server/
│   │   ├── index.ts          # Server entry point
│   │   ├── tools.ts          # Tool definitions
│   │   └── handlers.ts       # Tool handlers
│   ├── pages/
│   │   ├── BasePage.ts       # Base page class
│   │   ├── LoginPage.ts      # Login page object
│   │   └── HomePage.ts       # Home page object
│   └── utils/
│       └── helpers.ts        # Utility functions
├── tests/
│   ├── login.spec.ts         # Login tests
│   └── home.spec.ts          # Home page tests
├── config/
│   └── test.config.ts        # Test configuration
├── package.json
├── tsconfig.json
└── playwright.config.ts
Enter fullscreen mode Exit fullscreen mode

Step 4: MCP Server Implementation

Create the MCP server that will handle communication between Claude and Playwright. This is the core component that enables AI-driven browser automation.

// src/mcp-server/index.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { chromium, Browser, Page } from "playwright";
import { registerTools } from "./tools.js";

let browser: Browser | null = null;
let page: Page | null = null;

const server = new Server(
  {
    name: "playwright-mcp-server",
    version: "1.0.0"
  },
  {
    capabilities: {
      tools: {}
    }
  }
);

// Initialize browser on first use
async function ensureBrowser(): Promise<Page> {
  if (!browser) {
    browser = await chromium.launch({
      headless: false
    });
    page = await browser.newPage();
  }
  return page!;
}

// Register all tools
registerTools(server, ensureBrowser);

// Start the server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("Playwright MCP Server running");
}

main().catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Step 5: Define Playwright Tools

Define the tools that Claude can use to interact with the browser. Each tool maps to a specific Playwright action with proper input validation.

Note - This is not mandatory Once the MCP agents are configured then claude/co-pilot will automatically show below Playwright MCP agents:

Playwright MCP Agents

Step 6: Claude Desktop Configuration

Configure Claude Desktop to recognize and connect to your MCP server. This configuration file tells Claude where to find your Playwright MCP server.

Configuration File Location:

  • Windows - %APPDATA%\Claude\claude_desktop_config.json

  • MacOS - ~/Library/Application Support/Claude/claude_desktop_config.json

  • Linux - ~/.config/claude/claude_desktop_config.json

Configuration Content:

// claude_desktop_config.json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["ts-node", "src/mcp-server/index.ts"],
      "cwd": "/path/to/playwright-mcp-automation"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 7: VS Code Configuration

Configure VS Code for optimal development experience with MCP and Playwright. Install the recommended extensions and configure workspace settings.

Recommended VS Code Extensions:

VS Code Extensions

Understanding the Communication Flow

The sequence diagram below illustrates how a natural language command flows through the system, from user input to browser action and back.

Flow Diagram

Running Your First AI-Powered Test

With everything configured, you can now run tests using natural language commands through Claude. Here's how to verify your setup is working correctly.

Verification Steps:

  • Start the MCP server: npx ts-node src/mcp-server/index.ts
  • Open Claude Desktop application
  • Verify the Playwright server appears in connected MCP servers
  • Test with a simple command: "Navigate to google.com"
  • Confirm the browser opens and navigates successfully

Troubleshooting Common Issues

Common Issues

Conclusion

The integration of MCP with Playwright represents a significant advancement in test automation technology. By following this guide, you have established a foundation for intelligent, AI-driven browser automation that can understand natural language commands and execute complex testing scenarios.

This setup enables testers at all levels to leverage the power of AI without sacrificing the precision and control that Playwright provides. As MCP and AI technologies continue to evolve, this architecture will scale to accommodate new capabilities and use cases.

The future of test automation is here. Embrace it, experiment with it, and continuously improve your implementation to stay at the forefront of quality engineering excellence.

Have questions or want to share your implementation experience?

Let's discuss the future of AI-powered test automation!

Top comments (0)