-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathai-code-mcp-server.el
More file actions
1780 lines (1644 loc) · 76.6 KB
/
Copy pathai-code-mcp-server.el
File metadata and controls
1780 lines (1644 loc) · 76.6 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
;;; ai-code-mcp-server.el --- MCP tools core for AI Code Interface -*- lexical-binding: t; -*-
;; Author: Yoav Orot, Kang Tu, Andrew Morrow, AI Agent
;; SPDX-License-Identifier: Apache-2.0
;;; Commentary:
;; This module provides a transport-agnostic MCP tools core for AI Code
;; Interface. It handles tool registration, session context, method
;; dispatch, and a small built-in toolset that exposes common Emacs
;; project navigation, diagnostics, and code-intelligence capabilities.
;;; Code:
(require 'cl-lib)
(require 'json)
(require 'ai-code-mcp-common)
(require 'imenu)
(require 'project)
(require 'seq)
(require 'subr-x)
(require 'url-parse)
(require 'url-util)
(require 'xref)
(require 'flycheck nil t)
(require 'flymake nil t)
(require 'ai-code-input)
(declare-function treesit-available-p "treesit")
(declare-function treesit-parser-list "treesit")
(declare-function treesit-parser-root-node "treesit" (parser))
(declare-function treesit-node-at "treesit" (pos &optional parser-or-lang named))
(declare-function treesit-node-text "treesit" (node &optional no-property))
(declare-function treesit-node-type "treesit" (node))
(declare-function treesit-node-start "treesit" (node))
(declare-function treesit-node-end "treesit" (node))
(declare-function flycheck-error-line "flycheck" (err))
(declare-function flycheck-error-column "flycheck" (err))
(declare-function flycheck-error-end-line "flycheck" (err))
(declare-function flycheck-error-end-column "flycheck" (err))
(declare-function flycheck-error-level "flycheck" (err))
(declare-function flycheck-error-checker "flycheck" (err))
(declare-function flycheck-error-message "flycheck" (err))
(declare-function flycheck-running-p "flycheck")
(declare-function flymake-diagnostics "flymake" (&optional beg end))
(declare-function flymake-diagnostic-beg "flymake" (diag))
(declare-function flymake-diagnostic-end "flymake" (diag))
(declare-function flymake-diagnostic-type "flymake" (diag))
(declare-function flymake-diagnostic-backend "flymake" (diag))
(declare-function flymake-diagnostic-text "flymake" (diag))
(declare-function flymake-running-backends "flymake")
(declare-function url-filename "url-parse" (urlobj))
(declare-function url-generic-parse-url "url-parse" (url))
(declare-function url-host "url-parse" (urlobj))
(declare-function url-type "url-parse" (urlobj))
(defvar flycheck-current-errors)
(defvar flycheck-last-status-change)
(defgroup ai-code-mcp-server nil
"MCP tools core settings for AI Code Interface."
:group 'ai-code
:prefix "ai-code-mcp-")
(defcustom ai-code-mcp-server-tools nil
"List of MCP tool specifications.
Each item is a plist with at least `:function', `:name', and `:description'."
:type '(repeat sexp)
:group 'ai-code-mcp-server)
(defcustom ai-code-mcp-default-tool-profile 'debug
"Default MCP tool exposure profile.
The `core' profile exposes editor and project tools, `debug' additionally
exposes read-only Emacs inspection tools, and `full' also permits tools in the
`eval' category when their own explicit feature gate is enabled."
:type '(choice (const core) (const debug) (const full))
:group 'ai-code-mcp-server)
(defcustom ai-code-mcp-diagnostics-backend 'auto
"Backend used by `ai-code-mcp-get-diagnostics'.
Use `auto' to prefer Flycheck and then Flymake when available."
:type '(choice (const :tag "Automatic detection" auto)
(const :tag "Flycheck" flycheck)
(const :tag "Flymake" flymake))
:group 'ai-code-mcp-server)
(defcustom ai-code-mcp-diagnostics-max-report-diagnostics 200
"Maximum number of diagnostics listed in a `get_diagnostics' report.
When a report would exceed this many diagnostics, the observation envelope
lists only the first this-many and records the truncation in its summary, so a
large project cannot overflow the model context. The summary always reports
the true totals. Set to nil to disable truncation; otherwise the value must
be a non-negative integer."
:type '(choice (const :tag "No limit" nil) natnum)
:group 'ai-code-mcp-server)
(defvar ai-code-mcp--sessions (make-hash-table :test 'equal)
"Hash table mapping MCP session ids to session metadata.")
(defvar ai-code-mcp--current-session-id nil
"Dynamically bound MCP session id for the current tool invocation.")
(defvar ai-code-mcp--current-protocol-version nil
"Dynamically bound MCP version for the current request.")
(defvar ai-code-mcp--diagnostics-baselines (make-hash-table :test 'equal)
"Hash table mapping MCP session ids to recorded diagnostics baselines.
Each value is a hash table mapping diagnostic identity strings to counts.
The baseline lets `get_diagnostics' report only NEW diagnostics so the
agent can verify it introduced no regressions, without tracking the
baseline in the model context itself.")
(define-error 'ai-code-mcp-protocol-error "MCP protocol error")
(defun ai-code-mcp-signal-protocol-error (code message &optional data)
"Signal an MCP protocol error with CODE, MESSAGE, and optional DATA."
(signal 'ai-code-mcp-protocol-error (list code message data)))
(defconst ai-code-mcp--protocol-version "2025-11-25"
"Preferred initialization-based MCP protocol version.")
(defconst ai-code-mcp--modern-protocol-version "2026-07-28"
"Stateless MCP protocol version supported by the server.")
(defconst ai-code-mcp--legacy-protocol-versions
'("2025-11-25" "2025-06-18" "2025-03-26")
"Initialization-based MCP protocol versions supported by the server.")
(defconst ai-code-mcp--builtin-tool-specs
'((:function ai-code-mcp-project-info
:name "project_info"
:description "Get information about the current project context."
:args nil)
(:function ai-code-mcp-editor-state
:name "editor_state"
:description "Get the current editor state."
:args nil)
(:function ai-code-mcp-visible-buffers
:name "visible_buffers"
:description "List buffers visible in the selected frame."
:args nil)
(:function ai-code-mcp-buffer-query
:name "buffer_query"
:description "Read contents from an Emacs buffer by line range."
:args ((:name "buffer_name"
:type string
:description "Name of the buffer to read.")
(:name "start_line"
:type integer
:description "1-based first line to read."
:optional t)
(:name "num_lines"
:type integer
:description "Number of lines to read from start_line."
:optional t)))
(:function ai-code-mcp-get-diagnostics
:name "get_diagnostics"
:description "Get language diagnostics as an observation envelope (status, summary, files, next_actions, artifacts) for a file or the active project. Pass since=\"baseline\" to report only diagnostics that are new since diagnostics_baseline was called."
:args ((:name "uri"
:type string
:description "Optional file URI to inspect."
:optional t)
(:name "since"
:type string
:description "Optional. Use \"baseline\" to report only diagnostics new since the last diagnostics_baseline call."
:optional t)))
(:function ai-code-mcp-diagnostics-baseline
:name "diagnostics_baseline"
:description "Record current project diagnostics as a baseline. After editing, call get_diagnostics with since=\"baseline\" to verify no new diagnostics were introduced."
:args nil)
(:function ai-code-mcp-get-project-files
:name "get_project_files"
:description "List regular files in the current project."
:args nil)
(:function ai-code-mcp-get-project-buffers
:name "get_project_buffers"
:description "List open buffers that belong to the current project."
:args nil)
(:function ai-code-mcp-notify-user
:name "notify_user"
:description "Show a notification to the Emacs user."
:args ((:name "message_text"
:type string
:description "Notification text to show in Emacs.")))
(:function ai-code-mcp-imenu-list-symbols
:name "imenu_list_symbols"
:description "List useful symbols in a file via imenu."
:args ((:name "file_path"
:type string
:description "Path to the file to inspect.")))
(:function ai-code-mcp-xref-find-references
:name "xref_find_references"
:description "Find references to an identifier in project context."
:args ((:name "identifier"
:type string
:description "Identifier to resolve.")
(:name "file_path"
:type string
:description "Path to the file that provides backend context.")))
(:function ai-code-mcp-xref-find-definitions-at-point
:name "xref_find_definitions_at_point"
:description "Find definitions of the identifier at a file location."
:args ((:name "file_path"
:type string
:description "Path to the file that provides backend context.")
(:name "line"
:type integer
:description "1-based line number.")
(:name "column"
:type integer
:description "0-based column number.")))
(:function ai-code-mcp-treesit-info
:name "treesit_info"
:description "Return tree-sitter node information for a file location."
:args ((:name "file_path"
:type string
:description "Path to the file to inspect.")
(:name "line"
:type integer
:description "1-based line number."
:optional t)
(:name "column"
:type integer
:description "0-based column number."
:optional t)
(:name "whole_file"
:type boolean
:description "When non-nil, inspect the root node."
:optional t))))
"Built-in MCP tool specifications.
The default tool list includes:
- `project_info'
- `editor_state'
- `visible_buffers'
- `buffer_query'
- `get_diagnostics'
- `diagnostics_baseline'
- `get_project_files'
- `get_project_buffers'
- `notify_user'
- `imenu_list_symbols'
- `xref_find_references'
- `xref_find_definitions_at_point'
- `treesit_info'")
(defun ai-code-mcp-make-tool (&rest slots)
"Create an MCP tool specification from SLOTS and register it.
Required keys are `:function', `:name', and `:description'."
(let ((function (plist-get slots :function))
(name (plist-get slots :name))
(description (plist-get slots :description))
(args (plist-get slots :args))
(category (plist-get slots :category))
(annotations (plist-get slots :annotations))
(output-schema (plist-get slots :output-schema))
spec)
(unless function
(error "Tool :function is required"))
(unless name
(error "Tool :name is required"))
(unless description
(error "Tool :description is required"))
(setq spec (list :function function
:name name
:description description))
(when args
(setq spec (plist-put spec :args args)))
(when category
(setq spec (plist-put spec :category category)))
(when annotations
(setq spec (plist-put spec :annotations annotations)))
(when output-schema
(setq spec (plist-put spec :output-schema output-schema)))
(setq ai-code-mcp-server-tools
(append
(seq-remove
(lambda (tool)
(equal (plist-get tool :name) name))
ai-code-mcp-server-tools)
(list spec)))
spec))
(defun ai-code-mcp-register-session (session-id project-dir buffer &optional metadata)
"Register MCP SESSION-ID with PROJECT-DIR, source BUFFER, and METADATA."
(let ((context (list :project-dir project-dir
:buffer buffer
:source-buffer buffer
:state 'ready
:start-time (current-time))))
(while metadata
(setq context (plist-put context (pop metadata) (pop metadata))))
(puthash session-id context ai-code-mcp--sessions)
(ai-code-mcp-update-source-context session-id buffer)))
(defun ai-code-mcp-unregister-session (session-id)
"Unregister MCP SESSION-ID and free its recorded diagnostics baseline."
(remhash session-id ai-code-mcp--sessions)
(remhash session-id ai-code-mcp--diagnostics-baselines))
(defun ai-code-mcp-get-session-context (&optional session-id)
"Return session context for SESSION-ID or the current session."
(gethash (or session-id ai-code-mcp--current-session-id)
ai-code-mcp--sessions))
(defun ai-code-mcp-session-count ()
"Return the number of registered MCP application sessions."
(hash-table-count ai-code-mcp--sessions))
(defun ai-code-mcp-find-session-by-token (token)
"Return the session id and context authenticated by TOKEN."
(when (stringp token)
(catch 'found
(maphash
(lambda (session-id context)
(when (and (stringp (plist-get context :token))
(string= token (plist-get context :token))
(not (ai-code-mcp--session-expired-p context)))
(throw 'found (cons session-id context))))
ai-code-mcp--sessions)
nil)))
(defun ai-code-mcp--session-expired-p (context)
"Return non-nil when CONTEXT has passed its authentication expiry."
(when-let ((expires-at (plist-get context :expires-at)))
(time-less-p expires-at (current-time))))
(defun ai-code-mcp-update-source-context (session-id source-buffer)
"Snapshot SOURCE-BUFFER as the prompt origin for SESSION-ID."
(let ((context (ai-code-mcp-get-session-context session-id)))
(unless context
(error "Unknown MCP session: %s" session-id))
(unless (buffer-live-p source-buffer)
(error "MCP source buffer is not live"))
(let ((snapshot
(with-current-buffer source-buffer
(let ((position (ai-code-mcp--point-line-column
source-buffer (point))))
(list :buffer source-buffer
:point (point)
:line (alist-get 'line position)
:column (alist-get 'column position)
:modification-tick (buffer-chars-modified-tick)
:captured-at (current-time))))))
(setq context (plist-put context :buffer source-buffer))
(setq context (plist-put context :source-buffer source-buffer))
(setq context (plist-put context :source-snapshot snapshot))
(setq context (plist-put context :updated-at (current-time)))
(puthash session-id context ai-code-mcp--sessions)
context)))
(defun ai-code-mcp-attach-agent-buffer (session-id agent-buffer)
"Attach AGENT-BUFFER to SESSION-ID without replacing its source."
(let ((context (ai-code-mcp-get-session-context session-id)))
(unless context
(error "Unknown MCP session: %s" session-id))
(setq context (plist-put context :agent-buffer agent-buffer))
(setq context (plist-put context :state 'ready))
(setq context (plist-put context :updated-at (current-time)))
(puthash session-id context ai-code-mcp--sessions)
context))
(defun ai-code-mcp-begin-legacy-session
(session-id transport-session-id protocol-version client-info)
"Begin legacy MCP initialization for SESSION-ID.
TRANSPORT-SESSION-ID identifies subsequent HTTP requests, while
PROTOCOL-VERSION and CLIENT-INFO record the negotiated client metadata."
(let ((context (ai-code-mcp-get-session-context session-id)))
(unless context
(error "Unknown MCP session: %s" session-id))
(setq context (plist-put context :transport-session-id transport-session-id))
(setq context (plist-put context :protocol-version protocol-version))
(setq context (plist-put context :client-info client-info))
(setq context (plist-put context :state 'initializing))
(setq context (plist-put context :updated-at (current-time)))
(puthash session-id context ai-code-mcp--sessions)
context))
(defun ai-code-mcp-complete-legacy-session
(session-id transport-session-id protocol-version)
"Complete legacy initialization for SESSION-ID.
TRANSPORT-SESSION-ID and PROTOCOL-VERSION must match the initialized session."
(let ((context (ai-code-mcp-get-session-context session-id)))
(unless (and context
(eq (plist-get context :state) 'initializing)
(equal transport-session-id
(plist-get context :transport-session-id))
(equal protocol-version (plist-get context :protocol-version)))
(error "Invalid MCP initialized notification"))
(setq context (plist-put context :state 'ready))
(setq context (plist-put context :updated-at (current-time)))
(puthash session-id context ai-code-mcp--sessions)
context))
(defmacro ai-code-mcp-with-session-context (session-id &rest body)
"Run BODY with SESSION-ID project context."
(declare (indent 1))
`(let* ((context (ai-code-mcp-get-session-context ,session-id))
(project-dir (plist-get context :project-dir))
(buffer (plist-get context :buffer)))
(if (and buffer (buffer-live-p buffer))
(with-current-buffer buffer
(let ((default-directory (if project-dir
(file-name-as-directory project-dir)
default-directory)))
,@body))
(let ((default-directory (if project-dir
(file-name-as-directory project-dir)
default-directory)))
,@body))))
(defun ai-code-mcp-dispatch (method &optional params)
"Dispatch MCP METHOD using PARAMS."
(pcase method
("initialize" (ai-code-mcp--initialize params))
("server/discover" (ai-code-mcp--discover))
("ping" '())
("tools/list" (ai-code-mcp--tools-list))
("tools/call" (ai-code-mcp--tools-call params))
(_ (ai-code-mcp-signal-protocol-error
-32601 (format "Method not found: %s" method)))))
(defun ai-code-mcp-builtins-setup ()
"Register the built-in common Emacs MCP tools."
(interactive)
(dolist (tool ai-code-mcp--builtin-tool-specs)
(apply #'ai-code-mcp-make-tool
(append tool
(list :category 'core
:annotations
(ai-code-mcp--builtin-tool-annotations
(plist-get tool :name))))))
(dolist (setup-fn ai-code-mcp-server-tool-setup-functions)
(funcall setup-fn)))
(defun ai-code-mcp--builtin-tool-annotations (name)
"Return effect annotations for built-in tool NAME."
(let ((read-only (not (member name '("diagnostics_baseline"
"notify_user")))))
`((title . ,(capitalize (string-replace "_" " " name)))
(readOnlyHint . ,(ai-code-mcp--json-bool read-only))
(destructiveHint . :json-false)
(idempotentHint . ,(ai-code-mcp--json-bool read-only))
(openWorldHint . :json-false))))
(defun ai-code-mcp--ensure-builtins ()
"Ensure built-in MCP tools are registered."
(unless (ai-code-mcp--find-tool-spec "project_info")
(ai-code-mcp-builtins-setup)))
(defun ai-code-mcp-project-info ()
"Return a short textual description of the active project context."
(let* ((project-dir (ai-code-mcp--project-directory))
(active-buffer (current-buffer))
(file-count (ai-code-mcp--count-project-files project-dir)))
(format "Project: %s\nBuffer: %s\nFiles: %d"
project-dir
(if (buffer-live-p active-buffer)
(buffer-name active-buffer)
"No active buffer")
file-count)))
(defun ai-code-mcp--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--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--region-state (buffer point)
"Return region metadata for BUFFER at POINT."
(with-current-buffer buffer
(let ((mark (mark t)))
(if (and mark mark-active)
(let* ((start (min point mark))
(end (max point mark))
(start-pos (ai-code-mcp--point-line-column buffer start))
(end-pos (ai-code-mcp--point-line-column buffer end)))
`((region_active . t)
(region . ((start . ,start-pos)
(end . ,end-pos)))))
'((region_active . :json-false)
(region . nil))))))
(defun ai-code-mcp--editor-state-data ()
"Return an alist describing the active session source buffer."
(let* ((context (ai-code-mcp-get-session-context))
(source-buffer (plist-get context :buffer))
(source-snapshot (plist-get context :source-snapshot))
(window (ai-code-mcp--selected-window)))
(if (and context (not (buffer-live-p source-buffer)))
'((ok . :json-false)
(status . "unavailable")
(reason . "Prompt source buffer is no longer live"))
(let* ((buffer (if (buffer-live-p source-buffer)
source-buffer
(window-buffer window)))
(point (if (and (eq buffer source-buffer) source-snapshot)
(plist-get source-snapshot :point)
(window-point window)))
(position (if (and (eq buffer source-buffer) source-snapshot)
`((line . ,(plist-get source-snapshot :line))
(column . ,(plist-get source-snapshot :column)))
(ai-code-mcp--point-line-column buffer point)))
(region-point (with-current-buffer buffer
(min point (point-max))))
(region-state (ai-code-mcp--region-state buffer region-point)))
(with-current-buffer buffer
`((ok . t)
(buffer_name . ,(buffer-name buffer))
(file_path . ,(buffer-file-name buffer))
(major_mode . ,(symbol-name major-mode))
(modified . ,(ai-code-mcp--json-bool
(buffer-modified-p)))
(read_only . ,(ai-code-mcp--json-bool buffer-read-only))
(narrowed . ,(ai-code-mcp--json-bool
(buffer-narrowed-p)))
(point . ,point)
(line . ,(alist-get 'line position))
(column . ,(alist-get 'column position))
(region_active . ,(alist-get 'region_active region-state))
(region . ,(alist-get 'region region-state))
(default_directory . ,default-directory)))))))
(defun ai-code-mcp-editor-state ()
"Return a JSON payload for the current editor state."
(json-encode (ai-code-mcp--editor-state-data)))
(defun ai-code-mcp--visible-buffer-entry (window index)
"Return a visible buffer entry for WINDOW at INDEX."
(let* ((buffer (window-buffer window))
(point (window-point window))
(position (ai-code-mcp--point-line-column buffer point)))
(with-current-buffer buffer
`((index . ,index)
(buffer_name . ,(buffer-name buffer))
(file_path . ,(buffer-file-name buffer))
(major_mode . ,(symbol-name major-mode))
(modified . ,(ai-code-mcp--json-bool
(buffer-modified-p)))
(line . ,(alist-get 'line position))
(column . ,(alist-get 'column position))))))
(defun ai-code-mcp-visible-buffers ()
"Return a JSON payload for visible buffers."
(let* ((selected-window (ai-code-mcp--selected-window))
(windows (window-list (selected-frame) 'no-minibuffer))
(entries (cl-mapcar #'ai-code-mcp--visible-buffer-entry
windows
(number-sequence 0 (1- (length windows)))))
(selected-index (or (cl-position selected-window windows) 0)))
(json-encode
`((ok . t)
(selected_index . ,selected-index)
(items . ,(vconcat entries))))))
(defun ai-code-mcp--validate-buffer-query-range (start-line num-lines)
"Validate optional buffer query range arguments START-LINE and NUM-LINES."
(when (or (and start-line (not num-lines))
(and num-lines (not start-line)))
(error "Arguments start_line and num_lines must both be provided or both be omitted"))
(when (and start-line
(or (< start-line 1)
(< num-lines 1)))
(error "Arguments start_line and num_lines must be positive integers")))
(defun ai-code-mcp--drop-trailing-newline (text)
"Return TEXT without a single trailing newline."
(if (string-suffix-p "\n" text)
(substring text 0 -1)
text))
(defun ai-code-mcp-buffer-query (buffer-name &optional start-line num-lines)
"Return contents from BUFFER-NAME.
When START-LINE and NUM-LINES are non-nil, return only that line range."
(let ((buffer (get-buffer buffer-name)))
(if (not buffer)
(format "Error: Buffer not found: %s" buffer-name)
(ai-code-mcp--validate-buffer-query-range start-line num-lines)
(with-current-buffer buffer
(save-excursion
(if (not start-line)
(buffer-substring-no-properties (point-min) (point-max))
(goto-char (point-min))
(forward-line (1- start-line))
(let ((start-pos (point)))
(forward-line num-lines)
(ai-code-mcp--drop-trailing-newline
(buffer-substring-no-properties start-pos (point))))))))))
(defun ai-code-mcp-get-diagnostics (&optional uri since)
"Return a JSON diagnostics observation envelope for URI or the project.
The envelope includes coverage and freshness metadata so an unavailable or
still-running diagnostics backend cannot be mistaken for a clean result.
When SINCE is the string \"baseline\", report only diagnostics that are new
relative to the baseline recorded by `ai-code-mcp-diagnostics-baseline'."
(let* ((observation (if uri
(ai-code-mcp--diagnostics-for-uri uri)
(ai-code-mcp--diagnostics-for-project)))
(entries (plist-get observation :entries))
(delta (and (stringp since) (string-equal since "baseline"))))
(json-encode
(cond
((and delta (not (ai-code-mcp--diagnostics-baseline-recorded-p)))
(ai-code-mcp--diagnostics-no-baseline-envelope observation))
(delta
(ai-code-mcp--diagnostics-envelope
(ai-code-mcp--diagnostics-new-since-baseline entries)
'delta
observation))
(t
(ai-code-mcp--diagnostics-envelope entries 'current observation))))))
(defun ai-code-mcp--diagnostics-summary (entries)
"Return a one-line human summary string for diagnostics ENTRIES."
(let ((file-count (length entries))
(total 0)
(errors 0)
(warnings 0))
(dolist (entry entries)
(seq-doseq (diagnostic (alist-get 'diagnostics entry))
(setq total (1+ total))
(pcase (alist-get 'severity diagnostic)
("Error" (setq errors (1+ errors)))
("Warning" (setq warnings (1+ warnings))))))
(if (zerop total)
"No diagnostics found."
(format "%d diagnostic%s across %d file%s (%d Error, %d Warning)."
total (if (= total 1) "" "s")
file-count (if (= file-count 1) "" "s")
errors warnings))))
(defun ai-code-mcp--diagnostic-action-line (uri diagnostic)
"Return a one-line fix suggestion for DIAGNOSTIC located via URI."
(let* ((range (alist-get 'range diagnostic))
(start (alist-get 'start range))
(line (alist-get 'line start))
(column (alist-get 'character start))
(severity (alist-get 'severity diagnostic))
(message (alist-get 'message diagnostic))
(path (or (ignore-errors
(ai-code-mcp--display-path
(ai-code-mcp--uri-to-file-path uri)))
uri)))
(format "Fix %s at %s:%s:%s - %s"
(or severity "issue") path (or line "?") (or column "?")
(or message ""))))
(defun ai-code-mcp--diagnostics-next-actions (entries)
"Return a vector of fix suggestions for diagnostics ENTRIES."
(let (actions)
(dolist (entry entries)
(let ((uri (alist-get 'uri entry)))
(seq-doseq (diagnostic (alist-get 'diagnostics entry))
(push (ai-code-mcp--diagnostic-action-line uri diagnostic) actions))))
(vconcat (nreverse actions))))
(defun ai-code-mcp--cap-diagnostics-entries (entries limit)
"Return ENTRIES truncated to at most LIMIT total diagnostics.
The return value is a cons (CAPPED-ENTRIES . SHOWN-COUNT). Whole and partial
file entries beyond LIMIT are dropped so the listed diagnostics never exceed
LIMIT. When LIMIT is nil, ENTRIES are returned unchanged."
(if (null limit)
(cons entries (ai-code-mcp--diagnostics-total-count entries))
(let ((remaining (max limit 0))
capped)
(dolist (entry entries)
(when (> remaining 0)
(let* ((diagnostics (append (alist-get 'diagnostics entry) nil))
(take (min remaining (length diagnostics))))
(when (> take 0)
(push `((uri . ,(alist-get 'uri entry))
(diagnostics . ,(vconcat (seq-take diagnostics take))))
capped)
(setq remaining (- remaining take))))))
(cons (nreverse capped) (- (max limit 0) remaining)))))
(defun ai-code-mcp--diagnostics-truncation-note (shown total context)
"Return a truncation note describing SHOWN of TOTAL diagnostics for CONTEXT.
In the `delta' context the caller is already filtering with since=\"baseline\",
so the note only points to per-file (uri) narrowing. In the `current' context
it also offers since=\"baseline\" as a way to focus on newly introduced
diagnostics -- not as a way to page through the omitted ones."
(let ((plural (if (= total 1) "" "s")))
(if (eq context 'delta)
(format " Listing %d of %d new diagnostic%s here;\
request a specific file by uri to see the rest."
shown total plural)
(format " Listing %d of %d diagnostic%s here; request a specific\
file by uri to see the rest, or use since=\"baseline\"\
to focus on diagnostics you introduced."
shown total plural))))
(defun ai-code-mcp--diagnostics-observation-count (observation predicate)
"Count targets in OBSERVATION that satisfy PREDICATE."
(cl-count-if predicate (plist-get observation :targets)))
(defun ai-code-mcp--diagnostics-observation-complete-p (observation)
"Return non-nil when OBSERVATION covers every requested target.
A nil observation represents a compatibility caller that supplied diagnostic
entries directly and is therefore treated as complete."
(or (null observation)
(let ((targets (plist-get observation :targets)))
(and targets
(cl-every (lambda (target)
(eq (plist-get target :state) 'ready))
targets)))))
(defun ai-code-mcp--diagnostics-backend-counts (observation)
"Return sorted backend coverage entries for OBSERVATION."
(let ((counts (make-hash-table :test 'eq))
pairs)
(dolist (target (plist-get observation :targets))
(when-let ((backend (plist-get target :backend)))
(puthash backend (1+ (gethash backend counts 0)) counts)))
(maphash (lambda (backend count)
(push (cons backend count) pairs))
counts)
(vconcat
(mapcar (lambda (pair)
`((name . ,(symbol-name (car pair)))
(files . ,(cdr pair))))
(sort pairs
(lambda (left right)
(string< (symbol-name (car left))
(symbol-name (car right)))))))))
(defun ai-code-mcp--diagnostics-coverage-data (observation)
"Return JSON-ready diagnostics coverage metadata for OBSERVATION."
(let* ((targets (plist-get observation :targets))
(requested (length targets))
(checked (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target) (plist-get target :backend))))
(unavailable (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target)
(eq (plist-get target :state) 'unavailable))))
(running (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target)
(eq (plist-get target :state) 'running))))
(complete (ai-code-mcp--diagnostics-observation-complete-p
observation))
(unavailable-targets
(delq nil
(mapcar
(lambda (target)
(when (eq (plist-get target :state) 'unavailable)
`((uri . ,(plist-get target :uri))
(reason . ,(plist-get target :reason)))))
targets))))
(append
`((scope . ,(or (plist-get observation :scope) "supplied_entries"))
(requested_files . ,requested)
(checked_files . ,checked)
(unavailable_files . ,unavailable)
(running_files . ,running)
(complete . ,(ai-code-mcp--json-bool complete))
(backends . ,(ai-code-mcp--diagnostics-backend-counts observation))
(unavailable . ,(vconcat unavailable-targets)))
(when-let ((reason (plist-get observation :reason)))
`((reason . ,reason))))))
(defun ai-code-mcp--diagnostics-freshness-data (observation)
"Return JSON-ready snapshot metadata for diagnostics OBSERVATION."
(let* ((targets (plist-get observation :targets))
(modified (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target) (plist-get target :modified))))
(buffers
(mapcar
(lambda (target)
`((uri . ,(plist-get target :uri))
(backend . ,(if-let ((backend (plist-get target :backend)))
(symbol-name backend)
:null))
(state . ,(symbol-name (plist-get target :state)))
(modified . ,(ai-code-mcp--json-bool
(plist-get target :modified)))
(modification_tick
. ,(or (plist-get target :modification-tick) :null))))
targets)))
`((observed_at . ,(or (plist-get observation :observed-at)
(format-time-string "%Y-%m-%dT%H:%M:%SZ" nil t)))
(modified_files . ,modified)
(buffers . ,(vconcat buffers)))))
(defun ai-code-mcp--diagnostics-coverage-summary (observation)
"Return a concise coverage warning for OBSERVATION, or nil."
(unless (ai-code-mcp--diagnostics-observation-complete-p observation)
(let* ((targets (plist-get observation :targets))
(requested (length targets))
(checked (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target) (plist-get target :backend))))
(running (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target)
(eq (plist-get target :state) 'running)))))
(cond
((zerop requested)
" Diagnostics unavailable: no open project buffers were in scope.")
((zerop checked)
(format " Diagnostics unavailable: no active checker covered the %d requested file%s."
requested (if (= requested 1) "" "s")))
(t
(format " Diagnostics coverage incomplete: checked %d of %d requested file%s%s."
checked requested (if (= requested 1) "" "s")
(if (> running 0)
(format "; %d checker%s still running"
running (if (= running 1) " is" "s are"))
"")))))))
(defun ai-code-mcp--diagnostics-coverage-actions (observation)
"Return actions needed to complete diagnostics OBSERVATION coverage."
(unless (ai-code-mcp--diagnostics-observation-complete-p observation)
(let ((running (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target)
(eq (plist-get target :state) 'running))))
(unavailable (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target)
(eq (plist-get target :state) 'unavailable)))))
(delq nil
(list
(when (> unavailable 0)
"Enable Flymake or Flycheck for each unavailable buffer, then run get_diagnostics again.")
(when (> running 0)
"Wait for running diagnostics backends to finish, then run get_diagnostics again.")
(when (zerop (length (plist-get observation :targets)))
"Open the project files to inspect and enable Flymake or Flycheck before retrying."))))))
(defun ai-code-mcp--diagnostics-envelope (entries &optional context observation)
"Return a diagnostics observation envelope alist for ENTRIES.
CONTEXT is `current' (default) or `delta'. In the `delta' context the
status and summary describe diagnostics that are new since the baseline
and express the done-condition the agent must reach (new == 0).
OBSERVATION supplies coverage and freshness metadata for the scan.
The listed `files' and `next_actions' are capped at
`ai-code-mcp-diagnostics-max-report-diagnostics' so a large project cannot
overflow the model context; the summary always reports the true totals and
notes any truncation."
(let* ((total (ai-code-mcp--diagnostics-total-count entries))
(has-issues (> total 0))
(complete (ai-code-mcp--diagnostics-observation-complete-p
observation))
(checked (ai-code-mcp--diagnostics-observation-count
observation
(lambda (target) (plist-get target :backend))))
(capped-cell (ai-code-mcp--cap-diagnostics-entries
entries ai-code-mcp-diagnostics-max-report-diagnostics))
(capped (car capped-cell))
(shown (cdr capped-cell))
(truncated (> total shown))
(status (cond
(has-issues (if (eq context 'delta) "regression" "issues"))
(complete "clean")
((zerop checked) "unavailable")
(t "incomplete")))
(base-summary (cond
((eq context 'delta)
(cond
(has-issues
(concat (ai-code-mcp--diagnostics-summary entries)
" These are NEW versus the baseline;"
" not done until new == 0."))
(complete
(concat "No new diagnostics versus the baseline;"
" done-condition met (new == 0)."))
(t
(concat "No new diagnostics were observed versus"
" the baseline, but coverage is incomplete;"
" the done-condition is not established."))))
(t (ai-code-mcp--diagnostics-summary entries))))
(coverage-summary
(ai-code-mcp--diagnostics-coverage-summary observation))
(summary (concat
base-summary
(or coverage-summary "")
(if truncated
(ai-code-mcp--diagnostics-truncation-note
shown total context)
"")))
(actions (append
(append (ai-code-mcp--diagnostics-next-actions capped) nil)
(ai-code-mcp--diagnostics-coverage-actions observation))))
`((status . ,status)
(summary . ,summary)
(files . ,(vconcat capped))
(next_actions . ,(vconcat actions))
(coverage . ,(ai-code-mcp--diagnostics-coverage-data observation))
(freshness . ,(ai-code-mcp--diagnostics-freshness-data observation))
(artifacts . ,(vconcat nil)))))
(defun ai-code-mcp--diagnostics-baseline-key ()
"Return the baseline storage key for the active MCP session."
(or ai-code-mcp--current-session-id "default"))
(defun ai-code-mcp--diagnostics-baseline-recorded-p ()
"Return non-nil when a diagnostics baseline exists for the active session."
(and (gethash (ai-code-mcp--diagnostics-baseline-key)
ai-code-mcp--diagnostics-baselines)
t))
(defun ai-code-mcp--diagnostics-total-count (entries)
"Return the total number of diagnostics across ENTRIES."
(let ((total 0))
(dolist (entry entries total)
(setq total (+ total (length (alist-get 'diagnostics entry)))))))
(defun ai-code-mcp--diagnostics-no-baseline-envelope (&optional observation)
"Return an envelope explaining that no diagnostics baseline was recorded.
This avoids reporting pre-existing diagnostics as regressions when the agent
requests `since=\"baseline\"' without first calling `diagnostics_baseline'.
OBSERVATION supplies metadata about the attempted diagnostics scan."
`((status . "no_baseline")
(summary . ,(concat "No diagnostics baseline recorded for this session;"
" current diagnostics are not reported as regressions."))
(files . ,(vconcat nil))
(next_actions . ,(vector
(concat "Call the diagnostics_baseline MCP tool, then"
" re-run get_diagnostics with since=\"baseline\".")))
(coverage . ,(ai-code-mcp--diagnostics-coverage-data observation))
(freshness . ,(ai-code-mcp--diagnostics-freshness-data observation))
(artifacts . ,(vconcat nil))))
(defun ai-code-mcp--diagnostic-identity (uri diagnostic)
"Return a stable identity string for DIAGNOSTIC located in URI.
Position is intentionally excluded so edits that shift line numbers do not
make a pre-existing diagnostic look new. Multiplicity is tracked by the
baseline count table, so duplicate diagnostics beyond the recorded count
are still reported as new."
(format "%s\0%s\0%s\0%s"
(or uri "")
(or (alist-get 'severity diagnostic) "")
(or (alist-get 'source diagnostic) "")
(or (alist-get 'message diagnostic) "")))
(defun ai-code-mcp--diagnostics-identity-counts (entries)
"Return a hash table of identity counts for diagnostics ENTRIES."
(let ((counts (make-hash-table :test 'equal)))
(dolist (entry entries counts)
(let ((uri (alist-get 'uri entry)))
(seq-doseq (diagnostic (alist-get 'diagnostics entry))
(let ((identity (ai-code-mcp--diagnostic-identity uri diagnostic)))
(puthash identity (1+ (gethash identity counts 0)) counts)))))))
(defun ai-code-mcp--diagnostics-new-since-baseline (entries)
"Return ENTRIES filtered to diagnostics absent from the session baseline.
When no baseline has been recorded, return ENTRIES unchanged."
(let ((baseline (gethash (ai-code-mcp--diagnostics-baseline-key)
ai-code-mcp--diagnostics-baselines)))
(if (null baseline)
entries
(let ((remaining (copy-hash-table baseline)))
(delq nil
(mapcar
(lambda (entry)
(let* ((uri (alist-get 'uri entry))
(new (delq nil
(mapcar
(lambda (diagnostic)
(let* ((identity
(ai-code-mcp--diagnostic-identity
uri diagnostic))
(count (gethash identity
remaining 0)))
(if (> count 0)
(progn
(puthash identity (1- count)
remaining)
nil)
diagnostic)))
(append (alist-get 'diagnostics entry)
nil)))))
(when new
`((uri . ,uri)
(diagnostics . ,(vconcat new))))))
entries))))))
(defun ai-code-mcp--diagnostics-source-counts (entries)
"Return an alist of (SOURCE . COUNT) for ENTRIES, ordered by descending count."
(let ((counts (make-hash-table :test 'equal))
pairs)
(dolist (entry entries)
(seq-doseq (diagnostic (alist-get 'diagnostics entry))
(let ((source (or (alist-get 'source diagnostic) "unknown")))
(puthash source (1+ (gethash source counts 0)) counts))))
(maphash (lambda (source count) (push (cons source count) pairs)) counts)