dap-mcp-server 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/.claude/settings.local.json +31 -0
  2. package/.forgejo/workflows/publish.yml +63 -0
  3. package/CLAUDE.md +71 -0
  4. package/LICENSE +21 -0
  5. package/README.md +105 -0
  6. package/SKILL.md +62 -0
  7. package/build/adapters/builtin.d.ts +24 -0
  8. package/build/adapters/builtin.js +46 -0
  9. package/build/adapters/builtin.js.map +1 -0
  10. package/build/adapters/detect.d.ts +23 -0
  11. package/build/adapters/detect.js +36 -0
  12. package/build/adapters/detect.js.map +1 -0
  13. package/build/adapters/registry.d.ts +39 -0
  14. package/build/adapters/registry.js +79 -0
  15. package/build/adapters/registry.js.map +1 -0
  16. package/build/dap/dap-client.d.ts +46 -0
  17. package/build/dap/dap-client.js +190 -0
  18. package/build/dap/dap-client.js.map +1 -0
  19. package/build/dap/protocol.d.ts +32 -0
  20. package/build/dap/protocol.js +71 -0
  21. package/build/dap/protocol.js.map +1 -0
  22. package/build/dap/ring-buffer.d.ts +35 -0
  23. package/build/dap/ring-buffer.js +57 -0
  24. package/build/dap/ring-buffer.js.map +1 -0
  25. package/build/dap/types.d.ts +87 -0
  26. package/build/dap/types.js +25 -0
  27. package/build/dap/types.js.map +1 -0
  28. package/build/index.d.ts +24 -0
  29. package/build/index.js +30 -0
  30. package/build/index.js.map +1 -0
  31. package/build/server.d.ts +24 -0
  32. package/build/server.js +735 -0
  33. package/build/server.js.map +1 -0
  34. package/build/session/session-manager.d.ts +32 -0
  35. package/build/session/session-manager.js +60 -0
  36. package/build/session/session-manager.js.map +1 -0
  37. package/build/session/session.d.ts +85 -0
  38. package/build/session/session.js +374 -0
  39. package/build/session/session.js.map +1 -0
  40. package/docs/plans/2026-03-05-dap-wrapper-mcp-design.md +326 -0
  41. package/docs/plans/2026-03-05-dap-wrapper-mcp-implementation.md +2815 -0
  42. package/package.json +43 -0
  43. package/src/adapters/builtin.ts +47 -0
  44. package/src/adapters/detect.test.ts +36 -0
  45. package/src/adapters/detect.ts +36 -0
  46. package/src/adapters/registry.test.ts +73 -0
  47. package/src/adapters/registry.ts +86 -0
  48. package/src/dap/dap-client.test.ts +87 -0
  49. package/src/dap/dap-client.ts +216 -0
  50. package/src/dap/protocol.test.ts +82 -0
  51. package/src/dap/protocol.ts +78 -0
  52. package/src/dap/ring-buffer.test.ts +82 -0
  53. package/src/dap/ring-buffer.ts +64 -0
  54. package/src/dap/types.ts +92 -0
  55. package/src/index.ts +30 -0
  56. package/src/integration/debug-lifecycle.test.ts +107 -0
  57. package/src/server.ts +866 -0
  58. package/src/session/session-manager.test.ts +74 -0
  59. package/src/session/session-manager.ts +67 -0
  60. package/src/session/session.test.ts +84 -0
  61. package/src/session/session.ts +435 -0
  62. package/src/test-fixtures/crash-adapter.js +23 -0
  63. package/src/test-fixtures/mock-adapter.js +142 -0
  64. package/src/test-fixtures/silent-adapter.js +24 -0
  65. package/tsconfig.json +16 -0
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Copyright (c) 2026 Ivan Iraci <ivan.iraci@professioneit.com>
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { describe, it, expect } from "vitest";
24
+ import { SessionManager } from "./session-manager.js";
25
+
26
+ describe("SessionManager", () => {
27
+ it("generates unique session IDs", () => {
28
+ const manager = new SessionManager();
29
+ const id1 = manager.generateId();
30
+ const id2 = manager.generateId();
31
+ expect(id1).not.toBe(id2);
32
+ });
33
+
34
+ it("stores and retrieves sessions by ID", () => {
35
+ const manager = new SessionManager();
36
+ const mockSession = { id: "test-1" } as any;
37
+ manager.add(mockSession);
38
+ expect(manager.get("test-1")).toBe(mockSession);
39
+ });
40
+
41
+ it("removes sessions", () => {
42
+ const manager = new SessionManager();
43
+ const mockSession = { id: "test-1" } as any;
44
+ manager.add(mockSession);
45
+ manager.remove("test-1");
46
+ expect(manager.get("test-1")).toBeUndefined();
47
+ });
48
+
49
+ it("resolves single session when no ID provided", () => {
50
+ const manager = new SessionManager();
51
+ const mockSession = { id: "test-1" } as any;
52
+ manager.add(mockSession);
53
+ expect(manager.resolve(undefined)).toBe(mockSession);
54
+ });
55
+
56
+ it("throws when resolving without ID and multiple sessions exist", () => {
57
+ const manager = new SessionManager();
58
+ manager.add({ id: "s1" } as any);
59
+ manager.add({ id: "s2" } as any);
60
+ expect(() => manager.resolve(undefined)).toThrow(/multiple/i);
61
+ });
62
+
63
+ it("throws when resolving non-existent session", () => {
64
+ const manager = new SessionManager();
65
+ expect(() => manager.resolve("nope")).toThrow(/not found/i);
66
+ });
67
+
68
+ it("lists all sessions", () => {
69
+ const manager = new SessionManager();
70
+ manager.add({ id: "s1" } as any);
71
+ manager.add({ id: "s2" } as any);
72
+ expect(manager.listAll()).toHaveLength(2);
73
+ });
74
+ });
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Copyright (c) 2026 Ivan Iraci <ivan.iraci@professioneit.com>
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { DebugSession } from "./session.js";
24
+ import { randomUUID } from "node:crypto";
25
+
26
+ export class SessionManager {
27
+ private sessions = new Map<string, DebugSession>();
28
+
29
+ generateId(): string {
30
+ return randomUUID().slice(0, 8);
31
+ }
32
+
33
+ add(session: DebugSession): void {
34
+ this.sessions.set(session.id, session);
35
+ }
36
+
37
+ get(id: string): DebugSession | undefined {
38
+ return this.sessions.get(id);
39
+ }
40
+
41
+ remove(id: string): void {
42
+ this.sessions.delete(id);
43
+ }
44
+
45
+ resolve(sessionId: string | undefined): DebugSession {
46
+ if (sessionId) {
47
+ const session = this.sessions.get(sessionId);
48
+ if (!session) {
49
+ const available = Array.from(this.sessions.keys()).join(", ");
50
+ throw new Error(`Session '${sessionId}' not found. Available sessions: ${available || "none"}`);
51
+ }
52
+ return session;
53
+ }
54
+ if (this.sessions.size === 0) {
55
+ throw new Error("No active debug sessions. Use debug_launch or debug_attach first.");
56
+ }
57
+ if (this.sessions.size === 1) {
58
+ return this.sessions.values().next().value!;
59
+ }
60
+ const available = Array.from(this.sessions.keys()).join(", ");
61
+ throw new Error(`Multiple active sessions: ${available}. Specify sessionId.`);
62
+ }
63
+
64
+ listAll(): DebugSession[] {
65
+ return Array.from(this.sessions.values());
66
+ }
67
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Copyright (c) 2026 Ivan Iraci <ivan.iraci@professioneit.com>
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { describe, it, expect, afterEach } from "vitest";
24
+ import { DebugSession } from "./session.js";
25
+ import path from "node:path";
26
+ import { fileURLToPath } from "node:url";
27
+
28
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
29
+ const MOCK_ADAPTER = path.join(__dirname, "../test-fixtures/mock-adapter.js");
30
+
31
+ describe("DebugSession", () => {
32
+ let session: DebugSession | undefined;
33
+
34
+ afterEach(async () => {
35
+ if (session) {
36
+ try { await session.disconnect(); } catch { /* ignore */ }
37
+ session = undefined;
38
+ }
39
+ });
40
+
41
+ it("initializes and tracks state", async () => {
42
+ session = new DebugSession("test-1", {
43
+ type: "mock",
44
+ runtime: "node",
45
+ program: MOCK_ADAPTER,
46
+ });
47
+ expect(session.state).toBe("idle");
48
+ await session.initialize();
49
+ expect(session.state).toBe("configuring");
50
+ });
51
+
52
+ it("has a unique session ID", () => {
53
+ session = new DebugSession("my-session", {
54
+ type: "mock",
55
+ runtime: "node",
56
+ program: MOCK_ADAPTER,
57
+ });
58
+ expect(session.id).toBe("my-session");
59
+ });
60
+
61
+ it("buffers output events", async () => {
62
+ session = new DebugSession("test-2", {
63
+ type: "mock",
64
+ runtime: "node",
65
+ program: MOCK_ADAPTER,
66
+ });
67
+ session.addOutput("stdout", "hello world");
68
+ const output = session.getOutput();
69
+ expect(output.output).toHaveLength(1);
70
+ expect(output.output[0].text).toBe("hello world");
71
+ expect(output.output[0].category).toBe("stdout");
72
+ });
73
+
74
+ it("detects adapter crash", async () => {
75
+ const crashAdapter = path.join(__dirname, "../test-fixtures/crash-adapter.js");
76
+ session = new DebugSession("test-crash", {
77
+ type: "mock",
78
+ runtime: "node",
79
+ program: crashAdapter,
80
+ });
81
+ await expect(session.initialize()).rejects.toThrow();
82
+ expect(session.state).toBe("terminated");
83
+ });
84
+ });
@@ -0,0 +1,435 @@
1
+ /**
2
+ * Copyright (c) 2026 Ivan Iraci <ivan.iraci@professioneit.com>
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { DAPClient } from "../dap/dap-client.js";
24
+ import { RingBuffer } from "../dap/ring-buffer.js";
25
+ import {
26
+ SessionState,
27
+ StoppedState,
28
+ AdapterConfig,
29
+ OutputEntry,
30
+ BreakpointConfig,
31
+ BreakpointResult,
32
+ } from "../dap/types.js";
33
+ import { DebugProtocol } from "@vscode/debugprotocol";
34
+ import path from "node:path";
35
+
36
+ const MAX_OUTPUT_LINES = 10000;
37
+ const DEFAULT_TIMEOUT = 30000;
38
+
39
+ export class DebugSession {
40
+ readonly id: string;
41
+ private client: DAPClient;
42
+ private adapterConfig: AdapterConfig;
43
+ private _state: SessionState = "idle";
44
+ private outputBuffer = new RingBuffer<OutputEntry>(MAX_OUTPUT_LINES);
45
+ private breakpointsMap = new Map<string, BreakpointConfig[]>();
46
+ private capabilities: DebugProtocol.Capabilities = {};
47
+ private stoppedThreadId?: number;
48
+ private stoppedReason?: string;
49
+ private launchConfig?: Record<string, unknown>;
50
+ private attachConfig?: Record<string, unknown>;
51
+ private launchMode: "launch" | "attach" = "launch";
52
+ private stoppedResolvers: Array<(event: DebugProtocol.StoppedEvent) => void> = [];
53
+ private initializedResolvers: Array<() => void> = [];
54
+ private _initializedReceived = false;
55
+
56
+ constructor(id: string, config: AdapterConfig) {
57
+ this.id = id;
58
+ this.adapterConfig = config;
59
+ const runtime = config.runtime || "";
60
+ const program = config.program;
61
+ const args = config.args || [];
62
+ this.client = new DAPClient(runtime, program, args);
63
+
64
+ this.client.on("event", (event: DebugProtocol.Event) => {
65
+ this.handleEvent(event);
66
+ });
67
+
68
+ this.client.on("exit", () => {
69
+ if (this._state !== "terminated") {
70
+ this._state = "terminated";
71
+ }
72
+ });
73
+ }
74
+
75
+ get state(): SessionState {
76
+ return this._state;
77
+ }
78
+
79
+ async initialize(): Promise<DebugProtocol.Capabilities> {
80
+ try {
81
+ await this.client.spawn();
82
+ } catch (err) {
83
+ this._state = "terminated";
84
+ throw err;
85
+ }
86
+ try {
87
+ const response = await this.client.sendRequest("initialize", {
88
+ adapterID: this.adapterConfig.type,
89
+ clientID: "dap-mcp-server",
90
+ clientName: "DAP MCP Server",
91
+ linesStartAt1: true,
92
+ columnsStartAt1: true,
93
+ pathFormat: "path",
94
+ });
95
+ this.capabilities = response.body || {};
96
+ this._state = "configuring";
97
+ await this.waitForInitialized(10000);
98
+ return this.capabilities;
99
+ } catch (err) {
100
+ this._state = "terminated";
101
+ throw err;
102
+ }
103
+ }
104
+
105
+ async waitForInitialized(timeout = 10000): Promise<void> {
106
+ // If we already received the initialized event, resolve immediately
107
+ if (this._initializedReceived) return;
108
+ return new Promise<void>((resolve) => {
109
+ let settled = false;
110
+ const wrappedResolve = () => {
111
+ if (settled) return;
112
+ settled = true;
113
+ clearTimeout(timer);
114
+ const idx = this.initializedResolvers.indexOf(wrappedResolve);
115
+ if (idx !== -1) this.initializedResolvers.splice(idx, 1);
116
+ resolve();
117
+ };
118
+ const timer = setTimeout(() => {
119
+ // Don't reject — some adapters never send initialized; just continue
120
+ wrappedResolve();
121
+ }, timeout);
122
+ this.initializedResolvers.push(wrappedResolve);
123
+ });
124
+ }
125
+
126
+ async setBreakpoints(
127
+ filePath: string,
128
+ breakpoints: BreakpointConfig[]
129
+ ): Promise<BreakpointResult[]> {
130
+ const absPath = path.resolve(filePath);
131
+ this.breakpointsMap.set(absPath, breakpoints);
132
+ const response = await this.client.sendRequest("setBreakpoints", {
133
+ source: { path: absPath },
134
+ breakpoints: breakpoints.map((bp) => ({
135
+ line: bp.line,
136
+ condition: bp.condition,
137
+ hitCondition: bp.hitCondition,
138
+ logMessage: bp.logMessage,
139
+ })),
140
+ });
141
+ return ((response.body?.breakpoints as DebugProtocol.Breakpoint[]) || []).map((bp) => ({
142
+ id: bp.id,
143
+ verified: bp.verified ?? false,
144
+ line: bp.line ?? 0,
145
+ message: bp.message,
146
+ }));
147
+ }
148
+
149
+ async setExceptionBreakpoints(filters: string[]): Promise<void> {
150
+ await this.client.sendRequest("setExceptionBreakpoints", { filters });
151
+ }
152
+
153
+ async configurationDone(): Promise<void> {
154
+ if (this.capabilities.supportsConfigurationDoneRequest) {
155
+ await this.client.sendRequest("configurationDone");
156
+ }
157
+ }
158
+
159
+ async launch(config: Record<string, unknown>): Promise<void> {
160
+ this.launchConfig = config;
161
+ this.launchMode = "launch";
162
+ await this.client.sendRequest("launch", config);
163
+ this._state = "running";
164
+ }
165
+
166
+ async attach(config: Record<string, unknown>): Promise<void> {
167
+ this.attachConfig = config;
168
+ this.launchMode = "attach";
169
+ await this.client.sendRequest("attach", config);
170
+ this._state = "running";
171
+ }
172
+
173
+ async continueExecution(threadId?: number): Promise<void> {
174
+ const tid = threadId ?? this.stoppedThreadId ?? 1;
175
+ await this.client.sendRequest("continue", { threadId: tid });
176
+ this._state = "running";
177
+ }
178
+
179
+ async next(threadId?: number): Promise<void> {
180
+ const tid = threadId ?? this.stoppedThreadId ?? 1;
181
+ await this.client.sendRequest("next", { threadId: tid });
182
+ this._state = "running";
183
+ }
184
+
185
+ async stepIn(threadId?: number): Promise<void> {
186
+ const tid = threadId ?? this.stoppedThreadId ?? 1;
187
+ await this.client.sendRequest("stepIn", { threadId: tid });
188
+ this._state = "running";
189
+ }
190
+
191
+ async stepOut(threadId?: number): Promise<void> {
192
+ const tid = threadId ?? this.stoppedThreadId ?? 1;
193
+ await this.client.sendRequest("stepOut", { threadId: tid });
194
+ this._state = "running";
195
+ }
196
+
197
+ async pause(threadId?: number): Promise<void> {
198
+ const tid = threadId ?? this.stoppedThreadId ?? 1;
199
+ await this.client.sendRequest("pause", { threadId: tid });
200
+ }
201
+
202
+ async waitForStopped(timeout = DEFAULT_TIMEOUT): Promise<DebugProtocol.StoppedEvent> {
203
+ if (this._state === "stopped") {
204
+ return {
205
+ seq: 0,
206
+ type: "event",
207
+ event: "stopped",
208
+ body: { reason: this.stoppedReason || "unknown", threadId: this.stoppedThreadId },
209
+ } as DebugProtocol.StoppedEvent;
210
+ }
211
+ return new Promise<DebugProtocol.StoppedEvent>((resolve, reject) => {
212
+ let settled = false;
213
+ const wrappedResolve = (event: DebugProtocol.StoppedEvent) => {
214
+ if (settled) return;
215
+ settled = true;
216
+ clearTimeout(timer);
217
+ const idx = this.stoppedResolvers.indexOf(wrappedResolve);
218
+ if (idx !== -1) this.stoppedResolvers.splice(idx, 1);
219
+ resolve(event);
220
+ };
221
+ const timer = setTimeout(() => {
222
+ if (settled) return;
223
+ settled = true;
224
+ const idx = this.stoppedResolvers.indexOf(wrappedResolve);
225
+ if (idx !== -1) this.stoppedResolvers.splice(idx, 1);
226
+ reject(new Error("timeout"));
227
+ }, timeout);
228
+ this.stoppedResolvers.push(wrappedResolve);
229
+ });
230
+ }
231
+
232
+ async getThreads(): Promise<DebugProtocol.Thread[]> {
233
+ const response = await this.client.sendRequest("threads");
234
+ return (response.body?.threads as DebugProtocol.Thread[]) || [];
235
+ }
236
+
237
+ async getStackTrace(threadId: number, depth = 10): Promise<DebugProtocol.StackFrame[]> {
238
+ const response = await this.client.sendRequest("stackTrace", {
239
+ threadId,
240
+ startFrame: 0,
241
+ levels: depth,
242
+ });
243
+ return (response.body?.stackFrames as DebugProtocol.StackFrame[]) || [];
244
+ }
245
+
246
+ async getScopes(frameId: number): Promise<DebugProtocol.Scope[]> {
247
+ const response = await this.client.sendRequest("scopes", { frameId });
248
+ return (response.body?.scopes as DebugProtocol.Scope[]) || [];
249
+ }
250
+
251
+ async getVariables(
252
+ variablesReference: number,
253
+ depth = 1
254
+ ): Promise<
255
+ Array<{
256
+ name: string;
257
+ value: string;
258
+ type?: string;
259
+ hasChildren: boolean;
260
+ variablesReference: number;
261
+ }>
262
+ > {
263
+ const response = await this.client.sendRequest("variables", { variablesReference });
264
+ const vars = ((response.body?.variables as DebugProtocol.Variable[]) || []).map((v) => ({
265
+ name: v.name,
266
+ value: v.value,
267
+ type: v.type,
268
+ hasChildren: (v.variablesReference ?? 0) > 0,
269
+ variablesReference: v.variablesReference ?? 0,
270
+ }));
271
+ if (depth > 1) {
272
+ for (const v of vars) {
273
+ if (v.hasChildren) {
274
+ const children = await this.getVariables(v.variablesReference, depth - 1);
275
+ v.value = `${v.value} { ${children.map((c) => `${c.name}: ${c.value}`).join(", ")} }`;
276
+ }
277
+ }
278
+ }
279
+ return vars;
280
+ }
281
+
282
+ async evaluate(
283
+ expression: string,
284
+ frameId?: number,
285
+ context: "repl" | "watch" | "hover" = "repl"
286
+ ): Promise<{
287
+ result: string;
288
+ type?: string;
289
+ hasChildren: boolean;
290
+ variablesReference: number;
291
+ }> {
292
+ const args: Record<string, unknown> = { expression, context };
293
+ if (frameId !== undefined) args.frameId = frameId;
294
+ const response = await this.client.sendRequest("evaluate", args);
295
+ return {
296
+ result: (response.body?.result as string) ?? "",
297
+ type: response.body?.type as string | undefined,
298
+ hasChildren: ((response.body?.variablesReference as number) ?? 0) > 0,
299
+ variablesReference: (response.body?.variablesReference as number) ?? 0,
300
+ };
301
+ }
302
+
303
+ async collectState(
304
+ threadId?: number,
305
+ depth = 10,
306
+ variableDepth = 1
307
+ ): Promise<StoppedState> {
308
+ const tid = threadId ?? this.stoppedThreadId ?? 1;
309
+ const threads = await this.getThreads();
310
+ const frames = await this.getStackTrace(tid, depth);
311
+ const topFrame = frames[0];
312
+ const location = topFrame
313
+ ? {
314
+ file: topFrame.source?.path || topFrame.source?.name || "<unknown>",
315
+ line: topFrame.line,
316
+ column: topFrame.column,
317
+ functionName: topFrame.name,
318
+ }
319
+ : { file: "<unknown>", line: 0 };
320
+
321
+ const scopes: StoppedState["scopes"] = [];
322
+ if (topFrame) {
323
+ const rawScopes = await this.getScopes(topFrame.id);
324
+ for (const scope of rawScopes) {
325
+ const variables = await this.getVariables(scope.variablesReference, variableDepth);
326
+ scopes.push({ name: scope.name, variables });
327
+ }
328
+ }
329
+ const output = this.outputBuffer.getAll().map((e) => e.text);
330
+ return {
331
+ status: "stopped",
332
+ reason: this.stoppedReason || "unknown",
333
+ location,
334
+ threads: threads.map((t) => ({ id: t.id, name: t.name, stopped: t.id === tid })),
335
+ stackTrace: frames.map((f) => ({
336
+ id: f.id,
337
+ name: f.name,
338
+ file: f.source?.path || f.source?.name || "<unknown>",
339
+ line: f.line,
340
+ column: f.column,
341
+ })),
342
+ scopes,
343
+ output: output.length > 0 ? output : undefined,
344
+ };
345
+ }
346
+
347
+ addOutput(category: string, text: string): void {
348
+ this.outputBuffer.push({ category, text, timestamp: new Date().toISOString() });
349
+ }
350
+
351
+ getOutput(
352
+ category?: string,
353
+ clear = false
354
+ ): { output: OutputEntry[]; truncated: boolean } {
355
+ const entries = category
356
+ ? this.outputBuffer.getFiltered((e) => e.category === category)
357
+ : this.outputBuffer.getAll();
358
+ const truncated = this.outputBuffer.truncated;
359
+ if (clear) {
360
+ if (category) {
361
+ this.outputBuffer.removeMatching((e) => e.category === category);
362
+ } else {
363
+ this.outputBuffer.clear();
364
+ }
365
+ }
366
+ return { output: entries, truncated };
367
+ }
368
+
369
+ async disconnect(terminateDebuggee?: boolean): Promise<void> {
370
+ const terminate = terminateDebuggee ?? this.launchMode === "launch";
371
+ try {
372
+ await this.client.sendRequest("disconnect", { terminateDebuggee: terminate }, 5000);
373
+ } catch {
374
+ /* Ignore — adapter may have already exited */
375
+ }
376
+ this._state = "terminated";
377
+ await this.client.dispose();
378
+ }
379
+
380
+ getLaunchConfig(): Record<string, unknown> | undefined {
381
+ // Only returns a value for launched sessions, not attached
382
+ if (this.launchMode === "attach") return undefined;
383
+ return this.launchConfig;
384
+ }
385
+
386
+ getAttachConfig(): Record<string, unknown> | undefined {
387
+ return this.attachConfig;
388
+ }
389
+
390
+ getLaunchMode(): "launch" | "attach" {
391
+ return this.launchMode;
392
+ }
393
+
394
+ getAdapterConfig(): AdapterConfig {
395
+ return this.adapterConfig;
396
+ }
397
+
398
+ getBreakpoints(): Map<string, BreakpointConfig[]> {
399
+ return this.breakpointsMap;
400
+ }
401
+
402
+ private handleEvent(event: DebugProtocol.Event): void {
403
+ switch (event.event) {
404
+ case "initialized":
405
+ this._initializedReceived = true;
406
+ for (const resolve of this.initializedResolvers) resolve();
407
+ this.initializedResolvers = [];
408
+ break;
409
+ case "stopped":
410
+ this._state = "stopped";
411
+ this.stoppedThreadId = event.body?.threadId as number | undefined;
412
+ this.stoppedReason = event.body?.reason as string | undefined;
413
+ {
414
+ const resolvers = this.stoppedResolvers;
415
+ this.stoppedResolvers = [];
416
+ for (const resolve of resolvers) resolve(event as DebugProtocol.StoppedEvent);
417
+ }
418
+ break;
419
+ case "continued":
420
+ this._state = "running";
421
+ break;
422
+ case "output":
423
+ if (event.body?.output)
424
+ this.addOutput(
425
+ (event.body.category as string) || "console",
426
+ event.body.output as string
427
+ );
428
+ break;
429
+ case "terminated":
430
+ case "exited":
431
+ this._state = "terminated";
432
+ break;
433
+ }
434
+ }
435
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Copyright (c) 2026 Ivan Iraci <ivan.iraci@professioneit.com>
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ process.exit(1);