Skip to main content
Glama
GinzaTech
by GinzaTech

RN Agent Observer

VI · English

RN Agent Observer 2.4.0 — это локальный мост наблюдаемости времени выполнения для React Native/Expo. Инструмент использует одно общее TypeScript-ядро для CLI и MCP, управляет Android через ADB/UIAutomator, получает телеметрию от development-инструментации, экспортирует console/exception/heap/JS CPU profile через Chrome DevTools Protocol от Metro, собирает сетевой трафик per-request без инструментации приложения, формирует screen-understanding с state/headline/actions/UI findings для агента, обеспечивает стабильные по сессии ref-снимки + diff + автоматическую запись replay, записывает видео экрана, сохраняет сессии в SQLite и хранит скриншоты/trace/UI tree как артефакты на диске.

Текущая версия завершает Android v1 на Windows: 45 MCP-инструментов, соответствующий CLI, демо Expo с детерминированными лабораториями, прозрачная эвристическая диагностика и сравнение изображений + структуры UI.

Требования

  • Node.js 22.12 или новее

  • pnpm 9.6

  • Android Platform Tools (adb)

  • Эмулятор Android или физическое устройство с включённой USB-отладкой

  • Expo development build, если нужна собственная телеметрия приложения

Related MCP server: React Native MCP Server

Быстрый старт

pnpm install
pnpm check
adb devices -l
pnpm rn-observe --help
pnpm mcp:check

Направьте observer на приложение Expo/React Native:

$env:RN_OBSERVER_PROJECT_ROOT = 'C:\path\to\expo-app'
$env:RN_OBSERVER_DEVICE_ID = 'emulator-5554'
# Có thể bỏ qua nếu app.json chứa expo.android.package
$env:RN_OBSERVER_APP_ID = 'com.example.app'

pnpm rn-observe launch
pnpm rn-observe observe
pnpm rn-observe understand-screen
pnpm rn-observe ui-model
pnpm rn-observe tap --test-id buy-button
pnpm rn-observe performance
pnpm rn-observe diagnose

Артефакты и данные SQLite создаются в <projectRoot>/.artifacts/; большие бинарные файлы никогда не встраиваются в MCP-ответы.

Детерминированное демо

pnpm --filter @rn-agent-observer/demo-expo android -- --device <device-name>

Демо включает PerformanceLab, NetworkLab, RenderLab, AnimationLab, ErrorLab и VisualLab. NetworkLab использует внутренние фикстуры (0/500/2000мс и HTTP 503), поэтому не зависит от интернет-сервисов. PerformanceLab точно сообщает о длинной JS-задаче 100мс через инструментацию.

MCP

pnpm mcp:check
pnpm mcp:start

Сервер использует stdio. Конфигурация клиента и полный список из 45 инструментов описаны в docs/protocol.md.

Интеграция для AI-агентов

Есть 3 способа для агента (OpenCode/Claude Code/Cursor/Codex...) использовать observer:

1. MCP-сервер (рекомендуется — структурированные инструменты)

{
  "mcpServers": {
    "rn-agent-observer": {
      "command": "node",
      "args": [
        "C:\\abs\\rn-agent-observer\\packages\\mcp-server\\dist\\server.js"
      ],
      "env": {
        "RN_OBSERVER_PROJECT_ROOT": "C:\\path\\to\\expo-app",
        "RN_OBSERVER_DEVICE_ID": "emulator-5554"
      }
    }
  }
}

2. Установка как skill (обучает агента workflow отладки через команды)

npx skills add GinzaTech/rn-agent-observer

Skill находится в skills/rn-agent-observer/SKILL.md — обучает агента циклу observe -> understand-screen -> reproduce -> diagnose -> fix -> understand-screen -> compare, честному чтению метрик и обработке частых ошибок. После установки достаточно сказать «отладь приложение X, оно лагает» — агент сам будет знать, как использовать rn-observe.

3. AGENTS.md (если агент работает прямо в этом репозитории) — уже есть в корне, агент прочитает сам.

Все 3 способа можно использовать одновременно: skill/AGENTS.md обучает workflow, MCP предоставляет инструменты прямого вызова.

Документация

Текущая версия

  • Android/Windows — единственная поддерживаемая цель Observer 2.4.0.

  • ADB не имеет надёжного сигнала JS FPS; поле возвращается как available: false — значения никогда не угадываются.

  • JS blocking, route, React renders и network metadata требуют development-инструментации внутри приложения.

  • Экспорт DevTools через CDP (devtools-export, devtools-profile) и network per-request (metro-network) требуют запущенного Metro и подключённого к нему приложения (adb reverse tcp:8081 tcp:8081); недоступно, когда другая сессия React Native DevTools удерживает соединение.

  • reload --fast использует CDP Page.reload (только JS); автоматически переключается на force-stop, когда Metro недоступен.

  • Приложение без инструментации: используйте metro-network (CDP), app-state (foreground activity, PID) и device-network (счётчики байтов на уровне устройства, не привязанные к приложению) как запасные доказательства.

  • record (screenrecord) ограничен 180 секундами на клип в Android.

  • Perfetto trace поддерживается на Android; глубокий анализ trace по-прежнему выполняется в Perfetto UI/Android Studio.

  • CDP-команды ставятся в очередь между процессами; внешний React Native DevTools всё равно должен быть закрыт, так как он не участвует в блокировке observer.

  • session stop автоматически создаёт replay; ref в сессии стабильны при reorder/scroll; отсутствующая сессия выдаёт EVIDENCE_NOT_RECORDED.

  • understand-screen/MCP understand_screen возвращает route из инструментации, когда он есть, screen state, headline, text/action refs, UI findings и screenshot/UI-tree evidence; повторные вызовы обнаруживают неизменную загрузку. Классификация эвристическая, а значения текстовых полей всегда редактируются (redact).

  • ui-model/MCP runtime_ui_model разбирает TSX с помощью TypeScript AST для получения component + file:line, затем соотносит с инструментацией и нативным деревом. Результат различает rendered, visible/offscreen/hidden/unmounted/flattened-or-unobserved, enabled и canPress с указанием причины.

  • Babel-плагин только для разработки автоматически добавляет testID из исходного кода и оборачивает onPress; session stop собирает interaction start/success/error и включает tap с testID в replay. Аргументы обработчиков, props и значения полей ввода никогда не записываются.

  • Observer по умолчанию не собирает тело сетевых запросов. Опциональное включение только для разработки использует allowlist с fail-closed, но всё равно должно ограничиваться фикстурами.


RN Agent Observer (English)

RN Agent Observer 2.4.0 is a local runtime observability bridge for React Native/Expo. It uses one shared TypeScript core behind both a CLI and an MCP server, drives Android through ADB/UIAutomator, receives telemetry from development instrumentation, exports console/exceptions/heap/JS CPU profiles through Metro's Chrome DevTools Protocol, captures per-request network traffic without app instrumentation, produces structured screen understanding (state/headline/actions/UI findings) for agents, provides session-stable ref snapshots + diffs + automatically recorded replay scripts, records on-screen video, persists sessions in SQLite, and keeps screenshots/traces/UI trees as on-disk artifacts.

The current release completes Android v1 on Windows: 45 MCP tools, the matching CLI, an Expo demo app with deterministic labs, transparent heuristic diagnosis, and pixel + structural UI comparison.

Requirements

  • Node.js 22.12 or newer

  • pnpm 9.6

  • Android Platform Tools (adb)

  • An Android emulator or physical device with USB debugging enabled

  • An Expo development build if you need app-specific telemetry

Quick Start

pnpm install
pnpm check
adb devices -l
pnpm rn-observe --help
pnpm mcp:check

Point the observer at your Expo/React Native app:

$env:RN_OBSERVER_PROJECT_ROOT = 'C:\path\to\expo-app'
$env:RN_OBSERVER_DEVICE_ID = 'emulator-5554'
# Optional when app.json contains expo.android.package
$env:RN_OBSERVER_APP_ID = 'com.example.app'

pnpm rn-observe launch
pnpm rn-observe observe
pnpm rn-observe understand-screen
pnpm rn-observe ui-model
pnpm rn-observe tap --test-id buy-button
pnpm rn-observe performance
pnpm rn-observe diagnose

Artifacts and SQLite data are created under <projectRoot>/.artifacts/; large binaries are never embedded in MCP responses.

Deterministic demo

pnpm --filter @rn-agent-observer/demo-expo android -- --device <device-name>

The demo ships PerformanceLab, NetworkLab, RenderLab, AnimationLab, ErrorLab, and VisualLab. NetworkLab uses internal fixtures (0/500/2000ms and HTTP 503) so it never depends on Internet services. PerformanceLab reports its intentional 100ms long JS task precisely through instrumentation.

MCP

pnpm mcp:check
pnpm mcp:start

The server speaks stdio. Client configuration and the full list of 45 tools are documented in docs/protocol.md.

Documentation

AI agent integration

Three ways for agents (OpenCode/Claude Code/Cursor/Codex...) to use the observer:

1. MCP server (recommended — structured tools)

{
  "mcpServers": {
    "rn-agent-observer": {
      "command": "node",
      "args": [
        "C:\\abs\\rn-agent-observer\\packages\\mcp-server\\dist\\server.js"
      ],
      "env": {
        "RN_OBSERVER_PROJECT_ROOT": "C:\\path\\to\\expo-app",
        "RN_OBSERVER_DEVICE_ID": "emulator-5554"
      }
    }
  }
}

2. Install as a skill (teaches the agent the debugging workflow via CLI)

npx skills add GinzaTech/rn-agent-observer

The skill lives at skills/rn-agent-observer/SKILL.md — it teaches the observe -> understand-screen -> reproduce -> diagnose -> fix -> understand-screen -> compare loop, how to read metrics honestly, and common failure recovery. After installing, just say "app X feels laggy" and the agent knows to reach for rn-observe.

3. AGENTS.md (when the agent works inside this repo) — already present at the repo root; agents read it automatically.

All three can be combined: the skill/AGENTS.md teach the workflow, MCP provides directly callable tools.

Current boundary

  • Android/Windows is the only supported target of Observer 2.4.0.

  • ADB has no trustworthy JS FPS signal; the field is returned as available: false — values are never guessed.

  • JS blocking, route, React renders, and network metadata require development instrumentation inside the app.

  • CDP features (devtools-export, devtools-profile, metro-network) need Metro running for the right app and the app connected to it (adb reverse tcp:8081 tcp:8081); they cannot attach while another React Native DevTools session holds the connection.

  • reload --fast uses CDP Page.reload (JS-only) and automatically falls back to force-stop when Metro is unavailable.

  • Observer CDP commands queue across processes; external React Native DevTools must still be closed because it does not participate in the observer lock.

  • session stop automatically writes a replay, session refs survive reorder/scroll, and missing sessions produce EVIDENCE_NOT_RECORDED.

  • understand-screen/MCP understand_screen returns the instrumented route when available, screen state, headline, text/action refs, UI findings, and screenshot/UI-tree evidence; repeated calls detect unchanged loading. Classification is heuristic and text-field values are always redacted.

  • ui-model/MCP runtime_ui_model parses TSX with the TypeScript AST for component + file:line, then correlates source with instrumentation and the native tree. It distinguishes rendered, visible/off-screen/hidden/unmounted/flattened-or-unobserved, enabled, and evidence-backed canPress states.

  • The development-only Babel plugin injects a source-derived testID and wraps onPress; session stop collects interaction start/success/error and promotes testID taps into replay. Handler arguments, props, and input values are never recorded.

  • Network body capture is off by default. Development-only opt-in uses fail-closed allowlists and should still be limited to fixtures.

  • Apps without instrumentation: use metro-network (CDP), app-state (foreground activity, PID), and device-network (device-level byte counters, not app-attributed) as fallback evidence.

  • record (screenrecord) is limited to 180s per clip by Android.

  • Perfetto tracing is supported on Android; deep trace analysis remains in Perfetto UI/Android Studio.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    A
    maintenance
    This MCP server enables real-time debugging and inspection of running React Native apps, providing access to console logs, errors, network requests, navigation state, storage, and performance profiling.
    1
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    A plugin-based MCP server for React Native runtime debugging, inspection, and automation via Chrome DevTools Protocol. Works with Expo, bare React Native, and any Metro + Hermes project without app code changes.
    822 npm
    85
    MIT
  • A
    license
    B
    quality
    B
    maintenance
    An MCP server that gives AI agents hands-on control of a live React Native app, enabling UI taps, screenshots, UI/component trees, native logs, and JS/React profiling to debug, verify fixes, and diagnose performance issues.
    16
    4 npm
    MIT