tokensafe 3.1.5 → 4.0.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.
Files changed (44) hide show
  1. package/README.md +79 -58
  2. package/bin/tokensafe.js +25 -9
  3. package/hooks/claude_code_hook.py +7 -0
  4. package/hooks/pre_tool_use.py +24 -0
  5. package/hooks/session_start.py +8 -0
  6. package/package.json +3 -3
  7. package/plugin.json +1 -1
  8. package/rules/AGENTS.md +13 -7
  9. package/server.json +3 -3
  10. package/skills/token-optimizer/SKILL.md +7 -2
  11. package/skills/token-optimizer/references/cli-reference.md +11 -1
  12. package/skills/token-optimizer/references/mcp-tools.md +44 -2
  13. package/src/bench_scenarios.json +376 -0
  14. package/src/cache_normalizer.py +21 -0
  15. package/src/cli.py +425 -4
  16. package/src/command_sanitizer.py +2 -0
  17. package/src/compactor.py +1 -1
  18. package/src/competitors.py +179 -0
  19. package/src/environment_auditor.py +110 -1
  20. package/src/format_parsers/__init__.py +20 -0
  21. package/src/format_parsers/ansi.py +41 -0
  22. package/src/format_parsers/compiler_errors.py +159 -0
  23. package/src/format_parsers/docker_k8s.py +95 -0
  24. package/src/format_parsers/json_log.py +89 -0
  25. package/src/format_parsers/lockfiles.py +157 -0
  26. package/src/format_parsers/tabular.py +175 -0
  27. package/src/fts_index.py +296 -0
  28. package/src/graph_engine.py +395 -48
  29. package/src/image_downscale.py +228 -0
  30. package/src/installer.py +47 -1
  31. package/src/license_manager.py +103 -7
  32. package/src/loop_detector.py +5 -0
  33. package/src/mcp_config_manager.py +197 -0
  34. package/src/mcp_proxy.py +154 -0
  35. package/src/mcp_server.py +215 -1
  36. package/src/mistakes.py +203 -0
  37. package/src/result_ledger.py +8 -1
  38. package/src/scoped_search.py +32 -0
  39. package/src/stash.py +199 -0
  40. package/src/superseded.py +220 -0
  41. package/src/telemetry_sync.py +14 -1
  42. package/src/test_parsers.py +271 -0
  43. package/src/version_checker.py +1 -1
  44. package/src/web_reader.py +202 -0
@@ -0,0 +1,228 @@
1
+ """
2
+ TokenSafe Vision Image Downscaler & Optimizer (v3.3.0).
3
+
4
+ Optimizes oversized screenshots and UI diagrams before LLM vision ingestion.
5
+ Downscales images exceeding max_edge (default: 1024px) while preserving aspect ratio,
6
+ text crispness, and leaving the original image file intact on disk.
7
+
8
+ Engines:
9
+ 1. Pillow (PIL) - high-quality Lanczos resampling
10
+ 2. macOS sips - zero-dependency built-in OS tool
11
+ 3. ImageMagick (convert/magick) - headless Linux fallback
12
+ """
13
+
14
+ import os
15
+ import shutil
16
+ import hashlib
17
+ import subprocess
18
+ from typing import Dict, Any, Tuple, Optional
19
+ from src.paths import resolve_data_dir
20
+
21
+ # Supported extensions
22
+ IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}
23
+
24
+
25
+ def estimate_vision_tokens(width: int, height: int) -> int:
26
+ """
27
+ Estimates LLM vision token cost based on standard tile-based pricing
28
+ (Anthropic Claude 3.5 Sonnet / OpenAI GPT-4o tile calculation).
29
+ """
30
+ if width <= 0 or height <= 0:
31
+ return 0
32
+ # Base tile calculation: 512x512 grid
33
+ tiles_w = (width + 511) // 512
34
+ tiles_h = (height + 511) // 512
35
+ total_tiles = max(1, tiles_w * tiles_h)
36
+ # 85 base tokens + 170 tokens per tile
37
+ return 85 + (total_tiles * 170)
38
+
39
+
40
+ def _get_cache_dir() -> str:
41
+ cache_dir = os.path.join(resolve_data_dir(), "cache", "images")
42
+ os.makedirs(cache_dir, exist_ok=True)
43
+ return cache_dir
44
+
45
+
46
+ def _read_dimensions_pillow(path: str) -> Optional[Tuple[int, int]]:
47
+ try:
48
+ from PIL import Image
49
+ with Image.open(path) as img:
50
+ return img.size # (width, height)
51
+ except Exception:
52
+ return None
53
+
54
+
55
+ def _read_dimensions_sips(path: str) -> Optional[Tuple[int, int]]:
56
+ try:
57
+ res = subprocess.run(
58
+ ["/usr/bin/sips", "-g", "pixelWidth", "-g", "pixelHeight", path],
59
+ capture_output=True, text=True, timeout=5
60
+ )
61
+ if res.returncode == 0:
62
+ w, h = 0, 0
63
+ for line in res.stdout.splitlines():
64
+ if "pixelWidth:" in line:
65
+ w = int(line.split(":")[-1].strip())
66
+ elif "pixelHeight:" in line:
67
+ h = int(line.split(":")[-1].strip())
68
+ if w > 0 and h > 0:
69
+ return (w, h)
70
+ except Exception:
71
+ pass
72
+ return None
73
+
74
+
75
+ def get_image_dimensions(path: str) -> Optional[Tuple[int, int]]:
76
+ dims = _read_dimensions_pillow(path)
77
+ if dims:
78
+ return dims
79
+ if shutil.which("sips"):
80
+ dims = _read_dimensions_sips(path)
81
+ if dims:
82
+ return dims
83
+ return None
84
+
85
+
86
+ class ImageDownscaler:
87
+ """Downscales images to save vision tokens without mutating original files."""
88
+
89
+ @classmethod
90
+ def optimize(
91
+ cls,
92
+ image_path: str,
93
+ max_edge: int = 1024,
94
+ cache_dir: Optional[str] = None
95
+ ) -> Dict[str, Any]:
96
+ """
97
+ Downscales an image if max(width, height) > max_edge.
98
+ Returns metadata with optimized_path, saved_tokens, etc.
99
+ """
100
+ if not os.path.exists(image_path):
101
+ return {
102
+ "success": False,
103
+ "error": f"Image file not found: {image_path}",
104
+ "was_downscaled": False
105
+ }
106
+
107
+ ext = os.path.splitext(image_path)[1].lower()
108
+ if ext not in IMAGE_EXTENSIONS:
109
+ return {
110
+ "success": False,
111
+ "error": f"Unsupported image format: {ext}",
112
+ "was_downscaled": False
113
+ }
114
+
115
+ dims = get_image_dimensions(image_path)
116
+ if not dims:
117
+ return {
118
+ "success": True,
119
+ "was_downscaled": False,
120
+ "optimized_path": image_path,
121
+ "note": "Could not inspect dimensions; using original file"
122
+ }
123
+
124
+ w, h = dims
125
+ orig_bytes = os.path.getsize(image_path)
126
+ orig_tokens = estimate_vision_tokens(w, h)
127
+
128
+ if max(w, h) <= max_edge:
129
+ return {
130
+ "success": True,
131
+ "was_downscaled": False,
132
+ "original_path": image_path,
133
+ "optimized_path": image_path,
134
+ "dimensions": (w, h),
135
+ "bytes": orig_bytes,
136
+ "estimated_tokens": orig_tokens,
137
+ "saved_tokens": 0
138
+ }
139
+
140
+ # Compute new dimensions maintaining aspect ratio
141
+ if w >= h:
142
+ new_w = max_edge
143
+ new_h = max(1, int(round(h * (max_edge / float(w)))))
144
+ else:
145
+ new_h = max_edge
146
+ new_w = max(1, int(round(w * (max_edge / float(h)))))
147
+
148
+ # Compute output cache path based on content hash and max_edge
149
+ target_dir = cache_dir or _get_cache_dir()
150
+ hasher = hashlib.sha256()
151
+ with open(image_path, "rb") as f:
152
+ while chunk := f.read(65536):
153
+ hasher.update(chunk)
154
+ hasher.update(str(max_edge).encode("utf-8"))
155
+ cache_key = hasher.hexdigest()[:16]
156
+ optimized_path = os.path.join(target_dir, f"{cache_key}{ext}")
157
+
158
+ engine_used = None
159
+
160
+ # 1. Try Pillow
161
+ try:
162
+ from PIL import Image
163
+ with Image.open(image_path) as img:
164
+ resample_filter = getattr(Image.Resampling, "LANCZOS", Image.LANCZOS if hasattr(Image, "LANCZOS") else 1)
165
+ resized = img.resize((new_w, new_h), resample=resample_filter)
166
+ resized.save(optimized_path)
167
+ engine_used = "pillow"
168
+ except Exception:
169
+ engine_used = None
170
+
171
+ # 2. Try macOS sips if Pillow failed or was unavailable
172
+ if not engine_used and shutil.which("sips"):
173
+ try:
174
+ res = subprocess.run(
175
+ ["/usr/bin/sips", "-Z", str(max_edge), image_path, "--out", optimized_path],
176
+ capture_output=True, timeout=10
177
+ )
178
+ if res.returncode == 0 and os.path.exists(optimized_path):
179
+ engine_used = "sips"
180
+ except Exception:
181
+ engine_used = None
182
+
183
+ # 3. Try ImageMagick
184
+ if not engine_used:
185
+ magick_cmd = shutil.which("magick") or shutil.which("convert")
186
+ if magick_cmd:
187
+ try:
188
+ res = subprocess.run(
189
+ [magick_cmd, image_path, "-resize", f"{max_edge}x{max_edge}>", optimized_path],
190
+ capture_output=True, timeout=10
191
+ )
192
+ if res.returncode == 0 and os.path.exists(optimized_path):
193
+ engine_used = "imagemagick"
194
+ except Exception:
195
+ engine_used = None
196
+
197
+ if not engine_used or not os.path.exists(optimized_path):
198
+ # Graceful fallback: return original image
199
+ return {
200
+ "success": True,
201
+ "was_downscaled": False,
202
+ "original_path": image_path,
203
+ "optimized_path": image_path,
204
+ "dimensions": (w, h),
205
+ "bytes": orig_bytes,
206
+ "estimated_tokens": orig_tokens,
207
+ "saved_tokens": 0,
208
+ "note": "Downscaling engines unavailable; using original file"
209
+ }
210
+
211
+ new_bytes = os.path.getsize(optimized_path)
212
+ new_tokens = estimate_vision_tokens(new_w, new_h)
213
+ saved_tokens = max(0, orig_tokens - new_tokens)
214
+
215
+ return {
216
+ "success": True,
217
+ "was_downscaled": True,
218
+ "engine": engine_used,
219
+ "original_path": image_path,
220
+ "optimized_path": optimized_path,
221
+ "orig_dimensions": (w, h),
222
+ "new_dimensions": (new_w, new_h),
223
+ "orig_bytes": orig_bytes,
224
+ "new_bytes": new_bytes,
225
+ "orig_tokens": orig_tokens,
226
+ "new_tokens": new_tokens,
227
+ "saved_tokens": saved_tokens,
228
+ }
package/src/installer.py CHANGED
@@ -550,7 +550,7 @@ WantedBy=default.target
550
550
  try:
551
551
  if not (sys.stdin.isatty() and sys.stdout.isatty()):
552
552
  return
553
- if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes"):
553
+ if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes") or "unittest" in sys.modules:
554
554
  return
555
555
  st = cls.proxy_status()
556
556
  if st.get("claude_code_wired"):
@@ -574,6 +574,50 @@ WantedBy=default.target
574
574
  except Exception:
575
575
  return # fail-open: a prompt problem never breaks install/update
576
576
 
577
+ @classmethod
578
+ def maybe_prompt_account_login(cls, context: str = "install") -> None:
579
+ """
580
+ Interactive prompt to connect TokenSafe account and unlock web dashboard.
581
+ Migrates anonymous community@tokensafe.dev licenses to verified user accounts.
582
+ Fail-open: skips quietly on non-interactive environments (CI, scripts).
583
+ """
584
+ try:
585
+ from src.license_manager import LicenseManager
586
+ _, lic = LicenseManager.get_active_license()
587
+ email = lic.get("email", "")
588
+
589
+ # If user already has a real personal account (not the legacy anonymous key), nothing to prompt
590
+ if email and email != "community@tokensafe.dev":
591
+ return
592
+
593
+ is_anonymous = (email == "community@tokensafe.dev")
594
+
595
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
596
+ print(f" {CYAN}ℹ{RESET} Run {BOLD}tokensafe login{RESET} anytime to activate your Community license & web dashboard.\n")
597
+ return
598
+
599
+ if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes") or "unittest" in sys.modules:
600
+ return
601
+
602
+ if context == "update" and is_anonymous:
603
+ print(f"\n {YELLOW}→ Anonymous Community license detected (migrating to verified personal account).{RESET}")
604
+ print(f" Connect your free account at {CYAN}https://tokensafe.dev{RESET} to unlock your web dashboard.")
605
+ else:
606
+ print(f"\n {CYAN}→ Connect your free TokenSafe account (500,000 tokens/mo) to unlock your web dashboard:{RESET}")
607
+
608
+ print(f" Open browser to authorize? [{GREEN}Y{RESET}/n] ", end="", flush=True)
609
+ answer = input().strip().lower()
610
+ if answer in ("", "y", "yes"):
611
+ from src.cli import main as cli_main
612
+ cli_main(["login"])
613
+ else:
614
+ print(f" {CYAN}ℹ{RESET} You can run {BOLD}tokensafe login{RESET} anytime to activate your account.\n")
615
+ except (EOFError, KeyboardInterrupt):
616
+ print()
617
+ return
618
+ except Exception:
619
+ return
620
+
577
621
  @classmethod
578
622
  def install_mcp_config(cls, agent_key: str) -> Tuple[bool, str]:
579
623
  """Injects TokenSafe MCP config into target agent."""
@@ -1073,6 +1117,7 @@ WantedBy=default.target
1073
1117
 
1074
1118
  print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
1075
1119
  print(" Restart your IDE / Agent to start saving tokens automatically.\n")
1120
+ cls.maybe_prompt_account_login(context="install")
1076
1121
  cls.maybe_prompt_proxy_enable(context="install")
1077
1122
 
1078
1123
  @staticmethod
@@ -1419,6 +1464,7 @@ WantedBy=default.target
1419
1464
  print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
1420
1465
  print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
1421
1466
  print(f" {CYAN}ℹ{RESET} If your terminal still shows the old version, open a new window or run {BOLD}hash -r{RESET}.")
1467
+ cls.maybe_prompt_account_login(context="update")
1422
1468
  cls.maybe_prompt_proxy_enable(context="update")
1423
1469
 
1424
1470
  def main():
@@ -91,9 +91,58 @@ class LicenseManager:
91
91
 
92
92
  @classmethod
93
93
  def get_machine_fingerprint(cls) -> str:
94
- """One-way anonymized machine identifier for server-side free-tier quota continuity."""
95
- raw = f"ts:{platform.system()}:{platform.node()}:{uuid.getnode()}:{os.path.expanduser('~')}"
96
- return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
94
+ """
95
+ One-way anonymized machine identifier for server-side quota continuity.
96
+ Uses persistent ~/.tokensafe/data/.machine_id backed by hardware UUID
97
+ (IOPlatformUUID on macOS / /etc/machine-id on Linux) to prevent Wi-Fi/DHCP drift.
98
+ """
99
+ try:
100
+ data_dir = resolve_data_dir()
101
+ mid_file = os.path.join(data_dir, ".machine_id")
102
+ if os.path.exists(mid_file):
103
+ with open(mid_file, "r", encoding="utf-8") as f:
104
+ content = f.read().strip().lower()
105
+ if re.fullmatch(r"[0-9a-f]{32}", content):
106
+ return content
107
+ except Exception:
108
+ pass
109
+
110
+ hw_uuid = ""
111
+ try:
112
+ if platform.system() == "Darwin":
113
+ import subprocess
114
+ cmd = ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"]
115
+ res = subprocess.run(cmd, capture_output=True, text=True, timeout=2)
116
+ if res.returncode == 0:
117
+ for line in res.stdout.splitlines():
118
+ if "IOPlatformUUID" in line:
119
+ parts = line.split("=")
120
+ if len(parts) > 1:
121
+ hw_uuid = parts[1].strip().strip('"')
122
+ break
123
+ elif platform.system() == "Linux":
124
+ for p in ("/etc/machine-id", "/var/lib/dbus/machine-id"):
125
+ if os.path.exists(p):
126
+ with open(p, "r", encoding="utf-8") as f:
127
+ hw_uuid = f.read().strip()
128
+ if hw_uuid:
129
+ break
130
+ except Exception:
131
+ hw_uuid = ""
132
+
133
+ raw = f"ts:{platform.system()}:{hw_uuid or uuid.getnode()}"
134
+ fp = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
135
+
136
+ try:
137
+ data_dir = resolve_data_dir()
138
+ os.makedirs(data_dir, exist_ok=True)
139
+ mid_file = os.path.join(data_dir, ".machine_id")
140
+ with open(mid_file, "w", encoding="utf-8") as f:
141
+ f.write(fp)
142
+ except Exception:
143
+ pass
144
+
145
+ return fp
97
146
 
98
147
  @classmethod
99
148
  def detect_agent(cls) -> str:
@@ -444,18 +493,64 @@ class LicenseManager:
444
493
  return key
445
494
 
446
495
  @classmethod
447
- def save_license(cls, license_key: str) -> Tuple[bool, str]:
448
- """Saves a verified license key to local and user global persistent storage."""
496
+ def get_device_token(cls) -> str:
497
+ """Retrieves stored device refresh token."""
498
+ for target_file in cls._candidate_license_files():
499
+ if os.path.exists(target_file):
500
+ try:
501
+ with open(target_file, "r", encoding="utf-8") as f:
502
+ tok = json.load(f).get("device_token", "")
503
+ if tok:
504
+ return str(tok).strip()
505
+ except Exception:
506
+ pass
507
+ return ""
508
+
509
+ @classmethod
510
+ def refresh_device_license(cls) -> Tuple[bool, str]:
511
+ """Silently refreshes signed Community license via saved device_token without user interaction."""
512
+ device_token = cls.get_device_token()
513
+ if not device_token:
514
+ return False, "no_device_token"
515
+ try:
516
+ import urllib.request
517
+ cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
518
+ req = urllib.request.Request(
519
+ f"{cloud_url}/api/auth/device/refresh",
520
+ data=json.dumps({
521
+ "device_token": device_token,
522
+ "machine_fp": cls.get_machine_fingerprint()
523
+ }).encode("utf-8"),
524
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/Refresh"},
525
+ method="POST"
526
+ )
527
+ with urllib.request.urlopen(req, timeout=3.5) as resp:
528
+ data = json.loads(resp.read().decode("utf-8") or "{}")
529
+ new_key = data.get("license_key", "")
530
+ if resp.status == 200 and data.get("success") and new_key:
531
+ ok, msg = cls.save_license(new_key, device_token=device_token)
532
+ return ok, msg
533
+ return False, str(data.get("error") or "refresh_failed")
534
+ except Exception as exc:
535
+ return False, str(exc)
536
+
537
+ @classmethod
538
+ def save_license(cls, license_key: str, device_token: str = "") -> Tuple[bool, str]:
539
+ """Saves a verified license key and optional device refresh token to persistent storage."""
449
540
  valid, payload, msg = cls.validate_license(license_key)
450
541
  if not valid:
451
542
  return False, f"Cannot save invalid license: {msg}"
452
543
 
544
+ # Preserve existing device_token if none provided
545
+ resolved_device_token = device_token or cls.get_device_token()
546
+
453
547
  record = {
454
548
  "license_key": license_key,
455
549
  "tier": payload.get("tier"),
456
550
  "email": payload.get("email"),
457
551
  "expires_at": payload.get("expires_at"),
458
552
  "trial": payload.get("trial", False),
553
+ "device_token": resolved_device_token,
459
554
  "saved_at": int(time.time())
460
555
  }
461
556
 
@@ -497,8 +592,9 @@ class LicenseManager:
497
592
  )
498
593
  if base_dir:
499
594
  mirror_paths.append(os.path.join(base_dir, ".qledger.json"))
500
- mirror_paths.append(os.path.join(os.path.dirname(DATA_DIR), ".qledger.json"))
501
- mirror_paths.append(os.path.join(DATA_DIR, ".qledger.json"))
595
+ else:
596
+ mirror_paths.append(os.path.join(os.path.dirname(DATA_DIR), ".qledger.json"))
597
+ mirror_paths.append(os.path.join(DATA_DIR, ".qledger.json"))
502
598
 
503
599
  for mirror_path in mirror_paths:
504
600
  if os.path.exists(mirror_path):
@@ -159,6 +159,11 @@ class LoopDetector:
159
159
  f"Token Optimizer Loop Guard: Tool '{tool_name}' invoked with identical "
160
160
  f"parameters {repeats} times in a row. Pausing loop to prevent token drain."
161
161
  )
162
+ try:
163
+ from src.mistakes import MistakesLedger
164
+ MistakesLedger.record_from_loop(tool_name, args, repeats)
165
+ except Exception:
166
+ pass
162
167
  return True, repeats, msg
163
168
 
164
169
  return False, repeats, ""
@@ -0,0 +1,197 @@
1
+ """
2
+ TokenSafe MCP Config Manager (v3.3.0).
3
+
4
+ Inspects, wraps, and unwraps third-party MCP servers across AI coding agent configs
5
+ (Claude Code, Cursor, Codex, Windsurf) to route them through `tokensafe mcp-proxy`.
6
+ Preserves original command & arguments under `_tokensafe_orig` for 100% reversible unwrapping.
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import json
12
+ import shutil
13
+ from typing import Dict, Any, List, Optional, Tuple
14
+
15
+ HOME = os.path.expanduser("~")
16
+
17
+ CONFIG_CANDIDATES = [
18
+ ("Claude Code / Desktop", os.path.join(HOME, ".claude.json")),
19
+ ("Claude Settings", os.path.join(HOME, ".claude", "settings.json")),
20
+ ("Cursor Global", os.path.join(HOME, ".cursor", "mcp.json")),
21
+ ("Codex Global", os.path.join(HOME, ".codex", "config.json")),
22
+ ("Windsurf Global", os.path.join(HOME, ".codeium", "windsurf", "mcp_config.json")),
23
+ ]
24
+
25
+
26
+ class MCPConfigManager:
27
+ """Manages MCP configurations across local coding agents."""
28
+
29
+ @classmethod
30
+ def get_existing_configs(cls) -> List[Tuple[str, str]]:
31
+ """Returns list of (agent_name, file_path) for existing configuration files."""
32
+ found = []
33
+ for name, path in CONFIG_CANDIDATES:
34
+ if os.path.isfile(path):
35
+ found.append((name, path))
36
+ return found
37
+
38
+ @classmethod
39
+ def _read_config(cls, path: str) -> Optional[Dict[str, Any]]:
40
+ try:
41
+ with open(path, "r", encoding="utf-8") as f:
42
+ data = json.load(f)
43
+ return data if isinstance(data, dict) else None
44
+ except Exception:
45
+ return None
46
+
47
+ @classmethod
48
+ def _write_config(cls, path: str, data: Dict[str, Any]) -> bool:
49
+ try:
50
+ # Backup
51
+ bak_path = f"{path}.bak.tokensafe"
52
+ if not os.path.exists(bak_path):
53
+ shutil.copy2(path, bak_path)
54
+ tmp_path = f"{path}.tmp.{os.getpid()}"
55
+ with open(tmp_path, "w", encoding="utf-8") as f:
56
+ json.dump(data, f, indent=2, ensure_ascii=False)
57
+ f.write("\n")
58
+ os.replace(tmp_path, path)
59
+ return True
60
+ except Exception:
61
+ return False
62
+
63
+ @classmethod
64
+ def list_servers(cls) -> List[Dict[str, Any]]:
65
+ """Lists all registered MCP servers and their wrapping status."""
66
+ results = []
67
+ for agent_name, path in cls.get_existing_configs():
68
+ data = cls._read_config(path)
69
+ if not data:
70
+ continue
71
+
72
+ servers = data.get("mcpServers") or data.get("mcp") or {}
73
+ if not isinstance(servers, dict):
74
+ continue
75
+
76
+ for s_name, s_def in servers.items():
77
+ if not isinstance(s_def, dict):
78
+ continue
79
+ cmd = s_def.get("command", "")
80
+ args = s_def.get("args", [])
81
+ is_wrapped = False
82
+ if "_tokensafe_orig" in s_def:
83
+ is_wrapped = True
84
+ elif isinstance(cmd, str) and ("tokensafe" in cmd and "mcp-proxy" in " ".join(args)):
85
+ is_wrapped = True
86
+
87
+ # Skip TokenSafe's own MCP server
88
+ if s_name in ("tokensafe", "tokensafe-mcp", "tokensafe-cloud"):
89
+ continue
90
+
91
+ results.append({
92
+ "agent": agent_name,
93
+ "config_path": path,
94
+ "server_name": s_name,
95
+ "command": cmd,
96
+ "args": args,
97
+ "is_wrapped": is_wrapped,
98
+ "orig_def": s_def.get("_tokensafe_orig"),
99
+ })
100
+ return results
101
+
102
+ @classmethod
103
+ def wrap_server(cls, config_path: str, server_name: str) -> bool:
104
+ """Wraps a specific server in config_path to route through tokensafe mcp-proxy."""
105
+ data = cls._read_config(config_path)
106
+ if not data:
107
+ return False
108
+
109
+ key = "mcpServers" if "mcpServers" in data else ("mcp" if "mcp" in data else "mcpServers")
110
+ servers = data.get(key)
111
+ if not isinstance(servers, dict) or server_name not in servers:
112
+ return False
113
+
114
+ s_def = servers[server_name]
115
+ if not isinstance(s_def, dict):
116
+ return False
117
+
118
+ if "_tokensafe_orig" in s_def:
119
+ # Already wrapped
120
+ return True
121
+
122
+ orig_cmd = s_def.get("command")
123
+ orig_args = s_def.get("args") or []
124
+ if not orig_cmd:
125
+ return False
126
+
127
+ s_def["_tokensafe_orig"] = {
128
+ "command": orig_cmd,
129
+ "args": list(orig_args)
130
+ }
131
+
132
+ # Resolve tokensafe CLI binary path or python entrypoint
133
+ tokensafe_bin = shutil.which("tokensafe")
134
+ if tokensafe_bin:
135
+ proxy_cmd = tokensafe_bin
136
+ proxy_args = ["mcp-proxy", "--", orig_cmd] + list(orig_args)
137
+ else:
138
+ proxy_cmd = sys.executable
139
+ # Find cli.py path
140
+ script_dir = os.path.dirname(os.path.realpath(__file__))
141
+ cli_path = os.path.join(script_dir, "cli.py")
142
+ proxy_args = [cli_path, "mcp-proxy", "--", orig_cmd] + list(orig_args)
143
+
144
+ s_def["command"] = proxy_cmd
145
+ s_def["args"] = proxy_args
146
+
147
+ return cls._write_config(config_path, data)
148
+
149
+ @classmethod
150
+ def unwrap_server(cls, config_path: str, server_name: str) -> bool:
151
+ """Restores original command and args for a wrapped server."""
152
+ data = cls._read_config(config_path)
153
+ if not data:
154
+ return False
155
+
156
+ key = "mcpServers" if "mcpServers" in data else ("mcp" if "mcp" in data else "mcpServers")
157
+ servers = data.get(key)
158
+ if not isinstance(servers, dict) or server_name not in servers:
159
+ return False
160
+
161
+ s_def = servers[server_name]
162
+ if not isinstance(s_def, dict):
163
+ return False
164
+
165
+ orig = s_def.get("_tokensafe_orig")
166
+ if not orig or not isinstance(orig, dict):
167
+ return False
168
+
169
+ s_def["command"] = orig.get("command")
170
+ s_def["args"] = orig.get("args", [])
171
+ del s_def["_tokensafe_orig"]
172
+
173
+ return cls._write_config(config_path, data)
174
+
175
+ @classmethod
176
+ def wrap_all(cls) -> int:
177
+ """Wraps all detected unwrapped third-party MCP servers. Returns count of wrapped servers."""
178
+ wrapped_count = 0
179
+ servers = cls.list_servers()
180
+ for s in servers:
181
+ if not s["is_wrapped"]:
182
+ ok = cls.wrap_server(s["config_path"], s["server_name"])
183
+ if ok:
184
+ wrapped_count += 1
185
+ return wrapped_count
186
+
187
+ @classmethod
188
+ def unwrap_all(cls) -> int:
189
+ """Unwraps all wrapped third-party MCP servers. Returns count of unwrapped servers."""
190
+ unwrapped_count = 0
191
+ servers = cls.list_servers()
192
+ for s in servers:
193
+ if s["is_wrapped"]:
194
+ ok = cls.unwrap_server(s["config_path"], s["server_name"])
195
+ if ok:
196
+ unwrapped_count += 1
197
+ return unwrapped_count