@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
@@ -3,1166 +3,1293 @@
3
3
  * These tests use mocked YNAB API responses to test complete workflows
4
4
  */
5
5
 
6
- import { describe, it, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';
7
- import { YNABMCPServer } from '../server/YNABMCPServer.js';
8
- import { executeToolCall, parseToolResult, validateToolResult, waitFor } from './testUtils.js';
9
- import { cacheManager } from '../server/cacheManager.js';
6
+ import {
7
+ afterAll,
8
+ beforeAll,
9
+ beforeEach,
10
+ describe,
11
+ expect,
12
+ it,
13
+ vi,
14
+ } from "vitest";
15
+ import { YNABMCPServer } from "../server/YNABMCPServer.js";
16
+ import { cacheManager } from "../server/cacheManager.js";
17
+ import {
18
+ executeToolCall,
19
+ parseToolResult,
20
+ validateToolResult,
21
+ waitFor,
22
+ } from "./testUtils.js";
10
23
 
11
24
  // Mock the YNAB SDK
12
- vi.mock('ynab', () => {
13
- const mockAPI = {
14
- budgets: {
15
- getBudgets: vi.fn(),
16
- getBudgetById: vi.fn(),
17
- },
18
- accounts: {
19
- getAccounts: vi.fn(),
20
- getAccountById: vi.fn(),
21
- createAccount: vi.fn(),
22
- },
23
- transactions: {
24
- getTransactions: vi.fn(),
25
- getTransactionsByAccount: vi.fn(),
26
- getTransactionsByCategory: vi.fn(),
27
- getTransactionById: vi.fn(),
28
- createTransaction: vi.fn(),
29
- updateTransaction: vi.fn(),
30
- deleteTransaction: vi.fn(),
31
- },
32
- categories: {
33
- getCategories: vi.fn(),
34
- getCategoryById: vi.fn(),
35
- updateMonthCategory: vi.fn(),
36
- },
37
- payees: {
38
- getPayees: vi.fn(),
39
- getPayeeById: vi.fn(),
40
- },
41
- months: {
42
- getBudgetMonth: vi.fn(),
43
- getBudgetMonths: vi.fn(),
44
- },
45
- user: {
46
- getUser: vi.fn(),
47
- },
48
- };
49
-
50
- return {
51
- API: vi.fn(() => mockAPI),
52
- utils: {
53
- convertMilliUnitsToCurrencyAmount: vi.fn(
54
- (milliunits: number, currencyDecimalDigits: number = 2) => {
55
- const amount = milliunits / 1000;
56
- return Number(amount.toFixed(currencyDecimalDigits));
57
- },
58
- ),
59
- convertCurrencyAmountToMilliUnits: vi.fn((amount: number) => Math.round(amount * 1000)),
60
- },
61
- };
25
+ vi.mock("ynab", () => {
26
+ const mockAPI = {
27
+ budgets: {
28
+ getBudgets: vi.fn(),
29
+ getBudgetById: vi.fn(),
30
+ },
31
+ accounts: {
32
+ getAccounts: vi.fn(),
33
+ getAccountById: vi.fn(),
34
+ createAccount: vi.fn(),
35
+ },
36
+ transactions: {
37
+ getTransactions: vi.fn(),
38
+ getTransactionsByAccount: vi.fn(),
39
+ getTransactionsByCategory: vi.fn(),
40
+ getTransactionById: vi.fn(),
41
+ createTransaction: vi.fn(),
42
+ updateTransaction: vi.fn(),
43
+ deleteTransaction: vi.fn(),
44
+ },
45
+ categories: {
46
+ getCategories: vi.fn(),
47
+ getCategoryById: vi.fn(),
48
+ updateMonthCategory: vi.fn(),
49
+ },
50
+ payees: {
51
+ getPayees: vi.fn(),
52
+ getPayeeById: vi.fn(),
53
+ },
54
+ months: {
55
+ getBudgetMonth: vi.fn(),
56
+ getBudgetMonths: vi.fn(),
57
+ },
58
+ user: {
59
+ getUser: vi.fn(),
60
+ },
61
+ };
62
+
63
+ return {
64
+ API: vi.fn(() => mockAPI),
65
+ utils: {
66
+ convertMilliUnitsToCurrencyAmount: vi.fn(
67
+ (milliunits: number, currencyDecimalDigits = 2) => {
68
+ const amount = milliunits / 1000;
69
+ return Number(amount.toFixed(currencyDecimalDigits));
70
+ },
71
+ ),
72
+ convertCurrencyAmountToMilliUnits: vi.fn((amount: number) =>
73
+ Math.round(amount * 1000),
74
+ ),
75
+ },
76
+ };
62
77
  });
63
78
 
64
- const TEST_BUDGET_UUID = '00000000-0000-0000-0000-000000000001';
79
+ const TEST_BUDGET_UUID = "00000000-0000-0000-0000-000000000001";
65
80
 
66
- describe('YNAB utils mock', () => {
67
- it(
68
- 'converts milliunits using SDK rounding rules',
69
- { meta: { tier: 'domain', domain: 'workflows' } },
70
- async () => {
71
- const { utils } = await import('ynab');
81
+ describe("YNAB utils mock", () => {
82
+ it(
83
+ "converts milliunits using SDK rounding rules",
84
+ { meta: { tier: "domain", domain: "workflows" } },
85
+ async () => {
86
+ const { utils } = await import("ynab");
72
87
 
73
- expect(utils.convertMilliUnitsToCurrencyAmount(123456, 2)).toBe(123.46);
74
- expect(utils.convertMilliUnitsToCurrencyAmount(123456, 3)).toBe(123.456);
75
- expect(utils.convertMilliUnitsToCurrencyAmount(-98765, 2)).toBe(-98.77);
76
- },
77
- );
88
+ expect(utils.convertMilliUnitsToCurrencyAmount(123456, 2)).toBe(123.46);
89
+ expect(utils.convertMilliUnitsToCurrencyAmount(123456, 3)).toBe(123.456);
90
+ expect(utils.convertMilliUnitsToCurrencyAmount(-98765, 2)).toBe(-98.77);
91
+ },
92
+ );
78
93
  });
79
94
 
80
- describe('YNAB MCP Server - Comprehensive Integration Tests', () => {
81
- let server: YNABMCPServer;
82
- let mockYnabAPI: any;
83
-
84
- beforeEach(async () => {
85
- // Set up environment
86
- process.env['YNAB_ACCESS_TOKEN'] = 'test-token';
87
-
88
- // Create server instance
89
- server = new YNABMCPServer();
90
-
91
- // Get the mocked YNAB API instance
92
- const { API } = await import('ynab');
93
- mockYnabAPI = new (API as any)();
94
-
95
- // Reset all mocks
96
- vi.clearAllMocks();
97
- });
98
-
99
- describe('Complete Budget Management Integration', () => {
100
- it(
101
- 'should handle complete budget listing and retrieval workflow',
102
- { meta: { tier: 'domain', domain: 'workflows' } },
103
- async () => {
104
- // Mock budget list response
105
- const mockBudgets = {
106
- data: {
107
- budgets: [
108
- {
109
- id: 'budget-1',
110
- name: 'Test Budget 1',
111
- last_modified_on: '2024-01-01T00:00:00Z',
112
- first_month: '2024-01-01',
113
- last_month: '2024-12-01',
114
- date_format: { format: 'MM/DD/YYYY' },
115
- currency_format: {
116
- iso_code: 'USD',
117
- example_format: '$123.45',
118
- decimal_digits: 2,
119
- decimal_separator: '.',
120
- symbol_first: true,
121
- group_separator: ',',
122
- currency_symbol: '$',
123
- display_symbol: true,
124
- },
125
- },
126
- {
127
- id: 'budget-2',
128
- name: 'Test Budget 2',
129
- last_modified_on: '2024-01-02T00:00:00Z',
130
- first_month: '2024-01-01',
131
- last_month: '2024-12-01',
132
- date_format: { format: 'MM/DD/YYYY' },
133
- currency_format: {
134
- iso_code: 'USD',
135
- example_format: '$123.45',
136
- decimal_digits: 2,
137
- decimal_separator: '.',
138
- symbol_first: true,
139
- group_separator: ',',
140
- currency_symbol: '$',
141
- display_symbol: true,
142
- },
143
- },
144
- ],
145
- },
146
- };
147
-
148
- mockYnabAPI.budgets.getBudgets.mockResolvedValue(mockBudgets);
149
-
150
- // Test budget listing
151
- const listResult = await executeToolCall(server, 'ynab:list_budgets');
152
- validateToolResult(listResult);
153
-
154
- const budgets = parseToolResult(listResult);
155
- expect(budgets.data.budgets).toHaveLength(2);
156
- expect(budgets.data.budgets[0].name).toBe('Test Budget 1');
157
- expect(budgets.data.budgets[1].name).toBe('Test Budget 2');
158
-
159
- // Mock specific budget response
160
- const mockBudget = {
161
- data: {
162
- budget: {
163
- id: 'budget-1',
164
- name: 'Test Budget 1',
165
- last_modified_on: '2024-01-01T00:00:00Z',
166
- first_month: '2024-01-01',
167
- last_month: '2024-12-01',
168
- date_format: { format: 'MM/DD/YYYY' },
169
- currency_format: {
170
- iso_code: 'USD',
171
- example_format: '$123.45',
172
- decimal_digits: 2,
173
- decimal_separator: '.',
174
- symbol_first: true,
175
- group_separator: ',',
176
- currency_symbol: '$',
177
- display_symbol: true,
178
- },
179
- accounts: [],
180
- payees: [],
181
- category_groups: [],
182
- months: [],
183
- },
184
- },
185
- };
186
-
187
- mockYnabAPI.budgets.getBudgetById.mockResolvedValue(mockBudget);
188
-
189
- // Test specific budget retrieval
190
- const getResult = await executeToolCall(server, 'ynab:get_budget', {
191
- budget_id: 'budget-1',
192
- });
193
- validateToolResult(getResult);
194
-
195
- const budget = parseToolResult(getResult);
196
- expect(budget.data.budget.id).toBe('budget-1');
197
- expect(budget.data.budget.name).toBe('Test Budget 1');
198
-
199
- // Verify API calls
200
- expect(mockYnabAPI.budgets.getBudgets).toHaveBeenCalledTimes(1);
201
- expect(mockYnabAPI.budgets.getBudgetById).toHaveBeenCalledWith('budget-1');
202
- },
203
- );
204
-
205
- it(
206
- 'should handle budget retrieval errors gracefully',
207
- { meta: { tier: 'domain', domain: 'workflows' } },
208
- async () => {
209
- // Mock API error
210
- const apiError = new Error('Budget not found');
211
- (apiError as any).error = {
212
- id: '404.2',
213
- name: 'not_found',
214
- description: 'Budget not found',
215
- };
216
- mockYnabAPI.budgets.getBudgetById.mockRejectedValue(apiError);
217
-
218
- // Test error handling
219
- try {
220
- await executeToolCall(server, 'ynab:get_budget', {
221
- budget_id: 'invalid-budget',
222
- });
223
- expect.fail('Should have thrown an error');
224
- } catch (error) {
225
- expect(error).toBeDefined();
226
- }
227
-
228
- expect(mockYnabAPI.budgets.getBudgetById).toHaveBeenCalledWith('invalid-budget');
229
- },
230
- );
231
- });
232
-
233
- describe('Complete Account Management Integration', () => {
234
- it(
235
- 'should handle complete account workflow',
236
- { meta: { tier: 'domain', domain: 'workflows' } },
237
- async () => {
238
- const budgetId = TEST_BUDGET_UUID;
239
-
240
- // Mock accounts list
241
- const mockAccounts = {
242
- data: {
243
- accounts: [
244
- {
245
- id: 'account-1',
246
- name: 'Checking Account',
247
- type: 'checking',
248
- on_budget: true,
249
- closed: false,
250
- balance: 100000, // $100.00
251
- cleared_balance: 95000,
252
- uncleared_balance: 5000,
253
- transfer_payee_id: 'payee-transfer-1',
254
- },
255
- {
256
- id: 'account-2',
257
- name: 'Savings Account',
258
- type: 'savings',
259
- on_budget: true,
260
- closed: false,
261
- note: 'Emergency fund',
262
- balance: 500000, // $500.00
263
- cleared_balance: 500000,
264
- uncleared_balance: 0,
265
- transfer_payee_id: 'payee-transfer-2',
266
- },
267
- ],
268
- },
269
- };
270
-
271
- mockYnabAPI.accounts.getAccounts.mockResolvedValue(mockAccounts);
272
-
273
- // Test account listing
274
- const listResult = await executeToolCall(server, 'ynab:list_accounts', {
275
- budget_id: budgetId,
276
- });
277
- validateToolResult(listResult);
278
-
279
- const accounts = parseToolResult(listResult);
280
- expect(accounts.data.accounts).toHaveLength(2);
281
- expect(accounts.data.accounts[0].name).toBe('Checking Account');
282
- expect(accounts.data.accounts[1].name).toBe('Savings Account');
283
-
284
- // Mock specific account response
285
- const mockAccount = {
286
- data: {
287
- account: mockAccounts.data.accounts[0],
288
- },
289
- };
290
-
291
- mockYnabAPI.accounts.getAccountById.mockResolvedValue(mockAccount);
292
-
293
- // Test specific account retrieval
294
- const getResult = await executeToolCall(server, 'ynab:get_account', {
295
- budget_id: budgetId,
296
- account_id: 'account-1',
297
- });
298
- validateToolResult(getResult);
299
-
300
- const account = parseToolResult(getResult);
301
- expect(account.data.account.id).toBe('account-1');
302
- expect(account.data.account.name).toBe('Checking Account');
303
- expect(account.data.account.balance).toBe(100);
304
-
305
- // Mock account creation
306
- const newAccount = {
307
- id: 'account-3',
308
- name: 'New Test Account',
309
- type: 'checking',
310
- on_budget: true,
311
- closed: false,
312
- balance: 0,
313
- cleared_balance: 0,
314
- uncleared_balance: 0,
315
- transfer_payee_id: 'payee-transfer-3',
316
- };
317
-
318
- const mockCreateResponse = {
319
- data: {
320
- account: newAccount,
321
- },
322
- };
323
-
324
- mockYnabAPI.accounts.createAccount.mockResolvedValue(mockCreateResponse);
325
-
326
- // Test account creation
327
- const createResult = await executeToolCall(server, 'ynab:create_account', {
328
- budget_id: budgetId,
329
- name: 'New Test Account',
330
- type: 'checking',
331
- balance: 0,
332
- });
333
- validateToolResult(createResult);
334
-
335
- const createdAccount = parseToolResult(createResult);
336
- expect(createdAccount.data.account.name).toBe('New Test Account');
337
- expect(createdAccount.data.account.type).toBe('checking');
338
-
339
- // Verify API calls
340
- expect(mockYnabAPI.accounts.getAccounts).toHaveBeenCalledWith(budgetId);
341
- expect(mockYnabAPI.accounts.getAccountById).toHaveBeenCalledWith(budgetId, 'account-1');
342
- expect(mockYnabAPI.accounts.createAccount).toHaveBeenCalledWith(budgetId, {
343
- account: {
344
- name: 'New Test Account',
345
- type: 'checking',
346
- balance: 0,
347
- },
348
- });
349
- },
350
- );
351
- });
352
-
353
- describe('Complete Transaction Management Integration', () => {
354
- // TODO: Re-enable after DeltaFetcher cache integration alignment.
355
- it.skip(
356
- 'should handle complete transaction workflow',
357
- { meta: { tier: 'domain', domain: 'workflows' } },
358
- async () => {
359
- const budgetId = TEST_BUDGET_UUID;
360
- const accountId = 'test-account';
361
-
362
- // Mock transactions list
363
- const mockTransactions = {
364
- data: {
365
- transactions: [
366
- {
367
- id: 'transaction-1',
368
- date: '2024-01-15',
369
- amount: -5000, // $5.00 outflow
370
- memo: 'Coffee shop',
371
- cleared: 'cleared',
372
- approved: true,
373
- flag_color: null,
374
- account_id: accountId,
375
- payee_id: 'payee-1',
376
- category_id: 'category-1',
377
- transfer_account_id: null,
378
- },
379
- {
380
- id: 'transaction-2',
381
- date: '2024-01-16',
382
- amount: 100000, // $100.00 inflow
383
- memo: 'Salary',
384
- cleared: 'cleared',
385
- approved: true,
386
- flag_color: null,
387
- account_id: accountId,
388
- payee_id: 'payee-2',
389
- category_id: null,
390
- transfer_account_id: null,
391
- },
392
- ],
393
- },
394
- };
395
-
396
- mockYnabAPI.transactions.getTransactionsByAccount.mockResolvedValue(mockTransactions);
397
-
398
- // Test transaction listing
399
- const listResult = await executeToolCall(server, 'ynab:list_transactions', {
400
- budget_id: budgetId,
401
- account_id: accountId,
402
- });
403
- validateToolResult(listResult);
404
-
405
- const transactions = parseToolResult(listResult);
406
- expect(transactions.data.transactions).toHaveLength(2);
407
- expect(transactions.data.transactions[0].memo).toBe('Coffee shop');
408
- expect(transactions.data.transactions[1].memo).toBe('Salary');
409
-
410
- // Mock specific transaction response
411
- const mockTransaction = {
412
- data: {
413
- transaction: mockTransactions.data.transactions[0],
414
- },
415
- };
416
-
417
- mockYnabAPI.transactions.getTransactionById.mockResolvedValue(mockTransaction);
418
-
419
- // Test specific transaction retrieval
420
- const getResult = await executeToolCall(server, 'ynab:get_transaction', {
421
- budget_id: budgetId,
422
- transaction_id: 'transaction-1',
423
- });
424
- validateToolResult(getResult);
425
-
426
- const transaction = parseToolResult(getResult);
427
- expect(transaction.data.transaction.id).toBe('transaction-1');
428
- expect(transaction.data.transaction.memo).toBe('Coffee shop');
429
- expect(transaction.data.transaction.amount).toBe(-5);
430
-
431
- // Mock transaction creation
432
- const newTransaction = {
433
- id: 'transaction-3',
434
- date: '2024-01-17',
435
- amount: -2500,
436
- memo: 'Test transaction',
437
- cleared: 'uncleared',
438
- approved: true,
439
- flag_color: null,
440
- account_id: accountId,
441
- payee_id: null,
442
- category_id: 'category-1',
443
- transfer_account_id: null,
444
- };
445
-
446
- const mockCreateResponse = {
447
- data: {
448
- transaction: newTransaction,
449
- },
450
- };
451
-
452
- mockYnabAPI.transactions.createTransaction.mockResolvedValue(mockCreateResponse);
453
-
454
- // Test transaction creation
455
- const createResult = await executeToolCall(server, 'ynab:create_transaction', {
456
- budget_id: budgetId,
457
- account_id: accountId,
458
- category_id: 'category-1',
459
- payee_name: 'Test Payee',
460
- amount: -2500,
461
- memo: 'Test transaction',
462
- date: '2024-01-17',
463
- cleared: 'uncleared',
464
- });
465
- validateToolResult(createResult);
466
-
467
- const createdTransaction = parseToolResult(createResult);
468
- expect(createdTransaction.data.transaction.memo).toBe('Test transaction');
469
- expect(createdTransaction.data.transaction.amount).toBe(-2.5);
470
-
471
- // Mock transaction update
472
- const updatedTransaction = { ...newTransaction, memo: 'Updated memo' };
473
- const mockUpdateResponse = {
474
- data: {
475
- transaction: updatedTransaction,
476
- },
477
- };
478
-
479
- mockYnabAPI.transactions.updateTransaction.mockResolvedValue(mockUpdateResponse);
480
-
481
- // Test transaction update
482
- const updateResult = await executeToolCall(server, 'ynab:update_transaction', {
483
- budget_id: budgetId,
484
- transaction_id: 'transaction-3',
485
- memo: 'Updated memo',
486
- });
487
- validateToolResult(updateResult);
488
-
489
- const updated = parseToolResult(updateResult);
490
- expect(updated.data.transaction.memo).toBe('Updated memo');
491
-
492
- // Mock transaction deletion
493
- mockYnabAPI.transactions.deleteTransaction.mockResolvedValue({
494
- data: {
495
- transaction: { ...updatedTransaction, deleted: true },
496
- },
497
- });
498
-
499
- // Test transaction deletion
500
- const deleteResult = await executeToolCall(server, 'ynab:delete_transaction', {
501
- budget_id: budgetId,
502
- transaction_id: 'transaction-3',
503
- });
504
- validateToolResult(deleteResult);
505
-
506
- // Verify API calls
507
- expect(mockYnabAPI.transactions.getTransactionsByAccount).toHaveBeenCalledWith(
508
- budgetId,
509
- accountId,
510
- undefined,
511
- );
512
- expect(mockYnabAPI.transactions.getTransactionById).toHaveBeenCalledWith(
513
- budgetId,
514
- 'transaction-1',
515
- );
516
- expect(mockYnabAPI.transactions.createTransaction).toHaveBeenCalled();
517
- expect(mockYnabAPI.transactions.updateTransaction).toHaveBeenCalled();
518
- expect(mockYnabAPI.transactions.deleteTransaction).toHaveBeenCalledWith(
519
- budgetId,
520
- 'transaction-3',
521
- );
522
- },
523
- );
524
-
525
- it(
526
- 'should handle transaction filtering',
527
- { meta: { tier: 'domain', domain: 'workflows' } },
528
- async () => {
529
- const budgetId = TEST_BUDGET_UUID;
530
-
531
- // Mock filtered transactions
532
- mockYnabAPI.transactions.getTransactions.mockResolvedValue({
533
- data: {
534
- transactions: [
535
- {
536
- id: 'filtered-transaction',
537
- date: '2024-01-15',
538
- amount: -1000,
539
- memo: 'Filtered transaction',
540
- cleared: 'cleared',
541
- approved: true,
542
- account_id: 'account-1',
543
- category_id: 'category-1',
544
- },
545
- ],
546
- },
547
- });
548
-
549
- // Test filtering by date
550
- const dateFilterResult = await executeToolCall(server, 'ynab:list_transactions', {
551
- budget_id: budgetId,
552
- since_date: '2024-01-01',
553
- });
554
- validateToolResult(dateFilterResult);
555
-
556
- // Also mock account/category specific endpoints
557
- mockYnabAPI.transactions.getTransactionsByAccount.mockResolvedValue({
558
- data: {
559
- transactions: [
560
- {
561
- id: 'filtered-transaction',
562
- date: '2024-01-15',
563
- amount: -1000,
564
- memo: 'Filtered transaction',
565
- cleared: 'cleared',
566
- approved: true,
567
- account_id: 'account-1',
568
- category_id: 'category-1',
569
- },
570
- ],
571
- },
572
- });
573
- mockYnabAPI.transactions.getTransactionsByCategory.mockResolvedValue({
574
- data: {
575
- transactions: [
576
- {
577
- id: 'filtered-transaction',
578
- date: '2024-01-15',
579
- amount: -1000,
580
- memo: 'Filtered transaction',
581
- cleared: 'cleared',
582
- approved: true,
583
- account_id: 'account-1',
584
- category_id: 'category-1',
585
- },
586
- ],
587
- },
588
- });
589
-
590
- // Test filtering by account
591
- const accountFilterResult = await executeToolCall(server, 'ynab:list_transactions', {
592
- budget_id: budgetId,
593
- account_id: 'account-1',
594
- });
595
- validateToolResult(accountFilterResult);
596
-
597
- // Test filtering by category
598
- const categoryFilterResult = await executeToolCall(server, 'ynab:list_transactions', {
599
- budget_id: budgetId,
600
- category_id: 'category-1',
601
- });
602
- validateToolResult(categoryFilterResult);
603
-
604
- // Verify API calls with different parameters
605
- expect(mockYnabAPI.transactions.getTransactions).toHaveBeenCalledTimes(1);
606
- expect(mockYnabAPI.transactions.getTransactionsByAccount).toHaveBeenCalledTimes(1);
607
- expect(mockYnabAPI.transactions.getTransactionsByCategory).toHaveBeenCalledTimes(1);
608
- },
609
- );
610
- });
611
-
612
- describe('Complete Category Management Integration', () => {
613
- it(
614
- 'should handle complete category workflow',
615
- { meta: { tier: 'domain', domain: 'workflows' } },
616
- async () => {
617
- const budgetId = TEST_BUDGET_UUID;
618
-
619
- // Mock categories response
620
- const mockCategories = {
621
- data: {
622
- category_groups: [
623
- {
624
- id: 'group-1',
625
- name: 'Immediate Obligations',
626
- hidden: false,
627
- deleted: false,
628
- categories: [
629
- {
630
- id: 'category-1',
631
- category_group_id: 'group-1',
632
- name: 'Rent/Mortgage',
633
- hidden: false,
634
- budgeted: 150000, // $150.00
635
- activity: -150000,
636
- balance: 0,
637
- // goal_type omitted (undefined, not null)
638
- deleted: false,
639
- },
640
- {
641
- id: 'category-2',
642
- category_group_id: 'group-1',
643
- name: 'Utilities',
644
- hidden: false,
645
- budgeted: 10000, // $10.00
646
- activity: -8500,
647
- balance: 1500,
648
- // goal_type omitted (undefined, not null)
649
- deleted: false,
650
- },
651
- ],
652
- },
653
- ],
654
- },
655
- };
656
-
657
- mockYnabAPI.categories.getCategories.mockResolvedValue(mockCategories);
658
-
659
- // Test category listing
660
- const listResult = await executeToolCall(server, 'ynab:list_categories', {
661
- budget_id: budgetId,
662
- });
663
- validateToolResult(listResult);
664
-
665
- const categories = parseToolResult(listResult);
666
- expect(categories.data.category_groups).toHaveLength(1);
667
- expect(categories.data.categories).toHaveLength(2);
668
- expect(categories.data.categories[0].name).toBe('Rent/Mortgage');
669
-
670
- // Mock specific category response
671
- const mockCategory = {
672
- data: {
673
- category: mockCategories.data.category_groups[0].categories[0],
674
- },
675
- };
676
-
677
- mockYnabAPI.categories.getCategoryById.mockResolvedValue(mockCategory);
678
-
679
- // Test specific category retrieval
680
- const getResult = await executeToolCall(server, 'ynab:get_category', {
681
- budget_id: budgetId,
682
- category_id: 'category-1',
683
- });
684
- validateToolResult(getResult);
685
-
686
- const category = parseToolResult(getResult);
687
- expect(category.data.category.id).toBe('category-1');
688
- expect(category.data.category.name).toBe('Rent/Mortgage');
689
- expect(category.data.category.budgeted).toBe(150);
690
-
691
- // Mock category update
692
- const updatedCategory = {
693
- ...mockCategories.data.category_groups[0].categories[0],
694
- budgeted: 160000, // $160.00
695
- };
696
-
697
- const mockUpdateResponse = {
698
- data: {
699
- category: updatedCategory,
700
- },
701
- };
702
-
703
- mockYnabAPI.categories.updateMonthCategory.mockResolvedValue(mockUpdateResponse);
704
-
705
- // Test category budget update
706
- const updateResult = await executeToolCall(server, 'ynab:update_category', {
707
- budget_id: budgetId,
708
- category_id: 'category-1',
709
- budgeted: 160000,
710
- });
711
- validateToolResult(updateResult);
712
-
713
- const updated = parseToolResult(updateResult);
714
- expect(updated.data.category.budgeted).toBe(160);
715
-
716
- // Verify API calls
717
- expect(mockYnabAPI.categories.getCategories).toHaveBeenCalledWith(budgetId);
718
- expect(mockYnabAPI.categories.getCategoryById).toHaveBeenCalledWith(budgetId, 'category-1');
719
- expect(mockYnabAPI.categories.updateMonthCategory).toHaveBeenCalled();
720
- },
721
- );
722
- });
723
-
724
- describe('Complete Utility Tools Integration', () => {
725
- it(
726
- 'should handle user information retrieval',
727
- { meta: { tier: 'domain', domain: 'workflows' } },
728
- async () => {
729
- // Mock user response
730
- const mockUser = {
731
- data: {
732
- user: {
733
- id: 'user-123',
734
- email: 'test@example.com',
735
- },
736
- },
737
- };
738
-
739
- mockYnabAPI.user.getUser.mockResolvedValue(mockUser);
740
-
741
- // Test user retrieval
742
- const userResult = await executeToolCall(server, 'ynab:get_user');
743
- validateToolResult(userResult);
744
-
745
- const user = parseToolResult(userResult);
746
- expect(user.data.user.id).toBe('user-123');
747
-
748
- expect(mockYnabAPI.user.getUser).toHaveBeenCalledTimes(1);
749
- },
750
- );
751
- });
752
-
753
- describe('Error Handling Integration', () => {
754
- it(
755
- 'should handle various API error scenarios',
756
- { meta: { tier: 'domain', domain: 'workflows' } },
757
- async () => {
758
- // Test 401 Unauthorized
759
- const authError = new Error('Unauthorized');
760
- (authError as any).error = { id: '401', name: 'unauthorized', description: 'Unauthorized' };
761
- mockYnabAPI.budgets.getBudgets.mockRejectedValue(authError);
762
-
763
- try {
764
- await executeToolCall(server, 'ynab:list_budgets');
765
- expect.fail('Should have thrown an error');
766
- } catch (error) {
767
- expect(error).toBeDefined();
768
- }
769
-
770
- // Test 404 Not Found
771
- const notFoundError = new Error('Not Found');
772
- (notFoundError as any).error = {
773
- id: '404.2',
774
- name: 'not_found',
775
- description: 'Budget not found',
776
- };
777
- mockYnabAPI.budgets.getBudgetById.mockRejectedValue(notFoundError);
778
-
779
- try {
780
- await executeToolCall(server, 'ynab:get_budget', { budget_id: 'invalid' });
781
- expect.fail('Should have thrown an error');
782
- } catch (error) {
783
- expect(error).toBeDefined();
784
- }
785
-
786
- // Test 429 Rate Limit
787
- const rateLimitError = new Error('Too Many Requests');
788
- (rateLimitError as any).error = {
789
- id: '429',
790
- name: 'rate_limit',
791
- description: 'Rate limit exceeded',
792
- };
793
- mockYnabAPI.accounts.getAccounts.mockRejectedValue(rateLimitError);
794
-
795
- try {
796
- await executeToolCall(server, 'ynab:list_accounts', { budget_id: 'test' });
797
- expect.fail('Should have thrown an error');
798
- } catch (error) {
799
- expect(error).toBeDefined();
800
- }
801
- },
802
- );
803
-
804
- it(
805
- 'should validate input parameters',
806
- { meta: { tier: 'domain', domain: 'workflows' } },
807
- async () => {
808
- // Test missing required parameters
809
- try {
810
- await executeToolCall(server, 'ynab:get_budget', {});
811
- expect.fail('Should have thrown validation error');
812
- } catch (error) {
813
- expect(error).toBeDefined();
814
- }
815
-
816
- // Test invalid parameter types
817
- try {
818
- await executeToolCall(server, 'ynab:create_transaction', {
819
- budget_id: 'test',
820
- account_id: 'test',
821
- amount: 'invalid-amount', // Should be number
822
- date: '2024-01-01',
823
- });
824
- expect.fail('Should have thrown validation error');
825
- } catch (error) {
826
- expect(error).toBeDefined();
827
- }
828
- },
829
- );
830
- });
831
-
832
- describe('Caching Integration Tests', () => {
833
- let previousNodeEnv: string | undefined;
834
-
835
- beforeAll(() => {
836
- previousNodeEnv = process.env['NODE_ENV'];
837
- process.env['NODE_ENV'] = 'development';
838
- });
839
-
840
- beforeEach(() => {
841
- cacheManager.clear();
842
- process.env['NODE_ENV'] = 'development';
843
- });
844
-
845
- afterAll(() => {
846
- // Restore NODE_ENV after all caching tests complete
847
- if (previousNodeEnv === undefined) {
848
- delete process.env['NODE_ENV'];
849
- } else {
850
- process.env['NODE_ENV'] = previousNodeEnv;
851
- }
852
- });
853
-
854
- // TODO: Re-enable after DeltaFetcher cache integration alignment.
855
- it.skip(
856
- 'should cache budget list requests and improve performance on subsequent calls',
857
- { meta: { tier: 'domain', domain: 'workflows' } },
858
- async () => {
859
- const mockBudgets = {
860
- data: {
861
- budgets: [
862
- {
863
- id: 'budget-1',
864
- name: 'Test Budget',
865
- last_modified_on: '2024-01-01T00:00:00Z',
866
- first_month: '2024-01-01',
867
- last_month: '2024-12-01',
868
- date_format: { format: 'MM/DD/YYYY' },
869
- currency_format: {
870
- iso_code: 'USD',
871
- example_format: '$123.45',
872
- decimal_digits: 2,
873
- decimal_separator: '.',
874
- symbol_first: true,
875
- group_separator: ',',
876
- currency_symbol: '$',
877
- display_symbol: true,
878
- },
879
- },
880
- ],
881
- },
882
- };
883
-
884
- mockYnabAPI.budgets.getBudgets.mockResolvedValue(mockBudgets);
885
-
886
- const statsBeforeFirstCall = cacheManager.getStats();
887
- const initialSize = statsBeforeFirstCall.size;
888
-
889
- // First call - should hit API and cache result
890
- const firstResult = await executeToolCall(server, 'ynab:list_budgets');
891
- validateToolResult(firstResult);
892
-
893
- const firstParsed = parseToolResult(firstResult);
894
- expect(firstParsed.data.cached).toBe(false);
895
- expect(firstParsed.data.cache_info).toBe('Fresh data retrieved from YNAB API');
896
-
897
- // Cache should have grown
898
- const statsAfterFirstCall = cacheManager.getStats();
899
- expect(statsAfterFirstCall.size).toBeGreaterThan(initialSize);
900
-
901
- // Second call - should hit cache
902
- const secondResult = await executeToolCall(server, 'ynab:list_budgets');
903
- validateToolResult(secondResult);
904
-
905
- const secondParsed = parseToolResult(secondResult);
906
- expect(secondParsed.data.cached).toBe(true);
907
- expect(secondParsed.data.cache_info).toBe(
908
- 'Data retrieved from cache for improved performance',
909
- );
910
-
911
- // API should only have been called once
912
- expect(mockYnabAPI.budgets.getBudgets).toHaveBeenCalledTimes(1);
913
-
914
- // Cache hit count should have increased
915
- const finalStats = cacheManager.getStats();
916
- expect(finalStats.hits).toBeGreaterThan(statsBeforeFirstCall.hits);
917
- },
918
- );
919
-
920
- it(
921
- 'should invalidate cache on write operations',
922
- { meta: { tier: 'domain', domain: 'workflows' } },
923
- async () => {
924
- const budgetId = TEST_BUDGET_UUID;
925
-
926
- // Mock responses
927
- const mockAccounts = {
928
- data: {
929
- accounts: [
930
- {
931
- id: 'account-1',
932
- name: 'Test Account',
933
- type: 'checking',
934
- on_budget: true,
935
- closed: false,
936
- balance: 100000,
937
- cleared_balance: 95000,
938
- uncleared_balance: 5000,
939
- },
940
- ],
941
- },
942
- };
943
-
944
- const mockCreatedAccount = {
945
- data: {
946
- account: {
947
- id: 'account-2',
948
- name: 'New Account',
949
- type: 'savings',
950
- on_budget: true,
951
- closed: false,
952
- balance: 0,
953
- cleared_balance: 0,
954
- uncleared_balance: 0,
955
- },
956
- },
957
- };
958
-
959
- mockYnabAPI.accounts.getAccounts.mockResolvedValue(mockAccounts);
960
- mockYnabAPI.accounts.createAccount.mockResolvedValue(mockCreatedAccount);
961
-
962
- // First, populate cache with account list
963
- await executeToolCall(server, 'ynab:list_accounts', { budget_id: budgetId });
964
-
965
- // Verify cache has entries
966
- const statsAfterRead = cacheManager.getStats();
967
- expect(statsAfterRead.size).toBeGreaterThan(0);
968
-
969
- // Create a new account (write operation)
970
- await executeToolCall(server, 'ynab:create_account', {
971
- budget_id: budgetId,
972
- name: 'New Account',
973
- type: 'savings',
974
- });
975
-
976
- // Next call to list accounts should hit API again (cache was invalidated)
977
- mockYnabAPI.accounts.getAccounts.mockClear();
978
- await executeToolCall(server, 'ynab:list_accounts', { budget_id: budgetId });
979
-
980
- // Verify API was called again after cache invalidation
981
- expect(mockYnabAPI.accounts.getAccounts).toHaveBeenCalledTimes(1);
982
- },
983
- );
984
-
985
- // TODO: Re-enable after DeltaFetcher cache integration alignment.
986
- it.skip(
987
- 'should not cache filtered transaction requests',
988
- { meta: { tier: 'domain', domain: 'workflows' } },
989
- async () => {
990
- const budgetId = TEST_BUDGET_UUID;
991
-
992
- const mockTransactions = {
993
- data: {
994
- transactions: [
995
- {
996
- id: 'transaction-1',
997
- date: '2024-01-15',
998
- amount: -5000,
999
- memo: 'Test transaction',
1000
- cleared: 'cleared',
1001
- approved: true,
1002
- account_id: 'account-1',
1003
- category_id: 'category-1',
1004
- },
1005
- ],
1006
- },
1007
- };
1008
-
1009
- mockYnabAPI.transactions.getTransactions.mockResolvedValue(mockTransactions);
1010
- mockYnabAPI.transactions.getTransactionsByAccount.mockResolvedValue(mockTransactions);
1011
-
1012
- const statsBeforeUnfiltered = cacheManager.getStats();
1013
-
1014
- // Unfiltered request - should be cached
1015
- const unfilteredResult = await executeToolCall(server, 'ynab:list_transactions', {
1016
- budget_id: budgetId,
1017
- });
1018
- const unfilteredParsed = parseToolResult(unfilteredResult);
1019
- expect(unfilteredParsed.data.cached).toBe(false); // First call, cache miss
1020
-
1021
- const statsAfterUnfiltered = cacheManager.getStats();
1022
- expect(statsAfterUnfiltered.size).toBeGreaterThan(statsBeforeUnfiltered.size);
1023
-
1024
- // Filtered request - should NOT be cached
1025
- const filteredResult = await executeToolCall(server, 'ynab:list_transactions', {
1026
- budget_id: budgetId,
1027
- account_id: 'account-1',
1028
- });
1029
- const filteredParsed = parseToolResult(filteredResult);
1030
- expect(filteredParsed.data.cached).toBe(false);
1031
- expect(filteredParsed.data.cache_info).toBe('Fresh data retrieved from YNAB API');
1032
-
1033
- // Cache size should not have increased for filtered request
1034
- const statsAfterFiltered = cacheManager.getStats();
1035
- expect(statsAfterFiltered.size).toBe(statsAfterUnfiltered.size);
1036
-
1037
- // Both API methods should have been called
1038
- expect(mockYnabAPI.transactions.getTransactions).toHaveBeenCalledTimes(1);
1039
- expect(mockYnabAPI.transactions.getTransactionsByAccount).toHaveBeenCalledTimes(1);
1040
- },
1041
- );
1042
-
1043
- it(
1044
- 'should handle cache warming after setting default budget',
1045
- { meta: { tier: 'domain', domain: 'workflows' } },
1046
- async () => {
1047
- const budgetId = TEST_BUDGET_UUID;
1048
-
1049
- // Mock all the responses for cache warming
1050
- mockYnabAPI.accounts.getAccounts.mockResolvedValue({
1051
- data: { accounts: [] },
1052
- });
1053
- mockYnabAPI.budgets.getBudgetById.mockResolvedValue({
1054
- data: { budget: { id: budgetId, name: 'Warm Cache Budget' } },
1055
- });
1056
- mockYnabAPI.categories.getCategories.mockResolvedValue({
1057
- data: { category_groups: [] },
1058
- });
1059
- mockYnabAPI.payees.getPayees.mockResolvedValue({
1060
- data: { payees: [] },
1061
- });
1062
-
1063
- const statsBeforeSet = cacheManager.getStats();
1064
- const initialSize = statsBeforeSet.size;
1065
-
1066
- // Set default budget (should trigger cache warming)
1067
- await executeToolCall(server, 'ynab:set_default_budget', {
1068
- budget_id: budgetId,
1069
- });
1070
-
1071
- // Wait for cache warming to populate entries (fire-and-forget process)
1072
- let statsAfterSet = cacheManager.getStats();
1073
- await waitFor(
1074
- () => {
1075
- statsAfterSet = cacheManager.getStats();
1076
- return statsAfterSet.size > initialSize;
1077
- },
1078
- 1000,
1079
- 50,
1080
- );
1081
-
1082
- // Cache should have more entries due to warming
1083
- expect(statsAfterSet.size).toBeGreaterThan(initialSize);
1084
-
1085
- // Verify that cache warming API calls were made
1086
- expect(mockYnabAPI.accounts.getAccounts).toHaveBeenCalled();
1087
- expect(mockYnabAPI.categories.getCategories).toHaveBeenCalled();
1088
- expect(mockYnabAPI.payees.getPayees).toHaveBeenCalled();
1089
- },
1090
- );
1091
-
1092
- it(
1093
- 'should handle cache clear operation',
1094
- { meta: { tier: 'domain', domain: 'workflows' } },
1095
- async () => {
1096
- // Populate cache with some data
1097
- mockYnabAPI.budgets.getBudgets.mockResolvedValue({
1098
- data: { budgets: [] },
1099
- });
1100
-
1101
- await executeToolCall(server, 'ynab:list_budgets');
1102
-
1103
- // Verify cache has entries
1104
- const statsAfterPopulation = cacheManager.getStats();
1105
- expect(statsAfterPopulation.size).toBeGreaterThan(0);
1106
-
1107
- // Clear cache
1108
- await executeToolCall(server, 'ynab:clear_cache');
1109
-
1110
- // Verify cache is empty
1111
- const statsAfterClear = cacheManager.getStats();
1112
- expect(statsAfterClear.size).toBe(0);
1113
- expect(statsAfterClear.hits).toBe(0);
1114
- expect(statsAfterClear.misses).toBe(0);
1115
- },
1116
- );
1117
-
1118
- // TODO: Re-enable after DeltaFetcher cache integration alignment.
1119
- it.skip(
1120
- 'should respect cache TTL and return fresh data after expiration',
1121
- { meta: { tier: 'domain', domain: 'workflows' } },
1122
- async () => {
1123
- // Note: This test is conceptual since TTL testing requires time manipulation
1124
- // In a real scenario, we would mock the Date.now() or use a test clock
1125
-
1126
- const mockBudgets = {
1127
- data: {
1128
- budgets: [
1129
- {
1130
- id: 'budget-1',
1131
- name: 'Test Budget',
1132
- last_modified_on: '2024-01-01T00:00:00Z',
1133
- first_month: '2024-01-01',
1134
- last_month: '2024-12-01',
1135
- date_format: { format: 'MM/DD/YYYY' },
1136
- currency_format: {
1137
- iso_code: 'USD',
1138
- example_format: '$123.45',
1139
- decimal_digits: 2,
1140
- decimal_separator: '.',
1141
- symbol_first: true,
1142
- group_separator: ',',
1143
- currency_symbol: '$',
1144
- display_symbol: true,
1145
- },
1146
- },
1147
- ],
1148
- },
1149
- };
1150
-
1151
- mockYnabAPI.budgets.getBudgets.mockResolvedValue(mockBudgets);
1152
-
1153
- // First call - cache miss
1154
- const firstResult = await executeToolCall(server, 'ynab:list_budgets');
1155
- const firstParsed = parseToolResult(firstResult);
1156
- expect(firstParsed.data.cached).toBe(false);
1157
-
1158
- // Second call - cache hit
1159
- const secondResult = await executeToolCall(server, 'ynab:list_budgets');
1160
- const secondParsed = parseToolResult(secondResult);
1161
- expect(secondParsed.data.cached).toBe(true);
1162
-
1163
- // Verify API was only called once (second call used cache)
1164
- expect(mockYnabAPI.budgets.getBudgets).toHaveBeenCalledTimes(1);
1165
- },
1166
- );
1167
- });
95
+ describe("YNAB MCP Server - Comprehensive Integration Tests", () => {
96
+ let server: YNABMCPServer;
97
+ let mockYnabAPI: any;
98
+
99
+ beforeEach(async () => {
100
+ // Set up environment
101
+ process.env.YNAB_ACCESS_TOKEN = "test-token";
102
+
103
+ // Create server instance
104
+ server = new YNABMCPServer();
105
+
106
+ // Get the mocked YNAB API instance
107
+ const { API } = await import("ynab");
108
+ mockYnabAPI = new (API as any)();
109
+
110
+ // Reset all mocks
111
+ vi.clearAllMocks();
112
+ });
113
+
114
+ describe("Complete Budget Management Integration", () => {
115
+ it(
116
+ "should handle complete budget listing and retrieval workflow",
117
+ { meta: { tier: "domain", domain: "workflows" } },
118
+ async () => {
119
+ // Mock budget list response
120
+ const mockBudgets = {
121
+ data: {
122
+ budgets: [
123
+ {
124
+ id: "budget-1",
125
+ name: "Test Budget 1",
126
+ last_modified_on: "2024-01-01T00:00:00Z",
127
+ first_month: "2024-01-01",
128
+ last_month: "2024-12-01",
129
+ date_format: { format: "MM/DD/YYYY" },
130
+ currency_format: {
131
+ iso_code: "USD",
132
+ example_format: "$123.45",
133
+ decimal_digits: 2,
134
+ decimal_separator: ".",
135
+ symbol_first: true,
136
+ group_separator: ",",
137
+ currency_symbol: "$",
138
+ display_symbol: true,
139
+ },
140
+ },
141
+ {
142
+ id: "budget-2",
143
+ name: "Test Budget 2",
144
+ last_modified_on: "2024-01-02T00:00:00Z",
145
+ first_month: "2024-01-01",
146
+ last_month: "2024-12-01",
147
+ date_format: { format: "MM/DD/YYYY" },
148
+ currency_format: {
149
+ iso_code: "USD",
150
+ example_format: "$123.45",
151
+ decimal_digits: 2,
152
+ decimal_separator: ".",
153
+ symbol_first: true,
154
+ group_separator: ",",
155
+ currency_symbol: "$",
156
+ display_symbol: true,
157
+ },
158
+ },
159
+ ],
160
+ },
161
+ };
162
+
163
+ mockYnabAPI.budgets.getBudgets.mockResolvedValue(mockBudgets);
164
+
165
+ // Test budget listing
166
+ const listResult = await executeToolCall(server, "ynab:list_budgets");
167
+ validateToolResult(listResult);
168
+
169
+ const budgets = parseToolResult(listResult);
170
+ expect(budgets.data.budgets).toHaveLength(2);
171
+ expect(budgets.data.budgets[0].name).toBe("Test Budget 1");
172
+ expect(budgets.data.budgets[1].name).toBe("Test Budget 2");
173
+
174
+ // Mock specific budget response
175
+ const mockBudget = {
176
+ data: {
177
+ budget: {
178
+ id: "budget-1",
179
+ name: "Test Budget 1",
180
+ last_modified_on: "2024-01-01T00:00:00Z",
181
+ first_month: "2024-01-01",
182
+ last_month: "2024-12-01",
183
+ date_format: { format: "MM/DD/YYYY" },
184
+ currency_format: {
185
+ iso_code: "USD",
186
+ example_format: "$123.45",
187
+ decimal_digits: 2,
188
+ decimal_separator: ".",
189
+ symbol_first: true,
190
+ group_separator: ",",
191
+ currency_symbol: "$",
192
+ display_symbol: true,
193
+ },
194
+ accounts: [],
195
+ payees: [],
196
+ category_groups: [],
197
+ months: [],
198
+ },
199
+ },
200
+ };
201
+
202
+ mockYnabAPI.budgets.getBudgetById.mockResolvedValue(mockBudget);
203
+
204
+ // Test specific budget retrieval
205
+ const getResult = await executeToolCall(server, "ynab:get_budget", {
206
+ budget_id: "budget-1",
207
+ });
208
+ validateToolResult(getResult);
209
+
210
+ const budget = parseToolResult(getResult);
211
+ expect(budget.data.budget.id).toBe("budget-1");
212
+ expect(budget.data.budget.name).toBe("Test Budget 1");
213
+
214
+ // Verify API calls
215
+ expect(mockYnabAPI.budgets.getBudgets).toHaveBeenCalledTimes(1);
216
+ expect(mockYnabAPI.budgets.getBudgetById).toHaveBeenCalledWith(
217
+ "budget-1",
218
+ );
219
+ },
220
+ );
221
+
222
+ it(
223
+ "should handle budget retrieval errors gracefully",
224
+ { meta: { tier: "domain", domain: "workflows" } },
225
+ async () => {
226
+ // Mock API error
227
+ const apiError = new Error("Budget not found");
228
+ (apiError as any).error = {
229
+ id: "404.2",
230
+ name: "not_found",
231
+ description: "Budget not found",
232
+ };
233
+ mockYnabAPI.budgets.getBudgetById.mockRejectedValue(apiError);
234
+
235
+ // Test error handling
236
+ try {
237
+ await executeToolCall(server, "ynab:get_budget", {
238
+ budget_id: "invalid-budget",
239
+ });
240
+ expect.fail("Should have thrown an error");
241
+ } catch (error) {
242
+ expect(error).toBeDefined();
243
+ }
244
+
245
+ expect(mockYnabAPI.budgets.getBudgetById).toHaveBeenCalledWith(
246
+ "invalid-budget",
247
+ );
248
+ },
249
+ );
250
+ });
251
+
252
+ describe("Complete Account Management Integration", () => {
253
+ it(
254
+ "should handle complete account workflow",
255
+ { meta: { tier: "domain", domain: "workflows" } },
256
+ async () => {
257
+ const budgetId = TEST_BUDGET_UUID;
258
+
259
+ // Mock accounts list
260
+ const mockAccounts = {
261
+ data: {
262
+ accounts: [
263
+ {
264
+ id: "account-1",
265
+ name: "Checking Account",
266
+ type: "checking",
267
+ on_budget: true,
268
+ closed: false,
269
+ balance: 100000, // $100.00
270
+ cleared_balance: 95000,
271
+ uncleared_balance: 5000,
272
+ transfer_payee_id: "payee-transfer-1",
273
+ },
274
+ {
275
+ id: "account-2",
276
+ name: "Savings Account",
277
+ type: "savings",
278
+ on_budget: true,
279
+ closed: false,
280
+ note: "Emergency fund",
281
+ balance: 500000, // $500.00
282
+ cleared_balance: 500000,
283
+ uncleared_balance: 0,
284
+ transfer_payee_id: "payee-transfer-2",
285
+ },
286
+ ],
287
+ },
288
+ };
289
+
290
+ mockYnabAPI.accounts.getAccounts.mockResolvedValue(mockAccounts);
291
+
292
+ // Test account listing
293
+ const listResult = await executeToolCall(server, "ynab:list_accounts", {
294
+ budget_id: budgetId,
295
+ });
296
+ validateToolResult(listResult);
297
+
298
+ const accounts = parseToolResult(listResult);
299
+ expect(accounts.data.accounts).toHaveLength(2);
300
+ expect(accounts.data.accounts[0].name).toBe("Checking Account");
301
+ expect(accounts.data.accounts[1].name).toBe("Savings Account");
302
+
303
+ // Mock specific account response
304
+ const mockAccount = {
305
+ data: {
306
+ account: mockAccounts.data.accounts[0],
307
+ },
308
+ };
309
+
310
+ mockYnabAPI.accounts.getAccountById.mockResolvedValue(mockAccount);
311
+
312
+ // Test specific account retrieval
313
+ const getResult = await executeToolCall(server, "ynab:get_account", {
314
+ budget_id: budgetId,
315
+ account_id: "account-1",
316
+ });
317
+ validateToolResult(getResult);
318
+
319
+ const account = parseToolResult(getResult);
320
+ expect(account.data.account.id).toBe("account-1");
321
+ expect(account.data.account.name).toBe("Checking Account");
322
+ expect(account.data.account.balance).toBe(100);
323
+
324
+ // Mock account creation
325
+ const newAccount = {
326
+ id: "account-3",
327
+ name: "New Test Account",
328
+ type: "checking",
329
+ on_budget: true,
330
+ closed: false,
331
+ balance: 0,
332
+ cleared_balance: 0,
333
+ uncleared_balance: 0,
334
+ transfer_payee_id: "payee-transfer-3",
335
+ };
336
+
337
+ const mockCreateResponse = {
338
+ data: {
339
+ account: newAccount,
340
+ },
341
+ };
342
+
343
+ mockYnabAPI.accounts.createAccount.mockResolvedValue(
344
+ mockCreateResponse,
345
+ );
346
+
347
+ // Test account creation
348
+ const createResult = await executeToolCall(
349
+ server,
350
+ "ynab:create_account",
351
+ {
352
+ budget_id: budgetId,
353
+ name: "New Test Account",
354
+ type: "checking",
355
+ balance: 0,
356
+ },
357
+ );
358
+ validateToolResult(createResult);
359
+
360
+ const createdAccount = parseToolResult(createResult);
361
+ expect(createdAccount.data.account.name).toBe("New Test Account");
362
+ expect(createdAccount.data.account.type).toBe("checking");
363
+
364
+ // Verify API calls
365
+ expect(mockYnabAPI.accounts.getAccounts).toHaveBeenCalledWith(budgetId);
366
+ expect(mockYnabAPI.accounts.getAccountById).toHaveBeenCalledWith(
367
+ budgetId,
368
+ "account-1",
369
+ );
370
+ expect(mockYnabAPI.accounts.createAccount).toHaveBeenCalledWith(
371
+ budgetId,
372
+ {
373
+ account: {
374
+ name: "New Test Account",
375
+ type: "checking",
376
+ balance: 0,
377
+ },
378
+ },
379
+ );
380
+ },
381
+ );
382
+ });
383
+
384
+ describe("Complete Transaction Management Integration", () => {
385
+ // TODO: Re-enable after DeltaFetcher cache integration alignment.
386
+ it.skip(
387
+ "should handle complete transaction workflow",
388
+ { meta: { tier: "domain", domain: "workflows" } },
389
+ async () => {
390
+ const budgetId = TEST_BUDGET_UUID;
391
+ const accountId = "test-account";
392
+
393
+ // Mock transactions list
394
+ const mockTransactions = {
395
+ data: {
396
+ transactions: [
397
+ {
398
+ id: "transaction-1",
399
+ date: "2024-01-15",
400
+ amount: -5000, // $5.00 outflow
401
+ memo: "Coffee shop",
402
+ cleared: "cleared",
403
+ approved: true,
404
+ flag_color: null,
405
+ account_id: accountId,
406
+ payee_id: "payee-1",
407
+ category_id: "category-1",
408
+ transfer_account_id: null,
409
+ },
410
+ {
411
+ id: "transaction-2",
412
+ date: "2024-01-16",
413
+ amount: 100000, // $100.00 inflow
414
+ memo: "Salary",
415
+ cleared: "cleared",
416
+ approved: true,
417
+ flag_color: null,
418
+ account_id: accountId,
419
+ payee_id: "payee-2",
420
+ category_id: null,
421
+ transfer_account_id: null,
422
+ },
423
+ ],
424
+ },
425
+ };
426
+
427
+ mockYnabAPI.transactions.getTransactionsByAccount.mockResolvedValue(
428
+ mockTransactions,
429
+ );
430
+
431
+ // Test transaction listing
432
+ const listResult = await executeToolCall(
433
+ server,
434
+ "ynab:list_transactions",
435
+ {
436
+ budget_id: budgetId,
437
+ account_id: accountId,
438
+ },
439
+ );
440
+ validateToolResult(listResult);
441
+
442
+ const transactions = parseToolResult(listResult);
443
+ expect(transactions.data.transactions).toHaveLength(2);
444
+ expect(transactions.data.transactions[0].memo).toBe("Coffee shop");
445
+ expect(transactions.data.transactions[1].memo).toBe("Salary");
446
+
447
+ // Mock specific transaction response
448
+ const mockTransaction = {
449
+ data: {
450
+ transaction: mockTransactions.data.transactions[0],
451
+ },
452
+ };
453
+
454
+ mockYnabAPI.transactions.getTransactionById.mockResolvedValue(
455
+ mockTransaction,
456
+ );
457
+
458
+ // Test specific transaction retrieval
459
+ const getResult = await executeToolCall(
460
+ server,
461
+ "ynab:get_transaction",
462
+ {
463
+ budget_id: budgetId,
464
+ transaction_id: "transaction-1",
465
+ },
466
+ );
467
+ validateToolResult(getResult);
468
+
469
+ const transaction = parseToolResult(getResult);
470
+ expect(transaction.data.transaction.id).toBe("transaction-1");
471
+ expect(transaction.data.transaction.memo).toBe("Coffee shop");
472
+ expect(transaction.data.transaction.amount).toBe(-5);
473
+
474
+ // Mock transaction creation
475
+ const newTransaction = {
476
+ id: "transaction-3",
477
+ date: "2024-01-17",
478
+ amount: -2500,
479
+ memo: "Test transaction",
480
+ cleared: "uncleared",
481
+ approved: true,
482
+ flag_color: null,
483
+ account_id: accountId,
484
+ payee_id: null,
485
+ category_id: "category-1",
486
+ transfer_account_id: null,
487
+ };
488
+
489
+ const mockCreateResponse = {
490
+ data: {
491
+ transaction: newTransaction,
492
+ },
493
+ };
494
+
495
+ mockYnabAPI.transactions.createTransaction.mockResolvedValue(
496
+ mockCreateResponse,
497
+ );
498
+
499
+ // Test transaction creation
500
+ const createResult = await executeToolCall(
501
+ server,
502
+ "ynab:create_transaction",
503
+ {
504
+ budget_id: budgetId,
505
+ account_id: accountId,
506
+ category_id: "category-1",
507
+ payee_name: "Test Payee",
508
+ amount: -2500,
509
+ memo: "Test transaction",
510
+ date: "2024-01-17",
511
+ cleared: "uncleared",
512
+ },
513
+ );
514
+ validateToolResult(createResult);
515
+
516
+ const createdTransaction = parseToolResult(createResult);
517
+ expect(createdTransaction.data.transaction.memo).toBe(
518
+ "Test transaction",
519
+ );
520
+ expect(createdTransaction.data.transaction.amount).toBe(-2.5);
521
+
522
+ // Mock transaction update
523
+ const updatedTransaction = { ...newTransaction, memo: "Updated memo" };
524
+ const mockUpdateResponse = {
525
+ data: {
526
+ transaction: updatedTransaction,
527
+ },
528
+ };
529
+
530
+ mockYnabAPI.transactions.updateTransaction.mockResolvedValue(
531
+ mockUpdateResponse,
532
+ );
533
+
534
+ // Test transaction update
535
+ const updateResult = await executeToolCall(
536
+ server,
537
+ "ynab:update_transaction",
538
+ {
539
+ budget_id: budgetId,
540
+ transaction_id: "transaction-3",
541
+ memo: "Updated memo",
542
+ },
543
+ );
544
+ validateToolResult(updateResult);
545
+
546
+ const updated = parseToolResult(updateResult);
547
+ expect(updated.data.transaction.memo).toBe("Updated memo");
548
+
549
+ // Mock transaction deletion
550
+ mockYnabAPI.transactions.deleteTransaction.mockResolvedValue({
551
+ data: {
552
+ transaction: { ...updatedTransaction, deleted: true },
553
+ },
554
+ });
555
+
556
+ // Test transaction deletion
557
+ const deleteResult = await executeToolCall(
558
+ server,
559
+ "ynab:delete_transaction",
560
+ {
561
+ budget_id: budgetId,
562
+ transaction_id: "transaction-3",
563
+ },
564
+ );
565
+ validateToolResult(deleteResult);
566
+
567
+ // Verify API calls
568
+ expect(
569
+ mockYnabAPI.transactions.getTransactionsByAccount,
570
+ ).toHaveBeenCalledWith(budgetId, accountId, undefined);
571
+ expect(
572
+ mockYnabAPI.transactions.getTransactionById,
573
+ ).toHaveBeenCalledWith(budgetId, "transaction-1");
574
+ expect(mockYnabAPI.transactions.createTransaction).toHaveBeenCalled();
575
+ expect(mockYnabAPI.transactions.updateTransaction).toHaveBeenCalled();
576
+ expect(mockYnabAPI.transactions.deleteTransaction).toHaveBeenCalledWith(
577
+ budgetId,
578
+ "transaction-3",
579
+ );
580
+ },
581
+ );
582
+
583
+ it(
584
+ "should handle transaction filtering",
585
+ { meta: { tier: "domain", domain: "workflows" } },
586
+ async () => {
587
+ const budgetId = TEST_BUDGET_UUID;
588
+
589
+ // Mock filtered transactions
590
+ mockYnabAPI.transactions.getTransactions.mockResolvedValue({
591
+ data: {
592
+ transactions: [
593
+ {
594
+ id: "filtered-transaction",
595
+ date: "2024-01-15",
596
+ amount: -1000,
597
+ memo: "Filtered transaction",
598
+ cleared: "cleared",
599
+ approved: true,
600
+ account_id: "account-1",
601
+ category_id: "category-1",
602
+ },
603
+ ],
604
+ },
605
+ });
606
+
607
+ // Test filtering by date
608
+ const dateFilterResult = await executeToolCall(
609
+ server,
610
+ "ynab:list_transactions",
611
+ {
612
+ budget_id: budgetId,
613
+ since_date: "2024-01-01",
614
+ },
615
+ );
616
+ validateToolResult(dateFilterResult);
617
+
618
+ // Also mock account/category specific endpoints
619
+ mockYnabAPI.transactions.getTransactionsByAccount.mockResolvedValue({
620
+ data: {
621
+ transactions: [
622
+ {
623
+ id: "filtered-transaction",
624
+ date: "2024-01-15",
625
+ amount: -1000,
626
+ memo: "Filtered transaction",
627
+ cleared: "cleared",
628
+ approved: true,
629
+ account_id: "account-1",
630
+ category_id: "category-1",
631
+ },
632
+ ],
633
+ },
634
+ });
635
+ mockYnabAPI.transactions.getTransactionsByCategory.mockResolvedValue({
636
+ data: {
637
+ transactions: [
638
+ {
639
+ id: "filtered-transaction",
640
+ date: "2024-01-15",
641
+ amount: -1000,
642
+ memo: "Filtered transaction",
643
+ cleared: "cleared",
644
+ approved: true,
645
+ account_id: "account-1",
646
+ category_id: "category-1",
647
+ },
648
+ ],
649
+ },
650
+ });
651
+
652
+ // Test filtering by account
653
+ const accountFilterResult = await executeToolCall(
654
+ server,
655
+ "ynab:list_transactions",
656
+ {
657
+ budget_id: budgetId,
658
+ account_id: "account-1",
659
+ },
660
+ );
661
+ validateToolResult(accountFilterResult);
662
+
663
+ // Test filtering by category
664
+ const categoryFilterResult = await executeToolCall(
665
+ server,
666
+ "ynab:list_transactions",
667
+ {
668
+ budget_id: budgetId,
669
+ category_id: "category-1",
670
+ },
671
+ );
672
+ validateToolResult(categoryFilterResult);
673
+
674
+ // Verify API calls with different parameters
675
+ expect(mockYnabAPI.transactions.getTransactions).toHaveBeenCalledTimes(
676
+ 1,
677
+ );
678
+ expect(
679
+ mockYnabAPI.transactions.getTransactionsByAccount,
680
+ ).toHaveBeenCalledTimes(1);
681
+ expect(
682
+ mockYnabAPI.transactions.getTransactionsByCategory,
683
+ ).toHaveBeenCalledTimes(1);
684
+ },
685
+ );
686
+ });
687
+
688
+ describe("Complete Category Management Integration", () => {
689
+ it(
690
+ "should handle complete category workflow",
691
+ { meta: { tier: "domain", domain: "workflows" } },
692
+ async () => {
693
+ const budgetId = TEST_BUDGET_UUID;
694
+
695
+ // Mock categories response
696
+ const mockCategories = {
697
+ data: {
698
+ category_groups: [
699
+ {
700
+ id: "group-1",
701
+ name: "Immediate Obligations",
702
+ hidden: false,
703
+ deleted: false,
704
+ categories: [
705
+ {
706
+ id: "category-1",
707
+ category_group_id: "group-1",
708
+ name: "Rent/Mortgage",
709
+ hidden: false,
710
+ budgeted: 150000, // $150.00
711
+ activity: -150000,
712
+ balance: 0,
713
+ // goal_type omitted (undefined, not null)
714
+ deleted: false,
715
+ },
716
+ {
717
+ id: "category-2",
718
+ category_group_id: "group-1",
719
+ name: "Utilities",
720
+ hidden: false,
721
+ budgeted: 10000, // $10.00
722
+ activity: -8500,
723
+ balance: 1500,
724
+ // goal_type omitted (undefined, not null)
725
+ deleted: false,
726
+ },
727
+ ],
728
+ },
729
+ ],
730
+ },
731
+ };
732
+
733
+ mockYnabAPI.categories.getCategories.mockResolvedValue(mockCategories);
734
+
735
+ // Test category listing
736
+ const listResult = await executeToolCall(
737
+ server,
738
+ "ynab:list_categories",
739
+ {
740
+ budget_id: budgetId,
741
+ },
742
+ );
743
+ validateToolResult(listResult);
744
+
745
+ const categories = parseToolResult(listResult);
746
+ expect(categories.data.category_groups).toHaveLength(1);
747
+ expect(categories.data.categories).toHaveLength(2);
748
+ expect(categories.data.categories[0].name).toBe("Rent/Mortgage");
749
+
750
+ // Mock specific category response
751
+ const mockCategory = {
752
+ data: {
753
+ category: mockCategories.data.category_groups[0].categories[0],
754
+ },
755
+ };
756
+
757
+ mockYnabAPI.categories.getCategoryById.mockResolvedValue(mockCategory);
758
+
759
+ // Test specific category retrieval
760
+ const getResult = await executeToolCall(server, "ynab:get_category", {
761
+ budget_id: budgetId,
762
+ category_id: "category-1",
763
+ });
764
+ validateToolResult(getResult);
765
+
766
+ const category = parseToolResult(getResult);
767
+ expect(category.data.category.id).toBe("category-1");
768
+ expect(category.data.category.name).toBe("Rent/Mortgage");
769
+ expect(category.data.category.budgeted).toBe(150);
770
+
771
+ // Mock category update
772
+ const updatedCategory = {
773
+ ...mockCategories.data.category_groups[0].categories[0],
774
+ budgeted: 160000, // $160.00
775
+ };
776
+
777
+ const mockUpdateResponse = {
778
+ data: {
779
+ category: updatedCategory,
780
+ },
781
+ };
782
+
783
+ mockYnabAPI.categories.updateMonthCategory.mockResolvedValue(
784
+ mockUpdateResponse,
785
+ );
786
+
787
+ // Test category budget update
788
+ const updateResult = await executeToolCall(
789
+ server,
790
+ "ynab:update_category",
791
+ {
792
+ budget_id: budgetId,
793
+ category_id: "category-1",
794
+ budgeted: 160000,
795
+ },
796
+ );
797
+ validateToolResult(updateResult);
798
+
799
+ const updated = parseToolResult(updateResult);
800
+ expect(updated.data.category.budgeted).toBe(160);
801
+
802
+ // Verify API calls
803
+ expect(mockYnabAPI.categories.getCategories).toHaveBeenCalledWith(
804
+ budgetId,
805
+ );
806
+ expect(mockYnabAPI.categories.getCategoryById).toHaveBeenCalledWith(
807
+ budgetId,
808
+ "category-1",
809
+ );
810
+ expect(mockYnabAPI.categories.updateMonthCategory).toHaveBeenCalled();
811
+ },
812
+ );
813
+ });
814
+
815
+ describe("Complete Utility Tools Integration", () => {
816
+ it(
817
+ "should handle user information retrieval",
818
+ { meta: { tier: "domain", domain: "workflows" } },
819
+ async () => {
820
+ // Mock user response
821
+ const mockUser = {
822
+ data: {
823
+ user: {
824
+ id: "user-123",
825
+ email: "test@example.com",
826
+ },
827
+ },
828
+ };
829
+
830
+ mockYnabAPI.user.getUser.mockResolvedValue(mockUser);
831
+
832
+ // Test user retrieval
833
+ const userResult = await executeToolCall(server, "ynab:get_user");
834
+ validateToolResult(userResult);
835
+
836
+ const user = parseToolResult(userResult);
837
+ expect(user.data.user.id).toBe("user-123");
838
+
839
+ expect(mockYnabAPI.user.getUser).toHaveBeenCalledTimes(1);
840
+ },
841
+ );
842
+ });
843
+
844
+ describe("Error Handling Integration", () => {
845
+ it(
846
+ "should handle various API error scenarios",
847
+ { meta: { tier: "domain", domain: "workflows" } },
848
+ async () => {
849
+ // Test 401 Unauthorized
850
+ const authError = new Error("Unauthorized");
851
+ (authError as any).error = {
852
+ id: "401",
853
+ name: "unauthorized",
854
+ description: "Unauthorized",
855
+ };
856
+ mockYnabAPI.budgets.getBudgets.mockRejectedValue(authError);
857
+
858
+ try {
859
+ await executeToolCall(server, "ynab:list_budgets");
860
+ expect.fail("Should have thrown an error");
861
+ } catch (error) {
862
+ expect(error).toBeDefined();
863
+ }
864
+
865
+ // Test 404 Not Found
866
+ const notFoundError = new Error("Not Found");
867
+ (notFoundError as any).error = {
868
+ id: "404.2",
869
+ name: "not_found",
870
+ description: "Budget not found",
871
+ };
872
+ mockYnabAPI.budgets.getBudgetById.mockRejectedValue(notFoundError);
873
+
874
+ try {
875
+ await executeToolCall(server, "ynab:get_budget", {
876
+ budget_id: "invalid",
877
+ });
878
+ expect.fail("Should have thrown an error");
879
+ } catch (error) {
880
+ expect(error).toBeDefined();
881
+ }
882
+
883
+ // Test 429 Rate Limit
884
+ const rateLimitError = new Error("Too Many Requests");
885
+ (rateLimitError as any).error = {
886
+ id: "429",
887
+ name: "rate_limit",
888
+ description: "Rate limit exceeded",
889
+ };
890
+ mockYnabAPI.accounts.getAccounts.mockRejectedValue(rateLimitError);
891
+
892
+ try {
893
+ await executeToolCall(server, "ynab:list_accounts", {
894
+ budget_id: "test",
895
+ });
896
+ expect.fail("Should have thrown an error");
897
+ } catch (error) {
898
+ expect(error).toBeDefined();
899
+ }
900
+ },
901
+ );
902
+
903
+ it(
904
+ "should validate input parameters",
905
+ { meta: { tier: "domain", domain: "workflows" } },
906
+ async () => {
907
+ // Test missing required parameters
908
+ try {
909
+ await executeToolCall(server, "ynab:get_budget", {});
910
+ expect.fail("Should have thrown validation error");
911
+ } catch (error) {
912
+ expect(error).toBeDefined();
913
+ }
914
+
915
+ // Test invalid parameter types
916
+ try {
917
+ await executeToolCall(server, "ynab:create_transaction", {
918
+ budget_id: "test",
919
+ account_id: "test",
920
+ amount: "invalid-amount", // Should be number
921
+ date: "2024-01-01",
922
+ });
923
+ expect.fail("Should have thrown validation error");
924
+ } catch (error) {
925
+ expect(error).toBeDefined();
926
+ }
927
+ },
928
+ );
929
+ });
930
+
931
+ describe("Caching Integration Tests", () => {
932
+ let previousNodeEnv: string | undefined;
933
+
934
+ beforeAll(() => {
935
+ previousNodeEnv = process.env.NODE_ENV;
936
+ process.env.NODE_ENV = "development";
937
+ });
938
+
939
+ beforeEach(() => {
940
+ cacheManager.clear();
941
+ process.env.NODE_ENV = "development";
942
+ });
943
+
944
+ afterAll(() => {
945
+ // Restore NODE_ENV after all caching tests complete
946
+ if (previousNodeEnv === undefined) {
947
+ process.env.NODE_ENV = undefined;
948
+ } else {
949
+ process.env.NODE_ENV = previousNodeEnv;
950
+ }
951
+ });
952
+
953
+ // TODO: Re-enable after DeltaFetcher cache integration alignment.
954
+ it.skip(
955
+ "should cache budget list requests and improve performance on subsequent calls",
956
+ { meta: { tier: "domain", domain: "workflows" } },
957
+ async () => {
958
+ const mockBudgets = {
959
+ data: {
960
+ budgets: [
961
+ {
962
+ id: "budget-1",
963
+ name: "Test Budget",
964
+ last_modified_on: "2024-01-01T00:00:00Z",
965
+ first_month: "2024-01-01",
966
+ last_month: "2024-12-01",
967
+ date_format: { format: "MM/DD/YYYY" },
968
+ currency_format: {
969
+ iso_code: "USD",
970
+ example_format: "$123.45",
971
+ decimal_digits: 2,
972
+ decimal_separator: ".",
973
+ symbol_first: true,
974
+ group_separator: ",",
975
+ currency_symbol: "$",
976
+ display_symbol: true,
977
+ },
978
+ },
979
+ ],
980
+ },
981
+ };
982
+
983
+ mockYnabAPI.budgets.getBudgets.mockResolvedValue(mockBudgets);
984
+
985
+ const statsBeforeFirstCall = cacheManager.getStats();
986
+ const initialSize = statsBeforeFirstCall.size;
987
+
988
+ // First call - should hit API and cache result
989
+ const firstResult = await executeToolCall(server, "ynab:list_budgets");
990
+ validateToolResult(firstResult);
991
+
992
+ const firstParsed = parseToolResult(firstResult);
993
+ expect(firstParsed.data.cached).toBe(false);
994
+ expect(firstParsed.data.cache_info).toBe(
995
+ "Fresh data retrieved from YNAB API",
996
+ );
997
+
998
+ // Cache should have grown
999
+ const statsAfterFirstCall = cacheManager.getStats();
1000
+ expect(statsAfterFirstCall.size).toBeGreaterThan(initialSize);
1001
+
1002
+ // Second call - should hit cache
1003
+ const secondResult = await executeToolCall(server, "ynab:list_budgets");
1004
+ validateToolResult(secondResult);
1005
+
1006
+ const secondParsed = parseToolResult(secondResult);
1007
+ expect(secondParsed.data.cached).toBe(true);
1008
+ expect(secondParsed.data.cache_info).toBe(
1009
+ "Data retrieved from cache for improved performance",
1010
+ );
1011
+
1012
+ // API should only have been called once
1013
+ expect(mockYnabAPI.budgets.getBudgets).toHaveBeenCalledTimes(1);
1014
+
1015
+ // Cache hit count should have increased
1016
+ const finalStats = cacheManager.getStats();
1017
+ expect(finalStats.hits).toBeGreaterThan(statsBeforeFirstCall.hits);
1018
+ },
1019
+ );
1020
+
1021
+ it(
1022
+ "should invalidate cache on write operations",
1023
+ { meta: { tier: "domain", domain: "workflows" } },
1024
+ async () => {
1025
+ const budgetId = TEST_BUDGET_UUID;
1026
+
1027
+ // Mock responses
1028
+ const mockAccounts = {
1029
+ data: {
1030
+ accounts: [
1031
+ {
1032
+ id: "account-1",
1033
+ name: "Test Account",
1034
+ type: "checking",
1035
+ on_budget: true,
1036
+ closed: false,
1037
+ balance: 100000,
1038
+ cleared_balance: 95000,
1039
+ uncleared_balance: 5000,
1040
+ },
1041
+ ],
1042
+ },
1043
+ };
1044
+
1045
+ const mockCreatedAccount = {
1046
+ data: {
1047
+ account: {
1048
+ id: "account-2",
1049
+ name: "New Account",
1050
+ type: "savings",
1051
+ on_budget: true,
1052
+ closed: false,
1053
+ balance: 0,
1054
+ cleared_balance: 0,
1055
+ uncleared_balance: 0,
1056
+ },
1057
+ },
1058
+ };
1059
+
1060
+ mockYnabAPI.accounts.getAccounts.mockResolvedValue(mockAccounts);
1061
+ mockYnabAPI.accounts.createAccount.mockResolvedValue(
1062
+ mockCreatedAccount,
1063
+ );
1064
+
1065
+ // First, populate cache with account list
1066
+ await executeToolCall(server, "ynab:list_accounts", {
1067
+ budget_id: budgetId,
1068
+ });
1069
+
1070
+ // Verify cache has entries
1071
+ const statsAfterRead = cacheManager.getStats();
1072
+ expect(statsAfterRead.size).toBeGreaterThan(0);
1073
+
1074
+ // Create a new account (write operation)
1075
+ await executeToolCall(server, "ynab:create_account", {
1076
+ budget_id: budgetId,
1077
+ name: "New Account",
1078
+ type: "savings",
1079
+ });
1080
+
1081
+ // Next call to list accounts should hit API again (cache was invalidated)
1082
+ mockYnabAPI.accounts.getAccounts.mockClear();
1083
+ await executeToolCall(server, "ynab:list_accounts", {
1084
+ budget_id: budgetId,
1085
+ });
1086
+
1087
+ // Verify API was called again after cache invalidation
1088
+ expect(mockYnabAPI.accounts.getAccounts).toHaveBeenCalledTimes(1);
1089
+ },
1090
+ );
1091
+
1092
+ // TODO: Re-enable after DeltaFetcher cache integration alignment.
1093
+ it.skip(
1094
+ "should not cache filtered transaction requests",
1095
+ { meta: { tier: "domain", domain: "workflows" } },
1096
+ async () => {
1097
+ const budgetId = TEST_BUDGET_UUID;
1098
+
1099
+ const mockTransactions = {
1100
+ data: {
1101
+ transactions: [
1102
+ {
1103
+ id: "transaction-1",
1104
+ date: "2024-01-15",
1105
+ amount: -5000,
1106
+ memo: "Test transaction",
1107
+ cleared: "cleared",
1108
+ approved: true,
1109
+ account_id: "account-1",
1110
+ category_id: "category-1",
1111
+ },
1112
+ ],
1113
+ },
1114
+ };
1115
+
1116
+ mockYnabAPI.transactions.getTransactions.mockResolvedValue(
1117
+ mockTransactions,
1118
+ );
1119
+ mockYnabAPI.transactions.getTransactionsByAccount.mockResolvedValue(
1120
+ mockTransactions,
1121
+ );
1122
+
1123
+ const statsBeforeUnfiltered = cacheManager.getStats();
1124
+
1125
+ // Unfiltered request - should be cached
1126
+ const unfilteredResult = await executeToolCall(
1127
+ server,
1128
+ "ynab:list_transactions",
1129
+ {
1130
+ budget_id: budgetId,
1131
+ },
1132
+ );
1133
+ const unfilteredParsed = parseToolResult(unfilteredResult);
1134
+ expect(unfilteredParsed.data.cached).toBe(false); // First call, cache miss
1135
+
1136
+ const statsAfterUnfiltered = cacheManager.getStats();
1137
+ expect(statsAfterUnfiltered.size).toBeGreaterThan(
1138
+ statsBeforeUnfiltered.size,
1139
+ );
1140
+
1141
+ // Filtered request - should NOT be cached
1142
+ const filteredResult = await executeToolCall(
1143
+ server,
1144
+ "ynab:list_transactions",
1145
+ {
1146
+ budget_id: budgetId,
1147
+ account_id: "account-1",
1148
+ },
1149
+ );
1150
+ const filteredParsed = parseToolResult(filteredResult);
1151
+ expect(filteredParsed.data.cached).toBe(false);
1152
+ expect(filteredParsed.data.cache_info).toBe(
1153
+ "Fresh data retrieved from YNAB API",
1154
+ );
1155
+
1156
+ // Cache size should not have increased for filtered request
1157
+ const statsAfterFiltered = cacheManager.getStats();
1158
+ expect(statsAfterFiltered.size).toBe(statsAfterUnfiltered.size);
1159
+
1160
+ // Both API methods should have been called
1161
+ expect(mockYnabAPI.transactions.getTransactions).toHaveBeenCalledTimes(
1162
+ 1,
1163
+ );
1164
+ expect(
1165
+ mockYnabAPI.transactions.getTransactionsByAccount,
1166
+ ).toHaveBeenCalledTimes(1);
1167
+ },
1168
+ );
1169
+
1170
+ it(
1171
+ "should handle cache warming after setting default budget",
1172
+ { meta: { tier: "domain", domain: "workflows" } },
1173
+ async () => {
1174
+ const budgetId = TEST_BUDGET_UUID;
1175
+
1176
+ // Mock all the responses for cache warming
1177
+ mockYnabAPI.accounts.getAccounts.mockResolvedValue({
1178
+ data: { accounts: [] },
1179
+ });
1180
+ mockYnabAPI.budgets.getBudgetById.mockResolvedValue({
1181
+ data: { budget: { id: budgetId, name: "Warm Cache Budget" } },
1182
+ });
1183
+ mockYnabAPI.categories.getCategories.mockResolvedValue({
1184
+ data: { category_groups: [] },
1185
+ });
1186
+ mockYnabAPI.payees.getPayees.mockResolvedValue({
1187
+ data: { payees: [] },
1188
+ });
1189
+
1190
+ const statsBeforeSet = cacheManager.getStats();
1191
+ const initialSize = statsBeforeSet.size;
1192
+
1193
+ // Set default budget (should trigger cache warming)
1194
+ await executeToolCall(server, "ynab:set_default_budget", {
1195
+ budget_id: budgetId,
1196
+ });
1197
+
1198
+ // Wait for cache warming to populate entries (fire-and-forget process)
1199
+ let statsAfterSet = cacheManager.getStats();
1200
+ await waitFor(
1201
+ () => {
1202
+ statsAfterSet = cacheManager.getStats();
1203
+ return statsAfterSet.size > initialSize;
1204
+ },
1205
+ 1000,
1206
+ 50,
1207
+ );
1208
+
1209
+ // Cache should have more entries due to warming
1210
+ expect(statsAfterSet.size).toBeGreaterThan(initialSize);
1211
+
1212
+ // Verify that cache warming API calls were made
1213
+ expect(mockYnabAPI.accounts.getAccounts).toHaveBeenCalled();
1214
+ expect(mockYnabAPI.categories.getCategories).toHaveBeenCalled();
1215
+ expect(mockYnabAPI.payees.getPayees).toHaveBeenCalled();
1216
+ },
1217
+ );
1218
+
1219
+ it(
1220
+ "should handle cache clear operation",
1221
+ { meta: { tier: "domain", domain: "workflows" } },
1222
+ async () => {
1223
+ // Populate cache with some data
1224
+ mockYnabAPI.budgets.getBudgets.mockResolvedValue({
1225
+ data: { budgets: [] },
1226
+ });
1227
+
1228
+ await executeToolCall(server, "ynab:list_budgets");
1229
+
1230
+ // Verify cache has entries
1231
+ const statsAfterPopulation = cacheManager.getStats();
1232
+ expect(statsAfterPopulation.size).toBeGreaterThan(0);
1233
+
1234
+ // Clear cache
1235
+ await executeToolCall(server, "ynab:clear_cache");
1236
+
1237
+ // Verify cache is empty
1238
+ const statsAfterClear = cacheManager.getStats();
1239
+ expect(statsAfterClear.size).toBe(0);
1240
+ expect(statsAfterClear.hits).toBe(0);
1241
+ expect(statsAfterClear.misses).toBe(0);
1242
+ },
1243
+ );
1244
+
1245
+ // TODO: Re-enable after DeltaFetcher cache integration alignment.
1246
+ it.skip(
1247
+ "should respect cache TTL and return fresh data after expiration",
1248
+ { meta: { tier: "domain", domain: "workflows" } },
1249
+ async () => {
1250
+ // Note: This test is conceptual since TTL testing requires time manipulation
1251
+ // In a real scenario, we would mock the Date.now() or use a test clock
1252
+
1253
+ const mockBudgets = {
1254
+ data: {
1255
+ budgets: [
1256
+ {
1257
+ id: "budget-1",
1258
+ name: "Test Budget",
1259
+ last_modified_on: "2024-01-01T00:00:00Z",
1260
+ first_month: "2024-01-01",
1261
+ last_month: "2024-12-01",
1262
+ date_format: { format: "MM/DD/YYYY" },
1263
+ currency_format: {
1264
+ iso_code: "USD",
1265
+ example_format: "$123.45",
1266
+ decimal_digits: 2,
1267
+ decimal_separator: ".",
1268
+ symbol_first: true,
1269
+ group_separator: ",",
1270
+ currency_symbol: "$",
1271
+ display_symbol: true,
1272
+ },
1273
+ },
1274
+ ],
1275
+ },
1276
+ };
1277
+
1278
+ mockYnabAPI.budgets.getBudgets.mockResolvedValue(mockBudgets);
1279
+
1280
+ // First call - cache miss
1281
+ const firstResult = await executeToolCall(server, "ynab:list_budgets");
1282
+ const firstParsed = parseToolResult(firstResult);
1283
+ expect(firstParsed.data.cached).toBe(false);
1284
+
1285
+ // Second call - cache hit
1286
+ const secondResult = await executeToolCall(server, "ynab:list_budgets");
1287
+ const secondParsed = parseToolResult(secondResult);
1288
+ expect(secondParsed.data.cached).toBe(true);
1289
+
1290
+ // Verify API was only called once (second call used cache)
1291
+ expect(mockYnabAPI.budgets.getBudgets).toHaveBeenCalledTimes(1);
1292
+ },
1293
+ );
1294
+ });
1168
1295
  });