Skip to main content
Glama
kalavakuntabharathkumar

AI Agent Automation Hub MCP Server

README.md
# AI Agent Automation Hub — MCP-Based Multi-Tool Backend Platform

A production-quality personal expense tracker whose REST endpoints are also exposed as
**MCP (Model Context Protocol) tools**, enabling AI agents (Claude, GPT-4) to add, query,
and summarise expenses through natural language. Includes a LangChain agent layer and an
n8n scheduled workflow for daily email summaries.

**Built:** April 2 – April 4, 2026  
**Author:** Bharath Kumar Kalavakunta

---

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                      AI Agent Automation Hub                    │
│                                                                 │
│  ┌──────────────┐    ┌───────────────┐    ┌─────────────────┐  │
│  │  FastAPI App  │    │  MCP Server   │    │ LangChain Agent │  │
│  │  (Port 8000) │◄───│  (Port 8001)  │◄───│  (OpenAI/       │  │
│  │              │    │               │    │   Anthropic)    │  │
│  │  /api/...    │    │  add_expense  │    │                 │  │
│  │  CRUD + auth │    │  get_expenses │    │ "Add ₹500       │  │
│  └──────┬───────┘    │  get_summary  │    │  grocery"       │  │
│         │            │  delete_exp.  │    └─────────────────┘  │
│         │            └───────────────┘                         │
│  ┌──────▼───────┐                                              │
│  │  PostgreSQL  │    ┌───────────────┐    ┌─────────────────┐  │
│  │  (or SQLite) │    │  Django Admin  │    │  n8n Workflow   │  │
│  └──────────────┘    │  (Port 8080)  │    │  Daily Summary  │  │
│                      │  /admin/      │    │  → Email/Slack  │  │
│                      └───────────────┘    └─────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
```

---

## Project Structure

```
AI-Agent-Automation-Hub/
├── fastapi_app/            # Core REST API (FastAPI + SQLAlchemy)
│   ├── main.py             # App entry point, router registration
│   ├── models.py           # SQLAlchemy ORM models (User, Expense)
│   ├── schemas.py          # Pydantic request/response schemas
│   ├── database.py         # DB engine, session, init_db()
│   ├── auth.py             # JWT auth, password hashing
│   └── routers/
│       ├── expenses.py     # CRUD + summary endpoints
│       ├── users.py        # Register, login, /me
│       └── agent.py        # POST /api/agent/query
│
├── django_app/             # Django admin panel + auth
│   ├── manage.py
│   ├── config/             # Django project settings, URLs, WSGI
│   └── expenses/           # Django app: models, admin, views, URLs
│
├── mcp_server/             # MCP server wrapping FastAPI as tools
│   ├── server.py           # MCP tool definitions + server loop
│   └── example_client.py   # End-to-end demo client
│
├── agent/                  # LangChain agent layer
│   ├── agent.py            # AgentExecutor, OpenAI/Anthropic switch
│   └── tools.py            # LangChain Tool wrappers around REST API
│
├── n8n_workflow/           # n8n automation workflow
│   ├── workflow.json       # Importable n8n workflow definition
│   └── README.md           # Setup and usage guide
│
├── seed.py                 # Seed script — 18 sample expenses
├── requirements.txt        # All Python dependencies
├── .env.example            # Environment variable template
└── README.md               # This file
```

---

## Quick Start

### 1. Clone and install dependencies

```bash
git clone https://github.com/kalavakuntabharathkumar/AI-Agent-Automation-Hub-MCP-Based-Multi-Tool-Backend-Platform.git
cd AI-Agent-Automation-Hub-MCP-Based-Multi-Tool-Backend-Platform

python -m venv venv
source venv/bin/activate        # Windows: venv\Scripts\activate
pip install -r requirements.txt
```

### 2. Configure environment

```bash
cp .env.example .env
# Edit .env with your database URL and API keys
```

### 3. Start the FastAPI server

```bash
uvicorn fastapi_app.main:app --reload --port 8000
```

The API is now live at `http://localhost:8000`.  
Interactive docs: `http://localhost:8000/api/docs`

### 4. Start the Django admin panel

```bash
# Apply migrations
python -m django_app.manage migrate --settings=django_app.config.settings

# Create a superuser
python -m django_app.manage createsuperuser --settings=django_app.config.settings

# Run Django dev server
python -m django_app.manage runserver 8080 --settings=django_app.config.settings
```

Django admin: `http://localhost:8080/admin/`  
Expense dashboard: `http://localhost:8080/dashboard/`

### 5. Seed sample data

```bash
# Ensure the FastAPI server is running first
python seed.py
```

Adds 18 sample expenses across 8 categories. Demo credentials:
- **Username:** `demo_user`
- **Password:** `demopassword123`

---

## API Reference

### Authentication

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/auth/register` | Create a new user account |
| `POST` | `/api/auth/login` | Login and receive a JWT token |
| `GET`  | `/api/auth/me` | Get current user profile |

All expense endpoints require `Authorization: Bearer <token>`.

### Expenses

| Method   | Endpoint | Description |
|----------|----------|-------------|
| `POST`   | `/api/expenses/` | Create a new expense |
| `GET`    | `/api/expenses/` | List expenses (filterable) |
| `GET`    | `/api/expenses/summary` | Spending summary by category |
| `GET`    | `/api/expenses/{id}` | Get a single expense |
| `PUT`    | `/api/expenses/{id}` | Update an expense |
| `DELETE` | `/api/expenses/{id}` | Delete an expense |

**Query parameters for `GET /api/expenses/`:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `category` | string | Filter by category (partial match) |
| `start_date` | date | Start of date range (YYYY-MM-DD) |
| `end_date` | date | End of date range (YYYY-MM-DD) |
| `limit` | integer | Max results (default 50, max 200) |

**Query parameters for `GET /api/expenses/summary`:**

| Parameter | Type | Values |
|-----------|------|--------|
| `period` | string | `week` \| `month` \| `year` \| `all` |

### AI Agent

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/agent/query` | Submit a natural language instruction |

**Request body:**
```json
{ "query": "How much did I spend on groceries this month?" }
```

---

## MCP Tool Schemas

The MCP server (`mcp_server/server.py`) exposes four tools:

### `add_expense`

```json
{
  "name": "add_expense",
  "inputSchema": {
    "type": "object",
    "required": ["amount", "category"],
    "properties": {
      "amount":      { "type": "number",  "description": "Amount in INR (positive)" },
      "category":    { "type": "string",  "description": "Expense category" },
      "description": { "type": "string",  "description": "Optional note" },
      "date":        { "type": "string",  "format": "date", "description": "YYYY-MM-DD, defaults to today" }
    }
  }
}
```

### `get_expenses`

```json
{
  "name": "get_expenses",
  "inputSchema": {
    "type": "object",
    "properties": {
      "category":   { "type": "string" },
      "start_date": { "type": "string", "format": "date" },
      "end_date":   { "type": "string", "format": "date" },
      "limit":      { "type": "integer", "minimum": 1, "maximum": 200 }
    }
  }
}
```

### `get_summary`

```json
{
  "name": "get_summary",
  "inputSchema": {
    "type": "object",
    "properties": {
      "period": { "type": "string", "enum": ["week", "month", "year", "all"] }
    }
  }
}
```

### `delete_expense`

```json
{
  "name": "delete_expense",
  "inputSchema": {
    "type": "object",
    "required": ["expense_id"],
    "properties": {
      "expense_id": { "type": "integer" }
    }
  }
}
```

---

## LangChain Agent — Example Commands

| Natural Language Input | Expected Response |
|------------------------|-------------------|
| `Add ₹500 grocery expense` | "Added ₹500 expense under 'Groceries' ✅ ID: 21, Date: 2026-04-03" |
| `How much did I spend this month?` | "Spending summary for this month: Total ₹8,456.50 across 17 transactions..." |
| `Show all transport expenses` | Lists all expenses in the Transport category |
| `Delete expense #5` | "Expense #5 deleted successfully. ✅" |
| `What's my biggest spending category this week?` | Calls get_summary with period=week and interprets results |

### Running the agent via CLI

```bash
python -m agent.agent "Add ₹750 food expense — dinner at a restaurant"
python -m agent.agent "How much did I spend on transport this week?"
python -m agent.agent "Show my last 5 expenses"
```

### Running via the REST endpoint

