terraphim_mcp_server 1.0.0

Model Context Protocol (MCP) server for Terraphim AI
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
use anyhow::Result;
use regex::Regex;
use rmcp::{
    model::{CallToolRequestParam, ReadResourceRequestParam},
    service::ServiceExt,
    transport::TokioChildProcess,
};
use std::process::Stdio;
use terraphim_config::{ConfigBuilder, Haystack, ServiceType};
use tokio::process::Command;

async fn setup_server_command() -> Result<Command> {
    // Allow CI / build environments to inject a pre-built binary path so tests
    // do not need to spawn a nested cargo build.
    if let Ok(bin) = std::env::var("TERRAPHIM_MCP_SERVER_BIN") {
        let path = std::path::PathBuf::from(bin);
        if path.exists() {
            println!("🚀 Using pre-built server binary at {:?}", path);
            let mut command = Command::new(path);
            command
                .env("RUST_BACKTRACE", "1")
                .env("RUST_LOG", "debug")
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped());
            return Ok(command);
        }
    }

    // Build the server first to ensure the binary is up-to-date
    let mut build = Command::new("cargo");
    build
        .arg("build")
        .arg("--package")
        .arg("terraphim_mcp_server");

    // CI sets CI=true, and terraphim_mcp_server depends on fff-search whose
    // build script requires the zlob feature under CI. The top-level main
    // workflow already runs the workspace tests with zlob enabled, so mirror
    // that feature contract for this nested build as well.
    if std::env::var_os("CI").is_some() {
        build.arg("--features").arg("zlob");
    }

    let build_status = build.status().await?;
    if !build_status.success() {
        return Err(anyhow::anyhow!("Failed to build terraphim_mcp_server"));
    }
    // Determine the path to the compiled binary.
    // When building inside a workspace Cargo will place the binary in the *workspace* target dir,
    // whereas `std::env::current_dir()` inside the test is the **crate** directory
    // (e.g. crates/terraphim_mcp_server). Therefore the binary lives two levels up.
    let crate_dir = std::env::current_dir()?;
    let binary_name = if cfg!(target_os = "windows") {
        "terraphim_mcp_server.exe"
    } else {
        "terraphim_mcp_server"
    };
    // Candidate locations (checked in order).
    let candidate_paths = [
        // 1. Workspace level (../../target/debug/…)
        crate_dir
            .parent()
            .and_then(|p| p.parent())
            .map(|workspace| workspace.join("target").join("debug").join(binary_name)),
        // 2. Crate-local target dir (./target/debug/…)
        Some(crate_dir.join("target").join("debug").join(binary_name)),
    ];
    let binary_path = candidate_paths
        .into_iter()
        .flatten()
        .find(|p| p.exists())
        .ok_or_else(|| anyhow::anyhow!("Built binary not found in expected locations"))?;
    println!("🚀 Using server binary at {:?}", binary_path);
    // Command to run the server binary directly
    let mut command = Command::new(binary_path);
    command
        .env("RUST_BACKTRACE", "1")
        .env("RUST_LOG", "debug")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    Ok(command)
}
fn create_test_config() -> String {
    // Create a test configuration that points to docs/src
    let mut config = ConfigBuilder::new()
        .build_default_server()
        .build()
        .expect("Failed to build test configuration");
    // Update the haystack path to point to docs/src in the project root
    // Since we're running from the workspace root, docs/src should be directly accessible
    let docs_src_path = std::env::current_dir()
        .expect("Failed to get current directory")
        .join("docs/src");
    println!("📁 Using docs/src as haystack: {:?}", docs_src_path);
    // Verify the path exists
    if !docs_src_path.exists() {
        println!(
            "❌ Warning: docs/src path does not exist: {:?}",
            docs_src_path
        );
        // List current directory contents to debug
        if let Ok(entries) =
            std::fs::read_dir(std::env::current_dir().expect("Failed to get current directory"))
        {
            let dirs: Vec<_> = entries
                .filter_map(|entry| entry.ok())
                .filter(|entry| entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false))
                .collect();
            println!(
                "📁 Current directory contents: {:?}",
                dirs.iter().map(|e| e.path()).collect::<Vec<_>>()
            );
        }
        // Try to find docs directory
        let workspace_root = std::env::current_dir().expect("Failed to get current directory");
        let possible_paths = [
            workspace_root.join("docs/src"),
            workspace_root.join("..").join("docs/src"),
            workspace_root.join("..").join("..").join("docs/src"),
        ];
        for (i, path) in possible_paths.iter().enumerate() {
            println!(
                "🔍 Trying path {}: {:?} (exists: {})",
                i,
                path,
                path.exists()
            );
            if path.exists() {
                println!("✅ Found docs/src at: {:?}", path);
                for role in config.roles.values_mut() {
                    role.haystacks = vec![Haystack {
                        location: path.to_string_lossy().to_string(),
                        service: ServiceType::Ripgrep,
                        read_only: false,
                        atomic_server_secret: None,
                        extra_parameters: std::collections::HashMap::new(),

                        fetch_content: false,
                    }];
                }
                break;
            }
        }
    } else {
        println!("✅ docs/src path exists, using it");
        // Update all roles to use docs/src
        for role in config.roles.values_mut() {
            role.haystacks = vec![Haystack {
                location: docs_src_path.to_string_lossy().to_string(),
                service: ServiceType::Ripgrep,
                read_only: false,
                atomic_server_secret: None,
                extra_parameters: std::collections::HashMap::new(),

                fetch_content: false,
            }];
        }
    }
    serde_json::to_string(&config).expect("Failed to serialize config")
}
/// Extract the leading integer from messages like "Found 7 documents matching your query.".
fn extract_found_count(message: &str) -> Option<usize> {
    // lazy static regex unnecessary in test context
    let re = Regex::new(r"Found (\d+) documents?").ok()?;
    re.captures(message)
        .and_then(|cap| cap.get(1))
        .and_then(|m| m.as_str().parse::<usize>().ok())
}
#[tokio::test]
async fn test_mcp_server_integration() -> Result<()> {
    let command = setup_server_command().await?;
    let transport = TokioChildProcess::new(command)?;
    let service = ().serve(transport).await?;
    println!("Connected to server: {:?}", service.peer_info());
    // List available tools
    let tools = service.list_tools(Default::default()).await?;
    println!("Available tools: {:#?}", tools);
    assert!(!tools.tools.is_empty());
    // Update configuration to use test fixtures
    let test_config = create_test_config();
    let config_result = service
        .call_tool(CallToolRequestParam {
            name: "update_config_tool".into(),
            arguments: serde_json::json!({
                "config_str": test_config
            })
            .as_object()
            .cloned(),
        })
        .await?;
    println!("Update config result: {:#?}", config_result);
    assert!(!config_result.is_error.unwrap_or(false));
    // Test search with different queries
    let search_queries = vec![
        ("terraphim", "Search for terraphim"),
        ("machine learning", "Search for machine learning"),
        ("system operator", "Search for system operator"),
        ("neural networks", "Search for neural networks"),
    ];
    for (query, description) in search_queries {
        println!("Testing: {}", description);
        let search_result = service
            .call_tool(CallToolRequestParam {
                name: "search".into(),
                arguments: serde_json::json!({
                    "query": query,
                    "role": "Default",
                    "limit": 5
                })
                .as_object()
                .cloned(),
            })
            .await?;
        println!("Search result for '{}': {:#?}", query, search_result);
        // Check if search was successful (even if no results found)
        assert!(!search_result.is_error.unwrap_or(false));
        // Verify we got a response
        if let Some(content) = search_result.content.first()
            && let Some(text_content) = content.as_text()
        {
            println!("Search response: {}", text_content.text);
            // Ensure the reported count matches number of resource objects returned (text node excluded)
            if let Some(found) = extract_found_count(&text_content.text) {
                assert!(
                    found >= search_result.content.len() - 1,
                    "Reported document count {} is less than returned resources {}",
                    found,
                    search_result.content.len() - 1
                );
            } else {
                panic!("Failed to parse found-count message: {}", text_content.text);
            }
        }
    }
    service.cancel().await?;
    Ok(())
}

