@dizzlkheinz/ynab-mcpb 0.12.1

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 (435) hide show
  1. package/.chunkhound.json +11 -0
  2. package/.code/agents/0427d95e-edca-431f-a214-5e53264e29c4/error.txt +8 -0
  3. package/.code/agents/0d675174-d1e1-41c3-9975-4c2e275819a9/error.txt +3 -0
  4. package/.code/agents/0d8c5afd-4787-422b-abf8-2e5943fc7e67/error.txt +3 -0
  5. package/.code/agents/0ec34a70-ed5d-4b9e-bee4-bb0e4cccbc4b/error.txt +1 -0
  6. package/.code/agents/0ef51a21-1ab1-49d7-9561-0eaa43875ebc/error.txt +12 -0
  7. package/.code/agents/15db95d7-abad-4b4d-9c3b-8446089cb61d/error.txt +1 -0
  8. package/.code/agents/19ab9acb-f675-4ff0-902a-09a5476f8149/error.txt +1 -0
  9. package/.code/agents/1ef7e12d-f6ff-4897-8a9b-152d523d898e/error.txt +5 -0
  10. package/.code/agents/2465/exec-call_lroN9KKzJVWC7t5423DK1nT9.txt +1453 -0
  11. package/.code/agents/28edb6fe-95a9-41a0-ae69-aa0100d26c0c/error.txt +8 -0
  12. package/.code/agents/2ae40cf5-b4bf-42e2-92bf-7ea350a7755e/error.txt +9 -0
  13. package/.code/agents/2bfc4e1f-ac4b-45a5-b6df-bf89d4dbb54c/error.txt +1 -0
  14. package/.code/agents/2e2e1134-eff0-49be-ba25-8e2c3468a564/error.txt +5 -0
  15. package/.code/agents/3/exec-call_203OC4TNVkLxW7z2HCVEQ1cM.txt +81 -0
  16. package/.code/agents/3/exec-call_SS5T0XSiXB4LSNzUKTl75wkh.txt +610 -0
  17. package/.code/agents/3322c003-ce5e-48e3-a342-f5049c5bf9a2/error.txt +1 -0
  18. package/.code/agents/391e9b08-1ebc-468c-9bcd-6d0cc3193b37/error.txt +1 -0
  19. package/.code/agents/3ab0aa84-b7bb-4054-afa3-40b8fd7d3be0/error.txt +1 -0
  20. package/.code/agents/3bed368d-50fe-477e-aee3-a6707eaa1ab9/error.txt +3 -0
  21. package/.code/agents/3e40b925-db12-442f-8d7a-a25fc69a6672/error.txt +8 -0
  22. package/.code/agents/414d5776-cf58-41f3-9328-a6daed503a50/error.txt +5 -0
  23. package/.code/agents/42687751-4565-4610-b240-67835b17d861/error.txt +1 -0
  24. package/.code/agents/46b98876-1a39-43c9-9e2f-507ca6d47335/error.txt +9 -0
  25. package/.code/agents/4a7d9491-b26f-43dd-850d-2ecdc49b5d1b/error.txt +1 -0
  26. package/.code/agents/4e60f00a-1b3e-447f-87f3-7faf9deddec3/error.txt +13 -0
  27. package/.code/agents/5138fc1c-4d49-4b74-a7da-ccdb3a8e44e7/error.txt +14 -0
  28. package/.code/agents/521cff39-a7a3-42e5-a557-134f0f7daaa0/error.txt +5 -0
  29. package/.code/agents/53302dc5-3857-4413-9a47-9e0f64a51dc4/error.txt +5 -0
  30. package/.code/agents/567c7c2e-6a6f-4761-a08d-d36deeb2e0ac/error.txt +5 -0
  31. package/.code/agents/57b00845-80dc-47c9-953c-3028d16275d6/error.txt +3 -0
  32. package/.code/agents/593d9005-c2a5-48fd-8813-ece0d3f2de96/error.txt +1 -0
  33. package/.code/agents/5a112e66-0e1a-42f9-877c-53af56ea3551/error.txt +1 -0
  34. package/.code/agents/5b05e8ed-7788-4738-b7ee-9faa8180f992/error.txt +5 -0
  35. package/.code/agents/5f888d6f-d7ca-4ac8-be23-9ea1bf753951/error.txt +5 -0
  36. package/.code/agents/607db3ab-e4b0-435b-b497-93e9aa525549/error.txt +8 -0
  37. package/.code/agents/67dcb2a2-900f-4c78-b3fc-80b5213e0ddf/error.txt +8 -0
  38. package/.code/agents/69ad848c-4e98-49b3-b16c-0094ac2d1759/error.txt +5 -0
  39. package/.code/agents/6c9cfc5f-0d0b-445c-b121-9f60082c4f70/error.txt +1 -0
  40. package/.code/agents/6f6f8f77-4ab0-4f6e-9f30-40e8be0bd8f5/error.txt +1 -0
  41. package/.code/agents/72a7cde4-fa8a-4024-9038-27faa550539b/error.txt +1 -0
  42. package/.code/agents/7b48335c-8247-43aa-9949-5f820ba8e199/error.txt +1 -0
  43. package/.code/agents/80944249-bea9-4ac5-87de-a666c4df306e/error.txt +1 -0
  44. package/.code/agents/826099df-1b66-4186-a915-7eb59f9db19d/error.txt +5 -0
  45. package/.code/agents/8291d158-18a8-4a92-b799-4e9a4d9cce88/error.txt +1 -0
  46. package/.code/agents/82fb71a3-20fb-4341-804a-a2fc900f95bc/error.txt +1 -0
  47. package/.code/agents/855790ea-54ee-43e4-8209-a66994e37590/error.txt +1 -0
  48. package/.code/agents/88ce3a2e-04f2-42be-9062-bf97aa798da0/error.txt +3 -0
  49. package/.code/agents/9a17e398-b6ed-4218-bb55-bc64a8d38ce8/error.txt +8 -0
  50. package/.code/agents/9a4f4bfc-a2a6-4f40-a896-9335b41a7ed1/error.txt +1 -0
  51. package/.code/agents/9b633e55-ef84-47d6-94bb-fd3dd172ad97/error.txt +1 -0
  52. package/.code/agents/9b81f3ab-c72b-4a81-9a8f-28a49ddba84a/error.txt +8 -0
  53. package/.code/agents/a35daf29-b2d1-4aef-9b42-dad63a76bd47/error.txt +3 -0
  54. package/.code/agents/a81990cc-69ee-44d2-b907-17403c9bc5d7/error.txt +5 -0
  55. package/.code/agents/ab56260a-4a83-4ad4-9410-f88a23d6520a/error.txt +1 -0
  56. package/.code/agents/ad722c31-2d1d-45f7-bae2-3f02ca455b60/error.txt +1 -0
  57. package/.code/agents/b62e8690-3324-4b97-9309-731bee79416b/error.txt +5 -0
  58. package/.code/agents/baf60a3a-752b-4ad8-99d6-df32423ed2eb/error.txt +1 -0
  59. package/.code/agents/be049042-7dcb-4ac8-9beb-c8f1aea67742/error.txt +14 -0
  60. package/.code/agents/bed1dcb4-bfce-4a9f-8594-0f994962aafd/error.txt +1 -0
  61. package/.code/agents/c324a6cf-e935-4ede-9529-b3ebc18e8d6b/error.txt +5 -0
  62. package/.code/agents/c37c06ff-dfe3-43f2-9bbc-3ec73ec8f41d/error.txt +5 -0
  63. package/.code/agents/c8cd6671-433a-456b-9f88-e51cb2df6bfc/error.txt +11 -0
  64. package/.code/agents/ca2ccb67-2f24-428e-b27d-9365beadd140/error.txt +1 -0
  65. package/.code/agents/cf08c0c8-e7f0-423e-93ba-547e8e818340/error.txt +8 -0
  66. package/.code/agents/d579c74f-874b-40a4-9d56-ced1eb6a701d/error.txt +1 -0
  67. package/.code/agents/df412c98-7378-4deb-8e1e-76c416931181/error.txt +3 -0
  68. package/.code/agents/e5134eb3-2af4-45b0-8998-051cb4afdb45/error.txt +3 -0
  69. package/.code/agents/e6308471-aa45-4e9e-9496-2e9404164d97/error.txt +8 -0
  70. package/.code/agents/e7bd8bc7-23fb-4f46-98dc-b0dcf11b75a1/error.txt +1 -0
  71. package/.code/agents/e92bec35-378d-4fe1-8ac0-6e1bb3c86911/error.txt +5 -0
  72. package/.code/agents/ed918fbf-2dc4-4aa2-bfc5-04b65d9471ea/error.txt +1 -0
  73. package/.code/agents/ef1d756f-b272-48fc-8729-f05c494674f7/error.txt +1 -0
  74. package/.code/agents/ef359853-0249-4e41-a804-c0fc459fe456/error.txt +1 -0
  75. package/.code/agents/effc7b4a-4b90-40a0-8c86-a7a99d2d5fd2/error.txt +1 -0
  76. package/.code/agents/fa15f8d5-8359-4a8b-83a3-2f2056b3ff40/error.txt +3 -0
  77. package/.code/agents/fbef4193-eadf-4c8a-83ff-4878a6310f25/error.txt +8 -0
  78. package/.code/agents/fd0a4b4a-fda4-4964-a6d6-2b8a2da387c6/error.txt +1 -0
  79. package/.dxtignore +57 -0
  80. package/.env.example +44 -0
  81. package/.gemini/settings.json +8 -0
  82. package/.github/ISSUE_TEMPLATE/bug_report.md +41 -0
  83. package/.github/ISSUE_TEMPLATE/config.yml +5 -0
  84. package/.github/ISSUE_TEMPLATE/feature_request.md +24 -0
  85. package/.github/ISSUE_TEMPLATE/release_checklist.md +31 -0
  86. package/.github/pull_request_template.md +41 -0
  87. package/.github/workflows/ci-tests.yml +41 -0
  88. package/.github/workflows/claude-code-review.yml +57 -0
  89. package/.github/workflows/claude.yml +50 -0
  90. package/.github/workflows/full-integration.yml +22 -0
  91. package/.github/workflows/pr-description-check.yml +88 -0
  92. package/.github/workflows/publish.yml +33 -0
  93. package/.github/workflows/release.yml +89 -0
  94. package/.mcpbignore +58 -0
  95. package/.prettierignore +10 -0
  96. package/.prettierrc.json +10 -0
  97. package/ADOS-2-Module-1-Complete-Manual.md +757 -0
  98. package/AGENTS.md +36 -0
  99. package/CHANGELOG.md +187 -0
  100. package/CLAUDE.md +414 -0
  101. package/CODEREVIEW_RESPONSE.md +128 -0
  102. package/LICENSE +17 -0
  103. package/NUL +1 -0
  104. package/README.md +222 -0
  105. package/SCHEMA_IMPROVEMENT_SUMMARY.md +120 -0
  106. package/TESTING_NOTES.md +217 -0
  107. package/WARP.md +245 -0
  108. package/accountactivity-merged.csv +149 -0
  109. package/bin/ynab-mcp-server.cjs +4 -0
  110. package/bin/ynab-mcp-server.js +8 -0
  111. package/bundle-analysis.html +13110 -0
  112. package/dist/bundle/index.cjs +124 -0
  113. package/dist/index.d.ts +2 -0
  114. package/dist/index.js +85 -0
  115. package/dist/server/YNABMCPServer.d.ts +264 -0
  116. package/dist/server/YNABMCPServer.js +845 -0
  117. package/dist/server/budgetResolver.d.ts +15 -0
  118. package/dist/server/budgetResolver.js +99 -0
  119. package/dist/server/cacheManager.d.ts +74 -0
  120. package/dist/server/cacheManager.js +306 -0
  121. package/dist/server/config.d.ts +3 -0
  122. package/dist/server/config.js +19 -0
  123. package/dist/server/deltaCache.d.ts +61 -0
  124. package/dist/server/deltaCache.js +206 -0
  125. package/dist/server/deltaCache.merge.d.ts +9 -0
  126. package/dist/server/deltaCache.merge.js +111 -0
  127. package/dist/server/diagnostics.d.ts +90 -0
  128. package/dist/server/diagnostics.js +163 -0
  129. package/dist/server/errorHandler.d.ts +69 -0
  130. package/dist/server/errorHandler.js +524 -0
  131. package/dist/server/prompts.d.ts +31 -0
  132. package/dist/server/prompts.js +205 -0
  133. package/dist/server/rateLimiter.d.ts +27 -0
  134. package/dist/server/rateLimiter.js +82 -0
  135. package/dist/server/requestLogger.d.ts +62 -0
  136. package/dist/server/requestLogger.js +190 -0
  137. package/dist/server/resources.d.ts +39 -0
  138. package/dist/server/resources.js +85 -0
  139. package/dist/server/responseFormatter.d.ts +14 -0
  140. package/dist/server/responseFormatter.js +42 -0
  141. package/dist/server/securityMiddleware.d.ts +87 -0
  142. package/dist/server/securityMiddleware.js +117 -0
  143. package/dist/server/serverKnowledgeStore.d.ts +11 -0
  144. package/dist/server/serverKnowledgeStore.js +42 -0
  145. package/dist/server/toolRegistry.d.ts +85 -0
  146. package/dist/server/toolRegistry.js +272 -0
  147. package/dist/tools/__tests__/deltaTestUtils.d.ts +18 -0
  148. package/dist/tools/__tests__/deltaTestUtils.js +26 -0
  149. package/dist/tools/accountTools.d.ts +37 -0
  150. package/dist/tools/accountTools.js +175 -0
  151. package/dist/tools/budgetTools.d.ts +10 -0
  152. package/dist/tools/budgetTools.js +68 -0
  153. package/dist/tools/categoryTools.d.ts +27 -0
  154. package/dist/tools/categoryTools.js +232 -0
  155. package/dist/tools/compareTransactions/formatter.d.ts +71 -0
  156. package/dist/tools/compareTransactions/formatter.js +97 -0
  157. package/dist/tools/compareTransactions/index.d.ts +30 -0
  158. package/dist/tools/compareTransactions/index.js +160 -0
  159. package/dist/tools/compareTransactions/matcher.d.ts +12 -0
  160. package/dist/tools/compareTransactions/matcher.js +140 -0
  161. package/dist/tools/compareTransactions/parser.d.ts +14 -0
  162. package/dist/tools/compareTransactions/parser.js +430 -0
  163. package/dist/tools/compareTransactions/types.d.ts +27 -0
  164. package/dist/tools/compareTransactions/types.js +1 -0
  165. package/dist/tools/compareTransactions.d.ts +1 -0
  166. package/dist/tools/compareTransactions.js +1 -0
  167. package/dist/tools/deltaFetcher.d.ts +22 -0
  168. package/dist/tools/deltaFetcher.js +137 -0
  169. package/dist/tools/deltaSupport.d.ts +20 -0
  170. package/dist/tools/deltaSupport.js +176 -0
  171. package/dist/tools/exportTransactions.d.ts +17 -0
  172. package/dist/tools/exportTransactions.js +191 -0
  173. package/dist/tools/monthTools.d.ts +16 -0
  174. package/dist/tools/monthTools.js +107 -0
  175. package/dist/tools/payeeTools.d.ts +17 -0
  176. package/dist/tools/payeeTools.js +82 -0
  177. package/dist/tools/reconcileAdapter.d.ts +25 -0
  178. package/dist/tools/reconcileAdapter.js +167 -0
  179. package/dist/tools/reconciliation/analyzer.d.ts +3 -0
  180. package/dist/tools/reconciliation/analyzer.js +567 -0
  181. package/dist/tools/reconciliation/executor.d.ts +94 -0
  182. package/dist/tools/reconciliation/executor.js +611 -0
  183. package/dist/tools/reconciliation/index.d.ts +54 -0
  184. package/dist/tools/reconciliation/index.js +249 -0
  185. package/dist/tools/reconciliation/matcher.d.ts +3 -0
  186. package/dist/tools/reconciliation/matcher.js +160 -0
  187. package/dist/tools/reconciliation/payeeNormalizer.d.ts +6 -0
  188. package/dist/tools/reconciliation/payeeNormalizer.js +77 -0
  189. package/dist/tools/reconciliation/recommendationEngine.d.ts +2 -0
  190. package/dist/tools/reconciliation/recommendationEngine.js +273 -0
  191. package/dist/tools/reconciliation/reportFormatter.d.ts +13 -0
  192. package/dist/tools/reconciliation/reportFormatter.js +214 -0
  193. package/dist/tools/reconciliation/types.d.ts +172 -0
  194. package/dist/tools/reconciliation/types.js +7 -0
  195. package/dist/tools/schemas/outputs/accountOutputs.d.ts +58 -0
  196. package/dist/tools/schemas/outputs/accountOutputs.js +24 -0
  197. package/dist/tools/schemas/outputs/budgetOutputs.d.ts +48 -0
  198. package/dist/tools/schemas/outputs/budgetOutputs.js +15 -0
  199. package/dist/tools/schemas/outputs/categoryOutputs.d.ts +93 -0
  200. package/dist/tools/schemas/outputs/categoryOutputs.js +37 -0
  201. package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +269 -0
  202. package/dist/tools/schemas/outputs/comparisonOutputs.js +181 -0
  203. package/dist/tools/schemas/outputs/index.d.ts +14 -0
  204. package/dist/tools/schemas/outputs/index.js +14 -0
  205. package/dist/tools/schemas/outputs/monthOutputs.d.ts +122 -0
  206. package/dist/tools/schemas/outputs/monthOutputs.js +51 -0
  207. package/dist/tools/schemas/outputs/payeeOutputs.d.ts +34 -0
  208. package/dist/tools/schemas/outputs/payeeOutputs.js +16 -0
  209. package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +1275 -0
  210. package/dist/tools/schemas/outputs/reconciliationOutputs.js +377 -0
  211. package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +717 -0
  212. package/dist/tools/schemas/outputs/transactionMutationOutputs.js +260 -0
  213. package/dist/tools/schemas/outputs/transactionOutputs.d.ts +98 -0
  214. package/dist/tools/schemas/outputs/transactionOutputs.js +49 -0
  215. package/dist/tools/schemas/outputs/utilityOutputs.d.ts +219 -0
  216. package/dist/tools/schemas/outputs/utilityOutputs.js +120 -0
  217. package/dist/tools/schemas/shared/commonOutputs.d.ts +24 -0
  218. package/dist/tools/schemas/shared/commonOutputs.js +27 -0
  219. package/dist/tools/toolCategories.d.ts +32 -0
  220. package/dist/tools/toolCategories.js +32 -0
  221. package/dist/tools/transactionTools.d.ts +315 -0
  222. package/dist/tools/transactionTools.js +1722 -0
  223. package/dist/tools/utilityTools.d.ts +10 -0
  224. package/dist/tools/utilityTools.js +56 -0
  225. package/dist/types/index.d.ts +20 -0
  226. package/dist/types/index.js +16 -0
  227. package/dist/types/toolAnnotations.d.ts +7 -0
  228. package/dist/types/toolAnnotations.js +1 -0
  229. package/dist/utils/amountUtils.d.ts +3 -0
  230. package/dist/utils/amountUtils.js +10 -0
  231. package/dist/utils/dateUtils.d.ts +9 -0
  232. package/dist/utils/dateUtils.js +43 -0
  233. package/dist/utils/money.d.ts +21 -0
  234. package/dist/utils/money.js +51 -0
  235. package/docs/README.md +72 -0
  236. package/docs/assets/examples/reconciliation-with-recommendations.json +68 -0
  237. package/docs/assets/schemas/reconciliation-v2.json +338 -0
  238. package/docs/getting-started/CONFIGURATION.md +175 -0
  239. package/docs/getting-started/INSTALLATION.md +333 -0
  240. package/docs/getting-started/QUICKSTART.md +282 -0
  241. package/docs/guides/ARCHITECTURE.md +650 -0
  242. package/docs/guides/DEPLOYMENT.md +189 -0
  243. package/docs/guides/INTEGRATION_TESTING.md +730 -0
  244. package/docs/guides/TESTING.md +591 -0
  245. package/docs/reconciliation-flow.md +83 -0
  246. package/docs/reference/API.md +1450 -0
  247. package/docs/reference/EXAMPLES.md +946 -0
  248. package/docs/reference/TOOLS.md +348 -0
  249. package/docs/reference/TROUBLESHOOTING.md +481 -0
  250. package/esbuild.config.mjs +68 -0
  251. package/eslint.config.js +49 -0
  252. package/fix-types.sh +17 -0
  253. package/meta.json +12550 -0
  254. package/package.json +105 -0
  255. package/package.json.tmp +105 -0
  256. package/scripts/analyze-bundle.mjs +41 -0
  257. package/scripts/create-pr-description.js +203 -0
  258. package/scripts/generate-mcpb.ps1 +96 -0
  259. package/scripts/run-domain-integration-tests.js +33 -0
  260. package/scripts/run-generate-mcpb.js +29 -0
  261. package/scripts/run-throttled-integration-tests.js +116 -0
  262. package/scripts/test-delta-params.mjs +140 -0
  263. package/scripts/test-recommendations.ts +53 -0
  264. package/scripts/tmpTransaction.ts +48 -0
  265. package/scripts/validate-env.js +122 -0
  266. package/scripts/verify-build.js +105 -0
  267. package/scripts/watch-and-restart.ps1 +50 -0
  268. package/src/__tests__/comprehensive.integration.test.ts +1196 -0
  269. package/src/__tests__/delta.performance.test.ts +80 -0
  270. package/src/__tests__/performance.test.ts +725 -0
  271. package/src/__tests__/setup.ts +449 -0
  272. package/src/__tests__/testRunner.ts +444 -0
  273. package/src/__tests__/testUtils.ts +563 -0
  274. package/src/__tests__/workflows.e2e.test.ts +1675 -0
  275. package/src/index.ts +124 -0
  276. package/src/server/.gitkeep +1 -0
  277. package/src/server/YNABMCPServer.ts +1188 -0
  278. package/src/server/__tests__/YNABMCPServer.integration.test.ts +903 -0
  279. package/src/server/__tests__/YNABMCPServer.test.ts +894 -0
  280. package/src/server/__tests__/budgetResolver.test.ts +425 -0
  281. package/src/server/__tests__/cacheManager.test.ts +880 -0
  282. package/src/server/__tests__/config.test.ts +166 -0
  283. package/src/server/__tests__/deltaCache.merge.test.ts +724 -0
  284. package/src/server/__tests__/deltaCache.swr.test.ts +168 -0
  285. package/src/server/__tests__/deltaCache.test.ts +774 -0
  286. package/src/server/__tests__/diagnostics.test.ts +823 -0
  287. package/src/server/__tests__/errorHandler.integration.test.ts +466 -0
  288. package/src/server/__tests__/errorHandler.test.ts +416 -0
  289. package/src/server/__tests__/prompts.test.ts +354 -0
  290. package/src/server/__tests__/rateLimiter.test.ts +314 -0
  291. package/src/server/__tests__/requestLogger.test.ts +408 -0
  292. package/src/server/__tests__/resources.test.ts +299 -0
  293. package/src/server/__tests__/security.integration.test.ts +426 -0
  294. package/src/server/__tests__/securityMiddleware.test.ts +449 -0
  295. package/src/server/__tests__/server-startup.integration.test.ts +477 -0
  296. package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -0
  297. package/src/server/__tests__/toolRegistry.test.ts +855 -0
  298. package/src/server/budgetResolver.ts +235 -0
  299. package/src/server/cacheManager.ts +503 -0
  300. package/src/server/config.ts +41 -0
  301. package/src/server/deltaCache.merge.ts +149 -0
  302. package/src/server/deltaCache.ts +341 -0
  303. package/src/server/diagnostics.ts +338 -0
  304. package/src/server/errorHandler.ts +756 -0
  305. package/src/server/prompts.ts +291 -0
  306. package/src/server/rateLimiter.ts +156 -0
  307. package/src/server/requestLogger.ts +344 -0
  308. package/src/server/resources.ts +168 -0
  309. package/src/server/responseFormatter.ts +51 -0
  310. package/src/server/securityMiddleware.ts +236 -0
  311. package/src/server/serverKnowledgeStore.ts +91 -0
  312. package/src/server/toolRegistry.ts +489 -0
  313. package/src/tools/.gitkeep +1 -0
  314. package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -0
  315. package/src/tools/__tests__/accountTools.integration.test.ts +117 -0
  316. package/src/tools/__tests__/accountTools.test.ts +653 -0
  317. package/src/tools/__tests__/budgetTools.delta.integration.test.ts +90 -0
  318. package/src/tools/__tests__/budgetTools.integration.test.ts +134 -0
  319. package/src/tools/__tests__/budgetTools.test.ts +423 -0
  320. package/src/tools/__tests__/categoryTools.delta.integration.test.ts +80 -0
  321. package/src/tools/__tests__/categoryTools.integration.test.ts +295 -0
  322. package/src/tools/__tests__/categoryTools.test.ts +622 -0
  323. package/src/tools/__tests__/compareTransactions/formatter.test.ts +486 -0
  324. package/src/tools/__tests__/compareTransactions/index.test.ts +383 -0
  325. package/src/tools/__tests__/compareTransactions/matcher.test.ts +410 -0
  326. package/src/tools/__tests__/compareTransactions/parser.test.ts +764 -0
  327. package/src/tools/__tests__/compareTransactions.test.ts +342 -0
  328. package/src/tools/__tests__/compareTransactions.window.test.ts +147 -0
  329. package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +76 -0
  330. package/src/tools/__tests__/deltaFetcher.test.ts +270 -0
  331. package/src/tools/__tests__/deltaSupport.test.ts +188 -0
  332. package/src/tools/__tests__/deltaTestUtils.ts +46 -0
  333. package/src/tools/__tests__/exportTransactions.test.ts +213 -0
  334. package/src/tools/__tests__/monthTools.delta.integration.test.ts +80 -0
  335. package/src/tools/__tests__/monthTools.integration.test.ts +174 -0
  336. package/src/tools/__tests__/monthTools.test.ts +523 -0
  337. package/src/tools/__tests__/payeeTools.delta.integration.test.ts +80 -0
  338. package/src/tools/__tests__/payeeTools.integration.test.ts +150 -0
  339. package/src/tools/__tests__/payeeTools.test.ts +445 -0
  340. package/src/tools/__tests__/transactionTools.integration.test.ts +762 -0
  341. package/src/tools/__tests__/transactionTools.test.ts +3521 -0
  342. package/src/tools/__tests__/utilityTools.integration.test.ts +128 -0
  343. package/src/tools/__tests__/utilityTools.test.ts +205 -0
  344. package/src/tools/accountTools.ts +283 -0
  345. package/src/tools/budgetTools.ts +112 -0
  346. package/src/tools/categoryTools.ts +366 -0
  347. package/src/tools/compareTransactions/formatter.ts +163 -0
  348. package/src/tools/compareTransactions/index.ts +228 -0
  349. package/src/tools/compareTransactions/matcher.ts +240 -0
  350. package/src/tools/compareTransactions/parser.ts +557 -0
  351. package/src/tools/compareTransactions/types.ts +60 -0
  352. package/src/tools/compareTransactions.ts +3 -0
  353. package/src/tools/deltaFetcher.ts +278 -0
  354. package/src/tools/deltaSupport.ts +293 -0
  355. package/src/tools/exportTransactions.ts +273 -0
  356. package/src/tools/monthTools.ts +164 -0
  357. package/src/tools/payeeTools.ts +140 -0
  358. package/src/tools/reconcileAdapter.ts +312 -0
  359. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +122 -0
  360. package/src/tools/reconciliation/__tests__/adapter.test.ts +234 -0
  361. package/src/tools/reconciliation/__tests__/analyzer.test.ts +406 -0
  362. package/src/tools/reconciliation/__tests__/executor.integration.test.ts +366 -0
  363. package/src/tools/reconciliation/__tests__/executor.test.ts +779 -0
  364. package/src/tools/reconciliation/__tests__/matcher.test.ts +650 -0
  365. package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +278 -0
  366. package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +658 -0
  367. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1000 -0
  368. package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +151 -0
  369. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +573 -0
  370. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +78 -0
  371. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +47 -0
  372. package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +61 -0
  373. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +49 -0
  374. package/src/tools/reconciliation/analyzer.ts +824 -0
  375. package/src/tools/reconciliation/executor.ts +880 -0
  376. package/src/tools/reconciliation/index.ts +400 -0
  377. package/src/tools/reconciliation/matcher.ts +269 -0
  378. package/src/tools/reconciliation/payeeNormalizer.ts +167 -0
  379. package/src/tools/reconciliation/recommendationEngine.ts +506 -0
  380. package/src/tools/reconciliation/reportFormatter.ts +363 -0
  381. package/src/tools/reconciliation/types.ts +314 -0
  382. package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +424 -0
  383. package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +310 -0
  384. package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +448 -0
  385. package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +519 -0
  386. package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +155 -0
  387. package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +288 -0
  388. package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +478 -0
  389. package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +370 -0
  390. package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +401 -0
  391. package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +213 -0
  392. package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +474 -0
  393. package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +333 -0
  394. package/src/tools/schemas/outputs/accountOutputs.ts +137 -0
  395. package/src/tools/schemas/outputs/budgetOutputs.ts +86 -0
  396. package/src/tools/schemas/outputs/categoryOutputs.ts +194 -0
  397. package/src/tools/schemas/outputs/comparisonOutputs.ts +600 -0
  398. package/src/tools/schemas/outputs/index.ts +270 -0
  399. package/src/tools/schemas/outputs/monthOutputs.ts +243 -0
  400. package/src/tools/schemas/outputs/payeeOutputs.ts +105 -0
  401. package/src/tools/schemas/outputs/reconciliationOutputs.ts +796 -0
  402. package/src/tools/schemas/outputs/transactionMutationOutputs.ts +758 -0
  403. package/src/tools/schemas/outputs/transactionOutputs.ts +243 -0
  404. package/src/tools/schemas/outputs/utilityOutputs.ts +411 -0
  405. package/src/tools/schemas/shared/commonOutputs.ts +140 -0
  406. package/src/tools/toolCategories.ts +140 -0
  407. package/src/tools/transactionTools.ts +2509 -0
  408. package/src/tools/utilityTools.ts +90 -0
  409. package/src/types/.gitkeep +1 -0
  410. package/src/types/__tests__/index.test.ts +52 -0
  411. package/src/types/index.ts +67 -0
  412. package/src/types/integration-tests.d.ts +35 -0
  413. package/src/types/toolAnnotations.ts +44 -0
  414. package/src/utils/__tests__/dateUtils.test.ts +170 -0
  415. package/src/utils/__tests__/money.test.ts +189 -0
  416. package/src/utils/amountUtils.ts +32 -0
  417. package/src/utils/dateUtils.ts +108 -0
  418. package/src/utils/money.ts +123 -0
  419. package/test-csv-sample.csv +28 -0
  420. package/test-exports/sample_bank_statement.csv +7 -0
  421. package/test-exports/ynab_account_e9ddc2a6_minimal_1items_2025-11-19_09-04-53.json +23 -0
  422. package/test-exports/ynab_account_e9ddc2a6_minimal_1items_2025-11-19_10-37-42.json +23 -0
  423. package/test-exports/ynab_account_e9ddc2a6_minimal_4items_2025-11-19_09-02-09.json +44 -0
  424. package/test-exports/ynab_account_e9ddc2a6_minimal_6items_2025-11-19_10-37-52.json +58 -0
  425. package/test-exports/ynab_since_2025-11-01_account_4c18e9f0_minimal_14items_2025-11-16_10-07-10.json +115 -0
  426. package/test-reconcile-autodetect.js +40 -0
  427. package/test-reconcile-tool.js +152 -0
  428. package/test-reconcile-with-csv.cjs +89 -0
  429. package/test-statement.csv +8 -0
  430. package/test_debug.js +47 -0
  431. package/test_simple.mjs +16 -0
  432. package/tsconfig.json +31 -0
  433. package/tsconfig.prod.json +18 -0
  434. package/vitest-reporters/split-json-reporter.ts +211 -0
  435. package/vitest.config.ts +96 -0
