@dizzlkheinz/ynab-mcpb 0.18.4 → 0.19.0

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