#[tokio::test]
async fn test_search_with_different_roles() -> Result<()> {
    let command = setup_server_command().await?;
    let transport = TokioChildProcess::new(command)?;
    let service = ().serve(transport).await?;
    println!("Connected to server: {:?}", service.peer_info());

    // Update configuration to use test fixtures
    let test_config = create_test_config();
    let config_result = service
        .call_tool(CallToolRequestParam {
            name: "update_config_tool".into(),
            arguments: serde_json::json!({
                "config_str": test_config
            })
            .as_object()
            .cloned(),
        })
        .await?;
    println!("Config update result: {:?}", config_result);

    // Test search with different roles
    let role_queries = vec![
        ("Default", "terraphim"),
        ("Engineer", "system operator"),
        ("System Operator", "system operator"),
    ];
    for (role, query) in role_queries {
        println!("Testing search with role: {}", role);
        let search_result = service
            .call_tool(CallToolRequestParam {
                name: "search".into(),
                arguments: serde_json::json!({
                    "query": query,
                    "role": role,
                    "limit": 3
                })
                .as_object()
                .cloned(),
            })
            .await?;
        println!("Search result for role '{}': {:#?}", role, search_result);
        if let Some(content) = search_result.content.first()
            && let Some(text_content) = content.as_text()
        {
            println!("Role '{}' response: {}", role, text_content.text);
            if let Some(found) = extract_found_count(&text_content.text) {
                // For Default role there should be at least one document
                if role == "Default" {
                    assert!(
                        found > 0,
                        "Default role should return at least one document"
                    );
                }
            }
        }
    }
    Ok(())
}

