tzero-mcp 11.0.0 → 11.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +56 -56
  2. package/CONTRIBUTING.md +71 -71
  3. package/LICENSE +21 -21
  4. package/README.md +64 -64
  5. package/bin/tzero-mcp.js +62 -62
  6. package/bin/tzero.js +61 -61
  7. package/index.d.ts +25 -25
  8. package/index.js +15 -15
  9. package/package.json +89 -88
  10. package/src/addmcp.py +1203 -1197
  11. package/src/app.py +1810 -1810
  12. package/src/main.py +60 -60
  13. package/src/pc_fixer_mcp.py +25 -25
  14. package/src/tzero/__init__.py +54 -54
  15. package/src/tzero/__main__.py +6 -6
  16. package/src/tzero/siber_akademi_icon.py +77 -77
  17. package/src/tzero/tzero_arch_test.py +463 -463
  18. package/src/tzero/tzero_benchmark.py +475 -475
  19. package/src/tzero/tzero_blackboard.py +257 -257
  20. package/src/tzero/tzero_bridge.py +546 -546
  21. package/src/tzero/tzero_budget.py +195 -195
  22. package/src/tzero/tzero_card.py +431 -0
  23. package/src/tzero/tzero_ci.py +153 -153
  24. package/src/tzero/tzero_commit.py +192 -192
  25. package/src/tzero/tzero_contracts.py +1093 -1093
  26. package/src/tzero/tzero_cost.py +166 -166
  27. package/src/tzero/tzero_dashboard.py +1960 -1960
  28. package/src/tzero/tzero_debt.py +461 -461
  29. package/src/tzero/tzero_deps.py +462 -462
  30. package/src/tzero/tzero_drift.py +208 -208
  31. package/src/tzero/tzero_explain.py +306 -306
  32. package/src/tzero/tzero_features.py +3024 -3024
  33. package/src/tzero/tzero_federation.py +299 -299
  34. package/src/tzero/tzero_fix.py +557 -228
  35. package/src/tzero/tzero_fixer/__init__.py +63 -63
  36. package/src/tzero/tzero_fixer/amalgamation.py +334 -334
  37. package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
  38. package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
  39. package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
  40. package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
  41. package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
  42. package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
  43. package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
  44. package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
  45. package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
  46. package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
  47. package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
  48. package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
  49. package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
  50. package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
  51. package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
  52. package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
  53. package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
  54. package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
  55. package/src/tzero/tzero_fixer/mcp_server.py +489 -489
  56. package/src/tzero/tzero_fixer/models.py +385 -385
  57. package/src/tzero/tzero_fixer/orchestrator.py +375 -375
  58. package/src/tzero/tzero_fixer/os_doctor.py +502 -502
  59. package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
  60. package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
  61. package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
  62. package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
  63. package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
  64. package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
  65. package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
  66. package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
  67. package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
  68. package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
  69. package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
  70. package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
  71. package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
  72. package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
  73. package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
  74. package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
  75. package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
  76. package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
  77. package/src/tzero/tzero_golden.py +319 -319
  78. package/src/tzero/tzero_graph_hud.html +338 -338
  79. package/src/tzero/tzero_graph_rag.py +263 -263
  80. package/src/tzero/tzero_growth.py +415 -0
  81. package/src/tzero/tzero_guard.py +251 -243
  82. package/src/tzero/tzero_hooks.py +565 -565
  83. package/src/tzero/tzero_infra.py +274 -274
  84. package/src/tzero/tzero_jarvis/__init__.py +134 -124
  85. package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
  86. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  87. package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
  88. package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
  89. package/src/tzero/tzero_jarvis/latent_press.py +137 -137
  90. package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
  91. package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
  92. package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
  93. package/src/tzero/tzero_jarvis/self_healing.py +308 -308
  94. package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
  95. package/src/tzero/tzero_jarvis/swarm.py +261 -261
  96. package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
  97. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
  98. package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
  99. package/src/tzero/tzero_lsp.py +634 -634
  100. package/src/tzero/tzero_mcp.py +5314 -5237
  101. package/src/tzero/tzero_mutation.py +358 -358
  102. package/src/tzero/tzero_neural_cortex.py +1425 -1425
  103. package/src/tzero/tzero_packer.py +577 -577
  104. package/src/tzero/tzero_patch.py +624 -624
  105. package/src/tzero/tzero_pc_fixer.py +12699 -12699
  106. package/src/tzero/tzero_pipe.py +95 -95
  107. package/src/tzero/tzero_polyglot.py +799 -799
  108. package/src/tzero/tzero_proxy.py +127 -127
  109. package/src/tzero/tzero_reachability.py +272 -272
  110. package/src/tzero/tzero_replay.py +141 -141
  111. package/src/tzero/tzero_rust_bridge.py +198 -198
  112. package/src/tzero/tzero_scip.py +368 -368
  113. package/src/tzero/tzero_security.py +573 -573
  114. package/src/tzero/tzero_semantic_merge.py +189 -189
  115. package/src/tzero/tzero_snapshot.py +471 -471
  116. package/src/tzero/tzero_stubs.py +313 -313
  117. package/src/tzero/tzero_subagent_engine.py +459 -459
  118. package/src/tzero/tzero_superdesign.py +774 -774
  119. package/src/tzero/tzero_sync.py +241 -241
  120. package/src/tzero/tzero_task_benchmark.py +506 -458
  121. package/src/tzero/tzero_tui.py +313 -313
  122. package/src/tzero/tzero_turbo.py +264 -264
  123. package/src/tzero/tzero_v3.py +9997 -9900
  124. package/src/tzero.py +6 -6
  125. package/src/tzero_mcp.py +25 -0
  126. package/test/package.test.js +55 -55
