WebDriverIO
Сервер WebDriverIO MCP предоставляет AI-ассистентам, таким как Claude, возможность легко автоматизировать веб-браузеры и мобильные приложения (iOS/Android). Наслаждайтесь унифицированным тестированием, расширенным взаимодействием и записью сессий.
Сервер WebDriverIO выступает в качестве конечной точки Model Context Protocol, позволяя AI-ассистентам беспрепятственно автоматизировать веб-браузеры (Chrome, Firefox, Edge, Safari) и нативные мобильные приложения (iOS и Android) через единый унифицированный интерфейс. Он устраняет разрыв между AI и UI-автоматизацией, способствуя продвинутому тестированию, извлечению данных и интерактивным рабочим процессам на различных платформах. Этот инструмент упрощает создание AI-управляемых агентов, способных взаимодействовать со сложными пользовательскими интерфейсами как в вебе, так и на мобильных устройствах, включая такие функции, как эмуляция устройств и запись сессий.
Ключевые особенности
Варианты использования
A Model Context Protocol (MCP) server that enables Claude Desktop to interact with web browsers and mobile applications using WebDriverIO. Automate Chrome, Firefox, Edge, and Safari browsers plus iOS and Android apps—all through a unified interface.
Option 1: Configure Claude Desktop or Claude Code (Recommended)
Add the following configuration to your Claude MCP settings:
{
"mcpServers": {
"wdio-mcp": {
"command": "npx",
"args": [
"-y",
"@wdio/mcp"
]
}
}
}Option 2: Global Installation
npm i -g @wdio/mcpThen configure MCP:
{
"mcpServers": {
"wdio-mcp": {
"command": "wdio-mcp"
}
}
}Note: The npm package is
@wdio/mcp, but the executable binary iswdio-mcp.
Restart Claude Desktop
⚠️ You may need to fully restart Claude Desktop. On Windows, use Task Manager to ensure it's completely closed before restarting.
📖 Need help? Read the official MCP configuration guide
- Appium Server: Install globally with
npm install -g appium - Platform Drivers:
- iOS:
appium driver install xcuitest(requires Xcode on macOS) - Android:
appium driver install uiautomator2(requires Android Studio)
- iOS:
- Devices/Emulators:
- iOS Simulator (macOS) or physical device
- Android Emulator or physical device
- For iOS Real Devices: You'll need the device's UDID (Unique Device Identifier)
- Find UDID on macOS: Connect device → Open Finder → Select device → Click device name/model to reveal UDID
- Find UDID on Windows: Connect device → iTunes or Apple Devices app → Click device icon → Click "Serial Number" to reveal UDID
- Xcode method: Window → Devices and Simulators → Select device → UDID shown as "Identifier"
Start the Appium server before using mobile features:
appium
# Server runs at http://127.0.0.1:4723 by default- Session Management: Start and close browser sessions (Chrome, Firefox, Edge, Safari) with headless/headed modes
- Navigation & Interaction: Navigate URLs, click elements, fill forms, and retrieve content
- Page Analysis: Get visible elements, accessibility trees, take screenshots
- Cookie Management: Get, set, and delete cookies
- Scrolling: Smooth scrolling with configurable distances
- Attach to running Chrome: Connect to an existing Chrome window via
--remote-debugging-port— ideal for testing authenticated or pre-configured sessions - Device emulation: Apply mobile/tablet presets (iPhone 15, Pixel 7, etc.) to simulate responsive layouts without a physical device
- Session Recording: All tool calls are automatically recorded and exportable as runnable WebdriverIO JS
- Native App Testing: Test iOS (.app/.ipa) and Android (.apk) apps via Appium
- Touch Gestures: Tap, swipe, long-press, drag-and-drop
- App Lifecycle: Launch, background, terminate, check app state
- Context Switching: Seamlessly switch between native and webview contexts for hybrid apps
- Device Control: Rotate, lock/unlock, geolocation, keyboard control, notifications
- Cross-Platform Selectors: Accessibility IDs, XPath, UiAutomator (Android), Predicates (iOS)
| Tool | Description |
|---|---|
start_browser |
Start a browser session (Chrome, Firefox, Edge, Safari; headless/headed, custom dimensions) |
start_app_session |
Start an iOS or Android app session via Appium (supports state preservation via noReset) |
close_session |
Close or detach from the current browser or app session (supports detach mode) |
attach_browser |
Attach to a running Chrome instance via --remote-debugging-port (CDP) |
emulate_device |
Emulate a mobile/tablet device preset (viewport, DPR, UA, touch); requires BiDi session |
| Tool | Description |
|---|---|
navigate |
Navigate to a URL |
get_visible_elements |
Get visible, interactable elements on the page. Supports inViewportOnly (default: true) to filter viewport elements, and includeContainers (default: false) to include layout containers on mobile |
get_accessibility |
Get accessibility tree with semantic element information |
scroll |
Scroll in a direction (up/down) by specified pixels |
take_screenshot |
Capture a screenshot |
| Tool | Description |
|---|---|
click_element |
Click an element |
set_value |
Type text into input fields |
| Tool | Description |
|---|---|
get_cookies |
Get all cookies or a specific cookie by name |
set_cookie |
Set a cookie with name, value, and optional attributes |
delete_cookies |
Delete all cookies or a specific cookie |
| Tool | Description |
|---|---|
tap_element |
Tap an element by selector or coordinates |
swipe |
Swipe in a direction (up/down/left/right) |
drag_and_drop |
Drag from one location to another |
| Tool | Description |
|---|---|
get_app_state |
Check app state (installed, running, background, foreground) |
| Tool | Description |
|---|---|
get_contexts |
List available contexts (NATIVE_APP, WEBVIEW_*) |
get_current_context |
Show the currently active context |
switch_context |
Switch between native and webview contexts |
| Tool | Description |
|---|---|
rotate_device |
Rotate to portrait or landscape |
hide_keyboard |
Hide on-screen keyboard |
get_geolocation / set_geolocation |
Get or set device GPS location |
Example 1: Testing Demo Android App (Book Scanning)
Test the Demo Android app at C:\Users\demo-liveApiGbRegionNonMinifiedRelease-3018788.apk on emulator-5554:
1. Start the app with auto-grant permissions
2. Get visible elements on the onboarding screen
3. Tap "Skip" to bypass onboarding
4. Verify main screen loads
5. Take a screenshot
Example 2: Testing World of Books E-commerce Site
You are a Testing expert, and want to assess the basic workflows of worldofbooks.com:
- Open World of Books (accept all cookies)
- Get visible elements to see navigation structure
- Search for a fiction book
- Choose one and validate if there are NEW and used book options
- Report your findings at the end
Basic web testing prompt:
You are a Testing expert, and want to assess the basic workflows of a web application:
- Open World of Books (accept all cookies)
- Search for a fiction book
- Choose one and validate if there are NEW and used book options
- Report your findings at the end
Browser configuration options:
// Default settings (headed mode, 1280x1080)
start_browser()
// Firefox
start_browser({browser: 'firefox'})
// Edge
start_browser({browser: 'edge'})
// Safari (headed only; requires macOS)
start_browser({browser: 'safari'})
// Headless mode
start_browser({headless: true})
// Custom dimensions
start_browser({windowWidth: 1920, windowHeight: 1080})
// Headless with custom dimensions
start_browser({headless: true, windowWidth: 1920, windowHeight: 1080})
// Pass custom capabilities (e.g. Chrome extensions, profile, prefs)
start_browser({
headless: false,
capabilities: {
'goog:chromeOptions': {
args: ['--user-data-dir=/tmp/wdio-mcp-profile', '--load-extension=/path/to/unpacked-extension']
}
}
})Attach to a running Chrome instance:
// First, launch Chrome with remote debugging enabled:
//
// macOS (must quit Chrome first — open -a ignores args if Chrome is already running):
// pkill -x "Google Chrome" && sleep 1
// /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
// --remote-debugging-port=9222 \
// --user-data-dir=/tmp/chrome-debug &
//
// Linux:
// google-chrome --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug &
//
// Verify it's ready: curl http://localhost:9222/json/version
attach_browser()
attach_browser({port: 9333})
attach_browser({port: 9222, navigationUrl: 'https://app.example.com'})
Device emulation (requires BiDi session):
// Device emulation (requires BiDi session)
start_browser({capabilities: {webSocketUrl: true}})
emulate_device() // list available presets
emulate_device({device: 'iPhone 15'}) // activate emulation
emulate_device({device: 'Pixel 7'}) // switch device
emulate_device({device: 'reset'}) // restore desktop defaults
Testing an iOS app on simulator:
Test my iOS app located at /path/to/MyApp.app on iPhone 15 Pro simulator:
1. Start the app session
2. Tap the login button
3. Enter "testuser" in the username field
4. Take a screenshot of the home screen
5. Close the session
Preserving app state between sessions:
Test my Android app without resetting data:
1. Start app session with noReset: true and fullReset: false
2. App launches with existing login state and user data preserved
3. Run test scenarios
4. Close session (app remains installed with data intact)
Testing an iOS app on real device:
Test my iOS app on my physical iPhone:
1. Start app session with:
- platform: iOS
- appPath: /path/to/MyApp.ipa
- deviceName: My iPhone
- udid: 00008030-001234567890ABCD (your device's UDID)
- platformVersion: 17.0
2. Run your test scenario
3. Close the session
Testing an Android app:
Test my Android app /path/to/app.apk on the Pixel_6_API_34 emulator:
1. Start the app with auto-grant permissions
2. Get visible elements (use inViewportOnly: false to see all elements)
3. Swipe up to scroll
4. Tap on the "Settings" button using text matching
5. Verify the settings screen is displayed
Advanced element detection:
Test my app and debug layout issues:
1. Start the app session
2. Get visible elements with includeContainers: true to see the layout hierarchy
3. Analyze ViewGroup, FrameLayout, and ScrollView containers
4. Use inViewportOnly: false to find off-screen elements that need scrolling
Hybrid app testing (switching contexts):
Test my hybrid app:
1. Start the Android app session
2. Tap "Open Web" button in native context
3. List available contexts
4. Switch to WEBVIEW context
5. Click the login button using CSS selector
6. Switch back to NATIVE_APP context
7. Verify we're back on the home screen
⚠️ Session Management:
- Only one session (browser OR app) can be active at a time
- Always close sessions when done to free system resources
- To switch between browser and mobile, close the current session first
- Use
close_session({ detach: true })to disconnect without terminating the session on the Appium server - State preservation can be controlled with
noResetandfullResetparameters during session creation - Sessions created with
noReset: trueor withoutappPathwill automatically detach on close
⚠️ Task Planning:
- Break complex automation into smaller, focused operations
- Claude may consume message limits quickly with extensive automation
⚠️ Mobile Automation:
- Appium server must be running before starting mobile sessions
- Ensure emulators/simulators are running and devices are connected
- iOS automation requires macOS with Xcode installed
- iOS Real Devices: Testing on physical iOS devices requires the device's UDID (40-character unique identifier). See Prerequisites section for how to find your UDID
Web (CSS/XPath):
- CSS:
button.my-class,#element-id - XPath:
//button[@class='my-class'] - Text:
button=Exact text,a*=Contains text
Mobile (Cross-Platform):
- Accessibility ID:
~loginButton(works on both iOS and Android) - Android UiAutomator:
android=new UiSelector().text("Login") - iOS Predicate:
-ios predicate string:label == "Login" AND visible == 1 - XPath:
//android.widget.Button[@text="Login"]
State Preservation with noReset/fullReset:
Control app state when creating new sessions using the noReset and fullReset parameters:
| noReset | fullReset | Behavior |
|---|---|---|
true |
false |
Preserve state: App stays installed, data preserved |
false |
false |
Clear app data but keep app installed (default) |
false |
true |
Full reset: Uninstall and reinstall app (clean slate) |
Example with state preservation:
// Preserve login state between test runs
start_app_session({
platform: 'Android',
appPath: '/path/to/app.apk',
deviceName: 'emulator-5554',
noReset: true, // Don't reset app state
fullReset: false, // Don't uninstall
autoGrantPermissions: true,
capabilities: {
'appium:chromedriverExecutable': '/path/to/chromedriver',
'appium:autoWebview': true
}
})
// App launches with existing user data, login tokens, preferences intactDetach from Sessions:
The close_session tool supports a detach parameter that disconnects from the session without terminating it on the
Appium server:
// Detach without killing the session
close_session({detach: true})
// Standard session termination (closes the app and removes session)
close_session({detach: false}) // or just close_session()Sessions created with noReset: true or without appPath will automatically detach on close.
This is particularly useful when:
- Preserving app state for manual testing continuation
- Debugging multi-step workflows (leave session running between tool invocations)
- Testing scenarios where you want the app to remain installed and in current state
- Platform-specific element classification: Automatically identifies interactable elements vs layout containers
- Android: Button, EditText, CheckBox vs ViewGroup, FrameLayout, ScrollView
- iOS: Button, TextField, Switch vs View, StackView, CollectionView
- Multiple locator strategies: Each element provides accessibility ID, resource ID, text, XPath, and platform-specific selectors
- Viewport filtering: Control whether to get only visible elements or all elements including off-screen
- Layout debugging: Optionally include container elements to understand UI hierarchy
Both iOS and Android sessions now support automatic handling of system permissions and alerts:
autoGrantPermissions(default: true): Automatically grants app permissions (camera, location, etc.)autoAcceptAlerts(default: true): Automatically accepts system alerts and dialogsautoDismissAlerts(optional): Set to true to dismiss alerts instead of accepting them
This eliminates the need to manually handle permission popups during automated testing.
- Built with: TypeScript, WebDriverIO, Appium
- Browser Support: Chrome, Firefox, Edge (headed/headless, automated driver management), Safari (headed only; macOS)
- Mobile Support: iOS (XCUITest) and Android (UiAutomator2/Espresso)
- Protocol: Model Context Protocol (MCP) for Claude Desktop integration
- Session Model: Single active session (browser or mobile app)
- Data Format: TOON (Token-Oriented Object Notation) for efficient LLM communication
- Element Detection: XML-based page source parsing with intelligent filtering and multi-strategy locator generation
Every tool call is automatically recorded to a session history. You can inspect sessions and export runnable code via MCP resources — no extra tool calls needed:
wdio://sessions— lists all recorded sessions with type, timestamps, and step countwdio://session/current/steps— step log for the active session, plus a generated WebdriverIO JS script ready to run withwebdriveriowdio://session/{sessionId}/steps— same for any past session by ID
The generated script reconstructs the full session — including capabilities, navigation, clicks, and inputs — as a standalone import { remote } from 'webdriverio' file.
Browser automation not working?
- Ensure Chrome, Firefox, Edge, or Safari is installed (Safari requires macOS)
- Try restarting Claude Desktop completely
- Check that no other WebDriver instances are running
Mobile automation not working?
- Verify Appium server is running:
appium - Check device/emulator is running:
adb devices(Android) or Xcode Devices (iOS) - Ensure correct platform drivers are installed
- Verify app path is correct and accessible
Found issues or have suggestions? Please share your feedback!
WebDriverIO MCP Server (@wdio/mcp)
WebDriverIO MCP Server — это сервер на основе Model Context Protocol (MCP), который позволяет Claude Desktop и другим MCP-клиентам напрямую управлять веб-браузерами (Chrome, Firefox, Edge, Safari) и мобильными приложениями (iOS/Android) через единый интерфейс. Используется WebDriverIO + Appium.
Установка
Способ 1: через конфигурацию Claude Desktop (рекомендуется)
Добавьте в настройки MCP вашего Claude:
{
"mcpServers": {
"wdio-mcp": {
"command": "npx",
"args": ["-y", "@wdio/mcp"]
}
}
}
Способ 2: глобальная установка
npm i -g @wdio/mcp
Затем укажите в настройках MCP:
{
"mcpServers": {
"wdio-mcp": {
"command": "wdio-mcp"
}
}
}
Важно: пакет npm называется
@wdio/mcp, а исполняемый файл —wdio-mcp.
После настройки полностью перезапустите Claude Desktop (на Windows используйте Task Manager для гарантированного закрытия).
Официальное руководство по настройке MCP: https://modelcontextprotocol.io/quickstart/user
Предварительные требования для работы с мобильными приложениями
-
Appium Server — установите глобально:
npm install -g appium -
Платформенные драйверы:
- iOS:
appium driver install xcuitest(требуется Xcode на macOS) - Android:
appium driver install uiautomator2(требуется Android Studio)
- iOS:
-
Устройства/эмуляторы:
- iOS: симулятор (macOS) или физическое устройство (требуется UDID)
- Android: эмулятор или физическое устройство
-
Запустите Appium сервер перед использованием мобильных функций:
appium # По умолчанию сервер слушает http://127.0.0.1:4723
Возможности
Управление браузерами
- Запуск/закрытие сессий Chrome, Firefox, Edge, Safari (headed/headless режимы, произвольные размеры окна)
- Навигация по URL, клики, заполнение форм, получение содержимого
- Получение видимых элементов, дерева доступности, скриншотов
- Управление куками (получить, установить, удалить)
- Прокрутка с настраиваемым расстоянием
- Подключение к запущенному Chrome через
--remote-debugging-port(для тестирования аутентифицированных сессий) - Эмуляция мобильных устройств (iPhone 15, Pixel 7 и др.) для проверки адаптивности
- Запись всех вызовов инструментов — доступна в формате готового скрипта WebdriverIO JS
Управление мобильными приложениями (iOS/Android)
- Тестирование нативных приложений (.app/.ipa для iOS, .apk для Android) через Appium
- Жесты: тап, свайп, долгое нажатие, drag-and-drop
- Управление жизненным циклом приложения: запуск, фон, завершение, проверка состояния
- Переключение между нативным и WebView контекстами для гибридных приложений
- Управление устройством: поворот, блокировка, геолокация, клавиатура, уведомления
- Селекторы: Accessibility ID, XPath, UiAutomator (Android), Predicates (iOS)
Инструменты (краткий обзор)
| Категория | Инструменты |
|---|---|
| Управление сессиями | start_browser, start_app_session, close_session, attach_browser, emulate_device |
| Навигация и взаимодействие | navigate, get_visible_elements, get_accessibility, scroll, take_screenshot |
| Элементы | click_element, set_value |
| Куки (веб) | get_cookies, set_cookie, delete_cookies |
| Жесты (мобильные) | tap_element, swipe, drag_and_drop |
| Жизненный цикл приложения | get_app_state |
| Переключение контекстов | get_contexts, get_current_context, switch_context |
| Управление устройством | rotate_device, hide_keyboard, get_geolocation, set_geolocation |
Примеры использования
Браузерная автоматизация
Простой сценарий тестирования веб-сайта (на примере worldofbooks.com):
1. Открой World of Books (прими все cookies)
2. Получи видимые элементы, чтобы увидеть навигацию
3. Найди художественную книгу
4. Выбери одну и проверь, есть ли варианты NEW и used
5. В конце сообщи результаты
Параметры запуска браузера:
start_browser()— по умолчанию headed, 1280x1080start_browser({ browser: 'firefox' })— Firefoxstart_browser({ headless: true })— headless режимstart_browser({ windowWidth: 1920, windowHeight: 1080 })— произвольные размеры- Передача произвольных возможностей (Chrome extensions, профиль):
start_browser({ headless: false, capabilities: { 'goog:chromeOptions': { args: ['--user-data-dir=/tmp/wdio-mcp-profile', '--load-extension=/path/to/unpacked-extension'] } } })
Подключение к запущенному Chrome:
- Запустите Chrome с флагом
--remote-debugging-port=9222 - В Claude используйте
attach_browser()илиattach_browser({ port: 9222, navigationUrl: 'https://app.example.com' })
Эмуляция устройства (требуется BiDi сессия):
start_browser({ capabilities: { webSocketUrl: true } })
emulate_device() // список доступных пресетов
emulate_device({ device: 'iPhone 15' }) // активация эмуляции
emulate_device({ device: 'reset' }) // сброс на десктоп
Мобильная автоматизация
iOS на симуляторе:
- Запустите сессию приложения, указав
platform: iOS,appPath: /path/to/MyApp.app,deviceName: iPhone 15 Pro - Выполните сценарий (тап, ввод текста, скриншот)
- Закройте сессию
Android на эмуляторе:
- Запустите сессию с
platform: Android,appPath: /path/to/app.apk,deviceName: emulator-5554,autoGrantPermissions: true - Работайте с элементами:
get_visible_elements,swipe,tap_element
Сохранение состояния приложения:
noReset: true, fullReset: false— данные и логин сохраняются между сессиямиnoReset: false, fullReset: false— очистка данных, но приложение остаётсяnoReset: false, fullReset: true— полный сброс (удаление и переустановка)
Тестирование на физическом iOS-устройстве: требуется указать UDID (40 символов).
Гибридные приложения (WebView): используйте get_contexts для списка контекстов, switch_context для переключения между NATIVE_APP и WEBVIEW_*.
Важные замечания
- Одновременно активна только одна сессия (браузер ИЛИ мобильное приложение). Чтобы переключиться, сначала закройте текущую сессию.
- Используйте
close_session({ detach: true })для отключения без завершения сессии на стороне Appium. - Разбивайте сложные сценарии на небольшие шаги — у Claude есть ограничение на количество сообщений.
- Для мобильной автоматизации Appium-сервер должен быть запущен заранее.
- iOS-автоматизация требует macOS с Xcode.
Краткая справка по селекторам
Веб (CSS/XPath):
button.my-class,#element-id(CSS)//button[@class='my-class'](XPath)button=Exact text(по тексту)
Мобильные (кросс-платформенные):
~loginButton(Accessibility ID — работает на iOS и Android)android=new UiSelector().text("Login")(Android UiAutomator)-ios predicate string:label == "Login" AND visible == 1(iOS Predicate)
Этот README создан на основе исходного описания @wdio/mcp.
Какие платформы может автоматизировать WebDriverIO MCP?
Он обеспечивает единую автоматизацию популярных веб-браузеров (Chrome, Firefox, Edge, Safari) и нативных мобильных приложений на платформах iOS и Android.
Какую пользу это приносит ИИ-ассистентам?
Предоставляя богатый набор инструментов и структурированный протокол, он позволяет ИИ-ассистентам понимать контекст страницы, взаимодействовать с элементами интерфейса, выполнять сложные рабочие процессы и записывать скрипты автоматизации.
Есть ли особые требования для автоматизации мобильных приложений?
Да, для автоматизации мобильных приложений требуется глобально установленный сервер Appium, платформозависимые драйверы (например, xcuitest для iOS и uiautomator2 для Android), а также настроенные симуляторы/устройства iOS или эмуляторы/устройства Android.
Каковы его основные возможности автоматизации?
Основные возможности включают всестороннее управление сессиями, расширенное взаимодействие с элементами, жесты касания, переключение контекста для гибридных приложений, эмуляцию мобильных устройств в браузере и автоматический экспорт записей сессий в виде WebDriverIO JS.
Что такое WebDriverIO MCP Server?
WebDriverIO MCP Server — это сервер протокола Model Context Protocol (MCP), который позволяет ИИ-ассистентам, таким как Claude, беспрепятственно взаимодействовать с веб-браузерами и нативными мобильными приложениями и автоматизировать их с помощью WebDriverIO.
Источник: https://mcpmarket.com/server/webdriverio
Комментарии
Комментариев пока нет. Будьте первым.