multitool-mcp 0.2.0__tar.gz → 0.3.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.
Files changed (22) hide show
  1. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/PKG-INFO +4 -3
  2. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/README.md +3 -2
  3. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/pyproject.toml +1 -1
  4. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/dut_mcp/device.py +31 -25
  5. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/dut_mcp/server.py +22 -5
  6. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/dut_mcp/websocket.py +19 -6
  7. multitool_mcp-0.3.0/src/dut_mcp/wire.py +126 -0
  8. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/multitool_mcp.egg-info/PKG-INFO +4 -3
  9. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/multitool_mcp.egg-info/SOURCES.txt +4 -1
  10. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/tests/test_debug.py +1 -2
  11. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/tests/test_dut_mcp.py +26 -16
  12. multitool_mcp-0.3.0/tests/test_session_busy.py +27 -0
  13. multitool_mcp-0.3.0/tests/test_spi_binary.py +69 -0
  14. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/LICENSE +0 -0
  15. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/setup.cfg +0 -0
  16. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/dut_mcp/__init__.py +0 -0
  17. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/dut_mcp/__main__.py +0 -0
  18. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/dut_mcp/debug.py +0 -0
  19. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/multitool_mcp.egg-info/dependency_links.txt +0 -0
  20. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/multitool_mcp.egg-info/entry_points.txt +0 -0
  21. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/multitool_mcp.egg-info/requires.txt +0 -0
  22. {multitool_mcp-0.2.0 → multitool_mcp-0.3.0}/src/multitool_mcp.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multitool-mcp
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: MCP server for debugging devices under test through WE Multitool
5
5
  Author: Wise Electronics
6
6
  License-Expression: GPL-3.0-or-later
@@ -25,7 +25,7 @@ Dynamic: license-file
25
25
 
26
26
  `multitool-mcp` is a dependency-free [Model Context Protocol](https://modelcontextprotocol.io/) server for inspecting and debugging a device under test (DUT) through a Wise Electronics WE Multitool.
27
27
 
28
- It runs over standard input/output and bridges the Multitool's JSON-over-WebSocket API. It exposes bounded MCP tools for GPIO, I2C, SPI, UART, PWM, GPIO ownership, SWD debugging, and SWO trace. SWD/SWO tools manage a host OpenOCD process connected to the Multitool CMSIS-DAP TCP probe.
28
+ It accepts MCP JSON-RPC over standard input/output and connects to the Multitool over binary WebSocket. It exposes bounded MCP tools for GPIO, I2C, SPI, UART, PWM, GPIO ownership, SWD debugging, and SWO trace. SWD/SWO tools manage a host OpenOCD process connected to the Multitool CMSIS-DAP TCP probe.
29
29
 
30
30
  ## Requirements
31
31
 
@@ -82,7 +82,8 @@ Read `pins_get` before configuring pins, and verify wiring, voltage, bus role, a
82
82
  - Commands are serialized because firmware responses do not carry request IDs.
83
83
  - UART data received while another command awaits a response is buffered.
84
84
  - The `gpio_set` firmware command has no acknowledgement; `gpio_write` reports it as dispatched but unverified.
85
- - The firmware tracks one active WebSocket response socket. Do not use the browser UI and MCP bridge concurrently.
85
+ - The device firmware must support the binary WebSocket protocol. It reserves one exclusive control session. A second browser or MCP connection receives HTTP 409 (`session_busy`). Abrupt network loss may delay ownership release until the device detects disconnect.
86
+ - `spi_transfer` accepts up to 8192 bytes in either direction and 8224 bytes combined. UART bytes travel as raw binary on the device connection.
86
87
 
87
88
  ## SWD and SWO
88
89
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  `multitool-mcp` is a dependency-free [Model Context Protocol](https://modelcontextprotocol.io/) server for inspecting and debugging a device under test (DUT) through a Wise Electronics WE Multitool.
4
4
 
5
- It runs over standard input/output and bridges the Multitool's JSON-over-WebSocket API. It exposes bounded MCP tools for GPIO, I2C, SPI, UART, PWM, GPIO ownership, SWD debugging, and SWO trace. SWD/SWO tools manage a host OpenOCD process connected to the Multitool CMSIS-DAP TCP probe.
5
+ It accepts MCP JSON-RPC over standard input/output and connects to the Multitool over binary WebSocket. It exposes bounded MCP tools for GPIO, I2C, SPI, UART, PWM, GPIO ownership, SWD debugging, and SWO trace. SWD/SWO tools manage a host OpenOCD process connected to the Multitool CMSIS-DAP TCP probe.
6
6
 
7
7
  ## Requirements
8
8
 
@@ -59,7 +59,8 @@ Read `pins_get` before configuring pins, and verify wiring, voltage, bus role, a
59
59
  - Commands are serialized because firmware responses do not carry request IDs.
60
60
  - UART data received while another command awaits a response is buffered.
61
61
  - The `gpio_set` firmware command has no acknowledgement; `gpio_write` reports it as dispatched but unverified.
62
- - The firmware tracks one active WebSocket response socket. Do not use the browser UI and MCP bridge concurrently.
62
+ - The device firmware must support the binary WebSocket protocol. It reserves one exclusive control session. A second browser or MCP connection receives HTTP 409 (`session_busy`). Abrupt network loss may delay ownership release until the device detects disconnect.
63
+ - `spi_transfer` accepts up to 8192 bytes in either direction and 8224 bytes combined. UART bytes travel as raw binary on the device connection.
63
64
 
64
65
  ## SWD and SWO
65
66
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "multitool-mcp"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "MCP server for debugging devices under test through WE Multitool"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,9 +1,7 @@
1
- """Client for the JSON-over-WebSocket protocol implemented by WE Multitool."""
1
+ """Client for the binary WebSocket protocol implemented by WE Multitool."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import base64
6
- import json
7
5
  import socket
8
6
  import threading
9
7
  import time
@@ -12,6 +10,7 @@ from collections.abc import Callable
12
10
  from typing import Any
13
11
 
14
12
  from .websocket import WebSocket, WebSocketError
13
+ from .wire import SPI, VERSION, decode, encode
15
14
 
16
15
 
17
16
  class DeviceError(RuntimeError):
@@ -23,7 +22,7 @@ Matcher = Callable[[Message], bool]
23
22
 
24
23
 
25
24
  class DeviceClient:
26
- """Serializes commands because the firmware protocol has no request IDs."""
25
+ """Keeps command exchanges ordered because firmware messages have no request IDs."""
27
26
 
28
27
  def __init__(self, url: str, timeout: float = 5.0, transport: WebSocket | None = None) -> None:
29
28
  self.url, self.timeout = url, timeout
@@ -43,7 +42,7 @@ class DeviceClient:
43
42
  def request(self, command: Message, matcher: Matcher, timeout: float | None = None) -> Message:
44
43
  with self._lock:
45
44
  try:
46
- self._ws.send_text(json.dumps(command, separators=(",", ":")))
45
+ self._ws.send_binary(encode(command))
47
46
  deadline = time.monotonic() + (self.timeout if timeout is None else timeout)
48
47
  while True:
49
48
  remaining = deadline - time.monotonic()
@@ -53,16 +52,33 @@ class DeviceClient:
53
52
  if matcher(message):
54
53
  return message
55
54
  self._pending.append(message)
56
- except (OSError, socket.timeout, WebSocketError) as exc:
57
- self._ws.close()
55
+ except (OSError, WebSocketError, DeviceError, ValueError) as exc:
56
+ self.close()
58
57
  raise DeviceError(f"Device communication failed: {exc}") from exc
59
58
 
60
59
  def send(self, command: Message) -> None:
61
60
  with self._lock:
62
61
  try:
63
- self._ws.send_text(json.dumps(command, separators=(",", ":")))
64
- except (OSError, socket.timeout, WebSocketError) as exc:
65
- self._ws.close()
62
+ self._ws.send_binary(encode(command))
63
+ except (OSError, WebSocketError, ValueError) as exc:
64
+ self.close()
65
+ raise DeviceError(f"Device communication failed: {exc}") from exc
66
+
67
+ def request_spi(self, payload: bytes) -> bytes:
68
+ with self._lock:
69
+ try:
70
+ self._ws.send_binary(payload)
71
+ deadline = time.monotonic() + self.timeout
72
+ while True:
73
+ remaining = deadline - time.monotonic()
74
+ if remaining <= 0:
75
+ raise DeviceError("Timed out waiting for a binary device reply")
76
+ message = self._ws.receive_binary(remaining)
77
+ if message.startswith(bytes((VERSION, SPI))):
78
+ return message
79
+ self._pending.append(decode(message))
80
+ except (OSError, WebSocketError, DeviceError, ValueError) as exc:
81
+ self.close()
66
82
  raise DeviceError(f"Device communication failed: {exc}") from exc
67
83
 
68
84
  def read_uart(self, timeout: float, max_bytes: int) -> bytes:
@@ -80,27 +96,17 @@ class DeviceClient:
80
96
  message = self._receive(remaining)
81
97
  except socket.timeout:
82
98
  break
83
- except (OSError, WebSocketError) as exc:
84
- self._ws.close()
99
+ except (OSError, WebSocketError, ValueError) as exc:
100
+ self.close()
85
101
  raise DeviceError(f"Device communication failed: {exc}") from exc
86
102
  if not self._is_uart_data(message):
87
103
  self._pending.append(message)
88
104
  continue
89
- try:
90
- output.extend(base64.b64decode(message["data"], validate=True))
91
- except (ValueError, TypeError) as exc:
92
- raise DeviceError("Device returned invalid base64 UART data") from exc
105
+ output.extend(message["data"])
93
106
  return bytes(output[:max_bytes])
94
107
 
95
108
  def _receive(self, timeout: float) -> Message:
96
- raw = self._ws.receive_text(timeout)
97
- try:
98
- message = json.loads(raw)
99
- except json.JSONDecodeError as exc:
100
- raise DeviceError(f"Device returned invalid JSON: {raw[:200]}") from exc
101
- if not isinstance(message, dict):
102
- raise DeviceError("Device response is not a JSON object")
103
- return message
109
+ return decode(self._ws.receive_binary(timeout))
104
110
 
105
111
  def _take_pending(self, matcher: Matcher) -> Message | None:
106
112
  for index, message in enumerate(self._pending):
@@ -111,4 +117,4 @@ class DeviceClient:
111
117
 
112
118
  @staticmethod
113
119
  def _is_uart_data(message: Message) -> bool:
114
- return message.get("type") == "uart_response" and "error" not in message
120
+ return message.get("type") == "uart_response" and message.get("event") == "rx" and isinstance(message.get("data"), bytes)
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import base64
6
6
  import json
7
7
  import os
8
+ import struct
8
9
  import sys
9
10
  import traceback
10
11
  from dataclasses import dataclass
@@ -95,7 +96,7 @@ class DutTools:
95
96
  Tool("i2c_read", "Read bytes from a register on the configured I2C bus.", _object_schema({"address": {"type": "integer", "minimum": 1, "maximum": 127}, "register": BYTE, "length": {"type": "integer", "minimum": 1, "maximum": 128}}, ["address", "register", "length"]), self.i2c_read, True),
96
97
  Tool("i2c_write", "Write bytes to a register on the configured I2C bus.", _object_schema({"address": {"type": "integer", "minimum": 1, "maximum": 127}, "register": BYTE, "data": BYTES}, ["address", "register", "data"]), self.i2c_write),
97
98
  Tool("spi_configure", "Configure WE Multitool as an SPI master.", _object_schema({"cs_pin": PIN, "sck_pin": PIN, "mosi_pin": PIN, "miso_pin": PIN, "frequency_hz": {"type": "integer", "minimum": 1000}, "mode": {"type": "integer", "minimum": 0, "maximum": 3}}, ["cs_pin", "sck_pin", "mosi_pin", "miso_pin", "frequency_hz", "mode"]), self.spi_configure, False, True),
98
- Tool("spi_transfer", "Write bytes and optionally read bytes in one SPI master transaction.", _object_schema({"write_data": BYTES, "read_length": {"type": "integer", "minimum": 0, "maximum": 1024}}, ["write_data", "read_length"]), self.spi_transfer),
99
+ Tool("spi_transfer", "Write bytes and optionally read bytes in one SPI master transaction. Up to 8192 bytes each way, with 8224 bytes total.", _object_schema({"write_data": {**BYTES, "maxItems": 8192}, "read_length": {"type": "integer", "minimum": 0, "maximum": 8192}}, ["write_data", "read_length"]), self.spi_transfer),
99
100
  Tool("uart_configure", "Configure UART2 pins and framing. Use -1 for unused CTS/RTS pins.", _object_schema({"tx_pin": PIN, "rx_pin": PIN, "baudrate": {"type": "integer", "minimum": 300, "maximum": 5000000}, "data_bits": {"type": "integer", "enum": [5, 6, 7, 8]}, "parity": {"type": "string", "enum": ["none", "even", "odd"]}, "stop_bits": {"type": "number", "enum": [1, 1.5, 2]}, "flow_control": {"type": "string", "enum": ["none", "rts", "cts", "cts_rts"]}, "cts_pin": OPTIONAL_PIN, "rts_pin": OPTIONAL_PIN}, ["tx_pin", "rx_pin"]), self.uart_configure, False, True),
100
101
  Tool("uart_write", "Send text, base64, or byte-array data to the configured DUT UART.", _object_schema({"text": {"type": "string"}, "base64_data": {"type": "string"}, "bytes": BYTES}), self.uart_write),
101
102
  Tool("uart_read", "Collect buffered UART bytes from the DUT for a bounded time.", _object_schema({"timeout_ms": {"type": "integer", "minimum": 0, "maximum": 30000}, "max_bytes": {"type": "integer", "minimum": 1, "maximum": 10240}}), self.uart_read, True),
@@ -172,7 +173,23 @@ class DutTools:
172
173
  return self._command({"type": "spi_setup", "mode": "Master", "conn_mode": args["mode"] + 1, "cs": args["cs_pin"], "sck": args["sck_pin"], "mosi": args["mosi_pin"], "miso": args["miso_pin"], "freq": args["frequency_hz"]}, "spi_response")
173
174
 
174
175
  def spi_transfer(self, args: JsonObject) -> JsonObject:
175
- return self._command({"type": "spi_write", "word_length": 8, "data": args["write_data"], "data_read": args["read_length"]}, "spi_response")
176
+ tx, read_length = args["write_data"], args["read_length"]
177
+ total = len(tx) + read_length
178
+ if not total:
179
+ raise DeviceError("Supply bytes to write or a read length.")
180
+ if total > 8224:
181
+ raise DeviceError("SPI write and read lengths together must be at most 8224 bytes.")
182
+ request = struct.pack("<BBHH", 1, 1, len(tx), read_length) + bytes(tx)
183
+ reply = self.client.request_spi(request)
184
+ if len(reply) < 8:
185
+ raise DeviceError("Incomplete binary SPI reply")
186
+ version, operation, length, status = struct.unpack_from("<BBHI", reply)
187
+ if (version, operation) != (1, 1) or len(reply) != 8 + length or length != (0 if status else read_length):
188
+ raise DeviceError("Invalid binary SPI reply")
189
+ if status:
190
+ raise DeviceError(f"SPI transfer failed (ESP-IDF status 0x{status:X})")
191
+ return {"type": "spi_response", "event": "transfer", "error": False,
192
+ "result_type": 2 if length else 1, "data": list(reply[8:]) if length else tx}
176
193
 
177
194
  def uart_configure(self, args: JsonObject) -> JsonObject:
178
195
  command = {
@@ -191,14 +208,14 @@ class DutTools:
191
208
  if len(choices) != 1:
192
209
  raise DeviceError("Provide exactly one of text, base64_data, or bytes")
193
210
  if choices[0] == "text":
194
- data: Any = args["text"]
211
+ data = args["text"].encode("utf-8")
195
212
  elif choices[0] == "base64_data":
196
213
  try:
197
- data = list(base64.b64decode(args["base64_data"], validate=True))
214
+ data = base64.b64decode(args["base64_data"], validate=True)
198
215
  except (ValueError, TypeError) as exc:
199
216
  raise DeviceError("base64_data is not valid base64") from exc
200
217
  else:
201
- data = args["bytes"]
218
+ data = bytes(args["bytes"])
202
219
  response = self.client.request({"type": "uart_write", "data": data}, lambda message: message.get("type") == "uart_response" and "error" in message)
203
220
  return self._check_error(response)
204
221
 
@@ -10,6 +10,8 @@ import ssl
10
10
  import struct
11
11
  from urllib.parse import urlsplit
12
12
 
13
+ from .wire import MAX_PACKET
14
+
13
15
 
14
16
  class WebSocketError(RuntimeError):
15
17
  pass
@@ -49,6 +51,11 @@ class WebSocket:
49
51
  raw.sendall(request.encode("ascii"))
50
52
  response = self._receive_headers(raw)
51
53
  status = response.split("\r\n", 1)[0]
54
+ if " 409 " in status:
55
+ raise WebSocketError(
56
+ "Device control session is busy (HTTP 409). Close the other browser tab "
57
+ "or MCP connection, then retry."
58
+ )
52
59
  if " 101 " not in status:
53
60
  raise WebSocketError(f"WebSocket upgrade failed: {status}")
54
61
  headers = {}
@@ -75,11 +82,11 @@ class WebSocket:
75
82
  finally:
76
83
  sock.close()
77
84
 
78
- def send_text(self, text: str) -> None:
85
+ def send_binary(self, data: bytes) -> None:
79
86
  self.connect()
80
- self._send_frame(0x1, text.encode("utf-8"))
87
+ self._send_frame(0x2, data)
81
88
 
82
- def receive_text(self, timeout: float | None = None) -> str:
89
+ def receive_binary(self, timeout: float | None = None) -> bytes:
83
90
  if self._socket is None:
84
91
  raise WebSocketError("WebSocket is not connected")
85
92
  previous_timeout = self._socket.gettimeout()
@@ -87,6 +94,7 @@ class WebSocket:
87
94
  self._socket.settimeout(timeout)
88
95
  try:
89
96
  fragments = bytearray()
97
+ started = False
90
98
  while True:
91
99
  final, opcode, payload = self._receive_frame()
92
100
  if opcode == 0x8:
@@ -97,11 +105,14 @@ class WebSocket:
97
105
  continue
98
106
  if opcode == 0xA:
99
107
  continue
100
- if opcode not in {0x0, 0x1}:
101
- raise WebSocketError(f"Unsupported WebSocket opcode: {opcode}")
108
+ if opcode != (0x0 if started else 0x2):
109
+ raise WebSocketError(f"Unexpected WebSocket opcode: {opcode}")
110
+ started = True
111
+ if len(fragments) + len(payload) > MAX_PACKET:
112
+ raise WebSocketError("Device WebSocket message exceeds the size limit")
102
113
  fragments.extend(payload)
103
114
  if final:
104
- return fragments.decode("utf-8")
115
+ return bytes(fragments)
105
116
  finally:
106
117
  if self._socket is not None:
107
118
  self._socket.settimeout(previous_timeout)
@@ -126,6 +137,8 @@ class WebSocket:
126
137
  length = struct.unpack("!H", self._read_exact(2))[0]
127
138
  elif length == 127:
128
139
  length = struct.unpack("!Q", self._read_exact(8))[0]
140
+ if length > MAX_PACKET:
141
+ raise WebSocketError("Device WebSocket frame exceeds the size limit")
129
142
  mask = self._read_exact(4) if masked else b""
130
143
  payload = self._read_exact(length)
131
144
  if masked:
@@ -0,0 +1,126 @@
1
+ """Versioned CBOR messages carried in binary WE Multitool WebSocket frames."""
2
+
3
+ import math
4
+ import struct
5
+
6
+ VERSION = 1
7
+ MESSAGE = 0
8
+ SPI = 1
9
+ UART_RX = 2
10
+ MAX_PACKET = 16384
11
+ MAX_DEPTH = 12
12
+ MAX_INT = (1 << 53) - 1
13
+
14
+
15
+ def encode(message: dict) -> bytes:
16
+ packet = bytearray((VERSION, MESSAGE))
17
+
18
+ def head(major: int, value: int) -> None:
19
+ if value < 24:
20
+ packet.append((major << 5) | value)
21
+ return
22
+ width = 1 if value <= 0xff else 2 if value <= 0xffff else 4 if value <= 0xffffffff else 8
23
+ packet.append((major << 5) | (23 + width.bit_length()))
24
+ packet.extend(value.to_bytes(width, "big"))
25
+
26
+ def write(value, depth: int) -> None:
27
+ if depth > MAX_DEPTH:
28
+ raise ValueError("Device message is nested too deeply")
29
+ if value is None or isinstance(value, bool):
30
+ packet.append(0xf6 if value is None else 0xf5 if value else 0xf4)
31
+ elif type(value) is int and abs(value) <= MAX_INT:
32
+ head(0 if value >= 0 else 1, value if value >= 0 else -1 - value)
33
+ elif type(value) is float and math.isfinite(value):
34
+ packet.extend(b"\xfb" + struct.pack(">d", value))
35
+ elif isinstance(value, str):
36
+ if "\0" in value:
37
+ raise ValueError("Use byte strings for data containing NUL")
38
+ data = value.encode("utf-8")
39
+ head(3, len(data))
40
+ packet.extend(data)
41
+ elif isinstance(value, bytes):
42
+ head(2, len(value))
43
+ packet.extend(value)
44
+ elif isinstance(value, list):
45
+ if value and all(type(byte) is int and 0 <= byte <= 255 for byte in value):
46
+ write(bytes(value), depth)
47
+ else:
48
+ head(4, len(value))
49
+ for item in value:
50
+ write(item, depth + 1)
51
+ elif isinstance(value, dict):
52
+ head(5, len(value))
53
+ for key, item in value.items():
54
+ if not isinstance(key, str):
55
+ raise ValueError("Device messages require text keys")
56
+ write(key, depth + 1)
57
+ write(item, depth + 1)
58
+ else:
59
+ raise ValueError("Unsupported device message value")
60
+ if len(packet) > MAX_PACKET:
61
+ raise ValueError("Device message is too large")
62
+
63
+ write(message, 0)
64
+ return bytes(packet)
65
+
66
+
67
+ def decode(packet: bytes) -> dict:
68
+ if len(packet) < 2 or len(packet) > MAX_PACKET or packet[0] != VERSION:
69
+ raise ValueError("Invalid device packet header")
70
+ if packet[1] == UART_RX:
71
+ return {"type": "uart_response", "event": "rx", "data": packet[2:]}
72
+ if packet[1] != MESSAGE:
73
+ raise ValueError("Unexpected device packet type")
74
+ offset = 2
75
+
76
+ def take(length: int) -> bytes:
77
+ nonlocal offset
78
+ if length > len(packet) - offset:
79
+ raise ValueError("Truncated device message")
80
+ data = packet[offset:offset + length]
81
+ offset += length
82
+ return data
83
+
84
+ def read(depth: int):
85
+ if depth > MAX_DEPTH:
86
+ raise ValueError("Device message is nested too deeply")
87
+ tag = take(1)[0]
88
+ major, info = tag >> 5, tag & 31
89
+ if major == 7:
90
+ if info in (20, 21, 22):
91
+ return {20: False, 21: True, 22: None}[info]
92
+ if info == 27:
93
+ value = struct.unpack(">d", take(8))[0]
94
+ if math.isfinite(value):
95
+ return value
96
+ raise ValueError("Unsupported CBOR simple value")
97
+ if info < 24:
98
+ value = info
99
+ elif info <= 27:
100
+ value = int.from_bytes(take(1 << (info - 24)), "big")
101
+ else:
102
+ raise ValueError("Invalid CBOR length")
103
+ if major in (0, 1):
104
+ result = value if major == 0 else -1 - value
105
+ if abs(result) <= MAX_INT:
106
+ return result
107
+ elif major == 2:
108
+ return list(take(value))
109
+ elif major == 3:
110
+ return take(value).decode("utf-8")
111
+ elif major == 4 and value <= len(packet) - offset:
112
+ return [read(depth + 1) for _ in range(value)]
113
+ elif major == 5 and value * 2 <= len(packet) - offset:
114
+ result = {}
115
+ for _ in range(value):
116
+ key = read(depth + 1)
117
+ if not isinstance(key, str) or key in result:
118
+ raise ValueError("Invalid CBOR map key")
119
+ result[key] = read(depth + 1)
120
+ return result
121
+ raise ValueError("Unsupported or malformed CBOR item")
122
+
123
+ result = read(0)
124
+ if not isinstance(result, dict) or offset != len(packet):
125
+ raise ValueError("Device response must contain one CBOR map")
126
+ return result
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multitool-mcp
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: MCP server for debugging devices under test through WE Multitool
5
5
  Author: Wise Electronics
6
6
  License-Expression: GPL-3.0-or-later
@@ -25,7 +25,7 @@ Dynamic: license-file
25
25
 
26
26
  `multitool-mcp` is a dependency-free [Model Context Protocol](https://modelcontextprotocol.io/) server for inspecting and debugging a device under test (DUT) through a Wise Electronics WE Multitool.
27
27
 
28
- It runs over standard input/output and bridges the Multitool's JSON-over-WebSocket API. It exposes bounded MCP tools for GPIO, I2C, SPI, UART, PWM, GPIO ownership, SWD debugging, and SWO trace. SWD/SWO tools manage a host OpenOCD process connected to the Multitool CMSIS-DAP TCP probe.
28
+ It accepts MCP JSON-RPC over standard input/output and connects to the Multitool over binary WebSocket. It exposes bounded MCP tools for GPIO, I2C, SPI, UART, PWM, GPIO ownership, SWD debugging, and SWO trace. SWD/SWO tools manage a host OpenOCD process connected to the Multitool CMSIS-DAP TCP probe.
29
29
 
30
30
  ## Requirements
31
31
 
@@ -82,7 +82,8 @@ Read `pins_get` before configuring pins, and verify wiring, voltage, bus role, a
82
82
  - Commands are serialized because firmware responses do not carry request IDs.
83
83
  - UART data received while another command awaits a response is buffered.
84
84
  - The `gpio_set` firmware command has no acknowledgement; `gpio_write` reports it as dispatched but unverified.
85
- - The firmware tracks one active WebSocket response socket. Do not use the browser UI and MCP bridge concurrently.
85
+ - The device firmware must support the binary WebSocket protocol. It reserves one exclusive control session. A second browser or MCP connection receives HTTP 409 (`session_busy`). Abrupt network loss may delay ownership release until the device detects disconnect.
86
+ - `spi_transfer` accepts up to 8192 bytes in either direction and 8224 bytes combined. UART bytes travel as raw binary on the device connection.
86
87
 
87
88
  ## SWD and SWO
88
89
 
@@ -7,6 +7,7 @@ src/dut_mcp/debug.py
7
7
  src/dut_mcp/device.py
8
8
  src/dut_mcp/server.py
9
9
  src/dut_mcp/websocket.py
10
+ src/dut_mcp/wire.py
10
11
  src/multitool_mcp.egg-info/PKG-INFO
11
12
  src/multitool_mcp.egg-info/SOURCES.txt
12
13
  src/multitool_mcp.egg-info/dependency_links.txt
@@ -14,4 +15,6 @@ src/multitool_mcp.egg-info/entry_points.txt
14
15
  src/multitool_mcp.egg-info/requires.txt
15
16
  src/multitool_mcp.egg-info/top_level.txt
16
17
  tests/test_debug.py
17
- tests/test_dut_mcp.py
18
+ tests/test_dut_mcp.py
19
+ tests/test_session_busy.py
20
+ tests/test_spi_binary.py
@@ -1,4 +1,3 @@
1
- import base64
2
1
  import json
3
2
  import socket
4
3
  import subprocess
@@ -18,7 +17,7 @@ def call(server, name, **args):
18
17
  def test_probe_matches_event_and_preserves_uart_data():
19
18
  server, transport = make_server([
20
19
  {'type': 'swd_status', 'event': 'status', 'enabled': False},
21
- {'type': 'uart_response', 'data': base64.b64encode(b'log').decode()},
20
+ b'\x01\x02log',
22
21
  {'type': 'swd_status', 'event': 'enable', 'error': False, 'enabled': True, 'swo': 17},
23
22
  ])
24
23
  result = call(server, 'swd_enable', swclk_pin=8, swdio_pin=3, nreset_pin=18, swo_pin=17)
@@ -1,10 +1,11 @@
1
- import base64
2
- import json
3
1
  import socket
4
2
 
3
+ import pytest
4
+
5
5
  from dut_mcp.device import DeviceClient
6
6
  from dut_mcp.server import DutTools, McpServer
7
- from dut_mcp.websocket import WebSocket
7
+ from dut_mcp.websocket import WebSocket, WebSocketError
8
+ from dut_mcp.wire import decode, encode
8
9
 
9
10
 
10
11
  class FakeTransport:
@@ -19,14 +20,15 @@ class FakeTransport:
19
20
  def close(self):
20
21
  self.connected = False
21
22
 
22
- def send_text(self, text):
23
+ def send_binary(self, packet):
23
24
  self.connected = True
24
- self.sent.append(json.loads(text))
25
+ self.sent.append(decode(packet))
25
26
 
26
- def receive_text(self, timeout=None):
27
+ def receive_binary(self, timeout=None):
27
28
  if not self.responses:
28
29
  raise socket.timeout()
29
- return json.dumps(self.responses.pop(0))
30
+ reply = self.responses.pop(0)
31
+ return reply if isinstance(reply, bytes) else encode(reply)
30
32
 
31
33
 
32
34
  class FakeSocket:
@@ -70,7 +72,7 @@ def test_initialize_and_tool_annotations():
70
72
 
71
73
  def test_i2c_read_translates_wire_contract():
72
74
  server, transport = make_server([
73
- {"type": "uart_response", "data": base64.b64encode(b"boot").decode()},
75
+ b"\x01\x02boot",
74
76
  {"type": "i2c_response", "result_type": 2, "addr": 0x48, "data": [1, 2]},
75
77
  ])
76
78
  response = server.handle({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "i2c_read", "arguments": {"address": 0x48, "register": 1, "length": 2}}})
@@ -79,12 +81,13 @@ def test_i2c_read_translates_wire_contract():
79
81
 
80
82
 
81
83
  def test_uart_rx_is_buffered_while_waiting_for_ack():
82
- server, _ = make_server([
83
- {"type": "uart_response", "data": base64.b64encode(b"hello").decode()},
84
+ server, transport = make_server([
85
+ b"\x01\x02hello",
84
86
  {"type": "uart_response", "data": "Data has been sent", "error": False},
85
87
  ])
86
- write = server.handle({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "uart_write", "arguments": {"text": "AT\r\n"}}})
88
+ write = server.handle({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "uart_write", "arguments": {"text": "AT\0\r\n"}}})
87
89
  assert write["result"].get("isError") is not True
90
+ assert transport.sent == [{"type": "uart_write", "data": [65, 84, 0, 13, 10]}]
88
91
  read = server.handle({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "uart_read", "arguments": {"timeout_ms": 0, "max_bytes": 20}}})
89
92
  assert read["result"]["structuredContent"]["text_utf8"] == "hello"
90
93
 
@@ -123,18 +126,25 @@ def test_arguments_are_validated_before_device_access():
123
126
  assert transport.sent == []
124
127
 
125
128
 
126
- def test_websocket_decodes_server_text_frame():
129
+ def test_websocket_decodes_server_binary_frame():
130
+ websocket = WebSocket("ws://test/ws")
131
+ websocket._socket = FakeSocket(b"\x82\x05hello")
132
+ assert websocket.receive_binary() == b"hello"
133
+
134
+
135
+ def test_websocket_rejects_text_frames():
127
136
  websocket = WebSocket("ws://test/ws")
128
137
  websocket._socket = FakeSocket(b"\x81\x05hello")
129
- assert websocket.receive_text() == "hello"
138
+ with pytest.raises(WebSocketError):
139
+ websocket.receive_binary()
130
140
 
131
141
 
132
- def test_websocket_masks_client_text_frame():
142
+ def test_websocket_masks_client_binary_frame():
133
143
  websocket = WebSocket("ws://test/ws")
134
144
  sock = FakeSocket()
135
145
  websocket._socket = sock
136
- websocket.send_text("hello")
137
- assert sock.outgoing[0] == 0x81
146
+ websocket.send_binary(b"hello")
147
+ assert sock.outgoing[0] == 0x82
138
148
  assert sock.outgoing[1] & 0x80
139
149
  length = sock.outgoing[1] & 0x7F
140
150
  mask = sock.outgoing[2:6]
@@ -0,0 +1,27 @@
1
+ from unittest.mock import Mock, patch
2
+
3
+ import pytest
4
+
5
+ from dut_mcp.websocket import WebSocket, WebSocketError
6
+
7
+
8
+ def test_busy_handshake_is_actionable_and_closes_socket():
9
+ sock = Mock()
10
+ ws = WebSocket('ws://device/ws')
11
+ with patch('dut_mcp.websocket.socket.create_connection', return_value=sock), \
12
+ patch.object(WebSocket, '_receive_headers', return_value='HTTP/1.1 409 Conflict\r\n\r\n'):
13
+ with pytest.raises(WebSocketError, match='Close the other browser tab'):
14
+ ws.connect()
15
+ sock.close.assert_called_once()
16
+ assert not ws.connected
17
+
18
+
19
+ def test_other_upgrade_failures_preserve_status():
20
+ sock = Mock()
21
+ ws = WebSocket('ws://device/ws')
22
+ with patch('dut_mcp.websocket.socket.create_connection', return_value=sock), \
23
+ patch.object(WebSocket, '_receive_headers', return_value='HTTP/1.1 503 Unavailable\r\n\r\n'):
24
+ with pytest.raises(WebSocketError, match='503 Unavailable'):
25
+ ws.connect()
26
+ sock.close.assert_called_once()
27
+ assert not ws.connected
@@ -0,0 +1,69 @@
1
+ import struct
2
+ from unittest.mock import Mock
3
+
4
+ import pytest
5
+
6
+ from dut_mcp.device import DeviceClient, DeviceError
7
+ from dut_mcp.server import DutTools
8
+ from dut_mcp.websocket import WebSocket
9
+ from dut_mcp.wire import decode, encode
10
+
11
+ CONFIG = {
12
+ "cs_pin": 7, "sck_pin": 6, "mosi_pin": 5, "miso_pin": 15,
13
+ "frequency_hz": 20_000_000, "mode": 0,
14
+ }
15
+
16
+
17
+ def make_tools():
18
+ socket = Mock(spec=WebSocket, connected=True)
19
+ socket.receive_binary.return_value = encode({"type": "spi_response", "error": False})
20
+ tools = DutTools(DeviceClient("ws://test/ws", transport=socket))
21
+ tools.spi_configure(CONFIG)
22
+ setup = decode(socket.send_binary.call_args.args[0])
23
+ assert setup == {
24
+ "type": "spi_setup", "mode": "Master", "conn_mode": 1, "cs": 7,
25
+ "sck": 6, "mosi": 5, "miso": 15, "freq": 20_000_000,
26
+ }
27
+ socket.send_binary.reset_mock()
28
+ return tools, socket
29
+
30
+
31
+ def test_spi_uses_binary_and_buffers_interleaved_uart():
32
+ tools, socket = make_tools()
33
+ data = bytes(range(256)) * 32
34
+ socket.receive_binary.side_effect = [
35
+ b"\x01\x02hi",
36
+ struct.pack("<BBHI", 1, 1, len(data), 0) + data,
37
+ ]
38
+ result = tools.spi_transfer({"write_data": [3, 0, 0, 0], "read_length": len(data)})
39
+
40
+ socket.send_binary.assert_called_once_with(b"\x01\x01\x04\x00\x00\x20\x03\x00\x00\x00")
41
+ assert result["data"] == list(data)
42
+ assert tools.client.read_uart(0.1, 2) == b"hi"
43
+
44
+
45
+ def test_spi_binary_write_keeps_the_existing_result_shape():
46
+ tools, socket = make_tools()
47
+ socket.receive_binary.return_value = struct.pack("<BBHI", 1, 1, 0, 0)
48
+ result = tools.spi_transfer({"write_data": [0x06], "read_length": 0})
49
+ socket.send_binary.assert_called_once_with(b"\x01\x01\x01\x00\x00\x00\x06")
50
+ assert result["result_type"] == 1 and result["data"] == [0x06]
51
+
52
+
53
+ def test_cbor_interoperability_vector():
54
+ message = {"t": "x", "b": [0, 255], "n": 1.5}
55
+ packet = bytes.fromhex("01 00 A3 61 74 61 78 61 62 42 00 FF 61 6E FB 3F F8 00 00 00 00 00 00")
56
+ assert encode(message) == packet
57
+ assert decode(packet) == message
58
+ with pytest.raises(ValueError):
59
+ decode(packet[:-1])
60
+ with pytest.raises(ValueError):
61
+ decode(bytes.fromhex("01 00 A2 61 78 01 61 78 02"))
62
+
63
+
64
+ def test_binary_error_does_not_replay_transfer():
65
+ tools, socket = make_tools()
66
+ socket.receive_binary.return_value = struct.pack("<BBHI", 1, 1, 0, 0x103)
67
+ with pytest.raises(DeviceError, match="0x103"):
68
+ tools.spi_transfer({"write_data": [0x06], "read_length": 0})
69
+ socket.send_binary.assert_called_once()
File without changes
File without changes