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
mod support;

use anyhow::Result;
use rmcp::{model::CallToolRequestParam, service::ServiceExt, transport::TokioChildProcess};
use serde_json::json;
use std::process::Stdio;
use tokio::process::Command;

/// Test extract_paragraphs_from_automata with Terraphim Engineer role and real content
#[tokio::test]
async fn test_extract_paragraphs_with_terraphim_engineer() -> Result<()> {
    println!("📄 Testing extract_paragraphs_from_automata with Terraphim Engineer role");

    let mut cmd = Command::new(support::mcp_server_binary()?);
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .arg("--profile")
        .arg("desktop"); // Use desktop profile for Terraphim Engineer role

    let transport = TokioChildProcess::new(cmd)?;
    let service = ().serve(transport).await?;

    println!("🔗 Connected to MCP server with Terraphim Engineer profile");

    // Configure the server to use Terraphim Engineer role with proper KG setup
    println!("⚙️ Configuring Terraphim Engineer role...");
    let current_dir = std::env::current_dir()?;
    let workspace_root = current_dir
        .parent()
        .and_then(|p| p.parent())
        .ok_or_else(|| anyhow::anyhow!("Cannot find workspace root"))?;
    let kg_path = workspace_root.join("docs/src/kg");

    let terraphim_config = json!({
        "roles": {
            "Terraphim Engineer": {
                "shortname": "terraphim_engineer",
                "name": "Terraphim Engineer",
                "relevance_function": "TerraphimGraph",
                "theme": "lumen",
                "terraphim_it": true,
                "kg": {
                    "automata_path": null,
                    "knowledge_graph_local": {
                        "input_type": "markdown",
                        "path": kg_path.to_string_lossy().to_string()
                    },
                    "public": true,
                    "publish": true
                },
                "haystacks": [{
                    "location": workspace_root.join("docs/src").to_string_lossy().to_string(),
                    "service": "Ripgrep",
                    "read_only": true,
                    "atomic_server_secret": null,
                    "extra_parameters": {}
                }],
                "extra": {}
            }
        },
        "selected_role": "Terraphim Engineer",
        "default_role": "Terraphim Engineer",
        "global_shortcut": "Ctrl+Space"
    });

    let config_result = service
        .call_tool(CallToolRequestParam {
            name: "update_config_tool".into(),
            arguments: json!({
                "config_str": terraphim_config.to_string()
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ Configuration result: {:?}", config_result.content);

    // Build autocomplete index for Terraphim Engineer role
    println!("🔧 Building autocomplete index for Terraphim Engineer role...");
    let build_index_result = service
        .call_tool(CallToolRequestParam {
            name: "build_autocomplete_index".into(),
            arguments: json!({
                "role": "Terraphim Engineer"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ Build index result: {:?}", build_index_result.content);

    // Test with realistic content that contains terms from our knowledge graph
    let test_text = r#"
This document discusses the Terraphim Graph system and its components.

The haystack provides data sources for indexing. The haystack can be configured
as a service that acts as a datasource for the knowledge graph system.

Graph embeddings are used by the Terraphim Graph scorer to rank terms based on
their connections. The graph embeddings technique allows for knowledge graph
based embeddings that improve search relevance.

The service layer coordinates between different components. The provider
implements the middleware functionality that connects haystacks to the
knowledge graph system.
"#;

    // Test 1: Extract paragraphs containing 'haystack' term
    println!("🔍 Testing paragraph extraction for 'haystack' term...");
    let haystack_result = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": test_text,
                "terms": ["haystack"]
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Haystack extraction result: {:?}",
        haystack_result.content
    );

    // Test 2: Extract paragraphs containing 'graph embeddings' term
    println!("🔍 Testing paragraph extraction for 'graph embeddings' term...");
    let graph_result = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": test_text,
                "terms": ["graph embeddings"]
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Graph embeddings extraction result: {:?}",
        graph_result.content
    );

    // Test 3: Extract paragraphs with multiple terms
    println!("🔍 Testing paragraph extraction for multiple terms...");
    let multiple_result = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": test_text,
                "terms": ["service", "provider", "middleware"]
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Multiple terms extraction result: {:?}",
        multiple_result.content
    );

    // Test 4: Test with content from actual KG files
    let kg_content = r#"
# Terraphim-graph

## Terraphim Graph scorer

Terraphim Graph (scorer) is using unique graph embeddings, where the rank of the term is defined by number of synonyms connected to the concept.

synonyms:: graph embeddings, graph, knowledge graph based embeddings

Now we will have a concept "Terraphim Graph Scorer" with synonyms "graph embeddings".

# Haystack
synonyms:: datasource, service, agent

The haystack provides access to various data sources and acts as an agent for data retrieval.

# Terraphim Service
synonyms:: provider, middleware

The service layer acts as a provider and middleware between components.
"#;

    println!("🔍 Testing paragraph extraction from real KG content...");
    let kg_result = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": kg_content,
                "terms": ["terraphim", "synonyms", "knowledge graph"]
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ KG content extraction result: {:?}", kg_result.content);

    println!("🎉 All extract_paragraphs_from_automata tests completed!");
    Ok(())
}

/// Test is_all_terms_connected_by_path with knowledge graph connections
#[tokio::test]
async fn test_terms_connectivity_with_knowledge_graph() -> Result<()> {
    println!("🔗 Testing is_all_terms_connected_by_path with knowledge graph");

    let mut cmd = Command::new(support::mcp_server_binary()?);
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .arg("--profile")
        .arg("desktop"); // Use desktop profile for Terraphim Engineer role

    let transport = TokioChildProcess::new(cmd)?;
    let service = ().serve(transport).await?;

    println!("🔗 Connected to MCP server with Terraphim Engineer profile");

    // Test 1: Check if terms that should be connected via synonyms are connected
    // API expects "text" containing terms to be extracted and checked for connectivity
    println!("🔍 Testing connectivity of known synonym terms...");
    let synonym_connectivity = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "The haystack datasource provides a service interface"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Synonym connectivity result: {:?}",
        synonym_connectivity.content
    );

    // Test 2: Check connectivity of graph embedding related terms
    println!("🔍 Testing connectivity of graph embedding terms...");
    let graph_connectivity = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "The graph uses graph embeddings and knowledge graph based embeddings"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Graph embedding connectivity result: {:?}",
        graph_connectivity.content
    );

    // Test 3: Check connectivity of service-related terms
    println!("🔍 Testing connectivity of service terms...");
    let service_connectivity = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "The service uses a provider and middleware layer"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Service connectivity result: {:?}",
        service_connectivity.content
    );

    // Test 4: Test with text containing no known terms (should handle gracefully)
    println!("🔍 Testing text with no known terms...");
    let unconnected_test = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "completely random unrelated words that are not in the knowledge graph"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ No known terms result: {:?}", unconnected_test.content);

    // Test 5: Test single term (should always be connected to itself)
    println!("🔍 Testing single term connectivity...");
    let single_term = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "haystack is a useful concept"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Single term connectivity result: {:?}",
        single_term.content
    );

    // Test 6: Test with role parameter
    println!("🔍 Testing with explicit role...");
    let role_connectivity = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "The haystack service uses automata",
                "role": "Terraphim Engineer"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Role-specific connectivity result: {:?}",
        role_connectivity.content
    );

    println!("🎉 All is_all_terms_connected_by_path tests completed!");
    Ok(())
}

