monarch-mcp 0.1.0

Monarch Money MCP server — an agentic budgeting companion (read + categorize only)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Pure aggregation logic for the `spending_report` tool.
//!
//! All arithmetic lives here, separated from I/O, so it can be unit-tested
//! without standing up a mock server. The tool handler in `tools.rs` fetches
//! data then delegates to [`compute_spending_report`].

use crate::client::{Budget, Cashflow, Transaction};
use serde::Serialize;
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Input types — subsets of client types we actually need
// ---------------------------------------------------------------------------

/// Spending and budget data for one category.
#[derive(Debug, Serialize, PartialEq)]
pub struct CategoryReport {
    pub spent: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub budget: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percent_of_budget: Option<i64>,
}

/// A possible duplicate charge pair.
#[derive(Debug, Serialize, PartialEq)]
pub struct DuplicateCharge {
    pub merchant: String,
    pub amount: f64,
    pub date: String,
}

/// Month-over-month spending comparison.
#[derive(Debug, Serialize, PartialEq)]
pub struct PriorPeriodComparison {
    /// Positive = spending went up, negative = spending went down.
    pub delta: f64,
}

/// The full spending report payload returned as JSON inside an MCP `CallToolResult`.
#[derive(Debug, Serialize, PartialEq)]
pub struct SpendingReport {
    pub total_spent: f64,
    pub over_budget_categories: Vec<String>,
    pub by_category: HashMap<String, CategoryReport>,
    pub possible_duplicates: Vec<DuplicateCharge>,
    pub vs_prior_month: PriorPeriodComparison,
}

// ---------------------------------------------------------------------------
// Pure computation — no I/O
// ---------------------------------------------------------------------------

/// Compute the spending report from already-fetched Monarch data.
pub fn compute_spending_report(
    transactions: &[Transaction],
    budgets: &[Budget],
    cashflow: &Cashflow,
) -> SpendingReport {
    let by_category = aggregate_spending_by_category(transactions);
    let budget_map = build_budget_map(budgets);
    let category_reports = build_category_reports(&by_category, &budget_map);
    let over_budget_categories = find_over_budget_categories(&category_reports);
    let total_spent = by_category.values().sum();
    let possible_duplicates = find_possible_duplicates(transactions);
    let prior_period = PriorPeriodComparison {
        delta: total_spent - cashflow.prior_month_spending,
    };

    SpendingReport {
        total_spent,
        over_budget_categories,
        by_category: category_reports,
        possible_duplicates,
        vs_prior_month: prior_period,
    }
}

/// Sum transaction amounts per category name.
fn aggregate_spending_by_category(transactions: &[Transaction]) -> HashMap<String, f64> {
    let mut totals: HashMap<String, f64> = HashMap::new();
    for txn in transactions {
        *totals.entry(txn.category.name.clone()).or_insert(0.0) += txn.amount;
    }
    totals
}

/// Build a lookup map from category name to budget amount.
fn build_budget_map(budgets: &[Budget]) -> HashMap<String, f64> {
    budgets
        .iter()
        .map(|b| (b.category.name.clone(), b.amount))
        .collect()
}

/// Build per-category reports, attaching budget and percent-of-budget when available.
fn build_category_reports(
    spending: &HashMap<String, f64>,
    budget_map: &HashMap<String, f64>,
) -> HashMap<String, CategoryReport> {
    spending
        .iter()
        .map(|(category, &spent)| {
            let report = match budget_map.get(category) {
                Some(&budget) => CategoryReport {
                    spent,
                    budget: Some(budget),
                    percent_of_budget: percent_of_budget(spent, budget),
                },
                None => CategoryReport {
                    spent,
                    budget: None,
                    percent_of_budget: None,
                },
            };
            (category.clone(), report)
        })
        .collect()
}

