tokensafe 4.7.2 → 4.7.4

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
@@ -37,13 +37,14 @@ from src.agent_firewall import AgentFirewall
37
37
  from src.diff_slicer import DiffSlicer
38
38
  from src.guard import TokenSafeGuard
39
39
  from src.scoped_search import ScopedSearch
40
+ from src import route_index
40
41
  from src.license_manager import LicenseManager
41
42
  from src.paths import get_active_workspace, is_plugin_or_system_dir
42
43
  from src.session_context import current_root, current_session_id
43
44
 
44
45
  SERVER_INFO = {
45
46
  "name": "tokensafe-mcp",
46
- "version": "4.7.2"
47
+ "version": "4.7.4"
47
48
  }
48
49
 
49
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -674,10 +675,12 @@ _LEAN_TOOL_NAMES = frozenset({"smart_read_file", "scoped_search", "apply_edits",
674
675
  # previous literal: this schema is re-sent in every request of every session.
675
676
  TOOLS = [{'name': 'smart_read_file',
676
677
  '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.',
678
+ 'description': 'AST-skeleton reader. endpoint="POST /api/x" resolves route→handler body + path + lines + version in one call; '
679
+ 'path+symbol for one file; targets=[{path,symbol}] for 2-8 at once; package_name+symbol for .d.ts.',
679
680
  'inputSchema': {'type': 'object',
680
- 'properties': {'path': {'type': 'string', 'description': 'File path'},
681
+ 'properties': {'endpoint': {'type': 'string',
682
+ 'description': "'METHOD /path' repo route target"},
683
+ 'path': {'type': 'string', 'description': 'File path'},
681
684
  'symbol': {'type': 'string',
682
685
  'description': "Identifier, 'Type.Method', endpoint or schema "
683
686
  'model; a non-declaration returns the enclosing '
@@ -694,45 +697,24 @@ TOOLS = [{'name': 'smart_read_file',
694
697
  'symbol': {'type': 'string'}},
695
698
  'required': ['path']}},
696
699
  'package_name': {'type': 'string', 'description': '.d.ts npm package'}},
697
- 'required': ['path']}},
700
+ 'anyOf': [{'required': ['path']}, {'required': ['endpoint']}, {'required': ['package_name']}]}},
698
701
  {'name': 'scoped_search',
699
702
  'annotations': {'readOnlyHint': True},
700
- 'description': 'Bounded search replacing grep/find. Single query+scope, or '
701
- 'queries=[{pattern,type,path,glob}] for up to 20.',
703
+ 'description': 'Search replacing grep/find: query+scope, or queries=[{pattern,type,path,glob}] batch (max 20).',
702
704
  'inputSchema': {'type': 'object',
703
705
  'properties': {'query': {'type': 'string'},
704
706
  'mode': {'type': 'string',
705
- 'enum': ['auto', 'text', 'regex', 'glob', 'fuzzy', 'git']},
707
+ 'description': 'auto|text|regex|glob|fuzzy|git'},
706
708
  'scope': {'type': 'string',
707
- 'description': "'code','config','all', ext or subfolder"},
709
+ 'description': "code|config|all|ext|subfolder"},
708
710
  '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)'},
711
+ 'cwd': {'type': 'string'},
712
+ 'max_results': {'type': 'integer', 'description': 'default 25'},
713
+ 'per_file': {'type': 'integer'},
717
714
  'queries': {'type': 'array',
718
715
  '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']}}}}},
