@dizzlkheinz/ynab-mcpb 0.18.3 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (346) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/CLAUDE.md +87 -8
  3. package/bin/ynab-mcp-server.cjs +2 -2
  4. package/bin/ynab-mcp-server.js +3 -3
  5. package/biome.json +39 -0
  6. package/dist/bundle/index.cjs +67 -67
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +27 -27
  9. package/dist/server/YNABMCPServer.d.ts +3 -4
  10. package/dist/server/YNABMCPServer.js +111 -116
  11. package/dist/server/budgetResolver.d.ts +6 -5
  12. package/dist/server/budgetResolver.js +46 -36
  13. package/dist/server/cacheKeys.js +6 -6
  14. package/dist/server/cacheManager.js +14 -11
  15. package/dist/server/completions.d.ts +2 -2
  16. package/dist/server/completions.js +20 -15
  17. package/dist/server/config.d.ts +10 -5
  18. package/dist/server/config.js +24 -7
  19. package/dist/server/deltaCache.d.ts +2 -2
  20. package/dist/server/deltaCache.js +22 -16
  21. package/dist/server/deltaCache.merge.d.ts +2 -2
  22. package/dist/server/diagnostics.d.ts +4 -4
  23. package/dist/server/diagnostics.js +38 -32
  24. package/dist/server/errorHandler.d.ts +5 -12
  25. package/dist/server/errorHandler.js +219 -217
  26. package/dist/server/prompts.d.ts +2 -2
  27. package/dist/server/prompts.js +45 -45
  28. package/dist/server/rateLimiter.js +4 -4
  29. package/dist/server/requestLogger.d.ts +1 -1
  30. package/dist/server/requestLogger.js +40 -35
  31. package/dist/server/resources.d.ts +3 -3
  32. package/dist/server/resources.js +55 -52
  33. package/dist/server/responseFormatter.js +6 -6
  34. package/dist/server/securityMiddleware.d.ts +2 -2
  35. package/dist/server/securityMiddleware.js +22 -20
  36. package/dist/server/serverKnowledgeStore.js +1 -1
  37. package/dist/server/toolRegistry.d.ts +3 -3
  38. package/dist/server/toolRegistry.js +47 -40
  39. package/dist/tools/__tests__/deltaTestUtils.d.ts +3 -3
  40. package/dist/tools/__tests__/deltaTestUtils.js +2 -2
  41. package/dist/tools/accountTools.d.ts +9 -8
  42. package/dist/tools/accountTools.js +47 -47
  43. package/dist/tools/adapters.d.ts +13 -8
  44. package/dist/tools/adapters.js +21 -11
  45. package/dist/tools/budgetTools.d.ts +8 -7
  46. package/dist/tools/budgetTools.js +22 -22
  47. package/dist/tools/categoryTools.d.ts +9 -8
  48. package/dist/tools/categoryTools.js +68 -59
  49. package/dist/tools/compareTransactions/formatter.d.ts +3 -3
  50. package/dist/tools/compareTransactions/formatter.js +9 -9
  51. package/dist/tools/compareTransactions/index.d.ts +6 -6
  52. package/dist/tools/compareTransactions/index.js +58 -43
  53. package/dist/tools/compareTransactions/matcher.d.ts +1 -1
  54. package/dist/tools/compareTransactions/matcher.js +28 -15
  55. package/dist/tools/compareTransactions/parser.d.ts +2 -2
  56. package/dist/tools/compareTransactions/parser.js +144 -138
  57. package/dist/tools/compareTransactions/types.d.ts +4 -4
  58. package/dist/tools/compareTransactions.d.ts +1 -1
  59. package/dist/tools/compareTransactions.js +1 -1
  60. package/dist/tools/deltaFetcher.d.ts +2 -2
  61. package/dist/tools/deltaFetcher.js +16 -15
  62. package/dist/tools/deltaSupport.d.ts +4 -4
  63. package/dist/tools/deltaSupport.js +35 -41
  64. package/dist/tools/exportTransactions.d.ts +5 -4
  65. package/dist/tools/exportTransactions.js +61 -59
  66. package/dist/tools/monthTools.d.ts +7 -6
  67. package/dist/tools/monthTools.js +31 -29
  68. package/dist/tools/payeeTools.d.ts +7 -6
  69. package/dist/tools/payeeTools.js +28 -28
  70. package/dist/tools/reconcileAdapter.d.ts +2 -2
  71. package/dist/tools/reconcileAdapter.js +21 -11
  72. package/dist/tools/reconciliation/analyzer.d.ts +4 -4
  73. package/dist/tools/reconciliation/analyzer.js +136 -57
  74. package/dist/tools/reconciliation/csvParser.d.ts +3 -3
  75. package/dist/tools/reconciliation/csvParser.js +128 -104
  76. package/dist/tools/reconciliation/executor.d.ts +4 -4
  77. package/dist/tools/reconciliation/executor.js +148 -109
  78. package/dist/tools/reconciliation/index.d.ts +10 -10
  79. package/dist/tools/reconciliation/index.js +96 -83
  80. package/dist/tools/reconciliation/matcher.d.ts +3 -3
  81. package/dist/tools/reconciliation/matcher.js +17 -16
  82. package/dist/tools/reconciliation/payeeNormalizer.js +19 -8
  83. package/dist/tools/reconciliation/recommendationEngine.d.ts +1 -1
  84. package/dist/tools/reconciliation/recommendationEngine.js +40 -40
  85. package/dist/tools/reconciliation/reportFormatter.d.ts +2 -2
  86. package/dist/tools/reconciliation/reportFormatter.js +79 -54
  87. package/dist/tools/reconciliation/signDetector.d.ts +1 -1
  88. package/dist/tools/reconciliation/types.d.ts +19 -16
  89. package/dist/tools/reconciliation/ynabAdapter.d.ts +2 -2
  90. package/dist/tools/schemas/common.d.ts +1 -1
  91. package/dist/tools/schemas/common.js +1 -1
  92. package/dist/tools/schemas/outputs/accountOutputs.d.ts +1 -1
  93. package/dist/tools/schemas/outputs/accountOutputs.js +24 -18
  94. package/dist/tools/schemas/outputs/budgetOutputs.d.ts +1 -1
  95. package/dist/tools/schemas/outputs/budgetOutputs.js +14 -11
  96. package/dist/tools/schemas/outputs/categoryOutputs.d.ts +1 -1
  97. package/dist/tools/schemas/outputs/categoryOutputs.js +49 -29
  98. package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +1 -1
  99. package/dist/tools/schemas/outputs/comparisonOutputs.js +12 -12
  100. package/dist/tools/schemas/outputs/index.d.ts +14 -14
  101. package/dist/tools/schemas/outputs/index.js +14 -14
  102. package/dist/tools/schemas/outputs/monthOutputs.d.ts +1 -1
  103. package/dist/tools/schemas/outputs/monthOutputs.js +56 -41
  104. package/dist/tools/schemas/outputs/payeeOutputs.d.ts +1 -1
  105. package/dist/tools/schemas/outputs/payeeOutputs.js +10 -10
  106. package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +2 -2
  107. package/dist/tools/schemas/outputs/reconciliationOutputs.js +45 -45
  108. package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +1 -1
  109. package/dist/tools/schemas/outputs/transactionMutationOutputs.js +28 -22
  110. package/dist/tools/schemas/outputs/transactionOutputs.d.ts +1 -1
  111. package/dist/tools/schemas/outputs/transactionOutputs.js +43 -35
  112. package/dist/tools/schemas/outputs/utilityOutputs.d.ts +1 -1
  113. package/dist/tools/schemas/outputs/utilityOutputs.js +5 -3
  114. package/dist/tools/schemas/shared/commonOutputs.d.ts +1 -1
  115. package/dist/tools/schemas/shared/commonOutputs.js +15 -9
  116. package/dist/tools/transactionReadTools.d.ts +11 -0
  117. package/dist/tools/transactionReadTools.js +202 -0
  118. package/dist/tools/transactionSchemas.d.ts +309 -0
  119. package/dist/tools/transactionSchemas.js +235 -0
  120. package/dist/tools/transactionTools.d.ts +6 -302
  121. package/dist/tools/transactionTools.js +7 -2054
  122. package/dist/tools/transactionUtils.d.ts +31 -0
  123. package/dist/tools/transactionUtils.js +364 -0
  124. package/dist/tools/transactionWriteTools.d.ts +20 -0
  125. package/dist/tools/transactionWriteTools.js +1342 -0
  126. package/dist/tools/utilityTools.d.ts +5 -4
  127. package/dist/tools/utilityTools.js +11 -11
  128. package/dist/types/index.d.ts +7 -7
  129. package/dist/types/index.js +6 -6
  130. package/dist/types/reconciliation.d.ts +1 -1
  131. package/dist/types/toolRegistration.d.ts +14 -12
  132. package/dist/utils/amountUtils.js +1 -1
  133. package/dist/utils/dateUtils.js +4 -4
  134. package/dist/utils/errors.d.ts +3 -3
  135. package/dist/utils/errors.js +4 -4
  136. package/dist/utils/money.d.ts +2 -2
  137. package/dist/utils/money.js +8 -8
  138. package/dist/utils/validationError.d.ts +1 -1
  139. package/dist/utils/validationError.js +1 -1
  140. package/docs/assets/examples/reconciliation-with-recommendations.json +66 -66
  141. package/docs/assets/schemas/reconciliation-v2.json +360 -336
  142. package/docs/plans/2025-12-25-transaction-tools-refactor-design.md +211 -0
  143. package/docs/plans/2025-12-25-transaction-tools-refactor.md +905 -0
  144. package/esbuild.config.mjs +53 -50
  145. package/meta.json +12548 -12548
  146. package/package.json +98 -109
  147. package/scripts/analyze-bundle.mjs +33 -30
  148. package/scripts/create-pr-description.js +169 -120
  149. package/scripts/run-all-tests.js +205 -0
  150. package/scripts/run-domain-integration-tests.js +28 -18
  151. package/scripts/run-generate-mcpb.js +19 -17
  152. package/scripts/run-throttled-integration-tests.js +92 -83
  153. package/scripts/test-delta-params.mjs +149 -120
  154. package/scripts/test-recommendations.ts +36 -32
  155. package/scripts/tmpTransaction.ts +80 -43
  156. package/scripts/validate-env.js +98 -91
  157. package/scripts/verify-build.js +78 -76
  158. package/src/__tests__/comprehensive.integration.test.ts +1281 -1154
  159. package/src/__tests__/performance.test.ts +723 -671
  160. package/src/__tests__/setup.ts +442 -395
  161. package/src/__tests__/smoke.e2e.test.ts +41 -39
  162. package/src/__tests__/testRunner.ts +314 -295
  163. package/src/__tests__/testUtils.ts +456 -364
  164. package/src/__tests__/tools/reconciliation/csvParser.integration.test.ts +109 -107
  165. package/src/__tests__/tools/reconciliation/real-world.integration.test.ts +41 -41
  166. package/src/index.ts +68 -59
  167. package/src/server/CLAUDE.md +480 -0
  168. package/src/server/YNABMCPServer.ts +821 -794
  169. package/src/server/__tests__/YNABMCPServer.integration.test.ts +929 -893
  170. package/src/server/__tests__/YNABMCPServer.test.ts +903 -899
  171. package/src/server/__tests__/budgetResolver.test.ts +466 -423
  172. package/src/server/__tests__/cacheManager.test.ts +891 -874
  173. package/src/server/__tests__/completions.integration.test.ts +115 -106
  174. package/src/server/__tests__/completions.test.ts +334 -313
  175. package/src/server/__tests__/config.test.ts +98 -86
  176. package/src/server/__tests__/deltaCache.merge.test.ts +774 -703
  177. package/src/server/__tests__/deltaCache.swr.test.ts +198 -153
  178. package/src/server/__tests__/deltaCache.test.ts +946 -759
  179. package/src/server/__tests__/diagnostics.test.ts +825 -792
  180. package/src/server/__tests__/errorHandler.integration.test.ts +512 -462
  181. package/src/server/__tests__/errorHandler.test.ts +402 -397
  182. package/src/server/__tests__/prompts.test.ts +424 -347
  183. package/src/server/__tests__/rateLimiter.test.ts +313 -309
  184. package/src/server/__tests__/requestLogger.test.ts +443 -403
  185. package/src/server/__tests__/resources.template.test.ts +196 -185
  186. package/src/server/__tests__/resources.test.ts +294 -288
  187. package/src/server/__tests__/security.integration.test.ts +487 -421
  188. package/src/server/__tests__/securityMiddleware.test.ts +519 -444
  189. package/src/server/__tests__/server-startup.integration.test.ts +509 -490
  190. package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -173
  191. package/src/server/__tests__/toolRegistration.test.ts +239 -210
  192. package/src/server/__tests__/toolRegistry.test.ts +907 -845
  193. package/src/server/budgetResolver.ts +221 -181
  194. package/src/server/cacheKeys.ts +6 -6
  195. package/src/server/cacheManager.ts +498 -484
  196. package/src/server/completions.ts +267 -243
  197. package/src/server/config.ts +35 -14
  198. package/src/server/deltaCache.merge.ts +146 -128
  199. package/src/server/deltaCache.ts +352 -309
  200. package/src/server/diagnostics.ts +257 -242
  201. package/src/server/errorHandler.ts +747 -744
  202. package/src/server/prompts.ts +181 -176
  203. package/src/server/rateLimiter.ts +131 -129
  204. package/src/server/requestLogger.ts +350 -322
  205. package/src/server/resources.ts +442 -374
  206. package/src/server/responseFormatter.ts +41 -37
  207. package/src/server/securityMiddleware.ts +223 -205
  208. package/src/server/serverKnowledgeStore.ts +67 -67
  209. package/src/server/toolRegistry.ts +508 -474
  210. package/src/tools/CLAUDE.md +604 -0
  211. package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -111
  212. package/src/tools/__tests__/accountTools.integration.test.ts +129 -111
  213. package/src/tools/__tests__/accountTools.test.ts +685 -638
  214. package/src/tools/__tests__/adapters.test.ts +142 -108
  215. package/src/tools/__tests__/budgetTools.delta.integration.test.ts +73 -73
  216. package/src/tools/__tests__/budgetTools.integration.test.ts +132 -124
  217. package/src/tools/__tests__/budgetTools.test.ts +442 -413
  218. package/src/tools/__tests__/categoryTools.delta.integration.test.ts +76 -68
  219. package/src/tools/__tests__/categoryTools.integration.test.ts +314 -288
  220. package/src/tools/__tests__/categoryTools.test.ts +656 -625
  221. package/src/tools/__tests__/compareTransactions/formatter.test.ts +535 -462
  222. package/src/tools/__tests__/compareTransactions/index.test.ts +378 -358
  223. package/src/tools/__tests__/compareTransactions/matcher.test.ts +497 -398
  224. package/src/tools/__tests__/compareTransactions/parser.test.ts +765 -747
  225. package/src/tools/__tests__/compareTransactions.test.ts +352 -332
  226. package/src/tools/__tests__/compareTransactions.window.test.ts +150 -146
  227. package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +69 -65
  228. package/src/tools/__tests__/deltaFetcher.test.ts +325 -265
  229. package/src/tools/__tests__/deltaSupport.test.ts +211 -184
  230. package/src/tools/__tests__/deltaTestUtils.ts +37 -33
  231. package/src/tools/__tests__/exportTransactions.test.ts +205 -200
  232. package/src/tools/__tests__/monthTools.delta.integration.test.ts +68 -68
  233. package/src/tools/__tests__/monthTools.integration.test.ts +178 -166
  234. package/src/tools/__tests__/monthTools.test.ts +561 -512
  235. package/src/tools/__tests__/payeeTools.delta.integration.test.ts +68 -68
  236. package/src/tools/__tests__/payeeTools.integration.test.ts +158 -142
  237. package/src/tools/__tests__/payeeTools.test.ts +486 -434
  238. package/src/tools/__tests__/transactionSchemas.test.ts +1204 -0
  239. package/src/tools/__tests__/transactionTools.integration.test.ts +875 -825
  240. package/src/tools/__tests__/transactionTools.test.ts +4923 -4366
  241. package/src/tools/__tests__/transactionUtils.test.ts +1016 -0
  242. package/src/tools/__tests__/utilityTools.integration.test.ts +32 -32
  243. package/src/tools/__tests__/utilityTools.test.ts +68 -58
  244. package/src/tools/accountTools.ts +293 -271
  245. package/src/tools/adapters.ts +120 -63
  246. package/src/tools/budgetTools.ts +121 -116
  247. package/src/tools/categoryTools.ts +379 -339
  248. package/src/tools/compareTransactions/formatter.ts +131 -119
  249. package/src/tools/compareTransactions/index.ts +249 -214
  250. package/src/tools/compareTransactions/matcher.ts +259 -209
  251. package/src/tools/compareTransactions/parser.ts +517 -487
  252. package/src/tools/compareTransactions/types.ts +38 -38
  253. package/src/tools/compareTransactions.ts +1 -1
  254. package/src/tools/deltaFetcher.ts +281 -260
  255. package/src/tools/deltaSupport.ts +264 -259
  256. package/src/tools/exportTransactions.ts +230 -218
  257. package/src/tools/monthTools.ts +180 -165
  258. package/src/tools/payeeTools.ts +152 -140
  259. package/src/tools/reconcileAdapter.ts +297 -246
  260. package/src/tools/reconciliation/CLAUDE.md +506 -0
  261. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +135 -112
  262. package/src/tools/reconciliation/__tests__/adapter.test.ts +249 -227
  263. package/src/tools/reconciliation/__tests__/analyzer.test.ts +408 -335
  264. package/src/tools/reconciliation/__tests__/csvParser.test.ts +71 -69
  265. package/src/tools/reconciliation/__tests__/executor.integration.test.ts +348 -323
  266. package/src/tools/reconciliation/__tests__/executor.progress.test.ts +503 -457
  267. package/src/tools/reconciliation/__tests__/executor.test.ts +898 -831
  268. package/src/tools/reconciliation/__tests__/matcher.test.ts +667 -663
  269. package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +296 -276
  270. package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +692 -624
  271. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1008 -986
  272. package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +187 -146
  273. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +583 -530
  274. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +75 -71
  275. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +70 -58
  276. package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +102 -88
  277. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +58 -43
  278. package/src/tools/reconciliation/__tests__/signDetector.test.ts +209 -206
  279. package/src/tools/reconciliation/__tests__/ynabAdapter.test.ts +66 -60
  280. package/src/tools/reconciliation/analyzer.ts +582 -406
  281. package/src/tools/reconciliation/csvParser.ts +656 -609
  282. package/src/tools/reconciliation/executor.ts +1290 -1128
  283. package/src/tools/reconciliation/index.ts +580 -528
  284. package/src/tools/reconciliation/matcher.ts +256 -240
  285. package/src/tools/reconciliation/payeeNormalizer.ts +92 -78
  286. package/src/tools/reconciliation/recommendationEngine.ts +357 -345
  287. package/src/tools/reconciliation/reportFormatter.ts +349 -276
  288. package/src/tools/reconciliation/signDetector.ts +89 -83
  289. package/src/tools/reconciliation/types.ts +164 -153
  290. package/src/tools/reconciliation/ynabAdapter.ts +17 -15
  291. package/src/tools/schemas/CLAUDE.md +546 -0
  292. package/src/tools/schemas/common.ts +1 -1
  293. package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +410 -409
  294. package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +305 -299
  295. package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +431 -430
  296. package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +510 -495
  297. package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +179 -153
  298. package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +293 -254
  299. package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +457 -457
  300. package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +362 -356
  301. package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +402 -399
  302. package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +225 -211
  303. package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +457 -454
  304. package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +316 -315
  305. package/src/tools/schemas/outputs/accountOutputs.ts +40 -34
  306. package/src/tools/schemas/outputs/budgetOutputs.ts +24 -19
  307. package/src/tools/schemas/outputs/categoryOutputs.ts +76 -56
  308. package/src/tools/schemas/outputs/comparisonOutputs.ts +192 -169
  309. package/src/tools/schemas/outputs/index.ts +163 -163
  310. package/src/tools/schemas/outputs/monthOutputs.ts +95 -80
  311. package/src/tools/schemas/outputs/payeeOutputs.ts +18 -18
  312. package/src/tools/schemas/outputs/reconciliationOutputs.ts +386 -373
  313. package/src/tools/schemas/outputs/transactionMutationOutputs.ts +259 -231
  314. package/src/tools/schemas/outputs/transactionOutputs.ts +81 -71
  315. package/src/tools/schemas/outputs/utilityOutputs.ts +90 -84
  316. package/src/tools/schemas/shared/commonOutputs.ts +27 -19
  317. package/src/tools/toolCategories.ts +114 -114
  318. package/src/tools/transactionReadTools.ts +327 -0
  319. package/src/tools/transactionSchemas.ts +484 -0
  320. package/src/tools/transactionTools.ts +107 -2990
  321. package/src/tools/transactionUtils.ts +621 -0
  322. package/src/tools/transactionWriteTools.ts +2110 -0
  323. package/src/tools/utilityTools.ts +46 -41
  324. package/src/types/CLAUDE.md +477 -0
  325. package/src/types/__tests__/index.test.ts +51 -51
  326. package/src/types/index.ts +43 -39
  327. package/src/types/integration-tests.d.ts +26 -26
  328. package/src/types/reconciliation.ts +29 -29
  329. package/src/types/toolAnnotations.ts +30 -30
  330. package/src/types/toolRegistration.ts +43 -32
  331. package/src/utils/CLAUDE.md +508 -0
  332. package/src/utils/__tests__/dateUtils.test.ts +174 -168
  333. package/src/utils/__tests__/money.test.ts +193 -187
  334. package/src/utils/amountUtils.ts +5 -5
  335. package/src/utils/baseError.ts +5 -5
  336. package/src/utils/dateUtils.ts +29 -26
  337. package/src/utils/errors.ts +14 -14
  338. package/src/utils/money.ts +66 -52
  339. package/src/utils/validationError.ts +1 -1
  340. package/tsconfig.json +29 -29
  341. package/tsconfig.prod.json +16 -16
  342. package/vitest-reporters/split-json-reporter.ts +247 -204
  343. package/vitest.config.ts +99 -95
  344. package/.prettierignore +0 -10
  345. package/.prettierrc.json +0 -10
  346. package/eslint.config.js +0 -49
@@ -1,832 +1,882 @@
1
- import { describe, it, expect, beforeAll, afterEach } from 'vitest';
2
- import { randomUUID } from 'crypto';
3
- import * as ynab from 'ynab';
4
- import { z } from 'zod';
1
+ import { randomUUID } from "node:crypto";
2
+ import { afterEach, beforeAll, describe, expect, it } from "vitest";
3
+ import * as ynab from "ynab";
4
+ import type { z } from "zod";
5
+ import { waitFor } from "../../__tests__/testUtils.js";
5
6
  import {
6
- handleListTransactions,
7
- handleGetTransaction,
8
- handleCreateTransactions,
9
- handleUpdateTransactions,
10
- CreateTransactionsSchema,
11
- } from '../transactionTools.js';
12
- import { waitFor } from '../../__tests__/testUtils.js';
13
-
14
- const isSkip = ['true', '1', 'yes', 'y', 'on'].includes(
15
- (process.env['SKIP_E2E_TESTS'] || '').toLowerCase().trim(),
7
+ type CreateTransactionsSchema,
8
+ handleCreateTransactions,
9
+ handleGetTransaction,
10
+ handleListTransactions,
11
+ handleUpdateTransactions,
12
+ } from "../transactionTools.js";
13
+
14
+ const isSkip = ["true", "1", "yes", "y", "on"].includes(
15
+ (process.env.SKIP_E2E_TESTS || "").toLowerCase().trim(),
16
16
  );
17
- const hasToken = !!process.env['YNAB_ACCESS_TOKEN'];
17
+ const hasToken = !!process.env.YNAB_ACCESS_TOKEN;
18
18
  const shouldSkip = isSkip || !hasToken;
19
19
  const describeIntegration = shouldSkip ? describe.skip : describe;
20
20
  type CreateTransactionsParams = z.infer<typeof CreateTransactionsSchema>;
21
21
 
22
- describeIntegration('Transaction Tools Integration', () => {
23
- let ynabAPI: ynab.API;
24
- let testBudgetId: string;
25
- let testAccountId: string;
26
- let secondaryAccountId: string | undefined;
27
-
28
- beforeAll(async () => {
29
- const accessToken = process.env['YNAB_ACCESS_TOKEN']!;
30
- ynabAPI = new ynab.API(accessToken);
31
-
32
- // Get the first budget for testing
33
- const budgetsResponse = await ynabAPI.budgets.getBudgets();
34
- testBudgetId = budgetsResponse.data.budgets[0].id;
35
-
36
- // Get the first account for testing
37
- const accountsResponse = await ynabAPI.accounts.getAccounts(testBudgetId);
38
- const accounts = accountsResponse.data.accounts;
39
- testAccountId = accounts[0].id;
40
- secondaryAccountId = accounts[1]?.id;
41
- });
42
-
43
- it(
44
- 'should successfully list transactions from real API',
45
- { meta: { tier: 'core', domain: 'transactions' } },
46
- async () => {
47
- const params = {
48
- budget_id: testBudgetId,
49
- };
50
-
51
- const result = await handleListTransactions(ynabAPI, params);
52
- const response = JSON.parse(result.content[0].text);
53
-
54
- // Handle large response case (preview_transactions instead of transactions)
55
- const transactions = response.transactions || response.preview_transactions;
56
- expect(transactions).toBeDefined();
57
- expect(Array.isArray(transactions)).toBe(true);
58
-
59
- const count = response.total_count || transactions.length;
60
- console.warn(`✅ Successfully listed ${count} transactions`);
61
- },
62
- );
63
-
64
- it(
65
- 'should successfully list transactions with account filter',
66
- { meta: { tier: 'domain', domain: 'transactions' } },
67
- async () => {
68
- const params = {
69
- budget_id: testBudgetId,
70
- account_id: testAccountId,
71
- };
72
-
73
- const result = await handleListTransactions(ynabAPI, params);
74
- const response = JSON.parse(result.content[0].text);
75
-
76
- expect(response.transactions).toBeDefined();
77
- expect(Array.isArray(response.transactions)).toBe(true);
78
-
79
- // All transactions should be from the specified account
80
- response.transactions.forEach((transaction: any) => {
81
- expect(transaction.account_id).toBe(testAccountId);
82
- });
83
-
84
- console.warn(
85
- `✅ Successfully listed ${response.transactions.length} transactions for account`,
86
- );
87
- },
88
- );
89
-
90
- it(
91
- 'should successfully list transactions with date filter',
92
- { meta: { tier: 'domain', domain: 'transactions' } },
93
- async () => {
94
- const params = {
95
- budget_id: testBudgetId,
96
- since_date: '2024-01-01',
97
- };
98
-
99
- const result = await handleListTransactions(ynabAPI, params);
100
- const response = JSON.parse(result.content[0].text);
101
-
102
- // Handle large response case (preview_transactions instead of transactions)
103
- const transactions = response.transactions || response.preview_transactions;
104
- expect(transactions).toBeDefined();
105
- expect(Array.isArray(transactions)).toBe(true);
106
-
107
- const count = response.total_count || transactions.length;
108
- console.warn(`✅ Successfully listed ${count} transactions since 2024-01-01`);
109
- },
110
- );
111
-
112
- it(
113
- 'should get transaction details if transactions exist',
114
- { meta: { tier: 'core', domain: 'transactions' } },
115
- async () => {
116
- // First get a list of transactions to find one to test with
117
- const listParams = {
118
- budget_id: testBudgetId,
119
- };
120
-
121
- const listResult = await handleListTransactions(ynabAPI, listParams);
122
- const listResponse = JSON.parse(listResult.content[0].text);
123
-
124
- if (listResponse.transactions && listResponse.transactions.length > 0) {
125
- const testTransactionId = listResponse.transactions[0].id;
126
-
127
- const params = {
128
- budget_id: testBudgetId,
129
- transaction_id: testTransactionId,
130
- };
131
-
132
- const result = await handleGetTransaction(ynabAPI, params);
133
- const response = JSON.parse(result.content[0].text);
134
-
135
- expect(response.transaction).toBeDefined();
136
- expect(response.transaction.id).toBe(testTransactionId);
137
-
138
- console.warn(`✅ Successfully retrieved transaction: ${response.transaction.id}`);
139
- } else {
140
- console.warn('⚠️ No transactions found to test get transaction');
141
- }
142
- },
143
- );
144
-
145
- it(
146
- 'should handle invalid budget ID gracefully',
147
- { meta: { tier: 'domain', domain: 'transactions' } },
148
- async () => {
149
- const params = {
150
- budget_id: 'invalid-budget-id',
151
- };
152
-
153
- const result = await handleListTransactions(ynabAPI, params);
154
- const response = JSON.parse(result.content[0].text);
155
-
156
- expect(response.error).toBeDefined();
157
- expect(response.error.message).toBeDefined();
158
-
159
- console.warn(`✅ Correctly handled invalid budget ID: ${response.error.message}`);
160
- },
161
- );
162
-
163
- it(
164
- 'should handle invalid transaction ID gracefully',
165
- { meta: { tier: 'domain', domain: 'transactions' } },
166
- async () => {
167
- const params = {
168
- budget_id: testBudgetId,
169
- transaction_id: 'invalid-transaction-id',
170
- };
171
-
172
- const result = await handleGetTransaction(ynabAPI, params);
173
- const response = JSON.parse(result.content[0].text);
174
-
175
- expect(response.error).toBeDefined();
176
- expect(response.error.message).toBeDefined();
177
-
178
- console.warn(`✅ Correctly handled invalid transaction ID: ${response.error.message}`);
179
- },
180
- );
181
-
182
- describe('handleCreateTransactions - Integration', () => {
183
- type BulkTransactionInput = CreateTransactionsParams['transactions'][number];
184
- const createdTransactionIds: string[] = [];
185
-
186
- const parseToolResult = (toolResult: { content?: { text?: string }[] }) => {
187
- const raw = toolResult.content?.[0]?.text ?? '{}';
188
- try {
189
- return JSON.parse(raw);
190
- } catch {
191
- throw new Error(`Unable to parse tool output: ${raw}`);
192
- }
193
- };
194
-
195
- const today = () => new Date().toISOString().slice(0, 10);
196
-
197
- const buildTransaction = (
198
- overrides: Partial<BulkTransactionInput> = {},
199
- ): BulkTransactionInput => {
200
- const base: BulkTransactionInput = {
201
- account_id: testAccountId,
202
- amount: -1234,
203
- date: today(),
204
- memo: `Bulk MCP Test ${randomUUID().slice(0, 8)}`,
205
- // YNAB import_id max length is 36 characters: "MCP:" (4) + UUID first 32 chars = 36
206
- import_id: `MCP:${randomUUID().slice(0, 32)}`,
207
- };
208
- return { ...base, ...overrides };
209
- };
210
-
211
- const executeBulkCreate = async (
212
- params: CreateTransactionsParams,
213
- trackCreatedIds = true,
214
- ): Promise<{ response: any }> => {
215
- const result = await handleCreateTransactions(ynabAPI, params);
216
- const response = parseToolResult(result);
217
-
218
- if (response.error) {
219
- console.error('Bulk Create Failed:', JSON.stringify(response.error, null, 2));
220
- }
221
-
222
- if (trackCreatedIds && Array.isArray(response.results)) {
223
- const createdIds = response.results
224
- .filter(
225
- (res: { status?: string; transaction_id?: string }) =>
226
- res.status === 'created' && typeof res.transaction_id === 'string',
227
- )
228
- .map((res: { transaction_id: string }) => res.transaction_id);
229
- createdTransactionIds.push(...createdIds);
230
- }
231
-
232
- return { response };
233
- };
234
-
235
- const fetchBudgetTransactions = async () => {
236
- const listResult = await handleListTransactions(ynabAPI, { budget_id: testBudgetId });
237
- return parseToolResult(listResult);
238
- };
239
-
240
- afterEach(async () => {
241
- while (createdTransactionIds.length > 0) {
242
- const transactionId = createdTransactionIds.pop();
243
- if (!transactionId) continue;
244
- try {
245
- await ynabAPI.transactions.deleteTransaction(testBudgetId, transactionId);
246
- } catch (error) {
247
- console.warn(
248
- `⚠️ Failed to clean up integration test transaction ${transactionId}: ${
249
- (error as Error).message
250
- }`,
251
- );
252
- }
253
- }
254
- });
255
- it(
256
- 'should create two transactions via the bulk handler',
257
- { meta: { tier: 'core', domain: 'transactions' } },
258
- async () => {
259
- const importPrefix = randomUUID().slice(0, 30); // Keep short for import_id
260
- const { response } = await executeBulkCreate({
261
- budget_id: testBudgetId,
262
- transactions: [
263
- buildTransaction({
264
- amount: -1500,
265
- memo: `Bulk Pair A ${importPrefix}`,
266
- // Max 36 chars: "MCP:" (4) + prefix (30) + ":A" (2) = 36
267
- import_id: `MCP:${importPrefix}:A`,
268
- }),
269
- buildTransaction({
270
- amount: -2500,
271
- memo: `Bulk Pair B ${importPrefix}`,
272
- // Max 36 chars: "MCP:" (4) + prefix (30) + ":B" (2) = 36
273
- import_id: `MCP:${importPrefix}:B`,
274
- }),
275
- ],
276
- });
277
-
278
- expect(response.summary.created).toBe(2);
279
- expect(response.results).toHaveLength(2);
280
- expect(response.results.every((res: any) => res.status === 'created')).toBe(true);
281
- },
282
- );
283
-
284
- it(
285
- 'should detect duplicates when reusing import IDs',
286
- { meta: { tier: 'domain', domain: 'transactions' } },
287
- async () => {
288
- const importId = `MCP:DUP:${randomUUID().slice(0, 20)}`;
289
- await executeBulkCreate({
290
- budget_id: testBudgetId,
291
- transactions: [
292
- buildTransaction({
293
- import_id: importId,
294
- memo: `Duplicate seed ${importId}`,
295
- }),
296
- ],
297
- });
298
-
299
- const { response } = await executeBulkCreate({
300
- budget_id: testBudgetId,
301
- transactions: [
302
- buildTransaction({
303
- import_id: importId,
304
- memo: `Duplicate attempt ${importId}`,
305
- }),
306
- ],
307
- });
308
-
309
- if (!response.summary) {
310
- console.error('Duplicate test response:', JSON.stringify(response, null, 2));
311
- }
312
-
313
- expect(response.summary.duplicates).toBe(1);
314
- expect(response.results[0].status).toBe('duplicate');
315
- },
316
- );
317
-
318
- it(
319
- 'should invalidate caches so new transactions appear in list results',
320
- { meta: { tier: 'domain', domain: 'transactions' } },
321
- async () => {
322
- const memo = `Cache Invalidation ${randomUUID()}`;
323
- await fetchBudgetTransactions(); // warm cache to ensure invalidation path executes
324
-
325
- await executeBulkCreate({
326
- budget_id: testBudgetId,
327
- transactions: [
328
- buildTransaction({
329
- memo,
330
- amount: -4321,
331
- // Max 36 chars: "MCP:CACHE:" (10) + 26 chars
332
- import_id: `MCP:CACHE:${randomUUID().slice(0, 26)}`,
333
- }),
334
- ],
335
- });
336
-
337
- let transactions: any[] | undefined;
338
- await waitFor(
339
- async () => {
340
- const afterList = await fetchBudgetTransactions();
341
- transactions =
342
- afterList.transactions ||
343
- afterList.preview_transactions ||
344
- afterList.transaction_preview;
345
- return (
346
- (transactions as any[])?.some((transaction) => transaction.memo === memo) ?? false
347
- );
348
- },
349
- 10000,
350
- 500,
351
- );
352
-
353
- expect(transactions).toBeDefined();
354
- expect((transactions as any[]).some((transaction) => transaction.memo === memo)).toBe(true);
355
- },
356
- );
357
-
358
- it(
359
- 'should create transactions across multiple accounts within one batch',
360
- { meta: { tier: 'domain', domain: 'transactions' } },
361
- async () => {
362
- if (!secondaryAccountId || secondaryAccountId === testAccountId) {
363
- console.warn(
364
- 'Skipping multi-account bulk test because only one account is available in this budget.',
365
- );
366
- return;
367
- }
368
-
369
- const { response } = await executeBulkCreate({
370
- budget_id: testBudgetId,
371
- transactions: [
372
- buildTransaction({
373
- account_id: testAccountId,
374
- memo: 'Primary account bulk entry',
375
- // Max 36 chars: "MCP:PRIMARY:" (12) + 24 chars
376
- import_id: `MCP:PRIMARY:${randomUUID().slice(0, 24)}`,
377
- }),
378
- buildTransaction({
379
- account_id: secondaryAccountId,
380
- memo: 'Secondary account bulk entry',
381
- // Max 36 chars: "MCP:SECONDARY:" (14) + 22 chars
382
- import_id: `MCP:SECONDARY:${randomUUID().slice(0, 22)}`,
383
- }),
384
- ],
385
- });
386
-
387
- expect(response.summary.created).toBe(2);
388
- const accountIds = new Set((response.transactions ?? []).map((txn: any) => txn.account_id));
389
- expect(accountIds.has(testAccountId)).toBe(true);
390
- expect(accountIds.has(secondaryAccountId)).toBe(true);
391
- },
392
- );
393
-
394
- it(
395
- 'should handle large batches and report response mode',
396
- { meta: { tier: 'domain', domain: 'transactions' } },
397
- async () => {
398
- const batch = Array.from({ length: 50 }, (_, index) =>
399
- buildTransaction({
400
- amount: -1000 - index,
401
- memo: `Bulk batch item ${index}`,
402
- // Max 36 chars: "MCP:BATCH:" (10) + index (up to 2 chars) + ":" (1) + UUID
403
- // With index 0-99, max prefix is 13 chars, leaving 23 for UUID
404
- import_id: `MCP:BATCH:${index}:${randomUUID().slice(0, 23)}`,
405
- }),
406
- );
407
-
408
- const { response } = await executeBulkCreate({
409
- budget_id: testBudgetId,
410
- transactions: batch,
411
- });
412
-
413
- expect(response.summary.total_requested).toBe(50);
414
- expect(response.results).toHaveLength(50);
415
- expect(['full', 'summary', 'ids_only']).toContain(response.mode);
416
- },
417
- );
418
-
419
- it(
420
- 'should support dry run mode without creating transactions',
421
- { meta: { tier: 'domain', domain: 'transactions' } },
422
- async () => {
423
- const result = await handleCreateTransactions(ynabAPI, {
424
- budget_id: testBudgetId,
425
- dry_run: true,
426
- transactions: [
427
- buildTransaction({
428
- memo: `Dry run ${randomUUID()}`,
429
- }),
430
- ],
431
- });
432
- const response = parseToolResult(result);
433
- expect(response.dry_run).toBe(true);
434
- expect(response.transactions_preview).toHaveLength(1);
435
- expect(response.summary.total_transactions).toBe(1);
436
- },
437
- );
438
-
439
- it(
440
- 'should confirm dry run does not persist data',
441
- { meta: { tier: 'domain', domain: 'transactions' } },
442
- async () => {
443
- const memo = `DryRunNoPersist ${randomUUID()}`;
444
- await handleCreateTransactions(ynabAPI, {
445
- budget_id: testBudgetId,
446
- dry_run: true,
447
- transactions: [
448
- buildTransaction({
449
- memo,
450
- }),
451
- ],
452
- });
453
-
454
- const afterList = await fetchBudgetTransactions();
455
- const transactions =
456
- afterList.transactions || afterList.preview_transactions || afterList.transaction_preview;
457
- const memoExists = Array.isArray(transactions)
458
- ? transactions.some((transaction) => transaction.memo === memo)
459
- : false;
460
- expect(memoExists).toBe(false);
461
- },
462
- );
463
-
464
- it(
465
- 'should handle invalid budget IDs gracefully during bulk create',
466
- { meta: { tier: 'domain', domain: 'transactions' } },
467
- async () => {
468
- const result = await handleCreateTransactions(ynabAPI, {
469
- budget_id: 'invalid-budget-id',
470
- transactions: [buildTransaction()],
471
- });
472
- const response = parseToolResult(result);
473
- expect(response.error).toBeDefined();
474
- expect(response.error.message).toBeDefined();
475
- },
476
- );
477
-
478
- it(
479
- 'should handle invalid account IDs during bulk create',
480
- { meta: { tier: 'domain', domain: 'transactions' } },
481
- async () => {
482
- const result = await handleCreateTransactions(ynabAPI, {
483
- budget_id: testBudgetId,
484
- transactions: [
485
- buildTransaction({
486
- account_id: 'invalid-account-id',
487
- // Max 36 chars: "MCP:INVALID:" (12) + 24 chars
488
- import_id: `MCP:INVALID:${randomUUID().slice(0, 24)}`,
489
- }),
490
- ],
491
- });
492
- const response = parseToolResult(result);
493
- expect(response.error).toBeDefined();
494
- expect(response.error.message).toBeDefined();
495
- },
496
- );
497
-
498
- it.skip(
499
- 'documents rate limiting behavior for bulk requests',
500
- { meta: { tier: 'domain', domain: 'transactions' } },
501
- () => {
502
- // Intentionally skipped provoking API rate limits is outside automated integration scope
503
- },
504
- );
505
- });
506
-
507
- describeIntegration('Bulk Update Transactions Integration', () => {
508
- const createdTransactionIds: string[] = [];
509
-
510
- const parseToolResult = (result: any) => {
511
- if (!result.content || !result.content[0]?.text) {
512
- throw new Error('Invalid tool result structure');
513
- }
514
- return JSON.parse(result.content[0].text);
515
- };
516
-
517
- afterEach(async () => {
518
- // Clean up created transactions
519
- while (createdTransactionIds.length > 0) {
520
- const transactionId = createdTransactionIds.pop();
521
- if (!transactionId) continue;
522
- try {
523
- await ynabAPI.transactions.deleteTransaction(testBudgetId, transactionId);
524
- } catch (error) {
525
- console.warn(
526
- `⚠️ Failed to clean up integration test transaction ${transactionId}: ${
527
- (error as Error).message
528
- }`,
529
- );
530
- }
531
- }
532
- });
533
-
534
- it(
535
- 'should successfully update multiple transactions with provided metadata',
536
- { meta: { tier: 'core', domain: 'transactions' } },
537
- async () => {
538
- // First create test transactions
539
- const createResult = await handleCreateTransactions(ynabAPI, {
540
- budget_id: testBudgetId,
541
- transactions: [
542
- {
543
- account_id: testAccountId,
544
- amount: -5000,
545
- date: new Date().toISOString().slice(0, 10),
546
- memo: 'Original memo 1',
547
- // Max 36 chars: "MCP:UPDATE-TEST-1:" (18) + 18 chars
548
- import_id: `MCP:UPDATE-TEST-1:${randomUUID().slice(0, 18)}`,
549
- },
550
- {
551
- account_id: testAccountId,
552
- amount: -10000,
553
- date: new Date().toISOString().slice(0, 10),
554
- memo: 'Original memo 2',
555
- // Max 36 chars: "MCP:UPDATE-TEST-2:" (18) + 18 chars
556
- import_id: `MCP:UPDATE-TEST-2:${randomUUID().slice(0, 18)}`,
557
- },
558
- ],
559
- });
560
-
561
- const createResponse = parseToolResult(createResult);
562
- const transactionIds = createResponse.results
563
- .filter((r: any) => r.status === 'created')
564
- .map((r: any) => r.transaction_id);
565
-
566
- expect(transactionIds).toHaveLength(2);
567
- createdTransactionIds.push(...transactionIds);
568
-
569
- // Now update the transactions with metadata
570
- const updateResult = await handleUpdateTransactions(ynabAPI, {
571
- budget_id: testBudgetId,
572
- transactions: [
573
- {
574
- id: transactionIds[0],
575
- amount: -7500,
576
- memo: 'Updated memo 1',
577
- original_account_id: testAccountId,
578
- original_date: new Date().toISOString().slice(0, 10),
579
- },
580
- {
581
- id: transactionIds[1],
582
- memo: 'Updated memo 2',
583
- cleared: 'cleared' as const,
584
- original_account_id: testAccountId,
585
- original_date: new Date().toISOString().slice(0, 10),
586
- },
587
- ],
588
- });
589
-
590
- const updateResponse = parseToolResult(updateResult);
591
- expect(updateResponse.success).toBe(true);
592
- expect(updateResponse.summary.updated).toBe(2);
593
- expect(updateResponse.summary.failed).toBe(0);
594
- expect(updateResponse.results).toHaveLength(2);
595
- expect(updateResponse.results[0].status).toBe('updated');
596
- expect(updateResponse.results[0].correlation_key).toBe(transactionIds[0]);
597
- expect(updateResponse.results[1].status).toBe('updated');
598
- expect(updateResponse.results[1].correlation_key).toBe(transactionIds[1]);
599
-
600
- // Verify changes persisted
601
- await waitFor(
602
- async () => {
603
- const getResult1 = await handleGetTransaction(ynabAPI, {
604
- budget_id: testBudgetId,
605
- transaction_id: transactionIds[0],
606
- });
607
- const transaction1 = parseToolResult(getResult1).transaction;
608
- return transaction1.amount === -7.5 && transaction1.memo === 'Updated memo 1';
609
- },
610
- 10000,
611
- 500,
612
- );
613
-
614
- const getResult1 = await handleGetTransaction(ynabAPI, {
615
- budget_id: testBudgetId,
616
- transaction_id: transactionIds[0],
617
- });
618
- const transaction1 = parseToolResult(getResult1).transaction;
619
- expect(transaction1.amount).toBe(-7.5);
620
- expect(transaction1.memo).toBe('Updated memo 1');
621
-
622
- await waitFor(
623
- async () => {
624
- const getResult2 = await handleGetTransaction(ynabAPI, {
625
- budget_id: testBudgetId,
626
- transaction_id: transactionIds[1],
627
- });
628
- const transaction2 = parseToolResult(getResult2).transaction;
629
- return transaction2.memo === 'Updated memo 2' && transaction2.cleared === 'cleared';
630
- },
631
- 10000,
632
- 500,
633
- );
634
-
635
- const getResult2 = await handleGetTransaction(ynabAPI, {
636
- budget_id: testBudgetId,
637
- transaction_id: transactionIds[1],
638
- });
639
- const transaction2 = parseToolResult(getResult2).transaction;
640
- expect(transaction2.memo).toBe('Updated memo 2');
641
- expect(transaction2.cleared).toBe('cleared');
642
-
643
- console.warn('✅ Successfully updated 2 transactions with provided metadata');
644
- },
645
- );
646
-
647
- it(
648
- 'should successfully update transactions without metadata (using cache/API)',
649
- { meta: { tier: 'domain', domain: 'transactions' } },
650
- async () => {
651
- // Create a test transaction
652
- const createResult = await handleCreateTransactions(ynabAPI, {
653
- budget_id: testBudgetId,
654
- transactions: [
655
- {
656
- account_id: testAccountId,
657
- amount: -3000,
658
- date: new Date().toISOString().slice(0, 10),
659
- memo: 'Original',
660
- // Max 36 chars: "MCP:UPDATE-NO-META:" (19) + 17 chars
661
- import_id: `MCP:UPDATE-NO-META:${randomUUID().slice(0, 17)}`,
662
- },
663
- ],
664
- });
665
-
666
- const createResponse = parseToolResult(createResult);
667
- const transactionId = createResponse.results[0].transaction_id;
668
- createdTransactionIds.push(transactionId);
669
-
670
- // Update without providing original_account_id/original_date
671
- const updateResult = await handleUpdateTransactions(ynabAPI, {
672
- budget_id: testBudgetId,
673
- transactions: [
674
- {
675
- id: transactionId,
676
- memo: 'Updated without metadata',
677
- },
678
- ],
679
- });
680
-
681
- const updateResponse = parseToolResult(updateResult);
682
- expect(updateResponse.success).toBe(true);
683
- expect(updateResponse.summary.updated).toBe(1);
684
-
685
- // Verify change
686
- await waitFor(
687
- async () => {
688
- const getResult = await handleGetTransaction(ynabAPI, {
689
- budget_id: testBudgetId,
690
- transaction_id: transactionId,
691
- });
692
- const transaction = parseToolResult(getResult).transaction;
693
- return transaction.memo === 'Updated without metadata';
694
- },
695
- 10000,
696
- 500,
697
- );
698
-
699
- const getResult = await handleGetTransaction(ynabAPI, {
700
- budget_id: testBudgetId,
701
- transaction_id: transactionId,
702
- });
703
- const transaction = parseToolResult(getResult).transaction;
704
- expect(transaction.memo).toBe('Updated without metadata');
705
-
706
- console.warn('✅ Successfully updated transaction without metadata');
707
- },
708
- );
709
-
710
- it(
711
- 'should provide before/after preview in dry_run mode',
712
- { meta: { tier: 'domain', domain: 'transactions' } },
713
- async () => {
714
- // Create a test transaction
715
- const createResult = await handleCreateTransactions(ynabAPI, {
716
- budget_id: testBudgetId,
717
- transactions: [
718
- {
719
- account_id: testAccountId,
720
- amount: -2000,
721
- date: new Date().toISOString().slice(0, 10),
722
- memo: 'For dry run test',
723
- // Max 36 chars: "MCP:DRY-RUN:" (12) + 24 chars
724
- import_id: `MCP:DRY-RUN:${randomUUID().slice(0, 24)}`,
725
- },
726
- ],
727
- });
728
-
729
- const createResponse = parseToolResult(createResult);
730
- const transactionId = createResponse.results[0].transaction_id;
731
- createdTransactionIds.push(transactionId);
732
-
733
- // Run dry_run update
734
- const dryRunResult = await handleUpdateTransactions(ynabAPI, {
735
- budget_id: testBudgetId,
736
- transactions: [
737
- {
738
- id: transactionId,
739
- amount: -5000,
740
- memo: 'Dry run update',
741
- },
742
- ],
743
- dry_run: true,
744
- });
745
-
746
- const dryRunResponse = parseToolResult(dryRunResult);
747
- expect(dryRunResponse.dry_run).toBe(true);
748
- expect(dryRunResponse.transactions_preview).toHaveLength(1);
749
-
750
- const preview = dryRunResponse.transactions_preview[0];
751
- expect(preview.transaction_id).toBe(transactionId);
752
- expect(preview.before).toBeDefined();
753
- expect(preview.after).toBeDefined();
754
-
755
- if (typeof preview.before !== 'string') {
756
- expect(preview.before.amount).toBe(-2);
757
- expect(preview.before.memo).toBe('For dry run test');
758
- expect(preview.after.amount).toBe(-5);
759
- expect(preview.after.memo).toBe('Dry run update');
760
- }
761
-
762
- // Verify transaction was NOT actually updated
763
- const getResult = await handleGetTransaction(ynabAPI, {
764
- budget_id: testBudgetId,
765
- transaction_id: transactionId,
766
- });
767
- const transaction = parseToolResult(getResult).transaction;
768
- expect(transaction.amount).toBe(-2); // Should still be original amount
769
- expect(transaction.memo).toBe('For dry run test'); // Should still be original memo
770
-
771
- console.warn('✅ Dry run preview successful, no changes persisted');
772
- },
773
- );
774
-
775
- it(
776
- 'should handle partial failures gracefully',
777
- { meta: { tier: 'domain', domain: 'transactions' } },
778
- async () => {
779
- // Create one valid transaction
780
- const createResult = await handleCreateTransactions(ynabAPI, {
781
- budget_id: testBudgetId,
782
- transactions: [
783
- {
784
- account_id: testAccountId,
785
- amount: -1000,
786
- date: new Date().toISOString().slice(0, 10),
787
- // Max 36 chars: "MCP:PARTIAL-FAIL:" (17) + 19 chars
788
- import_id: `MCP:PARTIAL-FAIL:${randomUUID().slice(0, 19)}`,
789
- },
790
- ],
791
- });
792
-
793
- const createResponse = parseToolResult(createResult);
794
- const validTransactionId = createResponse.results[0].transaction_id;
795
- createdTransactionIds.push(validTransactionId);
796
-
797
- // Try to update with one valid and one invalid ID
798
- const updateResult = await handleUpdateTransactions(ynabAPI, {
799
- budget_id: testBudgetId,
800
- transactions: [
801
- {
802
- id: validTransactionId,
803
- memo: 'Valid update',
804
- },
805
- {
806
- id: 'invalid-transaction-id-12345',
807
- memo: 'This should fail',
808
- original_account_id: testAccountId,
809
- original_date: new Date().toISOString().slice(0, 10),
810
- },
811
- ],
812
- });
813
-
814
- const updateResponse = parseToolResult(updateResult);
815
-
816
- if (updateResponse.error) {
817
- throw new Error(
818
- `Tool execution failed unexpectedly: ${JSON.stringify(updateResponse.error)}`,
819
- );
820
- }
821
-
822
- expect(updateResponse.summary.total_requested).toBe(2);
823
- expect(updateResponse.summary.updated).toBe(1);
824
- expect(updateResponse.summary.failed).toBeGreaterThan(0);
825
-
826
- console.warn(
827
- `✅ Partial failure handled: ${updateResponse.summary.updated} updated, ${updateResponse.summary.failed} failed`,
828
- );
829
- },
830
- );
831
- });
22
+ describeIntegration("Transaction Tools Integration", () => {
23
+ let ynabAPI: ynab.API;
24
+ let testBudgetId: string;
25
+ let testAccountId: string;
26
+ let secondaryAccountId: string | undefined;
27
+
28
+ beforeAll(async () => {
29
+ const accessToken = process.env.YNAB_ACCESS_TOKEN!;
30
+ ynabAPI = new ynab.API(accessToken);
31
+
32
+ // Get the first budget for testing
33
+ const budgetsResponse = await ynabAPI.budgets.getBudgets();
34
+ testBudgetId = budgetsResponse.data.budgets[0].id;
35
+
36
+ // Get the first account for testing
37
+ const accountsResponse = await ynabAPI.accounts.getAccounts(testBudgetId);
38
+ const accounts = accountsResponse.data.accounts;
39
+ testAccountId = accounts[0].id;
40
+ secondaryAccountId = accounts[1]?.id;
41
+ });
42
+
43
+ it(
44
+ "should successfully list transactions from real API",
45
+ { meta: { tier: "core", domain: "transactions" } },
46
+ async () => {
47
+ const params = {
48
+ budget_id: testBudgetId,
49
+ };
50
+
51
+ const result = await handleListTransactions(ynabAPI, params);
52
+ const response = JSON.parse(result.content[0].text);
53
+
54
+ // Handle large response case (preview_transactions instead of transactions)
55
+ const transactions =
56
+ response.transactions || response.preview_transactions;
57
+ expect(transactions).toBeDefined();
58
+ expect(Array.isArray(transactions)).toBe(true);
59
+
60
+ const count = response.total_count || transactions.length;
61
+ console.warn(`✅ Successfully listed ${count} transactions`);
62
+ },
63
+ );
64
+
65
+ it(
66
+ "should successfully list transactions with account filter",
67
+ { meta: { tier: "domain", domain: "transactions" } },
68
+ async () => {
69
+ const params = {
70
+ budget_id: testBudgetId,
71
+ account_id: testAccountId,
72
+ };
73
+
74
+ const result = await handleListTransactions(ynabAPI, params);
75
+ const response = JSON.parse(result.content[0].text);
76
+
77
+ expect(response.transactions).toBeDefined();
78
+ expect(Array.isArray(response.transactions)).toBe(true);
79
+
80
+ // All transactions should be from the specified account
81
+ response.transactions.forEach((transaction: any) => {
82
+ expect(transaction.account_id).toBe(testAccountId);
83
+ });
84
+
85
+ console.warn(
86
+ `✅ Successfully listed ${response.transactions.length} transactions for account`,
87
+ );
88
+ },
89
+ );
90
+
91
+ it(
92
+ "should successfully list transactions with date filter",
93
+ { meta: { tier: "domain", domain: "transactions" } },
94
+ async () => {
95
+ const params = {
96
+ budget_id: testBudgetId,
97
+ since_date: "2024-01-01",
98
+ };
99
+
100
+ const result = await handleListTransactions(ynabAPI, params);
101
+ const response = JSON.parse(result.content[0].text);
102
+
103
+ // Handle large response case (preview_transactions instead of transactions)
104
+ const transactions =
105
+ response.transactions || response.preview_transactions;
106
+ expect(transactions).toBeDefined();
107
+ expect(Array.isArray(transactions)).toBe(true);
108
+
109
+ const count = response.total_count || transactions.length;
110
+ console.warn(
111
+ `✅ Successfully listed ${count} transactions since 2024-01-01`,
112
+ );
113
+ },
114
+ );
115
+
116
+ it(
117
+ "should get transaction details if transactions exist",
118
+ { meta: { tier: "core", domain: "transactions" } },
119
+ async () => {
120
+ // First get a list of transactions to find one to test with
121
+ const listParams = {
122
+ budget_id: testBudgetId,
123
+ };
124
+
125
+ const listResult = await handleListTransactions(ynabAPI, listParams);
126
+ const listResponse = JSON.parse(listResult.content[0].text);
127
+
128
+ if (listResponse.transactions && listResponse.transactions.length > 0) {
129
+ const testTransactionId = listResponse.transactions[0].id;
130
+
131
+ const params = {
132
+ budget_id: testBudgetId,
133
+ transaction_id: testTransactionId,
134
+ };
135
+
136
+ const result = await handleGetTransaction(ynabAPI, params);
137
+ const response = JSON.parse(result.content[0].text);
138
+
139
+ expect(response.transaction).toBeDefined();
140
+ expect(response.transaction.id).toBe(testTransactionId);
141
+
142
+ console.warn(
143
+ `✅ Successfully retrieved transaction: ${response.transaction.id}`,
144
+ );
145
+ } else {
146
+ console.warn("⚠️ No transactions found to test get transaction");
147
+ }
148
+ },
149
+ );
150
+
151
+ it(
152
+ "should handle invalid budget ID gracefully",
153
+ { meta: { tier: "domain", domain: "transactions" } },
154
+ async () => {
155
+ const params = {
156
+ budget_id: "invalid-budget-id",
157
+ };
158
+
159
+ const result = await handleListTransactions(ynabAPI, params);
160
+ const response = JSON.parse(result.content[0].text);
161
+
162
+ expect(response.error).toBeDefined();
163
+ expect(response.error.message).toBeDefined();
164
+
165
+ console.warn(
166
+ `✅ Correctly handled invalid budget ID: ${response.error.message}`,
167
+ );
168
+ },
169
+ );
170
+
171
+ it(
172
+ "should handle invalid transaction ID gracefully",
173
+ { meta: { tier: "domain", domain: "transactions" } },
174
+ async () => {
175
+ const params = {
176
+ budget_id: testBudgetId,
177
+ transaction_id: "invalid-transaction-id",
178
+ };
179
+
180
+ const result = await handleGetTransaction(ynabAPI, params);
181
+ const response = JSON.parse(result.content[0].text);
182
+
183
+ expect(response.error).toBeDefined();
184
+ expect(response.error.message).toBeDefined();
185
+
186
+ console.warn(
187
+ `✅ Correctly handled invalid transaction ID: ${response.error.message}`,
188
+ );
189
+ },
190
+ );
191
+
192
+ describe("handleCreateTransactions - Integration", () => {
193
+ type BulkTransactionInput =
194
+ CreateTransactionsParams["transactions"][number];
195
+ const createdTransactionIds: string[] = [];
196
+
197
+ const parseToolResult = (toolResult: { content?: { text?: string }[] }) => {
198
+ const raw = toolResult.content?.[0]?.text ?? "{}";
199
+ try {
200
+ return JSON.parse(raw);
201
+ } catch {
202
+ throw new Error(`Unable to parse tool output: ${raw}`);
203
+ }
204
+ };
205
+
206
+ const today = () => new Date().toISOString().slice(0, 10);
207
+
208
+ const buildTransaction = (
209
+ overrides: Partial<BulkTransactionInput> = {},
210
+ ): BulkTransactionInput => {
211
+ const base: BulkTransactionInput = {
212
+ account_id: testAccountId,
213
+ amount: -1234,
214
+ date: today(),
215
+ memo: `Bulk MCP Test ${randomUUID().slice(0, 8)}`,
216
+ // YNAB import_id max length is 36 characters: "MCP:" (4) + UUID first 32 chars = 36
217
+ import_id: `MCP:${randomUUID().slice(0, 32)}`,
218
+ };
219
+ return { ...base, ...overrides };
220
+ };
221
+
222
+ const executeBulkCreate = async (
223
+ params: CreateTransactionsParams,
224
+ trackCreatedIds = true,
225
+ ): Promise<{ response: any }> => {
226
+ const result = await handleCreateTransactions(ynabAPI, params);
227
+ const response = parseToolResult(result);
228
+
229
+ if (response.error) {
230
+ console.error(
231
+ "Bulk Create Failed:",
232
+ JSON.stringify(response.error, null, 2),
233
+ );
234
+ }
235
+
236
+ if (trackCreatedIds && Array.isArray(response.results)) {
237
+ const createdIds = response.results
238
+ .filter(
239
+ (res: { status?: string; transaction_id?: string }) =>
240
+ res.status === "created" &&
241
+ typeof res.transaction_id === "string",
242
+ )
243
+ .map((res: { transaction_id: string }) => res.transaction_id);
244
+ createdTransactionIds.push(...createdIds);
245
+ }
246
+
247
+ return { response };
248
+ };
249
+
250
+ const fetchBudgetTransactions = async () => {
251
+ const listResult = await handleListTransactions(ynabAPI, {
252
+ budget_id: testBudgetId,
253
+ });
254
+ return parseToolResult(listResult);
255
+ };
256
+
257
+ afterEach(async () => {
258
+ while (createdTransactionIds.length > 0) {
259
+ const transactionId = createdTransactionIds.pop();
260
+ if (!transactionId) continue;
261
+ try {
262
+ await ynabAPI.transactions.deleteTransaction(
263
+ testBudgetId,
264
+ transactionId,
265
+ );
266
+ } catch (error) {
267
+ console.warn(
268
+ `⚠️ Failed to clean up integration test transaction ${transactionId}: ${
269
+ (error as Error).message
270
+ }`,
271
+ );
272
+ }
273
+ }
274
+ });
275
+ it(
276
+ "should create two transactions via the bulk handler",
277
+ { meta: { tier: "core", domain: "transactions" } },
278
+ async () => {
279
+ const importPrefix = randomUUID().slice(0, 30); // Keep short for import_id
280
+ const { response } = await executeBulkCreate({
281
+ budget_id: testBudgetId,
282
+ transactions: [
283
+ buildTransaction({
284
+ amount: -1500,
285
+ memo: `Bulk Pair A ${importPrefix}`,
286
+ // Max 36 chars: "MCP:" (4) + prefix (30) + ":A" (2) = 36
287
+ import_id: `MCP:${importPrefix}:A`,
288
+ }),
289
+ buildTransaction({
290
+ amount: -2500,
291
+ memo: `Bulk Pair B ${importPrefix}`,
292
+ // Max 36 chars: "MCP:" (4) + prefix (30) + ":B" (2) = 36
293
+ import_id: `MCP:${importPrefix}:B`,
294
+ }),
295
+ ],
296
+ });
297
+
298
+ expect(response.summary.created).toBe(2);
299
+ expect(response.results).toHaveLength(2);
300
+ expect(
301
+ response.results.every((res: any) => res.status === "created"),
302
+ ).toBe(true);
303
+ },
304
+ );
305
+
306
+ it(
307
+ "should detect duplicates when reusing import IDs",
308
+ { meta: { tier: "domain", domain: "transactions" } },
309
+ async () => {
310
+ const importId = `MCP:DUP:${randomUUID().slice(0, 20)}`;
311
+ await executeBulkCreate({
312
+ budget_id: testBudgetId,
313
+ transactions: [
314
+ buildTransaction({
315
+ import_id: importId,
316
+ memo: `Duplicate seed ${importId}`,
317
+ }),
318
+ ],
319
+ });
320
+
321
+ const { response } = await executeBulkCreate({
322
+ budget_id: testBudgetId,
323
+ transactions: [
324
+ buildTransaction({
325
+ import_id: importId,
326
+ memo: `Duplicate attempt ${importId}`,
327
+ }),
328
+ ],
329
+ });
330
+
331
+ if (!response.summary) {
332
+ console.error(
333
+ "Duplicate test response:",
334
+ JSON.stringify(response, null, 2),
335
+ );
336
+ }
337
+
338
+ expect(response.summary.duplicates).toBe(1);
339
+ expect(response.results[0].status).toBe("duplicate");
340
+ },
341
+ );
342
+
343
+ it(
344
+ "should invalidate caches so new transactions appear in list results",
345
+ { meta: { tier: "domain", domain: "transactions" } },
346
+ async () => {
347
+ const memo = `Cache Invalidation ${randomUUID()}`;
348
+ await fetchBudgetTransactions(); // warm cache to ensure invalidation path executes
349
+
350
+ await executeBulkCreate({
351
+ budget_id: testBudgetId,
352
+ transactions: [
353
+ buildTransaction({
354
+ memo,
355
+ amount: -4321,
356
+ // Max 36 chars: "MCP:CACHE:" (10) + 26 chars
357
+ import_id: `MCP:CACHE:${randomUUID().slice(0, 26)}`,
358
+ }),
359
+ ],
360
+ });
361
+
362
+ let transactions: any[] | undefined;
363
+ // Use 30s timeout for CI stability - YNAB API can have propagation delays
364
+ await waitFor(
365
+ async () => {
366
+ const afterList = await fetchBudgetTransactions();
367
+ transactions =
368
+ afterList.transactions ||
369
+ afterList.preview_transactions ||
370
+ afterList.transaction_preview;
371
+ return (
372
+ (transactions as any[])?.some(
373
+ (transaction) => transaction.memo === memo,
374
+ ) ?? false
375
+ );
376
+ },
377
+ 30000,
378
+ 1000,
379
+ );
380
+
381
+ expect(transactions).toBeDefined();
382
+ expect(
383
+ (transactions as any[]).some(
384
+ (transaction) => transaction.memo === memo,
385
+ ),
386
+ ).toBe(true);
387
+ },
388
+ );
389
+
390
+ it(
391
+ "should create transactions across multiple accounts within one batch",
392
+ { meta: { tier: "domain", domain: "transactions" } },
393
+ async () => {
394
+ if (!secondaryAccountId || secondaryAccountId === testAccountId) {
395
+ console.warn(
396
+ "Skipping multi-account bulk test because only one account is available in this budget.",
397
+ );
398
+ return;
399
+ }
400
+
401
+ const { response } = await executeBulkCreate({
402
+ budget_id: testBudgetId,
403
+ transactions: [
404
+ buildTransaction({
405
+ account_id: testAccountId,
406
+ memo: "Primary account bulk entry",
407
+ // Max 36 chars: "MCP:PRIMARY:" (12) + 24 chars
408
+ import_id: `MCP:PRIMARY:${randomUUID().slice(0, 24)}`,
409
+ }),
410
+ buildTransaction({
411
+ account_id: secondaryAccountId,
412
+ memo: "Secondary account bulk entry",
413
+ // Max 36 chars: "MCP:SECONDARY:" (14) + 22 chars
414
+ import_id: `MCP:SECONDARY:${randomUUID().slice(0, 22)}`,
415
+ }),
416
+ ],
417
+ });
418
+
419
+ expect(response.summary.created).toBe(2);
420
+ const accountIds = new Set(
421
+ (response.transactions ?? []).map((txn: any) => txn.account_id),
422
+ );
423
+ expect(accountIds.has(testAccountId)).toBe(true);
424
+ expect(accountIds.has(secondaryAccountId)).toBe(true);
425
+ },
426
+ );
427
+
428
+ it(
429
+ "should handle large batches and report response mode",
430
+ { meta: { tier: "domain", domain: "transactions" } },
431
+ async () => {
432
+ const batch = Array.from({ length: 50 }, (_, index) =>
433
+ buildTransaction({
434
+ amount: -1000 - index,
435
+ memo: `Bulk batch item ${index}`,
436
+ // Max 36 chars: "MCP:BATCH:" (10) + index (up to 2 chars) + ":" (1) + UUID
437
+ // With index 0-99, max prefix is 13 chars, leaving 23 for UUID
438
+ import_id: `MCP:BATCH:${index}:${randomUUID().slice(0, 23)}`,
439
+ }),
440
+ );
441
+
442
+ const { response } = await executeBulkCreate({
443
+ budget_id: testBudgetId,
444
+ transactions: batch,
445
+ });
446
+
447
+ expect(response.summary.total_requested).toBe(50);
448
+ expect(response.results).toHaveLength(50);
449
+ expect(["full", "summary", "ids_only"]).toContain(response.mode);
450
+ },
451
+ );
452
+
453
+ it(
454
+ "should support dry run mode without creating transactions",
455
+ { meta: { tier: "domain", domain: "transactions" } },
456
+ async () => {
457
+ const result = await handleCreateTransactions(ynabAPI, {
458
+ budget_id: testBudgetId,
459
+ dry_run: true,
460
+ transactions: [
461
+ buildTransaction({
462
+ memo: `Dry run ${randomUUID()}`,
463
+ }),
464
+ ],
465
+ });
466
+ const response = parseToolResult(result);
467
+ expect(response.dry_run).toBe(true);
468
+ expect(response.transactions_preview).toHaveLength(1);
469
+ expect(response.summary.total_transactions).toBe(1);
470
+ },
471
+ );
472
+
473
+ it(
474
+ "should confirm dry run does not persist data",
475
+ { meta: { tier: "domain", domain: "transactions" } },
476
+ async () => {
477
+ const memo = `DryRunNoPersist ${randomUUID()}`;
478
+ await handleCreateTransactions(ynabAPI, {
479
+ budget_id: testBudgetId,
480
+ dry_run: true,
481
+ transactions: [
482
+ buildTransaction({
483
+ memo,
484
+ }),
485
+ ],
486
+ });
487
+
488
+ const afterList = await fetchBudgetTransactions();
489
+ const transactions =
490
+ afterList.transactions ||
491
+ afterList.preview_transactions ||
492
+ afterList.transaction_preview;
493
+ const memoExists = Array.isArray(transactions)
494
+ ? transactions.some((transaction) => transaction.memo === memo)
495
+ : false;
496
+ expect(memoExists).toBe(false);
497
+ },
498
+ );
499
+
500
+ it(
501
+ "should handle invalid budget IDs gracefully during bulk create",
502
+ { meta: { tier: "domain", domain: "transactions" } },
503
+ async () => {
504
+ const result = await handleCreateTransactions(ynabAPI, {
505
+ budget_id: "invalid-budget-id",
506
+ transactions: [buildTransaction()],
507
+ });
508
+ const response = parseToolResult(result);
509
+ expect(response.error).toBeDefined();
510
+ expect(response.error.message).toBeDefined();
511
+ },
512
+ );
513
+
514
+ it(
515
+ "should handle invalid account IDs during bulk create",
516
+ { meta: { tier: "domain", domain: "transactions" } },
517
+ async () => {
518
+ const result = await handleCreateTransactions(ynabAPI, {
519
+ budget_id: testBudgetId,
520
+ transactions: [
521
+ buildTransaction({
522
+ account_id: "invalid-account-id",
523
+ // Max 36 chars: "MCP:INVALID:" (12) + 24 chars
524
+ import_id: `MCP:INVALID:${randomUUID().slice(0, 24)}`,
525
+ }),
526
+ ],
527
+ });
528
+ const response = parseToolResult(result);
529
+ expect(response.error).toBeDefined();
530
+ expect(response.error.message).toBeDefined();
531
+ },
532
+ );
533
+
534
+ it.skip(
535
+ "documents rate limiting behavior for bulk requests",
536
+ { meta: { tier: "domain", domain: "transactions" } },
537
+ () => {
538
+ // Intentionally skipped provoking API rate limits is outside automated integration scope
539
+ },
540
+ );
541
+ });
542
+
543
+ describeIntegration("Bulk Update Transactions Integration", () => {
544
+ const createdTransactionIds: string[] = [];
545
+
546
+ const parseToolResult = (result: any) => {
547
+ if (!result.content || !result.content[0]?.text) {
548
+ throw new Error("Invalid tool result structure");
549
+ }
550
+ return JSON.parse(result.content[0].text);
551
+ };
552
+
553
+ afterEach(async () => {
554
+ // Clean up created transactions
555
+ while (createdTransactionIds.length > 0) {
556
+ const transactionId = createdTransactionIds.pop();
557
+ if (!transactionId) continue;
558
+ try {
559
+ await ynabAPI.transactions.deleteTransaction(
560
+ testBudgetId,
561
+ transactionId,
562
+ );
563
+ } catch (error) {
564
+ console.warn(
565
+ `⚠️ Failed to clean up integration test transaction ${transactionId}: ${
566
+ (error as Error).message
567
+ }`,
568
+ );
569
+ }
570
+ }
571
+ });
572
+
573
+ it(
574
+ "should successfully update multiple transactions with provided metadata",
575
+ { meta: { tier: "core", domain: "transactions" } },
576
+ async () => {
577
+ // First create test transactions
578
+ const createResult = await handleCreateTransactions(ynabAPI, {
579
+ budget_id: testBudgetId,
580
+ transactions: [
581
+ {
582
+ account_id: testAccountId,
583
+ amount: -5000,
584
+ date: new Date().toISOString().slice(0, 10),
585
+ memo: "Original memo 1",
586
+ // Max 36 chars: "MCP:UPDATE-TEST-1:" (18) + 18 chars
587
+ import_id: `MCP:UPDATE-TEST-1:${randomUUID().slice(0, 18)}`,
588
+ },
589
+ {
590
+ account_id: testAccountId,
591
+ amount: -10000,
592
+ date: new Date().toISOString().slice(0, 10),
593
+ memo: "Original memo 2",
594
+ // Max 36 chars: "MCP:UPDATE-TEST-2:" (18) + 18 chars
595
+ import_id: `MCP:UPDATE-TEST-2:${randomUUID().slice(0, 18)}`,
596
+ },
597
+ ],
598
+ });
599
+
600
+ const createResponse = parseToolResult(createResult);
601
+ const transactionIds = createResponse.results
602
+ .filter((r: any) => r.status === "created")
603
+ .map((r: any) => r.transaction_id);
604
+
605
+ expect(transactionIds).toHaveLength(2);
606
+ createdTransactionIds.push(...transactionIds);
607
+
608
+ // Now update the transactions with metadata
609
+ const updateResult = await handleUpdateTransactions(ynabAPI, {
610
+ budget_id: testBudgetId,
611
+ transactions: [
612
+ {
613
+ id: transactionIds[0],
614
+ amount: -7500,
615
+ memo: "Updated memo 1",
616
+ original_account_id: testAccountId,
617
+ original_date: new Date().toISOString().slice(0, 10),
618
+ },
619
+ {
620
+ id: transactionIds[1],
621
+ memo: "Updated memo 2",
622
+ cleared: "cleared" as const,
623
+ original_account_id: testAccountId,
624
+ original_date: new Date().toISOString().slice(0, 10),
625
+ },
626
+ ],
627
+ });
628
+
629
+ const updateResponse = parseToolResult(updateResult);
630
+ expect(updateResponse.success).toBe(true);
631
+ expect(updateResponse.summary.updated).toBe(2);
632
+ expect(updateResponse.summary.failed).toBe(0);
633
+ expect(updateResponse.results).toHaveLength(2);
634
+ expect(updateResponse.results[0].status).toBe("updated");
635
+ expect(updateResponse.results[0].correlation_key).toBe(
636
+ transactionIds[0],
637
+ );
638
+ expect(updateResponse.results[1].status).toBe("updated");
639
+ expect(updateResponse.results[1].correlation_key).toBe(
640
+ transactionIds[1],
641
+ );
642
+
643
+ // Verify changes persisted - use 30s timeout for CI stability
644
+ await waitFor(
645
+ async () => {
646
+ const getResult1 = await handleGetTransaction(ynabAPI, {
647
+ budget_id: testBudgetId,
648
+ transaction_id: transactionIds[0],
649
+ });
650
+ const transaction1 = parseToolResult(getResult1).transaction;
651
+ return (
652
+ transaction1.amount === -7.5 &&
653
+ transaction1.memo === "Updated memo 1"
654
+ );
655
+ },
656
+ 30000,
657
+ 1000,
658
+ );
659
+
660
+ const getResult1 = await handleGetTransaction(ynabAPI, {
661
+ budget_id: testBudgetId,
662
+ transaction_id: transactionIds[0],
663
+ });
664
+ const transaction1 = parseToolResult(getResult1).transaction;
665
+ expect(transaction1.amount).toBe(-7.5);
666
+ expect(transaction1.memo).toBe("Updated memo 1");
667
+
668
+ await waitFor(
669
+ async () => {
670
+ const getResult2 = await handleGetTransaction(ynabAPI, {
671
+ budget_id: testBudgetId,
672
+ transaction_id: transactionIds[1],
673
+ });
674
+ const transaction2 = parseToolResult(getResult2).transaction;
675
+ return (
676
+ transaction2.memo === "Updated memo 2" &&
677
+ transaction2.cleared === "cleared"
678
+ );
679
+ },
680
+ 30000,
681
+ 1000,
682
+ );
683
+
684
+ const getResult2 = await handleGetTransaction(ynabAPI, {
685
+ budget_id: testBudgetId,
686
+ transaction_id: transactionIds[1],
687
+ });
688
+ const transaction2 = parseToolResult(getResult2).transaction;
689
+ expect(transaction2.memo).toBe("Updated memo 2");
690
+ expect(transaction2.cleared).toBe("cleared");
691
+
692
+ console.warn(
693
+ "✅ Successfully updated 2 transactions with provided metadata",
694
+ );
695
+ },
696
+ );
697
+
698
+ it(
699
+ "should successfully update transactions without metadata (using cache/API)",
700
+ { meta: { tier: "domain", domain: "transactions" } },
701
+ async () => {
702
+ // Create a test transaction
703
+ const createResult = await handleCreateTransactions(ynabAPI, {
704
+ budget_id: testBudgetId,
705
+ transactions: [
706
+ {
707
+ account_id: testAccountId,
708
+ amount: -3000,
709
+ date: new Date().toISOString().slice(0, 10),
710
+ memo: "Original",
711
+ // Max 36 chars: "MCP:UPDATE-NO-META:" (19) + 17 chars
712
+ import_id: `MCP:UPDATE-NO-META:${randomUUID().slice(0, 17)}`,
713
+ },
714
+ ],
715
+ });
716
+
717
+ const createResponse = parseToolResult(createResult);
718
+ const transactionId = createResponse.results[0].transaction_id;
719
+ createdTransactionIds.push(transactionId);
720
+
721
+ // Update without providing original_account_id/original_date
722
+ const updateResult = await handleUpdateTransactions(ynabAPI, {
723
+ budget_id: testBudgetId,
724
+ transactions: [
725
+ {
726
+ id: transactionId,
727
+ memo: "Updated without metadata",
728
+ },
729
+ ],
730
+ });
731
+
732
+ const updateResponse = parseToolResult(updateResult);
733
+ expect(updateResponse.success).toBe(true);
734
+ expect(updateResponse.summary.updated).toBe(1);
735
+
736
+ // Verify change - use 30s timeout for CI stability
737
+ await waitFor(
738
+ async () => {
739
+ const getResult = await handleGetTransaction(ynabAPI, {
740
+ budget_id: testBudgetId,
741
+ transaction_id: transactionId,
742
+ });
743
+ const transaction = parseToolResult(getResult).transaction;
744
+ return transaction.memo === "Updated without metadata";
745
+ },
746
+ 30000,
747
+ 1000,
748
+ );
749
+
750
+ const getResult = await handleGetTransaction(ynabAPI, {
751
+ budget_id: testBudgetId,
752
+ transaction_id: transactionId,
753
+ });
754
+ const transaction = parseToolResult(getResult).transaction;
755
+ expect(transaction.memo).toBe("Updated without metadata");
756
+
757
+ console.warn("✅ Successfully updated transaction without metadata");
758
+ },
759
+ );
760
+
761
+ it(
762
+ "should provide before/after preview in dry_run mode",
763
+ { meta: { tier: "domain", domain: "transactions" } },
764
+ async () => {
765
+ // Create a test transaction
766
+ const createResult = await handleCreateTransactions(ynabAPI, {
767
+ budget_id: testBudgetId,
768
+ transactions: [
769
+ {
770
+ account_id: testAccountId,
771
+ amount: -2000,
772
+ date: new Date().toISOString().slice(0, 10),
773
+ memo: "For dry run test",
774
+ // Max 36 chars: "MCP:DRY-RUN:" (12) + 24 chars
775
+ import_id: `MCP:DRY-RUN:${randomUUID().slice(0, 24)}`,
776
+ },
777
+ ],
778
+ });
779
+
780
+ const createResponse = parseToolResult(createResult);
781
+ const transactionId = createResponse.results[0].transaction_id;
782
+ createdTransactionIds.push(transactionId);
783
+
784
+ // Run dry_run update
785
+ const dryRunResult = await handleUpdateTransactions(ynabAPI, {
786
+ budget_id: testBudgetId,
787
+ transactions: [
788
+ {
789
+ id: transactionId,
790
+ amount: -5000,
791
+ memo: "Dry run update",
792
+ },
793
+ ],
794
+ dry_run: true,
795
+ });
796
+
797
+ const dryRunResponse = parseToolResult(dryRunResult);
798
+ expect(dryRunResponse.dry_run).toBe(true);
799
+ expect(dryRunResponse.transactions_preview).toHaveLength(1);
800
+
801
+ const preview = dryRunResponse.transactions_preview[0];
802
+ expect(preview.transaction_id).toBe(transactionId);
803
+ expect(preview.before).toBeDefined();
804
+ expect(preview.after).toBeDefined();
805
+
806
+ if (typeof preview.before !== "string") {
807
+ expect(preview.before.amount).toBe(-2);
808
+ expect(preview.before.memo).toBe("For dry run test");
809
+ expect(preview.after.amount).toBe(-5);
810
+ expect(preview.after.memo).toBe("Dry run update");
811
+ }
812
+
813
+ // Verify transaction was NOT actually updated
814
+ const getResult = await handleGetTransaction(ynabAPI, {
815
+ budget_id: testBudgetId,
816
+ transaction_id: transactionId,
817
+ });
818
+ const transaction = parseToolResult(getResult).transaction;
819
+ expect(transaction.amount).toBe(-2); // Should still be original amount
820
+ expect(transaction.memo).toBe("For dry run test"); // Should still be original memo
821
+
822
+ console.warn("✅ Dry run preview successful, no changes persisted");
823
+ },
824
+ );
825
+
826
+ it(
827
+ "should reject entire batch when any transaction ID is invalid",
828
+ { meta: { tier: "domain", domain: "transactions" } },
829
+ async () => {
830
+ // Create one valid transaction
831
+ const createResult = await handleCreateTransactions(ynabAPI, {
832
+ budget_id: testBudgetId,
833
+ transactions: [
834
+ {
835
+ account_id: testAccountId,
836
+ amount: -1000,
837
+ date: new Date().toISOString().slice(0, 10),
838
+ // Max 36 chars: "MCP:PARTIAL-FAIL:" (17) + 19 chars
839
+ import_id: `MCP:PARTIAL-FAIL:${randomUUID().slice(0, 19)}`,
840
+ },
841
+ ],
842
+ });
843
+
844
+ const createResponse = parseToolResult(createResult);
845
+ const validTransactionId = createResponse.results[0].transaction_id;
846
+ createdTransactionIds.push(validTransactionId);
847
+
848
+ // Try to update with one valid and one invalid ID
849
+ // YNAB API rejects the entire batch if any transaction ID is invalid
850
+ const updateResult = await handleUpdateTransactions(ynabAPI, {
851
+ budget_id: testBudgetId,
852
+ transactions: [
853
+ {
854
+ id: validTransactionId,
855
+ memo: "Valid update",
856
+ },
857
+ {
858
+ id: "invalid-transaction-id-12345",
859
+ memo: "This should fail",
860
+ original_account_id: testAccountId,
861
+ original_date: new Date().toISOString().slice(0, 10),
862
+ },
863
+ ],
864
+ });
865
+
866
+ const updateResponse = parseToolResult(updateResult);
867
+
868
+ // YNAB API does NOT support partial failures - it rejects the entire batch
869
+ // when any transaction ID is invalid (returns 400 error)
870
+ expect(updateResponse.error).toBeDefined();
871
+ expect(updateResponse.error.code).toBe(400);
872
+ expect(updateResponse.error.details).toContain(
873
+ "transaction does not exist",
874
+ );
875
+
876
+ console.warn(
877
+ `✅ Batch correctly rejected due to invalid transaction ID: ${updateResponse.error.message}`,
878
+ );
879
+ },
880
+ );
881
+ });
832
882
  });