Skip to main content
Glama
Aqara Local MCP

Aqara Local MCP

by marc3k18
README.md
# Aqara Local MCP

An [MCP](https://modelcontextprotocol.io) server that talks to Aqara hubs **over your local network** using the LANLink protocol, so an AI assistant (Claude Desktop, Claude Code, or any MCP client) can read your Aqara devices, follow live events and, if you allow it, send commands.

> **Based on [Aqara LANLink](https://github.com/absent42/Aqara-LANLink) by Dan Gibson ([absent42](https://github.com/absent42)).**
> The hard part, reverse engineering the LANLink protocol (encrypted tunnel, key exchange, message format, discovery) and building the device catalogue, is his work, published under the MIT license as a Home Assistant integration. This project takes that protocol code and catalogue out of Home Assistant and serves them as an MCP server. If you find this useful, go star the original project. [NOTICE.md](NOTICE.md) lists exactly what was copied and what was changed.

Not affiliated with or endorsed by Aqara. The protocol was reverse engineered: a hub firmware update may break it without warning.

## Contents

- [How it works](#how-it-works)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Connecting an MCP client](#connecting-an-mcp-client)
- [Tools](#tools)
- [Security](#security)
- [Troubleshooting](#troubleshooting)
- [Limitations](#limitations)
- [Development](#development)
- [Credits and license](#credits-and-license)

## How it works

```
 MCP client (Claude...)
        |  stdio, or HTTP + bearer token
        v
 aqara-local-mcp  ----------------------------->  Aqara cloud
        |          login, device list,               (once at startup,
        |          initial values, push subscribe     then on demand)
        |
        |  LANLink: encrypted TCP session (ECDH + AES-128)
        v
 Aqara hub (M3...)  <---- Zigbee / Thread / Wi-Fi ---->  your devices
```

1. **Login.** The server logs in to your Aqara account once and caches the session token (file mode 600). LANLink needs this token for the hub to accept the session.
2. **Inventory.** It downloads your device list (names, rooms, models, parent hub) from the Aqara cloud.
3. **Local session.** It opens an encrypted LANLink session with each hub you configured. Hubs in a cluster (for example two M3) relay each other's devices.
4. **Initial values and push.** It reads the current values of every device through the same cloud call the Aqara app uses. That call also arms the hub's push subscription. The hub forgets subscriptions when a connection drops, so they are armed again on every reconnect.
5. **Live events.** From then on, every change (motion, door, power, temperature, a light turning on...) arrives **locally** as a push report from the hub and updates the in-memory state.
6. **Commands.** Writes are sent **locally** to the hub, which forwards them to the device. They are disabled unless you turn them on.

| Step | Where |
|---|---|
| Account login (then cached) | Aqara cloud |
| Device list (names, rooms, models) | Aqara cloud |
| Initial values and push subscription | Aqara cloud |
| Live events | **Local (LANLink)** |
| Commands | **Local (LANLink)** |

Why not read everything locally? On current M3 firmware, direct LANLink reads of Zigbee sub-devices time out. Push reports and writes work locally, so the cloud is only used to bootstrap.

**Finding the hub.** The LANLink port changes every time the hub reboots. The server finds it by mDNS (`_aqara-setup._tcp`). If the hub is on another VLAN and mDNS does not cross over, it scans the hub's TCP ports and keeps the one that accepts a LANLink handshake. The last known port is cached, so restarts are instant.

**Names.** Device values are addressed by numeric paths such as `2.132.32920`. The catalogue inherited from Aqara LANLink (about 380 models) turns them into readable names (`On off`, `Current power`), units, allowed values and whether they are writable.

## Requirements

- Python 3.11 or newer (Linux, macOS or Windows).
- An Aqara hub with **LAN control** enabled. Tested with two Hub M3 (firmware 4.5.90_0011). Other `lumi1.` hubs may work but are not tested.
- The Aqara account that owns the hub, and its region.
- Network access from the machine running the server to the hub (any TCP port; the hub uses a random high port).

### Enable LAN control on the hub

In the Aqara Home app: open the hub, then its settings, and turn on **LAN control** (on the M3 you may also see **Hub cluster** if you have several hubs). Give the hub a fixed IP address in your router.

## Installation

```bash
git clone https://github.com/marc3k18/Aqara-Local-MCP.git
cd Aqara-Local-MCP
python3 -m venv .venv
.venv/bin/pip install .
```

Create your configuration:

```bash
cp .env.example .env
chmod 600 .env
```

Edit `.env` (see [Configuration](#configuration)), then check that everything connects:

```bash
set -a; . ./.env; set +a
.venv/bin/aqara-local-mcp --check
```

`--check` logs in, connects to the hubs and prints a status like this:

```json
{
 "hubs": [
  {"name": "Hub M3", "host": "192.168.1.20", "port": 43280, "connected": true, "lan_topology": 11}
 ],
 "devices": 181,
 "seed": "running",
 "writes": "disabled (read-only)"
}
```

### Finding your hub's DID

The DID is `lumi1.` followed by the hub's MAC address in lowercase without separators, for example MAC `54:EF:44:12:34:56` gives `lumi1.54ef44123456`. The MAC is in your router or in the Aqara Home app (hub settings, network information). Once the server runs, `aqara_list_devices` with `only_lan=false` also shows every hub with its DID.

## Configuration

All settings are environment variables. [.env.example](.env.example) has every one with comments.

| Variable | Default | Purpose |
|---|---|---|
| `AQARA_EMAIL`, `AQARA_PASSWORD` | | Aqara account (required) |
| `AQARA_REGION` | `US` | `US`, `EU`, `CN`, `RU`, `KR`, `JP`, `AU`, `ME`, `HMT`, `AF`, `OTHER` |
| `AQARA_HUBS` | | Comma separated `did=ip[:port]` (required). The port is optional. |
| `AQARA_ALLOW_WRITE` | `false` | Allow commands |
| `AQARA_ALLOW_SENSITIVE` | `false` | Also allow locks, valves, hubs, cameras, garage doors, curtains |
| `AQARA_WRITE_ALLOWLIST` | | Only these DIDs can be written (empty: all) |
| `AQARA_PORT_SCAN` | `true` | Scan the hub's ports when mDNS cannot find it |
| `AQARA_STATE_DIR` | `~/.local/state/aqara-local-mcp` | Session cache, known ports, audit log |
| `AQARA_AUDIT_LOG` | `<state dir>/audit.log` | One JSON line per write |
| `AQARA_LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`... |
| `MCP_HTTP_HOST` / `MCP_HTTP_PORT` | `127.0.0.1` / `8790` | Listen address in HTTP mode |
| `MCP_HTTP_TOKEN` | | Bearer token, required in HTTP mode |
| `MCP_ALLOWED_IPS` | | Allowed client IPs or networks (empty: any) |
| `MCP_ALLOWED_HOSTS` / `MCP_ALLOWED_ORIGINS` | | Accepted `Host` and `Origin` headers |

Example:

```bash
AQARA_EMAIL=you@example.com
AQARA_PASSWORD=...
AQARA_REGION=US
AQARA_HUBS=lumi1.54ef44123456=192.168.1.20,lumi1.54ef44abcdef=192.168.1.21
```

## Connecting an MCP client

### Claude Desktop (stdio)

Add this to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "aqara-local": {
      "command": "/path/to/Aqara-Local-MCP/.venv/bin/aqara-local-mcp",
      "env": {
        "AQARA_EMAIL": "you@example.com",
        "AQARA_PASSWORD": "...",
        "AQARA_REGION": "US",
        "AQARA_HUBS": "lumi1.54ef44123456=192.168.1.20"
      }
    }
  }
}
```

### Claude Code (stdio)

```bash
claude mcp add aqara-local \
  -e AQARA_EMAIL=you@example.com -e AQARA_PASSWORD=... \
  -e AQARA_REGION=US -e AQARA_HUBS=lumi1.54ef44123456=192.168.1.20 \
  -- /path/to/Aqara-Local-MCP/.venv/bin/aqara-local-mcp
```

### HTTP (server, gateway or several clients)

```bash
.venv/bin/aqara-local-mcp --generate-token     # put it in MCP_HTTP_TOKEN
.venv/bin/aqara-local-mcp --transport http
```

Clients connect to `http://<host>:<port>/mcp` with the header `Authorization: Bearer <token>`. To accept connections from other machines, set `MCP_HTTP_HOST` to the server's IP, restrict `MCP_ALLOWED_IPS`, and put a reverse proxy in front for TLS (Caddy, nginx, Cloudflare Access, an MCP gateway...). A hardened systemd unit is in [deploy/aqara-local-mcp.service](deploy/aqara-local-mcp.service).

In HTTP mode the server connects to the hubs at startup and keeps collecting events between requests. In stdio mode it does the same for as long as the client keeps it running.

## Tools

| Tool | What it does |
|---|---|
| `aqara_status` | Hubs (connected, LANLink port, seconds since last report), startup progress, write mode |
| `aqara_list_devices` | Devices with name, room, model, DID, online state, parent hub. Filter by name or room. |
| `aqara_get_device` | One device's values with names, units, writable flag, source (`lan` or `cloud`) and age. `refresh=true` reads fresh values. |
| `aqara_recent_events` | Latest changes pushed by the hubs, newest first, optionally for one device |
| `aqara_set_value` | Writes one value (by path, trait code such as `OnOff`, or name). Refused unless writes are enabled. |
| `aqara_refresh_inventory` | Reloads the device list from the account |

Example prompts: *"Is anyone in the bathroom?"*, *"What changed in the last ten minutes?"*, *"How much power is the network rack plug drawing?"*, *"Turn off the kitchen ceiling light"* (needs writes enabled).

## Security

Secure by default. Details in [SECURITY.md](SECURITY.md).

- **stdio by default:** no network port at all.
- **HTTP is locked down:** a bearer token is mandatory (the server will not start without one), it listens on `127.0.0.1` by default, an IP allow list is available, and `Host` / `Origin` headers are checked against DNS rebinding.
- **Read-only by default:** `AQARA_ALLOW_WRITE=true` to allow commands.
- **Sensitive devices need a second switch:** locks, water valves, hubs, cameras, security stations, garage doors and curtains also require `AQARA_ALLOW_SENSITIVE=true`.
- **Optional allow list:** `AQARA_WRITE_ALLOWLIST` limits writes to specific DIDs.
- **Audit log:** every write is recorded (time, device, value, hub).
- **Secrets stay secret:** the password, the Aqara token and the HTTP token are masked in logs; state files are created with mode 600.

Tip: create a secondary Aqara account, share your home with it, and use that account here.

## Troubleshooting

| Symptom | What to check |
|---|---|
| `LANLink port not found` | LAN control enabled in the app? Right IP and DID? Can the server reach the hub (firewall between VLANs)? Leave `AQARA_PORT_SCAN=true` if the hub is on another VLAN. |
| `hub rejected checkin (bad user/token)` | Wrong account or region, or the hub belongs to another account. Delete `session.json` in the state dir to force a new login. |
| Login fails with `invalid sign` or region errors | Try another `AQARA_REGION` (the one shown in the Aqara app's account settings). |
| Values are old or `source: cloud` only | Push subscriptions are armed in the background at startup; check `aqara_status` (`seed`). Use `aqara_get_device` with `refresh=true`. |
| A device is missing | Matter devices, groups and third party devices are not LANLink devices and are not listed. Devices behind a hub you did not configure are listed but cannot be written. |
| Write refused | Read the message: writes disabled, sensitive device, not in the allow list, or read-only value. |

Run with `AQARA_LOG_LEVEL=DEBUG` to see every frame (secrets stay masked).

## Limitations

- Tested only with Hub M3. Other LANLink hubs are untested.
- Cameras (video, PTZ), scenes and automations are not exposed.
- Values of devices missing from the catalogue are shown with their raw path (`show_unknown=true`), and are never writable by name.
- The cloud is still needed at startup (login, device list, initial values).

## Development

```bash
.venv/bin/pip install -e . pytest
.venv/bin/python -m pytest -q
```

The catalogue is generated from the Aqara LANLink models:

```bash
python3 scripts/build_catalogue.py \
  <Aqara-LANLink>/custom_components/aqara_lanlink/device/models \
  src/aqara_local_mcp/data/catalogue.json <commit>
```

Project layout:

```
src/aqara_local_mcp/
  lanlink/        LANLink protocol, from Aqara LANLink (absent42)
  data/           catalogue.json, from Aqara LANLink device models
  config.py       environment settings
  service.py      login, hub sessions, state, events, writes
  server.py       MCP tools and transports
  security.py     HTTP bearer token, IP allow list, log masking
tests/            offline tests
deploy/           systemd unit example
```

## Credits and license

- **Dan Gibson ([absent42](https://github.com/absent42))** for [Aqara LANLink](https://github.com/absent42/Aqara-LANLink): the LANLink protocol implementation and the device catalogue used here.
- MIT license, see [LICENSE](LICENSE) and [NOTICE.md](NOTICE.md).

TDQS

A3.7/5.0

Scored across 6 tools

Disambiguation4/5

Each tool targets a distinct operation: status, list, get, set, events, refresh. The only mild overlap is between aqara_list_devices (local filtered listing) and aqara_refresh_inventory (cloud reload), and between aqara_status's 'seed progress' and inventory reloading, but descriptions clarify these boundaries.

Naming Consistency4/5

All tools share the aqara_ prefix and snake_case, mostly following verb_noun (list_devices, get_device, set_value, refresh_inventory). Minor deviations: aqara_status is a bare noun and aqara_recent_events uses an adjective, but the pattern remains predictable.

Tool Count5/5

Six tools is well-scoped for a local smart-home hub bridge, covering status, discovery, read, write, events and refresh without redundant entries. Each tool earns its place.

Completeness4/5

The core lifecycle (inspect connection, list devices, read values, write values, stream events, reload inventory) is covered, enabling full read/write workflows. Gaps are minor: no explicit room/scene listing or device metadata operations, but agents can work around these via existing tools.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues