Back to Intelligence

Elastic Ships 143 Detection Rules for AI Agents and LLM Platforms: Detecting Malicious MCP Servers, Rogue Coding Agents, and Stolen API Keys

SA
Security Arsenal Team
November 23, 2026
13 min read

Security operations teams have spent the last eighteen months racing to deploy AI coding assistants, MCP-connected agents, and LLM-backed workflows — often with less telemetry and fewer guardrails than we would ever tolerate for a traditional application stack. Attackers noticed first. Elastic Security Labs has now shipped a pack of 143 detection rules specifically targeting AI agents and LLM platforms, and the threat scenarios they cover are not theoretical: a fake Model Context Protocol (MCP) server silently copying every outgoing email to an attacker, coding agents tricked into executing attacker-supplied commands, developers pasting secrets directly into prompts, and stolen API keys being used to run model inference on your cloud bill.

This is the most concrete signal yet that AI agent abuse has matured from conference talk to operational detection engineering. If your organization has rolled out Copilot-style coding agents, Claude Desktop, Cursor, or any MCP-connected tooling — and you almost certainly have, whether sanctioned or not — you need this coverage in your detection stack today.

The Threat Scenarios the New Rules Address

1. Malicious MCP Servers: The New Supply Chain Edge

The Model Context Protocol has exploded as the standard way AI assistants connect to external tools — email, filesystems, databases, SaaS APIs. That convenience is exactly the problem. An MCP server runs locally or remotely with access to whatever the agent can see, and users install them with the same casual trust they once gave browser extensions.

The headline scenario Elastic's rules catch: a fake MCP server configured for email integration that silently BCCs or forwards every outgoing message to an attacker-controlled endpoint. From the host's perspective, this is a legitimate-looking process making outbound HTTPS connections. From the business's perspective, it is wholesale correspondence exfiltration with zero malware signatures to trip on.

The defensive lesson: MCP server configurations are a new persistence and exfiltration surface. The config files (claude_desktop_config.json, .cursor/mcp.json, project-level .mcp.json) define which binaries run and which remote servers get your data — and almost nobody is monitoring them.

2. Coding Agents Executing Attacker Commands

Prompt injection against coding agents is no longer a research demo. Agents that can read repositories, issue trackers, and web content can ingest adversarial instructions embedded in a README, a Jira ticket, or a poisoned dependency's documentation. When the agent then spawns bash, curl, or a Python interpreter to run those instructions, you have remote code execution laundered through a trusted developer tool.

Elastic's rules target the behavioral signature: AI agent processes spawning suspicious child processes — shells, download cradles, base64-decoding pipelines — under user contexts where that activity has no legitimate baseline.

3. Secrets Pasted Into Prompts

Developers are pasting API keys, connection strings, private certificates, and credentials into LLM prompts at an alarming rate. Once a secret hits a prompt, it may be logged by the provider, retained in conversation history, cached by a proxy, or — worst case — returned to a future attacker in a prompt-injection scenario. The detection opportunity here is pattern-matching high-entropy strings and known secret formats (AWS access keys, sk- prefixed OpenAI/Anthropic keys, GitHub PATs, PEM blocks) in outbound traffic to LLM API endpoints.

4. Stolen API Keys Running Models on Your Bill

The financially motivated angle: threat actors steal LLM provider API keys (from .env files, CI/CD logs, exposed repos) and resell access or run their own workloads against your quota. Beyond direct cost, a stolen key with broad scope is a data exfiltration channel — an attacker can query models with your attached retrieval context. Detection hinges on impossible geography, anomalous token consumption, and provider API calls from infrastructure that has never touched those endpoints before.

Affected Products and Platforms

This is not a vulnerability in a single product — it is a detection gap across an emerging platform category. The rule pack is relevant to any environment running:

  • MCP clients and hosts: Claude Desktop, Cursor, VS Code with agent extensions, Windsurf, custom agent frameworks
  • MCP servers: local stdio-based servers and remote SSE/HTTP MCP endpoints, including community-published servers of unvetted provenance
  • LLM provider APIs: OpenAI, Anthropic, Google Gemini, Azure OpenAI, AWS Bedrock, and self-hosted inference
  • CI/CD and developer endpoints: anywhere coding agents execute tool calls with shell access

Exploitation status: The malicious MCP server scenario and API key abuse are observed in the wild — the email-exfiltrating fake MCP server is a documented real incident pattern, not a hypothetical. API key theft and resale is an established criminal economy. Prompt injection against coding agents has multiple public demonstrations and confirmed operational abuse. None of this requires a CVE; it abuses intended functionality.

Detection & Response

Elastic customers should deploy the updated prebuilt rule pack via the Detection Rules management page in Kibana. But the techniques are platform-agnostic — the detections below translate the same behavioral logic for Microsoft Sentinel, Sigma-compatible pipelines, and Velociraptor hunts so non-Elastic shops get equivalent coverage.

Sigma Rules

The following rules target three of the highest-fidelity behaviors: AI agent processes spawning shells/downloaders, modification of MCP configuration files, and secrets traversing outbound connections to LLM endpoints. All three are designed to be low-noise when your legitimate agent baseline is understood — test in your environment before promoting to high severity.

YAML
---
title: AI Coding Agent Spawning Suspicious Child Process
id: 8b2c4d6e-1a3f-4b5c-9d7e-2f4a6c8e0b1d
status: experimental
description: Detects AI coding assistants and agent hosts (Claude Desktop, Cursor, VS Code agent extensions) spawning shells, download cradles, or encoded command interpreters — consistent with prompt injection driving attacker command execution through a trusted agent process.
references:
  - https://www.elastic.co/security-labs/blog/ai-security-detection-rules-coding-agents-mcp
  - https://attack.mitre.org/techniques/T1059/
author: Security Arsenal
date: 2026/04/06
tags:
  - attack.execution
  - attack.t1059
  - attack.defense_evasion
logsource:
  category: process_creation
  product: windows
detection:
  selection_parent:
    ParentImage|endswith:
      - '\cursor.exe'
      - '\claude.exe'
      - '\code.exe'
      - '\windsurf.exe'
  selection_child:
    Image|endswith:
      - '\powershell.exe'
      - '\pwsh.exe'
      - '\cmd.exe'
      - '\wscript.exe'
      - '\cscript.exe'
      - '\mshta.exe'
      - '\curl.exe'
      - '\certutil.exe'
      - '\bitsadmin.exe'
  selection_cmdline:
    CommandLine|contains:
      - 'enc '
      - '-e '
      - 'frombase64'
      - 'iex'
      - 'invoke-webrequest'
      - 'downloadstring'
      - 'http://'
      - 'https://'
  condition: selection_parent and selection_child and selection_cmdline
falsepositives:
  - Legitimate agent tool use such as running project build scripts — baseline per agent host and tune CommandLine requirements
level: high
---
title: MCP Server Configuration Modification
id: 3f7a9b1c-5d2e-4f6a-8b0c-1e3d5f7a9b2c
status: experimental
description: Detects creation or modification of MCP server configuration files for Claude Desktop, Cursor, and project-level MCP configs. Attackers implant malicious MCP servers (e.g., email-exfiltrating fake servers) by editing these files; unexpected changes warrant immediate review.
references:
  - https://www.elastic.co/security-labs/blog/ai-security-detection-rules-coding-agents-mcp
  - https://attack.mitre.org/techniques/T1546/
author: Security Arsenal
date: 2026/04/06
tags:
  - attack.persistence
  - attack.collection
  - attack.exfiltration
logsource:
  category: file_event
  product: windows
detection:
  selection:
    TargetFilename|contains:
      - 'claude_desktop_config.json'
      - '\.cursor\mcp.json'
      - '\.mcp.json'
      - 'mcp_settings.json'
  filter_installers:
    Image|endswith:
      - '\claude.exe'
      - '\cursor.exe'
  condition: selection and not filter_installers
falsepositives:
  - Developers manually adding legitimate MCP servers — treat every hit as a review task, not a benign dismissal
level: high
---
title: MCP Server Spawning Shell or Script Interpreter on Linux/macOS
id: 6d4e2a8b-9c1f-4d3e-7a5b-2c6e8a0d4f2e
status: experimental
description: Detects locally installed MCP server processes spawning shells or interpreters with network download patterns, consistent with a trojanized community MCP server executing attacker payloads on developer endpoints.
references:
  - https://www.elastic.co/security-labs/blog/ai-security-detection-rules-coding-agents-mcp
  - https://attack.mitre.org/techniques/T1059.004/
author: Security Arsenal
date: 2026/04/06
tags:
  - attack.execution
  - attack.t1059.004
  - attack.t1105
logsource:
  category: process_creation
  product: linux
detection:
  selection_parent:
    ParentCommandLine|contains:
      - 'mcp'
      - 'claude'
      - 'cursor'
  selection_child:
    Image|endswith:
      - '/bash'
      - '/sh'
      - '/zsh'
      - '/python'
      - '/python3'
      - '/node'
  selection_net:
    CommandLine|contains:
      - 'curl '
      - 'wget '
      - 'http://'
      - 'https://'
      - 'base64 -d'
      - '| sh'
      - '| bash'
  condition: selection_parent and selection_child and selection_net
falsepositives:
  - Legitimate MCP servers that fetch remote resources — inventory approved servers and exclude their exact command lines
level: high

KQL Hunt: Microsoft Sentinel / Defender

This query hunts the coding-agent child-process execution pattern across Defender endpoint telemetry, and joins a companion hunt for MCP config file tampering. Run both over a 7-day window to establish your baseline before alerting.

KQL — Microsoft Sentinel / Defender
// Hunt: AI agent hosts spawning shells/downloaders + MCP config file changes
let AgentHosts = dynamic(["cursor.exe", "claude.exe", "code.exe", "windsurf.exe", "zed.exe", "windsurf" ]);
let SuspiciousChildren = dynamic(["powershell.exe", "pwsh.exe", "cmd.exe", "mshta.exe", "curl.exe", "wscript.exe", "bash", "sh", "python3", "node"]);
DeviceProcessEvents
| where TimeGenerated > ago(7d)
| where InitiatingProcessFileName has_any (AgentHosts)
| where FileName has_any (SuspiciousChildren)
| where ProcessCommandLine has_any ("enc", "-e ", "frombase64", "iex", "downloadstring", "invoke-webrequest", "curl ", "wget ", "base64 -d", "| sh", "| bash", "http://", "https://")
| project TimeGenerated, DeviceName, AccountName,
    AgentProcess = InitiatingProcessFileName, AgentCmd = InitiatingProcessCommandLine,
    ChildProcess = FileName, ChildCmd = ProcessCommandLine, SHA256
| order by TimeGenerated desc;
// Companion hunt: MCP configuration file creation/modification
DeviceFileEvents
| where TimeGenerated > ago(7d)
| where FileName has_any ("claude_desktop_config.json", "mcp.json", "mcp_settings.json")
   or FolderPath has_any (@"\.cursor\mcp.json", @"\.mcp.json")
| where InitiatingProcessFileName !in~ ("cursor.exe", "claude.exe", "code.exe")
| project TimeGenerated, DeviceName, AccountName, FolderPath, FileName,
    ActionType, InitiatingProcessFileName, InitiatingProcessCommandLine, SHA256
| order by TimeGenerated desc;

Velociraptor VQL

Use this artifact to sweep your developer fleet for MCP configuration files and extract the configured server commands and remote endpoints — the fastest way to find a trojanized MCP server before it exfiltrates another day of email.

VQL — Velociraptor
-- Hunt: enumerate MCP server configurations across endpoints
-- Surfaces server commands and remote URLs for analyst review
LET configs = SELECT FullPath, Mtime, Size,
       read_file(filename=FullPath, length=1048576) AS ConfigContent
FROM glob(globs=[
  "C:/Users/*/AppData/Roaming/Claude/claude_desktop_config.json",
  "C:/Users/*/.cursor/mcp.json",
  "C:/Users/*/**/.mcp.json",
  "/Users/*/Library/Application Support/Claude/claude_desktop_config.json",
  "/home/*/.config/Claude/claude_desktop_config.json",
  "/home/*/.cursor/mcp.json"
])
SELECT FullPath, Mtime, Size,
       parse_string_with_regex(string=ConfigContent,
         regex="(?i)(https?://[^\"'\\s]+)") AS RemoteEndpoints,
       parse_string_with_regex(string=ConfigContent,
         regex="(?i)\"command\"\\s*:\\s*\"([^\"]+)\"") AS ServerCommand,
       ConfigContent
FROM configs
WHERE ConfigContent =~ "mcp|command|url"

Hardening and Verification Script

This PowerShell script audits a Windows developer endpoint for MCP configuration files, flags unsigned or unexpected server binaries, and inventories outbound connections to known LLM API hosts — giving IR teams a fast triage artifact per machine.

PowerShell
# Audit-MCPConfiguration.ps1 - Triage MCP configs and LLM API egress on a developer endpoint
# Run elevated. Review output before taking any containment action.

$report = @()

# 1. Locate and hash MCP configuration files
$paths = @(
  "$env:APPDATA\Claude\claude_desktop_config.json",
  "$env:USERPROFILE\.cursor\mcp.json",
  "$env:USERPROFILE\.mcp.json"
)
foreach ($p in $paths) {
  if (Test-Path $p) {
    $f = Get-Item $p
    $report += [pscustomobject]@{
      Check = 'MCPConfig'; Path = $f.FullName
      LastWrite = $f.LastWriteTime
      SHA256 = (Get-FileHash $p -Algorithm SHA256).Hash
      Content = (Get-Content $p -Raw)
    }
    Write-Host "[+] Found MCP config: $($f.FullName) (modified $($f.LastWriteTime))"
  }
}

# 2. Extract configured server commands and verify Authenticode signatures
foreach ($p in $paths | Where-Object { Test-Path $_ }) {
  $json = Get-Content $p -Raw | ConvertFrom-Json
  $json.mcpServers.PSObject.Properties | ForEach-Object {
    $cmd = $_.Value.command
    if ($cmd -and (Test-Path $cmd)) {
      $sig = Get-AuthenticodeSignature $cmd
      $report += [pscustomobject]@{
        Check = 'MCPServerBinary'; ServerName = $_.Name
        Command = $cmd; SignatureStatus = $sig.Status
        Signer = $sig.SignerCertificate.Subject
      }
      if ($sig.Status -ne 'Valid') {
        Write-Warning "Unsigned/invalid MCP server binary: $cmd (server: $($_.Name))"
      }
    }
    if ($_.Value.url) {
      Write-Host "[!] Remote MCP endpoint configured for '$($_.Name)': $($_.Value.url)"
    }
  }
}

# 3. Flag active connections to LLM API hosts from unexpected processes
$llmHosts = @('api.openai.com','api.anthropic.com','generativelanguage.googleapis.com')
Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue | ForEach-Object {
  try {
    $dns = (Resolve-DnsName $_.RemoteAddress -ErrorAction Stop).NameHost
  } catch { $dns = $null }
  if ($dns -and ($llmHosts | Where-Object { $dns -like "*$_*" })) {
    $proc = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue
    $report += [pscustomobject]@{
      Check = 'LLMEgress'; RemoteHost = $dns
      Process = $proc.ProcessName; Path = $proc.Path; PID = $_.OwningProcess
    }
    Write-Host "[i] LLM API connection: $($proc.ProcessName) (PID $($_.OwningProcess)) -> $dns"
  }
}

$report | Export-Csv -Path ".\MCP-Audit-$(Get-Date -Format 'yyyyMMdd-HHmmss').csv" -NoTypeInformation
Write-Host "Audit complete. CSV written to current directory."

For Linux and macOS developer fleets, the Bash equivalent checks the same config locations and flags MCP servers piping downloads into shells:

