← Back to Tutorials

21. Playwright Agents & MCP

MCP (Model Context Protocol)

MCP is an open protocol for connecting AI models to tools and data sources. Playwright MCP servers let AI agents control browsers, generate tests, and debug failures autonomously.

Copilot Integration

// GitHub Copilot can generate Playwright tests from natural language
// Example prompt in VS Code:
// "Write a Playwright test that logs into SauceDemo and adds an item to cart"

// Copilot generates:
test('add item to cart', async ({ page }) => {
  await page.goto('https://www.saucedemo.com');
  await page.fill('#user-name', 'standard_user');
  await page.fill('#password', 'secret_sauce');
  await page.click('#login-button');
  await page.click('#add-to-cart-sauce-labs-backpack');
  await expect(page.locator('.shopping_cart_badge')).toHaveText('1');
});

Planner Agent

// An AI agent that plans test scenarios
// Prompt: "Plan E2E tests for an e-commerce checkout flow"

const plan = {
  scenarios: [
    { name: 'Happy path', steps: ['Login', 'Search product', 'Add to cart', 'Checkout', 'Verify confirmation'] },
    { name: 'Invalid coupon', steps: ['Login', 'Add to cart', 'Apply invalid coupon', 'Verify error'] },
    { name: 'Empty cart', steps: ['Login', 'Go to cart', 'Verify empty message'] },
    { name: 'Guest checkout', steps: ['Add to cart', 'Proceed as guest', 'Fill shipping', 'Complete order'] },
  ]
};

Generator Agent

// An AI agent that converts plain English to Playwright code
// Input: "Click the login button and wait for the dashboard"
// Output:
async function clickLoginAndWait(page: Page) {
  await page.getByRole('button', { name: 'Login' }).click();
  await page.waitForURL('**/dashboard');
  await expect(page.getByText('Welcome')).toBeVisible();
}

Healing Agent

// Auto-healing locators when selectors break
// If a locator fails, the healing agent tries alternative strategies:
// 1. Try getByRole with different accessible name
// 2. Try getByText with partial match
// 3. Try nearby element + relative locator
// 4. Try data-testid fallback
// 5. Report failure with suggested fix
✏️ Exercise: Use GitHub Copilot to generate a Playwright test for a multi-step form. Then use the MCP Playwright server to run a browser command via an AI prompt.