tokensafe 2.4.2 → 2.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/src/mcp_server.py CHANGED
@@ -36,35 +36,57 @@ from src.agent_firewall import AgentFirewall
36
36
  from src.diff_slicer import DiffSlicer
37
37
  from src.guard import TokenSafeGuard
38
38
  from src.scoped_search import ScopedSearch
39
+ from src.license_manager import LicenseManager
39
40
 
40
41
  SERVER_INFO = {
41
42
  "name": "tokensafe-mcp",
42
- "version": "2.4.2"
43
+ "version": "2.5.0"
43
44
  }
44
45
 
45
46
  # MCP client attribution: the initialize handshake carries clientInfo, which
46
47
  # lets every session-scoped metric name the REAL agent instead of a shared
47
48
  # anonymous bucket (see METRICS.md by_agent).
48
49
  _MCP_CLIENT_NAME = ""
50
+ _TOOLS_LISTED = False
51
+ _EPOCH_GEN = 0
52
+ _IN_PROCESS_DELIVERED = {}
53
+ _KNOWN_POINTER_CLIENTS = (
54
+ "antigravity", "claude", "cursor", "windsurf", "cline", "roo",
55
+ "codex", "zcode", "copilot", "gemini", "zed", "vscode",
56
+ )
57
+
49
58
 
50
59
  def _set_mcp_client(name: str):
51
60
  global _MCP_CLIENT_NAME
52
61
  clean = re.sub(r"[^a-z0-9_-]", "", str(name or "").lower())[:30]
53
62
  _MCP_CLIENT_NAME = clean
54
63
 
64
+
55
65
  def _mcp_session_id() -> str:
56
66
  return f"mcp:{_MCP_CLIENT_NAME}" if _MCP_CLIENT_NAME else "mcp_session"
57
67
 
68
+
69
+ def _client_supports_pointers() -> bool:
70
+ """Out-of-the-box capability detection (zero env vars): returns True once the
71
+ MCP client has fetched tools/list (seeing force_full) or identified as an
72
+ interactive AI coding host."""
73
+ if _TOOLS_LISTED:
74
+ return True
75
+ return bool(_MCP_CLIENT_NAME and any(k in _MCP_CLIENT_NAME for k in _KNOWN_POINTER_CLIENTS))
76
+
77
+
58
78
  TOOLS = [
59
79
  {
60
80
  "name": "smart_read_file",
61
- "description": "Reads a code file using AST skeletonization and predictive dependency prefetching to save up to 90% context tokens.",
81
+ "description": "Reads a code file using AST skeletonization and graph-guided slicing to save 90-99% context tokens.",
62
82
  "inputSchema": {
63
83
  "type": "object",
64
84
  "properties": {
65
85
  "path": {"type": "string", "description": "Absolute path to the code file"},
66
86
  "symbol": {"type": "string", "description": "Optional: targeted function or class name for graph-guided skeletonization"},
67
- "include_deps": {"type": "boolean", "description": "Optional: whether to include 1-hop dependencies in full (default: true). Set false for single-symbol surgical isolation."},
87
+ "include_deps": {"type": "boolean", "description": "Optional: whether to include 1-hop dependencies (default: true). Set false for 0-hop surgical isolation."},
88
+ "dep_mode": {"type": "string", "enum": ["signature", "full"], "description": "Optional: how 1-hop dependencies are returned when include_deps is true. 'signature' (default, -95%+ tokens) returns compact 1-line signatures; 'full' inlines full dependency bodies."},
89
+ "force_full": {"type": "boolean", "description": "Optional: bypass session pointer deduplication and return the full skeleton directly (use only if your context was compacted or you are a fresh subagent lacking earlier reads)."},
68
90
  "start_line": {"type": "integer", "description": "Optional: starting line number"},
69
91
  "end_line": {"type": "integer", "description": "Optional: ending line number"}
70
92
  },
@@ -426,7 +448,19 @@ def _get_safe_tracker():
426
448
  return _NoOpTracker()
427
449
 
428
450
 
429
- def _team_skeleton_lookup(path: str, symbol: str) -> Optional[str]:
451
+ def _team_cache_key(path: str, symbol: str, dep_mode: str = "signature") -> str:
452
+ """Builds a portable, content-hash-validated key shared across machines."""
453
+ abs_path = os.path.abspath(path)
454
+ repo_root = GraphEngine.find_project_root(abs_path)
455
+ try:
456
+ rel_path = os.path.relpath(abs_path, repo_root).replace("\\", "/")
457
+ except ValueError:
458
+ rel_path = os.path.basename(abs_path)
459
+ content_hash = AgentFirewall._file_content_hash(abs_path)[:16]
460
+ return f"{rel_path}::{symbol or ''}::{dep_mode}::{content_hash}"
461
+
462
+
463
+ def _team_skeleton_lookup(path: str, symbol: str, dep_mode: str = "signature") -> Optional[str]:
430
464
  """Team cache pre-warm lookup: returns a teammate's cached skeleton or None.
431
465
 
432
466
  Never blocks the caller for more than ~250ms: the network fetch runs in a
@@ -435,11 +469,12 @@ def _team_skeleton_lookup(path: str, symbol: str) -> Optional[str]:
435
469
  is_team, _ = TeamCache._is_team_tier()
436
470
  if not is_team:
437
471
  return None
472
+ cache_key = _team_cache_key(path, symbol, dep_mode=dep_mode)
438
473
  box: dict = {}
439
474
 
440
475
  def _fetch():
441
476
  try:
442
- box["value"] = TeamCache.get("SKELETON", f"{path}::{symbol or ''}")
477
+ box["value"] = TeamCache.get("SKELETON", cache_key)
443
478
  except Exception:
444
479
  pass
445
480
 
@@ -451,49 +486,88 @@ def _team_skeleton_lookup(path: str, symbol: str) -> Optional[str]:
451
486
  return None
452
487
 
453
488
 
454
- def _team_skeleton_prewarm(path: str, symbol: str, skeleton_text: str, tokens_saved: int):
489
+ def _team_skeleton_prewarm(
490
+ path: str,
491
+ symbol: str,
492
+ skeleton_text: str,
493
+ tokens_saved: int,
494
+ dep_mode: str = "signature",
495
+ ):
455
496
  """Publishes a freshly built skeleton to the team cache (async, team tier only).
456
497
 
457
498
  Teammate B's later smart_read_file on the same symbol hits the cache instead
458
499
  of re-reading and re-skeletonizing the file."""
459
500
  try:
460
- TeamCache.put("SKELETON", f"{path}::{symbol or ''}", skeleton_text, tokens_saved=tokens_saved)
501
+ cache_key = _team_cache_key(path, symbol, dep_mode=dep_mode)
502
+ TeamCache.put("SKELETON", cache_key, skeleton_text, tokens_saved=tokens_saved)
461
503
  except Exception:
462
504
  pass
463
505
 
464
506
 
507
+ def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
508
+ inc_deps = bool(args.get("include_deps", True))
509
+ if not inc_deps:
510
+ return False, "none"
511
+ raw_mode = str(args.get("dep_mode") or "").strip().lower()
512
+ if raw_mode in ("signature", "full"):
513
+ return True, raw_mode
514
+ return True, "signature"
515
+
516
+
465
517
  def handle_tool_call(name: str, args: dict) -> dict:
466
518
  if args is None or not isinstance(args, dict):
467
519
  args = {}
468
520
  try:
469
521
  result = _dispatch_tool_call(name, args)
470
- # Populate the Subagent Firewall dedup cache with what we actually returned,
471
- # so repeated reads of the same file within a session can be served from cache.
472
522
  if name == "smart_read_file" and isinstance(result, dict) and not result.get("isError"):
473
523
  content_parts = result.get("content") or []
474
524
  text_out = "".join(p.get("text", "") for p in content_parts if isinstance(p, dict))
475
- if text_out:
476
- try:
477
- AgentFirewall.record_cache(
478
- session_id=_mcp_session_id(),
479
- file_path=args.get("path", ""),
480
- content=text_out,
481
- symbol=(args.get("symbol") or "").strip(),
482
- tracker=_get_safe_tracker()
483
- )
484
- except Exception:
485
- pass
525
+ path = args.get("path", "")
526
+ symbol = (args.get("symbol") or "").strip()
527
+ _, eff_dep_mode = _resolve_dep_mode(args)
528
+ cache_sym = f"{symbol}@{eff_dep_mode}" if (symbol and eff_dep_mode != "signature") else symbol
529
+ if text_out and path:
530
+ abs_path = os.path.abspath(path)
531
+ cur_hash = AgentFirewall._file_content_hash(abs_path)
532
+ if cur_hash and args.get("start_line") is None and args.get("end_line") is None:
533
+ _IN_PROCESS_DELIVERED[(abs_path, symbol, eff_dep_mode)] = (cur_hash, _EPOCH_GEN)
534
+ # Never overwrite cached skeleton with a firewall header or pointer hit
535
+ if not text_out.startswith("// [TokenSafe Subagent Firewall:"):
536
+ try:
537
+ AgentFirewall.record_cache(
538
+ session_id=_mcp_session_id(),
539
+ file_path=path,
540
+ content=text_out,
541
+ symbol=cache_sym,
542
+ tracker=_get_safe_tracker()
543
+ )
544
+ except Exception:
545
+ pass
486
546
  return result
487
547
  except Exception as e:
488
548
  return _fallback_error(name, f"{type(e).__name__}: {str(e)}")
489
549
 
490
550
 
551
+ def _quota_banner_if_due(quota: dict, tracker, session_id: str) -> str:
552
+ """Emits a concise Community 500k quota CTA on turn #1 of exceedance and every 5 turns."""
553
+ if not quota.get("is_quota_exceeded"):
554
+ return ""
555
+ if LicenseManager.should_emit_quota_banner(tracker, session_id=session_id, every_n_turns=5):
556
+ return f"// {quota.get('warning', '')}\n"
557
+ return ""
558
+
559
+
491
560
  def _dispatch_tool_call(name: str, args: dict) -> dict:
561
+ global _EPOCH_GEN
492
562
  tracker = _get_safe_tracker()
563
+ quota = LicenseManager.check_quota(tracker)
564
+ is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
493
565
 
494
566
  if name == "smart_read_file":
495
567
  path = args.get("path", "")
496
568
  symbol = args.get("symbol", "")
569
+ inc_deps, eff_dep_mode = _resolve_dep_mode(args)
570
+ force_full = bool(args.get("force_full", False))
497
571
  start_line = args.get("start_line")
498
572
  end_line = args.get("end_line")
499
573
  # Clamp explicit line ranges to sane bounds so bad indices can never produce
@@ -514,18 +588,52 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
514
588
  except OSError as e:
515
589
  return _fallback_error("smart_read_file", f"cannot stat path: {e}")
516
590
 
517
- # Check Subagent Firewall dedup cache
518
- is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(_mcp_session_id(), path, symbol=symbol or "", tracker=tracker)
519
- if is_hit and cached_text:
520
- return {"content": [{"type": "text", "text": cached_text}]}
591
+ # Community 500k quota reached: soft-degrade to bounded raw read (disable Graph/AST/Pointer/Team Cache)
592
+ if is_quota_exceeded:
593
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
594
+ lines = f.readlines()
595
+ if start_line is not None and end_line is not None:
596
+ e_line = min(end_line, len(lines))
597
+ if start_line > e_line:
598
+ return _fallback_error("smart_read_file", f"start_line {start_line} is beyond end of file ({len(lines)} lines)")
599
+ raw_chunk = "".join(lines[start_line - 1 : e_line])
600
+ else:
601
+ cap = min(250, len(lines))
602
+ raw_chunk = "".join(lines[:cap])
603
+ if len(lines) > cap:
604
+ raw_chunk += f"\n// [TokenSafe Community 500k limit reached: showing raw lines 1-{cap} of {len(lines)}. AST/graph slicing & pointer dedup are paused.]\n"
605
+ banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
606
+ return {"content": [{"type": "text", "text": banner + raw_chunk}]}
521
607
 
522
- # Check loop detector
523
- is_loop, repeats, msg = LoopDetector.check_loop(_mcp_session_id(), "smart_read_file", args)
524
- if is_loop:
525
- return {"isError": True, "content": [{"type": "text", "text": f"⚠️ {msg}"}]}
608
+ abs_path = os.path.abspath(path)
609
+ sym_clean = (symbol or "").strip()
610
+ cache_sym = f"{sym_clean}@{eff_dep_mode}" if (sym_clean and eff_dep_mode != "signature") else sym_clean
611
+
612
+ if start_line is None and end_line is None:
613
+ cur_hash = AgentFirewall._file_content_hash(abs_path)
614
+ delivered = _IN_PROCESS_DELIVERED.get((abs_path, sym_clean, eff_dep_mode))
615
+ already_here = bool(delivered and cur_hash and delivered == (cur_hash, _EPOCH_GEN))
616
+ allow_pointer = (not force_full) and _client_supports_pointers() and already_here
617
+ is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
618
+ _mcp_session_id(),
619
+ path,
620
+ symbol=cache_sym,
621
+ tracker=tracker,
622
+ allow_pointer=allow_pointer,
623
+ )
624
+ if is_hit and cached_text:
625
+ return {"content": [{"type": "text", "text": cached_text}]}
626
+
627
+ # Check loop detector (skip when force_full explicitly recovers from a pointer)
628
+ if not force_full:
629
+ is_loop, repeats, msg = LoopDetector.check_loop(_mcp_session_id(), "smart_read_file", args)
630
+ if is_loop:
631
+ return {"isError": True, "content": [{"type": "text", "text": f"⚠️ {msg}"}]}
526
632
 
527
- # Check prefetcher
528
- prefetch_block, saved_dep = DependencyPrefetcher.prefetch_for_file(path)
633
+ # Only inline extra DependencyPrefetcher stubs when full deps or whole-file mode requested
634
+ prefetch_block = ""
635
+ if not sym_clean or eff_dep_mode == "full":
636
+ prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
529
637
 
530
638
  # Check targeted symbol or skeleton
531
639
  if start_line is not None and end_line is not None:
@@ -539,7 +647,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
539
647
 
540
648
  if symbol:
541
649
  # Team pre-warm hit: a teammate already skeletonized this symbol
542
- team_skel = _team_skeleton_lookup(path, symbol)
650
+ team_skel = _team_skeleton_lookup(path, symbol, dep_mode=eff_dep_mode)
543
651
  if team_skel:
544
652
  with open(path, "r", encoding="utf-8", errors="replace") as f:
545
653
  raw_code = f.read()
@@ -550,15 +658,20 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
550
658
  event_type="TEAM_CACHE_HIT",
551
659
  original_tokens=orig_t,
552
660
  optimized_tokens=skel_t,
553
- details={"file": os.path.basename(path), "symbol": symbol, "source": "team_cache"}
661
+ details={"file": os.path.basename(path), "symbol": symbol, "dep_mode": eff_dep_mode, "source": "team_cache"}
554
662
  )
555
663
  header = f"// [TokenSafe Team-Cached Skeleton for '{symbol}' | shared by a teammate]\n"
556
664
  return {"content": [{"type": "text", "text": (prefetch_block or "") + header + team_skel}]}
557
665
 
558
666
  try:
559
667
  graph, rel_path = GraphEngine.for_file(path)
560
- inc_deps = bool(args.get("include_deps", True))
561
- graph_skel = graph.graph_guided_skeletonize(path, target_symbol=symbol, include_deps=inc_deps)
668
+ graph_skel = graph.graph_guided_skeletonize(
669
+ path,
670
+ target_symbol=symbol,
671
+ include_deps=inc_deps,
672
+ dep_mode=eff_dep_mode,
673
+ collapse_imports=(eff_dep_mode != "full"),
674
+ )
562
675
  if graph_skel:
563
676
  with open(path, "r", encoding="utf-8", errors="replace") as f:
564
677
  raw_code = f.read()
@@ -570,11 +683,22 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
570
683
  event_type="GRAPH_SKELETON",
571
684
  original_tokens=orig_t,
572
685
  optimized_tokens=skel_t,
573
- details={"file": os.path.basename(path), "symbol": symbol, "saved_tokens": saved, "include_deps": inc_deps}
686
+ details={
687
+ "file": os.path.basename(path),
688
+ "symbol": symbol,
689
+ "saved_tokens": saved,
690
+ "include_deps": inc_deps,
691
+ "dep_mode": eff_dep_mode,
692
+ }
574
693
  )
