tokensafe 4.4.9 → 4.5.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/bin/agy-tokens +10 -1
- package/bin/tokensafe.js +2 -1
- package/hooks/claude_code_hook.py +38 -126
- package/hooks/cursor_hook.py +45 -1
- package/hooks/kimi_hook.py +46 -90
- package/hooks/pre_invocation.py +23 -4
- package/hooks/pre_tool_use.py +40 -22
- package/hooks/session_start.py +44 -15
- package/hooks/zcode_hook.py +95 -0
- package/hooks.json +1 -1
- package/kimi.plugin.json +17 -1
- package/mcp_config.json +24 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +24 -21
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +61 -76
- package/skills/token-optimizer/references/mcp-tools.md +32 -132
- package/src/adapter_core.py +231 -7
- package/src/batch_editor.py +403 -0
- package/src/batch_search.py +428 -0
- package/src/burn_monitor.py +581 -0
- package/src/cache_normalizer.py +2 -0
- package/src/cli.py +85 -4
- package/src/compactor.py +1 -1
- package/src/dashboard.py +17 -9
- package/src/diff_slicer.py +1 -1
- package/src/distiller.py +11 -1
- package/src/environment_auditor.py +30 -6
- package/src/format_parsers/ansi.py +1 -1
- package/src/format_parsers/lockfiles.py +22 -17
- package/src/format_parsers/tabular.py +6 -3
- package/src/fts_index.py +26 -20
- package/src/governor.py +2 -2
- package/src/graph_engine.py +232 -52
- package/src/guard.py +3 -3
- package/src/image_downscale.py +26 -0
- package/src/installer.py +61 -48
- package/src/license_manager.py +49 -16
- package/src/live_relay.py +9 -8
- package/src/mcp_proxy.py +13 -7
- package/src/mcp_server.py +758 -26
- package/src/metrics.py +10 -1
- package/src/mistakes.py +4 -2
- package/src/oumv_gateway.py +81 -7
- package/src/paths.py +4 -1
- package/src/proxy.py +302 -123
- package/src/result_ledger.py +39 -1
- package/src/schema_slicer.py +40 -18
- package/src/scoped_search.py +66 -23
- package/src/skeletonizer.py +22 -11
- package/src/slicer.py +6 -4
- package/src/snapshot.py +249 -0
- package/src/stash.py +37 -7
- package/src/superseded.py +42 -23
- package/src/syntax_guard.py +86 -0
- package/src/team_cache.py +3 -0
- package/src/telemetry_sync.py +66 -53
- package/src/thinking_fold.py +50 -12
- package/src/transcript_analyzer.py +483 -0
- package/src/treesitter_backend.py +2 -0
- package/src/type_slicer.py +60 -18
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +55 -22
package/src/mcp_server.py
CHANGED
|
@@ -13,7 +13,7 @@ import re
|
|
|
13
13
|
import threading
|
|
14
14
|
import traceback
|
|
15
15
|
import fnmatch
|
|
16
|
-
from typing import List, Tuple, Optional
|
|
16
|
+
from typing import List, Tuple, Optional, Any, Dict
|
|
17
17
|
|
|
18
18
|
# Ensure project root in sys.path
|
|
19
19
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
|
42
42
|
|
|
43
43
|
SERVER_INFO = {
|
|
44
44
|
"name": "tokensafe-mcp",
|
|
45
|
-
"version": "4.
|
|
45
|
+
"version": "4.5.1"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -77,7 +77,7 @@ def _client_supports_pointers() -> bool:
|
|
|
77
77
|
return bool(_MCP_CLIENT_NAME and any(k in _MCP_CLIENT_NAME for k in _KNOWN_POINTER_CLIENTS))
|
|
78
78
|
|
|
79
79
|
|
|
80
|
-
|
|
80
|
+
FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
81
81
|
'description': 'AST-skeleton file reader: keeps the target function/class body + 1-line 1-hop dependency '
|
|
82
82
|
'signatures, folds inert code (-90-99% tokens). Relative or absolute paths. Schema files '
|
|
83
83
|
"(OpenAPI/Prisma/GraphQL/SQL) auto-slice via 'symbol'. For 3+ related symbols use smart_bundle "
|
|
@@ -413,8 +413,10 @@ TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
413
413
|
'type': 'object'},
|
|
414
414
|
'name': 'oumv_observe'},
|
|
415
415
|
{ 'annotations': {'readOnlyHint': True},
|
|
416
|
-
'description': "Answers 'Why is state X / why is button disabled?' or performs impact
|
|
417
|
-
'
|
|
416
|
+
'description': "Answers 'Why is state X / why is button disabled?' (causality/why_state) or performs impact "
|
|
417
|
+
'analysis: causality merges both runtimes and adds static cross-stack edges (frontend action '
|
|
418
|
+
'-> backend endpoint) with evidence; impact walks reverse dependencies plus cross-stack '
|
|
419
|
+
'frontend callers of matching backend endpoints.',
|
|
418
420
|
'inputSchema': { 'properties': { 'query': { 'default': 'causality',
|
|
419
421
|
'description': 'Query type (causality, impact, why_state)',
|
|
420
422
|
'enum': ['causality', 'impact', 'why_state'],
|
|
@@ -430,7 +432,9 @@ TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
430
432
|
'name': 'oumv_understand'},
|
|
431
433
|
{ 'annotations': {'destructiveHint': False, 'readOnlyHint': False},
|
|
432
434
|
'description': 'Applies Optimistic Concurrency Control (OCC) source edit with Babel AST JSX/TSX syntax guards, '
|
|
433
|
-
'TypeScript verification, and secret leak prevention.'
|
|
435
|
+
'TypeScript verification, and secret leak prevention. Offline fallback performs an OCC-verified '
|
|
436
|
+
'direct workspace edit with syntax pre-flight (.py via ast, .js via node --check) and an '
|
|
437
|
+
'automatic backup of the previous content.',
|
|
434
438
|
'inputSchema': { 'properties': { 'expectedVersion': { 'description': 'Expected version token for '
|
|
435
439
|
'optimistic concurrency',
|
|
436
440
|
'type': 'string'},
|
|
@@ -466,7 +470,392 @@ TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
466
470
|
'type': 'string'}},
|
|
467
471
|
'required': ['target'],
|
|
468
472
|
'type': 'object'},
|
|
469
|
-
'name': 'oumv_verify'}
|
|
473
|
+
'name': 'oumv_verify'},
|
|
474
|
+
{ 'annotations': {'readOnlyHint': True},
|
|
475
|
+
'description': 'Unified cross-stack intelligence graph (spec §11): nodes and edges across frontend actions '
|
|
476
|
+
'and backend endpoints with evidence metadata. Queries: overview (graph summary, optionally '
|
|
477
|
+
'filtered by target), who_depends_on (which frontend code calls an endpoint), impact (affected '
|
|
478
|
+
'callers + suggested verification steps).',
|
|
479
|
+
'inputSchema': { 'properties': { 'query': { 'default': 'overview',
|
|
480
|
+
'description': 'Graph query (overview, who_depends_on, impact)',
|
|
481
|
+
'enum': ['overview', 'who_depends_on', 'impact'],
|
|
482
|
+
'type': 'string'},
|
|
483
|
+
'target': { 'description': "Target resource (e.g. '/api/orders' or "
|
|
484
|
+
"'POST /api/orders')",
|
|
485
|
+
'type': 'string'}},
|
|
486
|
+
'type': 'object'},
|
|
487
|
+
'name': 'oumv_graph'},
|
|
488
|
+
{ 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
|
|
489
|
+
'description': 'Atomic or best-effort multi-hunk and multi-file code editor (up to 50 files) with optional '
|
|
490
|
+
'inline verification command (e.g. npm test, pytest). Replaces serial single-hunk edit turns. '
|
|
491
|
+
'Validates hunks in-memory before disk write and preserves CRLF/permissions.',
|
|
492
|
+
'inputSchema': { 'properties': { 'best_effort': { 'description': 'If true, commits valid files while '
|
|
493
|
+
'returning drift hints for failed files',
|
|
494
|
+
'type': 'boolean'},
|
|
495
|
+
'cwd': {'description': 'Optional working directory', 'type': 'string'},
|
|
496
|
+
'dry_run': { 'description': 'If true, validates all hunks without touching '
|
|
497
|
+
'disk',
|
|
498
|
+
'type': 'boolean'},
|
|
499
|
+
'edits': { 'description': 'Array of up to 50 file edit objects',
|
|
500
|
+
'items': { 'properties': { 'create': { 'description': 'Optional '
|
|
501
|
+
'content '
|
|
502
|
+
'for newly '
|
|
503
|
+
'created '
|
|
504
|
+
'file',
|
|
505
|
+
'type': 'string'},
|
|
506
|
+
'hunks': { 'description': 'Array of '
|
|
507
|
+
'replacement '
|
|
508
|
+
'hunks',
|
|
509
|
+
'items': { 'properties': { 'end_line': { 'description': 'Optional '
|
|
510
|
+
'1-based '
|
|
511
|
+
'end '
|
|
512
|
+
'line '
|
|
513
|
+
'bound',
|
|
514
|
+
'type': 'integer'},
|
|
515
|
+
'replace_all': { 'description': 'Replace '
|
|
516
|
+
'all '
|
|
517
|
+
'occurrences',
|
|
518
|
+
'type': 'boolean'},
|
|
519
|
+
'replacement': { 'description': 'Replacement '
|
|
520
|
+
'string',
|
|
521
|
+
'type': 'string'},
|
|
522
|
+
'start_line': { 'description': 'Optional '
|
|
523
|
+
'1-based '
|
|
524
|
+
'start '
|
|
525
|
+
'line '
|
|
526
|
+
'bound',
|
|
527
|
+
'type': 'integer'},
|
|
528
|
+
'target': { 'description': 'Exact '
|
|
529
|
+
'string '
|
|
530
|
+
'to '
|
|
531
|
+
'be '
|
|
532
|
+
'replaced',
|
|
533
|
+
'type': 'string'}},
|
|
534
|
+
'required': [ 'target',
|
|
535
|
+
'replacement'],
|
|
536
|
+
'type': 'object'},
|
|
537
|
+
'type': 'array'},
|
|
538
|
+
'overwrite': { 'description': 'Allow '
|
|
539
|
+
'overwriting '
|
|
540
|
+
'existing '
|
|
541
|
+
'file '
|
|
542
|
+
'with '
|
|
543
|
+
'create',
|
|
544
|
+
'type': 'boolean'},
|
|
545
|
+
'path': { 'description': 'File '
|
|
546
|
+
'path '
|
|
547
|
+
'(relative '
|
|
548
|
+
'or '
|
|
549
|
+
'absolute)',
|
|
550
|
+
'type': 'string'}},
|
|
551
|
+
'required': ['path'],
|
|
552
|
+
'type': 'object'},
|
|
553
|
+
'maxItems': 50,
|
|
554
|
+
'type': 'array'},
|
|
555
|
+
'verify': { 'description': 'Optional shell command to execute immediately '
|
|
556
|
+
'after applying edits (e.g. npm test, pytest, '
|
|
557
|
+
'cargo test)',
|
|
558
|
+
'type': 'string'},
|
|
559
|
+
'verify_timeout_sec': { 'description': 'Verification timeout in seconds '
|
|
560
|
+
'(default 30)',
|
|
561
|
+
'type': 'integer'}},
|
|
562
|
+
'required': ['edits'],
|
|
563
|
+
'type': 'object'},
|
|
564
|
+
'name': 'apply_edits'},
|
|
565
|
+
{ 'annotations': {'readOnlyHint': True},
|
|
566
|
+
'description': 'Concurrent multi-query search engine: executes up to 20 text, regex, glob, fuzzy, or '
|
|
567
|
+
'read-only git queries in ONE call (<70ms local) without paying per-command remote check latency.',
|
|
568
|
+
'inputSchema': { 'properties': { 'cwd': {'description': 'Optional working directory', 'type': 'string'},
|
|
569
|
+
'queries': { 'description': 'Array of up to 20 search query objects',
|
|
570
|
+
'items': { 'properties': { 'case_sensitive': { 'description': 'Case-sensitive '
|
|
571
|
+
'search '
|
|
572
|
+
'(default '
|
|
573
|
+
'false)',
|
|
574
|
+
'type': 'boolean'},
|
|
575
|
+
'file_type': { 'description': 'Optional '
|
|
576
|
+
'file '
|
|
577
|
+
'type '
|
|
578
|
+
'filter '
|
|
579
|
+
"(e.g. "
|
|
580
|
+
"'typescript', "
|
|
581
|
+
"'python')",
|
|
582
|
+
'type': 'string'},
|
|
583
|
+
'glob': { 'description': 'Optional '
|
|
584
|
+
'glob '
|
|
585
|
+
'filter '
|
|
586
|
+
"(e.g. "
|
|
587
|
+
"'*.ts')",
|
|
588
|
+
'type': 'string'},
|
|
589
|
+
'max_results': { 'description': 'Max '
|
|
590
|
+
'matches '
|
|
591
|
+
'per '
|
|
592
|
+
'query '
|
|
593
|
+
'(default '
|
|
594
|
+
'25)',
|
|
595
|
+
'type': 'integer'},
|
|
596
|
+
'output_mode': { 'description': 'Output '
|
|
597
|
+
'mode: '
|
|
598
|
+
'content, '
|
|
599
|
+
'files_with_matches, '
|
|
600
|
+
'or '
|
|
601
|
+
'count',
|
|
602
|
+
'enum': [ 'content',
|
|
603
|
+
'files_with_matches',
|
|
604
|
+
'count'],
|
|
605
|
+
'type': 'string'},
|
|
606
|
+
'path': { 'description': 'Optional '
|
|
607
|
+
'subpath '
|
|
608
|
+
'to '
|
|
609
|
+
'scope '
|
|
610
|
+
'query',
|
|
611
|
+
'type': 'string'},
|
|
612
|
+
'pattern': { 'description': 'Search '
|
|
613
|
+
'pattern, '
|
|
614
|
+
'text, '
|
|
615
|
+
'regex, '
|
|
616
|
+
'glob, '
|
|
617
|
+
'or '
|
|
618
|
+
'read-only '
|
|
619
|
+
'git '
|
|
620
|
+
'command',
|
|
621
|
+
'type': 'string'},
|
|
622
|
+
'type': { 'description': 'Query '
|
|
623
|
+
'type: '
|
|
624
|
+
'text, '
|
|
625
|
+
'regex, '
|
|
626
|
+
'glob, '
|
|
627
|
+
'fuzzy, '
|
|
628
|
+
'or '
|
|
629
|
+
'git',
|
|
630
|
+
'enum': [ 'text',
|
|
631
|
+
'regex',
|
|
632
|
+
'glob',
|
|
633
|
+
'fuzzy',
|
|
634
|
+
'git'],
|
|
635
|
+
'type': 'string'}},
|
|
636
|
+
'required': ['pattern'],
|
|
637
|
+
'type': 'object'},
|
|
638
|
+
'maxItems': 20,
|
|
639
|
+
'type': 'array'}},
|
|
640
|
+
'required': ['queries'],
|
|
641
|
+
'type': 'object'},
|
|
642
|
+
'name': 'batch_search'}]
|
|
643
|
+
|
|
644
|
+
# Compact MCP surface (default): 7 consolidated tools (~2.2k tok vs ~6.0k tok for 28 schemas).
|
|
645
|
+
# All 28 legacy tool names remain callable in _dispatch_tool_call for backward compatibility.
|
|
646
|
+
# Set TOKENSAFE_MCP_PROFILE=full to expose FULL_TOOLS in tools/list.
|
|
647
|
+
TOOLS = [
|
|
648
|
+
{
|
|
649
|
+
'name': 'smart_read_file',
|
|
650
|
+
'description': (
|
|
651
|
+
'AST-skeleton reader (-90-98% tokens). Pass path+symbol for one file (auto-slices '
|
|
652
|
+
'OpenAPI/Prisma/GraphQL/SQL/lockfiles), targets=[{path,symbol}] to bundle 2-8 symbols, '
|
|
653
|
+
'or package_name+symbol for 3rd-party .d.ts types.'
|
|
654
|
+
),
|
|
655
|
+
'annotations': {'readOnlyHint': True},
|
|
656
|
+
'inputSchema': {
|
|
657
|
+
'type': 'object',
|
|
658
|
+
'properties': {
|
|
659
|
+
'path': {'type': 'string', 'description': 'File path (relative or absolute)'},
|
|
660
|
+
'symbol': {'type': 'string', 'description': 'Function/class/model/type to extract'},
|
|
661
|
+
'start_line': {'type': 'integer', 'description': 'Optional start line'},
|
|
662
|
+
'end_line': {'type': 'integer', 'description': 'Optional end line'},
|
|
663
|
+
'dep_mode': {'type': 'string', 'enum': ['signature', 'full'], 'description': '1-hop dep mode (default signature)'},
|
|
664
|
+
'include_deps': {'type': 'boolean', 'description': 'Include 1-hop deps (default true)'},
|
|
665
|
+
'force_full': {'type': 'boolean', 'description': 'Bypass pointer dedup'},
|
|
666
|
+
'project_root': {'type': 'string', 'description': 'Workspace root directory (for external types / lockfiles)'},
|
|
667
|
+
'targets': {
|
|
668
|
+
'type': 'array', 'maxItems': 8,
|
|
669
|
+
'description': 'Bundle mode: 2-8 {path, symbol} targets in one call',
|
|
670
|
+
'items': {'type': 'object', 'properties': {'path': {'type': 'string'}, 'symbol': {'type': 'string'}}, 'required': ['path']},
|
|
671
|
+
},
|
|
672
|
+
'package_name': {'type': 'string', 'description': 'External .d.ts npm package name'},
|
|
673
|
+
},
|
|
674
|
+
},
|
|
675
|
+
},
|
|
676
|
+
{
|
|
677
|
+
'name': 'scoped_search',
|
|
678
|
+
'description': (
|
|
679
|
+
'Safe token-bounded search replacing grep/find (-90% tokens). Pass query+scope for single '
|
|
680
|
+
'search (mode/type: auto|text|regex|glob|fuzzy|git), or queries=[{pattern,type,path,glob}] '
|
|
681
|
+
'for up to 20 concurrent queries.'
|
|
682
|
+
),
|
|
683
|
+
'annotations': {'readOnlyHint': True},
|
|
684
|
+
'inputSchema': {
|
|
685
|
+
'type': 'object',
|
|
686
|
+
'properties': {
|
|
687
|
+
'query': {'type': 'string', 'description': 'Text, symbol, regex, glob, or read-only git query'},
|
|
688
|
+
'mode': {'type': 'string', 'enum': ['auto', 'text', 'regex', 'glob', 'fuzzy', 'git'], 'description': 'Single-query mode'},
|
|
689
|
+
'scope': {'type': 'string', 'description': "'code', 'config', 'all', ext ('py'), or subfolder"},
|
|
690
|
+
'path': {'type': 'string', 'description': 'Directory path (default project root)'},
|
|
691
|
+
'project_path': {'type': 'string', 'description': 'Alias for path'},
|
|
692
|
+
'use_regex': {'type': 'boolean', 'description': 'Force regex true/false'},
|
|
693
|
+
'case_sensitive': {'type': 'boolean'},
|
|
694
|
+
'max_results': {'type': 'integer', 'description': 'Max lines (default 25, max 100)'},
|
|
695
|
+
'queries': {
|
|
696
|
+
'type': 'array', 'maxItems': 20,
|
|
697
|
+
'description': 'Batch mode: up to 20 {pattern, type, path, glob, output_mode} objects',
|
|
698
|
+
'items': {
|
|
699
|
+
'type': 'object',
|
|
700
|
+
'properties': {
|
|
701
|
+
'pattern': {'type': 'string'},
|
|
702
|
+
'type': {'type': 'string', 'enum': ['text', 'regex', 'glob', 'fuzzy', 'git']},
|
|
703
|
+
'path': {'type': 'string'},
|
|
704
|
+
'glob': {'type': 'string'},
|
|
705
|
+
'file_type': {'type': 'string'},
|
|
706
|
+
'output_mode': {'type': 'string', 'enum': ['content', 'files_with_matches', 'count']},
|
|
707
|
+
'case_sensitive': {'type': 'boolean'},
|
|
708
|
+
'max_results': {'type': 'integer'},
|
|
709
|
+
},
|
|
710
|
+
'required': ['pattern'],
|
|
711
|
+
},
|
|
712
|
+
},
|
|
713
|
+
'cwd': {'type': 'string', 'description': 'Optional working directory for batch mode'},
|
|
714
|
+
},
|
|
715
|
+
},
|
|
716
|
+
},
|
|
717
|
+
{
|
|
718
|
+
'name': 'apply_edits',
|
|
719
|
+
'description': 'Atomic/best-effort multi-hunk editor (up to 50 files) with optional inline verify command.',
|
|
720
|
+
'annotations': {'readOnlyHint': False, 'destructiveHint': False},
|
|
721
|
+
'inputSchema': {
|
|
722
|
+
'type': 'object',
|
|
723
|
+
'properties': {
|
|
724
|
+
'edits': {
|
|
725
|
+
'type': 'array', 'maxItems': 50,
|
|
726
|
+
'items': {
|
|
727
|
+
'type': 'object',
|
|
728
|
+
'properties': {
|
|
729
|
+
'path': {'type': 'string'},
|
|
730
|
+
'create': {'type': 'string'},
|
|
731
|
+
'overwrite': {'type': 'boolean'},
|
|
732
|
+
'hunks': {
|
|
733
|
+
'type': 'array',
|
|
734
|
+
'items': {
|
|
735
|
+
'type': 'object',
|
|
736
|
+
'properties': {
|
|
737
|
+
'target': {'type': 'string'},
|
|
738
|
+
'replacement': {'type': 'string'},
|
|
739
|
+
'start_line': {'type': 'integer'},
|
|
740
|
+
'end_line': {'type': 'integer'},
|
|
741
|
+
'replace_all': {'type': 'boolean'},
|
|
742
|
+
},
|
|
743
|
+
'required': ['target', 'replacement'],
|
|
744
|
+
},
|
|
745
|
+
},
|
|
746
|
+
},
|
|
747
|
+
'required': ['path'],
|
|
748
|
+
},
|
|
749
|
+
},
|
|
750
|
+
'best_effort': {'type': 'boolean'},
|
|
751
|
+
'dry_run': {'type': 'boolean'},
|
|
752
|
+
'verify': {'type': 'string', 'description': 'Shell command to run after edits (e.g. pytest, npm test)'},
|
|
753
|
+
'verify_timeout_sec': {'type': 'integer'},
|
|
754
|
+
'cwd': {'type': 'string'},
|
|
755
|
+
},
|
|
756
|
+
'required': ['edits'],
|
|
757
|
+
},
|
|
758
|
+
},
|
|
759
|
+
{
|
|
760
|
+
'name': 'repo_map',
|
|
761
|
+
'description': (
|
|
762
|
+
'Project structure & architecture without crawling: view="graph" (God Nodes & deps), '
|
|
763
|
+
'"api" (exported classes/types/interfaces), or "tree" (clean directory tree).'
|
|
764
|
+
),
|
|
765
|
+
'annotations': {'readOnlyHint': True},
|
|
766
|
+
'inputSchema': {
|
|
767
|
+
'type': 'object',
|
|
768
|
+
'properties': {
|
|
769
|
+
'view': {'type': 'string', 'enum': ['graph', 'api', 'tree'], 'default': 'graph'},
|
|
770
|
+
'project_path': {'type': 'string', 'description': 'Project root (pass absolute path in multi-repo setups)'},
|
|
771
|
+
'path': {'type': 'string', 'description': "Directory path for view='tree' (default '.')"},
|
|
772
|
+
'depth': {'type': 'integer', 'description': 'Tree depth (default 2, max 4)'},
|
|
773
|
+
'max_entries': {'type': 'integer'},
|
|
774
|
+
},
|
|
775
|
+
},
|
|
776
|
+
},
|
|
777
|
+
{
|
|
778
|
+
'name': 'session_context',
|
|
779
|
+
'description': (
|
|
780
|
+
'Session & context hygiene: action="budget" (Context Quality Score S-F), "compact" (fold transcript '
|
|
781
|
+
'to State Ledger), "prune" (drop superseded reads), "mistakes" (anti-stuck memory), or "metrics".'
|
|
782
|
+
),
|
|
783
|
+
'annotations': {'readOnlyHint': False, 'destructiveHint': False},
|
|
784
|
+
'inputSchema': {
|
|
785
|
+
'type': 'object',
|
|
786
|
+
'properties': {
|
|
787
|
+
'action': {'type': 'string', 'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics'], 'default': 'budget'},
|
|
788
|
+
'model': {'type': 'string'},
|
|
789
|
+
'session_id': {'type': 'string'},
|
|
790
|
+
'transcript_path': {'type': 'string'},
|
|
791
|
+
'window_tokens': {'type': 'integer'},
|
|
792
|
+
'invocation_num': {'type': 'integer'},
|
|
793
|
+
'project_root': {'type': 'string'},
|
|
794
|
+
'clear': {'type': 'boolean'},
|
|
795
|
+
},
|
|
796
|
+
'required': ['action'],
|
|
797
|
+
},
|
|
798
|
+
},
|
|
799
|
+
{
|
|
800
|
+
'name': 'oumv',
|
|
801
|
+
'description': (
|
|
802
|
+
'Live Frontend/Backend OUMV runtime protocol: action="status"|"observe" (L0-L4)|"understand" '
|
|
803
|
+
'(causality/impact)|"verify" (in-memory sandbox)|"mutate" (OCC edit)|"graph" (cross-stack).'
|
|
804
|
+
),
|
|
805
|
+
'annotations': {'readOnlyHint': False, 'destructiveHint': False},
|
|
806
|
+
'inputSchema': {
|
|
807
|
+
'type': 'object',
|
|
808
|
+
'properties': {
|
|
809
|
+
'action': {'type': 'string', 'enum': ['status', 'observe', 'understand', 'mutate', 'verify', 'graph'], 'default': 'status'},
|
|
810
|
+
'level': {'type': 'string', 'enum': ['L0', 'L1', 'L2', 'L3', 'L4']},
|
|
811
|
+
'query': {'type': 'string'},
|
|
812
|
+
'runtime': {'type': 'string', 'enum': ['frontend', 'backend', 'auto']},
|
|
813
|
+
'target': {'type': 'string'},
|
|
814
|
+
'path': {'type': 'string'},
|
|
815
|
+
'symbol': {'type': 'string'},
|
|
816
|
+
'replacement': {'type': 'string'},
|
|
817
|
+
'expectedVersion': {'type': 'string'},
|
|
818
|
+
'verify_action': {'type': 'string', 'description': "Action name for action='verify' (e.g. click, submit)"},
|
|
819
|
+
'payload': {'type': 'object'},
|
|
820
|
+
'workspace_dir': {'type': 'string'},
|
|
821
|
+
},
|
|
822
|
+
'required': ['action'],
|
|
823
|
+
},
|
|
824
|
+
},
|
|
825
|
+
{
|
|
826
|
+
'name': 'run_helper',
|
|
827
|
+
'description': (
|
|
828
|
+
'Unified utility runner: action="sanitize" (rewrite bash/tests), "guard" (security/hygiene check), '
|
|
829
|
+
'"diff" (slice diff), "deps" (query lockfile), "web" (fetch clean MD), "expand" (unfold #hash), '
|
|
830
|
+
'"image" (downscale), or "compress" (TOCP prompt).'
|
|
831
|
+
),
|
|
832
|
+
'annotations': {'readOnlyHint': False, 'destructiveHint': False},
|
|
833
|
+
'inputSchema': {
|
|
834
|
+
'type': 'object',
|
|
835
|
+
'properties': {
|
|
836
|
+
'action': {
|
|
837
|
+
'type': 'string',
|
|
838
|
+
'enum': ['sanitize', 'guard', 'diff', 'deps', 'web', 'expand', 'image', 'compress'],
|
|
839
|
+
},
|
|
840
|
+
'command': {'type': 'string'},
|
|
841
|
+
'code': {'type': 'string'},
|
|
842
|
+
'file_path': {'type': 'string'},
|
|
843
|
+
'diff': {'type': 'string'},
|
|
844
|
+
'max_context': {'type': 'integer'},
|
|
845
|
+
'package_name': {'type': 'string'},
|
|
846
|
+
'lockfile_path': {'type': 'string'},
|
|
847
|
+
'url': {'type': 'string'},
|
|
848
|
+
'force_refresh': {'type': 'boolean'},
|
|
849
|
+
'hash': {'type': 'string'},
|
|
850
|
+
'image_path': {'type': 'string'},
|
|
851
|
+
'max_edge': {'type': 'integer'},
|
|
852
|
+
'prompt': {'type': 'string'},
|
|
853
|
+
'cwd': {'type': 'string'},
|
|
854
|
+
},
|
|
855
|
+
'required': ['action'],
|
|
856
|
+
},
|
|
857
|
+
},
|
|
858
|
+
]
|
|
470
859
|
|
|
471
860
|
def format_file_size(size_bytes: int) -> str:
|
|
472
861
|
if size_bytes < 1024:
|
|
@@ -869,9 +1258,17 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
869
1258
|
_, eff_dep_mode = _resolve_dep_mode(args)
|
|
870
1259
|
cache_sym = f"{symbol}@{eff_dep_mode}" if (symbol and eff_dep_mode != "signature") else symbol
|
|
871
1260
|
is_ranged = args.get("start_line") is not None or args.get("end_line") is not None
|
|
872
|
-
is_quota_truncated =
|
|
1261
|
+
is_quota_truncated = (
|
|
1262
|
+
"[TokenSafe Community 500k limit reached:" in text_out
|
|
1263
|
+
or "// Quota exceeded" in text_out
|
|
1264
|
+
or ("monthly limit (" in text_out and "optimizations paused" in text_out)
|
|
1265
|
+
)
|
|
873
1266
|
if text_out and path and not is_ranged and not is_quota_truncated:
|
|
874
|
-
|
|
1267
|
+
active_ws = get_active_workspace()
|
|
1268
|
+
if not os.path.isabs(path) and active_ws and os.path.exists(os.path.join(active_ws, path)):
|
|
1269
|
+
abs_path = os.path.abspath(os.path.join(active_ws, path))
|
|
1270
|
+
else:
|
|
1271
|
+
abs_path = os.path.abspath(path)
|
|
875
1272
|
cur_hash = AgentFirewall._file_content_hash(abs_path)
|
|
876
1273
|
if cur_hash:
|
|
877
1274
|
_IN_PROCESS_DELIVERED[(abs_path, symbol, eff_dep_mode)] = (cur_hash, _EPOCH_GEN)
|
|
@@ -880,7 +1277,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
880
1277
|
try:
|
|
881
1278
|
AgentFirewall.record_cache(
|
|
882
1279
|
session_id=_mcp_session_id(),
|
|
883
|
-
file_path=
|
|
1280
|
+
file_path=abs_path,
|
|
884
1281
|
content=text_out,
|
|
885
1282
|
symbol=cache_sym,
|
|
886
1283
|
tracker=_get_safe_tracker()
|
|
@@ -910,8 +1307,100 @@ def _tier_quota_limit_msg(quota: dict) -> str:
|
|
|
910
1307
|
return f"{tier_name} monthly limit ({limit:,} tokens) reached; optimizations paused ({cta})."
|
|
911
1308
|
|
|
912
1309
|
|
|
1310
|
+
_REPO_MAP_ACTIONS = {
|
|
1311
|
+
"graph": "get_architecture_graph",
|
|
1312
|
+
"api": "get_api_surface",
|
|
1313
|
+
"tree": "list_dir",
|
|
1314
|
+
}
|
|
1315
|
+
_SESSION_CONTEXT_ACTIONS = {
|
|
1316
|
+
"budget": "context_budget",
|
|
1317
|
+
"compact": "compact_conversation",
|
|
1318
|
+
"prune": "prune_superseded",
|
|
1319
|
+
"mistakes": "get_mistakes",
|
|
1320
|
+
"metrics": "get_token_savings_metrics",
|
|
1321
|
+
}
|
|
1322
|
+
_OUMV_ACTIONS = {
|
|
1323
|
+
"status": "oumv_status",
|
|
1324
|
+
"observe": "oumv_observe",
|
|
1325
|
+
"understand": "oumv_understand",
|
|
1326
|
+
"mutate": "oumv_mutate",
|
|
1327
|
+
"verify": "oumv_verify",
|
|
1328
|
+
"graph": "oumv_graph",
|
|
1329
|
+
}
|
|
1330
|
+
_HELPER_ACTIONS = {
|
|
1331
|
+
"sanitize": "sanitize_command",
|
|
1332
|
+
"guard": "guard_inspect",
|
|
1333
|
+
"diff": "slice_diff",
|
|
1334
|
+
"deps": "query_dependency",
|
|
1335
|
+
"web": "read_web_page",
|
|
1336
|
+
"expand": "expand_ref",
|
|
1337
|
+
"image": "optimize_image",
|
|
1338
|
+
"compress": "compress_prompt",
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
|
|
913
1342
|
def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
914
1343
|
global _EPOCH_GEN
|
|
1344
|
+
# Route consolidated tools to canonical internal handlers (zero logic duplication).
|
|
1345
|
+
if name == "smart_read_file":
|
|
1346
|
+
if args.get("targets"):
|
|
1347
|
+
name = "smart_bundle"
|
|
1348
|
+
elif args.get("package_name") and not (args.get("path") or args.get("file_path") or args.get("file")):
|
|
1349
|
+
name = "slice_external_type"
|
|
1350
|
+
elif name == "scoped_search":
|
|
1351
|
+
mode = str(args.get("mode") or "").strip().lower()
|
|
1352
|
+
if args.get("queries"):
|
|
1353
|
+
name = "batch_search"
|
|
1354
|
+
elif mode in ("glob", "fuzzy", "git"):
|
|
1355
|
+
q = args.get("query") or args.get("pattern") or ""
|
|
1356
|
+
q_spec = {
|
|
1357
|
+
"pattern": q,
|
|
1358
|
+
"type": mode,
|
|
1359
|
+
"path": args.get("path") or args.get("project_path") or "",
|
|
1360
|
+
"case_sensitive": bool(args.get("case_sensitive", False)),
|
|
1361
|
+
"max_results": int(args.get("max_results") or 25),
|
|
1362
|
+
}
|
|
1363
|
+
raw_sc = str(args.get("scope") or "").strip()
|
|
1364
|
+
if raw_sc.startswith("*.") or "*" in raw_sc:
|
|
1365
|
+
q_spec["glob"] = raw_sc
|
|
1366
|
+
elif raw_sc and raw_sc.lower() not in ("all", "code", "config"):
|
|
1367
|
+
q_spec["file_type"] = raw_sc.lstrip(".")
|
|
1368
|
+
args = {
|
|
1369
|
+
"queries": [q_spec],
|
|
1370
|
+
"cwd": args.get("cwd") or args.get("project_path") or args.get("path"),
|
|
1371
|
+
}
|
|
1372
|
+
name = "batch_search"
|
|
1373
|
+
elif mode in ("text", "regex") and args.get("use_regex") is None:
|
|
1374
|
+
args = dict(args, use_regex=(mode == "regex"))
|
|
1375
|
+
elif name == "repo_map":
|
|
1376
|
+
view = str(args.get("view") or "graph").strip().lower()
|
|
1377
|
+
if view not in _REPO_MAP_ACTIONS:
|
|
1378
|
+
return _fallback_error("repo_map", f"unknown view '{view}' (expected graph|api|tree)")
|
|
1379
|
+
mapped = _REPO_MAP_ACTIONS[view]
|
|
1380
|
+
if view == "tree" and not args.get("path"):
|
|
1381
|
+
args = dict(args, path=args.get("project_path") or ".")
|
|
1382
|
+
elif view in ("graph", "api") and not args.get("project_path") and args.get("path"):
|
|
1383
|
+
args = dict(args, project_path=args.get("path"))
|
|
1384
|
+
name = mapped
|
|
1385
|
+
elif name == "session_context":
|
|
1386
|
+
action = str(args.get("action") or "budget").strip().lower()
|
|
1387
|
+
if action not in _SESSION_CONTEXT_ACTIONS:
|
|
1388
|
+
return _fallback_error("session_context", f"unknown action '{action}'")
|
|
1389
|
+
name = _SESSION_CONTEXT_ACTIONS[action]
|
|
1390
|
+
elif name == "oumv":
|
|
1391
|
+
action = str(args.get("action") or "status").strip().lower()
|
|
1392
|
+
if action not in _OUMV_ACTIONS:
|
|
1393
|
+
return _fallback_error("oumv", f"unknown action '{action}'")
|
|
1394
|
+
mapped = _OUMV_ACTIONS[action]
|
|
1395
|
+
if action == "verify":
|
|
1396
|
+
args = dict(args, action=args.get("verify_action") or "invoke")
|
|
1397
|
+
name = mapped
|
|
1398
|
+
elif name == "run_helper":
|
|
1399
|
+
action = str(args.get("action") or "").strip().lower()
|
|
1400
|
+
if action not in _HELPER_ACTIONS:
|
|
1401
|
+
return _fallback_error("run_helper", f"unknown action '{action}'")
|
|
1402
|
+
name = _HELPER_ACTIONS[action]
|
|
1403
|
+
|
|
915
1404
|
tracker = _get_safe_tracker()
|
|
916
1405
|
quota = LicenseManager.check_quota(tracker)
|
|
917
1406
|
is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
|
|
@@ -1113,12 +1602,14 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1113
1602
|
allow_pointer = (not force_full) and _client_supports_pointers() and already_here
|
|
1114
1603
|
is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
|
|
1115
1604
|
_mcp_session_id(),
|
|
1116
|
-
|
|
1605
|
+
abs_path,
|
|
1117
1606
|
symbol=cache_sym,
|
|
1118
1607
|
tracker=tracker,
|
|
1119
1608
|
allow_pointer=allow_pointer,
|
|
1120
1609
|
)
|
|
1121
1610
|
if is_hit and cached_text:
|
|
1611
|
+
if cur_hash and not already_here:
|
|
1612
|
+
_IN_PROCESS_DELIVERED[(abs_path, sym_clean, eff_dep_mode)] = (cur_hash, _EPOCH_GEN)
|
|
1122
1613
|
return {"content": [{"type": "text", "text": cached_text}]}
|
|
1123
1614
|
|
|
1124
1615
|
# Check loop detector (skip when force_full explicitly recovers from a pointer)
|
|
@@ -1321,7 +1812,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1321
1812
|
dep_sym = graph.symbols.get(dep_key)
|
|
1322
1813
|
if not dep_sym:
|
|
1323
1814
|
continue
|
|
1324
|
-
line = f" {qual} -> {dep_key
|
|
1815
|
+
line = f" {qual} -> {dep_key.split('::', 1)[-1]}: {dep_sym.signature.strip()[:160]}"
|
|
1325
1816
|
if line not in seen_dep_lines:
|
|
1326
1817
|
seen_dep_lines.add(line)
|
|
1327
1818
|
dep_lines.append(line)
|
|
@@ -1844,12 +2335,21 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1844
2335
|
# 2. Smart scope routing: handle agents passing subdirectories or extensions in `scope`
|
|
1845
2336
|
scope = raw_scope
|
|
1846
2337
|
if raw_scope and raw_scope.lower() not in ("code", "config", "all"):
|
|
1847
|
-
|
|
2338
|
+
real_base = os.path.realpath(target_path)
|
|
2339
|
+
candidate_subdir = os.path.realpath(os.path.normpath(os.path.join(target_path, raw_scope)))
|
|
2340
|
+
try:
|
|
2341
|
+
within_base = os.path.commonpath([real_base, candidate_subdir]) == real_base
|
|
2342
|
+
except ValueError:
|
|
2343
|
+
within_base = False
|
|
1848
2344
|
if os.path.isdir(candidate_subdir):
|
|
2345
|
+
if not within_base or is_plugin_or_system_dir(candidate_subdir):
|
|
2346
|
+
return _fallback_error("scoped_search", f"refusing to search outside target directory via scope '{raw_scope}'")
|
|
1849
2347
|
target_path = candidate_subdir
|
|
1850
2348
|
scope = "all"
|
|
1851
2349
|
elif "/" in raw_scope or "\\" in raw_scope:
|
|
1852
2350
|
if os.path.exists(candidate_subdir):
|
|
2351
|
+
if not within_base or is_plugin_or_system_dir(candidate_subdir):
|
|
2352
|
+
return _fallback_error("scoped_search", f"refusing to search outside target directory via scope '{raw_scope}'")
|
|
1853
2353
|
target_path = candidate_subdir
|
|
1854
2354
|
scope = "all"
|
|
1855
2355
|
|
|
@@ -1945,10 +2445,28 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1945
2445
|
elif name == "query_dependency":
|
|
1946
2446
|
pkg = str(args.get("package_name") or args.get("package") or "").strip()
|
|
1947
2447
|
lock_p = str(args.get("lockfile_path") or args.get("path") or "").strip() or None
|
|
2448
|
+
if lock_p and not os.path.isabs(lock_p):
|
|
2449
|
+
active_ws = get_active_workspace()
|
|
2450
|
+
if active_ws and os.path.exists(os.path.join(active_ws, lock_p)):
|
|
2451
|
+
lock_p = os.path.abspath(os.path.join(active_ws, lock_p))
|
|
1948
2452
|
if not pkg:
|
|
1949
2453
|
return _fallback_error("query_dependency", "missing required 'package_name' argument")
|
|
1950
2454
|
try:
|
|
1951
2455
|
from src.format_parsers.lockfiles import LockfileReducer
|
|
2456
|
+
if not lock_p:
|
|
2457
|
+
active_ws = get_active_workspace()
|
|
2458
|
+
if active_ws and hasattr(LockfileReducer, "find_lockfile"):
|
|
2459
|
+
orig_cwd = os.getcwd()
|
|
2460
|
+
try:
|
|
2461
|
+
os.chdir(active_ws)
|
|
2462
|
+
lock_p = LockfileReducer.find_lockfile()
|
|
2463
|
+
except Exception:
|
|
2464
|
+
lock_p = None
|
|
2465
|
+
finally:
|
|
2466
|
+
try:
|
|
2467
|
+
os.chdir(orig_cwd)
|
|
2468
|
+
except Exception:
|
|
2469
|
+
pass
|
|
1952
2470
|
res = LockfileReducer.query_dependency(lock_p, pkg)
|
|
1953
2471
|
lock_bytes = res.pop("_lockfile_bytes", 0)
|
|
1954
2472
|
json_text = json.dumps(res, indent=2, ensure_ascii=False)
|
|
@@ -1971,7 +2489,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1971
2489
|
elif name == "slice_external_type":
|
|
1972
2490
|
pkg = str(args.get("package_name") or args.get("package") or "").strip()
|
|
1973
2491
|
sym = str(args.get("symbol") or args.get("type") or args.get("type_name") or "").strip()
|
|
1974
|
-
proj_root = str(args.get("project_root") or "").strip() or None
|
|
2492
|
+
proj_root = str(args.get("project_root") or "").strip() or get_active_workspace() or None
|
|
1975
2493
|
if not pkg or not sym:
|
|
1976
2494
|
return _fallback_error("slice_external_type", "missing required 'package_name' or 'symbol' argument")
|
|
1977
2495
|
try:
|
|
@@ -2026,6 +2544,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2026
2544
|
res = SupersededPruner.prune_transcript(t_path)
|
|
2027
2545
|
if not res.get("success"):
|
|
2028
2546
|
return _fallback_error("prune_superseded", res.get("error", "pruning failed"))
|
|
2547
|
+
_EPOCH_GEN += 1
|
|
2029
2548
|
if res.get("saved_tokens", 0) > 0:
|
|
2030
2549
|
tracker.record_event(
|
|
2031
2550
|
session_id=_mcp_session_id(),
|
|
@@ -2061,7 +2580,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2061
2580
|
elif name == "oumv_status":
|
|
2062
2581
|
try:
|
|
2063
2582
|
from src.oumv_gateway import OUMVGateway
|
|
2064
|
-
ws = str(args.get("workspace_dir") or "").strip() or
|
|
2583
|
+
ws = str(args.get("workspace_dir") or "").strip() or get_active_workspace() or os.getcwd()
|
|
2065
2584
|
res = OUMVGateway.status(workspace_dir=ws)
|
|
2066
2585
|
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
2067
2586
|
except Exception as e:
|
|
@@ -2112,7 +2631,146 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2112
2631
|
res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt)
|
|
2113
2632
|
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
2114
2633
|
except Exception as e:
|
|
2115
|
-
return _fallback_error("oumv_verify", f"failed to
|
|
2634
|
+
return _fallback_error("oumv_verify", f"failed to verify OUMV action: {e}")
|
|
2635
|
+
|
|
2636
|
+
elif name == "oumv_graph":
|
|
2637
|
+
try:
|
|
2638
|
+
from src.oumv_gateway import OUMVGateway
|
|
2639
|
+
qry = str(args.get("query") or "overview").strip()
|
|
2640
|
+
tgt = str(args.get("target") or "").strip() or None
|
|
2641
|
+
res = OUMVGateway.graph(query=qry, target=tgt)
|
|
2642
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
2643
|
+
except Exception as e:
|
|
2644
|
+
return _fallback_error("oumv_graph", f"failed to query cross-stack graph: {e}")
|
|
2645
|
+
|
|
2646
|
+
elif name == "apply_edits":
|
|
2647
|
+
try:
|
|
2648
|
+
from src.batch_editor import execute_batch_edits
|
|
2649
|
+
edits = args.get("edits")
|
|
2650
|
+
if not edits:
|
|
2651
|
+
return _fallback_error("apply_edits", "missing required 'edits' list")
|
|
2652
|
+
best_effort = bool(args.get("best_effort", False))
|
|
2653
|
+
dry_run = bool(args.get("dry_run", False))
|
|
2654
|
+
verify = args.get("verify")
|
|
2655
|
+
verify_timeout = int(args.get("verify_timeout_sec") or 30)
|
|
2656
|
+
cwd = args.get("cwd") or get_active_workspace()
|
|
2657
|
+
|
|
2658
|
+
res = execute_batch_edits(
|
|
2659
|
+
edits=edits,
|
|
2660
|
+
best_effort=best_effort,
|
|
2661
|
+
dry_run=dry_run,
|
|
2662
|
+
verify=verify,
|
|
2663
|
+
verify_timeout_sec=verify_timeout,
|
|
2664
|
+
cwd=cwd
|
|
2665
|
+
)
|
|
2666
|
+
lines = []
|
|
2667
|
+
if res.get("success"):
|
|
2668
|
+
action_desc = "Validated" if dry_run else "Applied"
|
|
2669
|
+
lines.append(f"✔ {action_desc} {res.get('applied_count', 0)} file(s) successfully.")
|
|
2670
|
+
else:
|
|
2671
|
+
lines.append(f"✖ Batch edits failed ({res.get('failed_count', 0)} error(s)).")
|
|
2672
|
+
for f in res.get("failed_files", []):
|
|
2673
|
+
lines.append(f" - `{f.get('path')}`: {f.get('error')}")
|
|
2674
|
+
|
|
2675
|
+
if res.get("applied_files"):
|
|
2676
|
+
if not res.get("success"):
|
|
2677
|
+
lines.append(f"Applied {len(res['applied_files'])} file(s) before error/verify:")
|
|
2678
|
+
for f in res.get("applied_files", []):
|
|
2679
|
+
h_cnt = f.get("hunks", 0)
|
|
2680
|
+
is_cr = f.get("is_create", False)
|
|
2681
|
+
label = "created" if is_cr else f"{h_cnt} hunk(s)"
|
|
2682
|
+
lines.append(f" - `{f.get('path')}` ({label})")
|
|
2683
|
+
|
|
2684
|
+
if "verify" in res:
|
|
2685
|
+
v = res["verify"]
|
|
2686
|
+
status_sym = "✔ PASS" if v.get("passed") else "✖ FAIL"
|
|
2687
|
+
lines.append(f"\nInline Verify ({v.get('command')}): {status_sym} (exit {v.get('exit_code')}, {v.get('duration_seconds', 0)}s)")
|
|
2688
|
+
if v.get("output"):
|
|
2689
|
+
lines.append("```text\n" + v["output"] + "\n```")
|
|
2690
|
+
elif v.get("error"):
|
|
2691
|
+
lines.append(f"Error: {v['error']}")
|
|
2692
|
+
|
|
2693
|
+
out_msg = {"content": [{"type": "text", "text": "\n".join(lines)}]}
|
|
2694
|
+
if not res.get("success"):
|
|
2695
|
+
out_msg["isError"] = True
|
|
2696
|
+
return out_msg
|
|
2697
|
+
except Exception as e:
|
|
2698
|
+
return _fallback_error("apply_edits", f"failed to execute batch edits: {e}")
|
|
2699
|
+
|
|
2700
|
+
elif name == "batch_search":
|
|
2701
|
+
try:
|
|
2702
|
+
from src.batch_search import execute_batch_search
|
|
2703
|
+
queries = args.get("queries")
|
|
2704
|
+
if isinstance(queries, dict):
|
|
2705
|
+
queries = [queries]
|
|
2706
|
+
elif not queries and (args.get("query") or args.get("pattern")):
|
|
2707
|
+
queries = [{"pattern": args.get("query") or args.get("pattern"), "type": args.get("type", "text")}]
|
|
2708
|
+
if not queries:
|
|
2709
|
+
return _fallback_error("batch_search", "missing required 'queries' list")
|
|
2710
|
+
|
|
2711
|
+
raw_cwd = args.get("cwd") or args.get("project_path") or args.get("path")
|
|
2712
|
+
active_ws = get_active_workspace()
|
|
2713
|
+
if raw_cwd:
|
|
2714
|
+
if not os.path.isabs(raw_cwd) and active_ws and os.path.isdir(os.path.join(active_ws, raw_cwd)):
|
|
2715
|
+
cwd = os.path.abspath(os.path.join(active_ws, raw_cwd))
|
|
2716
|
+
else:
|
|
2717
|
+
cwd = os.path.abspath(raw_cwd)
|
|
2718
|
+
else:
|
|
2719
|
+
cwd, err = _resolve_project_root(args)
|
|
2720
|
+
if err or not cwd:
|
|
2721
|
+
return _fallback_error("batch_search", err or "unspecified project_path")
|
|
2722
|
+
if is_plugin_or_system_dir(cwd):
|
|
2723
|
+
return _fallback_error("batch_search", f"refusing to search system root or plugin dir '{cwd}'")
|
|
2724
|
+
|
|
2725
|
+
safe_queries: List[Dict[str, Any]] = []
|
|
2726
|
+
real_cwd = os.path.realpath(cwd)
|
|
2727
|
+
for q_item in queries:
|
|
2728
|
+
if not isinstance(q_item, dict):
|
|
2729
|
+
safe_queries.append(q_item)
|
|
2730
|
+
continue
|
|
2731
|
+
q_copy = dict(q_item)
|
|
2732
|
+
sub_p = q_copy.get("path")
|
|
2733
|
+
if sub_p:
|
|
2734
|
+
sub_abs = os.path.realpath(os.path.normpath(os.path.join(cwd, str(sub_p))))
|
|
2735
|
+
try:
|
|
2736
|
+
inside = os.path.commonpath([real_cwd, sub_abs]) == real_cwd
|
|
2737
|
+
except ValueError:
|
|
2738
|
+
inside = False
|
|
2739
|
+
if not inside or is_plugin_or_system_dir(sub_abs):
|
|
2740
|
+
return _fallback_error("batch_search", f"refusing subquery path outside project root '{sub_p}'")
|
|
2741
|
+
if is_quota_exceeded:
|
|
2742
|
+
q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
|
|
2743
|
+
safe_queries.append(q_copy)
|
|
2744
|
+
|
|
2745
|
+
res = execute_batch_search(queries=safe_queries, cwd=cwd)
|
|
2746
|
+
summary_md = res.get("summary_md", "")
|
|
2747
|
+
if is_quota_exceeded:
|
|
2748
|
+
banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
|
|
2749
|
+
current_tier = str(quota.get("tier") or "guest").lower()
|
|
2750
|
+
limit_val = int(quota.get("monthly_limit") or (50000 if current_tier == "guest" else 500000))
|
|
2751
|
+
cta_note = (
|
|
2752
|
+
"Run 'tokensafe login' in your terminal to unlock 500,000 free tokens/month!"
|
|
2753
|
+
if current_tier == "guest"
|
|
2754
|
+
else "Upgrade to Solo for unlimited optimization: https://tokensafe.dev/pricing"
|
|
2755
|
+
)
|
|
2756
|
+
degraded_header = (
|
|
2757
|
+
f"// [TokenSafe Quota Notice: {current_tier.upper()} limit of {limit_val:,} tokens reached. "
|
|
2758
|
+
f"Showing up to 3 matches per query in degraded mode.]\n"
|
|
2759
|
+
f"// [{cta_note}]\n\n"
|
|
2760
|
+
)
|
|
2761
|
+
return {"content": [{"type": "text", "text": banner + degraded_header + summary_md}]}
|
|
2762
|
+
res_tokens = count_tokens(summary_md)
|
|
2763
|
+
est_orig = max(1500, res_tokens * 8)
|
|
2764
|
+
tracker.record_event(
|
|
2765
|
+
session_id=_mcp_session_id(),
|
|
2766
|
+
event_type="SCOPED_SEARCH",
|
|
2767
|
+
original_tokens=est_orig,
|
|
2768
|
+
optimized_tokens=res_tokens,
|
|
2769
|
+
details={"query_count": len(safe_queries), "mode": "batch_search"},
|
|
2770
|
+
)
|
|
2771
|
+
return {"content": [{"type": "text", "text": summary_md}]}
|
|
2772
|
+
except Exception as e:
|
|
2773
|
+
return _fallback_error("batch_search", f"failed to execute batch search: {e}")
|
|
2116
2774
|
|
|
2117
2775
|
return _fallback_error(name, f"unknown tool '{name}'")
|
|
2118
2776
|
|
|
@@ -2156,6 +2814,73 @@ def _redact_result_secrets(result):
|
|
|
2156
2814
|
return redacted
|
|
2157
2815
|
|
|
2158
2816
|
|
|
2817
|
+
def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int = 8800) -> Any:
|
|
2818
|
+
"""Zero-Spill Guard: guarantees no MCP tool response exceeds 8800 UTF-8 bytes.
|
|
2819
|
+
Prevents Antigravity from spilling tool output to disk (output.txt) which forces
|
|
2820
|
+
an extra LLM roundtrip turn to read the spill file. Full content is saved to
|
|
2821
|
+
reversible stash and referenced with an 8-char hash anchor."""
|
|
2822
|
+
if not isinstance(result, dict):
|
|
2823
|
+
return result
|
|
2824
|
+
content = result.get("content")
|
|
2825
|
+
if not isinstance(content, list):
|
|
2826
|
+
return result
|
|
2827
|
+
|
|
2828
|
+
modified = False
|
|
2829
|
+
new_content = []
|
|
2830
|
+
for block in content:
|
|
2831
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
2832
|
+
text = block.get("text", "")
|
|
2833
|
+
raw_bytes = text.encode("utf-8")
|
|
2834
|
+
if len(raw_bytes) > max_bytes:
|
|
2835
|
+
try:
|
|
2836
|
+
from src.stash import stash_block
|
|
2837
|
+
from src.format_parsers.ansi import strip_ansi
|
|
2838
|
+
clean_text = strip_ansi(text)
|
|
2839
|
+
hash8, marker = stash_block(clean_text, source=f"mcp:{tool_name}")
|
|
2840
|
+
lines = clean_text.splitlines()
|
|
2841
|
+
footer = f"\n{marker}"
|
|
2842
|
+
footer_bytes = len(footer.encode("utf-8"))
|
|
2843
|
+
if len(lines) > 35:
|
|
2844
|
+
head = lines[:20]
|
|
2845
|
+
tail = lines[-15:]
|
|
2846
|
+
omitted = len(lines) - (len(head) + len(tail))
|
|
2847
|
+
folded_msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
|
|
2848
|
+
tail_str = "\n".join(tail)
|
|
2849
|
+
budget = max_bytes - len(folded_msg.encode("utf-8")) - footer_bytes - len(tail_str.encode("utf-8")) - 50
|
|
2850
|
+
head_str = ""
|
|
2851
|
+
for line in head:
|
|
2852
|
+
if len((head_str + line + "\n").encode("utf-8")) <= budget:
|
|
2853
|
+
head_str += line + "\n"
|
|
2854
|
+
else:
|
|
2855
|
+
break
|
|
2856
|
+
folded_text = f"{head_str.rstrip()}{folded_msg}{tail_str}{footer}"
|
|
2857
|
+
else:
|
|
2858
|
+
msg_mid = f"\n... [{len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
|
|
2859
|
+
avail = max(120, max_bytes - len(msg_mid.encode("utf-8")) - footer_bytes - 50)
|
|
2860
|
+
head_b = raw_bytes[: avail // 2].decode("utf-8", errors="ignore")
|
|
2861
|
+
tail_b = raw_bytes[-(avail - avail // 2):].decode("utf-8", errors="ignore")
|
|
2862
|
+
folded_text = f"{head_b.rstrip()}{msg_mid}{tail_b.lstrip()}{footer}"
|
|
2863
|
+
|
|
2864
|
+
if len(folded_text.encode("utf-8")) > max_bytes:
|
|
2865
|
+
allowed_head = max(80, max_bytes - footer_bytes - 60)
|
|
2866
|
+
folded_text = clean_text.encode("utf-8")[:allowed_head].decode("utf-8", errors="ignore") + f"\n... [folded]\n{footer}"
|
|
2867
|
+
|
|
2868
|
+
new_block = dict(block)
|
|
2869
|
+
new_block["text"] = folded_text
|
|
2870
|
+
new_content.append(new_block)
|
|
2871
|
+
modified = True
|
|
2872
|
+
continue
|
|
2873
|
+
except Exception:
|
|
2874
|
+
pass
|
|
2875
|
+
new_content.append(block)
|
|
2876
|
+
|
|
2877
|
+
if modified:
|
|
2878
|
+
new_res = dict(result)
|
|
2879
|
+
new_res["content"] = new_content
|
|
2880
|
+
return new_res
|
|
2881
|
+
return result
|
|
2882
|
+
|
|
2883
|
+
|
|
2159
2884
|
def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
|
|
2160
2885
|
"""Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
|
|
2161
2886
|
box = {"result": None, "error": None}
|
|
@@ -2261,20 +2986,27 @@ def run_mcp_server():
|
|
|
2261
2986
|
}
|
|
2262
2987
|
elif method == "tools/list":
|
|
2263
2988
|
_TOOLS_LISTED = True
|
|
2264
|
-
|
|
2989
|
+
profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
|
|
2990
|
+
response["result"] = {"tools": FULL_TOOLS if profile == "full" else TOOLS}
|
|
2991
|
+
elif method == "ping":
|
|
2992
|
+
response["result"] = {}
|
|
2265
2993
|
elif method == "tools/call":
|
|
2266
2994
|
tool_name = str(params.get("name") or "")
|
|
2267
2995
|
raw_tool_args = params.get("arguments")
|
|
2268
|
-
tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
|
|
2269
|
-
if not tool_args and raw_tool_args:
|
|
2270
|
-
# Self-healing: hosts on small/local models intermittently send
|
|
2271
|
-
# arguments as a malformed JSON string — repair before failing.
|
|
2272
|
-
from src.json_repair import parse_tool_arguments
|
|
2273
|
-
tool_args = parse_tool_arguments(raw_tool_args) or {}
|
|
2274
2996
|
try:
|
|
2275
|
-
|
|
2997
|
+
tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
|
|
2998
|
+
if not tool_args and raw_tool_args:
|
|
2999
|
+
# Self-healing: hosts on small/local models intermittently send
|
|
3000
|
+
# arguments as a malformed JSON string — repair before failing.
|
|
3001
|
+
from src.json_repair import parse_tool_arguments
|
|
3002
|
+
tool_args = parse_tool_arguments(raw_tool_args) or {}
|
|
3003
|
+
raw_res = _execute_with_timeout(tool_name, tool_args)
|
|
3004
|
+
redacted = _redact_result_secrets(raw_res)
|
|
3005
|
+
response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
|
|
2276
3006
|
except Exception as e:
|
|
2277
|
-
|
|
3007
|
+
err_res = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
|
|
3008
|
+
redacted = _redact_result_secrets(err_res)
|
|
3009
|
+
response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
|
|
2278
3010
|
finally:
|
|
2279
3011
|
try:
|
|
2280
3012
|
from src.telemetry_sync import TelemetrySync
|
|
@@ -2285,7 +3017,7 @@ def run_mcp_server():
|
|
|
2285
3017
|
response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
|
|
2286
3018
|
|
|
2287
3019
|
try:
|
|
2288
|
-
sys.stdout.write(json.dumps(response) + "\n")
|
|
3020
|
+
sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
|
|
2289
3021
|
sys.stdout.flush()
|
|
2290
3022
|
except Exception:
|
|
2291
3023
|
break
|