@@ -0,0 +1,2509 @@
1
+ import { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
+ import * as ynab from 'ynab';
3
+ import { SaveTransaction } from 'ynab/dist/models/SaveTransaction.js';
4
+ import { SaveSubTransaction } from 'ynab/dist/models/SaveSubTransaction.js';
5
+ import type { SaveTransactionsResponseData } from 'ynab/dist/models/SaveTransactionsResponseData.js';
6
+ import { z } from 'zod/v4';
7
+ import { createHash } from 'crypto';
8
+ import { ValidationError, withToolErrorHandling } from '../types/index.js';
9
+ import { responseFormatter } from '../server/responseFormatter.js';
10
+ import { amountToMilliunits, milliunitsToAmount } from '../utils/amountUtils.js';
11
+ import { cacheManager, CACHE_TTLS, CacheManager } from '../server/cacheManager.js';
12
+ import { globalRequestLogger } from '../server/requestLogger.js';
13
+ import type { DeltaFetcher } from './deltaFetcher.js';
14
+ import type { DeltaCache } from '../server/deltaCache.js';
15
+ import type { ServerKnowledgeStore } from '../server/serverKnowledgeStore.js';
16
+ import { resolveDeltaFetcherArgs, resolveDeltaWriteArgs } from './deltaSupport.js';
17
+
18
+ /**
19
+ * Utility function to ensure transaction is not null/undefined
20
+ */
21
+ function ensureTransaction<T>(transaction: T | undefined, errorMessage: string): T {
22
+ if (!transaction) {
23
+ throw new Error(errorMessage);
24
+ }
25
+ return transaction;
26
+ }
27
+
28
+ const toMonthKey = (date: string): string => `${date.slice(0, 7)}-01`;
29
+
30
+ interface CategorySource {
31
+ category_id?: string | null;
32
+ subtransactions?: { category_id?: string | null }[] | null | undefined;
33
+ }
34
+
35
+ function appendCategoryIds(source: CategorySource | undefined, target: Set<string>): void {
36
+ if (!source) {
37
+ return;
38
+ }
39
+ if (source.category_id) {
40
+ target.add(source.category_id);
41
+ }
42
+ if (Array.isArray(source.subtransactions)) {
43
+ for (const sub of source.subtransactions) {
44
+ if (sub?.category_id) {
45
+ target.add(sub.category_id);
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ function collectCategoryIdsFromSources(...sources: (CategorySource | undefined)[]): Set<string> {
52
+ const result = new Set<string>();
53
+ for (const source of sources) {
54
+ appendCategoryIds(source, result);
55
+ }
56
+ return result;
57
+ }
58
+
59
+ function setsEqual<T>(a: Set<T>, b: Set<T>): boolean {
60
+ if (a.size !== b.size) {
61
+ return false;
62
+ }
63
+ for (const value of a) {
64
+ if (!b.has(value)) {
65
+ return false;
66
+ }
67
+ }
68
+ return true;
69
+ }
70
+
71
+ interface TransactionCacheInvalidationOptions {
72
+ affectedCategoryIds?: Set<string>;
73
+ invalidateAllCategories?: boolean;
74
+ accountTotalsChanged?: boolean;
75
+ invalidateMonths?: boolean;
76
+ }
77
+
78
+ function invalidateTransactionCaches(
79
+ deltaCache: DeltaCache,
80
+ knowledgeStore: ServerKnowledgeStore,
81
+ budgetId: string,
82
+ serverKnowledge: number | undefined,
83
+ affectedAccountIds: Set<string>,
84
+ affectedMonths: Set<string>,
85
+ options: TransactionCacheInvalidationOptions = {},
86
+ ): void {
87
+ deltaCache.invalidate(budgetId, 'transactions');
88
+ cacheManager.delete(CacheManager.generateKey('transactions', 'list', budgetId));
89
+
90
+ for (const accountId of affectedAccountIds) {
91
+ const accountPrefix = CacheManager.generateKey('transactions', 'account', budgetId, accountId);
92
+ cacheManager.deleteByPrefix(accountPrefix);
93
+ }
94
+
95
+ const invalidateAccountsList = options.accountTotalsChanged ?? true;
96
+ if (invalidateAccountsList) {
97
+ cacheManager.delete(CacheManager.generateKey('accounts', 'list', budgetId));
98
+ }
99
+ for (const accountId of affectedAccountIds) {
100
+ cacheManager.delete(CacheManager.generateKey('account', 'get', budgetId, accountId));
101
+ }
102
+
103
+ const affectedCategoryIds = options.affectedCategoryIds ?? new Set<string>();
104
+ const shouldInvalidateCategories =
105
+ options.invalidateAllCategories || affectedCategoryIds.size > 0;
106
+ if (shouldInvalidateCategories) {
107
+ cacheManager.delete(CacheManager.generateKey('categories', 'list', budgetId));
108
+ for (const categoryId of affectedCategoryIds) {
109
+ cacheManager.delete(CacheManager.generateKey('category', 'get', budgetId, categoryId));
110
+ }
111
+ }
112
+
113
+ const shouldInvalidateMonths = options.invalidateMonths ?? affectedMonths.size > 0;
114
+ if (shouldInvalidateMonths) {
115
+ cacheManager.delete(CacheManager.generateKey('months', 'list', budgetId));
116
+ deltaCache.invalidate(budgetId, 'months');
117
+ for (const month of affectedMonths) {
118
+ cacheManager.delete(CacheManager.generateKey('month', 'get', budgetId, month));
119
+ }
120
+ }
121
+
122
+ if (serverKnowledge !== undefined) {
123
+ const transactionCacheKey = CacheManager.generateKey('transactions', 'list', budgetId);
124
+ knowledgeStore.update(transactionCacheKey, serverKnowledge);
125
+ if (invalidateAccountsList) {
126
+ const accountsCacheKey = CacheManager.generateKey('accounts', 'list', budgetId);
127
+ knowledgeStore.update(accountsCacheKey, serverKnowledge);
128
+ }
129
+ if (shouldInvalidateMonths && affectedMonths.size > 0) {
130
+ const monthsCacheKey = CacheManager.generateKey('months', 'list', budgetId);
131
+ knowledgeStore.update(monthsCacheKey, serverKnowledge);
132
+ }
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Schema for ynab:list_transactions tool parameters
138
+ */
139
+ export const ListTransactionsSchema = z
140
+ .object({
141
+ budget_id: z.string().min(1, 'Budget ID is required'),
142
+ account_id: z.string().optional(),
143
+ category_id: z.string().optional(),
144
+ since_date: z
145
+ .string()
146
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
147
+ .optional(),
148
+ type: z.enum(['uncategorized', 'unapproved']).optional(),
149
+ })
150
+ .strict();
151
+
152
+ export type ListTransactionsParams = z.infer<typeof ListTransactionsSchema>;
153
+
154
+ /**
155
+ * Schema for ynab:get_transaction tool parameters
156
+ */
157
+ export const GetTransactionSchema = z
158
+ .object({
159
+ budget_id: z.string().min(1, 'Budget ID is required'),
160
+ transaction_id: z.string().min(1, 'Transaction ID is required'),
161
+ })
162
+ .strict();
163
+
164
+ export type GetTransactionParams = z.infer<typeof GetTransactionSchema>;
165
+
166
+ /**
167
+ * Schema for ynab:create_transaction tool parameters
168
+ */
169
+ export const CreateTransactionSchema = z
170
+ .object({
171
+ budget_id: z.string().min(1, 'Budget ID is required'),
172
+ account_id: z.string().min(1, 'Account ID is required'),
173
+ amount: z.number().int('Amount must be an integer in milliunits'),
174
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)'),
175
+ payee_name: z.string().optional(),
176
+ payee_id: z.string().optional(),
177
+ category_id: z.string().optional(),
178
+ memo: z.string().optional(),
179
+ cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
180
+ approved: z.boolean().optional(),
181
+ flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
182
+ import_id: z.string().min(1, 'Import ID cannot be empty').optional(),
183
+ dry_run: z.boolean().optional(),
184
+ subtransactions: z
185
+ .array(
186
+ z
187
+ .object({
188
+ amount: z.number().int('Subtransaction amount must be an integer in milliunits'),
189
+ payee_name: z.string().optional(),
190
+ payee_id: z.string().optional(),
191
+ category_id: z.string().optional(),
192
+ memo: z.string().optional(),
193
+ })
194
+ .strict(),
195
+ )
196
+ .min(1, 'At least one subtransaction is required when provided')
197
+ .optional(),
198
+ })
199
+ .strict()
200
+ .superRefine((data, ctx) => {
201
+ if (data.subtransactions && data.subtransactions.length > 0) {
202
+ const total = data.subtransactions.reduce((sum, sub) => sum + sub.amount, 0);
203
+ if (total !== data.amount) {
204
+ ctx.addIssue({
205
+ code: z.ZodIssueCode.custom,
206
+ message: 'Amount must equal the sum of subtransaction amounts',
207
+ path: ['amount'],
208
+ });
209
+ }
210
+ }
211
+ });
212
+
213
+ export type CreateTransactionParams = z.infer<typeof CreateTransactionSchema>;
214
+
215
+ const BulkTransactionInputSchemaBase = CreateTransactionSchema.pick({
216
+ account_id: true,
217
+ amount: true,
218
+ date: true,
219
+ payee_name: true,
220
+ payee_id: true,
221
+ category_id: true,
222
+ memo: true,
223
+ cleared: true,
224
+ approved: true,
225
+ flag_color: true,
226
+ import_id: true,
227
+ });
228
+
229
+ type BulkTransactionInput = Omit<
230
+ CreateTransactionParams,
231
+ 'budget_id' | 'dry_run' | 'subtransactions'
232
+ >;
233
+
234
+ const BulkTransactionInputSchema = BulkTransactionInputSchemaBase.extend({
235
+ subtransactions: z.any().optional(),
236
+ })
237
+ .strict()
238
+ .superRefine((data, ctx) => {
239
+ if (data.subtransactions !== undefined) {
240
+ ctx.addIssue({
241
+ code: z.ZodIssueCode.custom,
242
+ message: 'Subtransactions are not supported in bulk transaction creation',
243
+ path: ['subtransactions'],
244
+ });
245
+ }
246
+ })
247
+ .transform((data): BulkTransactionInput => {
248
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
249
+ const { subtransactions, ...rest } = data;
250
+ return rest;
251
+ });
252
+
253
+ export const CreateTransactionsSchema = z
254
+ .object({
255
+ budget_id: z.string().min(1, 'Budget ID is required'),
256
+ transactions: z
257
+ .array(BulkTransactionInputSchema)
258
+ .min(1, 'At least one transaction is required')
259
+ .max(100, 'A maximum of 100 transactions may be created at once'),
260
+ dry_run: z.boolean().optional(),
261
+ })
262
+ .strict();
263
+
264
+ export type CreateTransactionsParams = z.infer<typeof CreateTransactionsSchema>;
265
+
266
+ export interface BulkTransactionResult {
267
+ request_index: number;
268
+ status: 'created' | 'duplicate' | 'failed';
269
+ transaction_id?: string | undefined;
270
+ correlation_key: string;
271
+ error_code?: string | undefined;
272
+ error?: string | undefined;
273
+ }
274
+
275
+ export interface BulkCreateResponse {
276
+ success: boolean;
277
+ server_knowledge?: number;
278
+ summary: {
279
+ total_requested: number;
280
+ created: number;
281
+ duplicates: number;
282
+ failed: number;
283
+ };
284
+ results: BulkTransactionResult[];
285
+ transactions?: ynab.TransactionDetail[];
286
+ duplicate_import_ids?: string[];
287
+ message?: string;
288
+ mode?: 'full' | 'summary' | 'ids_only';
289
+ }
290
+
291
+ const FULL_RESPONSE_THRESHOLD = 64 * 1024;
292
+ const SUMMARY_RESPONSE_THRESHOLD = 96 * 1024;
293
+ const MAX_RESPONSE_BYTES = 100 * 1024;
294
+
295
+ export function generateCorrelationKey(transaction: {
296
+ account_id?: string;
297
+ date?: string;
298
+ amount?: number;
299
+ payee_id?: string | null;
300
+ payee_name?: string | null;
301
+ category_id?: string | null;
302
+ memo?: string | null;
303
+ cleared?: ynab.TransactionClearedStatus;
304
+ approved?: boolean;
305
+ flag_color?: ynab.TransactionFlagColor | null;
306
+ import_id?: string | null;
307
+ }): string {
308
+ if (transaction.import_id) {
309
+ return transaction.import_id;
310
+ }
311
+
312
+ const segments = [
313
+ `account:${transaction.account_id ?? ''}`,
314
+ `date:${transaction.date ?? ''}`,
315
+ `amount:${transaction.amount ?? 0}`,
316
+ `payee:${transaction.payee_id ?? transaction.payee_name ?? ''}`,
317
+ `category:${transaction.category_id ?? ''}`,
318
+ `memo:${transaction.memo ?? ''}`,
319
+ `cleared:${transaction.cleared ?? ''}`,
320
+ `approved:${transaction.approved ?? false}`,
321
+ `flag:${transaction.flag_color ?? ''}`,
322
+ ];
323
+
324
+ const normalized = segments.join('|');
325
+ const hash = createHash('sha256').update(normalized).digest('hex').slice(0, 16);
326
+ return `hash:${hash}`;
327
+ }
328
+
329
+ type CorrelationPayload = Parameters<typeof generateCorrelationKey>[0];
330
+
331
+ interface CorrelationPayloadInput {
332
+ account_id?: string | undefined;
333
+ date?: string | undefined;
334
+ amount?: number | undefined;
335
+ payee_id?: string | null | undefined;
336
+ payee_name?: string | null | undefined;
337
+ category_id?: string | null | undefined;
338
+ memo?: string | null | undefined;
339
+ cleared?: ynab.TransactionClearedStatus | undefined;
340
+ approved?: boolean | undefined;
341
+ flag_color?: ynab.TransactionFlagColor | null | undefined;
342
+ import_id?: string | null | undefined;
343
+ }
344
+
345
+ export function toCorrelationPayload(transaction: CorrelationPayloadInput): CorrelationPayload {
346
+ const payload: CorrelationPayload = {};
347
+ if (transaction.account_id !== undefined) {
348
+ payload.account_id = transaction.account_id;
349
+ }
350
+ if (transaction.date !== undefined) {
351
+ payload.date = transaction.date;
352
+ }
353
+ if (transaction.amount !== undefined) {
354
+ payload.amount = transaction.amount;
355
+ }
356
+ if (transaction.cleared !== undefined) {
357
+ payload.cleared = transaction.cleared;
358
+ }
359
+ if (transaction.approved !== undefined) {
360
+ payload.approved = transaction.approved;
361
+ }
362
+ if (transaction.flag_color !== undefined) {
363
+ payload.flag_color = transaction.flag_color;
364
+ }
365
+ payload.payee_id = transaction.payee_id ?? null;
366
+ payload.payee_name = transaction.payee_name ?? null;
367
+ payload.category_id = transaction.category_id ?? null;
368
+ payload.memo = transaction.memo ?? null;
369
+ payload.import_id = transaction.import_id ?? null;
370
+ return payload;
371
+ }
372
+
373
+ export function correlateResults(
374
+ requests: BulkTransactionInput[],
375
+ responseData: SaveTransactionsResponseData,
376
+ duplicateImportIds: Set<string>,
377
+ ): BulkTransactionResult[] {
378
+ const createdByImportId = new Map<string, string[]>();
379
+ const createdByHash = new Map<string, string[]>();
380
+ const responseTransactions = responseData.transactions ?? [];
381
+
382
+ const register = (map: Map<string, string[]>, key: string, transactionId: string): void => {
383
+ const existing = map.get(key);
384
+ if (existing) {
385
+ existing.push(transactionId);
386
+ return;
387
+ }
388
+ map.set(key, [transactionId]);
389
+ };
390
+
391
+ for (const transaction of responseTransactions) {
392
+ if (!transaction.id) {
393
+ continue;
394
+ }
395
+ const key = generateCorrelationKey(transaction);
396
+ if (key.startsWith('hash:')) {
397
+ register(createdByHash, key, transaction.id);
398
+ } else {
399
+ register(createdByImportId, key, transaction.id);
400
+ }
401
+ }
402
+
403
+ const popId = (map: Map<string, string[]>, key: string): string | undefined => {
404
+ const bucket = map.get(key);
405
+ if (!bucket || bucket.length === 0) {
406
+ return undefined;
407
+ }
408
+ const [transactionId] = bucket.splice(0, 1);
409
+ if (bucket.length === 0) {
410
+ map.delete(key);
411
+ }
412
+ return transactionId;
413
+ };
414
+
415
+ const correlatedResults: BulkTransactionResult[] = [];
416
+
417
+ for (const [index, transaction] of requests.entries()) {
418
+ const normalizedRequest = toCorrelationPayload(transaction);
419
+ const correlationKey = generateCorrelationKey(normalizedRequest);
420
+
421
+ if (transaction.import_id && duplicateImportIds.has(transaction.import_id)) {
422
+ correlatedResults.push({
423
+ request_index: index,
424
+ status: 'duplicate',
425
+ correlation_key: correlationKey,
426
+ });
427
+ continue;
428
+ }
429
+
430
+ let transactionId: string | undefined;
431
+ if (correlationKey.startsWith('hash:')) {
432
+ transactionId = popId(createdByHash, correlationKey);
433
+ } else {
434
+ transactionId = popId(createdByImportId, correlationKey);
435
+ }
436
+
437
+ if (!transactionId && !correlationKey.startsWith('hash:')) {
438
+ // Attempt hash-based fallback if import_id was not matched.
439
+ const hashKey = generateCorrelationKey(
440
+ toCorrelationPayload({ ...transaction, import_id: undefined }),
441
+ );
442
+ transactionId = popId(createdByHash, hashKey);
443
+ }
444
+
445
+ if (transactionId) {
446
+ const successResult: BulkTransactionResult = {
447
+ request_index: index,
448
+ status: 'created',
449
+ correlation_key: correlationKey,
450
+ };
451
+ successResult.transaction_id = transactionId;
452
+ correlatedResults.push(successResult);
453
+ continue;
454
+ }
455
+
456
+ globalRequestLogger.logError(
457
+ 'ynab:create_transactions',
458
+ 'correlate_results',
459
+ {
460
+ request_index: index,
461
+ correlation_key: correlationKey,
462
+ request: {
463
+ account_id: transaction.account_id,
464
+ date: transaction.date,
465
+ amount: transaction.amount,
466
+ import_id: transaction.import_id,
467
+ },
468
+ },
469
+ 'correlation_failed',
470
+ );
471
+
472
+ correlatedResults.push({
473
+ request_index: index,
474
+ status: 'failed',
475
+ correlation_key: correlationKey,
476
+ error_code: 'correlation_failed',
477
+ error: 'Unable to correlate request transaction with YNAB response',
478
+ });
479
+ }
480
+
481
+ return correlatedResults;
482
+ }
483
+
484
+ function estimatePayloadSize(payload: BulkCreateResponse | BulkUpdateResponse): number {
485
+ return Buffer.byteLength(JSON.stringify(payload), 'utf8');
486
+ }
487
+
488
+ function finalizeResponse(response: BulkCreateResponse): BulkCreateResponse {
489
+ const appendMessage = (message: string | undefined, addition: string): string => {
490
+ if (!message) {
491
+ return addition;
492
+ }
493
+ if (message.includes(addition)) {
494
+ return message;
495
+ }
496
+ return `${message} ${addition}`;
497
+ };
498
+
499
+ const fullSize = estimatePayloadSize({ ...response, mode: 'full' });
500
+ if (fullSize <= FULL_RESPONSE_THRESHOLD) {
501
+ return { ...response, mode: 'full' };
502
+ }
503
+
504
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
505
+ const { transactions, ...summaryResponse } = response;
506
+ const summaryPayload: BulkCreateResponse = {
507
+ ...summaryResponse,
508
+ message: appendMessage(
509
+ response.message,
510
+ 'Response downgraded to summary to stay under size limits.',
511
+ ),
512
+ mode: 'summary',
513
+ };
514
+
515
+ if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
516
+ return summaryPayload;
517
+ }
518
+
519
+ const idsOnlyPayload: BulkCreateResponse = {
520
+ ...summaryPayload,
521
+ results: summaryResponse.results.map((result) => ({
522
+ request_index: result.request_index,
523
+ status: result.status,
524
+ transaction_id: result.transaction_id,
525
+ correlation_key: result.correlation_key,
526
+ error: result.error,
527
+ })),
528
+ message: appendMessage(
529
+ summaryResponse.message,
530
+ 'Response downgraded to ids_only to meet 100KB limit.',
531
+ ),
532
+ mode: 'ids_only',
533
+ };
534
+
535
+ if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
536
+ return idsOnlyPayload;
537
+ }
538
+
539
+ throw new ValidationError(
540
+ 'RESPONSE_TOO_LARGE: Unable to format bulk create response within 100KB limit',
541
+ `Batch size: ${response.summary.total_requested} transactions`,
542
+ ['Reduce the batch size and retry', 'Consider splitting into multiple smaller batches'],
543
+ );
544
+ }
545
+
546
+ const ReceiptSplitItemSchema = z
547
+ .object({
548
+ name: z.string().min(1, 'Item name is required'),
549
+ amount: z
550
+ .number()
551
+ .finite('Item amount must be a finite number')
552
+ .refine((value) => value >= 0, 'Item amount must be zero or greater'),
553
+ quantity: z
554
+ .number()
555
+ .finite('Quantity must be a finite number')
556
+ .positive('Quantity must be greater than zero')
557
+ .optional(),
558
+ memo: z.string().optional(),
559
+ })
560
+ .strict();
561
+
562
+ const ReceiptSplitCategorySchema = z
563
+ .object({
564
+ category_id: z.string().min(1, 'Category ID is required'),
565
+ category_name: z.string().optional(),
566
+ items: z.array(ReceiptSplitItemSchema).min(1, 'Each category must include at least one item'),
567
+ })
568
+ .strict();
569
+
570
+ export const CreateReceiptSplitTransactionSchema = z
571
+ .object({
572
+ budget_id: z.string().min(1, 'Budget ID is required'),
573
+ account_id: z.string().min(1, 'Account ID is required'),
574
+ payee_name: z.string().min(1, 'Payee name is required'),
575
+ date: z
576
+ .string()
577
+ .regex(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
578
+ .optional(),
579
+ memo: z.string().optional(),
580
+ receipt_subtotal: z
581
+ .number()
582
+ .finite('Receipt subtotal must be a finite number')
583
+ .refine((value) => value >= 0, 'Receipt subtotal must be zero or greater')
584
+ .optional(),
585
+ receipt_tax: z
586
+ .number()
587
+ .finite('Receipt tax must be a finite number')
588
+ .refine((value) => value >= 0, 'Receipt tax must be zero or greater'),
589
+ receipt_total: z
590
+ .number()
591
+ .finite('Receipt total must be a finite number')
592
+ .refine((value) => value > 0, 'Receipt total must be greater than zero'),
593
+ categories: z
594
+ .array(ReceiptSplitCategorySchema)
595
+ .min(1, 'At least one categorized group is required to create a split transaction'),
596
+ cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
597
+ approved: z.boolean().optional(),
598
+ flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
599
+ dry_run: z.boolean().optional(),
600
+ })
601
+ .strict()
602
+ .superRefine((data, ctx) => {
603
+ const itemsSubtotal = data.categories
604
+ .flatMap((category) => category.items)
605
+ .reduce((sum, item) => sum + item.amount, 0);
606
+
607
+ if (data.receipt_subtotal !== undefined) {
608
+ const delta = Math.abs(data.receipt_subtotal - itemsSubtotal);
609
+ if (delta > 0.01) {
610
+ ctx.addIssue({
611
+ code: z.ZodIssueCode.custom,
612
+ message: `Receipt subtotal (${data.receipt_subtotal.toFixed(2)}) does not match categorized items total (${itemsSubtotal.toFixed(2)})`,
613
+ path: ['receipt_subtotal'],
614
+ });
615
+ }
616
+ }
617
+
618
+ const expectedTotal = itemsSubtotal + data.receipt_tax;
619
+ const deltaTotal = Math.abs(expectedTotal - data.receipt_total);
620
+ if (deltaTotal > 0.01) {
621
+ ctx.addIssue({
622
+ code: z.ZodIssueCode.custom,
623
+ message: `Receipt total (${data.receipt_total.toFixed(2)}) does not match subtotal plus tax (${expectedTotal.toFixed(2)})`,
624
+ path: ['receipt_total'],
625
+ });
626
+ }
627
+ });
628
+
629
+ export type CreateReceiptSplitTransactionParams = z.infer<
630
+ typeof CreateReceiptSplitTransactionSchema
631
+ >;
632
+
633
+ /**
634
+ * Schema for ynab:update_transaction tool parameters
635
+ */
636
+ export const UpdateTransactionSchema = z
637
+ .object({
638
+ budget_id: z.string().min(1, 'Budget ID is required'),
639
+ transaction_id: z.string().min(1, 'Transaction ID is required'),
640
+ account_id: z.string().optional(),
641
+ amount: z.number().int('Amount must be an integer in milliunits').optional(),
642
+ date: z
643
+ .string()
644
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
645
+ .optional(),
646
+ payee_name: z.string().optional(),
647
+ payee_id: z.string().optional(),
648
+ category_id: z.string().optional(),
649
+ memo: z.string().optional(),
650
+ cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
651
+ approved: z.boolean().optional(),
652
+ flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
653
+ dry_run: z.boolean().optional(),
654
+ })
655
+ .strict();
656
+
657
+ export type UpdateTransactionParams = z.infer<typeof UpdateTransactionSchema>;
658
+
659
+ /**
660
+ * Schema for bulk transaction updates - each item in the array
661
+ * Note: account_id is intentionally excluded as account moves are not supported in bulk updates
662
+ */
663
+ const BulkUpdateTransactionInputSchema = z
664
+ .object({
665
+ id: z.string().min(1, 'Transaction ID is required'),
666
+ amount: z.number().int('Amount must be an integer in milliunits').optional(),
667
+ date: z
668
+ .string()
669
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
670
+ .optional(),
671
+ payee_name: z.string().optional(),
672
+ payee_id: z.string().optional(),
673
+ category_id: z.string().optional(),
674
+ memo: z.string().optional(),
675
+ cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
676
+ approved: z.boolean().optional(),
677
+ flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
678
+ // Metadata fields for cache invalidation
679
+ original_account_id: z.string().optional(),
680
+ original_date: z
681
+ .string()
682
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
683
+ .optional(),
684
+ })
685
+ .strict();
686
+
687
+ export type BulkUpdateTransactionInput = z.infer<typeof BulkUpdateTransactionInputSchema>;
688
+
689
+ /**
690
+ * Schema for ynab:update_transactions tool parameters
691
+ */
692
+ export const UpdateTransactionsSchema = z
693
+ .object({
694
+ budget_id: z.string().min(1, 'Budget ID is required'),
695
+ transactions: z
696
+ .array(BulkUpdateTransactionInputSchema)
697
+ .min(1, 'At least one transaction is required')
698
+ .max(100, 'A maximum of 100 transactions may be updated at once'),
699
+ dry_run: z.boolean().optional(),
700
+ })
701
+ .strict();
702
+
703
+ export type UpdateTransactionsParams = z.infer<typeof UpdateTransactionsSchema>;
704
+
705
+ export interface BulkUpdateResult {
706
+ request_index: number;
707
+ status: 'updated' | 'failed';
708
+ transaction_id: string;
709
+ correlation_key: string;
710
+ error_code?: string;
711
+ error?: string;
712
+ }
713
+
714
+ export interface BulkUpdateResponse {
715
+ success: boolean;
716
+ server_knowledge?: number;
717
+ summary: {
718
+ total_requested: number;
719
+ updated: number;
720
+ failed: number;
721
+ };
722
+ results: BulkUpdateResult[];
723
+ transactions?: ynab.TransactionDetail[];
724
+ message?: string;
725
+ mode?: 'full' | 'summary' | 'ids_only';
726
+ }
727
+
728
+ /**
729
+ * Schema for ynab:delete_transaction tool parameters
730
+ */
731
+ export const DeleteTransactionSchema = z
732
+ .object({
733
+ budget_id: z.string().min(1, 'Budget ID is required'),
734
+ transaction_id: z.string().min(1, 'Transaction ID is required'),
735
+ dry_run: z.boolean().optional(),
736
+ })
737
+ .strict();
738
+
739
+ export type DeleteTransactionParams = z.infer<typeof DeleteTransactionSchema>;
740
+
741
+ /**
742
+ * Handles the ynab:list_transactions tool call
743
+ * Lists transactions for a budget with optional filtering
744
+ */
745
+
746
+ export async function handleListTransactions(
747
+ ynabAPI: ynab.API,
748
+ deltaFetcher: DeltaFetcher,
749
+ params: ListTransactionsParams,
750
+ ): Promise<CallToolResult>;
751
+ export async function handleListTransactions(
752
+ ynabAPI: ynab.API,
753
+ params: ListTransactionsParams,
754
+ ): Promise<CallToolResult>;
755
+ export async function handleListTransactions(
756
+ ynabAPI: ynab.API,
757
+ deltaFetcherOrParams: DeltaFetcher | ListTransactionsParams,
758
+ maybeParams?: ListTransactionsParams,
759
+ ): Promise<CallToolResult> {
760
+ const { deltaFetcher, params } = resolveDeltaFetcherArgs(
761
+ ynabAPI,
762
+ deltaFetcherOrParams,
763
+ maybeParams,
764
+ );
765
+ return await withToolErrorHandling(
766
+ async () => {
767
+ // Always use cache
768
+ let transactions: (ynab.TransactionDetail | ynab.HybridTransaction)[];
769
+ let cacheHit = false;
770
+ let usedDelta = false;
771
+
772
+ if (params.account_id) {
773
+ const result = await deltaFetcher.fetchTransactionsByAccount(
774
+ params.budget_id,
775
+ params.account_id,
776
+ params.since_date,
777
+ );
778
+ transactions = result.data;
779
+ cacheHit = result.wasCached;
780
+ usedDelta = result.usedDelta;
781
+ } else if (params.category_id) {
782
+ const response = await ynabAPI.transactions.getTransactionsByCategory(
783
+ params.budget_id,
784
+ params.category_id,
785
+ params.since_date,
786
+ );
787
+ transactions = response.data.transactions;
788
+ } else {
789
+ const result = await deltaFetcher.fetchTransactions(
790
+ params.budget_id,
791
+ params.since_date,
792
+ params.type as ynab.GetTransactionsTypeEnum | undefined,
793
+ );
794
+ transactions = result.data;
795
+ cacheHit = result.wasCached;
796
+ usedDelta = result.usedDelta;
797
+ }
798
+
799
+ // Check if response might be too large for MCP
800
+ const estimatedSize = JSON.stringify(transactions).length;
801
+ const sizeLimit = 90000; // Conservative limit under 100KB
802
+
803
+ if (estimatedSize > sizeLimit) {
804
+ // Return summary and suggest export
805
+ const preview = transactions.slice(0, 50);
806
+ return {
807
+ content: [
808
+ {
809
+ type: 'text',
810
+ text: responseFormatter.format({
811
+ message: `Found ${transactions.length} transactions (${Math.round(estimatedSize / 1024)}KB). Too large to display all.`,
812
+ suggestion: "Use 'export_transactions' tool to save all transactions to a file.",
813
+ showing: `First ${preview.length} transactions:`,
814
+ total_count: transactions.length,
815
+ estimated_size_kb: Math.round(estimatedSize / 1024),
816
+ preview_transactions: preview.map((transaction) => ({
817
+ id: transaction.id,
818
+ date: transaction.date,
819
+ amount: milliunitsToAmount(transaction.amount),
820
+ memo: transaction.memo,
821
+ payee_name: transaction.payee_name,
822
+ category_name: transaction.category_name,
823
+ })),
824
+ }),
825
+ },
826
+ ],
827
+ };
828
+ }
829
+
830
+ return {
831
+ content: [
832
+ {
833
+ type: 'text',
834
+ text: responseFormatter.format({
835
+ total_count: transactions.length,
836
+ cached: cacheHit,
837
+ cache_info: cacheHit
838
+ ? `Data retrieved from cache for improved performance${usedDelta ? ' (delta merge applied)' : ''}`
839
+ : 'Fresh data retrieved from YNAB API',
840
+ transactions: transactions.map((transaction) => ({
841
+ id: transaction.id,
842
+ date: transaction.date,
843
+ amount: milliunitsToAmount(transaction.amount),
844
+ memo: transaction.memo,
845
+ cleared: transaction.cleared,
846
+ approved: transaction.approved,
847
+ flag_color: transaction.flag_color,
848
+ account_id: transaction.account_id,
849
+ payee_id: transaction.payee_id,
850
+ category_id: transaction.category_id,
851
+ transfer_account_id: transaction.transfer_account_id,
852
+ transfer_transaction_id: transaction.transfer_transaction_id,
853
+ matched_transaction_id: transaction.matched_transaction_id,
854
+ import_id: transaction.import_id,
855
+ deleted: transaction.deleted,
856
+ })),
857
+ }),
858
+ },
859
+ ],
860
+ };
861
+ },
862
+ 'ynab:list_transactions',
863
+ 'listing transactions',
864
+ );
865
+ }
866
+
867
+ /**
868
+ * Handles the ynab:get_transaction tool call
869
+ * Gets detailed information for a specific transaction
870
+ */
871
+ export async function handleGetTransaction(
872
+ ynabAPI: ynab.API,
873
+ params: GetTransactionParams,
874
+ ): Promise<CallToolResult> {
875
+ try {
876
+ const useCache = process.env['NODE_ENV'] !== 'test';
877
+
878
+ let transaction: ynab.TransactionDetail;
879
+ let cacheHit = false;
880
+
881
+ if (useCache) {
882
+ // Use enhanced CacheManager wrap method
883
+ const cacheKey = CacheManager.generateKey(
884
+ 'transaction',
885
+ 'get',
886
+ params.budget_id,
887
+ params.transaction_id,
888
+ );
889
+ cacheHit = cacheManager.has(cacheKey);
890
+ transaction = await cacheManager.wrap<ynab.TransactionDetail>(cacheKey, {
891
+ ttl: CACHE_TTLS.TRANSACTIONS,
892
+ loader: async () => {
893
+ const response = await ynabAPI.transactions.getTransactionById(
894
+ params.budget_id,
895
+ params.transaction_id,
896
+ );
897
+ return ensureTransaction(response.data.transaction, 'Transaction not found');
898
+ },
899
+ });
900
+ } else {
901
+ // Bypass cache in test environment
902
+ const response = await ynabAPI.transactions.getTransactionById(
903
+ params.budget_id,
904
+ params.transaction_id,
905
+ );
906
+ transaction = ensureTransaction(response.data.transaction, 'Transaction not found');
907
+ }
908
+
909
+ return {
910
+ content: [
911
+ {
912
+ type: 'text',
913
+ text: responseFormatter.format({
914
+ transaction: {
915
+ id: transaction.id,
916
+ date: transaction.date,
917
+ amount: milliunitsToAmount(transaction.amount),
918
+ memo: transaction.memo,
919
+ cleared: transaction.cleared,
920
+ approved: transaction.approved,
921
+ flag_color: transaction.flag_color,
922
+ account_id: transaction.account_id,
923
+ payee_id: transaction.payee_id,
924
+ category_id: transaction.category_id,
925
+ transfer_account_id: transaction.transfer_account_id,
926
+ transfer_transaction_id: transaction.transfer_transaction_id,
927
+ matched_transaction_id: transaction.matched_transaction_id,
928
+ import_id: transaction.import_id,
929
+ deleted: transaction.deleted,
930
+ account_name: transaction.account_name,
931
+ payee_name: transaction.payee_name,
932
+ category_name: transaction.category_name,
933
+ },
934
+ cached: cacheHit,
935
+ cache_info: cacheHit
936
+ ? 'Data retrieved from cache for improved performance'
937
+ : 'Fresh data retrieved from YNAB API',
938
+ }),
939
+ },
940
+ ],
941
+ };
942
+ } catch (error) {
943
+ return handleTransactionError(error, 'Failed to get transaction');
944
+ }
945
+ }
946
+
947
+ /**
948
+ * Handles the ynab:create_transaction tool call
949
+ * Creates a new transaction in the specified budget and account
950
+ */
951
+ export async function handleCreateTransaction(
952
+ ynabAPI: ynab.API,
953
+ deltaCache: DeltaCache,
954
+ knowledgeStore: ServerKnowledgeStore,
955
+ params: CreateTransactionParams,
956
+ ): Promise<CallToolResult>;
957
+ export async function handleCreateTransaction(
958
+ ynabAPI: ynab.API,
959
+ params: CreateTransactionParams,
960
+ ): Promise<CallToolResult>;
961
+ export async function handleCreateTransaction(
962
+ ynabAPI: ynab.API,
963
+ deltaCacheOrParams: DeltaCache | CreateTransactionParams,
964
+ knowledgeStoreOrParams?: ServerKnowledgeStore | CreateTransactionParams,
965
+ maybeParams?: CreateTransactionParams,
966
+ ): Promise<CallToolResult> {
967
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
968
+ deltaCacheOrParams,
969
+ knowledgeStoreOrParams,
970
+ maybeParams,
971
+ );
972
+ try {
973
+ if (params.dry_run) {
974
+ return {
975
+ content: [
976
+ {
977
+ type: 'text',
978
+ text: responseFormatter.format({
979
+ dry_run: true,
980
+ action: 'create_transaction',
981
+ request: params,
982
+ }),
983
+ },
984
+ ],
985
+ };
986
+ }
987
+ // Prepare transaction data
988
+ const transactionData: SaveTransaction = {
989
+ account_id: params.account_id,
990
+ amount: params.amount, // Already validated as integer milliunits
991
+ date: params.date,
992
+ cleared: params.cleared as ynab.TransactionClearedStatus,
993
+ flag_color: params.flag_color as ynab.TransactionFlagColor,
994
+ };
995
+ if (params.payee_name !== undefined) transactionData.payee_name = params.payee_name;
996
+ if (params.payee_id !== undefined) transactionData.payee_id = params.payee_id;
997
+ if (params.category_id !== undefined) transactionData.category_id = params.category_id;
998
+ if (params.memo !== undefined) transactionData.memo = params.memo;
999
+ if (params.approved !== undefined) transactionData.approved = params.approved;
1000
+ if (params.import_id !== undefined) transactionData.import_id = params.import_id;
1001
+ if (params.subtransactions && params.subtransactions.length > 0) {
1002
+ const subtransactions: SaveSubTransaction[] = params.subtransactions.map((subtransaction) => {
1003
+ const mapped: SaveSubTransaction = {
1004
+ amount: subtransaction.amount,
1005
+ };
1006
+
1007
+ if (subtransaction.payee_name !== undefined) mapped.payee_name = subtransaction.payee_name;
1008
+ if (subtransaction.payee_id !== undefined) mapped.payee_id = subtransaction.payee_id;
1009
+ if (subtransaction.category_id !== undefined) {
1010
+ mapped.category_id = subtransaction.category_id;
1011
+ }
1012
+ if (subtransaction.memo !== undefined) mapped.memo = subtransaction.memo;
1013
+
1014
+ return mapped;
1015
+ });
1016
+
1017
+ transactionData.subtransactions = subtransactions;
1018
+ }
1019
+
1020
+ const response = await ynabAPI.transactions.createTransaction(params.budget_id, {
1021
+ transaction: transactionData,
1022
+ });
1023
+
1024
+ const transaction = ensureTransaction(response.data.transaction, 'Transaction creation failed');
1025
+
1026
+ const affectedAccountIds = new Set<string>([transaction.account_id]);
1027
+ const affectedMonths = new Set<string>([toMonthKey(transaction.date)]);
1028
+ const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
1029
+ invalidateTransactionCaches(
1030
+ deltaCache,
1031
+ knowledgeStore,
1032
+ params.budget_id,
1033
+ response.data.server_knowledge,
1034
+ affectedAccountIds,
1035
+ affectedMonths,
1036
+ {
1037
+ affectedCategoryIds,
1038
+ accountTotalsChanged: true,
1039
+ invalidateMonths: true,
1040
+ },
1041
+ );
1042
+
1043
+ // Get the updated account balance
1044
+ const accountResponse = await ynabAPI.accounts.getAccountById(
1045
+ params.budget_id,
1046
+ transaction.account_id,
1047
+ );
1048
+ const account = accountResponse.data.account;
1049
+
1050
+ return {
1051
+ content: [
1052
+ {
1053
+ type: 'text',
1054
+ text: responseFormatter.format({
1055
+ transaction: {
1056
+ id: transaction.id,
1057
+ date: transaction.date,
1058
+ amount: milliunitsToAmount(transaction.amount),
1059
+ memo: transaction.memo,
1060
+ cleared: transaction.cleared,
1061
+ approved: transaction.approved,
1062
+ flag_color: transaction.flag_color,
1063
+ account_id: transaction.account_id,
1064
+ payee_id: transaction.payee_id,
1065
+ category_id: transaction.category_id,
1066
+ transfer_account_id: transaction.transfer_account_id,
1067
+ transfer_transaction_id: transaction.transfer_transaction_id,
1068
+ matched_transaction_id: transaction.matched_transaction_id,
1069
+ import_id: transaction.import_id,
1070
+ deleted: transaction.deleted,
1071
+ // New fields for account balance
1072
+ account_balance: account.balance,
1073
+ account_cleared_balance: account.cleared_balance,
1074
+ subtransactions: transaction.subtransactions?.map((subtransaction) => ({
1075
+ id: subtransaction.id,
1076
+ transaction_id: subtransaction.transaction_id,
1077
+ amount: milliunitsToAmount(subtransaction.amount),
1078
+ memo: subtransaction.memo,
1079
+ payee_id: subtransaction.payee_id,
1080
+ payee_name: subtransaction.payee_name,
1081
+ category_id: subtransaction.category_id,
1082
+ category_name: subtransaction.category_name,
1083
+ transfer_account_id: subtransaction.transfer_account_id,
1084
+ transfer_transaction_id: subtransaction.transfer_transaction_id,
1085
+ deleted: subtransaction.deleted,
1086
+ })),
1087
+ },
1088
+ }),
1089
+ },
1090
+ ],
1091
+ };
1092
+ } catch (error) {
1093
+ return handleTransactionError(error, 'Failed to create transaction');
1094
+ }
1095
+ }
1096
+
1097
+ interface ReceiptCategoryCalculation {
1098
+ category_id: string;
1099
+ category_name: string | undefined;
1100
+ subtotal_milliunits: number;
1101
+ tax_milliunits: number;
1102
+ items: {
1103
+ name: string;
1104
+ amount_milliunits: number;
1105
+ quantity: number | undefined;
1106
+ memo: string | undefined;
1107
+ }[];
1108
+ }
1109
+
1110
+ interface SubtransactionInput {
1111
+ amount: number;
1112
+ payee_name?: string;
1113
+ payee_id?: string;
1114
+ category_id?: string;
1115
+ memo?: string;
1116
+ }
1117
+
1118
+ function buildItemMemo(item: {
1119
+ name: string;
1120
+ quantity: number | undefined;
1121
+ memo: string | undefined;
1122
+ }): string | undefined {
1123
+ const quantitySuffix = item.quantity ? ` (x${item.quantity})` : '';
1124
+ if (item.memo && item.memo.trim().length > 0) {
1125
+ return `${item.name}${quantitySuffix} - ${item.memo}`;
1126
+ }
1127
+ if (quantitySuffix) {
1128
+ return `${item.name}${quantitySuffix}`;
1129
+ }
1130
+ return item.name;
1131
+ }
1132
+
1133
+ function distributeTaxProportionally(
1134
+ subtotalMilliunits: number,
1135
+ totalTaxMilliunits: number,
1136
+ categories: ReceiptCategoryCalculation[],
1137
+ ): void {
1138
+ if (totalTaxMilliunits === 0) {
1139
+ for (const category of categories) category.tax_milliunits = 0;
1140
+ return;
1141
+ }
1142
+
1143
+ if (subtotalMilliunits <= 0) {
1144
+ throw new Error('Receipt subtotal must be greater than zero to distribute tax');
1145
+ }
1146
+
1147
+ let allocated = 0;
1148
+ categories.forEach((category, index) => {
1149
+ if (index === categories.length - 1) {
1150
+ category.tax_milliunits = totalTaxMilliunits - allocated;
1151
+ } else {
1152
+ const proportionalTax = Math.round(
1153
+ (totalTaxMilliunits * category.subtotal_milliunits) / subtotalMilliunits,
1154
+ );
1155
+ category.tax_milliunits = proportionalTax;
1156
+ allocated += proportionalTax;
1157
+ }
1158
+ });
1159
+ }
1160
+
1161
+ export async function handleCreateReceiptSplitTransaction(
1162
+ ynabAPI: ynab.API,
1163
+ deltaCache: DeltaCache,
1164
+ knowledgeStore: ServerKnowledgeStore,
1165
+ params: CreateReceiptSplitTransactionParams,
1166
+ ): Promise<CallToolResult>;
1167
+ export async function handleCreateReceiptSplitTransaction(
1168
+ ynabAPI: ynab.API,
1169
+ params: CreateReceiptSplitTransactionParams,
1170
+ ): Promise<CallToolResult>;
1171
+ export async function handleCreateReceiptSplitTransaction(
1172
+ ynabAPI: ynab.API,
1173
+ deltaCacheOrParams: DeltaCache | CreateReceiptSplitTransactionParams,
1174
+ knowledgeStoreOrParams?: ServerKnowledgeStore | CreateReceiptSplitTransactionParams,
1175
+ maybeParams?: CreateReceiptSplitTransactionParams,
1176
+ ): Promise<CallToolResult> {
1177
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1178
+ deltaCacheOrParams,
1179
+ knowledgeStoreOrParams,
1180
+ maybeParams,
1181
+ );
1182
+ const date = params.date ?? new Date().toISOString().slice(0, 10);
1183
+
1184
+ const categoryCalculations: ReceiptCategoryCalculation[] = params.categories.map((category) => {
1185
+ const items = category.items.map((item) => ({
1186
+ name: item.name,
1187
+ amount_milliunits: amountToMilliunits(item.amount),
1188
+ quantity: item.quantity,
1189
+ memo: item.memo,
1190
+ }));
1191
+ const subtotalMilliunits = items.reduce((sum, item) => sum + item.amount_milliunits, 0);
1192
+ return {
1193
+ category_id: category.category_id,
1194
+ category_name: category.category_name,
1195
+ subtotal_milliunits: subtotalMilliunits,
1196
+ tax_milliunits: 0,
1197
+ items,
1198
+ };
1199
+ });
1200
+
1201
+ const subtotalMilliunits = categoryCalculations.reduce(
1202
+ (sum, category) => sum + category.subtotal_milliunits,
1203
+ 0,
1204
+ );
1205
+
1206
+ const declaredSubtotalMilliunits =
1207
+ params.receipt_subtotal !== undefined ? amountToMilliunits(params.receipt_subtotal) : undefined;
1208
+ if (
1209
+ declaredSubtotalMilliunits !== undefined &&
1210
+ Math.abs(declaredSubtotalMilliunits - subtotalMilliunits) > 1
1211
+ ) {
1212
+ throw new Error(
1213
+ `Categorized items subtotal (${milliunitsToAmount(subtotalMilliunits)}) does not match receipt subtotal (${milliunitsToAmount(declaredSubtotalMilliunits)})`,
1214
+ );
1215
+ }
1216
+
1217
+ const taxMilliunits = amountToMilliunits(params.receipt_tax);
1218
+ const totalMilliunits = amountToMilliunits(params.receipt_total);
1219
+ const computedTotal = subtotalMilliunits + taxMilliunits;
1220
+ if (Math.abs(computedTotal - totalMilliunits) > 1) {
1221
+ throw new Error(
1222
+ `Receipt total (${milliunitsToAmount(totalMilliunits)}) does not equal subtotal plus tax (${milliunitsToAmount(computedTotal)})`,
1223
+ );
1224
+ }
1225
+
1226
+ distributeTaxProportionally(subtotalMilliunits, taxMilliunits, categoryCalculations);
1227
+
1228
+ const subtransactions: SubtransactionInput[] = categoryCalculations.flatMap((category) => {
1229
+ const itemSubtransactions: SubtransactionInput[] = category.items.map((item) => {
1230
+ const memo = buildItemMemo({ name: item.name, quantity: item.quantity, memo: item.memo });
1231
+ const payload: SubtransactionInput = {
1232
+ amount: -item.amount_milliunits,
1233
+ category_id: category.category_id,
1234
+ };
1235
+ if (memo) payload.memo = memo;
1236
+ return payload;
1237
+ });
1238
+
1239
+ const taxSubtransaction: SubtransactionInput[] =
1240
+ category.tax_milliunits > 0
1241
+ ? [
1242
+ {
1243
+ amount: -category.tax_milliunits,
1244
+ category_id: category.category_id,
1245
+ memo: `Tax - ${category.category_name ?? 'Uncategorized'}`,
1246
+ },
1247
+ ]
1248
+ : [];
1249
+
1250
+ return [...itemSubtransactions, ...taxSubtransaction];
1251
+ });
1252
+
1253
+ const receiptSummary = {
1254
+ subtotal: milliunitsToAmount(subtotalMilliunits),
1255
+ tax: milliunitsToAmount(taxMilliunits),
1256
+ total: milliunitsToAmount(totalMilliunits),
1257
+ categories: categoryCalculations.map((category) => ({
1258
+ category_id: category.category_id,
1259
+ category_name: category.category_name,
1260
+ items: category.items.map((item) => ({
1261
+ name: item.name,
1262
+ quantity: item.quantity,
1263
+ amount: milliunitsToAmount(item.amount_milliunits),
1264
+ memo: item.memo,
1265
+ })),
1266
+ subtotal: milliunitsToAmount(category.subtotal_milliunits),
1267
+ tax: milliunitsToAmount(category.tax_milliunits),
1268
+ total: milliunitsToAmount(category.subtotal_milliunits + category.tax_milliunits),
1269
+ })),
1270
+ };
1271
+
1272
+ if (params.dry_run) {
1273
+ return {
1274
+ content: [
1275
+ {
1276
+ type: 'text',
1277
+ text: responseFormatter.format({
1278
+ dry_run: true,
1279
+ action: 'create_receipt_split_transaction',
1280
+ transaction_preview: {
1281
+ account_id: params.account_id,
1282
+ payee_name: params.payee_name,
1283
+ date,
1284
+ amount: milliunitsToAmount(totalMilliunits),
1285
+ cleared: params.cleared ?? 'uncleared',
1286
+ },
1287
+ receipt_summary: receiptSummary,
1288
+ subtransactions: subtransactions.map((subtransaction) => ({
1289
+ amount: milliunitsToAmount(-subtransaction.amount),
1290
+ category_id: subtransaction.category_id,
1291
+ memo: subtransaction.memo,
1292
+ })),
1293
+ }),
1294
+ },
1295
+ ],
1296
+ };
1297
+ }
1298
+
1299
+ const createTransactionParams: CreateTransactionParams = {
1300
+ budget_id: params.budget_id,
1301
+ account_id: params.account_id,
1302
+ amount: -totalMilliunits,
1303
+ date,
1304
+ payee_name: params.payee_name,
1305
+ memo: params.memo,
1306
+ cleared: params.cleared ?? 'uncleared',
1307
+ flag_color: params.flag_color,
1308
+ subtransactions: subtransactions,
1309
+ };
1310
+
1311
+ if (params.approved !== undefined) {
1312
+ createTransactionParams.approved = params.approved;
1313
+ }
1314
+
1315
+ const baseResult = await handleCreateTransaction(
1316
+ ynabAPI,
1317
+ deltaCache,
1318
+ knowledgeStore,
1319
+ createTransactionParams,
1320
+ );
1321
+
1322
+ const firstContent = baseResult.content?.[0];
1323
+ if (!firstContent || firstContent.type !== 'text') {
1324
+ return baseResult;
1325
+ }
1326
+
1327
+ try {
1328
+ const parsed = JSON.parse(firstContent.text) as Record<string, unknown>;
1329
+ parsed['receipt_summary'] = receiptSummary;
1330
+ firstContent.text = responseFormatter.format(parsed);
1331
+ } catch {
1332
+ // If parsing fails, return the original result without augmentation.
1333
+ }
1334
+
1335
+ return baseResult;
1336
+ }
1337
+
1338
+ /**
1339
+ * Handles the ynab:update_transaction tool call
1340
+ * Updates an existing transaction with the provided fields
1341
+ */
1342
+ export async function handleUpdateTransaction(
1343
+ ynabAPI: ynab.API,
1344
+ deltaCache: DeltaCache,
1345
+ knowledgeStore: ServerKnowledgeStore,
1346
+ params: UpdateTransactionParams,
1347
+ ): Promise<CallToolResult>;
1348
+ export async function handleUpdateTransaction(
1349
+ ynabAPI: ynab.API,
1350
+ params: UpdateTransactionParams,
1351
+ ): Promise<CallToolResult>;
1352
+ export async function handleUpdateTransaction(
1353
+ ynabAPI: ynab.API,
1354
+ deltaCacheOrParams: DeltaCache | UpdateTransactionParams,
1355
+ knowledgeStoreOrParams?: ServerKnowledgeStore | UpdateTransactionParams,
1356
+ maybeParams?: UpdateTransactionParams,
1357
+ ): Promise<CallToolResult> {
1358
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1359
+ deltaCacheOrParams,
1360
+ knowledgeStoreOrParams,
1361
+ maybeParams,
1362
+ );
1363
+ try {
1364
+ if (params.dry_run) {
1365
+ return {
1366
+ content: [
1367
+ {
1368
+ type: 'text',
1369
+ text: responseFormatter.format({
1370
+ dry_run: true,
1371
+ action: 'update_transaction',
1372
+ request: params,
1373
+ }),
1374
+ },
1375
+ ],
1376
+ };
1377
+ }
1378
+
1379
+ // Get the original transaction before updating to capture the original account_id
1380
+ const originalTransactionResponse = await ynabAPI.transactions.getTransactionById(
1381
+ params.budget_id,
1382
+ params.transaction_id,
1383
+ );
1384
+ const originalTransaction = ensureTransaction(
1385
+ originalTransactionResponse.data.transaction,
1386
+ 'Original transaction not found',
1387
+ );
1388
+
1389
+ // Prepare transaction update data - only include fields that are provided
1390
+ const transactionData: SaveTransaction = {};
1391
+
1392
+ // Only include fields that are provided in the update
1393
+ if (params.account_id !== undefined) {
1394
+ transactionData.account_id = params.account_id;
1395
+ }
1396
+ if (params.amount !== undefined) {
1397
+ transactionData.amount = params.amount;
1398
+ }
1399
+ if (params.date !== undefined) {
1400
+ transactionData.date = params.date;
1401
+ }
1402
+ if (params.payee_name !== undefined) {
1403
+ transactionData.payee_name = params.payee_name;
1404
+ }
1405
+ if (params.payee_id !== undefined) {
1406
+ transactionData.payee_id = params.payee_id;
1407
+ }
1408
+ if (params.category_id !== undefined) {
1409
+ transactionData.category_id = params.category_id;
1410
+ }
1411
+ if (params.memo !== undefined) {
1412
+ transactionData.memo = params.memo;
1413
+ }
1414
+ if (params.cleared !== undefined) {
1415
+ transactionData.cleared = params.cleared as ynab.TransactionClearedStatus;
1416
+ }
1417
+ if (params.approved !== undefined) {
1418
+ transactionData.approved = params.approved;
1419
+ }
1420
+ if (params.flag_color !== undefined) {
1421
+ transactionData.flag_color = params.flag_color as ynab.TransactionFlagColor;
1422
+ }
1423
+
1424
+ const response = await ynabAPI.transactions.updateTransaction(
1425
+ params.budget_id,
1426
+ params.transaction_id,
1427
+ {
1428
+ transaction: transactionData,
1429
+ },
1430
+ );
1431
+
1432
+ const transaction = ensureTransaction(response.data.transaction, 'Transaction update failed');
1433
+
1434
+ const specificTransactionCacheKey = CacheManager.generateKey(
1435
+ 'transaction',
1436
+ 'get',
1437
+ params.budget_id,
1438
+ params.transaction_id,
1439
+ );
1440
+ cacheManager.delete(specificTransactionCacheKey);
1441
+
1442
+ const affectedAccountIds = new Set<string>([
1443
+ originalTransaction.account_id,
1444
+ transaction.account_id,
1445
+ ]);
1446
+
1447
+ if (originalTransaction.transfer_account_id) {
1448
+ affectedAccountIds.add(originalTransaction.transfer_account_id);
1449
+ }
1450
+ if (transaction.transfer_account_id) {
1451
+ affectedAccountIds.add(transaction.transfer_account_id);
1452
+ }
1453
+
1454
+ const affectedMonths = new Set<string>([
1455
+ toMonthKey(originalTransaction.date),
1456
+ toMonthKey(transaction.date),
1457
+ ]);
1458
+ const originalCategoryIds = collectCategoryIdsFromSources(originalTransaction);
1459
+ const updatedCategoryIds = collectCategoryIdsFromSources(transaction);
1460
+ const affectedCategoryIds = new Set<string>([...originalCategoryIds, ...updatedCategoryIds]);
1461
+ const categoryChanged = !setsEqual(originalCategoryIds, updatedCategoryIds);
1462
+ const amountChanged = transaction.amount !== originalTransaction.amount;
1463
+ const accountChanged = transaction.account_id !== originalTransaction.account_id;
1464
+ const clearedChanged = transaction.cleared !== originalTransaction.cleared;
1465
+ const transferAccountChanged =
1466
+ transaction.transfer_account_id !== originalTransaction.transfer_account_id;
1467
+ const transferLinkChanged =
1468
+ transaction.transfer_transaction_id !== originalTransaction.transfer_transaction_id;
1469
+ const dateChanged = transaction.date !== originalTransaction.date;
1470
+
1471
+ invalidateTransactionCaches(
1472
+ deltaCache,
1473
+ knowledgeStore,
1474
+ params.budget_id,
1475
+ response.data.server_knowledge,
1476
+ affectedAccountIds,
1477
+ affectedMonths,
1478
+ {
1479
+ affectedCategoryIds,
1480
+ accountTotalsChanged:
1481
+ amountChanged ||
1482
+ accountChanged ||
1483
+ clearedChanged ||
1484
+ transferAccountChanged ||
1485
+ transferLinkChanged,
1486
+ invalidateMonths: amountChanged || categoryChanged || dateChanged,
1487
+ },
1488
+ );
1489
+
1490
+ // Get the updated account balance
1491
+ const accountResponse = await ynabAPI.accounts.getAccountById(
1492
+ params.budget_id,
1493
+ transaction.account_id,
1494
+ );
1495
+ const account = accountResponse.data.account;
1496
+
1497
+ return {
1498
+ content: [
1499
+ {
1500
+ type: 'text',
1501
+ text: responseFormatter.format({
1502
+ transaction: {
1503
+ id: transaction.id,
1504
+ date: transaction.date,
1505
+ amount: milliunitsToAmount(transaction.amount),
1506
+ memo: transaction.memo,
1507
+ cleared: transaction.cleared,
1508
+ approved: transaction.approved,
1509
+ flag_color: transaction.flag_color,
1510
+ account_id: transaction.account_id,
1511
+ payee_id: transaction.payee_id,
1512
+ category_id: transaction.category_id,
1513
+ transfer_account_id: transaction.transfer_account_id,
1514
+ transfer_transaction_id: transaction.transfer_transaction_id,
1515
+ matched_transaction_id: transaction.matched_transaction_id,
1516
+ import_id: transaction.import_id,
1517
+ deleted: transaction.deleted,
1518
+ },
1519
+ updated_balance: account.balance,
1520
+ updated_cleared_balance: account.cleared_balance,
1521
+ }),
1522
+ },
1523
+ ],
1524
+ };
1525
+ } catch (error) {
1526
+ return handleTransactionError(error, 'Failed to update transaction');
1527
+ }
1528
+ }
1529
+
1530
+ /**
1531
+ * Handles the ynab:delete_transaction tool call
1532
+ * Deletes a transaction from the specified budget
1533
+ */
1534
+ export async function handleDeleteTransaction(
1535
+ ynabAPI: ynab.API,
1536
+ deltaCache: DeltaCache,
1537
+ knowledgeStore: ServerKnowledgeStore,
1538
+ params: DeleteTransactionParams,
1539
+ ): Promise<CallToolResult>;
1540
+ export async function handleDeleteTransaction(
1541
+ ynabAPI: ynab.API,
1542
+ params: DeleteTransactionParams,
1543
+ ): Promise<CallToolResult>;
1544
+ export async function handleDeleteTransaction(
1545
+ ynabAPI: ynab.API,
1546
+ deltaCacheOrParams: DeltaCache | DeleteTransactionParams,
1547
+ knowledgeStoreOrParams?: ServerKnowledgeStore | DeleteTransactionParams,
1548
+ maybeParams?: DeleteTransactionParams,
1549
+ ): Promise<CallToolResult> {
1550
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1551
+ deltaCacheOrParams,
1552
+ knowledgeStoreOrParams,
1553
+ maybeParams,
1554
+ );
1555
+ try {
1556
+ if (params.dry_run) {
1557
+ return {
1558
+ content: [
1559
+ {
1560
+ type: 'text',
1561
+ text: responseFormatter.format({
1562
+ dry_run: true,
1563
+ action: 'delete_transaction',
1564
+ request: params,
1565
+ }),
1566
+ },
1567
+ ],
1568
+ };
1569
+ }
1570
+ const response = await ynabAPI.transactions.deleteTransaction(
1571
+ params.budget_id,
1572
+ params.transaction_id,
1573
+ );
1574
+
1575
+ const transaction = ensureTransaction(response.data.transaction, 'Transaction deletion failed');
1576
+
1577
+ const specificTransactionCacheKey = CacheManager.generateKey(
1578
+ 'transaction',
1579
+ 'get',
1580
+ params.budget_id,
1581
+ params.transaction_id,
1582
+ );
1583
+ cacheManager.delete(specificTransactionCacheKey);
1584
+
1585
+ const affectedAccountIds = new Set<string>([transaction.account_id]);
1586
+ if (transaction.transfer_account_id) {
1587
+ affectedAccountIds.add(transaction.transfer_account_id);
1588
+ }
1589
+
1590
+ const affectedMonths = new Set<string>([toMonthKey(transaction.date)]);
1591
+ const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
1592
+ invalidateTransactionCaches(
1593
+ deltaCache,
1594
+ knowledgeStore,
1595
+ params.budget_id,
1596
+ response.data.server_knowledge,
1597
+ affectedAccountIds,
1598
+ affectedMonths,
1599
+ {
1600
+ affectedCategoryIds,
1601
+ accountTotalsChanged: true,
1602
+ invalidateMonths: true,
1603
+ },
1604
+ );
1605
+
1606
+ // Get the updated account balance
1607
+ const accountResponse = await ynabAPI.accounts.getAccountById(
1608
+ params.budget_id,
1609
+ transaction.account_id,
1610
+ );
1611
+ const account = accountResponse.data.account;
1612
+
1613
+ return {
1614
+ content: [
1615
+ {
1616
+ type: 'text',
1617
+ text: responseFormatter.format({
1618
+ message: 'Transaction deleted successfully',
1619
+ transaction: {
1620
+ id: transaction.id,
1621
+ deleted: transaction.deleted,
1622
+ },
1623
+ updated_balance: account.balance,
1624
+ updated_cleared_balance: account.cleared_balance,
1625
+ }),
1626
+ },
1627
+ ],
1628
+ };
1629
+ } catch (error) {
1630
+ return handleTransactionError(error, 'Failed to delete transaction');
1631
+ }
1632
+ }
1633
+
1634
+ export async function handleCreateTransactions(
1635
+ ynabAPI: ynab.API,
1636
+ deltaCache: DeltaCache,
1637
+ knowledgeStore: ServerKnowledgeStore,
1638
+ params: CreateTransactionsParams,
1639
+ ): Promise<CallToolResult>;
1640
+ export async function handleCreateTransactions(
1641
+ ynabAPI: ynab.API,
1642
+ params: CreateTransactionsParams,
1643
+ ): Promise<CallToolResult>;
1644
+ export async function handleCreateTransactions(
1645
+ ynabAPI: ynab.API,
1646
+ deltaCacheOrParams: DeltaCache | CreateTransactionsParams,
1647
+ knowledgeStoreOrParams?: ServerKnowledgeStore | CreateTransactionsParams,
1648
+ maybeParams?: CreateTransactionsParams,
1649
+ ): Promise<CallToolResult> {
1650
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1651
+ deltaCacheOrParams,
1652
+ knowledgeStoreOrParams,
1653
+ maybeParams,
1654
+ );
1655
+ return (await withToolErrorHandling(
1656
+ async () => {
1657
+ const validationResult = CreateTransactionsSchema.safeParse(params);
1658
+ if (!validationResult.success) {
1659
+ type TransactionIssueIndex = number | null;
1660
+ const issuesByIndex = new Map<TransactionIssueIndex, string[]>();
1661
+ const validationIssues = validationResult.error.issues ?? [];
1662
+ for (const issue of validationIssues) {
1663
+ const transactionIndex = issue.path.find(
1664
+ (segment): segment is number => typeof segment === 'number',
1665
+ );
1666
+ const message = issue.message;
1667
+ const issueIndex: TransactionIssueIndex =
1668
+ transactionIndex !== undefined ? transactionIndex : null;
1669
+ const existing = issuesByIndex.get(issueIndex) ?? [];
1670
+ existing.push(message);
1671
+ issuesByIndex.set(issueIndex, existing);
1672
+ }
1673
+
1674
+ const details = Array.from(issuesByIndex.entries()).map(([index, errors]) => ({
1675
+ transaction_index: index,
1676
+ errors,
1677
+ }));
1678
+
1679
+ throw new ValidationError(
1680
+ 'Bulk transaction validation failed',
1681
+ JSON.stringify(details, null, 2),
1682
+ ['Ensure each transaction includes required fields', 'Limit batches to 100 items'],
1683
+ );
1684
+ }
1685
+
1686
+ const { budget_id, transactions, dry_run } = validationResult.data;
1687
+
1688
+ // Pre-flight duplicate import_id detection within batch
1689
+ const importIdMap = new Map<string, number[]>();
1690
+ for (const [index, transaction] of transactions.entries()) {
1691
+ if (transaction.import_id && transaction.import_id.trim().length > 0) {
1692
+ const existing = importIdMap.get(transaction.import_id);
1693
+ if (existing) {
1694
+ existing.push(index);
1695
+ } else {
1696
+ importIdMap.set(transaction.import_id, [index]);
1697
+ }
1698
+ }
1699
+ }
1700
+
1701
+ const duplicates = Array.from(importIdMap.entries())
1702
+ .filter(([, indices]) => indices.length > 1)
1703
+ .map(([importId, indices]) => ({ import_id: importId, indices }));
1704
+
1705
+ if (duplicates.length > 0) {
1706
+ const details = duplicates.map(({ import_id, indices }) => ({
1707
+ import_id,
1708
+ transaction_indices: indices,
1709
+ count: indices.length,
1710
+ }));
1711
+
1712
+ throw new ValidationError(
1713
+ 'Duplicate import_id values detected within batch',
1714
+ JSON.stringify(details, null, 2),
1715
+ [
1716
+ 'Ensure each transaction has a unique import_id within the batch',
1717
+ 'Remove duplicate import_id values or omit import_id to use hash-based correlation',
1718
+ ],
1719
+ );
1720
+ }
1721
+
1722
+ if (dry_run) {
1723
+ const totalAmount = transactions.reduce((sum, transaction) => sum + transaction.amount, 0);
1724
+ const accountsAffected = Array.from(
1725
+ new Set(transactions.map((transaction) => transaction.account_id)),
1726
+ );
1727
+ const categoriesAffected = Array.from(
1728
+ new Set(
1729
+ transactions
1730
+ .map((transaction) => transaction.category_id)
1731
+ .filter((id): id is string => id !== undefined),
1732
+ ),
1733
+ );
1734
+ const sortedDates = [...transactions.map((transaction) => transaction.date)].sort();
1735
+ const dateRange =
1736
+ sortedDates.length > 0
1737
+ ? { earliest: sortedDates[0], latest: sortedDates[sortedDates.length - 1] }
1738
+ : undefined;
1739
+
1740
+ const transactionsPreview = transactions.slice(0, 10).map((transaction, index) => ({
1741
+ request_index: index,
1742
+ account_id: transaction.account_id,
1743
+ date: transaction.date,
1744
+ amount: milliunitsToAmount(transaction.amount),
1745
+ memo: transaction.memo,
1746
+ payee_id: transaction.payee_id,
1747
+ payee_name: transaction.payee_name,
1748
+ category_id: transaction.category_id,
1749
+ import_id: transaction.import_id,
1750
+ }));
1751
+
1752
+ return {
1753
+ content: [
1754
+ {
1755
+ type: 'text',
1756
+ text: responseFormatter.format({
1757
+ dry_run: true,
1758
+ action: 'create_transactions',
1759
+ validation: 'passed',
1760
+ summary: {
1761
+ total_transactions: transactions.length,
1762
+ total_amount: milliunitsToAmount(totalAmount),
1763
+ accounts_affected: accountsAffected,
1764
+ date_range: dateRange,
1765
+ categories_affected: categoriesAffected,
1766
+ },
1767
+ transactions_preview: transactionsPreview,
1768
+ note: 'Dry run complete. No transactions created. No caches invalidated. No server_knowledge updated.',
1769
+ }),
1770
+ },
1771
+ ],
1772
+ };
1773
+ }
1774
+
1775
+ const saveTransactions: SaveTransaction[] = transactions.map((transaction) => {
1776
+ const payload: SaveTransaction = {
1777
+ account_id: transaction.account_id,
1778
+ amount: transaction.amount,
1779
+ date: transaction.date,
1780
+ };
1781
+
1782
+ if (transaction.payee_id !== undefined) payload.payee_id = transaction.payee_id;
1783
+ if (transaction.payee_name !== undefined) payload.payee_name = transaction.payee_name;
1784
+ if (transaction.category_id !== undefined) payload.category_id = transaction.category_id;
1785
+ if (transaction.memo !== undefined) payload.memo = transaction.memo;
1786
+ if (transaction.cleared !== undefined) payload.cleared = transaction.cleared;
1787
+ if (transaction.approved !== undefined) payload.approved = transaction.approved;
1788
+ if (transaction.flag_color !== undefined) payload.flag_color = transaction.flag_color;
1789
+ if (transaction.import_id !== undefined) payload.import_id = transaction.import_id;
1790
+
1791
+ return payload;
1792
+ });
1793
+
1794
+ const response = await ynabAPI.transactions.createTransactions(budget_id, {
1795
+ transactions: saveTransactions,
1796
+ });
1797
+
1798
+ const responseData = response.data;
1799
+ const duplicateImportIds = new Set(responseData.duplicate_import_ids ?? []);
1800
+ const results = correlateResults(transactions, responseData, duplicateImportIds);
1801
+
1802
+ const summary = {
1803
+ total_requested: transactions.length,
1804
+ created: responseData.transaction_ids?.length ?? 0,
1805
+ duplicates: duplicateImportIds.size,
1806
+ failed: results.filter((result) => result.status === 'failed').length,
1807
+ };
1808
+
1809
+ const baseResponse: BulkCreateResponse = {
1810
+ success: summary.failed === 0,
1811
+ server_knowledge: responseData.server_knowledge,
1812
+ summary,
1813
+ results,
1814
+ transactions: responseData.transactions ?? [],
1815
+ duplicate_import_ids: responseData.duplicate_import_ids ?? [],
1816
+ message: `Processed ${summary.total_requested} transactions: ${summary.created} created, ${summary.duplicates} duplicates, ${summary.failed} failed.`,
1817
+ };
1818
+
1819
+ const accountIds = new Set<string>(transactions.map((transaction) => transaction.account_id));
1820
+ const affectedMonths = new Set<string>(
1821
+ transactions.map((transaction) => toMonthKey(transaction.date)),
1822
+ );
1823
+ const affectedCategoryIds = new Set<string>();
1824
+ for (const created of responseData.transactions ?? []) {
1825
+ appendCategoryIds(created, affectedCategoryIds);
1826
+ }
1827
+ invalidateTransactionCaches(
1828
+ deltaCache,
1829
+ knowledgeStore,
1830
+ budget_id,
1831
+ responseData.server_knowledge,
1832
+ accountIds,
1833
+ affectedMonths,
1834
+ {
1835
+ affectedCategoryIds,
1836
+ accountTotalsChanged: true,
1837
+ invalidateMonths: true,
1838
+ },
1839
+ );
1840
+
1841
+ const finalizedResponse = finalizeResponse(baseResponse);
1842
+
1843
+ return {
1844
+ content: [
1845
+ {
1846
+ type: 'text',
1847
+ text: responseFormatter.format(finalizedResponse),
1848
+ },
1849
+ ],
1850
+ };
1851
+ },
1852
+ 'ynab:create_transactions',
1853
+ 'bulk transaction creation',
1854
+ )) as CallToolResult;
1855
+ }
1856
+
1857
+ /**
1858
+ * Interface for transaction metadata needed for cache invalidation
1859
+ */
1860
+ interface TransactionMetadata {
1861
+ account_id: string;
1862
+ date: string;
1863
+ }
1864
+
1865
+ /**
1866
+ * Result of metadata resolution including both resolved metadata and unresolved IDs
1867
+ */
1868
+ interface MetadataResolutionResult {
1869
+ metadata: Map<string, TransactionMetadata>;
1870
+ unresolvedIds: string[];
1871
+ previewDetails: Map<string, ynab.TransactionDetail>;
1872
+ }
1873
+
1874
+ interface ResolveMetadataOptions {
1875
+ previewTransactionIds?: string[];
1876
+ }
1877
+
1878
+ /**
1879
+ * Resolves metadata for bulk update transactions
1880
+ * Uses a multi-tier approach: request metadata -> cache -> limited API calls
1881
+ * Returns both the resolved metadata and a list of IDs that could not be resolved
1882
+ */
1883
+ async function resolveMetadata(
1884
+ ynabAPI: ynab.API,
1885
+ budgetId: string,
1886
+ transactions: BulkUpdateTransactionInput[],
1887
+ options: ResolveMetadataOptions = {},
1888
+ ): Promise<MetadataResolutionResult> {
1889
+ const metadata = new Map<string, TransactionMetadata>();
1890
+ const needsResolution: string[] = [];
1891
+ const previewIds = new Set(options.previewTransactionIds ?? []);
1892
+ const previewDetails = new Map<string, ynab.TransactionDetail>();
1893
+ const previewIdsNeedingFetch = new Set(previewIds);
1894
+
1895
+ // First pass: Use provided metadata
1896
+ for (const transaction of transactions) {
1897
+ if (transaction.original_account_id && transaction.original_date) {
1898
+ metadata.set(transaction.id, {
1899
+ account_id: transaction.original_account_id,
1900
+ date: transaction.original_date,
1901
+ });
1902
+ } else {
1903
+ needsResolution.push(transaction.id);
1904
+ }
1905
+ }
1906
+
1907
+ if (previewIds.size === 0 && needsResolution.length === 0) {
1908
+ return { metadata, unresolvedIds: [], previewDetails };
1909
+ }
1910
+
1911
+ // Second pass: hydrate from cache for both metadata needs and preview requests
1912
+ const needsResolutionSet = new Set(needsResolution);
1913
+ const cacheLookupIds = new Set<string>([...needsResolution, ...previewIds]);
1914
+ for (const transactionId of cacheLookupIds) {
1915
+ const cacheKey = CacheManager.generateKey('transaction', 'get', budgetId, transactionId);
1916
+ const cached = cacheManager.get<ynab.TransactionDetail>(cacheKey);
1917
+ if (!cached) {
1918
+ continue;
1919
+ }
1920
+
1921
+ if (needsResolutionSet.has(transactionId)) {
1922
+ metadata.set(transactionId, {
1923
+ account_id: cached.account_id,
1924
+ date: cached.date,
1925
+ });
1926
+ needsResolutionSet.delete(transactionId);
1927
+ }
1928
+ if (previewIds.has(transactionId) && !previewDetails.has(transactionId)) {
1929
+ previewDetails.set(transactionId, cached);
1930
+ previewIdsNeedingFetch.delete(transactionId);
1931
+ }
1932
+ }
1933
+
1934
+ const stillNeedsResolution = Array.from(needsResolutionSet);
1935
+ if (stillNeedsResolution.length === 0 && previewIdsNeedingFetch.size === 0) {
1936
+ return { metadata, unresolvedIds: [], previewDetails };
1937
+ }
1938
+
1939
+ // Third pass: Limited API calls with concurrency limit
1940
+ const MAX_CONCURRENT_FETCHES = 5;
1941
+ const fetchPromises: Promise<void>[] = [];
1942
+ const metadataAwaitingResolution = new Set(stillNeedsResolution);
1943
+ const idsNeedingApiFetch = Array.from(
1944
+ new Set([...stillNeedsResolution, ...previewIdsNeedingFetch]),
1945
+ );
1946
+
1947
+ for (let i = 0; i < idsNeedingApiFetch.length; i += MAX_CONCURRENT_FETCHES) {
1948
+ const batch = idsNeedingApiFetch.slice(i, i + MAX_CONCURRENT_FETCHES);
1949
+ const batchPromises = batch.map(async (transactionId) => {
1950
+ try {
1951
+ const response = await ynabAPI.transactions.getTransactionById(budgetId, transactionId);
1952
+ const transaction = response.data.transaction;
1953
+ if (transaction) {
1954
+ if (metadataAwaitingResolution.has(transactionId)) {
1955
+ metadata.set(transactionId, {
1956
+ account_id: transaction.account_id,
1957
+ date: transaction.date,
1958
+ });
1959
+ metadataAwaitingResolution.delete(transactionId);
1960
+ }
1961
+ if (previewIdsNeedingFetch.has(transactionId) && !previewDetails.has(transactionId)) {
1962
+ previewDetails.set(transactionId, transaction);
1963
+ previewIdsNeedingFetch.delete(transactionId);
1964
+ }
1965
+ }
1966
+ } catch {
1967
+ if (metadataAwaitingResolution.has(transactionId)) {
1968
+ globalRequestLogger.logError(
1969
+ 'ynab:update_transactions',
1970
+ 'resolve_metadata',
1971
+ { transaction_id: transactionId },
1972
+ 'Failed to resolve transaction metadata',
1973
+ );
1974
+ }
1975
+ }
1976
+ });
1977
+ fetchPromises.push(...batchPromises);
1978
+ }
1979
+
1980
+ await Promise.all(fetchPromises);
1981
+ return { metadata, unresolvedIds: Array.from(metadataAwaitingResolution), previewDetails };
1982
+ }
1983
+
1984
+ /**
1985
+ * Finalizes bulk update response based on size constraints
1986
+ */
1987
+ function finalizeBulkUpdateResponse(response: BulkUpdateResponse): BulkUpdateResponse {
1988
+ const appendMessage = (message: string | undefined, addition: string): string => {
1989
+ if (!message) {
1990
+ return addition;
1991
+ }
1992
+ if (message.includes(addition)) {
1993
+ return message;
1994
+ }
1995
+ return `${message} ${addition}`;
1996
+ };
1997
+
1998
+ const fullSize = estimatePayloadSize(response);
1999
+ if (fullSize <= FULL_RESPONSE_THRESHOLD) {
2000
+ return { ...response, mode: 'full' };
2001
+ }
2002
+
2003
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
2004
+ const { transactions, ...summaryResponse } = response;
2005
+ const summaryPayload: BulkUpdateResponse = {
2006
+ ...summaryResponse,
2007
+ message: appendMessage(
2008
+ response.message,
2009
+ 'Response downgraded to summary to stay under size limits.',
2010
+ ),
2011
+ mode: 'summary',
2012
+ };
2013
+
2014
+ if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
2015
+ return summaryPayload;
2016
+ }
2017
+
2018
+ const idsOnlyPayload: BulkUpdateResponse = {
2019
+ ...summaryPayload,
2020
+ results: summaryResponse.results.map((result) => {
2021
+ const simplified: BulkUpdateResult = {
2022
+ request_index: result.request_index,
2023
+ status: result.status,
2024
+ transaction_id: result.transaction_id,
2025
+ correlation_key: result.correlation_key,
2026
+ };
2027
+ if (result.error) {
2028
+ simplified.error = result.error;
2029
+ }
2030
+ if (result.error_code) {
2031
+ simplified.error_code = result.error_code;
2032
+ }
2033
+ return simplified;
2034
+ }),
2035
+ message: appendMessage(
2036
+ summaryResponse.message,
2037
+ 'Response downgraded to ids_only to meet 100KB limit.',
2038
+ ),
2039
+ mode: 'ids_only',
2040
+ };
2041
+
2042
+ if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
2043
+ return idsOnlyPayload;
2044
+ }
2045
+
2046
+ throw new ValidationError(
2047
+ 'RESPONSE_TOO_LARGE: Unable to format bulk update response within 100KB limit',
2048
+ `Batch size: ${response.summary.total_requested} transactions`,
2049
+ ['Reduce the batch size and retry', 'Consider splitting into multiple smaller batches'],
2050
+ );
2051
+ }
2052
+
2053
+ /**
2054
+ * Handles the ynab:update_transactions tool call
2055
+ * Updates multiple transactions in a single batch operation
2056
+ */
2057
+ export async function handleUpdateTransactions(
2058
+ ynabAPI: ynab.API,
2059
+ deltaCache: DeltaCache,
2060
+ knowledgeStore: ServerKnowledgeStore,
2061
+ params: UpdateTransactionsParams,
2062
+ ): Promise<CallToolResult>;
2063
+ export async function handleUpdateTransactions(
2064
+ ynabAPI: ynab.API,
2065
+ params: UpdateTransactionsParams,
2066
+ ): Promise<CallToolResult>;
2067
+ export async function handleUpdateTransactions(
2068
+ ynabAPI: ynab.API,
2069
+ deltaCacheOrParams: DeltaCache | UpdateTransactionsParams,
2070
+ knowledgeStoreOrParams?: ServerKnowledgeStore | UpdateTransactionsParams,
2071
+ maybeParams?: UpdateTransactionsParams,
2072
+ ): Promise<CallToolResult> {
2073
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
2074
+ deltaCacheOrParams,
2075
+ knowledgeStoreOrParams,
2076
+ maybeParams,
2077
+ );
2078
+ return (await withToolErrorHandling(
2079
+ async () => {
2080
+ const validationResult = UpdateTransactionsSchema.safeParse(params);
2081
+ if (!validationResult.success) {
2082
+ type TransactionIssueIndex = number | null;
2083
+ const issuesByIndex = new Map<TransactionIssueIndex, string[]>();
2084
+ const validationIssues = validationResult.error.issues ?? [];
2085
+ for (const issue of validationIssues) {
2086
+ const transactionIndex = issue.path.find(
2087
+ (segment): segment is number => typeof segment === 'number',
2088
+ );
2089
+ const message = issue.message;
2090
+ const issueIndex: TransactionIssueIndex =
2091
+ transactionIndex !== undefined ? transactionIndex : null;
2092
+ const existing = issuesByIndex.get(issueIndex) ?? [];
2093
+ existing.push(message);
2094
+ issuesByIndex.set(issueIndex, existing);
2095
+ }
2096
+
2097
+ const details = Array.from(issuesByIndex.entries()).map(([index, errors]) => ({
2098
+ transaction_index: index,
2099
+ errors,
2100
+ }));
2101
+
2102
+ throw new ValidationError(
2103
+ 'Bulk transaction update validation failed',
2104
+ JSON.stringify(details, null, 2),
2105
+ ['Ensure each transaction includes an id field', 'Limit batches to 100 items'],
2106
+ );
2107
+ }
2108
+
2109
+ const { budget_id, transactions, dry_run } = validationResult.data;
2110
+
2111
+ if (dry_run) {
2112
+ const previewTransactions = transactions.slice(0, 10);
2113
+ const previewTransactionIds = previewTransactions.map((transaction) => transaction.id);
2114
+ // Resolve metadata once and reuse any transaction details for preview rendering
2115
+ const { metadata, unresolvedIds, previewDetails } = await resolveMetadata(
2116
+ ynabAPI,
2117
+ budget_id,
2118
+ transactions,
2119
+ {
2120
+ previewTransactionIds,
2121
+ },
2122
+ );
2123
+
2124
+ const transactionsPreview = [];
2125
+ const unavailablePreviewIds: string[] = [];
2126
+
2127
+ for (const transaction of previewTransactions) {
2128
+ const currentState = previewDetails.get(transaction.id);
2129
+ if (!currentState) {
2130
+ unavailablePreviewIds.push(transaction.id);
2131
+ transactionsPreview.push({
2132
+ transaction_id: transaction.id,
2133
+ before: 'unavailable',
2134
+ after: transaction,
2135
+ });
2136
+ continue;
2137
+ }
2138
+
2139
+ const before: Record<string, unknown> = {};
2140
+ const after: Record<string, unknown> = {};
2141
+
2142
+ if (transaction.amount !== undefined && transaction.amount !== currentState.amount) {
2143
+ before['amount'] = milliunitsToAmount(currentState.amount);
2144
+ after['amount'] = milliunitsToAmount(transaction.amount);
2145
+ }
2146
+ if (transaction.date !== undefined && transaction.date !== currentState.date) {
2147
+ before['date'] = currentState.date;
2148
+ after['date'] = transaction.date;
2149
+ }
2150
+ if (transaction.memo !== undefined && transaction.memo !== currentState.memo) {
2151
+ before['memo'] = currentState.memo;
2152
+ after['memo'] = transaction.memo;
2153
+ }
2154
+ if (
2155
+ transaction.payee_id !== undefined &&
2156
+ transaction.payee_id !== currentState.payee_id
2157
+ ) {
2158
+ before['payee_id'] = currentState.payee_id;
2159
+ after['payee_id'] = transaction.payee_id;
2160
+ }
2161
+ if (
2162
+ transaction.payee_name !== undefined &&
2163
+ transaction.payee_name !== currentState.payee_name
2164
+ ) {
2165
+ before['payee_name'] = currentState.payee_name;
2166
+ after['payee_name'] = transaction.payee_name;
2167
+ }
2168
+ if (
2169
+ transaction.category_id !== undefined &&
2170
+ transaction.category_id !== currentState.category_id
2171
+ ) {
2172
+ before['category_id'] = currentState.category_id;
2173
+ after['category_id'] = transaction.category_id;
2174
+ }
2175
+ if (transaction.cleared !== undefined && transaction.cleared !== currentState.cleared) {
2176
+ before['cleared'] = currentState.cleared;
2177
+ after['cleared'] = transaction.cleared;
2178
+ }
2179
+ if (
2180
+ transaction.approved !== undefined &&
2181
+ transaction.approved !== currentState.approved
2182
+ ) {
2183
+ before['approved'] = currentState.approved;
2184
+ after['approved'] = transaction.approved;
2185
+ }
2186
+ if (
2187
+ transaction.flag_color !== undefined &&
2188
+ transaction.flag_color !== currentState.flag_color
2189
+ ) {
2190
+ before['flag_color'] = currentState.flag_color;
2191
+ after['flag_color'] = transaction.flag_color;
2192
+ }
2193
+
2194
+ transactionsPreview.push({
2195
+ transaction_id: transaction.id,
2196
+ before,
2197
+ after,
2198
+ });
2199
+ }
2200
+
2201
+ // Build warnings array
2202
+ const warnings: { code: string; count: number; message: string; sample_ids?: string[] }[] =
2203
+ [];
2204
+ if (unavailablePreviewIds.length > 0 || unresolvedIds.length > 0) {
2205
+ const totalMissing = Math.max(unavailablePreviewIds.length, unresolvedIds.length);
2206
+ const sampleIds =
2207
+ unresolvedIds.length > 0
2208
+ ? unresolvedIds.slice(0, 10)
2209
+ : unavailablePreviewIds.slice(0, 10);
2210
+ warnings.push({
2211
+ code: 'metadata_unavailable',
2212
+ count: totalMissing,
2213
+ message: `Unable to fetch prior state for ${totalMissing} transactions`,
2214
+ sample_ids: sampleIds,
2215
+ });
2216
+ }
2217
+
2218
+ // Collect summary statistics
2219
+ const accountsAffected = Array.from(
2220
+ new Set(Array.from(metadata.values()).map((m) => m.account_id)),
2221
+ );
2222
+ const fieldsToUpdate = new Set<string>();
2223
+ for (const transaction of transactions) {
2224
+ if (transaction.amount !== undefined) fieldsToUpdate.add('amount');
2225
+ if (transaction.date !== undefined) fieldsToUpdate.add('date');
2226
+ if (transaction.memo !== undefined) fieldsToUpdate.add('memo');
2227
+ if (transaction.payee_id !== undefined) fieldsToUpdate.add('payee_id');
2228
+ if (transaction.payee_name !== undefined) fieldsToUpdate.add('payee_name');
2229
+ if (transaction.category_id !== undefined) fieldsToUpdate.add('category_id');
2230
+ if (transaction.cleared !== undefined) fieldsToUpdate.add('cleared');
2231
+ if (transaction.approved !== undefined) fieldsToUpdate.add('approved');
2232
+ if (transaction.flag_color !== undefined) fieldsToUpdate.add('flag_color');
2233
+ }
2234
+
2235
+ const response: Record<string, unknown> = {
2236
+ dry_run: true,
2237
+ action: 'update_transactions',
2238
+ validation: 'passed',
2239
+ summary: {
2240
+ total_transactions: transactions.length,
2241
+ accounts_affected: accountsAffected,
2242
+ fields_to_update: Array.from(fieldsToUpdate),
2243
+ },
2244
+ transactions_preview: transactionsPreview,
2245
+ note: 'Dry run complete. No transactions updated. No caches invalidated. No server_knowledge updated.',
2246
+ };
2247
+
2248
+ if (warnings.length > 0) {
2249
+ response['warnings'] = warnings;
2250
+ }
2251
+
2252
+ return {
2253
+ content: [
2254
+ {
2255
+ type: 'text',
2256
+ text: responseFormatter.format(response),
2257
+ },
2258
+ ],
2259
+ };
2260
+ }
2261
+
2262
+ // Resolve metadata for cache invalidation before making updates
2263
+ const { metadata, unresolvedIds } = await resolveMetadata(ynabAPI, budget_id, transactions);
2264
+
2265
+ // Check metadata completeness threshold (5%)
2266
+ const missingMetadataRatio = unresolvedIds.length / transactions.length;
2267
+ const METADATA_THRESHOLD = 0.05; // 5%
2268
+
2269
+ if (missingMetadataRatio > METADATA_THRESHOLD) {
2270
+ throw new ValidationError(
2271
+ `METADATA_INCOMPLETE: ${(missingMetadataRatio * 100).toFixed(1)}% of transactions have missing metadata (threshold: ${(METADATA_THRESHOLD * 100).toFixed(0)}%)`,
2272
+ JSON.stringify(
2273
+ {
2274
+ unresolved_count: unresolvedIds.length,
2275
+ total_transactions: transactions.length,
2276
+ ratio: (missingMetadataRatio * 100).toFixed(1) + '%',
2277
+ threshold: (METADATA_THRESHOLD * 100).toFixed(0) + '%',
2278
+ sample_unresolved_ids: unresolvedIds.slice(0, 5),
2279
+ },
2280
+ null,
2281
+ 2,
2282
+ ),
2283
+ [
2284
+ 'Provide original_account_id and original_date for all transactions being updated',
2285
+ 'Ensure transactions exist in YNAB before updating them',
2286
+ ],
2287
+ );
2288
+ }
2289
+
2290
+ if (missingMetadataRatio > 0.01) {
2291
+ globalRequestLogger.logRequest(
2292
+ 'ynab:update_transactions',
2293
+ 'metadata_resolution_warning',
2294
+ {
2295
+ unresolved_count: unresolvedIds.length,
2296
+ total_transactions: transactions.length,
2297
+ ratio: missingMetadataRatio.toFixed(3),
2298
+ sample_ids: unresolvedIds.slice(0, 5),
2299
+ message: 'Metadata resolution incomplete for some transactions',
2300
+ },
2301
+ true,
2302
+ );
2303
+ }
2304
+
2305
+ // Prepare update transactions for the YNAB API
2306
+ const updateTransactions: { id: string; transaction: SaveTransaction }[] = transactions.map(
2307
+ (transaction) => {
2308
+ const transactionData: SaveTransaction = {};
2309
+
2310
+ // Note: account_id is intentionally excluded as account moves are not supported
2311
+ if (transaction.amount !== undefined) {
2312
+ transactionData.amount = transaction.amount;
2313
+ }
2314
+ if (transaction.date !== undefined) {
2315
+ transactionData.date = transaction.date;
2316
+ }
2317
+ if (transaction.payee_name !== undefined) {
2318
+ transactionData.payee_name = transaction.payee_name;
2319
+ }
2320
+ if (transaction.payee_id !== undefined) {
2321
+ transactionData.payee_id = transaction.payee_id;
2322
+ }
2323
+ if (transaction.category_id !== undefined) {
2324
+ transactionData.category_id = transaction.category_id;
2325
+ }
2326
+ if (transaction.memo !== undefined) {
2327
+ transactionData.memo = transaction.memo;
2328
+ }
2329
+ if (transaction.cleared !== undefined) {
2330
+ transactionData.cleared = transaction.cleared as ynab.TransactionClearedStatus;
2331
+ }
2332
+ if (transaction.approved !== undefined) {
2333
+ transactionData.approved = transaction.approved;
2334
+ }
2335
+ if (transaction.flag_color !== undefined) {
2336
+ transactionData.flag_color = transaction.flag_color as ynab.TransactionFlagColor;
2337
+ }
2338
+
2339
+ return {
2340
+ id: transaction.id,
2341
+ transaction: transactionData,
2342
+ };
2343
+ },
2344
+ );
2345
+
2346
+ // Execute bulk update
2347
+ const response = await ynabAPI.transactions.updateTransactions(budget_id, {
2348
+ transactions: updateTransactions,
2349
+ });
2350
+
2351
+ const responseData = response.data;
2352
+ const updatedTransactions = responseData.transactions ?? [];
2353
+
2354
+ // Build results
2355
+ const results: BulkUpdateResult[] = [];
2356
+ const updatedIds = new Set(updatedTransactions.map((t) => t.id));
2357
+
2358
+ for (const [index, transaction] of transactions.entries()) {
2359
+ if (updatedIds.has(transaction.id)) {
2360
+ results.push({
2361
+ request_index: index,
2362
+ status: 'updated',
2363
+ transaction_id: transaction.id,
2364
+ correlation_key: transaction.id,
2365
+ });
2366
+ } else {
2367
+ results.push({
2368
+ request_index: index,
2369
+ status: 'failed',
2370
+ transaction_id: transaction.id,
2371
+ correlation_key: transaction.id,
2372
+ error_code: 'update_failed',
2373
+ error: 'Transaction was not updated by YNAB API',
2374
+ });
2375
+ }
2376
+ }
2377
+
2378
+ const summary = {
2379
+ total_requested: transactions.length,
2380
+ updated: updatedTransactions.length,
2381
+ failed: results.filter((r) => r.status === 'failed').length,
2382
+ };
2383
+
2384
+ const baseResponse: BulkUpdateResponse = {
2385
+ success: summary.failed === 0,
2386
+ server_knowledge: responseData.server_knowledge,
2387
+ summary,
2388
+ results,
2389
+ transactions: updatedTransactions,
2390
+ message: `Processed ${summary.total_requested} transactions: ${summary.updated} updated, ${summary.failed} failed.`,
2391
+ };
2392
+
2393
+ for (const transaction of transactions) {
2394
+ cacheManager.delete(
2395
+ CacheManager.generateKey('transaction', 'get', budget_id, transaction.id),
2396
+ );
2397
+ }
2398
+
2399
+ const affectedAccountIds = new Set<string>();
2400
+ const affectedMonthKeys = new Set<string>();
2401
+ const affectedCategoryIds = new Set<string>();
2402
+ let invalidateAllCategories = false;
2403
+ let accountTotalsChanged = false;
2404
+ let monthsImpacted = false;
2405
+
2406
+ for (const transaction of transactions) {
2407
+ const meta = metadata.get(transaction.id);
2408
+ const amountChanged = transaction.amount !== undefined;
2409
+ const clearedChanged = transaction.cleared !== undefined;
2410
+ const categoryChanged = transaction.category_id !== undefined;
2411
+ const dateChanged = transaction.date !== undefined;
2412
+
2413
+ if ((amountChanged || clearedChanged) && meta) {
2414
+ affectedAccountIds.add(meta.account_id);
2415
+ }
2416
+
2417
+ if (amountChanged) {
2418
+ monthsImpacted = true;
2419
+ accountTotalsChanged = true;
2420
+ invalidateAllCategories = true;
2421
+ if (meta) {
2422
+ affectedMonthKeys.add(toMonthKey(meta.date));
2423
+ }
2424
+ }
2425
+
2426
+ if (categoryChanged) {
2427
+ monthsImpacted = true;
2428
+ invalidateAllCategories = true;
2429
+ if (transaction.category_id) {
2430
+ affectedCategoryIds.add(transaction.category_id);
2431
+ }
2432
+ if (meta) {
2433
+ affectedMonthKeys.add(toMonthKey(meta.date));
2434
+ }
2435
+ }
2436
+
2437
+ if (dateChanged && meta) {
2438
+ monthsImpacted = true;
2439
+ affectedMonthKeys.add(toMonthKey(meta.date));
2440
+ }
2441
+ if (dateChanged && transaction.date) {
2442
+ affectedMonthKeys.add(toMonthKey(transaction.date));
2443
+ }
2444
+ }
2445
+
2446
+ invalidateTransactionCaches(
2447
+ deltaCache,
2448
+ knowledgeStore,
2449
+ budget_id,
2450
+ responseData.server_knowledge,
2451
+ affectedAccountIds,
2452
+ affectedMonthKeys,
2453
+ {
2454
+ affectedCategoryIds,
2455
+ invalidateAllCategories,
2456
+ accountTotalsChanged,
2457
+ invalidateMonths: monthsImpacted,
2458
+ },
2459
+ );
2460
+
2461
+ const finalizedResponse = finalizeBulkUpdateResponse(baseResponse);
2462
+
2463
+ return {
2464
+ content: [
2465
+ {
2466
+ type: 'text',
2467
+ text: responseFormatter.format(finalizedResponse),
2468
+ },
2469
+ ],
2470
+ };
2471
+ },
2472
+ 'ynab:update_transactions',
2473
+ 'bulk transaction update',
2474
+ )) as CallToolResult;
2475
+ }
2476
+
2477
+ /**
2478
+ * Handles errors from transaction-related API calls
2479
+ */
2480
+ function handleTransactionError(error: unknown, defaultMessage: string): CallToolResult {
2481
+ let errorMessage = defaultMessage;
2482
+
2483
+ if (error instanceof Error) {
2484
+ if (error.message.includes('401') || error.message.includes('Unauthorized')) {
2485
+ errorMessage = 'Invalid or expired YNAB access token';
2486
+ } else if (error.message.includes('403') || error.message.includes('Forbidden')) {
2487
+ errorMessage = 'Insufficient permissions to access YNAB data';
2488
+ } else if (error.message.includes('404') || error.message.includes('Not Found')) {
2489
+ errorMessage = 'Budget, account, category, or transaction not found';
2490
+ } else if (error.message.includes('429') || error.message.includes('Too Many Requests')) {
2491
+ errorMessage = 'Rate limit exceeded. Please try again later';
2492
+ } else if (error.message.includes('500') || error.message.includes('Internal Server Error')) {
2493
+ errorMessage = 'YNAB service is currently unavailable';
2494
+ }
2495
+ }
2496
+
2497
+ return {
2498
+ content: [
2499
+ {
2500
+ type: 'text',
2501
+ text: responseFormatter.format({
2502
+ error: {
2503
+ message: errorMessage,
2504
+ },
2505
+ }),
2506
+ },
2507
+ ],
2508
+ };
2509
+ }