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
//! Search and info tools: get_index_info, semantic_search_docs,
//! semantic_search_with_context, search_symbols, search_documents.
use rmcp::model::ErrorData as McpError;
use rmcp::model::*;
use rmcp::{handler::server::wrapper::Parameters, tool, tool_router};
use crate::documents::SearchQuery as DocSearchQuery;
use crate::mcp::requests::{
GetIndexInfoRequest, SearchDocumentsRequest, SearchSymbolsRequest, SemanticSearchRequest,
SemanticSearchWithContextRequest,
};
use crate::mcp::server::{CodeIntelligenceServer, format_relative_time, generate_mcp_guidance};
#[tool_router(router = search_router, vis = "pub(crate)")]
impl CodeIntelligenceServer {
#[tool(description = "Get information about the indexed codebase")]
pub async fn get_index_info(
&self,
Parameters(_params): Parameters<GetIndexInfoRequest>,
) -> Result<CallToolResult, McpError> {
let indexer = self.facade.read().await;
let symbol_count = indexer.symbol_count();
let file_count = indexer.file_count();
let relationship_count = indexer.relationship_count();
// Efficiently count symbols by kind in one pass
let mut kind_counts = std::collections::HashMap::new();
for symbol in indexer.get_all_symbols() {
*kind_counts.entry(symbol.kind).or_insert(0) += 1;
}
// Build symbol kinds display dynamically
let mut kinds_display = String::new();
// Sort by kind name for consistent output
let mut sorted_kinds: Vec<_> = kind_counts.iter().collect();
sorted_kinds.sort_by_key(|(kind, _)| format!("{kind:?}"));
for (kind, count) in sorted_kinds {
kinds_display.push_str(&format!("\n - {kind:?}s: {count}"));
}
// Get semantic search info
let semantic_info = if let Some(metadata) = indexer.get_semantic_metadata() {
let live_count = indexer.semantic_search_embedding_count();
format!(
"\n\nSemantic Search:\n - Status: Enabled\n - Model: {}\n - Embeddings: {}\n - Dimensions: {}\n - Created: {}\n - Updated: {}",
metadata.model_name,
live_count,
metadata.dimension,
format_relative_time(metadata.created_at),
format_relative_time(metadata.updated_at)
)
} else {
"\n\nSemantic Search:\n - Status: Disabled".to_string()
};
let result = format!(
"Index contains {symbol_count} symbols across {file_count} files.\n\nBreakdown:\n - Symbols: {symbol_count}\n - Relationships: {relationship_count}\n\nSymbol Kinds:{kinds_display}{semantic_info}"
);
Ok(CallToolResult::success(vec![ContentBlock::text(result)]))
}
#[tool(description = "Search documentation using natural language semantic search")]
pub async fn semantic_search_docs(
&self,
Parameters(SemanticSearchRequest {
query,
limit,
threshold,
lang,
}): Parameters<SemanticSearchRequest>,
) -> Result<CallToolResult, McpError> {
let indexer = self.facade.read().await;
tracing::debug!(
target: "mcp",
"semantic_search_docs called - symbols: {}, semantic: {}",
indexer.symbol_count(),
indexer.has_semantic_search()
);
if !indexer.has_semantic_search() {
// Check if semantic files exist
let semantic_path = indexer.settings().index_path.join("semantic");
let metadata_exists = semantic_path.join("metadata.json").exists();
let vectors_exist = semantic_path.join("segment_0.vec").exists();
let symbol_count = indexer.symbol_count();
// Get current working directory for debugging
let cwd = std::env::current_dir()
.map(|p| p.display().to_string())
.unwrap_or_else(|_| "unknown".to_string());
return Ok(CallToolResult::error(vec![ContentBlock::text(format!(
"Semantic search is not enabled. The index needs to be rebuilt with semantic search enabled.\n\nDEBUG INFO:\n- Index path: {}\n- Symbol count: {}\n- Semantic files exist: {}\n- Has semantic search: {}\n- Working dir: {}",
indexer.settings().index_path.display(),
symbol_count,
metadata_exists && vectors_exist,
indexer.has_semantic_search(),
cwd
))]));
}
let results = match threshold {
Some(t) => indexer.semantic_search_docs_with_threshold_and_language(
&query,
limit as usize,
t,
lang.as_deref(),
),
None => {
indexer.semantic_search_docs_with_language(&query, limit as usize, lang.as_deref())
}
};
match results {
Ok(results) => {
if results.is_empty() {
let mut output =
format!("No semantically similar documentation found for: {query}");
// Add guidance for no results
if let Some(guidance) =
generate_mcp_guidance(indexer.settings(), "semantic_search_docs", 0)
{
output.push_str("\n\n---\nGuidance: ");
output.push_str(&guidance);
output.push('\n');
}
return Ok(CallToolResult::success(vec![ContentBlock::text(output)]));
}
let mut result = format!(
"Found {} semantically similar result(s) for '{}':\n\n",
results.len(),
query
);
for (i, (symbol, score)) in results.iter().enumerate() {
result.push_str(&format!(
"{}. {} ({:?}) - Similarity: {:.3}\n",
i + 1,
symbol.name,
symbol.kind,
score
));
result.push_str(&format!(
" File: {}:{}\n",
symbol.file_path,
symbol.range.start_line + 1
));
if let Some(ref doc) = symbol.doc_comment {
// Show first 3 lines of doc
let preview: Vec<&str> = doc.lines().take(3).collect();
let doc_preview = if doc.lines().count() > 3 {
format!("{}...", preview.join(" "))
} else {
preview.join(" ")
};
result.push_str(&format!(" Doc: {doc_preview}\n"));
}
if let Some(ref sig) = symbol.signature {
result.push_str(&format!(" Signature: {sig}\n"));
}
result.push('\n');
}
// Add system guidance
if let Some(guidance) =
generate_mcp_guidance(indexer.settings(), "semantic_search_docs", results.len())
{
result.push_str("\n---\nGuidance: ");
result.push_str(&guidance);
result.push('\n');
}
Ok(CallToolResult::success(vec![ContentBlock::text(result)]))
}
Err(e) => Ok(CallToolResult::error(vec![ContentBlock::text(format!(
"Semantic search failed: {e}"
))])),
}
}
#[tool(
description = "Search by natural language and get full context: documentation, dependencies, callers, impact.\n\nReturns symbols with:\n- Their documentation\n- What calls them\n- What they call\n- Complete impact graph (includes ALL relationships: calls, type usage, composition)\n\nUse this when: You want to find and understand symbols with their complete usage context."
)]
pub async fn semantic_search_with_context(
&self,
Parameters(SemanticSearchWithContextRequest {
query,
limit,
threshold,
lang,
}): Parameters<SemanticSearchWithContextRequest>,
) -> Result<CallToolResult, McpError> {
let indexer = self.facade.read().await;
if !indexer.has_semantic_search() {
tracing::debug!(
target: "mcp",
"semantic search not available - index_path: {}, has_semantic: {}",
indexer.settings().index_path.display(),
indexer.has_semantic_search()
);
// Check if semantic files exist
let semantic_path = indexer.settings().index_path.join("semantic");
let metadata_exists = semantic_path.join("metadata.json").exists();
let vectors_exist = semantic_path.join("segment_0.vec").exists();
return Ok(CallToolResult::error(vec![ContentBlock::text(format!(
"Semantic search is not enabled. The index needs to be rebuilt with semantic search enabled.\n\nDEBUG INFO:\n- Index path: {}\n- Has semantic search: {}\n- Semantic path: {}\n- Metadata exists: {}\n- Vectors exist: {}",
indexer.settings().index_path.display(),
indexer.has_semantic_search(),
semantic_path.display(),
metadata_exists,
vectors_exist
))]));
}
// First, perform semantic search
let search_results = match threshold {
Some(t) => indexer.semantic_search_docs_with_threshold_and_language(
&query,
limit as usize,
t,
lang.as_deref(),
),
None => {
indexer.semantic_search_docs_with_language(&query, limit as usize, lang.as_deref())
}
};
match search_results {
Ok(results) => {
if results.is_empty() {
let mut output = format!("No documentation found matching query: {query}");
// Add guidance for no results
if let Some(guidance) =
generate_mcp_guidance(indexer.settings(), "semantic_search_with_context", 0)
{
output.push_str("\n\n---\nGuidance: ");
output.push_str(&guidance);
output.push('\n');
}
return Ok(CallToolResult::success(vec![ContentBlock::text(output)]));
}
let mut output = String::new();
output.push_str(&format!(
"Found {} results for query: '{}'\n\n",
results.len(),
query
));
// For each result, gather comprehensive context
for (idx, (symbol, score)) in results.iter().enumerate() {
// Basic symbol information - matching find_symbol format
output.push_str(&format!(
"{}. {} - {:?} at {} [symbol_id:{}]\n",
idx + 1,
symbol.name,
symbol.kind,
crate::symbol::context::SymbolContext::symbol_location(symbol),
symbol.id.value()
));
output.push_str(&format!(" Similarity Score: {score:.3}\n"));
// Documentation
if let Some(ref doc) = symbol.doc_comment {
output.push_str(" Documentation:\n");
for line in doc.lines().take(5) {
output.push_str(&format!(" {line}\n"));
}
if doc.lines().count() > 5 {
output.push_str(" ...\n");
}
}
// Signature
if let Some(ref sig) = symbol.signature {
output.push_str(&format!(" Signature: {sig}\n"));
}
// Only gather additional context for functions/methods
if matches!(
symbol.kind,
crate::SymbolKind::Function | crate::SymbolKind::Method
) {
// Dependencies (what this function calls) - using logic from get_calls
let called_with_metadata =
indexer.get_called_functions_with_metadata(symbol.id);
if !called_with_metadata.is_empty() {
output.push_str(&format!(
"\n {} calls {} function(s):\n",
symbol.name,
called_with_metadata.len()
));
for (i, (called, metadata)) in
called_with_metadata.iter().take(10).enumerate()
{
// Parse receiver information from metadata and get call site location
let (call_display, call_line) = if let Some(meta) = metadata {
let display = if let Some(context) = &meta.context {
if context.contains("receiver:")
&& context.contains("static:")
{
let parts: Vec<&str> = context.split(',').collect();
let mut receiver = None;
let mut is_static = false;
for part in parts {
if let Some(recv) = part.strip_prefix("receiver:") {
receiver = Some(recv.trim());
} else if let Some(static_val) =
part.strip_prefix("static:")
{
is_static = static_val.trim() == "true";
}
}
match (receiver, is_static) {
(Some("self"), false) => {
format!("(self.{})", called.name)
}
(Some(recv), true) if recv != "self" => {
format!("({}::{})", recv, called.name)
}
(Some(recv), false) if recv != "self" => {
format!("({}.{})", recv, called.name)
}
_ => called.name.to_string(),
}
} else {
called.name.to_string()
}
} else {
called.name.to_string()
};
// Use call site line if available
let line = meta
.line
.map(|l| l + 1)
.unwrap_or(called.range.start_line + 1);
(display, line)
} else {
(called.name.to_string(), called.range.start_line + 1)
};
output.push_str(&format!(
" -> {:?} {} at {}:{} [symbol_id:{}]\n",
called.kind,
call_display,
called.file_path,
call_line,
called.id.value()
));
if i == 9 && called_with_metadata.len() > 10 {
output.push_str(&format!(
" ... and {} more\n",
called_with_metadata.len() - 10
));
}
}
}
// Callers (who uses this function) - using logic from find_callers
let calling_functions_with_metadata =
indexer.get_calling_functions_with_metadata(symbol.id);
if !calling_functions_with_metadata.is_empty() {
output.push_str(&format!(
"\n {} function(s) call {}:\n",
calling_functions_with_metadata.len(),
symbol.name
));
for (i, (caller, metadata)) in
calling_functions_with_metadata.iter().take(10).enumerate()
{
// Parse metadata to extract receiver info and call site location
let (call_info, call_line) = if let Some(meta) = metadata {
let info = if let Some(context) = &meta.context {
if context.contains("receiver:")
&& context.contains("static:")
{
// Parse "receiver:{receiver},static:{is_static}"
let parts: Vec<&str> = context.split(',').collect();
let mut receiver = "";
let mut is_static = false;
for part in parts {
if let Some(r) = part.strip_prefix("receiver:") {
receiver = r;
} else if let Some(s) = part.strip_prefix("static:")
{
is_static = s == "true";
}
}
if !receiver.is_empty() {
let qualified_name = if is_static {
format!("{}::{}", receiver, symbol.name)
} else {
format!("{}.{}", receiver, symbol.name)
};
format!(" (calls {qualified_name})")
} else {
String::new()
}
} else {
String::new()
}
} else {
String::new()
};
// Use call site line if available
let line = meta
.line
.map(|l| l + 1)
.unwrap_or(caller.range.start_line + 1);
(info, line)
} else {
(String::new(), caller.range.start_line + 1)
};
output.push_str(&format!(
" <- {:?} {} at {}:{}{} [symbol_id:{}]\n",
caller.kind,
caller.name,
caller.file_path,
call_line,
call_info,
caller.id.value()
));
if i == 9 && calling_functions_with_metadata.len() > 10 {
output.push_str(&format!(
" ... and {} more\n",
calling_functions_with_metadata.len() - 10
));
}
}
}
// Impact analysis - using logic from analyze_impact
let impacted = indexer.get_impact_radius(symbol.id, Some(2));
if !impacted.is_empty() {
output.push_str(&format!(
"\n Changing {} would impact {} symbol(s) (max depth: 2):\n",
symbol.name,
impacted.len()
));
// Get details and group by kind
let impacted_details: Vec<_> = impacted
.iter()
.filter_map(|id| indexer.get_symbol(*id))
.collect();
// Group by kind
let mut methods = Vec::new();
let mut functions = Vec::new();
let mut other = Vec::new();
for sym in impacted_details {
match sym.kind {
crate::SymbolKind::Method => methods.push(sym),
crate::SymbolKind::Function => functions.push(sym),
_ => other.push(sym),
}
}
if !methods.is_empty() {
output.push_str(&format!("\n methods ({}):\n", methods.len()));
for method in methods.iter().take(5) {
output.push_str(&format!(
" - {} [symbol_id:{}]\n",
method.name,
method.id.value()
));
}
if methods.len() > 5 {
output.push_str(&format!(
" ... and {} more\n",
methods.len() - 5
));
}
}
if !functions.is_empty() {
output.push_str(&format!(
"\n functions ({}):\n",
functions.len()
));
for func in functions.iter().take(5) {
output.push_str(&format!(
" - {} [symbol_id:{}]\n",
func.name,
func.id.value()
));
}
if functions.len() > 5 {
output.push_str(&format!(
" ... and {} more\n",
functions.len() - 5
));
}
}
if !other.is_empty() {
output.push_str(&format!("\n other ({}):\n", other.len()));
for sym in other.iter().take(3) {
output.push_str(&format!(
" - {} ({:?}) [symbol_id:{}]\n",
sym.name,
sym.kind,
sym.id.value()
));
}
}
}
}
// Show inheritance relationships for classes/structs/enums
if matches!(
symbol.kind,
crate::SymbolKind::Class
| crate::SymbolKind::Struct
| crate::SymbolKind::Enum
) {
// What does this class extend?
let extends = indexer.get_extends(symbol.id);
if !extends.is_empty() {
output.push_str(&format!(
"\n {} extends {} class(es):\n",
symbol.name,
extends.len()
));
for (i, base_class) in extends.iter().take(5).enumerate() {
output.push_str(&format!(
" -> {:?} {} at {} [symbol_id:{}]\n",
base_class.kind,
base_class.name,
crate::symbol::context::SymbolContext::symbol_location(
base_class
),
base_class.id.value()
));
if i == 4 && extends.len() > 5 {
output.push_str(&format!(
" ... and {} more\n",
extends.len() - 5
));
}
}
}
// What classes extend this class?
let extended_by = indexer.get_extended_by(symbol.id);
if !extended_by.is_empty() {
output.push_str(&format!(
"\n {} class(es) extend {}:\n",
extended_by.len(),
symbol.name
));
for (i, derived_class) in extended_by.iter().take(5).enumerate() {
output.push_str(&format!(
" <- {:?} {} at {} [symbol_id:{}]\n",
derived_class.kind,
derived_class.name,
crate::symbol::context::SymbolContext::symbol_location(
derived_class
),
derived_class.id.value()
));
if i == 4 && extended_by.len() > 5 {
output.push_str(&format!(
" ... and {} more\n",
extended_by.len() - 5
));
}
}
}
// What traits does this type implement?
let implements = indexer.get_implemented_traits(symbol.id);
if !implements.is_empty() {
output.push_str(&format!(
"\n {} implements {} trait(s):\n",
symbol.name,
implements.len()
));
for (i, trait_sym) in implements.iter().take(5).enumerate() {
output.push_str(&format!(
" -> {:?} {} at {} [symbol_id:{}]\n",
trait_sym.kind,
trait_sym.name,
crate::symbol::context::SymbolContext::symbol_location(
trait_sym
),
trait_sym.id.value()
));
if i == 4 && implements.len() > 5 {
output.push_str(&format!(
" ... and {} more\n",
implements.len() - 5
));
}
}
}
}
// Show what implements this trait/interface
if matches!(
symbol.kind,
crate::SymbolKind::Trait | crate::SymbolKind::Interface
) {
let implementations = indexer.get_implementations(symbol.id);
if !implementations.is_empty() {
output.push_str(&format!(
"\n {} type(s) implement {}:\n",
implementations.len(),
symbol.name
));
for (i, impl_sym) in implementations.iter().take(5).enumerate() {
output.push_str(&format!(
" <- {:?} {} at {} [symbol_id:{}]\n",
impl_sym.kind,
impl_sym.name,
crate::symbol::context::SymbolContext::symbol_location(
impl_sym
),
impl_sym.id.value()
));
if i == 4 && implementations.len() > 5 {
output.push_str(&format!(
" ... and {} more\n",
implementations.len() - 5
));
}
}
}
}
// Show uses relationships (for all symbols)
let uses = indexer.get_uses(symbol.id);
if !uses.is_empty() {
output.push_str(&format!(
"\n {} uses {} type(s):\n",
symbol.name,
uses.len()
));
for (i, used_type) in uses.iter().take(5).enumerate() {
output.push_str(&format!(
" -> {:?} {} at {} [symbol_id:{}]\n",
used_type.kind,
used_type.name,
crate::symbol::context::SymbolContext::symbol_location(used_type),
used_type.id.value()
));
if i == 4 && uses.len() > 5 {
output.push_str(&format!(" ... and {} more\n", uses.len() - 5));
}
}
}
// What symbols use this type?
let used_by = indexer.get_used_by(symbol.id);
if !used_by.is_empty() {
output.push_str(&format!(
"\n {} type(s) use {}:\n",
used_by.len(),
symbol.name
));
for (i, using_symbol) in used_by.iter().take(5).enumerate() {
output.push_str(&format!(
" <- {:?} {} at {} [symbol_id:{}]\n",
using_symbol.kind,
using_symbol.name,
crate::symbol::context::SymbolContext::symbol_location(
using_symbol
),
using_symbol.id.value()
));
if i == 4 && used_by.len() > 5 {
output.push_str(&format!(
" ... and {} more\n",
used_by.len() - 5
));
}
}
}
output.push('\n');
}
// Add system guidance
if let Some(guidance) = generate_mcp_guidance(
indexer.settings(),
"semantic_search_with_context",
results.len(),
) {
output.push_str("\n---\nGuidance: ");
output.push_str(&guidance);
output.push('\n');
}
Ok(CallToolResult::success(vec![ContentBlock::text(output)]))
}
Err(e) => Ok(CallToolResult::error(vec![ContentBlock::text(format!(
"Semantic search failed: {e}"
))])),
}
}
#[tool(description = "Search for symbols using full-text search with fuzzy matching")]
pub async fn search_symbols(
&self,
Parameters(SearchSymbolsRequest {
query,
limit,
kind,
module,
lang,
}): Parameters<SearchSymbolsRequest>,
) -> Result<CallToolResult, McpError> {
let indexer = self.facade.read().await;
// One kind vocabulary (SymbolKind::from_str); unknown kinds error
// instead of silently returning unfiltered results.
let kind_filter = match kind.as_deref().map(str::parse::<crate::SymbolKind>) {
None => None,
Some(Ok(k)) => Some(k),
Some(Err(e)) => {
return Ok(CallToolResult::error(vec![ContentBlock::text(format!(
"Error: {e}"
))]));
}
};
match indexer.search(
&query,
limit as usize,
kind_filter,
module.as_deref(),
lang.as_deref(),
) {
Ok(results) => {
if results.is_empty() {
let mut output = format!("No results found for query: {query}");
// Add guidance for no results
if let Some(guidance) =
generate_mcp_guidance(indexer.settings(), "search_symbols", 0)
{
output.push_str("\n\n---\nGuidance: ");
output.push_str(&guidance);
output.push('\n');
}
return Ok(CallToolResult::success(vec![ContentBlock::text(output)]));
}
let mut result = format!(
"Found {} result(s) for query '{}':\n\n",
results.len(),
query
);
for (i, search_result) in results.iter().enumerate() {
result.push_str(&format!(
"{}. {} ({:?})\n",
i + 1,
search_result.name,
search_result.kind
));
result.push_str(&format!(
" File: {}:{}\n",
search_result.file_path, search_result.line
));
if !search_result.module_path.is_empty() {
result.push_str(&format!(" Module: {}\n", search_result.module_path));
}
if let Some(ref doc) = search_result.doc_comment {
// Show first line of doc comment
let first_line = doc.lines().next().unwrap_or("");
result.push_str(&format!(" Doc: {first_line}\n"));
}
if let Some(ref sig) = search_result.signature {
result.push_str(&format!(" Signature: {sig}\n"));
}
result.push_str(&format!(" Score: {:.2}\n", search_result.score));
result.push('\n');
}
// Add system guidance
if let Some(guidance) =
generate_mcp_guidance(indexer.settings(), "search_symbols", results.len())
{
result.push_str("\n---\nGuidance: ");
result.push_str(&guidance);
result.push('\n');
}
Ok(CallToolResult::success(vec![ContentBlock::text(result)]))
}
Err(e) => Ok(CallToolResult::error(vec![ContentBlock::text(format!(
"Search failed: {e}"
))])),
}
}
#[tool(
description = "Search indexed documents (markdown, text files) using natural language queries. Returns relevant chunks with context and highlighted keywords."
)]
pub async fn search_documents(
&self,
Parameters(SearchDocumentsRequest {
query,
collection,
limit,
}): Parameters<SearchDocumentsRequest>,
) -> Result<CallToolResult, McpError> {
let store = match &self.document_store {
Some(s) => s,
None => {
return Ok(CallToolResult::error(vec![ContentBlock::text(
"Document search not available. No document collections are indexed.\n\n\
To enable:\n\
1. Add a collection: codanna documents add-collection docs docs/\n\
2. Index it: codanna documents index\n\
3. Restart the MCP server",
)]));
}
};
let mut store = store.write().await;
let indexer = self.facade.read().await;
// Auto-sync: check for file changes in all collections before searching
let settings = indexer.settings();
for (name, config) in &settings.documents.collections {
if let Err(e) = store.index_collection(name, config, &settings.documents.defaults) {
tracing::warn!(target: "rag", "auto-sync failed for collection '{}': {}", name, e);
}
}
let search_query = DocSearchQuery {
text: query.clone(),
collection,
document: None,
limit: limit as usize,
preview_config: Some(indexer.settings().documents.search.clone()),
};
match store.search(search_query) {
Ok(results) => {
if results.is_empty() {
return Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"No documents found for: {query}"
))]));
}
let mut output = format!(
"Found {} document(s) matching '{}':\n\n",
results.len(),
query
);
for (i, result) in results.iter().enumerate() {
output.push_str(&format!(
"{}. {} (score: {:.3})\n",
i + 1,
result.source_path.display(),
result.similarity
));
if !result.heading_context.is_empty() {
output.push_str(&format!(
" Context: {}\n",
result.heading_context.join(" > ")
));
}
// Preview is already KWIC-processed with highlighting
output.push_str(&format!(" Preview: {}\n\n", result.content_preview));
}
Ok(CallToolResult::success(vec![ContentBlock::text(output)]))
}
Err(e) => Ok(CallToolResult::error(vec![ContentBlock::text(format!(
"Document search failed: {e}"
))])),
}
}
}