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
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
use rmcp::{
    model::{CallToolRequestParam, ReadResourceRequestParam},
    serde_json::{Map, Value},
    service::ServiceExt,
    transport::{ConfigureCommandExt, TokioChildProcess},
};
use tokio::process::Command;
use tracing::{error, info};
use tracing_test::traced_test;

use crate::{server::core::b3sum, test_utils::*};

// Macro to create an MCP service using the pre-compiled binary
macro_rules! create_mcp_service {
    () => {{
        let command = Command::new(get_compiled_binary()).configure(|cmd| {
            cmd.args(["--connect", "manual"]);
        });
        ().serve(TokioChildProcess::new(command)?)
            .await
            .map_err(|e| {
                error!("Failed to connect to server: {}", e);
                e
            })?
    }};
    ($target:expr) => {{
        // Macro to create an MCP service with auto-connect to a specific target
        let command = Command::new(get_compiled_binary()).configure(|cmd| {
            cmd.args(["--connect", $target]);
        });
        ().serve(TokioChildProcess::new(command)?)
            .await
            .map_err(|e| {
                error!("Failed to connect to server: {}", e);
                e
            })?
    }};
}

/// Macro to setup auto-connected service and return (service, connection_id, guard)
/// This eliminates the boilerplate for auto-connect tests
macro_rules! setup_connected_service {
    () => {{
        let ipc_path = generate_random_ipc_path();
        let _guard = setup_test_neovim_instance(&ipc_path).await?;
        let service = create_mcp_service!(&ipc_path);
        let connection_id = b3sum(&ipc_path)[..7].to_string();
        (service, connection_id, _guard)
    }};
    ($cfg_path:expr, $open_file:expr) => {{
        let ipc_path = generate_random_ipc_path();
        let child = setup_neovim_instance_socket_advance(&ipc_path, $cfg_path, $open_file).await;
        let _guard = NeovimIpcGuard::new(child, ipc_path.clone());
        let service = create_mcp_service!(&ipc_path);
        let connection_id = b3sum(&ipc_path)[..7].to_string();
        (service, connection_id, _guard)
    }};
}

/// Macro to connect to a Neovim instance through MCP service and get connection_id
macro_rules! connect_to_neovim {
    ($service:expr, $ipc_path:expr) => {{
        let mut connect_args = Map::new();
        connect_args.insert("target".to_string(), Value::String($ipc_path));

        let connect_result = $service
            .call_tool(CallToolRequestParam {
                name: "connect".into(),
                arguments: Some(connect_args),
            })
            .await?;

        extract_connection_id(&connect_result)?
    }};
}

macro_rules! wait_for_lsp_ready {
    ($service:expr, $connection_id:expr, $lsp_client:expr) => {{
        // Wait for LSP client (gopls) to be ready
        let mut wait_lsp_args = Map::new();
        wait_lsp_args.insert("connection_id".to_string(), Value::String($connection_id));
        wait_lsp_args.insert("client_name".to_string(), Value::String($lsp_client));
        wait_lsp_args.insert("timeout_ms".to_string(), Value::Number(30000.into()));

        $service
            .call_tool(CallToolRequestParam {
                name: "wait_for_lsp_ready".into(),
                arguments: Some(wait_lsp_args),
            })
            .await?;

        info!("LSP client ready");
    }};
}

// Helper function to extract connection_id from connect response
fn extract_connection_id(
    result: &rmcp::model::CallToolResult,
) -> Result<String, Box<dyn std::error::Error>> {
    if let Some(content) = result.content.first() {
        // The content should be JSON
        let json_str = match &content.raw {
            rmcp::model::RawContent::Text(text_content) => &text_content.text,
            _ => return Err("Expected text content".into()),
        };

        // Parse JSON
        let json_value: serde_json::Value = serde_json::from_str(json_str)?;
        if let Some(connection_id) = json_value["connection_id"].as_str() {
            return Ok(connection_id.to_string());
        }
    }
    Err("Failed to extract connection_id from response".into())
}

