tokensafe 4.4.7 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp_server.py CHANGED
@@ -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.4.7"
45
+ "version": "4.5.0"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -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 analysis by querying "
417
- 'runtime signal & causality graph for tokensafe-ui, React, Vue, and Backend services.',
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,162 @@ 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': False, 'destructiveHint': False},
475
+ 'description': 'Atomic or best-effort multi-hunk and multi-file code editor (up to 50 files) with optional '
476
+ 'inline verification command (e.g. npm test, pytest). Replaces serial single-hunk edit turns. '
477
+ 'Validates hunks in-memory before disk write and preserves CRLF/permissions.',
478
+ 'inputSchema': { 'properties': { 'best_effort': { 'description': 'If true, commits valid files while '
479
+ 'returning drift hints for failed files',
480
+ 'type': 'boolean'},
481
+ 'cwd': {'description': 'Optional working directory', 'type': 'string'},
482
+ 'dry_run': { 'description': 'If true, validates all hunks without touching '
483
+ 'disk',
484
+ 'type': 'boolean'},
485
+ 'edits': { 'description': 'Array of up to 50 file edit objects',
486
+ 'items': { 'properties': { 'create': { 'description': 'Optional '
487
+ 'content '
488
+ 'for newly '
489
+ 'created '
490
+ 'file',
491
+ 'type': 'string'},
492
+ 'hunks': { 'description': 'Array of '
493
+ 'replacement '
494
+ 'hunks',
495
+ 'items': { 'properties': { 'end_line': { 'description': 'Optional '
496
+ '1-based '
497
+ 'end '
498
+ 'line '
499
+ 'bound',
500
+ 'type': 'integer'},
501
+ 'replace_all': { 'description': 'Replace '
502
+ 'all '
503
+ 'occurrences',
504
+ 'type': 'boolean'},
505
+ 'replacement': { 'description': 'Replacement '
506
+ 'string',
507
+ 'type': 'string'},
508
+ 'start_line': { 'description': 'Optional '
509
+ '1-based '
510
+ 'start '
511
+ 'line '
512
+ 'bound',
513
+ 'type': 'integer'},
514
+ 'target': { 'description': 'Exact '
515
+ 'string '
516
+ 'to '
517
+ 'be '
518
+ 'replaced',
519
+ 'type': 'string'}},
520
+ 'required': [ 'target',
521
+ 'replacement'],
522
+ 'type': 'object'},
523
+ 'type': 'array'},
524
+ 'overwrite': { 'description': 'Allow '
525
+ 'overwriting '
526
+ 'existing '
527
+ 'file '
528
+ 'with '
529
+ 'create',
530
+ 'type': 'boolean'},
531
+ 'path': { 'description': 'File '
532
+ 'path '
533
+ '(relative '
534
+ 'or '
535
+ 'absolute)',
536
+ 'type': 'string'}},
537
+ 'required': ['path'],
538
+ 'type': 'object'},
539
+ 'maxItems': 50,
540
+ 'type': 'array'},
541
+ 'verify': { 'description': 'Optional shell command to execute immediately '
542
+ 'after applying edits (e.g. npm test, pytest, '
543
+ 'cargo test)',
544
+ 'type': 'string'},
545
+ 'verify_timeout_sec': { 'description': 'Verification timeout in seconds '
546
+ '(default 30)',
547
+ 'type': 'integer'}},
548
+ 'required': ['edits'],
549
+ 'type': 'object'},
550
+ 'name': 'apply_edits'},
551
+ { 'annotations': {'readOnlyHint': True},
552
+ 'description': 'Concurrent multi-query search engine: executes up to 20 text, regex, glob, fuzzy, or '
553
+ 'read-only git queries in ONE call (<70ms local) without paying per-command remote check latency.',
554
+ 'inputSchema': { 'properties': { 'cwd': {'description': 'Optional working directory', 'type': 'string'},
555
+ 'queries': { 'description': 'Array of up to 20 search query objects',
556
+ 'items': { 'properties': { 'case_sensitive': { 'description': 'Case-sensitive '
557
+ 'search '
558
+ '(default '
559
+ 'false)',
560
+ 'type': 'boolean'},
561
+ 'file_type': { 'description': 'Optional '
562
+ 'file '
563
+ 'type '
564
+ 'filter '
565
+ "(e.g. "
566
+ "'typescript', "
567
+ "'python')",
568
+ 'type': 'string'},
569
+ 'glob': { 'description': 'Optional '
570
+ 'glob '
571
+ 'filter '
572
+ "(e.g. "
573
+ "'*.ts')",
574
+ 'type': 'string'},
575
+ 'max_results': { 'description': 'Max '
576
+ 'matches '
577
+ 'per '
578
+ 'query '
579
+ '(default '
580
+ '25)',
581
+ 'type': 'integer'},
582
+ 'output_mode': { 'description': 'Output '
583
+ 'mode: '
584
+ 'content, '
585
+ 'files_with_matches, '
586
+ 'or '
587
+ 'count',
588
+ 'enum': [ 'content',
589
+ 'files_with_matches',
590
+ 'count'],
591
+ 'type': 'string'},
592
+ 'path': { 'description': 'Optional '
593
+ 'subpath '
594
+ 'to '
595
+ 'scope '
596
+ 'query',
597
+ 'type': 'string'},
598
+ 'pattern': { 'description': 'Search '
599
+ 'pattern, '
600
+ 'text, '
601
+ 'regex, '
602
+ 'glob, '
603
+ 'or '
604
+ 'read-only '
605
+ 'git '
606
+ 'command',
607
+ 'type': 'string'},
608
+ 'type': { 'description': 'Query '
609
+ 'type: '
610
+ 'text, '
611
+ 'regex, '
612
+ 'glob, '
613
+ 'fuzzy, '
614
+ 'or '
615
+ 'git',
616
+ 'enum': [ 'text',
617
+ 'regex',
618
+ 'glob',
619
+ 'fuzzy',
620
+ 'git'],
621
+ 'type': 'string'}},
622
+ 'required': ['pattern'],
623
+ 'type': 'object'},
624
+ 'maxItems': 20,
625
+ 'type': 'array'}},
626
+ 'required': ['queries'],
627
+ 'type': 'object'},
628
+ 'name': 'batch_search'}]
470
629
 
471
630
  def format_file_size(size_bytes: int) -> str:
472
631
  if size_bytes < 1024:
@@ -610,18 +769,18 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
610
769
  return None, f"Error: project_path not found or not a directory: '{target}'."
611
770
  return target_abs, None
612
771
 
772
+ # Check active workspace recorded by lifecycle hooks
773
+ if active_ws and not is_plugin_or_system_dir(active_ws) and os.path.isdir(active_ws):
774
+ return active_ws, None
775
+
613
776
  # Check environment variables
614
- for env_var in ("AGY_PROJECT_PATH", "WORKSPACE_FOLDER", "PROJECT_DIR", "PWD"):
777
+ for env_var in ("AGY_PROJECT_PATH", "WORKSPACE_FOLDER", "PROJECT_DIR"):
615
778
  candidate = os.environ.get(env_var)
616
779
  if candidate:
617
780
  cand_abs = os.path.abspath(candidate)
618
781
  if not is_plugin_or_system_dir(cand_abs) and os.path.isdir(cand_abs):
619
782
  return cand_abs, None
620
783
 
621
- # Check active workspace recorded by lifecycle hooks
622
- if active_ws and not is_plugin_or_system_dir(active_ws) and os.path.isdir(active_ws):
623
- return active_ws, None
624
-
625
784
  # Check cwd (only if it is not inside an agent plugin or system root directory)
626
785
  cwd = os.getcwd()
627
786
  if cwd:
@@ -1813,6 +1972,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1813
1972
  return {"content": [{"type": "text", "text": tree_output}]}
1814
1973
 
1815
1974
  elif name == "scoped_search":
1975
+ if args.get("queries"):
1976
+ from src.batch_search import execute_batch_search
1977
+ cwd = args.get("cwd") or get_active_workspace()
1978
+ res = execute_batch_search(queries=args.get("queries"), cwd=cwd)
1979
+ return {"content": [{"type": "text", "text": res.get("summary_md", "")}]}
1980
+
1816
1981
  query = args.get("query") or args.get("q") or args.get("pattern") or args.get("text") or ""
1817
1982
  if not query:
1818
1983
  return _fallback_error("scoped_search", "missing required 'query' argument")
@@ -2114,6 +2279,70 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2114
2279
  except Exception as e:
2115
2280
  return _fallback_error("oumv_verify", f"failed to execute OUMV verification: {e}")
2116
2281
 
2282
+ elif name == "apply_edits":
2283
+ try:
2284
+ from src.batch_editor import execute_batch_edits
2285
+ edits = args.get("edits")
2286
+ if not edits:
2287
+ return _fallback_error("apply_edits", "missing required 'edits' list")
2288
+ best_effort = bool(args.get("best_effort", False))
2289
+ dry_run = bool(args.get("dry_run", False))
2290
+ verify = args.get("verify")
2291
+ verify_timeout = int(args.get("verify_timeout_sec") or 30)
2292
+ cwd = args.get("cwd") or get_active_workspace()
2293
+
2294
+ res = execute_batch_edits(
2295
+ edits=edits,
2296
+ best_effort=best_effort,
2297
+ dry_run=dry_run,
2298
+ verify=verify,
2299
+ verify_timeout_sec=verify_timeout,
2300
+ cwd=cwd
2301
+ )
2302
+ lines = []
2303
+ if res.get("success"):
2304
+ action_desc = "Validated" if dry_run else "Applied"
2305
+ lines.append(f"✔ {action_desc} {res.get('applied_count', 0)} file(s) successfully.")
2306
+ for f in res.get("applied_files", []):
2307
+ h_cnt = f.get("hunks", 0)
2308
+ is_cr = f.get("is_create", False)
2309
+ label = "created" if is_cr else f"{h_cnt} hunk(s)"
2310
+ lines.append(f" - `{f.get('path')}` ({label})")
2311
+ else:
2312
+ lines.append(f"✖ Batch edits failed ({res.get('failed_count', 0)} error(s)).")
2313
+ for f in res.get("failed_files", []):
2314
+ lines.append(f" - `{f.get('path')}`: {f.get('error')}")
2315
+
2316
+ if "verify" in res:
2317
+ v = res["verify"]
2318
+ status_sym = "✔ PASS" if v.get("passed") else "✖ FAIL"
2319
+ lines.append(f"\nInline Verify ({v.get('command')}): {status_sym} (exit {v.get('exit_code')}, {v.get('duration_seconds', 0)}s)")
2320
+ if v.get("output"):
2321
+ lines.append("```text\n" + v["output"] + "\n```")
2322
+ elif v.get("error"):
2323
+ lines.append(f"Error: {v['error']}")
2324
+
2325
+ return {"content": [{"type": "text", "text": "\n".join(lines)}]}
2326
+ except Exception as e:
2327
+ return _fallback_error("apply_edits", f"failed to execute batch edits: {e}")
2328
+
2329
+ elif name == "batch_search":
2330
+ try:
2331
+ from src.batch_search import execute_batch_search
2332
+ queries = args.get("queries")
2333
+ if isinstance(queries, dict):
2334
+ queries = [queries]
2335
+ elif not queries and (args.get("query") or args.get("pattern")):
2336
+ queries = [{"pattern": args.get("query") or args.get("pattern"), "type": args.get("type", "text")}]
2337
+ if not queries:
2338
+ return _fallback_error("batch_search", "missing required 'queries' list")
2339
+
2340
+ cwd = args.get("cwd") or get_active_workspace()
2341
+ res = execute_batch_search(queries=queries, cwd=cwd)
2342
+ return {"content": [{"type": "text", "text": res.get("summary_md", "")}]}
2343
+ except Exception as e:
2344
+ return _fallback_error("batch_search", f"failed to execute batch search: {e}")
2345
+
2117
2346
  return _fallback_error(name, f"unknown tool '{name}'")
