#!/usr/bin/env python3 """ CodeArchitect Docker & Self-Healing PyTest Guard - Free Community MCP Server Standard Model Context Protocol (MCP) Server for Cursor IDE & Claude Desktop. Protocol: JSON-RPC 2.0 via stdio License: Apache 2.0 (Community Evaluation Edition) Full Enterprise Master Package on Gumroad: https://bacardy.gumroad.com/l/wyhbjn (Use Coupon LAUNCH20 for €20 off!) """ import sys import os import json import ast import inspect from typing import Dict, Any, List, Optional sys.stdout.reconfigure(encoding="utf-8") sys.stdin.reconfigure(encoding="utf-8") CALL_COUNTER = 0 MAX_COMMUNITY_CALLS = 25 GUMROAD_UPGRADE_URL = "https://bacardy.gumroad.com/l/wyhbjn" def heal_failing_pytest_traceback(traceback_text: str) -> dict: tb = traceback_text.lower() if "scope='function'" in tb or "scopemismatch" in tb: return {"fix_type": "FIXTURE_SCOPE_MISMATCH", "issue": "Event loop fixture scope incompatible with test module scope.", "fix": "Use @pytest_asyncio.fixture(scope='session') with custom event_loop fixture.", "ast_verified": True} if "fixture 'event_loop' not found" in tb: return {"fix_type": "MISSING_EVENT_LOOP_FIXTURE", "issue": "pytest-asyncio 0.21+ loop policy requirement.", "fix": "Add asyncio_mode = auto in pytest.ini or pyproject.toml.", "ast_verified": True} return {"fix_type": "GENERIC_ASSERTION", "issue": "Standard assertion failure.", "fix": "Inspect diff or mock external side effects.", "ast_verified": True} def audit_dockerfile_multi_stage(dockerfile_content: str) -> dict: df = dockerfile_content.lower() issues = [] if "from " in df and df.count("from ") < 2: issues.append({"rule": "SINGLE_STAGE_BUILD", "message": "Build tools and compilers remain in final image.", "fix": "Use multi-stage Docker build (AS builder / FROM distroless or alpine)."}) if "user " not in df: issues.append({"rule": "RUNS_AS_ROOT", "message": "Container defaults to root user.", "fix": "Add USER 10001 or USER appuser before CMD/ENTRYPOINT."}) return {"status": "ok", "total_issues": len(issues), "issues": issues} TOOLS = [ { "name": "heal_failing_pytest_traceback", "description": "Parses PyTest failure tracebacks (AssertionError, ScopeMismatch, FixtureLookupError) and synthesizes the exact fix.", "inputSchema": { "type": "object", "properties": { "input_data": { "type": "string", "description": "Primary input code, traceback, payload, or query string." } } } }, { "name": "audit_dockerfile_multi_stage", "description": "Audits Dockerfile for multi-stage caching, non-root user enforcement, and image size bloat.", "inputSchema": { "type": "object", "properties": { "input_data": { "type": "string", "description": "Primary input code, traceback, payload, or query string." } } } } ] def handle_request(req: Dict[str, Any]) -> Optional[Dict[str, Any]]: global CALL_COUNTER req_id = req.get("id") method = req.get("method") params = req.get("params", {}) if method == "initialize": return { "jsonrpc": "2.0", "id": req_id, "result": { "protocolVersion": "2024-11-05", "capabilities": {"tools": {}}, "serverInfo": { "name": "emgena-docker-pytest-selfheal", "version": "1.0.0" } } } elif method == "tools/list": return { "jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS} } elif method == "tools/call": CALL_COUNTER += 1 tool_name = params.get("name") args = params.get("arguments", {}) res = None if False: pass elif tool_name == "heal_failing_pytest_traceback": first_param = list(inspect.signature(heal_failing_pytest_traceback).parameters.keys())[0] if inspect.signature(heal_failing_pytest_traceback).parameters else None if first_param: arg_val = args.get(first_param, args.get("input_data", args.get("code", args.get("query", "")))) res = heal_failing_pytest_traceback(arg_val) else: res = heal_failing_pytest_traceback() elif tool_name == "audit_dockerfile_multi_stage": first_param = list(inspect.signature(audit_dockerfile_multi_stage).parameters.keys())[0] if inspect.signature(audit_dockerfile_multi_stage).parameters else None if first_param: arg_val = args.get(first_param, args.get("input_data", args.get("code", args.get("query", "")))) res = audit_dockerfile_multi_stage(arg_val) else: res = audit_dockerfile_multi_stage() else: return { "jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Tool not found: {tool_name}"} } conversion_notice = ( f"\n\n---\n" f"⚡ **Emgena MCP Free Edition** (Call {CALL_COUNTER}/{MAX_COMMUNITY_CALLS})\n" f"🏆 **Unlock Unlimited Enterprise Suite, 0ms Latency & Full Source Code:**\n" f"👉 [Purchase Production License on Gumroad]({GUMROAD_UPGRADE_URL})\n" f"🏷️ *Use coupon **LAUNCH20** for €20 discount at checkout!*" ) output_text = json.dumps(res, indent=2, ensure_ascii=False) + conversion_notice return { "jsonrpc": "2.0", "id": req_id, "result": { "content": [{"type": "text", "text": output_text}] } } elif method == "notifications/initialized": return None elif method == "ping": return {"jsonrpc": "2.0", "id": req_id, "result": {}} else: if req_id is not None: return { "jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not supported: {method}"} } return None def main(): if len(sys.argv) > 1 and sys.argv[1] == "--test": print(f"CodeArchitect Docker & Self-Healing PyTest Guard MCP Server Health: OK") print("Tools available:", [t["name"] for t in TOOLS]) return for line in sys.stdin: if not line.strip(): continue try: req = json.loads(line) resp = handle_request(req) if resp is not None: sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n") sys.stdout.flush() except Exception as e: err_resp = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(e)}} sys.stdout.write(json.dumps(err_resp, ensure_ascii=False) + "\n") sys.stdout.flush() if __name__ == "__main__": main()