Skip to main content
Glama
stm32-stlink-mcp

stm32-stlink-mcp

by phryniszak

stm32-stlink-mcp

STM32 마이크로컨트롤러를 ST-LINK를 통해 디버깅하기 위한 MCP 서버이며, STMicroelectronics 자체 STM32CubeCLT 툴셋 — ST-LINK_gdbserver, STM32_Programmer_CLI, arm-none-eabi-gdb (GDB/MI2로 구동됨) — 으로 제작되었습니다. OpenOCD, J-Link 또는 probe-rs는 사용하지 않습니다.

아키텍처

디버그 세션은 ST가 문서화한 워크플로(UM2576, "STM32CubeIDE ST-LINK GDB server")를 그대로 반영하는 한 쌍의 자식 프로세스입니다:

 arm-none-eabi-gdb  --interpreter=mi2  --(TCP, target extended-remote)-->  ST-LINK_gdbserver  --(USB)-->  ST-LINK  --(SWD)-->  STM32

arm-none-eabi-gdb는 MI2 모드로 구동되므로, 서버가 GDB Remote Serial Protocol을 직접 구현하는 대신 소스 수준 스텝, 심볼릭 브레이크포인트, 심볼 인식 표현식 평가를 자동으로 얻습니다. ST-LINK_gdbserver는 세션이 살아 있는 동안 프로브에 대한 USB 핸들을 소유합니다. gdb의 load(MI: -target-download)를 통한 플래싱은 서버가 STM32CubeProgrammer에 투명하게 위임하므로, 다시 플래시하기 위해 세션을 종료할 필요가 없습니다. 독립 실행형 원샷 플래시(flash_standalone, 세션 불필요)는 STM32_Programmer_CLI를 직접 호출하며, 따라서 같은 프로브에 이미 열려 있는 세션과 충돌합니다. 자세한 내용은 도구 설명을 참조하세요.

Related MCP server: dbgprobe-mcp-server

설치

npm install
npm run build

STM32CubeCLT가 설치되어 있고 bin/ 디렉터리에 접근 가능해야 합니다. 이미 PATH에 있거나(CLT 설치 프로그램이 기본적으로 이렇게 설정) 또는 STMCP_CUBECLT_PATH 및 개별 도구 재정의를 통해 접근할 수 있습니다. 확인하려면 npm run doctor를 실행하세요.

실행

node dist/index.js serve     # starts the MCP server on stdio (default mode)
node dist/index.js doctor    # pre-flight check: tool resolution, connected probes, udev rules
node dist/index.js doctor --json

MCP 클라이언트에 등록

{
  "mcpServers": {
    "stm32-stlink": {
      "command": "node",
      "args": ["<path-to-this-repo>/stmcp/dist/index.js"]
    }
  }
}

구성(환경 변수)

변수

기본값

용도

STMCP_GDBSERVER_PATH / STMCP_PROGRAMMER_CLI_PATH / STMCP_PE_GDB_PATH

—

바이너리별 재정의(가장 높은 우선순위)

STMCP_CUBECLT_PATH

—

CubeCLT 설치 루트; 하위 경로는 STM32CubeCLT_metadata.sh -j로 결정

STMCP_STLINK_SERIAL

—

기본 프로브 시리얼(하나만 연결되어 있으면 생략 가능. 생략하면 자동 선택)

STMCP_DEFAULT_DEVICE

STM32G431CBTx

기본 MCU 장치 문자열

STMCP_DEFAULT_INTERFACE

swd

swd 또는 jtag

STMCP_DEFAULT_FREQUENCY_KHZ

4000

SWD/JTAG 클럭

STMCP_MAX_SESSIONS

1

동시 디버그 세션 상한

STMCP_GDBSERVER_READY_TIMEOUT_MS

8000

"Waiting for debugger connection..." 메시지를 기다리는 시간

STMCP_LOG_LEVEL

info

로그 레벨 — error | warn | info | debug

STMCP_LOG_FILE

—

선택적 로그 파일 (어떤 경우에도 stderr는 사용됨 — stdout은 MCP 프레이밍 전용)

