tokensafe 4.7.0 → 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.
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +22 -0
- package/hooks/claude_code_hook.py +15 -13
- package/hooks/kimi_hook.py +14 -12
- package/hooks/session_start.py +8 -2
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +2 -1
- package/src/agent_firewall.py +16 -1
- package/src/auto_inject.py +93 -7
- package/src/batch_editor.py +106 -15
- package/src/bench/driver.py +18 -3
- package/src/bench/go_target.py +308 -22
- package/src/bench/mechanics.py +214 -0
- package/src/bench/react_target.py +312 -5
- package/src/bench/runner.py +114 -30
- package/src/bench/tokensafe_mcp.py +144 -0
- package/src/cli.py +32 -1
- package/src/installer.py +3 -3
- package/src/mcp_server.py +457 -227
- package/src/retrofit.py +27 -5
- package/src/scaffold.py +8 -6
- package/src/scoped_search.py +67 -5
- package/src/session_brief.py +180 -15
- package/src/skeletonizer.py +9 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
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.
|
|
46
|
+
"version": "4.7.1"
|
|
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
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
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=
|
|
1684
|
-
optimized_tokens=
|
|
1685
|
-
details={"file": os.path.basename(path), "lines": range_label,
|
|
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:
|
|
@@ -2357,13 +2532,35 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2357
2532
|
raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
|
|
2358
2533
|
active_ws = _workspace_root()
|
|
2359
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
|
|
2549
|
+
|
|
2360
2550
|
# 1. Resolve base directory safely without scanning plugin or system roots
|
|
2361
2551
|
if raw_path:
|
|
2362
2552
|
if not os.path.isabs(raw_path):
|
|
2363
|
-
if
|
|
2364
|
-
target_path = os.path.abspath(os.path.join(
|
|
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))
|
|
2365
2555
|
else:
|
|
2366
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
|
+
)
|
|
2367
2564
|
else:
|
|
2368
2565
|
target_path = os.path.abspath(raw_path)
|
|
2369
2566
|
|
|
@@ -2415,7 +2612,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2415
2612
|
scope=scope,
|
|
2416
2613
|
max_results=max_res,
|
|
2417
2614
|
case_sensitive=c_sens,
|
|
2418
|
-
use_regex=u_regex
|
|
2615
|
+
use_regex=u_regex,
|
|
2616
|
+
per_file=_safe_int(args.get("per_file"), 0, lo=0, hi=100)
|
|
2419
2617
|
)
|
|
2420
2618
|
md_text = res["markdown"]
|
|
2421
2619
|
if not res.get("success", True):
|
|
@@ -2861,8 +3059,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2861
3059
|
return _fallback_error(
|
|
2862
3060
|
"batch_search",
|
|
2863
3061
|
f"subquery path '{sub_p}' resolves to '{sub_abs}', outside project root "
|
|
2864
|
-
f"'{real_cwd}'.
|
|
2865
|
-
f"
|
|
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.",
|
|
2866
3064
|
)
|
|
2867
3065
|
if is_quota_exceeded:
|
|
2868
3066
|
q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
|
|
@@ -3113,6 +3311,25 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
|
|
|
3113
3311
|
return new_res
|
|
3114
3312
|
|
|
3115
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
|
+
|
|
3116
3333
|
def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
|
|
3117
3334
|
"""Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
|
|
3118
3335
|
box = {"result": None, "error": None}
|
|
@@ -3217,10 +3434,17 @@ def run_mcp_server():
|
|
|
3217
3434
|
"serverInfo": SERVER_INFO
|
|
3218
3435
|
}
|
|
3219
3436
|
# Routing brief (MCP `instructions`): which stacks this workspace
|
|
3220
|
-
# 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.
|
|
3221
3441
|
try:
|
|
3222
|
-
from src.session_brief import build_workspace_brief
|
|
3223
|
-
brief = build_workspace_brief(
|
|
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
|
+
)
|
|
3224
3448
|
if brief:
|
|
3225
3449
|
response["result"]["instructions"] = brief
|
|
3226
3450
|
except Exception:
|
|
@@ -3228,7 +3452,13 @@ def run_mcp_server():
|
|
|
3228
3452
|
elif method == "tools/list":
|
|
3229
3453
|
_TOOLS_LISTED = True
|
|
3230
3454
|
profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
|
|
3231
|
-
|
|
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}
|
|
3232
3462
|
elif method == "ping":
|
|
3233
3463
|
response["result"] = {}
|
|
3234
3464
|
elif method == "tools/call":
|
|
@@ -3241,7 +3471,7 @@ def run_mcp_server():
|
|
|
3241
3471
|
# arguments as a malformed JSON string — repair before failing.
|
|
3242
3472
|
from src.json_repair import parse_tool_arguments
|
|
3243
3473
|
tool_args = parse_tool_arguments(raw_tool_args) or {}
|
|
3244
|
-
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))
|
|
3245
3475
|
redacted = _redact_result_secrets(raw_res)
|
|
3246
3476
|
response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
|
|
3247
3477
|
except Exception as e:
|