Repository navigation
Expand file tree
/
Copy pathai-code-mcp-server.el
More file actions
2424 lines (2258 loc) · 107 KB
/
Copy pathai-code-mcp-server.el
File metadata and controls
2424 lines (2258 loc) · 107 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 'thingatpt)
(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-buffer "flycheck")
(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-reporting-backends "flymake")
(declare-function flymake-running-backends "flymake")
(declare-function flymake-start "flymake" (&optional deferred force))
(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)
(defcustom ai-code-mcp-buffer-query-default-max-chars 16000
"Default output cap for `buffer_query' when the caller sets no limit.
A whole-buffer read with no `max_chars' is capped at this many
characters and explicitly marked truncated, so one call on a large
buffer (a log, *Messages*, a data file) cannot overflow the model
context. Set to nil to restore uncapped whole-buffer reads."
:type '(choice (const :tag "No default limit" nil) positive-integer)
:group 'ai-code-mcp-server)
(defcustom ai-code-mcp-project-files-max-report 1000
"Maximum number of files listed by the `get_project_files' tool.
When a project has more files, the report is truncated to this many
entries and a final marker entry records the true total. 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)
(defcustom ai-code-mcp-tool-call-log-enabled t
"When non-nil, record every MCP tool call in the audit log.
The log records the tool name, argument names (never argument values),
the session id, the result size, the duration, and the error type
\(never the error message, which may embed argument values).
Inspect it with `ai-code-mcp-show-tool-call-log' and clear it with
`ai-code-mcp-clear-tool-call-log'."
:type 'boolean
:group 'ai-code-mcp-server)
(defcustom ai-code-mcp-tool-call-log-max-entries 500
"Maximum number of entries kept in the MCP tool-call audit log.
Older entries are dropped once the log grows past this many calls."
:type 'natnum
:group 'ai-code-mcp-server)
(defvar ai-code-mcp--tool-call-log nil
"MCP tool-call audit log entries, newest first.
Each entry is a plist with `:time', `:session', `:tool', `:args',
`:status', `:result-chars', `:error', and `:duration-ms'.")
(defconst ai-code-mcp--tool-call-log-buffer-name "*AI Code MCP Log*"
"Buffer name used to display the MCP tool-call audit log.")
(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."
:plain-text t
: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 live buffer text: whole buffer, a line range, or an exact line/column range."
:plain-text t
: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 (not used for exact ranges)."
:optional t)
(:name "start_column"
:type integer
:description "Optional 0-based display column for an exact range; requires start_line, end_line, end_column."
:optional t)
(:name "end_line"
:type integer
:description "Optional 1-based exclusive end line for an exact range."
:optional t)
(:name "end_column"
:type integer
:description "Optional 0-based exclusive end column for an exact range."
:optional t)
(:name "max_chars"
:type integer
:description "Optional positive output character limit; truncated responses are explicitly marked."
:optional t)))
(:function ai-code-mcp-get-key-binding-info
:name "get_key_binding_info"
:description "Inspect the effective Emacs key binding in a live buffer, including the active map that supplies it."
:args ((:name "key_sequence"
:type string
:description "Emacs kbd notation, for example C-c a v.")
(:name "buffer_name"
:type string
:description "Optional live buffer; defaults to the MCP source buffer."
: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."
:plain-text t
: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."
:plain-text t
: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; supply a location when ambiguous."
:plain-text t
:args ((:name "identifier"
:type string
:description "Identifier to resolve.")
(:name "file_path"
:type string
:description "Path to the file that provides backend context.")
(:name "line"
:type integer
:description "Optional 1-based line of the identifier, for disambiguation."
:optional t)
(:name "column"
:type integer
:description "Optional 0-based display column on line, as in editor_state."
:optional t)))
(: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."
:plain-text t
: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."
:plain-text t
: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'
- `get_key_binding_info'
- `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))
(plain-text (plist-get slots :plain-text))
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)))
(when plain-text
(setq spec (plist-put spec :plain-text t)))
(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 &optional no-renew)
"Return the session id and context authenticated by TOKEN.
Successful authentication renews sessions with a token renewal interval
unless NO-RENEW is non-nil. Expired tokens cannot renew themselves
through this entry point."
(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)))
(unless no-renew
(setq context (ai-code-mcp--renew-session-token context))
(puthash session-id context ai-code-mcp--sessions))
(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--renew-session-token (context)
"Return CONTEXT with its renewable token expiry extended from now.
Only sessions with both `:expires-at' and a positive
`:token-lifetime-seconds' opt in; fixed expiry sessions stay unchanged."
(let ((lifetime (plist-get context :token-lifetime-seconds)))
(if (and (plist-get context :expires-at)
(numberp lifetime) (> lifetime 0))
(plist-put context :expires-at
(time-add (current-time) (seconds-to-time lifetime)))
context)))
(defun ai-code-mcp-touch-session (session-id)
"Extend renewable token expiry for SESSION-ID from now.
Return the updated session context, or nil when SESSION-ID is unknown."
(when-let* ((context (ai-code-mcp-get-session-context session-id)))
(setq context (ai-code-mcp--renew-session-token context))
(puthash session-id context ai-code-mcp--sessions)
context))
(defun ai-code-mcp-update-source-context (session-id source-buffer)
"Snapshot SOURCE-BUFFER as the prompt origin for SESSION-ID.
This trusted local update also renews an expired renewable token so a new
prompt can resume an idle agent without restarting its CLI process."
(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)))
(setq context (ai-code-mcp--renew-session-token context))
(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.
Coordinates ignore narrowing so they match `buffer_query' exact ranges."
(with-current-buffer buffer
(save-excursion
(save-restriction
(widen)
(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)
(snapshot_captured_at
. ,(and (eq buffer source-buffer)
source-snapshot
(float-time (plist-get source-snapshot :captured-at))))
(snapshot_modification_tick
. ,(and (eq buffer source-buffer)
source-snapshot
(plist-get source-snapshot :modification-tick)))
(current_modification_tick . ,(buffer-chars-modified-tick))
(snapshot_stale
. ,(ai-code-mcp--json-bool
(and (eq buffer source-buffer)
source-snapshot
(/= (plist-get source-snapshot :modification-tick)
(buffer-chars-modified-tick)))))))))))
(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 &optional start-column end-line end-column)
"Validate legacy line range or exact coordinates for a buffer query."
(let ((exact (or start-column end-line end-column)))
(if exact
(unless (and (null num-lines)
(integerp start-line) (> start-line 0)
(integerp start-column) (>= start-column 0)
(integerp end-line) (> end-line 0)
(integerp end-column) (>= end-column 0)
(or (> end-line start-line)
(and (= end-line start-line)
(>= end-column start-column))))
(user-error "Exact range needs start_line, start_column, end_line and end_column (no num_lines)"))
(when (or (and start-line (not num-lines))
(and num-lines (not start-line)))
(user-error "start_line and num_lines must both be provided or omitted"))
(when (and start-line
(or (not (integerp start-line)) (not (integerp num-lines))
(< start-line 1) (< num-lines 1)))
(user-error "start_line and num_lines must be positive integers")))))
(defun ai-code-mcp--strict-buffer-position (line column)
"Return the buffer position at LINE and display COLUMN, or reject it.
The caller widens the buffer so coordinates match the file's line numbers."
(save-excursion
(goto-char (point-min))
(unless (zerop (forward-line (1- line)))
(user-error "Line %d is outside the buffer" line))
(let ((end (line-end-position)))
(move-to-column column)
(unless (and (= (current-column) column)
(<= (point) end))
(user-error "Column %d is outside line %d" column line)))
(point)))
(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 start-column end-line end-column
max-chars)
"Return live BUFFER-NAME text, supporting legacy lines or exact ranges.
Exact ranges use 1-based lines and 0-based display columns, with an
exclusive end position. MAX-CHARS optionally caps the returned text."
(let ((buffer (get-buffer buffer-name)))
(unless buffer
(user-error "Buffer not found: %s" buffer-name))
(ai-code-mcp--validate-buffer-query-range
start-line num-lines start-column end-line end-column)
(when (and max-chars
(not (and (integerp max-chars) (> max-chars 0))))
(user-error "max_chars must be a positive integer"))
(let ((exact (or start-column end-line end-column)))
(when (and (null max-chars)
(null exact)
(null start-line)
ai-code-mcp-buffer-query-default-max-chars)
(unless (and (integerp ai-code-mcp-buffer-query-default-max-chars)
(> ai-code-mcp-buffer-query-default-max-chars 0))
(user-error
"Default buffer_query max_chars must be nil or a positive integer"))
(setq max-chars ai-code-mcp-buffer-query-default-max-chars))
(with-current-buffer buffer
(let ((text
(save-excursion
(if exact
(save-restriction
(widen)
(let ((start (ai-code-mcp--strict-buffer-position
start-line start-column))
(end (ai-code-mcp--strict-buffer-position
end-line end-column)))
(buffer-substring-no-properties start end)))
(if (not start-line)
(buffer-substring-no-properties (point-min) (point-max))
(goto-char (point-min))
(forward-line (1- start-line))
(let ((start (point)))
(forward-line num-lines)
(ai-code-mcp--drop-trailing-newline
(buffer-substring-no-properties start (point)))))))))
(if (and max-chars (> (length text) max-chars))
(concat (substring text 0 max-chars)
"\n[truncated; request a smaller buffer range]")
text))))))
(defun ai-code-mcp--key-binding-map-source (map)
"Describe the active key MAP as a global, major, or minor mode map."
(cond
((eq map (current-global-map))
'((kind . "global") (mode . nil)))
((eq map (current-local-map))
`((kind . "major-mode") (mode . ,(symbol-name major-mode))))
(t
(let ((minor-mode
(cl-loop for entry in (append minor-mode-overriding-map-alist
minor-mode-map-alist)
for mode = (car entry)
when (and (symbolp mode)
(boundp mode)
(symbol-value mode)
(eq map (cdr entry)))
return mode)))
`((kind . ,(if minor-mode "minor-mode" "other"))
(mode . ,(and minor-mode (symbol-name minor-mode))))))))
(defun ai-code-mcp-get-key-binding-info (key-sequence &optional buffer-name)
"Inspect KEY-SEQUENCE as it is bound in BUFFER-NAME.
Use the MCP prompt source buffer by default. This is a read-only lookup;
it never invokes the resolved command."
(unless (and (stringp key-sequence)
(not (string-empty-p key-sequence)))
(user-error "key_sequence must be nonempty Emacs kbd notation"))
(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))))
(keys (kbd key-sequence)))
(if (not buffer)
(json-encode
'((ok . :json-false)
(status . "unavailable")
(reason . "Prompt source buffer is no longer live")))
(with-current-buffer buffer
;; Accept default [t] bindings everywhere so the reported map and
;; raw binding agree with `key-binding'.
(let* ((binding (key-binding keys t))
(map (seq-find
(lambda (candidate)
(let ((entry (lookup-key candidate keys t)))
(and entry (not (numberp entry)))))
(current-active-maps t)))
(raw (and map (lookup-key map keys t)))
(source-info (and map (ai-code-mcp--key-binding-map-source map))))
(json-encode
`((ok . t)
(buffer_name . ,(buffer-name buffer))
(key_sequence . ,(key-description keys))
(bound . ,(ai-code-mcp--json-bool (not (null binding))))
(binding . ,(and raw (format "%S" raw)))
(effective_command . ,(and binding (format "%S" binding)))
(interactive . ,(ai-code-mcp--json-bool
(and binding (commandp binding))))
(source . ,source-info))))))))
(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