tokensafe 4.4.7 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +27 -2
- package/hooks/session_start.py +20 -9
- package/kimi.plugin.json +1 -1
- package/mcp_config.json +18 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +5 -2
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +10 -0
- package/src/batch_editor.py +352 -0
- package/src/batch_search.py +408 -0
- package/src/cli.py +117 -1
- package/src/graph_engine.py +273 -41
- package/src/mcp_proxy.py +13 -7
- package/src/mcp_server.py +306 -13
- package/src/oumv_gateway.py +221 -22
- package/src/retrofit.py +355 -0
- package/src/snapshot.py +249 -0
- package/src/syntax_guard.py +84 -0
- package/src/telemetry_sync.py +1 -1
- package/src/transcript_analyzer.py +281 -0
- package/src/version_checker.py +39 -3
package/src/graph_engine.py
CHANGED
|
@@ -51,7 +51,7 @@ _SKIP_CALLS = {
|
|
|
51
51
|
"true", "false", "null", "undefined", "None", "True", "False",
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
_CACHE_SCHEMA_VERSION =
|
|
54
|
+
_CACHE_SCHEMA_VERSION = 4
|
|
55
55
|
|
|
56
56
|
_STATIC_ASSET_EXTS = {
|
|
57
57
|
".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
|
|
@@ -62,32 +62,57 @@ _STATIC_ASSET_EXTS = {
|
|
|
62
62
|
|
|
63
63
|
_BACKEND_ROUTE_PATTERNS = [
|
|
64
64
|
# Python: @app.get("/users"), @router.post('/login'), @bp.route('/data')
|
|
65
|
-
re.compile(r'@(?:app|router|api|bp)\.(?:get|post|put|delete|patch|route)\(\s*["\']([^"\']+)["\']', re.IGNORECASE),
|
|
65
|
+
(re.compile(r'@(?:app|router|api|bp)\.(?:get|post|put|delete|patch|route)\(\s*["\']([^"\']+)["\']', re.IGNORECASE), None),
|
|
66
66
|
# JS/TS: app.get("/users", ...), router.post('/login', ...)
|
|
67
|
-
re.compile(r'(?<!@)\b(?:app|router|server|fastify)\.(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']', re.IGNORECASE),
|
|
67
|
+
(re.compile(r'(?<!@)\b(?:app|router|server|fastify)\.(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']', re.IGNORECASE), None),
|
|
68
68
|
# Java/Kotlin Spring: @GetMapping("/users"), @PostMapping(value = "/login"), @RequestMapping("/api")
|
|
69
|
-
re.compile(r'@(?:Get|Post|Put|Delete|Patch|Request)Mapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']', re.IGNORECASE),
|
|
69
|
+
(re.compile(r'@(?:Get|Post|Put|Delete|Patch|Request)Mapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']', re.IGNORECASE), None),
|
|
70
70
|
# Go Gin/Echo/Fiber: r.GET("/users", ...), router.POST('/login', ...)
|
|
71
|
-
re.compile(r'\b(?:r|router|g|e|app)\.(?:GET|POST|PUT|DELETE|PATCH)\(\s*["\']([^"\']+)["\']'),
|
|
71
|
+
(re.compile(r'\b(?:r|router|g|e|app)\.(?:GET|POST|PUT|DELETE|PATCH)\(\s*["\']([^"\']+)["\']'), None),
|
|
72
72
|
# Go net/http: http.HandleFunc("/users", ...)
|
|
73
|
-
re.compile(r'http\.HandleFunc\(\s*["\']([^"\']+)["\']'),
|
|
73
|
+
(re.compile(r'http\.HandleFunc\(\s*["\']([^"\']+)["\']'), None),
|
|
74
74
|
# C# ASP.NET Core: [HttpGet("/users")], [Route("api/users")]
|
|
75
|
-
re.compile(r'\[(?:Http(?:Get|Post|Put|Delete|Patch)|Route)\(\s*["\']([^"\']+)["\']'),
|
|
75
|
+
(re.compile(r'\[(?:Http(?:Get|Post|Put|Delete|Patch)|Route)\(\s*["\']([^"\']+)["\']'), None),
|
|
76
76
|
# PHP Laravel: Route::get('/users', ...), Route::post('/login', ...)
|
|
77
|
-
re.compile(r'Route::(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']'),
|
|
77
|
+
(re.compile(r'Route::(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']'), None),
|
|
78
78
|
]
|
|
79
79
|
|
|
80
80
|
_FRONTEND_CALL_PATTERNS = [
|
|
81
|
-
# fetch("/api/users") or fetch(`/api/users/${id}`)
|
|
82
|
-
re.compile(r'\bfetch\(\s*[`"\']([^`"\'?#]+)'),
|
|
81
|
+
# fetch("/api/users") or fetch(`/api/users/${id}`) (method unknown: depends on init options)
|
|
82
|
+
(re.compile(r'\bfetch\(\s*[`"\']([^`"\'?#]+)'), None),
|
|
83
83
|
# axios.get("/api/users"), api.post(`/api/users/${id}`), client.get, etc.
|
|
84
|
-
re.compile(r'\b(?:axios|api|client|httpClient|ky)\.(?:get|post|put|delete|patch)\(\s*[`"\']([^`"\'?#]+)'),
|
|
85
|
-
# useSWR("/api/users")
|
|
86
|
-
re.compile(r'\buseSWR\(\s*[`"\']([^`"\'?#]+)'),
|
|
87
|
-
# axios("/api/users")
|
|
88
|
-
re.compile(r'\baxios\(\s*[`"\']([^`"\'?#]+)'),
|
|
84
|
+
(re.compile(r'\b(?:axios|api|client|httpClient|ky)\.(?:get|post|put|delete|patch)\(\s*[`"\']([^`"\'?#]+)'), None),
|
|
85
|
+
# useSWR("/api/users") — semantically always GET
|
|
86
|
+
(re.compile(r'\buseSWR\(\s*[`"\']([^`"\'?#]+)'), "GET"),
|
|
87
|
+
# axios("/api/users") (method unknown: depends on config)
|
|
88
|
+
(re.compile(r'\baxios\(\s*[`"\']([^`"\'?#]+)'), None),
|
|
89
89
|
]
|
|
90
90
|
|
|
91
|
+
# HTTP method extraction from route-declaration / API-call matched text.
|
|
92
|
+
_HTTP_METHOD_ANNOTATION_RE = re.compile(r'(?i)@(get|post|put|delete|patch)mapping\b')
|
|
93
|
+
_HTTP_METHOD_BRACKET_RE = re.compile(r'(?i)\[\s*http(get|post|put|delete|patch)\b')
|
|
94
|
+
_HTTP_METHOD_CALL_RE = re.compile(r'(?i)(?:\.|::)\s*(get|post|put|delete|patch|head|options)\s*\(')
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _match_http_method(matched_text: str) -> Optional[str]:
|
|
98
|
+
"""Extracts the HTTP verb from a matched route-declaration or client-call fragment.
|
|
99
|
+
|
|
100
|
+
Searches only the matched fragment (method word always precedes the route string),
|
|
101
|
+
so route segments like `/get-started` never produce a false method.
|
|
102
|
+
"""
|
|
103
|
+
if not matched_text:
|
|
104
|
+
return None
|
|
105
|
+
m = _HTTP_METHOD_ANNOTATION_RE.search(matched_text)
|
|
106
|
+
if m:
|
|
107
|
+
return m.group(1).upper()
|
|
108
|
+
m = _HTTP_METHOD_BRACKET_RE.search(matched_text)
|
|
109
|
+
if m:
|
|
110
|
+
return m.group(1).upper()
|
|
111
|
+
m = _HTTP_METHOD_CALL_RE.search(matched_text)
|
|
112
|
+
if m:
|
|
113
|
+
return m.group(1).upper()
|
|
114
|
+
return None
|
|
115
|
+
|
|
91
116
|
_NEXT_APP_ROUTE_RE = re.compile(r'^(?:src/)?app/(api/.+?)/route\.[a-zA-Z0-9]+$')
|
|
92
117
|
_NEXT_PAGES_ROUTE_RE = re.compile(r'^(?:src/)?pages/(api/.+?)\.[a-zA-Z0-9]+$')
|
|
93
118
|
_CONTROLLER_PREFIX_RE = re.compile(r'@RequestMapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']|\[Route\(\s*["\']([^"\']+)["\']\)', re.IGNORECASE)
|
|
@@ -211,8 +236,9 @@ class CodeGraph:
|
|
|
211
236
|
self.file_mtimes: Dict[str, float] = {} # file_rel_path -> mtime
|
|
212
237
|
self.file_stats: Dict[str, Tuple[float, int]] = {} # file_rel_path -> (mtime, size)
|
|
213
238
|
self.file_imports: Dict[str, Set[str]] = {} # file_rel_path -> raw imported modules
|
|
214
|
-
self.file_endpoints: Dict[str, List[Tuple[str, Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key)]
|
|
215
|
-
self.file_api_calls: Dict[str, List[Tuple[str, Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key)]
|
|
239
|
+
self.file_endpoints: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key, http_method)]
|
|
240
|
+
self.file_api_calls: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key, http_method)]
|
|
241
|
+
self.api_links: List[Dict[str, Any]] = [] # cross-stack edges: frontend call -> backend endpoint
|
|
216
242
|
self.last_scanned: float = 0.0
|
|
217
243
|
self.backend: str = self._detect_backend()
|
|
218
244
|
|
|
@@ -249,6 +275,7 @@ class CodeGraph:
|
|
|
249
275
|
self.file_imports.clear()
|
|
250
276
|
self.file_endpoints.clear()
|
|
251
277
|
self.file_api_calls.clear()
|
|
278
|
+
self.api_links.clear()
|
|
252
279
|
|
|
253
280
|
def _load_disk_cache(self) -> bool:
|
|
254
281
|
path = self._cache_path()
|
|
@@ -299,15 +326,17 @@ class CodeGraph:
|
|
|
299
326
|
|
|
300
327
|
self.file_endpoints = {}
|
|
301
328
|
try:
|
|
302
|
-
for row in cur.execute("SELECT rel_path, route, sym_key FROM api_endpoints").fetchall():
|
|
303
|
-
|
|
329
|
+
for row in cur.execute("SELECT rel_path, route, sym_key, method FROM api_endpoints").fetchall():
|
|
330
|
+
method = row[3] if len(row) > 3 else None
|
|
331
|
+
self.file_endpoints.setdefault(row[0], []).append((row[1], row[2], method))
|
|
304
332
|
except sqlite3.OperationalError:
|
|
305
333
|
pass
|
|
306
334
|
|
|
307
335
|
self.file_api_calls = {}
|
|
308
336
|
try:
|
|
309
|
-
for row in cur.execute("SELECT rel_path, route, sym_key FROM api_calls").fetchall():
|
|
310
|
-
|
|
337
|
+
for row in cur.execute("SELECT rel_path, route, sym_key, method FROM api_calls").fetchall():
|
|
338
|
+
method = row[3] if len(row) > 3 else None
|
|
339
|
+
self.file_api_calls.setdefault(row[0], []).append((row[1], row[2], method))
|
|
311
340
|
except sqlite3.OperationalError:
|
|
312
341
|
pass
|
|
313
342
|
|
|
@@ -375,8 +404,8 @@ class CodeGraph:
|
|
|
375
404
|
cur.execute("CREATE TABLE file_symbols (rel_path TEXT, sym_key TEXT, idx INTEGER, PRIMARY KEY (rel_path, sym_key))")
|
|
376
405
|
cur.execute("CREATE TABLE file_imports (rel_path TEXT, imported TEXT, PRIMARY KEY (rel_path, imported))")
|
|
377
406
|
cur.execute("CREATE TABLE edges (source TEXT, target TEXT, PRIMARY KEY (source, target))")
|
|
378
|
-
cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT)")
|
|
379
|
-
cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT)")
|
|
407
|
+
cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
|
|
408
|
+
cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
|
|
380
409
|
|
|
381
410
|
cur.executemany(
|
|
382
411
|
"INSERT INTO graph_meta VALUES (?, ?)",
|
|
@@ -413,12 +442,12 @@ class CodeGraph:
|
|
|
413
442
|
[(src, tgt) for src, tgts in self.edges.items() for tgt in tgts],
|
|
414
443
|
)
|
|
415
444
|
cur.executemany(
|
|
416
|
-
"INSERT INTO api_endpoints VALUES (?, ?, ?)",
|
|
417
|
-
[(rel, ep[0], ep[1]) for rel, eps in self.file_endpoints.items() for ep in eps],
|
|
445
|
+
"INSERT INTO api_endpoints VALUES (?, ?, ?, ?)",
|
|
446
|
+
[(rel, ep[0], ep[1], ep[2] if len(ep) > 2 else None) for rel, eps in self.file_endpoints.items() for ep in eps],
|
|
418
447
|
)
|
|
419
448
|
cur.executemany(
|
|
420
|
-
"INSERT INTO api_calls VALUES (?, ?, ?)",
|
|
421
|
-
[(rel, call[0], call[1]) for rel, calls in self.file_api_calls.items() for call in calls],
|
|
449
|
+
"INSERT INTO api_calls VALUES (?, ?, ?, ?)",
|
|
450
|
+
[(rel, call[0], call[1], call[2] if len(call) > 2 else None) for rel, calls in self.file_api_calls.items() for call in calls],
|
|
422
451
|
)
|
|
423
452
|
con.commit()
|
|
424
453
|
finally:
|
|
@@ -614,13 +643,14 @@ class CodeGraph:
|
|
|
614
643
|
for sk in sym_keys:
|
|
615
644
|
s = self.symbols.get(sk)
|
|
616
645
|
if s and s.name.upper() in {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "HANDLER", "DEFAULT"}:
|
|
617
|
-
|
|
646
|
+
method = s.name.upper() if s.name.upper() in {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"} else None
|
|
647
|
+
self.file_endpoints[rel_path].append((norm_route, sk, method))
|
|
618
648
|
matched_any = True
|
|
619
649
|
if not matched_any:
|
|
620
|
-
self.file_endpoints[rel_path].append((norm_route, None))
|
|
650
|
+
self.file_endpoints[rel_path].append((norm_route, None, None))
|
|
621
651
|
|
|
622
652
|
# 2. Backend route definitions
|
|
623
|
-
for rx in _BACKEND_ROUTE_PATTERNS:
|
|
653
|
+
for rx, _default_method in _BACKEND_ROUTE_PATTERNS:
|
|
624
654
|
for match in rx.finditer(content):
|
|
625
655
|
route_raw = match.group(1)
|
|
626
656
|
if class_prefix and not route_raw.startswith(class_prefix):
|
|
@@ -632,10 +662,11 @@ class CodeGraph:
|
|
|
632
662
|
continue
|
|
633
663
|
line_no = content[:match.start()].count("\n") + 1
|
|
634
664
|
sym_key = self._find_enclosing_symbol(rel_path, line_no)
|
|
635
|
-
|
|
665
|
+
method = _match_http_method(match.group(0))
|
|
666
|
+
self.file_endpoints[rel_path].append((norm_route, sym_key, method))
|
|
636
667
|
|
|
637
668
|
# 3. Frontend API call sites
|
|
638
|
-
for rx in _FRONTEND_CALL_PATTERNS:
|
|
669
|
+
for rx, default_method in _FRONTEND_CALL_PATTERNS:
|
|
639
670
|
for match in rx.finditer(content):
|
|
640
671
|
route_raw = match.group(1)
|
|
641
672
|
norm_route = _normalize_route_path(route_raw)
|
|
@@ -643,7 +674,8 @@ class CodeGraph:
|
|
|
643
674
|
continue
|
|
644
675
|
line_no = content[:match.start()].count("\n") + 1
|
|
645
676
|
sym_key = self._find_enclosing_symbol(rel_path, line_no)
|
|
646
|
-
|
|
677
|
+
method = _match_http_method(match.group(0)) or default_method
|
|
678
|
+
self.file_api_calls[rel_path].append((norm_route, sym_key, method))
|
|
647
679
|
|
|
648
680
|
@staticmethod
|
|
649
681
|
def _route_matches(path: str, pattern_route: str) -> bool:
|
|
@@ -669,32 +701,35 @@ class CodeGraph:
|
|
|
669
701
|
"""
|
|
670
702
|
Cross-boundary semantic linking between frontend client API calls
|
|
671
703
|
and backend route endpoints across languages and frameworks.
|
|
704
|
+
Also records OUMV cross-stack relationships (with evidence) in `api_links`.
|
|
672
705
|
"""
|
|
706
|
+
self.api_links = []
|
|
673
707
|
try:
|
|
674
|
-
endpoint_map: Dict[str, List[Tuple[str, Optional[str]]]] = {}
|
|
708
|
+
endpoint_map: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {}
|
|
675
709
|
for rel_path, endpoints in self.file_endpoints.items():
|
|
676
|
-
for norm_route, sym_key in endpoints:
|
|
710
|
+
for norm_route, sym_key, method in endpoints:
|
|
677
711
|
if norm_route:
|
|
678
|
-
endpoint_map.setdefault(norm_route, []).append((rel_path, sym_key))
|
|
712
|
+
endpoint_map.setdefault(norm_route, []).append((rel_path, sym_key, method))
|
|
679
713
|
|
|
680
714
|
if not endpoint_map:
|
|
681
715
|
return
|
|
682
716
|
|
|
717
|
+
seen_links = set()
|
|
683
718
|
for caller_rel, calls in self.file_api_calls.items():
|
|
684
719
|
caller_file_node = f"file:{caller_rel}"
|
|
685
|
-
for norm_route, caller_sym in calls:
|
|
720
|
+
for norm_route, caller_sym, caller_method in calls:
|
|
686
721
|
if not norm_route:
|
|
687
722
|
continue
|
|
688
|
-
matched_endpoints: List[Tuple[str, Optional[str]]] = []
|
|
723
|
+
matched_endpoints: List[Tuple[str, str, Optional[str], Optional[str]]] = []
|
|
689
724
|
if norm_route in endpoint_map:
|
|
690
|
-
matched_endpoints.extend(endpoint_map[norm_route])
|
|
725
|
+
matched_endpoints.extend((norm_route, rel, sym, m) for (rel, sym, m) in endpoint_map[norm_route])
|
|
691
726
|
|
|
692
727
|
for ep_route, eps in endpoint_map.items():
|
|
693
728
|
if ep_route != norm_route and ("*" in ep_route or "*" in norm_route):
|
|
694
729
|
if self._route_matches(norm_route, ep_route):
|
|
695
|
-
matched_endpoints.extend(eps)
|
|
730
|
+
matched_endpoints.extend((ep_route, rel, sym, m) for (rel, sym, m) in eps)
|
|
696
731
|
|
|
697
|
-
for ep_rel, ep_sym in matched_endpoints:
|
|
732
|
+
for ep_route, ep_rel, ep_sym, ep_method in matched_endpoints:
|
|
698
733
|
if ep_rel == caller_rel:
|
|
699
734
|
continue
|
|
700
735
|
ep_file_node = f"file:{ep_rel}"
|
|
@@ -704,6 +739,26 @@ class CodeGraph:
|
|
|
704
739
|
dst = ep_sym or ep_file_node
|
|
705
740
|
if src != dst:
|
|
706
741
|
self.add_edge(src, dst)
|
|
742
|
+
|
|
743
|
+
link_key = (caller_rel, caller_sym or "", norm_route, ep_rel, ep_sym or "", ep_route)
|
|
744
|
+
if link_key not in seen_links:
|
|
745
|
+
seen_links.add(link_key)
|
|
746
|
+
self.api_links.append({
|
|
747
|
+
"source": {
|
|
748
|
+
"type": "frontend.action",
|
|
749
|
+
"route": norm_route,
|
|
750
|
+
"method": caller_method,
|
|
751
|
+
"file": caller_rel,
|
|
752
|
+
"symbol": caller_sym,
|
|
753
|
+
},
|
|
754
|
+
"target": {
|
|
755
|
+
"type": "backend.endpoint",
|
|
756
|
+
"route": ep_route,
|
|
757
|
+
"method": ep_method,
|
|
758
|
+
"file": ep_rel,
|
|
759
|
+
"symbol": ep_sym,
|
|
760
|
+
},
|
|
761
|
+
})
|
|
707
762
|
except Exception:
|
|
708
763
|
pass
|
|
709
764
|
|
|
@@ -1475,6 +1530,183 @@ class CodeGraph:
|
|
|
1475
1530
|
items = [f"{g['file']} ({g['dependents']} deps)" for g in nodes_to_show]
|
|
1476
1531
|
return f"[TokenSafe Architecture Map | Core Hubs: {', '.join(items)}]"
|
|
1477
1532
|
|
|
1533
|
+
def get_static_oumv_slice(self, level: str = "L0", target: Optional[str] = None) -> Dict[str, Any]:
|
|
1534
|
+
"""
|
|
1535
|
+
Level 1 Static OUMV Inspection:
|
|
1536
|
+
Returns statically discoverable components, API endpoints, routes, and call sites
|
|
1537
|
+
directly from the AST graph when runtime dev-servers are disconnected.
|
|
1538
|
+
"""
|
|
1539
|
+
evidence = {
|
|
1540
|
+
"provenance": "static",
|
|
1541
|
+
"sourceAdapter": "tokensafe-graph-engine",
|
|
1542
|
+
"confidence": "confirmed",
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
lvl = (level or "L0").upper()
|
|
1546
|
+
if lvl == "L0":
|
|
1547
|
+
god_nodes = self.get_god_nodes(top_n=5)
|
|
1548
|
+
endpoints_count = sum(len(eps) for eps in self.file_endpoints.values())
|
|
1549
|
+
calls_count = sum(len(c) for c in self.file_api_calls.values())
|
|
1550
|
+
return {
|
|
1551
|
+
"level": "L0",
|
|
1552
|
+
"mode": "STATIC_OFFLINE_PULSE",
|
|
1553
|
+
"status": "OFFLINE_STATIC",
|
|
1554
|
+
"summary": f"Indexed {len(self.file_symbols)} files, {len(self.symbols)} symbols, {endpoints_count} API endpoints, {calls_count} client calls, {len(self.api_links)} cross-stack links",
|
|
1555
|
+
"totalFiles": len(self.file_symbols),
|
|
1556
|
+
"totalSymbols": len(self.symbols),
|
|
1557
|
+
"totalEndpoints": endpoints_count,
|
|
1558
|
+
"totalClientCalls": calls_count,
|
|
1559
|
+
"totalRelationships": len(self.api_links),
|
|
1560
|
+
"topGodNodes": [g["file"] for g in god_nodes],
|
|
1561
|
+
"evidence": evidence,
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
# L1: Discovered API surface & Routes
|
|
1565
|
+
endpoints = []
|
|
1566
|
+
for rel_path, eps in self.file_endpoints.items():
|
|
1567
|
+
for norm_route, sym, method in eps:
|
|
1568
|
+
if not target or target.lower() in norm_route.lower() or target.lower() in rel_path.lower():
|
|
1569
|
+
endpoints.append({
|
|
1570
|
+
"route": norm_route,
|
|
1571
|
+
"method": method,
|
|
1572
|
+
"file": rel_path,
|
|
1573
|
+
"symbol": sym,
|
|
1574
|
+
"type": "backend.endpoint",
|
|
1575
|
+
})
|
|
1576
|
+
|
|
1577
|
+
client_calls = []
|
|
1578
|
+
for rel_path, calls in self.file_api_calls.items():
|
|
1579
|
+
for norm_route, sym, method in calls:
|
|
1580
|
+
if not target or target.lower() in norm_route.lower() or target.lower() in rel_path.lower():
|
|
1581
|
+
client_calls.append({
|
|
1582
|
+
"route": norm_route,
|
|
1583
|
+
"method": method,
|
|
1584
|
+
"file": rel_path,
|
|
1585
|
+
"symbol": sym,
|
|
1586
|
+
"type": "frontend.action",
|
|
1587
|
+
})
|
|
1588
|
+
|
|
1589
|
+
# Cross-stack relationships (frontend call -> backend endpoint) with evidence
|
|
1590
|
+
relationships = []
|
|
1591
|
+
for link in self.api_links:
|
|
1592
|
+
if target:
|
|
1593
|
+
t = target.lower()
|
|
1594
|
+
hay = " ".join([
|
|
1595
|
+
link["source"]["route"] or "", link["source"]["file"] or "",
|
|
1596
|
+
link["target"]["route"] or "", link["target"]["file"] or "",
|
|
1597
|
+
]).lower()
|
|
1598
|
+
if t not in hay:
|
|
1599
|
+
continue
|
|
1600
|
+
relationships.append({
|
|
1601
|
+
"source": link["source"],
|
|
1602
|
+
"target": link["target"],
|
|
1603
|
+
"evidence": {
|
|
1604
|
+
"provenance": "static",
|
|
1605
|
+
"sourceAdapter": "tokensafe-graph-engine",
|
|
1606
|
+
"confidence": "probable",
|
|
1607
|
+
},
|
|
1608
|
+
})
|
|
1609
|
+
|
|
1610
|
+
matching_symbols = []
|
|
1611
|
+
if target:
|
|
1612
|
+
for sk, sym in self.symbols.items():
|
|
1613
|
+
if target.lower() in sym.name.lower():
|
|
1614
|
+
matching_symbols.append({
|
|
1615
|
+
"name": sym.name,
|
|
1616
|
+
"kind": sym.kind,
|
|
1617
|
+
"file": sym.file_path,
|
|
1618
|
+
"lines": [sym.line_start, sym.line_end],
|
|
1619
|
+
})
|
|
1620
|
+
|
|
1621
|
+
return {
|
|
1622
|
+
"level": "L1",
|
|
1623
|
+
"target": target,
|
|
1624
|
+
"mode": "STATIC_SURFACE",
|
|
1625
|
+
"endpoints": endpoints[:30],
|
|
1626
|
+
"clientCalls": client_calls[:30],
|
|
1627
|
+
"relationships": relationships[:30],
|
|
1628
|
+
"matchingSymbols": matching_symbols[:20],
|
|
1629
|
+
"evidence": evidence,
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1632
|
+
def get_static_impact(self, target: str, max_depth: int = 3) -> Dict[str, Any]:
|
|
1633
|
+
"""
|
|
1634
|
+
Static impact analysis over the AST graph: reverse-dependency walk
|
|
1635
|
+
("who depends on the target") plus cross-stack frontend callers of
|
|
1636
|
+
matching backend endpoints. Honest about missing runtime evidence.
|
|
1637
|
+
"""
|
|
1638
|
+
evidence = {
|
|
1639
|
+
"provenance": "static",
|
|
1640
|
+
"sourceAdapter": "tokensafe-graph-engine",
|
|
1641
|
+
"confidence": "probable",
|
|
1642
|
+
}
|
|
1643
|
+
t = (target or "").strip()
|
|
1644
|
+
if not t:
|
|
1645
|
+
return {"target": t, "mode": "STATIC_IMPACT", "error": "target is required", "evidence": evidence}
|
|
1646
|
+
|
|
1647
|
+
start_nodes: Set[str] = set()
|
|
1648
|
+
if t.startswith("file:"):
|
|
1649
|
+
start_nodes.add(t)
|
|
1650
|
+
for sk, sym in self.symbols.items():
|
|
1651
|
+
if t.lower() in sym.name.lower() or t.lower() in sym.file_path.lower():
|
|
1652
|
+
start_nodes.add(sk)
|
|
1653
|
+
for rel_path in self.file_symbols:
|
|
1654
|
+
if t.lower() in rel_path.lower():
|
|
1655
|
+
start_nodes.add(f"file:{rel_path}")
|
|
1656
|
+
|
|
1657
|
+
visited: Dict[str, int] = {}
|
|
1658
|
+
frontier = [(n, 0) for n in start_nodes]
|
|
1659
|
+
while frontier:
|
|
1660
|
+
node, depth = frontier.pop(0)
|
|
1661
|
+
if node in visited:
|
|
1662
|
+
continue
|
|
1663
|
+
visited[node] = depth
|
|
1664
|
+
if depth >= max_depth:
|
|
1665
|
+
continue
|
|
1666
|
+
for dep in self.rev_edges.get(node, ()):
|
|
1667
|
+
if dep not in visited:
|
|
1668
|
+
frontier.append((dep, depth + 1))
|
|
1669
|
+
|
|
1670
|
+
def _node_info(node: str) -> Dict[str, Any]:
|
|
1671
|
+
if node.startswith("file:"):
|
|
1672
|
+
return {"type": "file", "file": node[5:]}
|
|
1673
|
+
sym = self.symbols.get(node)
|
|
1674
|
+
if sym:
|
|
1675
|
+
return {"type": "symbol", "name": sym.name, "kind": sym.kind, "file": sym.file_path}
|
|
1676
|
+
return {"type": "node", "id": node}
|
|
1677
|
+
|
|
1678
|
+
direct = [_node_info(n) for n, d in visited.items() if d == 1 and n not in start_nodes]
|
|
1679
|
+
transitive = [_node_info(n) for n, d in visited.items() if d > 1]
|
|
1680
|
+
|
|
1681
|
+
frontend_callers = []
|
|
1682
|
+
for link in self.api_links:
|
|
1683
|
+
hay = " ".join([link["target"]["route"] or "", link["target"]["file"] or ""])
|
|
1684
|
+
if t.lower() in hay.lower():
|
|
1685
|
+
frontend_callers.append({
|
|
1686
|
+
"source": link["source"],
|
|
1687
|
+
"target": link["target"],
|
|
1688
|
+
"evidence": {
|
|
1689
|
+
"provenance": "static",
|
|
1690
|
+
"sourceAdapter": "tokensafe-graph-engine",
|
|
1691
|
+
"confidence": "probable",
|
|
1692
|
+
},
|
|
1693
|
+
})
|
|
1694
|
+
|
|
1695
|
+
return {
|
|
1696
|
+
"target": t,
|
|
1697
|
+
"mode": "STATIC_IMPACT",
|
|
1698
|
+
"directDependents": direct[:20],
|
|
1699
|
+
"transitiveDependents": transitive[:20],
|
|
1700
|
+
"crossStack": {
|
|
1701
|
+
"frontendCallers": frontend_callers[:20],
|
|
1702
|
+
"count": len(frontend_callers),
|
|
1703
|
+
},
|
|
1704
|
+
"evidence": evidence,
|
|
1705
|
+
"missingEvidence": [
|
|
1706
|
+
"Runtime-confirmed dependencies are not included while dev-servers are offline.",
|
|
1707
|
+
],
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1478
1710
|
|
|
1479
1711
|
class GraphEngine:
|
|
1480
1712
|
"""Multi-Project Manager for automatic background graph execution."""
|
package/src/mcp_proxy.py
CHANGED
|
@@ -21,33 +21,39 @@ from src.stash import stash_block
|
|
|
21
21
|
|
|
22
22
|
MAX_UNFOLDED_CHARS = 1500
|
|
23
23
|
MAX_UNFOLDED_LINES = 35
|
|
24
|
+
MAX_UNFOLDED_BYTES = 8800
|
|
24
25
|
HEAD_LINES = 15
|
|
25
26
|
TAIL_LINES = 10
|
|
26
27
|
|
|
27
28
|
|
|
28
29
|
def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
|
|
29
|
-
"""Folds oversized text and returns (folded_text, was_folded).
|
|
30
|
+
"""Folds oversized text and returns (folded_text, was_folded).
|
|
31
|
+
Strictly enforces MAX_UNFOLDED_BYTES (8800 bytes) to prevent disk spills."""
|
|
30
32
|
if not text:
|
|
31
33
|
return text, False
|
|
32
34
|
from src.format_parsers.ansi import strip_ansi
|
|
33
35
|
text = strip_ansi(text)
|
|
34
|
-
|
|
35
|
-
return text, False
|
|
36
|
-
|
|
36
|
+
raw_bytes = len(text.encode("utf-8"))
|
|
37
37
|
lines = text.splitlines()
|
|
38
|
-
|
|
38
|
+
|
|
39
|
+
if raw_bytes <= MAX_UNFOLDED_BYTES and len(text) <= MAX_UNFOLDED_CHARS and len(lines) <= MAX_UNFOLDED_LINES:
|
|
39
40
|
return text, False
|
|
40
41
|
|
|
41
42
|
hash8, marker = stash_block(text, source=f"mcp:{tool_name}")
|
|
42
43
|
head = lines[:HEAD_LINES]
|
|
43
44
|
tail = lines[-TAIL_LINES:]
|
|
44
|
-
omitted = len(lines) - (
|
|
45
|
+
omitted = max(0, len(lines) - (len(head) + len(tail)))
|
|
45
46
|
|
|
46
47
|
folded_lines = head + [
|
|
47
48
|
f"... [{omitted} lines folded by TokenSafe MCP Proxy] ...",
|
|
48
49
|
] + tail + [marker]
|
|
50
|
+
folded_res = "\n".join(folded_lines)
|
|
51
|
+
|
|
52
|
+
if len(folded_res.encode("utf-8")) > MAX_UNFOLDED_BYTES:
|
|
53
|
+
allowed = MAX_UNFOLDED_BYTES - len(marker.encode("utf-8")) - 100
|
|
54
|
+
folded_res = text.encode("utf-8")[:allowed].decode("utf-8", errors="ignore") + f"\n... [folded]\n{marker}"
|
|
49
55
|
|
|
50
|
-
return
|
|
56
|
+
return folded_res, True
|
|
51
57
|
|
|
52
58
|
|
|
53
59
|
def compact_mcp_response(resp: Dict[str, Any]) -> Dict[str, Any]:
|