@dizzlkheinz/ynab-mcpb 0.18.4 → 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 (343) hide show
  1. package/CLAUDE.md +87 -8
  2. package/bin/ynab-mcp-server.cjs +2 -2
  3. package/bin/ynab-mcp-server.js +3 -3
  4. package/biome.json +39 -0
  5. package/dist/bundle/index.cjs +67 -67
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +27 -27
  8. package/dist/server/YNABMCPServer.d.ts +3 -4
  9. package/dist/server/YNABMCPServer.js +111 -116
  10. package/dist/server/budgetResolver.d.ts +6 -5
  11. package/dist/server/budgetResolver.js +46 -36
  12. package/dist/server/cacheKeys.js +6 -6
  13. package/dist/server/cacheManager.js +14 -11
  14. package/dist/server/completions.d.ts +2 -2
  15. package/dist/server/completions.js +20 -15
  16. package/dist/server/config.d.ts +10 -5
  17. package/dist/server/config.js +24 -7
  18. package/dist/server/deltaCache.d.ts +2 -2
  19. package/dist/server/deltaCache.js +22 -16
  20. package/dist/server/deltaCache.merge.d.ts +2 -2
  21. package/dist/server/diagnostics.d.ts +4 -4
  22. package/dist/server/diagnostics.js +38 -32
  23. package/dist/server/errorHandler.d.ts +5 -12
  24. package/dist/server/errorHandler.js +219 -217
  25. package/dist/server/prompts.d.ts +2 -2
  26. package/dist/server/prompts.js +45 -45
  27. package/dist/server/rateLimiter.js +4 -4
  28. package/dist/server/requestLogger.d.ts +1 -1
  29. package/dist/server/requestLogger.js +40 -35
  30. package/dist/server/resources.d.ts +3 -3
  31. package/dist/server/resources.js +55 -52
  32. package/dist/server/responseFormatter.js +6 -6
  33. package/dist/server/securityMiddleware.d.ts +2 -2
  34. package/dist/server/securityMiddleware.js +22 -20
  35. package/dist/server/serverKnowledgeStore.js +1 -1
  36. package/dist/server/toolRegistry.d.ts +3 -3
  37. package/dist/server/toolRegistry.js +47 -40
  38. package/dist/tools/__tests__/deltaTestUtils.d.ts +3 -3
  39. package/dist/tools/__tests__/deltaTestUtils.js +2 -2
  40. package/dist/tools/accountTools.d.ts +9 -8
  41. package/dist/tools/accountTools.js +47 -47
  42. package/dist/tools/adapters.d.ts +13 -8
  43. package/dist/tools/adapters.js +21 -11
  44. package/dist/tools/budgetTools.d.ts +8 -7
  45. package/dist/tools/budgetTools.js +22 -22
  46. package/dist/tools/categoryTools.d.ts +9 -8
  47. package/dist/tools/categoryTools.js +68 -59
  48. package/dist/tools/compareTransactions/formatter.d.ts +3 -3
  49. package/dist/tools/compareTransactions/formatter.js +9 -9
  50. package/dist/tools/compareTransactions/index.d.ts +6 -6
  51. package/dist/tools/compareTransactions/index.js +58 -43
  52. package/dist/tools/compareTransactions/matcher.d.ts +1 -1
  53. package/dist/tools/compareTransactions/matcher.js +28 -15
  54. package/dist/tools/compareTransactions/parser.d.ts +2 -2
  55. package/dist/tools/compareTransactions/parser.js +144 -138
  56. package/dist/tools/compareTransactions/types.d.ts +4 -4
  57. package/dist/tools/compareTransactions.d.ts +1 -1
  58. package/dist/tools/compareTransactions.js +1 -1
  59. package/dist/tools/deltaFetcher.d.ts +2 -2
  60. package/dist/tools/deltaFetcher.js +16 -15
  61. package/dist/tools/deltaSupport.d.ts +4 -4
  62. package/dist/tools/deltaSupport.js +35 -41
  63. package/dist/tools/exportTransactions.d.ts +5 -4
  64. package/dist/tools/exportTransactions.js +61 -59
  65. package/dist/tools/monthTools.d.ts +7 -6
  66. package/dist/tools/monthTools.js +31 -29
  67. package/dist/tools/payeeTools.d.ts +7 -6
  68. package/dist/tools/payeeTools.js +28 -28
  69. package/dist/tools/reconcileAdapter.d.ts +2 -2
  70. package/dist/tools/reconcileAdapter.js +19 -12
  71. package/dist/tools/reconciliation/analyzer.d.ts +4 -4
  72. package/dist/tools/reconciliation/analyzer.js +73 -59
  73. package/dist/tools/reconciliation/csvParser.d.ts +3 -3
  74. package/dist/tools/reconciliation/csvParser.js +128 -104
  75. package/dist/tools/reconciliation/executor.d.ts +4 -4
  76. package/dist/tools/reconciliation/executor.js +148 -109
  77. package/dist/tools/reconciliation/index.d.ts +10 -10
  78. package/dist/tools/reconciliation/index.js +96 -83
  79. package/dist/tools/reconciliation/matcher.d.ts +3 -3
  80. package/dist/tools/reconciliation/matcher.js +17 -16
  81. package/dist/tools/reconciliation/payeeNormalizer.js +19 -8
  82. package/dist/tools/reconciliation/recommendationEngine.d.ts +1 -1
  83. package/dist/tools/reconciliation/recommendationEngine.js +40 -40
  84. package/dist/tools/reconciliation/reportFormatter.d.ts +2 -2
  85. package/dist/tools/reconciliation/reportFormatter.js +59 -58
  86. package/dist/tools/reconciliation/signDetector.d.ts +1 -1
  87. package/dist/tools/reconciliation/types.d.ts +16 -16
  88. package/dist/tools/reconciliation/ynabAdapter.d.ts +2 -2
  89. package/dist/tools/schemas/common.d.ts +1 -1
  90. package/dist/tools/schemas/common.js +1 -1
  91. package/dist/tools/schemas/outputs/accountOutputs.d.ts +1 -1
  92. package/dist/tools/schemas/outputs/accountOutputs.js +24 -18
  93. package/dist/tools/schemas/outputs/budgetOutputs.d.ts +1 -1
  94. package/dist/tools/schemas/outputs/budgetOutputs.js +14 -11
  95. package/dist/tools/schemas/outputs/categoryOutputs.d.ts +1 -1
  96. package/dist/tools/schemas/outputs/categoryOutputs.js +49 -29
  97. package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +1 -1
  98. package/dist/tools/schemas/outputs/comparisonOutputs.js +12 -12
  99. package/dist/tools/schemas/outputs/index.d.ts +14 -14
  100. package/dist/tools/schemas/outputs/index.js +14 -14
  101. package/dist/tools/schemas/outputs/monthOutputs.d.ts +1 -1
  102. package/dist/tools/schemas/outputs/monthOutputs.js +56 -41
  103. package/dist/tools/schemas/outputs/payeeOutputs.d.ts +1 -1
  104. package/dist/tools/schemas/outputs/payeeOutputs.js +10 -10
  105. package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +2 -2
  106. package/dist/tools/schemas/outputs/reconciliationOutputs.js +45 -45
  107. package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +1 -1
  108. package/dist/tools/schemas/outputs/transactionMutationOutputs.js +28 -22
  109. package/dist/tools/schemas/outputs/transactionOutputs.d.ts +1 -1
  110. package/dist/tools/schemas/outputs/transactionOutputs.js +43 -35
  111. package/dist/tools/schemas/outputs/utilityOutputs.d.ts +1 -1
  112. package/dist/tools/schemas/outputs/utilityOutputs.js +5 -3
  113. package/dist/tools/schemas/shared/commonOutputs.d.ts +1 -1
  114. package/dist/tools/schemas/shared/commonOutputs.js +15 -9
  115. package/dist/tools/transactionReadTools.d.ts +11 -0
  116. package/dist/tools/transactionReadTools.js +202 -0
  117. package/dist/tools/transactionSchemas.d.ts +7 -7
  118. package/dist/tools/transactionSchemas.js +77 -57
  119. package/dist/tools/transactionTools.d.ts +6 -24
  120. package/dist/tools/transactionTools.js +7 -1499
  121. package/dist/tools/transactionUtils.d.ts +6 -6
  122. package/dist/tools/transactionUtils.js +78 -63
  123. package/dist/tools/transactionWriteTools.d.ts +20 -0
  124. package/dist/tools/transactionWriteTools.js +1342 -0
  125. package/dist/tools/utilityTools.d.ts +5 -4
  126. package/dist/tools/utilityTools.js +11 -11
  127. package/dist/types/index.d.ts +7 -7
  128. package/dist/types/index.js +6 -6
  129. package/dist/types/reconciliation.d.ts +1 -1
  130. package/dist/types/toolRegistration.d.ts +14 -12
  131. package/dist/utils/amountUtils.js +1 -1
  132. package/dist/utils/dateUtils.js +4 -4
  133. package/dist/utils/errors.d.ts +3 -3
  134. package/dist/utils/errors.js +4 -4
  135. package/dist/utils/money.d.ts +2 -2
  136. package/dist/utils/money.js +8 -8
  137. package/dist/utils/validationError.d.ts +1 -1
  138. package/dist/utils/validationError.js +1 -1
  139. package/docs/assets/examples/reconciliation-with-recommendations.json +66 -66
  140. package/docs/assets/schemas/reconciliation-v2.json +360 -336
  141. package/esbuild.config.mjs +53 -50
  142. package/meta.json +12548 -12548
  143. package/package.json +98 -111
  144. package/scripts/analyze-bundle.mjs +33 -30
  145. package/scripts/create-pr-description.js +169 -120
  146. package/scripts/run-all-tests.js +178 -169
  147. package/scripts/run-domain-integration-tests.js +28 -18
  148. package/scripts/run-generate-mcpb.js +19 -17
  149. package/scripts/run-throttled-integration-tests.js +92 -83
  150. package/scripts/test-delta-params.mjs +149 -120
  151. package/scripts/test-recommendations.ts +36 -32
  152. package/scripts/tmpTransaction.ts +80 -43
  153. package/scripts/validate-env.js +98 -91
  154. package/scripts/verify-build.js +78 -76
  155. package/src/__tests__/comprehensive.integration.test.ts +1281 -1154
  156. package/src/__tests__/performance.test.ts +723 -671
  157. package/src/__tests__/setup.ts +442 -395
  158. package/src/__tests__/smoke.e2e.test.ts +41 -39
  159. package/src/__tests__/testRunner.ts +314 -295
  160. package/src/__tests__/testUtils.ts +456 -364
  161. package/src/__tests__/tools/reconciliation/csvParser.integration.test.ts +109 -107
  162. package/src/__tests__/tools/reconciliation/real-world.integration.test.ts +41 -41
  163. package/src/index.ts +68 -59
  164. package/src/server/CLAUDE.md +480 -0
  165. package/src/server/YNABMCPServer.ts +821 -794
  166. package/src/server/__tests__/YNABMCPServer.integration.test.ts +929 -893
  167. package/src/server/__tests__/YNABMCPServer.test.ts +903 -899
  168. package/src/server/__tests__/budgetResolver.test.ts +466 -423
  169. package/src/server/__tests__/cacheManager.test.ts +891 -874
  170. package/src/server/__tests__/completions.integration.test.ts +115 -106
  171. package/src/server/__tests__/completions.test.ts +334 -313
  172. package/src/server/__tests__/config.test.ts +98 -86
  173. package/src/server/__tests__/deltaCache.merge.test.ts +774 -703
  174. package/src/server/__tests__/deltaCache.swr.test.ts +198 -153
  175. package/src/server/__tests__/deltaCache.test.ts +946 -759
  176. package/src/server/__tests__/diagnostics.test.ts +825 -792
  177. package/src/server/__tests__/errorHandler.integration.test.ts +512 -462
  178. package/src/server/__tests__/errorHandler.test.ts +402 -397
  179. package/src/server/__tests__/prompts.test.ts +424 -347
  180. package/src/server/__tests__/rateLimiter.test.ts +313 -309
  181. package/src/server/__tests__/requestLogger.test.ts +443 -403
  182. package/src/server/__tests__/resources.template.test.ts +196 -185
  183. package/src/server/__tests__/resources.test.ts +294 -288
  184. package/src/server/__tests__/security.integration.test.ts +487 -421
  185. package/src/server/__tests__/securityMiddleware.test.ts +519 -444
  186. package/src/server/__tests__/server-startup.integration.test.ts +509 -490
  187. package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -173
  188. package/src/server/__tests__/toolRegistration.test.ts +239 -210
  189. package/src/server/__tests__/toolRegistry.test.ts +907 -845
  190. package/src/server/budgetResolver.ts +221 -181
  191. package/src/server/cacheKeys.ts +6 -6
  192. package/src/server/cacheManager.ts +498 -484
  193. package/src/server/completions.ts +267 -243
  194. package/src/server/config.ts +35 -14
  195. package/src/server/deltaCache.merge.ts +146 -128
  196. package/src/server/deltaCache.ts +352 -309
  197. package/src/server/diagnostics.ts +257 -242
  198. package/src/server/errorHandler.ts +747 -744
  199. package/src/server/prompts.ts +181 -176
  200. package/src/server/rateLimiter.ts +131 -129
  201. package/src/server/requestLogger.ts +350 -322
  202. package/src/server/resources.ts +442 -374
  203. package/src/server/responseFormatter.ts +41 -37
  204. package/src/server/securityMiddleware.ts +223 -205
  205. package/src/server/serverKnowledgeStore.ts +67 -67
  206. package/src/server/toolRegistry.ts +508 -474
  207. package/src/tools/CLAUDE.md +604 -0
  208. package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -111
  209. package/src/tools/__tests__/accountTools.integration.test.ts +129 -111
  210. package/src/tools/__tests__/accountTools.test.ts +685 -638
  211. package/src/tools/__tests__/adapters.test.ts +142 -108
  212. package/src/tools/__tests__/budgetTools.delta.integration.test.ts +73 -73
  213. package/src/tools/__tests__/budgetTools.integration.test.ts +132 -124
  214. package/src/tools/__tests__/budgetTools.test.ts +442 -413
  215. package/src/tools/__tests__/categoryTools.delta.integration.test.ts +76 -68
  216. package/src/tools/__tests__/categoryTools.integration.test.ts +314 -288
  217. package/src/tools/__tests__/categoryTools.test.ts +656 -625
  218. package/src/tools/__tests__/compareTransactions/formatter.test.ts +535 -462
  219. package/src/tools/__tests__/compareTransactions/index.test.ts +378 -358
  220. package/src/tools/__tests__/compareTransactions/matcher.test.ts +497 -398
  221. package/src/tools/__tests__/compareTransactions/parser.test.ts +765 -747
  222. package/src/tools/__tests__/compareTransactions.test.ts +352 -332
  223. package/src/tools/__tests__/compareTransactions.window.test.ts +150 -146
  224. package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +69 -65
  225. package/src/tools/__tests__/deltaFetcher.test.ts +325 -265
  226. package/src/tools/__tests__/deltaSupport.test.ts +211 -184
  227. package/src/tools/__tests__/deltaTestUtils.ts +37 -33
  228. package/src/tools/__tests__/exportTransactions.test.ts +205 -200
  229. package/src/tools/__tests__/monthTools.delta.integration.test.ts +68 -68
  230. package/src/tools/__tests__/monthTools.integration.test.ts +178 -166
  231. package/src/tools/__tests__/monthTools.test.ts +561 -512
  232. package/src/tools/__tests__/payeeTools.delta.integration.test.ts +68 -68
  233. package/src/tools/__tests__/payeeTools.integration.test.ts +158 -142
  234. package/src/tools/__tests__/payeeTools.test.ts +486 -434
  235. package/src/tools/__tests__/transactionSchemas.test.ts +1202 -1186
  236. package/src/tools/__tests__/transactionTools.integration.test.ts +875 -825
  237. package/src/tools/__tests__/transactionTools.test.ts +4923 -4366
  238. package/src/tools/__tests__/transactionUtils.test.ts +1004 -977
  239. package/src/tools/__tests__/utilityTools.integration.test.ts +32 -32
  240. package/src/tools/__tests__/utilityTools.test.ts +68 -58
  241. package/src/tools/accountTools.ts +293 -271
  242. package/src/tools/adapters.ts +120 -63
  243. package/src/tools/budgetTools.ts +121 -116
  244. package/src/tools/categoryTools.ts +379 -339
  245. package/src/tools/compareTransactions/formatter.ts +131 -119
  246. package/src/tools/compareTransactions/index.ts +249 -214
  247. package/src/tools/compareTransactions/matcher.ts +259 -209
  248. package/src/tools/compareTransactions/parser.ts +517 -487
  249. package/src/tools/compareTransactions/types.ts +38 -38
  250. package/src/tools/compareTransactions.ts +1 -1
  251. package/src/tools/deltaFetcher.ts +281 -260
  252. package/src/tools/deltaSupport.ts +264 -259
  253. package/src/tools/exportTransactions.ts +230 -218
  254. package/src/tools/monthTools.ts +180 -165
  255. package/src/tools/payeeTools.ts +152 -140
  256. package/src/tools/reconcileAdapter.ts +297 -252
  257. package/src/tools/reconciliation/CLAUDE.md +506 -0
  258. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +133 -124
  259. package/src/tools/reconciliation/__tests__/adapter.test.ts +249 -230
  260. package/src/tools/reconciliation/__tests__/analyzer.test.ts +408 -400
  261. package/src/tools/reconciliation/__tests__/csvParser.test.ts +71 -69
  262. package/src/tools/reconciliation/__tests__/executor.integration.test.ts +348 -323
  263. package/src/tools/reconciliation/__tests__/executor.progress.test.ts +503 -457
  264. package/src/tools/reconciliation/__tests__/executor.test.ts +898 -831
  265. package/src/tools/reconciliation/__tests__/matcher.test.ts +667 -663
  266. package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +296 -276
  267. package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +692 -624
  268. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1008 -989
  269. package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +187 -146
  270. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +583 -533
  271. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +75 -74
  272. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +70 -62
  273. package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +102 -88
  274. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +56 -55
  275. package/src/tools/reconciliation/__tests__/signDetector.test.ts +209 -206
  276. package/src/tools/reconciliation/__tests__/ynabAdapter.test.ts +66 -60
  277. package/src/tools/reconciliation/analyzer.ts +564 -504
  278. package/src/tools/reconciliation/csvParser.ts +656 -609
  279. package/src/tools/reconciliation/executor.ts +1290 -1128
  280. package/src/tools/reconciliation/index.ts +580 -528
  281. package/src/tools/reconciliation/matcher.ts +256 -240
  282. package/src/tools/reconciliation/payeeNormalizer.ts +92 -78
  283. package/src/tools/reconciliation/recommendationEngine.ts +357 -345
  284. package/src/tools/reconciliation/reportFormatter.ts +343 -307
  285. package/src/tools/reconciliation/signDetector.ts +89 -83
  286. package/src/tools/reconciliation/types.ts +164 -159
  287. package/src/tools/reconciliation/ynabAdapter.ts +17 -15
  288. package/src/tools/schemas/CLAUDE.md +546 -0
  289. package/src/tools/schemas/common.ts +1 -1
  290. package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +410 -409
  291. package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +305 -299
  292. package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +431 -430
  293. package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +510 -495
  294. package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +179 -153
  295. package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +293 -254
  296. package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +457 -457
  297. package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +362 -356
  298. package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +402 -399
  299. package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +225 -211
  300. package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +457 -454
  301. package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +316 -315
  302. package/src/tools/schemas/outputs/accountOutputs.ts +40 -34
  303. package/src/tools/schemas/outputs/budgetOutputs.ts +24 -19
  304. package/src/tools/schemas/outputs/categoryOutputs.ts +76 -56
  305. package/src/tools/schemas/outputs/comparisonOutputs.ts +192 -169
  306. package/src/tools/schemas/outputs/index.ts +163 -163
  307. package/src/tools/schemas/outputs/monthOutputs.ts +95 -80
  308. package/src/tools/schemas/outputs/payeeOutputs.ts +18 -18
  309. package/src/tools/schemas/outputs/reconciliationOutputs.ts +386 -373
  310. package/src/tools/schemas/outputs/transactionMutationOutputs.ts +259 -231
  311. package/src/tools/schemas/outputs/transactionOutputs.ts +81 -71
  312. package/src/tools/schemas/outputs/utilityOutputs.ts +90 -84
  313. package/src/tools/schemas/shared/commonOutputs.ts +27 -19
  314. package/src/tools/toolCategories.ts +114 -114
  315. package/src/tools/transactionReadTools.ts +327 -0
  316. package/src/tools/transactionSchemas.ts +322 -291
  317. package/src/tools/transactionTools.ts +84 -2246
  318. package/src/tools/transactionUtils.ts +507 -422
  319. package/src/tools/transactionWriteTools.ts +2110 -0
  320. package/src/tools/utilityTools.ts +46 -41
  321. package/src/types/CLAUDE.md +477 -0
  322. package/src/types/__tests__/index.test.ts +51 -51
  323. package/src/types/index.ts +43 -39
  324. package/src/types/integration-tests.d.ts +26 -26
  325. package/src/types/reconciliation.ts +29 -29
  326. package/src/types/toolAnnotations.ts +30 -30
  327. package/src/types/toolRegistration.ts +43 -32
  328. package/src/utils/CLAUDE.md +508 -0
  329. package/src/utils/__tests__/dateUtils.test.ts +174 -168
  330. package/src/utils/__tests__/money.test.ts +193 -187
  331. package/src/utils/amountUtils.ts +5 -5
  332. package/src/utils/baseError.ts +5 -5
  333. package/src/utils/dateUtils.ts +29 -26
  334. package/src/utils/errors.ts +14 -14
  335. package/src/utils/money.ts +66 -52
  336. package/src/utils/validationError.ts +1 -1
  337. package/tsconfig.json +29 -29
  338. package/tsconfig.prod.json +16 -16
  339. package/vitest-reporters/split-json-reporter.ts +247 -204
  340. package/vitest.config.ts +99 -95
  341. package/.prettierignore +0 -10
  342. package/.prettierrc.json +0 -10
  343. 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
  });