This repository was archived by the owner on Jan 9, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmcp-server.js
More file actions
1318 lines (1173 loc) Β· 38.3 KB
/
Copy pathmcp-server.js
File metadata and controls
1318 lines (1173 loc) Β· 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import WebSocket from 'ws';
import fetch from 'node-fetch';
// Disable console output for MCP compatibility
console.log = function() {};
console.error = function() {};
// Create an MCP server
const server = new McpServer({
name: "NodeJS Debugger",
version: "0.3.0",
description: `Advanced Node.js debugger for runtime analysis and troubleshooting. This tool connects to Node.js's built-in Inspector Protocol to provide powerful debugging capabilities directly through Claude Code.
DEBUGGING STRATEGY:
Use debugger for the following:
- When you need to understand the runtime state of the application
- When you need to test potential fixes for the application
- When you need to explore the codebase to find the root cause of an issue
CONNECTION MANAGEMENT:
- Use 'get_connection_status' to check current connection state
- Use 'disconnect' after completing a debug session - this allows the debugged process to exit cleanly
- Use 'connect' to establish a new connection after disconnect, or to connect to a different debug port
- Use 'retry_connect' if connection drops unexpectedly
IMPORTANT NOTES:
- ALWAYS assume the user has already started their Node.js application in debug mode.
- When a fix requires restarting the app: 1) use disconnect, 2) restart the app or tell the user to do so as appropriate, 3) use connect
- Don't try to start the debugger or the node server yourself.
- Always ask the user to trigger breakpoints manually, give them specific instructions on how to do so.
- When user interaction is required, provide EXTREMELY specific instructions
- Take initiative to explore the runtime state thoroughly when breakpoint is hit
- Keep breakpoints active until issue is fully resolved, then clean up using delete_breakpoint
- Set multiple strategic breakpoints at once to capture the full execution path leading to an error.
- NEVER use fetch() as it will break the debugging connection.`
});
class Inspector {
constructor(port = 9229, retryOptions = { maxRetries: 5, retryInterval: 1000, continuousRetry: true }) {
this.port = port;
this.connected = false;
this.pendingRequests = new Map();
this.debuggerEnabled = false;
this.breakpoints = new Map();
this.paused = false;
this.currentCallFrames = [];
this.retryOptions = retryOptions;
this.retryCount = 0;
this.callbackHandlers = new Map();
this.continuousRetryEnabled = retryOptions.continuousRetry;
this.reconnectEnabled = true; // Controls whether auto-reconnect is active
this.initialize();
}
async initialize() {
try {
// First, get the WebSocket URL from the inspector JSON API
// Use 127.0.0.1 instead of localhost to avoid IPv6 issues
const response = await fetch(`http://127.0.0.1:${this.port}/json`);
const data = await response.json();
const debuggerUrl = data[0]?.webSocketDebuggerUrl;
if (!debuggerUrl) {
this.scheduleRetry();
return;
}
this.ws = new WebSocket(debuggerUrl);
this.ws.on('open', () => {
this.connected = true;
this.retryCount = 0;
this.enableDebugger();
});
this.ws.on('error', (error) => {
this.scheduleRetry();
this.debuggerEnabled = false;
});
this.ws.on('close', () => {
this.connected = false;
this.scheduleRetry();
this.debuggerEnabled = false;
});
this.ws.on('message', (data) => {
const response = JSON.parse(data.toString());
// Handle events
if (response.method) {
this.handleEvent(response);
return;
}
// Handle response for pending request
if (response.id && this.pendingRequests.has(response.id)) {
const { resolve, reject } = this.pendingRequests.get(response.id);
this.pendingRequests.delete(response.id);
if (response.error) {
reject(response.error);
} else {
resolve(response.result);
}
}
});
} catch (error) {
this.scheduleRetry();
}
}
scheduleRetry() {
// Don't retry if reconnection is disabled (e.g., after explicit disconnect)
if (!this.reconnectEnabled) {
return;
}
// If continuous retry is enabled, we'll keep trying after the initial attempts
if (this.retryCount < this.retryOptions.maxRetries || this.continuousRetryEnabled) {
this.retryCount++;
// Use a longer interval for continuous retries to reduce resource usage
const interval = this.continuousRetryEnabled && this.retryCount > this.retryOptions.maxRetries
? Math.min(this.retryOptions.retryInterval * 5, 10000) // Max 10 seconds between retries
: this.retryOptions.retryInterval;
setTimeout(() => this.initialize(), interval);
}
}
async enableDebugger() {
try {
if (!this.debuggerEnabled && this.connected) {
await this.send('Debugger.enable', {});
this.debuggerEnabled = true;
// Setup event listeners
await this.send('Runtime.enable', {});
// Also activate possible domains we'll need
await this.send('Runtime.runIfWaitingForDebugger', {});
}
} catch (error) {
this.scheduleRetry();
}
}
handleEvent(event) {
switch (event.method) {
case 'Debugger.paused':
this.paused = true;
this.currentCallFrames = event.params.callFrames;
// Notify any registered callbacks for pause events
if (this.callbackHandlers.has('paused')) {
this.callbackHandlers.get('paused').forEach(callback =>
callback(event.params));
}
break;
case 'Debugger.resumed':
this.paused = false;
this.currentCallFrames = [];
// Notify any registered callbacks for resume events
if (this.callbackHandlers.has('resumed')) {
this.callbackHandlers.get('resumed').forEach(callback =>
callback());
}
break;
case 'Debugger.scriptParsed':
// Script parsing might be useful for source maps
break;
case 'Runtime.exceptionThrown':
break;
case 'Runtime.consoleAPICalled':
// Handle console logs from the debugged program
const args = event.params.args.map(arg => {
if (arg.type === 'string') return arg.value;
if (arg.type === 'number') return arg.value;
if (arg.type === 'boolean') return arg.value;
if (arg.type === 'object') {
if (arg.value) {
return JSON.stringify(arg.value, null, 2);
} else if (arg.objectId) {
// We'll try to get properties later as we can't do async here
return arg.description || `[${arg.subtype || arg.type}]`;
} else {
return arg.description || `[${arg.subtype || arg.type}]`;
}
}
return JSON.stringify(arg);
}).join(' ');
// Store console logs to make them available to the MCP tools
if (!this.consoleOutput) {
this.consoleOutput = [];
}
this.consoleOutput.push({
type: event.params.type,
message: args,
timestamp: Date.now(),
raw: event.params.args
});
// Keep only the last 100 console messages to avoid memory issues
if (this.consoleOutput.length > 100) {
this.consoleOutput.shift();
}
break;
}
}
registerCallback(event, callback) {
if (!this.callbackHandlers.has(event)) {
this.callbackHandlers.set(event, []);
}
this.callbackHandlers.get(event).push(callback);
}
unregisterCallback(event, callback) {
if (this.callbackHandlers.has(event)) {
const callbacks = this.callbackHandlers.get(event);
const index = callbacks.indexOf(callback);
if (index !== -1) {
callbacks.splice(index, 1);
}
}
}
async send(method, params) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Request timed out: ${method}`));
this.pendingRequests.delete(id);
}, 5000);
const checkConnection = () => {
if (this.connected) {
try {
const id = Math.floor(Math.random() * 1000000);
this.pendingRequests.set(id, {
resolve: (result) => {
clearTimeout(timeout);
resolve(result);
},
reject: (err) => {
clearTimeout(timeout);
reject(err);
}
});
this.ws.send(JSON.stringify({
id,
method,
params
}));
} catch (err) {
clearTimeout(timeout);
reject(err);
}
} else {
const connectionCheckTimer = setTimeout(checkConnection, 100);
// If still not connected after 3 seconds, reject the promise
setTimeout(() => {
clearTimeout(connectionCheckTimer);
clearTimeout(timeout);
reject(new Error('Not connected to debugger'));
}, 3000);
}
};
checkConnection();
});
}
async getScriptSource(scriptId) {
try {
const response = await this.send('Debugger.getScriptSource', {
scriptId
});
return response.scriptSource;
} catch (err) {
return null;
}
}
async evaluateOnCallFrame(callFrameId, expression) {
if (!this.paused) {
throw new Error('Debugger is not paused');
}
try {
return await this.send('Debugger.evaluateOnCallFrame', {
callFrameId,
expression,
objectGroup: 'console',
includeCommandLineAPI: true,
silent: false,
returnByValue: true,
generatePreview: true
});
} catch (err) {
throw err;
}
}
async getProperties(objectId, ownProperties = true) {
try {
return await this.send('Runtime.getProperties', {
objectId,
ownProperties,
accessorPropertiesOnly: false,
generatePreview: true
});
} catch (err) {
throw err;
}
}
disconnect() {
// Disable automatic reconnection
this.reconnectEnabled = false;
// Close the WebSocket connection if it exists
if (this.ws) {
this.ws.close();
}
// Reset state
this.connected = false;
this.debuggerEnabled = false;
this.paused = false;
this.currentCallFrames = [];
this.breakpoints.clear();
this.pendingRequests.clear();
}
getStatus() {
return {
connected: this.connected,
debuggerEnabled: this.debuggerEnabled,
port: this.port,
paused: this.paused,
reconnectEnabled: this.reconnectEnabled,
activeBreakpoints: this.breakpoints.size
};
}
}
// Create the inspector instance with continuous retry enabled
const inspector = new Inspector(9229, {
maxRetries: 5,
retryInterval: 1000,
continuousRetry: true
});
// Initialize console output storage
inspector.consoleOutput = [];
// Execute JavaScript code
server.tool(
"nodejs_inspect",
"Executes JavaScript code in the debugged process",
{
js_code: z.string().describe("JavaScript code to execute")
},
async ({ js_code }) => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
// Capture the current console output length to know where to start capturing new output
const consoleStartIndex = inspector.consoleOutput.length;
// Wrap the code in a try-catch with explicit console logging for errors
let codeToExecute = `
try {
${js_code}
} catch (e) {
e; // Return the error
}
`;
const response = await inspector.send('Runtime.evaluate', {
expression: codeToExecute,
contextId: 1,
objectGroup: 'console',
includeCommandLineAPI: true,
silent: false,
returnByValue: true,
generatePreview: true,
awaitPromise: true // This will wait for promises to resolve
});
// Give some time for console logs to be processed
await new Promise(resolve => setTimeout(resolve, 200));
// Get any console output that was generated during execution
const consoleOutputs = inspector.consoleOutput.slice(consoleStartIndex);
const consoleText = consoleOutputs.map(output =>
`[${output.type}] ${output.message}`
).join('\n');
// Process the return value
let result;
if (response.result) {
if (response.result.type === 'object') {
if (response.result.value) {
// If we have a value, use it
result = response.result.value;
} else if (response.result.objectId) {
// If we have an objectId but no value, the object was too complex to serialize directly
// Get more details about the object
try {
const objectProps = await inspector.getProperties(response.result.objectId);
const formattedObject = {};
for (const prop of objectProps.result) {
if (prop.value) {
if (prop.value.type === 'object' && prop.value.subtype !== 'null') {
// For nested objects, try to get their details too
if (prop.value.objectId) {
try {
const nestedProps = await inspector.getProperties(prop.value.objectId);
const nestedObj = {};
for (const nestedProp of nestedProps.result) {
if (nestedProp.value) {
if (nestedProp.value.value !== undefined) {
nestedObj[nestedProp.name] = nestedProp.value.value;
} else {
nestedObj[nestedProp.name] = nestedProp.value.description ||
`[${nestedProp.value.subtype || nestedProp.value.type}]`;
}
}
}
formattedObject[prop.name] = nestedObj;
} catch (nestedErr) {
formattedObject[prop.name] = prop.value.description ||
`[${prop.value.subtype || prop.value.type}]`;
}
} else {
formattedObject[prop.name] = prop.value.description ||
`[${prop.value.subtype || prop.value.type}]`;
}
} else if (prop.value.type === 'function') {
formattedObject[prop.name] = '[function]';
} else if (prop.value.value !== undefined) {
formattedObject[prop.name] = prop.value.value;
} else {
formattedObject[prop.name] = `[${prop.value.type}]`;
}
}
}
result = formattedObject;
} catch (propErr) {
// If we can't get properties, at least show the object description
result = response.result.description || `[${response.result.subtype || response.result.type}]`;
}
} else {
// Fallback for objects without value or objectId
result = response.result.description || `[${response.result.subtype || response.result.type}]`;
}
} else if (response.result.type === 'undefined') {
result = undefined;
} else if (response.result.value !== undefined) {
result = response.result.value;
} else {
result = `[${response.result.type}]`;
}
}
let responseContent = [];
// Add console output if there was any
if (consoleText.length > 0) {
responseContent.push({
type: "text",
text: `Console output:\n${consoleText}`
});
}
// Add the result
responseContent.push({
type: "text",
text: `Code executed successfully. Result: ${JSON.stringify(result, null, 2)}`
});
return { content: responseContent };
} catch (err) {
return {
content: [{
type: "text",
text: `Error executing code: ${err.message}`
}]
};
}
}
);
// Set breakpoint tool
server.tool(
"set_breakpoint",
"Sets a breakpoint at specified line and file",
{
file: z.string().describe("File path where to set breakpoint"),
line: z.number().describe("Line number for breakpoint")
},
async ({ file, line }) => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
// Convert file path to a URL-like format that the debugger can understand
// For local files, typically file:///path/to/file.js
let fileUrl = file;
if (!file.startsWith('file://') && !file.startsWith('http://') && !file.startsWith('https://')) {
fileUrl = `file://${file.startsWith('/') ? '' : '/'}${file}`;
}
const response = await inspector.send('Debugger.setBreakpointByUrl', {
lineNumber: line - 1, // Chrome DevTools Protocol uses 0-based line numbers
urlRegex: fileUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), // Escape special regex characters
columnNumber: 0
});
// Store the breakpoint for future reference
inspector.breakpoints.set(response.breakpointId, { file, line, id: response.breakpointId });
return {
content: [{
type: "text",
text: `Breakpoint set successfully. ID: ${response.breakpointId}`
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: `Error setting breakpoint: ${err.message}`
}]
};
}
}
);
// Inspect variables tool
server.tool(
"inspect_variables",
"Inspects variables in current scope",
{
scope: z.string().optional().describe("Scope to inspect (local/global)")
},
async ({ scope = 'local' }) => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
if (scope === 'global' || !inspector.paused) {
// For global scope or when not paused, use Runtime.globalProperties
const response = await inspector.send('Runtime.globalLexicalScopeNames', {});
// Get global object properties for a more complete picture
const globalObjResponse = await inspector.send('Runtime.evaluate', {
expression: 'this',
contextId: 1,
returnByValue: true
});
return {
content: [{
type: "text",
text: JSON.stringify({
lexicalNames: response.names,
globalThis: globalObjResponse.result.value
}, null, 2)
}]
};
} else {
// For local scope when paused, get variables from the current call frame
if (inspector.currentCallFrames.length === 0) {
return {
content: [{
type: "text",
text: "No active call frames. Debugger is not paused at a breakpoint."
}]
};
}
const frame = inspector.currentCallFrames[0]; // Get top frame
const scopeChain = frame.scopeChain;
// Create a formatted output of variables in scope
const result = {};
for (const scopeObj of scopeChain) {
const { scope, type, name } = scopeObj;
if (type === 'global') continue; // Skip global scope for local inspection
const objProperties = await inspector.getProperties(scope.object.objectId);
const variables = {};
for (const prop of objProperties.result) {
if (prop.value && prop.configurable) {
if (prop.value.type === 'object' && prop.value.subtype !== 'null') {
variables[prop.name] = `[${prop.value.subtype || prop.value.type}]`;
} else if (prop.value.type === 'function') {
variables[prop.name] = '[function]';
} else if (prop.value.value !== undefined) {
variables[prop.name] = prop.value.value;
} else {
variables[prop.name] = `[${prop.value.type}]`;
}
}
}
result[type] = variables;
}
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
} catch (err) {
return {
content: [{
type: "text",
text: `Error inspecting variables: ${err.message}`
}]
};
}
}
);
// Step over tool
server.tool(
"step_over",
"Steps over to the next line of code",
{},
async () => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
if (!inspector.paused) {
return {
content: [{
type: "text",
text: "Debugger is not paused at a breakpoint"
}]
};
}
await inspector.send('Debugger.stepOver', {});
return {
content: [{
type: "text",
text: "Stepped over to next line"
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: `Error stepping over: ${err.message}`
}]
};
}
}
);
// Step into tool
server.tool(
"step_into",
"Steps into function calls",
{},
async () => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
if (!inspector.paused) {
return {
content: [{
type: "text",
text: "Debugger is not paused at a breakpoint"
}]
};
}
await inspector.send('Debugger.stepInto', {});
return {
content: [{
type: "text",
text: "Stepped into function call"
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: `Error stepping into: ${err.message}`
}]
};
}
}
);
// Step out tool
server.tool(
"step_out",
"Steps out of current function",
{},
async () => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
if (!inspector.paused) {
return {
content: [{
type: "text",
text: "Debugger is not paused at a breakpoint"
}]
};
}
await inspector.send('Debugger.stepOut', {});
return {
content: [{
type: "text",
text: "Stepped out of current function"
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: `Error stepping out: ${err.message}`
}]
};
}
}
);
// Continue execution tool
server.tool(
"continue",
"Continues code execution",
{},
async () => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
if (!inspector.paused) {
return {
content: [{
type: "text",
text: "Debugger is not paused at a breakpoint"
}]
};
}
await inspector.send('Debugger.resume', {});
return {
content: [{
type: "text",
text: "Execution resumed"
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: `Error continuing execution: ${err.message}`
}]
};
}
}
);
// Delete breakpoint tool
server.tool(
"delete_breakpoint",
"Deletes a specified breakpoint",
{
breakpointId: z.string().describe("ID of the breakpoint to remove")
},
async ({ breakpointId }) => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
await inspector.send('Debugger.removeBreakpoint', {
breakpointId: breakpointId
});
// Remove from our local tracking
inspector.breakpoints.delete(breakpointId);
return {
content: [{
type: "text",
text: `Breakpoint ${breakpointId} removed`
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: `Error removing breakpoint: ${err.message}`
}]
};
}
}
);
// List all breakpoints tool
server.tool(
"list_breakpoints",
"Lists all active breakpoints",
{},
async () => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
if (inspector.breakpoints.size === 0) {
return {
content: [{
type: "text",
text: "No active breakpoints"
}]
};
}
const breakpointsList = Array.from(inspector.breakpoints.values());
return {
content: [{
type: "text",
text: JSON.stringify(breakpointsList, null, 2)
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: `Error listing breakpoints: ${err.message}`
}]
};
}
}
);
// Evaluate expression tool
server.tool(
"evaluate",
"Evaluates a JavaScript expression in the current context",
{
expression: z.string().describe("JavaScript expression to evaluate")
},
async ({ expression }) => {
try {
// Ensure debugger is enabled
if (!inspector.debuggerEnabled) {
await inspector.enableDebugger();
}
// Capture the current console output length to know where to start capturing new output
const consoleStartIndex = inspector.consoleOutput.length;
// Wrap the expression in a try-catch to better handle errors
const wrappedExpression = `
try {
${expression}
} catch (e) {
e; // Return the error
}
`;
let result;
if (inspector.paused && inspector.currentCallFrames.length > 0) {
// When paused at a breakpoint, evaluate in the context of the call frame
const frame = inspector.currentCallFrames[0];
result = await inspector.evaluateOnCallFrame(frame.callFrameId, wrappedExpression);
} else {
// Otherwise, evaluate in the global context
result = await inspector.send('Runtime.evaluate', {
expression: wrappedExpression,
contextId: 1,
objectGroup: 'console',
includeCommandLineAPI: true,
silent: false,
returnByValue: true,
generatePreview: true,
awaitPromise: true // This will wait for promises to resolve
});
}
// Give some time for console logs to be processed
await new Promise(resolve => setTimeout(resolve, 200));
// Get any console output that was generated during execution
const consoleOutputs = inspector.consoleOutput.slice(consoleStartIndex);
const consoleText = consoleOutputs.map(output =>
`[${output.type}] ${output.message}`
).join('\n');
let valueRepresentation;
if (result.result) {
if (result.result.type === 'object') {
if (result.result.value) {
// If we have a value, use it
valueRepresentation = JSON.stringify(result.result.value, null, 2);
} else if (result.result.objectId) {
// If we have an objectId but no value, the object was too complex to serialize directly
// Get more details about the object
try {
const objectProps = await inspector.getProperties(result.result.objectId);
const formattedObject = {};
for (const prop of objectProps.result) {
if (prop.value) {
if (prop.value.type === 'object' && prop.value.subtype !== 'null') {
// For nested objects, try to get their details too
if (prop.value.objectId) {
try {
const nestedProps = await inspector.getProperties(prop.value.objectId);
const nestedObj = {};
for (const nestedProp of nestedProps.result) {
if (nestedProp.value) {
if (nestedProp.value.value !== undefined) {
nestedObj[nestedProp.name] = nestedProp.value.value;
} else {
nestedObj[nestedProp.name] = nestedProp.value.description ||
`[${nestedProp.value.subtype || nestedProp.value.type}]`;
}
}
}
formattedObject[prop.name] = nestedObj;
} catch (nestedErr) {
formattedObject[prop.name] = prop.value.description ||
`[${prop.value.subtype || prop.value.type}]`;
}
} else {
formattedObject[prop.name] = prop.value.description ||
`[${prop.value.subtype || prop.value.type}]`;
}
} else if (prop.value.type === 'function') {
formattedObject[prop.name] = '[function]';
} else if (prop.value.value !== undefined) {
formattedObject[prop.name] = prop.value.value;
} else {
formattedObject[prop.name] = `[${prop.value.type}]`;
}
}
}
valueRepresentation = JSON.stringify(formattedObject, null, 2);