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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Clangd stderr log monitor for progress tracking
//!
//! Monitors clangd's stderr output for indexing progress messages and emits
//! structured progress events. This complements the LSP progress notifications
//! with more detailed file-level progress information.

use crate::clangd::index::ProgressEvent;
use regex::Regex;
use std::path::PathBuf;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc;
use tracing::{debug, trace, warn};

/// Log parser trait for testing and extensibility
pub trait LogParser: Send + Sync {
    /// Parse a log line and return a progress event if applicable
    fn parse_line(&self, line: &str) -> Option<ProgressEvent>;
}

/// Default clangd log parser using regex patterns
#[derive(Clone)]
pub struct ClangdLogParser {
    indexing_start_regex: Regex,
    indexing_complete_regex: Regex,
    ast_indexed_regex: Regex,
    ast_failed_compiler_invocation_regex: Regex,
    ast_failed_execute_regex: Regex,
    ast_failed_begin_source_regex: Regex,
    stdlib_start_regex: Regex,
    stdlib_complete_regex: Regex,
}

impl ClangdLogParser {
    /// Create a new clangd log parser with compiled regex patterns
    pub fn new() -> Result<Self, regex::Error> {
        Ok(Self {
            // V[14:23:45.123] Indexing /path/to/file.cpp (digest:=0x1234ABCD)
            indexing_start_regex: Regex::new(
                r"V\[\d{2}:\d{2}:\d{2}\.\d{3}\] Indexing (.+?) \(digest:=(.+?)\)",
            )?,

            // I[14:23:46.456] Indexed /path/to/file.cpp (42 symbols, 10 refs, 3 files)
            indexing_complete_regex: Regex::new(
                r"I\[\d{2}:\d{2}:\d{2}\.\d{3}\] Indexed (.+?) \((\d+) symbols?, (\d+) refs?, \d+ files?\)",
            )?,

            // V[22:06:42.564] indexed file AST for /tmp/.tmpCSsikQ/src/Container.cpp version 1:
            ast_indexed_regex: Regex::new(
                r"V\[\d{2}:\d{2}:\d{2}\.\d{3}\] indexed file AST for (.+?) version \d+",
            )?,

            // E[14:23:45.123] Could not build CompilerInvocation for file /path/to/file.cpp
            ast_failed_compiler_invocation_regex: Regex::new(
                r"[EW]\[\d{2}:\d{2}:\d{2}\.\d{3}\] Could not build CompilerInvocation for file (.+)",
            )?,

            // E[14:23:45.123] Execute() failed when building AST for /path/to/file.cpp: error message
            ast_failed_execute_regex: Regex::new(
                r"[EW]\[\d{2}:\d{2}:\d{2}\.\d{3}\] Execute\(\) failed when building AST for (.+?): .+",
            )?,

            // E[14:23:45.123] BeginSourceFile() failed when building AST for /path/to/file.cpp
            ast_failed_begin_source_regex: Regex::new(
                r"[EW]\[\d{2}:\d{2}:\d{2}\.\d{3}\] BeginSourceFile\(\) failed when building AST for (.+)",
            )?,

            // I[14:23:47.789] Indexing c++20 standard library in the context of /path/to/file.cpp
            stdlib_start_regex: Regex::new(
                r"I\[\d{2}:\d{2}:\d{2}\.\d{3}\] Indexing (.+?) standard library in the context of (.+)",
            )?,

            // I[14:23:48.000] Indexed c++20 standard library: 1234 symbols, 567 filtered
            stdlib_complete_regex: Regex::new(
                r"I\[\d{2}:\d{2}:\d{2}\.\d{3}\] Indexed (.+?) standard library: (\d+) symbols?, (\d+) filtered",
            )?,
        })
    }
}

impl Default for ClangdLogParser {
    fn default() -> Self {
        Self::new().expect("Failed to compile regex patterns")
    }
}

impl LogParser for ClangdLogParser {
    fn parse_line(&self, line: &str) -> Option<ProgressEvent> {
        // Try indexing start pattern
        if let Some(captures) = self.indexing_start_regex.captures(line) {
            let path = captures.get(1)?.as_str();
            let digest = captures.get(2)?.as_str();

            return Some(ProgressEvent::FileIndexingStarted {
                path: PathBuf::from(path),
                digest: digest.to_string(),
            });
        }

        // Try indexing complete pattern
        if let Some(captures) = self.indexing_complete_regex.captures(line) {
            let path = captures.get(1)?.as_str();
            let symbols: u32 = captures.get(2)?.as_str().parse().ok()?;
            let refs: u32 = captures.get(3)?.as_str().parse().ok()?;

            return Some(ProgressEvent::FileIndexingCompleted {
                path: PathBuf::from(path),
                symbols,
                refs,
            });
        }

        // Try AST indexed pattern
        if let Some(captures) = self.ast_indexed_regex.captures(line) {
            let path = captures.get(1)?.as_str();

            return Some(ProgressEvent::FileAstIndexed {
                path: PathBuf::from(path),
            });
        }

        // Try AST failed patterns
        if let Some(captures) = self.ast_failed_compiler_invocation_regex.captures(line) {
            let path = captures.get(1)?.as_str();
            return Some(ProgressEvent::FileAstFailed {
                path: PathBuf::from(path),
            });
        }

        if let Some(captures) = self.ast_failed_execute_regex.captures(line) {
            let path = captures.get(1)?.as_str();
            return Some(ProgressEvent::FileAstFailed {
                path: PathBuf::from(path),
            });
        }

        if let Some(captures) = self.ast_failed_begin_source_regex.captures(line) {
            let path = captures.get(1)?.as_str();
            return Some(ProgressEvent::FileAstFailed {
                path: PathBuf::from(path),
            });
        }

        // Try stdlib start pattern
        if let Some(captures) = self.stdlib_start_regex.captures(line) {
            let stdlib_version = captures.get(1)?.as_str();
            let context_file = captures.get(2)?.as_str();

            return Some(ProgressEvent::StandardLibraryStarted {
                context_file: PathBuf::from(context_file),
                stdlib_version: stdlib_version.to_string(),
            });
        }

        // Try stdlib complete pattern
        if let Some(captures) = self.stdlib_complete_regex.captures(line) {
            let symbols: u32 = captures.get(2)?.as_str().parse().ok()?;
            let filtered: u32 = captures.get(3)?.as_str().parse().ok()?;

            return Some(ProgressEvent::StandardLibraryCompleted { symbols, filtered });
        }

        None
    }
}

/// Log monitor that processes clangd stderr output
pub struct LogMonitor {
    parser: ClangdLogParser,
    event_sender: Option<mpsc::Sender<ProgressEvent>>,
}

impl LogMonitor {
    /// Create a new log monitor with the default parser (no progress events)
    pub fn new() -> Self {
        Self {
            parser: ClangdLogParser::default(),
            event_sender: None,
        }
    }

    /// Create a log monitor with the default parser and progress event sender
    pub fn with_sender(sender: mpsc::Sender<ProgressEvent>) -> Self {
        Self {
            parser: ClangdLogParser::default(),
            event_sender: Some(sender),
        }
    }

    /// Create a log monitor with a custom parser and progress event sender
    pub fn with_parser_and_sender(
        parser: ClangdLogParser,
        sender: mpsc::Sender<ProgressEvent>,
    ) -> Self {
        Self {
            parser,
            event_sender: Some(sender),
        }
    }

    /// Process a single log line
    pub fn process_line(&self, line: &str) {
        trace!("LogMonitor: Processing stderr line: {}", line);

        if let Some(event) = self.parser.parse_line(line)
            && let Some(ref sender) = self.event_sender
        {
            // Non-blocking send - drop event if channel is full
            if sender.try_send(event).is_err() {
                warn!("LogMonitor: Progress event channel full, dropping event");
            }
        }
    }

    /// Create a stderr line processor that can be used as a callback
    pub fn create_stderr_processor(&self) -> impl Fn(String) + Send + Sync + 'static {
        // Clone the existing parser instead of creating a duplicate
        let parser = self.parser.clone();
        let sender = self.event_sender.clone();

        move |line: String| {
            if let Some(event) = parser.parse_line(&line) {
                trace!("LogMonitor: Parsed event from stderr: {:?}", event);

                if let Some(ref tx) = sender {
                    // Non-blocking send - drop event if channel is full
                    if tx.try_send(event).is_err() {
                        warn!("LogMonitor: Progress event channel full, dropping event");
                    }
                }
            }
        }
    }

    /// Process stderr stream asynchronously
    pub async fn monitor_stream<R>(&self, reader: R) -> Result<(), std::io::Error>
    where
        R: tokio::io::AsyncRead + Unpin,
    {
        let mut lines = BufReader::new(reader).lines();

        debug!("LogMonitor: Starting stderr monitoring");

        while let Some(line) = lines.next_line().await? {
            self.process_line(&line);
        }

        debug!("LogMonitor: Stderr monitoring ended");
        Ok(())
    }
}

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

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

    #[test]
    fn test_clangd_log_parser_creation() {
        let parser = ClangdLogParser::new();
        assert!(parser.is_ok());
    }

    #[test]
    fn test_parse_indexing_start_log() {
        let parser = ClangdLogParser::default();
        let line = "V[14:23:45.123] Indexing /path/to/file.cpp (digest:=0x1234ABCD)";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::FileIndexingStarted { path, digest } => {
                assert_eq!(path, PathBuf::from("/path/to/file.cpp"));
                assert_eq!(digest, "0x1234ABCD");
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_parse_indexing_complete_log() {
        let parser = ClangdLogParser::default();
        let line = "I[14:23:46.456] Indexed /path/to/file.cpp (42 symbols, 10 refs, 3 files)";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::FileIndexingCompleted {
                path,
                symbols,
                refs,
            } => {
                assert_eq!(path, PathBuf::from("/path/to/file.cpp"));
                assert_eq!(symbols, 42);
                assert_eq!(refs, 10);
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_parse_ast_indexed_log() {
        let parser = ClangdLogParser::default();
        let line =
            "V[22:06:42.564] indexed file AST for /tmp/.tmpCSsikQ/src/Container.cpp version 1:";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::FileAstIndexed { path } => {
                assert_eq!(path, PathBuf::from("/tmp/.tmpCSsikQ/src/Container.cpp"));
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_parse_stdlib_indexing_start() {
        let parser = ClangdLogParser::default();
        let line =
            "I[14:23:47.789] Indexing c++20 standard library in the context of /path/to/file.cpp";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::StandardLibraryStarted {
                context_file,
                stdlib_version,
            } => {
                assert_eq!(context_file, PathBuf::from("/path/to/file.cpp"));
                assert_eq!(stdlib_version, "c++20");
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_parse_stdlib_indexing_complete() {
        let parser = ClangdLogParser::default();
        let line = "I[14:23:48.000] Indexed c++20 standard library: 1234 symbols, 567 filtered";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::StandardLibraryCompleted { symbols, filtered } => {
                assert_eq!(symbols, 1234);
                assert_eq!(filtered, 567);
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_parse_ignore_unrelated_logs() {
        let parser = ClangdLogParser::default();
        let line = "I[14:23:48.000] Some other log message";

        let event = parser.parse_line(line);
        assert!(event.is_none());
    }

    #[test]
    fn test_log_monitor_creation() {
        let monitor = LogMonitor::new();
        assert!(monitor.event_sender.is_none());
    }

    #[tokio::test]
    async fn test_log_monitor_with_channel() {
        let (tx, mut rx) = mpsc::channel(10);
        let monitor = LogMonitor::with_sender(tx);

        // Test processing a line
        let line = "V[14:23:45.123] Indexing /test.cpp (digest:=0xABC)";
        monitor.process_line(line);

        // Receive the event
        let event = rx.recv().await.expect("Should receive event");
        match event {
            ProgressEvent::FileIndexingStarted { path, digest } => {
                assert_eq!(path, PathBuf::from("/test.cpp"));
                assert_eq!(digest, "0xABC");
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_log_monitor_no_sender() {
        let monitor = LogMonitor::new();

        // Should not panic when no sender is set
        let line = "V[14:23:45.123] Indexing /test.cpp (digest:=0xABC)";
        monitor.process_line(line);
    }

    #[tokio::test]
    async fn test_monitor_stream() {
        let (tx, mut rx) = mpsc::channel(10);
        let monitor = LogMonitor::with_sender(tx);

        let log_data = "V[14:23:45.123] Indexing /test1.cpp (digest:=0xABC)\n\
                       I[14:23:46.456] Indexed /test1.cpp (42 symbols, 10 refs, 3 files)\n\
                       I[14:23:47.000] Some unrelated log\n\
                       V[14:23:48.123] Indexing /test2.cpp (digest:=0xDEF)\n";

        let cursor = std::io::Cursor::new(log_data.as_bytes());

        // Monitor the stream
        monitor.monitor_stream(cursor).await.unwrap();

        // Collect all events
        let mut events = Vec::new();
        while let Ok(event) = rx.try_recv() {
            events.push(event);
        }
        assert_eq!(events.len(), 3);

        match &events[0] {
            ProgressEvent::FileIndexingStarted { path, .. } => {
                assert_eq!(*path, PathBuf::from("/test1.cpp"));
            }
            _ => panic!("Wrong event type at index 0"),
        }

        match &events[1] {
            ProgressEvent::FileIndexingCompleted {
                path,
                symbols,
                refs,
            } => {
                assert_eq!(*path, PathBuf::from("/test1.cpp"));
                assert_eq!(*symbols, 42);
                assert_eq!(*refs, 10);
            }
            _ => panic!("Wrong event type at index 1"),
        }

        match &events[2] {
            ProgressEvent::FileIndexingStarted { path, .. } => {
                assert_eq!(*path, PathBuf::from("/test2.cpp"));
            }
            _ => panic!("Wrong event type at index 2"),
        }
    }

    #[test]
    fn test_parse_ast_failed_compiler_invocation() {
        let parser = ClangdLogParser::default();
        let line = "E[14:23:45.123] Could not build CompilerInvocation for file /path/to/file.cpp";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::FileAstFailed { path } => {
                assert_eq!(path, PathBuf::from("/path/to/file.cpp"));
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_parse_ast_failed_execute() {
        let parser = ClangdLogParser::default();
        let line =
            "E[14:23:45.123] Execute() failed when building AST for /path/to/file.cpp: some error";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::FileAstFailed { path } => {
                assert_eq!(path, PathBuf::from("/path/to/file.cpp"));
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_parse_ast_failed_begin_source() {
        let parser = ClangdLogParser::default();
        let line =
            "E[14:23:45.123] BeginSourceFile() failed when building AST for /path/to/file.cpp";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::FileAstFailed { path } => {
                assert_eq!(path, PathBuf::from("/path/to/file.cpp"));
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_parse_ast_failed_warning_level() {
        let parser = ClangdLogParser::default();
        let line = "W[14:23:45.123] Could not build CompilerInvocation for file /path/to/file.cpp";

        let event = parser.parse_line(line);

        assert!(event.is_some());
        match event.unwrap() {
            ProgressEvent::FileAstFailed { path } => {
                assert_eq!(path, PathBuf::from("/path/to/file.cpp"));
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_regex_edge_cases() {
        let parser = ClangdLogParser::default();

        // Test with different timestamp formats
        let line1 = "V[01:02:03.999] Indexing /some/path.cpp (digest:=ABC123)";
        assert!(parser.parse_line(line1).is_some());

        // Test with different digest formats
        let line2 = "V[14:23:45.123] Indexing /path.cpp (digest:=0x1234ABCDEF)";
        assert!(parser.parse_line(line2).is_some());

        // Test with paths containing spaces (should not match due to regex)
        let line3 = "V[14:23:45.123] Indexing /path with spaces/file.cpp (digest:=ABC)";
        // This will match because our regex uses .+? which is non-greedy
        assert!(parser.parse_line(line3).is_some());

        // Test malformed lines
        let line4 = "V[14:23:45.123] Indexing incomplete line";
        assert!(parser.parse_line(line4).is_none());
    }
}