tokensafe 1.4.0 → 1.4.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/package.json +1 -1
- package/plugin.json +1 -1
- package/skills/token-optimizer/SKILL.md +17 -0
- package/src/cli.py +50 -0
- package/src/guard.py +2 -1
- package/src/mcp_server.py +98 -1
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.1",
|
|
5
5
|
"description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
|
@@ -53,6 +53,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
53
53
|
| `tokensafe:sanitize_command` | Intercepts shell commands to strip lockfiles, cap unbounded git logs, and quiet test tracebacks. | Saves **10k-50k tokens** per run |
|
|
54
54
|
| `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
|
|
55
55
|
| `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
|
|
56
|
+
| `tokensafe:guard_inspect` | Pre-flight security & hygiene audit for commands or code snippets (secrets, TLS, SQLi, raw grep). | **Zero-Risk** pre-flight gate |
|
|
56
57
|
| `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved, context ratio, USD value, and optimization source breakdown. | Persistent SQLite analytics |
|
|
57
58
|
|
|
58
59
|
---
|
|
@@ -96,6 +97,20 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
96
97
|
```
|
|
97
98
|
*Returns all exported interfaces and types without reading hundreds of module files.*
|
|
98
99
|
|
|
100
|
+
### 4. Pre-flight Security & Hygiene Audit
|
|
101
|
+
```json
|
|
102
|
+
{
|
|
103
|
+
"ServerName": "tokensafe",
|
|
104
|
+
"ToolName": "guard_inspect",
|
|
105
|
+
"Arguments": {
|
|
106
|
+
"command": "git add .env",
|
|
107
|
+
"code": "const key = process.env.JWT_SECRET || 'hardcoded_secret';",
|
|
108
|
+
"file_path": "src/auth.ts"
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
*Validates commands and code snippets before execution; returns structured pass/block verdict with check_name.*
|
|
113
|
+
|
|
99
114
|
---
|
|
100
115
|
|
|
101
116
|
## Security & Hygiene Engine (TokenSafe Guard)
|
|
@@ -152,6 +167,8 @@ tokensafe install --all # Automatically configure all 9 detected agent env
|
|
|
152
167
|
tokensafe update # One-click self-update & multi-agent re-synchronization
|
|
153
168
|
|
|
154
169
|
# System Health & Hygiene
|
|
170
|
+
tokensafe guard "<command>" # Pre-flight check command safety (rm, secrets, grep)
|
|
171
|
+
tokensafe guard audit [path] # Recursively audit project files for security violations
|
|
155
172
|
tokensafe doctor # Audit MCP tool overhead and token tax
|
|
156
173
|
tokensafe prune # Compact metrics database and prune old events
|
|
157
174
|
tokensafe vacuum # Reclaim SQLite database disk space
|
package/src/cli.py
CHANGED
|
@@ -73,6 +73,56 @@ def main():
|
|
|
73
73
|
from src.installer import AgentInstaller
|
|
74
74
|
AgentInstaller.self_update()
|
|
75
75
|
|
|
76
|
+
elif command in ("guard", "security"):
|
|
77
|
+
from src.guard import TokenSafeGuard
|
|
78
|
+
sub = args[1] if len(args) > 1 else "help"
|
|
79
|
+
if sub in ("audit", "scan"):
|
|
80
|
+
target_path = args[2] if len(args) > 2 else os.getcwd()
|
|
81
|
+
print(f"\n\033[1m\033[36m🛡️ TOKENSAFE SECURITY & HYGIENE AUDIT 🛡️\033[0m")
|
|
82
|
+
print(f" Target: {target_path}\n")
|
|
83
|
+
violations = []
|
|
84
|
+
files_scanned = 0
|
|
85
|
+
code_exts = (".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java")
|
|
86
|
+
for root, dirs, files in os.walk(target_path):
|
|
87
|
+
dirs[:] = [d for d in dirs if d not in (".git", "node_modules", "dist", "build", ".next", ".venv", "venv", "__pycache__")]
|
|
88
|
+
for f in files:
|
|
89
|
+
if f.endswith(code_exts):
|
|
90
|
+
files_scanned += 1
|
|
91
|
+
full_p = os.path.join(root, f)
|
|
92
|
+
try:
|
|
93
|
+
with open(full_p, "r", encoding="utf-8", errors="replace") as fp:
|
|
94
|
+
content = fp.read()
|
|
95
|
+
res = TokenSafeGuard.inspect_file_write(full_p, content)
|
|
96
|
+
if res.blocked:
|
|
97
|
+
rel_p = os.path.relpath(full_p, target_path)
|
|
98
|
+
violations.append((rel_p, res.check_name, res.reason))
|
|
99
|
+
except Exception:
|
|
100
|
+
pass
|
|
101
|
+
if not violations:
|
|
102
|
+
print(f" \033[32m✔ All {files_scanned} files passed TokenSafe Guard audit cleanly! Zero secret fallbacks or SQLi.\033[0m\n")
|
|
103
|
+
else:
|
|
104
|
+
print(f" \033[31m✖ Found {len(violations)} security violations in {files_scanned} files:\033[0m\n")
|
|
105
|
+
for rel_p, check, reason in violations:
|
|
106
|
+
print(f" \033[31m• [{check}]\033[0m {rel_p}: {reason}")
|
|
107
|
+
print()
|
|
108
|
+
elif sub in ("check", "test") or len(args) > 1:
|
|
109
|
+
cmd_to_test = " ".join(args[2:]) if sub in ("check", "test") and len(args) > 2 else " ".join(args[1:])
|
|
110
|
+
print(f"\n\033[1m\033[36m🛡️ TOKENSAFE COMMAND GUARD CHECK 🛡️\033[0m\n")
|
|
111
|
+
print(f" Command: \033[1m{cmd_to_test}\033[0m")
|
|
112
|
+
res = TokenSafeGuard.inspect_command(cmd_to_test)
|
|
113
|
+
if res.blocked:
|
|
114
|
+
print(f" Status: \033[31m\033[1mBLOCKED\033[0m [{res.check_name}]")
|
|
115
|
+
print(f" Reason: {res.reason}\n")
|
|
116
|
+
elif res.warning_only:
|
|
117
|
+
print(f" Status: \033[33m\033[1mWARNING\033[0m [{res.check_name}]")
|
|
118
|
+
print(f" Notice: {res.reason}\n")
|
|
119
|
+
else:
|
|
120
|
+
print(f" Status: \033[32m\033[1mALLOWED\033[0m (Command is safe and policy-compliant)\n")
|
|
121
|
+
else:
|
|
122
|
+
print("\nUsage:")
|
|
123
|
+
print(" tokensafe guard \"<command>\" Audit a terminal command line")
|
|
124
|
+
print(" tokensafe guard audit [path] Recursively audit source files for secrets & vulnerabilities\n")
|
|
125
|
+
|
|
76
126
|
elif command == "proxy":
|
|
77
127
|
from src.proxy import run_proxy
|
|
78
128
|
port = int(args[1]) if len(args) > 1 else 8765
|
package/src/guard.py
CHANGED
|
@@ -75,7 +75,8 @@ class TokenSafeGuard:
|
|
|
75
75
|
|
|
76
76
|
is_test = cls.is_test_file(file_path)
|
|
77
77
|
is_doc = cls.is_doc_file(file_path)
|
|
78
|
-
|
|
78
|
+
is_scanner = bool(file_path and os.path.basename(file_path) in ("guard.py", "secret_redactor.py"))
|
|
79
|
+
skip_code_checks = is_test or is_doc or is_scanner
|
|
79
80
|
|
|
80
81
|
# 1. Secret & Private Key Fallback Guard
|
|
81
82
|
is_leak, leak_reason = SecretRedactor.check_secret_fallback(code_snippet, file_path=file_path)
|
package/src/mcp_server.py
CHANGED
|
@@ -26,10 +26,11 @@ from src.graph_engine import GraphEngine
|
|
|
26
26
|
from src.tokenizer import count_tokens
|
|
27
27
|
from src.agent_firewall import AgentFirewall
|
|
28
28
|
from src.diff_slicer import DiffSlicer
|
|
29
|
+
from src.guard import TokenSafeGuard
|
|
29
30
|
|
|
30
31
|
SERVER_INFO = {
|
|
31
32
|
"name": "tokensafe-mcp",
|
|
32
|
-
"version": "1.4.
|
|
33
|
+
"version": "1.4.1"
|
|
33
34
|
}
|
|
34
35
|
|
|
35
36
|
TOOLS = [
|
|
@@ -108,6 +109,18 @@ TOOLS = [
|
|
|
108
109
|
"type": "object",
|
|
109
110
|
"properties": {}
|
|
110
111
|
}
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
"name": "guard_inspect",
|
|
115
|
+
"description": "Pre-flight security & hygiene audit for commands or code snippets. Detects secret leaks, SQL injection, TLS bypass, CORS wildcard, destructive commands, and raw grep.",
|
|
116
|
+
"inputSchema": {
|
|
117
|
+
"type": "object",
|
|
118
|
+
"properties": {
|
|
119
|
+
"command": {"type": "string", "description": "Optional: Terminal command line to audit"},
|
|
120
|
+
"code": {"type": "string", "description": "Optional: Code snippet, replacement diff, or file content to audit"},
|
|
121
|
+
"file_path": {"type": "string", "description": "Optional: File path being written or modified"}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
111
124
|
}
|
|
112
125
|
]
|
|
113
126
|
|
|
@@ -236,15 +249,99 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
236
249
|
|
|
237
250
|
elif name == "sanitize_command":
|
|
238
251
|
cmd = args.get("command", "")
|
|
252
|
+
# Step 1: TokenSafe Guard security inspection
|
|
253
|
+
guard_res = TokenSafeGuard.inspect_command(cmd)
|
|
254
|
+
if guard_res.blocked:
|
|
255
|
+
tracker.record_event(
|
|
256
|
+
session_id="mcp_session",
|
|
257
|
+
event_type=f"GUARD_{guard_res.check_name}",
|
|
258
|
+
original_tokens=count_tokens(cmd),
|
|
259
|
+
optimized_tokens=0,
|
|
260
|
+
details={"cmd": cmd[:100], "reason": guard_res.reason}
|
|
261
|
+
)
|
|
262
|
+
result = {
|
|
263
|
+
"original_command": cmd,
|
|
264
|
+
"sanitized_command": None,
|
|
265
|
+
"blocked": True,
|
|
266
|
+
"check_name": guard_res.check_name,
|
|
267
|
+
"reason": guard_res.reason,
|
|
268
|
+
"recommendation": "Blocked by TokenSafe Guard. Do not execute this command."
|
|
269
|
+
}
|
|
270
|
+
return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
|
|
271
|
+
|
|
272
|
+
# Step 2: Command sanitization
|
|
239
273
|
new_cmd, saved, reason = CommandSanitizer.sanitize(cmd)
|
|
240
274
|
result = {
|
|
241
275
|
"original_command": cmd,
|
|
242
276
|
"sanitized_command": new_cmd or cmd,
|
|
277
|
+
"blocked": False,
|
|
243
278
|
"tokens_saved": saved,
|
|
244
279
|
"reason": reason or "No modification needed"
|
|
245
280
|
}
|
|
281
|
+
if guard_res.warning_only:
|
|
282
|
+
result["warning"] = guard_res.reason
|
|
246
283
|
return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
|
|
247
284
|
|
|
285
|
+
elif name == "guard_inspect":
|
|
286
|
+
cmd = args.get("command")
|
|
287
|
+
code = args.get("code")
|
|
288
|
+
file_path = args.get("file_path", "")
|
|
289
|
+
|
|
290
|
+
results = []
|
|
291
|
+
if cmd is not None:
|
|
292
|
+
c_res = TokenSafeGuard.inspect_command(cmd)
|
|
293
|
+
results.append({
|
|
294
|
+
"target": "command",
|
|
295
|
+
"input": cmd,
|
|
296
|
+
"allowed": not c_res.blocked,
|
|
297
|
+
"blocked": c_res.blocked,
|
|
298
|
+
"check_name": c_res.check_name,
|
|
299
|
+
"reason": c_res.reason,
|
|
300
|
+
"warning_only": c_res.warning_only
|
|
301
|
+
})
|
|
302
|
+
if c_res.blocked:
|
|
303
|
+
tracker.record_event(
|
|
304
|
+
session_id="mcp_session",
|
|
305
|
+
event_type=f"GUARD_{c_res.check_name}",
|
|
306
|
+
original_tokens=count_tokens(cmd),
|
|
307
|
+
optimized_tokens=0,
|
|
308
|
+
details={"cmd": cmd[:100], "reason": c_res.reason}
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
if code is not None:
|
|
312
|
+
w_res = TokenSafeGuard.inspect_file_write(file_path, code)
|
|
313
|
+
results.append({
|
|
314
|
+
"target": "code",
|
|
315
|
+
"file_path": file_path,
|
|
316
|
+
"allowed": not w_res.blocked,
|
|
317
|
+
"blocked": w_res.blocked,
|
|
318
|
+
"check_name": w_res.check_name,
|
|
319
|
+
"reason": w_res.reason,
|
|
320
|
+
"warning_only": w_res.warning_only
|
|
321
|
+
})
|
|
322
|
+
if w_res.blocked:
|
|
323
|
+
tracker.record_event(
|
|
324
|
+
session_id="mcp_session",
|
|
325
|
+
event_type=f"GUARD_{w_res.check_name}",
|
|
326
|
+
original_tokens=count_tokens(code),
|
|
327
|
+
optimized_tokens=0,
|
|
328
|
+
details={"target_file": os.path.basename(file_path) if file_path else "unknown", "reason": w_res.reason}
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
if not results:
|
|
332
|
+
return {
|
|
333
|
+
"isError": True,
|
|
334
|
+
"content": [{"type": "text", "text": "Error: Please provide 'command' or 'code' (with optional 'file_path') to inspect."}]
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
overall_blocked = any(r["blocked"] for r in results)
|
|
338
|
+
payload = {
|
|
339
|
+
"passed": not overall_blocked,
|
|
340
|
+
"blocked": overall_blocked,
|
|
341
|
+
"checks": results
|
|
342
|
+
}
|
|
343
|
+
return {"content": [{"type": "text", "text": json.dumps(payload, indent=2)}]}
|
|
344
|
+
|
|
248
345
|
elif name == "slice_diff":
|
|
249
346
|
raw_diff = args.get("diff", "")
|
|
250
347
|
max_ctx = int(args.get("max_context", 2))
|