emgena's picture
Upgrade with turnkey MCP Server for Cursor & Claude Desktop
f638eea verified
Raw History Blame Contribute Delete
7.2 kB
#!/usr/bin/env python3
"""
SQLAuditor BigQuery Analytics & Slot Optimizer - 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/pzisdo (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/pzisdo"
def analyze_bigquery_slot_exhaustion(sql_query: str) -> dict:
q = sql_query.lower()
recommendations = []
if "select *" in q:
recommendations.append({"rule": "AVOID_SELECT_ALL", "message": "SELECT * in BigQuery reads all column stores, drastically multiplying query cost.", "fix": "Select only explicit columns required."})
if "cross join" in q or ", " in q and "join" not in q and "where" not in q:
recommendations.append({"rule": "CARTESIAN_JOIN", "message": "Cross join creates exponential slot consumption.", "fix": "Use inner join with explicit indexed ON conditions."})
if "order by" in q and "limit" not in q:
recommendations.append({"rule": "ORDER_BY_WITHOUT_LIMIT", "message": "Global ORDER BY forces single-node slot sorting.", "fix": "Add LIMIT or partition by window function."})
return {"status": "ok", "total_bottlenecks": len(recommendations), "recommendations": recommendations}
def recommend_partition_clustering_keys(table_name: str, filter_columns: list) -> dict:
return {
"table": table_name,
"partition_strategy": f"PARTITION BY DATE({filter_columns[0]})" if filter_columns else "PARTITION BY DATE(_PARTITIONDATE)",
"clustering_strategy": f"CLUSTER BY {', '.join(filter_columns[1:4])}" if len(filter_columns) > 1 else "CLUSTER BY id",
"projected_cost_reduction": "70% to 92% less bytes scanned per query."
}
TOOLS = [
{
"name": "analyze_bigquery_slot_exhaustion",
"description": "Audits BigQuery SQL queries for unpartitioned scans, cartesian joins, and slot starvation.",
"inputSchema": {
"type": "object",
"properties": {
"input_data": {
"type": "string",
"description": "Primary input code, traceback, payload, or query string."
}
}
}
},
{
"name": "recommend_partition_clustering_keys",
"description": "Recommends time-partitioning and clustering keys based on query WHERE clause patterns.",
"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-bigquery-sql-optimizer",
"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 == "analyze_bigquery_slot_exhaustion":
first_param = list(inspect.signature(analyze_bigquery_slot_exhaustion).parameters.keys())[0] if inspect.signature(analyze_bigquery_slot_exhaustion).parameters else None
if first_param:
arg_val = args.get(first_param, args.get("input_data", args.get("code", args.get("query", ""))))
res = analyze_bigquery_slot_exhaustion(arg_val)
else:
res = analyze_bigquery_slot_exhaustion()
elif tool_name == "recommend_partition_clustering_keys":
first_param = list(inspect.signature(recommend_partition_clustering_keys).parameters.keys())[0] if inspect.signature(recommend_partition_clustering_keys).parameters else None
if first_param:
arg_val = args.get(first_param, args.get("input_data", args.get("code", args.get("query", ""))))
res = recommend_partition_clustering_keys(arg_val)
else:
res = recommend_partition_clustering_keys()
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"SQLAuditor BigQuery Analytics & Slot Optimizer 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()