tokensafe 5.0.0 → 5.0.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.
Files changed (53) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/assets/logo.svg +1 -13
  5. package/hooks/claude_code_hook.py +5 -1
  6. package/hooks/cursor_hook.py +1 -1
  7. package/kimi.plugin.json +3 -2
  8. package/package.json +1 -1
  9. package/plugin.json +1 -1
  10. package/rules/AGENTS.md +4 -3
  11. package/server.json +3 -3
  12. package/skills/oumv-protocol/SKILL.md +59 -0
  13. package/skills/token-optimizer/SKILL.md +5 -3
  14. package/skills/token-optimizer/references/mcp-tools.md +1 -1
  15. package/tokensafe/adapter_core.py +62 -18
  16. package/tokensafe/atomic_io.py +20 -16
  17. package/tokensafe/auto_inject.py +2 -2
  18. package/tokensafe/backend_release.py +3 -3
  19. package/tokensafe/batch_editor.py +299 -10
  20. package/tokensafe/batch_search.py +53 -0
  21. package/tokensafe/bounded_flock.py +60 -0
  22. package/tokensafe/burn_monitor.py +60 -2
  23. package/tokensafe/call_context.py +158 -0
  24. package/tokensafe/cli.py +41 -13
  25. package/tokensafe/compactor.py +87 -5
  26. package/tokensafe/context_index.py +3 -0
  27. package/tokensafe/dashboard.py +119 -43
  28. package/tokensafe/environment_auditor.py +30 -2
  29. package/tokensafe/fts_index.py +3 -0
  30. package/tokensafe/graph_engine.py +246 -29
  31. package/tokensafe/installer.py +72 -13
  32. package/tokensafe/loop_detector.py +8 -20
  33. package/tokensafe/mcp_server.py +1084 -188
  34. package/tokensafe/metrics.py +173 -46
  35. package/tokensafe/oumv_brief.py +144 -8
  36. package/tokensafe/oumv_gateway.py +689 -222
  37. package/tokensafe/oumv_home.py +259 -0
  38. package/tokensafe/oumv_policy.py +64 -1
  39. package/tokensafe/proc_run.py +162 -0
  40. package/tokensafe/proxy.py +78 -8
  41. package/tokensafe/retrofit.py +484 -82
  42. package/tokensafe/route_index.py +2 -0
  43. package/tokensafe/savings.py +10 -2
  44. package/tokensafe/scoped_search.py +77 -0
  45. package/tokensafe/session_brief.py +17 -2
  46. package/tokensafe/stack_summary.py +73 -0
  47. package/tokensafe/syntax_guard.py +8 -2
  48. package/tokensafe/telemetry_sync.py +1 -1
  49. package/tokensafe/version_checker.py +1 -1
  50. package/tokensafe/web_reader.py +53 -4
  51. package/tokensafe/workspace_roots.py +127 -9
  52. package/assets/social/linkedin_banner.png +0 -0
  53. package/assets/social/tokensafe_logo_square.png +0 -0
@@ -22,6 +22,7 @@ from typing import List, Tuple, Optional, Any, Dict
22
22
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
23
  sys.path.insert(0, BASE_DIR)
24
24
 
25
+ from tokensafe import call_context as _call_context
25
26
  from tokensafe.compactor import PromptCompactor
26
27
  from tokensafe.skeletonizer import Skeletonizer
27
28
  from tokensafe.slicer import ToolSlicer
@@ -44,13 +45,22 @@ from tokensafe import route_index
44
45
  from tokensafe import oumv_policy
45
46
  from tokensafe.license_manager import LicenseManager
46
47
  from tokensafe.paths import get_active_workspace, is_plugin_or_system_dir
47
- from tokensafe.workspace_roots import known_roots, rebase_edits, register_roots, resolve_input_path
48
+ from tokensafe.workspace_roots import (
49
+ known_roots,
50
+ client_roots,
51
+ primary_client_root,
52
+ rebase_edits,
53
+ register_roots,
54
+ resolve_input_path,
55
+ roots_from_list_result,
56
+ set_client_roots,
57
+ )
48
58
  from tokensafe.win_paths import is_within
49
59
  from tokensafe.session_context import current_root, current_session_id
50
60
 
51
61
  SERVER_INFO = {
52
62
  "name": "tokensafe-mcp",
53
- "version": "5.0.0"
63
+ "version": "5.0.2"
54
64
  }
55
65
 
56
66
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -95,6 +105,13 @@ def _delivered_key(path: str, symbol: str, dep_mode: str) -> str:
95
105
 
96
106
  def _ensure_delivered_loaded() -> None:
97
107
  """Loads this session's delivered snapshot once per process."""
108
+ # Tool calls run concurrently: two reads must not clear and reload the map
109
+ # (and the epoch) under each other. The lock is reentrant.
110
+ with _DELIVERED_LOCK:
111
+ _ensure_delivered_loaded_locked()
112
+
113
+
114
+ def _ensure_delivered_loaded_locked() -> None:
98
115
  global _EPOCH_GEN, _DELIVERED_SESSION
99
116
  session_id = str(_mcp_session_id() or "")
100
117
  if _DELIVERED_SESSION == session_id:
@@ -198,7 +215,7 @@ def _resolve_read_cache_path(path: str, root: Any = None) -> str:
198
215
  try:
199
216
  resolved, _meta_info, err = resolve_input_path(
200
217
  raw,
201
- base=root or _workspace_root(),
218
+ base=[root, _workspace_root()],
202
219
  mode="read",
203
220
  must_exist=True,
204
221
  )
@@ -267,6 +284,12 @@ def _workspace_root() -> Optional[str]:
267
284
  cwd = os.getcwd()
268
285
  if cwd and os.path.isdir(cwd) and not is_plugin_or_system_dir(cwd):
269
286
  return cwd
287
+ # A GUI host spawns the server with cwd `/`: the roots the client declared
288
+ # for this connection outrank the machine-wide marker, which another
289
+ # session's hooks may have rewritten to an unrelated repo.
290
+ client_root = primary_client_root()
291
+ if client_root:
292
+ return client_root
270
293
  return get_active_workspace() or cwd or None
271
294
 
272
295
 
@@ -350,6 +373,9 @@ def _oumv_default_workspace() -> Optional[str]:
350
373
  cwd = os.getcwd()
351
374
  if _plausible_project_root(cwd):
352
375
  return cwd
376
+ client_root = primary_client_root()
377
+ if client_root:
378
+ return client_root
353
379
  marker = get_active_workspace()
354
380
  if marker:
355
381
  return marker
@@ -715,6 +741,7 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
715
741
  "/api/products'), or DOM element "
716
742
  "('#submit-btn')",
717
743
  'type': 'string'},
744
+ 'requestId': {'type': 'string', 'description': 'Optional OUMV requestId (cancellable; echoed by live results)'},
718
745
  'workspace_dir': {'type': 'string'}},
719
746
  'type': 'object'},
720
747
  'name': 'oumv_observe'},
@@ -736,6 +763,7 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
736
763
  'target': { 'description': 'Target component ID, state key, endpoint, '
737
764
  'or UI element',
738
765
  'type': 'string'},
766
+ 'requestId': {'type': 'string', 'description': 'Optional OUMV requestId (cancellable; echoed by live results)'},
739
767
  'workspace_dir': {'type': 'string'}},
740
768
  'type': 'object'},
741
769
  'name': 'oumv_understand'},
@@ -756,6 +784,7 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
756
784
  'enum': ['frontend', 'backend', 'auto'],
757
785
  'type': 'string'},
758
786
  'symbol': {'description': 'Target symbol to edit', 'type': 'string'},
787
+ 'requestId': {'type': 'string', 'description': 'Optional OUMV requestId (cancellable; echoed by live results)'},
759
788
  'workspace_dir': {'type': 'string'}},
760
789
  'required': ['path'],
761
790
  'type': 'object'},
@@ -788,6 +817,7 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
788
817
  'target': { 'description': "Action target (component ID, e.g. 'cart', "
789
818
  "or 'POST /api/v1/orders' or '#submit-btn')",
790
819
  'type': 'string'},
820
+ 'requestId': {'type': 'string', 'description': 'Optional OUMV requestId (cancellable; echoed by live results)'},
791
821
  'workspace_dir': {'type': 'string'}},
792
822
  'required': ['target'],
793
823
  'type': 'object'},
@@ -1187,7 +1217,12 @@ TOOLS = [{'name': 'smart_read_file',
1187
1217
  "expectedVersion and symbol for the offline static "
1188
1218
  'checks'},
1189
1219
  'requestId': {'type': 'string',
1190
- 'description': 'cancel: the requestId echoed by the target call'},
1220
+ 'description': 'observe/understand/mutate/verify/preview/build: '
1221
+ 'optional caller-chosen id sent to the runtime '
1222
+ '(a uuid is generated otherwise; live results echo '
1223
+ 'it as requestId). cancel: the id to cancel; or '
1224
+ "pass target='last' for the most recent in-flight "
1225
+ 'request'},
1191
1226
  'workspace_dir': {'type': 'string',
1192
1227
  'description': 'Target repo root; for '
1193
1228
  'status/observe/understand/verify/graph/index/preview/build/cancel '
@@ -1484,6 +1519,13 @@ def _shared_batch_root(paths: List[str], real_cwd: str) -> Optional[str]:
1484
1519
  return shared
1485
1520
 
1486
1521
 
1522
+ def _oumv_request_id(args: dict) -> Optional[str]:
1523
+ """Caller-supplied OUMV requestId (spec §2.1), or None to have one generated."""
1524
+ raw = args.get("requestId") if isinstance(args, dict) else None
1525
+ value = str(raw or "").strip()
1526
+ return value[:128] or None
1527
+
1528
+
1487
1529
  def _oumv_workspace_arg(args: dict, allow_path: bool = False) -> Tuple[Optional[str], Optional[str]]:
1488
1530
  """Validated workspace root for an OUMV call; falls back to a per-server default.
1489
1531
 
@@ -2663,7 +2705,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
2663
2705
  # Same resolution as the read (the call's `root` first): rebuilding the
2664
2706
  # path from the session root recorded worktree B's content under
2665
2707
  # worktree A's file and later served it there as a pointer hit.
2666
- abs_path = _resolve_read_cache_path(path, args.get("root")) if path else ""
2708
+ abs_path = _resolve_read_cache_path(path, args.get("root") or args.get("cwd")) if path else ""
2667
2709
  if text_out and abs_path and not is_ranged and not is_quota_truncated:
2668
2710
  active_ws = _workspace_root()
2669
2711
  cur_hash = AgentFirewall._file_content_hash(abs_path)
@@ -2807,9 +2849,13 @@ def _parse_if_modified_since(value: Any) -> Optional[tuple]:
2807
2849
  from datetime import datetime
2808
2850
 
2809
2851
  iso = raw.replace("Z", "+00:00")
2852
+ fraction = re.search(r"([T ]\d{2}:\d{2}:\d{2})[.,](\d+)", iso)
2853
+ digits = min(len(fraction.group(2)), 6) if fraction else 0
2854
+ if fraction:
2855
+ # Python < 3.11 fromisoformat only takes exactly 3 or 6 fraction
2856
+ # digits after a '.': normalize to 6 before parsing.
2857
+ iso = iso[:fraction.start()] + fraction.group(1) + "." + fraction.group(2)[:6].ljust(6, "0") + iso[fraction.end():]
2810
2858
  parsed = datetime.fromisoformat(iso)
2811
- fraction = re.search(r"[T ]\d{2}:\d{2}:\d{2}[.,](\d+)", iso)
2812
- digits = min(len(fraction.group(1)), 6) if fraction else 0
2813
2859
  unit = 10 ** (9 - digits)
2814
2860
  # Integer arithmetic: float timestamp() * 1e9 is off by hundreds of ns.
2815
2861
  whole = int(parsed.replace(microsecond=0).timestamp())
@@ -2950,7 +2996,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2950
2996
  elif raw_sc and raw_sc.lower() not in ("all", "code", "config"):
2951
2997
  q_spec["file_type"] = raw_sc.lstrip(".")
2952
2998
  rerouted = {"queries": [q_spec]}
2953
- explicit_root = args.get("cwd") or args.get("project_path")
2999
+ explicit_root = args.get("root") or args.get("cwd") or args.get("project_path")
2954
3000
  if explicit_root:
2955
3001
  rerouted["cwd"] = explicit_root
2956
3002
  args = rerouted
@@ -3085,7 +3131,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3085
3131
  if path:
3086
3132
  resolved, _meta_info, resolve_err = resolve_input_path(
3087
3133
  path,
3088
- base=args.get("root") or active_ws,
3134
+ base=[args.get("root") or args.get("cwd"), active_ws],
3089
3135
  mode="read",
3090
3136
  must_exist=True,
3091
3137
  )
@@ -3409,9 +3455,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3409
3455
 
3410
3456
  if start_line is None and end_line is None:
3411
3457
  cur_hash = AgentFirewall._file_content_hash(abs_path)
3412
- _ensure_delivered_loaded()
3413
- delivered = _IN_PROCESS_DELIVERED.get((abs_path, sym_clean, eff_dep_mode))
3414
- already_here = bool(delivered and cur_hash and delivered == (cur_hash, _EPOCH_GEN))
3458
+ with _DELIVERED_LOCK:
3459
+ _ensure_delivered_loaded()
3460
+ delivered = _IN_PROCESS_DELIVERED.get((abs_path, sym_clean, eff_dep_mode))
3461
+ already_here = bool(delivered and cur_hash and delivered == (cur_hash, _EPOCH_GEN))
3415
3462
  allow_pointer = (not force_full) and _client_supports_pointers() and already_here
3416
3463
  is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
3417
3464
  _mcp_session_id(),
@@ -3596,22 +3643,43 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3596
3643
  max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
3597
3644
 
3598
3645
  active_ws = _workspace_root()
3646
+ # `root`/`cwd` were ignored here: a relative target joined the session
3647
+ # root (possibly another repo) and then the process cwd (`/` for a
3648
+ # GUI-spawned server), answering "File(s) not found: /pkg/x.py".
3649
+ explicit_root = args.get("root") or args.get("cwd")
3650
+ bundle_bases = [explicit_root, active_ws]
3599
3651
  by_file: Dict[str, List[str]] = {}
3652
+ unresolved: List[str] = []
3600
3653
  for t in targets:
3601
3654
  if not isinstance(t, dict) or not str(t.get("path") or "").strip():
3602
3655
  return _fallback_error("smart_bundle", "each target must be {path: str, symbol?: str}")
3603
3656
  raw_p = str(t["path"]).strip()
3604
- if not os.path.isabs(raw_p) and active_ws and os.path.exists(os.path.join(active_ws, raw_p)):
3605
- target_p = os.path.abspath(os.path.join(active_ws, raw_p))
3606
- else:
3657
+ if os.path.isabs(raw_p):
3607
3658
  target_p = os.path.abspath(raw_p)
3659
+ else:
3660
+ resolved_p, _meta_info, _resolve_err = resolve_input_path(
3661
+ raw_p, base=bundle_bases, mode="read", must_exist=True
3662
+ )
3663
+ if not resolved_p:
3664
+ unresolved.append(raw_p)
3665
+ continue
3666
+ target_p = resolved_p
3608
3667
  if is_plugin_or_system_dir(target_p):
3609
3668
  return _fallback_error("smart_bundle", f"refusing to read from system root or plugin dir '{raw_p}'")
3610
3669
  by_file.setdefault(target_p, []).append(str(t.get("symbol") or "").strip())
3611
3670
 
3612
- missing = [p for p in by_file if not os.path.isfile(p)]
3671
+ missing = unresolved + [p for p in by_file if not os.path.isfile(p)]
3613
3672
  if missing:
3614
- return {"isError": True, "content": [{"type": "text", "text": f"File(s) not found: {', '.join(missing)}"}]}
3673
+ base_note = next(
3674
+ (b for b in bundle_bases if b and os.path.dirname(os.path.abspath(str(b))) != os.path.abspath(str(b))),
3675
+ None,
3676
+ )
3677
+ where = (
3678
+ f" (relative paths resolved against '{os.path.abspath(str(base_note))}')"
3679
+ if unresolved and base_note
3680
+ else (" (no root: pass 'root' or 'cwd' with repo-relative paths)" if unresolved else "")
3681
+ )
3682
+ return {"isError": True, "content": [{"type": "text", "text": f"File(s) not found: {', '.join(missing)}{where}"}]}
3615
3683
 
3616
3684
  bundle_max_bytes = 512 * 1024
3617
3685
  file_sections: List[Tuple[str, str, List[str]]] = [] # (abs_path, skeleton, import_lines)
@@ -3639,21 +3707,22 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3639
3707
  try:
3640
3708
  graph, rel = GraphEngine.for_file(p)
3641
3709
  if graph and rel:
3642
- for sym in keep:
3643
- # A class target's call edges live on its methods:
3644
- # resolve every qual key under the target symbol.
3645
- keys = [k for k in graph.symbols if k == f"{rel}::{sym}" or k.startswith(f"{rel}::{sym}::")]
3646
- for key in keys[:12]:
3647
- qual = key[len(rel) + 2:]
3648
- nb = graph.get_neighborhood(qual, target_file=rel)
3649
- for dep_key in sorted(nb.get("one_hop", [])):
3650
- dep_sym = graph.symbols.get(dep_key)
3651
- if not dep_sym:
3652
- continue
3653
- line = f" {qual} -> {dep_key.split('::', 1)[-1]}: {dep_sym.signature.strip()[:160]}"
3654
- if line not in seen_dep_lines:
3655
- seen_dep_lines.add(line)
3656
- dep_lines.append(line)
3710
+ with graph.snapshot():
3711
+ for sym in keep:
3712
+ # A class target's call edges live on its methods:
3713
+ # resolve every qual key under the target symbol.
3714
+ keys = [k for k in graph.symbols if k == f"{rel}::{sym}" or k.startswith(f"{rel}::{sym}::")]
3715
+ for key in keys[:12]:
3716
+ qual = key[len(rel) + 2:]
3717
+ nb = graph.get_neighborhood(qual, target_file=rel)
3718
+ for dep_key in sorted(nb.get("one_hop", [])):
3719
+ dep_sym = graph.symbols.get(dep_key)
3720
+ if not dep_sym:
3721
+ continue
3722
+ line = f" {qual} -> {dep_key.split('::', 1)[-1]}: {dep_sym.signature.strip()[:160]}"
3723
+ if line not in seen_dep_lines:
3724
+ seen_dep_lines.add(line)
3725
+ dep_lines.append(line)
3657
3726
  except Exception:
3658
3727
  pass
3659
3728
 
@@ -4240,7 +4309,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4240
4309
  tree_output = build_dir_tree(abs_path, max_depth=depth, max_entries=max_entries)
4241
4310
  tree_tokens = count_tokens(tree_output)
4242
4311
  # Estimate equivalent tokens from multiple verbose ls -la calls (at least ~800 tokens)
4243
- est_orig_tokens = max(800, tree_tokens * 6)
4312
+ est_orig_tokens = tree_tokens * 6 # counterfactual multiplier, labelled estimated; no constant floor
4244
4313
  tracker.record_event(
4245
4314
  session_id=_mcp_session_id(),
4246
4315
  event_type="DIR_LIST",
@@ -4278,17 +4347,27 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4278
4347
  single_file: Optional[str] = None
4279
4348
  if raw_path:
4280
4349
  if not os.path.isabs(raw_path):
4281
- if base_dir and os.path.isdir(os.path.join(base_dir, raw_path)):
4282
- target_path = os.path.abspath(os.path.join(base_dir, raw_path))
4283
- else:
4284
- target_path = os.path.abspath(raw_path)
4285
- if not os.path.exists(target_path):
4286
- scope_root = base_dir or active_ws or os.getcwd()
4350
+ # A FILE path used to join `cwd` only when the join was a
4351
+ # directory and otherwise fell back to the process cwd, which is
4352
+ # `/` for a GUI-spawned server: `tokensafe/x.py` became
4353
+ # `/tokensafe/x.py`. Files and directories now resolve the same
4354
+ # way: explicit cwd/root, then the session root, never `/`.
4355
+ resolved, _meta_info, _resolve_err = resolve_input_path(
4356
+ raw_path, base=[base_dir, active_ws], mode="read", must_exist=True
4357
+ )
4358
+ if not resolved:
4359
+ scope_root = next(
4360
+ (b for b in (base_dir, active_ws) if b and os.path.dirname(os.path.abspath(b)) != os.path.abspath(b)),
4361
+ None,
4362
+ )
4363
+ tried = os.path.abspath(os.path.join(scope_root, raw_path)) if scope_root else raw_path
4287
4364
  return _fallback_error(
4288
4365
  "scoped_search",
4289
- f"path '{raw_path}' does not exist (resolved to '{target_path}' from '{scope_root}'). "
4290
- f"Pass the repo root as 'cwd' plus a repo-relative path, or an absolute path.",
4366
+ f"path '{raw_path}' does not exist (resolved to '{tried}' from '{scope_root or 'no root'}'). "
4367
+ f"Pass the repo root as 'cwd' plus a repo-relative path, or an absolute path."
4368
+ + (f" {_resolve_err}" if _resolve_err and "ambiguous" in _resolve_err else ""),
4291
4369
  )
4370
+ target_path = resolved
4292
4371
  else:
4293
4372
  target_path = os.path.abspath(raw_path)
4294
4373
 
@@ -4305,6 +4384,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4305
4384
  target_path = os.path.abspath(str(base_dir)) if inside_base else os.path.dirname(single_file)
4306
4385
  if is_plugin_or_system_dir(target_path):
4307
4386
  return _fallback_error("scoped_search", f"refusing to search system root or plugin dir '{raw_path}'")
4387
+ elif raw_cwd and base_dir:
4388
+ # An explicit cwd/root is the search root. `_resolve_project_root`
4389
+ # never reads `cwd`, so `scoped_search(cwd=X, query=...)` searched
4390
+ # the session root (possibly another repo) instead of X.
4391
+ target_path = base_dir
4392
+ if is_plugin_or_system_dir(target_path):
4393
+ return _fallback_error("scoped_search", f"refusing to search system root or plugin dir '{raw_cwd}'")
4308
4394
  else:
4309
4395
  resolved_path, err = _resolve_project_root(args)
4310
4396
  if err or not resolved_path:
@@ -4464,17 +4550,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4464
4550
  if not lock_p:
4465
4551
  active_ws = _workspace_root()
4466
4552
  if active_ws and hasattr(LockfileReducer, "find_lockfile"):
4467
- orig_cwd = os.getcwd()
4553
+ # Never os.chdir here: the cwd is process-wide and tool calls
4554
+ # run concurrently, so every parallel call resolving a relative
4555
+ # path would briefly see this workspace as its cwd.
4468
4556
  try:
4469
- os.chdir(active_ws)
4470
- lock_p = LockfileReducer.find_lockfile()
4557
+ lock_p = LockfileReducer.find_lockfile(directory=active_ws)
4471
4558
  except Exception:
4472
4559
  lock_p = None
4473
- finally:
4474
- try:
4475
- os.chdir(orig_cwd)
4476
- except Exception:
4477
- pass
4478
4560
  res = LockfileReducer.query_dependency(lock_p, pkg)
4479
4561
  lock_bytes = res.pop("_lockfile_bytes", 0)
4480
4562
  json_text = json.dumps(res, indent=2, ensure_ascii=False)
@@ -4607,7 +4689,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4607
4689
  ws, ws_err = _oumv_workspace_arg(args)
4608
4690
  if ws_err:
4609
4691
  return _fallback_error("oumv_observe", ws_err)
4610
- res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws, path=raw_path)
4692
+ res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws, path=raw_path,
4693
+ request_id=_oumv_request_id(args))
4611
4694
  try:
4612
4695
  _observe_seed_read_cache(res, lvl, tgt, raw_path, ws)
4613
4696
  except Exception:
@@ -4644,7 +4727,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4644
4727
  ws, ws_err = _oumv_workspace_arg(args)
4645
4728
  if ws_err:
4646
4729
  return _fallback_error("oumv_understand", ws_err)
4647
- res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt, workspace_dir=ws, path=raw_path)
4730
+ res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt, workspace_dir=ws, path=raw_path,
4731
+ request_id=_oumv_request_id(args))
4648
4732
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4649
4733
  except Exception as e:
4650
4734
  return _fallback_error("oumv_understand", f"failed to query OUMV understanding: {e}")
@@ -4660,7 +4744,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4660
4744
  ws, ws_err = _oumv_workspace_arg(args)
4661
4745
  if ws_err:
4662
4746
  return _fallback_error("oumv_mutate", ws_err)
4663
- res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt, workspace_dir=ws)
4747
+ res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt,
4748
+ workspace_dir=ws, request_id=_oumv_request_id(args))
4664
4749
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4665
4750
  except Exception as e:
4666
4751
  return _fallback_error("oumv_mutate", f"failed to apply OUMV mutation: {e}")
@@ -4676,7 +4761,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4676
4761
  if ws_err:
4677
4762
  return _fallback_error("oumv_verify", ws_err)
4678
4763
  sandbox = args.get("sandbox") if isinstance(args.get("sandbox"), dict) else None
4679
- res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws, sandbox=sandbox)
4764
+ res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws,
4765
+ sandbox=sandbox, request_id=_oumv_request_id(args))
4680
4766
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4681
4767
  except Exception as e:
4682
4768
  return _fallback_error(
@@ -4733,7 +4819,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4733
4819
  if not p:
4734
4820
  return _fallback_error("oumv_preview", "missing required 'path'")
4735
4821
  res = OUMVGateway.preview(path=p, symbol=sym, replacement=rep, expected_version=ev,
4736
- batch=batch, runtime=rt, workspace_dir=ws)
4822
+ batch=batch, runtime=rt, workspace_dir=ws,
4823
+ request_id=_oumv_request_id(args))
4737
4824
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4738
4825
  except Exception as e:
4739
4826
  return _fallback_error("oumv_preview", f"failed to preview OUMV mutation: {e}")
@@ -4748,7 +4835,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4748
4835
  ws, ws_err = _oumv_workspace_arg(args)
4749
4836
  if ws_err:
4750
4837
  return _fallback_error("oumv_build", ws_err)
4751
- res = OUMVGateway.build(command=cmd, target=tgt, timeout_ms=tms, runtime=rt, workspace_dir=ws)
4838
+ res = OUMVGateway.build(command=cmd, target=tgt, timeout_ms=tms, runtime=rt, workspace_dir=ws,
4839
+ request_id=_oumv_request_id(args))
4752
4840
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4753
4841
  except Exception as e:
4754
4842
  return _fallback_error("oumv_build", f"failed to run OUMV build: {e}")
@@ -4795,9 +4883,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4795
4883
  verify_off = isinstance(verify, str) and verify.strip().lower() in (
4796
4884
  "off", "none", "skip", "false", "0",
4797
4885
  )
4886
+ verify_implicit = False
4798
4887
  if verify_off:
4799
4888
  verify = None
4800
4889
  elif verify in (None, "") and _verify_default_enabled():
4890
+ verify_implicit = True
4801
4891
  # The strongest convergence lever: the edit and its verdict arrive in
4802
4892
  # one call. A red suite is reported, not rolled back, unless the
4803
4893
  # caller sets strict_verify.
@@ -4855,16 +4945,27 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4855
4945
  return _fallback_error("apply_edits", str(res.get("error") or "verify command blocked"))
4856
4946
  applied_files = res.get("applied_files") or []
4857
4947
  lines = []
4948
+ verify_red = isinstance(res.get("verify"), dict) and res["verify"].get("passed") is False
4949
+ edit_errors = int(res.get("failed_count") or 0)
4858
4950
  if res.get("success"):
4859
4951
  action_desc = "Validated" if dry_run else "Applied"
4860
4952
  lines.append(f"✔ {action_desc} {res.get('applied_count', 0)} file(s) successfully.")
4953
+ elif verify_red and not edit_errors and res.get("edits_applied"):
4954
+ # The edit landed; only the verdict is red. "Batch edits failed (0 error(s))"
4955
+ # sent agents into re-applying an edit that was already on disk.
4956
+ lines.append(
4957
+ f"✔ Applied {res.get('applied_count', 0)} file(s); ✖ inline verify failed — edits kept "
4958
+ "(strict_verify=true rolls back on a red verify)."
4959
+ )
4960
+ elif verify_red and not edit_errors and res.get("rolled_back"):
4961
+ lines.append("✖ Inline verify failed — edits rolled back (strict_verify).")
4861
4962
  else:
4862
- lines.append(f"✖ Batch edits failed ({res.get('failed_count', 0)} error(s)).")
4963
+ lines.append(f"✖ Batch edits failed ({edit_errors} error(s)).")
4863
4964
  for f in res.get("failed_files", []):
4864
4965
  lines.append(f" - `{f.get('path')}`: {f.get('error')}")
4865
4966
 
4866
4967
  if res.get("applied_files"):
4867
- if not res.get("success"):
4968
+ if not res.get("success") and edit_errors:
4868
4969
  lines.append(f"Applied {len(res['applied_files'])} file(s) before error/verify:")
4869
4970
  for f in res.get("applied_files", []):
4870
4971
  h_cnt = f.get("hunks", 0)
@@ -4894,6 +4995,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4894
4995
  lines.append(f"\nInline Verify ({v.get('command')}): {status_sym} (exit {v.get('exit_code')}, {v.get('duration_seconds', 0)}s)")
4895
4996
  if v.get("note"):
4896
4997
  lines.append(f" ↳ {v['note']}")
4998
+ if verify_implicit:
4999
+ lines.append(" ↳ verify ran by default (verify='auto'); pass verify='off' to skip it")
4897
5000
  if v.get("output"):
4898
5001
  lines.append("```text\n" + v["output"] + "\n```")
4899
5002
  elif v.get("error"):
@@ -4902,7 +5005,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4902
5005
  # Static blast radius (warm graph only): one advisory line, no crawl
4903
5006
  # and no mandatory follow-up call.
4904
5007
  try:
4905
- if res.get("success") and applied_files and not res.get("dry_run"):
5008
+ if res.get("edits_applied") and applied_files:
4906
5009
  warm = GraphEngine.get_cached(cwd)
4907
5010
  if warm is not None:
4908
5011
  session_id = _mcp_session_id()
@@ -4999,7 +5102,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4999
5102
  "pattern": args.get("query") or args.get("pattern"),
5000
5103
  "type": args.get("type", "text"),
5001
5104
  }
5002
- has_explicit_root = bool(args.get("cwd") or args.get("project_path"))
5105
+ has_explicit_root = bool(args.get("root") or args.get("cwd") or args.get("project_path"))
5003
5106
  for key in ("path", "glob", "file_type", "scope", "output_mode",
5004
5107
  "case_sensitive", "max_results", "use_regex"):
5005
5108
  if key == "path" and not has_explicit_root:
@@ -5393,6 +5496,20 @@ def _tool_timeout(tool_name: str, tool_args: dict) -> float:
5393
5496
  declared = fallback if has_verify else 0
5394
5497
  if declared > 0:
5395
5498
  return min(max(MCP_TOOL_TIMEOUT, declared + 5.0), 180.0)
5499
+ if tool_name == "oumv_build" or (tool_name == "oumv" and str(tool_args.get("action") or "").lower() == "build"):
5500
+ # oumv build forwards timeout_ms to the runtime; the transport must outlive
5501
+ # it or the build keeps running after the caller was told it failed.
5502
+ try:
5503
+ declared_ms = int(tool_args.get("timeout_ms") or 0)
5504
+ except (TypeError, ValueError):
5505
+ declared_ms = 0
5506
+ if declared_ms > 0:
5507
+ return min(max(MCP_GRAPH_TIMEOUT, declared_ms / 1000.0 + 10.0), 180.0)
5508
+ if tool_name in ("oumv_mutate", "oumv_preview", "oumv_verify", "oumv_build"):
5509
+ # Internal oumv names (full profile) get the public oumv budget: their
5510
+ # runtime RPCs are allowed 20-25 s (oumv_gateway._RPC_TIMEOUTS), and an
5511
+ # 8 s cut reported a write as failed while it still held the workspace lock.
5512
+ return max(MCP_TOOL_TIMEOUT, MCP_GRAPH_TIMEOUT)
5396
5513
  if tool_name in _GRAPH_TOOLS:
5397
5514
  # Graph-backed calls may pay a one-time cold crawl; it is cached on disk, so
5398
5515
  # the next call is milliseconds. TOKENSAFE_MCP_GRAPH_TIMEOUT tunes the ceiling.
@@ -5479,6 +5596,9 @@ def _reload_due(now: Optional[float] = None) -> bool:
5479
5596
  """True when a pending upgrade may take the server down: armed AND idle."""
5480
5597
  if not _RELOAD_PENDING or not _auto_reload_enabled():
5481
5598
  return False
5599
+ if _in_flight_count() or _write_in_progress():
5600
+ # Never take the process down under a running tool call or a write.
5601
+ return False
5482
5602
  return (time.time() if now is None else now) - _LAST_ACTIVITY >= _reload_idle_seconds()
5483
5603
 
5484
5604
 
@@ -5495,19 +5615,836 @@ def _start_reload_watchdog(idle_sec: float) -> None:
5495
5615
  if not _SERVER_ACTIVE:
5496
5616
  return
5497
5617
  if _reload_due():
5498
- try:
5499
- sys.stdout.flush()
5500
- except Exception:
5501
- pass
5502
- os._exit(0)
5618
+ _exit_for_restart("", still_due=_reload_due)
5503
5619
 
5504
5620
  threading.Thread(target=_watch, name="tokensafe-mcp-reload", daemon=True).start()
5505
5621
 
5506
5622
 
5623
+ _CLIENT_HAS_ROOTS = False
5624
+ # Id of the outstanding server->client `roots/list` request (one at a time).
5625
+ _PENDING_ROOTS_REQUEST_ID: List[Optional[str]] = [None]
5626
+ _ROOTS_REQUEST_SEQ = [0]
5627
+
5628
+ # --------------------------------------------------------------------------- #
5629
+ # Wire output. Tool calls answer from worker threads, so every message is one
5630
+ # whole newline-terminated line written and flushed under one lock: two
5631
+ # responses can never interleave or leave a partial line on stdout.
5632
+ # --------------------------------------------------------------------------- #
5633
+ _STDOUT_LOCK = threading.Lock()
5634
+
5635
+
5636
+ def _write_message(message: Dict[str, Any]) -> bool:
5637
+ """Writes one JSON-RPC message as a single line. False when stdout is gone."""
5638
+ try:
5639
+ data = json.dumps(message, ensure_ascii=False) + "\n"
5640
+ except Exception:
5641
+ return False
5642
+ with _STDOUT_LOCK:
5643
+ try:
5644
+ sys.stdout.write(data)
5645
+ sys.stdout.flush()
5646
+ return True
5647
+ except Exception:
5648
+ return False
5649
+
5650
+
5651
+ def _request_client_roots() -> None:
5652
+ """Sends `roots/list` to the client (MCP roots capability).
5653
+
5654
+ The answer is handled in the serve loop; until it arrives the previous
5655
+ precedence applies (session scope, spawn cwd, then the marker)."""
5656
+ _ROOTS_REQUEST_SEQ[0] += 1
5657
+ req_id = f"tokensafe-roots-{_ROOTS_REQUEST_SEQ[0]}"
5658
+ _PENDING_ROOTS_REQUEST_ID[0] = req_id
5659
+ if not _write_message({"jsonrpc": "2.0", "id": req_id, "method": "roots/list"}):
5660
+ _PENDING_ROOTS_REQUEST_ID[0] = None
5661
+
5662
+
5663
+ # --------------------------------------------------------------------------- #
5664
+ # Concurrent tools/call dispatch
5665
+ #
5666
+ # The read loop never runs a tool. Each tools/call gets a supervisor thread that
5667
+ # owns the answer (timeout, cancellation, the single response line) and a runner
5668
+ # thread that executes the handler. At most TOKENSAFE_MCP_WORKERS handlers run at
5669
+ # once; calls that write the same workspace root are serialized by a per-root
5670
+ # lock that the runner holds until the handler really returns, so a write that
5671
+ # outlived its timeout still blocks the next write instead of interleaving with
5672
+ # it. Cross-process write safety stays with the per-file advisory locks in
5673
+ # oumv_home (taken by apply_edits and OUMVGateway.mutate around read->check->write).
5674
+ # --------------------------------------------------------------------------- #
5675
+
5676
+ def _env_float(name: str, default: float, lo: float, hi: float) -> float:
5677
+ try:
5678
+ value = float(os.environ.get(name, "") or default)
5679
+ except (TypeError, ValueError):
5680
+ value = default
5681
+ return min(max(value, lo), hi)
5682
+
5683
+
5684
+ def _mcp_workers() -> int:
5685
+ return int(_env_float("TOKENSAFE_MCP_WORKERS", 8, 1, 64))
5686
+
5687
+
5688
+ def _queue_wait_seconds() -> float:
5689
+ """How long a call may wait for its workspace write lock / a worker slot."""
5690
+ return _env_float("TOKENSAFE_MCP_QUEUE_WAIT_SEC", 180.0, 0.05, 3600.0)
5691
+
5692
+
5693
+ def _drain_seconds() -> float:
5694
+ """Grace period for in-flight calls after stdin EOF."""
5695
+ return _env_float("TOKENSAFE_MCP_DRAIN_SEC", 5.0, 0.0, 600.0)
5696
+
5697
+
5698
+ _WORKER_SLOTS: Optional[threading.Semaphore] = None
5699
+ # Guards _ACTIVE_CALLS (answer pending) and _LIVE_RUNNERS (handler thread alive).
5700
+ # Reentrant: the restart path re-evaluates _reload_due() while holding it.
5701
+ _ACTIVE_LOCK = threading.RLock()
5702
+ _ACTIVE_CALLS: Dict[str, "_ToolCall"] = {}
5703
+ # Calls whose handler is running, answered or not: a timed-out handler stays
5704
+ # here (and keeps its workspace lock) until it really returns.
5705
+ _LIVE_RUNNERS: Dict[int, "_ToolCall"] = {}
5706
+ _SERVER_CLOSED = False
5707
+ _WS_LOCKS: Dict[str, "_RWLock"] = {}
5708
+ _WS_LOCKS_GUARD = threading.Lock()
5709
+
5710
+ # Tool names (public and internal) whose oumv action mutates workspace files.
5711
+ _OUMV_WRITE_ACTIONS = frozenset({"mutate", "preview"})
5712
+ # oumv actions that observe the built/running workspace: ordered against writes
5713
+ # (shared side of the per-root lock) so they never see a half-applied edit.
5714
+ _OUMV_SHARED_ACTIONS = frozenset({"build", "verify"})
5715
+ # A started write is awaited on EOF up to its own timeout plus this margin.
5716
+ _WRITE_DRAIN_MARGIN_SEC = 10.0
5717
+ # Hard bound on waiting for an in-progress file write/rename before exiting.
5718
+ _WRITE_IO_EXIT_WAIT_SEC = 30.0
5719
+
5720
+
5721
+ class _RWLock:
5722
+ """Per-workspace reader/writer lock with writer preference.
5723
+
5724
+ Writers (apply_edits, oumv mutate/preview, dict apply) are exclusive; the
5725
+ shared side (oumv build, oumv verify) admits any number of holders at once
5726
+ but never alongside a writer. A waiting writer blocks new readers, so a
5727
+ stream of verifies cannot starve a write. Acquisition polls `abort` so a
5728
+ queued call that was cancelled or timed out leaves the queue.
5729
+ """
5730
+
5731
+ def __init__(self) -> None:
5732
+ self._cond = threading.Condition(threading.Lock())
5733
+ self.readers = 0
5734
+ self.writer = False
5735
+ self.waiting_writers = 0
5736
+
5737
+ def acquire_read(self, abort=lambda: False) -> bool:
5738
+ with self._cond:
5739
+ while self.writer or self.waiting_writers:
5740
+ if abort():
5741
+ return False
5742
+ self._cond.wait(0.05)
5743
+ self.readers += 1
5744
+ return True
5745
+
5746
+ def release_read(self) -> None:
5747
+ with self._cond:
5748
+ self.readers -= 1
5749
+ self._cond.notify_all()
5750
+
5751
+ def acquire_write(self, abort=lambda: False) -> bool:
5752
+ with self._cond:
5753
+ self.waiting_writers += 1
5754
+ try:
5755
+ while self.writer or self.readers:
5756
+ if abort():
5757
+ return False
5758
+ self._cond.wait(0.05)
5759
+ self.writer = True
5760
+ return True
5761
+ finally:
5762
+ self.waiting_writers -= 1
5763
+ # A writer that gave up must wake readers it was holding off.
5764
+ self._cond.notify_all()
5765
+
5766
+ def release_write(self) -> None:
5767
+ with self._cond:
5768
+ self.writer = False
5769
+ self._cond.notify_all()
5770
+
5771
+ def acquire(self, mode: str, abort=lambda: False) -> bool:
5772
+ return self.acquire_write(abort) if mode == "write" else self.acquire_read(abort)
5773
+
5774
+ def release(self, mode: str) -> None:
5775
+ if mode == "write":
5776
+ self.release_write()
5777
+ else:
5778
+ self.release_read()
5779
+
5780
+
5781
+ def _call_key(msg_id: Any) -> str:
5782
+ try:
5783
+ return json.dumps(msg_id, sort_keys=True)
5784
+ except Exception:
5785
+ return repr(msg_id)
5786
+
5787
+
5788
+ def _workspace_lock(root: str) -> "_RWLock":
5789
+ with _WS_LOCKS_GUARD:
5790
+ lock = _WS_LOCKS.get(root)
5791
+ if lock is None:
5792
+ lock = _RWLock()
5793
+ _WS_LOCKS[root] = lock
5794
+ return lock
5795
+
5796
+
5797
+ def _is_write_call(tool_name: str, args: dict) -> bool:
5798
+ if tool_name == "apply_edits":
5799
+ return not bool(args.get("dry_run"))
5800
+ if tool_name == "oumv":
5801
+ return str(args.get("action") or "").strip().lower() in _OUMV_WRITE_ACTIONS
5802
+ if tool_name in ("oumv_mutate", "oumv_preview"):
5803
+ return True
5804
+ if tool_name == "run_helper" and str(args.get("action") or "").strip().lower() != "dict":
5805
+ return False
5806
+ if tool_name in ("run_helper", "dict_catalog"):
5807
+ cmd = str(args.get("command") or "")
5808
+ return bool(re.search(r"(^|\s)apply(\s|$)", cmd)) and "--dry-run" not in cmd
5809
+ return False
5810
+
5811
+
5812
+ def _is_shared_call(tool_name: str, args: dict) -> bool:
5813
+ """oumv build / verify: observe the workspace, so they wait out a write."""
5814
+ if tool_name in ("oumv_build", "oumv_verify"):
5815
+ action = "build" if tool_name == "oumv_build" else "verify"
5816
+ elif tool_name == "oumv":
5817
+ action = str(args.get("action") or "").strip().lower()
5818
+ else:
5819
+ return False
5820
+ if action not in _OUMV_SHARED_ACTIONS:
5821
+ return False
5822
+ # An explicitly static verify reads the source only, like observe.
5823
+ return not (action == "verify" and str(args.get("runtime") or "").strip().lower() == "static")
5824
+
5825
+
5826
+ def _lock_roots(tool_name: str, args: dict, mode: str) -> List[str]:
5827
+ """Workspace roots a call locks (sorted, realpath'd).
5828
+
5829
+ Each target path maps to its project root (the same marker walk the graph
5830
+ uses), so `root=sub/dir` and an absolute path into the same repo share one
5831
+ lock. When nothing names a path, the server's workspace is the root.
5832
+ """
5833
+ base = str(
5834
+ args.get("workspace_dir") or args.get("root") or args.get("cwd") or args.get("project_path") or ""
5835
+ ).strip()
5836
+ fallback = _workspace_root() or os.getcwd()
5837
+ if base and not os.path.isabs(base):
5838
+ base = os.path.join(fallback, base)
5839
+ base = base or fallback
5840
+ targets: List[str] = []
5841
+ if tool_name == "apply_edits":
5842
+ top = str(args.get("path") or "").strip()
5843
+ if top:
5844
+ targets.append(top)
5845
+ for edit in args.get("edits") or []:
5846
+ if isinstance(edit, dict) and str(edit.get("path") or "").strip():
5847
+ targets.append(str(edit["path"]).strip())
5848
+ elif mode == "write":
5849
+ for key in ("path", "target"):
5850
+ value = str(args.get(key) or "").strip()
5851
+ if value and ("/" in value or os.sep in value or "." in os.path.basename(value)):
5852
+ targets.append(value)
5853
+ break
5854
+ else:
5855
+ # build/verify: `target` is a route or a symbol, never a lock path. A
5856
+ # `path` only counts when no workspace was named.
5857
+ value = str(args.get("path") or "").strip()
5858
+ if value and not str(args.get("workspace_dir") or "").strip():
5859
+ targets.append(value)
5860
+ roots = set()
5861
+ for target in targets or [base]:
5862
+ absolute = target if os.path.isabs(target) else os.path.join(base, target)
5863
+ try:
5864
+ roots.add(os.path.realpath(GraphEngine.find_project_root(absolute)))
5865
+ except Exception:
5866
+ roots.add(os.path.realpath(os.path.dirname(absolute) or absolute))
5867
+ return sorted(roots)
5868
+
5869
+
5870
+ def _write_lock_roots(tool_name: str, args: dict) -> List[str]:
5871
+ """Workspace roots a call writes (sorted, realpath'd); [] for anything else."""
5872
+ if not _is_write_call(tool_name, args):
5873
+ return []
5874
+ return _lock_roots(tool_name, args, "write")
5875
+
5876
+
5877
+ def _lock_plan(tool_name: str, args: dict) -> Tuple[str, List[str]]:
5878
+ """("write", roots) | ("read", roots) for build/verify | ("", []) for reads."""
5879
+ if _is_write_call(tool_name, args):
5880
+ return "write", _lock_roots(tool_name, args, "write")
5881
+ if _is_shared_call(tool_name, args):
5882
+ return "read", _lock_roots(tool_name, args, "read")
5883
+ return "", []
5884
+
5885
+
5886
+ def _oumv_call_request_id(tool_name: str, args: dict) -> Tuple[dict, Optional[str]]:
5887
+ """Gives an oumv call a transport-known requestId (spec §2.1).
5888
+
5889
+ The gateway echoes a caller-supplied id on every runtime RPC, so the
5890
+ transport can forward `oumv/cancel` for exactly this call when the client
5891
+ cancels it or it times out. `cancel` itself takes requestId as its target.
5892
+ """
5893
+ if tool_name == "oumv":
5894
+ action = str(args.get("action") or "status").strip().lower()
5895
+ if action == "cancel":
5896
+ return args, None
5897
+ elif not (tool_name.startswith("oumv_") and tool_name != "oumv_cancel"):
5898
+ return args, None
5899
+ rid = _oumv_request_id(args)
5900
+ if not rid:
5901
+ import uuid as _uuid
5902
+ rid = str(_uuid.uuid4())
5903
+ args = dict(args, requestId=rid)
5904
+ return args, rid
5905
+
5906
+
5907
+ class _ToolCall:
5908
+ """State of one in-flight tools/call."""
5909
+
5910
+ def __init__(self, msg_id: Any, tool_name: str, args: dict):
5911
+ self.msg_id = msg_id
5912
+ self.key = _call_key(msg_id)
5913
+ self.tool_name = tool_name
5914
+ self.args = args
5915
+ self.oumv_request_id: Optional[str] = None
5916
+ self.lock = threading.Lock()
5917
+ self.changed = threading.Event()
5918
+ self.started = False
5919
+ self.abandoned = False
5920
+ self.done = False
5921
+ self.cancelled = False
5922
+ self.finished = False # answered, dropped, or abandoned: no response may follow
5923
+ self.slot_held = False
5924
+ self.result: Any = None
5925
+ self.error: Optional[str] = None
5926
+ self.interrupted = False # the handler stopped itself via check_cancelled()
5927
+ self.lock_mode = "" # "write" | "read" (build/verify) | "" (no workspace lock)
5928
+ self.holds_write = False
5929
+ self.timeout = MCP_TOOL_TIMEOUT
5930
+ self.started_at: Optional[float] = None # time.monotonic() when the handler started
5931
+ self.ctx = _call_context.CallContext(tool_name)
5932
+
5933
+ def release_slot(self) -> None:
5934
+ with self.lock:
5935
+ held, self.slot_held = self.slot_held, False
5936
+ if held and _WORKER_SLOTS is not None:
5937
+ _WORKER_SLOTS.release()
5938
+
5939
+ def write_pending(self) -> bool:
5940
+ """Holds the write side and its bytes may not all be on disk yet."""
5941
+ return self.holds_write and not self.ctx.write_phase_done
5942
+
5943
+
5944
+ def _forward_oumv_cancel(request_id: Optional[str]) -> None:
5945
+ if not request_id:
5946
+ return
5947
+ try:
5948
+ from tokensafe.oumv_gateway import OUMVGateway
5949
+ OUMVGateway.cancel_inflight(request_id)
5950
+ except Exception:
5951
+ pass
5952
+
5953
+
5954
+ def _run_call(call: _ToolCall, roots: List[str]) -> None:
5955
+ """Runner thread: workspace locks (write or shared) -> worker slot -> handler.
5956
+
5957
+ The workspace locks are held until the handler really returns, also after
5958
+ the supervisor answered with a timeout, so a write that outlived its budget
5959
+ still excludes the next write and every build/verify of that workspace.
5960
+ """
5961
+ mode = call.lock_mode
5962
+ acquired: List["_RWLock"] = []
5963
+ abort = lambda: call.abandoned # noqa: E731
5964
+ try:
5965
+ for root in roots:
5966
+ lock = _workspace_lock(root)
5967
+ if not lock.acquire(mode, abort):
5968
+ return
5969
+ acquired.append(lock)
5970
+ if mode == "write" and roots:
5971
+ call.holds_write = True
5972
+ slots = _WORKER_SLOTS
5973
+ while slots is not None and not slots.acquire(timeout=0.05):
5974
+ if call.abandoned:
5975
+ return
5976
+ with call.lock:
5977
+ call.slot_held = slots is not None
5978
+ if call.abandoned:
5979
+ start = False
5980
+ else:
5981
+ call.started = start = True
5982
+ call.started_at = time.monotonic()
5983
+ call.ctx.deadline = call.started_at + call.timeout
5984
+ if not start:
5985
+ call.release_slot()
5986
+ return
5987
+ with _ACTIVE_LOCK:
5988
+ _LIVE_RUNNERS[id(call)] = call
5989
+ call.changed.set()
5990
+ try:
5991
+ with _call_context.bind(call.ctx):
5992
+ call.result = handle_tool_call(call.tool_name, call.args)
5993
+ except _call_context.CallCancelled:
5994
+ call.interrupted = True
5995
+ except Exception as exc:
5996
+ call.error = f"{type(exc).__name__}: {str(exc)}"
5997
+ finally:
5998
+ call.release_slot()
5999
+ finally:
6000
+ call.holds_write = False
6001
+ for lock in reversed(acquired):
6002
+ lock.release(mode)
6003
+ with _ACTIVE_LOCK:
6004
+ _LIVE_RUNNERS.pop(id(call), None)
6005
+ call.done = True
6006
+ call.changed.set()
6007
+
6008
+
6009
+ def _finish_call(call: _ToolCall, result: Optional[dict]) -> None:
6010
+ """Writes the call's single response, unless it was cancelled or the server closed.
6011
+
6012
+ The cancellation check and the write happen under one lock: once a
6013
+ `notifications/cancelled` was processed, no result for that id is written.
6014
+ """
6015
+ global _LAST_ACTIVITY
6016
+ with _ACTIVE_LOCK:
6017
+ if _ACTIVE_CALLS.get(call.key) is call:
6018
+ del _ACTIVE_CALLS[call.key]
6019
+ if call.finished:
6020
+ return
6021
+ call.finished = True
6022
+ if result is None or call.cancelled or _SERVER_CLOSED:
6023
+ return
6024
+ _write_message({"jsonrpc": "2.0", "id": call.msg_id, "result": result})
6025
+ _LAST_ACTIVITY = time.time()
6026
+
6027
+
6028
+ def _shape_result(tool_name: str, raw: Any) -> dict:
6029
+ redacted = _redact_result_secrets(raw)
6030
+ return _cap_mcp_output_size(redacted, tool_name=tool_name)
6031
+
6032
+
6033
+ def _supervise_call(call: _ToolCall) -> None:
6034
+ """Supervisor thread: waits for the runner, enforces timeout and cancellation."""
6035
+ tool_name = call.tool_name
6036
+ result: Optional[dict] = None
6037
+ try:
6038
+ timeout = _tool_timeout(tool_name, call.args)
6039
+ call.timeout = timeout
6040
+ try:
6041
+ call.lock_mode, roots = _lock_plan(tool_name, call.args)
6042
+ except Exception:
6043
+ call.lock_mode, roots = "", []
6044
+ runner = threading.Thread(
6045
+ target=_run_call, args=(call, roots), name=f"tokensafe-mcp-run-{call.key[:24]}", daemon=True
6046
+ )
6047
+ runner.start()
6048
+
6049
+ # 1. Queued: behind a write (or build/verify) of the same workspace or a full pool.
6050
+ deadline = time.monotonic() + _queue_wait_seconds()
6051
+ while True:
6052
+ call.changed.clear()
6053
+ with call.lock:
6054
+ if call.started:
6055
+ break
6056
+ if call.cancelled or call.abandoned or time.monotonic() >= deadline:
6057
+ call.abandoned = True
6058
+ break
6059
+ call.changed.wait(max(0.0, min(0.5, deadline - time.monotonic())))
6060
+ if call.abandoned:
6061
+ if not call.cancelled:
6062
+ if call.lock_mode == "write":
6063
+ reason = "another write, build or verify of this workspace is still running"
6064
+ elif call.lock_mode == "read":
6065
+ reason = "a write to this workspace is still running"
6066
+ else:
6067
+ reason = "all MCP worker slots stayed busy"
6068
+ result = _shape_result(tool_name, _fallback_error(
6069
+ tool_name, f"{reason} (queued {_queue_wait_seconds():.1f}s); nothing was run",
6070
+ hint="retry after the running call finishes",
6071
+ ))
6072
+ return
6073
+
6074
+ # 2. Running: the tool's own budget starts once it actually runs
6075
+ # (call.ctx.deadline, set by the runner when the handler starts).
6076
+ while True:
6077
+ call.changed.clear()
6078
+ if call.done or call.cancelled:
6079
+ break
6080
+ remaining = (call.ctx.deadline or 0.0) - time.monotonic()
6081
+ if remaining <= 0:
6082
+ break
6083
+ call.changed.wait(min(0.5, remaining))
6084
+ if call.cancelled:
6085
+ call.ctx.cancel("cancelled by the client")
6086
+ return
6087
+ if not call.done or call.interrupted:
6088
+ # Stop waiting; the handler cannot be killed. It is told to stop at
6089
+ # its next check_cancelled(), a live OUMV runtime is asked to stop,
6090
+ # and the worker slot is handed to the next call (the workspace lock
6091
+ # stays with the runner until it returns).
6092
+ call.ctx.cancel("timeout")
6093
+ if call.oumv_request_id:
6094
+ threading.Thread(
6095
+ target=_forward_oumv_cancel, args=(call.oumv_request_id,), daemon=True
6096
+ ).start()
6097
+ call.release_slot()
6098
+ result = _shape_result(tool_name, _fallback_error(tool_name, f"execution exceeded {timeout:.1f}s timeout"))
6099
+ return
6100
+ if call.error is not None:
6101
+ result = _shape_result(tool_name, _fallback_error(tool_name, call.error))
6102
+ elif call.result is None:
6103
+ result = _shape_result(tool_name, _fallback_error(tool_name, "empty result returned"))
6104
+ else:
6105
+ result = _shape_result(tool_name, call.result)
6106
+ except Exception as exc:
6107
+ fallback = _fallback_error(tool_name, f"{type(exc).__name__}: {str(exc)}")
6108
+ try:
6109
+ result = _shape_result(tool_name, fallback)
6110
+ except Exception:
6111
+ result = fallback
6112
+ finally:
6113
+ # Telemetry first: the call stays registered (and EOF drain waits for it)
6114
+ # until nothing of it touches the data dir any more.
6115
+ try:
6116
+ from tokensafe.telemetry_sync import TelemetrySync
6117
+ TelemetrySync.sync_background(throttle_seconds=5.0)
6118
+ except Exception:
6119
+ pass
6120
+ _finish_call(call, result)
6121
+
6122
+
6123
+ def _start_tool_call(msg_id: Any, params: dict) -> None:
6124
+ """Registers a tools/call and hands it to a supervisor; never blocks the read loop."""
6125
+ tool_name = str(params.get("name") or "")
6126
+ raw_tool_args = params.get("arguments")
6127
+ try:
6128
+ tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
6129
+ if not tool_args and raw_tool_args:
6130
+ # Self-healing: hosts on small/local models intermittently send
6131
+ # arguments as a malformed JSON string — repair before failing.
6132
+ from tokensafe.json_repair import parse_tool_arguments
6133
+ tool_args = parse_tool_arguments(raw_tool_args) or {}
6134
+ tool_args, oumv_rid = _oumv_call_request_id(tool_name, tool_args)
6135
+ except Exception as e:
6136
+ _write_message({
6137
+ "jsonrpc": "2.0", "id": msg_id,
6138
+ "result": _shape_result(tool_name, _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")),
6139
+ })
6140
+ return
6141
+ call = _ToolCall(msg_id, tool_name, tool_args)
6142
+ call.oumv_request_id = oumv_rid
6143
+ with _ACTIVE_LOCK:
6144
+ _ACTIVE_CALLS[call.key] = call
6145
+ threading.Thread(
6146
+ target=_supervise_call, args=(call,), name=f"tokensafe-mcp-call-{call.key[:24]}", daemon=True
6147
+ ).start()
6148
+
6149
+
6150
+ def _cancel_call(request_id: Any) -> bool:
6151
+ """Handles `notifications/cancelled`: the call gets no response (MCP spec).
6152
+
6153
+ The handler is told to stop at its next `check_cancelled()`; an in-flight
6154
+ oumv call is also cancelled at the runtime (`oumv/cancel`), forwarded off the
6155
+ read loop. Unknown or already-answered ids are ignored.
6156
+ """
6157
+ if request_id is None:
6158
+ return False
6159
+ with _ACTIVE_LOCK:
6160
+ call = _ACTIVE_CALLS.get(_call_key(request_id))
6161
+ if call is None or call.finished:
6162
+ return False
6163
+ call.cancelled = True
6164
+ call.ctx.cancel("cancelled by the client")
6165
+ call.changed.set()
6166
+ if call.oumv_request_id:
6167
+ threading.Thread(target=_forward_oumv_cancel, args=(call.oumv_request_id,), daemon=True).start()
6168
+ return True
6169
+
6170
+
6171
+ def _in_flight_count() -> int:
6172
+ with _ACTIVE_LOCK:
6173
+ return len(_ACTIVE_CALLS)
6174
+
6175
+
6176
+ def _write_in_progress_locked() -> bool:
6177
+ """Caller holds _ACTIVE_LOCK. A write whose bytes may not all be on disk."""
6178
+ if _call_context.write_io_count():
6179
+ return True
6180
+ return any(c.write_pending() for c in _LIVE_RUNNERS.values())
6181
+
6182
+
6183
+ def _write_in_progress() -> bool:
6184
+ with _ACTIVE_LOCK:
6185
+ return _write_in_progress_locked()
6186
+
6187
+
6188
+ def _write_await_deadline(call: _ToolCall) -> float:
6189
+ """How long EOF waits for a started write: its own timeout plus a margin."""
6190
+ started = call.started_at if call.started_at is not None else time.monotonic()
6191
+ return started + call.timeout + _WRITE_DRAIN_MARGIN_SEC
6192
+
6193
+
6194
+ def _drain_calls(grace: float) -> None:
6195
+ """After EOF: finish what must finish, drop what may be dropped, then close.
6196
+
6197
+ - A write that has not started (queued behind a lock or a worker slot) is
6198
+ cancelled with no response: nothing of it ran.
6199
+ - A started write (holding the write side of its workspace lock) is awaited
6200
+ until its bytes are on disk (apply_edits: the write phase, not the verify
6201
+ after it), bounded by its own timeout + _WRITE_DRAIN_MARGIN_SEC. This
6202
+ includes a write whose caller was already answered with a timeout.
6203
+ - Every other call (reads, build/verify, a write already in its verify) gets
6204
+ `grace` seconds; a late result is dropped and the handler told to stop.
6205
+ - The process never exits while an atomic write/rename is in progress.
6206
+ """
6207
+ global _SERVER_CLOSED
6208
+ read_deadline = time.monotonic() + max(0.0, grace)
6209
+ queued_writes: List[_ToolCall] = []
6210
+ with _ACTIVE_LOCK:
6211
+ for call in list(_ACTIVE_CALLS.values()):
6212
+ # Classified from the arguments: the supervisor may not have set
6213
+ # lock_mode yet when EOF follows the request immediately.
6214
+ try:
6215
+ is_write = _is_write_call(call.tool_name, call.args)
6216
+ except Exception:
6217
+ is_write = call.lock_mode == "write"
6218
+ if not is_write:
6219
+ continue
6220
+ with call.lock:
6221
+ if call.started:
6222
+ continue
6223
+ call.abandoned = True
6224
+ call.finished = True
6225
+ _ACTIVE_CALLS.pop(call.key, None)
6226
+ queued_writes.append(call)
6227
+ for call in queued_writes:
6228
+ call.changed.set()
6229
+
6230
+ while True:
6231
+ now = time.monotonic()
6232
+ with _ACTIVE_LOCK:
6233
+ writes_pending = [
6234
+ c for c in _LIVE_RUNNERS.values() if c.write_pending() and now < _write_await_deadline(c)
6235
+ ]
6236
+ others = [c for c in _ACTIVE_CALLS.values() if not c.write_pending()]
6237
+ if now >= read_deadline and others:
6238
+ # Grace is over: late results of reads (and of a write that is
6239
+ # past its write phase, e.g. in its verify) are dropped.
6240
+ for c in others:
6241
+ c.finished = True
6242
+ _ACTIVE_CALLS.pop(c.key, None)
6243
+ if now >= read_deadline:
6244
+ for c in others:
6245
+ with c.lock:
6246
+ c.abandoned = True
6247
+ c.ctx.cancel("server closing")
6248
+ c.changed.set()
6249
+ others = []
6250
+ answered = not _ACTIVE_CALLS
6251
+ if not writes_pending and (answered or (now >= read_deadline and not others)):
6252
+ break
6253
+ time.sleep(0.02)
6254
+
6255
+ with _ACTIVE_LOCK:
6256
+ _SERVER_CLOSED = True
6257
+ pending = list(_ACTIVE_CALLS.values())
6258
+ _ACTIVE_CALLS.clear()
6259
+ for call in pending:
6260
+ # A call still queued never starts; one already running is not killed,
6261
+ # but it is told to stop and its late result is never written.
6262
+ with call.lock:
6263
+ call.abandoned = True
6264
+ call.ctx.cancel("server closing")
6265
+ call.changed.set()
6266
+ # Never let the process end between a temp-file write and its rename.
6267
+ _call_context.wait_write_io_idle(_WRITE_IO_EXIT_WAIT_SEC)
6268
+
6269
+
6270
+ # --------------------------------------------------------------------------- #
6271
+ # Stuck-handler watchdog. A handler still alive past its timeout plus
6272
+ # TOKENSAFE_MCP_HARD_KILL_SEC holds a thread (and maybe a worker slot's worth of
6273
+ # CPU) forever. When such threads exist and the server is otherwise idle (no
6274
+ # call awaiting an answer, no write in progress) the process exits through the
6275
+ # same restart path as an upgrade drain; the host respawns it.
6276
+ # --------------------------------------------------------------------------- #
6277
+
6278
+ def _hard_kill_seconds() -> float:
6279
+ """0 disables the stuck-handler restart."""
6280
+ return _env_float("TOKENSAFE_MCP_HARD_KILL_SEC", 300.0, 0.0, 86400.0)
6281
+
6282
+
6283
+ def _stuck_calls(now: Optional[float] = None) -> List[_ToolCall]:
6284
+ hard = _hard_kill_seconds()
6285
+ if hard <= 0:
6286
+ return []
6287
+ now = time.monotonic() if now is None else now
6288
+ with _ACTIVE_LOCK:
6289
+ return [
6290
+ c for c in _LIVE_RUNNERS.values()
6291
+ if not c.done and c.started_at is not None and now - c.started_at > c.timeout + hard
6292
+ ]
6293
+
6294
+
6295
+ def _stuck_restart_due(now: Optional[float] = None) -> List[_ToolCall]:
6296
+ """Stuck handlers, when a restart may take them down now; [] otherwise."""
6297
+ stuck = _stuck_calls(now)
6298
+ if not stuck:
6299
+ return []
6300
+ with _ACTIVE_LOCK:
6301
+ if _ACTIVE_CALLS or _write_in_progress_locked():
6302
+ return []
6303
+ return stuck
6304
+
6305
+
6306
+ def _hard_exit(code: int = 0) -> None:
6307
+ """Process exit for a restart (patched in tests)."""
6308
+ os._exit(code)
6309
+
6310
+
6311
+ def _exit_for_restart(reason: str, still_due=None) -> bool:
6312
+ """The one restart path (upgrade drain, stuck handler): flush and exit.
6313
+
6314
+ The host respawns the server. Re-checks under the call registry lock that no
6315
+ call arrived and no write is in progress, so a new tools/call can never be
6316
+ registered between the check and the exit. False when the exit was refused.
6317
+ """
6318
+ with _ACTIVE_LOCK:
6319
+ if _ACTIVE_CALLS or _write_in_progress_locked():
6320
+ return False
6321
+ if still_due is not None and not still_due():
6322
+ return False
6323
+ if reason:
6324
+ try:
6325
+ sys.stderr.write(f"tokensafe-mcp: restarting ({reason})\n")
6326
+ sys.stderr.flush()
6327
+ except Exception:
6328
+ pass
6329
+ with _STDOUT_LOCK:
6330
+ try:
6331
+ sys.stdout.flush()
6332
+ except Exception:
6333
+ pass
6334
+ _hard_exit(0)
6335
+ return True
6336
+
6337
+
6338
+ def _watchdog_tick(now: Optional[float] = None) -> bool:
6339
+ """One stuck-handler check. True when the restart path was taken."""
6340
+ stuck = _stuck_restart_due(now)
6341
+ if not stuck:
6342
+ return False
6343
+ names = sorted({c.tool_name or "?" for c in stuck})
6344
+ return _exit_for_restart(
6345
+ f"stuck handler past timeout + {_hard_kill_seconds():.0f}s: {', '.join(names)}"
6346
+ )
6347
+
6348
+
6349
+ _WATCHDOG_GEN = [0]
6350
+
6351
+
6352
+ def _start_stuck_watchdog() -> None:
6353
+ """One watchdog per served session (a newer run_mcp_server retires it)."""
6354
+ _WATCHDOG_GEN[0] += 1
6355
+ gen = _WATCHDOG_GEN[0]
6356
+
6357
+ def _watch() -> None:
6358
+ while _SERVER_ACTIVE and _WATCHDOG_GEN[0] == gen:
6359
+ time.sleep(_env_float("TOKENSAFE_MCP_WATCHDOG_SEC", 5.0, 0.05, 300.0))
6360
+ if not _SERVER_ACTIVE or _WATCHDOG_GEN[0] != gen:
6361
+ return
6362
+ try:
6363
+ _watchdog_tick()
6364
+ except Exception:
6365
+ pass
6366
+
6367
+ threading.Thread(target=_watch, name="tokensafe-mcp-watchdog", daemon=True).start()
6368
+
6369
+
6370
+ def _initialize_result(params: dict) -> dict:
6371
+ global _CLIENT_HAS_ROOTS
6372
+ try:
6373
+ client_info = params.get("clientInfo") or {}
6374
+ if isinstance(client_info, dict):
6375
+ _set_mcp_client(str(client_info.get("name") or ""))
6376
+ except Exception:
6377
+ pass
6378
+ client_caps = params.get("capabilities")
6379
+ _CLIENT_HAS_ROOTS = isinstance(client_caps, dict) and isinstance(client_caps.get("roots"), dict)
6380
+ try:
6381
+ from tokensafe.telemetry_sync import TelemetrySync
6382
+ TelemetrySync.sync_background()
6383
+ except Exception:
6384
+ pass
6385
+ req_version = str(params.get("protocolVersion") or "")
6386
+ supported_versions = ("2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25")
6387
+ negotiated_version = req_version if req_version in supported_versions else "2025-06-18"
6388
+ result: Dict[str, Any] = {
6389
+ "protocolVersion": negotiated_version,
6390
+ "capabilities": {"tools": {}},
6391
+ "serverInfo": SERVER_INFO
6392
+ }
6393
+ # Routing brief (MCP `instructions`): which stacks this workspace
6394
+ # works through OUMV and which through the TokenSafe tools. The
6395
+ # default root resolves per server (session scope, then the spawn
6396
+ # cwd, then the active marker), and extra roots — TOKENSAFE_WORKSPACES
6397
+ # plus any multi-root payload the host passed to initialize — are
6398
+ # classified one by one so a single-root verdict is never global.
6399
+ try:
6400
+ from tokensafe.session_brief import (
6401
+ build_workspace_brief,
6402
+ workspace_roots_from_env,
6403
+ workspace_roots_from_payload,
6404
+ )
6405
+ extra_roots = workspace_roots_from_env() + workspace_roots_from_payload(params)
6406
+ seen_roots = set()
6407
+ extra_roots = [r for r in extra_roots if not (r in seen_roots or seen_roots.add(r))]
6408
+ payload_roots = workspace_roots_from_payload(params)
6409
+ if payload_roots:
6410
+ set_client_roots(payload_roots)
6411
+ default_ws = _oumv_default_workspace()
6412
+ # The machine-wide marker is a last-resort default, never a
6413
+ # registered root or the brief's subject: another session's
6414
+ # hooks may have pointed it at an unrelated repo.
6415
+ from_marker = bool(default_ws) and default_ws == get_active_workspace() and not (
6416
+ _plausible_project_root(os.getcwd()) or default_ws in client_roots()
6417
+ )
6418
+ if default_ws and not from_marker:
6419
+ register_roots([default_ws])
6420
+ register_roots(extra_roots)
6421
+ brief = build_workspace_brief(
6422
+ None if from_marker else default_ws,
6423
+ include_live=False,
6424
+ extra_workspaces=extra_roots,
6425
+ )
6426
+ if brief:
6427
+ result["instructions"] = brief
6428
+ except Exception:
6429
+ pass
6430
+ return result
6431
+
6432
+
5507
6433
  def run_mcp_server():
5508
- """Runs stdio JSON-RPC 2.0 loop with per-call timeout, resilient recovery & idle-only reload."""
6434
+ """Runs the stdio JSON-RPC 2.0 loop.
6435
+
6436
+ Protocol methods (initialize, tools/list, ping, roots answers, notifications)
6437
+ are answered inline and in order; each tools/call runs concurrently and its
6438
+ response may arrive out of order (ids correlate). `notifications/cancelled`
6439
+ suppresses the cancelled call's response and tells its handler to stop
6440
+ (call_context.check_cancelled). On EOF the loop stops reading: reads get a
6441
+ short grace period, queued writes are cancelled, started writes are awaited
6442
+ until their bytes are on disk (see _drain_calls); an armed upgrade or a
6443
+ stuck-handler restart drains only when idle and never during a write.
6444
+ """
5509
6445
  global _MCP_CLIENT_NAME, _TOOLS_LISTED, _EPOCH_GEN, _DELIVERED_SESSION
5510
- global _LAST_ACTIVITY, _RELOAD_PENDING, _SERVER_ACTIVE
6446
+ global _LAST_ACTIVITY, _RELOAD_PENDING, _SERVER_ACTIVE, _CLIENT_HAS_ROOTS
6447
+ global _WORKER_SLOTS, _SERVER_CLOSED
5511
6448
  # Windows pipes default to the ANSI code page; one emoji in a response used
5512
6449
  # to raise UnicodeEncodeError and exit the whole server loop.
5513
6450
  from tokensafe.stdio_io import ensure_utf8_stdio
@@ -5515,9 +6452,15 @@ def run_mcp_server():
5515
6452
  ensure_utf8_stdio()
5516
6453
  _MCP_CLIENT_NAME = ""
5517
6454
  _TOOLS_LISTED = False
6455
+ _CLIENT_HAS_ROOTS = False
6456
+ _PENDING_ROOTS_REQUEST_ID[0] = None
5518
6457
  _EPOCH_GEN = 0
5519
6458
  _DELIVERED_SESSION = ""
5520
6459
  _IN_PROCESS_DELIVERED.clear()
6460
+ with _ACTIVE_LOCK:
6461
+ _ACTIVE_CALLS.clear()
6462
+ _SERVER_CLOSED = False
6463
+ _WORKER_SLOTS = threading.Semaphore(_mcp_workers())
5521
6464
  initial_mtimes = _get_watched_mtimes()
5522
6465
  auto_reload = _auto_reload_enabled()
5523
6466
  _LAST_ACTIVITY = time.time()
@@ -5525,137 +6468,90 @@ def run_mcp_server():
5525
6468
  _SERVER_ACTIVE = True
5526
6469
  if auto_reload:
5527
6470
  _start_reload_watchdog(_reload_idle_seconds())
6471
+ _start_stuck_watchdog()
5528
6472
 
5529
- while True:
5530
- try:
5531
- line = sys.stdin.readline()
5532
- except Exception:
5533
- break
5534
- if not line:
5535
- break
5536
- line = line.strip()
5537
- if not line:
5538
- continue
5539
-
5540
- try:
5541
- req = json.loads(line)
5542
- except Exception:
5543
- continue
5544
- if not isinstance(req, dict):
5545
- continue
6473
+ try:
6474
+ while True:
6475
+ try:
6476
+ line = sys.stdin.readline()
6477
+ except Exception:
6478
+ break
6479
+ if not line:
6480
+ break
6481
+ line = line.strip()
6482
+ if not line:
6483
+ continue
5546
6484
 
5547
- msg_id = req.get("id")
5548
- method = req.get("method")
5549
- raw_params = req.get("params")
5550
- params = raw_params if isinstance(raw_params, dict) else {}
6485
+ try:
6486
+ req = json.loads(line)
6487
+ except Exception:
6488
+ continue
6489
+ if not isinstance(req, dict):
6490
+ continue
5551
6491
 
5552
- # Notifications (no id, or notifications/*) must never receive JSON-RPC responses
5553
- if msg_id is None or (isinstance(method, str) and method.startswith("notifications/")):
5554
- continue
6492
+ msg_id = req.get("id")
6493
+ method = req.get("method")
6494
+ raw_params = req.get("params")
6495
+ params = raw_params if isinstance(raw_params, dict) else {}
6496
+
6497
+ # A response to a request this server sent (no method, has id): the
6498
+ # client's `roots/list` answer. Responses must never be answered.
6499
+ if method is None and msg_id is not None:
6500
+ if msg_id == _PENDING_ROOTS_REQUEST_ID[0]:
6501
+ _PENDING_ROOTS_REQUEST_ID[0] = None
6502
+ if isinstance(req.get("result"), dict):
6503
+ set_client_roots(roots_from_list_result(req["result"]))
6504
+ continue
5555
6505
 
5556
- # A pending upgrade drains at a safe boundary only: the first initialize
5557
- # after the idle window (a new session has nothing to lose) or the
5558
- # watchdog. Never mid-session.
5559
- if method == "initialize" and auto_reload and _reload_due():
5560
- break
5561
- _LAST_ACTIVITY = time.time()
6506
+ # MCP roots: ask once the session is initialized, and again whenever the
6507
+ # client says its roots changed.
6508
+ if method in ("notifications/initialized", "notifications/roots/list_changed") and _CLIENT_HAS_ROOTS:
6509
+ _request_client_roots()
5562
6510
 
5563
- response = {"jsonrpc": "2.0", "id": msg_id}
6511
+ if method == "notifications/cancelled":
6512
+ _cancel_call(params.get("requestId"))
6513
+ continue
5564
6514
 
5565
- if method == "initialize":
5566
- try:
5567
- client_info = params.get("clientInfo") or {}
5568
- if isinstance(client_info, dict):
5569
- _set_mcp_client(str(client_info.get("name") or ""))
5570
- except Exception:
5571
- pass
5572
- try:
5573
- from tokensafe.telemetry_sync import TelemetrySync
5574
- TelemetrySync.sync_background()
5575
- except Exception:
5576
- pass
5577
- req_version = str(params.get("protocolVersion") or "")
5578
- supported_versions = ("2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25")
5579
- negotiated_version = req_version if req_version in supported_versions else "2025-06-18"
5580
- response["result"] = {
5581
- "protocolVersion": negotiated_version,
5582
- "capabilities": {"tools": {}},
5583
- "serverInfo": SERVER_INFO
5584
- }
5585
- # Routing brief (MCP `instructions`): which stacks this workspace
5586
- # works through OUMV and which through the TokenSafe tools. The
5587
- # default root resolves per server (session scope, then the spawn
5588
- # cwd, then the active marker), and extra roots — TOKENSAFE_WORKSPACES
5589
- # plus any multi-root payload the host passed to initialize — are
5590
- # classified one by one so a single-root verdict is never global.
5591
- try:
5592
- from tokensafe.session_brief import (
5593
- build_workspace_brief,
5594
- workspace_roots_from_env,
5595
- workspace_roots_from_payload,
5596
- )
5597
- extra_roots = workspace_roots_from_env() + workspace_roots_from_payload(params)
5598
- seen_roots = set()
5599
- extra_roots = [r for r in extra_roots if not (r in seen_roots or seen_roots.add(r))]
5600
- register_roots([_oumv_default_workspace() or os.getcwd()] + extra_roots)
5601
- brief = build_workspace_brief(
5602
- _oumv_default_workspace() or os.getcwd(),
5603
- include_live=False,
5604
- extra_workspaces=extra_roots,
5605
- )
5606
- if brief:
5607
- response["result"]["instructions"] = brief
5608
- except Exception:
5609
- pass
5610
- elif method == "tools/list":
5611
- _TOOLS_LISTED = True
5612
- profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
5613
- if profile == "full":
5614
- advertised = FULL_TOOLS
5615
- elif profile == "lean":
5616
- advertised = [t for t in TOOLS if t["name"] in _LEAN_TOOL_NAMES]
5617
- else:
5618
- advertised = TOOLS
5619
- response["result"] = {"tools": advertised}
5620
- elif method == "ping":
5621
- response["result"] = {}
5622
- elif method == "tools/call":
5623
- tool_name = str(params.get("name") or "")
5624
- raw_tool_args = params.get("arguments")
5625
- try:
5626
- tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
5627
- if not tool_args and raw_tool_args:
5628
- # Self-healing: hosts on small/local models intermittently send
5629
- # arguments as a malformed JSON string — repair before failing.
5630
- from tokensafe.json_repair import parse_tool_arguments
5631
- tool_args = parse_tool_arguments(raw_tool_args) or {}
5632
- raw_res = _execute_with_timeout(tool_name, tool_args, timeout=_tool_timeout(tool_name, tool_args))
5633
- redacted = _redact_result_secrets(raw_res)
5634
- response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
5635
- except Exception as e:
5636
- err_res = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
5637
- redacted = _redact_result_secrets(err_res)
5638
- response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
5639
- finally:
5640
- try:
5641
- from tokensafe.telemetry_sync import TelemetrySync
5642
- TelemetrySync.sync_background(throttle_seconds=5.0)
5643
- except Exception:
5644
- pass
5645
- else:
5646
- response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
6515
+ # Notifications (no id, or notifications/*) must never receive JSON-RPC responses
6516
+ if msg_id is None or (isinstance(method, str) and method.startswith("notifications/")):
6517
+ continue
5647
6518
 
5648
- try:
5649
- sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
5650
- sys.stdout.flush()
5651
- except Exception:
5652
- break
6519
+ # A pending upgrade drains at a safe boundary only: the first initialize
6520
+ # after the idle window (a new session has nothing to lose) or the
6521
+ # watchdog. Never mid-session.
6522
+ if method == "initialize" and auto_reload and _reload_due():
6523
+ break
6524
+ _LAST_ACTIVITY = time.time()
5653
6525
 
5654
- # An upgrade marker arms the drain; it never cuts the live session.
5655
- if auto_reload and _get_watched_mtimes() != initial_mtimes:
5656
- _RELOAD_PENDING = True
6526
+ if method == "tools/call":
6527
+ _start_tool_call(msg_id, params)
6528
+ else:
6529
+ response: Dict[str, Any] = {"jsonrpc": "2.0", "id": msg_id}
6530
+ if method == "initialize":
6531
+ response["result"] = _initialize_result(params)
6532
+ elif method == "tools/list":
6533
+ _TOOLS_LISTED = True
6534
+ profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
6535
+ if profile == "full":
6536
+ advertised = FULL_TOOLS
6537
+ elif profile == "lean":
6538
+ advertised = [t for t in TOOLS if t["name"] in _LEAN_TOOL_NAMES]
6539
+ else:
6540
+ advertised = TOOLS
6541
+ response["result"] = {"tools": advertised}
6542
+ elif method == "ping":
6543
+ response["result"] = {}
6544
+ else:
6545
+ response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
6546
+ if not _write_message(response):
6547
+ break
5657
6548
 
5658
- _SERVER_ACTIVE = False
6549
+ # An upgrade marker arms the drain; it never cuts the live session.
6550
+ if auto_reload and _get_watched_mtimes() != initial_mtimes:
6551
+ _RELOAD_PENDING = True
6552
+ finally:
6553
+ _drain_calls(_drain_seconds())
6554
+ _SERVER_ACTIVE = False
5659
6555
 
5660
6556
  def main():
5661
6557
  run_mcp_server()