@dizzlkheinz/ynab-mcpb 0.18.3 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (346) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/CLAUDE.md +87 -8
  3. package/bin/ynab-mcp-server.cjs +2 -2
  4. package/bin/ynab-mcp-server.js +3 -3
  5. package/biome.json +39 -0
  6. package/dist/bundle/index.cjs +67 -67
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +27 -27
  9. package/dist/server/YNABMCPServer.d.ts +3 -4
  10. package/dist/server/YNABMCPServer.js +111 -116
  11. package/dist/server/budgetResolver.d.ts +6 -5
  12. package/dist/server/budgetResolver.js +46 -36
  13. package/dist/server/cacheKeys.js +6 -6
  14. package/dist/server/cacheManager.js +14 -11
  15. package/dist/server/completions.d.ts +2 -2
  16. package/dist/server/completions.js +20 -15
  17. package/dist/server/config.d.ts +10 -5
  18. package/dist/server/config.js +24 -7
  19. package/dist/server/deltaCache.d.ts +2 -2
  20. package/dist/server/deltaCache.js +22 -16
  21. package/dist/server/deltaCache.merge.d.ts +2 -2
  22. package/dist/server/diagnostics.d.ts +4 -4
  23. package/dist/server/diagnostics.js +38 -32
  24. package/dist/server/errorHandler.d.ts +5 -12
  25. package/dist/server/errorHandler.js +219 -217
  26. package/dist/server/prompts.d.ts +2 -2
  27. package/dist/server/prompts.js +45 -45
  28. package/dist/server/rateLimiter.js +4 -4
  29. package/dist/server/requestLogger.d.ts +1 -1
  30. package/dist/server/requestLogger.js +40 -35
  31. package/dist/server/resources.d.ts +3 -3
  32. package/dist/server/resources.js +55 -52
  33. package/dist/server/responseFormatter.js +6 -6
  34. package/dist/server/securityMiddleware.d.ts +2 -2
  35. package/dist/server/securityMiddleware.js +22 -20
  36. package/dist/server/serverKnowledgeStore.js +1 -1
  37. package/dist/server/toolRegistry.d.ts +3 -3
  38. package/dist/server/toolRegistry.js +47 -40
  39. package/dist/tools/__tests__/deltaTestUtils.d.ts +3 -3
  40. package/dist/tools/__tests__/deltaTestUtils.js +2 -2
  41. package/dist/tools/accountTools.d.ts +9 -8
  42. package/dist/tools/accountTools.js +47 -47
  43. package/dist/tools/adapters.d.ts +13 -8
  44. package/dist/tools/adapters.js +21 -11
  45. package/dist/tools/budgetTools.d.ts +8 -7
  46. package/dist/tools/budgetTools.js +22 -22
  47. package/dist/tools/categoryTools.d.ts +9 -8
  48. package/dist/tools/categoryTools.js +68 -59
  49. package/dist/tools/compareTransactions/formatter.d.ts +3 -3
  50. package/dist/tools/compareTransactions/formatter.js +9 -9
  51. package/dist/tools/compareTransactions/index.d.ts +6 -6
  52. package/dist/tools/compareTransactions/index.js +58 -43
  53. package/dist/tools/compareTransactions/matcher.d.ts +1 -1
  54. package/dist/tools/compareTransactions/matcher.js +28 -15
  55. package/dist/tools/compareTransactions/parser.d.ts +2 -2
  56. package/dist/tools/compareTransactions/parser.js +144 -138
  57. package/dist/tools/compareTransactions/types.d.ts +4 -4
  58. package/dist/tools/compareTransactions.d.ts +1 -1
  59. package/dist/tools/compareTransactions.js +1 -1
  60. package/dist/tools/deltaFetcher.d.ts +2 -2
  61. package/dist/tools/deltaFetcher.js +16 -15
  62. package/dist/tools/deltaSupport.d.ts +4 -4
  63. package/dist/tools/deltaSupport.js +35 -41
  64. package/dist/tools/exportTransactions.d.ts +5 -4
  65. package/dist/tools/exportTransactions.js +61 -59
  66. package/dist/tools/monthTools.d.ts +7 -6
  67. package/dist/tools/monthTools.js +31 -29
  68. package/dist/tools/payeeTools.d.ts +7 -6
  69. package/dist/tools/payeeTools.js +28 -28
  70. package/dist/tools/reconcileAdapter.d.ts +2 -2
  71. package/dist/tools/reconcileAdapter.js +21 -11
  72. package/dist/tools/reconciliation/analyzer.d.ts +4 -4
  73. package/dist/tools/reconciliation/analyzer.js +136 -57
  74. package/dist/tools/reconciliation/csvParser.d.ts +3 -3
  75. package/dist/tools/reconciliation/csvParser.js +128 -104
  76. package/dist/tools/reconciliation/executor.d.ts +4 -4
  77. package/dist/tools/reconciliation/executor.js +148 -109
  78. package/dist/tools/reconciliation/index.d.ts +10 -10
  79. package/dist/tools/reconciliation/index.js +96 -83
  80. package/dist/tools/reconciliation/matcher.d.ts +3 -3
  81. package/dist/tools/reconciliation/matcher.js +17 -16
  82. package/dist/tools/reconciliation/payeeNormalizer.js +19 -8
  83. package/dist/tools/reconciliation/recommendationEngine.d.ts +1 -1
  84. package/dist/tools/reconciliation/recommendationEngine.js +40 -40
  85. package/dist/tools/reconciliation/reportFormatter.d.ts +2 -2
  86. package/dist/tools/reconciliation/reportFormatter.js +79 -54
  87. package/dist/tools/reconciliation/signDetector.d.ts +1 -1
  88. package/dist/tools/reconciliation/types.d.ts +19 -16
  89. package/dist/tools/reconciliation/ynabAdapter.d.ts +2 -2
  90. package/dist/tools/schemas/common.d.ts +1 -1
  91. package/dist/tools/schemas/common.js +1 -1
  92. package/dist/tools/schemas/outputs/accountOutputs.d.ts +1 -1
  93. package/dist/tools/schemas/outputs/accountOutputs.js +24 -18
  94. package/dist/tools/schemas/outputs/budgetOutputs.d.ts +1 -1
  95. package/dist/tools/schemas/outputs/budgetOutputs.js +14 -11
  96. package/dist/tools/schemas/outputs/categoryOutputs.d.ts +1 -1
  97. package/dist/tools/schemas/outputs/categoryOutputs.js +49 -29
  98. package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +1 -1
  99. package/dist/tools/schemas/outputs/comparisonOutputs.js +12 -12
  100. package/dist/tools/schemas/outputs/index.d.ts +14 -14
  101. package/dist/tools/schemas/outputs/index.js +14 -14
  102. package/dist/tools/schemas/outputs/monthOutputs.d.ts +1 -1
  103. package/dist/tools/schemas/outputs/monthOutputs.js +56 -41
  104. package/dist/tools/schemas/outputs/payeeOutputs.d.ts +1 -1
  105. package/dist/tools/schemas/outputs/payeeOutputs.js +10 -10
  106. package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +2 -2
  107. package/dist/tools/schemas/outputs/reconciliationOutputs.js +45 -45
  108. package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +1 -1
  109. package/dist/tools/schemas/outputs/transactionMutationOutputs.js +28 -22
  110. package/dist/tools/schemas/outputs/transactionOutputs.d.ts +1 -1
  111. package/dist/tools/schemas/outputs/transactionOutputs.js +43 -35
  112. package/dist/tools/schemas/outputs/utilityOutputs.d.ts +1 -1
  113. package/dist/tools/schemas/outputs/utilityOutputs.js +5 -3
  114. package/dist/tools/schemas/shared/commonOutputs.d.ts +1 -1
  115. package/dist/tools/schemas/shared/commonOutputs.js +15 -9
  116. package/dist/tools/transactionReadTools.d.ts +11 -0
  117. package/dist/tools/transactionReadTools.js +202 -0
  118. package/dist/tools/transactionSchemas.d.ts +309 -0
  119. package/dist/tools/transactionSchemas.js +235 -0
  120. package/dist/tools/transactionTools.d.ts +6 -302
  121. package/dist/tools/transactionTools.js +7 -2054
  122. package/dist/tools/transactionUtils.d.ts +31 -0
  123. package/dist/tools/transactionUtils.js +364 -0
  124. package/dist/tools/transactionWriteTools.d.ts +20 -0
  125. package/dist/tools/transactionWriteTools.js +1342 -0
  126. package/dist/tools/utilityTools.d.ts +5 -4
  127. package/dist/tools/utilityTools.js +11 -11
  128. package/dist/types/index.d.ts +7 -7
  129. package/dist/types/index.js +6 -6
  130. package/dist/types/reconciliation.d.ts +1 -1
  131. package/dist/types/toolRegistration.d.ts +14 -12
  132. package/dist/utils/amountUtils.js +1 -1
  133. package/dist/utils/dateUtils.js +4 -4
  134. package/dist/utils/errors.d.ts +3 -3
  135. package/dist/utils/errors.js +4 -4
  136. package/dist/utils/money.d.ts +2 -2
  137. package/dist/utils/money.js +8 -8
  138. package/dist/utils/validationError.d.ts +1 -1
  139. package/dist/utils/validationError.js +1 -1
  140. package/docs/assets/examples/reconciliation-with-recommendations.json +66 -66
  141. package/docs/assets/schemas/reconciliation-v2.json +360 -336
  142. package/docs/plans/2025-12-25-transaction-tools-refactor-design.md +211 -0
  143. package/docs/plans/2025-12-25-transaction-tools-refactor.md +905 -0
  144. package/esbuild.config.mjs +53 -50
  145. package/meta.json +12548 -12548
  146. package/package.json +98 -109
  147. package/scripts/analyze-bundle.mjs +33 -30
  148. package/scripts/create-pr-description.js +169 -120
  149. package/scripts/run-all-tests.js +205 -0
  150. package/scripts/run-domain-integration-tests.js +28 -18
  151. package/scripts/run-generate-mcpb.js +19 -17
  152. package/scripts/run-throttled-integration-tests.js +92 -83
  153. package/scripts/test-delta-params.mjs +149 -120
  154. package/scripts/test-recommendations.ts +36 -32
  155. package/scripts/tmpTransaction.ts +80 -43
  156. package/scripts/validate-env.js +98 -91
  157. package/scripts/verify-build.js +78 -76
  158. package/src/__tests__/comprehensive.integration.test.ts +1281 -1154
  159. package/src/__tests__/performance.test.ts +723 -671
  160. package/src/__tests__/setup.ts +442 -395
  161. package/src/__tests__/smoke.e2e.test.ts +41 -39
  162. package/src/__tests__/testRunner.ts +314 -295
  163. package/src/__tests__/testUtils.ts +456 -364
  164. package/src/__tests__/tools/reconciliation/csvParser.integration.test.ts +109 -107
  165. package/src/__tests__/tools/reconciliation/real-world.integration.test.ts +41 -41
  166. package/src/index.ts +68 -59
  167. package/src/server/CLAUDE.md +480 -0
  168. package/src/server/YNABMCPServer.ts +821 -794
  169. package/src/server/__tests__/YNABMCPServer.integration.test.ts +929 -893
  170. package/src/server/__tests__/YNABMCPServer.test.ts +903 -899
  171. package/src/server/__tests__/budgetResolver.test.ts +466 -423
  172. package/src/server/__tests__/cacheManager.test.ts +891 -874
  173. package/src/server/__tests__/completions.integration.test.ts +115 -106
  174. package/src/server/__tests__/completions.test.ts +334 -313
  175. package/src/server/__tests__/config.test.ts +98 -86
  176. package/src/server/__tests__/deltaCache.merge.test.ts +774 -703
  177. package/src/server/__tests__/deltaCache.swr.test.ts +198 -153
  178. package/src/server/__tests__/deltaCache.test.ts +946 -759
  179. package/src/server/__tests__/diagnostics.test.ts +825 -792
  180. package/src/server/__tests__/errorHandler.integration.test.ts +512 -462
  181. package/src/server/__tests__/errorHandler.test.ts +402 -397
  182. package/src/server/__tests__/prompts.test.ts +424 -347
  183. package/src/server/__tests__/rateLimiter.test.ts +313 -309
  184. package/src/server/__tests__/requestLogger.test.ts +443 -403
  185. package/src/server/__tests__/resources.template.test.ts +196 -185
  186. package/src/server/__tests__/resources.test.ts +294 -288
  187. package/src/server/__tests__/security.integration.test.ts +487 -421
  188. package/src/server/__tests__/securityMiddleware.test.ts +519 -444
  189. package/src/server/__tests__/server-startup.integration.test.ts +509 -490
  190. package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -173
  191. package/src/server/__tests__/toolRegistration.test.ts +239 -210
  192. package/src/server/__tests__/toolRegistry.test.ts +907 -845
  193. package/src/server/budgetResolver.ts +221 -181
  194. package/src/server/cacheKeys.ts +6 -6
  195. package/src/server/cacheManager.ts +498 -484
  196. package/src/server/completions.ts +267 -243
  197. package/src/server/config.ts +35 -14
  198. package/src/server/deltaCache.merge.ts +146 -128
  199. package/src/server/deltaCache.ts +352 -309
  200. package/src/server/diagnostics.ts +257 -242
  201. package/src/server/errorHandler.ts +747 -744
  202. package/src/server/prompts.ts +181 -176
  203. package/src/server/rateLimiter.ts +131 -129
  204. package/src/server/requestLogger.ts +350 -322
  205. package/src/server/resources.ts +442 -374
  206. package/src/server/responseFormatter.ts +41 -37
  207. package/src/server/securityMiddleware.ts +223 -205
  208. package/src/server/serverKnowledgeStore.ts +67 -67
  209. package/src/server/toolRegistry.ts +508 -474
  210. package/src/tools/CLAUDE.md +604 -0
  211. package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -111
  212. package/src/tools/__tests__/accountTools.integration.test.ts +129 -111
  213. package/src/tools/__tests__/accountTools.test.ts +685 -638
  214. package/src/tools/__tests__/adapters.test.ts +142 -108
  215. package/src/tools/__tests__/budgetTools.delta.integration.test.ts +73 -73
  216. package/src/tools/__tests__/budgetTools.integration.test.ts +132 -124
  217. package/src/tools/__tests__/budgetTools.test.ts +442 -413
  218. package/src/tools/__tests__/categoryTools.delta.integration.test.ts +76 -68
  219. package/src/tools/__tests__/categoryTools.integration.test.ts +314 -288
  220. package/src/tools/__tests__/categoryTools.test.ts +656 -625
  221. package/src/tools/__tests__/compareTransactions/formatter.test.ts +535 -462
  222. package/src/tools/__tests__/compareTransactions/index.test.ts +378 -358
  223. package/src/tools/__tests__/compareTransactions/matcher.test.ts +497 -398
  224. package/src/tools/__tests__/compareTransactions/parser.test.ts +765 -747
  225. package/src/tools/__tests__/compareTransactions.test.ts +352 -332
  226. package/src/tools/__tests__/compareTransactions.window.test.ts +150 -146
  227. package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +69 -65
  228. package/src/tools/__tests__/deltaFetcher.test.ts +325 -265
  229. package/src/tools/__tests__/deltaSupport.test.ts +211 -184
  230. package/src/tools/__tests__/deltaTestUtils.ts +37 -33
  231. package/src/tools/__tests__/exportTransactions.test.ts +205 -200
  232. package/src/tools/__tests__/monthTools.delta.integration.test.ts +68 -68
  233. package/src/tools/__tests__/monthTools.integration.test.ts +178 -166
  234. package/src/tools/__tests__/monthTools.test.ts +561 -512
  235. package/src/tools/__tests__/payeeTools.delta.integration.test.ts +68 -68
  236. package/src/tools/__tests__/payeeTools.integration.test.ts +158 -142
  237. package/src/tools/__tests__/payeeTools.test.ts +486 -434
  238. package/src/tools/__tests__/transactionSchemas.test.ts +1204 -0
  239. package/src/tools/__tests__/transactionTools.integration.test.ts +875 -825
  240. package/src/tools/__tests__/transactionTools.test.ts +4923 -4366
  241. package/src/tools/__tests__/transactionUtils.test.ts +1016 -0
  242. package/src/tools/__tests__/utilityTools.integration.test.ts +32 -32
  243. package/src/tools/__tests__/utilityTools.test.ts +68 -58
  244. package/src/tools/accountTools.ts +293 -271
  245. package/src/tools/adapters.ts +120 -63
  246. package/src/tools/budgetTools.ts +121 -116
  247. package/src/tools/categoryTools.ts +379 -339
  248. package/src/tools/compareTransactions/formatter.ts +131 -119
  249. package/src/tools/compareTransactions/index.ts +249 -214
  250. package/src/tools/compareTransactions/matcher.ts +259 -209
  251. package/src/tools/compareTransactions/parser.ts +517 -487
  252. package/src/tools/compareTransactions/types.ts +38 -38
  253. package/src/tools/compareTransactions.ts +1 -1
  254. package/src/tools/deltaFetcher.ts +281 -260
  255. package/src/tools/deltaSupport.ts +264 -259
  256. package/src/tools/exportTransactions.ts +230 -218
  257. package/src/tools/monthTools.ts +180 -165
  258. package/src/tools/payeeTools.ts +152 -140
  259. package/src/tools/reconcileAdapter.ts +297 -246
  260. package/src/tools/reconciliation/CLAUDE.md +506 -0
  261. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +135 -112
  262. package/src/tools/reconciliation/__tests__/adapter.test.ts +249 -227
  263. package/src/tools/reconciliation/__tests__/analyzer.test.ts +408 -335
  264. package/src/tools/reconciliation/__tests__/csvParser.test.ts +71 -69
  265. package/src/tools/reconciliation/__tests__/executor.integration.test.ts +348 -323
  266. package/src/tools/reconciliation/__tests__/executor.progress.test.ts +503 -457
  267. package/src/tools/reconciliation/__tests__/executor.test.ts +898 -831
  268. package/src/tools/reconciliation/__tests__/matcher.test.ts +667 -663
  269. package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +296 -276
  270. package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +692 -624
  271. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1008 -986
  272. package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +187 -146
  273. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +583 -530
  274. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +75 -71
  275. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +70 -58
  276. package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +102 -88
  277. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +58 -43
  278. package/src/tools/reconciliation/__tests__/signDetector.test.ts +209 -206
  279. package/src/tools/reconciliation/__tests__/ynabAdapter.test.ts +66 -60
  280. package/src/tools/reconciliation/analyzer.ts +582 -406
  281. package/src/tools/reconciliation/csvParser.ts +656 -609
  282. package/src/tools/reconciliation/executor.ts +1290 -1128
  283. package/src/tools/reconciliation/index.ts +580 -528
  284. package/src/tools/reconciliation/matcher.ts +256 -240
  285. package/src/tools/reconciliation/payeeNormalizer.ts +92 -78
  286. package/src/tools/reconciliation/recommendationEngine.ts +357 -345
  287. package/src/tools/reconciliation/reportFormatter.ts +349 -276
  288. package/src/tools/reconciliation/signDetector.ts +89 -83
  289. package/src/tools/reconciliation/types.ts +164 -153
  290. package/src/tools/reconciliation/ynabAdapter.ts +17 -15
  291. package/src/tools/schemas/CLAUDE.md +546 -0
  292. package/src/tools/schemas/common.ts +1 -1
  293. package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +410 -409
  294. package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +305 -299
  295. package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +431 -430
  296. package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +510 -495
  297. package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +179 -153
  298. package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +293 -254
  299. package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +457 -457
  300. package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +362 -356
  301. package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +402 -399
  302. package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +225 -211
  303. package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +457 -454
  304. package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +316 -315
  305. package/src/tools/schemas/outputs/accountOutputs.ts +40 -34
  306. package/src/tools/schemas/outputs/budgetOutputs.ts +24 -19
  307. package/src/tools/schemas/outputs/categoryOutputs.ts +76 -56
  308. package/src/tools/schemas/outputs/comparisonOutputs.ts +192 -169
  309. package/src/tools/schemas/outputs/index.ts +163 -163
  310. package/src/tools/schemas/outputs/monthOutputs.ts +95 -80
  311. package/src/tools/schemas/outputs/payeeOutputs.ts +18 -18
  312. package/src/tools/schemas/outputs/reconciliationOutputs.ts +386 -373
  313. package/src/tools/schemas/outputs/transactionMutationOutputs.ts +259 -231
  314. package/src/tools/schemas/outputs/transactionOutputs.ts +81 -71
  315. package/src/tools/schemas/outputs/utilityOutputs.ts +90 -84
  316. package/src/tools/schemas/shared/commonOutputs.ts +27 -19
  317. package/src/tools/toolCategories.ts +114 -114
  318. package/src/tools/transactionReadTools.ts +327 -0
  319. package/src/tools/transactionSchemas.ts +484 -0
  320. package/src/tools/transactionTools.ts +107 -2990
  321. package/src/tools/transactionUtils.ts +621 -0
  322. package/src/tools/transactionWriteTools.ts +2110 -0
  323. package/src/tools/utilityTools.ts +46 -41
  324. package/src/types/CLAUDE.md +477 -0
  325. package/src/types/__tests__/index.test.ts +51 -51
  326. package/src/types/index.ts +43 -39
  327. package/src/types/integration-tests.d.ts +26 -26
  328. package/src/types/reconciliation.ts +29 -29
  329. package/src/types/toolAnnotations.ts +30 -30
  330. package/src/types/toolRegistration.ts +43 -32
  331. package/src/utils/CLAUDE.md +508 -0
  332. package/src/utils/__tests__/dateUtils.test.ts +174 -168
  333. package/src/utils/__tests__/money.test.ts +193 -187
  334. package/src/utils/amountUtils.ts +5 -5
  335. package/src/utils/baseError.ts +5 -5
  336. package/src/utils/dateUtils.ts +29 -26
  337. package/src/utils/errors.ts +14 -14
  338. package/src/utils/money.ts +66 -52
  339. package/src/utils/validationError.ts +1 -1
  340. package/tsconfig.json +29 -29
  341. package/tsconfig.prod.json +16 -16
  342. package/vitest-reporters/split-json-reporter.ts +247 -204
  343. package/vitest.config.ts +99 -95
  344. package/.prettierignore +0 -10
  345. package/.prettierrc.json +0 -10
  346. package/eslint.config.js +0 -49
@@ -1,653 +1,700 @@
1
- import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
2
- import * as ynab from 'ynab';
1
+ import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import type * as ynab from "ynab";
3
3
  import {
4
- handleListAccounts,
5
- handleGetAccount,
6
- handleCreateAccount,
7
- ListAccountsSchema,
8
- GetAccountSchema,
9
- CreateAccountSchema,
10
- } from '../accountTools.js';
11
- import { createDeltaFetcherMock, createRejectingDeltaFetcherMock } from './deltaTestUtils.js';
4
+ CreateAccountSchema,
5
+ GetAccountSchema,
6
+ ListAccountsSchema,
7
+ handleCreateAccount,
8
+ handleGetAccount,
9
+ handleListAccounts,
10
+ } from "../accountTools.js";
11
+ import {
12
+ createDeltaFetcherMock,
13
+ createRejectingDeltaFetcherMock,
14
+ } from "./deltaTestUtils.js";
12
15
 
13
16
  // Mock the cache manager
14
- vi.mock('../../server/cacheManager.js', () => ({
15
- cacheManager: {
16
- wrap: vi.fn(),
17
- has: vi.fn(),
18
- delete: vi.fn(),
19
- deleteMany: vi.fn(),
20
- deleteByPrefix: vi.fn(),
21
- deleteByBudgetId: vi.fn(),
22
- clear: vi.fn(),
23
- },
24
- CacheManager: {
25
- generateKey: vi.fn(),
26
- },
27
- CACHE_TTLS: {
28
- ACCOUNTS: 300000,
29
- },
17
+ vi.mock("../../server/cacheManager.js", () => ({
18
+ cacheManager: {
19
+ wrap: vi.fn(),
20
+ has: vi.fn(),
21
+ delete: vi.fn(),
22
+ deleteMany: vi.fn(),
23
+ deleteByPrefix: vi.fn(),
24
+ deleteByBudgetId: vi.fn(),
25
+ clear: vi.fn(),
26
+ },
27
+ CacheManager: {
28
+ generateKey: vi.fn(),
29
+ },
30
+ CACHE_TTLS: {
31
+ ACCOUNTS: 300000,
32
+ },
30
33
  }));
31
34
 
32
35
  // Mock the YNAB API
33
36
  const mockYnabAPI = {
34
- accounts: {
35
- getAccounts: vi.fn(),
36
- getAccountById: vi.fn(),
37
- createAccount: vi.fn(),
38
- },
37
+ accounts: {
38
+ getAccounts: vi.fn(),
39
+ getAccountById: vi.fn(),
40
+ createAccount: vi.fn(),
41
+ },
39
42
  } as unknown as ynab.API;
40
43
 
41
44
  // Import mocked cache manager
42
- const { cacheManager, CacheManager } = await import('../../server/cacheManager.js');
45
+ const { cacheManager, CacheManager } = await import(
46
+ "../../server/cacheManager.js"
47
+ );
43
48
 
44
49
  // Capture original NODE_ENV for restoration
45
50
  const originalNodeEnv = process.env.NODE_ENV;
46
51
 
47
- describe('Account Tools', () => {
48
- beforeEach(() => {
49
- vi.resetAllMocks();
50
- // Reset NODE_ENV to test to ensure cache bypassing in tests
51
- process.env['NODE_ENV'] = 'test';
52
- (cacheManager.wrap as ReturnType<typeof vi.fn>).mockImplementation(
53
- async (
54
- _key: string,
55
- options: {
56
- loader: () => Promise<unknown>;
57
- },
58
- ) => {
59
- return await options.loader();
60
- },
61
- );
62
- (cacheManager.has as ReturnType<typeof vi.fn>).mockReturnValue(false);
63
- (CacheManager.generateKey as ReturnType<typeof vi.fn>).mockImplementation(
64
- (prefix: string, ...parts: (string | number | boolean | undefined)[]) =>
65
- [prefix, ...parts.filter((part) => part !== undefined)].join(':'),
66
- );
67
- });
68
-
69
- afterAll(() => {
70
- // Restore original NODE_ENV value
71
- if (originalNodeEnv === undefined) {
72
- delete process.env.NODE_ENV;
73
- } else {
74
- process.env.NODE_ENV = originalNodeEnv;
75
- }
76
- });
77
-
78
- describe('handleListAccounts', () => {
79
- it('should include cache metadata from delta fetcher results', async () => {
80
- const mockAccounts = [
81
- {
82
- id: 'account-1',
83
- name: 'Checking Account',
84
- type: 'checking',
85
- on_budget: true,
86
- closed: false,
87
- note: 'Main checking account',
88
- balance: 100000,
89
- cleared_balance: 95000,
90
- uncleared_balance: 5000,
91
- transfer_payee_id: 'payee-1',
92
- direct_import_linked: false,
93
- direct_import_in_error: false,
94
- },
95
- ];
96
- const { fetcher, resolved } = createDeltaFetcherMock('fetchAccounts', {
97
- data: mockAccounts,
98
- wasCached: true,
99
- usedDelta: true,
100
- });
101
-
102
- const result = await handleListAccounts(mockYnabAPI, fetcher, { budget_id: 'budget-1' });
103
-
104
- const fetchAccountsMock = fetcher.fetchAccounts as ReturnType<typeof vi.fn>;
105
- expect(fetchAccountsMock).toHaveBeenCalledWith('budget-1');
106
-
107
- const parsedContent = JSON.parse(result.content[0].text);
108
- expect(parsedContent.cached).toBe(resolved.wasCached);
109
- expect(parsedContent.cache_info).toContain('delta merge applied');
110
- });
111
-
112
- it('should return formatted account list on success', async () => {
113
- const mockAccounts = [
114
- {
115
- id: 'account-1',
116
- name: 'Checking Account',
117
- type: 'checking',
118
- on_budget: true,
119
- closed: false,
120
- note: 'Main checking account',
121
- balance: 100000,
122
- cleared_balance: 95000,
123
- uncleared_balance: 5000,
124
- transfer_payee_id: 'payee-1',
125
- direct_import_linked: false,
126
- direct_import_in_error: false,
127
- },
128
- {
129
- id: 'account-2',
130
- name: 'Savings Account',
131
- type: 'savings',
132
- on_budget: true,
133
- closed: false,
134
- note: 'Emergency fund',
135
- balance: 500000,
136
- cleared_balance: 500000,
137
- uncleared_balance: 0,
138
- transfer_payee_id: 'payee-2',
139
- direct_import_linked: true,
140
- direct_import_in_error: false,
141
- },
142
- ];
143
- const { fetcher, resolved } = createDeltaFetcherMock('fetchAccounts', {
144
- data: mockAccounts,
145
- wasCached: false,
146
- });
147
-
148
- const result = await handleListAccounts(mockYnabAPI, fetcher, { budget_id: 'budget-1' });
149
-
150
- expect(result.content).toHaveLength(1);
151
- expect(result.content[0].type).toBe('text');
152
-
153
- const parsedContent = JSON.parse(result.content[0].text);
154
- expect(parsedContent.accounts).toHaveLength(2);
155
- expect(parsedContent.accounts[0]).toEqual({
156
- id: 'account-1',
157
- name: 'Checking Account',
158
- type: 'checking',
159
- on_budget: true,
160
- closed: false,
161
- note: 'Main checking account',
162
- balance: 100,
163
- cleared_balance: 95,
164
- uncleared_balance: 5,
165
- transfer_payee_id: 'payee-1',
166
- direct_import_linked: false,
167
- direct_import_in_error: false,
168
- });
169
- expect(parsedContent.cached).toBe(resolved.wasCached);
170
- expect(parsedContent.cache_info).toBe('Fresh data retrieved from YNAB API');
171
- });
172
-
173
- it('should handle 404 budget not found errors', async () => {
174
- const { fetcher } = createRejectingDeltaFetcherMock(
175
- 'fetchAccounts',
176
- new Error('404 Not Found'),
177
- );
178
-
179
- const result = await handleListAccounts(mockYnabAPI, fetcher, {
180
- budget_id: 'invalid-budget',
181
- });
182
-
183
- expect(result.content).toHaveLength(1);
184
- const parsedContent = JSON.parse(result.content[0].text);
185
- expect(parsedContent.error.message).toBe(
186
- 'Failed to list accounts - budget or account not found',
187
- );
188
- });
189
-
190
- it('should handle 401 authentication errors', async () => {
191
- const { fetcher } = createRejectingDeltaFetcherMock(
192
- 'fetchAccounts',
193
- new Error('401 Unauthorized'),
194
- );
195
-
196
- const result = await handleListAccounts(mockYnabAPI, fetcher, { budget_id: 'budget-1' });
197
-
198
- expect(result.content).toHaveLength(1);
199
- const parsedContent = JSON.parse(result.content[0].text);
200
- expect(parsedContent.error.message).toBe('Invalid or expired YNAB access token');
201
- });
202
-
203
- it('should handle generic errors', async () => {
204
- const { fetcher } = createRejectingDeltaFetcherMock(
205
- 'fetchAccounts',
206
- new Error('Network error'),
207
- );
208
-
209
- const result = await handleListAccounts(mockYnabAPI, fetcher, { budget_id: 'budget-1' });
210
-
211
- expect(result.content).toHaveLength(1);
212
- const parsedContent = JSON.parse(result.content[0].text);
213
- expect(parsedContent.error.message).toBe('Failed to list accounts');
214
- });
215
- });
216
-
217
- describe('handleGetAccount', () => {
218
- it('should return detailed account information on success', async () => {
219
- const mockAccount = {
220
- id: 'account-1',
221
- name: 'Checking Account',
222
- type: 'checking',
223
- on_budget: true,
224
- closed: false,
225
- note: 'Main checking account',
226
- balance: 100000,
227
- cleared_balance: 95000,
228
- uncleared_balance: 5000,
229
- transfer_payee_id: 'payee-1',
230
- direct_import_linked: false,
231
- direct_import_in_error: false,
232
- };
233
-
234
- (mockYnabAPI.accounts.getAccountById as any).mockResolvedValue({
235
- data: { account: mockAccount },
236
- });
237
-
238
- const result = await handleGetAccount(mockYnabAPI, {
239
- budget_id: 'budget-1',
240
- account_id: 'account-1',
241
- });
242
-
243
- expect(result.content).toHaveLength(1);
244
- expect(result.content[0].type).toBe('text');
245
-
246
- const parsedContent = JSON.parse(result.content[0].text);
247
- expect(parsedContent.account).toEqual({
248
- id: 'account-1',
249
- name: 'Checking Account',
250
- type: 'checking',
251
- on_budget: true,
252
- closed: false,
253
- note: 'Main checking account',
254
- balance: 100,
255
- cleared_balance: 95,
256
- uncleared_balance: 5,
257
- transfer_payee_id: 'payee-1',
258
- direct_import_linked: false,
259
- direct_import_in_error: false,
260
- });
261
- expect(parsedContent.cached).toBe(false);
262
- expect(parsedContent.cache_info).toBe('Fresh data retrieved from YNAB API');
263
- });
264
-
265
- it('should report cached responses when cache entries exist', async () => {
266
- const mockAccount = {
267
- id: 'account-1',
268
- name: 'Checking Account',
269
- type: 'checking',
270
- on_budget: true,
271
- closed: false,
272
- note: 'Main checking account',
273
- balance: 100000,
274
- cleared_balance: 95000,
275
- uncleared_balance: 5000,
276
- transfer_payee_id: 'payee-1',
277
- direct_import_linked: false,
278
- direct_import_in_error: false,
279
- };
280
-
281
- (mockYnabAPI.accounts.getAccountById as any).mockResolvedValue({
282
- data: { account: mockAccount },
283
- });
284
- (cacheManager.has as ReturnType<typeof vi.fn>).mockReturnValueOnce(true);
285
-
286
- const result = await handleGetAccount(mockYnabAPI, {
287
- budget_id: 'budget-1',
288
- account_id: 'account-1',
289
- });
290
-
291
- const parsedContent = JSON.parse(result.content[0].text);
292
- expect(parsedContent.cached).toBe(true);
293
- expect(parsedContent.cache_info).toBe('Data retrieved from cache for improved performance');
294
- });
295
-
296
- it('should handle 404 account not found errors', async () => {
297
- (mockYnabAPI.accounts.getAccountById as any).mockRejectedValue(new Error('404 Not Found'));
298
-
299
- const result = await handleGetAccount(mockYnabAPI, {
300
- budget_id: 'budget-1',
301
- account_id: 'invalid-account',
302
- });
303
-
304
- expect(result.content).toHaveLength(1);
305
- const parsedContent = JSON.parse(result.content[0].text);
306
- expect(parsedContent.error.message).toBe(
307
- 'Failed to get account - budget or account not found',
308
- );
309
- });
310
-
311
- it('should handle authentication errors', async () => {
312
- (mockYnabAPI.accounts.getAccountById as any).mockRejectedValue(new Error('401 Unauthorized'));
313
-
314
- const result = await handleGetAccount(mockYnabAPI, {
315
- budget_id: 'budget-1',
316
- account_id: 'account-1',
317
- });
318
-
319
- expect(result.content).toHaveLength(1);
320
- const parsedContent = JSON.parse(result.content[0].text);
321
- expect(parsedContent.error.message).toBe('Invalid or expired YNAB access token');
322
- });
323
- });
324
-
325
- describe('handleCreateAccount', () => {
326
- it('should create account with all supported types', async () => {
327
- const accountTypes = [
328
- 'checking',
329
- 'savings',
330
- 'creditCard',
331
- 'cash',
332
- 'lineOfCredit',
333
- 'otherAsset',
334
- 'otherLiability',
335
- ];
336
-
337
- for (const accountType of accountTypes) {
338
- const mockAccount = {
339
- id: `account-${accountType}`,
340
- name: `${accountType} Account`,
341
- type: accountType,
342
- on_budget: true,
343
- closed: false,
344
- note: null,
345
- balance: 100000,
346
- cleared_balance: 100000,
347
- uncleared_balance: 0,
348
- transfer_payee_id: `payee-${accountType}`,
349
- direct_import_linked: false,
350
- direct_import_in_error: false,
351
- };
352
-
353
- (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
354
- data: { account: mockAccount },
355
- });
356
-
357
- const result = await handleCreateAccount(mockYnabAPI, {
358
- budget_id: 'budget-1',
359
- name: `${accountType} Account`,
360
- type: accountType as any,
361
- balance: 100,
362
- });
363
-
364
- expect(result.content).toHaveLength(1);
365
- const parsedContent = JSON.parse(result.content[0].text);
366
- expect(parsedContent.account.type).toBe(accountType);
367
- expect(parsedContent.account.name).toBe(`${accountType} Account`);
368
- }
369
- });
370
-
371
- it('should create account without initial balance', async () => {
372
- const mockAccount = {
373
- id: 'account-1',
374
- name: 'New Account',
375
- type: 'checking',
376
- on_budget: true,
377
- closed: false,
378
- note: null,
379
- balance: 0,
380
- cleared_balance: 0,
381
- uncleared_balance: 0,
382
- transfer_payee_id: 'payee-1',
383
- direct_import_linked: false,
384
- direct_import_in_error: false,
385
- };
386
-
387
- (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
388
- data: { account: mockAccount },
389
- });
390
-
391
- const result = await handleCreateAccount(mockYnabAPI, {
392
- budget_id: 'budget-1',
393
- name: 'New Account',
394
- type: 'checking',
395
- });
396
-
397
- expect(result.content).toHaveLength(1);
398
- const parsedContent = JSON.parse(result.content[0].text);
399
- expect(parsedContent.account.balance).toBe(0);
400
-
401
- // Verify the API was called with balance 0 in milliunits
402
- expect(mockYnabAPI.accounts.createAccount).toHaveBeenCalledWith('budget-1', {
403
- account: {
404
- name: 'New Account',
405
- type: 'checking',
406
- balance: 0,
407
- },
408
- });
409
- });
410
-
411
- it('should convert balance to milliunits', async () => {
412
- const mockAccount = {
413
- id: 'account-1',
414
- name: 'New Account',
415
- type: 'checking',
416
- on_budget: true,
417
- closed: false,
418
- note: null,
419
- balance: 150000,
420
- cleared_balance: 150000,
421
- uncleared_balance: 0,
422
- transfer_payee_id: 'payee-1',
423
- direct_import_linked: false,
424
- direct_import_in_error: false,
425
- };
426
-
427
- (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
428
- data: { account: mockAccount },
429
- });
430
-
431
- await handleCreateAccount(mockYnabAPI, {
432
- budget_id: 'budget-1',
433
- name: 'New Account',
434
- type: 'checking',
435
- balance: 150, // $150 should become 150000 milliunits
436
- });
437
-
438
- // Verify the API was called with balance converted to milliunits
439
- expect(mockYnabAPI.accounts.createAccount).toHaveBeenCalledWith('budget-1', {
440
- account: {
441
- name: 'New Account',
442
- type: 'checking',
443
- balance: 150000,
444
- },
445
- });
446
- });
447
-
448
- it('should handle creation errors', async () => {
449
- (mockYnabAPI.accounts.createAccount as any).mockRejectedValue(new Error('400 Bad Request'));
450
-
451
- const result = await handleCreateAccount(mockYnabAPI, {
452
- budget_id: 'budget-1',
453
- name: 'New Account',
454
- type: 'checking',
455
- });
456
-
457
- expect(result.content).toHaveLength(1);
458
- const parsedContent = JSON.parse(result.content[0].text);
459
- expect(parsedContent.error.message).toBe('Failed to create account');
460
- });
461
-
462
- it('should invalidate account list cache on successful account creation', async () => {
463
- const mockAccount = {
464
- id: 'account-1',
465
- name: 'New Account',
466
- type: 'checking',
467
- on_budget: true,
468
- closed: false,
469
- note: null,
470
- balance: 100000,
471
- cleared_balance: 100000,
472
- uncleared_balance: 0,
473
- transfer_payee_id: 'payee-1',
474
- direct_import_linked: false,
475
- direct_import_in_error: false,
476
- };
477
-
478
- (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
479
- data: { account: mockAccount },
480
- });
481
-
482
- const result = await handleCreateAccount(mockYnabAPI, {
483
- budget_id: 'budget-1',
484
- name: 'New Account',
485
- type: 'checking',
486
- });
487
-
488
- // Verify cache was invalidated for account list
489
- expect(CacheManager.generateKey).toHaveBeenCalledWith('accounts', 'list', 'budget-1');
490
- expect(cacheManager.delete).toHaveBeenCalledWith('accounts:list:budget-1');
491
-
492
- expect(result.content).toHaveLength(1);
493
- const parsedContent = JSON.parse(result.content[0].text);
494
- expect(parsedContent.account.id).toBe('account-1');
495
- });
496
-
497
- it('should not invalidate cache on dry_run account creation', async () => {
498
- const mockAccount = {
499
- id: 'account-1',
500
- name: 'New Account',
501
- type: 'checking',
502
- on_budget: true,
503
- closed: false,
504
- note: null,
505
- balance: 100000,
506
- cleared_balance: 100000,
507
- uncleared_balance: 0,
508
- transfer_payee_id: 'payee-1',
509
- direct_import_linked: false,
510
- direct_import_in_error: false,
511
- };
512
-
513
- (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
514
- data: { account: mockAccount },
515
- });
516
-
517
- const result = await handleCreateAccount(mockYnabAPI, {
518
- budget_id: 'budget-1',
519
- name: 'New Account',
520
- type: 'checking',
521
- dry_run: true,
522
- });
523
-
524
- // Verify cache was NOT invalidated for dry run
525
- expect(cacheManager.delete).not.toHaveBeenCalled();
526
- expect(CacheManager.generateKey).not.toHaveBeenCalled();
527
-
528
- expect(result.content).toHaveLength(1);
529
- const parsedContent = JSON.parse(result.content[0].text);
530
- expect(parsedContent.dry_run).toBe(true);
531
- expect(parsedContent.action).toBe('create_account');
532
- expect(parsedContent.request).toMatchObject({
533
- budget_id: 'budget-1',
534
- name: 'New Account',
535
- type: 'checking',
536
- });
537
- });
538
- });
539
-
540
- describe('Schema Validation', () => {
541
- describe('ListAccountsSchema', () => {
542
- it('should validate valid budget_id', () => {
543
- const result = ListAccountsSchema.parse({ budget_id: 'valid-budget-id' });
544
- expect(result.budget_id).toBe('valid-budget-id');
545
- });
546
-
547
- it('should reject empty budget_id', () => {
548
- expect(() => ListAccountsSchema.parse({ budget_id: '' })).toThrow();
549
- });
550
-
551
- it('should reject missing budget_id', () => {
552
- expect(() => ListAccountsSchema.parse({})).toThrow();
553
- });
554
- });
555
-
556
- describe('GetAccountSchema', () => {
557
- it('should validate valid parameters', () => {
558
- const result = GetAccountSchema.parse({
559
- budget_id: 'budget-1',
560
- account_id: 'account-1',
561
- });
562
- expect(result.budget_id).toBe('budget-1');
563
- expect(result.account_id).toBe('account-1');
564
- });
565
-
566
- it('should reject missing account_id', () => {
567
- expect(() => GetAccountSchema.parse({ budget_id: 'budget-1' })).toThrow();
568
- });
569
-
570
- it('should reject empty account_id', () => {
571
- expect(() =>
572
- GetAccountSchema.parse({
573
- budget_id: 'budget-1',
574
- account_id: '',
575
- }),
576
- ).toThrow();
577
- });
578
- });
579
-
580
- describe('CreateAccountSchema', () => {
581
- it('should validate valid account creation parameters', () => {
582
- const result = CreateAccountSchema.parse({
583
- budget_id: 'budget-1',
584
- name: 'New Account',
585
- type: 'checking',
586
- balance: 100,
587
- });
588
- expect(result.budget_id).toBe('budget-1');
589
- expect(result.name).toBe('New Account');
590
- expect(result.type).toBe('checking');
591
- expect(result.balance).toBe(100);
592
- });
593
-
594
- it('should validate without optional balance', () => {
595
- const result = CreateAccountSchema.parse({
596
- budget_id: 'budget-1',
597
- name: 'New Account',
598
- type: 'savings',
599
- });
600
- expect(result.balance).toBeUndefined();
601
- });
602
-
603
- it('should validate all supported account types', () => {
604
- const validTypes = [
605
- 'checking',
606
- 'savings',
607
- 'creditCard',
608
- 'cash',
609
- 'lineOfCredit',
610
- 'otherAsset',
611
- 'otherLiability',
612
- ];
613
-
614
- validTypes.forEach((type) => {
615
- const result = CreateAccountSchema.parse({
616
- budget_id: 'budget-1',
617
- name: 'Test Account',
618
- type,
619
- });
620
- expect(result.type).toBe(type);
621
- });
622
- });
623
-
624
- it('should reject invalid account type', () => {
625
- expect(() =>
626
- CreateAccountSchema.parse({
627
- budget_id: 'budget-1',
628
- name: 'Test Account',
629
- type: 'invalid-type',
630
- }),
631
- ).toThrow();
632
- });
633
-
634
- it('should reject empty name', () => {
635
- expect(() =>
636
- CreateAccountSchema.parse({
637
- budget_id: 'budget-1',
638
- name: '',
639
- type: 'checking',
640
- }),
641
- ).toThrow();
642
- });
643
-
644
- it('should reject missing required fields', () => {
645
- expect(() =>
646
- CreateAccountSchema.parse({
647
- budget_id: 'budget-1',
648
- }),
649
- ).toThrow();
650
- });
651
- });
652
- });
52
+ describe("Account Tools", () => {
53
+ beforeEach(() => {
54
+ vi.resetAllMocks();
55
+ // Reset NODE_ENV to test to ensure cache bypassing in tests
56
+ process.env.NODE_ENV = "test";
57
+ (cacheManager.wrap as ReturnType<typeof vi.fn>).mockImplementation(
58
+ async (
59
+ _key: string,
60
+ options: {
61
+ loader: () => Promise<unknown>;
62
+ },
63
+ ) => {
64
+ return await options.loader();
65
+ },
66
+ );
67
+ (cacheManager.has as ReturnType<typeof vi.fn>).mockReturnValue(false);
68
+ (CacheManager.generateKey as ReturnType<typeof vi.fn>).mockImplementation(
69
+ (prefix: string, ...parts: (string | number | boolean | undefined)[]) =>
70
+ [prefix, ...parts.filter((part) => part !== undefined)].join(":"),
71
+ );
72
+ });
73
+
74
+ afterAll(() => {
75
+ // Restore original NODE_ENV value
76
+ if (originalNodeEnv === undefined) {
77
+ process.env.NODE_ENV = undefined;
78
+ } else {
79
+ process.env.NODE_ENV = originalNodeEnv;
80
+ }
81
+ });
82
+
83
+ describe("handleListAccounts", () => {
84
+ it("should include cache metadata from delta fetcher results", async () => {
85
+ const mockAccounts = [
86
+ {
87
+ id: "account-1",
88
+ name: "Checking Account",
89
+ type: "checking",
90
+ on_budget: true,
91
+ closed: false,
92
+ note: "Main checking account",
93
+ balance: 100000,
94
+ cleared_balance: 95000,
95
+ uncleared_balance: 5000,
96
+ transfer_payee_id: "payee-1",
97
+ direct_import_linked: false,
98
+ direct_import_in_error: false,
99
+ },
100
+ ];
101
+ const { fetcher, resolved } = createDeltaFetcherMock("fetchAccounts", {
102
+ data: mockAccounts,
103
+ wasCached: true,
104
+ usedDelta: true,
105
+ });
106
+
107
+ const result = await handleListAccounts(mockYnabAPI, fetcher, {
108
+ budget_id: "budget-1",
109
+ });
110
+
111
+ const fetchAccountsMock = fetcher.fetchAccounts as ReturnType<
112
+ typeof vi.fn
113
+ >;
114
+ expect(fetchAccountsMock).toHaveBeenCalledWith("budget-1");
115
+
116
+ const parsedContent = JSON.parse(result.content[0].text);
117
+ expect(parsedContent.cached).toBe(resolved.wasCached);
118
+ expect(parsedContent.cache_info).toContain("delta merge applied");
119
+ });
120
+
121
+ it("should return formatted account list on success", async () => {
122
+ const mockAccounts = [
123
+ {
124
+ id: "account-1",
125
+ name: "Checking Account",
126
+ type: "checking",
127
+ on_budget: true,
128
+ closed: false,
129
+ note: "Main checking account",
130
+ balance: 100000,
131
+ cleared_balance: 95000,
132
+ uncleared_balance: 5000,
133
+ transfer_payee_id: "payee-1",
134
+ direct_import_linked: false,
135
+ direct_import_in_error: false,
136
+ },
137
+ {
138
+ id: "account-2",
139
+ name: "Savings Account",
140
+ type: "savings",
141
+ on_budget: true,
142
+ closed: false,
143
+ note: "Emergency fund",
144
+ balance: 500000,
145
+ cleared_balance: 500000,
146
+ uncleared_balance: 0,
147
+ transfer_payee_id: "payee-2",
148
+ direct_import_linked: true,
149
+ direct_import_in_error: false,
150
+ },
151
+ ];
152
+ const { fetcher, resolved } = createDeltaFetcherMock("fetchAccounts", {
153
+ data: mockAccounts,
154
+ wasCached: false,
155
+ });
156
+
157
+ const result = await handleListAccounts(mockYnabAPI, fetcher, {
158
+ budget_id: "budget-1",
159
+ });
160
+
161
+ expect(result.content).toHaveLength(1);
162
+ expect(result.content[0].type).toBe("text");
163
+
164
+ const parsedContent = JSON.parse(result.content[0].text);
165
+ expect(parsedContent.accounts).toHaveLength(2);
166
+ expect(parsedContent.accounts[0]).toEqual({
167
+ id: "account-1",
168
+ name: "Checking Account",
169
+ type: "checking",
170
+ on_budget: true,
171
+ closed: false,
172
+ note: "Main checking account",
173
+ balance: 100,
174
+ cleared_balance: 95,
175
+ uncleared_balance: 5,
176
+ transfer_payee_id: "payee-1",
177
+ direct_import_linked: false,
178
+ direct_import_in_error: false,
179
+ });
180
+ expect(parsedContent.cached).toBe(resolved.wasCached);
181
+ expect(parsedContent.cache_info).toBe(
182
+ "Fresh data retrieved from YNAB API",
183
+ );
184
+ });
185
+
186
+ it("should handle 404 budget not found errors", async () => {
187
+ const { fetcher } = createRejectingDeltaFetcherMock(
188
+ "fetchAccounts",
189
+ new Error("404 Not Found"),
190
+ );
191
+
192
+ const result = await handleListAccounts(mockYnabAPI, fetcher, {
193
+ budget_id: "invalid-budget",
194
+ });
195
+
196
+ expect(result.content).toHaveLength(1);
197
+ const parsedContent = JSON.parse(result.content[0].text);
198
+ expect(parsedContent.error.message).toBe(
199
+ "Failed to list accounts - budget or account not found",
200
+ );
201
+ });
202
+
203
+ it("should handle 401 authentication errors", async () => {
204
+ const { fetcher } = createRejectingDeltaFetcherMock(
205
+ "fetchAccounts",
206
+ new Error("401 Unauthorized"),
207
+ );
208
+
209
+ const result = await handleListAccounts(mockYnabAPI, fetcher, {
210
+ budget_id: "budget-1",
211
+ });
212
+
213
+ expect(result.content).toHaveLength(1);
214
+ const parsedContent = JSON.parse(result.content[0].text);
215
+ expect(parsedContent.error.message).toBe(
216
+ "Invalid or expired YNAB access token",
217
+ );
218
+ });
219
+
220
+ it("should handle generic errors", async () => {
221
+ const { fetcher } = createRejectingDeltaFetcherMock(
222
+ "fetchAccounts",
223
+ new Error("Network error"),
224
+ );
225
+
226
+ const result = await handleListAccounts(mockYnabAPI, fetcher, {
227
+ budget_id: "budget-1",
228
+ });
229
+
230
+ expect(result.content).toHaveLength(1);
231
+ const parsedContent = JSON.parse(result.content[0].text);
232
+ expect(parsedContent.error.message).toBe("Failed to list accounts");
233
+ });
234
+ });
235
+
236
+ describe("handleGetAccount", () => {
237
+ it("should return detailed account information on success", async () => {
238
+ const mockAccount = {
239
+ id: "account-1",
240
+ name: "Checking Account",
241
+ type: "checking",
242
+ on_budget: true,
243
+ closed: false,
244
+ note: "Main checking account",
245
+ balance: 100000,
246
+ cleared_balance: 95000,
247
+ uncleared_balance: 5000,
248
+ transfer_payee_id: "payee-1",
249
+ direct_import_linked: false,
250
+ direct_import_in_error: false,
251
+ };
252
+
253
+ (mockYnabAPI.accounts.getAccountById as any).mockResolvedValue({
254
+ data: { account: mockAccount },
255
+ });
256
+
257
+ const result = await handleGetAccount(mockYnabAPI, {
258
+ budget_id: "budget-1",
259
+ account_id: "account-1",
260
+ });
261
+
262
+ expect(result.content).toHaveLength(1);
263
+ expect(result.content[0].type).toBe("text");
264
+
265
+ const parsedContent = JSON.parse(result.content[0].text);
266
+ expect(parsedContent.account).toEqual({
267
+ id: "account-1",
268
+ name: "Checking Account",
269
+ type: "checking",
270
+ on_budget: true,
271
+ closed: false,
272
+ note: "Main checking account",
273
+ balance: 100,
274
+ cleared_balance: 95,
275
+ uncleared_balance: 5,
276
+ transfer_payee_id: "payee-1",
277
+ direct_import_linked: false,
278
+ direct_import_in_error: false,
279
+ });
280
+ expect(parsedContent.cached).toBe(false);
281
+ expect(parsedContent.cache_info).toBe(
282
+ "Fresh data retrieved from YNAB API",
283
+ );
284
+ });
285
+
286
+ it("should report cached responses when cache entries exist", async () => {
287
+ const mockAccount = {
288
+ id: "account-1",
289
+ name: "Checking Account",
290
+ type: "checking",
291
+ on_budget: true,
292
+ closed: false,
293
+ note: "Main checking account",
294
+ balance: 100000,
295
+ cleared_balance: 95000,
296
+ uncleared_balance: 5000,
297
+ transfer_payee_id: "payee-1",
298
+ direct_import_linked: false,
299
+ direct_import_in_error: false,
300
+ };
301
+
302
+ (mockYnabAPI.accounts.getAccountById as any).mockResolvedValue({
303
+ data: { account: mockAccount },
304
+ });
305
+ (cacheManager.has as ReturnType<typeof vi.fn>).mockReturnValueOnce(true);
306
+
307
+ const result = await handleGetAccount(mockYnabAPI, {
308
+ budget_id: "budget-1",
309
+ account_id: "account-1",
310
+ });
311
+
312
+ const parsedContent = JSON.parse(result.content[0].text);
313
+ expect(parsedContent.cached).toBe(true);
314
+ expect(parsedContent.cache_info).toBe(
315
+ "Data retrieved from cache for improved performance",
316
+ );
317
+ });
318
+
319
+ it("should handle 404 account not found errors", async () => {
320
+ (mockYnabAPI.accounts.getAccountById as any).mockRejectedValue(
321
+ new Error("404 Not Found"),
322
+ );
323
+
324
+ const result = await handleGetAccount(mockYnabAPI, {
325
+ budget_id: "budget-1",
326
+ account_id: "invalid-account",
327
+ });
328
+
329
+ expect(result.content).toHaveLength(1);
330
+ const parsedContent = JSON.parse(result.content[0].text);
331
+ expect(parsedContent.error.message).toBe(
332
+ "Failed to get account - budget or account not found",
333
+ );
334
+ });
335
+
336
+ it("should handle authentication errors", async () => {
337
+ (mockYnabAPI.accounts.getAccountById as any).mockRejectedValue(
338
+ new Error("401 Unauthorized"),
339
+ );
340
+
341
+ const result = await handleGetAccount(mockYnabAPI, {
342
+ budget_id: "budget-1",
343
+ account_id: "account-1",
344
+ });
345
+
346
+ expect(result.content).toHaveLength(1);
347
+ const parsedContent = JSON.parse(result.content[0].text);
348
+ expect(parsedContent.error.message).toBe(
349
+ "Invalid or expired YNAB access token",
350
+ );
351
+ });
352
+ });
353
+
354
+ describe("handleCreateAccount", () => {
355
+ it("should create account with all supported types", async () => {
356
+ const accountTypes = [
357
+ "checking",
358
+ "savings",
359
+ "creditCard",
360
+ "cash",
361
+ "lineOfCredit",
362
+ "otherAsset",
363
+ "otherLiability",
364
+ ];
365
+
366
+ for (const accountType of accountTypes) {
367
+ const mockAccount = {
368
+ id: `account-${accountType}`,
369
+ name: `${accountType} Account`,
370
+ type: accountType,
371
+ on_budget: true,
372
+ closed: false,
373
+ note: null,
374
+ balance: 100000,
375
+ cleared_balance: 100000,
376
+ uncleared_balance: 0,
377
+ transfer_payee_id: `payee-${accountType}`,
378
+ direct_import_linked: false,
379
+ direct_import_in_error: false,
380
+ };
381
+
382
+ (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
383
+ data: { account: mockAccount },
384
+ });
385
+
386
+ const result = await handleCreateAccount(mockYnabAPI, {
387
+ budget_id: "budget-1",
388
+ name: `${accountType} Account`,
389
+ type: accountType as any,
390
+ balance: 100,
391
+ });
392
+
393
+ expect(result.content).toHaveLength(1);
394
+ const parsedContent = JSON.parse(result.content[0].text);
395
+ expect(parsedContent.account.type).toBe(accountType);
396
+ expect(parsedContent.account.name).toBe(`${accountType} Account`);
397
+ }
398
+ });
399
+
400
+ it("should create account without initial balance", async () => {
401
+ const mockAccount = {
402
+ id: "account-1",
403
+ name: "New Account",
404
+ type: "checking",
405
+ on_budget: true,
406
+ closed: false,
407
+ note: null,
408
+ balance: 0,
409
+ cleared_balance: 0,
410
+ uncleared_balance: 0,
411
+ transfer_payee_id: "payee-1",
412
+ direct_import_linked: false,
413
+ direct_import_in_error: false,
414
+ };
415
+
416
+ (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
417
+ data: { account: mockAccount },
418
+ });
419
+
420
+ const result = await handleCreateAccount(mockYnabAPI, {
421
+ budget_id: "budget-1",
422
+ name: "New Account",
423
+ type: "checking",
424
+ });
425
+
426
+ expect(result.content).toHaveLength(1);
427
+ const parsedContent = JSON.parse(result.content[0].text);
428
+ expect(parsedContent.account.balance).toBe(0);
429
+
430
+ // Verify the API was called with balance 0 in milliunits
431
+ expect(mockYnabAPI.accounts.createAccount).toHaveBeenCalledWith(
432
+ "budget-1",
433
+ {
434
+ account: {
435
+ name: "New Account",
436
+ type: "checking",
437
+ balance: 0,
438
+ },
439
+ },
440
+ );
441
+ });
442
+
443
+ it("should convert balance to milliunits", async () => {
444
+ const mockAccount = {
445
+ id: "account-1",
446
+ name: "New Account",
447
+ type: "checking",
448
+ on_budget: true,
449
+ closed: false,
450
+ note: null,
451
+ balance: 150000,
452
+ cleared_balance: 150000,
453
+ uncleared_balance: 0,
454
+ transfer_payee_id: "payee-1",
455
+ direct_import_linked: false,
456
+ direct_import_in_error: false,
457
+ };
458
+
459
+ (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
460
+ data: { account: mockAccount },
461
+ });
462
+
463
+ await handleCreateAccount(mockYnabAPI, {
464
+ budget_id: "budget-1",
465
+ name: "New Account",
466
+ type: "checking",
467
+ balance: 150, // $150 should become 150000 milliunits
468
+ });
469
+
470
+ // Verify the API was called with balance converted to milliunits
471
+ expect(mockYnabAPI.accounts.createAccount).toHaveBeenCalledWith(
472
+ "budget-1",
473
+ {
474
+ account: {
475
+ name: "New Account",
476
+ type: "checking",
477
+ balance: 150000,
478
+ },
479
+ },
480
+ );
481
+ });
482
+
483
+ it("should handle creation errors", async () => {
484
+ (mockYnabAPI.accounts.createAccount as any).mockRejectedValue(
485
+ new Error("400 Bad Request"),
486
+ );
487
+
488
+ const result = await handleCreateAccount(mockYnabAPI, {
489
+ budget_id: "budget-1",
490
+ name: "New Account",
491
+ type: "checking",
492
+ });
493
+
494
+ expect(result.content).toHaveLength(1);
495
+ const parsedContent = JSON.parse(result.content[0].text);
496
+ expect(parsedContent.error.message).toBe("Failed to create account");
497
+ });
498
+
499
+ it("should invalidate account list cache on successful account creation", async () => {
500
+ const mockAccount = {
501
+ id: "account-1",
502
+ name: "New Account",
503
+ type: "checking",
504
+ on_budget: true,
505
+ closed: false,
506
+ note: null,
507
+ balance: 100000,
508
+ cleared_balance: 100000,
509
+ uncleared_balance: 0,
510
+ transfer_payee_id: "payee-1",
511
+ direct_import_linked: false,
512
+ direct_import_in_error: false,
513
+ };
514
+
515
+ (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
516
+ data: { account: mockAccount },
517
+ });
518
+
519
+ const result = await handleCreateAccount(mockYnabAPI, {
520
+ budget_id: "budget-1",
521
+ name: "New Account",
522
+ type: "checking",
523
+ });
524
+
525
+ // Verify cache was invalidated for account list
526
+ expect(CacheManager.generateKey).toHaveBeenCalledWith(
527
+ "accounts",
528
+ "list",
529
+ "budget-1",
530
+ );
531
+ expect(cacheManager.delete).toHaveBeenCalledWith(
532
+ "accounts:list:budget-1",
533
+ );
534
+
535
+ expect(result.content).toHaveLength(1);
536
+ const parsedContent = JSON.parse(result.content[0].text);
537
+ expect(parsedContent.account.id).toBe("account-1");
538
+ });
539
+
540
+ it("should not invalidate cache on dry_run account creation", async () => {
541
+ const mockAccount = {
542
+ id: "account-1",
543
+ name: "New Account",
544
+ type: "checking",
545
+ on_budget: true,
546
+ closed: false,
547
+ note: null,
548
+ balance: 100000,
549
+ cleared_balance: 100000,
550
+ uncleared_balance: 0,
551
+ transfer_payee_id: "payee-1",
552
+ direct_import_linked: false,
553
+ direct_import_in_error: false,
554
+ };
555
+
556
+ (mockYnabAPI.accounts.createAccount as any).mockResolvedValue({
557
+ data: { account: mockAccount },
558
+ });
559
+
560
+ const result = await handleCreateAccount(mockYnabAPI, {
561
+ budget_id: "budget-1",
562
+ name: "New Account",
563
+ type: "checking",
564
+ dry_run: true,
565
+ });
566
+
567
+ // Verify cache was NOT invalidated for dry run
568
+ expect(cacheManager.delete).not.toHaveBeenCalled();
569
+ expect(CacheManager.generateKey).not.toHaveBeenCalled();
570
+
571
+ expect(result.content).toHaveLength(1);
572
+ const parsedContent = JSON.parse(result.content[0].text);
573
+ expect(parsedContent.dry_run).toBe(true);
574
+ expect(parsedContent.action).toBe("create_account");
575
+ expect(parsedContent.request).toMatchObject({
576
+ budget_id: "budget-1",
577
+ name: "New Account",
578
+ type: "checking",
579
+ });
580
+ });
581
+ });
582
+
583
+ describe("Schema Validation", () => {
584
+ describe("ListAccountsSchema", () => {
585
+ it("should validate valid budget_id", () => {
586
+ const result = ListAccountsSchema.parse({
587
+ budget_id: "valid-budget-id",
588
+ });
589
+ expect(result.budget_id).toBe("valid-budget-id");
590
+ });
591
+
592
+ it("should reject empty budget_id", () => {
593
+ expect(() => ListAccountsSchema.parse({ budget_id: "" })).toThrow();
594
+ });
595
+
596
+ it("should reject missing budget_id", () => {
597
+ expect(() => ListAccountsSchema.parse({})).toThrow();
598
+ });
599
+ });
600
+
601
+ describe("GetAccountSchema", () => {
602
+ it("should validate valid parameters", () => {
603
+ const result = GetAccountSchema.parse({
604
+ budget_id: "budget-1",
605
+ account_id: "account-1",
606
+ });
607
+ expect(result.budget_id).toBe("budget-1");
608
+ expect(result.account_id).toBe("account-1");
609
+ });
610
+
611
+ it("should reject missing account_id", () => {
612
+ expect(() =>
613
+ GetAccountSchema.parse({ budget_id: "budget-1" }),
614
+ ).toThrow();
615
+ });
616
+
617
+ it("should reject empty account_id", () => {
618
+ expect(() =>
619
+ GetAccountSchema.parse({
620
+ budget_id: "budget-1",
621
+ account_id: "",
622
+ }),
623
+ ).toThrow();
624
+ });
625
+ });
626
+
627
+ describe("CreateAccountSchema", () => {
628
+ it("should validate valid account creation parameters", () => {
629
+ const result = CreateAccountSchema.parse({
630
+ budget_id: "budget-1",
631
+ name: "New Account",
632
+ type: "checking",
633
+ balance: 100,
634
+ });
635
+ expect(result.budget_id).toBe("budget-1");
636
+ expect(result.name).toBe("New Account");
637
+ expect(result.type).toBe("checking");
638
+ expect(result.balance).toBe(100);
639
+ });
640
+
641
+ it("should validate without optional balance", () => {
642
+ const result = CreateAccountSchema.parse({
643
+ budget_id: "budget-1",
644
+ name: "New Account",
645
+ type: "savings",
646
+ });
647
+ expect(result.balance).toBeUndefined();
648
+ });
649
+
650
+ it("should validate all supported account types", () => {
651
+ const validTypes = [
652
+ "checking",
653
+ "savings",
654
+ "creditCard",
655
+ "cash",
656
+ "lineOfCredit",
657
+ "otherAsset",
658
+ "otherLiability",
659
+ ];
660
+
661
+ validTypes.forEach((type) => {
662
+ const result = CreateAccountSchema.parse({
663
+ budget_id: "budget-1",
664
+ name: "Test Account",
665
+ type,
666
+ });
667
+ expect(result.type).toBe(type);
668
+ });
669
+ });
670
+
671
+ it("should reject invalid account type", () => {
672
+ expect(() =>
673
+ CreateAccountSchema.parse({
674
+ budget_id: "budget-1",
675
+ name: "Test Account",
676
+ type: "invalid-type",
677
+ }),
678
+ ).toThrow();
679
+ });
680
+
681
+ it("should reject empty name", () => {
682
+ expect(() =>
683
+ CreateAccountSchema.parse({
684
+ budget_id: "budget-1",
685
+ name: "",
686
+ type: "checking",
687
+ }),
688
+ ).toThrow();
689
+ });
690
+
691
+ it("should reject missing required fields", () => {
692
+ expect(() =>
693
+ CreateAccountSchema.parse({
694
+ budget_id: "budget-1",
695
+ }),
696
+ ).toThrow();
697
+ });
698
+ });
699
+ });
653
700
  });