@dizzlkheinz/ynab-mcpb 0.18.3 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (346) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/CLAUDE.md +87 -8
  3. package/bin/ynab-mcp-server.cjs +2 -2
  4. package/bin/ynab-mcp-server.js +3 -3
  5. package/biome.json +39 -0
  6. package/dist/bundle/index.cjs +67 -67
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +27 -27
  9. package/dist/server/YNABMCPServer.d.ts +3 -4
  10. package/dist/server/YNABMCPServer.js +111 -116
  11. package/dist/server/budgetResolver.d.ts +6 -5
  12. package/dist/server/budgetResolver.js +46 -36
  13. package/dist/server/cacheKeys.js +6 -6
  14. package/dist/server/cacheManager.js +14 -11
  15. package/dist/server/completions.d.ts +2 -2
  16. package/dist/server/completions.js +20 -15
  17. package/dist/server/config.d.ts +10 -5
  18. package/dist/server/config.js +24 -7
  19. package/dist/server/deltaCache.d.ts +2 -2
  20. package/dist/server/deltaCache.js +22 -16
  21. package/dist/server/deltaCache.merge.d.ts +2 -2
  22. package/dist/server/diagnostics.d.ts +4 -4
  23. package/dist/server/diagnostics.js +38 -32
  24. package/dist/server/errorHandler.d.ts +5 -12
  25. package/dist/server/errorHandler.js +219 -217
  26. package/dist/server/prompts.d.ts +2 -2
  27. package/dist/server/prompts.js +45 -45
  28. package/dist/server/rateLimiter.js +4 -4
  29. package/dist/server/requestLogger.d.ts +1 -1
  30. package/dist/server/requestLogger.js +40 -35
  31. package/dist/server/resources.d.ts +3 -3
  32. package/dist/server/resources.js +55 -52
  33. package/dist/server/responseFormatter.js +6 -6
  34. package/dist/server/securityMiddleware.d.ts +2 -2
  35. package/dist/server/securityMiddleware.js +22 -20
  36. package/dist/server/serverKnowledgeStore.js +1 -1
  37. package/dist/server/toolRegistry.d.ts +3 -3
  38. package/dist/server/toolRegistry.js +47 -40
  39. package/dist/tools/__tests__/deltaTestUtils.d.ts +3 -3
  40. package/dist/tools/__tests__/deltaTestUtils.js +2 -2
  41. package/dist/tools/accountTools.d.ts +9 -8
  42. package/dist/tools/accountTools.js +47 -47
  43. package/dist/tools/adapters.d.ts +13 -8
  44. package/dist/tools/adapters.js +21 -11
  45. package/dist/tools/budgetTools.d.ts +8 -7
  46. package/dist/tools/budgetTools.js +22 -22
  47. package/dist/tools/categoryTools.d.ts +9 -8
  48. package/dist/tools/categoryTools.js +68 -59
  49. package/dist/tools/compareTransactions/formatter.d.ts +3 -3
  50. package/dist/tools/compareTransactions/formatter.js +9 -9
  51. package/dist/tools/compareTransactions/index.d.ts +6 -6
  52. package/dist/tools/compareTransactions/index.js +58 -43
  53. package/dist/tools/compareTransactions/matcher.d.ts +1 -1
  54. package/dist/tools/compareTransactions/matcher.js +28 -15
  55. package/dist/tools/compareTransactions/parser.d.ts +2 -2
  56. package/dist/tools/compareTransactions/parser.js +144 -138
  57. package/dist/tools/compareTransactions/types.d.ts +4 -4
  58. package/dist/tools/compareTransactions.d.ts +1 -1
  59. package/dist/tools/compareTransactions.js +1 -1
  60. package/dist/tools/deltaFetcher.d.ts +2 -2
  61. package/dist/tools/deltaFetcher.js +16 -15
  62. package/dist/tools/deltaSupport.d.ts +4 -4
  63. package/dist/tools/deltaSupport.js +35 -41
  64. package/dist/tools/exportTransactions.d.ts +5 -4
  65. package/dist/tools/exportTransactions.js +61 -59
  66. package/dist/tools/monthTools.d.ts +7 -6
  67. package/dist/tools/monthTools.js +31 -29
  68. package/dist/tools/payeeTools.d.ts +7 -6
  69. package/dist/tools/payeeTools.js +28 -28
  70. package/dist/tools/reconcileAdapter.d.ts +2 -2
  71. package/dist/tools/reconcileAdapter.js +21 -11
  72. package/dist/tools/reconciliation/analyzer.d.ts +4 -4
  73. package/dist/tools/reconciliation/analyzer.js +136 -57
  74. package/dist/tools/reconciliation/csvParser.d.ts +3 -3
  75. package/dist/tools/reconciliation/csvParser.js +128 -104
  76. package/dist/tools/reconciliation/executor.d.ts +4 -4
  77. package/dist/tools/reconciliation/executor.js +148 -109
  78. package/dist/tools/reconciliation/index.d.ts +10 -10
  79. package/dist/tools/reconciliation/index.js +96 -83
  80. package/dist/tools/reconciliation/matcher.d.ts +3 -3
  81. package/dist/tools/reconciliation/matcher.js +17 -16
  82. package/dist/tools/reconciliation/payeeNormalizer.js +19 -8
  83. package/dist/tools/reconciliation/recommendationEngine.d.ts +1 -1
  84. package/dist/tools/reconciliation/recommendationEngine.js +40 -40
  85. package/dist/tools/reconciliation/reportFormatter.d.ts +2 -2
  86. package/dist/tools/reconciliation/reportFormatter.js +79 -54
  87. package/dist/tools/reconciliation/signDetector.d.ts +1 -1
  88. package/dist/tools/reconciliation/types.d.ts +19 -16
  89. package/dist/tools/reconciliation/ynabAdapter.d.ts +2 -2
  90. package/dist/tools/schemas/common.d.ts +1 -1
  91. package/dist/tools/schemas/common.js +1 -1
  92. package/dist/tools/schemas/outputs/accountOutputs.d.ts +1 -1
  93. package/dist/tools/schemas/outputs/accountOutputs.js +24 -18
  94. package/dist/tools/schemas/outputs/budgetOutputs.d.ts +1 -1
  95. package/dist/tools/schemas/outputs/budgetOutputs.js +14 -11
  96. package/dist/tools/schemas/outputs/categoryOutputs.d.ts +1 -1
  97. package/dist/tools/schemas/outputs/categoryOutputs.js +49 -29
  98. package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +1 -1
  99. package/dist/tools/schemas/outputs/comparisonOutputs.js +12 -12
  100. package/dist/tools/schemas/outputs/index.d.ts +14 -14
  101. package/dist/tools/schemas/outputs/index.js +14 -14
  102. package/dist/tools/schemas/outputs/monthOutputs.d.ts +1 -1
  103. package/dist/tools/schemas/outputs/monthOutputs.js +56 -41
  104. package/dist/tools/schemas/outputs/payeeOutputs.d.ts +1 -1
  105. package/dist/tools/schemas/outputs/payeeOutputs.js +10 -10
  106. package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +2 -2
  107. package/dist/tools/schemas/outputs/reconciliationOutputs.js +45 -45
  108. package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +1 -1
  109. package/dist/tools/schemas/outputs/transactionMutationOutputs.js +28 -22
  110. package/dist/tools/schemas/outputs/transactionOutputs.d.ts +1 -1
  111. package/dist/tools/schemas/outputs/transactionOutputs.js +43 -35
  112. package/dist/tools/schemas/outputs/utilityOutputs.d.ts +1 -1
  113. package/dist/tools/schemas/outputs/utilityOutputs.js +5 -3
  114. package/dist/tools/schemas/shared/commonOutputs.d.ts +1 -1
  115. package/dist/tools/schemas/shared/commonOutputs.js +15 -9
  116. package/dist/tools/transactionReadTools.d.ts +11 -0
  117. package/dist/tools/transactionReadTools.js +202 -0
  118. package/dist/tools/transactionSchemas.d.ts +309 -0
  119. package/dist/tools/transactionSchemas.js +235 -0
  120. package/dist/tools/transactionTools.d.ts +6 -302
  121. package/dist/tools/transactionTools.js +7 -2054
  122. package/dist/tools/transactionUtils.d.ts +31 -0
  123. package/dist/tools/transactionUtils.js +364 -0
  124. package/dist/tools/transactionWriteTools.d.ts +20 -0
  125. package/dist/tools/transactionWriteTools.js +1342 -0
  126. package/dist/tools/utilityTools.d.ts +5 -4
  127. package/dist/tools/utilityTools.js +11 -11
  128. package/dist/types/index.d.ts +7 -7
  129. package/dist/types/index.js +6 -6
  130. package/dist/types/reconciliation.d.ts +1 -1
  131. package/dist/types/toolRegistration.d.ts +14 -12
  132. package/dist/utils/amountUtils.js +1 -1
  133. package/dist/utils/dateUtils.js +4 -4
  134. package/dist/utils/errors.d.ts +3 -3
  135. package/dist/utils/errors.js +4 -4
  136. package/dist/utils/money.d.ts +2 -2
  137. package/dist/utils/money.js +8 -8
  138. package/dist/utils/validationError.d.ts +1 -1
  139. package/dist/utils/validationError.js +1 -1
  140. package/docs/assets/examples/reconciliation-with-recommendations.json +66 -66
  141. package/docs/assets/schemas/reconciliation-v2.json +360 -336
  142. package/docs/plans/2025-12-25-transaction-tools-refactor-design.md +211 -0
  143. package/docs/plans/2025-12-25-transaction-tools-refactor.md +905 -0
  144. package/esbuild.config.mjs +53 -50
  145. package/meta.json +12548 -12548
  146. package/package.json +98 -109
  147. package/scripts/analyze-bundle.mjs +33 -30
  148. package/scripts/create-pr-description.js +169 -120
  149. package/scripts/run-all-tests.js +205 -0
  150. package/scripts/run-domain-integration-tests.js +28 -18
  151. package/scripts/run-generate-mcpb.js +19 -17
  152. package/scripts/run-throttled-integration-tests.js +92 -83
  153. package/scripts/test-delta-params.mjs +149 -120
  154. package/scripts/test-recommendations.ts +36 -32
  155. package/scripts/tmpTransaction.ts +80 -43
  156. package/scripts/validate-env.js +98 -91
  157. package/scripts/verify-build.js +78 -76
  158. package/src/__tests__/comprehensive.integration.test.ts +1281 -1154
  159. package/src/__tests__/performance.test.ts +723 -671
  160. package/src/__tests__/setup.ts +442 -395
  161. package/src/__tests__/smoke.e2e.test.ts +41 -39
  162. package/src/__tests__/testRunner.ts +314 -295
  163. package/src/__tests__/testUtils.ts +456 -364
  164. package/src/__tests__/tools/reconciliation/csvParser.integration.test.ts +109 -107
  165. package/src/__tests__/tools/reconciliation/real-world.integration.test.ts +41 -41
  166. package/src/index.ts +68 -59
  167. package/src/server/CLAUDE.md +480 -0
  168. package/src/server/YNABMCPServer.ts +821 -794
  169. package/src/server/__tests__/YNABMCPServer.integration.test.ts +929 -893
  170. package/src/server/__tests__/YNABMCPServer.test.ts +903 -899
  171. package/src/server/__tests__/budgetResolver.test.ts +466 -423
  172. package/src/server/__tests__/cacheManager.test.ts +891 -874
  173. package/src/server/__tests__/completions.integration.test.ts +115 -106
  174. package/src/server/__tests__/completions.test.ts +334 -313
  175. package/src/server/__tests__/config.test.ts +98 -86
  176. package/src/server/__tests__/deltaCache.merge.test.ts +774 -703
  177. package/src/server/__tests__/deltaCache.swr.test.ts +198 -153
  178. package/src/server/__tests__/deltaCache.test.ts +946 -759
  179. package/src/server/__tests__/diagnostics.test.ts +825 -792
  180. package/src/server/__tests__/errorHandler.integration.test.ts +512 -462
  181. package/src/server/__tests__/errorHandler.test.ts +402 -397
  182. package/src/server/__tests__/prompts.test.ts +424 -347
  183. package/src/server/__tests__/rateLimiter.test.ts +313 -309
  184. package/src/server/__tests__/requestLogger.test.ts +443 -403
  185. package/src/server/__tests__/resources.template.test.ts +196 -185
  186. package/src/server/__tests__/resources.test.ts +294 -288
  187. package/src/server/__tests__/security.integration.test.ts +487 -421
  188. package/src/server/__tests__/securityMiddleware.test.ts +519 -444
  189. package/src/server/__tests__/server-startup.integration.test.ts +509 -490
  190. package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -173
  191. package/src/server/__tests__/toolRegistration.test.ts +239 -210
  192. package/src/server/__tests__/toolRegistry.test.ts +907 -845
  193. package/src/server/budgetResolver.ts +221 -181
  194. package/src/server/cacheKeys.ts +6 -6
  195. package/src/server/cacheManager.ts +498 -484
  196. package/src/server/completions.ts +267 -243
  197. package/src/server/config.ts +35 -14
  198. package/src/server/deltaCache.merge.ts +146 -128
  199. package/src/server/deltaCache.ts +352 -309
  200. package/src/server/diagnostics.ts +257 -242
  201. package/src/server/errorHandler.ts +747 -744
  202. package/src/server/prompts.ts +181 -176
  203. package/src/server/rateLimiter.ts +131 -129
  204. package/src/server/requestLogger.ts +350 -322
  205. package/src/server/resources.ts +442 -374
  206. package/src/server/responseFormatter.ts +41 -37
  207. package/src/server/securityMiddleware.ts +223 -205
  208. package/src/server/serverKnowledgeStore.ts +67 -67
  209. package/src/server/toolRegistry.ts +508 -474
  210. package/src/tools/CLAUDE.md +604 -0
  211. package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -111
  212. package/src/tools/__tests__/accountTools.integration.test.ts +129 -111
  213. package/src/tools/__tests__/accountTools.test.ts +685 -638
  214. package/src/tools/__tests__/adapters.test.ts +142 -108
  215. package/src/tools/__tests__/budgetTools.delta.integration.test.ts +73 -73
  216. package/src/tools/__tests__/budgetTools.integration.test.ts +132 -124
  217. package/src/tools/__tests__/budgetTools.test.ts +442 -413
  218. package/src/tools/__tests__/categoryTools.delta.integration.test.ts +76 -68
  219. package/src/tools/__tests__/categoryTools.integration.test.ts +314 -288
  220. package/src/tools/__tests__/categoryTools.test.ts +656 -625
  221. package/src/tools/__tests__/compareTransactions/formatter.test.ts +535 -462
  222. package/src/tools/__tests__/compareTransactions/index.test.ts +378 -358
  223. package/src/tools/__tests__/compareTransactions/matcher.test.ts +497 -398
  224. package/src/tools/__tests__/compareTransactions/parser.test.ts +765 -747
  225. package/src/tools/__tests__/compareTransactions.test.ts +352 -332
  226. package/src/tools/__tests__/compareTransactions.window.test.ts +150 -146
  227. package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +69 -65
  228. package/src/tools/__tests__/deltaFetcher.test.ts +325 -265
  229. package/src/tools/__tests__/deltaSupport.test.ts +211 -184
  230. package/src/tools/__tests__/deltaTestUtils.ts +37 -33
  231. package/src/tools/__tests__/exportTransactions.test.ts +205 -200
  232. package/src/tools/__tests__/monthTools.delta.integration.test.ts +68 -68
  233. package/src/tools/__tests__/monthTools.integration.test.ts +178 -166
  234. package/src/tools/__tests__/monthTools.test.ts +561 -512
  235. package/src/tools/__tests__/payeeTools.delta.integration.test.ts +68 -68
  236. package/src/tools/__tests__/payeeTools.integration.test.ts +158 -142
  237. package/src/tools/__tests__/payeeTools.test.ts +486 -434
  238. package/src/tools/__tests__/transactionSchemas.test.ts +1204 -0
  239. package/src/tools/__tests__/transactionTools.integration.test.ts +875 -825
  240. package/src/tools/__tests__/transactionTools.test.ts +4923 -4366
  241. package/src/tools/__tests__/transactionUtils.test.ts +1016 -0
  242. package/src/tools/__tests__/utilityTools.integration.test.ts +32 -32
  243. package/src/tools/__tests__/utilityTools.test.ts +68 -58
  244. package/src/tools/accountTools.ts +293 -271
  245. package/src/tools/adapters.ts +120 -63
  246. package/src/tools/budgetTools.ts +121 -116
  247. package/src/tools/categoryTools.ts +379 -339
  248. package/src/tools/compareTransactions/formatter.ts +131 -119
  249. package/src/tools/compareTransactions/index.ts +249 -214
  250. package/src/tools/compareTransactions/matcher.ts +259 -209
  251. package/src/tools/compareTransactions/parser.ts +517 -487
  252. package/src/tools/compareTransactions/types.ts +38 -38
  253. package/src/tools/compareTransactions.ts +1 -1
  254. package/src/tools/deltaFetcher.ts +281 -260
  255. package/src/tools/deltaSupport.ts +264 -259
  256. package/src/tools/exportTransactions.ts +230 -218
  257. package/src/tools/monthTools.ts +180 -165
  258. package/src/tools/payeeTools.ts +152 -140
  259. package/src/tools/reconcileAdapter.ts +297 -246
  260. package/src/tools/reconciliation/CLAUDE.md +506 -0
  261. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +135 -112
  262. package/src/tools/reconciliation/__tests__/adapter.test.ts +249 -227
  263. package/src/tools/reconciliation/__tests__/analyzer.test.ts +408 -335
  264. package/src/tools/reconciliation/__tests__/csvParser.test.ts +71 -69
  265. package/src/tools/reconciliation/__tests__/executor.integration.test.ts +348 -323
  266. package/src/tools/reconciliation/__tests__/executor.progress.test.ts +503 -457
  267. package/src/tools/reconciliation/__tests__/executor.test.ts +898 -831
  268. package/src/tools/reconciliation/__tests__/matcher.test.ts +667 -663
  269. package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +296 -276
  270. package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +692 -624
  271. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1008 -986
  272. package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +187 -146
  273. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +583 -530
  274. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +75 -71
  275. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +70 -58
  276. package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +102 -88
  277. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +58 -43
  278. package/src/tools/reconciliation/__tests__/signDetector.test.ts +209 -206
  279. package/src/tools/reconciliation/__tests__/ynabAdapter.test.ts +66 -60
  280. package/src/tools/reconciliation/analyzer.ts +582 -406
  281. package/src/tools/reconciliation/csvParser.ts +656 -609
  282. package/src/tools/reconciliation/executor.ts +1290 -1128
  283. package/src/tools/reconciliation/index.ts +580 -528
  284. package/src/tools/reconciliation/matcher.ts +256 -240
  285. package/src/tools/reconciliation/payeeNormalizer.ts +92 -78
  286. package/src/tools/reconciliation/recommendationEngine.ts +357 -345
  287. package/src/tools/reconciliation/reportFormatter.ts +349 -276
  288. package/src/tools/reconciliation/signDetector.ts +89 -83
  289. package/src/tools/reconciliation/types.ts +164 -153
  290. package/src/tools/reconciliation/ynabAdapter.ts +17 -15
  291. package/src/tools/schemas/CLAUDE.md +546 -0
  292. package/src/tools/schemas/common.ts +1 -1
  293. package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +410 -409
  294. package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +305 -299
  295. package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +431 -430
  296. package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +510 -495
  297. package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +179 -153
  298. package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +293 -254
  299. package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +457 -457
  300. package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +362 -356
  301. package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +402 -399
  302. package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +225 -211
  303. package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +457 -454
  304. package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +316 -315
  305. package/src/tools/schemas/outputs/accountOutputs.ts +40 -34
  306. package/src/tools/schemas/outputs/budgetOutputs.ts +24 -19
  307. package/src/tools/schemas/outputs/categoryOutputs.ts +76 -56
  308. package/src/tools/schemas/outputs/comparisonOutputs.ts +192 -169
  309. package/src/tools/schemas/outputs/index.ts +163 -163
  310. package/src/tools/schemas/outputs/monthOutputs.ts +95 -80
  311. package/src/tools/schemas/outputs/payeeOutputs.ts +18 -18
  312. package/src/tools/schemas/outputs/reconciliationOutputs.ts +386 -373
  313. package/src/tools/schemas/outputs/transactionMutationOutputs.ts +259 -231
  314. package/src/tools/schemas/outputs/transactionOutputs.ts +81 -71
  315. package/src/tools/schemas/outputs/utilityOutputs.ts +90 -84
  316. package/src/tools/schemas/shared/commonOutputs.ts +27 -19
  317. package/src/tools/toolCategories.ts +114 -114
  318. package/src/tools/transactionReadTools.ts +327 -0
  319. package/src/tools/transactionSchemas.ts +484 -0
  320. package/src/tools/transactionTools.ts +107 -2990
  321. package/src/tools/transactionUtils.ts +621 -0
  322. package/src/tools/transactionWriteTools.ts +2110 -0
  323. package/src/tools/utilityTools.ts +46 -41
  324. package/src/types/CLAUDE.md +477 -0
  325. package/src/types/__tests__/index.test.ts +51 -51
  326. package/src/types/index.ts +43 -39
  327. package/src/types/integration-tests.d.ts +26 -26
  328. package/src/types/reconciliation.ts +29 -29
  329. package/src/types/toolAnnotations.ts +30 -30
  330. package/src/types/toolRegistration.ts +43 -32
  331. package/src/utils/CLAUDE.md +508 -0
  332. package/src/utils/__tests__/dateUtils.test.ts +174 -168
  333. package/src/utils/__tests__/money.test.ts +193 -187
  334. package/src/utils/amountUtils.ts +5 -5
  335. package/src/utils/baseError.ts +5 -5
  336. package/src/utils/dateUtils.ts +29 -26
  337. package/src/utils/errors.ts +14 -14
  338. package/src/utils/money.ts +66 -52
  339. package/src/utils/validationError.ts +1 -1
  340. package/tsconfig.json +29 -29
  341. package/tsconfig.prod.json +16 -16
  342. package/vitest-reporters/split-json-reporter.ts +247 -204
  343. package/vitest.config.ts +99 -95
  344. package/.prettierignore +0 -10
  345. package/.prettierrc.json +0 -10
  346. package/eslint.config.js +0 -49
