|
| 1 | +import csv |
| 2 | +import logging |
| 3 | +from datetime import date |
| 4 | +from enum import Enum |
| 5 | +from pathlib import Path |
| 6 | +from typing import Annotated |
| 7 | + |
| 8 | +from fastmcp import FastMCP |
| 9 | + |
| 10 | +logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s") |
| 11 | +logger = logging.getLogger("ExpensesMCP") |
| 12 | + |
| 13 | + |
| 14 | +SCRIPT_DIR = Path(__file__).parent |
| 15 | +EXPENSES_FILE = SCRIPT_DIR / "expenses.csv" |
| 16 | + |
| 17 | + |
| 18 | +mcp = FastMCP("Expenses Tracker") |
| 19 | + |
| 20 | + |
| 21 | +class PaymentMethod(Enum): |
| 22 | + AMEX = "amex" |
| 23 | + VISA = "visa" |
| 24 | + CASH = "cash" |
| 25 | + |
| 26 | + |
| 27 | +class Category(Enum): |
| 28 | + FOOD = "food" |
| 29 | + TRANSPORT = "transport" |
| 30 | + ENTERTAINMENT = "entertainment" |
| 31 | + SHOPPING = "shopping" |
| 32 | + GADGET = "gadget" |
| 33 | + OTHER = "other" |
| 34 | + |
| 35 | + |
| 36 | +@mcp.tool |
| 37 | +async def add_expense( |
| 38 | + date: Annotated[date, "Date of the expense in YYYY-MM-DD format"], |
| 39 | + amount: Annotated[float, "Positive numeric amount of the expense"], |
| 40 | + category: Annotated[Category, "Category label"], |
| 41 | + description: Annotated[str, "Human-readable description of the expense"], |
| 42 | + payment_method: Annotated[PaymentMethod, "Payment method used"], |
| 43 | +): |
| 44 | + """Add a new expense to the expenses.csv file.""" |
| 45 | + if amount <= 0: |
| 46 | + return "Error: Amount must be positive" |
| 47 | + |
| 48 | + date_iso = date.isoformat() |
| 49 | + logger.info(f"Adding expense: ${amount} for {description} on {date_iso}") |
| 50 | + |
| 51 | + try: |
| 52 | + file_exists = EXPENSES_FILE.exists() |
| 53 | + |
| 54 | + with open(EXPENSES_FILE, "a", newline="", encoding="utf-8") as file: |
| 55 | + writer = csv.writer(file) |
| 56 | + |
| 57 | + if not file_exists: |
| 58 | + writer.writerow( |
| 59 | + ["date", "amount", "category", "description", "payment_method"] |
| 60 | + ) |
| 61 | + |
| 62 | + writer.writerow( |
| 63 | + [date_iso, amount, category.value, description, payment_method.name] |
| 64 | + ) |
| 65 | + |
| 66 | + return f"Successfully added expense: ${amount} for {description} on {date_iso}" |
| 67 | + |
| 68 | + except Exception as e: |
| 69 | + logger.error(f"Error adding expense: {str(e)}") |
| 70 | + return "Error: Unable to add expense" |
| 71 | + |
| 72 | + |
| 73 | +@mcp.resource("resource://expenses") |
| 74 | +async def get_expenses_data(): |
| 75 | + """Get raw expense data from CSV file""" |
| 76 | + logger.info("Expenses data accessed") |
| 77 | + |
| 78 | + try: |
| 79 | + with open(EXPENSES_FILE, "r", newline="", encoding="utf-8") as file: |
| 80 | + reader = csv.DictReader(file) |
| 81 | + expenses_data = list(reader) |
| 82 | + |
| 83 | + csv_content = f"Expense data ({len(expenses_data)} entries):\n\n" |
| 84 | + for expense in expenses_data: |
| 85 | + csv_content += ( |
| 86 | + f"Date: {expense['date']}, " |
| 87 | + f"Amount: ${expense['amount']}, " |
| 88 | + f"Category: {expense['category']}, " |
| 89 | + f"Description: {expense['description']}, " |
| 90 | + f"Payment: {expense['payment_method']}\n" |
| 91 | + ) |
| 92 | + |
| 93 | + return csv_content |
| 94 | + |
| 95 | + except FileNotFoundError: |
| 96 | + logger.error("Expenses file not found") |
| 97 | + return "Error: Expense data unavailable" |
| 98 | + except Exception as e: |
| 99 | + logger.error(f"Error reading expenses: {str(e)}") |
| 100 | + return "Error: Unable to retrieve expense data" |
| 101 | + |
| 102 | + |
| 103 | +@mcp.prompt |
| 104 | +def create_expense_prompt( |
| 105 | + date: str, |
| 106 | + amount: float, |
| 107 | + category: str, |
| 108 | + description: str, |
| 109 | + payment_method: str |
| 110 | +) -> str: |
| 111 | + |
| 112 | + """Generate a prompt to add a new expense using the add_expense tool.""" |
| 113 | + |
| 114 | + logger.info(f"Expense prompt created for: {description}") |
| 115 | + |
| 116 | + return f""" |
| 117 | + Please add the following expense: |
| 118 | + - Date: {date} |
| 119 | + - Amount: ${amount} |
| 120 | + - Category: {category} |
| 121 | + - Description: {description} |
| 122 | + - Payment Method: {payment_method} |
| 123 | + Use the `add_expense` tool to record this transaction. |
| 124 | + """ |
| 125 | + |
| 126 | + |
| 127 | +if __name__ == "__main__": |
| 128 | + logger.info("MCP Expenses server starting") |
| 129 | + mcp.run() |
0 commit comments