-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_v2.py
More file actions
1986 lines (1792 loc) · 76.9 KB
/
mcp_v2.py
File metadata and controls
1986 lines (1792 loc) · 76.9 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 V2 graph query surface (``search`` / ``find`` / ``describe`` / ``neighbors`` / ``resolve``).
Strict frame contract
---------------------
NodeFilter is a typed predicate bag: each populated field maps to one stored graph
attribute for the selected kind; inapplicable fields fail loud with a teaching message.
The ``search`` tool's ``query`` parameter is the ranked-text carve-out; structured
prefix fields (``fqn_prefix``, ``path_prefix``, ``target_path_prefix``) reject ``*``
and ``?`` — see ``_validate_no_wildcards``.
Revisit trigger (``propose/completed/MCP-FILTER-FRAME-PROPOSE.md`` section 3.4.6)
--------------------------------------------------------------
If **three** legitimate issue-tracker workflows appear within **six months** of frame
lock where the strict frame has no clean analog under ``search``, deferred
``resolve``, or documented multi-call patterns, reopen the frame for revision.
"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
import threading
from typing import Annotated, Any, Literal, get_args
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError, model_validator, validate_call
from sentence_transformers import SentenceTransformer
from index_common import SBERT_MODEL
from java_codebase_rag.config import resolved_sbert_model_for_process_env
from java_ontology import EDGE_SCHEMA, ResolveReason
from kuzu_queries import KuzuGraph, OVERRIDE_AXIS_COMPOSED_EDGE_TYPES
from mcp_hints import generate_hints, MCP_HINTS_STRUCTURED_FIELD_DESCRIPTION
from search_lancedb import TABLES, run_search
DeclarationSymbolKind = Literal["class", "interface", "enum", "record", "annotation", "method", "constructor"]
# Stored graph edge labels for one-hop neighbors. Composed DECLARES.* and OVERRIDDEN_BY.*
# dot-keys are separate ComposedEdgeType literals (2-hop traversal). Stored OVERRIDES is an EdgeType.
EdgeType = Literal[
"EXTENDS",
"IMPLEMENTS",
"INJECTS",
"OVERRIDES",
"DECLARES",
"DECLARES_CLIENT",
"DECLARES_PRODUCER",
"CALLS",
"EXPOSES",
"HTTP_CALLS",
"ASYNC_CALLS",
]
ComposedEdgeType = Literal[
"DECLARES.DECLARES_CLIENT",
"DECLARES.DECLARES_PRODUCER",
"DECLARES.EXPOSES",
"OVERRIDDEN_BY",
"OVERRIDDEN_BY.DECLARES_CLIENT",
"OVERRIDDEN_BY.DECLARES_PRODUCER",
"OVERRIDDEN_BY.EXPOSES",
]
NeighborEdgeType = EdgeType | ComposedEdgeType
_COMPOSED_EDGE_TYPES = frozenset(get_args(ComposedEdgeType))
_MEMBER_COMPOSED_EDGE_TYPES = frozenset(
k for k in _COMPOSED_EDGE_TYPES if k.startswith("DECLARES.")
)
_OVERRIDE_COMPOSED_EDGE_TYPES = OVERRIDE_AXIS_COMPOSED_EDGE_TYPES
_NEIGHBOR_EDGE_TYPES_ADAPTER = TypeAdapter(
Annotated[
list[NeighborEdgeType],
Field(min_length=1, description="At least one graph edge label or DECLARES.* dot-key"),
]
)
_st_lock = threading.Lock()
_st_model: SentenceTransformer | None = None
_TYPE_SYMBOL_KINDS_FOR_EDGE_ROLLUP = frozenset(
{"class", "interface", "enum", "record", "annotation"}
)
_METHOD_SYMBOL_KINDS_FOR_OVERRIDE_ROLLUP = frozenset({"method"})
_fail_loud_counts: dict[str, int] = {}
_fail_loud_lock = threading.Lock()
def _log_fail_loud(category: str) -> None:
"""Increment process-local fail-loud counter and emit one stderr line (PR-FRAME-3)."""
with _fail_loud_lock:
_fail_loud_counts[category] = _fail_loud_counts.get(category, 0) + 1
n = _fail_loud_counts[category]
print(f"[filter-frame] fail-loud category={category} count={n}", file=sys.stderr, flush=True)
def filter_frame_counters() -> dict[str, int]:
"""Snapshot of fail-loud counts (tests / local diagnostics; not an MCP tool)."""
with _fail_loud_lock:
return dict(_fail_loud_counts)
def _get_sentence_transformer(model_name: str, device: str | None) -> SentenceTransformer:
global _st_model
with _st_lock:
if _st_model is None:
_st_model = SentenceTransformer(
model_name,
device=device,
trust_remote_code=True,
)
return _st_model
class NodeFilter(BaseModel):
model_config = ConfigDict(extra="forbid")
microservice: str | None = None
module: str | None = None
source_layer: str | None = None
role: str | None = None
exclude_roles: list[str] | None = None
annotation: str | None = None
capability: str | None = None
fqn_prefix: str | None = None
symbol_kind: DeclarationSymbolKind | None = None
symbol_kinds: list[DeclarationSymbolKind] | None = None
http_method: str | None = None
path_prefix: str | None = None
framework: str | None = None
client_kind: str | None = None
target_service: str | None = None
target_path_prefix: str | None = None
producer_kind: str | None = None
topic_prefix: str | None = None
class EdgeFilter(BaseModel):
model_config = ConfigDict(extra="forbid")
min_confidence: float | None = None
exclude_strategies: list[str] | None = None
include_strategies: list[str] | None = None
callee_declaring_role: str | None = None
callee_declaring_roles: list[str] | None = None
exclude_callee_declaring_roles: list[str] | None = None
@model_validator(mode="after")
def _strategy_axes_mutually_exclusive(self) -> EdgeFilter:
has_include = bool(self.include_strategies)
has_exclude = bool(self.exclude_strategies)
if has_include and has_exclude:
raise ValueError("include_strategies and exclude_strategies are mutually exclusive")
return self
@model_validator(mode="after")
def _role_axes_mutually_exclusive(self) -> EdgeFilter:
role_axes = (
self.callee_declaring_role is not None,
bool(self.callee_declaring_roles),
bool(self.exclude_callee_declaring_roles),
)
if sum(role_axes) > 1:
raise ValueError(
"callee_declaring_role, callee_declaring_roles, and "
"exclude_callee_declaring_roles are mutually exclusive"
)
return self
_NODEFILTER_FIELD_ORDER: tuple[str, ...] = tuple(NodeFilter.model_fields.keys())
_EDGEFILTER_FIELD_ORDER: tuple[str, ...] = tuple(EdgeFilter.model_fields.keys())
class StructuredHint(BaseModel):
label: str = ""
tool: Literal["search", "find", "describe", "neighbors", "resolve"]
args: dict[str, Any]
actionable: bool = True
reason: str = ""
# Populated EdgeFilter field -> EDGE_SCHEMA attribute name used in Cypher pushdown.
_EDGEFILTER_FIELD_TO_ATTR: dict[str, str] = {
"min_confidence": "confidence",
"exclude_strategies": "strategy",
"include_strategies": "strategy",
"callee_declaring_role": "callee_declaring_role",
"callee_declaring_roles": "callee_declaring_role",
"exclude_callee_declaring_roles": "callee_declaring_role",
}
_ROLE_FILTER_OTHER_FALLBACK_VALUES = frozenset({"SERVICE", "REPOSITORY"})
_NODEFILTER_APPLICABLE_FIELDS: dict[Literal["symbol", "route", "client", "producer"], tuple[str, ...]] = {
"symbol": (
"microservice",
"module",
"role",
"exclude_roles",
"annotation",
"capability",
"fqn_prefix",
"symbol_kind",
"symbol_kinds",
),
"route": (
"microservice",
"module",
"http_method",
"path_prefix",
"framework",
),
"client": (
"microservice",
"module",
"source_layer",
"client_kind",
"target_service",
"target_path_prefix",
"http_method",
),
"producer": (
"microservice",
"module",
"source_layer",
"producer_kind",
"topic_prefix",
),
}
def _ordered_nodefilter_fields(field_names: set[str]) -> list[str]:
return [name for name in _NODEFILTER_FIELD_ORDER if name in field_names]
def _populated_nodefilter_fields(nf: NodeFilter) -> set[str]:
populated: set[str] = set()
for field_name in _NODEFILTER_FIELD_ORDER:
value = getattr(nf, field_name)
if value is None:
continue
if isinstance(value, list) and not value:
continue
populated.add(field_name)
return populated
def _nodefilter_inapplicable_fields(
kind: Literal["symbol", "route", "client", "producer"], nf: NodeFilter,
) -> list[str]:
populated = _populated_nodefilter_fields(nf)
applicable = set(_NODEFILTER_APPLICABLE_FIELDS[kind])
return _ordered_nodefilter_fields(populated - applicable)
def _nodefilter_applicability_error(
kind: Literal["symbol", "route", "client", "producer"], nf: NodeFilter,
) -> str | None:
inapplicable = _nodefilter_inapplicable_fields(kind, nf)
if not inapplicable:
return None
applicable = ", ".join(_NODEFILTER_APPLICABLE_FIELDS[kind])
bad = ", ".join(inapplicable)
return (
f"Invalid filter for kind='{kind}': populated field(s) not applicable: [{bad}]. "
f"Applicable field(s): [{applicable}]"
)
def _validate_no_wildcards(nf: NodeFilter) -> str | None:
"""Reject ``*`` / ``?`` in prefix-match fields; wildcards belong in ``search(query=…)``."""
for field_name in ("fqn_prefix", "path_prefix", "target_path_prefix"):
val = getattr(nf, field_name)
if val is None:
continue
if "*" in val or "?" in val:
return (
f"Wildcards (* and ?) are not supported in structured filter field `{field_name}`; "
"use search(query=...) for ranked text match instead."
)
return None
def _filter_validation_error_message(exc: ValidationError) -> str:
items: list[str] = []
for err in exc.errors():
loc = ".".join(str(part) for part in err.get("loc", ()))
msg = str(err.get("msg") or "invalid value")
if loc:
items.append(f"{loc}: {msg}")
else:
items.append(msg)
details = "; ".join(items) if items else str(exc)
return f"Invalid filter: {details}"
def _populated_edgefilter_fields(ef: EdgeFilter) -> set[str]:
populated: set[str] = set()
for field_name in _EDGEFILTER_FIELD_ORDER:
value = getattr(ef, field_name)
if value is None:
continue
if isinstance(value, list) and not value:
continue
populated.add(field_name)
return populated
def _edge_schema_attr_names(edge_type: str) -> set[str]:
spec = EDGE_SCHEMA.get(edge_type)
if spec is None:
return set()
return {attr.name for attr in spec.attrs}
def _edgefilter_applicability_error(edge_types: list[str], ef: EdgeFilter) -> str | None:
populated = _populated_edgefilter_fields(ef)
if not populated:
return None
flat_types = [et for et in edge_types if et not in _COMPOSED_EDGE_TYPES]
composed = [et for et in edge_types if et in _COMPOSED_EDGE_TYPES]
if composed or flat_types != ["CALLS"]:
parts: list[str] = []
if flat_types != ["CALLS"]:
parts.append(f"stored labels {flat_types!r}")
if composed:
parts.append(f"composed keys {composed!r}")
detail = " and ".join(parts) if parts else "requested edge_types"
return (
f"edge_filter requires edge_types=['CALLS'] only; {detail} is not supported — "
"split into separate neighbors calls"
)
for edge_type in flat_types:
available = _edge_schema_attr_names(edge_type)
for field_name in _EDGEFILTER_FIELD_ORDER:
if field_name not in populated:
continue
attr = _EDGEFILTER_FIELD_TO_ATTR[field_name]
if attr not in available:
return (
f"{attr} is not on {edge_type}; restrict edge_types to ['CALLS'] "
"or split into two neighbors_v2 calls"
)
return None
def _to_structured_hints(raw: list[Any]) -> list[StructuredHint]:
return [StructuredHint(label=h.label, tool=h.tool, args=h.args, actionable=h.actionable, reason=h.reason) for h in raw]
def _coerce_edge_filter(
value: EdgeFilter | dict[str, Any] | str | None,
) -> EdgeFilter | dict[str, Any] | None:
"""Normalize MCP tool input: weak clients sometimes pass JSON-encoded strings."""
if value is None or isinstance(value, EdgeFilter):
return value
if isinstance(value, str):
s = value.strip()
if not s:
return None
try:
decoded = json.loads(s)
except json.JSONDecodeError as exc:
raise ValueError(f"edge_filter must be a JSON object; invalid JSON: {exc.msg}") from exc
if decoded is None:
return None
if not isinstance(decoded, dict):
raise ValueError(
f"edge_filter must decode to a JSON object, got {type(decoded).__name__}"
)
return decoded
return value
def _coerce_filter(
value: NodeFilter | dict[str, Any] | str | None,
) -> NodeFilter | dict[str, Any] | None:
"""Normalize MCP tool input: weak clients sometimes pass JSON-encoded strings."""
if value is None or isinstance(value, NodeFilter):
return value
if isinstance(value, str):
s = value.strip()
if not s:
return None
try:
decoded = json.loads(s)
except json.JSONDecodeError as exc:
raise ValueError(f"filter must be a JSON object; invalid JSON: {exc.msg}") from exc
if decoded is None:
return None
if not isinstance(decoded, dict):
raise ValueError(f"filter must decode to a JSON object, got {type(decoded).__name__}")
return decoded
return value
class SearchHit(BaseModel):
chunk_id: str
symbol_id: str | None = None
fqn: str | None = None
score: float
snippet: str
microservice: str | None = None
module: str | None = None
role: str | None = None
class NodeRef(BaseModel):
id: str
kind: Literal["symbol", "route", "client", "producer", "unresolved_call_site"]
fqn: str
symbol_kind: str | None = None
microservice: str | None = None
module: str | None = None
role: str | None = None
class NodeRecord(BaseModel):
id: str
kind: Literal["symbol", "route", "client", "producer"]
fqn: str
data: dict[str, Any] = Field(default_factory=dict)
edge_summary: dict[str, dict[str, int]] | None = Field(
default=None,
description=(
"Per graph edge label, in/out incident counts. For type Symbols (class, interface, "
"enum, record, annotation), may also include composed dot-keys "
"`DECLARES.DECLARES_CLIENT`, `DECLARES.DECLARES_PRODUCER`, and `DECLARES.EXPOSES`: 2-hop summaries "
"(DECLARES to member, then that edge) — edge-row counts; navigable via neighbors for type "
"Symbol origins (`direction=\"out\"` only). For non-static method Symbols, may include "
"override-axis virtual keys `OVERRIDDEN_BY`, `OVERRIDDEN_BY.DECLARES_CLIENT`, "
"`OVERRIDDEN_BY.DECLARES_PRODUCER`, `OVERRIDDEN_BY.EXPOSES` (stored `[:OVERRIDES]` "
"dispatch hop, then terminal edges; navigable via neighbors for method Symbol origins, "
"`direction=\"out\"` only; composed results include `via_id` in attrs). Plus an "
"`OVERRIDES` map entry that **merges** stored `[:OVERRIDES]` in/out counts with the "
"describe-time dispatch-up rollup (per direction `max`, so inbound stored overrides "
"are not dropped). The stored relationship label `OVERRIDES` **is** also a valid "
"EdgeType for one-hop neighbors (`direction=\"in\"` from declaration toward overriders)."
),
)
class Edge(BaseModel):
origin_id: str
edge_type: str
direction: Literal["in", "out"]
other: NodeRef
attrs: dict[str, Any] = Field(default_factory=dict)
class SearchOutput(BaseModel):
success: bool
results: list[SearchHit] = Field(default_factory=list)
message: str | None = None
limit: int | None = Field(
default=None,
description="Echoed from the request — the page size the server applied. None on success=False.",
)
offset: int | None = Field(
default=None,
description="Echoed from the request — the page offset the server applied. None on success=False.",
)
advisories: list[str] = Field(default_factory=list, description="Pure informational text with no tool call suggestion")
hints_structured: list[StructuredHint] = Field(default_factory=list, description=MCP_HINTS_STRUCTURED_FIELD_DESCRIPTION)
class FindOutput(BaseModel):
success: bool
results: list[NodeRef] = Field(default_factory=list)
message: str | None = None
limit: int | None = Field(
default=None,
description="Echoed from the request — the page size the server applied. None on success=False.",
)
offset: int | None = Field(
default=None,
description="Echoed from the request — the page offset the server applied. None on success=False.",
)
advisories: list[str] = Field(default_factory=list, description="Pure informational text with no tool call suggestion")
hints_structured: list[StructuredHint] = Field(default_factory=list, description=MCP_HINTS_STRUCTURED_FIELD_DESCRIPTION)
class DescribeOutput(BaseModel):
success: bool
record: NodeRecord | None = None
message: str | None = None
advisories: list[str] = Field(default_factory=list, description="Pure informational text with no tool call suggestion")
hints_structured: list[StructuredHint] = Field(default_factory=list, description=MCP_HINTS_STRUCTURED_FIELD_DESCRIPTION)
class NeighborsOutput(BaseModel):
success: bool
results: list[Edge] = Field(default_factory=list)
message: str | None = None
requested_edge_types: list[str] = Field(
default_factory=list,
description="Echo of neighbors(edge_types=...) from the request; empty when success=False.",
)
advisories: list[str] = Field(default_factory=list, description="Pure informational text with no tool call suggestion")
hints_structured: list[StructuredHint] = Field(default_factory=list, description=MCP_HINTS_STRUCTURED_FIELD_DESCRIPTION)
ResolveStatus = Literal["one", "many", "none"]
_RESOLVE_CANDIDATE_CAP = 10
_RESOLVE_REASON_PRIORITY: dict[ResolveReason, int] = {
"exact_id": 0,
"exact_fqn": 1,
"route_method_path": 1,
"client_target_path": 1,
"producer_topic_prefix": 1,
"fqn_suffix": 2,
"route_template": 2,
"short_name": 3,
"client_target": 3,
"producer_topic": 3,
}
_SYMBOL_RESOLVE_RETURN = (
"s.id AS id, s.fqn AS fqn, s.microservice AS microservice, "
"s.module AS module, s.role AS role, s.kind AS symbol_kind"
)
_ROUTE_RESOLVE_RETURN = (
"r.id AS id, r.kind AS kind, r.framework AS framework, r.method AS method, "
"r.path AS path, r.path_template AS path_template, r.path_regex AS path_regex, "
"r.topic AS topic, r.broker AS broker, r.feign_name AS feign_name, r.feign_url AS feign_url, "
"r.microservice AS microservice, r.module AS module, r.filename AS filename, "
"r.start_line AS start_line, r.end_line AS end_line, r.resolved AS resolved"
)
_CLIENT_RESOLVE_RETURN = (
"c.id AS id, c.client_kind AS client_kind, c.target_service AS target_service, "
"c.method AS method, c.path AS path, c.path_template AS path_template, "
"c.path_regex AS path_regex, c.member_fqn AS member_fqn, c.member_id AS member_id, "
"c.microservice AS microservice, c.module AS module, c.filename AS filename, "
"c.start_line AS start_line, c.end_line AS end_line, c.resolved AS resolved, "
"c.source_layer AS source_layer"
)
_PRODUCER_RESOLVE_RETURN = (
"p.id AS id, p.producer_kind AS producer_kind, p.topic AS topic, p.broker AS broker, "
"p.direction AS direction, p.member_fqn AS member_fqn, p.member_id AS member_id, "
"p.microservice AS microservice, p.module AS module, p.filename AS filename, "
"p.start_line AS start_line, p.end_line AS end_line, p.resolved AS resolved, "
"p.source_layer AS source_layer"
)
_RESOLVE_PRE_DEDUP_LIMIT = 50
class ResolveCandidate(BaseModel):
model_config = ConfigDict(extra="forbid")
node: NodeRef
score: float
reason: ResolveReason
class ResolveOutput(BaseModel):
model_config = ConfigDict(extra="forbid")
success: bool
status: ResolveStatus
node: NodeRef | None = None
candidates: list[ResolveCandidate] = Field(default_factory=list)
message: str | None = None
resolved_identifier: str | None = None
advisories: list[str] = Field(default_factory=list, description="Pure informational text with no tool call suggestion")
hints_structured: list[StructuredHint] = Field(default_factory=list, description=MCP_HINTS_STRUCTURED_FIELD_DESCRIPTION)
def _node_kind_from_id(
id_str: str,
) -> Literal["symbol", "route", "client", "producer", "unresolved_call_site"]:
if id_str.startswith("ucs:"):
return "unresolved_call_site"
if id_str.startswith("sym:"):
return "symbol"
if id_str.startswith("route:") or id_str.startswith("r:"):
return "route"
if id_str.startswith("client:") or id_str.startswith("c:"):
return "client"
if id_str.startswith("producer:") or id_str.startswith("p:"):
return "producer"
raise ValueError(f"Unknown id prefix for `{id_str}`")
def _resolve_node_kind(
graph: KuzuGraph,
node_id: str,
) -> Literal["symbol", "route", "client", "producer", "unresolved_call_site"]:
try:
return _node_kind_from_id(node_id)
except ValueError:
pass
if graph._rows("MATCH (n:Symbol) WHERE n.id = $id RETURN n.id AS id LIMIT 1", {"id": node_id}): # noqa: SLF001
return "symbol"
if graph._rows("MATCH (n:Route) WHERE n.id = $id RETURN n.id AS id LIMIT 1", {"id": node_id}): # noqa: SLF001
return "route"
if graph._rows("MATCH (n:Client) WHERE n.id = $id RETURN n.id AS id LIMIT 1", {"id": node_id}): # noqa: SLF001
return "client"
if graph._rows("MATCH (n:Producer) WHERE n.id = $id RETURN n.id AS id LIMIT 1", {"id": node_id}): # noqa: SLF001
return "producer"
raise ValueError(f"Unknown id prefix for `{node_id}`")
def _chunk_id_from_row(row: dict[str, Any]) -> str:
filename = str(row.get("filename") or "")
start = row.get("start") or {}
end = row.get("end") or {}
sb = int(start.get("byte_offset") or 0) if isinstance(start, dict) else 0
eb = int(end.get("byte_offset") or 0) if isinstance(end, dict) else 0
return f"{filename}:{sb}:{eb}"
def _row_to_search_hit(row: dict[str, Any]) -> SearchHit:
score = float(row.get("_rrf_score") or row.get("_score") or 0.0)
return SearchHit(
chunk_id=_chunk_id_from_row(row),
symbol_id=_chunk_to_symbol_id(row),
fqn=str(row.get("primary_type_fqn")) if row.get("primary_type_fqn") else None,
score=score,
snippet=str(row.get("text") or ""),
microservice=str(row.get("microservice")) if row.get("microservice") else None,
module=str(row.get("module")) if row.get("module") else None,
role=str(row.get("role")) if row.get("role") else None,
)
def _chunk_to_symbol_id(chunk_row: dict[str, Any]) -> str | None:
symbol_id = chunk_row.get("symbol_id")
if symbol_id:
return str(symbol_id)
meta = chunk_row.get("metadata")
if isinstance(meta, str):
try:
parsed = json.loads(meta)
if isinstance(parsed, dict):
meta = parsed
except Exception:
meta = None
if isinstance(meta, dict):
nested = meta.get("symbol_id")
if nested:
return str(nested)
return None
def _symbol_where_from_filter(f: NodeFilter) -> tuple[str, dict[str, Any]]:
preds: list[str] = []
params: dict[str, Any] = {}
if f.microservice:
preds.append("s.microservice = $microservice")
params["microservice"] = f.microservice
if f.module:
preds.append("s.module = $module")
params["module"] = f.module
if f.role:
preds.append("s.role = $role")
params["role"] = f.role
if f.exclude_roles:
preds.append("NOT s.role IN $exclude_roles")
params["exclude_roles"] = list(f.exclude_roles)
if f.annotation:
preds.append("list_contains(s.annotations, $annotation)")
params["annotation"] = f.annotation
if f.capability:
preds.append("$capability IN s.capabilities")
params["capability"] = f.capability
if f.fqn_prefix:
preds.append("s.fqn STARTS WITH $fqn_prefix")
params["fqn_prefix"] = f.fqn_prefix
if f.symbol_kind:
preds.append("s.kind = $symbol_kind")
params["symbol_kind"] = f.symbol_kind
if f.symbol_kinds:
preds.append("s.kind IN $symbol_kinds")
params["symbol_kinds"] = list(f.symbol_kinds)
where = f"WHERE {' AND '.join(preds)}" if preds else ""
return where, params
def _node_ref_from_row(kind: Literal["symbol", "route", "client", "producer"], row: dict[str, Any]) -> NodeRef:
symbol_kind: str | None = None
if kind == "symbol":
fqn = str(row.get("fqn") or "")
role = str(row.get("role") or "") or None
symbol_kind_val = str(row.get("symbol_kind") or row.get("kind") or "").strip()
symbol_kind = symbol_kind_val or None
elif kind == "route":
method = str(row.get("method") or "")
path = str(row.get("path_template") or row.get("path") or "")
fqn = f"{method} {path}".strip()
role = None
elif kind == "client":
method = str(row.get("method") or "")
target = str(row.get("target_service") or "")
path = str(row.get("path_template") or row.get("path") or "")
fqn = f"{target} {method} {path}".strip()
role = None
else:
topic = str(row.get("topic") or "")
broker = str(row.get("broker") or "")
fqn = f"{topic} {broker}".strip()
role = None
return NodeRef(
id=str(row.get("id") or ""),
kind=kind,
fqn=fqn,
symbol_kind=symbol_kind,
microservice=str(row.get("microservice") or "") or None,
module=str(row.get("module") or "") or None,
role=role,
)
def _load_node_record(
graph: KuzuGraph, node_id: str, kind: Literal["symbol", "route", "client", "producer"],
) -> dict[str, Any] | None:
if kind == "symbol":
projection = (
"n.id AS id, n.kind AS kind, n.name AS name, n.fqn AS fqn, n.package AS package, "
"n.module AS module, n.microservice AS microservice, n.filename AS filename, "
"n.start_line AS start_line, n.end_line AS end_line, n.start_byte AS start_byte, "
"n.end_byte AS end_byte, n.modifiers AS modifiers, n.annotations AS annotations, "
"n.capabilities AS capabilities, n.role AS role, n.signature AS signature, "
"n.parent_id AS parent_id, n.resolved AS resolved"
)
label = "Symbol"
elif kind == "route":
projection = (
"n.id AS id, n.kind AS kind, n.framework AS framework, n.method AS method, n.path AS path, "
"n.path_template AS path_template, n.path_regex AS path_regex, n.topic AS topic, "
"n.broker AS broker, n.feign_name AS feign_name, n.feign_url AS feign_url, "
"n.microservice AS microservice, n.module AS module, n.filename AS filename, "
"n.start_line AS start_line, n.end_line AS end_line, n.resolved AS resolved"
)
label = "Route"
elif kind == "client":
projection = (
"n.id AS id, n.client_kind AS client_kind, n.target_service AS target_service, "
"n.method AS method, n.path AS path, n.path_template AS path_template, "
"n.path_regex AS path_regex, n.member_fqn AS member_fqn, n.member_id AS member_id, "
"n.microservice AS microservice, n.module AS module, n.filename AS filename, "
"n.start_line AS start_line, n.end_line AS end_line, n.resolved AS resolved, "
"n.source_layer AS source_layer"
)
label = "Client"
else:
projection = (
"n.id AS id, n.producer_kind AS producer_kind, n.topic AS topic, n.broker AS broker, "
"n.direction AS direction, n.member_fqn AS member_fqn, n.member_id AS member_id, "
"n.microservice AS microservice, n.module AS module, n.filename AS filename, "
"n.start_line AS start_line, n.end_line AS end_line, n.resolved AS resolved, "
"n.source_layer AS source_layer"
)
label = "Producer"
rows = graph._rows(f"MATCH (n:{label}) WHERE n.id = $id RETURN {projection}", {"id": node_id}) # noqa: SLF001
if not rows:
return None
return rows[0]
def _incident_counts(cell: dict[str, int] | None) -> dict[str, int]:
if not cell:
return {"in": 0, "out": 0}
return {"in": int(cell.get("in", 0)), "out": int(cell.get("out", 0))}
def _merge_overrides_edge_summary(
stored_before_rollups: dict[str, int],
summary_after_rollups: dict[str, dict[str, int]],
) -> None:
"""Reconcile `OVERRIDES` with `override_axis_rollup_for` without clobbering stored `in`.
Rollup rows reuse the ``OVERRIDES`` key for dispatch-up counts only (``in`` is always
zero there). Stored ``[:OVERRIDES]`` edges contribute real ``in``/``out`` from Kuzu;
merge per direction with ``max`` so inbound override edges stay visible.
"""
roll = _incident_counts(summary_after_rollups.get("OVERRIDES"))
if "OVERRIDES" not in summary_after_rollups and not any(stored_before_rollups.values()):
return
merged_in = max(stored_before_rollups["in"], roll["in"])
merged_out = max(stored_before_rollups["out"], roll["out"])
if merged_in == 0 and merged_out == 0:
summary_after_rollups.pop("OVERRIDES", None)
else:
summary_after_rollups["OVERRIDES"] = {"in": merged_in, "out": merged_out}
def _edge_summary_for_node(
graph: KuzuGraph, node_id: str, *, kind: str, row: dict[str, Any]
) -> dict[str, dict[str, int]]:
summary = dict(graph.edge_counts_for(node_id))
sym_kind = str(row.get("kind") or "")
if kind == "symbol" and sym_kind in _TYPE_SYMBOL_KINDS_FOR_EDGE_ROLLUP:
summary.update(graph.member_edge_rollup_for(node_id))
elif kind == "symbol" and sym_kind in _METHOD_SYMBOL_KINDS_FOR_OVERRIDE_ROLLUP:
stored_overrides = _incident_counts(summary.get("OVERRIDES"))
summary.update(graph.override_axis_rollup_for(node_id))
_merge_overrides_edge_summary(stored_overrides, summary)
return summary
def _node_matches_filter(
kind: Literal["symbol", "route", "client", "producer"], row: dict[str, Any], f: NodeFilter | None,
) -> bool:
if f is None:
return True
if f.microservice and str(row.get("microservice") or "") != f.microservice:
return False
if f.module and str(row.get("module") or "") != f.module:
return False
if kind in ("client", "producer") and f.source_layer and str(row.get("source_layer") or "") != f.source_layer:
return False
if kind == "symbol":
role = str(row.get("role") or "")
fqn_val = str(row.get("fqn") or row.get("primary_type_fqn") or "")
symbol_kind_val = str(row.get("kind") or row.get("symbol_kind") or "")
if f.role and role != f.role:
return False
if f.exclude_roles and role in set(f.exclude_roles):
return False
if f.annotation and f.annotation not in list(row.get("annotations") or []):
return False
if f.capability and f.capability not in list(row.get("capabilities") or []):
return False
if f.fqn_prefix and not fqn_val.startswith(f.fqn_prefix):
return False
if f.symbol_kind and symbol_kind_val != f.symbol_kind:
return False
if f.symbol_kinds and symbol_kind_val not in set(f.symbol_kinds):
return False
elif kind == "route":
if f.http_method and str(row.get("method") or "") != f.http_method:
return False
if f.path_prefix:
path = str(row.get("path") or "")
if not path.startswith(f.path_prefix):
return False
if f.framework and str(row.get("framework") or "") != f.framework:
return False
elif kind == "client":
if f.client_kind and str(row.get("client_kind") or "") != f.client_kind:
return False
if f.target_service and str(row.get("target_service") or "") != f.target_service:
return False
if f.target_path_prefix:
path = str(row.get("path") or "")
if not path.startswith(f.target_path_prefix):
return False
if f.http_method and str(row.get("method") or "") != f.http_method:
return False
else:
if f.producer_kind and str(row.get("producer_kind") or "") != f.producer_kind:
return False
if f.topic_prefix:
topic = str(row.get("topic") or "")
if not topic.startswith(f.topic_prefix):
return False
return True
def search_v2(
query: str,
table: str = "java",
hybrid: bool = False,
limit: int = 5,
offset: int = 0,
path_contains: str | None = None,
filter: NodeFilter | dict[str, Any] | str | None = None,
graph: KuzuGraph | None = None,
) -> SearchOutput:
try:
raw_filter = _coerce_filter(filter)
try:
nf = (
NodeFilter.model_validate(raw_filter)
if raw_filter is not None and not isinstance(raw_filter, NodeFilter)
else raw_filter
)
except ValidationError as exc:
_log_fail_loud("unknown_key")
return SearchOutput(
success=False,
message=_filter_validation_error_message(exc),
advisories=[],
limit=None,
offset=None,
)
if nf and (err := _nodefilter_applicability_error("symbol", nf)):
_log_fail_loud("applicability")
return SearchOutput(success=False, message=err, advisories=[], limit=None, offset=None)
if nf and (err := _validate_no_wildcards(nf)):
_log_fail_loud("wildcard")
return SearchOutput(success=False, message=err, advisories=[], limit=None, offset=None)
model_name = resolved_sbert_model_for_process_env(SBERT_MODEL)
device = os.environ.get("SBERT_DEVICE") or None
model = _get_sentence_transformer(model_name, device)
uri = os.environ.get("JAVA_CODEBASE_RAG_INDEX_DIR", "").strip() or str(
(Path.cwd() / ".java-codebase-rag").resolve()
)
uri_path = Path(uri)
if not uri.startswith(("s3://", "gs://", "az://")) and uri_path.exists():
uri = str(uri_path.resolve())
table_keys = list(TABLES) if table == "all" else [table]
rows = run_search(
query,
uri=uri,
table_keys=table_keys,
hybrid=hybrid,
limit=limit,
offset=offset,
path_substring=path_contains,
model_name=model_name,
device=device,
model=model,
)
hits: list[SearchHit] = []
for row in rows:
if path_contains and path_contains not in str(row.get("filename") or ""):
continue
if nf:
row_kind = "symbol"
if not _node_matches_filter(row_kind, row, nf):
continue
hits.append(_row_to_search_hit(row))
hint_payload = {
"success": True,
"results": [h.model_dump() for h in hits],
"limit": limit,
"offset": offset,
}
raw_struct, raw_advisories = generate_hints("search", hint_payload)
return SearchOutput(
success=True,
results=hits,
limit=limit,
offset=offset,
advisories=raw_advisories,
hints_structured=_to_structured_hints(raw_struct),
)
except Exception as exc:
return SearchOutput(success=False, message=str(exc), advisories=[], limit=None, offset=None)
def find_v2(
kind: Literal["symbol", "route", "client", "producer"],
filter: NodeFilter | dict[str, Any] | str,
limit: int = 25,
offset: int = 0,
graph: KuzuGraph | None = None,
) -> FindOutput:
try:
g = graph or KuzuGraph.get()
raw_filter = _coerce_filter(filter)
if raw_filter is None:
raw_filter = {}
try:
nf = NodeFilter.model_validate(raw_filter) if not isinstance(raw_filter, NodeFilter) else raw_filter
except ValidationError as exc:
_log_fail_loud("unknown_key")
return FindOutput(
success=False,
message=_filter_validation_error_message(exc),
advisories=[],
limit=None,
offset=None,
)
if err := _nodefilter_applicability_error(kind, nf):
_log_fail_loud("applicability")
return FindOutput(success=False, message=err, advisories=[], limit=None, offset=None)
if err := _validate_no_wildcards(nf):
_log_fail_loud("wildcard")
return FindOutput(success=False, message=err, advisories=[], limit=None, offset=None)
fetch_cap = int(limit) + int(offset) + 1
if kind == "symbol":
where, params = _symbol_where_from_filter(nf)
params["lim"] = fetch_cap
rows = g._rows( # noqa: SLF001
f"MATCH (s:Symbol) {where} RETURN s.id AS id, s.fqn AS fqn, s.microservice AS microservice, "
"s.module AS module, s.role AS role, s.kind AS symbol_kind ORDER BY s.fqn LIMIT $lim",
params,
)
elif kind == "route":
rows = g.list_routes(
microservice=nf.microservice,
framework=nf.framework,
path_prefix=nf.path_prefix,
method=nf.http_method,
limit=max(500, fetch_cap),
)
rows = [r for r in rows if _node_matches_filter("route", r, nf)]
elif kind == "client":