Coding agents now sit on student laptops with a shell, a project folder and often a cloud key. In this tutorial we build a set of AI agent detection rules in Python: a local, SIEM-style engine that reads coding-agent and Model Context Protocol (MCP) telemetry, flags risky activity, redacts secrets in the evidence and shows alerts in a CLI or a small Flask dashboard.
This is not a cloud product and it does not need a paid API. The bundled rules are original and educational. They are inspired by public reporting from the week of 17–23 November 2026, not copied from any vendor pack. All 29 tests pass on a normal laptop, and the complete source is free on GitHub under the MIT License.
If you are a BTech, MCA or MTech student looking for a timely AI and cyber security final-year project, this is a complete, tested codebase you can explain in a viva: parsers, a rule engine, threshold detections, redaction, storage and a web UI.
Table of Contents
Why AI Agent Detection Rules Matter in November 2026
On 23 November 2026, Elastic Security Labs wrote that Elastic 9.6 will ship 143 production SIEM rules for AI security. The post is blunt about why the rules exist: a coding agent runs with your shell and your files, along with your cloud keys. The coverage includes agents hijacked into running attacker commands, malicious MCP servers, credentials pasted into prompts, jailbreaks, and stolen API keys used to run models at someone else’s expense. When that activity happens on a developer machine, Elastic Defend can even stop the process. See Elastic Security Labs, 23 November 2026.
A coding agent runs with your shell and your files, along with your cloud keys. The rules cover agents hijacked into running attacker commands, malicious Model Context Protocol (MCP) servers, credentials pasted into prompts, jailbreaks, and stolen API keys used to run models at someone else’s expense. (Elastic Security Labs, 23 Nov 2026)
That announcement is useful even if you will never buy Elastic. It names the layers that matter: user AI tooling on the laptop, AI platform logs, and the cloud control plane. A student project cannot ingest CloudTrail or ChatGPT Enterprise audit logs, but it can do a serious job on the first layer. That is what we build here: AI agent detection rules that run on exported JSONL events and local settings files.
The same week added more context. On 22 November 2026, InfoQ summarised research from GitGuardian and Apiiro: Claude Code can save an approved shell command into .claude/settings.local.json when a developer clicks “Yes, and don’t ask again”. If that command contains an API key or a database password, the file can land in a public GitHub repository or a Docker image. GitGuardian counted 31,088 distinct secrets in public settings.local.json files, and 5,343 were still valid when they were checked. See InfoQ, 22 November 2026 and the GitGuardian write-up.
Earlier in the week, Bitdefender Labs (17 November 2026) described a campaign that abuses the files, rules, hooks and configurations AI coding tools use, and Wiz (17 November 2026) reported malicious versions of Microsoft’s agent-framework package on PyPI. Those stories are why a runtime detector sits alongside a static config scanner and a Python supply-chain scanner.
What Is an AI Agent Detection Rules Engine?
An AI agent detection rules engine is a small, local SIEM. You feed it events. Each event says something like “this coding agent ran this command”, “this prompt contained this text”, or “this MCP server connected to this URL”. The engine loads YAML rules, evaluates every event (and, for some rules, a time window of events), and raises an alert with a severity, a short evidence string and a MITRE ATLAS technique id.
It is the missing middle layer between “scan the repo before I clone it” and “put a hardened gateway in front of the model”. The AI coding agent security scanner looks at AGENTS.md, CLAUDE.md and MCP configs at rest. The prompt injection firewall inspects prompts as they go to a model. The hardened LLM gateway checks API keys, rate limits and routes. This project asks a different question: what did the agent actually do, according to the logs?

The design is intentionally simple so you can defend it in a project demo. Ingest is read-only. The rule language is YAML, not a proprietary query language. Threshold rules can group events by user or model over a time window, which is how we catch a token-usage spike or a burst of failed logins. Every alert is redacted before it is printed, stored or rendered in the browser.
Features of the AI Agent Detection Rules Project
- 19 bundled YAML rules across credentials, MCP servers, process behaviour, prompts, usage spikes and configuration changes.
- MITRE ATLAS mappings on every rule, using real technique ids such as
AML.T0051(LLM prompt injection),AML.T0054(LLM jailbreak),AML.T0055(unsecured credentials),AML.T0083(credentials from AI agent configuration),AML.T0086(exfiltration via an agent tool) andAML.T0034(cost harvesting). - Read-only ingest of native JSONL, common field aliases (
cmd,input,timestamp,usage.total_tokens), and Claude or Cursor stylesettings.local.json/mcp.jsonfiles. - MCP URL allow-lists so only reviewed local servers stay quiet. If you do not pass an allow-list, that rule does not fire, which avoids noisy defaults.
- Automatic redaction of common API key and password formats in the CLI, Markdown and JSON reports, the SQLite store and the web UI.
- CLI + Flask dashboard + 29 pytest tests, a synthetic demo with obviously fake credentials, and an MIT licence. No GPU and no paid model required.
Tech Stack and Prerequisites
You only need Python 3.10 or newer, pip, and a terminal. The runtime dependencies are PyYAML and Flask. Pytest is the only extra package for development. That keeps the project affordable for a college lab in India: no cloud account, no Elastic cluster and no GPU.
- Language: Python 3.10+
- Libraries: PyYAML, Flask, pytest, the standard library (argparse, dataclasses, sqlite3, re, json, pathlib)
- Optional: exported JSONL logs from a coding agent you already use, or the bundled demo telemetry
- OS: Linux, macOS or Windows with a virtual environment
Project Structure
AI-Agent-Detection-Rules-Engine-Python/
├── agent_detect/
│ ├── cli.py # scan, demo, rules, report, serve
│ ├── ingest.py # JSONL and settings-file parsers
│ ├── rules.py # YAML rule engine and threshold windows
│ ├── redact.py # secret-format redaction
│ ├── store.py # SQLite alerts
│ ├── report.py # Markdown and JSON reports
│ ├── demo.py # synthetic, clearly fake telemetry
│ ├── web.py # local Flask review UI
│ ├── rules/ # credentials, mcp, process, prompt, usage, config
│ └── templates/ # dashboard, alert detail, rule catalog
├── examples/ # allowlist.yaml and sample-events.jsonl
├── tests/ # 29 pytest tests
└── docs/screenshots/
The package is installable from the repo with pip, and python -m agent_detect is the main entry point. Rules live as data, not as hard-coded if statements, so you can add a pack for your college lab without editing the engine.
How the Detection Engine Works
The pipeline has three stages. First, ingest_path walks a file or a directory and turns JSONL lines and settings files into Event objects. Second, evaluate_rules loads every YAML pack, runs field matchers (equals, contains, regex, allow-list, any/all/not) and evaluates threshold rules over a sliding time window. Third, evidence is redacted, alerts are printed or stored in SQLite, and the Flask app reads that database for review.
A useful viva talking point is that deny lists in settings files are ignored on purpose. We only emit events for allow rules and declared MCP servers, because that is where secrets and untrusted tools actually get saved. The engine never executes a command it finds in a log or a settings file.
Step 1: Normalize Telemetry into a Simple Event Schema
Every parser targets the same small schema. That is the trick that lets one YAML rule work on Claude Code, Cursor, Codex or a generic process logger. The important fields are ts, event_type, agent, command, prompt, mcp_url, path, tokens, user and model. Event types are process, prompt, tool_call, mcp_connect, file_write, api_usage, config and auth.
{
"ts": "2026-11-23T10:08:00+00:00",
"event_type": "process",
"agent": "claude-code",
"process": "curl",
"command": "curl -H \"X-N8N-API-KEY: n8n_api_TESTFAKEKEY9f3ce21a\" https://n8n.example.internal/api/v1/workflows",
"parent": "claude"
}
The TEST and example.internal values above are fake demo data. If you export real logs, keep them on your own machine and let the redactor hide key-shaped strings before you paste a screenshot into a report. Aliases are accepted too, so a line that uses cmd, input or timestamp still becomes a normal event.
Step 2: Write YAML Detection Rules and Thresholds
Rules are YAML documents with an id, a title, a severity, a short description, ATLAS ids and a match tree. Here is the rule that catches a secret sitting in a Claude Code allow rule, which is the GitGuardian and Apiiro story in detection form:
- id: AD-CRED-003
title: Secret embedded in a coding-agent allow rule
severity: high
atlas: [AML.T0083, AML.T0055]
tags: [credentials, settings, claude-code]
match:
all:
- field: event_type
equals: config
- field: command
regex: "(sk-[A-Za-z0-9_\\-]{16,}|n8n_api_[A-Za-z0-9_\\-]{8,}|PGPASSWORD=\\S+|sshpass\\s+-p\\s+\\S+)"
Threshold rules add window_minutes, group_by and either sum_gt or count_gte. AD-USAGE-001 groups API usage by user and model and fires when more than 200,000 tokens are seen in 60 minutes, which is a student-scale version of the cost-harvesting pattern Elastic described for stolen keys. AD-USAGE-002 looks for a burst of authentication events for the same user.
MCP rules are allow-list based. AD-MCP-001 fires only when you pass a trusted_mcp_urls list and the server URL is not on it. AD-MCP-002 looks at tool names and server names such as send_email or postmark, because public incidents have involved a fake mail MCP server that copied outgoing messages. AD-MCP-003 flags any HTTP MCP URL that is not localhost. Process rules cover a download piped to a shell, writes to ~/.ssh/authorized_keys or a crontab, “skip permissions” flags, clearly destructive command strings, and an unexpected interpreter started from a coding-agent workspace.

Step 3: Scan Settings Files for Secrets in Allow Rules
Static configs still matter, which is why the engine can read settings files as well as logs. When Claude Code saves “don’t ask again”, the approved command is often the full string, API key included. The settings reader walks permissions.allow (and similar keys), skips deny lists, and emits one config event per allow rule plus mcp_connect events for each declared server.
That is a different job from the config auditor, which rates policy files for dangerous hooks and MCP setups. Here we are looking for a secret that has already been written into an allow rule, or for an MCP server URL that is not on the lab allow-list. The scanner never tries to log in with a finding. Format detection is enough, and trying a key would be both unsafe and, on a system you do not own, unauthorised.
Step 4: Redact Evidence Before You Share a Report
A detection project that prints live secrets in a screenshot is a liability. redact.py masks well-known shapes: sk- keys, GitHub tokens, AWS access key ids, Slack tokens, Google API keys, n8n keys, JWTs, database URLs, PGPASSWORD= prefixes and sshpass -p arguments. The mask keeps a short prefix and suffix so you can still recognise which finding you are looking at, without putting the full secret in a report, a git commit or a viva slide.
The same helper runs in the CLI printer, the Markdown and JSON reporters, the SQLite writer and the Flask templates. If you extend the project, call redact_text on any new field you display.
Step 5: Review Alerts in the Flask Dashboard
The dashboard is a local Flask app bound to 127.0.0.1 by default. It shows alert counts by severity, a table of redacted evidence, a detail page with ATLAS ids, and the full rule catalog. You can click “Run demo scan” to load the synthetic telemetry, or point the form at a folder of your own logs. Nothing is sent off the machine.


How to Install, Run and Test the Project
Clone the public repo, create a virtual environment and install the development dependencies. Then run the demo, the tests and the dashboard:
git clone https://github.com/GetProjectsIdea/AI-Agent-Detection-Rules-Engine-Python.git
cd AI-Agent-Detection-Rules-Engine-Python
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements-dev.txt
python -m agent_detect demo # fake logs + settings, print redacted alerts
python -m pytest -q # 29 tests
python -m agent_detect serve # http://127.0.0.1:5055
To scan your own files, pass a path and, for MCP allow-list rules, the example allow-list or one you have edited for your lab:
python -m agent_detect scan path/to/events.jsonl --allowlist examples/allowlist.yaml
python -m agent_detect scan path/to/project/.claude/settings.local.json
python -m agent_detect rules list
python -m agent_detect report --format md