@@ -1,2995 +1,112 @@
1
- import { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
- import * as ynab from 'ynab';
3
- import { SaveTransaction } from 'ynab/dist/models/SaveTransaction.js';
4
- import { SaveSubTransaction } from 'ynab/dist/models/SaveSubTransaction.js';
5
- import type { SaveTransactionsResponseData } from 'ynab/dist/models/SaveTransactionsResponseData.js';
6
- import { z } from 'zod/v4';
7
- import { createHash } from 'crypto';
8
- import { ValidationError, withToolErrorHandling } from '../types/index.js';
9
- import type { ToolFactory } from '../types/toolRegistration.js';
10
- import { createAdapters, createBudgetResolver } from './adapters.js';
11
- import { ToolAnnotationPresets } from './toolCategories.js';
12
- import { responseFormatter } from '../server/responseFormatter.js';
13
- import { amountToMilliunits, milliunitsToAmount } from '../utils/amountUtils.js';
14
- import { cacheManager, CACHE_TTLS, CacheManager } from '../server/cacheManager.js';
15
- import { globalRequestLogger } from '../server/requestLogger.js';
16
- import type { DeltaFetcher } from './deltaFetcher.js';
17
- import type { DeltaCache } from '../server/deltaCache.js';
18
- import type { ServerKnowledgeStore } from '../server/serverKnowledgeStore.js';
19
- import { resolveDeltaFetcherArgs, resolveDeltaWriteArgs } from './deltaSupport.js';
20
- import { handleExportTransactions, ExportTransactionsSchema } from './exportTransactions.js';
21
-
22
- /**
23
- * Utility function to ensure transaction is not null/undefined
24
- */
25
- function ensureTransaction<T>(transaction: T | undefined, errorMessage: string): T {
26
- if (!transaction) {
27
- throw new Error(errorMessage);
28
- }
29
- return transaction;
30
- }
31
-
32
- const toMonthKey = (date: string): string => `${date.slice(0, 7)}-01`;
33
-
34
- interface CategorySource {
35
- category_id?: string | null;
36
- subtransactions?: { category_id?: string | null }[] | null | undefined;
37
- }
38
-
39
- function appendCategoryIds(source: CategorySource | undefined, target: Set<string>): void {
40
- if (!source) {
41
- return;
42
- }
43
- if (source.category_id) {
44
- target.add(source.category_id);
45
- }
46
- if (Array.isArray(source.subtransactions)) {
47
- for (const sub of source.subtransactions) {
48
- if (sub?.category_id) {
49
- target.add(sub.category_id);
50
- }
51
- }
52
- }
53
- }
54
-
55
- function collectCategoryIdsFromSources(...sources: (CategorySource | undefined)[]): Set<string> {
56
- const result = new Set<string>();
57
- for (const source of sources) {
58
- appendCategoryIds(source, result);
59
- }
60
- return result;
61
- }
62
-
63
- function setsEqual<T>(a: Set<T>, b: Set<T>): boolean {
64
- if (a.size !== b.size) {
65
- return false;
66
- }
67
- for (const value of a) {
68
- if (!b.has(value)) {
69
- return false;
70
- }
71
- }
72
- return true;
73
- }
74
-
75
- interface TransactionCacheInvalidationOptions {
76
- affectedCategoryIds?: Set<string>;
77
- invalidateAllCategories?: boolean;
78
- accountTotalsChanged?: boolean;
79
- invalidateMonths?: boolean;
80
- }
81
-
82
- function invalidateTransactionCaches(
83
- deltaCache: DeltaCache,
84
- knowledgeStore: ServerKnowledgeStore,
85
- budgetId: string,
86
- serverKnowledge: number | undefined,
87
- affectedAccountIds: Set<string>,
88
- affectedMonths: Set<string>,
89
- options: TransactionCacheInvalidationOptions = {},
90
- ): void {
91
- deltaCache.invalidate(budgetId, 'transactions');
92
- cacheManager.delete(CacheManager.generateKey('transactions', 'list', budgetId));
93
-
94
- for (const accountId of affectedAccountIds) {
95
- const accountPrefix = CacheManager.generateKey('transactions', 'account', budgetId, accountId);
96
- cacheManager.deleteByPrefix(accountPrefix);
97
- }
98
-
99
- const invalidateAccountsList = options.accountTotalsChanged ?? true;
100
- if (invalidateAccountsList) {
101
- cacheManager.delete(CacheManager.generateKey('accounts', 'list', budgetId));
102
- }
103
- for (const accountId of affectedAccountIds) {
104
- cacheManager.delete(CacheManager.generateKey('account', 'get', budgetId, accountId));
105
- }
106
-
107
- const affectedCategoryIds = options.affectedCategoryIds ?? new Set<string>();
108
- const shouldInvalidateCategories =
109
- options.invalidateAllCategories || affectedCategoryIds.size > 0;
110
- if (shouldInvalidateCategories) {
111
- cacheManager.delete(CacheManager.generateKey('categories', 'list', budgetId));
112
- for (const categoryId of affectedCategoryIds) {
113
- cacheManager.delete(CacheManager.generateKey('category', 'get', budgetId, categoryId));
114
- }
115
- }
116
-
117
- const shouldInvalidateMonths = options.invalidateMonths ?? affectedMonths.size > 0;
118
- if (shouldInvalidateMonths) {
119
- cacheManager.delete(CacheManager.generateKey('months', 'list', budgetId));
120
- deltaCache.invalidate(budgetId, 'months');
121
- for (const month of affectedMonths) {
122
- cacheManager.delete(CacheManager.generateKey('month', 'get', budgetId, month));
123
- }
124
- }
125
-
126
- if (serverKnowledge !== undefined) {
127
- const transactionCacheKey = CacheManager.generateKey('transactions', 'list', budgetId);
128
- knowledgeStore.update(transactionCacheKey, serverKnowledge);
129
- if (invalidateAccountsList) {
130
- const accountsCacheKey = CacheManager.generateKey('accounts', 'list', budgetId);
131
- knowledgeStore.update(accountsCacheKey, serverKnowledge);
132
- }
133
- if (shouldInvalidateMonths && affectedMonths.size > 0) {
134
- const monthsCacheKey = CacheManager.generateKey('months', 'list', budgetId);
135
- knowledgeStore.update(monthsCacheKey, serverKnowledge);
136
- }
137
- }
138
- }
139
-
140
- /**
141
- * Schema for ynab:list_transactions tool parameters
142
- */
143
- export const ListTransactionsSchema = z
144
- .object({
145
- budget_id: z.string().min(1, 'Budget ID is required'),
146
- account_id: z.string().optional(),
147
- category_id: z.string().optional(),
148
- since_date: z
149
- .string()
150
- .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
151
- .optional(),
152
- type: z.enum(['uncategorized', 'unapproved']).optional(),
153
- })
154
- .strict();
155
-
156
- export type ListTransactionsParams = z.infer<typeof ListTransactionsSchema>;
157
-
158
- /**
159
- * Schema for ynab:get_transaction tool parameters
160
- */
161
- export const GetTransactionSchema = z
162
- .object({
163
- budget_id: z.string().min(1, 'Budget ID is required'),
164
- transaction_id: z.string().min(1, 'Transaction ID is required'),
165
- })
166
- .strict();
167
-
168
- export type GetTransactionParams = z.infer<typeof GetTransactionSchema>;
169
-
170
- /**
171
- * Schema for ynab:create_transaction tool parameters
172
- */
173
- export const CreateTransactionSchema = z
174
- .object({
175
- budget_id: z.string().min(1, 'Budget ID is required'),
176
- account_id: z.string().min(1, 'Account ID is required'),
177
- amount: z.number().int('Amount must be an integer in milliunits'),
178
- date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)'),
179
- payee_name: z.string().optional(),
180
- payee_id: z.string().optional(),
181
- category_id: z.string().optional(),
182
- memo: z.string().optional(),
183
- cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
184
- approved: z.boolean().optional(),
185
- flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
186
- import_id: z.string().min(1, 'Import ID cannot be empty').optional(),
187
- dry_run: z.boolean().optional(),
188
- subtransactions: z
189
- .array(
190
- z
191
- .object({
192
- amount: z.number().int('Subtransaction amount must be an integer in milliunits'),
193
- payee_name: z.string().optional(),
194
- payee_id: z.string().optional(),
195
- category_id: z.string().optional(),
196
- memo: z.string().optional(),
197
- })
198
- .strict(),
199
- )
200
- .min(1, 'At least one subtransaction is required when provided')
201
- .optional(),
202
- })
203
- .strict()
204
- .superRefine((data, ctx) => {
205
- if (data.subtransactions && data.subtransactions.length > 0) {
206
- const total = data.subtransactions.reduce((sum, sub) => sum + sub.amount, 0);
207
- if (total !== data.amount) {
208
- ctx.addIssue({
209
- code: z.ZodIssueCode.custom,
210
- message: 'Amount must equal the sum of subtransaction amounts',
211
- path: ['amount'],
212
- });
213
- }
214
- }
215
- });
216
-
217
- export type CreateTransactionParams = z.infer<typeof CreateTransactionSchema>;
218
-
219
- const BulkTransactionInputSchemaBase = CreateTransactionSchema.pick({
220
- account_id: true,
221
- amount: true,
222
- date: true,
223
- payee_name: true,
224
- payee_id: true,
225
- category_id: true,
226
- memo: true,
227
- cleared: true,
228
- approved: true,
229
- flag_color: true,
230
- import_id: true,
231
- });
232
-
233
- type BulkTransactionInput = Omit<
234
- CreateTransactionParams,
235
- 'budget_id' | 'dry_run' | 'subtransactions'
236
- >;
237
-
238
- // Schema for bulk transaction creation - subtransactions are not supported
239
- // The .strict() modifier automatically rejects any fields not in the schema
240
- const BulkTransactionInputSchema = BulkTransactionInputSchemaBase.strict();
241
-
242
- export const CreateTransactionsSchema = z
243
- .object({
244
- budget_id: z.string().min(1, 'Budget ID is required'),
245
- transactions: z
246
- .array(BulkTransactionInputSchema)
247
- .min(1, 'At least one transaction is required')
248
- .max(100, 'A maximum of 100 transactions may be created at once'),
249
- dry_run: z.boolean().optional(),
250
- })
251
- .strict();
252
-
253
- export type CreateTransactionsParams = z.infer<typeof CreateTransactionsSchema>;
254
-
255
- export interface BulkTransactionResult {
256
- request_index: number;
257
- status: 'created' | 'duplicate' | 'failed';
258
- transaction_id?: string | undefined;
259
- correlation_key: string;
260
- error_code?: string | undefined;
261
- error?: string | undefined;
262
- }
263
-
264
- export interface BulkCreateResponse {
265
- success: boolean;
266
- server_knowledge?: number;
267
- summary: {
268
- total_requested: number;
269
- created: number;
270
- duplicates: number;
271
- failed: number;
272
- };
273
- results: BulkTransactionResult[];
274
- transactions?: ynab.TransactionDetail[];
275
- duplicate_import_ids?: string[];
276
- message?: string;
277
- mode?: 'full' | 'summary' | 'ids_only';
278
- }
279
-
280
- const FULL_RESPONSE_THRESHOLD = 64 * 1024;
281
- const SUMMARY_RESPONSE_THRESHOLD = 96 * 1024;
282
- const MAX_RESPONSE_BYTES = 100 * 1024;
283
-
284
- export function generateCorrelationKey(transaction: {
285
- account_id?: string;
286
- date?: string;
287
- amount?: number;
288
- payee_id?: string | null;
289
- payee_name?: string | null;
290
- category_id?: string | null;
291
- memo?: string | null;
292
- cleared?: ynab.TransactionClearedStatus;
293
- approved?: boolean;
294
- flag_color?: ynab.TransactionFlagColor | null;
295
- import_id?: string | null;
296
- }): string {
297
- if (transaction.import_id) {
298
- return transaction.import_id;
299
- }
300
-
301
- const segments = [
302
- `account:${transaction.account_id ?? ''}`,
303
- `date:${transaction.date ?? ''}`,
304
- `amount:${transaction.amount ?? 0}`,
305
- `payee:${transaction.payee_id ?? transaction.payee_name ?? ''}`,
306
- `category:${transaction.category_id ?? ''}`,
307
- `memo:${transaction.memo ?? ''}`,
308
- `cleared:${transaction.cleared ?? ''}`,
309
- `approved:${transaction.approved ?? false}`,
310
- `flag:${transaction.flag_color ?? ''}`,
311
- ];
312
-
313
- const normalized = segments.join('|');
314
- const hash = createHash('sha256').update(normalized).digest('hex').slice(0, 16);
315
- return `hash:${hash}`;
316
- }
317
-
318
- type CorrelationPayload = Parameters<typeof generateCorrelationKey>[0];
319
-
320
- interface CorrelationPayloadInput {
321
- account_id?: string | undefined;
322
- date?: string | undefined;
323
- amount?: number | undefined;
324
- payee_id?: string | null | undefined;
325
- payee_name?: string | null | undefined;
326
- category_id?: string | null | undefined;
327
- memo?: string | null | undefined;
328
- cleared?: ynab.TransactionClearedStatus | undefined;
329
- approved?: boolean | undefined;
330
- flag_color?: ynab.TransactionFlagColor | null | undefined;
331
- import_id?: string | null | undefined;
332
- }
333
-
334
- export function toCorrelationPayload(transaction: CorrelationPayloadInput): CorrelationPayload {
335
- const payload: CorrelationPayload = {};
336
- if (transaction.account_id !== undefined) {
337
- payload.account_id = transaction.account_id;
338
- }
339
- if (transaction.date !== undefined) {
340
- payload.date = transaction.date;
341
- }
342
- if (transaction.amount !== undefined) {
343
- payload.amount = transaction.amount;
344
- }
345
- if (transaction.cleared !== undefined) {
346
- payload.cleared = transaction.cleared;
347
- }
348
- if (transaction.approved !== undefined) {
349
- payload.approved = transaction.approved;
350
- }
351
- if (transaction.flag_color !== undefined) {
352
- payload.flag_color = transaction.flag_color;
353
- }
354
- payload.payee_id = transaction.payee_id ?? null;
355
- payload.payee_name = transaction.payee_name ?? null;
356
- payload.category_id = transaction.category_id ?? null;
357
- payload.memo = transaction.memo ?? null;
358
- payload.import_id = transaction.import_id ?? null;
359
- return payload;
360
- }
361
-
362
- export function correlateResults(
363
- requests: BulkTransactionInput[],
364
- responseData: SaveTransactionsResponseData,
365
- duplicateImportIds: Set<string>,
366
- ): BulkTransactionResult[] {
367
- const createdByImportId = new Map<string, string[]>();
368
- const createdByHash = new Map<string, string[]>();
369
- const responseTransactions = responseData.transactions ?? [];
370
-
371
- const register = (map: Map<string, string[]>, key: string, transactionId: string): void => {
372
- const existing = map.get(key);
373
- if (existing) {
374
- existing.push(transactionId);
375
- return;
376
- }
377
- map.set(key, [transactionId]);
378
- };
379
-
380
- for (const transaction of responseTransactions) {
381
- if (!transaction.id) {
382
- continue;
383
- }
384
- const key = generateCorrelationKey(transaction);
385
- if (key.startsWith('hash:')) {
386
- register(createdByHash, key, transaction.id);
387
- } else {
388
- register(createdByImportId, key, transaction.id);
389
- }
390
- }
391
-
392
- const popId = (map: Map<string, string[]>, key: string): string | undefined => {
393
- const bucket = map.get(key);
394
- if (!bucket || bucket.length === 0) {
395
- return undefined;
396
- }
397
- const [transactionId] = bucket.splice(0, 1);
398
- if (bucket.length === 0) {
399
- map.delete(key);
400
- }
401
- return transactionId;
402
- };
403
-
404
- const correlatedResults: BulkTransactionResult[] = [];
405
-
406
- for (const [index, transaction] of requests.entries()) {
407
- const normalizedRequest = toCorrelationPayload(transaction);
408
- const correlationKey = generateCorrelationKey(normalizedRequest);
409
-
410
- if (transaction.import_id && duplicateImportIds.has(transaction.import_id)) {
411
- correlatedResults.push({
412
- request_index: index,
413
- status: 'duplicate',
414
- correlation_key: correlationKey,
415
- });
416
- continue;
417
- }
418
-
419
- let transactionId: string | undefined;
420
- if (correlationKey.startsWith('hash:')) {
421
- transactionId = popId(createdByHash, correlationKey);
422
- } else {
423
- transactionId = popId(createdByImportId, correlationKey);
424
- }
425
-
426
- if (!transactionId && !correlationKey.startsWith('hash:')) {
427
- // Attempt hash-based fallback if import_id was not matched.
428
- const hashKey = generateCorrelationKey(
429
- toCorrelationPayload({ ...transaction, import_id: undefined }),
430
- );
431
- transactionId = popId(createdByHash, hashKey);
432
- }
433
-
434
- if (transactionId) {
435
- const successResult: BulkTransactionResult = {
436
- request_index: index,
437
- status: 'created',
438
- correlation_key: correlationKey,
439
- };
440
- successResult.transaction_id = transactionId;
441
- correlatedResults.push(successResult);
442
- continue;
443
- }
444
-
445
- globalRequestLogger.logError(
446
- 'ynab:create_transactions',
447
- 'correlate_results',
448
- {
449
- request_index: index,
450
- correlation_key: correlationKey,
451
- request: {
452
- account_id: transaction.account_id,
453
- date: transaction.date,
454
- amount: transaction.amount,
455
- import_id: transaction.import_id,
456
- },
457
- },
458
- 'correlation_failed',
459
- );
460
-
461
- correlatedResults.push({
462
- request_index: index,
463
- status: 'failed',
464
- correlation_key: correlationKey,
465
- error_code: 'correlation_failed',
466
- error: 'Unable to correlate request transaction with YNAB response',
467
- });
468
- }
469
-
470
- return correlatedResults;
471
- }
472
-
473
- function estimatePayloadSize(payload: BulkCreateResponse | BulkUpdateResponse): number {
474
- return Buffer.byteLength(JSON.stringify(payload), 'utf8');
475
- }
476
-
477
- function finalizeResponse(response: BulkCreateResponse): BulkCreateResponse {
478
- const appendMessage = (message: string | undefined, addition: string): string => {
479
- if (!message) {
480
- return addition;
481
- }
482
- if (message.includes(addition)) {
483
- return message;
484
- }
485
- return `${message} ${addition}`;
486
- };
487
-
488
- const fullSize = estimatePayloadSize({ ...response, mode: 'full' });
489
- if (fullSize <= FULL_RESPONSE_THRESHOLD) {
490
- return { ...response, mode: 'full' };
491
- }
492
-
493
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
494
- const { transactions, ...summaryResponse } = response;
495
- const summaryPayload: BulkCreateResponse = {
496
- ...summaryResponse,
497
- message: appendMessage(
498
- response.message,
499
- 'Response downgraded to summary to stay under size limits.',
500
- ),
501
- mode: 'summary',
502
- };
503
-
504
- if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
505
- return summaryPayload;
506
- }
507
-
508
- const idsOnlyPayload: BulkCreateResponse = {
509
- ...summaryPayload,
510
- results: summaryResponse.results.map((result) => ({
511
- request_index: result.request_index,
512
- status: result.status,
513
- transaction_id: result.transaction_id,
514
- correlation_key: result.correlation_key,
515
- error: result.error,
516
- })),
517
- message: appendMessage(
518
- summaryResponse.message,
519
- 'Response downgraded to ids_only to meet 100KB limit.',
520
- ),
521
- mode: 'ids_only',
522
- };
523
-
524
- if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
525
- return idsOnlyPayload;
526
- }
527
-
528
- throw new ValidationError(
529
- 'RESPONSE_TOO_LARGE: Unable to format bulk create response within 100KB limit',
530
- `Batch size: ${response.summary.total_requested} transactions`,
531
- ['Reduce the batch size and retry', 'Consider splitting into multiple smaller batches'],
532
- );
533
- }
534
-
535
- const ReceiptSplitItemSchema = z
536
- .object({
537
- name: z.string().min(1, 'Item name is required'),
538
- amount: z.number().finite('Item amount must be a finite number'),
539
- quantity: z
540
- .number()
541
- .finite('Quantity must be a finite number')
542
- .positive('Quantity must be greater than zero')
543
- .optional(),
544
- memo: z.string().optional(),
545
- })
546
- .strict();
547
-
548
- const ReceiptSplitCategorySchema = z
549
- .object({
550
- category_id: z.string().min(1, 'Category ID is required'),
551
- category_name: z.string().optional(),
552
- items: z.array(ReceiptSplitItemSchema).min(1, 'Each category must include at least one item'),
553
- })
554
- .strict();
555
-
556
- export const CreateReceiptSplitTransactionSchema = z
557
- .object({
558
- budget_id: z.string().min(1, 'Budget ID is required'),
559
- account_id: z.string().min(1, 'Account ID is required'),
560
- payee_name: z.string().min(1, 'Payee name is required'),
561
- date: z
562
- .string()
563
- .regex(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
564
- .optional(),
565
- memo: z.string().optional(),
566
- receipt_subtotal: z
567
- .number()
568
- .finite('Receipt subtotal must be a finite number')
569
- .refine((value) => value >= 0, 'Receipt subtotal must be zero or greater')
570
- .optional(),
571
- receipt_tax: z.number().finite('Receipt tax must be a finite number'),
572
- receipt_total: z
573
- .number()
574
- .finite('Receipt total must be a finite number')
575
- .refine((value) => value > 0, 'Receipt total must be greater than zero'),
576
- categories: z
577
- .array(ReceiptSplitCategorySchema)
578
- .min(1, 'At least one categorized group is required to create a split transaction'),
579
- cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
580
- approved: z.boolean().optional(),
581
- flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
582
- dry_run: z.boolean().optional(),
583
- })
584
- .strict()
585
- .superRefine((data, ctx) => {
586
- const itemsSubtotal = data.categories
587
- .flatMap((category) => category.items)
588
- .reduce((sum, item) => sum + item.amount, 0);
589
-
590
- if (data.receipt_subtotal !== undefined) {
591
- const delta = Math.abs(data.receipt_subtotal - itemsSubtotal);
592
- if (delta > 0.01) {
593
- ctx.addIssue({
594
- code: z.ZodIssueCode.custom,
595
- message: `Receipt subtotal (${data.receipt_subtotal.toFixed(2)}) does not match categorized items total (${itemsSubtotal.toFixed(2)})`,
596
- path: ['receipt_subtotal'],
597
- });
598
- }
599
- }
600
-
601
- const expectedTotal = itemsSubtotal + data.receipt_tax;
602
- const deltaTotal = Math.abs(expectedTotal - data.receipt_total);
603
- if (deltaTotal > 0.01) {
604
- ctx.addIssue({
605
- code: z.ZodIssueCode.custom,
606
- message: `Receipt total (${data.receipt_total.toFixed(2)}) does not match subtotal plus tax (${expectedTotal.toFixed(2)})`,
607
- path: ['receipt_total'],
608
- });
609
- }
610
- });
611
-
612
- export type CreateReceiptSplitTransactionParams = z.infer<
613
- typeof CreateReceiptSplitTransactionSchema
614
- >;
615
-
616
- /**
617
- * Schema for ynab:update_transaction tool parameters
618
- */
619
- export const UpdateTransactionSchema = z
620
- .object({
621
- budget_id: z.string().min(1, 'Budget ID is required'),
622
- transaction_id: z.string().min(1, 'Transaction ID is required'),
623
- account_id: z.string().optional(),
624
- amount: z.number().int('Amount must be an integer in milliunits').optional(),
625
- date: z
626
- .string()
627
- .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
628
- .optional(),
629
- payee_name: z.string().optional(),
630
- payee_id: z.string().optional(),
631
- category_id: z.string().optional(),
632
- memo: z.string().optional(),
633
- cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
634
- approved: z.boolean().optional(),
635
- flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
636
- dry_run: z.boolean().optional(),
637
- })
638
- .strict();
639
-
640
- export type UpdateTransactionParams = z.infer<typeof UpdateTransactionSchema>;
641
-
642
- /**
643
- * Schema for bulk transaction updates - each item in the array
644
- * Note: account_id is intentionally excluded as account moves are not supported in bulk updates
645
- */
646
- const BulkUpdateTransactionInputSchema = z
647
- .object({
648
- id: z.string().min(1, 'Transaction ID is required'),
649
- amount: z.number().int('Amount must be an integer in milliunits').optional(),
650
- date: z
651
- .string()
652
- .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
653
- .optional(),
654
- payee_name: z.string().optional(),
655
- payee_id: z.string().optional(),
656
- category_id: z.string().optional(),
657
- memo: z.string().optional(),
658
- cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
659
- approved: z.boolean().optional(),
660
- flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
661
- // Metadata fields for cache invalidation
662
- original_account_id: z.string().optional(),
663
- original_date: z
664
- .string()
665
- .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
666
- .optional(),
667
- })
668
- .strict();
669
-
670
- export type BulkUpdateTransactionInput = z.infer<typeof BulkUpdateTransactionInputSchema>;
671
-
672
1
  /**
673
- * Schema for ynab:update_transactions tool parameters
674
- */
675
- export const UpdateTransactionsSchema = z
676
- .object({
677
- budget_id: z.string().min(1, 'Budget ID is required'),
678
- transactions: z
679
- .array(BulkUpdateTransactionInputSchema)
680
- .min(1, 'At least one transaction is required')
681
- .max(100, 'A maximum of 100 transactions may be updated at once'),
682
- dry_run: z.boolean().optional(),
683
- })
684
- .strict();
685
-
686
- export type UpdateTransactionsParams = z.infer<typeof UpdateTransactionsSchema>;
687
-
688
- export interface BulkUpdateResult {
689
- request_index: number;
690
- status: 'updated' | 'failed';
691
- transaction_id: string;
692
- correlation_key: string;
693
- error_code?: string;
694
- error?: string;
695
- }
696
-
697
- export interface BulkUpdateResponse {
698
- success: boolean;
699
- server_knowledge?: number;
700
- summary: {
701
- total_requested: number;
702
- updated: number;
703
- failed: number;
704
- };
705
- results: BulkUpdateResult[];
706
- transactions?: ynab.TransactionDetail[];
707
- message?: string;
708
- mode?: 'full' | 'summary' | 'ids_only';
709
- }
710
-
711
- /**
712
- * Schema for ynab:delete_transaction tool parameters
713
- */
714
- export const DeleteTransactionSchema = z
715
- .object({
716
- budget_id: z.string().min(1, 'Budget ID is required'),
717
- transaction_id: z.string().min(1, 'Transaction ID is required'),
718
- dry_run: z.boolean().optional(),
719
- })
720
- .strict();
721
-
722
- export type DeleteTransactionParams = z.infer<typeof DeleteTransactionSchema>;
723
-
724
- /**
725
- * Handles the ynab:list_transactions tool call
726
- * Lists transactions for a budget with optional filtering
727
- */
728
-
729
- export async function handleListTransactions(
730
- ynabAPI: ynab.API,
731
- deltaFetcher: DeltaFetcher,
732
- params: ListTransactionsParams,
733
- ): Promise<CallToolResult>;
734
- export async function handleListTransactions(
735
- ynabAPI: ynab.API,
736
- params: ListTransactionsParams,
737
- ): Promise<CallToolResult>;
738
- export async function handleListTransactions(
739
- ynabAPI: ynab.API,
740
- deltaFetcherOrParams: DeltaFetcher | ListTransactionsParams,
741
- maybeParams?: ListTransactionsParams,
742
- ): Promise<CallToolResult> {
743
- const { deltaFetcher, params } = resolveDeltaFetcherArgs(
744
- ynabAPI,
745
- deltaFetcherOrParams,
746
- maybeParams,
747
- );
748
- return await withToolErrorHandling(
749
- async () => {
750
- // Always use cache
751
- let transactions: (ynab.TransactionDetail | ynab.HybridTransaction)[];
752
- let cacheHit = false;
753
- let usedDelta = false;
754
-
755
- if (params.account_id) {
756
- // Validate that the account exists before fetching transactions
757
- // YNAB API returns empty array for invalid account IDs instead of an error
758
- const accountsResult = await deltaFetcher.fetchAccounts(params.budget_id);
759
- const accountExists = accountsResult.data.some(
760
- (account) => account.id === params.account_id,
761
- );
762
- if (!accountExists) {
763
- throw new Error(`Account ${params.account_id} not found in budget ${params.budget_id}`);
764
- }
765
-
766
- const result = await deltaFetcher.fetchTransactionsByAccount(
767
- params.budget_id,
768
- params.account_id,
769
- params.since_date,
770
- );
771
- transactions = result.data;
772
- cacheHit = result.wasCached;
773
- usedDelta = result.usedDelta;
774
- } else if (params.category_id) {
775
- const response = await ynabAPI.transactions.getTransactionsByCategory(
776
- params.budget_id,
777
- params.category_id,
778
- params.since_date,
779
- );
780
- transactions = response.data.transactions;
781
- } else {
782
- const result = await deltaFetcher.fetchTransactions(
783
- params.budget_id,
784
- params.since_date,
785
- params.type as ynab.GetTransactionsTypeEnum | undefined,
786
- );
787
- transactions = result.data;
788
- cacheHit = result.wasCached;
789
- usedDelta = result.usedDelta;
790
- }
791
-
792
- // Check if response might be too large for MCP
793
- const estimatedSize = JSON.stringify(transactions).length;
794
- const sizeLimit = 90000; // Conservative limit under 100KB
795
-
796
- if (estimatedSize > sizeLimit) {
797
- // Return summary and suggest export
798
- const preview = transactions.slice(0, 50);
799
- return {
800
- content: [
801
- {
802
- type: 'text',
803
- text: responseFormatter.format({
804
- message: `Found ${transactions.length} transactions (${Math.round(estimatedSize / 1024)}KB). Too large to display all.`,
805
- suggestion: "Use 'export_transactions' tool to save all transactions to a file.",
806
- showing: `First ${preview.length} transactions:`,
807
- total_count: transactions.length,
808
- estimated_size_kb: Math.round(estimatedSize / 1024),
809
- cached: cacheHit,
810
- cache_info: cacheHit
811
- ? `Data retrieved from cache for improved performance${usedDelta ? ' (delta merge applied)' : ''}`
812
- : 'Fresh data retrieved from YNAB API',
813
- preview_transactions: preview.map((transaction) => ({
814
- id: transaction.id,
815
- date: transaction.date,
816
- amount: milliunitsToAmount(transaction.amount),
817
- memo: transaction.memo,
818
- payee_name: transaction.payee_name,
819
- category_name: transaction.category_name,
820
- })),
821
- }),
822
- },
823
- ],
824
- };
825
- }
826
-
827
- return {
828
- content: [
829
- {
830
- type: 'text',
831
- text: responseFormatter.format({
832
- total_count: transactions.length,
833
- cached: cacheHit,
834
- cache_info: cacheHit
835
- ? `Data retrieved from cache for improved performance${usedDelta ? ' (delta merge applied)' : ''}`
836
- : 'Fresh data retrieved from YNAB API',
837
- transactions: transactions.map((transaction) => ({
838
- id: transaction.id,
839
- date: transaction.date,
840
- amount: milliunitsToAmount(transaction.amount),
841
- memo: transaction.memo,
842
- cleared: transaction.cleared,
843
- approved: transaction.approved,
844
- flag_color: transaction.flag_color,
845
- account_id: transaction.account_id,
846
- payee_id: transaction.payee_id,
847
- category_id: transaction.category_id,
848
- transfer_account_id: transaction.transfer_account_id,
849
- transfer_transaction_id: transaction.transfer_transaction_id,
850
- matched_transaction_id: transaction.matched_transaction_id,
851
- import_id: transaction.import_id,
852
- deleted: transaction.deleted,
853
- })),
854
- }),
855
- },
856
- ],
857
- };
858
- },
859
- 'ynab:list_transactions',
860
- 'listing transactions',
861
- );
862
- }
863
-
864
- /**
865
- * Handles the ynab:get_transaction tool call
866
- * Gets detailed information for a specific transaction
867
- */
868
- export async function handleGetTransaction(
869
- ynabAPI: ynab.API,
870
- params: GetTransactionParams,
871
- ): Promise<CallToolResult> {
872
- try {
873
- const useCache = process.env['NODE_ENV'] !== 'test';
874
-
875
- let transaction: ynab.TransactionDetail;
876
- let cacheHit = false;
877
-
878
- if (useCache) {
879
- // Use enhanced CacheManager wrap method
880
- const cacheKey = CacheManager.generateKey(
881
- 'transaction',
882
- 'get',
883
- params.budget_id,
884
- params.transaction_id,
885
- );
886
- cacheHit = cacheManager.has(cacheKey);
887
- transaction = await cacheManager.wrap<ynab.TransactionDetail>(cacheKey, {
888
- ttl: CACHE_TTLS.TRANSACTIONS,
889
- loader: async () => {
890
- const response = await ynabAPI.transactions.getTransactionById(
891
- params.budget_id,
892
- params.transaction_id,
893
- );
894
- return ensureTransaction(response.data.transaction, 'Transaction not found');
895
- },
896
- });
897
- } else {
898
- // Bypass cache in test environment
899
- const response = await ynabAPI.transactions.getTransactionById(
900
- params.budget_id,
901
- params.transaction_id,
902
- );
903
- transaction = ensureTransaction(response.data.transaction, 'Transaction not found');
904
- }
905
-
906
- return {
907
- content: [
908
- {
909
- type: 'text',
910
- text: responseFormatter.format({
911
- transaction: {
912
- id: transaction.id,
913
- date: transaction.date,
914
- amount: milliunitsToAmount(transaction.amount),
915
- memo: transaction.memo,
916
- cleared: transaction.cleared,
917
- approved: transaction.approved,
918
- flag_color: transaction.flag_color,
919
- account_id: transaction.account_id,
920
- payee_id: transaction.payee_id,
921
- category_id: transaction.category_id,
922
- transfer_account_id: transaction.transfer_account_id,
923
- transfer_transaction_id: transaction.transfer_transaction_id,
924
- matched_transaction_id: transaction.matched_transaction_id,
925
- import_id: transaction.import_id,
926
- deleted: transaction.deleted,
927
- account_name: transaction.account_name,
928
- payee_name: transaction.payee_name,
929
- category_name: transaction.category_name,
930
- },
931
- cached: cacheHit,
932
- cache_info: cacheHit
933
- ? 'Data retrieved from cache for improved performance'
934
- : 'Fresh data retrieved from YNAB API',
935
- }),
936
- },
937
- ],
938
- };
939
- } catch (error) {
940
- return handleTransactionError(error, 'Failed to get transaction');
941
- }
942
- }
943
-
944
- /**
945
- * Handles the ynab:create_transaction tool call
946
- * Creates a new transaction in the specified budget and account
947
- */
948
- export async function handleCreateTransaction(
949
- ynabAPI: ynab.API,
950
- deltaCache: DeltaCache,
951
- knowledgeStore: ServerKnowledgeStore,
952
- params: CreateTransactionParams,
953
- ): Promise<CallToolResult>;
954
- export async function handleCreateTransaction(
955
- ynabAPI: ynab.API,
956
- params: CreateTransactionParams,
957
- ): Promise<CallToolResult>;
958
- export async function handleCreateTransaction(
959
- ynabAPI: ynab.API,
960
- deltaCacheOrParams: DeltaCache | CreateTransactionParams,
961
- knowledgeStoreOrParams?: ServerKnowledgeStore | CreateTransactionParams,
962
- maybeParams?: CreateTransactionParams,
963
- ): Promise<CallToolResult> {
964
- const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
965
- deltaCacheOrParams,
966
- knowledgeStoreOrParams,
967
- maybeParams,
968
- );
969
- try {
970
- if (params.dry_run) {
971
- return {
972
- content: [
973
- {
974
- type: 'text',
975
- text: responseFormatter.format({
976
- dry_run: true,
977
- action: 'create_transaction',
978
- request: params,
979
- }),
980
- },
981
- ],
982
- };
983
- }
984
- // Prepare transaction data
985
- const transactionData: SaveTransaction = {
986
- account_id: params.account_id,
987
- amount: params.amount, // Already validated as integer milliunits
988
- date: params.date,
989
- cleared: params.cleared as ynab.TransactionClearedStatus,
990
- flag_color: params.flag_color as ynab.TransactionFlagColor,
991
- };
992
- if (params.payee_name !== undefined) transactionData.payee_name = params.payee_name;
993
- if (params.payee_id !== undefined) transactionData.payee_id = params.payee_id;
994
- if (params.category_id !== undefined) transactionData.category_id = params.category_id;
995
- if (params.memo !== undefined) transactionData.memo = params.memo;
996
- if (params.approved !== undefined) transactionData.approved = params.approved;
997
- if (params.import_id !== undefined) transactionData.import_id = params.import_id;
998
- if (params.subtransactions && params.subtransactions.length > 0) {
999
- const subtransactions: SaveSubTransaction[] = params.subtransactions.map((subtransaction) => {
1000
- const mapped: SaveSubTransaction = {
1001
- amount: subtransaction.amount,
1002
- };
1003
-
1004
- if (subtransaction.payee_name !== undefined) mapped.payee_name = subtransaction.payee_name;
1005
- if (subtransaction.payee_id !== undefined) mapped.payee_id = subtransaction.payee_id;
1006
- if (subtransaction.category_id !== undefined) {
1007
- mapped.category_id = subtransaction.category_id;
1008
- }
1009
- if (subtransaction.memo !== undefined) mapped.memo = subtransaction.memo;
1010
-
1011
- return mapped;
1012
- });
1013
-
1014
- transactionData.subtransactions = subtransactions;
1015
- }
1016
-
1017
- const response = await ynabAPI.transactions.createTransaction(params.budget_id, {
1018
- transaction: transactionData,
1019
- });
1020
-
1021
- const transaction = ensureTransaction(response.data.transaction, 'Transaction creation failed');
1022
-
1023
- const affectedAccountIds = new Set<string>([transaction.account_id]);
1024
- const affectedMonths = new Set<string>([toMonthKey(transaction.date)]);
1025
- const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
1026
- invalidateTransactionCaches(
1027
- deltaCache,
1028
- knowledgeStore,
1029
- params.budget_id,
1030
- response.data.server_knowledge,
1031
- affectedAccountIds,
1032
- affectedMonths,
1033
- {
1034
- affectedCategoryIds,
1035
- accountTotalsChanged: true,
1036
- invalidateMonths: true,
1037
- },
1038
- );
1039
-
1040
- // Get the updated account balance
1041
- const accountResponse = await ynabAPI.accounts.getAccountById(
1042
- params.budget_id,
1043
- transaction.account_id,
1044
- );
1045
- const account = accountResponse.data.account;
1046
-
1047
- return {
1048
- content: [
1049
- {
1050
- type: 'text',
1051
- text: responseFormatter.format({
1052
- transaction: {
1053
- id: transaction.id,
1054
- date: transaction.date,
1055
- amount: milliunitsToAmount(transaction.amount),
1056
- memo: transaction.memo,
1057
- cleared: transaction.cleared,
1058
- approved: transaction.approved,
1059
- flag_color: transaction.flag_color,
1060
- account_id: transaction.account_id,
1061
- payee_id: transaction.payee_id,
1062
- category_id: transaction.category_id,
1063
- transfer_account_id: transaction.transfer_account_id,
1064
- transfer_transaction_id: transaction.transfer_transaction_id,
1065
- matched_transaction_id: transaction.matched_transaction_id,
1066
- import_id: transaction.import_id,
1067
- deleted: transaction.deleted,
1068
- // New fields for account balance
1069
- account_balance: account.balance,
1070
- account_cleared_balance: account.cleared_balance,
1071
- subtransactions: transaction.subtransactions?.map((subtransaction) => ({
1072
- id: subtransaction.id,
1073
- transaction_id: subtransaction.transaction_id,
1074
- amount: milliunitsToAmount(subtransaction.amount),
1075
- memo: subtransaction.memo,
1076
- payee_id: subtransaction.payee_id,
1077
- payee_name: subtransaction.payee_name,
1078
- category_id: subtransaction.category_id,
1079
- category_name: subtransaction.category_name,
1080
- transfer_account_id: subtransaction.transfer_account_id,
1081
- transfer_transaction_id: subtransaction.transfer_transaction_id,
1082
- deleted: subtransaction.deleted,
1083
- })),
1084
- },
1085
- }),
1086
- },
1087
- ],
1088
- };
1089
- } catch (error) {
1090
- return handleTransactionError(error, 'Failed to create transaction');
1091
- }
1092
- }
1093
-
1094
- interface ReceiptCategoryCalculation {
1095
- category_id: string;
1096
- category_name: string | undefined;
1097
- subtotal_milliunits: number;
1098
- tax_milliunits: number;
1099
- items: {
1100
- name: string;
1101
- amount_milliunits: number;
1102
- quantity: number | undefined;
1103
- memo: string | undefined;
1104
- }[];
1105
- }
1106
-
1107
- interface SubtransactionInput {
1108
- amount: number;
1109
- payee_name?: string;
1110
- payee_id?: string;
1111
- category_id?: string;
1112
- memo?: string;
1113
- }
1114
-
1115
- /**
1116
- * Constants for smart collapse logic
1117
- */
1118
- const BIG_TICKET_THRESHOLD_MILLIUNITS = 50000; // $50.00
1119
- const COLLAPSE_THRESHOLD = 5; // Collapse if 5 or more remaining items
1120
- const MAX_ITEMS_PER_MEMO = 5;
1121
- const MAX_MEMO_LENGTH = 150;
1122
-
1123
- /**
1124
- * Truncates a string to fit within maxLength, adding ellipsis if truncated
1125
- */
1126
- function truncateToLength(str: string, maxLength: number): string {
1127
- if (str.length <= maxLength) {
1128
- return str;
1129
- }
1130
- const ellipsis = '...';
1131
- return str.substring(0, maxLength - ellipsis.length) + ellipsis;
1132
- }
1133
-
1134
- function buildItemMemo(item: {
1135
- name: string;
1136
- quantity: number | undefined;
1137
- memo: string | undefined;
1138
- }): string | undefined {
1139
- const quantitySuffix = item.quantity ? ` (x${item.quantity})` : '';
1140
- let result: string;
1141
- if (item.memo && item.memo.trim().length > 0) {
1142
- result = `${item.name}${quantitySuffix} - ${item.memo}`;
1143
- } else if (quantitySuffix) {
1144
- result = `${item.name}${quantitySuffix}`;
1145
- } else {
1146
- result = item.name;
1147
- }
1148
- // Truncate to MAX_MEMO_LENGTH if needed
1149
- return truncateToLength(result, MAX_MEMO_LENGTH);
1150
- }
1151
-
1152
- /**
1153
- * Applies smart collapse logic to receipt items according to the specification:
1154
- * 1. Extract special items (big ticket, returns, discounts)
1155
- * 2. Apply threshold to remaining items
1156
- * 3. Collapse by category if needed
1157
- * 4. Handle tax allocation
1158
- */
1159
- function applySmartCollapseLogic(
1160
- categoryCalculations: ReceiptCategoryCalculation[],
1161
- taxMilliunits: number,
1162
- ): SubtransactionInput[] {
1163
- // Step 1: Extract special items and classify remaining items
1164
- interface SpecialItem {
1165
- item: ReceiptCategoryCalculation['items'][0];
1166
- category_id: string;
1167
- category_name: string | undefined;
1168
- }
1169
-
1170
- interface CategoryItems {
1171
- category_id: string;
1172
- category_name: string | undefined;
1173
- items: ReceiptCategoryCalculation['items'][0][];
1174
- }
1175
-
1176
- const specialItems: SpecialItem[] = [];
1177
- const remainingItemsByCategory: CategoryItems[] = [];
1178
-
1179
- for (const category of categoryCalculations) {
1180
- const categorySpecials: ReceiptCategoryCalculation['items'][0][] = [];
1181
- const categoryRemaining: ReceiptCategoryCalculation['items'][0][] = [];
1182
-
1183
- for (const item of category.items) {
1184
- const isNegative = item.amount_milliunits < 0;
1185
- const unitPrice = item.quantity
1186
- ? item.amount_milliunits / item.quantity
1187
- : item.amount_milliunits;
1188
- const isBigTicket = unitPrice > BIG_TICKET_THRESHOLD_MILLIUNITS;
1189
-
1190
- if (isNegative || isBigTicket) {
1191
- categorySpecials.push(item);
1192
- } else {
1193
- categoryRemaining.push(item);
1194
- }
1195
- }
1196
-
1197
- // Add specials to the special items list (preserving category order)
1198
- for (const item of categorySpecials) {
1199
- specialItems.push({
1200
- item,
1201
- category_id: category.category_id,
1202
- category_name: category.category_name,
1203
- });
1204
- }
1205
-
1206
- // Track remaining items by category
1207
- if (categoryRemaining.length > 0) {
1208
- remainingItemsByCategory.push({
1209
- category_id: category.category_id,
1210
- category_name: category.category_name,
1211
- items: categoryRemaining,
1212
- });
1213
- }
1214
- }
1215
-
1216
- // Step 2: Count total remaining positive items
1217
- const totalRemainingItems = remainingItemsByCategory.reduce(
1218
- (sum, cat) => sum + cat.items.length,
1219
- 0,
1220
- );
1221
-
1222
- // Step 3: Decide whether to collapse
1223
- const shouldCollapse = totalRemainingItems >= COLLAPSE_THRESHOLD;
1224
-
1225
- // Build subtransactions
1226
- const subtransactions: SubtransactionInput[] = [];
1227
-
1228
- // Add special items first (returns, discounts, big tickets)
1229
- for (const special of specialItems) {
1230
- const memo = buildItemMemo({
1231
- name: special.item.name,
1232
- quantity: special.item.quantity,
1233
- memo: special.item.memo,
1234
- });
1235
- const payload: SubtransactionInput = {
1236
- amount: -special.item.amount_milliunits,
1237
- category_id: special.category_id,
1238
- };
1239
- if (memo) payload.memo = memo;
1240
- subtransactions.push(payload);
1241
- }
1242
-
1243
- // Add remaining items (collapsed or itemized)
1244
- if (shouldCollapse) {
1245
- // Collapse by category
1246
- for (const categoryGroup of remainingItemsByCategory) {
1247
- const collapsedSubtransactions = collapseItemsByCategory(categoryGroup);
1248
- subtransactions.push(...collapsedSubtransactions);
1249
- }
1250
- } else {
1251
- // Itemize each remaining item individually
1252
- for (const categoryGroup of remainingItemsByCategory) {
1253
- for (const item of categoryGroup.items) {
1254
- const memo = buildItemMemo({
1255
- name: item.name,
1256
- quantity: item.quantity,
1257
- memo: item.memo,
1258
- });
1259
- const payload: SubtransactionInput = {
1260
- amount: -item.amount_milliunits,
1261
- category_id: categoryGroup.category_id,
1262
- };
1263
- if (memo) payload.memo = memo;
1264
- subtransactions.push(payload);
1265
- }
1266
- }
1267
- }
1268
-
1269
- // Step 4: Handle tax allocation
1270
- const taxSubtransactions = allocateTax(categoryCalculations, taxMilliunits);
1271
- subtransactions.push(...taxSubtransactions);
1272
-
1273
- return subtransactions;
1274
- }
1275
-
1276
- /**
1277
- * Collapses items within a category into groups of up to MAX_ITEMS_PER_MEMO
1278
- */
1279
- function collapseItemsByCategory(categoryGroup: {
1280
- category_id: string;
1281
- category_name: string | undefined;
1282
- items: ReceiptCategoryCalculation['items'][0][];
1283
- }): SubtransactionInput[] {
1284
- const subtransactions: SubtransactionInput[] = [];
1285
- const items = categoryGroup.items;
1286
-
1287
- let currentBatch: ReceiptCategoryCalculation['items'][0][] = [];
1288
- let currentBatchTotal = 0;
1289
-
1290
- for (const item of items) {
1291
- // Check if we've hit the max items per memo
1292
- if (currentBatch.length >= MAX_ITEMS_PER_MEMO) {
1293
- // Flush current batch
1294
- const memo = buildCollapsedMemo(currentBatch);
1295
- subtransactions.push({
1296
- amount: -currentBatchTotal,
1297
- category_id: categoryGroup.category_id,
1298
- memo,
1299
- });
1300
- currentBatch = [];
1301
- currentBatchTotal = 0;
1302
- }
1303
-
1304
- // Try adding this item to the current batch
1305
- const testBatch = [...currentBatch, item];
1306
- const testMemo = buildCollapsedMemo(testBatch);
1307
-
1308
- if (testMemo.length <= MAX_MEMO_LENGTH) {
1309
- // Fits - add to batch
1310
- currentBatch.push(item);
1311
- currentBatchTotal += item.amount_milliunits;
1312
- } else {
1313
- // Doesn't fit - flush current batch and start new one
1314
- if (currentBatch.length > 0) {
1315
- const memo = buildCollapsedMemo(currentBatch);
1316
- subtransactions.push({
1317
- amount: -currentBatchTotal,
1318
- category_id: categoryGroup.category_id,
1319
- memo,
1320
- });
1321
- currentBatch = [item];
1322
- currentBatchTotal = item.amount_milliunits;
1323
- } else {
1324
- // Edge case: single item is too long, use it anyway
1325
- currentBatch = [item];
1326
- currentBatchTotal = item.amount_milliunits;
1327
- }
1328
- }
1329
- }
1330
-
1331
- // Flush remaining batch
1332
- if (currentBatch.length > 0) {
1333
- const memo = buildCollapsedMemo(currentBatch);
1334
- subtransactions.push({
1335
- amount: -currentBatchTotal,
1336
- category_id: categoryGroup.category_id,
1337
- memo,
1338
- });
1339
- }
1340
-
1341
- return subtransactions;
1342
- }
1343
-
1344
- /**
1345
- * Truncates an item name to fit within available space
1346
- * Preserves the amount suffix and adds "..." to indicate truncation
1347
- */
1348
- function truncateItemName(name: string, amountSuffix: string, maxLength: number): string {
1349
- const ellipsis = '...';
1350
- // We need: truncatedName + ellipsis + amountSuffix <= maxLength
1351
- const availableForName = maxLength - ellipsis.length - amountSuffix.length;
1352
-
1353
- if (availableForName <= 0) {
1354
- // Edge case: amount suffix alone is too long, just return what we can
1355
- return amountSuffix.substring(0, maxLength);
1356
- }
1357
-
1358
- return name.substring(0, availableForName) + ellipsis + amountSuffix;
1359
- }
1360
-
1361
- /**
1362
- * Builds a collapsed memo from a list of items
1363
- * Format: "Item1 $X.XX, Item2 $Y.YY, Item3 $Z.ZZ"
1364
- * Truncates with "..." if needed (either individual items or the list)
1365
- */
1366
- function buildCollapsedMemo(items: ReceiptCategoryCalculation['items'][0][]): string {
1367
- const parts: string[] = [];
1368
- let currentLength = 0;
1369
-
1370
- for (let i = 0; i < items.length; i++) {
1371
- const item = items[i];
1372
- if (!item) continue;
1373
- const amount = milliunitsToAmount(item.amount_milliunits);
1374
- const amountSuffix = ` $${amount.toFixed(2)}`;
1375
- let itemStr = `${item.name}${amountSuffix}`;
1376
- const separator = i > 0 ? ', ' : '';
1377
-
1378
- // For the first item, check if it alone exceeds the limit
1379
- if (parts.length === 0 && itemStr.length > MAX_MEMO_LENGTH) {
1380
- itemStr = truncateItemName(item.name, amountSuffix, MAX_MEMO_LENGTH);
1381
- }
1382
-
1383
- const testLength = currentLength + separator.length + itemStr.length;
1384
-
1385
- // Check if adding this item would exceed limit
1386
- if (parts.length > 0 && testLength + 4 > MAX_MEMO_LENGTH) {
1387
- // Would exceed - stop here and add "..."
1388
- break;
1389
- }
1390
-
1391
- parts.push(itemStr);
1392
- currentLength = testLength;
1393
- }
1394
-
1395
- let result = parts.join(', ');
1396
-
1397
- // Add "..." if we didn't include all items
1398
- if (parts.length < items.length) {
1399
- result += '...';
1400
- }
1401
-
1402
- return result;
1403
- }
1404
-
1405
- /**
1406
- * Allocates tax across categories
1407
- * - Positive categories get proportional tax subtransactions
1408
- * - Negative tax creates a single tax refund subtransaction
1409
- */
1410
- function allocateTax(
1411
- categoryCalculations: ReceiptCategoryCalculation[],
1412
- taxMilliunits: number,
1413
- ): SubtransactionInput[] {
1414
- const subtransactions: SubtransactionInput[] = [];
1415
-
1416
- // Handle tax = 0
1417
- if (taxMilliunits === 0) {
1418
- return subtransactions;
1419
- }
1420
-
1421
- // Handle negative tax (refund)
1422
- if (taxMilliunits < 0) {
1423
- // Find category with largest return
1424
- let largestReturnCategory: ReceiptCategoryCalculation | undefined = undefined;
1425
- let largestReturnAmount = 0;
1426
-
1427
- for (const category of categoryCalculations) {
1428
- const categoryReturnAmount = category.items
1429
- .filter((item) => item.amount_milliunits < 0)
1430
- .reduce((sum, item) => sum + Math.abs(item.amount_milliunits), 0);
1431
-
1432
- if (categoryReturnAmount > largestReturnAmount) {
1433
- largestReturnAmount = categoryReturnAmount;
1434
- largestReturnCategory = category;
1435
- }
1436
- }
1437
-
1438
- // Default to first category if no returns found
1439
- if (!largestReturnCategory) {
1440
- largestReturnCategory = categoryCalculations[0];
1441
- }
1442
-
1443
- if (largestReturnCategory) {
1444
- subtransactions.push({
1445
- amount: -taxMilliunits,
1446
- category_id: largestReturnCategory.category_id,
1447
- memo: 'Tax refund',
1448
- });
1449
- }
1450
-
1451
- return subtransactions;
1452
- }
1453
-
1454
- // Positive tax - allocate proportionally to positive categories only
1455
- const positiveCategorySubtotals = categoryCalculations
1456
- .map((cat) => ({
1457
- category: cat,
1458
- positiveSubtotal: cat.items
1459
- .filter((item) => item.amount_milliunits > 0)
1460
- .reduce((sum, item) => sum + item.amount_milliunits, 0),
1461
- }))
1462
- .filter((x) => x.positiveSubtotal > 0);
1463
-
1464
- if (positiveCategorySubtotals.length === 0) {
1465
- // No positive items, no tax allocation
1466
- return subtransactions;
1467
- }
1468
-
1469
- const totalPositiveSubtotal = positiveCategorySubtotals.reduce(
1470
- (sum, x) => sum + x.positiveSubtotal,
1471
- 0,
1472
- );
1473
-
1474
- // Distribute tax using largest remainder method
1475
- let allocatedTax = 0;
1476
- const taxAllocations: {
1477
- category: ReceiptCategoryCalculation;
1478
- taxAmount: number;
1479
- }[] = [];
1480
-
1481
- for (let i = 0; i < positiveCategorySubtotals.length; i++) {
1482
- const entry = positiveCategorySubtotals[i];
1483
- if (!entry) continue;
1484
-
1485
- const { category, positiveSubtotal } = entry;
1486
-
1487
- if (i === positiveCategorySubtotals.length - 1) {
1488
- // Last category gets remainder
1489
- const taxAmount = taxMilliunits - allocatedTax;
1490
- if (taxAmount > 0) {
1491
- taxAllocations.push({ category, taxAmount });
1492
- }
1493
- } else {
1494
- const taxAmount = Math.round((taxMilliunits * positiveSubtotal) / totalPositiveSubtotal);
1495
- if (taxAmount > 0) {
1496
- taxAllocations.push({ category, taxAmount });
1497
- allocatedTax += taxAmount;
1498
- }
1499
- }
1500
- }
1501
-
1502
- // Create tax subtransactions
1503
- for (const { category, taxAmount } of taxAllocations) {
1504
- subtransactions.push({
1505
- amount: -taxAmount,
1506
- category_id: category.category_id,
1507
- memo: `Tax - ${category.category_name ?? 'Uncategorized'}`,
1508
- });
1509
- }
1510
-
1511
- return subtransactions;
1512
- }
1513
-
1514
- export async function handleCreateReceiptSplitTransaction(
1515
- ynabAPI: ynab.API,
1516
- deltaCache: DeltaCache,
1517
- knowledgeStore: ServerKnowledgeStore,
1518
- params: CreateReceiptSplitTransactionParams,
1519
- ): Promise<CallToolResult>;
1520
- export async function handleCreateReceiptSplitTransaction(
1521
- ynabAPI: ynab.API,
1522
- params: CreateReceiptSplitTransactionParams,
1523
- ): Promise<CallToolResult>;
1524
- export async function handleCreateReceiptSplitTransaction(
1525
- ynabAPI: ynab.API,
1526
- deltaCacheOrParams: DeltaCache | CreateReceiptSplitTransactionParams,
1527
- knowledgeStoreOrParams?: ServerKnowledgeStore | CreateReceiptSplitTransactionParams,
1528
- maybeParams?: CreateReceiptSplitTransactionParams,
1529
- ): Promise<CallToolResult> {
1530
- const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1531
- deltaCacheOrParams,
1532
- knowledgeStoreOrParams,
1533
- maybeParams,
1534
- );
1535
- const date = params.date ?? new Date().toISOString().slice(0, 10);
1536
-
1537
- const categoryCalculations: ReceiptCategoryCalculation[] = params.categories.map((category) => {
1538
- const items = category.items.map((item) => ({
1539
- name: item.name,
1540
- amount_milliunits: amountToMilliunits(item.amount),
1541
- quantity: item.quantity,
1542
- memo: item.memo,
1543
- }));
1544
- const subtotalMilliunits = items.reduce((sum, item) => sum + item.amount_milliunits, 0);
1545
- return {
1546
- category_id: category.category_id,
1547
- category_name: category.category_name,
1548
- subtotal_milliunits: subtotalMilliunits,
1549
- tax_milliunits: 0,
1550
- items,
1551
- };
1552
- });
1553
-
1554
- const subtotalMilliunits = categoryCalculations.reduce(
1555
- (sum, category) => sum + category.subtotal_milliunits,
1556
- 0,
1557
- );
1558
-
1559
- const declaredSubtotalMilliunits =
1560
- params.receipt_subtotal !== undefined ? amountToMilliunits(params.receipt_subtotal) : undefined;
1561
- if (
1562
- declaredSubtotalMilliunits !== undefined &&
1563
- Math.abs(declaredSubtotalMilliunits - subtotalMilliunits) > 1
1564
- ) {
1565
- throw new Error(
1566
- `Categorized items subtotal (${milliunitsToAmount(subtotalMilliunits)}) does not match receipt subtotal (${milliunitsToAmount(declaredSubtotalMilliunits)})`,
1567
- );
1568
- }
1569
-
1570
- const taxMilliunits = amountToMilliunits(params.receipt_tax);
1571
- const totalMilliunits = amountToMilliunits(params.receipt_total);
1572
- const computedTotal = subtotalMilliunits + taxMilliunits;
1573
- if (Math.abs(computedTotal - totalMilliunits) > 1) {
1574
- throw new Error(
1575
- `Receipt total (${milliunitsToAmount(totalMilliunits)}) does not equal subtotal plus tax (${milliunitsToAmount(computedTotal)})`,
1576
- );
1577
- }
1578
-
1579
- // Apply smart collapse logic
1580
- const subtransactions = applySmartCollapseLogic(categoryCalculations, taxMilliunits);
1581
-
1582
- // Distribute tax proportionally for receipt_summary (only for positive categories)
1583
- if (taxMilliunits > 0) {
1584
- const positiveSubtotal = categoryCalculations.reduce(
1585
- (sum, cat) => sum + Math.max(0, cat.subtotal_milliunits),
1586
- 0,
1587
- );
1588
- if (positiveSubtotal > 0) {
1589
- let remainingTax = taxMilliunits;
1590
- const positiveCats = categoryCalculations.filter((cat) => cat.subtotal_milliunits > 0);
1591
- positiveCats.forEach((cat, index) => {
1592
- if (index === positiveCats.length - 1) {
1593
- cat.tax_milliunits = remainingTax;
1594
- } else {
1595
- const share = Math.round((cat.subtotal_milliunits / positiveSubtotal) * taxMilliunits);
1596
- cat.tax_milliunits = share;
1597
- remainingTax -= share;
1598
- }
1599
- });
1600
- }
1601
- }
1602
-
1603
- const receiptSummary = {
1604
- subtotal: milliunitsToAmount(subtotalMilliunits),
1605
- tax: milliunitsToAmount(taxMilliunits),
1606
- total: milliunitsToAmount(totalMilliunits),
1607
- categories: categoryCalculations.map((category) => ({
1608
- category_id: category.category_id,
1609
- category_name: category.category_name,
1610
- items: category.items.map((item) => ({
1611
- name: item.name,
1612
- quantity: item.quantity,
1613
- amount: milliunitsToAmount(item.amount_milliunits),
1614
- memo: item.memo,
1615
- })),
1616
- subtotal: milliunitsToAmount(category.subtotal_milliunits),
1617
- tax: milliunitsToAmount(category.tax_milliunits),
1618
- total: milliunitsToAmount(category.subtotal_milliunits + category.tax_milliunits),
1619
- })),
1620
- };
1621
-
1622
- if (params.dry_run) {
1623
- return {
1624
- content: [
1625
- {
1626
- type: 'text',
1627
- text: responseFormatter.format({
1628
- dry_run: true,
1629
- action: 'create_receipt_split_transaction',
1630
- transaction_preview: {
1631
- account_id: params.account_id,
1632
- payee_name: params.payee_name,
1633
- date,
1634
- amount: milliunitsToAmount(totalMilliunits),
1635
- cleared: params.cleared ?? 'uncleared',
1636
- },
1637
- receipt_summary: receiptSummary,
1638
- subtransactions: subtransactions.map((subtransaction) => ({
1639
- amount: milliunitsToAmount(-subtransaction.amount),
1640
- category_id: subtransaction.category_id,
1641
- memo: subtransaction.memo,
1642
- })),
1643
- }),
1644
- },
1645
- ],
1646
- };
1647
- }
1648
-
1649
- const createTransactionParams: CreateTransactionParams = {
1650
- budget_id: params.budget_id,
1651
- account_id: params.account_id,
1652
- amount: -totalMilliunits,
1653
- date,
1654
- payee_name: params.payee_name,
1655
- memo: params.memo,
1656
- cleared: params.cleared ?? 'uncleared',
1657
- flag_color: params.flag_color,
1658
- subtransactions: subtransactions,
1659
- };
1660
-
1661
- if (params.approved !== undefined) {
1662
- createTransactionParams.approved = params.approved;
1663
- }
1664
-
1665
- const baseResult = await handleCreateTransaction(
1666
- ynabAPI,
1667
- deltaCache,
1668
- knowledgeStore,
1669
- createTransactionParams,
1670
- );
1671
-
1672
- const firstContent = baseResult.content?.[0];
1673
- if (!firstContent || firstContent.type !== 'text') {
1674
- return baseResult;
1675
- }
1676
-
1677
- try {
1678
- const parsed = JSON.parse(firstContent.text) as Record<string, unknown>;
1679
- parsed['receipt_summary'] = receiptSummary;
1680
- firstContent.text = responseFormatter.format(parsed);
1681
- } catch {
1682
- // If parsing fails, return the original result without augmentation.
1683
- }
1684
-
1685
- return baseResult;
1686
- }
1687
-
1688
- /**
1689
- * Handles the ynab:update_transaction tool call
1690
- * Updates an existing transaction with the provided fields
1691
- */
1692
- export async function handleUpdateTransaction(
1693
- ynabAPI: ynab.API,
1694
- deltaCache: DeltaCache,
1695
- knowledgeStore: ServerKnowledgeStore,
1696
- params: UpdateTransactionParams,
1697
- ): Promise<CallToolResult>;
1698
- export async function handleUpdateTransaction(
1699
- ynabAPI: ynab.API,
1700
- params: UpdateTransactionParams,
1701
- ): Promise<CallToolResult>;
1702
- export async function handleUpdateTransaction(
1703
- ynabAPI: ynab.API,
1704
- deltaCacheOrParams: DeltaCache | UpdateTransactionParams,
1705
- knowledgeStoreOrParams?: ServerKnowledgeStore | UpdateTransactionParams,
1706
- maybeParams?: UpdateTransactionParams,
1707
- ): Promise<CallToolResult> {
1708
- const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1709
- deltaCacheOrParams,
1710
- knowledgeStoreOrParams,
1711
- maybeParams,
1712
- );
1713
- try {
1714
- if (params.dry_run) {
1715
- return {
1716
- content: [
1717
- {
1718
- type: 'text',
1719
- text: responseFormatter.format({
1720
- dry_run: true,
1721
- action: 'update_transaction',
1722
- request: params,
1723
- }),
1724
- },
1725
- ],
1726
- };
1727
- }
1728
-
1729
- // Get the original transaction before updating to capture the original account_id
1730
- const originalTransactionResponse = await ynabAPI.transactions.getTransactionById(
1731
- params.budget_id,
1732
- params.transaction_id,
1733
- );
1734
- const originalTransaction = ensureTransaction(
1735
- originalTransactionResponse.data.transaction,
1736
- 'Original transaction not found',
1737
- );
1738
-
1739
- // Prepare transaction update data - only include fields that are provided
1740
- const transactionData: SaveTransaction = {};
1741
-
1742
- // Only include fields that are provided in the update
1743
- if (params.account_id !== undefined) {
1744
- transactionData.account_id = params.account_id;
1745
- }
1746
- if (params.amount !== undefined) {
1747
- transactionData.amount = params.amount;
1748
- }
1749
- if (params.date !== undefined) {
1750
- transactionData.date = params.date;
1751
- }
1752
- if (params.payee_name !== undefined) {
1753
- transactionData.payee_name = params.payee_name;
1754
- }
1755
- if (params.payee_id !== undefined) {
1756
- transactionData.payee_id = params.payee_id;
1757
- }
1758
- if (params.category_id !== undefined) {
1759
- transactionData.category_id = params.category_id;
1760
- }
1761
- if (params.memo !== undefined) {
1762
- transactionData.memo = params.memo;
1763
- }
1764
- if (params.cleared !== undefined) {
1765
- transactionData.cleared = params.cleared as ynab.TransactionClearedStatus;
1766
- }
1767
- if (params.approved !== undefined) {
1768
- transactionData.approved = params.approved;
1769
- }
1770
- if (params.flag_color !== undefined) {
1771
- transactionData.flag_color = params.flag_color as ynab.TransactionFlagColor;
1772
- }
1773
-
1774
- const response = await ynabAPI.transactions.updateTransaction(
1775
- params.budget_id,
1776
- params.transaction_id,
1777
- {
1778
- transaction: transactionData,
1779
- },
1780
- );
1781
-
1782
- const transaction = ensureTransaction(response.data.transaction, 'Transaction update failed');
1783
-
1784
- const specificTransactionCacheKey = CacheManager.generateKey(
1785
- 'transaction',
1786
- 'get',
1787
- params.budget_id,
1788
- params.transaction_id,
1789
- );
1790
- cacheManager.delete(specificTransactionCacheKey);
1791
-
1792
- const affectedAccountIds = new Set<string>([
1793
- originalTransaction.account_id,
1794
- transaction.account_id,
1795
- ]);
1796
-
1797
- if (originalTransaction.transfer_account_id) {
1798
- affectedAccountIds.add(originalTransaction.transfer_account_id);
1799
- }
1800
- if (transaction.transfer_account_id) {
1801
- affectedAccountIds.add(transaction.transfer_account_id);
1802
- }
1803
-
1804
- const affectedMonths = new Set<string>([
1805
- toMonthKey(originalTransaction.date),
1806
- toMonthKey(transaction.date),
1807
- ]);
1808
- const originalCategoryIds = collectCategoryIdsFromSources(originalTransaction);
1809
- const updatedCategoryIds = collectCategoryIdsFromSources(transaction);
1810
- const affectedCategoryIds = new Set<string>([...originalCategoryIds, ...updatedCategoryIds]);
1811
- const categoryChanged = !setsEqual(originalCategoryIds, updatedCategoryIds);
1812
- const amountChanged = transaction.amount !== originalTransaction.amount;
1813
- const accountChanged = transaction.account_id !== originalTransaction.account_id;
1814
- const clearedChanged = transaction.cleared !== originalTransaction.cleared;
1815
- const transferAccountChanged =
1816
- transaction.transfer_account_id !== originalTransaction.transfer_account_id;
1817
- const transferLinkChanged =
1818
- transaction.transfer_transaction_id !== originalTransaction.transfer_transaction_id;
1819
- const dateChanged = transaction.date !== originalTransaction.date;
1820
-
1821
- invalidateTransactionCaches(
1822
- deltaCache,
1823
- knowledgeStore,
1824
- params.budget_id,
1825
- response.data.server_knowledge,
1826
- affectedAccountIds,
1827
- affectedMonths,
1828
- {
1829
- affectedCategoryIds,
1830
- accountTotalsChanged:
1831
- amountChanged ||
1832
- accountChanged ||
1833
- clearedChanged ||
1834
- transferAccountChanged ||
1835
- transferLinkChanged,
1836
- invalidateMonths: amountChanged || categoryChanged || dateChanged,
1837
- },
1838
- );
1839
-
1840
- // Get the updated account balance
1841
- const accountResponse = await ynabAPI.accounts.getAccountById(
1842
- params.budget_id,
1843
- transaction.account_id,
1844
- );
1845
- const account = accountResponse.data.account;
1846
-
1847
- return {
1848
- content: [
1849
- {
1850
- type: 'text',
1851
- text: responseFormatter.format({
1852
- transaction: {
1853
- id: transaction.id,
1854
- date: transaction.date,
1855
- amount: milliunitsToAmount(transaction.amount),
1856
- memo: transaction.memo,
1857
- cleared: transaction.cleared,
1858
- approved: transaction.approved,
1859
- flag_color: transaction.flag_color,
1860
- account_id: transaction.account_id,
1861
- payee_id: transaction.payee_id,
1862
- category_id: transaction.category_id,
1863
- transfer_account_id: transaction.transfer_account_id,
1864
- transfer_transaction_id: transaction.transfer_transaction_id,
1865
- matched_transaction_id: transaction.matched_transaction_id,
1866
- import_id: transaction.import_id,
1867
- deleted: transaction.deleted,
1868
- },
1869
- updated_balance: account.balance,
1870
- updated_cleared_balance: account.cleared_balance,
1871
- }),
1872
- },
1873
- ],
1874
- };
1875
- } catch (error) {
1876
- return handleTransactionError(error, 'Failed to update transaction');
1877
- }
1878
- }
1879
-
1880
- /**
1881
- * Handles the ynab:delete_transaction tool call
1882
- * Deletes a transaction from the specified budget
1883
- */
1884
- export async function handleDeleteTransaction(
1885
- ynabAPI: ynab.API,
1886
- deltaCache: DeltaCache,
1887
- knowledgeStore: ServerKnowledgeStore,
1888
- params: DeleteTransactionParams,
1889
- ): Promise<CallToolResult>;
1890
- export async function handleDeleteTransaction(
1891
- ynabAPI: ynab.API,
1892
- params: DeleteTransactionParams,
1893
- ): Promise<CallToolResult>;
1894
- export async function handleDeleteTransaction(
1895
- ynabAPI: ynab.API,
1896
- deltaCacheOrParams: DeltaCache | DeleteTransactionParams,
1897
- knowledgeStoreOrParams?: ServerKnowledgeStore | DeleteTransactionParams,
1898
- maybeParams?: DeleteTransactionParams,
1899
- ): Promise<CallToolResult> {
1900
- const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
1901
- deltaCacheOrParams,
1902
- knowledgeStoreOrParams,
1903
- maybeParams,
1904
- );
1905
- try {
1906
- if (params.dry_run) {
1907
- return {
1908
- content: [
1909
- {
1910
- type: 'text',
1911
- text: responseFormatter.format({
1912
- dry_run: true,
1913
- action: 'delete_transaction',
1914
- request: params,
1915
- }),
1916
- },
1917
- ],
1918
- };
1919
- }
1920
- const response = await ynabAPI.transactions.deleteTransaction(
1921
- params.budget_id,
1922
- params.transaction_id,
1923
- );
1924
-
1925
- const transaction = ensureTransaction(response.data.transaction, 'Transaction deletion failed');
1926
-
1927
- const specificTransactionCacheKey = CacheManager.generateKey(
1928
- 'transaction',
1929
- 'get',
1930
- params.budget_id,
1931
- params.transaction_id,
1932
- );
1933
- cacheManager.delete(specificTransactionCacheKey);
1934
-
1935
- const affectedAccountIds = new Set<string>([transaction.account_id]);
1936
- if (transaction.transfer_account_id) {
1937
- affectedAccountIds.add(transaction.transfer_account_id);
1938
- }
1939
-
1940
- const affectedMonths = new Set<string>([toMonthKey(transaction.date)]);
1941
- const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
1942
- invalidateTransactionCaches(
1943
- deltaCache,
1944
- knowledgeStore,
1945
- params.budget_id,
1946
- response.data.server_knowledge,
1947
- affectedAccountIds,
1948
- affectedMonths,
1949
- {
1950
- affectedCategoryIds,
1951
- accountTotalsChanged: true,
1952
- invalidateMonths: true,
1953
- },
1954
- );
1955
-
1956
- // Get the updated account balance
1957
- const accountResponse = await ynabAPI.accounts.getAccountById(
1958
- params.budget_id,
1959
- transaction.account_id,
1960
- );
1961
- const account = accountResponse.data.account;
1962
-
1963
- return {
1964
- content: [
1965
- {
1966
- type: 'text',
1967
- text: responseFormatter.format({
1968
- message: 'Transaction deleted successfully',
1969
- transaction: {
1970
- id: transaction.id,
1971
- deleted: transaction.deleted,
1972
- },
1973
- updated_balance: account.balance,
1974
- updated_cleared_balance: account.cleared_balance,
1975
- }),
1976
- },
1977
- ],
1978
- };
1979
- } catch (error) {
1980
- return handleTransactionError(error, 'Failed to delete transaction');
1981
- }
1982
- }
1983
-
1984
- export async function handleCreateTransactions(
1985
- ynabAPI: ynab.API,
1986
- deltaCache: DeltaCache,
1987
- knowledgeStore: ServerKnowledgeStore,
1988
- params: CreateTransactionsParams,
1989
- ): Promise<CallToolResult>;
1990
- export async function handleCreateTransactions(
1991
- ynabAPI: ynab.API,
1992
- params: CreateTransactionsParams,
1993
- ): Promise<CallToolResult>;
1994
- export async function handleCreateTransactions(
1995
- ynabAPI: ynab.API,
1996
- deltaCacheOrParams: DeltaCache | CreateTransactionsParams,
1997
- knowledgeStoreOrParams?: ServerKnowledgeStore | CreateTransactionsParams,
1998
- maybeParams?: CreateTransactionsParams,
1999
- ): Promise<CallToolResult> {
2000
- const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
2001
- deltaCacheOrParams,
2002
- knowledgeStoreOrParams,
2003
- maybeParams,
2004
- );
2005
- return (await withToolErrorHandling(
2006
- async () => {
2007
- const validationResult = CreateTransactionsSchema.safeParse(params);
2008
- if (!validationResult.success) {
2009
- type TransactionIssueIndex = number | null;
2010
- const issuesByIndex = new Map<TransactionIssueIndex, string[]>();
2011
- const validationIssues = validationResult.error.issues ?? [];
2012
- for (const issue of validationIssues) {
2013
- const transactionIndex = issue.path.find(
2014
- (segment): segment is number => typeof segment === 'number',
2015
- );
2016
- const message = issue.message;
2017
- const issueIndex: TransactionIssueIndex =
2018
- transactionIndex !== undefined ? transactionIndex : null;
2019
- const existing = issuesByIndex.get(issueIndex) ?? [];
2020
- existing.push(message);
2021
- issuesByIndex.set(issueIndex, existing);
2022
- }
2023
-
2024
- const details = Array.from(issuesByIndex.entries()).map(([index, errors]) => ({
2025
- transaction_index: index,
2026
- errors,
2027
- }));
2028
-
2029
- throw new ValidationError(
2030
- 'Bulk transaction validation failed',
2031
- JSON.stringify(details, null, 2),
2032
- ['Ensure each transaction includes required fields', 'Limit batches to 100 items'],
2033
- );
2034
- }
2035
-
2036
- const { budget_id, transactions, dry_run } = validationResult.data;
2037
-
2038
- // Pre-flight duplicate import_id detection within batch
2039
- const importIdMap = new Map<string, number[]>();
2040
- for (const [index, transaction] of transactions.entries()) {
2041
- if (transaction.import_id && transaction.import_id.trim().length > 0) {
2042
- const existing = importIdMap.get(transaction.import_id);
2043
- if (existing) {
2044
- existing.push(index);
2045
- } else {
2046
- importIdMap.set(transaction.import_id, [index]);
2047
- }
2048
- }
2049
- }
2050
-
2051
- const duplicates = Array.from(importIdMap.entries())
2052
- .filter(([, indices]) => indices.length > 1)
2053
- .map(([importId, indices]) => ({ import_id: importId, indices }));
2054
-
2055
- if (duplicates.length > 0) {
2056
- const details = duplicates.map(({ import_id, indices }) => ({
2057
- import_id,
2058
- transaction_indices: indices,
2059
- count: indices.length,
2060
- }));
2061
-
2062
- throw new ValidationError(
2063
- 'Duplicate import_id values detected within batch',
2064
- JSON.stringify(details, null, 2),
2065
- [
2066
- 'Ensure each transaction has a unique import_id within the batch',
2067
- 'Remove duplicate import_id values or omit import_id to use hash-based correlation',
2068
- ],
2069
- );
2070
- }
2071
-
2072
- if (dry_run) {
2073
- const totalAmount = transactions.reduce((sum, transaction) => sum + transaction.amount, 0);
2074
- const accountsAffected = Array.from(
2075
- new Set(transactions.map((transaction) => transaction.account_id)),
2076
- );
2077
- const categoriesAffected = Array.from(
2078
- new Set(
2079
- transactions
2080
- .map((transaction) => transaction.category_id)
2081
- .filter((id): id is string => id !== undefined),
2082
- ),
2083
- );
2084
- const sortedDates = [...transactions.map((transaction) => transaction.date)].sort();
2085
- const dateRange =
2086
- sortedDates.length > 0
2087
- ? { earliest: sortedDates[0], latest: sortedDates[sortedDates.length - 1] }
2088
- : undefined;
2089
-
2090
- const transactionsPreview = transactions.slice(0, 10).map((transaction, index) => ({
2091
- request_index: index,
2092
- account_id: transaction.account_id,
2093
- date: transaction.date,
2094
- amount: milliunitsToAmount(transaction.amount),
2095
- memo: transaction.memo,
2096
- payee_id: transaction.payee_id,
2097
- payee_name: transaction.payee_name,
2098
- category_id: transaction.category_id,
2099
- import_id: transaction.import_id,
2100
- }));
2101
-
2102
- return {
2103
- content: [
2104
- {
2105
- type: 'text',
2106
- text: responseFormatter.format({
2107
- dry_run: true,
2108
- action: 'create_transactions',
2109
- validation: 'passed',
2110
- summary: {
2111
- total_transactions: transactions.length,
2112
- total_amount: milliunitsToAmount(totalAmount),
2113
- accounts_affected: accountsAffected,
2114
- date_range: dateRange,
2115
- categories_affected: categoriesAffected,
2116
- },
2117
- transactions_preview: transactionsPreview,
2118
- note: 'Dry run complete. No transactions created. No caches invalidated. No server_knowledge updated.',
2119
- }),
2120
- },
2121
- ],
2122
- };
2123
- }
2124
-
2125
- const saveTransactions: SaveTransaction[] = transactions.map((transaction) => {
2126
- const payload: SaveTransaction = {
2127
- account_id: transaction.account_id,
2128
- amount: transaction.amount,
2129
- date: transaction.date,
2130
- };
2131
-
2132
- if (transaction.payee_id !== undefined) payload.payee_id = transaction.payee_id;
2133
- if (transaction.payee_name !== undefined) payload.payee_name = transaction.payee_name;
2134
- if (transaction.category_id !== undefined) payload.category_id = transaction.category_id;
2135
- if (transaction.memo !== undefined) payload.memo = transaction.memo;
2136
- if (transaction.cleared !== undefined) payload.cleared = transaction.cleared;
2137
- if (transaction.approved !== undefined) payload.approved = transaction.approved;
2138
- if (transaction.flag_color !== undefined) payload.flag_color = transaction.flag_color;
2139
- if (transaction.import_id !== undefined) payload.import_id = transaction.import_id;
2140
-
2141
- return payload;
2142
- });
2143
-
2144
- const response = await ynabAPI.transactions.createTransactions(budget_id, {
2145
- transactions: saveTransactions,
2146
- });
2147
-
2148
- const responseData = response.data;
2149
- const duplicateImportIds = new Set(responseData.duplicate_import_ids ?? []);
2150
- const results = correlateResults(transactions, responseData, duplicateImportIds);
2151
-
2152
- const summary = {
2153
- total_requested: transactions.length,
2154
- created: responseData.transaction_ids?.length ?? 0,
2155
- duplicates: duplicateImportIds.size,
2156
- failed: results.filter((result) => result.status === 'failed').length,
2157
- };
2158
-
2159
- const baseResponse: BulkCreateResponse = {
2160
- success: summary.failed === 0,
2161
- server_knowledge: responseData.server_knowledge,
2162
- summary,
2163
- results,
2164
- transactions: responseData.transactions ?? [],
2165
- duplicate_import_ids: responseData.duplicate_import_ids ?? [],
2166
- message: `Processed ${summary.total_requested} transactions: ${summary.created} created, ${summary.duplicates} duplicates, ${summary.failed} failed.`,
2167
- };
2168
-
2169
- const accountIds = new Set<string>(transactions.map((transaction) => transaction.account_id));
2170
- const affectedMonths = new Set<string>(
2171
- transactions.map((transaction) => toMonthKey(transaction.date)),
2172
- );
2173
- const affectedCategoryIds = new Set<string>();
2174
- for (const created of responseData.transactions ?? []) {
2175
- appendCategoryIds(created, affectedCategoryIds);
2176
- }
2177
- invalidateTransactionCaches(
2178
- deltaCache,
2179
- knowledgeStore,
2180
- budget_id,
2181
- responseData.server_knowledge,
2182
- accountIds,
2183
- affectedMonths,
2184
- {
2185
- affectedCategoryIds,
2186
- accountTotalsChanged: true,
2187
- invalidateMonths: true,
2188
- },
2189
- );
2190
-
2191
- const finalizedResponse = finalizeResponse(baseResponse);
2192
-
2193
- return {
2194
- content: [
2195
- {
2196
- type: 'text',
2197
- text: responseFormatter.format(finalizedResponse),
2198
- },
2199
- ],
2200
- };
2201
- },
2202
- 'ynab:create_transactions',
2203
- 'bulk transaction creation',
2204
- )) as CallToolResult;
2205
- }
2206
-
2207
- /**
2208
- * Interface for transaction metadata needed for cache invalidation
2209
- */
2210
- interface TransactionMetadata {
2211
- account_id: string;
2212
- date: string;
2213
- }
2214
-
2215
- /**
2216
- * Result of metadata resolution including both resolved metadata and unresolved IDs
2217
- */
2218
- interface MetadataResolutionResult {
2219
- metadata: Map<string, TransactionMetadata>;
2220
- unresolvedIds: string[];
2221
- previewDetails: Map<string, ynab.TransactionDetail>;
2222
- }
2223
-
2224
- interface ResolveMetadataOptions {
2225
- previewTransactionIds?: string[];
2226
- }
2227
-
2228
- /**
2229
- * Resolves metadata for bulk update transactions
2230
- * Uses a multi-tier approach: request metadata -> cache -> limited API calls
2231
- * Returns both the resolved metadata and a list of IDs that could not be resolved
2232
- */
2233
- async function resolveMetadata(
2234
- ynabAPI: ynab.API,
2235
- budgetId: string,
2236
- transactions: BulkUpdateTransactionInput[],
2237
- options: ResolveMetadataOptions = {},
2238
- ): Promise<MetadataResolutionResult> {
2239
- const metadata = new Map<string, TransactionMetadata>();
2240
- const needsResolution: string[] = [];
2241
- const previewIds = new Set(options.previewTransactionIds ?? []);
2242
- const previewDetails = new Map<string, ynab.TransactionDetail>();
2243
- const previewIdsNeedingFetch = new Set(previewIds);
2244
-
2245
- // First pass: Use provided metadata
2246
- for (const transaction of transactions) {
2247
- if (transaction.original_account_id && transaction.original_date) {
2248
- metadata.set(transaction.id, {
2249
- account_id: transaction.original_account_id,
2250
- date: transaction.original_date,
2251
- });
2252
- } else {
2253
- needsResolution.push(transaction.id);
2254
- }
2255
- }
2256
-
2257
- if (previewIds.size === 0 && needsResolution.length === 0) {
2258
- return { metadata, unresolvedIds: [], previewDetails };
2259
- }
2260
-
2261
- // Second pass: hydrate from cache for both metadata needs and preview requests
2262
- const needsResolutionSet = new Set(needsResolution);
2263
- const cacheLookupIds = new Set<string>([...needsResolution, ...previewIds]);
2264
- for (const transactionId of cacheLookupIds) {
2265
- const cacheKey = CacheManager.generateKey('transaction', 'get', budgetId, transactionId);
2266
- const cached = cacheManager.get<ynab.TransactionDetail>(cacheKey);
2267
- if (!cached) {
2268
- continue;
2269
- }
2270
-
2271
- if (needsResolutionSet.has(transactionId)) {
2272
- metadata.set(transactionId, {
2273
- account_id: cached.account_id,
2274
- date: cached.date,
2275
- });
2276
- needsResolutionSet.delete(transactionId);
2277
- }
2278
- if (previewIds.has(transactionId) && !previewDetails.has(transactionId)) {
2279
- previewDetails.set(transactionId, cached);
2280
- previewIdsNeedingFetch.delete(transactionId);
2281
- }
2282
- }
2283
-
2284
- const stillNeedsResolution = Array.from(needsResolutionSet);
2285
- if (stillNeedsResolution.length === 0 && previewIdsNeedingFetch.size === 0) {
2286
- return { metadata, unresolvedIds: [], previewDetails };
2287
- }
2288
-
2289
- // Third pass: Limited API calls with concurrency limit
2290
- const MAX_CONCURRENT_FETCHES = 5;
2291
- const fetchPromises: Promise<void>[] = [];
2292
- const metadataAwaitingResolution = new Set(stillNeedsResolution);
2293
- const idsNeedingApiFetch = Array.from(
2294
- new Set([...stillNeedsResolution, ...previewIdsNeedingFetch]),
2295
- );
2296
-
2297
- for (let i = 0; i < idsNeedingApiFetch.length; i += MAX_CONCURRENT_FETCHES) {
2298
- const batch = idsNeedingApiFetch.slice(i, i + MAX_CONCURRENT_FETCHES);
2299
- const batchPromises = batch.map(async (transactionId) => {
2300
- try {
2301
- const response = await ynabAPI.transactions.getTransactionById(budgetId, transactionId);
2302
- const transaction = response.data.transaction;
2303
- if (transaction) {
2304
- if (metadataAwaitingResolution.has(transactionId)) {
2305
- metadata.set(transactionId, {
2306
- account_id: transaction.account_id,
2307
- date: transaction.date,
2308
- });
2309
- metadataAwaitingResolution.delete(transactionId);
2310
- }
2311
- if (previewIdsNeedingFetch.has(transactionId) && !previewDetails.has(transactionId)) {
2312
- previewDetails.set(transactionId, transaction);
2313
- previewIdsNeedingFetch.delete(transactionId);
2314
- }
2315
- }
2316
- } catch {
2317
- if (metadataAwaitingResolution.has(transactionId)) {
2318
- globalRequestLogger.logError(
2319
- 'ynab:update_transactions',
2320
- 'resolve_metadata',
2321
- { transaction_id: transactionId },
2322
- 'Failed to resolve transaction metadata',
2323
- );
2324
- }
2325
- }
2326
- });
2327
- fetchPromises.push(...batchPromises);
2328
- }
2329
-
2330
- await Promise.all(fetchPromises);
2331
- return { metadata, unresolvedIds: Array.from(metadataAwaitingResolution), previewDetails };
2332
- }
2333
-
2334
- /**
2335
- * Finalizes bulk update response based on size constraints
2336
- */
2337
- function finalizeBulkUpdateResponse(response: BulkUpdateResponse): BulkUpdateResponse {
2338
- const appendMessage = (message: string | undefined, addition: string): string => {
2339
- if (!message) {
2340
- return addition;
2341
- }
2342
- if (message.includes(addition)) {
2343
- return message;
2344
- }
2345
- return `${message} ${addition}`;
2346
- };
2347
-
2348
- const fullSize = estimatePayloadSize(response);
2349
- if (fullSize <= FULL_RESPONSE_THRESHOLD) {
2350
- return { ...response, mode: 'full' };
2351
- }
2352
-
2353
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2354
- const { transactions, ...summaryResponse } = response;
2355
- const summaryPayload: BulkUpdateResponse = {
2356
- ...summaryResponse,
2357
- message: appendMessage(
2358
- response.message,
2359
- 'Response downgraded to summary to stay under size limits.',
2360
- ),
2361
- mode: 'summary',
2362
- };
2363
-
2364
- if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
2365
- return summaryPayload;
2366
- }
2367
-
2368
- const idsOnlyPayload: BulkUpdateResponse = {
2369
- ...summaryPayload,
2370
- results: summaryResponse.results.map((result) => {
2371
- const simplified: BulkUpdateResult = {
2372
- request_index: result.request_index,
2373
- status: result.status,
2374
- transaction_id: result.transaction_id,
2375
- correlation_key: result.correlation_key,
2376
- };
2377
- if (result.error) {
2378
- simplified.error = result.error;
2379
- }
2380
- if (result.error_code) {
2381
- simplified.error_code = result.error_code;
2382
- }
2383
- return simplified;
2384
- }),
2385
- message: appendMessage(
2386
- summaryResponse.message,
2387
- 'Response downgraded to ids_only to meet 100KB limit.',
2388
- ),
2389
- mode: 'ids_only',
2390
- };
2391
-
2392
- if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
2393
- return idsOnlyPayload;
2394
- }
2395
-
2396
- throw new ValidationError(
2397
- 'RESPONSE_TOO_LARGE: Unable to format bulk update response within 100KB limit',
2398
- `Batch size: ${response.summary.total_requested} transactions`,
2399
- ['Reduce the batch size and retry', 'Consider splitting into multiple smaller batches'],
2400
- );
2401
- }
2402
-
2403
- /**
2404
- * Handles the ynab:update_transactions tool call
2405
- * Updates multiple transactions in a single batch operation
2406
- */
2407
- export async function handleUpdateTransactions(
2408
- ynabAPI: ynab.API,
2409
- deltaCache: DeltaCache,
2410
- knowledgeStore: ServerKnowledgeStore,
2411
- params: UpdateTransactionsParams,
2412
- ): Promise<CallToolResult>;
2413
- export async function handleUpdateTransactions(
2414
- ynabAPI: ynab.API,
2415
- params: UpdateTransactionsParams,
2416
- ): Promise<CallToolResult>;
2417
- export async function handleUpdateTransactions(
2418
- ynabAPI: ynab.API,
2419
- deltaCacheOrParams: DeltaCache | UpdateTransactionsParams,
2420
- knowledgeStoreOrParams?: ServerKnowledgeStore | UpdateTransactionsParams,
2421
- maybeParams?: UpdateTransactionsParams,
2422
- ): Promise<CallToolResult> {
2423
- const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(
2424
- deltaCacheOrParams,
2425
- knowledgeStoreOrParams,
2426
- maybeParams,
2427
- );
2428
- return (await withToolErrorHandling(
2429
- async () => {
2430
- const validationResult = UpdateTransactionsSchema.safeParse(params);
2431
- if (!validationResult.success) {
2432
- type TransactionIssueIndex = number | null;
2433
- const issuesByIndex = new Map<TransactionIssueIndex, string[]>();
2434
- const validationIssues = validationResult.error.issues ?? [];
2435
- for (const issue of validationIssues) {
2436
- const transactionIndex = issue.path.find(
2437
- (segment): segment is number => typeof segment === 'number',
2438
- );
2439
- const message = issue.message;
2440
- const issueIndex: TransactionIssueIndex =
2441
- transactionIndex !== undefined ? transactionIndex : null;
2442
- const existing = issuesByIndex.get(issueIndex) ?? [];
2443
- existing.push(message);
2444
- issuesByIndex.set(issueIndex, existing);
2445
- }
2446
-
2447
- const details = Array.from(issuesByIndex.entries()).map(([index, errors]) => ({
2448
- transaction_index: index,
2449
- errors,
2450
- }));
2451
-
2452
- throw new ValidationError(
2453
- 'Bulk transaction update validation failed',
2454
- JSON.stringify(details, null, 2),
2455
- ['Ensure each transaction includes an id field', 'Limit batches to 100 items'],
2456
- );
2457
- }
2458
-
2459
- const { budget_id, transactions, dry_run } = validationResult.data;
2460
-
2461
- if (dry_run) {
2462
- const previewTransactions = transactions.slice(0, 10);
2463
- const previewTransactionIds = previewTransactions.map((transaction) => transaction.id);
2464
- // Resolve metadata once and reuse any transaction details for preview rendering
2465
- const { metadata, unresolvedIds, previewDetails } = await resolveMetadata(
2466
- ynabAPI,
2467
- budget_id,
2468
- transactions,
2469
- {
2470
- previewTransactionIds,
2471
- },
2472
- );
2473
-
2474
- const transactionsPreview = [];
2475
- const unavailablePreviewIds: string[] = [];
2476
-
2477
- for (const transaction of previewTransactions) {
2478
- const currentState = previewDetails.get(transaction.id);
2479
- if (!currentState) {
2480
- unavailablePreviewIds.push(transaction.id);
2481
- transactionsPreview.push({
2482
- transaction_id: transaction.id,
2483
- before: 'unavailable',
2484
- after: transaction,
2485
- });
2486
- continue;
2487
- }
2488
-
2489
- const before: Record<string, unknown> = {};
2490
- const after: Record<string, unknown> = {};
2491
-
2492
- if (transaction.amount !== undefined && transaction.amount !== currentState.amount) {
2493
- before['amount'] = milliunitsToAmount(currentState.amount);
2494
- after['amount'] = milliunitsToAmount(transaction.amount);
2495
- }
2496
- if (transaction.date !== undefined && transaction.date !== currentState.date) {
2497
- before['date'] = currentState.date;
2498
- after['date'] = transaction.date;
2499
- }
2500
- if (transaction.memo !== undefined && transaction.memo !== currentState.memo) {
2501
- before['memo'] = currentState.memo;
2502
- after['memo'] = transaction.memo;
2503
- }
2504
- if (
2505
- transaction.payee_id !== undefined &&
2506
- transaction.payee_id !== currentState.payee_id
2507
- ) {
2508
- before['payee_id'] = currentState.payee_id;
2509
- after['payee_id'] = transaction.payee_id;
2510
- }
2511
- if (
2512
- transaction.payee_name !== undefined &&
2513
- transaction.payee_name !== currentState.payee_name
2514
- ) {
2515
- before['payee_name'] = currentState.payee_name;
2516
- after['payee_name'] = transaction.payee_name;
2517
- }
2518
- if (
2519
- transaction.category_id !== undefined &&
2520
- transaction.category_id !== currentState.category_id
2521
- ) {
2522
- before['category_id'] = currentState.category_id;
2523
- after['category_id'] = transaction.category_id;
2524
- }
2525
- if (transaction.cleared !== undefined && transaction.cleared !== currentState.cleared) {
2526
- before['cleared'] = currentState.cleared;
2527
- after['cleared'] = transaction.cleared;
2528
- }
2529
- if (
2530
- transaction.approved !== undefined &&
2531
- transaction.approved !== currentState.approved
2532
- ) {
2533
- before['approved'] = currentState.approved;
2534
- after['approved'] = transaction.approved;
2535
- }
2536
- if (
2537
- transaction.flag_color !== undefined &&
2538
- transaction.flag_color !== currentState.flag_color
2539
- ) {
2540
- before['flag_color'] = currentState.flag_color;
2541
- after['flag_color'] = transaction.flag_color;
2542
- }
2543
-
2544
- transactionsPreview.push({
2545
- transaction_id: transaction.id,
2546
- before,
2547
- after,
2548
- });
2549
- }
2550
-
2551
- // Build warnings array
2552
- const warnings: { code: string; count: number; message: string; sample_ids?: string[] }[] =
2553
- [];
2554
- if (unavailablePreviewIds.length > 0 || unresolvedIds.length > 0) {
2555
- const totalMissing = Math.max(unavailablePreviewIds.length, unresolvedIds.length);
2556
- const sampleIds =
2557
- unresolvedIds.length > 0
2558
- ? unresolvedIds.slice(0, 10)
2559
- : unavailablePreviewIds.slice(0, 10);
2560
- warnings.push({
2561
- code: 'metadata_unavailable',
2562
- count: totalMissing,
2563
- message: `Unable to fetch prior state for ${totalMissing} transactions`,
2564
- sample_ids: sampleIds,
2565
- });
2566
- }
2567
-
2568
- // Collect summary statistics
2569
- const accountsAffected = Array.from(
2570
- new Set(Array.from(metadata.values()).map((m) => m.account_id)),
2571
- );
2572
- const fieldsToUpdate = new Set<string>();
2573
- for (const transaction of transactions) {
2574
- if (transaction.amount !== undefined) fieldsToUpdate.add('amount');
2575
- if (transaction.date !== undefined) fieldsToUpdate.add('date');
2576
- if (transaction.memo !== undefined) fieldsToUpdate.add('memo');
2577
- if (transaction.payee_id !== undefined) fieldsToUpdate.add('payee_id');
2578
- if (transaction.payee_name !== undefined) fieldsToUpdate.add('payee_name');
2579
- if (transaction.category_id !== undefined) fieldsToUpdate.add('category_id');
2580
- if (transaction.cleared !== undefined) fieldsToUpdate.add('cleared');
2581
- if (transaction.approved !== undefined) fieldsToUpdate.add('approved');
2582
- if (transaction.flag_color !== undefined) fieldsToUpdate.add('flag_color');
2583
- }
2584
-
2585
- const response: Record<string, unknown> = {
2586
- dry_run: true,
2587
- action: 'update_transactions',
2588
- validation: 'passed',
2589
- summary: {
2590
- total_transactions: transactions.length,
2591
- accounts_affected: accountsAffected,
2592
- fields_to_update: Array.from(fieldsToUpdate),
2593
- },
2594
- transactions_preview: transactionsPreview,
2595
- note: 'Dry run complete. No transactions updated. No caches invalidated. No server_knowledge updated.',
2596
- };
2597
-
2598
- if (warnings.length > 0) {
2599
- response['warnings'] = warnings;
2600
- }
2601
-
2602
- return {
2603
- content: [
2604
- {
2605
- type: 'text',
2606
- text: responseFormatter.format(response),
2607
- },
2608
- ],
2609
- };
2610
- }
2611
-
2612
- // Resolve metadata for cache invalidation before making updates
2613
- const { metadata, unresolvedIds } = await resolveMetadata(ynabAPI, budget_id, transactions);
2614
-
2615
- // Check metadata completeness threshold (5%)
2616
- const missingMetadataRatio = unresolvedIds.length / transactions.length;
2617
- const METADATA_THRESHOLD = 0.05; // 5%
2618
-
2619
- if (missingMetadataRatio > METADATA_THRESHOLD) {
2620
- throw new ValidationError(
2621
- `METADATA_INCOMPLETE: ${(missingMetadataRatio * 100).toFixed(1)}% of transactions have missing metadata (threshold: ${(METADATA_THRESHOLD * 100).toFixed(0)}%)`,
2622
- JSON.stringify(
2623
- {
2624
- unresolved_count: unresolvedIds.length,
2625
- total_transactions: transactions.length,
2626
- ratio: (missingMetadataRatio * 100).toFixed(1) + '%',
2627
- threshold: (METADATA_THRESHOLD * 100).toFixed(0) + '%',
2628
- sample_unresolved_ids: unresolvedIds.slice(0, 5),
2629
- },
2630
- null,
2631
- 2,
2632
- ),
2633
- [
2634
- 'Provide original_account_id and original_date for all transactions being updated',
2635
- 'Ensure transactions exist in YNAB before updating them',
2636
- ],
2637
- );
2638
- }
2639
-
2640
- if (missingMetadataRatio > 0.01) {
2641
- globalRequestLogger.logRequest(
2642
- 'ynab:update_transactions',
2643
- 'metadata_resolution_warning',
2644
- {
2645
- unresolved_count: unresolvedIds.length,
2646
- total_transactions: transactions.length,
2647
- ratio: missingMetadataRatio.toFixed(3),
2648
- sample_ids: unresolvedIds.slice(0, 5),
2649
- message: 'Metadata resolution incomplete for some transactions',
2650
- },
2651
- true,
2652
- );
2653
- }
2654
-
2655
- // Prepare update transactions for the YNAB API
2656
- const updateTransactions: { id: string; transaction: SaveTransaction }[] = transactions.map(
2657
- (transaction) => {
2658
- const transactionData: SaveTransaction = {};
2659
-
2660
- // Note: account_id is intentionally excluded as account moves are not supported
2661
- if (transaction.amount !== undefined) {
2662
- transactionData.amount = transaction.amount;
2663
- }
2664
- if (transaction.date !== undefined) {
2665
- transactionData.date = transaction.date;
2666
- }
2667
- if (transaction.payee_name !== undefined) {
2668
- transactionData.payee_name = transaction.payee_name;
2669
- }
2670
- if (transaction.payee_id !== undefined) {
2671
- transactionData.payee_id = transaction.payee_id;
2672
- }
2673
- if (transaction.category_id !== undefined) {
2674
- transactionData.category_id = transaction.category_id;
2675
- }
2676
- if (transaction.memo !== undefined) {
2677
- transactionData.memo = transaction.memo;
2678
- }
2679
- if (transaction.cleared !== undefined) {
2680
- transactionData.cleared = transaction.cleared as ynab.TransactionClearedStatus;
2681
- }
2682
- if (transaction.approved !== undefined) {
2683
- transactionData.approved = transaction.approved;
2684
- }
2685
- if (transaction.flag_color !== undefined) {
2686
- transactionData.flag_color = transaction.flag_color as ynab.TransactionFlagColor;
2687
- }
2688
-
2689
- return {
2690
- id: transaction.id,
2691
- transaction: transactionData,
2692
- };
2693
- },
2694
- );
2695
-
2696
- // Execute bulk update
2697
- const response = await ynabAPI.transactions.updateTransactions(budget_id, {
2698
- transactions: updateTransactions,
2699
- });
2700
-
2701
- const responseData = response.data;
2702
- const updatedTransactions = responseData.transactions ?? [];
2703
-
2704
- // Build results
2705
- const results: BulkUpdateResult[] = [];
2706
- const updatedIds = new Set(updatedTransactions.map((t) => t.id));
2707
-
2708
- for (const [index, transaction] of transactions.entries()) {
2709
- if (updatedIds.has(transaction.id)) {
2710
- results.push({
2711
- request_index: index,
2712
- status: 'updated',
2713
- transaction_id: transaction.id,
2714
- correlation_key: transaction.id,
2715
- });
2716
- } else {
2717
- results.push({
2718
- request_index: index,
2719
- status: 'failed',
2720
- transaction_id: transaction.id,
2721
- correlation_key: transaction.id,
2722
- error_code: 'update_failed',
2723
- error: 'Transaction was not updated by YNAB API',
2724
- });
2725
- }
2726
- }
2727
-
2728
- const summary = {
2729
- total_requested: transactions.length,
2730
- updated: updatedTransactions.length,
2731
- failed: results.filter((r) => r.status === 'failed').length,
2732
- };
2733
-
2734
- const baseResponse: BulkUpdateResponse = {
2735
- success: summary.failed === 0,
2736
- server_knowledge: responseData.server_knowledge,
2737
- summary,
2738
- results,
2739
- transactions: updatedTransactions,
2740
- message: `Processed ${summary.total_requested} transactions: ${summary.updated} updated, ${summary.failed} failed.`,
2741
- };
2742
-
2743
- for (const transaction of transactions) {
2744
- cacheManager.delete(
2745
- CacheManager.generateKey('transaction', 'get', budget_id, transaction.id),
2746
- );
2747
- }
2748
-
2749
- const affectedAccountIds = new Set<string>();
2750
- const affectedMonthKeys = new Set<string>();
2751
- const affectedCategoryIds = new Set<string>();
2752
- let invalidateAllCategories = false;
2753
- let accountTotalsChanged = false;
2754
- let monthsImpacted = false;
2755
-
2756
- for (const transaction of transactions) {
2757
- const meta = metadata.get(transaction.id);
2758
- const amountChanged = transaction.amount !== undefined;
2759
- const clearedChanged = transaction.cleared !== undefined;
2760
- const categoryChanged = transaction.category_id !== undefined;
2761
- const dateChanged = transaction.date !== undefined;
2762
-
2763
- if ((amountChanged || clearedChanged) && meta) {
2764
- affectedAccountIds.add(meta.account_id);
2765
- }
2766
-
2767
- if (amountChanged) {
2768
- monthsImpacted = true;
2769
- accountTotalsChanged = true;
2770
- invalidateAllCategories = true;
2771
- if (meta) {
2772
- affectedMonthKeys.add(toMonthKey(meta.date));
2773
- }
2774
- }
2775
-
2776
- if (categoryChanged) {
2777
- monthsImpacted = true;
2778
- invalidateAllCategories = true;
2779
- if (transaction.category_id) {
2780
- affectedCategoryIds.add(transaction.category_id);
2781
- }
2782
- if (meta) {
2783
- affectedMonthKeys.add(toMonthKey(meta.date));
2784
- }
2785
- }
2786
-
2787
- if (dateChanged && meta) {
2788
- monthsImpacted = true;
2789
- affectedMonthKeys.add(toMonthKey(meta.date));
2790
- }
2791
- if (dateChanged && transaction.date) {
2792
- affectedMonthKeys.add(toMonthKey(transaction.date));
2793
- }
2794
- }
2795
-
2796
- invalidateTransactionCaches(
2797
- deltaCache,
2798
- knowledgeStore,
2799
- budget_id,
2800
- responseData.server_knowledge,
2801
- affectedAccountIds,
2802
- affectedMonthKeys,
2803
- {
2804
- affectedCategoryIds,
2805
- invalidateAllCategories,
2806
- accountTotalsChanged,
2807
- invalidateMonths: monthsImpacted,
2808
- },
2809
- );
2810
-
2811
- const finalizedResponse = finalizeBulkUpdateResponse(baseResponse);
2812
-
2813
- return {
2814
- content: [
2815
- {
2816
- type: 'text',
2817
- text: responseFormatter.format(finalizedResponse),
2818
- },
2819
- ],
2820
- };
2821
- },
2822
- 'ynab:update_transactions',
2823
- 'bulk transaction update',
2824
- )) as CallToolResult;
2825
- }
2826
-
2827
- /**
2828
- * Handles errors from transaction-related API calls
2829
- */
2830
- function handleTransactionError(error: unknown, defaultMessage: string): CallToolResult {
2831
- let errorMessage = defaultMessage;
2832
-
2833
- if (error instanceof Error) {
2834
- if (error.message.includes('401') || error.message.includes('Unauthorized')) {
2835
- errorMessage = 'Invalid or expired YNAB access token';
2836
- } else if (error.message.includes('403') || error.message.includes('Forbidden')) {
2837
- errorMessage = 'Insufficient permissions to access YNAB data';
2838
- } else if (error.message.includes('404') || error.message.includes('Not Found')) {
2839
- errorMessage = 'Budget, account, category, or transaction not found';
2840
- } else if (error.message.includes('429') || error.message.includes('Too Many Requests')) {
2841
- errorMessage = 'Rate limit exceeded. Please try again later';
2842
- } else if (error.message.includes('500') || error.message.includes('Internal Server Error')) {
2843
- errorMessage = 'YNAB service is currently unavailable';
2844
- }
2845
- }
2846
-
2847
- return {
2848
- content: [
2849
- {
2850
- type: 'text',
2851
- text: responseFormatter.format({
2852
- error: {
2853
- message: errorMessage,
2854
- },
2855
- }),
2856
- },
2857
- ],
2858
- };
2859
- }
2860
-
2861
- /**
2862
- * Registers transaction-domain tools with the provided registry.
2
+ * Transaction Tools - Facade Module
3
+ *
4
+ * This module delegates to:
5
+ * - transactionReadTools.ts — read-only handlers (list, get, export)
6
+ * - transactionWriteTools.ts — write handlers (create, update, delete)
7
+ *
8
+ * Schemas and types live in transactionSchemas.ts.
9
+ * Utility functions live in transactionUtils.ts.
10
+ */
11
+
12
+ import type { ToolFactory } from "../types/toolRegistration.js";
13
+ import {
14
+ handleGetTransaction,
15
+ handleListTransactions,
16
+ registerTransactionReadTools,
17
+ } from "./transactionReadTools.js";
18
+ import {
19
+ handleCreateReceiptSplitTransaction,
20
+ handleCreateTransaction,
21
+ handleCreateTransactions,
22
+ handleDeleteTransaction,
23
+ handleUpdateTransaction,
24
+ handleUpdateTransactions,
25
+ registerTransactionWriteTools,
26
+ } from "./transactionWriteTools.js";
27
+
28
+ // ============================================================================
29
+ // Registration facade — called by YNABMCPServer.setupToolRegistry()
30
+ // ============================================================================
31
+
32
+ /**
33
+ * Registers all transaction-domain tools with the provided registry.
2863
34
  */
