meshtastic-mcp 0.1.0__py3-none-any.whl

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.
Files changed (114) hide show
  1. meshtastic_mcp/__init__.py +22 -0
  2. meshtastic_mcp/__main__.py +642 -0
  3. meshtastic_mcp/_version.py +24 -0
  4. meshtastic_mcp/admin.py +413 -0
  5. meshtastic_mcp/boards.py +158 -0
  6. meshtastic_mcp/camera.py +336 -0
  7. meshtastic_mcp/capabilities.py +147 -0
  8. meshtastic_mcp/cli/__init__.py +9 -0
  9. meshtastic_mcp/cli/_flashlog.py +76 -0
  10. meshtastic_mcp/cli/_fwlog.py +100 -0
  11. meshtastic_mcp/cli/_history.py +130 -0
  12. meshtastic_mcp/cli/_reproducer.py +216 -0
  13. meshtastic_mcp/cli/_uicap.py +86 -0
  14. meshtastic_mcp/cli/test_tui.py +1862 -0
  15. meshtastic_mcp/config.py +279 -0
  16. meshtastic_mcp/config_snapshot.py +144 -0
  17. meshtastic_mcp/connection.py +247 -0
  18. meshtastic_mcp/devices.py +163 -0
  19. meshtastic_mcp/doctor.py +655 -0
  20. meshtastic_mcp/emulator/__init__.py +2 -0
  21. meshtastic_mcp/emulator/apple_sim.py +318 -0
  22. meshtastic_mcp/emulator/avd.py +898 -0
  23. meshtastic_mcp/emulator/native_node.py +145 -0
  24. meshtastic_mcp/fixtures.py +415 -0
  25. meshtastic_mcp/flash.py +772 -0
  26. meshtastic_mcp/hw_tools.py +245 -0
  27. meshtastic_mcp/info.py +106 -0
  28. meshtastic_mcp/input_events.py +66 -0
  29. meshtastic_mcp/llama_server.py +163 -0
  30. meshtastic_mcp/local_model.py +228 -0
  31. meshtastic_mcp/log_query.py +414 -0
  32. meshtastic_mcp/lora_compliance.py +337 -0
  33. meshtastic_mcp/ocr.py +148 -0
  34. meshtastic_mcp/pio.py +317 -0
  35. meshtastic_mcp/port_recovery.py +300 -0
  36. meshtastic_mcp/py.typed +0 -0
  37. meshtastic_mcp/recorder/__init__.py +22 -0
  38. meshtastic_mcp/recorder/parsers.py +310 -0
  39. meshtastic_mcp/recorder/recorder.py +493 -0
  40. meshtastic_mcp/recorder/rotating.py +166 -0
  41. meshtastic_mcp/recovery.py +180 -0
  42. meshtastic_mcp/registry.py +115 -0
  43. meshtastic_mcp/replay/__init__.py +53 -0
  44. meshtastic_mcp/replay/build.py +276 -0
  45. meshtastic_mcp/replay/capture.py +443 -0
  46. meshtastic_mcp/replay/engine.py +786 -0
  47. meshtastic_mcp/replay/fuzz.py +489 -0
  48. meshtastic_mcp/replay/sim.py +822 -0
  49. meshtastic_mcp/rf_oracle.py +425 -0
  50. meshtastic_mcp/sdk_cli.py +224 -0
  51. meshtastic_mcp/sdr.py +371 -0
  52. meshtastic_mcp/serial_session.py +303 -0
  53. meshtastic_mcp/server.py +2543 -0
  54. meshtastic_mcp/skills/meshtastic-device-ops/SKILL.md +123 -0
  55. meshtastic_mcp/skills/meshtastic-e2e/SKILL.md +184 -0
  56. meshtastic_mcp/skills/meshtastic-e2e/references/emulator-lab.md +155 -0
  57. meshtastic_mcp/skills/meshtastic-e2e/references/harness.md +83 -0
  58. meshtastic_mcp/skills/meshtastic-e2e/references/journeys/inbound.journey.xml +25 -0
  59. meshtastic_mcp/skills/meshtastic-e2e/references/journeys/node-sync.journey.xml +19 -0
  60. meshtastic_mcp/skills/meshtastic-e2e/references/journeys/outbound.journey.xml +21 -0
  61. meshtastic_mcp/skills/meshtastic-e2e/references/journeys.md +52 -0
  62. meshtastic_mcp/skills/meshtastic-e2e/references/loop-config-writeback.md +49 -0
  63. meshtastic_mcp/skills/meshtastic-e2e/references/loop-inbound.md +54 -0
  64. meshtastic_mcp/skills/meshtastic-e2e/references/loop-node-sync.md +55 -0
  65. meshtastic_mcp/skills/meshtastic-e2e/references/loop-outbound.md +52 -0
  66. meshtastic_mcp/skills/meshtastic-e2e/references/loop-resilience.md +63 -0
  67. meshtastic_mcp/skills/meshtastic-e2e/references/mesh_e2e.py +216 -0
  68. meshtastic_mcp/skills/meshtastic-e2e/references/replay-app-features.md +65 -0
  69. meshtastic_mcp/skills/meshtastic-e2e/references/simulator-apple.md +157 -0
  70. meshtastic_mcp/skills/meshtastic-e2e/references/topology.md +71 -0
  71. meshtastic_mcp/skills/meshtastic-e2e/references/triage.md +42 -0
  72. meshtastic_mcp/skills/meshtastic-e2e/references/vision-oracle.md +38 -0
  73. meshtastic_mcp/skills/meshtastic-org-knowledge/SKILL.md +122 -0
  74. meshtastic_mcp/uhubctl.py +321 -0
  75. meshtastic_mcp/userprefs.py +535 -0
  76. meshtastic_mcp/web/__init__.py +14 -0
  77. meshtastic_mcp/web/__main__.py +99 -0
  78. meshtastic_mcp/web/app.py +985 -0
  79. meshtastic_mcp/web/camera_worker.py +133 -0
  80. meshtastic_mcp/web/db/__init__.py +6 -0
  81. meshtastic_mcp/web/db/database.py +188 -0
  82. meshtastic_mcp/web/db/repo_builds.py +62 -0
  83. meshtastic_mcp/web/db/repo_cameras.py +81 -0
  84. meshtastic_mcp/web/db/repo_devices.py +235 -0
  85. meshtastic_mcp/web/db/repo_flash.py +61 -0
  86. meshtastic_mcp/web/db/repo_runs.py +96 -0
  87. meshtastic_mcp/web/db/repo_settings.py +29 -0
  88. meshtastic_mcp/web/services/__init__.py +7 -0
  89. meshtastic_mcp/web/services/activity.py +113 -0
  90. meshtastic_mcp/web/services/builder.py +244 -0
  91. meshtastic_mcp/web/services/camera_stream.py +223 -0
  92. meshtastic_mcp/web/services/control.py +36 -0
  93. meshtastic_mcp/web/services/datadog.py +565 -0
  94. meshtastic_mcp/web/services/discovery.py +298 -0
  95. meshtastic_mcp/web/services/firmware.py +54 -0
  96. meshtastic_mcp/web/services/identity.py +144 -0
  97. meshtastic_mcp/web/services/keepalive.py +136 -0
  98. meshtastic_mcp/web/services/native.py +88 -0
  99. meshtastic_mcp/web/services/portlock.py +49 -0
  100. meshtastic_mcp/web/services/power.py +132 -0
  101. meshtastic_mcp/web/services/recovery.py +140 -0
  102. meshtastic_mcp/web/services/scrub.py +46 -0
  103. meshtastic_mcp/web/services/serial_monitor.py +243 -0
  104. meshtastic_mcp/web/services/test_runner.py +630 -0
  105. meshtastic_mcp/web/static/assets/index-BcjZL-YS.js +21 -0
  106. meshtastic_mcp/web/static/assets/index-Bxcb0DBw.css +1 -0
  107. meshtastic_mcp/web/static/index.html +13 -0
  108. meshtastic_mcp/web/ws/__init__.py +5 -0
  109. meshtastic_mcp/web/ws/hub.py +76 -0
  110. meshtastic_mcp-0.1.0.dist-info/METADATA +329 -0
  111. meshtastic_mcp-0.1.0.dist-info/RECORD +114 -0
  112. meshtastic_mcp-0.1.0.dist-info/WHEEL +4 -0
  113. meshtastic_mcp-0.1.0.dist-info/entry_points.txt +4 -0
  114. meshtastic_mcp-0.1.0.dist-info/licenses/LICENSE +675 -0
@@ -0,0 +1,22 @@
1
+ # SPDX-FileCopyrightText: Meshtastic contributors
2
+ # SPDX-License-Identifier: GPL-3.0-only
3
+
4
+ """Meshtastic MCP server — device discovery, admin, recorder, and hardware-free e2e."""
5
+
6
+ from __future__ import annotations
7
+
8
+ try:
9
+ # Written by hatch-vcs at build time (single source of truth: git tags).
10
+ from ._version import __version__
11
+ except ImportError: # pragma: no cover - editable installs without a build
12
+ try:
13
+ from importlib.metadata import PackageNotFoundError, version
14
+
15
+ try:
16
+ __version__ = version("meshtastic-mcp")
17
+ except PackageNotFoundError:
18
+ __version__ = "0+unknown"
19
+ except ImportError:
20
+ __version__ = "0+unknown"
21
+
22
+ __all__ = ["__version__"]
@@ -0,0 +1,642 @@
1
+ # SPDX-FileCopyrightText: Meshtastic contributors
2
+ # SPDX-License-Identifier: GPL-3.0-only
3
+
4
+ """Entry point for `python -m meshtastic_mcp` and the `meshtastic-mcp` console script.
5
+
6
+ Default (no args): run the MCP server over stdio.
7
+ Subcommands:
8
+ install [--client C] [--local] [--print] register this server in an MCP client's config
9
+ (default client: claude-code, user scope) + install skills
10
+ uninstall [--client C] [--purge-skills] remove the server registration (and optionally skills)
11
+ doctor [--json] probe external deps and print how to acquire any missing ones
12
+ skills install/uninstall [--dest DIR] copy/remove the bundled agent skills
13
+ (default: ~/.agents/skills)
14
+ provision [--dir DIR] clone missing source repos (firmware/android/apple) and
15
+ print the export commands to activate them
16
+
17
+ -- Read-only device/hardware queries (no MCP server needed) --
18
+ devices [--all] [--json] list connected Meshtastic devices
19
+ boards [--arch ARCH] [--query Q] list PlatformIO board environments
20
+ boards get ENV show full metadata for one board env
21
+ info PORT [--json] firmware version / region / node info
22
+ nodes PORT [--json] mesh peers visible to this node
23
+
24
+ Examples:
25
+ meshtastic-mcp devices
26
+ meshtastic-mcp boards --arch esp32s3 --query heltec
27
+ meshtastic-mcp boards get heltec-v3
28
+ meshtastic-mcp info /dev/ttyUSB0
29
+ meshtastic-mcp nodes /dev/ttyUSB0
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json as _json_mod
36
+ import os
37
+ import re
38
+ import shutil
39
+ import subprocess
40
+ import sys
41
+ from pathlib import Path
42
+
43
+ _SKILLS_SRC = Path(__file__).resolve().parent / "skills"
44
+ _DEFAULT_SKILLS_DEST = Path.home() / ".agents" / "skills"
45
+
46
+ # Candidate .env files loaded (in order) when a MESHTASTIC_* var is not set.
47
+ # Each file may contain `export KEY=value` or `KEY=value` lines.
48
+ _ENV_CANDIDATES = [
49
+ Path.home() / ".config" / "meshtastic-mcp" / ".env",
50
+ Path.home() / ".local" / "share" / "meshtastic-mcp" / "repos" / ".env",
51
+ ]
52
+
53
+
54
+ def _load_env_files() -> None:
55
+ """Load MESHTASTIC_* env vars from candidate .env files (first-found wins per key).
56
+
57
+ Only sets vars that are not already present in the environment, so explicit
58
+ env vars (from the shell, MCP client config, etc.) always take precedence.
59
+ Any line not matching `[export] KEY=value` is silently ignored.
60
+ """
61
+ _kv = re.compile(r"^\s*(?:export\s+)?(MESHTASTIC_\w+)=(.+)")
62
+ for path in _ENV_CANDIDATES:
63
+ if not path.is_file():
64
+ continue
65
+ try:
66
+ for raw in path.read_text().splitlines():
67
+ m = _kv.match(raw)
68
+ if m and m.group(1) not in os.environ:
69
+ os.environ[m.group(1)] = m.group(2).strip().strip("\"'")
70
+ except OSError:
71
+ pass
72
+
73
+
74
+ def _bundled_skill_names() -> list[str]:
75
+ if not _SKILLS_SRC.is_dir():
76
+ return []
77
+ return sorted(p.name for p in _SKILLS_SRC.iterdir() if p.is_dir())
78
+
79
+
80
+ def _skills_install(dest: Path) -> int:
81
+ if not _SKILLS_SRC.is_dir():
82
+ print(f"no bundled skills found at {_SKILLS_SRC}", file=sys.stderr)
83
+ return 1
84
+ dest.mkdir(parents=True, exist_ok=True)
85
+ installed = []
86
+ for pack in _SKILLS_SRC.iterdir():
87
+ if not pack.is_dir():
88
+ continue
89
+ target = dest / pack.name
90
+ shutil.rmtree(target, ignore_errors=True)
91
+ shutil.copytree(pack, target)
92
+ installed.append(pack.name)
93
+ print(f"installed {len(installed)} skill(s) into {dest}: {', '.join(installed)}")
94
+ return 0
95
+
96
+
97
+ def _skills_uninstall(dest: Path) -> int:
98
+ removed = []
99
+ for name in _bundled_skill_names():
100
+ target = dest / name
101
+ if target.is_dir():
102
+ shutil.rmtree(target, ignore_errors=True)
103
+ removed.append(name)
104
+ if removed:
105
+ print(f"removed {len(removed)} skill(s) from {dest}: {', '.join(removed)}")
106
+ else:
107
+ print(f"no bundled skills found in {dest}")
108
+ return 0
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # MCP client registration (install / uninstall the server)
113
+ # ---------------------------------------------------------------------------
114
+
115
+
116
+ # Where common MCP clients keep their `mcpServers` JSON config.
117
+ def _client_config_path(client: str, scope: str) -> Path:
118
+ home = Path.home()
119
+ if client == "claude-code":
120
+ return (home / ".claude.json") if scope == "user" else (Path.cwd() / ".mcp.json")
121
+ if client == "claude-desktop":
122
+ if sys.platform == "darwin":
123
+ return (
124
+ home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
125
+ )
126
+ if os.name == "nt":
127
+ return Path(os.environ.get("APPDATA", home)) / "Claude" / "claude_desktop_config.json"
128
+ return home / ".config" / "Claude" / "claude_desktop_config.json"
129
+ if client == "cursor":
130
+ return (
131
+ (home / ".cursor" / "mcp.json")
132
+ if scope == "user"
133
+ else (Path.cwd() / ".cursor" / "mcp.json")
134
+ )
135
+ if client == "windsurf":
136
+ return home / ".codeium" / "windsurf" / "mcp_config.json"
137
+ raise ValueError(f"unknown client {client!r}")
138
+
139
+
140
+ def _server_entry(local: bool, env: dict[str, str]) -> dict:
141
+ """The mcpServers entry for this server. `local` registers the current
142
+ interpreter (`python -m meshtastic_mcp`, for editable/dev installs); the
143
+ default is the zero-install `uvx meshtastic-mcp`."""
144
+ if local:
145
+ entry: dict = {"command": sys.executable, "args": ["-m", "meshtastic_mcp"]}
146
+ else:
147
+ entry = {"command": "uvx", "args": ["meshtastic-mcp"]}
148
+ if env:
149
+ entry["env"] = env
150
+ return entry
151
+
152
+
153
+ def _load_json_config(path: Path) -> dict:
154
+ if not path.exists():
155
+ return {}
156
+ try:
157
+ data = _json_mod.loads(path.read_text() or "{}")
158
+ except _json_mod.JSONDecodeError as exc:
159
+ raise SystemExit(
160
+ f"{path} is not valid JSON ({exc}); refusing to edit. "
161
+ f"Fix it, or use --print to copy the snippet manually."
162
+ ) from exc
163
+ return data if isinstance(data, dict) else {}
164
+
165
+
166
+ def _install(args) -> int:
167
+ name = args.name
168
+ entry = _server_entry(args.local, dict(args.env or []))
169
+ if args.print:
170
+ print(_json_mod.dumps({"mcpServers": {name: entry}}, indent=2))
171
+ return 0
172
+ path = Path(args.config) if args.config else _client_config_path(args.client, args.scope)
173
+ config = _load_json_config(path)
174
+ servers = config.setdefault("mcpServers", {})
175
+ if not isinstance(servers, dict):
176
+ raise SystemExit(f"{path}: 'mcpServers' is not an object; refusing to edit.")
177
+ action = "updated" if name in servers else "registered"
178
+ servers[name] = entry
179
+ if args.dry_run:
180
+ print(f"[dry-run] would write to {path}:")
181
+ print(_json_mod.dumps({"mcpServers": {name: entry}}, indent=2))
182
+ return 0
183
+ path.parent.mkdir(parents=True, exist_ok=True)
184
+ path.write_text(_json_mod.dumps(config, indent=2) + "\n")
185
+ print(f"{action} MCP server '{name}' in {path}")
186
+ print(f" command: {entry['command']} {' '.join(entry['args'])}")
187
+ if not args.no_skills:
188
+ _skills_install(args.skills_dest)
189
+ print("\nRestart your MCP client to pick up the change.")
190
+ return 0
191
+
192
+
193
+ def _uninstall(args) -> int:
194
+ name = args.name
195
+ path = Path(args.config) if args.config else _client_config_path(args.client, args.scope)
196
+ config = _load_json_config(path)
197
+ servers = config.get("mcpServers")
198
+ if isinstance(servers, dict) and name in servers:
199
+ del servers[name]
200
+ path.write_text(_json_mod.dumps(config, indent=2) + "\n")
201
+ print(f"unregistered MCP server '{name}' from {path}")
202
+ else:
203
+ print(f"MCP server '{name}' not found in {path}")
204
+ if args.purge_skills:
205
+ _skills_uninstall(args.skills_dest)
206
+ return 0
207
+
208
+
209
+ def _default_provision_dir() -> Path:
210
+ try:
211
+ from platformdirs import user_data_dir
212
+
213
+ return Path(user_data_dir("meshtastic-mcp")) / "repos"
214
+ except Exception:
215
+ return Path.home() / ".local" / "share" / "meshtastic-mcp" / "repos"
216
+
217
+
218
+ _REPOS = [
219
+ # (env_var, dir_name, clone_url, sentinel)
220
+ (
221
+ "MESHTASTIC_FIRMWARE_ROOT",
222
+ "firmware",
223
+ "https://github.com/meshtastic/firmware",
224
+ "platformio.ini",
225
+ ),
226
+ (
227
+ "MESHTASTIC_ANDROID_ROOT",
228
+ "Meshtastic-Android",
229
+ "https://github.com/meshtastic/Meshtastic-Android",
230
+ "gradlew",
231
+ ),
232
+ (
233
+ "MESHTASTIC_APPLE_ROOT",
234
+ "Meshtastic-Apple",
235
+ "https://github.com/meshtastic/Meshtastic-Apple",
236
+ "Meshtastic.xcworkspace",
237
+ ),
238
+ ]
239
+
240
+
241
+ def _provision(base_dir: Path) -> int:
242
+ base_dir.mkdir(parents=True, exist_ok=True)
243
+ exports: list[str] = []
244
+ ok = True
245
+
246
+ for env_var, dir_name, clone_url, sentinel in _REPOS:
247
+ existing = os.environ.get(env_var)
248
+ if existing:
249
+ print(f" {env_var} already set → {existing}")
250
+ exports.append(f"export {env_var}={existing}")
251
+ continue
252
+
253
+ dest = base_dir / dir_name
254
+ if dest.is_dir() and (dest / sentinel).exists():
255
+ print(f" {dir_name}: already cloned at {dest}")
256
+ else:
257
+ print(f" cloning {clone_url} → {dest}")
258
+ try:
259
+ subprocess.run(
260
+ ["git", "clone", "--recurse-submodules", clone_url, str(dest)],
261
+ check=True,
262
+ )
263
+ except subprocess.CalledProcessError:
264
+ print(f" ERROR: failed to clone {clone_url}", file=sys.stderr)
265
+ ok = False
266
+ continue
267
+
268
+ exports.append(f"export {env_var}={dest}")
269
+
270
+ # Write to both the repos dir and the canonical config location so
271
+ # `meshtastic-mcp` CLI picks them up automatically in future runs.
272
+ env_content = "\n".join(exports) + "\n"
273
+ env_file = base_dir / ".env"
274
+ env_file.write_text(env_content)
275
+
276
+ config_env = Path.home() / ".config" / "meshtastic-mcp" / ".env"
277
+ config_env.parent.mkdir(parents=True, exist_ok=True)
278
+ config_env.write_text(env_content)
279
+
280
+ print()
281
+ print("Add to your shell profile (or source this block):")
282
+ print()
283
+ for line in exports:
284
+ print(f" {line}")
285
+ print()
286
+ print(f"Auto-loaded by meshtastic-mcp CLI: {config_env}")
287
+ print(f"Sourceable shell file: {env_file}")
288
+ print(f" source {env_file}")
289
+
290
+ return 0 if ok else 1
291
+
292
+
293
+ # ---------------------------------------------------------------------------
294
+ # Read-only CLI command implementations
295
+ # ---------------------------------------------------------------------------
296
+
297
+
298
+ def _print_result(data: object, as_json: bool) -> None:
299
+ """Pretty-print a dict/list as JSON or a human table."""
300
+ if as_json:
301
+ print(_json_mod.dumps(data, indent=2, default=str))
302
+ return
303
+ if isinstance(data, list):
304
+ for item in data:
305
+ _print_result(item, as_json=False)
306
+ print()
307
+ elif isinstance(data, dict):
308
+ for k, v in data.items():
309
+ print(f" {k:<24} {v}")
310
+ else:
311
+ print(data)
312
+
313
+
314
+ def _cmd_devices(args) -> int:
315
+ from meshtastic_mcp import devices as _devices
316
+
317
+ result = _devices.list_devices(include_unknown=args.all)
318
+ if not result:
319
+ print("no devices found" + (" (try --all to see all serial ports)" if not args.all else ""))
320
+ return 0
321
+ if args.json:
322
+ print(_json_mod.dumps(result, indent=2, default=str))
323
+ return 0
324
+ for d in result:
325
+ flag = " [meshtastic]" if d.get("likely_meshtastic") else ""
326
+ desc = d.get("description") or ""
327
+ vid = d.get("vid") or ""
328
+ print(f" {d['port']}{flag} {desc} {vid}")
329
+ return 0
330
+
331
+
332
+ def _cmd_boards(args) -> int:
333
+ # boards get ENV
334
+ if getattr(args, "boards_cmd", None) == "get":
335
+ from meshtastic_mcp import boards as _boards
336
+
337
+ try:
338
+ result = _boards.get_board(args.env)
339
+ except Exception as e:
340
+ print(f"error: {e}", file=sys.stderr)
341
+ return 1
342
+ _print_result(result, getattr(args, "json", False))
343
+ return 0
344
+
345
+ # boards list
346
+ from meshtastic_mcp import boards as _boards
347
+
348
+ board_list = _boards.list_boards(
349
+ architecture=args.arch,
350
+ query=args.query,
351
+ actively_supported_only=args.supported,
352
+ )
353
+ if not board_list:
354
+ print("no boards matched")
355
+ return 0
356
+ if args.json:
357
+ print(_json_mod.dumps(board_list, indent=2, default=str))
358
+ return 0
359
+ print(f" {'env':<30} {'arch':<12} {'display_name'}")
360
+ print(" " + "-" * 70)
361
+ for b in board_list:
362
+ arch = b.get("architecture") or ""
363
+ print(f" {b['env']:<30} {arch!s:<12} {b.get('display_name', '')}")
364
+ return 0
365
+
366
+
367
+ def _cmd_info(args) -> int:
368
+ from meshtastic_mcp import info as _info
369
+
370
+ try:
371
+ result = _info.device_info(args.port)
372
+ except Exception as e:
373
+ print(f"error: {e}", file=sys.stderr)
374
+ return 1
375
+ if args.json:
376
+ print(_json_mod.dumps(result, indent=2, default=str))
377
+ return 0
378
+ # human-readable summary
379
+ print(f" port {result.get('port')}")
380
+ print(f" hw_model {result.get('hw_model')}")
381
+ print(f" firmware {result.get('firmware_version')}")
382
+ print(f" region {result.get('region')}")
383
+ print(f" node_num {result.get('my_node_num')}")
384
+ print(f" long_name {result.get('long_name')}")
385
+ print(f" short_name {result.get('short_name')}")
386
+ print(f" primary_channel {result.get('primary_channel')}")
387
+ print(f" num_nodes {result.get('num_nodes')}")
388
+ return 0
389
+
390
+
391
+ def _cmd_nodes(args) -> int:
392
+ from meshtastic_mcp import info as _info
393
+
394
+ try:
395
+ result = _info.list_nodes(args.port)
396
+ except Exception as e:
397
+ print(f"error: {e}", file=sys.stderr)
398
+ return 1
399
+ if args.json:
400
+ print(_json_mod.dumps(result, indent=2, default=str))
401
+ return 0
402
+ print(
403
+ f" {'node_num':<12} {'short':<6} {'long_name':<30} {'hw_model':<25} {'snr':<6} last_heard"
404
+ )
405
+ print(" " + "-" * 95)
406
+ for n in result:
407
+ user = n.get("user") or {}
408
+ ts = n.get("last_heard")
409
+ heard = str(ts) if ts else "—"
410
+ snr = n.get("snr") or "—"
411
+ print(
412
+ f" {n.get('node_num', '')!s:<12} "
413
+ f"{user.get('short_name', ''):<6} "
414
+ f"{user.get('long_name', ''):<30} "
415
+ f"{user.get('hw_model', ''):<25} "
416
+ f"{snr!s:<6} "
417
+ f"{heard}"
418
+ )
419
+ return 0
420
+
421
+
422
+ def _cmd_watch(args) -> int:
423
+ """Live-tail a recorder JSONL stream. Ctrl-C to stop."""
424
+ import time
425
+
426
+ from meshtastic_mcp import log_query
427
+
428
+ key = {"logs": "lines", "packets": "packets", "events": "events"}[args.stream]
429
+
430
+ def query(start, end="now"):
431
+ if args.stream == "logs":
432
+ return log_query.logs_window(start=start, end=end)
433
+ if args.stream == "packets":
434
+ return log_query.packets_window(start=start, end=end)
435
+ return log_query.events_window(start=start, end=end)
436
+
437
+ print(f"Watching {args.stream} (Ctrl-C to stop)…", file=sys.stderr)
438
+ seen: set[str] = set()
439
+ try:
440
+ # Prime with recent history so we don't replay the whole buffer.
441
+ last = time.time()
442
+ while True:
443
+ window = query(start=last - args.interval - 1, end="now")
444
+ for rec in window.get(key, []):
445
+ # Dedupe by a stable signature (ts + a short content slice).
446
+ sig = f"{rec.get('ts')}-{str(rec.get('line') or rec.get('id') or rec)[:60]}"
447
+ if sig in seen:
448
+ continue
449
+ seen.add(sig)
450
+ line = (
451
+ rec.get("line") if args.stream == "logs" else _json_mod.dumps(rec, default=str)
452
+ )
453
+ print(line)
454
+ # Bound the dedupe set so it doesn't grow without limit.
455
+ if len(seen) > 5000:
456
+ seen = set(list(seen)[-2000:])
457
+ last = time.time()
458
+ time.sleep(args.interval)
459
+ except KeyboardInterrupt:
460
+ print("\nstopped.", file=sys.stderr)
461
+ return 0
462
+
463
+
464
+ def _cmd_completion(args) -> int:
465
+ """Print a shell completion script for bash or zsh."""
466
+ cmds = "install uninstall doctor skills provision devices boards info nodes watch completion"
467
+ if args.shell == "bash":
468
+ print(f"""# meshtastic-mcp bash completion
469
+ # Add to ~/.bashrc: eval "$(meshtastic-mcp completion bash)"
470
+ _meshtastic_mcp() {{
471
+ local cur="${{COMP_WORDS[COMP_CWORD]}}"
472
+ if [ "$COMP_CWORD" -eq 1 ]; then
473
+ COMPREPLY=( $(compgen -W "{cmds}" -- "$cur") )
474
+ fi
475
+ }}
476
+ complete -F _meshtastic_mcp meshtastic-mcp""")
477
+ else: # zsh
478
+ print(f"""# meshtastic-mcp zsh completion
479
+ # Add to ~/.zshrc: eval "$(meshtastic-mcp completion zsh)"
480
+ _meshtastic_mcp() {{
481
+ local -a cmds
482
+ cmds=({cmds})
483
+ _describe 'command' cmds
484
+ }}
485
+ compdef _meshtastic_mcp meshtastic-mcp""")
486
+ return 0
487
+
488
+
489
+ def main(argv=None) -> None:
490
+ _load_env_files()
491
+ p = argparse.ArgumentParser(
492
+ prog="meshtastic-mcp",
493
+ formatter_class=argparse.RawDescriptionHelpFormatter,
494
+ )
495
+ sub = p.add_subparsers(dest="cmd")
496
+
497
+ doc = sub.add_parser("doctor", help="probe external deps + how to acquire missing ones")
498
+ doc.add_argument("--json", action="store_true", help="emit machine-readable JSON")
499
+
500
+ sk = sub.add_parser("skills", help="manage bundled agent skills")
501
+ sksub = sk.add_subparsers(dest="skills_cmd", required=True)
502
+ inst = sksub.add_parser("install", help="copy bundled skills into the skills dir")
503
+ inst.add_argument("--dest", type=Path, default=_DEFAULT_SKILLS_DEST)
504
+ skun = sksub.add_parser("uninstall", help="remove the bundled skills from the skills dir")
505
+ skun.add_argument("--dest", type=Path, default=_DEFAULT_SKILLS_DEST)
506
+
507
+ def _env_kv(s: str) -> tuple[str, str]:
508
+ k, _, v = s.partition("=")
509
+ return (k, v)
510
+
511
+ _CLIENTS = ("claude-code", "claude-desktop", "cursor", "windsurf")
512
+ ins = sub.add_parser("install", help="register this server in an MCP client config")
513
+ ins.add_argument("--client", choices=_CLIENTS, default="claude-code")
514
+ ins.add_argument("--scope", choices=("user", "project"), default="user")
515
+ ins.add_argument("--config", default=None, metavar="PATH", help="explicit config file to edit")
516
+ ins.add_argument("--name", default="meshtastic", help="server name in the config")
517
+ ins.add_argument(
518
+ "--local",
519
+ action="store_true",
520
+ help="register the current interpreter (python -m) instead of uvx",
521
+ )
522
+ ins.add_argument(
523
+ "--env",
524
+ action="append",
525
+ type=_env_kv,
526
+ metavar="KEY=VALUE",
527
+ help="env var to bake into the entry (repeatable)",
528
+ )
529
+ ins.add_argument("--no-skills", action="store_true", help="don't also install the skills")
530
+ ins.add_argument("--skills-dest", type=Path, default=_DEFAULT_SKILLS_DEST)
531
+ ins.add_argument("--print", action="store_true", help="print the JSON snippet, edit nothing")
532
+ ins.add_argument("--dry-run", action="store_true", help="show what would change, write nothing")
533
+
534
+ uns = sub.add_parser("uninstall", help="remove this server's MCP client registration")
535
+ uns.add_argument("--client", choices=_CLIENTS, default="claude-code")
536
+ uns.add_argument("--scope", choices=("user", "project"), default="user")
537
+ uns.add_argument("--config", default=None, metavar="PATH")
538
+ uns.add_argument("--name", default="meshtastic")
539
+ uns.add_argument("--purge-skills", action="store_true", help="also remove installed skills")
540
+ uns.add_argument("--skills-dest", type=Path, default=_DEFAULT_SKILLS_DEST)
541
+
542
+ prov = sub.add_parser(
543
+ "provision",
544
+ help="clone missing source repos (firmware/android/apple) and print export commands",
545
+ )
546
+ prov.add_argument(
547
+ "--dir",
548
+ type=Path,
549
+ default=None,
550
+ metavar="DIR",
551
+ help=f"base directory for cloned repos (default: {_default_provision_dir()})",
552
+ )
553
+
554
+ # --- read-only device / hardware queries ---
555
+ dev = sub.add_parser("devices", help="list connected Meshtastic devices")
556
+ dev.add_argument("--all", action="store_true", help="include non-Meshtastic serial ports")
557
+ dev.add_argument("--json", action="store_true", help="emit JSON")
558
+
559
+ brd = sub.add_parser("boards", help="list / inspect PlatformIO board environments")
560
+ brd.add_argument("--arch", default=None, help="filter by architecture (esp32s3, nrf52840 …)")
561
+ brd.add_argument("--query", default=None, metavar="Q", help="substring filter on name/env")
562
+ brd.add_argument("--supported", action="store_true", help="only actively-supported boards")
563
+ brd.add_argument("--json", action="store_true", help="emit JSON")
564
+ brdsub = brd.add_subparsers(dest="boards_cmd")
565
+ brdget = brdsub.add_parser("get", help="full metadata for one board env")
566
+ brdget.add_argument("env", help="PlatformIO env name (e.g. heltec-v3)")
567
+ brdget.add_argument("--json", action="store_true", help="emit JSON")
568
+
569
+ inf = sub.add_parser("info", help="device firmware/region/node info")
570
+ inf.add_argument("port", help="serial port or tcp://host:port")
571
+ inf.add_argument("--json", action="store_true", help="emit JSON")
572
+
573
+ nod = sub.add_parser("nodes", help="list mesh peers visible to this node")
574
+ nod.add_argument("port", help="serial port or tcp://host:port")
575
+ nod.add_argument("--json", action="store_true", help="emit JSON")
576
+
577
+ wat = sub.add_parser("watch", help="live-tail recorder streams (logs/packets/events)")
578
+ wat.add_argument(
579
+ "stream",
580
+ choices=("logs", "packets", "events"),
581
+ help="which recorder stream to follow",
582
+ )
583
+ wat.add_argument("--interval", type=float, default=2.0, help="poll interval seconds")
584
+
585
+ comp = sub.add_parser("completion", help="print a shell completion script")
586
+ comp.add_argument("shell", choices=("bash", "zsh"), help="target shell")
587
+
588
+ args = p.parse_args(argv)
589
+
590
+ if args.cmd == "doctor":
591
+ from meshtastic_mcp import doctor
592
+
593
+ rep = doctor.run()
594
+ if args.json:
595
+ print(_json_mod.dumps(rep.to_dict(), indent=2))
596
+ else:
597
+ print(doctor.report(rep))
598
+ raise SystemExit(1 if rep.missing else 0)
599
+
600
+ if args.cmd == "install":
601
+ raise SystemExit(_install(args))
602
+
603
+ if args.cmd == "uninstall":
604
+ raise SystemExit(_uninstall(args))
605
+
606
+ if args.cmd == "skills":
607
+ if args.skills_cmd == "uninstall":
608
+ raise SystemExit(_skills_uninstall(args.dest))
609
+ raise SystemExit(_skills_install(args.dest))
610
+
611
+ if args.cmd == "provision":
612
+ base = args.dir or _default_provision_dir()
613
+ print(f"Provisioning source repos under {base}")
614
+ print()
615
+ raise SystemExit(_provision(base))
616
+
617
+ if args.cmd == "devices":
618
+ raise SystemExit(_cmd_devices(args))
619
+
620
+ if args.cmd == "boards":
621
+ raise SystemExit(_cmd_boards(args))
622
+
623
+ if args.cmd == "info":
624
+ raise SystemExit(_cmd_info(args))
625
+
626
+ if args.cmd == "nodes":
627
+ raise SystemExit(_cmd_nodes(args))
628
+
629
+ if args.cmd == "watch":
630
+ raise SystemExit(_cmd_watch(args))
631
+
632
+ if args.cmd == "completion":
633
+ raise SystemExit(_cmd_completion(args))
634
+
635
+ # default: run the MCP server
636
+ from meshtastic_mcp.server import app
637
+
638
+ app.run()
639
+
640
+
641
+ if __name__ == "__main__":
642
+ main()
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None