package/src/addmcp.py CHANGED
@@ -1,1197 +1,1203 @@
1
- # -*- coding: utf-8 -*-
2
- """Install the bundled T-Zero MCP server into detected IDE configurations.
3
-
4
- Supports both a clean Dark GUI and a headless CLI (--all, --list, --targets).
5
- Automatically copies the standalone TZeroMCP runtime or configures the Python script,
6
- guaranteeing zero configuration headaches on any computer.
7
-
8
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
9
- """
10
-
11
- import argparse
12
- import hashlib
13
- import json
14
- import re
15
- import os
16
- import shutil
17
- import sys
18
- import tempfile
19
- from dataclasses import dataclass
20
- from datetime import datetime
21
- from pathlib import Path
22
- from typing import Callable, Dict, List, Optional, Tuple
23
-
24
-
25
- APP_VERSION = "11.0.0"
26
- SERVER_NAME = "tzero"
27
- SERVER_FILENAME = "TZeroMCP.exe"
28
-
29
-
30
- def _attach_windows_console() -> None:
31
- """If run from CMD or PowerShell on Windows with --noconsole, attach parent console."""
32
- if os.name == "nt":
33
- try:
34
- import ctypes
35
- if ctypes.windll.kernel32.AttachConsole(-1):
36
- if sys.stdout is None or getattr(sys.stdout, "closed", True):
37
- sys.stdout = open("CONOUT$", "w", encoding="utf-8", errors="replace")
38
- if sys.stderr is None or getattr(sys.stderr, "closed", True):
39
- sys.stderr = open("CONOUT$", "w", encoding="utf-8", errors="replace")
40
- except Exception:
41
- pass
42
-
43
-
44
- @dataclass(frozen=True)
45
- class ClientTarget:
46
- key: str
47
- name: str
48
- config_path: Path
49
- root_key: str
50
- detected: bool
51
-
52
-
53
- def _get_antigravity_config_path(home: Path) -> Path:
54
- """Resolves primary Google Antigravity MCP config path."""
55
- config_in_config = home / ".gemini" / "config" / "mcp_config.json"
56
- if config_in_config.exists() or (home / ".gemini" / "config").exists():
57
- return config_in_config
58
- return home / ".gemini" / "antigravity" / "mcp_config.json"
59
-
60
-
61
- def _get_claude_desktop_config_path(app_data: Path, local_app_data: Path) -> Tuple[Path, bool]:
62
- """Resolves Claude Desktop configuration path, handling both MSIX packages and standard AppData."""
63
- # 1. Standard AppData Roaming
64
- standard_cfg = app_data / "Claude" / "claude_desktop_config.json"
65
- if standard_cfg.exists():
66
- return standard_cfg, True
67
-
68
- # 2. Windows Store / MSIX Package sandboxed Roaming
69
- packages_dir = local_app_data / "Packages"
70
- if packages_dir.is_dir():
71
- for claude_pkg in packages_dir.glob("Claude_*"):
72
- candidate = claude_pkg / "LocalCache" / "Roaming" / "Claude" / "claude_desktop_config.json"
73
- if candidate.exists() or (claude_pkg / "LocalCache" / "Roaming" / "Claude").is_dir():
74
- return candidate, True
75
-
76
- detected = any([
77
- (app_data / "Claude").exists(),
78
- (local_app_data / "Programs" / "Claude" / "Claude.exe").exists(),
79
- bool(list(packages_dir.glob("Claude_*"))) if packages_dir.is_dir() else False,
80
- ])
81
- return standard_cfg, detected
82
-
83
-
84
- def build_client_targets(
85
- home: Optional[Path] = None,
86
- app_data: Optional[Path] = None,
87
- local_app_data: Optional[Path] = None,
88
- which: Callable[[str], Optional[str]] = shutil.which,
89
- ) -> List[ClientTarget]:
90
- """Return known per-user MCP configs and whether their client is installed."""
91
- home = Path(home or Path.home())
92
- app_data = Path(app_data or os.environ.get("APPDATA", home / "AppData/Roaming"))
93
- local_app_data = Path(
94
- local_app_data or os.environ.get("LOCALAPPDATA", home / "AppData/Local")
95
- )
96
- vscode_user = app_data / "Code" / "User"
97
- vscode_extensions = home / ".vscode" / "extensions"
98
-
99
- def any_path_exists(*paths: Path) -> bool:
100
- return any(path.exists() for path in paths)
101
-
102
- def extension_installed(prefix: str) -> bool:
103
- return bool(list(vscode_extensions.glob(f"{prefix}-*")))
104
-
105
- antigravity_config = _get_antigravity_config_path(home)
106
- claude_config, claude_detected = _get_claude_desktop_config_path(app_data, local_app_data)
107
-
108
- return [
109
- ClientTarget(
110
- "cursor",
111
- "Cursor",
112
- home / ".cursor" / "mcp.json",
113
- "mcpServers",
114
- any_path_exists(
115
- home / ".cursor",
116
- app_data / "Cursor",
117
- local_app_data / "Programs" / "Cursor" / "Cursor.exe",
118
- ),
119
- ),
120
- ClientTarget(
121
- "vscode",
122
- "Visual Studio Code / Copilot",
123
- home / ".copilot" / "mcp-config.json",
124
- "mcpServers",
125
- any_path_exists(
126
- app_data / "Code",
127
- local_app_data / "Programs" / "Microsoft VS Code" / "Code.exe",
128
- )
129
- or which("code") is not None,
130
- ),
131
- ClientTarget(
132
- "claude-desktop",
133
- "Claude Desktop",
134
- claude_config,
135
- "mcpServers",
136
- claude_detected,
137
- ),
138
- ClientTarget(
139
- "antigravity",
140
- "Google Antigravity",
141
- antigravity_config,
142
- "mcpServers",
143
- any_path_exists(
144
- home / ".gemini" / "config",
145
- home / ".gemini" / "antigravity",
146
- local_app_data / "Programs" / "Antigravity" / "Antigravity.exe",
147
- ),
148
- ),
149
- ClientTarget(
150
- "claude-code",
151
- "Claude Code",
152
- home / ".claude.json",
153
- "mcpServers",
154
- home.joinpath(".claude.json").exists() or which("claude") is not None,
155
- ),
156
- ClientTarget(
157
- "cline",
158
- "Cline",
159
- vscode_user
160
- / "globalStorage"
161
- / "saoudrizwan.claude-dev"
162
- / "settings"
163
- / "cline_mcp_settings.json",
164
- "mcpServers",
165
- (vscode_user / "globalStorage" / "saoudrizwan.claude-dev").exists()
166
- or extension_installed("saoudrizwan.claude-dev"),
167
- ),
168
- ClientTarget(
169
- "roo-code",
170
- "Roo Code",
171
- vscode_user
172
- / "globalStorage"
173
- / "rooveterinaryinc.roo-cline"
174
- / "settings"
175
- / "mcp_settings.json",
176
- "mcpServers",
177
- (vscode_user / "globalStorage" / "rooveterinaryinc.roo-cline").exists()
178
- or extension_installed("rooveterinaryinc.roo-cline"),
179
- ),
180
- ClientTarget(
181
- "windsurf",
182
- "Windsurf",
183
- home / ".codeium" / "windsurf" / "mcp_config.json",
184
- "mcpServers",
185
- any_path_exists(
186
- home / ".codeium" / "windsurf",
187
- app_data / "Windsurf",
188
- local_app_data / "Programs" / "Windsurf" / "Windsurf.exe",
189
- )
190
- or which("windsurf") is not None,
191
- ),
192
- ClientTarget(
193
- "gemini-cli",
194
- "Gemini CLI",
195
- home / ".gemini" / "settings.json",
196
- "mcpServers",
197
- home.joinpath(".gemini", "settings.json").exists()
198
- or which("gemini") is not None,
199
- ),
200
- ClientTarget(
201
- "zed",
202
- "Zed Editor",
203
- (app_data / "Zed" / "settings.json") if os.name == "nt" else (home / ".config" / "zed" / "settings.json"),
204
- "context_servers",
205
- any_path_exists(
206
- app_data / "Zed",
207
- home / ".config" / "zed",
208
- local_app_data / "Programs" / "Zed" / "Zed.exe",
209
- )
210
- or which("zed") is not None,
211
- ),
212
- ClientTarget(
213
- "continue",
214
- "Continue (VS Code / JetBrains)",
215
- home / ".continue" / "config.json",
216
- "mcpServers",
217
- (home / ".continue").exists() or any_path_exists(home / ".continue" / "config.json"),
218
- ),
219
- ]
220
-
221
-
222
- def server_entry(target: ClientTarget, server_path: Path) -> Dict[str, object]:
223
- """Generates the MCP configuration dictionary block for the target."""
224
- if server_path.suffix.lower() == ".py":
225
- entry: Dict[str, object] = {
226
- "command": sys.executable,
227
- "args": [str(server_path.resolve())],
228
- }
229
- else:
230
- entry: Dict[str, object] = {
231
- "command": str(server_path.resolve()),
232
- "args": [],
233
- }
234
- if target.root_key == "servers":
235
- entry["type"] = "stdio"
236
- return entry
237
-
238
-
239
- def _backup_path(path: Path) -> Path:
240
- timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
241
- return path.with_name(f"{path.name}.backup-{timestamp}")
242
-
243
-
244
- def merge_server_config(
245
- target: ClientTarget, server_path: Path, server_name: str = SERVER_NAME
246
- ) -> Dict[str, object]:
247
- """Safely merge one server entry, keeping the rest of the client's config."""
248
- config: Dict[str, object] = {}
249
- if target.config_path.exists():
250
- with target.config_path.open("r", encoding="utf-8-sig") as config_file:
251
- raw_text = config_file.read()
252
- try:
253
- loaded = json.loads(raw_text)
254
- except Exception:
255
- cleaned = re.sub(r"//.*", "", raw_text)
256
- cleaned = re.sub(r",\s*([\]}])", r"\1", cleaned)
257
- loaded = json.loads(cleaned)
258
- if not isinstance(loaded, dict):
259
- raise ValueError("Configuration root must be a JSON object")
260
- config = loaded
261
-
262
- servers = config.get(target.root_key, {})
263
- if not isinstance(servers, dict):
264
- raise ValueError(f"'{target.root_key}' must be a JSON object")
265
-
266
- entry = server_entry(target, server_path)
267
- if servers.get(server_name) == entry:
268
- if target.key == "antigravity":
269
- _sync_alternate_antigravity_config(target, server_path, server_name)
270
- elif target.key == "claude-desktop":
271
- _sync_alternate_claude_desktop_config(target, server_path, server_name)
272
- return {"status": "unchanged", "backup": None}
273
-
274
- backup = None
275
- if target.config_path.exists():
276
- backup = _backup_path(target.config_path)
277
- shutil.copy2(target.config_path, backup)
278
-
279
- updated_servers = dict(servers)
280
- updated_servers[server_name] = entry
281
- config[target.root_key] = updated_servers
282
- target.config_path.parent.mkdir(parents=True, exist_ok=True)
283
-
284
- temporary_path = None
285
- try:
286
- with tempfile.NamedTemporaryFile(
287
- "w",
288
- encoding="utf-8",
289
- dir=str(target.config_path.parent),
290
- prefix=f".{target.config_path.name}.",
291
- suffix=".tmp",
292
- delete=False,
293
- ) as temporary_file:
294
- json.dump(config, temporary_file, indent=2, ensure_ascii=False)
295
- temporary_file.write("\n")
296
- temporary_path = Path(temporary_file.name)
297
- os.replace(temporary_path, target.config_path)
298
- finally:
299
- if temporary_path is not None and temporary_path.exists():
300
- temporary_path.unlink()
301
-
302
- # If this is Google Antigravity or Claude Desktop, sync alternate config paths if present
303
- if target.key == "antigravity":
304
- _sync_alternate_antigravity_config(target, server_path, server_name)
305
- elif target.key == "claude-desktop":
306
- _sync_alternate_claude_desktop_config(target, server_path, server_name)
307
-
308
- return {"status": "installed", "backup": backup}
309
-
310
-
311
- def _sync_alternate_antigravity_config(
312
- target: ClientTarget, server_path: Path, server_name: str
313
- ) -> None:
314
- """Keep ~/.gemini/config/mcp_config.json and ~/.gemini/antigravity/mcp_config.json in sync."""
315
- try:
316
- home = Path.home()
317
- alt_paths = [
318
- home / ".gemini" / "config" / "mcp_config.json",
319
- home / ".gemini" / "antigravity" / "mcp_config.json",
320
- ]
321
- entry = server_entry(target, server_path)
322
- for alt_path in alt_paths:
323
- if alt_path.resolve() == target.config_path.resolve():
324
- continue
325
- if alt_path.parent.exists():
326
- cfg: Dict[str, object] = {}
327
- if alt_path.exists():
328
- try:
329
- with alt_path.open("r", encoding="utf-8-sig") as fp:
330
- cfg = json.load(fp)
331
- except Exception:
332
- continue
333
- if not isinstance(cfg, dict):
334
- cfg = {}
335
- servers = cfg.setdefault("mcpServers", {})
336
- if isinstance(servers, dict) and servers.get(server_name) != entry:
337
- servers[server_name] = entry
338
- alt_path.parent.mkdir(parents=True, exist_ok=True)
339
- with alt_path.open("w", encoding="utf-8") as fp:
340
- json.dump(cfg, fp, indent=2, ensure_ascii=False)
341
- fp.write("\n")
342
- # Also install the /tzero slash skills, plugin, and instructions into Antigravity
343
- _install_antigravity_skill(server_path)
344
- except Exception:
345
- pass
346
-
347
-
348
- def _install_antigravity_skill(server_path: Optional[Path] = None) -> None:
349
- """Installs the /tzero slash skills, Antigravity plugin, and MCP instructions."""
350
- try:
351
- home = Path.home()
352
- # 1. Global skills directories
353
- skills_targets = [
354
- home / ".gemini" / "config" / "skills",
355
- home / ".gemini" / "skills",
356
- ]
357
-
358
- # If running within a git or project workspace, also install workspace skill
359
- cwd = Path.cwd()
360
- if (cwd / ".git").is_dir() or (cwd / ".agents").is_dir():
361
- skills_targets.append(cwd / ".agents" / "skills")
362
-
363
- all_skills = {
364
- "tzero": _ANTIGRAVITY_SKILL_CONTENT,
365
- "tzero-tree": _ANTIGRAVITY_TREE_SKILL_CONTENT,
366
- "tzero-audit": _ANTIGRAVITY_AUDIT_SKILL_CONTENT,
367
- "tzero-arch": _ANTIGRAVITY_ARCH_SKILL_CONTENT,
368
- }
369
-
370
- for tool_name, (desc, action) in _MCP_TOOLS_SPEC.items():
371
- all_skills[tool_name] = f"""---
372
- name: {tool_name}
373
- description: >-
374
- {desc}
375
- Activate when the user types "/{tool_name}" or asks to run {tool_name}.
376
- ---
377
-
378
- # /{tool_name} — T-Zero MCP Tool
379
-
380
- {desc}
381
-
382
- ## Execution
383
- {action}
384
- """
385
-
386
- for target_base in skills_targets:
387
- for skill_name, content in all_skills.items():
388
- s_dir = target_base / skill_name
389
- s_dir.mkdir(parents=True, exist_ok=True)
390
- (s_dir / "SKILL.md").write_text(content, encoding="utf-8")
391
-
392
- # 2. Antigravity Plugin (~/.gemini/config/plugins/tzero)
393
- plugin_dir = home / ".gemini" / "config" / "plugins" / "tzero"
394
- plugin_dir.mkdir(parents=True, exist_ok=True)
395
- (plugin_dir / "plugin.json").write_text(_ANTIGRAVITY_PLUGIN_JSON, encoding="utf-8")
396
- (plugin_dir / "installed_version.json").write_text('{"version": "4.1.0"}\n', encoding="utf-8")
397
-
398
- # Plugin skills
399
- for skill_name, content in all_skills.items():
400
- p_skill_dir = plugin_dir / "skills" / skill_name
401
- p_skill_dir.mkdir(parents=True, exist_ok=True)
402
- (p_skill_dir / "SKILL.md").write_text(content, encoding="utf-8")
403
-
404
- # Plugin rules
405
- p_rules_dir = plugin_dir / "rules"
406
- p_rules_dir.mkdir(parents=True, exist_ok=True)
407
- (p_rules_dir / "tzero-token-optimization.md").write_text(_ANTIGRAVITY_RULE_CONTENT, encoding="utf-8")
408
-
409
- # Plugin mcp_config.json
410
- cmd = str(server_path.resolve()) if server_path else str(home / "AppData" / "Local" / "TZeroAlgorithm" / SERVER_FILENAME)
411
- plugin_mcp = {
412
- "mcpServers": {
413
- SERVER_NAME: {
414
- "command": cmd,
415
- "args": []
416
- }
417
- }
418
- }
419
- (plugin_dir / "mcp_config.json").write_text(json.dumps(plugin_mcp, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
420
-
421
- # 3. Enable plugin in ~/.gemini/config/config.json
422
- cfg_file = home / ".gemini" / "config" / "config.json"
423
- if cfg_file.exists():
424
- try:
425
- cfg_data = json.loads(cfg_file.read_text(encoding="utf-8-sig"))
426
- if isinstance(cfg_data, dict):
427
- plugins_dict = cfg_data.setdefault("plugins", {})
428
- if isinstance(plugins_dict, dict) and "tzero" not in plugins_dict:
429
- plugins_dict["tzero"] = {"enabled": True}
430
- cfg_file.write_text(json.dumps(cfg_data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
431
- except Exception:
432
- pass
433
-
434
- # 4. MCP instructions in ~/.gemini/antigravity-ide/mcp/tzero/instructions.md
435
- ide_mcp_dir = home / ".gemini" / "antigravity-ide" / "mcp" / SERVER_NAME
436
- if ide_mcp_dir.is_dir():
437
- (ide_mcp_dir / "instructions.md").write_text(_ANTIGRAVITY_MCP_INSTRUCTIONS, encoding="utf-8")
438
-
439
- except Exception:
440
- pass
441
-
442
-
443
- _ANTIGRAVITY_SKILL_CONTENT = """---
444
- name: tzero
445
- description: >-
446
- Enterprise-Grade Codebase Context Architect, AST Signatures Analyzer, & Token Reducer.
447
- Activate when the user types "/tzero", asks to reduce tokens, scan codebase architecture,
448
- audit code smells, analyze change impact, enforce architectural boundaries, or optimize prompt context for LLMs.
449
- ---
450
-
451
- # /tzero — Siber Akademi T-Zero Context Engine
452
-
453
- Enterprise-Grade Codebase Context Architect, AST Signatures Analyzer, and Token Reducer.
454
- Cuts LLM context ingestion overhead by up to 95% while preserving structural fidelity for AI agents.
455
-
456
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
457
- Repository: https://github.com/toprakahmetaydogmus/TZeroAlgorithm
458
-
459
- ## Slash Command Modes
460
-
461
- When the user enters `/tzero [subcommand]` or asks for T-Zero assistance, dispatch to the matching capability:
462
-
463
- | Subcommand | Description | Action / Tool |
464
- |:---|:---|:---|
465
- | `/tzero` or `/tzero tree` | Builds full multi-tier hierarchical context tree (T-1 to T-4) with ultra token pruning. | Call `get_project_context_tree` MCP tool |
466
- | `/tzero audit` | Runs AST static code smell check and checks for 100% Zero-Leak security (hardcoded secrets). | Call `audit_codebase_quality` MCP tool |
467
- | `/tzero arch` | Generates system architecture specification (`ARCHITECTURE.md`) with live Mermaid diagrams. | Call `generate_architecture_blueprint` MCP tool |
468
- | `/tzero deps [file]` | Traces internal & external module import topology and dependency graphs. | Call `query_module_dependencies` MCP tool |
469
- | `/tzero impact <symbol>` | Analyzes change impact and blast radius (0-100 score) before modifying a class/function. | Call `analyze_change_impact` MCP tool |
470
- | `/tzero rules` | Generates AI agent instruction files (`.cursorrules`, `.cursor/rules/*.mdc`, `.clinerules`). | Call `export_agent_rules` MCP tool |
471
- | `/tzero search <query>` | Performs 100% private local BM25 hybrid semantic code search without cloud embedding APIs. | Call `search_codebase_semantic` MCP tool |
472
- | `/tzero savings` | Computes quantitative token reduction metrics and team financial ROI savings (USD/month). | Call `get_token_savings_metrics` MCP tool |
473
- | `/tzero boundaries` | Enforces T-4 architectural boundaries defined in `tzero.rules.json` to prevent architectural erosion. | Call `enforce_architecture_boundaries` MCP tool |
474
- | `/tzero repomap` | Generates ultra-compact AST symbol token map for chat context windows. | Call `generate_repo_map` MCP tool |
475
- | `/tzero duplicity` | Scans workspace for duplicate or copy-pasted code blocks (6+ lines) across modules. | Call `find_code_duplicity` MCP tool |
476
- | `/tzero helpers <query>` | Discovers reusable repository helpers & guards against reinventing existing functions. | Call `suggest_reusable_helpers` MCP tool |
477
- | `/tzero doctor` | Inspects environment, Python runtime, and dependencies. | Run `python -m tzero_deps` or CLI `--doctor` |
478
-
479
- ## Execution Guidelines
480
-
481
- 1. **Prefer Native MCP Tools:** When the `tzero` MCP server is registered, invoke the corresponding MCP tool directly (`get_project_context_tree`, `audit_codebase_quality`, etc.).
482
- 2. **Fallback to CLI/Engine:** If MCP is temporarily unavailable, use the local CLI `tzero_v3.py` or `TZeroAlgorithm.exe` with matching flags (`--scan`, `--audit`, `--export-arch`, etc.).
483
- 3. **100% Zero-Leak Guarantee:** Never output, log, or commit sensitive API keys or user credentials.
484
- 4. **Summary & Presentation:** Format the output with clear GitHub-style Markdown, tables, and alerts (`> [!TIP]`, `> [!IMPORTANT]`).
485
- """
486
-
487
- _ANTIGRAVITY_TREE_SKILL_CONTENT = """---
488
- name: tzero-tree
489
- description: >-
490
- Generate multi-tier hierarchical AST context tree with up to 95% token reduction for AI context ingestion.
491
- Activate when the user types "/tzero-tree" or asks to build a code tree.
492
- ---
493
-
494
- # /tzero-tree — AST Hierarchical Context Tree Generator
495
-
496
- Generate a multi-tier pruned AST context tree to provide AI agents with full architectural understanding at up to 95% lower token cost.
497
-
498
- ## Modes & Tiers
499
- - **Tier 1 (T-1):** High-level architectural map & entry points.
500
- - **Tier 2 (T-2):** Public API & class/function signatures with types.
501
- - **Tier 3 (T-3):** Full signatures, method contracts, and docstrings.
502
- - **Tier 4 (T-4):** Full AST graph with import dependencies.
503
-
504
- ## Execution
505
- Call the `get_project_context_tree` MCP tool with the target path (default: current workspace) and desired tier (default: `T-2`).
506
- """
507
-
508
- _ANTIGRAVITY_AUDIT_SKILL_CONTENT = """---
509
- name: tzero-audit
510
- description: >-
511
- Run AST static code analysis, code smells check, cyclomatic complexity report, and 100% Zero-Leak security audit for hardcoded secrets.
512
- Activate when the user types "/tzero-audit" or asks to audit code quality.
513
- ---
514
-
515
- # /tzero-audit — AST Code Quality & Zero-Leak Security Audit
516
-
517
- Perform a comprehensive AST quality audit and verify 100% Zero-Leak security:
518
- 1. **Code Smells:** Functions >50 lines, classes >300 lines, high complexity.
519
- 2. **Dead Code:** Unused imports and unreferenced private functions.
520
- 3. **Security (Zero-Leak):** High-entropy strings, hardcoded API keys, tokens, and credentials.
521
-
522
- ## Execution
523
- Call the `audit_codebase_quality` MCP tool on the target path (default: `.`).
524
- """
525
-
526
- _ANTIGRAVITY_ARCH_SKILL_CONTENT = """---
527
- name: tzero-arch
528
- description: >-
529
- Generate complete system architecture specification (ARCHITECTURE.md) with live Mermaid component diagrams.
530
- Activate when the user types "/tzero-arch" or asks for system architecture blueprint.
531
- ---
532
-
533
- # /tzero-arch — System Architecture Blueprint Generator
534
-
535
- Generate an enterprise-grade architectural specification:
536
- 1. Module decomposition and layer boundaries.
537
- 2. Inter-module import topology.
538
- 3. Interactive Mermaid diagram showing system component relationships.
539
- 4. Auto-exports or updates `ARCHITECTURE.md`.
540
-
541
- ## Execution
542
- Call the `generate_architecture_blueprint` MCP tool on the target path (default: `.`).
543
- """
544
-
545
- _MCP_TOOLS_SPEC = {
546
- "get_project_context_tree": (
547
- "Scans target project directory and builds an enterprise-grade multi-tier T-Zero hierarchical context tree (T-1 to T-4) with up to 95% token reduction.",
548
- "Invoke the `get_project_context_tree` MCP tool with arguments `{\"project_root\": \".\", \"reduction_mode\": \"ultra\"}`."
549
- ),
550
- "query_module_dependencies": (
551
- "Analyzes import/export dependencies, module relationships, and internal vs external package dependencies across codebase or for a specific file.",
552
- "Invoke the `query_module_dependencies` MCP tool."
553
- ),
554
- "query_architecture_boundaries": (
555
- "Retrieves active T-4 architectural boundaries, operational constraints, and 100% Zero-Leak security rules.",
556
- "Invoke the `query_architecture_boundaries` MCP tool."
557
- ),
558
- "generate_architecture_blueprint": (
559
- "Generates a complete system architecture specification (ARCHITECTURE.md) including auto-generated Mermaid topology diagrams.",
560
- "Invoke the `generate_architecture_blueprint` MCP tool."
561
- ),
562
- "generate_repo_map": (
563
- "Generates an ultra-compact AST symbol token map for chat context windows.",
564
- "Invoke the `generate_repo_map` MCP tool."
565
- ),
566
- "audit_codebase_quality": (
567
- "Performs an AST static code smell audit and 100% Zero-Leak security check for hardcoded secret leaks across workspace files.",
568
- "Invoke the `audit_codebase_quality` MCP tool."
569
- ),
570
- "find_code_duplicity": (
571
- "Scans workspace for duplicate or copy-pasted code blocks (6+ lines) across modules.",
572
- "Invoke the `find_code_duplicity` MCP tool."
573
- ),
574
- "estimate_token_cost": (
575
- "Calculates exact token cost comparison across OpenAI, Anthropic, Gemini, DeepSeek models.",
576
- "Invoke the `estimate_token_cost` MCP tool."
577
- ),
578
- "analyze_change_impact": (
579
- "Analyzes change blast radius (0-100 score) and downstream dependents before modifying a class/function.",
580
- "Invoke the `analyze_change_impact` MCP tool."
581
- ),
582
- "enforce_architecture_boundaries": (
583
- "Enforces architectural boundary rules defined in tzero.rules.json to prevent architectural erosion.",
584
- "Invoke the `enforce_architecture_boundaries` MCP tool."
585
- ),
586
- "search_codebase_semantic": (
587
- "Performs 100% private local BM25 hybrid semantic code search across codebase without cloud embedding APIs.",
588
- "Invoke the `search_codebase_semantic` MCP tool."
589
- ),
590
- "export_agent_rules": (
591
- "Exports AI agent rule specifications (.cursorrules, .clinerules, .cursor/rules/*.mdc).",
592
- "Invoke the `export_agent_rules` MCP tool."
593
- ),
594
- "get_token_savings_metrics": (
595
- "Computes quantitative token reduction metrics and monthly team financial ROI savings.",
596
- "Invoke the `get_token_savings_metrics` MCP tool."
597
- ),
598
- "get_incremental_diff_context": (
599
- "Extracts ultra-compact PR diff context with modified symbols and downstream blast radius for code reviews.",
600
- "Invoke the `get_incremental_diff_context` MCP tool."
601
- ),
602
- "prune_code_snippet": (
603
- "Prunes arbitrary in-memory code snippets into compact AST signatures on-the-fly (80-95% reduction).",
604
- "Invoke the `prune_code_snippet` MCP tool."
605
- ),
606
- "verify_zero_leak_security": (
607
- "100% Zero-Leak security scanner for hardcoded API keys and secrets across workspace files.",
608
- "Invoke the `verify_zero_leak_security` MCP tool."
609
- ),
610
- "verify_hallucination_guard": (
611
- "Eliminates AI coding hallucinations before code is written by validating imports and function call signatures against workspace AST.",
612
- "Invoke the `verify_hallucination_guard` MCP tool with proposed code."
613
- ),
614
- "get_smart_skeleton_context": (
615
- "Focus-aware dynamic skeletonizer delivering full focus implementation with surrounding 1st-degree AST interface skeletons.",
616
- "Invoke the `get_smart_skeleton_context` MCP tool with focus file/symbol."
617
- ),
618
- "rank_repository_pagerank": (
619
- "Identifies repository architectural backbone and module centrality using graph-theory PageRank over AST topologies.",
620
- "Invoke the `rank_repository_pagerank` MCP tool."
621
- ),
622
- "trace_symbol_call_chain": (
623
- "Traces deep upstream callers and downstream callees across workspace AST with execution tree and Mermaid diagrams.",
624
- "Invoke the `trace_symbol_call_chain` MCP tool with target symbol name."
625
- ),
626
- "find_dead_code": (
627
- "Finds unused, orphaned, or unreferenced functions and classes across the codebase AST.",
628
- "Invoke the `find_dead_code` MCP tool."
629
- ),
630
- "suggest_reusable_helpers": (
631
- "Discovers and surfaces existing reusable helper and utility functions across the repository AST to prevent reinventing wheels.",
632
- "Invoke the `suggest_reusable_helpers` MCP tool with query or code snippet."
633
- ),
634
- }
635
-
636
- _ANTIGRAVITY_PLUGIN_JSON = """{
637
- "name": "tzero",
638
- "displayName": "Siber Akademi T-Zero Context Engine",
639
- "version": "4.1.0",
640
- "description": "Enterprise-Grade Codebase Context Architect, AST Signatures Analyzer, and Token Reducer. Cuts LLM prompt context by up to 95%, audits code smells & security, enforces architecture boundaries, and traces module dependencies.",
641
- "suggestedPrompts": [
642
- "/tzero tree - Build multi-tier AST hierarchical context tree with 95% token savings",
643
- "/tzero audit - Run AST code quality and 100% Zero-Leak security leak audit",
644
- "/tzero arch - Generate system architecture specification (ARCHITECTURE.md) with Mermaid diagrams",
645
- "/tzero impact <symbol> - Analyze blast radius and change impact before editing code",
646
- "/tzero savings - Compute token reduction metrics and financial ROI"
647
- ],
648
- "author": {
649
- "name": "Toprak Ahmet Aydoğmuş (Siber Akademi)",
650
- "url": "https://github.com/toprakahmetaydogmus/TZeroAlgorithm"
651
- },
652
- "keywords": [
653
- "tzero",
654
- "token-reduction",
655
- "ast",
656
- "codebase-context",
657
- "mcp",
658
- "architecture",
659
- "security-audit"
660
- ],
661
- "homepage": "https://github.com/toprakahmetaydogmus/TZeroAlgorithm",
662
- "repository": "https://github.com/toprakahmetaydogmus/TZeroAlgorithm",
663
- "license": "MIT"
664
- }
665
- """
666
-
667
- _ANTIGRAVITY_RULE_CONTENT = """---
668
- description: Suggest using T-Zero MCP tools for token pruning and AST architecture mapping on codebases.
669
- trigger: model_decision
670
- ---
671
-
672
- # T-Zero Token Efficiency & Architecture Rule
673
-
674
- When exploring large repositories or analyzing multi-file impact:
675
- 1. Prefer `tzero` MCP tools (`get_project_context_tree`, `analyze_change_impact`, `audit_codebase_quality`) to drastically reduce token usage and preserve context window limit.
676
- 2. Ensure Zero-Leak safety before committing or suggesting code with credentials or secrets.
677
- """
678
-
679
- _ANTIGRAVITY_MCP_INSTRUCTIONS = """# T-Zero MCP Server Instructions & Best Practices
680
-
681
- T-Zero is an Enterprise-Grade Codebase Context Architect and Token Reduction Engine.
682
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
683
- Repository: https://github.com/toprakahmetaydogmus/TZeroAlgorithm
684
-
685
- ## When to Use T-Zero MCP Tools:
686
- 1. **Large Codebases or Deep Trees:** Before reading massive directories or hundreds of files into prompt context, invoke `get_project_context_tree` with `tier="T-2"` or `tier="T-3"`. This reduces token consumption by up to 95% while keeping all class/function AST signatures and types.
687
- 2. **Refactoring & Symbol Edits:** Before modifying, deleting, or renaming functions/classes, call `analyze_change_impact` to assess the blast radius and downstream dependents across the workspace.
688
- 3. **Architecture Mapping:** Use `generate_architecture_blueprint` to produce comprehensive `ARCHITECTURE.md` and live Mermaid dependency diagrams.
689
- 4. **Code Quality & Security:** Use `audit_codebase_quality` to scan for code smells, cyclomatic complexity, dead code, and hardcoded secrets (100% Zero-Leak check).
690
- 5. **Architectural Guardrails:** Enforce boundary rules in `tzero.rules.json` using `enforce_architecture_boundaries` to prevent architectural erosion.
691
- """
692
-
693
-
694
- def _sync_alternate_claude_desktop_config(
695
- target: ClientTarget, server_path: Path, server_name: str
696
- ) -> None:
697
- """Keep standard AppData and Windows Store / MSIX Claude configs in sync."""
698
- try:
699
- home = Path.home()
700
- app_data = Path(os.environ.get("APPDATA", home / "AppData/Roaming"))
701
- local_app_data = Path(os.environ.get("LOCALAPPDATA", home / "AppData/Local"))
702
- entry = server_entry(target, server_path)
703
- candidates = [app_data / "Claude" / "claude_desktop_config.json"]
704
- packages_dir = local_app_data / "Packages"
705
- if packages_dir.is_dir():
706
- for claude_pkg in packages_dir.glob("Claude_*"):
707
- candidates.append(
708
- claude_pkg / "LocalCache" / "Roaming" / "Claude" / "claude_desktop_config.json"
709
- )
710
- for alt_path in candidates:
711
- if alt_path.resolve() == target.config_path.resolve():
712
- continue
713
- if alt_path.exists() or alt_path.parent.is_dir():
714
- cfg: Dict[str, object] = {}
715
- if alt_path.exists():
716
- try:
717
- with alt_path.open("r", encoding="utf-8-sig") as fp:
718
- cfg = json.load(fp)
719
- except Exception:
720
- continue
721
- if not isinstance(cfg, dict):
722
- cfg = {}
723
- servers = cfg.setdefault("mcpServers", {})
724
- if isinstance(servers, dict) and servers.get(server_name) != entry:
725
- servers[server_name] = entry
726
- alt_path.parent.mkdir(parents=True, exist_ok=True)
727
- with alt_path.open("w", encoding="utf-8") as fp:
728
- json.dump(cfg, fp, indent=2, ensure_ascii=False)
729
- fp.write("\n")
730
- except Exception:
731
- pass
732
-
733
-
734
- def _resource_path(filename: str) -> Path:
735
- bundle_root = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
736
- path = bundle_root / filename
737
- if path.is_file():
738
- return path
739
- for cand in [
740
- bundle_root / "dist" / filename,
741
- Path.cwd() / "dist" / filename,
742
- Path.cwd() / filename,
743
- Path(__file__).resolve().parent / "dist" / filename,
744
- ]:
745
- if cand.is_file():
746
- return cand
747
- return path
748
-
749
-
750
- def _install_server_binary(
751
- source: Path, local_app_data: Optional[Path] = None
752
- ) -> Path:
753
- if not source.is_file():
754
- raise FileNotFoundError(f"Bundled MCP server not found: {source}")
755
-
756
- local_app_data = Path(
757
- local_app_data or os.environ.get("LOCALAPPDATA", Path.home() / "AppData/Local")
758
- )
759
- destination = local_app_data / "TZeroAlgorithm" / SERVER_FILENAME
760
- destination.parent.mkdir(parents=True, exist_ok=True)
761
-
762
- if destination.exists() and _sha256(source) == _sha256(destination):
763
- return destination
764
-
765
- if destination.exists():
766
- shutil.copy2(destination, _backup_path(destination))
767
-
768
- temporary_path = destination.with_name(f".{destination.name}.tmp")
769
- try:
770
- shutil.copy2(source, temporary_path)
771
- os.replace(temporary_path, destination)
772
- finally:
773
- if temporary_path.exists():
774
- temporary_path.unlink()
775
- return destination
776
-
777
-
778
- def _sha256(path: Path) -> str:
779
- digest = hashlib.sha256()
780
- with path.open("rb") as source_file:
781
- for chunk in iter(lambda: source_file.read(1024 * 1024), b""):
782
- digest.update(chunk)
783
- return digest.hexdigest()
784
-
785
-
786
- def resolve_and_install_server() -> Path:
787
- """Finds TZeroMCP binary or falls back to tzero_mcp.py script."""
788
- # 1. Check for bundled or built binary
789
- primary = _resource_path(SERVER_FILENAME)
790
- if primary.is_file():
791
- try:
792
- return _install_server_binary(primary)
793
- except Exception:
794
- return primary
795
-
796
- # 2. Candidate folders
797
- root = Path(__file__).resolve().parent
798
- for cand in [
799
- root / "dist" / SERVER_FILENAME,
800
- Path.cwd() / "dist" / SERVER_FILENAME,
801
- Path.cwd() / SERVER_FILENAME,
802
- root / SERVER_FILENAME,
803
- ]:
804
- if cand.is_file():
805
- try:
806
- return _install_server_binary(cand)
807
- except Exception:
808
- return cand
809
-
810
- # 3. Python script fallback
811
- for script_cand in [
812
- root / "tzero" / "tzero_mcp.py",
813
- root / "tzero_mcp.py",
814
- Path.cwd() / "tzero" / "tzero_mcp.py",
815
- Path.cwd() / "tzero_mcp.py",
816
- ]:
817
- if script_cand.is_file():
818
- return script_cand.resolve()
819
-
820
- raise FileNotFoundError(
821
- f"Neither '{SERVER_FILENAME}' nor 'tzero_mcp.py' could be found."
822
- )
823
-
824
-
825
- def install_targets(
826
- targets: List[ClientTarget],
827
- log_fn: Optional[Callable[[str], None]] = None,
828
- server_path: Optional[Path] = None,
829
- ) -> Tuple[int, int]:
830
- """Installs server to specified client targets, returning (successes, failures)."""
831
- if log_fn is None:
832
- log_fn = lambda msg: print(f"[T-Zero MCP] {msg}")
833
-
834
- if server_path is None:
835
- server_path = resolve_and_install_server()
836
-
837
- log_fn(f"Runtime resolved: {server_path}")
838
- successes = 0
839
- failures = 0
840
- for target in targets:
841
- try:
842
- result = merge_server_config(target, server_path)
843
- status = str(result["status"]).capitalize()
844
- log_fn(f"{status}: {target.name} -> {target.config_path}")
845
- if result.get("backup"):
846
- log_fn(f"Backup created: {result['backup']}")
847
- successes += 1
848
- except Exception as error:
849
- failures += 1
850
- log_fn(f"Failed for {target.name}: {error}")
851
-
852
- return successes, failures
853
-
854
-
855
- class AddMCPApp:
856
- def __init__(self, root: object):
857
- import tkinter as tk
858
- from tkinter import ttk
859
- self.root = root # type: ignore
860
- self.targets = build_client_targets()
861
- self.check_vars: Dict[str, tk.BooleanVar] = {}
862
- self.root.title("T-Zero MCP Installer")
863
- self.root.geometry("720x650")
864
- self.root.minsize(600, 540)
865
- self.root.configure(bg="#11151c")
866
-
867
- icon_path = _resource_path("tzero/siber_akademi.ico")
868
- if not icon_path.is_file():
869
- icon_path = _resource_path("siber_akademi.ico")
870
- if icon_path.is_file():
871
- try:
872
- self.root.iconbitmap(str(icon_path))
873
- except Exception:
874
- pass
875
-
876
- self._create_widgets()
877
-
878
- def _create_widgets(self) -> None:
879
- import tkinter as tk
880
- from tkinter import ttk
881
-
882
- container = tk.Frame(self.root, bg="#11151c", padx=24, pady=20)
883
- container.pack(fill=tk.BOTH, expand=True)
884
-
885
- tk.Label(
886
- container,
887
- text="SIBER AKADEMI / T-ZERO MCP",
888
- bg="#11151c",
889
- fg="#22d3ee",
890
- font=("Segoe UI", 16, "bold"),
891
- ).pack(anchor="w")
892
- tk.Label(
893
- container,
894
- text="Install the bundled local MCP server in supported IDE configurations.",
895
- bg="#11151c",
896
- fg="#cbd5e1",
897
- font=("Segoe UI", 10),
898
- ).pack(anchor="w", pady=(5, 14))
899
-
900
- self.detected_label = tk.Label(
901
- container,
902
- text="Detected clients are selected by default. Existing config files are backed up before changes.",
903
- bg="#11151c",
904
- fg="#94a3b8",
905
- font=("Segoe UI", 9),
906
- wraplength=660,
907
- justify="left",
908
- )
909
- self.detected_label.pack(anchor="w", pady=(0, 8))
910
-
911
- list_frame = tk.Frame(container, bg="#1a202b", padx=12, pady=8)
912
- list_frame.pack(fill=tk.BOTH, expand=True)
913
- for target in self.targets:
914
- state = "Detected" if target.detected else "Not detected"
915
- variable = tk.BooleanVar(value=target.detected)
916
- self.check_vars[target.key] = variable
917
- row = tk.Frame(list_frame, bg="#1a202b")
918
- row.pack(fill=tk.X, pady=2)
919
- tk.Checkbutton(
920
- row,
921
- text=target.name,
922
- variable=variable,
923
- bg="#1a202b",
924
- fg="#f1f5f9",
925
- activebackground="#1a202b",
926
- activeforeground="#f1f5f9",
927
- selectcolor="#0f172a",
928
- font=("Segoe UI", 10),
929
- ).pack(side=tk.LEFT)
930
- tk.Label(
931
- row,
932
- text=state,
933
- bg="#1a202b",
934
- fg="#4ade80" if target.detected else "#64748b",
935
- font=("Segoe UI", 9),
936
- ).pack(side=tk.RIGHT, padx=6)
937
-
938
- self.log_text = tk.Text(
939
- container,
940
- height=7,
941
- bg="#080b10",
942
- fg="#a5f3fc",
943
- insertbackground="#f8fafc",
944
- relief=tk.FLAT,
945
- font=("Consolas", 9),
946
- state=tk.DISABLED,
947
- )
948
- self.log_text.pack(fill=tk.BOTH, expand=False, pady=(12, 8))
949
-
950
- buttons = tk.Frame(container, bg="#11151c")
951
- buttons.pack(fill=tk.X)
952
- ttk.Button(buttons, text="Select all", command=self._select_all).pack(side=tk.LEFT)
953
- self.install_button = ttk.Button(
954
- buttons, text="Install to selected IDEs", command=self.install_selected
955
- )
956
- self.install_button.pack(side=tk.RIGHT)
957
-
958
- tk.Label(
959
- container,
960
- text="Zero configuration required. Restart IDEs after installation.",
961
- bg="#11151c",
962
- fg="#94a3b8",
963
- font=("Segoe UI", 9),
964
- ).pack(anchor="w", pady=(10, 0))
965
-
966
- def _select_all(self) -> None:
967
- for variable in self.check_vars.values():
968
- variable.set(True)
969
-
970
- def _log(self, message: str) -> None:
971
- import tkinter as tk
972
- self.log_text.configure(state=tk.NORMAL)
973
- self.log_text.insert(tk.END, message + "\n")
974
- self.log_text.see(tk.END)
975
- self.log_text.configure(state=tk.DISABLED)
976
-
977
- def install_selected(self) -> None:
978
- import tkinter as tk
979
- from tkinter import messagebox
980
-
981
- selected = [
982
- target for target in self.targets if self.check_vars[target.key].get()
983
- ]
984
- if not selected:
985
- messagebox.showwarning("T-Zero MCP Installer", "Select at least one client.")
986
- return
987
-
988
- self.install_button.configure(state=tk.DISABLED)
989
- try:
990
- successes, failures = install_targets(selected, log_fn=self._log)
991
- message = f"Configured {successes} client(s)."
992
- if failures:
993
- message += f" {failures} client(s) were skipped; see log."
994
- messagebox.showinfo("T-Zero MCP Installer", message)
995
- except Exception as error:
996
- self._log(f"Installer failed: {error}")
997
- messagebox.showerror("T-Zero MCP Installer", f"Installer failed: {error}")
998
- finally:
999
- self.install_button.configure(state=tk.NORMAL)
1000
-
1001
-
1002
- def run_cli() -> int:
1003
- """Executes the CLI interface when called from command line or with flags."""
1004
- _attach_windows_console()
1005
-
1006
- parser = argparse.ArgumentParser(
1007
- prog="addmcp",
1008
- description="T-Zero MCP 1-Click Installer for Cursor, Claude Desktop, Antigravity, VS Code, Windsurf, etc."
1009
- )
1010
- parser.add_argument(
1011
- "--all", "-a", action="store_true",
1012
- help="Install into all detected IDEs without GUI."
1013
- )
1014
- parser.add_argument(
1015
- "--targets", "-t", metavar="KEYS",
1016
- help="Comma-separated list of target keys to install to (e.g. cursor,claude-desktop,antigravity)."
1017
- )
1018
- parser.add_argument(
1019
- "--list", "-l", action="store_true",
1020
- help="List all supported and detected IDE targets."
1021
- )
1022
- parser.add_argument(
1023
- "--gui", "-g", action="store_true",
1024
- help="Explicitly launch the GUI installer window."
1025
- )
1026
- parser.add_argument(
1027
- "--version", "-v", action="version",
1028
- version=f"T-Zero MCP Installer {APP_VERSION}"
1029
- )
1030
-
1031
- args, unknown = parser.parse_known_args()
1032
- all_targets = build_client_targets()
1033
-
1034
- if args.list:
1035
- print(f"\n[T-Zero MCP Installer v{APP_VERSION}] Available IDE Targets:\n")
1036
- for t in all_targets:
1037
- state = "DETECTED" if t.detected else "not found"
1038
- print(f" [{state:^9}] {t.key:<15} : {t.name} ({t.config_path})")
1039
- print()
1040
- return 0
1041
-
1042
- if args.all or args.targets:
1043
- if args.all:
1044
- selected = [t for t in all_targets if t.detected]
1045
- if not selected:
1046
- print("[T-Zero MCP] No installed IDE clients detected automatically.")
1047
- selected = all_targets
1048
- else:
1049
- keys = [k.strip().lower() for k in args.targets.split(",")]
1050
- selected = [t for t in all_targets if t.key.lower() in keys]
1051
-
1052
- if not selected:
1053
- print("[T-Zero MCP] No valid targets matched.")
1054
- return 1
1055
-
1056
- print(f"\n[T-Zero MCP Installer v{APP_VERSION}] Installing to {len(selected)} target(s)...")
1057
- successes, failures = install_targets(selected, log_fn=lambda m: print(f" -> {m}"))
1058
- print(f"[T-Zero MCP] Completed: {successes} configured, {failures} failed.")
1059
- print("[*] Enjoying T-Zero? Please star the project on GitHub: https://github.com/toprakahmetaydogmus/TZeroAlgorithm\n")
1060
- return 0 if failures == 0 else 1
1061
-
1062
- # Default action: launch GUI if display available, otherwise list targets
1063
- try:
1064
- import tkinter as tk
1065
- root = tk.Tk()
1066
- AddMCPApp(root)
1067
- root.mainloop()
1068
- return 0
1069
- except Exception as e:
1070
- print(f"[T-Zero MCP] GUI unavailable ({e}). Defaulting to automatic CLI install:")
1071
- selected = [t for t in all_targets if t.detected]
1072
- if not selected:
1073
- selected = all_targets
1074
- successes, failures = install_targets(selected, log_fn=lambda m: print(f" -> {m}"))
1075
- print("[*] Enjoying T-Zero? Please star the project on GitHub: https://github.com/toprakahmetaydogmus/TZeroAlgorithm\n")
1076
- return 0 if failures == 0 else 1
1077
-
1078
-
1079
- def run_init(argv: Optional[List[str]] = None) -> int:
1080
- """1-Click T-Zero initialization for modern AI IDEs.
1081
-
1082
- Usage:
1083
- tzero init # Auto-detects and installs to all installed IDEs
1084
- tzero init --cursor # Installs directly to Cursor (.cursor/mcp.json)
1085
- tzero init --claude # Installs to Claude Desktop & Claude Code
1086
- tzero init --windsurf # Installs to Windsurf
1087
- tzero init --vscode # Installs to VS Code / Copilot
1088
- tzero init --all # Installs to all supported IDEs
1089
- tzero init --list # Lists detected status of all supported IDEs
1090
- """
1091
- _attach_windows_console()
1092
- if argv is None:
1093
- argv = sys.argv[2:] if (len(sys.argv) > 1 and sys.argv[1].lower() == "init") else []
1094
-
1095
- all_targets = build_client_targets()
1096
- target_map = {t.key.lower(): t for t in all_targets}
1097
-
1098
- # Aliases
1099
- aliases = {
1100
- "cursor": ["cursor"],
1101
- "claude": ["claude-desktop", "claude-code"],
1102
- "claude-desktop": ["claude-desktop"],
1103
- "claude-code": ["claude-code"],
1104
- "windsurf": ["windsurf"],
1105
- "vscode": ["vscode"],
1106
- "copilot": ["vscode"],
1107
- "cline": ["cline"],
1108
- "roo": ["roo-code"],
1109
- "roo-code": ["roo-code"],
1110
- "antigravity": ["antigravity"],
1111
- "gemini": ["gemini-cli"],
1112
- "gemini-cli": ["gemini-cli"],
1113
- }
1114
-
1115
- # Print banner
1116
- print("""
1117
- \033[1;36m================================================================================
1118
- ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v11.0.0)
1119
- ================================================================================\033[0m
1120
- \033[32m🎯 Zero-Config AST Codebase Context & 100% Zero-Leak Security Guard\033[0m
1121
- """)
1122
-
1123
- # Parse arguments
1124
- flags = [a.lower().lstrip("-") for a in argv]
1125
- if "list" in flags or "l" in flags or "--list" in argv:
1126
- print("\033[1;33m📋 Supported & Detected IDE Environments:\033[0m\n")
1127
- for t in all_targets:
1128
- state = "\033[32m✓ DETECTED\033[0m" if t.detected else "\033[90mnot found \033[0m"
1129
- print(f" [{state}] {t.name:<25} : key='{t.key}' ({t.config_path})")
1130
- print("\n\033[36m💡 Run: 'tzero init' to install to all detected IDEs automatically.\033[0m\n")
1131
- return 0
1132
-
1133
- selected_keys = set()
1134
- install_all_mode = "all" in flags or "-a" in argv or "--all" in argv or not flags
1135
-
1136
- if install_all_mode:
1137
- detected_targets = [t for t in all_targets if t.detected]
1138
- if detected_targets:
1139
- selected_targets = detected_targets
1140
- print(f"\033[34m[AUTO-DETECT]\033[0m Found {len(selected_targets)} active IDE environment(s):")
1141
- for t in selected_targets:
1142
- print(f" • {t.name}")
1143
- else:
1144
- print("\033[33m[INFO]\033[0m No active IDEs currently detected; configuring default targets (Cursor, Claude, VS Code, Windsurf)...")
1145
- selected_targets = [t for t in all_targets if t.key in ("cursor", "claude-desktop", "vscode", "windsurf")]
1146
- else:
1147
- for f in flags:
1148
- if f in aliases:
1149
- selected_keys.update(aliases[f])
1150
- elif f in target_map:
1151
- selected_keys.add(f)
1152
- selected_targets = [t for t in all_targets if t.key in selected_keys]
1153
-
1154
- if not selected_targets:
1155
- print(f"\033[31m[ERROR]\033[0m No matching IDE target found for: {argv}")
1156
- print("Available targets: cursor, claude, windsurf, vscode, cline, roo, antigravity, gemini, all")
1157
- return 1
1158
-
1159
- print(f"\n\033[35m[INSTALLING]\033[0m Configuring {len(selected_targets)} target(s)...")
1160
- successes, failures = install_targets(
1161
- selected_targets,
1162
- log_fn=lambda m: print(f" \033[32m✓\033[0m {m}")
1163
- )
1164
-
1165
- print(f"\n\033[1;32m🎉 [SUCCESS] T-Zero MCP Server successfully registered in {successes} client(s)!\033[0m")
1166
- if failures:
1167
- print(f"\033[33m⚠️ {failures} client(s) could not be updated.\033[0m")
1168
-
1169
- print("""
1170
- \033[1;37m🚀 HOW TO USE IN YOUR IDE (CURSOR, CLAUDE, WINDSURF):
1171
- 1. Restart your IDE or Reload Window.
1172
- 2. In Composer / Chat, prompt your agent:\033[0m
1173
- \033[36m"Use T-Zero to get the project skeleton and analyze the blast radius."\033[0m
1174
- \033[36m"Use tzero reduce_tokens to prune noise and audit zero-leak security."\033[0m
1175
-
1176
- \033[1;36m┌──────────────────────────────────────────────────────────────────────────────┐
1177
- │ ⚡ SIBER AKADEMI T-ZERO CONTEXT ARCHITECT & MCP ENGINE │
1178
- │ │
1179
- │ Engineered by Toprak Ahmet Aydoğmuş & Siber Akademi to eliminate token │
1180
- │ bloat, token costs, and AI hallucinations for programmers worldwide. │
1181
- │ │
1182
- │ If this open-source tool saved you tokens or improved your coding flow: │
1183
- │ 👉 Please consider giving it a ⭐ on GitHub: │
1184
- │ https://github.com/toprakahmetaydogmus/TZeroAlgorithm │
1185
- │ │
1186
- │ 100% Free & Open-Source under MIT License. Thank you! 🚀 │
1187
- └──────────────────────────────────────────────────────────────────────────────┘\033[0m
1188
- """)
1189
- return 0 if failures == 0 else 1
1190
-
1191
-
1192
- def main() -> None:
1193
- sys.exit(run_cli())
1194
-
1195
-
1196
- if __name__ == "__main__":
1197
- main()
1
+ # -*- coding: utf-8 -*-
2
+ """Install the bundled T-Zero MCP server into detected IDE configurations.
3
+
4
+ Supports both a clean Dark GUI and a headless CLI (--all, --list, --targets).
5
+ Automatically copies the standalone TZeroMCP runtime or configures the Python script,
6
+ guaranteeing zero configuration headaches on any computer.
7
+
8
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
9
+ """
10
+
11
+ import argparse
12
+ import hashlib
13
+ import json
14
+ import re
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import tempfile
19
+ from dataclasses import dataclass
20
+ from datetime import datetime
21
+ from pathlib import Path
22
+ from typing import Callable, Dict, List, Optional, Tuple
23
+
24
+
25
+ APP_VERSION = "11.11.0"
26
+ SERVER_NAME = "tzero"
27
+ SERVER_FILENAME = "TZeroMCP.exe"
28
+
29
+
30
+ def _attach_windows_console() -> None:
31
+ """If run from CMD or PowerShell on Windows with --noconsole, attach parent console."""
32
+ if os.name == "nt":
33
+ try:
34
+ import ctypes
35
+ if ctypes.windll.kernel32.AttachConsole(-1):
36
+ if sys.stdout is None or getattr(sys.stdout, "closed", True):
37
+ sys.stdout = open("CONOUT$", "w", encoding="utf-8", errors="replace")
38
+ if sys.stderr is None or getattr(sys.stderr, "closed", True):
39
+ sys.stderr = open("CONOUT$", "w", encoding="utf-8", errors="replace")
40
+ except Exception:
41
+ pass
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class ClientTarget:
46
+ key: str
47
+ name: str
48
+ config_path: Path
49
+ root_key: str
50
+ detected: bool
51
+
52
+
53
+ def _get_antigravity_config_path(home: Path) -> Path:
54
+ """Resolves primary Google Antigravity MCP config path."""
55
+ config_in_config = home / ".gemini" / "config" / "mcp_config.json"
56
+ if config_in_config.exists() or (home / ".gemini" / "config").exists():
57
+ return config_in_config
58
+ return home / ".gemini" / "antigravity" / "mcp_config.json"
59
+
60
+
61
+ def _get_claude_desktop_config_path(app_data: Path, local_app_data: Path) -> Tuple[Path, bool]:
62
+ """Resolves Claude Desktop configuration path, handling both MSIX packages and standard AppData."""
63
+ # 1. Standard AppData Roaming
64
+ standard_cfg = app_data / "Claude" / "claude_desktop_config.json"
65
+ if standard_cfg.exists():
66
+ return standard_cfg, True
67
+
68
+ # 2. Windows Store / MSIX Package sandboxed Roaming
69
+ packages_dir = local_app_data / "Packages"
70
+ if packages_dir.is_dir():
71
+ for claude_pkg in packages_dir.glob("Claude_*"):
72
+ candidate = claude_pkg / "LocalCache" / "Roaming" / "Claude" / "claude_desktop_config.json"
73
+ if candidate.exists() or (claude_pkg / "LocalCache" / "Roaming" / "Claude").is_dir():
74
+ return candidate, True
75
+
76
+ detected = any([
77
+ (app_data / "Claude").exists(),
78
+ (local_app_data / "Programs" / "Claude" / "Claude.exe").exists(),
79
+ bool(list(packages_dir.glob("Claude_*"))) if packages_dir.is_dir() else False,
80
+ ])
81
+ return standard_cfg, detected
82
+
83
+
84
+ def build_client_targets(
85
+ home: Optional[Path] = None,
86
+ app_data: Optional[Path] = None,
87
+ local_app_data: Optional[Path] = None,
88
+ which: Callable[[str], Optional[str]] = shutil.which,
89
+ ) -> List[ClientTarget]:
90
+ """Return known per-user MCP configs and whether their client is installed."""
91
+ home = Path(home or Path.home())
92
+ app_data = Path(app_data or os.environ.get("APPDATA", home / "AppData/Roaming"))
93
+ local_app_data = Path(
94
+ local_app_data or os.environ.get("LOCALAPPDATA", home / "AppData/Local")
95
+ )
96
+ vscode_user = app_data / "Code" / "User"
97
+ vscode_extensions = home / ".vscode" / "extensions"
98
+
99
+ def any_path_exists(*paths: Path) -> bool:
100
+ return any(path.exists() for path in paths)
101
+
102
+ def extension_installed(prefix: str) -> bool:
103
+ return bool(list(vscode_extensions.glob(f"{prefix}-*")))
104
+
105
+ antigravity_config = _get_antigravity_config_path(home)
106
+ claude_config, claude_detected = _get_claude_desktop_config_path(app_data, local_app_data)
107
+
108
+ return [
109
+ ClientTarget(
110
+ "cursor",
111
+ "Cursor",
112
+ home / ".cursor" / "mcp.json",
113
+ "mcpServers",
114
+ any_path_exists(
115
+ home / ".cursor",
116
+ app_data / "Cursor",
117
+ local_app_data / "Programs" / "Cursor" / "Cursor.exe",
118
+ ),
119
+ ),
120
+ ClientTarget(
121
+ "vscode",
122
+ "Visual Studio Code / Copilot",
123
+ home / ".copilot" / "mcp-config.json",
124
+ "mcpServers",
125
+ any_path_exists(
126
+ app_data / "Code",
127
+ local_app_data / "Programs" / "Microsoft VS Code" / "Code.exe",
128
+ )
129
+ or which("code") is not None,
130
+ ),
131
+ ClientTarget(
132
+ "claude-desktop",
133
+ "Claude Desktop",
134
+ claude_config,
135
+ "mcpServers",
136
+ claude_detected,
137
+ ),
138
+ ClientTarget(
139
+ "antigravity",
140
+ "Google Antigravity",
141
+ antigravity_config,
142
+ "mcpServers",
143
+ any_path_exists(
144
+ home / ".gemini" / "config",
145
+ home / ".gemini" / "antigravity",
146
+ local_app_data / "Programs" / "Antigravity" / "Antigravity.exe",
147
+ ),
148
+ ),
149
+ ClientTarget(
150
+ "claude-code",
151
+ "Claude Code",
152
+ home / ".claude.json",
153
+ "mcpServers",
154
+ home.joinpath(".claude.json").exists() or which("claude") is not None,
155
+ ),
156
+ ClientTarget(
157
+ "cline",
158
+ "Cline",
159
+ vscode_user
160
+ / "globalStorage"
161
+ / "saoudrizwan.claude-dev"
162
+ / "settings"
163
+ / "cline_mcp_settings.json",
164
+ "mcpServers",
165
+ (vscode_user / "globalStorage" / "saoudrizwan.claude-dev").exists()
166
+ or extension_installed("saoudrizwan.claude-dev"),
167
+ ),
168
+ ClientTarget(
169
+ "roo-code",
170
+ "Roo Code",
171
+ vscode_user
172
+ / "globalStorage"
173
+ / "rooveterinaryinc.roo-cline"
174
+ / "settings"
175
+ / "mcp_settings.json",
176
+ "mcpServers",
177
+ (vscode_user / "globalStorage" / "rooveterinaryinc.roo-cline").exists()
178
+ or extension_installed("rooveterinaryinc.roo-cline"),
179
+ ),
180
+ ClientTarget(
181
+ "windsurf",
182
+ "Windsurf",
183
+ home / ".codeium" / "windsurf" / "mcp_config.json",
184
+ "mcpServers",
185
+ any_path_exists(
186
+ home / ".codeium" / "windsurf",
187
+ app_data / "Windsurf",
188
+ local_app_data / "Programs" / "Windsurf" / "Windsurf.exe",
189
+ )
190
+ or which("windsurf") is not None,
191
+ ),
192
+ ClientTarget(
193
+ "gemini-cli",
194
+ "Gemini CLI",
195
+ home / ".gemini" / "settings.json",
196
+ "mcpServers",
197
+ home.joinpath(".gemini", "settings.json").exists()
198
+ or which("gemini") is not None,
199
+ ),
200
+ ClientTarget(
201
+ "zed",
202
+ "Zed Editor",
203
+ (app_data / "Zed" / "settings.json") if os.name == "nt" else (home / ".config" / "zed" / "settings.json"),
204
+ "context_servers",
205
+ any_path_exists(
206
+ app_data / "Zed",
207
+ home / ".config" / "zed",
208
+ local_app_data / "Programs" / "Zed" / "Zed.exe",
209
+ )
210
+ or which("zed") is not None,
211
+ ),
212
+ ClientTarget(
213
+ "continue",
214
+ "Continue (VS Code / JetBrains)",
215
+ home / ".continue" / "config.json",
216
+ "mcpServers",
217
+ (home / ".continue").exists() or any_path_exists(home / ".continue" / "config.json"),
218
+ ),
219
+ ]
220
+
221
+
222
+ def server_entry(target: ClientTarget, server_path: Path) -> Dict[str, object]:
223
+ """Generates the MCP configuration dictionary block for the target."""
224
+ if server_path.suffix.lower() == ".py":
225
+ entry: Dict[str, object] = {
226
+ "command": sys.executable,
227
+ "args": [str(server_path.resolve())],
228
+ }
229
+ elif server_path.name.lower() in ("python", "python.exe"):
230
+ entry = {
231
+ "command": "python",
232
+ "args": ["-m", "tzero.tzero_mcp"],
233
+ }
234
+ else:
235
+ entry = {
236
+ "command": str(server_path.resolve()),
237
+ "args": [],
238
+ }
239
+ if target.root_key == "servers":
240
+ entry["type"] = "stdio"
241
+ return entry
242
+
243
+
244
+ def _backup_path(path: Path) -> Path:
245
+ timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
246
+ return path.with_name(f"{path.name}.backup-{timestamp}")
247
+
248
+
249
+ def merge_server_config(
250
+ target: ClientTarget, server_path: Path, server_name: str = SERVER_NAME
251
+ ) -> Dict[str, object]:
252
+ """Safely merge one server entry, keeping the rest of the client's config."""
253
+ config: Dict[str, object] = {}
254
+ if target.config_path.exists():
255
+ with target.config_path.open("r", encoding="utf-8-sig") as config_file:
256
+ raw_text = config_file.read()
257
+ try:
258
+ loaded = json.loads(raw_text)
259
+ except Exception:
260
+ cleaned = re.sub(r"//.*", "", raw_text)
261
+ cleaned = re.sub(r",\s*([\]}])", r"\1", cleaned)
262
+ loaded = json.loads(cleaned)
263
+ if not isinstance(loaded, dict):
264
+ raise ValueError("Configuration root must be a JSON object")
265
+ config = loaded
266
+
267
+ servers = config.get(target.root_key, {})
268
+ if not isinstance(servers, dict):
269
+ raise ValueError(f"'{target.root_key}' must be a JSON object")
270
+
271
+ entry = server_entry(target, server_path)
272
+ if servers.get(server_name) == entry:
273
+ if target.key == "antigravity":
274
+ _sync_alternate_antigravity_config(target, server_path, server_name)
275
+ elif target.key == "claude-desktop":
276
+ _sync_alternate_claude_desktop_config(target, server_path, server_name)
277
+ return {"status": "unchanged", "backup": None}
278
+
279
+ backup = None
280
+ if target.config_path.exists():
281
+ backup = _backup_path(target.config_path)
282
+ shutil.copy2(target.config_path, backup)
283
+
284
+ updated_servers = dict(servers)
285
+ updated_servers[server_name] = entry
286
+ config[target.root_key] = updated_servers
287
+ target.config_path.parent.mkdir(parents=True, exist_ok=True)
288
+
289
+ temporary_path = None
290
+ try:
291
+ with tempfile.NamedTemporaryFile(
292
+ "w",
293
+ encoding="utf-8",
294
+ dir=str(target.config_path.parent),
295
+ prefix=f".{target.config_path.name}.",
296
+ suffix=".tmp",
297
+ delete=False,
298
+ ) as temporary_file:
299
+ json.dump(config, temporary_file, indent=2, ensure_ascii=False)
300
+ temporary_file.write("\n")
301
+ temporary_path = Path(temporary_file.name)
302
+ os.replace(temporary_path, target.config_path)
303
+ finally:
304
+ if temporary_path is not None and temporary_path.exists():
305
+ temporary_path.unlink()
306
+
307
+ # If this is Google Antigravity or Claude Desktop, sync alternate config paths if present
308
+ if target.key == "antigravity":
309
+ _sync_alternate_antigravity_config(target, server_path, server_name)
310
+ elif target.key == "claude-desktop":
311
+ _sync_alternate_claude_desktop_config(target, server_path, server_name)
312
+
313
+ return {"status": "installed", "backup": backup}
314
+
315
+
316
+ def _sync_alternate_antigravity_config(
317
+ target: ClientTarget, server_path: Path, server_name: str
318
+ ) -> None:
319
+ """Keep ~/.gemini/config/mcp_config.json and ~/.gemini/antigravity/mcp_config.json in sync."""
320
+ try:
321
+ home = Path.home()
322
+ alt_paths = [
323
+ home / ".gemini" / "config" / "mcp_config.json",
324
+ home / ".gemini" / "antigravity" / "mcp_config.json",
325
+ ]
326
+ entry = server_entry(target, server_path)
327
+ for alt_path in alt_paths:
328
+ if alt_path.resolve() == target.config_path.resolve():
329
+ continue
330
+ if alt_path.parent.exists():
331
+ cfg: Dict[str, object] = {}
332
+ if alt_path.exists():
333
+ try:
334
+ with alt_path.open("r", encoding="utf-8-sig") as fp:
335
+ cfg = json.load(fp)
336
+ except Exception:
337
+ continue
338
+ if not isinstance(cfg, dict):
339
+ cfg = {}
340
+ servers = cfg.setdefault("mcpServers", {})
341
+ if isinstance(servers, dict) and servers.get(server_name) != entry:
342
+ servers[server_name] = entry
343
+ alt_path.parent.mkdir(parents=True, exist_ok=True)
344
+ with alt_path.open("w", encoding="utf-8") as fp:
345
+ json.dump(cfg, fp, indent=2, ensure_ascii=False)
346
+ fp.write("\n")
347
+ # Also install the /tzero slash skills, plugin, and instructions into Antigravity
348
+ _install_antigravity_skill(server_path)
349
+ except Exception:
350
+ pass
351
+
352
+
353
+ def _install_antigravity_skill(server_path: Optional[Path] = None) -> None:
354
+ """Installs the /tzero slash skills, Antigravity plugin, and MCP instructions."""
355
+ try:
356
+ home = Path.home()
357
+ # 1. Global skills directories
358
+ skills_targets = [
359
+ home / ".gemini" / "config" / "skills",
360
+ home / ".gemini" / "skills",
361
+ ]
362
+
363
+ # If running within a git or project workspace, also install workspace skill
364
+ cwd = Path.cwd()
365
+ if (cwd / ".git").is_dir() or (cwd / ".agents").is_dir():
366
+ skills_targets.append(cwd / ".agents" / "skills")
367
+
368
+ all_skills = {
369
+ "tzero": _ANTIGRAVITY_SKILL_CONTENT,
370
+ "tzero-tree": _ANTIGRAVITY_TREE_SKILL_CONTENT,
371
+ "tzero-audit": _ANTIGRAVITY_AUDIT_SKILL_CONTENT,
372
+ "tzero-arch": _ANTIGRAVITY_ARCH_SKILL_CONTENT,
373
+ }
374
+
375
+ for tool_name, (desc, action) in _MCP_TOOLS_SPEC.items():
376
+ all_skills[tool_name] = f"""---
377
+ name: {tool_name}
378
+ description: >-
379
+ {desc}
380
+ Activate when the user types "/{tool_name}" or asks to run {tool_name}.
381
+ ---
382
+
383
+ # /{tool_name} — T-Zero MCP Tool
384
+
385
+ {desc}
386
+
387
+ ## Execution
388
+ {action}
389
+ """
390
+
391
+ for target_base in skills_targets:
392
+ for skill_name, content in all_skills.items():
393
+ s_dir = target_base / skill_name
394
+ s_dir.mkdir(parents=True, exist_ok=True)
395
+ (s_dir / "SKILL.md").write_text(content, encoding="utf-8")
396
+
397
+ # 2. Antigravity Plugin (~/.gemini/config/plugins/tzero)
398
+ plugin_dir = home / ".gemini" / "config" / "plugins" / "tzero"
399
+ plugin_dir.mkdir(parents=True, exist_ok=True)
400
+ (plugin_dir / "plugin.json").write_text(_ANTIGRAVITY_PLUGIN_JSON, encoding="utf-8")
401
+ (plugin_dir / "installed_version.json").write_text('{"version": "4.1.0"}\n', encoding="utf-8")
402
+
403
+ # Plugin skills
404
+ for skill_name, content in all_skills.items():
405
+ p_skill_dir = plugin_dir / "skills" / skill_name
406
+ p_skill_dir.mkdir(parents=True, exist_ok=True)
407
+ (p_skill_dir / "SKILL.md").write_text(content, encoding="utf-8")
408
+
409
+ # Plugin rules
410
+ p_rules_dir = plugin_dir / "rules"
411
+ p_rules_dir.mkdir(parents=True, exist_ok=True)
412
+ (p_rules_dir / "tzero-token-optimization.md").write_text(_ANTIGRAVITY_RULE_CONTENT, encoding="utf-8")
413
+
414
+ # Plugin mcp_config.json
415
+ cmd = str(server_path.resolve()) if server_path else str(home / "AppData" / "Local" / "TZeroAlgorithm" / SERVER_FILENAME)
416
+ plugin_mcp = {
417
+ "mcpServers": {
418
+ SERVER_NAME: {
419
+ "command": cmd,
420
+ "args": []
421
+ }
422
+ }
423
+ }
424
+ (plugin_dir / "mcp_config.json").write_text(json.dumps(plugin_mcp, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
425
+
426
+ # 3. Enable plugin in ~/.gemini/config/config.json
427
+ cfg_file = home / ".gemini" / "config" / "config.json"
428
+ if cfg_file.exists():
429
+ try:
430
+ cfg_data = json.loads(cfg_file.read_text(encoding="utf-8-sig"))
431
+ if isinstance(cfg_data, dict):
432
+ plugins_dict = cfg_data.setdefault("plugins", {})
433
+ if isinstance(plugins_dict, dict) and "tzero" not in plugins_dict:
434
+ plugins_dict["tzero"] = {"enabled": True}
435
+ cfg_file.write_text(json.dumps(cfg_data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
436
+ except Exception:
437
+ pass
438
+
439
+ # 4. MCP instructions in ~/.gemini/antigravity-ide/mcp/tzero/instructions.md
440
+ ide_mcp_dir = home / ".gemini" / "antigravity-ide" / "mcp" / SERVER_NAME
441
+ if ide_mcp_dir.is_dir():
442
+ (ide_mcp_dir / "instructions.md").write_text(_ANTIGRAVITY_MCP_INSTRUCTIONS, encoding="utf-8")
443
+
444
+ except Exception:
445
+ pass
446
+
447
+
448
+ _ANTIGRAVITY_SKILL_CONTENT = """---
449
+ name: tzero
450
+ description: >-
451
+ Enterprise-Grade Codebase Context Architect, AST Signatures Analyzer, & Token Reducer.
452
+ Activate when the user types "/tzero", asks to reduce tokens, scan codebase architecture,
453
+ audit code smells, analyze change impact, enforce architectural boundaries, or optimize prompt context for LLMs.
454
+ ---
455
+
456
+ # /tzero — Siber Akademi T-Zero Context Engine
457
+
458
+ Enterprise-Grade Codebase Context Architect, AST Signatures Analyzer, and Token Reducer.
459
+ Cuts LLM context ingestion overhead by up to 95% while preserving structural fidelity for AI agents.
460
+
461
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
462
+ Repository: https://github.com/toprakahmetaydogmus/TZeroAlgorithm
463
+
464
+ ## Slash Command Modes
465
+
466
+ When the user enters `/tzero [subcommand]` or asks for T-Zero assistance, dispatch to the matching capability:
467
+
468
+ | Subcommand | Description | Action / Tool |
469
+ |:---|:---|:---|
470
+ | `/tzero` or `/tzero tree` | Builds full multi-tier hierarchical context tree (T-1 to T-4) with ultra token pruning. | Call `get_project_context_tree` MCP tool |
471
+ | `/tzero audit` | Runs AST static code smell check and checks for 100% Zero-Leak security (hardcoded secrets). | Call `audit_codebase_quality` MCP tool |
472
+ | `/tzero arch` | Generates system architecture specification (`ARCHITECTURE.md`) with live Mermaid diagrams. | Call `generate_architecture_blueprint` MCP tool |
473
+ | `/tzero deps [file]` | Traces internal & external module import topology and dependency graphs. | Call `query_module_dependencies` MCP tool |
474
+ | `/tzero impact <symbol>` | Analyzes change impact and blast radius (0-100 score) before modifying a class/function. | Call `analyze_change_impact` MCP tool |
475
+ | `/tzero rules` | Generates AI agent instruction files (`.cursorrules`, `.cursor/rules/*.mdc`, `.clinerules`). | Call `export_agent_rules` MCP tool |
476
+ | `/tzero search <query>` | Performs 100% private local BM25 hybrid semantic code search without cloud embedding APIs. | Call `search_codebase_semantic` MCP tool |
477
+ | `/tzero savings` | Computes quantitative token reduction metrics and team financial ROI savings (USD/month). | Call `get_token_savings_metrics` MCP tool |
478
+ | `/tzero boundaries` | Enforces T-4 architectural boundaries defined in `tzero.rules.json` to prevent architectural erosion. | Call `enforce_architecture_boundaries` MCP tool |
479
+ | `/tzero repomap` | Generates ultra-compact AST symbol token map for chat context windows. | Call `generate_repo_map` MCP tool |
480
+ | `/tzero duplicity` | Scans workspace for duplicate or copy-pasted code blocks (6+ lines) across modules. | Call `find_code_duplicity` MCP tool |
481
+ | `/tzero helpers <query>` | Discovers reusable repository helpers & guards against reinventing existing functions. | Call `suggest_reusable_helpers` MCP tool |
482
+ | `/tzero doctor` | Inspects environment, Python runtime, and dependencies. | Run `python -m tzero_deps` or CLI `--doctor` |
483
+
484
+ ## Execution Guidelines
485
+
486
+ 1. **Prefer Native MCP Tools:** When the `tzero` MCP server is registered, invoke the corresponding MCP tool directly (`get_project_context_tree`, `audit_codebase_quality`, etc.).
487
+ 2. **Fallback to CLI/Engine:** If MCP is temporarily unavailable, use the local CLI `tzero_v3.py` or `TZeroAlgorithm.exe` with matching flags (`--scan`, `--audit`, `--export-arch`, etc.).
488
+ 3. **100% Zero-Leak Guarantee:** Never output, log, or commit sensitive API keys or user credentials.
489
+ 4. **Summary & Presentation:** Format the output with clear GitHub-style Markdown, tables, and alerts (`> [!TIP]`, `> [!IMPORTANT]`).
490
+ """
491
+
492
+ _ANTIGRAVITY_TREE_SKILL_CONTENT = """---
493
+ name: tzero-tree
494
+ description: >-
495
+ Generate multi-tier hierarchical AST context tree with up to 95% token reduction for AI context ingestion.
496
+ Activate when the user types "/tzero-tree" or asks to build a code tree.
497
+ ---
498
+
499
+ # /tzero-tree — AST Hierarchical Context Tree Generator
500
+
501
+ Generate a multi-tier pruned AST context tree to provide AI agents with full architectural understanding at up to 95% lower token cost.
502
+
503
+ ## Modes & Tiers
504
+ - **Tier 1 (T-1):** High-level architectural map & entry points.
505
+ - **Tier 2 (T-2):** Public API & class/function signatures with types.
506
+ - **Tier 3 (T-3):** Full signatures, method contracts, and docstrings.
507
+ - **Tier 4 (T-4):** Full AST graph with import dependencies.
508
+
509
+ ## Execution
510
+ Call the `get_project_context_tree` MCP tool with the target path (default: current workspace) and desired tier (default: `T-2`).
511
+ """
512
+
513
+ _ANTIGRAVITY_AUDIT_SKILL_CONTENT = """---
514
+ name: tzero-audit
515
+ description: >-
516
+ Run AST static code analysis, code smells check, cyclomatic complexity report, and 100% Zero-Leak security audit for hardcoded secrets.
517
+ Activate when the user types "/tzero-audit" or asks to audit code quality.
518
+ ---
519
+
520
+ # /tzero-audit — AST Code Quality & Zero-Leak Security Audit
521
+
522
+ Perform a comprehensive AST quality audit and verify 100% Zero-Leak security:
523
+ 1. **Code Smells:** Functions >50 lines, classes >300 lines, high complexity.
524
+ 2. **Dead Code:** Unused imports and unreferenced private functions.
525
+ 3. **Security (Zero-Leak):** High-entropy strings, hardcoded API keys, tokens, and credentials.
526
+
527
+ ## Execution
528
+ Call the `audit_codebase_quality` MCP tool on the target path (default: `.`).
529
+ """
530
+
531
+ _ANTIGRAVITY_ARCH_SKILL_CONTENT = """---
532
+ name: tzero-arch
533
+ description: >-
534
+ Generate complete system architecture specification (ARCHITECTURE.md) with live Mermaid component diagrams.
535
+ Activate when the user types "/tzero-arch" or asks for system architecture blueprint.
536
+ ---
537
+
538
+ # /tzero-arch — System Architecture Blueprint Generator
539
+
540
+ Generate an enterprise-grade architectural specification:
541
+ 1. Module decomposition and layer boundaries.
542
+ 2. Inter-module import topology.
543
+ 3. Interactive Mermaid diagram showing system component relationships.
544
+ 4. Auto-exports or updates `ARCHITECTURE.md`.
545
+
546
+ ## Execution
547
+ Call the `generate_architecture_blueprint` MCP tool on the target path (default: `.`).
548
+ """
549
+
550
+ _MCP_TOOLS_SPEC = {
551
+ "get_project_context_tree": (
552
+ "Scans target project directory and builds an enterprise-grade multi-tier T-Zero hierarchical context tree (T-1 to T-4) with up to 95% token reduction.",
553
+ "Invoke the `get_project_context_tree` MCP tool with arguments `{\"project_root\": \".\", \"reduction_mode\": \"ultra\"}`."
554
+ ),
555
+ "query_module_dependencies": (
556
+ "Analyzes import/export dependencies, module relationships, and internal vs external package dependencies across codebase or for a specific file.",
557
+ "Invoke the `query_module_dependencies` MCP tool."
558
+ ),
559
+ "query_architecture_boundaries": (
560
+ "Retrieves active T-4 architectural boundaries, operational constraints, and 100% Zero-Leak security rules.",
561
+ "Invoke the `query_architecture_boundaries` MCP tool."
562
+ ),
563
+ "generate_architecture_blueprint": (
564
+ "Generates a complete system architecture specification (ARCHITECTURE.md) including auto-generated Mermaid topology diagrams.",
565
+ "Invoke the `generate_architecture_blueprint` MCP tool."
566
+ ),
567
+ "generate_repo_map": (
568
+ "Generates an ultra-compact AST symbol token map for chat context windows.",
569
+ "Invoke the `generate_repo_map` MCP tool."
570
+ ),
571
+ "audit_codebase_quality": (
572
+ "Performs an AST static code smell audit and 100% Zero-Leak security check for hardcoded secret leaks across workspace files.",
573
+ "Invoke the `audit_codebase_quality` MCP tool."
574
+ ),
575
+ "find_code_duplicity": (
576
+ "Scans workspace for duplicate or copy-pasted code blocks (6+ lines) across modules.",
577
+ "Invoke the `find_code_duplicity` MCP tool."
578
+ ),
579
+ "estimate_token_cost": (
580
+ "Calculates exact token cost comparison across OpenAI, Anthropic, Gemini, DeepSeek models.",
581
+ "Invoke the `estimate_token_cost` MCP tool."
582
+ ),
583
+ "analyze_change_impact": (
584
+ "Analyzes change blast radius (0-100 score) and downstream dependents before modifying a class/function.",
585
+ "Invoke the `analyze_change_impact` MCP tool."
586
+ ),
587
+ "enforce_architecture_boundaries": (
588
+ "Enforces architectural boundary rules defined in tzero.rules.json to prevent architectural erosion.",
589
+ "Invoke the `enforce_architecture_boundaries` MCP tool."
590
+ ),
591
+ "search_codebase_semantic": (
592
+ "Performs 100% private local BM25 hybrid semantic code search across codebase without cloud embedding APIs.",
593
+ "Invoke the `search_codebase_semantic` MCP tool."
594
+ ),
595
+ "export_agent_rules": (
596
+ "Exports AI agent rule specifications (.cursorrules, .clinerules, .cursor/rules/*.mdc).",
597
+ "Invoke the `export_agent_rules` MCP tool."
598
+ ),
599
+ "get_token_savings_metrics": (
600
+ "Computes quantitative token reduction metrics and monthly team financial ROI savings.",
601
+ "Invoke the `get_token_savings_metrics` MCP tool."
602
+ ),
603
+ "get_incremental_diff_context": (
604
+ "Extracts ultra-compact PR diff context with modified symbols and downstream blast radius for code reviews.",
605
+ "Invoke the `get_incremental_diff_context` MCP tool."
606
+ ),
607
+ "prune_code_snippet": (
608
+ "Prunes arbitrary in-memory code snippets into compact AST signatures on-the-fly (80-95% reduction).",
609
+ "Invoke the `prune_code_snippet` MCP tool."
610
+ ),
611
+ "verify_zero_leak_security": (
612
+ "100% Zero-Leak security scanner for hardcoded API keys and secrets across workspace files.",
613
+ "Invoke the `verify_zero_leak_security` MCP tool."
614
+ ),
615
+ "verify_hallucination_guard": (
616
+ "Eliminates AI coding hallucinations before code is written by validating imports and function call signatures against workspace AST.",
617
+ "Invoke the `verify_hallucination_guard` MCP tool with proposed code."
618
+ ),
619
+ "get_smart_skeleton_context": (
620
+ "Focus-aware dynamic skeletonizer delivering full focus implementation with surrounding 1st-degree AST interface skeletons.",
621
+ "Invoke the `get_smart_skeleton_context` MCP tool with focus file/symbol."
622
+ ),
623
+ "rank_repository_pagerank": (
624
+ "Identifies repository architectural backbone and module centrality using graph-theory PageRank over AST topologies.",
625
+ "Invoke the `rank_repository_pagerank` MCP tool."
626
+ ),
627
+ "trace_symbol_call_chain": (
628
+ "Traces deep upstream callers and downstream callees across workspace AST with execution tree and Mermaid diagrams.",
629
+ "Invoke the `trace_symbol_call_chain` MCP tool with target symbol name."
630
+ ),
631
+ "find_dead_code": (
632
+ "Finds unused, orphaned, or unreferenced functions and classes across the codebase AST.",
633
+ "Invoke the `find_dead_code` MCP tool."
634
+ ),
635
+ "suggest_reusable_helpers": (
636
+ "Discovers and surfaces existing reusable helper and utility functions across the repository AST to prevent reinventing wheels.",
637
+ "Invoke the `suggest_reusable_helpers` MCP tool with query or code snippet."
638
+ ),
639
+ }
640
+
641
+ _ANTIGRAVITY_PLUGIN_JSON = """{
642
+ "name": "tzero",
643
+ "displayName": "Siber Akademi T-Zero Context Engine",
644
+ "version": "4.1.0",
645
+ "description": "Enterprise-Grade Codebase Context Architect, AST Signatures Analyzer, and Token Reducer. Cuts LLM prompt context by up to 95%, audits code smells & security, enforces architecture boundaries, and traces module dependencies.",
646
+ "suggestedPrompts": [
647
+ "/tzero tree - Build multi-tier AST hierarchical context tree with 95% token savings",
648
+ "/tzero audit - Run AST code quality and 100% Zero-Leak security leak audit",
649
+ "/tzero arch - Generate system architecture specification (ARCHITECTURE.md) with Mermaid diagrams",
650
+ "/tzero impact <symbol> - Analyze blast radius and change impact before editing code",
651
+ "/tzero savings - Compute token reduction metrics and financial ROI"
652
+ ],
653
+ "author": {
654
+ "name": "Toprak Ahmet Aydoğmuş (Siber Akademi)",
655
+ "url": "https://github.com/toprakahmetaydogmus/TZeroAlgorithm"
656
+ },
657
+ "keywords": [
658
+ "tzero",
659
+ "token-reduction",
660
+ "ast",
661
+ "codebase-context",
662
+ "mcp",
663
+ "architecture",
664
+ "security-audit"
665
+ ],
666
+ "homepage": "https://github.com/toprakahmetaydogmus/TZeroAlgorithm",
667
+ "repository": "https://github.com/toprakahmetaydogmus/TZeroAlgorithm",
668
+ "license": "MIT"
669
+ }
670
+ """
671
+
672
+ _ANTIGRAVITY_RULE_CONTENT = """---
673
+ description: Suggest using T-Zero MCP tools for token pruning and AST architecture mapping on codebases.
674
+ trigger: model_decision
675
+ ---
676
+
677
+ # T-Zero Token Efficiency & Architecture Rule
678
+
679
+ When exploring large repositories or analyzing multi-file impact:
680
+ 1. Prefer `tzero` MCP tools (`get_project_context_tree`, `analyze_change_impact`, `audit_codebase_quality`) to drastically reduce token usage and preserve context window limit.
681
+ 2. Ensure Zero-Leak safety before committing or suggesting code with credentials or secrets.
682
+ """
683
+
684
+ _ANTIGRAVITY_MCP_INSTRUCTIONS = """# T-Zero MCP Server Instructions & Best Practices
685
+
686
+ T-Zero is an Enterprise-Grade Codebase Context Architect and Token Reduction Engine.
687
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
688
+ Repository: https://github.com/toprakahmetaydogmus/TZeroAlgorithm
689
+
690
+ ## When to Use T-Zero MCP Tools:
691
+ 1. **Large Codebases or Deep Trees:** Before reading massive directories or hundreds of files into prompt context, invoke `get_project_context_tree` with `tier="T-2"` or `tier="T-3"`. This reduces token consumption by up to 95% while keeping all class/function AST signatures and types.
692
+ 2. **Refactoring & Symbol Edits:** Before modifying, deleting, or renaming functions/classes, call `analyze_change_impact` to assess the blast radius and downstream dependents across the workspace.
693
+ 3. **Architecture Mapping:** Use `generate_architecture_blueprint` to produce comprehensive `ARCHITECTURE.md` and live Mermaid dependency diagrams.
694
+ 4. **Code Quality & Security:** Use `audit_codebase_quality` to scan for code smells, cyclomatic complexity, dead code, and hardcoded secrets (100% Zero-Leak check).
695
+ 5. **Architectural Guardrails:** Enforce boundary rules in `tzero.rules.json` using `enforce_architecture_boundaries` to prevent architectural erosion.
696
+ """
697
+
698
+
699
+ def _sync_alternate_claude_desktop_config(
700
+ target: ClientTarget, server_path: Path, server_name: str
701
+ ) -> None:
702
+ """Keep standard AppData and Windows Store / MSIX Claude configs in sync."""
703
+ try:
704
+ home = Path.home()
705
+ app_data = Path(os.environ.get("APPDATA", home / "AppData/Roaming"))
706
+ local_app_data = Path(os.environ.get("LOCALAPPDATA", home / "AppData/Local"))
707
+ entry = server_entry(target, server_path)
708
+ candidates = [app_data / "Claude" / "claude_desktop_config.json"]
709
+ packages_dir = local_app_data / "Packages"
710
+ if packages_dir.is_dir():
711
+ for claude_pkg in packages_dir.glob("Claude_*"):
712
+ candidates.append(
713
+ claude_pkg / "LocalCache" / "Roaming" / "Claude" / "claude_desktop_config.json"
714
+ )
715
+ for alt_path in candidates:
716
+ if alt_path.resolve() == target.config_path.resolve():
717
+ continue
718
+ if alt_path.exists() or alt_path.parent.is_dir():
719
+ cfg: Dict[str, object] = {}
720
+ if alt_path.exists():
721
+ try:
722
+ with alt_path.open("r", encoding="utf-8-sig") as fp:
723
+ cfg = json.load(fp)
724
+ except Exception:
725
+ continue
726
+ if not isinstance(cfg, dict):
727
+ cfg = {}
728
+ servers = cfg.setdefault("mcpServers", {})
729
+ if isinstance(servers, dict) and servers.get(server_name) != entry:
730
+ servers[server_name] = entry
731
+ alt_path.parent.mkdir(parents=True, exist_ok=True)
732
+ with alt_path.open("w", encoding="utf-8") as fp:
733
+ json.dump(cfg, fp, indent=2, ensure_ascii=False)
734
+ fp.write("\n")
735
+ except Exception:
736
+ pass
737
+
738
+
739
+ def _resource_path(filename: str) -> Path:
740
+ bundle_root = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
741
+ path = bundle_root / filename
742
+ if path.is_file():
743
+ return path
744
+ for cand in [
745
+ bundle_root / "dist" / filename,
746
+ Path.cwd() / "dist" / filename,
747
+ Path.cwd() / filename,
748
+ Path(__file__).resolve().parent / "dist" / filename,
749
+ ]:
750
+ if cand.is_file():
751
+ return cand
752
+ return path
753
+
754
+
755
+ def _install_server_binary(
756
+ source: Path, local_app_data: Optional[Path] = None
757
+ ) -> Path:
758
+ if not source.is_file():
759
+ raise FileNotFoundError(f"Bundled MCP server not found: {source}")
760
+
761
+ local_app_data = Path(
762
+ local_app_data or os.environ.get("LOCALAPPDATA", Path.home() / "AppData/Local")
763
+ )
764
+ destination = local_app_data / "TZeroAlgorithm" / SERVER_FILENAME
765
+ destination.parent.mkdir(parents=True, exist_ok=True)
766
+
767
+ if destination.exists() and _sha256(source) == _sha256(destination):
768
+ return destination
769
+
770
+ if destination.exists():
771
+ shutil.copy2(destination, _backup_path(destination))
772
+
773
+ temporary_path = destination.with_name(f".{destination.name}.tmp")
774
+ try:
775
+ shutil.copy2(source, temporary_path)
776
+ os.replace(temporary_path, destination)
777
+ finally:
778
+ if temporary_path.exists():
779
+ temporary_path.unlink()
780
+ return destination
781
+
782
+
783
+ def _sha256(path: Path) -> str:
784
+ digest = hashlib.sha256()
785
+ with path.open("rb") as source_file:
786
+ for chunk in iter(lambda: source_file.read(1024 * 1024), b""):
787
+ digest.update(chunk)
788
+ return digest.hexdigest()
789
+
790
+
791
+ def resolve_and_install_server() -> Path:
792
+ """Finds TZeroMCP binary or falls back to tzero_mcp.py script."""
793
+ # 1. Check for bundled or built binary
794
+ primary = _resource_path(SERVER_FILENAME)
795
+ if primary.is_file():
796
+ try:
797
+ return _install_server_binary(primary)
798
+ except Exception:
799
+ return primary
800
+
801
+ # 2. Candidate folders
802
+ root = Path(__file__).resolve().parent
803
+ for cand in [
804
+ root / "dist" / SERVER_FILENAME,
805
+ Path.cwd() / "dist" / SERVER_FILENAME,
806
+ Path.cwd() / SERVER_FILENAME,
807
+ root / SERVER_FILENAME,
808
+ ]:
809
+ if cand.is_file():
810
+ try:
811
+ return _install_server_binary(cand)
812
+ except Exception:
813
+ return cand
814
+
815
+ # 3. Python script fallback
816
+ for script_cand in [
817
+ root / "tzero" / "tzero_mcp.py",
818
+ root / "tzero_mcp.py",
819
+ Path.cwd() / "tzero" / "tzero_mcp.py",
820
+ Path.cwd() / "tzero_mcp.py",
821
+ ]:
822
+ if script_cand.is_file():
823
+ return script_cand.resolve()
824
+
825
+ raise FileNotFoundError(
826
+ f"Neither '{SERVER_FILENAME}' nor 'tzero_mcp.py' could be found."
827
+ )
828
+
829
+
830
+ def install_targets(
831
+ targets: List[ClientTarget],
832
+ log_fn: Optional[Callable[[str], None]] = None,
833
+ server_path: Optional[Path] = None,
834
+ ) -> Tuple[int, int]:
835
+ """Installs server to specified client targets, returning (successes, failures)."""
836
+ if log_fn is None:
837
+ log_fn = lambda msg: print(f"[T-Zero MCP] {msg}")
838
+
839
+ if server_path is None:
840
+ server_path = resolve_and_install_server()
841
+
842
+ log_fn(f"Runtime resolved: {server_path}")
843
+ successes = 0
844
+ failures = 0
845
+ for target in targets:
846
+ try:
847
+ result = merge_server_config(target, server_path)
848
+ status = str(result["status"]).capitalize()
849
+ log_fn(f"{status}: {target.name} -> {target.config_path}")
850
+ if result.get("backup"):
851
+ log_fn(f"Backup created: {result['backup']}")
852
+ successes += 1
853
+ except Exception as error:
854
+ failures += 1
855
+ log_fn(f"Failed for {target.name}: {error}")
856
+
857
+ return successes, failures
858
+
859
+
860
+ class AddMCPApp:
861
+ def __init__(self, root: object):
862
+ import tkinter as tk
863
+ from tkinter import ttk
864
+ self.root = root # type: ignore
865
+ self.targets = build_client_targets()
866
+ self.check_vars: Dict[str, tk.BooleanVar] = {}
867
+ self.root.title("T-Zero MCP Installer")
868
+ self.root.geometry("720x650")
869
+ self.root.minsize(600, 540)
870
+ self.root.configure(bg="#11151c")
871
+
872
+ icon_path = _resource_path("tzero/siber_akademi.ico")
873
+ if not icon_path.is_file():
874
+ icon_path = _resource_path("siber_akademi.ico")
875
+ if icon_path.is_file():
876
+ try:
877
+ self.root.iconbitmap(str(icon_path))
878
+ except Exception:
879
+ pass
880
+
881
+ self._create_widgets()
882
+
883
+ def _create_widgets(self) -> None:
884
+ import tkinter as tk
885
+ from tkinter import ttk
886
+
887
+ container = tk.Frame(self.root, bg="#11151c", padx=24, pady=20)
888
+ container.pack(fill=tk.BOTH, expand=True)
889
+
890
+ tk.Label(
891
+ container,
892
+ text="SIBER AKADEMI / T-ZERO MCP",
893
+ bg="#11151c",
894
+ fg="#22d3ee",
895
+ font=("Segoe UI", 16, "bold"),
896
+ ).pack(anchor="w")
897
+ tk.Label(
898
+ container,
899
+ text="Install the bundled local MCP server in supported IDE configurations.",
900
+ bg="#11151c",
901
+ fg="#cbd5e1",
902
+ font=("Segoe UI", 10),
903
+ ).pack(anchor="w", pady=(5, 14))
904
+
905
+ self.detected_label = tk.Label(
906
+ container,
907
+ text="Detected clients are selected by default. Existing config files are backed up before changes.",
908
+ bg="#11151c",
909
+ fg="#94a3b8",
910
+ font=("Segoe UI", 9),
911
+ wraplength=660,
912
+ justify="left",
913
+ )
914
+ self.detected_label.pack(anchor="w", pady=(0, 8))
915
+
916
+ list_frame = tk.Frame(container, bg="#1a202b", padx=12, pady=8)
917
+ list_frame.pack(fill=tk.BOTH, expand=True)
918
+ for target in self.targets:
919
+ state = "Detected" if target.detected else "Not detected"
920
+ variable = tk.BooleanVar(value=target.detected)
921
+ self.check_vars[target.key] = variable
922
+ row = tk.Frame(list_frame, bg="#1a202b")
923
+ row.pack(fill=tk.X, pady=2)
924
+ tk.Checkbutton(
925
+ row,
926
+ text=target.name,
927
+ variable=variable,
928
+ bg="#1a202b",
929
+ fg="#f1f5f9",
930
+ activebackground="#1a202b",
931
+ activeforeground="#f1f5f9",
932
+ selectcolor="#0f172a",
933
+ font=("Segoe UI", 10),
934
+ ).pack(side=tk.LEFT)
935
+ tk.Label(
936
+ row,
937
+ text=state,
938
+ bg="#1a202b",
939
+ fg="#4ade80" if target.detected else "#64748b",
940
+ font=("Segoe UI", 9),
941
+ ).pack(side=tk.RIGHT, padx=6)
942
+
943
+ self.log_text = tk.Text(
944
+ container,
945
+ height=7,
946
+ bg="#080b10",
947
+ fg="#a5f3fc",
948
+ insertbackground="#f8fafc",
949
+ relief=tk.FLAT,
950
+ font=("Consolas", 9),
951
+ state=tk.DISABLED,
952
+ )
953
+ self.log_text.pack(fill=tk.BOTH, expand=False, pady=(12, 8))
954
+
955
+ buttons = tk.Frame(container, bg="#11151c")
956
+ buttons.pack(fill=tk.X)
957
+ ttk.Button(buttons, text="Select all", command=self._select_all).pack(side=tk.LEFT)
958
+ self.install_button = ttk.Button(
959
+ buttons, text="Install to selected IDEs", command=self.install_selected
960
+ )
961
+ self.install_button.pack(side=tk.RIGHT)
962
+
963
+ tk.Label(
964
+ container,
965
+ text="Zero configuration required. Restart IDEs after installation.",
966
+ bg="#11151c",
967
+ fg="#94a3b8",
968
+ font=("Segoe UI", 9),
969
+ ).pack(anchor="w", pady=(10, 0))
970
+
971
+ def _select_all(self) -> None:
972
+ for variable in self.check_vars.values():
973
+ variable.set(True)
974
+
975
+ def _log(self, message: str) -> None:
976
+ import tkinter as tk
977
+ self.log_text.configure(state=tk.NORMAL)
978
+ self.log_text.insert(tk.END, message + "\n")
979
+ self.log_text.see(tk.END)
980
+ self.log_text.configure(state=tk.DISABLED)
981
+
982
+ def install_selected(self) -> None:
983
+ import tkinter as tk
984
+ from tkinter import messagebox
985
+
986
+ selected = [
987
+ target for target in self.targets if self.check_vars[target.key].get()
988
+ ]
989
+ if not selected:
990
+ messagebox.showwarning("T-Zero MCP Installer", "Select at least one client.")
991
+ return
992
+
993
+ self.install_button.configure(state=tk.DISABLED)
994
+ try:
995
+ successes, failures = install_targets(selected, log_fn=self._log)
996
+ message = f"Configured {successes} client(s)."
997
+ if failures:
998
+ message += f" {failures} client(s) were skipped; see log."
999
+ messagebox.showinfo("T-Zero MCP Installer", message)
1000
+ except Exception as error:
1001
+ self._log(f"Installer failed: {error}")
1002
+ messagebox.showerror("T-Zero MCP Installer", f"Installer failed: {error}")
1003
+ finally:
1004
+ self.install_button.configure(state=tk.NORMAL)
1005
+
1006
+
1007
+ def run_cli() -> int:
1008
+ """Executes the CLI interface when called from command line or with flags."""
1009
+ _attach_windows_console()
1010
+
1011
+ parser = argparse.ArgumentParser(
1012
+ prog="addmcp",
1013
+ description="T-Zero MCP 1-Click Installer for Cursor, Claude Desktop, Antigravity, VS Code, Windsurf, etc."
1014
+ )
1015
+ parser.add_argument(
1016
+ "--all", "-a", action="store_true",
1017
+ help="Install into all detected IDEs without GUI."
1018
+ )
1019
+ parser.add_argument(
1020
+ "--targets", "-t", metavar="KEYS",
1021
+ help="Comma-separated list of target keys to install to (e.g. cursor,claude-desktop,antigravity)."
1022
+ )
1023
+ parser.add_argument(
1024
+ "--list", "-l", action="store_true",
1025
+ help="List all supported and detected IDE targets."
1026
+ )
1027
+ parser.add_argument(
1028
+ "--gui", "-g", action="store_true",
1029
+ help="Explicitly launch the GUI installer window."
1030
+ )
1031
+ parser.add_argument(
1032
+ "--version", "-v", action="version",
1033
+ version=f"T-Zero MCP Installer {APP_VERSION}"
1034
+ )
1035
+
1036
+ args, unknown = parser.parse_known_args()
1037
+ all_targets = build_client_targets()
1038
+
1039
+ if args.list:
1040
+ print(f"\n[T-Zero MCP Installer v{APP_VERSION}] Available IDE Targets:\n")
1041
+ for t in all_targets:
1042
+ state = "DETECTED" if t.detected else "not found"
1043
+ print(f" [{state:^9}] {t.key:<15} : {t.name} ({t.config_path})")
1044
+ print()
1045
+ return 0
1046
+
1047
+ if args.all or args.targets:
1048
+ if args.all:
1049
+ selected = [t for t in all_targets if t.detected]
1050
+ if not selected:
1051
+ print("[T-Zero MCP] No installed IDE clients detected automatically.")
1052
+ selected = all_targets
1053
+ else:
1054
+ keys = [k.strip().lower() for k in args.targets.split(",")]
1055
+ selected = [t for t in all_targets if t.key.lower() in keys]
1056
+
1057
+ if not selected:
1058
+ print("[T-Zero MCP] No valid targets matched.")
1059
+ return 1
1060
+
1061
+ print(f"\n[T-Zero MCP Installer v{APP_VERSION}] Installing to {len(selected)} target(s)...")
1062
+ successes, failures = install_targets(selected, log_fn=lambda m: print(f" -> {m}"))
1063
+ print(f"[T-Zero MCP] Completed: {successes} configured, {failures} failed.")
1064
+ print("[*] Enjoying T-Zero? Please star the project on GitHub: https://github.com/toprakahmetaydogmus/TZeroAlgorithm\n")
1065
+ return 0 if failures == 0 else 1
1066
+
1067
+ # Default action: launch GUI if display available, otherwise list targets
1068
+ try:
1069
+ import tkinter as tk
1070
+ root = tk.Tk()
1071
+ AddMCPApp(root)
1072
+ root.mainloop()
1073
+ return 0
1074
+ except Exception as e:
1075
+ print(f"[T-Zero MCP] GUI unavailable ({e}). Defaulting to automatic CLI install:")
1076
+ selected = [t for t in all_targets if t.detected]
1077
+ if not selected:
1078
+ selected = all_targets
1079
+ successes, failures = install_targets(selected, log_fn=lambda m: print(f" -> {m}"))
1080
+ print("[*] Enjoying T-Zero? Please star the project on GitHub: https://github.com/toprakahmetaydogmus/TZeroAlgorithm\n")
1081
+ return 0 if failures == 0 else 1
1082
+
1083
+
1084
+ def run_init(argv: Optional[List[str]] = None) -> int:
1085
+ """1-Click T-Zero initialization for modern AI IDEs.
1086
+
1087
+ Usage:
1088
+ tzero init # Auto-detects and installs to all installed IDEs
1089
+ tzero init --cursor # Installs directly to Cursor (.cursor/mcp.json)
1090
+ tzero init --claude # Installs to Claude Desktop & Claude Code
1091
+ tzero init --windsurf # Installs to Windsurf
1092
+ tzero init --vscode # Installs to VS Code / Copilot
1093
+ tzero init --all # Installs to all supported IDEs
1094
+ tzero init --list # Lists detected status of all supported IDEs
1095
+ """
1096
+ _attach_windows_console()
1097
+ if argv is None:
1098
+ argv = sys.argv[2:] if (len(sys.argv) > 1 and sys.argv[1].lower() == "init") else []
1099
+
1100
+ all_targets = build_client_targets()
1101
+ target_map = {t.key.lower(): t for t in all_targets}
1102
+
1103
+ # Aliases
1104
+ aliases = {
1105
+ "cursor": ["cursor"],
1106
+ "claude": ["claude-desktop", "claude-code"],
1107
+ "claude-desktop": ["claude-desktop"],
1108
+ "claude-code": ["claude-code"],
1109
+ "windsurf": ["windsurf"],
1110
+ "vscode": ["vscode"],
1111
+ "copilot": ["vscode"],
1112
+ "cline": ["cline"],
1113
+ "roo": ["roo-code"],
1114
+ "roo-code": ["roo-code"],
1115
+ "antigravity": ["antigravity"],
1116
+ "gemini": ["gemini-cli"],
1117
+ "gemini-cli": ["gemini-cli"],
1118
+ }
1119
+
1120
+ # Print banner
1121
+ print("""
1122
+ \033[1;36m================================================================================
1123
+ ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v11.11.0)
1124
+ ================================================================================\033[0m
1125
+ \033[32m🎯 Zero-Config AST Codebase Context & 100% Zero-Leak Security Guard\033[0m
1126
+ """)
1127
+
1128
+ # Parse arguments
1129
+ flags = [a.lower().lstrip("-") for a in argv]
1130
+ if "list" in flags or "l" in flags or "--list" in argv:
1131
+ print("\033[1;33m📋 Supported & Detected IDE Environments:\033[0m\n")
1132
+ for t in all_targets:
1133
+ state = "\033[32m✓ DETECTED\033[0m" if t.detected else "\033[90mnot found \033[0m"
1134
+ print(f" [{state}] {t.name:<25} : key='{t.key}' ({t.config_path})")
1135
+ print("\n\033[36m💡 Run: 'tzero init' to install to all detected IDEs automatically.\033[0m\n")
1136
+ return 0
1137
+
1138
+ selected_keys = set()
1139
+ install_all_mode = "all" in flags or "-a" in argv or "--all" in argv or not flags
1140
+
1141
+ if install_all_mode:
1142
+ detected_targets = [t for t in all_targets if t.detected]
1143
+ if detected_targets:
1144
+ selected_targets = detected_targets
1145
+ print(f"\033[34m[AUTO-DETECT]\033[0m Found {len(selected_targets)} active IDE environment(s):")
1146
+ for t in selected_targets:
1147
+ print(f" • {t.name}")
1148
+ else:
1149
+ print("\033[33m[INFO]\033[0m No active IDEs currently detected; configuring default targets (Cursor, Claude, VS Code, Windsurf)...")
1150
+ selected_targets = [t for t in all_targets if t.key in ("cursor", "claude-desktop", "vscode", "windsurf")]
1151
+ else:
1152
+ for f in flags:
1153
+ if f in aliases:
1154
+ selected_keys.update(aliases[f])
1155
+ elif f in target_map:
1156
+ selected_keys.add(f)
1157
+ selected_targets = [t for t in all_targets if t.key in selected_keys]
1158
+
1159
+ if not selected_targets:
1160
+ print(f"\033[31m[ERROR]\033[0m No matching IDE target found for: {argv}")
1161
+ print("Available targets: cursor, claude, windsurf, vscode, cline, roo, antigravity, gemini, all")
1162
+ return 1
1163
+
1164
+ print(f"\n\033[35m[INSTALLING]\033[0m Configuring {len(selected_targets)} target(s)...")
1165
+ successes, failures = install_targets(
1166
+ selected_targets,
1167
+ log_fn=lambda m: print(f" \033[32m✓\033[0m {m}")
1168
+ )
1169
+
1170
+ print(f"\n\033[1;32m🎉 [SUCCESS] T-Zero MCP Server successfully registered in {successes} client(s)!\033[0m")
1171
+ if failures:
1172
+ print(f"\033[33m⚠️ {failures} client(s) could not be updated.\033[0m")
1173
+
1174
+ print("""
1175
+ \033[1;37m🚀 HOW TO USE IN YOUR IDE (CURSOR, CLAUDE, WINDSURF):
1176
+ 1. Restart your IDE or Reload Window.
1177
+ 2. In Composer / Chat, prompt your agent:\033[0m
1178
+ \033[36m"Use T-Zero to get the project skeleton and analyze the blast radius."\033[0m
1179
+ \033[36m"Use tzero reduce_tokens to prune noise and audit zero-leak security."\033[0m
1180
+
1181
+ \033[1;36m┌──────────────────────────────────────────────────────────────────────────────┐
1182
+ │ ⚡ SIBER AKADEMI T-ZERO CONTEXT ARCHITECT & MCP ENGINE │
1183
+ │ │
1184
+ │ Engineered by Toprak Ahmet Aydoğmuş (15-year-old solo dev) & Siber Akademi │
1185
+ │ to eliminate token bloat, costs, and AI hallucinations worldwide. │
1186
+ │ Search "Toprak Ahmet Aydoğmuş" on Google to learn more! │
1187
+ │ │
1188
+ │ If this open-source tool saved you tokens or improved your coding flow: │
1189
+ │ 👉 Please consider giving it a ⭐ on GitHub: │
1190
+ │ https://github.com/toprakahmetaydogmus/TZeroAlgorithm │
1191
+ │ │
1192
+ │ 100% Free & Open-Source under MIT License. Thank you! 🚀 │
1193
+ └──────────────────────────────────────────────────────────────────────────────┘\033[0m
1194
+ """)
1195
+ return 0 if failures == 0 else 1
1196
+
1197
+
1198
+ def main() -> None:
1199
+ sys.exit(run_cli())
1200
+
1201
+
1202
+ if __name__ == "__main__":
1203
+ main()