convez.ai
MCP ServerIntegração & APIsAvançado
alexander-zimmermann

IoT MCP Bridge

alexander-zimmermann/iot-mcp-bridge

Bridge seguro para consultar dados IoT domésticos via MCP

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP read-only que conecta dados de IoT doméstico (KNX, EMS, WARP, SolarEdge) armazenados em TimescaleDB ao Claude e outros clientes MCP-aware. Expõe ferramentas bem-estruturadas para consultar séries temporais de forma segura, sem acesso SQL direto ao banco.

Instalação

$npx convez-ai alexander-zimmermann/iot-mcp-bridge

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 2 dias
Versão
v1.36.0
Issues abertas
6
Contribuidores
2

Casos de uso

  • Consultar histórico de aquecimento, painéis solares e carga de EV no modelo de linguagem
  • Agregar dados de sensores em buckets horários ou maiores com continuous aggregates automáticos
  • Descobrir esquemas de dados IoT e inspecionar payloads JSONB sem SQL direto

Veredito

Solução bem pensada para o problema real de conectar IoT doméstico a LLMs sem expor acesso direto ao banco. Implementação clara com foco em segurança, descoberta de schema e agregação inteligente; ideal para quem já tem TimescaleDB em um homelab e quer questionar seus dados via Claude.

README

A tradução para o português deste README ainda está na fila.

iot-mcp-bridge

A read-only Model Context Protocol server that lets a large language model — Claude.ai, a local Ollama instance, or any other MCP-aware client — answer questions about an IoT-enabled home: heating, photovoltaics, EV charging, KNX bus events, room climate.

Instead of giving the LLM raw SQL access (brittle, hard to bound, no audit), iot-mcp-bridge exposes a small set of well-shaped tools backed by TimescaleDB hypertables plus their continuous aggregates. The LLM picks a tool, the server runs a parametrised query against a long-term timeseries store, and the result comes back already aggregated and capped to a token-friendly size.

Why

Modern homes generate a lot of telemetry — KNX writes, smart-meter readings, heat-pump flow temperatures, wallbox sessions, inverter data — and most of it lands in some database that nobody ever queries. Pointing an LLM at the database directly works for prototypes but breaks down quickly: the model invents column names, returns 50,000 rows, can't tell hypertables apart from rollups, and there is no policy on what it's allowed to read.

iot-mcp-bridge is the small, opinionated middle layer:

  • Discoverable — the LLM can list data sources and inspect schemas, including a sample of JSONB keys for raw payloads.
  • Aggregation-aware — when a query asks for hourly buckets or coarser, the server transparently routes to a TimescaleDB continuous aggregate, returning fewer rows and faster responses.
  • Read-only by construction — the server only ever connects with a Postgres role that has SELECT privileges. There is no execute_sql tool.
  • Result-bounded — every tool caps its output. The LLM cannot accidentally pull a year of 5-second sensor data into its context window.
  • Pluggable — the data source is just Postgres + TimescaleDB. There is nothing homelab-specific in the server itself; the schema discovery works on any TimescaleDB instance.

What it gives you

The server exposes two layers of tools — generic ones that work against any TimescaleDB schema, and domain-specific ones that hide the table layout behind high-level questions:

Generic

ToolWhat it does
list_data_sources()Enumerates all hypertables and continuous aggregates in the connected database, with their time range.
get_schema(table)Returns columns, types, and — for tables with a JSONB payload column — a sample of the most common JSON keys, so the LLM can construct sensible expressions like raw->>'flow_temp'.
query_timeseries(table, columns, from_ts, to_ts, aggregation, bucket, filters)Bucketed aggregate query (avg, sum, min, max, count). Automatically uses a *_1h continuous aggregate when the bucket is one hour or coarser and an aggregate exists.

Domain

ToolWhat it does
query_energy_flow(from_ts, to_ts, bucket)One row per bucket joining PV production, grid, household consumer, battery net, and wallbox power. Reads the hourly continuous aggregates; bucket must be 1 hour or coarser.
query_heating_cycles(from_ts, to_ts, …)Detects ON/OFF burner cycles from ems_esp (topic = 'boiler_data') via LAG window functions. Returns one row per cycle with start, end, duration, peak and average burner power.
query_room_climate(room, from_ts, to_ts, bucket)Bucketed temp/humidity/etc. per GA name within a room. room is whitelisted against the imported KNX catalog so unknown rooms produce a precise error the LLM can self-correct.
query_knx_events(from_ts, to_ts, room, ga, name, …)Raw event log against the ga_catalog_view view; supports room/ga/name/functions predicates with a default limit of 200.
query_unifi_events(from_ts, to_ts, camera, …)Recent UniFi Protect Alarm Manager events (person/vehicle/motion detections per camera) for security review.
correlate_events(source_a, source_b, …)Lagged Pearson correlation between two time-series streams. Each source is {table, column}; returns the best lag plus the top 10 by |corr|.

Insights (read-only views into the anomaly/forecast tables populated by iot-insights-engine batch jobs)

ToolWhat it does
detect_anomalies(source, severity, uc, …)Recent anomaly rows, newest first, filterable by source/severity/use-case.
explain_anomaly(time, source, metric, …)One anomaly by composite key plus the surrounding context window of the same (source, metric).
get_forecast(metric, horizon_hours, model)Stored model forecasts (PV via Forecast.Solar, seasonal via statsforecast).
generate_insight_report(timeframe, top_n)Aggregate anomaly summary (severity counts, top use-cases, recent serious entries) for a digest.

Live (current state straight from NATS JetStream; requires MCP_NATS_ENABLED=true)

ToolWhat it does
get_current_state(domain, identifier)Last retained message for a domain (knx/heating/dhw/solar/wallbox) with freshness metadata.
get_current_knx(room, function, name, …)Current value per matching KNX group address — answers "which lights are on right now?".
subscribe_nats(subject, duration_seconds)Tails an allowlisted NATS subject for a short bounded window.

Later phases (tracked separately) add optimization advisors and approval-gated control.

Standalone usage

iot-mcp-bridge does not depend on any specific cluster, ingress, or auth setup. You can run it against any TimescaleDB instance you already have.

Prerequisites

  • Python 3.14
  • uv
  • A Postgres database with the TimescaleDB extension and at least one hypertable
  • A Postgres role with SELECT on the schemas/tables you want to expose

Run it

git clone https://github.com/alexander-zimmermann/iot-mcp-bridge.git
cd iot-mcp-bridge
uv sync

export MCP_DB_HOST=localhost
export MCP_DB_PORT=5432
export MCP_DB_NAME=mydb
export MCP_DB_USERNAME=mcp_readonly
export MCP_DB_PASSWORD=secret
# The live tools default to an in-cluster NATS URL — disable them standalone:
export MCP_NATS_ENABLED=false

uv run iot-mcp-bridge
# server listening on http://0.0.0.0:8080/mcp

Connect Claude.ai

Open Claude.ai → Settings → Connectors → "Add custom connector" → URL http://localhost:8080/mcp (or wherever you exposed the server). Start a chat and ask "what data sources do you have?" — the connector will surface the tools listed above.

For a production deployment, put the server behind TLS and an authenticating proxy (or enable the built-in Authentik OAuth + JWKS validation, see configuration below).

Configuration

All settings are environment variables, prefixed with MCP_:

VariableDefaultPurpose
MCP_HOST0.0.0.0Bind address
MCP_PORT8080Bind port
MCP_LOG_LEVELINFOstructlog level
MCP_LOG_FORMATjsonjson or console
MCP_DB_HOSTrequiredPostgres host
MCP_DB_PORT5432Postgres port
MCP_DB_NAMErequiredDatabase name
MCP_DB_USERNAMErequiredRead-only role
MCP_DB_PASSWORDrequiredPassword
MCP_DB_USERNAME_FILE—Read role from a mounted file (overrides MCP_DB_USERNAME)
MCP_DB_PASSWORD_FILE—Read password from a mounted file (overrides MCP_DB_PASSWORD)
MCP_DB_POOL_MIN2psycopg pool min size
MCP_DB_POOL_MAX10psycopg pool max size
MCP_QUERY_ROW_LIMIT5000Hard cap on rows returned by the query tools
MCP_METRICS_PORT9090Prometheus /metrics port
MCP_AUTH_ENABLEDfalseEnable Bearer-token validation
MCP_AUTH_JWKS_URL—JWKS endpoint when auth is enabled
MCP_AUTH_ISSUER—Expected iss claim
MCP_AUTH_AUDIENCE—Expected aud claim
MCP_AUTH_JWKS_TTL_SECONDS3600JWKS cache lifetime
MCP_AUTH_JWKS_MIN_REFRESH_SECONDS30Cooldown between JWKS fetch attempts
MCP_AUTH_RESOURCE_URL—Public URL for RFC 9728 protected-resource metadata
MCP_NATS_ENABLEDtrueEnable the live tools (NATS JetStream)
MCP_NATS_SERVERSnats://nats.nats.svc:4222Comma-separated NATS server URLs
MCP_NATS_NKEY_SEED_FILE—nkey seed file for NATS auth (anonymous when unset)
MCP_LIVE_STALE_SECONDS600Age after which cyclic live state is flagged stale
MCP_SUBSCRIBE_MAX_SECONDS30Hard cap for subscribe_nats windows

When MCP_AUTH_ENABLED=true, every request must carry a valid OIDC Bearer token signed by the configured JWKS. Tested against Authentik but works with any OIDC-compliant authorization server.

Operational endpoints

  • GET /livez — liveness: process is up; never depends on DB/NATS health.
  • GET /healthz — readiness/deep health: 503 when the database is unreachable; reports NATS connectivity when the live tools are enabled.
  • GET :9090/metrics — Prometheus metrics (tool calls, DB query durations, JWKS refreshes, NATS fetches).

Container image

Multi-arch images are published on every release tag:

docker run --rm -p 8080:8080 \
  -e MCP_DB_HOST=host.docker.internal \
  -e MCP_DB_NAME=mydb \
  -e MCP_DB_USERNAME=mcp_readonly \
  -e MCP_DB_PASSWORD=secret \
  -e MCP_NATS_ENABLED=false \
  ghcr.io/alexander-zimmermann/iot-mcp-bridge:latest

GA catalog

The domain tools (query_room_climate, query_knx_events, get_current_knx) need a Postgres ga_catalog table that maps each KNX group address to a name, room, function, and description. The catalog is generated from the ETS .knxproj file by knx-nats-bridge, which also ships the import job that writes it into Postgres (the importer was moved there when this repo was slimmed down to the MCP server itself).

Development

uv sync --extra dev
uv run ruff check .
uv run ruff format --check .
uv run mypy src
uv run pytest -q

Tests use testcontainers to spin up a real TimescaleDB instance — no DB mocks.

License

GPL-2.0-or-later. See LICENSE.

Ver o original no GitHub

Bom para

Relacionados