#!/usr/bin/env python3 """ Emgena DataOps & Query Performance MCP Guard (Enterprise Edition) Standard Model Context Protocol (MCP) Server for Cursor IDE & Claude Desktop. Protocol: JSON-RPC 2.0 via stdio Zero external dependencies: 100% Python standard library. """ import sys import os import json import ast import re from pathlib import Path from typing import Dict, Any, List, Optional sys.stdout.reconfigure(encoding="utf-8") sys.stdin.reconfigure(encoding="utf-8") KB_FILE = Path(__file__).parent / "knowledge_base.json" KNOWLEDGE_BASE = [] if KB_FILE.exists(): try: KNOWLEDGE_BASE = json.loads(KB_FILE.read_text(encoding="utf-8")) except Exception: pass # ===================================================================== # CORE DATAOPS & QUERY PERFORMANCE LOGIC # ===================================================================== def diagnose_slow_query(query_or_plan: str, target_engine: str = "postgresql") -> Dict[str, Any]: """Analyzes SQL queries and PostgreSQL EXPLAIN (ANALYZE, BUFFERS) execution plans, diagnosing sequential scans and proposing concurrent indexes.""" issues = [] proposed_indexes = [] # 1. Sequential Scan on large tables seq_match = re.search(r"Seq Scan on (\w+).*?rows=(\d+)", query_or_plan, re.IGNORECASE) if seq_match or ("seq scan" in query_or_plan.lower()): tbl = seq_match.group(1) if seq_match else "target_table" rows = seq_match.group(2) if seq_match else "high" issues.append({ "severity": "HIGH", "type": "FULL_TABLE_SEQ_SCAN", "table": tbl, "message": f"Full table sequential scan detected on table '{tbl}' (estimated rows: {rows}). High I/O and shared buffer churn.", "optimization": f"Add a composite B-Tree index on filtered/joined predicate columns." }) proposed_indexes.append(f"CREATE INDEX CONCURRENTLY idx_{tbl}_query_perf ON {tbl} (created_at DESC, status);") # 2. SELECT * on wide tables if re.search(r"SELECT\s+\*\s+FROM", query_or_plan, re.IGNORECASE): issues.append({ "severity": "MEDIUM", "type": "SELECT_STAR_OVERFETCHING", "message": "Wildcard SELECT * forces PostgreSQL to read all toasted columns, bypassing index-only scans.", "optimization": "Explicitly project only required columns to enable Index-Only Scans." }) # 3. Missing LIMIT in high-volume query if ("select " in query_or_plan.lower()) and ("limit" not in query_or_plan.lower()) and ("count(" not in query_or_plan.lower()): issues.append({ "severity": "HIGH", "type": "UNBOUNDED_RESULT_SET", "message": "Query lacks an explicit LIMIT clause, risking client out-of-memory under large result sets.", "optimization": "Add 'LIMIT 100' or keyset pagination ('WHERE id > :last_id ORDER BY id LIMIT 50')." }) # 4. Hash Join with high buffer read if "hash join" in query_or_plan.lower() and "buffers: shared read" in query_or_plan.lower(): issues.append({ "severity": "HIGH", "type": "DISK_BUFFER_SPILL_JOIN", "message": "Hash Join spilled to disk or read from cold shared buffers due to insufficient work_mem.", "optimization": "Increase work_mem for the session: 'SET LOCAL work_mem = '64MB';'." }) score = max(0, 100 - (len(issues) * 25)) return { "engine": target_engine, "performance_score": score, "status": "OPTIMAL" if score == 100 else "DEGRADED" if score >= 60 else "CRITICAL", "total_issues": len(issues), "issues": issues, "proposed_indexes": proposed_indexes } def guard_ddl_migrations(migration_code: str) -> Dict[str, Any]: """Scans Alembic and SQL schema migration scripts for dangerous AccessExclusiveLock timeouts, table rewrites, and non-concurrent indexes.""" findings = [] # 1. Missing lock_timeout if ("op.alter_column" in migration_code or "op.add_column" in migration_code or "op.drop_column" in migration_code) and \ "lock_timeout" not in migration_code: findings.append({ "severity": "CRITICAL", "rule": "MISSING_MIGRATION_LOCK_TIMEOUT", "message": "ALTER TABLE statement without SET LOCAL lock_timeout can queue behind slow queries and cause a total connection pool stall.", "remediation": "Prepend migration with: op.execute(\"SET LOCAL lock_timeout = '2s';\")" }) # 2. Non-concurrent index creation if "op.create_index" in migration_code and "postgresql_concurrently=True" not in migration_code: findings.append({ "severity": "HIGH", "rule": "NON_CONCURRENT_INDEX_CREATION", "message": "Creating an index without 'postgresql_concurrently=True' holds a SHARE lock, blocking all concurrent writes.", "remediation": "Enable autocommit block and specify 'postgresql_concurrently=True' in op.create_index." }) # 3. Adding NOT NULL column without server default if "nullable=False" in migration_code and "server_default=" not in migration_code and "op.add_column" in migration_code: findings.append({ "severity": "HIGH", "rule": "ADD_NOT_NULL_WITHOUT_DEFAULT", "message": "Adding a NOT NULL column without server_default fails on existing non-empty tables and locks writes.", "remediation": "Add column as nullable first, backfill data in batches, then alter column to set NOT NULL." }) score = max(0, 100 - (len(findings) * 30)) return { "audit_type": "DDL_MIGRATION_SAFETY", "safety_score": score, "status": "APPROVED" if len(findings) == 0 else "REJECTED_DANGEROUS_LOCKS", "total_findings": len(findings), "findings": findings } def audit_connection_pool(config_or_code: str) -> Dict[str, Any]: """Audits SQLAlchemy Async, asyncpg, and pgBouncer configurations for unclosed sessions, pool exhaustion, and greenlet worker leaks.""" leaks = [] # 1. Missing AsyncSession context manager if "session = AsyncSession(" in config_or_code and "async with" not in config_or_code: leaks.append({ "severity": "CRITICAL", "type": "UNCLOSED_ASYNC_SESSION", "message": "AsyncSession initialized without 'async with' context manager. Connections remain checked out of the pool indefinitely.", "fix": "Wrap database interactions inside: 'async with AsyncSessionLocal() as session:'." }) # 2. Zero pool recycle / missing timeout if "create_async_engine" in config_or_code and "pool_recycle" not in config_or_code: leaks.append({ "severity": "MEDIUM", "type": "MISSING_POOL_RECYCLE", "message": "create_async_engine lacks pool_recycle parameter. Dead or severed stateful connections cause transient 500 errors.", "fix": "Set pool_recycle=1800 (30 minutes) and pool_pre_ping=True." }) # 3. Unbounded max_overflow if "max_overflow=0" not in config_or_code and "max_overflow" in config_or_code: m = re.search(r"max_overflow\s*=\s*(\d+)", config_or_code) if m and int(m.group(1)) > 50: leaks.append({ "severity": "HIGH", "type": "EXCESSIVE_MAX_OVERFLOW", "message": f"max_overflow ({m.group(1)}) is dangerously high, risking PostgreSQL max_connections exhaustion.", "fix": "Bound max_overflow <= 10 and delegate connection multiplexing to pgBouncer in transaction mode." }) score = max(0, 100 - (len(leaks) * 30)) return { "audit_type": "CONNECTION_POOL_INTEGRITY", "pool_health_score": score, "status": "HEALTHY" if score >= 80 else "AT_RISK", "total_issues": len(leaks), "issues": leaks } def cache_thundering_herd_guard(cache_code: str) -> Dict[str, Any]: """Audits Redis / Memcached caching patterns for cache stampede (thundering herd) risks and recommends probabilistic early expiration.""" vulnerabilities = [] # 1. Simple get-or-fetch without locking if ("redis.get(" in cache_code or "cache.get(" in cache_code) and \ ("lock(" not in cache_code and "setnx" not in cache_code.lower() and "stale" not in cache_code.lower()): vulnerabilities.append({ "severity": "HIGH", "risk": "CACHE_STAMPEDE_THUNDERING_HERD", "message": "Cache miss triggers direct database query without distributed locking. Under 5,000 req/s, all concurrent requests hit the DB simultaneously on key expiry.", "remediation": "Implement distributed lock (redis.set(key, val, nx=True, ex=5)) or probabilistic early recomputation (XFetch algorithm)." }) # 2. Static TTL without jitter if re.search(r"ex\s*=\s*3600|ttl\s*=\s*3600|expire\s*\(\s*key\s*,\s*\d+\s*\)", cache_code) and "random" not in cache_code: vulnerabilities.append({ "severity": "MEDIUM", "risk": "SYNCHRONIZED_CACHE_EXPIRY", "message": "Static cache TTL without randomized jitter causes batch keys to expire at the exact same second.", "remediation": "Add jitter to expiration: ttl = base_ttl + random.randint(0, int(base_ttl * 0.1))." }) score = max(0, 100 - (len(vulnerabilities) * 35)) return { "audit_type": "CACHE_STAMPEDE_DEFENSE", "cache_resilience_score": score, "status": "PROTECTED" if score == 100 else "VULNERABLE_TO_STAMPEDE", "findings_count": len(vulnerabilities), "findings": vulnerabilities } # ===================================================================== # STANDARD MCP JSON-RPC 2.0 PROTOCOL LOOP (STDIO) # ===================================================================== TOOLS = [ { "name": "diagnose_slow_query", "description": "Analyzes PostgreSQL EXPLAIN (ANALYZE, BUFFERS) plans and SQL queries, diagnosing sequential scans and proposing exact concurrent B-Tree/BRIN indexes.", "inputSchema": { "type": "object", "properties": { "query_or_plan": {"type": "string", "description": "SQL query or EXPLAIN (ANALYZE, BUFFERS) text to analyze."}, "target_engine": {"type": "string", "description": "Database engine (postgresql, mysql, clickhouse)", "default": "postgresql"} }, "required": ["query_or_plan"] } }, { "name": "guard_ddl_migrations", "description": "Scans Alembic and SQL schema migration scripts for dangerous table lock patterns (missing lock_timeout, non-concurrent indexes, table rewrites).", "inputSchema": { "type": "object", "properties": { "migration_code": {"type": "string", "description": "Alembic Python migration script or raw DDL SQL."} }, "required": ["migration_code"] } }, { "name": "audit_connection_pool", "description": "Audits SQLAlchemy Async, asyncpg, and pgBouncer configs for unclosed sessions, connection pool exhaustion, and greenlet worker leaks.", "inputSchema": { "type": "object", "properties": { "config_or_code": {"type": "string", "description": "Database connection and session handling code snippet."} }, "required": ["config_or_code"] } }, { "name": "cache_thundering_herd_guard", "description": "Audits Redis / Memcached caching patterns for cache stampede (thundering herd) risks, missing distributed locks, and synchronized TTL expiry.", "inputSchema": { "type": "object", "properties": { "cache_code": {"type": "string", "description": "Application caching logic to inspect."} }, "required": ["cache_code"] } } ] def handle_request(req: Dict[str, Any]) -> Optional[Dict[str, Any]]: method = req.get("method") req_id = req.get("id") params = req.get("params", {}) if method == "initialize": return { "jsonrpc": "2.0", "id": req_id, "result": { "protocolVersion": "2024-11-05", "capabilities": {"tools": {}}, "serverInfo": { "name": "emgena-dataops-query-performance", "version": "2.0.0" } } } elif method == "tools/list": return { "jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS} } elif method == "tools/call": tool_name = params.get("name") args = params.get("arguments", {}) result_data = {} if tool_name == "diagnose_slow_query": result_data = diagnose_slow_query(args.get("query_or_plan", ""), args.get("target_engine", "postgresql")) elif tool_name == "guard_ddl_migrations": result_data = guard_ddl_migrations(args.get("migration_code", "")) elif tool_name == "audit_connection_pool": result_data = audit_connection_pool(args.get("config_or_code", "")) elif tool_name == "cache_thundering_herd_guard": result_data = cache_thundering_herd_guard(args.get("cache_code", "")) else: return { "jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Tool not found: {tool_name}"} } return { "jsonrpc": "2.0", "id": req_id, "result": { "content": [{"type": "text", "text": json.dumps(result_data, indent=2, ensure_ascii=False)}] } } 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("Emgena DataOps Query Performance MCP Server Health: OK") res = diagnose_slow_query("Seq Scan on orders (cost=0.00..1524.00 rows=50000 width=32)") print("Test Query Result:", res.get("status")) return # Standard MCP JSON-RPC line-by-line stdio loop 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()