#!/usr/bin/env python3 """ OmniMCP Python Backend Architect - 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/iiqgpq (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/iiqgpq" def audit_python_concurrency(code: str) -> dict: findings = [] if "time.sleep(" in code and ("async def" in code or "await " in code): findings.append({"severity": "CRITICAL", "issue": "Blocking time.sleep() detected inside async scope. Replaces event loop execution.", "fix": "Replace with 'await asyncio.sleep(...)'.", "rule": "BLOCKING_SLEEP_IN_ASYNC"}) if "requests.get(" in code or "requests.post(" in code: if "async def" in code: findings.append({"severity": "HIGH", "issue": "Synchronous 'requests' library blocks thread inside async coroutine.", "fix": "Use httpx.AsyncClient or aiohttp.ClientSession.", "rule": "BLOCKING_HTTP_IN_ASYNC"}) if "asyncio.Queue()" in code and "maxsize=" not in code: findings.append({"severity": "MEDIUM", "issue": "Unbounded asyncio.Queue() leads to memory leak under backpressure.", "fix": "Instantiate with explicit maxsize, e.g. asyncio.Queue(maxsize=1000).", "rule": "UNBOUNDED_QUEUE"}) return {"status": "ok", "total_issues": len(findings), "findings": findings, "ast_verified": True} def verify_ast_clean(code: str) -> dict: try: tree = ast.parse(code) return {"status": "valid", "syntax_valid": True, "ast_node_count": sum(1 for _ in ast.walk(tree)), "message": "Syntax 100% clean and valid."} except SyntaxError as e: return {"status": "error", "syntax_valid": False, "error": str(e), "line": e.lineno, "offset": e.offset} def diagnose_asyncio_deadlock(traceback_text: str) -> dict: tb = traceback_text.lower() if "future exception was never retrieved" in tb: return {"root_cause": "Unhandled exception in background Task without await or callback.", "fix": "Use asyncio.gather(return_exceptions=True) or attach add_done_callback().", "severity": "HIGH"} if "event loop is already running" in tb: return {"root_cause": "Nested asyncio.run() invoked inside already active event loop.", "fix": "Use asyncio.create_task() or nest_asyncio.apply().", "severity": "CRITICAL"} return {"root_cause": "Async event loop thread starvation or unyielded loop.", "fix": "Insert 'await asyncio.sleep(0)' in tight computation loops or offload to loop.run_in_executor().", "severity": "MEDIUM"} TOOLS = [ { "name": "audit_python_concurrency", "description": "Audits Python async/await code for event loop deadlocks, unawaited coroutines, and blocking calls.", "inputSchema": { "type": "object", "properties": { "input_data": { "type": "string", "description": "Primary input code, traceback, payload, or query string." } } } }, { "name": "verify_ast_clean", "description": "Parses Python code into an Abstract Syntax Tree to guarantee 0.0% syntax errors.", "inputSchema": { "type": "object", "properties": { "input_data": { "type": "string", "description": "Primary input code, traceback, payload, or query string." } } } }, { "name": "diagnose_asyncio_deadlock", "description": "Diagnoses Celery/AsyncIO worker freeze, thread starvation, and event loop locking.", "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-python-backend-architect", "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 == "audit_python_concurrency": first_param = list(inspect.signature(audit_python_concurrency).parameters.keys())[0] if inspect.signature(audit_python_concurrency).parameters else None if first_param: arg_val = args.get(first_param, args.get("input_data", args.get("code", args.get("query", "")))) res = audit_python_concurrency(arg_val) else: res = audit_python_concurrency() elif tool_name == "verify_ast_clean": first_param = list(inspect.signature(verify_ast_clean).parameters.keys())[0] if inspect.signature(verify_ast_clean).parameters else None if first_param: arg_val = args.get(first_param, args.get("input_data", args.get("code", args.get("query", "")))) res = verify_ast_clean(arg_val) else: res = verify_ast_clean() elif tool_name == "diagnose_asyncio_deadlock": first_param = list(inspect.signature(diagnose_asyncio_deadlock).parameters.keys())[0] if inspect.signature(diagnose_asyncio_deadlock).parameters else None if first_param: arg_val = args.get(first_param, args.get("input_data", args.get("code", args.get("query", "")))) res = diagnose_asyncio_deadlock(arg_val) else: res = diagnose_asyncio_deadlock() 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"OmniMCP Python Backend Architect 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()