monarch-mcp 0.2.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
//! Pure computation for the `progress_vs_goals` tool.
//!
//! Measures actual finances against the household's stored goals and classifies
//! each as `on track`, `drifting`, or `off` using a single shared banding
//! function. Only goals the household has actually set are reported.

use crate::client::{Account, Cashflow};
use crate::goals::Goals;
use serde::Serialize;

// ---------------------------------------------------------------------------
// Output types
// ---------------------------------------------------------------------------

/// The result payload returned as JSON by `progress_vs_goals`.
/// Only fields for goals that have been set are present.
/// `guidance` is set whenever no *computable* goal produced output — either
/// because no goals are configured at all, or because only goals whose progress
/// tracking is not yet implemented (e.g. debt-payoff, tracked in #27) are set.
/// This prevents the payload from ever serializing to a silent empty object `{}`.
#[derive(Debug, Serialize, PartialEq)]
pub struct GoalsProgress {
    /// Savings-rate goal progress — present only when the goal is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_rate: Option<GoalStatus>,

    /// Emergency-fund runway goal progress — present only when the goal is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub emergency_fund: Option<GoalStatus>,

    /// Set when no computable goal produced output — explains next steps.
    /// Also fires when only goals with deferred computation (e.g. debt-payoff)
    /// are configured, so the wording adapts to avoid falsely claiming "no goals".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub guidance: Option<String>,
}

/// Classification of a single goal.
#[derive(Debug, Serialize, PartialEq)]
pub struct GoalStatus {
    /// One of `"on track"`, `"drifting"`, or `"off"`.
    pub status: String,
}

// ---------------------------------------------------------------------------
// Banding — shared classifier for all goal types
// ---------------------------------------------------------------------------

/// Classify `actual` against `goal` using the standard three-band rule:
///
/// - `"on track"`: actual ≥ goal
/// - `"off"`:      actual < goal / 2
/// - `"drifting"`: anything in between (goal/2 ≤ actual < goal)
pub fn classify_goal(actual: f64, goal: f64) -> &'static str {
    if actual >= goal {
        "on track"
    } else if actual < goal / 2.0 {
        "off"
    } else {
        "drifting"
    }
}

// ---------------------------------------------------------------------------
// Actuals computation helpers
// ---------------------------------------------------------------------------

/// Compute the savings rate as a percentage from cashflow data.
/// savings_rate = (income - spending) / income * 100
/// Returns 0.0 when income is zero to avoid division by zero.
pub fn actual_savings_rate_pct(cashflow: &Cashflow) -> f64 {
    if cashflow.income == 0.0 {
        return 0.0;
    }
    (cashflow.income - cashflow.spending) / cashflow.income * 100.0
}

/// Compute months of expenses covered by liquid cash-equivalent accounts.
///
/// `reserves_months = total_liquid_balance / monthly_spending`
/// Returns 0.0 when monthly spending is zero.
///
/// Liquid cash-equivalent types (included):
///   - `"savings"`      — traditional savings / HYSA
///   - `"checking"`     — checking / demand-deposit accounts
///   - `"depository"`   — Monarch's catch-all for bank deposit accounts
///   - `"money_market"` — money-market accounts / funds
///
/// Excluded: `"brokerage"`, `"investment"`, `"retirement"`, `"credit"`, `"loan"`,
/// and any other type not in the above list.  Investment/retirement balances are
/// not immediately liquid; liability balances would distort the runway figure.
///
/// Semantics rationale: an emergency fund is the cash you can tap in 1–3 business
/// days without selling assets or incurring penalties.  Brokerage accounts require
/// a T+2 settlement cycle and market-risk exposure; retirement accounts carry
/// withdrawal penalties.  Only deposit-type accounts qualify.
pub fn actual_reserve_months(accounts: &[Account], cashflow: &Cashflow) -> f64 {
    if cashflow.spending == 0.0 {
        return 0.0;
    }
    const LIQUID_TYPES: &[&str] = &["savings", "checking", "depository", "money_market"];
    let liquid_balance: f64 = accounts
        .iter()
        .filter(|a| LIQUID_TYPES.contains(&a.account_type.name.as_str()))
        .map(|a| a.current_balance)
        .sum();
    liquid_balance / cashflow.spending
}

// ---------------------------------------------------------------------------
// Pure aggregation — no I/O
// ---------------------------------------------------------------------------

/// Compute goal progress from already-fetched Monarch data and loaded goals.
///
/// When no goals have been configured, returns a `guidance` message directing
/// the household to create a goals.toml — consistent with the soft re-auth
/// pattern (a successful MCP result whose body explains next steps).
pub fn compute_progress(goals: &Goals, accounts: &[Account], cashflow: &Cashflow) -> GoalsProgress {
    let savings_rate = goals.savings_rate.as_ref().map(|g| {
        let actual = actual_savings_rate_pct(cashflow);
        GoalStatus {
            status: classify_goal(actual, g.target_percent).to_string(),
        }
    });

    let emergency_fund = goals.emergency_fund.as_ref().map(|g| {
        let actual = actual_reserve_months(accounts, cashflow);
        GoalStatus {
            status: classify_goal(actual, g.target_months).to_string(),
        }
    });

    // guidance fires whenever neither computable goal is set, so the payload is
    // never a silent empty object. Wording adapts when a debt-payoff goal is set
    // (its progress is not computed yet — tracked in #27) so we don't falsely
    // claim "no goals configured".
    let has_no_computable_goals = savings_rate.is_none() && emergency_fund.is_none();
    let guidance = has_no_computable_goals.then(|| {
        if goals.debt_payoff.is_some() {
            "A debt-payoff goal is configured, but debt-payoff progress tracking is \
             not available yet (tracked in #27). Set a savings-rate or emergency-fund \
             goal to see progress now."
                .to_string()
        } else {
            "No goals configured yet. Add a goals.toml file and set \
             MONARCH_GOALS_FILE to its path to start tracking progress."
                .to_string()
        }
    });

    GoalsProgress {
        savings_rate,
        emergency_fund,
        guidance,
    }
}

// ---------------------------------------------------------------------------
// Tests — TDD: RED → GREEN → TRIANGULATE → GREEN → REFACTOR
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::{AccountType, Cashflow};
    use crate::goals::{EmergencyFundGoal, Goals, SavingsRateGoal};

    // -----------------------------------------------------------------------
    // Classifier banding — boundary tests
    // -----------------------------------------------------------------------

    // 9a RED: exactly at goal → on track
    #[test]
    fn classify_at_goal_is_on_track() {
        assert_eq!(classify_goal(20.0, 20.0), "on track");
    }

    // 9a RED: above goal → on track
    #[test]
    fn classify_above_goal_is_on_track() {
        assert_eq!(classify_goal(25.0, 20.0), "on track");
    }

    // 9c TRIANGULATE: exactly at half → drifting (not off)
    #[test]
    fn classify_at_half_goal_is_drifting() {
        assert_eq!(classify_goal(10.0, 20.0), "drifting");
    }

    // 9c TRIANGULATE: just below half → off
    #[test]
    fn classify_just_below_half_is_off() {
        // 9.9 < 20/2=10 → off
        assert_eq!(classify_goal(9.9, 20.0), "off");
    }

    // 9c TRIANGULATE: midrange → drifting
    #[test]
    fn classify_midrange_is_drifting() {
        assert_eq!(classify_goal(17.0, 20.0), "drifting");
    }

    // 9c TRIANGULATE: far below half → off
    #[test]
    fn classify_far_below_half_is_off() {
        assert_eq!(classify_goal(6.0, 20.0), "off");
    }

    // 9c TRIANGULATE: zero → off (unless goal is also zero)
    #[test]
    fn classify_zero_actual_is_off() {
        assert_eq!(classify_goal(0.0, 20.0), "off");
    }

    // 9c TRIANGULATE: emergency-fund banding (6-month target)
    #[test]
    fn classify_emergency_fund_at_goal_is_on_track() {
        assert_eq!(classify_goal(6.0, 6.0), "on track");
    }

    #[test]
    fn classify_emergency_fund_above_goal_is_on_track() {
        assert_eq!(classify_goal(7.0, 6.0), "on track");
    }

    #[test]
    fn classify_emergency_fund_drifting() {
        assert_eq!(classify_goal(4.0, 6.0), "drifting");
    }

    #[test]
    fn classify_emergency_fund_off() {
        assert_eq!(classify_goal(2.0, 6.0), "off");
    }

    // -----------------------------------------------------------------------
    // Savings-rate computation
    // -----------------------------------------------------------------------

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

    #[test]
    fn savings_rate_pct_is_correct() {
        // (10000 - 7500) / 10000 * 100 = 25%
        assert_eq!(actual_savings_rate_pct(&cashflow(10000.0, 7500.0)), 25.0);
    }

    #[test]
    fn savings_rate_pct_zero_income_returns_zero() {
        assert_eq!(actual_savings_rate_pct(&cashflow(0.0, 0.0)), 0.0);
    }

    #[test]
    fn savings_rate_pct_full_spending_returns_zero() {
        // All income spent → 0% savings
        assert_eq!(actual_savings_rate_pct(&cashflow(10000.0, 10000.0)), 0.0);
    }

    // -----------------------------------------------------------------------
    // Reserve months computation
    // -----------------------------------------------------------------------

    fn savings_account(balance: f64) -> Account {
        Account {
            id: "s1".to_string(),
            display_name: "Emergency Fund".to_string(),
            current_balance: balance,
            account_type: AccountType {
                name: "savings".to_string(),
            },
        }
    }

    fn checking_account(balance: f64) -> Account {
        Account {
            id: "c1".to_string(),
            display_name: "Checking".to_string(),
            current_balance: balance,
            account_type: AccountType {
                name: "checking".to_string(),
            },
        }
    }

    fn money_market_account(balance: f64) -> Account {
        Account {
            id: "mm1".to_string(),
            display_name: "HYSA".to_string(),
            current_balance: balance,
            account_type: AccountType {
                name: "money_market".to_string(),
            },
        }
    }

    fn brokerage_account(balance: f64) -> Account {
        Account {
            id: "b1".to_string(),
            display_name: "Brokerage".to_string(),
            current_balance: balance,
            account_type: AccountType {
                name: "brokerage".to_string(),
            },
        }
    }

    fn retirement_account(balance: f64) -> Account {
        Account {
            id: "r1".to_string(),
            display_name: "401k".to_string(),
            current_balance: balance,
            account_type: AccountType {
                name: "retirement".to_string(),
            },
        }
    }

    // 9a RED: money-market should count as liquid reserves
    #[test]
    fn reserve_months_counts_money_market() {
        // 20000 money-market / 5000 spending = 4 months
        let accounts = vec![money_market_account(20000.0)];
        let cf = cashflow(6000.0, 5000.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 4.0);
    }

    // 9a RED: checking should count as liquid reserves
    #[test]
    fn reserve_months_counts_checking() {
        // 10000 checking / 5000 spending = 2 months
        let accounts = vec![checking_account(10000.0)];
        let cf = cashflow(6000.0, 5000.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 2.0);
    }

    // 9a RED: savings + checking + money_market all combined
    #[test]
    fn reserve_months_combines_all_liquid_types() {
        // 30000 + 10000 + 20000 = 60000 / 5000 = 12 months
        let accounts = vec![
            savings_account(30000.0),
            checking_account(10000.0),
            money_market_account(20000.0),
        ];
        let cf = cashflow(6000.0, 5000.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 12.0);
    }

    // 9c TRIANGULATE: brokerage must NOT count toward reserves
    #[test]
    fn reserve_months_excludes_brokerage() {
        let accounts = vec![savings_account(30000.0), brokerage_account(100000.0)];
        let cf = cashflow(6000.0, 5000.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 6.0);
    }

    // 9c TRIANGULATE: retirement must NOT count toward reserves
    #[test]
    fn reserve_months_excludes_retirement() {
        let accounts = vec![savings_account(30000.0), retirement_account(200000.0)];
        let cf = cashflow(6000.0, 5000.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 6.0);
    }

    #[test]
    fn reserve_months_divides_savings_by_spending() {
        // 30000 savings / 5000 spending = 6 months
        let accounts = vec![savings_account(30000.0)];
        let cf = cashflow(6000.0, 5000.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 6.0);
    }

    #[test]
    fn reserve_months_ignores_non_liquid_accounts() {
        // Only liquid-cash-equivalent types count; brokerage is excluded
        let accounts = vec![savings_account(30000.0), brokerage_account(10000.0)];
        let cf = cashflow(6000.0, 5000.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 6.0);
    }

    #[test]
    fn reserve_months_zero_spending_returns_zero() {
        let accounts = vec![savings_account(30000.0)];
        let cf = cashflow(0.0, 0.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 0.0);
    }

    #[test]
    fn reserve_months_no_liquid_accounts_returns_zero() {
        // Only non-liquid accounts (brokerage) — reserves = 0
        let accounts = vec![brokerage_account(10000.0)];
        let cf = cashflow(6000.0, 5000.0);
        assert_eq!(actual_reserve_months(&accounts, &cf), 0.0);
    }

    // -----------------------------------------------------------------------
    // compute_progress — full integration of goals + actuals
    // -----------------------------------------------------------------------

    fn goals_with_savings_rate(pct: f64) -> Goals {
        Goals {
            savings_rate: Some(SavingsRateGoal {
                target_percent: pct,
            }),
            emergency_fund: None,
            debt_payoff: None,
        }
    }

    fn goals_with_emergency_fund(months: f64) -> Goals {
        Goals {
            savings_rate: None,
            emergency_fund: Some(EmergencyFundGoal {
                target_months: months,
            }),
            debt_payoff: None,
        }
    }

    fn empty_goals() -> Goals {
        Goals {
            savings_rate: None,
            emergency_fund: None,
            debt_payoff: None,
        }
    }

    #[test]
    fn savings_rate_on_track_when_actual_exceeds_goal() {
        let goals = goals_with_savings_rate(20.0);
        // income=10000, spending=7500 → 25% actual, goal 20% → on track
        let cf = cashflow(10000.0, 7500.0);
        let result = compute_progress(&goals, &[], &cf);
        assert_eq!(result.savings_rate.unwrap().status, "on track");
        assert!(result.emergency_fund.is_none());
    }

    #[test]
    fn savings_rate_drifting_when_between_half_and_goal() {
        let goals = goals_with_savings_rate(20.0);
        // 17% actual, goal 20% → drifting
        let cf = cashflow(10000.0, 8300.0);
        let result = compute_progress(&goals, &[], &cf);
        assert_eq!(result.savings_rate.unwrap().status, "drifting");
    }

    #[test]
    fn savings_rate_off_when_below_half_goal() {
        let goals = goals_with_savings_rate(20.0);
        // 6% actual (spending=9400), goal 20% → off
        let cf = cashflow(10000.0, 9400.0);
        let result = compute_progress(&goals, &[], &cf);
        assert_eq!(result.savings_rate.unwrap().status, "off");
    }

    #[test]
    fn emergency_fund_on_track_when_reserves_cover_goal() {
        let goals = goals_with_emergency_fund(6.0);
        let accounts = vec![savings_account(42000.0)]; // 42000/5000 = 8.4 months
        let cf = cashflow(6000.0, 5000.0);
        let result = compute_progress(&goals, &accounts, &cf);
        assert_eq!(result.emergency_fund.unwrap().status, "on track");
    }

    #[test]
    fn emergency_fund_drifting_when_between_half_and_goal() {
        let goals = goals_with_emergency_fund(6.0);
        let accounts = vec![savings_account(20000.0)]; // 20000/5000 = 4 months
        let cf = cashflow(6000.0, 5000.0);
        let result = compute_progress(&goals, &accounts, &cf);
        assert_eq!(result.emergency_fund.unwrap().status, "drifting");
    }

    #[test]
    fn emergency_fund_off_when_below_half_target() {
        let goals = goals_with_emergency_fund(6.0);
        let accounts = vec![savings_account(10000.0)]; // 10000/5000 = 2 months
        let cf = cashflow(6000.0, 5000.0);
        let result = compute_progress(&goals, &accounts, &cf);
        assert_eq!(result.emergency_fund.unwrap().status, "off");
    }

    #[test]
    fn unset_goal_is_not_reported() {
        // No goals set at all → both are None
        let goals = empty_goals();
        let result = compute_progress(&goals, &[], &cashflow(10000.0, 8000.0));
        assert!(result.savings_rate.is_none());
        assert!(result.emergency_fund.is_none());
    }

    // --- RED: empty goals yields a guidance message, not a silent empty payload ---

    #[test]
    fn empty_goals_returns_guidance_message() {
        let goals = empty_goals();
        let result = compute_progress(&goals, &[], &cashflow(10000.0, 8000.0));
        let guidance = result.guidance.as_deref().unwrap_or("");
        assert!(
            guidance.contains("no goals") || guidance.contains("goals.toml"),
            "expected guidance about missing goals, got: {guidance:?}"
        );
    }

    // --- TRIANGULATE: a goal being set means no guidance message ---

    #[test]
    fn goals_present_means_no_guidance() {
        let goals = goals_with_savings_rate(20.0);
        let cf = cashflow(10000.0, 7500.0);
        let result = compute_progress(&goals, &[], &cf);
        assert!(
            result.guidance.is_none(),
            "guidance should be absent when goals are configured"
        );
    }

    // --- debt-payoff-only config: guidance present, mentions debt / #27 ---

    #[test]
    fn debt_payoff_only_config_yields_guidance_mentioning_debt() {
        use crate::goals::DebtPayoffGoal;
        let goals = Goals {
            savings_rate: None,
            emergency_fund: None,
            debt_payoff: Some(DebtPayoffGoal {
                target_date: "2027-12-01".to_string(),
                monthly_payment: Some(500.0),
            }),
        };
        let cf = cashflow(10000.0, 8000.0);
        let result = compute_progress(&goals, &[], &cf);
        let guidance = result
            .guidance
            .as_deref()
            .expect("guidance must be Some for debt-only config");
        assert!(
            guidance.contains("debt") || guidance.contains("#27"),
            "guidance for debt-only config must mention debt or #27, got: {guidance:?}"
        );
    }

    // --- savings-only config: guidance absent (savings_rate is computable) ---

    #[test]
    fn savings_rate_only_config_has_no_guidance() {
        let goals = goals_with_savings_rate(20.0);
        let cf = cashflow(10000.0, 8000.0);
        let result = compute_progress(&goals, &[], &cf);
        assert!(
            result.guidance.is_none(),
            "guidance must be absent when savings_rate goal is set"
        );
    }

    #[test]
    fn unset_savings_rate_absent_even_when_emergency_fund_present() {
        let goals = goals_with_emergency_fund(6.0);
        let accounts = vec![savings_account(30000.0)];
        let cf = cashflow(6000.0, 5000.0);
        let result = compute_progress(&goals, &accounts, &cf);
        assert!(
            result.savings_rate.is_none(),
            "savings_rate should be absent when goal not set"
        );
        assert!(result.emergency_fund.is_some());
    }
}