Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /github_mcp /github_mcp_server.py
| """ | |
| 🌐 GitHub MCP Server - Zentraler AI Hub | |
| Nutzt GitHub als Backend für: | |
| - AI Memory / Log Book (Issues) | |
| - Credentials (GitHub Secrets) | |
| - Aufgaben/Dienstplan (Projects + Issues) | |
| - Cronjobs (GitHub Actions) | |
| - Multi-AI Integration (Anthropic, Codex, etc.) | |
| """ | |
| import base64 | |
| import json | |
| import os | |
| import secrets | |
| from dataclasses import asdict, dataclass | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Any, Dict, List, Optional | |
| import requests | |
| class MCPContext: | |
| """Model Context Protocol Context""" | |
| session_id: str | |
| user_id: str | |
| ai_provider: str # anthropic, codex, openai, etc. | |
| workspace: str | |
| memory_refs: List[str] | |
| created_at: datetime | |
| expires_at: datetime | |
| def to_dict(self) -> Dict[str, Any]: | |
| data = asdict(self) | |
| data["created_at"] = self.created_at.isoformat() | |
| data["expires_at"] = self.expires_at.isoformat() | |
| return data | |
| class Task: | |
| """Aufgabe im Dienstplan""" | |
| id: str | |
| title: str | |
| description: str | |
| assignee: str # AI oder User | |
| priority: str # low, medium, high, critical | |
| status: str # pending, in_progress, completed | |
| due_date: Optional[datetime] | |
| ai_context: Dict[str, Any] | |
| created_at: datetime | |
| def to_issue_body(self) -> str: | |
| """Konvertiere zu GitHub Issue Format""" | |
| return f"""## 🎯 Task: {self.title} | |
| **Assignee:** {self.assignee} | |
| **Priority:** {self.priority} | |
| **Status:** {self.status} | |
| **Due:** {self.due_date.isoformat() if self.due_date else "TBD"} | |
| ### Description | |
| {self.description} | |
| ### AI Context | |
| ```json | |
| {json.dumps(self.ai_context, indent=2)} | |
| ``` | |
| --- | |
| *Created: {self.created_at.isoformat()}* | |
| *Task ID: {self.id}* | |
| """ | |
| class GitHubMCPServer: | |
| """ | |
| GitHub als MCP (Model Context Protocol) Server | |
| Ermöglicht AI-Integration ohne lokalen Server | |
| """ | |
| def __init__( | |
| self, | |
| github_token: str, | |
| repo_owner: str = "SHAdd0WTAka", | |
| repo_name: str = "zen-alpha-mcp", | |
| ai_providers: Optional[Dict[str, str]] = None, | |
| ): | |
| self.github_token = github_token | |
| self.repo_owner = repo_owner | |
| self.repo_name = repo_name | |
| self.base_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}" | |
| # AI Provider API Keys (via GitHub Secrets) | |
| self.ai_providers = ai_providers or {} | |
| # Headers für GitHub API | |
| self.headers = { | |
| "Authorization": f"token {github_token}", | |
| "Accept": "application/vnd.github.v3+json", | |
| } | |
| # Aktive Sessions | |
| self._sessions: Dict[str, MCPContext] = {} | |
| # ========================================================================= | |
| # GitHub API Helper | |
| # ========================================================================= | |
| def _github_request(self, method: str, endpoint: str, **kwargs) -> Dict: | |
| """Generische GitHub API Anfrage""" | |
| url = f"{self.base_url}/{endpoint}" | |
| response = requests.request(method, url, headers=self.headers, **kwargs, timeout=30) | |
| if response.status_code >= 400: | |
| raise Exception(f"GitHub API Error {response.status_code}: {response.text}") | |
| return response.json() if response.text else {} | |
| # ========================================================================= | |
| # AI Memory / Log Book | |
| # ========================================================================= | |
| def save_memory(self, session_id: str, content: str, tags: List[str] = None) -> Dict: | |
| """ | |
| Speichere AI Memory als GitHub Issue | |
| """ | |
| title = f"🧠 Memory: {content[:50]}..." | |
| body = f"""## AI Memory | |
| **Session:** {session_id} | |
| **Timestamp:** {datetime.now(timezone.utc).isoformat()} | |
| ### Content | |
| {content} | |
| ### Tags | |
| {", ".join(tags or ["memory"])} | |
| --- | |
| *Auto-generated by ZEN-ALPHA MCP Server* | |
| """ | |
| # Issue erstellen | |
| issue = self._github_request( | |
| "POST", | |
| "issues", | |
| json={ | |
| "title": title, | |
| "body": body, | |
| "labels": tags or ["memory", "ai-context"], | |
| }, | |
| ) | |
| return { | |
| "issue_number": issue["number"], | |
| "url": issue["html_url"], | |
| "memory_id": f"mem_{issue['number']}", | |
| "stored": True, | |
| } | |
| def get_memories(self, tags: List[str] = None, limit: int = 10) -> List[Dict]: | |
| """ | |
| Hole AI Memories aus GitHub Issues | |
| """ | |
| params = {"state": "open", "per_page": limit} | |
| if tags: | |
| params["labels"] = ",".join(tags) | |
| issues = self._github_request("GET", "issues", params=params) | |
| return [ | |
| { | |
| "id": f"mem_{i['number']}", | |
| "number": i["number"], | |
| "title": i["title"], | |
| "body": i["body"], | |
| "url": i["html_url"], | |
| "created_at": i["created_at"], | |
| "labels": [line["name"] for line in i["labels"]], | |
| } | |
| for i in issues | |
| ] | |
| def search_memories(self, query: str) -> List[Dict]: | |
| """Suche in Memories via GitHub Search API""" | |
| search_url = "https://api.github.com/search/issues" | |
| q = f"repo:{self.repo_owner}/{self.repo_name} is:issue label:memory {query}" | |
| response = requests.get(search_url, headers=self.headers, params={"q": q}, timeout=30) | |
| if response.status_code == 200: | |
| results = response.json() | |
| return [ | |
| { | |
| "number": item["number"], | |
| "title": item["title"], | |
| "url": item["html_url"], | |
| "score": item["score"], | |
| } | |
| for item in results.get("items", []) | |
| ] | |
| return [] | |
| # ========================================================================= | |
| # Aufgaben / Dienstplan | |
| # ========================================================================= | |
| def create_task(self, task: Task) -> Dict: | |
| """Erstelle Aufgabe als GitHub Issue""" | |
| issue = self._github_request( | |
| "POST", | |
| "issues", | |
| json={ | |
| "title": f"🎯 {task.title}", | |
| "body": task.to_issue_body(), | |
| "labels": ["task", task.priority, f"assignee:{task.assignee}"], | |
| "assignees": ([task.assignee] if task.assignee.startswith("@") else []), | |
| }, | |
| ) | |
| return { | |
| "task_id": task.id, | |
| "issue_number": issue["number"], | |
| "url": issue["html_url"], | |
| "created": True, | |
| } | |
| def get_tasks(self, assignee: str = None, status: str = None) -> List[Dict]: | |
| """Hole Aufgaben aus GitHub Issues""" | |
| params = {"state": "open", "per_page": 100} | |
| issues = self._github_request("GET", "issues", params=params) | |
| tasks = [] | |
| for issue in issues: | |
| labels = [line["name"] for line in issue["labels"]] | |
| if "task" not in labels: | |
| continue | |
| task = { | |
| "id": f"task_{issue['number']}", | |
| "number": issue["number"], | |
| "title": issue["title"], | |
| "body": issue["body"], | |
| "url": issue["html_url"], | |
| "labels": labels, | |
| "state": issue["state"], | |
| } | |
| if assignee and f"assignee:{assignee}" not in labels: | |
| continue | |
| if status and status not in labels: | |
| continue | |
| tasks.append(task) | |
| return tasks | |
| def update_task_status(self, issue_number: int, status: str) -> Dict: | |
| """Update Task Status""" | |
| return self._github_request( | |
| "PATCH", | |
| f"issues/{issue_number}", | |
| json={ | |
| "labels": ["task", status], | |
| "state": "closed" if status == "completed" else "open", | |
| }, | |
| ) | |
| # ========================================================================= | |
| # Credentials / Secrets Management | |
| # ========================================================================= | |
| def store_credential(self, name: str, value: str) -> Dict: | |
| """ | |
| Speichere Credential als GitHub Secret | |
| (Verschlüsselt, nur via GitHub Actions zugänglich) | |
| """ | |
| # GitHub Secrets API | |
| secrets_url = f"https://api.github.com/repos/{self.repo_owner}/{self.repo_name}/actions/secrets/{name}" | |
| # Get public key for encryption | |
| key_resp = self._github_request("GET", "actions/secrets/public-key") | |
| # Encrypt value | |
| from nacl import public | |
| public_key = public.PublicKey(base64.b64decode(key_resp["key"])) | |
| sealed_box = public.SealedBox(public_key) | |
| encrypted = base64.b64encode(sealed_box.encrypt(value.encode())).decode() | |
| # Store secret | |
| response = requests.put( | |
| secrets_url, headers=self.headers, json={"encrypted_value": encrypted, "key_id": key_resp["key_id"]}, timeout=30 | |
| ) | |
| return { | |
| "name": name, | |
| "stored": response.status_code == 201, | |
| "updated_at": datetime.now(timezone.utc).isoformat(), | |
| } | |
| def get_credential(self, name: str) -> Optional[str]: | |
| """ | |
| ⚠️ Credentials können NICHT direkt gelesen werden! | |
| Sie sind nur via GitHub Actions verfügbar. | |
| Dies ist ein Sicherheitsfeature! | |
| """ | |
| return None # Nicht möglich durch Design | |
| # ========================================================================= | |
| # AI Integration | |
| # ========================================================================= | |
| def call_anthropic(self, prompt: str, context: List[Dict] = None) -> Dict: | |
| """Rufe Anthropic Claude API über GitHub Secret""" | |
| api_key = self.ai_providers.get("anthropic") | |
| if not api_key: | |
| return {"error": "Anthropic API key not configured"} | |
| headers = { | |
| "x-api-key": api_key, | |
| "Content-Type": "application/json", | |
| "anthropic-version": "2023-06-01", | |
| } | |
| messages = [] | |
| if context: | |
| for ctx in context: | |
| messages.append( | |
| { | |
| "role": "assistant" if ctx.get("ai") else "user", | |
| "content": ctx.get("content", ""), | |
| } | |
| ) | |
| messages.append({"role": "user", "content": prompt}) | |
| response = requests.post( | |
| "https://api.anthropic.com/v1/messages", | |
| headers=headers, | |
| json={ | |
| "model": "claude-3-opus-20240229", | |
| "max_tokens": 4096, | |
| "messages": messages, | |
| }, | |
| timeout=30, | |
| ) | |
| if response.status_code == 200: | |
| data = response.json() | |
| # Speichere Response als Memory | |
| self.save_memory( | |
| f"anthropic_{datetime.now(timezone.utc).timestamp()}", | |
| f"Prompt: {prompt[:100]}...\n\nResponse: {data['content'][0]['text'][:200]}...", | |
| tags=["anthropic", "ai-response"], | |
| ) | |
| return { | |
| "success": True, | |
| "content": data["content"][0]["text"], | |
| "model": data["model"], | |
| "usage": data.get("usage", {}), | |
| } | |
| return {"error": response.text} | |
| def call_codex(self, prompt: str, context: List[Dict] = None) -> Dict: | |
| """Rufe OpenAI Codex API""" | |
| api_key = self.ai_providers.get("openai") | |
| if not api_key: | |
| return {"error": "OpenAI API key not configured"} | |
| headers = { | |
| "Authorization": f"Bearer {api_key}", | |
| "Content-Type": "application/json", | |
| } | |
| messages = [ | |
| { | |
| "role": "system", | |
| "content": "You are a helpful coding assistant.", | |
| } | |
| ] | |
| if context: | |
| for ctx in context: | |
| messages.append( | |
| { | |
| "role": "assistant" if ctx.get("ai") else "user", | |
| "content": ctx.get("content", ""), | |
| } | |
| ) | |
| messages.append({"role": "user", "content": prompt}) | |
| response = requests.post( | |
| "https://api.openai.com/v1/chat/completions", | |
| headers=headers, | |
| json={"model": "gpt-4-turbo-preview", "messages": messages}, | |
| timeout=30, | |
| ) | |
| if response.status_code == 200: | |
| data = response.json() | |
| # Speichere Response als Memory | |
| self.save_memory( | |
| f"codex_{datetime.now(timezone.utc).timestamp()}", | |
| f"Prompt: {prompt[:100]}...\n\nResponse: {data['choices'][0]['message']['content'][:200]}...", | |
| tags=["codex", "ai-response"], | |
| ) | |
| return { | |
| "success": True, | |
| "content": data["choices"][0]["message"]["content"], | |
| "model": data["model"], | |
| "usage": data.get("usage", {}), | |
| } | |
| return {"error": response.text} | |
| # ========================================================================= | |
| # Workflow / Cronjob Management | |
| # ========================================================================= | |
| def trigger_workflow(self, workflow_name: str, inputs: Dict[str, str] = None) -> Dict: | |
| """Trigger einen GitHub Actions Workflow""" | |
| endpoint = f"actions/workflows/{workflow_name}/dispatches" | |
| return self._github_request("POST", endpoint, json={"ref": "main", "inputs": inputs or {}}) | |
| def get_workflow_runs(self, workflow_name: str = None) -> List[Dict]: | |
| """Hole Workflow Ausführungen""" | |
| endpoint = "actions/runs" | |
| if workflow_name: | |
| # Filter by workflow | |
| pass | |
| data = self._github_request("GET", endpoint) | |
| return [ | |
| { | |
| "id": run["id"], | |
| "name": run["name"], | |
| "status": run["status"], | |
| "conclusion": run["conclusion"], | |
| "created_at": run["created_at"], | |
| "url": run["html_url"], | |
| } | |
| for run in data.get("workflow_runs", []) | |
| ] | |
| # ========================================================================= | |
| # MCP Session Management | |
| # ========================================================================= | |
| def create_session(self, user_id: str, ai_provider: str) -> MCPContext: | |
| """Erstelle neue MCP Session""" | |
| session = MCPContext( | |
| session_id=secrets.token_urlsafe(32), | |
| user_id=user_id, | |
| ai_provider=ai_provider, | |
| workspace=f"workspace_{user_id}_{datetime.now(timezone.utc).strftime('%Y%m%d')}", | |
| memory_refs=[], | |
| created_at=datetime.now(timezone.utc), | |
| expires_at=datetime.now(timezone.utc) + timedelta(hours=24), | |
| ) | |
| self._sessions[session.session_id] = session | |
| # Speichere Session als Memory | |
| self.save_memory( | |
| session.session_id, | |
| f"Session created for {user_id} with {ai_provider}", | |
| tags=["session", ai_provider], | |
| ) | |
| return session | |
| def get_session(self, session_id: str) -> Optional[MCPContext]: | |
| """Hole Session""" | |
| session = self._sessions.get(session_id) | |
| if session and datetime.now(timezone.utc) > session.expires_at: | |
| del self._sessions[session_id] | |
| return None | |
| return session | |
| def extend_session(self, session_id: str) -> bool: | |
| """Verlängere Session um 24h""" | |
| session = self._sessions.get(session_id) | |
| if session: | |
| session.expires_at = datetime.now(timezone.utc) + timedelta(hours=24) | |
| return True | |
| return False | |
| # Singleton | |
| _mcp_server: Optional[GitHubMCPServer] = None | |
| def get_mcp_server(github_token: str = None) -> GitHubMCPServer: | |
| """Get or create MCP Server instance""" | |
| global _mcp_server | |
| if _mcp_server is None: | |
| token = github_token or os.getenv("GITHUB_TOKEN") | |
| if not token: | |
| raise ValueError("GitHub token required") | |
| # AI Providers from env | |
| ai_providers = { | |
| "anthropic": os.getenv("ANTHROPIC_API_KEY"), | |
| "openai": os.getenv("OPENAI_API_KEY"), | |
| "kimi": os.getenv("KIMI_API_KEY"), | |
| } | |
| _mcp_server = GitHubMCPServer( | |
| github_token=token, | |
| ai_providers={k: v for k, v in ai_providers.items() if v}, | |
| ) | |
| return _mcp_server | |
| if __name__ == "__main__": | |
| print("🌐 GitHub MCP Server") | |
| print("=" * 50) | |
| print("\nFeatures:") | |
| print(" ✅ AI Memory via GitHub Issues") | |
| print(" ✅ Secure Credentials (GitHub Secrets)") | |
| print(" ✅ Aufgaben/Dienstplan") | |
| print(" ✅ Multi-AI Integration") | |
| print(" ✅ Workflow Management") | |
| print("\nSetup:") | |
| print(" 1. Create GitHub repo: zen-alpha-mcp") | |
| print(" 2. Set GITHUB_TOKEN env var") | |
| print(" 3. (Optional) Set AI API keys") | |
Xet Storage Details
- Size:
- 17.3 kB
- Xet hash:
- aa3289e8cb1ee11bd0d42cf449b5b3c57ca70f45144b91128c171e9ed9c24021
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.