tokensafe 4.5.0 → 4.5.1

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.
Files changed (62) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +28 -10
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +10 -4
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -24
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -86
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +73 -22
  22. package/src/batch_search.py +31 -11
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +34 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +31 -9
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_server.py +487 -48
  43. package/src/metrics.py +10 -1
  44. package/src/mistakes.py +4 -2
  45. package/src/paths.py +4 -1
  46. package/src/proxy.py +302 -123
  47. package/src/result_ledger.py +39 -1
  48. package/src/schema_slicer.py +40 -18
  49. package/src/scoped_search.py +66 -23
  50. package/src/skeletonizer.py +22 -11
  51. package/src/slicer.py +6 -4
  52. package/src/stash.py +37 -7
  53. package/src/superseded.py +42 -23
  54. package/src/syntax_guard.py +2 -0
  55. package/src/team_cache.py +3 -0
  56. package/src/telemetry_sync.py +66 -53
  57. package/src/thinking_fold.py +50 -12
  58. package/src/transcript_analyzer.py +270 -68
  59. package/src/treesitter_backend.py +2 -0
  60. package/src/type_slicer.py +60 -18
  61. package/src/version_checker.py +1 -1
  62. package/src/web_reader.py +55 -22
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.5.0"
45
+ "version": "4.5.1"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -77,7 +77,7 @@ def _client_supports_pointers() -> bool:
77
77
  return bool(_MCP_CLIENT_NAME and any(k in _MCP_CLIENT_NAME for k in _KNOWN_POINTER_CLIENTS))
78
78
 
79
79
 
80
- TOOLS = [ { 'annotations': {'readOnlyHint': True},
80
+ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
81
81
  'description': 'AST-skeleton file reader: keeps the target function/class body + 1-line 1-hop dependency '
82
82
  'signatures, folds inert code (-90-99% tokens). Relative or absolute paths. Schema files '
83
83
  "(OpenAPI/Prisma/GraphQL/SQL) auto-slice via 'symbol'. For 3+ related symbols use smart_bundle "
@@ -471,6 +471,20 @@ TOOLS = [ { 'annotations': {'readOnlyHint': True},
471
471
  'required': ['target'],
472
472
  'type': 'object'},
473
473
  'name': 'oumv_verify'},
474
+ { 'annotations': {'readOnlyHint': True},
475
+ 'description': 'Unified cross-stack intelligence graph (spec §11): nodes and edges across frontend actions '
476
+ 'and backend endpoints with evidence metadata. Queries: overview (graph summary, optionally '
477
+ 'filtered by target), who_depends_on (which frontend code calls an endpoint), impact (affected '
478
+ 'callers + suggested verification steps).',
479
+ 'inputSchema': { 'properties': { 'query': { 'default': 'overview',
480
+ 'description': 'Graph query (overview, who_depends_on, impact)',
481
+ 'enum': ['overview', 'who_depends_on', 'impact'],
482
+ 'type': 'string'},
483
+ 'target': { 'description': "Target resource (e.g. '/api/orders' or "
484
+ "'POST /api/orders')",
485
+ 'type': 'string'}},
486
+ 'type': 'object'},
487
+ 'name': 'oumv_graph'},
474
488
  { 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
475
489
  'description': 'Atomic or best-effort multi-hunk and multi-file code editor (up to 50 files) with optional '
476
490
  'inline verification command (e.g. npm test, pytest). Replaces serial single-hunk edit turns. '
@@ -627,6 +641,222 @@ TOOLS = [ { 'annotations': {'readOnlyHint': True},
627
641
  'type': 'object'},
628
642
  'name': 'batch_search'}]
629
643
 
644
+ # Compact MCP surface (default): 7 consolidated tools (~2.2k tok vs ~6.0k tok for 28 schemas).
645
+ # All 28 legacy tool names remain callable in _dispatch_tool_call for backward compatibility.
646
+ # Set TOKENSAFE_MCP_PROFILE=full to expose FULL_TOOLS in tools/list.
647
+ TOOLS = [
648
+ {
649
+ 'name': 'smart_read_file',
650
+ 'description': (
651
+ 'AST-skeleton reader (-90-98% tokens). Pass path+symbol for one file (auto-slices '
652
+ 'OpenAPI/Prisma/GraphQL/SQL/lockfiles), targets=[{path,symbol}] to bundle 2-8 symbols, '
653
+ 'or package_name+symbol for 3rd-party .d.ts types.'
654
+ ),
655
+ 'annotations': {'readOnlyHint': True},
656
+ 'inputSchema': {
657
+ 'type': 'object',
658
+ 'properties': {
659
+ 'path': {'type': 'string', 'description': 'File path (relative or absolute)'},
660
+ 'symbol': {'type': 'string', 'description': 'Function/class/model/type to extract'},
661
+ 'start_line': {'type': 'integer', 'description': 'Optional start line'},
662
+ 'end_line': {'type': 'integer', 'description': 'Optional end line'},
663
+ 'dep_mode': {'type': 'string', 'enum': ['signature', 'full'], 'description': '1-hop dep mode (default signature)'},
664
+ 'include_deps': {'type': 'boolean', 'description': 'Include 1-hop deps (default true)'},
665
+ 'force_full': {'type': 'boolean', 'description': 'Bypass pointer dedup'},
666
+ 'project_root': {'type': 'string', 'description': 'Workspace root directory (for external types / lockfiles)'},
667
+ 'targets': {
668
+ 'type': 'array', 'maxItems': 8,
669
+ 'description': 'Bundle mode: 2-8 {path, symbol} targets in one call',
670
+ 'items': {'type': 'object', 'properties': {'path': {'type': 'string'}, 'symbol': {'type': 'string'}}, 'required': ['path']},
671
+ },
672
+ 'package_name': {'type': 'string', 'description': 'External .d.ts npm package name'},
673
+ },
674
+ },
675
+ },
676
+ {
677
+ 'name': 'scoped_search',
678
+ 'description': (
679
+ 'Safe token-bounded search replacing grep/find (-90% tokens). Pass query+scope for single '
680
+ 'search (mode/type: auto|text|regex|glob|fuzzy|git), or queries=[{pattern,type,path,glob}] '
681
+ 'for up to 20 concurrent queries.'
682
+ ),
683
+ 'annotations': {'readOnlyHint': True},
684
+ 'inputSchema': {
685
+ 'type': 'object',
686
+ 'properties': {
687
+ 'query': {'type': 'string', 'description': 'Text, symbol, regex, glob, or read-only git query'},
688
+ 'mode': {'type': 'string', 'enum': ['auto', 'text', 'regex', 'glob', 'fuzzy', 'git'], 'description': 'Single-query mode'},
689
+ 'scope': {'type': 'string', 'description': "'code', 'config', 'all', ext ('py'), or subfolder"},
690
+ 'path': {'type': 'string', 'description': 'Directory path (default project root)'},
691
+ 'project_path': {'type': 'string', 'description': 'Alias for path'},
692
+ 'use_regex': {'type': 'boolean', 'description': 'Force regex true/false'},
693
+ 'case_sensitive': {'type': 'boolean'},
694
+ 'max_results': {'type': 'integer', 'description': 'Max lines (default 25, max 100)'},
695
+ 'queries': {
696
+ 'type': 'array', 'maxItems': 20,
697
+ 'description': 'Batch mode: up to 20 {pattern, type, path, glob, output_mode} objects',
698
+ 'items': {
699
+ 'type': 'object',
700
+ 'properties': {
701
+ 'pattern': {'type': 'string'},
702
+ 'type': {'type': 'string', 'enum': ['text', 'regex', 'glob', 'fuzzy', 'git']},
703
+ 'path': {'type': 'string'},
704
+ 'glob': {'type': 'string'},
705
+ 'file_type': {'type': 'string'},
706
+ 'output_mode': {'type': 'string', 'enum': ['content', 'files_with_matches', 'count']},
707
+ 'case_sensitive': {'type': 'boolean'},
708
+ 'max_results': {'type': 'integer'},
709
+ },
710
+ 'required': ['pattern'],
711
+ },
712
+ },
713
+ 'cwd': {'type': 'string', 'description': 'Optional working directory for batch mode'},
714
+ },
715
+ },
716
+ },
717
+ {
718
+ 'name': 'apply_edits',
719
+ 'description': 'Atomic/best-effort multi-hunk editor (up to 50 files) with optional inline verify command.',
720
+ 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
721
+ 'inputSchema': {
722
+ 'type': 'object',
723
+ 'properties': {
724
+ 'edits': {
725
+ 'type': 'array', 'maxItems': 50,
726
+ 'items': {
727
+ 'type': 'object',
728
+ 'properties': {
729
+ 'path': {'type': 'string'},
730
+ 'create': {'type': 'string'},
731
+ 'overwrite': {'type': 'boolean'},
732
+ 'hunks': {
733
+ 'type': 'array',
734
+ 'items': {
735
+ 'type': 'object',
736
+ 'properties': {
737
+ 'target': {'type': 'string'},
738
+ 'replacement': {'type': 'string'},
739
+ 'start_line': {'type': 'integer'},
740
+ 'end_line': {'type': 'integer'},
741
+ 'replace_all': {'type': 'boolean'},
742
+ },
743
+ 'required': ['target', 'replacement'],
744
+ },
745
+ },
746
+ },
747
+ 'required': ['path'],
748
+ },
749
+ },
750
+ 'best_effort': {'type': 'boolean'},
751
+ 'dry_run': {'type': 'boolean'},
752
+ 'verify': {'type': 'string', 'description': 'Shell command to run after edits (e.g. pytest, npm test)'},
753
+ 'verify_timeout_sec': {'type': 'integer'},
754
+ 'cwd': {'type': 'string'},
755
+ },
756
+ 'required': ['edits'],
757
+ },
758
+ },
759
+ {
760
+ 'name': 'repo_map',
761
+ 'description': (
762
+ 'Project structure & architecture without crawling: view="graph" (God Nodes & deps), '
763
+ '"api" (exported classes/types/interfaces), or "tree" (clean directory tree).'
764
+ ),
765
+ 'annotations': {'readOnlyHint': True},
766
+ 'inputSchema': {
767
+ 'type': 'object',
768
+ 'properties': {
769
+ 'view': {'type': 'string', 'enum': ['graph', 'api', 'tree'], 'default': 'graph'},
770
+ 'project_path': {'type': 'string', 'description': 'Project root (pass absolute path in multi-repo setups)'},
771
+ 'path': {'type': 'string', 'description': "Directory path for view='tree' (default '.')"},
772
+ 'depth': {'type': 'integer', 'description': 'Tree depth (default 2, max 4)'},
773
+ 'max_entries': {'type': 'integer'},
774
+ },
775
+ },
776
+ },
777
+ {
778
+ 'name': 'session_context',
779
+ 'description': (
780
+ 'Session & context hygiene: action="budget" (Context Quality Score S-F), "compact" (fold transcript '
781
+ 'to State Ledger), "prune" (drop superseded reads), "mistakes" (anti-stuck memory), or "metrics".'
782
+ ),
783
+ 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
784
+ 'inputSchema': {
785
+ 'type': 'object',
786
+ 'properties': {
787
+ 'action': {'type': 'string', 'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics'], 'default': 'budget'},
788
+ 'model': {'type': 'string'},
789
+ 'session_id': {'type': 'string'},
790
+ 'transcript_path': {'type': 'string'},
791
+ 'window_tokens': {'type': 'integer'},
792
+ 'invocation_num': {'type': 'integer'},
793
+ 'project_root': {'type': 'string'},
794
+ 'clear': {'type': 'boolean'},
795
+ },
796
+ 'required': ['action'],
797
+ },
798
+ },
799
+ {
800
+ 'name': 'oumv',
801
+ 'description': (
802
+ 'Live Frontend/Backend OUMV runtime protocol: action="status"|"observe" (L0-L4)|"understand" '
803
+ '(causality/impact)|"verify" (in-memory sandbox)|"mutate" (OCC edit)|"graph" (cross-stack).'
804
+ ),
805
+ 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
806
+ 'inputSchema': {
807
+ 'type': 'object',
808
+ 'properties': {
809
+ 'action': {'type': 'string', 'enum': ['status', 'observe', 'understand', 'mutate', 'verify', 'graph'], 'default': 'status'},
810
+ 'level': {'type': 'string', 'enum': ['L0', 'L1', 'L2', 'L3', 'L4']},
811
+ 'query': {'type': 'string'},
812
+ 'runtime': {'type': 'string', 'enum': ['frontend', 'backend', 'auto']},
813
+ 'target': {'type': 'string'},
814
+ 'path': {'type': 'string'},
815
+ 'symbol': {'type': 'string'},
816
+ 'replacement': {'type': 'string'},
817
+ 'expectedVersion': {'type': 'string'},
818
+ 'verify_action': {'type': 'string', 'description': "Action name for action='verify' (e.g. click, submit)"},
819
+ 'payload': {'type': 'object'},
820
+ 'workspace_dir': {'type': 'string'},
821
+ },
822
+ 'required': ['action'],
823
+ },
824
+ },
825
+ {
826
+ 'name': 'run_helper',
827
+ 'description': (
828
+ 'Unified utility runner: action="sanitize" (rewrite bash/tests), "guard" (security/hygiene check), '
829
+ '"diff" (slice diff), "deps" (query lockfile), "web" (fetch clean MD), "expand" (unfold #hash), '
830
+ '"image" (downscale), or "compress" (TOCP prompt).'
831
+ ),
832
+ 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
833
+ 'inputSchema': {
834
+ 'type': 'object',
835
+ 'properties': {
836
+ 'action': {
837
+ 'type': 'string',
838
+ 'enum': ['sanitize', 'guard', 'diff', 'deps', 'web', 'expand', 'image', 'compress'],
839
+ },
840
+ 'command': {'type': 'string'},
841
+ 'code': {'type': 'string'},
842
+ 'file_path': {'type': 'string'},
843
+ 'diff': {'type': 'string'},
844
+ 'max_context': {'type': 'integer'},
845
+ 'package_name': {'type': 'string'},
846
+ 'lockfile_path': {'type': 'string'},
847
+ 'url': {'type': 'string'},
848
+ 'force_refresh': {'type': 'boolean'},
849
+ 'hash': {'type': 'string'},
850
+ 'image_path': {'type': 'string'},
851
+ 'max_edge': {'type': 'integer'},
852
+ 'prompt': {'type': 'string'},
853
+ 'cwd': {'type': 'string'},
854
+ },
855
+ 'required': ['action'],
856
+ },
857
+ },
858
+ ]
859
+
630
860
  def format_file_size(size_bytes: int) -> str:
631
861
  if size_bytes < 1024:
632
862
  return f"{size_bytes} B"
@@ -1028,9 +1258,17 @@ def handle_tool_call(name: str, args: dict) -> dict:
1028
1258
  _, eff_dep_mode = _resolve_dep_mode(args)
1029
1259
  cache_sym = f"{symbol}@{eff_dep_mode}" if (symbol and eff_dep_mode != "signature") else symbol
1030
1260
  is_ranged = args.get("start_line") is not None or args.get("end_line") is not None
1031
- is_quota_truncated = "[TokenSafe Community 500k limit reached:" in text_out or "// Quota exceeded" in text_out
1261
+ is_quota_truncated = (
1262
+ "[TokenSafe Community 500k limit reached:" in text_out
1263
+ or "// Quota exceeded" in text_out
1264
+ or ("monthly limit (" in text_out and "optimizations paused" in text_out)
1265
+ )
1032
1266
  if text_out and path and not is_ranged and not is_quota_truncated:
1033
- abs_path = os.path.abspath(path)
1267
+ active_ws = get_active_workspace()
1268
+ if not os.path.isabs(path) and active_ws and os.path.exists(os.path.join(active_ws, path)):
1269
+ abs_path = os.path.abspath(os.path.join(active_ws, path))
1270
+ else:
1271
+ abs_path = os.path.abspath(path)
1034
1272
  cur_hash = AgentFirewall._file_content_hash(abs_path)
1035
1273
  if cur_hash:
1036
1274
  _IN_PROCESS_DELIVERED[(abs_path, symbol, eff_dep_mode)] = (cur_hash, _EPOCH_GEN)
@@ -1039,7 +1277,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
1039
1277
  try:
1040
1278
  AgentFirewall.record_cache(
1041
1279
  session_id=_mcp_session_id(),
1042
- file_path=path,
1280
+ file_path=abs_path,
1043
1281
  content=text_out,
1044
1282
  symbol=cache_sym,
1045
1283
  tracker=_get_safe_tracker()
@@ -1069,8 +1307,100 @@ def _tier_quota_limit_msg(quota: dict) -> str:
1069
1307
  return f"{tier_name} monthly limit ({limit:,} tokens) reached; optimizations paused ({cta})."
1070
1308
 
1071
1309
 
1310
+ _REPO_MAP_ACTIONS = {
1311
+ "graph": "get_architecture_graph",
1312
+ "api": "get_api_surface",
1313
+ "tree": "list_dir",
1314
+ }
1315
+ _SESSION_CONTEXT_ACTIONS = {
1316
+ "budget": "context_budget",
1317
+ "compact": "compact_conversation",
1318
+ "prune": "prune_superseded",
1319
+ "mistakes": "get_mistakes",
1320
+ "metrics": "get_token_savings_metrics",
1321
+ }
1322
+ _OUMV_ACTIONS = {
1323
+ "status": "oumv_status",
1324
+ "observe": "oumv_observe",
1325
+ "understand": "oumv_understand",
1326
+ "mutate": "oumv_mutate",
1327
+ "verify": "oumv_verify",
1328
+ "graph": "oumv_graph",
1329
+ }
1330
+ _HELPER_ACTIONS = {
1331
+ "sanitize": "sanitize_command",
1332
+ "guard": "guard_inspect",
1333
+ "diff": "slice_diff",
1334
+ "deps": "query_dependency",
1335
+ "web": "read_web_page",
1336
+ "expand": "expand_ref",
1337
+ "image": "optimize_image",
1338
+ "compress": "compress_prompt",
1339
+ }
1340
+
1341
+
1072
1342
  def _dispatch_tool_call(name: str, args: dict) -> dict:
1073
1343
  global _EPOCH_GEN
1344
+ # Route consolidated tools to canonical internal handlers (zero logic duplication).
1345
+ if name == "smart_read_file":
1346
+ if args.get("targets"):
1347
+ name = "smart_bundle"
1348
+ elif args.get("package_name") and not (args.get("path") or args.get("file_path") or args.get("file")):
1349
+ name = "slice_external_type"
1350
+ elif name == "scoped_search":
1351
+ mode = str(args.get("mode") or "").strip().lower()
1352
+ if args.get("queries"):
1353
+ name = "batch_search"
1354
+ elif mode in ("glob", "fuzzy", "git"):
1355
+ q = args.get("query") or args.get("pattern") or ""
1356
+ q_spec = {
1357
+ "pattern": q,
1358
+ "type": mode,
1359
+ "path": args.get("path") or args.get("project_path") or "",
1360
+ "case_sensitive": bool(args.get("case_sensitive", False)),
1361
+ "max_results": int(args.get("max_results") or 25),
1362
+ }
1363
+ raw_sc = str(args.get("scope") or "").strip()
1364
+ if raw_sc.startswith("*.") or "*" in raw_sc:
1365
+ q_spec["glob"] = raw_sc
1366
+ elif raw_sc and raw_sc.lower() not in ("all", "code", "config"):
1367
+ q_spec["file_type"] = raw_sc.lstrip(".")
1368
+ args = {
1369
+ "queries": [q_spec],
1370
+ "cwd": args.get("cwd") or args.get("project_path") or args.get("path"),
1371
+ }
1372
+ name = "batch_search"
1373
+ elif mode in ("text", "regex") and args.get("use_regex") is None:
1374
+ args = dict(args, use_regex=(mode == "regex"))
1375
+ elif name == "repo_map":
1376
+ view = str(args.get("view") or "graph").strip().lower()
1377
+ if view not in _REPO_MAP_ACTIONS:
1378
+ return _fallback_error("repo_map", f"unknown view '{view}' (expected graph|api|tree)")
1379
+ mapped = _REPO_MAP_ACTIONS[view]
1380
+ if view == "tree" and not args.get("path"):
1381
+ args = dict(args, path=args.get("project_path") or ".")
1382
+ elif view in ("graph", "api") and not args.get("project_path") and args.get("path"):
1383
+ args = dict(args, project_path=args.get("path"))
1384
+ name = mapped
1385
+ elif name == "session_context":
1386
+ action = str(args.get("action") or "budget").strip().lower()
1387
+ if action not in _SESSION_CONTEXT_ACTIONS:
1388
+ return _fallback_error("session_context", f"unknown action '{action}'")
1389
+ name = _SESSION_CONTEXT_ACTIONS[action]
1390
+ elif name == "oumv":
1391
+ action = str(args.get("action") or "status").strip().lower()
1392
+ if action not in _OUMV_ACTIONS:
1393
+ return _fallback_error("oumv", f"unknown action '{action}'")
1394
+ mapped = _OUMV_ACTIONS[action]
1395
+ if action == "verify":
1396
+ args = dict(args, action=args.get("verify_action") or "invoke")
1397
+ name = mapped
1398
+ elif name == "run_helper":
1399
+ action = str(args.get("action") or "").strip().lower()
1400
+ if action not in _HELPER_ACTIONS:
1401
+ return _fallback_error("run_helper", f"unknown action '{action}'")
1402
+ name = _HELPER_ACTIONS[action]
1403
+
1074
1404
  tracker = _get_safe_tracker()
1075
1405
  quota = LicenseManager.check_quota(tracker)
1076
1406
  is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
@@ -1272,12 +1602,14 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1272
1602
  allow_pointer = (not force_full) and _client_supports_pointers() and already_here
1273
1603
  is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
1274
1604
  _mcp_session_id(),
1275
- path,
1605
+ abs_path,
1276
1606
  symbol=cache_sym,
1277
1607
  tracker=tracker,
1278
1608
  allow_pointer=allow_pointer,
1279
1609
  )
1280
1610
  if is_hit and cached_text:
1611
+ if cur_hash and not already_here:
1612
+ _IN_PROCESS_DELIVERED[(abs_path, sym_clean, eff_dep_mode)] = (cur_hash, _EPOCH_GEN)
1281
1613
  return {"content": [{"type": "text", "text": cached_text}]}
1282
1614
 
1283
1615
  # Check loop detector (skip when force_full explicitly recovers from a pointer)
@@ -1480,7 +1812,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1480
1812
  dep_sym = graph.symbols.get(dep_key)
1481
1813
  if not dep_sym:
1482
1814
  continue
1483
- line = f" {qual} -> {dep_key[len(rel) + 2:]}: {dep_sym.signature.strip()[:160]}"
1815
+ line = f" {qual} -> {dep_key.split('::', 1)[-1]}: {dep_sym.signature.strip()[:160]}"
1484
1816
  if line not in seen_dep_lines:
1485
1817
  seen_dep_lines.add(line)
1486
1818
  dep_lines.append(line)
@@ -1972,12 +2304,6 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1972
2304
  return {"content": [{"type": "text", "text": tree_output}]}
1973
2305
 
1974
2306
  elif name == "scoped_search":
1975
- if args.get("queries"):
1976
- from src.batch_search import execute_batch_search
1977
- cwd = args.get("cwd") or get_active_workspace()
1978
- res = execute_batch_search(queries=args.get("queries"), cwd=cwd)
1979
- return {"content": [{"type": "text", "text": res.get("summary_md", "")}]}
1980
-
1981
2307
  query = args.get("query") or args.get("q") or args.get("pattern") or args.get("text") or ""
1982
2308
  if not query:
1983
2309
  return _fallback_error("scoped_search", "missing required 'query' argument")
@@ -2009,12 +2335,21 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2009
2335
  # 2. Smart scope routing: handle agents passing subdirectories or extensions in `scope`
2010
2336
  scope = raw_scope
2011
2337
  if raw_scope and raw_scope.lower() not in ("code", "config", "all"):
2012
- candidate_subdir = os.path.normpath(os.path.join(target_path, raw_scope))
2338
+ real_base = os.path.realpath(target_path)
2339
+ candidate_subdir = os.path.realpath(os.path.normpath(os.path.join(target_path, raw_scope)))
2340
+ try:
2341
+ within_base = os.path.commonpath([real_base, candidate_subdir]) == real_base
2342
+ except ValueError:
2343
+ within_base = False
2013
2344
  if os.path.isdir(candidate_subdir):
2345
+ if not within_base or is_plugin_or_system_dir(candidate_subdir):
2346
+ return _fallback_error("scoped_search", f"refusing to search outside target directory via scope '{raw_scope}'")
2014
2347
  target_path = candidate_subdir
2015
2348
  scope = "all"
2016
2349
  elif "/" in raw_scope or "\\" in raw_scope:
2017
2350
  if os.path.exists(candidate_subdir):
2351
+ if not within_base or is_plugin_or_system_dir(candidate_subdir):
2352
+ return _fallback_error("scoped_search", f"refusing to search outside target directory via scope '{raw_scope}'")
2018
2353
  target_path = candidate_subdir
2019
2354
  scope = "all"
2020
2355
 
@@ -2110,10 +2445,28 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2110
2445
  elif name == "query_dependency":
2111
2446
  pkg = str(args.get("package_name") or args.get("package") or "").strip()
2112
2447
  lock_p = str(args.get("lockfile_path") or args.get("path") or "").strip() or None
2448
+ if lock_p and not os.path.isabs(lock_p):
2449
+ active_ws = get_active_workspace()
2450
+ if active_ws and os.path.exists(os.path.join(active_ws, lock_p)):
2451
+ lock_p = os.path.abspath(os.path.join(active_ws, lock_p))
2113
2452
  if not pkg:
2114
2453
  return _fallback_error("query_dependency", "missing required 'package_name' argument")
2115
2454
  try:
2116
2455
  from src.format_parsers.lockfiles import LockfileReducer
2456
+ if not lock_p:
2457
+ active_ws = get_active_workspace()
2458
+ if active_ws and hasattr(LockfileReducer, "find_lockfile"):
2459
+ orig_cwd = os.getcwd()
2460
+ try:
2461
+ os.chdir(active_ws)
2462
+ lock_p = LockfileReducer.find_lockfile()
2463
+ except Exception:
2464
+ lock_p = None
2465
+ finally:
2466
+ try:
2467
+ os.chdir(orig_cwd)
2468
+ except Exception:
2469
+ pass
2117
2470
  res = LockfileReducer.query_dependency(lock_p, pkg)
2118
2471
  lock_bytes = res.pop("_lockfile_bytes", 0)
2119
2472
  json_text = json.dumps(res, indent=2, ensure_ascii=False)
@@ -2136,7 +2489,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2136
2489
  elif name == "slice_external_type":
2137
2490
  pkg = str(args.get("package_name") or args.get("package") or "").strip()
2138
2491
  sym = str(args.get("symbol") or args.get("type") or args.get("type_name") or "").strip()
2139
- proj_root = str(args.get("project_root") or "").strip() or None
2492
+ proj_root = str(args.get("project_root") or "").strip() or get_active_workspace() or None
2140
2493
  if not pkg or not sym:
2141
2494
  return _fallback_error("slice_external_type", "missing required 'package_name' or 'symbol' argument")
2142
2495
  try:
@@ -2191,6 +2544,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2191
2544
  res = SupersededPruner.prune_transcript(t_path)
2192
2545
  if not res.get("success"):
2193
2546
  return _fallback_error("prune_superseded", res.get("error", "pruning failed"))
2547
+ _EPOCH_GEN += 1
2194
2548
  if res.get("saved_tokens", 0) > 0:
2195
2549
  tracker.record_event(
2196
2550
  session_id=_mcp_session_id(),
@@ -2226,7 +2580,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2226
2580
  elif name == "oumv_status":
2227
2581
  try:
2228
2582
  from src.oumv_gateway import OUMVGateway
2229
- ws = str(args.get("workspace_dir") or "").strip() or None
2583
+ ws = str(args.get("workspace_dir") or "").strip() or get_active_workspace() or os.getcwd()
2230
2584
  res = OUMVGateway.status(workspace_dir=ws)
2231
2585
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2232
2586
  except Exception as e:
@@ -2277,7 +2631,17 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2277
2631
  res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt)
2278
2632
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2279
2633
  except Exception as e:
2280
- return _fallback_error("oumv_verify", f"failed to execute OUMV verification: {e}")
2634
+ return _fallback_error("oumv_verify", f"failed to verify OUMV action: {e}")
2635
+
2636
+ elif name == "oumv_graph":
2637
+ try:
2638
+ from src.oumv_gateway import OUMVGateway
2639
+ qry = str(args.get("query") or "overview").strip()
2640
+ tgt = str(args.get("target") or "").strip() or None
2641
+ res = OUMVGateway.graph(query=qry, target=tgt)
2642
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2643
+ except Exception as e:
2644
+ return _fallback_error("oumv_graph", f"failed to query cross-stack graph: {e}")
2281
2645
 
2282
2646
  elif name == "apply_edits":
2283
2647
  try:
@@ -2303,15 +2667,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2303
2667
  if res.get("success"):
2304
2668
  action_desc = "Validated" if dry_run else "Applied"
2305
2669
  lines.append(f"✔ {action_desc} {res.get('applied_count', 0)} file(s) successfully.")
2670
+ else:
2671
+ lines.append(f"✖ Batch edits failed ({res.get('failed_count', 0)} error(s)).")
2672
+ for f in res.get("failed_files", []):
2673
+ lines.append(f" - `{f.get('path')}`: {f.get('error')}")
2674
+
2675
+ if res.get("applied_files"):
2676
+ if not res.get("success"):
2677
+ lines.append(f"Applied {len(res['applied_files'])} file(s) before error/verify:")
2306
2678
  for f in res.get("applied_files", []):
2307
2679
  h_cnt = f.get("hunks", 0)
2308
2680
  is_cr = f.get("is_create", False)
2309
2681
  label = "created" if is_cr else f"{h_cnt} hunk(s)"
2310
2682
  lines.append(f" - `{f.get('path')}` ({label})")
2311
- else:
2312
- lines.append(f"✖ Batch edits failed ({res.get('failed_count', 0)} error(s)).")
2313
- for f in res.get("failed_files", []):
2314
- lines.append(f" - `{f.get('path')}`: {f.get('error')}")
2315
2683
 
2316
2684
  if "verify" in res:
2317
2685
  v = res["verify"]
@@ -2322,7 +2690,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2322
2690
  elif v.get("error"):
2323
2691
  lines.append(f"Error: {v['error']}")
2324
2692
 
2325
- return {"content": [{"type": "text", "text": "\n".join(lines)}]}
2693
+ out_msg = {"content": [{"type": "text", "text": "\n".join(lines)}]}
2694
+ if not res.get("success"):
2695
+ out_msg["isError"] = True
2696
+ return out_msg
2326
2697
  except Exception as e:
2327
2698
  return _fallback_error("apply_edits", f"failed to execute batch edits: {e}")
2328
2699
 
@@ -2337,9 +2708,67 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2337
2708
  if not queries:
2338
2709
  return _fallback_error("batch_search", "missing required 'queries' list")
2339
2710
 
2340
- cwd = args.get("cwd") or get_active_workspace()
2341
- res = execute_batch_search(queries=queries, cwd=cwd)
2342
- return {"content": [{"type": "text", "text": res.get("summary_md", "")}]}
2711
+ raw_cwd = args.get("cwd") or args.get("project_path") or args.get("path")
2712
+ active_ws = get_active_workspace()
2713
+ if raw_cwd:
2714
+ if not os.path.isabs(raw_cwd) and active_ws and os.path.isdir(os.path.join(active_ws, raw_cwd)):
2715
+ cwd = os.path.abspath(os.path.join(active_ws, raw_cwd))
2716
+ else:
2717
+ cwd = os.path.abspath(raw_cwd)
2718
+ else:
2719
+ cwd, err = _resolve_project_root(args)
2720
+ if err or not cwd:
2721
+ return _fallback_error("batch_search", err or "unspecified project_path")
2722
+ if is_plugin_or_system_dir(cwd):
2723
+ return _fallback_error("batch_search", f"refusing to search system root or plugin dir '{cwd}'")
2724
+
2725
+ safe_queries: List[Dict[str, Any]] = []
2726
+ real_cwd = os.path.realpath(cwd)
2727
+ for q_item in queries:
2728
+ if not isinstance(q_item, dict):
2729
+ safe_queries.append(q_item)
2730
+ continue
2731
+ q_copy = dict(q_item)
2732
+ sub_p = q_copy.get("path")
2733
+ if sub_p:
2734
+ sub_abs = os.path.realpath(os.path.normpath(os.path.join(cwd, str(sub_p))))
2735
+ try:
2736
+ inside = os.path.commonpath([real_cwd, sub_abs]) == real_cwd
2737
+ except ValueError:
2738
+ inside = False
2739
+ if not inside or is_plugin_or_system_dir(sub_abs):
2740
+ return _fallback_error("batch_search", f"refusing subquery path outside project root '{sub_p}'")
2741
+ if is_quota_exceeded:
2742
+ q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
2743
+ safe_queries.append(q_copy)
2744
+
2745
+ res = execute_batch_search(queries=safe_queries, cwd=cwd)
2746
+ summary_md = res.get("summary_md", "")
2747
+ if is_quota_exceeded:
2748
+ banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
2749
+ current_tier = str(quota.get("tier") or "guest").lower()
2750
+ limit_val = int(quota.get("monthly_limit") or (50000 if current_tier == "guest" else 500000))
2751
+ cta_note = (
2752
+ "Run 'tokensafe login' in your terminal to unlock 500,000 free tokens/month!"
2753
+ if current_tier == "guest"
2754
+ else "Upgrade to Solo for unlimited optimization: https://tokensafe.dev/pricing"
2755
+ )
2756
+ degraded_header = (
2757
+ f"// [TokenSafe Quota Notice: {current_tier.upper()} limit of {limit_val:,} tokens reached. "
2758
+ f"Showing up to 3 matches per query in degraded mode.]\n"
2759
+ f"// [{cta_note}]\n\n"
2760
+ )
2761
+ return {"content": [{"type": "text", "text": banner + degraded_header + summary_md}]}
2762
+ res_tokens = count_tokens(summary_md)
2763
+ est_orig = max(1500, res_tokens * 8)
2764
+ tracker.record_event(
2765
+ session_id=_mcp_session_id(),
2766
+ event_type="SCOPED_SEARCH",
2767
+ original_tokens=est_orig,
2768
+ optimized_tokens=res_tokens,
2769
+ details={"query_count": len(safe_queries), "mode": "batch_search"},
2770
+ )
2771
+ return {"content": [{"type": "text", "text": summary_md}]}
2343
2772
  except Exception as e:
2344
2773
  return _fallback_error("batch_search", f"failed to execute batch search: {e}")
2345
2774
 
@@ -2409,24 +2838,31 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
2409
2838
  clean_text = strip_ansi(text)
2410
2839
  hash8, marker = stash_block(clean_text, source=f"mcp:{tool_name}")
2411
2840
  lines = clean_text.splitlines()
2412
- head = lines[:20]
2413
- tail = lines[-15:]
2414
- omitted = len(lines) - (len(head) + len(tail))
2415
- folded_msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2416
- tail_str = "\n".join(tail)
2417
2841
  footer = f"\n{marker}"
2842
+ footer_bytes = len(footer.encode("utf-8"))
2843
+ if len(lines) > 35:
2844
+ head = lines[:20]
2845
+ tail = lines[-15:]
2846
+ omitted = len(lines) - (len(head) + len(tail))
2847
+ folded_msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2848
+ tail_str = "\n".join(tail)
2849
+ budget = max_bytes - len(folded_msg.encode("utf-8")) - footer_bytes - len(tail_str.encode("utf-8")) - 50
2850
+ head_str = ""
2851
+ for line in head:
2852
+ if len((head_str + line + "\n").encode("utf-8")) <= budget:
2853
+ head_str += line + "\n"
2854
+ else:
2855
+ break
2856
+ folded_text = f"{head_str.rstrip()}{folded_msg}{tail_str}{footer}"
2857
+ else:
2858
+ msg_mid = f"\n... [{len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2859
+ avail = max(120, max_bytes - len(msg_mid.encode("utf-8")) - footer_bytes - 50)
2860
+ head_b = raw_bytes[: avail // 2].decode("utf-8", errors="ignore")
2861
+ tail_b = raw_bytes[-(avail - avail // 2):].decode("utf-8", errors="ignore")
2862
+ folded_text = f"{head_b.rstrip()}{msg_mid}{tail_b.lstrip()}{footer}"
2418
2863
 
2419
- budget = max_bytes - len(folded_msg.encode("utf-8")) - len(footer.encode("utf-8")) - len(tail_str.encode("utf-8")) - 50
2420
- head_str = ""
2421
- for line in head:
2422
- if len((head_str + line + "\n").encode("utf-8")) <= budget:
2423
- head_str += line + "\n"
2424
- else:
2425
- break
2426
-
2427
- folded_text = f"{head_str.rstrip()}{folded_msg}{tail_str}{footer}"
2428
2864
  if len(folded_text.encode("utf-8")) > max_bytes:
2429
- allowed_head = max_bytes - len(footer.encode("utf-8")) - 100
2865
+ allowed_head = max(80, max_bytes - footer_bytes - 60)
2430
2866
  folded_text = clean_text.encode("utf-8")[:allowed_head].decode("utf-8", errors="ignore") + f"\n... [folded]\n{footer}"
2431
2867
 
2432
2868
  new_block = dict(block)
@@ -2550,17 +2986,20 @@ def run_mcp_server():
2550
2986
  }
2551
2987
  elif method == "tools/list":
2552
2988
  _TOOLS_LISTED = True
2553
- response["result"] = {"tools": TOOLS}
2989
+ profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
2990
+ response["result"] = {"tools": FULL_TOOLS if profile == "full" else TOOLS}
2991
+ elif method == "ping":
2992
+ response["result"] = {}
2554
2993
  elif method == "tools/call":
2555
2994
  tool_name = str(params.get("name") or "")
2556
2995
  raw_tool_args = params.get("arguments")
2557
- tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
2558
- if not tool_args and raw_tool_args:
2559
- # Self-healing: hosts on small/local models intermittently send
2560
- # arguments as a malformed JSON string — repair before failing.
2561
- from src.json_repair import parse_tool_arguments
2562
- tool_args = parse_tool_arguments(raw_tool_args) or {}
2563
2996
  try:
2997
+ tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
2998
+ if not tool_args and raw_tool_args:
2999
+ # Self-healing: hosts on small/local models intermittently send
3000
+ # arguments as a malformed JSON string — repair before failing.
3001
+ from src.json_repair import parse_tool_arguments
3002
+ tool_args = parse_tool_arguments(raw_tool_args) or {}
2564
3003
  raw_res = _execute_with_timeout(tool_name, tool_args)
2565
3004
  redacted = _redact_result_secrets(raw_res)
2566
3005
  response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
@@ -2578,7 +3017,7 @@ def run_mcp_server():
2578
3017
  response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
2579
3018
 
2580
3019
  try:
2581
- sys.stdout.write(json.dumps(response) + "\n")
3020
+ sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
2582
3021
  sys.stdout.flush()
2583
3022
  except Exception:
2584
3023
  break