tokensafe 2.7.2 → 2.8.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/src/mcp_server.py CHANGED
@@ -22,6 +22,7 @@ sys.path.insert(0, BASE_DIR)
22
22
  from src.compactor import PromptCompactor
23
23
  from src.skeletonizer import Skeletonizer
24
24
  from src.slicer import ToolSlicer
25
+ from src.schema_slicer import SchemaSlicer
25
26
  from src.dependency_prefetcher import DependencyPrefetcher
26
27
  from src.command_sanitizer import CommandSanitizer
27
28
  from src.loop_detector import LoopDetector
@@ -40,7 +41,7 @@ from src.license_manager import LicenseManager
40
41
 
41
42
  SERVER_INFO = {
42
43
  "name": "tokensafe-mcp",
43
- "version": "2.7.2"
44
+ "version": "2.8.0"
44
45
  }
45
46
 
46
47
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -78,7 +79,7 @@ def _client_supports_pointers() -> bool:
78
79
  TOOLS = [
79
80
  {
80
81
  "name": "smart_read_file",
81
- "description": "Reads a code file using AST skeletonization and graph-guided slicing to save 90-99% context tokens.",
82
+ "description": "Reads a code file using AST skeletonization and graph-guided slicing to save 90-99% context tokens. OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced instead: pass the spec path/model/type/table as 'symbol', or omit it for a compact overview. For 3+ related symbols across files prefer smart_bundle.",
82
83
  "inputSchema": {
83
84
  "type": "object",
84
85
  "properties": {
@@ -93,6 +94,32 @@ TOOLS = [
93
94
  "required": ["path"]
94
95
  }
95
96
  },
97
+ {
98
+ "name": "smart_bundle",
99
+ "description": "Reads 2-8 related symbols across multiple files as ONE merged context bundle: per-file AST skeletons with shared import lines deduplicated and merged 1-hop dependency signatures. Use it instead of 3+ separate smart_read_file calls on related code (one roundtrip, no duplicated imports/types).",
100
+ "inputSchema": {
101
+ "type": "object",
102
+ "properties": {
103
+ "targets": {
104
+ "type": "array",
105
+ "maxItems": 8,
106
+ "items": {
107
+ "type": "object",
108
+ "properties": {
109
+ "path": {"type": "string", "description": "Absolute path to the code file"},
110
+ "symbol": {"type": "string", "description": "Optional symbol to keep unfolded (class/function name)"}
111
+ },
112
+ "required": ["path"]
113
+ },
114
+ "description": "Up to 8 {path, symbol} targets; list several symbols of the same file as separate entries"
115
+ },
116
+ "include_deps": {"type": "boolean", "description": "Optional: include merged 1-hop dependency signatures (default: true)"},
117
+ "dep_mode": {"type": "string", "enum": ["signature", "full"], "description": "Optional: kept for parity with smart_read_file; signatures are always merged for bundles"},
118
+ "force_full": {"type": "boolean", "description": "Optional: bypass session pointer deduplication"}
119
+ },
120
+ "required": ["targets"]
121
+ }
122
+ },
96
123
  {
97
124
  "name": "get_architecture_graph",
98
125
  "description": "Returns top architectural God Nodes and dependency topology for the target project. Call this BEFORE reading files or searching.",
@@ -610,6 +637,23 @@ def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
610
637
  return True, "signature"
611
638
 
612
639
 
640
+ def _repo_fingerprint(graph) -> str:
641
+ """Stable Shared-Team-Symbol-Index cache key for an indexed repo: repo name +
642
+ per-file relative paths + sizes. Machine-independent on purpose (mtimes differ
643
+ across clones, sizes survive them); a 7-day TTL bounds staleness on the cloud."""
644
+ import hashlib
645
+ h = hashlib.sha256()
646
+ root = os.path.abspath(getattr(graph, "root_dir", "") or "")
647
+ h.update(os.path.basename(root).encode("utf-8", "ignore"))
648
+ stats = getattr(graph, "file_stats", {}) or {}
649
+ for rel in sorted(stats.keys()):
650
+ _m, s = stats[rel]
651
+ h.update(f"{rel}:{int(s)};".encode("utf-8", "ignore"))
652
+ if not stats:
653
+ h.update(f"symbols:{len(getattr(graph, 'symbols', {}) or {})}".encode("utf-8", "ignore"))
654
+ return h.hexdigest()[:40]
655
+
656
+
613
657
  def handle_tool_call(name: str, args: dict) -> dict:
614
658
  if args is None or not isinstance(args, dict):
615
659
  args = {}
@@ -699,6 +743,26 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
699
743
  if _is_binary_file(path):
700
744
  return _fallback_error("smart_read_file", f"'{os.path.basename(path)}' appears to be a binary file")
701
745
 
746
+ # Heavy declarative schema files (OpenAPI/Swagger/Prisma/GraphQL/SQL DDL):
747
+ # generic AST skeletonization does not apply — route to the schema slicer.
748
+ # `symbol` carries the target (a spec path, model, type or table); an empty
749
+ # symbol yields a compact overview instead of a 20k-50k token dump.
750
+ schema_kind = SchemaSlicer.detect(os.path.abspath(path))
751
+ if schema_kind:
752
+ sliced, sinfo = SchemaSlicer.slice_file(os.path.abspath(path), target=(symbol or ""))
753
+ if sliced:
754
+ orig_t = max(1000, st.st_size // 4)
755
+ sliced_t = count_tokens(sliced)
756
+ tracker.record_event(
757
+ session_id=_mcp_session_id(),
758
+ event_type="SCHEMA_SLICE",
759
+ original_tokens=orig_t,
760
+ optimized_tokens=sliced_t,
761
+ details={"kind": sinfo.get("kind"), "mode": sinfo.get("mode"), "target": (symbol or "")[:120]}
762
+ )
763
+ header = f"// [TokenSafe Schema Slice: {sinfo.get('kind')} | mode={sinfo.get('mode')} | target='{(symbol or '')[:80]}']\n"
764
+ return {"content": [{"type": "text", "text": header + sliced}]}
765
+
702
766
  # Community 500k quota reached: soft-degrade to bounded raw read (disable Graph/AST/Pointer/Team Cache)
703
767
  if is_quota_exceeded:
704
768
  if start_line is not None or end_line is not None:
@@ -714,8 +778,6 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
714
778
  total_seen = idx
715
779
  if idx <= cap:
716
780
  raw_lines.append(line)
717
- elif idx == cap + 1:
718
- pass
719
781
  raw_chunk = "".join(raw_lines)
720
782
  if total_seen > cap:
721
783
  raw_chunk += f"\n// [TokenSafe Community 500k limit reached: showing raw lines 1-{cap} of {total_seen}. AST/graph slicing & pointer dedup are paused.]\n"
@@ -859,6 +921,117 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
859
921
  content = f.read()
860
922
  return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
861
923
 
924
+ elif name == "smart_bundle":
925
+ targets = args.get("targets")
926
+ if not isinstance(targets, list) or not targets:
927
+ return _fallback_error("smart_bundle", "missing required 'targets' array of {path, symbol} objects")
928
+ if len(targets) > 8:
929
+ return _fallback_error("smart_bundle", "too many targets (max 8)")
930
+ if is_quota_exceeded:
931
+ LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
932
+ return {"content": [{"type": "text", "text": f"{quota.get('warning', '')}\n\nsmart_bundle is paused over the 500k Community limit. Use single smart_read_file calls, or activate a subscription at https://tokensafe.dev/#pricing."}]}
933
+
934
+ inc_deps, _eff_dep_mode = _resolve_dep_mode(args)
935
+ max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
936
+
937
+ by_file: Dict[str, List[str]] = {}
938
+ for t in targets:
939
+ if not isinstance(t, dict) or not str(t.get("path") or "").strip():
940
+ return _fallback_error("smart_bundle", "each target must be {path: str, symbol?: str}")
941
+ by_file.setdefault(os.path.abspath(str(t["path"])), []).append(str(t.get("symbol") or "").strip())
942
+
943
+ missing = [p for p in by_file if not os.path.isfile(p)]
944
+ if missing:
945
+ return {"isError": True, "content": [{"type": "text", "text": f"File(s) not found: {', '.join(missing)}"}]}
946
+
947
+ bundle_max_bytes = 512 * 1024
948
+ file_sections: List[Tuple[str, str, List[str]]] = [] # (abs_path, skeleton, import_lines)
949
+ dep_lines: List[str] = []
950
+ seen_dep_lines: set = set()
951
+ orig_tokens_est = 0
952
+
953
+ _imp_line_re = re.compile(r"^\s*(?:import\s|from\s+\S+\s+import\b|use\s|using\s|#include|require(?:_relative)?\s|extern crate\s).*$", re.MULTILINE)
954
+
955
+ for p, symbols in by_file.items():
956
+ try:
957
+ st_b = os.stat(p)
958
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
959
+ code = f.read(bundle_max_bytes)
960
+ except OSError as e:
961
+ return _fallback_error("smart_bundle", f"cannot read {p}: {e}")
962
+ orig_tokens_est += max(200, st_b.st_size // 4)
963
+ ext = os.path.splitext(p)[1].lower()
964
+ keep = {s for s in symbols if s} or None
965
+ skel = Skeletonizer.skeletonize_code(code, ext, keep_symbols=keep)
966
+ imp_lines = sorted({m.group(0).strip() for m in _imp_line_re.finditer(skel)})
967
+ file_sections.append((p, skel, imp_lines))
968
+
969
+ if inc_deps and keep:
970
+ try:
971
+ graph, rel = GraphEngine.for_file(p)
972
+ if graph and rel:
973
+ for sym in keep:
974
+ # A class target's call edges live on its methods:
975
+ # resolve every qual key under the target symbol.
976
+ keys = [k for k in graph.symbols if k == f"{rel}::{sym}" or k.startswith(f"{rel}::{sym}::")]
977
+ for key in keys[:12]:
978
+ qual = key[len(rel) + 2:]
979
+ nb = graph.get_neighborhood(qual, target_file=rel)
980
+ for dep_key in sorted(nb.get("one_hop", [])):
981
+ dep_sym = graph.symbols.get(dep_key)
982
+ if not dep_sym:
983
+ continue
984
+ line = f" {qual} -> {dep_key[len(rel) + 2:]}: {dep_sym.signature.strip()[:160]}"
985
+ if line not in seen_dep_lines:
986
+ seen_dep_lines.add(line)
987
+ dep_lines.append(line)
988
+ except Exception:
989
+ pass
990
+
991
+ # Shared imports: lines present in 2+ files are emitted once
992
+ from collections import Counter
993
+ imp_counter = Counter()
994
+ for _p, _skel, imps in file_sections:
995
+ imp_counter.update(set(imps))
996
+ shared = sorted({ln for ln, cnt in imp_counter.items() if cnt >= 2 and len(ln) > 4})
997
+
998
+ parts: List[str] = []
999
+ if shared:
1000
+ parts.append("// [Shared imports — deduplicated across files]")
1001
+ parts.extend(f" {ln}" for ln in shared[:40])
1002
+ for p, skel, imps in file_sections:
1003
+ body = skel
1004
+ if shared:
1005
+ body = "\n".join(ln for ln in body.splitlines() if ln.strip() not in shared)
1006
+ parts.append(f"\n// ===== {os.path.basename(p)} ({len(by_file[p])} symbol target(s)) =====")
1007
+ parts.append(body)
1008
+ if dep_lines:
1009
+ parts.append("\n// [Merged 1-hop dependency signatures (deduplicated)]")
1010
+ parts.extend(dep_lines)
1011
+ bundle = "\n".join(parts)
1012
+
1013
+ bundle_t = count_tokens(bundle)
1014
+ if bundle_t > max_tokens and dep_lines:
1015
+ # Graceful degradation: drop the merged dependency signatures first
1016
+ deps_idx = bundle.find("\n// [Merged 1-hop dependency signatures")
1017
+ if deps_idx > 0:
1018
+ bundle = bundle[:deps_idx] + (
1019
+ f"\n// [TokenSafe smart_bundle: dependency signatures omitted (output cap {max_tokens} tokens)"
1020
+ " — narrow the 'targets' list for deeper detail.]"
1021
+ )
1022
+ bundle_t = count_tokens(bundle)
1023
+ if bundle_t > max_tokens:
1024
+ bundle += f"\n// [TokenSafe smart_bundle: output exceeds the {max_tokens}-token cap — narrow the 'targets' list.]"
1025
+
1026
+ tracker.record_event(
1027
+ session_id=_mcp_session_id(),
1028
+ event_type="BUNDLE",
1029
+ original_tokens=min(orig_tokens_est, 200000),
1030
+ optimized_tokens=bundle_t,
1031
+ details={"files": len(by_file), "targets": len(targets), "shared_imports": len(shared), "dep_lines": len(dep_lines)}
1032
+ )
1033
+ return {"content": [{"type": "text", "text": bundle}]}
1034
+
862
1035
  elif name == "compress_prompt":
863
1036
  prompt = args.get("prompt", "")
864
1037
  if is_quota_exceeded:
@@ -872,7 +1045,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
872
1045
  "warning": quota.get("warning") if emit_warn else "Community 500k monthly limit reached; prompt compaction paused.",
873
1046
  }
874
1047
  return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
875
- res = PromptCompactor.compact(prompt, enable_deepseek=True)
1048
+ res = PromptCompactor.compact(prompt, enable_distill=True)
876
1049
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
877
1050
 
878
1051
  elif name == "context_budget":
@@ -1154,6 +1327,34 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1154
1327
  "warning": quota.get("warning"),
1155
1328
  }, indent=2, ensure_ascii=False)}]}
