@dizzlkheinz/ynab-mcpb 0.18.3 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (346) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/CLAUDE.md +87 -8
  3. package/bin/ynab-mcp-server.cjs +2 -2
  4. package/bin/ynab-mcp-server.js +3 -3
  5. package/biome.json +39 -0
  6. package/dist/bundle/index.cjs +67 -67
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +27 -27
  9. package/dist/server/YNABMCPServer.d.ts +3 -4
  10. package/dist/server/YNABMCPServer.js +111 -116
  11. package/dist/server/budgetResolver.d.ts +6 -5
  12. package/dist/server/budgetResolver.js +46 -36
  13. package/dist/server/cacheKeys.js +6 -6
  14. package/dist/server/cacheManager.js +14 -11
  15. package/dist/server/completions.d.ts +2 -2
  16. package/dist/server/completions.js +20 -15
  17. package/dist/server/config.d.ts +10 -5
  18. package/dist/server/config.js +24 -7
  19. package/dist/server/deltaCache.d.ts +2 -2
  20. package/dist/server/deltaCache.js +22 -16
  21. package/dist/server/deltaCache.merge.d.ts +2 -2
  22. package/dist/server/diagnostics.d.ts +4 -4
  23. package/dist/server/diagnostics.js +38 -32
  24. package/dist/server/errorHandler.d.ts +5 -12
  25. package/dist/server/errorHandler.js +219 -217
  26. package/dist/server/prompts.d.ts +2 -2
  27. package/dist/server/prompts.js +45 -45
  28. package/dist/server/rateLimiter.js +4 -4
  29. package/dist/server/requestLogger.d.ts +1 -1
  30. package/dist/server/requestLogger.js +40 -35
  31. package/dist/server/resources.d.ts +3 -3
  32. package/dist/server/resources.js +55 -52
  33. package/dist/server/responseFormatter.js +6 -6
  34. package/dist/server/securityMiddleware.d.ts +2 -2
  35. package/dist/server/securityMiddleware.js +22 -20
  36. package/dist/server/serverKnowledgeStore.js +1 -1
  37. package/dist/server/toolRegistry.d.ts +3 -3
  38. package/dist/server/toolRegistry.js +47 -40
  39. package/dist/tools/__tests__/deltaTestUtils.d.ts +3 -3
  40. package/dist/tools/__tests__/deltaTestUtils.js +2 -2
  41. package/dist/tools/accountTools.d.ts +9 -8
  42. package/dist/tools/accountTools.js +47 -47
  43. package/dist/tools/adapters.d.ts +13 -8
  44. package/dist/tools/adapters.js +21 -11
  45. package/dist/tools/budgetTools.d.ts +8 -7
  46. package/dist/tools/budgetTools.js +22 -22
  47. package/dist/tools/categoryTools.d.ts +9 -8
  48. package/dist/tools/categoryTools.js +68 -59
  49. package/dist/tools/compareTransactions/formatter.d.ts +3 -3
  50. package/dist/tools/compareTransactions/formatter.js +9 -9
  51. package/dist/tools/compareTransactions/index.d.ts +6 -6
  52. package/dist/tools/compareTransactions/index.js +58 -43
  53. package/dist/tools/compareTransactions/matcher.d.ts +1 -1
  54. package/dist/tools/compareTransactions/matcher.js +28 -15
  55. package/dist/tools/compareTransactions/parser.d.ts +2 -2
  56. package/dist/tools/compareTransactions/parser.js +144 -138
  57. package/dist/tools/compareTransactions/types.d.ts +4 -4
  58. package/dist/tools/compareTransactions.d.ts +1 -1
  59. package/dist/tools/compareTransactions.js +1 -1
  60. package/dist/tools/deltaFetcher.d.ts +2 -2
  61. package/dist/tools/deltaFetcher.js +16 -15
  62. package/dist/tools/deltaSupport.d.ts +4 -4
  63. package/dist/tools/deltaSupport.js +35 -41
  64. package/dist/tools/exportTransactions.d.ts +5 -4
  65. package/dist/tools/exportTransactions.js +61 -59
  66. package/dist/tools/monthTools.d.ts +7 -6
  67. package/dist/tools/monthTools.js +31 -29
  68. package/dist/tools/payeeTools.d.ts +7 -6
  69. package/dist/tools/payeeTools.js +28 -28
  70. package/dist/tools/reconcileAdapter.d.ts +2 -2
  71. package/dist/tools/reconcileAdapter.js +21 -11
  72. package/dist/tools/reconciliation/analyzer.d.ts +4 -4
  73. package/dist/tools/reconciliation/analyzer.js +136 -57
  74. package/dist/tools/reconciliation/csvParser.d.ts +3 -3
  75. package/dist/tools/reconciliation/csvParser.js +128 -104
  76. package/dist/tools/reconciliation/executor.d.ts +4 -4
  77. package/dist/tools/reconciliation/executor.js +148 -109
  78. package/dist/tools/reconciliation/index.d.ts +10 -10
  79. package/dist/tools/reconciliation/index.js +96 -83
  80. package/dist/tools/reconciliation/matcher.d.ts +3 -3
  81. package/dist/tools/reconciliation/matcher.js +17 -16
  82. package/dist/tools/reconciliation/payeeNormalizer.js +19 -8
  83. package/dist/tools/reconciliation/recommendationEngine.d.ts +1 -1
  84. package/dist/tools/reconciliation/recommendationEngine.js +40 -40
  85. package/dist/tools/reconciliation/reportFormatter.d.ts +2 -2
  86. package/dist/tools/reconciliation/reportFormatter.js +79 -54
  87. package/dist/tools/reconciliation/signDetector.d.ts +1 -1
  88. package/dist/tools/reconciliation/types.d.ts +19 -16
  89. package/dist/tools/reconciliation/ynabAdapter.d.ts +2 -2
  90. package/dist/tools/schemas/common.d.ts +1 -1
  91. package/dist/tools/schemas/common.js +1 -1
  92. package/dist/tools/schemas/outputs/accountOutputs.d.ts +1 -1
  93. package/dist/tools/schemas/outputs/accountOutputs.js +24 -18
  94. package/dist/tools/schemas/outputs/budgetOutputs.d.ts +1 -1
  95. package/dist/tools/schemas/outputs/budgetOutputs.js +14 -11
  96. package/dist/tools/schemas/outputs/categoryOutputs.d.ts +1 -1
  97. package/dist/tools/schemas/outputs/categoryOutputs.js +49 -29
  98. package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +1 -1
  99. package/dist/tools/schemas/outputs/comparisonOutputs.js +12 -12
  100. package/dist/tools/schemas/outputs/index.d.ts +14 -14
  101. package/dist/tools/schemas/outputs/index.js +14 -14
  102. package/dist/tools/schemas/outputs/monthOutputs.d.ts +1 -1
  103. package/dist/tools/schemas/outputs/monthOutputs.js +56 -41
  104. package/dist/tools/schemas/outputs/payeeOutputs.d.ts +1 -1
  105. package/dist/tools/schemas/outputs/payeeOutputs.js +10 -10
  106. package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +2 -2
  107. package/dist/tools/schemas/outputs/reconciliationOutputs.js +45 -45
  108. package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +1 -1
  109. package/dist/tools/schemas/outputs/transactionMutationOutputs.js +28 -22
  110. package/dist/tools/schemas/outputs/transactionOutputs.d.ts +1 -1
  111. package/dist/tools/schemas/outputs/transactionOutputs.js +43 -35
  112. package/dist/tools/schemas/outputs/utilityOutputs.d.ts +1 -1
  113. package/dist/tools/schemas/outputs/utilityOutputs.js +5 -3
  114. package/dist/tools/schemas/shared/commonOutputs.d.ts +1 -1
  115. package/dist/tools/schemas/shared/commonOutputs.js +15 -9
  116. package/dist/tools/transactionReadTools.d.ts +11 -0
  117. package/dist/tools/transactionReadTools.js +202 -0
  118. package/dist/tools/transactionSchemas.d.ts +309 -0
  119. package/dist/tools/transactionSchemas.js +235 -0
  120. package/dist/tools/transactionTools.d.ts +6 -302
  121. package/dist/tools/transactionTools.js +7 -2054
  122. package/dist/tools/transactionUtils.d.ts +31 -0
  123. package/dist/tools/transactionUtils.js +364 -0
  124. package/dist/tools/transactionWriteTools.d.ts +20 -0
  125. package/dist/tools/transactionWriteTools.js +1342 -0
  126. package/dist/tools/utilityTools.d.ts +5 -4
  127. package/dist/tools/utilityTools.js +11 -11
  128. package/dist/types/index.d.ts +7 -7
  129. package/dist/types/index.js +6 -6
  130. package/dist/types/reconciliation.d.ts +1 -1
  131. package/dist/types/toolRegistration.d.ts +14 -12
  132. package/dist/utils/amountUtils.js +1 -1
  133. package/dist/utils/dateUtils.js +4 -4
  134. package/dist/utils/errors.d.ts +3 -3
  135. package/dist/utils/errors.js +4 -4
  136. package/dist/utils/money.d.ts +2 -2
  137. package/dist/utils/money.js +8 -8
  138. package/dist/utils/validationError.d.ts +1 -1
  139. package/dist/utils/validationError.js +1 -1
  140. package/docs/assets/examples/reconciliation-with-recommendations.json +66 -66
  141. package/docs/assets/schemas/reconciliation-v2.json +360 -336
  142. package/docs/plans/2025-12-25-transaction-tools-refactor-design.md +211 -0
  143. package/docs/plans/2025-12-25-transaction-tools-refactor.md +905 -0
  144. package/esbuild.config.mjs +53 -50
  145. package/meta.json +12548 -12548
  146. package/package.json +98 -109
  147. package/scripts/analyze-bundle.mjs +33 -30
  148. package/scripts/create-pr-description.js +169 -120
  149. package/scripts/run-all-tests.js +205 -0
  150. package/scripts/run-domain-integration-tests.js +28 -18
  151. package/scripts/run-generate-mcpb.js +19 -17
  152. package/scripts/run-throttled-integration-tests.js +92 -83
  153. package/scripts/test-delta-params.mjs +149 -120
  154. package/scripts/test-recommendations.ts +36 -32
  155. package/scripts/tmpTransaction.ts +80 -43
  156. package/scripts/validate-env.js +98 -91
  157. package/scripts/verify-build.js +78 -76
  158. package/src/__tests__/comprehensive.integration.test.ts +1281 -1154
  159. package/src/__tests__/performance.test.ts +723 -671
  160. package/src/__tests__/setup.ts +442 -395
  161. package/src/__tests__/smoke.e2e.test.ts +41 -39
  162. package/src/__tests__/testRunner.ts +314 -295
  163. package/src/__tests__/testUtils.ts +456 -364
  164. package/src/__tests__/tools/reconciliation/csvParser.integration.test.ts +109 -107
  165. package/src/__tests__/tools/reconciliation/real-world.integration.test.ts +41 -41
  166. package/src/index.ts +68 -59
  167. package/src/server/CLAUDE.md +480 -0
  168. package/src/server/YNABMCPServer.ts +821 -794
  169. package/src/server/__tests__/YNABMCPServer.integration.test.ts +929 -893
  170. package/src/server/__tests__/YNABMCPServer.test.ts +903 -899
  171. package/src/server/__tests__/budgetResolver.test.ts +466 -423
  172. package/src/server/__tests__/cacheManager.test.ts +891 -874
  173. package/src/server/__tests__/completions.integration.test.ts +115 -106
  174. package/src/server/__tests__/completions.test.ts +334 -313
  175. package/src/server/__tests__/config.test.ts +98 -86
  176. package/src/server/__tests__/deltaCache.merge.test.ts +774 -703
  177. package/src/server/__tests__/deltaCache.swr.test.ts +198 -153
  178. package/src/server/__tests__/deltaCache.test.ts +946 -759
  179. package/src/server/__tests__/diagnostics.test.ts +825 -792
  180. package/src/server/__tests__/errorHandler.integration.test.ts +512 -462
  181. package/src/server/__tests__/errorHandler.test.ts +402 -397
  182. package/src/server/__tests__/prompts.test.ts +424 -347
  183. package/src/server/__tests__/rateLimiter.test.ts +313 -309
  184. package/src/server/__tests__/requestLogger.test.ts +443 -403
  185. package/src/server/__tests__/resources.template.test.ts +196 -185
  186. package/src/server/__tests__/resources.test.ts +294 -288
  187. package/src/server/__tests__/security.integration.test.ts +487 -421
  188. package/src/server/__tests__/securityMiddleware.test.ts +519 -444
  189. package/src/server/__tests__/server-startup.integration.test.ts +509 -490
  190. package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -173
  191. package/src/server/__tests__/toolRegistration.test.ts +239 -210
  192. package/src/server/__tests__/toolRegistry.test.ts +907 -845
  193. package/src/server/budgetResolver.ts +221 -181
  194. package/src/server/cacheKeys.ts +6 -6
  195. package/src/server/cacheManager.ts +498 -484
  196. package/src/server/completions.ts +267 -243
  197. package/src/server/config.ts +35 -14
  198. package/src/server/deltaCache.merge.ts +146 -128
  199. package/src/server/deltaCache.ts +352 -309
  200. package/src/server/diagnostics.ts +257 -242
  201. package/src/server/errorHandler.ts +747 -744
  202. package/src/server/prompts.ts +181 -176
  203. package/src/server/rateLimiter.ts +131 -129
  204. package/src/server/requestLogger.ts +350 -322
  205. package/src/server/resources.ts +442 -374
  206. package/src/server/responseFormatter.ts +41 -37
  207. package/src/server/securityMiddleware.ts +223 -205
  208. package/src/server/serverKnowledgeStore.ts +67 -67
  209. package/src/server/toolRegistry.ts +508 -474
  210. package/src/tools/CLAUDE.md +604 -0
  211. package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -111
  212. package/src/tools/__tests__/accountTools.integration.test.ts +129 -111
  213. package/src/tools/__tests__/accountTools.test.ts +685 -638
  214. package/src/tools/__tests__/adapters.test.ts +142 -108
  215. package/src/tools/__tests__/budgetTools.delta.integration.test.ts +73 -73
  216. package/src/tools/__tests__/budgetTools.integration.test.ts +132 -124
  217. package/src/tools/__tests__/budgetTools.test.ts +442 -413
  218. package/src/tools/__tests__/categoryTools.delta.integration.test.ts +76 -68
  219. package/src/tools/__tests__/categoryTools.integration.test.ts +314 -288
  220. package/src/tools/__tests__/categoryTools.test.ts +656 -625
  221. package/src/tools/__tests__/compareTransactions/formatter.test.ts +535 -462
  222. package/src/tools/__tests__/compareTransactions/index.test.ts +378 -358
  223. package/src/tools/__tests__/compareTransactions/matcher.test.ts +497 -398
  224. package/src/tools/__tests__/compareTransactions/parser.test.ts +765 -747
  225. package/src/tools/__tests__/compareTransactions.test.ts +352 -332
  226. package/src/tools/__tests__/compareTransactions.window.test.ts +150 -146
  227. package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +69 -65
  228. package/src/tools/__tests__/deltaFetcher.test.ts +325 -265
  229. package/src/tools/__tests__/deltaSupport.test.ts +211 -184
  230. package/src/tools/__tests__/deltaTestUtils.ts +37 -33
  231. package/src/tools/__tests__/exportTransactions.test.ts +205 -200
  232. package/src/tools/__tests__/monthTools.delta.integration.test.ts +68 -68
  233. package/src/tools/__tests__/monthTools.integration.test.ts +178 -166
  234. package/src/tools/__tests__/monthTools.test.ts +561 -512
  235. package/src/tools/__tests__/payeeTools.delta.integration.test.ts +68 -68
  236. package/src/tools/__tests__/payeeTools.integration.test.ts +158 -142
  237. package/src/tools/__tests__/payeeTools.test.ts +486 -434
  238. package/src/tools/__tests__/transactionSchemas.test.ts +1204 -0
  239. package/src/tools/__tests__/transactionTools.integration.test.ts +875 -825
  240. package/src/tools/__tests__/transactionTools.test.ts +4923 -4366
  241. package/src/tools/__tests__/transactionUtils.test.ts +1016 -0
  242. package/src/tools/__tests__/utilityTools.integration.test.ts +32 -32
  243. package/src/tools/__tests__/utilityTools.test.ts +68 -58
  244. package/src/tools/accountTools.ts +293 -271
  245. package/src/tools/adapters.ts +120 -63
  246. package/src/tools/budgetTools.ts +121 -116
  247. package/src/tools/categoryTools.ts +379 -339
  248. package/src/tools/compareTransactions/formatter.ts +131 -119
  249. package/src/tools/compareTransactions/index.ts +249 -214
  250. package/src/tools/compareTransactions/matcher.ts +259 -209
  251. package/src/tools/compareTransactions/parser.ts +517 -487
  252. package/src/tools/compareTransactions/types.ts +38 -38
  253. package/src/tools/compareTransactions.ts +1 -1
  254. package/src/tools/deltaFetcher.ts +281 -260
  255. package/src/tools/deltaSupport.ts +264 -259
  256. package/src/tools/exportTransactions.ts +230 -218
  257. package/src/tools/monthTools.ts +180 -165
  258. package/src/tools/payeeTools.ts +152 -140
  259. package/src/tools/reconcileAdapter.ts +297 -246
  260. package/src/tools/reconciliation/CLAUDE.md +506 -0
  261. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +135 -112
  262. package/src/tools/reconciliation/__tests__/adapter.test.ts +249 -227
  263. package/src/tools/reconciliation/__tests__/analyzer.test.ts +408 -335
  264. package/src/tools/reconciliation/__tests__/csvParser.test.ts +71 -69
  265. package/src/tools/reconciliation/__tests__/executor.integration.test.ts +348 -323
  266. package/src/tools/reconciliation/__tests__/executor.progress.test.ts +503 -457
  267. package/src/tools/reconciliation/__tests__/executor.test.ts +898 -831
  268. package/src/tools/reconciliation/__tests__/matcher.test.ts +667 -663
  269. package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +296 -276
  270. package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +692 -624
  271. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1008 -986
  272. package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +187 -146
  273. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +583 -530
  274. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +75 -71
  275. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +70 -58
  276. package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +102 -88
  277. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +58 -43
  278. package/src/tools/reconciliation/__tests__/signDetector.test.ts +209 -206
  279. package/src/tools/reconciliation/__tests__/ynabAdapter.test.ts +66 -60
  280. package/src/tools/reconciliation/analyzer.ts +582 -406
  281. package/src/tools/reconciliation/csvParser.ts +656 -609
  282. package/src/tools/reconciliation/executor.ts +1290 -1128
  283. package/src/tools/reconciliation/index.ts +580 -528
  284. package/src/tools/reconciliation/matcher.ts +256 -240
  285. package/src/tools/reconciliation/payeeNormalizer.ts +92 -78
  286. package/src/tools/reconciliation/recommendationEngine.ts +357 -345
  287. package/src/tools/reconciliation/reportFormatter.ts +349 -276
  288. package/src/tools/reconciliation/signDetector.ts +89 -83
  289. package/src/tools/reconciliation/types.ts +164 -153
  290. package/src/tools/reconciliation/ynabAdapter.ts +17 -15
  291. package/src/tools/schemas/CLAUDE.md +546 -0
  292. package/src/tools/schemas/common.ts +1 -1
  293. package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +410 -409
  294. package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +305 -299
  295. package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +431 -430
  296. package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +510 -495
  297. package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +179 -153
  298. package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +293 -254
  299. package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +457 -457
  300. package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +362 -356
  301. package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +402 -399
  302. package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +225 -211
  303. package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +457 -454
  304. package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +316 -315
  305. package/src/tools/schemas/outputs/accountOutputs.ts +40 -34
  306. package/src/tools/schemas/outputs/budgetOutputs.ts +24 -19
  307. package/src/tools/schemas/outputs/categoryOutputs.ts +76 -56
  308. package/src/tools/schemas/outputs/comparisonOutputs.ts +192 -169
  309. package/src/tools/schemas/outputs/index.ts +163 -163
  310. package/src/tools/schemas/outputs/monthOutputs.ts +95 -80
  311. package/src/tools/schemas/outputs/payeeOutputs.ts +18 -18
  312. package/src/tools/schemas/outputs/reconciliationOutputs.ts +386 -373
  313. package/src/tools/schemas/outputs/transactionMutationOutputs.ts +259 -231
  314. package/src/tools/schemas/outputs/transactionOutputs.ts +81 -71
  315. package/src/tools/schemas/outputs/utilityOutputs.ts +90 -84
  316. package/src/tools/schemas/shared/commonOutputs.ts +27 -19
  317. package/src/tools/toolCategories.ts +114 -114
  318. package/src/tools/transactionReadTools.ts +327 -0
  319. package/src/tools/transactionSchemas.ts +484 -0
  320. package/src/tools/transactionTools.ts +107 -2990
  321. package/src/tools/transactionUtils.ts +621 -0
  322. package/src/tools/transactionWriteTools.ts +2110 -0
  323. package/src/tools/utilityTools.ts +46 -41
  324. package/src/types/CLAUDE.md +477 -0
  325. package/src/types/__tests__/index.test.ts +51 -51
  326. package/src/types/index.ts +43 -39
  327. package/src/types/integration-tests.d.ts +26 -26
  328. package/src/types/reconciliation.ts +29 -29
  329. package/src/types/toolAnnotations.ts +30 -30
  330. package/src/types/toolRegistration.ts +43 -32
  331. package/src/utils/CLAUDE.md +508 -0
  332. package/src/utils/__tests__/dateUtils.test.ts +174 -168
  333. package/src/utils/__tests__/money.test.ts +193 -187
  334. package/src/utils/amountUtils.ts +5 -5
  335. package/src/utils/baseError.ts +5 -5
  336. package/src/utils/dateUtils.ts +29 -26
  337. package/src/utils/errors.ts +14 -14
  338. package/src/utils/money.ts +66 -52
  339. package/src/utils/validationError.ts +1 -1
  340. package/tsconfig.json +29 -29
  341. package/tsconfig.prod.json +16 -16
  342. package/vitest-reporters/split-json-reporter.ts +247 -204
  343. package/vitest.config.ts +99 -95
  344. package/.prettierignore +0 -10
  345. package/.prettierrc.json +0 -10
  346. package/eslint.config.js +0 -49
@@ -0,0 +1,2110 @@
1
+ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
+ import type * as ynab from "ynab";
3
+ import type { SaveSubTransaction } from "ynab/dist/models/SaveSubTransaction.js";
4
+ import type { SaveTransaction } from "ynab/dist/models/SaveTransaction.js";
5
+ import type { z } from "zod/v4";
6
+ import { CacheManager, cacheManager } from "../server/cacheManager.js";
7
+ import type { DeltaCache } from "../server/deltaCache.js";
8
+ import type { ErrorHandler } from "../server/errorHandler.js";
9
+ import { globalRequestLogger } from "../server/requestLogger.js";
10
+ import { responseFormatter } from "../server/responseFormatter.js";
11
+ import type { ServerKnowledgeStore } from "../server/serverKnowledgeStore.js";
12
+ import type { ToolRegistry } from "../server/toolRegistry.js";
13
+ import { ValidationError, withToolErrorHandling } from "../types/index.js";
14
+ import type { ToolContext } from "../types/toolRegistration.js";
15
+ import {
16
+ amountToMilliunits,
17
+ milliunitsToAmount,
18
+ } from "../utils/amountUtils.js";
19
+ import { createAdapters, createBudgetResolver } from "./adapters.js";
20
+ import { resolveDeltaWriteArgs } from "./deltaSupport.js";
21
+ import { ToolAnnotationPresets } from "./toolCategories.js";
22
+
23
+ import {
24
+ type BulkCreateResponse,
25
+ type BulkUpdateResponse,
26
+ type BulkUpdateResult,
27
+ type BulkUpdateTransactionInput,
28
+ type CreateReceiptSplitTransactionParams,
29
+ CreateReceiptSplitTransactionSchema,
30
+ type CreateTransactionParams,
31
+ CreateTransactionSchema,
32
+ type CreateTransactionsParams,
33
+ CreateTransactionsSchema,
34
+ type DeleteTransactionParams,
35
+ DeleteTransactionSchema,
36
+ type ReceiptCategoryCalculation,
37
+ type SubtransactionInput,
38
+ type UpdateTransactionParams,
39
+ UpdateTransactionSchema,
40
+ type UpdateTransactionsParams,
41
+ UpdateTransactionsSchema,
42
+ } from "./transactionSchemas.js";
43
+
44
+ import {
45
+ appendCategoryIds,
46
+ collectCategoryIdsFromSources,
47
+ correlateResults,
48
+ ensureTransaction,
49
+ finalizeBulkUpdateResponse,
50
+ finalizeResponse,
51
+ handleTransactionError,
52
+ invalidateTransactionCaches,
53
+ setsEqual,
54
+ toMonthKey,
55
+ } from "./transactionUtils.js";
56
+
57
+ /**
58
+ * Handles the ynab:create_transaction tool call
59
+ * Creates a new transaction in the specified budget and account
60
+ */
61
+ export async function handleCreateTransaction(
62
+ ynabAPI: ynab.API,
63
+ deltaCache: DeltaCache,
64
+ knowledgeStore: ServerKnowledgeStore,
65
+ params: CreateTransactionParams,
66
+ ): Promise<CallToolResult>;
67
+ export async function handleCreateTransaction(
68
+ ynabAPI: ynab.API,
69
+ params: CreateTransactionParams,
70
+ ): Promise<CallToolResult>;
71
+ export async function handleCreateTransaction(
72
+ ynabAPI: ynab.API,
73
+ deltaCacheOrParams: DeltaCache | CreateTransactionParams,
74
+ knowledgeStoreOrParams?: ServerKnowledgeStore | CreateTransactionParams,
75
+ maybeParams?: CreateTransactionParams,
76
+ _errorHandler?: ErrorHandler,
77
+ ): Promise<CallToolResult> {
78
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
79
+ deltaCacheOrParams,
80
+ knowledgeStoreOrParams,
81
+ maybeParams,
82
+ );
83
+ try {
84
+ if (params.dry_run) {
85
+ return {
86
+ content: [
87
+ {
88
+ type: "text",
89
+ text: responseFormatter.format({
90
+ dry_run: true,
91
+ action: "create_transaction",
92
+ request: params,
93
+ }),
94
+ },
95
+ ],
96
+ };
97
+ }
98
+ // Prepare transaction data
99
+ const transactionData: SaveTransaction = {
100
+ account_id: params.account_id,
101
+ amount: params.amount, // Already validated as integer milliunits
102
+ date: params.date,
103
+ cleared: params.cleared as ynab.TransactionClearedStatus,
104
+ flag_color: params.flag_color as ynab.TransactionFlagColor,
105
+ };
106
+ if (params.payee_name !== undefined)
107
+ transactionData.payee_name = params.payee_name;
108
+ if (params.payee_id !== undefined)
109
+ transactionData.payee_id = params.payee_id;
110
+ if (params.category_id !== undefined)
111
+ transactionData.category_id = params.category_id;
112
+ if (params.memo !== undefined) transactionData.memo = params.memo;
113
+ if (params.approved !== undefined)
114
+ transactionData.approved = params.approved;
115
+ if (params.import_id !== undefined)
116
+ transactionData.import_id = params.import_id;
117
+ if (params.subtransactions && params.subtransactions.length > 0) {
118
+ const subtransactions: SaveSubTransaction[] = params.subtransactions.map(
119
+ (subtransaction) => {
120
+ const mapped: SaveSubTransaction = {
121
+ amount: subtransaction.amount,
122
+ };
123
+
124
+ if (subtransaction.payee_name !== undefined)
125
+ mapped.payee_name = subtransaction.payee_name;
126
+ if (subtransaction.payee_id !== undefined)
127
+ mapped.payee_id = subtransaction.payee_id;
128
+ if (subtransaction.category_id !== undefined) {
129
+ mapped.category_id = subtransaction.category_id;
130
+ }
131
+ if (subtransaction.memo !== undefined)
132
+ mapped.memo = subtransaction.memo;
133
+
134
+ return mapped;
135
+ },
136
+ );
137
+
138
+ transactionData.subtransactions = subtransactions;
139
+ }
140
+
141
+ const response = await ynabAPI.transactions.createTransaction(
142
+ params.budget_id,
143
+ {
144
+ transaction: transactionData,
145
+ },
146
+ );
147
+
148
+ const transaction = ensureTransaction(
149
+ response.data.transaction,
150
+ "Transaction creation failed",
151
+ );
152
+
153
+ const affectedAccountIds = new Set<string>([transaction.account_id]);
154
+ const affectedMonths = new Set<string>([toMonthKey(transaction.date)]);
155
+ const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
156
+ invalidateTransactionCaches(
157
+ deltaCache,
158
+ knowledgeStore,
159
+ params.budget_id,
160
+ response.data.server_knowledge,
161
+ affectedAccountIds,
162
+ affectedMonths,
163
+ {
164
+ affectedCategoryIds,
165
+ accountTotalsChanged: true,
166
+ invalidateMonths: true,
167
+ },
168
+ );
169
+
170
+ // Get the updated account balance
171
+ const accountResponse = await ynabAPI.accounts.getAccountById(
172
+ params.budget_id,
173
+ transaction.account_id,
174
+ );
175
+ const account = accountResponse.data.account;
176
+
177
+ return {
178
+ content: [
179
+ {
180
+ type: "text",
181
+ text: responseFormatter.format({
182
+ transaction: {
183
+ id: transaction.id,
184
+ date: transaction.date,
185
+ amount: milliunitsToAmount(transaction.amount),
186
+ memo: transaction.memo,
187
+ cleared: transaction.cleared,
188
+ approved: transaction.approved,
189
+ flag_color: transaction.flag_color,
190
+ account_id: transaction.account_id,
191
+ payee_id: transaction.payee_id,
192
+ category_id: transaction.category_id,
193
+ transfer_account_id: transaction.transfer_account_id,
194
+ transfer_transaction_id: transaction.transfer_transaction_id,
195
+ matched_transaction_id: transaction.matched_transaction_id,
196
+ import_id: transaction.import_id,
197
+ deleted: transaction.deleted,
198
+ // New fields for account balance
199
+ account_balance: account.balance,
200
+ account_cleared_balance: account.cleared_balance,
201
+ subtransactions: transaction.subtransactions?.map(
202
+ (subtransaction) => ({
203
+ id: subtransaction.id,
204
+ transaction_id: subtransaction.transaction_id,
205
+ amount: milliunitsToAmount(subtransaction.amount),
206
+ memo: subtransaction.memo,
207
+ payee_id: subtransaction.payee_id,
208
+ payee_name: subtransaction.payee_name,
209
+ category_id: subtransaction.category_id,
210
+ category_name: subtransaction.category_name,
211
+ transfer_account_id: subtransaction.transfer_account_id,
212
+ transfer_transaction_id:
213
+ subtransaction.transfer_transaction_id,
214
+ deleted: subtransaction.deleted,
215
+ }),
216
+ ),
217
+ },
218
+ }),
219
+ },
220
+ ],
221
+ };
222
+ } catch (error) {
223
+ return handleTransactionError(error, "Failed to create transaction");
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Constants for smart collapse logic
229
+ */
230
+ const BIG_TICKET_THRESHOLD_MILLIUNITS = 50000; // $50.00
231
+ const COLLAPSE_THRESHOLD = 5; // Collapse if 5 or more remaining items
232
+ const MAX_ITEMS_PER_MEMO = 5;
233
+ const MAX_MEMO_LENGTH = 150;
234
+
235
+ /**
236
+ * Truncates a string to fit within maxLength, adding ellipsis if truncated
237
+ */
238
+ function truncateToLength(str: string, maxLength: number): string {
239
+ if (str.length <= maxLength) {
240
+ return str;
241
+ }
242
+ const ellipsis = "...";
243
+ return str.substring(0, maxLength - ellipsis.length) + ellipsis;
244
+ }
245
+
246
+ function buildItemMemo(item: {
247
+ name: string;
248
+ quantity: number | undefined;
249
+ memo: string | undefined;
250
+ }): string | undefined {
251
+ const quantitySuffix = item.quantity ? ` (x${item.quantity})` : "";
252
+ let result: string;
253
+ if (item.memo && item.memo.trim().length > 0) {
254
+ result = `${item.name}${quantitySuffix} - ${item.memo}`;
255
+ } else if (quantitySuffix) {
256
+ result = `${item.name}${quantitySuffix}`;
257
+ } else {
258
+ result = item.name;
259
+ }
260
+ // Truncate to MAX_MEMO_LENGTH if needed
261
+ return truncateToLength(result, MAX_MEMO_LENGTH);
262
+ }
263
+
264
+ /**
265
+ * Applies smart collapse logic to receipt items according to the specification:
266
+ * 1. Extract special items (big ticket, returns, discounts)
267
+ * 2. Apply threshold to remaining items
268
+ * 3. Collapse by category if needed
269
+ * 4. Handle tax allocation
270
+ */
271
+ function applySmartCollapseLogic(
272
+ categoryCalculations: ReceiptCategoryCalculation[],
273
+ taxMilliunits: number,
274
+ ): SubtransactionInput[] {
275
+ // Step 1: Extract special items and classify remaining items
276
+ interface SpecialItem {
277
+ item: ReceiptCategoryCalculation["items"][0];
278
+ category_id: string;
279
+ category_name: string | undefined;
280
+ }
281
+
282
+ interface CategoryItems {
283
+ category_id: string;
284
+ category_name: string | undefined;
285
+ items: ReceiptCategoryCalculation["items"][0][];
286
+ }
287
+
288
+ const specialItems: SpecialItem[] = [];
289
+ const remainingItemsByCategory: CategoryItems[] = [];
290
+
291
+ for (const category of categoryCalculations) {
292
+ const categorySpecials: ReceiptCategoryCalculation["items"][0][] = [];
293
+ const categoryRemaining: ReceiptCategoryCalculation["items"][0][] = [];
294
+
295
+ for (const item of category.items) {
296
+ const isNegative = item.amount_milliunits < 0;
297
+ const unitPrice = item.quantity
298
+ ? item.amount_milliunits / item.quantity
299
+ : item.amount_milliunits;
300
+ const isBigTicket = unitPrice > BIG_TICKET_THRESHOLD_MILLIUNITS;
301
+
302
+ if (isNegative || isBigTicket) {
303
+ categorySpecials.push(item);
304
+ } else {
305
+ categoryRemaining.push(item);
306
+ }
307
+ }
308
+
309
+ // Add specials to the special items list (preserving category order)
310
+ for (const item of categorySpecials) {
311
+ specialItems.push({
312
+ item,
313
+ category_id: category.category_id,
314
+ category_name: category.category_name,
315
+ });
316
+ }
317
+
318
+ // Track remaining items by category
319
+ if (categoryRemaining.length > 0) {
320
+ remainingItemsByCategory.push({
321
+ category_id: category.category_id,
322
+ category_name: category.category_name,
323
+ items: categoryRemaining,
324
+ });
325
+ }
326
+ }
327
+
328
+ // Step 2: Count total remaining positive items
329
+ const totalRemainingItems = remainingItemsByCategory.reduce(
330
+ (sum, cat) => sum + cat.items.length,
331
+ 0,
332
+ );
333
+
334
+ // Step 3: Decide whether to collapse
335
+ const shouldCollapse = totalRemainingItems >= COLLAPSE_THRESHOLD;
336
+
337
+ // Build subtransactions
338
+ const subtransactions: SubtransactionInput[] = [];
339
+
340
+ // Add special items first (returns, discounts, big tickets)
341
+ for (const special of specialItems) {
342
+ const memo = buildItemMemo({
343
+ name: special.item.name,
344
+ quantity: special.item.quantity,
345
+ memo: special.item.memo,
346
+ });
347
+ const payload: SubtransactionInput = {
348
+ amount: -special.item.amount_milliunits,
349
+ category_id: special.category_id,
350
+ };
351
+ if (memo) payload.memo = memo;
352
+ subtransactions.push(payload);
353
+ }
354
+
355
+ // Add remaining items (collapsed or itemized)
356
+ if (shouldCollapse) {
357
+ // Collapse by category
358
+ for (const categoryGroup of remainingItemsByCategory) {
359
+ const collapsedSubtransactions = collapseItemsByCategory(categoryGroup);
360
+ subtransactions.push(...collapsedSubtransactions);
361
+ }
362
+ } else {
363
+ // Itemize each remaining item individually
364
+ for (const categoryGroup of remainingItemsByCategory) {
365
+ for (const item of categoryGroup.items) {
366
+ const memo = buildItemMemo({
367
+ name: item.name,
368
+ quantity: item.quantity,
369
+ memo: item.memo,
370
+ });
371
+ const payload: SubtransactionInput = {
372
+ amount: -item.amount_milliunits,
373
+ category_id: categoryGroup.category_id,
374
+ };
375
+ if (memo) payload.memo = memo;
376
+ subtransactions.push(payload);
377
+ }
378
+ }
379
+ }
380
+
381
+ // Step 4: Handle tax allocation
382
+ const taxSubtransactions = allocateTax(categoryCalculations, taxMilliunits);
383
+ subtransactions.push(...taxSubtransactions);
384
+
385
+ return subtransactions;
386
+ }
387
+
388
+ /**
389
+ * Collapses items within a category into groups of up to MAX_ITEMS_PER_MEMO
390
+ */
391
+ function collapseItemsByCategory(categoryGroup: {
392
+ category_id: string;
393
+ category_name: string | undefined;
394
+ items: ReceiptCategoryCalculation["items"][0][];
395
+ }): SubtransactionInput[] {
396
+ const subtransactions: SubtransactionInput[] = [];
397
+ const items = categoryGroup.items;
398
+
399
+ let currentBatch: ReceiptCategoryCalculation["items"][0][] = [];
400
+ let currentBatchTotal = 0;
401
+
402
+ for (const item of items) {
403
+ // Check if we've hit the max items per memo
404
+ if (currentBatch.length >= MAX_ITEMS_PER_MEMO) {
405
+ // Flush current batch
406
+ const memo = buildCollapsedMemo(currentBatch);
407
+ subtransactions.push({
408
+ amount: -currentBatchTotal,
409
+ category_id: categoryGroup.category_id,
410
+ memo,
411
+ });
412
+ currentBatch = [];
413
+ currentBatchTotal = 0;
414
+ }
415
+
416
+ // Try adding this item to the current batch
417
+ const testBatch = [...currentBatch, item];
418
+ const testMemo = buildCollapsedMemo(testBatch);
419
+
420
+ if (testMemo.length <= MAX_MEMO_LENGTH) {
421
+ // Fits - add to batch
422
+ currentBatch.push(item);
423
+ currentBatchTotal += item.amount_milliunits;
424
+ } else {
425
+ // Doesn't fit - flush current batch and start new one
426
+ if (currentBatch.length > 0) {
427
+ const memo = buildCollapsedMemo(currentBatch);
428
+ subtransactions.push({
429
+ amount: -currentBatchTotal,
430
+ category_id: categoryGroup.category_id,
431
+ memo,
432
+ });
433
+ currentBatch = [item];
434
+ currentBatchTotal = item.amount_milliunits;
435
+ } else {
436
+ // Edge case: single item is too long, use it anyway
437
+ currentBatch = [item];
438
+ currentBatchTotal = item.amount_milliunits;
439
+ }
440
+ }
441
+ }
442
+
443
+ // Flush remaining batch
444
+ if (currentBatch.length > 0) {
445
+ const memo = buildCollapsedMemo(currentBatch);
446
+ subtransactions.push({
447
+ amount: -currentBatchTotal,
448
+ category_id: categoryGroup.category_id,
449
+ memo,
450
+ });
451
+ }
452
+
453
+ return subtransactions;
454
+ }
455
+
456
+ /**
457
+ * Truncates an item name to fit within available space
458
+ * Preserves the amount suffix and adds "..." to indicate truncation
459
+ */
460
+ function truncateItemName(
461
+ name: string,
462
+ amountSuffix: string,
463
+ maxLength: number,
464
+ ): string {
465
+ const ellipsis = "...";
466
+ // We need: truncatedName + ellipsis + amountSuffix <= maxLength
467
+ const availableForName = maxLength - ellipsis.length - amountSuffix.length;
468
+
469
+ if (availableForName <= 0) {
470
+ // Edge case: amount suffix alone is too long, just return what we can
471
+ return amountSuffix.substring(0, maxLength);
472
+ }
473
+
474
+ return name.substring(0, availableForName) + ellipsis + amountSuffix;
475
+ }
476
+
477
+ /**
478
+ * Builds a collapsed memo from a list of items
479
+ * Format: "Item1 $X.XX, Item2 $Y.YY, Item3 $Z.ZZ"
480
+ * Truncates with "..." if needed (either individual items or the list)
481
+ */
482
+ function buildCollapsedMemo(
483
+ items: ReceiptCategoryCalculation["items"][0][],
484
+ ): string {
485
+ const parts: string[] = [];
486
+ let currentLength = 0;
487
+
488
+ for (let i = 0; i < items.length; i++) {
489
+ const item = items[i];
490
+ if (!item) continue;
491
+ const amount = milliunitsToAmount(item.amount_milliunits);
492
+ const amountSuffix = ` $${amount.toFixed(2)}`;
493
+ let itemStr = `${item.name}${amountSuffix}`;
494
+ const separator = i > 0 ? ", " : "";
495
+
496
+ // For the first item, check if it alone exceeds the limit
497
+ if (parts.length === 0 && itemStr.length > MAX_MEMO_LENGTH) {
498
+ itemStr = truncateItemName(item.name, amountSuffix, MAX_MEMO_LENGTH);
499
+ }
500
+
501
+ const testLength = currentLength + separator.length + itemStr.length;
502
+
503
+ // Check if adding this item would exceed limit
504
+ if (parts.length > 0 && testLength + 4 > MAX_MEMO_LENGTH) {
505
+ // Would exceed - stop here and add "..."
506
+ break;
507
+ }
508
+
509
+ parts.push(itemStr);
510
+ currentLength = testLength;
511
+ }
512
+
513
+ let result = parts.join(", ");
514
+
515
+ // Add "..." if we didn't include all items
516
+ if (parts.length < items.length) {
517
+ result += "...";
518
+ }
519
+
520
+ return result;
521
+ }
522
+
523
+ /**
524
+ * Allocates tax across categories
525
+ * - Positive categories get proportional tax subtransactions
526
+ * - Negative tax creates a single tax refund subtransaction
527
+ */
528
+ function allocateTax(
529
+ categoryCalculations: ReceiptCategoryCalculation[],
530
+ taxMilliunits: number,
531
+ ): SubtransactionInput[] {
532
+ const subtransactions: SubtransactionInput[] = [];
533
+
534
+ // Handle tax = 0
535
+ if (taxMilliunits === 0) {
536
+ return subtransactions;
537
+ }
538
+
539
+ // Handle negative tax (refund)
540
+ if (taxMilliunits < 0) {
541
+ // Find category with largest return
542
+ let largestReturnCategory: ReceiptCategoryCalculation | undefined =
543
+ undefined;
544
+ let largestReturnAmount = 0;
545
+
546
+ for (const category of categoryCalculations) {
547
+ const categoryReturnAmount = category.items
548
+ .filter((item) => item.amount_milliunits < 0)
549
+ .reduce((sum, item) => sum + Math.abs(item.amount_milliunits), 0);
550
+
551
+ if (categoryReturnAmount > largestReturnAmount) {
552
+ largestReturnAmount = categoryReturnAmount;
553
+ largestReturnCategory = category;
554
+ }
555
+ }
556
+
557
+ // Default to first category if no returns found
558
+ if (!largestReturnCategory) {
559
+ largestReturnCategory = categoryCalculations[0];
560
+ }
561
+
562
+ if (largestReturnCategory) {
563
+ subtransactions.push({
564
+ amount: -taxMilliunits,
565
+ category_id: largestReturnCategory.category_id,
566
+ memo: "Tax refund",
567
+ });
568
+ }
569
+
570
+ return subtransactions;
571
+ }
572
+
573
+ // Positive tax - allocate proportionally to positive categories only
574
+ const positiveCategorySubtotals = categoryCalculations
575
+ .map((cat) => ({
576
+ category: cat,
577
+ positiveSubtotal: cat.items
578
+ .filter((item) => item.amount_milliunits > 0)
579
+ .reduce((sum, item) => sum + item.amount_milliunits, 0),
580
+ }))
581
+ .filter((x) => x.positiveSubtotal > 0);
582
+
583
+ if (positiveCategorySubtotals.length === 0) {
584
+ // No positive items, no tax allocation
585
+ return subtransactions;
586
+ }
587
+
588
+ const totalPositiveSubtotal = positiveCategorySubtotals.reduce(
589
+ (sum, x) => sum + x.positiveSubtotal,
590
+ 0,
591
+ );
592
+
593
+ // Distribute tax using largest remainder method
594
+ let allocatedTax = 0;
595
+ const taxAllocations: {
596
+ category: ReceiptCategoryCalculation;
597
+ taxAmount: number;
598
+ }[] = [];
599
+
600
+ for (let i = 0; i < positiveCategorySubtotals.length; i++) {
601
+ const entry = positiveCategorySubtotals[i];
602
+ if (!entry) continue;
603
+
604
+ const { category, positiveSubtotal } = entry;
605
+
606
+ if (i === positiveCategorySubtotals.length - 1) {
607
+ // Last category gets remainder
608
+ const taxAmount = taxMilliunits - allocatedTax;
609
+ if (taxAmount > 0) {
610
+ taxAllocations.push({ category, taxAmount });
611
+ }
612
+ } else {
613
+ const taxAmount = Math.round(
614
+ (taxMilliunits * positiveSubtotal) / totalPositiveSubtotal,
615
+ );
616
+ if (taxAmount > 0) {
617
+ taxAllocations.push({ category, taxAmount });
618
+ allocatedTax += taxAmount;
619
+ }
620
+ }
621
+ }
622
+
623
+ // Create tax subtransactions
624
+ for (const { category, taxAmount } of taxAllocations) {
625
+ subtransactions.push({
626
+ amount: -taxAmount,
627
+ category_id: category.category_id,
628
+ memo: `Tax - ${category.category_name ?? "Uncategorized"}`,
629
+ });
630
+ }
631
+
632
+ return subtransactions;
633
+ }
634
+
635
+ export async function handleCreateReceiptSplitTransaction(
636
+ ynabAPI: ynab.API,
637
+ deltaCache: DeltaCache,
638
+ knowledgeStore: ServerKnowledgeStore,
639
+ params: CreateReceiptSplitTransactionParams,
640
+ ): Promise<CallToolResult>;
641
+ export async function handleCreateReceiptSplitTransaction(
642
+ ynabAPI: ynab.API,
643
+ params: CreateReceiptSplitTransactionParams,
644
+ ): Promise<CallToolResult>;
645
+ export async function handleCreateReceiptSplitTransaction(
646
+ ynabAPI: ynab.API,
647
+ deltaCacheOrParams: DeltaCache | CreateReceiptSplitTransactionParams,
648
+ knowledgeStoreOrParams?:
649
+ | ServerKnowledgeStore
650
+ | CreateReceiptSplitTransactionParams,
651
+ maybeParams?: CreateReceiptSplitTransactionParams,
652
+ _errorHandler?: ErrorHandler,
653
+ ): Promise<CallToolResult> {
654
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
655
+ deltaCacheOrParams,
656
+ knowledgeStoreOrParams,
657
+ maybeParams,
658
+ );
659
+ const date = params.date ?? new Date().toISOString().slice(0, 10);
660
+
661
+ const categoryCalculations: ReceiptCategoryCalculation[] =
662
+ params.categories.map((category) => {
663
+ const items = category.items.map((item) => ({
664
+ name: item.name,
665
+ amount_milliunits: amountToMilliunits(item.amount),
666
+ quantity: item.quantity,
667
+ memo: item.memo,
668
+ }));
669
+ const subtotalMilliunits = items.reduce(
670
+ (sum, item) => sum + item.amount_milliunits,
671
+ 0,
672
+ );
673
+ return {
674
+ category_id: category.category_id,
675
+ category_name: category.category_name,
676
+ subtotal_milliunits: subtotalMilliunits,
677
+ tax_milliunits: 0,
678
+ items,
679
+ };
680
+ });
681
+
682
+ const subtotalMilliunits = categoryCalculations.reduce(
683
+ (sum, category) => sum + category.subtotal_milliunits,
684
+ 0,
685
+ );
686
+
687
+ const declaredSubtotalMilliunits =
688
+ params.receipt_subtotal !== undefined
689
+ ? amountToMilliunits(params.receipt_subtotal)
690
+ : undefined;
691
+ if (
692
+ declaredSubtotalMilliunits !== undefined &&
693
+ Math.abs(declaredSubtotalMilliunits - subtotalMilliunits) > 1
694
+ ) {
695
+ throw new Error(
696
+ `Categorized items subtotal (${milliunitsToAmount(subtotalMilliunits)}) does not match receipt subtotal (${milliunitsToAmount(declaredSubtotalMilliunits)})`,
697
+ );
698
+ }
699
+
700
+ const taxMilliunits = amountToMilliunits(params.receipt_tax);
701
+ const totalMilliunits = amountToMilliunits(params.receipt_total);
702
+ const computedTotal = subtotalMilliunits + taxMilliunits;
703
+ if (Math.abs(computedTotal - totalMilliunits) > 1) {
704
+ throw new Error(
705
+ `Receipt total (${milliunitsToAmount(totalMilliunits)}) does not equal subtotal plus tax (${milliunitsToAmount(computedTotal)})`,
706
+ );
707
+ }
708
+
709
+ // Apply smart collapse logic
710
+ const subtransactions = applySmartCollapseLogic(
711
+ categoryCalculations,
712
+ taxMilliunits,
713
+ );
714
+
715
+ // Distribute tax proportionally for receipt_summary (only for positive categories)
716
+ if (taxMilliunits > 0) {
717
+ const positiveSubtotal = categoryCalculations.reduce(
718
+ (sum, cat) => sum + Math.max(0, cat.subtotal_milliunits),
719
+ 0,
720
+ );
721
+ if (positiveSubtotal > 0) {
722
+ let remainingTax = taxMilliunits;
723
+ const positiveCats = categoryCalculations.filter(
724
+ (cat) => cat.subtotal_milliunits > 0,
725
+ );
726
+ positiveCats.forEach((cat, index) => {
727
+ if (index === positiveCats.length - 1) {
728
+ cat.tax_milliunits = remainingTax;
729
+ } else {
730
+ const share = Math.round(
731
+ (cat.subtotal_milliunits / positiveSubtotal) * taxMilliunits,
732
+ );
733
+ cat.tax_milliunits = share;
734
+ remainingTax -= share;
735
+ }
736
+ });
737
+ }
738
+ }
739
+
740
+ const receiptSummary = {
741
+ subtotal: milliunitsToAmount(subtotalMilliunits),
742
+ tax: milliunitsToAmount(taxMilliunits),
743
+ total: milliunitsToAmount(totalMilliunits),
744
+ categories: categoryCalculations.map((category) => ({
745
+ category_id: category.category_id,
746
+ category_name: category.category_name,
747
+ items: category.items.map((item) => ({
748
+ name: item.name,
749
+ quantity: item.quantity,
750
+ amount: milliunitsToAmount(item.amount_milliunits),
751
+ memo: item.memo,
752
+ })),
753
+ subtotal: milliunitsToAmount(category.subtotal_milliunits),
754
+ tax: milliunitsToAmount(category.tax_milliunits),
755
+ total: milliunitsToAmount(
756
+ category.subtotal_milliunits + category.tax_milliunits,
757
+ ),
758
+ })),
759
+ };
760
+
761
+ if (params.dry_run) {
762
+ return {
763
+ content: [
764
+ {
765
+ type: "text",
766
+ text: responseFormatter.format({
767
+ dry_run: true,
768
+ action: "create_receipt_split_transaction",
769
+ transaction_preview: {
770
+ account_id: params.account_id,
771
+ payee_name: params.payee_name,
772
+ date,
773
+ amount: milliunitsToAmount(totalMilliunits),
774
+ cleared: params.cleared ?? "uncleared",
775
+ },
776
+ receipt_summary: receiptSummary,
777
+ subtransactions: subtransactions.map((subtransaction) => ({
778
+ amount: milliunitsToAmount(-subtransaction.amount),
779
+ category_id: subtransaction.category_id,
780
+ memo: subtransaction.memo,
781
+ })),
782
+ }),
783
+ },
784
+ ],
785
+ };
786
+ }
787
+
788
+ const createTransactionParams: CreateTransactionParams = {
789
+ budget_id: params.budget_id,
790
+ account_id: params.account_id,
791
+ amount: -totalMilliunits,
792
+ date,
793
+ payee_name: params.payee_name,
794
+ memo: params.memo,
795
+ cleared: params.cleared ?? "uncleared",
796
+ flag_color: params.flag_color,
797
+ subtransactions: subtransactions,
798
+ };
799
+
800
+ if (params.approved !== undefined) {
801
+ createTransactionParams.approved = params.approved;
802
+ }
803
+
804
+ const baseResult = await handleCreateTransaction(
805
+ ynabAPI,
806
+ deltaCache,
807
+ knowledgeStore,
808
+ createTransactionParams,
809
+ );
810
+
811
+ const firstContent = baseResult.content?.[0];
812
+ if (!firstContent || firstContent.type !== "text") {
813
+ return baseResult;
814
+ }
815
+
816
+ try {
817
+ const parsed = JSON.parse(firstContent.text) as Record<string, unknown>;
818
+ parsed["receipt_summary"] = receiptSummary;
819
+ firstContent.text = responseFormatter.format(parsed);
820
+ } catch {
821
+ // If parsing fails, return the original result without augmentation.
822
+ }
823
+
824
+ return baseResult;
825
+ }
826
+
827
+ /**
828
+ * Handles the ynab:update_transaction tool call
829
+ * Updates an existing transaction with the provided fields
830
+ */
831
+ export async function handleUpdateTransaction(
832
+ ynabAPI: ynab.API,
833
+ deltaCache: DeltaCache,
834
+ knowledgeStore: ServerKnowledgeStore,
835
+ params: UpdateTransactionParams,
836
+ ): Promise<CallToolResult>;
837
+ export async function handleUpdateTransaction(
838
+ ynabAPI: ynab.API,
839
+ params: UpdateTransactionParams,
840
+ ): Promise<CallToolResult>;
841
+ export async function handleUpdateTransaction(
842
+ ynabAPI: ynab.API,
843
+ deltaCacheOrParams: DeltaCache | UpdateTransactionParams,
844
+ knowledgeStoreOrParams?: ServerKnowledgeStore | UpdateTransactionParams,
845
+ maybeParams?: UpdateTransactionParams,
846
+ _errorHandler?: ErrorHandler,
847
+ ): Promise<CallToolResult> {
848
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
849
+ deltaCacheOrParams,
850
+ knowledgeStoreOrParams,
851
+ maybeParams,
852
+ );
853
+ try {
854
+ if (params.dry_run) {
855
+ return {
856
+ content: [
857
+ {
858
+ type: "text",
859
+ text: responseFormatter.format({
860
+ dry_run: true,
861
+ action: "update_transaction",
862
+ request: params,
863
+ }),
864
+ },
865
+ ],
866
+ };
867
+ }
868
+
869
+ // Get the original transaction before updating to capture the original account_id
870
+ const originalTransactionResponse =
871
+ await ynabAPI.transactions.getTransactionById(
872
+ params.budget_id,
873
+ params.transaction_id,
874
+ );
875
+ const originalTransaction = ensureTransaction(
876
+ originalTransactionResponse.data.transaction,
877
+ "Original transaction not found",
878
+ );
879
+
880
+ // Prepare transaction update data - only include fields that are provided
881
+ const transactionData: SaveTransaction = {};
882
+
883
+ // Only include fields that are provided in the update
884
+ if (params.account_id !== undefined) {
885
+ transactionData.account_id = params.account_id;
886
+ }
887
+ if (params.amount !== undefined) {
888
+ transactionData.amount = params.amount;
889
+ }
890
+ if (params.date !== undefined) {
891
+ transactionData.date = params.date;
892
+ }
893
+ if (params.payee_name !== undefined) {
894
+ transactionData.payee_name = params.payee_name;
895
+ }
896
+ if (params.payee_id !== undefined) {
897
+ transactionData.payee_id = params.payee_id;
898
+ }
899
+ if (params.category_id !== undefined) {
900
+ transactionData.category_id = params.category_id;
901
+ }
902
+ if (params.memo !== undefined) {
903
+ transactionData.memo = params.memo;
904
+ }
905
+ if (params.cleared !== undefined) {
906
+ transactionData.cleared = params.cleared as ynab.TransactionClearedStatus;
907
+ }
908
+ if (params.approved !== undefined) {
909
+ transactionData.approved = params.approved;
910
+ }
911
+ if (params.flag_color !== undefined) {
912
+ transactionData.flag_color =
913
+ params.flag_color as ynab.TransactionFlagColor;
914
+ }
915
+
916
+ const response = await ynabAPI.transactions.updateTransaction(
917
+ params.budget_id,
918
+ params.transaction_id,
919
+ {
920
+ transaction: transactionData,
921
+ },
922
+ );
923
+
924
+ const transaction = ensureTransaction(
925
+ response.data.transaction,
926
+ "Transaction update failed",
927
+ );
928
+
929
+ const specificTransactionCacheKey = CacheManager.generateKey(
930
+ "transaction",
931
+ "get",
932
+ params.budget_id,
933
+ params.transaction_id,
934
+ );
935
+ cacheManager.delete(specificTransactionCacheKey);
936
+
937
+ const affectedAccountIds = new Set<string>([
938
+ originalTransaction.account_id,
939
+ transaction.account_id,
940
+ ]);
941
+
942
+ if (originalTransaction.transfer_account_id) {
943
+ affectedAccountIds.add(originalTransaction.transfer_account_id);
944
+ }
945
+ if (transaction.transfer_account_id) {
946
+ affectedAccountIds.add(transaction.transfer_account_id);
947
+ }
948
+
949
+ const affectedMonths = new Set<string>([
950
+ toMonthKey(originalTransaction.date),
951
+ toMonthKey(transaction.date),
952
+ ]);
953
+ const originalCategoryIds =
954
+ collectCategoryIdsFromSources(originalTransaction);
955
+ const updatedCategoryIds = collectCategoryIdsFromSources(transaction);
956
+ const affectedCategoryIds = new Set<string>([
957
+ ...originalCategoryIds,
958
+ ...updatedCategoryIds,
959
+ ]);
960
+ const categoryChanged = !setsEqual(originalCategoryIds, updatedCategoryIds);
961
+ const amountChanged = transaction.amount !== originalTransaction.amount;
962
+ const accountChanged =
963
+ transaction.account_id !== originalTransaction.account_id;
964
+ const clearedChanged = transaction.cleared !== originalTransaction.cleared;
965
+ const transferAccountChanged =
966
+ transaction.transfer_account_id !==
967
+ originalTransaction.transfer_account_id;
968
+ const transferLinkChanged =
969
+ transaction.transfer_transaction_id !==
970
+ originalTransaction.transfer_transaction_id;
971
+ const dateChanged = transaction.date !== originalTransaction.date;
972
+
973
+ invalidateTransactionCaches(
974
+ deltaCache,
975
+ knowledgeStore,
976
+ params.budget_id,
977
+ response.data.server_knowledge,
978
+ affectedAccountIds,
979
+ affectedMonths,
980
+ {
981
+ affectedCategoryIds,
982
+ accountTotalsChanged:
983
+ amountChanged ||
984
+ accountChanged ||
985
+ clearedChanged ||
986
+ transferAccountChanged ||
987
+ transferLinkChanged,
988
+ invalidateMonths: amountChanged || categoryChanged || dateChanged,
989
+ },
990
+ );
991
+
992
+ // Get the updated account balance
993
+ const accountResponse = await ynabAPI.accounts.getAccountById(
994
+ params.budget_id,
995
+ transaction.account_id,
996
+ );
997
+ const account = accountResponse.data.account;
998
+
999
+ return {
1000
+ content: [
1001
+ {
1002
+ type: "text",
1003
+ text: responseFormatter.format({
1004
+ transaction: {
1005
+ id: transaction.id,
1006
+ date: transaction.date,
1007
+ amount: milliunitsToAmount(transaction.amount),
1008
+ memo: transaction.memo,
1009
+ cleared: transaction.cleared,
1010
+ approved: transaction.approved,
1011
+ flag_color: transaction.flag_color,
1012
+ account_id: transaction.account_id,
1013
+ payee_id: transaction.payee_id,
1014
+ category_id: transaction.category_id,
1015
+ transfer_account_id: transaction.transfer_account_id,
1016
+ transfer_transaction_id: transaction.transfer_transaction_id,
1017
+ matched_transaction_id: transaction.matched_transaction_id,
1018
+ import_id: transaction.import_id,
1019
+ deleted: transaction.deleted,
1020
+ },
1021
+ updated_balance: account.balance,
1022
+ updated_cleared_balance: account.cleared_balance,
1023
+ }),
1024
+ },
1025
+ ],
1026
+ };
1027
+ } catch (error) {
1028
+ return handleTransactionError(error, "Failed to update transaction");
1029
+ }
1030
+ }
1031
+
1032
+ /**
1033
+ * Handles the ynab:delete_transaction tool call
1034
+ * Deletes a transaction from the specified budget
1035
+ */
1036
+ export async function handleDeleteTransaction(
1037
+ ynabAPI: ynab.API,
1038
+ deltaCache: DeltaCache,
1039
+ knowledgeStore: ServerKnowledgeStore,
1040
+ params: DeleteTransactionParams,
1041
+ ): Promise<CallToolResult>;
1042
+ export async function handleDeleteTransaction(
1043
+ ynabAPI: ynab.API,
1044
+ params: DeleteTransactionParams,
1045
+ ): Promise<CallToolResult>;
1046
+ export async function handleDeleteTransaction(
1047
+ ynabAPI: ynab.API,
1048
+ deltaCacheOrParams: DeltaCache | DeleteTransactionParams,
1049
+ knowledgeStoreOrParams?: ServerKnowledgeStore | DeleteTransactionParams,
1050
+ maybeParams?: DeleteTransactionParams,
1051
+ _errorHandler?: ErrorHandler,
1052
+ ): Promise<CallToolResult> {
1053
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1054
+ deltaCacheOrParams,
1055
+ knowledgeStoreOrParams,
1056
+ maybeParams,
1057
+ );
1058
+ try {
1059
+ if (params.dry_run) {
1060
+ return {
1061
+ content: [
1062
+ {
1063
+ type: "text",
1064
+ text: responseFormatter.format({
1065
+ dry_run: true,
1066
+ action: "delete_transaction",
1067
+ request: params,
1068
+ }),
1069
+ },
1070
+ ],
1071
+ };
1072
+ }
1073
+ const response = await ynabAPI.transactions.deleteTransaction(
1074
+ params.budget_id,
1075
+ params.transaction_id,
1076
+ );
1077
+
1078
+ const transaction = ensureTransaction(
1079
+ response.data.transaction,
1080
+ "Transaction deletion failed",
1081
+ );
1082
+
1083
+ const specificTransactionCacheKey = CacheManager.generateKey(
1084
+ "transaction",
1085
+ "get",
1086
+ params.budget_id,
1087
+ params.transaction_id,
1088
+ );
1089
+ cacheManager.delete(specificTransactionCacheKey);
1090
+
1091
+ const affectedAccountIds = new Set<string>([transaction.account_id]);
1092
+ if (transaction.transfer_account_id) {
1093
+ affectedAccountIds.add(transaction.transfer_account_id);
1094
+ }
1095
+
1096
+ const affectedMonths = new Set<string>([toMonthKey(transaction.date)]);
1097
+ const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
1098
+ invalidateTransactionCaches(
1099
+ deltaCache,
1100
+ knowledgeStore,
1101
+ params.budget_id,
1102
+ response.data.server_knowledge,
1103
+ affectedAccountIds,
1104
+ affectedMonths,
1105
+ {
1106
+ affectedCategoryIds,
1107
+ accountTotalsChanged: true,
1108
+ invalidateMonths: true,
1109
+ },
1110
+ );
1111
+
1112
+ // Get the updated account balance
1113
+ const accountResponse = await ynabAPI.accounts.getAccountById(
1114
+ params.budget_id,
1115
+ transaction.account_id,
1116
+ );
1117
+ const account = accountResponse.data.account;
1118
+
1119
+ return {
1120
+ content: [
1121
+ {
1122
+ type: "text",
1123
+ text: responseFormatter.format({
1124
+ message: "Transaction deleted successfully",
1125
+ transaction: {
1126
+ id: transaction.id,
1127
+ deleted: transaction.deleted,
1128
+ },
1129
+ updated_balance: account.balance,
1130
+ updated_cleared_balance: account.cleared_balance,
1131
+ }),
1132
+ },
1133
+ ],
1134
+ };
1135
+ } catch (error) {
1136
+ return handleTransactionError(error, "Failed to delete transaction");
1137
+ }
1138
+ }
1139
+
1140
+ export async function handleCreateTransactions(
1141
+ ynabAPI: ynab.API,
1142
+ deltaCache: DeltaCache,
1143
+ knowledgeStore: ServerKnowledgeStore,
1144
+ params: CreateTransactionsParams,
1145
+ ): Promise<CallToolResult>;
1146
+ export async function handleCreateTransactions(
1147
+ ynabAPI: ynab.API,
1148
+ params: CreateTransactionsParams,
1149
+ ): Promise<CallToolResult>;
1150
+ export async function handleCreateTransactions(
1151
+ ynabAPI: ynab.API,
1152
+ deltaCacheOrParams: DeltaCache | CreateTransactionsParams,
1153
+ knowledgeStoreOrParams?: ServerKnowledgeStore | CreateTransactionsParams,
1154
+ maybeParams?: CreateTransactionsParams,
1155
+ errorHandler?: ErrorHandler,
1156
+ ): Promise<CallToolResult> {
1157
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1158
+ deltaCacheOrParams,
1159
+ knowledgeStoreOrParams,
1160
+ maybeParams,
1161
+ );
1162
+ return (await withToolErrorHandling(
1163
+ async () => {
1164
+ const validationResult = CreateTransactionsSchema.safeParse(params);
1165
+ if (!validationResult.success) {
1166
+ type TransactionIssueIndex = number | null;
1167
+ const issuesByIndex = new Map<TransactionIssueIndex, string[]>();
1168
+ const validationIssues = validationResult.error.issues ?? [];
1169
+ for (const issue of validationIssues) {
1170
+ const transactionIndex = issue.path.find(
1171
+ (segment): segment is number => typeof segment === "number",
1172
+ );
1173
+ const message = issue.message;
1174
+ const issueIndex: TransactionIssueIndex =
1175
+ transactionIndex !== undefined ? transactionIndex : null;
1176
+ const existing = issuesByIndex.get(issueIndex) ?? [];
1177
+ existing.push(message);
1178
+ issuesByIndex.set(issueIndex, existing);
1179
+ }
1180
+
1181
+ const details = Array.from(issuesByIndex.entries()).map(
1182
+ ([index, errors]) => ({
1183
+ transaction_index: index,
1184
+ errors,
1185
+ }),
1186
+ );
1187
+
1188
+ throw new ValidationError(
1189
+ "Bulk transaction validation failed",
1190
+ JSON.stringify(details, null, 2),
1191
+ [
1192
+ "Ensure each transaction includes required fields",
1193
+ "Limit batches to 100 items",
1194
+ ],
1195
+ );
1196
+ }
1197
+
1198
+ const { budget_id, transactions, dry_run } = validationResult.data;
1199
+
1200
+ // Pre-flight duplicate import_id detection within batch
1201
+ const importIdMap = new Map<string, number[]>();
1202
+ for (const [index, transaction] of transactions.entries()) {
1203
+ if (transaction.import_id && transaction.import_id.trim().length > 0) {
1204
+ const existing = importIdMap.get(transaction.import_id);
1205
+ if (existing) {
1206
+ existing.push(index);
1207
+ } else {
1208
+ importIdMap.set(transaction.import_id, [index]);
1209
+ }
1210
+ }
1211
+ }
1212
+
1213
+ const duplicates = Array.from(importIdMap.entries())
1214
+ .filter(([, indices]) => indices.length > 1)
1215
+ .map(([importId, indices]) => ({ import_id: importId, indices }));
1216
+
1217
+ if (duplicates.length > 0) {
1218
+ const details = duplicates.map(({ import_id, indices }) => ({
1219
+ import_id,
1220
+ transaction_indices: indices,
1221
+ count: indices.length,
1222
+ }));
1223
+
1224
+ throw new ValidationError(
1225
+ "Duplicate import_id values detected within batch",
1226
+ JSON.stringify(details, null, 2),
1227
+ [
1228
+ "Ensure each transaction has a unique import_id within the batch",
1229
+ "Remove duplicate import_id values or omit import_id to use hash-based correlation",
1230
+ ],
1231
+ );
1232
+ }
1233
+
1234
+ if (dry_run) {
1235
+ const totalAmount = transactions.reduce(
1236
+ (sum, transaction) => sum + transaction.amount,
1237
+ 0,
1238
+ );
1239
+ const accountsAffected = Array.from(
1240
+ new Set(transactions.map((transaction) => transaction.account_id)),
1241
+ );
1242
+ const categoriesAffected = Array.from(
1243
+ new Set(
1244
+ transactions
1245
+ .map((transaction) => transaction.category_id)
1246
+ .filter((id): id is string => id !== undefined),
1247
+ ),
1248
+ );
1249
+ const sortedDates = [
1250
+ ...transactions.map((transaction) => transaction.date),
1251
+ ].sort();
1252
+ const dateRange =
1253
+ sortedDates.length > 0
1254
+ ? {
1255
+ earliest: sortedDates[0],
1256
+ latest: sortedDates[sortedDates.length - 1],
1257
+ }
1258
+ : undefined;
1259
+
1260
+ const transactionsPreview = transactions
1261
+ .slice(0, 10)
1262
+ .map((transaction, index) => ({
1263
+ request_index: index,
1264
+ account_id: transaction.account_id,
1265
+ date: transaction.date,
1266
+ amount: milliunitsToAmount(transaction.amount),
1267
+ memo: transaction.memo,
1268
+ payee_id: transaction.payee_id,
1269
+ payee_name: transaction.payee_name,
1270
+ category_id: transaction.category_id,
1271
+ import_id: transaction.import_id,
1272
+ }));
1273
+
1274
+ return {
1275
+ content: [
1276
+ {
1277
+ type: "text",
1278
+ text: responseFormatter.format({
1279
+ dry_run: true,
1280
+ action: "create_transactions",
1281
+ validation: "passed",
1282
+ summary: {
1283
+ total_transactions: transactions.length,
1284
+ total_amount: milliunitsToAmount(totalAmount),
1285
+ accounts_affected: accountsAffected,
1286
+ date_range: dateRange,
1287
+ categories_affected: categoriesAffected,
1288
+ },
1289
+ transactions_preview: transactionsPreview,
1290
+ note: "Dry run complete. No transactions created. No caches invalidated. No server_knowledge updated.",
1291
+ }),
1292
+ },
1293
+ ],
1294
+ };
1295
+ }
1296
+
1297
+ const saveTransactions: SaveTransaction[] = transactions.map(
1298
+ (transaction) => {
1299
+ const payload: SaveTransaction = {
1300
+ account_id: transaction.account_id,
1301
+ amount: transaction.amount,
1302
+ date: transaction.date,
1303
+ };
1304
+
1305
+ if (transaction.payee_id !== undefined)
1306
+ payload.payee_id = transaction.payee_id;
1307
+ if (transaction.payee_name !== undefined)
1308
+ payload.payee_name = transaction.payee_name;
1309
+ if (transaction.category_id !== undefined)
1310
+ payload.category_id = transaction.category_id;
1311
+ if (transaction.memo !== undefined) payload.memo = transaction.memo;
1312
+ if (transaction.cleared !== undefined)
1313
+ payload.cleared = transaction.cleared;
1314
+ if (transaction.approved !== undefined)
1315
+ payload.approved = transaction.approved;
1316
+ if (transaction.flag_color !== undefined)
1317
+ payload.flag_color = transaction.flag_color;
1318
+ if (transaction.import_id !== undefined)
1319
+ payload.import_id = transaction.import_id;
1320
+
1321
+ return payload;
1322
+ },
1323
+ );
1324
+
1325
+ const response = await ynabAPI.transactions.createTransactions(
1326
+ budget_id,
1327
+ {
1328
+ transactions: saveTransactions,
1329
+ },
1330
+ );
1331
+
1332
+ const responseData = response.data;
1333
+ const duplicateImportIds = new Set(
1334
+ responseData.duplicate_import_ids ?? [],
1335
+ );
1336
+ const results = correlateResults(
1337
+ transactions,
1338
+ responseData,
1339
+ duplicateImportIds,
1340
+ );
1341
+
1342
+ const summary = {
1343
+ total_requested: transactions.length,
1344
+ created: responseData.transaction_ids?.length ?? 0,
1345
+ duplicates: duplicateImportIds.size,
1346
+ failed: results.filter((result) => result.status === "failed").length,
1347
+ };
1348
+
1349
+ const baseResponse: BulkCreateResponse = {
1350
+ success: summary.failed === 0,
1351
+ server_knowledge: responseData.server_knowledge,
1352
+ summary,
1353
+ results,
1354
+ transactions: responseData.transactions ?? [],
1355
+ duplicate_import_ids: responseData.duplicate_import_ids ?? [],
1356
+ message: `Processed ${summary.total_requested} transactions: ${summary.created} created, ${summary.duplicates} duplicates, ${summary.failed} failed.`,
1357
+ };
1358
+
1359
+ const accountIds = new Set<string>(
1360
+ transactions.map((transaction) => transaction.account_id),
1361
+ );
1362
+ const affectedMonths = new Set<string>(
1363
+ transactions.map((transaction) => toMonthKey(transaction.date)),
1364
+ );
1365
+ const affectedCategoryIds = new Set<string>();
1366
+ for (const created of responseData.transactions ?? []) {
1367
+ appendCategoryIds(created, affectedCategoryIds);
1368
+ }
1369
+ invalidateTransactionCaches(
1370
+ deltaCache,
1371
+ knowledgeStore,
1372
+ budget_id,
1373
+ responseData.server_knowledge,
1374
+ accountIds,
1375
+ affectedMonths,
1376
+ {
1377
+ affectedCategoryIds,
1378
+ accountTotalsChanged: true,
1379
+ invalidateMonths: true,
1380
+ },
1381
+ );
1382
+
1383
+ const finalizedResponse = finalizeResponse(baseResponse);
1384
+
1385
+ return {
1386
+ content: [
1387
+ {
1388
+ type: "text",
1389
+ text: responseFormatter.format(finalizedResponse),
1390
+ },
1391
+ ],
1392
+ };
1393
+ },
1394
+ "ynab:create_transactions",
1395
+ "bulk transaction creation",
1396
+ errorHandler,
1397
+ )) as CallToolResult;
1398
+ }
1399
+
1400
+ /**
1401
+ * Interface for transaction metadata needed for cache invalidation
1402
+ */
1403
+ interface TransactionMetadata {
1404
+ account_id: string;
1405
+ date: string;
1406
+ }
1407
+
1408
+ /**
1409
+ * Result of metadata resolution including both resolved metadata and unresolved IDs
1410
+ */
1411
+ interface MetadataResolutionResult {
1412
+ metadata: Map<string, TransactionMetadata>;
1413
+ unresolvedIds: string[];
1414
+ previewDetails: Map<string, ynab.TransactionDetail>;
1415
+ }
1416
+
1417
+ interface ResolveMetadataOptions {
1418
+ previewTransactionIds?: string[];
1419
+ }
1420
+
1421
+ /**
1422
+ * Resolves metadata for bulk update transactions
1423
+ * Uses a multi-tier approach: request metadata -> cache -> limited API calls
1424
+ * Returns both the resolved metadata and a list of IDs that could not be resolved
1425
+ */
1426
+ async function resolveMetadata(
1427
+ ynabAPI: ynab.API,
1428
+ budgetId: string,
1429
+ transactions: BulkUpdateTransactionInput[],
1430
+ options: ResolveMetadataOptions = {},
1431
+ ): Promise<MetadataResolutionResult> {
1432
+ const metadata = new Map<string, TransactionMetadata>();
1433
+ const needsResolution: string[] = [];
1434
+ const previewIds = new Set(options.previewTransactionIds ?? []);
1435
+ const previewDetails = new Map<string, ynab.TransactionDetail>();
1436
+ const previewIdsNeedingFetch = new Set(previewIds);
1437
+
1438
+ // First pass: Use provided metadata
1439
+ for (const transaction of transactions) {
1440
+ if (transaction.original_account_id && transaction.original_date) {
1441
+ metadata.set(transaction.id, {
1442
+ account_id: transaction.original_account_id,
1443
+ date: transaction.original_date,
1444
+ });
1445
+ } else {
1446
+ needsResolution.push(transaction.id);
1447
+ }
1448
+ }
1449
+
1450
+ if (previewIds.size === 0 && needsResolution.length === 0) {
1451
+ return { metadata, unresolvedIds: [], previewDetails };
1452
+ }
1453
+
1454
+ // Second pass: hydrate from cache for both metadata needs and preview requests
1455
+ const needsResolutionSet = new Set(needsResolution);
1456
+ const cacheLookupIds = new Set<string>([...needsResolution, ...previewIds]);
1457
+ for (const transactionId of cacheLookupIds) {
1458
+ const cacheKey = CacheManager.generateKey(
1459
+ "transaction",
1460
+ "get",
1461
+ budgetId,
1462
+ transactionId,
1463
+ );
1464
+ const cached = cacheManager.get<ynab.TransactionDetail>(cacheKey);
1465
+ if (!cached) {
1466
+ continue;
1467
+ }
1468
+
1469
+ if (needsResolutionSet.has(transactionId)) {
1470
+ metadata.set(transactionId, {
1471
+ account_id: cached.account_id,
1472
+ date: cached.date,
1473
+ });
1474
+ needsResolutionSet.delete(transactionId);
1475
+ }
1476
+ if (previewIds.has(transactionId) && !previewDetails.has(transactionId)) {
1477
+ previewDetails.set(transactionId, cached);
1478
+ previewIdsNeedingFetch.delete(transactionId);
1479
+ }
1480
+ }
1481
+
1482
+ const stillNeedsResolution = Array.from(needsResolutionSet);
1483
+ if (stillNeedsResolution.length === 0 && previewIdsNeedingFetch.size === 0) {
1484
+ return { metadata, unresolvedIds: [], previewDetails };
1485
+ }
1486
+
1487
+ // Third pass: Limited API calls with concurrency limit
1488
+ const MAX_CONCURRENT_FETCHES = 5;
1489
+ const fetchPromises: Promise<void>[] = [];
1490
+ const metadataAwaitingResolution = new Set(stillNeedsResolution);
1491
+ const idsNeedingApiFetch = Array.from(
1492
+ new Set([...stillNeedsResolution, ...previewIdsNeedingFetch]),
1493
+ );
1494
+
1495
+ for (let i = 0; i < idsNeedingApiFetch.length; i += MAX_CONCURRENT_FETCHES) {
1496
+ const batch = idsNeedingApiFetch.slice(i, i + MAX_CONCURRENT_FETCHES);
1497
+ const batchPromises = batch.map(async (transactionId) => {
1498
+ try {
1499
+ const response = await ynabAPI.transactions.getTransactionById(
1500
+ budgetId,
1501
+ transactionId,
1502
+ );
1503
+ const transaction = response.data.transaction;
1504
+ if (transaction) {
1505
+ if (metadataAwaitingResolution.has(transactionId)) {
1506
+ metadata.set(transactionId, {
1507
+ account_id: transaction.account_id,
1508
+ date: transaction.date,
1509
+ });
1510
+ metadataAwaitingResolution.delete(transactionId);
1511
+ }
1512
+ if (
1513
+ previewIdsNeedingFetch.has(transactionId) &&
1514
+ !previewDetails.has(transactionId)
1515
+ ) {
1516
+ previewDetails.set(transactionId, transaction);
1517
+ previewIdsNeedingFetch.delete(transactionId);
1518
+ }
1519
+ }
1520
+ } catch {
1521
+ if (metadataAwaitingResolution.has(transactionId)) {
1522
+ globalRequestLogger.logError(
1523
+ "ynab:update_transactions",
1524
+ "resolve_metadata",
1525
+ { transaction_id: transactionId },
1526
+ "Failed to resolve transaction metadata",
1527
+ );
1528
+ }
1529
+ }
1530
+ });
1531
+ fetchPromises.push(...batchPromises);
1532
+ }
1533
+
1534
+ await Promise.all(fetchPromises);
1535
+ return {
1536
+ metadata,
1537
+ unresolvedIds: Array.from(metadataAwaitingResolution),
1538
+ previewDetails,
1539
+ };
1540
+ }
1541
+
1542
+ /**
1543
+ * Handles the ynab:update_transactions tool call
1544
+ * Updates multiple transactions in a single batch operation
1545
+ */
1546
+ export async function handleUpdateTransactions(
1547
+ ynabAPI: ynab.API,
1548
+ deltaCache: DeltaCache,
1549
+ knowledgeStore: ServerKnowledgeStore,
1550
+ params: UpdateTransactionsParams,
1551
+ ): Promise<CallToolResult>;
1552
+ export async function handleUpdateTransactions(
1553
+ ynabAPI: ynab.API,
1554
+ params: UpdateTransactionsParams,
1555
+ ): Promise<CallToolResult>;
1556
+ export async function handleUpdateTransactions(
1557
+ ynabAPI: ynab.API,
1558
+ deltaCacheOrParams: DeltaCache | UpdateTransactionsParams,
1559
+ knowledgeStoreOrParams?: ServerKnowledgeStore | UpdateTransactionsParams,
1560
+ maybeParams?: UpdateTransactionsParams,
1561
+ errorHandler?: ErrorHandler,
1562
+ ): Promise<CallToolResult> {
1563
+ const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1564
+ deltaCacheOrParams,
1565
+ knowledgeStoreOrParams,
1566
+ maybeParams,
1567
+ );
1568
+ return (await withToolErrorHandling(
1569
+ async () => {
1570
+ const validationResult = UpdateTransactionsSchema.safeParse(params);
1571
+ if (!validationResult.success) {
1572
+ type TransactionIssueIndex = number | null;
1573
+ const issuesByIndex = new Map<TransactionIssueIndex, string[]>();
1574
+ const validationIssues = validationResult.error.issues ?? [];
1575
+ for (const issue of validationIssues) {
1576
+ const transactionIndex = issue.path.find(
1577
+ (segment): segment is number => typeof segment === "number",
1578
+ );
1579
+ const message = issue.message;
1580
+ const issueIndex: TransactionIssueIndex =
1581
+ transactionIndex !== undefined ? transactionIndex : null;
1582
+ const existing = issuesByIndex.get(issueIndex) ?? [];
1583
+ existing.push(message);
1584
+ issuesByIndex.set(issueIndex, existing);
1585
+ }
1586
+
1587
+ const details = Array.from(issuesByIndex.entries()).map(
1588
+ ([index, errors]) => ({
1589
+ transaction_index: index,
1590
+ errors,
1591
+ }),
1592
+ );
1593
+
1594
+ throw new ValidationError(
1595
+ "Bulk transaction update validation failed",
1596
+ JSON.stringify(details, null, 2),
1597
+ [
1598
+ "Ensure each transaction includes an id field",
1599
+ "Limit batches to 100 items",
1600
+ ],
1601
+ );
1602
+ }
1603
+
1604
+ const { budget_id, transactions, dry_run } = validationResult.data;
1605
+
1606
+ if (dry_run) {
1607
+ const previewTransactions = transactions.slice(0, 10);
1608
+ const previewTransactionIds = previewTransactions.map(
1609
+ (transaction) => transaction.id,
1610
+ );
1611
+ // Resolve metadata once and reuse any transaction details for preview rendering
1612
+ const { metadata, unresolvedIds, previewDetails } =
1613
+ await resolveMetadata(ynabAPI, budget_id, transactions, {
1614
+ previewTransactionIds,
1615
+ });
1616
+
1617
+ const transactionsPreview = [];
1618
+ const unavailablePreviewIds: string[] = [];
1619
+
1620
+ for (const transaction of previewTransactions) {
1621
+ const currentState = previewDetails.get(transaction.id);
1622
+ if (!currentState) {
1623
+ unavailablePreviewIds.push(transaction.id);
1624
+ transactionsPreview.push({
1625
+ transaction_id: transaction.id,
1626
+ before: "unavailable",
1627
+ after: transaction,
1628
+ });
1629
+ continue;
1630
+ }
1631
+
1632
+ const before: Record<string, unknown> = {};
1633
+ const after: Record<string, unknown> = {};
1634
+
1635
+ if (
1636
+ transaction.amount !== undefined &&
1637
+ transaction.amount !== currentState.amount
1638
+ ) {
1639
+ before["amount"] = milliunitsToAmount(currentState.amount);
1640
+ after["amount"] = milliunitsToAmount(transaction.amount);
1641
+ }
1642
+ if (
1643
+ transaction.date !== undefined &&
1644
+ transaction.date !== currentState.date
1645
+ ) {
1646
+ before["date"] = currentState.date;
1647
+ after["date"] = transaction.date;
1648
+ }
1649
+ if (
1650
+ transaction.memo !== undefined &&
1651
+ transaction.memo !== currentState.memo
1652
+ ) {
1653
+ before["memo"] = currentState.memo;
1654
+ after["memo"] = transaction.memo;
1655
+ }
1656
+ if (
1657
+ transaction.payee_id !== undefined &&
1658
+ transaction.payee_id !== currentState.payee_id
1659
+ ) {
1660
+ before["payee_id"] = currentState.payee_id;
1661
+ after["payee_id"] = transaction.payee_id;
1662
+ }
1663
+ if (
1664
+ transaction.payee_name !== undefined &&
1665
+ transaction.payee_name !== currentState.payee_name
1666
+ ) {
1667
+ before["payee_name"] = currentState.payee_name;
1668
+ after["payee_name"] = transaction.payee_name;
1669
+ }
1670
+ if (
1671
+ transaction.category_id !== undefined &&
1672
+ transaction.category_id !== currentState.category_id
1673
+ ) {
1674
+ before["category_id"] = currentState.category_id;
1675
+ after["category_id"] = transaction.category_id;
1676
+ }
1677
+ if (
1678
+ transaction.cleared !== undefined &&
1679
+ transaction.cleared !== currentState.cleared
1680
+ ) {
1681
+ before["cleared"] = currentState.cleared;
1682
+ after["cleared"] = transaction.cleared;
1683
+ }
1684
+ if (
1685
+ transaction.approved !== undefined &&
1686
+ transaction.approved !== currentState.approved
1687
+ ) {
1688
+ before["approved"] = currentState.approved;
1689
+ after["approved"] = transaction.approved;
1690
+ }
1691
+ if (
1692
+ transaction.flag_color !== undefined &&
1693
+ transaction.flag_color !== currentState.flag_color
1694
+ ) {
1695
+ before["flag_color"] = currentState.flag_color;
1696
+ after["flag_color"] = transaction.flag_color;
1697
+ }
1698
+
1699
+ transactionsPreview.push({
1700
+ transaction_id: transaction.id,
1701
+ before,
1702
+ after,
1703
+ });
1704
+ }
1705
+
1706
+ // Build warnings array
1707
+ const warnings: {
1708
+ code: string;
1709
+ count: number;
1710
+ message: string;
1711
+ sample_ids?: string[];
1712
+ }[] = [];
1713
+ if (unavailablePreviewIds.length > 0 || unresolvedIds.length > 0) {
1714
+ const totalMissing = Math.max(
1715
+ unavailablePreviewIds.length,
1716
+ unresolvedIds.length,
1717
+ );
1718
+ const sampleIds =
1719
+ unresolvedIds.length > 0
1720
+ ? unresolvedIds.slice(0, 10)
1721
+ : unavailablePreviewIds.slice(0, 10);
1722
+ warnings.push({
1723
+ code: "metadata_unavailable",
1724
+ count: totalMissing,
1725
+ message: `Unable to fetch prior state for ${totalMissing} transactions`,
1726
+ sample_ids: sampleIds,
1727
+ });
1728
+ }
1729
+
1730
+ // Collect summary statistics
1731
+ const accountsAffected = Array.from(
1732
+ new Set(Array.from(metadata.values()).map((m) => m.account_id)),
1733
+ );
1734
+ const fieldsToUpdate = new Set<string>();
1735
+ for (const transaction of transactions) {
1736
+ if (transaction.amount !== undefined) fieldsToUpdate.add("amount");
1737
+ if (transaction.date !== undefined) fieldsToUpdate.add("date");
1738
+ if (transaction.memo !== undefined) fieldsToUpdate.add("memo");
1739
+ if (transaction.payee_id !== undefined)
1740
+ fieldsToUpdate.add("payee_id");
1741
+ if (transaction.payee_name !== undefined)
1742
+ fieldsToUpdate.add("payee_name");
1743
+ if (transaction.category_id !== undefined)
1744
+ fieldsToUpdate.add("category_id");
1745
+ if (transaction.cleared !== undefined) fieldsToUpdate.add("cleared");
1746
+ if (transaction.approved !== undefined)
1747
+ fieldsToUpdate.add("approved");
1748
+ if (transaction.flag_color !== undefined)
1749
+ fieldsToUpdate.add("flag_color");
1750
+ }
1751
+
1752
+ const response: Record<string, unknown> = {
1753
+ dry_run: true,
1754
+ action: "update_transactions",
1755
+ validation: "passed",
1756
+ summary: {
1757
+ total_transactions: transactions.length,
1758
+ accounts_affected: accountsAffected,
1759
+ fields_to_update: Array.from(fieldsToUpdate),
1760
+ },
1761
+ transactions_preview: transactionsPreview,
1762
+ note: "Dry run complete. No transactions updated. No caches invalidated. No server_knowledge updated.",
1763
+ };
1764
+
1765
+ if (warnings.length > 0) {
1766
+ response["warnings"] = warnings;
1767
+ }
1768
+
1769
+ return {
1770
+ content: [
1771
+ {
1772
+ type: "text",
1773
+ text: responseFormatter.format(response),
1774
+ },
1775
+ ],
1776
+ };
1777
+ }
1778
+
1779
+ // Resolve metadata for cache invalidation before making updates
1780
+ const { metadata, unresolvedIds } = await resolveMetadata(
1781
+ ynabAPI,
1782
+ budget_id,
1783
+ transactions,
1784
+ );
1785
+
1786
+ // Check metadata completeness threshold (5%)
1787
+ const missingMetadataRatio = unresolvedIds.length / transactions.length;
1788
+ const METADATA_THRESHOLD = 0.05; // 5%
1789
+
1790
+ if (missingMetadataRatio > METADATA_THRESHOLD) {
1791
+ throw new ValidationError(
1792
+ `METADATA_INCOMPLETE: ${(missingMetadataRatio * 100).toFixed(1)}% of transactions have missing metadata (threshold: ${(METADATA_THRESHOLD * 100).toFixed(0)}%)`,
1793
+ JSON.stringify(
1794
+ {
1795
+ unresolved_count: unresolvedIds.length,
1796
+ total_transactions: transactions.length,
1797
+ ratio: `${(missingMetadataRatio * 100).toFixed(1)}%`,
1798
+ threshold: `${(METADATA_THRESHOLD * 100).toFixed(0)}%`,
1799
+ sample_unresolved_ids: unresolvedIds.slice(0, 5),
1800
+ },
1801
+ null,
1802
+ 2,
1803
+ ),
1804
+ [
1805
+ "Provide original_account_id and original_date for all transactions being updated",
1806
+ "Ensure transactions exist in YNAB before updating them",
1807
+ ],
1808
+ );
1809
+ }
1810
+
1811
+ if (missingMetadataRatio > 0.01) {
1812
+ globalRequestLogger.logRequest(
1813
+ "ynab:update_transactions",
1814
+ "metadata_resolution_warning",
1815
+ {
1816
+ unresolved_count: unresolvedIds.length,
1817
+ total_transactions: transactions.length,
1818
+ ratio: missingMetadataRatio.toFixed(3),
1819
+ sample_ids: unresolvedIds.slice(0, 5),
1820
+ message: "Metadata resolution incomplete for some transactions",
1821
+ },
1822
+ true,
1823
+ );
1824
+ }
1825
+
1826
+ // Prepare update transactions for the YNAB API
1827
+ const updateTransactions: { id: string; transaction: SaveTransaction }[] =
1828
+ transactions.map((transaction) => {
1829
+ const transactionData: SaveTransaction = {};
1830
+
1831
+ // Note: account_id is intentionally excluded as account moves are not supported
1832
+ if (transaction.amount !== undefined) {
1833
+ transactionData.amount = transaction.amount;
1834
+ }
1835
+ if (transaction.date !== undefined) {
1836
+ transactionData.date = transaction.date;
1837
+ }
1838
+ if (transaction.payee_name !== undefined) {
1839
+ transactionData.payee_name = transaction.payee_name;
1840
+ }
1841
+ if (transaction.payee_id !== undefined) {
1842
+ transactionData.payee_id = transaction.payee_id;
1843
+ }
1844
+ if (transaction.category_id !== undefined) {
1845
+ transactionData.category_id = transaction.category_id;
1846
+ }
1847
+ if (transaction.memo !== undefined) {
1848
+ transactionData.memo = transaction.memo;
1849
+ }
1850
+ if (transaction.cleared !== undefined) {
1851
+ transactionData.cleared =
1852
+ transaction.cleared as ynab.TransactionClearedStatus;
1853
+ }
1854
+ if (transaction.approved !== undefined) {
1855
+ transactionData.approved = transaction.approved;
1856
+ }
1857
+ if (transaction.flag_color !== undefined) {
1858
+ transactionData.flag_color =
1859
+ transaction.flag_color as ynab.TransactionFlagColor;
1860
+ }
1861
+
1862
+ return {
1863
+ id: transaction.id,
1864
+ transaction: transactionData,
1865
+ };
1866
+ });
1867
+
1868
+ // Execute bulk update
1869
+ const response = await ynabAPI.transactions.updateTransactions(
1870
+ budget_id,
1871
+ {
1872
+ transactions: updateTransactions,
1873
+ },
1874
+ );
1875
+
1876
+ const responseData = response.data;
1877
+ const updatedTransactions = responseData.transactions ?? [];
1878
+
1879
+ // Build results
1880
+ const results: BulkUpdateResult[] = [];
1881
+ const updatedIds = new Set(updatedTransactions.map((t) => t.id));
1882
+
1883
+ for (const [index, transaction] of transactions.entries()) {
1884
+ if (updatedIds.has(transaction.id)) {
1885
+ results.push({
1886
+ request_index: index,
1887
+ status: "updated",
1888
+ transaction_id: transaction.id,
1889
+ correlation_key: transaction.id,
1890
+ });
1891
+ } else {
1892
+ results.push({
1893
+ request_index: index,
1894
+ status: "failed",
1895
+ transaction_id: transaction.id,
1896
+ correlation_key: transaction.id,
1897
+ error_code: "update_failed",
1898
+ error: "Transaction was not updated by YNAB API",
1899
+ });
1900
+ }
1901
+ }
1902
+
1903
+ const summary = {
1904
+ total_requested: transactions.length,
1905
+ updated: updatedTransactions.length,
1906
+ failed: results.filter((r) => r.status === "failed").length,
1907
+ };
1908
+
1909
+ const baseResponse: BulkUpdateResponse = {
1910
+ success: summary.failed === 0,
1911
+ server_knowledge: responseData.server_knowledge,
1912
+ summary,
1913
+ results,
1914
+ transactions: updatedTransactions,
1915
+ message: `Processed ${summary.total_requested} transactions: ${summary.updated} updated, ${summary.failed} failed.`,
1916
+ };
1917
+
1918
+ for (const transaction of transactions) {
1919
+ cacheManager.delete(
1920
+ CacheManager.generateKey(
1921
+ "transaction",
1922
+ "get",
1923
+ budget_id,
1924
+ transaction.id,
1925
+ ),
1926
+ );
1927
+ }
1928
+
1929
+ const affectedAccountIds = new Set<string>();
1930
+ const affectedMonthKeys = new Set<string>();
1931
+ const affectedCategoryIds = new Set<string>();
1932
+ let invalidateAllCategories = false;
1933
+ let accountTotalsChanged = false;
1934
+ let monthsImpacted = false;
1935
+
1936
+ for (const transaction of transactions) {
1937
+ const meta = metadata.get(transaction.id);
1938
+ const amountChanged = transaction.amount !== undefined;
1939
+ const clearedChanged = transaction.cleared !== undefined;
1940
+ const categoryChanged = transaction.category_id !== undefined;
1941
+ const dateChanged = transaction.date !== undefined;
1942
+
1943
+ if ((amountChanged || clearedChanged) && meta) {
1944
+ affectedAccountIds.add(meta.account_id);
1945
+ }
1946
+
1947
+ if (amountChanged) {
1948
+ monthsImpacted = true;
1949
+ accountTotalsChanged = true;
1950
+ invalidateAllCategories = true;
1951
+ if (meta) {
1952
+ affectedMonthKeys.add(toMonthKey(meta.date));
1953
+ }
1954
+ }
1955
+
1956
+ if (categoryChanged) {
1957
+ monthsImpacted = true;
1958
+ invalidateAllCategories = true;
1959
+ if (transaction.category_id) {
1960
+ affectedCategoryIds.add(transaction.category_id);
1961
+ }
1962
+ if (meta) {
1963
+ affectedMonthKeys.add(toMonthKey(meta.date));
1964
+ }
1965
+ }
1966
+
1967
+ if (dateChanged && meta) {
1968
+ monthsImpacted = true;
1969
+ affectedMonthKeys.add(toMonthKey(meta.date));
1970
+ }
1971
+ if (dateChanged && transaction.date) {
1972
+ affectedMonthKeys.add(toMonthKey(transaction.date));
1973
+ }
1974
+ }
1975
+
1976
+ invalidateTransactionCaches(
1977
+ deltaCache,
1978
+ knowledgeStore,
1979
+ budget_id,
1980
+ responseData.server_knowledge,
1981
+ affectedAccountIds,
1982
+ affectedMonthKeys,
1983
+ {
1984
+ affectedCategoryIds,
1985
+ invalidateAllCategories,
1986
+ accountTotalsChanged,
1987
+ invalidateMonths: monthsImpacted,
1988
+ },
1989
+ );
1990
+
1991
+ const finalizedResponse = finalizeBulkUpdateResponse(baseResponse);
1992
+
1993
+ return {
1994
+ content: [
1995
+ {
1996
+ type: "text",
1997
+ text: responseFormatter.format(finalizedResponse),
1998
+ },
1999
+ ],
2000
+ };
2001
+ },
2002
+ "ynab:update_transactions",
2003
+ "bulk transaction update",
2004
+ errorHandler,
2005
+ )) as CallToolResult;
2006
+ }
2007
+
2008
+ /**
2009
+ * Registers write transaction tools with the provided registry.
2010
+ */
2011
+ export function registerTransactionWriteTools(
2012
+ registry: ToolRegistry,
2013
+ context: ToolContext,
2014
+ ): void {
2015
+ const { adaptWrite } = createAdapters(context);
2016
+ const budgetResolver = createBudgetResolver(context);
2017
+
2018
+ registry.register({
2019
+ name: "create_transaction",
2020
+ description: "Create a new transaction in the specified budget and account",
2021
+ inputSchema: CreateTransactionSchema,
2022
+ handler: adaptWrite(handleCreateTransaction),
2023
+ defaultArgumentResolver:
2024
+ budgetResolver<z.infer<typeof CreateTransactionSchema>>(),
2025
+ metadata: {
2026
+ annotations: {
2027
+ ...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
2028
+ title: "YNAB: Create Transaction",
2029
+ },
2030
+ },
2031
+ });
2032
+
2033
+ registry.register({
2034
+ name: "create_transactions",
2035
+ description:
2036
+ "Create multiple transactions in a single batch (1-100 items) with duplicate detection, dry-run validation, and automatic response size management with correlation metadata.",
2037
+ inputSchema: CreateTransactionsSchema,
2038
+ handler: adaptWrite(handleCreateTransactions),
2039
+ defaultArgumentResolver:
2040
+ budgetResolver<z.infer<typeof CreateTransactionsSchema>>(),
2041
+ metadata: {
2042
+ annotations: {
2043
+ ...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
2044
+ title: "YNAB: Create Multiple Transactions",
2045
+ },
2046
+ },
2047
+ });
2048
+
2049
+ registry.register({
2050
+ name: "create_receipt_split_transaction",
2051
+ description:
2052
+ "Create a split transaction from receipt items with proportional tax allocation",
2053
+ inputSchema: CreateReceiptSplitTransactionSchema,
2054
+ handler: adaptWrite(handleCreateReceiptSplitTransaction),
2055
+ defaultArgumentResolver:
2056
+ budgetResolver<z.infer<typeof CreateReceiptSplitTransactionSchema>>(),
2057
+ metadata: {
2058
+ annotations: {
2059
+ ...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
2060
+ title: "YNAB: Create Split Transaction from Receipt",
2061
+ },
2062
+ },
2063
+ });
2064
+
2065
+ registry.register({
2066
+ name: "update_transaction",
2067
+ description: "Update an existing transaction",
2068
+ inputSchema: UpdateTransactionSchema,
2069
+ handler: adaptWrite(handleUpdateTransaction),
2070
+ defaultArgumentResolver:
2071
+ budgetResolver<z.infer<typeof UpdateTransactionSchema>>(),
2072
+ metadata: {
2073
+ annotations: {
2074
+ ...ToolAnnotationPresets.WRITE_EXTERNAL_UPDATE,
2075
+ title: "YNAB: Update Transaction",
2076
+ },
2077
+ },
2078
+ });
2079
+
2080
+ registry.register({
2081
+ name: "update_transactions",
2082
+ description:
2083
+ "Update multiple transactions in a single batch (1-100 items) with dry-run validation, automatic cache invalidation, and response size management. Supports optional original_account_id and original_date metadata for efficient cache invalidation.",
2084
+ inputSchema: UpdateTransactionsSchema,
2085
+ handler: adaptWrite(handleUpdateTransactions),
2086
+ defaultArgumentResolver:
2087
+ budgetResolver<z.infer<typeof UpdateTransactionsSchema>>(),
2088
+ metadata: {
2089
+ annotations: {
2090
+ ...ToolAnnotationPresets.WRITE_EXTERNAL_UPDATE,
2091
+ title: "YNAB: Update Multiple Transactions",
2092
+ },
2093
+ },
2094
+ });
2095
+
2096
+ registry.register({
2097
+ name: "delete_transaction",
2098
+ description: "Delete a transaction from the specified budget",
2099
+ inputSchema: DeleteTransactionSchema,
2100
+ handler: adaptWrite(handleDeleteTransaction),
2101
+ defaultArgumentResolver:
2102
+ budgetResolver<z.infer<typeof DeleteTransactionSchema>>(),
2103
+ metadata: {
2104
+ annotations: {
2105
+ ...ToolAnnotationPresets.WRITE_EXTERNAL_DELETE,
2106
+ title: "YNAB: Delete Transaction",
2107
+ },
2108
+ },
2109
+ });
2110
+ }