Skip to main content
Glama
README.md
# Keil Debug MCP (KDM)

MCP server cho AI agent (Claude Code, Devin...) đọc và ghi trạng thái vi điều khiển ARM Cortex-M trong phiên debug **Keil uVision** đang mở, qua giao diện UVSOCK của Keil. Chip vẫn chạy khi đọc và ghi; KDM không tự dừng chip.

Thiết kế đầy đủ: [docs/PLAN.md](docs/PLAN.md). Ghi chú UVSC và số đo trên board thật: [docs/uvsc_api_notes.md](docs/uvsc_api_notes.md).

## Làm được gì

- Đọc biến toàn cục và static, struct, mảng struct (kiểu lấy từ DWARF của `.axf`), thanh ghi lõi, call stack, vùng nhớ, thanh ghi ngoại vi theo SVD.
- `watch`: lấy mẫu nhiều biến tới 20 Hz (gộp biến SRAM gần nhau vào một lần đọc); luật trong `watch.toml`, flight recorder, baseline.
- `diagnose_fault`: giải mã CFSR/HFSR, khung stack lúc lỗi, chỉ ra file:dòng.
- `kdm_status` kiểm `firmware_match`: file `.axf` trên đĩa có khớp firmware trong chip không.
- Mức `write`: `write_var`, `write_memory`, `test_step` (ghi lệnh test, chờ điều kiện, lấy mẫu; tự dừng khẩn khi vi phạm luật hoặc hết giờ) và `estop`.
- Nhật ký bug (`journal`) và log phiên.

## Yêu cầu

- Windows 10/11.
- Keil MDK 5 có `UV4\UVSC64.dll` (đã thử uVision 5.31, ST-Link, STM32F103C8).
- Python 3.11 trở lên, **64-bit** (để nạp `UVSC64.dll`).

Header UVSC (`UVSC_C.h`, `UVSOCK.h`, gói Arm apnt_198) **không** cần khi chạy và không kèm trong repo vì thuộc bản quyền Arm. Chỉ cần khi sửa `src/kdm/backends/uvsc/bindings.py`.

## Cài đặt

```powershell
git clone https://github.com/anhzudeptrai2/keilc-debug-mcp.git
```

```powershell
cd keilc-debug-mcp
```

```powershell
py -3 -m venv .venv
```

```powershell
.\.venv\Scripts\python.exe -m pip install -e ".[test]"
```

Muốn đúng các phiên bản thư viện đã thử: cài `requirements.lock` trước (`pip install -r requirements.lock`) rồi chạy lệnh trên.

## Bật UVSOCK trong Keil

1. **Edit > Configuration > Other > UVSOCK (TCP/IP) Settings**: tick `Enable`, khởi động lại uVision. Nếu Windows Firewall hỏi, không cho truy cập từ mạng.
2. Mở project, nối board, bấm **Start/Stop Debug Session**.

KDM tự đọc số cổng từ cấu hình Keil (`uvsc_port = "auto"`); có thể đặt cố định trong profile. Chi tiết: [docs/uvsc_api_notes.md](docs/uvsc_api_notes.md) mục 8 và 14.

## Gắn vào dự án Keil

```powershell
.\.venv\Scripts\kdm.exe init "C:\path\to\your-keil-project"
```

```powershell
.\.venv\Scripts\kdm.exe doctor --project "C:\path\to\your-keil-project"
```

`init` tạo `.kdm/` (`profile.toml`, `watch.toml`, `journal.md`), `CLAUDE.md` và thêm `.gitignore` cho dự án; không ghi đè file đã có.

| Lệnh | Việc làm |
|---|---|
| `init [thư mục]` | Tạo `.kdm/`, `CLAUDE.md`, thêm `.gitignore`. Không ghi đè file đã có |
| `init --scan <thư mục>` | Tìm mọi `.uvprojx`, hỏi xác nhận rồi init hàng loạt |
| `doctor` | Kiểm tra Python/DLL, Keil, profile, axf, SVD |
| `probe` | Thử kết nối và in `kdm_status` |
| `tail-log` | In sự kiện log mới nhất |
| `serve` | Chạy MCP server qua stdio |

## Dùng với Claude Code

```powershell
claude mcp add --scope user kdm -- "C:\path\to\keilc-debug-mcp\.venv\Scripts\python.exe" -m kdm.server
```

- KDM tìm `.kdm/` từ thư mục làm việc đi lên. Muốn cố định dự án: thêm `--env KDM_PROJECT=C:\path\to\your-keil-project` vào trước tên `kdm` trong lệnh trên, hoặc truyền `project_dir` khi gọi tool.
- Quyền: chép [templates/claude_settings.json](templates/claude_settings.json) vào settings của Claude Code. Tool đọc được cho phép sẵn; tool điều khiển, ghi và `read_periph` (vì có `force`) ở chế độ hỏi.
- Quy trình debug chung: chép [templates/CLAUDE.user.md](templates/CLAUDE.user.md) vào `~/.claude/CLAUDE.md`.

## Dùng với Devin (Devin Desktop)

Chép [templates/devin_mcp_config.json](templates/devin_mcp_config.json) thành `.devin\mcp_config.local.json` trong thư mục mở bằng Devin, sửa hai đường dẫn, rồi kiểm bằng `devin mcp list`. File này chứa đường dẫn trên máy bạn: đừng commit nó vào repo dự án.

## Mức quyền và ghi

Mặc định `level = "read"`. Mức cao hơn do **bạn** bật trong `.kdm/profile.toml` của dự án:

