Skip to main content
Glama
ZMC1011

Keil5 MCP Server

by ZMC1011

Keil5 MCP Server

Python License: MIT MCP PyPI PRs Welcome

한국어 | 中文

Keil MDK를 사용한 STM32 개발을 위해 deepseek harness에게 코드 편집 → 플래시 → 디버그 → 피드백 읽기 → 코드 수정의 폐루프를 제공하는 Model Context Protocol (MCP) 서버입니다.

IDE, 프로그래머, 터미널을 수동으로 전환하는 대신, 에이전트는 다음을 수행할 수 있습니다:

  1. Keil 프로젝트를 빌드하고 실시간 컴파일 진행 상황을 확인

  2. UV4 로그에서 구조화된 오류를 획득 (파일 / 줄 / 열 / 코드 / 메시지)

  3. 오류 코드를 원인 및 제안된 수정 사항과 함께 설명

  4. 소스 파일을 안전하게 편집 (모든 편집은 자동 백업됨)

  5. 공식 UV4 채널 또는 pyOCD를 통해 펌웨어 플래시

  6. pyOCD를 통해 하드웨어 디버깅: 브레이크포인트, 단계 실행, 레지스터, 메모리, RTT 로그

  7. 공식 Keil 디버그 채널 실행 (UV4 -d + .ini 스크립트)


목차


Related MCP server: stm32-mcp

기능

  • 27개 MCP 도구mcp__<serverName>__<tool> 형식으로 등록됨 (예: mcp__keil__build_project)

  • 실시간 빌드 진행 상황: 백분율 / 현재 파일 / 단계를 표시하는 tail 기반 모니터로 링크 완료까지 95%에서 상한 설정

  • 구조화된 UV4 로그 파싱: 컴파일 오류 (main.c(25:1): error C2065: ...), 링크 오류 (L6218E), Program Size, 빌드 시간

  • 오류 코드 지식 베이스: 일반적인 armcc/armclang 코드(C2065, L6218E, L6406E, ...)에 대한 내장 설명 및 수정 방법

  • 안전한 소스 편집: 모든 편집 전 자동 .keil-mcp-backups/ 백업, 줄 범위 교체, 정규식 검색

  • 공식 플래시 경로: UV4 -f는 프로젝트에 설정된 플래시 알고리즘을 사용하고, pyOCD 폴백은 .axf 파일을 직접 허용

  • 하드웨어 디버깅: pyOCD 프로브 제어 (연결 / 중지 / 재개 / 스텝 / 브레이크포인트 / 레지스터 / 메모리 / RTT)

  • 프로브 임대: 프로브별 독점 액세스 (asyncio lock + file lock) 로 UV4와 pyOCD가 디버그 포트를 두고 충돌하지 않도록 함

  • 실행 경계: 읽기 전용 도구는 동시에 실행, 변경 도구는 세션 잠금으로 직렬화, asyncio.shield로 취소 안전

  • Keil 미설치 상태에서도 동작: keil_doctor가 누락된 구성 요소를 명확히 보고하며 서버는 계속 시작됨

요구 사항

구성 요소

버전 / 참고 사항

Python

3.10+ (3.12에서 테스트됨)

Keil MDK

UV4.exe (빌드 -b, 플래시 -f, 디버그 -dp) — 선택 사항이지만 빌드/플래시 도구에 필요

pyOCD

pip를 통해 자동 설치; 프로브 드라이버(ST-Link / J-Link / CMSIS-DAP) 필요

프로브

ST-Link V2/V3, J-Link, CMSIS-DAP, Keil ULINKplus

타깃 팩

예: pyocd pack install stm32f103c8 또는 Keil DFP 재정렬

설치

PyPI에서

python -m venv .venv
.venv/Scripts/activate        # Windows
# source .venv/bin/activate   # Linux / macOS
pip install keil-mcp-server

패키지는 PyPI 배포 준비 완료(pyproject.toml + LICENSE + server.json 포함). 아직 게시되지 않은 경우 아래 소스 설치를 사용하세요.

소스에서 (GitHub)

git clone https://github.com/ZMC1011/dsh-keil-mcp.git
cd ds-keil-mcp
python -m venv .venv
.venv/Scripts/activate                       # Windows
# source .venv/bin/activate                  # Linux / macOS
pip install -e ".[dev]"

설치 확인

# Environment self-check (UV4.exe, pyocd, connected probes)
python -m keil_mcp_server --check

# List all registered tools
python -m keil_mcp_server --tools

# Run the unit tests
pytest tests -q

빠른 시작