STMCP_ALLOW_FLASH_ERASE

false

소거 경로를 활성화

STMCP_ALLOW_MEMORY_WRITE

true

memory_write를 활성화

STMCP_ALLOW_FLASH_ADDRESS_WRITE

false

memory_write가 플래시 주소 창을 대상으로 할 수 있도록 허용 (기본적으로 차단됨 — 대신 플래시 도구를 사용)

STMCP_ALLOWED_FILE_PATHS

(무제한)

ELF/bin 파일 인자에 대한 쉼표로 구분된 허용 루트 목록

STMCP_MAX_FILE_SIZE_BYTES

16777216

파일 인자 허용 최대 크기

STMCP_FLASH_RANGE_START / STMCP_FLASH_RANGE_END

0x08000000 / 0x08020000

쓰기 보호를 위한 플래시 주소 창 (기본: 128KB, STM32G431CB)

도구

도메인

도구

용도

Probe

list_probes

연결된 ST-LINK 프로브 목록 반환

Session

debug_connect

gdbserver+gdb 실행, ELF 심볼 파일 로드, 연결

Session

debug_disconnect

정리된 세션 종료

Session

debug_session_status

세션 정보(하나 또는 전체)

Flash

flash_standalone

세션이 필요 없는 STM32_Programmer_CLI를 이용한 원샷 플래시

Flash

flash_load_in_session

열린 세션의 gdb load 명령을 통한 재플래시

Execution

debug_run

재개/계속

Execution

debug_halt

인터럽트

Execution

debug_reset

리셋 (monitor reset [halt])

Execution

debug_step

스텝 오버/인투/아웃

Breakpoints

breakpoint_set / breakpoint_clear / breakpoint_list

파일:줄, 심볼, 또는 *addr 주소 기준

Memory

memory_read / memory_write

원시 메모리 액세스(쓰기는 보호됨)

Registers

register_read / register_write

이름이 지정된 코어 레지스터 읽기/쓰기

Registers

read_fault_registers

Cortex-M SCB fault register 덤프 한 번 호출(CFSR/HFSR/... 디코딩)

Expressions

evaluate_expression

gdb MI를 통한 인지형 표현식 평가

v2로 미루어짐

SVD 주변기기 레지스터 도구(memory_read/memory_write + evaluate_expression은 이미 주소를 통해 모든 것에 접근 가능), 실시간/스트리밍 메모리 폴링, 플러그인 시스템, 칩별 메모리 영역 허용 목록, gdb monitor 임의 패스스루, 그리고 옵션 바이트/RDP 도구(Board-Blocking 기능으로 의도적으로 제외)를 포함합니다.

RTT

RTT(SEGGER Real Time Transfer — 실시간으로 언홀팅 콘솔/버블 변수 추적)는 의도적으로 이 서버에 구현하지 않았습니다. ST-LINK_gdbserver의 GDB/MI 콘솔에는 non-stop 모드가 없어서, 이 서버의 debug_connect 세션을 통해 메모리를 읽으려면 먼저 코어를 멈춰야 합니다. 이는 RTT의 목적을 무력화합니다. 올바른 메커니즘은 코어를 절대로 멈추지 않는 직접 AP 메모리 액세스입니다(STM32CubeMonitor 소스가 정확히 이렇게 동작하는 것을 확인했고, STM32_Programmer_CLI의 -r32fast 도 마찬가지입니다).

바로 이 일을 strtt가 이미 하고 있고, strtt-mcp가 이를 자체 MCP 서버(strtt_start/strtt_stop/strtt_status/strtt_read/strtt_write)로 감쌉니다. 이 서버를 통과하는 것이 아니라 옆에 나란히 등록하세요:

{
  "mcpServers": {
    "stm32-stlink": { "command": "node", "args": ["<...>/mcp-server/dist/index.js"] },
    "strtt": {
      "command": "node",
      "args": ["<path-to-strtt-repo>/mcp/dist/index.js"],
      "env": { "STRTT_BIN": "<path-to-strtt-binary>" }
    }
  }
}

