Skip to main content
Glama
chouaieb161

Azure Security MCP Agent

by chouaieb161
README.md
# Azure Security MCP Agent

An AI-powered agent that uses **Model Context Protocol (MCP)** tools and a **Groq LLM** to analyze the security of your **Azure** infrastructure.

The design is inspired by the YouTube example **`yt-mcp-agent`** [`github.com/ShawhinT/yt-mcp-agent`](https://github.com/ShawhinT/yt-mcp-agent) but adapted for **cloud security** and **Azure**.

---

## Overview

This project shows how to build a security-focused AI agent that can:

- Discover resources across an Azure subscription
- Analyze Network Security Groups (NSGs) for dangerous rules
- Audit storage accounts for insecure configuration
- List public IPs and identify exposed assets
- Check basic VM security posture
- Explain risks and relate them to **CIS Azure** best practices (you can reference the included CIS PDF)

There are **three main entry points**:

- **`main.py`** – OpenAI Agents SDK + MCP tools (Groq model) – *recommended path*
- **`agent.py`** – LangChain/LangGraph ReAct-style agent using the same MCP tools
- **`demo.py`** – Offline Groq-only demo using mock Azure data (no Azure access required)

---

## Architecture

```text
┌──────────────────────────────┐
│        Groq LLM API          │   (llama-3.3-70b-versatile via OpenAI-compatible API)
└───────────────┬──────────────┘
                │
                ▼
┌─────────────────────────────────────────────┐
│  Agent Clients                              │
│  - main.py  (OpenAI Agents SDK + MCP tools) │
│  - agent.py (LangChain / LangGraph)         │
└───────────────┬─────────────────────────────┘
                │  (MCP JSON-RPC over stdio)
                ▼
┌─────────────────────────────────────────────┐
│  MCP Server (FastMCP)                       │
│  - server.py                                │
│  - exposes azure_* tools                    │
└───────────────┬─────────────────────────────┘
                │
                ▼
┌─────────────────────────────────────────────┐
│  Azure SDK for Python                       │
│  - azure-identity / mgmt-resource/network   │
│  - mgmt-storage / mgmt-compute              │
└─────────────────────────────────────────────┘
```

---

## Key Components

- **`server.py`**  
  FastMCP-based MCP server (`FastMCP("azure-security-analyzer")`) exposing tools like:
  - `azure_list_resource_groups`
  - `azure_list_nsgs`
  - `azure_list_storage_accounts`
  - `azure_list_resources`
  - `azure_check_nsg_rules`
  - `azure_check_storage_security`
  - `azure_list_public_ips`
  - `azure_check_vm_security`  
  It also exposes a `system_prompt` via `@mcp.prompt()` that reads from `prompts/system_instructions.md`.

- **`main.py`**  
  Uses the **OpenAI Agents SDK** (`agents.Agent`, `MCPServerStdio`) to:
  - Start the MCP server (`server.py`) as a subprocess over stdio
  - Attach all MCP tools to the agent automatically
  - Use **Groq** as the model via the OpenAI-compatible API
  - Provide a simple terminal loop where you type natural-language security questions

- **`agent.py`**  
  An alternative **LangChain/LangGraph** implementation that:
  - Connects to the same MCP server
  - Wraps MCP tools into LangChain tools
  - Uses a ReAct-style graph to decide which Azure tools to call

- **`demo.py`**  
  Offline demo that feeds **mock Azure findings** (e.g. open NSG rules, insecure storage settings) into Groq and asks it to produce a security report. Useful when you don’t have real Azure access.

- **`prompts/system_instructions.md`**  
  System instructions for the agent (how to interpret tool results, severity levels, report format, etc.). You can customize this to align more strictly with the **CIS Microsoft Azure Compute Services Benchmark** (the PDF included in this repo).

---

## Prerequisites

- **Python** 3.10+
- **Azure subscription** with at least some test resources
- **Azure CLI** (`az`) for local authentication
- **Groq account + API key** (`https://console.groq.com`)
- (Optional) Basic familiarity with CIS Azure benchmarks

---

## Setup

### 1. Create and activate a virtual environment

**Windows (PowerShell)**:

```powershell
cd C:\Users\MSI\mcp_project
python -m venv venv
.\venv\Scripts\Activate.ps1
pip install -r requirements.txt
```

**Linux / macOS**:

```bash
cd /path/to/mcp_project
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```

Re-activate the venv in each new terminal before running the project.

### 2. Authenticate to Azure

```bash
az login

# (optional) select a specific subscription
az account set --subscription "YOUR-SUBSCRIPTION-ID"

# show your current subscription id
az account show --query id -o tsv
```

### 3. Configure environment variables

Create a `.env` file in the project root:

```text
GROQ_API_KEY=gsk_xxxxxxxxxxxxxxxxxxxxx
AZURE_SUBSCRIPTION_ID=your-subscription-id
```

These are read by both `main.py` and `agent.py`.

---

## Running the Agent (OpenAI Agents SDK + MCP tools)

This path is closest to the **`yt-mcp-agent`** example and is the **recommended** way to use the project.

```powershell
cd C:\Users\MSI\mcp_project
.\venv\Scripts\Activate.ps1
python main.py
```

You’ll see a prompt like:

```text
=== Azure Security Agent (MCP tools + Groq) ===
Type your security query, or 'exit' to quit.

You:
```

Example questions you can ask:

- “Discover my Azure resource groups and list any NSGs with open SSH or RDP.”
- “List storage accounts in my subscription and tell me which ones violate CIS recommendations.”
- “Give me a security review of NSG rules in resource group `rg-security-demo`.”
- “Find all public IPs and summarize which services they expose.”

Behind the scenes the agent will:

1. Use MCP tools (e.g. `azure_list_resource_groups`, `azure_list_nsgs`, `azure_check_nsg_rules`)
2. Combine those results with the **system instructions** and your question
3. Ask Groq’s model to produce a structured security analysis and recommendations

---

## Alternative: LangChain / LangGraph CLI (`agent.py`)

If you want to see how the same MCP tools plug into **LangChain/LangGraph**, run:

```powershell
cd C:\Users\MSI\mcp_project
.\venv\Scripts\Activate.ps1
python agent.py
```

This script:

- Connects to the MCP server via stdio
- Wraps Azure MCP tools as LangChain tools
- Uses a ReAct-style graph to decide which tools to call and in what order

Use this when you want to experiment with chain/graph-based orchestration rather than the OpenAI Agents SDK.

---

## Offline Demo (`demo.py`)

If you don’t have Azure access or just want to see the **security reasoning** piece:

```powershell
cd C:\Users\MSI\mcp_project
.\venv\Scripts\Activate.ps1
python demo.py
```

`demo.py` feeds **mock NSG, storage, public IP, and VM findings** into Groq and asks the model to:

- Prioritize findings by severity
- Explain risks in plain language
- Suggest remediation steps (e.g. align with CIS controls)

No Azure calls or MCP server are needed for this demo, just your `GROQ_API_KEY`.

---

## MCP Tools (Server-Side Capabilities)

The MCP server (`server.py`) exposes the following tools to whichever agent you use.

**Discovery tools** (use these when you don’t know exact resource names):

1. **`azure_list_resource_groups(subscription_id)`** – List all resource groups in the subscription.
2. **`azure_list_nsgs(subscription_id, resource_group=None)`** – List NSGs across the subscription or within a specific resource group.
3. **`azure_list_storage_accounts(subscription_id, resource_group=None)`** – List storage accounts.
4. **`azure_list_resources(subscription_id, resource_group=None)`** – Generic resource inventory (name, type, location, resource group).

**Analysis tools**:

5. **`azure_check_nsg_rules(subscription_id, resource_group, nsg_name)`**  
   - Flags wildcard sources (`*`, `Internet`)
   - Detects dangerous ports (22, 3389, 1433, 3306, 5432, 27017, 6379)
   - Warns on “all ports open” (`destination_port_range="*"`)

6. **`azure_check_storage_security(subscription_id, resource_group, storage_account_name)`**  
   - Checks public blob access, HTTPS-only, TLS version, encryption status.

7. **`azure_list_public_ips(subscription_id, resource_group=None)`**  
   - Lists all public IPs, where they live, and notes that they expose resources to the internet.

8. **`azure_check_vm_security(subscription_id, resource_group, vm_name)`**  
   - Looks for missing managed identities and disk encryption issues.

The **agent** doesn’t hard-code Azure logic; it just calls these tools and reasons over their JSON outputs.

---

## What the Agent Detects (Examples)

- **Network Security**
  - Wildcard source addresses (`*`, `Internet`, `0.0.0.0/0`)
  - Open SSH/RDP/SQL ports to the internet
  - Rules that allow all ports

- **Storage Security**
  - Public blob access enabled
  - HTTPS-only not enforced
  - Weak TLS minimum version
  - Missing or misconfigured encryption

- **VM Security**
  - VMs without managed identity
  - Unencrypted OS disks (or encryption not explicitly configured)

- **Exposure & Posture**
  - Public IP inventory
  - Resource misconfigurations compared to baseline best practices

You can refine or formalize these checks against the provided **CIS Azure** PDF.

---

## Security & Best Practices

- **Do not commit `.env`** – it contains secrets.
- Run initially against **non-production** subscriptions.
- Ensure you have at least **Reader** permissions for the subscription.
- Treat the agent’s output as **advice**, not an automatic “source of truth” – always validate before making changes.

---

## Extending the Project

Ideas for next steps:

- Add more Azure services (Key Vault, SQL, App Service, AKS, etc.).
- Encode more CIS controls directly into `server.py` tools.
- Add a small web UI on top of `main.py` flows.
- Persist findings and generate trend/compliance reports.
- Add multi-cloud support (AWS, GCP) with additional MCP servers.

---

## Inspiration & References

- **Inspiration**: [`yt-mcp-agent`](https://github.com/ShawhinT/yt-mcp-agent) – YouTube analysis agent using MCP and the OpenAI Agents SDK.
- **MCP Documentation**: [`https://modelcontextprotocol.io`](https://modelcontextprotocol.io)
- **Azure SDK for Python**: [`https://learn.microsoft.com/azure/developer/python/`](https://learn.microsoft.com/azure/developer/python/)
- **Groq API Docs**: [`https://console.groq.com/docs`](https://console.groq.com/docs)
- **CIS Azure Benchmark**: [`https://www.cisecurity.org/benchmark/azure`](https://www.cisecurity.org/benchmark/azure)

---

## License

MIT – feel free to use and adapt this project for your own experiments and learning.

# Azure Security MCP Agent

An AI-powered agent for analyzing Azure infrastructure security using Model Context Protocol (MCP) and Groq's free LLM API.

## 🎯 Project Overview

This project demonstrates a simple but powerful AI agent that can:
- Discover Azure resources across your subscription
- Analyze Network Security Groups (NSGs) for misconfigurations
- Check storage account security settings
- Identify public IP exposure
- Audit VM security configurations
- Provide actionable security recommendations based on CIS benchmarks

## 🏗️ Architecture

```
┌─────────────────┐
│   Groq LLM      │  (AI Brain - Free API)
│  (llama-3.3)    │
└────────┬────────┘
         │
         ↓
┌─────────────────┐
│  Agent Client   │  (Orchestrates analysis)
│   (agent.py)    │
└────────┬────────┘
         │
         ↓ (MCP Protocol)
┌─────────────────┐
│   MCP Server    │  (Tools for Azure)
│   (server.py)   │
└────────┬────────┘
         │
         ↓
┌─────────────────┐
│  Azure SDK      │  (Azure API calls)
│                 │
└─────────────────┘
```

## 🚀 Quick Start

### 1. Prerequisites

- Python 3.8+
- Azure subscription with resources to analyze
- Groq API key (free from https://console.groq.com)
- Azure credentials (Azure CLI recommended)

### 2. Installation (avec environnement virtuel recommandé)

**Oui, utilisez un virtual env** pour éviter les conflits de paquets.

**Windows (PowerShell ou CMD) :**

```powershell
# Aller dans le dossier du projet
cd c:\Users\MSI\mcp_project

# Créer l'environnement virtuel
python -m venv venv

# Activer le venv (PowerShell)
.\venv\Scripts\Activate.ps1

# Ou en CMD
.\venv\Scripts\activate.bat

# Installer les dépendances
pip install -r requirements.txt
```

**Linux / macOS :**

```bash
cd /chemin/vers/mcp_project
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```

Ensuite, à chaque nouvelle session, **réactivez le venv** avant de lancer le projet :
- Windows : `.\venv\Scripts\Activate.ps1`
- Linux/macOS : `source venv/bin/activate`

### 3. Azure Setup (Simple Test Infrastructure)

**Simplest way to prove the agent works:** Create one resource group, one NSG with one insecure rule, and one storage account with one bad setting. Then run the agent and choose **option 6 (Full discovery and security scan)** — the agent will discover everything and report the issues.

#### Option A: Using Azure Portal (Easiest for beginners)

1. **Create a Resource Group:**
   - Go to Azure Portal (portal.azure.com)
   - Click "Resource groups" → "Create"
   - Name: `rg-security-demo`
   - Region: `East US`
   - Click "Review + Create" → "Create"

2. **Create a Storage Account:**
   - Search for "Storage accounts" → "Create"
   - Resource group: `rg-security-demo`
   - Name: `secdemostorage<random>` (must be globally unique)
   - Region: `East US`
   - Performance: `Standard`
   - Redundancy: `LRS`
   - **Advanced tab:**
     - Enable "Allow Blob public access" (for testing - we'll flag this!)
     - Disable "Require secure transfer" (for testing - we'll catch this!)
   - Click "Review + Create" → "Create"

3. **Create a Network Security Group:**
   - Search for "Network security groups" → "Create"
   - Resource group: `rg-security-demo`
   - Name: `nsg-demo`
   - Region: `East US`
   - Click "Review + Create" → "Create"
   - After creation, click "Inbound security rules" → "Add"
   - Add a rule:
     - Source: `Any` (*)
     - Destination port: `22` (SSH)
     - Action: `Allow`
     - Name: `allow-ssh-any`
   - This creates a security issue for the agent to find!

4. **Create a Virtual Machine (Optional):**
   - Search for "Virtual machines" → "Create"
   - Resource group: `rg-security-demo`
   - VM name: `vm-demo`
   - Region: `East US`
   - Image: `Ubuntu Server 20.04 LTS`
   - Size: `B1s` (cheapest)
   - Authentication: SSH public key
   - Select inbound ports: SSH (22)
   - Click "Next" through tabs, then "Review + Create"

#### Option B: Using Azure CLI (Faster)

```bash
# Login to Azure
az login

# Create resource group
az group create --name rg-security-demo --location eastus

# Create storage account (intentionally insecure for demo)
az storage account create \
  --name secdemostorage$RANDOM \
  --resource-group rg-security-demo \
  --location eastus \
  --sku Standard_LRS \
  --allow-blob-public-access true \
  --https-only false

# Create NSG with insecure rule
az network nsg create \
  --resource-group rg-security-demo \
  --name nsg-demo

az network nsg rule create \
  --resource-group rg-security-demo \
  --nsg-name nsg-demo \
  --name allow-ssh-any \
  --priority 100 \
  --source-address-prefixes '*' \
  --destination-port-ranges 22 \
  --access Allow \
  --protocol Tcp

# Create public IP
az network public-ip create \
  --resource-group rg-security-demo \
  --name pip-demo
```

### 4. Configure Authentication

#### Azure CLI (Recommended)

```bash
# Login to Azure
az login

# Set your subscription
az account set --subscription "your-subscription-id"

# Verify
az account show
```

#### Environment Variables

```bash
# Copy example env file
cp .env.example .env

# Edit .env and add your keys
nano .env
```

Add:
```
GROQ_API_KEY=gsk_xxxxxxxxxxxxxxxxxxxxx
AZURE_SUBSCRIPTION_ID=your-subscription-id
```

Get your subscription ID:
```bash
az account show --query id -o tsv
```

### 5. Lancer le projet (Run the Agent)

**Résumé des étapes :**

1. **Créer et activer le virtual env** (une seule fois) :
   ```powershell
   cd c:\Users\MSI\mcp_project
   python -m venv venv
   .\venv\Scripts\Activate.ps1
   pip install -r requirements.txt
   ```

2. **Fichier `.env`** à la racine du projet avec :
   ```
   GROQ_API_KEY=gsk_xxxx
   AZURE_SUBSCRIPTION_ID=votre-subscription-id
   ```
   (Clé Groq : https://console.groq.com — Subscription ID : `az account show --query id -o tsv`)

3. **Se connecter à Azure** (dans le même terminal où vous lancez l’agent) :
   ```powershell
   az login
   ```

4. **Lancer l’agent** (avec le venv activé) :
   ```powershell
   python agent.py
   ```

5. Dans le menu, taper **6** pour un scan complet (découverte + analyse) sans saisir de noms de ressources.

**To show the agent working end-to-end:** Choose **6** (Full discovery and security scan). The agent will list resource groups, discover NSGs and storage accounts, run security checks, and return a report — no need to type resource names.

## 📋 Usage Examples

### Quick proof (no resource names needed)

1. Create a simple Azure setup: one resource group (e.g. `rg-security-demo`), one NSG with an “allow SSH from Any” rule, and one storage account with “Allow public blob access” enabled.
2. Run `python agent.py`, then choose **6** (Full discovery and security scan).
3. The agent will discover your resource groups, NSGs, and storage accounts, run security checks, and output a report with findings and recommendations.

### Example 1: Analyze NSG Rules

```
Enter command (1-5 or 'exit'): 2
Enter resource group name: rg-security-demo
Enter NSG name: nsg-demo
```

The agent will:
1. Call the `azure_check_nsg_rules` tool
2. Analyze all inbound/outbound rules
3. Flag dangerous configurations (open ports, wildcard sources)
4. Provide recommendations

### Example 2: Audit Storage Account

```
Enter command (1-5 or 'exit'): 3
Enter resource group name: rg-security-demo
Enter storage account name: secdemostorage12345
```

The agent will check:
- Public access settings
- HTTPS enforcement
- Encryption status
- TLS version

### Example 3: Custom Query

```
Enter command (1-5 or 'exit'): 5
Enter your security query: Find all resources with public access and tell me the risks
```

## 🛠️ Available Tools

The MCP server provides these tools:

**Discovery (use these first when you don’t know resource names):**
1. **azure_list_resource_groups** - List all resource groups in the subscription
2. **azure_list_nsgs** - List all NSGs (optionally in a resource group)
3. **azure_list_storage_accounts** - List all storage accounts (optionally in a resource group)
4. **azure_list_resources** - List all resources in subscription or resource group

**Analysis:**
5. **azure_check_nsg_rules** - Analyze NSG for security issues (open ports, wildcard rules)
6. **azure_check_storage_security** - Audit storage account configuration
7. **azure_list_public_ips** - Find all public IP addresses
8. **azure_check_vm_security** - Check VM security settings

## 🔍 What the Agent Detects

### Network Security
- ✓ Wildcard source addresses (*)
- ✓ Exposed dangerous ports (22, 3389, 1433, etc.)
- ✓ Overly permissive rules
- ✓ All ports open (*)

### Storage Security
- ✓ Public blob access enabled
- ✓ HTTPS-only not enforced
- ✓ Weak TLS versions
- ✓ Encryption status

### VM Security
- ✓ Missing managed identities
- ✓ Unencrypted disks
- ✓ Missing security extensions

### General
- ✓ Public IP exposure
- ✓ Resource misconfigurations
- ✓ CIS benchmark violations

## 📊 Sample Output

```
🤖 Agent analyzing: Analyze the NSG 'nsg-demo' in resource group 'rg-security-demo'

🔧 Executing: azure_check_nsg_rules
   Arguments: {
     "subscription_id": "xxxx",
     "resource_group": "rg-security-demo",
     "nsg_name": "nsg-demo"
   }
   ✓ Result: {
     "nsg_name": "nsg-demo",
     "issues_found": 2,
     "security_issues": [
       {
         "severity": "HIGH",
         "rule_name": "allow-ssh-any",
         "issue": "Inbound rule allows traffic from any source (*)",
         "destination_port": "22",
         "recommendation": "Restrict source IP addresses to specific ranges"
       },
       {
         "severity": "HIGH",
         "rule_name": "allow-ssh-any",
         "issue": "Potentially dangerous port 22 is exposed",
         "recommendation": "Consider restricting access to port 22 or using VPN/bastion"
       }
     ]
   }

============================================================
FINAL ANALYSIS
============================================================

⚠️ SECURITY ANALYSIS: NSG 'nsg-demo'

I found 2 HIGH severity security issues:

1. **Wildcard Source Address** (HIGH)
   - Rule: allow-ssh-any
   - Problem: Allows inbound traffic from ANY source (*)
   - Risk: Exposes SSH to the entire internet
   - Recommendation: Restrict to your office/home IP or use Azure Bastion

2. **Exposed SSH Port** (HIGH)
   - Port 22 is publicly accessible
   - Risk: Brute force attacks, unauthorized access attempts
   - Recommendation: Use Azure Bastion, VPN, or at minimum restrict source IPs

📋 Action Items:
- Immediately restrict the source IP range for SSH access
- Consider implementing Azure Bastion for secure VM access
- Review all NSG rules for least privilege principle
```

## 🔐 Security Best Practices

1. **Never commit `.env` file** - It contains secrets
2. **Use Azure CLI for local development** - Easiest auth method
3. **Use service principals for production** - More secure
4. **Review agent recommendations** - Human oversight is important
5. **Test on non-production first** - Always test safely

## 🚧 Extending the Agent

### Adding New Tools

Edit `server.py` and add new tool functions:

```python
@app.list_tools()
async def list_tools() -> list[Tool]:
    return [
        # ... existing tools ...
        Tool(
            name="azure_check_sql_security",
            description="Check Azure SQL database security",
            inputSchema={...}
        )
    ]

async def check_sql_security(args: dict) -> list[TextContent]:
    # Implement SQL security checks
    pass
```

### Adding More Azure Services

Install additional Azure SDK packages:
```bash
pip install azure-mgmt-sql azure-mgmt-keyvault azure-mgmt-web
```

Then add clients in `server.py`:
```python
from azure.mgmt.sql import SqlManagementClient
```

## 📝 Troubleshooting

### Nothing displays when I run `python agent.py`
- You should see at least: `Azure Security Agent — starting...` then `Starting MCP server...` then `Connecting to MCP server...`. If you see nothing at all, run from the project folder: `cd c:\Users\MSI\mcp_project` and ensure your venv is activated.
- If it stops at **Connecting to MCP server...** and hangs, the MCP handshake may be stuck (e.g. server and client waiting on each other). Try running again; if it persists, check that `server.py` runs alone: `python server.py` (it will wait for stdin — that’s normal; press Ctrl+C to exit).
- If it asks for **Azure Subscription ID**, type your subscription ID and press Enter (or add `AZURE_SUBSCRIPTION_ID` to `.env`).

### "Failed to initialize Azure clients"
- Run `az login` to authenticate
- Verify subscription ID is correct
- Check Azure permissions (Reader role minimum)

### "Error: GROQ_API_KEY not found"
- Create `.env` file from `.env.example`
- Add your Groq API key from console.groq.com

### "Resource not found"
- Verify resource names are correct
- Check you're using the right subscription
- Ensure resource group exists

### Rate Limiting
- Groq free tier: 30 requests/minute
- Add delays if needed
- Use smaller queries

## 🎯 Next Steps

1. **Add more security checks:**
   - Key Vault configuration
   - SQL database security
   - App Service settings
   - Kubernetes cluster security

2. **Implement CIS benchmarks:**
   - Azure CIS Benchmark v2.0
   - Automated compliance scoring
   - Remediation scripts

3. **Add visualization:**
   - Security score dashboard
   - Risk heat maps
   - Compliance reports

4. **Multi-cloud support:**
   - AWS security tools
   - GCP security tools
   - Cross-cloud comparison

## 📚 Resources

- [MCP Documentation](https://modelcontextprotocol.io/)
- [Azure SDK for Python](https://docs.microsoft.com/en-us/azure/developer/python/)
- [Groq API Documentation](https://console.groq.com/docs)
- [CIS Azure Benchmark](https://www.cisecurity.org/benchmark/azure)

## 📄 License

MIT License - Feel free to use and modify for your project!

## 🤝 Contributing

This is a demo project for learning. Feel free to extend it for your needs!

---

**Note**: This is a simple demonstration. For production use, add:
- Error handling
- Logging
- Rate limiting
- Caching
- Comprehensive test coverage
- Remediation automation