Keil5 MCP Server
Keil5 MCP Server
한국어 | 中文
Keil MDK를 사용한 STM32 개발을 위해 deepseek harness에게 코드 편집 → 플래시 → 디버그 → 피드백 읽기 → 코드 수정의 폐루프를 제공하는 Model Context Protocol (MCP) 서버입니다.
IDE, 프로그래머, 터미널을 수동으로 전환하는 대신, 에이전트는 다음을 수행할 수 있습니다:
Keil 프로젝트를 빌드하고 실시간 컴파일 진행 상황을 확인
UV4 로그에서 구조화된 오류를 획득 (파일 / 줄 / 열 / 코드 / 메시지)
오류 코드를 원인 및 제안된 수정 사항과 함께 설명
소스 파일을 안전하게 편집 (모든 편집은 자동 백업됨)
공식 UV4 채널 또는 pyOCD를 통해 펌웨어 플래시
pyOCD를 통해 하드웨어 디버깅: 브레이크포인트, 단계 실행, 레지스터, 메모리, RTT 로그
공식 Keil 디버그 채널 실행 (UV4
-d+.ini스크립트)
목차
Related MCP server: mcp-stm32cubeide-server
기능
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 |
|
pyOCD | pip를 통해 자동 설치; 프로브 드라이버(ST-Link / J-Link / CMSIS-DAP) 필요 |
프로브 | ST-Link V2/V3, J-Link, CMSIS-DAP, Keil ULINKplus |
타깃 팩 | 예: |
설치
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가 필요합니다.
빌드 & 오류
도구 | 설명 | 주요 매개변수 → 결과 |
| UV4 |
|
| 진행 중인 빌드 진행률 조회 |
|
| 빌드 취소 요청 |
|
| UV4 로그를 구조화된 오류로 파싱 |
|
| 오류 코드 → 설명 + 원인 + 수정 방법 |
|
소스 편집
도구 | 설명 | 주요 매개변수 → 결과 |
| 줄 번호가 있는 소스 읽기 |
|
| 줄 범위 교체; 사전 자동 백업 |
|
| 소스 파일 검색(텍스트 또는 정규식) |
|
공식 디버그 채널
도구 | 설명 | 주요 매개변수 → 결과 |
| UV4 |
|
| 세션 출력을 ID로 읽기 |
|
프로젝트 & 환경
도구 | 설명 | 주요 매개변수 → 결과 |
| 환경 확인: UV4.exe, pyocd, 팩, 연결된 프로브 | — → |
| 디렉페커리 아래 |
|
| 프로젝트 파싱: 타깃, 디바이스, 팩, 그룹, 소스 |
|
플래시
도구 | 설명 | 주요 매개변수 → 결과 |
| UV4 |
|
| 칩 플래시 지우기 (pyOCD |
|
| 이미지와 칩 대조로 확인 (pyOCD |
|
프로브 디버깅
도구 | 설명 |
| PyOCD 프로브 연결 / 해제 (disconnect는 UV4 |
| 코어 제어 |
| 주소 또는 심볼의 브레이크포인트 설정, 재개 |
| r0–r15, sp, lr, pc, xpsr 읽기 |
| 주소의 메모리 읽기 (hex 바이트) |
| 현재 실행된 경우 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문제 해결
증상 | 원인 / 조치 |
| 플래시를 시작하기 전에 |
| 구성 파일의 |
| 가상환경의 editable 설치가 낡은 경로를 가리킴. 현재 소스에서 다시 |
| 프로브 배선 / 드라이버 점검, |
| 예를 들어 |
로드맵
PyPI에 배포하고 MCP 레지스트리에 등록
MCUBUDDY_TOOLSETS 스타일 도메인 토글
이름 기반
set_breakpoint용 ELF 심볼 해석RTOS 태스크 인지 (FreeRTOS)
단위 테스트용 GitHub Actions CI
Linux/macOS 지원 참고 사항(Keil은 Windows에서만, pyOCD는 크로스 플랫폼)
기여
기여는 환영합니다! 변경 사항을 먼저 이슈로 하고, 이어서 PR 줄 것.
License
MIT — 출처를 표시하면 자유롭게 이용·변경·재배포 할 수 있습니다.
Available Tools
27 toolsbuild_cancelC
Request cancellation of a running build.
Inputs: build_id (required).
build_progress_statusB
Query the live progress of a running build.
Inputs: build_id (required).
build_projectA
Build a Keil project with UV4 -b (or -r rebuild / -c clean).
Args: project: path to .uvprojx (absolute or relative to default_project_dir) target: target name (default: first target in project) timeout_seconds: build timeout (default 120) stream_progress: tail the log for realtime progress (percent/phase) clean: run UV4 -c instead of -b rebuild: run UV4 -r (full rebuild) instead of -b Returns: {status: ok|error|canceled|not_found, returncode, build_log, errors[], summary, progress?}
Inputs: project (required), clean, target, rebuild, +2 more.
configure_keil_projectA
Parse a Keil project: targets, device, pack, groups, source files.
Use before building to pick the right target / confirm the device.
Inputs: project (required), target.
continue_targetB
Continue the target until the next breakpoint.
Inputs: probe_id.
discover_keil_projectsB
Discover *.uvprojx Keil projects under a directory.
Inputs: directory, recursive.
erase_flashA
Erase the target chip flash (pyocd erase -c). Requires confirm=True.
Inputs: chip, confirm, probe_id, timeout_seconds.
explain_build_errorB
Map a Keil/armclang error code to explanation, causes and fixes.
Inputs: error_code (required), file, line, message.
flash_firmwareA
Flash firmware to the target chip.
Preferred path: UV4 -f (Keil official flash download, uses the project's configured Flash algorithm). Fallback: pyocd load . Requires confirm=True (persistent destructive operation).
Args: project: .uvprojx path (for UV4 -f) — required unless image is given target: target name for UV4 -f image: firmware image (axf/hex/bin) for the pyocd path backend: "uv4" | "pyocd" | "auto" probe_id: pyOCD probe unique id (optional) confirm: MUST be True to actually flash
Inputs: project (required), image, target, backend, +3 more.
keil_doctorB
Check the Keil environment: UV4.exe, pyocd, packs, config.
Inputs: no named parameters.
keil_versionA
Return the keil5-mcp server version and available tool count.
Inputs: no named parameters.
parse_build_errorsA
Parse a UV4 build log into structured errors/warnings (blueprint §7.2).
Args: log_path: path to build log file, OR log_content: raw log text Returns: {errors[], warnings[], summary{success, errors, warnings, code_size, ...}}
Inputs: log_path, log_content.
probe_connectC
Connect to a debug probe via pyOCD (auto-detect or by unique id).
Inputs: chip, probe_id.
probe_disconnectA
Disconnect the probe (releases it for UV4 -f flash path).
Inputs: probe_id.
probe_haltC
Halt the target.
Inputs: probe_id.
probe_read_memoryC
Read memory at address (bytes).
Inputs: address (required), length, probe_id.
probe_read_registersB
Read core registers (r0-r15, xpsr, sp, lr, pc).
Inputs: probe_id.
probe_resumeC
Resume the target.
Inputs: probe_id.
probe_stepC
Single-step the target.
Inputs: probe_id.
read_rtt_logA
Read recent SEGGER RTT log output from the target (if RTT is running).
Inputs: probe_id, timeout_seconds.
set_breakpointC
Set a hardware breakpoint by symbol name or address.
Inputs: symbol, address, probe_id.
source_editA
Edit a source file; original is automatically backed up to .keil-mcp-backups/.
Args: file: path to source file start_line / end_line: 1-based inclusive line range to replace new_content: replacement text (can be multi-line)
Inputs: file (required), end_line (required), start_line (required), new_content (required).
source_readA
Read a source file with line numbers (auto backup not needed; read-only).
Inputs: file (required), end_line, start_line.
source_searchA
Search source files in the project directory.
Args: pattern: text or regex pattern path: directory to search (default: default_project_dir or cwd) files: optional explicit file list (relative to path) regex: treat pattern as a regular expression
Inputs: pattern (required), path, files, regex, +2 more.
uv4_debug_ddeC
Read the output of a UV4 -d debug session (session output channel).
Inputs: session_id (required).
uv4_debug_sessionA
Run an official Keil debug session via UV4 -d + a generated .ini script.
The debugger runs headless: sets a breakpoint, resets, runs, optionally steps, and prints variable values. Output is captured from the session log.
Args: project: path to .uvprojx target: target name (default first target) ini_path: custom .ini script path (overrides generated script) reset: reset target before running breakpoint: symbol/line to break at ("" = none) steps: extra single-step count after hitting the breakpoint dump_vars: variable names to print (e.g. ["i", "adc_value"]) timeout_seconds: session timeout
Inputs: project (required), reset, steps, target, +4 more.
verify_flashB
Verify firmware on chip against an image (pyocd verify).
Inputs: image (required), probe_id, timeout_seconds.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
TDQS
Scored across 27 tools
Most tools target clearly distinct operations (build, source, flash, probe control), and the descriptions help separate them. Minor ambiguity exists between 'probe_resume' and 'continue_target' and between 'parse_build_errors' and 'explain_build_error', but these are usable with the provided docs.
The majority follow a verb_noun pattern like 'build_project', 'source_edit', and 'probe_halt', but there are notable deviations such as 'uv4_debug_dde', 'keil_doctor', and 'build_progress_status'. Names are generally readable but the mixed styles prevent a higher score.
With 27 tools, the server exceeds the 25+ threshold where tool count becomes heavy for an agent to navigate. The tools cover many subdomains, but several low-level probe primitives and debug-session helpers could be consolidated or omitted.
The server covers build, source editing, flashing, and basic debugging well. However, obvious lifecycle gaps exist: breakpoints can be set but not listed/deleted, memory/registers are read-only, and there is no standalone reset target operation or project creation/configuration update capability.
Maintenance
Related MCP Connectors
Design circuits, simulate and verify embedded firmware, and lay out PCBs with AI agents.
Run, build, and validate firmware on virtual hardware from your AI agent. Hardware knowledge corpus.
Adaptive plan/build/review cycles for AI coding assistants, persisted across sessions.
Debug, build, and manage Power Automate cloud flows with AI agents
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables AI assistants to flash firmware, program memory, modify option bytes, erase chips, reset boards, and capture SWO printf traces for STM32 microcontrollers via STM32CubeCLT.12MIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server that lets AI coding agents drive the full STM32 development loop—code generation, build, flash, debug, serial monitoring, and fault diagnosis—end to end via CubeIDE, CubeMX, CubeProgrammer, OpenOCD, and GDB.1MIT
- AlicenseAqualityBmaintenanceEnables AI coding assistants to perform complete headless STM32 embedded firmware development, including project creation, pin configuration, code generation, building, and flashing, by driving the official STM32 command-line toolchain.29MIT
- AlicenseAqualityCmaintenanceThis server enables AI agents to fully control STM32CubeIDE and STMicroelectronics hardware, including GUI automation, headless builds, flashing, GDB debugging, option bytes, serial telemetry, and CubeMX .ioc engineering.342Apache 2.0