# 1. Start the MCP server (stdio transport — the MCP client will spawn this)
python -m keil_mcp_server

# 2. In your MCP client, call e.g.:
#    keil_doctor
#    discover_keil_projects { directory: "D:/STM32Projects" }
#    configure_keil_project { project: "D:/STM32Projects/app/app.uvprojx" }
#    build_project { project: "...", target: "Target 1", stream_progress: true }
#    flash_firmware { project: "...", confirm: true }

MCP 클라이언트 구성

DeepSeek Harness (DSH)

공식 DSH MCP 문서에 따르면: 플러그인 인스턴스 하나 = MCP 서버 하나이며, 공식 브릿지 플러그인 @deepseek-ai/dsh-mcp-client를 통해 연결됩니다. 프로필의 cordis.patch.yml(또는 cordis.yml)에 다음을 추가하세요:

- insert:
    - id: mcp-keil
      name: '@deepseek-ai/dsh-mcp-client'
      config:
        serverName: keil                 # tools appear as mcp__keil__build_project etc.
        transport: stdio
        command: D:/000_Environment/mcp-servers/ds-keil-mcp/.venv/Scripts/python.exe
        args: ['-m', 'keil_mcp_server']
        env:
          KEIL_UV4_PATH: D:/002_software/Keil5/UV4/UV4.exe
          KEIL_PROJECT_DIR: D:/STM32Projects
        # optional: toolCallTimeoutMs: 60000, failOnStartupError: false

다음으로 확인:

dsh web --dump-config | grep -A3 mcp
# or check session logs for mcp__keil__* calls

참고: serverName은 [A-Za-z0-9_-]{1,32}와 일치해야 하며 실행 중인 인스턴스 간에 고유해야 합니다.

Claude Desktop / 기타 stdio MCP 클라이언트

대부분의 MCP 클라이언트는 mcpServers JSON 규약을 사용합니다:

{
  "mcpServers": {
    "keil": {
      "command": "D:/000_Environment/mcp-servers/ds-keil-mcp/.venv/Scripts/python.exe",
      "args": ["-m", "keil_mcp_server"],
      "env": {
        "KEIL_UV4_PATH": "D:/002_software/Keil5/UV4/UV4.exe",
        "KEIL_PROJECT_DIR": "D:/STM32Projects"
      }
    }
  }
}

venv 없이 소스 체크아웃한 경우 uv로도 사용할 수 있습니다:

{
  "mcpServers": {
    "keil": {
      "command": "uv",
      "args": ["--directory", "D:/path/to/ds-keil-mcp", "run", "keil_mcp_server"]
    }
  }
}

도구

27개 도구 모두 구조화된 JSON을 반환합니다. 파괴적인 작업(플래시 / 지우기)은 confirm=True가 필요합니다.

빌드 & 오류

도구

설명

주요 매개변수 → 결과

build_project

UV4 -b로 컴파일(또는 -r 재빌드 / -c 정리), 실시간 진행

project, target?, timeout_seconds?, stream_progress?, clean?, rebuild?{status, returncode, build_log, errors[], summary, progress?}

build_progress_status

진행 중인 빌드 진행률 조회

build_id{status, percent, current_file, phase}

build_cancel

빌드 취소 요청

build_id{success}

parse_build_errors

UV4 로그를 구조화된 오류로 파싱

log_path? 또는 log_content?{errors[], warnings[], summary}

explain_build_error

오류 코드 → 설명 + 원인 + 수정 방법

error_code, message?, file?, line?{explanation, common_causes[], suggested_fixes[]}

소스 편집

도구

설명

주요 매개변수 → 결과

source_read

줄 번호가 있는 소스 읽기

file, start_line?, end_line?{content, total_lines, ...}

source_edit

줄 범위 교체; 사전 자동 백업

file, start_line, end_line, new_content{success, lines_changed, backup_path}

source_search

소스 파일 검색(텍스트 또는 정규식)

pattern, path?, files?, regex?{matches[]}

공식 디버그 채널

도구

설명

주요 매개변수 → 결과

uv4_debug_session

UV4 -d + 생성된 .ini 디버그 스크립트 실행(무인 브레이크/동작/스텝)

project, target?, ini_path?, breakpoint?, dump_vars?, timeout_seconds?{success, returncode, output}

uv4_debug_dde

세션 출력을 ID로 읽기

session_id{output}

프로젝트 & 환경

도구

설명

주요 매개변수 → 결과

keil_doctor

환경 확인: UV4.exe, pyocd, 팩, 연결된 프로브

— → {uv4_exists, pyocd_installed, probes[], status}

discover_keil_projects

디렉페커리 아래 *.uvprojx 찾기

directory?, recursive?{projects[]}

configure_keil_project

프로젝트 파싱: 타깃, 디바이스, 팩, 그룹, 소스

project, target?{targets[], device, pack_id, source_files[]}

플래시

도구

설명

주요 매개변수 → 결과

flash_firmware

UV4 -f(우선) 또는 pyOCD 플래시

project?, image?, backend?, probe_id?, confirm{success, log}

erase_flash

칩 플래시 지우기 (pyOCD erase -c)

confirm, probe_id?, chip?{success, output}

verify_flash

이미지와 칩 대조로 확인 (pyOCD verify)

image, probe_id?{success, output}

프로브 디버깅

도구

설명

probe_connect / probe_disconnect

PyOCD 프로브 연결 / 해제 (disconnect는 UV4 -f 포트를 해제함)

probe_halt / probe_resume / probe_step

코어 제어

set_breakpoint / continue_target

주소 또는 심볼의 브레이크포인트 설정, 재개

probe_read_registers

r0–r15, sp, lr, pc, xpsr 읽기

probe_read_memory

주소의 메모리 읽기 (hex 바이트)

read_rtt_log

현재 실행된 경우 SEGGER RTT 출력 읽기 (있으면)

아키텍처

┌──────────────────────────────────────────────────────────────┐
│  MCP Client (DeepSeek Harness / Claude Desktop / ...)        │
│  → tools registered as mcp__keil__*                          │
└──────────────────────────────┬───────────────────────────────┘
                               │ stdio (JSON-RPC 2.0)
┌──────────────────────────────▼───────────────────────────────┐
│  keil-mcp-server (Python, FastMCP)                           │
│                                                              │
│  server.py   — tool registration + Execution Boundary        │
│                (read-only whitelist → concurrent;            │
│                 mutating tools → session lock +              │
│                 asyncio.to_thread + asyncio.shield)          │
│                                                              │
│  tools/      — MCP tool layer (27 tools)                     │
│                                                              │
│  core/       — deliverable layer                             │
│    uv4_runner.py      UV4 -b/-r/-c/-f/-d process runner      │
│    build_progress.py  realtime log tail monitor              │
│    error_parser.py    UV4 log → structured errors + KB       │
│    source_editor.py   read/edit/search + auto-backup         │
│    uv4_debug.py       UV4 -d + .ini script engine            │
│    probe_lease.py     per-probe exclusive lease              │
│    project_utils.py   .uvprojx parser (namespace-tolerant)   │
│                                                              │
│  models.py / config.py / config.yaml                         │
└───────────────┬──────────────────────────────┬───────────────┘
                │                              │
      ┌─────────▼─────────┐          ┌─────────▼─────────┐
      │ Keil MDK (UV4.exe)│          │ pyOCD + probe     │
      │ build/flash/debug │          │ ST-Link/J-Link/   │
      │                   │          │ CMSIS-DAP → chip  │
      └───────────────────┘          └───────────────────┘

의존성 방향: MCP 레이어 → 도구 → 코어 → Keil MDK / pyOCD → 타깃 칩.

주요 설계 포인트:

  • 실행 경계 (McuBuddy에서 영감을 받음): 읽기 전용 도구는 동시에 실행되고, 다른 모든 작업은 세션별 asyncio.Lock으로 직렬화되며, 워커 스레드(asyncio.to_thread)에서 실행되고 취소로부터 보호됩니다(asyncio.shield).

  • 프로브 임대 (Probe lease): UV4 -f와 pyOCD는 디버그 포트를 공유할 수 없습니다. ProbeLease(asyncio lock + filelock)가 접근을 직렬화하며, 플래시 플로우는 UV4가 인계받기 전에 pyOCD를 분리합니다.

  • 실시간 진행률: 데몬 스레드가 UV4 로그의 끝부분을 tail하면서, .uvprojx에서 파싱한 소스 파일 수대비 compiling 줄을 카운트하며, Build Time Elapsed 마커가 나타날 때까지 백분율을 95%로 제한합니다.

  • XML 형식 오류 허용: 구형 Keil 프로젝트에는 태그가 맞지 않는 경우가 있습니다(예: <b><b> ... </b> 태그). 프로젝트 파서가 파싱 전에 이를 수리합니다.

설정

config.yaml(번들 제공) + 환경 변수 재정의:

keil:
  uv4_path: "C:/Keil_v5/UV4/UV4.exe"        # or env KEIL_UV4_PATH
  default_project_dir: ""                   # or env KEIL_PROJECT_DIR
build:
  build_timeout: 300
  stream_progress: true
  tail_flush_wait: 3        # seconds to wait for UV4 log tail flush after exit
error:
  max_errors: 200
source:
  backup_dir: ".keil-mcp-backups"
probe_lease:
  lock_dir: ".keil-mcp-locks"
server:
  transport: "stdio"
  log_level: "INFO"

엔드투엔드 워크플로우 예시

일반적인 에이전트 세션(도구 이름은 DSH 접두사 mcp__keil__로 표시):

1. mcp__keil__keil_doctor                       # environment + probe OK?
2. mcp__keil__discover_keil_projects            # find .uvprojx files
3. mcp__keil__configure_keil_project            # parse targets/device/sources
4. mcp__keil__build_project (stream_progress)   # compile; on failure:
5. mcp__keil__parse_build_errors                # structured errors[]
6. mcp__keil__explain_build_error               # causes + fixes
7. mcp__keil__source_edit                       # fix code (auto-backup)
   → back to 4 until 0 errors
8. mcp__keil__flash_firmware (confirm=true)     # UV4 -f → "Verify OK"
9. mcp__keil__probe_connect + set_breakpoint    # attach debugger
10. mcp__keil__probe_read_registers / _memory   # observe chip state
11. mcp__keil__read_rtt_log                     # firmware logs
    → if logic bug found: source_edit → rebuild → reflash

안전 규칙

단계

작업

기본값

읽기 전용

칩 매칭, 레지스터/메모리/심볼 읽기, 로그

확인 불필요

실행

정지 / 재개 / 스텝 / 리셋

확인 요청

상태 쓰기

메모리/레지스터 쓰기, 중단점, 감시점

확인

영구적인 파괴 작업

플래시 소거 / 프로그래밍

명시적 확인 + 복구 계획

호스트 프로세스

Keil 빌드, GDB 서버

확인 요청

Principles: 실행하기 전에 증거를 확보한다; 대상 칩을 먼저 식별한다; 플래시 전에 다시확인한 target / scope / image / recovery.

테스트

pytest tests -q        # 11 unit tests: log parsing, source editing, progress, project parsing

수동 스모크 테스트(tests/ 디렉터리):

python tests/raw_handshake.py    # bare JSON-RPC initialize + tools/list over stdio
python tests/func_test.py        # end-to-end tool calls through the MCP client SDK

문제 해결

증상

원인 / 조치

Target DLL is not found – flash시

플래시를 시작하기 전에 probe_disconnect(또는 프로브 임대 처리)를 호출한다.

UV4.exe not found

구성 파일의 KEIL_UV4_PATHkeil.uv4_path를 설정하고, keil_doctor로 확인.

No module named keil_mcp_server

가상환경의 editable 설치가 낡은 경로를 가리킴. 현재 소스에서 다시 pip install -e . 실행.

No target connected

프로브 배선 / 드라이버 점검, keil_doctor가 감지 가능한 프로브 목록을 표시.

pyocd pack install 필요

예를 들어 pyocd pack install stm32f103c8 실행하거나 Keil DFP 폴더를 지정.

로드맵

  • PyPI에 배포하고 MCP 레지스트리에 등록

  • MCUBUDDY_TOOLSETS 스타일 도메인 토글

  • 이름 기반 set_breakpoint 용 ELF 심볼 해석

  • RTOS 태스크 인지 (FreeRTOS)

  • 단위 테스트용 GitHub Actions CI

  • Linux/macOS 지원 참고 사항(Keil은 Windows에서만, pyOCD는 크로스 플랫폼)

기여

기여는 환영합니다! 변경 사항을 먼저 이슈로 하고, 이어서 PR 줄 것.

License

MIT — 출처를 표시하면 자유롭게 이용·변경·재배포 할 수 있습니다.

A
license - permissive license
Not graded
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    A
    quality
    B
    maintenance
    Enables AI assistants to interact with STM32 development boards via J-Link debugger using RTT communication, supporting connection, logging, memory operations, and firmware flashing through natural language.
    12
    1
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables Claude Code to build, flash, and communicate with STM32 hardware over SWD and serial, including multi-board management, live memory monitoring, and hardware sequences.
    21
    MIT
  • F
    license
    A
    quality
    C
    maintenance
    Enables AI assistants to flash firmware, program memory, modify option bytes, erase chips, reset boards, and capture SWO printf traces for STM32 microcontrollers via STM32CubeCLT.
    12

View all related MCP servers

Related MCP Connectors

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ZMC1011/dsh-keil-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server