Repository navigation
Expand file tree
/
Copy pathgraph_tool_executor.rs
More file actions
1056 lines (919 loc) · 36.1 KB
/
Copy pathgraph_tool_executor.rs
File metadata and controls
1056 lines (919 loc) · 36.1 KB
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ABOUTME: LLM tool executor for SurrealDB graph analysis functions
// ABOUTME: Executes graph analysis tools by calling Rust SDK wrappers with validated parameters
use codegraph_core::config_manager::CodeGraphConfig;
use codegraph_graph::GraphFunctions;
use codegraph_mcp_core::debug_logger::DebugLogger;
use codegraph_mcp_core::error::{McpError, Result};
use codegraph_vector::EmbeddingGenerator;
use codegraph_vector::reranking::{RerankDocument, Reranker, factory::create_reranker};
use lru::LruCache;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::{Value as JsonValue, json};
use std::num::NonZeroUsize;
use std::sync::Arc;
use tracing::{debug, info, warn};
const TOOL_PROGRESS_LOG_TARGET: &str = "codegraph::mcp::tools";
use crate::graph_tool_schemas::GraphToolSchemas;
/// Statistics about LRU cache performance
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CacheStats {
/// Number of cache hits (successful lookups)
pub hits: u64,
/// Number of cache misses (lookups that required SurrealDB call)
pub misses: u64,
/// Number of entries evicted due to LRU policy
pub evictions: u64,
/// Current number of entries in cache
pub current_size: usize,
/// Maximum cache size (capacity)
pub max_size: usize,
}
impl CacheStats {
/// Calculate cache hit rate as percentage
pub fn hit_rate(&self) -> f64 {
let total = self.hits + self.misses;
if total == 0 {
0.0
} else {
(self.hits as f64 / total as f64) * 100.0
}
}
}
/// Executor for graph analysis tools
/// Receives tool calls from LLM and executes appropriate SurrealDB functions
pub struct GraphToolExecutor {
graph_functions: Arc<GraphFunctions>,
/// Configuration for embedding and reranking
config: Arc<CodeGraphConfig>,
/// Shared embedding generator (created once, reused for all queries)
embedding_generator: Arc<EmbeddingGenerator>,
/// LRU cache for tool results (function_name + params → result)
cache: Arc<Mutex<LruCache<String, JsonValue>>>,
/// Cache statistics for observability
cache_stats: Arc<Mutex<CacheStats>>,
/// Whether caching is enabled
cache_enabled: bool,
/// Reranker for semantic search result refinement
reranker: Option<Arc<dyn Reranker>>,
/// Maximum result size in bytes (derived from LLM context window)
/// Prevents sending oversized results that would exceed model limits
max_result_bytes: usize,
}
/// Default max result bytes when context window not specified (~200KB)
const DEFAULT_MAX_RESULT_BYTES: usize = 200_000;
/// Ceiling for one tool result regardless of the configured context window. A window of a
/// million tokens does not make a multi-megabyte tool result useful to the model.
const MAX_RESULT_BYTES_CEILING: usize = 200_000;
/// Longest `content` a result row carries. Rows keep their file path and line range, so the
/// client can read the rest; whole documents and impl blocks otherwise dominate the context.
const DEFAULT_CONTENT_SNIPPET_CHARS: usize = 2_000;
/// `CODEGRAPH_TOOL_CONTENT_CHARS` overrides the snippet length; 0 disables shortening.
fn content_snippet_chars() -> usize {
std::env::var("CODEGRAPH_TOOL_CONTENT_CHARS")
.ok()
.and_then(|v| v.trim().parse().ok())
.unwrap_or(DEFAULT_CONTENT_SNIPPET_CHARS)
}
/// Shorten long `content` strings anywhere in a tool result to a leading snippet that ends
/// on a line boundary where possible, recording the original length next to it.
fn shorten_content(value: &mut JsonValue, max_chars: usize) {
if max_chars == 0 {
return;
}
match value {
JsonValue::Array(items) => items
.iter_mut()
.for_each(|item| shorten_content(item, max_chars)),
JsonValue::Object(map) => {
let original_chars = match map.get("content") {
Some(JsonValue::String(content)) if content.chars().count() > max_chars => {
Some(content.chars().count())
}
_ => None,
};
if let Some(original_chars) = original_chars {
if let Some(JsonValue::String(content)) = map.get_mut("content") {
let cut = content
.char_indices()
.nth(max_chars)
.map_or(content.len(), |(index, _)| index);
// Prefer ending on a complete line when that keeps most of the snippet.
let cut = content[..cut]
.rfind('\n')
.filter(|line_end| *line_end >= cut / 2)
.unwrap_or(cut);
content.truncate(cut);
}
map.insert("content_truncated".to_string(), JsonValue::Bool(true));
map.insert("content_chars".to_string(), json!(original_chars));
}
map.iter_mut()
.filter(|(key, _)| key.as_str() != "content")
.for_each(|(_, child)| shorten_content(child, max_chars));
}
_ => {}
}
}
impl GraphToolExecutor {
/// Create a new tool executor with shared EmbeddingGenerator
/// Derives max result size from the agent's context window (environment, then
/// `[llm] context_window` in the config file, then the default)
pub fn new(
graph_functions: Arc<GraphFunctions>,
config: Arc<CodeGraphConfig>,
embedding_generator: Arc<EmbeddingGenerator>,
) -> Self {
let context_window = codegraph_core::config_manager::ConfigManager::agent_context_window();
Self::with_context_window(graph_functions, config, embedding_generator, context_window)
}
/// Create a new tool executor with explicit context window for result size limiting
/// max_result_bytes = context_window * 2 (about half the window at 4 bytes/token), capped at
/// `MAX_RESULT_BYTES_CEILING`
pub fn with_context_window(
graph_functions: Arc<GraphFunctions>,
config: Arc<CodeGraphConfig>,
embedding_generator: Arc<EmbeddingGenerator>,
context_window: usize,
) -> Self {
// Calculate max result bytes: use ~50% of context window, assuming ~4 chars per token
// This leaves room for system prompt, conversation history, and response
let max_result_bytes = context_window
.saturating_mul(2)
.min(MAX_RESULT_BYTES_CEILING);
Self::with_limits(
graph_functions,
config,
embedding_generator,
true,
100,
max_result_bytes,
)
}
/// Create a new tool executor with custom cache and result size configuration
pub fn with_limits(
graph_functions: Arc<GraphFunctions>,
config: Arc<CodeGraphConfig>,
embedding_generator: Arc<EmbeddingGenerator>,
cache_enabled: bool,
cache_size: usize,
max_result_bytes: usize,
) -> Self {
let capacity = NonZeroUsize::new(cache_size).unwrap_or(NonZeroUsize::new(100).unwrap());
let cache = Arc::new(Mutex::new(LruCache::new(capacity)));
let cache_stats = Arc::new(Mutex::new(CacheStats {
hits: 0,
misses: 0,
evictions: 0,
current_size: 0,
max_size: cache_size,
}));
// Initialize reranker from config
let reranker = match create_reranker(&config.rerank) {
Ok(reranker) => reranker,
Err(error) => {
warn!("Configured reranker could not initialize; reranking disabled: {error:#}");
None
}
};
if let Some(ref reranker) = reranker {
info!(
"Reranker initialized: {} ({})",
reranker.model_name(),
reranker.provider_name()
);
}
info!(
"GraphToolExecutor initialized with max_result_bytes: {} ({:.1}MB)",
max_result_bytes,
max_result_bytes as f64 / 1_000_000.0
);
Self {
graph_functions,
config,
embedding_generator,
cache,
cache_stats,
cache_enabled,
reranker,
max_result_bytes,
}
}
/// Create a new tool executor with custom cache configuration (legacy compatibility)
pub fn with_cache(
graph_functions: Arc<GraphFunctions>,
config: Arc<CodeGraphConfig>,
embedding_generator: Arc<EmbeddingGenerator>,
cache_enabled: bool,
cache_size: usize,
) -> Self {
Self::with_limits(
graph_functions,
config,
embedding_generator,
cache_enabled,
cache_size,
DEFAULT_MAX_RESULT_BYTES,
)
}
/// Get current cache statistics
pub fn cache_stats(&self) -> CacheStats {
self.cache_stats.lock().clone()
}
/// Expose underlying graph functions for read-only summaries
pub fn graph_functions(&self) -> Arc<GraphFunctions> {
self.graph_functions.clone()
}
/// Clear the cache and reset statistics
pub fn clear_cache(&self) {
let mut cache = self.cache.lock();
cache.clear();
let mut stats = self.cache_stats.lock();
stats.hits = 0;
stats.misses = 0;
stats.evictions = 0;
stats.current_size = 0;
}
/// Truncate result if it exceeds max_result_bytes to prevent context window overflow
/// Returns truncated result with warning metadata if truncation occurred
fn truncate_if_oversized(&self, tool_name: &str, result: JsonValue) -> JsonValue {
let serialized = result.to_string();
let result_bytes = serialized.len();
if result_bytes <= self.max_result_bytes {
return result;
}
// Result is oversized - need to truncate
let overflow_ratio = result_bytes as f64 / self.max_result_bytes as f64;
tracing::warn!(
tool = tool_name,
result_bytes = result_bytes,
max_bytes = self.max_result_bytes,
overflow_ratio = format!("{:.1}x", overflow_ratio),
"Tool result exceeds max_result_bytes limit, truncating"
);
// Strategy: Try to truncate the "result" field if it's an array
if let Some(result_array) = result.get("result").and_then(|r| r.as_array()) {
// Calculate how many items we can keep
let item_count = result_array.len();
if item_count == 0 {
return result;
}
// Estimate bytes per item (rough average)
let bytes_per_item = result_bytes / item_count;
let max_items = self.max_result_bytes / bytes_per_item.max(1);
let keep_items = max_items.min(item_count).max(1); // Keep at least 1
// Create truncated result
let truncated_array: Vec<JsonValue> =
result_array.iter().take(keep_items).cloned().collect();
let truncated_count = item_count - keep_items;
tracing::info!(
tool = tool_name,
original_items = item_count,
kept_items = keep_items,
truncated_items = truncated_count,
"Truncated result array to fit context window"
);
// Reconstruct the result with truncation metadata
let mut truncated_result = result.clone();
if let Some(obj) = truncated_result.as_object_mut() {
obj.insert("result".to_string(), JsonValue::Array(truncated_array));
obj.insert(
"_truncated".to_string(),
json!({
"original_items": item_count,
"kept_items": keep_items,
"truncated_items": truncated_count,
"reason": "Result exceeded context window limit",
"max_bytes": self.max_result_bytes
}),
);
}
return truncated_result;
}
// Fallback: If we can't smart-truncate, just return with a warning
// This shouldn't happen often since most results are arrays
tracing::error!(
tool = tool_name,
result_bytes = result_bytes,
"Cannot truncate non-array result, returning as-is (may cause context overflow)"
);
result
}
/// Generate a cache key from project, tool name, and parameters
fn cache_key(project_id: &str, tool_name: &str, parameters: &JsonValue) -> String {
// Create deterministic key from project + function name + serialized params
format!("{}:{}:{}", project_id, tool_name, parameters.to_string())
}
/// Execute a tool call from LLM
///
/// # Arguments
/// * `tool_name` - Name of the tool to execute
/// * `parameters` - JSON parameters for the tool
///
/// # Returns
/// JSON result from the tool execution
pub async fn execute(&self, tool_name: &str, parameters: JsonValue) -> Result<JsonValue> {
log_tool_call_start(tool_name, ¶meters);
let exec_result: Result<JsonValue> = async {
// Validate tool exists
let _schema = GraphToolSchemas::get_by_name(tool_name)
.ok_or_else(|| McpError::Protocol(format!("Unknown tool: {}", tool_name)))?;
let project_id = self.graph_functions.project_id();
// Check cache if enabled
if self.cache_enabled {
let cache_key = Self::cache_key(project_id, tool_name, ¶meters);
// Try cache lookup
{
let mut cache = self.cache.lock();
if let Some(cached_result) = cache.get(&cache_key) {
// Cache hit
let mut stats = self.cache_stats.lock();
stats.hits += 1;
debug!("Cache hit for {}: {}", tool_name, cache_key);
let cached = cached_result.clone();
log_tool_call_finish(tool_name, &cached);
return Ok(cached);
}
}
// Cache miss - record it
{
let mut stats = self.cache_stats.lock();
stats.misses += 1;
}
debug!("Cache miss for {}: {}", tool_name, cache_key);
}
// Execute based on tool name
let result = match tool_name {
"get_transitive_dependencies" => {
self.execute_get_transitive_dependencies(parameters.clone())
.await?
}
"detect_circular_dependencies" => {
self.execute_detect_circular_dependencies(parameters.clone())
.await?
}
"trace_call_chain" => self.execute_trace_call_chain(parameters.clone()).await?,
"calculate_coupling_metrics" => {
self.execute_calculate_coupling_metrics(parameters.clone())
.await?
}
"get_hub_nodes" => self.execute_get_hub_nodes(parameters.clone()).await?,
"get_reverse_dependencies" => {
self.execute_get_reverse_dependencies(parameters.clone())
.await?
}
"semantic_code_search" => {
self.execute_semantic_code_search(parameters.clone())
.await?
}
"find_complexity_hotspots" => {
self.execute_find_complexity_hotspots(parameters.clone())
.await?
}
_ => {
return Err(
McpError::Protocol(format!("Tool not implemented: {}", tool_name)).into(),
);
}
};
// Shape the result for a model: content snippets first, then the size limit.
let mut result = result;
shorten_content(&mut result, content_snippet_chars());
let result = self.truncate_if_oversized(tool_name, result);
// Cache the result if enabled
if self.cache_enabled {
let cache_key = Self::cache_key(project_id, tool_name, ¶meters);
let mut cache = self.cache.lock();
let was_evicted = cache.len() >= cache.cap().get();
cache.put(cache_key, result.clone());
// Update stats
let mut stats = self.cache_stats.lock();
if was_evicted {
stats.evictions += 1;
}
stats.current_size = cache.len();
}
Ok(result)
}
.await;
match exec_result {
Ok(result) => {
log_tool_call_finish(tool_name, &result);
Ok(result)
}
Err(err) => {
warn!(
target: TOOL_PROGRESS_LOG_TARGET,
tool = tool_name,
parameters = %parameters,
error = %err,
"Tool call failed"
);
DebugLogger::log_tool_error(tool_name, ¶meters, &format!("{}", err));
Err(err)
}
}
}
/// Execute get_transitive_dependencies
async fn execute_get_transitive_dependencies(&self, params: JsonValue) -> Result<JsonValue> {
let node_id = params["node_id"]
.as_str()
.ok_or_else(|| McpError::Protocol("Missing node_id".to_string()))?;
// Default to "Calls" if edge_type not provided (for LATS compatibility)
let edge_type = params["edge_type"].as_str().unwrap_or("Calls");
let depth = params["depth"].as_i64().unwrap_or(3) as i32;
let result = self
.graph_functions
.get_transitive_dependencies(node_id, edge_type, depth)
.await
.map_err(|e| {
McpError::Protocol(format!("get_transitive_dependencies failed: {}", e))
})?;
Ok(json!({
"tool": "get_transitive_dependencies",
"parameters": {
"node_id": node_id,
"edge_type": edge_type,
"depth": depth
},
"result": result
}))
}
/// Execute detect_circular_dependencies
async fn execute_detect_circular_dependencies(&self, params: JsonValue) -> Result<JsonValue> {
let edge_type = params["edge_type"]
.as_str()
.ok_or_else(|| McpError::Protocol("Missing edge_type".to_string()))?;
let result = self
.graph_functions
.detect_circular_dependencies(edge_type)
.await
.map_err(|e| {
McpError::Protocol(format!("detect_circular_dependencies failed: {}", e))
})?;
Ok(json!({
"tool": "detect_circular_dependencies",
"parameters": {
"edge_type": edge_type
},
"result": result
}))
}
/// Execute trace_call_chain
async fn execute_trace_call_chain(&self, params: JsonValue) -> Result<JsonValue> {
// Accept both "from_node" (canonical) and "node_id" (common pattern) for compatibility
let from_node = params["from_node"]
.as_str()
.or_else(|| params["node_id"].as_str())
.ok_or_else(|| McpError::Protocol("Missing from_node or node_id".to_string()))?;
let max_depth = params["max_depth"].as_i64().unwrap_or(5) as i32;
let result = self
.graph_functions
.trace_call_chain(from_node, max_depth)
.await
.map_err(|e| McpError::Protocol(format!("trace_call_chain failed: {}", e)))?;
Ok(json!({
"tool": "trace_call_chain",
"parameters": {
"from_node": from_node,
"max_depth": max_depth
},
"result": result
}))
}
/// Execute calculate_coupling_metrics
async fn execute_calculate_coupling_metrics(&self, params: JsonValue) -> Result<JsonValue> {
let node_id = params["node_id"]
.as_str()
.ok_or_else(|| McpError::Protocol("Missing node_id".to_string()))?;
// Optional project_id override to reduce mismatches between indexing and runtime
let gf = if let Some(project_id) = params["project_id"].as_str() {
self.graph_functions.with_project_id(project_id)
} else {
(*self.graph_functions).clone()
};
let result = gf
.calculate_coupling_metrics(node_id)
.await
.map_err(|e| McpError::Protocol(format!("calculate_coupling_metrics failed: {}", e)))?;
Ok(json!({
"tool": "calculate_coupling_metrics",
"parameters": {
"node_id": node_id
},
"result": result
}))
}
/// Execute get_hub_nodes
async fn execute_get_hub_nodes(&self, params: JsonValue) -> Result<JsonValue> {
let min_degree = params["min_degree"].as_i64().unwrap_or(5) as i32;
let result = self
.graph_functions
.get_hub_nodes(min_degree)
.await
.map_err(|e| McpError::Protocol(format!("get_hub_nodes failed: {}", e)))?;
Ok(json!({
"tool": "get_hub_nodes",
"parameters": {
"min_degree": min_degree
},
"result": result
}))
}
/// Execute get_reverse_dependencies
async fn execute_get_reverse_dependencies(&self, params: JsonValue) -> Result<JsonValue> {
let node_id = params["node_id"]
.as_str()
.ok_or_else(|| McpError::Protocol("Missing node_id".to_string()))?;
// Default to "Calls" if edge_type not provided (for LATS compatibility)
let edge_type = params["edge_type"].as_str().unwrap_or("Calls");
let depth = params["depth"].as_i64().unwrap_or(3) as i32;
let result = self
.graph_functions
.get_reverse_dependencies(node_id, edge_type, depth)
.await
.map_err(|e| McpError::Protocol(format!("get_reverse_dependencies failed: {}", e)))?;
Ok(json!({
"tool": "get_reverse_dependencies",
"parameters": {
"node_id": node_id,
"edge_type": edge_type,
"depth": depth
},
"result": result
}))
}
/// Execute semantic code search with HNSW, full-text, and graph enrichment
/// Accepts natural language queries for comprehensive semantic search
async fn execute_semantic_code_search(&self, params: JsonValue) -> Result<JsonValue> {
let query_text = params["query"]
.as_str()
.ok_or_else(|| McpError::Protocol("Missing query".to_string()))?;
let limit = params["limit"].as_i64().unwrap_or(10) as usize;
let threshold = params["threshold"]
.as_f64()
.or_else(|| {
std::env::var("CODEGRAPH_SEMSEARCH_THRESHOLD")
.ok()?
.parse::<f64>()
.ok()
})
.map(|v| v.clamp(0.0, 1.0))
.unwrap_or(0.6);
// Step 1: Generate embedding using shared EmbeddingGenerator
let query_embedding = self
.embedding_generator
.generate_text_embedding(query_text)
.await
.map_err(|e| McpError::Protocol(format!("Embedding generation failed: {}", e)))?;
// Step 2: Get embedding dimension from shared generator (auto-detected)
let dimension = self.embedding_generator.dimension();
// Step 3: Call semantic search function with graph enrichment (always enabled)
let include_graph_context = true; // Always enabled per requirements
let candidates = self
.graph_functions
.semantic_search_with_context(
query_text,
&query_embedding,
dimension,
limit,
threshold as f32,
include_graph_context,
)
.await
.map_err(|e| {
McpError::Protocol(format!("semantic_search_with_context failed: {}", e))
})?;
// Step 4: Apply reranking if configured (Jina OR LM Studio)
let final_results = self.apply_reranking(query_text, candidates).await?;
Ok(json!({
"tool": "semantic_code_search",
"parameters": {
"query": query_text,
"limit": limit,
"dimension": dimension,
"threshold": threshold
},
"result": final_results
}))
}
/// Execute find_complexity_hotspots - find functions with high complexity and coupling
async fn execute_find_complexity_hotspots(&self, params: JsonValue) -> Result<JsonValue> {
let min_complexity = params["min_complexity"].as_f64().unwrap_or(5.0) as f32;
let limit = params["limit"].as_i64().unwrap_or(20) as i32;
let result = self
.graph_functions
.get_complexity_hotspots(min_complexity, limit)
.await
.map_err(|e| McpError::Protocol(format!("find_complexity_hotspots failed: {}", e)))?;
Ok(json!({
"tool": "find_complexity_hotspots",
"parameters": {
"min_complexity": min_complexity,
"limit": limit
},
"result": result
}))
}
/// Apply reranking if configured using text-based reranking system
async fn apply_reranking(
&self,
query: &str,
candidates: Vec<serde_json::Value>,
) -> Result<Vec<serde_json::Value>> {
if let Some(ref reranker) = self.reranker {
let top_n = self.config.rerank.top_n;
// Convert candidates to RerankDocuments
let documents: Vec<RerankDocument> = candidates
.iter()
.enumerate()
.map(|(idx, candidate)| RerankDocument {
id: idx.to_string(),
text: Self::extract_text_from_candidate(candidate),
metadata: Some(candidate.clone()),
})
.collect();
// Rerank using the configured provider
let results = reranker
.rerank(query, documents, top_n)
.await
.map_err(|e| McpError::Protocol(format!("Reranking failed: {}", e)))?;
// Convert back to original format
let reranked: Vec<serde_json::Value> =
results.into_iter().filter_map(|r| r.metadata).collect();
Ok(reranked)
} else {
// No reranking configured
Ok(candidates)
}
}
/// Extract text content from a candidate for reranking
fn extract_text_from_candidate(candidate: &serde_json::Value) -> String {
let mut text_parts = Vec::new();
if let Some(name) = candidate.get("name").and_then(|v| v.as_str()) {
text_parts.push(name.to_string());
}
if let Some(content) = candidate.get("content").and_then(|v| v.as_str()) {
text_parts.push(content.to_string());
}
if let Some(file_path) = candidate.get("file_path").and_then(|v| v.as_str()) {
text_parts.push(format!("File: {}", file_path));
}
text_parts.join(" ")
}
/// Get all available tool schemas for registration
pub fn get_tool_schemas() -> Vec<crate::ToolSchema> {
GraphToolSchemas::all()
}
/// Get tool names for listing
pub fn get_tool_names() -> Vec<String> {
GraphToolSchemas::tool_names()
}
}
fn log_tool_call_start(tool_name: &str, parameters: &JsonValue) {
info!(
target: TOOL_PROGRESS_LOG_TARGET,
tool = tool_name,
"Tool call started"
);
debug!(
target: TOOL_PROGRESS_LOG_TARGET,
tool = tool_name,
"Tool input payload: {}",
parameters
);
// Debug logging to file if enabled
DebugLogger::log_tool_start(tool_name, parameters);
}
fn log_tool_call_finish(tool_name: &str, result: &JsonValue) {
info!(
target: TOOL_PROGRESS_LOG_TARGET,
tool = tool_name,
result_bytes = result.to_string().len(),
"Tool call completed"
);
debug!(
target: TOOL_PROGRESS_LOG_TARGET,
tool = tool_name,
"Tool output payload: {}",
result
);
// Debug logging to file if enabled
DebugLogger::log_tool_finish(tool_name, result);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_shorten_content_keeps_location_and_marks_truncation() {
let long = (0..200)
.map(|i| format!("line {i} of a long document"))
.collect::<Vec<_>>()
.join("\n");
let mut result = json!({
"tool": "semantic_code_search",
"result": [
{ "name": "doc", "file_path": "README.md", "start_line": 1, "content": long },
{ "name": "small", "content": "fn small() {}" },
{ "node": { "name": "nested", "content": "x".repeat(5_000) } }
]
});
shorten_content(&mut result, 300);
let rows = result["result"].as_array().unwrap();
let snippet = rows[0]["content"].as_str().unwrap();
assert!(snippet.chars().count() <= 300, "{}", snippet.len());
assert!(
snippet.ends_with("of a long document"),
"ends on a full line"
);
assert_eq!(rows[0]["content_truncated"], true);
assert!(rows[0]["content_chars"].as_u64().unwrap() > 4_000);
assert_eq!(rows[0]["file_path"], "README.md");
assert_eq!(rows[1]["content"], "fn small() {}");
assert!(rows[1].get("content_truncated").is_none());
assert_eq!(rows[2]["node"]["content"].as_str().unwrap().len(), 300);
assert_eq!(rows[2]["node"]["content_truncated"], true);
}
#[test]
fn test_shorten_content_respects_char_boundaries_and_zero_disables() {
let mut result = json!({ "content": "é".repeat(50) });
shorten_content(&mut result, 10);
assert_eq!(result["content"].as_str().unwrap().chars().count(), 10);
let mut untouched = json!({ "content": "y".repeat(50) });
shorten_content(&mut untouched, 0);
assert_eq!(untouched["content"].as_str().unwrap().len(), 50);
}
#[test]
fn test_tool_schemas_available() {
let schemas = GraphToolExecutor::get_tool_schemas();
assert_eq!(schemas.len(), 8);
}
#[test]
fn test_tool_names() {
let names = GraphToolExecutor::get_tool_names();
assert_eq!(names.len(), 8);
assert!(names.contains(&"get_transitive_dependencies".to_string()));
assert!(names.contains(&"find_complexity_hotspots".to_string()));
}
#[test]
fn test_parameter_extraction() {
let params = json!({
"node_id": "nodes:123",
"edge_type": "Calls",
"depth": 5
});
assert_eq!(params["node_id"].as_str().unwrap(), "nodes:123");
assert_eq!(params["edge_type"].as_str().unwrap(), "Calls");
assert_eq!(params["depth"].as_i64().unwrap(), 5);
}
// === Cache Tests ===
#[test]
fn test_cache_key_generation() {
let params1 = json!({
"node_id": "nodes:123",
"edge_type": "Calls",
"depth": 3
});
let params2 = json!({
"node_id": "nodes:123",
"edge_type": "Calls",
"depth": 3
});
let params3 = json!({
"node_id": "nodes:456",
"edge_type": "Calls",
"depth": 3
});
let project = "proj-a";
let key1 = GraphToolExecutor::cache_key(project, "get_transitive_dependencies", ¶ms1);
let key2 = GraphToolExecutor::cache_key(project, "get_transitive_dependencies", ¶ms2);
let key3 = GraphToolExecutor::cache_key(project, "get_transitive_dependencies", ¶ms3);
// Same params should generate same key
assert_eq!(key1, key2);
// Different params should generate different key
assert_ne!(key1, key3);
}
#[test]
fn test_cache_key_includes_project_scope() {
let params = json!({
"node_id": "nodes:123"
});
let key_a = GraphToolExecutor::cache_key("proj-a", "get_hub_nodes", ¶ms);
let key_b = GraphToolExecutor::cache_key("proj-b", "get_hub_nodes", ¶ms);
assert_ne!(key_a, key_b);
assert!(
key_a.starts_with("proj-a:"),
"Project scope should prefix cache key"
);
}
#[test]
fn test_cache_stats_initialization() {
let stats = CacheStats {
hits: 0,
misses: 0,
evictions: 0,
current_size: 0,
max_size: 100,
};
assert_eq!(stats.hit_rate(), 0.0);
}
#[test]
fn test_cache_stats_hit_rate_calculation() {
let stats = CacheStats {
hits: 75,
misses: 25,
evictions: 5,
current_size: 50,
max_size: 100,
};
assert_eq!(stats.hit_rate(), 75.0);
}
#[test]
fn test_cache_stats_hit_rate_no_requests() {
let stats = CacheStats {
hits: 0,
misses: 0,
evictions: 0,
current_size: 0,
max_size: 100,
};
assert_eq!(stats.hit_rate(), 0.0);
}
#[test]
fn test_log_tool_call_start_captures_info_and_debug() {
let logs = capture_logs(|| {
let params = serde_json::json!({
"node_id": "nodes:123",
"edge_type": "Calls"
});
log_tool_call_start("get_transitive_dependencies", ¶ms);
});
assert!(logs.contains("Tool call started"));
assert!(logs.contains("Tool input payload"));
}
#[test]
fn test_log_tool_call_finish_captures_info_and_debug() {
let logs = capture_logs(|| {
let result = serde_json::json!({
"tool": "detect_cycles",
"result": "ok"
});
log_tool_call_finish("detect_cycles", &result);
});
assert!(logs.contains("Tool call completed"));
assert!(logs.contains("Tool output payload"));
}
fn capture_logs<F>(f: F) -> String
where
F: FnOnce(),
{
use std::io::Write;
use std::sync::{Arc, Mutex};
use tracing::subscriber::with_default;
use tracing_subscriber::EnvFilter;
#[derive(Clone)]