tokensafe 4.6.4 → 4.7.1

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 (44) hide show
  1. package/.codex-plugin/plugin.json +2 -2
  2. package/LICENSE +202 -21
  3. package/README.md +30 -4
  4. package/hooks/claude_code_hook.py +17 -15
  5. package/hooks/kimi_hook.py +14 -12
  6. package/hooks/pre_invocation.py +7 -12
  7. package/hooks/session_start.py +8 -2
  8. package/kimi.plugin.json +2 -2
  9. package/package.json +2 -2
  10. package/plugin.json +2 -1
  11. package/rules/AGENTS.md +1 -1
  12. package/server.json +3 -3
  13. package/src/acp/__init__.py +15 -0
  14. package/src/acp/server.py +328 -0
  15. package/src/adapter_core.py +2 -1
  16. package/src/agent/__init__.py +11 -0
  17. package/src/agent/context.py +99 -0
  18. package/src/agent/loop.py +385 -0
  19. package/src/agent/pricing.py +77 -0
  20. package/src/agent/providers.py +486 -0
  21. package/src/agent/tools.py +98 -0
  22. package/src/agent_firewall.py +16 -1
  23. package/src/auto_inject.py +93 -7
  24. package/src/batch_editor.py +106 -15
  25. package/src/bench/__init__.py +1 -0
  26. package/src/bench/driver.py +234 -0
  27. package/src/bench/go_target.py +646 -0
  28. package/src/bench/mechanics.py +214 -0
  29. package/src/bench/react_target.py +541 -0
  30. package/src/bench/runner.py +331 -0
  31. package/src/bench/tokensafe_mcp.py +144 -0
  32. package/src/cli.py +156 -0
  33. package/src/history_compactor.py +200 -2
  34. package/src/installer.py +3 -3
  35. package/src/mcp_server.py +510 -237
  36. package/src/paths.py +41 -2
  37. package/src/retrofit.py +27 -5
  38. package/src/scaffold.py +8 -6
  39. package/src/scoped_search.py +67 -5
  40. package/src/session_brief.py +180 -15
  41. package/src/session_context.py +124 -0
  42. package/src/skeletonizer.py +9 -3
  43. package/src/telemetry_sync.py +1 -1
  44. package/src/version_checker.py +1 -1
package/src/mcp_server.py CHANGED
@@ -39,10 +39,11 @@ from src.guard import TokenSafeGuard
39
39
  from src.scoped_search import ScopedSearch
40
40
  from src.license_manager import LicenseManager
41
41
  from src.paths import get_active_workspace, is_plugin_or_system_dir
42
+ from src.session_context import current_root, current_session_id
42
43
 
43
44
  SERVER_INFO = {
44
45
  "name": "tokensafe-mcp",
45
- "version": "4.6.4"
46
+ "version": "4.7.1"
46
47
  }
47
48
 
48
49
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -65,9 +66,25 @@ def _set_mcp_client(name: str):
65
66
 
66
67
 
67
68
  def _mcp_session_id() -> str:
69
+ """Metrics key for the current call.
70
+
71
+ An explicit session scope (ACP agent server, in-process loop, tests) wins:
72
+ one process can own several sessions, and mixing their metrics or pointer
73
+ caches together is what the legacy global client name did."""
74
+ scoped = current_session_id()
75
+ if scoped:
76
+ return scoped
68
77
  return f"mcp:{_MCP_CLIENT_NAME}" if _MCP_CLIENT_NAME else "mcp_session"
69
78
 
70
79
 
80
+ def _workspace_root() -> Optional[str]:
81
+ """Project root for relative-path resolution.
82
+
83
+ Session scope first, then the machine-wide marker written by lifecycle
84
+ hooks. Never returns scratch space (``get_active_workspace`` filters it)."""
85
+ return current_root() or get_active_workspace()
86
+
87
+
71
88
  def _client_supports_pointers() -> bool:
72
89
  """Out-of-the-box capability detection (zero env vars): returns True once the
73
90
  MCP client has fetched tools/list (seeing force_full) or identified as an
@@ -278,6 +295,9 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
278
295
  'inputSchema': { 'properties': { 'case_sensitive': { 'description': 'Case-sensitive search (default '
279
296
  'false)',
280
297
  'type': 'boolean'},
298
+ 'cwd': { 'description': 'Base directory for a relative path '
299
+ '(defaults to the active project)',
300
+ 'type': 'string'},
281
301
  'max_results': { 'description': 'Max matching lines (default 25, max '
282
302
  '100)',
283
303
  'type': 'integer'},
@@ -644,219 +664,165 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
644
664
 
645
665
  # Compact MCP surface (default): 7 consolidated tools (~2.2k tok vs ~6.0k tok for 28 schemas).
646
666
  # All 28 legacy tool names remain callable in _dispatch_tool_call for backward compatibility.
647
- # Set TOKENSAFE_MCP_PROFILE=full to expose FULL_TOOLS in tools/list.
648
- TOOLS = [
649
- {
650
- 'name': 'smart_read_file',
651
- 'description': (
652
- 'AST-skeleton reader (-90-98% tokens). Pass path+symbol for one file (auto-slices '
653
- 'OpenAPI/Prisma/GraphQL/SQL/lockfiles), targets=[{path,symbol}] to bundle 2-8 symbols, '
654
- 'or package_name+symbol for 3rd-party .d.ts types.'
655
- ),
656
- 'annotations': {'readOnlyHint': True},
657
- 'inputSchema': {
658
- 'type': 'object',
659
- 'properties': {
660
- 'path': {'type': 'string', 'description': 'File path (relative or absolute)'},
661
- 'symbol': {'type': 'string', 'description': 'Function/class/model/type to extract'},
662
- 'start_line': {'type': 'integer', 'description': 'Optional start line'},
663
- 'end_line': {'type': 'integer', 'description': 'Optional end line'},
664
- 'dep_mode': {'type': 'string', 'enum': ['signature', 'full'], 'description': '1-hop dep mode (default signature)'},
665
- 'include_deps': {'type': 'boolean', 'description': 'Include 1-hop deps (default true)'},
666
- 'force_full': {'type': 'boolean', 'description': 'Bypass pointer dedup'},
667
- 'project_root': {'type': 'string', 'description': 'Workspace root directory (for external types / lockfiles)'},
668
- 'targets': {
669
- 'type': 'array', 'maxItems': 8,
670
- 'description': 'Bundle mode: 2-8 {path, symbol} targets in one call',
671
- 'items': {'type': 'object', 'properties': {'path': {'type': 'string'}, 'symbol': {'type': 'string'}}, 'required': ['path']},
672
- },
673
- 'package_name': {'type': 'string', 'description': 'External .d.ts npm package name'},
674
- },
675
- },
676
- },
677
- {
678
- 'name': 'scoped_search',
679
- 'description': (
680
- 'Safe token-bounded search replacing grep/find (-90% tokens). Pass query+scope for single '
681
- 'search (mode/type: auto|text|regex|glob|fuzzy|git), or queries=[{pattern,type,path,glob}] '
682
- 'for up to 20 concurrent queries.'
683
- ),
684
- 'annotations': {'readOnlyHint': True},
685
- 'inputSchema': {
686
- 'type': 'object',
687
- 'properties': {
688
- 'query': {'type': 'string', 'description': 'Text, symbol, regex, glob, or read-only git query'},
689
- 'mode': {'type': 'string', 'enum': ['auto', 'text', 'regex', 'glob', 'fuzzy', 'git'], 'description': 'Single-query mode'},
690
- 'scope': {'type': 'string', 'description': "'code', 'config', 'all', ext ('py'), or subfolder"},
691
- 'path': {'type': 'string', 'description': 'Directory path (default project root)'},
692
- 'project_path': {'type': 'string', 'description': 'Alias for path'},
693
- 'use_regex': {'type': 'boolean', 'description': 'Force regex true/false'},
694
- 'case_sensitive': {'type': 'boolean'},
695
- 'max_results': {'type': 'integer', 'description': 'Max lines (default 25, max 100)'},
696
- 'queries': {
697
- 'type': 'array', 'maxItems': 20,
698
- 'description': 'Batch mode: up to 20 {pattern, type, path, glob, output_mode} objects',
699
- 'items': {
700
- 'type': 'object',
701
- 'properties': {
702
- 'pattern': {'type': 'string'},
703
- 'type': {'type': 'string', 'enum': ['text', 'regex', 'glob', 'fuzzy', 'git']},
704
- 'path': {'type': 'string'},
705
- 'glob': {'type': 'string'},
706
- 'file_type': {'type': 'string'},
707
- 'output_mode': {'type': 'string', 'enum': ['content', 'files_with_matches', 'count']},
708
- 'case_sensitive': {'type': 'boolean'},
709
- 'max_results': {'type': 'integer'},
710
- },
711
- 'required': ['pattern'],
712
- },
713
- },
714
- 'cwd': {'type': 'string', 'description': 'Optional working directory for batch mode'},
715
- },
716
- },
717
- },
718
- {
719
- 'name': 'apply_edits',
720
- 'description': 'Atomic/best-effort multi-hunk editor (up to 50 files) with optional inline verify command.',
721
- 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
722
- 'inputSchema': {
723
- 'type': 'object',
724
- 'properties': {
725
- 'edits': {
726
- 'type': 'array', 'maxItems': 50,
727
- 'items': {
728
- 'type': 'object',
729
- 'properties': {
730
- 'path': {'type': 'string'},
731
- 'create': {'type': 'string'},
732
- 'overwrite': {'type': 'boolean'},
733
- 'hunks': {
734
- 'type': 'array',
735
- 'items': {
736
- 'type': 'object',
737
- 'properties': {
738
- 'target': {'type': 'string'},
739
- 'replacement': {'type': 'string'},
740
- 'start_line': {'type': 'integer'},
741
- 'end_line': {'type': 'integer'},
742
- 'replace_all': {'type': 'boolean'},
743
- },
744
- 'required': ['target', 'replacement'],
745
- },
746
- },
747
- },
748
- 'required': ['path'],
749
- },
750
- },
751
- 'best_effort': {'type': 'boolean'},
752
- 'dry_run': {'type': 'boolean'},
753
- 'verify': {'type': 'string', 'description': 'Shell command to run after edits (e.g. pytest, npm test)'},
754
- 'verify_timeout_sec': {'type': 'integer'},
755
- 'cwd': {'type': 'string'},
756
- },
757
- 'required': ['edits'],
758
- },
759
- },
760
- {
761
- 'name': 'repo_map',
762
- 'description': (
763
- 'Project structure & architecture without crawling: view="graph" (God Nodes & deps), '
764
- '"api" (exported classes/types/interfaces), or "tree" (clean directory tree).'
765
- ),
766
- 'annotations': {'readOnlyHint': True},
767
- 'inputSchema': {
768
- 'type': 'object',
769
- 'properties': {
770
- 'view': {'type': 'string', 'enum': ['graph', 'api', 'tree'], 'default': 'graph'},
771
- 'project_path': {'type': 'string', 'description': 'Project root (pass absolute path in multi-repo setups)'},
772
- 'path': {'type': 'string', 'description': "Directory path for view='tree' (default '.')"},
773
- 'depth': {'type': 'integer', 'description': 'Tree depth (default 2, max 4)'},
774
- 'max_entries': {'type': 'integer'},
775
- },
776
- },
777
- },
778
- {
779
- 'name': 'session_context',
780
- 'description': (
781
- 'Session & context hygiene: action="budget" (Context Quality Score S-F), "compact" (fold transcript '
782
- 'to State Ledger), "prune" (drop superseded reads), "mistakes" (anti-stuck memory), or "metrics".'
783
- ),
784
- 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
785
- 'inputSchema': {
786
- 'type': 'object',
787
- 'properties': {
788
- 'action': {'type': 'string', 'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics'], 'default': 'budget'},
789
- 'model': {'type': 'string'},
790
- 'session_id': {'type': 'string'},
791
- 'transcript_path': {'type': 'string'},
792
- 'window_tokens': {'type': 'integer'},
793
- 'invocation_num': {'type': 'integer'},
794
- 'project_root': {'type': 'string'},
795
- 'clear': {'type': 'boolean'},
796
- },
797
- 'required': ['action'],
798
- },
799
- },
800
- {
801
- 'name': 'oumv',
802
- 'description': (
803
- 'Live Frontend/Backend OUMV runtime protocol: action="status"|"observe" (L0-L4)|"understand" '
804
- '(causality/impact)|"verify" (in-memory sandbox)|"mutate" (OCC edit)|"graph" (cross-stack).'
805
- ),
806
- 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
807
- 'inputSchema': {
808
- 'type': 'object',
809
- 'properties': {
810
- 'action': {'type': 'string', 'enum': ['status', 'observe', 'understand', 'mutate', 'verify', 'graph'], 'default': 'status'},
811
- 'level': {'type': 'string', 'enum': ['L0', 'L1', 'L2', 'L3', 'L4']},
812
- 'query': {'type': 'string'},
813
- 'runtime': {'type': 'string', 'enum': ['frontend', 'backend', 'auto']},
814
- 'target': {'type': 'string'},
815
- 'path': {'type': 'string'},
816
- 'symbol': {'type': 'string'},
817
- 'replacement': {'type': 'string'},
818
- 'expectedVersion': {'type': 'string'},
819
- 'verify_action': {'type': 'string', 'description': "Action name for action='verify' (e.g. click, submit)"},
820
- 'payload': {'type': 'object'},
821
- 'workspace_dir': {'type': 'string'},
822
- },
823
- 'required': ['action'],
824
- },
825
- },
826
- {
827
- 'name': 'run_helper',
828
- 'description': (
829
- 'Unified utility runner: action="sanitize" (rewrite bash/tests), "guard" (security/hygiene check), '
830
- '"diff" (slice diff), "deps" (query lockfile), "web" (fetch clean MD), "expand" (unfold #hash), '
831
- '"image" (downscale), or "compress" (TOCP prompt).'
832
- ),
833
- 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
834
- 'inputSchema': {
835
- 'type': 'object',
836
- 'properties': {
837
- 'action': {
838
- 'type': 'string',
839
- 'enum': ['sanitize', 'guard', 'diff', 'deps', 'web', 'expand', 'image', 'compress'],
840
- },
841
- 'command': {'type': 'string'},
842
- 'code': {'type': 'string'},
843
- 'file_path': {'type': 'string'},
844
- 'diff': {'type': 'string'},
845
- 'max_context': {'type': 'integer'},
846
- 'package_name': {'type': 'string'},
847
- 'lockfile_path': {'type': 'string'},
848
- 'url': {'type': 'string'},
849
- 'force_refresh': {'type': 'boolean'},
850
- 'hash': {'type': 'string'},
851
- 'image_path': {'type': 'string'},
852
- 'max_edge': {'type': 'integer'},
853
- 'prompt': {'type': 'string'},
854
- 'cwd': {'type': 'string'},
855
- },
856
- 'required': ['action'],
857
- },
858
- },
859
- ]
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'}}}}]
860
826
 
861
827
  def format_file_size(size_bytes: int) -> str:
862
828
  if size_bytes < 1024:
@@ -981,7 +947,7 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
981
947
  Safely resolves the target project root without falling back to system root dirs or plugin dirs.
982
948
  """