575
- dep_label = "Full body + 1-hop dependencies" if inc_deps else "Surgical single-symbol isolation"
694
+ if not inc_deps:
695
+ dep_label = "Surgical single-symbol isolation"
696
+ elif eff_dep_mode == "full":
697
+ dep_label = "Full body + 1-hop dependencies"
698
+ else:
699
+ dep_label = "Full body + 1-hop signature deps"
576
700
  header = f"// [TokenSafe Graph-Guided Skeleton for '{symbol}' | {dep_label}]\n"
577
- _team_skeleton_prewarm(path, symbol, graph_skel, saved)
701
+ _team_skeleton_prewarm(path, symbol, graph_skel, saved, dep_mode=eff_dep_mode)
578
702
  return {"content": [{"type": "text", "text": (prefetch_block or "") + header + graph_skel}]}
579
703
  except Exception:
580
704
  pass
@@ -603,6 +727,17 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
603
727
 
604
728
  elif name == "compress_prompt":
605
729
  prompt = args.get("prompt", "")
730
+ if is_quota_exceeded:
731
+ emit_warn = LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
732
+ payload = {
733
+ "original_text": prompt,
734
+ "compact_text": prompt,
735
+ "saved_tokens": 0,
736
+ "tier": "QUOTA_EXCEEDED",
737
+ "quota_exceeded": True,
738
+ "warning": quota.get("warning") if emit_warn else "Community 500k monthly limit reached; prompt compaction paused.",
739
+ }
740
+ return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
606
741
  res = PromptCompactor.compact(prompt, enable_deepseek=True)
