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
//! Integration tests for call hierarchy analysis functionality
//!
//! These tests verify that the call hierarchy analysis functionality works correctly
//! with real clangd integration, testing function and method call relationships including
//! incoming calls (callers) and outgoing calls (callees).

use crate::mcp_server::tools::analyze_symbols::{AnalyzeSymbolContextTool, AnalyzerResult};
use crate::project::{ProjectScanner, WorkspaceSession};
use crate::test_utils::{DEFAULT_INDEXING_TIMEOUT, integration::TestProject};
use tracing::info;

#[cfg(feature = "clangd-integration-tests")]
#[tokio::test]
async fn test_analyzer_call_hierarchy_function() {
    // Create a test project first
    let test_project = TestProject::new().await.unwrap();
    test_project.cmake_configure().await.unwrap();

    // Scan the test project to create a proper workspace with components
    let scanner = ProjectScanner::with_default_providers();
    let workspace = scanner
        .scan_project(&test_project.project_root, 3, None)
        .expect("Failed to scan test project");

    // Create a WorkspaceSession with test clangd path
    let clangd_path = crate::test_utils::get_test_clangd_path();
    let workspace_session = WorkspaceSession::new(workspace.clone(), clangd_path)
        .expect("Failed to create workspace session");

    // Test factorial function - should have callers from main.cpp
    let tool = AnalyzeSymbolContextTool {
        symbol: "factorial".to_string(),
        build_directory: None,
        max_examples: Some(2),
        location_hint: None,
        wait_timeout: None,
    };

    let component_session = workspace_session
        .get_component_session(test_project.build_dir.clone())
        .await
        .unwrap();
    let result = tool.call_tool(component_session, &workspace).await;

    assert!(result.is_ok());

    let call_result = result.unwrap();
    let text = if let Some(rust_mcp_sdk::schema::ContentBlock::TextContent(
        rust_mcp_sdk::schema::TextContent { text, .. },
    )) = call_result.content.first()
    {
        text
    } else {
        panic!("Expected TextContent in call_result");
    };
    let analyzer_result: AnalyzerResult = serde_json::from_str(text).unwrap();

    assert_eq!(analyzer_result.symbol.name, "factorial");
    assert_eq!(analyzer_result.symbol.kind, lsp_types::SymbolKind::METHOD);

    // Check call hierarchy
    assert!(analyzer_result.call_hierarchy.is_some());
    let hierarchy = analyzer_result.call_hierarchy.unwrap();

    // factorial should have callers (from main.cpp)
    info!("factorial callers: {:?}", hierarchy.callers);
    info!("factorial callees: {:?}", hierarchy.callees);

    // factorial should have at least one caller (main function)
    assert!(!hierarchy.callers.is_empty());

    info!(
        "factorial call hierarchy - callers: {} callees: {}",
        hierarchy.callers.len(),
        hierarchy.callees.len()
    );
}

#[cfg(feature = "clangd-integration-tests")]
#[tokio::test]
async fn test_analyzer_call_hierarchy_method() {
    // Create a test project first
    let test_project = TestProject::new().await.unwrap();
    test_project.cmake_configure().await.unwrap();

    // Scan the test project to create a proper workspace with components
    let scanner = ProjectScanner::with_default_providers();
    let workspace = scanner
        .scan_project(&test_project.project_root, 3, None)
        .expect("Failed to scan test project");

    // Create a WorkspaceSession with test clangd path
    let clangd_path = crate::test_utils::get_test_clangd_path();
    let workspace_session = WorkspaceSession::new(workspace.clone(), clangd_path)
        .expect("Failed to create workspace session");

    // Test Math::Complex::add method - should have callers from main.cpp
    let tool = AnalyzeSymbolContextTool {
        symbol: "Math::Complex::add".to_string(), // Fully qualified name
        build_directory: None,
        max_examples: Some(2),
        location_hint: None,
        wait_timeout: None,
    };

    let component_session = workspace_session
        .get_component_session(test_project.build_dir.clone())
        .await
        .unwrap();
    let result = tool.call_tool(component_session, &workspace).await;

    assert!(result.is_ok());

    let call_result = result.unwrap();
    let text = if let Some(rust_mcp_sdk::schema::ContentBlock::TextContent(
        rust_mcp_sdk::schema::TextContent { text, .. },
    )) = call_result.content.first()
    {
        text
    } else {
        panic!("Expected TextContent in call_result");
    };
    let analyzer_result: AnalyzerResult = serde_json::from_str(text).unwrap();

    assert_eq!(analyzer_result.symbol.name, "add"); // clangd returns just the method name
    assert_eq!(analyzer_result.symbol.kind, lsp_types::SymbolKind::METHOD);

    // Check call hierarchy
    assert!(analyzer_result.call_hierarchy.is_some());
    let hierarchy = analyzer_result.call_hierarchy.unwrap();

    info!("add method callers: {:?}", hierarchy.callers);
    info!("add method callees: {:?}", hierarchy.callees);

    // add should have at least one caller (main function)
    assert!(!hierarchy.callers.is_empty());

    info!(
        "add method call hierarchy - callers: {} callees: {}",
        hierarchy.callers.len(),
        hierarchy.callees.len()
    );
}

#[cfg(feature = "clangd-integration-tests")]
#[tokio::test]
async fn test_analyzer_call_hierarchy_non_function() {
    // Create a test project first
    let test_project = TestProject::new().await.unwrap();
    test_project.cmake_configure().await.unwrap();

    // Scan the test project to create a proper workspace with components
    let scanner = ProjectScanner::with_default_providers();
    let workspace = scanner
        .scan_project(&test_project.project_root, 3, None)
        .expect("Failed to scan test project");

    // Create a WorkspaceSession with test clangd path
    let clangd_path = crate::test_utils::get_test_clangd_path();
    let workspace_session = WorkspaceSession::new(workspace.clone(), clangd_path)
        .expect("Failed to create workspace session");

    // Test a class - should have no call hierarchy
    let tool = AnalyzeSymbolContextTool {
        symbol: "Math".to_string(),
        build_directory: None,
        max_examples: Some(2),
        location_hint: None,
        wait_timeout: None,
    };

    let component_session = workspace_session
        .get_component_session(test_project.build_dir.clone())
        .await
        .unwrap();
    let result = tool.call_tool(component_session, &workspace).await;

    assert!(result.is_ok());

    let call_result = result.unwrap();
    let text = if let Some(rust_mcp_sdk::schema::ContentBlock::TextContent(
        rust_mcp_sdk::schema::TextContent { text, .. },
    )) = call_result.content.first()
    {
        text
    } else {
        panic!("Expected TextContent in call_result");
    };
    let analyzer_result: AnalyzerResult = serde_json::from_str(text).unwrap();

    assert_eq!(analyzer_result.symbol.name, "Math");
    assert_eq!(analyzer_result.symbol.kind, lsp_types::SymbolKind::CLASS);

    // Check that call hierarchy is not present for classes
    assert!(analyzer_result.call_hierarchy.is_none());

    // But type hierarchy should be present for classes
    assert!(analyzer_result.type_hierarchy.is_some());

    info!(
        "Math class - has type hierarchy: {}, has call hierarchy: {}",
        analyzer_result.type_hierarchy.is_some(),
        analyzer_result.call_hierarchy.is_some()
    );
}

#[cfg(feature = "clangd-integration-tests")]
#[tokio::test]
async fn test_analyzer_call_hierarchy_coherence() {
    // Create a test project first
    let test_project = TestProject::new().await.unwrap();
    test_project.cmake_configure().await.unwrap();

    // Scan the test project to create a proper workspace with components
    let scanner = ProjectScanner::with_default_providers();
    let workspace = scanner
        .scan_project(&test_project.project_root, 3, None)
        .expect("Failed to scan test project");

    // Create a WorkspaceSession with test clangd path
    let clangd_path = crate::test_utils::get_test_clangd_path();
    let workspace_session = WorkspaceSession::new(workspace.clone(), clangd_path)
        .expect("Failed to create workspace session");

    // Ensure indexing is completed before testing call hierarchy coherence
    let component_session = workspace_session
        .get_component_session(test_project.build_dir.clone())
        .await
        .unwrap();

    // Wait for indexing to complete (30 seconds should be plenty for the test project)
    component_session
        .ensure_indexed(DEFAULT_INDEXING_TIMEOUT)
        .await
        .expect("Indexing should complete successfully for call hierarchy test");

    info!("Indexing completed, proceeding with call hierarchy coherence test");

    // Test the call chain: standardDeviation -> variance -> mean
    // This validates coherence: if A calls B, then B's callers must include A

    // Use qualified names to be more specific about which overload we want
    // According to clangd documentation, we can use scope-based queries

    // 1. Analyze variance (middle of the chain) - use location hint to target vector<double> overload
    let test_project_include = workspace.project_root_path.join("include/Math.hpp");
    let canonical_path = test_project_include
        .canonicalize()
        .expect("Failed to canonicalize Math.hpp path");
    let variance_location = format!("{}:431:19", canonical_path.display()); // Line 431, column 19 points to "variance" function name

    let variance_tool = AnalyzeSymbolContextTool {
        symbol: "variance".to_string(),
        build_directory: None,
        max_examples: Some(2),
        location_hint: Some(variance_location),
        wait_timeout: None,
    };

    let component_session = workspace_session
        .get_component_session(test_project.build_dir.clone())
        .await
        .unwrap();
    let variance_result = variance_tool
        .call_tool(component_session, &workspace)
        .await
        .expect("Failed to analyze variance");

    let variance_text = if let Some(rust_mcp_sdk::schema::ContentBlock::TextContent(
        rust_mcp_sdk::schema::TextContent { text, .. },
    )) = variance_result.content.first()
    {
        text
    } else {
        panic!("Expected TextContent in variance_result");
    };
    let variance_analysis: AnalyzerResult = serde_json::from_str(variance_text).unwrap();

    assert_eq!(variance_analysis.symbol.name, "variance");
    assert_eq!(variance_analysis.symbol.kind, lsp_types::SymbolKind::METHOD);
    assert!(variance_analysis.call_hierarchy.is_some());

    // Assert that indexing completed successfully (either None or Completed state)
    if let Some(ref status) = variance_analysis.index_status {
        assert!(
            status.state.contains("Completed") && status.indexed_files == status.total_files,
            "Indexing should have completed successfully for variance analysis. Index status: {:?}",
            variance_analysis.index_status
        );
    }

    let variance_hierarchy = variance_analysis.call_hierarchy.unwrap();
    info!("variance callers: {:?}", variance_hierarchy.callers);
    info!("variance callees: {:?}", variance_hierarchy.callees);

    // 2. Analyze mean (end of the chain) - use qualified name
    let mean_tool = AnalyzeSymbolContextTool {
        symbol: "Math::mean".to_string(), // Use qualified name
        build_directory: None,
        max_examples: Some(2),
        location_hint: None,
        wait_timeout: None,
    };

    let component_session = workspace_session
        .get_component_session(test_project.build_dir.clone())
        .await
        .unwrap();
    let mean_result = mean_tool
        .call_tool(component_session, &workspace)
        .await
        .expect("Failed to analyze mean");

    let mean_text = if let Some(rust_mcp_sdk::schema::ContentBlock::TextContent(
        rust_mcp_sdk::schema::TextContent { text, .. },
    )) = mean_result.content.first()
    {
        text
    } else {
        panic!("Expected TextContent in mean_result");
    };
    let mean_analysis: AnalyzerResult = serde_json::from_str(mean_text).unwrap();

    assert_eq!(mean_analysis.symbol.name, "mean");
    assert_eq!(mean_analysis.symbol.kind, lsp_types::SymbolKind::METHOD);
    assert!(mean_analysis.call_hierarchy.is_some());

    // Assert that indexing completed successfully for mean analysis
    if let Some(ref status) = mean_analysis.index_status {
        assert!(
            status.state.contains("Completed") && status.indexed_files == status.total_files,
            "Indexing should have completed successfully for mean analysis. Index status: {:?}",
            mean_analysis.index_status
        );
    }

    let mean_hierarchy = mean_analysis.call_hierarchy.unwrap();
    info!("mean callers: {:?}", mean_hierarchy.callers);
    info!("mean callees: {:?}", mean_hierarchy.callees);

    // 3. Analyze standardDeviation (start of the chain) - use qualified name
    let std_dev_tool = AnalyzeSymbolContextTool {
        symbol: "Math::standardDeviation".to_string(), // Use qualified name
        build_directory: None,
        max_examples: Some(2),
        location_hint: None,
        wait_timeout: None,
    };

    let component_session = workspace_session
        .get_component_session(test_project.build_dir.clone())
        .await
        .unwrap();
    let std_dev_result = std_dev_tool
        .call_tool(component_session, &workspace)
        .await
        .expect("Failed to analyze standardDeviation");

    let std_dev_text = if let Some(rust_mcp_sdk::schema::ContentBlock::TextContent(
        rust_mcp_sdk::schema::TextContent { text, .. },
    )) = std_dev_result.content.first()
    {
        text
    } else {
        panic!("Expected TextContent in std_dev_result");
    };
    let std_dev_analysis: AnalyzerResult = serde_json::from_str(std_dev_text).unwrap();

    assert_eq!(std_dev_analysis.symbol.name, "standardDeviation");
    assert_eq!(std_dev_analysis.symbol.kind, lsp_types::SymbolKind::METHOD);
    assert!(std_dev_analysis.call_hierarchy.is_some());

    // Assert that indexing completed successfully for standardDeviation analysis
    if let Some(ref status) = std_dev_analysis.index_status {
        assert!(
            status.state.contains("Completed") && status.indexed_files == status.total_files,
            "Indexing should have completed successfully for standardDeviation analysis. Index status: {:?}",
            std_dev_analysis.index_status
        );
    }

    let std_dev_hierarchy = std_dev_analysis.call_hierarchy.unwrap();
    info!("standardDeviation callers: {:?}", std_dev_hierarchy.callers);
    info!("standardDeviation callees: {:?}", std_dev_hierarchy.callees);

    // COHERENCE VALIDATION: Check bidirectional relationships

    // 1. Check standardDeviation -> variance relationship
    // standardDeviation's callees should include variance
    assert!(
        std_dev_hierarchy
            .callees
            .iter()
            .any(|c| c.contains("variance")),
        "standardDeviation should call variance"
    );

    // variance's callers should include standardDeviation
    assert!(
        variance_hierarchy
            .callers
            .iter()
            .any(|c| c.contains("standardDeviation")),
        "variance should be called by standardDeviation"
    );

    // 2. Check variance -> mean relationship
    // variance's callees should include mean
    assert!(
        variance_hierarchy
            .callees
            .iter()
            .any(|c| c.contains("mean")),
        "variance should call mean"
    );

    // mean's callers should include variance
    assert!(
        mean_hierarchy
            .callers
            .iter()
            .any(|c| c.contains("variance")),
        "mean should be called by variance"
    );

    // 3. Additional coherence check: verify the call chain
    // standardDeviation(double) -> variance(double) -> mean(double)
    // So mean should have variance as a caller (which we already verified)
    assert!(
        mean_hierarchy
            .callers
            .iter()
            .any(|c| c.contains("variance")),
        "mean should be called by variance (completing the call chain)"
    );

    info!(
        "Call hierarchy coherence validated successfully:\n\
         - standardDeviation -> variance: bidirectional relationship confirmed\n\
         - variance -> mean: bidirectional relationship confirmed\n\
         - standardDeviation -> mean (direct): relationship confirmed"
    );
}