tokensafe 4.7.8 → 4.7.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp_server.py CHANGED
@@ -44,7 +44,7 @@ from src.session_context import current_root, current_session_id
44
44
 
45
45
  SERVER_INFO = {
46
46
  "name": "tokensafe-mcp",
47
- "version": "4.7.8"
47
+ "version": "4.7.10"
48
48
  }
49
49
 
50
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -86,6 +86,48 @@ def _workspace_root() -> Optional[str]:
86
86
  return current_root() or get_active_workspace()
87
87
 
88
88
 
89
+ def _plausible_project_root(path: Optional[str]) -> bool:
90
+ """True when a directory can act as this server's workspace root.
91
+
92
+ Rejects missing/non-dirs, system/plugin dirs, and OS scratch space — the
93
+ same classes of roots the lifecycle hooks refuse for the active marker."""
94
+ if not path or not os.path.isdir(path):
95
+ return False
96
+ if is_plugin_or_system_dir(path):
97
+ return False
98
+ try:
99
+ from src.paths import is_transient_dir
100
+ if is_transient_dir(path):
101
+ return False
102
+ except Exception:
103
+ pass
104
+ return True
105
+
106
+
107
+ def _oumv_default_workspace() -> Optional[str]:
108
+ """Default workspace for an oumv call that carries no explicit root.
109
+
110
+ Precedence: session scope (ACP agent, in-process loop) > this server's own
111
+ spawn cwd > the machine-wide active marker. The marker is rewritten by the
112
+ hooks of EVERY concurrent session, so in multi-root setups it can name a
113
+ repo the caller never asked about; the MCP server is started by the host
114
+ with cwd in the primary workspace, which is per-server and race-free.
115
+ """
116
+ scoped = current_root()
117
+ # Session scope is bound explicitly by our own in-process agent / ACP server
118
+ # (benchmark and smoke workspaces legitimately live in temp dirs), so only
119
+ # existence and system-dir checks apply here.
120
+ if scoped and os.path.isdir(scoped) and not is_plugin_or_system_dir(scoped):
121
+ return scoped
122
+ cwd = os.getcwd()
123
+ if _plausible_project_root(cwd):
124
+ return cwd
125
+ marker = get_active_workspace()
126
+ if marker:
127
+ return marker
128
+ return cwd or None
129
+
130
+
89
131
  def _client_supports_pointers() -> bool:
90
132
  """Out-of-the-box capability detection (zero env vars): returns True once the
91
133
  MCP client has fetched tools/list (seeing force_full) or identified as an
@@ -779,7 +821,8 @@ TOOLS = [{'name': 'smart_read_file',
779
821
  'transcript_path': {'type': 'string'}}}},
780
822
  {'name': 'oumv',
781
823
  'annotations': {'readOnlyHint': False},
782
- 'description': "OUMV runtime: 'status'|'observe' L0-L4|'understand'|'verify'|'mutate' (OCC edit)|'graph'.",
824
+ 'description': "OUMV runtime: 'status'|'observe' L0-L4|'understand'|'verify'|'mutate' (OCC edit)|'graph'|'index' "
825
+ "(repo-wide symbol search: query, kinds?, limit?)|'preview' (dry-run diff, no write).",
783
826
  'inputSchema': {'type': 'object',
784
827
  'properties': {'action': {'type': 'string',
785
828
  'enum': ['status',
@@ -787,7 +830,10 @@ TOOLS = [{'name': 'smart_read_file',
787
830
  'understand',
788
831
  'verify',
789
832
  'mutate',
790
- 'graph']},
833
+ 'graph',
834
+ 'index',
835
+ 'preview',
836
+ 'build']},
791
837
  'level': {'type': 'string'},
792
838
  'query': {'type': 'string'},
793
839
  'target': {'type': 'string'},
@@ -795,11 +841,20 @@ TOOLS = [{'name': 'smart_read_file',
795
841
  'symbol': {'type': 'string'},
796
842
  'replacement': {'type': 'string'},
797
843
  'expectedVersion': {'type': 'string'},
844
+ 'kinds': {'type': 'array',
845
+ 'items': {'type': 'string'},
846
+ 'description': 'index: symbol-kind filter (function, class, ...)'},
847
+ 'limit': {'type': 'integer'},
848
+ 'batch': {'type': 'array',
849
+ 'items': {'type': 'object'},
850
+ 'description': 'preview: batch edits envelope (wire 1.5.0+)'},
851
+ 'timeout_ms': {'type': 'integer',
852
+ 'description': 'preview/build: per-call budget (§3/§14.3)'},
798
853
  'verify_action': {'type': 'string'},
799
854
  'payload': {'type': 'object'},
800
855
  'workspace_dir': {'type': 'string',
801
856
  'description': 'Target repo root; for '
802
- 'status/observe/understand/verify/graph '
857
+ 'status/observe/understand/verify/graph/index/preview '
803
858
  'also accepted as path'}}}},
804
859
  {'name': 'run_helper',
805
860
  'annotations': {'readOnlyHint': False},
@@ -1067,18 +1122,20 @@ def _shared_batch_root(paths: List[str], real_cwd: str) -> Optional[str]:
1067
1122
 
1068
1123
 
1069
1124
  def _oumv_workspace_arg(args: dict, allow_path: bool = False) -> Tuple[Optional[str], Optional[str]]:
1070
- """Validated workspace root for an OUMV call; None means "use the active one".
1125
+ """Validated workspace root for an OUMV call; falls back to a per-server default.
1071
1126
 
1072
1127
  The MCP server inherits the host process cwd, so without this an explicit
1073
1128
  target repo was either dropped (unadvertised property) or ignored, and the
1074
1129
  answer described the bound workspace. A root that does not exist now fails
1075
- closed instead of reporting another repo's stack.
1130
+ closed instead of reporting another repo's stack. With no explicit root the
1131
+ default is the session scope or this server's own cwd — not the machine-wide
1132
+ marker another concurrent session may have just rewritten.
1076
1133
  """
1077
1134
  raw = str(args.get("workspace_dir") or "").strip()
1078
1135
  if not raw and allow_path:
1079
1136
  raw = str(args.get("path") or "").strip()
1080
1137
  if not raw:
1081
- return None, None
1138
+ return _oumv_default_workspace(), None
1082
1139
  ws = os.path.abspath(raw)
1083
1140
  if os.path.isfile(ws):
1084
1141
  ws = os.path.dirname(ws)
@@ -1866,6 +1923,9 @@ _OUMV_ACTIONS = {
1866
1923
  "mutate": "oumv_mutate",
1867
1924
  "verify": "oumv_verify",
1868
1925
  "graph": "oumv_graph",
1926
+ "index": "oumv_index",
1927
+ "preview": "oumv_preview",
1928
+ "build": "oumv_build",
1869
1929
  }
1870
1930
  _HELPER_ACTIONS = {
1871
1931
  "sanitize": "sanitize_command",
@@ -1957,7 +2017,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1957
2017
  # wrong answer. Resolve the explicit root here and fail closed on a bad one.
1958
2018
  ws, ws_err = _oumv_workspace_arg(
1959
2019
  args,
1960
- allow_path=action in ("status", "observe", "understand", "verify", "graph"),
2020
+ allow_path=action in ("status", "observe", "understand", "verify", "graph", "index", "preview", "build"),
1961
2021
  )
1962
2022
  if ws_err:
1963
2023
  return _fallback_error("oumv", ws_err)
@@ -3246,7 +3306,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3246
3306
  ws, ws_err = _oumv_workspace_arg(args, allow_path=True)
3247
3307
  if ws_err:
3248
3308
  return _fallback_error("oumv_status", ws_err)
3249
- ws = ws or get_active_workspace() or os.getcwd()
3309
+ ws = ws or _oumv_default_workspace() or os.getcwd()
3250
3310
  res = OUMVGateway.status(workspace_dir=ws)
3251
3311
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3252
3312
  except Exception as e:
@@ -3325,6 +3385,57 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3325
3385
  except Exception as e:
3326
3386
  return _fallback_error("oumv_graph", f"failed to query cross-stack graph: {e}")
3327
3387
 
3388
+ elif name == "oumv_index":
3389
+ try:
3390
+ from src.oumv_gateway import OUMVGateway
3391
+ q = str(args.get("query") or "").strip()
3392
+ kinds = args.get("kinds") if isinstance(args.get("kinds"), list) else None
3393
+ limit = args.get("limit") if isinstance(args.get("limit"), int) else 25
3394
+ ws, ws_err = _oumv_workspace_arg(args)
3395
+ if ws_err:
3396
+ return _fallback_error("oumv_index", ws_err)
3397
+ if not q:
3398
+ return _fallback_error("oumv_index", "missing required 'query' (symbol name or substring)")
3399
+ res = OUMVGateway.index(query=q, kinds=kinds, limit=limit, workspace_dir=ws)
3400
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3401
+ except Exception as e:
3402
+ return _fallback_error("oumv_index", f"failed to search symbol index: {e}")
3403
+
3404
+ elif name == "oumv_preview":
3405
+ try:
3406
+ from src.oumv_gateway import OUMVGateway
3407
+ p = str(args.get("path") or "").strip()
3408
+ sym = str(args.get("symbol") or "").strip() or None
3409
+ rep = args.get("replacement")
3410
+ ev = str(args.get("expectedVersion") or "").strip() or None
3411
+ batch = args.get("batch") if isinstance(args.get("batch"), list) else None
3412
+ rt = str(args.get("runtime") or "auto").strip()
3413
+ ws, ws_err = _oumv_workspace_arg(args)
3414
+ if ws_err:
3415
+ return _fallback_error("oumv_preview", ws_err)
3416
+ if not p:
3417
+ return _fallback_error("oumv_preview", "missing required 'path'")
3418
+ res = OUMVGateway.preview(path=p, symbol=sym, replacement=rep, expected_version=ev,
3419
+ batch=batch, runtime=rt, workspace_dir=ws)
3420
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3421
+ except Exception as e:
3422
+ return _fallback_error("oumv_preview", f"failed to preview OUMV mutation: {e}")
3423
+
3424
+ elif name == "oumv_build":
3425
+ try:
3426
+ from src.oumv_gateway import OUMVGateway
3427
+ cmd = str(args.get("command") or "").strip() or None
3428
+ tgt = str(args.get("target") or "").strip() or None
3429
+ tms = args.get("timeout_ms") if isinstance(args.get("timeout_ms"), int) else None
3430
+ rt = str(args.get("runtime") or "auto").strip()
3431
+ ws, ws_err = _oumv_workspace_arg(args)
3432
+ if ws_err:
3433
+ return _fallback_error("oumv_build", ws_err)
3434
+ res = OUMVGateway.build(command=cmd, target=tgt, timeout_ms=tms, runtime=rt, workspace_dir=ws)
3435
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3436
+ except Exception as e:
3437
+ return _fallback_error("oumv_build", f"failed to run OUMV build: {e}")
3438
+
3328
3439
  elif name == "apply_edits":
3329
3440
  try:
3330
3441
  from src.batch_editor import execute_batch_edits
@@ -3918,15 +4029,23 @@ def run_mcp_server():
3918
4029
  }
3919
4030
  # Routing brief (MCP `instructions`): which stacks this workspace
3920
4031
  # works through OUMV and which through the TokenSafe tools. The
3921
- # server usually runs from the plugin dir, so prefer the session
3922
- # workspace marker; extra roots (TOKENSAFE_WORKSPACES) are
4032
+ # default root resolves per server (session scope, then the spawn
4033
+ # cwd, then the active marker), and extra roots — TOKENSAFE_WORKSPACES
4034
+ # plus any multi-root payload the host passed to initialize — are
3923
4035
  # classified one by one so a single-root verdict is never global.
3924
4036
  try:
3925
- from src.session_brief import build_workspace_brief, workspace_roots_from_env
4037
+ from src.session_brief import (
4038
+ build_workspace_brief,
4039
+ workspace_roots_from_env,
4040
+ workspace_roots_from_payload,
4041
+ )
4042
+ extra_roots = workspace_roots_from_env() + workspace_roots_from_payload(params)
4043
+ seen_roots = set()
4044
+ extra_roots = [r for r in extra_roots if not (r in seen_roots or seen_roots.add(r))]
3926
4045
  brief = build_workspace_brief(
3927
- _workspace_root() or os.getcwd(),
4046
+ _oumv_default_workspace() or os.getcwd(),
3928
4047
  include_live=False,
3929
- extra_workspaces=workspace_roots_from_env(),
4048
+ extra_workspaces=extra_roots,
3930
4049
  )
3931
4050
  if brief:
3932
4051
  response["result"]["instructions"] = brief