repodna-engine 1.0.1__py3-none-any.whl

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.
Files changed (173) hide show
  1. repodna/__init__.py +3 -0
  2. repodna/__main__.py +10 -0
  3. repodna/advisor/__init__.py +17 -0
  4. repodna/advisor/engine.py +502 -0
  5. repodna/advisor/models.py +101 -0
  6. repodna/agent/__init__.py +87 -0
  7. repodna/agent/context.py +558 -0
  8. repodna/agent/deltas.py +198 -0
  9. repodna/agent/evidence.py +134 -0
  10. repodna/agent/expansion.py +447 -0
  11. repodna/agent/localization.py +518 -0
  12. repodna/agent/models.py +695 -0
  13. repodna/agent/patch.py +378 -0
  14. repodna/agent/postflight.py +278 -0
  15. repodna/agent/preflight.py +336 -0
  16. repodna/agent/ranking.py +318 -0
  17. repodna/agent/repo_map.py +392 -0
  18. repodna/agent/safety.py +111 -0
  19. repodna/agent/service.py +574 -0
  20. repodna/agent/sessions.py +264 -0
  21. repodna/agent/task.py +660 -0
  22. repodna/agent/telemetry.py +101 -0
  23. repodna/agent/token_budget.py +231 -0
  24. repodna/api/__init__.py +1 -0
  25. repodna/api/agent_routes.py +248 -0
  26. repodna/api/app.py +2904 -0
  27. repodna/benchmarks/__init__.py +29 -0
  28. repodna/benchmarks/baselines.py +126 -0
  29. repodna/benchmarks/budget_bench.py +162 -0
  30. repodna/benchmarks/engine.py +418 -0
  31. repodna/benchmarks/evaluator.py +310 -0
  32. repodna/benchmarks/metrics.py +206 -0
  33. repodna/benchmarks/models.py +194 -0
  34. repodna/benchmarks/scalability.py +166 -0
  35. repodna/brain/__init__.py +46 -0
  36. repodna/brain/evidence.py +276 -0
  37. repodna/brain/extractor.py +1207 -0
  38. repodna/brain/indexer.py +766 -0
  39. repodna/brain/models.py +275 -0
  40. repodna/brain/multilang_extractors.py +889 -0
  41. repodna/brain/retrieval.py +469 -0
  42. repodna/brain/tracer.py +203 -0
  43. repodna/cli/__init__.py +1 -0
  44. repodna/cli/__main__.py +10 -0
  45. repodna/cli/agent_cmd.py +228 -0
  46. repodna/cli/installer.py +590 -0
  47. repodna/cli/main.py +2173 -0
  48. repodna/cli/plugin_cmd.py +130 -0
  49. repodna/cli/workspace_cmd.py +211 -0
  50. repodna/context/__init__.py +9 -0
  51. repodna/context/builder.py +379 -0
  52. repodna/context/models.py +133 -0
  53. repodna/contract/__init__.py +39 -0
  54. repodna/contract/evaluator.py +318 -0
  55. repodna/contract/loader.py +260 -0
  56. repodna/contract/models.py +185 -0
  57. repodna/core/__init__.py +1 -0
  58. repodna/core/analyzer.py +1424 -0
  59. repodna/diff/__init__.py +35 -0
  60. repodna/diff/engine.py +332 -0
  61. repodna/diff/models.py +117 -0
  62. repodna/diff/snapshot.py +248 -0
  63. repodna/ecosystem/__init__.py +27 -0
  64. repodna/ecosystem/contracts.py +129 -0
  65. repodna/ecosystem/doctor.py +253 -0
  66. repodna/git_insights/__init__.py +1 -0
  67. repodna/git_insights/analyzer.py +273 -0
  68. repodna/graph/__init__.py +1 -0
  69. repodna/graph/engine.py +562 -0
  70. repodna/guardian/__init__.py +17 -0
  71. repodna/guardian/engine.py +369 -0
  72. repodna/guardian/models.py +104 -0
  73. repodna/history/__init__.py +40 -0
  74. repodna/history/cache.py +240 -0
  75. repodna/history/diff.py +394 -0
  76. repodna/history/engine.py +557 -0
  77. repodna/history/evidence.py +160 -0
  78. repodna/history/models.py +258 -0
  79. repodna/history/timeline.py +164 -0
  80. repodna/intelligence/__init__.py +33 -0
  81. repodna/intelligence/models.py +165 -0
  82. repodna/intelligence/service.py +570 -0
  83. repodna/live/__init__.py +94 -0
  84. repodna/live/alerts.py +443 -0
  85. repodna/live/coordinator.py +351 -0
  86. repodna/live/diff.py +444 -0
  87. repodna/live/events.py +471 -0
  88. repodna/live/filtering.py +329 -0
  89. repodna/live/history.py +637 -0
  90. repodna/live/models.py +505 -0
  91. repodna/live/observer.py +653 -0
  92. repodna/live/reconciliation.py +253 -0
  93. repodna/live/session.py +1547 -0
  94. repodna/mcp/__init__.py +5 -0
  95. repodna/mcp/__main__.py +6 -0
  96. repodna/mcp/agent_tools.py +258 -0
  97. repodna/mcp/server.py +3283 -0
  98. repodna/mcp/workspace_tools.py +200 -0
  99. repodna/parsers/__init__.py +13 -0
  100. repodna/parsers/base.py +126 -0
  101. repodna/parsers/capabilities.py +361 -0
  102. repodna/parsers/project_metadata.py +232 -0
  103. repodna/parsers/resolver.py +621 -0
  104. repodna/parsers/treesitter_parser.py +830 -0
  105. repodna/passport/__init__.py +64 -0
  106. repodna/passport/generator.py +546 -0
  107. repodna/passport/migrator.py +139 -0
  108. repodna/passport/models.py +224 -0
  109. repodna/passport/validator.py +143 -0
  110. repodna/performance/__init__.py +89 -0
  111. repodna/performance/cache.py +1584 -0
  112. repodna/performance/identity.py +341 -0
  113. repodna/performance/incremental.py +317 -0
  114. repodna/performance/models.py +157 -0
  115. repodna/performance/parallel.py +291 -0
  116. repodna/plugins/__init__.py +47 -0
  117. repodna/plugins/evaluator.py +334 -0
  118. repodna/plugins/models.py +113 -0
  119. repodna/plugins/validator.py +256 -0
  120. repodna/quality/__init__.py +91 -0
  121. repodna/quality/complexity.py +352 -0
  122. repodna/quality/config.py +159 -0
  123. repodna/quality/debt.py +73 -0
  124. repodna/quality/duplicates.py +330 -0
  125. repodna/quality/engine.py +282 -0
  126. repodna/quality/impact.py +198 -0
  127. repodna/quality/models.py +427 -0
  128. repodna/quality/rules.py +364 -0
  129. repodna/quality/sarif.py +107 -0
  130. repodna/quality/security_signals.py +278 -0
  131. repodna/quality/test_mapping.py +271 -0
  132. repodna/quality/unused.py +201 -0
  133. repodna/reports/__init__.py +1 -0
  134. repodna/reports/exporter.py +374 -0
  135. repodna/rules/__init__.py +1 -0
  136. repodna/rules/health.py +436 -0
  137. repodna/schemas/__init__.py +1 -0
  138. repodna/schemas/models.py +348 -0
  139. repodna/security/__init__.py +1 -0
  140. repodna/security/safe_yaml.py +81 -0
  141. repodna/security/validators.py +583 -0
  142. repodna/skills/__init__.py +0 -0
  143. repodna/skills/repodna/SKILL.md +59 -0
  144. repodna/skills/repodna/__init__.py +0 -0
  145. repodna/skills/repodna/examples/workflows.md +85 -0
  146. repodna/skills/repodna/references/architecture-rules.md +26 -0
  147. repodna/storage/__init__.py +1 -0
  148. repodna/storage/workspace.py +199 -0
  149. repodna/webui/__init__.py +1 -0
  150. repodna/webui/assets/DependencyGraph-km_Qo-nG.js +43 -0
  151. repodna/webui/assets/HealthReportView-WVL39aNO.js +1 -0
  152. repodna/webui/assets/index-ByZ5e5pe.js +506 -0
  153. repodna/webui/assets/index-CDj3e8hw.css +1 -0
  154. repodna/webui/index.html +21 -0
  155. repodna/workspace/__init__.py +131 -0
  156. repodna/workspace/compatibility.py +317 -0
  157. repodna/workspace/context.py +175 -0
  158. repodna/workspace/contracts.py +369 -0
  159. repodna/workspace/federation.py +411 -0
  160. repodna/workspace/identity.py +202 -0
  161. repodna/workspace/impact.py +111 -0
  162. repodna/workspace/manifest.py +266 -0
  163. repodna/workspace/models.py +461 -0
  164. repodna/workspace/packages.py +494 -0
  165. repodna/workspace/policies.py +142 -0
  166. repodna/workspace/services.py +238 -0
  167. repodna/workspace/topology.py +316 -0
  168. repodna_engine-1.0.1.dist-info/METADATA +129 -0
  169. repodna_engine-1.0.1.dist-info/RECORD +173 -0
  170. repodna_engine-1.0.1.dist-info/WHEEL +5 -0
  171. repodna_engine-1.0.1.dist-info/entry_points.txt +2 -0
  172. repodna_engine-1.0.1.dist-info/licenses/LICENSE +21 -0
  173. repodna_engine-1.0.1.dist-info/top_level.txt +1 -0