#[tokio::test]
async fn test_resource_uri_mapping() -> Result<()> {
    let command = setup_server_command().await?;
    let transport = TokioChildProcess::new(command)?;
    let service = ().serve(transport).await?;
    println!("Connected to server: {:?}", service.peer_info());

    // Update configuration to use test fixtures
    let test_config = create_test_config();
    let config_result = service
        .call_tool(CallToolRequestParam {
            name: "update_config_tool".into(),
            arguments: serde_json::json!({
                "config_str": test_config
            })
            .as_object()
            .cloned(),
        })
        .await?;
    println!("Config update result: {:?}", config_result);

    // List available resources
    let resources = service.list_resources(Default::default()).await?;
    println!("Available resources: {:#?}", resources);
    // Test reading a specific resource if available
    if let Some(resource) = resources.resources.first() {
        println!("Testing read resource: {}", resource.uri);
        let read_result = service
            .read_resource(ReadResourceRequestParam {
                uri: resource.uri.clone(),
            })
            .await?;
        println!("Read resource result: {:#?}", read_result);
        // Verify we got content
        if let Some(content) = read_result.contents.first() {
            match content {
                rmcp::model::ResourceContents::TextResourceContents { text, .. } => {
                    println!("Resource text content: {}", text);
                    assert!(!text.is_empty());
                }
                rmcp::model::ResourceContents::BlobResourceContents { blob, .. } => {
                    println!("Resource binary content: {} bytes", blob.len());
                    assert!(!blob.is_empty());
                }
            }
        }
    }
    // Test error handling for invalid resource URI
    let invalid_result = service
        .read_resource(ReadResourceRequestParam {
            uri: "invalid://resource/uri".to_string(),
        })
        .await;
    // Should return an error for invalid URI
    assert!(invalid_result.is_err());
    service.cancel().await?;
    Ok(())
}

#[tokio::test]
async fn test_simple_search_with_debug() -> Result<()> {
    let command = setup_server_command().await?;
    let transport = TokioChildProcess::new(command)?;
    let service = ().serve(transport).await?;
    println!("Connected to server: {:?}", service.peer_info());

    // Update configuration to use test fixtures
    let test_config = create_test_config();
    let config_result = service
        .call_tool(CallToolRequestParam {
            name: "update_config_tool".into(),
            arguments: serde_json::json!({
                "config_str": test_config
            })
            .as_object()
            .cloned(),
        })
        .await?;
    println!("Config update result: {:?}", config_result);

    // Test with a simple search term that should definitely match
    let search_terms = vec![
        "Machine Learning", // Should match machine_learning.md
        "Terraphim",        // Should match terraphim.md
        "neural",           // Should match neural_networks.md
        "system",           // Should match System Operator.md
    ];
    for search_term in search_terms {
        println!("Testing search for: '{}'", search_term);
        let search_result = service
            .call_tool(CallToolRequestParam {
                name: "search".into(),
                arguments: serde_json::json!({
                    "query": search_term,
                    "limit": 10
                })
                .as_object()
                .cloned(),
            })
            .await?;
        println!("Search result for '{}': {:#?}", search_term, search_result);
        if let Some(content) = search_result.content.first()
            && let Some(text_content) = content.as_text()
        {
            println!(
                "Search response for '{}': {}",
                search_term, text_content.text
            );
            // If we found documents, let's see what they are
            if text_content.text.contains("Found") && !text_content.text.contains("Found 0") {
                println!(
                    "✅ Found documents for '{}': {}",
                    search_term, text_content.text
                );
            } else {
                println!(
                    "❌ No documents found for '{}': {}",
                    search_term, text_content.text
                );
            }
        }
    }
    service.cancel().await?;
    Ok(())
}

/// Test pagination behaviour of the search tool.
#[tokio::test]
async fn test_search_pagination() -> Result<()> {
    let command = setup_server_command().await?;
    let transport = TokioChildProcess::new(command)?;
    let service = ().serve(transport).await?;

    // Apply test configuration
    let test_config = create_test_config();
    service
        .call_tool(CallToolRequestParam {
            name: "update_config_tool".into(),
            arguments: serde_json::json!({"config_str": test_config})
                .as_object()
                .cloned(),
        })
        .await?;

    // First page. Pass `role` explicitly so the auto-router does not prepend
    // the `[auto-route]` text content -- this test asserts pagination shape,
    // not routing behaviour.
    let first_page = service
        .call_tool(CallToolRequestParam {
            name: "search".into(),
            arguments: serde_json::json!({
                "query": "terraphim",
                "role": "Default",
                "limit": 2
            })
            .as_object()
            .cloned(),
        })
        .await?;
    assert!(!first_page.is_error.unwrap_or(false));
    // Expect at most 3 items (heading + up to 2 resources)
    assert!(first_page.content.len() <= 3);
    let _first_batch_count = first_page
        .content
        .iter()
        .filter(|c| c.as_resource().is_some())
        .count();

    // Second page (skip=2). Same explicit-role short-circuit as above.
    let second_page = service
        .call_tool(CallToolRequestParam {
            name: "search".into(),
            arguments: serde_json::json!({
                "query": "terraphim",
                "role": "Default",
                "limit": 2,
                "skip": 2
            })
            .as_object()
            .cloned(),
        })
        .await?;
    assert!(!second_page.is_error.unwrap_or(false));
    let second_batch_count = second_page
        .content
        .iter()
        .filter(|c| c.as_resource().is_some())
        .count();
    // Ensure we actually paginated (either fewer or different resources)
    assert!(second_batch_count <= 2);
    Ok(())
}

/// Test that invalid pagination parameters are rejected.
#[tokio::test]
async fn test_search_invalid_pagination_params() -> Result<()> {
    let command = setup_server_command().await?;
    let transport = TokioChildProcess::new(command)?;
    let service = ().serve(transport).await?;

    // Negative limit – server may coerce or error; ensure it does not crash.
    let res = service
        .call_tool(CallToolRequestParam {
            name: "search".into(),
            arguments: serde_json::json!({
                "query": "test",
                "limit": -5
            })
            .as_object()
            .cloned(),
        })
        .await?;
    assert!(res.is_error.unwrap_or(false) || !res.content.is_empty());

    // Excessive limit should error
    let res2 = service
        .call_tool(CallToolRequestParam {
            name: "search".into(),
            arguments: serde_json::json!({
                "query": "test",
                "limit": 10_000
            })
            .as_object()
            .cloned(),
        })
        .await?;
    assert!(res2.is_error.unwrap_or(false) || !res2.content.is_empty());
    Ok(())
}

/// Perform search then fetch the same resource via read_resource and compare contents.
#[tokio::test]
async fn test_search_read_resource_round_trip() -> Result<()> {
    let command = setup_server_command().await?;
    let transport = TokioChildProcess::new(command)?;
    let service = ().serve(transport).await?;

    // Apply config
    let test_config = create_test_config();
    service
        .call_tool(CallToolRequestParam {
            name: "update_config_tool".into(),
            arguments: serde_json::json!({"config_str": test_config})
                .as_object()
                .cloned(),
        })
        .await?;

    // Search
    let search_res = service
        .call_tool(CallToolRequestParam {
            name: "search".into(),
            arguments: serde_json::json!({
                "query": "terraphim",
                "limit": 1
            })
            .as_object()
            .cloned(),
        })
        .await?;
    assert!(!search_res.is_error.unwrap_or(false));
    let resource = search_res
        .content
        .iter()
        .find_map(|c| c.as_resource())
        .expect("Expected at least one resource");
    let _embedded_text = if let rmcp::model::ResourceContents::TextResourceContents {
        text, ..
    } = &resource.resource
    {
        text.clone()
    } else {
        panic!("Unexpected resource content type");
    };
    // Read resource requires a URI obtained from list_resources; fallback to first available list entry
    let list_result = service.list_resources(Default::default()).await?;
    if list_result.resources.is_empty() {
        println!("No resources listed; skipping read_resource round trip test");
        return Ok(());
    }
    let first_uri = list_result.resources[0].uri.clone();
    let read_res = service
        .read_resource(ReadResourceRequestParam { uri: first_uri })
        .await?;
    let read_text = match read_res
        .contents
        .first()
        .expect("read_resource returned empty content")
    {
        rmcp::model::ResourceContents::TextResourceContents { text, .. } => text.clone(),
        _ => "".into(),
    };
    assert!(!read_text.is_empty());

    Ok(())
}