tcp: true를 설정하여 strtt_start를 시작하면 USB 장치를 직접 점유하는 대신 공용 ST-LINK Server를 통해 연결됩니다. 이렇게 하면 이 서버의 열린 debug_connect 세션과 동시에 실행할 수 있습니다. GdbServerProcess는 항상 ST-LINK_gdbserver에 -t/--shared를 전달하기 때문입니다. tcp: true가 아닌 경우 strtt와 열린 디버그 세션이 동일한 프로브를 두고 경쟁하게 됩니다.

하드웨어 검증 런북

ST-LINK 및 타깃이 연결된 상태에서:

node dist/index.js doctor                     # confirm probe + tools resolve
npx @modelcontextprotocol/inspector node dist/index.js   # interactive tool testing

그런 다음 Inspector 도구나 MCP 클라이언트로:

  1. list_probes → 프로브의 시리얼이 보입니다.

  2. debug_connect { file, device, serial } → sessionId를 반환합니다.

  3. breakpoint_set { sessionId, location: "main" } → 브레이크포인트 번호를 반환합니다.

  4. debug_run { sessionId } → reason: "breakpoint-hit"로 일시정지 합니다.

  5. register_read { sessionId, registers: ["pc","sp","lr","r0"] } 를 호출합니다.

  6. evaluate_expression { sessionId, expression: "<a known global>" } 를 호출합니다.

  7. read_fault_registers { sessionId } → 리셋 직후 무해/제로 플래그를 확인합니다.

  8. debug_disconnect { sessionId } → 고립된 프로세스가 없는지 확인: ps aux | grep -E 'ST-LINK_gdbserver|arm-none-eabi-gdb'.

  9. 세션이 열려 있지 않은 상태에서 flash_standalone { file, reset: "hard", run: true }를 호출합니다.

  10. 부정 테스트: 세션을 열어 둔 채 같은 시리얼에서에 flash_standalone을 호출 → DEVICE_BUSY가 예상됩니다.

참고: debug_connect는 타깃의 CPU를 일시정지 시킵니다. 예상치 않게 CPU가 멈추는 것이 안전하지 않은 방식으로 액추에이터·출력을 활발히 구동 중인 보드에 연결해서는 안 됩니다. 먼저 그러한 사용이 가능한지 확인하기 전에는 그렇게 하지 마세요.

Available Tools

19 tools
breakpoint_clearClear a breakpointA

Deletes a previously set breakpoint by its number.

Inputs: sessionId (required), breakpointNumber (required).

breakpoint_listList breakpointsA

Lists breakpoints currently tracked on a session (those set via breakpoint_set).

Inputs: sessionId (required).

breakpoint_setSet a breakpointB

Sets a breakpoint by file:line (e.g. main.c:42), symbol name (e.g. main), or address (e.g. *0x08000200).

Inputs: location (required), sessionId (required), condition, temporary.

debug_connectConnect a debug sessionA

Starts a debug session: spawns ST-LINK_gdbserver and arm-none-eabi-gdb (MI2), loads ELF symbols, and connects via target extended-remote.

Inputs: elfPath (required), apId, device, serial, +3 more.

debug_disconnectDisconnect a debug sessionA

Cleanly tears down a debug session's gdb and ST-LINK_gdbserver child processes.

Inputs: sessionId (required).

debug_haltHalt executionB

Interrupts the running target.

Inputs: sessionId (required).

debug_resetReset the targetA

Resets the target via ST-LINK_gdbserver's monitor reset command, optionally resuming afterward.

Inputs: sessionId (required), halt.

debug_runResume executionA

Resumes (continues) the target and waits for it to stop again (e.g. a breakpoint), up to a timeout.

Inputs: sessionId (required), waitForStopMs.

debug_session_statusDebug session statusA

Reports the status of one debug session (by id), or lists all active sessions if id is omitted.

Inputs: sessionId.

debug_stepSingle-stepB

Steps the target: 'over' (next line, step over calls), 'into' (step into calls), or 'out' (finish the current function).

Inputs: sessionId (required), mode, waitForStopMs.

evaluate_expressionEvaluate an expressionB

Symbol-aware expression evaluation in the current frame via gdb's -data-evaluate-expression — reads globals/locals by name, struct/array member access, pointer dereference, arithmetic, etc.

Inputs: sessionId (required), expression (required).

flash_load_in_sessionReflash firmware within a debug sessionA

Reflashes the currently loaded ELF via gdb's load (MI: -target-download) inside an already-open debug session. No USB conflict — ST-LINK_gdbserver retains ownership of the probe throughout.

Inputs: sessionId (required), runToMain, resetAfter.

flash_standaloneFlash firmware (standalone)A

One-shot flash via STM32_Programmer_CLI — no debug session required. Fails with DEVICE_BUSY if a debug session is already open on the same probe (it holds exclusive USB access); disconnect first, or use flash_load_in_session instead.

Inputs: file (required), run, reset, serial, +3 more.

list_probesList ST-LINK probesA

Lists connected ST-LINK probes via STM32_Programmer_CLI. Returns an empty list (not an error) if none are attached.

Inputs: no named parameters.

memory_readRead memoryA

Reads raw bytes from target memory at an address or symbol-address expression (e.g. '&my_global').

Inputs: length (required), address (required), sessionId (required).

memory_writeWrite memoryA

Writes raw bytes to target RAM/registers at an address. Blocked for addresses inside the flash window (use flash_standalone / flash_load_in_session for flash) unless STMCP_ALLOW_FLASH_ADDRESS_WRITE is set.

Inputs: address (required), bytesHex (required), sessionId (required).

read_fault_registersRead Cortex-M fault registersA

One-call dump of Cortex-M SCB fault registers (CFSR/HFSR/MMFAR/BFAR/SHCSR/CPUID/ICSR) plus PC/SP/LR, with CFSR/HFSR bits decoded to flag names. Raw evidence only — no root-cause interpretation.

Inputs: sessionId (required).

register_readRead core registersA

Reads named core registers (default: all general-purpose + sp/lr/pc/xpsr) via gdb MI.

Inputs: sessionId (required), registers.

register_writeWrite a core registerB

Writes a value to a named core register via gdb's -gdb-set $<register>=<value>.

Inputs: value (required), register (required), sessionId (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 19 tools

    Disambiguation5/5

    Each tool targets a distinct action: session lifecycle, run control, breakpoints, register/memory access, and flashing are clearly separated. The only similar pair, flash_standalone and flash_load_in_session, is explicitly differentiated by requiring or not requiring an active debug session.

    Naming Consistency4/5

    All tool names are lowercase snake_case and mostly follow a predictable domain-prefixed verb pattern such as breakpoint_set, memory_read, and debug_run. Minor exceptions like debug_session_status and flash_standalone break the strict verb_noun pattern but remain easy to anticipate.

    Tool Count4/5

    19 tools is on the heavier side, but the embedded debug workflow legitimately spans session management, execution control, breakpoints, register/memory inspection, fault diagnosis, and flashing. Each tool has a justifiable role, so the count feels slightly over ideal rather than bloated.

    Completeness4/5

    The toolset covers the full core debug loop: connect/disconnect, run/halt/reset/step, breakpoint management, register and memory access, expression evaluation, fault register dumps, and both standalone and in-session flashing. Missing conveniences like stack backtraces or watchpoints are minor gaps, not workflow-breaking omissions.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Stateful MCP server for driving debug probes (J-Link) to flash, debug, and inspect embedded targets. Enables AI agents to perform flash, memory, breakpoint, and ELF/SVD-aware operations conversationally.
      41
      23 PyPI
      11
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      MCP server for embedded debugging based on probe-rs, providing 22 tools for ARM Cortex-M and RISC-V microcontrollers, including connection, memory operations, breakpoints, flash programming, and RTT communication.
      2
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that provides comprehensive debugging capabilities for J-Link debuggers, enabling memory, flash, register, and RTT operations through AI assistants.
      43
      MIT