/// Comprehensive test that validates both functions work together
#[tokio::test]
async fn test_advanced_automata_integration() -> Result<()> {
    println!("🚀 Testing advanced automata functions integration");

    let mut cmd = Command::new(support::mcp_server_binary()?);
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .arg("--profile")
        .arg("desktop");

    let transport = TokioChildProcess::new(cmd)?;
    let service = ().serve(transport).await?;

    println!("🔗 Connected to MCP server for integration testing");

    // Scenario: Extract paragraphs and then check if found terms are connected
    let document_text = r#"
Introduction

This document explains how the Terraphim system works with various components.

Architecture Overview

The haystack component serves as a datasource for the system. It works closely
with the service layer to provide data access. The haystack can be configured
as different types of agents depending on the data source.

Graph Processing

The Terraphim Graph uses sophisticated graph embeddings for ranking. These
graph embeddings are a type of knowledge graph based embeddings that create
connections between related concepts.

Service Layer

The service layer acts as both a provider and middleware. The provider
functionality handles data requests while the middleware coordinates between
different system components.
"#;

    // Step 1: Extract paragraphs containing service-related terms
    println!("📄 Step 1: Extracting paragraphs with service terms...");
    let paragraphs = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": document_text,
                "terms": ["service", "provider", "middleware"]
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ Extracted paragraphs: {:?}", paragraphs.content);

    // Step 2: Check if these terms are connected in the knowledge graph
    // The API expects "text" parameter - terms are extracted from text automatically
    println!("🔗 Step 2: Checking connectivity of service terms...");
    let connectivity = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "The service uses a provider and middleware architecture"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ Connectivity result: {:?}", connectivity.content);

    // Step 3: Test with haystack-related terms
    println!("📄 Step 3: Testing haystack term extraction and connectivity...");
    let haystack_paragraphs = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": document_text
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ Haystack paragraphs: {:?}", haystack_paragraphs.content);

    let haystack_connectivity = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "The haystack datasource connects to the agent"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!(
        "✅ Haystack connectivity: {:?}",
        haystack_connectivity.content
    );

    // Step 4: Test cross-domain connectivity (should likely be false)
    println!("🔗 Step 4: Testing cross-domain connectivity...");
    let cross_domain = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "The haystack uses graph embeddings and service layer"
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ Cross-domain connectivity: {:?}", cross_domain.content);

    println!("🎉 Advanced automata integration test completed successfully!");
    Ok(())
}

/// Test error handling and edge cases
#[tokio::test]
async fn test_advanced_automata_edge_cases() -> Result<()> {
    println!("⚠️ Testing edge cases for advanced automata functions");

    let mut cmd = Command::new(support::mcp_server_binary()?);
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .arg("--profile")
        .arg("desktop");

    let transport = TokioChildProcess::new(cmd)?;
    let service = ().serve(transport).await?;

    // Test 1: Empty text
    println!("🔍 Testing empty text...");
    let empty_result = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": "",
                "terms": ["haystack"]
            })
            .as_object()
            .cloned(),
        })
        .await;

    match empty_result {
        Ok(result) => println!("✅ Empty text handled: {:?}", result.content),
        Err(e) => println!("⚠️ Empty text error (expected): {}", e),
    }

    // Test 2: Empty terms array
    println!("🔍 Testing empty terms array...");
    let empty_terms = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": "Some text here",
                "terms": []
            })
            .as_object()
            .cloned(),
        })
        .await;

    match empty_terms {
        Ok(result) => println!("✅ Empty terms handled: {:?}", result.content),
        Err(e) => println!("⚠️ Empty terms error (expected): {}", e),
    }

    // Test 3: Connectivity with text that has no known terms
    println!("🔗 Testing connectivity with text containing no known terms...");
    let empty_connectivity = service
        .call_tool(CallToolRequestParam {
            name: "is_all_terms_connected_by_path".into(),
            arguments: json!({
                "text": "This text contains no terms from the knowledge graph"
            })
            .as_object()
            .cloned(),
        })
        .await;

    match empty_connectivity {
        Ok(result) => println!("✅ No-terms connectivity handled: {:?}", result.content),
        Err(e) => println!("⚠️ No-terms connectivity error (expected): {}", e),
    }

    // Test 4: Very long text
    println!("📄 Testing very long text...");
    let long_text =
        "This is a test paragraph. ".repeat(100) + "The haystack provides excellent service.";
    let long_result = service
        .call_tool(CallToolRequestParam {
            name: "extract_paragraphs_from_automata".into(),
            arguments: json!({
                "text": long_text
            })
            .as_object()
            .cloned(),
        })
        .await?;

    println!("✅ Long text handled: {:?}", long_result.content);

    println!("🎉 Edge case testing completed!");
    Ok(())
}