forked from jsbattig/code-indexer
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandlers.py
More file actions
9304 lines (8009 loc) · 323 KB
/
handlers.py
File metadata and controls
9304 lines (8009 loc) · 323 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
"""MCP Tool Handler Functions - Complete implementation for all 22 tools.
All handlers return MCP-compliant responses with content arrays:
{
"content": [
{
"type": "text",
"text": "<JSON-stringified response data>"
}
]
}
"""
from code_indexer.server.middleware.correlation import get_correlation_id
import difflib
import json
import logging
import pathspec
from typing import Dict, Any, Optional, List
from pathlib import Path
from code_indexer.server.auth.user_manager import User, UserRole
from code_indexer.server.utils.registry_factory import get_server_global_registry
from code_indexer.server import app as app_module
from code_indexer.server.services.ssh_key_manager import (
SSHKeyManager,
KeyNotFoundError,
HostConflictError,
)
from code_indexer.server.services.ssh_key_generator import (
InvalidKeyNameError,
KeyAlreadyExistsError,
)
from code_indexer.server.services.git_operations_service import (
git_operations_service,
GitCommandError,
)
from code_indexer.server.repositories.activated_repo_manager import (
ActivatedRepoManager,
)
from code_indexer.server.repositories.scip_audit import SCIPAuditRepository
logger = logging.getLogger(__name__)
# Initialize SCIP Audit Repository singleton
scip_audit_repository = SCIPAuditRepository()
def _parse_json_string_array(value: Any) -> Any:
"""Parse JSON string arrays from MCP clients that serialize arrays as strings.
Some MCP clients send arrays as JSON strings like '["repo1", "repo2"]'
instead of actual arrays. This function handles that case.
"""
if isinstance(value, str) and value.startswith("["):
try:
parsed = json.loads(value)
if isinstance(parsed, list):
return parsed
except (json.JSONDecodeError, ValueError):
pass
return value
def _mcp_response(data: Dict[str, Any]) -> Dict[str, Any]:
"""Wrap response data in MCP-compliant content array format.
Per MCP spec, all tool responses must return:
{
"content": [
{
"type": "text",
"text": "<JSON-stringified data>"
}
]
}
Args:
data: The actual response data to wrap (dict with success, results, etc)
Returns:
MCP-compliant response with content array
"""
return {"content": [{"type": "text", "text": json.dumps(data, indent=2)}]}
def _get_golden_repos_dir() -> str:
"""Get golden_repos_dir from app.state.
Raises:
RuntimeError: If golden_repos_dir is not configured in app.state
"""
from typing import Optional, cast
golden_repos_dir: Optional[str] = cast(
Optional[str], getattr(app_module.app.state, "golden_repos_dir", None)
)
if golden_repos_dir:
return golden_repos_dir
raise RuntimeError(
"golden_repos_dir not configured in app.state. "
"Server must set app.state.golden_repos_dir during startup."
)
def _get_query_tracker():
"""Get QueryTracker from app.state.
Returns:
QueryTracker instance if configured, None otherwise.
Used for tracking active queries to prevent concurrent access issues
during repository removal operations.
"""
return getattr(app_module.app.state, "query_tracker", None)
async def _apply_payload_truncation(
results: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Apply payload truncation to search results (Story #679, Bug Fix #683).
For results with large content, replaces content with preview + cache_handle.
This reduces response size while allowing clients to fetch full content on demand.
Handles both 'content' field (REST API format) and 'code_snippet' field
(semantic search QueryResult.to_dict() format).
Args:
results: List of search result dicts with 'content' or 'code_snippet' field
Returns:
Modified results list with truncation applied
"""
payload_cache = getattr(app_module.app.state, "payload_cache", None)
if payload_cache is None:
# Cache not available, return results unchanged
return results
for result_dict in results:
# Handle both content and code_snippet fields (Bug Fix #683)
# Logic for field selection:
# - If ONLY code_snippet exists: truncate code_snippet (semantic search format)
# - If ONLY content exists: truncate content (REST API format)
# - If BOTH exist: truncate content (hybrid mode - code_snippet handled by FTS)
has_code_snippet = "code_snippet" in result_dict
has_content = "content" in result_dict
if has_content:
# Content field exists - truncate it (works for both legacy and hybrid)
content = result_dict.get("content")
field_name = "content"
elif has_code_snippet:
# Only code_snippet exists - truncate it (semantic search format)
content = result_dict.get("code_snippet")
field_name = "code_snippet"
else:
# No content field to truncate, add default metadata
result_dict["cache_handle"] = None
result_dict["has_more"] = False
continue
if content is None:
# Field exists but is None, add default metadata
result_dict["cache_handle"] = None
result_dict["has_more"] = False
continue
try:
truncated = await payload_cache.truncate_result(content)
if truncated.get("has_more", False):
# Large content: replace with preview and cache handle
result_dict["preview"] = truncated["preview"]
result_dict["cache_handle"] = truncated["cache_handle"]
result_dict["has_more"] = True
result_dict["total_size"] = truncated["total_size"]
del result_dict[field_name] # Remove full content
else:
# Small content: keep as-is, add metadata
result_dict["cache_handle"] = None
result_dict["has_more"] = False
except Exception as e:
# Log error but don't fail the search
logger.warning(
f"Failed to truncate result: {e}",
extra={"correlation_id": get_correlation_id()},
)
# Keep original content on error
result_dict["cache_handle"] = None
result_dict["has_more"] = False
return results
async def _apply_fts_payload_truncation(
results: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Apply payload truncation to FTS search results (Story #680).
For FTS results with large code_snippet or match_text fields, replaces
them with preview + cache_handle. Each field is cached independently.
Args:
results: List of FTS search result dicts with 'code_snippet' and/or
'match_text' fields
Returns:
Modified results list with truncation applied to FTS fields
"""
payload_cache = getattr(app_module.app.state, "payload_cache", None)
if payload_cache is None:
# Cache not available, return results unchanged
return results
preview_size = payload_cache.config.preview_size_chars
for result_dict in results:
# Handle code_snippet field (AC1)
code_snippet = result_dict.get("code_snippet")
if code_snippet is not None:
try:
if len(code_snippet) > preview_size:
# Large snippet: store and replace with preview
cache_handle = await payload_cache.store(code_snippet)
result_dict["snippet_preview"] = code_snippet[:preview_size]
result_dict["snippet_cache_handle"] = cache_handle
result_dict["snippet_has_more"] = True
result_dict["snippet_total_size"] = len(code_snippet)
del result_dict["code_snippet"]
else:
# Small snippet: keep as-is, add metadata
result_dict["snippet_cache_handle"] = None
result_dict["snippet_has_more"] = False
except Exception as e:
logger.warning(
f"Failed to truncate code_snippet: {e}",
extra={"correlation_id": get_correlation_id()},
)
result_dict["snippet_cache_handle"] = None
result_dict["snippet_has_more"] = False
# Handle match_text field (AC2)
match_text = result_dict.get("match_text")
if match_text is not None:
try:
if len(match_text) > preview_size:
# Large match_text: store and replace with preview
cache_handle = await payload_cache.store(match_text)
result_dict["match_text_preview"] = match_text[:preview_size]
result_dict["match_text_cache_handle"] = cache_handle
result_dict["match_text_has_more"] = True
result_dict["match_text_total_size"] = len(match_text)
del result_dict["match_text"]
else:
# Small match_text: keep as-is, add metadata
result_dict["match_text_cache_handle"] = None
result_dict["match_text_has_more"] = False
except Exception as e:
logger.warning(
f"Failed to truncate match_text: {e}",
extra={"correlation_id": get_correlation_id()},
)
result_dict["match_text_cache_handle"] = None
result_dict["match_text_has_more"] = False
return results
async def _truncate_regex_field(
result_dict: Dict[str, Any],
field_name: str,
payload_cache,
preview_size: int,
is_list: bool = False,
) -> None:
"""Truncate a single regex field if needed (Story #684 helper).
Args:
result_dict: Dict containing the field to truncate
field_name: Name of the field (e.g., "line_content", "context_before")
payload_cache: PayloadCache instance for storing large content
preview_size: Maximum chars before truncation
is_list: If True, field is a list of strings to join with newlines
"""
field_value = result_dict.get(field_name)
if field_value is None:
return
try:
content = "\n".join(field_value) if is_list else field_value
if len(content) > preview_size:
cache_handle = await payload_cache.store(content)
result_dict[f"{field_name}_preview"] = content[:preview_size]
result_dict[f"{field_name}_cache_handle"] = cache_handle
result_dict[f"{field_name}_has_more"] = True
result_dict[f"{field_name}_total_size"] = len(content)
del result_dict[field_name]
else:
result_dict[f"{field_name}_cache_handle"] = None
result_dict[f"{field_name}_has_more"] = False
except Exception as e:
logger.warning(
f"Failed to truncate {field_name}: {e}",
extra={"correlation_id": get_correlation_id()},
)
result_dict[f"{field_name}_cache_handle"] = None
result_dict[f"{field_name}_has_more"] = False
async def _apply_regex_payload_truncation(
results: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Apply payload truncation to regex search results (Story #684).
For regex results with large line_content, context_before, or context_after
fields, replaces them with preview + cache_handle. Each field is cached
independently.
Args:
results: List of regex search result dicts
Returns:
Modified results list with truncation applied to regex fields
"""
payload_cache = getattr(app_module.app.state, "payload_cache", None)
if payload_cache is None:
return results
preview_size = payload_cache.config.preview_size_chars
for result_dict in results:
# AC1: Handle line_content field
await _truncate_regex_field(
result_dict, "line_content", payload_cache, preview_size, is_list=False
)
# AC2: Handle context_before field (list of strings)
await _truncate_regex_field(
result_dict, "context_before", payload_cache, preview_size, is_list=True
)
# AC2: Handle context_after field (list of strings)
await _truncate_regex_field(
result_dict, "context_after", payload_cache, preview_size, is_list=True
)
return results
async def _truncate_field(
container: Dict[str, Any],
field_name: str,
payload_cache,
preview_size: int,
log_context: str = "field",
) -> None:
"""Truncate a single field if it exceeds preview_size (Story #681 helper).
Args:
container: Dict containing the field to truncate
field_name: Name of the field (e.g., "content", "diff")
payload_cache: PayloadCache instance for storing large content
preview_size: Maximum chars before truncation
log_context: Context string for warning messages
"""
value = container.get(field_name)
if value is None:
return
try:
if len(value) > preview_size:
cache_handle = await payload_cache.store(value)
container[f"{field_name}_preview"] = value[:preview_size]
container[f"{field_name}_cache_handle"] = cache_handle
container[f"{field_name}_has_more"] = True
container[f"{field_name}_total_size"] = len(value)
del container[field_name]
else:
container[f"{field_name}_cache_handle"] = None
container[f"{field_name}_has_more"] = False
except Exception as e:
logger.warning(
f"Failed to truncate {log_context}: {e}",
extra={"correlation_id": get_correlation_id()},
)
container[f"{field_name}_cache_handle"] = None
container[f"{field_name}_has_more"] = False
async def _apply_temporal_payload_truncation(
results: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Apply payload truncation to temporal search results (Story #681).
Truncates large content fields with preview + cache_handle pattern.
Args:
results: List of temporal search result dicts
Returns:
Modified results with truncation applied to content and evolution entries
"""
payload_cache = getattr(app_module.app.state, "payload_cache", None)
if payload_cache is None:
return results
preview_size = payload_cache.config.preview_size_chars
for result_dict in results:
# AC1: Handle main content field
await _truncate_field(
result_dict, "content", payload_cache, preview_size, "temporal content"
)
# Handle code_snippet field (temporal results use QueryResult.to_dict() format)
await _truncate_field(
result_dict,
"code_snippet",
payload_cache,
preview_size,
"temporal code_snippet",
)
# AC2/AC3: Handle temporal_context.evolution entries
temporal_context = result_dict.get("temporal_context")
if temporal_context and "evolution" in temporal_context:
for entry in temporal_context["evolution"]:
await _truncate_field(
entry, "content", payload_cache, preview_size, "evolution content"
)
await _truncate_field(
entry, "diff", payload_cache, preview_size, "evolution diff"
)
return results
async def _apply_scip_payload_truncation(
results: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Apply payload truncation to SCIP query results (Story #685).
For SCIP results with large context fields (> preview_size_chars), replaces
context with context_preview + context_cache_handle. This reduces response
size while allowing clients to fetch full context on demand.
Args:
results: List of SCIP result dicts with optional 'context' field
Returns:
Modified results list with truncation applied to context fields
"""
payload_cache = getattr(app_module.app.state, "payload_cache", None)
if payload_cache is None:
# Cache not available, return results unchanged
return results
preview_size = payload_cache.config.preview_size_chars
for result_dict in results:
context = result_dict.get("context")
# Handle missing context field
if "context" not in result_dict:
result_dict["context_cache_handle"] = None
result_dict["context_has_more"] = False
continue
# Handle None context
if context is None:
result_dict["context_cache_handle"] = None
result_dict["context_has_more"] = False
continue
try:
if len(context) > preview_size:
# Large context: store full content and replace with preview
cache_handle = await payload_cache.store(context)
result_dict["context_preview"] = context[:preview_size]
result_dict["context_cache_handle"] = cache_handle
result_dict["context_has_more"] = True
result_dict["context_total_size"] = len(context)
del result_dict["context"]
else:
# Small context: keep as-is, add metadata
result_dict["context_cache_handle"] = None
result_dict["context_has_more"] = False
except Exception as e:
logger.warning(
f"Failed to truncate SCIP context: {e}",
extra={"correlation_id": get_correlation_id()},
)
# Keep original context on error, add metadata
result_dict["context_cache_handle"] = None
result_dict["context_has_more"] = False
return results
def _error_with_suggestions(
error_msg: str,
attempted_value: str,
available_values: List[str],
max_suggestions: int = 3,
) -> Dict[str, Any]:
"""Create structured error response with fuzzy-matched suggestions.
Args:
error_msg: The error message to include
attempted_value: The value the user tried (e.g., "myrepo-gloabl")
available_values: List of valid values to match against
max_suggestions: Maximum number of suggestions to return
Returns:
Structured error envelope with suggestions and available_values
"""
# Use difflib for fuzzy matching
suggestions = difflib.get_close_matches(
attempted_value,
available_values,
n=max_suggestions,
cutoff=0.6, # 60% similarity threshold
)
return {
"success": False,
"error": error_msg,
"suggestions": suggestions,
"available_values": available_values[:10], # Limit to prevent huge responses
}
def _get_available_repos() -> List[str]:
"""Get list of available global repository aliases for suggestions."""
try:
golden_repos_dir = _get_golden_repos_dir()
registry = get_server_global_registry(golden_repos_dir)
return [r["alias_name"] for r in registry.list_global_repos()]
except Exception:
return []
def _format_omni_response(
all_results: List[Dict[str, Any]],
response_format: str,
total_repos_searched: int,
errors: Dict[str, str],
cursor: Optional[str] = None,
) -> Dict[str, Any]:
"""Format omni-search results based on response_format parameter.
Args:
all_results: Flat list of results with source_repo field
response_format: "flat" or "grouped"
total_repos_searched: Number of repos successfully searched
errors: Dict of repo alias -> error message for failed repos
cursor: Optional cursor for pagination
Returns:
Formatted response dict
"""
base_response: Dict[str, Any] = {
"success": True,
"total_repos_searched": total_repos_searched,
"errors": errors,
}
if cursor:
base_response["cursor"] = cursor
if response_format == "grouped":
results_by_repo: Dict[str, Dict[str, Any]] = {}
for result in all_results:
repo = result.get("source_repo", "unknown")
if repo not in results_by_repo:
results_by_repo[repo] = {"count": 0, "results": []}
results_by_repo[repo]["count"] += 1
results_by_repo[repo]["results"].append(result)
base_response["results_by_repo"] = results_by_repo
base_response["total_results"] = len(all_results)
else:
base_response["results"] = all_results
base_response["total_results"] = len(all_results)
return base_response
def _is_temporal_query(params: Dict[str, Any]) -> bool:
"""Check if query includes temporal parameters.
Returns True if any temporal search parameters are present and truthy.
"""
temporal_params = ["time_range", "time_range_all", "at_commit", "include_removed"]
return any(params.get(p) for p in temporal_params)
def _get_temporal_status(repo_aliases: List[str]) -> Dict[str, Any]:
"""Get temporal indexing status for each repository.
Args:
repo_aliases: List of repository aliases to check
Returns:
Dict with temporal_repos, non_temporal_repos, and optional warning
"""
try:
golden_repos_dir = _get_golden_repos_dir()
registry = get_server_global_registry(golden_repos_dir)
all_repos = {r["alias_name"]: r for r in registry.list_global_repos()}
temporal_repos = []
non_temporal_repos = []
for alias in repo_aliases:
if alias in all_repos:
if all_repos[alias].get("enable_temporal", False):
temporal_repos.append(alias)
else:
non_temporal_repos.append(alias)
status: Dict[str, Any] = {
"temporal_repos": temporal_repos,
"non_temporal_repos": non_temporal_repos,
}
if not temporal_repos and non_temporal_repos:
status["warning"] = (
"None of the searched repositories have temporal indexing enabled. "
"Temporal queries will return no results. "
"Re-index with --index-commits to enable temporal search."
)
return status
except Exception:
return {}
WILDCARD_CHARS = {"*", "?", "["}
def _has_wildcard(pattern: str) -> bool:
"""Check if pattern contains wildcard characters."""
return any(c in pattern for c in WILDCARD_CHARS)
def _validate_symbol_format(symbol: Optional[str], param_name: str) -> Optional[str]:
"""Validate symbol format for call chain queries.
Args:
symbol: The symbol string to validate (can be None)
param_name: Parameter name for error messages (e.g., "from_symbol", "to_symbol")
Returns:
None if valid, error message string if invalid
"""
if not symbol or not symbol.strip():
return f"{param_name} cannot be empty"
return None
def _expand_wildcard_patterns(patterns: List[str]) -> List[str]:
"""Expand wildcard patterns to matching repository aliases.
Args:
patterns: List of repo patterns (may include wildcards like '*-global')
Returns:
Expanded list of unique repository aliases
"""
golden_repos_dir = _get_golden_repos_dir()
if not golden_repos_dir:
logger.debug(
"No golden_repos_dir, returning patterns unchanged",
extra={"correlation_id": get_correlation_id()},
)
return patterns
# Get available repos
try:
registry = get_server_global_registry(golden_repos_dir)
available_repos = [r["alias_name"] for r in registry.list_global_repos()]
except Exception as e:
logger.warning(
f"Failed to list global repos for wildcard expansion: {e}",
extra={"correlation_id": get_correlation_id()},
)
return patterns
expanded = []
for pattern in patterns:
if _has_wildcard(pattern):
# Expand wildcard using pathspec (gitignore-style matching)
# This correctly handles ** as "zero or more directories"
spec = pathspec.PathSpec.from_lines("gitwildmatch", [pattern])
matches = [repo for repo in available_repos if spec.match_file(repo)]
if matches:
logger.debug(
f"Expanded wildcard '{pattern}' -> {matches}",
extra={"correlation_id": get_correlation_id()},
)
expanded.extend(matches)
else:
logger.warning(
f"Wildcard pattern '{pattern}' matched no repositories",
extra={"correlation_id": get_correlation_id()},
)
else:
# Keep literal pattern
expanded.append(pattern)
# Deduplicate while preserving order
seen = set()
result = []
for repo in expanded:
if repo not in seen:
seen.add(repo)
result.append(repo)
return result
async def _omni_search_code(params: Dict[str, Any], user: User) -> Dict[str, Any]:
"""Handle omni-search across multiple repositories.
Called when repository_alias is an array of repository names.
Aggregates results from all specified repos, sorted by score.
"""
import json as json_module
repo_aliases = params.get("repository_alias", [])
repo_aliases = _expand_wildcard_patterns(repo_aliases)
limit = params.get("limit", 10)
aggregation_mode = params.get("aggregation_mode", "global")
if not repo_aliases:
return _mcp_response(
{
"success": True,
"results": {
"cursor": "",
"total_results": 0,
"total_repos_searched": 0,
"results": [],
"errors": {},
},
}
)
all_results = []
errors = {}
repos_searched = 0
for repo_alias in repo_aliases:
try:
# Build single-repo params and call existing search_code
single_params = dict(params)
single_params["repository_alias"] = repo_alias
single_result = await search_code(single_params, user)
# Parse the MCP response to extract results
content = single_result.get("content", [])
if content and content[0].get("type") == "text":
result_data = json_module.loads(content[0]["text"])
if result_data.get("success"):
repos_searched += 1
results_list = result_data.get("results", {}).get("results", [])
# Tag each result with source repo
for r in results_list:
r["source_repo"] = repo_alias
all_results.extend(results_list)
else:
errors[repo_alias] = result_data.get("error", "Unknown error")
except Exception as e:
errors[repo_alias] = str(e)
logger.warning(
f"Omni-search failed for {repo_alias}: {e}",
extra={"correlation_id": get_correlation_id()},
)
# Aggregate results based on mode
if aggregation_mode == "per_repo":
# Per-repo mode: take proportional results from each repo
from collections import defaultdict
results_by_repo = defaultdict(list)
for r in all_results:
results_by_repo[r.get("source_repo", "unknown")].append(r)
# Sort each repo's results by score
for repo in results_by_repo:
results_by_repo[repo].sort(
key=lambda x: x.get("similarity_score", 0), reverse=True
)
# Take proportional results from each repo
num_repos = len(results_by_repo)
if num_repos > 0:
per_repo_limit = limit // num_repos
remainder = limit % num_repos
final_results = []
for i, (repo, results) in enumerate(results_by_repo.items()):
# Give first 'remainder' repos one extra result
repo_limit = per_repo_limit + (1 if i < remainder else 0)
final_results.extend(results[:repo_limit])
else:
final_results = []
else:
# Global mode: sort all by score, take top N
all_results.sort(key=lambda x: x.get("similarity_score", 0), reverse=True)
final_results = all_results[:limit]
# Get response_format parameter (default to "flat" for backward compatibility)
response_format = params.get("response_format", "flat")
# Story #683: Apply payload truncation to aggregated multi-repo results
# This ensures consistency with REST API which calls _apply_multi_truncation()
search_mode = params.get("search_mode", "semantic")
if final_results:
if search_mode in ["fts", "hybrid"]:
final_results = await _apply_fts_payload_truncation(final_results)
elif _is_temporal_query(params):
final_results = await _apply_temporal_payload_truncation(final_results)
else:
final_results = await _apply_payload_truncation(final_results)
# Use _format_omni_response helper to format results
formatted = _format_omni_response(
all_results=final_results,
response_format=response_format,
total_repos_searched=repos_searched,
errors=errors,
cursor="",
)
# Add temporal_status if this is a temporal query (Story #583)
if _is_temporal_query(params):
temporal_status = _get_temporal_status(repo_aliases)
if temporal_status:
formatted["temporal_status"] = temporal_status
# Wrap in nested "results" key for backward compatibility with existing API contract
return _mcp_response(
{
"success": True,
"results": formatted,
}
)
async def search_code(params: Dict[str, Any], user: User) -> Dict[str, Any]:
"""Search code using semantic search, FTS, or hybrid mode."""
try:
from pathlib import Path
repository_alias = params.get("repository_alias")
# Handle JSON string arrays (from MCP clients that serialize arrays as strings)
repository_alias = _parse_json_string_array(repository_alias)
params["repository_alias"] = repository_alias # Update params for downstream
# Route to omni-search when repository_alias is an array
if isinstance(repository_alias, list):
return await _omni_search_code(params, user)
# Check if this is a global repository query (ends with -global suffix)
if repository_alias and repository_alias.endswith("-global"):
# Global repository: query directly without activation requirement
golden_repos_dir = _get_golden_repos_dir()
# Look up global repo in GlobalRegistry to get actual path
registry = get_server_global_registry(golden_repos_dir)
global_repos = registry.list_global_repos()
# Find the matching global repo
repo_entry = next(
(r for r in global_repos if r["alias_name"] == repository_alias), None
)
if not repo_entry:
available_repos = _get_available_repos()
error_envelope = _error_with_suggestions(
error_msg=f"Global repository '{repository_alias}' not found",
attempted_value=repository_alias,
available_values=available_repos,
)
error_envelope["results"] = []
return _mcp_response(error_envelope)
# Use AliasManager to get current target path (registry path becomes stale after refresh)
from code_indexer.global_repos.alias_manager import AliasManager
alias_manager = AliasManager(str(Path(golden_repos_dir) / "aliases"))
target_path = alias_manager.read_alias(repository_alias)
if not target_path:
available_repos = _get_available_repos()
error_envelope = _error_with_suggestions(
error_msg=f"Alias for '{repository_alias}' not found",
attempted_value=repository_alias,
available_values=available_repos,
)
error_envelope["results"] = []
return _mcp_response(error_envelope)
global_repo_path = Path(target_path)
# Verify global repo exists
if not global_repo_path.exists():
raise FileNotFoundError(
f"Global repository '{repository_alias}' not found at {global_repo_path}"
)
# Build mock repository list for _perform_search (single global repo)
mock_user_repos = [
{
"user_alias": repository_alias,
"repo_path": str(global_repo_path),
"actual_repo_id": repo_entry["repo_name"],
}
]
# Call _perform_search directly with all query parameters
# Track query execution with QueryTracker for concurrency safety
import time
query_tracker = _get_query_tracker()
index_path = target_path # Use resolved path for tracking
start_time = time.time()
try:
# Increment ref count before query (if QueryTracker available)
if query_tracker is not None:
query_tracker.increment_ref(index_path)
results = app_module.semantic_query_manager._perform_search(
username=user.username,
user_repos=mock_user_repos,
query_text=params["query_text"],
limit=params.get("limit", 10),
min_score=params.get("min_score", 0.5),
file_extensions=params.get("file_extensions"),
language=params.get("language"),
exclude_language=params.get("exclude_language"),
path_filter=params.get("path_filter"),
exclude_path=params.get("exclude_path"),
accuracy=params.get("accuracy", "balanced"),
# Search mode (Story #503 - FTS Bug Fix)
search_mode=params.get("search_mode", "semantic"),
# Temporal query parameters (Story #446)
time_range=params.get("time_range"),
time_range_all=params.get("time_range_all", False),
at_commit=params.get("at_commit"),
include_removed=params.get("include_removed", False),
show_evolution=params.get("show_evolution", False),
evolution_limit=params.get("evolution_limit"),
# FTS-specific parameters (Story #503 Phase 2)
case_sensitive=params.get("case_sensitive", False),
fuzzy=params.get("fuzzy", False),
edit_distance=params.get("edit_distance", 0),
snippet_lines=params.get("snippet_lines", 5),
regex=params.get("regex", False),
# Temporal filtering parameters (Story #503 Phase 3)
diff_type=params.get("diff_type"),
author=params.get("author"),
chunk_type=params.get("chunk_type"),
)
execution_time_ms = int((time.time() - start_time) * 1000)
timeout_occurred = False
except TimeoutError as e:
execution_time_ms = int((time.time() - start_time) * 1000)
timeout_occurred = True
raise Exception(f"Query timed out: {str(e)}")
except Exception as e:
execution_time_ms = int((time.time() - start_time) * 1000)
if "timeout" in str(e).lower():
raise Exception(f"Query timed out: {str(e)}")
raise
finally:
# Always decrement ref count when query completes (if QueryTracker available)
if query_tracker is not None:
query_tracker.decrement_ref(index_path)
# Build response matching query_user_repositories format
response_results = []
for r in results:
result_dict = r.to_dict()
result_dict["source_repo"] = (
repository_alias # Fix: Set source_repo for single-repo searches
)
response_results.append(result_dict)
# Apply payload truncation based on search mode
search_mode = params.get("search_mode", "semantic")
if search_mode in ["fts", "hybrid"]:
# Story #680: FTS truncation for code_snippet and match_text
response_results = await _apply_fts_payload_truncation(response_results)
# Story #681: Temporal truncation for temporal queries
if _is_temporal_query(params):
response_results = await _apply_temporal_payload_truncation(