2864
35
  export const registerTransactionTools: ToolFactory = (registry, context) => {
2865
- const { adapt, adaptWithDelta, adaptWrite } = createAdapters(context);
2866
- const budgetResolver = createBudgetResolver(context);
2867
-
2868
- registry.register({
2869
- name: 'list_transactions',
2870
- description: 'List transactions for a budget with optional filtering',
2871
- inputSchema: ListTransactionsSchema,
2872
- handler: adaptWithDelta(handleListTransactions),
2873
- defaultArgumentResolver: budgetResolver<z.infer<typeof ListTransactionsSchema>>(),
2874
- metadata: {
2875
- annotations: {
2876
- ...ToolAnnotationPresets.READ_ONLY_EXTERNAL,
2877
- title: 'YNAB: List Transactions',
2878
- },
2879
- },
2880
- });
2881
-
2882
- registry.register({
2883
- name: 'export_transactions',
2884
- description: 'Export all transactions to a JSON file with descriptive filename',
2885
- inputSchema: ExportTransactionsSchema,
2886
- handler: adapt(handleExportTransactions),
2887
- defaultArgumentResolver: budgetResolver<z.infer<typeof ExportTransactionsSchema>>(),
2888
- metadata: {
2889
- annotations: {
2890
- ...ToolAnnotationPresets.READ_ONLY_EXTERNAL,
2891
- title: 'YNAB: Export Transactions',
2892
- },
2893
- },
2894
- });
2895
-
2896
- registry.register({
2897
- name: 'get_transaction',
2898
- description: 'Get detailed information for a specific transaction',
2899
- inputSchema: GetTransactionSchema,
2900
- handler: adapt(handleGetTransaction),
2901
- defaultArgumentResolver: budgetResolver<z.infer<typeof GetTransactionSchema>>(),
2902
- metadata: {
2903
- annotations: {
2904
- ...ToolAnnotationPresets.READ_ONLY_EXTERNAL,
2905
- title: 'YNAB: Get Transaction Details',
2906
- },
2907
- },
2908
- });
2909
-
2910
- registry.register({
2911
- name: 'create_transaction',
2912
- description: 'Create a new transaction in the specified budget and account',
2913
- inputSchema: CreateTransactionSchema,
2914
- handler: adaptWrite(handleCreateTransaction),
2915
- defaultArgumentResolver: budgetResolver<z.infer<typeof CreateTransactionSchema>>(),
2916
- metadata: {
2917
- annotations: {
2918
- ...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
2919
- title: 'YNAB: Create Transaction',
2920
- },
2921
- },
2922
- });
2923
-
2924
- registry.register({
2925
- name: 'create_transactions',
2926
- description:
2927
- 'Create multiple transactions in a single batch (1-100 items) with duplicate detection, dry-run validation, and automatic response size management with correlation metadata.',
2928
- inputSchema: CreateTransactionsSchema,
2929
- handler: adaptWrite(handleCreateTransactions),
2930
- defaultArgumentResolver: budgetResolver<z.infer<typeof CreateTransactionsSchema>>(),
2931
- metadata: {
2932
- annotations: {
2933
- ...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
2934
- title: 'YNAB: Create Multiple Transactions',
2935
- },
2936
- },
2937
- });
2938
-
2939
- registry.register({
2940
- name: 'create_receipt_split_transaction',
2941
- description: 'Create a split transaction from receipt items with proportional tax allocation',
2942
- inputSchema: CreateReceiptSplitTransactionSchema,
2943
- handler: adaptWrite(handleCreateReceiptSplitTransaction),
2944
- defaultArgumentResolver: budgetResolver<z.infer<typeof CreateReceiptSplitTransactionSchema>>(),
2945
- metadata: {
2946
- annotations: {
2947
- ...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
2948
- title: 'YNAB: Create Split Transaction from Receipt',
2949
- },
2950
- },
2951
- });
2952
-
2953
- registry.register({
2954
- name: 'update_transaction',
2955
- description: 'Update an existing transaction',
2956
- inputSchema: UpdateTransactionSchema,
2957
- handler: adaptWrite(handleUpdateTransaction),
2958
- defaultArgumentResolver: budgetResolver<z.infer<typeof UpdateTransactionSchema>>(),
2959
- metadata: {
2960
- annotations: {
2961
- ...ToolAnnotationPresets.WRITE_EXTERNAL_UPDATE,
2962
- title: 'YNAB: Update Transaction',
2963
- },
2964
- },
2965
- });
2966
-
2967
- registry.register({
2968
- name: 'update_transactions',
2969
- description:
2970
- '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.',
2971
- inputSchema: UpdateTransactionsSchema,
2972
- handler: adaptWrite(handleUpdateTransactions),
2973
- defaultArgumentResolver: budgetResolver<z.infer<typeof UpdateTransactionsSchema>>(),
2974
- metadata: {
2975
- annotations: {
2976
- ...ToolAnnotationPresets.WRITE_EXTERNAL_UPDATE,
2977
- title: 'YNAB: Update Multiple Transactions',
2978
- },
2979
- },
2980
- });
36
+ registerTransactionReadTools(registry, context);
37
+ registerTransactionWriteTools(registry, context);
38
+ };
2981
39
 