```bash
TOKEN="your_jwt_token_here"

curl -X POST http://localhost:8000/api/agent/query \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query": "Summarise my expenses for this month"}'
```

---

## Switching AI Providers

Set `AI_PROVIDER` in your `.env` file:

```bash
# Use OpenAI (default)
AI_PROVIDER=openai
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4o-mini

# Use Anthropic Claude
AI_PROVIDER=anthropic
ANTHROPIC_API_KEY=sk-ant-...
ANTHROPIC_MODEL=claude-3-5-haiku-20241022
```

---

## Deploying to AWS EC2 (Ubuntu)

### 1. Launch EC2 Instance

- AMI: Ubuntu 24.04 LTS
- Instance type: `t3.small` or larger
- Security group: open ports **22** (SSH), **8000** (FastAPI), **8080** (Django), **8001** (MCP)

### 2. Install Dependencies

```bash
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3.11 python3.11-venv python3-pip postgresql postgresql-contrib

# Create DB
sudo -u postgres psql -c "CREATE USER expenseuser WITH PASSWORD 'yourpassword';"
sudo -u postgres psql -c "CREATE DATABASE expense_tracker OWNER expenseuser;"

# Clone and set up
git clone https://github.com/kalavakuntabharathkumar/AI-Agent-Automation-Hub-MCP-Based-Multi-Tool-Backend-Platform.git
cd AI-Agent-Automation-Hub-MCP-Based-Multi-Tool-Backend-Platform
python3.11 -m venv venv && source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env && nano .env   # fill in DATABASE_URL, API keys
```

### 3. Run FastAPI with Gunicorn + Uvicorn

```bash
gunicorn fastapi_app.main:app \
  -w 4 \
  -k uvicorn.workers.UvicornWorker \
  --bind 0.0.0.0:8000 \
  --daemon \
  --access-logfile /var/log/expense_api.log
```

### 4. MCP Server as a systemd Service

Create `/etc/systemd/system/mcp-server.service`:

```ini
[Unit]
Description=Expense Tracker MCP Server
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/AI-Agent-Automation-Hub-MCP-Based-Multi-Tool-Backend-Platform
Environment=PATH=/home/ubuntu/AI-Agent-Automation-Hub-MCP-Based-Multi-Tool-Backend-Platform/venv/bin
ExecStart=/home/ubuntu/AI-Agent-Automation-Hub-MCP-Based-Multi-Tool-Backend-Platform/venv/bin/python -m mcp_server.server
Restart=always

[Install]
WantedBy=multi-user.target
```

```bash
sudo systemctl daemon-reload
sudo systemctl enable mcp-server
sudo systemctl start mcp-server
```

### 5. Django Admin

```bash
python -m django_app.manage migrate --settings=django_app.config.settings
python -m django_app.manage collectstatic --settings=django_app.config.settings
gunicorn django_app.config.wsgi:application --bind 0.0.0.0:8080 --daemon
```

### 6. Security Hardening

```bash
# Configure UFW firewall
sudo ufw allow 22/tcp
sudo ufw allow 8000/tcp
sudo ufw allow 8080/tcp
sudo ufw enable

# Use Nginx as a reverse proxy (recommended for production)
sudo apt install nginx
# Configure /etc/nginx/sites-available/expense-tracker to proxy to ports 8000 and 8080
```

---

## Environment Variables Reference

| Variable | Required | Description |
|----------|----------|-------------|
| `DATABASE_URL` | Yes | PostgreSQL or SQLite connection string |
| `DJANGO_SECRET_KEY` | Yes | Django secret key |
| `JWT_SECRET_KEY` | Yes | FastAPI JWT signing key |
| `AI_PROVIDER` | Yes | `openai` or `anthropic` |
| `OPENAI_API_KEY` | If using OpenAI | OpenAI API key |
| `ANTHROPIC_API_KEY` | If using Anthropic | Anthropic API key |
| `FASTAPI_BASE_URL` | Yes | Base URL of FastAPI server for MCP/agent |
| `N8N_WEBHOOK_URL` | Optional | n8n webhook URL for automation triggers |
| `NOTIFICATION_EMAIL` | Optional | Email for daily summary reports |

---

## License

MIT License — free to use, modify, and distribute.