tokensafe 4.6.0 → 4.6.2

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/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.2"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -1285,6 +1285,13 @@ def handle_tool_call(name: str, args: dict) -> dict:
1285
1285
  )
1286
1286
  except Exception:
1287
1287
  pass
1288
+ try:
1289
+ from src.adapter_core import get_oumv_read_edit_advisory
1290
+ oumv_note = get_oumv_read_edit_advisory(active_ws or os.path.dirname(abs_path), abs_path, _mcp_session_id())
1291
+ if oumv_note and content_parts and isinstance(content_parts[-1], dict):
1292
+ content_parts[-1]["text"] = f"{content_parts[-1].get('text', '')}\n\n{oumv_note}"
1293
+ except Exception:
1294
+ pass
1288
1295
  return result
1289
1296
  except Exception as e:
1290
1297
  return _fallback_error(name, f"{type(e).__name__}: {str(e)}")
@@ -1357,19 +1364,24 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1357
1364
  q_spec = {
1358
1365
  "pattern": q,
1359
1366
  "type": mode,
1360
- "path": args.get("path") or args.get("project_path") or "",
1361
1367
  "case_sensitive": bool(args.get("case_sensitive", False)),
1362
1368
  "max_results": int(args.get("max_results") or 25),
1363
1369
  }
1370
+ # `path` is a sub-query scope relative to the project root, never the
1371
+ # root itself: joining it twice produced "src/x.py/src/x.py" errors.
1372
+ sub_path = args.get("path")
1373
+ if sub_path:
1374
+ q_spec["path"] = sub_path
1364
1375
  raw_sc = str(args.get("scope") or "").strip()
1365
1376
  if raw_sc.startswith("*.") or "*" in raw_sc:
1366
1377
  q_spec["glob"] = raw_sc
1367
1378
  elif raw_sc and raw_sc.lower() not in ("all", "code", "config"):
1368
1379
  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
- }
1380
+ rerouted = {"queries": [q_spec]}
1381
+ explicit_root = args.get("cwd") or args.get("project_path")
1382
+ if explicit_root:
1383
+ rerouted["cwd"] = explicit_root
1384
+ args = rerouted
1373
1385
  name = "batch_search"
1374
1386
  elif mode in ("text", "regex") and args.get("use_regex") is None:
1375
1387
  args = dict(args, use_regex=(mode == "regex"))
@@ -2593,7 +2605,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2593
2605
  lvl = str(args.get("level") or "L0").strip()
2594
2606
  tgt = str(args.get("target") or "").strip() or None
2595
2607
  rt = str(args.get("runtime") or "auto").strip()
2596
- res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt)
2608
+ ws = str(args.get("workspace_dir") or "").strip() or None
2609
+ res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws)
2597
2610
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2598
2611
  except Exception as e:
2599
2612
  return _fallback_error("oumv_observe", f"failed to observe OUMV runtime: {e}")
@@ -2604,7 +2617,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2604
2617
  qry = str(args.get("query") or "causality").strip()
2605
2618
  tgt = str(args.get("target") or "").strip() or None
2606
2619
  rt = str(args.get("runtime") or "auto").strip()
2607
- res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt)
2620
+ ws = str(args.get("workspace_dir") or "").strip() or None
2621
+ res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt, workspace_dir=ws)
2608
2622
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2609
2623
  except Exception as e:
2610
2624
  return _fallback_error("oumv_understand", f"failed to query OUMV understanding: {e}")
@@ -2617,7 +2631,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2617
2631
  rep = args.get("replacement")
2618
2632
  ev = str(args.get("expectedVersion") or "").strip() or None
2619
2633
  rt = str(args.get("runtime") or "auto").strip()
2620
- res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt)
2634
+ ws = str(args.get("workspace_dir") or "").strip() or None
2635
+ res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt, workspace_dir=ws)
2621
2636
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2622
2637
  except Exception as e:
2623
2638
  return _fallback_error("oumv_mutate", f"failed to apply OUMV mutation: {e}")
@@ -2629,7 +2644,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2629
2644
  act = str(args.get("action") or "invoke").strip()
2630
2645
  payload = args.get("payload") if isinstance(args.get("payload"), dict) else None
2631
2646
  rt = str(args.get("runtime") or "auto").strip()
2632
- res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt)
2647
+ ws = str(args.get("workspace_dir") or "").strip() or None
2648
+ res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws)
2633
2649
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2634
2650
  except Exception as e:
2635
2651
  return _fallback_error("oumv_verify", f"failed to verify OUMV action: {e}")
@@ -2639,7 +2655,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2639
2655
  from src.oumv_gateway import OUMVGateway
2640
2656
  qry = str(args.get("query") or "overview").strip()
2641
2657
  tgt = str(args.get("target") or "").strip() or None
2642
- res = OUMVGateway.graph(query=qry, target=tgt)
2658
+ ws = str(args.get("workspace_dir") or "").strip() or None
2659
+ res = OUMVGateway.graph(query=qry, target=tgt, workspace_dir=ws)
2643
2660
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2644
2661
  except Exception as e:
2645
2662
  return _fallback_error("oumv_graph", f"failed to query cross-stack graph: {e}")
@@ -2752,7 +2769,25 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2752
2769
  if isinstance(queries, dict):
2753
2770
  queries = [queries]
2754
2771
  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")}]
2772
+ # Shorthand: forward every per-query knob instead of silently
2773
+ # dropping glob/case_sensitive/max_results/output_mode/scope.
2774
+ # `path` is a sub-query scope ONLY when an explicit project root
2775
+ # is supplied; otherwise it is the legacy cwd and must not be
2776
+ # joined twice.
2777
+ q_spec: Dict[str, Any] = {
2778
+ "pattern": args.get("query") or args.get("pattern"),
2779
+ "type": args.get("type", "text"),
2780
+ }
2781
+ has_explicit_root = bool(args.get("cwd") or args.get("project_path"))
2782
+ for key in ("path", "glob", "file_type", "scope", "output_mode",
2783
+ "case_sensitive", "max_results", "use_regex"):
2784
+ if key == "path" and not has_explicit_root:
2785
+ continue
2786
+ if args.get(key) is not None:
2787
+ q_spec[key] = args.get(key)
2788
+ if q_spec.get("use_regex") is not None:
2789
+ q_spec["type"] = "regex" if q_spec.pop("use_regex") else "text"
2790
+ queries = [q_spec]
2756
2791
  if not queries:
2757
2792
  return _fallback_error("batch_search", "missing required 'queries' list")
2758
2793
 
@@ -2816,7 +2851,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2816
2851
  optimized_tokens=res_tokens,
2817
2852
  details={"query_count": len(safe_queries), "mode": "batch_search"},
2818
2853
  )
2819
- return {"content": [{"type": "text", "text": summary_md}]}
2854
+ out = {"content": [{"type": "text", "text": summary_md}]}
2855
+ if not res.get("success"):
2856
+ # Every query errored: report a failed tool call instead of a
2857
+ # successful one whose body silently contains only errors.
2858
+ out["isError"] = True
2859
+ return out
2820
2860
  except Exception as e:
2821
2861
  return _fallback_error("batch_search", f"failed to execute batch search: {e}")
2822
2862
 
@@ -2862,71 +2902,122 @@ def _redact_result_secrets(result):
2862
2902
  return redacted
2863
2903
 
2864
2904
 
