tokensafe 4.6.2 → 4.6.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/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.2"
45
+ "version": "4.6.3"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -2902,8 +2902,59 @@ def _redact_result_secrets(result):
2902
2902
  return redacted
2903
2903
 
2904
2904
 
2905
+ _ENVELOPE_HEADROOM_BYTES = 200
2906
+
2907
+
2908
+ def _wire_bytes(text: str) -> int:
2909
+ """Bytes this text costs on the wire after json.dumps(..., ensure_ascii=False).
2910
+
2911
+ The MCP boundary serializes with ensure_ascii=False, so every newline, tab,
2912
+ quote and backslash is escaped to two characters. Measuring raw UTF-8
2913
+ undercounts newline-heavy output (logs) by up to 2x, which used to let a
2914
+ "capped" payload spill to disk anyway.
2915
+ """
2916
+ try:
2917
+ return len(json.dumps(text, ensure_ascii=False).encode("utf-8")) - 2
2918
+ except Exception:
2919
+ return len(str(text).encode("utf-8"))
2920
+
2921
+
2922
+ def _fit_prefix(text: str, limit_bytes: int) -> str:
2923
+ """Longest-ish prefix of `text` whose wire cost fits `limit_bytes` (never raises)."""
2924
+ if limit_bytes <= 0 or not text:
2925
+ return ""
2926
+ cost = _wire_bytes(text)
2927
+ if cost <= limit_bytes:
2928
+ return text
2929
+ n = len(text)
2930
+ guess = max(1, int(n * limit_bytes / max(1, cost)))
2931
+ for _ in range(8):
2932
+ candidate = text[:guess]
2933
+ if _wire_bytes(candidate) <= limit_bytes:
2934
+ return candidate
2935
+ guess = max(1, int(guess * 0.8))
2936
+ return text[:1]
2937
+
2938
+
2939
+ def _fit_suffix(text: str, limit_bytes: int) -> str:
2940
+ """Longest-ish suffix of `text` whose wire cost fits `limit_bytes` (never raises)."""
2941
+ if limit_bytes <= 0 or not text:
2942
+ return ""
2943
+ cost = _wire_bytes(text)
2944
+ if cost <= limit_bytes:
2945
+ return text
2946
+ n = len(text)
2947
+ guess = max(1, int(n * limit_bytes / max(1, cost)))
2948
+ for _ in range(8):
2949
+ candidate = text[-guess:]
2950
+ if _wire_bytes(candidate) <= limit_bytes:
2951
+ return candidate
2952
+ guess = max(1, int(guess * 0.8))
2953
+ return text[-1:]
2954
+
2955
+
2905
2956
  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.
2957
+ """Folds `text` into at most `limit_bytes` WIRE bytes (JSON-escaped cost).
2907
2958
 
2908
2959
  Never raises and never returns an over-budget string: if the stash write is
2909
2960
  unavailable the content is truncated with an explicit marker instead of
@@ -2916,8 +2967,7 @@ def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2916
2967
  clean_text = strip_ansi(text)
2917
2968
  except Exception:
2918
2969
  clean_text = text
2919
- raw = clean_text.encode("utf-8")
2920
- if len(raw) <= limit_bytes:
2970
+ if _wire_bytes(clean_text) <= limit_bytes:
2921
2971
  return clean_text
2922
2972
 
2923
2973
  marker = ""
@@ -2930,10 +2980,9 @@ def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2930
2980
  marker = "[TokenSafe Zero-Spill Guard: content folded; stash copy unavailable]"
2931
2981
 
2932
2982
  footer = "\n" + marker
2933
- footer_bytes = len(footer.encode("utf-8"))
2934
- budget = limit_bytes - footer_bytes
2983
+ budget = limit_bytes - _wire_bytes(footer)
2935
2984
  if budget <= 40:
2936
- return marker.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2985
+ return _fit_prefix(marker, limit_bytes)
2937
2986
 
2938
2987
  lines = clean_text.splitlines()
2939
2988
  if len(lines) > 35:
@@ -2942,41 +2991,39 @@ def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2942
2991
  omitted = len(lines) - (len(head) + len(tail))
2943
2992
  msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2944
2993
  tail_str = "\n".join(tail)
2945
- tail_bytes = len(tail_str.encode("utf-8"))
2946
- msg_bytes = len(msg.encode("utf-8"))
2994
+ msg_bytes = _wire_bytes(msg)
2995
+ tail_bytes = _wire_bytes(tail_str)
2947
2996
  if msg_bytes + tail_bytes < budget:
2948
2997
  head_budget = budget - msg_bytes - tail_bytes
2949
2998
  head_str = ""
2950
2999
  for line in head:
2951
3000
  candidate = head_str + line + "\n"
2952
- if len(candidate.encode("utf-8")) <= head_budget:
3001
+ if _wire_bytes(candidate) <= head_budget:
2953
3002
  head_str = candidate
2954
3003
  else:
2955
3004
  break
2956
3005
  folded = f"{head_str.rstrip()}{msg}{tail_str}{footer}"
2957
- if len(folded.encode("utf-8")) <= limit_bytes:
3006
+ if _wire_bytes(folded) <= limit_bytes:
2958
3007
  return folded
2959
3008
 
2960
3009
  msg = "\n... [content folded by TokenSafe Zero-Spill Guard] ...\n"
2961
- avail = budget - len(msg.encode("utf-8"))
3010
+ avail = budget - _wire_bytes(msg)
2962
3011
  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 ""
3012
+ return _fit_prefix(marker, limit_bytes)
3013
+ head_s = _fit_prefix(clean_text, max(1, avail // 2))
3014
+ tail_s = _fit_suffix(clean_text[len(head_s):], max(0, avail - _wire_bytes(head_s)))
2968
3015
  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")
3016
+ if _wire_bytes(folded) > limit_bytes:
3017
+ folded = _fit_prefix(folded, limit_bytes)
2971
3018
  return folded
2972
3019
 
2973
3020
 
2974
3021
  def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int = 8800) -> Any:
2975
3022
  """Zero-Spill Guard: keeps the whole tools/call payload under `max_bytes`.
