context-creator 1.5.0

High-performance CLI tool to convert codebases to Markdown for LLM context
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
//! Comprehensive acceptance tests for MCP server
//! These tests serve as both validation and documentation of the MCP server functionality

use anyhow::Result;
use jsonrpsee::core::client::ClientT;
use jsonrpsee::http_client::{HttpClient, HttpClientBuilder};
use jsonrpsee::rpc_params;
use serde_json::json;
use std::process::{Child, Command};
use std::time::Duration;
use tempfile::TempDir;
use tokio::time::sleep;

/// Test server configuration
struct TestServer {
    process: Child,
    #[allow(dead_code)]
    port: u16,
    client: HttpClient,
}

impl TestServer {
    /// Start a test MCP server
    async fn start() -> Result<Self> {
        let port = 8123; // Use a fixed port for testing

        // Build the binary in release mode for realistic performance testing
        let output = Command::new("cargo")
            .args(["build", "--release"])
            .output()?;

        if !output.status.success() {
            anyhow::bail!(
                "Failed to build binary: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Start the server
        let process = Command::new("./target/release/context-creator")
            .arg("--mcp")
            .arg("--mcp-port")
            .arg(port.to_string())
            .spawn()?;

        // Wait for server to start
        sleep(Duration::from_millis(500)).await;

        // Create client
        let client = HttpClientBuilder::default().build(format!("http://127.0.0.1:{port}"))?;

        Ok(Self {
            process,
            port,
            client,
        })
    }

    /// Stop the test server
    fn stop(mut self) -> Result<()> {
        self.process.kill()?;
        Ok(())
    }
}

#[tokio::test]
async fn test_health_check_endpoint() -> Result<()> {
    let server = TestServer::start().await?;

    // Test: Basic health check
    let response: serde_json::Value = server.client.request("health_check", rpc_params![]).await?;

    assert_eq!(response["status"], "healthy");
    assert!(response["timestamp"].is_number());
    assert!(response["version"].is_string());

    // Document the response format
    println!(
        "Health check response: {}",
        serde_json::to_string_pretty(&response)?
    );

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_process_local_codebase_basic() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Create a simple test project
    std::fs::write(
        temp_dir.path().join("main.rs"),
        r#"
fn main() {
    println!("Hello, world!");
}

fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_add() {
        assert_eq!(add(2, 2), 4);
    }
}
"#,
    )?;

    std::fs::write(
        temp_dir.path().join("lib.rs"),
        r#"
pub struct Calculator {
    value: i32,
}

impl Calculator {
    pub fn new() -> Self {
        Self { value: 0 }
    }
    
    pub fn add(&mut self, n: i32) {
        self.value += n;
    }
    
    pub fn get_value(&self) -> i32 {
        self.value
    }
}
"#,
    )?;

    // Test 1: Basic question about the codebase
    let response: serde_json::Value = server
        .client
        .request(
            "process_local_codebase",
            rpc_params![json!({
                "prompt": "What does this codebase do? List all the functions and their purposes.",
                "path": temp_dir.path(),
                "include_patterns": ["**/*.rs"],
                "ignore_patterns": [],
                "include_imports": false,
                "include_context": true
            })],
        )
        .await?;

    // Verify response structure
    assert!(response["answer"].is_string());
    assert!(response["context"].is_string());
    assert!(response["file_count"].as_u64().unwrap() >= 2);
    assert!(response["token_count"].is_number());
    assert!(response["processing_time_ms"].is_number());
    assert_eq!(response["llm_tool"], "gemini");

    // The answer should mention the functions
    let answer = response["answer"].as_str().unwrap();
    assert!(answer.contains("main") || answer.contains("add") || answer.contains("Calculator"));

    println!(
        "Basic codebase analysis response: {}",
        serde_json::to_string_pretty(&response)?
    );

    // Test 2: Specific query with file filtering
    let response: serde_json::Value = server
        .client
        .request(
            "process_local_codebase",
            rpc_params![json!({
                "prompt": "Find all test functions and explain what they test",
                "path": temp_dir.path(),
                "include_patterns": ["**/main.rs"],
                "ignore_patterns": [],
                "include_imports": false,
                "llm_tool": "gemini"
            })],
        )
        .await?;

    assert!(response["answer"].as_str().unwrap().contains("test_add"));
    assert_eq!(response["file_count"], 1);

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_process_local_codebase_with_imports() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Create a project with imports
    std::fs::create_dir_all(temp_dir.path().join("src"))?;

    std::fs::write(
        temp_dir.path().join("src/main.rs"),
        r#"
mod utils;
mod config;

use utils::process_data;
use config::Config;

fn main() {
    let config = Config::load();
    let data = vec![1, 2, 3, 4, 5];
    let result = process_data(&data, &config);
    println!("Result: {:?}", result);
}
"#,
    )?;

    std::fs::write(
        temp_dir.path().join("src/utils.rs"),
        r#"
use crate::config::Config;

pub fn process_data(data: &[i32], config: &Config) -> Vec<i32> {
    data.iter()
        .map(|&x| x * config.multiplier)
        .collect()
}

pub fn validate_data(data: &[i32]) -> bool {
    !data.is_empty() && data.iter().all(|&x| x > 0)
}
"#,
    )?;

    std::fs::write(
        temp_dir.path().join("src/config.rs"),
        r#"
pub struct Config {
    pub multiplier: i32,
    pub debug: bool,
}

impl Config {
    pub fn load() -> Self {
        Self {
            multiplier: 2,
            debug: false,
        }
    }
}
"#,
    )?;

    // Test with import tracing enabled
    let response: serde_json::Value = server.client
        .request("process_local_codebase", rpc_params![json!({
            "prompt": "Explain how the data processing flow works, tracing through all the imports and dependencies",
            "path": temp_dir.path().join("src"),
            "include_patterns": ["**/*.rs"],
            "ignore_patterns": [],
            "include_imports": true,
            "include_context": true
        })])
        .await?;

    let answer = response["answer"].as_str().unwrap();
    let context = response["context"].as_str().unwrap();

    // Should explain the flow through imports
    assert!(answer.contains("process_data") || answer.contains("Config"));

    // Context should include all related files when imports are traced
    assert!(context.contains("main.rs"));
    assert!(context.contains("utils.rs"));
    assert!(context.contains("config.rs"));

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_process_remote_repo() -> Result<()> {
    let server = TestServer::start().await?;

    // Test with a small public repository
    let response: serde_json::Value = server
        .client
        .request(
            "process_remote_repo",
            rpc_params![json!({
                "prompt": "What is the main purpose of this repository? What are its key features?",
                "repo_url": "https://github.com/rust-lang/mdBook.git",
                "include_patterns": ["**/*.rs", "**/*.md"],
                "ignore_patterns": ["target/**", ".git/**"],
                "include_imports": false,
                "max_tokens": 50000,
                "include_context": false
            })],
        )
        .await?;

    assert!(response["answer"].is_string());
    assert!(response["repo_name"].is_string());
    assert!(response["file_count"].as_u64().unwrap() > 0);
    assert_eq!(response["llm_tool"], "gemini");

    println!(
        "Remote repo analysis: {}",
        serde_json::to_string_pretty(&response)?
    );

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_get_file_metadata() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Create test files with different types
    let rust_file = temp_dir.path().join("test.rs");
    std::fs::write(&rust_file, "fn main() {}")?;

    let python_file = temp_dir.path().join("test.py");
    std::fs::write(&python_file, "def main():\n    pass")?;

    let binary_file = temp_dir.path().join("test.bin");
    std::fs::write(&binary_file, [0u8, 1, 2, 3, 255])?;

    // Test Rust file
    let response: serde_json::Value = server
        .client
        .request(
            "get_file_metadata",
            rpc_params![json!({
                "file_path": rust_file
            })],
        )
        .await?;

    assert!(response["size"].as_u64().unwrap() > 0);
    assert!(response["modified"].is_number());
    assert_eq!(response["is_symlink"], false);
    assert_eq!(response["language"], "rust");

    // Test Python file
    let response: serde_json::Value = server
        .client
        .request(
            "get_file_metadata",
            rpc_params![json!({
                "file_path": python_file
            })],
        )
        .await?;

    assert_eq!(response["language"], "python");

    // Test binary file
    let response: serde_json::Value = server
        .client
        .request(
            "get_file_metadata",
            rpc_params![json!({
                "file_path": binary_file
            })],
        )
        .await?;

    assert_eq!(response["language"], json!(null));

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_search_codebase() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Create files with searchable content
    std::fs::write(
        temp_dir.path().join("auth.rs"),
        r#"
use bcrypt::{hash, verify};

pub fn hash_password(password: &str) -> Result<String, Error> {
    hash(password, 10)
}

pub fn verify_password(password: &str, hash: &str) -> Result<bool, Error> {
    verify(password, hash)
}

pub fn authenticate_user(username: &str, password: &str) -> bool {
    // TODO: Implement database lookup
    if username == "admin" && password == "secret" {
        return true;
    }
    false
}
"#,
    )?;

    std::fs::write(
        temp_dir.path().join("user.rs"),
        r#"
pub struct User {
    username: String,
    email: String,
    password_hash: String,
}

impl User {
    pub fn new(username: String, email: String, password: &str) -> Self {
        let password_hash = crate::auth::hash_password(password).unwrap();
        Self {
            username,
            email,
            password_hash,
        }
    }
    
    pub fn verify_password(&self, password: &str) -> bool {
        crate::auth::verify_password(password, &self.password_hash).unwrap_or(false)
    }
}
"#,
    )?;

    // Test 1: Search for password-related code
    let response: serde_json::Value = server
        .client
        .request(
            "search_codebase",
            rpc_params![json!({
                "path": temp_dir.path(),
                "query": "password",
                "max_results": 10
            })],
        )
        .await?;

    assert!(response["total_matches"].as_u64().unwrap() >= 4);
    assert!(!response["results"].as_array().unwrap().is_empty());

    let first_result = &response["results"][0];
    assert!(first_result["line_content"]
        .as_str()
        .unwrap()
        .contains("password"));

    // Test 2: Search with file pattern
    let response: serde_json::Value = server
        .client
        .request(
            "search_codebase",
            rpc_params![json!({
                "path": temp_dir.path(),
                "query": "username",
                "file_pattern": "**/user.rs"
            })],
        )
        .await?;

    assert!(response["results"]
        .as_array()
        .unwrap()
        .iter()
        .all(|r| r["file_path"].as_str().unwrap().ends_with("user.rs")));

    println!(
        "Search results: {}",
        serde_json::to_string_pretty(&response)?
    );

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_diff_files() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Create two versions of a file
    let file1 = temp_dir.path().join("version1.rs");
    std::fs::write(
        &file1,
        r#"
fn calculate(x: i32, y: i32) -> i32 {
    x + y
}

fn main() {
    let result = calculate(5, 3);
    println!("Result: {}", result);
}
"#,
    )?;

    let file2 = temp_dir.path().join("version2.rs");
    std::fs::write(
        &file2,
        r#"
fn calculate(x: i32, y: i32, operation: &str) -> i32 {
    match operation {
        "add" => x + y,
        "subtract" => x - y,
        "multiply" => x * y,
        _ => 0,
    }
}

fn main() {
    let result = calculate(5, 3, "add");
    println!("Addition: {}", result);
    
    let result2 = calculate(10, 4, "multiply");
    println!("Multiplication: {}", result2);
}
"#,
    )?;

    // Get diff
    let response: serde_json::Value = server
        .client
        .request(
            "diff_files",
            rpc_params![json!({
                "file1_path": file1,
                "file2_path": file2,
                "context_lines": 3
            })],
        )
        .await?;

    assert!(!response["hunks"].as_array().unwrap().is_empty());
    assert!(response["added_lines"].as_u64().unwrap() > 0);
    assert!(response["removed_lines"].as_u64().unwrap() > 0);
    assert_eq!(response["is_binary"], false);

    // Check that diff shows the function signature change
    let hunks = response["hunks"].as_array().unwrap();
    let hunk_content = hunks[0]["content"].as_str().unwrap();
    assert!(hunk_content.contains("operation: &str"));

    println!("Diff output: {}", serde_json::to_string_pretty(&response)?);

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_semantic_search() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Create a complex codebase for semantic search
    std::fs::write(
        temp_dir.path().join("main.rs"),
        r#"
mod database;
mod handlers;
mod models;

use handlers::{UserHandler, PostHandler};
use models::{User, Post};

fn main() {
    let user_handler = UserHandler::new();
    let post_handler = PostHandler::new();
    
    // Example usage
    let user = user_handler.create_user("john", "john@example.com");
    let post = post_handler.create_post(&user, "Hello World", "My first post");
}
"#,
    )?;

    std::fs::write(
        temp_dir.path().join("models.rs"),
        r#"
#[derive(Debug, Clone)]
pub struct User {
    pub id: u64,
    pub username: String,
    pub email: String,
}

#[derive(Debug)]
pub struct Post {
    pub id: u64,
    pub author: User,
    pub title: String,
    pub content: String,
}

pub trait Model {
    fn id(&self) -> u64;
}

impl Model for User {
    fn id(&self) -> u64 {
        self.id
    }
}

impl Model for Post {
    fn id(&self) -> u64 {
        self.id
    }
}
"#,
    )?;

    std::fs::write(
        temp_dir.path().join("handlers.rs"),
        r#"
use crate::models::{User, Post};

pub struct UserHandler {
    next_id: u64,
}

impl UserHandler {
    pub fn new() -> Self {
        Self { next_id: 1 }
    }
    
    pub fn create_user(&mut self, username: &str, email: &str) -> User {
        let user = User {
            id: self.next_id,
            username: username.to_string(),
            email: email.to_string(),
        };
        self.next_id += 1;
        user
    }
}

pub struct PostHandler {
    next_id: u64,
}

impl PostHandler {
    pub fn new() -> Self {
        Self { next_id: 1 }
    }
    
    pub fn create_post(&mut self, author: &User, title: &str, content: &str) -> Post {
        let post = Post {
            id: self.next_id,
            author: author.clone(),
            title: title.to_string(),
            content: content.to_string(),
        };
        self.next_id += 1;
        post
    }
}
"#,
    )?;

    // Test 1: Find all functions
    let response: serde_json::Value = server
        .client
        .request(
            "semantic_search",
            rpc_params![json!({
                "path": temp_dir.path(),
                "query": "create",
                "search_type": "functions",
                "max_results": 10
            })],
        )
        .await?;

    let results = response["results"].as_array().unwrap();
    assert!(results.len() >= 2); // Should find create_user and create_post
    assert!(results
        .iter()
        .any(|r| r["symbol_name"].as_str().unwrap().contains("create_user")));
    assert!(results
        .iter()
        .any(|r| r["symbol_name"].as_str().unwrap().contains("create_post")));

    // Test 2: Find all types/structs
    let response: serde_json::Value = server
        .client
        .request(
            "semantic_search",
            rpc_params![json!({
                "path": temp_dir.path(),
                "query": "",
                "search_type": "types",
                "max_results": 20
            })],
        )
        .await?;

    let results = response["results"].as_array().unwrap();
    assert!(results.iter().any(|r| r["symbol_name"] == "User"));
    assert!(results.iter().any(|r| r["symbol_name"] == "Post"));
    assert!(results.iter().any(|r| r["symbol_name"] == "UserHandler"));

    // Test 3: Find imports
    let response: serde_json::Value = server
        .client
        .request(
            "semantic_search",
            rpc_params![json!({
                "path": temp_dir.path(),
                "query": "models",
                "search_type": "imports"
            })],
        )
        .await?;

    assert!(response["total_matches"].as_u64().unwrap() > 0);

    // Test 4: Find references to a symbol
    let response: serde_json::Value = server
        .client
        .request(
            "semantic_search",
            rpc_params![json!({
                "path": temp_dir.path(),
                "query": "User",
                "search_type": "references"
            })],
        )
        .await?;

    // Should find references in multiple files
    let file_paths: Vec<_> = response["results"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["file_path"].as_str().unwrap())
        .collect();

    assert!(file_paths.iter().any(|p| p.ends_with("models.rs")));
    assert!(file_paths.iter().any(|p| p.ends_with("handlers.rs")));

    println!(
        "Semantic search results: {}",
        serde_json::to_string_pretty(&response)?
    );

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_performance_and_caching() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Create a moderately complex project
    for i in 0..10 {
        std::fs::write(
            temp_dir.path().join(format!("module{i}.rs")),
            format!(
                r#"
pub mod module{i} {{
    pub fn process_{i}_data(input: &[u8]) -> Vec<u8> {{
        input.iter().map(|&b| b.wrapping_add({i} as u8)).collect()
    }}
    
    pub struct Processor{i} {{
        id: u64,
        name: String,
    }}
    
    impl Processor{i} {{
        pub fn new(name: String) -> Self {{
            Self {{ id: {i}, name }}
        }}
    }}
}}
"#
            ),
        )?;
    }

    // First request (cache miss)
    let start1 = std::time::Instant::now();
    let response1: serde_json::Value = server
        .client
        .request(
            "process_local_codebase",
            rpc_params![json!({
                "prompt": "List all the processor types and their IDs",
                "path": temp_dir.path(),
                "include_patterns": ["**/*.rs"],
                "ignore_patterns": [],
                "include_imports": false
            })],
        )
        .await?;
    let duration1 = start1.elapsed();

    // Second identical request (cache hit)
    let start2 = std::time::Instant::now();
    let response2: serde_json::Value = server
        .client
        .request(
            "process_local_codebase",
            rpc_params![json!({
                "prompt": "List all the processor types and their IDs",
                "path": temp_dir.path(),
                "include_patterns": ["**/*.rs"],
                "ignore_patterns": [],
                "include_imports": false
            })],
        )
        .await?;
    let duration2 = start2.elapsed();

    // Cache should make second request much faster
    assert!(
        duration2 < duration1 / 2,
        "Cache didn't improve performance: {duration1:?} vs {duration2:?}"
    );

    // Responses should be identical
    assert_eq!(response1["answer"], response2["answer"]);
    assert_eq!(response1["file_count"], response2["file_count"]);

    println!("Performance test - First request: {duration1:?}, Cached request: {duration2:?}");

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_concurrent_requests() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Create test files
    for i in 0..5 {
        std::fs::write(
            temp_dir.path().join(format!("file{i}.rs")),
            format!("fn function_{i}() {{ println!(\"{i}\"); }}"),
        )?;
    }

    // Send multiple concurrent requests
    let mut handles = vec![];

    for i in 0..5 {
        let client = server.client.clone();
        let path = temp_dir.path().to_path_buf();

        let handle = tokio::spawn(async move {
            let response: serde_json::Value = client
                .request(
                    "process_local_codebase",
                    rpc_params![json!({
                        "prompt": format!("What does function_{} do?", i),
                        "path": path,
                        "include_patterns": [format!("**/file{}.rs", i)],
                        "ignore_patterns": [],
                        "include_imports": false
                    })],
                )
                .await?;
            Ok::<_, anyhow::Error>(response)
        });

        handles.push(handle);
    }

    // Wait for all requests to complete
    let mut results = vec![];
    for handle in handles {
        results.push(handle.await);
    }

    // All requests should succeed
    for (i, result) in results.iter().enumerate() {
        let response = result.as_ref().unwrap().as_ref().unwrap();
        assert!(response["answer"]
            .as_str()
            .unwrap()
            .contains(&format!("{i}")));
    }

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_security_validation() -> Result<()> {
    let server = TestServer::start().await?;

    // Test 1: Path traversal attempt
    let result: Result<serde_json::Value, _> = server
        .client
        .request(
            "process_local_codebase",
            rpc_params![json!({
                "prompt": "What's in this directory?",
                "path": "../../../etc",
                "include_patterns": ["**/*"],
                "ignore_patterns": [],
                "include_imports": false
            })],
        )
        .await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(error.to_string().contains("Invalid path") || error.to_string().contains("traversal"));

    // Test 2: Invalid repository URL
    let result: Result<serde_json::Value, _> = server
        .client
        .request(
            "process_remote_repo",
            rpc_params![json!({
                "prompt": "Analyze this repo",
                "repo_url": "file:///etc/passwd",
                "include_patterns": [],
                "ignore_patterns": [],
                "include_imports": false
            })],
        )
        .await;

    assert!(result.is_err());

    // Test 3: Non-existent path
    let result: Result<serde_json::Value, _> = server
        .client
        .request(
            "get_file_metadata",
            rpc_params![json!({
                "file_path": "/definitely/does/not/exist/file.rs"
            })],
        )
        .await;

    assert!(result.is_err());

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_edge_cases() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    // Test 1: Empty directory
    let empty_dir = temp_dir.path().join("empty");
    std::fs::create_dir(&empty_dir)?;

    let response: serde_json::Value = server
        .client
        .request(
            "process_local_codebase",
            rpc_params![json!({
                "prompt": "What files are in this directory?",
                "path": empty_dir,
                "include_patterns": ["**/*"],
                "ignore_patterns": [],
                "include_imports": false
            })],
        )
        .await?;

    assert_eq!(response["file_count"], 0);

    // Test 2: Binary files
    let binary_file = temp_dir.path().join("binary.dat");
    std::fs::write(&binary_file, [0u8, 1, 2, 3, 255, 254, 253])?;

    let response: serde_json::Value = server
        .client
        .request(
            "diff_files",
            rpc_params![json!({
                "file1_path": &binary_file,
                "file2_path": &binary_file,
                "context_lines": 3
            })],
        )
        .await?;

    assert_eq!(response["is_binary"], true);

    // Test 3: Very long prompt with token limits
    let long_prompt = "Explain this: ".repeat(1000);
    let response: serde_json::Value = server
        .client
        .request(
            "process_local_codebase",
            rpc_params![json!({
                "prompt": long_prompt,
                "path": temp_dir.path(),
                "include_patterns": ["**/*"],
                "ignore_patterns": [],
                "include_imports": false,
                "max_tokens": 1000
            })],
        )
        .await?;

    // Should still work but with limited context
    assert!(response["answer"].is_string());

    // Test 4: Special characters in file names
    let special_file = temp_dir.path().join("file with spaces & special.rs");
    std::fs::write(&special_file, "fn main() {}")?;

    let response: serde_json::Value = server
        .client
        .request(
            "get_file_metadata",
            rpc_params![json!({
                "file_path": special_file
            })],
        )
        .await?;

    assert_eq!(response["language"], "rust");

    server.stop()?;
    Ok(())
}

#[tokio::test]
async fn test_llm_tool_selection() -> Result<()> {
    let server = TestServer::start().await?;
    let temp_dir = TempDir::new()?;

    std::fs::write(
        temp_dir.path().join("test.rs"),
        "fn main() { println!(\"Hello\"); }",
    )?;

    // Test with different LLM tools
    for tool in &["gemini", "codex"] {
        let response: serde_json::Value = server
            .client
            .request(
                "process_local_codebase",
                rpc_params![json!({
                    "prompt": "What does this code do?",
                    "path": temp_dir.path(),
                    "include_patterns": ["**/*.rs"],
                    "ignore_patterns": [],
                    "include_imports": false,
                    "llm_tool": tool
                })],
            )
            .await?;

        assert_eq!(response["llm_tool"], *tool);
    }

    // Test with invalid tool (should default to gemini)
    let response: serde_json::Value = server
        .client
        .request(
            "process_local_codebase",
            rpc_params![json!({
                "prompt": "What does this code do?",
                "path": temp_dir.path(),
                "include_patterns": ["**/*.rs"],
                "ignore_patterns": [],
                "include_imports": false,
                "llm_tool": "invalid_tool"
            })],
        )
        .await?;

    assert_eq!(response["llm_tool"], "gemini");

    server.stop()?;
    Ok(())
}