Expenses-Tracker---MCP-Server-_Client

Surya-KF/Expenses-Tracker---MCP-Server-_Client

3.2

If you are the rightful owner of Expenses-Tracker---MCP-Server-_Client and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

The MCP Expense Tracker is a modern expense tracking system utilizing FastMCP 2.0 and Streamlit, integrated with Google Gemini 2.5 Flash AI for intelligent natural language expense processing.

Tools
5
Resources
0
Prompts
0

💰 MCP Expense Tracker

A modern expense tracking system built with FastMCP 2.0 and Streamlit, featuring Google Gemini 2.5 Flash AI integration for intelligent natural language expense processing.

✨ Features

🏦 MCP Server (FastMCP 2.0)

  • Modern MCP Implementation: Latest FastMCP 2.0 with HTTP transport
  • SQLite Database: Robust local storage with proper indexing
  • Smart Categories: Predefined categories with intelligent subcategory mapping
  • Date Range Filtering: Flexible date-based expense queries
  • Currency Support: Native support for Indian Rupees (₹)
  • AI-Powered Analysis: Gemini integration for expense insights

🤖 AI Integration (Google Gemini 2.5 Flash)

  • Natural Language Processing: Parse expenses like "I spent 250 rupees on breakfast today"
  • Smart Date Recognition: Understands "today", "yesterday", "last week", "this month"
  • Intelligent Categorization: Auto-categorizes expenses from context
  • Conversational Interface: Chat-style interaction for expense management
  • Context-Aware Responses: AI responses based on your actual expense data

💻 Streamlit Web Client

  • Modern Chat Interface: WhatsApp-style conversation UI
  • Real-time Processing: Instant expense entry and retrieval
  • Dynamic Date Calculations: Automatic date range calculations
  • LangGraph Agent: Advanced AI agent with tool orchestration
  • Error Handling: Robust error handling with user-friendly messages

🎯 Smart Features

  • Week Calculation: Proper Monday-to-Sunday week definitions
  • Table Formatting: Beautiful expense tables with category breakdowns
  • Quick Commands: Sidebar with example queries
  • Session Persistence: Chat history maintained across interactions

🚀 Quick Start

1. Prerequisites

# Ensure you have Python 3.11+ installed
python --version

# Create virtual environment (recommended)
python -m venv .venv

# Activate virtual environment
# Windows:
.\.venv\Scripts\Activate.ps1
# Linux/Mac:
source .venv/bin/activate

2. Installation

# Install dependencies using uv (faster) or pip
uv pip install -r requirements.txt
# OR
pip install -r requirements.txt

3. Configuration

# Set your Google Gemini API key
# Get your key from: https://aistudio.google.com/app/apikey
set GOOGLE_API_KEY=your_actual_api_key_here
# OR Linux/Mac:
export GOOGLE_API_KEY=your_actual_api_key_here

4. Start the System

# Terminal 1: Start MCP Server
python server.py

# Terminal 2: Start Streamlit Client (in virtual environment)
.\.venv\Scripts\Activate.ps1
streamlit run client.py

5. Access the Applications

📖 Usage Guide

Streamlit Chat Interface

  1. Natural Language Expense Entry:

    "I spent 250 rupees on breakfast today"
    "Add ₹500 for groceries yesterday"
    "Paid ₹2000 for cab to native place on Oct 3"
    
  2. Smart Date Queries:

    "Show my expenses for last 10 days"
    "Summarize all my transactions for this week"
    "What did I spend this month?"
    "List expenses from last 30 days in tabular fashion"
    
  3. Category Analysis:

    "Analyze my spending patterns"
    "Show category breakdown for food expenses"
    "How much did I spend on transport?"
    
  4. Conversational Interface:

    • Type naturally in the chat box
    • Get instant responses with formatted tables
    • View category breakdowns and totals
    • Historical context maintained in chat

Example Interactions

Adding an Expense:

User: "I spent 150 rupees on cab fare today"
Assistant: ✅ Added expense: ₹150 for transport (cab) on 2025-10-07

Viewing Expenses:

User: "Show my last 7 days expenses"
Assistant: [Displays formatted table with 7 days of transactions]

Direct MCP Client Usage

Connect to the MCP server directly:

import asyncio
from fastmcp import Client

async def main():
    async with Client("http://localhost:8000/mcp") as client:
        # Add an expense
        result = await client.call_tool("add_expense", {
            "date": "2025-10-07",
            "amount": 250.0,
            "category": "food",
            "subcategory": "breakfast",
            "note": "Morning breakfast"
        })
        
        # List expenses for date range
        result = await client.call_tool("list_expenses", {
            "start_date": "2025-09-27",
            "end_date": "2025-10-07"
        })
        
        # Get expense summary
        result = await client.call_tool("get_expense_summary", {})
        
        # AI analysis
        result = await client.call_tool("analyze_expenses_with_ai", {
            "query": "What are my spending patterns this month?"
        })

asyncio.run(main())

🛠️ MCP Integration

FastMCP 2.0 Server

The system runs as a complete MCP server using FastMCP 2.0 with HTTP transport:

# The server runs automatically when you start server.py
# Accessible at: http://localhost:8000/mcp

Available MCP Tools

  • add_expense(date, amount, category, subcategory, note): Add new expense with validation
  • list_expenses(start_date?, end_date?, category?): List expenses with optional filtering
  • get_expense_summary(start_date?, end_date?, category?): Get category summaries and totals
  • delete_expense(expense_id): Remove expense by ID
  • analyze_expenses_with_ai(query): AI-powered expense analysis using Gemini

Tool Examples

# Add expense
await client.call_tool("add_expense", {
    "date": "2025-10-07",
    "amount": 250.0,
    "category": "food",
    "subcategory": "breakfast",
    "note": "Breakfast at cafe"
})

# List last 10 days
await client.call_tool("list_expenses", {
    "start_date": "2025-09-27",
    "end_date": "2025-10-07"
})

# Get summary for current month
await client.call_tool("get_expense_summary", {
    "start_date": "2025-10-01",
    "end_date": "2025-10-07"
})

📁 Project Structure

MCP/
├── server.py              # FastMCP 2.0 server with expense tools
├── client.py              # Streamlit chat interface with LangGraph agent
├── uv.lock               # Dependency lock file
├── data/
│   ├── expenses.db       # SQLite database with expenses
│   └── categories.json   # Category definitions
├── pyproject.toml         # Python dependencies and project metadata
└── README.md            

🔧 Configuration

Environment Variables

# Required for AI features
GOOGLE_API_KEY=your_gemini_api_key_here

# Optional: Custom MCP server URL for client
EXPENSE_MCP_URL=http://localhost:8000/mcp

Categories System

The system uses a hierarchical category structure defined in data/categories.json:

{
  "categories": {
    "food": ["groceries", "dining", "breakfast", "lunch", "dinner"],
    "transport": ["cab", "bus", "train", "fuel", "public_transport"],
    "shopping": ["clothing", "electronics", "household"],
    "healthcare": ["medical", "pharmacy", "fitness"],
    "utilities": ["electricity", "water", "internet", "phone"],
    "entertainment": ["movies", "games", "books"],
    "education": ["courses", "materials", "books"],
    "housing": ["rent", "maintenance", "utilities"],
    "other": ["miscellaneous"]
  }
}

Smart Categorization

The AI automatically maps natural language to categories:

  • "breakfast", "lunch", "dinner" → food
  • "cab", "taxi", "uber", "bus" → transport
  • "medicine", "doctor", "pharmacy" → healthcare

🚦 Running Options

Standard Setup (Recommended)

# Terminal 1: MCP Server
python server.py

# Terminal 2: Streamlit Client (ensure virtual environment is active)
.\.venv\Scripts\Activate.ps1
streamlit run client.py

Development Mode

# Run server with debug output
python server.py --debug

# Run Streamlit on custom port
streamlit run client.py --server.port 8502

🔍 MCP Server Endpoints

MCP Protocol

  • POST /mcp - Main MCP endpoint for tool calls
  • GET /mcp - MCP capabilities and tool listings

Available Tools via MCP

  1. add_expense - Add new expense entry
  2. list_expenses - List expenses with optional date/category filters
  3. get_expense_summary - Get aggregated expense summaries
  4. delete_expense - Remove expense by ID
  5. analyze_expenses_with_ai - AI-powered expense analysis

Health Check

  • Server runs on http://localhost:8000
  • MCP endpoint: http://localhost:8000/mcp

🧠 AI Features (Google Gemini 2.5 Flash)

Natural Language Processing

Transform conversational text into structured expense data:

  • Input: "I spent 250 rupees on breakfast today"
  • Processing: Extracts amount (250), category (food), subcategory (breakfast), date (today)
  • Output: Structured expense entry with ₹250, food category, 2025-10-07 date

Smart Date Recognition

Understands various date expressions:

  • "today", "yesterday" → Exact dates
  • "last 10 days", "this week" → Date ranges with proper calculations
  • "this month", "last month" → Monthly boundaries
  • Dynamic calculation using Python datetime

Intelligent Categorization

AI maps context to expense categories:

  • "breakfast", "lunch", "dinner" → food category
  • "cab", "taxi", "bus", "train" → transport category
  • "medicine", "doctor" → healthcare category
  • Falls back to "other" for unknown items

Conversational Analysis

Ask natural questions about spending:

  • "Show my expenses for last 10 days in tabular fashion"
  • "How much did I spend on transport this month?"
  • "Analyze my spending patterns"
  • "What's my category breakdown?"

Context-Aware Responses

  • Remembers conversation history
  • Provides formatted tables with ₹ currency
  • Shows category breakdowns and percentages
  • Calculates totals and trends automatically

🐛 Troubleshooting

Common Issues

  1. Streamlit "ModuleNotFoundError":

    # Ensure you're in the virtual environment
    .\.venv\Scripts\Activate.ps1
    streamlit run client.py
    
  2. MCP Server not starting:

    # Check if port 8000 is in use
    netstat -an | findstr :8000
    
    # Kill existing processes
    taskkill /f /im python.exe
    
  3. AI features not working:

  4. Date filtering issues:

    • Check system date/time settings
    • Verify date calculations in debug output
    • Use python quick_test.py to test MCP tools directly
  5. Tool parameter errors:

    # Test MCP server tools directly
    python quick_test.py
    
    # Check server logs for validation errors
    

Health Checks

# Test MCP server
python quick_test.py

# Check database
python view_database.py

# Verify Streamlit client
streamlit run client.py --server.headless true

Debug Mode

# Run with verbose output
python server.py --verbose

# Check Streamlit logs in terminal
# Look for "Found X tools from MCP server" message

📊 Database Schema

CREATE TABLE expenses (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    date TEXT NOT NULL,
    amount REAL NOT NULL,
    category TEXT NOT NULL,
    subcategory TEXT DEFAULT '',
    note TEXT DEFAULT '',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

🤝 Contributing

  1. Fork the repository
  2. Create feature branch: git checkout -b feature-name
  3. Make changes and test thoroughly
  4. Submit pull request with description

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • FastMCP: For the excellent MCP framework
  • FastAPI: For the robust web framework
  • Google Gemini: For the powerful AI capabilities
  • Rich: For the beautiful CLI interface

🎯 Key Features Demonstrated

MCP Integration Excellence

  • FastMCP 2.0 - Latest MCP framework with HTTP transport
  • Tool Orchestration - 5 expense management tools
  • Parameter Validation - Robust input validation and error handling
  • Async Operations - Non-blocking expense operations

AI Integration Mastery

  • Google Gemini 2.5 Flash - Latest AI model integration
  • LangGraph Agent - Advanced agent with React pattern
  • Natural Language - Conversational expense entry
  • Context Awareness - Chat history and session memory

Modern Web Interface

  • Streamlit Chat UI - Modern conversational interface
  • Real-time Processing - Instant AI responses
  • Dynamic Date Calculations - Smart date range handling
  • Currency Support - Native Indian Rupees (₹) formatting

🏆 Technical Achievements

This project demonstrates:

  • MCP Server Development using FastMCP 2.0
  • AI Agent Architecture with LangGraph and LangChain
  • Natural Language Processing for expense parsing
  • Modern Web UI with Streamlit chat interface
  • Database Management with SQLite and async operations
  • Error Handling and user experience optimization