emgena commited on
Commit
5772300
·
verified ·
1 Parent(s): ef79ea9

Publish Factory v3.0 Open-Core teaser

Browse files
.cursor_mcp_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mcpServers": {
3
+ "ai_generated_sql_migration_lock_guard": {
4
+ "command": "python",
5
+ "args": [
6
+ "D:\\Antigravit projekte\\Rechner vermieten an ki\\data\\packages\\ai_generated_sql_migration_lock_guard\\server.py"
7
+ ],
8
+ "env": {
9
+ "PYTHONUNBUFFERED": "1"
10
+ }
11
+ }
12
+ }
13
+ }
README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ tags:
4
+ - mcp
5
+ - cursor
6
+ - claude-desktop
7
+ - ast-guard
8
+ - security
9
+ ---
10
+
11
+ # Ai Generated Sql Migration Lock Guard (Open-Core Community Teaser)
12
+
13
+ > **Dual-Licensing Notice:** This free Hugging Face teaser (server_free.py, max 5 scans, & 50-sample rain.parquet) is licensed under **CC-BY-NC-4.0** (non-commercial research & local evaluation only).
14
+ > Commercial use, CI/CD SARIF integration (--scan --sarif --fail-on-critical), and the full 500-sample AST-mutated corpus + 30-incident knowledge_base.json require a commercial license.
15
+
16
+ 👉 **[Upgrade to Pro (20% Off with code LAUNCH20)](https://emgena.com/trainingslager?product=ai_generated_sql_migration_lock_guard&coupon=LAUNCH20)**
claude_desktop_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mcpServers": {
3
+ "ai_generated_sql_migration_lock_guard": {
4
+ "command": "python",
5
+ "args": [
6
+ "D:\\Antigravit projekte\\Rechner vermieten an ki\\data\\packages\\ai_generated_sql_migration_lock_guard\\server.py"
7
+ ],
8
+ "env": {
9
+ "PYTHONUNBUFFERED": "1"
10
+ }
11
+ }
12
+ }
13
+ }
server_free.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ EMGENA SENTINEL MCP SERVER - COMMUNITY EVALUATION EDITION (CC-BY-NC-4.0)
4
+ Package: ai_generated_sql_migration_lock_guard
5
+ Title: AI-Generated SQL & Zero-Downtime Migration Lock Guard MCP
6
+ Upgrade to Commercial Pro (Unlimited AST Scans + CI/CD SARIF Gate + B2B VAT Invoice):
7
+ https://emgena.com/trainingslager?product=ai_generated_sql_migration_lock_guard&coupon=LAUNCH20
8
+ """
9
+
10
+ import sys, os, json, ast, time, re
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Tuple
13
+
14
+ if sys.platform == "win32":
15
+ try:
16
+ sys.stdout.reconfigure(encoding="utf-8")
17
+ sys.stderr.reconfigure(encoding="utf-8")
18
+ except Exception:
19
+ pass
20
+
21
+ SESSION_SCANS = 0
22
+ MAX_FREE_SCANS = 5
23
+ UPGRADE_URL = "https://emgena.com/trainingslager?product=ai_generated_sql_migration_lock_guard&coupon=LAUNCH20"
24
+
25
+
26
+ import math as _math
27
+
28
+ SAFE_VALUE_MARKERS = (
29
+ "redacted", "placeholder", "example", "changeme", "your_", "dummy", "mock",
30
+ "***", "xxxx", "<", "alias/", "vault:", "kms:", "secret_ref", "env:",
31
+ "os.environ", "getenv", "test_", "rfc2606", "rfc5737",
32
+ )
33
+
34
+ def _shannon_entropy(data: str) -> float:
35
+ if not data:
36
+ return 0.0
37
+ freq = {}
38
+ for ch in data:
39
+ freq[ch] = freq.get(ch, 0) + 1
40
+ length = len(data)
41
+ return -sum((cnt / length) * _math.log2(cnt / length) for cnt in freq.values())
42
+
43
+ def _mask_preview(val: str) -> str:
44
+ s = str(val).replace("\n", " ").strip()
45
+ if len(s) <= 8:
46
+ return "****"
47
+ return s[:4] + "****" + s[-4:]
48
+
49
+ def _call_name(node: ast.Call) -> str:
50
+ if isinstance(node.func, ast.Name):
51
+ return node.func.id.lower()
52
+ if isinstance(node.func, ast.Attribute):
53
+ return node.func.attr.lower()
54
+ return ""
55
+
56
+ def _full_attr_name(node: ast.AST) -> str:
57
+ parts = []
58
+ cur = node
59
+ while isinstance(cur, ast.Attribute):
60
+ parts.append(cur.attr.lower())
61
+ cur = cur.value
62
+ if isinstance(cur, ast.Name):
63
+ parts.append(cur.id.lower())
64
+ return ".".join(reversed(parts))
65
+
66
+ def _has_kw(node: ast.Call, name: str) -> bool:
67
+ return any(kw.arg and kw.arg.lower() == name.lower() for kw in node.keywords)
68
+
69
+
70
+ DOMAIN_REGEX_RULES = [
71
+ ("EMGENA-SQL-001", "CRITICAL", "CWE-89", "Destructive DDL/DML DROP TABLE / DROP SCHEMA / TRUNCATE detected",
72
+ re.compile(r"\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\s+TABLE)\b", re.IGNORECASE)),
73
+ ("EMGENA-SQL-002", "CRITICAL", "CWE-89", "Unbounded DELETE FROM without WHERE clause",
74
+ re.compile(r"\bDELETE\s+FROM\s+[A-Za-z0-9_.\"`]+\s*(?:;|['\"]|$)", re.IGNORECASE)),
75
+ ("EMGENA-SQL-003", "HIGH", "CWE-502", "Unsafe YAML load() without SafeLoader",
76
+ re.compile(r"\byaml\.load\s*\([^)]*\)(?!.*SafeLoader)")),
77
+ ("EMGENA-SQL-004", "CRITICAL", "CWE-502", "Untrusted pickle.loads() deserialization",
78
+ re.compile(r"\bpickle\.loads?\s*\(")),
79
+ ]
80
+
81
+ class DomainASTVisitor(ast.NodeVisitor):
82
+ """Inspects SQL execution, f-string interpolation, destructive DDL, and ORM/serialization calls."""
83
+ def __init__(self, pro_mode: bool = True):
84
+ self.pro_mode = pro_mode
85
+ self.findings = []
86
+
87
+ def _is_interpolated_sql(self, arg: ast.AST) -> Tuple[bool, str]:
88
+ if isinstance(arg, ast.JoinedStr):
89
+ txt = "".join(v.value for v in arg.values if isinstance(v, ast.Constant) and isinstance(v.value, str))
90
+ if any(kw in txt.upper() for kw in ("SELECT ", "INSERT ", "UPDATE ", "DELETE ", "DROP ", "ALTER ")):
91
+ return True, txt
92
+ elif isinstance(arg, ast.BinOp) and isinstance(arg.op, (ast.Mod, ast.Add)):
93
+ if isinstance(arg.left, ast.Constant) and isinstance(arg.left.value, str):
94
+ if any(kw in arg.left.value.upper() for kw in ("SELECT ", "INSERT ", "UPDATE ", "DELETE ", "DROP ", "ALTER ")):
95
+ return True, arg.left.value
96
+ elif isinstance(arg, ast.Call) and isinstance(arg.func, ast.Attribute) and arg.func.attr == "format":
97
+ if isinstance(arg.func.value, ast.Constant) and isinstance(arg.func.value.value, str):
98
+ if any(kw in arg.func.value.value.upper() for kw in ("SELECT ", "INSERT ", "UPDATE ", "DELETE ", "DROP ")):
99
+ return True, arg.func.value.value
100
+ return False, ""
101
+
102
+ def visit_Call(self, node):
103
+ fname = _call_name(node)
104
+ full = _full_attr_name(node.func)
105
+ line = getattr(node, "lineno", 1)
106
+
107
+ if fname in ("execute", "executemany", "raw", "query", "text", "executescript"):
108
+ for arg in node.args:
109
+ hit, txt = self._is_interpolated_sql(arg)
110
+ if hit:
111
+ self.findings.append({
112
+ "rule_id": "EMGENA-SQL-AST-101", "severity": "CRITICAL", "cwe": "CWE-89", "line": line,
113
+ "message": f"SQL query string constructed dynamically via interpolation in '{fname}()'.",
114
+ "preview": _mask_preview(txt),
115
+ "remediation": "Use bound parameterized queries (e.g., cursor.execute(sql, (param,)) or text(sql).bindparams(...))."
116
+ })
117
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
118
+ up = arg.value.upper()
119
+ if ("DROP TABLE" in up or "TRUNCATE " in up) or ("DELETE FROM" in up and "WHERE" not in up):
120
+ self.findings.append({
121
+ "rule_id": "EMGENA-SQL-AST-102", "severity": "CRITICAL", "cwe": "CWE-284", "line": line,
122
+ "message": f"Destructive SQL DDL/DML executed in '{fname}()' without safeguard.",
123
+ "preview": _mask_preview(arg.value),
124
+ "remediation": "Block destructive DDL/DML or enforce WHERE clause + explicit migration review gate."
125
+ })
126
+
127
+ if full in ("pickle.loads", "pickle.load"):
128
+ self.findings.append({
129
+ "rule_id": "EMGENA-SQL-AST-201", "severity": "CRITICAL", "cwe": "CWE-502", "line": line,
130
+ "message": f"Unsafe binary deserialization via '{full}()'.",
131
+ "preview": f"{full}(...)",
132
+ "remediation": "Replace pickle with signed JSON / MsgPack / Pydantic schema validation."
133
+ })
134
+
135
+ if self.pro_mode and full == "yaml.load":
136
+ has_safe_loader = any(
137
+ isinstance(kw.value, ast.Attribute) and "safe" in kw.value.attr.lower()
138
+ for kw in node.keywords
139
+ )
140
+ if not has_safe_loader:
141
+ self.findings.append({
142
+ "rule_id": "EMGENA-SQL-AST-202", "severity": "HIGH", "cwe": "CWE-502", "line": line,
143
+ "message": "yaml.load() called without SafeLoader.",
144
+ "preview": "yaml.load(...)",
145
+ "remediation": "Use yaml.safe_load() exclusively."
146
+ })
147
+ self.generic_visit(node)
148
+
149
+
150
+ SCAN_EXTENSIONS = {".py", ".js", ".ts", ".jsx", ".tsx", ".env", ".json", ".yaml", ".yml", ".sh", ".toml", ".tf", ".ini", ".sql"}
151
+ SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "mlx_data"}
152
+
153
+ def run_domain_ast_scan(code: str, pro_mode: bool = True) -> list:
154
+ findings = []
155
+ if not code or not code.strip():
156
+ return findings
157
+
158
+ rules = DOMAIN_REGEX_RULES if pro_mode else DOMAIN_REGEX_RULES[:4]
159
+ for lineno, raw_line in enumerate(code.splitlines(), 1):
160
+ code_no_comment = raw_line.split("#")[0]
161
+ low = code_no_comment.lower()
162
+ if any(m in low for m in ("redacted", "placeholder", "example_only", "safe_sanitized", "***", "'except':", '"except":', "deny_cidr", "block_cidr", "block_privileged")):
163
+ continue
164
+ for rule_id, sev, cwe, desc, pat in rules:
165
+ m = pat.search(code_no_comment)
166
+ if m:
167
+ findings.append({
168
+ "rule_id": rule_id,
169
+ "severity": sev,
170
+ "cwe": cwe,
171
+ "line": lineno,
172
+ "message": desc,
173
+ "preview": _mask_preview(m.group(0)),
174
+ "remediation": "Remediate detected policy violation before execution or commit."
175
+ })
176
+
177
+ try:
178
+ tree = ast.parse(code)
179
+ visitor = DomainASTVisitor(pro_mode=pro_mode)
180
+ visitor.visit(tree)
181
+ findings.extend(visitor.findings)
182
+ except SyntaxError as e:
183
+ findings.append({
184
+ "rule_id": "EMGENA-SYNTAX-000",
185
+ "severity": "CRITICAL",
186
+ "cwe": "CWE-20",
187
+ "line": getattr(e, "lineno", 1) or 1,
188
+ "message": f"Python AST SyntaxError: {e.msg}",
189
+ "preview": str(e.text or "").strip()[:60],
190
+ "remediation": "Fix Python syntax before deploying or loading into MCP context."
191
+ })
192
+
193
+ seen = set()
194
+ unique = []
195
+ for f in findings:
196
+ key = (f["rule_id"], f["line"])
197
+ if key not in seen:
198
+ seen.add(key)
199
+ unique.append(f)
200
+ return unique
201
+
202
+ def scan_directory_or_file(target_path: str) -> dict:
203
+ p = Path(target_path)
204
+ files = [p] if p.is_file() else [
205
+ f for f in p.rglob("*")
206
+ if f.is_file() and (f.suffix.lower() in SCAN_EXTENSIONS or f.name.startswith(".env"))
207
+ and not any(sd in f.parts for sd in SKIP_DIRS)
208
+ and f.name not in ("server.py", "server_free.py")
209
+ ]
210
+ all_results = []
211
+ for fp in files:
212
+ try:
213
+ txt = fp.read_text(encoding="utf-8", errors="ignore")
214
+ except Exception:
215
+ continue
216
+ if len(txt) > 512 * 1024:
217
+ continue
218
+ hits = run_domain_ast_scan(txt, pro_mode=True)
219
+ for h in hits:
220
+ h["file"] = str(fp)
221
+ all_results.append(h)
222
+ return {"files_scanned": len(files), "total_findings": len(all_results), "findings": all_results}
223
+
224
+ def build_sarif(scan_res: dict, pkg_id: str) -> dict:
225
+ runs_results = []
226
+ for f in scan_res["findings"]:
227
+ runs_results.append({
228
+ "ruleId": f["rule_id"],
229
+ "level": "error" if f["severity"] == "CRITICAL" else "warning",
230
+ "message": {"text": f"{f['message']} ({f['preview']}) -> {f['remediation']}"},
231
+ "locations": [{
232
+ "physicalLocation": {
233
+ "artifactLocation": {"uri": f.get("file", "unknown")},
234
+ "region": {"startLine": int(f.get("line", 1))}
235
+ }
236
+ }]
237
+ })
238
+ return {
239
+ "version": "2.1.0",
240
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
241
+ "runs": [{
242
+ "tool": {"driver": {"name": f"EMGENA-{pkg_id}", "version": "3.0.0"}},
243
+ "results": runs_results
244
+ }]
245
+ }
246
+
247
+
248
+ def _legacy_package_check(code: str, code_text: str, tool_name: str) -> bool:
249
+ return False
250
+
251
+ def execute_tool(tool_name: str, arguments: dict) -> dict:
252
+ global SESSION_SCANS
253
+ if SESSION_SCANS >= MAX_FREE_SCANS:
254
+ return {
255
+ "package": "ai_generated_sql_migration_lock_guard",
256
+ "defect_detected": False,
257
+ "is_safe": False,
258
+ "status": "COMMUNITY_LIMIT_REACHED",
259
+ "error": f"Community Edition limit ({MAX_FREE_SCANS} scans/session) reached. Unlock Commercial Pro (code LAUNCH20): {UPGRADE_URL}",
260
+ "_emgena_commercial_pro": {"upgrade_url": UPGRADE_URL, "coupon": "LAUNCH20"}
261
+ }
262
+ SESSION_SCANS += 1
263
+ if not isinstance(arguments, dict):
264
+ arguments = {}
265
+ 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 "")
266
+ if not isinstance(code, str):
267
+ code = json.dumps(code, ensure_ascii=False)
268
+ if not code.strip():
269
+ return {"package": "ai_generated_sql_migration_lock_guard", "defect_detected": False, "is_safe": True, "status": "EMPTY_CODE", "findings": []}
270
+
271
+ ast_valid = True
272
+ try:
273
+ ast.parse(code)
274
+ except SyntaxError:
275
+ ast_valid = False
276
+
277
+ lines = [l.split("#")[0] for l in code.splitlines()]
278
+ code_text = "\n".join(lines).lower()
279
+ real_findings = run_domain_ast_scan(code, pro_mode=False)
280
+ legacy_hit = _legacy_package_check(code, code_text, tool_name) if ast_valid else False
281
+ defect_detected = bool(real_findings) or legacy_hit or (not ast_valid)
282
+
283
+ return {
284
+ "package": "ai_generated_sql_migration_lock_guard",
285
+ "tool": tool_name,
286
+ "edition": "COMMUNITY_EVALUATION (CC-BY-NC-4.0)",
287
+ "status": "VIOLATION_DETECTED" if defect_detected else "PASS_VALIDATED",
288
+ "defect_detected": defect_detected,
289
+ "is_safe": not defect_detected,
290
+ "scans_remaining": max(0, MAX_FREE_SCANS - SESSION_SCANS),
291
+ "findings": real_findings,
292
+ "_emgena_pro_notice": f"Commercial deployment or CI/CD --sarif requires Commercial License -> {UPGRADE_URL}"
293
+ }
294
+
295
+ TOOLS_SPEC = [
296
+ {
297
+ "name": "audit_blocking_ddl_operations",
298
+ "desc": "Detects CREATE INDEX without CONCURRENTLY, ALTER TABLE ADD COLUMN ... DEFAULT volatile, and full-table rewrites."
299
+ },
300
+ {
301
+ "name": "enforce_lock_and_statement_timeouts",
302
+ "desc": "Ensures migrations set explicit lock_timeout and statement_timeout before acquiring ACCESS EXCLUSIVE locks."
303
+ },
304
+ {
305
+ "name": "detect_destructive_drop_or_truncate",
306
+ "desc": "Blocks unguarded DROP TABLE, DROP COLUMN, and TRUNCATE statements in automated migration scripts."
307
+ },
308
+ {
309
+ "name": "check_not_null_expand_contract",
310
+ "desc": "Flags direct NOT NULL additions on populated tables instead of NOT VALID + VALIDATE CONSTRAINT two-step pattern."
311
+ },
312
+ {
313
+ "name": "audit_alembic_prisma_autogenerate",
314
+ "desc": "Inspects Alembic/Prisma migration files for unintended index drops, enum locks, or unsafe type casts."
315
+ },
316
+ {
317
+ "name": "generate_zero_downtime_migration_plan",
318
+ "desc": "Produces an expand-and-contract migration checklist and safe SQL rewrite."
319
+ }
320
+ ]
321
+ TOOLS = TOOLS_SPEC
322
+
323
+ def process_message(message: dict) -> dict:
324
+ msg_id = message.get("id")
325
+ method = message.get("method")
326
+ params = message.get("params", {}) or {}
327
+ if method == "initialize":
328
+ return {
329
+ "jsonrpc": "2.0", "id": msg_id,
330
+ "result": {
331
+ "protocolVersion": "2024-11-05",
332
+ "capabilities": {"tools": {"listChanged": False}},
333
+ "serverInfo": {"name": "ai_generated_sql_migration_lock_guard_community", "version": "3.0.0-free"}
334
+ }
335
+ }
336
+ elif method == "notifications/initialized":
337
+ return None
338
+ elif method == "tools/list":
339
+ return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
340
+ elif method == "tools/call":
341
+ tname = params.get("name", "")
342
+ args = params.get("arguments", {})
343
+ tool_res = execute_tool(tname, args)
344
+ return {
345
+ "jsonrpc": "2.0", "id": msg_id,
346
+ "result": {
347
+ "content": [{"type": "text", "text": json.dumps(tool_res, indent=2, ensure_ascii=False)}],
348
+ "isError": False
349
+ }
350
+ }
351
+ return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
352
+
353
+ def main():
354
+ if "--scan" in sys.argv:
355
+ print(f"CLI --scan & --sarif CI/CD Gate requires Commercial Pro. Unlock with LAUNCH20: {UPGRADE_URL}")
356
+ sys.exit(2)
357
+ while True:
358
+ line = sys.stdin.readline()
359
+ if not line:
360
+ break
361
+ line = line.strip()
362
+ if not line:
363
+ continue
364
+ try:
365
+ req = json.loads(line)
366
+ resp = process_message(req)
367
+ if resp is not None:
368
+ sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
369
+ sys.stdout.flush()
370
+ except Exception as e:
371
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}) + "\n")
372
+ sys.stdout.flush()
373
+
374
+ if __name__ == "__main__":
375
+ main()
train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4d5caf043a293fd1046714145ffacd2f55e5a8b4829d7547ce38ddcffe5d3fa
3
+ size 21375