iot-device-mcp-server 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.so
5
+ .env
6
+ .venv
7
+ env/
8
+ venv/
9
+ dist/
10
+ build/
11
+ *.egg-info/
12
+ .eggs/
13
+ *.egg
14
+ .pytest_cache/
15
+ .coverage
16
+ htmlcov/
17
+ .DS_Store
18
+ *.log
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AiAgentKarl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: iot-device-mcp-server
3
+ Version: 0.1.0
4
+ Summary: MCP Server for IoT Device Management — register, monitor, and control IoT devices via AI agents
5
+ Project-URL: Homepage, https://github.com/AiAgentKarl/iot-device-mcp-server
6
+ Project-URL: Repository, https://github.com/AiAgentKarl/iot-device-mcp-server
7
+ Author-email: AiAgentKarl <coach1916@gmail.com>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: ai-agents,device-management,edge-computing,iot,mcp,mqtt
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: System :: Networking
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: httpx>=0.27.0
19
+ Requires-Dist: mcp>=1.0.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # IoT Device Management MCP Server
23
+
24
+ [![PyPI version](https://badge.fury.io/py/iot-device-mcp-server.svg)](https://pypi.org/project/iot-device-mcp-server/)
25
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
26
+
27
+ **MCP Server for IoT Device Management** — Register, monitor, and control IoT devices via AI agents.
28
+
29
+ A generic, open-source alternative to platform-specific IoT management tools. No cloud API key required — all data stored locally.
30
+
31
+ ## Features
32
+
33
+ - **Device Registry** — Register and manage IoT devices (sensors, actuators, gateways, cameras)
34
+ - **Real-time Status** — Monitor device health, telemetry, and connectivity
35
+ - **Remote Commands** — Send commands (reboot, enable, disable, calibrate) to devices
36
+ - **Firmware Updates** — Track and simulate firmware update workflows
37
+ - **Alert Management** — Create, filter, and resolve device alerts
38
+ - **Fleet Analytics** — Health scores, status summaries, and recommendations
39
+ - **Fleet Dashboard** — Single-view overview of your entire device fleet
40
+
41
+ ## Tools
42
+
43
+ | Tool | Description |
44
+ |------|-------------|
45
+ | `register_device` | Register a new IoT device with type, location, and firmware version |
46
+ | `list_devices` | List all devices with optional filters (type, location, status, tag) |
47
+ | `get_device_status` | Get real-time status and simulated telemetry for a device |
48
+ | `update_firmware` | Simulate firmware update with version history |
49
+ | `send_command` | Send remote commands (reboot, enable, disable, calibrate, etc.) |
50
+ | `get_alerts` | Retrieve device alerts filtered by severity or device |
51
+ | `resolve_alert` | Mark an alert as resolved with optional notes |
52
+ | `device_analytics` | Fleet health score, statistics, and recommendations |
53
+ | `get_fleet_dashboard` | Complete fleet overview with recent activity |
54
+
55
+ ## Installation
56
+
57
+ ```bash
58
+ pip install iot-device-mcp-server
59
+ ```
60
+
61
+ ## Usage with Claude Desktop
62
+
63
+ Add to your `claude_desktop_config.json`:
64
+
65
+ ```json
66
+ {
67
+ "mcpServers": {
68
+ "iot-device": {
69
+ "command": "iot-device-mcp-server"
70
+ }
71
+ }
72
+ }
73
+ ```
74
+
75
+ ## Example Workflow
76
+
77
+ ```
78
+ Agent: "Register a temperature sensor in the server room"
79
+ → register_device(name="Temp Sensor 01", device_type="sensor", location="Server Room")
80
+
81
+ Agent: "What's the current status?"
82
+ → get_device_status(device_id="dev_abc123")
83
+
84
+ Agent: "Reboot the sensor"
85
+ → send_command(device_id="dev_abc123", command="reboot")
86
+
87
+ Agent: "Are there any critical alerts?"
88
+ → get_alerts(severity="critical")
89
+
90
+ Agent: "Show me the fleet health"
91
+ → device_analytics()
92
+ ```
93
+
94
+ ## Supported Device Types
95
+
96
+ - `sensor` — Temperature, humidity, pressure sensors
97
+ - `actuator` — Relays, motors, valves
98
+ - `gateway` — IoT edge gateways and routers
99
+ - `camera` — IP cameras and video devices
100
+ - Custom types also supported
101
+
102
+ ## Supported Protocols
103
+
104
+ - MQTT (default)
105
+ - HTTP/HTTPS
106
+ - CoAP
107
+ - LoRa/LoRaWAN
108
+
109
+ ## Data Storage
110
+
111
+ All data is stored locally in `~/.iot_device_store.json`. No cloud services required.
112
+
113
+ ## Why This Server?
114
+
115
+ - **Platform-agnostic** — Works with any IoT setup, no vendor lock-in
116
+ - **No API keys** — Fully local, no cloud dependency
117
+ - **AI-ready** — Natural language device management via Claude or any MCP-compatible AI
118
+ - **Open source** — MIT license, fork and extend freely
119
+
120
+ ## Comparison
121
+
122
+ | Feature | Digi Remote Manager | ThingsPanel | This Server |
123
+ |---------|--------------------|--------------|----|
124
+ | Platform-specific | ✅ (Digi only) | ✅ (proprietary) | ❌ (generic) |
125
+ | Open Source | ❌ | ❌ | ✅ |
126
+ | MCP Native | ❌ | ❌ | ✅ |
127
+ | No API Key | ❌ | ❌ | ✅ |
128
+ | PyPI Package | ❌ | ❌ | ✅ |
129
+
130
+ ## License
131
+
132
+ MIT License — see [LICENSE](LICENSE) for details.
133
+
134
+ ## Author
135
+
136
+ Built by [AiAgentKarl](https://github.com/AiAgentKarl) — Generalist AI Agent Infrastructure
@@ -0,0 +1,115 @@
1
+ # IoT Device Management MCP Server
2
+
3
+ [![PyPI version](https://badge.fury.io/py/iot-device-mcp-server.svg)](https://pypi.org/project/iot-device-mcp-server/)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
6
+ **MCP Server for IoT Device Management** — Register, monitor, and control IoT devices via AI agents.
7
+
8
+ A generic, open-source alternative to platform-specific IoT management tools. No cloud API key required — all data stored locally.
9
+
10
+ ## Features
11
+
12
+ - **Device Registry** — Register and manage IoT devices (sensors, actuators, gateways, cameras)
13
+ - **Real-time Status** — Monitor device health, telemetry, and connectivity
14
+ - **Remote Commands** — Send commands (reboot, enable, disable, calibrate) to devices
15
+ - **Firmware Updates** — Track and simulate firmware update workflows
16
+ - **Alert Management** — Create, filter, and resolve device alerts
17
+ - **Fleet Analytics** — Health scores, status summaries, and recommendations
18
+ - **Fleet Dashboard** — Single-view overview of your entire device fleet
19
+
20
+ ## Tools
21
+
22
+ | Tool | Description |
23
+ |------|-------------|
24
+ | `register_device` | Register a new IoT device with type, location, and firmware version |
25
+ | `list_devices` | List all devices with optional filters (type, location, status, tag) |
26
+ | `get_device_status` | Get real-time status and simulated telemetry for a device |
27
+ | `update_firmware` | Simulate firmware update with version history |
28
+ | `send_command` | Send remote commands (reboot, enable, disable, calibrate, etc.) |
29
+ | `get_alerts` | Retrieve device alerts filtered by severity or device |
30
+ | `resolve_alert` | Mark an alert as resolved with optional notes |
31
+ | `device_analytics` | Fleet health score, statistics, and recommendations |
32
+ | `get_fleet_dashboard` | Complete fleet overview with recent activity |
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install iot-device-mcp-server
38
+ ```
39
+
40
+ ## Usage with Claude Desktop
41
+
42
+ Add to your `claude_desktop_config.json`:
43
+
44
+ ```json
45
+ {
46
+ "mcpServers": {
47
+ "iot-device": {
48
+ "command": "iot-device-mcp-server"
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ ## Example Workflow
55
+
56
+ ```
57
+ Agent: "Register a temperature sensor in the server room"
58
+ → register_device(name="Temp Sensor 01", device_type="sensor", location="Server Room")
59
+
60
+ Agent: "What's the current status?"
61
+ → get_device_status(device_id="dev_abc123")
62
+
63
+ Agent: "Reboot the sensor"
64
+ → send_command(device_id="dev_abc123", command="reboot")
65
+
66
+ Agent: "Are there any critical alerts?"
67
+ → get_alerts(severity="critical")
68
+
69
+ Agent: "Show me the fleet health"
70
+ → device_analytics()
71
+ ```
72
+
73
+ ## Supported Device Types
74
+
75
+ - `sensor` — Temperature, humidity, pressure sensors
76
+ - `actuator` — Relays, motors, valves
77
+ - `gateway` — IoT edge gateways and routers
78
+ - `camera` — IP cameras and video devices
79
+ - Custom types also supported
80
+
81
+ ## Supported Protocols
82
+
83
+ - MQTT (default)
84
+ - HTTP/HTTPS
85
+ - CoAP
86
+ - LoRa/LoRaWAN
87
+
88
+ ## Data Storage
89
+
90
+ All data is stored locally in `~/.iot_device_store.json`. No cloud services required.
91
+
92
+ ## Why This Server?
93
+
94
+ - **Platform-agnostic** — Works with any IoT setup, no vendor lock-in
95
+ - **No API keys** — Fully local, no cloud dependency
96
+ - **AI-ready** — Natural language device management via Claude or any MCP-compatible AI
97
+ - **Open source** — MIT license, fork and extend freely
98
+
99
+ ## Comparison
100
+
101
+ | Feature | Digi Remote Manager | ThingsPanel | This Server |
102
+ |---------|--------------------|--------------|----|
103
+ | Platform-specific | ✅ (Digi only) | ✅ (proprietary) | ❌ (generic) |
104
+ | Open Source | ❌ | ❌ | ✅ |
105
+ | MCP Native | ❌ | ❌ | ✅ |
106
+ | No API Key | ❌ | ❌ | ✅ |
107
+ | PyPI Package | ❌ | ❌ | ✅ |
108
+
109
+ ## License
110
+
111
+ MIT License — see [LICENSE](LICENSE) for details.
112
+
113
+ ## Author
114
+
115
+ Built by [AiAgentKarl](https://github.com/AiAgentKarl) — Generalist AI Agent Infrastructure
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "iot-device-mcp-server"
7
+ version = "0.1.0"
8
+ description = "MCP Server for IoT Device Management — register, monitor, and control IoT devices via AI agents"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "AiAgentKarl", email = "coach1916@gmail.com" }]
12
+ requires-python = ">=3.10"
13
+ keywords = ["mcp", "iot", "device-management", "mqtt", "edge-computing", "ai-agents"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ "Topic :: System :: Networking",
21
+ ]
22
+ dependencies = [
23
+ "mcp>=1.0.0",
24
+ "httpx>=0.27.0",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/AiAgentKarl/iot-device-mcp-server"
29
+ Repository = "https://github.com/AiAgentKarl/iot-device-mcp-server"
30
+
31
+ [project.scripts]
32
+ iot-device-mcp-server = "iot_device_mcp_server.server:main"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/iot_device_mcp_server"]
@@ -0,0 +1 @@
1
+ # IoT Device Management MCP Server
@@ -0,0 +1,604 @@
1
+ """IoT Device Management MCP Server — Hauptmodul."""
2
+
3
+ import json
4
+ import random
5
+ import string
6
+ from datetime import datetime, timedelta
7
+ from typing import Any
8
+
9
+ from mcp.server.fastmcp import FastMCP
10
+ from .store import get_store, save_store, now_iso
11
+
12
+ # FastMCP-Server initialisieren
13
+ mcp = FastMCP(
14
+ "iot-device-mcp-server",
15
+ instructions=(
16
+ "MCP Server fuer IoT Device Management. "
17
+ "Ermoeglicht AI-Agents das Registrieren, Ueberwachen und Steuern von IoT-Geraeten. "
18
+ "Unterstuetzt Device-Registrierung, Status-Monitoring, Firmware-Updates, "
19
+ "Remote-Commands, Alert-Management und Device-Analytics. "
20
+ "Daten werden lokal in ~/.iot_device_store.json gespeichert. "
21
+ "Ideal fuer DevOps, IoT-Teams und Edge-Computing-Workflows."
22
+ ),
23
+ )
24
+
25
+ # --- Hilfsfunktionen ---
26
+
27
+ def _generate_id(prefix: str = "dev") -> str:
28
+ """Generiert eine eindeutige Geraete-ID."""
29
+ suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
30
+ return f"{prefix}_{suffix}"
31
+
32
+
33
+ def _device_uptime(registered_at: str) -> str:
34
+ """Berechnet Uptime aus Registrierungsdatum."""
35
+ try:
36
+ reg = datetime.strptime(registered_at, "%Y-%m-%dT%H:%M:%SZ")
37
+ delta = datetime.utcnow() - reg
38
+ days = delta.days
39
+ hours = delta.seconds // 3600
40
+ return f"{days}d {hours}h"
41
+ except Exception:
42
+ return "unknown"
43
+
44
+
45
+ # --- Tools ---
46
+
47
+ @mcp.tool()
48
+ def register_device(
49
+ name: str,
50
+ device_type: str,
51
+ location: str,
52
+ firmware_version: str = "1.0.0",
53
+ tags: str = "",
54
+ ip_address: str = "",
55
+ protocol: str = "mqtt",
56
+ ) -> dict:
57
+ """
58
+ Registriert ein neues IoT-Geraet im System.
59
+
60
+ Args:
61
+ name: Anzeigename des Geraets (z.B. 'Temperatur-Sensor Halle A')
62
+ device_type: Geraete-Typ (z.B. 'sensor', 'actuator', 'gateway', 'camera')
63
+ location: Standort des Geraets (z.B. 'Halle A / Regal 3')
64
+ firmware_version: Aktuelle Firmware-Version (Standard: 1.0.0)
65
+ tags: Komma-getrennte Tags (z.B. 'temperature,humidity')
66
+ ip_address: IP-Adresse des Geraets (optional)
67
+ protocol: Kommunikationsprotokoll (mqtt, http, coap, lora)
68
+ """
69
+ store = get_store()
70
+ device_id = _generate_id("dev")
71
+
72
+ device = {
73
+ "id": device_id,
74
+ "name": name,
75
+ "type": device_type,
76
+ "location": location,
77
+ "firmware_version": firmware_version,
78
+ "tags": [t.strip() for t in tags.split(",") if t.strip()],
79
+ "ip_address": ip_address,
80
+ "protocol": protocol,
81
+ "status": "online",
82
+ "registered_at": now_iso(),
83
+ "last_seen": now_iso(),
84
+ "telemetry": {},
85
+ "metadata": {}
86
+ }
87
+
88
+ store["devices"][device_id] = device
89
+ save_store(store)
90
+
91
+ return {
92
+ "success": True,
93
+ "device_id": device_id,
94
+ "message": f"Geraet '{name}' erfolgreich registriert",
95
+ "device": device
96
+ }
97
+
98
+
99
+ @mcp.tool()
100
+ def list_devices(
101
+ device_type: str = "",
102
+ location: str = "",
103
+ status: str = "",
104
+ tag: str = "",
105
+ ) -> dict:
106
+ """
107
+ Listet alle registrierten IoT-Geraete auf, optional gefiltert.
108
+
109
+ Args:
110
+ device_type: Filtert nach Geraete-Typ (sensor, actuator, gateway, etc.)
111
+ location: Filtert nach Standort (Teilstring-Suche)
112
+ status: Filtert nach Status (online, offline, warning, error)
113
+ tag: Filtert nach Tag
114
+ """
115
+ store = get_store()
116
+ devices = list(store["devices"].values())
117
+
118
+ # Filterung
119
+ if device_type:
120
+ devices = [d for d in devices if d.get("type") == device_type]
121
+ if location:
122
+ devices = [d for d in devices if location.lower() in d.get("location", "").lower()]
123
+ if status:
124
+ devices = [d for d in devices if d.get("status") == status]
125
+ if tag:
126
+ devices = [d for d in devices if tag in d.get("tags", [])]
127
+
128
+ # Zusammenfassung
129
+ status_counts = {}
130
+ for d in store["devices"].values():
131
+ s = d.get("status", "unknown")
132
+ status_counts[s] = status_counts.get(s, 0) + 1
133
+
134
+ return {
135
+ "total_registered": len(store["devices"]),
136
+ "filtered_count": len(devices),
137
+ "status_summary": status_counts,
138
+ "devices": devices
139
+ }
140
+
141
+
142
+ @mcp.tool()
143
+ def get_device_status(device_id: str) -> dict:
144
+ """
145
+ Gibt den aktuellen Status und Telemetrie-Daten eines Geraets zurueck.
146
+
147
+ Args:
148
+ device_id: ID des Geraets (aus register_device oder list_devices)
149
+ """
150
+ store = get_store()
151
+
152
+ if device_id not in store["devices"]:
153
+ return {"error": f"Geraet '{device_id}' nicht gefunden"}
154
+
155
+ device = store["devices"][device_id]
156
+
157
+ # Simulierte Telemetrie-Werte je nach Typ
158
+ device_type = device.get("type", "sensor")
159
+ simulated_telemetry = {}
160
+
161
+ if device_type == "sensor":
162
+ simulated_telemetry = {
163
+ "temperature": round(random.uniform(18.0, 35.0), 1),
164
+ "humidity": round(random.uniform(30.0, 80.0), 1),
165
+ "battery_level": random.randint(20, 100),
166
+ "signal_strength": random.randint(-80, -40),
167
+ }
168
+ elif device_type == "actuator":
169
+ simulated_telemetry = {
170
+ "state": random.choice(["on", "off"]),
171
+ "power_consumption_w": round(random.uniform(0, 500), 1),
172
+ "cycles_today": random.randint(0, 50),
173
+ }
174
+ elif device_type == "gateway":
175
+ simulated_telemetry = {
176
+ "connected_devices": random.randint(1, 50),
177
+ "messages_forwarded": random.randint(100, 10000),
178
+ "cpu_usage_pct": random.randint(5, 80),
179
+ "memory_usage_pct": random.randint(10, 90),
180
+ }
181
+ elif device_type == "camera":
182
+ simulated_telemetry = {
183
+ "fps": random.choice([15, 24, 30]),
184
+ "resolution": "1920x1080",
185
+ "storage_free_gb": round(random.uniform(0, 100), 1),
186
+ "motion_detected": random.choice([True, False]),
187
+ }
188
+
189
+ # Letztes Telemetrie-Update speichern
190
+ device["telemetry"] = simulated_telemetry
191
+ device["last_seen"] = now_iso()
192
+ store["devices"][device_id] = device
193
+ save_store(store)
194
+
195
+ return {
196
+ "device_id": device_id,
197
+ "name": device["name"],
198
+ "status": device["status"],
199
+ "type": device["type"],
200
+ "location": device["location"],
201
+ "firmware_version": device["firmware_version"],
202
+ "ip_address": device.get("ip_address", ""),
203
+ "protocol": device.get("protocol", "mqtt"),
204
+ "uptime": _device_uptime(device["registered_at"]),
205
+ "last_seen": device["last_seen"],
206
+ "telemetry": simulated_telemetry,
207
+ "tags": device.get("tags", []),
208
+ }
209
+
210
+
211
+ @mcp.tool()
212
+ def update_firmware(
213
+ device_id: str,
214
+ new_version: str,
215
+ notes: str = "",
216
+ ) -> dict:
217
+ """
218
+ Simuliert ein Firmware-Update fuer ein IoT-Geraet.
219
+
220
+ Args:
221
+ device_id: ID des Geraets
222
+ new_version: Neue Firmware-Version (z.B. '2.1.0')
223
+ notes: Notizen zum Update (z.B. 'Sicherheitspatch fuer CVE-2025-1234')
224
+ """
225
+ store = get_store()
226
+
227
+ if device_id not in store["devices"]:
228
+ return {"error": f"Geraet '{device_id}' nicht gefunden"}
229
+
230
+ device = store["devices"][device_id]
231
+ old_version = device["firmware_version"]
232
+
233
+ # Update ausfuehren
234
+ device["firmware_version"] = new_version
235
+ device["last_seen"] = now_iso()
236
+ store["devices"][device_id] = device
237
+
238
+ # History eintragen
239
+ history_entry = {
240
+ "device_id": device_id,
241
+ "device_name": device["name"],
242
+ "from_version": old_version,
243
+ "to_version": new_version,
244
+ "notes": notes,
245
+ "timestamp": now_iso(),
246
+ "status": "success",
247
+ }
248
+ store["firmware_history"].append(history_entry)
249
+
250
+ # Alert hinzufuegen
251
+ store["alerts"].append({
252
+ "id": _generate_id("alert"),
253
+ "device_id": device_id,
254
+ "type": "firmware_update",
255
+ "severity": "info",
256
+ "message": f"Firmware von {old_version} auf {new_version} aktualisiert",
257
+ "timestamp": now_iso(),
258
+ "resolved": True,
259
+ })
260
+
261
+ save_store(store)
262
+
263
+ return {
264
+ "success": True,
265
+ "device_id": device_id,
266
+ "device_name": device["name"],
267
+ "old_version": old_version,
268
+ "new_version": new_version,
269
+ "message": f"Firmware erfolgreich aktualisiert: {old_version} → {new_version}",
270
+ "notes": notes,
271
+ }
272
+
273
+
274
+ @mcp.tool()
275
+ def send_command(
276
+ device_id: str,
277
+ command: str,
278
+ parameters: str = "",
279
+ ) -> dict:
280
+ """
281
+ Sendet einen Remote-Befehl an ein IoT-Geraet.
282
+
283
+ Args:
284
+ device_id: ID des Geraets
285
+ command: Befehl (z.B. 'reboot', 'set_interval', 'enable', 'disable', 'calibrate', 'reset')
286
+ parameters: Optionale JSON-Parameter als String (z.B. '{"interval_seconds": 60}')
287
+ """
288
+ store = get_store()
289
+
290
+ if device_id not in store["devices"]:
291
+ return {"error": f"Geraet '{device_id}' nicht gefunden"}
292
+
293
+ device = store["devices"][device_id]
294
+
295
+ # Parameter parsen
296
+ params = {}
297
+ if parameters:
298
+ try:
299
+ params = json.loads(parameters)
300
+ except Exception:
301
+ params = {"raw": parameters}
302
+
303
+ # Befehlsausfuehrung simulieren
304
+ valid_commands = ["reboot", "set_interval", "enable", "disable", "calibrate", "reset", "blink", "ping", "get_config", "set_config"]
305
+ command_lower = command.lower()
306
+
307
+ if command_lower not in valid_commands:
308
+ return {
309
+ "success": False,
310
+ "error": f"Unbekannter Befehl '{command}'",
311
+ "valid_commands": valid_commands
312
+ }
313
+
314
+ # Status aendern bei bestimmten Befehlen
315
+ if command_lower == "reboot":
316
+ device["status"] = "online"
317
+ device["last_seen"] = now_iso()
318
+ elif command_lower == "disable":
319
+ device["status"] = "offline"
320
+ elif command_lower == "enable":
321
+ device["status"] = "online"
322
+
323
+ store["devices"][device_id] = device
324
+
325
+ # Command-Log eintragen
326
+ log_entry = {
327
+ "id": _generate_id("cmd"),
328
+ "device_id": device_id,
329
+ "device_name": device["name"],
330
+ "command": command,
331
+ "parameters": params,
332
+ "timestamp": now_iso(),
333
+ "status": "executed",
334
+ "response_time_ms": random.randint(10, 500),
335
+ }
336
+ store["command_log"].append(log_entry)
337
+
338
+ save_store(store)
339
+
340
+ return {
341
+ "success": True,
342
+ "device_id": device_id,
343
+ "device_name": device["name"],
344
+ "command": command,
345
+ "parameters": params,
346
+ "response": f"Befehl '{command}' erfolgreich ausgefuehrt",
347
+ "response_time_ms": log_entry["response_time_ms"],
348
+ "timestamp": log_entry["timestamp"],
349
+ }
350
+
351
+
352
+ @mcp.tool()
353
+ def get_alerts(
354
+ device_id: str = "",
355
+ severity: str = "",
356
+ resolved: bool = False,
357
+ limit: int = 20,
358
+ ) -> dict:
359
+ """
360
+ Ruft Alerts und Warnungen fuer IoT-Geraete ab.
361
+
362
+ Args:
363
+ device_id: Filtert Alerts fuer ein bestimmtes Geraet (optional)
364
+ severity: Filtert nach Schwere (info, warning, error, critical)
365
+ resolved: Wenn True, zeigt auch geloeste Alerts (Standard: False = nur offene)
366
+ limit: Maximale Anzahl zurueckgegebener Alerts (Standard: 20)
367
+ """
368
+ store = get_store()
369
+ alerts = store.get("alerts", [])
370
+
371
+ # Demo-Alerts hinzufuegen wenn leer
372
+ if not alerts:
373
+ alerts = _generate_demo_alerts(store)
374
+ store["alerts"] = alerts
375
+ save_store(store)
376
+
377
+ # Filterung
378
+ filtered = alerts.copy()
379
+ if device_id:
380
+ filtered = [a for a in filtered if a.get("device_id") == device_id]
381
+ if severity:
382
+ filtered = [a for a in filtered if a.get("severity") == severity]
383
+ if not resolved:
384
+ filtered = [a for a in filtered if not a.get("resolved", False)]
385
+
386
+ # Neueste zuerst
387
+ filtered = list(reversed(filtered))[:limit]
388
+
389
+ severity_counts = {}
390
+ for a in alerts:
391
+ s = a.get("severity", "unknown")
392
+ severity_counts[s] = severity_counts.get(s, 0) + 1
393
+
394
+ return {
395
+ "total_alerts": len(alerts),
396
+ "open_alerts": len([a for a in alerts if not a.get("resolved", False)]),
397
+ "severity_summary": severity_counts,
398
+ "filtered_count": len(filtered),
399
+ "alerts": filtered
400
+ }
401
+
402
+
403
+ @mcp.tool()
404
+ def resolve_alert(alert_id: str, resolution_note: str = "") -> dict:
405
+ """
406
+ Markiert einen Alert als geloest.
407
+
408
+ Args:
409
+ alert_id: ID des Alerts (aus get_alerts)
410
+ resolution_note: Optionale Notiz zur Loesung
411
+ """
412
+ store = get_store()
413
+ alerts = store.get("alerts", [])
414
+
415
+ for alert in alerts:
416
+ if alert.get("id") == alert_id:
417
+ alert["resolved"] = True
418
+ alert["resolved_at"] = now_iso()
419
+ alert["resolution_note"] = resolution_note
420
+ store["alerts"] = alerts
421
+ save_store(store)
422
+ return {
423
+ "success": True,
424
+ "alert_id": alert_id,
425
+ "message": "Alert als geloest markiert",
426
+ "resolution_note": resolution_note
427
+ }
428
+
429
+ return {"error": f"Alert '{alert_id}' nicht gefunden"}
430
+
431
+
432
+ @mcp.tool()
433
+ def device_analytics(
434
+ period_days: int = 7,
435
+ device_id: str = "",
436
+ ) -> dict:
437
+ """
438
+ Gibt Analyse und Statistiken ueber den Device-Fleet zurueck.
439
+
440
+ Args:
441
+ period_days: Analysezeitraum in Tagen (Standard: 7)
442
+ device_id: Optional: Analyse fuer ein spezifisches Geraet
443
+ """
444
+ store = get_store()
445
+ devices = list(store["devices"].values())
446
+ alerts = store.get("alerts", [])
447
+ firmware_history = store.get("firmware_history", [])
448
+ command_log = store.get("command_log", [])
449
+
450
+ if device_id:
451
+ if device_id not in store["devices"]:
452
+ return {"error": f"Geraet '{device_id}' nicht gefunden"}
453
+ devices = [store["devices"][device_id]]
454
+
455
+ # Fleet-Statistiken
456
+ total = len(devices)
457
+ by_status = {}
458
+ by_type = {}
459
+ by_location = {}
460
+
461
+ for d in devices:
462
+ s = d.get("status", "unknown")
463
+ t = d.get("type", "unknown")
464
+ loc = d.get("location", "unknown")
465
+
466
+ by_status[s] = by_status.get(s, 0) + 1
467
+ by_type[t] = by_type.get(t, 0) + 1
468
+ by_location[loc] = by_location.get(loc, 0) + 1
469
+
470
+ # Alert-Statistiken
471
+ critical_alerts = len([a for a in alerts if a.get("severity") == "critical" and not a.get("resolved")])
472
+ warning_alerts = len([a for a in alerts if a.get("severity") == "warning" and not a.get("resolved")])
473
+
474
+ # Firmware-Statistiken
475
+ unique_versions = set(d.get("firmware_version", "unknown") for d in devices)
476
+
477
+ # Fleet-Gesundheitsscore (0-100)
478
+ online_pct = (by_status.get("online", 0) / total * 100) if total > 0 else 0
479
+ alert_penalty = min(50, critical_alerts * 10 + warning_alerts * 3)
480
+ health_score = max(0, round(online_pct - alert_penalty))
481
+
482
+ # Empfehlungen
483
+ recommendations = []
484
+ if by_status.get("offline", 0) > 0:
485
+ recommendations.append(f"{by_status['offline']} Geraete offline — Verbindung pruefen")
486
+ if critical_alerts > 0:
487
+ recommendations.append(f"{critical_alerts} kritische Alerts erfordern sofortige Aufmerksamkeit")
488
+ if len(unique_versions) > 3:
489
+ recommendations.append(f"{len(unique_versions)} verschiedene Firmware-Versionen — Update-Strategie empfohlen")
490
+ if total == 0:
491
+ recommendations.append("Noch keine Geraete registriert — starte mit register_device")
492
+
493
+ return {
494
+ "analysis_period_days": period_days,
495
+ "fleet_overview": {
496
+ "total_devices": total,
497
+ "by_status": by_status,
498
+ "by_type": by_type,
499
+ "top_locations": dict(list(sorted(by_location.items(), key=lambda x: x[1], reverse=True))[:5]),
500
+ },
501
+ "health_score": health_score,
502
+ "health_rating": "Excellent" if health_score >= 90 else "Good" if health_score >= 70 else "Fair" if health_score >= 50 else "Poor",
503
+ "alerts": {
504
+ "total": len(alerts),
505
+ "open_critical": critical_alerts,
506
+ "open_warnings": warning_alerts,
507
+ },
508
+ "firmware": {
509
+ "unique_versions": list(unique_versions),
510
+ "update_history_total": len(firmware_history),
511
+ },
512
+ "commands_executed": len(command_log),
513
+ "recommendations": recommendations,
514
+ }
515
+
516
+
517
+ @mcp.tool()
518
+ def get_fleet_dashboard() -> dict:
519
+ """
520
+ Gibt ein vollstaendiges Fleet-Dashboard mit Gesamtueberblick zurueck.
521
+ Kein Parameter noetig — gibt eine strukturierte Uebersicht aller Geraete,
522
+ Alerts und Aktivitaeten zurueck.
523
+ """
524
+ store = get_store()
525
+ devices = store.get("devices", {})
526
+ alerts = store.get("alerts", [])
527
+ firmware_history = store.get("firmware_history", [])
528
+ command_log = store.get("command_log", [])
529
+
530
+ # Online/Offline
531
+ online = [d for d in devices.values() if d.get("status") == "online"]
532
+ offline = [d for d in devices.values() if d.get("status") == "offline"]
533
+ warning_devices = [d for d in devices.values() if d.get("status") == "warning"]
534
+
535
+ # Offene kritische Alerts
536
+ open_critical = [a for a in alerts if a.get("severity") == "critical" and not a.get("resolved")]
537
+
538
+ # Letzte 5 Aktivitaeten
539
+ recent_commands = list(reversed(command_log))[:5]
540
+ recent_firmware = list(reversed(firmware_history))[:5]
541
+
542
+ return {
543
+ "dashboard": {
544
+ "fleet_size": len(devices),
545
+ "online": len(online),
546
+ "offline": len(offline),
547
+ "warnings": len(warning_devices),
548
+ "open_critical_alerts": len(open_critical),
549
+ },
550
+ "top_devices": [
551
+ {"id": d["id"], "name": d["name"], "status": d["status"], "type": d["type"], "location": d["location"]}
552
+ for d in list(devices.values())[:10]
553
+ ],
554
+ "recent_commands": recent_commands,
555
+ "recent_firmware_updates": recent_firmware,
556
+ "critical_alerts": open_critical[:5],
557
+ "quick_actions": [
558
+ "register_device — Neues Geraet registrieren",
559
+ "list_devices — Alle Geraete anzeigen",
560
+ "get_device_status <id> — Geraete-Status abrufen",
561
+ "send_command <id> reboot — Geraet neu starten",
562
+ "get_alerts — Alle offenen Alerts anzeigen",
563
+ "device_analytics — Fleet-Analyse starten",
564
+ ],
565
+ }
566
+
567
+
568
+ def _generate_demo_alerts(store: dict) -> list:
569
+ """Generiert Demo-Alerts wenn keine Geraete vorhanden."""
570
+ devices = list(store.get("devices", {}).values())
571
+ if not devices:
572
+ return []
573
+
574
+ alerts = []
575
+ severities = ["info", "warning", "error", "critical"]
576
+
577
+ for i, device in enumerate(devices[:3]):
578
+ severity = severities[i % len(severities)]
579
+ messages = {
580
+ "info": f"Geraet '{device['name']}' meldet sich regelmaessig",
581
+ "warning": f"Battery low auf '{device['name']}' (< 20%)",
582
+ "error": f"Verbindungsabbruch bei '{device['name']}' — 3 Wiederversuche",
583
+ "critical": f"Kein Heartbeat von '{device['name']}' seit > 1 Stunde",
584
+ }
585
+ alerts.append({
586
+ "id": _generate_id("alert"),
587
+ "device_id": device["id"],
588
+ "type": "health_check",
589
+ "severity": severity,
590
+ "message": messages[severity],
591
+ "timestamp": now_iso(),
592
+ "resolved": severity == "info",
593
+ })
594
+
595
+ return alerts
596
+
597
+
598
+ def main():
599
+ """Einstiegspunkt fuer den MCP-Server."""
600
+ mcp.run()
601
+
602
+
603
+ if __name__ == "__main__":
604
+ main()
@@ -0,0 +1,44 @@
1
+ """Persistenter lokaler Device-Store (JSON-Datei)."""
2
+
3
+ import json
4
+ import os
5
+ from datetime import datetime
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ # Pfad zur persistenten Datei
10
+ STORE_PATH = Path.home() / ".iot_device_store.json"
11
+
12
+
13
+ def _load() -> dict:
14
+ """Laedt den Store aus der Datei."""
15
+ if not STORE_PATH.exists():
16
+ return {
17
+ "devices": {},
18
+ "alerts": [],
19
+ "firmware_history": [],
20
+ "command_log": [],
21
+ }
22
+ with open(STORE_PATH, "r", encoding="utf-8") as f:
23
+ return json.load(f)
24
+
25
+
26
+ def _save(data: dict) -> None:
27
+ """Speichert den Store in die Datei."""
28
+ with open(STORE_PATH, "w", encoding="utf-8") as f:
29
+ json.dump(data, f, indent=2, ensure_ascii=False)
30
+
31
+
32
+ def get_store() -> dict:
33
+ """Gibt den aktuellen Store zurueck."""
34
+ return _load()
35
+
36
+
37
+ def save_store(data: dict) -> None:
38
+ """Speichert den Store."""
39
+ _save(data)
40
+
41
+
42
+ def now_iso() -> str:
43
+ """Gibt aktuelle Zeit als ISO-String zurueck."""
44
+ return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")