tokensafe 3.2.0 → 4.0.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.
- package/README.md +60 -28
- package/bin/tokensafe.js +25 -9
- package/hooks/claude_code_hook.py +7 -0
- package/hooks/pre_tool_use.py +24 -0
- package/hooks/session_start.py +8 -0
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/rules/AGENTS.md +13 -7
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +7 -2
- package/skills/token-optimizer/references/cli-reference.md +11 -1
- package/skills/token-optimizer/references/mcp-tools.md +44 -2
- package/src/bench_scenarios.json +376 -0
- package/src/cache_normalizer.py +21 -0
- package/src/cli.py +234 -2
- package/src/command_sanitizer.py +2 -0
- package/src/competitors.py +179 -0
- package/src/environment_auditor.py +110 -1
- package/src/format_parsers/__init__.py +20 -0
- package/src/format_parsers/ansi.py +41 -0
- package/src/format_parsers/compiler_errors.py +159 -0
- package/src/format_parsers/docker_k8s.py +95 -0
- package/src/format_parsers/json_log.py +89 -0
- package/src/format_parsers/lockfiles.py +157 -0
- package/src/format_parsers/tabular.py +175 -0
- package/src/fts_index.py +296 -0
- package/src/graph_engine.py +395 -48
- package/src/image_downscale.py +228 -0
- package/src/loop_detector.py +5 -0
- package/src/mcp_config_manager.py +197 -0
- package/src/mcp_proxy.py +154 -0
- package/src/mcp_server.py +215 -1
- package/src/mistakes.py +203 -0
- package/src/result_ledger.py +8 -1
- package/src/scoped_search.py +32 -0
- package/src/stash.py +199 -0
- package/src/superseded.py +220 -0
- package/src/telemetry_sync.py +1 -1
- package/src/test_parsers.py +271 -0
- package/src/version_checker.py +1 -1
- 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/loop_detector.py
CHANGED
|
@@ -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
|
package/src/mcp_proxy.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe MCP Response Proxy (v3.3.0).
|
|
3
|
+
|
|
4
|
+
Transparent stdio JSON-RPC 2.0 proxy for third-party MCP servers.
|
|
5
|
+
Spawns the target MCP server as a subprocess, relays messages bidirectionally,
|
|
6
|
+
and intercepts oversized tool responses (e.g. GitHub, Linear, Slack, Context7).
|
|
7
|
+
When a tool response exceeds MAX_UNFOLDED_CHARS (1500 chars / ~400 tokens), it
|
|
8
|
+
folds the payload, saves the raw original into TokenSafe Reversible Stash, and
|
|
9
|
+
attaches a hash anchor:
|
|
10
|
+
[TokenSafe folded: #a1b2c3d4 — call tokensafe:expand_ref('a1b2c3d4') to restore raw content]
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import sys
|
|
14
|
+
import os
|
|
15
|
+
import json
|
|
16
|
+
import subprocess
|
|
17
|
+
import threading
|
|
18
|
+
from typing import Dict, Any, Optional, List, Tuple
|
|
19
|
+
|
|
20
|
+
from src.stash import stash_block
|
|
21
|
+
|
|
22
|
+
MAX_UNFOLDED_CHARS = 1500
|
|
23
|
+
MAX_UNFOLDED_LINES = 35
|
|
24
|
+
HEAD_LINES = 15
|
|
25
|
+
TAIL_LINES = 10
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
|
|
29
|
+
"""Folds oversized text and returns (folded_text, was_folded)."""
|
|
30
|
+
if not text:
|
|
31
|
+
return text, False
|
|
32
|
+
from src.format_parsers.ansi import strip_ansi
|
|
33
|
+
text = strip_ansi(text)
|
|
34
|
+
if len(text) <= MAX_UNFOLDED_CHARS:
|
|
35
|
+
return text, False
|
|
36
|
+
|
|
37
|
+
lines = text.splitlines()
|
|
38
|
+
if len(lines) <= MAX_UNFOLDED_LINES:
|
|
39
|
+
return text, False
|
|
40
|
+
|
|
41
|
+
hash8, marker = stash_block(text, source=f"mcp:{tool_name}")
|
|
42
|
+
head = lines[:HEAD_LINES]
|
|
43
|
+
tail = lines[-TAIL_LINES:]
|
|
44
|
+
omitted = len(lines) - (HEAD_LINES + TAIL_LINES)
|
|
45
|
+
|
|
46
|
+
folded_lines = head + [
|
|
47
|
+
f"... [{omitted} lines folded by TokenSafe MCP Proxy] ...",
|
|
48
|
+
] + tail + [marker]
|
|
49
|
+
|
|
50
|
+
return "\n".join(folded_lines), True
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def compact_mcp_response(resp: Dict[str, Any]) -> Dict[str, Any]:
|
|
54
|
+
"""Inspects an MCP JSON-RPC response and compacts tools/call content blocks."""
|
|
55
|
+
if not isinstance(resp, dict):
|
|
56
|
+
return resp
|
|
57
|
+
|
|
58
|
+
result = resp.get("result")
|
|
59
|
+
if not isinstance(result, dict):
|
|
60
|
+
return resp
|
|
61
|
+
|
|
62
|
+
content = result.get("content")
|
|
63
|
+
if not isinstance(content, list):
|
|
64
|
+
return resp
|
|
65
|
+
|
|
66
|
+
modified = False
|
|
67
|
+
new_content = []
|
|
68
|
+
for block in content:
|
|
69
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
70
|
+
raw_text = block.get("text", "")
|
|
71
|
+
folded_text, was_folded = fold_tool_text(raw_text)
|
|
72
|
+
if was_folded:
|
|
73
|
+
new_block = dict(block)
|
|
74
|
+
new_block["text"] = folded_text
|
|
75
|
+
new_content.append(new_block)
|
|
76
|
+
modified = True
|
|
77
|
+
else:
|
|
78
|
+
new_content.append(block)
|
|
79
|
+
else:
|
|
80
|
+
new_content.append(block)
|
|
81
|
+
|
|
82
|
+
if modified:
|
|
83
|
+
new_resp = dict(resp)
|
|
84
|
+
new_result = dict(result)
|
|
85
|
+
new_result["content"] = new_content
|
|
86
|
+
new_resp["result"] = new_result
|
|
87
|
+
return new_resp
|
|
88
|
+
|
|
89
|
+
return resp
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def run_proxy(target_cmd: List[str]):
|
|
93
|
+
"""Runs the stdio proxy bridging sys.stdin/stdout with target_cmd."""
|
|
94
|
+
if not target_cmd:
|
|
95
|
+
sys.stderr.write("TokenSafe MCP Proxy Error: No target command specified.\n")
|
|
96
|
+
sys.exit(1)
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
proc = subprocess.Popen(
|
|
100
|
+
target_cmd,
|
|
101
|
+
stdin=subprocess.PIPE,
|
|
102
|
+
stdout=subprocess.PIPE,
|
|
103
|
+
stderr=sys.stderr,
|
|
104
|
+
bufsize=0,
|
|
105
|
+
)
|
|
106
|
+
except Exception as e:
|
|
107
|
+
sys.stderr.write(f"TokenSafe MCP Proxy Error: Failed to spawn {' '.join(target_cmd)}: {e}\n")
|
|
108
|
+
sys.exit(1)
|
|
109
|
+
|
|
110
|
+
def _forward_stdin():
|
|
111
|
+
try:
|
|
112
|
+
while True:
|
|
113
|
+
line = sys.stdin.readline()
|
|
114
|
+
if not line:
|
|
115
|
+
break
|
|
116
|
+
if proc.stdin and not proc.stdin.closed:
|
|
117
|
+
proc.stdin.write(line.encode("utf-8"))
|
|
118
|
+
proc.stdin.flush()
|
|
119
|
+
except Exception:
|
|
120
|
+
pass
|
|
121
|
+
finally:
|
|
122
|
+
if proc.stdin and not proc.stdin.closed:
|
|
123
|
+
try:
|
|
124
|
+
proc.stdin.close()
|
|
125
|
+
except Exception:
|
|
126
|
+
pass
|
|
127
|
+
|
|
128
|
+
t_in = threading.Thread(target=_forward_stdin, daemon=True)
|
|
129
|
+
t_in.start()
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
while True:
|
|
133
|
+
line_bytes = proc.stdout.readline()
|
|
134
|
+
if not line_bytes:
|
|
135
|
+
break
|
|
136
|
+
line_str = line_bytes.decode("utf-8", errors="replace").strip()
|
|
137
|
+
if not line_str:
|
|
138
|
+
continue
|
|
139
|
+
|
|
140
|
+
# Parse JSON-RPC line
|
|
141
|
+
try:
|
|
142
|
+
msg = json.loads(line_str)
|
|
143
|
+
compacted = compact_mcp_response(msg)
|
|
144
|
+
out_line = json.dumps(compacted, ensure_ascii=False) + "\n"
|
|
145
|
+
except Exception:
|
|
146
|
+
out_line = line_str + "\n"
|
|
147
|
+
|
|
148
|
+
sys.stdout.write(out_line)
|
|
149
|
+
sys.stdout.flush()
|
|
150
|
+
except Exception:
|
|
151
|
+
pass
|
|
152
|
+
finally:
|
|
153
|
+
proc.wait()
|
|
154
|
+
sys.exit(proc.returncode or 0)
|