```toml
[safety]
level = "write"                              # read | control | write
write_regions = ["0x20000000-0x20004FFF"]    # chỉ SRAM
write_allow = ["app.cmd", "app.test_cm"]     # hoặc tiền tố "app.*"; rỗng = không hạn chế biến
estop = "app.cmd = 99"                       # lệnh dừng khẩn; biến phải nằm trong write_allow
```

- `control` thêm halt/run/step/reset/breakpoint, `write` thêm các tool ghi. Danh sách tool MCP đổi theo mức quyền.
- Luôn từ chối ghi Flash và option bytes (`0x00000000-0x1FFFFFFF`), ngoại vi (`0x40000000-0x5FFFFFFF`) và vùng hệ thống (`0xE0000000` trở lên), kể cả khi nằm trong `write_regions`.
- KDM không bao giờ tự halt để ghi. Mỗi lần ghi được đọc lại để kiểm (`verified`) và ghi vào log phiên.
- `test_step`: ghi lần lượt các lệnh, chờ `wait_until`, lấy mẫu; vi phạm luật mức error/critical trong `watch.toml` hoặc hết giờ thì gọi `estop`.
- Chưa kiểm uVision ghi một word 32-bit bằng một lần truy cập bus hay nhiều lần. Biến cho agent ghi nên có kiểu không quá 32 bit và firmware phải chịu được việc giá trị đổi bất kỳ lúc nào.

## Trạng thái

| Phần | Trạng thái |
|---|---|
| 27 tool MCP, resource, prompt, đổi danh sách tool theo mức quyền | Chạy qua stdio; đã dùng với Claude Code và Devin Desktop |
| Đọc qua Keil (`backends/uvsc`) | Chạy với uVision 5.31 thật khi chip đang chạy; tự nối lại khi mất kết nối |
| Struct, mảng struct, static | Qua DWARF của `.axf` (`core/dwarf.py`); chưa có biến cục bộ |
| `watch` 20 Hz | Đã đo 60 s trên project thật (mỗi lời gọi UVSC khoảng 30 ms) |
| Ghi: `write_var`, `write_memory`, `test_step`, `estop` | Đã thử trên board STM32F103C8 khi chip đang chạy |
| Fault lab (`firmware/fault_lab`) | Đã chạy trên STM32F103C8: lỗi NULL, Thumb, bus, chia 0, không căn hàng, tràn stack, ISR kẹt, clock tắt đều nhận đúng loại và đúng dòng |
| halt/run/step/reset/breakpoint, `build`, `read_output`, `rtos_tasks` | Có trong giao diện và chip giả; backend Keil chưa làm |
| Chip | Mới thử STM32F103C8 (Cortex-M3); có profile `stm32f1`, `stm32f4`, `generic-cortex-m` |

## Thử không cần Keil

Đặt biến môi trường `KDM_FAKE_BACKEND` trỏ tới file JSON mô tả chip giả (cấu trúc: xem `target_spec` trong [tests/conftest.py](tests/conftest.py) và docstring của `backends/fake.py`). Chỉ dùng để phát triển; dữ liệu không đến từ phần cứng.

## Test

```powershell
.\.venv\Scripts\python.exe -m pytest
```

Test dùng chip giả và DLL giả nên không cần Keil hay board; CI chạy cùng bộ test trên Windows.

## An toàn và riêng tư

- Mọi biểu thức đi qua `safe_expr`; backend chỉ nhận bản in lại đã kiểm.
- Thanh ghi dữ liệu/FIFO bị chặn trên mọi đường đọc, kể cả qua con trỏ, `read_memory`, luật và điều kiện breakpoint.
- KDM không nạp Flash và không ghi ngoại vi.
- Kết quả tool (giá trị biến, đoạn source, đường dẫn) được gửi tới nhà cung cấp mô hình AI. Kiểm tra NDA trước khi dùng cho dự án công ty; tắt đoạn source bằng `[privacy] source_snippets = false`.

## Giấy phép

MIT, xem [LICENSE](LICENSE).

Keil, uVision và UVSC là của Arm Limited. Repo này không kèm phần mềm, DLL hay header của Arm; bạn cần cài Keil MDK với giấy phép của riêng bạn.

TDQS

B3.1/5.0

Scored across 16 tools

Disambiguation4/5

The large family of read_* tools is mostly differentiated by data source (variables, memory blocks, core registers, SVD-decoded peripherals, ITM/serial output, session log), so an agent can pick correctly. Minor overlap remains between read_vars and read_memory, and between watch (time-sampled) and snapshot (instant sample of vars+peripherals+rules), which require reading descriptions carefully to separate.

Naming Consistency3/5

Several conventions coexist: verb_noun (read_output, read_vars, diagnose_fault), bare nouns (baseline, journal, recorder, watch, snapshot), prefixed status (kdm_status), and noun phrases (rtos_tasks, call_stack, read_log). Individual names are readable but there is no single predictable pattern.

Tool Count4/5

16 tools is at the upper end of the comfortable range, but a full embedded-debug workflow legitimately needs status, inspection, tracing, and fault analysis surfaces. Each tool appears to map to a distinct debugging need rather than being filler.

Completeness3/5

Inspection, tracing, and fault analysis are well covered (vars, memory, registers, peripherals, watch, recorder, call stack, diagnose_fault, journal). However, the surface is read-only: there are no execution-control tools (halt/run/step/reset), no breakpoint management, and no variable/memory write, which are core debugger operations an agent will likely need.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues