turboprop 0.1.2

Fast semantic code search and indexing tool
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
//! Main MCP server implementation
//!
//! Coordinates file watching, incremental indexing, and search tool handling

use anyhow::{Context, Result};
use async_trait::async_trait;
use serde_json::json;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};

use crate::config::TurboPropConfig;
use crate::index::PersistentChunkIndex;
use crate::types::{ConnectionLimit, Port, TimeoutSeconds};

use super::index_manager::IndexManager;
use super::protocol::{
    constants, InitializeParams, InitializeResult, JsonRpcError, JsonRpcRequest, JsonRpcResponse,
    ServerCapabilities, ServerInfo, ToolsCapability,
};
use super::tools::Tools;
use super::transport::StdioTransport;

/// Configuration for MCP server
#[derive(Debug, Clone)]
pub struct McpServerConfig {
    /// Server address (for future TCP transport)
    pub address: String,
    /// Server port (for future TCP transport)
    pub port: Port,
    /// Maximum number of connections
    pub max_connections: ConnectionLimit,
    /// Request timeout in seconds
    pub request_timeout: TimeoutSeconds,
}

impl Default for McpServerConfig {
    fn default() -> Self {
        Self {
            address: "127.0.0.1".to_string(),
            port: Port::dynamic(), // STDIO by default (port 0)
            max_connections: ConnectionLimit::default(),
            request_timeout: TimeoutSeconds::default(),
        }
    }
}

/// Server initialization state
#[derive(Debug, Clone, PartialEq, Default)]
pub enum InitializationState {
    /// Server is not initialized
    #[default]
    NotStarted,
    /// Server is currently initializing
    InProgress,
    /// Server initialization completed successfully
    Ready,
    /// Server initialization failed with error details
    Failed { 
        error: String, 
        retry_count: u32,
        last_attempt: std::time::SystemTime,
    },
}

impl InitializationState {
    /// Check if the server is ready to handle tool calls
    pub fn is_ready(&self) -> bool {
        matches!(self, InitializationState::Ready)
    }

    /// Check if initialization is in progress
    pub fn is_in_progress(&self) -> bool {
        matches!(self, InitializationState::InProgress)
    }

    /// Check if initialization has failed
    pub fn is_failed(&self) -> bool {
        matches!(self, InitializationState::Failed { .. })
    }

    /// Get error message if failed
    pub fn error_message(&self) -> Option<&str> {
        match self {
            InitializationState::Failed { error, .. } => Some(error),
            _ => None,
        }
    }

    /// Get retry count if failed
    pub fn retry_count(&self) -> u32 {
        match self {
            InitializationState::Failed { retry_count, .. } => *retry_count,
            _ => 0,
        }
    }

    /// Check if enough time has passed for a retry attempt
    pub fn can_retry(&self, retry_delay_seconds: u64) -> bool {
        match self {
            InitializationState::Failed { last_attempt, .. } => {
                std::time::SystemTime::now()
                    .duration_since(*last_attempt)
                    .map(|d| d.as_secs() >= retry_delay_seconds)
                    .unwrap_or(true)
            }
            _ => false,
        }
    }
}


/// Trait defining the MCP server interface
#[async_trait]
pub trait McpServerTrait {
    /// Initialize the server with given parameters
    async fn initialize(&mut self, params: InitializeParams) -> Result<InitializeResult>;

    /// Handle a request
    async fn handle_request(&self, request: JsonRpcRequest) -> Result<JsonRpcResponse>;

    /// Check if server is running
    fn is_running(&self) -> bool;
}

/// Main MCP server
pub struct McpServer {
    /// Repository path being indexed
    repo_path: PathBuf,
    /// TurboProp configuration
    config: TurboPropConfig,
    /// Server configuration
    server_config: McpServerConfig,
    /// Tools registry
    tools: Tools,
    /// Persistent index (wrapped for thread safety)
    index: Arc<RwLock<Option<PersistentChunkIndex>>>,
    /// Server initialization state
    initialization_state: Arc<RwLock<InitializationState>>,
    /// Server running state
    running: Arc<RwLock<bool>>,
    /// Index manager for file watching and incremental updates
    index_manager: Arc<RwLock<Option<IndexManager>>>,
}