1156
1329
  graph = GraphEngine.get_instance(target_abs)
1330
+ # Cap estimated crawl tokens to max 50,000 to prevent runaway spikes on large/root dirs
1331
+ capped_files = min(80, len(graph.file_symbols))
1332
+ est_crawl_tokens = min(50000, max(5000, capped_files * 600))
1333
+ topo_tokens = 250
1334
+
1335
+ # Shared Team Symbol Index: reuse a teammate's graph for the exact same
1336
+ # repo state (key = rel paths + sizes, so clones with identical trees hit).
1337
+ fp = _repo_fingerprint(graph)
1338
+ team_cached = None
1339
+ try:
1340
+ raw_cached = TeamCache.get("arch_index", fp)
1341
+ if raw_cached:
1342
+ team_cached = json.loads(raw_cached)
1343
+ except Exception:
1344
+ team_cached = None
1345
+ if isinstance(team_cached, dict) and team_cached.get("god_nodes") is not None:
1346
+ payload = dict(team_cached)
1347
+ payload["source"] = "team_symbol_index"
1348
+ hit_text = json.dumps(payload, indent=2, ensure_ascii=False)
1349
+ tracker.record_event(
1350
+ session_id=_mcp_session_id(),
1351
+ event_type="TEAM_CACHE_HIT",
1352
+ original_tokens=est_crawl_tokens,
1353
+ optimized_tokens=topo_tokens,
1354
+ details={"source": "team_symbol_index", "indexed_files": len(graph.file_symbols)}
1355
+ )
1356
+ return {"content": [{"type": "text", "text": hit_text}]}
1357
+
1157
1358
  god_nodes = graph.get_god_nodes(7)
1158
1359
  banner = graph.format_topology_banner()
1159
1360
  payload = {
@@ -1163,10 +1364,6 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1163
1364
  "total_symbols": len(graph.symbols),
1164
1365
  "god_nodes": god_nodes
1165
1366
  }
1166
- # Cap estimated crawl tokens to max 50,000 to prevent runaway spikes on large/root dirs
1167
- capped_files = min(80, len(graph.file_symbols))
1168
- est_crawl_tokens = min(50000, max(5000, capped_files * 600))
1169
- topo_tokens = 250
1170
1367
  tracker.record_event(
1171
1368
  session_id=_mcp_session_id(),
1172
1369
  event_type="GRAPH_TOPOLOGY",
@@ -1174,6 +1371,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1174
1371
  optimized_tokens=topo_tokens,
1175
1372
  details={"hubs_count": len(god_nodes), "indexed_files": len(graph.file_symbols)}
1176
1373
  )
1374
+ try:
1375
+ TeamCache.put("arch_index", fp, json.dumps(payload, ensure_ascii=False, default=str))
1376
+ except Exception:
1377
+ pass
1177
1378
  return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
1178
1379
 
1179
1380
  elif name == "get_api_surface":
@@ -1187,11 +1388,29 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1187
1388
  LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
1188
1389
  return {"content": [{"type": "text", "text": f"{quota.get('warning', '')}\n\nAPI surface map generation is paused over the 500k Community limit. Use scoped_search or list_dir, or activate a subscription at https://tokensafe.dev/#pricing."}]}
1189
1390
  graph = GraphEngine.get_instance(target_abs)
1190
- surface_md = graph.generate_api_surface()
1191
- surface_tokens = count_tokens(surface_md)
1192
1391
  # Cap estimated crawl tokens to max 60,000
1193
1392
  capped_files = min(100, len(graph.file_symbols))
1194
1393
  est_orig_tokens = min(60000, max(10000, capped_files * 600))
1394
+
1395
+ # Shared Team Symbol Index surface variant (separate key from the graph payload)
1396
+ fp = _repo_fingerprint(graph) + ":surface"
1397
+ team_cached_md = None
1398
+ try:
1399
+ team_cached_md = TeamCache.get("arch_index", fp)
1400
+ except Exception:
1401
+ team_cached_md = None
1402
+ if team_cached_md:
1403
+ tracker.record_event(
1404
+ session_id=_mcp_session_id(),
1405
+ event_type="TEAM_CACHE_HIT",
1406
+ original_tokens=est_orig_tokens,
1407
+ optimized_tokens=count_tokens(team_cached_md),
1408
+ details={"source": "team_symbol_index", "type": "API_SURFACE"}
1409
+ )
1410
+ return {"content": [{"type": "text", "text": team_cached_md}]}
1411
+
1412
+ surface_md = graph.generate_api_surface()
1413
+ surface_tokens = count_tokens(surface_md)
1195
1414
  tracker.record_event(
1196
1415
  session_id=_mcp_session_id(),
1197
1416
  event_type="GRAPH_TOPOLOGY",
@@ -1199,6 +1418,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1199
1418
  optimized_tokens=surface_tokens,
1200
1419
  details={"type": "API_SURFACE", "symbols_count": len(graph.symbols)}
1201
1420
  )
1421
+ try:
1422
+ TeamCache.put("arch_index", fp, surface_md[:200000])
1423
+ except Exception:
1424
+ pass
1202
1425
  return {"content": [{"type": "text", "text": surface_md}]}
1203
1426
 
1204
1427
  elif name == "list_dir":
@@ -1384,6 +1607,11 @@ def run_mcp_server():
1384
1607
  tool_name = str(params.get("name") or "")
1385
1608
  raw_tool_args = params.get("arguments")
1386
1609
  tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
1610
+ if not tool_args and raw_tool_args:
1611
+ # Self-healing: hosts on small/local models intermittently send
1612
+ # arguments as a malformed JSON string — repair before failing.
1613
+ from src.json_repair import parse_tool_arguments
1614
+ tool_args = parse_tool_arguments(raw_tool_args) or {}
1387
1615
  try:
1388
1616
  response["result"] = _execute_with_timeout(tool_name, tool_args)
1389
1617
  except Exception as e: