Skip to main content
Glama
zephyr-ra-mcp

zephyr-ra-mcp

by KaleoLiu
README.md
# zephyr-ra-mcp

Let an AI debug Zephyr firmware on Renesas RA directly, over MCP.

For the architecture, see [ARCHITECTURE.md](ARCHITECTURE.md).

## Where things stand

| Phase | Content | Status |
|---|---|---|
| A | probe connection + read_log | **Verified on real hardware** (log + shell dual buffer both working) |
| B | ELF symbol + read_var / read_mem | **Verified on real hardware** (including send_shell / read_log end to end) |
| C | Named SFR access + fault decoding | **Verified on real hardware** (fault decoding + named SFR, from the SVD) |
| D | halt / breakpoint / watchpoint | **Verified on real hardware** (quotas detected from FP_CTRL/DWT_CTRL, not assumed) |
| E | Stage gating + stuck detection | **Verified on real hardware** (stage 0-6 verifiers, failure paths verified too) |
| F | build / flash closed loop | **Verified on real hardware** (build -> flash -> re-verify, all the way through MCP) |

**Three different RA parts have been brought up**, across both Cortex-M4 and Cortex-M33, and
switching between them needs no line of this server changed. Everything that differs between
parts is asked of the hardware rather than tabulated: the breakpoint and watchpoint quota comes
from `FP_CTRL` / `DWT_CTRL`, the core from `CPUID`, register names and layouts from your SVD,
and the RTT buffer indices from the `.config` next to your ELF.

That portability is a measured claim, not an aspiration -- bringing up the second and third
parts is what turned up the places where the rules had quietly been written around the first
one, and each is written down as a rule rather than a special case. Two examples worth knowing
before you start: an Armv8-M stack overflow reports `STKOF`, a bit that does not exist on
Armv7-M at all, so **decide whether a fault happened from the CFSR value, not from how many
bits you managed to decode** (§8.36); and the same peripheral can sit at a different address on
a different part, which is why nothing is hardcoded. See [PROJECT_PLAN.md](PROJECT_PLAN.md) §8.

**"build -> flash -> observe -> modify with no human in the loop" has been run on real
hardware**: three rounds back to back, zero manual operations, and **what to change each round
is decided by the value observed in the previous round** -- if the observation does not actually
make it back to the host, the loop cannot keep running. It has been run on two different parts,
so the claim does not rest on one setup. See
[tests/demo_closed_loop.py](tests/demo_closed_loop.py) and the acceptance section of
[PROJECT_PLAN.md](PROJECT_PLAN.md).

## Install

```bash
pip install -e .            # core (stage 0-4)
pip install -e ".[svd]"     # plus SFR access (stage 5 onward needs cmsis-svd)
```

`cmsis-svd` is deliberately an extra: usage that only reads logs / variables / call stacks
never touches it. When it is missing, `connect(svd_path=...)` says exactly what is missing and
what to install -- it does not silently lose half the functionality.

