Repository avatar
AI Tools
v0.5.0
active

android-camera-mcp

io.github.sinhsac/android-camera-mcp

Private LAN-first Android remote camera for AI agents: 15 tools, on-device OCR & controls.

Documentation

Android Camera MCP

PyPI version MCP Registry Android APK CI Publish MCP Server GitHub Release License: MIT Android 10+ Python 3.10+

Turn any Android phone into a private, LAN-first remote camera for AI agents via the Model Context Protocol (MCP).

Android Camera MCP connects a Kotlin / CameraX Android foreground service agent to a decoupled Python asyncio Camera Gateway and MCP Server, giving multimodal AI assistants such as Antigravity, Claude Desktop / Claude Code, Cursor, Kiro, and custom LLM agents real-world visual perception, offline on-device ML Kit OCR/barcodes, and hardware camera controls (snapshot capture, phone-side ROI crop, optical/digital zoom, lens switching, torch, flash, autofocus/manual focus, and exposure compensation) over your local network — with zero cloud dependency.

Guide Site · PyPI · MCP Registry · Screenshots · Download APK · Quick Start · MCP Tools · Documentation


Key Features

  • LAN-First & Private: All control messages and JPEG frames stay strictly inside your local network — no cloud relays, accounts, or subscriptions.
  • Decoupled Gateway Daemon: Run android-camera-mcp gateway once (:8765 for phones, 127.0.0.1:8766 for local MCP clients). Restarting Claude Desktop/Cursor/Antigravity or running multiple AI clients simultaneously never drops the phone connection.
  • Screen-Off & Background Capture: CameraX is bound to an Android LifecycleService foreground service (FOREGROUND_SERVICE_TYPE_CAMERA) with wake and Wi-Fi locks so the phone keeps answering capture requests with the screen off or after rotation.
  • LLM-Ready Smart Downscaling & Upright Rotation: Captures default to 1600px on the long edge (640px for camera_preview) with upright pixel rotation (no broken EXIF orientation), plus max_dimension=0 for full sensor resolution.
  • Per-Camera Hardware Controls: Advertises real capabilities per physical/logical camera — zoom ratio (including ultra-wide <1.0x), torch, flash, autofocus, Camera2 manual focus distance, and EV steps.
  • Built-In Resilience: Connection-scoped device registry, mutex-serialized JSON+JPEG framing, 10s heartbeats with ack, exponential backoff reconnect (immediate when Wi-Fi returns), per-device FIFO command queue, per-command deadlines enforced on the phone, and a capture watchdog that reopens a stuck camera.
  • Fast Preview & Temporary Streaming: camera_preview grabs a frame from the live camera feed without the still-capture sequence; camera_stream_* pushes low-FPS frames that stop on duration, idle timeout, thermal limit or disconnect.
  • Traceable: every command is logged on the phone (SQLite log database with a log screen, crash report) and on the gateway with request ID and queue / phone / transfer timing.
  • On-device OCR / barcodes / scene stats: camera_analyze runs ML Kit on the phone and returns text boxes + exposure/focus hints without uploading a large image.
  • On-device crop / ROI: crop_x/y/w/h (0..1) crop on the phone before transfer; combine with zoom_ratio and max_dimension so the AI never downloads a full multi‑MP frame just to inspect a corner.
  • Capture presets: general, document, macro, low_light via the preset argument on camera_capture (explicit params always win).
  • mDNS discovery: gateway advertises _android-camera-mcp._tcp when zeroconf is installed; the app has a Discover button.
  • Phone log upload: unsynced SQLite rows are pushed to the gateway (~/.android-camera-mcp/device-logs/).
  • 4-Tab Android UI & Configurable AI Capture History: Dedicated Camera, History, Logs, and Settings tabs. Automatically records AI captures, previews, ML Kit analyses, and camera controls on-device (default 200 recent operations, configurable 10–2000 in Settings) with full-resolution viewer, Share, Save to Photos, and one-tap jump to matching request logs.
  • One-Scan APK Releases: Every build is compiled and tested in GitHub Actions with an auto-generated QR code, SHA-256 checksum, and Release Notes.

Android App Screenshots

Camera & StatusAI Capture History (200 ops)Operation DetailLive LogsSettings
Camera and Status tabAI History tab with thumbnailsOperation Detail viewerLive SQLite Logs tabSettings tab

Use Cases

  • Hardware & Electronics Bench: Let your AI inspect PCBs, soldering joints, multimeter screens, or wiring diagrams using your phone's macro/telephoto lens and torch.
  • 3D Printing & Lab Monitoring: Take on-demand high-resolution stills of a print bed or workspace without running a continuous video stream.
  • Document & Whiteboard Capture: Snap crisp, upright photos of whiteboards, handwritten notes, or receipts straight into your AI context.
  • Physical-World AI Agents: Give local coding or robotics agents an inexpensive, high-quality optical sensor by reusing any spare Android 10+ phone.

Architecture

flowchart LR
    A["Android Camera Agent<br/>(Kotlin + CameraX LifecycleService)<br/>Capture, ROI Crop & ML Kit OCR"]
    B["Camera Gateway Daemon<br/>(android-camera-mcp gateway)<br/>TCP :8765 & Local API 127.0.0.1:8766"]
    C["MCP Server (stdio)<br/>(uvx android-camera-mcp)<br/>15 Typed Camera Tools"]
    D["AI Agents / MCP Clients<br/>(Antigravity, Claude, Cursor, Kiro)"]

    A -- "Persistent TCP :8765<br/>Framed JSON + Binary JPEG" --> B
    B -- "Local Control API :8766" --> C
    C -- "MCP over stdio" --> D

Quick Start

1. Install the Android App (APK)

Option A — Scan QR Code / Download from GitHub Releases (Recommended)

  1. Scan the QR code below on your Android phone (or open the Releases page):

    Scan QR code to download Android Camera Agent APK
  2. Install android-camera-agent-debug.apk (requires Android 10 / API 29+).

Option B — Build Locally

./gradlew assembleDebug
# Output: app/build/outputs/apk/debug/app-debug.apk

2. Start the Camera Gateway Daemon

Requires Python 3.10+ (mcp>=1.2,<2).

Option A — Install from PyPI / uvx (Recommended)

# Install with pip (add [mdns] for automatic LAN discovery)
pip install "android-camera-mcp[mdns]"

# Start the gateway daemon (phone TCP :8765, local API 127.0.0.1:8766)
android-camera-mcp gateway

# Or run directly via uvx without creating a virtualenv
uvx --from "android-camera-mcp[mdns]" android-camera-mcp gateway

Option B — Run from Source

git clone https://github.com/sinhsac/android-camera-mcp.git
cd android-camera-mcp/server

python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -e ".[mdns]"

# Start the gateway daemon (phone TCP :8765, local API 127.0.0.1:8766)
python main.py gateway

# Optional: verbose debug logs
python main.py gateway -v

3. Configure Your MCP Client (Claude Desktop / Cursor / Kiro / Antigravity)

Add android-camera to your MCP client configuration using uvx:

{
  "mcpServers": {
    "android-camera": {
      "command": "uvx",
      "args": ["android-camera-mcp"]
    }
  }
}

Or if running from a local git clone:

{
  "mcpServers": {
    "android-camera": {
      "command": "/absolute/path/to/android-camera-mcp/server/.venv/bin/python",
      "args": ["/absolute/path/to/android-camera-mcp/server/main.py", "mcp"]
    }
  }
}

Antigravity CLI shortcut: agy mcp add android-camera uvx android-camera-mcp
Windows (from source): Set "command" to C:\\path\\to\\android-camera-mcp\\server\\.venv\\Scripts\\python.exe.
Keep android-camera-mcp gateway running in the background; if stopped, MCP tools cleanly return GATEWAY_UNAVAILABLE.

4. Connect Your Phone & Capture with AI

  1. Open Android Camera Agent on your phone and grant Camera permission (and Notifications on Android 13+).
  2. Enter your computer's LAN IP address and port 8765, then tap Connect.
  3. Verify locally with Test Capture, or ask your AI assistant:
    • "List my connected Android cameras and inspect their supported controls."
    • "Take a quick preview shot to check framing, then capture a sharp photo at 2x zoom."
    • "Turn on the torch, capture a close-up photo, then turn the torch off."

Tips for long-running background use: Keep the phone plugged into power while connected (the service holds a wake lock and Wi-Fi lock), and disable aggressive battery optimization for the app on Samsung/Xiaomi/Oppo devices so Android does not kill the foreground service.


Available MCP Tools

The MCP server exposes 15 tools via FastMCP:

CategoryToolDescriptionKey Parameters
Discoverycamera_listList connected Android agents, online/stale status, active camera, lenses, stream, battery/thermal—
Discoverycamera_infoInspect per-camera capabilities (zoom/EV ranges, flash, manual focus), features, queue and pending commandsdevice_id
Discoverycamera_statusLive phone state: idle/capturing/streaming, battery, temperature, thermal status, uptimedevice_id
Analysiscamera_analyzeOffline on-device ML Kit OCR, QR/barcodes, and exposure/focus hints (compact JSON + normalized crop boxes, no large JPEG by default)device_id, max_dimension, still, include_image, ocr, barcodes, stats, crop_x/y/w/h
Capturecamera_captureCapture an upright JPEG still (1600px long edge default; 0 = full sensor) with presets and phone-side ROI cropdevice_id, camera_id, max_dimension, width, height, jpeg_quality, zoom_ratio, torch, flash_mode, focus_mode, exposure_compensation, preset, crop_x/y/w/h
Capturecamera_previewFast low-resolution frame from the live feed (640px default) with optional ROI crop for framing checksdevice_id, max_dimension, jpeg_quality, crop_x/y/w/h
Streamcamera_stream_startStart a temporary low-FPS stream with duration and idle auto-stopdevice_id, fps, max_dimension, jpeg_quality, duration_s, idle_timeout_s
Streamcamera_stream_frameNewest stream frame; optionally wait for one newer than after_sequencedevice_id, after_sequence, wait_s
Streamcamera_stream_stopStop the stream (idempotent)device_id
Controlscamera_set_zoomSet zoom ratio on the active camera (clamped to supported bounds, including ultra-wide <1.0x)device_id, zoom_ratio
Controlscamera_set_torchToggle continuous flashlight/torch on or offdevice_id, enabled
Controlscamera_set_flashSet flash mode for subsequent capturesdevice_id, mode (off | auto | on)
Controlscamera_set_focusConfigure continuous AF, one-shot auto AF, or manual focus distance (0.0–1.0)device_id, mode, distance
Controlscamera_set_exposureSet EV compensation steps or omit to reset to auto exposure (0)device_id, exposure_compensation
Controlscamera_select_lensSwitch active camera/lens by camera_id and refresh capabilitiesdevice_id, camera_id

CLI Reference

CommandOptionsDescription
android-camera-mcp gateway--host 0.0.0.0, --port 8765, --api-host 127.0.0.1, --api-port 8766, --min-capture-interval 1.5, --max-queue 4, --no-mdns, --log-file PATH, -vRun the persistent TCP device gateway and local control API
android-camera-mcp mcp--api-host 127.0.0.1, --api-port 8766, --log-file PATH, -vRun the MCP stdio server (default subcommand when invoked as android-camera-mcp or uvx android-camera-mcp)
android-camera-mcp --version-V / --versionPrint installed package version

Optional environment variables: ANDROID_CAMERA_API_HOST (default 127.0.0.1) and ANDROID_CAMERA_API_PORT (default 8766). When running from a source checkout, python main.py ... remains fully supported.

Pacing & Error Handling

  • Queue, not reject: calls for one phone run one at a time in arrival order; a capture within ~1.5s of the previous one waits for the cooldown. Only more than 4 waiting calls return RATE_LIMITED.
  • Deadlines: each command carries timeout_ms; the phone abandons work past it, and a still that never arrives (20s) makes the phone reopen the camera.
  • Structured errors: GATEWAY_UNAVAILABLE, DEVICE_OFFLINE, REQUEST_TIMEOUT, CAMERA_BUSY, UNSUPPORTED_CONTROL, INVALID_ARGUMENT, STREAM_NOT_ACTIVE, THERMAL_LIMIT — AI agents never hang on an unreachable phone.

Debugging slow or failed calls

  • Phone: the Activity log card shows each command (-> capture [req-…], <- capture [req-…] OK 975ms (wait 0, camera 820, encode 140)), reconnects and camera errors. Every line (DEBUG to ERROR) is stored in an on-phone SQLite database; All logs opens a log screen with level / text / request-id filters, live updates and Share/Copy. A crash report is imported into the same database and shown on the next launch. adb logcat -s 'CamAgent.*' shows the same lines.
  • Gateway: one line per command with the same request ID and total / queue / device / transfer times. Add --log-file gateway.log, and -v for frame-level detail.
  • MCP server: one line per tool call. Use "args": ["android-camera-mcp", "mcp", "--log-file", "/path/to/mcp.log"] with uvx (or [".../main.py", "mcp", "--log-file", ".../mcp.log"] from source), since MCP clients often hide stderr.

LAN security

There is no pairing or authentication (ADR-008). Anyone who can reach port 8765 can register a fake camera, so:

  • Run the gateway only on a trusted home/lab network.
  • Allow 8765 on the private network profile only. Windows: netsh advfirewall firewall add rule name="Camera Gateway" dir=in action=allow protocol=TCP localport=8765 profile=private.
  • Keep the local API on 127.0.0.1:8766 (the default). Do not bind it to 0.0.0.0.
  • Do not forward either port on the router.

Wire Protocol Overview

The Android agent and Camera Gateway communicate over persistent TCP (:8765) with length-prefixed framing:

+-----------------------+------------------+----------------------------+
| Length (4B big-endian)| Kind (1B)        | Payload (Length - 1 bytes) |
+-----------------------+------------------+----------------------------+
  Kind 0x01 = UTF-8 JSON control frame (register, heartbeat/ack, command, response)
  Kind 0x02 = Raw binary JPEG payload (immediately follows capture response)

Full specification: docs/PROTOCOL.md.


Testing

cd server
pip install -e ".[dev,mdns]"
python -m pytest -q

Tests verify frame decoding, reconnect race handling, slow/late JPEG correlation, framing-error recovery, the FIFO queue and its overflow limit, stream frames/stop, preview fallback for older apps, local Gateway API roundtrips over real TCP sockets, and package/CLI/MCP Registry metadata consistency.


Project Structure

android-camera-mcp/
├── .github/workflows/
│   ├── android-apk.yml       # CI: Android APK build, QR Release & Python server tests
│   └── publish-mcp.yml       # CD: Publish PyPI package & Official MCP Registry via OIDC
├── app/                      # Android Camera Agent (Kotlin, CameraX, LifecycleService)
│   └── src/main/java/com/androidcameramcp/agent/
│       ├── agent/            # Registration, heartbeat + health, command dispatch with deadlines, frame streamer
│       ├── camera/           # CameraX stills + live analysis frames, Camera2 capabilities, controls, JPEG encoder
│       ├── log/              # TraceLog + LogStore: logcat, SQLite log database, crash report
│       ├── service/          # Foreground LifecycleService owning camera, wake/Wi-Fi locks, network callback
│       ├── transport/        # Framed TCP client with write mutex & network-aware backoff reconnect
│       └── ui/               # MainActivity: status, gateway, camera and activity-log cards
├── server/                   # Python Camera Gateway + MCP Server (PyPI: android-camera-mcp)
│   ├── android_camera_mcp/   # Installable Python package
│   │   ├── cli.py            # CLI entrypoint (`gateway` and `mcp` subcommands)
│   │   ├── gateway/          # TCP listener, connections, registry, sessions, rate limit, local API
│   │   ├── mcp_server/       # FastMCP tool definitions & local gateway API client
│   │   └── protocol/         # Framing codec & control message schemas
│   ├── main.py               # Backwards-compatible source-checkout entrypoint
│   └── tests/                # Automated pytest suite over real TCP sockets
├── server.json               # Official MCP Registry manifest
├── glama.json                # Glama MCP directory manifest
├── smithery.yaml             # Smithery stdio/uvx manifest
├── docs/                     # Architecture, protocol, MCP contract & roadmap
├── PROJECT_CONTEXT.md        # Canonical architecture & AI coding agent context
└── LICENSE                   # MIT License

Documentation


Roadmap

  • Phase 0 & 1: End-to-end LAN snapshot pipeline (Android → TCP → Gateway → MCP → Image)
  • Phase 2: Per-camera capability discovery, zoom/torch/flash/focus/exposure/lens controls, foreground LifecycleService, decoupled gateway daemon, automated server tests, and CI QR APK Releases (v0.2.0)
  • Phase 3 (v0.3.0): Live-frame camera_preview, bounded low-FPS temporary streaming, battery/thermal reporting
  • Phase 4 (v0.3.0–v0.4.0): FIFO command queue, phone-side deadlines, capture watchdog, network-aware reconnect, trace logging & phone log sync, Material 3 app UI (device pairing tokens deferred per ADR-008)
  • Phase 5 (v0.4.0–v0.5.0): mDNS/NSD automatic gateway discovery, multi-device registry, capture presets, phone-side ROI crop, on-device ML Kit camera_analyze, PyPI package (android-camera-mcp), and Official MCP Registry listing (io.github.sinhsac/android-camera-mcp)

Contributing & License

Contributions, bug reports, and feature requests are welcome via Issues and Pull Requests.

Licensed under the MIT License — see LICENSE for details.

PYPI
android-camera-mcp
Install Command
pip install android-camera-mcp
Runtime: uvx