/// Round (spent / budget_magnitude * 100) to the nearest whole percent.
///
/// Monarch stores expense budgets as negative `plannedCashFlowAmount` values
/// (e.g., "Loan Repayment" → `-1280`). We compare magnitudes so that a budget
/// of either `1280` or `-1280` yields the same percent for a given spend.
///
/// Returns `None` when `budget` is zero to avoid a divide-by-zero producing
/// `inf` (which casts to `i64::MAX`) or `NaN` (which casts to `0`).
fn percent_of_budget(spent: f64, budget: f64) -> Option<i64> {
    let magnitude = budget.abs();
    if magnitude == 0.0 {
        return None;
    }
    Some(((spent / magnitude) * 100.0).round() as i64)
}

/// A category is over budget only when spending strictly exceeds the budget magnitude.
///
/// Monarch stores expense budgets as negative `plannedCashFlowAmount` values
/// (e.g., "Loan Repayment" → `-1280`). We compare `spent` against `budget.abs()`
/// so that both positive-budget and negative-budget categories use the same
/// magnitude comparison. "Over budget" means "spent more than the planned amount".
fn find_over_budget_categories(category_reports: &HashMap<String, CategoryReport>) -> Vec<String> {
    let mut over_budget: Vec<String> = category_reports
        .iter()
        .filter_map(|(name, report)| {
            report.budget.and_then(|budget| {
                if report.spent > budget.abs() {
                    Some(name.clone())
                } else {
                    None
                }
            })
        })
        .collect();
    // Sort for deterministic output
    over_budget.sort();
    over_budget
}

/// Find transactions with the same merchant, same amount, and same date.
/// Each such group is reported as one `DuplicateCharge` entry.
fn find_possible_duplicates(transactions: &[Transaction]) -> Vec<DuplicateCharge> {
    let mut seen: HashMap<(&str, i64, &str), usize> = HashMap::new();
    let mut duplicates: Vec<DuplicateCharge> = Vec::new();
    let mut already_flagged: std::collections::HashSet<(&str, i64, &str)> =
        std::collections::HashSet::new();

    for txn in transactions {
        // Use integer representation of amount (cents) to avoid float key issues
        let amount_cents = (txn.amount * 100.0).round() as i64;
        let key = (txn.merchant_name.as_str(), amount_cents, txn.date.as_str());

        let count = seen.entry(key).or_insert(0);
        *count += 1;

        if *count == 2 && !already_flagged.contains(&key) {
            already_flagged.insert(key);
            duplicates.push(DuplicateCharge {
                merchant: txn.merchant_name.clone(),
                amount: txn.amount,
                date: txn.date.clone(),
            });
        }
    }

    duplicates
}

// ---------------------------------------------------------------------------
// Tests — TDD: RED first, then GREEN
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::{Budget, Cashflow, Category, Transaction};

    fn make_txn(merchant: &str, amount: f64, category: &str, date: &str) -> Transaction {
        Transaction {
            id: format!("{merchant}-{amount}-{date}"),
            amount,
            date: date.to_string(),
            merchant_name: merchant.to_string(),
            category: Category {
                name: category.to_string(),
            },
            tags: vec![],
            notes: String::new(),
            needs_review: false,
        }
    }

    fn make_budget(category: &str, amount: f64) -> Budget {
        Budget {
            category: Category {
                name: category.to_string(),
            },
            amount,
        }
    }

    fn zero_cashflow() -> Cashflow {
        Cashflow {
            income: 0.0,
            spending: 0.0,
            prior_month_spending: 0.0,
        }
    }

    // -----------------------------------------------------------------------
    // 9a RED: over-budget flag — spending strictly exceeds budget
    // -----------------------------------------------------------------------

    #[test]
    fn category_over_budget_is_flagged() {
        let txns = vec![make_txn("Dining merchant", 850.0, "Dining", "2026-05-15")];
        let budgets = vec![make_budget("Dining", 600.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            report
                .over_budget_categories
                .contains(&"Dining".to_string()),
            "expected Dining in over_budget_categories: {:?}",
            report.over_budget_categories
        );
    }

    // -----------------------------------------------------------------------
    // 9b GREEN + 9c TRIANGULATE: exactly at budget is NOT over budget
    // -----------------------------------------------------------------------

    #[test]
    fn category_exactly_at_budget_is_not_flagged() {
        let txns = vec![make_txn(
            "Groceries merchant",
            900.0,
            "Groceries",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Groceries", 900.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Groceries".to_string()),
            "Groceries at 100% should not be flagged: {:?}",
            report.over_budget_categories
        );
    }

    #[test]
    fn category_under_budget_is_not_flagged() {
        let txns = vec![make_txn(
            "Groceries merchant",
            720.0,
            "Groceries",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Groceries", 900.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Groceries".to_string()),
            "Groceries under budget should not be flagged"
        );
    }

    // -----------------------------------------------------------------------
    // 9c TRIANGULATE: every over-budget category is flagged (multiple)
    // -----------------------------------------------------------------------

    #[test]
    fn all_over_budget_categories_are_flagged() {
        let txns = vec![
            make_txn("Dining merchant", 850.0, "Dining", "2026-05-15"),
            make_txn("Shopping merchant", 500.0, "Shopping", "2026-05-15"),
        ];
        let budgets = vec![make_budget("Dining", 600.0), make_budget("Shopping", 400.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            report
                .over_budget_categories
                .contains(&"Dining".to_string()),
            "Dining should be over budget"
        );
        assert!(
            report
                .over_budget_categories
                .contains(&"Shopping".to_string()),
            "Shopping should be over budget"
        );
    }

    // -----------------------------------------------------------------------
    // 9a RED: percent of budget — 850/600 → 142%
    // -----------------------------------------------------------------------

    #[test]
    fn percent_of_budget_rounds_to_nearest_whole() {
        // 850/600 = 1.4166… → 142%
        assert_eq!(percent_of_budget(850.0, 600.0), Some(142));
        // 900/900 = 1.0 → 100%
        assert_eq!(percent_of_budget(900.0, 900.0), Some(100));
    }

    // -----------------------------------------------------------------------
    // 9c TRIANGULATE: rounding boundary cases
    // -----------------------------------------------------------------------

    #[test]
    fn percent_of_budget_rounds_up_at_half() {
        // 0.5 rounds up → 50/100 = 50%, not a boundary; use 1/3 * 100 = 33.33 → 33
        assert_eq!(percent_of_budget(1.0, 3.0), Some(33));
        // 2/3 * 100 = 66.67 → 67
        assert_eq!(percent_of_budget(2.0, 3.0), Some(67));
    }

    #[test]
    fn category_report_includes_percent_when_budgeted() {
        let txns = vec![make_txn("Dining merchant", 850.0, "Dining", "2026-05-15")];
        let budgets = vec![make_budget("Dining", 600.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        let cat = report.by_category.get("Dining").unwrap();
        assert_eq!(cat.percent_of_budget, Some(142));
    }

    // -----------------------------------------------------------------------
    // 9a RED: unbudgeted category — reported but not flagged
    // -----------------------------------------------------------------------

    #[test]
    fn unbudgeted_category_is_not_flagged_as_over_budget() {
        let txns = vec![make_txn("Travel merchant", 300.0, "Travel", "2026-05-15")];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Travel".to_string()),
            "unbudgeted Travel should not be flagged"
        );
        let cat = report.by_category.get("Travel").unwrap();
        assert_eq!(cat.spent, 300.0);
        assert_eq!(cat.budget, None);
        assert_eq!(cat.percent_of_budget, None);
    }

    // -----------------------------------------------------------------------
    // 9a RED: duplicate detection — same merchant + amount + date
    // -----------------------------------------------------------------------

    #[test]
    fn identical_charges_same_day_flagged_as_duplicate() {
        let txns = vec![
            make_txn("Acme Streaming", 49.99, "Subscriptions", "2026-05-14"),
            make_txn("Acme Streaming", 49.99, "Subscriptions", "2026-05-14"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        let merchants: Vec<&str> = report
            .possible_duplicates
            .iter()
            .map(|d| d.merchant.as_str())
            .collect();
        assert!(
            merchants.contains(&"Acme Streaming"),
            "expected Acme Streaming in duplicates: {:?}",
            merchants
        );
    }

    // -----------------------------------------------------------------------
    // 9c TRIANGULATE: same merchant, different amount → NOT a duplicate
    // -----------------------------------------------------------------------

    #[test]
    fn same_merchant_different_amount_not_a_duplicate() {
        let txns = vec![
            make_txn("Acme Streaming", 49.99, "Subscriptions", "2026-05-14"),
            make_txn("Acme Streaming", 9.99, "Subscriptions", "2026-05-14"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        let merchants: Vec<&str> = report
            .possible_duplicates
            .iter()
            .map(|d| d.merchant.as_str())
            .collect();
        assert!(
            !merchants.contains(&"Acme Streaming"),
            "different amounts should not be a duplicate: {:?}",
            merchants
        );
    }

    // -----------------------------------------------------------------------
    // 9a RED: prior-period delta
    // -----------------------------------------------------------------------

    #[test]
    fn prior_period_delta_is_positive_when_spending_increased() {
        let txns = vec![make_txn("Various", 4600.0, "General", "2026-05-15")];
        let cashflow = Cashflow {
            income: 0.0,
            spending: 0.0,
            prior_month_spending: 4000.0,
        };
        let report = compute_spending_report(&txns, &[], &cashflow);
        assert_eq!(report.vs_prior_month.delta, 600.0);
    }

    // -----------------------------------------------------------------------
    // 9c TRIANGULATE: prior-period delta when spending decreased
    // -----------------------------------------------------------------------

    #[test]
    fn prior_period_delta_is_negative_when_spending_decreased() {
        let txns = vec![make_txn("Various", 3000.0, "General", "2026-05-15")];
        let cashflow = Cashflow {
            income: 0.0,
            spending: 0.0,
            prior_month_spending: 4000.0,
        };
        let report = compute_spending_report(&txns, &[], &cashflow);
        assert_eq!(report.vs_prior_month.delta, -1000.0);
    }

    // -----------------------------------------------------------------------
    // 9a RED: empty period
    // -----------------------------------------------------------------------

    #[test]
    fn empty_period_reports_zero_spend_and_no_flags() {
        let report = compute_spending_report(&[], &[], &zero_cashflow());
        assert_eq!(report.total_spent, 0.0);
        assert!(report.over_budget_categories.is_empty());
        assert!(report.by_category.is_empty());
        assert!(report.possible_duplicates.is_empty());
    }

    // -----------------------------------------------------------------------
    // 9c TRIANGULATE: total_spent is sum of all transactions
    // -----------------------------------------------------------------------

    #[test]
    fn total_spent_is_sum_of_all_transactions() {
        let txns = vec![
            make_txn("Dining merchant", 850.0, "Dining", "2026-05-15"),
            make_txn("Groceries merchant", 720.0, "Groceries", "2026-05-15"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert_eq!(report.total_spent, 1570.0);
    }

    // -----------------------------------------------------------------------
    // BUG 1 RED: zero budget with nonzero spend must NOT produce i64::MAX percent
    // -----------------------------------------------------------------------

    #[test]
    fn zero_budget_with_spend_produces_no_percent_and_is_over_budget() {
        // A Monarch category with a $0 budget and any spending:
        // - percent_of_budget should be None (not i64::MAX from inf-cast)
        // - the category IS over budget (spent > budget)
        let txns = vec![make_txn("Netflix", 15.99, "Streaming", "2026-05-15")];
        let budgets = vec![make_budget("Streaming", 0.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());

        let cat = report
            .by_category
            .get("Streaming")
            .expect("Streaming category must exist");
        assert_ne!(
            cat.percent_of_budget,
            Some(i64::MAX),
            "zero budget with spend must not produce i64::MAX percent"
        );
        assert_eq!(
            cat.percent_of_budget, None,
            "zero budget should yield no percent (division by zero)"
        );
        assert!(
            report
                .over_budget_categories
                .contains(&"Streaming".to_string()),
            "spending on a $0-budget category must still be classified over budget"
        );
    }

    // -----------------------------------------------------------------------
    // 9a RED: negative-budget (loan-repayment style) — Monarch stores planned
    // outflows as negative plannedCashFlowAmount values.  A budget of -1280
    // means "plan to pay $1280 on the loan".  Transactions for that category
    // have positive amounts (all expenses are positive in Transaction.amount).
    // Over-budget means magnitude-of-spending > magnitude-of-budget.
    // -----------------------------------------------------------------------

    #[test]
    fn negative_budget_under_magnitude_is_not_over_budget() {
        // Planned: -1280 (loan repayment). Actual spend: 1000 (< 1280 magnitude).
        let txns = vec![make_txn("Loan Co", 1000.0, "Loan Repayment", "2026-05-15")];
        let budgets = vec![make_budget("Loan Repayment", -1280.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Loan Repayment".to_string()),
            "spending 1000 against a -1280 budget should NOT be over budget (1000 < 1280)"
        );
    }

    #[test]
    fn negative_budget_over_magnitude_is_flagged_as_over_budget() {
        // Planned: -1280. Actual spend: 1400 (> 1280 magnitude) → over budget.
        let txns = vec![make_txn("Loan Co", 1400.0, "Loan Repayment", "2026-05-15")];
        let budgets = vec![make_budget("Loan Repayment", -1280.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            report
                .over_budget_categories
                .contains(&"Loan Repayment".to_string()),
            "spending 1400 against a -1280 budget SHOULD be over budget (1400 > 1280)"
        );
    }

    #[test]
    fn negative_budget_percent_of_budget_is_positive_and_sane() {
        // 1000 spent against -1280 budget → 1000/1280 * 100 = 78%  (not negative)
        assert_eq!(percent_of_budget(1000.0, -1280.0), Some(78));
    }

    #[test]
    fn negative_budget_exactly_at_magnitude_is_not_over_budget() {
        // Planned: -1280. Actual spend: exactly 1280 → at budget, not over.
        let txns = vec![make_txn("Loan Co", 1280.0, "Loan Repayment", "2026-05-15")];
        let budgets = vec![make_budget("Loan Repayment", -1280.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Loan Repayment".to_string()),
            "spending exactly 1280 against a -1280 budget should NOT be over budget"
        );
        let cat = report.by_category.get("Loan Repayment").unwrap();
        assert_eq!(cat.percent_of_budget, Some(100));
    }

    #[test]
    fn negative_budget_zero_spend_is_not_over_budget() {
        // Planned: -1280. No transactions this month → $0 spent, not over budget.
        let txns = vec![];
        let budgets = vec![make_budget("Loan Repayment", -1280.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Loan Repayment".to_string()),
            "zero spend against a negative budget should not be over budget"
        );
    }

    #[test]
    fn zero_budget_with_zero_spend_produces_no_percent_and_is_not_over_budget() {
        // $0 budget, $0 spend: NaN→0 is wrong — should also be None
        let txns = vec![make_txn("Netflix", 0.0, "Streaming", "2026-05-15")];
        let budgets = vec![make_budget("Streaming", 0.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());

        let cat = report
            .by_category
            .get("Streaming")
            .expect("Streaming category must exist");
        assert_eq!(
            cat.percent_of_budget, None,
            "zero budget with zero spend should yield None percent (0/0 = NaN, not 0)"
        );
        assert!(
            !report
                .over_budget_categories
                .contains(&"Streaming".to_string()),
            "zero spend on $0-budget category is not over budget"
        );
    }
}