tokensafe 4.4.9 → 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.9"
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:
@@ -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
@@ -295,6 +295,31 @@ class OUMVGateway:
295
295
  def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto") -> Any:
296
296
  fe, be = cls.get_endpoints()
297
297
 
298
+ from src.graph_engine import GraphEngine
299
+ ws = get_active_workspace()
300
+ graph = GraphEngine.get_instance(ws)
301
+
302
+ # Impact analysis: static cross-stack graph as the backbone, runtime answers attached when online
303
+ if query == "impact":
304
+ report: Dict[str, Any] = {
305
+ "query": "impact",
306
+ "target": target,
307
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
308
+ }
309
+ report.update(graph.get_static_impact(target or ""))
310
+ if target:
311
+ if fe:
312
+ try:
313
+ report["frontendImpact"] = cls._rpc_call(fe["url"], "oumv/understand", {"query": "impact", "target": target, "componentId": target})
314
+ except Exception as e:
315
+ report["frontendError"] = str(e)
316
+ if be:
317
+ try:
318
+ report["backendImpact"] = cls._rpc_call(be["url"], "oumv/understand", {"query": "impact", "target": target})
319
+ except Exception as e:
320
+ report["backendError"] = str(e)
321
+ return report
322
+
298
323
  # Cross-layer causality query
299
324
  if query == "causality" and runtime in ("auto", ""):
300
325
  report = {
@@ -313,11 +338,13 @@ class OUMVGateway:
313
338
  except Exception as e:
314
339
  report["frontendError"] = str(e)
315
340
 
341
+ # Unified cross-stack relationships (frontend call -> backend endpoint), available online and offline
342
+ cross = cls._static_cross_stack(graph, target)
343
+ if cross["edges"]:
344
+ report["crossStack"] = cross
345
+
316
346
  # Out-of-the-box static fallback if neither is online
317
347
  if not be and not fe:
318
- from src.graph_engine import GraphEngine
319
- ws = get_active_workspace()
320
- graph = GraphEngine.get_instance(ws)
321
348
  report["staticAnalysis"] = graph.get_static_oumv_slice(level="L1", target=target)
322
349
  report["evidence"] = {"provenance": "static", "confidence": "confirmed", "sourceAdapter": "tokensafe-graph-engine"}
323
350
 
@@ -327,11 +354,31 @@ class OUMVGateway:
327
354
  url = cls._resolve_client_url(runtime=runtime, target=target)
328
355
  return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
329
356
  except RuntimeError:
330
- from src.graph_engine import GraphEngine
331
- ws = get_active_workspace()
332
- graph = GraphEngine.get_instance(ws)
357
+ if query == "impact":
358
+ return graph.get_static_impact(target or "")
333
359
  return graph.get_static_oumv_slice(level="L1", target=target)
334
360
 
361
+ @staticmethod
362
+ def _static_cross_stack(graph: Any, target: Optional[str]) -> Dict[str, Any]:
363
+ """Cross-stack edges (frontend API call -> backend endpoint) from the static graph."""
364
+ evidence = {"provenance": "static", "sourceAdapter": "tokensafe-graph-engine", "confidence": "probable"}
365
+ edges: List[Dict[str, Any]] = []
366
+ for link in getattr(graph, "api_links", []):
367
+ if target:
368
+ t = target.lower()
369
+ hay = " ".join([
370
+ link["source"].get("route") or "", link["source"].get("file") or "",
371
+ link["target"].get("route") or "", link["target"].get("file") or "",
372
+ ]).lower()
373
+ if t not in hay:
374
+ continue
375
+ edges.append({
376
+ "source": link["source"],
377
+ "target": link["target"],
378
+ "evidence": evidence,
379
+ })
380
+ return {"edges": edges[:30], "count": len(edges), "evidence": evidence}
381
+
335
382
  # 4. Tool: oumv_mutate
336
383
  @classmethod
337
384
  def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto") -> Any:
@@ -378,19 +425,46 @@ class OUMVGateway:
378
425
  if expected_version and current_version and expected_version != current_version:
379
426
  raise RuntimeError(f"[OUMV CONFLICT: -32001] OCC version mismatch: expected {expected_version}, current is {current_version}")
380
427
 
428
+ # Syntax pre-flight: never persist syntactically broken code (OUMV spec §8 Mutation Policy)
429
+ from src.syntax_guard import check_syntax
430
+ syntax_check = check_syntax(abs_path, replacement)
431
+ if syntax_check.get("status") == "failed":
432
+ raise RuntimeError(
433
+ f"[OUMV SYNTAX_ERROR: -32002] Edit rejected by syntax guard "
434
+ f"({syntax_check.get('tool')}): {syntax_check.get('error')}"
435
+ )
436
+
437
+ # Automatic backup of previous content before overwriting
438
+ backup_path = None
439
+ if current_version is not None:
440
+ try:
441
+ backup_dir = os.path.join(ws, ".tokensafe", "backups")
442
+ os.makedirs(backup_dir, exist_ok=True)
443
+ digest = hashlib.sha256(content).hexdigest()[:8]
444
+ backup_path = os.path.join(backup_dir, f"{digest}_{os.path.basename(abs_path)}.bak")
445
+ with open(backup_path, "wb") as f:
446
+ f.write(content)
447
+ except Exception:
448
+ backup_path = None
449
+
381
450
  os.makedirs(os.path.dirname(abs_path), exist_ok=True)
382
451
  with open(abs_path, "w", encoding="utf-8") as f:
383
452
  f.write(replacement)
384
453
 
385
454
  new_version = "sha256:" + hashlib.sha256(replacement.encode("utf-8")).hexdigest()
386
- return {
455
+ result = {
387
456
  "success": True,
388
457
  "path": path,
389
458
  "symbol": symbol,
390
459
  "newVersion": new_version,
391
460
  "mode": "OUT_OF_THE_BOX_DIRECT_EDIT",
461
+ "syntaxCheck": syntax_check,
392
462
  "message": "Surgical edit applied directly to workspace file (dev-server offline)",
393
463
  }
464
+ if backup_path:
465
+ result["backupPath"] = backup_path
466
+ result["rollbackHint"] = f"Previous content backed up at {backup_path}"
467
+ return result
394
468
  raise
395
469
 
396
470
  # 5. Tool: oumv_verify