Keil5 MCP Server
Keil5 MCP 服务器
英文 | 中文
一个 Model Context Protocol (MCP) 服务器,为 STM32 + Keil MDK 开发环境中的 deepseek harness 提供 编辑代码 → 烧录 → 调试 → 读取反馈 → 修复代码 的闭环。
无需手动在 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使用项目配置的 Flash 算法;pyOCD 后备方案直接接受.axf文件硬件调试:pyOCD 探针控制(连接 / 暂停 / 恢复 / 单步 / 断点 / 寄存器 / 内存 / RTT)
探针租约:每个探针独占访问(asyncio 锁 + 文件锁),避免 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 日志解析为结构化错误 |
|
| 错误代码 → 解释 + 原因 + 修复方案 |
|
源代码编辑
工具 | 说明 | 关键参数表 → 结果 |
| 读取带行号的源文件 |
|
| 替换指定行范围;自动备份 |
|
| 按文本或正则搜索源文件 |
|
官方调试通道
工具 | 说明 | 关键参数表 → 结果 |
| 运行 |
|
| 按 id 读取会话输出 |
|
项目与环境
工具 | 说明 | 关键参数表 → 结果 |
| 环境检查: | — → |
| 在目录下查找 |
|
| 解析项目:目标、设备、pack、组和、源文件 |
|
烧录
工具 | 说明 | 关键参数表 → 结果 |
| 通过 |
|
| 擦除芯片 Flash(pyOCD |
|
| 使用图像校验芯片(pyOCD |
|
烧录探针调试
工具 | 说明 |
| 连接 / 放弃调试探针(断开后释放端口供 |
| 核心控制 |
| 按符号或地址设置断点、继续执行 |
| 读取 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防止取消。探针租约:UV4
-f和 pyOCD 无法共享调试端口。ProbeLease(asyncio 锁 +filelock)将访问串行化;烧录流程在 UV4 接管前会先断开 pyOCD。实时进度:一个守护线程跟踪 UV4 日志,将
compiling行数与从.uvprojx解析出的源文件计数进行比对(百分比封顶 95%,直到出现Build Time Elapsed标记)。畸形 XML 容错:较老的 Keil 项目包含不匹配的标签(例如
<b498tele498>...</bUseTDR>);项目解析器在解析前会修复这些标签。
配置
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 服务器 | 提示 |
原则:先收集证据再行动;首先识别目标芯片;烧录前确认目标 / 范围 / 镜像 / 恢复。
测试
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故障排除
症状 | 原因 / 修复 |
烧录时出现 | pyOCD 仍占用探针。在使用 UV4 后端调用 |
| 在配置中设置 |
| venv 中的可编辑安装指向了旧路径——请从当前检出中重新安装: |
| 检查探针接线 / 驱动; |
需要 | 例如 |
路线图
发布到 PyPI 并在 MCP 注册表中注册
去让
set_breakpoint按名称进行 ELF按名称进行
set_breakpoint的 ELF 符号解析RTOS 任务感知(FreeRTOS)
为单元测试启用 GitHub Actions CI
Linux/macOS 支持说明(Keil 仅限 Windows;pyOCD 相关部分跨平台)
贡献
欢迎贡献!请先开 issue 讨论更改,然后提交 PR。
许可证
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.
Loading tool schema changelog…
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.
Build, validate, and deploy multi-agent AI solutions from any AI environment.
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.49MIT
- AlicenseCqualityCmaintenanceEnables AI agents to build, flash, and debug STM32 projects compiled with Keil MDK-ARM on Windows, returning structured UV4 build diagnostics and evidence-based results. It also provides pyOCD/ST-Link debugging operations such as run control, breakpoints, register/PC reads, and global/static variable inspection.29MIT