On the bundled demo the engine scans 29 events (the JSONL sample plus the settings file) and raises alerts such as AD-PROC-001 for a curl | bash command, AD-CRED-001 / AD-CRED-003 for a fake n8n key in a command and an allow rule, AD-MCP-001 for an unlisted MCP URL, and AD-USAGE-001 for a token spike. That walk-through is the easiest demo to show a project examiner, because it is reproducible and uses only fake credentials.
Limitations and Responsible Use
This tool is for detection and review only. It does not exploit a system, validate or replay a credential, or execute commands found in telemetry. Scan only logs and projects you are allowed to review. The bundled rules are educational pattern matchers; they will produce false positives, and a missing log source will produce false negatives. They are not a substitute for a production SIEM, endpoint agent or a sandboxed coding agent that asks before it runs a command.
If you write new rules, stay on the defensive side: detect, harden and monitor. Do not add payloads, exploit steps or “proof of concept” attacks to the repo or the report. For website telemetry rather than agent telemetry, see the third-party script monitor, which takes a different, also defensive, angle on supply-chain risk.
Learning Outcomes and Future Scope
By the end of this project you should be able to explain a normalized event schema, write a YAML detection rule with boolean logic, implement a sliding-window threshold, redact secret formats, store alerts in SQLite and serve a small review UI. Those are the same ideas used in real detection engineering, just sized for a college project.
Useful extensions for a Phase 2 or MTech dissertation include: a file tailer that follows a live JSONL log, more parsers for specific coding-agent export formats, a signed rule pack so a faculty account can distribute updates, dashboards that group alerts by MITRE ATLAS tactic, and correlation with the static config scanner so a risky MCP server is flagged both at rest and at connect time. Keep any extension read-only and redacted.
FAQs: AI Agent Detection Rules
Is this AI agent detection rules engine a good final-year project?
Yes. You get a rule engine, log parsers, secret redaction, SQLite storage, a CLI and a Flask dashboard, plus automated tests and MITRE ATLAS mappings. The topic is timely because of public reports from 23 November 2026, and the work stays defensive.
Do I need Elastic, a SIEM licence or a paid AI API?
No. The project is a local Python tool. The demo uses synthetic logs and fake credentials, and all 29 tests run on a laptop with PyYAML, Flask and pytest.
How is this different from the AI coding agent security scanner on GetProjects?
The AI coding agent security scanner reviews static files such as AGENTS.md, CLAUDE.md and MCP configs before you run an agent. This engine reviews runtime telemetry: process events, prompts, MCP connections, usage spikes and settings allow rules after or while the agent is used.
Will it copy Elastic’s 143 detection rules?
No. The 19 bundled rules are original educational rules inspired by public reporting. They are not a copy of any vendor rule pack, and they run on a simple JSONL schema rather than Elastic Defend or cloud audit logs.
What should I do if the scanner finds a real secret?
Treat it as compromised. Rotate the credential, remove .claude/settings.local.json from git with git rm --cached, add that path to the repository .gitignore (a global ignore is not enough), and check Docker build contexts so the file is not copied into an image.
Is the source code free?
Yes. The complete project is on GitHub under the MIT License, with 29 passing tests.
References
- Mika Ayenson, “Elastic ships 143 detection rules for AI agents and LLM platforms”, Elastic Security Labs, 23 November 2026.
- Sergio De Simone, “Claude Code Has Been Leaking Secrets through its ‘Don’t Ask Again’ Feature”, InfoQ, 22 November 2026.
- Guillaume Valadon, “Claude Code settings.local.json Secrets: GitHub, Docker Hub”, GitGuardian.
- Andrei Anton-Aanei, “How AI Agents Become New Targets in GitHub Malware Campaign”, Bitdefender Labs, 17 November 2026.
- Rami McCarthy, Scott Piper and Benjamin Read, “Microsoft agent-framework Compromised”, Wiz, 17 November 2026.
- MITRE, “Adversarial Threat Landscape for AI Systems (ATLAS)”, atlas.mitre.org.
Download the Source Code
The complete, tested source code for this AI agent detection rules engine — including the 19 YAML packs, the Flask dashboard, the demo telemetry and the 29 tests — is free on GitHub under the MIT License.
Conclusion
A coding agent is only as safe as the commands it runs, the MCP servers it trusts and the secrets that leak into prompts or allow rules. The public research from 17–23 November 2026 made that concrete. With this project you can build and demonstrate a local set of AI agent detection rules in Python, review redacted alerts, and extend the YAML packs for your own lab. Clone the repo, run the demo, and then point the scanner at logs you are allowed to review.