repodna/mcp/server.py ADDED
@@ -0,0 +1,3283 @@
1
+ """Official Model Context Protocol (MCP) server for RepoDNA repository intelligence.
2
+
3
+ Supports the 2024-11-05/2026 standard via the official Python SDK v2 (mcp>=2.0.0),
4
+ providing stdio transport, strict stdout cleanliness, and read-only tools.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ import sys
15
+ import time
16
+ from datetime import UTC, datetime
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from repodna import __version__
21
+ from repodna.advisor.engine import RefactoringAdvisorEngine
22
+ from repodna.advisor.models import AdvisorCategory
23
+ from repodna.agent.models import (
24
+ MAX_RESPONSE_BYTES,
25
+ ChangeIntent,
26
+ ChangeOperationType,
27
+ ContextDeltaRequest,
28
+ ContextExpansionRequest,
29
+ ExpansionTargetType,
30
+ RepositoryMapMode,
31
+ )
32
+ from repodna.agent.service import AgentIntelligenceService
33
+ from repodna.brain.evidence import extract_evidence_snippet
34
+ from repodna.brain.indexer import SymbolIndexer
35
+ from repodna.brain.retrieval import SmartRetrievalEngine
36
+ from repodna.brain.tracer import AmbiguousSymbolError, SymbolTracer
37
+ from repodna.context.builder import AgentContextBuilder
38
+ from repodna.contract.evaluator import ContractEvaluator
39
+ from repodna.contract.loader import find_contract_file, load_contract_file
40
+ from repodna.contract.models import ContractMode
41
+ from repodna.core.analyzer import run_repository_analysis
42
+ from repodna.diff.engine import ArchitectureDiffEngine
43
+ from repodna.diff.snapshot import SnapshotManager
44
+ from repodna.guardian.engine import PRArchitectureGuardian
45
+ from repodna.history.diff import EvolutionDiffEngine
46
+ from repodna.history.engine import HistoricalSnapshotEngine
47
+ from repodna.history.evidence import HistoricalEvidenceProvider
48
+ from repodna.history.timeline import TimelineEngine
49
+ from repodna.intelligence.service import RepositoryIntelligenceService
50
+ from repodna.live import (
51
+ LiveStatePersistence,
52
+ get_live_session_manager,
53
+ summarize_live_state_for_mcp,
54
+ )
55
+ from repodna.mcp.agent_tools import (
56
+ PROFILE_ALLOWLISTS,
57
+ VALID_TOOL_PROFILES,
58
+ filter_tools_by_profile,
59
+ get_agent_mcp_tool_schemas,
60
+ )
61
+ from repodna.mcp.workspace_tools import (
62
+ WORKSPACE_MCP_TOOL_NAMES,
63
+ dispatch_workspace_tool,
64
+ get_workspace_tool_schemas,
65
+ )
66
+ from repodna.passport.generator import (
67
+ export_passport_to_json,
68
+ export_passport_to_markdown,
69
+ generate_repository_passport,
70
+ generate_repository_passport_v2,
71
+ )
72
+ from repodna.passport.models import RepositoryPassport, RepositoryPassportV2
73
+ from repodna.performance.identity import compute_repo_identity
74
+ from repodna.quality import (
75
+ FindingStatus,
76
+ QualityIntelligenceEngine,
77
+ QualityReport,
78
+ compute_symbol_impact,
79
+ )
80
+ from repodna.schemas.models import AnalysisResult, ScanLimits, ScanRequest, SourceType
81
+ from repodna.security.validators import (
82
+ SecurityValidationError,
83
+ safe_read_evidence_file,
84
+ validate_and_resolve_evidence_path,
85
+ validate_local_directory,
86
+ )
87
+
88
+ try:
89
+ from mcp.server.mcpserver import MCPServer
90
+
91
+ HAS_OFFICIAL_MCP = True
92
+ except ImportError:
93
+ HAS_OFFICIAL_MCP = False
94
+ MCPServer = None # type: ignore
95
+
96
+ try:
97
+ import importlib.metadata
98
+
99
+ MCP_SDK_VERSION = importlib.metadata.version("mcp")
100
+ except Exception:
101
+ MCP_SDK_VERSION = "unknown"
102
+
103
+ PROTOCOL_VERSION = "2024-11-05"
104
+ SERVER_NAME = "repodna-mcp"
105
+ SERVER_VERSION = __version__
106
+
107
+ RELEVANT_EXTENSIONS = {
108
+ ".py",
109
+ ".ts",
110
+ ".tsx",
111
+ ".js",
112
+ ".jsx",
113
+ ".mjs",
114
+ ".cjs",
115
+ ".go",
116
+ ".rs",
117
+ ".cs",
118
+ ".java",
119
+ ".c",
120
+ ".cpp",
121
+ ".cc",
122
+ ".cxx",
123
+ ".h",
124
+ ".hpp",
125
+ ".json",
126
+ ".toml",
127
+ ".yaml",
128
+ ".yml",
129
+ ".md",
130
+ ".csproj",
131
+ ".sln",
132
+ }
133
+
134
+ IGNORED_SCAN_DIRS = {
135
+ ".git",
136
+ "node_modules",
137
+ ".venv",
138
+ "venv",
139
+ "dist",
140
+ "build",
141
+ "__pycache__",
142
+ ".pytest_cache",
143
+ ".mypy_cache",
144
+ ".ruff_cache",
145
+ ".next",
146
+ ".nuxt",
147
+ "bin",
148
+ "obj",
149
+ }
150
+
151
+
152
+ def _log(msg: str) -> None:
153
+ """Logs diagnostics strictly to stderr to prevent stdout JSON-RPC corruption."""
154
+ sys.stderr.write(f"[repodna-mcp] {msg}\n")
155
+ sys.stderr.flush()
156
+
157
+
158
+ class RepoDNAMCPServer:
159
+ """Dual-engine Model Context Protocol server (Official SDK v2 + Stdio fallback)."""
160
+
161
+ def __init__(
162
+ self,
163
+ allowed_roots: list[Path] | None = None,
164
+ tool_profile: str | None = None,
165
+ ) -> None:
166
+ raw_profile = (tool_profile or os.environ.get("REPODNA_MCP_TOOL_PROFILE", "full")).strip().lower()
167
+ self.tool_profile: str = raw_profile if raw_profile in VALID_TOOL_PROFILES else "full"
168
+ configured_roots: list[Path] = []
169
+ if allowed_roots:
170
+ configured_roots = [p.resolve() for p in allowed_roots if p]
171
+ else:
172
+ env_val = os.environ.get("REPODNA_ALLOWED_ROOTS", "").strip()
173
+ if env_val:
174
+ raw_parts = (
175
+ re.split(r"(?<![a-zA-Z]):|;", env_val)
176
+ if sys.platform == "win32"
177
+ else env_val.split(":")
178
+ )
179
+ for part in raw_parts:
180
+ p_str = part.strip()
181
+ if p_str:
182
+ p = Path(p_str).resolve()
183
+ if p.exists() and p.is_dir():
184
+ configured_roots.append(p)
185
+
186
+ if not configured_roots:
187
+ cwd = Path.cwd().resolve()
188
+ # If current directory is user home or drive root, do not default to it (require explicit root)
189
+ if cwd == Path.home().resolve() or cwd == cwd.parent:
190
+ _log(
191
+ f"Warning: Current working directory '{cwd}' is a system root or user home. Requiring explicit authorized root."
192
+ )
193
+ configured_roots = []
194
+ else:
195
+ configured_roots = [cwd]
196
+
197
+ self.allowed_roots: list[Path] = configured_roots
198
+ _log("Access Policy: RESTRICTED LOCAL-FIRST READ-ONLY")
199
+ _log(f"Configured authorized workspace roots: {[str(r) for r in self.allowed_roots]}")
200
+
201
+ # Analysis cache: (cache_type, repo_str, git_rev) -> (fingerprint, time_iso, dur_ms, AnalysisResult)
202
+ self._analysis_cache: dict[
203
+ tuple[str, str, str], tuple[str, str, float, AnalysisResult]
204
+ ] = {}
205
+ self._indexer_cache: dict[tuple[str, str], SymbolIndexer] = {}
206
+ # Per-repo file stat cache for fast incremental hashing: {repo_str: {norm_rel: (size, mtime_ns, hash)}}
207
+ self._file_stat_cache: dict[str, dict[str, tuple[int, int, str]]] = {}
208
+ self._last_cache_report: dict[str, Any] = {}
209
+ self._agent_baseline_snapshots: dict[str, tuple[str, AnalysisResult, SymbolIndexer]] = {}
210
+
211
+ self._official_server: Any = None
212
+ if HAS_OFFICIAL_MCP and MCPServer is not None:
213
+ self._setup_official_server()
214
+
215
+ def _resolve_target(self, target: str) -> tuple[Path | str, SourceType]:
216
+ cleaned = target.strip()
217
+ if cleaned.lower() == "demo":
218
+ return "demo", SourceType.DEMO
219
+
220
+ if not self.allowed_roots:
221
+ raise SecurityValidationError(
222
+ "ROOT_VIOLATION",
223
+ "No authorized workspace roots configured. Please pass --allowed-root <path> or set REPODNA_ALLOWED_ROOTS.",
224
+ )
225
+
226
+ if cleaned in ("", ".", "./", ".\\"):
227
+ resolved = self.allowed_roots[0]
228
+ else:
229
+ target_path = Path(cleaned)
230
+ if not target_path.is_absolute():
231
+ resolved = (self.allowed_roots[0] / target_path).resolve()
232
+ else:
233
+ resolved = target_path.resolve()
234
+
235
+ validate_local_directory(str(resolved))
236
+
237
+ # Strict boundary enforcement
238
+ is_allowed = False
239
+ for root in self.allowed_roots:
240
+ try:
241
+ if resolved == root or resolved.is_relative_to(root):
242
+ is_allowed = True
243
+ break
244
+ except (ValueError, TypeError):
245
+ continue
246
+
247
+ if not is_allowed:
248
+ roots_str = ", ".join(f"'{r}'" for r in self.allowed_roots)
249
+ raise SecurityValidationError(
250
+ "ROOT_VIOLATION",
251
+ f"Access denied: path '{resolved}' is outside authorized workspace roots ({roots_str}). "
252
+ "Use --allowed-root or set REPODNA_ALLOWED_ROOTS to authorize additional locations.",
253
+ )
254
+
255
+ return resolved, SourceType.LOCAL
256
+
257
+ def _compute_fingerprint(self, repo_path: Path, force: bool = False) -> tuple[str, str]:
258
+ """
259
+ Fast composite fingerprinting of repository files and Git state.
260
+ Uses direct content hashing for repositories with <= 300 files (100% guarantee against
261
+ mtime forgery), and incremental stat caching for larger repositories with optional force refresh.
262
+ Returns: (fingerprint_hex, git_revision_or_head)
263
+ """
264
+ repo_str = str(repo_path)
265
+ if repo_str not in self._file_stat_cache:
266
+ self._file_stat_cache[repo_str] = {}
267
+ cached_files = self._file_stat_cache[repo_str]
268
+
269
+ # 1. Git metadata
270
+ git_dir = repo_path / ".git"
271
+ git_metadata = "no_git"
272
+ git_rev = "working_tree"
273
+ if git_dir.exists():
274
+ head_file = git_dir / "HEAD"
275
+ index_file = git_dir / "index"
276
+ head_content = ""
277
+ head_mtime = 0
278
+ index_stat = "0_0"
279
+ if head_file.exists():
280
+ try:
281
+ head_content = head_file.read_text(encoding="utf-8", errors="replace").strip()
282
+ head_mtime = head_file.stat().st_mtime_ns
283
+ except OSError:
284
+ pass
285
+ if index_file.exists():
286
+ try:
287
+ st = index_file.stat()
288
+ index_stat = f"{st.st_size}_{st.st_mtime_ns}"
289
+ except OSError:
290
+ pass
291
+ git_metadata = f"{head_content}|{head_mtime}|{index_stat}"
292
+ git_rev = (
293
+ head_content.split("/")[-1] if "/" in head_content else (head_content[:8] or "HEAD")
294
+ )
295
+
296
+ # 2. Collect relevant source and config files (including .repodna/* and .gitignore; skip symlinks)
297
+ file_entries: list[tuple[str, int, int]] = []
298
+ for root, dirs, files in os.walk(repo_path):
299
+ dirs[:] = [
300
+ d
301
+ for d in dirs
302
+ if d not in IGNORED_SCAN_DIRS and (not d.startswith(".") or d == ".repodna")
303
+ ]
304
+ rel_root = os.path.relpath(root, repo_path)
305
+ for f in files:
306
+ ext = os.path.splitext(f)[1].lower()
307
+ if ext in RELEVANT_EXTENSIONS or f in (
308
+ "pyproject.toml",
309
+ "package.json",
310
+ "Cargo.toml",
311
+ "go.mod",
312
+ ".gitignore",
313
+ ):
314
+ rel_path = f if rel_root == "." else os.path.join(rel_root, f)
315
+ norm_rel = rel_path.replace("\\", "/")
316
+ full_path = os.path.join(root, f)
317
+ if os.path.islink(full_path):
318
+ continue
319
+ try:
320
+ st = os.stat(full_path)
321
+ if st.st_size > 5 * 1024 * 1024:
322
+ continue
323
+ file_entries.append((norm_rel, st.st_size, st.st_mtime_ns))
324
+ except OSError:
325
+ continue
326
+
327
+ file_entries.sort(key=lambda x: x[0])
328
+ current_rel_paths = {entry[0] for entry in file_entries}
329
+
330
+ # Evict deleted files from cache
331
+ for stale in list(cached_files.keys()):
332
+ if stale not in current_rel_paths:
333
+ del cached_files[stale]
334
+
335
+ # 3. Content-verified hash (never trust stat mtime/size alone for same-size/same-mtime edits)
336
+ hasher = hashlib.blake2b(digest_size=16)
337
+ hasher.update(git_metadata.encode("utf-8"))
338
+
339
+ for norm_rel, size, mtime_ns in file_entries:
340
+ target_file = repo_path / norm_rel
341
+ try:
342
+ content_bytes = target_file.read_bytes()
343
+ file_hash = hashlib.blake2b(content_bytes, digest_size=16).hexdigest()
344
+ cached_files[norm_rel] = (size, mtime_ns, file_hash)
345
+ except OSError:
346
+ file_hash = f"err_{size}_{mtime_ns}"
347
+
348
+ hasher.update(f"{norm_rel}:{file_hash}\n".encode())
349
+
350
+ return hasher.hexdigest(), git_rev
351
+
352
+ def get_analysis(self, target: str, force: bool = False) -> AnalysisResult:
353
+ resolved, stype = self._resolve_target(target)
354
+ if stype == SourceType.DEMO:
355
+ req = ScanRequest(
356
+ source_type=SourceType.DEMO,
357
+ target="demo",
358
+ limits=ScanLimits(max_files=2500, timeout_seconds=60.0),
359
+ )
360
+ return run_repository_analysis(req)
361
+
362
+ assert isinstance(resolved, Path)
363
+ repo_str = str(resolved)
364
+ fingerprint, git_rev = self._compute_fingerprint(resolved, force=force)
365
+ cache_key = ("worktree", repo_str, git_rev)
366
+
367
+ t0 = time.perf_counter()
368
+ if not force and cache_key in self._analysis_cache:
369
+ cached_fp, cached_time_iso, cached_dur, cached_res = self._analysis_cache[cache_key]
370
+ if cached_fp == fingerprint:
371
+ duration_ms = (time.perf_counter() - t0) * 1000.0
372
+ perf_cached = getattr(cached_res, "performance", None)
373
+ self._last_cache_report = {
374
+ "target": repo_str,
375
+ "cache_hit": True,
376
+ "freshness_status": "fresh_memory_cache",
377
+ "analysis_time_iso": cached_time_iso,
378
+ "revision": git_rev,
379
+ "fingerprint": fingerprint[:16],
380
+ "snapshot_identity": perf_cached.snapshot_identity if perf_cached else None,
381
+ "analysis_mode_executed": "warm_snapshot",
382
+ "cache_status": "hit",
383
+ "reused_files": cached_res.total_files,
384
+ "reparsed_files": 0,
385
+ "duration_ms": round(duration_ms, 2),
386
+ }
387
+ return cached_res
388
+
389
+ # Cache miss / stale in memory: invoke performance engine (persistent SQLite cache + incremental)
390
+ req = ScanRequest(
391
+ source_type=stype,
392
+ target=repo_str,
393
+ limits=ScanLimits(max_files=2500, timeout_seconds=60.0),
394
+ analysis_mode="full" if force else "auto",
395
+ use_cache=not force,
396
+ )
397
+ res = run_repository_analysis(req)
398
+ duration_ms = (time.perf_counter() - t0) * 1000.0
399
+ analysis_time_iso = datetime.now(UTC).isoformat()
400
+ perf = getattr(res, "performance", None)
401
+ disk_hit = perf is not None and perf.analysis_mode_executed == "warm_snapshot"
402
+ self._analysis_cache[cache_key] = (fingerprint, analysis_time_iso, duration_ms, res)
403
+ self._last_cache_report = {
404
+ "target": repo_str,
405
+ "cache_hit": False,
406
+ "persistent_cache_hit": bool(disk_hit),
407
+ "freshness_status": (
408
+ "fresh_persistent_cache"
409
+ if disk_hit
410
+ else ("fresh_incremental" if (perf and perf.analysis_mode_executed == "incremental") else "fresh_full")
411
+ ),
412
+ "analysis_time_iso": analysis_time_iso,
413
+ "revision": git_rev,
414
+ "fingerprint": fingerprint[:16],
415
+ "snapshot_identity": perf.snapshot_identity if perf else None,
416
+ "analysis_mode_executed": perf.analysis_mode_executed if perf else "full",
417
+ "cache_status": perf.cache_status if perf else "miss",
418
+ "reused_files": perf.reused_files if perf else 0,
419
+ "reparsed_files": perf.reparsed_files if perf else res.total_files,
420
+ "duration_ms": round(duration_ms, 2),
421
+ }
422
+ return res
423
+
424
+ def get_last_cache_report(self) -> dict[str, Any]:
425
+ """Returns the cache report from the most recent get_analysis query."""
426
+ return dict(self._last_cache_report)
427
+
428
+ def tool_repository_overview(
429
+ self, target: str, format: str = "text", force: bool = False
430
+ ) -> str:
431
+ analysis = self.get_analysis(target, force=force)
432
+ svc = RepositoryIntelligenceService(analysis)
433
+ ov = svc.get_repository_overview()
434
+ if format == "json":
435
+ payload = ov.model_dump(mode="json")
436
+ payload["snapshot_freshness"] = self.get_last_cache_report()
437
+ return json.dumps(payload, indent=2)
438
+ report = self.get_last_cache_report()
439
+ if report:
440
+ fresh_line = (
441
+ f"Snapshot: {report.get('snapshot_identity') or report.get('revision', 'unknown')} "
442
+ f"| Mode: {report.get('analysis_mode_executed', 'full')} "
443
+ f"| Cache: {report.get('cache_status', 'miss')} "
444
+ f"({report.get('reused_files', 0)} reused / {report.get('reparsed_files', 0)} reparsed)"
445
+ )
446
+ return f"{ov.summary_text}\n{fresh_line}"
447
+ return ov.summary_text
448
+
449
+ def tool_architecture_map(
450
+ self, target: str, level: str = "clusters", limit: int = 30, force: bool = False
451
+ ) -> str:
452
+ analysis = self.get_analysis(target, force=force)
453
+ svc = RepositoryIntelligenceService(analysis)
454
+ am = svc.get_architecture_map(level=level, limit=limit)
455
+ return am.model_dump_json(indent=2)
456
+
457
+ def tool_find_modules(
458
+ self, target: str, query: str, limit: int = 10, force: bool = False
459
+ ) -> str:
460
+ analysis = self.get_analysis(target, force=force)
461
+ svc = RepositoryIntelligenceService(analysis)
462
+ res = svc.find_relevant_modules(query=query, limit=limit)
463
+ return res.model_dump_json(indent=2)
464
+
465
+ def tool_module_dependencies(
466
+ self,
467
+ target: str,
468
+ file_path: str,
469
+ direction: str = "outgoing",
470
+ depth: int = 1,
471
+ force: bool = False,
472
+ ) -> str:
473
+ analysis = self.get_analysis(target, force=force)
474
+ svc = RepositoryIntelligenceService(analysis)
475
+ deps = svc.get_dependencies(file_path=file_path, direction=direction, depth=depth)
476
+ return deps.model_dump_json(indent=2)
477
+
478
+ def tool_module_findings(
479
+ self,
480
+ target: str,
481
+ file_path: str | None = None,
482
+ rule_id: str | None = None,
483
+ severity: str | None = None,
484
+ force: bool = False,
485
+ ) -> str:
486
+ analysis = self.get_analysis(target, force=force)
487
+ svc = RepositoryIntelligenceService(analysis)
488
+ if file_path:
489
+ dtls = svc.get_module_details(file_path)
490
+ return dtls.model_dump_json(indent=2)
491
+ findings = svc.get_architecture_findings(rule_id=rule_id, severity=severity)
492
+ return findings.model_dump_json(indent=2)
493
+
494
+ def tool_architecture_diff(
495
+ self, target: str, base_ref: str = "HEAD~1", head_ref: str = "HEAD"
496
+ ) -> str:
497
+ resolved, _ = self._resolve_target(target)
498
+ snap_mgr = SnapshotManager(resolved)
499
+ base_analysis, base_sha, base_is_wt = snap_mgr.create_snapshot(base_ref)
500
+ head_analysis, head_sha, head_is_wt = snap_mgr.create_snapshot(head_ref)
501
+ git_renames = snap_mgr.find_git_renames(base_ref, head_ref)
502
+ engine = ArchitectureDiffEngine()
503
+ diff_res = engine.compare_analyses(
504
+ base=base_analysis,
505
+ head=head_analysis,
506
+ base_ref=base_ref,
507
+ head_ref=head_ref,
508
+ base_commit_sha=base_sha,
509
+ head_commit_sha=head_sha,
510
+ base_is_working_tree=base_is_wt,
511
+ head_is_working_tree=head_is_wt,
512
+ git_renames=git_renames,
513
+ )
514
+ return diff_res.model_dump_json(indent=2)
515
+
516
+ def tool_change_impact(
517
+ self, target: str, changed_files: list[str], max_depth: int = 2, force: bool = False
518
+ ) -> str:
519
+ analysis = self.get_analysis(target, force=force)
520
+ svc = RepositoryIntelligenceService(analysis)
521
+ impact = svc.get_change_impact(changed_files=changed_files, max_depth=max_depth)
522
+ return impact.model_dump_json(indent=2)
523
+
524
+ def tool_analysis_coverage(self, target: str, force: bool = False) -> str:
525
+ analysis = self.get_analysis(target, force=force)
526
+ svc = RepositoryIntelligenceService(analysis)
527
+ cov = svc.get_analysis_coverage()
528
+ report = cov.model_dump()
529
+ report["cache_status"] = self.get_last_cache_report()
530
+ return json.dumps(report, indent=2)
531
+
532
+ def tool_get_passport(
533
+ self,
534
+ target: str,
535
+ max_modules: int = 150,
536
+ format: str = "json",
537
+ version: str = "2.0",
538
+ force: bool = False,
539
+ ) -> str:
540
+ resolved, stype = self._resolve_target(target)
541
+ analysis = self.get_analysis(target, force=force)
542
+ contract = None
543
+ git_rev = "HEAD"
544
+ if stype == SourceType.LOCAL and isinstance(resolved, Path):
545
+ c_file = find_contract_file(resolved)
546
+ if c_file:
547
+ try:
548
+ contract = load_contract_file(c_file)
549
+ except Exception as exc:
550
+ _log(f"Warning: Failed to load contract '{c_file}': {exc}")
551
+ try:
552
+ snap_mgr = SnapshotManager(resolved)
553
+ git_rev, _, _ = snap_mgr.resolve_commit_metadata("HEAD")
554
+ except Exception:
555
+ git_rev = "working_tree"
556
+
557
+ passport: RepositoryPassport | RepositoryPassportV2
558
+ if version == "1.0":
559
+ passport = generate_repository_passport(
560
+ analysis=analysis,
561
+ git_revision=git_rev,
562
+ contract=contract,
563
+ max_modules=max_modules,
564
+ )
565
+ else:
566
+ indexer = self._get_or_create_indexer(resolved, analysis)
567
+ passport = generate_repository_passport_v2(
568
+ analysis=analysis,
569
+ git_revision=git_rev,
570
+ contract=contract,
571
+ max_modules=max_modules,
572
+ indexer=indexer,
573
+ )
574
+ if format.lower() == "markdown":
575
+ return export_passport_to_markdown(passport)
576
+ return export_passport_to_json(passport)
577
+
578
+ def tool_get_contract(self, target: str, format: str = "yaml") -> str:
579
+ resolved, stype = self._resolve_target(target)
580
+ if stype != SourceType.LOCAL or not isinstance(resolved, Path):
581
+ return json.dumps(
582
+ {
583
+ "has_contract": False,
584
+ "message": "Contracts are only supported for local repositories.",
585
+ }
586
+ )
587
+ c_file = find_contract_file(resolved)
588
+ if not c_file:
589
+ return json.dumps(
590
+ {
591
+ "has_contract": False,
592
+ "message": "No .repodna/architecture.yml found in repository.",
593
+ }
594
+ )
595
+ from repodna.contract.loader import MAX_CONTRACT_SIZE_BYTES
596
+ from repodna.security.validators import safe_read_evidence_file
597
+
598
+ rel_contract = c_file.resolve().relative_to(resolved.resolve()).as_posix()
599
+ content, _, file_exists = safe_read_evidence_file(resolved, rel_contract, max_file_bytes=MAX_CONTRACT_SIZE_BYTES)
600
+ if not file_exists:
601
+ return json.dumps(
602
+ {
603
+ "has_contract": False,
604
+ "message": "No .repodna/architecture.yml found in repository.",
605
+ }
606
+ )
607
+ if format.lower() == "json":
608
+ contract = load_contract_file(c_file, repo_root=resolved)
609
+ return contract.model_dump_json(indent=2)
610
+ return content
611
+
612
+ def tool_check_contract(
613
+ self,
614
+ target: str,
615
+ mode: str | None = None,
616
+ force: bool = False,
617
+ ) -> str:
618
+ resolved, stype = self._resolve_target(target)
619
+ if stype != SourceType.LOCAL or not isinstance(resolved, Path):
620
+ return json.dumps({"error": "Contract checks require a local repository."})
621
+ c_file = find_contract_file(resolved)
622
+ if not c_file:
623
+ return json.dumps(
624
+ {
625
+ "has_contract": False,
626
+ "message": "No .repodna/architecture.yml found in repository. Run 'repodna contract init' to create one.",
627
+ }
628
+ )
629
+ contract = load_contract_file(c_file)
630
+ analysis = self.get_analysis(target, force=force)
631
+ mode_override = ContractMode(mode) if mode else None
632
+ evaluator = ContractEvaluator(contract=contract, mode_override=mode_override)
633
+ report = evaluator.evaluate(analysis)
634
+ return report.model_dump_json(indent=2)
635
+
636
+ def tool_pr_guardian(
637
+ self,
638
+ target: str,
639
+ base_ref: str = "HEAD~1",
640
+ head_ref: str = "HEAD",
641
+ mode: str | None = None,
642
+ format: str = "json",
643
+ ) -> str:
644
+ resolved, stype = self._resolve_target(target)
645
+ if stype != SourceType.LOCAL or not isinstance(resolved, Path):
646
+ return json.dumps({"error": "PR Guardian requires a local Git repository."})
647
+ snap_mgr = SnapshotManager(resolved)
648
+ base_analysis, base_sha, base_is_wt = snap_mgr.create_snapshot(base_ref)
649
+ head_analysis, head_sha, head_is_wt = snap_mgr.create_snapshot(head_ref)
650
+ git_renames = snap_mgr.find_git_renames(base_ref, head_ref)
651
+
652
+ contract = None
653
+ c_file = find_contract_file(resolved)
654
+ if c_file:
655
+ try:
656
+ contract = load_contract_file(c_file)
657
+ except Exception as exc:
658
+ _log(f"Warning: could not load contract '{c_file}': {exc}")
659
+
660
+ mode_override = ContractMode(mode) if mode else None
661
+ guardian = PRArchitectureGuardian(contract=contract, mode_override=mode_override)
662
+ report = guardian.assess(
663
+ base_analysis=base_analysis,
664
+ head_analysis=head_analysis,
665
+ base_ref=base_ref,
666
+ head_ref=head_ref,
667
+ base_commit_sha=base_sha,
668
+ head_commit_sha=head_sha,
669
+ base_is_working_tree=base_is_wt,
670
+ head_is_working_tree=head_is_wt,
671
+ git_renames=git_renames,
672
+ )
673
+ if format.lower() == "markdown":
674
+ return report.summary_markdown
675
+ return report.model_dump_json(indent=2)
676
+
677
+ def _get_or_create_indexer(
678
+ self, resolved: Path | str, analysis: AnalysisResult
679
+ ) -> SymbolIndexer:
680
+ repo_str = str(resolved)
681
+ cache_key = (repo_str, analysis.analyzed_at.isoformat())
682
+ if cache_key in self._indexer_cache:
683
+ return self._indexer_cache[cache_key]
684
+ indexer = SymbolIndexer(root_path=resolved, revision="HEAD", analysis=analysis)
685
+ indexer.index_all()
686
+ self._indexer_cache[cache_key] = indexer
687
+ return indexer
688
+
689
+ def tool_search_code(
690
+ self,
691
+ target: str,
692
+ query: str,
693
+ limit: int = 10,
694
+ kind: str | None = None,
695
+ path_filter: str | None = None,
696
+ force: bool = False,
697
+ ) -> str:
698
+ resolved, _ = self._resolve_target(target)
699
+ analysis = self.get_analysis(target, force=force)
700
+ indexer = self._get_or_create_indexer(resolved, analysis)
701
+ retrieval = SmartRetrievalEngine(indexer=indexer, analysis=analysis)
702
+ res = retrieval.search(query=query, limit=limit, kind=kind, path_filter=path_filter)
703
+ return res.model_dump_json(indent=2)
704
+
705
+ def tool_find_symbol(
706
+ self,
707
+ target: str,
708
+ name: str | None = None,
709
+ kind: str | None = None,
710
+ file_path: str | None = None,
711
+ container: str | None = None,
712
+ limit: int = 25,
713
+ force: bool = False,
714
+ ) -> str:
715
+ resolved, _ = self._resolve_target(target)
716
+ analysis = self.get_analysis(target, force=force)
717
+ indexer = self._get_or_create_indexer(resolved, analysis)
718
+ if name:
719
+ syms = indexer.find_by_name(name=name, kind=kind, file_path=file_path, exact=False)
720
+ return json.dumps([s.model_dump() for s in syms[:limit]], indent=2)
721
+ resp = indexer.list_symbols(
722
+ kind=kind, file_path=file_path, container=container, limit=limit
723
+ )
724
+ return resp.model_dump_json(indent=2)
725
+
726
+ def tool_trace_symbol(
727
+ self,
728
+ target: str,
729
+ symbol_name: str | None = None,
730
+ symbol_id: str | None = None,
731
+ file_path: str | None = None,
732
+ container_name: str | None = None,
733
+ force: bool = False,
734
+ ) -> str:
735
+ resolved, _ = self._resolve_target(target)
736
+ analysis = self.get_analysis(target, force=force)
737
+ indexer = self._get_or_create_indexer(resolved, analysis)
738
+ tracer = SymbolTracer(indexer=indexer, analysis=analysis)
739
+ try:
740
+ res = tracer.trace_symbol(
741
+ symbol_name=symbol_name,
742
+ symbol_id=symbol_id,
743
+ file_path=file_path,
744
+ container_name=container_name,
745
+ allow_ambiguous=False,
746
+ )
747
+ return res.model_dump_json(indent=2)
748
+ except AmbiguousSymbolError as amb:
749
+ return json.dumps(
750
+ {
751
+ "error": "AMBIGUOUS_SYMBOL",
752
+ "message": str(amb),
753
+ "candidates": [c.model_dump() for c in amb.candidates],
754
+ },
755
+ indent=2,
756
+ )
757
+
758
+ def tool_get_evidence(
759
+ self,
760
+ target: str,
761
+ evidence_id: str | None = None,
762
+ file_path: str | None = None,
763
+ symbol_name: str | None = None,
764
+ check_staleness: bool = True,
765
+ limit: int = 25,
766
+ force: bool = False,
767
+ ) -> str:
768
+ resolved, _ = self._resolve_target(target)
769
+ analysis = self.get_analysis(target, force=force)
770
+ indexer = self._get_or_create_indexer(resolved, analysis)
771
+ ledger = indexer.ledger
772
+ if evidence_id:
773
+ ev = ledger.get_by_id(evidence_id)
774
+ if not ev:
775
+ return json.dumps({"error": f"Evidence '{evidence_id}' not found."})
776
+ if check_staleness and isinstance(resolved, Path):
777
+ try:
778
+ content, _, file_exists = safe_read_evidence_file(resolved, ev.file_path)
779
+ ledger.check_staleness(
780
+ ev.file_path,
781
+ current_content=content if file_exists else "",
782
+ current_revision=indexer.revision,
783
+ )
784
+ except SecurityValidationError:
785
+ pass
786
+ return ev.model_dump_json(indent=2)
787
+ if file_path:
788
+ try:
789
+ root_target = resolved if isinstance(resolved, Path) else Path(".")
790
+ _, posix_rel = validate_and_resolve_evidence_path(root_target, file_path)
791
+ except SecurityValidationError as exc:
792
+ return json.dumps({"error": f"Invalid evidence file path: {exc.message}"})
793
+ evs = ledger.find_by_file(posix_rel)
794
+ if check_staleness and isinstance(resolved, Path):
795
+ try:
796
+ content, _, file_exists = safe_read_evidence_file(resolved, posix_rel)
797
+ evs = ledger.check_staleness(
798
+ posix_rel,
799
+ current_content=content if file_exists else "",
800
+ current_revision=indexer.revision,
801
+ )
802
+ except SecurityValidationError:
803
+ pass
804
+ return json.dumps([e.model_dump() for e in evs[:limit]], indent=2)
805
+ if symbol_name:
806
+ evs = ledger.find_by_symbol(symbol_name)
807
+ return json.dumps([e.model_dump() for e in evs[:limit]], indent=2)
808
+ return ledger.to_response(limit=limit).model_dump_json(indent=2)
809
+
810
+ def tool_build_context(
811
+ self,
812
+ target: str,
813
+ mode: str = "focused",
814
+ query: str | None = None,
815
+ target_files: list[str] | None = None,
816
+ max_tokens: int | None = 2000,
817
+ minimal_contract: bool = False,
818
+ format: str = "markdown",
819
+ force: bool = False,
820
+ ) -> str:
821
+ resolved, _ = self._resolve_target(target)
822
+ analysis = self.get_analysis(target, force=force)
823
+ indexer = self._get_or_create_indexer(resolved, analysis)
824
+ ctx = AgentContextBuilder.build_context(
825
+ analysis=analysis,
826
+ mode=mode,
827
+ query=query,
828
+ target_files=target_files,
829
+ max_tokens=max_tokens,
830
+ indexer=indexer,
831
+ minimal_contract=minimal_contract,
832
+ )
833
+ if format.lower() == "json":
834
+ return ctx.model_dump_json(indent=2)
835
+ return ctx.as_markdown()
836
+
837
+ def tool_history_snapshots(self, target: str, limit: int = 30) -> str:
838
+ resolved, _ = self._resolve_target(target)
839
+ root = resolved if isinstance(resolved, Path) else Path(".")
840
+ engine = HistoricalSnapshotEngine(repo_path=root)
841
+ keys = engine.cache.list_keys()[:limit]
842
+ items = []
843
+ for k in keys:
844
+ snap = engine.cache.get(k)
845
+ if snap:
846
+ items.append(
847
+ {
848
+ "cache_key": k,
849
+ "commit_sha": snap.commit_sha,
850
+ "timestamp": snap.commit_timestamp,
851
+ "author": snap.commit_author,
852
+ "health_score": snap.health.score,
853
+ "modules_count": len(snap.modules),
854
+ }
855
+ )
856
+ return json.dumps(
857
+ {
858
+ "repo_identity": engine.repo_identity,
859
+ "total_cached_snapshots": len(items),
860
+ "snapshots": items,
861
+ "read_only": True,
862
+ "provenance": "historical_disk_cache",
863
+ },
864
+ indent=2,
865
+ )
866
+
867
+ def tool_history_analyze(
868
+ self, target: str, commit_sha: str = "HEAD", use_cache: bool = True
869
+ ) -> str:
870
+ resolved, _ = self._resolve_target(target)
871
+ root = resolved if isinstance(resolved, Path) else Path(".")
872
+ engine = HistoricalSnapshotEngine(repo_path=root)
873
+ snap = engine.create_snapshot(commit_sha, use_cache=use_cache)
874
+ return snap.model_dump_json(indent=2)
875
+
876
+ def tool_history_diff(
877
+ self, target: str, base_sha: str = "HEAD~1", head_sha: str = "HEAD"
878
+ ) -> str:
879
+ resolved, _ = self._resolve_target(target)
880
+ root = resolved if isinstance(resolved, Path) else Path(".")
881
+ engine = HistoricalSnapshotEngine(repo_path=root)
882
+ base_snap = engine.create_snapshot(base_sha)
883
+ head_snap = engine.create_snapshot(head_sha)
884
+ diff_res = EvolutionDiffEngine.compare_snapshots(
885
+ base=base_snap, head=head_snap, repo_path=root
886
+ )
887
+ return diff_res.model_dump_json(indent=2)
888
+
889
+ def tool_history_timeline(self, target: str, limit: int = 20) -> str:
890
+ resolved, _ = self._resolve_target(target)
891
+ root = resolved if isinstance(resolved, Path) else Path(".")
892
+ engine = HistoricalSnapshotEngine(repo_path=root)
893
+ timeline_eng = TimelineEngine(engine=engine)
894
+ res = timeline_eng.build_timeline(limit=limit)
895
+ return res.model_dump_json(indent=2)
896
+
897
+ def tool_history_evidence(
898
+ self, target: str, commit_sha: str, file_path: str, line_start: int = 1, line_end: int = 50
899
+ ) -> str:
900
+ resolved, _ = self._resolve_target(target)
901
+ root = resolved if isinstance(resolved, Path) else Path(".")
902
+ engine = HistoricalSnapshotEngine(repo_path=root)
903
+ if len(commit_sha) != 40 or not all(c in "0123456789abcdefABCDEF" for c in commit_sha):
904
+ full_sha, _, _, _, _ = engine.resolve_commit(commit_sha)
905
+ else:
906
+ full_sha = commit_sha.lower()
907
+
908
+ provider = HistoricalEvidenceProvider(repo_path=root)
909
+ content = provider.read_historical_file(commit_sha=full_sha, file_path=file_path)
910
+ snippet, chash = extract_evidence_snippet(content, line_start, line_end)
911
+ return json.dumps(
912
+ {
913
+ "commit_sha": full_sha,
914
+ "file_path": file_path,
915
+ "line_start": line_start,
916
+ "line_end": line_end,
917
+ "snippet": snippet,
918
+ "content_hash": chash,
919
+ "is_historical_blob": True,
920
+ "revision_source": f"git_blob:{full_sha[:10]}",
921
+ },
922
+ indent=2,
923
+ )
924
+
925
+ def tool_refactoring_advisor(
926
+ self,
927
+ target: str,
928
+ category: str | None = None,
929
+ min_severity: str | None = None,
930
+ format: str = "json",
931
+ force: bool = False,
932
+ ) -> str:
933
+ analysis = self.get_analysis(target, force=force)
934
+ contract = None
935
+ resolved, _ = self._resolve_target(target)
936
+ if isinstance(resolved, Path) and resolved.is_dir():
937
+ c_file = find_contract_file(resolved)
938
+ if c_file and c_file.exists():
939
+ try:
940
+ contract = load_contract_file(c_file)
941
+ except Exception:
942
+ pass
943
+
944
+ cat_filter = None
945
+ if category:
946
+ try:
947
+ cat_filter = AdvisorCategory(category)
948
+ except ValueError:
949
+ return json.dumps(
950
+ {
951
+ "error": f"Invalid category '{category}'. Valid: {[c.value for c in AdvisorCategory]}"
952
+ }
953
+ )
954
+
955
+ engine = RefactoringAdvisorEngine(analysis=analysis, contract=contract)
956
+ report = engine.generate_report(category_filter=cat_filter, min_severity=min_severity)
957
+ if format == "text":
958
+ return report.summary
959
+ return report.model_dump_json(indent=2)
960
+
961
+ # -------------------------------------------------------------------------
962
+ # Live Architecture Engine Read-Only MCP Tools (v0.9.0)
963
+ # Never auto-starts watchers; reads cross-process SQLite WAL with PID check
964
+ # -------------------------------------------------------------------------
965
+
966
+ def _read_live_workspace_state(self, target: str) -> dict[str, Any]:
967
+ resolved, stype = self._resolve_target(target)
968
+ if stype != SourceType.LOCAL or not isinstance(resolved, Path):
969
+ return {
970
+ "session_available": False,
971
+ "source": "unsupported",
972
+ "reason": "Live monitoring is available for local repositories only.",
973
+ "session": None,
974
+ "alerts": [],
975
+ "recent_history": [],
976
+ }
977
+ ws_id = compute_repo_identity(resolved, SourceType.LOCAL.value, str(resolved))
978
+ mgr = get_live_session_manager()
979
+ in_proc = mgr.find_active_session_for_workspace(ws_id)
980
+ if in_proc is not None:
981
+ return summarize_live_state_for_mcp(
982
+ ws_id,
983
+ in_process_info=in_proc.get_info(),
984
+ in_process_alerts=in_proc.get_alerts(),
985
+ in_process_history=in_proc.get_history(limit=25),
986
+ )
987
+ return summarize_live_state_for_mcp(ws_id, persistence=LiveStatePersistence())
988
+
989
+ def tool_live_status(self, target: str = ".", format: str = "json") -> str:
990
+ state = self._read_live_workspace_state(target)
991
+ sess = state.get("session")
992
+ alerts = state.get("alerts", [])
993
+ active_alerts = [a for a in alerts if a.get("status") in ("ACTIVE", "UNKNOWN")]
994
+ payload = {
995
+ "session_available": bool(state.get("session_available", False)),
996
+ "source": state.get("source"),
997
+ "reason": state.get("reason"),
998
+ "session_id": sess.get("session_id") if sess else None,
999
+ "workspace_identity": sess.get("workspace_identity") if sess else None,
1000
+ "state": sess.get("state") if sess else "NOT_RUNNING",
1001
+ "freshness": sess.get("freshness") if sess else "UNKNOWN",
1002
+ "is_verified_current": bool(
1003
+ state.get("session_available") and sess and sess.get("freshness") == "VERIFIED_CURRENT"
1004
+ ),
1005
+ "last_verified_snapshot_identity": (
1006
+ sess.get("last_verified_snapshot_identity") if sess else None
1007
+ ),
1008
+ "pending_changes_count": sess.get("pending_changes_count", 0) if sess else 0,
1009
+ "analysis_in_progress": bool(sess.get("analysis_in_progress", False)) if sess else False,
1010
+ "watcher_backend": sess.get("watcher_backend") if sess else None,
1011
+ "health_status": sess.get("health_status") if sess else "inactive",
1012
+ "active_alerts_count": len(active_alerts),
1013
+ "last_verified_at": sess.get("last_verified_at") if sess else None,
1014
+ }
1015
+ if format == "text":
1016
+ if not payload["session_available"]:
1017
+ return (
1018
+ f"Live Architecture Status: NO ACTIVE SESSION ({payload.get('reason') or 'not watching'}). "
1019
+ "Start watching explicitly with 'repodna watch .' or the RepoDNA Workstation."
1020
+ )
1021
+ return (
1022
+ f"Live Architecture Status: {payload['state']} | Freshness: {payload['freshness']} | "
1023
+ f"Snapshot: {payload['last_verified_snapshot_identity'] or 'pending'} | "
1024
+ f"Pending: {payload['pending_changes_count']} | Active Alerts: {payload['active_alerts_count']}"
1025
+ )
1026
+ return json.dumps(payload, indent=2)
1027
+
1028
+ def tool_live_changes(
1029
+ self, target: str = ".", limit: int = 20, format: str = "json"
1030
+ ) -> str:
1031
+ state = self._read_live_workspace_state(target)
1032
+ sess = state.get("session")
1033
+ bounded_limit = max(1, min(100, int(limit)))
1034
+ entries = list(state.get("recent_history", []))[:bounded_limit]
1035
+ payload = {
1036
+ "session_available": bool(state.get("session_available", False)),
1037
+ "freshness": sess.get("freshness") if sess else "UNKNOWN",
1038
+ "last_verified_snapshot_identity": (
1039
+ sess.get("last_verified_snapshot_identity") if sess else None
1040
+ ),
1041
+ "total_returned": len(entries),
1042
+ "changes": entries,
1043
+ }
1044
+ if format == "text":
1045
+ if not entries:
1046
+ return "No live working-tree architectural changes recorded."
1047
+ lines = [
1048
+ f"Recent Live Working-Tree Changes ({len(entries)}, freshness={payload['freshness']}):"
1049
+ ]
1050
+ for e in entries[:10]:
1051
+ lines.append(
1052
+ f"- [{e.get('event_kind')}] {e.get('summary') or 'update'} "
1053
+ f"(files={e.get('changed_file_count', 0)}, snap={str(e.get('snapshot_identity') or '')[:16]})"
1054
+ )
1055
+ return "\n".join(lines)
1056
+ return json.dumps(payload, indent=2)
1057
+
1058
+ def tool_live_alerts(
1059
+ self, target: str = ".", status: str | None = None, format: str = "json"
1060
+ ) -> str:
1061
+ state = self._read_live_workspace_state(target)
1062
+ sess = state.get("session")
1063
+ alerts = list(state.get("alerts", []))
1064
+ if status:
1065
+ want = status.strip().upper()
1066
+ alerts = [a for a in alerts if str(a.get("status", "")).upper() == want]
1067
+ payload = {
1068
+ "session_available": bool(state.get("session_available", False)),
1069
+ "freshness": sess.get("freshness") if sess else "UNKNOWN",
1070
+ "total_alerts": len(alerts),
1071
+ "alerts": alerts,
1072
+ }
1073
+ if format == "text":
1074
+ if not alerts:
1075
+ return f"No live architectural alerts (freshness={payload['freshness']})."
1076
+ lines = [f"Live Architectural Alerts ({len(alerts)}, freshness={payload['freshness']}):"]
1077
+ for a in alerts[:15]:
1078
+ lines.append(
1079
+ f"- [{a.get('status')}/{a.get('severity')}] {a.get('category')}: {a.get('title')} — {a.get('explanation')}"
1080
+ )
1081
+ return "\n".join(lines)
1082
+ return json.dumps(payload, indent=2)
1083
+
1084
+ def tool_live_context(
1085
+ self,
1086
+ target: str = ".",
1087
+ max_tokens: int = 1500,
1088
+ format: str = "markdown",
1089
+ ) -> str:
1090
+ state = self._read_live_workspace_state(target)
1091
+ sess = state.get("session")
1092
+ alerts = list(state.get("alerts", []))
1093
+ history = list(state.get("recent_history", []))
1094
+ active_alerts = [a for a in alerts if a.get("status") in ("ACTIVE", "UNKNOWN")]
1095
+ is_avail = bool(state.get("session_available", False))
1096
+ freshness = sess.get("freshness") if (is_avail and sess) else "NO_ACTIVE_LIVE_SESSION"
1097
+
1098
+ max_chars = max(400, min(32000, int(max_tokens) * 4))
1099
+
1100
+ if format.lower() == "json":
1101
+ recent_deltas: list[dict[str, Any]] = [
1102
+ {
1103
+ "entry_id": h.get("entry_id"),
1104
+ "event_kind": h.get("event_kind"),
1105
+ "snapshot_identity": h.get("snapshot_identity"),
1106
+ "has_architectural_changes": h.get("has_architectural_changes"),
1107
+ "summary": h.get("summary"),
1108
+ }
1109
+ for h in history[:10]
1110
+ ]
1111
+ payload: dict[str, Any] = {
1112
+ "session_available": is_avail,
1113
+ "freshness": freshness,
1114
+ "is_verified_current": freshness == "VERIFIED_CURRENT",
1115
+ "disclosure": (
1116
+ "Verified current live working-tree snapshot."
1117
+ if freshness == "VERIFIED_CURRENT"
1118
+ else "WARNING: Snapshot is not verified current; do not assume working-tree changes are reflected."
1119
+ ),
1120
+ "snapshot_identity": sess.get("last_verified_snapshot_identity") if sess else None,
1121
+ "pending_changes_count": sess.get("pending_changes_count", 0) if sess else 0,
1122
+ "analysis_in_progress": bool(sess.get("analysis_in_progress", False)) if sess else False,
1123
+ "active_alerts": active_alerts[:15],
1124
+ "recent_deltas": recent_deltas,
1125
+ "max_tokens": max_tokens,
1126
+ }
1127
+ raw_json = json.dumps(payload, indent=2)
1128
+ if len(raw_json) > max_chars:
1129
+ payload["active_alerts"] = active_alerts[:5]
1130
+ payload["recent_deltas"] = recent_deltas[:5]
1131
+ payload["truncated"] = True
1132
+ raw_json = json.dumps(payload, indent=2)
1133
+ return raw_json
1134
+
1135
+ lines = [
1136
+ "# RepoDNA Live Architecture Context",
1137
+ "",
1138
+ f"- **Live Session Available:** `{is_avail}`",
1139
+ f"- **Freshness:** `{freshness}`",
1140
+ f"- **Latest Verified Snapshot:** `{sess.get('last_verified_snapshot_identity') if sess else 'none'}`",
1141
+ f"- **Pending Changes:** `{sess.get('pending_changes_count', 0) if sess else 0}`",
1142
+ f"- **Analysis In Progress:** `{bool(sess.get('analysis_in_progress', False)) if sess else False}`",
1143
+ ]
1144
+ if freshness != "VERIFIED_CURRENT":
1145
+ lines.append(
1146
+ "- **Freshness Disclosure:** Working tree state is NOT verified current "
1147
+ f"(`{freshness}`); treat architectural facts cautiously or trigger reconciliation."
1148
+ )
1149
+
1150
+ if active_alerts:
1151
+ lines.extend(["", f"## Active Architectural Risks ({len(active_alerts)})"])
1152
+ for a in active_alerts[:10]:
1153
+ mods = ", ".join(a.get("affected_modules", [])[:4])
1154
+ ev = ", ".join(a.get("evidence_refs", [])[:3])
1155
+ lines.append(
1156
+ f"- **[{a.get('severity', '').upper()}] {a.get('category')}**: {a.get('title')} "
1157
+ f"(modules: `{mods or 'workspace'}`; evidence: `{ev or 'n/a'}`)"
1158
+ )
1159
+
1160
+ if history:
1161
+ lines.extend(["", "## Recent Verified Working-Tree Changes"])
1162
+ for h in history[:8]:
1163
+ lines.append(
1164
+ f"- `{h.get('event_kind')}` ({h.get('changed_file_count', 0)} file(s)): {h.get('summary')}"
1165
+ )
1166
+
1167
+ rendered = "\n".join(lines)
1168
+ if len(rendered) > max_chars:
1169
+ rendered = rendered[: max_chars - 32] + "\n\n...[truncated to token budget]"
1170
+ return rendered
1171
+
1172
+ # -------------------------------------------------------------------------
1173
+ # Deep Code Intelligence Read-Only MCP Tools (v0.10.0)
1174
+ # -------------------------------------------------------------------------
1175
+ def _run_quality_for_target(self, target: str) -> tuple[QualityReport, SymbolIndexer, AnalysisResult]:
1176
+ resolved, _ = self._resolve_target(target)
1177
+ analysis = self.get_analysis(target)
1178
+ indexer = self._get_or_create_indexer(resolved, analysis)
1179
+ report = QualityIntelligenceEngine.analyze(
1180
+ root_path=resolved,
1181
+ analysis=analysis,
1182
+ indexer=indexer,
1183
+ use_cache=True,
1184
+ )
1185
+ return report, indexer, analysis
1186
+
1187
+ def tool_code_quality(self, target: str = ".", format: str = "json") -> str:
1188
+ report, _, _ = self._run_quality_for_target(target)
1189
+ active = [f for f in report.findings if f.status == FindingStatus.ACTIVE]
1190
+ payload = {
1191
+ "repo_name": report.repo_name,
1192
+ "snapshot_identity": report.snapshot_identity,
1193
+ "ruleset_fingerprint": report.ruleset_fingerprint,
1194
+ "cache_hit": report.cache_hit,
1195
+ "supported_files_count": report.supported_files_count,
1196
+ "unsupported_files_count": report.unsupported_files_count,
1197
+ "syntax_error_files_count": report.syntax_error_files_count,
1198
+ "active_findings_count": len(active),
1199
+ "complexity_symbols_count": len(report.complexity_metrics),
1200
+ "clone_groups_count": report.duplicates.total_clone_groups,
1201
+ "unused_candidates_count": len(report.unused_candidates),
1202
+ "security_signals_count": len(report.security_signals),
1203
+ "technical_debt": report.technical_debt.model_dump(mode="json"),
1204
+ "limitations": report.limitations,
1205
+ }
1206
+ if format == "text":
1207
+ return (
1208
+ f"RepoDNA Code Quality ({report.repo_name}): {len(active)} active findings, "
1209
+ f"{report.duplicates.total_clone_groups} clone groups, "
1210
+ f"{len(report.unused_candidates)} unused candidates, "
1211
+ f"debt_index={report.technical_debt.total_debt_index}."
1212
+ )
1213
+ return json.dumps(payload, indent=2)
1214
+
1215
+ def tool_get_quality_findings(
1216
+ self,
1217
+ target: str = ".",
1218
+ category: str | None = None,
1219
+ severity: str | None = None,
1220
+ language: str | None = None,
1221
+ offset: int = 0,
1222
+ limit: int = 25,
1223
+ ) -> str:
1224
+ report, _, _ = self._run_quality_for_target(target)
1225
+ items = report.findings
1226
+ if category:
1227
+ items = [f for f in items if f.category.value == category.lower()]
1228
+ if severity:
1229
+ items = [f for f in items if f.severity.value == severity.lower()]
1230
+ if language:
1231
+ items = [f for f in items if f.language.lower() == language.lower()]
1232
+ bounded_limit = max(1, min(100, int(limit)))
1233
+ bounded_offset = max(0, int(offset))
1234
+ return json.dumps(
1235
+ {
1236
+ "ruleset_fingerprint": report.ruleset_fingerprint,
1237
+ "snapshot_identity": report.snapshot_identity,
1238
+ "total": len(items),
1239
+ "offset": bounded_offset,
1240
+ "limit": bounded_limit,
1241
+ "items": [f.model_dump(mode="json") for f in items[bounded_offset : bounded_offset + bounded_limit]],
1242
+ },
1243
+ indent=2,
1244
+ )
1245
+
1246
+ def tool_symbol_complexity(
1247
+ self,
1248
+ target: str = ".",
1249
+ language: str | None = None,
1250
+ file_path: str | None = None,
1251
+ offset: int = 0,
1252
+ limit: int = 25,
1253
+ ) -> str:
1254
+ report, _, _ = self._run_quality_for_target(target)
1255
+ items = report.complexity_metrics
1256
+ if language:
1257
+ items = [m for m in items if m.language.lower() == language.lower()]
1258
+ if file_path:
1259
+ fp_l = file_path.replace("\\", "/").lower()
1260
+ items = [m for m in items if fp_l in m.file_path.lower()]
1261
+ bounded_limit = max(1, min(100, int(limit)))
1262
+ bounded_offset = max(0, int(offset))
1263
+ return json.dumps(
1264
+ {
1265
+ "methodology": "mccabe_cyclomatic_v1+repodna_nesting_weighted_v1",
1266
+ "total": len(items),
1267
+ "offset": bounded_offset,
1268
+ "limit": bounded_limit,
1269
+ "items": [m.model_dump(mode="json") for m in items[bounded_offset : bounded_offset + bounded_limit]],
1270
+ },
1271
+ indent=2,
1272
+ )
1273
+
1274
+ def tool_find_duplicates(
1275
+ self, target: str = ".", language: str | None = None, offset: int = 0, limit: int = 20
1276
+ ) -> str:
1277
+ report, _, _ = self._run_quality_for_target(target)
1278
+ groups = report.duplicates.groups
1279
+ if language:
1280
+ groups = [g for g in groups if g.language.lower() == language.lower()]
1281
+ bounded_limit = max(1, min(50, int(limit)))
1282
+ bounded_offset = max(0, int(offset))
1283
+ return json.dumps(
1284
+ {
1285
+ "min_tokens_threshold": report.duplicates.min_tokens_threshold,
1286
+ "incomplete_coverage": report.duplicates.incomplete_coverage,
1287
+ "incomplete_reason": report.duplicates.incomplete_reason,
1288
+ "total": len(groups),
1289
+ "offset": bounded_offset,
1290
+ "limit": bounded_limit,
1291
+ "items": [g.model_dump(mode="json") for g in groups[bounded_offset : bounded_offset + bounded_limit]],
1292
+ },
1293
+ indent=2,
1294
+ )
1295
+
1296
+ def tool_unused_candidates(
1297
+ self, target: str = ".", language: str | None = None, offset: int = 0, limit: int = 25
1298
+ ) -> str:
1299
+ report, _, _ = self._run_quality_for_target(target)
1300
+ items = report.unused_candidates
1301
+ if language:
1302
+ items = [u for u in items if u.language.lower() == language.lower()]
1303
+ bounded_limit = max(1, min(100, int(limit)))
1304
+ bounded_offset = max(0, int(offset))
1305
+ return json.dumps(
1306
+ {
1307
+ "disclosure": "Conservative unused-code review candidates only; absence of static references does not prove dead code.",
1308
+ "total": len(items),
1309
+ "offset": bounded_offset,
1310
+ "limit": bounded_limit,
1311
+ "items": [u.model_dump(mode="json") for u in items[bounded_offset : bounded_offset + bounded_limit]],
1312
+ },
1313
+ indent=2,
1314
+ )
1315
+
1316
+ def tool_test_relationships(
1317
+ self, target: str = ".", relationship: str | None = None, offset: int = 0, limit: int = 25
1318
+ ) -> str:
1319
+ report, _, _ = self._run_quality_for_target(target)
1320
+ tm = report.test_mapping
1321
+ items = tm.entries
1322
+ if relationship:
1323
+ items = [e for e in items if e.relationship_kind.value == relationship.lower()]
1324
+ bounded_limit = max(1, min(100, int(limit)))
1325
+ bounded_offset = max(0, int(offset))
1326
+ return json.dumps(
1327
+ {
1328
+ "methodology": tm.methodology,
1329
+ "disclosure": tm.disclosure,
1330
+ "total_test_files": tm.total_test_files,
1331
+ "ecosystems_detected": tm.ecosystems_detected,
1332
+ "total": len(items),
1333
+ "offset": bounded_offset,
1334
+ "limit": bounded_limit,
1335
+ "items": [e.model_dump(mode="json") for e in items[bounded_offset : bounded_offset + bounded_limit]],
1336
+ },
1337
+ indent=2,
1338
+ )
1339
+
1340
+ def tool_symbol_change_impact(self, target: str = ".", base_ref: str = "HEAD~1") -> str:
1341
+ report, indexer, analysis = self._run_quality_for_target(target)
1342
+ impact = compute_symbol_impact(
1343
+ before_symbols=list(indexer._symbols_by_id.values()),
1344
+ after_symbols=list(indexer._symbols_by_id.values()),
1345
+ before_complexity=report.complexity_metrics,
1346
+ after_complexity=report.complexity_metrics,
1347
+ before_findings=report.findings,
1348
+ after_findings=report.findings,
1349
+ before_snapshot_identity=base_ref,
1350
+ after_snapshot_identity=report.snapshot_identity,
1351
+ )
1352
+ return json.dumps(
1353
+ {
1354
+ "repo_name": analysis.repo_name,
1355
+ "base_ref": base_ref,
1356
+ **impact.model_dump(mode="json"),
1357
+ },
1358
+ indent=2,
1359
+ )
1360
+
1361
+ # -------------------------------------------------------------------------
1362
+ # Official Python MCP SDK Server Setup
1363
+ # -------------------------------------------------------------------------
1364
+ def _setup_official_server(self) -> None:
1365
+ """Configures official MCPServer with typed tools when SDK is available."""
1366
+ self._official_server = MCPServer(name=SERVER_NAME)
1367
+
1368
+ @self._official_server.tool(
1369
+ name="repodna_repository_overview",
1370
+ description="Provides high-level codebase architecture snapshot, health metrics, and component vitals.",
1371
+ )
1372
+ def _mcp_overview(target: str, format: str = "text", force: bool = False) -> str:
1373
+ return self.tool_repository_overview(target=target, format=format, force=force)
1374
+
1375
+ @self._official_server.tool(
1376
+ name="repodna_architecture_map",
1377
+ description="Outputs component taxonomy, dependency graph linkages, and modular hierarchy.",
1378
+ )
1379
+ def _mcp_arch_map(
1380
+ target: str, level: str = "clusters", limit: int = 30, force: bool = False
1381
+ ) -> str:
1382
+ return self.tool_architecture_map(target=target, level=level, limit=limit, force=force)
1383
+
1384
+ @self._official_server.tool(
1385
+ name="repodna_find_modules",
1386
+ description="Finds repository modules matching a search query by filename, symbols, or architectural hub status.",
1387
+ )
1388
+ def _mcp_find_modules(target: str, query: str, limit: int = 10, force: bool = False) -> str:
1389
+ return self.tool_find_modules(target=target, query=query, limit=limit, force=force)
1390
+
1391
+ @self._official_server.tool(
1392
+ name="repodna_module_dependencies",
1393
+ description="Traces direct or transitive incoming/outgoing dependencies for a specific module.",
1394
+ )
1395
+ def _mcp_dependencies(
1396
+ target: str,
1397
+ file_path: str,
1398
+ direction: str = "outgoing",
1399
+ depth: int = 1,
1400
+ force: bool = False,
1401
+ ) -> str:
1402
+ return self.tool_module_dependencies(
1403
+ target=target, file_path=file_path, direction=direction, depth=depth, force=force
1404
+ )
1405
+
1406
+ @self._official_server.tool(
1407
+ name="repodna_module_findings",
1408
+ description="Lists architectural rule findings (circular dependencies, coupling hotspots) filtered by module or rule.",
1409
+ )
1410
+ def _mcp_findings(
1411
+ target: str,
1412
+ file_path: str | None = None,
1413
+ rule_id: str | None = None,
1414
+ severity: str | None = None,
1415
+ force: bool = False,
1416
+ ) -> str:
1417
+ return self.tool_module_findings(
1418
+ target=target, file_path=file_path, rule_id=rule_id, severity=severity, force=force
1419
+ )
1420
+
1421
+ @self._official_server.tool(
1422
+ name="repodna_architecture_diff",
1423
+ description="Compares two Git revisions or working tree against a revision for architectural changes.",
1424
+ )
1425
+ def _mcp_diff(target: str, base_ref: str = "HEAD~1", head_ref: str = "HEAD") -> str:
1426
+ return self.tool_architecture_diff(target=target, base_ref=base_ref, head_ref=head_ref)
1427
+
1428
+ @self._official_server.tool(
1429
+ name="repodna_change_impact",
1430
+ description="Evaluates architectural risk and direct/transitive blast radius of proposed file edits.",
1431
+ )
1432
+ def _mcp_change_impact(
1433
+ target: str, changed_files: list[str], max_depth: int = 2, force: bool = False
1434
+ ) -> str:
1435
+ return self.tool_change_impact(
1436
+ target=target, changed_files=changed_files, max_depth=max_depth, force=force
1437
+ )
1438
+
1439
+ @self._official_server.tool(
1440
+ name="repodna_analysis_coverage",
1441
+ description="Returns full AST vs partial static language coverage, unverified rules, and honesty guarantees.",
1442
+ )
1443
+ def _mcp_coverage(target: str, force: bool = False) -> str:
1444
+ return self.tool_analysis_coverage(target=target, force=force)
1445
+
1446
+ @self._official_server.tool(
1447
+ name="repodna_get_passport",
1448
+ description="Retrieves portable Repository Passport containing structural identity, AST coverage, hubs, and contracts.",
1449
+ )
1450
+ def _mcp_passport(
1451
+ target: str,
1452
+ max_modules: int = 150,
1453
+ format: str = "json",
1454
+ version: str = "2.0",
1455
+ force: bool = False,
1456
+ ) -> str:
1457
+ return self.tool_get_passport(
1458
+ target=target, max_modules=max_modules, format=format, version=version, force=force
1459
+ )
1460
+
1461
+ @self._official_server.tool(
1462
+ name="repodna_get_contract",
1463
+ description="Returns declared repository Architecture Contract rules and boundary policies from .repodna/architecture.yml.",
1464
+ )
1465
+ def _mcp_get_contract(target: str, format: str = "yaml") -> str:
1466
+ return self.tool_get_contract(target=target, format=format)
1467
+
1468
+ @self._official_server.tool(
1469
+ name="repodna_check_contract",
1470
+ description="Evaluates repository against architecture contract rules, reporting violations, baseline items, and unknowns.",
1471
+ )
1472
+ def _mcp_check_contract(target: str, mode: str | None = None, force: bool = False) -> str:
1473
+ return self.tool_check_contract(target=target, mode=mode, force=force)
1474
+
1475
+ @self._official_server.tool(
1476
+ name="repodna_pr_guardian",
1477
+ description="Continuous architectural assessment between base and head Git revisions for PR review with pass/fail verdict.",
1478
+ )
1479
+ def _mcp_guardian(
1480
+ target: str,
1481
+ base_ref: str = "HEAD~1",
1482
+ head_ref: str = "HEAD",
1483
+ mode: str | None = None,
1484
+ format: str = "json",
1485
+ ) -> str:
1486
+ return self.tool_pr_guardian(
1487
+ target=target, base_ref=base_ref, head_ref=head_ref, mode=mode, format=format
1488
+ )
1489
+
1490
+ @self._official_server.tool(
1491
+ name="repodna_search_code",
1492
+ description="Smart Context Retrieval across repository code, symbols, and architecture with explainable scoring.",
1493
+ )
1494
+ def _mcp_search_code(
1495
+ target: str,
1496
+ query: str,
1497
+ limit: int = 10,
1498
+ kind: str | None = None,
1499
+ path_filter: str | None = None,
1500
+ force: bool = False,
1501
+ ) -> str:
1502
+ return self.tool_search_code(
1503
+ target=target,
1504
+ query=query,
1505
+ limit=limit,
1506
+ kind=kind,
1507
+ path_filter=path_filter,
1508
+ force=force,
1509
+ )
1510
+
1511
+ @self._official_server.tool(
1512
+ name="repodna_find_symbol",
1513
+ description="Queries Tree-sitter symbol index by name, kind, file path, or container class.",
1514
+ )
1515
+ def _mcp_find_symbol(
1516
+ target: str,
1517
+ name: str | None = None,
1518
+ kind: str | None = None,
1519
+ file_path: str | None = None,
1520
+ container: str | None = None,
1521
+ limit: int = 25,
1522
+ force: bool = False,
1523
+ ) -> str:
1524
+ return self.tool_find_symbol(
1525
+ target=target,
1526
+ name=name,
1527
+ kind=kind,
1528
+ file_path=file_path,
1529
+ container=container,
1530
+ limit=limit,
1531
+ force=force,
1532
+ )
1533
+
1534
+ @self._official_server.tool(
1535
+ name="repodna_trace_symbol",
1536
+ description="Traces cross-module call sites, importing files, and blast radius of modifying a symbol.",
1537
+ )
1538
+ def _mcp_trace_symbol(
1539
+ target: str, symbol_name: str, file_path: str | None = None, force: bool = False
1540
+ ) -> str:
1541
+ return self.tool_trace_symbol(
1542
+ target=target, symbol_name=symbol_name, file_path=file_path, force=force
1543
+ )
1544
+
1545
+ @self._official_server.tool(
1546
+ name="repodna_get_evidence",
1547
+ description="Retrieves verified architectural evidence citations with Git revision provenance and staleness status.",
1548
+ )
1549
+ def _mcp_get_evidence(
1550
+ target: str,
1551
+ evidence_id: str | None = None,
1552
+ file_path: str | None = None,
1553
+ symbol_name: str | None = None,
1554
+ check_staleness: bool = True,
1555
+ limit: int = 25,
1556
+ force: bool = False,
1557
+ ) -> str:
1558
+ return self.tool_get_evidence(
1559
+ target=target,
1560
+ evidence_id=evidence_id,
1561
+ file_path=file_path,
1562
+ symbol_name=symbol_name,
1563
+ check_staleness=check_staleness,
1564
+ limit=limit,
1565
+ force=force,
1566
+ )
1567
+
1568
+ @self._official_server.tool(
1569
+ name="repodna_build_context",
1570
+ description="Generates budget-aware architectural context (compact/focused/deep) with evidence citations for AI agents.",
1571
+ )
1572
+ def _mcp_build_context(
1573
+ target: str,
1574
+ mode: str = "focused",
1575
+ query: str | None = None,
1576
+ target_files: list[str] | None = None,
1577
+ max_tokens: int | None = 2000,
1578
+ minimal_contract: bool = False,
1579
+ format: str = "markdown",
1580
+ force: bool = False,
1581
+ ) -> str:
1582
+ return self.tool_build_context(
1583
+ target=target,
1584
+ mode=mode,
1585
+ query=query,
1586
+ target_files=target_files,
1587
+ max_tokens=max_tokens,
1588
+ minimal_contract=minimal_contract,
1589
+ format=format,
1590
+ force=force,
1591
+ )
1592
+
1593
+ @self._official_server.tool(
1594
+ name="repodna_history_snapshots",
1595
+ description="Lists cached historical architecture snapshots in the repository with health and module counts.",
1596
+ )
1597
+ def _mcp_history_snapshots(target: str, limit: int = 30) -> str:
1598
+ return self.tool_history_snapshots(target=target, limit=limit)
1599
+
1600
+ @self._official_server.tool(
1601
+ name="repodna_history_analyze",
1602
+ description="Extracts and returns an immutable architectural snapshot for a specific Git commit SHA.",
1603
+ )
1604
+ def _mcp_history_analyze(
1605
+ target: str, commit_sha: str = "HEAD", use_cache: bool = True
1606
+ ) -> str:
1607
+ return self.tool_history_analyze(
1608
+ target=target, commit_sha=commit_sha, use_cache=use_cache
1609
+ )
1610
+
1611
+ @self._official_server.tool(
1612
+ name="repodna_history_diff",
1613
+ description="Computes architectural evolution diff between base and head Git commits (added/removed modules, renames, cycles, coupling).",
1614
+ )
1615
+ def _mcp_history_diff(target: str, base_sha: str = "HEAD~1", head_sha: str = "HEAD") -> str:
1616
+ return self.tool_history_diff(target=target, base_sha=base_sha, head_sha=head_sha)
1617
+
1618
+ @self._official_server.tool(
1619
+ name="repodna_history_timeline",
1620
+ description="Builds historical architecture evolution timeline across a sequence of Git commits.",
1621
+ )
1622
+ def _mcp_history_timeline(target: str, limit: int = 20) -> str:
1623
+ return self.tool_history_timeline(target=target, limit=limit)
1624
+
1625
+ @self._official_server.tool(
1626
+ name="repodna_history_evidence",
1627
+ description="Retrieves historical source snippet directly from a Git commit blob with cryptographic provenance.",
1628
+ )
1629
+ def _mcp_history_evidence(
1630
+ target: str, commit_sha: str, file_path: str, line_start: int = 1, line_end: int = 50
1631
+ ) -> str:
1632
+ return self.tool_history_evidence(
1633
+ target=target,
1634
+ commit_sha=commit_sha,
1635
+ file_path=file_path,
1636
+ line_start=line_start,
1637
+ line_end=line_end,
1638
+ )
1639
+
1640
+ @self._official_server.tool(
1641
+ name="repodna_refactoring_advisor",
1642
+ description="Generates deterministic, evidence-grounded architectural refactoring recommendations (cycles, coupling, layer violations, oversized hubs).",
1643
+ )
1644
+ def _mcp_refactoring_advisor(
1645
+ target: str,
1646
+ category: str | None = None,
1647
+ min_severity: str | None = None,
1648
+ format: str = "json",
1649
+ force: bool = False,
1650
+ ) -> str:
1651
+ return self.tool_refactoring_advisor(
1652
+ target=target,
1653
+ category=category,
1654
+ min_severity=min_severity,
1655
+ format=format,
1656
+ force=force,
1657
+ )
1658
+
1659
+ @self._official_server.tool(
1660
+ name="repodna_live_status",
1661
+ description="Read-only live architecture session status, verified snapshot freshness, pending changes, and active risk count. Never starts watchers.",
1662
+ )
1663
+ def _mcp_live_status(target: str = ".", format: str = "json") -> str:
1664
+ return self.tool_live_status(target=target, format=format)
1665
+
1666
+ @self._official_server.tool(
1667
+ name="repodna_live_changes",
1668
+ description="Read-only recent verified working-tree architectural deltas from the active or recent live session timeline.",
1669
+ )
1670
+ def _mcp_live_changes(target: str = ".", limit: int = 20, format: str = "json") -> str:
1671
+ return self.tool_live_changes(target=target, limit=limit, format=format)
1672
+
1673
+ @self._official_server.tool(
1674
+ name="repodna_live_alerts",
1675
+ description="Read-only active, acknowledged, resolved, or unknown live architectural alerts with evidence references.",
1676
+ )
1677
+ def _mcp_live_alerts(
1678
+ target: str = ".", status: str | None = None, format: str = "json"
1679
+ ) -> str:
1680
+ return self.tool_live_alerts(target=target, status=status, format=format)
1681
+
1682
+ @self._official_server.tool(
1683
+ name="repodna_live_context",
1684
+ description="Token-budgeted read-only live architectural context with honest freshness disclosure, active risks, and recent working-tree changes.",
1685
+ )
1686
+ def _mcp_live_context(
1687
+ target: str = ".", max_tokens: int = 1500, format: str = "markdown"
1688
+ ) -> str:
1689
+ return self.tool_live_context(target=target, max_tokens=max_tokens, format=format)
1690
+
1691
+ @self._official_server.tool(
1692
+ name="repodna_code_quality",
1693
+ description="Read-only Deep Code Intelligence quality overview: findings summary, technical debt index, language capabilities, and honest limitations.",
1694
+ )
1695
+ def _mcp_code_quality(target: str = ".", format: str = "json") -> str:
1696
+ return self.tool_code_quality(target=target, format=format)
1697
+
1698
+ @self._official_server.tool(
1699
+ name="repodna_get_quality_findings",
1700
+ description="Paginated, filterable quality findings with stable finding IDs, confidence, evidence references, and rule metadata.",
1701
+ )
1702
+ def _mcp_get_quality_findings(
1703
+ target: str = ".",
1704
+ category: str | None = None,
1705
+ severity: str | None = None,
1706
+ language: str | None = None,
1707
+ offset: int = 0,
1708
+ limit: int = 25,
1709
+ ) -> str:
1710
+ return self.tool_get_quality_findings(
1711
+ target=target, category=category, severity=severity, language=language, offset=offset, limit=limit
1712
+ )
1713
+
1714
+ @self._official_server.tool(
1715
+ name="repodna_symbol_complexity",
1716
+ description="Language-aware per-symbol cyclomatic and nesting-weighted complexity metrics with line-level contributors.",
1717
+ )
1718
+ def _mcp_symbol_complexity(
1719
+ target: str = ".",
1720
+ language: str | None = None,
1721
+ file_path: str | None = None,
1722
+ offset: int = 0,
1723
+ limit: int = 25,
1724
+ ) -> str:
1725
+ return self.tool_symbol_complexity(
1726
+ target=target, language=language, file_path=file_path, offset=offset, limit=limit
1727
+ )
1728
+
1729
+ @self._official_server.tool(
1730
+ name="repodna_find_duplicates",
1731
+ description="Verified Type-1 and Type-2 structural clone groups using bounded Winnowing fingerprinting and exact token verification.",
1732
+ )
1733
+ def _mcp_find_duplicates(
1734
+ target: str = ".", language: str | None = None, offset: int = 0, limit: int = 20
1735
+ ) -> str:
1736
+ return self.tool_find_duplicates(target=target, language=language, offset=offset, limit=limit)
1737
+
1738
+ @self._official_server.tool(
1739
+ name="repodna_unused_candidates",
1740
+ description="Conservative unused-code review candidates (never proven dead code) with framework, WinForms, and public API exclusions.",
1741
+ )
1742
+ def _mcp_unused_candidates(
1743
+ target: str = ".", language: str | None = None, offset: int = 0, limit: int = 25
1744
+ ) -> str:
1745
+ return self.tool_unused_candidates(target=target, language=language, offset=offset, limit=limit)
1746
+
1747
+ @self._official_server.tool(
1748
+ name="repodna_test_relationships",
1749
+ description="Static test-to-source relationship mapping across 10 ecosystems (NOT runtime code coverage).",
1750
+ )
1751
+ def _mcp_test_relationships(
1752
+ target: str = ".", relationship: str | None = None, offset: int = 0, limit: int = 25
1753
+ ) -> str:
1754
+ return self.tool_test_relationships(
1755
+ target=target, relationship=relationship, offset=offset, limit=limit
1756
+ )
1757
+
1758
+ @self._official_server.tool(
1759
+ name="repodna_symbol_change_impact",
1760
+ description="Symbol-level change impact analysis comparing current working tree against a base Git revision or snapshot.",
1761
+ )
1762
+ def _mcp_symbol_change_impact(target: str = ".", base_ref: str = "HEAD~1") -> str:
1763
+ return self.tool_symbol_change_impact(target=target, base_ref=base_ref)
1764
+
1765
+ @self._official_server.tool(
1766
+ name="repodna_task_context",
1767
+ description="Compile a token-budgeted, evidence-grounded context pack (or acknowledged delta pack) for a developer task.",
1768
+ )
1769
+ def _mcp_task_context(
1770
+ target: str = ".",
1771
+ task: str = "",
1772
+ token_budget: int = 2048,
1773
+ target_model: str = "generic",
1774
+ tokenizer: str = "auto",
1775
+ profile: str = "balanced",
1776
+ offset: int = 0,
1777
+ known_block_ids: list[str] | None = None,
1778
+ known_block_hashes: dict[str, str] | None = None,
1779
+ previous_snapshot_id: str | None = None,
1780
+ format: str = "json",
1781
+ ) -> str:
1782
+ return self.tool_task_context(
1783
+ target=target,
1784
+ task=task,
1785
+ token_budget=token_budget,
1786
+ target_model=target_model,
1787
+ tokenizer=tokenizer,
1788
+ profile=profile,
1789
+ offset=offset,
1790
+ known_block_ids=known_block_ids,
1791
+ known_block_hashes=known_block_hashes,
1792
+ previous_snapshot_id=previous_snapshot_id,
1793
+ format=format,
1794
+ )
1795
+
1796
+ @self._official_server.tool(
1797
+ name="repodna_repository_map",
1798
+ description="Compile a deterministic, token-aware repository map with exported signatures, boundaries, and coverage limits.",
1799
+ )
1800
+ def _mcp_repository_map(
1801
+ target: str = ".",
1802
+ mode: str = "overview",
1803
+ task: str | None = None,
1804
+ focus_symbol: str | None = None,
1805
+ token_budget: int = 2048,
1806
+ max_modules: int = 25,
1807
+ ) -> str:
1808
+ return self.tool_repository_map(
1809
+ target=target,
1810
+ mode=mode,
1811
+ task=task,
1812
+ focus_symbol=focus_symbol,
1813
+ token_budget=token_budget,
1814
+ max_modules=max_modules,
1815
+ )
1816
+
1817
+ @self._official_server.tool(
1818
+ name="repodna_expand_context",
1819
+ description="Progressively expand a bounded file, symbol, evidence, dependency path, finding, test, rule, or live change.",
1820
+ )
1821
+ def _mcp_expand_context(
1822
+ target: str = ".",
1823
+ target_type: str = "file",
1824
+ target_id: str = "",
1825
+ snapshot_id: str | None = None,
1826
+ cursor: str | None = None,
1827
+ token_budget: int = 1024,
1828
+ max_lines: int = 80,
1829
+ ) -> str:
1830
+ return self.tool_expand_context(
1831
+ target=target,
1832
+ target_type=target_type,
1833
+ target_id=target_id,
1834
+ snapshot_id=snapshot_id,
1835
+ cursor=cursor,
1836
+ token_budget=token_budget,
1837
+ max_lines=max_lines,
1838
+ )
1839
+
1840
+ @self._official_server.tool(
1841
+ name="repodna_change_preflight",
1842
+ description="Read-only pre-edit impact plan separating verified structural impact from explicitly labeled hypothetical risks.",
1843
+ )
1844
+ def _mcp_change_preflight(
1845
+ target: str = ".",
1846
+ intended_files: list[str] | None = None,
1847
+ intended_symbols: list[str] | None = None,
1848
+ operation_type: str = "modify",
1849
+ proposed_dependency_edges: list[list[str]] | None = None,
1850
+ expected_behavior: str = "",
1851
+ ) -> str:
1852
+ return self.tool_change_preflight(
1853
+ target=target,
1854
+ intended_files=intended_files,
1855
+ intended_symbols=intended_symbols,
1856
+ operation_type=operation_type,
1857
+ proposed_dependency_edges=proposed_dependency_edges,
1858
+ expected_behavior=expected_behavior,
1859
+ )
1860
+
1861
+ @self._official_server.tool(
1862
+ name="repodna_inspect_patch",
1863
+ description="Bounded read-only unified diff inspection with path validation and fail-closed in-memory projection.",
1864
+ )
1865
+ def _mcp_inspect_patch(target: str = ".", patch_text: str = "") -> str:
1866
+ return self.tool_inspect_patch(target=target, patch_text=patch_text)
1867
+
1868
+ @self._official_server.tool(
1869
+ name="repodna_change_postflight",
1870
+ description="Static snapshot-backed postflight verification comparing before/after snapshots (does not run repository tests).",
1871
+ )
1872
+ def _mcp_change_postflight(
1873
+ target: str = ".",
1874
+ intended_files: list[str] | None = None,
1875
+ stale_evidence_ids: list[str] | None = None,
1876
+ ) -> str:
1877
+ return self.tool_change_postflight(
1878
+ target=target,
1879
+ intended_files=intended_files,
1880
+ stale_evidence_ids=stale_evidence_ids,
1881
+ )
1882
+
1883
+ @self._official_server.tool(
1884
+ name="repodna_verify_evidence",
1885
+ description="Verify an evidence ID against current repository snapshot and disk state (VERIFIED/STALE/UNAVAILABLE/PARTIAL/INVALID).",
1886
+ )
1887
+ def _mcp_verify_evidence(
1888
+ target: str = ".",
1889
+ evidence_id: str = "",
1890
+ expected_snapshot_id: str | None = None,
1891
+ ) -> str:
1892
+ return self.tool_verify_evidence(
1893
+ target=target,
1894
+ evidence_id=evidence_id,
1895
+ expected_snapshot_id=expected_snapshot_id,
1896
+ )
1897
+
1898
+ @self._official_server.tool(
1899
+ name="repodna_agent_capabilities",
1900
+ description="Discover RepoDNA read-only capabilities, supported languages, tokenizer mode, tool profiles, and resource bounds.",
1901
+ )
1902
+ def _mcp_agent_capabilities() -> str:
1903
+ return self.tool_agent_capabilities()
1904
+
1905
+ @self._official_server.tool(
1906
+ name="repodna_workspace_overview",
1907
+ description="Read-only federated overview of a multi-repository RepoDNA workspace manifest.",
1908
+ )
1909
+ def _mcp_workspace_overview(manifest_path: str, use_incremental_cache: bool = True) -> str:
1910
+ return json.dumps(
1911
+ dispatch_workspace_tool(
1912
+ "repodna_workspace_overview",
1913
+ {"manifest_path": manifest_path, "use_incremental_cache": use_incremental_cache},
1914
+ authorized_roots=self.allowed_roots,
1915
+ require_authorized_roots=True,
1916
+ ),
1917
+ indent=2,
1918
+ )
1919
+
1920
+ @self._official_server.tool(
1921
+ name="repodna_workspace_dependencies",
1922
+ description="Read-only cross-repository dependency graph, verified/candidate filters, and cycles.",
1923
+ )
1924
+ def _mcp_workspace_dependencies(manifest_path: str, verified_only: bool = False) -> str:
1925
+ return json.dumps(
1926
+ dispatch_workspace_tool(
1927
+ "repodna_workspace_dependencies",
1928
+ {"manifest_path": manifest_path, "verified_only": verified_only},
1929
+ authorized_roots=self.allowed_roots,
1930
+ require_authorized_roots=True,
1931
+ ),
1932
+ indent=2,
1933
+ )
1934
+
1935
+ @self._official_server.tool(
1936
+ name="repodna_workspace_contracts",
1937
+ description="Read-only inventory of static API contracts across workspace repositories.",
1938
+ )
1939
+ def _mcp_workspace_contracts(manifest_path: str) -> str:
1940
+ return json.dumps(
1941
+ dispatch_workspace_tool(
1942
+ "repodna_workspace_contracts",
1943
+ {"manifest_path": manifest_path},
1944
+ authorized_roots=self.allowed_roots,
1945
+ require_authorized_roots=True,
1946
+ ),
1947
+ indent=2,
1948
+ )
1949
+
1950
+ @self._official_server.tool(
1951
+ name="repodna_workspace_impact",
1952
+ description="Read-only bounded cross-repository change impact report for a changed repository alias.",
1953
+ )
1954
+ def _mcp_workspace_impact(
1955
+ manifest_path: str,
1956
+ changed_alias: str,
1957
+ changed_targets: list[str] | None = None,
1958
+ ) -> str:
1959
+ return json.dumps(
1960
+ dispatch_workspace_tool(
1961
+ "repodna_workspace_impact",
1962
+ {
1963
+ "manifest_path": manifest_path,
1964
+ "changed_alias": changed_alias,
1965
+ "changed_targets": changed_targets or [],
1966
+ },
1967
+ authorized_roots=self.allowed_roots,
1968
+ require_authorized_roots=True,
1969
+ ),
1970
+ indent=2,
1971
+ )
1972
+
1973
+ @self._official_server.tool(
1974
+ name="repodna_workspace_context",
1975
+ description="Read-only global token-budgeted multi-repository AI context pack.",
1976
+ )
1977
+ def _mcp_workspace_context(manifest_path: str, task: str, token_budget: int = 2048) -> str:
1978
+ return json.dumps(
1979
+ dispatch_workspace_tool(
1980
+ "repodna_workspace_context",
1981
+ {"manifest_path": manifest_path, "task": task, "token_budget": token_budget},
1982
+ authorized_roots=self.allowed_roots,
1983
+ require_authorized_roots=True,
1984
+ ),
1985
+ indent=2,
1986
+ )
1987
+
1988
+ # Respect opt-in tool profile on official SDK server too
1989
+ allowlist = PROFILE_ALLOWLISTS.get(self.tool_profile)
1990
+ if allowlist is not None and hasattr(self._official_server, "_tool_manager"):
1991
+ tm = self._official_server._tool_manager
1992
+ if hasattr(tm, "_tools") and isinstance(tm._tools, dict):
1993
+ for tname in list(tm._tools.keys()):
1994
+ if tname not in allowlist:
1995
+ tm._tools.pop(tname, None)
1996
+
1997
+ # -------------------------------------------------------------------------
1998
+ # v0.11.0 AI Agent Intelligence Tools (Shared AgentIntelligenceService)
1999
+ # -------------------------------------------------------------------------
2000
+ def _get_agent_service(self, target: str, force: bool = False) -> AgentIntelligenceService:
2001
+ resolved, source_type = self._resolve_target(target)
2002
+ canonical_target = str(resolved)
2003
+ analysis = self.get_analysis(canonical_target, force=force)
2004
+ indexer = self._get_or_create_indexer(canonical_target, analysis)
2005
+ repo_root = resolved if isinstance(resolved, Path) and source_type == SourceType.LOCAL else None
2006
+ q_report: QualityReport | None = None
2007
+ if repo_root is not None:
2008
+ try:
2009
+ q_report, _, _ = self._run_quality_for_target(canonical_target)
2010
+ except Exception:
2011
+ q_report = None
2012
+ return AgentIntelligenceService(
2013
+ analysis=analysis,
2014
+ indexer=indexer,
2015
+ repo_root=repo_root,
2016
+ quality_report=q_report,
2017
+ )
2018
+
2019
+ def tool_task_context(
2020
+ self,
2021
+ target: str = ".",
2022
+ task: str = "",
2023
+ token_budget: int = 2048,
2024
+ target_model: str = "generic",
2025
+ tokenizer: str = "auto",
2026
+ profile: str = "balanced",
2027
+ offset: int = 0,
2028
+ known_block_ids: list[str] | None = None,
2029
+ known_block_hashes: dict[str, str] | None = None,
2030
+ previous_snapshot_id: str | None = None,
2031
+ format: str = "json",
2032
+ ) -> str:
2033
+ svc = self._get_agent_service(target)
2034
+ if known_block_ids or known_block_hashes:
2035
+ delta_req = ContextDeltaRequest(
2036
+ known_block_ids=list(known_block_ids or []),
2037
+ known_block_hashes=dict(known_block_hashes or {}),
2038
+ previous_snapshot_id=previous_snapshot_id,
2039
+ )
2040
+ delta = svc.build_delta_context(
2041
+ task_text=task,
2042
+ delta_req=delta_req,
2043
+ token_budget=token_budget,
2044
+ target_model=target_model,
2045
+ tokenizer_pref=tokenizer,
2046
+ profile=profile,
2047
+ )
2048
+ return delta.model_dump_json(indent=2)
2049
+ pack = svc.build_task_context(
2050
+ task_text=task,
2051
+ token_budget=token_budget,
2052
+ target_model=target_model,
2053
+ tokenizer_pref=tokenizer,
2054
+ profile=profile,
2055
+ offset=offset,
2056
+ )
2057
+ if format.lower() == "markdown":
2058
+ return pack.rendered_markdown
2059
+ return pack.model_dump_json(indent=2)
2060
+
2061
+ def tool_repository_map(
2062
+ self,
2063
+ target: str = ".",
2064
+ mode: str = "overview",
2065
+ task: str | None = None,
2066
+ focus_symbol: str | None = None,
2067
+ token_budget: int = 2048,
2068
+ max_modules: int = 25,
2069
+ ) -> str:
2070
+ svc = self._get_agent_service(target)
2071
+ try:
2072
+ map_mode = RepositoryMapMode(mode.strip().lower())
2073
+ except ValueError:
2074
+ map_mode = RepositoryMapMode.OVERVIEW
2075
+ rmap = svc.compile_repository_map(
2076
+ mode=map_mode,
2077
+ task_text=task,
2078
+ focus_symbol=focus_symbol,
2079
+ token_budget=token_budget,
2080
+ max_modules=max_modules,
2081
+ )
2082
+ return rmap.model_dump_json(indent=2)
2083
+
2084
+ def tool_expand_context(
2085
+ self,
2086
+ target: str = ".",
2087
+ target_type: str = "file",
2088
+ target_id: str = "",
2089
+ snapshot_id: str | None = None,
2090
+ cursor: str | None = None,
2091
+ token_budget: int = 1024,
2092
+ max_lines: int = 80,
2093
+ ) -> str:
2094
+ svc = self._get_agent_service(target)
2095
+ req = ContextExpansionRequest(
2096
+ target_type=ExpansionTargetType(target_type.strip().lower()),
2097
+ target_id=target_id,
2098
+ snapshot_id=snapshot_id,
2099
+ cursor=cursor,
2100
+ token_budget=token_budget,
2101
+ max_lines=max_lines,
2102
+ )
2103
+ return svc.expand_context(req).model_dump_json(indent=2)
2104
+
2105
+ def tool_change_preflight(
2106
+ self,
2107
+ target: str = ".",
2108
+ intended_files: list[str] | None = None,
2109
+ intended_symbols: list[str] | None = None,
2110
+ operation_type: str = "modify",
2111
+ proposed_dependency_edges: list[list[str]] | None = None,
2112
+ expected_behavior: str = "",
2113
+ ) -> str:
2114
+ svc = self._get_agent_service(target)
2115
+ # Save baseline snapshot for subsequent postflight verification
2116
+ self._agent_baseline_snapshots[svc.repo_id] = (svc.snapshot_id, svc.analysis, svc.indexer)
2117
+ edges: list[tuple[str, str]] = [
2118
+ (e[0], e[1]) for e in (proposed_dependency_edges or []) if len(e) == 2
2119
+ ]
2120
+ try:
2121
+ op = ChangeOperationType(operation_type.strip().lower())
2122
+ except ValueError:
2123
+ op = ChangeOperationType.MODIFY
2124
+ intent = ChangeIntent(
2125
+ intended_files=list(intended_files or []),
2126
+ intended_symbols=list(intended_symbols or []),
2127
+ operation_type=op,
2128
+ proposed_dependency_edges=edges,
2129
+ expected_behavior=expected_behavior,
2130
+ )
2131
+ return svc.evaluate_preflight(intent).model_dump_json(indent=2)
2132
+
2133
+ def tool_inspect_patch(self, target: str = ".", patch_text: str = "") -> str:
2134
+ svc = self._get_agent_service(target)
2135
+ return svc.inspect_patch(patch_text).model_dump_json(indent=2)
2136
+
2137
+ def tool_change_postflight(
2138
+ self,
2139
+ target: str = ".",
2140
+ intended_files: list[str] | None = None,
2141
+ stale_evidence_ids: list[str] | None = None,
2142
+ ) -> str:
2143
+ svc = self._get_agent_service(target, force=True)
2144
+ baseline = self._agent_baseline_snapshots.get(svc.repo_id)
2145
+ before_snap_id = baseline[0] if baseline else None
2146
+ before_analysis = baseline[1] if baseline else None
2147
+ before_indexer = baseline[2] if baseline else None
2148
+ intent = ChangeIntent(intended_files=list(intended_files or [])) if intended_files else None
2149
+ res = svc.evaluate_postflight(
2150
+ before_analysis=before_analysis,
2151
+ before_snapshot_id=before_snap_id,
2152
+ before_indexer=before_indexer,
2153
+ change_intent=intent,
2154
+ stale_evidence_ids=stale_evidence_ids,
2155
+ )
2156
+ return res.model_dump_json(indent=2)
2157
+
2158
+ def tool_verify_evidence(
2159
+ self,
2160
+ target: str = ".",
2161
+ evidence_id: str = "",
2162
+ expected_snapshot_id: str | None = None,
2163
+ ) -> str:
2164
+ svc = self._get_agent_service(target)
2165
+ return svc.verify_evidence(
2166
+ evidence_id=evidence_id,
2167
+ expected_snapshot_id=expected_snapshot_id,
2168
+ ).model_dump_json(indent=2)
2169
+
2170
+ def tool_agent_capabilities(self) -> str:
2171
+ return AgentIntelligenceService.get_capabilities(
2172
+ active_tool_profile=self.tool_profile,
2173
+ mcp_sdk_version=MCP_SDK_VERSION,
2174
+ mcp_protocol_version=PROTOCOL_VERSION,
2175
+ ).model_dump_json(indent=2)
2176
+
2177
+ def run(self, transport: str = "stdio") -> None:
2178
+ """Runs the server. Enforces official Python MCP SDK as standard."""
2179
+ if not HAS_OFFICIAL_MCP or self._official_server is None:
2180
+ raise RuntimeError(
2181
+ f"RepoDNA MCP server requires the official Python Model Context Protocol SDK (mcp>=2.0.0). "
2182
+ f"Currently installed: {MCP_SDK_VERSION}. Please install with: pip install 'mcp>=2.0.0'"
2183
+ )
2184
+
2185
+ _log(
2186
+ f"Starting RepoDNA MCP server via official Python SDK v2 ({MCP_SDK_VERSION}), transport={transport}"
2187
+ )
2188
+ self._official_server.run(transport=transport)
2189
+
2190
+ # -------------------------------------------------------------------------
2191
+ # JSON-RPC 2.0 Direct Handling (For fast in-process tests & fallback)
2192
+ # -------------------------------------------------------------------------
2193
+ def get_tools_list(self) -> list[dict[str, Any]]:
2194
+ all_tools: list[dict[str, Any]] = [
2195
+ {
2196
+ "name": "repodna_repository_overview",
2197
+ "description": "Provides high-level codebase architecture snapshot, health metrics, and component vitals.",
2198
+ "inputSchema": {
2199
+ "type": "object",
2200
+ "properties": {
2201
+ "target": {
2202
+ "type": "string",
2203
+ "description": "Local path, repo URL, or 'demo'.",
2204
+ },
2205
+ "format": {"type": "string", "enum": ["text", "json"], "default": "text"},
2206
+ },
2207
+ "required": ["target"],
2208
+ },
2209
+ },
2210
+ {
2211
+ "name": "repodna_architecture_map",
2212
+ "description": "Outputs component taxonomy, dependency graph linkages, and modular hierarchy.",
2213
+ "inputSchema": {
2214
+ "type": "object",
2215
+ "properties": {
2216
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2217
+ "level": {
2218
+ "type": "string",
2219
+ "enum": ["overview", "clusters", "full"],
2220
+ "default": "clusters",
2221
+ },
2222
+ "limit": {"type": "integer", "default": 30},
2223
+ },
2224
+ "required": ["target"],
2225
+ },
2226
+ },
2227
+ {
2228
+ "name": "repodna_find_modules",
2229
+ "description": "Finds repository modules matching a search query by filename, symbols, or architectural hub status.",
2230
+ "inputSchema": {
2231
+ "type": "object",
2232
+ "properties": {
2233
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2234
+ "query": {
2235
+ "type": "string",
2236
+ "description": "Search keyword, symbol name, or path substring.",
2237
+ },
2238
+ "limit": {"type": "integer", "default": 10},
2239
+ },
2240
+ "required": ["target", "query"],
2241
+ },
2242
+ },
2243
+ {
2244
+ "name": "repodna_module_dependencies",
2245
+ "description": "Traces direct or transitive incoming/outgoing dependencies for a specific module.",
2246
+ "inputSchema": {
2247
+ "type": "object",
2248
+ "properties": {
2249
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2250
+ "file_path": {
2251
+ "type": "string",
2252
+ "description": "Relative file path within repository.",
2253
+ },
2254
+ "direction": {
2255
+ "type": "string",
2256
+ "enum": ["outgoing", "incoming", "both"],
2257
+ "default": "outgoing",
2258
+ },
2259
+ "depth": {"type": "integer", "default": 1},
2260
+ },
2261
+ "required": ["target", "file_path"],
2262
+ },
2263
+ },
2264
+ {
2265
+ "name": "repodna_module_findings",
2266
+ "description": "Lists architectural rule findings (circular dependencies, coupling hotspots) filtered by module or rule.",
2267
+ "inputSchema": {
2268
+ "type": "object",
2269
+ "properties": {
2270
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2271
+ "file_path": {
2272
+ "type": "string",
2273
+ "description": "Optional file path to inspect.",
2274
+ },
2275
+ "rule_id": {
2276
+ "type": "string",
2277
+ "description": "Optional rule filter (e.g. ARCH-001).",
2278
+ },
2279
+ "severity": {"type": "string", "enum": ["critical", "warning", "info"]},
2280
+ },
2281
+ "required": ["target"],
2282
+ },
2283
+ },
2284
+ {
2285
+ "name": "repodna_architecture_diff",
2286
+ "description": "Compares two Git revisions or working tree against a revision for architectural changes.",
2287
+ "inputSchema": {
2288
+ "type": "object",
2289
+ "properties": {
2290
+ "target": {
2291
+ "type": "string",
2292
+ "description": "Local Git repository directory.",
2293
+ },
2294
+ "base_ref": {"type": "string", "default": "HEAD~1"},
2295
+ "head_ref": {"type": "string", "default": "HEAD"},
2296
+ },
2297
+ "required": ["target"],
2298
+ },
2299
+ },
2300
+ {
2301
+ "name": "repodna_change_impact",
2302
+ "description": "Evaluates architectural risk and direct/transitive blast radius of proposed file edits.",
2303
+ "inputSchema": {
2304
+ "type": "object",
2305
+ "properties": {
2306
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2307
+ "changed_files": {"type": "array", "items": {"type": "string"}},
2308
+ "max_depth": {"type": "integer", "default": 2},
2309
+ },
2310
+ "required": ["target", "changed_files"],
2311
+ },
2312
+ },
2313
+ {
2314
+ "name": "repodna_analysis_coverage",
2315
+ "description": "Returns full AST vs partial static language coverage, unverified rules, and honesty guarantees.",
2316
+ "inputSchema": {
2317
+ "type": "object",
2318
+ "properties": {
2319
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2320
+ },
2321
+ "required": ["target"],
2322
+ },
2323
+ },
2324
+ {
2325
+ "name": "repodna_get_passport",
2326
+ "description": "Retrieves portable Repository Passport containing structural identity, AST coverage, hubs, and contracts.",
2327
+ "inputSchema": {
2328
+ "type": "object",
2329
+ "properties": {
2330
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2331
+ "max_modules": {"type": "integer", "default": 150},
2332
+ "format": {
2333
+ "type": "string",
2334
+ "enum": ["json", "markdown"],
2335
+ "default": "json",
2336
+ },
2337
+ "version": {
2338
+ "type": "string",
2339
+ "enum": ["1.0", "2.0"],
2340
+ "default": "2.0",
2341
+ "description": "Passport schema version.",
2342
+ },
2343
+ },
2344
+ "required": ["target"],
2345
+ },
2346
+ },
2347
+ {
2348
+ "name": "repodna_get_contract",
2349
+ "description": "Returns declared repository Architecture Contract rules and boundary policies from .repodna/architecture.yml.",
2350
+ "inputSchema": {
2351
+ "type": "object",
2352
+ "properties": {
2353
+ "target": {"type": "string", "description": "Local path."},
2354
+ "format": {"type": "string", "enum": ["yaml", "json"], "default": "yaml"},
2355
+ },
2356
+ "required": ["target"],
2357
+ },
2358
+ },
2359
+ {
2360
+ "name": "repodna_check_contract",
2361
+ "description": "Evaluates repository against architecture contract rules, reporting violations, baseline items, and unknowns.",
2362
+ "inputSchema": {
2363
+ "type": "object",
2364
+ "properties": {
2365
+ "target": {"type": "string", "description": "Local path."},
2366
+ "mode": {"type": "string", "enum": ["advisory", "enforce"]},
2367
+ },
2368
+ "required": ["target"],
2369
+ },
2370
+ },
2371
+ {
2372
+ "name": "repodna_pr_guardian",
2373
+ "description": "Continuous architectural assessment between base and head Git revisions for PR review with pass/fail verdict.",
2374
+ "inputSchema": {
2375
+ "type": "object",
2376
+ "properties": {
2377
+ "target": {
2378
+ "type": "string",
2379
+ "description": "Local Git repository directory.",
2380
+ },
2381
+ "base_ref": {"type": "string", "default": "HEAD~1"},
2382
+ "head_ref": {"type": "string", "default": "HEAD"},
2383
+ "mode": {"type": "string", "enum": ["advisory", "enforce"]},
2384
+ "format": {
2385
+ "type": "string",
2386
+ "enum": ["json", "markdown"],
2387
+ "default": "json",
2388
+ },
2389
+ },
2390
+ "required": ["target"],
2391
+ },
2392
+ },
2393
+ {
2394
+ "name": "repodna_search_code",
2395
+ "description": "Smart Context Retrieval across repository code, symbols, and architecture with explainable scoring.",
2396
+ "inputSchema": {
2397
+ "type": "object",
2398
+ "properties": {
2399
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2400
+ "query": {
2401
+ "type": "string",
2402
+ "description": "Natural or technical code query.",
2403
+ },
2404
+ "limit": {"type": "integer", "default": 10},
2405
+ "kind": {
2406
+ "type": "string",
2407
+ "enum": ["class", "function", "method", "interface", "type"],
2408
+ },
2409
+ "path_filter": {
2410
+ "type": "string",
2411
+ "description": "Optional file path filter.",
2412
+ },
2413
+ },
2414
+ "required": ["target", "query"],
2415
+ },
2416
+ },
2417
+ {
2418
+ "name": "repodna_find_symbol",
2419
+ "description": "Queries Tree-sitter symbol index by name, kind, file path, or container class.",
2420
+ "inputSchema": {
2421
+ "type": "object",
2422
+ "properties": {
2423
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2424
+ "name": {"type": "string", "description": "Symbol name."},
2425
+ "kind": {
2426
+ "type": "string",
2427
+ "enum": ["class", "function", "method", "interface", "type", "struct"],
2428
+ },
2429
+ "file_path": {"type": "string", "description": "File path filter."},
2430
+ "container": {
2431
+ "type": "string",
2432
+ "description": "Parent class or namespace name.",
2433
+ },
2434
+ "limit": {"type": "integer", "default": 25},
2435
+ },
2436
+ "required": ["target"],
2437
+ },
2438
+ },
2439
+ {
2440
+ "name": "repodna_trace_symbol",
2441
+ "description": "Traces cross-module call sites, importing files, and blast radius of modifying a symbol. Supports disambiguation via symbol_id, file_path, or container.",
2442
+ "inputSchema": {
2443
+ "type": "object",
2444
+ "properties": {
2445
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2446
+ "symbol_name": {
2447
+ "type": "string",
2448
+ "description": "Name of the symbol to trace.",
2449
+ },
2450
+ "symbol_id": {
2451
+ "type": "string",
2452
+ "description": "Deterministic symbol ID for unambiguous lookup.",
2453
+ },
2454
+ "file_path": {
2455
+ "type": "string",
2456
+ "description": "Optional file path of symbol definition.",
2457
+ },
2458
+ "container": {
2459
+ "type": "string",
2460
+ "description": "Optional parent class or namespace name.",
2461
+ },
2462
+ },
2463
+ "required": ["target"],
2464
+ },
2465
+ },
2466
+ {
2467
+ "name": "repodna_get_evidence",
2468
+ "description": "Retrieves verified architectural evidence citations with Git revision provenance and staleness status.",
2469
+ "inputSchema": {
2470
+ "type": "object",
2471
+ "properties": {
2472
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2473
+ "evidence_id": {
2474
+ "type": "string",
2475
+ "description": "Specific evidence ID (e.g. ev_<hash>).",
2476
+ },
2477
+ "file_path": {
2478
+ "type": "string",
2479
+ "description": "Filter evidence by file path.",
2480
+ },
2481
+ "symbol_name": {
2482
+ "type": "string",
2483
+ "description": "Filter evidence by symbol name.",
2484
+ },
2485
+ "check_staleness": {
2486
+ "type": "boolean",
2487
+ "default": True,
2488
+ "description": "Verify evidence staleness against files on disk.",
2489
+ },
2490
+ "limit": {"type": "integer", "default": 25},
2491
+ },
2492
+ "required": ["target"],
2493
+ },
2494
+ },
2495
+ {
2496
+ "name": "repodna_build_context",
2497
+ "description": "Generates budget-aware architectural context (compact/focused/deep) with evidence citations for AI agents.",
2498
+ "inputSchema": {
2499
+ "type": "object",
2500
+ "properties": {
2501
+ "target": {"type": "string", "description": "Local path or 'demo'."},
2502
+ "mode": {
2503
+ "type": "string",
2504
+ "enum": ["compact", "focused", "deep"],
2505
+ "default": "focused",
2506
+ },
2507
+ "query": {
2508
+ "type": "string",
2509
+ "description": "Search query for focused context mode.",
2510
+ },
2511
+ "target_files": {"type": "array", "items": {"type": "string"}},
2512
+ "max_tokens": {"type": "integer", "default": 2000},
2513
+ "minimal_contract": {
2514
+ "type": "boolean",
2515
+ "default": False,
2516
+ "description": "Strict minimal contract mode.",
2517
+ },
2518
+ "format": {
2519
+ "type": "string",
2520
+ "enum": ["markdown", "json"],
2521
+ "default": "markdown",
2522
+ },
2523
+ },
2524
+ "required": ["target"],
2525
+ },
2526
+ },
2527
+ {
2528
+ "name": "repodna_history_snapshots",
2529
+ "description": "Lists cached historical architecture snapshots in the repository with health and module counts.",
2530
+ "inputSchema": {
2531
+ "type": "object",
2532
+ "properties": {
2533
+ "target": {
2534
+ "type": "string",
2535
+ "description": "Local Git repository directory.",
2536
+ },
2537
+ "limit": {"type": "integer", "default": 30},
2538
+ },
2539
+ "required": ["target"],
2540
+ },
2541
+ },
2542
+ {
2543
+ "name": "repodna_history_analyze",
2544
+ "description": "Extracts and returns an immutable architectural snapshot for a specific Git commit SHA.",
2545
+ "inputSchema": {
2546
+ "type": "object",
2547
+ "properties": {
2548
+ "target": {
2549
+ "type": "string",
2550
+ "description": "Local Git repository directory.",
2551
+ },
2552
+ "commit_sha": {"type": "string", "default": "HEAD"},
2553
+ "use_cache": {"type": "boolean", "default": True},
2554
+ },
2555
+ "required": ["target"],
2556
+ },
2557
+ },
2558
+ {
2559
+ "name": "repodna_history_diff",
2560
+ "description": "Computes architectural evolution diff between base and head Git commits (added/removed modules, renames, cycles, coupling).",
2561
+ "inputSchema": {
2562
+ "type": "object",
2563
+ "properties": {
2564
+ "target": {
2565
+ "type": "string",
2566
+ "description": "Local Git repository directory.",
2567
+ },
2568
+ "base_sha": {"type": "string", "default": "HEAD~1"},
2569
+ "head_sha": {"type": "string", "default": "HEAD"},
2570
+ },
2571
+ "required": ["target"],
2572
+ },
2573
+ },
2574
+ {
2575
+ "name": "repodna_history_timeline",
2576
+ "description": "Builds historical architecture evolution timeline across a sequence of Git commits.",
2577
+ "inputSchema": {
2578
+ "type": "object",
2579
+ "properties": {
2580
+ "target": {
2581
+ "type": "string",
2582
+ "description": "Local Git repository directory.",
2583
+ },
2584
+ "limit": {"type": "integer", "default": 20},
2585
+ },
2586
+ "required": ["target"],
2587
+ },
2588
+ },
2589
+ {
2590
+ "name": "repodna_history_evidence",
2591
+ "description": "Retrieves historical source snippet directly from a Git commit blob with cryptographic provenance.",
2592
+ "inputSchema": {
2593
+ "type": "object",
2594
+ "properties": {
2595
+ "target": {
2596
+ "type": "string",
2597
+ "description": "Local Git repository directory.",
2598
+ },
2599
+ "commit_sha": {"type": "string", "description": "Full 40-char commit SHA."},
2600
+ "file_path": {"type": "string", "description": "Relative file path."},
2601
+ "line_start": {"type": "integer", "default": 1},
2602
+ "line_end": {"type": "integer", "default": 50},
2603
+ },
2604
+ "required": ["target", "commit_sha", "file_path"],
2605
+ },
2606
+ },
2607
+ {
2608
+ "name": "repodna_refactoring_advisor",
2609
+ "description": "Generates deterministic, evidence-grounded architectural refactoring recommendations (cycles, coupling, layer violations, oversized hubs).",
2610
+ "inputSchema": {
2611
+ "type": "object",
2612
+ "properties": {
2613
+ "target": {
2614
+ "type": "string",
2615
+ "description": "Local repository directory or GitHub clone URL.",
2616
+ },
2617
+ "category": {
2618
+ "type": "string",
2619
+ "description": "Optional category filter: circular_dependency_reduction, high_coupling_module_review, layer_boundary_improvement, oversized_architectural_hub_review.",
2620
+ },
2621
+ "min_severity": {
2622
+ "type": "string",
2623
+ "description": "Minimum severity filter: low, medium, high, critical.",
2624
+ },
2625
+ "format": {
2626
+ "type": "string",
2627
+ "enum": ["json", "text"],
2628
+ "default": "json",
2629
+ "description": "Output format: JSON structure or human-readable summary text.",
2630
+ },
2631
+ "force": {
2632
+ "type": "boolean",
2633
+ "default": False,
2634
+ "description": "Bypass in-memory cache and re-analyze repository.",
2635
+ },
2636
+ },
2637
+ "required": ["target"],
2638
+ },
2639
+ },
2640
+ {
2641
+ "name": "repodna_live_status",
2642
+ "description": "Read-only live architecture session status, verified snapshot freshness, pending changes, and active risk count. Never starts watchers.",
2643
+ "inputSchema": {
2644
+ "type": "object",
2645
+ "properties": {
2646
+ "target": {"type": "string", "default": ".", "description": "Local repository directory."},
2647
+ "format": {"type": "string", "enum": ["json", "text"], "default": "json"},
2648
+ },
2649
+ "required": ["target"],
2650
+ },
2651
+ },
2652
+ {
2653
+ "name": "repodna_live_changes",
2654
+ "description": "Read-only recent verified working-tree architectural deltas from the active or recent live session timeline.",
2655
+ "inputSchema": {
2656
+ "type": "object",
2657
+ "properties": {
2658
+ "target": {"type": "string", "default": ".", "description": "Local repository directory."},
2659
+ "limit": {"type": "integer", "default": 20},
2660
+ "format": {"type": "string", "enum": ["json", "text"], "default": "json"},
2661
+ },
2662
+ "required": ["target"],
2663
+ },
2664
+ },
2665
+ {
2666
+ "name": "repodna_live_alerts",
2667
+ "description": "Read-only live architectural alerts (active, acknowledged, resolved, unknown) with evidence references.",
2668
+ "inputSchema": {
2669
+ "type": "object",
2670
+ "properties": {
2671
+ "target": {"type": "string", "default": ".", "description": "Local repository directory."},
2672
+ "status": {"type": "string", "enum": ["ACTIVE", "ACKNOWLEDGED", "RESOLVED", "UNKNOWN"]},
2673
+ "format": {"type": "string", "enum": ["json", "text"], "default": "json"},
2674
+ },
2675
+ "required": ["target"],
2676
+ },
2677
+ },
2678
+ {
2679
+ "name": "repodna_live_context",
2680
+ "description": "Token-budgeted read-only live architectural context with honest freshness disclosure, active risks, and recent working-tree changes.",
2681
+ "inputSchema": {
2682
+ "type": "object",
2683
+ "properties": {
2684
+ "target": {"type": "string", "default": ".", "description": "Local repository directory."},
2685
+ "max_tokens": {"type": "integer", "default": 1500},
2686
+ "format": {"type": "string", "enum": ["markdown", "json"], "default": "markdown"},
2687
+ },
2688
+ "required": ["target"],
2689
+ },
2690
+ },
2691
+ {
2692
+ "name": "repodna_code_quality",
2693
+ "description": "Read-only Deep Code Intelligence quality overview: findings summary, technical debt index, language capabilities, and honest limitations.",
2694
+ "inputSchema": {
2695
+ "type": "object",
2696
+ "properties": {
2697
+ "target": {"type": "string", "default": "."},
2698
+ "format": {"type": "string", "enum": ["json", "text"], "default": "json"},
2699
+ },
2700
+ "required": ["target"],
2701
+ },
2702
+ },
2703
+ {
2704
+ "name": "repodna_get_quality_findings",
2705
+ "description": "Paginated, filterable quality findings with stable finding IDs, confidence, evidence references, and rule metadata.",
2706
+ "inputSchema": {
2707
+ "type": "object",
2708
+ "properties": {
2709
+ "target": {"type": "string", "default": "."},
2710
+ "category": {"type": "string"},
2711
+ "severity": {"type": "string"},
2712
+ "language": {"type": "string"},
2713
+ "offset": {"type": "integer", "default": 0},
2714
+ "limit": {"type": "integer", "default": 25},
2715
+ },
2716
+ "required": ["target"],
2717
+ },
2718
+ },
2719
+ {
2720
+ "name": "repodna_symbol_complexity",
2721
+ "description": "Language-aware per-symbol cyclomatic and nesting-weighted complexity metrics with line-level contributors.",
2722
+ "inputSchema": {
2723
+ "type": "object",
2724
+ "properties": {
2725
+ "target": {"type": "string", "default": "."},
2726
+ "language": {"type": "string"},
2727
+ "file_path": {"type": "string"},
2728
+ "offset": {"type": "integer", "default": 0},
2729
+ "limit": {"type": "integer", "default": 25},
2730
+ },
2731
+ "required": ["target"],
2732
+ },
2733
+ },
2734
+ {
2735
+ "name": "repodna_find_duplicates",
2736
+ "description": "Verified Type-1 and Type-2 structural clone groups using bounded Winnowing fingerprinting and exact token verification.",
2737
+ "inputSchema": {
2738
+ "type": "object",
2739
+ "properties": {
2740
+ "target": {"type": "string", "default": "."},
2741
+ "language": {"type": "string"},
2742
+ "offset": {"type": "integer", "default": 0},
2743
+ "limit": {"type": "integer", "default": 20},
2744
+ },
2745
+ "required": ["target"],
2746
+ },
2747
+ },
2748
+ {
2749
+ "name": "repodna_unused_candidates",
2750
+ "description": "Conservative unused-code review candidates (never proven dead code) with framework, WinForms, and public API exclusions.",
2751
+ "inputSchema": {
2752
+ "type": "object",
2753
+ "properties": {
2754
+ "target": {"type": "string", "default": "."},
2755
+ "language": {"type": "string"},
2756
+ "offset": {"type": "integer", "default": 0},
2757
+ "limit": {"type": "integer", "default": 25},
2758
+ },
2759
+ "required": ["target"],
2760
+ },
2761
+ },
2762
+ {
2763
+ "name": "repodna_test_relationships",
2764
+ "description": "Static test-to-source relationship mapping across 10 ecosystems (NOT runtime code coverage).",
2765
+ "inputSchema": {
2766
+ "type": "object",
2767
+ "properties": {
2768
+ "target": {"type": "string", "default": "."},
2769
+ "relationship": {"type": "string"},
2770
+ "offset": {"type": "integer", "default": 0},
2771
+ "limit": {"type": "integer", "default": 25},
2772
+ },
2773
+ "required": ["target"],
2774
+ },
2775
+ },
2776
+ {
2777
+ "name": "repodna_symbol_change_impact",
2778
+ "description": "Symbol-level change impact analysis comparing current working tree against a base Git revision or snapshot.",
2779
+ "inputSchema": {
2780
+ "type": "object",
2781
+ "properties": {
2782
+ "target": {"type": "string", "default": "."},
2783
+ "base_ref": {"type": "string", "default": "HEAD~1"},
2784
+ },
2785
+ "required": ["target"],
2786
+ },
2787
+ },
2788
+ ]
2789
+ all_tools.extend(get_agent_mcp_tool_schemas())
2790
+ all_tools.extend(get_workspace_tool_schemas())
2791
+ return filter_tools_by_profile(all_tools, self.tool_profile)
2792
+
2793
+ def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
2794
+ """Direct dispatch for in-process tests and fallback handling."""
2795
+ if not isinstance(arguments, dict):
2796
+ return {
2797
+ "isError": True,
2798
+ "content": [
2799
+ {"type": "text", "text": f"Invalid arguments for {name}: expected JSON object."}
2800
+ ],
2801
+ }
2802
+ target = arguments.get("target", ".")
2803
+ force = bool(arguments.get("force", False))
2804
+ try:
2805
+ if name == "repodna_repository_overview":
2806
+ content = self.tool_repository_overview(
2807
+ target=target,
2808
+ format=arguments.get("format", "text"),
2809
+ force=force,
2810
+ )
2811
+ elif name == "repodna_architecture_map":
2812
+ content = self.tool_architecture_map(
2813
+ target=target,
2814
+ level=arguments.get("level", "clusters"),
2815
+ limit=int(arguments.get("limit", 30)),
2816
+ force=force,
2817
+ )
2818
+ elif name == "repodna_find_modules":
2819
+ content = self.tool_find_modules(
2820
+ target=target,
2821
+ query=arguments.get("query", ""),
2822
+ limit=int(arguments.get("limit", 10)),
2823
+ force=force,
2824
+ )
2825
+ elif name in ("repodna_module_dependencies", "repodna_dependencies"):
2826
+ dep_path = arguments.get("file_path") or arguments.get("module_path", "")
2827
+ content = self.tool_module_dependencies(
2828
+ target=target,
2829
+ file_path=dep_path,
2830
+ direction=arguments.get("direction", "outgoing"),
2831
+ depth=int(arguments.get("depth", 1)),
2832
+ force=force,
2833
+ )
2834
+ elif name in ("repodna_module_findings", "repodna_architecture_findings"):
2835
+ content = self.tool_module_findings(
2836
+ target=target,
2837
+ file_path=arguments.get("file_path"),
2838
+ rule_id=arguments.get("rule_id"),
2839
+ severity=arguments.get("severity"),
2840
+ force=force,
2841
+ )
2842
+ elif name == "repodna_architecture_diff":
2843
+ content = self.tool_architecture_diff(
2844
+ target=target,
2845
+ base_ref=arguments.get("base_ref", "HEAD~1"),
2846
+ head_ref=arguments.get("head_ref", "HEAD"),
2847
+ )
2848
+ elif name == "repodna_change_impact":
2849
+ content = self.tool_change_impact(
2850
+ target=target,
2851
+ changed_files=arguments.get("changed_files", []),
2852
+ max_depth=int(arguments.get("max_depth", 2)),
2853
+ force=force,
2854
+ )
2855
+ elif name in ("repodna_analysis_coverage", "repodna_explain_health"):
2856
+ content = self.tool_analysis_coverage(target=target, force=force)
2857
+ elif name in ("repodna_get_passport", "repodna_passport"):
2858
+ content = self.tool_get_passport(
2859
+ target=target,
2860
+ max_modules=int(arguments.get("max_modules", 150)),
2861
+ format=arguments.get("format", "json"),
2862
+ version=arguments.get("version", "2.0"),
2863
+ force=force,
2864
+ )
2865
+
2866
+ elif name in ("repodna_get_contract", "repodna_contract"):
2867
+ content = self.tool_get_contract(
2868
+ target=target,
2869
+ format=arguments.get("format", "yaml"),
2870
+ )
2871
+ elif name in ("repodna_check_contract", "repodna_contract_check"):
2872
+ content = self.tool_check_contract(
2873
+ target=target,
2874
+ mode=arguments.get("mode"),
2875
+ force=force,
2876
+ )
2877
+ elif name in ("repodna_pr_guardian", "repodna_guardian"):
2878
+ content = self.tool_pr_guardian(
2879
+ target=target,
2880
+ base_ref=arguments.get("base_ref", "HEAD~1"),
2881
+ head_ref=arguments.get("head_ref", "HEAD"),
2882
+ mode=arguments.get("mode"),
2883
+ format=arguments.get("format", "json"),
2884
+ )
2885
+ elif name in ("repodna_search_code", "repodna_search"):
2886
+ content = self.tool_search_code(
2887
+ target=target,
2888
+ query=arguments.get("query", ""),
2889
+ limit=int(arguments.get("limit", 10)),
2890
+ kind=arguments.get("kind"),
2891
+ path_filter=arguments.get("path_filter"),
2892
+ force=force,
2893
+ )
2894
+ elif name in ("repodna_find_symbol", "repodna_symbols"):
2895
+ content = self.tool_find_symbol(
2896
+ target=target,
2897
+ name=arguments.get("name"),
2898
+ kind=arguments.get("kind"),
2899
+ file_path=arguments.get("file_path"),
2900
+ container=arguments.get("container"),
2901
+ limit=int(arguments.get("limit", 25)),
2902
+ force=force,
2903
+ )
2904
+ elif name in ("repodna_trace_symbol", "repodna_trace"):
2905
+ content = self.tool_trace_symbol(
2906
+ target=target,
2907
+ symbol_name=arguments.get("symbol_name"),
2908
+ symbol_id=arguments.get("symbol_id"),
2909
+ file_path=arguments.get("file_path"),
2910
+ container_name=arguments.get("container") or arguments.get("container_name"),
2911
+ force=force,
2912
+ )
2913
+ elif name in ("repodna_get_evidence", "repodna_evidence"):
2914
+ content = self.tool_get_evidence(
2915
+ target=target,
2916
+ evidence_id=arguments.get("evidence_id"),
2917
+ file_path=arguments.get("file_path"),
2918
+ symbol_name=arguments.get("symbol_name"),
2919
+ check_staleness=bool(arguments.get("check_staleness", True)),
2920
+ limit=int(arguments.get("limit", 25)),
2921
+ force=force,
2922
+ )
2923
+ elif name in ("repodna_build_context", "repodna_context"):
2924
+ content = self.tool_build_context(
2925
+ target=target,
2926
+ mode=arguments.get("mode", "focused"),
2927
+ query=arguments.get("query"),
2928
+ target_files=arguments.get("target_files"),
2929
+ max_tokens=arguments.get("max_tokens", 2000),
2930
+ minimal_contract=bool(arguments.get("minimal_contract", False)),
2931
+ format=arguments.get("format", "markdown"),
2932
+ force=force,
2933
+ )
2934
+ elif name in ("repodna_history_snapshots", "repodna_history_snapshots_list"):
2935
+ content = self.tool_history_snapshots(
2936
+ target=target,
2937
+ limit=int(arguments.get("limit", 30)),
2938
+ )
2939
+ elif name in ("repodna_history_analyze", "repodna_history_snapshot"):
2940
+ content = self.tool_history_analyze(
2941
+ target=target,
2942
+ commit_sha=arguments.get("commit_sha", "HEAD"),
2943
+ use_cache=bool(arguments.get("use_cache", True)),
2944
+ )
2945
+ elif name in ("repodna_history_diff", "repodna_history_diff_snapshots"):
2946
+ content = self.tool_history_diff(
2947
+ target=target,
2948
+ base_sha=arguments.get("base_sha", "HEAD~1"),
2949
+ head_sha=arguments.get("head_sha", "HEAD"),
2950
+ )
2951
+ elif name in ("repodna_history_timeline", "repodna_history_evolution_timeline"):
2952
+ content = self.tool_history_timeline(
2953
+ target=target,
2954
+ limit=int(arguments.get("limit", 20)),
2955
+ )
2956
+ elif name in ("repodna_history_evidence", "repodna_history_evidence_blob"):
2957
+ content = self.tool_history_evidence(
2958
+ target=target,
2959
+ commit_sha=arguments.get("commit_sha", "HEAD"),
2960
+ file_path=arguments.get("file_path", ""),
2961
+ line_start=int(arguments.get("line_start", 1)),
2962
+ line_end=int(arguments.get("line_end", 50)),
2963
+ )
2964
+ elif name in ("repodna_refactoring_advisor", "repodna_advisor"):
2965
+ content = self.tool_refactoring_advisor(
2966
+ target=target,
2967
+ category=arguments.get("category"),
2968
+ min_severity=arguments.get("min_severity"),
2969
+ format=arguments.get("format", "json"),
2970
+ force=bool(arguments.get("force", False)),
2971
+ )
2972
+ elif name == "repodna_live_status":
2973
+ content = self.tool_live_status(
2974
+ target=target,
2975
+ format=arguments.get("format", "json"),
2976
+ )
2977
+ elif name == "repodna_live_changes":
2978
+ content = self.tool_live_changes(
2979
+ target=target,
2980
+ limit=int(arguments.get("limit", 20)),
2981
+ format=arguments.get("format", "json"),
2982
+ )
2983
+ elif name == "repodna_live_alerts":
2984
+ content = self.tool_live_alerts(
2985
+ target=target,
2986
+ status=arguments.get("status"),
2987
+ format=arguments.get("format", "json"),
2988
+ )
2989
+ elif name == "repodna_live_context":
2990
+ content = self.tool_live_context(
2991
+ target=target,
2992
+ max_tokens=int(arguments.get("max_tokens", 1500)),
2993
+ format=arguments.get("format", "markdown"),
2994
+ )
2995
+ elif name == "repodna_code_quality":
2996
+ content = self.tool_code_quality(
2997
+ target=target,
2998
+ format=arguments.get("format", "json"),
2999
+ )
3000
+ elif name == "repodna_get_quality_findings":
3001
+ content = self.tool_get_quality_findings(
3002
+ target=target,
3003
+ category=arguments.get("category"),
3004
+ severity=arguments.get("severity"),
3005
+ language=arguments.get("language"),
3006
+ offset=int(arguments.get("offset", 0)),
3007
+ limit=int(arguments.get("limit", 25)),
3008
+ )
3009
+ elif name == "repodna_symbol_complexity":
3010
+ content = self.tool_symbol_complexity(
3011
+ target=target,
3012
+ language=arguments.get("language"),
3013
+ file_path=arguments.get("file_path"),
3014
+ offset=int(arguments.get("offset", 0)),
3015
+ limit=int(arguments.get("limit", 25)),
3016
+ )
3017
+ elif name == "repodna_find_duplicates":
3018
+ content = self.tool_find_duplicates(
3019
+ target=target,
3020
+ language=arguments.get("language"),
3021
+ offset=int(arguments.get("offset", 0)),
3022
+ limit=int(arguments.get("limit", 20)),
3023
+ )
3024
+ elif name == "repodna_unused_candidates":
3025
+ content = self.tool_unused_candidates(
3026
+ target=target,
3027
+ language=arguments.get("language"),
3028
+ offset=int(arguments.get("offset", 0)),
3029
+ limit=int(arguments.get("limit", 25)),
3030
+ )
3031
+ elif name == "repodna_test_relationships":
3032
+ content = self.tool_test_relationships(
3033
+ target=target,
3034
+ relationship=arguments.get("relationship"),
3035
+ offset=int(arguments.get("offset", 0)),
3036
+ limit=int(arguments.get("limit", 25)),
3037
+ )
3038
+ elif name == "repodna_symbol_change_impact":
3039
+ content = self.tool_symbol_change_impact(
3040
+ target=target,
3041
+ base_ref=arguments.get("base_ref", "HEAD~1"),
3042
+ )
3043
+ elif name == "repodna_task_context":
3044
+ content = self.tool_task_context(
3045
+ target=target,
3046
+ task=str(arguments.get("task", "")),
3047
+ token_budget=int(arguments.get("token_budget", 2048)),
3048
+ target_model=str(arguments.get("target_model", "generic")),
3049
+ tokenizer=str(arguments.get("tokenizer", "auto")),
3050
+ profile=str(arguments.get("profile", "balanced")),
3051
+ offset=int(arguments.get("offset", 0)),
3052
+ known_block_ids=arguments.get("known_block_ids"),
3053
+ known_block_hashes=arguments.get("known_block_hashes"),
3054
+ previous_snapshot_id=arguments.get("previous_snapshot_id"),
3055
+ format=str(arguments.get("format", "json")),
3056
+ )
3057
+ elif name == "repodna_repository_map":
3058
+ content = self.tool_repository_map(
3059
+ target=target,
3060
+ mode=str(arguments.get("mode", "overview")),
3061
+ task=arguments.get("task"),
3062
+ focus_symbol=arguments.get("focus_symbol"),
3063
+ token_budget=int(arguments.get("token_budget", 2048)),
3064
+ max_modules=int(arguments.get("max_modules", 25)),
3065
+ )
3066
+ elif name == "repodna_expand_context":
3067
+ content = self.tool_expand_context(
3068
+ target=target,
3069
+ target_type=str(arguments.get("target_type", "file")),
3070
+ target_id=str(arguments.get("target_id", "")),
3071
+ snapshot_id=arguments.get("snapshot_id"),
3072
+ cursor=arguments.get("cursor"),
3073
+ token_budget=int(arguments.get("token_budget", 1024)),
3074
+ max_lines=int(arguments.get("max_lines", 80)),
3075
+ )
3076
+ elif name == "repodna_change_preflight":
3077
+ content = self.tool_change_preflight(
3078
+ target=target,
3079
+ intended_files=arguments.get("intended_files"),
3080
+ intended_symbols=arguments.get("intended_symbols"),
3081
+ operation_type=str(arguments.get("operation_type", "modify")),
3082
+ proposed_dependency_edges=arguments.get("proposed_dependency_edges"),
3083
+ expected_behavior=str(arguments.get("expected_behavior", "")),
3084
+ )
3085
+ elif name == "repodna_inspect_patch":
3086
+ content = self.tool_inspect_patch(
3087
+ target=target,
3088
+ patch_text=str(arguments.get("patch_text", "")),
3089
+ )
3090
+ elif name == "repodna_change_postflight":
3091
+ content = self.tool_change_postflight(
3092
+ target=target,
3093
+ intended_files=arguments.get("intended_files"),
3094
+ stale_evidence_ids=arguments.get("stale_evidence_ids"),
3095
+ )
3096
+ elif name == "repodna_verify_evidence":
3097
+ content = self.tool_verify_evidence(
3098
+ target=target,
3099
+ evidence_id=str(arguments.get("evidence_id", "")),
3100
+ expected_snapshot_id=arguments.get("expected_snapshot_id"),
3101
+ )
3102
+ elif name == "repodna_agent_capabilities":
3103
+ content = self.tool_agent_capabilities()
3104
+
3105
+ elif name in WORKSPACE_MCP_TOOL_NAMES:
3106
+ content = json.dumps(
3107
+ dispatch_workspace_tool(
3108
+ name,
3109
+ arguments,
3110
+ authorized_roots=self.allowed_roots,
3111
+ require_authorized_roots=True,
3112
+ ),
3113
+ indent=2,
3114
+ )
3115
+
3116
+ else:
3117
+ return {
3118
+ "isError": True,
3119
+ "content": [{"type": "text", "text": f"Unknown tool: '{name}'"}],
3120
+ }
3121
+
3122
+ return {
3123
+ "content": [{"type": "text", "text": content}],
3124
+ }
3125
+
3126
+ except SecurityValidationError as exc:
3127
+ _log(f"Security error in tool '{name}': [{exc.code}] {exc}")
3128
+ return {
3129
+ "isError": True,
3130
+ "content": [
3131
+ {"type": "text", "text": f"Error executing {name}: [{exc.code}] {exc}"}
3132
+ ],
3133
+ }
3134
+ except Exception as exc:
3135
+ code = getattr(exc, "code", None)
3136
+ prefix = f"[{code}] " if isinstance(code, str) and code else ""
3137
+ _log(f"Error in tool '{name}': {prefix}{exc}")
3138
+ return {
3139
+ "isError": True,
3140
+ "content": [{"type": "text", "text": f"Error executing {name}: {prefix}{exc}"}],
3141
+ }
3142
+
3143
+ def handle_request(self, request: dict[str, Any]) -> dict[str, Any] | None:
3144
+ """Processes raw JSON-RPC 2.0 requests with strict validation."""
3145
+ if not isinstance(request, dict):
3146
+ return {
3147
+ "jsonrpc": "2.0",
3148
+ "id": None,
3149
+ "error": {"code": -32600, "message": "Invalid Request: root must be JSON object."},
3150
+ }
3151
+
3152
+ msg_id = request.get("id")
3153
+ method = request.get("method")
3154
+ params = request.get("params", {})
3155
+
3156
+ if request.get("jsonrpc") != "2.0":
3157
+ return {
3158
+ "jsonrpc": "2.0",
3159
+ "id": msg_id,
3160
+ "error": {
3161
+ "code": -32600,
3162
+ "message": "Invalid Request: 'jsonrpc' version must be '2.0'.",
3163
+ },
3164
+ }
3165
+
3166
+ if not method or not isinstance(method, str):
3167
+ return {
3168
+ "jsonrpc": "2.0",
3169
+ "id": msg_id,
3170
+ "error": {
3171
+ "code": -32600,
3172
+ "message": "Invalid Request: 'method' string is required.",
3173
+ },
3174
+ }
3175
+
3176
+ if method == "initialize":
3177
+ req_ver = params.get("protocolVersion") if isinstance(params, dict) else None
3178
+ supported_versions = {"2024-11-05", "2025-03-26", "2025-06-18", "2026-07-28"}
3179
+ negotiated = req_ver if req_ver in supported_versions else PROTOCOL_VERSION
3180
+ return {
3181
+ "jsonrpc": "2.0",
3182
+ "id": msg_id,
3183
+ "result": {
3184
+ "protocolVersion": negotiated,
3185
+ "capabilities": {"tools": {}},
3186
+ "serverInfo": {
3187
+ "name": SERVER_NAME,
3188
+ "version": SERVER_VERSION,
3189
+ },
3190
+ },
3191
+ }
3192
+
3193
+ if method == "notifications/initialized":
3194
+ _log("Client initialized successfully.")
3195
+ return None
3196
+
3197
+ if method == "ping":
3198
+ return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
3199
+
3200
+ if method == "tools/list":
3201
+ return {
3202
+ "jsonrpc": "2.0",
3203
+ "id": msg_id,
3204
+ "result": {"tools": self.get_tools_list()},
3205
+ }
3206
+
3207
+ if method == "tools/call":
3208
+ tool_name = params.get("name", "")
3209
+ args = params.get("arguments", {})
3210
+ call_res = self.call_tool(tool_name, args)
3211
+ return {
3212
+ "jsonrpc": "2.0",
3213
+ "id": msg_id,
3214
+ "result": call_res,
3215
+ }
3216
+
3217
+ return {
3218
+ "jsonrpc": "2.0",
3219
+ "id": msg_id,
3220
+ "error": {"code": -32601, "message": f"Method not found: '{method}'"},
3221
+ }
3222
+
3223
+ def run_stdio(self) -> None:
3224
+ """Synchronous stdio event loop."""
3225
+ _log(f"RepoDNA MCP server listening on stdio (JSON-RPC 2.0 / {PROTOCOL_VERSION}).")
3226
+ while True:
3227
+ line = sys.stdin.readline()
3228
+ if not line:
3229
+ break
3230
+ line_str = line.strip()
3231
+ if not line_str:
3232
+ continue
3233
+ if len(line_str.encode("utf-8", errors="replace")) > MAX_RESPONSE_BYTES:
3234
+ err_resp = {
3235
+ "jsonrpc": "2.0",
3236
+ "id": None,
3237
+ "error": {"code": -32600, "message": "Request payload exceeds maximum allowed size."},
3238
+ }
3239
+ sys.stdout.write(json.dumps(err_resp) + "\n")
3240
+ sys.stdout.flush()
3241
+ continue
3242
+ try:
3243
+ req = json.loads(line_str)
3244
+ resp = self.handle_request(req)
3245
+ if resp is not None:
3246
+ sys.stdout.write(json.dumps(resp) + "\n")
3247
+ sys.stdout.flush()
3248
+ except json.JSONDecodeError as err:
3249
+ _log(f"JSON decode error: {err}")
3250
+ err_resp = {
3251
+ "jsonrpc": "2.0",
3252
+ "id": None,
3253
+ "error": {"code": -32700, "message": "Parse error"},
3254
+ }
3255
+ sys.stdout.write(json.dumps(err_resp) + "\n")
3256
+ sys.stdout.flush()
3257
+ except Exception as exc:
3258
+ _log(f"Fatal error in event loop: {exc}")
3259
+
3260
+
3261
+ def main() -> int:
3262
+ parser = argparse.ArgumentParser(description="RepoDNA MCP Server")
3263
+ parser.add_argument(
3264
+ "--allowed-root",
3265
+ action="append",
3266
+ dest="allowed_roots",
3267
+ help="Authorized workspace root directory (can be specified multiple times).",
3268
+ )
3269
+ parser.add_argument(
3270
+ "--tool-profile",
3271
+ choices=sorted(VALID_TOOL_PROFILES),
3272
+ default=None,
3273
+ help="Optional tool profile (full [default], minimal, architecture, code-intelligence).",
3274
+ )
3275
+ args, _ = parser.parse_known_args()
3276
+ roots = [Path(r) for r in args.allowed_roots] if args.allowed_roots else None
3277
+ server = RepoDNAMCPServer(allowed_roots=roots, tool_profile=args.tool_profile)
3278
+ server.run(transport="stdio")
3279
+ return 0
3280
+
3281
+
3282
+ if __name__ == "__main__":
3283
+ raise SystemExit(main())