983
949
  target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory")
984
- active_ws = get_active_workspace()
950
+ active_ws = _workspace_root()
985
951
 
986
952
  if target:
987
953
  if not os.path.isabs(target):
@@ -1218,6 +1184,196 @@ def _read_line_slice(path: str, start_line: Optional[int], end_line: Optional[in
1218
1184
  return "".join(selected), None
1219
1185
 
1220
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
+
1221
1377
  def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
1222
1378
  raw_inc = args.get("include_deps")
1223
1379
  inc_deps = True if raw_inc is None else bool(raw_inc)
@@ -1265,7 +1421,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
1265
1421
  or ("monthly limit (" in text_out and "optimizations paused" in text_out)
1266
1422
  )
1267
1423
  if text_out and path and not is_ranged and not is_quota_truncated:
1268
- active_ws = get_active_workspace()
1424
+ active_ws = _workspace_root()
1269
1425
  if not os.path.isabs(path) and active_ws and os.path.exists(os.path.join(active_ws, path)):
1270
1426
  abs_path = os.path.abspath(os.path.join(active_ws, path))
1271
1427
  else:
@@ -1356,6 +1512,21 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1356
1512
  elif args.get("package_name") and not (args.get("path") or args.get("file_path") or args.get("file")):
1357
1513
  name = "slice_external_type"
1358
1514
  elif name == "scoped_search":
1515
+ # Schema contract: `path` is "Directory path (default project root)",
1516
+ # while `queries[].path` is a sub-scope. When the caller passes an
1517
+ # absolute directory and no explicit root, promote it to the root.
1518
+ # Without this, batch_search validated the path against the machine-wide
1519
+ # active-workspace marker (which may belong to another repo or a stale
1520
+ # temp dir) and rejected a path that is demonstrably inside the project.
1521
+ _raw_path = args.get("path")
1522
+ if (
1523
+ _raw_path
1524
+ and not (args.get("cwd") or args.get("project_path"))
1525
+ and os.path.isabs(str(_raw_path))
1526
+ and os.path.isdir(str(_raw_path))
1527
+ ):
1528
+ args = dict(args, project_path=str(_raw_path))
1529
+ args.pop("path", None)
1359
1530
  mode = str(args.get("mode") or "").strip().lower()
1360
1531
  if args.get("queries"):
1361
1532
  name = "batch_search"
@@ -1444,7 +1615,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1444
1615
  if start_line is not None:
1445
1616
  start_line = max(1, start_line)
1446
1617
 
1447
- active_ws = get_active_workspace()
1618
+ active_ws = _workspace_root()
1448
1619
  if path and not os.path.isabs(path):
1449
1620
  if active_ws and os.path.exists(os.path.join(active_ws, path)):
1450
1621
  path = os.path.abspath(os.path.join(active_ws, path))
@@ -1645,16 +1816,52 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1645
1816
  prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
1646
1817
  slice_header = f"// [TOCP Raw Slice: lines {range_label} of {os.path.basename(path)}]\n"
1647
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)
1648
1824
  tracker.record_event(
1649
1825
  session_id=_mcp_session_id(),
1650
1826
  event_type="RAW_SLICE",
1651
- original_tokens=max(200, st.st_size // 4),
1652
- optimized_tokens=count_tokens(delivered),
1653
- 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"}
1654
1831
  )
1655
1832
  return {"content": [{"type": "text", "text": delivered}]}
1656
1833
 
1657
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
+
1658
1865
  # Team pre-warm hit: a teammate already skeletonized this symbol
1659
1866
  team_skel = _team_skeleton_lookup(path, symbol, dep_mode=eff_dep_mode)
1660
1867
  if team_skel:
@@ -1770,7 +1977,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1770
1977
  inc_deps, _eff_dep_mode = _resolve_dep_mode(args)
1771
1978
  max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
1772
1979
 
1773
- active_ws = get_active_workspace()
1980
+ active_ws = _workspace_root()
1774
1981
  by_file: Dict[str, List[str]] = {}
1775
1982
  for t in targets:
1776
1983
  if not isinstance(t, dict) or not str(t.get("path") or "").strip():
@@ -2283,7 +2490,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2283
2490
  return _fallback_error("list_dir", "missing required 'path' argument")
2284
2491
 
2285
2492
  # Resolve path relative to active workspace, cwd, or absolute
2286
- active_ws = get_active_workspace()
2493
+ active_ws = _workspace_root()
2287
2494
  if not os.path.isabs(path):
2288
2495
  if active_ws and os.path.isdir(os.path.join(active_ws, path)):
2289
2496
  abs_path = os.path.abspath(os.path.join(active_ws, path))
@@ -2323,15 +2530,37 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2323
2530
 
2324
2531
  raw_scope = str(args.get("scope") or "all").strip()
2325
2532
  raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
2326
- active_ws = get_active_workspace()
2533
+ active_ws = _workspace_root()
2534
+
2535
+ # `cwd` is the single-mode base as well, not just batch mode: agents editing a
2536
+ # repo outside the session workspace pass cwd + a repo-relative path, and
2537
+ # anchoring that path to the active workspace used to surface as a bare
2538
+ # "Invalid project path" for a directory that exists under cwd.
2539
+ raw_cwd = args.get("cwd")
2540
+ if raw_cwd:
2541
+ if not os.path.isabs(str(raw_cwd)) and active_ws and os.path.isdir(os.path.join(active_ws, str(raw_cwd))):
2542
+ base_dir = os.path.abspath(os.path.join(active_ws, str(raw_cwd)))
2543
+ else:
2544
+ base_dir = os.path.abspath(str(raw_cwd))
2545
+ if not os.path.isdir(base_dir):
2546
+ return _fallback_error("scoped_search", f"invalid 'cwd': '{raw_cwd}' is not a directory")
2547
+ else:
2548
+ base_dir = active_ws
2327
2549
 
2328
2550
  # 1. Resolve base directory safely without scanning plugin or system roots
2329
2551
  if raw_path:
2330
2552
  if not os.path.isabs(raw_path):
2331
- if active_ws and os.path.isdir(os.path.join(active_ws, raw_path)):
2332
- target_path = os.path.abspath(os.path.join(active_ws, raw_path))
2553
+ if base_dir and os.path.isdir(os.path.join(base_dir, raw_path)):
2554
+ target_path = os.path.abspath(os.path.join(base_dir, raw_path))
2333
2555
  else:
2334
2556
  target_path = os.path.abspath(raw_path)
2557
+ if not os.path.exists(target_path):
2558
+ scope_root = base_dir or active_ws or os.getcwd()
2559
+ return _fallback_error(
2560
+ "scoped_search",
2561
+ f"path '{raw_path}' does not exist (resolved to '{target_path}' from '{scope_root}'). "
2562
+ f"Pass the repo root as 'cwd' plus a repo-relative path, or an absolute path.",
2563
+ )
2335
2564
  else:
2336
2565
  target_path = os.path.abspath(raw_path)
2337
2566
 
@@ -2383,7 +2612,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2383
2612
  scope=scope,
2384
2613
  max_results=max_res,
2385
2614
  case_sensitive=c_sens,
2386
- use_regex=u_regex
2615
+ use_regex=u_regex,
2616
+ per_file=_safe_int(args.get("per_file"), 0, lo=0, hi=100)
2387
2617
  )