Bash / Shell
#!/bin/bash
# mcp-audit.sh - audit MCP configs and flag suspicious server commands
CONFIGS=("$HOME/.config/Claude/claude_desktop_config.json" \
         "$HOME/Library/Application Support/Claude/claude_desktop_config.json" \
         "$HOME/.cursor/mcp.json")

for cfg in "${CONFIGS[@]}"; do
  if [ -f "$cfg" ]; then
    echo "[+] $cfg (modified: $(stat -c %y "$cfg" 2>/dev/null || stat -f %Sm "$cfg"))"
    grep -Eo '"command"[^,]*|"url"[^,}]*' "$cfg"
    echo "    sha256: $(shasum -a 256 "$cfg" | awk '{print $1}')"
  fi
done

# Flag running MCP-adjacent processes holding network connections to non-standard hosts
echo "[*] Processes with 'mcp' in command line holding established connections:"
lsof -i -n -P 2>/dev/null | grep -iE 'mcp|node|python' | grep ESTABLISHED

# Search shell histories for secrets pasted into prompt tooling
echo "[*] Possible secrets in recent shell history (review manually):"
grep -Eho '(sk-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{36})' \
  "$HOME/.bash_history" "$HOME/.zsh_history" 2>/dev/null | sort -u | head -20

Remediation

There is no patch for this class of threat because there is no single vulnerability — there is an architectural trust problem. Remediate it the way you would any new attack surface: inventory, policy, monitoring, and least privilege.

  1. Deploy the detection content. Elastic customers: update prebuilt rules in Kibana (Security → Rules → Rule Updates) and enable the AI/LLM rule pack. Non-Elastic shops: deploy the Sigma, KQL, and VQL content above and tune against a one-week baseline.

  2. Inventory every MCP server in your environment. You cannot defend a supply chain you cannot see. Use the Velociraptor artifact or the audit scripts above to enumerate configured servers, their binaries, and their remote endpoints across your developer fleet. Anything unsigned, unvetted, or pointing at an unfamiliar remote host gets pulled pending review.

  3. Establish an approved MCP server registry. Treat community MCP servers like third-party dependencies: pin versions, verify signatures, require security review before installation, and block installation of unapproved servers via application control policy. The email-exfiltration scenario works precisely because nobody validated the server.

  4. Constrain agent execution. Coding agents should run without standing access to production credentials, with network egress restricted to required endpoints, and — critically — with human-in-the-loop approval for any shell command touching the network. Alert on agents spawning download cradles; there is no legitimate development workflow that requires an agent to pipe curl into bash.

  5. Stop secrets from reaching prompts. Deploy pre-commit hooks and IDE-integrated secret scanning (gitleaks, trufflehog). DLP rules matching sk-, AKIA, ghp_, and PEM headers on outbound connections to LLM API hosts catch the paste-after-the-fact cases. Rotate any secret that has transited a prompt — assume provider-side logging.

  6. Monitor LLM API key consumption like a financial control. Set per-key spend and rate alerts with your providers, alert on API calls from ASNs and geographies outside your baseline, and scope keys to minimum required models and endpoints. Token theft is monetized within hours; a billing anomaly at 3 AM is an IR ticket, not a finance ticket.

  7. Tabletop the scenario. Run your IR team through the fake-MCP-server playbook: how would you detect it, which telemetry would you need, how would you scope the blast radius of an agent with mailbox access? The teams that answer those questions in an exercise will answer them in hours during the real event.

Bottom Line

AI agents and MCP integrations are now production infrastructure with privileged access to email, code, filesystems, and credentials — and attackers are already operating against them. Elastic's 143-rule release is the first detection pack at this scale aimed squarely at the surface, and it should be the forcing function for every SOC to answer one question honestly: do we have any detection coverage at all for the AI tooling our developers are running today? For most organizations, the answer is no. That gap is now unforgivable, because the detections exist and the attacks are live.

Related Resources

Security Arsenal Penetration Testing Services AlertMonitor Platform Book a SOC Assessment vulnerability-management Intel Hub

Is your security operations ready?

Get a free SOC assessment or see how AlertMonitor cuts through alert noise with automated triage.