impl McpServer {
    /// Create a new MCP server
    pub async fn new(repo_path: &Path, config: &TurboPropConfig) -> Result<Self> {
        info!("Initializing MCP server for {}", repo_path.display());

        let tools = Tools::with_search_tool(
            repo_path.to_path_buf(),
            repo_path.to_path_buf(),
            config.clone(),
        );

        let server = Self {
            repo_path: repo_path.to_path_buf(),
            config: config.clone(),
            server_config: McpServerConfig::default(),
            tools,
            index: Arc::new(RwLock::new(None)),
            initialization_state: Arc::new(RwLock::new(InitializationState::default())),
            running: Arc::new(RwLock::new(false)),
            index_manager: Arc::new(RwLock::new(None)),
        };

        Ok(server)
    }

    /// Create a new MCP server with custom configuration and tools
    pub fn with_config_and_tools(server_config: McpServerConfig, tools: Tools) -> Self {
        Self {
            repo_path: PathBuf::new(), // Will be set later
            config: TurboPropConfig::default(),
            server_config,
            tools,
            index: Arc::new(RwLock::new(None)),
            initialization_state: Arc::new(RwLock::new(InitializationState::default())),
            running: Arc::new(RwLock::new(false)),
            index_manager: Arc::new(RwLock::new(None)),
        }
    }

    /// Run the MCP server with file watching
    pub async fn run(self) -> Result<()> {
        let server = Arc::new(self);

        // Initialize transport
        let mut transport = StdioTransport::new();

        // Initialize index manager with comprehensive error handling
        let mut index_manager = match IndexManager::new(
            &server.repo_path,
            &server.config,
            None, // Initial index will be set after building
        )
        .await
        {
            Ok(manager) => manager,
            Err(e) => {
                error!(
                    "Failed to create IndexManager for repository '{}': {}",
                    server.repo_path.display(),
                    e
                );

                // Attempt basic recovery checks
                if !server.repo_path.exists() {
                    return Err(anyhow::anyhow!(
                        "Repository path '{}' does not exist",
                        server.repo_path.display()
                    ));
                }

                if !server.repo_path.is_dir() {
                    return Err(anyhow::anyhow!(
                        "Repository path '{}' is not a directory",
                        server.repo_path.display()
                    ));
                }

                // Check for permission issues
                if let Err(perm_err) = std::fs::read_dir(&server.repo_path) {
                    return Err(anyhow::anyhow!(
                        "Cannot access repository directory '{}': {}",
                        server.repo_path.display(), perm_err
                    ));
                }

                // If all basic checks pass, return the original error with additional context
                return Err(e.context(format!(
                    "Failed to create IndexManager for repository '{}'",
                    server.repo_path.display()
                )));
            }
        };

        // Start index manager with enhanced error handling
        if let Err(e) = index_manager.start().await {
            error!("Failed to start IndexManager background tasks: {}", e);
            return Err(e.context(
                "IndexManager initialization succeeded but background tasks failed to start"
            ));
        }

        // Store index manager reference
        {
            let mut manager_guard = server.index_manager.write().await;
            *manager_guard = Some(index_manager);
        }

        // Initialize index immediately with enhanced error handling
        if let Err(e) = server.initialize_index_with_manager().await {
            warn!("Initial index build failed: {}. The server will continue to run, but search functionality may be limited until the index is built.", e);
            // Note: We don't return an error here because the server can still function
            // for basic MCP operations even without a pre-built index
        } else {
            info!("Index initialization completed successfully");
        }

        // Set server running state
        {
            let mut running_guard = server.running.write().await;
            *running_guard = true;
        }

        info!(
            "MCP server ready and listening on stdio (timeout: {}s, max_connections: {})",
            server.server_config.request_timeout, server.server_config.max_connections
        );

        // Main message processing loop
        loop {
            match transport.receive_request().await {
                Some(Ok(request)) => {
                    let response = server.handle_request_internal(request).await;
                    if let Err(e) = transport.send_response(response).await {
                        error!("Failed to send response: {}", e);
                        break;
                    }
                }
                Some(Err(e)) => {
                    error!("Error receiving request: {}", e);
                    // Send error response if possible
                    let error_response = StdioTransport::create_error_response(
                        None,
                        JsonRpcError::parse_error(e.to_string()),
                    );
                    let _ = transport.send_response(error_response).await;
                }
                None => {
                    // STDIN closed
                    info!("STDIN closed, shutting down MCP server");
                    break;
                }
            }
        }

        // Set server running state to false during shutdown
        {
            let mut running_guard = server.running.write().await;
            *running_guard = false;
        }

        // Cleanup
        if let Some(manager) = server.index_manager.read().await.as_ref() {
            let _ = manager.stop().await;
        }

        info!("MCP server shutdown complete");
        Ok(())
    }

    /// Handle an incoming JSON-RPC request (internal implementation)
    async fn handle_request_internal(&self, request: JsonRpcRequest) -> JsonRpcResponse {
        debug!(
            "Handling request: method={}, id={:?}",
            request.method, request.id
        );

        // Validate request format
        if let Err(error) = request.validate() {
            return request.create_error_response(error);
        }

        // Dispatch to appropriate handler
        match request.method.as_str() {
            constants::methods::INITIALIZE => self.handle_initialize(request).await,
            constants::methods::TOOLS_LIST => self.handle_tools_list(request).await,
            constants::methods::TOOLS_CALL => self.handle_tools_call(request).await,
            _ => {
                let error = JsonRpcError::method_not_found(request.method.clone());
                request.create_error_response(error)
            }
        }
    }

    /// Handle MCP initialization
    async fn handle_initialize(&self, request: JsonRpcRequest) -> JsonRpcResponse {
        debug!("Handling initialize request");

        // Parse initialization parameters
        let params = match &request.params {
            Some(params) => match serde_json::from_value::<InitializeParams>(params.clone()) {
                Ok(params) => params,
                Err(e) => {
                    let error =
                        JsonRpcError::invalid_params(format!("Invalid initialize params: {}", e));
                    return request.create_error_response(error);
                }
            },
            None => {
                let error =
                    JsonRpcError::invalid_params("Missing initialize parameters".to_string());
                return request.create_error_response(error);
            }
        };

        info!(
            "Initializing MCP server for client: {} v{}",
            params.client_info.name, params.client_info.version
        );

        // Validate protocol version
        if params.protocol_version != constants::PROTOCOL_VERSION {
            warn!(
                "Client protocol version {} differs from server version {}",
                params.protocol_version,
                constants::PROTOCOL_VERSION
            );
        }

        // Start index initialization in background
        let index_clone = Arc::clone(&self.index);
        let repo_path = self.repo_path.clone();
        let config = self.config.clone();
        let init_state_clone = Arc::clone(&self.initialization_state);

        // Set state to InProgress before starting
        {
            let mut state_guard = init_state_clone.write().await;
            *state_guard = InitializationState::InProgress;
        }

        tokio::spawn(async move {
            const MAX_RETRIES: u32 = 3;
            const RETRY_DELAY_SECONDS: u64 = 10;
            
            let mut retry_count = 0;
            
            loop {
                match Self::initialize_index(&repo_path, &config).await {
                    Ok(index) => {
                        // Successfully initialized
                        {
                            let mut index_guard = index_clone.write().await;
                            *index_guard = Some(index);
                        }
                        {
                            let mut state_guard = init_state_clone.write().await;
                            *state_guard = InitializationState::Ready;
                        }
                        info!("Index initialization completed successfully");
                        break;
                    }
                    Err(e) => {
                        retry_count += 1;
                        let error_msg = format!("Failed to initialize index: {}", e);
                        
                        if retry_count >= MAX_RETRIES {
                            // Max retries reached, mark as failed
                            error!("{} (attempt {}/{}). Giving up.", error_msg, retry_count, MAX_RETRIES);
                            let mut state_guard = init_state_clone.write().await;
                            *state_guard = InitializationState::Failed {
                                error: error_msg,
                                retry_count,
                                last_attempt: std::time::SystemTime::now(),
                            };
                            break;
                        } else {
                            // Retry after delay
                            warn!("{} (attempt {}/{}). Retrying in {} seconds...", 
                                  error_msg, retry_count, MAX_RETRIES, RETRY_DELAY_SECONDS);
                            tokio::time::sleep(tokio::time::Duration::from_secs(RETRY_DELAY_SECONDS)).await;
                        }
                    }
                }
            }
        });

        // Create initialization result
        let result = InitializeResult {
            protocol_version: constants::PROTOCOL_VERSION.to_string(),
            server_info: ServerInfo {
                name: constants::SERVER_NAME.to_string(),
                version: constants::SERVER_VERSION.to_string(),
            },
            capabilities: ServerCapabilities {
                tools: Some(ToolsCapability {
                    list_changed: false, // Static tool list
                }),
                experimental: std::collections::HashMap::new(),
            },
        };

        match serde_json::to_value(result) {
            Ok(result_value) => {
                info!("MCP server initialized successfully");
                request.create_success_response(result_value)
            }
            Err(e) => {
                let error =
                    JsonRpcError::internal_error(format!("Failed to serialize result: {}", e));
                request.create_error_response(error)
            }
        }
    }

    /// Handle tools/list request
    async fn handle_tools_list(&self, request: JsonRpcRequest) -> JsonRpcResponse {
        debug!("Handling tools/list request");

        // Check if server is initialized first
        let init_state = {
            let state_guard = self.initialization_state.read().await;
            state_guard.clone()
        };

        if !init_state.is_ready() {
            let error = match init_state {
                InitializationState::InProgress => {
                    JsonRpcError::index_not_ready()
                }
                InitializationState::Failed { error, retry_count, .. } => {
                    JsonRpcError::internal_error(format!(
                        "Server initialization failed after {} attempts: {}",
                        retry_count, error
                    ))
                }
                _ => JsonRpcError::internal_error("Server not initialized")
            };
            return request.create_error_response(error);
        }

        // Use the tools registry
        let tools = self.tools.list_tools();

        let result = json!({
            "tools": tools
        });

        request.create_success_response(result)
    }

    /// Handle tools/call request
    async fn handle_tools_call(&self, request: JsonRpcRequest) -> JsonRpcResponse {
        debug!("Handling tools/call request");

        // Check if server is initialized
        let init_state = {
            let state_guard = self.initialization_state.read().await;
            state_guard.clone()
        };

        if !init_state.is_ready() {
            let error = match init_state {
                InitializationState::InProgress => {
                    JsonRpcError::index_not_ready()
                }
                InitializationState::Failed { error, retry_count, .. } => {
                    JsonRpcError::application_error(
                        -32003, // INDEX_NOT_READY error code
                        format!(
                            "Index initialization failed after {} attempts: {}. Please restart the server or check logs for details.",
                            retry_count, error
                        )
                    )
                }
                _ => JsonRpcError::index_not_ready()
            };
            return request.create_error_response(error);
        }

        // Parse tool call parameters
        let params = match &request.params {
            Some(params) => params.clone(),
            None => {
                let error =
                    JsonRpcError::invalid_params("Missing tool call parameters".to_string());
                return request.create_error_response(error);
            }
        };

        // Extract tool name and arguments
        let tool_name = match params.get("name").and_then(|v| v.as_str()) {
            Some(name) => name,
            None => {
                let error = JsonRpcError::invalid_params("Missing tool name".to_string());
                return request.create_error_response(error);
            }
        };

        let arguments = params.get("arguments").cloned().unwrap_or(json!({}));

        // Use the tools registry
        let tool_call_request = crate::mcp::tools::ToolCallRequest {
            name: tool_name.to_string(),
            arguments: serde_json::from_value(arguments).unwrap_or_default(),
        };

        match self.tools.execute_tool(tool_call_request).await {
            Ok(tool_response) => {
                if tool_response.success {
                    debug!("Tool executed successfully: {}", tool_name);
                    let result = tool_response.content.unwrap_or(json!({}));
                    request.create_success_response(result)
                } else {
                    error!(
                        "Tool execution failed: {}",
                        tool_response
                            .error
                            .as_ref()
                            .unwrap_or(&"Unknown error".to_string())
                    );
                    let error = JsonRpcError::tool_execution_error(
                        tool_response
                            .error
                            .unwrap_or_else(|| "Unknown error".to_string()),
                    );
                    request.create_error_response(error)
                }
            }
            Err(e) => {
                error!("Tool execution failed: {}", e);
                let error = JsonRpcError::tool_execution_error(e.to_string());
                request.create_error_response(error)
            }
        }
    }

    /// Initialize the search index
    async fn initialize_index(
        repo_path: &Path,
        config: &TurboPropConfig,
    ) -> Result<PersistentChunkIndex> {
        info!("Initializing search index for {}", repo_path.display());

        // Check if index already exists by trying to load it
        let index = if let Ok(existing_index) = PersistentChunkIndex::load(repo_path) {
            info!("Loading existing index from {}", repo_path.display());
            existing_index
        } else {
            info!("Creating new index");

            // Use existing TurboProp indexing logic
            let index = crate::commands::index::build_index(repo_path, config)
                .await
                .context("Failed to build initial index")?;

            info!("Index created successfully with {} chunks", index.len());
            index
        };

        Ok(index)
    }

    /// Initialize index with manager integration
    async fn initialize_index_with_manager(&self) -> Result<()> {
        info!("Starting index initialization");

        // Build initial index
        let index = Self::initialize_index(&self.repo_path, &self.config).await?;

        // Set index in manager
        if let Some(manager) = self.index_manager.read().await.as_ref() {
            manager.set_index(index.clone()).await;
        }

        // Set index in server
        {
            let mut index_guard = self.index.write().await;
            *index_guard = Some(index);
        }

        // Mark as initialized
        {
            let mut state_guard = self.initialization_state.write().await;
            *state_guard = InitializationState::Ready;
        }

        info!("Index initialization completed with file watching enabled");
        Ok(())
    }

    /// Initialize the server (public method for tests)
    pub async fn initialize(&mut self, params: InitializeParams) -> Result<InitializeResult> {
        info!(
            "Initializing MCP server for client: {} v{}",
            params.client_info.name, params.client_info.version
        );

        // Validate protocol version
        if params.protocol_version != constants::PROTOCOL_VERSION {
            anyhow::bail!(
                "Unsupported protocol version: {} (expected: {})",
                params.protocol_version,
                constants::PROTOCOL_VERSION
            );
        }

        // Validate parameters
        params
            .validate()
            .map_err(|e| anyhow::anyhow!("Invalid initialization parameters: {:?}", e))?;

        // Mark as initialized
        {
            let mut state_guard = self.initialization_state.write().await;
            *state_guard = InitializationState::Ready;
        }

        // Create initialization result
        let result = InitializeResult {
            protocol_version: constants::PROTOCOL_VERSION.to_string(),
            server_info: ServerInfo {
                name: constants::SERVER_NAME.to_string(),
                version: constants::SERVER_VERSION.to_string(),
            },
            capabilities: ServerCapabilities {
                tools: Some(ToolsCapability {
                    list_changed: false, // Static tool list
                }),
                experimental: std::collections::HashMap::new(),
            },
        };

        info!("MCP server initialized successfully");
        Ok(result)
    }

    /// Check if the server is running
    pub async fn is_running(&self) -> bool {
        // Check the actual running state
        *self.running.read().await
    }
}

/// MCP server builder for configuration
pub struct McpServerBuilder {
    repo_path: Option<PathBuf>,
    config: Option<TurboPropConfig>,
}

impl McpServerBuilder {
    /// Create a new server builder
    pub fn new() -> Self {
        Self {
            repo_path: None,
            config: None,
        }
    }

    /// Set the repository path
    pub fn repo_path<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.repo_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Set the configuration
    pub fn config(mut self, config: TurboPropConfig) -> Self {
        self.config = Some(config);
        self
    }

    /// Build the MCP server
    pub async fn build(self) -> Result<McpServer> {
        let repo_path = self
            .repo_path
            .ok_or_else(|| anyhow::anyhow!("Repository path is required"))?;
        let config = self
            .config
            .ok_or_else(|| anyhow::anyhow!("Configuration is required"))?;

        McpServer::new(&repo_path, &config).await
    }
}

impl Default for McpServerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Implementation of McpServerTrait for McpServer
#[async_trait]
impl McpServerTrait for McpServer {
    async fn initialize(&mut self, params: InitializeParams) -> Result<InitializeResult> {
        self.initialize(params).await
    }

    async fn handle_request(&self, request: JsonRpcRequest) -> Result<JsonRpcResponse> {
        // The internal method returns JsonRpcResponse, but the trait expects Result<JsonRpcResponse>
        // We need to wrap the response in Ok() for success cases
        let response = self.handle_request_internal(request).await;

        // Check if the response contains an error and convert to Result accordingly
        if response.error.is_some() {
            // Extract error message for the Err case
            let error_msg = response
                .error
                .as_ref()
                .map(|e| e.message.clone())
                .unwrap_or_else(|| "Unknown error".to_string());
            Err(anyhow::anyhow!("Request failed: {}", error_msg))
        } else {
            Ok(response)
        }
    }

    fn is_running(&self) -> bool {
        // Use try_read to avoid blocking in sync context
        self.running.try_read().map(|guard| *guard).unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_mcp_server_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config = TurboPropConfig::default();

        let server = McpServer::new(temp_dir.path(), &config).await;
        assert!(server.is_ok());
    }

    #[tokio::test]
    async fn test_initialize_request() {
        let temp_dir = TempDir::new().unwrap();
        let config = TurboPropConfig::default();
        let server = McpServer::new(temp_dir.path(), &config).await.unwrap();

        let request = JsonRpcRequest::new(
            constants::methods::INITIALIZE.to_string(),
            Some(json!({
                "protocol_version": constants::PROTOCOL_VERSION,
                "client_info": {
                    "name": "test-client",
                    "version": "1.0.0"
                },
                "capabilities": {}
            })),
        );

        let response = server.handle_initialize(request).await;

        if let Some(error) = &response.error {
            println!("Error: {:?}", error);
        }

        assert!(response.error.is_none());
        assert!(response.result.is_some());

        let result = response.result.unwrap();
        println!("Result: {:?}", result);
        assert_eq!(result["protocol_version"], constants::PROTOCOL_VERSION);
        assert_eq!(result["server_info"]["name"], constants::SERVER_NAME);
    }

    #[tokio::test]
    async fn test_tools_list_request() {
        let temp_dir = TempDir::new().unwrap();
        let config = TurboPropConfig::default();
        let server = McpServer::new(temp_dir.path(), &config).await.unwrap();

        // Mark server as initialized for this test
        {
            let mut state_guard = server.initialization_state.write().await;
            *state_guard = InitializationState::Ready;
        }

        let request = JsonRpcRequest::new(constants::methods::TOOLS_LIST.to_string(), None);

        let response = server.handle_tools_list(request).await;

        assert!(response.error.is_none());
        assert!(response.result.is_some());

        let result = response.result.unwrap();
        let tools = result["tools"].as_array().unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0]["name"], "semantic_search");
    }

    #[test]
    fn test_server_builder() {
        let temp_dir = TempDir::new().unwrap();
        let config = TurboPropConfig::default();

        let builder = McpServerBuilder::new()
            .repo_path(temp_dir.path())
            .config(config);

        // Builder should be created successfully
        // Actual build() test would require async context
        drop(builder);
    }

    #[tokio::test]
    async fn test_invalid_method_request() {
        let temp_dir = TempDir::new().unwrap();
        let config = TurboPropConfig::default();
        let server = McpServer::new(temp_dir.path(), &config).await.unwrap();

        let request = JsonRpcRequest::new("invalid_method".to_string(), None);

        let response = server.handle_request_internal(request).await;

        assert!(response.result.is_none());
        assert!(response.error.is_some());
        assert_eq!(response.error.unwrap().code, -32601); // Method not found
    }

    #[tokio::test]
    async fn test_tools_call_before_initialization() {
        let temp_dir = TempDir::new().unwrap();
        let config = TurboPropConfig::default();
        let server = McpServer::new(temp_dir.path(), &config).await.unwrap();

        let request = JsonRpcRequest::new(
            constants::methods::TOOLS_CALL.to_string(),
            Some(json!({
                "name": "semantic_search",
                "arguments": {
                    "query": "test"
                }
            })),
        );

        let response = server.handle_tools_call(request).await;

        assert!(response.result.is_none());
        assert!(response.error.is_some());
        // Should return index not ready error
    }
}