File size: 22,086 Bytes
5ae293c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
(function () {
  "use strict";

  const RULES_BY_ID = Object.fromEntries((window.MCP_RULES || []).map((r) => [r.rule_id, r]));
  const VALID_TYPES = new Set(["string", "integer", "number", "boolean", "array", "object", "null"]);
  const STRING_CONSTRAINTS = ["maxLength", "pattern", "format", "enum", "const"];
  const EXEC_PARAMS = new Set(["cmd", "command", "shell", "shell_cmd", "bash", "sh", "powershell", "pwsh", "eval", "exec", "python_code", "code", "script", "cli_command"]);
  const PATH_PARAMS = new Set(["path", "file_path", "filepath", "filename", "file", "dir", "directory", "folder", "target_path", "source_path", "dest_path", "output_path", "input_path"]);
  const URL_PARAMS = new Set(["url", "uri", "endpoint", "webhook", "webhook_url", "callback_url", "target_url", "fetch_url", "href", "link"]);
  const CONFIRM_PARAMS = new Set(["confirm", "confirmed", "acknowledge", "acknowledged", "dry_run", "force", "confirmation"]);
  const TRIVIAL_PATTERNS = new Set([".*", ".+", "^.*$", "^.+$"]);

  const INVISIBLE_SET = new Set([
    0x200b, 0x200c, 0x200d, 0x200e, 0x200f,
    0x202a, 0x202b, 0x202c, 0x202d, 0x202e,
    0x2060, 0x2061, 0x2062, 0x2063, 0x2064,
    0x2066, 0x2067, 0x2068, 0x2069, 0xfeff
  ]);

  const PROMPT_INJECTION_RES = [
    /<\s*(?:IMPORTANT|SYSTEM|INSTRUCTIONS?|OVERRIDE|ADMIN|PROMPT)\s*>/i,
    /\[\s*(?:SYSTEM|IMPORTANT|ADMIN\s+OVERRIDE|OVERRIDE)\s*\]/i,
    /\b(?:ignore|disregard|forget|bypass|override)\s+(?:all\s+)?(?:previous|prior|above|earlier|existing|system)\s+(?:instructions?|prompts?|rules?|directives?|guidelines?)\b/i,
    /\b(?:new|updated)\s+system\s+(?:instruction|prompt|directive)\b/i,
    /\byou\s+must\s+(?:now\s+)?(?:obey|follow)\s+these\s+(?:hidden|secret|new)\s+instructions?\b/i
  ];

  const CREDENTIAL_RES = [
    /(?:~\/|\$HOME\/|%USERPROFILE%[\/\\]|\/home\/[^\/\s]+\/)?\.ssh(?:[\/\\])?(?:id_rsa|id_ed25519|id_ecdsa|authorized_keys|known_hosts|config)?\b/i,
    /(?:\.aws[\/\\]credentials|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN)/i,
    /(?:\/etc\/shadow|\/etc\/passwd)\b/,
    /(?:\.npmrc|\.netrc|\.pypirc|\.kube[\/\\]config|\.docker[\/\\]config\.json)\b/i,
    /(?:~\/|\.\/*|\/)?\.env(?:\.(?:local|prod|production|dev))?\b.*?\b(?:read|load|send|include|cat|dump|exfiltrate|pass|contents?)\b|\b(?:read|load|send|include|cat|dump|exfiltrate|steal)\b.{0,40}(?:~\/|\.\/*|\/)?\.env(?:\.(?:local|prod|production|dev))?\b/i,
    /\b(?:read|steal|exfiltrate|dump|extract|leak|send)\b.{0,45}\b(?:api[_\s-]?keys?|secret[_\s-]?tokens?|private[_\s-]?keys?|credentials?|keychain|browser\s+cookies?|login\s+data)\b/i
  ];

  const SHADOWING_RES = [
    /\b(?:before|prior\s+to|instead\s+of|whenever|after)\s+(?:calling|invoking|using|executing|running)\s+(?:any\s+other\s+tool|(?:the\s+)?[a-zA-Z0-9_.-]+\s+tool|[a-zA-Z0-9]+_[a-zA-Z0-9_]+)\b/i,
    /\b(?:override|intercept|hijack|replace|shadow|re-?route)\s+(?:calls?\s+to\s+|behavior\s+of\s+)?(?:other\s+)?(?:tools?|functions?)\b/i,
    /\balways\s+(?:call|invoke|run)\s+this\s+tool\s+first\b/i,
    /\bdo\s+not\s+(?:call|use|invoke)\s+(?:the\s+)?[a-zA-Z0-9_.-]+\s+tool\b/i
  ];

  const EXFIL_DOMAIN_RE = /https?:\/\/(?:[a-z0-9-]+\.)*(?:webhook\.site|requestbin\.[a-z]+|pipedream\.net|ngrok\.(?:io|app|free)|burpcollaborator\.net|oastify\.com|interact\.sh|pastebin\.com)\b/i;
  const EXFIL_IP_RE = /https?:\/\/\d{1,3}(?:\.\d{1,3}){3}(?::\d+)?(?:\/[^\s'"]*)?/i;
  const EXFIL_CTX_RE = /\b(?:exfiltrate|forward|relay|upload|post|send|transmit|append|embed)\b.{0,70}\b(?:conversation|chat\s+history|entire\s+context|user\s+prompt|system\s+prompt|all\s+messages|secrets?|tokens?|file\s+contents?)\b/i;
  const EXEC_DESC_RE = /\b(?:execute|run|eval(?:uate)?)\s+(?:arbitrary|any|raw|unrestricted)\s+(?:shell|bash|os|system|python|javascript|code|commands?)\b/i;

  const CONCEAL_RES = [
    /\b(?:do\s+not|don'?t|never)\s+(?:mention|tell|inform|reveal|show|disclose|display|notify|alert)\s+(?:this|that|it|anything)?\s*(?:to\s+)?(?:the\s+)?(?:user|human|caller|operator)\b/i,
    /\b(?:hide|conceal|mask|omit)\s+(?:this|the)\s+(?:action|tool\s+call|invocation|output|step|error)\b/i,
    /\bsilently\s+(?:send|read|upload|execute|run|forward|exfiltrate|delete|write)\b/i,
    /\bwithout\s+(?:telling|notifying|informing|alerting|asking)\s+(?:the\s+)?(?:user|human)\b/i,
    /\bpretend\s+(?:that|to\s+the\s+user)\b/i
  ];

  const DESTRUCTIVE_NAME_RE = /(?:^|_)(?:delete|drop|truncate|purge|wipe|destroy|erase|rm|remove_all|transfer_funds|wire_money|format_disk|overwrite)(?:_|$)/i;
  const DESTRUCTIVE_DESC_RE = /\b(?:permanently\s+delete|irreversibly\s+(?:delete|remove|wipe|destroy)|drop\s+table|truncate\s+table|transfer\s+funds|wire\s+money)\b/i;
  const BASE64_RE = /[A-Za-z0-9+/]{24,}={0,2}/g;
  const HEX_RE = /(?:\\x[0-9a-fA-F]{2}){8,}/;
  const DECODE_CMD_RE = /\b(?:base64\s+-d|atob\(|frombase64)\b/i;
  const SSRF_TEXT_RE = /(?:169\.254\.169\.254|127\.0\.0\.1|0\.0\.0\.0|metadata\.google\.internal|\b(?:file|gopher|dict):\/\/)/i;

  function penaltyFor(sev) {
    return { CRITICAL: 25, HIGH: 15, MEDIUM: 7, LOW: 2, INFO: 0 }[sev] || 0;
  }

  function rankFor(sev) {
    return { CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1, INFO: 0 }[sev] || 0;
  }

  function findInvisible(str) {
    const out = [];
    for (const ch of str) {
      const cp = ch.codePointAt(0);
      if (INVISIBLE_SET.has(cp) || (cp >= 0xe0000 && cp <= 0xe007f)) {
        out.push("U+" + cp.toString(16).toUpperCase().padStart(4, "0"));
      }
    }
    return out;
  }

  function stripInvisible(str) {
    let out = "";
    for (const ch of str) {
      const cp = ch.codePointAt(0);
      if (!INVISIBLE_SET.has(cp) && !(cp >= 0xe0000 && cp <= 0xe007f)) {
        out += ch;
      }
    }
    return out;
  }

  function decodeSuspiciousBase64(text) {
    const matches = text.match(BASE64_RE) || [];
    for (const tok of matches) {
      if (tok.length % 4 !== 0) continue;
      try {
        const raw = atob(tok);
        if (raw.length < 16) continue;
        let printable = 0;
        for (let i = 0; i < raw.length; i++) {
          const code = raw.charCodeAt(i);
          if ((code >= 32 && code <= 126) || code === 10 || code === 13 || code === 9) printable++;
        }
        if (printable / raw.length >= 0.85 && /[ :\/()\[\]{};]/.test(raw)) {
          return raw;
        }
      } catch (_) {}
    }
    return null;
  }

  function levenshtein(a, b) {
    const dp = Array.from({ length: a.length + 1 }, (_, i) => [i]);
    for (let j = 1; j <= b.length; j++) dp[0][j] = j;
    for (let i = 1; i <= a.length; i++) {
      for (let j = 1; j <= b.length; j++) {
        const cost = a[i - 1] === b[j - 1] ? 0 : 1;
        dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
      }
    }
    return dp[a.length][b.length];
  }

  function makeFinding(ruleId, toolName, location, message, evidence) {
    const rule = RULES_BY_ID[ruleId] || { title: ruleId, category: "security", severity: "MEDIUM", remediation: "" };
    return {
      rule_id: ruleId,
      title: rule.title,
      category: rule.category,
      severity: rule.severity,
      tool_name: toolName || "<unnamed>",
      location,
      message,
      evidence: String(evidence || "").slice(0, 240),
      remediation: rule.remediation
    };
  }

  function collectTexts(node, loc, out, depth) {
    if (depth > 12 || !node || typeof node !== "object") return;
    for (const key of ["description", "title", "default"]) {
      if (typeof node[key] === "string") out.push([`${loc}.${key}`, node[key]]);
    }
    for (const lkey of ["enum", "examples"]) {
      if (Array.isArray(node[lkey])) {
        node[lkey].forEach((item, idx) => {
          if (typeof item === "string") out.push([`${loc}.${lkey}[${idx}]`, item]);
        });
      }
    }
    for (const mapKey of ["properties", "$defs", "definitions"]) {
      if (node[mapKey] && typeof node[mapKey] === "object" && !Array.isArray(node[mapKey])) {
        for (const [k, v] of Object.entries(node[mapKey])) {
          collectTexts(v, `${loc}.${mapKey}.${k}`, out, depth + 1);
        }
      }
    }
    for (const subKey of ["items", "additionalProperties"]) {
      if (node[subKey] && typeof node[subKey] === "object") {
        collectTexts(node[subKey], `${loc}.${subKey}`, out, depth + 1);
      }
    }
  }

  function scanToolSecurity(tool) {
    const findings = [];
    const seen = new Set();
    const emit = (rid, loc, msg, ev) => {
      const k = `${rid}@@${loc}`;
      if (seen.has(k)) return;
      seen.add(k);
      findings.push(makeFinding(rid, tool.name, loc, msg, ev));
    };

    const segments = [["name", String(tool.name || "")], ["description", String(tool.description || "")]];
    if (tool.inputSchema && typeof tool.inputSchema === "object") {
      collectTexts(tool.inputSchema, "inputSchema", segments, 0);
    }

    for (const [loc, rawText] of segments) {
      if (!rawText) continue;
      const inv = findInvisible(rawText);
      if (inv.length) {
        const uniq = [...new Set(inv)].sort();
        emit("MCP-SEC-003", loc, `Detected ${inv.length} hidden/invisible Unicode character(s): ${uniq.join(", ")}.`, `Codepoints: ${uniq.join(", ")}`);
      }
      const clean = stripInvisible(rawText);
      for (const re of PROMPT_INJECTION_RES) {
        const m = clean.match(re);
        if (m) { emit("MCP-SEC-001", loc, "Prompt injection or system override directive detected.", m[0]); break; }
      }
      for (const re of CREDENTIAL_RES) {
        const m = clean.match(re);
        if (m) { emit("MCP-SEC-002", loc, "Reference to sensitive credentials or secret files detected.", m[0]); break; }
      }
      for (const re of SHADOWING_RES) {
        const m = clean.match(re);
        if (m) { emit("MCP-SEC-004", loc, "Cross-tool shadowing or hijacking instruction detected.", m[0]); break; }
      }
      const exMatch = clean.match(EXFIL_DOMAIN_RE) || clean.match(EXFIL_IP_RE) || clean.match(EXFIL_CTX_RE);
      if (exMatch) {
        emit("MCP-SEC-005", loc, "Potential covert exfiltration endpoint or context-forwarding instruction detected.", exMatch[0]);
      }
      for (const re of CONCEAL_RES) {
        const m = clean.match(re);
        if (m) { emit("MCP-SEC-008", loc, "Deceptive instruction attempting to conceal behavior from the user.", m[0]); break; }
      }
      const dec = decodeSuspiciousBase64(clean);
      if (dec) {
        emit("MCP-SEC-010", loc, "Suspicious Base64-encoded plaintext payload embedded in metadata.", `Decoded preview: ${dec.slice(0, 120)}`);
      } else {
        const hm = clean.match(HEX_RE) || clean.match(DECODE_CMD_RE);
        if (hm) emit("MCP-SEC-010", loc, "Encoded hex sequence or decode instruction detected.", hm[0]);
      }
      const ssrfM = clean.match(SSRF_TEXT_RE);
      if (ssrfM) emit("MCP-SEC-011", loc, "Internal metadata address or dangerous URI scheme referenced.", ssrfM[0]);

      if (loc === "description" && EXEC_DESC_RE.test(clean)) {
        const props = (tool.inputSchema && tool.inputSchema.properties) || {};
        const hasEnum = Object.values(props).some((v) => v && Array.isArray(v.enum) && v.enum.length > 0);
        if (!hasEnum) emit("MCP-SEC-006", loc, "Tool advertises arbitrary command/code execution without an enum allowlist.", clean.slice(0, 160));
      }
    }

    function walkParams(node, loc, depth) {
      if (depth > 12 || !node || !node.properties || typeof node.properties !== "object") return;
      for (const [pname, pschema] of Object.entries(node.properties)) {
        if (!pschema || typeof pschema !== "object") continue;
        const ploc = `${loc}.properties.${pname}`;
        const norm = pname.trim().toLowerCase();
        const hasEnum = Array.isArray(pschema.enum) && pschema.enum.length > 0;
        const hasPattern = typeof pschema.pattern === "string" && pschema.pattern.trim() && !TRIVIAL_PATTERNS.has(pschema.pattern.trim());
        if (EXEC_PARAMS.has(norm) && !hasEnum && !hasPattern) {
          emit("MCP-SEC-006", ploc, `Parameter '${pname}' acts as an unconstrained command/code execution sink.`, JSON.stringify(pschema));
        }
        if (PATH_PARAMS.has(norm) && pschema.type === "string" && !hasEnum && !hasPattern) {
          emit("MCP-SEC-007", ploc, `Filesystem path parameter '${pname}' lacks a restrictive regex 'pattern' or 'enum'.`, JSON.stringify(pschema));
        }
        if (URL_PARAMS.has(norm) && pschema.type === "string" && !hasEnum && !hasPattern) {
          emit("MCP-SEC-011", ploc, `URL parameter '${pname}' lacks scheme/host 'pattern' or 'enum' allowlist (SSRF risk).`, JSON.stringify(pschema));
        }
        if (pschema.properties) walkParams(pschema, ploc, depth + 1);
      }
    }
    if (tool.inputSchema) walkParams(tool.inputSchema, "inputSchema", 0);

    const cleanDesc = stripInvisible(String(tool.description || ""));
    if (DESTRUCTIVE_NAME_RE.test(String(tool.name || "")) || DESTRUCTIVE_DESC_RE.test(cleanDesc)) {
      const props = (tool.inputSchema && tool.inputSchema.properties) || {};
      const propNames = new Set(Object.keys(props).map((k) => k.trim().toLowerCase()));
      const hasConfirm = [...CONFIRM_PARAMS].some((c) => propNames.has(c));
      const hasHint = tool.annotations && tool.annotations.destructiveHint === true;
      if (!hasConfirm && !hasHint) {
        emit("MCP-SEC-009", "inputSchema", `Destructive tool '${tool.name}' lacks a confirmation/dry_run parameter and destructiveHint.`, `properties=${[...propNames].join(",")}`);
      }
    }
    return findings;
  }

  function scanToolSchema(tool) {
    const findings = [];
    const desc = String(tool.description || "").trim();
    if (desc.length < 10) {
      findings.push(makeFinding("MCP-SCHEMA-002", tool.name, "description", desc ? `Tool description is too short (${desc.length} chars; min 10).` : "Tool is missing a description.", desc));
    }
    const schema = tool.inputSchema;
    if (!schema || typeof schema !== "object" || schema.type !== "object") {
      findings.push(makeFinding("MCP-SCHEMA-001", tool.name, "inputSchema", "Tool is missing 'inputSchema' with root type 'object'.", schema ? schema.type : null));
      return findings;
    }

    function validateObj(node, loc, depth) {
      if (depth > 16) return;
      if (node.additionalProperties !== false) {
        findings.push(makeFinding("MCP-SCHEMA-005", tool.name, `${loc}.additionalProperties`, "Object schema does not explicitly set 'additionalProperties: false'.", node.additionalProperties));
      }
      const props = node.properties && typeof node.properties === "object" && !Array.isArray(node.properties) ? node.properties : {};
      if (Array.isArray(node.required)) {
        for (const req of node.required) {
          if (typeof req !== "string" || !(req in props)) {
            findings.push(makeFinding("MCP-SCHEMA-004", tool.name, `${loc}.required`, `Required field '${req}' is not defined in 'properties'.`, req));
          }
        }
      }
      for (const [pname, ps] of Object.entries(props)) {
        const ploc = `${loc}.properties.${pname}`;
        if (!ps || typeof ps !== "object") {
          findings.push(makeFinding("MCP-SCHEMA-008", tool.name, ploc, `Property schema for '${pname}' must be an object.`, ps));
          continue;
        }
        const hasComb = ["anyOf", "oneOf", "allOf", "$ref"].some((k) => k in ps);
        const missing = [];
        if (ps.type === undefined && !hasComb) missing.push("'type'");
        if (typeof ps.description !== "string" || !ps.description.trim()) missing.push("'description'");
        if (missing.length) {
          findings.push(makeFinding("MCP-SCHEMA-003", tool.name, ploc, `Parameter '${pname}' is missing ${missing.join(" and ")}.`, JSON.stringify(ps)));
        }
        const types = typeof ps.type === "string" ? [ps.type] : (Array.isArray(ps.type) ? ps.type : []);
        for (const t of types) {
          if (!VALID_TYPES.has(t)) {
            findings.push(makeFinding("MCP-SCHEMA-008", tool.name, `${ploc}.type`, `Invalid JSON Schema type '${t}'.`, t));
          }
        }
        if (types.includes("string") && !STRING_CONSTRAINTS.some((c) => c in ps)) {
          findings.push(makeFinding("MCP-SCHEMA-006", tool.name, ploc, `String parameter '${pname}' lacks maxLength, pattern, format, or enum.`, JSON.stringify(ps)));
        }
        if (types.includes("array") && (!ps.items || typeof ps.items !== "object")) {
          findings.push(makeFinding("MCP-SCHEMA-007", tool.name, ploc, `Array parameter '${pname}' is missing an 'items' sub-schema.`, ps.items));
        }
        if (types.includes("object") || ps.properties) {
          validateObj(ps, ploc, depth + 1);
        }
      }
    }
    validateObj(schema, "inputSchema", 0);
    return findings;
  }

  function scanNamingAmbiguities(tools) {
    const findings = [];
    const seenExact = new Map();
    const seenNorm = new Map();
    for (let i = 0; i < tools.length; i++) {
      const name = String(tools[i].name || "");
      if (!name) continue;
      if (/[^\x00-\x7F]/.test(name)) {
        findings.push(makeFinding("MCP-SEC-012", name, "name", `Tool name '${name}' contains non-ASCII characters (homoglyph risk).`, name));
      }
      if (seenExact.has(name)) {
        findings.push(makeFinding("MCP-SEC-012", name, "name", `Duplicate tool name '${name}' registered multiple times.`, name));
      } else {
        seenExact.set(name, i);
      }
      const norm = name.toLowerCase().replace(/[-_\s]+/g, "");
      if (seenNorm.has(norm) && seenNorm.get(norm) !== name) {
        findings.push(makeFinding("MCP-SEC-012", name, "name", `Tool name '${name}' collides with normalized form of '${seenNorm.get(norm)}'.`, name));
      } else {
        seenNorm.set(norm, name);
      }
    }
    const uniq = [...seenExact.keys()];
    for (let i = 0; i < uniq.length; i++) {
      for (let j = i + 1; j < uniq.length; j++) {
        const a = uniq[i], b = uniq[j];
        if (Math.min(a.length, b.length) >= 6 && a.slice(0, 4).toLowerCase() === b.slice(0, 4).toLowerCase() && levenshtein(a.toLowerCase(), b.toLowerCase()) === 1) {
          findings.push(makeFinding("MCP-SEC-012", b, "name", `Tool name '${b}' differs by only 1 character from '${a}' (typosquatting risk).`, `${a} vs ${b}`));
        }
      }
    }
    return findings;
  }

  function auditTools(rawJson, includeSchema = true) {
    const parsed = JSON.parse(rawJson);
    let tools = [];
    if (Array.isArray(parsed)) tools = parsed;
    else if (parsed && Array.isArray(parsed.tools)) tools = parsed.tools;
    else if (parsed && parsed.tool && typeof parsed.tool === "object") tools = [parsed.tool];
    else if (parsed && typeof parsed === "object") tools = [parsed];
    else throw new Error("JSON root must be an object or array of MCP tool definitions.");

    let findings = [];
    for (const t of tools) {
      findings = findings.concat(scanToolSecurity(t));
      if (includeSchema) findings = findings.concat(scanToolSchema(t));
    }
    findings = findings.concat(scanNamingAmbiguities(tools));
    findings.sort((a, b) => rankFor(b.severity) - rankFor(a.severity));

    const counts = { CRITICAL: 0, HIGH: 0, MEDIUM: 0, LOW: 0, INFO: 0 };
    let penalty = 0;
    for (const f of findings) {
      counts[f.severity] = (counts[f.severity] || 0) + 1;
      penalty += penaltyFor(f.severity);
    }
    const score = Math.max(0, 100 - penalty);
    const passed = counts.CRITICAL === 0 && counts.HIGH === 0;

    const sarif = {
      $schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",
      version: "2.1.0",
      runs: [{
        tool: { driver: { name: "MCP-Guard", version: "0.1.0", informationUri: "https://github.com/NPLMSHJTR/mcp-guard" } },
        results: findings.map((f) => ({
          ruleId: f.rule_id,
          level: (f.severity === "CRITICAL" || f.severity === "HIGH") ? "error" : (f.severity === "MEDIUM" ? "warning" : "note"),
          message: { text: `[${f.tool_name} @ ${f.location}] ${f.message}` }
        }))
      }]
    };
    return { tools_scanned: tools.length, security_score: score, passed, severity_counts: counts, findings, sarif };
  }

  function simulateChaos(toolName, faultType, argsJson) {
    const args = argsJson && argsJson.trim() ? JSON.parse(argsJson) : {};
    const name = toolName || "get_weather_forecast";
    const map = {
      timeout: { raised_exception: `TimeoutError: ChaosProxy injected timeout on tool '${name}'`, response: null },
      rate_limit_429: { raised_exception: null, response: { jsonrpc: "2.0", id: 1, error: { code: -32029, message: "Too Many Requests: upstream rate limit exceeded (chaos injection)", data: { httpStatus: 429, retryAfterSeconds: 2, chaos: true } } } },
      internal_error_500: { raised_exception: null, response: { jsonrpc: "2.0", id: 1, error: { code: -32603, message: "Internal Server Error: simulated upstream 500 failure (chaos injection)", data: { httpStatus: 500, chaos: true } } } },
      malformed_json: { raised_exception: null, response: { _raw_invalid_frame: '{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"truncated...', chaos: true } },
      schema_drift: { raised_exception: null, response: { jsonrpc: "2.0", id: 1, result: { unexpected_nested_v2_payload: { legacy_content_removed: true }, isError: false } } },
      empty_result: { raised_exception: null, response: { jsonrpc: "2.0", id: 1, result: { content: [], isError: false } } }
    };
    return { tool_name: name, arguments: args, fault_type: faultType, ...(map[faultType] || map.rate_limit_429) };
  }

  window.MCPGuardEngine = { auditTools, simulateChaos };
})();