Datasets:
Download server_free.py from emgena/git_diff_chunk_window_optimizer_mcp_teaser: direct link, hf CLI and curl.
- Browser
- Download file 17.8 kB
-
https://huggingface.co/datasets/emgena/git_diff_chunk_window_optimizer_mcp_teaser/resolve/main/server_free.py
- Command line
-
hf download hf://datasets/emgena/git_diff_chunk_window_optimizer_mcp_teaser/server_free.py
-
curl -L -o server_free.py https://huggingface.co/datasets/emgena/git_diff_chunk_window_optimizer_mcp_teaser/resolve/main/server_free.py
17.8 kB
| #!/usr/bin/env python3 | |
| """ | |
| EMGENA SENTINEL MCP SERVER - COMMUNITY EVALUATION EDITION (CC-BY-NC-4.0) | |
| Package: git_diff_chunk_window_optimizer_mcp | |
| Title: Git Diff Chunk Window Optimizer Mcp | |
| Upgrade to Commercial Pro (Unlimited AST Scans + CI/CD SARIF Gate + B2B VAT Invoice): | |
| https://emgena.com/trainingslager?product=git_diff_chunk_window_optimizer_mcp&coupon=LAUNCH20 | |
| """ | |
| import sys, os, json, ast, time, re | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Tuple | |
| if sys.platform == "win32": | |
| try: | |
| sys.stdout.reconfigure(encoding="utf-8") | |
| sys.stderr.reconfigure(encoding="utf-8") | |
| except Exception: | |
| pass | |
| SESSION_SCANS = 0 | |
| MAX_FREE_SCANS = 5 | |
| UPGRADE_URL = "https://emgena.com/trainingslager?product=git_diff_chunk_window_optimizer_mcp&coupon=LAUNCH20" | |
| import math as _math | |
| SAFE_VALUE_MARKERS = ( | |
| "redacted", "placeholder", "example", "changeme", "your_", "dummy", "mock", | |
| "***", "xxxx", "<", "alias/", "vault:", "kms:", "secret_ref", "env:", | |
| "os.environ", "getenv", "test_", "rfc2606", "rfc5737", | |
| ) | |
| def _shannon_entropy(data: str) -> float: | |
| if not data: | |
| return 0.0 | |
| freq = {} | |
| for ch in data: | |
| freq[ch] = freq.get(ch, 0) + 1 | |
| length = len(data) | |
| return -sum((cnt / length) * _math.log2(cnt / length) for cnt in freq.values()) | |
| def _mask_preview(val: str) -> str: | |
| s = str(val).replace("\n", " ").strip() | |
| if len(s) <= 8: | |
| return "****" | |
| return s[:4] + "****" + s[-4:] | |
| def _call_name(node: ast.Call) -> str: | |
| if isinstance(node.func, ast.Name): | |
| return node.func.id.lower() | |
| if isinstance(node.func, ast.Attribute): | |
| return node.func.attr.lower() | |
| return "" | |
| def _full_attr_name(node: ast.AST) -> str: | |
| parts = [] | |
| cur = node | |
| while isinstance(cur, ast.Attribute): | |
| parts.append(cur.attr.lower()) | |
| cur = cur.value | |
| if isinstance(cur, ast.Name): | |
| parts.append(cur.id.lower()) | |
| return ".".join(reversed(parts)) | |
| def _has_kw(node: ast.Call, name: str) -> bool: | |
| return any(kw.arg and kw.arg.lower() == name.lower() for kw in node.keywords) | |
| PII_FIELDS = ("ssn", "iban", "credit_card", "card_number", "cvv", "patient_id", "tax_id", "passport") | |
| DOMAIN_REGEX_RULES = [ | |
| ("EMGENA-AI-001", "CRITICAL", "CWE-74", "Prompt injection / instruction override delimiter pattern detected", | |
| re.compile(r"ignore\s+(?:all\s+)?previous\s+instructions|system\s+prompt\s+override|<admin_mode>", re.IGNORECASE)), | |
| ("EMGENA-AI-002", "HIGH", "CWE-532", "Sensitive PII identifier passed into unredacted logging/prompt buffer", | |
| re.compile(r"\b(?:iban|credit_card|cvv|ssn|patient_name|birth_date)\b.*(?:logger\.|print\()")), | |
| ] | |
| class DomainASTVisitor(ast.NodeVisitor): | |
| """Inspects LLM tool-call safety, prompt interpolation, unguarded JSON parsing, recursion/token limits, and PII logs.""" | |
| def __init__(self, pro_mode: bool = True): | |
| self.pro_mode = pro_mode | |
| self.func_stack = [] | |
| self.findings = [] | |
| def visit_FunctionDef(self, node): | |
| self.func_stack.append(node.name) | |
| self.generic_visit(node) | |
| self.func_stack.pop() | |
| def visit_Assign(self, node): | |
| line = getattr(node, "lineno", 1) | |
| for t in node.targets: | |
| tname = t.id.lower() if isinstance(t, ast.Name) else "" | |
| if any(k in tname for k in ("prompt", "system_msg", "instruction")) and isinstance(node.value, ast.JoinedStr): | |
| self.findings.append({ | |
| "rule_id": "EMGENA-AI-AST-101", "severity": "HIGH", "cwe": "CWE-74", "line": line, | |
| "message": f"Untrusted f-string interpolation directly into LLM prompt variable '{tname}'.", | |
| "preview": f"{tname} = f'...{{...}}'", | |
| "remediation": "Separate system role from sanitized user content and wrap untrusted data in XML delimiters." | |
| }) | |
| self.generic_visit(node) | |
| def visit_Call(self, node): | |
| full = _full_attr_name(node.func) | |
| fname = _call_name(node) | |
| line = getattr(node, "lineno", 1) | |
| if self.func_stack and fname == self.func_stack[-1].lower(): | |
| # Check if depth/iteration limit passed | |
| if not (_has_kw(node, "depth") or _has_kw(node, "max_steps") or len(node.args) >= 2): | |
| self.findings.append({ | |
| "rule_id": "EMGENA-AI-AST-201", "severity": "HIGH", "cwe": "CWE-674", "line": line, | |
| "message": f"Unbounded recursive agent call '{fname}()' without depth/iteration ceiling.", | |
| "preview": f"def {fname}(): ... {fname}()", | |
| "remediation": "Pass explicit depth / max_iterations ceiling and terminate cleanly." | |
| }) | |
| if any(k in full for k in ("completions.create", "messages.create", "chat.completions")): | |
| if not (_has_kw(node, "max_tokens") or _has_kw(node, "max_completion_tokens")): | |
| self.findings.append({ | |
| "rule_id": "EMGENA-AI-AST-202", "severity": "HIGH", "cwe": "CWE-400", "line": line, | |
| "message": f"LLM inference call '{full}()' without max_tokens budget cap.", | |
| "preview": f"{full}(...)", | |
| "remediation": "Always enforce max_tokens and request timeout to prevent thinking-loop token burn." | |
| }) | |
| if any(k in full for k in ("logger.info", "logger.debug", "print")): | |
| for arg in node.args: | |
| dump = ast.dump(arg).lower() | |
| if any(p in dump for p in PII_FIELDS): | |
| self.findings.append({ | |
| "rule_id": "EMGENA-AI-AST-301", "severity": "CRITICAL", "cwe": "CWE-359", "line": line, | |
| "message": f"Potential DSGVO/HIPAA PII field emitted via '{full}()'.", | |
| "preview": f"{full}(<PII>)", | |
| "remediation": "Scrub or tokenize PII fields before telemetry, logging, or LLM prompt serialization." | |
| }) | |
| if fname in ("eval", "exec") and isinstance(node.func, ast.Name): | |
| self.findings.append({ | |
| "rule_id": "EMGENA-AI-AST-401", "severity": "CRITICAL", "cwe": "CWE-94", "line": line, | |
| "message": f"Agent generated unsafe '{fname}()' call.", | |
| "preview": f"{fname}(...)", | |
| "remediation": "Never evaluate untrusted model strings with eval/exec." | |
| }) | |
| self.generic_visit(node) | |
| SCAN_EXTENSIONS = {".py", ".js", ".ts", ".jsx", ".tsx", ".env", ".json", ".yaml", ".yml", ".sh", ".toml", ".tf", ".ini", ".sql"} | |
| SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "mlx_data"} | |
| def run_domain_ast_scan(code: str, pro_mode: bool = True) -> list: | |
| findings = [] | |
| if not code or not code.strip(): | |
| return findings | |
| rules = DOMAIN_REGEX_RULES if pro_mode else DOMAIN_REGEX_RULES[:4] | |
| for lineno, raw_line in enumerate(code.splitlines(), 1): | |
| code_no_comment = raw_line.split("#")[0] | |
| low = code_no_comment.lower() | |
| if any(m in low for m in ("redacted", "placeholder", "example_only", "safe_sanitized", "***")): | |
| continue | |
| for rule_id, sev, cwe, desc, pat in rules: | |
| m = pat.search(code_no_comment) | |
| if m: | |
| findings.append({ | |
| "rule_id": rule_id, | |
| "severity": sev, | |
| "cwe": cwe, | |
| "line": lineno, | |
| "message": desc, | |
| "preview": _mask_preview(m.group(0)), | |
| "remediation": "Remediate detected policy violation before execution or commit." | |
| }) | |
| try: | |
| tree = ast.parse(code) | |
| visitor = DomainASTVisitor(pro_mode=pro_mode) | |
| visitor.visit(tree) | |
| findings.extend(visitor.findings) | |
| except SyntaxError as e: | |
| findings.append({ | |
| "rule_id": "EMGENA-SYNTAX-000", | |
| "severity": "CRITICAL", | |
| "cwe": "CWE-20", | |
| "line": getattr(e, "lineno", 1) or 1, | |
| "message": f"Python AST SyntaxError: {e.msg}", | |
| "preview": str(e.text or "").strip()[:60], | |
| "remediation": "Fix Python syntax before deploying or loading into MCP context." | |
| }) | |
| seen = set() | |
| unique = [] | |
| for f in findings: | |
| key = (f["rule_id"], f["line"]) | |
| if key not in seen: | |
| seen.add(key) | |
| unique.append(f) | |
| return unique | |
| def scan_directory_or_file(target_path: str) -> dict: | |
| p = Path(target_path) | |
| files = [p] if p.is_file() else [ | |
| f for f in p.rglob("*") | |
| if f.is_file() and (f.suffix.lower() in SCAN_EXTENSIONS or f.name.startswith(".env")) | |
| and not any(sd in f.parts for sd in SKIP_DIRS) | |
| and f.name not in ("server.py", "server_free.py") | |
| ] | |
| all_results = [] | |
| for fp in files: | |
| try: | |
| txt = fp.read_text(encoding="utf-8", errors="ignore") | |
| except Exception: | |
| continue | |
| if len(txt) > 512 * 1024: | |
| continue | |
| hits = run_domain_ast_scan(txt, pro_mode=True) | |
| for h in hits: | |
| h["file"] = str(fp) | |
| all_results.append(h) | |
| return {"files_scanned": len(files), "total_findings": len(all_results), "findings": all_results} | |
| def build_sarif(scan_res: dict, pkg_id: str) -> dict: | |
| runs_results = [] | |
| for f in scan_res["findings"]: | |
| runs_results.append({ | |
| "ruleId": f["rule_id"], | |
| "level": "error" if f["severity"] == "CRITICAL" else "warning", | |
| "message": {"text": f"{f['message']} ({f['preview']}) -> {f['remediation']}"}, | |
| "locations": [{ | |
| "physicalLocation": { | |
| "artifactLocation": {"uri": f.get("file", "unknown")}, | |
| "region": {"startLine": int(f.get("line", 1))} | |
| } | |
| }] | |
| }) | |
| return { | |
| "version": "2.1.0", | |
| "$schema": "https://json.schemastore.org/sarif-2.1.0.json", | |
| "runs": [{ | |
| "tool": {"driver": {"name": f"EMGENA-{pkg_id}", "version": "3.0.0"}}, | |
| "results": runs_results | |
| }] | |
| } | |
| def _legacy_package_check(code: str, code_text: str, tool_name: str) -> bool: | |
| return False | |
| def execute_tool(tool_name: str, arguments: dict) -> dict: | |
| global SESSION_SCANS | |
| if SESSION_SCANS >= MAX_FREE_SCANS: | |
| return { | |
| "package": "git_diff_chunk_window_optimizer_mcp", | |
| "defect_detected": False, | |
| "is_safe": False, | |
| "status": "COMMUNITY_LIMIT_REACHED", | |
| "error": f"Community Edition limit ({MAX_FREE_SCANS} scans/session) reached. Unlock Commercial Pro (code LAUNCH20): {UPGRADE_URL}", | |
| "_emgena_commercial_pro": {"upgrade_url": UPGRADE_URL, "coupon": "LAUNCH20"} | |
| } | |
| SESSION_SCANS += 1 | |
| if not isinstance(arguments, dict): | |
| arguments = {} | |
| code = (arguments.get("code_content") or arguments.get("code") or arguments.get("code_snippet") or arguments.get("raw_chunk_text") or arguments.get("chunk_text") or arguments.get("flawed_code") or arguments.get("payload") or arguments.get("sql") or arguments.get("prompt") or arguments.get("source") or "") | |
| if not isinstance(code, str): | |
| code = json.dumps(code, ensure_ascii=False) | |
| if not code.strip(): | |
| return {"package": "git_diff_chunk_window_optimizer_mcp", "defect_detected": False, "is_safe": True, "status": "EMPTY_CODE", "findings": []} | |
| ast_valid = True | |
| try: | |
| ast.parse(code) | |
| except SyntaxError: | |
| ast_valid = False | |
| lines = [l.split("#")[0] for l in code.splitlines()] | |
| code_text = "\n".join(lines).lower() | |
| real_findings = run_domain_ast_scan(code, pro_mode=False) | |
| legacy_hit = _legacy_package_check(code, code_text, tool_name) if ast_valid else False | |
| defect_detected = bool(real_findings) or legacy_hit or (not ast_valid) | |
| return { | |
| "package": "git_diff_chunk_window_optimizer_mcp", | |
| "tool": tool_name, | |
| "edition": "COMMUNITY_EVALUATION (CC-BY-NC-4.0)", | |
| "status": "VIOLATION_DETECTED" if defect_detected else "PASS_VALIDATED", | |
| "defect_detected": defect_detected, | |
| "is_safe": not defect_detected, | |
| "scans_remaining": max(0, MAX_FREE_SCANS - SESSION_SCANS), | |
| "findings": real_findings, | |
| "_emgena_pro_notice": f"Commercial deployment or CI/CD --sarif requires Commercial License -> {UPGRADE_URL}" | |
| } | |
| TOOLS_SPEC = [ | |
| { | |
| "name": "parse_ast_git_diff", | |
| "description": "Deconstructs giant multi-file git diffs into semantic class- and function-level chunks.", | |
| "inputSchema": { | |
| "type": "object", | |
| "properties": { | |
| "code_content": { | |
| "type": "string" | |
| } | |
| }, | |
| "required": [ | |
| "code_content" | |
| ] | |
| } | |
| }, | |
| { | |
| "name": "prioritize_modified_signatures", | |
| "description": "Presents function signature modifications first, keeping implementation details on-demand.", | |
| "inputSchema": { | |
| "type": "object", | |
| "properties": { | |
| "code_content": { | |
| "type": "string" | |
| } | |
| }, | |
| "required": [ | |
| "code_content" | |
| ] | |
| } | |
| }, | |
| { | |
| "name": "filter_lockfile_noise", | |
| "description": "Automatically filters out noisy autogenerated changes in package-lock, poetry, or pnpm.", | |
| "inputSchema": { | |
| "type": "object", | |
| "properties": { | |
| "code_content": { | |
| "type": "string" | |
| } | |
| }, | |
| "required": [ | |
| "code_content" | |
| ] | |
| } | |
| }, | |
| { | |
| "name": "slice_diff_by_dependency_order", | |
| "description": "Orders diff slices topologically so coding agent sees core changes before call sites.", | |
| "inputSchema": { | |
| "type": "object", | |
| "properties": { | |
| "code_content": { | |
| "type": "string" | |
| } | |
| }, | |
| "required": [ | |
| "code_content" | |
| ] | |
| } | |
| }, | |
| { | |
| "name": "estimate_diff_context_overhead", | |
| "description": "Calculates token overhead of entire diff and recommends optimal chunk window.", | |
| "inputSchema": { | |
| "type": "object", | |
| "properties": { | |
| "code_content": { | |
| "type": "string" | |
| } | |
| }, | |
| "required": [ | |
| "code_content" | |
| ] | |
| } | |
| }, | |
| { | |
| "name": "collapse_unmodified_context_lines", | |
| "description": "Collapses 50-line unchanged context gutters into 3-line structural cues.", | |
| "inputSchema": { | |
| "type": "object", | |
| "properties": { | |
| "code_content": { | |
| "type": "string" | |
| } | |
| }, | |
| "required": [ | |
| "code_content" | |
| ] | |
| } | |
| }, | |
| { | |
| "name": "generate_compact_diff_summary", | |
| "description": "Generates a 10-line executive change overview before presenting code chunks.", | |
| "inputSchema": { | |
| "type": "object", | |
| "properties": { | |
| "code_content": { | |
| "type": "string" | |
| } | |
| }, | |
| "required": [ | |
| "code_content" | |
| ] | |
| } | |
| }, | |
| { | |
| "name": "export_optimized_diff_chunks", | |
| "description": "Exports sequenced array of prompt-ready diff chunks for iterative review.", | |
| "inputSchema": { | |
| "type": "object", | |
| "properties": { | |
| "code_content": { | |
| "type": "string" | |
| } | |
| }, | |
| "required": [ | |
| "code_content" | |
| ] | |
| } | |
| } | |
| ] | |
| TOOLS = TOOLS_SPEC | |
| def process_message(message: dict) -> dict: | |
| msg_id = message.get("id") | |
| method = message.get("method") | |
| params = message.get("params", {}) or {} | |
| if method == "initialize": | |
| return { | |
| "jsonrpc": "2.0", "id": msg_id, | |
| "result": { | |
| "protocolVersion": "2024-11-05", | |
| "capabilities": {"tools": {"listChanged": False}}, | |
| "serverInfo": {"name": "git_diff_chunk_window_optimizer_mcp_community", "version": "3.0.0-free"} | |
| } | |
| } | |
| elif method == "notifications/initialized": | |
| return None | |
| elif method == "tools/list": | |
| return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}} | |
| elif method == "tools/call": | |
| tname = params.get("name", "") | |
| args = params.get("arguments", {}) | |
| tool_res = execute_tool(tname, args) | |
| return { | |
| "jsonrpc": "2.0", "id": msg_id, | |
| "result": { | |
| "content": [{"type": "text", "text": json.dumps(tool_res, indent=2, ensure_ascii=False)}], | |
| "isError": False | |
| } | |
| } | |
| return {"jsonrpc": "2.0", "id": msg_id, "result": {}} | |
| def main(): | |
| if "--scan" in sys.argv: | |
| print(f"CLI --scan & --sarif CI/CD Gate requires Commercial Pro. Unlock with LAUNCH20: {UPGRADE_URL}") | |
| sys.exit(2) | |
| while True: | |
| line = sys.stdin.readline() | |
| if not line: | |
| break | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| req = json.loads(line) | |
| resp = process_message(req) | |
| if resp is not None: | |
| sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n") | |
| sys.stdout.flush() | |
| except Exception as e: | |
| sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}) + "\n") | |
| sys.stdout.flush() | |
| if __name__ == "__main__": | |
| main() | |