607
742
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
608
743
 
@@ -630,12 +765,22 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
630
765
  invocation_num = 3
631
766
  if not transcript_path or not os.path.exists(transcript_path):
632
767
  return {"isError": True, "content": [{"type": "text", "text": f"Transcript not found: {transcript_path}"}]}
768
+ if is_quota_exceeded:
769
+ LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
770
+ return {"content": [{"type": "text", "text": json.dumps({
771
+ "compactable": False,
772
+ "quota_exceeded": True,
773
+ "monthly_saved": quota.get("monthly_saved"),
774
+ "monthly_limit": quota.get("monthly_limit"),
775
+ "reason": quota.get("warning"),
776
+ }, indent=2, ensure_ascii=False)}]}
633
777
  ledger, orig_t, folded_t, stats = HistoryCompactor.fold_transcript(transcript_path, invocation_num)
634
778
  if not ledger:
635
779
  return {"content": [{"type": "text", "text": json.dumps({
636
780
  "compactable": False,
637
781
  "reason": "Transcript too short to fold (needs >= 4 steps and >= 1000 history tokens)"
638
782
  }, indent=2)}]}
783
+ _EPOCH_GEN += 1
639
784
  saved = max(0, orig_t - folded_t)
640
785
  # Incremental metrics guard (same policy as the PreInvocation hook):
641
786
  # repeated compaction of the SAME transcript must not re-record the
@@ -689,8 +834,21 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
689
834
  }
690
835
  return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
691
836
 
692
- # Step 2: Command sanitization (cwd unlocks the package.json peek for
693
- # opaque yarn/npm test scripts; None keeps the conservative fallback)
837
+ # Step 2: Command sanitization (paused at Community 500k quota while Security Guard stays active)
838
+ if is_quota_exceeded:
839
+ emit_note = LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
840
+ result = {
841
+ "original_command": cmd,
842
+ "sanitized_command": cmd,
843
+ "blocked": False,
844
+ "tokens_saved": 0,
845
+ "quota_exceeded": True,
846
+ "reason": quota.get("warning") if emit_note else "Community 500k monthly limit reached; command output compression paused (Security Guard active).",
847
+ }
848
+ if guard_res.warning_only:
849
+ result["warning"] = guard_res.reason
850
+ return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
851
+
694
852
  new_cmd, saved, reason = CommandSanitizer.sanitize(cmd, cwd=args.get("cwd") or None)
695
853
  result = {
696
854
  "original_command": cmd,
@@ -825,6 +983,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
825
983
 
826
984
  elif name == "slice_diff":
827
985
  raw_diff = args.get("diff", "")
986
+ if is_quota_exceeded:
987
+ banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
988
+ return {"content": [{"type": "text", "text": banner + raw_diff}]}
828
989
  max_ctx = int(args.get("max_context", 2))
829
990
  sliced, orig_t, opt_t = DiffSlicer.slice_diff(raw_diff, max_context_lines=max_ctx)
830
991
  saved = max(0, orig_t - opt_t)
@@ -849,6 +1010,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
849
1010
  "isError": True,
850
1011
  "content": [{"type": "text", "text": err or "Error: Invalid project_path."}]
851
1012
  }
1013
+ if is_quota_exceeded:
1014
+ LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
1015
+ return {"content": [{"type": "text", "text": json.dumps({
1016
+ "quota_exceeded": True,
1017
+ "monthly_saved": quota.get("monthly_saved"),
1018
+ "monthly_limit": quota.get("monthly_limit"),
1019
+ "fallback": "Use free list_dir / scoped_search or activate a Solo/Team license: tokensafe activate <key>",
1020
+ "warning": quota.get("warning"),
1021
+ }, indent=2, ensure_ascii=False)}]}
852
1022
  graph = GraphEngine.get_instance(target_abs)
853
1023
  god_nodes = graph.get_god_nodes(7)
854
1024
  banner = graph.format_topology_banner()
@@ -879,6 +1049,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
879
1049
  "isError": True,
880
1050
  "content": [{"type": "text", "text": err or "Error: Invalid project_path."}]
881
1051
  }
1052
+ if is_quota_exceeded:
1053
+ LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
1054
+ 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."}]}
882
1055
  graph = GraphEngine.get_instance(target_abs)
883
1056
  surface_md = graph.generate_api_surface()
884
1057
  surface_tokens = count_tokens(surface_md)
@@ -1014,6 +1187,11 @@ def _get_watched_mtimes() -> Tuple[Optional[float], ...]:
1014
1187
 
1015
1188
  def run_mcp_server():
1016
1189
  """Runs stdio JSON-RPC 2.0 loop with per-call timeout, resilient recovery & auto-reload on upgrade."""
1190
+ global _MCP_CLIENT_NAME, _TOOLS_LISTED, _EPOCH_GEN
1191
+ _MCP_CLIENT_NAME = ""
1192
+ _TOOLS_LISTED = False
1193
+ _EPOCH_GEN = 0
1194
+ _IN_PROCESS_DELIVERED.clear()
1017
1195
  initial_mtimes = _get_watched_mtimes()
1018
1196
  auto_reload = os.environ.get("TOKENSAFE_MCP_AUTORELOAD", "1").strip().lower() not in ("0", "false", "no")
1019
1197
 
@@ -1060,6 +1238,7 @@ def run_mcp_server():
1060
1238
  "serverInfo": SERVER_INFO
1061
1239
  }
1062
1240
  elif method == "tools/list":
1241
+ _TOOLS_LISTED = True
1063
1242
  response["result"] = {"tools": TOOLS}
1064
1243
  elif method == "tools/call":
1065
1244
  tool_name = params.get("name", "")
package/src/metrics.py CHANGED
@@ -36,6 +36,8 @@ ESTIMATED_EVENT_TYPES = frozenset({
36
36
  "ROLLUP_LIFETIME",
37
37
  "COMMAND_FILTER",
38
38
  "LOOP_GUARD",
39
+ "SCOPED_SEARCH",
40
+ "DIR_LIST",
39
41
  "GUARD_SECRET",
40
42
  "GUARD_DESTRUCTIVE",
41
43
  "GUARD_TLS_VERIFY_BYPASS",
@@ -174,10 +176,9 @@ class MetricsTracker:
174
176
  "UPDATE events SET measurement = 'estimated' "
175
177
  "WHERE measurement = 'measured' AND event_type IN "
176
178
  "('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME', "
177
- "'COMMAND_FILTER', 'LOOP_GUARD', 'GUARD_SECRET', "
178
- "'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
179
- "'GUARD_JUNK_READ', 'GUARD_INFINITE', "
180
- "'GUARD_RAW_CODE_SEARCH');"
179
+ "'COMMAND_FILTER', 'LOOP_GUARD', 'SCOPED_SEARCH', 'DIR_LIST', "
180
+ "'GUARD_SECRET', 'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
181
+ "'GUARD_JUNK_READ', 'GUARD_INFINITE', 'GUARD_RAW_CODE_SEARCH');"
181
182
  )
182
183
  cursor.execute("""
183
184
  CREATE TABLE IF NOT EXISTS lifetime_aggregates (
@@ -198,8 +199,99 @@ class MetricsTracker:
198
199
  """)
199
200
  cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp)")
200
201
  cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_session_id ON events(session_id)")
202
+ cursor.execute("""
203
+ CREATE TABLE IF NOT EXISTS quota_daily (
204
+ day_key TEXT PRIMARY KEY,
205
+ measured_saved INTEGER NOT NULL DEFAULT 0,
206
+ updated_at TEXT NOT NULL
207
+ )
208
+ """)
209
+ # One-time backfill for existing DBs so pre-upgrade 30d measured usage is captured
210
+ row_qd = cursor.execute("SELECT COUNT(*) FROM quota_daily").fetchone()
211
+ if row_qd and int(row_qd[0]) == 0:
212
+ cutoff_30 = (datetime.now() - timedelta(days=30)).isoformat()
213
+ cursor.execute("""
214
+ INSERT OR IGNORE INTO quota_daily (day_key, measured_saved, updated_at)
215
+ SELECT substr(timestamp, 1, 10), COALESCE(SUM(saved_tokens), 0), MAX(timestamp)
216
+ FROM events
217
+ WHERE timestamp >= ? AND measurement = 'measured' AND saved_tokens > 0
218
+ GROUP BY substr(timestamp, 1, 10)
219
+ """, (cutoff_30,))
201
220
  _INITIALIZED_METRICS_DBS.add(self.db_path)
202
221
 
222
+ def _quota_mirror_path(self) -> str:
223
+ """Returns persistent sidecar ledger path (kept outside data/metrics.db for default installs)."""
224
+ if os.environ.get("TOKENSAFE_DB_PATH") or os.environ.get("TOKENSAFE_DATA_DIR"):
225
+ return os.path.join(os.path.dirname(self.db_path), ".qledger.json")
226
+ default_data = os.path.abspath(resolve_data_dir())
227
+ if os.path.abspath(os.path.dirname(self.db_path)) == default_data:
228
+ return os.path.join(os.path.dirname(default_data), ".qledger.json")
229
+ return os.path.join(os.path.dirname(self.db_path), ".qledger.json")
230
+
231
+ def _sync_quota_mirror(self, day_key: str, delta_measured: int = 0) -> int:
232
+ """Merges quota_daily with a sidecar ledger so deleting metrics.db or pruning >5k rows cannot reset quota."""
233
+ mirror_path = self._quota_mirror_path()
234
+ cutoff_day = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")
235
+ data: Dict[str, Any] = {"days": {}, "server_floor": 0, "server_floor_ts": 0}
236
+ try:
237
+ if os.path.exists(mirror_path):
238
+ with open(mirror_path, "r", encoding="utf-8") as f:
239
+ loaded = json.load(f)
240
+ if isinstance(loaded, dict):
241
+ data.update(loaded)
242
+ except Exception:
243
+ pass
244
+ days = {
245
+ str(k): int(v)
246
+ for k, v in (data.get("days") or {}).items()
247
+ if str(k) >= cutoff_day and int(v or 0) > 0
248
+ }
249
+ if delta_measured > 0 and day_key >= cutoff_day:
250
+ days[day_key] = days.get(day_key, 0) + int(delta_measured)
251
+ data["days"] = days
252
+ if delta_measured > 0:
253
+ try:
254
+ os.makedirs(os.path.dirname(mirror_path), exist_ok=True)
255
+ tmp_p = mirror_path + ".tmp"
256
+ with open(tmp_p, "w", encoding="utf-8") as f:
257
+ json.dump(data, f)
258
+ os.replace(tmp_p, mirror_path)
259
+ except Exception:
260
+ pass
261
+ local_sum = sum(days.values())
262
+ srv_floor = 0
263
+ try:
264
+ if time.time() - float(data.get("server_floor_ts", 0)) <= 30 * 86400:
265
+ srv_floor = int(data.get("server_floor", 0) or 0)
266
+ except Exception:
267
+ srv_floor = 0
268
+ return max(local_sum, srv_floor)
269
+
270
+ def record_server_quota_floor(self, server_monthly_measured: int) -> None:
271
+ """Persists a server-verified 30-day measured quota floor so client resets cannot roll back usage."""
272
+ if int(server_monthly_measured or 0) <= 0:
273
+ return
274
+ mirror_path = self._quota_mirror_path()
275
+ data: Dict[str, Any] = {"days": {}, "server_floor": 0, "server_floor_ts": 0}
276
+ try:
277
+ if os.path.exists(mirror_path):
278
+ with open(mirror_path, "r", encoding="utf-8") as f:
279
+ loaded = json.load(f)
280
+ if isinstance(loaded, dict):
281
+ data.update(loaded)
282
+ except Exception:
283
+ pass
284
+ data["server_floor"] = max(int(data.get("server_floor", 0) or 0), int(server_monthly_measured))
285
+ data["server_floor_ts"] = int(time.time())
286
+ try:
287
+ os.makedirs(os.path.dirname(mirror_path), exist_ok=True)
288
+ tmp_p = mirror_path + ".tmp"
289
+ with open(tmp_p, "w", encoding="utf-8") as f:
290
+ json.dump(data, f)
291
+ os.replace(tmp_p, mirror_path)
292
+ except Exception:
293
+ pass
294
+
203
295
  def record_event(
204
296
  self,
205
297
  session_id: str,
@@ -251,6 +343,20 @@ class MetricsTracker:
251
343
  """, (session_id, now_iso, now_iso, original_tokens,
252
344
  optimized_tokens, saved_tokens, est_usd))
253
345
 
346
+ # 3. Monotonic 30-day measured quota ledger (never eroded by >5k event pruning)
347
+ if measurement_label == "measured" and saved_tokens > 0:
348
+ day_key = now_iso[:10]
349
+ cursor.execute("""
350
+ INSERT INTO quota_daily (day_key, measured_saved, updated_at)
351
+ VALUES (?, ?, ?)
352
+ ON CONFLICT(day_key) DO UPDATE SET
353
+ measured_saved = quota_daily.measured_saved + excluded.measured_saved,
354
+ updated_at = excluded.updated_at
355
+ """, (day_key, saved_tokens, now_iso))
356
+
357
+ if measurement_label == "measured" and saved_tokens > 0:
358
+ self._sync_quota_mirror(now_iso[:10], saved_tokens)
359
+
254
360
  # Wall-clock auto-retention (marker-file gated, cross-process safe)
255
361
  self._maybe_autoprune(self.db_path)
256
362
 
@@ -398,20 +504,40 @@ class MetricsTracker:
398
504
  "breakdown": combined_breakdown
399
505
  }
400
506
 
401
- def get_monthly_saved_tokens(self) -> int:
402
- """Returns total tokens saved in the trailing 30 days for quota calculations."""
403
- # Events are written with local-time now(); compute the cutoff the same way
404
- # (previously utcnow vs now mixed naive clocks and skewed the quota window).
507
+ def get_monthly_saved_tokens(self, measured_only: bool = True) -> int:
508
+ """Returns trailing 30-day tokens saved for quota calculations (measured-only by default).
509
+
510
+ Reconciles live `events`, the un-prunable `quota_daily` table, and the
511
+ persistent sidecar ledger so neither >5,000-row auto-pruning nor deleting
512
+ `metrics.db` drops counted Community usage.
513
+ """
405
514
  thirty_days_ago = (datetime.now() - timedelta(days=30)).isoformat()
515
+ thirty_days_day = thirty_days_ago[:10]
406
516
  with self._get_connection() as conn:
407
517
  cursor = conn.cursor()
408
- cursor.execute("""
409
- SELECT COALESCE(SUM(saved_tokens), 0) as monthly_saved
410
- FROM events
411
- WHERE timestamp >= ?
412
- """, (thirty_days_ago,))
413
- row = cursor.fetchone()
414
- return int(row["monthly_saved"]) if row else 0
518
+ if measured_only:
519
+ cursor.execute("""
520
+ SELECT COALESCE(SUM(saved_tokens), 0) as monthly_saved
521
+ FROM events
522
+ WHERE timestamp >= ? AND measurement = 'measured'
523
+ """, (thirty_days_ago,))
524
+ ev_sum = int(cursor.fetchone()["monthly_saved"])
525
+ cursor.execute("""
526
+ SELECT COALESCE(SUM(measured_saved), 0) as daily_saved
527
+ FROM quota_daily
528
+ WHERE day_key >= ?
529
+ """, (thirty_days_day,))
530
+ daily_sum = int(cursor.fetchone()["daily_saved"])
531
+ mirror_sum = self._sync_quota_mirror(thirty_days_day, 0)
532
+ return max(ev_sum, daily_sum, mirror_sum)
533
+ else:
534
+ cursor.execute("""
535
+ SELECT COALESCE(SUM(saved_tokens), 0) as monthly_saved
536
+ FROM events
537
+ WHERE timestamp >= ?
538
+ """, (thirty_days_ago,))
539
+ row = cursor.fetchone()
540
+ return int(row["monthly_saved"]) if row else 0
415
541
 
416
542
  def get_recent_events(self, limit: int = 10) -> List[Dict[str, Any]]:
417
543
  """Returns the most recent optimization events."""
@@ -589,6 +715,10 @@ class MetricsTracker:
589
715
  # 5. Delete pruned events
590
716
  cursor.execute(f"DELETE FROM events WHERE {combined_where}", params)
591
717
 
718
+ cutoff_qd = (datetime.now() - timedelta(days=45)).strftime("%Y-%m-%d")
719
+ with self._get_connection() as conn:
720
+ conn.execute("DELETE FROM quota_daily WHERE day_key < ?", (cutoff_qd,))
721
+
592
722
  if vacuum and prune_count > 0:
593
723
  self.vacuum()
594
724