tokensafe 2.7.0 → 2.7.2

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 (44) hide show
  1. package/bin/tokensafe +1 -1
  2. package/extensions/cursor-tokensafe/extension.js +21 -8
  3. package/hooks/claude_code_hook.py +13 -5
  4. package/hooks/cursor_hook.py +7 -4
  5. package/hooks/post_tool_use.py +24 -6
  6. package/hooks/pre_invocation.py +40 -27
  7. package/hooks/pre_tool_use.py +85 -83
  8. package/hooks/session_start.py +8 -4
  9. package/hooks/stop_hook.py +7 -4
  10. package/package.json +1 -1
  11. package/plugin.json +1 -1
  12. package/server.json +3 -3
  13. package/src/agent_firewall.py +38 -21
  14. package/src/cache_normalizer.py +39 -10
  15. package/src/cli.py +139 -83
  16. package/src/command_sanitizer.py +248 -136
  17. package/src/compactor.py +55 -25
  18. package/src/dashboard.py +17 -10
  19. package/src/deepseek_distiller.py +26 -17
  20. package/src/dependency_prefetcher.py +65 -40
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +80 -48
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +1 -1
  27. package/src/guard.py +316 -132
  28. package/src/history_compactor.py +57 -26
  29. package/src/installer.py +174 -131
  30. package/src/license_manager.py +12 -9
  31. package/src/loop_detector.py +68 -29
  32. package/src/mcp_server.py +206 -65
  33. package/src/metrics.py +141 -54
  34. package/src/paths.py +32 -6
  35. package/src/proxy.py +121 -52
  36. package/src/scoped_search.py +18 -6
  37. package/src/secret_redactor.py +78 -59
  38. package/src/slicer.py +15 -3
  39. package/src/team_cache.py +89 -16
  40. package/src/telemetry_sync.py +110 -39
  41. package/src/tokenizer.py +24 -13
  42. package/src/treesitter_backend.py +1 -0
  43. package/src/version_checker.py +67 -32
  44. package/src/weekly_digest.py +6 -3
package/src/mcp_server.py CHANGED
@@ -40,7 +40,7 @@ from src.license_manager import LicenseManager
40
40
 
41
41
  SERVER_INFO = {
42
42
  "name": "tokensafe-mcp",
43
- "version": "2.7.0"
43
+ "version": "2.7.2"
44
44
  }
45
45
 
46
46
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -284,10 +284,18 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
284
284
  if not os.path.isdir(dir_path):
285
285
  return f"Error: Path is not a directory: {dir_path}"
286
286
 
287
+ dirs_ignore_dots = {
288
+ ".git", ".hg", ".svn", ".venv", ".cache", ".idea", ".vscode",
289
+ ".next", ".turbo", ".pytest_cache", ".mypy_cache", ".DS_Store",
290
+ ".system_generated", ".Trash",
291
+ }
292
+ safe_dot_prefixes = (".env.example", ".env.sample", ".env.template")
293
+
287
294
  base_name = os.path.basename(os.path.abspath(dir_path)) or dir_path
288
295
  lines = [f"📁 **{base_name}/** (max depth: {max_depth})"]
289
296
  entries_count = 0
290
297
  start_time = time.monotonic()
298
+ visited_real_dirs = {os.path.realpath(dir_path)}
291
299
 
292
300
  def _traverse(curr_dir: str, prefix: str, current_depth: int):
293
301
  nonlocal entries_count
@@ -305,14 +313,21 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
305
313
  dirs = []
306
314
  files = []
307
315
  for it in items:
308
- if it.startswith('.') and it not in SECRET_FILES and it != '.gitignore':
309
- continue
310
316
  full_p = os.path.join(curr_dir, it)
311
317
  if os.path.isdir(full_p):
312
- if it in IGNORE_DIRS:
318
+ if it in IGNORE_DIRS or it in dirs_ignore_dots:
319
+ continue
320
+ if it.startswith('.') and it not in (".github", ".gitlab", ".claude", ".gemini", ".agents", ".cursor", ".vscode-test"):
313
321
  continue
314
322
  dirs.append(it)
315
323
  else:
324
+ if it in SECRET_FILES or it.startswith(".env.") and not it.endswith((".example", ".sample", ".template")):
325
+ files.append(it)
326
+ continue
327
+ if any(fnmatch.fnmatch(it, pat) for pat in IGNORE_FILES):
328
+ continue
329
+ if it.startswith('.') and it not in ('.gitignore', '.gitattributes', '.dockerignore', '.editorconfig', '.npmrc', '.nvmrc', '.python-version', '.prettierrc', '.eslintrc', '.eslintrc.json', '.eslintrc.js') and not any(it.startswith(p) for p in safe_dot_prefixes):
330
+ continue
316
331
  files.append(it)
317
332
 
318
333
  all_items = [(d, True) for d in dirs] + [(f, False) for f in files]
@@ -330,15 +345,18 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
330
345
 
331
346
  if is_dir:
332
347
  entries_count += 1
348
+ real_sub = os.path.realpath(item_path)
349
+ if real_sub in visited_real_dirs:
350
+ lines.append(f"{prefix}{pointer}📁 {name}/ [symlink cycle]")
351
+ continue
333
352
  lines.append(f"{prefix}{pointer}📁 {name}/")
353
+ visited_real_dirs.add(real_sub)
334
354
  _traverse(item_path, prefix + extension_prefix, current_depth + 1)
335
355
  else:
336
- if name in SECRET_FILES:
356
+ if name in SECRET_FILES or (name.startswith(".env.") and not name.endswith((".example", ".sample", ".template"))):
337
357
  lines.append(f"{prefix}{pointer}🔒 {name} [PROTECTED SECRET]")
338
358
  entries_count += 1
339
359
  continue
340
- if any(fnmatch.fnmatch(name, pat) for pat in IGNORE_FILES):
341
- continue
342
360
  try:
343
361
  sz = os.path.getsize(item_path)
344
362
  sz_str = format_file_size(sz)
@@ -363,8 +381,11 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
363
381
  target_abs = os.path.abspath(target)
364
382
  if os.path.isfile(target_abs):
365
383
  target_abs = os.path.dirname(target_abs)
366
- if target_abs not in system_roots and os.path.isdir(target_abs):
367
- return target_abs, None
384
+ if target_abs in system_roots:
385
+ return None, f"Error: Refusing to scan system root or home directory '{target}'. Please provide a specific project directory."
386
+ if not os.path.isdir(target_abs):
387
+ return None, f"Error: project_path not found or not a directory: '{target}'."
388
+ return target_abs, None
368
389
 
369
390
  # Check environment variables
370
391
  for env_var in ("AGY_PROJECT_PATH", "WORKSPACE_FOLDER", "PROJECT_DIR", "PWD"):
@@ -437,6 +458,30 @@ class _SafeTrackerProxy:
437
458
  except Exception:
438
459
  return 0
439
460
 
461
+ def get_monthly_saved_tokens(self, *args, **kwargs):
462
+ try:
463
+ return self._inner.get_monthly_saved_tokens(*args, **kwargs)
464
+ except Exception:
465
+ return 0
466
+
467
+ def get_last_event(self, *args, **kwargs):
468
+ try:
469
+ return self._inner.get_last_event(*args, **kwargs)
470
+ except Exception:
471
+ return None
472
+
473
+ def get_summary(self, *args, **kwargs):
474
+ try:
475
+ return self._inner.get_summary(*args, **kwargs)
476
+ except Exception:
477
+ return {}
478
+
479
+ def get_recent_events(self, *args, **kwargs):
480
+ try:
481
+ return self._inner.get_recent_events(*args, **kwargs)
482
+ except Exception:
483
+ return []
484
+
440
485
  def __getattr__(self, name):
441
486
  return getattr(self._inner, name)
442
487
 
@@ -463,10 +508,11 @@ def _team_cache_key(path: str, symbol: str, dep_mode: str = "signature") -> str:
463
508
  def _team_skeleton_lookup(path: str, symbol: str, dep_mode: str = "signature") -> Optional[str]:
464
509
  """Team cache pre-warm lookup: returns a teammate's cached skeleton or None.
465
510
 
466
- Never blocks the caller for more than ~250ms: the network fetch runs in a
467
- daemon thread with a short join. Non-team installs skip the network entirely."""
511
+ Never blocks the caller for more than ~450ms: the HTTP timeout matches
512
+ the thread join so discarded timeouts don't inflate cloud hit_count.
513
+ Non-team installs skip the network entirely."""
468
514
  try:
469
- is_team, _ = TeamCache._is_team_tier()
515
+ is_team, lic_key = TeamCache._is_team_tier()
470
516
  if not is_team:
471
517
  return None
472
518
  cache_key = _team_cache_key(path, symbol, dep_mode=dep_mode)
@@ -474,13 +520,13 @@ def _team_skeleton_lookup(path: str, symbol: str, dep_mode: str = "signature") -
474
520
 
475
521
  def _fetch():
476
522
  try:
477
- box["value"] = TeamCache.get("SKELETON", cache_key)
523
+ box["value"] = TeamCache.get("SKELETON", cache_key, timeout=0.45, lic_key=lic_key)
478
524
  except Exception:
479
525
  pass
480
526
 
481
527
  t = threading.Thread(target=_fetch, daemon=True)
482
528
  t.start()
483
- t.join(0.25)
529
+ t.join(0.45)
484
530
  return box.get("value")
485
531
  except Exception:
486
532
  return None
@@ -504,8 +550,58 @@ def _team_skeleton_prewarm(
504
550
  pass
505
551
 
506
552
 
553
+ def _safe_int(value, default: int, lo: Optional[int] = None, hi: Optional[int] = None) -> int:
554
+ if value is None or isinstance(value, bool):
555
+ n = default
556
+ else:
557
+ try:
558
+ n = int(value)
559
+ except (TypeError, ValueError):
560
+ n = default
561
+ if lo is not None:
562
+ n = max(lo, n)
563
+ if hi is not None:
564
+ n = min(hi, n)
565
+ return n
566
+
567
+
568
+ def _is_binary_file(path: str, probe_bytes: int = 4096) -> bool:
569
+ try:
570
+ with open(path, "rb") as f:
571
+ chunk = f.read(probe_bytes)
572
+ return b"\x00" in chunk
573
+ except OSError:
574
+ return False
575
+
576
+
577
+ def _read_line_slice(path: str, start_line: Optional[int], end_line: Optional[int]) -> Tuple[Optional[str], Optional[str]]:
578
+ """Reads 1-based [start_line..end_line] using bounded iteration. Returns (content, err_msg)."""
579
+ if start_line is not None and start_line < 1:
580
+ start_line = 1
581
+ if end_line is not None and end_line < 1:
582
+ return None, "end_line must be >= 1"
583
+ if start_line is not None and end_line is not None and start_line > end_line:
584
+ return None, f"start_line ({start_line}) cannot be greater than end_line ({end_line})"
585
+
586
+ s = 1 if start_line is None else start_line
587
+ selected: List[str] = []
588
+ total_seen = 0
589
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
590
+ for idx, line in enumerate(f, 1):
591
+ total_seen = idx
592
+ if idx < s:
593
+ continue
594
+ if end_line is not None and idx > end_line:
595
+ break
596
+ selected.append(line)
597
+ if s > total_seen and total_seen > 0:
598
+ return None, f"start_line {s} is beyond end of file ({total_seen} lines)"
599
+ return "".join(selected), None
600
+
601
+
507
602
  def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
508
- inc_deps = bool(args.get("include_deps", True))
603
+ raw_inc = args.get("include_deps")
604
+ inc_deps = True if raw_inc is None else bool(raw_inc)
509
605
  if not inc_deps:
510
606
  return False, "none"
511
607
  raw_mode = str(args.get("dep_mode") or "").strip().lower()
@@ -526,10 +622,12 @@ def handle_tool_call(name: str, args: dict) -> dict:
526
622
  symbol = (args.get("symbol") or "").strip()
527
623
  _, eff_dep_mode = _resolve_dep_mode(args)
528
624
  cache_sym = f"{symbol}@{eff_dep_mode}" if (symbol and eff_dep_mode != "signature") else symbol
529
- if text_out and path:
625
+ is_ranged = args.get("start_line") is not None or args.get("end_line") is not None
626
+ is_quota_truncated = "[TokenSafe Community 500k limit reached:" in text_out or "// Quota exceeded" in text_out
627
+ if text_out and path and not is_ranged and not is_quota_truncated:
530
628
  abs_path = os.path.abspath(path)
531
629
  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:
630
+ if cur_hash:
533
631
  _IN_PROCESS_DELIVERED[(abs_path, symbol, eff_dep_mode)] = (cur_hash, _EPOCH_GEN)
534
632
  # Never overwrite cached skeleton with a firewall header or pointer hit
535
633
  if not text_out.startswith("// [TokenSafe Subagent Firewall:"):
@@ -573,37 +671,56 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
573
671
  # Clamp explicit line ranges to sane bounds so bad indices can never produce
574
672
  # empty output or negative-index slicing artifacts.
575
673
  try:
576
- if start_line is not None:
577
- start_line = max(1, int(start_line))
578
- if end_line is not None:
674
+ if start_line is not None and not isinstance(start_line, bool):
675
+ start_line = int(start_line)
676
+ elif isinstance(start_line, bool):
677
+ raise TypeError("start_line cannot be bool")
678
+ if end_line is not None and not isinstance(end_line, bool):
579
679
  end_line = int(end_line)
680
+ elif isinstance(end_line, bool):
681
+ raise TypeError("end_line cannot be bool")
580
682
  except (TypeError, ValueError):
581
683
  return _fallback_error("smart_read_file", "start_line/end_line must be integers")
582
684
 
685
+ if end_line is not None and end_line < 1:
686
+ return _fallback_error("smart_read_file", "end_line must be >= 1")
687
+ if start_line is not None:
688
+ start_line = max(1, start_line)
689
+
583
690
  if not path or not os.path.exists(path):
584
691
  return {"isError": True, "content": [{"type": "text", "text": f"File not found: {path}"}]}
585
692
  try:
586
- if not stat.S_ISREG(os.stat(path).st_mode):
693
+ st = os.stat(path)
694
+ if not stat.S_ISREG(st.st_mode):
587
695
  return _fallback_error("smart_read_file", f"path is not a regular file: {path}")
588
696
  except OSError as e:
589
697
  return _fallback_error("smart_read_file", f"cannot stat path: {e}")
590
698
 
699
+ if _is_binary_file(path):
700
+ return _fallback_error("smart_read_file", f"'{os.path.basename(path)}' appears to be a binary file")
701
+
591
702
  # Community 500k quota reached: soft-degrade to bounded raw read (disable Graph/AST/Pointer/Team Cache)
592
703
  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])
704
+ if start_line is not None or end_line is not None:
705
+ raw_chunk, err = _read_line_slice(path, start_line, end_line)
706
+ if err:
707
+ return _fallback_error("smart_read_file", err)
600
708
  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"
709
+ cap = 250
710
+ raw_lines: List[str] = []
711
+ total_seen = 0
712
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
713
+ for idx, line in enumerate(f, 1):
714
+ total_seen = idx
715
+ if idx <= cap:
716
+ raw_lines.append(line)
717
+ elif idx == cap + 1:
718
+ pass
719
+ raw_chunk = "".join(raw_lines)
720
+ if total_seen > cap:
721
+ 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"
605
722
  banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
606
- return {"content": [{"type": "text", "text": banner + raw_chunk}]}
723
+ return {"content": [{"type": "text", "text": banner + (raw_chunk or "")}]}
607
724
 
608
725
  abs_path = os.path.abspath(path)
609
726
  sym_clean = (symbol or "").strip()
@@ -630,20 +747,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
630
747
  if is_loop:
631
748
  return {"isError": True, "content": [{"type": "text", "text": f"⚠️ {msg}"}]}
632
749
 
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)
637
-
638
- # Check targeted symbol or skeleton
639
- if start_line is not None and end_line is not None:
640
- with open(path, "r", encoding="utf-8", errors="replace") as f:
641
- lines = f.readlines()
642
- end_line = min(end_line, len(lines))
643
- if start_line > end_line:
644
- return _fallback_error("smart_read_file", f"start_line {start_line} is beyond end of file ({len(lines)} lines)")
645
- content = "".join(lines[start_line - 1 : end_line])
646
- return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
750
+ # Explicit line range (handles single-bound start_line or end_line as well as both)
751
+ if start_line is not None or end_line is not None:
752
+ content, err = _read_line_slice(path, start_line, end_line)
753
+ if err:
754
+ return _fallback_error("smart_read_file", err)
755
+ prefetch_block = ""
756
+ if not sym_clean or eff_dep_mode == "full":
757
+ prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
758
+ return {"content": [{"type": "text", "text": (prefetch_block or "") + (content or "")}]}
647
759
 
648
760
  if symbol:
649
761
  # Team pre-warm hit: a teammate already skeletonized this symbol
@@ -660,6 +772,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
660
772
  optimized_tokens=skel_t,
661
773
  details={"file": os.path.basename(path), "symbol": symbol, "dep_mode": eff_dep_mode, "source": "team_cache"}
662
774
  )
775
+ prefetch_block = ""
776
+ if eff_dep_mode == "full":
777
+ prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
663
778
  header = f"// [TokenSafe Team-Cached Skeleton for '{symbol}' | shared by a teammate]\n"
664
779
  return {"content": [{"type": "text", "text": (prefetch_block or "") + header + team_skel}]}
665
780
 
@@ -699,30 +814,49 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
699
814
  dep_label = "Full body + 1-hop signature deps"
700
815
  header = f"// [TokenSafe Graph-Guided Skeleton for '{symbol}' | {dep_label}]\n"
701
816
  _team_skeleton_prewarm(path, symbol, graph_skel, saved, dep_mode=eff_dep_mode)
817
+ prefetch_block = ""
818
+ if eff_dep_mode == "full":
819
+ prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
702
820
  return {"content": [{"type": "text", "text": (prefetch_block or "") + header + graph_skel}]}
703
821
  except Exception:
704
822
  pass
705
823
 
706
824
  overwrite, metrics = ToolSlicer.optimize_read_file({"Path": path}, context_hint=symbol)
707
825
  if overwrite:
708
- with open(path, "r", encoding="utf-8", errors="replace") as f:
709
- lines = f.readlines()
710
826
  s_line = overwrite["StartLine"]
711
827
  e_line = overwrite["EndLine"]
712
- content = "".join(lines[s_line - 1 : e_line])
828
+ content, _ = _read_line_slice(path, s_line, e_line)
829
+ prefetch_block = ""
830
+ if eff_dep_mode == "full":
831
+ prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
713
832
  header = f"// [TOCP Targeted Window: lines {s_line}-{e_line} for '{symbol}']\n"
714
- return {"content": [{"type": "text", "text": (prefetch_block or "") + header + content}]}
833
+ return {"content": [{"type": "text", "text": (prefetch_block or "") + header + (content or "")}]}
715
834
 
716
- # Check AST skeleton
717
- skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path)
835
+ # Check AST skeleton (preserves target_symbol body when symbol was given; avoids duplicate prefetch)
836
+ skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path, target_symbol=(symbol or None))
718
837
  if skel_path and os.path.exists(skel_path):
719
838
  with open(skel_path, "r", encoding="utf-8", errors="replace") as f:
720
839
  content = f.read()
840
+ if orig_t > skel_t:
841
+ tracker.record_event(
842
+ session_id=_mcp_session_id(),
843
+ event_type="AST_SKELETON",
844
+ original_tokens=orig_t,
845
+ optimized_tokens=skel_t,
846
+ details={"target_file": os.path.basename(path), "saved_tokens": orig_t - skel_t}
847
+ )
721
848
  return {"content": [{"type": "text", "text": content}]}
722
849
 
723
- # Default read
724
- with open(path, "r", encoding="utf-8", errors="replace") as f:
725
- content = f.read()
850
+ # Default bounded read (avoid dumping multi-MB files raw)
851
+ prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
852
+ max_raw_bytes = 512 * 1024
853
+ if st.st_size > max_raw_bytes:
854
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
855
+ content = f.read(max_raw_bytes)
856
+ content += f"\n// [TokenSafe: file truncated at 512KB ({st.st_size:,} bytes total). Use start_line/end_line or symbol to inspect specific sections.]\n"
857
+ else:
858
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
859
+ content = f.read()
726
860
  return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
727
861
 
728
862
  elif name == "compress_prompt":
@@ -986,7 +1120,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
986
1120
  if is_quota_exceeded:
987
1121
  banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
988
1122
  return {"content": [{"type": "text", "text": banner + raw_diff}]}
989
- max_ctx = int(args.get("max_context", 2))
1123
+ max_ctx = _safe_int(args.get("max_context"), 2, lo=0, hi=50)
990
1124
  sliced, orig_t, opt_t = DiffSlicer.slice_diff(raw_diff, max_context_lines=max_ctx)
991
1125
  saved = max(0, orig_t - opt_t)
992
1126
  if saved > 0:
@@ -1074,12 +1208,14 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1074
1208
 
1075
1209
  # Resolve path relative to current working directory or absolute
1076
1210
  abs_path = os.path.abspath(path)
1211
+ if not os.path.isdir(abs_path):
1212
+ return _fallback_error("list_dir", f"directory not found: {abs_path}")
1077
1213
  system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
1078
- depth = min(4, max(1, int(args.get("depth", 2))))
1214
+ depth = _safe_int(args.get("depth"), 2, lo=1, hi=4)
1079
1215
  if abs_path in system_roots:
1080
1216
  # Do not walk entire home dir or filesystem root deeply
1081
1217
  depth = 1
1082
- max_entries = min(150, max(10, int(args.get("max_entries", 80))))
1218
+ max_entries = _safe_int(args.get("max_entries"), 80, lo=10, hi=150)
1083
1219
 
1084
1220
  tree_output = build_dir_tree(abs_path, max_depth=depth, max_entries=max_entries)
1085
1221
  tree_tokens = count_tokens(tree_output)
@@ -1111,7 +1247,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1111
1247
  return _fallback_error("scoped_search", err or "unspecified project_path")
1112
1248
  target_path = resolved_path
1113
1249
 
1114
- max_res = args.get("max_results", 25)
1250
+ max_res = _safe_int(args.get("max_results"), 25, lo=1, hi=100)
1115
1251
  c_sens = bool(args.get("case_sensitive", False))
1116
1252
  u_regex = bool(args.get("use_regex", False))
1117
1253
 
@@ -1210,10 +1346,13 @@ def run_mcp_server():
1210
1346
  req = json.loads(line)
1211
1347
  except Exception:
1212
1348
  continue
1349
+ if not isinstance(req, dict):
1350
+ continue
1213
1351
 
1214
1352
  msg_id = req.get("id")
1215
1353
  method = req.get("method")
1216
- params = req.get("params", {})
1354
+ raw_params = req.get("params")
1355
+ params = raw_params if isinstance(raw_params, dict) else {}
1217
1356
 
1218
1357
  # Notifications (no id, or notifications/*) must never receive JSON-RPC responses
1219
1358
  if msg_id is None or (isinstance(method, str) and method.startswith("notifications/")):
@@ -1223,8 +1362,9 @@ def run_mcp_server():
1223
1362
 
1224
1363
  if method == "initialize":
1225
1364
  try:
1226
- client_info = (params or {}).get("clientInfo") or {}
1227
- _set_mcp_client(str(client_info.get("name") or ""))
1365
+ client_info = params.get("clientInfo") or {}
1366
+ if isinstance(client_info, dict):
1367
+ _set_mcp_client(str(client_info.get("name") or ""))
1228
1368
  except Exception:
1229
1369
  pass
1230
1370
  try:
@@ -1241,8 +1381,9 @@ def run_mcp_server():
1241
1381
  _TOOLS_LISTED = True
1242
1382
  response["result"] = {"tools": TOOLS}
1243
1383
  elif method == "tools/call":
1244
- tool_name = params.get("name", "")
1245
- tool_args = params.get("arguments", {})
1384
+ tool_name = str(params.get("name") or "")
1385
+ raw_tool_args = params.get("arguments")
1386
+ tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
1246
1387
  try:
1247
1388
  response["result"] = _execute_with_timeout(tool_name, tool_args)
1248
1389
  except Exception as e: