Skip to main content
Glama
ZMC1011

Keil5 MCP Server

by ZMC1011

Keil5 MCP 服务器

Python License: MIT MCP PyPI PRs Welcome

英文 | 中文

一个 Model Context Protocol (MCP) 服务器,为 STM32 + Keil MDK 开发环境中的 deepseek harness 提供 编辑代码 → 烧录 → 调试 → 读取反馈 → 修复代码 的闭环。

无需手动在 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 使用项目配置的 Flash 算法;pyOCD 后备方案直接接受 .axf 文件

  • 硬件调试:pyOCD 探针控制(连接 / 暂停 / 恢复 / 单步 / 断点 / 寄存器 / 内存 / RTT)

  • 探针租约:每个探针独占访问(asyncio 锁 + 文件锁),避免 UV4 和 pyOCD 争抢调试端口

  • 执行边界:只读工具并发运行;需要写入的工具在会话锁上串行执行;支持通过 asyncio.shield 进行取消操作

  • 无需安装 Keilkeil_doctor 会清晰报告缺失组件;服务器仍可启动

环境要求

组件

版本 / 说明

Python

3.10+(已在 3.12 上测试)

Keil MDK

UV4.exe(构建 -b、烧录 -f、调试 -d)— 可选但对于构建/烧录工具是必需的

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

使用 -b 编译(或 -r 重新构建 / -c 清理),实时查看进度

projecttarget?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_codemessage?file?line?{explanation, common_causes[], suggested_fixes[]}

源代码编辑

工具

说明

关键参数表 → 结果

source_read

读取带行号的源文件

filestart_line?end_line?{content, total_lines, ...}

source_edit

替换指定行范围;自动备份

filestart_lineend_linenew_content{success, lines_changed, backup_path}

source_search

按文本或正则搜索源文件

patternpath?files?regex?{matches[]}

官方调试通道

工具

说明

关键参数表 → 结果

uv4_debug_session

运行 -d + 生成的 .ini 调试脚本(无特定头断点/运行/step 返回)

projecttarget?ini_path?breakpoint?dump_vars?timeout_seconds?{success, returncode, output}

uv4_debug_dde

按 id 读取会话输出

session_id{output}

项目与环境

工具

说明

关键参数表 → 结果

keil_doctor ,

环境检查:UV4.exe、pyocd、packs、已连接的探针

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

discover_keil_projects

在目录下查找 *.uvprojx 文件

directory?recursive?{projects[]}

configure_keil_project

解析项目:目标、设备、pack、组和、源文件

projecttarget?{targets[], device, pack_id, source_files[]}

烧录

工具

说明

关键参数表 → 结果

flash_firmware

通过 UV4 -f(首选)或 pyOCD 烧录固件

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

erase_flash

擦除芯片 Flash(pyOCD erase -c

confirmprobe_id?chip?{success, output}

verify_flash

使用图像校验芯片(pyOCD verify

imageprobe_id?{success, output}

烧录探针调试

工具

说明

probe_connect / probe_disconnect

连接 / 放弃调试探针(断开后释放端口供 -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 防止取消。

  • 探针租约: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

故障排除

症状

原因 / 修复

烧录时出现 Target DLL has been cancelled

pyOCD 仍占用探针。在使用 UV4 后端调用 flash_firmware 前,请先调用 probe_disconnect(或让探针租约处理)。

UV4.exe not found

在配置中设置 KEIL_UV4_PATHkeil.uv4_path;运行 keil_doctor 确认。

No module named keil_mcp_server

venv 中的可编辑安装指向了旧路径——请从当前检出中重新安装:pip install -e .

No target connected

检查探针接线 / 驱动;keil_doctor 会列出检测到的探针。

需要 pyocd pack install

例如 pyocd pack install stm32f103c8,或将 pyOCD 指向 Keil DFP 文件夹。

路线图

  • 发布到 PyPI 并在 MCP 注册表中注册

  • 去让 set_breakpoint 按名称进行 ELF

  • 按名称进行 set_breakpoint 的 ELF 符号解析

  • RTOS 任务感知(FreeRTOS)

  • 为单元测试启用 GitHub Actions CI

  • Linux/macOS 支持说明(Keil 仅限 Windows;pyOCD 相关部分跨平台)

贡献

欢迎贡献!请先开 issue 讨论更改,然后提交 PR。

许可证

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