Skip to main content
Glama
README.md
<!-- mcp-name: io.github.sinhsac/android-camera-mcp -->

# Android Camera MCP

[![PyPI version](https://img.shields.io/pypi/v/android-camera-mcp?logo=pypi&logoColor=white)](https://pypi.org/project/android-camera-mcp/)
[![MCP Registry](https://img.shields.io/badge/MCP%20Registry-io.github.sinhsac%2Fandroid--camera--mcp-8A2BE2)](https://registry.modelcontextprotocol.io/v0.1/servers/io.github.sinhsac%2Fandroid-camera-mcp/versions/latest)
[![Android APK CI](https://github.com/sinhsac/android-camera-mcp/actions/workflows/android-apk.yml/badge.svg)](https://github.com/sinhsac/android-camera-mcp/actions/workflows/android-apk.yml)
[![Publish MCP Server](https://github.com/sinhsac/android-camera-mcp/actions/workflows/publish-mcp.yml/badge.svg)](https://github.com/sinhsac/android-camera-mcp/actions/workflows/publish-mcp.yml)
[![GitHub Release](https://img.shields.io/github/v/release/sinhsac/android-camera-mcp?include_prereleases&label=APK%20Release)](https://github.com/sinhsac/android-camera-mcp/releases)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Android 10+](https://img.shields.io/badge/Android-10%2B%20(API%2029)-3DDC84?logo=android&logoColor=white)](app/build.gradle.kts)
[![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776AB?logo=python&logoColor=white)](server/pyproject.toml)

**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](https://sinhsac.github.io/android-camera-mcp/) · [PyPI](https://pypi.org/project/android-camera-mcp/) · [MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers/io.github.sinhsac%2Fandroid-camera-mcp/versions/latest) · [Download APK](https://github.com/sinhsac/android-camera-mcp/releases) · [Quick Start](#quick-start) · [Install](docs/INSTALL.md) · [MCP Tools](#available-mcp-tools) · [Architecture](#architecture) · [Documentation](#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/`).
- **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.

---

## 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

```mermaid
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](https://github.com/sinhsac/android-camera-mcp/releases)):

   <a href="https://github.com/sinhsac/android-camera-mcp/releases/download/latest-debug/android-camera-agent-debug.apk">
     <img src="https://github.com/sinhsac/android-camera-mcp/releases/download/latest-debug/apk-download-qr.png" width="180" alt="Scan QR code to download Android Camera Agent APK" />
   </a>

2. Install `android-camera-agent-debug.apk` (requires **Android 10 / API 29+**).

**Option B — Build Locally**
```bash
./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)**
```bash
# 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**
```bash
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`:

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

Or if running from a local git clone:

```json
{
  "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`:

| Category | Tool | Description | Key Parameters |
| :--- | :--- | :--- | :--- |
| **Discovery** | `camera_list` | List connected Android agents, online/stale status, active camera, lenses, stream, battery/thermal | — |
| **Discovery** | `camera_info` | Inspect per-camera capabilities (zoom/EV ranges, flash, manual focus), features, queue and pending commands | `device_id` |
| **Discovery** | `camera_status` | Live phone state: idle/capturing/streaming, battery, temperature, thermal status, uptime | `device_id` |
| **Analysis** | `camera_analyze` | Offline 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` |
| **Capture** | `camera_capture` | Capture an upright JPEG still (`1600px` long edge default; `0` = full sensor) with presets and phone-side ROI crop | `device_id`, `camera_id`, `max_dimension`, `width`, `height`, `jpeg_quality`, `zoom_ratio`, `torch`, `flash_mode`, `focus_mode`, `exposure_compensation`, `preset`, `crop_x/y/w/h` |
| **Capture** | `camera_preview` | Fast low-resolution frame from the live feed (`640px` default) with optional ROI crop for framing checks | `device_id`, `max_dimension`, `jpeg_quality`, `crop_x/y/w/h` |
| **Stream** | `camera_stream_start` | Start a temporary low-FPS stream with duration and idle auto-stop | `device_id`, `fps`, `max_dimension`, `jpeg_quality`, `duration_s`, `idle_timeout_s` |
| **Stream** | `camera_stream_frame` | Newest stream frame; optionally wait for one newer than `after_sequence` | `device_id`, `after_sequence`, `wait_s` |
| **Stream** | `camera_stream_stop` | Stop the stream (idempotent) | `device_id` |
| **Controls** | `camera_set_zoom` | Set zoom ratio on the active camera (clamped to supported bounds, including ultra-wide `<1.0x`) | `device_id`, `zoom_ratio` |
| **Controls** | `camera_set_torch` | Toggle continuous flashlight/torch on or off | `device_id`, `enabled` |
| **Controls** | `camera_set_flash` | Set flash mode for subsequent captures | `device_id`, `mode` (`off` \| `auto` \| `on`) |
| **Controls** | `camera_set_focus` | Configure `continuous` AF, one-shot `auto` AF, or `manual` focus distance (`0.0–1.0`) | `device_id`, `mode`, `distance` |
| **Controls** | `camera_set_exposure` | Set EV compensation steps or omit to reset to auto exposure (`0`) | `device_id`, `exposure_compensation` |
| **Controls** | `camera_select_lens` | Switch active camera/lens by `camera_id` and refresh capabilities | `device_id`, `camera_id` |

### CLI Reference

| Command | Options | Description |
| :--- | :--- | :--- |
| `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`, `-v` | Run 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`, `-v` | Run the MCP `stdio` server (default subcommand when invoked as `android-camera-mcp` or `uvx android-camera-mcp`) |
| `android-camera-mcp --version` | `-V` / `--version` | Print 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:

```text
+-----------------------+------------------+----------------------------+
| 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](docs/PROTOCOL.md).

---

## Testing

```bash
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

```text
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

- [Architecture Overview](docs/ARCHITECTURE.md) — System components, gateway daemon design, and reliability model
- [Wire Protocol Specification](docs/PROTOCOL.md) — TCP framing, registration, heartbeats, and JPEG payloads
- [MCP Tool Contract](docs/MCP_TOOLS.md) — Tool schemas, error codes, and agent guidelines
- [Android App Guide](docs/ANDROID_APP.md) — Permissions, foreground service, and camera controls
- [Server README](server/README.md) — Python server setup, CLI subcommands, and tests
- [Engineering Decisions](docs/DECISIONS.md) — Technical trade-offs and constraints
- [Roadmap](docs/ROADMAP.md) — Planned milestones from MVP to streaming, pairing security, and mDNS

---

## Roadmap

- [x] **Phase 0 & 1**: End-to-end LAN snapshot pipeline (`Android → TCP → Gateway → MCP → Image`)
- [x] **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`)
- [x] **Phase 3** (`v0.3.0`): Live-frame `camera_preview`, bounded low-FPS temporary streaming, battery/thermal reporting
- [x] **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)
- [x] **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](https://github.com/sinhsac/android-camera-mcp/issues) and Pull Requests.

Licensed under the **MIT License** — see [LICENSE](LICENSE) for details.