Skip to main content
Glama
stm32-stlink-mcp

stm32-stlink-mcp

by phryniszak

stm32-stlink-mcp

Servidor MCP para depurar microcontroladores STM32 a través de ST-LINK, construido sobre el conjunto de herramientas STM32CubeCLT de STMicroelectronics — ST-LINK_gdbserver, STM32_Programmer_CLI y arm-none-eabi-gdb (controlado mediante GDB/MI2). No se utiliza OpenOCD, J-Link ni probe-rs.

Arquitectura

Una sesión de depuración es un par de procesos hijos, que refleja exactamente el flujo de trabajo documentado por 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 se controla en modo MI2 para que el servidor obtenga paso a paso a nivel de fuente, puntos de interrupción simbólicos y evaluación de expresiones con conocimiento de símbolos de forma gratuita, en lugar de implementar manualmente el Protocolo Serial Remoto de GDB. ST-LINK_gdbserver posee el manejador USB de la sonda durante toda la sesión; el flasheo mediante load de gdb (MI: -target-download) es delegado transparentemente por el servidor a STM32CubeProgrammer, por lo que no se necesita desmontar la sesión para reflashear. Un flasheo independiente de un solo disparo (flash_standalone, sin sesión requerida) invoca directamente a STM32_Programmer_CLI y por lo tanto entra en conflicto con una sesión ya abierta en la misma sonda — consulte la descripción de la herramienta.

Related MCP server: dbgprobe-mcp-server

Instalación

npm install
npm run build

Requiere que STM32CubeCLT esté instalado y que sus directorios bin/ sean accesibles — ya sea en PATH (el instalador de CLT lo hace por defecto) o mediante STMCP_CUBECLT_PATH / anulaciones por herramienta. Ejecute npm run doctor para comprobarlo.

Ejecución

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

Registro con un cliente MCP

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

Configuración (variables de entorno)

Variable

Default

Propósito

STMCP_GDBSERVER_PATH / STMCP_PROGRAMMER_CLI_PATH / STMCP_ARM_GDB_PATH

—

Anulación por binario (prioridad más alta)

STMCP_CUBECLT_PATH

—

Raíz de instalación de CubeCLT; subrutas resueltas mediante STM32CubeCLT_metadata.sh -j

STMCP_STLINK_SERIAL

—

Serial de sonda predeterminado (omitir para auto-seleccionar si hay exactamente una conectada)

STMCP_DEFAULT_DEVICE

STM32G431CBTx

Cadena de dispositivo MCU predeterminada

STMCP_DEFAULT_INTERFACE

swd

swd o jtag

STMCP_DEFAULT_FREQUENCY_KHZ

4000

Reloj SWD/JTAG

STMCP_MAX_SESSIONS

1

Límite de sesiones de depuración concurrentes

STMCP_GDBSERVER_READY_TIMEOUT_MS

8000

Cuánto tiempo esperar por "Waiting for debugger connection..."

STMCP_LOG_LEVEL

info

error | warn | info | debug

STMCP_LOG_FILE

—

Archivo de registro opcional (stderr siempre se usa independientemente — stdout está reservado para el marco MCP)

STMCP_ALLOW_FLASH_ERASE

false

Habilita la ruta de borrado

STMCP_ALLOW_MEMORY_WRITE

true

Habilita memory_write

STMCP_ALLOW_FLASH_ADDRESS_WRITE

false

Permite que memory_write apunte a la ventana de direcciones de flash (normalmente bloqueada — use las herramientas de flash en su lugar)

STMCP_ALLOWED_FILE_PATHS

(sin restricciones)

Raíces de lista blanca separadas por comas para argumentos de archivos ELF/bin

STMCP_MAX_FILE_SIZE_BYTES

16777216

Tamaño máximo para argumentos de archivos

STMCP_FLASH_RANGE_START / STMCP_FLASH_RANGE_END

0x08000000 / 0x08020000

Ventana de direcciones de flash para la protección de escritura (predeterminado: 128KB, STM32G431CB)

Herramientas

Dominio

Herramienta

Propósito

Sonda

