tokensafe 2.8.1 → 2.8.3
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/hooks/pre_invocation.py +8 -0
- package/hooks/pre_tool_use.py +8 -0
- package/hooks/session_start.py +5 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +3 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +14 -2
- package/skills/token-optimizer/references/mcp-tools.md +3 -3
- package/src/adapter_core.py +4 -0
- package/src/command_sanitizer.py +57 -0
- package/src/installer.py +11 -9
- package/src/mcp_server.py +49 -14
- package/src/paths.py +47 -0
- package/src/scoped_search.py +9 -2
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/hooks/pre_invocation.py
CHANGED
|
@@ -64,6 +64,14 @@ def _handle(payload: dict) -> dict:
|
|
|
64
64
|
invocation_num = 1
|
|
65
65
|
transcript_path = str(payload.get("transcriptPath") or "")
|
|
66
66
|
|
|
67
|
+
try:
|
|
68
|
+
from src.paths import save_active_workspace
|
|
69
|
+
raw_ws = payload.get("workspacePaths")
|
|
70
|
+
if raw_ws and isinstance(raw_ws, list) and raw_ws[0]:
|
|
71
|
+
save_active_workspace(str(raw_ws[0]))
|
|
72
|
+
except Exception:
|
|
73
|
+
pass
|
|
74
|
+
|
|
67
75
|
tracker = MetricsTracker()
|
|
68
76
|
inject_steps = []
|
|
69
77
|
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -53,6 +53,14 @@ def _handle(payload: dict) -> dict:
|
|
|
53
53
|
# package.json and Guard audit git staging in the user's repo (never plugin CWD).
|
|
54
54
|
workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
|
|
55
55
|
hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
|
|
56
|
+
try:
|
|
57
|
+
from src.paths import save_active_workspace
|
|
58
|
+
if workspace_paths and workspace_paths[0]:
|
|
59
|
+
save_active_workspace(str(workspace_paths[0]))
|
|
60
|
+
elif hook_cwd:
|
|
61
|
+
save_active_workspace(hook_cwd)
|
|
62
|
+
except Exception:
|
|
63
|
+
pass
|
|
56
64
|
|
|
57
65
|
tracker = MetricsTracker()
|
|
58
66
|
quota = LicenseManager.check_quota(tracker)
|
package/hooks/session_start.py
CHANGED
|
@@ -60,6 +60,11 @@ def main():
|
|
|
60
60
|
raw_ws = payload.get("workspacePaths")
|
|
61
61
|
workspace_paths = raw_ws if isinstance(raw_ws, list) else []
|
|
62
62
|
workspace_root = str(workspace_paths[0]) if workspace_paths else os.getcwd()
|
|
63
|
+
try:
|
|
64
|
+
from src.paths import save_active_workspace
|
|
65
|
+
save_active_workspace(workspace_root)
|
|
66
|
+
except Exception:
|
|
67
|
+
pass
|
|
63
68
|
|
|
64
69
|
inject_steps = [
|
|
65
70
|
{"systemMessage": {"systemMessage": PROTOCOL_DIRECTIVES, "metadata": {}}}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.8.
|
|
4
|
+
"version": "2.8.3",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.8.
|
|
4
|
+
"version": "2.8.3",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/rules/AGENTS.md
CHANGED
|
@@ -24,9 +24,11 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
24
24
|
2. **Surgical Code Edits**: Prefer `edit_file` with concise `Target` and `Replacement` over `write_file` on large existing files.
|
|
25
25
|
3. **Diff-Centric Responses**: Never reprint entire unmodified files or long boilerplate blocks. Reference file lines instead (e.g., `wallet.ts#L42-L50`).
|
|
26
26
|
4. **Dense Formatting**: Use compact bullet points and direct technical prose.
|
|
27
|
+
5. **Repeat Read Deduplication**: Never re-read unchanged files or symbols in the same session. Reuse the skeleton or pointer reference (`// [TokenSafe: Pointer Hit ...]`) returned earlier; only pass `force_full=true` if your context was compacted or you are a fresh subagent.
|
|
28
|
+
6. **Compact Test Output Execution**: Run unit tests with concise flags or via `tokensafe tests [cmd]` so passing test runs return a 1-line summary (`PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full output is preserved only on failure.
|
|
27
29
|
|
|
28
30
|
### 3. Architecture & Code Navigation Directives (Graph-Guided)
|
|
29
|
-
1. **Zero Raw Terminal Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.
|
|
31
|
+
1. **Zero Raw Terminal Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard. To search for text, symbols, or functions across unknown files, ALWAYS call `tokensafe:scoped_search(query, path=".", scope="code")`. The `path` parameter accepts the project root or subfolder (`"."`, `"./src"`), and `scope` accepts file categories (`"code"`, `"config"`, `"all"`), file extensions (`"go"`, `"ts"`), or subfolders (`"internal/promo"`).
|
|
30
32
|
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).
|
|
31
33
|
3. **Architecture Discovery**: Before executing multi-file exploration, ALWAYS call `tokensafe:get_architecture_graph(project_path)` to locate God Nodes and dependency topology in < 250 tokens without file crawling.
|
|
32
34
|
4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
|
|
6
|
-
"version": "2.8.
|
|
6
|
+
"version": "2.8.3",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "2.8.
|
|
33
|
+
"version": "2.8.3",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "2.8.
|
|
49
|
+
"version": "2.8.3",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -18,9 +18,10 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
18
18
|
|
|
19
19
|
## MANDATORY AGENT DIRECTIVES
|
|
20
20
|
|
|
21
|
-
1. **ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED)**:
|
|
21
|
+
1. **ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED & REPLACED BY `scoped_search`)**:
|
|
22
22
|
- Strictly NEVER run `grep`, `egrep`, `ripgrep`, or `find` in `run_command` on source code files (`.ts`, `.tsx`, `.py`, `.js`, `src/`, `views/`, `components/`).
|
|
23
23
|
- Raw code searches via bash burn thousands of context tokens and are blocked by **TokenSafe Guard** (`decision: deny`).
|
|
24
|
+
- **Mandatory Search Tool (`scoped_search`)**: ALWAYS call `tokensafe:scoped_search(query, path=".", scope="code")` to search for text, identifiers, or symbol definitions across unknown files (-90% tokens). The `path` parameter specifies the search directory or project root (e.g. `"."`, `"./src"`). The `scope` parameter filters files (`"code"`, `"config"`, `"all"`), a file extension (`"go"`, `"ts"`), or a subfolder path (`"internal/promo"`).
|
|
24
25
|
|
|
25
26
|
2. **SYMBOL & COMPONENT EXTRACTION (`smart_read_file`)**:
|
|
26
27
|
- When locating or reading any function, component, class, or handler (e.g. `<LuckyWheelTab>`, `areSectorEqual`, `useWallet`), ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`.
|
|
@@ -47,6 +48,17 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
47
48
|
- Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check the window budget (tools/history/prompts breakdown, 50/80/95% thresholds).
|
|
48
49
|
- When it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a State Ledger before continuing — do not let context exhaustion degrade code quality mid-task.
|
|
49
50
|
|
|
51
|
+
8. **REPEAT READ DEDUPLICATION & CACHE POINTERS**:
|
|
52
|
+
- Never repeatedly re-read the same file or symbol within an active session.
|
|
53
|
+
- When `smart_read_file` returns a pointer hit (`// [TokenSafe: Pointer Hit for ...]`), reuse earlier context; pass `"force_full": true` only if your context was compacted or you are a fresh subagent lacking prior turns.
|
|
54
|
+
|
|
55
|
+
9. **ZERO-FLUFF EGRESS & SURGICAL DIFFS**:
|
|
56
|
+
- Eliminate conversational preambles, courtesy fillers, and trailing sign-offs.
|
|
57
|
+
- Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.
|
|
58
|
+
|
|
59
|
+
10. **COMPACT TEST EXECUTION**:
|
|
60
|
+
- Run unit tests with concise flags or via `tokensafe tests [cmd]` so passing test suites emit a single-line summary (`PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full traceback is strictly preserved on failure.
|
|
61
|
+
|
|
50
62
|
---
|
|
51
63
|
|
|
52
64
|
## Core MCP Tools (`tokensafe`)
|
|
@@ -59,7 +71,7 @@ The full tool table with efficiency impact, JSON workflow examples, the Guard ch
|
|
|
59
71
|
|
|
60
72
|
Quick pointers:
|
|
61
73
|
|
|
62
|
-
- Search: `tokensafe:scoped_search(query, scope)` — never raw grep.
|
|
74
|
+
- Search: `tokensafe:scoped_search(query, path=".", scope="code")` — safe keyword & symbol search, never raw grep.
|
|
63
75
|
- Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps.
|
|
64
76
|
- Bundle: `tokensafe:smart_bundle(targets=[{path, symbol}])` — 3-8 related symbols across files in one call, shared imports deduplicated.
|
|
65
77
|
- Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
|
|
@@ -6,7 +6,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
6
6
|
|---|---|---|
|
|
7
7
|
| `tokensafe:smart_read_file` | Graph-guided AST reader with `symbol` body retention, `dep_mode` (`signature` default / `full`), and session pointer dedup (`force_full`). OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced: `symbol` = spec path/model/type/table; empty `symbol` returns a compact overview. | **-90% to -98%** token reduction |
|
|
8
8
|
| `tokensafe:smart_bundle` | Multi-symbol context bundle: up to 8 `{path, symbol}` targets in ONE call — per-file skeletons with shared import lines deduplicated and merged 1-hop dependency signatures. Replaces 3+ chained `smart_read_file` calls. | **-85% to -95%** + one roundtrip instead of many |
|
|
9
|
-
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path`, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
|
|
9
|
+
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path='.'`, `scope='code'`/`'config'`/`'all'`/file extension/subfolder, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
|
|
10
10
|
| `tokensafe:list_dir` | Token-efficient directory tree without lockfiles, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces `ls -la`. | **-90%** vs verbose `ls` |
|
|
11
11
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
12
12
|
| `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
|
|
@@ -41,12 +41,12 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
41
41
|
"ToolName": "scoped_search",
|
|
42
42
|
"Arguments": {
|
|
43
43
|
"query": "HARDCODED_VERSION",
|
|
44
|
-
"path": "
|
|
44
|
+
"path": "./src",
|
|
45
45
|
"scope": "code"
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
48
|
```
|
|
49
|
-
*Locates exact occurrences with file and line references in < 100 tokens. Always pass
|
|
49
|
+
*Locates exact occurrences with file and line references in < 100 tokens. Always pass `path` (defaults to active project root, e.g. ".") and optional `scope` ('code', 'config', 'all', file extension like 'go', or subfolder like 'internal/promo'). Auto-guarded against system roots.*
|
|
50
50
|
|
|
51
51
|
### 2b. Directory Navigation Workflow (`list_dir`)
|
|
52
52
|
```json
|
package/src/adapter_core.py
CHANGED
|
@@ -32,6 +32,10 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
32
32
|
"• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)' "
|
|
33
33
|
"(1-hop deps default to compact signatures via dep_mode='signature'; pass dep_mode='full' only when "
|
|
34
34
|
"dependency bodies are needed, or force_full=true if a cache pointer references content missing from context).\n"
|
|
35
|
+
"• Deduplication & Cache Pointers: Never re-read unchanged files repeatedly; reuse earlier context or pointer references.\n"
|
|
36
|
+
"• Zero-Fluff Egress: Omit conversational filler, courtesy preambles, and wrap-ups. Format responses in dense, technical prose.\n"
|
|
37
|
+
"• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.\n"
|
|
38
|
+
"• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
|
|
35
39
|
"• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
|
|
36
40
|
"• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
|
|
37
41
|
"• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check the context window budget.\n"
|
package/src/command_sanitizer.py
CHANGED
|
@@ -333,6 +333,11 @@ class CommandSanitizer:
|
|
|
333
333
|
if "--tb=" not in stage and "-q" not in cmd_args and "--quiet" not in cmd_args:
|
|
334
334
|
return f"{stage} -q --tb=short", 800, "Applied short traceback to pytest", None
|
|
335
335
|
|
|
336
|
+
# cargo test: quiet test runner by default when not specified
|
|
337
|
+
if cmd_tok == "cargo" and cmd_args[:1] == ["test"]:
|
|
338
|
+
if "--quiet" not in stage and "-q" not in stage and "--" not in stage:
|
|
339
|
+
return f"{stage} -- --quiet", 600, "Applied quiet mode to cargo test", None
|
|
340
|
+
|
|
336
341
|
# test runners: agents block on watch mode
|
|
337
342
|
guard = cls._optimize_test_stage(stage, cwd)
|
|
338
343
|
if guard:
|
|
@@ -594,3 +599,55 @@ class CommandSanitizer:
|
|
|
594
599
|
return None, 0, ""
|
|
595
600
|
|
|
596
601
|
return cls.join_stages(pairs), total_saved, "; ".join(reasons)
|
|
602
|
+
|
|
603
|
+
@classmethod
|
|
604
|
+
def compact_test_output(cls, raw: str, exit_code: int = 0) -> str:
|
|
605
|
+
"""
|
|
606
|
+
Compacts test execution output to prevent context bloating in Messages history.
|
|
607
|
+
- If exit_code != 0: returns full raw output untouched to preserve error context.
|
|
608
|
+
- If exit_code == 0: extracts concise summary lines (e.g. 'PASS: 42 passed in 1.2s')
|
|
609
|
+
discarding repetitive passing test lines.
|
|
610
|
+
"""
|
|
611
|
+
if exit_code != 0 or not raw or not raw.strip():
|
|
612
|
+
return raw
|
|
613
|
+
|
|
614
|
+
lines = [line.strip() for line in raw.splitlines() if line.strip()]
|
|
615
|
+
if not lines:
|
|
616
|
+
return raw
|
|
617
|
+
|
|
618
|
+
# 1. pytest check
|
|
619
|
+
for line in reversed(lines):
|
|
620
|
+
if re.search(r"=\s*(?:[0-9]+\s+passed.*in\s+[\d\.]+s|passed in\s+[\d\.]+s)\s*=", line):
|
|
621
|
+
clean = re.sub(r"^=+\s*|\s*=+$", "", line)
|
|
622
|
+
return f"PASS: {clean}"
|
|
623
|
+
|
|
624
|
+
# 2. unittest check
|
|
625
|
+
ran_line = ""
|
|
626
|
+
for line in lines:
|
|
627
|
+
if line.startswith("Ran ") and " test" in line:
|
|
628
|
+
ran_line = line
|
|
629
|
+
elif line.startswith("OK"):
|
|
630
|
+
return f"PASS: {ran_line or 'all tests passed'} ({line})"
|
|
631
|
+
|
|
632
|
+
# 3. jest / vitest check
|
|
633
|
+
for line in reversed(lines):
|
|
634
|
+
if "Tests:" in line and "passed" in line:
|
|
635
|
+
return f"PASS: {line}"
|
|
636
|
+
if re.search(r"✓.*tests? passed", line):
|
|
637
|
+
return f"PASS: {line}"
|
|
638
|
+
|
|
639
|
+
# 4. cargo test check
|
|
640
|
+
for line in reversed(lines):
|
|
641
|
+
if line.startswith("test result: ok."):
|
|
642
|
+
return f"PASS: {line}"
|
|
643
|
+
|
|
644
|
+
# 5. go test check
|
|
645
|
+
for line in reversed(lines):
|
|
646
|
+
if line.startswith("ok \t") or line.startswith("PASS"):
|
|
647
|
+
return f"PASS: {line}"
|
|
648
|
+
|
|
649
|
+
# Fallback for verbose outputs: if > 12 lines, cap to first line + last line
|
|
650
|
+
if len(lines) > 12:
|
|
651
|
+
return f"PASS: {lines[0]} ... {lines[-1]} (exit code 0)"
|
|
652
|
+
|
|
653
|
+
return raw
|
package/src/installer.py
CHANGED
|
@@ -45,18 +45,20 @@ def _app_data_dir(*parts: str) -> str:
|
|
|
45
45
|
UNIFIED_TOKENSAFE_RULE = (
|
|
46
46
|
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
47
47
|
"Always use `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
|
|
48
|
-
"1. **Zero Raw Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.\n"
|
|
48
|
+
"1. **Zero Raw Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard. To search for text, symbols, or functions across unknown files, ALWAYS call `tokensafe:scoped_search(query, path='.', scope='code')`. The `path` parameter accepts the project root or subfolder (`'.'`), and `scope` accepts categories (`'code'`, `'config'`, `'all'`), extensions (`'go'`, `'ts'`), or subfolders (`'internal/promo'`).\n"
|
|
49
49
|
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).\n"
|
|
50
|
-
"3. **
|
|
51
|
-
"4. **
|
|
52
|
-
"5. **
|
|
53
|
-
"6. **
|
|
54
|
-
"7. **
|
|
55
|
-
"8. **
|
|
56
|
-
"9. **
|
|
50
|
+
"3. **Repeat Read Deduplication**: Never repeatedly re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`); pass `force_full=true` only if context was compacted or you are a fresh subagent.\n"
|
|
51
|
+
"4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler, courtesy preambles, and sign-offs. Provide concise bullet prose. Never reprint full unmodified files or lengthy boilerplate; link to file line ranges (`file.ts#L10-L25`) and output surgical diffs.\n"
|
|
52
|
+
"5. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
|
|
53
|
+
"6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
|
|
54
|
+
"7. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens).\n"
|
|
55
|
+
"8. **Command Sanitization & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests with concise flags or via the `tokensafe tests [cmd]` CLI (compact passing summary `PASS: ...`, full traceback only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
|
|
56
|
+
"9. **Styles & Design Token Preservation**: When inspecting CSS, SCSS, LESS, or Tailwind, `smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors to protect project design integrity.\n"
|
|
57
|
+
"10. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage; when it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` before continuing.\n"
|
|
58
|
+
"11. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
|
|
57
59
|
"Never hardcode real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Whenever a secret fallback attempt is blocked, state:\n"
|
|
58
60
|
"`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
|
|
59
|
-
"
|
|
61
|
+
"12. **Proof-of-Savings Turn Footer (always in English)**:\n"
|
|
60
62
|
"At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
|
|
61
63
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
|
62
64
|
)
|
package/src/mcp_server.py
CHANGED
|
@@ -38,10 +38,11 @@ from src.diff_slicer import DiffSlicer
|
|
|
38
38
|
from src.guard import TokenSafeGuard
|
|
39
39
|
from src.scoped_search import ScopedSearch
|
|
40
40
|
from src.license_manager import LicenseManager
|
|
41
|
+
from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
41
42
|
|
|
42
43
|
SERVER_INFO = {
|
|
43
44
|
"name": "tokensafe-mcp",
|
|
44
|
-
"version": "2.8.
|
|
45
|
+
"version": "2.8.3"
|
|
45
46
|
}
|
|
46
47
|
|
|
47
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -250,12 +251,11 @@ TOOLS = [
|
|
|
250
251
|
},
|
|
251
252
|
"scope": {
|
|
252
253
|
"type": "string",
|
|
253
|
-
"
|
|
254
|
-
"description": "Scope of search: 'code' (source files only), 'config' (json, toml, yaml), or 'all' (default: 'all')"
|
|
254
|
+
"description": "Filter scope: 'code', 'config', 'all', a file extension (e.g. 'go', 'ts', '*.py'), or a subfolder path (e.g. 'internal/promo') (default: 'all')"
|
|
255
255
|
},
|
|
256
256
|
"path": {
|
|
257
257
|
"type": "string",
|
|
258
|
-
"description": "Directory or project path to search (alias for project_path)"
|
|
258
|
+
"description": "Directory or project path to search (alias for project_path, e.g. '.', './src', 'internal/promo')"
|
|
259
259
|
},
|
|
260
260
|
"project_path": {
|
|
261
261
|
"type": "string",
|
|
@@ -399,17 +399,24 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
|
|
|
399
399
|
|
|
400
400
|
def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
401
401
|
"""
|
|
402
|
-
Safely resolves the target project root without falling back to system root dirs.
|
|
402
|
+
Safely resolves the target project root without falling back to system root dirs or plugin dirs.
|
|
403
403
|
"""
|
|
404
404
|
target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory")
|
|
405
|
-
|
|
405
|
+
active_ws = get_active_workspace()
|
|
406
406
|
|
|
407
407
|
if target:
|
|
408
|
-
|
|
408
|
+
if not os.path.isabs(target):
|
|
409
|
+
if active_ws and os.path.isdir(os.path.join(active_ws, target)):
|
|
410
|
+
target_abs = os.path.abspath(os.path.join(active_ws, target))
|
|
411
|
+
else:
|
|
412
|
+
target_abs = os.path.abspath(target)
|
|
413
|
+
else:
|
|
414
|
+
target_abs = os.path.abspath(target)
|
|
415
|
+
|
|
409
416
|
if os.path.isfile(target_abs):
|
|
410
417
|
target_abs = os.path.dirname(target_abs)
|
|
411
|
-
if target_abs
|
|
412
|
-
return None, f"Error: Refusing to scan system root or
|
|
418
|
+
if is_plugin_or_system_dir(target_abs):
|
|
419
|
+
return None, f"Error: Refusing to scan system root or plugin directory '{target}'. Please provide a specific project directory."
|
|
413
420
|
if not os.path.isdir(target_abs):
|
|
414
421
|
return None, f"Error: project_path not found or not a directory: '{target}'."
|
|
415
422
|
return target_abs, None
|
|
@@ -419,14 +426,18 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
|
419
426
|
candidate = os.environ.get(env_var)
|
|
420
427
|
if candidate:
|
|
421
428
|
cand_abs = os.path.abspath(candidate)
|
|
422
|
-
if
|
|
429
|
+
if not is_plugin_or_system_dir(cand_abs) and os.path.isdir(cand_abs):
|
|
423
430
|
return cand_abs, None
|
|
424
431
|
|
|
425
|
-
# Check
|
|
432
|
+
# Check active workspace recorded by lifecycle hooks
|
|
433
|
+
if active_ws and not is_plugin_or_system_dir(active_ws) and os.path.isdir(active_ws):
|
|
434
|
+
return active_ws, None
|
|
435
|
+
|
|
436
|
+
# Check cwd (only if it is not inside an agent plugin or system root directory)
|
|
426
437
|
cwd = os.getcwd()
|
|
427
438
|
if cwd:
|
|
428
439
|
cwd_abs = os.path.abspath(cwd)
|
|
429
|
-
if
|
|
440
|
+
if not is_plugin_or_system_dir(cwd_abs) and os.path.isdir(cwd_abs):
|
|
430
441
|
return cwd_abs, None
|
|
431
442
|
|
|
432
443
|
# Hint with active projects if found under ~/Documents/projects
|
|
@@ -1458,18 +1469,42 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1458
1469
|
if not query:
|
|
1459
1470
|
return _fallback_error("scoped_search", "missing required 'query' argument")
|
|
1460
1471
|
|
|
1461
|
-
|
|
1472
|
+
raw_scope = str(args.get("scope") or "all").strip()
|
|
1462
1473
|
raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
|
|
1474
|
+
active_ws = get_active_workspace()
|
|
1475
|
+
|
|
1476
|
+
# 1. Resolve base directory safely without scanning plugin or system roots
|
|
1463
1477
|
if raw_path:
|
|
1464
|
-
|
|
1478
|
+
if not os.path.isabs(raw_path):
|
|
1479
|
+
if active_ws and os.path.isdir(os.path.join(active_ws, raw_path)):
|
|
1480
|
+
target_path = os.path.abspath(os.path.join(active_ws, raw_path))
|
|
1481
|
+
else:
|
|
1482
|
+
target_path = os.path.abspath(raw_path)
|
|
1483
|
+
else:
|
|
1484
|
+
target_path = os.path.abspath(raw_path)
|
|
1485
|
+
|
|
1465
1486
|
if os.path.isfile(target_path):
|
|
1466
1487
|
target_path = os.path.dirname(target_path)
|
|
1488
|
+
if is_plugin_or_system_dir(target_path):
|
|
1489
|
+
return _fallback_error("scoped_search", f"refusing to search system root or plugin dir '{raw_path}'")
|
|
1467
1490
|
else:
|
|
1468
1491
|
resolved_path, err = _resolve_project_root(args)
|
|
1469
1492
|
if err or not resolved_path:
|
|
1470
1493
|
return _fallback_error("scoped_search", err or "unspecified project_path")
|
|
1471
1494
|
target_path = resolved_path
|
|
1472
1495
|
|
|
1496
|
+
# 2. Smart scope routing: handle agents passing subdirectories or extensions in `scope`
|
|
1497
|
+
scope = raw_scope
|
|
1498
|
+
if raw_scope and raw_scope.lower() not in ("code", "config", "all"):
|
|
1499
|
+
candidate_subdir = os.path.normpath(os.path.join(target_path, raw_scope))
|
|
1500
|
+
if os.path.isdir(candidate_subdir):
|
|
1501
|
+
target_path = candidate_subdir
|
|
1502
|
+
scope = "all"
|
|
1503
|
+
elif "/" in raw_scope or "\\" in raw_scope:
|
|
1504
|
+
if os.path.exists(candidate_subdir):
|
|
1505
|
+
target_path = candidate_subdir
|
|
1506
|
+
scope = "all"
|
|
1507
|
+
|
|
1473
1508
|
max_res = _safe_int(args.get("max_results"), 25, lo=1, hi=100)
|
|
1474
1509
|
c_sens = bool(args.get("case_sensitive", False))
|
|
1475
1510
|
u_regex = bool(args.get("use_regex", False))
|
package/src/paths.py
CHANGED
|
@@ -19,6 +19,7 @@ active directory is identical for every agent on the machine.
|
|
|
19
19
|
import os
|
|
20
20
|
import shutil
|
|
21
21
|
import sqlite3
|
|
22
|
+
from typing import Optional
|
|
22
23
|
|
|
23
24
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
24
25
|
|
|
@@ -110,3 +111,49 @@ def _migrate_into(target: str) -> None:
|
|
|
110
111
|
f.write("1")
|
|
111
112
|
except Exception:
|
|
112
113
|
pass
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def is_plugin_or_system_dir(path: str) -> bool:
|
|
117
|
+
"""Returns True if path is a system root or inside an agent plugin directory."""
|
|
118
|
+
if not path:
|
|
119
|
+
return True
|
|
120
|
+
abs_p = os.path.abspath(path)
|
|
121
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
122
|
+
if abs_p in system_roots:
|
|
123
|
+
return True
|
|
124
|
+
lower = abs_p.lower()
|
|
125
|
+
if any(k in lower for k in (".gemini/config/plugins", "/.tokensafe", "plugins/tokensafe", ".cursor/extensions")):
|
|
126
|
+
return True
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def save_active_workspace(path: str) -> None:
|
|
131
|
+
"""Records the active user workspace directory observed by lifecycle hooks."""
|
|
132
|
+
if not path or not os.path.isabs(path) or not os.path.isdir(path):
|
|
133
|
+
return
|
|
134
|
+
if is_plugin_or_system_dir(path):
|
|
135
|
+
return
|
|
136
|
+
try:
|
|
137
|
+
data_dir = resolve_data_dir()
|
|
138
|
+
os.makedirs(data_dir, exist_ok=True)
|
|
139
|
+
marker = os.path.join(data_dir, ".active_workspace")
|
|
140
|
+
with open(marker, "w", encoding="utf-8") as f:
|
|
141
|
+
f.write(os.path.abspath(path))
|
|
142
|
+
except Exception:
|
|
143
|
+
pass
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def get_active_workspace() -> Optional[str]:
|
|
147
|
+
"""Retrieves the last known active user workspace directory."""
|
|
148
|
+
try:
|
|
149
|
+
data_dir = resolve_data_dir()
|
|
150
|
+
marker = os.path.join(data_dir, ".active_workspace")
|
|
151
|
+
if os.path.isfile(marker):
|
|
152
|
+
with open(marker, "r", encoding="utf-8") as f:
|
|
153
|
+
path = f.read().strip()
|
|
154
|
+
if path and os.path.isabs(path) and os.path.isdir(path):
|
|
155
|
+
if not is_plugin_or_system_dir(path):
|
|
156
|
+
return path
|
|
157
|
+
except Exception:
|
|
158
|
+
pass
|
|
159
|
+
return None
|
package/src/scoped_search.py
CHANGED
|
@@ -69,6 +69,12 @@ class ScopedSearch:
|
|
|
69
69
|
return lower_base in CONFIG_FILENAMES or ext in CONFIG_EXTENSIONS
|
|
70
70
|
elif scope == "all":
|
|
71
71
|
return True
|
|
72
|
+
elif scope.startswith("*."):
|
|
73
|
+
return ext == scope[1:].lower()
|
|
74
|
+
elif scope.startswith("."):
|
|
75
|
+
return ext == scope.lower()
|
|
76
|
+
elif f".{scope}" in CODE_EXTENSIONS or scope in ("go", "py", "ts", "js", "tsx", "jsx", "rs", "java", "cpp", "c", "php", "rb", "swift", "kt", "sql", "html", "css", "json", "yaml", "yml", "toml"):
|
|
77
|
+
return ext == f".{scope}"
|
|
72
78
|
return True
|
|
73
79
|
|
|
74
80
|
@classmethod
|
|
@@ -215,11 +221,12 @@ class ScopedSearch:
|
|
|
215
221
|
break
|
|
216
222
|
|
|
217
223
|
# Generate ultra-compact Markdown output (< 150 tokens)
|
|
224
|
+
display_root = os.path.basename(root_dir) or root_dir
|
|
218
225
|
lines = [
|
|
219
|
-
f"### TokenSafe Scoped Search: '{query}' ({len(matches)} match{'es' if len(matches) != 1 else ''} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, scope: {scope})"
|
|
226
|
+
f"### TokenSafe Scoped Search: '{query}' ({len(matches)} match{'es' if len(matches) != 1 else ''} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, dir: `{display_root}`, scope: {scope})"
|
|
220
227
|
]
|
|
221
228
|
if not matches:
|
|
222
|
-
lines.append(f"_No matches found across {total_scanned_files} scanned files
|
|
229
|
+
lines.append(f"_No matches found across {total_scanned_files} scanned files in `{root_dir}`._")
|
|
223
230
|
else:
|
|
224
231
|
for m in matches:
|
|
225
232
|
lines.append(f"- `{m['file']}:{m['line']}`: `{m['text']}`")
|
package/src/telemetry_sync.py
CHANGED
|
@@ -228,7 +228,7 @@ class TelemetrySync:
|
|
|
228
228
|
current_last_id = last_id
|
|
229
229
|
headers = {
|
|
230
230
|
"Content-Type": "application/json",
|
|
231
|
-
"User-Agent": "TokenSafe-Sync/2.8.
|
|
231
|
+
"User-Agent": "TokenSafe-Sync/2.8.3"
|
|
232
232
|
}
|
|
233
233
|
if active_key:
|
|
234
234
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "2.8.
|
|
20
|
+
CURRENT_VERSION = "2.8.3"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|