Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

OpenCode

Why this agent

OpenCode 是开源的 AI 编程工具,原生支持 MCP。 它的配置形态和基于 JSON 的 agent 不同(command 单数组、用 mcp 而非 mcpServers),但底层行为一样。

Prerequisites

  • 已安装 OpenCode(任何支持 MCP 的版本)。
  • espctl 已安装在磁盘上某个稳定位置(下文需要完整路径)。
  • (可选,用于远程构建)Aegis 构建服务器地址 + MCP_AUTH_SECRET

Install snippet (or alternative)

写入项目目录下的 opencode.json,或者 ~/.config/opencode/opencode.json 让 espctl 全局可用:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "espctl": {
      "type": "local",
      "command": ["/path/to/espctl", "mcp", "serve"],
      "enabled": true,
      "environment": {
        "CONTROL_BASE_URL": "https://esphome.cloud",
        "MCP_AUTH_SECRET": "your-access-key"
      }
    }
  }
}

和基于 JSON 的 AI 工具相比,有四点要注意:

  1. 顶层 key 是 mcp,不是 mcpServers
  2. command一个数组,程序和所有参数都在一起,不是分开的 command + args
  3. 环境变量 key 是 environment,不是 env
  4. type 必须是 "local",因为 espctl 是在你电脑上启动的程序。

其他路径/值规则和 Claude Code 那一章一样。

或者 —— 拿到预填好的代码片段:

读取 install://opencode 资源。

First-run verification

重启 OpenCode。在任意对话里:

你能调用哪些 espctl 工具?

预期:列出约 40 个工具。

Troubleshooting

  • 工具列表为空 / “espctl failed to start” → OpenCode 的日志会 显示实际错误。位置:
    • Linux:~/.local/share/opencode/logs/
    • macOS:~/Library/Logs/opencode/
  • command 解析错 → 确认 command 是 JSON 数组(例如 ["espctl", "mcp", "serve"]),不是其他 agent 用的 JSON 字符串 形式。
  • 想临时禁用 → 把 "enabled": false,而不是删整个条目; OpenCode 下次启动会跳过这个服务。

Tested as-of 2026-05-19

OpenCode 特有注意事项

OpenCode 支持每个服务自己的 cwd 字段,和 command 同一层:

"espctl": {
  "type": "local",
  "command": ["/path/to/espctl", "mcp", "serve"],
  "cwd": "/path/to/your/esp-idf/project",
  "enabled": true,
  "environment": { ... }
}