716
+ 'description': 'batch items: {pattern, type?, path?, glob?}',
717
+ 'items': {'type': 'object'}}}}},
736
718
  {'name': 'apply_edits',
737
719
  'annotations': {'readOnlyHint': False, 'destructiveHint': False},
738
720
  'description': 'Multi-hunk editor (up to 50 files) with optional inline verify: the edit and its verdict '
@@ -1298,6 +1280,36 @@ def _symbol_scope(graph: Any, rel_path: str, symbol: str, code: str) -> Dict[str
1298
1280
  return plan
1299
1281
 
1300
1282
 
1283
+ def _cross_file_declaration(plan: Dict[str, Any], from_path: str) -> Tuple[str, str]:
1284
+ """(header, body) for the one declaration that lives in another file.
1285
+
1286
+ A miss used to end with "call smart_read_file(path=..., symbol=...)" — which
1287
+ the measured runs did, or worse, replaced with a raw read of the whole file.
1288
+ When the declaration is small the answer fits in this response, so the
1289
+ follow-up call disappears.
1290
+ """
1291
+ elsewhere = plan.get("elsewhere")
1292
+ if not elsewhere:
1293
+ return "", ""
1294
+ rel, start, end, name = elsewhere
1295
+ if end < start or (end - start + 1) > _SYMBOL_MISS_FULL_DECL_LINES:
1296
+ return "", ""
1297
+ try:
1298
+ root = GraphEngine.find_project_root(from_path)
1299
+ full = os.path.join(root, rel)
1300
+ if os.path.getsize(full) > 2_000_000:
1301
+ return "", ""
1302
+ with open(full, "r", encoding="utf-8", errors="replace") as handle:
1303
+ lines = handle.read().splitlines()
1304
+ except (OSError, ValueError):
1305
+ return "", ""
1306
+ if start > len(lines):
1307
+ return "", ""
1308
+ version = route_index.file_version(full)
1309
+ header = f"// --- L{start}-L{end} ({rel}, {name}, ver={version})"
1310
+ return header, "\n".join(lines[start - 1:end])
1311
+
1312
+
1301
1313
  def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code: str) -> str:
1302
1314
  """Honest, actionable replacement for a skeleton that folded the requested symbol away."""
1303
1315
  base = os.path.basename(path)
@@ -1305,17 +1317,24 @@ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code
1305
1317
  probe = plan.get("probe")
1306
1318
  probe_note = f" (matched '{probe}')" if probe and probe != symbol else ""
1307
1319
  elsewhere = plan["elsewhere"]
1320
+ decl_header, decl_body = _cross_file_declaration(plan, path)
1308
1321
  pointer = ""
1309
- if elsewhere:
1322
+ if elsewhere and not decl_body:
1310
1323
  r, es, ee, _n = elsewhere
1311
1324
  pointer = (
1312
1325
  f"\n// ['{symbol}' is declared in {r} L{es}-L{ee} — call smart_read_file(path=\"{r}\", symbol=\"{symbol}\")"
1313
1326
  f" if you need that declaration instead]"
1314
1327
  )
1328
+ tail = f"\n{decl_header}\n{decl_body}" if decl_body else ""
1315
1329
 
1316
1330
  if plan["status"] == "absent":
1317
1331
  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}"
1332
+ head = f"// [TS: '{symbol}' does not occur in {base}"
1333
+ if decl_body:
1334
+ head += f"; declared in {elsewhere[0]} L{elsewhere[1]}-L{elsewhere[2]}, shown below]"
1335
+ else:
1336
+ head += f". Declarations here: {decl_txt}]"
1337
+ return f"{head}{pointer}{tail}"
1319
1338
 
1320
1339
  lines = code.splitlines()
1321
1340
  enclosing = plan["enclosing"]
@@ -1325,8 +1344,8 @@ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code
1325
1344
  name, start, end = enclosing
1326
1345
  windows = [(start, end)]
1327
1346
  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]"
1347
+ f"// [TS: '{symbol}' at {base} {hits}{probe_note} inside {name} L{start}-L{end}"
1348
+ f" — full declaration below]"
1330
1349
  )
1331
1350
  else:
1332
1351
  pad = _SYMBOL_MISS_WINDOW_PAD
@@ -1340,21 +1359,14 @@ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code
1340
1359
  else:
1341
1360
  merged.append((s, e))
1342
1361
  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
- )
1362
+ where = f"inside {enclosing[0]} L{enclosing[1]}-L{enclosing[2]}" if enclosing else "outside any declaration"
1363
+ head = (
1364
+ f"// [TS: '{symbol}' is not a declaration in {base}; hits {hits}{probe_note} {where}"
1365
+ f" — ±{pad} lines per hit]"
1366
+ )
1355
1367
 
1356
1368
  if not windows:
1357
- return f"{head}{pointer}"
1369
+ return f"{head}{pointer}{tail}"
1358
1370
 
1359
1371
  budget = _SYMBOL_MISS_MAX_LINES
1360
1372
  chunks: List[str] = []
@@ -1371,7 +1383,7 @@ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code
1371
1383
  if e < windows[i][1]:
1372
1384
  chunks.append("// [window truncated]")
1373
1385
 
1374
- return f"{head}{pointer}\n" + "\n".join(chunks)
1386
+ return f"{head}{pointer}\n" + "\n".join(chunks) + tail
1375
1387
 
1376
1388
 
1377
1389
  def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
@@ -1385,6 +1397,151 @@ def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
1385
1397
  return True, "signature"
1386
1398
 
1387
1399
 
1400
+ def _endpoint_symbol_index(graph: Any) -> Dict[str, List[Tuple[str, str, int, int]]]:
1401
+ """name -> [(file, qualified, start, end)] for resolving named route handlers."""
1402
+ index: Dict[str, List[Tuple[str, str, int, int]]] = {}
1403
+ for key, sym in getattr(graph, "symbols", {}).items():
1404
+ qualified = key.split("::", 1)[-1]
1405
+ index.setdefault(sym.name, []).append(
1406
+ (sym.file_path, qualified, sym.line_start, sym.line_end)
1407
+ )
1408
+ return index
1409
+
1410
+
1411
+ def _endpoint_callee_line(
1412
+ names: List[str], hit: Any, index: Dict[str, List[Tuple[str, str, int, int]]], limit: int = 2
1413
+ ) -> str:
1414
+ """`name -> path Ls-Le` for the handler's cross-file callees, capped.
1415
+
1416
+ This is the second half of the one-call promise: the route call says where
1417
+ the work continues, so the follow-up read is a direct path+symbol hit
1418
+ instead of another search. Callees in the handler's own top-level directory
1419
+ come first — a framework helper three trees away is not where the fix lives.
1420
+ """
1421
+ top = lambda file: file.split("/", 1)[0].lower()
1422
+ ranked: List[Tuple[int, str]] = []
1423
+ for name in names:
1424
+ entries = index.get(name) or []
1425
+ if len(entries) != 1:
1426
+ continue
1427
+ file, _qualified, start, end = entries[0]
1428
+ if file == hit.file:
1429
+ continue
1430
+ ranked.append((0 if top(file) == top(hit.file) else 1, f"{name} → {file} L{start}-L{end}"))
1431
+ ranked.sort()
1432
+ return "; ".join(entry for _rank, entry in ranked[:limit])
1433
+
1434
+
1435
+ def _render_endpoint_slice(
1436
+ endpoint: Any,
1437
+ prefer_path: str,
1438
+ tracker: Any,
1439
+ max_lines: int = 160,
1440
+ fallback_on_miss: bool = False,
1441
+ ) -> Optional[str]:
1442
+ """Route → handler body in one response: path, line range, whole-file version."""
1443
+ verb, route = endpoint
1444
+ root = os.path.abspath(_workspace_root() or os.getcwd())
1445
+ if prefer_path:
1446
+ # The caller named the file: its own project root is the honest scan root,
1447
+ # even when the MCP workspace points somewhere else.
1448
+ try:
1449
+ root = GraphEngine.find_project_root(prefer_path)
1450
+ except Exception:
1451
+ pass
1452
+ graph = None
1453
+ files: Optional[List[str]] = None
1454
+ try:
1455
+ graph = GraphEngine.get_instance(root)
1456
+ files = list(graph.file_stats.keys())
1457
+ except Exception:
1458
+ files = None
1459
+ prefer_rel = ""
1460
+ if prefer_path and files is not None:
1461
+ try:
1462
+ root_real = os.path.realpath(root)
1463
+ real = os.path.realpath(prefer_path)
1464
+ if real == root_real or real.startswith(root_real + os.sep):
1465
+ prefer_rel = os.path.relpath(real, root_real).replace("\\", "/")
1466
+ files = [prefer_rel] + [f for f in files if f != prefer_rel]
1467
+ except ValueError:
1468
+ prefer_rel = ""
1469
+ hits, scanned = route_index.find_registrations(root, verb, route, files=files)
1470
+ label = f"{verb} {route}".strip()
1471
+ if prefer_rel and hits:
1472
+ # The caller named a file: expand it first even though the repo answer is
1473
+ # sorted independently of the caller's context.
1474
+ hits.sort(key=lambda h: (h.file != prefer_rel, not h.exact, h.file, h.line))
1475
+ if not hits:
1476
+ if fallback_on_miss:
1477
+ return None
1478
+ others, _ = route_index.find_registrations(root, "", route, files=files, max_hits=3)
1479
+ if others:
1480
+ verbs = ", ".join(sorted({f"{h.verb} {h.route} L{h.line} in {h.file}" for h in others}))
1481
+ return (
1482
+ f"// [TS endpoint: no registration for '{label}' — the path exists as {verbs};"
1483
+ f" retry with one of those verbs]"
1484
+ )
1485
+ return (
1486
+ f"// [TS endpoint: no registration for '{label}' among {scanned} code files."
1487
+ f" Find the literal with scoped_search(query=\"{route}\") or pass the file path.]"
1488
+ )
1489
+ index = _endpoint_symbol_index(graph) if graph is not None else {}
1490
+ entries: List[str] = []
1491
+ total = 0
1492
+ for pos, hit in enumerate(hits, 1):
1493
+ full = os.path.join(root, hit.file)
1494
+ version = route_index.file_version(full)
1495
+ prefix = f"[{pos}] " if len(hits) > 1 else ""
1496
+ head = (
1497
+ f"// [TS endpoint {prefix}{verb} {route} → {hit.file} L{hit.line}-L{hit.end_line} "
1498
+ f"ver={version} via {hit.via}]"
1499
+ )
1500
+ body_lines, first, last = hit.body, hit.line, hit.end_line
1501
+ if hit.handler_kind == "named" and hit.handler:
1502
+ short = hit.handler.split(".")[-1]
1503
+ decls = [d for d in index.get(short, []) if d[0] != hit.file] or index.get(short, [])
1504
+ if decls:
1505
+ file, _qualified, start, end = decls[0]
1506
+ try:
1507
+ with open(os.path.join(root, file), "r", encoding="utf-8", errors="replace") as handle:
1508
+ src = handle.read().splitlines()
1509
+ body_lines, first, last = src[start - 1:end], start, end
1510
+ head = (
1511
+ f"// [TS endpoint {prefix}{verb} {route} → handler {short} in {file} "
1512
+ f"L{start}-L{end} ver={route_index.file_version(os.path.join(root, file))}]"
1513
+ )
1514
+ except OSError:
1515
+ pass
1516
+ if total + (last - first + 1) > max_lines:
1517
+ entries.append(f"// [... {len(hits) - pos + 1} more registration(s) suppressed; pass path= to pick one]")
1518
+ break
1519
+ total += last - first + 1
1520
+ entries.append(head)
1521
+ names = hit.callees() if hit.handler_kind == "inline" else route_index.extract_callees("\n".join(body_lines))
1522
+ callees = _endpoint_callee_line(names, hit, index)
1523
+ if callees:
1524
+ entries.append(f"// calls: {callees}")
1525
+ entries.append(f"// --- L{first}-L{last}")
1526
+ entries.extend(body_lines)
1527
+ delivered = "\n".join(entries) + "\n"
1528
+ if tracker is not None:
1529
+ try:
1530
+ orig_chars = 0
1531
+ for file in {h.file for h in hits}:
1532
+ orig_chars += os.path.getsize(os.path.join(root, file))
1533
+ tracker.record_event(
1534
+ session_id=_mcp_session_id(),
1535
+ event_type="ENDPOINT_SLICE",
1536
+ original_tokens=max(1, orig_chars // 4),
1537
+ optimized_tokens=count_tokens(delivered),
1538
+ details={"endpoint": label, "hits": len(hits), "scanned": scanned},
1539
+ )
1540
+ except Exception:
1541
+ pass
1542
+ return delivered
1543
+
1544
+
1388
1545
  def _repo_fingerprint(graph) -> str:
1389
1546
  """Stable Shared-Team-Symbol-Index cache key for an indexed repo: repo name +
1390
1547
  per-file relative paths + sizes. Machine-independent on purpose (mtimes differ
@@ -1615,6 +1772,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1615
1772
  if start_line is not None:
1616
1773
  start_line = max(1, start_line)
1617
1774
 
1775
+ # A route target ("POST /api/products") is resolved across the repo in one
1776
+ # call: registration site → handler body → path + line range + version.
1777
+ # Without this the caller spent two calls to find the file and a third to
1778
+ # read the handler (measured: 6.3 discovery calls per edit in matrix v4).
1779
+ endpoint_target = str(args.get("endpoint") or "").strip()
1780
+ if not endpoint_target:
1781
+ endpoint_target = str(symbol or "").strip()
1782
+ endpoint = route_index.parse_endpoint(endpoint_target) if endpoint_target else None
1783
+ if endpoint:
1784
+ rendered = _render_endpoint_slice(endpoint, path, tracker, fallback_on_miss=bool(path))
1785
+ if rendered is not None:
1786
+ return {"content": [{"type": "text", "text": rendered}]}
1787
+
1618
1788
  active_ws = _workspace_root()
1619
1789
  if path and not os.path.isabs(path):
1620
1790
  if active_ws and os.path.exists(os.path.join(active_ws, path)):