list_probes

Listar sondas ST-LINK conectadas

Sesión

debug_connect

Iniciar gdbserver+gdb, cargar símbolos ELF, conectar

Sesión

debug_disconnect

Cierre limpio de sesión

Sesión

debug_session_status

Información de sesión (una o todas)

Flash

flash_standalone

Flasheo de un solo disparo mediante STM32_Programmer_CLI, sin necesidad de sesión

Flash

flash_load_in_session

Reflashear mediante load de gdb dentro de una sesión abierta

Ejecución

debug_run

Reanudar/continuar

Ejecución

debug_halt

Interrumpir

Ejecución

debug_reset

Reiniciar (monitor reset [halt])

Ejecución

debug_step

Paso por encima/dentro/fuera

Puntos de interrupción

breakpoint_set / breakpoint_clear / breakpoint_list

Por archivo:línea, símbolo o *addr

Memoria

memory_read / memory_write

Acceso a memoria cruda (la escritura está protegida)

Registros

register_read / register_write

Registros de núcleo con nombre

Registros

read_fault_registers

Volcado de registros de fallo SCB Cortex-M en una sola llamada (CFSR/HFSR/... decodificados)

Expresiones

evaluate_expression

Evaluación con conocimiento de símbolos mediante gdb MI

Diferido a v2

Herramientas de registros periféricos SVD (memory_read/write + evaluate_expression ya alcanzan todo por dirección), sondeo de memoria en vivo/streaming, un sistema de plugins, listas blancas de regiones de memoria por chip, paso directo arbitrario de monitor de gdb, y herramientas de option-bytes/RDP (capaces de bloquear el dispositivo, intencionalmente fuera de alcance).

RTT

RTT (SEGGER Real Time Transfer — trazado en vivo de consola/variables sin detención) está intencionalmente no implementado en este servidor. El stub GDB/MI de ST-LINK_gdbserver no tiene modo no-stop, por lo que leer memoria a través de la sesión debug_connect de este servidor requiere detener el núcleo primero — lo que contradice el propósito de RTT. El mecanismo correcto es el acceso directo a memoria AP que nunca detiene el núcleo (confirmado al leer el código fuente de STM32CubeMonitor de ST, que usa exactamente esto, y por -r32fast de STM32_Programmer_CLI).

Eso es lo que strtt ya hace, y strtt-mcp lo envuelve como su propio servidor MCP (strtt_start/strtt_stop/strtt_status/strtt_read/strtt_write). Regístrelo junto a este servidor en lugar de a través de él:

{
  "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>" }
    }
  }
}

Inicie strtt_start con tcp: true para conectarse a través del servidor ST-LINK compartido en lugar de reclamar el dispositivo USB directamente — esto permite que se ejecute concurrentemente con una sesión debug_connect abierta aquí, ya que GdbServerProcess siempre pasa -t/--shared a ST-LINK_gdbserver. Sin tcp: true, strtt y una sesión de depuración abierta competirán por la misma sonda.

Manual de verificación de hardware

Con un ST-LINK y un objetivo conectados:

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

Luego, mediante el inspector o un cliente MCP:

  1. list_probes → aparece el serial de la sonda.

  2. debug_connect { elfPath, device, interface: "swd", serial } → devuelve un sessionId.

  3. breakpoint_set { sessionId, location: "main" } → devuelve un número de punto de interrupción.

  4. debug_run { sessionId } → se detiene con 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 } → indicadores benignos/cero justo después del reinicio.

  8. debug_disconnect { sessionId } → confirme que no hay procesos huérfanos: ps aux | grep -E 'ST-LINK_gdbserver|arm-none-eabi-gdb'.

  9. flash_standalone { file, reset: "hard", run: true } sin ninguna sesión abierta.

  10. Prueba negativa: abra una sesión, luego llame a flash_standalone en el mismo serial → espere DEVICE_BUSY.

Nota: debug_connect detiene la CPU del objetivo. No se conecte a una placa que esté manejando activamente actuadores/salidas de manera que una detención no planificada sea insegura, sin antes confirmar que está bien.

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