mqtt-mcp-server
An MCP server that subscribes to an MQTT broker, stores every message with a timestamp in SQLite, and lets an AI agent query the past instead of waiting for the next message.
list_topics(pattern, seit_stunden)— topic inventory: what exists, how many messages, when last seen.get_last(topic)— last known value immediately, no waiting (e.g. for a sleeping battery sensor).get_history(topic, seit_stunden, limit)— timestamped history, the core feature; can exclude the retained startup burst (mit_startschwall).get_tree(prefix, tiefe)— topic tree overview, like MQTT Explorer.find_silent(still_seit_stunden)— topics that stopped reporting, with warnings when connection gaps make silence ambiguous.get_gaps(seit_stunden)— periods when the collector was not connected, so "device silent" can be told apart from "nobody was listening".broker_konflikte(seit_stunden, nur_verdaechtige)— finds topics fed by more than one broker and classifies each as mirrored, probably mirrored, barely overlapping, independent (two writers), or unclear; amessbarfield says whether the result is trustworthy.status()— connection state, data volume, oldest retained timestamp, write mode, and last error (including failed connect attempts with cause and attempt count).publish(topic, payload, qos, retain)— send a message, but only when write mode is enabled and the topic is not block-listed (off by default).Automatic retention — deletes messages older than N days (default 30) and enforces a size cap (default 2048 MB), reporting every cleanup.
Provides tools for interacting with MQTT brokers, enabling AI agents to subscribe to topics, store messages with timestamps, query historical data, detect silent topics, monitor connection gaps, and optionally publish messages.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mqtt-mcp-server What is the last value of topic 'home/bedroom/temperature'?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
mqtt-mcp-server
An MCP server for MQTT that remembers. It subscribes to a broker, stores every message with a timestamp in SQLite, and lets an AI agent ask questions about the past — not just about the next message that happens to arrive.
Why another MQTT MCP server
The existing ones answer "wait for the next message on this topic". That is the wrong question for diagnosing home automation:
A battery-powered sensor (Shelly H&T) sleeps for hours. Waiting for its next message means waiting for hours.
A broken device sends nothing at all. Waiting tells you nothing — you need to know when it last spoke.
"No data" is ambiguous. Was the device silent, or was the collector not listening? Without a record of connection state, both look identical.
This server answers all three.
Related MCP server: SQLite MCP Server
Tools
Tool | Purpose |
| Topic inventory — what exists, how many messages, last seen |
| Last known value immediately, no waiting |
| Timestamped history — the core feature |
| Topic tree, like MQTT Explorer |
| Topics that stopped reporting |
| When was the collector disconnected? |
| Which topics are fed by more than one broker — and is that a bridge or two writers? |
| Connection, data volume, write mode |
| Send a message — disabled by default |
find_silent and get_gaps belong together
find_silent deliberately warns you when connection gaps exist in the queried
period. A topic can look "silent" simply because nobody was listening. The server
refuses to let you confuse the two.
A failed connection is not a quiet one
If the broker cannot be reached at all — DNS, routing, firewall, refused — paho
never calls on_disconnect, because there was never a connection. Up to v0.1.0 that
case left no trace: status() showed verbunden: false with letzter_fehler: null,
and get_gaps showed nothing, so a collector that could not connect looked exactly
like one that simply received no messages.
Since v0.2.0 a failed attempt is recorded:
status().letzter_fehlercarries the real cause and the number of attempts, e.g.connect fehlgeschlagen (7x): OSError: [Errno 65] No route to host.One
disconnectedevent per failure streak (not one per retry — paho keeps retrying with backoff up to 120 s).get_gapsshows it as an open gap ("hinweis": "noch offen") until the next successful connect closes it.
Install
git clone https://github.com/Schimmilab/mqtt-mcp-server.git
cd mqtt-mcp-server
python3 -m venv .venv
.venv/bin/pip install -e .Register with Claude Code:
claude mcp add mqtt --scope user \
--env MQTT_MCP_HOST=192.168.1.10 \
-- /ABSOLUTE/PATH/TO/mqtt-mcp-server/.venv/bin/mqtt-mcp-serverA newly registered server is only picked up by a new session — MCP connections are fixed at session start.
Configuration
Variable | Default | |
|
| broker host |
|
| |
| — | optional auth |
|
| comma-separated subscription filters |
|
| one file per broker — see below |
| all other | databases to compare against |
|
| delete messages older than this |
|
| hard cap, triggers oldest-first deletion |
|
| write mode |
| see | never published to, even in write mode |
Running two brokers side by side
Migrating a home automation system rarely happens in one jump. While the old and the new broker run in parallel, the same topic exists on both — and a value without a recorded origin is not wrong, it is unattributable. That is the worse kind of error, because it still looks like a measurement.
Two things make this visible:
Every row carries a
brokercolumn (host:port). Rows written before this existed stayNULL— deliberately. Backfilling them with the current broker would be an invented origin.Give each broker its own database file (
MQTT_MCP_DB). The origin is then guaranteed structurally, not merely by a column somebody has to fill correctly.broker_konflikte()attaches all of them read-only and answers the one question that matters: which topics are fed by more than one broker?
The result carries a messbar ("measurable") field, and it is the point of
the whole tool: an empty conflict list is only an all-clear when
messbar is true. If a peer database could not be read, or if most rows
predate the broker column, you get "teilweise" plus a warning — because
"no conflicts found" is exactly the answer you were hoping for, and that is
precisely when a broken measurement does the most damage.
A bridge is not a conflict
If a bridge runs between the brokers, both carry the same topics — that is the normal state, not the anomaly. The first real run reported 129 of 147 topics, none of which needed action. A tool that flags 88 % gets ignored by the third time, so every doubled topic is classified:
| bridge proven — for each message, the nearest message on the other broker carries an identical payload |
| same pattern, but too few pairs to call it proven |
| the two rarely send at the same time — that is a migration, not double control |
| the real finding: overlapping in time, different payloads |
| not decidable — reported as such rather than guessed |
Two details decide whether the classification is honest rather than merely confident:
Nearest partner per message, not all pairs in the window. The naive version is a cross join and lies badly on high-frequency topics.
No partner ≠ different payload. Dividing hits by all messages turns absence into "0 % identical", which reads as "two writers". It isn't.
nur_verdaechtige=True (default) lists only what is not cleared, and counts
the rest in entwarnt_nicht_gelistet.
Verify the canary itself. A canary that finds nothing is indistinguishable
from a broken one, so tools/canary-doppelbesitz.py publishes two test topics:
one written independently by both brokers (must be reported as unabhaengig)
and one written identically by both (must be cleared). Run it, then call
broker_konflikte(seit_stunden=0.1) and check that exactly the first one shows
up. Without the second topic the first proves nothing — a canary that flags
everything would pass it too.
Writing is off by default — on purpose
publish requires two conditions: write mode enabled and the topic not on the
block list. The default block list covers power switches and device restarts.
⚠️ The block list is a guard rail, not a security boundary. Anyone with access to the server can change it. Real enforcement requires a broker-side ACL.
The default exists because of a real incident: a switched socket in front of two servers failed and took the whole home automation down for nine days, costing seven weeks of measurement data. Measuring is safe; switching is not.
Retained messages
On connect, a broker delivers its entire retained backlog at once — potentially tens of thousands of messages with old content but a fresh arrival time. Storing those naively corrupts every history from the first second.
This server stores them, but flags them: aus_startschwall: true. get_last uses
them (that is how a sleeping sensor still has a value); get_history can exclude
them.
Known limitations
Broker authentication, connection gaps and silence detection are tested end-to-end
against a real broker since v0.3.0: tests/test_broker_e2e.py starts a killable test
broker (amqtt, pure Python, its own process) and checks
case | positive control | must go red |
auth | correct credentials connect | wrong password → not connected, error + open gap recorded |
| no outage → no gap | broker killed and restarted → exactly one closed gap |
| both test devices arrive | the device that stopped is reported, the active one is not |
Each test was checked against deliberately broken server code (outage not recorded, credentials not passed) and fails as it should.
uv run --group dev pytest -q tests/test_broker_e2e.pyOnly username/password auth is covered; TLS is not.
History only covers times when the server was running. It is a debugging tool started on demand, not a 24/7 collector. If something breaks while you are away and no session is open, nothing is recorded.
macOS: the collector inherits the Local Network permission of whatever launched
it. Started from an IDE's terminal (IntelliJ, CLion, VS Code …), Python and Node
get EHOSTUNREACH / No route to host for every LAN address if that IDE lacks
System Settings → Privacy & Security → Local Network. Apple's own binaries (nc,
curl) are not affected, which makes the failure look selective. Granting the
permission takes effect only after restarting the IDE. Since v0.2.0 the cause
shows up in status().letzter_fehler; before, it did not.
Retention
Runs at startup and hourly: delete older than N days, then — if still over the size cap — delete oldest-first. Every cleanup reports what it removed to stderr, including the oldest remaining timestamp. Silent deletion would quietly destroy the answer to "since when has this device been quiet?".
Check which limit actually applies: on a busy broker the size cap wins long before
the day limit. In practice ~1.8 GB held about four days of a home installation with
~200 topics — status().bestand.aeltestes tells you the real horizon.
License
MIT
Available Tools
9 toolsbroker_konflikteA
Topics, die von MEHR ALS EINEM Broker bespielt werden.
Der Ownership-Canary fuer den Parallelbetrieb zweier Broker: Die gefaehrliche Lage ist nicht "ein Geraet antwortet nicht", sondern "zwei Systeme schreiben auf dasselbe Topic und keiner merkt es".
Verglichen wird ueber ALLE Broker-Datenbanken nebeneinander (jeder Server
hat seit dem 22.08. seine eigene). messbar sagt, ob das Ergebnis
ueberhaupt belastbar ist — bei false oder "teilweise" ist eine leere
Konfliktliste ausdruecklich KEINE Entwarnung.
⛔ Eine BRIDGE ist kein Konflikt. Laeuft eine Bridge zwischen den Brokern, fuehren beide dieselben Topics — das ist der Normalzustand, nicht die Anomalie. Jedes Doppel-Topic wird deshalb eingeordnet:
gespiegelt Bridge belegt (hohe Payload-Gleichheit) wahrscheinlich_gespiegelt Payloads zu einfoermig fuer einen Beweis, aber der Zeitversatz spricht dafuer unabhaengig ⛔ der echte Befund: zwei Schreiber unklar nicht entscheidbar — von Hand ansehen
nur_verdaechtige=True (Default) listet Gespiegeltes nicht, sondern
zaehlt es in gespiegelt_nicht_gelistet. Auf False setzen, um alles zu
sehen.
Inputs: limit, stichprobe, seit_stunden, nur_verdaechtige. Returns: object
find_silentA
Topics, die seit X Stunden NICHT mehr gemeldet haben.
Die Frage vom 2026-08-01: 'seit wann meldet dieser Stecker nichts mehr?' (sonoff-4854 war seit dem 02.06. still — ein defekter Zwischenstecker).
Inputs: limit, still_seit_stunden. Returns: object
get_gapsB
Zeitraeume, in denen der Sammler NICHT mit dem Broker verbunden war.
Trennt 'Geraet ist still' von 'ich habe nicht zugehoert'. Ohne diese Auskunft sehen beide Faelle in den Daten identisch aus.
Inputs: seit_stunden. Returns: object
get_historyB
Verlauf eines Topics mit Zeitstempeln — die Kernfunktion dieses Servers.
mit_startschwall=False blendet den retained-Altbestand aus, der direkt nach dem Verbinden ankommt und einen irrefuehrend frischen Zeitstempel traegt.
Inputs: topic (required), limit, seit_stunden, mit_startschwall. Returns: object
get_lastA
Letzter bekannter Wert eines Topics — sofort, ohne auf die naechste Nachricht zu warten.
Genau das, was fertige MQTT-MCP-Server nicht koennen: bei einem schlafenden Batteriesensor (Shelly H&T) kaeme die naechste Nachricht erst in Stunden.
Inputs: topic (required). Returns: object
get_treeC
Topic-Baum ab einem Praefix — der Ueberblick wie im MQTT Explorer.
Inputs: limit, tiefe, prefix. Returns: object
list_topicsB
Topic-Inventar: welche Topics gibt es, wie viele Nachrichten, wann zuletzt.
pattern: Glob wie 'tele/*' oder '*SENSOR'. seit_stunden schraenkt auf den juengeren Zeitraum ein.
Inputs: limit, pattern, seit_stunden. Returns: object
publishA
Nachricht senden. Nur bei aktivem Schreibmodus und nicht auf gesperrte Topics.
⚠️ Die Sperrliste ist eine Bremse gegen Fehlgriffe, keine Sicherheitsgrenze.
Inputs: topic (required), payload (required), qos, retain. Returns: object
statusA
Zustand des Servers: Verbindung, Datenbestand, Schreibmodus.
Inputs: no named parameters. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 9 tools
Most tools have clearly distinct purposes: broker_konflikte, find_silent, get_gaps, get_history, get_last, get_tree, list_topics, publish, and status each target a different query. There is mild overlap between list_topics and get_tree (inventory vs. tree view) and between find_silent and get_gaps (device silent vs. collector disconnected), but the descriptions explicitly distinguish these cases.
Four tools follow a clean get_* pattern (get_gaps, get_history, get_last, get_tree) plus list_topics, but broker_konflikte is a German noun-first name and find_silent uses a different verb style, while publish and status are bare verbs/nouns. All snake_case, but the verb conventions are mixed and languages are inconsistent.
Nine tools is well-scoped for an MQTT broker client, covering query, diagnostics, write, and status without redundancy. Each tool earns its place in the workflow.
The surface covers topic history, latest value, tree/list inventory, silence and gap diagnostics, conflict detection, publish, and status — a solid read/diagnostic/write lifecycle. Minor gaps like retained-message management or subscription/streaming operations exist but are not essential.
Maintenance
Related MCP Connectors
Analytical memory for AI agents: a real Postgres queried in plain English over MCP. One command.
The all-in-one data stack for agents. Upload files, run SQL, evolve tables, and render charts.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Astra DB tools for agents: schema, find, vector search, guarded writes, and interactive views.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables LLM agents to interact with MQTT brokers through publish, subscribe, and query operations. Provides fine-grained topic permissions with wildcard support for secure IoT device communication and sensor data access.2BSD 3-Clause
- AlicenseNot gradedqualityDmaintenanceProvides comprehensive SQLite database interaction for AI agents, including data manipulation, schema inspection, and automated query logging. It features a unique context preservation pattern that uses a dedicated meta-table to help autonomous agents maintain self-documenting database architectures.27 npm1MIT
- AlicenseNot gradedqualityDmaintenanceConnects AI assistants to MQTT brokers for smart home automation and IoT device control, enabling topic discovery, sensor reading, command sending, and event monitoring.2MIT
- AlicenseBqualityDmaintenanceEnables AI agents to interact with local SQLite databases with full CRUD, schema introspection, foreign key relations, generated columns, and multi-format import/export (CSV, JSON, XLSX) through natural language.2614 npmMIT