sum_last_n_topups
Calculate the total amount of recent successful airtime top-ups by summing the last 'n' transactions in the same currency.
Instructions
Calculates the sum of the last 'n' successful top-ups.
This tool retrieves the last 'n' transactions from the database and
calculates their total sum. It ensures that all transactions are in the
same currency before summing.
Args:
n (int, optional): The number of recent top-ups to sum. Defaults to 3.
Returns:
str: The total sum of the last 'n' top-ups or an error message if
the currencies are mixed or no transactions are found.
Tool call template
This tool declares no required parameters. Add optional parameters from the input schema as needed.
{
"id": 1,
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"arguments": {},
"name": "sum_last_n_topups"
}
}Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| n | No |
Implementation Reference
- main.py:217-260 (handler)The core handler function for the 'sum_last_n_topups' MCP tool. It is registered via the @mcp.tool() decorator. The function queries the SQLite database for the last n transactions, ensures uniform currency, sums the amounts, and returns a formatted result string. Includes validation for n > 0 and comprehensive error handling. The docstring provides schema details for input (n: int=3) and output (str).
@mcp.tool() async def sum_last_n_topups(n: int = 3) -> str: """Calculates the sum of the last 'n' successful top-ups. This tool retrieves the last 'n' transactions from the database and calculates their total sum. It ensures that all transactions are in the same currency before summing. Args: n (int, optional): The number of recent top-ups to sum. Defaults to 3. Returns: str: The total sum of the last 'n' top-ups or an error message if the currencies are mixed or no transactions are found. """ if n <= 0: return "Please provide the number of top-ups whose total you need." try: with sqlite3.connect(DB_PATH) as conn: cursor = conn.cursor() cursor.execute( """ SELECT amount, currency_code FROM transactions ORDER BY transaction_time DESC LIMIT ? """, (n,), ) rows = cursor.fetchall() if not rows: return "No successful top-ups found." currencies = set(row[1] for row in rows) if len(currencies) > 1: return "Cannot sum amounts with different currencies." total = sum(amount for (amount, _) in rows) currency = rows[0][1] return f"Sum of last {n} successful top-ups:\n- {currency} {total:.2f}" except Exception as e: return f"Error calculating sum: {str(e)}"