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,41 @@
1
+ """Kernel-owned interprocess locks: automatic release after crash, no stale PID trust."""
2
+ import hashlib
3
+ import importlib
4
+ import os
5
+ from contextlib import contextmanager
6
+ from pathlib import Path
7
+ from typing import Any, cast
8
+
9
+ from github_ai_mcp.exceptions import AppError
10
+
11
+
12
+ @contextmanager
13
+ def lock(root: Path, key: str):
14
+ root.mkdir(parents=True, exist_ok=True)
15
+ path = root / (hashlib.sha256(key.encode()).hexdigest() + ".lock")
16
+ with path.open("a+b") as f:
17
+ f.seek(0, os.SEEK_END)
18
+ if f.tell() == 0:
19
+ f.write(b"0")
20
+ f.flush()
21
+ f.seek(0)
22
+ try:
23
+ if os.name == "nt":
24
+ import msvcrt
25
+ msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
26
+ else:
27
+ # Load the POSIX-only module dynamically for Windows mypy compatibility.
28
+ fcntl = cast(Any, importlib.import_module("fcntl"))
29
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
30
+ except OSError:
31
+ raise AppError("BUSY", "An active operation owns this application lock. Wait for it to finish; a crashed owner releases the kernel lock automatically. Do not delete lock files.") from None
32
+ try:
33
+ yield
34
+ finally:
35
+ if os.name == "nt":
36
+ import msvcrt
37
+ f.seek(0)
38
+ msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
39
+ else:
40
+ fcntl = cast(Any, importlib.import_module("fcntl"))
41
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
@@ -0,0 +1 @@
1
+ """Local desktop lifecycle (never exposed as MCP tools)."""
@@ -0,0 +1,26 @@
1
+ """Local lifecycle routes protected by bearer auth and a private per-instance nonce."""
2
+ import hmac
3
+ import hashlib
4
+ import os
5
+
6
+ from starlette.responses import JSONResponse
7
+
8
+
9
+ class ControlRoutes:
10
+ def __init__(self, app, instance, runner):
11
+ self.app, self.instance, self.runner = app, instance, runner
12
+
13
+ async def __call__(self, scope, receive, send):
14
+ if scope["type"] == "http" and scope["path"] == "/_local/health":
15
+ return await JSONResponse({"application": "GitHub-AI-MCP", "pid": os.getpid(),
16
+ "instance": hashlib.sha256(self.instance.encode()).hexdigest()})(scope, receive, send)
17
+ if scope["type"] == "http" and scope["path"] == "/_local/shutdown":
18
+ headers = dict(scope.get("headers", []))
19
+ valid = self.instance and hmac.compare_digest(
20
+ headers.get(b"x-local-control", b"").decode(), self.instance)
21
+ if scope["method"] != "POST" or not valid:
22
+ return await JSONResponse({"error": "FORBIDDEN"}, 403)(scope, receive, send)
23
+ await JSONResponse({"stopping": True})(scope, receive, send)
24
+ self.runner.should_exit = True
25
+ return
26
+ return await self.app(scope, receive, send)
@@ -0,0 +1,77 @@
1
+ """Frozen windowed entrypoint: GUI only; pipe-capable server has its own entrypoint."""
2
+ import sys
3
+ from pathlib import Path
4
+
5
+
6
+ def main():
7
+ from multiprocessing import freeze_support
8
+ freeze_support()
9
+ from github_ai_mcp.desktop.runtime import initialize_runtime
10
+ initialize_runtime()
11
+ from github_ai_mcp.desktop.streams import prepare_streams
12
+ internal = "--internal-server" in sys.argv[1:]
13
+ cli = "--cli" in sys.argv[1:]
14
+ # Dispatch before Qt import; HTTP and stdio workers never create a GUI.
15
+ service = internal or "serve" in sys.argv[1:]
16
+ prepare_streams(require_input=service and "streamable-http" not in sys.argv)
17
+ if service or cli:
18
+ if internal:
19
+ sys.argv.remove("--internal-server")
20
+ if cli:
21
+ sys.argv.remove("--cli")
22
+ from github_ai_mcp.cli.app import main as cli_main
23
+ cli_main()
24
+ return
25
+ from PySide6.QtWidgets import QApplication, QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout
26
+ from github_ai_mcp.config import Config, load_config, resolve_config, save_config
27
+ from github_ai_mcp.core.job_engine import Service
28
+ from github_ai_mcp.gui.app import run
29
+ app = QApplication.instance() or QApplication(sys.argv)
30
+ app.setApplicationName("GitHub-AI-MCP")
31
+ import argparse
32
+ parser = argparse.ArgumentParser(add_help=False)
33
+ parser.add_argument("--config", type=Path)
34
+ args, _ = parser.parse_known_args()
35
+ path = resolve_config(args.config)
36
+ if not path.exists():
37
+ try:
38
+ save_config(path, Config())
39
+ except OSError:
40
+ from PySide6.QtWidgets import QMessageBox
41
+ QMessageBox.warning(None, "GitHub-AI-MCP", "Configuration is not writable / Конфигурация недоступна для записи")
42
+ return
43
+ while True:
44
+ try:
45
+ config = load_config(path)
46
+ break
47
+ except (ValueError, OSError):
48
+ dialog = QDialog()
49
+ dialog.setWindowTitle("GitHub-AI-MCP — Configuration / Конфигурация")
50
+ dialog.resize(720, 550)
51
+ layout = QVBoxLayout(dialog)
52
+ info = QLabel("Invalid configuration. Edit and save, or cancel.\nНеверная конфигурация. Исправьте и сохраните либо отмените.")
53
+ layout.addWidget(info)
54
+ editor = QPlainTextEdit()
55
+ try:
56
+ editor.setPlainText(path.read_text(encoding="utf-8"))
57
+ except OSError:
58
+ pass
59
+ layout.addWidget(editor)
60
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel)
61
+ def save():
62
+ try:
63
+ config = Config.model_validate_json(editor.toPlainText())
64
+ save_config(path, config)
65
+ dialog.accept()
66
+ except (ValueError, OSError):
67
+ info.setText("Invalid schema or file not writable / Неверная схема или файл недоступен")
68
+ buttons.accepted.connect(save)
69
+ buttons.rejected.connect(dialog.reject)
70
+ layout.addWidget(buttons)
71
+ if dialog.exec() != QDialog.DialogCode.Accepted:
72
+ return
73
+ run(Service(config), path)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
@@ -0,0 +1,9 @@
1
+ """Offline discovery of installed legal files. Nothing opens user-selected URLs."""
2
+ from github_ai_mcp.desktop.runtime import program_root
3
+
4
+
5
+ def legal_files():
6
+ root = program_root()
7
+ paths = [root/"LICENSE", root/"docs/THIRD_PARTY.md", root/"docs/LICENSE_COMPLIANCE.md"]
8
+ paths += sorted(p for p in (root/"legal").rglob("*") if p.is_file()) if (root/"legal").exists() else []
9
+ return [p for p in paths if p.is_file()]
@@ -0,0 +1,31 @@
1
+ """Read-only dependency diagnostics; no installs, network access or vendor commands."""
2
+ import shutil
3
+ import subprocess
4
+
5
+ from github_ai_mcp.desktop.processes import run_background
6
+ from github_ai_mcp.exceptions import AppError
7
+ from github_ai_mcp.security.auth_github import vault
8
+
9
+ LINKS = {"git": "https://git-scm.com/download/win", "gh": "https://cli.github.com/",
10
+ "vault": "https://support.microsoft.com/windows"}
11
+
12
+
13
+ def check_prerequisites() -> dict:
14
+ result = {}
15
+ for tool in ("git", "gh"):
16
+ path = shutil.which(tool)
17
+ status = "Missing"
18
+ if path:
19
+ try:
20
+ probe = run_background([path, "--version"], capture_output=True, timeout=5)
21
+ status = "Installed" if probe.returncode == 0 else "Unusable"
22
+ except (OSError, subprocess.TimeoutExpired):
23
+ status = "Unusable"
24
+ result[tool] = {"status": status, "path": path, "url": LINKS[tool]}
25
+ try:
26
+ vault()
27
+ status = "Available"
28
+ except AppError:
29
+ status = "Unavailable"
30
+ result["vault"] = {"status": status, "url": LINKS["vault"]}
31
+ return result
@@ -0,0 +1,116 @@
1
+ """No-console subprocesses and Windows kernel-owned process trees."""
2
+ import ctypes
3
+ import os
4
+ import subprocess
5
+ from typing import Any, cast
6
+ from ctypes import wintypes
7
+
8
+
9
+ def background_options(suspended=False) -> dict:
10
+ return {"creationflags": 0x08000000 | (4 if suspended else 0)} if os.name == "nt" else {"start_new_session": True}
11
+
12
+
13
+ class ProcessTree:
14
+ """KILL_ON_JOB_CLOSE prevents orphaned descendants when the controller crashes."""
15
+ def __init__(self, process, suspended=False):
16
+ self.process = process
17
+ self.handle = None
18
+ if os.name != "nt":
19
+ return
20
+ kernel = cast(Any, ctypes).WinDLL("kernel32", use_last_error=True)
21
+ kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
22
+ kernel.CreateJobObjectW.restype = wintypes.HANDLE
23
+ kernel.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
24
+ kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
25
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
26
+ class Basic(ctypes.Structure):
27
+ _fields_ = [("process_time", ctypes.c_int64), ("job_time", ctypes.c_int64),
28
+ ("flags", wintypes.DWORD), ("min_ws", ctypes.c_size_t),
29
+ ("max_ws", ctypes.c_size_t), ("active", wintypes.DWORD),
30
+ ("affinity", ctypes.c_size_t), ("priority", wintypes.DWORD),
31
+ ("scheduling", wintypes.DWORD)]
32
+ class IO(ctypes.Structure):
33
+ _fields_ = [(name, ctypes.c_uint64) for name in
34
+ ["read_ops", "write_ops", "other_ops", "read_bytes", "write_bytes", "other_bytes"]]
35
+ class Extended(ctypes.Structure):
36
+ _fields_ = [("basic", Basic), ("io", IO), ("process_memory", ctypes.c_size_t),
37
+ ("job_memory", ctypes.c_size_t), ("peak_process", ctypes.c_size_t),
38
+ ("peak_job", ctypes.c_size_t)]
39
+ info = Extended()
40
+ info.basic.flags = 0x2000
41
+ handle = kernel.CreateJobObjectW(None, None)
42
+ if not handle:
43
+ raise OSError("Cannot create Windows process job")
44
+ if not kernel.SetInformationJobObject(handle, 9, ctypes.byref(info), ctypes.sizeof(info)) or not kernel.AssignProcessToJobObject(handle, wintypes.HANDLE(int(process._handle))):
45
+ kernel.CloseHandle(handle)
46
+ process.kill()
47
+ process.wait(timeout=5)
48
+ raise OSError("Cannot contain Windows service process")
49
+ self.handle, self.kernel = handle, kernel
50
+ if suspended:
51
+ try:
52
+ self._resume()
53
+ except Exception:
54
+ self.kill()
55
+ process.wait(timeout=5)
56
+ raise
57
+
58
+ def _resume(self):
59
+ # Popen closes the primary-thread handle. Enumerate only this suspended
60
+ # process's thread, after it is contained, and resume it via official APIs.
61
+ class ThreadEntry(ctypes.Structure):
62
+ _fields_ = [("size", wintypes.DWORD), ("usage", wintypes.DWORD),
63
+ ("id", wintypes.DWORD), ("owner", wintypes.DWORD),
64
+ ("base_priority", wintypes.LONG), ("delta", wintypes.LONG),
65
+ ("flags", wintypes.DWORD)]
66
+ kernel = self.kernel
67
+ kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
68
+ kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
69
+ kernel.Thread32First.argtypes = [wintypes.HANDLE, ctypes.POINTER(ThreadEntry)]
70
+ kernel.Thread32Next.argtypes = [wintypes.HANDLE, ctypes.POINTER(ThreadEntry)]
71
+ kernel.OpenThread.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
72
+ kernel.OpenThread.restype = wintypes.HANDLE
73
+ kernel.ResumeThread.argtypes = [wintypes.HANDLE]
74
+ kernel.ResumeThread.restype = wintypes.DWORD
75
+ snapshot = kernel.CreateToolhelp32Snapshot(4, 0)
76
+ if snapshot == ctypes.c_void_p(-1).value:
77
+ raise OSError("Cannot inspect suspended service thread")
78
+ entry = ThreadEntry()
79
+ entry.size = ctypes.sizeof(entry)
80
+ try:
81
+ found = kernel.Thread32First(snapshot, ctypes.byref(entry))
82
+ while found:
83
+ if entry.owner == self.process.pid:
84
+ thread = kernel.OpenThread(2, False, entry.id)
85
+ if not thread:
86
+ raise OSError("Cannot open owned service thread")
87
+ try:
88
+ if kernel.ResumeThread(thread) == 0xFFFFFFFF:
89
+ raise OSError("Cannot resume owned service thread")
90
+ finally:
91
+ kernel.CloseHandle(thread)
92
+ return
93
+ found = kernel.Thread32Next(snapshot, ctypes.byref(entry))
94
+ raise OSError("Owned service thread not found")
95
+ finally:
96
+ kernel.CloseHandle(snapshot)
97
+
98
+ def kill(self):
99
+ if self.handle:
100
+ self.kernel.CloseHandle(self.handle)
101
+ self.handle = None
102
+ elif os.name != "nt":
103
+ import signal
104
+ try:
105
+ cast(Any, os).killpg(self.process.pid, cast(Any, signal).SIGKILL)
106
+ except ProcessLookupError:
107
+ pass
108
+ elif self.process.poll() is None:
109
+ self.process.kill()
110
+
111
+ def close(self):
112
+ self.kill()
113
+
114
+
115
+ def run_background(*args, **kwargs):
116
+ return cast(Any, subprocess.run)(*args, **background_options(), **kwargs)
@@ -0,0 +1,34 @@
1
+ """Read-only bundle resources and same-executable worker commands."""
2
+ import os
3
+ import sys
4
+ from pathlib import Path
5
+
6
+
7
+
8
+ def program_root() -> Path:
9
+ return Path(getattr(sys, "_MEIPASS", Path(sys.executable).resolve().parent)) if getattr(sys, "frozen", False) else Path(__file__).resolve().parents[3]
10
+
11
+
12
+ def asset_path(name: str) -> Path:
13
+ return program_root() / "assets" / name
14
+
15
+
16
+ def service_command(config_path: Path, transport="streamable-http") -> list[str]:
17
+ if getattr(sys, "frozen", False):
18
+ command = [str(Path(sys.executable).resolve()), "--internal-server"]
19
+ else:
20
+ command = [sys.executable, "-m", "github_ai_mcp"]
21
+ return [*command, "--config", str(config_path.resolve()), "serve", "--transport", transport]
22
+
23
+
24
+ def bundled_tool(name: str) -> str | None:
25
+ relative = {"git": "git/cmd/git.exe", "gh": "gh.exe", "tunnel-client": "tunnel-client.exe"}
26
+ path = program_root() / "vendor" / relative[name]
27
+ return str(path) if path.is_file() else None
28
+
29
+
30
+ def initialize_runtime():
31
+ """Make bundled Git and its credential helper available to existing tool calls."""
32
+ if getattr(sys, "frozen", False):
33
+ directories = [str(program_root() / "vendor/git/cmd"), str(program_root() / "vendor")]
34
+ os.environ["PATH"] = os.pathsep.join([*directories, os.environ.get("PATH", "")])