github-ai-mcp 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. github_ai_mcp/__init__.py +1 -0
  2. github_ai_mcp/__main__.py +3 -0
  3. github_ai_mcp/cli/__init__.py +1 -0
  4. github_ai_mcp/cli/app.py +128 -0
  5. github_ai_mcp/config.py +112 -0
  6. github_ai_mcp/core/__init__.py +1 -0
  7. github_ai_mcp/core/git_engine.py +76 -0
  8. github_ai_mcp/core/github_api.py +86 -0
  9. github_ai_mcp/core/job_engine.py +889 -0
  10. github_ai_mcp/core/locking.py +41 -0
  11. github_ai_mcp/desktop/__init__.py +1 -0
  12. github_ai_mcp/desktop/control.py +26 -0
  13. github_ai_mcp/desktop/entry.py +77 -0
  14. github_ai_mcp/desktop/legal.py +9 -0
  15. github_ai_mcp/desktop/prerequisites.py +31 -0
  16. github_ai_mcp/desktop/processes.py +116 -0
  17. github_ai_mcp/desktop/runtime.py +34 -0
  18. github_ai_mcp/desktop/setup.py +408 -0
  19. github_ai_mcp/desktop/startup.py +64 -0
  20. github_ai_mcp/desktop/streams.py +50 -0
  21. github_ai_mcp/desktop/supervisor.py +358 -0
  22. github_ai_mcp/desktop/tunnel.py +242 -0
  23. github_ai_mcp/exceptions.py +6 -0
  24. github_ai_mcp/gui/__init__.py +1 -0
  25. github_ai_mcp/gui/app.py +969 -0
  26. github_ai_mcp/gui/workers.py +26 -0
  27. github_ai_mcp/security/__init__.py +1 -0
  28. github_ai_mcp/security/auth_github.py +67 -0
  29. github_ai_mcp/security/auth_mcp.py +38 -0
  30. github_ai_mcp/security/paths.py +34 -0
  31. github_ai_mcp/security/policy.py +40 -0
  32. github_ai_mcp/security/secret_scan.py +24 -0
  33. github_ai_mcp/server.py +97 -0
  34. github_ai_mcp/storage/__init__.py +1 -0
  35. github_ai_mcp/storage/database.py +88 -0
  36. github_ai_mcp/tool_definitions.py +185 -0
  37. github_ai_mcp-1.0.2.dist-info/METADATA +33 -0
  38. github_ai_mcp-1.0.2.dist-info/RECORD +42 -0
  39. github_ai_mcp-1.0.2.dist-info/WHEEL +5 -0
  40. github_ai_mcp-1.0.2.dist-info/entry_points.txt +2 -0
  41. github_ai_mcp-1.0.2.dist-info/licenses/LICENSE +21 -0
  42. github_ai_mcp-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,358 @@
