tzero-mcp 10.7.0 → 10.7.1

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 (96) hide show
  1. package/bin/tzero-mcp.js +9 -16
  2. package/bin/tzero.js +9 -16
  3. package/index.js +7 -2
  4. package/package.json +2 -1
  5. package/src/addmcp.py +1194 -0
  6. package/src/main.py +60 -0
  7. package/src/siber_akademi_icon.py +77 -0
  8. package/src/tzero/jarvis/semantic_compressor.py +373 -0
  9. package/src/tzero.py +58 -0
  10. package/src/tzero_benchmark.py +475 -0
  11. package/src/tzero_bridge.py +362 -0
  12. package/src/tzero_ci.py +153 -0
  13. package/src/tzero_commit.py +192 -0
  14. package/src/tzero_cost.py +163 -0
  15. package/src/tzero_dashboard.py +1448 -0
  16. package/src/tzero_deps.py +287 -0
  17. package/src/tzero_drift.py +208 -0
  18. package/src/tzero_explain.py +240 -0
  19. package/src/tzero_features.py +3022 -0
  20. package/src/tzero_fix.py +228 -0
  21. package/src/tzero_fixer/__init__.py +63 -0
  22. package/src/tzero_fixer/amalgamation.py +334 -0
  23. package/src/tzero_fixer/ast_syntax_healer.py +464 -0
  24. package/src/tzero_fixer/ast_type_modernizer.py +288 -0
  25. package/src/tzero_fixer/async_io_modernizer.py +127 -0
  26. package/src/tzero_fixer/automated_regression_suite.py +600 -0
  27. package/src/tzero_fixer/benchmarks_and_diagnostics.py +174 -0
  28. package/src/tzero_fixer/ci_cd_self_healing_gate.py +246 -0
  29. package/src/tzero_fixer/code_duplicity_and_refactorer.py +151 -0
  30. package/src/tzero_fixer/code_smells_healer.py +260 -0
  31. package/src/tzero_fixer/cwe_remediator.py +171 -0
  32. package/src/tzero_fixer/dead_code_eliminator.py +150 -0
  33. package/src/tzero_fixer/dependency_vulnerability_auditor.py +309 -0
  34. package/src/tzero_fixer/git_advanced_surgeon.py +280 -0
  35. package/src/tzero_fixer/hardware_and_disk_doctor.py +325 -0
  36. package/src/tzero_fixer/import_graph_healer.py +412 -0
  37. package/src/tzero_fixer/interactive_tui.py +91 -0
  38. package/src/tzero_fixer/knowledge_base.py +295 -0
  39. package/src/tzero_fixer/knowledge_base_extended.py +940 -0
  40. package/src/tzero_fixer/linters_and_static_analyzer.py +307 -0
  41. package/src/tzero_fixer/mcp_server.py +447 -0
  42. package/src/tzero_fixer/models.py +385 -0
  43. package/src/tzero_fixer/orchestrator.py +375 -0
  44. package/src/tzero_fixer/os_doctor.py +502 -0
  45. package/src/tzero_fixer/packaging_abi_surgeon.py +323 -0
  46. package/src/tzero_fixer/pc_fixer_doctor.py +599 -0
  47. package/src/tzero_fixer/performance_and_memory_profiler.py +274 -0
  48. package/src/tzero_fixer/polyglot_ast_parsers.py +313 -0
  49. package/src/tzero_fixer/polyglot_build_healer.py +364 -0
  50. package/src/tzero_fixer/polyglot_config_healer.py +318 -0
  51. package/src/tzero_fixer/polyglot_doctor.py +372 -0
  52. package/src/tzero_fixer/polyglot_linters.py +619 -0
  53. package/src/tzero_fixer/polyglot_schema_validator.py +305 -0
  54. package/src/tzero_fixer/security_cwe_database.py +444 -0
  55. package/src/tzero_fixer/security_deep_rules.py +114 -0
  56. package/src/tzero_fixer/security_rules_catalog.py +110 -0
  57. package/src/tzero_fixer/security_zero_leak.py +326 -0
  58. package/src/tzero_fixer/smart_patch_recommender.py +223 -0
  59. package/src/tzero_fixer/synthetic_workspace_generator.py +220 -0
  60. package/src/tzero_fixer/system_diagnostics_extended.py +493 -0
  61. package/src/tzero_fixer/system_repair_recipes.py +447 -0
  62. package/src/tzero_fixer/venv_doctor.py +309 -0
  63. package/src/tzero_gateway.py +885 -0
  64. package/src/tzero_guard.py +243 -0
  65. package/src/tzero_infra.py +274 -0
  66. package/src/tzero_jarvis/__init__.py +124 -0
  67. package/src/tzero_jarvis/causal_graph.py +310 -0
  68. package/src/tzero_jarvis/graph_visualizer.py +395 -0
  69. package/src/tzero_jarvis/hybrid_search.py +214 -0
  70. package/src/tzero_jarvis/latent_press.py +137 -0
  71. package/src/tzero_jarvis/memory_consolidation.py +212 -0
  72. package/src/tzero_jarvis/minhash_lsh.py +184 -0
  73. package/src/tzero_jarvis/orchestrator.py +335 -0
  74. package/src/tzero_jarvis/self_healing.py +308 -0
  75. package/src/tzero_jarvis/semantic_compressor.py +887 -0
  76. package/src/tzero_jarvis/swarm.py +261 -0
  77. package/src/tzero_jarvis/swarm_bft.py +144 -0
  78. package/src/tzero_jarvis/workspace_orchestrator.py +1167 -0
  79. package/src/tzero_jarvis/zero_key_router.py +173 -0
  80. package/src/tzero_mcp.py +4858 -0
  81. package/src/tzero_neural_cortex.py +1425 -0
  82. package/src/tzero_packer.py +370 -0
  83. package/src/tzero_patch.py +624 -0
  84. package/src/tzero_pc_fixer.py +12657 -0
  85. package/src/tzero_pipe.py +95 -0
  86. package/src/tzero_polyglot.py +422 -0
  87. package/src/tzero_reachability.py +272 -0
  88. package/src/tzero_replay.py +141 -0
  89. package/src/tzero_security.py +570 -0
  90. package/src/tzero_snapshot.py +258 -0
  91. package/src/tzero_stubs.py +313 -0
  92. package/src/tzero_superdesign.py +774 -0
  93. package/src/tzero_sync.py +241 -0
  94. package/src/tzero_task_benchmark.py +363 -0
  95. package/src/tzero_tui.py +244 -0
  96. package/src/tzero_v3.py +9435 -0
