firefox-devtools-mcp
Firefox DevTools MCP
Сервер протокола Model Context Protocol (MCP) для автоматизации Firefox через WebDriver BiDi (с использованием Selenium WebDriver). Работает с Claude Code, Claude Desktop, Cursor, Cline и другими MCP-клиентами.
Репозиторий: https://github.com/mozilla/firefox-devtools-mcp
Примечание: Этот MCP-сервер требует локальной установки браузера Firefox и не может работать на облачных хостингах, таких как glama.ai. Используйте
npx firefox-devtools-mcp@latestдля запуска локально или используйте Docker с предоставленным Dockerfile.
Требования
Node.js ≥ 20.19.0
Установленный Firefox 100+ (определяется автоматически или передается через
--firefox-path)
Related MCP server: gecko-mcp
Установка и использование с Claude Code (npx)
Рекомендуется использовать npx, чтобы всегда запускать последнюю опубликованную версию из npm.
Вариант A — Claude Code CLI
claude mcp add firefox-devtools npx firefox-devtools-mcp@latestПередавайте параметры как аргументы или переменные окружения. Примеры:
# Headless + viewport via args
claude mcp add firefox-devtools npx firefox-devtools-mcp@latest -- --headless --viewport 1280x720
# Or via environment variables
claude mcp add firefox-devtools npx firefox-devtools-mcp@latest \
--env START_URL=https://example.com \
--env FIREFOX_HEADLESS=trueВариант B — Редактирование JSON-настроек Claude Code
Добавьте в файл конфигурации Claude Code:
macOS:
~/Library/Application Support/Claude/Code/mcp_settings.jsonLinux:
~/.config/claude/code/mcp_settings.jsonWindows:
%APPDATA%\Claude\Code\mcp_settings.json
{
"mcpServers": {
"firefox-devtools": {
"command": "npx",
"args": ["-y", "firefox-devtools-mcp@latest", "--headless", "--viewport", "1280x720"],
"env": {
"START_URL": "about:home"
}
}
}
}Вариант C — Вспомогательный скрипт (локальная сборка для разработки)
npm run setup
# Choose Claude Code; the script saves JSON to the right pathПопробуйте с MCP Inspector
npx @modelcontextprotocol/inspector npx firefox-devtools-mcp@latest --start-url https://example.com --headlessЗатем вызывайте инструменты, такие как:
list_pages,select_page,navigate_pagetake_snapshot, затемclick_by_uid/fill_by_uidlist_network_requests(постоянный захват),get_network_requestscreenshot_page,list_console_messages
Параметры CLI
Вы можете передавать флаги или переменные окружения (имена справа):
--firefox-path— абсолютный путь к исполняемому файлу Firefox--headless— запуск без графического интерфейса (FIREFOX_HEADLESS=true)--viewport 1280x720— начальный размер окна--profile-path— использование определенного профиля Firefox--firefox-arg— дополнительные аргументы Firefox (можно повторять)--start-url— открыть этот URL при запуске (START_URL)--accept-insecure-certs— игнорировать ошибки TLS (ACCEPT_INSECURE_CERTS=true)--connect-existing— подключиться к уже запущенному Firefox вместо запуска нового (CONNECT_EXISTING=true)--marionette-port— порт Marionette для режима подключения к существующему экземпляру, по умолчанию 2828 (MARIONETTE_PORT)--pref name=value— установить настройки Firefox при запуске черезmoz:firefoxOptions(можно повторять)--enable-script— включить инструментevaluate_script, который выполняет произвольный JavaScript в контексте страницы (ENABLE_SCRIPT=true)--enable-privileged-context— включить инструменты привилегированного контекста: список/выбор привилегированных контекстов, выполнение привилегированных скриптов, получение/установка настроек Firefox и список расширений. ТребуетMOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1(ENABLE_PRIVILEGED_CONTEXT=true)
Примечание о
--pref: Когда Firefox работает в режиме автоматизации, он применяет RecommendedPreferences, которые изменяют поведение браузера для тестирования. Параметр--prefпозволяет при необходимости переопределить эти значения по умолчанию.
Подключение к существующему Firefox
Используйте --connect-existing для автоматизации вашего реального сеанса просмотра — с сохранением файлов cookie, авторизаций и открытых вкладок:
# Start Firefox with Marionette enabled
firefox --marionette
# Run the MCP server
npx firefox-devtools-mcp --connect-existing --marionette-port 2828Или установите marionette.enabled в true в about:config (или user.js), чтобы включать Marionette при каждом запуске.
Функции, зависящие от BiDi (события консоли, события сети), недоступны в режиме подключения к существующему экземпляру; все остальные функции работают в обычном режиме.
Внимание: Не оставляйте Marionette включенным во время обычного просмотра веб-страниц. Он устанавливает
navigator.webdriver = trueи изменяет другие сигналы отпечатков браузера, что может вызвать срабатывание защиты от ботов на сайтах, защищенных Cloudflare, Akamai и т. д. Включайте Marionette только тогда, когда вам нужна автоматизация MCP, а затем перезапускайте Firefox в обычном режиме.
Обзор инструментов
Страницы: список/новая/переход/выбор/закрыть
Снимок/UID: сделать/разрешить/очистить
Ввод: клик/наведение/заполнение/перетаскивание/загрузка файла/заполнение формы
Сеть: список/получить (по ID, фильтры, постоянный захват)
Консоль: список/очистить
Скриншот: страницы/по UID (с необязательным
saveToдля сред CLI)Скрипт: evaluate_script
Привилегированный контекст: список/выбор привилегированных ("chrome") контекстов, evaluate_privileged_script (требует
MOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1)WebExtension: install_extension, uninstall_extension, list_extensions (список требует
MOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1)Управление Firefox: get_firefox_info, get_firefox_output, restart_firefox, set_firefox_prefs, get_firefox_prefs
Утилиты: принять/отклонить диалог, история назад/вперед, установить размер окна
Оптимизация скриншотов для Claude Code
При использовании скриншотов в Claude Code CLI данные изображения в формате base64 могут занимать значительный объем контекста. Используйте параметр saveTo для сохранения скриншотов на диск:
screenshot_page({ saveTo: "/tmp/page.png" })
screenshot_by_uid({ uid: "abc123", saveTo: "/tmp/element.png" })Файл можно просмотреть с помощью инструмента Read в Claude Code, не влияя на размер контекста.
Локальная разработка
npm install
npm run build
# Run with Inspector against local build
npx @modelcontextprotocol/inspector node dist/index.js --headless --viewport 1280x720
# Or run in dev with hot reload
npm run inspector:devТестирование
npm run test:run # all tests once (unit + integration)
npm test # watch modeСм. docs/testing.md для получения полной информации о запуске конкретных наборов тестов, покрытии сценариев e2e и известных проблемах.
Устранение неполадок
Firefox не найден: передайте
--firefox-path "/Applications/Firefox.app/Contents/MacOS/firefox"(macOS) или правильный путь для вашей ОС.Первый запуск медленный: Selenium настраивает сеанс BiDi; последующие запуски будут быстрее.
Устаревшие UID после навигации: сделайте новый снимок (
take_snapshot) перед использованием инструментов UID.Windows 10: Ошибка при обнаружении MCP-сервера 'firefox-devtools': MCP error -32000: Connection closed
Решение 1 Оберните с помощью
cmd /c(подробности):"mcpServers": { "firefox-devtools": { "command": "cmd", "args": ["/c", "npx", "-y", "firefox-devtools-mcp@latest"] } }Решение 2 Используйте абсолютный путь к
npx(настройте расширение —.cmd,.bat,.exeили.ps1— в соответствии с вашей настройкой):"mcpServers": { "firefox-devtools": { "command": "C:\\nvm4w\\nodejs\\npx.ps1", "args": ["-y", "firefox-devtools-mcp@latest"] } }
Версионирование
API до версии 1.0: версии начинаются с
0.x. Используйте@latestс npx для получения последнего релиза.
CI и релизы
Включены GitHub Actions для CI, релизов и публикации в npm. Подробности и необходимые секреты см. в docs/ci-and-release.md.
Проблемы и участие в разработке
Проблемы отслеживаются на Bugzilla в разделе product: Developer Infrastructure, component: AI for Development.
Для вопросов и обсуждений присоединяйтесь к Matrix-комнате #firefox-devtools-mcp.
Автор
Поддерживается Mozilla.
Available Tools
36 toolsaccept_dialogA
Accept browser dialog. Provide promptText for prompts.
Inputs: promptText.
clear_downloadsA
Clear the tracked downloads buffer.
Inputs: no named parameters.
clear_snapshotC
Clear snapshot UIDs. Usually not needed.
Inputs: no named parameters.
click_by_uidA
Click element by UID. Set dblClick for double-click.
Inputs: uid (required), dblClick.
close_firefox_sessionA
Ends the browser session. If the server connected to your existing Firefox, this releases the connection and leaves Firefox running. If the server started Firefox itself, this closes it. Call this when the browser task is complete and no further browser interaction is expected.
Inputs: no named parameters.
close_pageA
Close tab by index.
Inputs: pageIdx (required).
dismiss_dialogA
Dismiss browser dialog.
Inputs: no named parameters.
drag_by_uid_to_uidB
Drag element to another (HTML5 drag events).
Inputs: toUid (required), fromUid (required).
evaluate_scriptA
Run a JS function in the page and return its result. Prefer this for targeted reads (a value, text, computed style, whether an element exists) instead of a full take_snapshot. Use the UID interaction tools for clicking, typing, and filling.
Inputs: function (required), args, saveTo, preview, +2 more.
fill_by_uidA
Fill text input/textarea or pick a select option by UID.
Inputs: uid (required), value (required).
fill_form_by_uidA
Fill multiple form fields at once.
Inputs: elements (required).
get_firefox_infoARead-only
Get information about the current Firefox instance configuration, including binary path, environment variables, and output file location.
Inputs: no named parameters.
get_firefox_outputARead-only
Retrieve Firefox output (stdout/stderr including MOZ_LOG, warnings, crashes, stack traces). Returns recent output from the capture file. Use filters to focus on specific content.
Inputs: grep, lines, since.
get_page_textARead-only
Get the visible text of the page (document.body.innerText). Caps at maxLength (default 20000 chars); saveTo saves the full text to a file.
Inputs: saveTo, preview, maxLength.
hover_by_uidB
Hover over element by UID.
Inputs: uid (required).
install_extensionA
Install a Firefox extension using WebDriver BiDi webExtension.install command. Supports installing from archive (.xpi/.zip), base64-encoded data, or unpacked directory.
Inputs: type (required), path, value, permanent.
list_downloadsARead-only
List downloads tracked since startup, including status and saved file path.
Inputs: limit, format, status, urlContains.
list_extensionsBRead-only
List installed Firefox extensions using the WebDriver BiDi webExtension.moz:listExtensions command.
Inputs: ids, name, isActive.
list_pagesARead-only
List open tabs (index, title, URL). Selected tab is marked.
Inputs: no named parameters.
new_pageB
Open new tab at URL. Returns tab index.
Inputs: url (required), wait.
press_keyA
Press a single key, optionally with modifiers, to submit, dismiss, navigate or trigger a shortcut. Not for entering text: use fill_by_uid instead.
Inputs: key (required), uid.
print_pageARead-only
Print the current page to a PDF file using print CSS. Returns the saved file path.
Inputs: saveTo, landscape, background.
resolve_uid_to_selectorARead-only
Resolve UID to CSS selector. Fails if the element is gone.
Inputs: uid (required).
screencast_startA
Start recording a screencast (video) of the current page viewport, saving the output to a file in the downloads directory. Returns a screencast id to pass to screencast_stop. Multiple recordings can run at once.
Inputs: width, height, context, mimeType, +1 more.
screencast_stopA
Stop an in-progress screencast recording started with screencast_start and finalize the video file. Returns the path to the saved file.
Inputs: screencast.
screenshot_by_uidBRead-only
Capture element screenshot by UID as base64 PNG.
Inputs: uid (required), saveTo.
screenshot_pageBRead-only
Capture viewport screenshot as base64 PNG. Set fullPage for the whole scrollable document.
Inputs: saveTo, fullPage.
select_pageA
Select active tab by index, URL, or title. Index takes precedence.
Inputs: url, title, pageIdx.
set_download_behaviorA
Control how downloads are handled: allow (save to a destination folder), deny (cancel), or reset to default. Avoids the native save-file dialog. Requires a recent Firefox.
Inputs: behavior (required), downloadFolder.
set_viewport_sizeA
Set viewport dimensions in pixels. Applies to the selected tab only.
Inputs: width (required), height (required).
take_snapshotARead-only
Capture DOM snapshot with stable UIDs. A UID stays valid across snapshots until its element is removed or the page navigates. Output caps at maxLines (default 100); scope with selector or dump the full tree with saveTo.
Inputs: saveTo, preview, maxDepth, maxLines, +4 more.
type_textA
Type text key by key into the focused element, optionally followed by a key such as Enter. Use fill_by_uid to set the value of a known input; use this for elements that only react to real typing, such as autocomplete fields and rich text editors.
Inputs: text (required), uid, submitKey.
uninstall_extensionA
Uninstall a Firefox extension using WebDriver BiDi webExtension.uninstall command. Requires the extension ID returned by install_extension or obtained from list_extensions.
Inputs: id (required).
upload_file_by_uidB
Upload file to file input by UID.
Inputs: uid (required), filePath (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 36 tools
Most tools target a distinct resource+action, and the descriptions actively steer between near-neighbors (fill_by_uid vs type_text vs press_key, screenshot_page vs screenshot_by_uid, take_snapshot vs get_page_text vs evaluate_script). The only real overlaps are the fill family (fill_by_uid, fill_form_by_uid, type_text) and the three 'read the page' tools, but each carries explicit guidance on when to use it.
The majority follow verb_noun (click_by_uid, list_pages, take_snapshot, install_extension), but there are deviations: noun-first forms like screencast_start/screencast_stop (vs the otherwise dominant verb_noun, cf. navigate_history), set_download_behavior/set_viewport_size, and noun-as-verb names like screenshot_by_uid, screenshot_page, drag_by_uid_to_uid. Still readable and predictable in spirit, but not a single consistent convention.
36 tools is heavy for a browser automation surface; most earn their place, but there is clear consolidation headroom (clear_snapshot, resolve_uid_to_selector, clear_downloads, get_firefox_info are marginal, and the fill/type/screenshot variants could be merged). The count pushes well past the 15-tool comfort zone into territory where selection cost is real.
Core lifecycle is well covered: tabs, navigation, history, viewport, UID-based interaction, forms, uploads, dialogs, downloads, extensions, screenshots, PDF printing, screencast, and session teardown. Notable devtools gaps remain: no console message retrieval distinct from raw Firefox stdout/stderr, no network request inspection/interception, no explicit wait-for-element/condition, and no frame/iframe or cookie/storage management.
Maintenance
Related MCP Connectors
Official Browserless MCP server: browser automation, scraping, screenshots and PDFs for AI agents.
Cloud browser, web extraction, screenshots, and remote CDP tools for AI agents.
Unofficial Browserless MCP — wraps the Browserless headless-Chromium REST API (browserless.io)
Automate cloud Chrome—navigate, click, type, screenshot, run code, record screen video
Related MCP Servers
- AlicenseCqualityDmaintenanceProvides Firefox browser automation capabilities through Playwright, allowing control of Firefox from MCP-enabled applications with features for basic automation and advanced multi-tab debugging.2930MIT
- AlicenseAqualityCmaintenanceDrive Firefox-based browsers (Floorp, LibreWolf, Zen, Waterfox, Mullvad, Firefox) from any MCP client — read pages, screenshot, click, fill forms and manage tabs in your real session, over Marionette/WebDriver. OS input & JS eval locked by default.4163 npm2MIT
- FlicenseAqualityDmaintenanceModel Context Protocol server for automating Firefox via WebDriver BiDi, enabling page navigation, snapshots, input, network monitoring, and console debugging for AI agents in MCP clients.31-
- AlicenseBqualityBmaintenanceEnables AI agents to drive a user-launched Firefox instance via its native Marionette protocol, providing precise DOM actuation like clicking, typing, uploading files, taking screenshots, and evaluating JavaScript.1811 npm1GPL 2.0