nvim-mcp 0.7.2

MCP server for Neovim
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
use std::collections::HashMap;

use rmcp::{
    ErrorData as McpError, RoleServer,
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::*,
    schemars,
    service::RequestContext,
    tool, tool_router,
};
use tracing::instrument;

use super::core::{NeovimMcpServer, find_get_all_targets};
use super::lua_tools;
use crate::neovim::client::TypeHierarchyItem;
use crate::neovim::{
    CallHierarchyItem, CodeAction, DocumentIdentifier, FormattingOptions, NeovimClient, Position,
    PrepareRenameResult, Range, WorkspaceEdit, string_or_struct,
};

/// Connect to Neovim instance via unix socket or TCP
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ConnectNvimRequest {
    /// target can be a unix socket path or a TCP address
    pub target: String,
}

/// New parameter struct for connection-aware requests
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ConnectionRequest {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
}

/// Updated parameter struct for buffer operations
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BufferRequest {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Neovim Buffer ID
    pub id: u64,
}

/// Buffer read request parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BufferReadRequest {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Start line index (zero-based, optional - defaults to 0)
    #[serde(default)]
    pub start: i64,
    /// End line index, exclusive (zero-based, optional - defaults to -1 for end of buffer)
    #[serde(default = "default_end_line")]
    pub end: i64,
}

fn default_end_line() -> i64 {
    -1
}

/// Lua execution request
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ExecuteLuaRequest {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Lua code to execute in Neovim
    pub code: String,
}

/// Wait for LSP client readiness parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct WaitForLspReadyRequest {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Optional specific LSP client name to wait for (waits for any client if None)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_name: Option<String>,
    /// Timeout in milliseconds (default 5000ms)
    #[serde(default = "default_timeout")]
    pub timeout_ms: u64,
}

fn default_timeout() -> u64 {
    5000
}

/// Workspace symbols parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct WorkspaceSymbolsParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Lsp client name
    pub lsp_client_name: String,
    /// A query string to filter symbols by. Clients may send an empty string here to request all symbols.
    pub query: String,
}

/// Code Actions parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CodeActionsParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Range start position, line number starts from 0
    pub start_line: u64,
    /// Range start position, character number starts from 0
    pub start_character: u64,
    /// Range end position, line number starts from 0
    pub end_line: u64,
    /// Range end position, character number starts from 0
    pub end_character: u64,
}

/// Hover parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct HoverParam {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
}

/// Document symbols parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DocumentSymbolsParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
}

/// References parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ReferencesParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
    /// Include the declaration of the current symbol in the results
    pub include_declaration: bool,
}

/// Definition parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DefinitionParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
}

/// Type definition parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct TypeDefinitionParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
}

/// Implementation parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ImplementationParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
}

/// Declaration parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DeclarationParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
}

/// Code action resolve parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ResolveCodeActionParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Code action to resolve
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub code_action: CodeAction,
}

/// Apply workspace edit parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ApplyWorkspaceEditParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Workspace edit to apply
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub workspace_edit: WorkspaceEdit,
}

/// Rename parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RenameParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
    /// The new name of the symbol
    pub new_name: String,
    /// Whether to run prepare rename first to validate the position (default: true)
    #[serde(default = "default_prepare_first")]
    pub prepare_first: bool,
}

fn default_prepare_first() -> bool {
    true
}

/// Document formatting parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DocumentFormattingParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// The formatting options
    pub options: FormattingOptions,
    /// Whether to apply the text edits automatically (default: false)
    #[serde(default)]
    pub apply_edits: bool,
}

/// Document range formatting parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DocumentRangeFormattingParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Range start position, line number starts from 0
    pub start_line: u64,
    /// Range start position, character number starts from 0
    pub start_character: u64,
    /// Range end position, line number starts from 0
    pub end_line: u64,
    /// Range end position, character number starts from 0
    pub end_character: u64,
    /// The formatting options
    #[serde(deserialize_with = "string_or_struct")]
    pub options: FormattingOptions,
    /// Whether to apply the text edits automatically (default: false)
    #[serde(default)]
    pub apply_edits: bool,
}

/// Organize imports parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct LspOrganizeImportsParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Whether to apply the text edits automatically (default: true)
    #[serde(default = "default_true")]
    pub apply_edits: bool,
}

fn default_true() -> bool {
    true
}

/// Navigate to a specific position in the current buffer or open a file at a specific position
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct NavigateParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Document to navigate to
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
}

/// Call hierarchy prepare parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CallHierarchyPrepareParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
}

/// Call hierarchy incoming calls parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CallHierarchyIncomingCallsParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Call hierarchy item to get incoming calls for
    #[serde(deserialize_with = "string_or_struct")]
    pub item: CallHierarchyItem,
}

/// Call hierarchy outgoing calls parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CallHierarchyOutgoingCallsParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Call hierarchy item to get outgoing calls for
    #[serde(deserialize_with = "string_or_struct")]
    pub item: CallHierarchyItem,
}

/// Type Hierarchy Prepare parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct TypeHierarchyPrepareParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Universal document identifier
    // Supports both string and struct deserialization.
    // Compatible with Claude Code when using subscription.
    #[serde(deserialize_with = "string_or_struct")]
    pub document: DocumentIdentifier,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Symbol position (zero-based)
    #[serde(flatten)]
    pub position: Position,
}

/// Type hierarchy supertypes parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct TypeHierarchySupertypesParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Type hierarchy item to get supertypes for
    #[serde(deserialize_with = "string_or_struct")]
    pub item: TypeHierarchyItem,
}

/// Type hierarchy subtypes parameters
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct TypeHierarchySubtypesParams {
    /// Unique identifier for the target Neovim instance
    pub connection_id: String,
    /// Lsp client name
    pub lsp_client_name: String,
    /// Type hierarchy item to get subtypes for
    #[serde(deserialize_with = "string_or_struct")]
    pub item: TypeHierarchyItem,
}

macro_rules! include_files {
    ($($key:ident),* $(,)?) => {{
        let mut map = HashMap::new();
        $(
            map.insert(stringify!($key), include_str!(concat!("../../docs/tools/", stringify!($key), ".md")));
        )*
        map
    }};
}

impl NeovimMcpServer {
    pub fn tool_descriptions() -> HashMap<&'static str, &'static str> {
        include_files! {
            get_targets,
            connect,
            read,
            buffer_diagnostics,
        }
    }

    pub fn get_tool_extra_description(&self, name: &str) -> Option<String> {
        if name == "get_targets" {
            Some(self.get_connections_instruction())
        } else {
            None
        }
    }
}

#[tool_router]
impl NeovimMcpServer {
    #[tool]
    #[instrument(skip(self))]
    pub async fn get_targets(&self) -> Result<CallToolResult, McpError> {
        let targets = find_get_all_targets();
        if targets.is_empty() {
            return Err(McpError::invalid_request(
                "No Neovim targets found".to_string(),
                None,
            ));
        }

        Ok(CallToolResult::success(vec![Content::json(targets)?]))
    }

    #[tool]
    #[instrument(skip(self))]
    pub async fn connect(
        &self,
        Parameters(ConnectNvimRequest { target: path }): Parameters<ConnectNvimRequest>,
        ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let connection_id = self.generate_shorter_connection_id(&path);

        // If connection already exists, disconnect the old one first (ignoring errors)
        if let Some(mut old_client) = self.nvim_clients.get_mut(&connection_id) {
            let _ = old_client.disconnect().await;
        }

        let mut client = NeovimClient::default();
        client.connect_path(&path).await?;

        self.setup_new_client(&connection_id, Box::new(client), &ctx)
            .await?;

        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({
                "connection_id": connection_id,
            }),
        )?]))
    }

    #[tool(description = "Connect via TCP address")]
    #[instrument(skip(self))]
    pub async fn connect_tcp(
        &self,
        Parameters(ConnectNvimRequest { target: address }): Parameters<ConnectNvimRequest>,
        ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let connection_id = self.generate_shorter_connection_id(&address);

        // If connection already exists, disconnect the old one first (ignoring errors)
        if let Some(mut old_client) = self.nvim_clients.get_mut(&connection_id) {
            let _ = old_client.disconnect().await;
        }

        let mut client = NeovimClient::default();
        client.connect_tcp(&address).await?;

        self.setup_new_client(&connection_id, Box::new(client), &ctx)
            .await?;

        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({
                "connection_id": connection_id,
            }),
        )?]))
    }

    #[tool(description = "Disconnect from Neovim instance")]
    #[instrument(skip(self))]
    pub async fn disconnect(
        &self,
        Parameters(ConnectionRequest { connection_id }): Parameters<ConnectionRequest>,
    ) -> Result<CallToolResult, McpError> {
        // Verify connection exists first
        let target = {
            let client = self.get_connection(&connection_id)?;
            client.target().unwrap_or_else(|| "Unknown".to_string())
        };

        // Remove the connection from the map
        if let Some((_, mut client)) = self.nvim_clients.remove(&connection_id) {
            if let Err(e) = client.disconnect().await {
                return Err(McpError::internal_error(
                    format!("Failed to disconnect: {e}"),
                    None,
                ));
            }
            Ok(CallToolResult::success(vec![Content::json(
                serde_json::json!({
                    "connection_id": connection_id,
                    "target": target,
                }),
            )?]))
        } else {
            Err(McpError::invalid_request(
                format!("No Neovim connection found for ID: {connection_id}"),
                None,
            ))
        }
    }

    #[tool(description = "List all open buffers")]
    #[instrument(skip(self))]
    pub async fn list_buffers(
        &self,
        Parameters(ConnectionRequest { connection_id }): Parameters<ConnectionRequest>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let buffers = client.get_buffers().await?;
        Ok(CallToolResult::success(vec![Content::json(buffers)?]))
    }

    #[tool(description = "Execute Lua code")]
    #[instrument(skip(self))]
    pub async fn exec_lua(
        &self,
        Parameters(ExecuteLuaRequest {
            connection_id,
            code,
        }): Parameters<ExecuteLuaRequest>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let result = client.execute_lua(&code).await?;
        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({
                "result": format!("{:?}", result)
            }),
        )?]))
    }

    #[tool(description = "Wait for LSP client to be ready and attached")]
    #[instrument(skip(self))]
    pub async fn wait_for_lsp_ready(
        &self,
        Parameters(WaitForLspReadyRequest {
            connection_id,
            client_name,
            timeout_ms,
        }): Parameters<WaitForLspReadyRequest>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        client
            .wait_for_lsp_ready(client_name.as_deref(), timeout_ms)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({
                "message": "LSP client ready",
                "client_name": client_name.unwrap_or_else(|| "any".to_string()),
                "timeout_ms": timeout_ms
            }),
        )?]))
    }

    #[tool]
    #[instrument(skip(self))]
    pub async fn read(
        &self,
        Parameters(BufferReadRequest {
            connection_id,
            document,
            start,
            end,
        }): Parameters<BufferReadRequest>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let text_content = client.read_document(document, start, end).await?;
        Ok(CallToolResult::success(vec![Content::text(text_content)]))
    }

    #[tool]
    #[instrument(skip(self))]
    pub async fn buffer_diagnostics(
        &self,
        Parameters(BufferRequest { connection_id, id }): Parameters<BufferRequest>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let diagnostics = client.get_buffer_diagnostics(id).await?;
        Ok(CallToolResult::success(vec![Content::json(diagnostics)?]))
    }

    #[tool(description = "Get workspace LSP clients")]
    #[instrument(skip(self))]
    pub async fn lsp_clients(
        &self,
        Parameters(ConnectionRequest { connection_id }): Parameters<ConnectionRequest>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let lsp_clients = client.lsp_get_clients().await?;
        Ok(CallToolResult::success(vec![Content::json(lsp_clients)?]))
    }

    #[tool(description = "Search workspace symbols by query")]
    #[instrument(skip(self))]
    pub async fn lsp_workspace_symbols(
        &self,
        Parameters(WorkspaceSymbolsParams {
            connection_id,
            lsp_client_name,
            query,
        }): Parameters<WorkspaceSymbolsParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let symbols = client
            .lsp_workspace_symbols(&lsp_client_name, &query)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(symbols)?]))
    }

    #[tool(description = "Get LSP code actions")]
    #[instrument(skip(self))]
    pub async fn lsp_code_actions(
        &self,
        Parameters(CodeActionsParams {
            connection_id,
            document,
            lsp_client_name,
            start_line,
            start_character,
            end_line,
            end_character,
        }): Parameters<CodeActionsParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let start = Position {
            line: start_line,
            character: start_character,
        };
        let end = Position {
            line: end_line,
            character: end_character,
        };
        let range = Range { start, end };

        let code_actions = client
            .lsp_get_code_actions(&lsp_client_name, document, range)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(code_actions)?]))
    }

    #[tool(description = "Get LSP hover information")]
    #[instrument(skip(self))]
    pub async fn lsp_hover(
        &self,
        Parameters(HoverParam {
            connection_id,
            document,
            lsp_client_name,
            position,
        }): Parameters<HoverParam>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let hover = client
            .lsp_hover(&lsp_client_name, document, position)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(hover)?]))
    }

    #[tool(description = "Get document symbols")]
    #[instrument(skip(self))]
    pub async fn lsp_document_symbols(
        &self,
        Parameters(DocumentSymbolsParams {
            connection_id,
            document,
            lsp_client_name,
        }): Parameters<DocumentSymbolsParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let symbols = client
            .lsp_document_symbols(&lsp_client_name, document)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(symbols)?]))
    }

    #[tool(description = "Get LSP references")]
    #[instrument(skip(self))]
    pub async fn lsp_references(
        &self,
        Parameters(ReferencesParams {
            connection_id,
            document,
            lsp_client_name,
            position,
            include_declaration,
        }): Parameters<ReferencesParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let references = client
            .lsp_references(&lsp_client_name, document, position, include_declaration)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(references)?]))
    }

    #[tool(description = "Get LSP definition")]
    #[instrument(skip(self))]
    pub async fn lsp_definition(
        &self,
        Parameters(DefinitionParams {
            connection_id,
            document,
            lsp_client_name,
            position,
        }): Parameters<DefinitionParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let definition = client
            .lsp_definition(&lsp_client_name, document, position)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(definition)?]))
    }

    #[tool(description = "Get LSP type definition")]
    #[instrument(skip(self))]
    pub async fn lsp_type_definition(
        &self,
        Parameters(TypeDefinitionParams {
            connection_id,
            document,
            lsp_client_name,
            position,
        }): Parameters<TypeDefinitionParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let type_definition = client
            .lsp_type_definition(&lsp_client_name, document, position)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(
            type_definition,
        )?]))
    }

    #[tool(description = "Get LSP implementation")]
    #[instrument(skip(self))]
    pub async fn lsp_implementations(
        &self,
        Parameters(ImplementationParams {
            connection_id,
            document,
            lsp_client_name,
            position,
        }): Parameters<ImplementationParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let implementation = client
            .lsp_implementation(&lsp_client_name, document, position)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(
            implementation,
        )?]))
    }

    #[tool(description = "Get LSP declaration")]
    #[instrument(skip(self))]
    pub async fn lsp_declaration(
        &self,
        Parameters(DeclarationParams {
            connection_id,
            document,
            lsp_client_name,
            position,
        }): Parameters<DeclarationParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let declaration = client
            .lsp_declaration(&lsp_client_name, document, position)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(declaration)?]))
    }

    #[tool(description = "Resolve a code action that may have incomplete data")]
    #[instrument(skip(self))]
    pub async fn lsp_resolve_code_action(
        &self,
        Parameters(ResolveCodeActionParams {
            connection_id,
            lsp_client_name,
            code_action,
        }): Parameters<ResolveCodeActionParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let resolved_action = client
            .lsp_resolve_code_action(&lsp_client_name, code_action)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(
            resolved_action,
        )?]))
    }

    #[tool(description = "Apply workspace edits using Neovim's LSP utility functions")]
    #[instrument(skip(self))]
    pub async fn lsp_apply_edit(
        &self,
        Parameters(ApplyWorkspaceEditParams {
            connection_id,
            lsp_client_name,
            workspace_edit,
        }): Parameters<ApplyWorkspaceEditParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        client
            .lsp_apply_workspace_edit(&lsp_client_name, workspace_edit)
            .await?;
        Ok(CallToolResult::success(vec![Content::text("success")]))
    }

    #[tool(description = "Rename symbol across workspace using LSP with optional validation")]
    #[instrument(skip(self))]
    pub async fn lsp_rename(
        &self,
        Parameters(RenameParams {
            connection_id,
            document,
            lsp_client_name,
            position,
            new_name,
            prepare_first,
        }): Parameters<RenameParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;

        // Optionally run prepare rename first to validate the position
        if prepare_first {
            match client
                .lsp_prepare_rename(&lsp_client_name, document.clone(), position.clone())
                .await
            {
                Ok(Some(prepare_result)) => {
                    // Prepare rename was successful, we can proceed
                    let prepare_info = match prepare_result {
                        PrepareRenameResult::Range(range) => {
                            format!("Range: {:?}", range)
                        }
                        PrepareRenameResult::RangeWithPlaceholder { range, placeholder } => {
                            format!("Range: {:?}, Current name: '{}'", range, placeholder)
                        }
                        PrepareRenameResult::DefaultBehavior { .. } => {
                            "Default behavior enabled".to_string()
                        }
                    };
                    tracing::debug!("Prepare rename successful: {}", prepare_info);
                }
                Ok(None) => {
                    return Err(McpError::invalid_request(
                        "Position is not renameable according to prepare rename".to_string(),
                        None,
                    ));
                }
                Err(e) => {
                    return Err(McpError::invalid_request(
                        format!("Prepare rename failed: {}", e),
                        None,
                    ));
                }
            }
        }

        // Proceed with the actual rename
        let workspace_edit = client
            .lsp_rename(&lsp_client_name, document, position, &new_name)
            .await?;

        if let Some(edit) = workspace_edit {
            // Apply the workspace edit automatically
            client
                .lsp_apply_workspace_edit(&lsp_client_name, edit)
                .await?;
            Ok(CallToolResult::success(vec![Content::text(
                "Rename completed successfully",
            )]))
        } else {
            Err(McpError::invalid_request(
                "Rename operation is not valid at this position".to_string(),
                None,
            ))
        }
    }

    #[tool(description = "Format entire document using LSP with optional auto-apply")]
    #[instrument(skip(self))]
    pub async fn lsp_formatting(
        &self,
        Parameters(DocumentFormattingParams {
            connection_id,
            document,
            lsp_client_name,
            options,
            apply_edits,
        }): Parameters<DocumentFormattingParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let text_edits = client
            .lsp_formatting(&lsp_client_name, document.clone(), options)
            .await?;

        if apply_edits {
            // Apply the text edits automatically
            client
                .lsp_apply_text_edits(&lsp_client_name, document, text_edits)
                .await?;
            Ok(CallToolResult::success(vec![Content::text(
                "Formatting applied successfully",
            )]))
        } else {
            // Return the text edits for inspection
            Ok(CallToolResult::success(vec![Content::json(text_edits)?]))
        }
    }

    #[tool(
        description = "Format a specific range in a document using LSP with optional auto-apply"
    )]
    #[instrument(skip(self))]
    pub async fn lsp_range_formatting(
        &self,
        Parameters(DocumentRangeFormattingParams {
            connection_id,
            document,
            lsp_client_name,
            start_line,
            start_character,
            end_line,
            end_character,
            options,
            apply_edits,
        }): Parameters<DocumentRangeFormattingParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let start = Position {
            line: start_line,
            character: start_character,
        };
        let end = Position {
            line: end_line,
            character: end_character,
        };
        let range = Range { start, end };

        let text_edits = client
            .lsp_range_formatting(&lsp_client_name, document.clone(), range, options)
            .await?;

        if apply_edits {
            // Apply the text edits automatically
            client
                .lsp_apply_text_edits(&lsp_client_name, document, text_edits)
                .await?;
            Ok(CallToolResult::success(vec![Content::text(
                "Range formatting applied successfully",
            )]))
        } else {
            // Return the text edits for inspection
            Ok(CallToolResult::success(vec![Content::json(text_edits)?]))
        }
    }

    #[tool(description = "Sort and organize imports")]
    #[instrument(skip(self))]
    pub async fn lsp_organize_imports(
        &self,
        Parameters(LspOrganizeImportsParams {
            connection_id,
            document,
            lsp_client_name,
            apply_edits,
        }): Parameters<LspOrganizeImportsParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;

        // Get organize imports code actions for the entire document
        let code_actions = client
            .lsp_get_organize_imports_actions(&lsp_client_name, document)
            .await?;

        if code_actions.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No organize imports actions available for this document",
            )]));
        }

        if !apply_edits {
            // Return the code actions for inspection
            return Ok(CallToolResult::success(vec![Content::json(code_actions)?]));
        }

        // Apply the first/preferred organize imports action
        let action = code_actions[0].clone();

        // Resolve the action if it needs resolution
        let resolved_action = if action.has_edit() {
            action
        } else {
            client
                .lsp_resolve_code_action(&lsp_client_name, action)
                .await?
        };

        // Apply the workspace edit
        if let Some(edit) = resolved_action.edit() {
            client
                .lsp_apply_workspace_edit(&lsp_client_name, edit.clone())
                .await?;
            Ok(CallToolResult::success(vec![Content::text(
                "Imports organized successfully",
            )]))
        } else {
            Err(McpError::invalid_request(
                "Organize imports action does not contain workspace edit".to_string(),
                None,
            ))
        }
    }

    #[tool(
        description = "Get the current cursor position: buffer id, buffer name, window id, and zero-based row/col index"
    )]
    #[instrument(skip(self))]
    pub async fn cursor_position(
        &self,
        Parameters(ConnectionRequest { connection_id }): Parameters<ConnectionRequest>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let lua_code = include_str!("./lua/cursor_position.lua");
        let result = client.execute_lua(lua_code).await?;

        // Convert nvim Value to serde_json::Value for serialization
        let json_result = lua_tools::convert_nvim_value_to_json(result).map_err(|e| {
            McpError::internal_error(
                format!("Failed to convert cursor position result to JSON: {}", e),
                None,
            )
        })?;

        Ok(CallToolResult::success(vec![Content::json(json_result)?]))
    }

    #[tool(
        description = "Navigate to a specific position in the current buffer or open a file at a specific position"
    )]
    #[instrument(skip(self))]
    pub async fn navigate(
        &self,
        Parameters(NavigateParams {
            connection_id,
            document,
            position,
        }): Parameters<NavigateParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let result = client.navigate(document, position).await?;
        Ok(CallToolResult::success(vec![Content::json(result)?]))
    }

    #[tool(description = "Prepare call hierarchy for a symbol at a specific position")]
    #[instrument(skip(self))]
    pub async fn lsp_call_hierarchy_prepare(
        &self,
        Parameters(CallHierarchyPrepareParams {
            connection_id,
            document,
            lsp_client_name,
            position,
        }): Parameters<CallHierarchyPrepareParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let result = client
            .lsp_call_hierarchy_prepare(&lsp_client_name, document, position)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(result)?]))
    }

    #[tool(description = "Get incoming calls for a call hierarchy item")]
    #[instrument(skip(self))]
    pub async fn lsp_call_hierarchy_incoming_calls(
        &self,
        Parameters(CallHierarchyIncomingCallsParams {
            connection_id,
            lsp_client_name,
            item,
        }): Parameters<CallHierarchyIncomingCallsParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let result = client
            .lsp_call_hierarchy_incoming_calls(&lsp_client_name, item)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(result)?]))
    }

    #[tool(description = "Get outgoing calls for a call hierarchy item")]
    #[instrument(skip(self))]
    pub async fn lsp_call_hierarchy_outgoing_calls(
        &self,
        Parameters(CallHierarchyOutgoingCallsParams {
            connection_id,
            lsp_client_name,
            item,
        }): Parameters<CallHierarchyOutgoingCallsParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let result = client
            .lsp_call_hierarchy_outgoing_calls(&lsp_client_name, item)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(result)?]))
    }

    #[tool(description = "Prepare type hierarchy for a symbol at a specific position")]
    #[instrument(skip(self))]
    pub async fn lsp_type_hierarchy_prepare(
        &self,
        Parameters(TypeHierarchyPrepareParams {
            connection_id,
            document,
            lsp_client_name,
            position,
        }): Parameters<TypeHierarchyPrepareParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let result = client
            .lsp_type_hierarchy_prepare(&lsp_client_name, document, position)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(result)?]))
    }

    #[tool(description = "Get supertypes for a type hierarchy item")]
    #[instrument(skip(self))]
    pub async fn lsp_type_hierarchy_supertypes(
        &self,
        Parameters(TypeHierarchySupertypesParams {
            connection_id,
            lsp_client_name,
            item,
        }): Parameters<TypeHierarchySupertypesParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let result = client
            .lsp_type_hierarchy_supertypes(&lsp_client_name, item)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(result)?]))
    }

    #[tool(description = "Get subtypes for a type hierarchy item")]
    #[instrument(skip(self))]
    pub async fn lsp_type_hierarchy_subtypes(
        &self,
        Parameters(TypeHierarchySubtypesParams {
            connection_id,
            lsp_client_name,
            item,
        }): Parameters<TypeHierarchySubtypesParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.get_connection(&connection_id)?;
        let result = client
            .lsp_type_hierarchy_subtypes(&lsp_client_name, item)
            .await?;
        Ok(CallToolResult::success(vec![Content::json(result)?]))
    }
}

/// Build tool router for NeovimMcpServer
pub fn build_tool_router() -> ToolRouter<NeovimMcpServer> {
    NeovimMcpServer::tool_router()
}