#[traced_test]
#[tokio::test]
async fn test_graceful_close_mcp_server() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP server using pre-compiled binary");

    let mut child = Command::new(get_compiled_binary())
        .stdin(std::process::Stdio::piped())
        .spawn()?;

    // Wait a moment to ensure the server starts
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;

    // Check if the process is still running
    match child.try_wait()? {
        Some(status) => {
            error!("MCP server exited prematurely with status: {}", status);
            return Err("MCP server exited prematurely".into());
        }
        None => {
            info!("MCP server is running");
        }
    }

    // Clean up: terminate the server process
    // Close stdin
    if let Some(stdin) = child.stdin.take() {
        drop(stdin);
    }
    // Or send SIGTERM signal

    child.wait().await?;
    info!("MCP server process terminated");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_mcp_server_connection() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test nvim-mcp server");

    // Connect to the server using pre-compiled binary
    let service = create_mcp_service!();

    // Get server information
    let server_info = service.peer_info();
    info!("Connected to server: {:#?}", server_info);

    // Verify server info contains expected information
    if let Some(info) = server_info {
        assert!(info.instructions.is_none());
        // Verify server capabilities
        assert!(info.capabilities.tools.is_some());
    } else {
        panic!("Expected server info to be present");
    }

    // Gracefully close the connection
    service.cancel().await?;
    info!("MCP server connection test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_list_tools() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test nvim-mcp server");

    let service = create_mcp_service!();

    // List available tools
    let tools = service.list_tools(Default::default()).await?;
    info!("Available tools: {:#?}", tools);

    // Verify we have the expected tools
    let tool_names: Vec<&str> = tools.tools.iter().map(|t| t.name.as_ref()).collect();
    assert!(tool_names.contains(&"get_targets"));
    assert!(tool_names.contains(&"connect"));
    assert!(tool_names.contains(&"connect_tcp"));

    // Verify tool descriptions are present
    for tool in &tools.tools {
        assert!(tool.description.is_some());
        assert!(!tool.description.as_ref().unwrap().is_empty());
    }

    service.cancel().await?;
    info!("List tools test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_connect_nvim() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test nvim-mcp server");

    let service = create_mcp_service!();

    // Start a test Neovim instance
    let ipc_path = generate_random_ipc_path();
    let _guard = setup_test_neovim_instance(&ipc_path).await?;

    // Create arguments as Map (based on rmcp expectations)
    let mut arguments = Map::new();
    arguments.insert("target".to_string(), Value::String(ipc_path.clone()));

    // Test successful connection
    let result = service
        .call_tool(CallToolRequestParam {
            name: "connect".into(),
            arguments: Some(arguments),
        })
        .await?;

    info!("Connect result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains success message
    if let Some(content) = result.content.first() {
        if let Some(text) = content.as_text() {
            assert!(text.text.contains("connection_id"));
        } else {
            panic!("Expected text content in connect result");
        }
    } else {
        panic!("No content in connect result");
    }

    // Test that connecting again succeeds (IPC connections allow reconnection)
    let mut arguments2 = Map::new();
    arguments2.insert("target".to_string(), Value::String(ipc_path.clone()));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "connect".into(),
            arguments: Some(arguments2),
        })
        .await;

    // For IPC connections, we allow reconnection to the same path
    assert!(
        result.is_ok(),
        "Should be able to reconnect to the same IPC path"
    );

    // Cleanup happens automatically via guard
    service.cancel().await?;
    info!("Connect nvim tool test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_invalid_connection_id_handling() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test invalid connection ID handling");

    let service = create_mcp_service!();

    // Test that all connection-aware tools fail with invalid connection ID
    let invalid_connection_id = "invalid_connection_id".to_string();
    let tools_to_test = vec![
        "disconnect",
        "list_buffers",
        "exec_lua",
        "lsp_clients",
        "cursor_position",
        "navigate",
    ];

    for tool_name in tools_to_test {
        let mut args = Map::new();
        args.insert(
            "connection_id".to_string(),
            Value::String(invalid_connection_id.clone()),
        );

        // Add tool-specific required arguments
        match tool_name {
            "exec_lua" => {
                args.insert("code".to_string(), Value::String("return 42".to_string()));
            }
            "navigate" => {
                args.insert("document".to_string(), serde_json::json!({"buffer_id": 1}));
                args.insert("line".to_string(), Value::Number(0.into()));
                args.insert("character".to_string(), Value::Number(0.into()));
            }
            _ => {}
        }

        let result = service
            .call_tool(CallToolRequestParam {
                name: tool_name.into(),
                arguments: Some(args),
            })
            .await;

        assert!(
            result.is_err(),
            "{} should fail with invalid connection ID",
            tool_name
        );
    }

    service.cancel().await?;
    info!("Invalid connection ID handling test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_disconnect_nvim() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test nvim-mcp server");

    let service = create_mcp_service!();

    // Now connect first, then test disconnect
    let ipc_path = generate_random_ipc_path();
    let _guard = setup_test_neovim_instance(&ipc_path).await?;

    // Connect first
    let mut connect_args = Map::new();
    connect_args.insert("target".to_string(), Value::String(ipc_path.clone()));

    let connect_result = service
        .call_tool(CallToolRequestParam {
            name: "connect".into(),
            arguments: Some(connect_args),
        })
        .await?;

    let connection_id = extract_connection_id(&connect_result)?;

    // Now test successful disconnect
    let mut disconnect_args = Map::new();
    disconnect_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "disconnect".into(),
            arguments: Some(disconnect_args),
        })
        .await?;

    info!("Disconnect result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains success message
    if let Some(content) = result.content.first() {
        if let Some(text) = content.as_text() {
            assert!(text.text.contains(&ipc_path));
        } else {
            panic!("Expected text content in disconnect result");
        }
    } else {
        panic!("No content in disconnect result");
    }

    // Test that disconnecting again fails (not connected)
    let mut disconnect_args2 = Map::new();
    disconnect_args2.insert("connection_id".to_string(), Value::String(connection_id));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "disconnect".into(),
            arguments: Some(disconnect_args2),
        })
        .await;

    assert!(
        result.is_err(),
        "Should not be able to disconnect when not connected"
    );

    // Cleanup happens automatically via guard
    service.cancel().await?;
    info!("Disconnect nvim tool test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_list_buffers_tool() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test nvim-mcp server");

    // Start Neovim instance and use auto-connect service
    let (service, connection_id, _guard) = setup_connected_service!();

    // Now test list buffers
    let mut list_buffers_args = Map::new();
    list_buffers_args.insert("connection_id".to_string(), Value::String(connection_id));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "list_buffers".into(),
            arguments: Some(list_buffers_args),
        })
        .await?;

    info!("List buffers result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains buffer information
    if let Some(content) = result.content.first() {
        if let Some(text) = content.as_text() {
            // The response should be JSON with buffer info
            assert!(text.text.contains("\"id\""));
            assert!(text.text.contains("\"name\""));
            assert!(text.text.contains("\"line_count\""));
            // Should have at least the initial empty buffer with id 1
            assert!(text.text.contains("\"id\":1"));
        } else {
            panic!("Expected text content in list buffers result");
        }
    } else {
        panic!("No content in list buffers result");
    }

    // Cleanup happens automatically via guard
    service.cancel().await?;
    info!("List buffers tool test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_read_buffer() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test read buffer tool");

    // Start Neovim instance and use auto-connect service
    let (service, connection_id, _guard) = setup_connected_service!();

    // First, let's add some content to the buffer
    let mut exec_lua_args = Map::new();
    exec_lua_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    exec_lua_args.insert(
        "code".to_string(),
        Value::String(
            r#"
            vim.api.nvim_buf_set_lines(0, 0, -1, false, {
                "Hello, World!",
                "This is line 2",
                "This is line 3",
                "End of buffer"
            })
        "#
            .to_string(),
        ),
    );

    service
        .call_tool(CallToolRequestParam {
            name: "exec_lua".into(),
            arguments: Some(exec_lua_args),
        })
        .await?;

    // Test reading entire buffer
    let mut read_args = Map::new();
    read_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    read_args.insert(
        "document".to_string(),
        Value::String(r#"{"buffer_id": 0}"#.to_string()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(read_args),
        })
        .await?;

    info!("Read buffer result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains the expected lines
    if let Some(content) = result.content.first() {
        if let Some(text) = content.as_text() {
            let text_content = &text.text;
            assert!(text_content.contains("Hello, World!"));
            assert!(text_content.contains("This is line 2"));
            assert!(text_content.contains("This is line 3"));
            assert!(text_content.contains("End of buffer"));
        } else {
            panic!("Expected text content in read buffer result");
        }
    } else {
        panic!("No content in read buffer result");
    }

    // Test reading specific line range
    let mut read_range_args = Map::new();
    read_range_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    read_range_args.insert(
        "document".to_string(),
        Value::String(r#"{"buffer_id": 0}"#.to_string()),
    );
    read_range_args.insert("start".to_string(), Value::Number(1.into()));
    read_range_args.insert("end".to_string(), Value::Number(3.into()));

    let range_result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(read_range_args),
        })
        .await?;

    info!("Read buffer range result: {:#?}", range_result);
    assert!(!range_result.content.is_empty());

    // Verify the range response contains only lines 1-2 (0-indexed)
    if let Some(content) = range_result.content.first() {
        if let Some(text) = content.as_text() {
            let text_content = &text.text;
            assert!(!text_content.contains("Hello, World!")); // Line 0, should not be included
            assert!(text_content.contains("This is line 2")); // Line 1, should be included
            assert!(text_content.contains("This is line 3")); // Line 2, should be included
            assert!(!text_content.contains("End of buffer")); // Line 3, should not be included
        } else {
            panic!("Expected text content in read buffer range result");
        }
    } else {
        panic!("No content in read buffer range result");
    }

    service.cancel().await?;
    info!("Read buffer tool test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_read_buffer_invalid() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing read buffer tool with invalid buffer ID");

    let (service, connection_id, _guard) = setup_connected_service!();

    // Test reading from non-existent buffer
    let mut read_args = Map::new();
    read_args.insert("connection_id".to_string(), Value::String(connection_id));
    read_args.insert(
        "document".to_string(),
        Value::String(r#"{"buffer_id": 999}"#.to_string()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(read_args),
        })
        .await;

    // Should fail with invalid buffer ID
    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(error.to_string().contains("Invalid buffer id"));

    service.cancel().await?;
    info!("Invalid buffer test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_complete_workflow() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test nvim-mcp server");

    let service = create_mcp_service!();

    // Start Neovim instance
    let ipc_path = generate_random_ipc_path();
    let _guard = setup_test_neovim_instance(&ipc_path).await?;

    // Step 1: Connect to Neovim
    info!("Step 1: Connecting to Neovim");
    let connection_id = connect_to_neovim!(service, ipc_path);
    info!(
        "✓ Connected successfully with connection_id: {}",
        connection_id
    );

    // Step 2: List buffers
    info!("Step 2: Listing buffers");
    let mut list_buffers_args = Map::new();
    list_buffers_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "list_buffers".into(),
            arguments: Some(list_buffers_args),
        })
        .await?;

    assert!(!result.content.is_empty());
    info!("✓ Listed buffers successfully");

    // Step 3: Get LSP clients
    info!("Step 3: Getting LSP clients");
    let mut lsp_clients_args = Map::new();
    lsp_clients_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_clients".into(),
            arguments: Some(lsp_clients_args),
        })
        .await?;

    assert!(!result.content.is_empty());
    info!("✓ Got LSP clients successfully");

    // Step 4: Disconnect
    info!("Step 4: Disconnecting from Neovim");
    let mut disconnect_args = Map::new();
    disconnect_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "disconnect".into(),
            arguments: Some(disconnect_args),
        })
        .await?;

    assert!(!result.content.is_empty());
    info!("✓ Disconnected successfully");

    // Step 5: Verify we can't list buffers after disconnect
    info!("Step 5: Verifying disconnect");
    let mut invalid_list_args = Map::new();
    invalid_list_args.insert("connection_id".to_string(), Value::String(connection_id));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "list_buffers".into(),
            arguments: Some(invalid_list_args),
        })
        .await;

    assert!(
        result.is_err(),
        "Should not be able to list buffers after disconnect"
    );
    info!("✓ Verified disconnect state");

    // Cleanup happens automatically via guard
    service.cancel().await?;
    info!("Complete workflow test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_error_handling() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test nvim-mcp server");

    let service = create_mcp_service!();

    // Test connecting to invalid address
    let mut invalid_args = Map::new();
    invalid_args.insert(
        "target".to_string(),
        Value::String("invalid:99999".to_string()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "connect_tcp".into(),
            arguments: Some(invalid_args),
        })
        .await;

    assert!(result.is_err(), "Should fail to connect to invalid address");

    // Test calling tools with missing arguments
    let result = service
        .call_tool(CallToolRequestParam {
            name: "connect_tcp".into(),
            arguments: None,
        })
        .await;

    assert!(result.is_err(), "Should fail when arguments are missing");

    // Test calling non-existent tool
    let result = service
        .call_tool(CallToolRequestParam {
            name: "non_existent_tool".into(),
            arguments: None,
        })
        .await;

    assert!(
        result.is_err(),
        "Should fail when calling non-existent tool"
    );

    service.cancel().await?;
    info!("Error handling test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_exec_lua_tool() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting MCP client to test nvim-mcp server");

    // Use auto-connect setup
    let (service, connection_id, _guard) = setup_connected_service!();

    // Test successful Lua execution
    let mut lua_args = Map::new();
    lua_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    lua_args.insert("code".to_string(), Value::String("return 42".to_string()));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "exec_lua".into(),
            arguments: Some(lua_args),
        })
        .await?;

    info!("Exec Lua result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains Lua result
    if let Some(content) = result.content.first() {
        if let Some(text) = content.as_text() {
            assert!(text.text.contains("42"));
        } else {
            panic!("Expected text content in exec_lua result");
        }
    } else {
        panic!("No content in exec_lua result");
    }

    // Test Lua execution with string result
    let mut lua_args = Map::new();
    lua_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    lua_args.insert(
        "code".to_string(),
        Value::String("return 'hello world'".to_string()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "exec_lua".into(),
            arguments: Some(lua_args),
        })
        .await?;

    assert!(!result.content.is_empty());

    // Test successful string execution
    let mut string_lua_args = Map::new();
    string_lua_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    string_lua_args.insert(
        "code".to_string(),
        Value::String("return 'hello world'".to_string()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "exec_lua".into(),
            arguments: Some(string_lua_args),
        })
        .await?;

    assert!(!result.content.is_empty());

    // Cleanup happens automatically via guard
    service.cancel().await?;
    info!("Exec Lua tool test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_lsp_clients_tool() -> Result<(), Box<dyn std::error::Error>> {
    let (service, connection_id, _guard) = setup_connected_service!();

    // Now test lsp_clients
    let mut lsp_clients_args = Map::new();
    lsp_clients_args.insert("connection_id".to_string(), Value::String(connection_id));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_clients".into(),
            arguments: Some(lsp_clients_args),
        })
        .await?;

    info!("LSP clients result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains content
    if let Some(_content) = result.content.first() {
        // Content received successfully - the JSON parsing is handled by the MCP framework
        info!("LSP clients content received successfully");
    } else {
        panic!("No content in lsp_clients result");
    }

    // Cleanup happens automatically via guard
    service.cancel().await?;
    info!("LSP clients tool test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_list_diagnostic_resources() -> Result<(), Box<dyn std::error::Error>> {
    let (service, _, _guard) = setup_connected_service!();

    // Test list_resources
    let result = service.list_resources(None).await?;
    info!("List resources result: {:#?}", result);

    // Verify we have the connections resource
    assert!(!result.resources.is_empty());

    let connections_resource = result
        .resources
        .iter()
        .find(|r| r.raw.uri == "nvim-connections://");

    assert!(
        connections_resource.is_some(),
        "Should have connections resource"
    );

    if let Some(resource) = connections_resource {
        assert_eq!(resource.raw.name, "Active Neovim Connections");
        assert!(resource.raw.description.is_some());
        assert_eq!(resource.raw.mime_type, Some("application/json".to_string()));
    }

    service.cancel().await?;
    info!("List diagnostic resources test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_read_workspace_diagnostics() -> Result<(), Box<dyn std::error::Error>> {
    let (service, connection_id, _guard) = setup_connected_service!();

    // Test read workspace diagnostics resource
    let result = service
        .read_resource(ReadResourceRequestParam {
            uri: format!("nvim-diagnostics://{connection_id}/workspace"),
        })
        .await?;

    info!("Read workspace diagnostics result: {:#?}", result);
    assert!(!result.contents.is_empty());

    // Verify the response contains diagnostic data
    if let Some(_content) = result.contents.first() {
        // Content received successfully - the actual parsing can be tested
        // in more detailed unit tests if needed
        info!("Successfully received resource content");
    } else {
        panic!("No content in workspace diagnostics result");
    }

    // Test reading invalid resource URI
    let result = service
        .read_resource(ReadResourceRequestParam {
            uri: "nvim-diagnostics://invalid/workspace".to_string(),
        })
        .await;

    assert!(result.is_err(), "Should fail for invalid connection ID");

    // Test reading buffer diagnostics resource
    let result = service
        .read_resource(ReadResourceRequestParam {
            uri: format!("nvim-diagnostics://{connection_id}/buffer/1"),
        })
        .await?;

    assert!(!result.contents.is_empty());
    info!("Buffer diagnostics resource read successfully");

    // Test invalid buffer ID
    let result = service
        .read_resource(ReadResourceRequestParam {
            uri: format!("nvim-diagnostics://{connection_id}/buffer/invalid"),
        })
        .await;

    assert!(result.is_err(), "Should fail for invalid buffer ID");

    // Cleanup happens automatically via guard
    service.cancel().await?;
    info!("Read workspace diagnostics test completed successfully");

    Ok(())
}

#[traced_test]
#[tokio::test]
async fn test_lsp_organize_imports_non_existent_file() -> Result<(), Box<dyn std::error::Error>> {
    let (service, connection_id, _guard) = setup_connected_service!();

    // Test lsp_organize_imports with valid connection but non-existent file
    let mut args = Map::new();
    args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    args.insert(
        "document".to_string(),
        Value::String(r#"{"project_relative_path": "non_existent_file.go"}"#.to_string()),
    );
    args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    args.insert("apply_edits".to_string(), Value::Bool(false));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_organize_imports".into(),
            arguments: Some(args),
        })
        .await;
    info!("Organize imports result: {:#?}", result);

    assert!(result.is_err(), "lsp_organize_imports should fail with LSP");
    let r = result.unwrap_err();
    // The result should contain either success message or actions
    assert!(r.to_string().contains("No such file or directory"));

    service.cancel().await?;
    info!("Non-existent file test completed successfully");

    Ok(())
}

#[traced_test]
#[tokio::test]
async fn test_lsp_organize_imports_with_lsp() -> Result<(), Box<dyn std::error::Error>> {
    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("main.go").to_str().unwrap()
    );

    wait_for_lsp_ready!(service, connection_id.clone(), "gopls".to_string());

    // Test lsp_organize_imports with apply_edits=true
    let mut args = Map::new();
    args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    args.insert(
        "document".to_string(),
        Value::String(r#"{"buffer_id": 0}"#.to_string()),
    );
    args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    args.insert("apply_edits".to_string(), Value::Bool(true));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_organize_imports".into(),
            arguments: Some(args),
        })
        .await;

    assert!(
        result.is_ok(),
        "lsp_organize_imports should succeed with LSP"
    );
    let r = result.unwrap();
    info!("Organize imports with LSP succeeded: {:?}", r);
    // The result should contain either success message or actions
    assert!(!r.content.is_empty());
    assert!(
        serde_json::to_string(&r)
            .unwrap()
            .contains("No organize imports actions available for this document")
    );

    service.cancel().await?;
    info!("LSP organize imports test completed successfully");

    Ok(())
}

#[traced_test]
#[tokio::test]
async fn test_lsp_organize_imports_inspect_mode() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing lsp_organize_imports in inspect mode (apply_edits=false)");
    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("organize_imports.go").to_str().unwrap()
    );

    // Wait for LSP client (gopls) to be ready
    let mut wait_lsp_args = Map::new();
    wait_lsp_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    wait_lsp_args.insert(
        "client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    wait_lsp_args.insert("timeout_ms".to_string(), Value::Number(5000.into()));

    service
        .call_tool(CallToolRequestParam {
            name: "wait_for_lsp_ready".into(),
            arguments: Some(wait_lsp_args),
        })
        .await?;

    info!("LSP client ready");

    // Test lsp_organize_imports with apply_edits=false (inspect mode)
    let mut inspect_args = Map::new();
    inspect_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    inspect_args.insert(
        "document".to_string(),
        Value::String(r#"{"buffer_id": 0}"#.to_string()),
    );
    inspect_args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    inspect_args.insert("apply_edits".to_string(), Value::Bool(false));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_organize_imports".into(),
            arguments: Some(inspect_args),
        })
        .await;

    assert!(
        result.is_ok(),
        "lsp_organize_imports should succeed in inspect mode"
    );

    let r = result.unwrap();
    info!("Organize imports inspection succeeded: {:?}", r);
    // The result should contain either code actions or a message about no actions
    assert!(!r.content.is_empty());
    assert!(
        serde_json::to_string(&r)
            .unwrap()
            .contains("documentChanges")
    );

    service.cancel().await?;
    info!("Inspect mode test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_lua_tools_end_to_end_workflow() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing end-to-end Lua tools workflow");

    // Connect to pre-compiled MCP server
    let service = create_mcp_service!();

    info!("Connected to server");

    info!("starting IPC Neovim for testing");

    let ipc_path = generate_random_socket_path();
    let cfg_path = "src/testdata/cfg_lsp.lua";
    let open_file = "src/testdata/main.go";

    let child =
        crate::test_utils::setup_neovim_instance_ipc_advance(&ipc_path, cfg_path, open_file).await;
    let _guard = NeovimIpcGuard::new(child, ipc_path.clone());

    // Neovim should be ready for connection immediately after process start

    let mut connect_args = Map::new();
    connect_args.insert("target".to_string(), Value::String(ipc_path));

    let result = service
        .call_tool(CallToolRequestParam {
            name: "connect".into(),
            arguments: Some(connect_args),
        })
        .await?;

    // Setup Lua tools configuration in Neovim
    let connection_id = extract_connection_id(&result)?;

    // Test tool discovery by listing tools (should include our custom tool)
    let tools_result = service.list_tools(Default::default()).await?;
    info!("Available tools after Lua setup: {:?}", tools_result);

    // Check if our custom tool is discovered
    let tools_contain_save_buffer = tools_result
        .tools
        .iter()
        .any(|tool| tool.name == "save_buffer");
    assert!(
        tools_contain_save_buffer,
        "Custom save_buffer tool should be discovered"
    );

    // Test custom tool execution
    let mut tool_args = Map::new();
    tool_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    tool_args.insert(
        "buffer_id".to_string(),
        Value::Number(serde_json::Number::from(1)),
    );
    let tool_result = service
        .call_tool(CallToolRequestParam {
            name: "save_buffer".into(),
            arguments: Some(tool_args),
        })
        .await;

    // The tool execution may fail (buffer not valid or no file), but it should not crash
    info!("Custom tool execution result: {:?}", tool_result);
    assert!(
        tool_result.is_ok(),
        "Custom tool should execute without error"
    );

    // Test error handling with invalid parameters
    let mut invalid_args = Map::new();
    invalid_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    invalid_args.insert(
        "buffer_id".to_string(),
        Value::Number(serde_json::Number::from(-1)),
    );

    // Test connection cleanup removes tools
    let mut disconnect_args = Map::new();
    disconnect_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );

    let disconnect_result = service
        .call_tool(CallToolRequestParam {
            name: "disconnect".into(),
            arguments: Some(disconnect_args),
        })
        .await?;

    info!("Disconnect result: {:?}", disconnect_result);

    let error_result = service
        .call_tool(CallToolRequestParam {
            name: "save_buffer".into(),
            arguments: Some(invalid_args),
        })
        .await;
    info!("Error handling test result: {:?}", error_result);
    assert!(
        error_result.is_err(),
        "Should fail when calling save_buffer with invalid parameters"
    );

    service.cancel().await?;
    info!("End-to-end Lua tools test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_cursor_position_tool() -> Result<(), Box<dyn std::error::Error>> {
    let (service, connection_id, _guard) = setup_connected_service!();

    // Test successful cursor_position call
    let mut cursor_args = Map::new();
    cursor_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "cursor_position".into(),
            arguments: Some(cursor_args),
        })
        .await?;

    info!("Cursor position result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains cursor position data
    if let Some(content) = result.content.first() {
        if let Some(text) = content.as_text() {
            // Parse JSON response
            let cursor_data: serde_json::Value = serde_json::from_str(&text.text)?;

            // Verify required fields are present
            assert!(
                cursor_data["buffer_name"].is_string(),
                "Should have bufname field"
            );
            assert!(
                cursor_data["buffer_id"].is_number(),
                "Should have buffer_id field"
            );
            assert!(
                cursor_data["window_id"].is_number(),
                "Should have window_id field"
            );
            assert!(cursor_data["row"].is_number(), "Should have row field");
            assert!(cursor_data["col"].is_number(), "Should have col field");

            // Verify coordinates are zero-based (should be 0,0 for new buffer)
            let row = cursor_data["row"].as_i64().expect("row should be a number");
            let col = cursor_data["col"].as_i64().expect("col should be a number");

            assert!(row >= 0, "Row should be zero-based (>= 0)");
            assert!(col >= 0, "Col should be zero-based (>= 0)");

            info!(
                "Cursor position: bufname={}, row={}, col={}",
                cursor_data["bufname"], row, col
            );
        } else {
            panic!("Expected text content in cursor_position result");
        }
    } else {
        panic!("No content in cursor_position result");
    }

    // Cleanup happens automatically via guard
    service.cancel().await?;
    info!("Cursor position tool test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_navigate_tool() -> Result<(), Box<dyn std::error::Error>> {
    let (service, connection_id, _guard) = setup_connected_service!();

    // Create a temporary directory and test file
    let temp_dir = tempfile::tempdir()?;
    let test_file = temp_dir.path().join("test_navigate.txt");
    std::fs::write(&test_file, "line 1\nline 2\nline 3\n")?;

    // Test 1: Navigate to absolute path
    info!("Test 1: Navigate to absolute path");
    let mut navigate_args = Map::new();
    navigate_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    navigate_args.insert(
        "document".to_string(),
        serde_json::json!({
            "absolute_path": test_file.to_string_lossy()
        }),
    );
    navigate_args.insert(
        "line".to_string(),
        Value::Number(serde_json::Number::from(1)),
    );
    navigate_args.insert(
        "character".to_string(),
        Value::Number(serde_json::Number::from(3)),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "navigate".into(),
            arguments: Some(navigate_args),
        })
        .await?;

    // Verify navigation result
    assert!(!result.content.is_empty());
    if let Some(content) = result.content.first()
        && let rmcp::model::RawContent::Text(text_content) = &content.raw
    {
        let navigate_data: serde_json::Value = serde_json::from_str(&text_content.text)?;

        assert!(
            navigate_data["success"].as_bool().unwrap_or(false),
            "Navigation should succeed"
        );
        assert_eq!(navigate_data["line"].as_str().unwrap_or_default(), "line 2");
        info!("✓ Successfully navigated to absolute path");
    }

    // Test 2: Navigate with invalid file path
    info!("Test 2: Navigate to non-existent file");
    let mut invalid_navigate_args = Map::new();
    invalid_navigate_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    invalid_navigate_args.insert(
        "document".to_string(),
        serde_json::json!({
            "absolute_path": "/non/existent/file.txt"
        }),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "navigate".into(),
            arguments: Some(invalid_navigate_args),
        })
        .await;

    assert!(
        result.is_err(),
        "Should fail to navigate to non-existent file"
    );
    info!("✓ Correctly handled invalid file path");

    // Test 3: Navigate to current buffer by ID
    info!("Test 3: Navigate by buffer ID");

    // First get the current buffer list
    let mut list_buffers_args = Map::new();
    list_buffers_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );

    let buffer_result = service
        .call_tool(CallToolRequestParam {
            name: "list_buffers".into(),
            arguments: Some(list_buffers_args),
        })
        .await?;

    if let Some(content) = buffer_result.content.first()
        && let rmcp::model::RawContent::Text(text_content) = &content.raw
    {
        let buffers_data: serde_json::Value = serde_json::from_str(&text_content.text)?;

        if let Some(buffers_array) = buffers_data.as_array()
            && let Some(first_buffer) = buffers_array.first()
            && let Some(buffer_id) = first_buffer["id"].as_u64()
        {
            // Navigate to this buffer
            let mut buffer_navigate_args = Map::new();
            buffer_navigate_args.insert(
                "connection_id".to_string(),
                Value::String(connection_id.clone()),
            );
            buffer_navigate_args.insert(
                "document".to_string(),
                serde_json::json!({
                    "buffer_id": buffer_id
                }),
            );
            buffer_navigate_args.insert(
                "line".to_string(),
                Value::Number(serde_json::Number::from(0)),
            );
            buffer_navigate_args.insert(
                "character".to_string(),
                Value::Number(serde_json::Number::from(0)),
            );

            let result = service
                .call_tool(CallToolRequestParam {
                    name: "navigate".into(),
                    arguments: Some(buffer_navigate_args),
                })
                .await?;

            if let Some(content) = result.content.first()
                && let rmcp::model::RawContent::Text(text_content) = &content.raw
            {
                let navigate_data: serde_json::Value = serde_json::from_str(&text_content.text)?;
                assert!(
                    navigate_data["success"].as_bool().unwrap_or(false),
                    "Navigation by buffer ID should succeed"
                );
                info!("✓ Successfully navigated by buffer ID");
            }
        }
    }

    // Cleanup
    service.cancel().await?;
    info!("Navigate tool test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_lsp_call_hierarchy_prepare() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing lsp_call_hierarchy_prepare");
    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("call_hierarchy.go").to_str().unwrap()
    );

    wait_for_lsp_ready!(service, connection_id.clone(), "gopls".to_string());

    // Test call hierarchy prepare - tool should exist and handle the request
    let mut args = Map::new();
    args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    args.insert(
        "document".to_string(),
        serde_json::json!({
            "buffer_id": 0
        }),
    );
    args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    args.insert(
        "line".to_string(),
        Value::Number(serde_json::Number::from(16)),
    ); // caller function line (0-based)
    args.insert(
        "character".to_string(),
        Value::Number(serde_json::Number::from(5)),
    ); // inside function name

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_call_hierarchy_prepare".into(),
            arguments: Some(args),
        })
        .await;

    info!("Call hierarchy prepare result: {:?}", result);

    // The tool should exist and execute (even if LSP is not available, it should not panic)
    // It may return an error about LSP not being available, but the tool itself should work
    match result {
        Ok(tool_result) => {
            info!("Tool executed successfully: {:?}", tool_result);
            assert!(!tool_result.content.is_empty());
        }
        Err(e) => {
            panic!("Tool failed as expected (LSP may not be ready): {}", e);
            // Tool failure due to LSP unavailability is acceptable in test environment
        }
    }

    service.cancel().await?;
    info!("Call hierarchy prepare test completed successfully");
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_lsp_call_hierarchy_incoming_calls() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing lsp_call_hierarchy_incoming_calls");
    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("call_hierarchy.go").to_str().unwrap()
    );

    wait_for_lsp_ready!(service, connection_id.clone(), "gopls".to_string());

    // Create a mock call hierarchy item for testing
    let mock_hierarchy_item = serde_json::json!({
        "name": "helper",
        "kind": 12, // Function symbol kind
        "uri": get_file_uri("call_hierarchy.go"),
        "range": {
            "start": {"line": 5, "character": 5},
            "end": {"line": 5, "character": 11}
        },
        "selectionRange": {
            "start": {"line": 5, "character": 5},
            "end": {"line": 5, "character": 11}
        }
    });

    // Test incoming calls tool
    let mut args = Map::new();
    args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    args.insert("item".to_string(), mock_hierarchy_item);

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_call_hierarchy_incoming_calls".into(),
            arguments: Some(args),
        })
        .await;

    info!("Call hierarchy incoming calls result: {:?}", result);

    // The tool should exist and execute (even if LSP is not available, it should not panic)
    match result {
        Ok(tool_result) => {
            info!("Tool executed successfully: {:?}", tool_result);
            assert!(!tool_result.content.is_empty());
        }
        Err(e) => {
            panic!("Tool failed as expected (LSP may not be ready): {}", e);
            // Tool failure due to LSP unavailability is acceptable in test environment
        }
    }

    service.cancel().await?;
    info!("Call hierarchy incoming calls test completed successfully");
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_lsp_call_hierarchy_outgoing_calls() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing lsp_call_hierarchy_outgoing_calls");
    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("call_hierarchy.go").to_str().unwrap()
    );

    wait_for_lsp_ready!(service, connection_id.clone(), "gopls".to_string());

    // Create a mock call hierarchy item for testing
    let mock_hierarchy_item = serde_json::json!({
        "name": "caller",
        "kind": 12, // Function symbol kind
        "uri": get_file_uri("call_hierarchy.go"),
        "range": {
            "start": {"line": 16, "character": 5},
            "end": {"line": 16, "character": 11}
        },
        "selectionRange": {
            "start": {"line": 16, "character": 5},
            "end": {"line": 16, "character": 11}
        }
    });

    // Test outgoing calls tool
    let mut args = Map::new();
    args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    args.insert("item".to_string(), mock_hierarchy_item);

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_call_hierarchy_outgoing_calls".into(),
            arguments: Some(args),
        })
        .await;

    info!("Call hierarchy outgoing calls result: {:?}", result);

    // The tool should exist and execute (even if LSP is not available, it should not panic)
    match result {
        Ok(tool_result) => {
            info!("Tool executed successfully: {:?}", tool_result);
            assert!(!tool_result.content.is_empty());
        }
        Err(e) => {
            panic!("Tool failed as expected (LSP may not be ready): {}", e);
            // Tool failure due to LSP unavailability is acceptable in test environment
        }
    }

    service.cancel().await?;
    info!("Call hierarchy outgoing calls test completed successfully");
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_lsp_type_hierarchy_prepare() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing lsp_type_hierarchy_prepare");
    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("type_hierarchy.go").to_str().unwrap()
    );

    wait_for_lsp_ready!(service, connection_id.clone(), "gopls".to_string());

    // Test type hierarchy prepare - tool should exist and handle the request
    let mut args = Map::new();
    args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    args.insert(
        "document".to_string(),
        serde_json::json!({
            "buffer_id": 0
        }),
    );
    args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    args.insert(
        "line".to_string(),
        Value::Number(serde_json::Number::from(11)),
    ); // Shape interface line
    args.insert(
        "character".to_string(),
        Value::Number(serde_json::Number::from(10)),
    ); // inside interface name

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_type_hierarchy_prepare".into(),
            arguments: Some(args),
        })
        .await;

    info!("Type hierarchy prepare result: {:?}", result);

    // The tool should exist and execute (even if LSP is not available, it should not panic)
    // It may return an error about LSP not being available, but the tool itself should work
    match result {
        Ok(tool_result) => {
            info!("Tool executed successfully: {:?}", tool_result);
            assert!(!tool_result.content.is_empty());
        }
        Err(e) => {
            panic!("Tool failed as expected (LSP may not be ready): {}", e);
            // Tool failure due to LSP unavailability is acceptable in test environment
        }
    }

    service.cancel().await?;
    info!("Type hierarchy prepare test completed successfully");
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_lsp_type_hierarchy_supertypes() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing lsp_type_hierarchy_supertypes");
    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("type_hierarchy.go").to_str().unwrap()
    );

    wait_for_lsp_ready!(service, connection_id.clone(), "gopls".to_string());

    // Create a mock type hierarchy item for testing
    let mock_hierarchy_item = serde_json::json!({
        "name": "ColoredShape",
        "kind": 11, // Interface symbol kind
        "uri": get_file_uri("type_hierarchy.go"),
        "range": {
            "start": {"line": 11, "character": 5},
            "end": {"line": 11, "character": 17}
        },
        "selectionRange": {
            "start": {"line": 11, "character": 5},
            "end": {"line": 11, "character": 17}
        }
    });

    // Test supertypes tool
    let mut args = Map::new();
    args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    args.insert("item".to_string(), mock_hierarchy_item);

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_type_hierarchy_supertypes".into(),
            arguments: Some(args),
        })
        .await;

    info!("Type hierarchy supertypes result: {:?}", result);

    // The tool should exist and execute (even if LSP is not available, it should not panic)
    match result {
        Ok(tool_result) => {
            info!("Tool executed successfully: {:?}", tool_result);
            assert!(!tool_result.content.is_empty());
        }
        Err(e) => {
            panic!("Tool failed as expected (LSP may not be ready): {}", e);
            // Tool failure due to LSP unavailability is acceptable in test environment
        }
    }

    service.cancel().await?;
    info!("Type hierarchy supertypes test completed successfully");
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_lsp_type_hierarchy_subtypes() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing lsp_type_hierarchy_subtypes");
    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("type_hierarchy.go").to_str().unwrap()
    );

    wait_for_lsp_ready!(service, connection_id.clone(), "gopls".to_string());

    // Create a mock type hierarchy item for testing
    let mock_hierarchy_item = serde_json::json!({
        "name": "Shape",
        "kind": 11, // Interface symbol kind
        "uri": get_file_uri("type_hierarchy.go"),
        "range": {
            "start": {"line": 5, "character": 5},
            "end": {"line": 5, "character": 10}
        },
        "selectionRange": {
            "start": {"line": 5, "character": 5},
            "end": {"line": 5, "character": 10}
        }
    });

    // Test subtypes tool
    let mut args = Map::new();
    args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    args.insert(
        "lsp_client_name".to_string(),
        Value::String("gopls".to_string()),
    );
    args.insert("item".to_string(), mock_hierarchy_item);

    let result = service
        .call_tool(CallToolRequestParam {
            name: "lsp_type_hierarchy_subtypes".into(),
            arguments: Some(args),
        })
        .await;

    info!("Type hierarchy subtypes result: {:?}", result);

    // The tool should exist and execute (even if LSP is not available, it should not panic)
    match result {
        Ok(tool_result) => {
            info!("Tool executed successfully: {:?}", tool_result);
            assert!(!tool_result.content.is_empty());
        }
        Err(e) => {
            panic!("Tool failed as expected (LSP may not be ready): {}", e);
            // Tool failure due to LSP unavailability is acceptable in test environment
        }
    }

    service.cancel().await?;
    info!("Type hierarchy subtypes test completed successfully");
    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_read_project_relative_path() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing read buffer tool with project relative path");

    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("main.go").to_str().unwrap()
    );

    // Test reading entire file using project relative path
    let mut read_args = Map::new();
    read_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    read_args.insert(
        "document".to_string(),
        serde_json::json!({
            "project_relative_path": "src/testdata/main.go"
        }),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(read_args),
        })
        .await?;

    info!("Read project relative path result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains the expected Go file content
    if let Some(content) = result.content.first() {
        if let Some(text) = content.as_text() {
            let text_content = &text.text;
            assert!(text_content.contains("package main"));
            assert!(text_content.contains("import \"fmt\""));
            assert!(text_content.contains("func main()"));
            assert!(text_content.contains("hello mcp"));
        } else {
            panic!("Expected text content in read buffer project relative path result");
        }
    } else {
        panic!("No content in read buffer project relative path result");
    }

    // Test reading specific line range using project relative path
    let mut read_range_args = Map::new();
    read_range_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    read_range_args.insert(
        "document".to_string(),
        serde_json::json!({
            "project_relative_path": "src/testdata/main.go"
        }),
    );
    read_range_args.insert("start".to_string(), Value::Number(4.into())); // Line 5: func main()
    read_range_args.insert("end".to_string(), Value::Number(7.into())); // Lines 5-6

    let range_result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(read_range_args),
        })
        .await?;

    info!(
        "Read project relative path range result: {:#?}",
        range_result
    );
    assert!(!range_result.content.is_empty());

    // Verify the range response contains only the specified lines
    if let Some(content) = range_result.content.first() {
        if let Some(text) = content.as_text() {
            let text_content = &text.text;
            assert!(text_content.contains("func main()"));
            assert!(text_content.contains("for i := 0; i < 10; i++"));
            assert!(!text_content.contains("package main")); // Should not include line 0
            assert!(!text_content.contains("}")); // Should not include the final closing brace
        } else {
            panic!("Expected text content in read buffer project relative path range result");
        }
    } else {
        panic!("No content in read buffer project relative path range result");
    }

    service.cancel().await?;
    info!("Read buffer project relative path test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_read_absolute_path() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing read buffer tool with absolute path");

    let (service, connection_id, _guard) = setup_connected_service!(
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        get_testdata_path("main.go").to_str().unwrap()
    );

    // Get absolute path to the test file
    let absolute_path = get_testdata_path("main.go")
        .canonicalize()
        .expect("Failed to get canonical path")
        .to_string_lossy()
        .to_string();

    // Test reading entire file using absolute path
    let mut read_args = Map::new();
    read_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    read_args.insert(
        "document".to_string(),
        serde_json::json!({
            "absolute_path": absolute_path
        }),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(read_args),
        })
        .await?;

    info!("Read absolute path result: {:#?}", result);
    assert!(!result.content.is_empty());

    // Verify the response contains the expected Go file content
    if let Some(content) = result.content.first() {
        if let Some(text) = content.as_text() {
            let text_content = &text.text;
            assert!(text_content.contains("package main"));
            assert!(text_content.contains("import \"fmt\""));
            assert!(text_content.contains("func main()"));
            assert!(text_content.contains("hello mcp"));
        } else {
            panic!("Expected text content in read buffer absolute path result");
        }
    } else {
        panic!("No content in read buffer absolute path result");
    }

    // Test reading specific line range using absolute path
    let mut read_range_args = Map::new();
    read_range_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    read_range_args.insert(
        "document".to_string(),
        serde_json::json!({
            "absolute_path": absolute_path
        }),
    );
    read_range_args.insert("start".to_string(), Value::Number(2.into())); // Line 3: import statement
    read_range_args.insert("end".to_string(), Value::Number(5.into())); // Lines 3-4

    let range_result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(read_range_args),
        })
        .await?;

    info!("Read absolute path range result: {:#?}", range_result);
    assert!(!range_result.content.is_empty());

    // Verify the range response contains only the specified lines
    if let Some(content) = range_result.content.first() {
        if let Some(text) = content.as_text() {
            let text_content = &text.text;
            assert!(text_content.contains("import \"fmt\""));
            assert!(text_content.contains("func main()"));
            assert!(!text_content.contains("package main")); // Should not include line 0
            assert!(!text_content.contains("for i := 0")); // Should not include line 5+
        } else {
            panic!("Expected text content in read buffer absolute path range result");
        }
    } else {
        panic!("No content in read buffer absolute path range result");
    }

    service.cancel().await?;
    info!("Read buffer absolute path test completed successfully");

    Ok(())
}

#[tokio::test]
#[traced_test]
async fn test_read_invalid_paths() -> Result<(), Box<dyn std::error::Error>> {
    info!("Testing read buffer tool with invalid paths");

    let (service, connection_id, _guard) = setup_connected_service!();

    // Test with non-existent project relative path
    let mut invalid_project_args = Map::new();
    invalid_project_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    invalid_project_args.insert(
        "document".to_string(),
        serde_json::json!({
            "project_relative_path": "non/existent/file.go"
        }),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(invalid_project_args),
        })
        .await;

    assert!(
        result.is_err(),
        "Should fail with non-existent project relative path"
    );
    let error = result.unwrap_err();
    assert!(
        error.to_string().contains("No such file or directory")
            || error.to_string().contains("not found")
            || error.to_string().contains("cannot find")
            || error.to_string().contains("Can't open file"),
        "Error message should indicate file not found: {}",
        error
    );

    // Test with non-existent absolute path
    let mut invalid_absolute_args = Map::new();
    invalid_absolute_args.insert(
        "connection_id".to_string(),
        Value::String(connection_id.clone()),
    );
    invalid_absolute_args.insert(
        "document".to_string(),
        serde_json::json!({
            "absolute_path": "/completely/non/existent/path/file.txt"
        }),
    );

    let result = service
        .call_tool(CallToolRequestParam {
            name: "read".into(),
            arguments: Some(invalid_absolute_args),
        })
        .await;

    assert!(
        result.is_err(),
        "Should fail with non-existent absolute path"
    );
    let error = result.unwrap_err();
    assert!(
        error.to_string().contains("No such file or directory")
            || error.to_string().contains("not found")
            || error.to_string().contains("cannot find")
            || error.to_string().contains("Can't open file"),
        "Error message should indicate file not found: {}",
        error
    );

    service.cancel().await?;
    info!("Invalid paths test completed successfully");

    Ok(())
}