Skip to main content
Glama
0xConsole

DeFi Sentinel X MCP Server

by 0xConsole
README.md
# πŸ›°οΈ DeFi Sentinel X

**Autonomous AI Agent for X Layer DeFi Protocol Monitoring**

An autonomous AI agent that monitors X Layer (OKX's EVM-compatible L2, chainId 196) DeFi protocols in real-time β€” detecting price manipulation, liquidity drains, and unusual trading activity, then generating severity-classified alerts with on-chain risk scores.

Built for the **OKX BuildX AI Season Hackathon** ($300K prize pool).

## 🎯 Problem

DeFi protocols on X Layer are vulnerable to attacks that execute in seconds:
- **Price manipulation** via sandwich attacks and oracle manipulation
- **Liquidity drains** from pool imbalances and rug pulls
- **Unusual trading** from MEV bots and exploit frontrunning

Users have no real-time early warning system. By the time a human notices a
pool's reserves dropping, the damage is done. Existing monitoring tools are
either centralized alerts (slow) or static dashboards (passive).

## πŸ’‘ Solution

**DeFi Sentinel X** is an autonomous AI agent that:

1. **Continuously scans** X Layer DeFi pools via real on-chain RPC calls
2. **Detects anomalies** using statistical heuristics (reserve imbalance, liquidity drain, unusual activity)
3. **Computes risk scores** (0-100 composite score) factoring anomaly severity, confidence, and type diversity
4. **Generates alerts** with severity classification and recommended actions
5. **Checks position health** for Aave V3 lending positions (health factor, liquidation distance)

The agent uses an **MCP-style tool architecture** β€” each capability is a
discrete tool with a JSON Schema input definition, orchestrated by an
agent layer that chains: `scan_pool β†’ detect_anomaly β†’ calculate_risk_score β†’ generate_alert`.

## 🌟 Unique Angle

Unlike passive monitoring dashboards, DeFi Sentinel X is an **active AI
agent** that:

- Uses **real X Layer RPC** (live block numbers, gas prices, eth_call against pool contracts)
- Follows the **MCP (Model Context Protocol) tool pattern** β€” 7 tools, each with name, description, and JSON Schema input, callable individually or orchestrated by the agent
- Runs **fully on free-tier infrastructure** (Vercel serverless + SQLite /tmp + public RPCs)
- Provides **deterministic, reproducible** agent orchestration (no LLM API key needed for the demo β€” the tool-chaining logic is the AI layer)
- Deploys as a **Vercel serverless function** β€” no servers, no cost, scales to zero

## πŸ—οΈ Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                 DeFi Sentinel X Agent                β”‚
β”‚          (Autonomous Tool Orchestrator)              β”‚
β”‚                                                      β”‚
β”‚  scan_pool β†’ detect_anomaly β†’ risk_score β†’ alert    β”‚
β”‚                                                      β”‚
β”‚  Additional: get_position_health, get_chain_status  β”‚
β”‚             get_audit_trail                          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚                      β”‚
       β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
       β”‚  X Layer RPC  β”‚    β”‚  SQLite (/tmp)  β”‚
       β”‚  (real data)  β”‚    β”‚  (audit trail)  β”‚
       β”‚               β”‚    β”‚                 β”‚
       β”‚ eth_chainId   β”‚    β”‚ scans table     β”‚
       β”‚ eth_blockNum  β”‚    β”‚ anomalies tbl   β”‚
       β”‚ eth_call      β”‚    β”‚ alerts table    β”‚
       β”‚ eth_getBalanceβ”‚    β”‚ risk_assess tbl β”‚
       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
       β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”
       β”‚   Vercel      β”‚
       β”‚  Serverless   β”‚
       β”‚  (@vercel/py) β”‚
       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### MCP Tool Architecture (7 Tools)

| # | Tool | Method | Description |
|---|------|--------|-------------|
| 1 | `scan_pool` | GET | Scan a DeFi pool for live reserves & TVL from X Layer RPC |
| 2 | `detect_anomaly` | GET | Run anomaly detection heuristics on pool data |
| 3 | `calculate_risk_score` | GET | Compute composite risk score (0-100) for a pool |
| 4 | `generate_alert` | GET/POST | Generate a severity-classified alert from an anomaly |
| 5 | `get_position_health` | GET | Check Aave V3 lending position health factor |
| 6 | `get_chain_status` | GET | Get live X Layer chain metadata (block, gas) |
| 7 | `get_audit_trail` | GET | Retrieve stored scan/anomaly/alert history |

All tools are also exposed via MCP protocol endpoints:
- `GET /mcp/tools` β€” MCP tools/list
- `POST /mcp/call` β€” MCP tools/call (body: `{"name": "...", "arguments": {...}}`)

## πŸ› οΈ Tech Stack

| Component | Technology | Why |
|-----------|-----------|-----|
| **API Framework** | FastAPI 0.115 | Async, auto-docs, Pydantic validation |
| **Hosting** | Vercel (serverless) | Free tier, auto-scaling, zero config |
| **Chain Data** | X Layer RPC (real) | Live on-chain data, no API key needed |
| **Persistence** | SQLite (/tmp) | Serverless-friendly, no external DB |
| **Agent Pattern** | MCP-style tools | Standardized tool interface |
| **Frontend** | Vanilla HTML/CSS/JS | No framework, fast load, simple deploy |
| **Language** | Python 3.12 | Vercel Python runtime |

## βœ… What's Real vs ⚠️ Mocked

### βœ… Real (Live On-Chain)

- **X Layer RPC calls** β€” `eth_chainId`, `eth_blockNumber`, `eth_gasPrice` return live data (chainId 196, current block ~67M)
- **eth_call** against pool contracts β€” `getReserves()`, `totalSupply()` selectors sent to real X Layer contracts
- **eth_getBalance** β€” real native balance reads for wallet health checks
- **SQLite persistence** β€” scans, anomalies, alerts, and risk assessments stored in `/tmp/defi_sentinel_x.db` (survives across warm serverless invocations)
- **Anomaly detection heuristics** β€” reserve imbalance, liquidity drain, zero liquidity, unusual activity detection run on real pool data
- **Composite risk scoring** β€” 0-100 score with severity classification (CRITICAL/HIGH/MODERATE/LOW/MINIMAL)
- **Agent orchestration** β€” tool-chaining logic: scan β†’ detect β†’ score β†’ alert (the AI layer)

### ⚠️ Mocked / Simulated

- **Pool reserve values** β€” if `eth_call` returns zeros (demo pool addresses aren't real Uniswap pairs on X Layer), falls back to **deterministic simulation** based on pool name + block number (reproducible, varies as blocks advance)
- **Aave V3 health factor** β€” derived from address hash (real Aave integration requires `Pool.getUserAccountData()` which needs a funded position; the `eth_getBalance` call IS real)
- **Baseline reserve ratios** β€” hardcoded (production would use a time-series DB like TimescaleDB)
- **"Unusual activity" heuristic** β€” uses block-number parity as a proxy for tx volume (production would use mempool/trace data)
- **No LLM API key** β€” the agent orchestration is deterministic (reproducible in serverless without external API dependencies)

## πŸš€ Quick Start

### Local Development

```bash
cd defi-sentinel-x
pip install -r requirements.txt
uvicorn app.main:app --reload --port 8000
# Open http://localhost:8000
```

### API Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/` | GET | Dashboard UI |
| `/api/health` | GET | Health check + RPC status |
| `/api/agent/status` | GET | Agent config + tool inventory |
| `/api/demo` | GET | Full autonomous agent demo (sweeps all pools) |
| `/api/sweep` | POST | Single-pool monitoring sweep |
| `/mcp/tools` | GET | MCP tools/list |
| `/mcp/call` | POST | MCP tools/call |
| `/api/tools/scan_pool` | GET | Scan a pool |
| `/api/tools/detect_anomaly` | GET | Detect anomalies |
| `/api/tools/calculate_risk_score` | GET | Compute risk score |
| `/api/tools/generate_alert` | GET/POST | Generate alert |
| `/api/tools/get_position_health` | GET | Check position health |
| `/api/tools/get_chain_status` | GET | Live chain metadata |
| `/api/tools/get_audit_trail` | GET | Stored history |
| `/api/audit` | GET | Full audit trail |
| `/api/stats` | GET | Aggregate stats |
| `/docs` | GET | Swagger UI |

### Deploy to Vercel

```bash
vercel --prod --yes --token "$VERCEL_TOKEN"
```

## πŸ”— Links

- **Live Demo:** [https://defi-sentinel-x.vercel.app](https://defi-sentinel-x.vercel.app)
- **GitHub:** [https://github.com/0xConsole/defi-sentinel-x](https://github.com/0xConsole/defi-sentinel-x)
- **X Layer:** [https://www.okx.com/xlayer](https://www.okx.com/xlayer)
- **Hackathon:** OKX BuildX AI Season ($300K)

## πŸ“ Project Structure

```
defi-sentinel-x/
β”œβ”€β”€ api/
β”‚   └── index.py              # Vercel entry point
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ main.py               # FastAPI app + routes
β”‚   β”œβ”€β”€ tools.py              # MCP tool registry + handlers (7 tools)
β”‚   β”œβ”€β”€ agent.py              # Agent orchestrator (tool-chaining)
β”‚   β”œβ”€β”€ xlayer_client.py      # X Layer RPC client (real on-chain reads)
β”‚   └── store.py              # SQLite persistence layer
β”œβ”€β”€ static/
β”‚   └── index.html            # Dark-theme dashboard UI
β”œβ”€β”€ vercel.json               # Vercel config
β”œβ”€β”€ requirements.txt          # Python deps
β”œβ”€β”€ SUBMISSION.md             # Hackathon submission fields
└── README.md                 # This file
```

## πŸ“œ License

MIT License β€” see [LICENSE](LICENSE)

---

Built by [0xConsole](https://github.com/0xConsole) for the OKX BuildX AI Season Hackathon.