Skip to main content
Glama

Embedded MCP

Universal Embedded AI Infrastructure & Serial over TCP Gateway for Antigravity & AI Agents

Python 3.12+ Package Manager uv Code Style ruff Tests Passing


1. 项目简介 (Overview)

在嵌入式与机器人开发中,传统物理串口(COM / UART)存在以下核心痛点:

  1. Windows 串口强排他性:一个 COM 口被上位机、VOFA+ 或终端打开后,AI Agent、自动化测试与 CLI 工具均会遭遇拒绝访问(WinError 5)。

  2. 多端并发写入冲突:多个 AI Agent 或测试脚本并发操作同一串口时,总线字节交错撕裂,回显混淆。

  3. 跨 Chunk 解码乱码:单片机输出中文或多字节 UTF-8 日志时,若按数据包切割解码,汉字极易损坏变成 \ufffd。

  4. 高频遥测淹没交互:单片机持续以 50Hz/10Hz 吐出红外或电机遥测流时,命令回执会被瞬间淹没。

Embedded MCP 通过 Serial over TCP Gateway 架构,将物理串口抽象为双端口微服务网络:

  • 5001 纯数据透传端口 (Raw Sniffer):PuTTY / VOFA+ 零配置直连监听波形与日志,无锁多读。

  • 5101 JSON-RPC 控制端口 (Control & Multiplexing):为 Antigravity AI Agent、自动化脚本与 CLI 提供结构化管控。

  • 方案二:微秒级原子事务排队池 (Transaction Multiplexing):并发下发命令无需手动申请锁,自动在异步 FIFO 队列中借还租约并剥离回显。

  • 单调偏移防乱码环形缓冲区 (ChunkedRingBuffer):在 Raw Bytes 空间反向定位边界,多字节 100% 完整,高频遥测下精准捕获命令回执。


Related MCP server: UART MCP Server

2. 系统架构 (Architecture)

┌──────────────────────────────────────────────────────────┐
│             Antigravity Agent / Claude Client            │
└────────────────────────────┬─────────────────────────────┘
                             │ stdio (JSON-RPC 2.0)
                             ▼
┌──────────────────────────────────────────────────────────┐
│                   embedded-mcp Server                    │
│   (board_list, board_status, serial_tail, serial_exchange)│
└────────────────────────────┬─────────────────────────────┘
                             │
                  ┌──────────┴──────────┐
                  ▼                     ▼
     JSON-RPC 2.0 (Port 5101)    Raw Stream (Port 5001)
     [Control & Leased Writes]   [PuTTY / VOFA+ Sniffer]
                  │                     ▲
                  └──────────┬──────────┘
                             ▼
┌──────────────────────────────────────────────────────────┐
│                  SerialGateway Engine                    │
│  ├── LeaseArbiter (FIFO Transaction Multiplexing Queue)  │
│  ├── ChunkedRingBuffer (Monotonic Byte Sliced Safe Buffer)│
│  └── SerialWorker (Dedicated Thread, Win32 Auto-Heal)    │
└────────────────────────────┬─────────────────────────────┘
                             │ pyserial (dtr=None, rts=None)
                             ▼
               COM4 (ATK-HSWL-CMSIS-DAP 04D8:00DF)

3. 环境准备与全局安装 (Installation)

本项目遵循 uv 环境规范,禁止使用传统 pip。

(1) 安装依赖与构建虚拟环境

在项目根目录(e:\WorkSpace\embedded-mcp)执行:

uv sync --extra dev

(2) 安装为全局命令行工具 (任选一种)

  • 推荐方法:通过 uv tool 全局链接

    uv tool install --editable . --force
  • 全局 PATH 支持: 若当前终端未包含 ~/.local/bin,系统已在全局 PATH(C:\Users\Administrator\.gemini\antigravity\bin\)配置了二进制包装器,可直接在任意目录(如 E:\Chassis control)执行 embedded-mcp。


4. 板卡配置规范 (Board Configuration)

本项目提供标准的开源示例配置模板于 config/boards.example/ 目录。 本地私有硬件定义存放于 config/boards/*.json(已受 .gitignore 保护,防止敏感信息泄漏),或通过环境变量 EMBEDDED_MCP_CONFIG_DIR 自定义路径。系统在任何目录下运行都会自动优先定位到本地私有目录,支持自动热重载。

首次使用时,可从示例模板复制:

# 从示例模板快速创建本地配置
cp -r config/boards.example config/boards

示例配置 (config/boards.example/board_a.json):

{
  "id": "board_a",
  "name": "ATK-HSWL-CMSIS-DAP Board",
  "adapter": "generic",
  "match": {
    "vid": 1240,
    "pid": 223,
    "serial_number": "ATK_20190528",
    "port": "COM4"
  },
  "serial": {
    "baudrate": 115200,
    "bytesize": 8,
    "parity": "N",
    "stopbits": 1,
    "dtr": null,
    "rts": null,
    "timeout": 0.05,
    "gateway": {
      "bind": "127.0.0.1",
      "data_port": 5001,
      "control_port": 5101
    }
  },
  "metadata": {
    "description": "Robot chassis main control board",
    "controller": "STM32",
    "shell_prompt": "dock:/$ "
  }
}
  • match:支持基于 vid / pid、serial_number 或显式 port 自动过滤并热插拔寻址,自动过滤 Windows 虚假 ACPI 端口。

  • dtr: null, rts: null:严格杜绝 Windows 串口打开时拉低引脚意外复位单片机。


5. 命令行使用指南 (CLI Manual)

你可以在系统中的任何目录(例如 E:\Chassis control 或任意项目文件夹)打开终端直接使用:

(1) 硬件与板卡发现

# 列出系统中所有已注册板卡与当前匹配的物理端口
embedded-mcp board list

# 扫描宿主机当前可用的物理串口(已过滤虚假 ACPI 端口)
embedded-mcp board ports

(2) 网关生命周期与状态

# 前台启动指定板卡的网关服务(若已有服务在运行,会自动友好提示)
embedded-mcp gateway run board_a

# 查询指定板卡的网关运行状态、波特率、收发字节数与控制器租约
embedded-mcp gateway status board_a

(3) 无锁查看单片机日志

# 查看最近 20 行历史日志(不抢占端口)
embedded-mcp serial tail board_a --lines 20

# 持续跟随实时输出(类似 Linux 的 tail -f,按 Ctrl+C 退出)
embedded-mcp serial tail board_a -f

(4) 下发命令与读取回执 (多写多读原子事务)

利用方案二事务池,命令在微秒级短借租约中排队下发,自动剥离回显并返回纯净内容:

# 查询当前电池电压
embedded-mcp serial exchange board_a "bat"

# 查询充电状态
embedded-mcp serial exchange board_a "charge_status"

# 查询底盘 Shell 支持的所有命令列表
embedded-mcp serial exchange board_a "help"

# 带自定义 Prompt 与超时时间的命令交互
embedded-mcp serial exchange board_a "status" --timeout 2000 --prompt "dock:/$ "

(5) 终端直接访问与全双工交互控制台 (Terminal / Console)

除了原子单次命令外,支持像物理串口助手/串口终端一样直接交互敲命令:

  • 方法 A:内置交互控制台(纯终端无依赖) 在任何终端中输入以下指令,直接进入板卡全双工 Shell 会话(按回车发送指令,输入 exit 或 Ctrl+C 退出):

    embedded-mcp console board_a
    # 或
    embedded-mcp serial console board_a
  • 方法 B:Netcat 终端直连 宿主机已内置 nc,直接连接 5001 端口:

    nc 127.0.0.1 5001

    直接键盘敲入 bat、help 等指令,单片机实时回显并输出。

  • 方法 C:PuTTY / MobaXterm / SecureCRT 直连

    • 协议选择:Raw 或 Telnet

    • 主机 IP:127.0.0.1,端口:5001

    • 打开即是标准串口终端,支持快捷键输入与实时波形/日志回显。


6. Antigravity & AI Agent 集成

本项目完整支持官方 MCP (Model Context Protocol) 2.x 协议标准,通过 stdio 与 Google Antigravity / Claude 互通。

(1) MCP 配置文件

位于 C:\Users\Administrator\.gemini\config\mcp_config.json:

{
  "mcpServers": {
    "embedded-mcp": {
      "command": "C:\\Users\\Administrator\\.gemini\\antigravity\\bin\\embedded-mcp.exe",
      "args": ["mcp"],
      "env": {
        "PYTHONUNBUFFERED": "1"
      }
    }
  }
}

(2) 专属 Skill

位于 C:\Users\Administrator\.gemini\config\skills\embedded-mcp\SKILL.md,AI Agent 自动加载并具备底层硬件诊断与无锁协同操作能力。

(3) 暴露的 MCP Tools 列表

Tool 名称

核心用途

board_list

获取注册的所有板卡及配置元数据

board_status

查询目标板卡串口连通性、收发计数、活跃租约与缓冲区指标

serial_connect

幂等确保板卡网关已启动连接物理串口

serial_tail

安全跨多字节边界读取最近历史日志(N 读无需持锁)

serial_exchange

核心交互工具:原子微事务下发指令、匹配 Prompt、剥离回显

serial_read

等待并读取最近串口输出

serial_write

受控写入串口(需 Lease)

serial_reset

触发硬件复位(DTR/RTS 脉冲)

ssh_connect

建立 SSH 会话并启动后台日志追踪流(如 tail -f enor.log)

ssh_tail

高速无锁获取远程日志最新 N 行(UTF-8 边界安全、防乱码)

ssh_exec

在远程嵌入式 Linux 主机上执行 Shell 命令并获取输出

ssh_status

查询 SSH 连接状态、目标主机、日志文件及环形缓冲区指标

firmware_release

固件一键发布:Keil 命令行编译 -> 产物新鲜度时间戳校验 -> MD5 -> FTP 上传 -> MQTT mcu_up 下发

firmware_build

Keil 命令行编译,自动发现并校验最新生成的新鲜 .bin 产物

firmware_upload

上传固件至 FTP 服务器并返回下载 URL 与 MD5 校验和

firmware_notify

下发 MQTT mcu_up OTA 升级命令至目标设备

firmware_get_version

从 APP/config/config.h 解析当前固件版本号(major.min.build)

firmware_get_config

查看当前激活的固件发布配置参数


7. 第三方工具并发协同 (PuTTY / VOFA+)

你可以在 AI 持续监视、CLI 下发测试的同时,使用图形化上位机直连观察波形:

  1. 打开 PuTTY 或 VOFA+。

  2. 连接类型选择 TCP(或 Raw)。

  3. 主机 IP 填 127.0.0.1,端口填 5001。

  4. 点击连接,即可实时接收底层完全相同、无任何延迟的原始数据流,彻底终结“调串口必须先关上位机”的历史。


8. 自动化测试与质量维护规范 (Maintenance & Testing)

后续对本库进行迭代、扩展适配新板卡或重构时,必须执行以下维护流程:

(1) 运行完整测试套件

uv run pytest -v
  • 包含 20 项测试:单元测试、JSON-RPC 协议解析、跨 Chunk 汉字切片无损性、多客户端高并发多写排队事务、以及对物理硬件(COM4)的生命周期全流程测试。

(2) 代码质量校验 (Ruff)

uv run ruff check .
  • 要求 0 warning / 0 error,保持 100% 格式洁净。

(3) 添加新板卡流程

  1. 在 config/boards/ 下新建 <board_id>.json。

  2. 配置 VID/PID 或串口号与波特率。

  3. 运行 embedded-mcp board list 验证识别。

  4. 运行 embedded-mcp serial tail <board_id> 验证通信。

Available Tools

20 tools
board_listA

List all configured boards in the registry and their capabilities.

Inputs: no named parameters. Returns: result

board_statusA

Get runtime connection, serial metrics, lease state, and buffer statistics for a board.

Args: board_id: The identifier of the board (e.g. 'board_a')

Inputs: board_id (required). Returns: object

firmware_buildA

Compile MCU firmware using Keil uVision command-line interface.

Verifies that a fresh .bin binary was produced by the compilation.

Args: board_id: Optional board identifier containing release config. rebuild: Force full rebuild (-r) instead of incremental (-b). config_path: Optional custom firmware release config file.

Inputs: rebuild, board_id, config_path. Returns: object

firmware_get_configB

Inspect the resolved firmware release configuration.

Args: board_id: Optional board identifier. config_path: Optional custom firmware release configuration file path.

Inputs: board_id, config_path. Returns: object

firmware_get_versionC

Read and parse firmware version from APP/config/config.h or active configuration.

Args: config_h_path: Optional explicit path to config.h header file. config_path: Optional firmware release configuration file path. board_id: Optional board identifier.

Inputs: board_id, config_path, config_h_path. Returns: object

firmware_notifyA

Publish MQTT OTA upgrade command (mcu_up) to target device topics.

Args: version: Firmware version string (e.g. '2.1.11'). file_url: Downloadable public URL of the uploaded firmware. md5: MD5 checksum of the firmware. board_id: Optional board identifier. device_ids: Target device ID(s) or topic(s). config_path: Optional custom firmware release config file.

Inputs: md5 (required), version (required), file_url (required), board_id, +2 more. Returns: object

firmware_releaseA

Execute full MCU firmware release pipeline:

  1. Keil command-line compilation (uVision.com -b or -r).

  2. Automatic discovery of latest .bin firmware with timestamp freshness verification.

  3. Calculate MD5 checksum.

  4. Upload .bin binary to FTP server.

  5. Publish MQTT OTA upgrade command (mcu_up) to target device topics.

Args: board_id: Optional board identifier (e.g. 'board_a') containing release config. rebuild: Force full Keil rebuild (-r) instead of incremental (-b). skip_build: Skip Keil compilation and use latest or specified existing binary. firmware_path: Explicit path to .bin file (bypasses auto-discovery). version: Firmware version string (e.g. '2.1.11'). If None, extracted from APP/config/config.h. device_ids: Target device ID(s) or topic(s). If None, taken from config. config_path: Path to custom firmware_release_config.json file. save_config: Save executed release artifact info back to the config file.

Inputs: rebuild, version, board_id, device_ids, +4 more. Returns: object

firmware_uploadB

Upload a firmware binary (.bin) to the configured FTP server.

Args: firmware_path: Path to the .bin file to upload. board_id: Optional board identifier containing release config. remote_filename: Optional remote filename on FTP server. config_path: Optional custom firmware release config file.

Inputs: firmware_path (required), board_id, config_path, remote_filename. Returns: object

serial_acquireA

Acquire exclusive controller lease (write permission) for the board.

Args: board_id: The identifier of the board (e.g. 'board_a') timeout_sec: Lease duration in seconds before auto-release (default: 60.0)

Inputs: board_id (required), timeout_sec. Returns: object

serial_connectC

Ensure the Serial Gateway is running and connected for the specified board.

Args: board_id: The identifier of the board (e.g. 'board_a')

Inputs: board_id (required). Returns: object

serial_exchangeA

Atomic composite command execution:

  1. Acquires lease temporarily if not already held.

  2. Transmits command with newline.

  3. Waits for expected prompt or output silence.

  4. Automatically strips echo.

  5. Cleanly restores previous lease state.

Args: board_id: The identifier of the board (e.g. 'board_a') request: Command to execute (e.g. 'help' or 'status') timeout_ms: Maximum duration in milliseconds to wait for reply (default: 1000) expected_prompt: Optional prompt to wait for (e.g. '> ' or 'shell#')

Inputs: request (required), board_id (required), timeout_ms, expected_prompt. Returns: result

serial_readA

Wait and read recent serial output from the board.

Args: board_id: The identifier of the board (e.g. 'board_a') timeout_ms: Duration in milliseconds to wait and collect (default: 500)

Inputs: board_id (required), timeout_ms. Returns: result

serial_releaseA

Release controller lease, restoring observer role.

Args: board_id: The identifier of the board (e.g. 'board_a')

Inputs: board_id (required). Returns: object

serial_resetA

Trigger hardware reset on target board via DTR line pulse.

Args: board_id: The identifier of the board (e.g. 'board_a')

Inputs: board_id (required). Returns: object

serial_tailA

Fetch the most recent log lines from the board's ring buffer history.

Safe across UTF-8 boundaries and non-intrusive (no TX write lock needed).

Args: board_id: The identifier of the board (e.g. 'board_a') lines: Number of recent lines to retrieve (default: 200)

Inputs: board_id (required), lines. Returns: result

serial_writeA

Write a raw command string to the board's serial port.

Requires active controller lease.

Args: board_id: The identifier of the board (e.g. 'board_a') data: String or command to transmit (e.g. 'help\r\n')

Inputs: data (required), board_id (required). Returns: object

ssh_connectB

Connect to remote board via SSH and start continuous log streaming (e.g. tail -f enor.log).

Args: board_id: The identifier of the board (e.g. 'e1_linux_host')

Inputs: board_id (required). Returns: object

ssh_execA

Execute a shell command on the remote host via SSH and return exit status, stdout, and stderr.

Args: board_id: The identifier of the board (e.g. 'e1_linux_host') command: Shell command string to execute (e.g. 'ps aux | grep enor' or 'dmesg | tail') timeout_sec: Maximum timeout in seconds (default: 30.0)

Inputs: command (required), board_id (required), timeout_sec. Returns: object

ssh_statusA

Get real-time SSH connection status, target host, monitored log file, and buffer metrics.

Args: board_id: The identifier of the board (e.g. 'e1_linux_host')

Inputs: board_id (required). Returns: object

ssh_tailA

Fetch the most recent log lines from the remote log file (e.g. enor.log) via SSH ring buffer.

Instantly returns latest lines with UTF-8 boundary protection, non-blocking.

Args: board_id: The identifier of the board (e.g. 'e1_linux_host') lines: Number of recent lines to retrieve (default: 200)

Inputs: board_id (required), lines. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 20 tools

    Disambiguation3/5

    Several tools overlap in function: serial_write and serial_exchange both transmit commands, serial_read and serial_tail both retrieve output, and firmware_release wraps build/upload/notify. The descriptions do clarify the intended use cases, but an agent could easily select the wrong granularity.

    Naming Consistency5/5

    All tools follow a consistent lowercase snake_case naming convention with domain prefixes: serial_, ssh_, firmware_, and board_. Actions are consistently placed after the domain prefix, making the tool family predictable and easy to navigate.

    Tool Count4/5

    At 20 tools, the surface is above the ideal 3-15 range, but the server covers three distinct areas: serial control, SSH access, and firmware release management. Each tool represents a real suboperation, so the count is slightly heavy but still reasonable.

    Completeness4/5

    The serial lifecycle is well covered with connect, lease, read/write, exchange, tail, and reset, and the firmware pipeline supports build, upload, notify, and full release. Minor gaps exist such as no explicit serial/SSH disconnect and no post-OTA verification, but core workflows have no dead ends.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables AI assistants to interact with physical serial port devices across platforms (Windows COM/Linux tty) with support for asynchronous communication, URC pattern recognition, and structured logging.
      1
      -
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI assistants to communicate with serial port devices, supporting port management, data transmission in text/binary modes, interactive terminal sessions, and automatic reconnection.
      14
      12
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to communicate with UART/serial devices, offering tools for port management, data read/write, and protocol handling.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to interact with serial port devices by sending commands, capturing output, and managing connections, with real-time browser-based terminal monitoring.
      1
      MIT