2905
+ def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2906
+ """Folds `text` into at most `limit_bytes` UTF-8 bytes.
2907
+
2908
+ Never raises and never returns an over-budget string: if the stash write is
2909
+ unavailable the content is truncated with an explicit marker instead of
2910
+ being passed through uncapped.
2911
+ """
2912
+ if limit_bytes <= 0:
2913
+ return ""
2914
+ try:
2915
+ from src.format_parsers.ansi import strip_ansi
2916
+ clean_text = strip_ansi(text)
2917
+ except Exception:
2918
+ clean_text = text
2919
+ raw = clean_text.encode("utf-8")
2920
+ if len(raw) <= limit_bytes:
2921
+ return clean_text
2922
+
2923
+ marker = ""
2924
+ try:
2925
+ from src.stash import stash_block
2926
+ _hash, marker = stash_block(clean_text, source=f"mcp:{tool_name}")
2927
+ except Exception:
2928
+ marker = ""
2929
+ if not marker:
2930
+ marker = "[TokenSafe Zero-Spill Guard: content folded; stash copy unavailable]"
2931
+
2932
+ footer = "\n" + marker
2933
+ footer_bytes = len(footer.encode("utf-8"))
2934
+ budget = limit_bytes - footer_bytes
2935
+ if budget <= 40:
2936
+ return marker.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2937
+
2938
+ lines = clean_text.splitlines()
2939
+ if len(lines) > 35:
2940
+ head = lines[:20]
2941
+ tail = lines[-15:]
2942
+ omitted = len(lines) - (len(head) + len(tail))
2943
+ msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2944
+ tail_str = "\n".join(tail)
2945
+ tail_bytes = len(tail_str.encode("utf-8"))
2946
+ msg_bytes = len(msg.encode("utf-8"))
2947
+ if msg_bytes + tail_bytes < budget:
2948
+ head_budget = budget - msg_bytes - tail_bytes
2949
+ head_str = ""
2950
+ for line in head:
2951
+ candidate = head_str + line + "\n"
2952
+ if len(candidate.encode("utf-8")) <= head_budget:
2953
+ head_str = candidate
2954
+ else:
2955
+ break
2956
+ folded = f"{head_str.rstrip()}{msg}{tail_str}{footer}"
2957
+ if len(folded.encode("utf-8")) <= limit_bytes:
2958
+ return folded
2959
+
2960
+ msg = "\n... [content folded by TokenSafe Zero-Spill Guard] ...\n"
2961
+ avail = budget - len(msg.encode("utf-8"))
2962
+ if avail <= 40:
2963
+ return marker.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2964
+ head_n = avail // 2
2965
+ tail_n = avail - head_n
2966
+ head_s = raw[:head_n].decode("utf-8", errors="ignore")
2967
+ tail_s = raw[len(raw) - tail_n:].decode("utf-8", errors="ignore") if tail_n else ""
2968
+ folded = f"{head_s}{msg}{tail_s}{footer}"
2969
+ if len(folded.encode("utf-8")) > limit_bytes:
2970
+ folded = folded.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2971
+ return folded
2972
+
2973
+
2865
2974
  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."""
2975
+ """Zero-Spill Guard: keeps the whole tools/call payload under `max_bytes`.
2976
+
2977
+ The budget is per RESPONSE, not per text block: several medium blocks used
2978
+ to slip through and spill to disk. Only ~90% of `max_bytes` is spent on
2979
+ text, leaving headroom for the JSON escaping the JSON-RPC envelope adds.
2980
+ """
2870
2981
  if not isinstance(result, dict):
2871
2982
  return result
2872
2983
  content = result.get("content")
2873
2984
  if not isinstance(content, list):
2874
2985
  return result
2875
2986
 
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)
2987
+ text_idx = [i for i, b in enumerate(content) if isinstance(b, dict) and b.get("type") == "text"]
2988
+ if not text_idx:
2989
+ return result
2924
2990
 
2925
- if modified:
2926
- new_res = dict(result)
2927
- new_res["content"] = new_content
2928
- return new_res
2929
- return result
2991
+ budget = max(256, int(max_bytes * 0.9))
2992
+ sizes = {i: len(str(content[i].get("text") or "").encode("utf-8")) for i in text_idx}
2993
+ total = sum(sizes.values())
2994
+ if total <= budget:
2995
+ return result
2996
+
2997
+ new_content = list(content)
2998
+ # Fold the largest blocks first: that frees the most bytes per block touched.
2999
+ for i in sorted(text_idx, key=lambda idx: sizes[idx], reverse=True):
3000
+ if total <= budget:
3001
+ break
3002
+ others = total - sizes[i]
3003
+ target = max(200, budget - others)
3004
+ if target >= sizes[i]:
3005
+ continue
3006
+ folded = _fold_text_for_guard(str(content[i].get("text") or ""), target, tool_name)
3007
+ new_content[i] = {**content[i], "text": folded}
3008
+ total = total - sizes[i] + len(folded.encode("utf-8"))
3009
+
3010
+ if total > budget:
3011
+ # Last resort: keep only the first block, folded to the full budget.
3012
+ first = text_idx[0]
3013
+ kept = _fold_text_for_guard(str(content[first].get("text") or ""), budget, tool_name)
3014
+ for i in text_idx[1:]:
3015
+ new_content[i] = {**new_content[i], "text": ""}
3016
+ new_content[first] = {**content[first], "text": kept}
3017
+
3018
+ new_res = dict(result)
3019
+ new_res["content"] = new_content
3020
+ return new_res
2930
3021
 
2931
3022
 
2932
3023
  def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict: