tokensafe 4.7.0 → 4.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp_server.py CHANGED
@@ -43,7 +43,7 @@ from src.session_context import current_root, current_session_id
43
43
 
44
44
  SERVER_INFO = {
45
45
  "name": "tokensafe-mcp",
46
- "version": "4.7.0"
46
+ "version": "4.7.2"
47
47
  }
48
48
 
49
49
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -295,6 +295,9 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
295
295
  'inputSchema': { 'properties': { 'case_sensitive': { 'description': 'Case-sensitive search (default '
296
296
  'false)',
297
297
  'type': 'boolean'},
298
+ 'cwd': { 'description': 'Base directory for a relative path '
299
+ '(defaults to the active project)',
300
+ 'type': 'string'},
298
301
  'max_results': { 'description': 'Max matching lines (default 25, max '
299
302
  '100)',
300
303
  'type': 'integer'},
@@ -661,219 +664,165 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
661
664
 
662
665
  # Compact MCP surface (default): 7 consolidated tools (~2.2k tok vs ~6.0k tok for 28 schemas).
663
666
  # All 28 legacy tool names remain callable in _dispatch_tool_call for backward compatibility.
664
- # Set TOKENSAFE_MCP_PROFILE=full to expose FULL_TOOLS in tools/list.
665
- TOOLS = [
666
- {
667
- 'name': 'smart_read_file',
668
- 'description': (
669
- 'AST-skeleton reader (-90-98% tokens). Pass path+symbol for one file (auto-slices '
670
- 'OpenAPI/Prisma/GraphQL/SQL/lockfiles), targets=[{path,symbol}] to bundle 2-8 symbols, '
671
- 'or package_name+symbol for 3rd-party .d.ts types.'
672
- ),
673
- 'annotations': {'readOnlyHint': True},
674
- 'inputSchema': {
675
- 'type': 'object',
676
- 'properties': {
677
- 'path': {'type': 'string', 'description': 'File path (relative or absolute)'},
678
- 'symbol': {'type': 'string', 'description': 'Function/class/model/type to extract'},
679
- 'start_line': {'type': 'integer', 'description': 'Optional start line'},
680
- 'end_line': {'type': 'integer', 'description': 'Optional end line'},
681
- 'dep_mode': {'type': 'string', 'enum': ['signature', 'full'], 'description': '1-hop dep mode (default signature)'},
682
- 'include_deps': {'type': 'boolean', 'description': 'Include 1-hop deps (default true)'},
683
- 'force_full': {'type': 'boolean', 'description': 'Bypass pointer dedup'},
684
- 'project_root': {'type': 'string', 'description': 'Workspace root directory (for external types / lockfiles)'},
685
- 'targets': {
686
- 'type': 'array', 'maxItems': 8,
687
- 'description': 'Bundle mode: 2-8 {path, symbol} targets in one call',
688
- 'items': {'type': 'object', 'properties': {'path': {'type': 'string'}, 'symbol': {'type': 'string'}}, 'required': ['path']},
689
- },
690
- 'package_name': {'type': 'string', 'description': 'External .d.ts npm package name'},
691
- },
692
- },
693
- },
694
- {
695
- 'name': 'scoped_search',
696
- 'description': (
697
- 'Safe token-bounded search replacing grep/find (-90% tokens). Pass query+scope for single '
698
- 'search (mode/type: auto|text|regex|glob|fuzzy|git), or queries=[{pattern,type,path,glob}] '
699
- 'for up to 20 concurrent queries.'
700
- ),
701
- 'annotations': {'readOnlyHint': True},
702
- 'inputSchema': {
703
- 'type': 'object',
704
- 'properties': {
705
- 'query': {'type': 'string', 'description': 'Text, symbol, regex, glob, or read-only git query'},
706
- 'mode': {'type': 'string', 'enum': ['auto', 'text', 'regex', 'glob', 'fuzzy', 'git'], 'description': 'Single-query mode'},
707
- 'scope': {'type': 'string', 'description': "'code', 'config', 'all', ext ('py'), or subfolder"},
708
- 'path': {'type': 'string', 'description': 'Directory path (default project root)'},
709
- 'project_path': {'type': 'string', 'description': 'Alias for path'},
710
- 'use_regex': {'type': 'boolean', 'description': 'Force regex true/false'},
711
- 'case_sensitive': {'type': 'boolean'},
712
- 'max_results': {'type': 'integer', 'description': 'Max lines (default 25, max 100)'},
713
- 'queries': {
714
- 'type': 'array', 'maxItems': 20,
715
- 'description': 'Batch mode: up to 20 {pattern, type, path, glob, output_mode} objects',
716
- 'items': {
717
- 'type': 'object',
718
- 'properties': {
719
- 'pattern': {'type': 'string'},
720
- 'type': {'type': 'string', 'enum': ['text', 'regex', 'glob', 'fuzzy', 'git']},
721
- 'path': {'type': 'string'},
722
- 'glob': {'type': 'string'},
723
- 'file_type': {'type': 'string'},
724
- 'output_mode': {'type': 'string', 'enum': ['content', 'files_with_matches', 'count']},
725
- 'case_sensitive': {'type': 'boolean'},
726
- 'max_results': {'type': 'integer'},
727
- },
728
- 'required': ['pattern'],
729
- },
730
- },
731
- 'cwd': {'type': 'string', 'description': 'Optional working directory for batch mode'},
732
- },
733
- },
734
- },
735
- {
736
- 'name': 'apply_edits',
737
- 'description': 'Atomic/best-effort multi-hunk editor (up to 50 files) with optional inline verify command.',
738
- 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
739
- 'inputSchema': {
740
- 'type': 'object',
741
- 'properties': {
742
- 'edits': {
743
- 'type': 'array', 'maxItems': 50,
744
- 'items': {
745
- 'type': 'object',
746
- 'properties': {
747
- 'path': {'type': 'string'},
748
- 'create': {'type': 'string'},
749
- 'overwrite': {'type': 'boolean'},
750
- 'hunks': {
751
- 'type': 'array',
752
- 'items': {
753
- 'type': 'object',
754
- 'properties': {
755
- 'target': {'type': 'string'},
756
- 'replacement': {'type': 'string'},
757
- 'start_line': {'type': 'integer'},
758
- 'end_line': {'type': 'integer'},
759
- 'replace_all': {'type': 'boolean'},
760
- },
761
- 'required': ['target', 'replacement'],
762
- },
763
- },
764
- },
765
- 'required': ['path'],
766
- },
767
- },
768
- 'best_effort': {'type': 'boolean'},
769
- 'dry_run': {'type': 'boolean'},
770
- 'verify': {'type': 'string', 'description': 'Shell command to run after edits (e.g. pytest, npm test)'},
771
- 'verify_timeout_sec': {'type': 'integer'},
772
- 'cwd': {'type': 'string'},
773
- },
774
- 'required': ['edits'],
775
- },
776
- },
777
- {
778
- 'name': 'repo_map',
779
- 'description': (
780
- 'Project structure & architecture without crawling: view="graph" (God Nodes & deps), '
781
- '"api" (exported classes/types/interfaces), or "tree" (clean directory tree).'
782
- ),
783
- 'annotations': {'readOnlyHint': True},
784
- 'inputSchema': {
785
- 'type': 'object',
786
- 'properties': {
787
- 'view': {'type': 'string', 'enum': ['graph', 'api', 'tree'], 'default': 'graph'},
788
- 'project_path': {'type': 'string', 'description': 'Project root (pass absolute path in multi-repo setups)'},
789
- 'path': {'type': 'string', 'description': "Directory path for view='tree' (default '.')"},
790
- 'depth': {'type': 'integer', 'description': 'Tree depth (default 2, max 4)'},
791
- 'max_entries': {'type': 'integer'},
792
- },
793
- },
794
- },
795
- {
796
- 'name': 'session_context',
797
- 'description': (
798
- 'Session & context hygiene: action="budget" (Context Quality Score S-F), "compact" (fold transcript '
799
- 'to State Ledger), "prune" (drop superseded reads), "mistakes" (anti-stuck memory), or "metrics".'
800
- ),
801
- 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
802
- 'inputSchema': {
803
- 'type': 'object',
804
- 'properties': {
805
- 'action': {'type': 'string', 'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics'], 'default': 'budget'},
806
- 'model': {'type': 'string'},
807
- 'session_id': {'type': 'string'},
808
- 'transcript_path': {'type': 'string'},
809
- 'window_tokens': {'type': 'integer'},
810
- 'invocation_num': {'type': 'integer'},
811
- 'project_root': {'type': 'string'},
812
- 'clear': {'type': 'boolean'},
813
- },
814
- 'required': ['action'],
815
- },
816
- },
817
- {
818
- 'name': 'oumv',
819
- 'description': (
820
- 'Live Frontend/Backend OUMV runtime protocol: action="status"|"observe" (L0-L4)|"understand" '
821
- '(causality/impact)|"verify" (in-memory sandbox)|"mutate" (OCC edit)|"graph" (cross-stack).'
822
- ),
823
- 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
824
- 'inputSchema': {
825
- 'type': 'object',
826
- 'properties': {
827
- 'action': {'type': 'string', 'enum': ['status', 'observe', 'understand', 'mutate', 'verify', 'graph'], 'default': 'status'},
828
- 'level': {'type': 'string', 'enum': ['L0', 'L1', 'L2', 'L3', 'L4']},
829
- 'query': {'type': 'string'},
830
- 'runtime': {'type': 'string', 'enum': ['frontend', 'backend', 'auto']},
831
- 'target': {'type': 'string'},
832
- 'path': {'type': 'string'},
833
- 'symbol': {'type': 'string'},
834
- 'replacement': {'type': 'string'},
835
- 'expectedVersion': {'type': 'string'},
836
- 'verify_action': {'type': 'string', 'description': "Action name for action='verify' (e.g. click, submit)"},
837
- 'payload': {'type': 'object'},
838
- 'workspace_dir': {'type': 'string'},
839
- },
840
- 'required': ['action'],
841
- },
842
- },
843
- {
844
- 'name': 'run_helper',
845
- 'description': (
846
- 'Unified utility runner: action="sanitize" (rewrite bash/tests), "guard" (security/hygiene check), '
847
- '"diff" (slice diff), "deps" (query lockfile), "web" (fetch clean MD), "expand" (unfold #hash), '
848
- '"image" (downscale), or "compress" (TOCP prompt).'
849
- ),
850
- 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
851
- 'inputSchema': {
852
- 'type': 'object',
853
- 'properties': {
854
- 'action': {
855
- 'type': 'string',
856
- 'enum': ['sanitize', 'guard', 'diff', 'deps', 'web', 'expand', 'image', 'compress'],
857
- },
858
- 'command': {'type': 'string'},
859
- 'code': {'type': 'string'},
860
- 'file_path': {'type': 'string'},
861
- 'diff': {'type': 'string'},
862
- 'max_context': {'type': 'integer'},
863
- 'package_name': {'type': 'string'},
864
- 'lockfile_path': {'type': 'string'},
865
- 'url': {'type': 'string'},
866
- 'force_refresh': {'type': 'boolean'},
867
- 'hash': {'type': 'string'},
868
- 'image_path': {'type': 'string'},
869
- 'max_edge': {'type': 'integer'},
870
- 'prompt': {'type': 'string'},
871
- 'cwd': {'type': 'string'},
872
- },
873
- 'required': ['action'],
874
- },
875
- },
876
- ]
667
+ # Set TOKENSAFE_MCP_PROFILE=full to expose FULL_TOOLS in tools/list, or =lean for the
668
+ # five tools a code session uses (read / search / edit / map / oumv). Each advertised tool is
669
+ # re-sent in every request, so an unused tool is a per-step tax: the seven-tool surface
670
+ # costs ~1,615 tokens per request, the lean one ~1,100.
671
+ _LEAN_TOOL_NAMES = frozenset({"smart_read_file", "scoped_search", "apply_edits", "repo_map", "oumv"})
672
+ # Slim tool surface: 7 tools, every enum kept, prose and unused optional
673
+ # parameters dropped (the runtime still accepts them). ~35% smaller than the
674
+ # previous literal: this schema is re-sent in every request of every session.
675
+ TOOLS = [{'name': 'smart_read_file',
676
+ 'annotations': {'readOnlyHint': True},
677
+ 'description': 'AST-skeleton reader. path+symbol for one file, targets=[{path,symbol}] for 2-8 at once, '
678
+ 'package_name+symbol for .d.ts.',
679
+ 'inputSchema': {'type': 'object',
680
+ 'properties': {'path': {'type': 'string', 'description': 'File path'},
681
+ 'symbol': {'type': 'string',
682
+ 'description': "Identifier, 'Type.Method', endpoint or schema "
683
+ 'model; a non-declaration returns the enclosing '
684
+ 'body'},
685
+ 'start_line': {'type': 'integer'},
686
+ 'end_line': {'type': 'integer'},
687
+ 'dep_mode': {'type': 'string', 'enum': ['signature', 'full']},
688
+ 'include_deps': {'type': 'boolean'},
689
+ 'force_full': {'type': 'boolean'},
690
+ 'targets': {'type': 'array',
691
+ 'maxItems': 8,
692
+ 'items': {'type': 'object',
693
+ 'properties': {'path': {'type': 'string'},
694
+ 'symbol': {'type': 'string'}},
695
+ 'required': ['path']}},
696
+ 'package_name': {'type': 'string', 'description': '.d.ts npm package'}},
697
+ 'required': ['path']}},
698
+ {'name': 'scoped_search',
699
+ 'annotations': {'readOnlyHint': True},
700
+ 'description': 'Bounded search replacing grep/find. Single query+scope, or '
701
+ 'queries=[{pattern,type,path,glob}] for up to 20.',
702
+ 'inputSchema': {'type': 'object',
703
+ 'properties': {'query': {'type': 'string'},
704
+ 'mode': {'type': 'string',
705
+ 'enum': ['auto', 'text', 'regex', 'glob', 'fuzzy', 'git']},
706
+ 'scope': {'type': 'string',
707
+ 'description': "'code','config','all', ext or subfolder"},
708
+ 'path': {'type': 'string'},
709
+ 'project_path': {'type': 'string', 'description': 'alias for path'},
710
+ 'cwd': {'type': 'string',
711
+ 'description': 'base dir for a relative path'},
712
+ 'use_regex': {'type': 'boolean'},
713
+ 'case_sensitive': {'type': 'boolean'},
714
+ 'max_results': {'type': 'integer', 'description': 'default 25, max 100'},
715
+ 'per_file': {'type': 'integer',
716
+ 'description': 'hits per file (default auto)'},
717
+ 'queries': {'type': 'array',
718
+ 'maxItems': 20,
719
+ 'items': {'type': 'object',
720
+ 'properties': {'pattern': {'type': 'string'},
721
+ 'type': {'type': 'string',
722
+ 'enum': ['text',
723
+ 'regex',
724
+ 'glob',
725
+ 'fuzzy',
726
+ 'git']},
727
+ 'path': {'type': 'string'},
728
+ 'glob': {'type': 'string'},
729
+ 'file_type': {'type': 'string'},
730
+ 'output_mode': {'type': 'string',
731
+ 'enum': ['content',
732
+ 'files_with_matches',
733
+ 'count']},
734
+ 'max_results': {'type': 'integer'}},
735
+ 'required': ['pattern']}}}}},
736
+ {'name': 'apply_edits',
737
+ 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
738
+ 'description': 'Multi-hunk editor (up to 50 files) with optional inline verify: the edit and its verdict '
739
+ 'come back in one call.',
740
+ 'inputSchema': {'type': 'object',
741
+ 'properties': {'edits': {'type': 'array',
742
+ 'maxItems': 50,
743
+ 'items': {'type': 'object',
744
+ 'properties': {'path': {'type': 'string'},
745
+ 'create': {'type': 'string'},
746
+ 'overwrite': {'type': 'boolean'},
747
+ 'hunks': {'type': 'array',
748
+ 'items': {'type': 'object',
749
+ 'properties': {'target': {'type': 'string'},
750
+ 'replacement': {'type': 'string'},
751
+ 'start_line': {'type': 'integer'},
752
+ 'end_line': {'type': 'integer'},
753
+ 'replace_all': {'type': 'boolean'}},
754
+ 'required': ['target',
755
+ 'replacement']}}},
756
+ 'required': ['path']}},
757
+ 'dry_run': {'type': 'boolean'},
758
+ 'best_effort': {'type': 'boolean'},
759
+ 'verify': {'type': 'string',
760
+ 'description': "Command run after the edit; 'auto' = the "
761
+ "project's declared test command"}},
762
+ 'required': ['edits']}},
763
+ {'name': 'repo_map',
764
+ 'annotations': {'readOnlyHint': True},
765
+ 'description': "Structure without crawling: view='graph' (God Nodes), 'api' (exports) or 'tree' "
766
+ '(directories).',
767
+ 'inputSchema': {'type': 'object',
768
+ 'properties': {'view': {'type': 'string', 'enum': ['graph', 'api', 'tree']},
769
+ 'project_path': {'type': 'string',
770
+ 'description': 'Absolute path in multi-repo setups'},
771
+ 'path': {'type': 'string'},
772
+ 'depth': {'type': 'integer'}}}},
773
+ {'name': 'session_context',
774
+ 'annotations': {'readOnlyHint': False},
775
+ 'description': "Context hygiene: 'budget' (score S-F), 'compact' (fold transcript), 'prune' (drop "
776
+ "superseded reads), 'mistakes', 'metrics'.",
777
+ 'inputSchema': {'type': 'object',
778
+ 'properties': {'action': {'type': 'string',
779
+ 'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics']},
780
+ 'model': {'type': 'string'},
781
+ 'transcript_path': {'type': 'string'}}}},
782
+ {'name': 'oumv',
783
+ 'annotations': {'readOnlyHint': False},
784
+ 'description': "OUMV runtime: 'status'|'observe' L0-L4|'understand'|'verify'|'mutate' (OCC edit)|'graph'.",
785
+ 'inputSchema': {'type': 'object',
786
+ 'properties': {'action': {'type': 'string',
787
+ 'enum': ['status',
788
+ 'observe',
789
+ 'understand',
790
+ 'verify',
791
+ 'mutate',
792
+ 'graph']},
793
+ 'level': {'type': 'string'},
794
+ 'query': {'type': 'string'},
795
+ 'target': {'type': 'string'},
796
+ 'path': {'type': 'string'},
797
+ 'symbol': {'type': 'string'},
798
+ 'replacement': {'type': 'string'},
799
+ 'expectedVersion': {'type': 'string'},
800
+ 'verify_action': {'type': 'string'},
801
+ 'payload': {'type': 'object'}}}},
802
+ {'name': 'run_helper',
803
+ 'annotations': {'readOnlyHint': False},
804
+ 'description': "Utilities: 'sanitize','guard','diff','deps','web','expand','image','compress'.",
805
+ 'inputSchema': {'type': 'object',
806
+ 'properties': {'action': {'type': 'string',
807
+ 'enum': ['sanitize',
808
+ 'guard',
809
+ 'diff',
810
+ 'deps',
811
+ 'web',
812
+ 'expand',
813
+ 'image',
814
+ 'compress']},
815
+ 'command': {'type': 'string'},
816
+ 'code': {'type': 'string'},
817
+ 'file_path': {'type': 'string'},
818
+ 'diff': {'type': 'string'},
819
+ 'package_name': {'type': 'string'},
820
+ 'lockfile_path': {'type': 'string'},
821
+ 'url': {'type': 'string'},
822
+ 'hash': {'type': 'string'},
823
+ 'image_path': {'type': 'string'},
824
+ 'max_edge': {'type': 'integer'},
825
+ 'prompt': {'type': 'string'}}}}]
877
826
 
878
827
  def format_file_size(size_bytes: int) -> str:
879
828
  if size_bytes < 1024:
@@ -1235,6 +1184,196 @@ def _read_line_slice(path: str, start_line: Optional[int], end_line: Optional[in
1235
1184
  return "".join(selected), None
1236
1185
 
1237
1186
 
1187
+ _SYMBOL_MISS_MAX_LINES = 200
1188
+ _SYMBOL_MISS_HIT_CAP = 8
1189
+ _SYMBOL_MISS_FULL_DECL_LINES = 60 # a declaration up to this size is shown whole
1190
+ _SYMBOL_MISS_WINDOW_PAD = 8 # otherwise: ±lines around each hit
1191
+ _SYMBOL_MISS_WINDOW_HITS = 3
1192
+
1193
+
1194
+ def _symbol_scope(graph: Any, rel_path: str, symbol: str, code: str) -> Dict[str, Any]:
1195
+ """Resolve what `symbol` means for *this* file before any skeleton is built.
1196
+
1197
+ A `symbol` is not always a declaration in the file the caller pointed at: it may
1198
+ be a method of a type that lives elsewhere, or plain text inside an anonymous
1199
+ closure (Go `r.POST("/x", func(c *gin.Context) { ... })`, Express handlers,
1200
+ decorators). Skeletonizing then folds away everything while the header still
1201
+ claims "Full body" — the caller pays for the call, gets nothing actionable and
1202
+ re-reads the whole file, which is strictly worse than not calling at all.
1203
+
1204
+ Returns {status, decls, hit_lines, enclosing, elsewhere}:
1205
+ declared — a declaration by that name lives here (the skeleton keeps its body)
1206
+ body_here — no declaration here, but the text occurs inside one (closure case)
1207
+ absent — the text does not occur here at all
1208
+ """
1209
+ decls: List[Tuple[str, int, int]] = [] # every declaration in this file
1210
+ matched_here = False
1211
+ elsewhere: Optional[Tuple[str, int, int, str]] = None
1212
+ for key, sym in getattr(graph, "symbols", {}).items():
1213
+ qualified = key.split("::", 1)[-1]
1214
+ matches = sym.name == symbol or qualified == symbol or qualified.endswith("." + symbol)
1215
+ if sym.file_path == rel_path:
1216
+ decls.append((sym.name, sym.line_start, sym.line_end))
1217
+ matched_here = matched_here or matches
1218
+ elif matches and elsewhere is None:
1219
+ elsewhere = (sym.file_path, sym.line_start, sym.line_end, sym.name)
1220
+
1221
+ decls.sort(key=lambda d: d[1])
1222
+ plan: Dict[str, Any] = {
1223
+ "status": "absent",
1224
+ "decls": decls,
1225
+ "hit_lines": [],
1226
+ "enclosing": None,
1227
+ "elsewhere": elsewhere,
1228
+ }
1229
+ if matched_here:
1230
+ plan["status"] = "declared"
1231
+ return plan
1232
+
1233
+ try:
1234
+ pattern = re.compile(rf"\b{re.escape(symbol)}\b")
1235
+ except re.error:
1236
+ return plan
1237
+ # A caller's "symbol" is often a compound target rather than an identifier:
1238
+ # "POST /api/products", "GET /orders/{id}", "@app.route('/x')". Probe the
1239
+ # whole string first, then narrower predicates (all tokens on one line, the
1240
+ # path token, then identifiers) so an endpoint target anchors on the exact
1241
+ # route registration instead of on every line containing the HTTP verb.
1242
+ parts = [p for p in re.split(r"[\s\"'`(),;]+", symbol) if p]
1243
+ verbs = [p for p in parts if p.upper() in ("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS")]
1244
+ paths = [p for p in parts if p.startswith("/")]
1245
+ bare_names = [p for p in parts if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{2,}", p)]
1246
+ # dotted targets ("Type.Method") resolve to the member first, the type second
1247
+ member_names = [seg for p in parts for seg in reversed(p.split(".")) if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{2,}", seg)]
1248
+ name_parts = member_names + bare_names
1249
+
1250
+ def _is_identifier(value: str) -> bool:
1251
+ return bool(re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", value))
1252
+
1253
+ def _word(value: str) -> Any:
1254
+ return lambda line, q=value: re.search(rf"\b{re.escape(q)}\b", line) is not None
1255
+
1256
+ predicates: List[Tuple[str, Any]] = []
1257
+ if _is_identifier(symbol):
1258
+ predicates.append((symbol, _word(symbol)))
1259
+ else:
1260
+ predicates.append((symbol, lambda line, q=symbol: q in line))
1261
+ if paths and verbs:
1262
+ predicates.append((
1263
+ f"{verbs[0]} \"{paths[0]}\"",
1264
+ lambda line, v=verbs[0], q=paths[0]: v in line and f'"{q}"' in line,
1265
+ ))
1266
+ for p in paths:
1267
+ predicates.append((f'"{p}"', lambda line, q=p: f'"{q}"' in line))
1268
+ if len(parts) > 1:
1269
+ predicates.append((" ".join(parts), lambda line, ps=parts: all(p in line for p in ps)))
1270
+ for p in paths:
1271
+ predicates.append((p, lambda line, q=p: q in line))
1272
+ for p in dict.fromkeys(name_parts):
1273
+ predicates.append((p, _word(p)))
1274
+
1275
+ matched_probe = None
1276
+ for label, predicate in predicates:
1277
+ hits = []
1278
+ for idx, line in enumerate(code.splitlines(), 1):
1279
+ if predicate(line):
1280
+ hits.append(idx)
1281
+ if len(hits) >= _SYMBOL_MISS_HIT_CAP:
1282
+ break
1283
+ if hits:
1284
+ plan["hit_lines"] = hits
1285
+ matched_probe = label
1286
+ break
1287
+ plan["probe"] = matched_probe
1288
+ if not plan["hit_lines"]:
1289
+ return plan
1290
+
1291
+ first = plan["hit_lines"][0]
1292
+ best: Optional[Tuple[str, int, int]] = None
1293
+ for name, start, end in decls: # innermost declaration wins
1294
+ if start <= first <= end and (best is None or (end - start) < (best[2] - best[1])):
1295
+ best = (name, start, end)
1296
+ plan["enclosing"] = best
1297
+ plan["status"] = "body_here"
1298
+ return plan
1299
+
1300
+
1301
+ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code: str) -> str:
1302
+ """Honest, actionable replacement for a skeleton that folded the requested symbol away."""
1303
+ base = os.path.basename(path)
1304
+ hits = ", ".join(f"L{n}" for n in plan["hit_lines"]) or "none"
1305
+ probe = plan.get("probe")
1306
+ probe_note = f" (matched '{probe}')" if probe and probe != symbol else ""
1307
+ elsewhere = plan["elsewhere"]
1308
+ pointer = ""
1309
+ if elsewhere:
1310
+ r, es, ee, _n = elsewhere
1311
+ pointer = (
1312
+ f"\n// ['{symbol}' is declared in {r} L{es}-L{ee} — call smart_read_file(path=\"{r}\", symbol=\"{symbol}\")"
1313
+ f" if you need that declaration instead]"
1314
+ )
1315
+
1316
+ if plan["status"] == "absent":
1317
+ decl_txt = ", ".join(f"{n} L{s}-L{e}" for n, s, e in plan["decls"][:12]) or "none indexed"
1318
+ return f"// [TokenSafe: '{symbol}' does not occur in {base}. Declarations in this file: {decl_txt}]{pointer}"
1319
+
1320
+ lines = code.splitlines()
1321
+ enclosing = plan["enclosing"]
1322
+ windows: List[Tuple[int, int]] = []
1323
+
1324
+ if enclosing and (enclosing[2] - enclosing[1] + 1) <= _SYMBOL_MISS_FULL_DECL_LINES:
1325
+ name, start, end = enclosing
1326
+ windows = [(start, end)]
1327
+ head = (
1328
+ f"// [TokenSafe Text-Anchor Slice: '{symbol}' is not a declaration in {base}; "
1329
+ f"it occurs at {hits}{probe_note} inside {name} (L{start}-L{end}) — that declaration is shown in full]"
1330
+ )
1331
+ else:
1332
+ pad = _SYMBOL_MISS_WINDOW_PAD
1333
+ for hit in plan["hit_lines"][:_SYMBOL_MISS_WINDOW_HITS]:
1334
+ windows.append((max(1, hit - pad), min(len(lines), hit + pad)))
1335
+ windows.sort()
1336
+ merged: List[Tuple[int, int]] = []
1337
+ for s, e in windows:
1338
+ if merged and s <= merged[-1][1] + 1:
1339
+ merged[-1] = (merged[-1][0], max(merged[-1][1], e))
1340
+ else:
1341
+ merged.append((s, e))
1342
+ windows = merged
1343
+ if enclosing:
1344
+ name, ds, de = enclosing
1345
+ head = (
1346
+ f"// [TokenSafe Text-Anchor Slice: '{symbol}' is not a declaration in {base}; "
1347
+ f"it occurs at {hits}{probe_note} inside {name} (L{ds}-L{de}) — showing ±{pad} lines around each hit]"
1348
+ f"\n// {lines[ds - 1].strip()}"
1349
+ )
1350
+ else:
1351
+ head = (
1352
+ f"// [TokenSafe Text-Anchor Slice: '{symbol}' is not a declaration in {base}; "
1353
+ f"it occurs at {hits}{probe_note} outside any indexed declaration — showing ±{pad} lines around each hit]"
1354
+ )
1355
+
1356
+ if not windows:
1357
+ return f"{head}{pointer}"
1358
+
1359
+ budget = _SYMBOL_MISS_MAX_LINES
1360
+ chunks: List[str] = []
1361
+ for i, (s, e) in enumerate(windows):
1362
+ if budget <= 0:
1363
+ chunks.append(f"// [... {len(windows) - i} more window(s) suppressed; request start_line/end_line]")
1364
+ break
1365
+ e = min(e, s + budget - 1)
1366
+ budget -= (e - s + 1)
1367
+ # Always print the range: it is the `start_line`/`end_line` the caller needs
1368
+ # when the snippet they edit occurs more than once in the file.
1369
+ chunks.append(f"// --- L{s}-L{e}")
1370
+ chunks.append("\n".join(lines[s - 1:e]))
1371
+ if e < windows[i][1]:
1372
+ chunks.append("// [window truncated]")
1373
+
1374
+ return f"{head}{pointer}\n" + "\n".join(chunks)
1375
+
1376
+
1238
1377
  def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
1239
1378
  raw_inc = args.get("include_deps")
1240
1379
  inc_deps = True if raw_inc is None else bool(raw_inc)
@@ -1677,16 +1816,52 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1677
1816
  prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
1678
1817
  slice_header = f"// [TOCP Raw Slice: lines {range_label} of {os.path.basename(path)}]\n"
1679
1818
  delivered = (prefetch_block or "") + slice_header + (content or "")
1819
+ # A requested line range is a read, not an optimization: the caller already
1820
+ # knew what it wanted and any agent does the same with offset/limit. Charging
1821
+ # the whole file as the counterfactual credited 257k tokens to a 30-line read
1822
+ # of a 29k-line file (measured in the lifetime aggregate) and hid regressions.
1823
+ delivered_tokens = count_tokens(delivered)
1680
1824
  tracker.record_event(
1681
1825
  session_id=_mcp_session_id(),
1682
1826
  event_type="RAW_SLICE",
1683
- original_tokens=max(200, st.st_size // 4),
1684
- optimized_tokens=count_tokens(delivered),
1685
- details={"file": os.path.basename(path), "lines": range_label, "symbol": sym_clean[:120]}
1827
+ original_tokens=delivered_tokens,
1828
+ optimized_tokens=delivered_tokens,
1829
+ details={"file": os.path.basename(path), "lines": range_label,
1830
+ "symbol": sym_clean[:120], "counterfactual": "same_range"}
1686
1831
  )
1687
1832
  return {"content": [{"type": "text", "text": delivered}]}
1688
1833
 
1689
1834
  if symbol:
1835
+ # Resolve the symbol against this file's declarations *before* skeletonizing.
1836
+ # A miss used to fall through to a whole-file skeleton whose header claimed
1837
+ # "Full body" — the caller then re-read the file anyway (measured in the
1838
+ # OUMV agent matrix: smart_read_file saved zero read tokens).
1839
+ scope_plan = None
1840
+ raw_for_scope = ""
1841
+ try:
1842
+ with open(path, "r", encoding="utf-8", errors="replace") as _sf:
1843
+ raw_for_scope = _sf.read()
1844
+ graph_for_scope, rel_for_scope = GraphEngine.for_file(path)
1845
+ scope_plan = _symbol_scope(graph_for_scope, rel_for_scope, symbol, raw_for_scope)
1846
+ except Exception:
1847
+ scope_plan = None
1848
+ if scope_plan and scope_plan["status"] in ("body_here", "absent"):
1849
+ anchored = _render_symbol_scope_miss(scope_plan, path, symbol, raw_for_scope)
1850
+ tracker.record_event(
1851
+ session_id=_mcp_session_id(),
1852
+ event_type="SYMBOL_TEXT_ANCHOR",
1853
+ original_tokens=count_tokens(raw_for_scope),
1854
+ optimized_tokens=count_tokens(anchored),
1855
+ details={
1856
+ "file": os.path.basename(path),
1857
+ "symbol": symbol,
1858
+ "resolution": scope_plan["status"],
1859
+ "hits": len(scope_plan["hit_lines"]),
1860
+ "enclosing": (scope_plan["enclosing"] or ("", 0, 0))[0],
1861
+ }
1862
+ )
1863
+ return {"content": [{"type": "text", "text": anchored}]}
1864
+
1690
1865
  # Team pre-warm hit: a teammate already skeletonized this symbol
1691
1866
  team_skel = _team_skeleton_lookup(path, symbol, dep_mode=eff_dep_mode)
1692
1867
  if team_skel:
@@ -2310,22 +2485,39 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2310
2485
  return {"content": [{"type": "text", "text": surface_md}]}
2311
2486
 
2312
2487
  elif name == "list_dir":
2313
- path = args.get("path") or args.get("project_path") or args.get("directory") or args.get("root_dir") or ""
2314
- if not path:
2488
+ path = args.get("path") or args.get("directory") or ""
2489
+ explicit_root = args.get("project_path") or args.get("root_dir")
2490
+ if not path and not explicit_root:
2315
2491
  return _fallback_error("list_dir", "missing required 'path' argument")
2316
2492
 
2317
- # Resolve path relative to active workspace, cwd, or absolute
2493
+ # An explicit project_path is the base for a relative path. Before this,
2494
+ # `path` shadowed it and joined to the session workspace, so repo_map
2495
+ # view='tree' on a second repo reported "directory not found".
2318
2496
  active_ws = _workspace_root()
2319
- if not os.path.isabs(path):
2320
- if active_ws and os.path.isdir(os.path.join(active_ws, path)):
2321
- abs_path = os.path.abspath(os.path.join(active_ws, path))
2322
- else:
2323
- abs_path = os.path.abspath(path)
2324
- else:
2497
+
2498
+ def _abs_candidate(value: str) -> str:
2499
+ if os.path.isabs(value):
2500
+ return os.path.abspath(value)
2501
+ if active_ws and os.path.isdir(os.path.join(active_ws, value)):
2502
+ return os.path.abspath(os.path.join(active_ws, value))
2503
+ return os.path.abspath(value)
2504
+
2505
+ base_dir = _abs_candidate(str(explicit_root)) if explicit_root else None
2506
+ if base_dir and not os.path.isdir(base_dir):
2507
+ return _fallback_error("list_dir", f"project_path not found or not a directory: '{explicit_root}'")
2508
+
2509
+ if not path:
2510
+ abs_path = base_dir
2511
+ elif os.path.isabs(path):
2325
2512
  abs_path = os.path.abspath(path)
2513
+ elif base_dir:
2514
+ abs_path = os.path.abspath(os.path.join(base_dir, path))
2515
+ else:
2516
+ abs_path = _abs_candidate(path)
2326
2517
 
2327
2518
  if not os.path.isdir(abs_path):
2328
- return _fallback_error("list_dir", f"directory not found: {abs_path}")
2519
+ where = f" (resolved from '{path}' under '{base_dir}')" if base_dir and not os.path.isabs(path) else ""
2520
+ return _fallback_error("list_dir", f"directory not found: {abs_path}{where}")
2329
2521
  if is_plugin_or_system_dir(abs_path):
2330
2522
  return _fallback_error("list_dir", f"refusing to inspect system root or plugin dir '{path}'")
2331
2523
  system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
@@ -2357,13 +2549,35 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2357
2549
  raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
2358
2550
  active_ws = _workspace_root()
2359
2551
 
2552
+ # `cwd` is the single-mode base as well, not just batch mode: agents editing a
2553
+ # repo outside the session workspace pass cwd + a repo-relative path, and
2554
+ # anchoring that path to the active workspace used to surface as a bare
2555
+ # "Invalid project path" for a directory that exists under cwd.
2556
+ raw_cwd = args.get("cwd")
2557
+ if raw_cwd:
2558
+ if not os.path.isabs(str(raw_cwd)) and active_ws and os.path.isdir(os.path.join(active_ws, str(raw_cwd))):
2559
+ base_dir = os.path.abspath(os.path.join(active_ws, str(raw_cwd)))
2560
+ else:
2561
+ base_dir = os.path.abspath(str(raw_cwd))
2562
+ if not os.path.isdir(base_dir):
2563
+ return _fallback_error("scoped_search", f"invalid 'cwd': '{raw_cwd}' is not a directory")
2564
+ else:
2565
+ base_dir = active_ws
2566
+
2360
2567
  # 1. Resolve base directory safely without scanning plugin or system roots
2361
2568
  if raw_path:
2362
2569
  if not os.path.isabs(raw_path):
2363
- if active_ws and os.path.isdir(os.path.join(active_ws, raw_path)):
2364
- target_path = os.path.abspath(os.path.join(active_ws, raw_path))
2570
+ if base_dir and os.path.isdir(os.path.join(base_dir, raw_path)):
2571
+ target_path = os.path.abspath(os.path.join(base_dir, raw_path))
2365
2572
  else:
2366
2573
  target_path = os.path.abspath(raw_path)
2574
+ if not os.path.exists(target_path):
2575
+ scope_root = base_dir or active_ws or os.getcwd()
2576
+ return _fallback_error(
2577
+ "scoped_search",
2578
+ f"path '{raw_path}' does not exist (resolved to '{target_path}' from '{scope_root}'). "
2579
+ f"Pass the repo root as 'cwd' plus a repo-relative path, or an absolute path.",
2580
+ )
2367
2581
  else:
2368
2582
  target_path = os.path.abspath(raw_path)
2369
2583
 
@@ -2415,7 +2629,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2415
2629
  scope=scope,
2416
2630
  max_results=max_res,
2417
2631
  case_sensitive=c_sens,
2418
- use_regex=u_regex
2632
+ use_regex=u_regex,
2633
+ per_file=_safe_int(args.get("per_file"), 0, lo=0, hi=100)
2419
2634
  )
2420
2635
  md_text = res["markdown"]
2421
2636
  if not res.get("success", True):
@@ -2861,8 +3076,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2861
3076
  return _fallback_error(
2862
3077
  "batch_search",
2863
3078
  f"subquery path '{sub_p}' resolves to '{sub_abs}', outside project root "
2864
- f"'{real_cwd}'. Pass the repo root as project_path and a repo-relative "
2865
- f"path, or omit path entirely.",
3079
+ f"'{real_cwd}'. One call searches one root: pass that repo as cwd/project_path "
3080
+ f"with repo-relative paths, and split queries for other repos into separate calls.",
2866
3081
  )
2867
3082
  if is_quota_exceeded:
2868
3083
  q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
@@ -3113,6 +3328,25 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
3113
3328
  return new_res
3114
3329
 
3115
3330
 
3331
+ def _tool_timeout(tool_name: str, tool_args: dict) -> float:
3332
+ """The tool's own declared budget wins over the transport's default.
3333
+
3334
+ `apply_edits` can run an inline verify command, and the edit is already on disk by
3335
+ then: cutting the call at the default 8 s both loses the verdict and tells the
3336
+ caller "could not complete" about work that did complete. Ask for the declared
3337
+ verify budget plus a margin, capped so a hung suite cannot wedge the server.
3338
+ """
3339
+ if tool_name == "apply_edits":
3340
+ has_verify = bool(tool_args.get("verify"))
3341
+ try:
3342
+ declared = int(tool_args.get("verify_timeout_sec") or (30 if has_verify else 0))
3343
+ except (TypeError, ValueError):
3344
+ declared = 30 if has_verify else 0
3345
+ if declared > 0:
3346
+ return min(max(MCP_TOOL_TIMEOUT, declared + 5.0), 180.0)
3347
+ return MCP_TOOL_TIMEOUT
3348
+
3349
+
3116
3350
  def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
3117
3351
  """Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
3118
3352
  box = {"result": None, "error": None}
@@ -3217,10 +3451,17 @@ def run_mcp_server():
3217
3451
  "serverInfo": SERVER_INFO
3218
3452
  }
3219
3453
  # Routing brief (MCP `instructions`): which stacks this workspace
3220
- # works through OUMV and which through the TokenSafe tools.
3454
+ # works through OUMV and which through the TokenSafe tools. The
3455
+ # server usually runs from the plugin dir, so prefer the session
3456
+ # workspace marker; extra roots (TOKENSAFE_WORKSPACES) are
3457
+ # classified one by one so a single-root verdict is never global.
3221
3458
  try:
3222
- from src.session_brief import build_workspace_brief
3223
- brief = build_workspace_brief(os.getcwd(), include_live=False)
3459
+ from src.session_brief import build_workspace_brief, workspace_roots_from_env
3460
+ brief = build_workspace_brief(
3461
+ _workspace_root() or os.getcwd(),
3462
+ include_live=False,
3463
+ extra_workspaces=workspace_roots_from_env(),
3464
+ )
3224
3465
  if brief:
3225
3466
  response["result"]["instructions"] = brief
3226
3467
  except Exception:
@@ -3228,7 +3469,13 @@ def run_mcp_server():
3228
3469
  elif method == "tools/list":
3229
3470
  _TOOLS_LISTED = True
3230
3471
  profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
3231
- response["result"] = {"tools": FULL_TOOLS if profile == "full" else TOOLS}
3472
+ if profile == "full":
3473
+ advertised = FULL_TOOLS
3474
+ elif profile == "lean":
3475
+ advertised = [t for t in TOOLS if t["name"] in _LEAN_TOOL_NAMES]
3476
+ else:
3477
+ advertised = TOOLS
3478
+ response["result"] = {"tools": advertised}
3232
3479
  elif method == "ping":
3233
3480
  response["result"] = {}
3234
3481
  elif method == "tools/call":
@@ -3241,7 +3488,7 @@ def run_mcp_server():
3241
3488
  # arguments as a malformed JSON string — repair before failing.
3242
3489
  from src.json_repair import parse_tool_arguments
3243
3490
  tool_args = parse_tool_arguments(raw_tool_args) or {}
3244
- raw_res = _execute_with_timeout(tool_name, tool_args)
3491
+ raw_res = _execute_with_timeout(tool_name, tool_args, timeout=_tool_timeout(tool_name, tool_args))
3245
3492
  redacted = _redact_result_secrets(raw_res)
3246
3493
  response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
3247
3494
  except Exception as e: