Skip to main content
Glama
README.md
# šŸ” Zomato Voice Bot (MCP-Powered)

An interactive, voice-activated food ordering bot powered by the **Model Context Protocol (MCP 2.x)**. Users can speak naturally to search restaurants, build food carts, handle out-of-stock item replacements interactively, calculate the best discounts/coupons, and confirm the exact final best amount before placing the order.

---

## 🌟 Key Features

1. **Model Context Protocol (MCP 2.x) Integration**:
   - Implements standard MCP tools:
     - `search_restaurants`: Discover restaurants by cuisine, rating, budget, and location.
     - `get_menu`: Browse categories, dishes, prices, and food details.
     - `check_item_availability`: Real-time stock verification with automatic alternative recommendations.
     - `add_to_cart`: Add items with quantity and customization options.
     - `calculate_best_amount`: Evaluates all coupons (`ZOMATO50`, `FEAST150`, `GOLDDELIVERY`, `JUMBO200`), maximizes discounts, calculates delivery fees, taxes, and generates the voice confirmation phrase.
     - `confirm_and_place_order`: Places order only after final user agreement, generating Order ID and payment QR.
     - `track_order`: Live order tracking and delivery partner status.
   - Dual-mode support: Runs with the built-in local MCP server or connects to the remote Zomato MCP endpoint (`https://mcp-server.zomato.com/mcp`).

2. **Interactive Voice Assistance (STT & TTS)**:
   - **Speech Recognition**: Voice input via Web Speech API in the browser or terminal input.
   - **Natural Voice Feedback**: Spoken audio replies (English with Indian accent `en-IN` / `gTTS` / SpeechSynthesis).
   - **Visual Voice Orb**: Pulsing glowing voice orb with animated sound rings and waveform bars reacting to speech.

3. **Smart Missing & Out-of-Stock Handling**:
   - If an item is unavailable (e.g. Garlic Naan at Paradise Biryani or Cheesy Dip at Domino's), the bot **does not fail or drop it silently**.
   - It actively speaks:
     > *"However, Garlic Naan is currently out of stock at Paradise Biryani. They have Butter Naan (₹45) and Tandoori Roti (₹30) available. Would you like me to add one of these instead, or skip it?"*
   - Listens to the user's answer ("Yes, add butter naan instead" or "Skip it") and updates the order state seamlessly.

4. **Mandatory Final Best Amount Confirmation**:
   - The bot automatically evaluates all coupons, applies the biggest discount, and speaks the exact final amount:
     > *"You have 2x Chicken Dum Biryani and 1x Butter Naan from Paradise Biryani. The subtotal is ₹605. With coupon FEAST150 applied saving ₹150, including delivery and taxes, your final best amount is ₹497. Should I confirm and place your order?"*
   - Waits for the user's voice confirmation (*"Yes, place order"*).

5. **Production-Grade Persistence & Agent Memory**:
    - **Database Architecture**: Async SQLAlchemy 2.0 with high-throughput SQLite (`journal_mode=WAL`) or PostgreSQL.
    - **Persistent Active Cart**: Food items and pricing breakdown remain intact across browser tabs, reloads, and server restarts.
    - **Long-term Agent Memory**: Autonomously learns dietary preferences (Veg/Non-Veg), preferred payment methods (UPI/Zomato Money/COD), favorite restaurants, and favorite dishes across voice sessions.
    - **Order History & Audit Trail**: Real-time order records with tracking URLs and payment states (including live order `#8585879147`).
    - **MCP Tool Call Auditing**: Every tool invocation is logged with execution duration (`duration_ms`), arguments, and status in `mcp_audit_logs`.

6. **Modern Web Voice Console & Terminal CLI**:
   - **Web UI (`http://localhost:8000`)**: Full-screen foodie dark theme with live Cart sidebar, Best Offer badge, real-time MCP tool call inspector, Orders History modal, and Memory Profile manager.
   - **Terminal CLI (`./run.sh cli`)**: Lightweight command-line interface with spoken audio.

---

## šŸš€ Quick Start

### 1. Run the Web Voice Assistant
```bash
./run.sh
# or
./run.sh web
```
Open your browser at **`http://localhost:8000`**. Tap the microphone icon or say:
> *"Order 2 chickpea salads from Lulu Hypermarket"*

### 2. Run the Terminal Voice Assistant
```bash
./run.sh cli
```

### 3. Run the Automated Test Suite
```bash
./run.sh test
# or
.venv/bin/pytest -v tests/
```

### 4. Run the Zomato MCP Server directly via stdio
```bash
./run.sh mcp
```

---

## šŸ”Œ Production REST API Endpoints

- **`GET /health`**: Production health check reporting uptime, database connectivity, and MCP server status.
- **`GET /api/orders`**: Retrieves historical and current orders with items, pricing, and live tracking links.
- **`GET /api/memory`**: Fetches long-term user preferences, favorite dishes, and dietary habits.
- **`POST /api/memory/preference`**: Explicitly updates dietary, payment, or restaurant preferences.
- **`GET /api/audit/logs`**: Audits all MCP tool executions with millisecond latency timings.
- **`GET /api/conversation/{session_id}`**: Retrieves chat history for multi-turn session persistence.

---

## šŸ—£ļø Example Voice Walkthrough

| User Voice Input | Bot Voice Response | MCP Tool Call |
| :--- | :--- | :--- |
| šŸŽ¤ *"Order 2 chicken biryanis and garlic naan from Paradise Biryani"* | šŸ”Š *"I've added 2x Chicken Dum Biryani to your cart. However, Garlic Naan is currently not available at Paradise Biryani. They have Butter Naan (₹45) and Tandoori Roti (₹30) available. Would you like me to add one of these instead, or skip it?"* | `tools/call check_item_availability`<br>`tools/call add_to_cart` |
| šŸŽ¤ *"Yes, add butter naan instead"* | šŸ”Š *"Added Butter Naan as replacement! You have 2x Chicken Dum Biryani, 1x Butter Naan from Paradise Biryani. The food subtotal is ₹605. With coupon FEAST150 applied saving ₹150, including delivery and taxes, your final best amount is ₹497. Should I confirm and place your order?"* | `tools/call add_to_cart`<br>`tools/call calculate_best_amount` |
| šŸŽ¤ *"Yes, place order"* | šŸ”Š *"Order placed successfully! Your Zomato Order ID is ZOM-0F7F4C. Arriving in approximately 30 to 35 minutes. Total amount of ₹497 will be processed via UPI."* | `tools/call confirm_and_place_order` |
| šŸŽ¤ *"What did I order earlier?"* | šŸ”Š *"You have 1 previous order on record: Order #8585879147 from Lulu Hypermarket for ₹144.0. Track it here: https://zoma.to/t/GEAjkmaO"* | DB query `OrderRecord` |

---

## āš™ļø Configuration (`.env`)

```env
# Database URL (SQLite WAL default or PostgreSQL)
DATABASE_URL=sqlite+aiosqlite:///./zomato_bot.db

# Optional: Gemini API Key
GEMINI_API_KEY=
GEMINI_MODEL=gemini-2.5-flash

# MCP Mode: "local" or "remote"
ZOMATO_MCP_MODE=remote
ZOMATO_MCP_REMOTE_URL=https://mcp-server.zomato.com/mcp
ZOMATO_MCP_AUTH_TOKEN=your_token_here
```

---

## šŸ“‚ Project Structure

```
zomato_bot/
ā”œā”€ā”€ zomato_bot/
│   ā”œā”€ā”€ config.py             # App, DB & MCP configuration
│   ā”œā”€ā”€ audio.py              # CLI text-to-speech audio engine
│   ā”œā”€ā”€ cli.py                # Terminal voice ordering console
│   ā”œā”€ā”€ db/
│   │   ā”œā”€ā”€ session.py        # Async engine, connection pool & WAL pragmas
│   │   └── models.py         # SQLAlchemy 2.0 models (Session, Cart, Order, Memory, Audit)
│   ā”œā”€ā”€ memory/
│   │   └── service.py        # Long-term preference learning & persistent cart/order CRUD
│   ā”œā”€ā”€ mcp/
│   │   ā”œā”€ā”€ server.py         # Official MCP 2.x Server implementation
│   │   ā”œā”€ā”€ client.py         # MCP Client with async tool auditing
│   │   ā”œā”€ā”€ tools.py          # Restaurant, menu, cart & checkout logic
│   │   └── data.py           # Restaurant, menu, coupon data
│   ā”œā”€ā”€ agent/
│   │   ā”œā”€ā”€ bot.py            # Unified agent interface
│   │   ā”œā”€ā”€ nlp_fallback.py   # Multi-turn voice conversation & intent manager
│   │   └── prompts.py        # System prompt & voice dialogue rules
│   └── web/
│       ā”œā”€ā”€ app.py            # FastAPI REST & WebSocket endpoints with lifespan
│       ā”œā”€ā”€ templates/
│       │   └── index.html    # Interactive Voice UI with Orders & Memory modals
│       └── static/
│           ā”œā”€ā”€ css/style.css # Zomato dark theme styling
│           └── js/
│               ā”œā”€ā”€ voice.js  # Web Speech API STT/TTS engine
│               └── app.js    # UI, persistence syncing, Orders & Memory handlers
ā”œā”€ā”€ tests/                    # 16-test suite covering MCP, Agent, API & DB Persistence
ā”œā”€ā”€ run.sh                    # Launcher script
└── README.md
```

Maintenance

ActivityMaintained
ResponsivenessNo issues