mcpls-core 0.3.9

Core library for MCP to LSP protocol translation
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
//! Integration tests with real rust-analyzer LSP server.
//!
//! These tests require rust-analyzer to be installed and available in PATH.
//! Run with: cargo nextest run -- --ignored

#![allow(
    clippy::expect_used,
    clippy::unwrap_used,
    clippy::uninlined_format_args,
    clippy::unnecessary_unwrap
)]

use std::path::Path;
use std::sync::{Arc, Once};
use std::time::{Duration, Instant};

use mcpls_core::bridge::{NotificationCache, Translator};
use mcpls_core::config::{LspServerConfig, ServerId, ToolRouter};
use mcpls_core::lsp::{LspServer, ServerInitConfig};
use tokio::sync::Mutex;
use tokio::time::timeout;

use crate::common::test_utils::{rust_analyzer_available, rust_workspace_path};

static INIT_TRACING: Once = Once::new();

fn init_tracing() {
    INIT_TRACING.call_once(|| {
        tracing_subscriber::fmt()
            .with_env_filter(
                tracing_subscriber::EnvFilter::from_default_env()
                    .add_directive(tracing::Level::TRACE.into()),
            )
            .with_test_writer()
            .init();
    });
}

/// Setup helper to spawn rust-analyzer and create a translator.
///
/// This function:
/// 1. Spawns rust-analyzer process
/// 2. Initializes the LSP server
/// 3. Creates and configures a Translator
/// 4. Returns the translator wrapped in `Arc<Mutex>`
async fn setup_rust_analyzer() -> Arc<Mutex<Translator>> {
    init_tracing();
    let workspace_path = rust_workspace_path();

    let lsp_config = LspServerConfig {
        language_id: "rust".to_string(),
        command: "rust-analyzer".to_string(),
        args: vec![],
        env: std::collections::HashMap::new(),
        file_patterns: vec!["**/*.rs".to_string()],
        initialization_options: None,
        timeout_seconds: 30,
        request_timeout_seconds: 30,
        heuristics: None,
        name: None,
        handles: None,
    };

    let server_init_config = ServerInitConfig {
        server_config: lsp_config,
        workspace_roots: vec![workspace_path.clone()],
        initialization_options: None,
        position_encodings: vec!["utf-8".to_string(), "utf-16".to_string()],
        notification_tx: None,
    };

    let server = LspServer::spawn(server_init_config)
        .await
        .expect("Failed to spawn rust-analyzer");

    let client = server.client().clone();

    let extension_map = std::collections::HashMap::from([("rs".to_string(), "rust".to_string())]);
    let mut translator = Translator::new()
        .with_extensions(extension_map)
        .with_router(ToolRouter::catch_all([(
            ServerId::from("rust"),
            "rust".to_string(),
        )]));
    translator.set_workspace_roots(vec![workspace_path]);
    translator.register_client("rust".to_string(), client);
    translator.register_server("rust".to_string(), server);

    Arc::new(Mutex::new(translator))
}

/// Poll hover on the `add` function until rust-analyzer returns consistent results.
///
/// Requires 3 consecutive successful hover responses that contain "fn add" and
/// "i32" before declaring RA ready. This mirrors the approach in `ra_e2e.rs` and
/// is more reliable than waiting for `publishDiagnostics`, which can arrive before
/// type-checking is complete.
async fn wait_for_indexing_ready(
    translator: &Arc<Mutex<Translator>>,
    workspace: &Path,
    timeout: Duration,
) {
    let lib_rs = workspace.join("src/lib.rs");
    let file_path = lib_rs.to_string_lossy().to_string();
    // `pub fn add(` is on line 51; 'a' of "add" is at column 8 (1-based).
    let add_line: u32 = 51;
    let add_col: u32 = 8;

    let deadline = Instant::now() + timeout;
    let required_consecutive: u32 = 3;
    let mut consecutive = 0u32;

    loop {
        if Instant::now() >= deadline {
            tracing::warn!("Timed out waiting for rust-analyzer readiness");
            return;
        }

        let hover_result = translator
            .lock()
            .await
            .handle_hover(file_path.clone(), add_line, add_col)
            .await;

        match hover_result {
            Ok(result) => {
                let text = serde_json::to_string(&result).unwrap_or_default();
                if text.contains("fn add") && text.contains("i32") {
                    consecutive += 1;
                    if consecutive >= required_consecutive {
                        return;
                    }
                } else {
                    consecutive = 0;
                }
            }
            Err(_) => {
                consecutive = 0;
            }
        }

        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_hover_on_std_vec() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let file_path = workspace_path.join("src/lib.rs");

    // Give rust-analyzer time to index the workspace
    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Hover over "String" in User struct (line 20)
    // The line is: `pub name: String,`
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_hover(
            file_path.to_string_lossy().to_string(),
            20,
            19, // Position on "String"
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let hover_result = result.unwrap();
    assert!(
        hover_result.is_ok(),
        "Should successfully get hover: {:?}",
        hover_result.err()
    );

    let hover_json = hover_result.unwrap();
    let hover_str = serde_json::to_string(&hover_json).unwrap();

    // Verify hover contains String type information
    assert!(
        hover_str.contains("String") || hover_str.contains("string"),
        "Hover should contain String type information, got: {}",
        hover_str
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_hover_on_u64_type() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let file_path = workspace_path.join("src/lib.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Hover over "u64" in User struct (line 19)
    // The line is: `pub id: u64,`
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_hover(
            file_path.to_string_lossy().to_string(),
            19,
            13, // Position on "u64"
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let hover_result = result.unwrap();
    assert!(hover_result.is_ok(), "Should successfully get hover");

    let hover_json = hover_result.unwrap();
    let hover_str = serde_json::to_string(&hover_json).unwrap();

    // Verify hover contains u64 type information
    assert!(
        hover_str.contains("u64") || hover_str.contains("unsigned"),
        "Hover should contain u64 type information, got: {}",
        hover_str
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_definition_user_struct() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let types_file = workspace_path.join("src/types.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Go to definition of User in types.rs (line 9, owner: User)
    // The line is: `pub owner: User,`
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_definition(
            types_file.to_string_lossy().to_string(),
            9,
            16, // Position on "User"
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let def_result = result.unwrap();
    assert!(
        def_result.is_ok(),
        "Should successfully get definition: {:?}",
        def_result.err()
    );

    let def_json = def_result.unwrap();
    let def_str = serde_json::to_string(&def_json).unwrap();

    // Verify definition points to lib.rs where User is defined
    assert!(
        def_str.contains("lib.rs") && def_str.contains("User"),
        "Definition should reference User struct in lib.rs, got: {}",
        def_str
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_definition_across_files() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let functions_file = workspace_path.join("src/functions.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Go to definition of Repository in functions.rs (line 3, use statement)
    // The line is: `use crate::types::Repository;`
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_definition(
            functions_file.to_string_lossy().to_string(),
            3,
            24, // Position on "Repository"
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let def_result = result.unwrap();
    assert!(def_result.is_ok(), "Should successfully get definition");

    let def_json = def_result.unwrap();
    let def_str = serde_json::to_string(&def_json).unwrap();

    // Verify definition points to types.rs
    assert!(
        def_str.contains("types.rs") || def_str.contains("Repository"),
        "Definition should reference Repository in types.rs, got: {}",
        def_str
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_references_create_repo_function() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let functions_file = workspace_path.join("src/functions.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Find references to create_repo function (line 7, function name)
    // The line is: `pub fn create_repo(name: &str) -> Repository {`
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_references(
            functions_file.to_string_lossy().to_string(),
            7,
            12,   // Position on "create_repo"
            true, // Include declaration
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let refs_result = result.unwrap();
    assert!(
        refs_result.is_ok(),
        "Should successfully get references: {:?}",
        refs_result.err()
    );

    let refs_json = refs_result.unwrap();

    // Should find at least the definition itself
    assert!(
        !refs_json.locations.is_empty(),
        "Should find at least one reference (the definition)"
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_references_user_struct() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let lib_file = workspace_path.join("src/lib.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Find references to User struct (line 18, struct name)
    // The line is: `pub struct User {`
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_references(
            lib_file.to_string_lossy().to_string(),
            18,
            15, // Position on "User"
            true,
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let refs_result = result.unwrap();
    assert!(refs_result.is_ok(), "Should successfully get references");

    let refs_json = refs_result.unwrap();

    // User is referenced in types.rs and functions.rs, plus the definition
    assert!(
        refs_json.locations.len() >= 2,
        "Should find multiple references to User struct, got: {}",
        refs_json.locations.len()
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_diagnostics_with_error() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let lib_file = workspace_path.join("src/lib.rs");

    // Give rust-analyzer extra time to analyze and generate diagnostics
    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Get diagnostics from lib.rs (has intentional error on line 37). No
    // push notifications are captured in this harness, so the cache is
    // empty and handle_diagnostics falls back to the pull-only result.
    let notification_cache = Mutex::new(NotificationCache::new());
    let result = timeout(
        Duration::from_secs(10),
        translator
            .lock()
            .await
            .handle_diagnostics(lib_file.to_string_lossy().to_string(), &notification_cache),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let diag_result = result.unwrap();
    assert!(
        diag_result.is_ok(),
        "Should successfully get diagnostics: {:?}",
        diag_result.err()
    );

    let diag_json = diag_result.unwrap();
    let diag_str = serde_json::to_string(&diag_json).unwrap();

    // Should contain the error about undefined_variable
    assert!(
        diag_str.contains("undefined_variable") || diag_str.contains("cannot find"),
        "Diagnostics should report the intentional error, got: {}",
        diag_str
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_diagnostics_no_errors() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let types_file = workspace_path.join("src/types.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Get diagnostics from types.rs (should have no errors)
    let notification_cache = Mutex::new(NotificationCache::new());
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_diagnostics(
            types_file.to_string_lossy().to_string(),
            &notification_cache,
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let diag_result = result.unwrap();
    assert!(diag_result.is_ok(), "Should successfully get diagnostics");

    let diag_json = diag_result.unwrap();

    // types.rs should have no errors or warnings
    // (it's a clean file without issues)
    let errors: Vec<_> = diag_json
        .diagnostics
        .iter()
        .filter(|d| matches!(d.severity, mcpls_core::bridge::DiagnosticSeverity::Error))
        .collect();

    assert!(
        errors.is_empty(),
        "types.rs should have no errors, got: {:?}",
        errors
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_document_symbols() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let lib_file = workspace_path.join("src/lib.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Get document symbols from lib.rs
    let result = timeout(
        Duration::from_secs(10),
        translator
            .lock()
            .await
            .handle_document_symbols(lib_file.to_string_lossy().to_string()),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let symbols_result = result.unwrap();
    assert!(
        symbols_result.is_ok(),
        "Should successfully get symbols: {:?}",
        symbols_result.err()
    );

    let symbols_json = symbols_result.unwrap();
    let symbols_str = serde_json::to_string(&symbols_json).unwrap();

    // Should contain User struct
    assert!(
        symbols_str.contains("User"),
        "Should find User struct, got: {}",
        symbols_str
    );

    // Should contain has_error function
    assert!(
        symbols_str.contains("has_error"),
        "Should find has_error function, got: {}",
        symbols_str
    );

    // Should contain has_warning function
    assert!(
        symbols_str.contains("has_warning"),
        "Should find has_warning function, got: {}",
        symbols_str
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_document_symbols_types_file() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let types_file = workspace_path.join("src/types.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Get document symbols from types.rs
    let result = timeout(
        Duration::from_secs(10),
        translator
            .lock()
            .await
            .handle_document_symbols(types_file.to_string_lossy().to_string()),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let symbols_result = result.unwrap();
    assert!(symbols_result.is_ok(), "Should successfully get symbols");

    let symbols_json = symbols_result.unwrap();
    let symbols_str = serde_json::to_string(&symbols_json).unwrap();

    // Should contain Repository struct
    assert!(
        symbols_str.contains("Repository"),
        "Should find Repository struct, got: {}",
        symbols_str
    );

    // Should contain methods
    assert!(
        symbols_str.contains("new") || symbols_str.contains("get_owner"),
        "Should find struct methods, got: {}",
        symbols_str
    );
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_completions_basic() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let functions_file = workspace_path.join("src/functions.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Get completions in functions.rs
    // Position after "repo." on line 23 (repo.get_owner().name)
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_completions(
            functions_file.to_string_lossy().to_string(),
            23,
            11, // Position after "repo."
            None,
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let completions_result = result.unwrap();

    // Completions might not always be available depending on timing, so only assert
    // on content when the call actually succeeded.
    if let Ok(completions_json) = completions_result {
        let completions_str = serde_json::to_string(&completions_json).unwrap();
        assert!(
            completions_str.contains("get_owner")
                || completions_str.contains("name")
                || completions_str.contains("stars"),
            "Completions should include Repository fields/methods, got: {}",
            completions_str
        );
    }
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_format_document() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let lib_file = workspace_path.join("src/lib.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Request document formatting
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_format_document(
            lib_file.to_string_lossy().to_string(),
            4,    // tab_size
            true, // insert_spaces
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let format_result = result.unwrap();

    // rust-analyzer may or may not support formatting directly
    // (often defers to rustfmt which needs to be configured separately)
    // So we just check that the call doesn't error out catastrophically
    match format_result {
        Ok(format_json) => {
            // Format succeeded, verify it returns edits
            println!("Format response: {:?}", format_json);
        }
        Err(e) => {
            // Format might not be supported, which is ok for this test
            println!("Format not supported or failed (expected): {:?}", e);
        }
    }
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_timeout_handling() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let lib_file = workspace_path.join("src/lib.rs");

    // Very short timeout to test timeout behavior
    let result = timeout(
        Duration::from_millis(1), // 1ms - should timeout
        translator
            .lock()
            .await
            .handle_hover(lib_file.to_string_lossy().to_string(), 20, 19),
    )
    .await;

    // Should timeout
    assert!(result.is_err(), "Should timeout with 1ms timeout");
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_invalid_file_path() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;

    // Try to get hover on non-existent file
    let result = translator
        .lock()
        .await
        .handle_hover("/nonexistent/file.rs".to_string(), 1, 1)
        .await;

    // Should return an error (file not found or not in workspace)
    assert!(result.is_err(), "Should fail for non-existent file");
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_out_of_bounds_position() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;
    let workspace_path = rust_workspace_path();
    let lib_file = workspace_path.join("src/lib.rs");

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Try to get hover at an extremely large line number
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_hover(
            lib_file.to_string_lossy().to_string(),
            99999, // Way beyond file bounds
            1,
        ),
    )
    .await;

    // LSP server should handle this gracefully (might return empty or error)
    assert!(
        result.is_ok(),
        "Should not timeout even with out-of-bounds position"
    );

    // The actual result might be Ok(empty) or Err, both are acceptable
    // We just want to ensure it doesn't hang or crash
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_workspace_symbol_search_basic() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;

    // Give rust-analyzer time to index the workspace
    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Search for "User" struct
    let result = timeout(
        Duration::from_secs(10),
        translator
            .lock()
            .await
            .handle_workspace_symbol("User".to_string(), None, 100),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let symbol_result = result.unwrap();
    assert!(
        symbol_result.is_ok(),
        "Should successfully search symbols: {:?}",
        symbol_result.err()
    );

    let symbols = symbol_result.unwrap();
    let symbols_str = serde_json::to_string(&symbols).unwrap();
    println!("Workspace symbols for 'User': {}", symbols_str);

    // Should find the User struct
    assert!(
        !symbols.symbols.is_empty(),
        "Should find at least one symbol for 'User'"
    );

    // Verify at least one result is the User struct
    let has_user_struct = symbols.symbols.iter().any(|s| s.name == "User");
    assert!(has_user_struct, "Should find User struct in results");
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_workspace_symbol_search_with_kind_filter() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Search for symbols and filter by Struct kind
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_workspace_symbol(
            String::new(), // Empty query to get all symbols
            Some("Struct".to_string()),
            100,
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let symbol_result = result.unwrap();

    if let Ok(symbols) = symbol_result {
        println!("Found {} struct symbols", symbols.symbols.len());

        // All results should be structs
        for symbol in &symbols.symbols {
            assert_eq!(
                symbol.kind, "Struct",
                "All filtered results should be Struct kind"
            );
        }
    }
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_workspace_symbol_search_max_results() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Search with very low limit
    let result = timeout(
        Duration::from_secs(10),
        translator
            .lock()
            .await
            .handle_workspace_symbol(String::new(), None, 5),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let symbol_result = result.unwrap();

    if let Ok(symbols) = symbol_result {
        println!("Found {} symbols (limited to 5)", symbols.symbols.len());
        assert!(
            symbols.symbols.len() <= 5,
            "Should respect max_results limit of 5"
        );
    }
}

#[tokio::test]
#[ignore = "Requires rust-analyzer installed"]
async fn test_workspace_symbol_search_function() {
    if !rust_analyzer_available() {
        eprintln!("Skipping: rust-analyzer not available");
        return;
    }

    let translator = setup_rust_analyzer().await;

    wait_for_indexing_ready(&translator, &rust_workspace_path(), Duration::from_secs(30)).await;

    // Search for function symbols
    let result = timeout(
        Duration::from_secs(10),
        translator.lock().await.handle_workspace_symbol(
            "create".to_string(),
            Some("Function".to_string()),
            100,
        ),
    )
    .await;

    assert!(result.is_ok(), "Should not timeout");
    let symbol_result = result.unwrap();

    if let Ok(symbols) = symbol_result {
        println!("Found {} function symbols", symbols.symbols.len());

        // All results should be functions
        for symbol in &symbols.symbols {
            assert_eq!(
                symbol.kind, "Function",
                "All filtered results should be Function kind"
            );
        }

        // Should find functions with "create" in the name
        if !symbols.symbols.is_empty() {
            let has_create = symbols
                .symbols
                .iter()
                .any(|s| s.name.to_lowercase().contains("create"));
            println!("Has 'create' in name: {}", has_create);
        }
    }
}