stlink-mcp 0.8.5__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.
stlink_mcp/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """An MCP server for programming and inspecting STM32 targets over ST-LINK."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ # Read from the installed metadata, which versioningit derives from the git tag,
6
+ # so the tag stays the only copy. This used to be a literal "0.1.0", a second
7
+ # copy that would have been wrong from the first commit after the next tag.
8
+ try:
9
+ __version__ = version("stlink-mcp")
10
+ except PackageNotFoundError:
11
+ # Imported from a source tree that was never installed, as tools/dwctl.py
12
+ # does. Nothing there says which version it is.
13
+ __version__ = "0.0.0+unknown"
stlink_mcp/__main__.py ADDED
@@ -0,0 +1,175 @@
1
+ """Entry point. Runs the MCP server on stdio, which is how MCP clients spawn it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import signal
7
+ import sys
8
+
9
+ from . import __version__, settings
10
+ from . import server as server_mod
11
+ from .quirks import BoardConfigError
12
+ from .runner import release_all_servers
13
+ from .toolchain import ToolchainError
14
+
15
+
16
+ def _release_and_exit(signum: int, _frame: object) -> None:
17
+ """Free held probes on a signal, which `atexit` alone does not cover.
18
+
19
+ Python runs `atexit` handlers on a normal exit, and on SIGINT because it
20
+ installs a handler for that one. It installs none for SIGTERM or SIGHUP, so
21
+ the default action terminates the process immediately and any held GDB
22
+ server is orphaned: it keeps the probe and both of its ports, and nothing on
23
+ disk records that it exists. SIGTERM is what `kill` and any supervisor send,
24
+ and SIGHUP is what a closing terminal sends, so neither is an exotic case.
25
+
26
+ SIGKILL cannot be caught and is not covered. Nothing in a process can cover
27
+ it, which is worth saying plainly rather than implying the guarantee is
28
+ complete.
29
+ """
30
+ release_all_servers()
31
+ # Die the way the signal would have, so a supervisor sees a normal signal
32
+ # death rather than a clean exit that hides what happened.
33
+ signal.signal(signum, signal.SIG_DFL)
34
+ signal.raise_signal(signum)
35
+
36
+
37
+ def _install_signal_handlers() -> None:
38
+ wanted = [signal.SIGTERM]
39
+ hangup = getattr(signal, "SIGHUP", None) # absent on Windows
40
+ if hangup is not None:
41
+ wanted.append(hangup)
42
+
43
+ for sig in wanted:
44
+ try:
45
+ signal.signal(sig, _release_and_exit)
46
+ except (OSError, ValueError):
47
+ # Not the main thread, or a platform that will not take it. The
48
+ # atexit path still covers the ordinary exit.
49
+ pass
50
+
51
+
52
+ def _parse_arguments(argv: list[str] | None) -> argparse.Namespace:
53
+ parser = argparse.ArgumentParser(
54
+ prog="stlink-mcp",
55
+ description=(
56
+ "An MCP server for STM32 targets over ST-LINK. It speaks MCP on stdin "
57
+ "and stdout and is meant to be started by an MCP client; README.md "
58
+ "has the client configuration."
59
+ ),
60
+ epilog=(
61
+ "Settings are environment variables: STLINK_MCP_CLT_ROOT, "
62
+ "STLINK_MCP_BOARDS, STLINK_MCP_CONSOLE, STLINK_MCP_CONSOLE_BAUD, "
63
+ "STLINK_MCP_GDB_PORT and STLINK_MCP_NO_VENDOR_SEED."
64
+ ),
65
+ )
66
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
67
+ parser.add_argument(
68
+ "--check", action="store_true",
69
+ help=(
70
+ "report the settings, toolchain, vendor database, board file and "
71
+ "attached probes this server would use, then exit"
72
+ ),
73
+ )
74
+ return parser.parse_args(argv)
75
+
76
+
77
+ def _check() -> int:
78
+ """`stlink-mcp --check`: what the server would use, without starting it.
79
+
80
+ Exit status 0 when it would start with a toolchain, 1 when no usable
81
+ STM32CubeCLT or probe listing was found, 2 for a setting or board file the
82
+ server would refuse. It lists probes with the programmer's `-l`, which
83
+ neither halts nor resets anything and works while other probes are held.
84
+ """
85
+ print(f"stlink-mcp {__version__}")
86
+ try:
87
+ settings.check()
88
+ except settings.SettingError as exc:
89
+ print(f"settings: {exc}")
90
+ return 2
91
+ print("settings: usable")
92
+
93
+ try:
94
+ toolchain = server_mod._toolchain()
95
+ except ToolchainError as exc:
96
+ print(f"toolchain: {exc}")
97
+ return 1
98
+ source = getattr(toolchain, "source", "STM32CubeCLT")
99
+ print(f"toolchain: {toolchain.root}" + (f" ({source}'s bundled tools)" if source != "STM32CubeCLT" else ""))
100
+ if getattr(toolchain, "passed_over", ()):
101
+ passed = ", ".join(str(p) for p in toolchain.passed_over)
102
+ print(f" passed over as incomplete, though newer: {passed}")
103
+ print(f"vendor database: {server_mod.load_vendor_seed()}")
104
+
105
+ try:
106
+ count, path = server_mod.load_board_config()
107
+ except BoardConfigError as exc:
108
+ print(f"board file: {exc}")
109
+ return 2
110
+ print(f"board file: {path}, {count} board(s)" if path else "board file: none")
111
+
112
+ listing = server_mod.list_probes()
113
+ if listing["status"] != "verified":
114
+ print(f"probes: {listing.get('error') or listing.get('unverified_because')}")
115
+ for line in listing.get("errors", []):
116
+ print(f" {line}")
117
+ return 1
118
+ print(f"probes: {listing['count']} attached")
119
+ for probe in listing["probes"]:
120
+ console = probe["console_port"] or "no console mapped"
121
+ if probe["console_port"]:
122
+ console += f" ({probe['console_port_source']})"
123
+ print(
124
+ f" {probe['serial']} {probe['board'] or 'unknown board'} "
125
+ f"firmware {probe['firmware'] or 'unknown'} console {console}"
126
+ )
127
+ if probe.get("console_note"):
128
+ print(f" {probe['console_note']}")
129
+ if listing.get("unreadable_note"):
130
+ print(f" {listing['unreadable_note']}")
131
+ return 0
132
+
133
+
134
+ def main(argv: list[str] | None = None) -> None:
135
+ arguments = _parse_arguments(argv)
136
+ if arguments.check:
137
+ raise SystemExit(_check())
138
+
139
+ _install_signal_handlers()
140
+
141
+ # Settings first, and the same way a bad board file is handled: one line on
142
+ # stderr and exit 2. Two of them used to be parsed at import time, so a typo
143
+ # in the GDB port killed the process with a traceback before this ran.
144
+ try:
145
+ settings.check()
146
+ except settings.SettingError as exc:
147
+ print(f"stlink-mcp: {exc}", file=sys.stderr)
148
+ raise SystemExit(2) from exc
149
+
150
+ # Board config is loaded here, before the server accepts anything, and a bad
151
+ # file stops the process. That is deliberate. A user who wrote a board file
152
+ # is telling this server what is on their desk; starting anyway with those
153
+ # boards missing would answer every later question about a different machine
154
+ # than the one they described, and the client would see a working server.
155
+ #
156
+ # stderr rather than stdout: stdout is the MCP transport.
157
+ # Printed unconditionally. The previous version gated this on a non-zero
158
+ # count, which is how a database format change that silently lost all 99
159
+ # device IDs became indistinguishable from a machine with no toolchain.
160
+ print(f"stlink-mcp: {server_mod.load_vendor_seed()}", file=sys.stderr)
161
+
162
+ try:
163
+ count, path = server_mod.load_board_config()
164
+ except BoardConfigError as exc:
165
+ print(f"stlink-mcp: {exc}", file=sys.stderr)
166
+ raise SystemExit(2) from exc
167
+ if count:
168
+ print(f"stlink-mcp: loaded {count} user-described board(s) from {path}",
169
+ file=sys.stderr)
170
+
171
+ server_mod.mcp.run()
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
stlink_mcp/console.py ADDED
@@ -0,0 +1,128 @@
1
+ """Capturing the target's serial console.
2
+
3
+ Most ST development boards expose a UART through the on-board debug probe as a
4
+ USB CDC device. On a target whose debug port is closed in its normal boot
5
+ configuration, this is the only way to observe a running program, so it is a
6
+ first-class part of the tool surface rather than a convenience.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from collections.abc import Callable
13
+ from typing import Any
14
+
15
+ import serial
16
+
17
+ #: How long the port must stay quiet after opening before the capture counts
18
+ #: what arrives as new. Measured on an STLINK-V3E (2026-10-01): the output it
19
+ #: buffered while the port was closed, up to about 8 KB, arrived at once after
20
+ #: the open, and a target printing a line every 650 ms sent its next one then.
21
+ _BACKLOG_QUIET = 0.1
22
+
23
+ #: The longest the drain runs. A target that prints with no 100 ms gap keeps
24
+ #: it going, and what it prints in that time is set aside with the backlog.
25
+ _BACKLOG_LIMIT = 1.0
26
+
27
+
28
+ class ConsoleError(RuntimeError):
29
+ pass
30
+
31
+
32
+ # There was a find_console_port() here, which returned STLINK_MCP_CONSOLE or else
33
+ # the first /dev/ttyACM* on the machine. run_firmware fell back to it whenever it
34
+ # had no probe listing, which is the guess docs/findings.md records as the wrong
35
+ # board about half the time with two attached. The console now comes only from
36
+ # the probe list or from STLINK_MCP_CONSOLE naming the probe (settings.py).
37
+
38
+
39
+ class ConsoleCapture:
40
+ """Collects console output in the background across an operation.
41
+
42
+ Used as a context manager around a load-and-run so that output produced
43
+ immediately at start-up is not missed, which is exactly the output that says
44
+ whether the thing started.
45
+
46
+ What arrives the moment the port opens is kept apart, in `buffered`. An
47
+ ST-LINK keeps what the target prints while nothing has its serial port open
48
+ and hands it over on the next open, so those bytes come from before the
49
+ capture: from the previous image, on the run path. Counting them as new is
50
+ how a run of an image that printed nothing was verified on the previous
51
+ image's lines (docs/findings.md, 2026-10-01). Clearing the host's input
52
+ buffer does not catch them, because they have not arrived yet when it runs.
53
+ """
54
+
55
+ def __init__(
56
+ self, port: str, baud: int = 115200,
57
+ opener: Callable[..., Any] = serial.Serial,
58
+ ) -> None:
59
+ self.port = port
60
+ self.baud = baud
61
+ self._opener = opener
62
+ self._serial: Any = None
63
+ self._buffer = bytearray()
64
+ self._buffered = bytearray()
65
+
66
+ def __enter__(self) -> "ConsoleCapture":
67
+ try:
68
+ self._serial = self._opener(self.port, self.baud, timeout=0.1)
69
+ except (serial.SerialException, OSError) as exc:
70
+ raise ConsoleError(
71
+ f"Could not open {self.port} at {self.baud}: {exc}. "
72
+ "On Linux the user usually needs to be in the 'dialout' group."
73
+ ) from exc
74
+ self._serial.reset_input_buffer()
75
+ try:
76
+ self._drain_backlog()
77
+ except (serial.SerialException, OSError) as exc:
78
+ self.__exit__()
79
+ raise ConsoleError(f"{self.port} failed while it was being opened: {exc}") from exc
80
+ return self
81
+
82
+ def _drain_backlog(self) -> None:
83
+ """Set aside what arrives until the port has been quiet for _BACKLOG_QUIET."""
84
+ start = last = time.monotonic()
85
+ while True:
86
+ now = time.monotonic()
87
+ if now - start >= _BACKLOG_LIMIT or now - last >= _BACKLOG_QUIET:
88
+ return
89
+ waiting = self._serial.in_waiting
90
+ if waiting:
91
+ self._buffered.extend(self._serial.read(waiting))
92
+ last = time.monotonic()
93
+ else:
94
+ time.sleep(0.005)
95
+
96
+ def __exit__(self, *exc_info: object) -> None:
97
+ if self._serial is not None:
98
+ self._serial.close()
99
+ self._serial = None
100
+
101
+ def collect(self, seconds: float) -> str:
102
+ """Read for a fixed period and return what arrived."""
103
+ if self._serial is None:
104
+ raise ConsoleError("Capture is not open")
105
+
106
+ deadline = time.monotonic() + seconds
107
+ while time.monotonic() < deadline:
108
+ waiting = self._serial.in_waiting
109
+ chunk = self._serial.read(waiting or 1)
110
+ if chunk:
111
+ self._buffer.extend(chunk)
112
+ return self.text
113
+
114
+ @property
115
+ def text(self) -> str:
116
+ """What arrived after the port went quiet, which is what a capture counts."""
117
+ return self._buffer.decode("utf-8", errors="replace")
118
+
119
+ @property
120
+ def buffered(self) -> str:
121
+ """What the probe handed over when the port opened, from before the capture."""
122
+ return self._buffered.decode("utf-8", errors="replace")
123
+
124
+
125
+ # There was a one-shot capture() here. capture_console used it, and an unplug
126
+ # mid-capture escaped it as a SerialException with everything already read lost.
127
+ # capture_console now drives ConsoleCapture itself, as run_firmware does, so it
128
+ # keeps what arrived, and nothing else called this.