2976
3023
 
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.
3024
+ The budget is per RESPONSE, not per text block, and it is measured in the
3025
+ bytes the JSON-RPC envelope will actually carry (JSON-escaped), leaving a
3026
+ fixed headroom for the envelope itself.
2980
3027
  """
2981
3028
  if not isinstance(result, dict):
2982
3029
  return result
@@ -2988,8 +3035,8 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
2988
3035
  if not text_idx:
2989
3036
  return result
2990
3037
 
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}
3038
+ budget = max(256, max_bytes - _ENVELOPE_HEADROOM_BYTES)
3039
+ sizes = {i: _wire_bytes(str(content[i].get("text") or "")) for i in text_idx}
2993
3040
  total = sum(sizes.values())
2994
3041
  if total <= budget:
2995
3042
  return result
@@ -3005,7 +3052,7 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
3005
3052
  continue
3006
3053
  folded = _fold_text_for_guard(str(content[i].get("text") or ""), target, tool_name)
3007
3054
  new_content[i] = {**content[i], "text": folded}
3008
- total = total - sizes[i] + len(folded.encode("utf-8"))
3055
+ total = total - sizes[i] + _wire_bytes(folded)
3009
3056
 
3010
3057
  if total > budget:
3011
3058
  # Last resort: keep only the first block, folded to the full budget.
@@ -3013,6 +3060,9 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
3013
3060
  kept = _fold_text_for_guard(str(content[first].get("text") or ""), budget, tool_name)
3014
3061
  for i in text_idx[1:]:
3015
3062
  new_content[i] = {**new_content[i], "text": ""}
3063
+ # Final guarantee on the wire budget even if the fold overshot.
3064
+ if _wire_bytes(kept) > budget:
3065
+ kept = _fit_prefix(kept, budget)
3016
3066
  new_content[first] = {**content[first], "text": kept}
3017
3067
 
3018
3068
  new_res = dict(result)
@@ -7,9 +7,11 @@ Connects AI coding agents to live Frontend (tokensafe-ui, Vite, React) and Backe
7
7
  import os
8
8
  import json
9
9
  import time
10
+ import socket
10
11
  import hashlib
11
12
  import urllib.request
12
13
  import urllib.error
14
+ import urllib.parse
13
15
  from concurrent.futures import ThreadPoolExecutor, as_completed
14
16
  from typing import Dict, Any, Optional, Tuple, List
15
17
  from src.paths import get_active_workspace
@@ -19,6 +21,23 @@ class OUMVRpcError(RuntimeError):
19
21
  """Raised when a live OUMV runtime explicitly returns a JSON-RPC error."""
20
22
 
21
23
 
24
+ class OUMVUnsupportedMethodError(OUMVRpcError):
25
+ """The runtime answered but does not implement the requested method.
26
+
27
+ This is not a safety rejection: the runtime cannot mediate the operation at
28
+ all, so the gateway may perform the guarded offline edit instead.
29
+ """
30
+
31
+
32
+ _UNSUPPORTED_HINTS = (
33
+ "unknown method",
34
+ "method not found",
35
+ "-32601",
36
+ "not implemented",
37
+ "not supported",
38
+ )
39
+
40
+
22
41
  class OUMVGateway:
23
42
  """Dispatches OUMV protocol calls to live DevServers with zero-config discovery."""
24
43
 
@@ -26,6 +45,65 @@ class OUMVGateway:
26
45
  _cached_be: Optional[Dict[str, Any]] = None
27
46
  _last_scan_time: float = 0.0
28
47
  _SCAN_INTERVAL_SEC: float = 5.0
48
+ # Liveness cache for descriptor-derived ports: the bash guard runs per command,
49
+ # so a TCP probe must be memoized instead of blocking every invocation.
50
+ _port_liveness: Dict[Tuple[str, int], Tuple[float, bool]] = {}
51
+ _PORT_TTL_SEC: float = 8.0
52
+ _PORT_PROBE_TIMEOUT: float = 0.05
53
+ # Descriptors left behind by a crashed dev server must not stay authoritative forever.
54
+ _DESCRIPTOR_MAX_AGE_SEC: float = 12 * 3600.0
55
+
56
+ @classmethod
57
+ def _is_port_open(cls, host: str, port: int, timeout: Optional[float] = None, use_cache: bool = True) -> bool:
58
+ """Cheap TCP liveness check with a short TTL cache (never raises)."""
59
+ key = (host or "127.0.0.1", int(port))
60
+ now = time.time()
61
+ if use_cache:
62
+ hit = cls._port_liveness.get(key)
63
+ if hit and (now - hit[0]) < cls._PORT_TTL_SEC:
64
+ return hit[1]
65
+ alive = False
66
+ try:
67
+ with socket.create_connection(key, timeout=timeout or cls._PORT_PROBE_TIMEOUT):
68
+ alive = True
69
+ except OSError:
70
+ alive = False
71
+ cls._port_liveness[key] = (now, alive)
72
+ return alive
73
+
74
+ @classmethod
75
+ def _is_url_live(cls, url: Optional[str]) -> bool:
76
+ """True when a runtime URL's port accepts connections (port-less URLs are trusted)."""
77
+ if not url:
78
+ return False
79
+ try:
80
+ parsed = urllib.parse.urlparse(url)
81
+ port = parsed.port
82
+ except ValueError:
83
+ return False
84
+ except Exception:
85
+ return True
86
+ if not port:
87
+ return True
88
+ return cls._is_port_open(parsed.hostname or "127.0.0.1", int(port))
89
+
90
+ @classmethod
91
+ def _drop_stale_descriptor_endpoints(cls) -> List[Dict[str, Any]]:
92
+ """Clears descriptor-sourced endpoints whose port no longer listens.
93
+
94
+ A descriptor is a hint written by the dev server; after a crash it keeps
95
+ pointing at a dead (or reused) port and every consumer would report CONNECTED.
96
+ Returns the dropped entries so callers can explain the downgrade.
97
+ """
98
+ dropped: List[Dict[str, Any]] = []
99
+ for attr in ("_cached_fe", "_cached_be"):
100
+ entry = getattr(cls, attr)
101
+ if entry and entry.get("source") == "descriptor":
102
+ url = entry.get("url")
103
+ if url and not cls._is_url_live(url):
104
+ dropped.append(entry)
105
+ setattr(cls, attr, None)
106
+ return dropped
29
107
 
30
108
  @classmethod
31
109
  def get_endpoints(cls, workspace_dir: Optional[str] = None) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
@@ -33,6 +111,7 @@ class OUMVGateway:
33
111
  now = time.time()
34
112
  if (now - cls._last_scan_time > cls._SCAN_INTERVAL_SEC) or (not cls._cached_fe and not cls._cached_be):
35
113
  cls.scan(workspace_dir=workspace_dir)
114
+ cls._drop_stale_descriptor_endpoints()
36
115
  return cls._cached_fe, cls._cached_be
37
116
 
38
117
  @classmethod
@@ -111,6 +190,7 @@ class OUMVGateway:
111
190
  "url": fe_info["url"],
112
191
  "sessionToken": fe_info.get("sessionToken"),
113
192
  "healthy": True,
193
+ "source": "descriptor",
114
194
  "capabilities": fe_info.get("capabilities", {}),
115
195
  }
116
196
  be_info = data.get("backend")
@@ -122,6 +202,7 @@ class OUMVGateway:
122
202
  "url": be_info["url"],
123
203
  "sessionToken": be_info.get("session_token") or be_info.get("sessionToken"),
124
204
  "healthy": True,
205
+ "source": "descriptor",
125
206
  "capabilities": be_info.get("capabilities", {}),
