tokensafe 4.6.0 → 4.6.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.
@@ -10,7 +10,12 @@ Supported query types:
10
10
  - 'regex': regular expression pattern matching.
11
11
  - 'glob': file name and path pattern matching.
12
12
  - 'fuzzy': case-insensitive fuzzy path and symbol search.
13
- - 'git': read-only git queries (status, diff, log, show, branch, rev-parse, ls-files).
13
+ - 'git': read-only git queries (status, diff, log, show, branch, rev-parse,
14
+ ls-files, blame, shortlog, describe, tag) with writing/escaping flags blocked.
15
+
16
+ `path` may point to a directory or to a single file. A missing path, an
17
+ uncompilable regex, and an unknown `file_type` are reported as per-query
18
+ errors instead of silent zero-hit results.
14
19
  """
15
20
 
16
21
  import os
@@ -36,11 +41,15 @@ ALLOWED_GIT_COMMANDS = {
36
41
  HARDENED_GIT_BASE_ARGS = [
37
42
  "--no-optional-locks",
38
43
  "-c", "core.fsmonitor=false",
44
+ "-c", "core.quotePath=false",
39
45
  "-c", "diff.external=",
40
46
  "-c", "gpg.program=false",
41
- "--no-pager"
47
+ "--no-pager",
42
48
  ]
43
49
 
50
+ # Subcommands that support --no-textconv (a per-command option, not a global one)
51
+ _TEXTCONV_SUBCOMMANDS = frozenset({"diff", "log", "show", "blame"})
52
+
44
53
 
45
54
  def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
46
55
  """Checks if git command is strictly read-only and returns tokens."""
@@ -57,8 +66,15 @@ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
57
66
  if subcmd not in ALLOWED_GIT_COMMANDS:
58
67
  return False, f"Git subcommand '{subcmd}' is not in the read-only allowlist ({', '.join(sorted(ALLOWED_GIT_COMMANDS))}).", []
59
68
 
60
- # Block destructive, config-overriding, or mutating flags
61
- _BLOCKED_GIT_PREFIXES = ("-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output", "--ext-diff", "--exec")
69
+ # Block destructive, config-overriding, escaping, or helper-executing options.
70
+ # --no-index/--contents/--pathspec-from-file read arbitrary files outside the
71
+ # workspace root the MCP handler confines sub-queries to; --textconv runs
72
+ # repo-configured helpers, so it is blocked and --no-textconv is forced below.
73
+ _BLOCKED_GIT_PREFIXES = (
74
+ "-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output",
75
+ "--ext-diff", "--exec", "--no-index", "--contents", "--pathspec-from-file",
76
+ "--textconv",
77
+ )
62
78
  _READ_ONLY_BRANCH_TAG_FLAGS = {
63
79
  "-l", "--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--verbose",
64
80
  "--show-current", "--contains", "--no-contains", "--merged", "--no-merged",
@@ -80,7 +96,7 @@ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
80
96
  return True, "", tokens
81
97
 
82
98
 
83
- def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, Any]:
99
+ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5, max_results: int = 50) -> Dict[str, Any]:
84
100
  """Runs a read-only git query."""
85
101
  is_safe, err_msg, tokens = _is_git_command_safe(pattern)
86
102
  if not is_safe:
@@ -90,15 +106,24 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, An
90
106
  if not git_bin:
91
107
  return {"error": "git executable not found in PATH", "matches": [], "count": 0}
92
108
 
93
- cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
109
+ # --no-textconv is a per-subcommand option (diff/log/show/blame), so it must
110
+ # follow the subcommand, not sit in the global option block.
111
+ if tokens and tokens[0].lower() in _TEXTCONV_SUBCOMMANDS:
112
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, tokens[0], "--no-textconv", *tokens[1:]]
113
+ else:
114
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
115
+
94
116
  env = os.environ.copy()
95
117
  env["GIT_TERMINAL_PROMPT"] = "0"
96
118
  env["GIT_PAGER"] = "cat"
119
+ # Never let git consume the MCP server's own stdin (rev-parse --parseopt blocks on it).
120
+ stdin_devnull = subprocess.DEVNULL
97
121
 
98
122
  try:
99
123
  proc = subprocess.run(
100
124
  cmd,
101
125
  cwd=cwd,
126
+ stdin=stdin_devnull,
102
127
  stdout=subprocess.PIPE,
103
128
  stderr=subprocess.PIPE,
104
129
  text=True,
@@ -111,7 +136,8 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, An
111
136
 
112
137
  raw_out = strip_ansi(proc.stdout or "").strip()
113
138
  lines = [l for l in raw_out.splitlines() if l.strip()]
114
- return {"matches": lines[:50], "count": len(lines), "raw": "\n".join(lines[:50])}
139
+ limited = lines[:max_results]
140
+ return {"matches": limited, "count": len(limited), "raw": "\n".join(limited)}
115
141
  except subprocess.TimeoutExpired:
116
142
  return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
117
143
  except Exception as e:
@@ -159,11 +185,16 @@ def _run_rg_query(
159
185
  proc = subprocess.run(
160
186
  cmd,
161
187
  cwd=cwd,
188
+ stdin=subprocess.DEVNULL,
162
189
  stdout=subprocess.PIPE,
163
190
  stderr=subprocess.PIPE,
164
191
  text=True,
165
192
  timeout=5
166
193
  )
194
+ err_text = (proc.stderr or "").strip()
195
+ # rg exits 1 for "no matches" (not an error) and 2 for real failures.
196
+ if proc.returncode not in (0, 1) and err_text:
197
+ raise RuntimeError(f"ripgrep failed: {err_text.splitlines()[0]}")
167
198
  matches = []
168
199
  _rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
169
200
  for line in proc.stdout.splitlines():
@@ -198,6 +229,37 @@ def _iter_search_files(search_root: str, cwd: str):
198
229
  yield full_path, os.path.relpath(full_path, cwd)
199
230
 
200
231
 
232
+ # Approximation of ripgrep's --type map for the pure-Python fallback, so the
233
+ # file_type filter is not silently ignored when rg is unavailable.
234
+ FILE_TYPE_EXTENSIONS = {
235
+ "typescript": {".ts", ".tsx", ".mts", ".cts"},
236
+ "ts": {".ts", ".tsx", ".mts", ".cts"},
237
+ "javascript": {".js", ".jsx", ".mjs", ".cjs"},
238
+ "js": {".js", ".jsx", ".mjs", ".cjs"},
239
+ "python": {".py", ".pyi"},
240
+ "py": {".py", ".pyi"},
241
+ "rust": {".rs"},
242
+ "go": {".go"},
243
+ "java": {".java"},
244
+ "ruby": {".rb"},
245
+ "php": {".php"},
246
+ "c": {".c", ".h"},
247
+ "cpp": {".cpp", ".cc", ".cxx", ".hpp", ".hh"},
248
+ "csharp": {".cs"},
249
+ "markdown": {".md", ".markdown"},
250
+ "md": {".md", ".markdown"},
251
+ "json": {".json"},
252
+ "yaml": {".yaml", ".yml"},
253
+ "toml": {".toml"},
254
+ "html": {".html", ".htm"},
255
+ "css": {".css", ".scss", ".sass", ".less"},
256
+ "sql": {".sql"},
257
+ "shell": {".sh", ".bash", ".zsh"},
258
+ "swift": {".swift"},
259
+ "kotlin": {".kt", ".kts"},
260
+ }
261
+
262
+
201
263
  def _run_python_text_search(
202
264
  pattern: str,
203
265
  cwd: str,
@@ -206,20 +268,30 @@ def _run_python_text_search(
206
268
  case_sensitive: bool = False,
207
269
  scope: str = "all",
208
270
  glob_filter: Optional[str] = None,
271
+ file_type: Optional[str] = None,
209
272
  max_results: int = 25
210
273
  ) -> List[Dict[str, Any]]:
211
- """Pure Python search fallback."""
274
+ """Pure Python search fallback. Raises ValueError for an unusable regex or file_type."""
212
275
  search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
213
276
  if not os.path.exists(search_root):
214
277
  return []
215
278
 
279
+ type_exts = None
280
+ if file_type:
281
+ type_exts = FILE_TYPE_EXTENSIONS.get(str(file_type).lower().lstrip("."))
282
+ if type_exts is None:
283
+ raise ValueError(
284
+ f"unsupported file_type '{file_type}' (known: {', '.join(sorted(FILE_TYPE_EXTENSIONS))})"
285
+ )
286
+
216
287
  regex = None
217
288
  if is_regex:
218
289
  flags = 0 if case_sensitive else re.IGNORECASE
219
290
  try:
220
291
  regex = re.compile(pattern, flags)
221
- except re.error:
222
- regex = None
292
+ except re.error as e:
293
+ # Never degrade to a literal search: that silently returns bogus hits.
294
+ raise ValueError(f"invalid regular expression: {e}")
223
295
 
224
296
  matches = []
225
297
  target_lower = pattern if case_sensitive else pattern.lower()
@@ -234,6 +306,8 @@ def _run_python_text_search(
234
306
  continue
235
307
  if scope == "code" and ext not in CODE_EXTENSIONS:
236
308
  continue
309
+ if type_exts is not None and ext not in type_exts:
310
+ continue
237
311
  if glob_filter and not (fnmatch.fnmatch(os.path.basename(full_path), glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
238
312
  continue
239
313
 
@@ -312,20 +386,39 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
312
386
  output_mode = str(query_dict.get("output_mode") or "content").lower()
313
387
  file_type = query_dict.get("file_type")
314
388
  glob_filter = query_dict.get("glob")
389
+ scope = str(query_dict.get("scope") or "all").lower()
315
390
 
316
391
  if not pattern and q_type != "git":
317
392
  return {"type": q_type, "pattern": pattern, "error": "Empty pattern.", "matches": [], "count": 0}
318
393
 
394
+ # A path that does not exist must be an explicit error: an empty result list
395
+ # is indistinguishable from a genuine zero-hit search.
396
+ if path_filter:
397
+ search_root = os.path.normpath(os.path.join(cwd, str(path_filter)))
398
+ if not os.path.exists(search_root):
399
+ return {
400
+ "type": q_type,
401
+ "pattern": pattern,
402
+ "error": f"path does not exist: {path_filter}",
403
+ "matches": [],
404
+ "count": 0,
405
+ }
406
+
319
407
  if q_type == "git":
320
- res = _run_git_query(pattern, cwd)
408
+ git_cwd = os.path.normpath(os.path.join(cwd, str(path_filter))) if path_filter else cwd
409
+ res = _run_git_query(pattern, git_cwd, max_results=max_res)
321
410
  return {"type": "git", "pattern": pattern, **res}
322
411
 
323
412
  if q_type == "glob":
324
413
  matched_paths = _run_glob_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
414
+ if output_mode == "count":
415
+ return {"type": "glob", "pattern": pattern, "count": len(matched_paths)}
325
416
  return {"type": "glob", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
326
417
 
327
418
  if q_type == "fuzzy":
328
419
  matched_paths = _run_fuzzy_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
420
+ if output_mode == "count":
421
+ return {"type": "fuzzy", "pattern": pattern, "count": len(matched_paths)}
329
422
  return {"type": "fuzzy", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
330
423
 
331
424
  is_regex = (q_type == "regex")
@@ -341,16 +434,20 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
341
434
  max_results=max_res
342
435
  )
343
436
 
344
- matches = rg_matches if rg_matches is not None else _run_python_text_search(
345
- pattern=pattern,
346
- cwd=cwd,
347
- path_filter=path_filter,
348
- is_regex=is_regex,
349
- case_sensitive=case_sensitive,
350
- scope="all",
351
- glob_filter=glob_filter,
352
- max_results=max_res
353
- )
437
+ try:
438
+ matches = rg_matches if rg_matches is not None else _run_python_text_search(
439
+ pattern=pattern,
440
+ cwd=cwd,
441
+ path_filter=path_filter,
442
+ is_regex=is_regex,
443
+ case_sensitive=case_sensitive,
444
+ scope=scope,
445
+ glob_filter=glob_filter,
446
+ file_type=file_type,
447
+ max_results=max_res
448
+ )
449
+ except ValueError as e:
450
+ return {"type": q_type, "pattern": pattern, "error": str(e), "matches": [], "count": 0}
354
451
 
355
452
  if output_mode == "files_with_matches":
356
453
  unique_files = list(dict.fromkeys(m["file"] for m in matches if isinstance(m, dict) and "file" in m))
@@ -418,11 +515,13 @@ def execute_batch_search(
418
515
  if q_type == "git":
419
516
  raw_git = res.get("raw")
420
517
  if raw_git:
421
- md_lines.append("```text\n" + raw_git[:1200] + "\n```")
518
+ md_lines.append("```text\n" + raw_git + "\n```")
422
519
  elif not matches:
423
520
  md_lines.append("*(clean / no output)*")
424
521
  elif isinstance(matches, list):
425
- for m in matches[:15]:
522
+ # Honor the caller's max_results instead of a fixed 15-item cap;
523
+ # the Zero-Spill Guard folds oversized payloads at the MCP boundary.
524
+ for m in matches:
426
525
  if isinstance(m, dict):
427
526
  f_name = m.get("file", "")
428
527
  l_num = m.get("line", "")
@@ -430,12 +529,11 @@ def execute_batch_search(
430
529
  md_lines.append(f"- `{f_name}:{l_num}`: {content}")
431
530
  elif isinstance(m, str):
432
531
  md_lines.append(f"- `{m}`")
433
- if len(matches) > 15:
434
- md_lines.append(f"- *(+{len(matches) - 15} more matches)*")
435
532
 
436
533
  summary_md = "\n".join(md_lines)
534
+ errored = [r for r in results if isinstance(r, dict) and r.get("error")]
437
535
  return {
438
- "success": True,
536
+ "success": not (errored and len(errored) == len(results)),
439
537
  "query_count": len(queries),
440
538
  "results": results,
441
539
  "summary_md": summary_md
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.6.0"
45
+ "version": "4.6.1"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -1357,19 +1357,24 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1357
1357
  q_spec = {
1358
1358
  "pattern": q,
1359
1359
  "type": mode,
1360
- "path": args.get("path") or args.get("project_path") or "",
1361
1360
  "case_sensitive": bool(args.get("case_sensitive", False)),
1362
1361
  "max_results": int(args.get("max_results") or 25),
1363
1362
  }
1363
+ # `path` is a sub-query scope relative to the project root, never the
1364
+ # root itself: joining it twice produced "src/x.py/src/x.py" errors.
1365
+ sub_path = args.get("path")
1366
+ if sub_path:
1367
+ q_spec["path"] = sub_path
1364
1368
  raw_sc = str(args.get("scope") or "").strip()
1365
1369
  if raw_sc.startswith("*.") or "*" in raw_sc:
1366
1370
  q_spec["glob"] = raw_sc
1367
1371
  elif raw_sc and raw_sc.lower() not in ("all", "code", "config"):
1368
1372
  q_spec["file_type"] = raw_sc.lstrip(".")
1369
- args = {
1370
- "queries": [q_spec],
1371
- "cwd": args.get("cwd") or args.get("project_path") or args.get("path"),
1372
- }
1373
+ rerouted = {"queries": [q_spec]}
1374
+ explicit_root = args.get("cwd") or args.get("project_path")
1375
+ if explicit_root:
1376
+ rerouted["cwd"] = explicit_root
1377
+ args = rerouted
1373
1378
  name = "batch_search"
1374
1379
  elif mode in ("text", "regex") and args.get("use_regex") is None:
1375
1380
  args = dict(args, use_regex=(mode == "regex"))
@@ -2752,7 +2757,25 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2752
2757
  if isinstance(queries, dict):
2753
2758
  queries = [queries]
2754
2759
  elif not queries and (args.get("query") or args.get("pattern")):
2755
- queries = [{"pattern": args.get("query") or args.get("pattern"), "type": args.get("type", "text")}]
2760
+ # Shorthand: forward every per-query knob instead of silently
2761
+ # dropping glob/case_sensitive/max_results/output_mode/scope.
2762
+ # `path` is a sub-query scope ONLY when an explicit project root
2763
+ # is supplied; otherwise it is the legacy cwd and must not be
2764
+ # joined twice.
2765
+ q_spec: Dict[str, Any] = {
2766
+ "pattern": args.get("query") or args.get("pattern"),
2767
+ "type": args.get("type", "text"),
2768
+ }
2769
+ has_explicit_root = bool(args.get("cwd") or args.get("project_path"))
2770
+ for key in ("path", "glob", "file_type", "scope", "output_mode",
2771
+ "case_sensitive", "max_results", "use_regex"):
2772
+ if key == "path" and not has_explicit_root:
2773
+ continue
2774
+ if args.get(key) is not None:
2775
+ q_spec[key] = args.get(key)
2776
+ if q_spec.get("use_regex") is not None:
2777
+ q_spec["type"] = "regex" if q_spec.pop("use_regex") else "text"
2778
+ queries = [q_spec]
2756
2779
  if not queries:
2757
2780
  return _fallback_error("batch_search", "missing required 'queries' list")
2758
2781
 
@@ -2816,7 +2839,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2816
2839
  optimized_tokens=res_tokens,
2817
2840
  details={"query_count": len(safe_queries), "mode": "batch_search"},
2818
2841
  )
2819
- return {"content": [{"type": "text", "text": summary_md}]}
2842
+ out = {"content": [{"type": "text", "text": summary_md}]}
2843
+ if not res.get("success"):
2844
+ # Every query errored: report a failed tool call instead of a
2845
+ # successful one whose body silently contains only errors.
2846
+ out["isError"] = True
2847
+ return out
2820
2848
  except Exception as e:
2821
2849
  return _fallback_error("batch_search", f"failed to execute batch search: {e}")
2822
2850
 
@@ -2862,71 +2890,122 @@ def _redact_result_secrets(result):
2862
2890
  return redacted
2863
2891
 
2864
2892
 
2893
+ def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2894
+ """Folds `text` into at most `limit_bytes` UTF-8 bytes.
2895
+
2896
+ Never raises and never returns an over-budget string: if the stash write is
2897
+ unavailable the content is truncated with an explicit marker instead of
2898
+ being passed through uncapped.
2899
+ """
2900
+ if limit_bytes <= 0:
2901
+ return ""
2902
+ try:
2903
+ from src.format_parsers.ansi import strip_ansi
2904
+ clean_text = strip_ansi(text)
2905
+ except Exception:
2906
+ clean_text = text
2907
+ raw = clean_text.encode("utf-8")
2908
+ if len(raw) <= limit_bytes:
2909
+ return clean_text
2910
+
2911
+ marker = ""
2912
+ try:
2913
+ from src.stash import stash_block
2914
+ _hash, marker = stash_block(clean_text, source=f"mcp:{tool_name}")
2915
+ except Exception:
2916
+ marker = ""
2917
+ if not marker:
2918
+ marker = "[TokenSafe Zero-Spill Guard: content folded; stash copy unavailable]"
2919
+
2920
+ footer = "\n" + marker
2921
+ footer_bytes = len(footer.encode("utf-8"))
2922
+ budget = limit_bytes - footer_bytes
2923
+ if budget <= 40:
2924
+ return marker.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2925
+
2926
+ lines = clean_text.splitlines()
2927
+ if len(lines) > 35:
2928
+ head = lines[:20]
2929
+ tail = lines[-15:]
2930
+ omitted = len(lines) - (len(head) + len(tail))
2931
+ msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2932
+ tail_str = "\n".join(tail)
2933
+ tail_bytes = len(tail_str.encode("utf-8"))
2934
+ msg_bytes = len(msg.encode("utf-8"))
2935
+ if msg_bytes + tail_bytes < budget:
2936
+ head_budget = budget - msg_bytes - tail_bytes
2937
+ head_str = ""
2938
+ for line in head:
2939
+ candidate = head_str + line + "\n"
2940
+ if len(candidate.encode("utf-8")) <= head_budget:
2941
+ head_str = candidate
2942
+ else:
2943
+ break
2944
+ folded = f"{head_str.rstrip()}{msg}{tail_str}{footer}"
2945
+ if len(folded.encode("utf-8")) <= limit_bytes:
2946
+ return folded
2947
+
2948
+ msg = "\n... [content folded by TokenSafe Zero-Spill Guard] ...\n"
2949
+ avail = budget - len(msg.encode("utf-8"))
2950
+ if avail <= 40:
2951
+ return marker.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2952
+ head_n = avail // 2
2953
+ tail_n = avail - head_n
2954
+ head_s = raw[:head_n].decode("utf-8", errors="ignore")
2955
+ tail_s = raw[len(raw) - tail_n:].decode("utf-8", errors="ignore") if tail_n else ""
2956
+ folded = f"{head_s}{msg}{tail_s}{footer}"
2957
+ if len(folded.encode("utf-8")) > limit_bytes:
2958
+ folded = folded.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2959
+ return folded
2960
+
2961
+
2865
2962
  def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int = 8800) -> Any:
2866
- """Zero-Spill Guard: guarantees no MCP tool response exceeds 8800 UTF-8 bytes.
2867
- Prevents Antigravity from spilling tool output to disk (output.txt) which forces
2868
- an extra LLM roundtrip turn to read the spill file. Full content is saved to
2869
- reversible stash and referenced with an 8-char hash anchor."""
2963
+ """Zero-Spill Guard: keeps the whole tools/call payload under `max_bytes`.
2964
+
2965
+ The budget is per RESPONSE, not per text block: several medium blocks used
2966
+ to slip through and spill to disk. Only ~90% of `max_bytes` is spent on
2967
+ text, leaving headroom for the JSON escaping the JSON-RPC envelope adds.
2968
+ """
2870
2969
  if not isinstance(result, dict):
2871
2970
  return result
2872
2971
  content = result.get("content")
2873
2972
  if not isinstance(content, list):
2874
2973
  return result
2875
2974
 
2876
- modified = False
2877
- new_content = []
2878
- for block in content:
2879
- if isinstance(block, dict) and block.get("type") == "text":
2880
- text = block.get("text", "")
2881
- raw_bytes = text.encode("utf-8")
2882
- if len(raw_bytes) > max_bytes:
2883
- try:
2884
- from src.stash import stash_block
2885
- from src.format_parsers.ansi import strip_ansi
2886
- clean_text = strip_ansi(text)
2887
- hash8, marker = stash_block(clean_text, source=f"mcp:{tool_name}")
2888
- lines = clean_text.splitlines()
2889
- footer = f"\n{marker}"
2890
- footer_bytes = len(footer.encode("utf-8"))
2891
- if len(lines) > 35:
2892
- head = lines[:20]
2893
- tail = lines[-15:]
2894
- omitted = len(lines) - (len(head) + len(tail))
2895
- folded_msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2896
- tail_str = "\n".join(tail)
2897
- budget = max_bytes - len(folded_msg.encode("utf-8")) - footer_bytes - len(tail_str.encode("utf-8")) - 50
2898
- head_str = ""
2899
- for line in head:
2900
- if len((head_str + line + "\n").encode("utf-8")) <= budget:
2901
- head_str += line + "\n"
2902
- else:
2903
- break
2904
- folded_text = f"{head_str.rstrip()}{folded_msg}{tail_str}{footer}"
2905
- else:
2906
- msg_mid = f"\n... [{len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2907
- avail = max(120, max_bytes - len(msg_mid.encode("utf-8")) - footer_bytes - 50)
2908
- head_b = raw_bytes[: avail // 2].decode("utf-8", errors="ignore")
2909
- tail_b = raw_bytes[-(avail - avail // 2):].decode("utf-8", errors="ignore")
2910
- folded_text = f"{head_b.rstrip()}{msg_mid}{tail_b.lstrip()}{footer}"
2911
-
2912
- if len(folded_text.encode("utf-8")) > max_bytes:
2913
- allowed_head = max(80, max_bytes - footer_bytes - 60)
2914
- folded_text = clean_text.encode("utf-8")[:allowed_head].decode("utf-8", errors="ignore") + f"\n... [folded]\n{footer}"
2915
-
2916
- new_block = dict(block)
2917
- new_block["text"] = folded_text
2918
- new_content.append(new_block)
2919
- modified = True
2920
- continue
2921
- except Exception:
2922
- pass
2923
- new_content.append(block)
2975
+ text_idx = [i for i, b in enumerate(content) if isinstance(b, dict) and b.get("type") == "text"]
2976
+ if not text_idx:
2977
+ return result
2978
+
2979
+ budget = max(256, int(max_bytes * 0.9))
2980
+ sizes = {i: len(str(content[i].get("text") or "").encode("utf-8")) for i in text_idx}
2981
+ total = sum(sizes.values())
2982
+ if total <= budget:
2983
+ return result
2924
2984
 
2925
- if modified:
2926
- new_res = dict(result)
2927
- new_res["content"] = new_content
2928
- return new_res
2929
- return result
2985
+ new_content = list(content)
2986
+ # Fold the largest blocks first: that frees the most bytes per block touched.
2987
+ for i in sorted(text_idx, key=lambda idx: sizes[idx], reverse=True):
2988
+ if total <= budget:
2989
+ break
2990
+ others = total - sizes[i]
2991
+ target = max(200, budget - others)
2992
+ if target >= sizes[i]:
2993
+ continue
2994
+ folded = _fold_text_for_guard(str(content[i].get("text") or ""), target, tool_name)
2995
+ new_content[i] = {**content[i], "text": folded}
2996
+ total = total - sizes[i] + len(folded.encode("utf-8"))
2997
+
2998
+ if total > budget:
2999
+ # Last resort: keep only the first block, folded to the full budget.
3000
+ first = text_idx[0]
3001
+ kept = _fold_text_for_guard(str(content[first].get("text") or ""), budget, tool_name)
3002
+ for i in text_idx[1:]:
3003
+ new_content[i] = {**new_content[i], "text": ""}
3004
+ new_content[first] = {**content[first], "text": kept}
3005
+
3006
+ new_res = dict(result)
3007
+ new_res["content"] = new_content
3008
+ return new_res
2930
3009
 
2931
3010
 
2932
3011
  def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict: