5.8b ACP 协议
💡 一句话总结:了解 ACP 协议,实现 OpenCode 与其他工具的互联互通。
学完你能做什么
- 理解 ACP 协议的概念
- 能配置 ACP 连接
- 能实现工具集成
- 能创建自定义 ACP 端点
🎒 开始前的准备
确保你已经完成以下事项:
- [ ] 了解 OpenCode 的基本配置
- [ ] 有 API 开发经验
核心思路
什么是 ACP
ACP (Agent Communication Protocol) 是 OpenCode 的通信协议,用于不同工具之间的互联互通。
工具 A ←→ ACP ←→ 工具 BACP 特点
- 标准化接口
- 双向通信
- 事件驱动
- 易于扩展
配置结构
连接配置
yaml
acp:
enabled: true
servers:
- name: "IDE"
url: "http://localhost:3000"
auth:
type: "bearer"
token: "${ACP_TOKEN}"
- name: "CI/CD"
url: "http://localhost:3001"端点配置
yaml
acp:
endpoints:
chat:
path: "/api/chat"
methods: ["POST"]
tools:
path: "/api/tools"
methods: ["GET", "POST"]
events:
path: "/api/events"
methods: ["GET"]API 接口
发送消息
bash
curl -X POST http://localhost:8080/api/chat \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${TOKEN}" \
-d '{
"message": "帮我写一个函数",
"context": {
"file": "src/app.js"
}
}'接收事件
typescript
// 监听事件
const eventSource = new EventSource("http://localhost:8080/api/events", {
headers: {
Authorization: "Bearer ${TOKEN}",
},
});
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("收到事件:", data);
};跟我做
实战:创建 ACP 集成
- 配置 OpenCode:
yaml
acp:
enabled: true
port: 8080
auth:
type: "bearer"
token: "${ACP_TOKEN}"
endpoints:
chat: "/api/chat"
tools: "/api/tools"
events: "/api/events"- 创建客户端:
typescript
import { ACPClient } from "@opencode/acp-client";
const client = new ACPClient({
url: "http://localhost:8080",
token: process.env.ACP_TOKEN,
});
// 发送消息
const response = await client.sendMessage({
message: "帮我写一个函数",
context: {
file: "src/app.ts",
},
});
// 监听事件
client.on("code_change", (data) => {
console.log("代码变更:", data);
});检查点 ✅
全部通过才能继续
- [ ] 理解 ACP 协议
- [ ] 能配置连接
- [ ] 能使用 API
- [ ] 能创建集成
本课小结
你学会了:
- ACP 协议概念
- 配置方法
- API 接口
- 集成实战
下一课预告
下一课我们将学习远程模式。
📚 更多完整模板:Prompt 模板库