126
207
  }
127
208
  except Exception:
@@ -175,16 +256,44 @@ class OUMVGateway:
175
256
  method="POST",
176
257
  )
177
258
 
178
- with urllib.request.urlopen(req, timeout=timeout) as resp:
179
- data = json.loads(resp.read().decode("utf-8"))
180
- if "error" in data and data["error"]:
181
- err = data["error"]
182
- if isinstance(err, dict):
183
- code = err.get("code")
184
- msg = err.get("message") or str(err)
185
- raise OUMVRpcError(f"JSON-RPC error ({code}) from {endpoint_url}: {msg}")
186
- raise OUMVRpcError(f"JSON-RPC error from {endpoint_url}: {err}")
187
- return data.get("result")
259
+ try:
260
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
261
+ data = json.loads(resp.read().decode("utf-8"))
262
+ if "error" in data and data["error"]:
263
+ err = data["error"]
264
+ if isinstance(err, dict):
265
+ code = err.get("code")
266
+ msg = err.get("message") or str(err)
267
+ raise OUMVRpcError(f"JSON-RPC error ({code}) from {endpoint_url}: {msg}")
268
+ raise OUMVRpcError(f"JSON-RPC error from {endpoint_url}: {err}")
269
+ return data.get("result")
270
+ except urllib.error.HTTPError as exc:
271
+ # Some bridges answer an unsupported method with HTTP 400 instead of a
272
+ # JSON-RPC envelope. Treat that as a protocol error (RuntimeError) so
273
+ # callers can fall back to offline operation instead of crashing on OSError.
274
+ code, msg = cls._http_error_detail(exc)
275
+ raise OUMVRpcError(f"JSON-RPC error ({code}) from {endpoint_url}: {msg}") from exc
276
+ except urllib.error.URLError as exc:
277
+ raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {exc.reason}") from exc
278
+ except (TimeoutError, OSError) as exc:
279
+ raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {exc}") from exc
280
+
281
+ @staticmethod
282
+ def _http_error_detail(exc: urllib.error.HTTPError) -> Tuple[Optional[int], str]:
283
+ """Extracts (JSON-RPC code, message) from an HTTP error body (read once)."""
284
+ try:
285
+ raw = exc.read().decode("utf-8", "replace")
286
+ except Exception:
287
+ return None, str(exc)
288
+ try:
289
+ err = json.loads(raw).get("error")
290
+ if isinstance(err, dict):
291
+ return err.get("code"), err.get("message") or raw.strip() or str(exc)
292
+ if isinstance(err, str):
293
+ return None, err
294
+ except Exception:
295
+ pass
296
+ return None, raw.strip() or str(exc)
188
297
 
189
298
  @classmethod
190
299
  def _resolve_client_url(cls, runtime: str = "auto", target: Optional[str] = None, workspace_dir: Optional[str] = None) -> str:
@@ -257,9 +366,14 @@ class OUMVGateway:
257
366
 
258
367
  @classmethod
259
368
  def get_live_ports(cls, workspace_dir: Optional[str] = None) -> List[int]:
260
- """Returns localhost ports from active workspace/global OUMV runtime descriptors without blocking scans."""
261
- import urllib.parse
369
+ """Ports from OUMV runtime descriptors that are fresh AND actually listening.
370
+
371
+ Guards that hard-block raw curl rely on this list, so a descriptor left behind
372
+ by a crashed dev server (or a port later reused by another process) must not
373
+ count as a live runtime.
374
+ """
262
375
  ws = workspace_dir or get_active_workspace()
376
+ now = time.time()
263
377
  ports: List[int] = []
264
378
  for lp in (
265
379
  cls.global_runtime_file(ws),
@@ -269,14 +383,22 @@ class OUMVGateway:
269
383
  if not os.path.isfile(lp):
270
384
  continue
271
385
  try:
386
+ if (now - os.path.getmtime(lp)) > cls._DESCRIPTOR_MAX_AGE_SEC:
387
+ continue
272
388
  with open(lp, "r", encoding="utf-8") as f:
273
389
  data = json.load(f)
274
390
  for sec in ("frontend", "backend"):
275
391
  url = (data.get(sec) or {}).get("url")
276
- if url:
277
- parsed = urllib.parse.urlparse(url)
278
- if parsed.port and parsed.port not in ports:
279
- ports.append(int(parsed.port))
392
+ if not url:
393
+ continue
394
+ parsed = urllib.parse.urlparse(url)
395
+ if not parsed.port:
396
+ continue
397
+ port = int(parsed.port)
398
+ if port in ports:
399
+ continue
400
+ if cls._is_port_open(parsed.hostname or "127.0.0.1", port):
401
+ ports.append(port)
280
402
  except Exception:
281
403
  pass
282
404
  return ports
@@ -286,6 +408,8 @@ class OUMVGateway:
286
408
  def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
287
409
  cls.mark_oumv_used(workspace_dir)
288
410
  cls.scan(workspace_dir=workspace_dir)
411
+ # A descriptor whose port is closed must not be reported as a live runtime.
412
+ dropped = cls._drop_stale_descriptor_endpoints()
289
413
  fe, be = cls._cached_fe, cls._cached_be
290
414
  ws = workspace_dir or get_active_workspace()
291
415
 
@@ -300,7 +424,7 @@ class OUMVGateway:
300
424
  be_stack = stack_info.get("backend") or {}
301
425
  be_unsupported = bool(be_stack) and not be_stack.get("oumv_supported", True) and not be
302
426
 
303
- return {
427
+ result: Dict[str, Any] = {
304
428
  "mode": "OUT_OF_THE_BOX_HYBRID",
305
429
  "frontend": fe or {
306
430
  "status": "DISCONNECTED",
@@ -322,6 +446,16 @@ class OUMVGateway:
322
446
  "detectedStack": stack_info,
323
447
  "workspace": ws,
324
448
  }
449
+ if dropped:
450
+ result["staleRuntimes"] = [
451
+ {
452
+ "kind": d.get("kind"),
453
+ "url": d.get("url"),
454
+ "reason": "runtime descriptor present but its port is closed (crashed dev server?)",
455
+ }
456
+ for d in dropped
457
+ ]
458
+ return result
325
459
 
326
460
  @staticmethod
327
461
  def _adapter_lifecycle(stack_info: Dict[str, Any], fe: Optional[Dict[str, Any]], be: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
@@ -588,9 +722,14 @@ class OUMVGateway:
588
722
  "source": replacement,
589
723
  "expectedVersion": expected_version,
590
724
  })
591
- except OUMVRpcError:
592
- raise
593
725
  except RuntimeError as e:
726
+ if isinstance(e, OUMVRpcError) and not isinstance(e, OUMVUnsupportedMethodError):
727
+ if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
728
+ # Explicit safety rejection (conflict, syntax, permission): obey it.
729
+ raise
730
+ # The runtime cannot mediate the edit at all; the offline path below
731
+ # performs the same guarded edit and reports why.
732
+ e = OUMVUnsupportedMethodError(str(e))
594
733
  # Out-of-the-box direct fallback when live dev-servers are offline
595
734
  if replacement is not None:
596
735
  abs_path = os.path.normpath(os.path.join(ws, path))
@@ -647,6 +786,16 @@ class OUMVGateway:
647
786
  if backup_path:
648
787
  result["backupPath"] = backup_path
649
788
  result["rollbackHint"] = f"Previous content backed up at {backup_path}"
789
+ if isinstance(e, OUMVUnsupportedMethodError):
790
+ # The runtime was reachable but has no applyEdit: the edit was
791
+ # mediated by the gateway instead. Say so instead of implying
792
+ # the runtime verified it.
793
+ result["mode"] = "RUNTIME_LACKS_APPLYEDIT_OFFLINE_FALLBACK"
794
+ result["runtimeFallbackReason"] = str(e)
795
+ result["message"] = (
796
+ "Live runtime does not implement oumv/applyEdit; edit applied by the gateway "
797
+ "with the same OCC, syntax-guard and backup checks"
798
+ )
650
799
  return result
651
800
  raise
652
801