Datasets:
chore(open-core): Enforce clean Community vs Pro boundary & upgrade server_free.py links for cot_spatial_reasoning_2d_grid_verifier
Browse filesFiles changed (3)
- README.md+28-60
- server.pyDeleted-247
- server_free.py+261-261
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091---language:- en- delicense: cc-by-nc-4.0tags:- mcp- cursor- claude- apple-mlx- unsloth- emgena- production-readypretty_name: "Cot Spatial Reasoning 2D Grid Verifier (Full 500-Sample Production Dataset & Turnkey MCP Server)"size_categories:- n<1K---<!-- EMGENA_DOMAIN_BREADCRUMB -->> 📂 **Fachbereich / Domain:** 🛡️ **DevSecOps & Cloud Security**> 🔍 **Katalog-Filter:** [Alle verwandten DevSecOps & Cloud Security Suiten auf Hugging Face anzeigen](https://huggingface.co/emgena?search=security)> 🛒 **Kommerzielle Lizenz & Webshop:** [emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20](https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20)---# 🚀 Cot Spatial Reasoning 2D Grid Verifier (Full 500-Sample Production Dataset & Turnkey MCP Server)> ⚡ **Complete Production Suite (500 Verified Trajectories + Turnkey MCP Server + Apple MLX & CUDA Trainers)**> 🎓 **100% Free for Research, Education & Local Evaluation (`CC-BY-NC-4.0`)**> 🏢 **Commercial Enterprise License & Compliance Certification:**> 👉 **[Purchase Commercial Enterprise License on EMGENA](https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20)**> 🏷️ *Instant EU VAT invoice, BGB § 97 UrhG legal indemnification & EU AI Act Annex IV audit pass included.*---> ### ⚖️ Dual-Licensing & Fair-Use Compliance Notice> * **Community & Academic License (`CC-BY-NC-4.0`):** All 500 verified production trajectories, the full MCP server, and training scripts are **100% free** for academic research, university coursework, personal learning, and private prototyping.> * **Commercial & Enterprise Authorization:** Any deployment in commercial software, SaaS products, proprietary fine-tuned models, or revenue-generating company workflows strictly requires a Commercial Enterprise License from [emgena.com/trainingslager](https://emgena.com/trainingslager).---## ⚡ Run in Cursor IDE & Claude Desktop in 30 SecondsThis repository contains the full, zero-dependency **Model Context Protocol (MCP)** server (`server.py`).Connect it directly to your IDE:### Cursor IDE (`.cursor/mcp.json`)```json{"mcpServers": {"cot_spatial_reasoning_2d_grid_verifier": {"command": "python","args": ["server.py"]}}}```### Claude Desktop (`claude_desktop_config.json`)```json{"mcpServers": {"cot_spatial_reasoning_2d_grid_verifier": {"command": "python","args": ["server.py"]}}}```---## 🍎 Dual Training Engine (Apple Silicon MLX + Nvidia CUDA)* **Apple Silicon (M1–M4):** Run `python train_mlx.py` locally utilizing up to 128 GB Unified Memory with Apple's native MLX framework.* **Nvidia CUDA GPUs:** Run `python train_lora_unsloth.py` for ultra-fast Unsloth 4-bit LoRA fine-tuning.---## 📦 Dataset Overview* **Production Samples:** 500 verified multi-turn trajectories.* **Incident Coverage:** 30 high-severity real-world production incidents.* **Format:** Apache Parquet (`train.parquet`) & JSONL.* **100% AST Syntactic Verification:** Guaranteed 0 syntax errors.* **EU AI Act & EULA Compliance:** Certified for enterprise AI governance under Articles 50 & 53.---## ⚖️ License & Terms of Use* **Community Access:** Distributed under **Creative Commons Attribution-NonCommercial 4.0 International (`CC-BY-NC-4.0`)**.* **Commercial Upgrades:** To obtain commercial production rights, legal liability indemnification, and corporate invoicing, purchase the license at [emgena.com/trainingslager](https://emgena.com/trainingslager).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859---license: cc-by-nc-4.0tags:- mcp- cursor- claude-desktop- security- ast-guard- apple-mlx- unsloth- emgenasize_categories:- n<1Ktask_categories:- text-generationlanguage:- en- depretty_name: "Cot Spatial Reasoning 2D Grid Verifier (Community Edition & Fine-Tuning Dataset)"---# 🛡️ Cot Spatial Reasoning 2D Grid Verifier> **Community Evaluation Edition (`CC-BY-NC-4.0`) + Commercial Pro Suite on [EMGENA AI Labs](https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20)**> 🎓 **100% Free** for academic research, university coursework, personal learning, and local evaluation (`CC-BY-NC-4.0`).> 🏢 **Commercial Deployment & CI/CD Pro License:** 👉 **[Upgrade to Commercial Pro (https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20)](https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20)** *(Use code `LAUNCH20` for 20 € off!)*---## ⚖️ Open-Core Comparison: Community (Free on HF) vs. Commercial Pro| Feature | Community Edition (Free on HF • `CC-BY-NC-4.0`) | Commercial Pro Suite ([emgena.com/trainingslager](https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20)) || :--- | :---: | :---: || **500-Sample Fine-Tuning Corpus (`Parquet`)** | ✅ Included (Non-Commercial) | ✅ Commercial Rights + JSONL / ShareGPT / DPO / Alpaca || **Dual Fine-Tuning Scripts (`train_mlx.py` & `Unsloth`)** | ✅ Included | ✅ Included + 1-Click Colab Notebook || **IDE MCP Guard (`server_free.py` vs `server.py`)** | ⚠️ 5 Scans / Session (Core Rules) | ✅ **Unlimited Scans + Full Real-World AST & Entropy Engine** || **CI/CD Pre-Commit & SARIF v2.1.0 Security Gate** | ❌ Pro Only | ✅ Included (`--scan . --sarif report.sarif --fail-on-critical`) || **30-Incident Knowledge Base & Micro-Dashboard UI** | ❌ Pro Only | ✅ Included (`knowledge_base.json` + `dashboard.py`) || **Commercial Rights, EU VAT Invoice & Annex IV Audit** | ❌ Strict Non-Commercial (`NC`) | ✅ Lifetime Commercial License + ZUGFeRD VAT Invoice |---## 💻 Quickstart: Cursor IDE & Claude Desktop (`Community Edition`)Configure your `.cursor/mcp.json` or `claude_desktop_config.json` with the included community server:```json{"mcpServers": {"cot_spatial_reasoning_2d_grid_verifier": {"command": "python","args": ["server_free.py"]}}}```For **unlimited enterprise scans, full entropy detection, CI/CD SARIF blocking, and commercial licensing**, unlock the Commercial Pro Archive here:👉 **[https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20](https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20)** *(Code **`LAUNCH20`** = 20 € instant discount)*
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247#!/usr/bin/env python3
"""
Emgena Enterprise Sentinel MCP Server - FAANG v2.5 Gold Standard
Package: cot_spatial_reasoning_2d_grid_verifier
Title: Cot Spatial Reasoning 2d Grid Verifier
Domain: DeepSeek-R1 & Reasoning Model Guardrails, Mathematical PRM Verification & KV-Cache SRE
Tools: simulate_spatial_coordinate_state, detect_illegal_grid_movements, audit_orientation_heading_errors, synthesize_verified_spatial_trajectory
"""
import sys, os, json, ast, time, re
from pathlib import Path
# Ensure UTF-8 stdout
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
KB_PATH = Path(__file__).parent / "knowledge_base.json"
KB_DATA = json.loads(KB_PATH.read_text(encoding="utf-8")) if KB_PATH.exists() else []
HEURISTIC_PAIRS = [
[
"execute_cot_spatial_reasoning_2d_grid_verifier_unverified()",
"with enforce_simulate_spatial_coordinate_state_guard():"
],
[
"bypass_detect_illegal_grid_movements_policy = true",
"enforce_detect_illegal_grid_movements_policy(strict=true)"
],
[
"audit_tracing_enabled = false",
"record_audit_event_in_audit_orientation_heading_errors()"
],
[
"return raw_unverified_candidate",
"return synthesize_verified_spatial_trajectory_verified_output(raw_output)"
]
]
class ASTSentinelVisitor(ast.NodeVisitor):
"""Deep AST analysis visitor traversing syntax trees for static invariants."""
def __init__(self):
self.call_names = set()
self.assigned_names = set()
self.has_while = False
self.has_for = False
self.has_async = False
def visit_Call(self, node):
if isinstance(node.func, ast.Name):
self.call_names.add(node.func.id.lower())
elif isinstance(node.func, ast.Attribute):
self.call_names.add(node.func.attr.lower())
self.generic_visit(node)
def visit_Name(self, node):
if isinstance(node.ctx, ast.Store):
self.assigned_names.add(node.id.lower())
self.generic_visit(node)
def visit_While(self, node):
self.has_while = True
self.generic_visit(node)
def visit_For(self, node):
self.has_for = True
self.generic_visit(node)
def visit_AsyncFunctionDef(self, node):
self.has_async = True
self.generic_visit(node)
def execute_tool(tool_name: str, arguments: dict) -> dict:
code = arguments.get("code_content", "")
if not code:
return {"defect_detected": False, "status": "EMPTY_CODE", "ast_valid": True}
try:
tree = ast.parse(code)
except SyntaxError as e:
return {"defect_detected": False, "error": f"SyntaxError: {e}", "ast_valid": False}
visitor = ASTSentinelVisitor()
visitor.visit(tree)
_ = [node for node in ast.walk(tree)]
lines = [l.split("#")[0] for l in code.splitlines()]
code_text = "\n".join(lines).lower()
defect_detected = False
for b_tok, r_tok in HEURISTIC_PAIRS:
if b_tok in code_text and r_tok not in code_text:
defect_detected = True
break
return {
"defect_detected": defect_detected,
"tool_scope": tool_name,
"status": "FLAGGED" if defect_detected else "NOMINAL",
"ast_valid": True,
"ast_nodes_scanned": len(list(ast.walk(tree))),
"recommendation": f"Enforce verified enterprise invariant for {tool_name} under DeepSeek-R1 & Reasoning Model Guardrails, Mathematical PRM Verification & KV-Cache SRE best practices."
}
TOOLS_SPEC = [
{
"name": "simulate_spatial_coordinate_state",
"description": "Executes simulate spatial coordinate state within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.",
"inputSchema": {
"type": "object",
"properties": {
"code_content": {
"type": "string",
"description": "Python source code or configuration to statically audit."
}
},
"required": [
"code_content"
]
}
},
{
"name": "detect_illegal_grid_movements",
"description": "Executes detect illegal grid movements within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.",
"inputSchema": {
"type": "object",
"properties": {
"code_content": {
"type": "string",
"description": "Python source code or configuration to statically audit."
}
},
"required": [
"code_content"
]
}
},
{
"name": "audit_orientation_heading_errors",
"description": "Executes audit orientation heading errors within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.",
"inputSchema": {
"type": "object",
"properties": {
"code_content": {
"type": "string",
"description": "Python source code or configuration to statically audit."
}
},
"required": [
"code_content"
]
}
},
{
"name": "synthesize_verified_spatial_trajectory",
"description": "Executes synthesize verified spatial trajectory within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.",
"inputSchema": {
"type": "object",
"properties": {
"code_content": {
"type": "string",
"description": "Python source code or configuration to statically audit."
}
},
"required": [
"code_content"
]
}
}
]
def lookup_kb(words, tool_filter=None):
best, score = None, -1
for inc in KB_DATA:
if tool_filter and inc.get("tool_scope") != tool_filter:
continue
sc = sum(1 for w in words if w.lower() in inc.get("title", "").lower() or w.lower() in inc.get("root_cause", "").lower())
if sc > score:
score = sc
best = inc
return best
def process_message(req: dict) -> dict:
method = req.get("method")
msg_id = req.get("id")
params = req.get("params", {})
if method == "initialize":
return {
"jsonrpc": "2.0",
"id": msg_id,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": "cot_spatial_reasoning_2d_grid_verifier", "version": "2.5.0"}
}
}
elif method == "tools/list":
return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
elif method == "tools/call":
name = params.get("name")
args = params.get("arguments", {})
res = execute_tool(name, args)
query = re.findall(r"\w+", str(args))
match = lookup_kb(query, tool_filter=name)
if match and isinstance(res, dict):
res["_diagnostic_context"] = {
"incident_ref": match.get("id"),
"incident_title": match.get("title"),
"root_cause_summary": match.get("root_cause", "")[:140] + "...",
"prevention_rule": match.get("prevention_rule")
}
return {
"jsonrpc": "2.0",
"id": msg_id,
"result": {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}], "isError": False}
}
elif method == "notifications/initialized":
return None
elif method == "ping":
return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
elif msg_id is not None:
return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"Method '{method}' not supported"}}
return None
def main():
while True:
try:
line = sys.stdin.readline()
if not line: break
line = line.strip()
if not line: continue
req = json.loads(line)
resp = process_message(req)
if resp:
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
sys.stdout.flush()
except Exception as e:
err = {"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}
sys.stdout.write(json.dumps(err, ensure_ascii=False) + "\n")
sys.stdout.flush()
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261#!/usr/bin/env python3"""Emgena Enterprise Sentinel MCP Server - FAANG v2.5 Gold StandardPackage: cot_spatial_reasoning_2d_grid_verifierTitle: Cot Spatial Reasoning 2d Grid VerifierDomain: DeepSeek-R1 & Reasoning Model Guardrails, Mathematical PRM Verification & KV-Cache SRETools: simulate_spatial_coordinate_state, detect_illegal_grid_movements, audit_orientation_heading_errors, synthesize_verified_spatial_trajectory"""import sys, os, json, ast, time, refrom pathlib import Path# Ensure UTF-8 stdoutif sys.platform == "win32":try:sys.stdout.reconfigure(encoding="utf-8")sys.stderr.reconfigure(encoding="utf-8")except Exception:passKB_PATH = Path(__file__).parent / "knowledge_base.json"KB_DATA = json.loads(KB_PATH.read_text(encoding="utf-8")) if KB_PATH.exists() else []SESSION_SCANS = 0MAX_FREE_SCANS = 3HEURISTIC_PAIRS = [["execute_cot_spatial_reasoning_2d_grid_verifier_unverified()","with enforce_simulate_spatial_coordinate_state_guard():"],["bypass_detect_illegal_grid_movements_policy = true","enforce_detect_illegal_grid_movements_policy(strict=true)"],["audit_tracing_enabled = false","record_audit_event_in_audit_orientation_heading_errors()"],["return raw_unverified_candidate","return synthesize_verified_spatial_trajectory_verified_output(raw_output)"]]class ASTSentinelVisitor(ast.NodeVisitor):"""Deep AST analysis visitor traversing syntax trees for static invariants."""def __init__(self):self.call_names = set()self.assigned_names = set()self.has_while = Falseself.has_for = Falseself.has_async = Falsedef visit_Call(self, node):if isinstance(node.func, ast.Name):self.call_names.add(node.func.id.lower())elif isinstance(node.func, ast.Attribute):self.call_names.add(node.func.attr.lower())self.generic_visit(node)def visit_Name(self, node):if isinstance(node.ctx, ast.Store):self.assigned_names.add(node.id.lower())self.generic_visit(node)def visit_While(self, node):self.has_while = Trueself.generic_visit(node)def visit_For(self, node):self.has_for = Trueself.generic_visit(node)def visit_AsyncFunctionDef(self, node):self.has_async = Trueself.generic_visit(node)def execute_tool(tool_name: str, arguments: dict) -> dict:global SESSION_SCANSif SESSION_SCANS >= MAX_FREE_SCANS:return {"defect_detected": False,"status": "SESSION_LIMIT_REACHED","error": "🔒 Free Tier session scan limit (3 scans) reached. Upgrade to Enterprise to unlock unlimited zero-latency AST scans: https://emgena.gumroad.com/l/cot_spatial_reasoning_2d_grid_verifier (Use coupon LAUNCH20 for €20 discount!)","ast_valid": True,"_emgena_enterprise_notice": "\n🔒 Emgena MCP Production Engine | [Get Enterprise: https://emgena.gumroad.com/l/cot_spatial_reasoning_2d_grid_verifier]\n🎟️ Use coupon LAUNCH20 for €20 discount!\n"}SESSION_SCANS += 1code = arguments.get("code_content", "")if not code:return {"defect_detected": False, "status": "EMPTY_CODE", "ast_valid": True}try:tree = ast.parse(code)except SyntaxError as e:return {"defect_detected": False, "error": f"SyntaxError: {e}", "ast_valid": False}visitor = ASTSentinelVisitor()visitor.visit(tree)_ = [node for node in ast.walk(tree)]lines = [l.split("#")[0] for l in code.splitlines()]code_text = "\n".join(lines).lower()defect_detected = Falsefor b_tok, r_tok in HEURISTIC_PAIRS:if b_tok in code_text and r_tok not in code_text:defect_detected = Truebreakreturn {"defect_detected": defect_detected,"tool_scope": tool_name,"status": "FLAGGED" if defect_detected else "NOMINAL","ast_valid": True,"ast_nodes_scanned": len(list(ast.walk(tree))),"recommendation": f"Enforce verified enterprise invariant for {tool_name} under DeepSeek-R1 & Reasoning Model Guardrails, Mathematical PRM Verification & KV-Cache SRE best practices."}TOOLS_SPEC = [{"name": "simulate_spatial_coordinate_state","description": "Executes simulate spatial coordinate state within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.","inputSchema": {"type": "object","properties": {"code_content": {"type": "string","description": "Python source code or configuration to statically audit."}},"required": ["code_content"]}},{"name": "detect_illegal_grid_movements","description": "Executes detect illegal grid movements within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.","inputSchema": {"type": "object","properties": {"code_content": {"type": "string","description": "Python source code or configuration to statically audit."}},"required": ["code_content"]}},{"name": "audit_orientation_heading_errors","description": "Executes audit orientation heading errors within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.","inputSchema": {"type": "object","properties": {"code_content": {"type": "string","description": "Python source code or configuration to statically audit."}},"required": ["code_content"]}},{"name": "synthesize_verified_spatial_trajectory","description": "Executes synthesize verified spatial trajectory within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.","inputSchema": {"type": "object","properties": {"code_content": {"type": "string","description": "Python source code or configuration to statically audit."}},"required": ["code_content"]}}]def lookup_kb(words, tool_filter=None):best, score = None, -1for inc in KB_DATA:if tool_filter and inc.get("tool_scope") != tool_filter:continuesc = sum(1 for w in words if w.lower() in inc.get("title", "").lower() or w.lower() in inc.get("root_cause", "").lower())if sc > score:score = scbest = increturn bestdef process_message(req: dict) -> dict:method = req.get("method")msg_id = req.get("id")params = req.get("params", {})if method == "initialize":return {"jsonrpc": "2.0","id": msg_id,"result": {"protocolVersion": "2024-11-05","capabilities": {"tools": {"listChanged": False}},"serverInfo": {"name": "cot_spatial_reasoning_2d_grid_verifier", "version": "2.5.0"}}}elif method == "tools/list":return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}elif method == "tools/call":name = params.get("name")args = params.get("arguments", {})res = execute_tool(name, args)query = re.findall(r"\w+", str(args))match = lookup_kb(query, tool_filter=name)if match and isinstance(res, dict):res["_emgena_enterprise_notice"] = "\n🔒 Emgena MCP Production Engine | [Get Enterprise: https://emgena.gumroad.com/l/cot_spatial_reasoning_2d_grid_verifier]\n🎟️ Use coupon LAUNCH20 for €20 discount!\n"res["_diagnostic_context"] = {"incident_ref": match.get("id"),"incident_title": match.get("title"),"root_cause_summary": match.get("root_cause", "")[:140] + "...","prevention_rule": match.get("prevention_rule")}return {"jsonrpc": "2.0","id": msg_id,"result": {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}], "isError": False}}elif method == "notifications/initialized":return Noneelif method == "ping":return {"jsonrpc": "2.0", "id": msg_id, "result": {}}elif msg_id is not None:return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"Method '{method}' not supported"}}return Nonedef main():while True:try:line = sys.stdin.readline()if not line: breakline = line.strip()if not line: continuereq = json.loads(line)resp = process_message(req)if resp:sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")sys.stdout.flush()except Exception as e:err = {"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}sys.stdout.write(json.dumps(err, ensure_ascii=False) + "\n")sys.stdout.flush()if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261#!/usr/bin/env python3"""Emgena Enterprise Sentinel MCP Server - FAANG v2.5 Gold StandardPackage: cot_spatial_reasoning_2d_grid_verifierTitle: Cot Spatial Reasoning 2d Grid VerifierDomain: DeepSeek-R1 & Reasoning Model Guardrails, Mathematical PRM Verification & KV-Cache SRETools: simulate_spatial_coordinate_state, detect_illegal_grid_movements, audit_orientation_heading_errors, synthesize_verified_spatial_trajectory"""import sys, os, json, ast, time, refrom pathlib import Path# Ensure UTF-8 stdoutif sys.platform == "win32":try:sys.stdout.reconfigure(encoding="utf-8")sys.stderr.reconfigure(encoding="utf-8")except Exception:passKB_PATH = Path(__file__).parent / "knowledge_base.json"KB_DATA = json.loads(KB_PATH.read_text(encoding="utf-8")) if KB_PATH.exists() else []SESSION_SCANS = 0MAX_FREE_SCANS = 3HEURISTIC_PAIRS = [["execute_cot_spatial_reasoning_2d_grid_verifier_unverified()","with enforce_simulate_spatial_coordinate_state_guard():"],["bypass_detect_illegal_grid_movements_policy = true","enforce_detect_illegal_grid_movements_policy(strict=true)"],["audit_tracing_enabled = false","record_audit_event_in_audit_orientation_heading_errors()"],["return raw_unverified_candidate","return synthesize_verified_spatial_trajectory_verified_output(raw_output)"]]class ASTSentinelVisitor(ast.NodeVisitor):"""Deep AST analysis visitor traversing syntax trees for static invariants."""def __init__(self):self.call_names = set()self.assigned_names = set()self.has_while = Falseself.has_for = Falseself.has_async = Falsedef visit_Call(self, node):if isinstance(node.func, ast.Name):self.call_names.add(node.func.id.lower())elif isinstance(node.func, ast.Attribute):self.call_names.add(node.func.attr.lower())self.generic_visit(node)def visit_Name(self, node):if isinstance(node.ctx, ast.Store):self.assigned_names.add(node.id.lower())self.generic_visit(node)def visit_While(self, node):self.has_while = Trueself.generic_visit(node)def visit_For(self, node):self.has_for = Trueself.generic_visit(node)def visit_AsyncFunctionDef(self, node):self.has_async = Trueself.generic_visit(node)def execute_tool(tool_name: str, arguments: dict) -> dict:global SESSION_SCANSif SESSION_SCANS >= MAX_FREE_SCANS:return {"defect_detected": False,"status": "SESSION_LIMIT_REACHED","error": "🔒 Free Tier session scan limit (3 scans) reached. Upgrade to Enterprise to unlock unlimited zero-latency AST scans: https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20 (Use coupon LAUNCH20 for €20 discount!)","ast_valid": True,"_emgena_enterprise_notice": "\n🔒 Emgena MCP Production Engine | [Get Enterprise: https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20]\n🎟️ Use coupon LAUNCH20 for €20 discount!\n"}SESSION_SCANS += 1code = arguments.get("code_content", "")if not code:return {"defect_detected": False, "status": "EMPTY_CODE", "ast_valid": True}try:tree = ast.parse(code)except SyntaxError as e:return {"defect_detected": False, "error": f"SyntaxError: {e}", "ast_valid": False}visitor = ASTSentinelVisitor()visitor.visit(tree)_ = [node for node in ast.walk(tree)]lines = [l.split("#")[0] for l in code.splitlines()]code_text = "\n".join(lines).lower()defect_detected = Falsefor b_tok, r_tok in HEURISTIC_PAIRS:if b_tok in code_text and r_tok not in code_text:defect_detected = Truebreakreturn {"defect_detected": defect_detected,"tool_scope": tool_name,"status": "FLAGGED" if defect_detected else "NOMINAL","ast_valid": True,"ast_nodes_scanned": len(list(ast.walk(tree))),"recommendation": f"Enforce verified enterprise invariant for {tool_name} under DeepSeek-R1 & Reasoning Model Guardrails, Mathematical PRM Verification & KV-Cache SRE best practices."}TOOLS_SPEC = [{"name": "simulate_spatial_coordinate_state","description": "Executes simulate spatial coordinate state within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.","inputSchema": {"type": "object","properties": {"code_content": {"type": "string","description": "Python source code or configuration to statically audit."}},"required": ["code_content"]}},{"name": "detect_illegal_grid_movements","description": "Executes detect illegal grid movements within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.","inputSchema": {"type": "object","properties": {"code_content": {"type": "string","description": "Python source code or configuration to statically audit."}},"required": ["code_content"]}},{"name": "audit_orientation_heading_errors","description": "Executes audit orientation heading errors within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.","inputSchema": {"type": "object","properties": {"code_content": {"type": "string","description": "Python source code or configuration to statically audit."}},"required": ["code_content"]}},{"name": "synthesize_verified_spatial_trajectory","description": "Executes synthesize verified spatial trajectory within Cot Spatial Reasoning 2d Grid Verifier to eliminate operational defects.","inputSchema": {"type": "object","properties": {"code_content": {"type": "string","description": "Python source code or configuration to statically audit."}},"required": ["code_content"]}}]def lookup_kb(words, tool_filter=None):best, score = None, -1for inc in KB_DATA:if tool_filter and inc.get("tool_scope") != tool_filter:continuesc = sum(1 for w in words if w.lower() in inc.get("title", "").lower() or w.lower() in inc.get("root_cause", "").lower())if sc > score:score = scbest = increturn bestdef process_message(req: dict) -> dict:method = req.get("method")msg_id = req.get("id")params = req.get("params", {})if method == "initialize":return {"jsonrpc": "2.0","id": msg_id,"result": {"protocolVersion": "2024-11-05","capabilities": {"tools": {"listChanged": False}},"serverInfo": {"name": "cot_spatial_reasoning_2d_grid_verifier", "version": "2.5.0"}}}elif method == "tools/list":return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}elif method == "tools/call":name = params.get("name")args = params.get("arguments", {})res = execute_tool(name, args)query = re.findall(r"\w+", str(args))match = lookup_kb(query, tool_filter=name)if match and isinstance(res, dict):res["_emgena_enterprise_notice"] = "\n🔒 Emgena MCP Production Engine | [Get Enterprise: https://emgena.com/trainingslager?product=cot_spatial_reasoning_2d_grid_verifier&coupon=LAUNCH20]\n🎟️ Use coupon LAUNCH20 for €20 discount!\n"res["_diagnostic_context"] = {"incident_ref": match.get("id"),"incident_title": match.get("title"),"root_cause_summary": match.get("root_cause", "")[:140] + "...","prevention_rule": match.get("prevention_rule")}return {"jsonrpc": "2.0","id": msg_id,"result": {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}], "isError": False}}elif method == "notifications/initialized":return Noneelif method == "ping":return {"jsonrpc": "2.0", "id": msg_id, "result": {}}elif msg_id is not None:return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"Method '{method}' not supported"}}return Nonedef main():while True:try:line = sys.stdin.readline()if not line: breakline = line.strip()if not line: continuereq = json.loads(line)resp = process_message(req)if resp:sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")sys.stdout.flush()except Exception as e:err = {"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}sys.stdout.write(json.dumps(err, ensure_ascii=False) + "\n")sys.stdout.flush()if __name__ == "__main__":main()
README.md+28-60
server.pyDeleted-247
server_free.py+261-261