tokensafe 5.0.1 → 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 +1078 -186
  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.1"
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)
@@ -2954,7 +2996,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2954
2996
  elif raw_sc and raw_sc.lower() not in ("all", "code", "config"):
2955
2997
  q_spec["file_type"] = raw_sc.lstrip(".")
2956
2998
  rerouted = {"queries": [q_spec]}
2957
- 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")
2958
3000
  if explicit_root:
2959
3001
  rerouted["cwd"] = explicit_root
2960
3002
  args = rerouted
@@ -3089,7 +3131,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3089
3131
  if path:
3090
3132
  resolved, _meta_info, resolve_err = resolve_input_path(
3091
3133
  path,
3092
- base=args.get("root") or active_ws,
3134
+ base=[args.get("root") or args.get("cwd"), active_ws],
3093
3135
  mode="read",
3094
3136
  must_exist=True,
3095
3137
  )
@@ -3413,9 +3455,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3413
3455
 
3414
3456
  if start_line is None and end_line is None:
3415
3457
  cur_hash = AgentFirewall._file_content_hash(abs_path)
3416
- _ensure_delivered_loaded()
3417
- delivered = _IN_PROCESS_DELIVERED.get((abs_path, sym_clean, eff_dep_mode))
3418
- 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))
3419
3462
  allow_pointer = (not force_full) and _client_supports_pointers() and already_here
3420
3463
  is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
3421
3464
  _mcp_session_id(),
@@ -3600,22 +3643,43 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3600
3643
  max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
3601
3644
 
3602
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]
3603
3651
  by_file: Dict[str, List[str]] = {}
3652
+ unresolved: List[str] = []
3604
3653
  for t in targets:
3605
3654
  if not isinstance(t, dict) or not str(t.get("path") or "").strip():
3606
3655
  return _fallback_error("smart_bundle", "each target must be {path: str, symbol?: str}")
3607
3656
  raw_p = str(t["path"]).strip()
3608
- if not os.path.isabs(raw_p) and active_ws and os.path.exists(os.path.join(active_ws, raw_p)):
3609
- target_p = os.path.abspath(os.path.join(active_ws, raw_p))
3610
- else:
3657
+ if os.path.isabs(raw_p):
3611
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
3612
3667
  if is_plugin_or_system_dir(target_p):
3613
3668
  return _fallback_error("smart_bundle", f"refusing to read from system root or plugin dir '{raw_p}'")
3614
3669
  by_file.setdefault(target_p, []).append(str(t.get("symbol") or "").strip())
3615
3670
 
3616
- 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)]
3617
3672
  if missing:
3618
- 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}"}]}
3619
3683
 
3620
3684
  bundle_max_bytes = 512 * 1024
3621
3685
  file_sections: List[Tuple[str, str, List[str]]] = [] # (abs_path, skeleton, import_lines)
@@ -3643,21 +3707,22 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3643
3707
  try:
3644
3708
  graph, rel = GraphEngine.for_file(p)
3645
3709
  if graph and rel:
3646
- for sym in keep:
3647
- # A class target's call edges live on its methods:
3648
- # resolve every qual key under the target symbol.
3649
- keys = [k for k in graph.symbols if k == f"{rel}::{sym}" or k.startswith(f"{rel}::{sym}::")]
3650
- for key in keys[:12]:
3651
- qual = key[len(rel) + 2:]
3652
- nb = graph.get_neighborhood(qual, target_file=rel)
3653
- for dep_key in sorted(nb.get("one_hop", [])):
3654
- dep_sym = graph.symbols.get(dep_key)
3655
- if not dep_sym:
3656
- continue
3657
- line = f" {qual} -> {dep_key.split('::', 1)[-1]}: {dep_sym.signature.strip()[:160]}"
3658
- if line not in seen_dep_lines:
3659
- seen_dep_lines.add(line)
3660
- 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)
3661
3726
  except Exception:
3662
3727
  pass
3663
3728
 
@@ -4244,7 +4309,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4244
4309
  tree_output = build_dir_tree(abs_path, max_depth=depth, max_entries=max_entries)
4245
4310
  tree_tokens = count_tokens(tree_output)
4246
4311
  # Estimate equivalent tokens from multiple verbose ls -la calls (at least ~800 tokens)
