emgena commited on
Commit
180b57d
·
verified ·
1 Parent(s): ae7c7ba

Publish Factory v3.0 Open-Core test category teaser

Browse files
.cursor_mcp_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mcpServers": {
3
+ "rag_embedding_model_drift_version_validator": {
4
+ "command": "python",
5
+ "args": [
6
+ "server.py"
7
+ ]
8
+ }
9
+ }
10
+ }
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
+ # RAG Embedding Model Drift & Chunk Boundary Validator MCP (Open-Core Community Teaser)
12
+
13
+ > **Dual-Licensing Notice:** This free Hugging Face teaser (`server_free.py`, max 5 scans, & 50-sample `train.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=rag_embedding_model_drift_version_validator&coupon=LAUNCH20)**
claude_desktop_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mcpServers": {
3
+ "rag_embedding_model_drift_version_validator": {
4
+ "command": "python",
5
+ "args": [
6
+ "server.py"
7
+ ]
8
+ }
9
+ }
10
+ }
server_free.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ EMGENA SENTINEL MCP SERVER - COMMUNITY EVALUATION EDITION (CC-BY-NC-4.0)
4
+ Package: rag_embedding_model_drift_version_validator
5
+ Title: RAG Embedding Model Drift & Chunk Boundary Validator MCP
6
+ Upgrade to Commercial Pro (Unlimited AST Scans + CI/CD SARIF Gate + B2B VAT Invoice):
7
+ https://emgena.com/trainingslager?product=rag_embedding_model_drift_version_validator&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=rag_embedding_model_drift_version_validator&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
+ PII_FIELDS = ("ssn", "iban", "credit_card", "card_number", "cvv", "patient_id", "tax_id", "passport")
71
+
72
+ DOMAIN_REGEX_RULES = [
73
+ ("EMGENA-AI-001", "CRITICAL", "CWE-74", "Prompt injection / instruction override delimiter pattern detected",
74
+ re.compile(r"ignore\s+(?:all\s+)?previous\s+instructions|system\s+prompt\s+override|<admin_mode>", re.IGNORECASE)),
75
+ ("EMGENA-AI-002", "HIGH", "CWE-532", "Sensitive PII identifier passed into unredacted logging/prompt buffer",
76
+ re.compile(r"\b(?:iban|credit_card|cvv|ssn|patient_name|birth_date)\b.*(?:logger\.|print\()")),
77
+ ]
78
+
79
+ class DomainASTVisitor(ast.NodeVisitor):
80
+ """Inspects LLM tool-call safety, prompt interpolation, unguarded JSON parsing, recursion/token limits, and PII logs."""
81
+ def __init__(self, pro_mode: bool = True):
82
+ self.pro_mode = pro_mode
83
+ self.func_stack = []
84
+ self.findings = []
85
+
86
+ def visit_FunctionDef(self, node):
87
+ self.func_stack.append(node.name)
88
+ self.generic_visit(node)
89
+ self.func_stack.pop()
90
+
91
+ def visit_Assign(self, node):
92
+ line = getattr(node, "lineno", 1)
93
+ for t in node.targets:
94
+ tname = t.id.lower() if isinstance(t, ast.Name) else ""
95
+ if any(k in tname for k in ("prompt", "system_msg", "instruction")) and isinstance(node.value, ast.JoinedStr):
96
+ dump = ast.dump(node.value).lower()
97
+ if any(fn in dump for fn in ("sanitize", "escape", "redact", "strip_prompt", "wrap_delimited")):
98
+ continue
99
+ self.findings.append({
100
+ "rule_id": "EMGENA-AI-AST-101", "severity": "HIGH", "cwe": "CWE-74", "line": line,
101
+ "message": f"Untrusted f-string interpolation directly into LLM prompt variable '{tname}'.",
102
+ "preview": f"{tname} = f'...{{...}}'",
103
+ "remediation": "Separate system role from sanitized user content and wrap untrusted data in XML delimiters."
104
+ })
105
+ self.generic_visit(node)
106
+
107
+ def visit_Call(self, node):
108
+ full = _full_attr_name(node.func)
109
+ fname = _call_name(node)
110
+ line = getattr(node, "lineno", 1)
111
+
112
+ if self.func_stack and fname == self.func_stack[-1].lower():
113
+ # Check if depth/iteration limit passed
114
+ if not (_has_kw(node, "depth") or _has_kw(node, "max_steps") or len(node.args) >= 2):
115
+ self.findings.append({
116
+ "rule_id": "EMGENA-AI-AST-201", "severity": "HIGH", "cwe": "CWE-674", "line": line,
117
+ "message": f"Unbounded recursive agent call '{fname}()' without depth/iteration ceiling.",
118
+ "preview": f"def {fname}(): ... {fname}()",
119
+ "remediation": "Pass explicit depth / max_iterations ceiling and terminate cleanly."
120
+ })
121
+
122
+ if any(k in full for k in ("completions.create", "messages.create", "chat.completions")):
123
+ if not (_has_kw(node, "max_tokens") or _has_kw(node, "max_completion_tokens")):
124
+ self.findings.append({
125
+ "rule_id": "EMGENA-AI-AST-202", "severity": "HIGH", "cwe": "CWE-400", "line": line,
126
+ "message": f"LLM inference call '{full}()' without max_tokens budget cap.",
127
+ "preview": f"{full}(...)",
128
+ "remediation": "Always enforce max_tokens and request timeout to prevent thinking-loop token burn."
129
+ })
130
+
131
+ if any(k in full for k in ("logger.info", "logger.debug", "print")):
132
+ for arg in node.args:
133
+ dump = ast.dump(arg).lower()
134
+ if any(p in dump for p in PII_FIELDS):
135
+ self.findings.append({
136
+ "rule_id": "EMGENA-AI-AST-301", "severity": "CRITICAL", "cwe": "CWE-359", "line": line,
137
+ "message": f"Potential DSGVO/HIPAA PII field emitted via '{full}()'.",
138
+ "preview": f"{full}(<PII>)",
139
+ "remediation": "Scrub or tokenize PII fields before telemetry, logging, or LLM prompt serialization."
140
+ })
141
+
142
+ if fname in ("eval", "exec") and isinstance(node.func, ast.Name):
143
+ self.findings.append({
144
+ "rule_id": "EMGENA-AI-AST-401", "severity": "CRITICAL", "cwe": "CWE-94", "line": line,
145
+ "message": f"Agent generated unsafe '{fname}()' call.",
146
+ "preview": f"{fname}(...)",
147
+ "remediation": "Never evaluate untrusted model strings with eval/exec."
148
+ })
149
+ self.generic_visit(node)
150
+
151
+
152
+ SCAN_EXTENSIONS = {".py", ".js", ".ts", ".jsx", ".tsx", ".env", ".json", ".yaml", ".yml", ".sh", ".toml", ".tf", ".ini", ".sql"}
153
+ SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "mlx_data"}
154
+
155
+ def run_domain_ast_scan(code: str, pro_mode: bool = True) -> list:
156
+ findings = []
157
+ if not code or not code.strip():
158
+ return findings
159
+
160
+ rules = DOMAIN_REGEX_RULES if pro_mode else DOMAIN_REGEX_RULES[:4]
161
+ for lineno, raw_line in enumerate(code.splitlines(), 1):
162
+ code_no_comment = raw_line.split("#")[0]
163
+ low = code_no_comment.lower()
164
+ if any(m in low for m in ("redacted", "placeholder", "example_only", "safe_sanitized", "***", "'except':", '"except":', "deny_cidr", "block_cidr", "block_privileged")):
165
+ continue
166
+ for rule_id, sev, cwe, desc, pat in rules:
167
+ m = pat.search(code_no_comment)
168
+ if m:
169
+ findings.append({
170
+ "rule_id": rule_id,
171
+ "severity": sev,
172
+ "cwe": cwe,
173
+ "line": lineno,
174
+ "message": desc,
175
+ "preview": _mask_preview(m.group(0)),
176
+ "remediation": "Remediate detected policy violation before execution or commit."
177
+ })
178
+
179
+ try:
180
+ tree = ast.parse(code)
181
+ visitor = DomainASTVisitor(pro_mode=pro_mode)
182
+ visitor.visit(tree)
183
+ findings.extend(visitor.findings)
184
+ except SyntaxError as e:
185
+ findings.append({
186
+ "rule_id": "EMGENA-SYNTAX-000",
187
+ "severity": "CRITICAL",
188
+ "cwe": "CWE-20",
189
+ "line": getattr(e, "lineno", 1) or 1,
190
+ "message": f"Python AST SyntaxError: {e.msg}",
191
+ "preview": str(e.text or "").strip()[:60],
192
+ "remediation": "Fix Python syntax before deploying or loading into MCP context."
193
+ })
194
+
195
+ seen = set()
196
+ unique = []
197
+ for f in findings:
198
+ key = (f["rule_id"], f["line"])
199
+ if key not in seen:
200
+ seen.add(key)
201
+ unique.append(f)
202
+ return unique
203
+
204
+ def scan_directory_or_file(target_path: str) -> dict:
205
+ p = Path(target_path)
206
+ files = [p] if p.is_file() else [
207
+ f for f in p.rglob("*")
208
+ if f.is_file() and (f.suffix.lower() in SCAN_EXTENSIONS or f.name.startswith(".env"))
209
+ and not any(sd in f.parts for sd in SKIP_DIRS)
210
+ and f.name not in ("server.py", "server_free.py")
211
+ ]
212
+ all_results = []
213
+ for fp in files:
214
+ try:
215
+ txt = fp.read_text(encoding="utf-8", errors="ignore")
216
+ except Exception:
217
+ continue
218
+ if len(txt) > 512 * 1024:
219
+ continue
220
+ hits = run_domain_ast_scan(txt, pro_mode=True)
221
+ for h in hits:
222
+ h["file"] = str(fp)
223
+ all_results.append(h)
224
+ return {"files_scanned": len(files), "total_findings": len(all_results), "findings": all_results}
225
+
226
+ def build_sarif(scan_res: dict, pkg_id: str) -> dict:
227
+ runs_results = []
228
+ for f in scan_res["findings"]:
229
+ runs_results.append({
230
+ "ruleId": f["rule_id"],
231
+ "level": "error" if f["severity"] == "CRITICAL" else "warning",
232
+ "message": {"text": f"{f['message']} ({f['preview']}) -> {f['remediation']}"},
233
+ "locations": [{
234
+ "physicalLocation": {
235
+ "artifactLocation": {"uri": f.get("file", "unknown")},
236
+ "region": {"startLine": int(f.get("line", 1))}
237
+ }
238
+ }]
239
+ })
240
+ return {
241
+ "version": "2.1.0",
242
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
243
+ "runs": [{
244
+ "tool": {"driver": {"name": f"EMGENA-{pkg_id}", "version": "3.0.0"}},
245
+ "results": runs_results
246
+ }]
247
+ }
248
+
249
+
250
+ def _legacy_package_check(code: str, code_text: str, tool_name: str) -> bool:
251
+ return False
252
+
253
+ def execute_tool(tool_name: str, arguments: dict) -> dict:
254
+ global SESSION_SCANS
255
+ if SESSION_SCANS >= MAX_FREE_SCANS:
256
+ return {
257
+ "package": "rag_embedding_model_drift_version_validator",
258
+ "defect_detected": False,
259
+ "is_safe": False,
260
+ "status": "COMMUNITY_LIMIT_REACHED",
261
+ "error": f"Community Edition limit ({MAX_FREE_SCANS} scans/session) reached. Unlock Commercial Pro (code LAUNCH20): {UPGRADE_URL}",
262
+ "_emgena_commercial_pro": {"upgrade_url": UPGRADE_URL, "coupon": "LAUNCH20"}
263
+ }
264
+ SESSION_SCANS += 1
265
+ if not isinstance(arguments, dict):
266
+ arguments = {}
267
+ 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 "")
268
+ if not isinstance(code, str):
269
+ code = json.dumps(code, ensure_ascii=False)
270
+ if not code.strip():
271
+ return {"package": "rag_embedding_model_drift_version_validator", "defect_detected": False, "is_safe": True, "status": "EMPTY_CODE", "findings": []}
272
+
273
+ ast_valid = True
274
+ try:
275
+ ast.parse(code)
276
+ except SyntaxError:
277
+ ast_valid = False
278
+
279
+ lines = [l.split("#")[0] for l in code.splitlines()]
280
+ code_text = "\n".join(lines).lower()
281
+ real_findings = run_domain_ast_scan(code, pro_mode=False)
282
+ legacy_hit = _legacy_package_check(code, code_text, tool_name) if ast_valid else False
283
+ defect_detected = bool(real_findings) or legacy_hit or (not ast_valid)
284
+
285
+ return {
286
+ "package": "rag_embedding_model_drift_version_validator",
287
+ "tool": tool_name,
288
+ "edition": "COMMUNITY_EVALUATION (CC-BY-NC-4.0)",
289
+ "status": "VIOLATION_DETECTED" if defect_detected else "PASS_VALIDATED",
290
+ "defect_detected": defect_detected,
291
+ "is_safe": not defect_detected,
292
+ "scans_remaining": max(0, MAX_FREE_SCANS - SESSION_SCANS),
293
+ "findings": real_findings,
294
+ "_emgena_pro_notice": f"Commercial deployment or CI/CD --sarif requires Commercial License -> {UPGRADE_URL}"
295
+ }
296
+
297
+ TOOLS_SPEC = [
298
+ {
299
+ "name": "scan_rag_embedding_model_drif",
300
+ "description": "AST/SARIF static analyzer for RAG Embedding Model Drift & Chunk Boundary Validator MCP"
301
+ },
302
+ {
303
+ "name": "audit_rag_embedding_model_dri",
304
+ "description": "Deterministic policy & config audit for RAG Embedding Model Drift & Chunk Boundary Validator MCP"
305
+ }
306
+ ]
307
+ TOOLS = TOOLS_SPEC
308
+
309
+ def process_message(message: dict) -> dict:
310
+ msg_id = message.get("id")
311
+ method = message.get("method")
312
+ params = message.get("params", {}) or {}
313
+ if method == "initialize":
314
+ return {
315
+ "jsonrpc": "2.0", "id": msg_id,
316
+ "result": {
317
+ "protocolVersion": "2024-11-05",
318
+ "capabilities": {"tools": {"listChanged": False}},
319
+ "serverInfo": {"name": "rag_embedding_model_drift_version_validator_community", "version": "3.0.0-free"}
320
+ }
321
+ }
322
+ elif method == "notifications/initialized":
323
+ return None
324
+ elif method == "tools/list":
325
+ return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
326
+ elif method == "tools/call":
327
+ tname = params.get("name", "")
328
+ args = params.get("arguments", {})
329
+ tool_res = execute_tool(tname, args)
330
+ return {
331
+ "jsonrpc": "2.0", "id": msg_id,
332
+ "result": {
333
+ "content": [{"type": "text", "text": json.dumps(tool_res, indent=2, ensure_ascii=False)}],
334
+ "isError": False
335
+ }
336
+ }
337
+ return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
338
+
339
+ def main():
340
+ if "--scan" in sys.argv:
341
+ print(f"CLI --scan & --sarif CI/CD Gate requires Commercial Pro. Unlock with LAUNCH20: {UPGRADE_URL}")
342
+ sys.exit(2)
343
+ while True:
344
+ line = sys.stdin.readline()
345
+ if not line:
346
+ break
347
+ line = line.strip()
348
+ if not line:
349
+ continue
350
+ try:
351
+ req = json.loads(line)
352
+ resp = process_message(req)
353
+ if resp is not None:
354
+ sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
355
+ sys.stdout.flush()
356
+ except Exception as e:
357
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}) + "\n")
358
+ sys.stdout.flush()
359
+
360
+ if __name__ == "__main__":
361
+ main()
train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc2c4f187721509a3c9b75af6b2487fcda95c86653ddcce497726436207a303a
3
+ size 21862