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 @@
1
+ """GitHub-AI-MCP: local administration, policy-enforced AI tools."""
@@ -0,0 +1,3 @@
1
+ from github_ai_mcp.cli.app import main
2
+
3
+ main()
@@ -0,0 +1 @@
1
+ """Application layer."""
@@ -0,0 +1,128 @@
1
+ """Trusted local CLI. Never run local approval commands on behalf of an AI tool."""
2
+ import argparse
3
+ import getpass
4
+ import json
5
+ import secrets
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from github_ai_mcp.config import Config, load_config, resolve_config, save_config
11
+ from github_ai_mcp.core.job_engine import Service
12
+ from github_ai_mcp.exceptions import AppError
13
+
14
+
15
+ def parser():
16
+ p = argparse.ArgumentParser(prog="github-ai-mcp")
17
+ p.add_argument("--config", type=Path, default=None)
18
+ sub = p.add_subparsers(dest="command", required=True)
19
+ sub.add_parser("init")
20
+ sub.add_parser("doctor")
21
+ sub.add_parser("prune-audit")
22
+ sub.add_parser("gui")
23
+ sub.add_parser("login")
24
+ sub.add_parser("logout")
25
+ sub.add_parser("auth-mcp")
26
+ srv = sub.add_parser("serve")
27
+ srv.add_argument("--transport", choices=["stdio", "streamable-http"], default="stdio")
28
+ repo = sub.add_parser("repo")
29
+ repo.add_argument("action", choices=["list", "info"])
30
+ repo.add_argument("repository", nargs="?")
31
+ job = sub.add_parser("job")
32
+ job.add_argument("action", choices=["list", "status", "preview", "resume", "cancel", "commit", "publish", "report", "approve"])
33
+ job.add_argument("job_id", nargs="?")
34
+ job.add_argument("--fingerprint")
35
+ job.add_argument("--actions", nargs="+", choices=["commit", "push", "pr"], default=["commit"])
36
+ job.add_argument("--output", type=Path)
37
+ return p
38
+
39
+
40
+ def main():
41
+ args = parser().parse_args()
42
+ args.config = resolve_config(args.config)
43
+ try:
44
+ result: dict[str, Any] | list[Any]
45
+ if args.command == "init":
46
+ if args.config.exists():
47
+ raise AppError("ALREADY_EXISTS", "Configuration already exists")
48
+ save_config(args.config, Config())
49
+ result = {"config": str(args.config), "mode": "READ_ONLY"}
50
+ elif args.command in {"login", "logout", "auth-mcp"}:
51
+ from github_ai_mcp.security.auth_github import logout, store_token
52
+ if args.command == "login":
53
+ store_token(getpass.getpass("GitHub fine-grained PAT (hidden): "))
54
+ result = {"stored": True, "note": "Install GitHub CLI for private Git clone/push; the vault credential is reused"}
55
+ elif args.command == "logout":
56
+ logout()
57
+ result = {"deleted_from_vault": True, "revoke": "https://github.com/settings/tokens"}
58
+ else:
59
+ from github_ai_mcp.security.auth_github import store_secret
60
+ token = secrets.token_urlsafe(32)
61
+ store_secret("mcp-http", token)
62
+ # Explicit local administrator command is the only place this secret is printed.
63
+ print("MCP HTTP bearer token; save in your client's secure credentials (never Git):")
64
+ print(token)
65
+ return
66
+ else:
67
+ config = load_config(args.config)
68
+ service = Service(config)
69
+ if args.command == "serve":
70
+ from github_ai_mcp.server import serve
71
+ serve(service, args.transport)
72
+ return
73
+ if args.command == "gui":
74
+ from github_ai_mcp.gui.app import run
75
+ run(service, args.config)
76
+ return
77
+ if args.command == "prune-audit":
78
+ result = service.db.prune_audit(config.retention_days)
79
+ elif args.command == "doctor":
80
+ import shutil
81
+ doctor_result = service.health_check()
82
+ doctor_result["executables"] = {n: shutil.which(n) for n in ["python", "git", "gh"]}
83
+ import socket
84
+ with socket.socket() as probe:
85
+ probe.settimeout(1)
86
+ doctor_result["loopback_port_open"] = probe.connect_ex(("127.0.0.1", config.port)) == 0
87
+ try:
88
+ doctor_result["github"] = service.github.request("GET", "/user")["login"]
89
+ except AppError as e:
90
+ doctor_result["github"] = e.code
91
+ result = doctor_result
92
+ elif args.command == "repo":
93
+ result = service.list_repositories() if args.action == "list" else service.get_repository_info(args.repository)
94
+ elif args.command == "job":
95
+ if args.action == "list":
96
+ result = [service._report(j) for j in service.db.list_jobs() if j["repository"] in config.repositories]
97
+ else:
98
+ if not args.job_id:
99
+ raise AppError("INVALID_INPUT", "job_id required")
100
+ if args.action == "approve":
101
+ preview = service.preview_job(args.job_id)
102
+ if args.fingerprint != preview["fingerprint"]:
103
+ raise AppError("STALE_APPROVAL", "Supply --fingerprint from the reviewed preview")
104
+ print(json.dumps(preview, ensure_ascii=False, indent=2))
105
+ if input(f"Approve {args.actions} for this exact diff? Type APPROVE: ") != "APPROVE":
106
+ raise AppError("CANCELLED", "Approval cancelled")
107
+ result = service.approve_local(args.job_id, args.fingerprint, args.actions)
108
+ else:
109
+ method = {"status": "get_job_status", "preview": "preview_job", "resume": "resume_job",
110
+ "cancel": "cancel_job", "commit": "create_file_commits", "publish": "publish_branch",
111
+ "report": "get_job_report"}[args.action]
112
+ result = getattr(service, method)(args.job_id)
113
+ if args.output:
114
+ data = json.dumps(result, ensure_ascii=False, indent=2)
115
+ if args.output.suffix.lower() == ".md":
116
+ data = "# GitHub-AI-MCP Job Report\n\n```json\n" + data + "\n```\n"
117
+ args.output.write_text(data, encoding="utf-8")
118
+ print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
119
+ except AppError as e:
120
+ print(json.dumps({"ok": False, "error_code": e.code, "message": str(e)}), file=sys.stderr)
121
+ raise SystemExit(2)
122
+ except (ValueError, OSError):
123
+ print("Configuration/file error; check the path and validated config schema", file=sys.stderr)
124
+ raise SystemExit(2) from None
125
+
126
+
127
+ if __name__ == "__main__":
128
+ main()
@@ -0,0 +1,112 @@
1
+ """Trusted local JSON configuration. MCP never exposes configuration mutations."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Literal
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
8
+
9
+
10
+ class StrictModel(BaseModel):
11
+ model_config = ConfigDict(extra="forbid")
12
+
13
+
14
+ class Repository(StrictModel):
15
+ source: str
16
+ default_branch: str = "main"
17
+ author_name: str
18
+ author_email: str = ""
19
+ identity_authorized: bool = False
20
+ allow_binary: bool = False
21
+ required_checks: list[str] = Field(default_factory=list)
22
+ # Commands are trusted local administration, never MCP inputs.
23
+ @field_validator("author_name", "author_email")
24
+ @classmethod
25
+ def real_identity_text(cls, value: str, info):
26
+ # Legacy configurations may omit email. Preserve read-only access, but
27
+ # require an explicit identity before any commit/publication.
28
+ if info.field_name == "author_email" and value == "":
29
+ return value
30
+ if not value or len(value) > 200 or any(ord(c) < 32 for c in value) or "<" in value or ">" in value:
31
+ raise ValueError("Identity must be nonempty single-line real author text")
32
+ return value
33
+
34
+ checks: dict[str, list[str]] = Field(default_factory=dict)
35
+ trusted_execution: bool = False
36
+
37
+
38
+ class Grant(StrictModel):
39
+ repository: str
40
+ # Empty string explicitly opts into all safe non-default task branches.
41
+ # Existing ai/* grants are never widened automatically.
42
+ branch_prefix: str = "ai/"
43
+ actions: list[Literal["commit", "push", "pr"]]
44
+ expires_at: float
45
+ max_files: int = Field(default=100, ge=1, le=1000)
46
+ max_bytes: int = Field(default=10_000_000, ge=1)
47
+
48
+
49
+ class Config(StrictModel):
50
+ data_dir: Path = Field(default_factory=lambda: Path(
51
+ os.environ.get("LOCALAPPDATA", str(Path.home() / ".local/share"))) / "GitHub-AI-MCP")
52
+ mode: Literal["READ_ONLY", "LOCAL_REVIEW", "AUTO_APPROVED"] = "READ_ONLY"
53
+ locale: Literal["ru", "en"] = "ru"
54
+ port: int = Field(default=8766, ge=1024, le=65535)
55
+ tunnel_client: str = ""
56
+ tunnel_profile: str = "github-ai-local"
57
+ autostart_services: bool = True
58
+ start_mcp: bool = True
59
+ start_tunnel: bool = True
60
+ minimize_on_startup: bool = False
61
+ restart_services: bool = True
62
+ critical_notifications: bool = True
63
+ tunnel_profile_file: str = ""
64
+ # Explicit local administrator override; empty follows the current executable.
65
+ tunnel_stdio_command: str = ""
66
+ background_on_close: bool = True
67
+ setup_complete: bool = False
68
+ repositories: dict[str, Repository] = Field(default_factory=dict)
69
+ grants: list[Grant] = Field(default_factory=list)
70
+ max_files: int = Field(default=100, ge=1, le=1000)
71
+ max_file_bytes: int = Field(default=1_000_000, ge=1, le=10_000_000)
72
+ max_job_bytes: int = Field(default=10_000_000, ge=1)
73
+ git_timeout: int = Field(default=120, ge=1, le=600)
74
+ retention_days: int = Field(default=14, ge=1)
75
+
76
+ @model_validator(mode="after")
77
+ def validate_sources(self):
78
+ import re
79
+ for name, repo in self.repositories.items():
80
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", name):
81
+ raise ValueError("Repository identifier must be owner/repo")
82
+ if not repo.source.startswith("https://github.com/"):
83
+ if not Path(repo.source).is_absolute():
84
+ raise ValueError("Source must be absolute local path or canonical GitHub HTTPS URL")
85
+ elif repo.source != f"https://github.com/{name}.git":
86
+ raise ValueError("GitHub source must match the allowlisted owner/repo")
87
+ return self
88
+
89
+
90
+ def load_config(path: Path) -> Config:
91
+ config = Config.model_validate_json(path.read_text(encoding="utf-8"))
92
+ if not config.data_dir.is_absolute():
93
+ config.data_dir = (path.resolve().parent / config.data_dir).resolve()
94
+ return config
95
+
96
+
97
+ def save_config(path: Path, config: Config) -> None:
98
+ path.parent.mkdir(parents=True, exist_ok=True)
99
+ temp = path.with_suffix(".tmp")
100
+ temp.write_text(json.dumps(config.model_dump(mode="json"), ensure_ascii=False, indent=2),
101
+ encoding="utf-8")
102
+ os.chmod(temp, 0o600)
103
+ temp.replace(path)
104
+
105
+
106
+ def resolve_config(path: Path | None = None) -> Path:
107
+ """Explicit paths, environment, then per-user state; never write beside the EXE."""
108
+ if path is not None:
109
+ return path.expanduser().resolve()
110
+ if os.environ.get("GITHUB_AI_CONFIG"):
111
+ return Path(os.environ["GITHUB_AI_CONFIG"]).expanduser().resolve()
112
+ return Config().data_dir / "config.json"
@@ -0,0 +1 @@
1
+ """Application layer."""
@@ -0,0 +1,76 @@
1
+ """Argument-array Git operations; isolated indexes and hardened configuration."""
2
+ import os
3
+ import subprocess
4
+
5
+ from github_ai_mcp.desktop.processes import run_background
6
+ from pathlib import Path
7
+
8
+ from github_ai_mcp.exceptions import AppError
9
+ from github_ai_mcp.security.auth_github import get_token
10
+
11
+
12
+ class Git:
13
+ def __init__(self, timeout: int = 120):
14
+ self.timeout = timeout
15
+
16
+ def run(self, cwd: Path, *args: str, input: bytes | None = None) -> bytes:
17
+ env = {k: v for k, v in os.environ.items() if not k.startswith(("GIT_", "GH_", "GITHUB_"))}
18
+ env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,
19
+ GIT_TERMINAL_PROMPT="0", GIT_LITERAL_PATHSPECS="1")
20
+ # GitHub CLI reads a transient token from the OS vault for network commands.
21
+ # Nothing is written to gh's configuration, command line, or Git remotes.
22
+ if args and args[0] in {"clone", "fetch", "ls-remote", "push"}:
23
+ github_source = any(a.startswith("https://github.com/") for a in args)
24
+ if not github_source and (cwd / ".git").exists():
25
+ probe = run_background(["git", "config", "--local", "--get", "remote.origin.url"],
26
+ cwd=cwd, env=env, capture_output=True, timeout=10)
27
+ github_source = probe.stdout.decode("utf-8", "replace").strip().startswith("https://github.com/")
28
+ if github_source:
29
+ try:
30
+ env["GH_TOKEN"] = get_token()
31
+ except AppError:
32
+ pass # Public cloning may succeed without authentication.
33
+ # Fresh clones have no inherited hooks/filters. Disable template hooks explicitly.
34
+ command = ["git", "-c", "core.hooksPath=" + os.devnull, "-c", "credential.helper=",
35
+ "-c", "credential.https://github.com.helper=!gh auth git-credential",
36
+ "-c", "core.whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol",
37
+ "-c", "core.autocrlf=false", "-c", "core.quotepath=false",
38
+ "-c", "protocol.ext.allow=never", "-c", "protocol.file.allow=always", *args]
39
+ try:
40
+ p = run_background(command, cwd=cwd, env=env, input=input,
41
+ capture_output=True, timeout=self.timeout)
42
+ except (OSError, subprocess.TimeoutExpired):
43
+ raise AppError("GIT_UNAVAILABLE", "Git unavailable or command timed out") from None
44
+ if p.returncode:
45
+ # Git stderr can contain credentials or private code: never forward it.
46
+ raise AppError("GIT_ERROR", f"Git operation failed ({args[0]}, exit {p.returncode})")
47
+ return p.stdout
48
+
49
+ def text(self, cwd: Path, *args: str) -> str:
50
+ return self.run(cwd, *args).decode("utf-8").strip()
51
+
52
+ def paths(self, cwd: Path, *args: str) -> list[str]:
53
+ return [p.decode("utf-8") for p in self.run(cwd, *args).split(b"\0") if p]
54
+
55
+ def clone(self, source: str, dest: Path):
56
+ dest.parent.mkdir(parents=True, exist_ok=True)
57
+ self.run(dest.parent, "clone", "--no-local", "--no-hardlinks", "--template=", "--", source, str(dest))
58
+
59
+ def tree(self, cwd: Path, ref: str = "HEAD") -> dict[str, dict]:
60
+ result = {}
61
+ for record in self.run(cwd, "ls-tree", "-rz", ref).split(b"\0"):
62
+ if record:
63
+ meta, path = record.split(b"\t", 1)
64
+ mode, kind, sha = meta.decode().split()
65
+ result[path.decode()] = {"mode": mode, "kind": kind, "sha": sha}
66
+ return result
67
+
68
+ def blob(self, cwd: Path, sha: str) -> bytes:
69
+ size = int(self.text(cwd, "cat-file", "-s", sha))
70
+ if size > 10_000_000:
71
+ raise AppError("LIMIT_EXCEEDED", "Git blob exceeds read limit")
72
+ return self.run(cwd, "cat-file", "blob", sha)
73
+
74
+ def remote_sha(self, cwd: Path, branch: str) -> str | None:
75
+ out = self.text(cwd, "ls-remote", "--heads", "origin", "refs/heads/" + branch)
76
+ return out.split()[0] if out else None
@@ -0,0 +1,86 @@
1
+ """Canonical GitHub REST endpoint, bounded requests, safe public failures."""
2
+ import time
3
+ from urllib.parse import quote
4
+
5
+ import httpx
6
+
7
+ from github_ai_mcp.exceptions import AppError
8
+ from github_ai_mcp.security.auth_github import get_token
9
+
10
+
11
+ class GitHub:
12
+ def __init__(self, token: str | None = None, transport=None):
13
+ self._token = token
14
+ self.transport = transport
15
+
16
+ def request(self, method: str, path: str, data=None):
17
+ if not path.startswith("/") or ".." in path or "?" in path or ":" in path:
18
+ raise AppError("UNSAFE_URL", "Invalid GitHub API path")
19
+ token = self._token or get_token()
20
+ with httpx.Client(base_url="https://api.github.com", follow_redirects=False,
21
+ transport=self.transport, timeout=20,
22
+ headers={"Authorization": "Bearer " + token,
23
+ "Accept": "application/vnd.github+json",
24
+ "X-GitHub-Api-Version": "2022-11-28"}) as client:
25
+ for attempt in range(3):
26
+ try:
27
+ r = client.request(method, path, json=data)
28
+ except httpx.HTTPError:
29
+ raise AppError("RETRYABLE_ERROR", "GitHub network request failed; inspect remote before retrying writes") from None
30
+ if r.status_code in {429, 502, 503, 504} or (
31
+ r.status_code == 403 and ("retry-after" in r.headers or r.headers.get("x-ratelimit-remaining") == "0")
32
+ ):
33
+ if method != "GET" or attempt == 2:
34
+ raise AppError("RATE_LIMITED", "GitHub rate limit; retry later")
35
+ try:
36
+ delay = min(5.0, max(0.1, float(r.headers.get("retry-after", 1))))
37
+ except ValueError:
38
+ delay = 1.0
39
+ time.sleep(delay)
40
+ continue
41
+ if r.status_code == 401:
42
+ raise AppError("AUTH_REQUIRED", "GitHub credential expired or invalid")
43
+ # GitHub Free does not expose branch rulesets on private repositories.
44
+ # Distinguish ONLY GitHub's exact plan-upgrade denial, so other 403/404
45
+ # responses remain fail-closed and cannot be silently ignored.
46
+ if (r.status_code == 403 and method == "GET"
47
+ and path.startswith("/repos/") and "/rules/branches/" in path):
48
+ try:
49
+ error_message = r.json().get("message", "")
50
+ except (ValueError, AttributeError):
51
+ error_message = ""
52
+ if error_message == (
53
+ "Upgrade to GitHub Pro or make this repository public to enable this feature."
54
+ ):
55
+ raise AppError("RULESETS_UNAVAILABLE", "GitHub plan does not provide branch rulesets")
56
+ if r.status_code in {403, 404}:
57
+ raise AppError("PERMISSION_DENIED", "GitHub resource unavailable or permission denied")
58
+ if r.is_error:
59
+ raise AppError("GITHUB_ERROR", f"GitHub rejected request ({r.status_code})")
60
+ if len(r.content) > 2_000_000:
61
+ raise AppError("LIMIT_EXCEEDED", "GitHub response too large")
62
+ return r.json() if r.content else {}
63
+ raise AppError("RETRYABLE_ERROR", "GitHub retries exhausted")
64
+
65
+ def identity(self, email: str):
66
+ user = self.request("GET", "/user")
67
+ status = "unverified"
68
+ try:
69
+ emails = self.request("GET", "/user/emails")
70
+ status = "verified" if any(e["email"].casefold() == email.casefold() and e["verified"]
71
+ for e in emails) else "unverified"
72
+ except AppError:
73
+ status = "unknown"
74
+ return {"actor": user["login"], "email_association": status}
75
+
76
+ def info(self, repository: str):
77
+ meta = self.request("GET", "/repos/" + repository)
78
+ branch = quote(meta["default_branch"], safe="")
79
+ result = {k: meta.get(k) for k in ["full_name", "default_branch", "fork", "private", "permissions", "html_url"]}
80
+ for key, endpoint in [("rules", f"/repos/{repository}/rules/branches/{branch}"),
81
+ ("protection", f"/repos/{repository}/branches/{branch}/protection")]:
82
+ try:
83
+ result[key] = self.request("GET", endpoint)
84
+ except AppError:
85
+ result[key] = "unknown"
86
+ return result