4247
- est_orig_tokens = max(800, tree_tokens * 6)
4312
+ est_orig_tokens = tree_tokens * 6 # counterfactual multiplier, labelled estimated; no constant floor
4248
4313
  tracker.record_event(
4249
4314
  session_id=_mcp_session_id(),
4250
4315
  event_type="DIR_LIST",
@@ -4282,17 +4347,27 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4282
4347
  single_file: Optional[str] = None
4283
4348
  if raw_path:
4284
4349
  if not os.path.isabs(raw_path):
4285
- if base_dir and os.path.isdir(os.path.join(base_dir, raw_path)):
4286
- target_path = os.path.abspath(os.path.join(base_dir, raw_path))
4287
- else:
4288
- target_path = os.path.abspath(raw_path)
4289
- if not os.path.exists(target_path):
4290
- 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
4291
4364
  return _fallback_error(
4292
4365
  "scoped_search",
4293
- f"path '{raw_path}' does not exist (resolved to '{target_path}' from '{scope_root}'). "
4294
- 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 ""),
4295
4369
  )
4370
+ target_path = resolved
4296
4371
  else:
4297
4372
  target_path = os.path.abspath(raw_path)
4298
4373
 
@@ -4309,6 +4384,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4309
4384
  target_path = os.path.abspath(str(base_dir)) if inside_base else os.path.dirname(single_file)
4310
4385
  if is_plugin_or_system_dir(target_path):
4311
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}'")
4312
4394
  else:
4313
4395
  resolved_path, err = _resolve_project_root(args)
4314
4396
  if err or not resolved_path:
@@ -4468,17 +4550,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4468
4550
  if not lock_p:
4469
4551
  active_ws = _workspace_root()
4470
4552
  if active_ws and hasattr(LockfileReducer, "find_lockfile"):
4471
- 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.
4472
4556
  try:
4473
- os.chdir(active_ws)
4474
- lock_p = LockfileReducer.find_lockfile()
4557
+ lock_p = LockfileReducer.find_lockfile(directory=active_ws)
4475
4558
  except Exception:
4476
4559
  lock_p = None
4477
- finally:
4478
- try:
4479
- os.chdir(orig_cwd)
4480
- except Exception:
4481
- pass
4482
4560
  res = LockfileReducer.query_dependency(lock_p, pkg)
4483
4561
  lock_bytes = res.pop("_lockfile_bytes", 0)
4484
4562
  json_text = json.dumps(res, indent=2, ensure_ascii=False)
@@ -4611,7 +4689,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4611
4689
  ws, ws_err = _oumv_workspace_arg(args)
4612
4690
  if ws_err:
4613
4691
  return _fallback_error("oumv_observe", ws_err)
4614
- 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))
4615
4694
  try:
4616
4695
  _observe_seed_read_cache(res, lvl, tgt, raw_path, ws)
4617
4696
  except Exception:
@@ -4648,7 +4727,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4648
4727
  ws, ws_err = _oumv_workspace_arg(args)
4649
4728
  if ws_err:
4650
4729
  return _fallback_error("oumv_understand", ws_err)
4651
- 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))
4652
4732
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4653
4733
  except Exception as e:
4654
4734
  return _fallback_error("oumv_understand", f"failed to query OUMV understanding: {e}")
@@ -4664,7 +4744,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4664
4744
  ws, ws_err = _oumv_workspace_arg(args)
4665
4745
  if ws_err:
4666
4746
  return _fallback_error("oumv_mutate", ws_err)
4667
- 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))
4668
4749
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4669
4750
  except Exception as e:
4670
4751
  return _fallback_error("oumv_mutate", f"failed to apply OUMV mutation: {e}")
@@ -4680,7 +4761,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4680
4761
  if ws_err:
4681
4762
  return _fallback_error("oumv_verify", ws_err)
4682
4763
  sandbox = args.get("sandbox") if isinstance(args.get("sandbox"), dict) else None
4683
- 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))
4684
4766
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4685
4767
  except Exception as e:
4686
4768
  return _fallback_error(
@@ -4737,7 +4819,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4737
4819
  if not p:
4738
4820
  return _fallback_error("oumv_preview", "missing required 'path'")
4739
4821
  res = OUMVGateway.preview(path=p, symbol=sym, replacement=rep, expected_version=ev,
4740
- batch=batch, runtime=rt, workspace_dir=ws)
4822
+ batch=batch, runtime=rt, workspace_dir=ws,
4823
+ request_id=_oumv_request_id(args))
4741
4824
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4742
4825
  except Exception as e:
4743
4826
  return _fallback_error("oumv_preview", f"failed to preview OUMV mutation: {e}")
@@ -4752,7 +4835,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4752
4835
  ws, ws_err = _oumv_workspace_arg(args)
4753
4836
  if ws_err:
4754
4837
  return _fallback_error("oumv_build", ws_err)
4755
- 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))
4756
4840
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
4757
4841
  except Exception as e:
4758
4842
  return _fallback_error("oumv_build", f"failed to run OUMV build: {e}")
@@ -4799,9 +4883,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4799
4883
  verify_off = isinstance(verify, str) and verify.strip().lower() in (
4800
4884
  "off", "none", "skip", "false", "0",
4801
4885
  )
4886
+ verify_implicit = False
4802
4887
  if verify_off:
4803
4888
  verify = None
4804
4889
  elif verify in (None, "") and _verify_default_enabled():
4890
+ verify_implicit = True
4805
4891
  # The strongest convergence lever: the edit and its verdict arrive in
4806
4892
  # one call. A red suite is reported, not rolled back, unless the
4807
4893
  # caller sets strict_verify.
@@ -4859,16 +4945,27 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4859
4945
  return _fallback_error("apply_edits", str(res.get("error") or "verify command blocked"))
4860
4946
  applied_files = res.get("applied_files") or []
4861
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)
4862
4950
  if res.get("success"):
4863
4951
  action_desc = "Validated" if dry_run else "Applied"
4864
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).")
4865
4962
  else:
4866
- lines.append(f"✖ Batch edits failed ({res.get('failed_count', 0)} error(s)).")
4963
+ lines.append(f"✖ Batch edits failed ({edit_errors} error(s)).")
4867
4964
  for f in res.get("failed_files", []):
4868
4965
  lines.append(f" - `{f.get('path')}`: {f.get('error')}")
4869
4966
 
4870
4967
  if res.get("applied_files"):
4871
- if not res.get("success"):
4968
+ if not res.get("success") and edit_errors:
4872
4969
  lines.append(f"Applied {len(res['applied_files'])} file(s) before error/verify:")
4873
4970
  for f in res.get("applied_files", []):
4874
4971
  h_cnt = f.get("hunks", 0)
@@ -4898,6 +4995,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4898
4995
  lines.append(f"\nInline Verify ({v.get('command')}): {status_sym} (exit {v.get('exit_code')}, {v.get('duration_seconds', 0)}s)")
4899
4996
  if v.get("note"):
4900
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")
4901
5000
  if v.get("output"):
4902
5001
  lines.append("```text\n" + v["output"] + "\n```")
4903
5002
  elif v.get("error"):
@@ -4906,7 +5005,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
4906
5005
  # Static blast radius (warm graph only): one advisory line, no crawl
4907
5006
  # and no mandatory follow-up call.
4908
5007
  try:
4909
- if res.get("success") and applied_files and not res.get("dry_run"):
5008
+ if res.get("edits_applied") and applied_files:
4910
5009
  warm = GraphEngine.get_cached(cwd)
4911
5010
  if warm is not None:
4912
5011
  session_id = _mcp_session_id()
@@ -5003,7 +5102,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
5003
5102
  "pattern": args.get("query") or args.get("pattern"),
5004
5103
  "type": args.get("type", "text"),
5005
5104
  }
5006
- 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"))
5007
5106
  for key in ("path", "glob", "file_type", "scope", "output_mode",
5008
5107
  "case_sensitive", "max_results", "use_regex"):
5009
5108
  if key == "path" and not has_explicit_root:
@@ -5397,6 +5496,20 @@ def _tool_timeout(tool_name: str, tool_args: dict) -> float:
5397
5496
  declared = fallback if has_verify else 0
5398
5497
  if declared > 0:
5399
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)
5400
5513
  if tool_name in _GRAPH_TOOLS:
5401
5514
  # Graph-backed calls may pay a one-time cold crawl; it is cached on disk, so
5402
5515
  # the next call is milliseconds. TOKENSAFE_MCP_GRAPH_TIMEOUT tunes the ceiling.
@@ -5483,6 +5596,9 @@ def _reload_due(now: Optional[float] = None) -> bool:
5483
5596
  """True when a pending upgrade may take the server down: armed AND idle."""
5484
5597
  if not _RELOAD_PENDING or not _auto_reload_enabled():
5485
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
5486
5602
  return (time.time() if now is None else now) - _LAST_ACTIVITY >= _reload_idle_seconds()
5487
5603
 
5488
5604
 
@@ -5499,19 +5615,836 @@ def _start_reload_watchdog(idle_sec: float) -> None:
5499
5615
  if not _SERVER_ACTIVE:
5500
5616
  return
5501
5617
  if _reload_due():
5502
- try:
5503
- sys.stdout.flush()
5504
- except Exception:
5505
- pass
5506
- os._exit(0)
5618
+ _exit_for_restart("", still_due=_reload_due)
5507
5619
 
5508
5620
  threading.Thread(target=_watch, name="tokensafe-mcp-reload", daemon=True).start()
5509
5621
 
5510
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
+
5511
6433
  def run_mcp_server():
5512
- """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
+ """
5513
6445
  global _MCP_CLIENT_NAME, _TOOLS_LISTED, _EPOCH_GEN, _DELIVERED_SESSION
5514
- global _LAST_ACTIVITY, _RELOAD_PENDING, _SERVER_ACTIVE
6446
+ global _LAST_ACTIVITY, _RELOAD_PENDING, _SERVER_ACTIVE, _CLIENT_HAS_ROOTS
6447
+ global _WORKER_SLOTS, _SERVER_CLOSED
5515
6448
  # Windows pipes default to the ANSI code page; one emoji in a response used
5516
6449
  # to raise UnicodeEncodeError and exit the whole server loop.
5517
6450
  from tokensafe.stdio_io import ensure_utf8_stdio
@@ -5519,9 +6452,15 @@ def run_mcp_server():
5519
6452
  ensure_utf8_stdio()
5520
6453
  _MCP_CLIENT_NAME = ""
5521
6454
  _TOOLS_LISTED = False
6455
+ _CLIENT_HAS_ROOTS = False
6456
+ _PENDING_ROOTS_REQUEST_ID[0] = None
5522
6457
  _EPOCH_GEN = 0
5523
6458
  _DELIVERED_SESSION = ""
5524
6459
  _IN_PROCESS_DELIVERED.clear()
6460
+ with _ACTIVE_LOCK:
6461
+ _ACTIVE_CALLS.clear()
6462
+ _SERVER_CLOSED = False
6463
+ _WORKER_SLOTS = threading.Semaphore(_mcp_workers())
5525
6464
  initial_mtimes = _get_watched_mtimes()
5526
6465
  auto_reload = _auto_reload_enabled()
5527
6466
  _LAST_ACTIVITY = time.time()
@@ -5529,137 +6468,90 @@ def run_mcp_server():
5529
6468
  _SERVER_ACTIVE = True
5530
6469
  if auto_reload:
5531
6470
  _start_reload_watchdog(_reload_idle_seconds())
6471
+ _start_stuck_watchdog()
5532
6472
 
5533
- while True:
5534
- try:
5535
- line = sys.stdin.readline()
5536
- except Exception:
5537
- break
5538
- if not line:
5539
- break
5540
- line = line.strip()
5541
- if not line:
5542
- continue
5543
-
5544
- try:
5545
- req = json.loads(line)
5546
- except Exception:
5547
- continue
5548
- if not isinstance(req, dict):
5549
- 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
5550
6484
 
5551
- msg_id = req.get("id")
5552
- method = req.get("method")
5553
- raw_params = req.get("params")
5554
- 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
5555
6491
 
5556
- # Notifications (no id, or notifications/*) must never receive JSON-RPC responses
5557
- if msg_id is None or (isinstance(method, str) and method.startswith("notifications/")):
5558
- 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
5559
6505
 
5560
- # A pending upgrade drains at a safe boundary only: the first initialize
5561
- # after the idle window (a new session has nothing to lose) or the
5562
- # watchdog. Never mid-session.
5563
- if method == "initialize" and auto_reload and _reload_due():
5564
- break
5565
- _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()
5566
6510
 
5567
- response = {"jsonrpc": "2.0", "id": msg_id}
6511
+ if method == "notifications/cancelled":
6512
+ _cancel_call(params.get("requestId"))
6513
+ continue
5568
6514
 
5569
- if method == "initialize":
5570
- try:
5571
- client_info = params.get("clientInfo") or {}
5572
- if isinstance(client_info, dict):
5573
- _set_mcp_client(str(client_info.get("name") or ""))
5574
- except Exception:
5575
- pass
5576
- try:
5577
- from tokensafe.telemetry_sync import TelemetrySync
5578
- TelemetrySync.sync_background()
5579
- except Exception:
5580
- pass
5581
- req_version = str(params.get("protocolVersion") or "")
5582
- supported_versions = ("2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25")
5583
- negotiated_version = req_version if req_version in supported_versions else "2025-06-18"
5584
- response["result"] = {
5585
- "protocolVersion": negotiated_version,
5586
- "capabilities": {"tools": {}},
5587
- "serverInfo": SERVER_INFO
5588
- }
5589
- # Routing brief (MCP `instructions`): which stacks this workspace
5590
- # works through OUMV and which through the TokenSafe tools. The
5591
- # default root resolves per server (session scope, then the spawn
5592
- # cwd, then the active marker), and extra roots — TOKENSAFE_WORKSPACES
5593
- # plus any multi-root payload the host passed to initialize — are
5594
- # classified one by one so a single-root verdict is never global.
5595
- try:
5596
- from tokensafe.session_brief import (
5597
- build_workspace_brief,
5598
- workspace_roots_from_env,
5599
- workspace_roots_from_payload,
5600
- )
5601
- extra_roots = workspace_roots_from_env() + workspace_roots_from_payload(params)
5602
- seen_roots = set()
5603
- extra_roots = [r for r in extra_roots if not (r in seen_roots or seen_roots.add(r))]
5604
- register_roots([_oumv_default_workspace() or os.getcwd()] + extra_roots)
5605
- brief = build_workspace_brief(
5606
- _oumv_default_workspace() or os.getcwd(),
5607
- include_live=False,
5608
- extra_workspaces=extra_roots,
5609
- )
5610
- if brief:
5611
- response["result"]["instructions"] = brief
5612
- except Exception:
5613
- pass
5614
- elif method == "tools/list":
5615
- _TOOLS_LISTED = True
5616
- profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
5617
- if profile == "full":
5618
- advertised = FULL_TOOLS
5619
- elif profile == "lean":
5620
- advertised = [t for t in TOOLS if t["name"] in _LEAN_TOOL_NAMES]
5621
- else:
5622
- advertised = TOOLS
5623
- response["result"] = {"tools": advertised}
5624
- elif method == "ping":
5625
- response["result"] = {}
5626
- elif method == "tools/call":
5627
- tool_name = str(params.get("name") or "")
5628
- raw_tool_args = params.get("arguments")
5629
- try:
5630
- tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
5631
- if not tool_args and raw_tool_args:
5632
- # Self-healing: hosts on small/local models intermittently send
5633
- # arguments as a malformed JSON string — repair before failing.
5634
- from tokensafe.json_repair import parse_tool_arguments
5635
- tool_args = parse_tool_arguments(raw_tool_args) or {}
5636
- raw_res = _execute_with_timeout(tool_name, tool_args, timeout=_tool_timeout(tool_name, tool_args))
5637
- redacted = _redact_result_secrets(raw_res)
5638
- response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
5639
- except Exception as e:
5640
- err_res = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
5641
- redacted = _redact_result_secrets(err_res)
5642
- response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
5643
- finally:
5644
- try:
5645
- from tokensafe.telemetry_sync import TelemetrySync
5646
- TelemetrySync.sync_background(throttle_seconds=5.0)
5647
- except Exception:
5648
- pass
5649
- else:
5650
- 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
5651
6518
 
5652
- try:
5653
- sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
5654
- sys.stdout.flush()
5655
- except Exception:
5656
- 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()
5657
6525
 
5658
- # An upgrade marker arms the drain; it never cuts the live session.
5659
- if auto_reload and _get_watched_mtimes() != initial_mtimes:
5660
- _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
5661
6548
 
5662
- _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
5663
6555
 
5664
6556
  def main():
5665
6557
  run_mcp_server()