package/src/addmcp.py ADDED
@@ -0,0 +1,1194 @@
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 = "10.2.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_mcp.py",
813
+ Path.cwd() / "tzero_mcp.py",
814
+ ]:
815
+ if script_cand.is_file():
816
+ return script_cand.resolve()
817
+
818
+ raise FileNotFoundError(
819
+ f"Neither '{SERVER_FILENAME}' nor 'tzero_mcp.py' could be found."
820
+ )
821
+
822
+
823
+ def install_targets(
824
+ targets: List[ClientTarget],
825
+ log_fn: Optional[Callable[[str], None]] = None,
826
+ server_path: Optional[Path] = None,
827
+ ) -> Tuple[int, int]:
828
+ """Installs server to specified client targets, returning (successes, failures)."""
829
+ if log_fn is None:
830
+ log_fn = lambda msg: print(f"[T-Zero MCP] {msg}")
831
+
832
+ if server_path is None:
833
+ server_path = resolve_and_install_server()
834
+
835
+ log_fn(f"Runtime resolved: {server_path}")
836
+ successes = 0
837
+ failures = 0
838
+ for target in targets:
839
+ try:
840
+ result = merge_server_config(target, server_path)
841
+ status = str(result["status"]).capitalize()
842
+ log_fn(f"{status}: {target.name} -> {target.config_path}")
843
+ if result.get("backup"):
844
+ log_fn(f"Backup created: {result['backup']}")
845
+ successes += 1
846
+ except Exception as error:
847
+ failures += 1
848
+ log_fn(f"Failed for {target.name}: {error}")
849
+
850
+ return successes, failures
851
+
852
+
853
+ class AddMCPApp:
854
+ def __init__(self, root: object):
855
+ import tkinter as tk
856
+ from tkinter import ttk
857
+ self.root = root # type: ignore
858
+ self.targets = build_client_targets()
859
+ self.check_vars: Dict[str, tk.BooleanVar] = {}
860
+ self.root.title("T-Zero MCP Installer")
861
+ self.root.geometry("720x650")
862
+ self.root.minsize(600, 540)
863
+ self.root.configure(bg="#11151c")
864
+
865
+ icon_path = _resource_path("siber_akademi.ico")
866
+ if icon_path.is_file():
867
+ try:
868
+ self.root.iconbitmap(str(icon_path))
869
+ except Exception:
870
+ pass
871
+
872
+ self._create_widgets()
873
+
874
+ def _create_widgets(self) -> None:
875
+ import tkinter as tk
876
+ from tkinter import ttk
877
+
878
+ container = tk.Frame(self.root, bg="#11151c", padx=24, pady=20)
879
+ container.pack(fill=tk.BOTH, expand=True)
880
+
881
+ tk.Label(
882
+ container,
883
+ text="SIBER AKADEMI / T-ZERO MCP",
884
+ bg="#11151c",
885
+ fg="#22d3ee",
886
+ font=("Segoe UI", 16, "bold"),
887
+ ).pack(anchor="w")
888
+ tk.Label(
889
+ container,
890
+ text="Install the bundled local MCP server in supported IDE configurations.",
891
+ bg="#11151c",
892
+ fg="#cbd5e1",
893
+ font=("Segoe UI", 10),
894
+ ).pack(anchor="w", pady=(5, 14))
895
+
896
+ self.detected_label = tk.Label(
897
+ container,
898
+ text="Detected clients are selected by default. Existing config files are backed up before changes.",
899
+ bg="#11151c",
900
+ fg="#94a3b8",
901
+ font=("Segoe UI", 9),
902
+ wraplength=660,
903
+ justify="left",
904
+ )
905
+ self.detected_label.pack(anchor="w", pady=(0, 8))
906
+
907
+ list_frame = tk.Frame(container, bg="#1a202b", padx=12, pady=8)
908
+ list_frame.pack(fill=tk.BOTH, expand=True)
909
+ for target in self.targets:
910
+ state = "Detected" if target.detected else "Not detected"
911
+ variable = tk.BooleanVar(value=target.detected)
912
+ self.check_vars[target.key] = variable
913
+ row = tk.Frame(list_frame, bg="#1a202b")
914
+ row.pack(fill=tk.X, pady=2)
915
+ tk.Checkbutton(
916
+ row,
917
+ text=target.name,
918
+ variable=variable,
919
+ bg="#1a202b",
920
+ fg="#f1f5f9",
921
+ activebackground="#1a202b",
922
+ activeforeground="#f1f5f9",
923
+ selectcolor="#0f172a",
924
+ font=("Segoe UI", 10),
925
+ ).pack(side=tk.LEFT)
926
+ tk.Label(
927
+ row,
928
+ text=state,
929
+ bg="#1a202b",
930
+ fg="#4ade80" if target.detected else "#64748b",
931
+ font=("Segoe UI", 9),
932
+ ).pack(side=tk.RIGHT, padx=6)
933
+
934
+ self.log_text = tk.Text(
935
+ container,
936
+ height=7,
937
+ bg="#080b10",
938
+ fg="#a5f3fc",
939
+ insertbackground="#f8fafc",
940
+ relief=tk.FLAT,
941
+ font=("Consolas", 9),
942
+ state=tk.DISABLED,
943
+ )
944
+ self.log_text.pack(fill=tk.BOTH, expand=False, pady=(12, 8))
945
+
946
+ buttons = tk.Frame(container, bg="#11151c")
947
+ buttons.pack(fill=tk.X)
948
+ ttk.Button(buttons, text="Select all", command=self._select_all).pack(side=tk.LEFT)
949
+ self.install_button = ttk.Button(
950
+ buttons, text="Install to selected IDEs", command=self.install_selected
951
+ )
952
+ self.install_button.pack(side=tk.RIGHT)
953
+
954
+ tk.Label(
955
+ container,
956
+ text="Zero configuration required. Restart IDEs after installation.",
957
+ bg="#11151c",
958
+ fg="#94a3b8",
959
+ font=("Segoe UI", 9),
960
+ ).pack(anchor="w", pady=(10, 0))
961
+
962
+ def _select_all(self) -> None:
963
+ for variable in self.check_vars.values():
964
+ variable.set(True)
965
+
966
+ def _log(self, message: str) -> None:
967
+ import tkinter as tk
968
+ self.log_text.configure(state=tk.NORMAL)
969
+ self.log_text.insert(tk.END, message + "\n")
970
+ self.log_text.see(tk.END)
971
+ self.log_text.configure(state=tk.DISABLED)
972
+
973
+ def install_selected(self) -> None:
974
+ import tkinter as tk
975
+ from tkinter import messagebox
976
+
977
+ selected = [
978
+ target for target in self.targets if self.check_vars[target.key].get()
979
+ ]
980
+ if not selected:
981
+ messagebox.showwarning("T-Zero MCP Installer", "Select at least one client.")
982
+ return
983
+
984
+ self.install_button.configure(state=tk.DISABLED)
985
+ try:
986
+ successes, failures = install_targets(selected, log_fn=self._log)
987
+ message = f"Configured {successes} client(s)."
988
+ if failures:
989
+ message += f" {failures} client(s) were skipped; see log."
990
+ messagebox.showinfo("T-Zero MCP Installer", message)
991
+ except Exception as error:
992
+ self._log(f"Installer failed: {error}")
993
+ messagebox.showerror("T-Zero MCP Installer", f"Installer failed: {error}")
994
+ finally:
995
+ self.install_button.configure(state=tk.NORMAL)
996
+
997
+
998
+ def run_cli() -> int:
999
+ """Executes the CLI interface when called from command line or with flags."""
1000
+ _attach_windows_console()
1001
+
1002
+ parser = argparse.ArgumentParser(
1003
+ prog="addmcp",
1004
+ description="T-Zero MCP 1-Click Installer for Cursor, Claude Desktop, Antigravity, VS Code, Windsurf, etc."
1005
+ )
1006
+ parser.add_argument(
1007
+ "--all", "-a", action="store_true",
1008
+ help="Install into all detected IDEs without GUI."
1009
+ )
1010
+ parser.add_argument(
1011
+ "--targets", "-t", metavar="KEYS",
1012
+ help="Comma-separated list of target keys to install to (e.g. cursor,claude-desktop,antigravity)."
1013
+ )
1014
+ parser.add_argument(
1015
+ "--list", "-l", action="store_true",
1016
+ help="List all supported and detected IDE targets."
1017
+ )
1018
+ parser.add_argument(
1019
+ "--gui", "-g", action="store_true",
1020
+ help="Explicitly launch the GUI installer window."
1021
+ )
1022
+ parser.add_argument(
1023
+ "--version", "-v", action="version",
1024
+ version=f"T-Zero MCP Installer {APP_VERSION}"
1025
+ )
1026
+
1027
+ args, unknown = parser.parse_known_args()
1028
+ all_targets = build_client_targets()
1029
+
1030
+ if args.list:
1031
+ print(f"\n[T-Zero MCP Installer v{APP_VERSION}] Available IDE Targets:\n")
1032
+ for t in all_targets:
1033
+ state = "DETECTED" if t.detected else "not found"
1034
+ print(f" [{state:^9}] {t.key:<15} : {t.name} ({t.config_path})")
1035
+ print()
1036
+ return 0
1037
+
1038
+ if args.all or args.targets:
1039
+ if args.all:
1040
+ selected = [t for t in all_targets if t.detected]
1041
+ if not selected:
1042
+ print("[T-Zero MCP] No installed IDE clients detected automatically.")
1043
+ selected = all_targets
1044
+ else:
1045
+ keys = [k.strip().lower() for k in args.targets.split(",")]
1046
+ selected = [t for t in all_targets if t.key.lower() in keys]
1047
+
1048
+ if not selected:
1049
+ print("[T-Zero MCP] No valid targets matched.")
1050
+ return 1
1051
+
1052
+ print(f"\n[T-Zero MCP Installer v{APP_VERSION}] Installing to {len(selected)} target(s)...")
1053
+ successes, failures = install_targets(selected, log_fn=lambda m: print(f" -> {m}"))
1054
+ print(f"[T-Zero MCP] Completed: {successes} configured, {failures} failed.")
1055
+ print("[*] Enjoying T-Zero? Please star the project on GitHub: https://github.com/toprakahmetaydogmus/TZeroAlgorithm\n")
1056
+ return 0 if failures == 0 else 1
1057
+
1058
+ # Default action: launch GUI if display available, otherwise list targets
1059
+ try:
1060
+ import tkinter as tk
1061
+ root = tk.Tk()
1062
+ AddMCPApp(root)
1063
+ root.mainloop()
1064
+ return 0
1065
+ except Exception as e:
1066
+ print(f"[T-Zero MCP] GUI unavailable ({e}). Defaulting to automatic CLI install:")
1067
+ selected = [t for t in all_targets if t.detected]
1068
+ if not selected:
1069
+ selected = all_targets
1070
+ successes, failures = install_targets(selected, log_fn=lambda m: print(f" -> {m}"))
1071
+ print("[*] Enjoying T-Zero? Please star the project on GitHub: https://github.com/toprakahmetaydogmus/TZeroAlgorithm\n")
1072
+ return 0 if failures == 0 else 1
1073
+
1074
+
1075
+ def run_init(argv: Optional[List[str]] = None) -> int:
1076
+ """1-Click T-Zero initialization for modern AI IDEs.
1077
+
1078
+ Usage:
1079
+ tzero init # Auto-detects and installs to all installed IDEs
1080
+ tzero init --cursor # Installs directly to Cursor (.cursor/mcp.json)
1081
+ tzero init --claude # Installs to Claude Desktop & Claude Code
1082
+ tzero init --windsurf # Installs to Windsurf
1083
+ tzero init --vscode # Installs to VS Code / Copilot
1084
+ tzero init --all # Installs to all supported IDEs
1085
+ tzero init --list # Lists detected status of all supported IDEs
1086
+ """
1087
+ _attach_windows_console()
1088
+ if argv is None:
1089
+ argv = sys.argv[2:] if (len(sys.argv) > 1 and sys.argv[1].lower() == "init") else []
1090
+
1091
+ all_targets = build_client_targets()
1092
+ target_map = {t.key.lower(): t for t in all_targets}
1093
+
1094
+ # Aliases
1095
+ aliases = {
1096
+ "cursor": ["cursor"],
1097
+ "claude": ["claude-desktop", "claude-code"],
1098
+ "claude-desktop": ["claude-desktop"],
1099
+ "claude-code": ["claude-code"],
1100
+ "windsurf": ["windsurf"],
1101
+ "vscode": ["vscode"],
1102
+ "copilot": ["vscode"],
1103
+ "cline": ["cline"],
1104
+ "roo": ["roo-code"],
1105
+ "roo-code": ["roo-code"],
1106
+ "antigravity": ["antigravity"],
1107
+ "gemini": ["gemini-cli"],
1108
+ "gemini-cli": ["gemini-cli"],
1109
+ }
1110
+
1111
+ # Print banner
1112
+ print("""
1113
+ \033[1;36m================================================================================
1114
+ ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v10.0.0)
1115
+ ================================================================================\033[0m
1116
+ \033[32m🎯 Zero-Config AST Codebase Context & 100% Zero-Leak Security Guard\033[0m
1117
+ """)
1118
+
1119
+ # Parse arguments
1120
+ flags = [a.lower().lstrip("-") for a in argv]
1121
+ if "list" in flags or "l" in flags or "--list" in argv:
1122
+ print("\033[1;33m📋 Supported & Detected IDE Environments:\033[0m\n")
1123
+ for t in all_targets:
1124
+ state = "\033[32m✓ DETECTED\033[0m" if t.detected else "\033[90mnot found \033[0m"
1125
+ print(f" [{state}] {t.name:<25} : key='{t.key}' ({t.config_path})")
1126
+ print("\n\033[36m💡 Run: 'tzero init' to install to all detected IDEs automatically.\033[0m\n")
1127
+ return 0
1128
+
1129
+ selected_keys = set()
1130
+ install_all_mode = "all" in flags or "-a" in argv or "--all" in argv or not flags
1131
+
1132
+ if install_all_mode:
1133
+ detected_targets = [t for t in all_targets if t.detected]
1134
+ if detected_targets:
1135
+ selected_targets = detected_targets
1136
+ print(f"\033[34m[AUTO-DETECT]\033[0m Found {len(selected_targets)} active IDE environment(s):")
1137
+ for t in selected_targets:
1138
+ print(f" • {t.name}")
1139
+ else:
1140
+ print("\033[33m[INFO]\033[0m No active IDEs currently detected; configuring default targets (Cursor, Claude, VS Code, Windsurf)...")
1141
+ selected_targets = [t for t in all_targets if t.key in ("cursor", "claude-desktop", "vscode", "windsurf")]
1142
+ else:
1143
+ for f in flags:
1144
+ if f in aliases:
1145
+ selected_keys.update(aliases[f])
1146
+ elif f in target_map:
1147
+ selected_keys.add(f)
1148
+ selected_targets = [t for t in all_targets if t.key in selected_keys]
1149
+
1150
+ if not selected_targets:
1151
+ print(f"\033[31m[ERROR]\033[0m No matching IDE target found for: {argv}")
1152
+ print("Available targets: cursor, claude, windsurf, vscode, cline, roo, antigravity, gemini, all")
1153
+ return 1
1154
+
1155
+ print(f"\n\033[35m[INSTALLING]\033[0m Configuring {len(selected_targets)} target(s)...")
1156
+ successes, failures = install_targets(
1157
+ selected_targets,
1158
+ log_fn=lambda m: print(f" \033[32m✓\033[0m {m}")
1159
+ )
1160
+
1161
+ print(f"\n\033[1;32m🎉 [SUCCESS] T-Zero MCP Server successfully registered in {successes} client(s)!\033[0m")
1162
+ if failures:
1163
+ print(f"\033[33m⚠️ {failures} client(s) could not be updated.\033[0m")
1164
+
1165
+ print("""
1166
+ \033[1;37m🚀 HOW TO USE IN YOUR IDE (CURSOR, CLAUDE, WINDSURF):
1167
+ 1. Restart your IDE or Reload Window.
1168
+ 2. In Composer / Chat, prompt your agent:\033[0m
1169
+ \033[36m"Use T-Zero to get the project skeleton and analyze the blast radius."\033[0m
1170
+ \033[36m"Use tzero reduce_tokens to prune noise and audit zero-leak security."\033[0m
1171
+
1172
+ \033[1;33m┌──────────────────────────────────────────────────────────────────────────────┐
1173
+ │ ⭐ A MESSAGE FROM THE CREATOR │
1174
+ │ │
1175
+ │ Hi! I'm Toprak Ahmet Aydoğmuş, a 15-year-old self-taught developer from │
1176
+ │ Siber Akademi. I built T-Zero from scratch to eliminate token bloat and │
1177
+ │ AI hallucinations for programmers worldwide ($0.00 cloud cost). │
1178
+ │ │
1179
+ │ If this open-source tool saved you tokens or helped your coding flow: │
1180
+ │ 👉 Please consider giving it a ⭐ on GitHub: │
1181
+ │ https://github.com/toprakahmetaydogmus/TZeroAlgorithm │
1182
+ │ │
1183
+ │ Every star means the world and helps a young open-source developer grow! 🚀 │
1184
+ └──────────────────────────────────────────────────────────────────────────────┘\033[0m
1185
+ """)
1186
+ return 0 if failures == 0 else 1
1187
+
1188
+
1189
+ def main() -> None:
1190
+ sys.exit(run_cli())
1191
+
1192
+
1193
+ if __name__ == "__main__":
1194
+ main()