mpy-workbench 0.2.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.
mpywb/mcp_server.py ADDED
@@ -0,0 +1,230 @@
1
+ """MCP server (stdio) for MicroPython boards, with no dependency beyond Python itself:
2
+ it speaks JSON-RPC over stdin/stdout. mpremote is installed on the first call that
3
+ needs the board (deps.py), so the server starts instantly.
4
+ """
5
+ import contextlib
6
+ import io
7
+ import json
8
+ import sys
9
+ import traceback
10
+
11
+ from . import __version__
12
+ from . import tools
13
+ from .board import BoardError
14
+
15
+ PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
16
+
17
+ PORT = {"type": "string", "description": "Serial port, e.g. /dev/cu.usbmodem101 or COM3. Leave out to use the only board plugged in (or $MPYWB_PORT)."}
18
+ TIMEOUT = {"type": "number", "description": "Seconds to wait for the program to end (default 10)."}
19
+
20
+ TOOLS = [
21
+ {
22
+ "name": "list_ports",
23
+ "description": "List the serial ports on this computer and which ones look like MicroPython boards.",
24
+ "inputSchema": {"type": "object", "properties": {}},
25
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
26
+ },
27
+ {
28
+ "name": "board_info",
29
+ "description": "MicroPython version, chip, free memory and free flash of the connected board.",
30
+ "inputSchema": {"type": "object", "properties": {"port": PORT}},
31
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
32
+ },
33
+ {
34
+ "name": "run_file",
35
+ "description": (
36
+ "Run a project file on the board as __main__. It is uploaded first if the board copy differs "
37
+ "(same path on the board as in the project: lib/x.py -> /lib/x.py). Returns the printed output "
38
+ "and the traceback if it failed. Programs that loop forever (blink, sensors, servers) keep running "
39
+ "after the timeout unless stop_at_timeout is true; then use read_output or stop."
40
+ ),
41
+ "inputSchema": {
42
+ "type": "object",
43
+ "properties": {
44
+ "path": {"type": "string", "description": "File on this computer, relative to the project folder."},
45
+ "port": PORT,
46
+ "timeout": TIMEOUT,
47
+ "stop_at_timeout": {"type": "boolean", "description": "Stop the program with Ctrl-C at the timeout instead of leaving it running (default false)."},
48
+ "device_path": {"type": "string", "description": "Board path to upload to and run, if not the project path."},
49
+ },
50
+ "required": ["path"],
51
+ },
52
+ "annotations": {"destructiveHint": False, "openWorldHint": False},
53
+ },
54
+ {
55
+ "name": "run_code",
56
+ "description": "Run a few lines of MicroPython on the board (like typing them in the REPL) and return what they print, e.g. to check a pin, list I2C devices or try an expression.",
57
+ "inputSchema": {
58
+ "type": "object",
59
+ "properties": {"code": {"type": "string"}, "port": PORT, "timeout": TIMEOUT},
60
+ "required": ["code"],
61
+ },
62
+ "annotations": {"destructiveHint": False, "openWorldHint": False},
63
+ },
64
+ {
65
+ "name": "read_output",
66
+ "description": "Read what a program still running on the board prints, for a few seconds, without stopping it.",
67
+ "inputSchema": {"type": "object", "properties": {"port": PORT, "seconds": {"type": "number", "description": "How long to listen (default 3)."}}},
68
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
69
+ },
70
+ {
71
+ "name": "stop",
72
+ "description": "Stop the program running on the board (Ctrl-C).",
73
+ "inputSchema": {"type": "object", "properties": {"port": PORT}},
74
+ "annotations": {"destructiveHint": False, "idempotentHint": True, "openWorldHint": False},
75
+ },
76
+ {
77
+ "name": "soft_reset",
78
+ "description": "Soft-reset the board: clears memory and imported modules. Use it when a changed module doesn't seem to take effect.",
79
+ "inputSchema": {"type": "object", "properties": {"port": PORT}},
80
+ "annotations": {"destructiveHint": False, "openWorldHint": False},
81
+ },
82
+ {
83
+ "name": "upload",
84
+ "description": "Upload a project file or folder to the board (same path on the board as in the project). Only files whose bytes differ are sent; each one is checked by SHA-256 afterwards.",
85
+ "inputSchema": {
86
+ "type": "object",
87
+ "properties": {
88
+ "path": {"type": "string", "description": "File or folder on this computer, relative to the project folder."},
89
+ "port": PORT,
90
+ "device_path": {"type": "string", "description": "Board path, if not the project path."},
91
+ },
92
+ "required": ["path"],
93
+ },
94
+ "annotations": {"destructiveHint": True, "openWorldHint": False},
95
+ },
96
+ {
97
+ "name": "list_files",
98
+ "description": "List the files and folders in a folder on the board.",
99
+ "inputSchema": {"type": "object", "properties": {"path": {"type": "string", "description": "Board folder (default /)."}, "port": PORT}},
100
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
101
+ },
102
+ {
103
+ "name": "diff",
104
+ "description": (
105
+ "Compare the project with the board. Without a path: lists files that differ, are only in the project "
106
+ "or only on the board (rules from .mpyignore). With a path: the line diff between the board copy and the project file."
107
+ ),
108
+ "inputSchema": {"type": "object", "properties": {"path": {"type": "string", "description": "Project file to diff (optional)."}, "port": PORT}},
109
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
110
+ },
111
+ {
112
+ "name": "sync",
113
+ "description": (
114
+ "Make the board match the project folder: upload every file that differs or is missing (checked by SHA-256; "
115
+ ".mpyignore and .mpy-workbench/.mpyignore are respected). Board-only files are kept unless delete is true. "
116
+ "Use dry_run first when unsure."
117
+ ),
118
+ "inputSchema": {"type": "object", "properties": {
119
+ "port": PORT,
120
+ "delete": {"type": "boolean", "description": "Also delete board files that are not in the project (default false). Ask the user first."},
121
+ "dry_run": {"type": "boolean", "description": "Only report what would change."},
122
+ }},
123
+ "annotations": {"destructiveHint": True, "openWorldHint": False},
124
+ },
125
+ {
126
+ "name": "read_file",
127
+ "description": "Read a text file from the board.",
128
+ "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "port": PORT}, "required": ["path"]},
129
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
130
+ },
131
+ ]
132
+
133
+
134
+ def call_tool(name, a):
135
+ port = a.get("port") or None
136
+ if name == "list_ports":
137
+ return tools.tool_list_ports()
138
+ if name == "board_info":
139
+ return tools.tool_board_info(port)
140
+ if name == "run_file":
141
+ return tools.tool_run_file(a["path"], port, float(a.get("timeout") or 10), bool(a.get("stop_at_timeout")), a.get("device_path"))[0]
142
+ if name == "run_code":
143
+ return tools.tool_run_code(a["code"], port, float(a.get("timeout") or 10))[0]
144
+ if name == "read_output":
145
+ return tools.tool_read_output(port, float(a.get("seconds") or 3))
146
+ if name == "stop":
147
+ return tools.tool_stop(port)
148
+ if name == "soft_reset":
149
+ return tools.tool_soft_reset(port)
150
+ if name == "upload":
151
+ return tools.tool_upload(a["path"], port, a.get("device_path"))
152
+ if name == "list_files":
153
+ return tools.tool_list_files(a.get("path") or "/", port)
154
+ if name == "diff":
155
+ return tools.tool_diff(a.get("path") or None, port)
156
+ if name == "sync":
157
+ return tools.tool_sync(port, bool(a.get("delete")), bool(a.get("dry_run")))
158
+ if name == "read_file":
159
+ return tools.tool_read_file(a["path"], port)
160
+ raise KeyError(name)
161
+
162
+
163
+ def handle(msg):
164
+ """Answer for one JSON-RPC message, or None for notifications."""
165
+ method = msg.get("method")
166
+ mid = msg.get("id")
167
+ if mid is None:
168
+ return None # notifications (initialized, cancelled…)
169
+ if method == "initialize":
170
+ asked = (msg.get("params") or {}).get("protocolVersion")
171
+ return {"jsonrpc": "2.0", "id": mid, "result": {
172
+ "protocolVersion": asked if asked in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0],
173
+ "capabilities": {"tools": {"listChanged": False}},
174
+ "serverInfo": {"name": "mpy-workbench", "title": "MPY Workbench (MicroPython board)", "version": __version__},
175
+ "instructions": (
176
+ "Tools for a MicroPython board on USB (ESP32, Raspberry Pi Pico and others). Edit files in the "
177
+ "project as usual; run_file uploads what changed and runs it, returning output and tracebacks. "
178
+ "The board's port is opened only during each call."
179
+ ),
180
+ }}
181
+ if method == "ping":
182
+ return {"jsonrpc": "2.0", "id": mid, "result": {}}
183
+ if method == "tools/list":
184
+ return {"jsonrpc": "2.0", "id": mid, "result": {"tools": TOOLS}}
185
+ if method == "tools/call":
186
+ p = msg.get("params") or {}
187
+ name = p.get("name")
188
+ args = p.get("arguments") or {}
189
+ if name not in {t["name"] for t in TOOLS}:
190
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": "Unknown tool: %s" % name}}
191
+ stray = io.StringIO()
192
+ try:
193
+ with contextlib.redirect_stdout(stray): # stdout belongs to the protocol
194
+ text, is_error = call_tool(name, args), False
195
+ except (BoardError, RuntimeError, KeyError, ValueError) as e:
196
+ text, is_error = str(e), True
197
+ except Exception as e:
198
+ text, is_error = "%s: %s\n%s" % (type(e).__name__, e, traceback.format_exc(limit=3)), True
199
+ if stray.getvalue():
200
+ sys.stderr.write(stray.getvalue())
201
+ return {"jsonrpc": "2.0", "id": mid, "result": {"content": [{"type": "text", "text": text}], "isError": is_error}}
202
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "Method not found: %s" % method}}
203
+
204
+
205
+ def serve(stdin=None, stdout=None):
206
+ stdin = stdin or sys.stdin
207
+ stdout = stdout or sys.stdout
208
+ for line in stdin:
209
+ line = line.strip()
210
+ if not line:
211
+ continue
212
+ try:
213
+ msg = json.loads(line)
214
+ except ValueError:
215
+ reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}
216
+ else:
217
+ msgs = msg if isinstance(msg, list) else [msg]
218
+ replies = [r for r in (handle(m) for m in msgs) if r is not None]
219
+ reply = replies if isinstance(msg, list) else (replies[0] if replies else None)
220
+ if reply:
221
+ stdout.write(json.dumps(reply) + "\n")
222
+ stdout.flush()
223
+
224
+
225
+ def main():
226
+ serve()
227
+
228
+
229
+ if __name__ == "__main__":
230
+ main()
mpywb/sync.py ADDED
@@ -0,0 +1,101 @@
1
+ """Keeps the board in step with the project folder, like the VS Code extension does.
2
+ Pure logic (which files, which are ignored, what differs): no board needed, so it is
3
+ unit-tested. The board work is in tools.py.
4
+
5
+ Ignore rules come from the same file the extension uses, .mpy-workbench/.mpyignore, and
6
+ from .mpyignore at the project root. One glob per line, # for comments:
7
+ *.md any .md file docs/ the docs folder
8
+ /secret.py only at the root **/test_* test files anywhere
9
+ """
10
+ import hashlib
11
+ import os
12
+ import re
13
+
14
+ # The extension's defaults, plus folders that never belong on a board
15
+ DEFAULT_IGNORE = [
16
+ ".git/", ".hg/", ".svn/", ".vscode/", ".idea/", ".claude/", ".mpy-workbench/",
17
+ "node_modules/", "dist/", "out/", "build/", "__pycache__/", ".venv/", "venv/",
18
+ ".DS_Store", "*.pyc", ".mpyignore", ".gitignore",
19
+ ]
20
+ IGNORE_FILES = (os.path.join(".mpy-workbench", ".mpyignore"), ".mpyignore")
21
+
22
+
23
+ def glob_to_regex(pattern):
24
+ """Same rules as the extension's globToRegExp (src/sync.ts)."""
25
+ p = pattern.strip()
26
+ anchored = p.startswith("/")
27
+ if anchored:
28
+ p = p[1:]
29
+ p = re.sub(r"([.+^${}()|\[\]\\])", r"\\\1", p)
30
+ p = p.replace("**", "\0").replace("*", "[^/]*").replace("?", "[^/]").replace("\0", ".*")
31
+ trailing = p.endswith("/")
32
+ core = p[:-1] if trailing else p
33
+ return re.compile(("^" if anchored else "(^|.*/)") + core + ("(?:/.*)?$" if trailing else "$"))
34
+
35
+
36
+ def load_ignore(project):
37
+ patterns = list(DEFAULT_IGNORE)
38
+ for name in IGNORE_FILES:
39
+ try:
40
+ with open(os.path.join(project, name), encoding="utf-8") as f:
41
+ patterns += [l.strip() for l in f if l.strip() and not l.strip().startswith("#")]
42
+ except OSError:
43
+ pass
44
+ regs = [glob_to_regex(p) for p in patterns]
45
+
46
+ def ignored(rel, is_dir=False):
47
+ rel = rel.replace("\\", "/").strip("/")
48
+ if is_dir:
49
+ rel += "/"
50
+ return any(r.search(rel) or r.search(rel.rstrip("/")) for r in regs)
51
+
52
+ return ignored
53
+
54
+
55
+ def local_files(project, ignored=None):
56
+ """{project-relative path: absolute path} of the files that belong on the board."""
57
+ ignored = ignored or load_ignore(project)
58
+ out = {}
59
+ for root, dirs, files in os.walk(project):
60
+ rel_root = os.path.relpath(root, project).replace(os.sep, "/")
61
+ rel_root = "" if rel_root == "." else rel_root + "/"
62
+ dirs[:] = sorted(d for d in dirs if not ignored(rel_root + d, True))
63
+ for f in sorted(files):
64
+ rel = rel_root + f
65
+ if not ignored(rel):
66
+ out[rel] = os.path.join(root, f)
67
+ return out
68
+
69
+
70
+ def file_sha256(path):
71
+ h = hashlib.sha256()
72
+ with open(path, "rb") as f:
73
+ for block in iter(lambda: f.read(65536), b""):
74
+ h.update(block)
75
+ return h.hexdigest()
76
+
77
+
78
+ def compare(local_hashes, board_hashes, board_files, ignored=lambda rel, is_dir=False: False):
79
+ """What differs between the project and the board.
80
+ local_hashes: {rel: sha}; board_hashes: {"/rel": sha | None | ""} for those files;
81
+ board_files: every file path on the board ("/rel"). Board files that the ignore
82
+ rules cover (e.g. boot.py if listed) are not reported as board-only.
83
+ Returns {"same", "differs", "local_only", "board_only", "unknown"} → sorted lists of rel paths."""
84
+ res = {"same": [], "differs": [], "local_only": [], "board_only": [], "unknown": []}
85
+ for rel, sha in local_hashes.items():
86
+ b = board_hashes.get("/" + rel)
87
+ if b is None:
88
+ res["local_only"].append(rel)
89
+ elif b == "":
90
+ res["unknown"].append(rel)
91
+ elif b == sha:
92
+ res["same"].append(rel)
93
+ else:
94
+ res["differs"].append(rel)
95
+ for path in board_files:
96
+ rel = path.lstrip("/")
97
+ if rel not in local_hashes and not ignored(rel):
98
+ res["board_only"].append(rel)
99
+ for k in res:
100
+ res[k].sort()
101
+ return res
mpywb/tools.py ADDED
@@ -0,0 +1,282 @@
1
+ """The actions an agent can take, shared by the command line (cli.py) and the MCP
2
+ server (mcp_server.py). Each returns plain text meant to be read by a person or a model.
3
+
4
+ Paths on this computer are relative to the project folder ($CLAUDE_PROJECT_DIR, else
5
+ the current folder). A project file goes to the same path on the board: lib/util.py on
6
+ this computer is /lib/util.py on the board.
7
+ """
8
+ import difflib
9
+ import os
10
+
11
+ from . import sync
12
+ from .board import Board, BoardError, list_ports, pick_port
13
+ from .linkclient import LinkBoard, find_link
14
+
15
+ SKIP_DIRS = {".git", ".hg", ".svn", "__pycache__", "node_modules", ".venv", "venv", ".vscode", ".idea", ".mpy-workbench", ".claude"}
16
+ SKIP_FILES = {".DS_Store"}
17
+
18
+
19
+ def open_board(port):
20
+ """The board on `port`: through VS Code's shared link when the MPY Workbench
21
+ extension holds the port, else by opening the port directly."""
22
+ info = find_link(port)
23
+ return LinkBoard(port, info) if info else Board(port)
24
+
25
+
26
+ def project_dir():
27
+ return os.path.abspath(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
28
+
29
+
30
+ def local_path(path):
31
+ p = os.path.expanduser(path)
32
+ return os.path.abspath(p if os.path.isabs(p) else os.path.join(project_dir(), p))
33
+
34
+
35
+ def project_relative(local):
36
+ """Path inside the project ("lib/util.py"), or None if the file is outside it
37
+ (including on another drive on Windows, where relpath can't be computed)."""
38
+ try:
39
+ rel = os.path.relpath(local, project_dir())
40
+ except ValueError:
41
+ return None
42
+ return None if rel.startswith("..") else rel.replace(os.sep, "/")
43
+
44
+
45
+ def device_path_for(local, device_path=None):
46
+ """Board path for a local file: the given one, else its path inside the project."""
47
+ if device_path:
48
+ return device_path if device_path.startswith("/") else "/" + device_path
49
+ return "/" + (project_relative(local) or os.path.basename(local))
50
+
51
+
52
+ def _status_line(r, timeout):
53
+ if r["still_running"]:
54
+ return "Still running after %g s (left running; use stop to end it, read_output to see more)." % timeout
55
+ if r["stopped"]:
56
+ return "Stopped with Ctrl-C after %g s." % timeout
57
+ return "Finished with an error." if r["error"] else "Finished."
58
+
59
+
60
+ def _format_run(r, timeout, header=""):
61
+ parts = [header] if header else []
62
+ parts.append(_status_line(r, timeout))
63
+ parts.append("--- output ---\n" + (r["output"] if r["output"].strip() else "(no output)"))
64
+ if r["error"].strip():
65
+ parts.append("--- error ---\n" + r["error"].rstrip())
66
+ return "\n".join(parts)
67
+
68
+
69
+ def tool_list_ports():
70
+ ports = list_ports()
71
+ if not ports:
72
+ return "No serial ports found. Plug the board in with a data cable (some USB cables only charge)."
73
+ lines = []
74
+ for p in ports:
75
+ tag = " ← MicroPython board?" if p["likely_micropython"] else ""
76
+ lines.append("%s %s%s%s" % (p["port"], p["description"], (" (" + p["maker"] + ")") if p["maker"] else "", tag))
77
+ return "\n".join(lines)
78
+
79
+
80
+ def tool_board_info(port=None):
81
+ port = pick_port(port)
82
+ with open_board(port) as b:
83
+ i = b.info()
84
+ return ("Port: %s\nMicroPython %s (%s) on %s\nFree memory: %d bytes\nFlash: %d of %d bytes free"
85
+ % (port, i["version"], i["implementation"], i["machine"], i["free_memory_bytes"], i["flash_free_bytes"], i["flash_total_bytes"]))
86
+
87
+
88
+ def tool_run_file(path, port=None, timeout=10.0, stop_at_timeout=False, device_path=None):
89
+ from .codegen import run_file_code
90
+
91
+ local = local_path(path)
92
+ if not os.path.isfile(local):
93
+ raise BoardError("No such file on this computer: %s" % local)
94
+ dev = device_path_for(local, device_path)
95
+ trace = project_relative(local) or os.path.basename(local)
96
+ port = pick_port(port)
97
+ with open_board(port) as b:
98
+ b.stop()
99
+ state = b.put(local, dev)
100
+ r = b.run(run_file_code(dev, trace), timeout=timeout, stop_at_timeout=stop_at_timeout)
101
+ header = "Ran %s on the board (%s, %s)." % (dev, port, "uploaded first" if state == "uploaded" else "board copy was already up to date")
102
+ return _format_run(r, timeout, header), r
103
+
104
+
105
+ def tool_run_code(code, port=None, timeout=10.0, stop_at_timeout=True):
106
+ port = pick_port(port)
107
+ with open_board(port) as b:
108
+ r = b.run(code, timeout=timeout, stop_at_timeout=stop_at_timeout)
109
+ return _format_run(r, timeout), r
110
+
111
+
112
+ def tool_stop(port=None):
113
+ port = pick_port(port)
114
+ with open_board(port) as b:
115
+ b.stop()
116
+ return "Stopped whatever was running on %s; the board is at the REPL." % port
117
+
118
+
119
+ def tool_soft_reset(port=None):
120
+ port = pick_port(port)
121
+ with open_board(port) as b:
122
+ b.soft_reset()
123
+ return "Soft reset done on %s (memory and modules cleared)." % port
124
+
125
+
126
+ def tool_read_output(port=None, seconds=3.0):
127
+ port = pick_port(port)
128
+ with open_board(port) as b:
129
+ text = b.watch(seconds)
130
+ return "--- output during %g s ---\n%s" % (seconds, text if text.strip() else "(nothing printed)")
131
+
132
+
133
+ def _walk(local_dir):
134
+ for root, dirs, files in os.walk(local_dir):
135
+ dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.startswith("."))
136
+ for f in sorted(files):
137
+ if f in SKIP_FILES or f.endswith(".pyc"):
138
+ continue
139
+ yield os.path.join(root, f)
140
+
141
+
142
+ def tool_upload(path, port=None, device_path=None):
143
+ local = local_path(path)
144
+ if not os.path.exists(local):
145
+ raise BoardError("No such file or folder on this computer: %s" % local)
146
+ port = pick_port(port)
147
+ lines = []
148
+ with open_board(port) as b:
149
+ b.stop()
150
+ if os.path.isdir(local):
151
+ base_dev = device_path_for(local, device_path).rstrip("/")
152
+ for f in _walk(local):
153
+ dev = base_dev + "/" + os.path.relpath(f, local).replace(os.sep, "/")
154
+ lines.append("%-9s %s" % (b.put(f, dev), dev))
155
+ else:
156
+ dev = device_path_for(local, device_path)
157
+ lines.append("%-9s %s" % (b.put(local, dev), dev))
158
+ if not lines:
159
+ return "Nothing to upload in %s." % local
160
+ return "Upload to %s (each file checked by SHA-256):\n%s" % (port, "\n".join(lines))
161
+
162
+
163
+ def tool_list_files(path="/", port=None):
164
+ port = pick_port(port)
165
+ with open_board(port) as b:
166
+ entries = b.listdir(path)
167
+ if not entries:
168
+ return "%s is empty." % path
169
+ return "\n".join(("%s/" % e["name"]) if e["dir"] else "%s (%d bytes)" % (e["name"], e["size"]) for e in entries)
170
+
171
+
172
+ def tool_read_file(path, port=None):
173
+ port = pick_port(port)
174
+ with open_board(port) as b:
175
+ return b.read_text(path)
176
+
177
+
178
+ def _project_state(b):
179
+ """Compares the project with the board: (comparison, local {rel: abs}, local hashes)."""
180
+ project = project_dir()
181
+ ignored = sync.load_ignore(project)
182
+ files = sync.local_files(project, ignored)
183
+ local_hashes = {rel: sync.file_sha256(p) for rel, p in files.items()}
184
+ board_files, _ = b.walk("/")
185
+ board_hashes = b.hashes(["/" + rel for rel in files if "/" + rel in board_files])
186
+ for rel in files:
187
+ board_hashes.setdefault("/" + rel, None)
188
+ return sync.compare(local_hashes, board_hashes, board_files, ignored), files, board_hashes
189
+
190
+
191
+ def _summary(c):
192
+ lines = []
193
+ for key, label in (("differs", "≠ different on the board"), ("local_only", "↑ only in the project"),
194
+ ("board_only", "↓ only on the board"), ("unknown", "? board can't hash (no hashlib)")):
195
+ for rel in c[key]:
196
+ lines.append("%s %s" % (label.split(" ", 1)[0], rel))
197
+ head = "%d same, %d different, %d only in the project, %d only on the board" % (
198
+ len(c["same"]), len(c["differs"]), len(c["local_only"]), len(c["board_only"]))
199
+ return head + ("\n" + "\n".join(lines) if lines else "")
200
+
201
+
202
+ def tool_diff(path=None, port=None):
203
+ """Without a path: which project files differ from the board. With a path: the
204
+ line diff between the board copy and the project file."""
205
+ port = pick_port(port)
206
+ with open_board(port) as b:
207
+ b.stop()
208
+ if not path:
209
+ c, _, _ = _project_state(b)
210
+ return "Project %s vs board (%s); ignore rules: .mpyignore\n%s" % (project_dir(), port, _summary(c))
211
+ local = local_path(path)
212
+ dev = device_path_for(local)
213
+ try:
214
+ board_text = b.read_text(dev, limit=10 ** 9)
215
+ except BoardError:
216
+ board_text = None
217
+ if board_text is None:
218
+ return "%s is not on the board." % dev
219
+ try:
220
+ with open(local, encoding="utf-8", errors="replace") as f:
221
+ local_text = f.read()
222
+ except OSError:
223
+ return "%s is only on the board (no %s in the project)." % (dev, local)
224
+ diff = list(difflib.unified_diff(board_text.splitlines(True), local_text.splitlines(True),
225
+ "board:" + dev, "project:" + (project_relative(local) or local)))
226
+ return "".join(diff) if diff else "%s is the same on the board and in the project." % dev
227
+
228
+
229
+ def tool_sync(port=None, delete=False, dry_run=False):
230
+ """Makes the board match the project: uploads files that differ or are missing.
231
+ delete=True also removes board files that are not in the project (never ignored ones)."""
232
+ port = pick_port(port)
233
+ with open_board(port) as b:
234
+ b.stop()
235
+ c, files, board_hashes = _project_state(b)
236
+ todo = c["differs"] + c["local_only"]
237
+ removed = c["board_only"] if delete else []
238
+ if dry_run:
239
+ return "Dry run on %s, nothing changed.\nWould upload: %s\nWould delete: %s\n%s" % (
240
+ port, ", ".join(todo) or "nothing", ", ".join(removed) or "nothing", _summary(c))
241
+ lines = []
242
+ for rel in todo:
243
+ lines.append("%-9s /%s" % (b.put(files[rel], "/" + rel, board_hashes.get("/" + rel)), rel))
244
+ for rel in removed:
245
+ b.delete("/" + rel)
246
+ lines.append("deleted /%s" % rel)
247
+ kept = "" if delete or not c["board_only"] else "\nOnly on the board (kept; delete=true removes them): " + ", ".join(c["board_only"])
248
+ if not lines:
249
+ return "The board already matches the project (%d files)." % len(c["same"]) + kept
250
+ return "Synced the project to %s:\n%s%s" % (port, "\n".join(lines), kept)
251
+
252
+
253
+ def hook_upload(event):
254
+ """PostToolUse hook: uploads the file Claude just wrote, when the project is a
255
+ MicroPython project and one board is plugged in. Returns a note for Claude, or None
256
+ to stay silent (not a board project, ignored file, no board)."""
257
+ if os.environ.get("MPYWB_AUTO_UPLOAD") == "0":
258
+ return None
259
+ path = ((event or {}).get("tool_input") or {}).get("file_path")
260
+ if not path:
261
+ return None
262
+ project = project_dir()
263
+ marked = os.path.isdir(os.path.join(project, ".mpy-workbench")) or os.path.isfile(os.path.join(project, ".mpyignore"))
264
+ if not marked and os.environ.get("MPYWB_AUTO_UPLOAD") != "1":
265
+ return None # not a MicroPython project: never touch a board
266
+ local = local_path(path)
267
+ rel = project_relative(local)
268
+ if not rel or not os.path.isfile(local) or sync.load_ignore(project)(rel):
269
+ return None
270
+ try:
271
+ port = pick_port()
272
+ except BoardError:
273
+ return None # no board, or several: run_file/upload will say which
274
+ try:
275
+ with open_board(port) as b:
276
+ b.stop()
277
+ state = b.put(local, "/" + rel)
278
+ except BoardError as e:
279
+ return "Auto-upload: %s was NOT uploaded to the board: %s" % (rel, e)
280
+ if state == "unchanged":
281
+ return None
282
+ return "Auto-upload: %s uploaded to /%s on the board (%s). A program that was running there was stopped." % (rel, rel, port)