2982
- registry.register({
2983
- name: 'delete_transaction',
2984
- description: 'Delete a transaction from the specified budget',
2985
- inputSchema: DeleteTransactionSchema,
2986
- handler: adaptWrite(handleDeleteTransaction),
2987
- defaultArgumentResolver: budgetResolver<z.infer<typeof DeleteTransactionSchema>>(),
2988
- metadata: {
2989
- annotations: {
2990
- ...ToolAnnotationPresets.WRITE_EXTERNAL_DELETE,
2991
- title: 'YNAB: Delete Transaction',
2992
- },
2993
- },
2994
- });
40
+ // ============================================================================
41
+ // Re-export handler functions for consumers
42
+ // ============================================================================
43
+
44
+ export {
45
+ handleListTransactions,
46
+ handleGetTransaction,
47
+ handleCreateTransaction,
48
+ handleCreateReceiptSplitTransaction,
49
+ handleUpdateTransaction,
50
+ handleDeleteTransaction,
51
+ handleCreateTransactions,
52
+ handleUpdateTransactions,
2995
53
  };
54
+
55
+ // ============================================================================
56
+ // Re-exports for backward compatibility
57
+ // ============================================================================
58
+
59
+ /**
60
+ * Re-export schemas and types from transactionSchemas.ts
61
+ * These exports maintain backward compatibility for code that imports directly from transactionTools.ts
62
+ */
63
+ export {
64
+ ListTransactionsSchema,
65
+ type ListTransactionsParams,
66
+ GetTransactionSchema,
67
+ type GetTransactionParams,
68
+ CreateTransactionSchema,
69
+ type CreateTransactionParams,
70
+ CreateTransactionsSchema,
71
+ type CreateTransactionsParams,
72
+ CreateReceiptSplitTransactionSchema,
73
+ type CreateReceiptSplitTransactionParams,
74
+ UpdateTransactionSchema,
75
+ type UpdateTransactionParams,
76
+ UpdateTransactionsSchema,
77
+ type UpdateTransactionsParams,
78
+ type BulkUpdateTransactionInput,
79
+ DeleteTransactionSchema,
80
+ type DeleteTransactionParams,
81
+ type BulkTransactionResult,
82
+ type BulkCreateResponse,
83
+ type BulkUpdateResult,
84
+ type BulkUpdateResponse,
85
+ type CorrelationPayload,
86
+ type CorrelationPayloadInput,
87
+ type CategorySource,
88
+ type TransactionCacheInvalidationOptions,
89
+ type ReceiptCategoryCalculation,
90
+ type SubtransactionInput,
91
+ type BulkTransactionInput,
92
+ } from "./transactionSchemas.js";
93
+
94
+ /**
95
+ * Re-export utility functions from transactionUtils.ts
96
+ * These exports maintain backward compatibility for code that imports directly from transactionTools.ts
97
+ */
98
+ export {
99
+ generateCorrelationKey,
100
+ toCorrelationPayload,
101
+ correlateResults,
102
+ estimatePayloadSize,
103
+ finalizeResponse,
104
+ finalizeBulkUpdateResponse,
105
+ handleTransactionError,
106
+ toMonthKey,
107
+ ensureTransaction,
108
+ appendCategoryIds,
109
+ collectCategoryIdsFromSources,
110
+ setsEqual,
111
+ invalidateTransactionCaches,
112
+ } from "./transactionUtils.js";