Repository navigation
Expand file tree
/
Copy pathai-code-mcp-debug-tools.el
More file actions
790 lines (724 loc) · 32.1 KB
/
Copy pathai-code-mcp-debug-tools.el
File metadata and controls
790 lines (724 loc) · 32.1 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
;;; ai-code-mcp-debug-tools.el --- Optional MCP debugging tools -*- lexical-binding: t; -*-
;; SPDX-License-Identifier: Apache-2.0
;;; Commentary:
;; Optional MCP debugging tools for inspecting Emacs variables,
;; functions, features, messages, and the most recent command error.
;;; Code:
(require 'json)
(require 'ai-code-mcp-common)
(require 'nadvice)
(require 'subr-x)
(declare-function ai-code-mcp-make-tool "ai-code-mcp-server")
(declare-function ai-code-mcp-get-session-context "ai-code-mcp-server")
(declare-function eglot-managed-p "eglot")
(declare-function treesit-parser-list "treesit")
(declare-function treesit-parser-language "treesit")
(defgroup ai-code-mcp-debug-tools nil
"Optional MCP debugging tools."
:group 'ai-code-mcp-server
:prefix "ai-code-mcp-debug-tools-")
(defcustom ai-code-mcp-debug-tools-enabled t
"When non-nil, register optional MCP debugging tools."
:type 'boolean
:group 'ai-code-mcp-debug-tools)
(defcustom ai-code-mcp-debug-tools-enable-eval-elisp nil
"When non-nil, register the `eval_elisp' MCP tool."
:type 'boolean
:group 'ai-code-mcp-debug-tools)
(defcustom ai-code-mcp-debug-tools-max-value-chars 2048
"Maximum characters in a printed value returned by the debug tools.
Variable values and `eval_elisp' results are printed with bounded
length, depth, and circular-structure sharing, then truncated to
this many characters, so inspecting a large or circular value can
neither overflow the model context nor hang the printer."
:type 'natnum
:group 'ai-code-mcp-debug-tools)
(defun ai-code-mcp-debug-tools--value-repr (value)
"Return the printed representation of VALUE, bounded and cycle-safe."
(let* ((print-length 100)
(print-level 10)
(print-circle t)
(text (prin1-to-string value)))
(if (> (length text) ai-code-mcp-debug-tools-max-value-chars)
(concat (substring text 0 ai-code-mcp-debug-tools-max-value-chars)
"...[truncated]")
text)))
(defvar ai-code-mcp--last-error-record nil
"Most recent Emacs error snapshot recorded for MCP diagnostics tools.")
(defvar ai-code-mcp--error-capture-installed nil
"Non-nil when MCP error capture advice has been installed.")
(defconst ai-code-mcp-debug-tools--specs
'((:function ai-code-mcp-get-variable-binding-info
:name "get_variable_binding_info"
:description "Get current and default binding details for an Emacs variable."
:args ((:name "variable_name"
:type string
:description "Emacs variable name to inspect.")
(:name "buffer_name"
:type string
:description "Optional buffer name used for buffer-local inspection."
:optional t)))
(:function ai-code-mcp-get-variable-value
:name "get_variable_value"
:description "Get the printed representation of an Emacs variable value by name."
:plain-text t
:args ((:name "variable_name"
:type string
:description "Emacs variable name to inspect.")))
(:function ai-code-mcp-get-function-info
:name "get_function_info"
:description "Get metadata about an Emacs function by name."
:args ((:name "function_name"
:type string
:description "Emacs function name to inspect.")))
(:function ai-code-mcp-get-last-error-backtrace
:name "get_last_error_backtrace"
:description "Get the most recently recorded Emacs error backtrace."
:args nil)
(:function ai-code-mcp-get-feature-load-state
:name "get_feature_load_state"
:description "Get load state details for an Emacs feature."
:args ((:name "feature_name"
:type string
:description "Emacs feature name to inspect.")))
(:function ai-code-mcp-get-buffer-runtime-state
:name "get_buffer_runtime_state"
:description "Read buffer-local Emacs mode, diagnostics, language-server and optional hook state without evaluating code."
:args ((:name "buffer_name"
:type string
:description "Optional live buffer; defaults to MCP prompt origin."
:optional t)
(:name "hook_name"
:type string
:description "Optional hook variable ending in -hook, -hooks or -functions."
:optional t)))
(:function ai-code-mcp-get-recent-messages
:name "get_recent_messages"
:description "Get recent entries from the Emacs *Messages* buffer."
:args ((:name "limit"
:type integer
:description "Maximum number of messages to return."
:optional t))))
"Optional MCP debugging tool specifications.")
(defconst ai-code-mcp-debug-tools--eval-spec
'(:function ai-code-mcp-eval-elisp
:name "eval_elisp"
:description "Evaluate arbitrary Emacs Lisp with possible side effects once explicitly enabled."
:args ((:name "code"
:type string
:description "Single Emacs Lisp form to evaluate.")
(:name "buffer_name"
:type string
:description "Optional buffer context."
:optional t)
(:name "file_path"
:type string
:description "Optional file buffer context."
:optional t)
(:name "capture_messages"
:type boolean
:description "When non-nil, capture new messages."
:optional t)
(:name "include_backtrace"
:type boolean
:description "When non-nil, include a backtrace on failure."
:optional t)
(:name "timeout_ms"
:type integer
:description "Maximum time budget for the evaluation."
:optional t)))
"Optional MCP eval tool specification.")
(defun ai-code-mcp-debug-tools--register-base-tools ()
"Register the standard MCP debugging tools."
(dolist (tool ai-code-mcp-debug-tools--specs)
(apply #'ai-code-mcp-make-tool
(append
tool
'(:category debug
:annotations
((readOnlyHint . t)
(destructiveHint . :json-false)
(idempotentHint . t)
(openWorldHint . :json-false)))))))
(defun ai-code-mcp-debug-tools--register-eval-tool ()
"Register the optional `eval_elisp' MCP tool."
(apply #'ai-code-mcp-make-tool
(append
ai-code-mcp-debug-tools--eval-spec
'(:category eval
:annotations
((readOnlyHint . :json-false)
(destructiveHint . t)
(idempotentHint . :json-false)
(openWorldHint . t))))))
(defun ai-code-mcp-debug-tools--enabled-p ()
"Return non-nil when debug tools are enabled globally."
ai-code-mcp-debug-tools-enabled)
(defun ai-code-mcp-debug-tools--eval-enabled-p ()
"Return non-nil when `eval_elisp' is enabled globally."
ai-code-mcp-debug-tools-enable-eval-elisp)
(defun ai-code-mcp-debug-tools--require-enabled ()
"Signal an error unless debug inspection tools are enabled."
(unless (ai-code-mcp-debug-tools--enabled-p)
(error
"Enable ai-code-mcp-debug-tools-enabled to use the global Emacs debug MCP tools")))
(defun ai-code-mcp-debug-tools--require-eval-enabled ()
"Signal an error unless `eval_elisp' is enabled."
(unless (ai-code-mcp-debug-tools--eval-enabled-p)
(error
"Enable ai-code-mcp-debug-tools-enable-eval-elisp to use the global eval_elisp MCP tool")))
(defun ai-code-mcp-debug-tools-setup ()
"Register optional MCP debugging tools when enabled."
(when ai-code-mcp-debug-tools-enabled
(ai-code-mcp--ensure-error-capture)
(ai-code-mcp-debug-tools--register-base-tools)
(when ai-code-mcp-debug-tools-enable-eval-elisp
(ai-code-mcp-debug-tools--register-eval-tool))))
(defun ai-code-mcp--documentation-summary (documentation)
"Return a trimmed summary line for DOCUMENTATION."
(if (stringp documentation)
(string-trim (car (split-string documentation "\n" t)))
""))
(defun ai-code-mcp--resolve-buffer (buffer-name)
"Return BUFFER-NAME when it names a live buffer, or the current buffer."
(if buffer-name
(or (get-buffer buffer-name)
(error "Buffer not found: %s" buffer-name))
(current-buffer)))
(defun ai-code-mcp-debug-tools--bool-arg (value default)
"Return boolean VALUE, falling back to DEFAULT when VALUE is omitted."
(cond
((null value) default)
((eq value :json-false) nil)
(t (and value t))))
(defun ai-code-mcp-debug-tools--selected-window ()
"Return the selected window, falling back to the frame root window."
(or (and (window-live-p (selected-window))
(selected-window))
(frame-root-window)))
(defun ai-code-mcp-debug-tools--resolve-eval-buffer (&optional buffer-name file-path)
"Return the requested live buffer from BUFFER-NAME or FILE-PATH."
(when (and buffer-name file-path)
(error "Arguments buffer_name and file_path are mutually exclusive"))
(cond
(buffer-name
(or (get-buffer buffer-name)
(error "Buffer not found: %s" buffer-name)))
(file-path
(find-file-noselect (expand-file-name file-path) t))
(t
(window-buffer (ai-code-mcp-debug-tools--selected-window)))))
(defun ai-code-mcp-debug-tools--point-line-column (buffer point)
"Return line and column for POINT in BUFFER."
(with-current-buffer buffer
(save-excursion
(goto-char point)
`((line . ,(line-number-at-pos))
(column . ,(current-column))))))
(defun ai-code-mcp-debug-tools--modified-buffer-snapshot ()
"Return an alist of live buffers and their modified states."
(mapcar (lambda (buffer)
(cons buffer
(with-current-buffer buffer
(buffer-modified-p))))
(buffer-list)))
(defun ai-code-mcp-debug-tools--changed-buffers (before)
"Return a list of buffers whose modified state changed after BEFORE."
(let ((before-table (make-hash-table :test 'eq))
changed)
(dolist (entry before)
(puthash (car entry) (cdr entry) before-table))
(dolist (buffer (buffer-list) (nreverse changed))
(let ((before-modified (gethash buffer before-table :missing))
(after-modified (with-current-buffer buffer
(buffer-modified-p))))
(when (or (eq before-modified :missing)
(not (eq before-modified after-modified)))
(push `((buffer_name . ,(buffer-name buffer))
(file_path . ,(buffer-file-name buffer))
(modified . ,(ai-code-mcp--json-bool
after-modified)))
changed))))))
(defun ai-code-mcp-debug-tools--context-summary (buffer)
"Return a summary of BUFFER after an evaluation.
Return nil when BUFFER is no longer live."
(when (buffer-live-p buffer)
(let ((position (ai-code-mcp-debug-tools--point-line-column
buffer
(with-current-buffer buffer (point)))))
`((buffer_name . ,(buffer-name buffer))
(file_path . ,(buffer-file-name buffer))
(line . ,(alist-get 'line position))
(column . ,(alist-get 'column position))))))
(defun ai-code-mcp-debug-tools--parse-single-form (code)
"Parse CODE and return exactly one top-level Emacs Lisp form."
(let* ((read-result (read-from-string code))
(form (car read-result))
(position (cdr read-result))
(rest (substring code position)))
(unless (string-match-p "\\`[[:space:]\n\r\t]*\\'" rest)
(error "Argument code must contain exactly one top-level form"))
form))
(defun ai-code-mcp-debug-tools--evaluation-messages (before capture-messages)
"Return messages added after BEFORE when CAPTURE-MESSAGES."
(if capture-messages
(nthcdr (length before) (ai-code-mcp--message-lines))
'()))
(defun ai-code-mcp-debug-tools--error-alist (type message)
"Return a JSON-ready error payload for TYPE and MESSAGE."
`((type . ,type)
(message . ,message)))
(defun ai-code-mcp-debug-tools--backtrace-string ()
"Return the current backtrace as a string."
(with-temp-buffer
(let ((standard-output (current-buffer)))
(backtrace))
(buffer-string)))
(defun ai-code-mcp-debug-tools--encode-eval-result
(target-buffer before-messages capture-messages timed-out
value changed-buffers &optional error-object backtrace)
"Return a JSON eval response for TARGET-BUFFER.
BEFORE-MESSAGES and CAPTURE-MESSAGES control message collection.
TIMED-OUT records timeout state, VALUE carries the result,
CHANGED-BUFFERS lists modified buffers, and ERROR-OBJECT or BACKTRACE
describe failures."
(json-encode
`((ok . ,(ai-code-mcp--json-bool (null error-object)))
(value_repr . ,(and (null error-object)
(ai-code-mcp-debug-tools--value-repr value)))
(value_type . ,(and (null error-object)
(symbol-name (type-of value))))
(messages . ,(vconcat
(ai-code-mcp-debug-tools--evaluation-messages
before-messages
capture-messages)))
(error . ,error-object)
(backtrace . ,backtrace)
(changed_buffers . ,(vconcat changed-buffers))
(context_after . ,(ai-code-mcp-debug-tools--context-summary
target-buffer))
(timed_out . ,(ai-code-mcp--json-bool timed-out)))))
(defun ai-code-mcp-debug-tools--run-eval (form target-buffer timeout-ms
capture-messages
include-backtrace)
"Evaluate FORM within TARGET-BUFFER using TIMEOUT-MS.
CAPTURE-MESSAGES controls message collection, and INCLUDE-BACKTRACE
keeps the backtrace on failures."
(let ((before-messages (ai-code-mcp--message-lines))
(before-snapshot (ai-code-mcp-debug-tools--modified-buffer-snapshot))
(value nil)
(timed-out nil)
(error-object nil)
(backtrace nil))
(condition-case err
(catch 'ai-code-mcp-debug-tools-timeout
(with-timeout ((/ (float timeout-ms) 1000.0)
(setq timed-out t)
(throw 'ai-code-mcp-debug-tools-timeout nil))
(setq value
(save-current-buffer
(with-current-buffer target-buffer
(eval form t))))))
(error
(setq error-object
(ai-code-mcp-debug-tools--error-alist
(symbol-name (car err))
(error-message-string err)))
(when include-backtrace
(setq backtrace (ai-code-mcp-debug-tools--backtrace-string)))))
(when timed-out
(setq error-object
(ai-code-mcp-debug-tools--error-alist
"timeout"
"Evaluation exceeded the configured timeout")))
(ai-code-mcp-debug-tools--encode-eval-result
target-buffer
before-messages
capture-messages
timed-out
value
(ai-code-mcp-debug-tools--changed-buffers before-snapshot)
error-object
backtrace)))
(defun ai-code-mcp--backtrace-frame-summary (frame)
"Return a readable summary string for backtrace FRAME."
(let ((function (nth 1 frame))
(arguments (nth 2 frame)))
(if arguments
(format "%S %S" function arguments)
(format "%S" function))))
(defun ai-code-mcp--capture-backtrace-summaries ()
"Return the current backtrace as a list of summary strings."
(mapcar #'ai-code-mcp--backtrace-frame-summary
(backtrace-frames)))
(defun ai-code-mcp--error-message (data)
"Return a friendly error message string for DATA."
(condition-case nil
(error-message-string data)
(error
(prin1-to-string data))))
(defun ai-code-mcp--record-command-error (data context signal)
"Record the command error DATA, CONTEXT, and SIGNAL for MCP tools."
(let ((frames (ai-code-mcp--capture-backtrace-summaries)))
(setq ai-code-mcp--last-error-record
`((error_symbol . ,(symbol-name (car data)))
(error_message . ,(ai-code-mcp--error-message data))
(context . ,(format "%s" context))
(signal . ,signal)
(timestamp . ,(format-time-string "%FT%T%z"))
(frame_count . ,(length frames))
(frames . ,frames)))))
(defun ai-code-mcp--ensure-error-capture ()
"Install error capture advice once for MCP debugging tools."
(unless ai-code-mcp--error-capture-installed
(advice-add 'command-error-default-function
:before
#'ai-code-mcp--record-command-error)
(setq ai-code-mcp--error-capture-installed t)))
(defun ai-code-mcp--find-existing-variable-symbol (variable-name)
"Return the interned symbol for VARIABLE-NAME, or nil when missing."
(and (stringp variable-name)
(intern-soft variable-name)))
(defun ai-code-mcp-get-variable-binding-info (variable-name &optional buffer-name)
"Return JSON binding details for VARIABLE-NAME in BUFFER-NAME."
(ai-code-mcp-debug-tools--require-enabled)
(let ((symbol (ai-code-mcp--find-existing-variable-symbol variable-name)))
(if (not symbol)
(json-encode
`((exists . :json-false)
(variable_name . ,variable-name)
(buffer_name . ,buffer-name)
(bound . :json-false)
(default_bound . :json-false)
(buffer_local . :json-false)
(current_value_repr . nil)
(default_value_repr . nil)
(documentation_summary . nil)))
(with-current-buffer (ai-code-mcp--resolve-buffer buffer-name)
(let ((bound (boundp symbol))
(default-bound (default-boundp symbol))
(buffer-local (local-variable-p symbol (current-buffer))))
(json-encode
`((exists . t)
(variable_name . ,variable-name)
(buffer_name . ,(buffer-name (current-buffer)))
(bound . ,(ai-code-mcp--json-bool bound))
(default_bound . ,(ai-code-mcp--json-bool default-bound))
(buffer_local . ,(ai-code-mcp--json-bool buffer-local))
(current_value_repr . ,(and bound
(ai-code-mcp-debug-tools--value-repr
(symbol-value symbol))))
(default_value_repr . ,(and default-bound
(ai-code-mcp-debug-tools--value-repr
(default-value symbol))))
(documentation_summary
. ,(ai-code-mcp--documentation-summary
(documentation-property symbol
'variable-documentation
t))))))))))
(defun ai-code-mcp-get-variable-value (variable-name)
"Return the printed representation of VARIABLE-NAME.
Return a friendly error string when VARIABLE-NAME does not name an
existing bound variable."
(ai-code-mcp-debug-tools--require-enabled)
(let ((symbol (ai-code-mcp--find-existing-variable-symbol variable-name)))
(cond
((not symbol)
(format "Variable not found: %s" variable-name))
((not (boundp symbol))
(format "Variable is unbound: %s" variable-name))
(t
(ai-code-mcp-debug-tools--value-repr (symbol-value symbol))))))
(defun ai-code-mcp--find-existing-function-symbol (function-name)
"Return the interned symbol for FUNCTION-NAME, or nil when missing."
(and (stringp function-name)
(intern-soft function-name)))
(defun ai-code-mcp--function-advised-p (symbol)
"Return non-nil when SYMBOL has active advice."
(let (advised)
(advice-mapc (lambda (&rest _args)
(setq advised t))
symbol)
advised))
(defun ai-code-mcp--function-root-definition (symbol)
"Return SYMBOL's root definition with advice wrappers removed."
(let ((definition (advice--symbol-function symbol)))
(if (advice--p definition)
(advice--cd*r definition)
definition)))
(defun ai-code-mcp--function-kind (symbol)
"Return a string describing SYMBOL's callable kind."
(let ((root-definition (ai-code-mcp--function-root-definition symbol)))
(cond
((autoloadp root-definition) "autoload")
((macrop symbol) "macro")
(t
(let ((resolved-definition (if (symbolp root-definition)
(indirect-function root-definition)
(indirect-function symbol))))
(cond
((subrp resolved-definition) "subr")
((or (functionp resolved-definition)
(and (consp resolved-definition)
(memq (car resolved-definition) (list 'lambda 'closure))))
"lambda")
(t "unknown")))))))
(defun ai-code-mcp-get-function-info (function-name)
"Return JSON metadata describing FUNCTION-NAME."
(ai-code-mcp-debug-tools--require-enabled)
(let ((symbol (ai-code-mcp--find-existing-function-symbol function-name)))
(if (not (and symbol (fboundp symbol)))
(json-encode
`((exists . :json-false)
(function_name . ,function-name)
(kind . nil)
(interactive . :json-false)
(advised . :json-false)
(aliased_to . nil)
(source_file . nil)
(documentation_summary . nil)))
(let* ((root-definition (ai-code-mcp--function-root-definition symbol))
(aliased-to (and (symbolp root-definition)
(symbol-name root-definition))))
(json-encode
`((exists . t)
(function_name . ,function-name)
(kind . ,(ai-code-mcp--function-kind symbol))
(interactive . ,(ai-code-mcp--json-bool (commandp symbol)))
(advised . ,(ai-code-mcp--json-bool
(ai-code-mcp--function-advised-p symbol)))
(aliased_to . ,aliased-to)
(source_file . ,(symbol-file symbol 'defun))
(documentation_summary
. ,(ai-code-mcp--documentation-summary
(documentation symbol t)))))))))
(defun ai-code-mcp--last-error-json-payload (record)
"Return a JSON-ready payload for a recorded error RECORD."
`((recorded . t)
(error_symbol . ,(alist-get 'error_symbol record))
(error_message . ,(alist-get 'error_message record))
(context . ,(alist-get 'context record))
(signal . ,(ai-code-mcp--json-bool (alist-get 'signal record)))
(timestamp . ,(alist-get 'timestamp record))
(frame_count . ,(alist-get 'frame_count record))
(frames . ,(vconcat (alist-get 'frames record)))))
(defun ai-code-mcp--empty-last-error-json-payload ()
"Return a JSON-ready payload when no error has been recorded."
`((recorded . :json-false)
(error_symbol . nil)
(error_message . nil)
(context . nil)
(signal . :json-false)
(timestamp . nil)
(frame_count . 0)
(frames . nil)))
(defun ai-code-mcp-get-last-error-backtrace ()
"Return a JSON snapshot of the most recently recorded Emacs error."
(ai-code-mcp-debug-tools--require-enabled)
(json-encode
(if ai-code-mcp--last-error-record
(ai-code-mcp--last-error-json-payload ai-code-mcp--last-error-record)
(ai-code-mcp--empty-last-error-json-payload))))
(defun ai-code-mcp--feature-providers (feature-symbol)
"Return `load-history' files that provided FEATURE-SYMBOL."
(let (providers)
(dolist (entry load-history (delete-dups (nreverse providers)))
(when (and (car entry)
(member `(provide . ,feature-symbol) (cdr entry)))
(push (car entry) providers)))))
(defun ai-code-mcp--feature-library-matches (feature-name)
"Return `load-path' files that look like FEATURE-NAME libraries."
(let (matches)
(dolist (directory load-path (delete-dups (nreverse matches)))
(when (stringp directory)
(dolist (suffix '(".el" ".elc" ".eln"))
(let ((candidate (expand-file-name (concat feature-name suffix)
directory)))
(when (file-exists-p candidate)
(push candidate matches))))))))
(defun ai-code-mcp--valid-feature-name-p (feature-name)
"Return non-nil when FEATURE-NAME is a non-empty string."
(and (stringp feature-name)
(not (string-empty-p feature-name))))
(defun ai-code-mcp--invalid-feature-load-state-payload (feature-name)
"Return a JSON payload for invalid FEATURE-NAME input."
`((feature_name . ,feature-name)
(loaded . :json-false)
(error_message . "feature_name must be a non-empty string")
(library_path . nil)
(provided_by_files . nil)
(load_path_matches . nil)))
(defun ai-code-mcp-get-feature-load-state (feature-name)
"Return JSON load-state details for FEATURE-NAME."
(ai-code-mcp-debug-tools--require-enabled)
(if (not (ai-code-mcp--valid-feature-name-p feature-name))
(json-encode
(ai-code-mcp--invalid-feature-load-state-payload feature-name))
(let* ((feature-symbol (intern-soft feature-name))
(loaded (and feature-symbol (featurep feature-symbol)))
(library-path (locate-library feature-name))
(providers (and feature-symbol
(ai-code-mcp--feature-providers feature-symbol))))
(json-encode
`((feature_name . ,feature-name)
(loaded . ,(ai-code-mcp--json-bool loaded))
(error_message . nil)
(library_path . ,library-path)
(provided_by_files . ,(vconcat providers))
(load_path_matches
. ,(vconcat (ai-code-mcp--feature-library-matches feature-name))))))))
(defun ai-code-mcp-debug-tools--hook-function-names (value)
"Return human-readable function names from hook VALUE, without closures."
(let ((entries (if (and (listp value) (not (functionp value)))
value
(and value (list value)))))
(vconcat
(mapcar (lambda (entry)
(cond
((eq entry t) "<inherit-global-hook>")
((symbolp entry) (symbol-name entry))
((functionp entry) "<anonymous-function>")
(t "<unknown-hook-entry>")))
entries))))
(defun ai-code-mcp-debug-tools--treesit-languages ()
"Return the unique language names of every tree-sitter parser here."
(when (and (fboundp 'treesit-parser-list)
(fboundp 'treesit-parser-language))
(delete-dups
(mapcar (lambda (parser)
(symbol-name (treesit-parser-language parser)))
;; Emacs 30+ hides tagged parsers unless TAG is t; Emacs 29
;; only accepts BUFFER. `apply' avoids an arity warning there.
(condition-case nil
(apply #'treesit-parser-list '(nil nil t))
(wrong-number-of-arguments (treesit-parser-list)))))))
(defun ai-code-mcp-get-buffer-runtime-state (&optional buffer-name hook-name)
"Report live buffer-local modes and an optional named HOOK-NAME.
Use BUFFER-NAME or the MCP prompt-origin buffer. Never invoke hooks,
load language servers, or print closure contents."
(ai-code-mcp-debug-tools--require-enabled)
(when (and hook-name
(not (and (stringp hook-name)
(string-match-p "-\\(?:hooks?\\|functions\\)\\'"
hook-name))))
(user-error "hook_name must end in -hook, -hooks or -functions"))
(let* ((context (ai-code-mcp-get-session-context))
(source (plist-get context :source-buffer))
(buffer (cond
(buffer-name
(or (get-buffer buffer-name)
(user-error "No such buffer: %s" buffer-name)))
((buffer-live-p source) source)
((not context) (current-buffer)))))
(if (not buffer)
(json-encode
'((ok . :json-false)
(status . "unavailable")
(reason . "Prompt source buffer is no longer live")))
(with-current-buffer buffer
(let* ((hook (and hook-name (intern-soft hook-name)))
(hook-bound (and hook (boundp hook)))
(hook-value (and hook-bound (symbol-value hook)))
(hook-local (and hook (local-variable-p hook)))
(inherits-global (and hook-local
(listp hook-value)
(memq t hook-value)))
(server (cond
((and (fboundp 'eglot-managed-p) (eglot-managed-p))
"eglot")
((bound-and-true-p lsp-mode) "lsp-mode")
(t nil))))
(json-encode
`((ok . t)
(buffer_name . ,(buffer-name buffer))
(file_path . ,(buffer-file-name buffer))
(major_mode . ,(symbol-name major-mode))
(active_minor_modes . ,(vconcat (mapcar #'symbol-name
local-minor-modes)))
(global_minor_modes . ,(vconcat (mapcar #'symbol-name
global-minor-modes)))
(language_server . ,server)
(tree_sitter_languages
. ,(vconcat (ai-code-mcp-debug-tools--treesit-languages)))
(flycheck_enabled . ,(ai-code-mcp--json-bool
(bound-and-true-p flycheck-mode)))
(flymake_enabled . ,(ai-code-mcp--json-bool
(bound-and-true-p flymake-mode)))
;; Hook fields are null when no hook was requested.
(hook_name . ,hook-name)
(hook_bound . ,(and hook-name
(ai-code-mcp--json-bool hook-bound)))
(hook_buffer_local . ,(and hook-name
(ai-code-mcp--json-bool hook-local)))
(hook_functions
. ,(and hook-name
(ai-code-mcp-debug-tools--hook-function-names
hook-value)))
;; A local `t' entry runs the global value too; list it so
;; agents see every function the hook actually calls.
(hook_global_functions
. ,(and hook-name
(ai-code-mcp-debug-tools--hook-function-names
(and inherits-global (default-value hook))))))))))))
(defun ai-code-mcp-get-recent-messages (&optional limit)
"Return a JSON payload for recent messages using LIMIT."
(ai-code-mcp-debug-tools--require-enabled)
(let* ((limit (or limit 50))
(messages (ai-code-mcp--message-lines)))
(unless (and (integerp limit) (> limit 0))
(error "Argument limit must be a positive integer"))
(setq messages (last messages (min limit (length messages))))
(json-encode
`((ok . t)
(limit . ,limit)
(messages . ,(vconcat messages))))))
(defun ai-code-mcp-eval-elisp (code &optional buffer-name file-path
capture-messages include-backtrace
timeout-ms)
"Evaluate CODE as a single Emacs Lisp form.
Return a JSON payload. BUFFER-NAME or FILE-PATH select the evaluation
context. CAPTURE-MESSAGES, INCLUDE-BACKTRACE, and TIMEOUT-MS control
diagnostics."
(ai-code-mcp-debug-tools--require-enabled)
(ai-code-mcp-debug-tools--require-eval-enabled)
(let* ((capture-messages (ai-code-mcp-debug-tools--bool-arg
capture-messages
t))
(include-backtrace (ai-code-mcp-debug-tools--bool-arg
include-backtrace
nil))
(timeout-ms (or timeout-ms 1000))
(target-buffer (ai-code-mcp-debug-tools--resolve-eval-buffer
buffer-name
file-path))
(parse-error nil)
form)
(unless (and (integerp timeout-ms) (> timeout-ms 0))
(error "Argument timeout_ms must be a positive integer"))
(condition-case err
(setq form (ai-code-mcp-debug-tools--parse-single-form code))
(error
(setq parse-error err)))
(if parse-error
(ai-code-mcp-debug-tools--encode-eval-result
target-buffer
(ai-code-mcp--message-lines)
capture-messages
nil
nil
'()
(ai-code-mcp-debug-tools--error-alist
(symbol-name (car parse-error))
(error-message-string parse-error))
(and include-backtrace
(ai-code-mcp-debug-tools--backtrace-string)))
(ai-code-mcp-debug-tools--run-eval
form
target-buffer
timeout-ms
capture-messages
include-backtrace))))
(add-to-list 'ai-code-mcp-server-tool-setup-functions
#'ai-code-mcp-debug-tools-setup)
(provide 'ai-code-mcp-debug-tools)
;;; ai-code-mcp-debug-tools.el ends here