2118
2347
 
2119
2348
 
@@ -2156,6 +2385,66 @@ def _redact_result_secrets(result):
2156
2385
  return redacted
2157
2386
 
2158
2387
 
2388
+ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int = 8800) -> Any:
2389
+ """Zero-Spill Guard: guarantees no MCP tool response exceeds 8800 UTF-8 bytes.
2390
+ Prevents Antigravity from spilling tool output to disk (output.txt) which forces
2391
+ an extra LLM roundtrip turn to read the spill file. Full content is saved to
2392
+ reversible stash and referenced with an 8-char hash anchor."""
2393
+ if not isinstance(result, dict):
2394
+ return result
2395
+ content = result.get("content")
2396
+ if not isinstance(content, list):
2397
+ return result
2398
+
2399
+ modified = False
2400
+ new_content = []
2401
+ for block in content:
2402
+ if isinstance(block, dict) and block.get("type") == "text":
2403
+ text = block.get("text", "")
2404
+ raw_bytes = text.encode("utf-8")
2405
+ if len(raw_bytes) > max_bytes:
2406
+ try:
2407
+ from src.stash import stash_block
2408
+ from src.format_parsers.ansi import strip_ansi
2409
+ clean_text = strip_ansi(text)
2410
+ hash8, marker = stash_block(clean_text, source=f"mcp:{tool_name}")
2411
+ lines = clean_text.splitlines()
2412
+ head = lines[:20]
2413
+ tail = lines[-15:]
2414
+ omitted = len(lines) - (len(head) + len(tail))
2415
+ folded_msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2416
+ tail_str = "\n".join(tail)
2417
+ footer = f"\n{marker}"
2418
+
2419
+ budget = max_bytes - len(folded_msg.encode("utf-8")) - len(footer.encode("utf-8")) - len(tail_str.encode("utf-8")) - 50
2420
+ head_str = ""
2421
+ for line in head:
2422
+ if len((head_str + line + "\n").encode("utf-8")) <= budget:
2423
+ head_str += line + "\n"
2424
+ else:
2425
+ break
2426
+
2427
+ folded_text = f"{head_str.rstrip()}{folded_msg}{tail_str}{footer}"
2428
+ if len(folded_text.encode("utf-8")) > max_bytes:
2429
+ allowed_head = max_bytes - len(footer.encode("utf-8")) - 100
2430
+ folded_text = clean_text.encode("utf-8")[:allowed_head].decode("utf-8", errors="ignore") + f"\n... [folded]\n{footer}"
2431
+
2432
+ new_block = dict(block)
2433
+ new_block["text"] = folded_text
2434
+ new_content.append(new_block)
2435
+ modified = True
2436
+ continue
2437
+ except Exception:
2438
+ pass
2439
+ new_content.append(block)
2440
+
2441
+ if modified:
2442
+ new_res = dict(result)
2443
+ new_res["content"] = new_content
2444
+ return new_res
2445
+ return result
2446
+
2447
+
2159
2448
  def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
2160
2449
  """Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
2161
2450
  box = {"result": None, "error": None}
@@ -2272,9 +2561,13 @@ def run_mcp_server():
2272
2561
  from src.json_repair import parse_tool_arguments
2273
2562
  tool_args = parse_tool_arguments(raw_tool_args) or {}
2274
2563
  try:
2275
- response["result"] = _redact_result_secrets(_execute_with_timeout(tool_name, tool_args))
2564
+ raw_res = _execute_with_timeout(tool_name, tool_args)
2565
+ redacted = _redact_result_secrets(raw_res)
2566
+ response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
2276
2567
  except Exception as e:
2277
- response["result"] = _redact_result_secrets(_fallback_error(tool_name, f"{type(e).__name__}: {str(e)}"))
2568
+ err_res = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
2569
+ redacted = _redact_result_secrets(err_res)
2570
+ response["result"] = _cap_mcp_output_size(redacted, tool_name=tool_name)
2278
2571
  finally:
2279
2572
  try:
2280
2573
  from src.telemetry_sync import TelemetrySync