1
+ """Serialized, ownership-verified lifecycle with bounded recovery and redacted logs."""
2
+ import json
3
+ import hashlib
4
+ import os
5
+ import secrets
6
+ import random
7
+ import shutil
8
+ import socket
9
+ import subprocess
10
+ import threading
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import httpx
15
+ import psutil
16
+
17
+ from github_ai_mcp.config import load_config
18
+ from github_ai_mcp.desktop.processes import ProcessTree, background_options
19
+ from github_ai_mcp.desktop.runtime import service_command, bundled_tool
20
+ from github_ai_mcp.desktop.tunnel import preflight, external_processes, health_observation
21
+ from github_ai_mcp.exceptions import AppError
22
+ from github_ai_mcp.security.auth_github import get_secret
23
+ from github_ai_mcp.security.secret_scan import redact
24
+
25
+
26
+ def port_open(port):
27
+ with socket.socket() as probe:
28
+ probe.settimeout(0.3)
29
+ return probe.connect_ex(("127.0.0.1", port)) == 0
30
+
31
+
32
+ class Supervisor:
33
+ def __init__(self, config_path: Path):
34
+ self.path = config_path.resolve()
35
+ self.config = load_config(self.path)
36
+ self.mutex = threading.RLock()
37
+ self.children: dict = {}
38
+ self.desired = {"mcp": False, "tunnel": False}
39
+ self.errors = {"mcp": "", "tunnel": ""}
40
+ self.error_codes = {"mcp": "", "tunnel": ""}
41
+ self.retries = {"mcp": 0, "tunnel": 0}
42
+ self.retry_at = {"mcp": 0.0, "tunnel": 0.0}
43
+ self.log_path = self.config.data_dir / "services.jsonl"
44
+ self.log_path.parent.mkdir(parents=True, exist_ok=True)
45
+ self.log_mutex = threading.Lock()
46
+ self.permanent = {"mcp": False, "tunnel": False}
47
+ self.last_output = {"mcp": "", "tunnel": ""}
48
+ self.control = secrets.token_urlsafe(32)
49
+ self.hidden = [self.control]
50
+
51
+ def log(self, name, event):
52
+ message = str(event)
53
+ for secret in self.hidden:
54
+ message = message.replace(secret, "[REDACTED]")
55
+ message = redact(message)
56
+ with self.log_mutex:
57
+ if self.log_path.exists() and self.log_path.stat().st_size > 2_000_000:
58
+ self.log_path.replace(self.log_path.with_suffix(".previous.jsonl"))
59
+ with self.log_path.open("a", encoding="utf-8") as stream:
60
+ stream.write(json.dumps({"time": time.time(), "service": name,
61
+ "event": redact(message[:8000])}, ensure_ascii=False) + "\n")
62
+
63
+ def logs(self):
64
+ if not self.log_path.exists():
65
+ return ""
66
+ with self.log_path.open("rb") as stream:
67
+ stream.seek(max(0, self.log_path.stat().st_size - 100_000))
68
+ return stream.read().decode("utf-8", "replace")
69
+
70
+ def _drain(self, name, process):
71
+ for line in iter(process.stdout.readline, b""):
72
+ message = line.decode("utf-8", "replace").rstrip()
73
+ for secret in self.hidden:
74
+ message = message.replace(secret, "[REDACTED]")
75
+ safe = redact(message)
76
+ self.last_output[name] = safe[:2000]
77
+ if name == "tunnel" and any(term in safe.lower() for term in
78
+ ("unauthorized", "authentication rejected", "invalid api key", "status 401", "status 403", "exit status 2", "yaml:", "not set")):
79
+ self.permanent[name] = True
80
+ self.log(name, safe)
81
+ process.stdout.close()
82
+
83
+ def _health(self):
84
+ token = get_secret("mcp-http")
85
+ if token not in self.hidden:
86
+ self.hidden.append(token)
87
+ with httpx.Client(timeout=0.8, trust_env=False) as client:
88
+ r = client.get(f"http://127.0.0.1:{self.config.port}/_local/health",
89
+ headers={"Authorization": "Bearer " + token})
90
+ r.raise_for_status()
91
+ data = r.json()
92
+ return data
93
+
94
+ def _health_pid_is_owned(self, pid):
95
+ child = self.children.get("mcp")
96
+ if not child or child[0].poll() is not None or type(pid) is not int:
97
+ return False
98
+ root_pid = child[0].pid
99
+ if pid == root_pid:
100
+ return True
101
+ try:
102
+ return any(process.pid == pid for process in
103
+ psutil.Process(root_pid).children(recursive=True))
104
+ except (psutil.Error, OSError):
105
+ return False
106
+
107
+ def start(self, name, retry=False):
108
+ with self.mutex:
109
+ if name not in self.desired:
110
+ raise ValueError("Unknown service")
111
+ child = self.children.get(name)
112
+ if child and child[0].poll() is None:
113
+ return self.status()
114
+ if not retry:
115
+ self.retries[name] = 0
116
+ self.permanent[name] = False
117
+ self.retry_at[name] = 0
118
+ self.last_output[name] = ""
119
+ self.desired[name] = True
120
+ self.errors[name] = ""
121
+ self.error_codes[name] = ""
122
+ process = None
123
+ tree = None
124
+ try:
125
+ if child:
126
+ child[1].close()
127
+ self.children.pop(name, None)
128
+ candidate = load_config(self.path)
129
+ mcp = self.children.get("mcp")
130
+ if mcp and mcp[0].poll() is None and candidate.port != self.config.port:
131
+ raise AppError("CONFIG_CHANGED", "Restart the application before changing the live MCP port")
132
+ self.config = candidate
133
+ env = os.environ.copy()
134
+ if name == "mcp":
135
+ if port_open(self.config.port):
136
+ # Even a compatible server is never adopted without ownership proof.
137
+ raise AppError("PORT_CONFLICT", "Port is occupied by another instance. Stop it in its owning application or change the configured port.")
138
+ get_secret("mcp-http")
139
+ env["GITHUB_AI_CONTROL"] = self.control
140
+ args = service_command(self.path)
141
+ else:
142
+ external, inaccessible = external_processes(self.config)
143
+ if external:
144
+ raise AppError("EXTERNAL_TUNNEL", "External tunnel client detected; stop it in its owning application / Найден внешний клиент: остановите его в исходном приложении")
145
+ if inaccessible:
146
+ raise AppError("EXTERNAL_UNKNOWN", "Process inspection denied; duplicate safety cannot be verified / Доступ к процессам запрещён: нельзя исключить дубликат")
147
+ args, env, _ = preflight(self.config, self.path)
148
+ key = env["CONTROL_PLANE_API_KEY"]
149
+ if key not in self.hidden:
150
+ self.hidden.append(key)
151
+ process = subprocess.Popen(args, cwd=self.path.parent, env=env, stdin=subprocess.DEVNULL,
152
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **background_options(suspended=True))
153
+ tree = ProcessTree(process, suspended=True)
154
+ self.children[name] = (process, tree, time.monotonic())
155
+ threading.Thread(target=self._drain, args=(name, process), daemon=True).start()
156
+ self.log(name, "started owned process " + str(process.pid))
157
+ except Exception as error:
158
+ if tree is not None:
159
+ tree.close()
160
+ elif process is not None and process.poll() is None:
161
+ process.kill()
162
+ if process is not None:
163
+ process.wait(timeout=5)
164
+ if process.stdout:
165
+ process.stdout.close()
166
+ self.children.pop(name, None)
167
+ self.error_codes[name] = error.code if isinstance(error, AppError) else "START_FAILED"
168
+ self.permanent[name] = isinstance(error, AppError) and error.code not in {"DOCTOR_TIMEOUT"}
169
+ self.errors[name] = str(error) if isinstance(error, AppError) else "Service start failed; check selected executable and configuration"
170
+ self.log(name, self.errors[name])
171
+ if not retry:
172
+ self.desired[name] = not self.permanent[name]
173
+ raise AppError("START_FAILED", self.errors[name]) from None
174
+ return self.status()
175
+
176
+ def stop(self, name):
177
+ with self.mutex:
178
+ self.desired[name] = False
179
+ self.errors[name] = ""
180
+ self.error_codes[name] = ""
181
+ child = self.children.get(name)
182
+ if child:
183
+ process, tree, _ = child
184
+ if process.poll() is None:
185
+ if name == "mcp":
186
+ try:
187
+ data = self._health()
188
+ if data.get("instance") != hashlib.sha256(self.control.encode()).hexdigest() or not self._health_pid_is_owned(data.get("pid")):
189
+ raise AppError("OWNERSHIP_FAILED", "Server identity mismatch")
190
+ with httpx.Client(timeout=2, trust_env=False) as client:
191
+ response = client.post(f"http://127.0.0.1:{self.config.port}/_local/shutdown",
192
+ headers={"Authorization": "Bearer " + get_secret("mcp-http"),
193
+ "X-Local-Control": self.control})
194
+ response.raise_for_status()
195
+ process.wait(timeout=6)
196
+ except (httpx.HTTPError, ValueError, AppError, subprocess.TimeoutExpired):
197
+ self.log(name, "graceful shutdown unavailable; terminating owned process tree")
198
+ tree.kill()
199
+ else:
200
+ # No undocumented tunnel shutdown API is assumed.
201
+ process.terminate()
202
+ try:
203
+ process.wait(timeout=4)
204
+ except subprocess.TimeoutExpired:
205
+ tree.kill()
206
+ tree.close()
207
+ process.wait(timeout=5)
208
+ self.children.pop(name, None)
209
+ self.log(name, "owned process tree stopped")
210
+ if name == "mcp":
211
+ deadline = time.monotonic() + 3
212
+ while port_open(self.config.port) and time.monotonic() < deadline:
213
+ time.sleep(0.1)
214
+ if port_open(self.config.port):
215
+ self.errors[name] = "Owned process exited but port is occupied; unrelated listener left untouched"
216
+ raise AppError("PORT_CONFLICT", self.errors[name])
217
+ return self.status()
218
+
219
+ def reload_config(self):
220
+ with self.mutex:
221
+ candidate = load_config(self.path)
222
+ child = self.children.get("mcp")
223
+ if child and child[0].poll() is None and candidate.port != self.config.port:
224
+ raise AppError("CONFIG_CHANGED", "Restart MCP before changing its live port")
225
+ self.config = candidate
226
+ return self.status()
227
+
228
+ def restart(self, name):
229
+ with self.mutex:
230
+ self.stop(name)
231
+ return self.start(name)
232
+
233
+ def stop_all(self):
234
+ errors = []
235
+ for name in ("tunnel", "mcp"):
236
+ try:
237
+ self.stop(name)
238
+ except Exception as error:
239
+ errors.append(str(error))
240
+ if errors:
241
+ raise AppError("STOP_FAILED", "; ".join(errors))
242
+ return self.status()
243
+
244
+ def poll(self):
245
+ with self.mutex:
246
+ for name, desired in self.desired.items():
247
+ child = self.children.get(name)
248
+ if name == "tunnel" and child and child[0].poll() is None and self.permanent[name]:
249
+ child[0].terminate()
250
+ try:
251
+ child[0].wait(timeout=4)
252
+ except subprocess.TimeoutExpired:
253
+ child[1].kill()
254
+ child[0].wait(timeout=5)
255
+ if child and child[0].poll() is None and time.monotonic() - child[2] > 60:
256
+ if name == "mcp":
257
+ try:
258
+ if self._health().get("instance") == hashlib.sha256(self.control.encode()).hexdigest():
259
+ self.retries[name] = 0
260
+ except (AppError, httpx.HTTPError, ValueError):
261
+ pass
262
+ # Tunnel retry count is not reset solely on process liveness.
263
+ if desired and name == "mcp" and child and child[0].poll() is None and time.monotonic() - child[2] > 15:
264
+ try:
265
+ health = self._health()
266
+ healthy = health.get("instance") == hashlib.sha256(self.control.encode()).hexdigest() and self._health_pid_is_owned(health.get("pid"))
267
+ except (AppError, httpx.HTTPError, ValueError):
268
+ healthy = False
269
+ if not healthy:
270
+ self.last_output[name] = "MCP readiness timeout / Превышено время готовности MCP"
271
+ child[1].kill()
272
+ child[0].wait(timeout=5)
273
+ if not desired or (child and child[0].poll() is None):
274
+ continue
275
+ if child:
276
+ child[1].close()
277
+ if name == "mcp":
278
+ # The Windows Job has been closed, but its descendants may
279
+ # release the listening socket slightly later.
280
+ deadline = time.monotonic() + 5
281
+ while port_open(self.config.port) and time.monotonic() < deadline:
282
+ time.sleep(0.1)
283
+ self.errors[name] = ("Service exited unexpectedly (exit " + str(child[0].returncode) + "). "
284
+ + (self.last_output[name] or "Open service logs / Откройте журнал служб"))
285
+ self.error_codes[name] = "PROCESS_EXITED"
286
+ if child[0].returncode == 2:
287
+ self.permanent[name] = True
288
+ now = time.monotonic()
289
+ if not self.retry_at[name]:
290
+ self.retry_at[name] = now + 2 ** (self.retries[name] + 1) + random.uniform(0, 1)
291
+ if self.config.restart_services and not self.permanent[name] and self.retries[name] < 3 and now >= self.retry_at[name]:
292
+ self.retries[name] += 1
293
+ self.retry_at[name] = 0
294
+ self.log(name, "bounded crash recovery " + str(self.retries[name]))
295
+ try:
296
+ self.start(name, retry=True)
297
+ except AppError:
298
+ pass
299
+ return self.status()
300
+
301
+ def status(self):
302
+ with self.mutex:
303
+ result = {}
304
+ for name in self.desired:
305
+ child = self.children.get(name)
306
+ running = bool(child and child[0].poll() is None)
307
+ result[name] = {"state": "Running" if running else "Failed" if self.errors[name] else "Stopped",
308
+ "process_alive": running, "owned": bool(child),
309
+ "pid": child[0].pid if child and running else None, "error": self.errors[name],
310
+ "error_code": self.error_codes[name],
311
+ "exit_code": child[0].returncode if child and not running else None,
312
+ "retries": self.retries[name]}
313
+ result["mcp"]["port_open"] = port_open(self.config.port)
314
+ result["mcp"]["endpoint"] = f"http://127.0.0.1:{self.config.port}/mcp"
315
+ result["mcp"]["healthy"] = False
316
+ if not result["mcp"]["process_alive"] and result["mcp"]["port_open"]:
317
+ result["mcp"]["state"] = "Failed"
318
+ result["mcp"]["error"] = "Port occupied by an external instance; this controller does not own it"
319
+ result["mcp"]["error_code"] = "PORT_CONFLICT"
320
+ if result["mcp"]["process_alive"]:
321
+ try:
322
+ data = self._health()
323
+ result["mcp"]["healthy"] = (data.get("instance") == hashlib.sha256(self.control.encode()).hexdigest() and
324
+ self._health_pid_is_owned(data.get("pid")))
325
+ except (AppError, httpx.HTTPError, ValueError):
326
+ pass
327
+ if not result["mcp"]["healthy"]:
328
+ result["mcp"]["state"] = "Starting" if time.monotonic() - self.children.get("mcp", (None, None, time.monotonic()))[2] < 15 else "Failed"
329
+ if not result["tunnel"]["process_alive"] and not self.errors["tunnel"] and not self.config.tunnel_client and not bundled_tool("tunnel-client") and not shutil.which("tunnel-client.exe") and not shutil.which("tunnel-client"):
330
+ result["tunnel"]["state"] = "Not configured"
331
+ if result["mcp"]["process_alive"] and not result["mcp"]["healthy"] and result["mcp"]["state"] == "Failed":
332
+ result["mcp"]["error"] = "Owned process is alive but authenticated health verification failed; check service logs"
333
+ result["mcp"]["error_code"] = "HEALTH_FAILED"
334
+ if result["tunnel"]["process_alive"]:
335
+ result["tunnel"]["state"] = "Running, connection unverified"
336
+ evidence = health_observation(self.config, result["tunnel"]["pid"])
337
+ result["tunnel"]["observations"] = evidence
338
+ if evidence.get("degraded"):
339
+ result["tunnel"]["state"] = "Degraded"
340
+ elif evidence.get("mcp") == evidence.get("control-plane") == "Recent successful observation":
341
+ if time.monotonic() - self.children["tunnel"][2] > 60:
342
+ self.retries["tunnel"] = 0
343
+ else:
344
+ external, inaccessible = external_processes(self.config)
345
+ if external:
346
+ result["tunnel"]["state"] = "External process detected, ownership unverified"
347
+ result["tunnel"]["external_pids"] = external
348
+ result["tunnel"]["owned"] = False
349
+ if len(external) == 1:
350
+ result["tunnel"]["observations"] = health_observation(self.config, external[0])
351
+ elif inaccessible:
352
+ result["tunnel"]["inspection"] = "Access denied; external detection incomplete"
353
+ elif self.desired["tunnel"] and self.retry_at["tunnel"] and self.retries["tunnel"] < 3 and not self.permanent["tunnel"] and self.config.restart_services:
354
+ result["tunnel"]["state"] = "Reconnecting"
355
+ result["tunnel"]["remote_availability"] = "Unverified"
356
+ result["tunnel"]["profile"] = self.config.tunnel_profile
357
+ result["tunnel"]["connection"] = "Unverified" if result["tunnel"]["process_alive"] else "Disconnected"
358
+ return result
@@ -0,0 +1,242 @@
1
+ """Profile preflight and lossless, backed-up edits. Vendor doctor owns exact schema."""
2
+ import io
3
+ import os
4
+ import re
5
+ import secrets
6
+ import shlex
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ from pathlib import Path
12
+ from ruamel.yaml import YAML
13
+ from github_ai_mcp.desktop.processes import background_options
14
+ from github_ai_mcp.desktop.runtime import service_command, bundled_tool
15
+ from github_ai_mcp.exceptions import AppError
16
+ from github_ai_mcp.security.auth_github import get_secret
17
+
18
+ SECRET = "tunnel-control-plane"
19
+
20
+
21
+ def profile_path(config):
22
+ if config.tunnel_profile_file:
23
+ return Path(config.tunnel_profile_file).expanduser().resolve()
24
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+", config.tunnel_profile) or config.tunnel_profile in {".", ".."}:
25
+ raise AppError("PROFILE_INVALID", "Invalid profile name / Неверное имя профиля")
26
+ directories = [os.environ.get("TUNNEL_CLIENT_PROFILE_DIR"),
27
+ str(Path(os.environ["APPDATA"]) / "tunnel-client") if os.environ.get("APPDATA") else None,
28
+ str(Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home()/".config"))) / "tunnel-client")]
29
+ for directory in filter(None, directories):
30
+ candidate = Path(directory) / (config.tunnel_profile + ".yaml")
31
+ if candidate.is_file():
32
+ return candidate.resolve()
33
+ raise AppError("PROFILE_MISSING", "Select existing tunnel YAML in Setup / Выберите существующий YAML профиля")
34
+
35
+
36
+ def read_profile(path):
37
+ try:
38
+ data = YAML(typ="rt").load(path.read_text(encoding="utf-8"))
39
+ if not isinstance(data, dict) or not isinstance(data.get("control_plane"), dict):
40
+ raise ValueError()
41
+ if data["control_plane"].get("api_key") != "env:CONTROL_PLANE_API_KEY":
42
+ raise AppError("PROFILE_SECRET", "Use api_key: env:CONTROL_PLANE_API_KEY; no plaintext key migration / Используйте ссылку env:CONTROL_PLANE_API_KEY")
43
+ check_references(data)
44
+ return data
45
+ except AppError:
46
+ raise
47
+ except Exception:
48
+ # Parser exceptions can contain YAML source, including credentials.
49
+ raise AppError("PROFILE_INVALID", "Invalid YAML structure; repair profile in editor / Неверная структура YAML: исправьте профиль в редакторе") from None
50
+
51
+
52
+ def command_text(config_path):
53
+ args = service_command(config_path, "stdio")
54
+ if sys.platform == "win32":
55
+ # Forward slashes survive vendor shell-word parsing as well as Windows argv.
56
+ args = [argument.replace("\\", "/") for argument in args]
57
+ return subprocess.list2cmdline(args)
58
+ return shlex.join(args)
59
+
60
+
61
+ def expected_command(config, config_path):
62
+ command = config.tunnel_stdio_command.strip() or command_text(config_path)
63
+ if not command or any(ord(c) < 32 for c in command):
64
+ raise AppError("MCP_COMMAND", "Use a single-line stdio command / Укажите однострочную команду stdio")
65
+ from github_ai_mcp.security.secret_scan import scan
66
+ scan(command.encode())
67
+ return command
68
+
69
+
70
+ def local_profile(config, config_path, path=None):
71
+ """Validate local structure/command without credentials, vendor or network."""
72
+ data = read_profile(path or profile_path(config))
73
+ main = main_command(data)
74
+ if main["command"].strip() != expected_command(config, config_path):
75
+ raise AppError("MCP_COMMAND", "Repair the MCP command in Setup (stale path or arguments) / Исправьте команду MCP в настройке запуска")
76
+ if not Path(config_path).is_file():
77
+ raise AppError("CONFIG_MISSING", "Application configuration missing / Конфигурация приложения отсутствует")
78
+ return data
79
+
80
+
81
+ def main_command(data):
82
+ mcp = data.get("mcp")
83
+ commands = mcp.get("commands") if isinstance(mcp, dict) else None
84
+ if not isinstance(commands, list):
85
+ raise AppError("MCP_COMMAND", "mcp.commands must be a list / mcp.commands должен быть списком")
86
+ main = [item for item in commands if isinstance(item, dict) and item.get("channel", "main") == "main"]
87
+ if len(main) != 1 or not isinstance(main[0].get("command"), str):
88
+ raise AppError("MCP_COMMAND", "This integration requires one main stdio command / Требуется одна команда stdio канала main")
89
+ return main[0]
90
+
91
+
92
+ def child_environment(runtime_key=None):
93
+ env = os.environ.copy()
94
+ # Credential selected explicitly; never persist/import a shell key automatically.
95
+ for name in ("TUNNEL_CLIENT_CONFIG", "TUNNEL_CLIENT_PROFILE", "TUNNEL_CLIENT_PROFILE_FILE", "MCP_COMMAND", "MCP_SERVER_URL", "CONTROL_PLANE_BASE_URL", "CONTROL_PLANE_TUNNEL_ID", "CONTROL_PLANE_API_KEY"):
96
+ env.pop(name, None)
97
+ try:
98
+ env["CONTROL_PLANE_API_KEY"] = runtime_key or get_secret(SECRET)
99
+ except AppError:
100
+ raise AppError("TUNNEL_KEY_MISSING", "Save the tunnel runtime key in Setup / Сохраните ключ туннеля в настройке запуска") from None
101
+ return env
102
+
103
+
104
+ def preflight(config, config_path, doctor=True, path=None, runtime_key=None):
105
+ client = config.tunnel_client or bundled_tool("tunnel-client") or shutil.which("tunnel-client.exe") or shutil.which("tunnel-client")
106
+ if not client or not Path(client).is_file():
107
+ raise AppError("TUNNEL_MISSING", "Select official tunnel executable / Выберите официальный клиент туннеля")
108
+ path = path or profile_path(config)
109
+ data = local_profile(config, config_path, path)
110
+ env = child_environment(runtime_key)
111
+ if doctor:
112
+ try:
113
+ result = subprocess.run([str(Path(client).resolve()), "doctor", "--profile-file", str(path)],
114
+ env=env, capture_output=True, timeout=25, **background_options())
115
+ except subprocess.TimeoutExpired:
116
+ raise AppError("DOCTOR_TIMEOUT", "Client doctor timed out; check network/profile / Проверка клиента превысила время: проверьте сеть и профиль") from None
117
+ except OSError:
118
+ raise AppError("TUNNEL_EXECUTABLE", "Cannot execute tunnel client / Не удалось запустить файл клиента туннеля") from None
119
+ if result.returncode:
120
+ # Vendor output can contain arbitrary secrets: do not export it.
121
+ raise AppError("DOCTOR_FAILED", "Client doctor rejected the profile or credentials; open official client diagnostics / Клиент отклонил профиль или ключ: откройте его диагностику")
122
+ return [str(Path(client).resolve()), "run", "--profile-file", str(path)], env, data
123
+
124
+
125
+ def repair_profile(config, config_path):
126
+ path = profile_path(config)
127
+ before = path.read_bytes()
128
+ data = read_profile(path)
129
+ main = main_command(data)
130
+ main["command"] = expected_command(config, config_path)
131
+ output = io.StringIO()
132
+ YAML(typ="rt").dump(data, output)
133
+ fd, name = tempfile.mkstemp(prefix=".github-ai-", suffix=".yaml", dir=path.parent)
134
+ temp = Path(name)
135
+ try:
136
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
137
+ stream.write(output.getvalue())
138
+ stream.flush()
139
+ os.fsync(stream.fileno())
140
+ local_profile(config, config_path, path=temp)
141
+ if path.read_bytes() != before:
142
+ raise AppError("PROFILE_CHANGED", "Profile changed during validation; retry / Профиль изменился: повторите")
143
+ backup = path.with_name(path.name + ".github-ai-backup-" + secrets.token_hex(6))
144
+ backup.write_bytes(before)
145
+ os.chmod(backup, 0o600)
146
+ temp.replace(path)
147
+ finally:
148
+ temp.unlink(missing_ok=True)
149
+ return str(backup)
150
+
151
+
152
+ def external_processes(config):
153
+ import psutil
154
+ matches: list[int] = []
155
+ inaccessible = False
156
+ target = config.tunnel_client or bundled_tool("tunnel-client") or shutil.which("tunnel-client.exe") or shutil.which("tunnel-client")
157
+ if not target:
158
+ return matches, inaccessible
159
+ for process in psutil.process_iter(["pid", "name", "exe", "cmdline"]):
160
+ try:
161
+ info = process.info
162
+ if not info["exe"] and info.get("name", "").lower() == Path(target).name.lower():
163
+ inaccessible = True
164
+ if not info["exe"] or Path(info["exe"]).resolve() != Path(target).resolve():
165
+ continue
166
+ # Exact executable match only; no inference from an occupied port.
167
+ matches.append(info["pid"])
168
+ except psutil.AccessDenied:
169
+ inaccessible = True
170
+ except (psutil.NoSuchProcess, OSError):
171
+ pass
172
+ return matches, inaccessible
173
+
174
+
175
+ def health_observation(config, pid):
176
+ """Only read a loopback listener belonging to the selected process; no adoption."""
177
+ import psutil
178
+ import httpx
179
+ from datetime import datetime, timezone
180
+ try:
181
+ data = read_profile(profile_path(config))
182
+ address = data.get("health", {}).get("listen_addr", "127.0.0.1:8080")
183
+ host, port = address.rsplit(":", 1)
184
+ if host not in {"127.0.0.1", "localhost"} or not 0 < int(port) < 65536:
185
+ return {"health": "Unverified"}
186
+ connections = psutil.Process(pid).net_connections(kind="tcp")
187
+ if not any(c.status == psutil.CONN_LISTEN and c.laddr.port == int(port) for c in connections):
188
+ return {"health": "Unverified"}
189
+ with httpx.Client(timeout=0.5, trust_env=False) as client:
190
+ response = client.get(f"http://127.0.0.1:{int(port)}/health?details=true")
191
+ response.raise_for_status()
192
+ if len(response.content) > 65536:
193
+ return {"health": "Unverified"}
194
+ snapshot = response.json()
195
+ if snapshot.get("schema_version") != 1:
196
+ return {"health": "Unverified"}
197
+ observations = {"health": "Observed", "ready": snapshot.get("ready") is True}
198
+ for name in ("mcp", "control-plane"):
199
+ item = snapshot.get("components", {}).get(name, {})
200
+ observed = item.get("observed_at")
201
+ fresh = False
202
+ if isinstance(observed, str):
203
+ age = (datetime.now(timezone.utc) - datetime.fromisoformat(observed.replace("Z", "+00:00"))).total_seconds()
204
+ fresh = 0 <= age <= 60
205
+ observations[name] = "Recent successful observation" if item.get("status") == "ok" and fresh else "Unverified"
206
+ observations["degraded"] = any(snapshot.get("components", {}).get(name, {}).get("status") == "degraded" for name in ("mcp", "control-plane"))
207
+ return observations
208
+ except (AppError, OSError, ValueError, KeyError, TypeError, AttributeError, psutil.Error, httpx.HTTPError):
209
+ return {"health": "Unverified"}
210
+
211
+
212
+ def check_references(data):
213
+ if isinstance(data, dict):
214
+ for key, value in data.items():
215
+ if re.search(r"(?i)(api[_-]?key|password|secret|token|authorization|cookie)", str(key)) and isinstance(value, str):
216
+ if not value.startswith(("env:", "file:")):
217
+ raise AppError("PROFILE_SECRET", "Literal secret field blocked; use env:/file: references / Замените секрет на ссылку env:/file:")
218
+ check_references(value)
219
+ elif isinstance(data, list):
220
+ for value in data:
221
+ check_references(value)
222
+
223
+
224
+ def safe_editor_text(text):
225
+ from github_ai_mcp.security.secret_scan import redact
226
+ references: dict[str, str] = {}
227
+ lines = []
228
+ for line in text.splitlines(keepends=True):
229
+ match = re.match(r"(\s*(?:api[_-]?key|password|secret|token|authorization|cookie)\s*:\s*)(.*)", line, re.I)
230
+ if match and not match[2].strip().strip("\"'").startswith(("env:", "file:")):
231
+ line = match[1] + "env:REPLACE_WITH_SECRET_REFERENCE\n"
232
+ lines.append(line)
233
+ text = "".join(lines)
234
+ def hold(match):
235
+ placeholder = "REF" + str(len(references))
236
+ references[placeholder] = match.group(0)
237
+ return placeholder
238
+ text = re.sub(r"(?:env:|file:)[^\s\"']+", hold, text)
239
+ text = redact(text)
240
+ for placeholder, reference in references.items():
241
+ text = text.replace(placeholder, reference)
242
+ return text
@@ -0,0 +1,6 @@
1
+ class AppError(Exception):
2
+ """Safe, public failure with a stable machine code."""
3
+
4
+ def __init__(self, code: str, message: str):
5
+ self.code = code
6
+ super().__init__(message)
@@ -0,0 +1 @@
1
+ """Application layer."""