Playwright MCP Server
Enables browser automation using Playwright for web scraping, testing, and automation tasks through natural language commands.
README
Playwright MCP Server
A Model Context Protocol (MCP) server that provides Playwright browser automation capabilities. This server enables AI assistants like GitHub Copilot to perform web scraping, testing, and browser automation tasks.
Features
This MCP server exposes 25 comprehensive Playwright tools organized by category:
🆕 Auto-Recording Feature
All actions are automatically recorded! You can generate a complete Playwright test file from any workflow with a single command:
"Generate a Playwright test from my workflow"
This automatically creates a test file in generated-tests/ with all your actions. No manual recording needed!
Navigation & Page Control (6 tools)
- playwright_navigate: Navigate to URLs with custom wait conditions
- playwright_go_back: Navigate back in browser history
- playwright_go_forward: Navigate forward in browser history
- playwright_reload: Reload the current page
- playwright_set_viewport: Set custom viewport dimensions
- playwright_get_page_info: Get current page URL and title
Element Interaction (8 tools)
- playwright_click: Click elements (supports multiple buttons and click counts)
- playwright_fill: Fill input fields quickly
- playwright_type: Type text with keyboard simulation and delays
- playwright_hover: Hover over elements
- playwright_select: Select dropdown options
- playwright_checkbox: Check or uncheck checkboxes
- playwright_drag_and_drop: Drag and drop elements
- playwright_press_key: Press keyboard keys (Enter, Escape, etc.)
Data Extraction (3 tools)
- playwright_extract_text: Extract text from single or multiple elements
- playwright_get_attribute: Get attribute values from elements
- playwright_evaluate: Execute custom JavaScript and get results
Waiting & Synchronization (1 tool)
- playwright_wait_for_selector: Wait for elements with custom timeout and state
Capture (1 tool)
- playwright_screenshot: Capture full or partial page screenshots
Test Recording & Generation (4 tools)
- playwright_record_start: Start recording user actions for test generation
- playwright_record_stop: Stop recording actions
- playwright_generate_test: Generate test scripts (Playwright/Puppeteer/Selenium in TypeScript/JavaScript/Python)
- playwright_generate_workflow_test: 🆕 Auto-generate Playwright test from current workflow actions
Browser Management (2 tools)
- playwright_close: Close browser and cleanup
- All tools support stateful browser sessions (cookies, auth, history preserved)
📋 Prerequisites
Before you begin, ensure you have:
- Node.js 18 or higher - Download here
- npm (comes with Node.js)
- VS Code (for GitHub Copilot integration) - Download here
- GitHub Copilot subscription (for AI-powered usage)
🔧 Installation & Setup
Step 1: Clone the Repository
git clone <your-repo-url>
cd playwright-mcp-server
Step 2: Install Dependencies
npm install
This will install:
@modelcontextprotocol/sdk- MCP protocol implementationplaywright- Browser automation libraryzod- Schema validation- TypeScript and related dependencies
Step 3: Install Playwright Browsers
npx playwright install chromium
This downloads the Chromium browser binary (~170MB). You can also install other browsers:
# Optional: Install all browsers
npx playwright install
Step 4: Build the Server
npm run build
This compiles TypeScript to JavaScript in the build/ directory.
Step 5: Configure VS Code (GitHub Copilot Integration)
Create or update .vscode/mcp.json in your workspace (not in this project):
{
"mcpServers": {
"playwright": {
"command": "node",
"args": ["/absolute/path/to/playwright-mcp-server/build/index.js"]
}
}
}
⚠️ Important: Replace /absolute/path/to/playwright-mcp-server/ with the actual path where you cloned this repo.
Examples:
- Windows:
"C:\\Users\\YourName\\Projects\\playwright-mcp-server\\build\\index.js" - Mac/Linux:
"/home/username/projects/playwright-mcp-server/build/index.js"
Step 6: Reload VS Code
- Press
Ctrl+Shift+P(Windows/Linux) orCmd+Shift+P(Mac) - Type "Reload Window" and press Enter
- Or simply restart VS Code
Step 7: Verify Installation
Open GitHub Copilot Chat in VS Code and try:
Navigate to https://example.com and take a screenshot
If it works, you're all set! 🎉
💡 Usage Examples
Basic Browser Automation
Use natural language with GitHub Copilot Chat:
Navigate to https://news.ycombinator.com and get the page title
Go to https://example.com, click the link with text "More information", and take a screenshot
Navigate to https://github.com, fill the search box with "playwright", and press Enter
Advanced Interactions
Go to https://amazon.com, hover over the menu, wait for the dropdown, and extract all category names
Navigate to a form page, check the terms checkbox, select "United States" from the country dropdown, and click submit
Open the developer console and execute: document.querySelectorAll('a').length
Test Recording & Generation
Start recording a test named "login_flow"
Navigate to https://example.com/login
Fill the username field with "testuser"
Fill the password field with "password123"
Click the login button
Wait for the dashboard to load
Stop recording
Generate a Playwright test in TypeScript, save as "login.spec.ts"
This will create a complete test file in generated-tests/login.spec.ts!
Multi-Step Workflows
1. Navigate to https://opensource-demo.orangehrmlive.com/web/index.php/auth/login
2. Extract the demo credentials from the page
3. Login with those credentials
4. Verify the dashboard title
5. Take a screenshot
Data Extraction
Go to https://news.ycombinator.com and extract all article titles
Navigate to a product page and get the price attribute from the element with class "product-price"
🎬 Test Generation Feature
Auto-Generate Tests (NEW!)
Simply perform your workflow and generate a test:
Navigate to https://example.com
Click login button
Fill username with "test"
Fill password with "pass"
Click submit
Generate a Playwright test from my workflow
Result: Complete test file in generated-tests/workflow_TIMESTAMP.spec.ts
Manual Recording (Original Method)
Record → Generate → Run
Step 1: Start Recording
Start recording "checkout_flow"
Step 2: Perform Actions (all are automatically recorded)
Navigate to https://demo-store.com
Click .add-to-cart
Fill #email with "test@example.com"
Click .checkout-button
Step 3: Stop Recording
Stop recording
Step 4: Generate Test
Generate a Playwright test in TypeScript, save as "checkout.spec.ts"
Or generate for different frameworks:
Generate a Puppeteer test in JavaScript, save as "checkout.test.js"
Generate a Selenium test in Python, save as "test_checkout.py"
Generated test files are saved in generated-tests/ directory and are ready to run!
📚 Tool Reference
Navigation & Page Control
| Tool | Description | Key Parameters |
|---|---|---|
playwright_navigate |
Navigate to URL | url, waitUntil (load/networkidle/domcontentloaded) |
playwright_go_back |
Browser back button | - |
playwright_go_forward |
Browser forward button | - |
playwright_reload |
Reload current page | - |
playwright_set_viewport |
Set viewport size | width, height |
playwright_get_page_info |
Get URL and title | - |
Element Interaction
| Tool | Description | Key Parameters |
|---|---|---|
playwright_click |
Click element | selector, button (left/right/middle), clickCount |
playwright_fill |
Fill input quickly | selector, value |
playwright_type |
Type with delays | selector, text, delay |
playwright_hover |
Hover over element | selector |
playwright_select |
Select dropdown option | selector, value |
playwright_checkbox |
Check/uncheck checkbox | selector, checked (true/false) |
playwright_drag_and_drop |
Drag and drop | sourceSelector, targetSelector |
playwright_press_key |
Press keyboard key | key (Enter, Escape, etc.) |
Data Extraction
| Tool | Description | Key Parameters |
|---|---|---|
playwright_extract_text |
Extract text content | selector, multiple (true for all matches) |
playwright_get_attribute |
Get element attribute | selector, attribute |
playwright_evaluate |
Execute JavaScript | script |
Waiting & Capture
| Tool | Description | Key Parameters |
|---|---|---|
playwright_wait_for_selector |
Wait for element | selector, timeout, state (visible/hidden/attached) |
playwright_screenshot |
Capture screenshot | name, fullPage (true/false) |
Test Generation
| Tool | Description | Key Parameters |
|---|---|---|
playwright_record_start |
Start recording | name |
playwright_record_stop |
Stop recording | - |
playwright_generate_test |
Generate test script | framework (playwright/puppeteer/selenium), language (typescript/javascript/python), fileName |
Browser Management
| Tool | Description | Key Parameters |
|---|---|---|
playwright_close |
Close browser | - |
🏗️ Architecture
This MCP server follows a 100% local architecture:
┌─────────────────────────────────────────────────────────┐
│ YOUR LOCAL MACHINE │
│ │
│ ┌──────────────┐ │
│ │ VS Code │ │
│ │ + Copilot │ │
│ └──────┬───────┘ │
│ │ stdio (no network) │
│ ▼ │
│ ┌──────────────────────────────────┐ │
│ │ Playwright MCP Server │ │
│ │ (build/index.js) │ │
│ └──────────────┬───────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────┐ │
│ │ Chromium Browser (Local) │ │
│ └───────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────┘
Key Points:
- ✅ No external MCP services - Everything runs locally
- ✅ stdio communication - No HTTP or WebSocket connections
- ✅ No API keys needed - No authentication required
- ✅ Privacy-first - Your automation scripts never leave your machine
- ✅ Offline capable - Works without internet (except for accessing websites)
🛠️ Development
Build Commands
# Build once
npm run build
# Watch mode (auto-rebuild on changes)
npm run watch
# Clean build
rm -rf build && npm run build
Project Structure
playwright-mcp-server/
├── .github/
│ └── copilot-instructions.md # GitHub Copilot context
├── .vscode/
│ └── mcp.json # MCP server configuration
├── src/
│ └── index.ts # Main server implementation
├── build/
│ └── index.js # Compiled output (generated)
├── generated-tests/ # Generated test files (created at runtime)
├── package.json # Dependencies
├── tsconfig.json # TypeScript configuration
└── README.md # This file
Extending the Server
To add a new tool:
- Define the schema in
src/index.ts:
const MyToolSchema = z.object({
param1: z.string().describe("Description"),
param2: z.number().optional(),
});
- Add the tool definition:
{
name: "playwright_my_tool",
description: "What this tool does",
inputSchema: { /* JSON schema */ }
}
- Implement the handler:
case "playwright_my_tool": {
const { param1, param2 } = MyToolSchema.parse(args);
const page = await browserManager.ensurePage();
// Your implementation
return { content: [{ type: "text", text: "Result" }] };
}
- Rebuild:
npm run build
🔒 Security & Privacy
- Local-only operation - No data sent to external servers
- Headless mode - Browser runs without visible window (configurable)
- Input validation - All parameters validated with Zod schemas
- Sandboxed browser - Chromium runs with security flags
- No telemetry - No usage tracking or analytics
Best Practices:
- Be cautious when navigating to untrusted URLs
- Validate user input before passing to
playwright_evaluate - Review generated test scripts before running
- Use in trusted environments only
🐛 Troubleshooting
Issue: MCP Server Not Connecting
Solution:
# 1. Verify build exists
ls build/index.js
# 2. Test server manually
node build/index.js
# 3. Check VS Code MCP configuration
cat .vscode/mcp.json
# 4. Reload VS Code
# Ctrl+Shift+P → "Reload Window"
Issue: Browser Launch Fails
Solution:
# Install/reinstall browsers
npx playwright install chromium
# Check system dependencies (Linux)
npx playwright install-deps chromium
# Test browser manually
npx playwright open https://example.com
Issue: Tool Not Found
Cause: MCP server cache or outdated build
Solution:
# Rebuild
npm run build
# Clear VS Code cache and reload
# Ctrl+Shift+P → "Developer: Reload Window"
Issue: Screenshots Not Saving
Cause: Permission issues or invalid path
Solution:
# Create screenshots directory
mkdir -p screenshots
# Check write permissions
ls -la
Issue: Generated Tests Not Appearing
Cause: Directory not created
Solution:
Tests are automatically saved to generated-tests/ directory. If missing:
mkdir generated-tests
Debug Mode
Enable detailed logging by modifying src/index.ts:
console.error("DEBUG:", JSON.stringify(request, null, 2));
Then rebuild and check terminal output.
🎯 Use Cases
1. Web Scraping
Navigate to a news site and extract all article titles and links
2. Automated Testing
Record my login flow, then generate a test suite
3. Form Automation
Fill out and submit contact forms with test data
4. Visual Regression Testing
Take screenshots of my app in different viewport sizes
5. Data Collection
Navigate through paginated results and collect all product information
6. Browser-Based Scripts
Execute custom JavaScript to analyze page performance
📝 Configuration Options
Change Browser Type
Edit src/index.ts:
// Use Firefox instead of Chromium
import { firefox } from "playwright";
this.browser = await firefox.launch({ ... });
Headful Mode (Visible Browser)
Edit src/index.ts:
this.browser = await chromium.launch({
headless: false, // Show browser window
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
Custom Viewport
Default is 1280x720. Change in src/index.ts:
this.context = await browser.newContext({
viewport: { width: 1920, height: 1080 },
userAgent: "...",
});
Screenshot Directory
Generated tests save to generated-tests/. Modify in src/index.ts:
const testsDir = path.join(process.cwd(), "my-custom-tests");
🤝 Contributing
Contributions are welcome! Here's how:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes
- Build and test:
npm run build - Commit:
git commit -m 'Add amazing feature' - Push:
git push origin feature/amazing-feature - Open a Pull Request
Development Setup
git clone <your-fork>
cd playwright-mcp-server
npm install
npm run build
# Make changes in src/
npm run watch # Auto-rebuild on changes
📄 License
MIT
🔗 Related Resources
- Model Context Protocol - Official MCP documentation
- Playwright - Browser automation framework
- MCP TypeScript SDK - Official SDK
- GitHub Copilot - AI pair programmer
- VS Code - Recommended editor
⭐ Support & Community
If you find this project useful:
- ⭐ Star this repository
- 🐛 Report issues on GitHub
- 💡 Suggest new features
- 🤝 Contribute improvements
📮 Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: This README and inline code comments
🎉 Acknowledgments
- Built with the Model Context Protocol
- Powered by Playwright
- Inspired by the MCP community
Made with ❤️ for browser automation
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。