Skip to main content
Glama
README.md
# mqtt-readonly-mcp

> **First attempt.** This is an early, hobby-grade release: it works on the author's own Home Assistant setup and has a test suite, but it has not been used by many people or on many brokers. Expect rough edges, and please read the [disclaimer](#disclaimer-use-at-your-own-risk) before you point it at anything you care about.

A small **listen-only** MQTT tool for [Claude Code](https://claude.com/claude-code) and other MCP clients.

## Purpose

The goal is to let an AI assistant **watch the traffic on a smart-home MQTT broker live**, understand it, and then help you **bring that traffic under control through Home Assistant**.

The tool itself only listens. It shows the assistant what Home Assistant, Zigbee2MQTT, Frigate and your devices are publishing: which topics are chatty, what a sensor sends when something happens, how busy the broker is. The assistant then uses that picture, together with Home Assistant, to change things: for example lowering a presence radar's update rate or turning down a noisy Zigbee2MQTT log level. Those changes are made through Home Assistant (or Zigbee2MQTT), not through this tool, and they need your approval like any other change the assistant proposes.

- `server.py`: an MCP server (stdio). Keeps a rolling buffer of what the broker publishes, so the assistant can ask "what did topic X send in the last N minutes?".
- `stream.py`: prints one line per message, for Claude Code's **Monitor** tool (live notifications in the chat).
- `mqtt_common.py`: shared code (buffer, redaction, payload formatting, connection).

Neither program contains any publish code. `tests/test_no_publish.py` fails if publish-like code appears in them.

## What it is good for

It was built to answer questions like these on a real smart home:

- Which device is flooding the broker? (`mqtt_rates` found that one presence radar produced 87% of about 1,400 messages per minute; after the radar's update rate was lowered in Home Assistant, traffic fell to about a fifth.)
- Did the Zigbee2MQTT change I just made actually reduce traffic?
- What exactly does this sensor publish when the door opens? (`mqtt_wait`)

## Changing Home Assistant: what else you need

This project **only listens**. It cannot change Home Assistant, a device or the broker. To go from "the assistant can see the problem" to "the assistant can fix it", you have to give the assistant a separate, deliberate way to write to Home Assistant. None of the tools below are part of this repository or are made by it, each has its own documentation and its own risks, and you should check their current instructions before installing anything.

| Route | What it lets the assistant do | What you set up |
|---|---|---|
| **A Home Assistant MCP server**, for example the community project [ha-mcp](https://github.com/homeassistant-ai/ha-mcp), usually run as a Home Assistant app (add-on) | Read states, entities, devices and history; create or edit automations, scripts, scenes, helpers and dashboards; rename entities; reload or restart Home Assistant; manage backups. This is the broadest route. | Install the app in Home Assistant, create a long-lived access token (your profile page), and register the server with your MCP client. Many of these servers have a read-only mode: start there. |
| **Home Assistant's own MCP server integration / the Nabu Casa Claude connector** | Control only the entities you have exposed to Assist (lights, climate, media players, to-do lists and similar). It does not edit automations or configuration. | Enable the integration (or the cloud connector), then choose which entities to expose. |
| **The Home Assistant REST and WebSocket API**, called from scripts or a command line tool such as [hass-cli](https://github.com/home-assistant-ecosystem/home-assistant-cli) | Anything the web interface can do, including entity registry changes and service calls. | A long-lived access token in an environment variable (for example `HASS_SERVER` and `HASS_TOKEN`). Never paste the token into a chat. |
| **SSH and a file share to the `/config` folder** (the Terminal & SSH app and the Samba share app) | Edit YAML files, run `ha core check`, `ha core restart` and `ha backups new`, read logs. | Install both apps, set up an SSH key, and decide which commands your assistant may run without asking. |
| **Zigbee2MQTT's own configuration** | Change its log level, debounce and similar settings by editing its config file or via the bridge topics. | Access to that file (SSH or share). Publishing to bridge topics needs a broker login that is allowed to publish, which this tool deliberately is not. |
| *Optional:* a database MCP server (read-only SQL against the recorder) and a browser automation tool | Look at what the recorder actually stored, or drive the web interface. | Their own installation steps. |

A reasonable minimum for the use case in this README: this tool for the MQTT view, plus **one** write route from the table (the Home Assistant MCP server or the API with a token), plus a backup you can restore.

Things worth doing before you let an assistant change anything:

1. **Take a backup** (Settings, System, Backups) and keep your configuration in git so every change is a reviewable diff you can undo.
2. **Treat the access token like a password.** A long-lived token from an administrator account can do everything that account can do, including restarting Home Assistant or deleting data.
3. **Keep approvals on.** Your MCP client should ask before it runs a change. Do not turn on "allow everything" for a tool that can write to your home.
4. **Change one thing at a time and check it.** For example lower a radar's update rate, then run `mqtt_rates` again to see whether traffic really fell.

### Where to read more

These are third-party sites. Check that they are still current before you follow them.

- **The assistant and MCP:** [Claude Code](https://claude.com/claude-code), [Model Context Protocol](https://modelcontextprotocol.io/)
- **Home Assistant MCP server (community project):** [ha-mcp](https://github.com/homeassistant-ai/ha-mcp)
- **Home Assistant's own routes:** [MCP Server integration](https://www.home-assistant.io/integrations/mcp_server/), [Nabu Casa](https://www.nabucasa.com/) (cloud account, Assist, the connector)
- **API and tokens:** [REST API](https://developers.home-assistant.io/docs/api/rest/), [WebSocket API](https://developers.home-assistant.io/docs/api/websocket/), [long-lived access tokens](https://www.home-assistant.io/docs/authentication/#your-account-profile), [hass-cli](https://github.com/home-assistant-ecosystem/home-assistant-cli)
- **Apps (add-ons) used in the table:** [Terminal & SSH](https://github.com/home-assistant/addons/tree/master/ssh), [Samba share](https://github.com/home-assistant/addons/tree/master/samba), [Mosquitto broker](https://github.com/home-assistant/addons/tree/master/mosquitto), [MariaDB](https://github.com/home-assistant/addons/tree/master/mariadb)
- **Install and backups:** [Installing Home Assistant](https://www.home-assistant.io/installation/), [Backups](https://www.home-assistant.io/integrations/backup/)
- **Devices and software mentioned here:** [Zigbee2MQTT](https://www.zigbee2mqtt.io/), [ESPHome](https://esphome.io/), [Frigate](https://frigate.video/), [Proxmox](https://www.proxmox.com/)

## Example setup: the author's

For orientation, this is the kind of setup the tool was built and tested on. Device models, addresses, user names, folder paths and anything about the layout of the house are left out on purpose.

| Piece | What it is |
|---|---|
| Where the assistant runs | [Claude Code](https://claude.com/claude-code) (the command line version) on a Windows 11 PC |
| Home Assistant | Home Assistant OS in a virtual machine on a Proxmox host |
| Apps in Home Assistant | Mosquitto broker, Zigbee2MQTT, ESPHome Device Builder, MariaDB (recorder database), Terminal & SSH, Samba share, File editor, Samba Backup, and the ha-mcp server |
| What publishes to MQTT | Zigbee devices through Zigbee2MQTT (plugs, sensors), Wi-Fi presence radars that publish to MQTT directly, Frigate (running on a separate machine), and a few Home Assistant automations that republish selected sensors |
| How the assistant changes Home Assistant | The **ha-mcp** app, registered with Claude Code as an MCP server; plus small command line helpers that call the REST and WebSocket API with a token kept in environment variables; plus SSH (`ha core check`, `ha core restart`) and the Samba share for editing YAML |
| Configuration in git | A local git copy of the Home Assistant configuration with a `test` branch and a `main` branch. Changes are made on `test`, copied to Home Assistant, checked with `ha core check`, and merged to `main` only after they work. The remote repository is private. |
| This tool | Registered with Claude Code at user scope, using its own read-only broker login (the credentials file sits outside the project) |
| Other MCP servers | A read-only SQL server for the recorder database, and browser automation for the web interface |
| Safety net | A Home Assistant backup before risky changes, plus the git history |

A typical session: ask the assistant to run `mqtt_rates`, see which device is flooding the broker, have it lower that device's update rate through Home Assistant (with approval), then run `mqtt_rates` again to confirm the traffic fell.

## Redaction: on by default, how to switch it

Message payloads end up in the AI conversation, and MQTT carries secrets (the Zigbee2MQTT network key, camera passwords in URLs, API tokens). So **redaction is on by default**.

| You want | Set |
|---|---|
| Secrets scrubbed (default) | nothing, or `MQTT_RO_REDACT=1` |
| Payloads exactly as published | `MQTT_RO_REDACT=0` |

Set it in the environment of the server, for example when registering with Claude Code:

```
claude mcp add --scope user mqtt-readonly -e MQTT_RO_HOST=192.168.1.10 -e MQTT_RO_REDACT=0 -- /path/to/.venv/bin/python /path/to/server.py
```

To turn redaction back on, remove that variable or set `MQTT_RO_REDACT=1`, then restart the server (in Claude Code, reload the session). The same variable controls `stream.py`. Details of what is scrubbed are in [Redaction](#redaction) below. Turn it off only on a broker whose traffic you are happy to paste into a chat.

## Requirements

- Python 3.10 or newer
- An MQTT broker you can log in to. Create a separate login for this tool.
- `pip install -r requirements.txt` (`mcp` is pinned below 2 because version 2 renamed the server API)

## Setup

1. Create a virtual environment and install the requirements.
   ```
   python -m venv .venv
   .venv/bin/pip install -r requirements.txt        # Windows: .venv\Scripts\pip
   ```
2. Put the broker login in a credentials file that is **not** inside this project. The default location is `~/.config/mqtt-readonly/credentials.json`:
   ```json
   {"username": "mqtt_readonly", "password": "..."}
   ```
   Restrict it to your own account (`chmod 600`, or `icacls` on Windows). The tool never prints it.
3. Register the server with Claude Code. The password is not on the command line:
   ```
   claude mcp add --scope user mqtt-readonly \
     -e MQTT_RO_HOST=192.168.1.10 -e MQTT_RO_PORT=1883 \
     -- /path/to/.venv/bin/python /path/to/server.py
   ```
   Any other MCP client works the same way: run `python server.py` over stdio with the environment variables below.

### Environment variables

| Variable | Default | Meaning |
|---|---|---|
| `MQTT_RO_HOST` | `127.0.0.1` | Broker address |
| `MQTT_RO_PORT` | `1883` | Broker port |
| `MQTT_RO_CRED_FILE` | `~/.config/mqtt-readonly/credentials.json` | Credentials file |
| `MQTT_RO_NO_AUTH` | unset | `1` connects without a login (local test broker only) |
| `MQTT_RO_FILTERS` | `#` | Comma-separated subscription filters |
| `MQTT_RO_ALLOW` | empty (allow all) | Comma-separated topic filters this tool may see at all (see below) |
| `MQTT_RO_IGNORE` | empty | Comma-separated topic filters to skip (noisy sources) |
| `MQTT_RO_BUFFER` | `5000` | Messages kept in the rolling buffer |
| `MQTT_RO_REDACT` | `1` | `0` reports payloads exactly as published (see below) |

The connection is plain MQTT. There is no TLS option yet, so use it on a trusted network.

## Running the programs

| Program | Who starts it | How |
|---|---|---|
| `server.py` | Your MCP client (Claude Code), not you | Register it once with `claude mcp add ...` (see Setup). Check it with `claude mcp list`: it should say **Connected**. The `mqtt_*` tools appear after you reload the session. You rarely run it by hand; `python server.py` just waits for an MCP client on stdin. |
| `stream.py` | You in a terminal, or Claude Code's **Monitor** tool | Set the broker address, then run it. Bash: `MQTT_RO_HOST=192.168.1.10 python stream.py --filter "zigbee2mqtt/#" --seconds 120`. PowerShell: `$env:MQTT_RO_HOST="192.168.1.10"; python stream.py --filter "zigbee2mqtt/#" --seconds 120`. In Claude Code you can also just ask for it ("watch the alarm topics for two minutes"). |
| The tests | You | `python -m unittest discover -s tests -t .` (see Tests; the integration tests need the throwaway broker). |
| `tests/demo_publisher.py` | You, only against the throwaway test broker | Publishes sample messages so the Monitor has something to show. Never point it at your real broker. |

Use the virtual environment's Python (`.venv/bin/python`, or `.venv\Scripts\python.exe` on Windows) so the pinned dependencies are found. The programs read the broker login from the credentials file, so there is no password to type.

## Tools

| Tool | What it does |
|---|---|
| `mqtt_status` | Connection state, buffer fill, uptime |
| `mqtt_topics(prefix, limit)` | Topics seen, newest first, with counts |
| `mqtt_tree(prefix, depth, limit)` | Topic tree: topics grouped by their first `depth` levels, with topic and message counts, busiest first |
| `mqtt_broker_stats` | Broker statistics from `$SYS`: version, uptime, clients, subscriptions, retained messages, messages per minute |
| `mqtt_last(topic_filter, limit)` | Latest value per matching topic (includes retained values) |
| `mqtt_recent(topic_filter, minutes, limit)` | Messages from the buffer, oldest first |
| `mqtt_rates(minutes, limit, group_levels)` | Messages per minute, busiest first: finds chatty topics |
| `mqtt_wait(topic_filter, seconds, max_messages)` | Waits for NEW messages (max 60 s) |

MQTT wildcards `+` and `#` work in every filter. Retained messages (replayed on connect) go only into the last-value map, not the buffer. Responses are capped at 20,000 characters.

## Limiting what it can see (`MQTT_RO_ALLOW`)

By default the tool subscribes to `#` and can read every topic your login can. Set `MQTT_RO_ALLOW` to a comma-separated list of topic filters to make that a hard limit:

```
MQTT_RO_ALLOW=zigbee2mqtt/#,alarm/#,$SYS/#
```

- The server only subscribes to filters inside the allow list, and drops any message outside it before it is stored.
- `stream.py` reads the same variable and refuses (`[ERROR]`, exit code 2) any `--filter` the allow list does not cover, so the Monitor tool cannot widen access.
- `MQTT_RO_FILTERS` only chooses what the server subscribes to. `MQTT_RO_ALLOW` is the limit that also constrains `stream.py`.
- Include `$SYS/#` if you want `mqtt_broker_stats` to work.

This restricts the tool, not your broker login. For enforcement on the broker itself, use an ACL (see "What read-only means here").

## Broker statistics

The server also subscribes to `$SYS/#` (the `#` filter alone does not match `$SYS` topics). Mosquitto publishes these roughly every 10 seconds, so only the latest value of each is kept and they never fill the message buffer. `mqtt_broker_stats` reports a short list of the useful figures. If the broker publishes no `$SYS` topics, or your login may not read them, the tool says so rather than failing. Other brokers use different `$SYS` names, so the output may be sparse there.

## Redaction

Message payloads end up in the AI conversation, and MQTT carries secrets: the Zigbee2MQTT network key, camera passwords in URLs, API tokens. So redaction is **on by default**:

- JSON values whose key contains `pass`, `secret`, `token`, `key`, `psk`, `auth` or `credential` become `[REDACTED]`, at any depth.
- The same pattern is applied to non-JSON text (`key=value`), and `user:password@` inside URLs is masked.
- `zigbee2mqtt/bridge/*` topics (except `bridge/state`) report their size only, because they carry network and device configuration.
- Redaction runs before a payload is trimmed or stored, so a secret cannot survive a cut.
- Binary payloads (camera JPEGs) are shown as `[binary N bytes]`.

Redaction is pattern based. It will miss a secret that sits under an unusual key name, so treat it as a safety net, not a guarantee. Set `MQTT_RO_REDACT=0` only on a broker whose traffic you are happy to paste into a chat. JSON is re-serialised compactly when redaction is on, so spacing differs from the original.

## Monitor (live stream)

```
python stream.py --filter "zigbee2mqtt/#" --exclude "zigbee2mqtt/bridge/#" --max-per-minute 30 --seconds 120
```

Each printed line becomes a chat notification when run through Claude Code's Monitor tool, so a per-minute cap applies and the excess is summarised as `[suppressed N messages ...]`. It prints `[ERROR] ...` and exits if credentials are missing, the login fails, or the broker cannot be reached. Retained replay is skipped unless you pass `--retained`.

## Optional: recording to files on your PC

The MCP server only looks at live traffic. If you want a history (what the alarm sensors said at 3 a.m., which door opened when), you can run a small recorder next to it. The recorder is included: `recorder.py`, with `recorder.example.json` as a starting point and `windows/recorder.ps1` as a Windows helper. It reuses this project's `mqtt_common.py`, so it is subscribe-only, redacts by default and uses the same broker login as the rest of the project.

**What it needs.** Nothing beyond the project's own requirements (Python 3.10+, `paho-mqtt`, the same virtual environment and credentials file as `server.py`), plus a folder it can write to. It does not use the `mcp` package, so it runs without the MCP server. Settings are environment variables: `MQTT_RO_HOST` and `MQTT_RO_PORT` (broker), `MQTT_RO_NO_AUTH=1` (broker without a login), `MQTT_RO_REDACT=0` (turn redaction off), and `MQTT_REC_DIR` (output folder, default `mqtt-logs` in your home folder).

**How to run it.**

```
python recorder.py                                        # general log
python recorder.py --config recorder.example.json alarm   # one named stream
python recorder.py --config recorder.json alarm doors cameras   # several streams, one program
```

Copy `recorder.example.json` to `recorder.json` and change the topic patterns to match your own devices. Each stream is a list of regular expressions to `include` (and optionally `exclude`) plus `keep_days`. The general log has its own `exclude` list and an optional `log_changes_only` list for topics that repeat the same payload. On Windows, `windows\recorder.ps1 -Action start|stop|status|register|unregister -Streams alarm,doors` starts and stops it and, with `register`, creates the logon task. Read the script before running `register`.

**Where it records.** On the computer that runs the recorder (the same PC as the assistant), as plain text files. Nothing is stored in Home Assistant or in its database. Home Assistant only holds the on/off switches that pause the recorder (see "Pausing").

**What it records.**

| Recorder | What goes in (the example config) | Kept |
|---|---|---|
| General log | Everything on the broker except noise: retained replay on connect, high-rate radar target topics, Home Assistant discovery messages, the Zigbee2MQTT bridge topics and `$SYS` | 7 days |
| `alarm` | Topics the alarm system watches or publishes | 30 days |
| `doors` | Door and gate sensors | 30 days |
| `cameras` | Camera person and line-crossing events | 30 days |

One file per recorder per day, one JSON line per message (time, topic, payload). Passwords and tokens are scrubbed before writing. Yesterday's file is compressed to `.gz`, and files older than the keep time are deleted.

**How big the files get** (measured on the author's installation, about 300 messages a minute). The general log grows about 17 KB a minute, roughly 23 MB a day, and compresses about 15 to 1, so a compressed day is around 1.5 MB. The `alarm` file grows about 6 MB a day. The `doors` and `cameras` files only grow when something happens, usually a few KB a day. With this retention the whole folder stays under about 100 MB. Your numbers depend on how chatty your devices are; run `mqtt_rates` to see.

**The processes.** The general log and the named streams are two separate programs, each with its own connection to the broker, so they never interfere. All the streams you list on one command line (`alarm doors cameras`) run inside one program. On Windows, a program started from a virtual environment shows up as two processes (a launcher and the real one), so two entries per recorder is normal.

**Writing.** Each message is written and flushed immediately, so a crash loses nothing. When the recorder connects it records the retained messages once, marked `"retained": true`, as a snapshot of the current state. Streams keep recording whatever state your alarm or other devices are in; nothing in the recorder looks at it.

**Reboots and restarts.**

- *Home Assistant restart:* nothing to do. The broker is a separate service and keeps running, so the recorder stays connected.
- *Broker restart:* the recorder reconnects on its own within about half a minute and writes a "connected" line.
- *PC reboot or sleep:* if the recorder is registered as a scheduled task that starts at logon and restarts on failure, it starts by itself after a reboot. While the PC sleeps nothing is recorded; it reconnects after waking. If nobody logs in after a reboot, nothing records.
- *It cannot hang Home Assistant.* The recorder only listens. If it stops or stalls, nothing in Home Assistant is affected.

**Pausing.** In Home Assistant, create one MQTT switch per recorder whose state topic and command topic are the same retained topic (for example `mqttlog/alarm`) with payloads `ON` and `OFF`. The recorder watches those topics. `OFF` pauses writing for that recorder and puts a "paused" line in the file; `ON`, or no message at all, means recording. A pause survives restarts because the broker keeps the retained message. The recorder program keeps running while paused. The switches cannot start or stop the program itself, only pause what it writes. Starting and stopping it is done on the PC (a shortcut, or the scheduled task).

## Viewing the output in a window

**Today** there are three ways to see what the tool is reporting:

- **In the chat.** Tool results (`mqtt_rates`, `mqtt_recent` and so on) appear in your Claude Code conversation, and the Monitor tool pushes live lines into it.
- **In your own terminal window.** Run `stream.py` yourself (see "Running the programs") and watch it print one line per message. Raise the cap for a busy broker with `--max-per-minute 600`, or send it to a file with `> mqtt.log` and open that in an editor.
- **In an MQTT client.** Any desktop MQTT client logged in with the same read-only login shows the same traffic; this tool adds nothing there.

**Planned, not built yet:** a small viewer window (a local web page or a terminal screen) that shows the live stream, the busiest topics, and the questions the assistant has asked the tool, side by side, so that you can follow what it is looking at while it works. It would stay read-only, listen on your own machine only, and use the same redaction setting. Until then, the terminal route above is the way to watch in a separate window.

## What "read-only" means here

The code has no publish path, and a test enforces that. But the **broker login can still publish** unless you restrict it on the broker. For real enforcement, give the login read access only. With Mosquitto, an ACL file like this does it:

```
user mqtt_readonly
topic read #
```

Be careful: once you enable `acl_file`, every other user and client must also be listed in it, or they lose access. Back up the broker configuration first.

## Known limits

- The buffer holds 5,000 messages by default. A very chatty device shortens the window; use `MQTT_RO_IGNORE` or lower that device's update rate. `mqtt_rates` reports the effective window.
- The buffer only holds what arrived while the server was running.
- No TLS and no MQTT 5 specific features.

## Tests

Most tests run without a broker. The integration tests need a throwaway broker and skip themselves when it is not running:

```
docker run -d --rm --name mqtt-ro-test -p 18830:1883 eclipse-mosquitto:2 mosquitto -c /mosquitto-no-auth.conf
python -m unittest discover -s tests -t .
docker stop mqtt-ro-test
```

(Git Bash on Windows needs `MSYS_NO_PATHCONV=1` in front of `docker run`.) `tests/demo_publisher.py` publishes sample messages to that test broker so the Monitor tool has something to stream. It is a test helper and is not part of the server.

## Acknowledgments

- **[OdorDecoder](https://github.com/OdorDecoder)** (the author): idea, requirements, testing on a real Home Assistant installation, and every decision about what the tool should and should not do.
- **Claude** (Anthropic's AI assistant, used through Claude Code): wrote the code, tests and documentation in collaboration with the author.
- Built on the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk), [Eclipse Paho MQTT client](https://github.com/eclipse-paho/paho.mqtt.python) and [Eclipse Mosquitto](https://mosquitto.org/) (used as the throwaway test broker).
- Ideas for features came from looking at descriptions of other MQTT MCP servers: [mcmqtt](https://git.supported.systems/MCP/mcmqtt/src/branch/main/llms.txt), [tspspi/mcpMQTT](https://lobehub.com/mcp/tspspi-mcpmqtt) and [rsbohn/mqtt-bridge](https://lobehub.com/mcp/rsbohn-mqtt-bridge). No code was copied from them, and thanks to their authors for showing what is useful.

## Disclaimer: use at your own risk

This is a first attempt, shared as is, under the MIT license, which already says the software comes **without warranty of any kind**. In plain words:

- **The author takes no responsibility for anything that goes wrong** from using, misusing or relying on this software. That includes, without limit, exposed secrets or private data, a broker or smart-home device that misbehaves or loses access, wrong advice from an AI assistant that uses this tool, and any cost or damage that follows.
- The tool is read-only in its own code, but your broker login may still be able to publish unless you restrict it on the broker. See "What read-only means here".
- Redaction is pattern based and can miss a secret. Do not rely on it as your only protection. Review what you send to any AI service.
- Test on a non-critical setup first, and take a backup before changing your broker or Home Assistant configuration.

## A note on personal information

Care was taken to scrub this repository of personal information: the author's network addresses, file paths, credentials and device names were removed from the code, tests and documentation, and the full git history was checked for secrets before publishing. The example values you see (such as `192.168.1.10`, `mqtt_readonly` or the fake passwords in the tests) are placeholders. No scrub is perfect, so if you spot something that should not be here, please open an issue.

## License

MIT, see `LICENSE`.