2388
2618
  md_text = res["markdown"]
2389
2619
  if not res.get("success", True):
@@ -2459,7 +2689,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2459
2689
  pkg = str(args.get("package_name") or args.get("package") or "").strip()
2460
2690
  lock_p = str(args.get("lockfile_path") or args.get("path") or "").strip() or None
2461
2691
  if lock_p and not os.path.isabs(lock_p):
2462
- active_ws = get_active_workspace()
2692
+ active_ws = _workspace_root()
2463
2693
  if active_ws and os.path.exists(os.path.join(active_ws, lock_p)):
2464
2694
  lock_p = os.path.abspath(os.path.join(active_ws, lock_p))
2465
2695
  if not pkg:
@@ -2467,7 +2697,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2467
2697
  try:
2468
2698
  from src.format_parsers.lockfiles import LockfileReducer
2469
2699
  if not lock_p:
2470
- active_ws = get_active_workspace()
2700
+ active_ws = _workspace_root()
2471
2701
  if active_ws and hasattr(LockfileReducer, "find_lockfile"):
2472
2702
  orig_cwd = os.getcwd()
2473
2703
  try:
@@ -2672,7 +2902,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2672
2902
  verify = args.get("verify")
2673
2903
  verify_timeout = int(args.get("verify_timeout_sec") or 30)
2674
2904
  raw_cwd = args.get("cwd")
2675
- active_ws = get_active_workspace()
2905
+ active_ws = _workspace_root()
2676
2906
  if raw_cwd:
2677
2907
  if not os.path.isabs(str(raw_cwd)) and active_ws and os.path.isdir(os.path.join(active_ws, str(raw_cwd))):
2678
2908
  cwd = os.path.abspath(os.path.join(active_ws, str(raw_cwd)))
@@ -2792,7 +3022,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2792
3022
  return _fallback_error("batch_search", "missing required 'queries' list")
2793
3023
 
2794
3024
  raw_cwd = args.get("cwd") or args.get("project_path") or args.get("path")
2795
- active_ws = get_active_workspace()
3025
+ active_ws = _workspace_root()
2796
3026
  if raw_cwd:
2797
3027
  if not os.path.isabs(raw_cwd) and active_ws and os.path.isdir(os.path.join(active_ws, raw_cwd)):
2798
3028
  cwd = os.path.abspath(os.path.join(active_ws, raw_cwd))
@@ -2815,12 +3045,23 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2815
3045
  sub_p = q_copy.get("path")
2816
3046
  if sub_p:
2817
3047
  sub_abs = os.path.realpath(os.path.normpath(os.path.join(cwd, str(sub_p))))
