mcp-cpp-server 0.2.2

A high-performance Model Context Protocol (MCP) server for C++ code analysis using clangd LSP integration
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
//! Clangd session management
//!
//! Provides ClangdSession trait and implementation for managing clangd process
//! lifecycle with direct integration to lsp components (no orchestrator).

use async_trait::async_trait;
use std::path::PathBuf;
use std::time::Instant;
use tracing::{debug, info, warn};

use crate::clangd::config::ClangdConfig;
use crate::clangd::error::ClangdSessionError;
use crate::clangd::index::IndexProgressMonitor;
use crate::clangd::log_monitor::LogMonitor;
use crate::clangd::session_builder::ClangdSessionBuilder;
use crate::io::{ChildProcessManager, ProcessManager, StderrMonitor, StdioTransport, StopMode};
use crate::lsp::{LspClient, traits::LspClientTrait};

/// Type alias for testing sessions with mock dependencies
#[cfg(test)]
type TestSession =
    ClangdSession<crate::io::process::MockProcessManager, crate::lsp::testing::MockLspClientTrait>;

// ============================================================================
// Clangd Session Trait
// ============================================================================

/// Trait for clangd session management with generic client abstraction
#[async_trait]
pub trait ClangdSessionTrait: Send + Sync {
    /// Associated error type for session operations
    type Error: std::error::Error + Send + Sync + 'static;

    /// Associated LSP client type - enables polymorphic client usage
    type Client: Send + Sync;

    /// Graceful async cleanup (consumes self)
    async fn close(self) -> Result<(), Self::Error>;

    /// Get LSP client (always available)
    ///
    /// Returns reference to the underlying LSP client, which can be either
    /// a real LspClient<StdioTransport> or MockLspClient depending on implementation.
    fn client(&self) -> &Self::Client;

    /// Get mutable LSP client (always available)
    ///
    /// Returns mutable reference to the underlying LSP client for operations
    /// that require client state modification.
    fn client_mut(&mut self) -> &mut Self::Client;

    /// Get current configuration
    fn config(&self) -> &ClangdConfig;

    /// Get session uptime
    fn uptime(&self) -> std::time::Duration;

    /// Get session working directory
    fn working_directory(&self) -> &PathBuf;

    /// Get session build directory
    fn build_directory(&self) -> &PathBuf;
}

// ============================================================================
// Clangd Session Implementation
// ============================================================================

/// Clangd session implementation with dependency injection support
pub struct ClangdSession<P = ChildProcessManager, C = LspClient<StdioTransport>>
where
    P: ProcessManager + 'static,
    C: LspClientTrait + 'static,
{
    /// Session configuration
    config: ClangdConfig,

    /// Process manager for clangd (injected dependency)
    process_manager: Box<P>,

    /// LSP client (injected dependency)
    lsp_client: Box<C>,

    /// Indexing progress monitor
    index_progress_monitor: IndexProgressMonitor,

    /// Log monitor for stderr parsing
    log_monitor: LogMonitor,

    /// Session start timestamp
    started_at: Instant,
}

impl<P, C> ClangdSession<P, C>
where
    P: ProcessManager + 'static,
    C: LspClientTrait + 'static,
{
    /// Create a new clangd session with injected dependencies (for testing)
    ///
    /// This constructor enables dependency injection of both ProcessManager and LspClient,
    /// making the session fully unit testable without external processes.
    pub fn with_dependencies(
        config: ClangdConfig,
        process_manager: P,
        lsp_client: C,
        index_progress_monitor: IndexProgressMonitor,
        log_monitor: LogMonitor,
    ) -> Self {
        let started_at = Instant::now();

        Self {
            config,
            process_manager: Box::new(process_manager),
            lsp_client: Box::new(lsp_client),
            index_progress_monitor,
            log_monitor,
            started_at,
        }
    }
}

impl ClangdSession {
    /// Create a new clangd session with real dependencies using the builder
    ///
    /// Performs complete initialization: process start, LSP setup, and connection.
    /// If this method succeeds, the session is fully operational.
    pub async fn new(config: ClangdConfig) -> Result<Self, ClangdSessionError> {
        ClangdSessionBuilder::new()
            .with_config(config)
            .build()
            .await
    }
}

impl<P, C> ClangdSession<P, C>
where
    P: ProcessManager + 'static,
    C: LspClientTrait + 'static,
{
    /// Graceful async cleanup - consumes self to prevent further use
    ///
    /// Performs orderly shutdown: LSP client shutdown, then process termination.
    /// Prefer this over letting Drop trait handle cleanup.
    pub async fn close(mut self) -> Result<(), ClangdSessionError> {
        info!("Gracefully shutting down clangd session");

        // Step 1: Shutdown LSP client gracefully
        debug!("Shutting down LSP client");
        let shutdown_result = tokio::time::timeout(
            self.config.lsp_config.request_timeout,
            self.lsp_client.shutdown(),
        )
        .await;

        match shutdown_result {
            Ok(Ok(())) => debug!("LSP client shutdown completed"),
            Ok(Err(e)) => warn!("LSP client shutdown error: {}", e),
            Err(_) => warn!("LSP client shutdown timed out"),
        }

        // Always close the client connection
        let _ = self.lsp_client.close().await;

        // Step 2: Stop the clangd process gracefully
        debug!("Stopping clangd process");
        self.process_manager
            .stop(StopMode::Graceful)
            .await
            .map_err(|e| {
                ClangdSessionError::unexpected_failure(format!("Process stop failed: {}", e))
            })?;

        info!("Clangd session shutdown completed");
        Ok(())
    }

    /// Get session uptime
    pub fn uptime(&self) -> std::time::Duration {
        self.started_at.elapsed()
    }

    /// Get reference to the indexing progress monitor
    pub fn index_progress_monitor(&self) -> &IndexProgressMonitor {
        &self.index_progress_monitor
    }

    /// Get reference to the log monitor
    pub fn log_monitor(&self) -> &LogMonitor {
        &self.log_monitor
    }

    /// Setup stderr processing for the log monitor
    /// This must be called after session creation to wire stderr to log monitor
    pub fn setup_stderr_monitoring(&mut self)
    where
        P: StderrMonitor,
    {
        let processor = self.log_monitor.create_stderr_processor();

        // Install the stderr processor
        self.process_manager.on_stderr_line(move |line: String| {
            processor(line);
        });

        debug!("LogMonitor stderr processing wired to process manager");
    }
}

/// Drop trait implementation - force cleanup fallback
///
/// This provides a sync fallback if close() wasn't called explicitly.
/// Issues a warning and performs immediate process cleanup.
impl<P, C> Drop for ClangdSession<P, C>
where
    P: ProcessManager + 'static,
    C: LspClientTrait + 'static,
{
    fn drop(&mut self) {
        // Check if process is still running
        if self.process_manager.is_running() {
            warn!("ClangdSession dropped without calling close() - force killing process");

            // Clean sync kill - no async runtime needed
            self.process_manager.kill_sync();
        }
    }
}

#[async_trait]
impl<P, C> ClangdSessionTrait for ClangdSession<P, C>
where
    P: ProcessManager + 'static,
    C: LspClientTrait + 'static,
{
    type Error = ClangdSessionError;
    type Client = C;

    /// Graceful async cleanup (consumes self)
    async fn close(self) -> Result<(), Self::Error> {
        // Call the close method directly (avoid recursive call)
        ClangdSession::close(self).await
    }

    /// Get LSP client
    fn client(&self) -> &Self::Client {
        &self.lsp_client
    }

    /// Get mutable LSP client
    fn client_mut(&mut self) -> &mut Self::Client {
        &mut self.lsp_client
    }

    /// Get current configuration
    fn config(&self) -> &ClangdConfig {
        &self.config
    }

    /// Get session uptime
    fn uptime(&self) -> std::time::Duration {
        self.uptime()
    }

    /// Get session working directory
    fn working_directory(&self) -> &PathBuf {
        &self.config.working_directory
    }

    /// Get session build directory
    fn build_directory(&self) -> &PathBuf {
        &self.config.build_directory
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // Auto-initialize logging for all tests in this module
    #[cfg(feature = "test-logging")]
    #[ctor::ctor]
    fn init_test_logging() {
        crate::test_utils::logging::init();
    }

    #[tokio::test]
    async fn test_session_construction_failure() {
        use crate::clangd::testing::test_helpers::*;

        // Test constructor failure with invalid clangd path
        let (_temp_dir, project_root, build_dir) =
            crate::test_utils::project::create_mock_build_folder();
        let config =
            create_test_config(&project_root, &build_dir, TestConfigType::Failing).unwrap();

        // Constructor should fail due to invalid clangd path
        let result = ClangdSession::new(config).await;
        assert!(result.is_err());
    }

    #[cfg(feature = "clangd-integration-tests")]
    #[tokio::test]
    async fn test_session_ready_when_constructed() {
        use crate::clangd::testing::test_helpers::*;

        let (_temp_dir, project_root, build_dir) =
            crate::test_utils::project::create_mock_build_folder();
        let config =
            create_test_config(&project_root, &build_dir, TestConfigType::Integration).unwrap();

        // Constructor should succeed and return ready session
        let session = ClangdSession::new(config).await.unwrap();

        // Session should be immediately ready to use
        assert_eq!(session.working_directory(), &project_root);
        assert_eq!(session.build_directory(), &build_dir);
        assert!(session.uptime().as_nanos() > 0);

        session.close().await.unwrap();
    }

    #[cfg(feature = "clangd-integration-tests")]
    #[tokio::test]
    async fn test_session_close() {
        use crate::clangd::testing::test_helpers::*;

        let (_temp_dir, project_root, build_dir) =
            crate::test_utils::project::create_mock_build_folder();
        let config =
            create_test_config(&project_root, &build_dir, TestConfigType::Integration).unwrap();
        let session = ClangdSession::new(config).await.unwrap();

        // Close should succeed and consume the session
        let result = session.close().await;
        assert!(result.is_ok());

        // Session is now consumed and cannot be used further
    }

    #[tokio::test]
    async fn test_trait_polymorphism_with_mocks() {
        use crate::clangd::testing::test_helpers::*;

        let (_temp_dir, project_root, build_dir) =
            crate::test_utils::project::create_mock_build_folder();
        let session = create_mock_session(&project_root, &build_dir).unwrap();

        // Verify client access works correctly with mock dependencies
        let client = session.client();
        assert!(client.is_initialized());

        session.close().await.unwrap();
    }

    #[tokio::test]
    async fn test_polymorphic_session_usage() {
        use crate::clangd::testing::test_helpers::*;

        async fn use_session_polymorphically<S>(session: S) -> Result<String, S::Error>
        where
            S: ClangdSessionTrait,
        {
            let uptime = session.uptime();
            session.close().await?;
            Ok(format!("Session ran for {uptime:?}"))
        }

        let (_temp_dir, project_root, build_dir) =
            crate::test_utils::project::create_mock_build_folder();
        let mock_session = create_mock_session(&project_root, &build_dir).unwrap();

        // Test polymorphic trait usage with proper cleanup
        let result = use_session_polymorphically(mock_session).await;
        assert!(result.is_ok());
        assert!(result.unwrap().contains("Session ran for"));
    }

    #[tokio::test]
    async fn test_dependency_injection_with_mocks() {
        use crate::clangd::testing::test_helpers::*;

        let (_temp_dir, project_root, build_dir) =
            crate::test_utils::project::create_mock_build_folder();
        let config = create_test_config(&project_root, &build_dir, TestConfigType::Mock).unwrap();

        // Create session with dependency injection using helper
        let session = create_session_with_mock_dependencies(config);

        // Verify session is properly configured
        assert_eq!(session.working_directory(), &project_root);
        assert_eq!(session.build_directory(), &build_dir);
        assert!(session.uptime().as_nanos() > 0);

        // Verify client is accessible and initialized (mocked)
        let client = session.client();
        assert!(client.is_initialized());

        // Clean shutdown should work with mocks
        session.close().await.unwrap();
    }

    #[tokio::test]
    async fn test_session_factory_for_testing() {
        use crate::clangd::testing::test_helpers::*;

        let (_temp_dir, project_root, build_dir) =
            crate::test_utils::project::create_mock_build_folder();
        let config = create_test_config(&project_root, &build_dir, TestConfigType::Mock).unwrap();

        // Use proper fluent builder API with mock dependencies
        use crate::io::process::MockProcessManager;
        use crate::lsp::testing::MockLspClientTrait;
        use crate::lsp::traits::LspClientTrait;

        let process_manager = MockProcessManager::new();
        let mut lsp_client = MockLspClientTrait::new();

        // Setup expectations for basic mock functionality
        lsp_client.expect_is_initialized().returning(|| true);
        lsp_client
            .expect_shutdown()
            .returning(|| Box::pin(async { Ok(()) }));
        lsp_client
            .expect_close()
            .returning(|| Box::pin(async { Ok(()) }));
        lsp_client
            .expect_open_text_document()
            .returning(|_, _, _, _| Box::pin(async { Ok(()) }));

        let session = ClangdSessionBuilder::new()
            .with_config(config)
            .with_process_manager(process_manager)
            .with_lsp_client(lsp_client)
            .build()
            .await
            .unwrap();

        // Session should be immediately ready with mock dependencies
        assert_eq!(session.working_directory(), &project_root);
        assert_eq!(session.build_directory(), &build_dir);
        assert!(session.uptime().as_nanos() > 0);

        // Mock client should be pre-initialized
        let client = session.client();
        assert!(client.is_initialized());

        // Session should be ready for use

        session.close().await.unwrap();
    }

    #[tokio::test]
    async fn test_unit_testing_without_external_processes() {
        use crate::clangd::testing::test_helpers::*;

        let (temp_dir, project_root, build_dir) =
            crate::test_utils::project::create_mock_build_folder();
        let config = create_test_config(&project_root, &build_dir, TestConfigType::Mock).unwrap();

        // Demonstrate comprehensive unit testing with mock dependencies using fluent API
        use crate::io::process::MockProcessManager;
        use crate::lsp::testing::MockLspClientTrait;
        use crate::lsp::traits::LspClientTrait;

        let process_manager = MockProcessManager::new();
        let mut lsp_client = MockLspClientTrait::new();

        // Setup expectations for basic mock functionality
        lsp_client.expect_is_initialized().returning(|| true);
        lsp_client
            .expect_shutdown()
            .returning(|| Box::pin(async { Ok(()) }));
        lsp_client
            .expect_close()
            .returning(|| Box::pin(async { Ok(()) }));
        lsp_client
            .expect_open_text_document()
            .returning(|_, _, _, _| Box::pin(async { Ok(()) }));

        let session = ClangdSessionBuilder::new()
            .with_config(config)
            .with_process_manager(process_manager)
            .with_lsp_client(lsp_client)
            .build()
            .await
            .unwrap();

        // Test session behavior with mocked dependencies
        assert!(session.client().is_initialized());
        assert!(!session.process_manager.is_running()); // Mock starts not running

        // File management operations work with mocks
        let fake_file_path = temp_dir.path().join("fake.cpp");
        std::fs::write(&fake_file_path, "// test content").unwrap();

        // Mock LSP client operations work correctly

        // Graceful shutdown works with mock dependencies
        session.close().await.unwrap();

        // Test validates isolated unit testing without external dependencies
    }

    #[cfg(all(test, feature = "clangd-integration-tests"))]
    #[tokio::test]
    async fn test_clangd_session_with_real_project() {
        use crate::clangd::testing::test_helpers::*;

        let (test_project, session) = create_integration_test_session().await.unwrap();

        assert!(session.uptime().as_nanos() > 0);
        assert_eq!(session.working_directory(), &test_project.project_root);
        assert_eq!(session.build_directory(), &test_project.build_dir);

        let client = session.client();
        assert!(client.is_initialized());

        session.close().await.unwrap();
    }
}