Real hardware also needs the [SEGGER J-Link Software and Documentation Pack](https://www.segger.com/downloads/jlink/)
(pylink calls into that package's C library; it is not a pure Python implementation).

After installing you get the `zephyr-ra-mcp` entry point. To hook it into an MCP client such as
Claude Code, use a project-level `.mcp.json` (the paths in the one in this repo are the ones
this checkout was developed on -- change them for yours):

```json
{
  "mcpServers": {
    "zephyr-ra": {
      "command": "C:/path/to/.venv/Scripts/zephyr-ra-mcp.exe",
      "env": { "ZEPHYR_RA_PROJECT": "C:/path/to/your/project" }
    }
  }
}
```

`ZEPHYR_RA_PROJECT` decides where `session.json` (the stage progress) lands; without it, it is
cwd, so it drifts with wherever you started the session. Use forward slashes for paths in JSON
-- backslashes have to be escaped, one mistake fails the parse of the whole config, and the
only symptom is "this server did not show up".

## Tests

```bash
pip install -e ".[test]"
pytest                      # offline, about 1 minute
ZEPHYR_RA_HW=1 pytest       # plus the ones that need a board attached
```

The offline layer covers `LogRing`, `decode_fault`, DTS parsing, build output extraction, tool
registration and gating, plus **DWARF backtrace** -- the last one by replaying a recorded real
fault scene; details in [tests/README.md](tests/README.md).

## Testing without hardware

`MockProbe` lets Phase A-E be developed without a board:

```bash
ZEPHYR_RA_MOCK=1 python -m zephyr_ra_mcp.server
```

Quick check of the core logic:

```bash
python - << 'EOF'
import sys; sys.path.insert(0, "src")
from zephyr_ra_mcp.probe import MockProbe
from zephyr_ra_mcp.svd import decode_fault

p = MockProbe(); p.connect("ANY_DEVICE")   # the mock does not look at the name
p.write_u32(0xE000ED28, (1 << 1) | (1 << 7))  # DACCVIOL + MMARVALID
p.write_u32(0xE000ED34, 4)                     # MMFAR = 4
print(decode_fault(p)["likely_cause"])
EOF
```

## Hooking it into a client

For Claude Code, copy `.mcp.json.example` to `.mcp.json` and edit the paths.
The real file is gitignored on purpose: it holds absolute paths, and a checked-in
one would be wrong on every machine but the author's.

For Claude Desktop:

```json
{
  "mcpServers": {
    "zephyr-ra": {
      "command": "python",
      "args": ["-m", "zephyr_ra_mcp.server"],
      "env": {
        "ZEPHYR_RA_PROJECT": "/path/to/your/zephyr/app",
        "ZEPHYR_RA_MOCK": "0"
      }
    }
  }
}
```

## Configuration needed on the firmware side

```conf
# prj.conf
CONFIG_USE_SEGGER_RTT=y
CONFIG_LOG=y
CONFIG_LOG_BACKEND_RTT=y

# optional: lets the AI query state actively instead of waiting for logs
CONFIG_SHELL=y
CONFIG_SHELL_BACKEND_RTT=y

# optional: stack overflow gives a clear signal instead of a random fault
CONFIG_HW_STACK_PROTECTION=y
CONFIG_THREAD_ANALYZER=y
```

Without `CONFIG_USE_SEGGER_RTT`, `connect` will fail to find `_SEGGER_RTT` in the ELF and say so
explicitly (it does not fail silently).

## Six key designs

**The RTT address comes from the ELF, not from scanning.** `pylink.rtt_start()`'s auto-detection
is unreliable on some Cortex-M parts. We have `zephyr.elf`, so just look up the `_SEGGER_RTT`
symbol -- this is the structural advantage of holding the build artifacts, relative to RTT Viewer.

**SFRs are addressed by name, not by address.** `read_sfr("IIC0.ICSR2")` returns decoded
bitfields. Addresses and field definitions come from the SVD and decoding is a table lookup, so
the AI's output is machine-verifiable.

**Logs are broadcast, not fought over.** The background pump is the only place that reads RTT
from hardware, into a ring buffer; each consumer holds its own cursor, and `tail` does not move
the cursor at all. An RTT up-buffer is gone once read -- without this layer, continuous
monitoring and on-demand queries would eat each other's data, and there would be no error at all.

**Stage ordering is enforced through tool availability.** `list_tools()` returns dynamically
based on `session.stage`. Before the GPIO stage passes, the I2C tools do not exist in the tool
list -- the AI cannot skip what it cannot see.

**Variable addresses come from symtab, types from DWARF.** Take the best of each -- most global
variables' DWARF entries are extern declarations only (no address), but the declaration does
carry the type. So signed numbers, floats, enums, pointers, arrays, and structs (bitfields
included) all decode correctly, and `char *` even extracts the string. With no type information
it says plainly that "the value is guessed from the size".

**backtrace walks CFI, it does not scan the stack.** `.debug_frame` is a fact the compiler
produced; follow it and there is nothing to guess. It can cross Cortex-M's exception boundary,
so at a fault scene you see the line that went wrong (measured: `cmd_crash_null @ main.c:27`)
rather than just `z_arm_hard_fault`. When stacking failed (`MSTKERR`) it says "this chain is not
trustworthy" instead of printing it anyway.

## Open items

Only the undecided ones are listed. Decided items, with their reasoning, stay in
[PROJECT_PLAN.md §10](PROJECT_PLAN.md).

### Before this is published: the history, not the tree

Licensed under MIT ([LICENSE](LICENSE)). The tree is clean, but **the git history
is not**: commits before the clean-up still carry personal paths and hardware
product names, and every commit carries the author's e-mail. Publish from a fresh
history (or rewrite it) -- pushing this one as-is undoes the clean-up below.

What has been dealt with in the tree:

| | |
|---|---|
| Vendor SVD (~5 MB, redistribution terms unconfirmed) | never tracked; `svd/*.svd` is gitignored and [PROJECT_PLAN.md §12](PROJECT_PLAN.md) says how to obtain it |
| Board names, part numbers, probe serials, personal paths | no tracked file carries one; the machine-specific settings live in `tests/local_config.json` and `.mcp.json`, both gitignored with `.example` files beside them |
| Hardware verification | all three boards run; two re-verified against the current tree, see the table below |

The repository also has **no git remote** -- every commit exists on one disk.

## Verification status

| | hardware | unwind fixtures replayed offline | measured |
|---|---|---|---|
| Target A (Cortex-M4) | 87 passed / 3 skipped / 0 failed | 4 scenes, strict | 2026-09-03 |
| Target B (Cortex-M33) | 76 passed / 14 skipped / 0 failed | -- | 2026-08-31, **not re-run since** |
| Target C (Cortex-M33) | 87 passed / 3 skipped / 0 failed | 5 scenes, strict | 2026-09-04 |

The offline suite itself is **540 passed / 1 skipped** and is not board-specific: the only thing
the attached board changes is which `tests/fixtures/` recordings the specimen ELF selects. That
one skip is the deep-overflow scene, which exists only on Target C, and it says so by name.

Target C's closed loop was re-run the same day: three rounds of build -> flash -> observe ->
modify with no manual step, 46 s total (15 s a round), each round's seed derived from the
checksum the previous round was observed to produce. It restored the source afterwards to a
byte-identical `build_id`, confirmed independently rather than taken from the test's own report.

**Target B is the one gap.** It has not been re-run since `app_ram_symbols()` changed to select
by ELF section; the risk is low (that board's ELF statically offers 39 candidates) but it is not
a measurement, and the row says so instead of inheriting a neighbour's green.

The hardware skips are not passes. Target A's and C's three are `ZEPHYR_RA_DEMO=1` (opt-in,
rewrites app source) and two multi-probe tests that need a second J-Link attached -- environmental,
not coverage holes. Target B's fourteen are `needs_app_symbol()` skips, where that board's
application does not carry the scaffolding the test asks about; PROJECT_PLAN.md §8.44 says what
that leaves unwatched.

TDQS

B3.1/5.0

Scored across 8 tools

Disambiguation4/5

Most tools are clearly distinct: connect/disconnect/reset/read_core_regs cover separate actions, and stage_verify vs stage_override have opposite semantics that descriptions make explicit. The one real ambiguity is `status` vs `stage_status`, which both report stage information; the descriptions differentiate them (connection/halt vs bring-up stages and unlocked tools) but an agent could still hesitate.

Naming Consistency4/5

All names are snake_case, with a coherent `stage_*` prefix grouping for the workflow-gating tools and plain verbs for connection lifecycle tools. The mix of noun-first (stage_status) and verb-first (read_core_regs, connect) patterns is a minor deviation but still predictable and readable.

Tool Count5/5

Eight tools is well within a sensible range for a J-Link/MCU bring-up server, and each tool maps to a distinct step or query in the workflow. Nothing feels padded or thin for the stated scope.

Completeness3/5

The stage-gating lifecycle (connect, verify, override, status, disconnect) is covered, but core debugging operations are missing: no halt/resume despite `status` reporting halt state, no memory or register write, and no way to read the RTT log pump that `disconnect` refers to. These gaps would force an agent to dead-end on common debug tasks.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues