tokensafe 1.4.7 → 1.4.9
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 +30 -13
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/skills/token-optimizer/SKILL.md +20 -4
- package/src/graph_engine.py +7 -6
- package/src/guard.py +3 -2
- package/src/license_manager.py +32 -19
- package/src/mcp_server.py +75 -4
- package/src/scoped_search.py +197 -0
- package/src/skeletonizer.py +9 -7
- package/src/telemetry_sync.py +2 -2
- package/src/version_checker.py +1 -1
- package/hooks/__pycache__/pre_tool_use.cpython-313.pyc +0 -0
package/hooks/pre_invocation.py
CHANGED
|
@@ -99,7 +99,8 @@ def main():
|
|
|
99
99
|
"target_file": compaction["target_file"],
|
|
100
100
|
"symbol": compaction["symbol"],
|
|
101
101
|
"traits": compaction["traits"],
|
|
102
|
-
"tier": tier
|
|
102
|
+
"tier": tier,
|
|
103
|
+
"model": payload.get("model") or os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
|
|
103
104
|
}
|
|
104
105
|
)
|
|
105
106
|
|
|
@@ -149,7 +150,8 @@ def main():
|
|
|
149
150
|
"turns": invocation_num,
|
|
150
151
|
"total_accum_orig": orig_hist_tokens,
|
|
151
152
|
"read_files": stats.get("read_files_count", 0),
|
|
152
|
-
"edited_files": stats.get("edited_files_count", 0)
|
|
153
|
+
"edited_files": stats.get("edited_files_count", 0),
|
|
154
|
+
"model": payload.get("model") or os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
|
|
153
155
|
}
|
|
154
156
|
)
|
|
155
157
|
|
|
@@ -167,18 +169,33 @@ def main():
|
|
|
167
169
|
}
|
|
168
170
|
})
|
|
169
171
|
|
|
170
|
-
# 3. Protocol Enforcement Reminder (
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
172
|
+
# 3. Adaptive Protocol Enforcement Reminder (Dynamic Deduplication)
|
|
173
|
+
# Injects full directives on initial turns, after history folding, or upon guard violations.
|
|
174
|
+
# Otherwise suppresses repetitive blocks, saving ~60 tokens per invocation.
|
|
175
|
+
recent_guard = tracker.get_last_event(conversation_id, "GUARD_RAW_CODE_SEARCH")
|
|
176
|
+
should_inject_full = (
|
|
177
|
+
invocation_num <= 2 or
|
|
178
|
+
folded_text is not None or
|
|
179
|
+
recent_guard is not None
|
|
178
180
|
)
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
181
|
+
|
|
182
|
+
if should_inject_full:
|
|
183
|
+
protocol_reminder = (
|
|
184
|
+
"[TokenSafe Mandatory Directives]:\n"
|
|
185
|
+
"• Terminal code searches (grep/rg/find on source files) are BLOCKED by TokenSafe Guard.\n"
|
|
186
|
+
"• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'.\n"
|
|
187
|
+
"• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)'.\n"
|
|
188
|
+
"• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
|
|
189
|
+
"• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
|
|
190
|
+
"• Prefer 'edit_file' over 'write_file' for existing files."
|
|
191
|
+
)
|
|
192
|
+
inject_steps.append({
|
|
193
|
+
"ephemeralMessage": protocol_reminder
|
|
194
|
+
})
|
|
195
|
+
elif invocation_num % 5 == 0:
|
|
196
|
+
inject_steps.append({
|
|
197
|
+
"ephemeralMessage": "[Protocol: TokenSafe Active | Use 'tokensafe:scoped_search' & 'smart_read_file']"
|
|
198
|
+
})
|
|
182
199
|
|
|
183
200
|
response = {}
|
|
184
201
|
if inject_steps:
|
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.9",
|
|
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": {
|
|
@@ -24,7 +24,8 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
24
24
|
|
|
25
25
|
2. **SYMBOL & COMPONENT EXTRACTION (`smart_read_file`)**:
|
|
26
26
|
- 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`.
|
|
27
|
-
- **
|
|
27
|
+
- **1-Hop vs Surgical**: By default, `smart_read_file` includes direct 1-hop dependencies so you understand called helper functions without extra tool calls. When you only need the target method for a surgical edit, pass `"include_deps": false` to get pure single-method isolation (-95% tokens).
|
|
28
|
+
- **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -95% tokens).
|
|
28
29
|
|
|
29
30
|
3. **ARCHITECTURE SURVEY BEFORE BROWSING (`get_architecture_graph`)**:
|
|
30
31
|
- Before multi-file exploration or asking where things are located, ALWAYS call `tokensafe:get_architecture_graph(project_path)`.
|
|
@@ -48,6 +49,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
48
49
|
| MCP Tool | Description | Efficiency Impact |
|
|
49
50
|
|---|---|---|
|
|
50
51
|
| `tokensafe:smart_read_file` | Graph-guided AST reader with target `symbol` body retention and 1-hop dependency inlining. | **-85% to -92%** token reduction |
|
|
52
|
+
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase. | **-90% to -95%** vs raw grep/find |
|
|
51
53
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
52
54
|
| `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
|
|
53
55
|
| `tokensafe:sanitize_command` | Intercepts shell commands to strip lockfiles, cap unbounded git logs, and quiet test tracebacks. | Saves **10k-50k tokens** per run |
|
|
@@ -72,18 +74,32 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
72
74
|
```
|
|
73
75
|
*Identifies core architectural hubs and dependency weights before inspecting files.*
|
|
74
76
|
|
|
75
|
-
### 2.
|
|
77
|
+
### 2. Scoped Code & Config Search Workflow
|
|
78
|
+
```json
|
|
79
|
+
{
|
|
80
|
+
"ServerName": "tokensafe",
|
|
81
|
+
"ToolName": "scoped_search",
|
|
82
|
+
"Arguments": {
|
|
83
|
+
"query": "HARDCODED_VERSION",
|
|
84
|
+
"scope": "code"
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
*Locates exact occurrences with file and line references in < 100 tokens, without running raw terminal grep.*
|
|
89
|
+
|
|
90
|
+
### 3. Targeted Symbol Inspection Workflow
|
|
76
91
|
```json
|
|
77
92
|
{
|
|
78
93
|
"ServerName": "tokensafe",
|
|
79
94
|
"ToolName": "smart_read_file",
|
|
80
95
|
"Arguments": {
|
|
81
96
|
"path": "/Users/.../projects/my-app/src/views/StatsView.tsx",
|
|
82
|
-
"symbol": "LuckyWheelTab"
|
|
97
|
+
"symbol": "LuckyWheelTab",
|
|
98
|
+
"include_deps": false
|
|
83
99
|
}
|
|
84
100
|
}
|
|
85
101
|
```
|
|
86
|
-
*Extracts only the `LuckyWheelTab` implementation and
|
|
102
|
+
*Extracts only the targeted `LuckyWheelTab` implementation with inert code and docstrings folded. Omit `include_deps` or set `true` to also inline 1-hop internal dependencies.*
|
|
87
103
|
|
|
88
104
|
### 3. Public API Map Workflow
|
|
89
105
|
```json
|
package/src/graph_engine.py
CHANGED
|
@@ -318,12 +318,12 @@ class CodeGraph:
|
|
|
318
318
|
"one_hop": one_hop
|
|
319
319
|
}
|
|
320
320
|
|
|
321
|
-
def graph_guided_skeletonize(self, full_path: str, target_symbol: Optional[str] = None) -> str:
|
|
321
|
+
def graph_guided_skeletonize(self, full_path: str, target_symbol: Optional[str] = None, include_deps: bool = True) -> str:
|
|
322
322
|
"""
|
|
323
323
|
Surgically folds code based on graph connectivity:
|
|
324
324
|
- target_symbol: Retains FULL function body.
|
|
325
|
-
- 1-hop dependencies:
|
|
326
|
-
- 2-hop / Unrelated functions in the same file: Stripped to AST signatures (ellipsis
|
|
325
|
+
- 1-hop dependencies: Retained if include_deps=True.
|
|
326
|
+
- 2-hop / Unrelated functions in the same file: Stripped to AST signatures (ellipsis).
|
|
327
327
|
Yields up to 90% token reduction without breaking context.
|
|
328
328
|
"""
|
|
329
329
|
try:
|
|
@@ -339,10 +339,11 @@ class CodeGraph:
|
|
|
339
339
|
if not target_symbol:
|
|
340
340
|
return Skeletonizer.skeletonize_code(code, ext)
|
|
341
341
|
|
|
342
|
-
neighborhood = self.get_neighborhood(target_symbol)
|
|
343
342
|
keep_full_names = {target_symbol}
|
|
344
|
-
|
|
345
|
-
|
|
343
|
+
if include_deps:
|
|
344
|
+
neighborhood = self.get_neighborhood(target_symbol)
|
|
345
|
+
for k in neighborhood.get("one_hop", set()):
|
|
346
|
+
keep_full_names.add(k.split("::")[-1])
|
|
346
347
|
|
|
347
348
|
return Skeletonizer.skeletonize_code(code, ext, keep_symbols=keep_full_names)
|
|
348
349
|
|
package/src/guard.py
CHANGED
|
@@ -343,6 +343,7 @@ class TokenSafeGuard:
|
|
|
343
343
|
return (
|
|
344
344
|
f"Raw terminal code search blocked: '{sub_cmd}'. "
|
|
345
345
|
f"TokenSafe Protocol mandates using MCP tools to prevent context window bloat:\n"
|
|
346
|
+
f"• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'\n"
|
|
346
347
|
f"• To inspect definitions/symbols in a file: call 'tokensafe:smart_read_file(path, symbol)'\n"
|
|
347
348
|
f"• To locate God Nodes & architecture: call 'tokensafe:get_architecture_graph(project_path)'\n"
|
|
348
349
|
f"• To inspect project exports & types: call 'tokensafe:get_api_surface(project_path)'"
|
|
@@ -356,8 +357,8 @@ class TokenSafeGuard:
|
|
|
356
357
|
if has_code_ext or has_code_dir:
|
|
357
358
|
return (
|
|
358
359
|
f"Raw file crawl via 'find' blocked: '{sub_cmd}'. "
|
|
359
|
-
f"Use 'tokensafe:get_architecture_graph(project_path)'
|
|
360
|
-
f"
|
|
360
|
+
f"Use 'tokensafe:scoped_search(query)' or 'tokensafe:get_architecture_graph(project_path)' "
|
|
361
|
+
f"instead of scanning directory trees."
|
|
361
362
|
)
|
|
362
363
|
|
|
363
364
|
return None
|
package/src/license_manager.py
CHANGED
|
@@ -16,6 +16,8 @@ from typing import Dict, Any, Tuple, Optional
|
|
|
16
16
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
17
17
|
DATA_DIR = os.path.join(PROJECT_ROOT, "data")
|
|
18
18
|
LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
|
|
19
|
+
GLOBAL_DATA_DIR = os.path.expanduser("~/.tokensafe")
|
|
20
|
+
GLOBAL_LICENSE_FILE = os.path.join(GLOBAL_DATA_DIR, "license.json")
|
|
19
21
|
|
|
20
22
|
# Master Public Key for client-side offline verification (RFC 8032 Ed25519)
|
|
21
23
|
DEFAULT_ED25519_PUBLIC_KEY = os.environ.get("TOKENSAFE_PUBLIC_KEY", "3911e2ffe5ad07ee23be392b88f238af302f9d3a0bf51881de8b5e0e6af71430")
|
|
@@ -276,34 +278,45 @@ class LicenseManager:
|
|
|
276
278
|
|
|
277
279
|
@classmethod
|
|
278
280
|
def get_active_license_key(cls) -> str:
|
|
279
|
-
"""Retrieves active raw license key string from env or
|
|
281
|
+
"""Retrieves active raw license key string from env or persistent license.json files."""
|
|
280
282
|
key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
|
|
281
|
-
if not key
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
283
|
+
if not key:
|
|
284
|
+
for p in (LICENSE_FILE, GLOBAL_LICENSE_FILE):
|
|
285
|
+
if os.path.exists(p):
|
|
286
|
+
try:
|
|
287
|
+
with open(p, "r", encoding="utf-8") as f:
|
|
288
|
+
data = json.load(f)
|
|
289
|
+
candidate = data.get("license_key", "").strip()
|
|
290
|
+
if candidate:
|
|
291
|
+
key = candidate
|
|
292
|
+
break
|
|
293
|
+
except Exception:
|
|
294
|
+
pass
|
|
288
295
|
return key
|
|
289
296
|
|
|
290
297
|
@classmethod
|
|
291
298
|
def save_license(cls, license_key: str) -> Tuple[bool, str]:
|
|
292
|
-
"""Saves a verified license key to local persistent storage."""
|
|
299
|
+
"""Saves a verified license key to local and user global persistent storage."""
|
|
293
300
|
valid, payload, msg = cls.validate_license(license_key)
|
|
294
301
|
if not valid:
|
|
295
302
|
return False, f"Cannot save invalid license: {msg}"
|
|
296
303
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
304
|
+
record = {
|
|
305
|
+
"license_key": license_key,
|
|
306
|
+
"tier": payload.get("tier"),
|
|
307
|
+
"email": payload.get("email"),
|
|
308
|
+
"expires_at": payload.get("expires_at"),
|
|
309
|
+
"trial": payload.get("trial", False),
|
|
310
|
+
"saved_at": int(time.time())
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
for target_dir, target_file in ((DATA_DIR, LICENSE_FILE), (GLOBAL_DATA_DIR, GLOBAL_LICENSE_FILE)):
|
|
314
|
+
try:
|
|
315
|
+
os.makedirs(target_dir, exist_ok=True)
|
|
316
|
+
with open(target_file, "w", encoding="utf-8") as f:
|
|
317
|
+
json.dump(record, f, indent=2)
|
|
318
|
+
except Exception:
|
|
319
|
+
pass
|
|
307
320
|
|
|
308
321
|
tier_name = payload.get("tier", "").upper()
|
|
309
322
|
trial_note = " (7-Day Trial)" if payload.get("trial") else ""
|
package/src/mcp_server.py
CHANGED
|
@@ -28,10 +28,11 @@ from src.tokenizer import count_tokens
|
|
|
28
28
|
from src.agent_firewall import AgentFirewall
|
|
29
29
|
from src.diff_slicer import DiffSlicer
|
|
30
30
|
from src.guard import TokenSafeGuard
|
|
31
|
+
from src.scoped_search import ScopedSearch
|
|
31
32
|
|
|
32
33
|
SERVER_INFO = {
|
|
33
34
|
"name": "tokensafe-mcp",
|
|
34
|
-
"version": "1.4.
|
|
35
|
+
"version": "1.4.9"
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
TOOLS = [
|
|
@@ -43,6 +44,7 @@ TOOLS = [
|
|
|
43
44
|
"properties": {
|
|
44
45
|
"path": {"type": "string", "description": "Absolute path to the code file"},
|
|
45
46
|
"symbol": {"type": "string", "description": "Optional: targeted function or class name for graph-guided skeletonization"},
|
|
47
|
+
"include_deps": {"type": "boolean", "description": "Optional: whether to include 1-hop dependencies in full (default: true). Set false for single-symbol surgical isolation."},
|
|
46
48
|
"start_line": {"type": "integer", "description": "Optional: starting line number"},
|
|
47
49
|
"end_line": {"type": "integer", "description": "Optional: ending line number"}
|
|
48
50
|
},
|
|
@@ -135,6 +137,41 @@ TOOLS = [
|
|
|
135
137
|
},
|
|
136
138
|
"required": ["path"]
|
|
137
139
|
}
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
"name": "scoped_search",
|
|
143
|
+
"description": "Safe, token-bounded symbol and text search across the codebase. Replaces raw grep/find with clean, line-numbered markdown matches (-90% tokens).",
|
|
144
|
+
"inputSchema": {
|
|
145
|
+
"type": "object",
|
|
146
|
+
"properties": {
|
|
147
|
+
"query": {
|
|
148
|
+
"type": "string",
|
|
149
|
+
"description": "Text, identifier, or symbol name to search for"
|
|
150
|
+
},
|
|
151
|
+
"scope": {
|
|
152
|
+
"type": "string",
|
|
153
|
+
"enum": ["code", "config", "all"],
|
|
154
|
+
"description": "Scope of search: 'code' (source files only), 'config' (json, toml, yaml), or 'all' (default: 'all')"
|
|
155
|
+
},
|
|
156
|
+
"project_path": {
|
|
157
|
+
"type": "string",
|
|
158
|
+
"description": "Optional root directory path (defaults to current project)"
|
|
159
|
+
},
|
|
160
|
+
"max_results": {
|
|
161
|
+
"type": "integer",
|
|
162
|
+
"description": "Maximum matching lines to return (default: 25, max: 100)"
|
|
163
|
+
},
|
|
164
|
+
"case_sensitive": {
|
|
165
|
+
"type": "boolean",
|
|
166
|
+
"description": "Whether search is case-sensitive (default: false)"
|
|
167
|
+
},
|
|
168
|
+
"use_regex": {
|
|
169
|
+
"type": "boolean",
|
|
170
|
+
"description": "Whether query is a regular expression (default: false)"
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
"required": ["query"]
|
|
174
|
+
}
|
|
138
175
|
}
|
|
139
176
|
]
|
|
140
177
|
|
|
@@ -311,7 +348,8 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
311
348
|
if symbol:
|
|
312
349
|
try:
|
|
313
350
|
graph, rel_path = GraphEngine.for_file(path)
|
|
314
|
-
|
|
351
|
+
inc_deps = bool(args.get("include_deps", True))
|
|
352
|
+
graph_skel = graph.graph_guided_skeletonize(path, target_symbol=symbol, include_deps=inc_deps)
|
|
315
353
|
if graph_skel:
|
|
316
354
|
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
317
355
|
raw_code = f.read()
|
|
@@ -323,9 +361,10 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
323
361
|
event_type="GRAPH_SKELETON",
|
|
324
362
|
original_tokens=orig_t,
|
|
325
363
|
optimized_tokens=skel_t,
|
|
326
|
-
details={"file": os.path.basename(path), "symbol": symbol, "saved_tokens": saved}
|
|
364
|
+
details={"file": os.path.basename(path), "symbol": symbol, "saved_tokens": saved, "include_deps": inc_deps}
|
|
327
365
|
)
|
|
328
|
-
|
|
366
|
+
dep_label = "Full body + 1-hop dependencies" if inc_deps else "Surgical single-symbol isolation"
|
|
367
|
+
header = f"// [TokenSafe Graph-Guided Skeleton for '{symbol}' | {dep_label}]\n"
|
|
329
368
|
return {"content": [{"type": "text", "text": (prefetch_block or "") + header + graph_skel}]}
|
|
330
369
|
except Exception:
|
|
331
370
|
pass
|
|
@@ -546,6 +585,38 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
546
585
|
)
|
|
547
586
|
return {"content": [{"type": "text", "text": tree_output}]}
|
|
548
587
|
|
|
588
|
+
elif name == "scoped_search":
|
|
589
|
+
query = args.get("query", "")
|
|
590
|
+
if not query:
|
|
591
|
+
return {"isError": True, "content": [{"type": "text", "text": "Error: 'query' argument is required for scoped_search."}]}
|
|
592
|
+
|
|
593
|
+
scope = args.get("scope", "all")
|
|
594
|
+
p_path = args.get("project_path", "")
|
|
595
|
+
target_path = os.path.abspath(p_path) if p_path else os.getcwd()
|
|
596
|
+
max_res = args.get("max_results", 25)
|
|
597
|
+
c_sens = bool(args.get("case_sensitive", False))
|
|
598
|
+
u_regex = bool(args.get("use_regex", False))
|
|
599
|
+
|
|
600
|
+
res = ScopedSearch.search(
|
|
601
|
+
query=query,
|
|
602
|
+
project_path=target_path,
|
|
603
|
+
scope=scope,
|
|
604
|
+
max_results=max_res,
|
|
605
|
+
case_sensitive=c_sens,
|
|
606
|
+
use_regex=u_regex
|
|
607
|
+
)
|
|
608
|
+
md_text = res["markdown"]
|
|
609
|
+
res_tokens = count_tokens(md_text)
|
|
610
|
+
est_orig = max(1500, res_tokens * 8)
|
|
611
|
+
tracker.record_event(
|
|
612
|
+
session_id="mcp_session",
|
|
613
|
+
event_type="SCOPED_SEARCH",
|
|
614
|
+
original_tokens=est_orig,
|
|
615
|
+
optimized_tokens=res_tokens,
|
|
616
|
+
details={"query": query, "scope": scope, "matches": res["total_matches"]}
|
|
617
|
+
)
|
|
618
|
+
return {"content": [{"type": "text", "text": md_text}]}
|
|
619
|
+
|
|
549
620
|
return {"isError": True, "content": [{"type": "text", "text": f"Unknown tool: {name}"}]}
|
|
550
621
|
|
|
551
622
|
def run_mcp_server():
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Scoped Search Engine.
|
|
3
|
+
High-efficiency, token-bounded symbol and text search across codebases.
|
|
4
|
+
Replaces uncontrolled grep/find commands with bounded, clean, token-efficient results.
|
|
5
|
+
"""
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import fnmatch
|
|
9
|
+
from typing import Dict, List, Optional, Any, Tuple
|
|
10
|
+
|
|
11
|
+
IGNORED_DIRS = {
|
|
12
|
+
".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
|
|
13
|
+
".next", ".turbo", ".idea", ".vscode", "coverage", ".pytest_cache",
|
|
14
|
+
".mypy_cache", ".gemini", ".system_generated", "data", "tokensafe.egg-info"
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
IGNORED_EXTENSIONS = {
|
|
18
|
+
".pyc", ".pyo", ".pyd", ".so", ".dll", ".dylib", ".exe", ".bin",
|
|
19
|
+
".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".svg",
|
|
20
|
+
".woff", ".woff2", ".ttf", ".eot", ".mp4", ".mp3", ".wav",
|
|
21
|
+
".zip", ".tar", ".gz", ".tgz", ".whl", ".jar", ".db", ".sqlite",
|
|
22
|
+
".sqlite3", ".wasm"
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
LOCKFILES = {
|
|
26
|
+
"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock",
|
|
27
|
+
"Pipfile.lock", "composer.lock", "Cargo.lock", "flake.lock"
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
CODE_EXTENSIONS = {
|
|
31
|
+
".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
|
|
32
|
+
".py", ".pyw", ".go", ".rs", ".java", ".cpp", ".cc", ".c", ".h", ".hpp",
|
|
33
|
+
".php", ".rb", ".vue", ".svelte", ".swift", ".kt", ".kts", ".cs", ".scala",
|
|
34
|
+
".sh", ".bash", ".zsh"
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
CONFIG_EXTENSIONS = {
|
|
38
|
+
".json", ".toml", ".yaml", ".yml", ".ini", ".conf", ".cfg", ".xml"
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
CONFIG_FILENAMES = {
|
|
42
|
+
"package.json", "pyproject.toml", "plugin.json", "tsconfig.json",
|
|
43
|
+
"dockerfile", "dockerfile.cloud", "docker-compose.yml", ".env.example",
|
|
44
|
+
"vite.config.ts", "vite.config.js", "next.config.js", "webpack.config.js"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ScopedSearch:
|
|
49
|
+
"""Safe, bounded search engine replacing terminal grep/find."""
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def is_match_file(cls, filename: str, rel_path: str, scope: str) -> bool:
|
|
53
|
+
"""Determines if a file matches the target search scope."""
|
|
54
|
+
basename = os.path.basename(filename)
|
|
55
|
+
lower_base = basename.lower()
|
|
56
|
+
ext = os.path.splitext(filename)[1].lower()
|
|
57
|
+
|
|
58
|
+
# Reject binary / lockfiles
|
|
59
|
+
if ext in IGNORED_EXTENSIONS or lower_base in LOCKFILES:
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
if scope == "code":
|
|
63
|
+
return ext in CODE_EXTENSIONS
|
|
64
|
+
elif scope == "config":
|
|
65
|
+
return lower_base in CONFIG_FILENAMES or ext in CONFIG_EXTENSIONS
|
|
66
|
+
elif scope == "all":
|
|
67
|
+
return True
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def search(
|
|
72
|
+
cls,
|
|
73
|
+
query: str,
|
|
74
|
+
project_path: Optional[str] = None,
|
|
75
|
+
scope: str = "all",
|
|
76
|
+
max_results: int = 25,
|
|
77
|
+
case_sensitive: bool = False,
|
|
78
|
+
use_regex: bool = False
|
|
79
|
+
) -> Dict[str, Any]:
|
|
80
|
+
"""
|
|
81
|
+
Executes a bounded code/config search and returns structured results and compact markdown.
|
|
82
|
+
"""
|
|
83
|
+
if not query or not query.strip():
|
|
84
|
+
return {
|
|
85
|
+
"success": False,
|
|
86
|
+
"error": "Query string cannot be empty",
|
|
87
|
+
"matches": [],
|
|
88
|
+
"total_matches": 0,
|
|
89
|
+
"markdown": "No search query provided."
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
root_dir = os.path.abspath(project_path or os.getcwd())
|
|
93
|
+
if not os.path.isdir(root_dir):
|
|
94
|
+
return {
|
|
95
|
+
"success": False,
|
|
96
|
+
"error": f"Invalid project path: {root_dir}",
|
|
97
|
+
"matches": [],
|
|
98
|
+
"total_matches": 0,
|
|
99
|
+
"markdown": f"Invalid project path: {root_dir}"
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
query = query.strip()
|
|
103
|
+
scope = (scope or "all").lower().strip()
|
|
104
|
+
max_results = min(100, max(1, int(max_results)))
|
|
105
|
+
|
|
106
|
+
# Compile search pattern
|
|
107
|
+
flags = 0 if case_sensitive else re.IGNORECASE
|
|
108
|
+
try:
|
|
109
|
+
if use_regex:
|
|
110
|
+
pattern = re.compile(query, flags)
|
|
111
|
+
else:
|
|
112
|
+
pattern = re.compile(re.escape(query), flags)
|
|
113
|
+
except Exception as e:
|
|
114
|
+
return {
|
|
115
|
+
"success": False,
|
|
116
|
+
"error": f"Invalid regex pattern: {str(e)}",
|
|
117
|
+
"matches": [],
|
|
118
|
+
"total_matches": 0,
|
|
119
|
+
"markdown": f"Regex compilation error: {str(e)}"
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
matches: List[Dict[str, Any]] = []
|
|
123
|
+
total_scanned_files = 0
|
|
124
|
+
hit_files = set()
|
|
125
|
+
|
|
126
|
+
for dirpath, dirnames, filenames in os.walk(root_dir):
|
|
127
|
+
# Prune ignored directories in-place
|
|
128
|
+
dirnames[:] = [
|
|
129
|
+
d for d in dirnames
|
|
130
|
+
if d not in IGNORED_DIRS and not d.startswith(".")
|
|
131
|
+
]
|
|
132
|
+
|
|
133
|
+
for fname in filenames:
|
|
134
|
+
full_path = os.path.join(dirpath, fname)
|
|
135
|
+
rel_path = os.path.relpath(full_path, root_dir).replace("\\", "/")
|
|
136
|
+
|
|
137
|
+
if not cls.is_match_file(fname, rel_path, scope):
|
|
138
|
+
continue
|
|
139
|
+
|
|
140
|
+
# Skip files larger than 1MB to prevent memory exhaustion
|
|
141
|
+
try:
|
|
142
|
+
if os.path.getsize(full_path) > 1024 * 1024:
|
|
143
|
+
continue
|
|
144
|
+
except OSError:
|
|
145
|
+
continue
|
|
146
|
+
|
|
147
|
+
total_scanned_files += 1
|
|
148
|
+
|
|
149
|
+
try:
|
|
150
|
+
with open(full_path, "r", encoding="utf-8", errors="replace") as f:
|
|
151
|
+
for line_idx, line in enumerate(f, 1):
|
|
152
|
+
if pattern.search(line):
|
|
153
|
+
clean_line = line.strip()
|
|
154
|
+
# Truncate long lines to 100 characters for compact token output
|
|
155
|
+
if len(clean_line) > 100:
|
|
156
|
+
clean_line = clean_line[:97] + "..."
|
|
157
|
+
|
|
158
|
+
matches.append({
|
|
159
|
+
"file": rel_path,
|
|
160
|
+
"line": line_idx,
|
|
161
|
+
"text": clean_line
|
|
162
|
+
})
|
|
163
|
+
hit_files.add(rel_path)
|
|
164
|
+
|
|
165
|
+
if len(matches) >= max_results:
|
|
166
|
+
break
|
|
167
|
+
except Exception:
|
|
168
|
+
continue
|
|
169
|
+
|
|
170
|
+
if len(matches) >= max_results:
|
|
171
|
+
break
|
|
172
|
+
if len(matches) >= max_results:
|
|
173
|
+
break
|
|
174
|
+
|
|
175
|
+
# Generate ultra-compact Markdown output (< 150 tokens)
|
|
176
|
+
lines = [
|
|
177
|
+
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})"
|
|
178
|
+
]
|
|
179
|
+
if not matches:
|
|
180
|
+
lines.append(f"_No matches found across {total_scanned_files} scanned files._")
|
|
181
|
+
else:
|
|
182
|
+
for m in matches:
|
|
183
|
+
lines.append(f"- `{m['file']}:{m['line']}`: `{m['text']}`")
|
|
184
|
+
|
|
185
|
+
if len(matches) >= max_results:
|
|
186
|
+
lines.append(f"_Results capped at {max_results} matches._")
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
"success": True,
|
|
190
|
+
"query": query,
|
|
191
|
+
"scope": scope,
|
|
192
|
+
"total_matches": len(matches),
|
|
193
|
+
"files_matched": len(hit_files),
|
|
194
|
+
"scanned_files": total_scanned_files,
|
|
195
|
+
"matches": matches,
|
|
196
|
+
"markdown": "\n".join(lines)
|
|
197
|
+
}
|
package/src/skeletonizer.py
CHANGED
|
@@ -129,19 +129,21 @@ class Skeletonizer:
|
|
|
129
129
|
|
|
130
130
|
@classmethod
|
|
131
131
|
def _skeletonize_python(cls, code: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
|
132
|
-
"""Uses Python standard library `ast` to fold function bodies."""
|
|
132
|
+
"""Uses Python standard library `ast` to fold function bodies cleanly."""
|
|
133
133
|
try:
|
|
134
134
|
tree = ast.parse(code)
|
|
135
|
+
# When targeting specific symbols, condense verbose module docstring to 1 line
|
|
136
|
+
if keep_symbols and tree.body and isinstance(tree.body[0], ast.Expr) and isinstance(tree.body[0].value, ast.Constant):
|
|
137
|
+
doc_val = str(tree.body[0].value.value)
|
|
138
|
+
first_line = doc_val.strip().split("\n")[0].strip()
|
|
139
|
+
tree.body[0].value.value = f"{first_line} ..."
|
|
140
|
+
|
|
135
141
|
for node in ast.walk(tree):
|
|
136
142
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
137
143
|
if keep_symbols is not None and node.name in keep_symbols:
|
|
138
144
|
continue
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
if doc:
|
|
142
|
-
new_body.append(ast.Expr(value=ast.Constant(value=doc)))
|
|
143
|
-
new_body.append(ast.Expr(value=ast.Constant(value=Ellipsis)))
|
|
144
|
-
node.body = new_body
|
|
145
|
+
# Fold inert functions to pure ellipsis without verbose docstrings
|
|
146
|
+
node.body = [ast.Expr(value=ast.Constant(value=Ellipsis))]
|
|
145
147
|
return ast.unparse(tree)
|
|
146
148
|
except Exception:
|
|
147
149
|
return code
|
package/src/telemetry_sync.py
CHANGED
|
@@ -215,7 +215,7 @@ class TelemetrySync:
|
|
|
215
215
|
except Exception:
|
|
216
216
|
ts_int = int(time.time())
|
|
217
217
|
|
|
218
|
-
model_name = "
|
|
218
|
+
model_name = os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
|
|
219
219
|
if r["details"]:
|
|
220
220
|
try:
|
|
221
221
|
det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
|
|
@@ -236,7 +236,7 @@ class TelemetrySync:
|
|
|
236
236
|
total_sent = 0
|
|
237
237
|
headers = {
|
|
238
238
|
"Content-Type": "application/json",
|
|
239
|
-
"User-Agent": "TokenSafe-Sync/1.4.
|
|
239
|
+
"User-Agent": "TokenSafe-Sync/1.4.9"
|
|
240
240
|
}
|
|
241
241
|
if active_key:
|
|
242
242
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -16,7 +16,7 @@ import urllib.request
|
|
|
16
16
|
import urllib.error
|
|
17
17
|
from typing import Dict, Any, Optional, Tuple
|
|
18
18
|
|
|
19
|
-
CURRENT_VERSION = "1.4.
|
|
19
|
+
CURRENT_VERSION = "1.4.9"
|
|
20
20
|
CACHE_TTL = 86400 # 24 hours
|
|
21
21
|
|
|
22
22
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
Binary file
|