3048
+ if is_plugin_or_system_dir(sub_abs):
3049
+ return _fallback_error(
3050
+ "batch_search",
3051
+ f"refusing subquery path in a system/plugin dir '{sub_abs}' "
3052
+ f"(project root '{real_cwd}')",
3053
+ )
2818
3054
  try:
2819
3055
  inside = os.path.commonpath([real_cwd, sub_abs]) == real_cwd
2820
3056
  except ValueError:
2821
3057
  inside = False
2822
- if not inside or is_plugin_or_system_dir(sub_abs):
2823
- return _fallback_error("batch_search", f"refusing subquery path outside project root '{sub_p}'")
3058
+ if not inside:
3059
+ return _fallback_error(
3060
+ "batch_search",
3061
+ f"subquery path '{sub_p}' resolves to '{sub_abs}', outside project root "
3062
+ f"'{real_cwd}'. One call searches one root: pass that repo as cwd/project_path "
3063
+ f"with repo-relative paths, and split queries for other repos into separate calls.",
3064
+ )
2824
3065
  if is_quota_exceeded:
2825
3066
  q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
2826
3067
  safe_queries.append(q_copy)
@@ -3070,6 +3311,25 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
3070
3311
  return new_res
3071
3312
 
3072
3313
 
3314
+ def _tool_timeout(tool_name: str, tool_args: dict) -> float:
3315
+ """The tool's own declared budget wins over the transport's default.
3316
+
3317
+ `apply_edits` can run an inline verify command, and the edit is already on disk by
3318
+ then: cutting the call at the default 8 s both loses the verdict and tells the
3319
+ caller "could not complete" about work that did complete. Ask for the declared
3320
+ verify budget plus a margin, capped so a hung suite cannot wedge the server.
3321
+ """
3322
+ if tool_name == "apply_edits":
3323
+ has_verify = bool(tool_args.get("verify"))
3324
+ try:
3325
+ declared = int(tool_args.get("verify_timeout_sec") or (30 if has_verify else 0))
3326
+ except (TypeError, ValueError):
3327
+ declared = 30 if has_verify else 0
3328
+ if declared > 0:
3329
+ return min(max(MCP_TOOL_TIMEOUT, declared + 5.0), 180.0)
3330
+ return MCP_TOOL_TIMEOUT
3331
+
3332
+
3073
3333
  def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
