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
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
//! Workspace symbols extraction functionality for C++ projects
//!
//! This module provides LSP-based workspace symbol search with filtering capabilities
//! that work with clangd to find symbols across the entire project workspace.
//! It follows the same builder and iterator patterns as document_symbols.rs for consistency.
//!
//! ## Important Limitations
//!
//! ### Clangd Heuristics and Result Filtering
//!
//! **You may not get all symbols even with high limits** due to clangd's internal heuristics:
//!
//! 1. **Relevance Ranking**: clangd applies its own relevance scoring and may filter out
//!    symbols it considers less relevant to the query, even if they match.
//!
//! 2. **Query-dependent Filtering**: clangd uses fuzzy matching and may exclude symbols
//!    that don't meet its internal similarity thresholds.
//!
//! 3. **Performance Optimizations**: clangd may limit results based on index size,
//!    query complexity, and performance considerations.
//!
//! 4. **Index Coverage**: Symbols may not appear if:
//!    - The file hasn't been indexed yet
//!    - The compilation database is incomplete
//!    - clangd encountered parsing errors
//!
//! ### When to Use Workspace vs Document Search
//!
//! - **Workspace Search**: Best for discovery and fuzzy matching across the entire project.
//!   Results are subject to clangd's relevance ranking and may be incomplete.
//!
//! - **Document Search**: Best for comprehensive symbol listing within specific files.
//!   Returns all symbols in the file that match the criteria (more predictable results).
//!
//! ### Configuration
//!
//! The workspace symbol limit is configured via `DEFAULT_WORKSPACE_SYMBOL_LIMIT` (1000)
//! and passed to clangd via the `--limit-results` argument. However, clangd may return
//! fewer results based on its internal filtering.

use lsp_types::{SymbolKind, WorkspaceSymbol};
use tracing::{debug, trace};

use crate::clangd::session::ClangdSessionTrait;
use crate::lsp::traits::LspClientTrait;
use crate::mcp_server::tools::analyze_symbols::AnalyzerError;
use crate::project::ProjectComponent;
use crate::project::component_session::ComponentSession;

// ============================================================================
// Traits for Workspace Symbol Filtering
// ============================================================================

/// Trait for filtering workspace symbols based on various criteria
pub trait WorkspaceSymbolFilter {
    /// Check if the workspace symbol passes the filter
    fn matches(&self, symbol: &WorkspaceSymbol) -> bool;
}

/// Filter for project boundary detection
pub struct ProjectBoundaryFilter {
    include_external: bool,
    canonical_source_root: std::path::PathBuf,
}

impl ProjectBoundaryFilter {
    pub fn new(component: &ProjectComponent, include_external: bool) -> Self {
        let canonical_source_root = component
            .source_root_path
            .canonicalize()
            .unwrap_or_else(|_| component.source_root_path.clone());

        Self {
            include_external,
            canonical_source_root,
        }
    }

    /// Check if a file path belongs to the project
    fn is_project_file(&self, path: &str) -> bool {
        let file_path = std::path::PathBuf::from(path);

        if let Ok(canonical_file) = file_path.canonicalize() {
            canonical_file.starts_with(&self.canonical_source_root)
        } else {
            false
        }
    }
}

impl WorkspaceSymbolFilter for ProjectBoundaryFilter {
    fn matches(&self, symbol: &WorkspaceSymbol) -> bool {
        if self.include_external {
            return true;
        }

        let uri_str = match &symbol.location {
            lsp_types::OneOf::Left(location) => location.uri.as_str(),
            lsp_types::OneOf::Right(workspace_location) => workspace_location.uri.as_str(),
        };

        if let Some(path) = uri_str.strip_prefix("file://") {
            self.is_project_file(path)
        } else {
            true // Default to inclusion when URI parsing fails
        }
    }
}

/// Filter for symbol kinds
pub struct SymbolKindFilter {
    allowed_kinds: Vec<lsp_types::SymbolKind>,
}

impl SymbolKindFilter {
    #[allow(dead_code)]
    pub fn new(kinds: Vec<SymbolKind>) -> Self {
        Self {
            allowed_kinds: kinds,
        }
    }
}

impl WorkspaceSymbolFilter for SymbolKindFilter {
    fn matches(&self, symbol: &WorkspaceSymbol) -> bool {
        self.allowed_kinds.contains(&symbol.kind)
    }
}

/// Filter for symbol names using substring matching
pub struct NameFilter {
    query: String,
    case_sensitive: bool,
}

impl NameFilter {
    pub fn new(query: String, case_sensitive: bool) -> Self {
        Self {
            query,
            case_sensitive,
        }
    }
}

impl WorkspaceSymbolFilter for NameFilter {
    fn matches(&self, symbol: &WorkspaceSymbol) -> bool {
        if self.case_sensitive {
            symbol.name.contains(&self.query)
        } else {
            symbol
                .name
                .to_lowercase()
                .contains(&self.query.to_lowercase())
        }
    }
}

// ============================================================================
// Iterator for Workspace Symbols
// ============================================================================

/// Iterator over workspace symbols with filtering capabilities
pub struct WorkspaceSymbolIterator<'a> {
    symbols: std::slice::Iter<'a, WorkspaceSymbol>,
    filters: Vec<Box<dyn WorkspaceSymbolFilter + 'a>>,
}

impl<'a> WorkspaceSymbolIterator<'a> {
    /// Create a new iterator over workspace symbols
    pub fn new(symbols: &'a [WorkspaceSymbol]) -> Self {
        Self {
            symbols: symbols.iter(),
            filters: Vec::new(),
        }
    }

    /// Add a filter to the iterator
    pub fn with_filter<F: WorkspaceSymbolFilter + 'a>(mut self, filter: F) -> Self {
        self.filters.push(Box::new(filter));
        self
    }

    /// Check if a symbol passes all filters
    fn passes_filters(&self, symbol: &WorkspaceSymbol) -> bool {
        self.filters.iter().all(|filter| filter.matches(symbol))
    }
}

impl<'a> Iterator for WorkspaceSymbolIterator<'a> {
    type Item = &'a WorkspaceSymbol;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let symbol = self.symbols.next()?;
            if self.passes_filters(symbol) {
                return Some(symbol);
            }
        }
    }
}

// ============================================================================
// Workspace Symbol Search Builder
// ============================================================================

/// Builder pattern for flexible workspace symbol searching
#[derive(Debug, Clone)]
pub struct WorkspaceSymbolSearchBuilder {
    query: String,
    kinds: Option<Vec<lsp_types::SymbolKind>>,
    max_results: Option<u32>,
    include_external: bool,
    case_sensitive: bool,
}

impl WorkspaceSymbolSearchBuilder {
    /// Create a new search builder with the given query
    pub fn new(query: String) -> Self {
        Self {
            query,
            kinds: None,
            max_results: None,
            include_external: false,
            case_sensitive: false,
        }
    }

    /// Filter by specific symbol kinds
    pub fn with_kinds(mut self, kinds: Vec<lsp_types::SymbolKind>) -> Self {
        self.kinds = Some(kinds);
        self
    }

    /// Limit the maximum number of results
    pub fn with_max_results(mut self, max_results: u32) -> Self {
        self.max_results = Some(max_results);
        self
    }

    /// Include external symbols from system libraries
    pub fn include_external(mut self, include: bool) -> Self {
        self.include_external = include;
        self
    }

    /// Enable case-sensitive search
    #[allow(dead_code)]
    pub fn case_sensitive(mut self, sensitive: bool) -> Self {
        self.case_sensitive = sensitive;
        self
    }

    /// Execute the search and return filtered results
    pub async fn search(
        &self,
        component_session: &ComponentSession,
        component: &ProjectComponent,
    ) -> Result<Vec<WorkspaceSymbol>, AnalyzerError> {
        trace!(
            "Executing workspace symbol search with query: {}",
            self.query
        );

        // Get symbols from clangd with a large limit (2000) to preserve ranking
        let mut session = component_session.lsp_session().await;
        let symbols = session
            .client_mut()
            .workspace_symbols(self.query.clone())
            .await
            .map_err(AnalyzerError::from)?;

        debug!("Retrieved {} symbols from clangd", symbols.len());

        // Apply filters using iterator pattern
        let mut filtered_iter = WorkspaceSymbolIterator::new(&symbols);

        // Add project boundary filter
        filtered_iter =
            filtered_iter.with_filter(ProjectBoundaryFilter::new(component, self.include_external));

        // Add symbol kind filter if specified
        if let Some(ref kinds) = self.kinds {
            filtered_iter = filtered_iter.with_filter(SymbolKindFilter::new(kinds.clone()));
        }

        // Add name filter for additional refinement (beyond clangd's initial filtering)
        filtered_iter =
            filtered_iter.with_filter(NameFilter::new(self.query.clone(), self.case_sensitive));

        // Collect results with optional limit
        let results: Vec<WorkspaceSymbol> = if let Some(max) = self.max_results {
            filtered_iter
                .take(max.min(1000) as usize)
                .cloned()
                .collect()
        } else {
            filtered_iter.cloned().collect()
        };

        debug!(
            "Filtered to {} symbols after applying filters",
            results.len()
        );
        Ok(results)
    }

    /// Execute search and return only the first result
    #[allow(dead_code)]
    pub async fn find_first(
        &self,
        component_session: &ComponentSession,
        component: &ProjectComponent,
    ) -> Result<Option<WorkspaceSymbol>, AnalyzerError> {
        let mut builder = self.clone();
        builder.max_results = Some(1);
        let results = builder.search(component_session, component).await?;
        Ok(results.into_iter().next())
    }
}

// ============================================================================
// Public API Functions
// ============================================================================

/// Search for workspace symbols using the builder pattern
///
/// This is a convenience function that creates a builder with common defaults.
/// For more control, use `WorkspaceSymbolSearchBuilder::new()` directly.
///
/// # Arguments
/// * `query` - Search query string
/// * `session` - Active clangd session
/// * `component` - Project component for boundary filtering
///
/// # Returns
/// * `Ok(Vec<WorkspaceSymbol>)` - Filtered workspace symbols
/// * `Err(AnalyzerError)` - LSP error or search failure
#[allow(dead_code)]
pub async fn search_workspace_symbols(
    query: &str,
    component_session: &ComponentSession,
    component: &ProjectComponent,
) -> Result<Vec<WorkspaceSymbol>, AnalyzerError> {
    WorkspaceSymbolSearchBuilder::new(query.to_string())
        .search(component_session, component)
        .await
}

/// Search for workspace symbols with kind filtering
///
/// # Arguments
/// * `query` - Search query string
/// * `kinds` - Symbol kinds to include
/// * `session` - Active clangd session
/// * `component` - Project component for boundary filtering
///
/// # Returns
/// * `Ok(Vec<WorkspaceSymbol>)` - Filtered workspace symbols
/// * `Err(AnalyzerError)` - LSP error or search failure
#[allow(dead_code)]
pub async fn search_workspace_symbols_with_kinds(
    query: &str,
    kinds: Vec<lsp_types::SymbolKind>,
    component_session: &ComponentSession,
    component: &ProjectComponent,
) -> Result<Vec<WorkspaceSymbol>, AnalyzerError> {
    WorkspaceSymbolSearchBuilder::new(query.to_string())
        .with_kinds(kinds)
        .search(component_session, component)
        .await
}

/// Find the first workspace symbol matching the query
///
/// # Arguments
/// * `query` - Search query string
/// * `session` - Active clangd session
/// * `component` - Project component for boundary filtering
///
/// # Returns
/// * `Ok(Some(WorkspaceSymbol))` - First matching symbol
/// * `Ok(None)` - No symbols found
/// * `Err(AnalyzerError)` - LSP error or search failure
#[allow(dead_code)]
pub async fn find_first_workspace_symbol(
    query: &str,
    component_session: &ComponentSession,
    component: &ProjectComponent,
) -> Result<Option<WorkspaceSymbol>, AnalyzerError> {
    WorkspaceSymbolSearchBuilder::new(query.to_string())
        .find_first(component_session, component)
        .await
}

/// Search for workspace symbols in project scope only
///
/// This excludes external libraries and system headers by default.
///
/// # Arguments
/// * `query` - Search query string
/// * `session` - Active clangd session
/// * `component` - Project component for boundary filtering
///
/// # Returns
/// * `Ok(Vec<WorkspaceSymbol>)` - Project-scoped workspace symbols
/// * `Err(AnalyzerError)` - LSP error or search failure
#[allow(dead_code)]
pub async fn search_project_symbols(
    query: &str,
    component_session: &ComponentSession,
    component: &ProjectComponent,
) -> Result<Vec<WorkspaceSymbol>, AnalyzerError> {
    WorkspaceSymbolSearchBuilder::new(query.to_string())
        .include_external(false)
        .search(component_session, component)
        .await
}

/// Count total workspace symbols matching query
///
/// # Arguments
/// * `query` - Search query string
/// * `session` - Active clangd session
/// * `component` - Project component for boundary filtering
///
/// # Returns
/// * `Ok(usize)` - Count of matching symbols
/// * `Err(AnalyzerError)` - LSP error or search failure
#[allow(dead_code)]
pub async fn count_workspace_symbols(
    query: &str,
    component_session: &ComponentSession,
    component: &ProjectComponent,
) -> Result<usize, AnalyzerError> {
    let symbols = search_workspace_symbols(query, component_session, component).await?;
    Ok(symbols.len())
}

#[cfg(test)]
mod tests {
    use super::*;
    use lsp_types::{Location, OneOf, Position, Range, Uri, WorkspaceSymbol};
    use std::path::PathBuf;
    use std::str::FromStr;

    fn create_test_workspace_symbol(
        name: &str,
        kind: SymbolKind,
        uri: &str,
        container: Option<&str>,
    ) -> WorkspaceSymbol {
        WorkspaceSymbol {
            name: name.to_string(),
            kind,
            tags: None,
            container_name: container.map(|c| c.to_string()),
            location: OneOf::Left(Location {
                uri: Uri::from_str(uri).unwrap(),
                range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: name.len() as u32,
                    },
                },
            }),
            data: None,
        }
    }

    fn create_test_component() -> ProjectComponent {
        ProjectComponent {
            build_dir_path: PathBuf::from("/test/project/build"),
            source_root_path: PathBuf::from("/test/project"),
            compilation_database_path: PathBuf::from("/test/project/build/compile_commands.json"),
            provider_type: "cmake".to_string(),
            generator: "Ninja".to_string(),
            build_type: "Debug".to_string(),
            build_options: std::collections::HashMap::new(),
        }
    }

    #[test]
    fn test_workspace_symbol_iterator_basic() {
        let symbols = vec![
            create_test_workspace_symbol("ClassA", SymbolKind::CLASS, "file:///test.cpp", None),
            create_test_workspace_symbol(
                "functionB",
                SymbolKind::FUNCTION,
                "file:///test.cpp",
                None,
            ),
            create_test_workspace_symbol("ClassC", SymbolKind::CLASS, "file:///test.cpp", None),
        ];

        let classes: Vec<_> = WorkspaceSymbolIterator::new(&symbols)
            .with_filter(SymbolKindFilter::new(vec![SymbolKind::CLASS]))
            .collect();

        assert_eq!(classes.len(), 2);
        assert!(classes.iter().all(|s| s.kind == SymbolKind::CLASS));
    }

    #[test]
    fn test_workspace_symbol_iterator_multiple_filters() {
        let symbols = vec![
            create_test_workspace_symbol("TestClass", SymbolKind::CLASS, "file:///test.cpp", None),
            create_test_workspace_symbol("MyClass", SymbolKind::CLASS, "file:///test.cpp", None),
            create_test_workspace_symbol(
                "TestFunction",
                SymbolKind::FUNCTION,
                "file:///test.cpp",
                None,
            ),
        ];

        let results: Vec<_> = WorkspaceSymbolIterator::new(&symbols)
            .with_filter(SymbolKindFilter::new(vec![SymbolKind::CLASS]))
            .with_filter(NameFilter::new("Test".to_string(), false))
            .collect();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "TestClass");
    }

    #[test]
    fn test_symbol_kind_filter_from_kinds() {
        let kinds = vec![SymbolKind::CLASS, SymbolKind::FUNCTION];
        let filter = SymbolKindFilter::new(kinds);

        let class_symbol =
            create_test_workspace_symbol("Test", SymbolKind::CLASS, "file:///test.cpp", None);
        let function_symbol =
            create_test_workspace_symbol("Test", SymbolKind::FUNCTION, "file:///test.cpp", None);
        let variable_symbol =
            create_test_workspace_symbol("Test", SymbolKind::VARIABLE, "file:///test.cpp", None);

        assert!(filter.matches(&class_symbol));
        assert!(filter.matches(&function_symbol));
        assert!(!filter.matches(&variable_symbol));
    }

    #[test]
    fn test_name_filter_case_insensitive() {
        let filter = NameFilter::new("test".to_string(), false);

        let symbol1 =
            create_test_workspace_symbol("TestClass", SymbolKind::CLASS, "file:///test.cpp", None);
        let symbol2 =
            create_test_workspace_symbol("mytest", SymbolKind::FUNCTION, "file:///test.cpp", None);
        let symbol3 =
            create_test_workspace_symbol("Other", SymbolKind::VARIABLE, "file:///test.cpp", None);

        assert!(filter.matches(&symbol1));
        assert!(filter.matches(&symbol2));
        assert!(!filter.matches(&symbol3));
    }

    #[test]
    fn test_name_filter_case_sensitive() {
        let filter = NameFilter::new("Test".to_string(), true);

        let symbol1 =
            create_test_workspace_symbol("TestClass", SymbolKind::CLASS, "file:///test.cpp", None);
        let symbol2 = create_test_workspace_symbol(
            "testClass",
            SymbolKind::FUNCTION,
            "file:///test.cpp",
            None,
        );

        assert!(filter.matches(&symbol1));
        assert!(!filter.matches(&symbol2));
    }

    #[test]
    fn test_workspace_symbol_search_builder() {
        let builder = WorkspaceSymbolSearchBuilder::new("test".to_string())
            .with_kinds(vec![lsp_types::SymbolKind::CLASS])
            .with_max_results(10)
            .include_external(true)
            .case_sensitive(false);

        assert_eq!(builder.query, "test");
        assert_eq!(builder.kinds, Some(vec![lsp_types::SymbolKind::CLASS]));
        assert_eq!(builder.max_results, Some(10));
        assert!(builder.include_external);
        assert!(!builder.case_sensitive);
    }

    #[test]
    fn test_project_boundary_filter() {
        let component = create_test_component();

        // Create symbols - one in project, one external
        let _project_symbol = create_test_workspace_symbol(
            "ProjectClass",
            SymbolKind::CLASS,
            "file:///test/project/src/main.cpp",
            None,
        );
        let _external_symbol = create_test_workspace_symbol(
            "ExternalClass",
            SymbolKind::CLASS,
            "file:///usr/include/vector",
            None,
        );

        let filter = ProjectBoundaryFilter::new(&component, false);

        // Note: This test will not actually work without real file system
        // In practice, canonicalize() would be mocked or tested with real files
        // For now, we test the structure is correct
        assert!(!filter.include_external);
        // canonical_source_root should be the canonicalized version of source_root_path
        // In tests, canonicalize might fail, so it falls back to the original path
        assert!(
            filter.canonical_source_root == component.source_root_path
                || filter.canonical_source_root.ends_with("test/project")
        );
    }
}