Skip to main content
Glama
Sharan0402

Expense Tracker MCP Server

by Sharan0402

get_item_history

Query purchase history for a specific item type to analyze spending patterns, view purchase details, and track expenses over time.

Instructions

Query purchase history for a specific item type.

Returns detailed purchase history including:

  • List of all purchases with dates, stores, quantities, and prices

  • Statistics: total purchases, date range, average frequency, total spent

Args: item_type: Category to query (e.g., 'milk', 'bread', 'eggs') time_range_days: Number of days to look back (default: 365)

Returns: Dictionary with purchases list and aggregated statistics

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
item_typeYesItem category to query (e.g., 'milk', 'bread', 'eggs')
time_range_daysNoNumber of days to look back (default: 365)

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • main.py:122-163 (handler)
    The MCP tool handler for 'get_item_history'. It calls the database helper query_item_history and formats the response, including handling empty results.
    @mcp.tool
    async def get_item_history(
        item_type: Annotated[str, "Item category to query (e.g., 'milk', 'bread', 'eggs')"],
        time_range_days: Annotated[
            int, "Number of days to look back (default: 365)"
        ] = 365,
    ) -> dict:
        """Query purchase history for a specific item type.
    
        Returns detailed purchase history including:
        - List of all purchases with dates, stores, quantities, and prices
        - Statistics: total purchases, date range, average frequency, total spent
    
        Args:
            item_type: Category to query (e.g., 'milk', 'bread', 'eggs')
            time_range_days: Number of days to look back (default: 365)
    
        Returns:
            Dictionary with purchases list and aggregated statistics
        """
        try:
            result = query_item_history(item_type, time_range_days)
    
            if not result["purchases"]:
                return {
                    "item_type": item_type,
                    "purchases": [],
                    "stats": {
                        "total_purchases": 0,
                        "message": f"No purchases found for '{item_type}' in the last {time_range_days} days",
                    },
                }
    
            return {
                "item_type": item_type,
                "purchases": result["purchases"],
                "stats": result["stats"],
            }
    
        except Exception as e:
            raise ToolError(f"Failed to query item history: {str(e)}")
  • Database helper function that executes SQL queries to retrieve purchase history and compute statistics for a given item type over a time range.
    def query_item_history(
        item_type: str,
        time_range_days: int = 365,
        db_path: Path = DEFAULT_DB_PATH,
    ) -> dict:
        """Query purchase history for a specific item type.
    
        Returns a dictionary with:
        - purchases: list of purchase records
        - stats: ItemStats object with aggregated statistics
        """
        cutoff_date = (datetime.now() - timedelta(days=time_range_days)).strftime(
            "%Y-%m-%d"
        )
    
        conn = get_connection(db_path)
    
        try:
            # Query purchases
            cursor = conn.execute(
                """
                SELECT
                    r.purchase_date,
                    r.store_name,
                    i.item_name_raw,
                    i.quantity,
                    i.unit_price,
                    i.line_total
                FROM items i
                JOIN receipts r ON i.receipt_id = r.id
                WHERE i.item_type = ? AND r.purchase_date >= ?
                ORDER BY r.purchase_date DESC
            """,
                (item_type, cutoff_date),
            )
    
            purchases = []
            for row in cursor.fetchall():
                purchases.append(
                    {
                        "date": row["purchase_date"],
                        "store": row["store_name"],
                        "item_name": row["item_name_raw"],
                        "quantity": row["quantity"],
                        "unit_price": row["unit_price"],
                        "price": row["line_total"],
                    }
                )
    
            # Query stats
            stats_cursor = conn.execute(
                """
                SELECT
                    COUNT(DISTINCT r.id) as total_purchases,
                    MAX(r.purchase_date) as last_purchase_date,
                    MIN(r.purchase_date) as first_purchase_date,
                    SUM(i.line_total) as total_spent
                FROM items i
                JOIN receipts r ON i.receipt_id = r.id
                WHERE i.item_type = ? AND r.purchase_date >= ?
            """,
                (item_type, cutoff_date),
            )
    
            stats_row = stats_cursor.fetchone()
    
            # Calculate average days between purchases
            avg_days = None
            if stats_row["total_purchases"] and stats_row["total_purchases"] > 1:
                first_date = datetime.fromisoformat(stats_row["first_purchase_date"])
                last_date = datetime.fromisoformat(stats_row["last_purchase_date"])
                total_days = (last_date - first_date).days
                if total_days > 0:
                    avg_days = total_days / (stats_row["total_purchases"] - 1)
    
            stats = {
                "total_purchases": stats_row["total_purchases"] or 0,
                "last_purchase_date": stats_row["last_purchase_date"],
                "first_purchase_date": stats_row["first_purchase_date"],
                "average_days_between": round(avg_days, 1) if avg_days else None,
                "total_spent": round(stats_row["total_spent"] or 0, 2),
            }
    
            return {"purchases": purchases, "stats": stats}
    
        finally:
            conn.close()
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the return format in detail (list of purchases with specific fields and aggregated statistics), which is valuable context. However, it lacks information on potential limitations, such as data availability, error handling, or performance considerations (e.g., large datasets). This partial coverage results in a baseline score.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured and appropriately sized, starting with the core purpose, detailing return values, and listing parameters. Each sentence serves a clear purpose: the first states the action, the next two outline outputs, and the last specifies args and returns. It could be slightly more concise by avoiding redundancy with the schema, but overall, it's efficient and front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (2 parameters, read-only query), no annotations, and the presence of an output schema (implied by 'Returns' section), the description is reasonably complete. It explains what the tool does, what it returns, and the parameters, compensating for the lack of annotations. However, it misses some behavioral context like data source or limitations, preventing a perfect score.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, meaning the input schema already fully documents both parameters ('item_type' and 'time_range_days') with descriptions and defaults. The description repeats some of this information (e.g., examples for 'item_type' and the default for 'time_range_days'), adding minimal value beyond the schema. According to the rules, with high schema coverage, the baseline is 3 even without additional param info in the description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as 'Query purchase history for a specific item type,' which is a specific verb ('query') + resource ('purchase history') combination. It distinguishes itself from sibling tools like 'import_receipt_from_pdf' (data ingestion) and 'list_item_types' (metadata listing) by focusing on historical data retrieval. However, it doesn't explicitly contrast with potential alternatives for querying history, keeping it from a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for retrieving purchase history based on item type and time range, but provides no explicit guidance on when to use this tool versus alternatives. There's no mention of prerequisites, such as needing existing data from 'import_receipt_from_pdf,' or exclusions like not handling real-time data. This leaves usage context somewhat vague, relying on the agent to infer from the purpose.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Sharan0402/expense-tracker-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server