答案是理解并实现Debug Adapter Protocol(DAP),通过VSCode与Debug Adapter通信,基于JSON-RPC格式解析请求与事件,用任意语言实现适配器逻辑,处理launch、breakpoint、step等调试命令,并在package.json中注册调试器类型,最终集成到VSCode调试流程中。

想在 VSCode 中实现自定义调试器,核心是理解并实现 Debug Adapter Protocol(DAP)。VSCode 本身不直接运行或调试代码,而是通过 DAP 与一个独立的 Debug Adapter 进程通信。这个协议基于 JSON-RPC,使用标准输入输出(stdin/stdout)或 WebSocket 进行消息传输。
1. 理解 Debug Adapter Protocol (DAP)
DAP 是一种语言无关的协议,定义了调试器前端(如 VSCode)和调试后端(即 Debug Adapter)之间的通信规则。它采用请求-响应-事件模型:
- Request → Response:前端发送请求(如 launch、next),后端处理并返回结果
- Event:后端主动向前端推送状态变化(如 stopped、output)
- 消息格式:每条消息以头部(含 content-length)和 JSON 正文组成
Content-Length: 145\r\n\r\n{
"type": "request",
"command": "launch",
"arguments": { "program": "app.js" },
"seq": 1
}
2. 实现一个最简 Debug Adapter
你可以用任意语言实现 Debug Adapter,只要能读写 stdin/stdout 并解析 DAP 消息。以下以 Node.js 为例说明基本结构:
- 监听 stdin 的数据流,按 Content-Length 解包 JSON 消息
- 根据 command 字段分发处理逻辑
- 向 stdout 写入响应或事件消息
关键处理流程:
process.stdin.on('data', data => {
const messages = parseMessages(data); // 按 DAP 格式拆分
messages.forEach(msg => {
if (msg.type === 'request') {
switch(msg.command) {
case 'initialize':
respond(msg, { supportsConfigurationDoneRequest: true });
break;
case 'launch':
// 启动目标程序逻辑
sendEvent('initialized'); // 通知前端已准备就绪
respond(msg, {});
break;
case 'configurationDone':
// 可在此启动自动暂停或运行
respond(msg, {});
break;
case 'threads':
respond(msg, { threads: [{ id: 1, name: 'main' }] });
break;
default:
respond(msg, {}, true); // 错误响应
}
}
});
});
3. 支持断点与单步执行
要让调试器真正可用,需处理断点和控制流:
- setBreakpoints:接收文件路径和行号列表,更新内部断点表
- 当程序执行到断点时,发送 stopped 事件(带 reason: 'breakpoint')
- next / continue / stepIn:实现对应的执行控制,并在完成后发送 continued 或 stopped 事件
- stackTrace:返回调用栈信息,用于显示当前执行位置
- scopes + variables:支持查看变量值,需提供作用域和变量列表
比如用户点击“继续”,VSCode 发送 continue 请求,你的适配器应恢复目标程序运行,并在下次中断时推送 stopped 事件。
4. 注册自定义调试器到 VSCode
在扩展的 package.json 中声明调试贡献点:
"contributes": {
"debuggers": [{
"type": "my-debugger",
"label": "My Debugger",
"programs": {
"adapter": "./out/debugAdapter.js"
},
"configurationAttributes": {
"launch": {
"required": ["program"],
"properties": {
"program": {
"type": "string",
"description": "The program to debug"
}
}
}
}
}]
}
然后在 launch.json 中使用:
{
"type": "my-debugger",
"request": "launch",
"name": "Launch My Program",
"program": "${workspaceFolder}/test.my"
}
基本上就这些。实现一个基础 DAP 服务,处理核心请求和事件,再对接你的实际解释器或运行时,就能在 VSCode 中获得完整的调试体验。