3074
3334
  """Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
3075
3335
  box = {"result": None, "error": None}
@@ -3174,10 +3434,17 @@ def run_mcp_server():
3174
3434
  "serverInfo": SERVER_INFO
3175
3435
  }
3176
3436
  # Routing brief (MCP `instructions`): which stacks this workspace
3177
- # works through OUMV and which through the TokenSafe tools.
3437
+ # works through OUMV and which through the TokenSafe tools. The
3438
+ # server usually runs from the plugin dir, so prefer the session
3439
+ # workspace marker; extra roots (TOKENSAFE_WORKSPACES) are
3440
+ # classified one by one so a single-root verdict is never global.
3178
3441
  try:
3179
- from src.session_brief import build_workspace_brief
3180
- brief = build_workspace_brief(os.getcwd(), include_live=False)
3442
+ from src.session_brief import build_workspace_brief, workspace_roots_from_env
3443
+ brief = build_workspace_brief(
3444
+ _workspace_root() or os.getcwd(),
3445
+ include_live=False,
3446
+ extra_workspaces=workspace_roots_from_env(),
3447
+ )
3181
3448
  if brief:
3182
3449
  response["result"]["instructions"] = brief
3183
3450
  except Exception:
@@ -3185,7 +3452,13 @@ def run_mcp_server():
3185
3452
  elif method == "tools/list":
3186
3453
  _TOOLS_LISTED = True
3187
3454
  profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
3188
- response["result"] = {"tools": FULL_TOOLS if profile == "full" else TOOLS}
3455
+ if profile == "full":
3456
+ advertised = FULL_TOOLS
3457
+ elif profile == "lean":
3458
+ advertised = [t for t in TOOLS if t["name"] in _LEAN_TOOL_NAMES]
3459
+ else:
3460
+ advertised = TOOLS
3461
+ response["result"] = {"tools": advertised}
3189
3462
  elif method == "ping":
3190
3463
  response["result"] = {}
3191
3464
  elif method == "tools/call":
@@ -3198,7 +3471,7 @@ def run_mcp_server():
3198
3471
  # arguments as a malformed JSON string — repair before failing.
3199
3472
  from src.json_repair import parse_tool_arguments
3200
3473
  tool_args = parse_tool_arguments(raw_tool_args) or {}
3201
- raw_res = _execute_with_timeout(tool_name, tool_args)
3474
+ raw_res = _execute_with_timeout(tool_name, tool_args, timeout=_tool_timeout(tool_name, tool_args))
3202
3475
  redacted = _redact_result_secrets(raw_res)
3203
3476
  response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
3204
3477
  except Exception as e: