1. The Full-Stack Mental Model: Cloud Meets Pixels
Modern mobile agents no longer stop at writing Kotlin files in the dark. By pairing Firebase MCP on the cloud side with the android CLI and its live UI sidecars on the device side, an agent can verify schemas, builds, Compose bounds, and tap-by-tap user journeys in one continuous loop.
Quick Navigation
android CLI & Compose SidecarPart 6
2. Install, Auth & Tool MatrixPart 2
8. Device Hub & XML JourneysPart 7
3. Annotated Cockpit UI TourPart 3
9. 5 Copy-Paste Production RecipesPart 8
4. Firebase MCP & Data ConnectPart 4
10. App Check & Multi-Device OpsPart 9
5. AI Logic Kotlin & Config AnatomyPart 5
11. Cross-Tool Synergy PipelinePart 10
6. Troubleshooting & Pre-FlightPart 11
Architecture: Two Bridges Closing the Mobile Loop
npx skills add firebase/agent-skills with android init and android skills add teaches your agent idiomatic Security Rules patterns, Play Integrity guards, and fast UI inspection rules before it writes a single line of code.
2. Installation, Auth & Backend-to-Device Matrix
Set up both toolchains in under three minutes. Keep Firebase MCP tightly scoped per project directory while initializing the android CLI globally for fast SDK, emulator, and Studio access.
android CLIInstall the native binary for your host OS, then run android init to configure directories and default skills:
Discover domain skills anytime via android skills find compose and install with android skills add <id>.
Firebase MCP runs as a built-in subcommand of firebase-tools. Refresh OAuth credentials, add agent skills, and pin MCP flags:
Pinning --dir and --only prevents accidental edits across unrelated Firebase projects.
Android Tooling Decision Matrix: Pick the Fastest Layer
| Layer | Primary Strength | When to Use It | What to Avoid |
|---|---|---|---|
Raw adb |
Low-level shell, input injection, logcat, port tunnels | Sending taps, swipes, input text, or checking getprop sys.boot_completed |
Slow full-APK installs or manual UI hierarchy XML parsing |
android CLI |
Delta installs, JSON layout, screen resolve, SDK & docs | android run --use-delta-install, layout, screen capture --annotate, docs search |
Running android preview render directly outside the sidecar |
| UI Sidecars | Persistent HTTP servers + live IDE visual panes | Inspecting bounds_url Compose trees and mirroring live devices in Device Hub |
Sending browser Origin headers or omitting X-Sidecar-Conversation |
| Android Studio Bridge | Live PSI/AST symbol index & inspection engine | android studio analyze-file, find-declaration, find-usages, version-lookup |
Assuming Studio is open without checking android studio check first |
"command": "npx" with "args": ["-y", "firebase-tools@latest", "mcp", "--dir", "/abs/path", "--only", "firestore,auth,dataconnect"].
3. Annotated Android Device Hub & Compose Preview Cockpit
When both Android sidecar plugins run alongside your terminal, you get instant pixel feedback in the IDE while your agent inspects exact coordinates, composable bounds, and incremental layout diffs over loopback HTTP and CLI.
X-Sidecar-Conversation: conv-828aSession:
gradle://.?:app@debug 3
bounds_url → HomeScreen.kt:94semantics:
text="Ask Gemini", clickable
{"text":"Tap to Speak","state":["focused"],"center":"[540,1820]"}
$ android screen capture --annotate -o /tmp/s.png 7
$ adb shell $(android screen resolve --screenshot /tmp/s.png --string "input tap #7")
Seven-Point Cockpit Reference Legend
~/.android/cli/sidecars/compose-preview.json to get the active dynamic loopback port, then verify with GET /api/status.X-Sidecar-Conversation: <id> on POST /api/session, POST /api/render, and GET /api/state so the pane renders your thread.POST /api/session sets project_dir, Gradle/Bazel reference, fqns, and "wait": true to build and render cleanly.bounds_url): Inspect sourceLocation, semantics, and modifiers in JSON to audit padding and accessibility without guessing./mirror/ws): Streams live AVD or USB device video and input in the Device Hub UI; agents inspect and drive devices via CLI and adb.android layout --pretty --diff first to capture exact element bounds, focus states, and changes in minimal tokens.android screen capture --annotate and substitute box #N centers with android screen resolve.
4. Firebase MCP: Inspecting Live Cloud State & Rules
Running firebase-tools@latest mcp gives your coding agent a live, least-privilege window into your Firebase backend—so database schemas, Security Rules, GraphQL operations, and deploy logs stay aligned with your Android client.
firebase mcp routes agent queries through directory-pinned permissions and Security Rules checks into Firestore, Data Connect GraphQL, and App Check gates.
Core Firebase MCP Capability Groups (--only)
| Capability Group | What the Agent Can Inspect & Validate | Android Synergy Payoff |
|---|---|---|
| Firestore & RTDB + Rules | Query documents, inspect collection indexes, and validate Security Rules logic before deploy | Matches Kotlin data classes and ensures queries will not fail with PERMISSION_DENIED |
| Data Connect (GraphQL) | Author PostgreSQL-backed GraphQL schemas, mutations, and generated client connectors | Generates strongly typed Kotlin SDK calls ready for Compose UI state flows |
| App Hosting & Functions | Tail build failures, Cloud Functions runtime logs, and rollout environment config | Diagnoses backend webhook or server-side token errors in seconds without browser tabs |
| Auth, Crashlytics, FCM & RC | Look up Auth users, triage top Crashlytics stack traces, inspect Remote Config & FCM | Pairs real crash frames with android studio find-declaration to patch root causes |
| AI Logic Schema Consulting | Verify Gemini Developer API / Vertex AI backend setup, App Check enforcement, and quotas | Prevents client SDK mismatches before testing gemini-3.8-flash or gemini-3.8-live |
firebase/agent-skills for Idiomatic Generationnpx skills add firebase/agent-skills in your workspace so the agent loads battle-tested guidance on Firestore indexing, Data Connect query security, and App Check token flows automatically whenever Firebase files appear.
5. Firebase AI Logic + App Check: Kotlin & Prompt Anatomy
Firebase AI Logic lets your Android app invoke Gemini directly from Kotlin without standing up a custom proxy server—while Firebase App Check proves every request originates from your genuine app binary.
35.1.0)Register your app's SHA-256 fingerprint in Firebase Console under Play Integrity, and install the matching provider in Application.onCreate():
3. Invoking Gemini 3.8 Flash & Gemini 3.8 Live in Kotlin
Anatomy of a Complete Full-Stack Agent Prompt
6. android CLI Mastery & Compose Preview Sidecar Loop
Replace slow trial-and-error Gradle cycles with fast delta deployments, live Android Knowledge Base queries, and headless Compose Preview rendering that exposes every composable's coordinates and accessibility semantics.
- SDK & Scaffolding: Manage toolchains with
android sdk list --all/install, scaffold templates viaandroid create, and inspect build targets withandroid describe. - Fast Delta Deploy:
android installandandroid run --use-delta-installship only changed dex and resource deltas. - Wear & Multi-Surface Types: Pass
--typeforACTIVITY,WATCH_FACE,TILE,COMPLICATION,DECLARATIVE_WATCH_FACE, orWEAR_WIDGET. - Authoritative Docs: Query current APIs via
android docs search "App Check"and read full pages withandroid docs fetch kb://....
Discover every @Preview and MultiPreview function in JSON before rendering:
Flavor Gotcha: Modules with product flavors have no bare debug variant. Always include flavors first, such as gradle://.?:feature:home@demoDebug.
3. Compose Preview Sidecar Loop (Save First, Then Render!)
bounds_url--component-tree is active (on by default), GET /api/state returns a bounds_url JSON tree for every rendered PNG. Read sourceLocation (fileName, lineNumber) to jump straight to the composable, check modifiers (padding, clickable, size), and verify semantics (text, contentDescription, role, testTag) to catch inaccessible icon buttons automatically.
7. Device Hub Sidecar, Visual Targeting & XML Journeys
Previews confirm static layout; real journeys prove behavior. Combine the Device Hub sidecar and android emulator CLI with JSON-first inspection, visual box resolution, and strict sequential XML journey scripts.
android layout and screen resolve.
- AVD Control: Use
android emulator list|start|stop|create|removeor Device HubGET /api/devices(never start duplicate jobs on one device). - Wait for Full Boot: Online emulators may still be booting. Run:
adb -s <serial> wait-for-device shell 'while [ -z "$(getprop sys.boot_completed)" ]; do sleep 1; done' - JSON First, Pixels Second: Start with
android layout --device <serial> --pretty(add--diffafter actions). Switch toandroid screen capture --annotate -o /tmp/screen.pngfor WebViews or custom canvases, then inspect the PNG visually.
<journey>- Tap Resolved Boxes:
adb -s <serial> shell $(android screen resolve --screenshot /tmp/screen.png --string "input tap #7") - Safe Text & Slow Scrolls: Confirm
"focused"in elementstate, encode spaces as%s("Hello%sworld"), and scroll slowly over 500ms (adb shell input swipe 250 400 250 200 500). - Sequential XML Journeys: Execute each
<action>strictly as written in order; stop immediately on failure or crash and emit a Markdown report marking steps✅or❌.
8. 5 Real-World Copy-Paste Recipes
Drop these five battle-tested command and code recipes straight into your terminal, Gradle config, or agent prompt to eliminate repetitive boilerplate.
| Recipe & Goal | Copy-Paste Snippet / Command | Expected Outcome |
|---|---|---|
| 1. Scoped Firebase MCP + Skills Bootstrap | npx -y firebase-tools@latest login --reauth && npx skills add firebase/agent-skills && claude mcp add firebase npx -- -y firebase-tools@latest mcp --dir /abs/app --only firestore,auth,dataconnect |
Installs Firebase idioms and pins MCP strictly to your target directory and services. |
2. App Check Protected gemini-3.8-live Screen |
Firebase.initialize(this); Firebase.appCheck.installAppCheckProviderFactory(DebugAppCheckProviderFactory.getInstance()); val live = Firebase.ai.liveModel(modelName = "gemini-3.8-live").connect() |
Establishes a real-time Live session with automatic App Check attestation headers. |
| 3. Fast Delta Run + Studio Analysis Loop | android studio check && android studio analyze-file --file app/src/main/java/ChatVm.kt && android run --device emulator-5554 --use-delta-install |
Catches Kotlin lint/type issues via Studio PSI before shipping a delta APK to the AVD. |
| 4. Headless Compose Accessibility Audit | PORT=$(jq -r .port ~/.android/cli/sidecars/compose-preview.json) && curl -s -X POST http://127.0.0.1:$PORT/api/session -H "X-Sidecar-Conversation: $CID" -H "Content-Type: application/json" -d '{"project_dir":"/abs/app","reference":"gradle://.?:app@debug","fqns":["com.app.HomeKt.HomePreview"],"wait":true}' |
Renders the preview in your conversation pane and writes bounds_url semantics JSON. |
| 5. XML Journey Visual & Diff Audit | android screen capture --device emulator-5554 --annotate -o /tmp/s.png && adb -s emulator-5554 shell $(android screen resolve --screenshot /tmp/s.png --string "input tap #7") && android layout --device emulator-5554 --diff --pretty |
Resolves visual box #7 to screen coordinates, taps it, and returns only changed UI nodes. |
POST /api/renderPOST /api/render request in the same parallel batch—Wait until all Kotlin file writes finish on disk so Gradle does not compile stale code.
9. App Check Enforcements, Least-Privilege MCP & Fleet Ops
Production AI mobile apps require tight boundaries at every hop—limiting what your coding agent can mutate in Firebase, proving app identity at runtime, and testing safely across remote hardware.
- Always Pin
--dir: Pass an absolute project path so agents never read or write the wrong Firebase alias. - Scope With
--only: Enable only the tool groups needed for the sprint (for examplefirestore,auth,dataconnect) instead of exposing destructive project-wide surfaces. - Review Rules Before Deploy: Ask the agent to validate Firestore and Storage Security Rules before updating client queries.
- Local Debug Tokens: Register the Logcat token printed by
firebase-appcheck-debugin Firebase Console for emulator tests. - Release Attestation: Swap to
firebase-appcheck-playintegrityand add your Play App Signing SHA-256 fingerprint in Console. - Enforce Last: Monitor App Check metrics for
gemini-3.8-flashandgemini-3.8-livetraffic before flipping enforcement on.
When Android Studio is open, let the agent tap directly into its live PSI index rather than grepping blindly:
android studio check— verify running IDE instances.android studio find-declaration&find-usages— trace Compose callbacks and ViewModels accurately.android studio version-lookup— fetch latest Maven artifacts likefirebase-bom:35.1.0and SDK tools.
Scale beyond local emulators when testing real sensors, Play Integrity, and WebViews:
- Remote Physical Lab: Reserve and connect to cloud hardware via
android device remote. - Tunnel Latency: Screen captures over tunneled devices take longer; re-capture only after state-changing actions.
- DRM & Banking Blackouts:
FLAG_SECUREwindows capture strictly black in both screenshots and Device Hub mirrors.
android CLI share the same local ADB server, remote devices attached via adb connect 127.0.0.1:6555 appear automatically in GET /api/devices and can be mirrored live by the user while you inspect them.
10. Cross-Tool Synergy: From Cloud Schema to Verified APK
Watch how all four toolchains interlock in a single sprint—passing validated schemas, protected Gemini 3.8 clients, accessibility-checked Compose trees, and sequential XML journey reports cleanly from stage to stage.
Stage Handoff Checklist for Teams & Multi-Agent Swarms
Keep one agent or phase on Firebase MCP to finalize Firestore indexes, Data Connect mutations, and Security Rules before the UI agent generates Kotlin callers. This prevents broken field names and silent permission failures during device runs.
Run Compose Preview bounds checks before booting an AVD for journey QA. Catching missing contentDescription labels or clipped padding in 10 seconds inside the sidecar saves minutes of emulator interaction.
11. Troubleshooting Clinic & 6-Point Pre-Flight Checklist
Hit a blank pane, dropped Live session, or misbehaving ADB command? Match your symptom below for a 10-second root-cause fix.
| Symptom / Failure | 10-Second Root-Cause Fix |
|---|---|
1. Compose Preview pane stays blank after POST /api/session |
You omitted the X-Sidecar-Conversation: <id> header (or used a query parameter). Re-send with the exact HTTP header. |
2. android preview render fails or renders stale UI edits |
Never invoke android preview render directly, and never call POST /api/render in parallel with file edits. Save all edits first, then call POST /api/render. |
3. Gradle preview lookup fails on :feature@debug |
Modules with product flavors have no bare debug variant. Supply the flavor-first reference, e.g. gradle://.?:feature:home@demoDebug. |
4. gemini-3.8-live drops immediately on physical release builds |
App Check rejected an unverified token. Ensure firebase-appcheck-playintegrity is installed and your Play App Signing SHA-256 is registered in Console. |
5. adb shell input text drops words after the first space |
Raw spaces truncate Android text injection, or the field lacks focus. Check "focused" in android layout state and replace spaces with %s. |
6. android layout returns empty inside a login or WebView |
WebViews and custom canvases hide from accessibility trees. Run android screen capture --annotate -o /tmp/s.png, view it, and tap via screen resolve. |
| 7. Firebase MCP exposes unrelated projects or risky writes | Pin the workspace with --dir /abs/path and restrict active tool families using --only firestore,auth,dataconnect. |
firebase mcp --dir --only paired with firebase/agent-skills and android init.bounds_url verified for clickable semantics and contentDescription.gemini-3.8-flash and gemini-3.8-live via BoM 35.1.0.android run --use-delta-install boots cleanly on AVD with sys.boot_completed.<actions> pass in order with a signed-off ✅ Markdown audit.