Download gemini_mcp_server2.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/gemini_mcp_server2.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/gemini_mcp_server2.py
-
curl -L -o gemini_mcp_server2.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/gemini_mcp_server2.py
10.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| MINIMAL MCP SERVER FOR GEMINI CLI (DIAGNOSTIC VERSION 2.0) | |
| MODE: EXECUTION ONLY | |
| NO INITIATIVE. NO INTERPRETATION. | |
| """ | |
| import asyncio | |
| import json | |
| import re | |
| import shlex | |
| import uuid | |
| import logging | |
| import sys | |
| from dataclasses import dataclass | |
| from enum import Enum | |
| from pathlib import Path | |
| from typing import Dict, Any, Optional, Tuple | |
| import websockets | |
| import locale | |
| # ================= DIAGNOSTIC LOGGING — SPEC_2026_04_02-1 ================= | |
| logger = logging.getLogger("MCP_SERVER") | |
| logger.setLevel(logging.DEBUG) | |
| if logger.handlers: | |
| logger.handlers.clear() | |
| file_handler = logging.FileHandler( | |
| 'mcp_server_crash_log.txt', | |
| encoding='utf-8', | |
| mode='a' | |
| ) | |
| file_handler.setLevel(logging.DEBUG) | |
| file_handler.setFormatter( | |
| logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s') | |
| ) | |
| console_handler = logging.StreamHandler(sys.stdout) | |
| console_handler.setLevel(logging.INFO) | |
| console_handler.setFormatter( | |
| logging.Formatter('%(message)s') | |
| ) | |
| logger.addHandler(file_handler) | |
| logger.addHandler(console_handler) | |
| # ========================================================================= | |
| # ================= CONFIG ================= | |
| WORKSPACE_ROOT = Path(r"D:\gemini\AIColab") # CHANGE ONLY IF REQUIRED | |
| HOST = "127.0.0.1" | |
| PORT = 8765 | |
| # ================= MODELS ================= | |
| class ActionType(Enum): | |
| SHELL = "shell" | |
| FILE_EDIT = "file_edit" | |
| FILE_READ = "file_read" | |
| CODE_ANALYSIS = "code_analysis" | |
| SEARCH = "search" | |
| class Directive: | |
| action: ActionType | |
| tool: str | |
| parameters: Dict[str, Any] | |
| class ExecutionResult: | |
| success: bool | |
| output: str | |
| error: Optional[str] = None | |
| metadata: Optional[Dict[str, Any]] = None | |
| # ================= SECURITY ================= | |
| class SecurityLayer: | |
| ALLOWED_PATHS = [WORKSPACE_ROOT] | |
| FORBIDDEN_COMMANDS = [ | |
| r"rm\s+-rf", | |
| r"mkfs", | |
| r"dd\s+if=.*of=.*", | |
| r"chmod\s+777", | |
| r"shutdown", | |
| r"reboot", | |
| ] | |
| def validate_path(cls, path: Path) -> Tuple[bool, str]: | |
| try: | |
| abs_path = path.resolve() | |
| if any(abs_path.is_relative_to(p) for p in cls.ALLOWED_PATHS): | |
| return True, "OK" | |
| return False, "Path outside workspace" | |
| except Exception: | |
| return False, "Invalid path" | |
| def validate_command(cls, command: str) -> Tuple[bool, str]: | |
| for pattern in cls.FORBIDDEN_COMMANDS: | |
| if re.search(pattern, command, re.IGNORECASE): | |
| return False, f"Forbidden pattern: {pattern}" | |
| return True, "OK" | |
| # ================= EXECUTOR ================= | |
| class SimpleExecutor: | |
| def __init__(self, session_id: str): | |
| self.session_id = session_id | |
| async def execute(self, directive: Directive) -> ExecutionResult: | |
| if directive.action == ActionType.SHELL: | |
| return await self._shell(directive.parameters["command"]) | |
| if directive.action == ActionType.FILE_EDIT: | |
| return await self._edit(directive.parameters["path"], directive.parameters["content"]) | |
| if directive.action == ActionType.FILE_READ: | |
| return await self._read(directive.parameters["path"]) | |
| if directive.action == ActionType.CODE_ANALYSIS: | |
| return await self._tool(directive.parameters["tool"], directive.parameters["query"]) | |
| if directive.action == ActionType.SEARCH: | |
| return await self._search(directive.parameters["pattern"], directive.parameters.get("scope", "project")) | |
| return ExecutionResult(False, "", "Unknown action") | |
| async def _shell(self, command: str) -> ExecutionResult: | |
| ok, reason = SecurityLayer.validate_command(command) | |
| if not ok: | |
| return ExecutionResult(False, "", reason) | |
| try: | |
| proc = await asyncio.create_subprocess_shell( | |
| command, | |
| stdout=asyncio.subprocess.PIPE, | |
| stderr=asyncio.subprocess.PIPE, | |
| cwd=WORKSPACE_ROOT | |
| ) | |
| out, err = await asyncio.wait_for(proc.communicate(), timeout=30) | |
| # На Windows CMD использует CP866. Попытаемся использовать её, | |
| # если не выйдет - откатимся на системную. | |
| def safe_decode(data): | |
| if not data: return "" | |
| try: | |
| return data.decode('cp866') | |
| except: | |
| return data.decode(locale.getpreferredencoding(False), errors='replace') | |
| return ExecutionResult( | |
| proc.returncode == 0, | |
| safe_decode(out), | |
| safe_decode(err) if err else None | |
| ) | |
| except Exception as e: | |
| return ExecutionResult(False, "", str(e)) | |
| async def _edit(self, path: str, content: str) -> ExecutionResult: | |
| file_path = WORKSPACE_ROOT / path | |
| ok, reason = SecurityLayer.validate_path(file_path) | |
| if not ok: | |
| return ExecutionResult(False, "", reason) | |
| backup_created = False | |
| backup_name = None | |
| try: | |
| if file_path.exists(): | |
| backup_name = f"{file_path.name}.backup_{uuid.uuid4().hex[:8]}" | |
| file_path.rename(file_path.with_name(backup_name)) | |
| backup_created = True | |
| file_path.parent.mkdir(parents=True, exist_ok=True) | |
| file_path.write_text(content, encoding="utf-8") | |
| return ExecutionResult( | |
| True, | |
| f"File updated: {path}", | |
| metadata={ | |
| "backup_created": backup_created, | |
| "backup_file": backup_name | |
| } | |
| ) | |
| except Exception as e: | |
| return ExecutionResult(False, "", str(e)) | |
| async def _read(self, path: str) -> ExecutionResult: | |
| file_path = WORKSPACE_ROOT / path | |
| ok, reason = SecurityLayer.validate_path(file_path) | |
| if not ok: | |
| return ExecutionResult(False, "", reason) | |
| try: | |
| data = file_path.read_text(encoding="utf-8") | |
| return ExecutionResult(True, data, metadata={"size": len(data)}) | |
| except Exception as e: | |
| return ExecutionResult(False, "", str(e)) | |
| async def _tool(self, tool: str, query: str) -> ExecutionResult: | |
| # PLACEHOLDERS — DO NOT EXTEND | |
| tools = { | |
| "codebase_investigator": "find . -name '*.py' | head -20", | |
| "search_file_content": f"grep -r {shlex.quote(query)} --include='*.py' . | head -20", | |
| "dependency_analyzer": "cat requirements.txt 2>/dev/null || echo 'No requirements.txt'" | |
| } | |
| if tool not in tools: | |
| return ExecutionResult(False, "", "Unknown tool") | |
| result = await self._shell(tools[tool]) | |
| if result.success: | |
| result.output = "PLACEHOLDER TOOL\n" + result.output | |
| return result | |
| async def _search(self, pattern: str, scope: str) -> ExecutionResult: | |
| scopes = { | |
| "project": ".", | |
| "config": "config", | |
| "core": "core", | |
| "scripts": "scripts" | |
| } | |
| if scope not in scopes: | |
| return ExecutionResult(False, "", "Unknown scope") | |
| safe = shlex.quote(pattern) | |
| cmd = f"grep -r -E {safe} {scopes[scope]} 2>/dev/null | head -100" | |
| return await self._shell(cmd) | |
| # ================= MCP SERVER ================= | |
| class GeminiMCPServer: | |
| def __init__(self): | |
| self.sessions: Dict[str, SimpleExecutor] = {} | |
| async def handle(self, *args): | |
| # Универсальный адаптер для websockets < 10.0 и >= 10.0 | |
| if len(args) == 2: | |
| ws, path = args[0], args[1] | |
| else: | |
| ws = args[0] | |
| path = getattr(ws, 'path', '/') | |
| session_id = f"mcp-{uuid.uuid4()}" | |
| self.sessions[session_id] = SimpleExecutor(session_id) | |
| try: | |
| async for msg in ws: | |
| await self.process(session_id, ws, msg) | |
| finally: | |
| self.sessions.pop(session_id, None) | |
| async def process(self, sid, ws, msg): | |
| try: | |
| data = json.loads(msg) | |
| if "directive" not in data: | |
| logger.info(f"[MCP] Received non-directive message: {data.get('message', 'empty')}") | |
| return | |
| directive = Directive( | |
| action=ActionType(data["directive"]["action"]), | |
| tool=data["directive"]["tool"], | |
| parameters=data["directive"]["parameters"] | |
| ) | |
| result = await self.sessions[sid].execute(directive) | |
| # Преобразуем результат в словарь вручную для надежности | |
| result_dict = { | |
| "success": result.success, | |
| "output": result.output, | |
| "error": result.error, | |
| "metadata": result.metadata | |
| } | |
| await ws.send(json.dumps({ | |
| "type": "execution_result", | |
| "session_id": sid, | |
| "result": result_dict | |
| })) | |
| except Exception as e: | |
| logger.error(f"[ERROR] Error processing message: {e}") | |
| await ws.send(json.dumps({ | |
| "type": "error", | |
| "message": str(e) | |
| })) | |
| async def main(): | |
| server = GeminiMCPServer() | |
| logger.info(f"🚀 Starting MCP Diagnostic Server on {HOST}:{PORT}") | |
| # Запускаем сервер и ждем, пока он не будет прерван | |
| await websockets.serve(server.handle, HOST, PORT) | |
| # Эта строка должна быть после websockets.serve, чтобы цикл событий работал | |
| await asyncio.Future() # Это предотвращает выход из main, пока сервер работает | |
| if __name__ == "__main__": | |
| try: | |
| asyncio.run(main()) | |
| except KeyboardInterrupt: | |
| logger.info("🛑 Server stopped by user") | |
| except Exception as e: | |
| logger.critical(f"💥 Server crashed: {e}", exc_info=True) | |